Python教程之粒子运动轨迹动态绘图

(本文整理自《Python高性能》)
  今天我们来讲一下Python中的动态绘图库–matplotlib.animation,以粒子运动轨迹为例来说明如何绘制动态图。

  假设按照圆周运动,如下图所示:

image-20200829214510346

为了模拟这个运动,我们需要如下信息:粒子的起始位置、速度和旋转方向。因此定义一个通用的Particle类,用于存储粒子的位置及角速度。

class Particle:
    def __init__(self, x, y, ang_vel):
        self.x = x
        self.y = y
        self.ang_vel = ang_vel

  对于特定粒子,经过时间t后,它将到达圆周上的下一个位置。我们可以这样近似计算圆周轨迹:将时间段t分成一系列很小的时间段dt,在这些很小的时段内,粒子沿圆周的切线移动。这样就近似模拟了圆周运动。粒子运动方向可以按照下面的公式计算:

v_x = -y / (x **2 + y **2) ** 0.5
v_y = x / (x **2 + y **2) ** 0.5

  计算经过时间t后的粒子位置,必须采取如下步骤:

1)计算运动方向(v_x和v_y)

2)计算位置(d_x和d_y),即时段dt、角速度和移动方向的乘积

3)不断重复第1步和第2步,直到时间过去t

class ParticleSimulator:
    def __init__(self, particles):
        self.particles = particles

    def evolve(self, dt):
        timestep = 0.00001
        nsteps = int(dt / timestep)

        for i in range(nsteps):
            for p in self.particles:
                norm = (p.x **2 + p.y ** 2) ** 0.5
                v_x = -p.y / norm
                v_y = p.x / norm

                d_x = timestep * p.ang_vel * v_x
                d_y = timestep * p.ang_vel * v_y

                p.x += d_x
                p.y += d_y

  下面就是进行绘图了,我们先把代码放上来,再具体解释:

def visualize(simulator):
    X = [p.x for p in simulator.particles]
    Y = [p.y for p in simulator.particles]

    fig = plt.figure()
    ax = plt.subplot(111, aspect = 'equal')
    line, = ax.plot(X, Y, 'ro')  #如果不加逗号,返回值是包含一个元素的list,加上逗号表示直接将list的值取出

    plt.xlim(-1, 1)
    plt.ylim(-1, 1)

    def init():
        line.set_data([], [])
        return line,   #加上逗号表示返回包含只元素line的元组

    def animate(i):
        simulator.evolve(0.01)
        X = [p.x for p in simulator.particles]
        Y = [p.y for p in simulator.particles]

        line.set_data(X, Y)
        return line,   #加上逗号表示返回包含只元素line的元组

    anim = animation.FuncAnimation(fig,
                                   animate,
                                   init_func = init,
                                   blit = True,
                                   interval = 10)
    plt.show()

这里再对animation.FuncAnimation函数作具体解释:

  • fig表示动画绘制的画布
  • func = animate表示绘制动画,本例中animate的参数未使用,但不可省略
  • frames参数省略未写,表示要传给func的参数,省略的话会一直累加
  • blit表示是否更新整张图
  • interval表示更新频率,单位为ms

完整代码如下:

# -*- coding: utf-8 -*-

from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np

class Particle:
    def __init__(self, x, y, ang_vel):
        self.x = x
        self.y = y
        self.ang_vel = ang_vel

class ParticleSimulator:
    def __init__(self, particles):
        self.particles = particles

    def evolve(self, dt):
        timestep = 0.00001
        nsteps = int(dt / timestep)

        for i in range(nsteps):
            for p in self.particles:
                norm = (p.x **2 + p.y ** 2) ** 0.5
                v_x = -p.y / norm
                v_y = p.x / norm

                d_x = timestep * p.ang_vel * v_x
                d_y = timestep * p.ang_vel * v_y

                p.x += d_x
                p.y += d_y


def visualize(simulator):
    X = [p.x for p in simulator.particles]
    Y = [p.y for p in simulator.particles]

    fig = plt.figure()
    ax = plt.subplot(111, aspect = 'equal')
    line, = ax.plot(X, Y, 'ro')

    plt.xlim(-1, 1)
    plt.ylim(-1, 1)

    def init():
        line.set_data([], [])
        return line,

    def init2():
        line.set_data([], [])
        return line

    def animate(aa):
        simulator.evolve(0.01)
        X = [p.x for p in simulator.particles]
        Y = [p.y for p in simulator.particles]

        line.set_data(X, Y)
        return line,

    anim = animation.FuncAnimation(fig,
                                   animate,
                                   frames=10,
                                   init_func = init,
                                   blit = True,
                                   interval = 10)
    plt.show()


def test_visualize():
    particles = [Particle(0.3, 0.5, 1),
                 Particle(0.0, -0.5, -1),
                 Particle(-0.1, -0.4, 3)]
    simulator = ParticleSimulator(particles)
    visualize(simulator)

if __name__ == '__main__':
    test_visualize()

绘制效果如下:

粒子

  可能很多同学看了上面这个例子,也不是很清楚animation函数的用法,下面我们再举个简单例子:

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
 
def update_points(num):
    point_ani.set_data(x[num], y[num])
    return point_ani,
 
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
 
fig = plt.figure(tight_layout=True)
plt.plot(x,y)
point_ani, = plt.plot(x[0], y[0], "ro")
plt.grid(ls="--")

ani = animation.FuncAnimation(fig, update_points, frames = np.arange(0, 100), interval=100, blit=True)
 
plt.show()

显示效果如下图所示:

sine

但如果把animation.FuncAnimation中的frames参数改成`np.arange(0, 10):

ani = animation.FuncAnimation(fig, update_points, frames = np.arange(0, 10), interval=100, blit=True)

那显示效果就会如下图所示:

sine10

这是因为我们定义了一百个点的数据,但只看前10个点。

微信公众号:Quant_Times

在这里插入图片描述

### 关于粒子群优化算法的绘图方法 对于粒子群优化算法(Particle Swarm Optimization, PSO),绘制目标函数以及粒子运动轨迹有助于理解算法的工作原理及其收敛特性。通常情况下,可以利用Python中的Matplotlib库来完成这些图形化展示。 #### 使用Matplotlib绘制二维空间下的PSO运行情况 为了更好地观察粒子在搜索空间内的移动路径,可以通过如下方式创建动画效果: ```python import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation def animate(i): """Update the image for each frame.""" global pso_instance # Update swarm positions and velocities here using your own update function. scat.set_offsets(pso_instance.positions) fig, ax = plt.subplots() ax.set_xlim(-10, 10) ax.set_ylim(-10, 10) scat = ax.scatter([], [], c='blue') ani = FuncAnimation(fig, animate, frames=range(100), interval=50, repeat=False) plt.show() ``` 上述代码片段展示了如何设置一个简单的动画框架[^4]。需要注意的是,在实际应用中应当替换`pso_instance`为具体的PSO实例对象,并实现相应的更新逻辑以便正确反映粒子位置变化。 #### 可视化三维环境下的PSO性能表现 当处理更高维度的问题时,则可能需要用到Mayavi或者Plotly这样的工具来进行更复杂的视觉呈现。下面给出一段基于Plotly的例子用于表示三个变量之间的关系: ```python import plotly.graph_objects as go import pandas as pd df = pd.DataFrame({'x': x_values, 'y': y_values, 'z': z_values}) trace = go.Scatter3d( x=df['x'], y=df['y'], z=df['z'], mode='markers', marker=dict(size=2)) layout = go.Layout(scene=dict(xaxis_title='X Axis Title', yaxis_title='Y Axis Title', zaxis_title='Z Axis Title')) fig = go.Figure(data=[trace], layout=layout) fig.show() ``` 这段脚本说明了怎样构建一个交互式的三维散点图,其中包含了来自数据框`df`里的坐标信息。 #### 绘制适应度随迭代次数的变化趋势曲线 除了直观显示粒子分布外,还可以记录每次迭代后的最佳个体适应度值并画成折线图,以此评估整个进化过程中种群质量的发展态势。 ```python iterations = list(range(len(best_fitnesses))) best_fitness_series = best_fitnesses plt.plot(iterations, best_fitness_series, label="Best Fitness Over Iteration") plt.xlabel('Iteration') plt.ylabel('Fitness Value') plt.title('Convergence Curve of Particle Swarm Optimization') plt.legend() plt.grid(True) plt.show() ``` 此段代码实现了对PSO收敛性的简单分析图表生成操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值