mercredi 7 juin 2023

Problem with brownian motion simulation in Python

I'm trying to make a simple animation of brownian motion for some particles on a box, and although I think I'm not far away from achieving it, I keep getting the same error: 'FuncAnimation' object has no attribute '_resize_id'. I don't know if I'm doing something wrong with the dimensions or if it's something form the animation function.

# Set random seed for reproducibility
np.random.seed(0)

num_particles = 80
box_size = 10
total_steps = 200

# Initialize particle positions and velocities
positionX = np.random.uniform(low=1, high=box_size-1, size=(num_particles, 1))
positionY = np.random.uniform(low=1, high=box_size-1, size=(num_particles, 1))

# Initialize figure and axis
fig, ax = plt.subplots()
ax.set_xlim(0, box_size)
ax.set_ylim(0, box_size)


# Initialize particles as scatter plot objects
particles = ax.scatter(positionX[:,0], positionY[:,0])

def update(frame, positionX,positionY):
    # Random displacements for particles
    displacementX =  np.random.normal(loc=0, scale=0.1, size=(num_particles, 1))
    displacementY =  np.random.normal(loc=0, scale=0.1, size=(num_particles, 1))
    
    # Update particle positions
    positionX += displacementX
    positionY += displacementY
    
    # Ensure particles stay within the box
    positionX = np.clip(positionX, 0, box_size)
    positionY = np.clip(positionY, 0, box_size)

    
    # Update scatter plot
    particles.set_offsets(positionX,positionY)
    
    return particles,

# Animation
ani = animation.FuncAnimation(fig, update, frames=total_steps, fargs=(positionX,positionY), interval=100, blit=True)

ani.save("brownian_mot.gif", writer="pillow")

plt.show()

I've tried to change the way I define the positions but I keep doing it wrong.




Aucun commentaire:

Enregistrer un commentaire