To implement the collision simulation using an event-driven approach, we'll need to:
- Implement an
Event class to model collision events, with a priority queue to manage these events based on their scheduled times.
- Extend the
Particle class to include methods for predicting collision times with other particles and walls, as well as methods to handle the collisions.
- Write a
simulate function that drives the simulation by processing events from the priority queue, updating particle positions, handling collisions, and scheduling new events.
Here's the complete code incorporating these elements:
import functools
import math
import random
import warnings
import heapq
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# disable warnings
warnings.filterwarnings("ignore")
# matplotlib configuration
# bounds of the room
x_lim = (0, 30)
y_lim = (0, 20)
# scaler for bigger points in plots
PLT_RADIUS_SCALER = 25
Hz = 60.0 # Frames per second
# set up plot to draw animations
fig = plt.figure()
ax = fig.add_subplot(111, autoscale_on=False, xlim=x_lim, ylim=y_lim)
# disable x and y axes labels
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
# scatter plot for drawing point
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
# updates point position in plot
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
# Compute magnitude of normal force
J = 2 * self.mass * that.mass * dvdr / ((self.mass + that.mass) * dist)
# Compute normal force components
Jx = J * dx / dist
Jy = J * dy / dist
# Update velocities
self.vx += Jx / self.mass
self.vy += Jy / self.mass
that.vx -= Jx / that.mass
that.vy -= Jy / that.mass
self.collisions_count += 1
that.collisions_count += 1
def time_to_hit(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 (x_lim[0] - self.rx + self.radius) / 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 (y_lim[0] - self.ry + self.radius) / self.vy
else:
return math.inf
def bounce_off_vertical_wall(self):
self.vx = -self.vx
self.collisions_count += 1
def bounce_off_horizontal_wall(self):
self.vy = -self.vy
self.collisions_count += 1
class Event:
def __init__(self, time, a, b):
self.time = time # time of event
self.a = a # particle a; None if wall collision
self.b = b # particle b; None if wall collision
if a:
self.countA = a.collisions_count
else:
self.countA = -1
if b:
self.countB = b.collisions_count
else:
self.countB = -1
def __lt__(self, other):
return self.time < other.time
def is_valid(self):
if self.a and self.a.collisions_count != self.countA:
return False
if self.b and self.b.collisions_count != self.countB:
return False
return True
def predict(a, t, particles, pq, limit):
if a is None:
return
for b in particles:
if b == a:
continue
dt = a.time_to_hit(b)
if t + dt <= limit and dt != math.inf:
heapq.heappush(pq, Event(t + dt, a, b))
dt = a.time_to_hit_vertical_wall()
if t + dt <= limit and dt != math.inf:
heapq.heappush(pq, Event(t + dt, a, None))
dt = a.time_to_hit_horizontal_wall()
if t + dt <= limit and dt != math.inf:
heapq.heappush(pq, Event(t + dt, None, a))
def redraw():
plt.pause(0.001)
def simulate(particles, limit=10000.0):
t = 0.0
pq = []
# Initialize priority queue with all initial events
for a in particles:
predict(a, t, particles, pq, limit)
# Schedule initial redraw event
heapq.heappush(pq, Event(0, None, None))
while pq and t < limit:
event = heapq.heappop(pq)
if not event.is_valid():
continue
dt = event.time - t
for p in particles:
p.move(dt)
t = event.time
a = event.a
b = event.b
if a and b:
# Collision between particles
a.bounce_off(b)
elif a and not b:
# Collision with vertical wall
a.bounce_off_vertical_wall()
elif not a and b:
# Collision with horizontal wall
b.bounce_off_horizontal_wall()
else:
# Redraw event
redraw()
# Schedule next redraw
heapq.heappush(pq, Event(t + 1.0 / Hz, None, None))
# Predict new events for particles involved in collision
predict(a, t, particles, pq, limit)
predict(b, t, particles, pq, limit)
# Create particles with random positions and velocities
N = 10 # Number of particles
particles = []
radius = 0.5
mass = 1.0
for _ in range(N):
rx = random.uniform(x_lim[0] + radius, x_lim[1] - radius)
ry = random.uniform(y_lim[0] + radius, y_lim[1] - radius)
vx = random.uniform(-1.0, 1.0)
vy = random.uniform(-1.0, 1.0)
particles.append(Particle(rx, ry, vx, vy, radius, mass))
simulate(particles)
plt.show()
Explanation:
Note:
- The simulation runs until the event queue is empty or the simulation time exceeds the specified
limit.
- The particles move in straight lines between collision events, which are calculated precisely to maintain accuracy.
- This implementation assumes a perfectly elastic collision model without considering external forces like gravity or friction.
Run this code in an environment where you can display plots (like Jupyter Notebook or a Python script on your local machine) to observe the particles moving and colliding within the defined bounds.