I need to write a code in Python to emulate the motion of N points in a closed perimeter, taking into account some laws of physics.
We should use an event-based model
We change the state only if something has happened
between collisions, points move along their trajectory
we focus only on the time points where collisions occur
create a priority queue containing collision events ordered by time
remove min and get the next collision
We have a method that can predict collisions in time:
it receives the position, velocity, and radius of a point and calculates when it will collide with another point or wall
If a collision occurs, we have to update the colliding objects.
You should also remember about collisions with walls
Predicting a collision:
we have a point of radius s at position (rx,ry)
the point is moving with speed (vx,vy)
the question is: will it collide with a vertical wall and if so, when?
Collision between points is a more difficult problem, to predict the collision of points and their behavior afterwards. I'm also sending an example of the code that will be used to do this
Code example:
import functools
import math
import random
import warnings
import matplotlib.pyplot as plt
import matplotlib.animation as animation
this function moves all objects passing delta time, returns
scatter plot of points that should be drawn
the last parameter is time in seconds, it goes from matplotlib animator
def animate(objects, dt, _t):
for obj in objects:
obj.move(dt)
code
return [obj.scatter for obj in objects]
if name == "main":
# 10 milliseconds delta t
delta_t = 10
n_balls = 5
balls = []
code
for i in range(n_balls):
x = random.randint(1, 25)
y = random.randint(1, 15)
vx = random.randint(1, 20)
vy = random.randint(1, 20)
mass = random.random()
radius = random.random()
print(f"Creating a new Particle({x}, {y}, {vx}, {vy}, {radius}, {mass})")
balls.append(Particle(x, y, vx, vy, radius, mass))
# interval in milliseconds
ani = animation.FuncAnimation(
fig, functools.partial(animate, balls, delta_t / 1_000), interval=delta_t, blit=True, save_count=100,
)
plt.show()
Certainly! I'll help you implement an event-driven simulation for N particles moving within a bounded area, focusing on collisions between particles and with the walls. We'll use a priority queue to manage collision events based on their occurrence times.
Here's how we'll approach this:
Predict Collision Times: Implement methods to predict the time until the next collision between particles and between particles and walls.
Event Queue: Use a priority queue to keep track of upcoming collision events.
Simulation Loop: Process events from the priority queue, update the system state, and schedule new events as needed.
Below, I'll provide the necessary code additions and explain each part in detail.
1. Augment the Particle Class
First, we need to add methods to the Particle class that predict collision times with vertical and horizontal walls.
We'll create an Event class that represents collision events. Each event will have an occurrence time and references to the particles involved.
python
class Event:
def __init__(self, time, a, b):
self.time = time # Time when the event occurs
self.a = a # First particle (can be None for wall collisions)
self.b = b # Second particle (can be None for wall collisions)
self.count_a = a.collisions_count if a else -1
self.count_b = b.collisions_count if b else -1
def __lt__(self, other): # For the priority queue
return self.time < other.time
def is_valid(self):
if self.a and self.a.collisions_count != self.count_a:
return False
if self.b and self.b.collisions_count != self.count_b:
return False
return True
3. Initialize the Priority Queue
We need to set up a priority queue (min-heap) that keeps track of all future events.
python
event_queue = []
heapq.heapify(event_queue)
4. Schedule Initial Events
For each particle, we predict collisions with other particles and walls, and add those events to the queue.
python
def predict_events(particle, current_time, limit):
# Predict particle's collisions with other particles
for other in balls:
if particle != other:
dt = particle.time_to_hit(other)
event_time = current_time + dt
if 0 <= dt <= limit:
event = Event(event_time, particle, other)
heapq.heappush(event_queue, event)
# Predict particle's collisions with vertical walls
dt = particle.time_to_hit_vertical_wall()
event_time = current_time + dt
if 0 <= dt <= limit:
event = Event(event_time, particle, None)
heapq.heappush(event_queue, event)
# Predict particle's collisions with horizontal walls
dt = particle.time_to_hit_horizontal_wall()
event_time = current_time + dt
if 0 <= dt <= limit:
event = Event(event_time, None, particle)
heapq.heappush(event_queue, event)
We call predict_events for each particle at the simulation start:
python
current_time = 0.0
simulation_limit = 100.0 # Run simulation for 100 seconds
# Schedule initial events
for particle in balls:
predict_events(particle, current_time, simulation_limit)
5. Simulation Loop
We process events in chronological order, updating particle positions as needed.
python
def simulate():
global current_time
while event_queue and current_time < simulation_limit:
event = heapq.heappop(event_queue)
if not event.is_valid():
continue # Ignore invalid events
# Move all particles to the time of the event
dt = event.time - current_time
for particle in balls:
particle.move(dt)
current_time = event.time
# Process the event
a, b = event.a, event.b
if a and b:
# Particle-particle collision
a.bounce_off(b)
elif a and not b:
# Particle-wall (vertical) collision
a.bounce_off_vertical_wall()
elif b and not a:
# Particle-wall (horizontal) collision
b.bounce_off_horizontal_wall()
# After processing, predict new events involving the affected particles
if a:
predict_events(a, current_time, simulation_limit)
if b:
predict_events(b, current_time, simulation_limit)
6. Modify the Animation Function
Update the animation function to reflect the event-driven simulation.
python
def animate(_):
simulate()
# Return updated scatter plots for redrawing
return [obj.scatter for obj in balls]
7. Run the Simulation
Finally, set up the animation to use the new animate function.
python
ani = animation.FuncAnimation(
fig, animate, frames=200, interval=delta_t, blit=True)
Full Updated Code
Here's the complete code with all the additions:
python
Explanation
Particle Class: Added methods to predict collision times with walls and to handle wall collisions (bounce_off_vertical_wall, bounce_off_horizontal_wall).
Event Class: Represents events in the simulation. The is_valid method ensures events are still valid by checking collision counts.
Priority Queue: Used to keep track of future events. We use heapq to implement a min-heap based on event times.
Event Prediction: The predict_events function schedules future collisions for a given particle.
Simulation Loop: The simulate function processes events in order, updates particle positions, handles collisions, and schedules new events.
Animation: The animate function calls simulate and updates the plot accordingly.
Notes
Time Management: Time advances only when events occur. Between events, particles move in straight lines.
Event Validity: When a collision occurs, it may invalidate other scheduled events involving the same particles. The is_valid method checks for this.
Particle Initialization: Particles are placed randomly within the bounds, and their velocities, masses, and radii are randomized within specified ranges.
Simulation Limit: You can adjust simulation_limit to control the total simulation time.
Testing the Simulation
Run the code and observe the animation. You should see particles moving and colliding with each other and the walls. The event-driven approach ensures accurate collision handling without small time-step approximations.
Feel free to adjust parameters like the number of particles, their properties, or the simulation limit to suit your needs. If you have any questions or need further assistance, let me know!