python - modelling crowd movement with matplotlib -


i model basic crowd movement python. want show animation. have made following program test matplotlib :

import numpy np import matplotlib.pyplot plt matplotlib import animation  #size of crowd n = 100  def gen_data():     """ init position , 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():     line in lines:         line.set_data([],[])     return line,  def update_lines(i, lines, data):     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] 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 n=100, animation slow... there can speed mathplotlib ? matplotlib best graphic tool make thins kind of animation python ? if no, ?

here 3 things can make animation faster:

  • replace n calls plt.plot one call plt.scatter.
  • replace for-loop in update assignments modify whole slices of data @ 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 interval=0.


import numpy np import matplotlib.pyplot plt matplotlib import animation  # size of crowd n = 100  def gen_data():     """ init position , 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() 

Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -