To implement the collision simulation in the provided code, we'll follow the event-driven simulation approach as described. Here's the step-by-step implementation:
-
Implement Particle methods for wall collisions:
time_to_hit_vertical_wall(): Calculates the time until a particle hits a vertical wall.
time_to_hit_horizontal_wall(): Calculates the time until a particle hits a horizontal wall.
bounce_off_vertical_wall(): Updates the particle's velocity after colliding with a vertical wall.
bounce_off_horizontal_wall(): Updates the particle's velocity after colliding with a horizontal wall.
-
Implement the Event class:
- Represents collision events with attributes for the time of the event and the particles involved.
- Includes a method
is_valid() to check if the event is still valid (particles haven't collided with something else in the meantime).
-
Implement the SimulationSystem class:
- Manages the event priority queue and the simulation clock.
- Includes the
predict() method to calculate future collisions and insert them into the priority queue.
- Includes the
simulate_up_to() method to process events up to the given time.
-
Modify the move() method in Particle:
- Updates the particle's position based on its velocity and the given time interval
dt.
-
Adjust the animation function:
- Calls
simulate_up_to() to advance the simulation to the current time.
- Updates the positions of the particles for plotting.
-
Integrate everything in the main code:
- Initialize particles ensuring they don't overlap and are within boundaries.
- Create an instance of
SimulationSystem.
- Set up the animation using
FuncAnimation, passing the simulation system to the animate function.
Here's the complete code incorporating the above steps:
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
# 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):
# Move particle according to its velocity for time dt
self._rx += self._vx * dt
self._ry += self._vy * dt
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
# Calculate magnitude of force
J = 2 * self.mass * that.mass * dvdr / ((self.mass + that.mass) * dist)
Jx = J * dx / dist
Jy = J * dy / dist
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 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
def time_to_hit_vertical_wall(self):
if self.vx > 0:
dt = (x_lim[1] - self.rx - self.radius) / self.vx
elif self.vx < 0:
dt = (x_lim[0] + self.radius - self.rx) / self.vx
else:
dt = math.inf
return dt if dt >= 0 else math.inf
def time_to_hit_horizontal_wall(self):
if self.vy > 0:
dt = (y_lim[1] - self.ry - self.radius) / self.vy
elif self.vy < 0:
dt = (y_lim[0] + self.radius - self.ry) / self.vy
else:
dt = math.inf
return dt if dt >= 0 else math.inf
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
class Event:
def __init__(self, time, a, b):
self.time = time # time of event
self.a = a # particle a (can be None)
self.b = b # particle b (can be None)
self.countA = a.collisions_count if a else -1
self.countB = b.collisions_count if b else -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
class SimulationSystem:
def __init__(self, particles):
self.particles = particles
self.pq = []
self.t = 0.0
# Initialize priority queue with prediction for all particles
for particle in particles:
self.predict(particle)
# Insert initial redraw event
heapq.heappush(self.pq, Event(0.0, None, None))
def predict(self, a):
if a is None:
return
# Predict collisions with other particles
for particle in self.particles:
dt = a.time_to_hit(particle)
if dt != math.inf:
heapq.heappush(self.pq, Event(self.t + dt, a, particle))
# Predict collision with vertical wall
dt = a.time_to_hit_vertical_wall()
if dt != math.inf:
heapq.heappush(self.pq, Event(self.t + dt, a, None))
# Predict collision with horizontal wall
dt = a.time_to_hit_horizontal_wall()
if dt != math.inf:
heapq.heappush(self.pq, Event(self.t + dt, None, a))
def simulate_up_to(self, time_limit):
while self.pq and self.pq[0].time <= time_limit:
event = heapq.heappop(self.pq)
if not event.is_valid():
continue
dt = event.time - self.t
for particle in self.particles:
particle.move(dt)
self.t = event.time
a = event.a
b = event.b
if a is not None and b is not None:
# Particle-particle collision
a.bounce_off(b)
elif a is not None and b is None:
# Particle-wall collision (vertical wall)
a.bounce_off_vertical_wall()
elif a is None and b is not None:
# Particle-wall collision (horizontal wall)
b.bounce_off_horizontal_wall()
elif a is None and b is None:
# Redraw event (handled in animation)
pass
# After processing event, predict new events for a and b
self.predict(a)
self.predict(b)
# Move particles up to time_limit, if necessary
dt = time_limit - self.t
if dt > 0:
for particle in self.particles:
particle.move(dt)
self.t = time_limit
def animate(frame, simulation_system):
t = frame * delta_t
simulation_system.simulate_up_to(t)
# Update positions in plot
for particle in simulation_system.particles:
particle.scatter.set_data([particle.rx], [particle.ry])
return [particle.scatter for particle in simulation_system.particles]
if __name__ == "__main__":
# Simulation parameters
delta_t = 1 / 60 # Time between frames (60 FPS)
t_max = 100 # Total simulation time
num_frames = int(t_max / delta_t)
n_balls = 10
balls = []
for i in range(n_balls):
while True:
radius = random.uniform(0.1, 0.4)
mass = random.uniform(0.5, 1.5)
x = random.uniform(x_lim[0] + radius, x_lim[1] - radius)
y = random.uniform(y_lim[0] + radius, y_lim[1] - radius)
vx = random.uniform(-5, 5)
vy = random.uniform(-5, 5)
new_particle = Particle(x, y, vx, vy, radius, mass)
# Check for overlaps with existing particles
overlap = False
for particle in balls:
dx = new_particle.rx - particle.rx
dy = new_particle.ry - particle.ry
dist = math.hypot(dx, dy)
if dist < new_particle.radius + particle.radius:
overlap = True
break
if not overlap:
break
print(f"Creating a new Particle({x:.2f}, {y:.2f}, {vx:.2f}, {vy:.2f}, radius={radius:.2f}, mass={mass:.2f})")
balls.append(new_particle)
simulation_system = SimulationSystem(balls)
# interval in milliseconds
ani = animation.FuncAnimation(
fig, animate, fargs=(simulation_system,), frames=num_frames,
interval=delta_t * 1000, blit=True, save_count=100,
)
plt.show()
Explanation:
This implementation follows the event-driven simulation approach, ensuring accurate collision handling and efficient computation by only processing events when necessary.