Advertisement
rfmonk

visualize.py

Mar 18th, 2014
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.09 KB | None | 0 0
  1. from matplotlib import pyplot as plt
  2. from matplotlib import animation
  3.  
  4.  
  5. class Particle:
  6.  
  7.     def __init__(self, x, y, ang_speed):
  8.         self.x = x
  9.         self.y = y
  10.         self.ang_speed = ang_speed
  11.  
  12.  
  13. class ParticleSimulator:
  14.  
  15.     def __init__(self, particles):
  16.         self.particles = particles
  17.  
  18.     def evolve(self, dt):
  19.         timestep = 0.00001
  20.         nsteps = int(dt / timestep)
  21.  
  22.         for i in range(nsteps):
  23.             for p in self.particles:
  24.  
  25.                 # 1. calculate the direction
  26.                 norm = (p.x ** 2 + p.y ** 2) ** 0.5
  27.                 v_x = (-p.y) / norm
  28.                 v_y = p.x / norm
  29.  
  30.                 # 2. calculate the displacement
  31.                 d_x = timestep * p.ang_speed * v_x
  32.                 d_y = timestep * p.ang_speed * v_y
  33.  
  34.                 p.x += d_x
  35.                 p.y += d_y
  36.  
  37.                 # 3. repeat for all the time steps
  38.  
  39.  
  40. def visualize(simulator):
  41.     X = [p.x for p in simulator.particles]
  42.     Y = [p.y for p in simulator.particles]
  43.  
  44.     fig = plt.figure()
  45.     ax = plt.subplot(111, aspect='equal')
  46.     line, = ax.plot(X, Y, 'ro')
  47.  
  48.     # Axis limits
  49.     plt.xlim(-1, 1)
  50.     plt.ylim(-1, 1)
  51.  
  52.     # It will be run when the animation starts
  53.     def init():
  54.         line.set_data([], [])
  55.         return line,
  56.  
  57.     def animate(i):
  58.         # We let the particle evolve for 0.1 time units
  59.         simulator.evolve(0.01)
  60.         X = [p.x for p in simulator.particles]
  61.         Y = [p.y for p in simulator.particles]
  62.  
  63.         line.set_data(X, Y)
  64.         return line,
  65.  
  66.     # Call the animate function each 10 ms
  67.     anim = animation.FuncAnimation(fig, animate,
  68.                                    init_func=init,
  69.                                    blit=True,
  70.                                    # Efficient animation
  71.                                    interval=10)
  72.     plt.show()
  73.  
  74.     def test_visualize():
  75.         particles = [Particle(0.3,  0.5,  +1),
  76.                      Particle(0.0,  -0.5, -1),
  77.                      Particle(-0.1, -0.4, +3)]
  78.  
  79.         simulator = ParticleSimulator(particles)
  80.         visualize(simulator)
  81.  
  82.     if __name__ == '__main__':
  83.         test_visualize()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement