Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

15. Emergence: traffic jams in a cellular automaton and flocking

School of Engineering, Nazarbayev University

Drivers sometimes queue for many minutes and then reach clear road without passing any accident, lane closure or stalled vehicle. Where did the jam come from, and why does a traffic jam travel backward, against the traffic, while every car drives forward? Collective waves and order–disorder transitions can arise from simple local rules. In this lecture, you will simulate Nagel-Schreckenberg (1992) highway cellular automata (emergence_verification.nagel_schreckenberg_traffic), construct the Fundamental Diagram J(ρ)=ρvˉ(ρ)J(\rho) = \rho \bar{v}(\rho) showing capacity breakdown past ρc=1/(vmax⁡+1)\rho_c = 1/(v_{\max} + 1), explore Vicsek’s (1995) self-propelled flocking transition (emergence_verification.vicsek_flocking_step_and_run), show how, in the model, removing the random braking (pslow→0p_{\mathrm{slow}} \to 0, a stand-in for adaptive cruise control) dissolves the jams, and implement Thomas Schelling’s (1971) segregation lattice.

Learning objectives

  1. Simulate 1-D Nagel-Schreckenberg traffic cellular automata (emergence_verification.nagel_schreckenberg_traffic) and explain why macroscopic jam fronts propagate backward (cjam<0c_{\mathrm{jam}} < 0) while microscopic car velocities stay non-negative.

  2. Construct the macroscopic Fundamental Diagram J(ρ)=ρvˉ(ρ)J(\rho) = \rho \bar{v}(\rho) and prove analytically why deterministic capacity peaks at ρc=1/(vmax⁡+1)\rho_c = 1/(v_{\max} + 1) with Jmax⁡=vmax⁡/(vmax⁡+1)J_{\max} = v_{\max}/(v_{\max} + 1).

  3. Track collective polarization Φ(η)∈[0,1]\Phi(\eta) \in [0, 1] across angular noise η\eta in 2-D Vicsek flocking (emergence_verification.vicsek_flocking_step_and_run) and audit circular angle-averaging vs. asynchronous update bugs.

  4. Implement Schelling’s tipping-point lattice model to quantify how mild local preferences (τ=35%\tau = 35\%) raise the like-neighbour fraction from about 50 % to more than 75 %.

Time: about 60 min

1. Four Local Driver Rules & Backward-Moving Phantom Jam Waves

Kai Nagel and Michael Schreckenberg (1992) stripped highway driving down to a 1-D periodic ring of LL discrete cells (7.5 m7.5\ \mathrm{m} per cell) occupied by NN cars with integer speeds vi∈{0,1,…,vmax⁡}v_i \in \{0, 1, \dots, v_{\max}\}. At every synchronous tick t→t+1t \to t + 1, all drivers apply four 1-line rules simultaneously (emergence_verification.nagel_schreckenberg_traffic):

  1. Accelerate: vi←min⁡(vi+1, vmax⁡)v_i \leftarrow \min(v_i + 1,\, v_{\max}) (drivers want to reach speed limit).

  2. Brake for gap gig_i: vi←min⁡(vi, gi)v_i \leftarrow \min(v_i,\, g_i) where gi=(xi+1−xi−1) mod Lg_i = (x_{i+1} - x_i - 1) \bmod L (zero-collision invariant).

  3. Random human dawdling: With probability pslowp_{\mathrm{slow}}, if vi>0v_i > 0, vi←vi−1v_i \leftarrow v_i - 1 (hesitation / over-braking).

  4. Synchronous advance: xi←(xi+vi) mod Lx_i \leftarrow (x_i + v_i) \bmod L.

Why does a jam move backward? At the downstream front of a stopped queue, the lead car accelerates away only after seeing an empty cell ahead, releasing an empty hole backward by 1 cell per tick—while at the upstream tail, fast cars arrive at vmax⁡v_{\max} and slam on the brakes behind the last stopped car.


Demonstration 1: Nagel-Schreckenberg space-time diagrams — free flow against backward jam shockwaves
====================================================================================================
Free-flow  (rho=0.111): mean_v = 4.47, flow J = 0.496, stopped jam_frac = 0.64%
Congested  (rho=0.300): mean_v = 1.31, flow J = 0.394, stopped jam_frac = 42.84%
<Figure size 1265x473 with 2 Axes>

Figure 15.1. Space-time diagrams of the Nagel–Schreckenberg model, time running downward. (a) Free flow at ρ=0.11\rho = 0.11: cars move to the right in parallel streaks. (b) At ρ=0.30\rho = 0.30 bands of stopped cars (red) form and move to the left, against the traffic.

What Demonstration 1 shows. Time runs downward (t=0→140t = 0 \to 140) and cars drive rightward (xx increasing):

  • On the left (ρ=0.11\rho = 0.11), blue trajectories slant down-and-right with slope Δx/Δt≈4.5\Delta x / \Delta t \approx 4.5 cells per tick (mean speed 4.47) and only 0.64 %0.64\,\% of cars stopped.

  • On the right (ρ=0.30\rho = 0.30, with no accident and no bottleneck on the ring), small random dawdling fluctuations grow into bands of stopped cars (v == 0, 42.8 %42.8\,\% of the cars) that slant down and to the left: the jams travel upstream, against the traffic, and arise only from local over-braking.


2. The Macroscopic Fundamental Diagram J(ρ)=ρvˉ(ρ)J(\rho) = \rho \bar{v}(\rho) & Critical Capacity Breakdown

How many vehicles per tick J(ρ)=ρvˉ(ρ)J(\rho) = \rho \bar{v}(\rho) can a highway actually carry as vehicle density ρ=N/L∈[0,1]\rho = N / L \in [0, 1] increases?

  • In the deterministic limit (pslow=0p_{\mathrm{slow}} = 0), cars can cruise at full speed vmax⁡v_{\max} only if the average spacing 1/ρ−1≥vmax⁡1/\rho - 1 \ge v_{\max}, defining the critical capacity density:

ρc=1vmax⁡+1,Jdet(ρ)=min⁡ ⁣(ρ vmax⁡, 1−ρ)(2.1)\rho_c = \frac{1}{v_{\max} + 1}, \qquad J_{\mathrm{det}}(\rho) = \min\!\big(\rho\,v_{\max},\ 1 - \rho\big) \tag{2.1}
  • Once human reaction noise (pslow>0p_{\mathrm{slow}} > 0) is switched on, spontaneous phantom jams erode peak capacity well below Jmax⁡=vmax⁡vmax⁡+1J_{\max} = \frac{v_{\max}}{v_{\max} + 1} and shift breakdown to lower density.


Demonstration 2: Macroscopic fundamental diagram J(rho) — human dawdling against deterministic limit
====================================================================================================
Analytical deterministic peak at rho_c = 1/(v_max+1) = 0.1667: J_max = 0.8333 cars/step
Simulated peak throughput: Deterministic (p=0) = 0.8333 vs. Stochastic human (p=0.25) = 0.5393
<Figure size 1254x451 with 2 Axes>

Figure 15.2. Fundamental diagram. (a) Flow against density for the deterministic model (pslow=0p_{\mathrm{slow}} = 0), which follows min⁡(ρvmax⁡,1−ρ)\min(\rho v_{\max}, 1 - \rho), and with dawdling (pslow=0.25p_{\mathrm{slow}} = 0.25), whose peak is lower and at lower density. (b) Mean speed with dawdling.

What Demonstration 2 shows. In the deterministic limit the flow rises linearly up to ρc=0.167\rho_c = 0.167 and reaches Jmax⁡=0.833J_{\max} = 0.833; with dawdling (pslow=0.25p_{\mathrm{slow}} = 0.25) the peak falls to 0.539 and occurs at a lower density. Beyond the peak, more cars on the road means fewer cars arriving per unit time. This is the argument for ramp metering, which limits entry to keep the density near the peak of the curve.


3. Collective Flocking & Spontaneous Symmetry Breaking (vicsek_flocking_step_and_run)

Can NN self-propelled birds, fish, or autonomous drones with zero leader and zero global GPS map align into a single coherent flock using only short-range neighbor compasses? Tamás Vicsek et al. (1995) proposed updating each agent’s heading θi(t+1)\theta_i(t+1) to the circular vector average of neighbors within radius ralignr_{\mathrm{align}} plus uniform angular noise ξi∈[−η/2,+η/2]\xi_i \in [-\eta/2, +\eta/2]:

θi(t+1)=atan2⁡ ⁣(∑∥xj−xi∥≤rsin⁡θj(t), ∑∥xj−xi∥≤rcos⁡θj(t))+ξi(t)(3.1)\theta_i(t + 1) = \operatorname{atan2}\!\left(\sum_{\| \mathbf{x}_j - \mathbf{x}_i \| \le r} \sin\theta_j(t),\ \sum_{\| \mathbf{x}_j - \mathbf{x}_i \| \le r} \cos\theta_j(t)\right) + \xi_i(t) \tag{3.1}

Tracking the global polarization order parameter:

Φ(t)=1N∥∑i=1N[cos⁡θi(t)sin⁡θi(t)]∥2∈[0,1](3.2)\Phi(t) = \frac{1}{N}\left\|\sum_{i=1}^N \begin{bmatrix}\cos\theta_i(t) \\ \sin\theta_i(t)\end{bmatrix}\right\|_2 \in [0, 1] \tag{3.2}

reveals a kinetic ferromagnetic-style phase transition: at low noise η≪ηc\eta \ll \eta_c, Φ→1\Phi \to 1 (coherent flock); at high noise η→2π\eta \to 2\pi, Φ→O(1/N)\Phi \to \mathcal{O}(1/\sqrt{N}) (disordered gas).


Demonstration 3: Vicsek collective motion phase transition across angular noise eta
===================================================================================
Low noise  (eta=0.25 rad): final polarization Phi = 0.9972 (coherent flock)
High noise (eta=5.40 rad): final polarization Phi = 0.1674 (disordered; 1/sqrt(130) = 0.088)
<Figure size 1254x462 with 2 Axes>

Figure 15.3. Vicsek flocking with 130 agents. (a) Steady-state polarization against the angular noise η\eta; the dashed line is 1/N1/\sqrt{N}. (b) A snapshot at η=0.25\eta = 0.25, where the agents move together.

What Demonstration 3 shows. In equilibrium 2-D statistical mechanics, the Mermin–Wagner theorem (Mermin & Wagner 1966) forbids continuous O(2)O(2) rotational symmetry breaking at finite temperature on a fixed 2-D lattice. The theorem does not apply to Vicsek’s agents because they move (Toner & Tu 1995): each agent carries its heading to new neighbours, which keeps mixing the neighbourhoods and lets the whole flock settle on one heading. At η=0.25\eta = 0.25 the polarization reaches 0.997; at η=5.40\eta = 5.40 it is 0.17, about twice the value 1/N=0.0881/\sqrt{N} = 0.088 for independent random headings.


4. Decentralized Control: Eliminating Phantom Jams via Adaptive Cruise Control (pslow→0p_{\mathrm{slow}} \to 0)

Suppose a congested ring road operates above critical density (ρ=0.22>ρc=0.167\rho = 0.22 > \rho_c = 0.167). What happens if vehicle automation, for example adaptive cruise control (ACC), reduces the dawdling probability pslowp_{\mathrm{slow}} from 0.35 to 0? Modelling ACC as pslow=0p_{\mathrm{slow}} = 0 is an assumption of this lecture.


Demonstration 4: Dissolving phantom stop-and-go jams by reducing dawdling noise p_slow
======================================================================================
At rho = 0.22: Human p_slow=0.35 -> flow=0.400, stopped jam_frac=29.7%
               ACC   p_slow=0.00 -> flow=0.771, stopped jam_frac=2.55% (+92.8% capacity gain)
<Figure size 836x451 with 2 Axes>

Figure 15.4. Flow (blue, left axis) and fraction of stopped cars (red, right axis) at ρ=0.22\rho = 0.22 against the dawdling probability. Removing the dawdling raises the flow from 0.40 to 0.77 cars per tick.

Inside the algorithm

We inspect emergence_verification.nagel_schreckenberg_traffic and emergence_verification.vicsek_flocking_step_and_run side by side, and build a standalone verifier deterministic_fukui_ishibashi_limit showing that once the initial transient has relaxed in ≤L\le L ticks at pslow=0p_{\mathrm{slow}} = 0, the exact discrete cellular automaton settles onto the piecewise-linear Fukui-Ishibashi / Nagel-Schreckenberg analytical flow law J(ρ)=min⁡(ρvmax⁡, 1−ρ)J(\rho) = \min(\rho v_{\max},\, 1 - \rho) to machine precision.

Check against the library


Inside the algorithm: Traffic CA, Vicsek vector alignment and exact deterministic limit
=======================================================================================
def nagel_schreckenberg_traffic(
    road_length: int = 200,
    n_cars: int = 50,
    v_max: int = 5,
    p_slow: float = 0.25,
    n_steps: int = 160,
    seed: int = 42,
) -> dict:
    """Simulate Nagel-Schreckenberg 1-D periodic traffic cellular automaton generating phantom jam waves."""
    L = int(road_length)
    nc = int(n_cars)
    vm = int(v_max)
    if L < 4 or not (0 <= nc <= L) or vm < 1 or not (0.0 <= p_slow <= 1.0) or n_steps < 1:
        raise ValueError("Invalid traffic CA parameters.")

    spacetime = np.full((n_steps, L), -1, dtype=int)
    if nc == 0:
        return {"spacetime_grid": spacetime, "mean_velocity": 0.0, "fundamental_flow": 0.0, "jam_fraction": 0.0}

    rng = np.random.default_rng(seed)
    pos = np.sort(rng.choice(L, size=nc, replace=False))
    vel = np.minimum(vm, rng.integers(0, vm + 1, size=nc))
    v_sum = 0.0
    stopped_cnt = 0

    for step in range(n_steps):
        spacetime[step, pos] = vel
        v_sum += float(np.mean(vel))
        stopped_cnt += int(np.sum(vel == 0))

        # Distance gap to next car ahead on periodic ring:
        next_pos = np.roll(pos, -1)
        gaps = (next_pos - pos - 1) % L
        vel = np.minimum(vel + 1, vm)
        vel = np.minimum(vel, gaps)
        dawdle = (vel > 0) & (rng.random(nc) < float(p_slow))
        vel = np.where(dawdle, vel - 1, vel)
        pos = (pos + vel) % L
        order = np.argsort(pos)
        pos = pos[order]
        vel = vel[order]

    mean_v = v_sum / n_steps
    density = nc / float(L)
    return {
        "spacetime_grid": spacetime,
        "mean_velocity": mean_v,
        "fundamental_flow": density * mean_v,
        "jam_fraction": stopped_cnt / float(nc * n_steps),
    }

def vicsek_flocking_step_and_run(
    n_agents: int = 120,
    box_size: float = 10.0,
    r_align: float = 1.5,
    eta_noise: float = 0.3,
    speed: float = 0.25,
    n_steps: int = 80,
    seed: int = 42,
) -> dict:
    """Simulate 2-D periodic Vicsek collective motion and track polarization order parameter Phi(t) in [0, 1]."""
    if n_agents < 2 or box_size <= 0.0 or r_align <= 0.0 or eta_noise < 0.0 or speed <= 0.0 or n_steps < 1:
        raise ValueError("Invalid Vicsek flocking parameters.")
    rng = np.random.default_rng(seed)
    pos = rng.uniform(0.0, float(box_size), size=(n_agents, 2))
    theta = rng.uniform(-math.pi, math.pi, size=n_agents)
    order_hist = np.zeros(n_steps, dtype=float)
    r2 = float(r_align) ** 2
    L = float(box_size)

    for step in range(n_steps):
        vx = np.cos(theta)
        vy = np.sin(theta)
        order_hist[step] = float(math.hypot(float(np.sum(vx)), float(np.sum(vy))) / n_agents)

        # Minimum-image periodic pairwise alignment within r_align:
        dx = pos[:, None, 0] - pos[None, :, 0]
        dy = pos[:, None, 1] - pos[None, :, 1]
        dx -= L * np.round(dx / L)
        dy -= L * np.round(dy / L)
        mask = (dx * dx + dy * dy) <= r2
        avg_theta = np.arctan2(mask @ vy, mask @ vx)
        theta = avg_theta + rng.uniform(-0.5 * float(eta_noise), 0.5 * float(eta_noise), size=n_agents)
        pos[:, 0] = (pos[:, 0] + float(speed) * np.cos(theta)) % L
        pos[:, 1] = (pos[:, 1] + float(speed) * np.sin(theta)) % L

    return {
        "final_positions": pos,
        "final_angles": theta,
        "order_parameter_history": order_hist,
        "final_order_parameter": float(order_hist[-1]),
    }

Max |J_CA(p_slow=0) - min(rho*v_max, 1 - rho)| across 8 densities = 2.776e-17

Exercises

Worked solutions are in 15_solutions.ipynb. The cell below the list is a short self-check to start from.

  1. Verify a result. Verify the exact deterministic cellular-automaton flow law J(ρ)=min⁡(ρvmax⁡, 1−ρ)J(\rho) = \min(\rho v_{\max},\, 1 - \rho) at p_slow = 0.0, road_length = 200, and v_max = 4 across 15 densities ρ∈[0.05,0.95]\rho \in [0.05, 0.95] (n_cars = 10, 20, 30, 36, 40, ..., 190). Verify machine-precision agreement (atol = 1e-13) in steady state (t≥150t \ge 150), and verify particle-hole duality: for ρ≤ρc=0.20\rho \le \rho_c = 0.20, zero cars ever brake (gap >= v_max everywhere); for ρ≥ρc\rho \ge \rho_c, zero holes ever bunch (every empty cell advances backward by 1 cell/tick, so J=ρholes⋅1=1−ρJ = \rho_{\mathrm{holes}} \cdot 1 = 1 - \rho).

  2. Find how it fails. Audit two subtle bugs that ruin agent-based simulations: (a) Compare synchronous parallel updates (nagel_schreckenberg_traffic) against asynchronous in-place sequential car updates (pos[i] updated immediately inside for i in range(N)) at ρ=0.50\rho = 0.50, vmax⁡=4v_{\max} = 4, pslow=0p_{\mathrm{slow}} = 0, showing how sequential sweep order artificially inflates throughput above the physical 1−ρ=0.501 - \rho = 0.50 hole-conservation bound. (b) Compare circular vector atan2(sum sin, sum cos) against naive arithmetic mean(theta) on a westward-flying Vicsek flock (θ≈±π\theta \approx \pm\pi), showing how the −π/+π-\pi/+\pi branch cut reverses the flock and its mean velocity Φ\Phi.

  3. Implement it yourself. Implement Thomas Schelling’s (1971) Spatial Segregation Model schelling_segregation_emergence(L=36, tolerance_tau=0.35, vacancy_frac=0.12, max_sweeps=80, seed=42) in NumPy on an L×LL \times L grid with open boundaries (8-neighbor Moore stencil). An occupied cell is satisfied if it has zero occupied neighbors OR at least fraction tolerance_tau of its occupied neighbors share its own type (+1 or -1). Each sweep relocates all dissatisfied agents in random order into randomly chosen vacant cells (0). Prove that even at mild tolerance τ=0.35\tau = 0.35 (agents welcome up to 65%65\% unlike neighbors), the same-type neighbour similarity rises from about 50 %50\,\% to more than 75 %75\,\%.


Self-check for the exercises
============================
All checks passed.