I'm focused on the basic needs of the simulation script. I've begun with the fundamental goal of traffic simulation using agent-based modeling. Now, I'm defining the scope, which currently includes a 1D road to keep things simple.
Defining the Core Model
I'm solidifying the implementation strategy for the Nagel-Schreckenberg model. I've pinpointed the model's core components: discrete cells for the road, car agents defined by position and velocity. Now, I'm defining the rules for each timestep: acceleration, deceleration (safety), and randomization to mimic human behavior.
Formulating the Implementation
I'm now zeroing in on the detailed implementation. The key aspects are the Car class, and the main TrafficSimulation class, with parameters, a simulation step function, and a visualization function. My choice of object-oriented approach is guiding the structure, which should improve code readability, even if it might sacrifice some raw speed. I'm prioritizing clarity.
Comprehending the Implementation
Now, I'm analyzing the potential Python code. I'm focusing on the main loop and the logic for car movement. Considering the distance calculations on the circular road, I'm planning to use modulo operations to handle wrap-around. I will also incorporate randomization to add some human behavior into the car's movements.
Developing the Algorithm
I'm now mapping out the steps to implement the Nagel-Schreckenberg model. I've broken down the model's core rules and considering the logic for acceleration, safety checks, and the probabilistic slowdown. Furthermore, I'm thinking about the car movement and the necessary modulus operations for the circular road.
Refining the Algorithm Choice
I'm now contemplating specific details within the Nagel-Schreckenberg model implementation. Vectorization might speed up the calculations, but I'll prioritize readability with the partially object-oriented structure I planned. I'm focusing on the main loop and the order of operations, especially how car positions affect each other in a circular road environment.
This script implements the Nagel-Schreckenberg model, a classic cellular automata model for traffic simulation. It demonstrates how simple individual agent rules can lead to complex emergent behavior, such as "phantom traffic jams" (jams that appear without an accident or bottleneck).
Prerequisites
You will need numpy and matplotlib:
bash
pip install numpy matplotlib
The Python Script
python
How it works
This model relies on 4 key rules applied to every car in every frame:
Acceleration: Cars always want to go faster, up to the speed limit.
Safety (Deceleration): If the car ahead is close, the driver slows down to avoid a crash (distance = speed).
Randomization: Drivers have a probability (slow_prob) of slowing down randomly. This simulates distraction, hesitation, or over-braking.
Movement: The car moves forward based on the calculated velocity.
How to analyze the results
Ghost Traffic Jams: Even if you set slow_prob very low, you will see clusters of cars form.
Backward Propagation: In the Space-Time Heatmap, notice that while the cars (points) move from left to right, the traffic jams (the red/orange clusters) actually move from right to left. This matches real-world physics where a brake light wave travels upstream against the flow of traffic.
Density Impact:
Density < 0.1: Free flow traffic.
Density > 0.3: Frequent stop-and-go waves.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class TrafficSimulation:
def __init__(self, length=100, density=0.3, max_speed=5, slow_prob=0.3):
"""
Initialize the simulation sets.
Args:
length (int): Length of the circular road.
density (float): Percentage of road occupied by cars (0.0 to 1.0).
max_speed (int): Maximum speed limit of cars.
slow_prob (float): Probability of a driver randomly slowing down.
"""
self.length = length
self.density = density
self.max_speed = max_speed
self.slow_prob = slow_prob
# Initialize road: -1 represents empty space, 0-max_speed is a car
self.state = np.full(self.length, -1, dtype=int)
# Randomly place cars
num_cars = int(length * density)
indices = np.random.choice(length, num_cars, replace=False)
self.state[indices] = np.random.randint(0, max_speed + 1, size=num_cars)
def step(self):
"""
Advance the simulation by one time step using Nagel-Schreckenberg rules.
"""
# Get indices of all cars
car_indices = np.where(self.state > -1)[0]
if len(car_indices) == 0:
return
# Prepare the next state
next_state = np.full(self.length, -1, dtype=int)
for i, idx in enumerate(car_indices):
velocity = self.state[idx]
# Find distance to the next car (handling circular road wrap-around)
next_car_idx = car_indices[(i + 1) % len(car_indices)]
dist = (next_car_idx - idx) % self.length
# RULES OF THE AGENT:
# 1. Acceleration: If not at max speed, speed up
if velocity < self.max_speed:
velocity += 1
# 2. Deceleration: Don't hit the car in front
# dist is distance to next car, valid gap is dist - 1
if velocity >= dist:
velocity = dist - 1
# 3. Randomization: Randomly slow down (human error/distraction)
if velocity > 0 and np.random.rand() < self.slow_prob:
velocity -= 1
# 4. Movement: Update position
new_pos = (idx + velocity) % self.length
next_state[new_pos] = velocity
self.state = next_state
def run_simulation(self, steps):
"""Run simulation and return history for static visualization."""
history = []
for _ in range(steps):
history.append(self.state.copy())
self.step()
return np.array(history)
# --- Visualization Functions ---
def animate_traffic():
"""Creates a real-time animation of the ring road."""
# Simulation Parameters
road_len = 100
sim = TrafficSimulation(length=road_len, density=0.35, max_speed=5, slow_prob=0.3)
fig, ax = plt.subplots(figsize=(8, 8), subplot_kw={'projection': 'polar'})
ax.set_axis_off()
ax.set_title("Agent-Based Traffic Flow (Nagel-Schreckenberg Model)", va='bottom')
# Setup scatter plot
# Convert linear road 0..100 to radians 0..2pi
theta = np.linspace(0, 2*np.pi, road_len, endpoint=False)
r = np.ones(road_len)
# Initialize scatter: colors map to speed
scat = ax.scatter(theta, r, c=[], cmap='viridis', s=50, vmin=0, vmax=sim.max_speed)
def update(frame):
sim.step()
# Create arrays for visualization
# Filter only cells that have cars (value != -1)
mask = sim.state > -1
current_theta = theta[mask]
current_r = r[mask]
current_colors = sim.state[mask]
# Update plot data
scat.set_offsets(np.c_[current_theta, current_r])
scat.set_array(current_colors)
return scat,
ani = animation.FuncAnimation(fig, update, frames=200, interval=50, blit=False)
plt.show()
def plot_spacetime_diagram():
"""
Creates a Time-Space diagram.
X-axis is road position, Y-axis is time (descending).
This visualizes how traffic jams propagate backward (waves).
"""
sim = TrafficSimulation(length=200, density=0.4, max_speed=5, slow_prob=0.3)
steps = 300
data = sim.run_simulation(steps)
plt.figure(figsize=(10, 8))
# Mask empty spots for better visualization (make them white)
masked_data = np.ma.masked_where(data == -1, data)
plt.imshow(masked_data, cmap='plasma', aspect='auto', interpolation='nearest')
plt.colorbar(label='Speed (0 to Max)')
plt.xlabel('Lane Position')
plt.ylabel('Time (Steps)')
plt.title('Space-Time Diagram: Traffic Jam Propagation')
plt.text(5, 10, "Traffic flows right ->\nJams move left <-", color='black', backgroundcolor='white')
plt.show()
if __name__ == "__main__":
print("Choose visualization mode:")
print("1. Real-time Animation (Circle Road)")
print("2. Space-Time Heatmap (Analysis)")
choice = input("Enter 1 or 2: ")
if choice == '1':
animate_traffic()
elif choice == '2':
plot_spacetime_diagram()
else:
print("Invalid choice.")