Advertisement
rfmonk

Visualize.py

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