Worked solutions to the three exercises of Lecture 15. Each solution is computed here and checked with assert statements against an exact identity or an independent calculation. The first code cell sets up the notebook and runs Demonstration 1 of the lecture without showing its output, because some of the solutions use its variables.
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))
# Demonstration 1 of the lecture, run without output: the solutions use its variables.
import contextlib, io
_show, plt.show = plt.show, lambda *args, **kwargs: None
_stdout = contextlib.redirect_stdout(io.StringIO()); _stdout.__enter__()
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()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Verify the exact deterministic cellular-automaton flow law at p_slow = 0.0, road_length = 200, and v_max = 4 across 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_max everywhere); for , zero holes ever bunch (every empty cell advances backward by 1 cell/tick, so ).
heading("Exercise 1: Exact 15-density verification of J(rho) = min(rho * v_max, 1 - rho) and particle-hole duality")
L_e1 = 200
vmax_e1 = 4
car_counts_15 = [10, 20, 30, 36, 40, 50, 64, 80, 96, 112, 128, 144, 160, 176, 190]
rhos_15 = np.array(car_counts_15, dtype=float) / L_e1
j_sim_15, j_ana_15 = [], []
for nc in car_counts_15:
res = emergence_verification.nagel_schreckenberg_traffic(
road_length=L_e1, n_cars=nc, v_max=vmax_e1, p_slow=0.0, n_steps=280, seed=1501
)
tail = res["spacetime_grid"][160:] # Steady-state 120 ticks
j_num = float(np.sum(tail[tail >= 0])) / float(120 * L_e1)
rho = nc / float(L_e1)
j_th = min(rho * vmax_e1, 1.0 - rho)
j_sim_15.append(j_num)
j_ana_15.append(j_th)
if rho <= 0.20 + 1e-12:
# Every car cruises at exact v_max = 4 in steady state
assert np.all(tail[tail >= 0] == vmax_e1)
j_sim_arr = np.array(j_sim_15)
j_ana_arr = np.array(j_ana_15)
max_err_15 = float(np.max(np.abs(j_sim_arr - j_ana_arr)))
print(f"Tested {len(rhos_15)} densities in [{rhos_15[0]:.2f}, {rhos_15[-1]:.2f}] at L={L_e1}, v_max={vmax_e1}, p_slow=0:")
print(f"Peak flow at critical density rho_c = 0.20: J_sim = {j_sim_arr[4]:.12f} vs. exact 4/5 = {j_ana_arr[4]:.12f}")
print(f"Maximum |J_sim - min(rho*v_max, 1 - rho)| across all 15 densities = {max_err_15:.3e}")
assert len(rhos_15) == 15 and max_err_15 < 1e-13
fig, ax = plt.subplots(figsize=(7.5, 4.1))
r_dense = np.linspace(0.0, 1.0, 300)
ax.plot(r_dense, np.minimum(r_dense * vmax_e1, 1.0 - r_dense), "k--", lw=2.0, label="Analytical $\\min(4\\rho,\\ 1 - \\rho)$")
ax.plot(rhos_15, j_sim_arr, "ro", ms=6.5, label="Steady-state CA simulation (15 densities)")
ax.axvline(0.20, color="#2166AC", ls=":", lw=1.6, label="Critical density $\\rho_c = 1/(v_{\\max}+1) = 0.20$")
ax.annotate("Free-flow branch:\n$J = v_{\\max}\\rho$ (car-limited)", xy=(0.10, 0.40), xytext=(0.22, 0.10),
arrowprops={"arrowstyle": "->", "lw": 1.2}, fontsize=8.5)
ax.annotate("Congested branch:\n$J = 1 - \\rho$ (hole-limited)", xy=(0.60, 0.40), xytext=(0.54, 0.64),
arrowprops={"arrowstyle": "->", "lw": 1.2}, fontsize=8.5)
ax.set_xlabel("Vehicle density $\\rho = N / L$")
ax.set_ylabel("Steady-state flow $J(\\rho)$ [cars/tick]")
ax.set_title("Deterministic flow against the exact law")
ax.legend(loc="center left", bbox_to_anchor=(1.01, 0.5), fontsize=8.3)
plt.show()
Exercise 1: Exact 15-density verification of J(rho) = min(rho * v_max, 1 - rho) and particle-hole duality
=========================================================================================================
Tested 15 densities in [0.05, 0.95] at L=200, v_max=4, p_slow=0:
Peak flow at critical density rho_c = 0.20: J_sim = 0.800000000000 vs. exact 4/5 = 0.800000000000
Maximum |J_sim - min(rho*v_max, 1 - rho)| across all 15 densities = 1.110e-16

Figure S15.1. Steady-state flow of the deterministic model at 15 densities (points) against (dashed), with the critical density 0.20 (dotted).
Explanation. When and , after transient relaxation no gap exceeds , so every car’s new speed equals its exact gap . That means car steps onto the exact cell right behind car ’s previous position—which is equivalent to every empty hole stepping backward by 1 cell per tick without blocking. Since hole density is and every hole shifts 1 cell per tick, exactly cars advance across any detector per tick: .
Exercise 2¶
Problem. 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 , , , showing how sequential sweep order artificially inflates throughput above the physical hole-conservation bound. (b) Compare circular vector atan2(sum sin, sum cos) against naive arithmetic mean(theta) on a westward-flying Vicsek flock (), showing how the branch cut reverses the flock and its mean velocity .
heading("Exercise 2: Asynchronous in-place traffic bug and branch-cut angle-averaging collapse")
# --- Part A: Synchronous vs. Asynchronous In-Place Traffic Update at rho = 0.50, p_slow = 0 ---
L_b, nc_b, vm_b = 120, 60, 4 # Exact synchronous maximum possible flow at rho=0.50 is 1 - rho = 0.50
sync_res = emergence_verification.nagel_schreckenberg_traffic(L_b, nc_b, vm_b, p_slow=0.0, n_steps=160, seed=7)
sync_flow = float(np.sum(sync_res["spacetime_grid"][80:][sync_res["spacetime_grid"][80:] >= 0])) / float(80 * L_b)
# Buggy in-place sequential update (updating from front-most car downward or index 0..N-1 in place):
pos_async = np.arange(0, L_b, 2, dtype=int) # Alternating car, empty, car, empty (gaps = 1 everywhere)
vel_async = np.ones(nc_b, dtype=int)
dist_async = 0
for step in range(160):
step_move = 0
# BUG: Updating cars in reverse index order (downstream car moves FIRST, opening extra gap in the SAME tick):
for i in range(nc_b - 1, -1, -1):
nxt_p = pos_async[(i + 1) % nc_b]
gap = (nxt_p - pos_async[i] - 1) % L_b
v_new = min(vel_async[i] + 1, vm_b, gap)
pos_async[i] = (pos_async[i] + v_new) % L_b
vel_async[i] = v_new
step_move += v_new
if step >= 80:
dist_async += step_move
async_flow = dist_async / float(80 * L_b)
print(f"[Part A] At rho = 0.50: Exact physical bound 1 - rho = 0.5000 | Synchronous CA = {sync_flow:.4f} | Buggy In-Place Async = {async_flow:.4f} (unphysical, > 0.50)")
assert np.isclose(sync_flow, 0.50, atol=1e-12) and async_flow > 0.90
# --- Part B: Circular atan2(sum sin, sum cos) vs. Naive Arithmetic mean(theta) Across +-pi Branch Cut ---
two_west = np.deg2rad(np.array([-179.0, +179.0]))
naive_mean_deg = float(np.rad2deg(np.mean(two_west)))
vec_mean_deg = float(np.rad2deg(math.atan2(float(np.sum(np.sin(two_west))), float(np.sum(np.cos(two_west))))))
print(f"[Part B] Two westward drones [-179 deg, +179 deg]: Naive mean = {naive_mean_deg:+.1f} deg (east, backward) vs. atan2 vector mean = {vec_mean_deg:+.1f} deg (west)")
assert abs(naive_mean_deg) < 1e-12 and abs(abs(vec_mean_deg) - 180.0) < 1e-12
# Simulate 80 drones initialized heading West (theta ~ pi +- 0.15 rad) under Vector vs. Naive Arithmetic alignment:
def run_westward_flock(use_vector_mean: bool, n_steps: int = 40, seed: int = 1502) -> tuple[np.ndarray, np.ndarray]:
rng = np.random.default_rng(seed)
n_ag, box, r_al, eta, spd = 80, 8.0, 1.6, 0.20, 0.25
pos = rng.uniform(0.0, box, size=(n_ag, 2))
# Initialize heading West around +-pi (wrapped into [-pi, pi)):
theta = ((math.pi + rng.uniform(-0.18, 0.18, size=n_ag) + math.pi) % (2.0 * math.pi)) - math.pi
vx_hist = np.zeros(n_steps)
phi_hist = np.zeros(n_steps)
for t in range(n_steps):
vx, vy = np.cos(theta), np.sin(theta)
vx_hist[t] = float(np.mean(vx)) # True initial flock velocity is -0.99 (West)
phi_hist[t] = math.hypot(float(np.sum(vx)), float(np.sum(vy))) / n_ag
dx = pos[:, None, 0] - pos[None, :, 0]
dy = pos[:, None, 1] - pos[None, :, 1]
dx -= box * np.round(dx / box)
dy -= box * np.round(dy / box)
mask = (dx * dx + dy * dy) <= r_al ** 2
if use_vector_mean:
avg_th = np.arctan2(mask @ vy, mask @ vx)
else:
# BUG: Arithmetic average of wrapped [-pi, pi) angles flips (-pi, +pi) neighbors to 0 (DUE EAST)
avg_th = (mask @ theta) / np.sum(mask, axis=1)
theta = avg_th + rng.uniform(-0.5 * eta, 0.5 * eta, size=n_ag)
theta = ((theta + math.pi) % (2.0 * math.pi)) - math.pi
pos[:, 0] = (pos[:, 0] + spd * np.cos(theta)) % box
pos[:, 1] = (pos[:, 1] + spd * np.sin(theta)) % box
return vx_hist, phi_hist
vx_vec_ok, phi_vec_ok = run_westward_flock(use_vector_mean=True)
vx_arith_bug, phi_arith_bug = run_westward_flock(use_vector_mean=False)
print(f"Westward flock mean v_x (initial = {vx_vec_ok[0]:+.3f} West): Vector atan2 = {vx_vec_ok[-1]:+.3f} (stays West) vs. Arithmetic mean = {vx_arith_bug[-1]:+.3f} (reversed, 180 deg east)")
assert vx_vec_ok[0] < -0.95 and vx_vec_ok[-1] < -0.90
assert vx_arith_bug[-1] > +0.85 # Entire flock flipped 180 degrees backward to East
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.0))
ax1.bar(["Physical limit\n$1 - \\rho$", "Synchronous CA\n(correct)", "In-place update\n(sequential bug)"],
[0.50, sync_flow, async_flow], color=["#2E8B57", "#2166AC", "#C0392B"], edgecolor="k", width=0.52)
ax1.set_ylabel("Steady-state flow $J$ at $\\rho = 0.50$")
ax1.set_title("In-place updates exceed the flow limit")
t_fl = np.arange(vx_vec_ok.size)
ax2.plot(t_fl, vx_vec_ok, "b-o", ms=3.5, lw=2.1, label="Vector mean (atan2): stays west ($\\bar{v}_x \\approx -1$)")
ax2.plot(t_fl, vx_arith_bug, "r-s", ms=3.5, lw=2.0, label="Mean of angles: flips east ($\\bar{v}_x \\to +1$)")
ax2.axhline(0.0, color="k", ls=":", lw=1.2)
ax2.set_xlabel("Time step $t$")
ax2.set_ylabel("Mean east-west velocity $\\bar{v}_x(t)$")
ax2.set_title("Mean of angles across the branch cut")
ax2.legend(loc="upper center", bbox_to_anchor=(0.5, -0.14), ncol=1, fontsize=8.2)
label_panels(fig)
plt.show()
Exercise 2: Asynchronous in-place traffic bug and branch-cut angle-averaging collapse
=====================================================================================
[Part A] At rho = 0.50: Exact physical bound 1 - rho = 0.5000 | Synchronous CA = 0.5000 | Buggy In-Place Async = 2.0000 (unphysical, > 0.50)
[Part B] Two westward drones [-179 deg, +179 deg]: Naive mean = +0.0 deg (east, backward) vs. atan2 vector mean = +180.0 deg (west)
Westward flock mean v_x (initial = -0.994 West): Vector atan2 = -0.997 (stays West) vs. Arithmetic mean = +0.955 (reversed, 180 deg east)

Figure S15.2. Two simulation bugs. (a) Flow at : the in-place update gives 2.0, four times the physical limit . (b) East–west velocity of a westward flock: the circular mean keeps it at -1, the arithmetic mean of the angles reverses it.
Explanation. (a) In cellular automata and stencil PDEs, updating array entries in-place turns a discrete-time synchronous law into a sweep-direction-dependent Gauss-Seidel cascade in which a car can move into a cell freed in the same time step, so empty space travels upstream without delay. (b) Angles live on the circle , not the real line : atan2(sum(sin), sum(cos)) embeds headings on the unit circle where average cleanly to independently of where the branch cut lies.
Exercise 3¶
Problem. 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 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 (agents welcome up to unlike neighbors), the same-type neighbour similarity rises from about to more than .
heading("Exercise 3: Implement it yourself — Schelling's tipping-point segregation emergence")
def schelling_segregation_emergence(
L: int = 36,
tolerance_tau: float = 0.35,
vacancy_frac: float = 0.12,
max_sweeps: int = 80,
seed: int = 42,
) -> dict:
"""Simulate Thomas Schelling's (1971) 2-D lattice segregation dynamics in pure NumPy."""
rng = np.random.default_rng(seed)
n_tot = L * L
n_vac = int(round(vacancy_frac * n_tot))
n_occ = n_tot - n_vac
n_a = n_occ // 2
n_b = n_occ - n_a
flat = np.array([0] * n_vac + [1] * n_a + [-1] * n_b, dtype=int)
rng.shuffle(flat)
grid = flat.reshape((L, L))
init_grid = grid.copy()
offsets = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
def _metrics_and_unhappy(g: np.ndarray) -> tuple[float, list[tuple[int, int]]]:
same_sum = 0
tot_nbr_pairs = 0
unhappy: list[tuple[int, int]] = []
for r in range(L):
for c in range(L):
val = int(g[r, c])
if val == 0:
continue
same = 0
occ_n = 0
for dr, dc in offsets:
nr, nc = r + dr, c + dc
if 0 <= nr < L and 0 <= nc < L and g[nr, nc] != 0:
occ_n += 1
if g[nr, nc] == val:
same += 1
same_sum += same
tot_nbr_pairs += occ_n
if occ_n > 0 and (same / float(occ_n)) < tolerance_tau - 1e-12:
unhappy.append((r, c))
sim = (same_sum / float(tot_nbr_pairs)) if tot_nbr_pairs > 0 else 1.0
return sim, unhappy
sim_hist: list[float] = []
unhappy_hist: list[int] = []
for _ in range(max_sweeps):
sim_now, unh = _metrics_and_unhappy(grid)
sim_hist.append(sim_now)
unhappy_hist.append(len(unh))
if not unh:
break
rng.shuffle(unh)
vacant_rc = [(int(r), int(c)) for r, c in np.argwhere(grid == 0)]
for r_old, c_old in unh:
idx_v = int(rng.integers(0, len(vacant_rc)))
r_new, c_new = vacant_rc[idx_v]
grid[r_new, c_new] = grid[r_old, c_old]
grid[r_old, c_old] = 0
vacant_rc[idx_v] = (r_old, c_old)
final_sim, final_unh = _metrics_and_unhappy(grid)
sim_hist.append(final_sim)
unhappy_hist.append(len(final_unh))
return {
"initial_grid": init_grid,
"final_grid": grid,
"initial_similarity": sim_hist[0],
"final_similarity": final_sim,
"similarity_history": np.array(sim_hist),
"unhappy_history": np.array(unhappy_hist),
}
sch_35 = schelling_segregation_emergence(L=36, tolerance_tau=0.35)
# Also sweep tolerance_tau in [0.15, 0.25, 0.35, 0.45, 0.55, 0.65] to reveal Schelling's tipping point:
taus = [0.15, 0.25, 0.35, 0.45, 0.55, 0.65]
final_sims = [100.0 * schelling_segregation_emergence(L=30, tolerance_tau=tv, seed=99)["final_similarity"] for tv in taus]
print("Schelling L=36, tau=0.35 (happy with 65% unlike neighbors):")
print(f" Initial mixed similarity = {100*sch_35['initial_similarity']:.1f}% -> Final segregated similarity = {100*sch_35['final_similarity']:.1f}% (unhappy left = {sch_35['unhappy_history'][-1]})")
assert 0.46 < sch_35["initial_similarity"] < 0.54
assert sch_35["final_similarity"] > 0.76 and sch_35["unhappy_history"][-1] == 0
assert final_sims[2] > final_sims[0] + 20.0
fig, axes = plt.subplot_mosaic([["a", "b"], ["c", "c"]], figsize=(8.4, 8.0))
axes = [axes["a"], axes["b"], axes["c"]]
from matplotlib.colors import ListedColormap
cmap_sch = ListedColormap(["#2166AC", "#F4F6F7", "#E08214"])
axes[0].imshow(sch_35["initial_grid"], cmap=cmap_sch, vmin=-1, vmax=1, interpolation="nearest")
axes[0].grid(False); axes[0].set_xticks([]); axes[0].set_yticks([])
axes[0].set_title(f"Initial random mix\n(same-type neighbours = {100*sch_35['initial_similarity']:.1f}%)")
axes[1].imshow(sch_35["final_grid"], cmap=cmap_sch, vmin=-1, vmax=1, interpolation="nearest")
axes[1].grid(False); axes[1].set_xticks([]); axes[1].set_yticks([])
axes[1].set_title(f"Equilibrium at $\\tau = 0.35$\n(same-type neighbours = {100*sch_35['final_similarity']:.1f}%)")
axes[2].plot([100 * tv for tv in taus], final_sims, "r-o", ms=6, lw=2.2, label="Macroscopic segregation [%]")
axes[2].plot([100 * tv for tv in taus], [100 * tv for tv in taus], "k--", lw=1.5, label="Individual desire line $y = \\tau$")
axes[2].set_xlabel("Microscopic tolerance threshold $\\tau$ [%]")
axes[2].set_ylabel("Final same-type neighbor share [%]")
axes[2].set_title("Final like-neighbour share against tolerance")
axes[2].legend(fontsize=8.0)
label_panels(fig)
plt.show()
Exercise 3: Implement it yourself — Schelling's tipping-point segregation emergence
===================================================================================
Schelling L=36, tau=0.35 (happy with 65% unlike neighbors):
Initial mixed similarity = 49.1% -> Final segregated similarity = 77.7% (unhappy left = 0)

Figure S15.3. Schelling’s model on a 36 × 36 grid. (a) The initial random mix. (b) The equilibrium at . (c) Final like-neighbour share against the tolerance , always well above itself (dashed).
Summary. The similarity rises from to although each agent is content with like neighbours, so a strongly segregated pattern (or a phase-separated alloy) does not imply that the individuals sought homogeneity. When an agent leaves a borderline cell, it lowers the like-neighbour fraction of the neighbours left behind, which can make them move as well; the moves continue until broad domains with thin interfaces have formed.