使用matplotlib建模人群运动

时间:2015-07-08 20:31:47

标签: python optimization matplotlib

我想用python模拟基本的人群运动。我想要播放动画。我已经制作了以下程序来使用matplotlib测试它:

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

#size of the crowd
N = 100

def gen_data():
    """ init position and speed of each people """
    x = y = np.zeros(N)
    theta = np.random.random(N) * 360 / (2 * np.pi)
    v0 = 0.1
    vx, vy = v0 * np.cos(theta), v0 * np.sin(theta)
    return np.array([x, y, vx, vy]).T

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

def update_lines(i, lines, data):
    for d, line in zip(data, lines):
        d[0:2] += d[2:4]
        if abs(d[0]) > 5: d[2] *= -1
        if abs(d[1]) > 5: d[3] *= -1
        line.set_data(d[0] ,d[1])
    return lines

fig = plt.figure()
ax = plt.axes(xlim=(-5,5),ylim=(-5,5))
lines = [plt.plot([],[], 'ko')[0] for i in range(N)]

data = gen_data()

anim = animation.FuncAnimation(fig, update_lines, init_func=init, fargs=(lines, data), interval=10, blit=True)

plt.show()

即使N = 100,动画也很慢......我可以用mathplotlib加快速度吗? matplotlib是使用python制作各种动画的最佳图形工具吗?如果不是,它会是什么?

1 个答案:

答案 0 :(得分:3)

您可以采取以下三项措施来加快动画效果:

  • N来自plt.plot的电话改为<{strong>一次电话改为plt.scatter
  • for-loop中的update替换为一次修改data整个切片的作业:

    data[:, 0:2] += data[:, 2:4]
    data[:, 2] = np.where(np.abs(data[:, 0]) > 5, -data[:, 2], data[:, 2])
    data[:, 3] = np.where(np.abs(data[:, 1]) > 5, -data[:, 3], data[:, 3])
    
  • interval=10缩减为interval=0

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

# size of the crowd
N = 100

def gen_data():
    """ init position and speed of each people """
    x = y = np.zeros(N)
    theta = np.random.random(N) * 360 / (2 * np.pi)
    v0 = 0.1
    vx, vy = v0 * np.cos(theta), v0 * np.sin(theta)
    return np.column_stack([x, y, vx, vy])

def init():
    pathcol.set_offsets([[], []])
    return pathcol,

def update(i, pathcol, data):
    data[:, 0:2] += data[:, 2:4]
    data[:, 2] = np.where(np.abs(data[:, 0]) > 5, -data[:, 2], data[:, 2])
    data[:, 3] = np.where(np.abs(data[:, 1]) > 5, -data[:, 3], data[:, 3])
    pathcol.set_offsets(data[:, 0:2])
    return [pathcol]

fig = plt.figure()
ax = plt.axes(xlim=(-5, 5), ylim=(-5, 5))
pathcol = plt.scatter([], [])
data = gen_data()
anim = animation.FuncAnimation(fig, update, init_func=init,
                               fargs=(pathcol, data), interval=0, blit=True)
plt.show()