Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions models/intersection/queue.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/** @typedef {{ NS: number, EW: number }} Counts */
/** @typedef {{ horizon_slots: number, initial_queue: Counts, phase_sequence: string[], service: Record<string, Counts> }} QueueModel */

/** @param {Counts | undefined} counts */
function validCounts(counts) {
return counts && [counts.NS, counts.EW].every(value => Number.isSafeInteger(value) && value >= 0);
}

/** @param {QueueModel} model @param {Counts[]} arrivals */
export function runQueue(model, arrivals) {
if (model.horizon_slots !== model.phase_sequence.length || arrivals.length !== model.horizon_slots) {
throw new Error('Each slot needs a phase and an arrival record.');
}
if (!validCounts(model.initial_queue)) throw new Error('Invalid initial queue.');
let queue = { ...model.initial_queue };
return model.phase_sequence.map((phase, index) => {
const arrival = arrivals[index];
const capacity = model.service[phase];
if (!validCounts(arrival) || !validCounts(capacity)) throw new Error(`Invalid arrivals or phase at slot ${index + 1}.`);
const waitingNS = queue.NS + arrival.NS;
const waitingEW = queue.EW + arrival.EW;
const departures = { NS: Math.min(waitingNS, capacity.NS), EW: Math.min(waitingEW, capacity.EW) };
queue = { NS: waitingNS - departures.NS, EW: waitingEW - departures.EW };
return { slot: index + 1, phase, arrival, departures, queue };
});
}

/** Move one vehicle, using the one-based slot numbers shown in the chapter.
* @param {Counts[]} arrivals @param {'NS' | 'EW'} group @param {number} from @param {number} to */
export function moveArrival(arrivals, group, from, to) {
if (!['NS', 'EW'].includes(group) || ![from, to].every(slot => Number.isInteger(slot) && slot >= 1 && slot <= arrivals.length)) {
throw new Error('Choose a vehicle group and two valid slots.');
}
if (from === to || arrivals[from - 1][group] < 1) throw new Error('Move an existing arrival to a different slot.');
const edited = arrivals.map(arrival => ({ ...arrival }));
edited[from - 1][group]--;
edited[to - 1][group]++;
return edited;
}
39 changes: 39 additions & 0 deletions models/intersection/queue.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
import inputs from '../../project/v3/case-study/model-inputs-v1.json';
import { moveArrival, runQueue } from './queue.mjs';

const trace = readFileSync(new URL('../../project/v3/case-study/trace-v1.csv', import.meta.url), 'utf8')
.trim().split(/\r?\n/).slice(1);
const clustered = inputs.scenarios.find(s => s.id === 'B')!.arrivals;

describe('fixed-phase intersection experiment', () => {
it('matches every arrival, phase, departure and queue in the independent reference trace', () => {
const calculated = inputs.scenarios.flatMap(scenario => runQueue(inputs, scenario.arrivals)
.map(({ slot, phase, arrival, departures, queue }) =>
[scenario.id, slot, phase, arrival.NS, arrival.EW, departures.NS, departures.EW, queue.NS, queue.EW].join(',')));
expect(calculated).toEqual(trace);
});

it('moves one NS arrival to the last NS green and preserves the baseline', () => {
const edited = moveArrival(clustered, 'NS', 3, 2);
expect(runQueue(inputs, edited).at(-1)?.queue).toEqual({ NS: 1, EW: 0 });
expect(runQueue(inputs, clustered).at(-1)?.queue).toEqual({ NS: 2, EW: 0 });
expect(edited.reduce((n, row) => n + row.NS + row.EW, 0)).toBe(4);
});

it('rejects an empty origin, an unchanged slot and slots outside the horizon', () => {
expect(() => moveArrival(clustered, 'EW', 3, 2)).toThrow();
expect(() => moveArrival(clustered, 'NS', 3, 3)).toThrow();
expect(() => moveArrival(clustered, 'NS', 3, 9)).toThrow();
expect(() => moveArrival(clustered, 'NS', 0, 2)).toThrow();
});

it('rejects malformed records before reporting a result', () => {
for (const count of [-1, 0.5]) {
expect(() => runQueue(inputs, [{ NS: count, EW: 0 }, ...clustered.slice(1)])).toThrow();
}
expect(() => runQueue(inputs, clustered.slice(1))).toThrow();
expect(() => runQueue({ ...inputs, phase_sequence: ['UNKNOWN', ...inputs.phase_sequence.slice(1)] }, clustered)).toThrow();
});
});
4 changes: 2 additions & 2 deletions project/v3/case-study/MODEL-CHECK.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ Both have **four** invented arrivals; the fixed phase schedule never changes. On

During preparation, a first JavaScript implementation generated all **16 trace records** from the declared inputs and checked conservation. A second, separately written calculation fetched the saved inputs and CSV through the GitHub connection and independently recomputed **every field in all 16 rows**; it matched exactly. The second check also resolved all eight typed graph edges to twelve existing source objects, confirmed the deliberately missing target is not a real object, rejected negative/fractional arrivals and unknown phase labels, and verified each derived final queue in the data-quality file.

Those are **editorial consistency checks**, not an independent accredited engineering examination, an executed Astro simulation or empirical evidence. The standalone [verify-fixture.mjs](verify-fixture.mjs) preserves a reproducible check for future editors. **It has not been wired into GitHub Actions or the public site**; before promotion, run and record its results in the checked-out repository and review its test coverage.
Those checks established the internal consistency of the teaching fixture. The [Chapter 5 browser exercise](../manuscripts/revised/05-learning-through-models-and-prototypes.md) and the [standalone checker](verify-fixture.mjs) now use the same [queue calculation](../../../models/intersection/queue.mjs). Its [regression tests](../../../models/intersection/queue.test.ts) compare every original row with the stored trace and check the effect of moving one arrival.

### Conservation

Expand All @@ -51,7 +51,7 @@ Every existing edge has a known source and target ID, a declared relation type,

The allowed editorial conclusion is narrow: **with T1's eight-slot rule and invented arrivals, arrival clustering changes the number still queued**. No real intersection, physical indication, safety or AI-agent performance is assessed.

## Explicit missing work / future checks
## Follow-ups recorded in the original review on 16 November 2026

- [ ] Owner/editorial review of object vocabulary, system boundary, source revision, model assumptions and whether two-group signal phase is a useful pedagogical simplification.
- [ ] Run `node project/v3/case-study/verify-fixture.mjs` in the repository environment; retain actual stdout and CLI exit code for the record.
Expand Down
19 changes: 4 additions & 15 deletions project/v3/case-study/verify-fixture.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import assert from 'node:assert/strict';
import { runQueue } from '../../../models/intersection/queue.mjs';

const root = dirname(fileURLToPath(import.meta.url));
const read = (name) => readFileSync(join(root, name), 'utf8');
Expand Down Expand Up @@ -43,21 +44,9 @@ assert.throws(() => validate({ ...input, scenarios: [{ ...input.scenarios[0], ar
assert.throws(() => validate({ ...input, scenarios: [{ ...input.scenarios[0], arrivals: input.scenarios[0].arrivals.slice(1) }] }));

function run(scenario) {
const queue = { NS: 0, EW: 0 };
const rows = [];
for (let k = 0; k < input.horizon_slots; k++) {
const arrival = scenario.arrivals[k];
const phase = input.phase_sequence[k];
const capacity = input.service[phase];
queue.NS += arrival.NS;
queue.EW += arrival.EW;
const departNS = Math.min(queue.NS, capacity.NS);
const departEW = Math.min(queue.EW, capacity.EW);
queue.NS -= departNS;
queue.EW -= departEW;
rows.push([scenario.id,k+1,phase,arrival.NS,arrival.EW,departNS,departEW,queue.NS,queue.EW]);
}
return rows;
return runQueue(input, scenario.arrivals).map(({ slot, phase, arrival, departures, queue }) => [
scenario.id, slot, phase, arrival.NS, arrival.EW, departures.NS, departures.EW, queue.NS, queue.EW,
]);
}
const expected = input.scenarios.flatMap(run);
const csvLines = read('trace-v1.csv').trimEnd().split(/\r?\n/);
Expand Down
21 changes: 21 additions & 0 deletions project/v3/learning/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Learning activities in V3 manuscripts

The [V3 chapter route](../../../site/src/pages/learn/v3/%5Bslug%5D.astro) inserts activities into the published Markdown during the build. Each chapter issue owns its questions, their placement and its reading links.

## Knowledge checks

Use the stable `id` from the manuscript frontmatter as the filename in `quizzes/`. Each question has an ID, a prompt and distinct choices with feedback for each choice. Set `"correct": true` on one choice. The [Chapter 3 questions](quizzes/eel-v3-ch03-planning.json) show the format.

Place `<!-- interactive: chapter-quiz -->` on its own line, with a blank line before and after it, where readers have enough information to reason about the questions. The build checks the question data and the placement marker. Chapter 5 uses `<!-- interactive: intersection-model -->` for the arrival experiment.

## Cards

Use a Markdown blockquote with a bold first paragraph containing either `Concept` or `Explore further`. A concept card explains a distinction at the point of need. An optional reading card names what a linked source lets the reader inspect.

```markdown
> **Explore further**
>
> Inspect the [arrival and service rules](../../case-study/model-inputs-v1.json) used in the comparison.
```

Use relative Markdown links from the manuscript. The V3 link processor resolves current chapter links under the Pages base path and other source files in GitHub. Run the repository's preview check to exercise the chapter, quiz and model tests together.
40 changes: 40 additions & 0 deletions project/v3/learning/quizzes/eel-v3-ch01-new-paradigm.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
[
{
"id": "repeatable-feedback",
"prompt": "Teams discover the same interface mismatch late in integration. Which investment would shorten the next decision cycle?",
"options": [
{
"text": "Add a second sign-off meeting before integration.",
"feedback": "The team would still discover the mismatch at integration. Identify where the two interface definitions first become comparable."
},
{
"text": "Check the two versioned interface definitions whenever either changes.",
"feedback": "An early comparison exposes a disagreement while the teams can still change their designs. The reusable check improves the engineering system.",
"correct": true
},
{
"text": "Build the next product variant before investigating the mismatch.",
"feedback": "A further variant increases the number of configurations the teams must investigate. It does little to locate the existing disagreement."
}
]
},
{
"id": "what-a-check-supports",
"prompt": "A model check passes for a proposed design change. Which decision can the team now make?",
"options": [
{
"text": "Use the result to decide what to integrate or investigate next.",
"feedback": "The check gives timely evidence about the modeled condition. The team can use that evidence to choose its next integration or test step.",
"correct": true
},
{
"text": "Release the product in every intended operating condition.",
"feedback": "The check covered a particular model and condition. Release also depends on integration and evidence for the intended use."
},
{
"text": "Count the check as a measured reduction in total development cost.",
"feedback": "A passing check records a technical result. A cost claim needs a measure of the work or rework it actually saved."
}
]
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
[
{
"id": "first-question",
"prompt": "The city wants better flow and safe crossings. Which question fits the first fixed-phase queue prototype?",
"options": [
{
"text": "Which crossing time is suitable for all pedestrians?",
"feedback": "The prototype has vehicle arrivals and signal phases. Answering a crossing-time question requires information about pedestrians, geometry and timing."
},
{
"text": "Which detector should the city purchase?",
"feedback": "Choosing hardware requires sensing and interface needs that the first queue experiment leaves open."
},
{
"text": "Can different arrival patterns leave different queues under the same phases?",
"feedback": "Arrivals, phases and queues are part of the prototype. Varying arrivals while holding the phases fixed isolates a question it can answer.",
"correct": true
}
]
},
{
"id": "intent-and-criteria",
"prompt": "Two groups agree to improve the intersection but give different meanings to “better.” What is the next useful step?",
"options": [
{
"text": "Identify each group’s intended outcome and choose one uncertainty to investigate.",
"feedback": "A driver’s queue and a pedestrian’s crossing opportunity call for different observations. Naming both helps turn a shared intent into meaningful criteria.",
"correct": true
},
{
"text": "Make the shortest vehicle queue the acceptance criterion for everyone.",
"feedback": "Queue length describes one outcome for one group. It leaves the crossing concern unanswered."
},
{
"text": "Choose adaptive control so that everyone can work to one design.",
"feedback": "Selecting a controller settles the proposed mechanism before the team has agreed which outcomes it should improve."
}
]
}
]
40 changes: 40 additions & 0 deletions project/v3/learning/quizzes/eel-v3-ch03-planning.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
[
{
"id": "replan-increment",
"prompt": "Two teams count arrivals on different sides of the same service step. What should change in the next increment?",
"options": [
{
"text": "Order detectors to get a larger set of arrival records.",
"feedback": "Additional records will still have two interpretations until the event order is agreed."
},
{
"text": "Agree on event order, record the decision and rerun the comparison.",
"feedback": "The disagreement affects the meaning of the result. A small, reviewable rerun makes the investigation useful again.",
"correct": true
},
{
"text": "Replace the long-term aim for the intersection.",
"feedback": "The ambiguity concerns an experiment. It provides grounds to revise the increment while the stakeholder aim still guides planning."
}
]
},
{
"id": "planning-horizon",
"prompt": "A team wants to keep its direction while learning whether the fixed-phase model is useful. Which entry belongs in its immediate backlog?",
"options": [
{
"text": "Improve how people move through the intersection.",
"feedback": "That describes a longer-term outcome. A backlog item identifies a concrete piece of work toward it."
},
{
"text": "Set the full hardware procurement schedule.",
"feedback": "Procurement depends on choices that this investigation is meant to inform."
},
{
"text": "Write down how each slot treats arrivals and check one trace together.",
"feedback": "The task can be done and reviewed within the next increment. Its result gives the team grounds to keep or revise the plan.",
"correct": true
}
]
}
]
40 changes: 40 additions & 0 deletions project/v3/learning/quizzes/eel-v3-ch04-engineering-knowledge.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
[
{
"id": "follow-a-relation",
"prompt": "The phase-selection function may change. The source says the queue model represents that function. What should an engineer do with this link?",
"options": [
{
"text": "Review the model assumptions that depend on phase selection.",
"feedback": "The directed link identifies a concrete model to inspect. The engineer can then establish and record the effect of the proposed change.",
"correct": true
},
{
"text": "Mark the signal interface as failed.",
"feedback": "The link records what the model represents. A failure claim requires an observed result against a criterion."
},
{
"text": "Update every diagram independently.",
"feedback": "The views draw on maintained definitions. Checking the shared definition first shows which views actually need updating."
}
]
},
{
"id": "unresolved-target",
"prompt": "An assistant suggests an interface ID that is missing from the source graph. How should the engineer record it?",
"options": [
{
"text": "Connect it to the nearest-looking interface name.",
"feedback": "A similar label provides no evidence of identity. That guessed connection would mislead the next review."
},
{
"text": "Remove the question because the graph has no edge.",
"feedback": "A missing edge can identify a gap in the recorded information. Other sources may still show an effect."
},
{
"text": "Keep it as an unresolved review question and check its source.",
"feedback": "The uncertainty stays visible and reviewable. A verified identity can later support a recorded relationship.",
"correct": true
}
]
}
]
40 changes: 40 additions & 0 deletions project/v3/learning/quizzes/eel-v3-ch05-models-prototypes.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
[
{
"id": "bounded-claim",
"prompt": "Two scenarios have the same four arrivals and fixed signal phases, yet finish with different queues. What accounts for the difference?",
"options": [
{
"text": "The model has selected a better controller for one scenario.",
"feedback": "Both scenarios use the same phase sequence. Look at when each vehicle arrives relative to a green slot."
},
{
"text": "The timing of arrivals changes which vehicles can depart within the eight slots.",
"feedback": "The rule serves the active green group after arrivals join its queue. An arrival that misses that group’s green can still be waiting at the end.",
"correct": true
},
{
"text": "The smaller final queue establishes a shorter average wait in city traffic.",
"feedback": "The trace counts vehicles remaining at one horizon. It contains neither a mean waiting-time measure nor observed city traffic."
}
]
},
{
"id": "capture-observation",
"prompt": "What should be saved so a colleague can use this experiment in the next investigation?",
"options": [
{
"text": "The model revision, scenario edit, observation horizon, queue result and next question.",
"feedback": "These details connect the observation to the exact assumptions and inputs that produced it and make the follow-up reproducible.",
"correct": true
},
{
"text": "Only the smallest queue shown by the experiment.",
"feedback": "A count on its own omits the arrival pattern, model revision and time at which it was taken."
},
{
"text": "An instruction to use the simulated schedule for the real intersection.",
"feedback": "A source-linked observation supports the next investigation. Choosing an operational schedule requires evidence about the real system."
}
]
}
]
Loading
Loading