modelling crowd movement with matplotlib

馋奶兔 提交于 2020-01-13 06:31:11

问题


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:


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()


来源:https://stackoverflow.com/questions/31303105/modelling-crowd-movement-with-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!