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 showing capacity breakdown past , explore Vicsek’s (1995) self-propelled flocking transition (emergence_verification.vicsek_flocking_step_and_run), show how, in the model, removing the random braking (, a stand-in for adaptive cruise control) dissolves the jams, and implement Thomas Schelling’s (1971) segregation lattice.
Learning objectives¶
Simulate 1-D Nagel-Schreckenberg traffic cellular automata (
emergence_verification.nagel_schreckenberg_traffic) and explain why macroscopic jam fronts propagate backward () while microscopic car velocities stay non-negative.Construct the macroscopic Fundamental Diagram and prove analytically why deterministic capacity peaks at with .
Track collective polarization across angular noise in 2-D Vicsek flocking (
emergence_verification.vicsek_flocking_step_and_run) and audit circular angle-averaging vs. asynchronous update bugs.Implement Schelling’s tipping-point lattice model to quantify how mild local preferences () raise the like-neighbour fraction from about 50 % to more than 75 %.
Time: about 60 min
try: # use the installed package, or the copy in this repository
import engthink
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engthink" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engthink.git"], check=True)
import engthink
import inspect
import math
import numpy as np
import matplotlib.pyplot as plt
from engthink import (constants_benchmarks, divide_spatial, dynamic_optimality, emergence_verification,
greedy_heuristic_search, information_streams, invariants_complexity, reductions_constraints,
representation_scaling)
from engthink.plotting import label_panels, log_ticks, panel_label, use_style
use_style()
def show_source(obj):
"""Return the source code of a library function or class."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))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 discrete cells ( per cell) occupied by cars with integer speeds . At every synchronous tick , all drivers apply four 1-line rules simultaneously (emergence_verification.nagel_schreckenberg_traffic):
Accelerate: (drivers want to reach speed limit).
Brake for gap : where (zero-collision invariant).
Random human dawdling: With probability , if , (hesitation / over-braking).
Synchronous advance: .
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 and slam on the brakes behind the last stopped car.
heading("Demonstration 1: Nagel-Schreckenberg space-time diagrams — free flow against backward jam shockwaves")
L_road = 180
n_steps_tr = 140
v_lim = 5
free_run = emergence_verification.nagel_schreckenberg_traffic(
road_length=L_road, n_cars=20, v_max=v_lim, p_slow=0.25, n_steps=n_steps_tr, seed=42
)
jam_run = emergence_verification.nagel_schreckenberg_traffic(
road_length=L_road, n_cars=54, v_max=v_lim, p_slow=0.28, n_steps=n_steps_tr, seed=42
)
print(f"Free-flow (rho={20/L_road:.3f}): mean_v = {free_run['mean_velocity']:.2f}, flow J = {free_run['fundamental_flow']:.3f}, stopped jam_frac = {100*free_run['jam_fraction']:.2f}%")
print(f"Congested (rho={54/L_road:.3f}): mean_v = {jam_run['mean_velocity']:.2f}, flow J = {jam_run['fundamental_flow']:.3f}, stopped jam_frac = {100*jam_run['jam_fraction']:.2f}%")
# Verify exact car-count conservation in every single row of spacetime_grid:
assert np.all(np.sum(free_run["spacetime_grid"] >= 0, axis=1) == 20)
assert np.all(np.sum(jam_run["spacetime_grid"] >= 0, axis=1) == 54)
assert free_run["mean_velocity"] > 4.2 and jam_run["jam_fraction"] > 0.12
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.5, 4.3))
for ax, st_grid, ttl in [
(ax1, free_run["spacetime_grid"], "Free flow ($\\rho = 0.11$)"),
(ax2, jam_run["spacetime_grid"], "Jams move backward ($\\rho = 0.30$)"),
]:
# Map empty road (-1) to white, stopped cars (0) to crimson/black, fast cars (5) to bright green/blue:
rgb = np.ones((n_steps_tr, L_road, 3), dtype=float)
occ = st_grid >= 0
stopped = st_grid == 0
moving = st_grid > 0
rgb[moving] = [0.129, 0.400, 0.675]
rgb[stopped] = [0.753, 0.224, 0.169]
ax.imshow(rgb, aspect="auto", interpolation="nearest")
ax.grid(False)
ax.set_xlabel("Highway ring position $x$ [cells, cars drive $\\rightarrow$]")
ax.set_ylabel("Time step $t$ [ticks $\\downarrow$]")
ax.set_title(ttl, fontsize=9.6)
label_panels(fig)
plt.show()
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 15.1. Space-time diagrams of the Nagel–Schreckenberg model, time running downward. (a) Free flow at : cars move to the right in parallel streaks. (b) At bands of stopped cars (red) form and move to the left, against the traffic.
What Demonstration 1 shows. Time runs downward () and cars drive rightward ( increasing):
On the left (), blue trajectories slant down-and-right with slope cells per tick (mean speed 4.47) and only of cars stopped.
On the right (, with no accident and no bottleneck on the ring), small random dawdling fluctuations grow into bands of stopped cars (
v == 0, 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 & Critical Capacity Breakdown¶
How many vehicles per tick can a highway actually carry as vehicle density increases?
In the deterministic limit (), cars can cruise at full speed only if the average spacing , defining the critical capacity density:
Once human reaction noise () is switched on, spontaneous phantom jams erode peak capacity well below and shift breakdown to lower density.
heading("Demonstration 2: Macroscopic fundamental diagram J(rho) — human dawdling against deterministic limit")
L_fd = 240
v_fd = 5
rho_c_det = 1.0 / (v_fd + 1.0)
n_cars_grid = np.array([6, 16, 28, 36, 40, 48, 60, 76, 92, 108, 124, 140, 156, 172, 188, 204, 216, 228])
densities = n_cars_grid / float(L_fd)
flow_human, flow_det, vmean_human = [], [], []
for nc in n_cars_grid:
# Run 220 steps; use steady-state second half via spacetime_grid[100:]
r_hum = emergence_verification.nagel_schreckenberg_traffic(L_fd, int(nc), v_fd, p_slow=0.25, n_steps=220, seed=71)
r_det = emergence_verification.nagel_schreckenberg_traffic(L_fd, int(nc), v_fd, p_slow=0.00, n_steps=220, seed=71)
st_h = r_hum["spacetime_grid"][100:]
st_d = r_det["spacetime_grid"][100:]
vh = float(np.sum(st_h[st_h >= 0])) / float(120 * nc)
vd = float(np.sum(st_d[st_d >= 0])) / float(120 * nc)
rho = nc / float(L_fd)
flow_human.append(rho * vh)
flow_det.append(rho * vd)
vmean_human.append(vh)
rho_fine = np.linspace(0.0, 1.0, 201)
j_theory = np.minimum(rho_fine * v_fd, 1.0 - rho_fine)
print(f"Analytical deterministic peak at rho_c = 1/(v_max+1) = {rho_c_det:.4f}: J_max = {v_fd/(v_fd+1):.4f} cars/step")
print(f"Simulated peak throughput: Deterministic (p=0) = {max(flow_det):.4f} vs. Stochastic human (p=0.25) = {max(flow_human):.4f}")
assert np.allclose(flow_det, np.minimum(densities * v_fd, 1.0 - densities), atol=1e-3)
assert max(flow_det) > 1.38 * max(flow_human)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.1))
ax1.plot(rho_fine, j_theory, "k--", lw=1.9, label="Exact $p_{\\mathrm{slow}}=0$: $\\min(\\rho v_{\\max}, 1-\\rho)$")
ax1.plot(densities, flow_det, "g-o", ms=4.5, lw=1.8, label="Simulated CA ($p_{\\mathrm{slow}} = 0.00$)")
ax1.plot(densities, flow_human, "r-s", ms=5, lw=2.2, label="Human traffic ($p_{\\mathrm{slow}} = 0.25$)")
ax1.axvline(rho_c_det, color="gray", ls=":", lw=1.5, label=f"$\\rho_c = 1/6 \\approx {rho_c_det:.3f}$")
ax1.set_xlabel("Vehicle density $\\rho = N / L$")
ax1.set_ylabel("Highway throughput $J(\\rho) = \\rho \\bar{v}$ [cars/tick]")
ax1.set_title("Fundamental diagram")
ax1.legend(fontsize=8.0)
ax2.plot(densities, vmean_human, "b-^", ms=5, lw=2.1, label="Mean speed $\\bar{v}(\\rho)$ ($p_{\\mathrm{slow}}=0.25$)")
ax2.axvline(rho_c_det, color="gray", ls=":", lw=1.5, label="Free-flow $\\to$ jam transition")
ax2.set_xlabel("Vehicle density $\\rho = N / L$")
ax2.set_ylabel("Mean vehicle velocity $\\bar{v}$ [cells/tick]")
ax2.set_title("Mean speed with dawdling")
ax2.legend(fontsize=8.2)
label_panels(fig)
plt.show()
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 15.2. Fundamental diagram. (a) Flow against density for the deterministic model (), which follows , and with dawdling (), 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 and reaches ; with dawdling () 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 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 to the circular vector average of neighbors within radius plus uniform angular noise :
Tracking the global polarization order parameter:
reveals a kinetic ferromagnetic-style phase transition: at low noise , (coherent flock); at high noise , (disordered gas).
heading("Demonstration 3: Vicsek collective motion phase transition across angular noise eta")
eta_grid = np.linspace(0.15, 5.6, 12)
phi_steady = []
for ev in eta_grid:
phi_runs = []
for sd in (11, 22, 33):
vr = emergence_verification.vicsek_flocking_step_and_run(
n_agents=130, box_size=10.0, r_align=1.6, eta_noise=float(ev), speed=0.25, n_steps=95, seed=sd
)
phi_runs.append(float(np.mean(vr["order_parameter_history"][-25:])))
phi_steady.append(float(np.mean(phi_runs)))
low_noise_flock = emergence_verification.vicsek_flocking_step_and_run(
n_agents=130, box_size=10.0, r_align=1.6, eta_noise=0.25, speed=0.25, n_steps=95, seed=42
)
high_noise_gas = emergence_verification.vicsek_flocking_step_and_run(
n_agents=130, box_size=10.0, r_align=1.6, eta_noise=5.40, speed=0.25, n_steps=95, seed=42
)
print(f"Low noise (eta=0.25 rad): final polarization Phi = {low_noise_flock['final_order_parameter']:.4f} (coherent flock)")
print(f"High noise (eta=5.40 rad): final polarization Phi = {high_noise_gas['final_order_parameter']:.4f} (disordered; 1/sqrt(130) = {1/math.sqrt(130):.3f})")
assert low_noise_flock["final_order_parameter"] > 0.92
assert high_noise_gas["final_order_parameter"] < 0.22
assert phi_steady[0] > 0.92 and phi_steady[-1] < 0.18
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.2))
ax1.plot(eta_grid, phi_steady, "b-o", ms=5.5, lw=2.2, label="Steady-state polarization $\\Phi(\\eta)$")
ax1.axhline(1.0 / math.sqrt(130), color="gray", ls="--", lw=1.4, label="Random-walk floor $1/\\sqrt{N} \\approx 0.088$")
ax1.set_xlabel("Angular noise amplitude $\\eta$ [rad]")
ax1.set_ylabel("Collective order parameter $\\Phi \\in [0, 1]$")
ax1.set_title("Polarization against noise")
ax1.legend(fontsize=8.2)
p_lo = low_noise_flock["final_positions"]
ang_lo = low_noise_flock["final_angles"]
ax2.quiver(p_lo[:, 0], p_lo[:, 1], np.cos(ang_lo), np.sin(ang_lo), color="#2166AC", scale=22, width=0.005)
ax2.set_xlim(0.0, 10.0)
ax2.set_ylim(0.0, 10.0)
ax2.set_xlabel("$x$ [periodic box]")
ax2.set_ylabel("$y$ [periodic box]")
ax2.set_title(f"Flocking snapshot ($\\eta=0.25,\\ \\Phi={low_noise_flock['final_order_parameter']:.3f}$)")
label_panels(fig)
plt.show()
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 15.3. Vicsek flocking with 130 agents. (a) Steady-state polarization against the angular noise ; the dashed line is . (b) A snapshot at , where the agents move together.
What Demonstration 3 shows. In equilibrium 2-D statistical mechanics, the Mermin–Wagner theorem (Mermin & Wagner 1966) forbids continuous 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 the polarization reaches 0.997; at it is 0.17, about twice the value for independent random headings.
4. Decentralized Control: Eliminating Phantom Jams via Adaptive Cruise Control ()¶
Suppose a congested ring road operates above critical density (). What happens if vehicle automation, for example adaptive cruise control (ACC), reduces the dawdling probability from 0.35 to 0? Modelling ACC as is an assumption of this lecture.
heading("Demonstration 4: Dissolving phantom stop-and-go jams by reducing dawdling noise p_slow")
pslow_sweep = np.linspace(0.0, 0.45, 10)
flows_acc, jams_acc = [], []
for ps in pslow_sweep:
f_list, j_list = [], []
for sd in (10, 20, 30):
res_ps = emergence_verification.nagel_schreckenberg_traffic(
road_length=200, n_cars=44, v_max=5, p_slow=float(ps), n_steps=200, seed=sd
)
f_list.append(res_ps["fundamental_flow"])
j_list.append(100.0 * res_ps["jam_fraction"])
flows_acc.append(float(np.mean(f_list)))
jams_acc.append(float(np.mean(j_list)))
print(f"At rho = 0.22: Human p_slow=0.35 -> flow={flows_acc[7]:.3f}, stopped jam_frac={jams_acc[7]:.1f}%")
print(f" ACC p_slow=0.00 -> flow={flows_acc[0]:.3f}, stopped jam_frac={jams_acc[0]:.2f}% (+{100*(flows_acc[0]/flows_acc[7]-1):.1f}% capacity gain)")
assert flows_acc[0] > 1.50 * flows_acc[-1]
assert jams_acc[0] < 3.5 and jams_acc[-1] > 18.0
fig, ax1 = plt.subplots(figsize=(7.6, 4.1))
ax2 = ax1.twinx()
ax2.spines["top"].set_visible(False)
ax1.plot(pslow_sweep, flows_acc, "b-o", ms=5.5, lw=2.2, label="Highway throughput $J$ [cars/tick]")
ax2.plot(pslow_sweep, jams_acc, "r-s", ms=5.5, lw=2.2, label="Stopped-car jam fraction [%]")
ax1.set_xlabel("Microscopic dawdling probability $p_{\\mathrm{slow}}$")
ax1.set_ylabel("Macroscopic flow $J$ [cars/tick]", color="#2166AC")
ax2.set_ylabel("Stopped vehicles ($v = 0$) [%]", color="#C0392B")
ax1.set_title("Flow and stopped cars against dawdling at $\\rho = 0.22$")
plt.show()
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 15.4. Flow (blue, left axis) and fraction of stopped cars (red, right axis) at 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 ticks at , the exact discrete cellular automaton settles onto the piecewise-linear Fukui-Ishibashi / Nagel-Schreckenberg analytical flow law to machine precision.
Check against the library¶
heading("Inside the algorithm: Traffic CA, Vicsek vector alignment and exact deterministic limit")
print(show_source(emergence_verification.nagel_schreckenberg_traffic))
print(show_source(emergence_verification.vicsek_flocking_step_and_run))
def deterministic_fukui_ishibashi_limit(road_length: int, car_counts: list[int], v_max: int = 4) -> dict:
"""Verify exact post-transient steady-state flow J(rho) == min(rho * v_max, 1 - rho) at p_slow = 0."""
L = int(road_length)
sim_flows = []
exact_flows = []
for nc in car_counts:
res = emergence_verification.nagel_schreckenberg_traffic(
road_length=L, n_cars=int(nc), v_max=v_max, p_slow=0.0, n_steps=260, seed=123
)
# Post-transient window (last 100 steps):
tail = res["spacetime_grid"][-100:]
total_dist = int(np.sum(tail[tail >= 0]))
j_sim = total_dist / float(100 * L)
rho = nc / float(L)
j_ex = min(rho * v_max, 1.0 - rho)
sim_flows.append(j_sim)
exact_flows.append(j_ex)
max_err = float(np.max(np.abs(np.array(sim_flows) - np.array(exact_flows))))
return {"sim_flows": np.array(sim_flows), "exact_flows": np.array(exact_flows), "max_abs_error": max_err}
chk_det = deterministic_fukui_ishibashi_limit(road_length=120, car_counts=[6, 12, 18, 24, 36, 60, 90, 108], v_max=4)
print(f"Max |J_CA(p_slow=0) - min(rho*v_max, 1 - rho)| across 8 densities = {chk_det['max_abs_error']:.3e}")
assert chk_det["max_abs_error"] < 1e-13
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.
Verify a result. Verify the exact deterministic cellular-automaton flow law at
p_slow = 0.0,road_length = 200, andv_max = 4across 15 densities (n_cars = 10, 20, 30, 36, 40, ..., 190). Verify machine-precision agreement (atol = 1e-13) in steady state (), and verify particle-hole duality: for , zero cars ever brake (gap >= v_maxeverywhere); for , zero holes ever bunch (every empty cell advances backward by 1 cell/tick, so ).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 insidefor i in range(N)) at , , , showing how sequential sweep order artificially inflates throughput above the physical hole-conservation bound. (b) Compare circular vectoratan2(sum sin, sum cos)against naive arithmeticmean(theta)on a westward-flying Vicsek flock (), showing how the branch cut reverses the flock and its mean velocity .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 grid with open boundaries (8-neighbor Moore stencil). An occupied cell is satisfied if it has zero occupied neighbors OR at least fractiontolerance_tauof its occupied neighbors share its own type (+1or-1). Each sweep relocates all dissatisfied agents in random order into randomly chosen vacant cells (0). Prove that even at mild tolerance (agents welcome up to unlike neighbors), the same-type neighbour similarity rises from about to more than .
heading("Self-check for the exercises")
assert free_run["mean_velocity"] > 4.2 and jam_run["jam_fraction"] > 0.12, "Traffic free/jam regime check failed"
assert max(flow_det) > 1.38 * max(flow_human), "Fundamental diagram capacity breakdown check failed"
assert low_noise_flock["final_order_parameter"] > 0.92 and high_noise_gas["final_order_parameter"] < 0.22, "Vicsek transition check failed"
assert chk_det["max_abs_error"] < 1e-13, "Deterministic Fukui-Ishibashi flow law check failed"
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.