To create an event-based simulation for N particles moving within a closed perimeter, handling collisions with both walls and other particles, we'll follow these steps:
-
Event-Based Model Overview:
- Events: Collisions between particles or between a particle and a wall.
- Priority Queue: Maintain a priority queue (min-heap) that orders events by their scheduled time.
- State Updates: Only update the system state when an event occurs.
- Recalculation: After each event, predict future events involving the affected particles and add them to the queue.
-
Key Components:
- Particle Class: Represents each particle with properties like position, velocity, radius, mass, and collision count.
- Event Class: Represents collision events, storing the event time and the involved particles.
- Simulation Class: Manages the overall simulation, including the priority queue of events and the current simulation time.
- Collision Prediction: Methods to predict the next collision time between particles and walls.
-
Handling Collision Validity:
- Each particle maintains a
collision_count to track how many times it has collided.
- When processing an event, verify that the involved particles haven't collided since the event was scheduled. This ensures outdated events (due to prior collisions) are ignored.
-
Integrating with Visualization:
- Use
matplotlib for animating the particle movements.
- Update particle positions based on the current simulation time.
Below is the complete Python code implementing the described event-based simulation:
import functools
import math
import random
import warnings
import heapq
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Disable warning
warnings.filterwarnings("ignore")
# Matplotlib configuration
x_lim = (0, 30)
y_lim = (0, 20)
PLT_RADIUS_SCALER = 25
fig = plt.figure()
ax = fig.add_subplot(111, autoscale_on=False, xlim=x_lim, ylim=y_lim)
ax.set_yticks([])
ax.set_xticks([])
class Particle:
def __init__(self, rx, ry, vx, vy, radius, mass):
self._rx = rx
self._ry = ry
self._vx = vx
self._vy = vy
self._radius = radius
self._mass = mass
self._collisions_count = 0
self._scatter, = ax.plot([], [], 'o',
markersize=self._radius * PLT_RADIUS_SCALER)
@property
def rx(self):
return self._rx
@property
def ry(self):
return self._ry
@property
def vx(self):
return self._vx
@property
def vy(self):
return self._vy
@vx.setter
def vx(self, value):
self._vx = value
@vy.setter
def vy(self, value):
self._vy = value
@property
def radius(self):
return self._radius
@property
def mass(self):
return self._mass
@property
def collisions_count(self):
return self._collisions_count
@collisions_count.setter
def collisions_count(self, value):
self._collisions_count = value
@property
def scatter(self):
return self._scatter
def move(self, dt):
self._rx += self._vx * dt
self._ry += self._vy * dt
self.scatter.set_data([self._rx], [self._ry])
def bounce_off(self, that):
dx = that.rx - self.rx
dy = that.ry - self.ry
dvx = that.vx - self.vx
dvy = that.vy - self.vy
dvdr = dx * dvx + dy * dvy
dist = self.radius + that.radius
# Magnitude of the force
j = 2 * self.mass * that.mass * dvdr / ((self.mass + that.mass) * dist)
j_x = j * dx / dist
j_y = j * dy / dist
self.vx += j_x / self.mass
self.vy += j_y / self.mass
that.vx -= j_x / that.mass
that.vy -= j_y / that.mass
self.collisions_count += 1
that.collisions_count += 1
def time_to_hit_particle(self, that):
if self == that:
return math.inf
dx = that.rx - self.rx
dy = that.ry - self.ry
dvx = that.vx - self.vx
dvy = that.vy - self.vy
dvdr = dx * dvx + dy * dvy
if dvdr > 0:
return math.inf
dvdv = dvx * dvx + dvy * dvy
drdr = dx * dx + dy * dy
sigma = self.radius + that.radius
d = (dvdr * dvdr) - dvdv * (drdr - sigma * sigma)
if d < 0:
return math.inf
return -(dvdr + math.sqrt(d)) / dvdv
def time_to_hit_vertical_wall(self):
if self.vx > 0:
return (x_lim[1] - self.rx - self.radius) / self.vx
elif self.vx < 0:
return (self.radius - self.rx) / self.vx
else:
return math.inf
def time_to_hit_horizontal_wall(self):
if self.vy > 0:
return (y_lim[1] - self.ry - self.radius) / self.vy
elif self.vy < 0:
return (self.radius - self.ry) / self.vy
else:
return math.inf
class Event:
def __init__(self, time, a, b):
self.time = time
self.a = a
self.b = b
if a:
self.a_collision_count = a.collisions_count
else:
self.a_collision_count = -1
if b:
self.b_collision_count = b.collisions_count
else:
self.b_collision_count = -1
def __lt__(self, other):
return self.time < other.time
def is_valid(self):
if self.a and self.a.collisions_count != self.a_collision_count:
return False
if self.b and self.b.collisions_count != self.b_collision_count:
return False
return True
class Simulation:
def __init__(self, particles):
self.particles = particles
self.pq = []
self.t = 0.0
self.limit = 1000.0 # Simulation time limit
# Initialize event queue with initial collision events
for p in self.particles:
self.predict(p, 0.0)
def predict(self, a, current_time):
if a is None:
return
# Particle-wall collisions
dt = a.time_to_hit_vertical_wall()
if current_time + dt <= self.limit:
heapq.heappush(self.pq, Event(current_time + dt, a, None))
dt = a.time_to_hit_horizontal_wall()
if current_time + dt <= self.limit:
heapq.heappush(self.pq, Event(current_time + dt, None, a))
# Particle-particle collisions
for b in self.particles:
if b != a:
dt = a.time_to_hit_particle(b)
if current_time + dt <= self.limit:
heapq.heappush(self.pq, Event(current_time + dt, a, b))
def simulate(self):
while self.pq:
event = heapq.heappop(self.pq)
if not event.is_valid():
continue
if event.time > self.limit:
break
# Move all particles to the time of event
dt = event.time - self.t
for p in self.particles:
p.move(dt)
self.t = event.time
# Process event
if event.a and event.b:
event.a.bounce_off(event.b)
elif event.a and not event.b:
# Vertical wall collision
event.a.vx = -event.a.vx
event.a.collisions_count += 1
elif not event.a and event.b:
# Horizontal wall collision
event.b.vy = -event.b.vy
event.b.collisions_count += 1
# After processing, predict new events for the involved particles
self.predict(event.a, self.t)
self.predict(event.b, self.t)
yield # Yield control back to the animation
def initialize_particles(n_balls):
balls = []
for _ in range(n_balls):
radius = random.uniform(0.5, 1.0)
mass = radius # For simplicity, let's set mass proportional to radius
x = random.uniform(x_lim[0] + radius, x_lim[1] - radius)
y = random.uniform(y_lim[0] + radius, y_lim[1] - radius)
# Ensure particles don't overlap initially
overlap = True
while overlap:
overlap = False
for p in balls:
dx = p.rx - x
dy = p.ry - y
distance = math.hypot(dx, dy)
if distance < p.radius + radius:
overlap = True
x = random.uniform(x_lim[0] + radius, x_lim[1] - radius)
y = random.uniform(y_lim[0] + radius, y_lim[1] - radius)
break
vx = random.uniform(-5, 5)
vy = random.uniform(-5, 5)
particle = Particle(x, y, vx, vy, radius, mass)
balls.append(particle)
return balls
def animate_sim(simulation, frames):
try:
next(simulation)
objects = [p.scatter for p in simulation.particles]
return objects
except StopIteration:
return []
if __name__ == "__main__":
delta_t = 10 # Not used in event-based simulation
n_balls = 10
balls = initialize_particles(n_balls)
sim = Simulation(balls)
frames = int(sim.limit * 10) # Arbitrary number of frames
ani = animation.FuncAnimation(
fig,
functools.partial(animate_sim, sim),
frames=frames,
interval=20, # Time between frames in ms
blit=True,
repeat=False
)
plt.show()
Explanation of the Code:
-
Particle Class:
- Initialization: Initializes position
(rx, ry), velocity (vx, vy), radius, mass, and a scatter plot for visualization.
- Movement: The
move(dt) method updates the particle's position based on its velocity and the elapsed time dt. It also updates its position on the plot.
- Collision Handling:
bounce_off(that): Updates velocities of both particles self and that after a collision based on momentum conservation.
time_to_hit_particle(that): Calculates the time until this particle collides with another particle that.
time_to_hit_vertical_wall() and time_to_hit_horizontal_wall(): Calculate the time until the particle collides with a vertical or horizontal wall, respectively.
-
Event Class:
- Represents a collision event with properties:
time: When the event occurs.
a and b: The particles involved (None if it's a wall collision).
a_collision_count and b_collision_count: The state of each particle's collision count at the time of event scheduling.
- Validity Check:
is_valid() ensures the event is still valid by comparing the stored collision counts with the current counts. If either particle has collided since the event was scheduled, the event is invalidated.
-
Simulation Class:
- Initialization: Takes a list of
particles, initializes a priority queue pq, sets the simulation time t to 0, and a simulation time limit.
- Predicting Events: The
predict(a, current_time) method schedules future events involving particle a by:
- Calculating collision times with walls and other particles.
- Adding valid future events to the priority queue.
- Simulation Loop: The
simulate() generator function processes events in chronological order:
- Pops the next event from the queue.
Notes:
- Performance: Event-based simulations are generally more efficient than time-step-based simulations, especially when events (collisions) are sparse.
- Collision Prediction: The methods for predicting collision times are derived from kinematic equations and ensure that only future collision events are considered.
- Visualization: The
matplotlib animation updates particle positions based on the simulation's event times, providing a smooth and accurate visualization of the system.
This implementation provides a robust event-based simulation framework for particles interacting within a closed perimeter, handling both particle-particle and particle-wall collisions efficiently.