Implementing Nagel-Schreckenberg simulation with visualization
The code simulates traffic on a circular single-lane road applying the NaSch rules including acceleration, deceleration, random slowdowns, and movement with periodic boundary conditions, then produces a space-time diagram to clearly show spontaneous traffic jams emerging from initial uniform spacing.
Below is a self‑contained Python example of the Nagel–Schreckenberg (NaSch) cellular automaton on a single‑lane circular road. It implements the canonical four steps (acceleration, deceleration, randomization, movement) in parallel for each time step and produces a space–time diagram to visualize “phantom” traffic jams emerging from random slowdowns.
import numpy as np
import matplotlib.pyplot as plt
def nagel_schreckenberg(L=100, N=30, vmax=5, p=0.3, steps=200, seed=None):
"""
Simulate the Nagel–Schreckenberg traffic model on a ring road.
Parameters
----------
L : int
Number of cells in the ring.
N : int
Number of cars.
vmax : int
Maximum speed (cells per time step).
p : float
Probability of random slowdown.
steps : int
Number of simulation time steps.
seed : int or None
Random seed for reproducibility.
Returns
-------
occupancy : ndarray, shape (steps, L)
occupancy[t, x] = 1 if cell x is occupied at time t, else 0.
positions_history : list of ndarray
positions_history[t] = array of car positions at time t (sorted).
velocities_history : list of ndarray
velocities_history[t] = array of velocities at time t (aligned with positions_history).
"""
rng = np.random.default_rng(seed)
# Randomly choose distinct initial positions and set velocities to zero
positions = np.sort(rng.choice(L, N, replace=False))
velocities = np.zeros(N, dtype=int)
occupancy = np.zeros((steps, L), dtype=int)
positions_history = []
velocities_history = []
for t in range(steps):
# Record state
occupancy[t, positions] = 1
positions_history.append(positions.copy())
velocities_history.append(velocities.copy())
# Step 1: Acceleration
velocities = np.minimum(velocities + 1, vmax)
# Step 2: Deceleration to avoid collisions (compute gaps)
gaps = np.zeros(N, dtype=int)
for i in range(N):
next_i = (i + 1) % N
# distance to next car minus 1
gap = (positions[next_i] - positions[i] - 1) % L
gaps[i] = gap
velocities = np.minimum(velocities, gaps)
# Step 3: Randomization (with probability p, slow down by 1 if v>0)
rand_mask = rng.random(N) < p
slow_mask = (velocities > 0) & rand_mask
velocities[slow_mask] -= 1
# Step 4: Movement
positions = (positions + velocities) % L
# Re-sort positions and velocities to keep cars in order along the ring
order = np.argsort(positions)
positions = positions[order]
velocities = velocities[order]
return occupancy, positions_history, velocities_history
if __name__ == "__main__":
# Parameters
L = 100 # length of road
N = 30 # number of cars
vmax = 5 # maximum speed
p = 0.3 # probability of random slowdown
steps = 300 # number of time steps
seed = 42 # reproducible randomness
occupancy, pos_hist, vel_hist = nagel_schreckenberg(
L=L, N=N, vmax=vmax, p=p, steps=steps, seed=seed
)
# Space–time diagram: rows are time, columns are position
plt.figure(figsize=(8, 6))
plt.imshow(occupancy, aspect='auto', cmap='Greys', interpolation='nearest')
plt.xlabel("Position on Ring (cells)")
plt.ylabel("Time Step")
plt.title("Nagel–Schreckenberg Model: Space–Time Diagram")
plt.gca().invert_yaxis()
plt.show()
How it works
At each time step, all cars are updated in parallel according to these rules:
- Acceleration:
v = min(v + 1, vmax)
- Deceleration to avoid collisions:
v = min(v, gap) where gap is the number of empty cells to the next car.
- Randomization: with probability
p, if v > 0 then v = v - 1.
- Movement: position
x = (x + v) mod L.
Because of random slowdowns, small perturbations can grow into clusters of slow vehicles: the “phantom” traffic jams appear in the space–time diagram as slanted lines or stationary high‑density bands even without any obstacle or “bottleneck” on the road. Adjusting density N/L and p can accentuate or diminish jam formation.