3 · Drive the Black Car
A game: one careful driver against a phantom jam. Can you smooth traffic for all 22 cars?
The ring road has jammed: 22 cars, stop and go, with no bottleneck anywhere. You take the wheel of one car. Can one driver dissolve the jam for everyone?
NoteBefore you play: predict
To smooth the jam, should your car drive faster than the others, or slower? And will everyone’s average speed go up or down?
Your turn: be the smart car
Dissolve the jam, and beat the jam’s average speed.
viewof gameOn = flip("🚗 Take the wheel", "✋ Let go")
viewof gameV = knob({min: 1, max: 6, step: 0.25, value: 6, label: "My cruising speed", format: v => `${v.toFixed(2)} m/s`})
viewof gameReset = action("↻ Restart")
viewof gamePause = pauser()
// the best jam-free average of this visit: kept across restarts
gameBest = ({value: null})
gameState = { gameReset; return {hist: [], L: 230}; }// The ring road again. Car 0 is yours: when you drive, it holds your speed smoothly (gain 0.1 per second, no wobble)
// but never accelerates more than the Intelligent Driver Model allows, so it cannot hit the car ahead.
// You win when the jam meter (the spread of all 22 speeds) stays under 0.8 m/s for 30 simulated seconds;
// your score is everyone's average speed over those 30 s, against the jam's average before you took over.
game = {
const S = gameState, N = 22, L = S.L, v0 = 12, T = 1.2, s0 = 2, a = 0.5, b = 1.5, lc = 4, dt = 0.1, noise = 0.3;
let lo = 0, hi = v0; // start at the uniform equilibrium speed, as on the ring above
for (let k = 0; k < 60; k++) { const m = (lo + hi) / 2; if ((s0 + m * T) / Math.sqrt(1 - (m / v0) ** 4) < L / N - lc) lo = m; else hi = m; }
const x = Float64Array.from({length: N}, (_, i) => i * L / N), v = new Float64Array(N).fill(lo), acc = new Float64Array(N);
const randn = () => Math.sqrt(-2 * Math.log(1 - Math.random())) * Math.cos(2 * Math.PI * Math.random());
let t = 0, nextRecord = 0;
const step = mine => {
for (let i = 0; i < N; i++) {
const j = (i + 1) % N, gap = Math.max(((x[j] - x[i]) % L + L) % L - lc, 0.1);
const sStar = s0 + Math.max(0, v[i] * T + v[i] * (v[i] - v[j]) / (2 * Math.sqrt(a * b)));
const idm = a * (1 - (v[i] / v0) ** 4 - (sStar / gap) ** 2);
acc[i] = i === 0 && mine !== null ? Math.min(idm, 0.1 * (mine - v[i])) : idm + noise * randn();
}
for (let i = 0; i < N; i++) { v[i] = Math.max(0, v[i] + acc[i] * dt); x[i] = (x[i] + v[i] * dt) % L; }
t += dt;
};
let jamSum = 0, jamN = 0;
for (let k = 0; k < 3000; k++) { step(null); if (k >= 2000) { jamSum += d3.mean(v); jamN++; } } // 300 s warm-up: the jam forms
const jamAvg = jamSum / jamN, t0 = t;
let clean = 0, startAt = null, lastMine = null, wonAt = null, score = null, snap = null;
const recent = []; // everyone's mean speed, once per simulated second
while (true) {
if (snap && viewof gamePause.value) { yield snap; await Promises.delay(100); continue; } // paused: hold the picture
const mine = viewof gameOn.value ? viewof gameV.value : null;
if (mine !== lastMine) { startAt = mine === null ? null : t; clean = 0; wonAt = null; score = null; lastMine = mine; }
for (let k = 0; k < 2; k++) step(mine); // 12 times real time
const sd = d3.deviation(v), mean = d3.mean(v);
if (mine !== null) {
clean = sd < 0.8 ? clean + 2 * dt : 0;
if (clean >= 30 && wonAt === null) {
wonAt = t - startAt - 30;
score = d3.mean(recent.slice(-30));
if (gameBest.value === null || score > gameBest.value) gameBest.value = score;
}
}
if (t >= nextRecord) {
S.hist.push({t: t - t0, sd, you: mine !== null});
recent.push(mean);
if (S.hist.length > 400) S.hist.shift();
if (recent.length > 60) recent.shift();
nextRecord = t + 1;
}
yield snap = {x: Array.from(x), v: Array.from(v), L, sd, mean, jamAvg, clean, driving: mine !== null, wonAt, score};
}
}drawRing(game, htl.svg`<text x="150" y="130" text-anchor="middle" font-size="16" fill="gray">jam meter</text>
<text x="150" y="164" text-anchor="middle" font-size="28" font-weight="bold" fill=${game.sd < 0.8 ? "#2e9e5b" : "#d7263d"}>${game.sd.toFixed(1)}</text>
<text x="150" y="188" text-anchor="middle" font-size="15" fill="gray">goal: under 0.8</text>`, !!document.querySelector(".reveal") ? 235 : 300){
const S = gameState;
while (true) {
yield Plot.plot({
width: colWidth(0.62), height: !!document.querySelector(".reveal") ? 215 : 240,
marginLeft: 52, marginBottom: 42, marginTop: 26, style: {fontSize: "13px"},
x: {label: "Time (simulated s)"},
y: {label: "Jam meter (m/s)", domain: [0, 4], grid: true},
marks: [
Plot.ruleY([0.8], {stroke: "#2e9e5b", strokeDasharray: "6 4"}),
Plot.text([0.8], {x: () => S.hist.length ? S.hist[0].t : 0, y: d => d, text: () => "goal", dy: -8, dx: 4, textAnchor: "start", fill: "#2e9e5b", fontWeight: "bold"}),
Plot.areaY(S.hist.slice(), {x: "t", y: "sd", fill: d => d.you ? accent : "#d7263d", fillOpacity: 0.12, z: null}),
Plot.line(S.hist.slice(), {x: "t", y: "sd", stroke: d => d.you ? accent : "#d7263d", strokeWidth: 1.5, z: null})
]
});
await Promises.delay(500);
}
}{
const kmh = x => (x * 3.6).toFixed(1), g = game;
const msg = !g.driving ? "Press <b>🚗 Take the wheel</b>, then choose your speed."
: g.wonAt === null ? "Hold the jam meter under 0.8 for 30 s."
: g.score > g.jamAvg ? `🏆 <b>Jam dissolved</b> in ${g.wonAt.toFixed(0)} s, and everyone averages <b>${kmh(g.score)} km/h</b>, faster than in the jam. Can anyone beat it?`
: `<b>Jam dissolved</b> in ${g.wonAt.toFixed(0)} s, but everyone crawls at ${kmh(g.score)} km/h, slower than in the jam. Try a little faster.`;
return htl.html`<div class="loop-dash p1-dash">
<div class="dash-tile"><div class="dash-label">Jam meter (goal: under 0.8)</div><div class="dash-value" style="color:${g.sd < 0.8 ? "#2e9e5b" : "#d7263d"}">${g.sd.toFixed(2)} <small>m/s</small></div></div>
<div class="dash-tile"><div class="dash-label">Everyone's average speed</div><div class="dash-value" style="color:${accent}">${kmh(g.mean)} <small>km/h · jam: ${kmh(g.jamAvg)}</small></div></div>
<div class="dash-tile"><div class="dash-label">Jam-free for</div><div class="dash-value" style="color:#2e9e5b">${Math.min(30, g.clean).toFixed(0)} <small>of 30 s</small></div>
<div class="dash-bar"><div style="width:${Math.min(100, g.clean / 30 * 100).toFixed(0)}%;background:#2e9e5b"></div></div></div>
<div class="dash-tile"><div class="dash-label">Your best score</div><div class="dash-value" style="color:${accent}">${gameBest.value === null ? "–" : kmh(gameBest.value)} <small>${gameBest.value === null ? "" : "km/h"}</small></div></div>
</div>${Object.assign(document.createElement("div"), {className: "p1-result", innerHTML: msg})}`;
}
NoteHow to read it
- Ring: 22 cars on a 230 m ring, jammed after 5 minutes on their own. Your car (thick outline) becomes a smart cruise control: it holds your speed smoothly, with no wobble, and never gets closer to the car ahead than is safe.
- Jam meter: the spread (standard deviation) of all 22 speeds. The green dashes mark the goal, 0.8 m/s: above it the ring is jammed, below it the ring flows. The trace is red while nobody drives, violet while you do.
- You win when the meter stays under 0.8 for 30 simulated seconds. Your score is everyone’s average speed over those 30 s; beat the jam’s own average to earn the trophy.
- The movie runs at 12 times real time.
How it works
This is the idea behind a real experiment in Tucson (Stern et al., Transportation Research Part C, 2018), where one automated car damped stop-and-go waves on a ring of about 20 cars. Lecture 1 shows the ring road; Lab 12 trains a reinforcement-learning car to find a strategy on its own.
import {knob, seg, toggles, action, pauser, flip, panel, row, pair} from "../assets/controls.js"
// the copyright notice for figure licence lines in live figures; the years come from _copyright.yml (via the
// trgy-copyright-years tag that assets/figure-license.lua adds to every page)
trgyCopy = "© " + (document.querySelector('meta[name="trgy-copyright-years"]')?.content || "2026") + " Wuping Xin"
theme = Generators.observe(notify => {
const read = () => notify(document.body.classList.contains("quarto-dark") ? "dark" : "light");
read();
const watcher = new MutationObserver(read);
watcher.observe(document.body, {attributes: true, attributeFilter: ["class"]});
return () => watcher.disconnect();
})
accent = theme === "dark" ? "#c9a0ff" : "#57068c"
// the outline behind a label on a plot: the page colour, so it never glares on the dark theme
halo = theme === "dark" ? "#222222" : "white"
accentRange = theme === "dark" ? ["#4b3a5c", "#ecdcff"] : ["#dccbee", "#3a0463"]
ink = theme === "dark" ? "#f2f2f2" : "black"
// Plot width: Plot's default 640 px, except on a phone, where a plot is drawn to fit its card
// instead of being shrunk (and its text with it). Changes only when the width actually changes.
plotW = Generators.observe(notify => {
let last;
const read = () => {
const main = document.querySelector("main"), fit = main ? main.clientWidth - 50 : 640;
const w = !document.querySelector(".reveal") && fit < 640 ? Math.max(240, Math.floor(fit)) : 640;
if (w !== last) notify(last = w);
};
read();
window.addEventListener("resize", read);
return () => window.removeEventListener("resize", read);
})
// Width for a plot inside a column that takes fraction f of the card: columns stand side by side only on
// slides and on web screens of 992 px or more; below that they stack and the plot gets the full plotW.
// fullW: a figure that spans the whole card: the card's width on the web (not capped at 640 like plotW),
// the content width on a slide (narrower in portrait)
fullW = Generators.observe(notify => {
let last;
const read = () => {
const reveal = document.querySelector(".reveal");
let w;
if (reveal) w = (window.Reveal && window.Reveal.getConfig ? window.Reveal.getConfig().width : 1280) - 140; // window.: a bare name would be read as an OJS cell
else { const main = document.querySelector("main"); w = Math.max(240, Math.floor((main ? main.clientWidth : 640) - 50)); }
if (w !== last) notify(last = w);
};
read();
window.addEventListener("resize", read);
return () => window.removeEventListener("resize", read);
})
colWidth = f => {
if (document.querySelector(".reveal") || window.innerWidth < 992) return plotW;
const main = document.querySelector("main");
return Math.max(240, Math.min(plotW, Math.floor((main ? main.clientWidth : 800) * f - 40)));
}ringClock = ({paused: false, buttons: new Set()})
ringPauseButton = () => {
const w = htl.html`<span class="run-pause-wrap"><button type="button" class="ctl-play" title="Pause" aria-label="Pause">⏸︎ Pause</button></span>`;
const b = w.querySelector("button");
const show = () => { b.innerHTML = ringClock.paused ? `<span class="ctl-icon">▶︎</span><span class="ctl-word"> Run</span>` : `<span class="ctl-icon">⏸︎</span><span class="ctl-word"> Pause</span>`; b.title = ringClock.paused ? "Run" : "Pause"; b.setAttribute("aria-label", b.title); };
ringClock.buttons.add(show); show();
b.onclick = () => { ringClock.paused = !ringClock.paused; ringClock.buttons.forEach(f => f()); };
return w;
}
// The ring road drawn as a grey one-lane road with each car an outlined box, coloured by speed (red slow, green fast).
// Car 0 ("you") has the thick outline and is drawn last, on top. Cars drive clockwise.
drawRing = (st, centre, maxPx = 300) => {
const W = 300, c = W / 2, R = 112, pxm = 2 * Math.PI * R / st.L, carL = 4 * pxm, carH = 8;
const color = d3.scaleSequential(d3.interpolateRdYlGn).domain([0, 8]);
const order = d3.range(1, st.x.length).concat([0]);
return htl.svg`<svg width="100%" viewBox="0 0 ${W} ${W}" style="max-width:${maxPx}px;height:auto;display:block;margin:0 auto" role="img" aria-label="Cars on a ring road, coloured by speed">
<circle cx=${c} cy=${c} r=${R} fill="none" stroke="#d9d9d9" stroke-width="20" />
<circle cx=${c} cy=${c} r=${R + 10} fill="none" stroke="#9a9a9a" stroke-width="1" />
<circle cx=${c} cy=${c} r=${R - 10} fill="none" stroke="#9a9a9a" stroke-width="1" />
${order.map(i => {
const th = 2 * Math.PI * st.x[i] / st.L;
return htl.svg`<rect x=${-carL} y=${-carH / 2} width=${carL} height=${carH} rx="2"
transform=${`translate(${c + R * Math.cos(th)},${c + R * Math.sin(th)}) rotate(${th * 180 / Math.PI + 90})`}
fill=${color(st.v[i])} stroke=${i === 0 ? ink : "#333"} stroke-width=${i === 0 ? 2.6 : 0.8} />`;
})}
${centre}
</svg>`;
}
// The ring's time-space diagram: one dot per car every 0.5 s, coloured by speed; your car in black.
// wave (optional): the fitted path of the jam, drawn as a dashed violet line.
ringTS = (hist, L, w, h, wave) => Plot.plot({
width: w, height: h, marginLeft: 52, marginBottom: 42, marginTop: 14, style: {fontSize: "13px"},
x: {label: "Time (s)"},
y: {label: "Position around the ring (m)", domain: [0, L]},
color: {type: "sequential", scheme: "RdYlGn", domain: [0, 8]},
marks: [
Plot.dot(hist, {x: "t", y: "x", fill: "v", r: 1.2}),
Plot.dot(hist.filter(d => d.i === 0), {x: "t", y: "x", fill: ink, r: 1.6}),
wave ? Plot.line(wave.pts, {x: "t", y: "x", z: "seg", stroke: accent, strokeWidth: 3, strokeDasharray: "9 6"}) : null
]
})
// How fast the jam moves: over the last 60 s, take the position of the slowest car (if it is nearly stopped),
// unwrap it around the ring, and fit a straight line. Negative = backward, against the traffic.
jamWave = (hist, L) => {
if (!hist.length) return null;
const tEnd = hist[hist.length - 1].t, pts = [];
for (const [t, cars] of d3.group(hist.filter(d => d.t >= tEnd - 60), d => d.t)) {
const slow = d3.least(cars, d => d.v);
if (slow.v < 1.5) pts.push({t, x: slow.x});
}
if (pts.length < 40) return null;
let off = 0;
const u = pts.map((p, k) => {
if (k) { const d = p.x - pts[k - 1].x; if (d > L / 2) off -= L; else if (d < -L / 2) off += L; }
return {t: p.t, x: p.x + off};
});
const mt = d3.mean(u, d => d.t), mx = d3.mean(u, d => d.x);
const slope = d3.sum(u, d => (d.t - mt) * (d.x - mx)) / d3.sum(u, d => (d.t - mt) ** 2);
const line = d3.range(tEnd - 60, tEnd + 0.01, 0.5).map(t => {
const xu = mx + slope * (t - mt);
return {t, x: ((xu % L) + L) % L, seg: Math.floor(xu / L)};
});
const recent = hist.filter(d => d.t >= tEnd - 60);
return {slope, pts: line, carSpeed: d3.mean(recent, d => d.v)};
}