The same traffic, two different speeds · Edie’s definitions · why your phone and the road disagree
Every sensor watches the road in its own way. Meet the two we compare today.
| Loop detector | Drone | |
|---|---|---|
| Where | in the pavement | above the road |
| How | the car’s metal changes its magnetic field | a camera films |
| Sees | one point, over time | the whole stretch, at one instant |
Watch the loop: every vehicle that covers it switches it on.
viewof loopSetting = seg(["Freeway 60 Hz", "Intersection 10 Hz", "NYC 30 Hz"], {value: "Freeway 60 Hz", label: "Polling Rate (Hz)",
format: d => d.match(/\d+ Hz/)[0].replace(" ", "")}) // "60Hz": the road type is in the How to read it box
viewof loopPeriod = seg(["20 s", "30 s", "60 s"], {value: "30 s", label: "Report every"})
viewof loopPause = pauser()// A loop detector in action: vehicles drive over a 1.8 m loop; it is "on" while any part of a vehicle covers it.
// Every 30 s it reports a count and an occupancy (the share of the 30 s it was on), as a real detector does.
loopAnim = {
// Two lanes; a 1.8 m loop in the near lane is occupied while any part of a vehicle in that lane covers it.
// Far-lane vehicles pass without being counted: one loop watches one lane.
// The controller polls the loop at a fixed rate: 60 Hz on freeways (Coifman 2004), 10 Hz at signalised
// intersections (NEMA TS 2), 30 Hz in New York City. Occupancy = samples hit / samples taken; count = number of
// times the samples switch from empty to occupied. It reports both every 30 s.
const hz = loopSetting.startsWith("Freeway") ? 60 : loopSetting.startsWith("Intersection") ? 10 : 30;
const vMin = hz === 60 ? 16 : 7, vSpan = hz === 60 ? 8 : 6; // freeway 58-86 km/h; city streets 25-47 km/h
const L = 60, x0 = 34, d = 1.8, period = parseInt(loopPeriod), dt = 1 / 60, every = 60 / hz; // period: the reporting interval
let veh = [], t = 0, step = 0, hits = 0, samples = 0, count = 0, start = 0, last = null, prev = false;
const next = [0, 0.8];
const trace = []; // [time, sample] for the signal plot
let snap = null;
while (true) {
if (snap && viewof loopPause.value) { yield snap; await Promises.delay(100); continue; } // paused: hold the picture
for (let k = 0; k < 4; k++) { // four 1/60 s samples per frame: about twice real time
for (const lane of [0, 1]) {
if (t >= next[lane]) {
const truck = Math.random() < 0.15, v = vMin + Math.random() * vSpan, len = truck ? 14 : 4.5;
const lead = veh.filter(c => c.lane === lane).at(-1);
if (!lead || lead.x - lead.len > 10) veh.push({x: 0, len, v, truck, lane});
next[lane] = t + 1.2 + Math.random() * 2.6;
}
}
let on = false;
for (const c of veh) {
c.x += c.v * dt;
if (c.lane === 0 && c.x >= x0 && c.x - c.len <= x0 + d) on = true;
}
veh = veh.filter(c => c.x - c.len < L);
if (step % every === 0) { // the controller polls: is a vehicle over the loop?
samples++; if (on) hits++;
if (on && !prev) count++; // empty -> occupied: one more vehicle
prev = on;
trace.push([t, on ? 1 : 0]);
while (trace.length && trace[0][0] < Math.min(start, t - 2)) trace.shift(); // this period (and the last 2 s)
}
step++; t += dt;
if (samples >= period * hz) { last = {count, occ: hits / samples}; count = 0; hits = 0; samples = 0; start = t; }
}
yield snap = {veh: veh.map(c => ({...c})), on: prev, trace: trace.slice(), t, x0, d, L, count, hits, samples, hz, period, start,
occ: samples ? hits / samples : 0, elapsed: t - start, last};
await Promises.delay(33);
}
}{
const A = loopAnim, slide = !!document.querySelector(".reveal");
// drawn at the width it is shown at (inside the dashed box on the web), so its text is never shrunk on a phone
const W = slide ? fullW : Math.max(240, fullW - 34), padL = 16, padR = 16, laneW = 3.7, roadW = 2 * laneW;
// an angled 3-D view: x along the road, y across it (0 = near edge), z up
const sc = (W - padL - padR) / (A.L + roadW * 0.55), kx = sc * 0.55, ky = sc * 0.62, kz = sc * 0.95;
const base = 106, H1 = 168;
const P = (x, y, z = 0) => [padL + x * sc + y * kx, base - y * ky - z * kz];
const poly = (pts, fill, stroke = null) => htl.svg`<polygon points=${pts.map(p => p.join(",")).join(" ")} fill=${fill}
stroke=${stroke || "none"} stroke-width=${stroke ? 1.3 : 0} />`;
const on = A.on;
// the road surface, its edges and the dashed centre line
const road = poly([P(0, 0), P(A.L, 0), P(A.L, roadW), P(0, roadW)], "#d9d9d9");
const edges = [0, roadW].map(y => htl.svg`<line x1=${P(0, y)[0]} y1=${P(0, y)[1]} x2=${P(A.L, y)[0]} y2=${P(A.L, y)[1]} stroke="#8a8a8a" stroke-width="1.2"/>`);
const centre = htl.svg`<line x1=${P(0, laneW)[0]} y1=${P(0, laneW)[1]} x2=${P(A.L, laneW)[0]} y2=${P(A.L, laneW)[1]}
stroke="white" stroke-width="2" stroke-dasharray="14 12"/>`;
// the loop: three turns of wire on the near lane, glowing while a vehicle covers it
const ly = laneW / 2 - 0.9;
const loopFill = poly([P(A.x0, ly), P(A.x0 + A.d, ly), P(A.x0 + A.d, ly + 1.8), P(A.x0, ly + 1.8)],
on ? "#e08a0088" : "#e08a0018");
const turns = [0, 0.16, 0.32].map(g => poly([P(A.x0 + g, ly + g), P(A.x0 + A.d - g, ly + g), P(A.x0 + A.d - g, ly + 1.8 - g), P(A.x0 + g, ly + 1.8 - g)],
"none", "#e08a00"));
// the wiring: the loop's lead-in wire runs in a saw cut to a pull box at the road edge; a lead-in cable
// runs from there, underground, to the cabinet, where the detector card sits (FHWA Traffic Detector Handbook)
const pbX = A.x0 + A.d / 2, pbY = -1.9, cabX = A.x0 + 10; // the pull box off the road edge; the cabinet further back
const wire = [P(A.x0 + A.d / 2, ly), P(pbX, pbY + 0.35)];
const cable = [P(pbX + 0.4, pbY), P(cabX + 0.3, pbY), P(cabX + 0.3, -4.0)]; // runs along the shoulder, into the cabinet's base
const pullbox = poly([P(pbX - 0.4, pbY - 0.35), P(pbX + 0.4, pbY - 0.35), P(pbX + 0.4, pbY + 0.35), P(pbX - 0.4, pbY + 0.35)], "#8a8a8a", "#555");
// a roadside signal cabinet: an aluminium box on a concrete pad, a door with a handle and vent louvres
const box3 = (x1, x2, y1, y2, z1, z2, cols, line = null) => [
poly([P(x1, y1, z2), P(x2, y1, z2), P(x2, y2, z2), P(x1, y2, z2)], cols[0], line), // top
poly([P(x2, y1, z1), P(x2, y2, z1), P(x2, y2, z2), P(x2, y1, z2)], cols[1], line), // right side
poly([P(x1, y1, z1), P(x2, y1, z1), P(x2, y1, z2), P(x1, y1, z2)], cols[2], line)]; // front
const cab = (() => {
const x1 = cabX, x2 = cabX + 1.1, y1 = -4.4, y2 = -3.75, h = 2.1, pad = 0.18;
const seg = (a, b) => htl.svg`<line x1=${a[0]} y1=${a[1]} x2=${b[0]} y2=${b[1]} stroke="#6f787d" stroke-width="1" />`;
const door = poly([P(x1 + 0.09, y1, pad + 0.12), P(x2 - 0.09, y1, pad + 0.12), P(x2 - 0.09, y1, h - 0.12), P(x1 + 0.09, y1, h - 0.12)], "none", "#6f787d");
const louvres = [0.35, 0.45, 0.55, h - 0.55, h - 0.45].map(z => seg(P(x1 + 0.3, y1, pad + z), P(x2 - 0.3, y1, pad + z)));
const handle = htl.svg`<line x1=${P(x2 - 0.2, y1, pad + 1.0)[0]} y1=${P(x2 - 0.2, y1, pad + 1.0)[1]} x2=${P(x2 - 0.2, y1, pad + 1.3)[0]} y2=${P(x2 - 0.2, y1, pad + 1.3)[1]}
stroke="#3e4549" stroke-width="2.4" stroke-linecap="round" />`;
return [...box3(x1 - 0.3, x2 + 0.3, y1 - 0.25, y2 + 0.25, 0, pad, ["#dcdcdc", "#b8b8b8", "#c9c9c9"]), // concrete pad
...box3(x1, x2, y1, y2, pad, pad + h, ["#cfd6da", "#8d979c", "#aab3b8"], "#7a8489"), // the cabinet
...box3(x1 - 0.05, x2 + 0.05, y1 - 0.05, y2 + 0.05, pad + h, pad + h + 0.08, ["#dde3e6", "#9aa4a9", "#b9c2c6"]), // lid
door, ...louvres, handle];
})();
// vehicles as boxes: the far lane first, so the near lane is drawn over it
const box = c => {
const yc = c.lane === 0 ? laneW / 2 : laneW * 1.5, y1 = yc - 0.9, y2 = yc + 0.9, xr = Math.max(0, c.x - c.len), xf = Math.min(A.L, c.x);
if (xf <= xr) return null;
const h = c.truck ? 3.4 : 1.5, col = c.truck ? ["#6c757d", "#9aa1a8", "#565e64"] : ["#2a9d8f", "#6cc9bd", "#1f7f74"];
return [poly([P(xr, y1, h), P(xf, y1, h), P(xf, y2, h), P(xr, y2, h)], col[1]),
poly([P(xf, y1), P(xf, y2), P(xf, y2, h), P(xf, y1, h)], col[2]),
poly([P(xr, y1), P(xf, y1), P(xf, y1, h), P(xr, y1, h)], col[0])];
};
const cars = [...A.veh.filter(c => c.lane === 1), ...A.veh.filter(c => c.lane === 0)].map(box).filter(Boolean).flat(); // htl draws a flat list
const roadSvg = htl.svg`<svg width="100%" viewBox="0 0 ${W} ${H1}" role="img" aria-label="Two lanes of vehicles; a loop detector in the near lane switches on while a vehicle covers it">
${road}${edges}${centre}${loopFill}${turns}
<polyline points=${wire.map(p => p.join(",")).join(" ")} fill="none" stroke="#e08a00" stroke-width="1.3" />
${pullbox}
<polyline points=${cable.map(p => p.join(",")).join(" ")} fill="none" stroke="#555" stroke-width="1.6" stroke-dasharray="5 3" />
${W < 480 ? null : htl.svg`<text x=${P(pbX - 0.6, pbY)[0] - 4} y=${P(pbX, pbY)[1] + 4} font-size="12" fill="gray" text-anchor="end">pull box</text>
<text x=${(P(pbX, pbY)[0] + P(cabX, pbY)[0]) / 2} y=${P(cabX, pbY)[1] + 15} font-size="12" fill="gray" text-anchor="middle">lead-in cable</text>`}
${cab}${cars}
<line x1=${P(A.x0 + A.d / 2, ly + 1.8)[0]} y1=${P(A.x0 + A.d / 2, ly + 1.8)[1]} x2=${P(A.x0 + A.d / 2, roadW)[0]} y2=${P(A.x0 + A.d / 2, roadW)[1] - 14}
stroke="#c77700" stroke-width="1" stroke-dasharray="3 3" />
<text x=${P(A.x0 + A.d / 2, roadW)[0]} y=${P(A.x0 + A.d / 2, roadW)[1] - 18} font-size="13" fill="#c77700" class="loop-label" text-anchor="middle" font-weight="bold">loop: ${on ? "ON" : "OFF"}</text>
${W < 480 ? null : htl.svg`<text x=${P(cabX + 1.5, -4.1)[0] + 8} y=${P(cabX + 1.5, -4.1, 1.2)[1] + 4} font-size="12" fill="gray">cabinet: detector card</text>`}
</svg>`;
// on a slide the sample strip and the period trace sit side by side, so the card fits without scrolling
const W2 = slide ? Math.floor((W - 28) / 2) : W;
const sig = Plot.plot({
width: W2, height: slide ? 64 : 116, marginLeft: 46, marginRight: padR, marginTop: 6, marginBottom: 34, style: {fontSize: "13px"},
x: {label: null, domain: [0, A.period], tickFormat: d => d === A.period ? `${d} s` : d.toFixed(0)}, // the title above says what the axis is
y: {label: null, domain: [0, 1], ticks: [0, 1], tickFormat: d => d ? "on" : "off"},
marks: [
Plot.areaY(A.trace.filter(d => d[0] >= A.start), {x: d => d[0] - A.start, y: d => d[1], curve: "step-after", fill: "#e08a00", fillOpacity: 0.25}),
Plot.line(A.trace.filter(d => d[0] >= A.start), {x: d => d[0] - A.start, y: d => d[1], curve: "step-after", stroke: "#e08a00", strokeWidth: 1.6})
]
});
const pct = x => (100 * x).toFixed(0) + " %";
const nRecent = Math.round(1.5 * A.hz), recent = A.trace.slice(-nRecent); // the last 1.5 s of samples
const tw = (W2 - 2 * padR) / nRecent;
// the samples on a time axis: oldest on the left, now on the right, a tick every half second
const ax0 = padR, ax1 = W2 - padR, axY = 31;
const tickAt = [[0, "1.5 s ago"], [1 / 3, "1 s ago"], [2 / 3, "0.5 s ago"], [1, "now"]];
const ticks = htl.svg`<svg width="100%" viewBox="0 0 ${W2} 50" role="img" aria-label=${`The last ${nRecent} samples of the loop on a time axis, oldest on the left`}>
${recent.map((d, i) => htl.svg`<rect x=${padR + i * tw + 0.5} y="4" width=${Math.max(1, tw - 1.5)} height="20" rx="1"
fill=${d[1] ? "#e08a00" : "#dcdcdc"} />`)}
<line x1=${ax0} x2=${ax1 - 2} y1=${axY} y2=${axY} stroke="#6c757d" stroke-width="1" />
<polygon points=${`${ax1},${axY} ${ax1 - 8},${axY - 4} ${ax1 - 8},${axY + 4}`} fill="#6c757d" />
${tickAt.map(([f, label]) => htl.svg`<line x1=${ax0 + f * (ax1 - ax0)} x2=${ax0 + f * (ax1 - ax0)} y1=${axY - 4} y2=${axY + 4} stroke="#6c757d" stroke-width="1" />
<text x=${ax0 + f * (ax1 - ax0)} y="47" font-size="12" fill="#6c757d" text-anchor=${f === 0 ? "start" : f === 1 ? "end" : "middle"}>${label}</text>`)}
</svg>`;
return htl.html`<div class="pullbox loop-anim">${roadSvg}${W < 480 ? htl.html`<div class="loop-wiring">Wiring: loop → pull box → lead-in cable → cabinet (detector card)</div>` : ""}
<div class=${slide ? "loop-sig-pair" : ""}><div><div class="loop-sig-title">${slide ? `Asked ${A.hz} times a second: the last 1.5 s, ${nRecent} samples`
: `The controller asks ${A.hz} times a second: is a vehicle over the loop? (last 1.5 s: ${nRecent} samples)`}</div>${ticks}</div>
<div><div class="loop-sig-title">${slide ? `This ${A.period} s period: the next report counts these`
: `This ${A.period}-second period, sample by sample: the next report counts these`}</div>${sig}</div></div>
<div class="loop-dash">
<div class="dash-tile"><div class="dash-label">Vehicles this period</div><div class="dash-value">${A.count}</div></div>
<div class="dash-tile"><div class="dash-label">Samples hit</div><div class="dash-value">${A.hits.toLocaleString()} <small>of ${A.samples.toLocaleString()}</small></div>
<div class="dash-bar"><div style="width:${Math.min(100, A.samples / (A.period * A.hz) * 100).toFixed(1)}%"></div></div></div>
<div class="dash-tile"><div class="dash-label">Occupancy = hit ÷ taken</div><div class="dash-value">${pct(A.occ)}</div></div>
<div class="dash-tile dash-last"><div class="dash-label">Last report sent</div><div class="dash-value">${A.last
? htl.html`${A.last.count} <small>veh</small> · ${pct(A.last.occ)}` : htl.html`<small>after 30 s…</small>`}</div></div>
</div></div>`;
}How to read it
A loop is one sensor of many. Sort them all by two questions: where do they sit, and what do they see?
| Where they sit | Pavement: loops, tubes | Roadside: radar, video, LiDAR | Vehicle: phones, fleet GPS | Air: aircraft, drones |
| What they see | A point: counts, spot speeds | Two points: travel time | An area: all cars, one instant | A vehicle: its trajectory |
How to read it
How to read the picture: time runs to the right, position up the road. Each grey line is one car stopping at a red light and moving off.
| Sensor | Measures | Strength | Weakness |
|---|---|---|---|
| Inductive loop | count, occupancy | cheap, accurate | road must be cut |
| Magnetometer | count, occupancy | small, often wireless | battery life |
| Pneumatic tube | axles, vehicle class | cheap, portable | temporary only |
| Weigh-in-motion | axle weights | weighs trucks at speed | costly, needs calibration |
| Sensor | Measures | Strength | Weakness |
|---|---|---|---|
| Microwave radar | speed, counts by lane | all weather, many lanes | Doppler misses stopped cars |
| Video | counts, class, queues | rich information | glare, darkness, weather |
| LiDAR | exact positions | precise 3-D picture | cost; fog, heavy rain |
| Infrared | presence, speed | day and night | weather |
| Acoustic | presence, speed | passive, cheap | background noise |
| Sensor | Measures | Strength | Weakness |
|---|---|---|---|
| Bluetooth / Wi-Fi | travel time | cheap | few matches; random IDs |
| Toll-tag readers | travel time | high match rate | tagged vehicles only |
| Plate cameras | travel time, O–D | nearly every vehicle | privacy, misreads |
| Sensor | Measures | Strength | Weakness |
|---|---|---|---|
| GPS probes | speeds, travel times | wide coverage | sample bias |
| Connected vehicles | trajectories | rich, frequent | few vehicles yet |
| Drones | every trajectory | the whole time-space diagram | short flights |
| Aerial photos | density; speed from two photos | a whole stretch at once | one moment only |
| Floating car | travel time, delay | simple, direct | one vehicle’s view |
Almost every sensor in the catalogue watches one point, or two. Can we see a whole stretch at once? Go up.
Photo: NOAA (public domain).
More
A photo freezes one instant. What if the camera keeps watching?
Video: pNEUMA Vision dataset, Kim, Anagnostopoulos, Barmpounakis and Geroliminis (EPFL), CC BY 4.0.
More
A loop in the road and a drone overhead watch the same cars, and both report the average speed. They will not agree, and neither is wrong.
Before you watch: predict
Which reports the higher average speed: the loop or the drone? Or will they agree?
Two lanes, one loop, one drone. Watch both report the average speed.
// Two lanes with no lane changing; a loop at x0 averages the speeds of the cars that cross it,
// and a drone averages the speeds of all cars in view at each instant.
showdown = {
const Lr = 360, x0 = 180, lanes = [{v: 30, s: 60}, {v: 15, s: 40}];
const cars = [];
lanes.forEach((ln, li) => { for (let x = 0; x < Lr; x += ln.s) cars.push({x, lane: li, v: ln.v}); });
const dt = 1 / 60;
let t = 0, loopN = 0, loopSum = 0, droneSum = 0, droneN = 0;
const flash = [0, 0];
while (true) {
for (const c of cars) {
const xn = c.x + c.v * dt;
if (c.x < x0 && xn >= x0) { loopN++; loopSum += c.v; flash[c.lane] = 10; }
c.x = xn >= Lr ? xn - Lr : xn;
}
droneSum += cars.reduce((s, c) => s + c.v, 0) / cars.length; droneN++;
flash[0] = Math.max(0, flash[0] - 1); flash[1] = Math.max(0, flash[1] - 1);
t += dt;
yield {cars: cars.map(c => ({...c})), t, Lr, x0, flash: [...flash], loopN,
loop: loopN ? loopSum / loopN : NaN, drone: droneSum / droneN};
}
}// The two lanes under the drone, drawn from the simulation's current state. A function, so the
// "What just happened?" card can show the same live picture.
showdownView = (showdown, maxH = 190) => {
const narrow = plotW < 640, W = narrow ? plotW : 720, left = 20, right = W - 20, sc = (right - left) / showdown.Lr;
const laneY = [52, 92], H = 28;
const colors = ["#2a9d8f", "#e76f51"];
return htl.html`<div class="view-title"><b>Drone's view: the whole road, at one instant</b>
<span>top: 108 km/h, 60 m apart · bottom: 54 km/h, 40 m apart</span></div>${htl.svg`<svg width="100%" viewBox="0 18 ${W} 150" style=${document.querySelector(".reveal") ? `display: block; max-height: ${maxH}px; margin: 0 auto` : ""} role="img" aria-label="Two lanes of cars passing a loop detector under a drone">
<rect x=${left - 8} y="22" width=${right - left + 16} height="112" fill="none" stroke=${accent} stroke-width="2" stroke-dasharray="7 5" rx="6"/>
${laneY.map(y => htl.svg`<rect x=${left} y=${y - H / 2} width=${right - left} height=${H} fill="#8882"/>`)}
${laneY.map((y, li) => htl.svg`<rect x=${left + showdown.x0 * sc - 4} y=${y - H / 2} width="8" height=${H}
fill=${showdown.flash[li] ? "#ff9f1c" : "#ff9f1c55"} />`)}
${showdown.cars.map(c => htl.svg`<rect x=${left + c.x * sc} y=${laneY[c.lane] - 8} width=${Math.max(4, 4.5 * sc)} height="16" rx="3" fill=${colors[c.lane]} />`)}
<polygon points=${`${left + showdown.x0 * sc - 6},146 ${left + showdown.x0 * sc + 6},146 ${left + showdown.x0 * sc},137`} fill="#c77700" />
<text x=${left + showdown.x0 * sc} y="162" font-size="12" text-anchor="middle" fill="#c77700" font-weight="bold">loop detector</text>
</svg>`}`;
}md`<div class="grid">
<div class="g-col-12 g-col-md-6 card-lite"><b>Loop detector</b> (one point, over time)<br>
<span style="font-size:1.45rem;font-weight:800;color:#c77700">${showdown.loopN ? (showdown.loop * 3.6).toFixed(0) + " km/h" : "waiting…"}</span><br>
<small>${showdown.loopN} cars counted so far</small></div>
<div class="g-col-12 g-col-md-6 card-lite"><b>Drone</b> (the whole road, at an instant)<br>
<span style="font-size:1.45rem;font-weight:800;color:${accent}">${(showdown.drone * 3.6).toFixed(0)} km/h</span><br>
<small>average of every car in view</small></div>
</div>`Same cars, same moment, two different averages. Why?
{
// the two averages of the same cars: 108 km/h every 60 m and 54 km/h every 40 m (flows 1,800 and 1,350 veh/h)
const rows = [{who: "loop: time-mean", v: (1800 * 108 + 1350 * 54) / 3150, col: "#c77700"},
{who: "drone: space-mean", v: (1800 + 1350) / (1000 / 60 + 1000 / 40), col: accent}];
return Plot.plot({
width: plotW, height: 110, marginLeft: 130, marginRight: 60, style: {fontSize: "13px"},
x: {label: "Average speed (km/h)", domain: [0, 110], grid: true}, y: {label: null},
marks: [Plot.barX(rows, {y: "who", x: "v", fill: d => d.col}),
Plot.text(rows, {y: "who", x: "v", text: d => `${d.v.toFixed(0)} km/h`, dx: 6, textAnchor: "start", fontWeight: 700, fill: "currentColor"})]
});
}More
Both answers are right: the loop and the drone average over different things.
| Time-mean speed \(\bar v_t\) | Space-mean speed \(\bar v_s\) | |
|---|---|---|
| Watching | one point, over time | a stretch, at one instant |
| Like | loops, radar guns, cameras | drones, aerial photos |
Which one is “the” average speed? Try it on a trip you know.
Quick question
You drive 30 km to work at 30 km/h, and drive home at 60 km/h. What was your average speed?
Answer
Two lanes, with no lane changing. Set each lane’s speed and spacing, and see what each sensor reports.
viewof vA = knob({min: 5, max: 40, step: 1, value: 30, label: "Lane A speed", format: v => `${v} m/s`})
viewof sA = knob({min: 10, max: 120, step: 5, value: 60, label: "Lane A spacing", format: s => `${s} m`})
viewof vB = knob({min: 5, max: 40, step: 1, value: 15, label: "Lane B speed", format: v => `${v} m/s`})
viewof sB = knob({min: 10, max: 120, step: 5, value: 40, label: "Lane B spacing", format: s => `${s} m`})lanes = {
const qA = vA / sA, qB = vB / sB; // flow = speed / spacing (veh/s)
const kA = 1 / sA, kB = 1 / sB; // density = 1 / spacing (veh/m)
const vt = (qA * vA + qB * vB) / (qA + qB); // flow-weighted: what a point sensor sees
const vs = (kA * vA + kB * vB) / (kA + kB); // density-weighted: what a snapshot sees
const varS = (kA * (vA - vs) ** 2 + kB * (vB - vs) ** 2) / (kA + kB);
return {vt, vs, varS};
}{
const Lr = 500;
const cars = [];
for (let x = 0; x < Lr; x += sA) cars.push({x, lane: "Lane A"});
for (let x = 0; x < Lr; x += sB) cars.push({x, lane: "Lane B"});
const slide = !!document.querySelector(".reveal");
// the two lanes as a drone sees them, large, in a framed box under the controls
return htl.html`<div class="pullbox"><div class="pullbox-title">A drone's view: 500 m of road</div>${Plot.plot({
width: fullW - 40, height: slide ? 116 : 150, marginLeft: 84, marginRight: 24, marginTop: 10,
style: {fontSize: slide ? "18px" : "14px", width: "100%", height: "auto"}, // fills the box exactly
x: {label: null, domain: [0, Lr], ticks: 6, tickFormat: d => d === Lr ? `${d} m` : d},
y: {label: null, padding: 0.35},
marks: [
Plot.ruleY(["Lane A", "Lane B"], {stroke: "#e6e6e6", strokeWidth: slide ? 32 : 30}),
Plot.dot(cars.map(c => ({...c, x: c.x + 6})), {x: "x", y: "lane", r: slide ? 9 : 8, fill: d => d.lane === "Lane A" ? "#2a9d8f" : "#e76f51", stroke: "white"})
]
})}</div>`;
}md`<div class="grid">
<div class="g-col-12 g-col-md-6 card-lite"><b>Loop detector</b> (time-mean)<br>
<span style="font-size:1.45rem;font-weight:800;color:#c77700">${lanes.vt.toFixed(1)} m/s</span><br>
${(lanes.vt * 3.6).toFixed(0)} km/h</div>
<div class="g-col-12 g-col-md-6 card-lite"><b>Drone</b> (space-mean)<br>
<span style="font-size:1.45rem;font-weight:800;color:${accent}">${lanes.vs.toFixed(1)} m/s</span><br>
${(lanes.vs * 3.6).toFixed(0)} km/h</div>
</div>
Loop ÷ drone = **${(lanes.vt / lanes.vs).toFixed(2)}** · check: space-mean + variance ÷ space-mean = **${(lanes.vs + lanes.varS / lanes.vs).toFixed(1)} m/s**`How to read it
Now give every driver a speed of their own, and watch both averages build up, car by car.
wSim = {
// Three lanes. Every driver wants their own speed. Nobody drives through anybody: a faster car that
// catches up changes lanes if there is a gap, and otherwise follows the slower car until one opens.
// Both sensors record the speed each car actually has at that moment.
const S = wState, L = 400, x0 = 200, mean = 25, sd = wSpread, rate = 0.6, dt = 1 / 30;
const len = 5, gapAhead = 8, gapBehind = 6, lanes = 3;
let seed = 11;
const rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
const randn = () => Math.sqrt(-2 * Math.log(rnd())) * Math.cos(2 * Math.PI * rnd());
const bin = v => Math.min(S.bins.length - 1, Math.max(0, Math.floor((v - 8) / 2)));
let cars = [], t = 0, nextArrival = 0, nextSnap = 0;
const ahead = (c, lane) => cars.filter(o => o !== c && o.lane === lane && o.x >= c.x).sort((a, b) => a.x - b.x)[0];
const behind = (c, lane) => cars.filter(o => o !== c && o.lane === lane && o.x < c.x).sort((a, b) => b.x - a.x)[0];
const free = (c, lane) => {
const a = ahead(c, lane), b = behind(c, lane);
return (!a || a.x - len - c.x > gapAhead + 4) && (!b || c.x - len - b.x > gapBehind);
};
const step = record => {
while (t >= nextArrival) {
const v0 = Math.min(40, Math.max(8, mean + sd * randn()));
const open = d3.shuffle([0, 1, 2]).find(l => !cars.some(o => o.lane === l && o.x < len + gapAhead));
if (open !== undefined) cars.push({x: 0, v0, v: v0, lane: open});
nextArrival += -Math.log(1 - rnd()) / rate;
}
for (const c of [...cars].sort((a, b) => b.x - a.x)) { // front cars first
const a = ahead(c, c.lane);
const tooClose = a && a.x - len - c.x < gapAhead + Math.max(0, c.v0 - a.v) * 1.2;
if (tooClose && a.v < c.v0) {
const tryLanes = [c.lane - 1, c.lane + 1].filter(l => l >= 0 && l < lanes);
const to = tryLanes.find(l => free(c, l));
if (to !== undefined) { c.lane = to; c.v = c.v0; }
else c.v = Math.min(c.v0, a.v); // no gap: follow the slower car
} else c.v = c.v0;
}
for (const c of cars) {
const xn = c.x + c.v * dt;
if (record && c.x < x0 && xn >= x0) { S.loop[bin(c.v)]++; S.loopN++; S.loopSum += c.v; S.loopInv += 1 / c.v; }
c.x = xn;
}
cars = cars.filter(c => c.x < L + len);
if (record && t >= nextSnap) {
for (const c of cars) if (c.x < L) { S.drone[bin(c.v)]++; S.droneN++; S.droneSum += c.v; }
nextSnap += 1;
}
t += dt;
};
for (let k = 0; k < 30 / dt; k++) step(false); // warm up so the road is full
nextSnap = t;
let snap = null;
while (true) {
if (snap && viewof wPause.value) { yield snap; await Promises.delay(100); continue; } // paused: hold the picture
for (let k = 0; k < 3; k++) step(true);
S.t = t;
yield snap = {cars: cars.map(c => ({...c})), L, x0, len};
}
}{
const W = Math.max(300, fullW), left = 20, right = W - 20, sc = (right - left) / wSim.L; // drawn at the full width
const color = d3.scaleSequential(d3.interpolateRdYlGn).domain([8, 40]);
const laneH = 30, top = 22, carL = Math.max(14, wSim.len * sc), carH = 16;
const fs = document.querySelector(".reveal") ? 16 : 13; // the strip is drawn smaller on a slide: larger labels
const laneY = l => top + l * laneH;
return htl.svg`<svg width="100%" viewBox="0 0 ${W} ${top + 3 * laneH + (W < 560 ? 52 : 34)}" style=${document.querySelector(".reveal") ? "display: block; max-height: 118px; margin: 0 auto" : ""} role="img" aria-label="Three lanes of cars passing a loop; a drone sees the whole stretch">
<text x=${left} y="15" font-size=${fs} font-weight="bold" fill=${accent}>Drone's view: the whole 400 m stretch</text>
<rect x=${left} y=${top} width=${right - left} height=${3 * laneH} fill="#e4e4e4" />
${[1, 2].map(l => htl.svg`<line x1=${left} x2=${right} y1=${laneY(l)} y2=${laneY(l)} stroke="white" stroke-width="2" stroke-dasharray="14 10" />`)}
<line x1=${left} x2=${right} y1=${top} y2=${top} stroke="#999" stroke-width="1.2" />
<line x1=${left} x2=${right} y1=${top + 3 * laneH} y2=${top + 3 * laneH} stroke="#999" stroke-width="1.2" />
<rect x=${left + wSim.x0 * sc - 3} y=${top} width="6" height=${3 * laneH} fill="#ff9f1c" />
${wSim.cars.map(c => htl.svg`<rect x=${left + c.x * sc - carL} y=${laneY(c.lane) + (laneH - carH) / 2} width=${carL} height=${carH} rx="4"
fill=${color(c.v)} stroke="#333" stroke-width="1" />`)}
<rect x=${left - 6} y=${top - 4} width=${right - left + 12} height=${3 * laneH + 8} fill="none" stroke=${accent} stroke-width="2" stroke-dasharray="7 5" rx="6" />
<text x=${left + wSim.x0 * sc} y=${top + 3 * laneH + 20} font-size=${fs} text-anchor="middle" fill="#c77700" font-weight="bold">▲ loop</text>
<text x=${right} y=${top + 3 * laneH + (W < 560 ? 40 : 20)} font-size=${fs} text-anchor="end" fill="#6c757d">colour: speed (red slow, green fast)</text>
</svg>`;
}{
const S = wState;
while (true) {
const rows = S.bins.flatMap((b, i) => [
{v: b + 1, who: "Loop (in time)", p: S.loopN ? S.loop[i] / S.loopN : 0},
{v: b + 1, who: "Drone (in space)", p: S.droneN ? S.drone[i] / S.droneN : 0}]);
const means = [{who: "Loop (in time)", m: S.loopN ? S.loopSum / S.loopN : NaN},
{who: "Drone (in space)", m: S.droneN ? S.droneSum / S.droneN : NaN}];
const harmonic = S.loopN ? S.loopN / S.loopInv : NaN;
const f = x => isNaN(x) ? "…" : x.toFixed(1);
// the two histograms side by side: the drone on the left, the loop on the right
yield htl.html`<div><div class="fig-frame">${Plot.plot({
width: fullW - 40, height: !!document.querySelector(".reveal") ? 158 : 330, marginLeft: 50, marginTop: 28, marginBottom: 42, style: {fontSize: "12px"},
fx: {label: null, domain: ["Drone (in space)", "Loop (in time)"], padding: 0.12},
x: {label: "Speed (m/s)", labelAnchor: "center", domain: [8, 40]}, y: {label: fullW < 560 ? "Share" : "Share of cars", grid: true},
color: {domain: ["Loop (in time)", "Drone (in space)"], range: ["#c77700", accent]},
marks: [
Plot.rectY(rows, {x1: d => d.v - 1, x2: d => d.v + 1, y: "p", fx: "who", fill: "who", fillOpacity: 0.75}),
Plot.ruleX(means, {x: "m", fx: "who", stroke: ink, strokeWidth: 2}),
Plot.text(means, {x: "m", fx: "who", frameAnchor: "top", text: d => isNaN(d.m) ? "" : `mean ${d.m.toFixed(1)}`, dx: 6, textAnchor: "start", dy: 6})
]
})}<div class="fig-license">${trgyCopy} · CC BY-NC-SA 4.0</div></div>
${document.querySelector(".reveal") ? md`**Drone** (space-mean) <b style="color:${accent}">${f(means[1].m)} m/s</b> · **Loop** (time-mean) <b style="color:#c77700">${f(means[0].m)} m/s</b>, harmonic mean ${f(harmonic)} m/s · ${S.loopN} cars` : md`<div class="grid">
<div class="g-col-12 g-col-md-6 card-lite"><b>Drone</b> (space-mean: plain average)<br>
<span style="font-size:1.45rem;font-weight:800;color:${accent}">${f(means[1].m)} m/s</span><br>
every car in view, once a second</div>
<div class="g-col-12 g-col-md-6 card-lite"><b>Loop</b> (time-mean: plain average)<br>
<span style="font-size:1.45rem;font-weight:800;color:#c77700">${f(means[0].m)} m/s</span><br>
harmonic mean of the same speeds: <b>${f(harmonic)} m/s</b> · ${S.loopN} cars</div>
</div>`}</div>`;
await Promises.delay(400);
}
}How to read it
Since \(k_i v_i = q_i\), the numerator of the space-mean speed is just \(Q\):
\[ \begin{gathered} \bar v_s = \frac{\sum_i q_i}{K} = \frac{Q}{K} \\ \Longrightarrow\quad Q = K\,\bar v_s. \end{gathered} \]
The fundamental relation \(q = kv\) holds with the space-mean speed, and only with it.
Check with two lanes (24 m/s every 48 m, 12 m/s every 24 m): \(K = 1/48 + 1/24 = 1/16\) veh/m.
Total flow
\(Q\) = 1.0 veh/s
With the drone’s speed
\(K\,\bar v_s = 16/16\) = 1.0 \(\checkmark\)
With the loop’s speed
\(K\,\bar v_t = 18/16\) = 1.125 \(\times\)
Wardrop’s definitions tell us how to compute each mean from the data we actually have:
| Data collected… | Time-mean speed \(\bar v_t\) | Space-mean speed \(\bar v_s\) |
|---|---|---|
| at a point (\(N\) vehicles passing, speeds \(v_j\)) | arithmetic mean: \(\dfrac{1}{N}\sum_j v_j\) | harmonic mean: \(\dfrac{N}{\sum_j 1/v_j}\) |
| in space (\(N\) vehicles in a snapshot) | \(\dfrac{\sum_j v_j^2}{\sum_j v_j}\) | arithmetic mean: \(\dfrac{1}{N}\sum_j v_j\) |
A common misconception
“Arithmetic mean = time-mean, harmonic mean = space-mean.” Not in general.
We will prove \(\bar v_t = \bar v_s + \sigma_s^2/\bar v_s\), checking each step with two lanes: 24 m/s every 48 m, 12 m/s every 24 m.
Step 1. Write the time-mean speed in space terms. Substitute \(q_i = k_i v_i\):
\[ \begin{aligned} \bar v_t &= \frac{\sum_i q_i v_i}{\sum_i q_i} \\ &= \frac{\sum_i k_i v_i^2}{\sum_i k_i v_i}. \end{aligned} \]
In numbers: \(\dfrac{576/48 + 144/24}{24/48 + 12/24} = \dfrac{18}{1}\) = 18 m/s \(\checkmark\)
Step 2. Divide the top and bottom by \(K\). Both become averages over the space distribution \(f_i' = k_i/K\):
\[ \begin{aligned} \bar v_t &= \frac{\sum_i f_i' v_i^2}{\sum_i f_i' v_i} \\ &= \frac{\sum_i f_i' v_i^2}{\bar v_s}. \end{aligned} \]
In numbers: \(f_A' = 1/3\), \(f_B' = 2/3\): \(\dfrac{576/3 + 2 \cdot 144/3}{16} = \dfrac{288}{16}\) = 18 m/s \(\checkmark\)
Step 3. Expand around the mean. Write \(v_i = \bar v_s + (v_i - \bar v_s)\) and square:
\[ \begin{aligned} \textstyle\sum_i f_i' v_i^2 &= \bar v_s^2 \\ &\quad + 2\,\bar v_s \underbrace{\textstyle\sum_i f_i' (v_i - \bar v_s)}_{=\,0} \\ &\quad + \underbrace{\textstyle\sum_i f_i' (v_i - \bar v_s)^2}_{=\,\sigma_s^2}. \end{aligned} \]
Step 4. Put it together.
\[ \boxed{\;\begin{aligned} \bar v_t &= \frac{\bar v_s^2 + \sigma_s^2}{\bar v_s} \\ &= \bar v_s + \frac{\sigma_s^2}{\bar v_s} \end{aligned}\;} \]
In numbers: \(\sigma_s^2 = 32\), so \(256 + 32 = 288\) and \(16 + 32/16\) = 18 m/s \(\checkmark\)
More
Two lanes: equal flow, different speeds. What do the loop and the drone report?
1 · The loop (by flow)
\[ \begin{aligned} q_A &= 24/48 = 0.5 \\ q_B &= 12/24 = 0.5 \end{aligned} \]
\(\bar v_t =\) 18 m/s
2 · The drone (by density)
\[ \begin{aligned} f_A' &= 1/3 \\ f_B' &= 2/3 \end{aligned} \]
\(\bar v_s =\) 16 m/s
3 · Check (Wardrop)
\[ \begin{aligned} \sigma_s^2 &= 32 \\ \bar v_s + \sigma_s^2/\bar v_s &= 18 \end{aligned} \]
18 m/s \(\checkmark\)
How to read it
A loop watches one point; a snapshot, one moment. Edie (1965) asked: why not any region?
Pick a region \(A\) of the time-space diagram; add up the distance \(d(A)\) and time \(t(A)\) spent in it.
// three regions on the red-light trajectories of the next card: a loop, a snapshot, and an ellipse (any other shape)
{
const narrow = fullW < 640; // short labels on a phone, so none runs into a box
const regions = [
{t1: 4, t2: 86, x1: 146, x2: 154, c: "#c77700"},
{t1: 69, t2: 71, x1: 20, x2: 480, c: accent}
];
// the ellipse around the queue: centre 38 s, 260 m; half-widths 11 s and 55 m
const blob = d3.range(0, 1.0001, 0.02).map(f => {
const t = 27 + 22 * f, h = 55 * Math.sqrt(Math.max(0, 1 - ((t - 38) / 11) ** 2));
return {t, lo: 260 - h, hi: 260 + h};
});
// each label sits close to its shape, in empty space, with a short arrow to the shape's edge (never on the shape)
const labels = [
{t: 74, x: 112, text: narrow ? "loop" : "a loop: thin, long in time", c: "#c77700", a: "start"},
{t: 62.5, x: 60, text: narrow ? "snapshot" : "a snapshot: thin, long in space", c: accent, a: "end"},
{t: 20, x: 392, text: narrow ? "any shape" : "any other shape", c: ink, a: "middle"}
];
const arrows = [
{x1: 77, y1: 124, x2: 77, y2: 143, c: "#c77700"},
{x1: 63, y1: 60, x2: 68.4, y2: 60, c: accent},
{x1: 22, y1: 377, x2: 29.4, y2: 309, c: ink}
];
return htl.html`<div class="fig-frame">${Plot.plot({
width: fullW - 40, height: !!document.querySelector(".reveal") ? 240 : 340, marginTop: 24, marginRight: 20, marginBottom: 42,
style: {fontSize: "13px"},
x: {label: "Time (s)", labelAnchor: "center", domain: [0, 90]}, y: {label: "Position (m)", domain: [0, 500]},
color: {type: "sequential", scheme: "RdYlGn", domain: [0, 15]},
marks: [
Plot.line(edieSim.rows, {x: "t", y: "x", z: "car", stroke: "v", strokeWidth: 1}),
Plot.rect(regions, {x1: "t1", x2: "t2", y1: "x1", y2: "x2", fill: "c", fillOpacity: 0.16, stroke: "c", strokeWidth: 2}),
Plot.areaY(blob, {x: "t", y1: "lo", y2: "hi", fill: ink, fillOpacity: 0.12, stroke: ink, strokeWidth: 2}),
Plot.arrow(arrows, {x1: "x1", y1: "y1", x2: "x2", y2: "y2", stroke: "c", strokeWidth: 1.6, headLength: 8}),
// textAnchor is not a channel: one text mark per anchor
...["start", "end", "middle"].map(an => Plot.text(labels.filter(d => d.a === an), {x: "t", y: "x", text: "text", fill: "c", textAnchor: an,
fontWeight: "bold", fontSize: 14, stroke: halo, strokeWidth: 4, paintOrder: "stroke"}))
]
})}<div class="fig-license">${trgyCopy} · CC BY-NC-SA 4.0</div></div>`;
}Flow \(\displaystyle q(A) = \frac{d(A)}{|A|}\)
Density \(\displaystyle k(A) = \frac{t(A)}{|A|}\)
Speed \(\displaystyle v(A) = \frac{d(A)}{t(A)}\)
How to read it
Draw a box anywhere on the time-space diagram: Edie gives its flow, density and speed.
// The red-light scenario of Lecture 1, with twelve cars.
edieSim = {
const v0 = 15, T = 1.2, s0 = 2, a = 1.5, b = 2, lc = 5, dt = 0.1, stop = 300, red = [16, 46], n = 12;
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 >= 3 * 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]});
}
const cars = d3.groups(rows, r => r.car).map(([, rs]) => rs);
return {rows, cars, dtSample: 0.2};
}// Edie's d(A) and t(A), exact: each trajectory is a chain of straight pieces between samples, clipped to the box.
edieRegion = {
const size = {"Square": [20, 100], "Thin and long in time (a loop)": [80, 10], "Thin and long in space (a snapshot)": [2, 440]}[edieShape];
const t1 = Math.max(0, edieT - size[0] / 2), t2 = Math.min(90, edieT + size[0] / 2);
const x1 = Math.max(0, edieX - size[1] / 2), x2 = Math.min(500, edieX + size[1] / 2);
const xc = (x1 + x2) / 2, tc = (t1 + t2) / 2;
let dA = 0, tA = 0;
const crossing = [], snapshot = [], inside = [];
for (const car of edieSim.cars) {
for (let j = 1; j < car.length; j++) {
const a = car[j - 1], b = car[j], dt = b.t - a.t, dx = b.x - a.x;
let lo = Math.max(0, (t1 - a.t) / dt), hi = Math.min(1, (t2 - a.t) / dt);
if (dx > 1e-9) { lo = Math.max(lo, (x1 - a.x) / dx); hi = Math.min(hi, (x2 - a.x) / dx); }
else if (a.x < x1 || a.x >= x2) hi = -1;
if (hi > lo) {
tA += (hi - lo) * dt; dA += (hi - lo) * dx;
inside.push({id: `${a.car}-${j}`, t: a.t + lo * dt, x: a.x + lo * dx}, {id: `${a.car}-${j}`, t: a.t + hi * dt, x: a.x + hi * dx});
}
// the loop: speed of each car as it crosses the middle line inside the time window
if (a.x < xc && b.x >= xc) {
const u = (xc - a.x) / dx, t = a.t + u * dt;
if (t >= t1 && t < t2) crossing.push(a.v + u * (b.v - a.v));
}
// the snapshot: speed of each car inside the box at the middle instant
if (a.t <= tc && b.t > tc) {
const u = (tc - a.t) / dt, x = a.x + u * dx;
if (x >= x1 && x < x2) snapshot.push(a.v + u * (b.v - a.v));
}
}
}
const area = (t2 - t1) * (x2 - x1);
const mean = s => s.length ? d3.mean(s) * 3.6 : NaN;
const harm = s => s.length && s.every(v => v > 0) ? s.length / d3.sum(s, v => 1 / v) * 3.6 : NaN;
return {t1, t2, x1, x2, q: dA / area * 3600, k: tA / area * 1000, v: tA > 0 ? dA / tA * 3.6 : NaN,
crossing, snapshot, inside, cross: {plain: mean(crossing), harm: harm(crossing)}, snap: {plain: mean(snapshot), harm: harm(snapshot)}};
}viewof edieShape = seg(["Square", "Thin and long in time (a loop)", "Thin and long in space (a snapshot)"], {value: "Thin and long in time (a loop)", label: "Box shape",
format: d => d === "Square" ? "Square" : d.includes("loop") ? "Loop" : "Snapshot"})
viewof edieT = knob({min: 5, max: 85, step: 1, value: 55, label: "Centre time", format: t => `${t} s`})
viewof edieX = knob({min: 40, max: 460, step: 5, value: 235, label: "Centre position", format: x => `${x} m`})// right panel: the time-space diagram, tall enough that the trajectories keep their true shape;
// the speed legend sits in the top right corner, beside the axis label, so it costs no height
htl.html`<div class="split-plot"><div class="corner-legend">${Plot.legend({color: {type: "sequential", scheme: "RdYlGn", domain: [0, 15], label: "Speed (m/s)"},
width: 240, marginLeft: 10, marginRight: 16, style: {fontSize: "13px"}})}</div>${Plot.plot({
// the full width of the box, under (web) or above (slides) the controls: .split-box is one column (2026-10-11)
width: !!document.querySelector(".reveal") ? fullW - 50 : Math.max(240, fullW - 34),
height: !!document.querySelector(".reveal") ? 230 : 420, marginTop: 48, marginBottom: 40, style: {fontSize: "13px"},
x: {label: "Time (s)", labelOffset: 34, domain: [0, 90]},
y: {label: "Position (m)", domain: [0, 500]},
color: {type: "sequential", scheme: "RdYlGn", domain: [0, 15]},
marks: [
Plot.line(edieSim.rows, {x: "t", y: "x", z: "car", stroke: "v", strokeWidth: 1}),
Plot.rect([edieRegion], {x1: "t1", x2: "t2", y1: "x1", y2: "x2", fill: edieShape.includes("loop") ? "#c77700" : accent, fillOpacity: 0.22, stroke: edieShape.includes("loop") ? "#c77700" : accent, strokeWidth: 2}),
Plot.line(edieRegion.inside, {x: "t", y: "x", z: "id", stroke: ink, strokeWidth: 2.5}), // what d(A) and t(A) add up
Plot.text([edieRegion], {x: "t2", y: "x2", text: () => "A", dx: 8, dy: -8, fill: accent, fontWeight: "bold", fontSize: 16})
]
})}</div>`{
const r = edieRegion, f = x => isNaN(x) ? "—" : x.toFixed(1);
const loop = edieShape.includes("loop"), snap = edieShape.includes("snapshot");
const testLabel = loop ? `Harmonic mean of the ${r.crossing.length} crossing speeds` : snap ? `Plain average of the ${r.snapshot.length} cars in view` : "A square is neither";
const testValue = loop ? htl.html`${f(r.cross.harm)} <small>km/h</small>` : snap ? htl.html`${f(r.snap.plain)} <small>km/h</small>` : htl.html`<small>no single average</small>`;
const other = loop ? `plain mean ${f(r.cross.plain)} km/h` : snap ? `harmonic ${f(r.snap.harm)} km/h` : "v(A) weighs each car by its time in the box";
return htl.html`<div class="loop-dash">
<div class="dash-tile"><div class="dash-label">Flow q</div><div class="dash-value">${r.q.toFixed(0)} <small>veh/h</small></div></div>
<div class="dash-tile"><div class="dash-label">Density k</div><div class="dash-value">${r.k.toFixed(1)} <small>veh/km</small></div></div>
<div class="dash-tile dash-last"><div class="dash-label">Speed v(A)</div><div class="dash-value">${f(r.v)} <small>km/h</small></div></div>
<div class="dash-tile"><div class="dash-label">${testLabel}</div><div class="dash-value">${testValue}</div><div class="dash-label">${other}</div></div>
</div>`;
}How to read it
More
A loop stands at one point, yet occupancy measures space. Vehicle \(j\) covers it for \(\tau_j = (d + \ell_j)/\dot x_j\) seconds:
Over \(T\) seconds, \(N\) vehicles pass. Occupancy is their pulses added up, divided by \(T\):
\[ o = \frac{1}{T}\sum_{j=1}^{N} \tau_j \]
Put in each \(\tau_j\):
\[ o = \frac{1}{T}\sum_{j=1}^{N} \frac{d + \ell_j}{\dot x_j}. \]
How to read it
Take every vehicle as the same length, \(\ell_j \approx \ell\), and the sum becomes an average of \(1/\text{speed}\):
Step 1. Equal lengths:
\[ o \approx (d + \ell)\,\frac{1}{T}\sum_{j=1}^{N}\frac{1}{\dot x_j} \]
Step 2. Multiply and divide by \(N\):
\[ o \approx (d + \ell)\,\underbrace{\frac{N}{T}}_{q}\,\underbrace{\frac{1}{N}\sum_{j=1}^{N}\frac{1}{\dot x_j}}_{1/\bar v_s} \]
Step 3. Use \(q = k\,\bar v_s\):
\[ o \approx (d + \ell)\,\frac{q}{\bar v_s} = (d + \ell)\,k. \]
In numbers: a 1.8 m loop and 4.5 m cars, \(d + \ell = 6.3\) m; occupancy \(o = 0.12\): \(k = 0.12 / 0.0063\) km \(=\) 19 veh/km
How to read it
Occupancy assumed equal lengths. Nobody slows down: add trucks, and watch the loop’s speed estimate fall.
loopLive = {
const v = 20, L = 360, x0 = 200, d = 1.8, dt = 1 / 30, rate = 0.45, p = loopTrucks / 100, period = 30;
let veh = [], t = 0, nextArrival = 0, occTime = 0, count = 0, periodStart = 0;
const reports = [];
while (true) {
if (viewof trucksPause.value) { await Promises.delay(100); continue; } // paused: hold the picture
for (let s = 0; s < 4; s++) {
if (t >= nextArrival) {
const len = Math.random() < p ? 18 : 5;
const last = veh[veh.length - 1];
if (!last || last.x - last.len > 8) veh.push({x: 0, len, truck: len > 5});
nextArrival = t - Math.log(1 - Math.random()) / rate;
}
let over = false;
for (const c of veh) {
const xn = c.x + v * dt;
if (c.x < x0 && xn >= x0) count++;
c.x = xn;
if (c.x >= x0 && c.x - c.len <= x0 + d) over = true;
}
if (over) occTime += dt;
veh = veh.filter(c => c.x - c.len < L);
t += dt;
if (t - periodStart >= period) {
const o = occTime / period, q = count / period * 3600, kEst = o / (5 + d) * 1000; // veh/h and veh/km, so q / kEst is in km/h
reports.unshift({time: Math.round(t), count, occ: o, q, vEst: kEst > 0 ? q / kEst : NaN});
if (reports.length > 5) reports.pop();
occTime = 0; count = 0; periodStart = t;
}
}
yield {veh: veh.map(c => ({...c})), over: veh.some(c => c.x >= x0 && c.x - c.len <= x0 + d), reports: reports.slice(), L, x0};
}
}{
const W = Math.max(320, fullW - 40), left = 20, right = W - 20, sc = (right - left) / loopLive.L;
return htl.html`<div class="pullbox"><div class="pullbox-title">One lane at a steady 72 km/h over a 1.8 m loop</div>${htl.svg`<svg width="100%" viewBox="0 0 ${W} 74">
<rect x=${left} y="20" width=${right - left} height="28" fill="#8882" />
<rect x=${left + loopLive.x0 * sc - 3} y="16" width="6" height="36" fill=${loopLive.over ? "#ff9f1c" : "#ff9f1c55"} />
${loopLive.veh.map(c => htl.svg`<rect x=${left + (c.x - c.len) * sc} y="26" width=${Math.max(3, c.len * sc)} height="16" rx="3" fill=${c.truck ? "#6c757d" : "#2a9d8f"} />`)}
<text x=${left + loopLive.x0 * sc} y="66" font-size="12" text-anchor="middle" fill="#c77700" font-weight="bold">loop</text>
<text x=${right} y="12" font-size="12" text-anchor="end" fill="gray">green: 5 m cars · grey: 18 m trucks</text>
</svg>`}</div>`;
}{
const R = loopLive.reports, r = R[0];
if (!r) return htl.html`<div class="loop-dash"><div class="dash-tile"><div class="dash-label">First 30-second report</div><div class="dash-value"><small>on its way…</small></div></div></div>`;
const earlier = R.slice(1).map(x => isNaN(x.vEst) ? "—" : x.vEst.toFixed(0)).join(", ");
return htl.html`<div class="loop-dash">
<div class="dash-tile"><div class="dash-label">Count (last 30 s)</div><div class="dash-value">${r.count}</div></div>
<div class="dash-tile"><div class="dash-label">Occupancy</div><div class="dash-value">${(100 * r.occ).toFixed(1)} <small>%</small></div></div>
<div class="dash-tile"><div class="dash-label">Speed the loop reports</div><div class="dash-value">${isNaN(r.vEst) ? "—" : r.vEst.toFixed(0)} <small>km/h</small></div>
<div class="dash-label">${earlier ? `earlier reports: ${earlier}` : ""}</div></div>
<div class="dash-tile dash-last"><div class="dash-label">True speed</div><div class="dash-value">72 <small>km/h</small></div></div>
</div>`;
}How to read it
Navigation apps estimate speed from the phones that send them GPS pings. How good is that estimate?
// 300 simulated five-minute periods of 180 vehicles each. The app's estimate is the harmonic mean
// of the app users' speeds (pings arrive in proportion to time spent on the road).
probe = {
probeRun;
const randn = () => Math.sqrt(-2 * Math.log(1 - Math.random())) * Math.cos(2 * Math.PI * Math.random());
const rows = [];
let none = 0;
for (let r = 0; r < 300; r++) {
let inv = 0, invApp = 0, nApp = 0;
for (let i = 0; i < 180; i++) {
const app = Math.random() < pen / 100;
let v = Math.min(40, Math.max(8, 25 + 7 * randn()));
if (app) v *= 1 + appBias / 100;
inv += 1 / v;
if (app) { invApp += 1 / v; nApp++; }
}
if (nApp === 0) { none++; continue; }
rows.push({r, err: (nApp / invApp - 180 / inv) * 3.6});
}
const rmse = Math.sqrt(d3.mean(rows, d => d.err ** 2));
return {rows, none, rmse, bias: d3.mean(rows, d => d.err)};
}htl.html`<div class="pullbox"><div class="pullbox-title">300 five-minute periods, 180 vehicles each</div>${Plot.plot({
width: fullW - 40, height: !!document.querySelector(".reveal") ? 200 : 260, marginBottom: 40, style: {fontSize: "13px"},
x: {label: fullW < 640 ? "App minus true speed (km/h)" : "App estimate minus true space-mean speed (km/h) · one dot per five-minute period",
domain: [-40, 40], labelOffset: 34},
y: {axis: null},
marks: [
Plot.ruleX([0], {stroke: ink, strokeWidth: 2}),
Plot.dot(probe.rows, Plot.dodgeY({x: "err", r: !!document.querySelector(".reveal") ? 3.6 : 3, fill: accent, fillOpacity: 0.6})),
]
})}</div>`htl.html`<div class="loop-dash">
<div class="dash-tile"><div class="dash-label">Typical error (noise)</div><div class="dash-value">± ${probe.rmse.toFixed(1)} <small>km/h</small></div></div>
<div class="dash-tile dash-last"><div class="dash-label">Average error (bias)</div><div class="dash-value">${probe.bias >= 0 ? "+" : ""}${probe.bias.toFixed(1)} <small>km/h</small></div></div>
<div class="dash-tile"><div class="dash-label">Periods with no app user</div><div class="dash-value">${probe.none} <small>of 300</small></div></div>
</div>`How to read it
More
A sign turns the loop’s average speed into a travel time for 640 m of US-101. Drivers take 66 s. What does the sign say?
viewof raceGo = {
const w = htl.html`<span class="run-pause-wrap"><button type="button" class="pill-btn">▶ Race</button></span>`;
const b = w.querySelector("button");
w.value = 0;
b.onclick = () => { w.value++; b.textContent = "↻ Race again"; w.dispatchEvent(new Event("input", {bubbles: true})); };
return w;
}// two cars drive the 640 m section: one at the loop's speed, one at the true (space-mean) speed; 6x real time
raceView = {
const W = Math.max(320, fullW - 40), L = 120, R = W - 70, sc = (R - L) / 640, speedUp = 6;
const rows = [{name: "Sign says", v: 44.6 / 3.6, T: 52, c: "#c77700"}, {name: "Real drivers", v: 35.0 / 3.6, T: 66, c: accent}];
const draw = t => htl.svg`<svg width="100%" viewBox="0 0 ${W} 128" style="" role="img" aria-label="Two cars race over 640 m: the loop's speed arrives at 52 s, the real drivers at 66 s">
<text x=${L} y="16" font-size="13" fill="#6c757d">start</text><text x=${R} y="16" font-size="13" fill="#6c757d" text-anchor="end">640 m</text>
<line x1=${R} x2=${R} y1="22" y2="108" stroke="#333" stroke-width="1.5" stroke-dasharray="4 3" />
${rows.map((r, i) => {
const y = 26 + i * 42, x = L + Math.min(640, r.v * t) * sc, done = t >= r.T;
return htl.svg`<g>
<text x="0" y=${y + 21} font-size="15" font-weight="bold" fill=${r.c}>${r.name}</text>
<rect x=${L} y=${y} width=${R - L} height="32" fill="#e4e4e4" />
<line x1=${L} x2=${x} y1=${y + 16} y2=${y + 16} stroke=${r.c} stroke-width="2" stroke-opacity="0.5" />
<rect x=${x - 34} y=${y + 6} width="34" height="20" rx="5" fill=${r.c} stroke="#333" stroke-width="1" />
<text x=${R + 8} y=${y + 21} font-size="16" font-weight="bold" fill=${r.c}>${done ? `${r.T} s` : ""}</text>
</g>`;
})}
<text x=${W / 2} y="124" font-size="14" text-anchor="middle" fill="currentColor">clock: <tspan font-weight="bold">${Math.min(t, 66).toFixed(0)} s</tspan>${t >= 66 ? " · the sign was 14 s short" : ""}</text>
</svg>`;
raceGo; // re-run on every press
if (raceGo === 0) { yield draw(0); return; }
const t0 = performance.now();
while (true) {
const t = (performance.now() - t0) / 1000 * speedUp;
yield draw(t);
if (t >= 66) break;
await Promises.delay(40);
}
}htl.html`<div class="fig-frame" style="margin-top: 0.45rem !important"><div class="knob-row">${viewof raceGo}<span>Predict first. Top: the sign, at the loop's speed. Bottom: real drivers.</span></div>${raceView}<div class="fig-license">Data: NGSIM US-101, 8:00 a.m. · ${trgyCopy} · CC BY-NC-SA 4.0</div></div>`Loop (time-mean) 44.6 km/h
predicts 52 s: what the sign says
Edie (space-mean) 35.0 km/h
predicts 66 s: what drivers took
Take-home: the sign says 52 s: the loop underestimates travel time by a fifth.
The sign needs the space-mean speed, which a drone sees. But drone video is only pixels: AI turns it into trajectories.
Video: the Athens drone video with every vehicle detected and tracked by computer vision (pNEUMA Vision, EPFL, CC BY 4.0).
More
LiDAR times laser echoes to map the road in 3-D.
Predict which cars can the black car not see? Then press Reveal.
lidar = {
lidarSeed;
let seed = 7 + 104729 * lidarSeed;
const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
const lanes = [-5.25, -1.75, 1.75, 5.25], X = 60, R = 50; // four 3.5 m lanes, 120 m of road, 50 m range
const cars = [];
for (const y of lanes) {
let x = -X + rnd() * 8;
while (x < X) {
const truck = rnd() < 0.12, len = truck ? 14 : 4.6, wid = truck ? 2.6 : 1.9;
if (!(y === 1.75 && Math.abs(x + len / 2) < 6)) cars.push({x, y, len, wid, truck});
x += len + 4 + rnd() * 16;
}
}
const ego = {x: -2.3, y: 1.75, len: 4.6, wid: 1.9};
// ray casting in 2-D: each beam stops at the first car it meets (slab test against the car's box)
const hits = [], rays = [];
for (let k = 0; k < 720; k++) {
const a = k * Math.PI / 360, dx = Math.cos(a), dy = Math.sin(a);
let best = R, who = -1;
cars.forEach((c, i) => {
const x0 = c.x, x1 = c.x + c.len, y0 = c.y - c.wid / 2, y1 = c.y + c.wid / 2;
const tx0 = dx ? (x0 - 0) / dx : -Infinity, tx1 = dx ? (x1 - 0) / dx : Infinity;
const ty0 = dy ? (y0 - 1.75) / dy : -Infinity, ty1 = dy ? (y1 - 1.75) / dy : Infinity;
const tin = Math.max(Math.min(tx0, tx1), Math.min(ty0, ty1)), tout = Math.min(Math.max(tx0, tx1), Math.max(ty0, ty1));
if (dx === 0 && (0 < x0 || 0 > x1)) return;
if (dy === 0 && (1.75 < y0 || 1.75 > y1)) return;
if (tin <= tout && tin > 0 && tin < best) { best = tin; who = i; }
});
rays.push({x: best * dx, y: 1.75 + best * dy});
if (who >= 0) { hits.push({x: best * dx, y: 1.75 + best * dy}); cars[who].n = (cars[who].n || 0) + 1; }
}
const inRange = cars.filter(c => Math.hypot(c.x + c.len / 2, c.y - 1.75) <= R);
return {cars, inRange, hits, rays, ego, X, R, lanes, hidden: inRange.filter(c => !c.n).length};
}{
const W = 720, H = 172, sx = W / (2 * lidar.X), y0 = H / 2, sy = sx; // metres -> pixels
const px = x => (x + lidar.X) * sx, py = y => y0 - (y - 0) * sy * 1.6; // lanes drawn 1.6x wider
const shown = lidarShow, grey = "#9a9a9a";
const inR = c => Math.hypot(c.x + c.len / 2, c.y - 1.75) <= lidar.R;
const carColor = c => !shown || !inR(c) ? grey : (c.n ? "#1a9850" : "#a50026");
return htl.html`<div class="pullbox"><div class="pullbox-title">A self-driving car (the one not in grey) and the traffic around it, seen from above</div>${htl.svg`<svg width="100%" viewBox="0 0 ${W} ${H}" style="display: block; max-height: ${document.querySelector(".reveal") ? 222 : 250}px; margin: 0 auto" role="img" aria-label="Top view of a four-lane road with a self-driving car whose LiDAR beams are blocked by nearby vehicles">
<rect x="0" y="${py(7)}" width="${W}" height="${py(-7) - py(7)}" fill="#8882"/>
${[-3.5, 3.5].map(y => htl.svg`<line x1="0" x2="${W}" y1="${py(y)}" y2="${py(y)}" stroke="#bbb" stroke-dasharray="8 8"/>`)}
<line x1="0" x2="${W}" y1="${py(0)}" y2="${py(0)}" stroke="#e0b000" stroke-width="2"/>
${shown ? lidar.rays.filter((r, i) => i % 3 === 0).map(r => htl.svg`<line x1="${px(0)}" y1="${py(1.75)}" x2="${px(r.x)}" y2="${py(r.y)}" stroke="${accent}" stroke-opacity="0.12"/>`) : ""}
<circle cx="${px(0)}" cy="${py(1.75)}" r="${lidar.R * sx}" fill="none" stroke="${grey}" stroke-dasharray="3 4"/>
${lidar.cars.map(c => htl.svg`<rect x="${px(c.x)}" y="${py(c.y + c.wid / 2)}" width="${c.len * sx}" height="${c.wid * sy * 1.6}" rx="2"
fill="${carColor(c)}" fill-opacity="${shown && !c.n && inR(c) ? 0.25 : 0.85}" stroke="${carColor(c)}" stroke-dasharray=${shown && !c.n && inR(c) ? "3 2" : null} />`)}
<rect x="${px(lidar.ego.x)}" y="${py(1.75 + lidar.ego.wid / 2)}" width="${lidar.ego.len * sx}" height="${lidar.ego.wid * sy * 1.6}" rx="2" fill="${ink}"/>
${shown ? lidar.hits.map(h => htl.svg`<circle cx="${px(h.x)}" cy="${py(h.y)}" r="1.6" fill="${accent}"/>`) : ""}
</svg>`}</div>`;
}htl.html`<div class="loop-dash">
<div class="dash-tile"><div class="dash-label">Vehicles within 50 m (dashed circle)</div><div class="dash-value">${lidar.inRange.length}</div></div>
<div class="dash-tile dash-last"><div class="dash-label">Completely hidden: no beam reaches them</div><div class="dash-value">${lidarShow
? htl.html`${lidar.hidden} <small>(red, dashed)</small>` : htl.html`<small>? press Reveal</small>`}</div></div>
</div>`How to read it
More
A program reads real LiDAR points and boxes every vehicle it finds: out of every 100 vehicles, how many does it miss?
Source: Zhu and Feng, TR-C 194 (2027), online 2026.
How to read it
Predict how many people are at this corner? Then reveal what LiDAR sees.
How to read it
Predict a loop saw 12 cars and nothing unusual. How many near misses did a camera see?
viewof nmShow = {
const w = htl.html`<span><button type="button" class="pill-btn">Reveal what the camera sees</button></span>`;
const b = w.querySelector("button");
w.value = false;
b.onclick = () => { w.value = !w.value; b.textContent = w.value ? "Show only the loop" : "Reveal what the camera sees";
w.dispatchEvent(new Event("input", {bubbles: true})); };
return w;
}
// Six simulated car pairs. The leader drives at 36 km/h; the follower comes up at 72 km/h, 60 m behind, and brakes
// (5 m/s²) once its time-to-collision falls to tb, slows to 29 km/h until the gap is back to 22 m, then matches the
// leader. Three followers brake late: their TTC dips under 1.5 s about 100 m along, long before the loop at 400 m.
nearMiss = {
const Lc = 4.5, dt = 0.05, loopX = 400, tbs = [4.0, 1.3, 3.2, 1.15, 2.6, 1.45];
const pairs = tbs.map((tb, k) => {
const t0 = 10 * k, lead = [], foll = [];
let xL = 60 + Lc, xF = 0, vF = 20, ph = 0, t = 0, mn = {ttc: Infinity}, cross = {};
while (t <= 40) {
const gap = xL - Lc - xF, c = vF - 10;
if (c > 0 && gap / c < mn.ttc) mn = {ttc: gap / c, t: t0 + t, x: xF};
if (ph === 0 && c > 0 && gap / c <= tb) ph = 1;
if (ph === 1) { vF -= 5 * dt; if (vF <= 8) { vF = 8; ph = 2; } }
if (ph === 2 && gap >= 22) ph = 3;
if (ph === 3) vF = Math.min(10, vF + dt);
if (cross.L === undefined && xL >= loopX) cross.L = t0 + t;
if (cross.F === undefined && xF >= loopX) cross.F = t0 + t;
if (Math.round(t / dt) % 10 === 0) { lead.push({k, t: t0 + t, x: xL}); foll.push({k, t: t0 + t, x: xF}); }
xL += 10 * dt; xF += vF * dt; t += dt;
}
return {k, lead: lead.filter(d => d.x <= 450), foll: foll.filter(d => d.x <= 450), mn, headway: cross.F - cross.L, cross};
});
return {pairs, loopX};
}nmView = {
const colours = ["#4e79a7", "#59a14f", "#b07aa1", "#9c755f", "#76b7b2", "#edc948"]; // one colour per pair; red and orange stay free
const {pairs, loopX} = nearMiss, slide = !!document.querySelector(".reveal");
const misses = pairs.filter(p => p.mn.ttc <= 1.5);
const ticks = pairs.flatMap(p => [{t: p.cross.L, k: p.k}, {t: p.cross.F, k: p.k}]);
const hw = d3.extent(pairs, p => p.headway);
const plot = Plot.plot({
width: fullW - 30, height: slide ? 300 : 260, marginLeft: 44, marginRight: 14, marginBottom: 38, style: {fontSize: "13px"},
x: {domain: [0, 90], label: "time (s) →", labelOffset: 34}, y: {domain: [0, 450], label: "↑ position (m)"},
marks: [
Plot.ruleY([loopX], {stroke: "#c77700", strokeWidth: 3}),
Plot.text([loopX], {x: 1, y: loopX, text: () => "loop", dy: -9, textAnchor: "start", fill: "#c77700", fontWeight: "bold", fontSize: 14}),
nmShow ? Plot.line(pairs.flatMap(p => p.lead), {x: "t", y: "x", z: "k", stroke: d => colours[d.k], strokeWidth: 1.5}) : null,
nmShow ? Plot.line(pairs.flatMap(p => p.foll), {x: "t", y: "x", z: "k", stroke: d => colours[d.k], strokeWidth: 1.5, strokeDasharray: "5 3"}) : null,
Plot.link(ticks, {x1: "t", x2: "t", y1: loopX - 14, y2: loopX + 14, stroke: "#333", strokeWidth: 2}),
nmShow ? null : Plot.text(["What happened before the loop? The loop cannot tell."], {x: 45, y: 200, text: d => d, fill: "#999", fontSize: 15, fontStyle: "italic", lineWidth: fullW < 600 ? 13 : 40}), // wraps on a phone
nmShow ? Plot.dot(misses.map(p => p.mn), {x: "t", y: "x", r: 8, fill: "#d62728", stroke: "white", strokeWidth: 2}) : null,
nmShow ? Plot.text(misses.map(p => p.mn), {x: "t", y: "x", text: d => `TTC ${d.ttc.toFixed(1)} s`, dx: 10, dy: 14, textAnchor: "start", fill: "#d62728", fontWeight: "bold", fontSize: 13}) : null
]
});
const read = nmShow
? htl.html`<b style="color:#d62728">Camera: ${misses.length} near misses</b> (TTC under 1.5 s), all about ${Math.round(d3.mean(misses, p => p.mn.x) / 10) * 10} m along: ${loopX - Math.round(d3.mean(misses, p => p.mn.x) / 10) * 10} m before the loop`
: htl.html`<b style="color:#c77700">Loop:</b> 12 vehicles, all at 36 km/h, headways ${hw[0].toFixed(1)} to ${hw[1].toFixed(1)} s: <b>nothing unusual</b>`;
return htl.html`<div class="fig-frame"><div class="knob-row">${viewof nmShow}</div>${plot}<div class="loop-readout">${read}</div><div class="fig-license">Simulated car pairs · ${trgyCopy} · CC BY-NC-SA 4.0</div></div>`;
}How to read it
Now avoid the crash yourself. Game: a car at 90 km/h closes on a truck at 36 km/h. Press Brake! as late as you dare.
// Brake in time. The car brakes hard (6 m/s²) from 25 m/s until it matches the truck's 10 m/s. It closes
// (15 m/s)² / (2 · 6 m/s²) = 18.75 m while braking, so a brake at a time-to-collision under 15 / (2 · 6) = 1.25 s
// ends in a crash; from 1.25 s to 1.5 s it ends without one, but counts as a near miss (TTC ≤ 1.5 s).
ttcGame = {
const vF0 = 25, vL = 10, b = 6, carL = 4.5, truckL = 12, crit = 1.5, ttcMax = 4;
const W = Math.max(300, fullW - 40), L = 8, R = W - 8, view = 112, sc = (R - L) / view, rear = 98; // the truck's rear at 98 m of a 112 m window
const gx = t => L + Math.min(t, ttcMax) / ttcMax * (R - L); // the TTC gauge
const carC = accent, truckC = "#1f77b4";
const svg = htl.svg`<svg width="100%" viewBox="0 0 ${W} 112" style="display: block" role="img" aria-label="A car closing on a slow truck, and a time-to-collision gauge from 0 to 4 seconds">
<rect x=${L} y="4" width=${R - L} height="40" fill="#e4e4e4" />
<line x1=${L} x2=${R} y1="24" y2="24" stroke="white" stroke-width="2" stroke-dasharray="14 12" />
<rect x=${L + rear * sc} y="10" width=${truckL * sc} height="28" rx="3" fill=${truckC} stroke="#333" />
<rect class="t-car" x="0" y="14" width=${carL * sc} height="20" rx="4" fill=${carC} stroke="#333" />
<line class="t-gap" y1="52" y2="52" stroke="#333" stroke-width="1.5" />
<rect x=${gx(0)} y="66" width=${gx(1.25) - gx(0)} height="16" fill="#d62728" />
<rect x=${gx(1.25)} y="66" width=${gx(1.5) - gx(1.25)} height="16" fill="#ff9f1c" />
<rect x=${gx(1.5)} y="66" width=${gx(ttcMax) - gx(1.5)} height="16" fill="#2ca02c" />
${[0, 1, 2, 3, 4].map(t => htl.svg`<text x=${gx(t)} y="104" font-size="13" fill="currentColor" text-anchor=${t === 0 ? "start" : t === ttcMax ? "end" : "middle"}>${t === ttcMax ? "4 s +" : t + " s"}</text>`)}
<path class="t-mark" d="M0,62 l-7,-10 h14 z" fill="#111" />
</svg>`;
const frame = htl.html`<div class="fig-frame">
<div class="knob-row"><button type="button" class="pill-btn">▶ Start</button><button type="button" class="pill-btn" disabled>Brake!</button><span class="t-best"></span></div>
${svg}
<div class="loop-readout t-read"></div>
<div class="loop-readout"><b class="t-msg">Press Start, then Brake!</b></div>
<div class="fig-license">${trgyCopy} · CC BY-NC-SA 4.0</div></div>`;
const [go, brake] = frame.querySelectorAll("button"), q = s => frame.querySelector(s);
let st = {gap: 70, vF: vF0, braking: false, done: true}, raf = 0, best = null;
const draw = () => {
const g = Math.max(0, st.gap), c = st.vF - vL, ttc = c > 0 ? g / c : Infinity;
const x1 = L + (rear - g) * sc;
q(".t-car").setAttribute("x", x1 - carL * sc);
q(".t-gap").setAttribute("x1", x1); q(".t-gap").setAttribute("x2", L + rear * sc);
q(".t-mark").setAttribute("transform", `translate(${gx(ttc)},0)`);
q(".t-read").innerHTML = `car <b>${(st.vF * 3.6).toFixed(0)} km/h</b> · gap <b>${g.toFixed(1)} m</b> · TTC <b>${c > 0 ? ttc.toFixed(2) + " s" : "∞ (no longer closing)"}</b>`;
};
const finish = kind => {
st.done = true; brake.disabled = true; go.textContent = "↻ Again";
const at = st.braking ? `Braked at TTC ${st.ttcB.toFixed(2)} s: ` : "No brake: ";
let msg;
if (kind === "crash") msg = at + "crash.";
else {
msg = at + `no crash, ${st.gap.toFixed(1)} m to spare` + (st.ttcB <= crit ? ", but a near miss (TTC ≤ 1.5 s)." : ". Safe.");
if (best === null || st.ttcB < best) best = st.ttcB;
q(".t-best").textContent = `Boldest safe brake: ${best.toFixed(2)} s`;
}
q(".t-msg").textContent = msg;
};
const step = now => {
const dt = Math.min(0.05, (now - st.t) / 1000); st.t = now;
if (st.braking) st.vF = Math.max(vL, st.vF - b * dt);
st.gap -= (st.vF - vL) * dt;
if (st.gap <= 0) { st.gap = 0; draw(); finish("crash"); return; }
draw();
if (st.braking && st.vF <= vL) { finish("safe"); return; }
raf = requestAnimationFrame(step);
};
go.onclick = () => {
cancelAnimationFrame(raf);
st = {gap: 70 + Math.random() * 30, vF: vF0, braking: false, done: false, t: performance.now()};
brake.disabled = false; go.textContent = "↻ Restart"; q(".t-msg").textContent = "Closing in…";
raf = requestAnimationFrame(step);
};
brake.onclick = () => {
if (st.done || st.braking) return;
st.braking = true; st.ttcB = st.gap / (st.vF - vL); brake.disabled = true;
};
draw();
invalidation.then(() => cancelAnimationFrame(raf));
return frame;
}Time-to-collision \[ \mathrm{TTC} = \frac{g}{v_\text{follower} - v_\text{leader}} \]
Near miss (a conflict)
TTC \(\le\) 1.5 s, counted from video, LiDAR or simulation: no crash needed
How to read it
Heavy wheels press grooves, ruts, into asphalt, deepest where trucks brake and stand. How would you measure one?

Photo: 14 cm ruts on road DK1 in Poczesna, Poland, with a traffic signal ahead (Burda, via Wikimedia Commons; cropped. Photo and crop: CC BY-SA 3.0).
How to read it
A truck measures every rut at traffic speed.
Predict where on this 1 km are the ruts deepest? Slide it along.
viewof vanX = knob({min: 0, max: 1000, step: 10, value: 0, label: "Truck at", format: x => `${x} m`})
// One layout for the slider, the road and the rut-depth plot, so all three share the 0-1000 m axis: the drawing is
// rutW wide with the kilometre from rutL to rutR, and every piece scales with the box (SVG at width 100%, the
// slider's margins in percent)
rutW = Math.max(260, fullW - 34)
rutL = 46
rutR = rutW - 48
// A made-up 1 km lane (a sketch, not measured data): ruts of 2 to 4 mm, deepening on the approach to a traffic
// signal at 850 m, where heavy vehicles brake, stand and pull away; shallower again past the stop line.
rutDepth = (x, side) => {
const bump = x <= 850 ? Math.exp(-(((x - 800) / 110) ** 2)) : Math.exp(-(((50) / 110) ** 2)) * Math.exp(-(x - 850) / 25);
const wig = 0.5 * Math.sin(x / 37 + 3 * side) + 0.3 * Math.sin(x / 13 + 5 * side);
return side === 0 ? 2.4 + wig + 8 * bump : 3 + wig + 10.5 * bump;
}
// The scanner's cross-section at x: a dip under each wheel path (at 0.9 m and 2.7 m), the cross slope removed,
// a little surface texture. Rut depth is measured as a real system does: the biggest gap under a 1.2 m straightedge.
rutProfile = {
const ys = d3.range(0, 4.001, 0.01), paths = [0.9, 2.7];
const z = y => -paths.reduce((s, c, i) => s + rutDepth(vanX, i) * Math.exp(-(((y - c) / 0.2) ** 2)), 0)
+ 0.25 * Math.sin(y * 47 + vanX / 7) * Math.sin(y * 13);
const prof = ys.map(y => ({y, z: z(y)}));
const edges = paths.map((c, i) => {
const a = c - 0.6, bb = c + 0.6, za = z(a), zb = z(bb);
const under = ys.filter(y => y >= a && y <= bb).map(y => ({y, d: za + (zb - za) * (y - a) / (bb - a) - z(y)}));
const deep = under.reduce((m, p) => p.d > m.d ? p : m);
return {i, a, bb, za, zb, y: deep.y, d: deep.d, zLine: z(deep.y) + deep.d, zLow: z(deep.y)};
});
return {prof, edges};
}
// good, fair, poor: one hue, deeper ruts darker. Not green/yellow/red, which read as signal states beside the signal
rutCond = d => d < 5 ? "#9fd8cd" : d < 10 ? "#2a9d8f" : "#1b2a6b"// the slider, its track running exactly from 0 m to 1000 m of the road below (8 px: half the slider's thumb)
htl.html`<div class="ctl-panel rut-slider" style="margin: 0; background: none; padding: 0.2rem calc(${(rutW - rutR) / rutW * 100}% - 8px) 0 calc(${rutL / rutW * 100}% - 8px)">${viewof vanX}</div>`// the road from above, painted by the van as it scans (a condition map); under it the rut depth along the road
// so far, on the same axis; then the laser's view across the lane at the van
rutView = {
const pc = ["#d55e00", "#2b6cb0"]; // left and right wheel path
const {prof, edges} = rutProfile, slide = !!document.querySelector(".reveal");
const W = rutW, L = rutL, R = rutR, sx = x => L + x / 1000 * (R - L);
const y0 = 24, lh = slide ? 30 : 46, sy = y => y0 + y / 4 * lh, H = y0 + lh + 4;
const segs = d3.range(0, vanX, 5), vx = sx(vanX);
// the inspection truck from above (it drives to the right): a white cargo box with roof ribs and a soft shadow,
// a dark cab with a rounded nose, windscreen and mirrors. 2.5 m wide, so both wheel paths (0.9 m and 2.7 m) pass
// under it; its length is exaggerated so it shows on a 1 km strip
const tL = Math.max(26, Math.min(slide ? 62 : 80, 0.12 * (R - L))), cab = tL * 0.24, ty1 = sy(0.55), ty2 = sy(3.05), bh = ty2 - ty1, tx = vx - tL, gap = 2;
const box = tL - cab - gap, ribs = d3.range(1, 6).map(k => tx + k * box / 6);
const truck = htl.svg`<g aria-hidden="true" opacity=${R - L < 500 ? 0.75 : 1}>
<rect x=${tx + 2} y=${ty1 + 2} width=${tL} height=${bh} rx="4" fill="black" fill-opacity="0.18" />
<rect x=${tx} y=${ty1} width=${box} height=${bh} rx="3" fill="#f7f7f5" stroke="#4a4a4a" stroke-width="1.2" />
${ribs.map(x => htl.svg`<line x1=${x} x2=${x} y1=${ty1 + 2} y2=${ty2 - 2} stroke="#c9c9c9" stroke-width="1" />`)}
<rect x=${vx - cab - 3} y=${ty1 - 2.5} width="3.5" height="3" rx="1" fill="#3d434b" />
<rect x=${vx - cab - 3} y=${ty2 - 0.5} width="3.5" height="3" rx="1" fill="#3d434b" />
<rect x=${vx - cab} y=${ty1 + 1} width=${cab} height=${bh - 2} rx=${Math.min(cab * 0.45, bh / 2 - 1)} fill="#3d434b" stroke="#2a2a2a" stroke-width="1" />
<rect x=${vx - cab * 0.42} y=${ty1 + 3.5} width=${cab * 0.24} height=${bh - 7} rx="2" fill="#a9cdee" />
</g>`;
const road = htl.svg`<svg width="100%" viewBox="0 0 ${W} ${H}" style="display: block" role="img" aria-label="The road from above: the truck has scanned it up to ${vanX} m and coloured each wheel path by rut depth">
<rect x=${L} y=${y0} width=${R - L} height=${lh} fill="#cfcfcf" />
<line x1=${L} x2=${R} y1=${y0 + 1} y2=${y0 + 1} stroke="white" stroke-width="2" /><line x1=${L} x2=${R} y1=${y0 + lh - 1} y2=${y0 + lh - 1} stroke="white" stroke-width="2" />
${[0, 1].flatMap(i => segs.map(x => htl.svg`<rect x=${sx(x)} y=${sy([0.9, 2.7][i]) - 5} width=${Math.max(1, sx(x + 5) - sx(x)) + 0.5} height="10" fill=${rutCond(rutDepth(x + 2.5, i))} />`))}
<rect x=${sx(850)} y=${y0} width="3" height=${lh} fill="white" />
<rect x=${sx(850) + 6} y="1" width="11" height="22" rx="2" fill="#333" /><circle cx=${sx(850) + 11.5} cy="7" r="2.6" fill="#d62728" /><circle cx=${sx(850) + 11.5} cy="16" r="2.6" fill="#555" />
<text x=${sx(850) - 4} y="16" font-size="12" text-anchor="end" fill="gray">signal</text>
${truck}
<line x1=${vx} x2=${vx} y1=${y0 - 4} y2=${y0 + lh + 2} stroke="#e4007c" stroke-width="2.5" />
</svg>`;
const along = d3.range(0, vanX + 1, 5).flatMap(x => [0, 1].map(i => ({x, i, d: rutDepth(x, i)})));
const bands = [{a: 0, b: 5, c: "#9fd8cd", t: "good"}, {a: 5, b: 10, c: "#2a9d8f", t: "fair"}, {a: 10, b: 16, c: "#1b2a6b", t: "poor"}];
const depth = Plot.plot({
width: W, height: slide ? 120 : 180, marginLeft: L, marginRight: W - R, marginTop: 22, marginBottom: 38,
style: {fontSize: "13px", width: "100%", height: "auto"},
x: {domain: [0, 1000], label: "along the road (m) →", labelOffset: 34, ticks: [0, 200, 400, 600, 800, 1000]},
y: {domain: [0, 16], label: "↑ rut depth (mm)", ticks: [0, 5, 10, 15]},
marks: [
// the bands in exactly the road's colours, full strength, so the plot and the road read the same
Plot.rect(bands, {x1: 0, x2: 1000, y1: "a", y2: "b", fill: "c"}),
Plot.text(bands, {x: 1000, y: d => (d.a + d.b) / 2, text: "t", textAnchor: "start", dx: 5, fill: "currentColor", fontSize: 12}),
// each wheel path drawn over a white outline, so it stays visible on every band
Plot.line(along, {x: "x", y: "d", z: "i", stroke: "white", strokeWidth: 4.5}),
Plot.line(along, {x: "x", y: "d", z: "i", stroke: (d) => pc[d.i], strokeWidth: 1.5}),
Plot.ruleX([850], {stroke: "white", strokeDasharray: "4 3"}),
Plot.ruleX([vanX], {stroke: "#e4007c", strokeWidth: 2.5})
]
});
const slice = Plot.plot({
width: slide ? Math.floor((fullW - 50) / 2) : plotW, height: slide ? 118 : 180, marginLeft: 40, marginRight: 12, marginBottom: 38,
style: {fontSize: "13px"},
x: {domain: [0, 4], label: "across the lane (m) →", labelOffset: 34}, y: {domain: [-16, 5], label: "↑ height (mm)"},
marks: [
Plot.line(prof, {x: "y", y: "z", stroke: ink, strokeWidth: 1.2}),
Plot.link(edges, {x1: "a", y1: "za", x2: "bb", y2: "zb", stroke: (d) => pc[d.i], strokeWidth: 4}),
Plot.link(edges, {x1: "y", x2: "y", y1: "zLine", y2: "zLow", stroke: (d) => pc[d.i], strokeWidth: 2}),
Plot.text(edges, {x: "y", y: "zLine", text: d => `${d.d.toFixed(1)} mm`, dy: -11, fill: (d) => pc[d.i], fontWeight: "bold", fontSize: 13})
]
});
const worst = Math.max(...edges.map(e => e.d)), cond = worst < 5 ? "good" : worst < 10 ? "fair" : "poor";
const readout = htl.html`<div class="loop-readout">Under the truck: <b style="color:${pc[0]}">left ${edges[0].d.toFixed(1)} mm</b> · <b style="color:${pc[1]}">right ${edges[1].d.toFixed(1)} mm</b> · <b style="color:${rutCond(worst) === "#9fd8cd" ? "#2a7f73" : rutCond(worst)}">${cond}</b></div>`;
return htl.html`${road}${depth}
<div class="rut-pair"><div><div class="plot-cap">What the laser sees across the lane, at the truck</div>
<div class="rut-cap">bars: a 1.2 m ruler on each wheel path · number: the gap under it, the rut depth</div>${slice}</div>
<div class="rut-side">${readout}</div></div>
<div class="fig-license">A sketch, not measured data · ${trgyCopy} · CC BY-NC-SA 4.0</div>`;
}How to read it
Game: buy sensors to cover all four jobs at the lowest cost. Then change the weather.
viewof fuseBuy = {
const items = [["Loop", 1], ["Radar", 2], ["Camera", 2], ["LiDAR", 5], ["GPS probes", 3]];
const w = htl.html`<div class="toggle-row"><span class="toggle-label">Buy:</span>${items.map(([n, c]) =>
htl.html`<button type="button" class="pill-btn toggle" data-n=${n}>${n} · ${c}</button>`)}</div>`;
w.value = [];
for (const b of w.querySelectorAll("button")) b.onclick = () => {
b.classList.toggle("on");
w.value = [...w.querySelectorAll("button.on")].map(x => x.dataset.n);
w.dispatchEvent(new Event("input", {bubbles: true}));
};
return w;
}
viewof fuseWeather = {
const items = [["Clear day", "☀"], ["Night", "☾"], ["Snow or fog", "❄"]];
const w = htl.html`<div class="toggle-row"><span class="toggle-label">Weather:</span>${items.map(([n, ic], i) =>
htl.html`<button type="button" class=${"pill-btn toggle" + (i === 0 ? " on" : "")} data-n=${n}>${ic} ${n}</button>`)}</div>`;
w.value = "Clear day";
for (const b of w.querySelectorAll("button")) b.onclick = () => {
for (const x of w.querySelectorAll("button")) x.classList.toggle("on", x === b);
w.value = b.dataset.n; w.dispatchEvent(new Event("input", {bubbles: true}));
};
return w;
}
// Who can do each job in each weather: a simplification of the table in the card's "More" box. "Radar+LiDAR": only the
// two together (radar finds the object through snow, LiDAR's short-range shape tells what it is).
fuseRules = ({
"Clear day": {"Counts": ["Loop", "Radar", "Camera", "LiDAR"], "Travel times": ["GPS probes"], "People on foot": ["Camera", "LiDAR"], "Bus, truck or bike?": ["Camera", "LiDAR"]},
"Night": {"Counts": ["Loop", "Radar", "LiDAR"], "Travel times": ["GPS probes"], "People on foot": ["LiDAR"], "Bus, truck or bike?": ["LiDAR"]},
"Snow or fog": {"Counts": ["Loop", "Radar"], "Travel times": ["GPS probes"], "People on foot": ["Radar+LiDAR"], "Bus, truck or bike?": ["Radar+LiDAR"]}
})// a street scene: the sensors you bought on the pole (and in the road, and in the sky), their beams, the weather;
// under it, the four jobs light up when a sensor you own can do them in this weather
fuseView = {
const cost = {"Loop": 1, "Radar": 2, "Camera": 2, "LiDAR": 5, "GPS probes": 3}, names = Object.keys(cost);
const col = {"Loop": "#c77700", "Radar": "#59a14f", "Camera": "#4e79a7", "LiDAR": "#b07aa1", "GPS probes": "#9c755f"};
const weathers = Object.keys(fuseRules), wx = fuseWeather;
const cover = (set, w) => Object.entries(fuseRules[w]).map(([job, who]) => ({job, by: who.filter(x => x.split("+").every(s => set.has(s)))}));
const ok = (set, w) => cover(set, w).every(r => r.by.length > 0);
const price = set => [...set].reduce((a, s) => a + cost[s], 0);
const sets = d3.range(32).map(m => new Set(names.filter((_, i) => (m >> i) & 1)));
const best = d3.min(sets.filter(s => ok(s, wx)), price), bestAll = d3.min(sets.filter(s => weathers.every(w => ok(s, w))), price);
const pick = new Set(fuseBuy), rows = cover(pick, wx), p = price(pick);
const done = ok(pick, wx), all = weathers.every(w => ok(pick, w)), missing = rows.filter(r => !r.by.length).length;
// which bought sensors still see anything in this weather
const works = s => Object.values(fuseRules[wx]).some(who => who.some(x => x.split("+").includes(s) && x.split("+").every(q => pick.has(q))));
// the scene
const W = Math.max(300, fullW - 30), H = 168, px = Math.max(40, W * 0.1), road = 118;
// the sky follows the weather, and is a dusk blue on the dark theme so the scene is no bright panel there
const sky = theme === "dark" ? {"Clear day": "#2c4157", "Night": "#141a36", "Snow or fog": "#4a5058"}[wx]
: {"Clear day": "#dff0ff", "Night": "#1b2142", "Snow or fog": "#d5dae1"}[wx];
const beam = (s, sy, x1, x2) => !pick.has(s) ? null : htl.svg`<polygon points="${px + 14},${sy} ${x1},${road + 40} ${x2},${road + 40}"
fill=${works(s) ? col[s] : "#888"} fill-opacity=${works(s) ? 0.22 : 0.12} stroke=${works(s) ? col[s] : "#888"} stroke-dasharray=${works(s) ? "" : "4 3"} />`;
const label = (s, sy) => !pick.has(s) ? null : htl.svg`<text x=${px + 24} y=${sy + 4} font-size="12" font-weight="bold" fill=${wx === "Night" ? "white" : col[s]}>${s}${works(s) ? "" : " · blind"}</text>`;
const flakes = d3.range(60).map(i => [((i * 97) % 1000) / 1000 * W, ((i * 61) % 100) / 100 * (H - 10)]);
const scene = htl.svg`<svg width="100%" viewBox="0 0 ${W} ${H}" style=${document.querySelector(".reveal") ? "display: block; max-height: 146px; margin: 0 auto" : "display: block"} role="img" aria-label="A street at ${wx}: a pole carries the sensors you bought, with their beams on the road">
<rect x="0" y="0" width=${W} height=${road - 14} fill=${sky} />
${wx === "Clear day" ? htl.svg`<circle cx=${W - 40} cy="26" r="13" fill="#ffcf33" />` : wx === "Night" ? htl.svg`<circle cx=${W - 40} cy="26" r="11" fill="#f4f1d0" /><circle cx=${W - 35} cy="22" r="10" fill=${sky} />` : null}
<rect x="0" y=${road - 14} width=${W} height="14" fill="#bdbdbd" />
<rect x="0" y=${road} width=${W} height=${H - road} fill="#6b6b6b" />
<line x1="0" x2=${W} y1=${road + 25} y2=${road + 25} stroke="white" stroke-width="2" stroke-dasharray="14 10" />
${pick.has("Loop") ? htl.svg`<rect x=${W * 0.27} y=${road + 31} width="34" height="12" fill="none" stroke=${col.Loop} stroke-width="3" /><text x=${W * 0.27 + 17} y=${road + 58} font-size="12" font-weight="bold" text-anchor="middle" fill="white">loop</text>` : null}
<rect x=${W * 0.36} y=${road + 30} width="38" height="15" rx="4" fill="#e0e0e0" stroke="#333" />
<rect x=${W * 0.55} y=${road + 4} width="78" height="18" rx="3" fill="#f2c12e" stroke="#333" />
<g stroke=${theme === "dark" || wx === "Night" ? "#e6e6e6" : "#333"} stroke-width="2" fill="none"><circle cx=${W * 0.72} cy=${road - 26} r="4" /><line x1=${W * 0.72} x2=${W * 0.72} y1=${road - 22} y2=${road - 10} /><line x1=${W * 0.72 - 5} x2=${W * 0.72 + 5} y1=${road - 18} y2=${road - 18} /><line x1=${W * 0.72} x2=${W * 0.72 - 4} y1=${road - 10} y2=${road - 2} /><line x1=${W * 0.72} x2=${W * 0.72 + 4} y1=${road - 10} y2=${road - 2} /></g>
${beam("Camera", 40, W * 0.3, W * 0.62)}${beam("Radar", 62, W * 0.42, W * 0.92)}${beam("LiDAR", 20, W * 0.24, W * 0.78)}
${pick.has("GPS probes") ? htl.svg`<g><rect x=${W - 96} y="40" width="16" height="10" fill="#9c755f" /><line x1=${W - 104} x2=${W - 72} y1="45" y2="45" stroke="#9c755f" stroke-width="3" />
<line x1=${W - 88} y1="50" x2=${W * 0.36 + 19} y2=${road + 30} stroke="#9c755f" stroke-dasharray="3 3" /><line x1=${W - 88} y1="50" x2=${W * 0.55 + 39} y2=${road + 4} stroke="#9c755f" stroke-dasharray="3 3" />
<text x=${W - 88} y="66" font-size="12" font-weight="bold" text-anchor="middle" fill=${wx === "Night" ? "white" : "#9c755f"}>GPS</text></g>` : null}
${wx === "Snow or fog" ? htl.svg`<g><rect x="0" y="0" width=${W} height=${H} fill="white" fill-opacity="0.35" />${flakes.map(([x, y]) => htl.svg`<circle cx=${x} cy=${y} r="2" fill="white" />`)}</g>` : null}
${wx === "Night" ? htl.svg`<rect x="0" y=${road - 14} width=${W} height=${H - road + 14} fill="#000" fill-opacity="0.45" />` : null}
<rect x=${px} y="14" width="5" height=${road - 14} fill="#444" /><rect x=${px} y="30" width="22" height="4" fill="#444" />
${pick.has("LiDAR") ? htl.svg`<rect x=${px - 4} y="8" width="13" height="12" rx="3" fill=${col.LiDAR} stroke="#222" />` : null}
${pick.has("Camera") ? htl.svg`<rect x=${px + 8} y="34" width="16" height="10" rx="2" fill=${col.Camera} stroke="#222" />` : null}
${pick.has("Radar") ? htl.svg`<rect x=${px + 8} y="54" width="12" height="16" rx="3" fill=${col.Radar} stroke="#222" />` : null}
${label("LiDAR", 16)}${label("Camera", 40)}${label("Radar", 64)}
</svg>`;
const icons = {"Counts": "🚗", "Travel times": "⏱", "People on foot": "🚶", "Bus, truck or bike?": "🚌"};
const tiles = htl.html`<div class="job-grid">${rows.map(r => htl.html`<div class=${"job-tile" + (r.by.length ? " ok" : "")}>
<div class="job-icon">${icons[r.job]}</div><div class="job-name">${r.job}</div>
<div class="job-by">${r.by.length ? "✓ " + r.by.map(s => s.replace("+", " + ")).join(", ") : "✗ nobody"}</div></div>`)}</div>`;
const verdict = !done ? `${missing} job${missing > 1 ? "s" : ""} not covered · cost <b>${p}</b>`
: `✓ All four covered for <b>${p}</b>` + (p === best ? " · the cheapest for this weather!" : " · can you do it for less?")
+ (all ? (p === bestAll ? " · and in <b>every</b> weather, at the lowest cost: bragging rights" : " · works in every weather") : "");
return htl.html`<div class="fig-frame">${viewof fuseBuy}${viewof fuseWeather}${scene}${tiles}
<div class="loop-readout">${Object.assign(document.createElement("span"), {innerHTML: verdict})}</div>
<div class="fig-license">Costs are game points, not prices · ${trgyCopy} · CC BY-NC-SA 4.0</div></div>`;
}Data fusion: each sensor covers the others’ blind spots. Fusion is a model too: how were the data made?
More
| Sensor | Strong at | Weak at |
|---|---|---|
| Camera | detail; telling a bus from a truck from a cyclist | darkness, glare, rain, snow, fog |
| Radar | any weather, day or night; long range | coarse detail; poor at telling objects apart |
| LiDAR | precise 3-D positions; unaffected by light | cost, occlusion, heavy data; rain, snow and fog add noise |
| Loop detector | reliable counts and occupancy at one point | one point only; cannot see pedestrians |
| Phone and vehicle GPS | whole trips, citywide | only some vehicles, and not a random sample |
Sources: Yeong et al. (Sensors, 2021), Sun et al. (Sensors, 2022), NCHRP Web-Only Document 436 (2025).
🏆 First correct answer, with a one-line reason, wins bragging rights
🤝
🌶️ Sensor truce
Make the loop and the drone agree exactly. What must be true?
Try it in: Build your own road
2×
🌶️🌶️ Maximum disagreement
Make the loop report twice the drone’s speed. Where would you see that traffic?
Try it in: Build your own road
🚚
🌶️🌶️🌶️ Truck trouble
What share of trucks makes a single loop read 25 % too slow?
Try it in: Live: a loop, and trucks
Answer in your head, then tap.
Loop or drone: whose average speed is higher?
The loop’s: \(\bar v_t = \bar v_s + \sigma_s^2/\bar v_s\)
Which speed goes in \(q = k\,v\)?
The space-mean \(\bar v_s\)
What decides which average to compute?
Where the data came from: a point or a stretch
Flow and density in any region \(A\)?
Edie: \(q = d(A)/\lvert A\rvert\), \(k = t(A)/\lvert A\rvert\)
The sign said 52 s. What did drivers take?
66 s: the sign was a fifth short
Safety without waiting for crashes?
Count near misses: TTC \(\le\) 1.5 s
Know which window your data came from.
This week’s lab: Lab 2 · Real Traffic from Above: build a virtual loop detector.
| Symbol | Meaning (units) |
|---|---|
| \(\bar v_t\) | time-mean speed: the average over vehicles passing a point (m/s or km/h) |
| \(\bar v_s\) | space-mean speed: the average over vehicles on a stretch of road (m/s or km/h) |
| \(\sigma_s^2\) | variance of speeds measured in space, in (m/s)² |
| \(M\) | number of sub-streams in Wardrop’s model |
| \(q_i,\ k_i,\ v_i\) | flow, density and speed of sub-stream \(i\) (veh/h, veh/km, km/h) |
| \(Q,\ K\) | total flow and total density (veh/h, veh/km) |
| \(f_i,\ f_i'\) | share of sub-stream \(i\) in time (\(q_i/Q\)) and in space (\(k_i/K\)) |
| \(A,\ \lvert A\rvert\) | a region of the time-space diagram, and its area (m·s) |
| \(d(A),\ t(A)\) | total distance and total time travelled by vehicles inside \(A\) (m, s) |
| \(N\) | number of vehicles observed (veh) |
| Symbol | Meaning (units) |
|---|---|
| \(o\) | occupancy: fraction of time the loop is covered |
| \(d\) | loop length (m); not the same as Edie’s \(d(A)\) |
| \(\ell,\ \ell_j\) | assumed vehicle length; length of vehicle \(j\) (m) |
| \(\tau_j\) | time vehicle \(j\) covers the loop (s) |
| \(T\) | length of the counting period (s) |
| \(g\) | bumper-to-bumper gap between a follower and its leader (m) |
| TTC | time-to-collision: time until two road users collide if neither changes speed or path (s) |
| PET | post-encroachment time: time between one road user leaving a conflict point and the next arriving (s) |
import {knob, seg, action, pauser, flip, panel, row, pair, end} from "../assets/controls.js"
// Colours that follow the light/dark theme switch: plots redraw when the reader toggles the theme.
// 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.
// 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);
})
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);
})