PYTHON   24
diffusion 2D
Guest on 14th March 2023 01:11:42 PM


  1. #%%
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. import matplotlib.animation as animation
  5. import time
  6. import random as rn
  7.  
  8.  
  9. xmin = -1.6
  10. xmax = 1.6
  11. ymin = -0.8
  12. ymax = 0.8
  13. N = 2000 #nombre de particules
  14. fig, ax = plt.subplots(figsize=(xmax*6.5,ymax*6.5))
  15. ax.set(xlim=(xmin, xmax))
  16. ax.set(ylim=(ymin,ymax))
  17.  
  18. scat = ax.scatter([0,0],[0,0], s=5, c='black')
  19. k = 2*np.pi
  20. dt = 0.01
  21. v = 1 # vitesse des particules
  22.  
  23. class Particule:
  24.     def __init__(self, x=0, y=0):
  25.         self.px = rn.uniform(-1.6, -1.4)
  26.         self.py = rn.uniform(ymin, ymax)
  27.         self.dirx = rn.uniform(0,2)
  28.         self.diry = rn.uniform(0,2)
  29.         self.t = time.time()
  30.  
  31. class ParticuleManager:
  32.     def __init__(self):
  33.         self.to = time.time()
  34.  
  35.     def move(self, p):
  36.         t = time.time() - p.t
  37.  
  38.         self.setNextPos(p, t)
  39.         if t > 0.1:
  40.             p.dirx = rn.uniform(0,2)
  41.             p.diry = rn.uniform(0,2)
  42.             p.t = time.time()
  43.  
  44.     def setNextPos(self, p, t):
  45.         nextposx = -99
  46.         nextposy = -99
  47.         while (nextposx > xmax or nextposx < xmin) or (nextposy > ymax or nextposy < ymin):
  48.             p.dirx = rn.uniform(0,2)
  49.             nextposx = p.px + v*t*np.cos(k*p.dirx)
  50.             p.diry = rn.uniform(0,2)
  51.             nextposy = p.py + v*t*np.sin(k*p.diry)
  52.         p.px = nextposx
  53.         p.py = nextposy
  54.  
  55.  
  56. man = ParticuleManager()
  57. particules = []
  58. for i in range (0,N):
  59.     particules.append(Particule())
  60. positions = [[0]*2 for i in range(N)]
  61. for i in range(N):
  62.     positions[i][0] = particules[i].px
  63.     positions[i][1] = particules[i].py
  64.  
  65.  
  66. def animate(i):
  67.     for i in range(N):
  68.         positions[i][0] = particules[i].px
  69.         positions[i][1] = particules[i].py
  70.     scat.set_offsets(positions)
  71.     for p in particules:
  72.         man.move(p)
  73.  
  74. ani = animation.FuncAnimation(fig, animate, interval=10, frames=500, repeat=True)
  75.  
  76. plt.show()
  77. #%%

Raw Paste

Login or Register to edit or fork this paste. It's free.