Skip to content

W2: sensor-field core, worker and parity - #591

Merged
neuromechanist merged 24 commits into
feature/issue-586-epic-pipeline-progressfrom
feature/issue-588-w2-sensor-field
Nov 25, 2026
Merged

neuromechanist merged 24 commits into
feature/issue-586-epic-pipeline-progressfrom
feature/issue-588-w2-sensor-field

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Phase W2 of #588 (epic nemarOrg/nemar-cli#2324, nemar-cli ADR 0137 and its amendment of 2026-11-24, website ADR 0035): the scalp map's core, its module worker, and parity with neuroschema 0.6.0's reference.

Changes

  • src/lib/quality-views/sensor-field.ts: nemar.sensor-field.v1 as neuroschema's docs/views/sensor-field.md states it.
    It is EEGLAB's topoplot with v4 interpolation, the Green's function d²(ln d − 1) solved by LU with partial pivoting, on a 67-by-67 grid masked at the head.
    The amendment's rules are in: mean-removed interpolation z = m + spline(v − m), merges within 1e-3 at the exact mean first + sum(x − first) / k, at least 8 interpolated sensors (too_few_sensors), the flat_field and near_flat notes, the minmax axis widened by 5% of the range (absmax by EEGLAB's caxis), six contour levels, and EEGLAB's head.
    head_outside_grid and interpolation_failed are refused with their words.
    The geometry (factorized G, evaluation matrix) is built once per layout and set of usable sensors and shared by every map of a view.
  • linalg.ts: the LU solver, with its factors kept, so a cached solve gives the same bits as a fresh one.
  • sensor-layout.ts: nemar.sensor-layout.v1.
    It uses the exact BIDS frame table and alias, refuses frame_unknown and never assumes a frame, and lays out scalp rows only.
    Template positions are centered on the montage's center; measured positions on the algebraic sphere, with the six bounds (positions_flat, positions_partial).
    The conversion is cart2topo, with theta in (−180, 180].
  • sensor-names.ts: the parts of nemar.sensor-labels.v1 the layout reads (fold, clean, finish, type classes, non-EEG prefixes, fiducials, the twenty montage names), for W2b to build on.
  • worker.ts, worker-protocol.ts, worker-client.ts: the module worker.
    The geometry is cached by the layout file's SHA-256 and the usable rows (LRU of 6), with the cached places compared so a reused key never serves stale geometry.
    The maps on screen go first in batches of 8, then the rest in batches of 64, with a cancel read between batches.
    Each grid leaves as the algorithm's own Float64Array, transferred; each geometry is sent once per draw; contour lines are traced in the worker for the maps on screen, and contoursOf traces any other map's lines when it is shown.
    The client imports none of the interpolation, never rejects on worker trouble (unavailable with a reason, including messageerror), ignores a dropped worker's late events, and runs the same handler over a MessageChannel where a browser has no Worker at all.
    No CSP change: worker-src 'self' already allows it.
  • contours.ts: marching squares, the renderer's own lines (outside parity). All levels are traced in one pass, masked corners draw nothing, and saddles are split by the square's mean.
  • colormap.ts, turbo-lut.ts, --qv-* tokens in tokens.css: three maps and the theme-aware head line.
    The diverging map is ColorBrewer RdBu reversed and colorblind-safe; the sequential map is the signal viewer's viridis stops, color for color; Turbo is Google's 256-entry table, rounded to 8 bits.
    entryFor places a value on halved operands, so an axis wider than the largest double still paints, and a position that is not finite takes the middle entry, never black.
    The Apache-2.0 notices for Turbo and ColorBrewer ship with the site, with the license's full text, in public/licenses/quality-views/NOTICE.txt (COLOR_MAPS_NOTICE), and are listed in THIRD_PARTY_NOTICES.md.
  • scripts/check-quality-views-size.mjs, run in CI after astro build: the worker at most 12 KB gzipped and the main-thread code (the client's chunk and every chunk it imports statically) at most 30 KB.
    It measures dist/ once a page imports the client; until then Astro's own Vite builds the client as an entry, with the worker emitted by Vite's worker plugin.
  • test/quality-views-perf.test.ts: the drawing budget gated at the budget itself, in its own CI step, alone on the runner (bun run test:quality-views-perf); e2e/quality-views-perf.spec.ts times a real module worker in Chromium.
  • The CI budget steps run with if: ${{ !cancelled() }}, so they run even when Vitest is red on the drift tests.
  • AGENTS.md map. No new runtime dependency and no chart library.

Parity

Every case of sensor-field.v1.json (42) and sensor-layout.v1.json (66) is replayed within the specs' bounds, and every refusal gives its exact word.
Every ALS and RAS frame name gives frame_als's or frame_ras's layout, and every cart2topo point converts.

Worst unmasked-cell error per drawn sensor-field case, as a share of the bound 1e-6 * range + 1e-12 * magnitude:

Case Max error Bound Share
montage_32 / 64 / 128 / 256 2.7e-13 / 6.4e-13 / 3.1e-12 / 7.0e-12 about 2.7e-5 up to 2.5e-7
exact_duplicates, near_duplicates 2.9e-13, 2.3e-13 2.9e-5, 2.8e-5 1.0e-8, 8.3e-9
close_pair (the worst) 7.0e-11 3.3e-5 2.1e-6
collinear_midline, outside, eight_sensors 8.5e-14, 4.5e-13, 3.9e-14 up to 1.7e-8
nan_values, nan_positions 1.9e-13, 2.7e-13 under 1e-8
dynamic_range 4.4e-11 1.4e-3 3.1e-8
boundary_ties, merged_outermost 5.6e-13, 2.7e-13 under 2e-8
one_sign_positive_db, one_sign_negative_db 1.3e-13 each 1.4e-5 9.3e-9
near_flat_minus_110_db, negative_extreme 1.4e-14, 8.0e-12 5.8e-8, 2.9e-5 2.5e-7, 2.7e-7
positions_measured / template / template_midline 3.3e-13 / 3.7e-13 / 6.2e-15 under 1.3e-8
every flat and near-flat case, zero_map, flat_minus_zero 0 (exact) 0

The refused cases all match by word:

  • too_few_sensors: seven_sensors, merged_to_seven;
  • head_outside_grid: far_sensor;
  • interpolation_failed: overflow;
  • frame_unknown: positions_frame_unknown, positions_montage_beside_a_frame;
  • positions_flat: positions_flat_disk, positions_three, positions_ring.

Worst layout errors over all drawn layout cases:

  • radius 2.6e-15 (bound 1e-12);
  • planar point 3.6e-15 (bound 1e-12);
  • sphere center 7.1e-14 absolute (bound 1e-9 × scale);
  • the six measures 8.2e-9 (bound 1e-6).

Performance

The owner's ruling keeps ADR 0137's budget: first maps within 50 ms and the whole 128-map view within 100 ms (256 within 300 ms).
Each view is the heaviest of its size, one independent-component map per sensor, with 8 maps on screen asked for first; the median is over 5 views, each with an empty layout cache, after one warm-up view.

Measured after the review round (the runner in CI run 45718762963 on 03998a1):

Where View First view (cold): first maps / view Median: first maps / view
CI runner (GitHub ubuntu-latest), gate step alone 128 × 128 maps 51.3 / 106.9 ms 23.5 / 58.5 ms
CI runner (GitHub ubuntu-latest), gate step alone 256 × 256 maps 39.2 / 183.5 ms 39.3 / 180.2 ms
Apple M4, Node 26, same gate 128 × 128 maps 16.1 / 54.7 ms 6.8 / 20.9 ms
Apple M4, Node 26, same gate 256 × 256 maps 15.1 / 70.8 ms 12.8 / 68.3 ms
Apple M4, Chromium 148, real module worker (e2e) 128 × 128 maps 42.7 / 85.2 ms (with worker start) 8.4 / 33.9 ms
Apple M4, Chromium 148, real module worker (e2e) 256 × 256 maps 42.4 / 140.1 ms (with worker start) 19.7 / 82.4 ms

Before the round, the same views measured 36.0 ms (M4, Node, 128) and 47.3 ms (M4, Chromium, 128); the runner's 102.5 ms was measured inside the parallel suite.
What changed:

  • contour lines only for the maps on screen (about 20% of a view);
  • grids transferred as they are, with no Float32 copy;
  • each geometry once per draw instead of once per batch;
  • later batches of 64 instead of 16;
  • a single-sensor merge group without an array.

In Chromium the worker's own time is now the whole view's to within 0.3 ms (33.8 of 33.9 ms at 128), so messaging and copying no longer cost anything measurable.

Sizes, from Vite 7.3.3 (Astro's) building the client as an entry: the worker is 5.2 KB gzipped (12.5 KB minified) against 12 KB.
The main thread is 5.5 KB gzipped against 30 KB, counting the shared chunk; the fallback chunk for a browser without workers (4.7 KB) is imported only dynamically and is listed, not counted.

Mutation testing

Each mutation edits the source and runs the field parity, rules, layout parity and solver suites: 42 mutations, 0 survivors.
The table gives the failing tests per suite.

Rule Mutation Caught by
Mean removal interpolate the values, as eegprep (no mean removed or added) vectors 29, rules 5
Mean removal remove the mean but do not add it back vectors 29, rules 6
Mean removal mean as a naive sum / n vectors 2, rules 2
Merge mean merged value is the first member's vectors 4, rules 1
Merge mean merged value is a naive sum / k vectors 2, rules 2
Merge mean merged value is the last member's vectors 4, rules 1
Near-flat threshold 1e-9 to 1e-10 rules 2
Near-flat threshold 1e-9 to 1e-8 vectors 1, rules 2
Near-flat threshold <= to < rules 1 (it survived until the exact-tie test, see the last commit)
Near-flat threshold no near-flat rule vectors 2, rules 2
Near-flat threshold threshold against the range instead of the magnitude vectors 2, rules 2
8-sensor minimum 8 to 7 vectors 2, rules 3
8-sensor minimum 8 to 9 vectors 2, rules 1
8-sensor minimum 8 to 3 (plan C7's old minimum) vectors 2, rules 3
8-sensor minimum counted before the merge vectors 1, rules 1
Minmax margin 5% to 0 vectors 31, rules 2
Minmax margin EEGLAB's magnitude rule for minmax vectors 31, rules 1
Minmax margin 5% to 10% of the range vectors 23, rules 1
Minmax margin margin on the upper limit only vectors 23, rules 1
Other radius margin 1.02 to 1.0 vectors 30
Other merge distance to 0 vectors 3, rules 1
Other merge distance to 2e-3 vectors 1
Other merge strictly within the distance vectors 1
Other square with abs() vectors 2
Other square strictly inside intrad vectors 1
Other plotted strictly inside plotrad vectors 1
Other mask >= for > vectors 33
Other radii from kept sensors only vectors 1
Other contours 6 to 5 vectors 23, rules 2
Other absmax from the largest value vectors 15
Other head not squeezed vectors 31, rules 1
Other no flat_field note vectors 7, rules 2
Other grid 67 to 66 vectors 33
Other LU without pivoting vectors 32, rules (file fails), solver 2
Layout FLAT_RATIO 0.05 to 0.04 layout vectors 1
Layout PARTIAL_DILUTION 4.5 to 4.7 layout vectors 1
Layout PARTIAL_SHIFT 0.12 to 0.13 layout vectors 1
Layout COVERAGE_ELEVATION 38 to 40 layout vectors 2
Layout GAP_AZIMUTH 120 to 125 layout vectors 2
Layout RAS kept as ALS field vectors 3, layout vectors 60
Layout theta not wrapped into (−180, 180] layout vectors 1
Layout fiducials kept as scalp rows layout vectors 4

The checks added in the review round, by the same method (worker and colormap suites, and the size script itself):

Check Mutation Caught by
Exact grids narrow to Float32 before transfer worker 9 (the received-grid parity of the near-flat cases, among them)
Contours on request trace every map worker 1
Geometry once send it in every batch worker 1
Batches one batch size for every batch worker 3
messageerror client ignores it worker 1
Dropped worker client hears its late events worker 1
Retry after failure client keeps the failed worker worker 2
Addressed failure client drops it worker 1
Color overflow position on unhalved operands colormap 1
Non-finite entry no guard colormap 1
Size gate worker budget 12 KB to 4 KB the script exits 1
Size gate main-thread budget to 5 KB (5.5 KB with the shared chunk) the script exits 1
Size gate count the entry chunk only the script exits 1 (the measured set must hold the client)

The 42 core mutations above were run again after the round: all still killed.

Deviations

  1. Plan C7 is superseded where the ADR 0137 amendment and sensor-field.md say so:
    • 8 sensors, not 3;
    • mean-removed interpolation;
    • the flat and near-flat notes;
    • exact merge means;
    • the minmax margin of 5% of the range;
    • EEGLAB's nose;
    • the parity bound 1e-6 * range + 1e-12 * magnitude;
    • the words head_outside_grid and interpolation_failed.
  2. Template montage centers.
    views/montages is not copied yet (ADR 0035 decision 2 copies it with the montages).
    So sensorLayout takes the montage center as an injected montageCenter and throws when it is missing.
    The tests read each template center from the vector's own expected center (ALS to RAS).
    For those six cases the center check is therefore not independent; the frame rules, the rotation and the projection still are.
    The cases are positions_template, positions_template_midline, template_montage, template_full_1005, template_midline_9 and template_coronal_9.
  3. sensor-names.ts is not in the plan's file list.
    The layout's scalp-row rule needs the name rules, which W2b's sensor-labels.ts should import rather than repeat.
  4. The Green's function is evaluated as r2 * (ln(r2) / 2 − 1) with no square root and no hypot.
    It differs from the reference in the last bits; the worst cell is 2.1e-6 of the bound.
  5. No page imports the client yet, so the CI size step measures Astro's Vite building the client as an entry, beside the real astro build it also runs; dist/ is measured from the first page that imports it.
    The perf gate runs the in-thread worker path in Node, because Node has no Web Worker; the real worker is timed by the e2e spec, which, like every e2e spec here, runs locally only.
    The gate is skipped inside the parallel bun run test, where timings would measure the other test files, and runs in a CI step of its own.
  6. Grids are Float64Array, not the plan's Float32: the narrower type rounded near-flat maps onto one value (the review's finding), and transferring the algorithm's own array costs no copy at all.
    Contour lines are unjoined segments, traced in the worker for the maps on screen only.
  7. topo.ts is untouched; W3 moves the viewer.

What W3 needs

  • The montages copy.
    • Widen the copy rule in scripts/copy-quality-views-vocabulary.mjs and test/quality-views-vocabulary-drift.test.ts to views/montages/*.json, PROVENANCE.json included: it carries the montages' sources and licenses, and it is not a montage (sensorLayout already refuses the name).
    • Ship them, and pass montageCenter from the files to sensorLayout.
    • Then replace montageCentersFrom in test/quality-views-vectors.ts with the files, so the six template center checks become independent.
    • W2b's label placement needs the same files.
  • Move the viewer's map onto prepareSensorField / drawSensorFields (or the worker) and sensorLayout, and delete the TPS code, projectPositions and renderTopomap.
  • Swap viridisColor / VIRIDIS_CSS for colormap.ts's SEQUENTIAL_STOPS and colorAt, which test/quality-views-colormap.test.ts pins to the same colors. Update ieeg-spatial/live-activity.ts.
  • sensorLayout throws MontageCenterUnavailable when no montage center is given; W3 must catch it by type and leave the map undrawn with its reason, never end the view.
  • Legends and exports that show the color maps link COLOR_MAPS_NOTICE (W4, W8).
  • The first page that imports worker-client.ts makes the CI size step measure dist/ as well.

A note for neuroschema (spec level)

A single sensor far behind the head, or far to its left, is interpolated (EEGLAB's square has no absolute value) and stretches the grid until almost no cell lies inside the head.
On the 64-sensor cap of the vectors with one sensor added at theta 180 or −90: radius 10 leaves 611 of 3,409 cells inside, 100 leaves 56, and from 200 (300 in the review's probe) a single cell, so the map is drawn as one cell rather than refused.
Farther out the grid misses the head entirely and the whole map is refused with head_outside_grid (the vectors' far_sensor: one sensor at radius 1e10, theta −135).
One bad position thus wrecks the map; a sensor far in front or to the right is simply not interpolated.
This follows the specification as written, so the site keeps it; the coordinator is filing it with neuroschema.

Testing

  • bun run typecheck: 0 errors, 0 warnings.

  • bun run lint: clean.

  • Targeted Vitest, the quality-view files: 283 passed, 4 skipped (the perf gate without QUALITY_VIEWS_PERF=gate, and the vocabulary drift's nemar-cli checks with no local nemar-cli checkout).

  • Full bun run test: 6,994 passed, 52 skipped.

  • bun run test:quality-views-perf passes on this machine and on the CI runner (its own step in run 45718762963): 128 maps in 58.5 ms, 256 in 180.2 ms, first maps 23.5 and 39.3 ms.

  • bunx astro build (4 s), then bun scripts/check-quality-views-size.mjs --require-build passes.

  • bun run test:e2e e2e/quality-views-perf.spec.ts passes, 2/2, in local Chromium.

  • Mutation tables above.

  • CI run 45718762963 on 03998a1 was also red on two of the new stub-transport tests: the runner's Node has no global ErrorEvent. Fixed in 7862d85 (the stub raises an Event with the message). CI run 45719315333 on 7862d85 fails only the 6 expected drift tests; its budget step measured 20.5 / 63.5 ms (128) and 34.8 / 179.9 ms (256), and the size step 5.2 KB and 5.5 KB.

Expected red in CI, as in W1: the vocabulary and pipeline drift tests compare with nemar-cli dev, which does not carry neuroschema 0.6.0 until epic nemarOrg/nemar-cli#2324 merges there.
The budget steps run regardless (!cancelled()) and do not depend on nemar-cli.

Refs #588, nemarOrg/nemar-cli#2324

Partial pivoting in binary64 with the factors kept, so one matrix is solved for many maps in the same operation order as a fresh solve (neuroschema 0.6.0 linalg.py). Tested through the sensor-field and sensor-layout parity suites.
EEGLAB topoplot v4 map per neuroschema 0.6.0 and the ADR 0137 amendment: mean-removed interpolation, exact merge means, 8-sensor minimum, flat_field and near_flat notes, 5% minmax margin. Geometry (factorized G, evaluation matrix) is shared by every map of a view.
Positions to topoplot layout: exact BIDS frame table, scalp rows, montage or sphere center with the six bounds, cart2topo. The name rules it reads (fold, clean, finish, types, fiducials) live in sensor-names.ts for W2b to build on.
Every case of sensor-field.v1.json (42) and sensor-layout.v1.json (66, plus every frame name and cart2topo point) within the specs' parity bounds; refusals by exact word. Tested: 166/166 pass.
Mean removal (offset invariance, exact flat fields), the exact merge mean, the near-flat threshold either side, the 8-sensor minimum after merge and drop, the 5% minmax margin and EEGLAB absmax axis. Tested: 25/25 pass.
Types, name exclusions, unhyphenated keys and fiducials checked on all 5,895 sensor-labels.v1 channels, plus fold, clean and finish edge cases. Tested: 9/9 pass.
The renderer's own lines at the spec's six levels, outside parity: masked corners draw nothing, saddles split by the square's mean. Tested: straight lines, closed rings, masks, saddles (6/6).
Geometry cached by layout SHA-256 and usable rows, maps on screen first then batches, Float32 grids and contour segments transferred, cancel between batches. The client imports no numerics. Tested over a real MessageChannel: 15/15.
Diverging (ColorBrewer RdBu reversed), sequential (the viewer's viridis stops) and the Turbo LUT, with their Apache-2.0 notices; --qv-* tokens, data colors theme-independent, head line per theme. Tested: tokens equal the tables, viridis equals viridisColor, Turbo digest (7/7).
Each E and w value is loaded once for eight sums; every sum still runs over the sensors in order, so cells are bit-identical to the one-map loop. 128-sensor view (128 maps) 44 to 36 ms in Node. Tested: parity 47/47.
Each square is visited once and traced only for the levels inside its corner range, edges computed only when crossed. 128 maps: about 15 to 7 ms. Tested: contours 6/6, worker 15/15.
Vitest gates the full worker path at twice the budget (first maps 50 ms, 128-sensor view 100 ms, 256 at 300) for 128 and 256 IC maps; the Playwright spec times a real module worker in Chromium against the budgets themselves. Tested: both pass on this machine.
Worker at most 12 KB and the lazy chunk at most 30 KB gzipped, bundled alone with Bun (and in dist/ when built); runs in CI's test job. Tested: worker 5.2 KB, main thread so far 3.4 KB; a 4 KB budget fails it; bun run build passes.
976562.5 and 976562.4990234375 differ by exactly 1e-9 of the magnitude; the mutation of <= to < survived every other test and fails this one.
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Deploying nemar-website with  Cloudflare Pages  Cloudflare Pages

Latest commit: 7862d85
Status: ✅  Deploy successful!
Preview URL: https://5d29ebb9.nemar-website.pages.dev
Branch Preview URL: https://feature-issue-588-w2-sensor.nemar-website.pages.dev

View logs

center([v]) is v + 0, written without allocating a group array per sensor per map. Bit-identical: parity 47/47, the 42 core mutations still all killed.
MontageCenterUnavailable lets W3 catch the site's own wiring fault by type and leave the map undrawn with a sentence. Tested: layout parity 119/119.
Review of #591: grids leave as the algorithm's own Float64Array, transferred (Float32 flattened near-flat maps); geometry once per draw; contours only for maps on screen (contoursOf traces the rest); larger later batches; messageerror handled; a dropped worker's events ignored. Tested: the received grid of all 33 drawn vectors within the parity bound; stub-transport error paths (56/56).
Owner ruling: keep ADR 0137's budget. The perf test gates at the budget itself (first maps 50 ms, 128-map view 100 ms, 256 at 300) in its own CI step, alone on the runner, and is skipped inside the parallel suite. Tested on M4: 6.8 / 20.9 ms and 12.8 / 68.3 ms medians.
The CI size step now runs after astro build, even when Vitest failed, and measures dist/ once a page imports the client; until then Astro's own Vite builds the client as an entry with its worker. Shared chunks count. Tested: worker 5.2 KB, main thread 5.5 KB; lowered budgets and an entry-only count fail it.
entryFor works on halved operands, so an axis wider than the largest double (a flat field at 1.5e308, absmax +-1.575e308) places its cells, and a position that is not finite takes the middle entry, never an empty one. Tested: flat_huge_duplicate_pair paints entry 249 in every cell; both mutations fail.
public/licenses/quality-views/NOTICE.txt carries Turbo's and ColorBrewer's Apache-2.0 notices with the license's full text, served beside the bundles; COLOR_MAPS_NOTICE names it for legends and exports. Tested: the file holds both copyrights and the full license.
CI's Node has no global ErrorEvent, so two stub-transport tests failed there (one by timeout). The stub now raises an Event carrying the message the client reads. Tested: 56/56 with ErrorEvent deleted, the pushed version fails the same 2 that way.
@neuromechanist
neuromechanist merged commit 3689f2f into feature/issue-586-epic-pipeline-progress Nov 25, 2026
3 of 4 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-588-w2-sensor-field branch November 25, 2026 23:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant