A jam out of nothing · trajectories · flow, density and speed
22 drivers on a 230 m circle, all at one steady speed. No bottleneck, no accident, no traffic light.
What happens next?
Before you watch: predict
Will a jam form? If one does, does it move with the traffic, or against it?
Each box is a car, coloured by its speed. Yours has the thick outline. Wait and watch.
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)};
}viewof ringN = knob({min: 12, max: 30, step: 1, value: 22, label: "Number of cars", format: n => `${n}`})
viewof ringA = knob({min: 0.2, max: 2.0, step: 0.1, value: 0.5, label: "Drivers' max. acceleration a", format: a => `${a.toFixed(1)} m/s²`})
viewof ringSpeed = knob({min: 1, max: 20, step: 1, value: 8, label: "Playback", format: s => `${s} × real time`})
viewof ringRestart = action("↻ Restart")
ringPause1 = ringPauseButton()// Ring road with the Intelligent Driver Model (IDM) and small random fluctuations in each driver's acceleration.
// The adjustment and playback sliders are read live, so they can be changed without restarting.
// ringState is shared with the time-space plots, which redraw on their own timer.
ringState = { ringRestart; ringN; return {hist: [], L: 230}; }ring = {
const N = ringN, L = ringState.L, v0 = 12, T = 1.2, s0 = 2, b = 1.5, lc = 4, dt = 0.1, noise = 0.3;
const x = Float64Array.from({length: N}, (_, i) => i * L / N);
// start every car at the uniform equilibrium speed for this spacing (3.7 m/s for 22 cars), so nobody causes the jam
let lo = 0, hi = v0;
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 v = new Float64Array(N).fill(lo);
const acc = new Float64Array(N);
const hist = ringState.hist;
const randn = () => Math.sqrt(-2 * Math.log(1 - Math.random())) * Math.cos(2 * Math.PI * Math.random());
let t = 0, budget = 0, nextRecord = 0, snap = null;
while (true) {
if (snap && ringClock.paused) { yield snap; await Promises.delay(100); continue; } // paused: hold the picture
budget += viewof ringSpeed.value / 60; // about 60 frames per second
const a = viewof ringA.value;
while (budget >= dt) {
for (let i = 0; i < N; i++) {
const j = (i + 1) % N;
const 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)));
acc[i] = a * (1 - (v[i] / v0) ** 4 - (sStar / gap) ** 2) + 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; budget -= dt;
if (t >= nextRecord) {
for (let i = 0; i < N; i++) hist.push({t, i, x: x[i], v: v[i]});
nextRecord += 0.5;
while (hist.length && hist[0].t < t - 150) hist.shift();
}
}
yield snap = {t, x: Array.from(x), v: Array.from(v), L};
}
}How to read it
Now ride in the black car. Did anyone ahead of you have a reason to stop?
{
const S = ringState;
while (true) {
const mine = S.hist.filter(d => d.i === 0);
let stops = 0, moving = true; // a stop: below 1 m/s after having been above 2 m/s
for (const d of mine) { if (moving && d.v < 1) { stops++; moving = false; } else if (!moving && d.v > 2) moving = true; }
const span = mine.length ? mine[mine.length - 1].t - mine[0].t : 0;
yield htl.html`<div class="pullbox"><div class="knob-row follow-head"><span class="pullbox-title">Your speed, live (the last ${Math.max(1, Math.round(span))} s)</span>${ringPause2}</div>
${Plot.plot({
width: fullW - 40, height: !!document.querySelector(".reveal") ? 230 : 200, marginLeft: 52, marginBottom: 42, style: {fontSize: "13px"},
x: {label: "Time (s)"},
y: {label: "Your speed (m/s)", domain: [0, 9], grid: true},
marks: [
Plot.areaY(mine, {x: "t", y: "v", fill: accent, fillOpacity: 0.12}),
Plot.line(mine, {x: "t", y: "v", stroke: accent, strokeWidth: 2}),
Plot.ruleY([0])
]
})}
<div class="loop-dash p1-dash">
<div class="dash-tile"><div class="dash-label">Times you stopped</div><div class="dash-value" style="color:#d7263d">${stops}</div></div>
<div class="dash-tile"><div class="dash-label">Your speed now</div><div class="dash-value" style="color:${accent}">${mine.length ? mine[mine.length - 1].v.toFixed(1) : "…"} <small>m/s</small></div></div>
<div class="dash-tile"><div class="dash-label">Your average</div><div class="dash-value" style="color:${accent}">${mine.length ? d3.mean(mine, d => d.v).toFixed(1) : "…"} <small>m/s</small></div></div>
<div class="dash-tile"><div class="dash-label">Accidents, signals, lane drops</div><div class="dash-value" style="color:#2e9e5b">0</div></div>
</div></div>`;
await Promises.delay(500);
}
}How to read it
The red bands tilt.
Predict does the jam move with the cars, or against them? Then reveal.
viewof waveReveal = {
const w = htl.html`<span class="run-pause-wrap"><button type="button" class="pill-btn">Reveal the jam's speed</button></span>`;
const b = w.querySelector("button");
w.value = false;
b.onclick = () => { w.value = !w.value; b.textContent = w.value ? "Hide" : "Reveal the jam's speed"; w.dispatchEvent(new Event("input", {bubbles: true})); };
return w;
}
ringPause3 = ringPauseButton(){
const S = ringState;
while (true) {
const hist = S.hist.slice(), wave = waveReveal ? jamWave(hist, S.L) : null;
const f = x => (x * 3.6).toFixed(0);
const result = !waveReveal ? ""
: !wave ? htl.html`<div class="p1-result">No jam right now: let the ring run (or lower the maximum acceleration <i>a</i>).</div>`
: htl.html`<div class="p1-tiles">
<div class="g-col-12 g-col-md-6 card-lite"><b>The jam</b> (violet dashes)<br>
<span class="result-num" style="color:${accent}">${Math.abs(wave.slope).toFixed(1)} m/s ${wave.slope < 0 ? "backward" : "forward"}</span><br>${f(Math.abs(wave.slope))} km/h, against the traffic</div>
<div class="g-col-12 g-col-md-6 card-lite"><b>The cars</b> (average)<br>
<span class="result-num" style="color:#2e9e5b">${wave.carSpeed.toFixed(1)} m/s forward</span><br>every car keeps moving forward</div>
</div>`;
yield htl.html`<div class="pullbox"><div class="knob-row follow-head">${viewof waveReveal}${ringPause3}</div>
${ringTS(hist, S.L, fullW - 40, !!document.querySelector(".reveal") ? (waveReveal ? 215 : 290) : 260, wave)}
<div class="fig-license">${trgyCopy} · CC BY-NC-SA 4.0</div>${result}</div>`;
await Promises.delay(500);
}
}How to read it
Only a computer game? Here is US-101, Los Angeles, 2005: every vehicle in one lane, ten times a second.
Find the jam. Which way does it move?
us101 = FileAttachment("data/l01-us101-lane2.json").json()
us101Rows = us101.t.map((t, k) => ({t, x: us101.x[k], kmh: us101.v[k] * 3.6, veh: us101.vehicle[k]}))
viewof usReveal = {
const w = htl.html`<span class="run-pause-wrap"><button type="button" class="pill-btn">Reveal the wave</button></span>`;
const b = w.querySelector("button");
w.value = false;
b.onclick = () => { w.value = !w.value; b.textContent = w.value ? "Hide the wave" : "Reveal the wave"; w.dispatchEvent(new Event("input", {bubbles: true})); };
return w;
}{
const W = us101.wave, t0 = W.t0 - 15, t1 = Math.min(240, W.t1 + 15);
const line = [{t: t0, x: W.slope * t0 + W.intercept}, {t: t1, x: W.slope * t1 + W.intercept}];
const speed = Math.abs(W.slope * 3.6);
return htl.html`<div class="pullbox"><div class="knob-row follow-head"><span class="pullbox-title">US-101, lane 2, 8:00–8:04 a.m.</span>${viewof usReveal}</div>
${Plot.plot({
width: fullW - 40, height: !!document.querySelector(".reveal") ? 262 : (fullW < 500 ? 300 : 360),
marginLeft: 52, marginBottom: 36, marginTop: 14, style: {fontSize: "13px"},
x: {label: "Time (s)", domain: [0, 240]},
y: {label: "Position along the road (m)", domain: [0, 660]},
color: {type: "sequential", scheme: "RdYlGn", domain: [0, 100]},
marks: [
Plot.line(us101Rows, {x: "t", y: "x", z: "veh", stroke: "kmh", strokeWidth: 1}),
usReveal ? Plot.line(line, {x: "t", y: "x", stroke: accent, strokeWidth: 3.5, strokeDasharray: "9 6"}) : null,
usReveal ? Plot.text([line[0]], {x: "t", y: "x", text: () => `wave: ${speed.toFixed(0)} km/h backward`, dx: 8, dy: -8, textAnchor: "start",
fill: accent, fontWeight: "bold", stroke: halo, strokeWidth: 4, paintOrder: "stroke"}) : null
]
})}
<div class="p1-result tight-top">Colour: speed, <b style="color:#d7263d">red = stopped</b>, <b style="color:#2e9e5b">green = 100 km/h</b>${usReveal
? htl.html` · the wave moves <b style="color:${accent}">${speed.toFixed(0)} km/h backward</b>, against the traffic` : ""}</div>
<div class="fig-license">Data: NGSIM US-101, FHWA (2016) · ${trgyCopy} · CC BY-NC-SA 4.0</div></div>`;
}In Lab 2 you load these data and measure the wave’s speed yourself.
How to read it
Why does a tiny wobble grow into a jam? In 1959, General Motors researchers boiled it down to one line of cars.
Each driver reacts late. Does one brief brake fade down the line, or grow?
\[ \begin{aligned} \ddot x_{n+1}(t) &= \lambda\,\Delta\dot x(t-T), \\ \Delta\dot x &= \dot x_n - \dot x_{n+1}. \end{aligned} \]
\(\lambda\): how strongly
the driver responds to a speed difference (1/s)
\(T\): how late
the reaction time (s)
\(C = \lambda T\): decides
strongly × late: one number
How to read it
The leader (dashed) brakes for 2 s, then recovers.
Predict at \(C = 0.75\), does car 8 change speed more or less than car 1?
viewof hermanC = knob({min: 0.1, max: 1.8, step: 0.01, value: 0.75, label: "Sensitivity × reaction time", format: c => `C = λT = ${c.toFixed(2)}`})
// one colour per follower; the toggle buttons double as the legend
hermanCars = d3.range(1, 9).map(n => `Car ${n}`)
hermanColors = theme === "dark" ? d3.schemeSet2 : d3.schemeTableau10
viewof hermanShow = toggles(hermanCars, {value: hermanCars, label: "Cars shown",
format: c => htl.html`<span><i class="car-key" style="background:${hermanColors[hermanCars.indexOf(c)]}"></i>${c.slice(4)}</span>`})
// Herman, Montroll, Potts and Rothery (1959): linear car-following with a delay T = 1 s, Euler steps of 0.01 s.
// u[n][k] is car n's speed change (m/s) at step k; car 0 is the leader.
hermanRun = (C, N = 8, tEnd = 50) => {
const T = 1.0, dt = 0.01, lag = Math.round(T / dt), steps = Math.round(tEnd / dt), lam = C / T;
const u = Array.from({length: N + 1}, () => new Float64Array(steps + 1));
for (let k = 1; k <= steps; k++) {
const t = k * dt;
u[0][k] = u[0][k - 1] + (t < 2 ? -1 : t < 4 ? 1 : 0) * dt; // leader brakes, then recovers
const kd = k - 1 - lag;
for (let n = 1; n <= N; n++) {
const a = kd >= 0 ? lam * (u[n - 1][kd] - u[n][kd]) : 0;
u[n][k] = u[n][k - 1] + a * dt;
}
}
const peak = n => u[n].reduce((m, x) => Math.max(m, Math.abs(x)), 0);
return {u, dt, steps, peaks: d3.range(N + 1).map(peak)};
}
herman = {
const r = hermanRun(hermanC), rows = [];
for (let n = 0; n <= 8; n++)
for (let k = 0; k <= r.steps; k += 20) // a point every 0.2 s: light to redraw
rows.push({car: n === 0 ? "Leader" : `Car ${n}`, n, t: k * r.dt, du: r.u[n][k]});
return {rows, ratio: r.peaks[8] / r.peaks[1]};
}
// The same 8 followers on a real road, as in Lab 1: 30 m apart front to front at 20 m/s (a 1.25 s gap), cars 5 m
// long. Positions are drawn relative to a car cruising at 20 m/s, so the strip moves with the traffic.
hermanRoad = {
const N = 8, sp = 30, len = 5, r = hermanRun(hermanC, N, 50);
const x = d3.range(N + 1).map(n => -sp * n);
const frames = [], traj = []; // every 0.1 s: positions and the closest gap so far
let crash = null, closest = Infinity;
for (let k = 0; k <= r.steps; k++) {
if (k > 0) for (let n = 0; n <= N; n++) x[n] += r.u[n][k] * r.dt;
for (let n = 1; n <= N; n++) {
const g = x[n - 1] - x[n] - len;
closest = Math.min(closest, g);
if (!crash && g <= 0) crash = {t: k * r.dt, car: n};
}
if (k % 10 === 0 || crash) frames.push({t: k * r.dt, x: x.slice(), closest});
if (k % 20 === 0 || crash) // trajectories: a point every 0.2 s
for (let n = 0; n <= N; n++) traj.push({t: k * r.dt, n, car: n === 0 ? "Leader" : `Car ${n}`, x: x[n]});
if (crash) break;
}
return {frames, traj, crash, tEnd: crash ? crash.t : 50, N, len, sp};
}
viewof hermanReplay = action("↻ Replay")
viewof hermanPause = pauser()
// One clock for the road and the curves: 0.5 s of traffic every 100 ms (5 x real time, 10 redraws a second). It starts again
// when C changes or on Replay, and stops at the end, or at the moment of a crash.
hermanT = {
hermanReplay;
const R = hermanRoad;
let t = 0;
while (true) {
if (!viewof hermanPause.value && t < R.tEnd) t = Math.min(R.tEnd, Math.round((t + 0.5) * 100) / 100);
yield t;
await Promises.delay(100);
}
}// on a slide the car picker shares the slider's row, so the card fits without scrolling
document.querySelector(".reveal") ? panel(row(viewof hermanC, viewof hermanShow, viewof hermanReplay, viewof hermanPause))
: panel(row(viewof hermanC, viewof hermanReplay, viewof hermanPause), viewof hermanShow){
const C = hermanC, e = 1 / Math.E, h = Math.PI / 2, R = hermanRoad, t = hermanT, done = t >= R.tEnd;
const regime =
C <= e ? ["Smooth and stable", "#2e9e5b", "no overshoot; the brake fades"]
: C < 0.5 ? ["Wobbly, but stable", "#2e9e5b", "overshoots; the brake still fades"]
: C < h ? ["Stable driver, unstable line", "#d7263d", "each settles alone; the line grows it"]
: ["Unstable", "#d7263d", "even one follower over-reacts"];
const slide = !!document.querySelector(".reveal"), W = fullW - 40, mL = 52, mR = 30;
// the road: from behind the last car to just ahead of the leader, metres relative to the cruising traffic
const fr = R.frames[Math.min(R.frames.length - 1, Math.round(t / 0.1))];
const x0 = -R.sp * R.N - 14, x1 = 16, sx = d3.scaleLinear([x0, x1], [mL, W - mR]);
const carW = Math.max(6, sx(R.len) - sx(0)), crashed = R.crash && done;
const road = htl.svg`<svg width=${W} viewBox="0 0 ${W} 72" style="max-width:100%;height:auto;display:block" role="img" aria-label="Nine cars in one lane, the leader on the right; the gaps between them shrink and grow as the brake passes down the line">
<text x=${mL} y="12" font-size="13" fill="gray"><tspan font-weight="bold">Where the cars are</tspan>${W < 640 ? "" : ", filmed from a camera driving along at 72 km/h"}</text>
<text x=${W - mR} y="12" font-size="13" fill="gray" text-anchor="end">${W < 420 ? "" : "traffic →"}</text>
<rect x=${mL - 4} y="18" width=${W - mL - mR + 8} height="30" fill="#8883" rx="3"/>
${d3.range(R.N + 1).map(n => {
const col = n === 0 ? ink : hermanColors[n - 1];
const hit = crashed && (n === R.crash.car || n === R.crash.car - 1);
const dim = n > 0 && !hermanShow.includes(`Car ${n}`);
const left = sx(fr.x[n] - R.len);
return htl.svg`<g opacity=${dim ? 0.3 : 1}>
<rect x=${left} y="25" width=${carW} height="16" rx="3" fill=${col} stroke=${hit ? "#d7263d" : "#333"} stroke-width=${hit ? 3 : 0.8} />
<text x=${left + carW / 2} y="65" font-size="14" text-anchor="middle" fill="currentColor">${n === 0 ? "L" : n}</text></g>`;
})}
</svg>`;
const now = herman.rows.filter(d => d.t <= t + 1e-9);
const side = slide || fullW >= 992, PW = side ? Math.floor((W - 20) / 2) : W, PH = slide ? 146 : (fullW < 500 ? 260 : 300);
// the speed axis fits the whole run at this C (up to a crash), at least ±6 m/s, rounded: it is set once when C
// changes, so it does not jump while the cars move
const duMax = d3.max(herman.rows, d => d.t <= R.tEnd ? Math.abs(d.du) : 0);
const duDomain = d3.scaleLinear().domain([-Math.max(6, duMax * 1.05), Math.max(6, duMax * 1.05)]).nice().domain();
const lbMin = d3.least(herman.rows.filter(d => d.n === 0), d => d.du), lbX = lbMin.t, lbDu = lbMin.du; // the leader's dip
const plot = Plot.plot({
width: PW,
height: PH,
marginTop: 26, marginRight: 12, marginLeft: 44, marginBottom: 40, style: {fontSize: "13px"},
x: {label: "Time (s)", domain: [0, 50]},
y: {label: fullW < 500 ? "Speed change (m/s)" : "Speed change (m/s): − slower, + faster", domain: duDomain, grid: true},
// one colour per driver, in order down the line (the leader is the dashed line)
color: {type: "categorical", domain: hermanCars, range: hermanColors}, // legend: the tick boxes above
clip: true,
marks: [
Plot.ruleY([0]),
Plot.line(now.filter(d => d.n > 0 && hermanShow.includes(d.car)), {x: "t", y: "du", z: "car", stroke: "car", strokeWidth: 1.5}),
Plot.line(now.filter(d => d.n === 0), {x: "t", y: "du", stroke: ink, strokeWidth: 2.5, strokeDasharray: "6 4"}),
Plot.ruleX([t], {stroke: "gray", strokeDasharray: "2 3"}),
// the label sits in the empty band near the bottom, with a short arrow up to the leader's deepest braking
Plot.text(["Leader brakes"], {x: lbX + 4, y: duDomain[0] * 0.82, text: d => d, fill: ink, textAnchor: "start", fontWeight: "bold"}),
Plot.arrow([{x1: lbX + 3.6, y1: duDomain[0] * 0.82, x2: lbX + 0.4, y2: lbDu - 0.4}], {x1: "x1", y1: "y1", x2: "x2", y2: "y2", stroke: ink, strokeWidth: 1.2, headLength: 7})
]
});
// the same cars as trajectories, position in the moving traffic against time: two lines touching is a crash
const tr = R.traj.filter(d => d.t <= t + 1e-9);
const hitAt = crashed ? [{t: R.crash.t, x: fr.x[R.crash.car]}] : [];
const traj = Plot.plot({
width: PW,
height: PH,
marginTop: 26, marginRight: 12, marginLeft: 48, marginBottom: 40, style: {fontSize: "13px"},
x: {label: "Time (s)", domain: [0, 50]},
y: {label: "Position in the moving traffic (m)", domain: [x0, x1]},
color: {type: "categorical", domain: hermanCars, range: hermanColors},
clip: true,
marks: [
Plot.line(tr.filter(d => d.n > 0 && hermanShow.includes(d.car)), {x: "t", y: "x", z: "car", stroke: "car", strokeWidth: 1.5}),
Plot.line(tr.filter(d => d.n === 0), {x: "t", y: "x", stroke: ink, strokeWidth: 2}),
Plot.ruleX([t], {stroke: "gray", strokeDasharray: "2 3"}),
Plot.dot(hitAt, {x: "t", y: "x", r: 7, stroke: "#d7263d", strokeWidth: 2.5}),
Plot.text(hitAt, {x: "t", y: "x", text: () => "crash", dy: -14, fill: "#d7263d", fontWeight: "bold"})
]
});
const big = herman.ratio >= 100;
return htl.html`<div class="pullbox framed-fig">${road}<div class=${side ? "herman-pair side" : "herman-pair"}>${plot}${traj}</div><div class="fig-license">${trgyCopy} · CC BY-NC-SA 4.0</div>
<div class="p1-tiles herman-tiles">
<div class="card-lite"><b>Regime:</b> ${regime[2]}<br><span class="result-num" style="color:${regime[1]}">${regime[0]}</span></div>
<div class="card-lite"><b>Car 8 ÷ car 1,</b> largest speed change<br>${done && !R.crash
? htl.html`<span class="result-num" style="color:${herman.ratio > 1 ? "#d7263d" : "#2e9e5b"}">${big ? "over 100" : herman.ratio.toFixed(2)} ×</span>`
: htl.html`<span class="result-num" style="color:gray">${R.crash && done ? "no answer: a crash" : "after the run…"}</span>`}</div>
<div class="card-lite"><b>Closest gap,</b> 25 m at the start<br>${crashed
? htl.html`<span class="result-num" style="color:#d7263d">Car ${R.crash.car} hits car ${R.crash.car - 1} at ${R.crash.t.toFixed(1)} s</span>`
: htl.html`<span class="result-num" style="color:${fr.closest < 5 ? "#d7263d" : "#2e9e5b"}">${fr.closest.toFixed(1)} m</span>`}</div>
</div></div>`;
}How to read it
At \(C = 0.75\) every driver, alone, settles down. Does the line?
{
const runs = [[0.4, "#2a9d8f"], [0.75, "#d7263d"]].map(([C, col]) => ({C, col, peaks: hermanRun(C, 10, 80).peaks}));
const rows = runs.flatMap(r => r.peaks.slice(1).map((p, i) => ({car: i + 1, p, C: `C = ${r.C}`})));
const alone = hermanRun(0.75, 1, 60), tail = alone.u[1].slice(-1000).reduce((m, x) => Math.max(m, Math.abs(x)), 0);
const last = runs[1].peaks[10] / runs[1].peaks[1];
return htl.html`<div class="pullbox">${Plot.plot({
width: fullW - 40, height: !!document.querySelector(".reveal") ? 215 : 280,
marginLeft: 52, marginBottom: 42, marginTop: 20, marginRight: 20, style: {fontSize: "13px"},
x: {label: "Car number down the line", ticks: d3.range(1, 11), tickFormat: d => d},
y: {label: "Largest speed change (m/s)", grid: true, domain: [0, 11]},
color: {domain: runs.map(r => `C = ${r.C}`), range: runs.map(r => r.col)},
marks: [
// the key, in the empty top-left corner
Plot.text(["C = 0.75"], {frameAnchor: "top-left", dx: 10, dy: 4, fill: runs[1].col, fontWeight: "bold"}),
Plot.text(["C = 0.4"], {frameAnchor: "top-left", dx: 10, dy: 22, fill: runs[0].col, fontWeight: "bold"}),
Plot.ruleY([2], {stroke: "#8a8a8a", strokeDasharray: "5 4"}),
Plot.text([{car: 10, p: 2}], {x: "car", y: "p", text: () => "the leader's", dy: -9, textAnchor: "end", fill: "#6c757d"}),
Plot.line(rows, {x: "car", y: "p", stroke: "C", strokeWidth: 2}),
Plot.dot(rows, {x: "car", y: "p", fill: "C", r: 4})
]
})}<div class="fig-license">${trgyCopy} · CC BY-NC-SA 4.0</div></div>
<div class="p1-tiles">
<div class="g-col-12 g-col-md-6 card-lite"><b>One follower alone</b> (C = 0.75)<br><span class="result-num" style="color:#2e9e5b">settles ✓</span><br>after a minute, within ${tail.toFixed(2)} m/s of its speed</div>
<div class="g-col-12 g-col-md-6 card-lite"><b>A line of 10</b> (C = 0.75)<br><span class="result-num" style="color:#d7263d">grows ✗</span><br>car 10 swings ${last.toFixed(0)} × as much as car 1</div>
</div>`;
}In Lab 1 you rebuild this experiment, find the thresholds, and find when a line crashes.
How to read it
Can one driver change the line? You drive the black car: dissolve the jam, and beat its 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})}`;
}How to read it
Every plot so far had time across and position up. Read one car’s line first.
Think at which number is it stopped? Where is it braking?
1 · steep, straight
cruising
2 · bending flatter
braking
3 · flat
stopped
4 · bending steeper
speeding up
How to read it
Predict wait 20 s at the light instead of 10. Which part of the line moves, and how much time does the car lose?
// A car cruises at v, brakes at 3 m/s² for a red light at 200 m, waits, then speeds up at 2 m/s² back to v.
oneCar = {
const v = oneV, dec = 3, acc = 2, stop = 200;
const xb = stop - v * v / (2 * dec); // where braking starts
const t1 = xb / v, t2 = t1 + v / dec, t3 = t2 + oneWait, t4 = t3 + v / acc;
const pos = t => t <= t1 ? v * t
: t <= t2 ? xb + v * (t - t1) - dec * (t - t1) ** 2 / 2
: t <= t3 ? stop
: t <= t4 ? stop + acc * (t - t3) ** 2 / 2
: stop + v * v / (2 * acc) + v * (t - t4);
const pts = d3.range(0, 70.01, 0.2).map(t => ({t, x: pos(t)})).filter(d => d.x <= 420);
// the four shapes, numbered as on the card above (3 only when the car actually waits)
const spots = [
{n: 1, t: t1 / 2, text: "cruising"},
{n: 2, t: (t1 + t2) / 2, text: "braking"},
{n: 3, t: (t2 + t3) / 2, text: "stopped"},
{n: 4, t: (t3 + t4) / 2, text: "speeding up"}
].map(d => ({...d, x: pos(d.t)})).filter(d => d.x <= 420 && (d.n !== 3 || oneWait > 2));
// time lost to the light: braking costs v/(2·dec), the wait itself, speeding up costs v/(2·acc)
return {pts, spots, stop, xb, lost: v / (2 * dec) + oneWait + v / (2 * acc)};
}{
const slide = !!document.querySelector(".reveal"), narrow = fullW < 600;
const plot = Plot.plot({
width: fullW - 30, height: slide ? 245 : 280, marginLeft: 50, marginBottom: 40, style: {fontSize: "13px"},
x: {label: "Time (s) →", domain: [0, 70], labelOffset: 34},
y: {label: "↑ Position (m)", domain: [0, 420], grid: true},
marks: [
Plot.ruleY([oneCar.stop], {stroke: "#d7263d", strokeDasharray: "4 3"}),
Plot.text([oneCar.stop], {x: 69, y: d => d, text: () => "traffic light", dy: -9, textAnchor: "end", fill: "#d7263d", fontWeight: "bold"}),
Plot.line(oneCar.pts, {x: "t", y: "x", stroke: accent, strokeWidth: 3}),
Plot.dot(oneCar.spots, {x: "t", y: "x", r: 11, fill: accent, stroke: "white", strokeWidth: 2}),
Plot.text(oneCar.spots, {x: "t", y: "x", text: "n", fill: "white", fontWeight: "bold", fontSize: 13}),
narrow ? null : Plot.text(oneCar.spots, {x: "t", y: "x", text: "text", dx: 16, dy: d => d.n === 3 ? -16 : 10,
textAnchor: "start", fontWeight: "bold", fill: ink, stroke: halo, strokeWidth: 4, paintOrder: "stroke"})
]
});
const tile = (label, value) => htl.html`<div class="dash-tile"><div class="dash-label">${label}</div><div class="dash-value">${value}</div></div>`;
return htl.html`<div class="pullbox framed-fig">${plot}
<div class="loop-dash p2-dash3">
${tile("Braking starts at", htl.html`${oneCar.xb.toFixed(1)} <small>m</small>`)}
${tile("Stopped for", htl.html`${oneWait} <small>s</small>`)}
${tile("Time lost to the light", htl.html`${oneCar.lost.toFixed(1)} <small>s</small>`)}
</div>
<div class="fig-license">${trgyCopy} · CC BY-NC-SA 4.0</div></div>`;
}How to read it
One line tells one trip. Put several cars on one diagram: the gaps between lines tell how they share the road.
Two gaps: how far apart, and how long apart? Double the speed: which gap changes?
// Three cars at the same speed, one headway apart. Spacing is the vertical gap (one instant),
// headway the horizontal gap (one point); spacing = speed × headway.
{
const v = shV, h = shH, slide = !!document.querySelector(".reveal"), Y = 300;
const cols = ["#4e79a7", "#59a14f", "#b07aa1"]; // one colour per car
const car = i => d3.range(0, 24.01, 0.25).map(t => ({t, x: v * (t - i * h)})).filter(d => d.x >= 0 && d.x <= Y);
// spacing measured where car 1 is at xs (200 m, or less for slow cars so it stays inside the 24 s axis); headway at xh
const xs = Math.max(v * h, Math.min(200, 0.7 * v * 24)), ts = xs / v, xh = Math.min(100, 0.45 * v * 24);
const plot = Plot.plot({
width: fullW - 30, height: slide ? 240 : 280, marginLeft: 50, marginBottom: 40, style: {fontSize: "13px"},
x: {label: "Time (s) →", domain: [0, 24], labelOffset: 34}, y: {label: "↑ Position (m)", domain: [0, Y], grid: true},
marks: [
...[0, 1, 2].map(i => Plot.line(car(i), {x: "t", y: "x", stroke: cols[i], strokeWidth: 2.5})),
// the key, in the empty top-left corner
...[0, 1, 2].map(i => Plot.text([`car ${i + 1}`], {frameAnchor: "top-left", dx: 10, dy: 4 + 18 * i, fill: cols[i], fontWeight: "bold"})),
Plot.arrow([0], {x1: ts, x2: ts, y1: xs - v * h, y2: xs, stroke: ink, strokeWidth: 2, headLength: 8, bend: false}),
Plot.text([`spacing ${(v * h).toFixed(0)} m`], {x: ts, y: xs - v * h / 2, text: d => d, dx: ts > 14 ? -8 : 8, textAnchor: ts > 14 ? "end" : "start",
fontWeight: "bold", fill: ink, stroke: halo, strokeWidth: 4, paintOrder: "stroke"}),
Plot.arrow([0], {x1: xh / v, x2: xh / v + h, y1: xh, y2: xh, stroke: ink, strokeWidth: 2, headLength: 8, bend: false}),
Plot.text([`headway ${h} s`], {x: xh / v + h / 2, y: xh, text: d => d, dy: 14, fontWeight: "bold",
fill: ink, stroke: halo, strokeWidth: 4, paintOrder: "stroke"})
]
});
return htl.html`<div class="pullbox framed-fig">${plot}
<div class="loop-readout"><b>spacing = speed × headway</b>: ${v} m/s × ${h} s = <b>${(v * h).toFixed(0)} m</b></div>
<div class="fig-license">${trgyCopy} · CC BY-NC-SA 4.0</div></div>`;
}How to read it
Now make the gaps change: eight cars meet a red light.
Predict red at 16 s, green at 46 s. Do all eight cars start moving at 46 s?
// Advance the time slider while running (⏸ shown); dragging the slider works either way.
tsClock = {
while (true) {
const slider = viewof tsT;
if (!viewof tsPause.value) {
slider.value = slider.value >= 90 ? 0 : Math.round((slider.value + 0.2) * 10) / 10;
slider.dispatchEvent(new Event("input", {bubbles: true}));
}
yield Promises.delay(40, 0);
}
}// Eight cars follow the Intelligent Driver Model; during the red phase the stop line acts as a stopped vehicle.
tsSim = {
const v0 = 15, T = 1.2, s0 = 2, a = 1.5, b = 2, lc = 5, dt = 0.1, stop = 300, red = [16, 46], n = 8;
const enter = Array.from({length: n}, (_, i) => 3 * i);
const x = new Array(n).fill(null), v = new Array(n).fill(v0), rows = [];
const idm = (vi, gap, dv) => a * (1 - (vi / v0) ** 4 - ((s0 + Math.max(0, vi * T + vi * dv / (2 * Math.sqrt(a * b)))) / Math.max(gap, 0.1)) ** 2);
for (let k = 0; k <= 900; k++) {
const t = k * dt, isRed = t >= red[0] && t < red[1];
for (let i = 0; i < n; i++) if (x[i] === null && t >= enter[i]) x[i] = 0;
const acc = new Array(n).fill(0);
for (let i = 0; i < n; i++) {
if (x[i] === null) continue;
let gap = Infinity, dv = 0;
if (i > 0 && x[i - 1] !== null) { gap = x[i - 1] - x[i] - lc; dv = v[i] - v[i - 1]; }
if (isRed && x[i] < stop && stop - x[i] - 1 < gap) { gap = stop - x[i] - 1; dv = v[i]; }
acc[i] = Math.max(-8, gap === Infinity ? a * (1 - (v[i] / v0) ** 4) : idm(v[i], gap, dv));
}
for (let i = 0; i < n; i++) if (x[i] !== null) { v[i] = Math.max(0, v[i] + acc[i] * dt); x[i] += v[i] * dt; }
if (k % 2 === 0) for (let i = 0; i < n; i++) if (x[i] !== null && x[i] <= 500) rows.push({t: +t.toFixed(1), car: i + 1, x: x[i], v: v[i]});
}
// headway at x = 100 m and spacing at t = 10 s, between cars 1 and 2
const pass = (car, x0) => rows.find(r => r.car === car && r.x >= x0).t;
const at = (car, t0) => rows.find(r => r.car === car && r.t >= t0).x;
// where each car stops (first speed under 0.5 m/s after the red) and starts again; when it crosses the stop line
const stops = [], starts = [], cross = [];
for (let c = 1; c <= n; c++) {
const r = rows.filter(d => d.car === c);
const s = r.find(d => d.t >= red[0] && d.v < 0.5);
if (s) { stops.push(s); starts.push(r.find(d => d.t > s.t && d.v >= 0.5)); }
const c0 = r.find(d => d.x >= stop); if (c0) cross.push(c0.t);
}
const fit = p => { const mt = d3.mean(p, d => d.t), mx = d3.mean(p, d => d.x);
const m = d3.sum(p, d => (d.t - mt) * (d.x - mx)) / d3.sum(p, d => (d.t - mt) ** 2); return {m, c: mx - m * mt}; };
const after = cross.filter(t => t > red[1]), hw = d3.mean(d3.pairs(after), ([p, q]) => q - p);
return {rows, stop, red, loop: 150, stops, starts, back: fit(stops), go: fit(starts), hw, jam: stops[0].x - stops[1].x,
headway: {x: 100, t1: pass(1, 100), t2: pass(2, 100)},
spacing: {t: 10, x1: at(1, 10), x2: at(2, 10)}};
}tsNow = {
const t = Math.round(tsT * 5) / 5;
const cars = tsSim.rows.filter(r => Math.abs(r.t - t) < 0.05);
const isRed = t >= tsSim.red[0] && t < tsSim.red[1];
const passed = new Set(tsSim.rows.filter(r => r.t <= t && r.x >= tsSim.loop).map(r => r.car)).size;
return {t, cars, isRed, passed, stopped: cars.filter(c => c.v < 0.5).length};
}// The red-light time-space diagram, shared by this card and the next one.
// now: the time cursor (null: none); read: zoom on the queue (no loop, no arrows); answers: add the two waves
// fitted through the points where cars stop and start.
tsDiagram = (width, height, now, read, answers) => Plot.plot({
width: width, height, marginTop: 20, marginLeft: 46, marginBottom: 40, style: {fontSize: "13px"},
x: {label: "Time (s) →", domain: [0, 90], labelOffset: 34},
y: {label: "↑ Position (m)", domain: read ? [150, 420] : [0, 500]},
color: {type: "sequential", scheme: "RdYlGn", domain: [0, 15]},
marks: [
Plot.rect([0], {x1: tsSim.red[0], x2: tsSim.red[1], y1: tsSim.stop - 3, y2: tsSim.stop + 3, fill: "#d7263d"}),
read ? null : Plot.ruleY([tsSim.loop], {stroke: "#c77700", strokeDasharray: "6 4", strokeWidth: 2}),
read ? null : Plot.text([0], {x: 89, y: tsSim.loop, text: () => "loop detector", dy: -9, textAnchor: "end", fill: "#c77700", fontWeight: "bold"}),
Plot.line(tsSim.rows.filter(d => !read || d.x >= 150), {x: "t", y: "x", z: "car", stroke: "v", strokeWidth: 1.5}),
read ? null : Plot.arrow([tsSim.headway], {x1: "t1", x2: "t2", y1: "x", y2: "x", stroke: ink, headLength: 6, bend: false}),
read ? null : Plot.text([tsSim.headway], {x: d => (d.t1 + d.t2) / 2, y: "x", text: () => "headway", dy: 13, fill: ink, stroke: halo, strokeWidth: 4, paintOrder: "stroke"}),
read ? null : Plot.arrow([tsSim.spacing], {x1: "t", x2: "t", y1: "x2", y2: "x1", stroke: ink, headLength: 6}),
read ? null : Plot.text([tsSim.spacing], {x: "t", y: d => (d.x1 + d.x2) / 2, text: () => "spacing", dx: -6, textAnchor: "end", fill: ink, stroke: halo, strokeWidth: 4, paintOrder: "stroke"}),
now === null ? null : Plot.ruleX([now.t], {stroke: accent, strokeWidth: 2}),
now === null ? null : Plot.text([now.t], {x: d => d, y: 485, text: () => width < 420 ? "drone" : "drone snapshot", dx: now.t > 45 ? -6 : 6, textAnchor: now.t > 45 ? "end" : "start", fill: accent, fontWeight: "bold"}),
now === null ? null : Plot.dot(now.cars, {x: "t", y: "x", r: 4, fill: ink}),
...(answers ? [[tsSim.back, tsSim.stops, "#d7263d"], [tsSim.go, tsSim.starts, "#2e9e5b"]].flatMap(([f, p, col]) => {
const t0 = d3.min(p, d => d.t) - 2, t1 = d3.max(p, d => d.t) + 2;
return [Plot.link([0], {x1: t0, y1: f.m * t0 + f.c, x2: t1, y2: f.m * t1 + f.c, stroke: col, strokeWidth: 3, strokeDasharray: "7 4"}),
Plot.dot(p, {x: "t", y: "x", r: 4.5, fill: col, stroke: "white"})];
}) : [])
]
}){
const slide = !!document.querySelector(".reveal"), stripW = fullW < 640 ? 64 : 100, h = slide ? 240 : 360;
const strip = Plot.plot({
width: stripW, height: h, marginLeft: 40, marginRight: 4, marginTop: 20, marginBottom: 40, style: {fontSize: "13px"},
x: {axis: null, domain: [0, 1]}, y: {domain: [0, 500], label: null, ticks: 5},
marks: [
Plot.rect([0], {x1: 0.15, x2: 0.85, y1: 0, y2: 500, fill: "#8883"}),
Plot.ruleY([tsSim.stop], {x1: 0.05, x2: 0.95, stroke: tsNow.isRed ? "#d7263d" : "#2e9e5b", strokeWidth: 5}),
Plot.rect(tsNow.cars, {x1: 0.28, x2: 0.72, y1: d => d.x - 5, y2: "x",
fill: d => d3.interpolateRdYlGn(Math.min(d.v / 15, 1)), stroke: "#333", strokeWidth: 1})
]
});
const tile = (label, value) => htl.html`<div class="dash-tile"><div class="dash-label">${label}</div><div class="dash-value">${value}</div></div>`;
return htl.html`<div class="pullbox framed-fig"><div class="p2-road-row">${strip}${tsDiagram(fullW - 30 - stripW - 8, h, tsNow, false, false)}</div>
<div class="loop-dash">
${tile("Light", htl.html`<span style="color:${tsNow.isRed ? "#d7263d" : "#2e9e5b"}">${tsNow.isRed ? "red" : "green"}</span> <small>t = ${tsNow.t.toFixed(0)} s</small>`)}
${tile("Stopped", htl.html`${tsNow.stopped} <small>of ${tsNow.cars.length}</small>`)}
${tile("Loop has counted", htl.html`${tsNow.passed} <small>cars</small>`)}
${tile("Drone sees", htl.html`${tsNow.cars.length} <small>cars</small>`)}
</div>
<div class="fig-license">Simulated cars · ${trgyCopy} · CC BY-NC-SA 4.0</div></div>`;
}How to read it
Three questions about the red-light diagram. Answer each, then reveal.
viewof readShow = {
const w = htl.html`<span><button type="button" class="pill-btn">Reveal the answers</button></span>`;
const b = w.querySelector("button");
w.value = false;
b.onclick = () => { w.value = !w.value; b.textContent = w.value ? "Hide the answers" : "Reveal the answers";
w.dispatchEvent(new Event("input", {bubbles: true})); };
return w;
}{
const slide = !!document.querySelector(".reveal"), S = tsSim, kmh = m => Math.abs(m * 3.6).toFixed(0);
const q = (n, col, question, answer) => htl.html`<div class="g-col-12 g-col-md-4 card-lite p2-q" style="border-top: 4px solid ${col}">
<b>${n}.</b> ${question}<div class="p2-a" style="color:${col}">${readShow ? answer : "?"}</div></div>`;
return htl.html`<div class="fig-frame"><div class="knob-row">${viewof readShow}</div>
${tsDiagram(fullW - 30, slide ? 220 : 260, null, true, readShow)}
<div class="fig-license">Simulated cars · ${trgyCopy} · CC BY-NC-SA 4.0</div></div>
<div class="grid p2-qs">
${q(1, "#d7263d", "During the red, the points where lines turn flat move down. What moves, how fast?",
htl.html`the back of the queue, ${kmh(S.back.m)} km/h upstream`)}
${q(2, "#2e9e5b", "After the green, where does the “go” signal travel, and how fast?",
htl.html`upstream, car by car, ${kmh(S.go.m)} km/h`)}
${q(3, "#c77700", "A queue: high density, zero flow? What flow leaves the stop line after green?",
htl.html`yes, a car every ${S.jam.toFixed(0)} m; then ${(Math.round(3600 / S.hw / 10) * 10).toLocaleString("en-US")} veh/h`)}
</div>`;
}How to read it
That light showed every car’s trajectory. A real signal sees only the connected cars, day after day.
Predict if 7 % of cars report, how many days of data until you see the queue at this light?
// A seeded random generator (mulberry32), so every reader sees the same days and the PDF shows the same numbers.
p2rng = seed => { let a = seed >>> 0; return () => { a = (a + 0x6D2B79F5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }// One approach to a fixed-time signal (cycle 90 s, red the first 30 s, stop line at 300 m), 600 veh/h arriving at
// random. Cars follow Newell's simplified car-following (free speed 15 m/s, 7 m per stopped car, 2 s wave time).
// Each "day" is 6 cycles; the middle 4 are kept. Every car draws a number u: it is connected if u < share.
probeSim = {
const VF = 15, DELTA = 7, TAU = 2, DT = 0.5, STOP = 300, C = 90, RED = 30, FLOW = 600, DAYS = 60, CYC = 6;
const LAG = Math.round(TAU / DT), steps = Math.round(CYC * C / DT), mean = 3600 / FLOW - 2.5, rnd = p2rng(7353);
const vehicles = [];
for (let d = 0; d < DAYS; d++) {
const arr = []; let t = 0;
while (true) { t += 2.5 - mean * Math.log(1 - rnd()); if (t > CYC * C - 60) break; arr.push({ta: t, u: rnd()}); }
const xs = [];
arr.forEach((a, n) => {
const x = new Array(steps + 1).fill(null);
for (let k = 0; k <= steps; k++) {
const tk = k * DT, prev = k ? x[k - 1] : null;
let cand;
if (prev === null) {
if (tk < a.ta) continue;
const lead = n ? xs[n - 1][Math.max(k - LAG, 0)] : null;
if (lead !== null && lead - DELTA < 0) continue; // no room to enter yet
cand = 0;
} else {
cand = prev + VF * DT;
if (n && k >= LAG && xs[n - 1][k - LAG] !== null) cand = Math.min(cand, xs[n - 1][k - LAG] - DELTA);
if (tk % C < RED && prev <= STOP) cand = Math.min(cand, STOP); // red: the stop line holds
cand = Math.max(cand, prev);
}
x[k] = cand;
}
xs.push(x);
});
arr.forEach((a, n) => {
const x = xs[n], kc = x.findIndex(v => v !== null && v >= STOP);
if (kc < 0) return;
const cyc = Math.floor(kc * DT / C);
if (cyc < 1 || cyc > CYC - 2) return;
let stopX = null;
for (let k = 1; k <= steps; k++)
if (x[k] !== null && x[k - 1] !== null && x[k] - x[k - 1] < 0.25 && x[k] < STOP + 0.01) stopX = stopX === null ? x[k] : Math.min(stopX, x[k]);
const pts = [];
for (let k = 2; k <= steps; k += 2) {
const ta = k * DT - cyc * C;
if (x[k] !== null && x[k - 2] !== null && ta >= -30 && ta <= 90 && x[k] <= 400) pts.push({ta, x: x[k], v: (x[k] - x[k - 2]) / (2 * DT)});
}
vehicles.push({day: d, id: vehicles.length, u: a.u, stopX, pts});
});
}
return {vehicles, STOP, RED};
}{
const p = prShare / 100, D = prDays, slide = !!document.querySelector(".reveal");
const all = probeSim.vehicles.filter(v => v.day < D), probes = all.filter(v => v.u < p);
const pct = (a, b) => b ? Math.round(100 * a / b) : 0;
const st = probes.filter(v => v.stopX !== null), stAll = all.filter(v => v.stopX !== null);
const qSeen = st.length ? probeSim.STOP - d3.min(st, v => v.stopX) : 0, qTrue = probeSim.STOP - d3.min(stAll, v => v.stopX);
const plot = Plot.plot({
width: fullW - 30, height: slide ? 240 : 280, marginLeft: 46, marginBottom: 40, style: {fontSize: "13px"},
x: {label: "Time in the signal cycle (s) →", domain: [-30, 90], labelOffset: 34},
y: {label: "↑ Position (m)", domain: [0, 400]},
color: {type: "sequential", scheme: "RdYlGn", domain: [0, 15]},
marks: [
Plot.rect([0], {x1: 0, x2: probeSim.RED, y1: probeSim.STOP - 4, y2: probeSim.STOP + 4, fill: "#d7263d"}),
Plot.text(["red"], {x: probeSim.RED / 2, y: probeSim.STOP, dy: -14, text: d => d, fill: "#d7263d", fontWeight: "bold"}),
Plot.line(probes.flatMap(v => v.pts.map(q => ({...q, id: v.id}))), {x: "ta", y: "x", z: "id", stroke: "v", strokeWidth: 1.4})
]
});
const tile = (label, value) => htl.html`<div class="dash-tile"><div class="dash-label">${label}</div><div class="dash-value">${value}</div></div>`;
return htl.html`<div class="pullbox framed-fig">${plot}
<div class="loop-dash p2-dash3">
${tile("Connected trips", htl.html`${probes.length} <small>of ${all.length} cars</small>`)}
${tile("Had to stop", htl.html`${pct(st.length, probes.length)} % <small>all cars ${pct(stAll.length, all.length)} %</small>`)}
${tile("Longest queue", htl.html`${qSeen.toFixed(0)} m <small>real ${qTrue.toFixed(0)} m</small>`)}
</div>
<div class="fig-license">Simulated traffic · ${trgyCopy} · CC BY-NC-SA 4.0</div></div>`;
}How to read it
This is how real signals are now judged: connected-car trajectories, no detectors in the road.
Michigan · retiming
7 % of traffic, GM vehicle trajectories, 34 signals in Birmingham, MI
Delay −20 %, stops −30 % (up to)
Purdue · report cards
0 detectors
Arrivals on green, split failures, level of service, from commercial connected-vehicle data
Nevada, Reno · arterials
1 corridor, many signals
Coordination evaluated, and the corridor split into groups by where drivers actually go
More in Lecture 5 (queues and shock waves) and Lecture 12 (a real signal controller in the loop).
Self-driving cars learn to drive from human trajectories, and must be tested on dangerous moments.
Predict in real driving, one crash in how many trips?
viewof crashShow = {
const w = htl.html`<span><button type="button" class="pill-btn">Reveal</button></span>`;
const b = w.querySelector("button");
w.value = false;
b.onclick = () => { w.value = !w.value; b.textContent = w.value ? "Hide" : "Reveal";
w.dispatchEvent(new Event("input", {bubbles: true})); };
return w;
}{
// SHRP2: 5.4 million trips and 1,541 crashes, so roughly one crash per 3,500 trips:
// 3,500 squares, one of them red.
const cols = 175, rows = 20, s = 10, hit = 2741;
const cells = d3.range(cols * rows).map(i => htl.svg`<rect x=${(i % cols) * s} y=${Math.floor(i / cols) * s} width="8.4" height="8.4" rx="1.5"
fill=${crashShow && i === hit ? "#d7263d" : "#b9c2cc"} />`);
const r = crashShow ? htl.svg`<circle cx=${(hit % cols) * s + 4.2} cy=${Math.floor(hit / cols) * s + 4.2} r="16" fill="none" stroke="#d7263d" stroke-width="3"/>` : null;
return htl.html`<div class="fig-frame"><div class="knob-row">${viewof crashShow}
<span class="p2-crash-read">${crashShow ? htl.html`<b style="color:#d7263d">About 1 crash in 3,500 trips</b>` : "Each square is one trip."}</span></div>
<svg width="100%" viewBox="-2 -2 1754 204" role="img" aria-label="3,500 small grey squares, one per trip; after the reveal, one is red: about one crash per 3,500 trips">${cells}${r}</svg>
<div class="fig-license">Data: SHRP2 Naturalistic Driving Study · ${trgyCopy} · CC BY-NC-SA 4.0</div></div>`;
}Learn how people drive
A deep learning car-following model, trained on 2,000 real following events (Shanghai)
Test robot drivers
Keep only the rare, dangerous moments: far faster tests, still unbiased
Watch one driver
SHRP2: 3,400 drivers, 5.4 million trips, 1,541 crashes on video
More
Can trajectories feed travel demand models? Yes, but not the dense ones in this lecture.
| Dense (NGSIM, highD) | Sparse (phones, ride-hailing) | |
|---|---|---|
| Good for | traffic flow, driver behaviour | origins, destinations, route choice |
| The catch | one short stretch of road | not a random sample of travellers |
More
This course needs dense trajectories of every vehicle. Who records them?
| Dataset | Where | How |
|---|---|---|
| NGSIM (FHWA, 2005–06) | US-101, I-80, two city streets | video from tall buildings, 10 Hz |
| highD (2017–18) | German highways | drone video, 25 Hz, about 110,000 vehicles |
| inD, rounD, exiD | German intersections, roundabouts, ramps | drone video |
| pNEUMA (EPFL, 2018) | central Athens | 10 drones, about half a million trajectories |
| I-24 MOTION | 4.2 miles of I-24, Nashville | 276 pole-mounted cameras |
| TGSIM (FHWA) | Chicago, Washington DC | video, people beside automated cars |
| Waymo, Argoverse 2 | US cities | sensors on self-driving cars |
First, missed cars, from the table’s last row: a self-driving car’s laser scanner.
Predict one sweep at a Boston intersection, seen from above. How many vehicles?
viewof lidarShow = {
const w = htl.html`<span><button type="button" class="pill-btn">Reveal the vehicles</button></span>`;
const b = w.querySelector("button");
w.value = false;
b.onclick = () => { w.value = !w.value; b.textContent = w.value ? "Hide the vehicles" : "Reveal the vehicles";
const fig = document.querySelector(".p2-lidar"); if (fig) fig.classList.toggle("show", w.value);
w.dispatchEvent(new Event("input", {bubbles: true})); };
return w;
}

How to read it
Next, cars in the wrong place, from the table’s first row: NGSIM saw every car, but each slightly off.
Predict every car within 30 cm. How wrong can its acceleration be?
// One car slows from 15 to 5 m/s and back over 30 s, recorded 10 times a second. Each recorded position gets a
// random error (fixed seed), the positions are averaged over a window, then differentiated twice (central differences).
noisy = {
const dt = 0.1, N = 301, rnd = p2rng(2005), w = {"none": 1, "1 s": 11, "2 s": 21}[nzSmooth], h = (w - 1) / 2;
const t = d3.range(N).map(i => i * dt), om = 2 * Math.PI / 30;
const vt = t.map(s => 15 - 5 * (1 - Math.cos(om * s))), at = t.map(s => -5 * om * Math.sin(om * s));
const z = t.map(() => Math.sqrt(-2 * Math.log(1 - rnd())) * Math.cos(2 * Math.PI * rnd()));
const x = t.map((s, i) => 15 * s - 5 * (s - Math.sin(om * s) / om) + nzSigma * z[i]);
const xs = x.map((_, i) => i >= h && i < N - h ? d3.mean(x.slice(i - h, i + h + 1)) : NaN);
const v = xs.map((_, i) => i > 0 && i < N - 1 ? (xs[i + 1] - xs[i - 1]) / (2 * dt) : NaN);
const a = v.map((_, i) => i > 0 && i < N - 1 ? (v[i + 1] - v[i - 1]) / (2 * dt) : NaN);
const rows = t.map((s, i) => ({t: s, vt: vt[i], at: at[i], v: v[i], a: a[i]}));
const ok = rows.filter(d => !isNaN(d.a));
return {rows, amax: d3.max(ok, d => Math.abs(d.a)), atrue: d3.max(rows, d => Math.abs(d.at)),
verr: Math.sqrt(d3.mean(rows.filter(d => !isNaN(d.v)), d => (d.v - d.vt) ** 2))};
}{
const slide = !!document.querySelector(".reveal"), side = fullW >= 600, w = side ? (fullW - 30 - 16) / 2 : fullW - 30, h = slide ? 162 : 210;
const common = {width: w, height: h, marginLeft: 46, marginBottom: 40, style: {fontSize: "13px"}, x: {label: "Time (s) →", domain: [0, 30], labelOffset: 34}};
const speed = Plot.plot({...common, width: w, y: {label: "↑ Speed (m/s)", domain: [0, 25], grid: true}, clip: true,
marks: [Plot.line(noisy.rows, {x: "t", y: "v", stroke: accent, strokeWidth: 1.2}),
Plot.line(noisy.rows, {x: "t", y: "vt", stroke: ink, strokeWidth: 2.5})]});
const accel = Plot.plot({...common, width: w, y: {label: "↑ Acceleration (m/s²)", domain: [-40, 40], grid: true}, clip: true,
marks: [Plot.rect([0], {x1: 0, x2: 30, y1: 9.8, y2: 40, fill: "#8882"}),
Plot.rect([0], {x1: 0, x2: 30, y1: -40, y2: -9.8, fill: "#8882"}),
Plot.line(noisy.rows, {x: "t", y: "a", stroke: accent, strokeWidth: 1.2}),
Plot.line(noisy.rows, {x: "t", y: "at", stroke: ink, strokeWidth: 2.5})]});
const tile = (label, value) => htl.html`<div class="dash-tile"><div class="dash-label">${label}</div><div class="dash-value">${value}</div></div>`;
return htl.html`<div class="pullbox framed-fig"><div class="p2-plots">${speed}${accel}</div>
<div class="loop-dash p2-dash3">
${tile("Largest acceleration", htl.html`${noisy.amax.toFixed(1)} <small>m/s² (real ${noisy.atrue.toFixed(2)})</small>`)}
${tile("Speed error", htl.html`${noisy.verr.toFixed(2)} <small>m/s, typical</small>`)}
${tile("Verdict", noisy.amax > 9.8 ? htl.html`<span style="color:#d7263d">impossible</span>` : noisy.amax > 2 * noisy.atrue ? htl.html`<span style="color:#c77700">too jumpy</span>` : htl.html`<span style="color:#2e9e5b">believable</span>`)}
</div>
<div class="fig-license">Simulated measurement · ${trgyCopy} · CC BY-NC-SA 4.0</div></div>`;
}The lesson: fit a model to raw positions and it learns the noise. Check accelerations first.
How to read it
A time-space diagram holds every car; often three numbers are enough, and where you stand decides what you count.
| Number | Units | How you count it |
|---|---|---|
| Flow \(q\) | veh/h | cars crossing a line, per hour |
| Density \(k\) | veh/km | cars on a stretch, at one instant |
| Speed \(v\) | km/h | how fast they move |
In a steady stream the three are linked: \(q = k\,v\) (Appendix A1).
How sensors really measure them, and when they disagree: Lecture 2.
Quick question
Cars 25 m apart drive past you at 36 km/h. How many pass in an hour?
Answer
1,440 veh/h. One car every 25 m is \(k\) = 40 veh/km, and \(q = k\,v = 40 \times 36\).
Count cars at the orange line and on the violet stretch. Do the two counts agree with \(q = k\,v\)?
// One lane, every car at the same speed v, spacings random between 0.6 and 1.4 times the average.
// A new slider setting starts the count again.
qkvCars = {
const rnd = d3.randomLcg(11), X = [];
let x = 430;
for (let i = 0; i < 3000; i++) { X.push(x); x -= qkvS * (0.6 + 0.8 * rnd()); }
return {X, v: qkvV / 3.6};
}qkvCount = {
const {X, v} = qkvCars, t = qkvT, line = 300, a = 50, b = 250;
let passed = 0, inside = 0, timeIn = 0;
for (const x0 of X) {
const x = x0 + v * t;
if (x0 < line && x >= line) passed++;
if (x >= a && x < b) inside++;
// time this car has spent on the stretch since the count started
const t1 = Math.max(0, (a - x0) / v), t2 = Math.min(t, (b - x0) / v);
if (t2 > t1) timeIn += t2 - t1;
}
const kNow = inside / 0.2, kAvg = t > 0 ? timeIn / t / 0.2 : kNow; // veh/km on a 200 m stretch
return {t, passed, inside, q: t > 0 ? passed / t * 3600 : NaN, kNow, kAvg, kv: kAvg * qkvV};
}{
const W = fullW - 40, slide = !!document.querySelector(".reveal"), H = slide ? 150 : 120;
const m = 10, sx = x => m + (W - 2 * m) * x / 400, y0 = H / 2 - 16, lw = slide ? 34 : 26;
const carLen = sx(4.5) - sx(0), col = d3.interpolateRdYlGn(Math.min(qkvV / 100, 1));
const cars = qkvCars.X.map(x0 => x0 + qkvCars.v * qkvT).filter(x => x > -5 && x < 405);
const fs = slide ? 18 : 13;
const svg = htl.svg`<svg width="100%" viewBox="0 0 ${W} ${H}" style="display:block">
<rect x=${sx(0)} y=${y0 - lw / 2} width=${sx(400) - sx(0)} height=${lw} fill="#e6e6e6"/>
<line x1=${sx(0)} x2=${sx(400)} y1=${y0 - lw / 2} y2=${y0 - lw / 2} stroke="#999"/>
<line x1=${sx(0)} x2=${sx(400)} y1=${y0 + lw / 2} y2=${y0 + lw / 2} stroke="#999"/>
<rect x=${sx(50)} y=${y0 - lw / 2 - 6} width=${sx(250) - sx(50)} height=${lw + 12} fill="#57068c" fill-opacity="0.08" stroke="#57068c" stroke-width="2" stroke-dasharray="6 4"/>
<line x1=${sx(300)} x2=${sx(300)} y1=${y0 - lw / 2 - 8} y2=${y0 + lw / 2 + 8} stroke="#c77700" stroke-width="4"/>
${cars.map(x => htl.svg`<rect x=${sx(x) - carLen} y=${y0 - lw / 4} width=${carLen} height=${lw / 2} rx="2"
fill=${col} stroke=${x >= 50 && x < 250 ? "#57068c" : "#333"} stroke-width=${x >= 50 && x < 250 ? 2 : 0.8} />`)}
<text x=${sx(150)} y=${H - 8} text-anchor="middle" font-size=${fs} fill="#57068c">stretch: 200 m</text>
<text x=${sx(300)} y=${H - 8} text-anchor="middle" font-size=${fs} fill="#c77700">line</text>
<text x=${sx(400)} y=${H - 8} text-anchor="end" font-size=${fs} fill="gray">traffic →</text>
</svg>`;
return htl.html`<div class="pullbox"><div class="pullbox-title">400 m of road, 5 × real time</div>${svg}</div>`;
}{
const c = qkvCount, f0 = x => isNaN(x) ? "…" : Math.round(x).toLocaleString("en-US");
const err = Math.abs(c.q - c.kv) / c.kv;
return htl.html`<div class="loop-dash">
<div class="dash-tile"><div class="dash-label">Crossed the line</div><div class="dash-value">${c.passed} <small>cars in ${c.t.toFixed(0)} s</small></div></div>
<div class="dash-tile"><div class="dash-label">Flow q = count ÷ time</div><div class="dash-value">${f0(c.q)} <small>veh/h</small></div></div>
<div class="dash-tile dash-last"><div class="dash-label">On the stretch: ${c.inside} now</div><div class="dash-value">${c.kAvg.toFixed(1)} <small>veh/km, average</small></div></div>
<div class="dash-tile"><div class="dash-label">Check: k × v</div><div class="dash-value" style="color:${c.t > 60 && err < 0.05 ? "#2e9e5b" : "#6c757d"}">${f0(c.kv)} <small>veh/h</small></div></div>
</div>`;
}How to read it
Pack more and more cars onto a road.
Does the flow keep rising?
Before you try: predict
Sketch flow against density, empty road to jam: a rising line, a hill, or something else?
Slide the density up from an empty road, and watch the dots it leaves. (The real curve: Lecture 3.)
viewof fdK = knob({min: 0, max: 200, step: 1, value: 20, label: "Density k", format: k => `${k} veh/km`})
viewof vf = knob({min: 60, max: 130, step: 1, value: 100, label: "Free-flow speed vf", format: v => `${v} km/h`})
viewof kj = knob({min: 80, max: 200, step: 1, value: 150, label: "Jam density kj", format: k => `${k} veh/km`})
viewof fdReveal = flip("Reveal the whole curve", "Hide the curve"){
const k = fdK, v = fdModel.v(k), q = fdModel.q(k);
fdTrace.set(k, q);
const trace = Array.from(fdTrace, ([k, q]) => ({k, q}));
const curve = d3.range(0, 200.01, 1).map(k => ({k, q: fdModel.q(k)}));
const slide = !!document.querySelector(".reveal");
return htl.html`<div class="pullbox">${Plot.plot({
width: fullW - 40, height: slide ? 190 : (fullW < 500 ? 260 : 300),
style: {fontSize: slide ? "18px" : "13px", width: "100%", height: "auto"},
marginLeft: slide ? 70 : 56, marginBottom: 44, marginRight: 20,
x: {label: "Density k (veh/km) →", domain: [0, 200]},
y: {label: "↑ Flow q (veh/h)", domain: [0, 6500], grid: true},
marks: [
Plot.ruleY([0]),
fdReveal ? Plot.line(curve, {x: "k", y: "q", stroke: accent, strokeWidth: 2.5}) : null,
fdReveal ? Plot.dot([{k: kj / 2, q: vf * kj / 4}], {x: "k", y: "q", r: 6, fill: "white", stroke: accent, strokeWidth: 2.5}) : null,
fdReveal ? Plot.text([{k: kj / 2, q: vf * kj / 4}], {x: "k", y: "q", text: () => "capacity", dy: -14, fill: accent, fontWeight: "bold"}) : null,
Plot.dot(trace, {x: "k", y: "q", r: 2.5, fill: "#888"}),
Plot.dot([{k, q, v}], {x: "k", y: "q", r: 9, fill: d3.interpolateRdYlGn(v / vf), stroke: ink, strokeWidth: 1.5})
]
})}</div>`;
}{
const k = fdK, v = fdModel.v(k), q = fdModel.q(k);
return htl.html`<div class="loop-dash">
<div class="dash-tile"><div class="dash-label">Speed v</div><div class="dash-value" style="color:${d3.interpolateRdYlGn(v / vf)}">${v.toFixed(0)} <small>km/h</small></div></div>
<div class="dash-tile dash-last"><div class="dash-label">Flow q = k v</div><div class="dash-value">${Math.round(q).toLocaleString("en-US")} <small>veh/h</small></div></div>
<div class="dash-tile"><div class="dash-label">Capacity</div><div class="dash-value">${fdReveal ? htl.html`${Math.round(vf * kj / 4).toLocaleString("en-US")} <small>veh/h at ${kj / 2} veh/km</small>` : htl.html`<small>reveal the curve</small>`}</div></div>
</div>`;
}How to read it
🌊 Explain where jams come from and how they move L3–6
🛠️ Build your own traffic simulator in Python all term
📡 Measure traffic from video, drones and sensors L1–4
📏 Fit models to data, and know how far to trust them L10
🤖 Use AI well, and know when a simple rule wins L9, 11, 12
🔁 Run a digital twin with a real signal controller L12
🏆 First correct answer, with a one-line reason, wins bragging rights
🚗
🌶️ Fewest cars
Drivers adjust at 0.5 m/s². What is the fewest cars on the ring that still make a jam? Why does a jam need enough cars?
Try it in: Watch it happen
🎚️
🌶️🌶️ Just enough acceleration
With 22 cars, what is the smallest maximum acceleration \(a\) that keeps traffic smooth?
Try it in: Watch it happen
⚖️
🌶️🌶️🌶️ The tipping point
Find the \(C\) at which the last car’s swing equals the first follower’s. Theory says \(1/2\). Why don’t you get it?
Try it in: Try it: C decides
Answer in your head, then tap.
Who caused the ring-road jam?
Nobody: tiny wobbles grew into a wave
Which way does a jam move?
Backward, at 15–20 km/h on freeways
Every driver is stable. Is the line?
Not always: \(C = \lambda T\) decides
Can one car dissolve a jam?
Yes: slow and steady absorbs the waves
A trajectory’s slope tells you…
Its speed; flat means stopped
More cars on a road: more flow?
Up to capacity, then less
Next week: two sensors, two average speeds.
This week’s lab: Lab 1 · Phantom Jams on Your Laptop · Play more: Shock Wave Builder
| Symbol | Meaning (units) |
|---|---|
| \(t\) | time (s) |
| \(x(t)\) | a vehicle’s position along the road: its trajectory (m) |
| \(v = dx/dt\) | speed (m/s or km/h) |
| \(a = d^2x/dt^2\) | acceleration (m/s²) |
| \(s\) | spacing: distance to the car ahead, front to front (m) |
| \(h\) | headway: time to the car ahead (s) |
| \(q\) | flow: vehicles passing a point per hour (veh/h) |
| \(k\) | density: vehicles per km of road (veh/km) |
| \(v_f,\ k_j\) | free-flow speed (km/h); jam density (veh/km) |
| \(k_c,\ q_{\max}\) | critical density (veh/km); capacity (veh/h) |
| \(T\) | reaction time, Herman et al. (s) |
| \(\lambda\) | sensitivity: how strongly a driver responds (1/s) |
| \(C = \lambda T\) | the one number that decides stability |
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)));
}