Skip to content
Closed
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
18 changes: 18 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -930,6 +930,24 @@ time down the left, each hideable; one screen at full browser width (plot | char
Checks: `conformance/onnx/demo_node.mjs` (golden `demo/golden-tlm.json` for the model's port),
`demo_page.mjs` (Chromium), golden least squares `demo/golden-ls.json` from Python
(`demo_golden.py`); CI job `demo`. Figures `scripts/research/demo_charts.mjs`.
Owner 2026-11-21 ("predict steady legs"): `tlm-sK-legs` reads the same network as steady legs:
spec 016's `spans_from_logit` ported (`tlm.js`, checked against Python on the golden logits,
`demo/golden-spans.json`), the four most probable spans handed to the physics layer as chords with
both knots free (`solveLegs`, shared with the oracle). `TmaSolution.manoeuvre_start_s/end_s`,
schema 0.38.0. The target-turn preset zigs at 50 min, between ownship turns (owner: a target
turning with the ownship is a worst case, not the basis of analysis). The head states 0.00–0.02
at that turn on all three seeds; where seed 3 states anything (0.2–0.4) it is at an ownship turn,
so at the 0.5 threshold the read-out is one leg; at 0.1 seed 3 breaks at two ownship turns either
side of the truth and reaches 4–8% range error for that reason, not by finding the turn. The page
states the largest probability, and a **manoeuvre threshold** slider (owner, 2026-11-21;
`DemoScenario.manoeuvre_threshold`, 0.05–0.95, in the URL) moves the 0.5 for the declared spans
and the legs. The course and speed error charts carry ownship course and speed in blue (`Chart`'s
`overlay`). **`break-scan`** (`breakscan.js`; owner's yardstick, nothing learned): one speed, at
most one instantaneous course change (five unknowns), the break time scanned, declared when
chi-square falls by over 3 ln n. On the target-turn preset it declares the turn at 48–50 min with
39–41° and 0.5–1.9% range error; none on the other presets. The layer's chord (four free unknowns
a break, a soft speed prior) leaves the time flat from 30 to 65 min: holding speed exactly pins it. The points are not segmented (that would double-smooth); a proposer
from them into the search is unbuilt.

## Stack (owner decisions, 2026-10-31)

Expand Down
34 changes: 17 additions & 17 deletions conformance/onnx/demo/golden-ls.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"what": "tma2.references.lsq.solve_batch on the demonstrator's problems (spec 035)",
"problems_sha256": "0027c5a86e88703e5cb9def6005fbf6cb1dc129ab3983b9c9a4c06926b5986c1",
"problems_sha256": "72e90efb82960e97e0b9ee2c6e6796b7943be171dff54d7da4694225837651aa",
"solutions": {
"good-geometry-s1": {
"found": true,
Expand Down Expand Up @@ -53,26 +53,26 @@
"target-turn-s1": {
"found": true,
"theta": [
283.72407824135865,
25266.577601059125,
2.4925357772343855,
-2.8858648014833435
67.46331425243032,
23390.21946214587,
2.353436062237211,
-2.7020878971737865
],
"converged": true,
"iterations": 7,
"cost": 3.557536336724512
"cost": 2.933262486022508
},
"target-turn-s0": {
"found": true,
"theta": [
290.5773174138251,
25146.06648341229,
2.4867515632045114,
-2.8589610042051037
73.9835248591278,
23279.67537275816,
2.348088615978294,
-2.6763048416918807
],
"converged": true,
"iterations": 7,
"cost": 3.1532242669494193
"cost": 2.5219085833838544
},
"endfire-s1": {
"found": true,
Expand Down Expand Up @@ -125,14 +125,14 @@
"target-turn-first-leg": {
"found": true,
"theta": [
-1830.4195206294712,
16663.778990149218,
3.000966704121369,
-0.5827650654795341
-1823.2831770254747,
16602.80326496443,
2.988289990814913,
-0.5745637773891902
],
"converged": true,
"iterations": 7,
"cost": 0.21649161389171923
"iterations": 6,
"cost": 0.17912862976184626
}
}
}
1 change: 1 addition & 0 deletions conformance/onnx/demo/golden-spans.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"problems_sha256": "72e90efb82960e97e0b9ee2c6e6796b7943be171dff54d7da4694225837651aa", "cases": {"good-geometry-s1": {"rows": 1429, "spans": [], "spans_max4": []}, "good-geometry-s0": {"rows": 1429, "spans": [], "spans_max4": []}, "no-zig-s1": {"rows": 1429, "spans": [], "spans_max4": []}, "no-zig-s0": {"rows": 1429, "spans": [[7130.0, 7140.0]], "spans_max4": [[7130.0, 7140.0]]}, "target-turn-s1": {"rows": 1429, "spans": [], "spans_max4": []}, "target-turn-s0": {"rows": 1429, "spans": [], "spans_max4": []}, "endfire-s1": {"rows": 1429, "spans": [], "spans_max4": []}, "endfire-s0": {"rows": 1429, "spans": [[7130.0, 7140.0]], "spans_max4": [[7130.0, 7140.0]]}, "short-window-s1": {"rows": 181, "spans": [], "spans_max4": []}, "short-window-s0": {"rows": 181, "spans": [], "spans_max4": []}, "target-turn-first-leg": {"rows": 581, "spans": [], "spans_max4": []}}}
2 changes: 1 addition & 1 deletion conformance/onnx/demo/golden-tlm.json

Large diffs are not rendered by default.

93 changes: 92 additions & 1 deletion conformance/onnx/demo_node.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ test("target turn: mismatch flagged; one target leg clears it and cuts the error
const sc = preset("target-turn");
const full = await solveScenario(sc);
assert.ok(full.kn.length > 0, "a target manoeuvre in the window");
const leg = await solveScenario({ ...sc, window: { start_s: 0, end_s: 3500 } });
const leg = await solveScenario({ ...sc, window: { start_s: 0, end_s: 2900 } });
assert.equal(leg.kn.length, 0);
assert.ok(leg.ev.summary.range_pct.rms < full.ev.summary.range_pct.rms / 5, `${leg.ev.summary.range_pct.rms} vs ${full.ev.summary.range_pct.rms}`);
});
Expand Down Expand Up @@ -208,6 +208,32 @@ test("the oracle told the manoeuvre times removes the turn's bias", async () =>
assert.ok(or.ev.summary.range_pct.rms < 0.5 && cv.ev.summary.range_pct.rms > 20, `${or.ev.summary.range_pct.rms} vs ${cv.ev.summary.range_pct.rms}`);
});

test("the classical break scan finds the target-turn preset's turn and declares none elsewhere", async () => {
for (const seed of [1, 2, 3]) {
const r = await solveScenario({ ...preset("target-turn"), seed }, "break-scan");
const truth = r.kn[0];
assert.equal(r.sol.status, "converged");
assert.equal(r.sol.manoeuvre_start_s.length, 1, `seed ${seed}: one break declared`);
const tb = (r.sol.manoeuvre_start_s[0] + r.sol.manoeuvre_end_s[0]) / 2;
const mid = (truth.t0 + truth.t1) / 2;
assert.ok(Math.abs(tb - mid) <= 180, `seed ${seed}: break at ${tb} s, truth ${mid} s`);
assert.ok(r.ev.summary.range_pct.rms < 4, `seed ${seed}: range ${r.ev.summary.range_pct.rms}`);
// legs: one speed, and the course changes by about the truth's 40 degrees
const sp = (k) => Math.hypot(r.sol.vx_mps[k], r.sol.vy_mps[k]);
assert.ok(Math.abs(sp(0) - sp(r.sol.t_s.length - 1)) < 1e-9);
const turn = (Math.atan2(r.sol.vx_mps.at(-1), r.sol.vy_mps.at(-1)) - Math.atan2(r.sol.vx_mps[0], r.sol.vy_mps[0])) * 180 / Math.PI;
assert.ok(Math.abs(turn - 40) < 8, `seed ${seed}: turn ${turn}`);
}
for (const id of ["good-geometry", "no-zig", "endfire", "short-window"]) {
const r = await solveScenario(preset(id), "break-scan");
const ls = await solveScenario(preset(id), "ls-js");
assert.equal(r.sol.manoeuvre_start_s.length, 0, `${id}: no break declared (${r.sol.message})`);
assert.ok(Math.abs(r.sol.x_m.at(-1) - ls.sol.x_m.at(-1)) < 1e-6, `${id}: one leg returned`);
}
const a = await solveScenario(preset("target-turn"), "break-scan"), b = await solveScenario(preset("target-turn"), "break-scan");
assert.deepEqual(a.sol.x_m, b.sol.x_m, "deterministic");
});

test("the whole-period model's inputs and own track equal Python's (spec 016 port)", async () => {
const golden = JSON.parse(readFileSync(here + "demo/golden-tlm.json", "utf8"));
const cases = goldenCases();
Expand All @@ -233,6 +259,71 @@ test("the whole-period model's inputs and own track equal Python's (spec 016 por
}
});

test("the declared manoeuvre spans equal Python's spans_from_logit (spec 016 port)", () => {
const golden = JSON.parse(readFileSync(here + "demo/golden-spans.json", "utf8"));
const tlm = JSON.parse(readFileSync(here + "demo/golden-tlm.json", "utf8"));
assert.equal(golden.problems_sha256, tlm.problems_sha256);
let declared = 0;
for (const [id, g] of Object.entries(golden.cases)) {
const prob = tlm.cases[id].logit.map((l) => 1 / (1 + Math.exp(-l)));
assert.deepEqual(TLM.spansFromLogit(prob, g.rows), g.spans, `${id}: spans`);
assert.deepEqual(TLM.spansFromLogit(prob, g.rows, 0.5, 60.0, 4), g.spans_max4, `${id}: at most four`);
declared += g.spans.length;
}
assert.ok(declared > 0, "some golden case declares a manoeuvre");
// a hand-made case (Python's answers): merging within 60 s, the cap keeping the most probable
// runs, and the 10 s floor extended backwards
const prob = new Array(20).fill(0.1);
prob[2] = prob[3] = 0.9; prob[6] = 0.6; prob[7] = 0.55; prob[9] = 0.7; prob[12] = 0.8; prob[13] = 0.85; prob[16] = 0.95; prob[19] = 0.52;
assert.deepEqual(TLM.spansFromLogit(prob, 120), [[55, 595]]);
assert.deepEqual(TLM.spansFromLogit(prob, 120, 0.5, 0, 10), [[55, 115], [175, 235], [265, 295], [355, 415], [475, 505], [565, 595]]);
assert.deepEqual(TLM.spansFromLogit(prob, 120, 0.5, 0, 3), [[55, 115], [355, 415], [475, 505]]);
assert.deepEqual(TLM.spansFromLogit([0.9, 0.1], 7), [[0, 25]], "the first token's span starts at 0");
assert.deepEqual(TLM.spansFromLogit([0.1, 0.9, 0.1], 18), [[25, 55]]);
assert.deepEqual(TLM.spansFromLogit([0.1, 0.1, 0.9], 13), [[50, 60]], "a last token of one row is extended backwards to 10 s");
});

test("the learned model read as steady legs: the layer's legs at the model's spans", async () => {
for (const name of ["tlm-s1-legs", "tlm-s2-legs", "tlm-s3-legs"]) {
const r = await solveScenario(preset("target-turn"), name);
const own = await solveScenario(preset("target-turn"), name.replace("-legs", ""));
assert.notEqual(r.sol.status, "failed", name);
assert.deepEqual(r.sol.manoeuvre_prob, own.sol.manoeuvre_prob, `${name}: the same network statement`);
assert.ok(r.sol.manoeuvre_start_s.length <= 4 && r.sol.manoeuvre_start_s.length === r.sol.manoeuvre_end_s.length, name);
assert.equal(r.ev.t.length, r.rows.length, `${name}: an answer at every bearing`);
// legs: the velocity is piecewise constant, changing only inside a declared span
const vx = r.sol.vx_mps, t = r.sol.t_s;
for (let k = 1; k < t.length; k++) {
if (Math.abs(vx[k] - vx[k - 1]) < 1e-9) continue;
const inside = r.sol.manoeuvre_start_s.some((a, j) => t[k] >= a - 10.01 && t[k] <= r.sol.manoeuvre_end_s[j] + 10.01);
assert.ok(inside, `${name}: velocity changes at ${t[k]} s outside the declared spans ${JSON.stringify(r.sol.manoeuvre_start_s)}`);
}
assert.ok(r.sol.cov_end === null || r.sol.cov_end.length === 16, name);
}
const bad = await solveScenario({ ...preset("good-geometry"), interval_s: 10 }, "tlm-s1-legs");
assert.equal(bad.sol.status, "failed");
});

test("the manoeuvre threshold slider reaches the declared spans and the legs", async () => {
// at the registered 0.5 the head declares nothing on the target-turn preset; lowered, it does
const at = async (th, name) => solveScenario({ ...preset("target-turn"), manoeuvre_threshold: th }, name);
const high = await at(0.5, "tlm-s3-legs"), low = await at(0.1, "tlm-s3-legs");
assert.deepEqual(high.sol.manoeuvre_prob, low.sol.manoeuvre_prob, "the network's statement does not depend on the threshold");
assert.equal(high.sol.manoeuvre_start_s.length, 0);
assert.ok(low.sol.manoeuvre_start_s.length >= 1 && low.sol.manoeuvre_start_s.length <= 4, JSON.stringify(low.sol.manoeuvre_start_s));
assert.notEqual(low.sol.x_m.at(-1), high.sol.x_m.at(-1), "the legs change with the spans");
const own = await at(0.1, "tlm-s3");
const lastT = own.sol.t_s.at(-1);
const kept = own.sol.manoeuvre_start_s.filter((_, j) => lastT - own.sol.manoeuvre_end_s[j] >= 60).slice(0, 4);
assert.deepEqual(low.sol.manoeuvre_start_s, kept, "the legs read-out keeps the own-track spans that end before the last minute, four at most");
// the no-zig preset at seed 0 is where the head declares the window's last two rows (golden spans)
const edge = await solveScenario({ ...preset("no-zig"), sigma_deg: 0 }, "tlm-s1-legs");
assert.equal(edge.sol.manoeuvre_start_s.length, 0, "a span at the window's end is dropped");
assert.notEqual(edge.sol.status, "failed");
const frag = await encodeFragment({ ...preset("target-turn"), manoeuvre_threshold: 0.1 });
assert.equal((await decodeFragment(frag)).manoeuvre_threshold, 0.1, "the threshold survives the URL");
});

test("each seed of the whole-period model solves the presets", async () => {
for (const name of ["tlm-s1", "tlm-s2", "tlm-s3"]) {
const good = await solveScenario(preset("good-geometry"), name);
Expand Down
30 changes: 29 additions & 1 deletion conformance/onnx/demo_page.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ try {
check("target turn: mismatch flag shown (acceptance 4)", s.mismatch && flag === 1);
const before = s.summary.range_pct.rms;
// narrow the window with the slider's end (released: the native change event)
await page.locator("[data-testid=win-end]").fill("3500");
await page.locator("[data-testid=win-end]").fill("2900");
await page.waitForTimeout(50);
await settled();
const t = await state();
Expand Down Expand Up @@ -152,9 +152,37 @@ try {
const tl = await state();
const said = await page.locator("[data-testid=model-manoeuvres]").innerText().catch(() => "");
check("whole-period learned model: progress while loading, then a time-late track and its manoeuvres", badge === 1 && tl.status === "done" && tl.sol.status === "converged" && tl.summary.answered === tl.sol.t_s.length && /states \d+ target/.test(said), { range_pct_rms: tl.summary && tl.summary.range_pct.rms, ms: tl.sol && tl.sol.runtime_ms, said });
await page.selectOption("[data-testid=solver]", "tlm-s1-legs");
await settled();
const legs = await state();
const saidLegs = await page.locator("[data-testid=model-manoeuvres]").innerText().catch(() => "");
check("the learned model read as steady legs: the layer's track at the model's spans", legs.status === "done" && legs.sol.status !== "failed" && Array.isArray(legs.sol.manoeuvre_start_s) && legs.sol.manoeuvre_start_s.length <= 4 && /Read as \d+ steady/.test(saidLegs), { range_pct_rms: legs.summary && legs.summary.range_pct.rms, spans: legs.sol && legs.sol.manoeuvre_start_s, said: saidLegs });
// the threshold slider: lowered, the model declares spans on the target turn and the legs follow
await page.selectOption("[data-testid=solver]", "tlm-s3-legs");
await settled();
await page.locator("[data-testid=threshold]").evaluate((el) => { const set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set; set.call(el, "0.1"); el.dispatchEvent(new Event("input", { bubbles: true })); el.dispatchEvent(new Event("change", { bubbles: true })); });
await settled();
const low = await state();
check("manoeuvre threshold slider: at 0.1 the model declares spans and the legs read-out uses them", low.status === "done" && low.sol && Array.isArray(low.sol.manoeuvre_start_s) && low.sol.manoeuvre_start_s.length >= 1 && /over 0\.10/.test(await page.locator("[data-testid=model-manoeuvres]").innerText().catch(() => "")), { spans: low.sol && low.sol.manoeuvre_start_s, range_pct_rms: low.summary && low.summary.range_pct.rms });
await page.selectOption("[data-testid=solver]", "ls-js");
await settled();

// the classical break scan in the browser: one break declared near the true zig at 50 min
await page.selectOption("[data-testid=preset]", "target-turn");
await settled();
await page.selectOption("[data-testid=solver]", "break-scan");
await settled();
const bs = await state();
const at = bs.sol && bs.sol.manoeuvre_start_s && bs.sol.manoeuvre_start_s.length === 1 ? (bs.sol.manoeuvre_start_s[0] + bs.sol.manoeuvre_end_s[0]) / 2 : NaN;
check("classical break scan declares the target's zig within 3 min of 50 min", bs.status === "done" && Math.abs(at - 3000) <= 180 && bs.summary.range_pct.rms < 4, { break_s: at, range_pct_rms: bs.summary && bs.summary.range_pct.rms, ms: bs.sol && bs.sol.runtime_ms, message: bs.sol && bs.sol.message });
await page.selectOption("[data-testid=solver]", "ls-js");
await settled();

// ownship course and speed in blue on the course and speed error charts, nowhere else
const overlayOn = async (q) => { await page.locator(`input[type=radio][value=${q}]`).check(); await page.waitForTimeout(100); return page.locator("[data-testid=chart-error] [data-testid=chart-overlay] path").count(); };
const ov = { course: await overlayOn("course"), speed: await overlayOn("speed"), range: await overlayOn("range"), position: await overlayOn("position") };
check("ownship course and speed drawn on the course and speed charts only", ov.course === 1 && ov.speed === 1 && ov.range === 0 && ov.position === 0, ov);

// chart toggles hide each chart
await page.locator("[data-testid=toggle-bearings]").uncheck();
const hidden = await page.locator("[data-testid=panel-bearings]").count();
Expand Down
2 changes: 1 addition & 1 deletion conformance/onnx/demo_problems.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export function goldenCases() {
for (const sigma of [1, 0]) out.push({ id: `${p.id}-s${sigma}`, sc: { ...p.scenario, sigma_deg: sigma } });
}
const tt = PRESETS.find((p) => p.id === "target-turn").scenario;
out.push({ id: "target-turn-first-leg", sc: { ...tt, window: { start_s: 0, end_s: 3500 } } });
out.push({ id: "target-turn-first-leg", sc: { ...tt, window: { start_s: 0, end_s: 2900 } } });
return out.map(({ id, sc }) => {
const b = bearings(sc);
const { problem } = problemOf(sc, b, windowRows(sc, b));
Expand Down
48 changes: 48 additions & 0 deletions conformance/onnx/demo_spans_golden.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""Spec 035: golden manoeuvre spans for the demonstrator's legs read-out.

From the committed ``demo/golden-tlm.json`` (seed 1's logits per token on the golden problems,
from torch), Python's ``tma2.timelate.learned.spans_from_logit`` at spec 016's settings
(threshold 0.5, merge 60 s) with at most ten spans and with the page's cap of four. The
JavaScript port (``tlm.js`` ``spansFromLogit``) is checked against this file in
``demo_node.mjs``; ``tests/unit/test_demo_golden.py`` checks the file is Python's.

uv run python demo_spans_golden.py demo/golden-tlm.json demo/golden-spans.json
"""

from __future__ import annotations

import json
import sys
from pathlib import Path

import numpy as np

from tma2.timelate.learned import spans_from_logit, token_times

DT = 5.0
PATCH = 6


def spans_of(golden: dict) -> dict:
out: dict = {"problems_sha256": golden["problems_sha256"], "cases": {}}
for cid, g in golden["cases"].items():
rows = int(g["rows"])
logit = np.asarray(g["logit"], dtype=np.float64)
prob = 1.0 / (1.0 + np.exp(-logit))
tt = token_times(rows, DT, PATCH)
out["cases"][cid] = {
"rows": rows,
"spans": spans_from_logit(prob, tt).tolist(),
"spans_max4": spans_from_logit(prob, tt, max_manoeuvres=4).tolist(),
}
return out


def main(argv: list[str]) -> int:
src, dst = Path(argv[0]), Path(argv[1])
dst.write_text(json.dumps(spans_of(json.loads(src.read_text()))) + "\n")
return 0


if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
Loading
Loading