modelling crowd movement with matplotlib

2020-08-01 06:03发布

I would like to model basic crowd movement with python. I want to show an animation. I have made the following program to test it with 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()

Even for N=100, the animation is slow... Is there something I can do to speed it up with mathplotlib ? Is matplotlib the best graphic tool to make thins kind of animation with python ? If no, what would it be ?

1条回答
欢心
2楼-- · 2020-08-01 06:33

Here are 3 things you can do to make the animation faster:

  • Replace the N calls to plt.plot with one call to plt.scatter.
  • Replace the for-loop in update with assignments which modify whole slices of data at once:

    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])
    
  • Reduce interval=10 to 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()
查看更多
登录 后发表回答