forked from github.com/concept-collection/turing-surface
Comparing changes
main is 26 commits ahead of random-fields.
Create pull request
Merge pull request #11 from concept-collection/compare-against-sphere
Jeremy Magland committed
9321562Merge main into compare-against-sphere
Jeremy Magland committed
9916f17Accept a surface handed over as coefficients (reharm's export button)
Dan Fortunato committed
77f627eexport standalone matlab
Jeremy Magland committed
9b71d5bWIP: comparison with unit sphere
Owen Melia committed
cf4af12Update comparison UI
Owen Melia committed
02e7a36Merge pull request #10 from concept-collection/compare-interface
Jeremy Magland committed
71b6492Add short descriptions for each mode
Owen Melia committed
2bb4f78Adding a way to reset simulation from same random IC.
Owen Melia committed
ca37955Fixing some bugs in the UI
Owen Melia committed
c8e230aWIP: First draft at new interface with multiple comparison modes
Owen Melia committed
9389d73Update ids in index.html for easier refactor
Owen Melia committed
a158c73Merge pull request #9 from concept-collection/reference-compare-mode
Jeremy Magland committed
c88cad7Generate numbl's stdlib bundle in the preview workflow too
Jeremy Magland committed
1a01a2fGenerate numbl's stdlib bundle in the preview workflow too
Jeremy Magland committed
90d9678Open the reference comparison in one click
Jeremy Magland committed
3210e7dCheck reference files in the browser's compare mode
Jeremy Magland committed
c90d0e2Merge pull request #6 from concept-collection/reference_soln
Jeremy Magland committed
327b4ecMerge main into reference_soln
Jeremy Magland committed
4b7c487Scale the randnfun3 GPU/CPU bound to the field
Dan Fortunato committed
c2fcb48Generate numbl's stdlib bundle in CI
Dan Fortunato committed
cc9b1caMerge pull request #7 from concept-collection/random-fields
Jeremy Magland committed
87ad61eChanged local node to version 24; updated package-lock.json accordingly
Owen Melia committed
f4de749Updated command now tracks L_infty error too.
Owen Melia committed
66ae13eMerge branch 'main' into reference_soln
Owen Melia committed
b460a9fCommand for testing against a reference implementation
Owen Melia committed
90108a628 changed files+3660−193
.github/workflows/ci.ymlmodified+11−5View file
@@ -14,14 +14,19 @@ jobs:
1414 node-version: 24
1515 cache: npm
1616 # numbl is a `file:../../numbl` dependency: we use its compiler internals
17- # (parser, lowerer, IR, inline pass), which its published package `exports`
18- # do not expose. Clone it where that relative path expects it. Pinned so a
19- # change to those internals cannot silently break the build — the surface we
20- # rely on is written down in src/mgpu/numbl.d.ts.
17+ # (parser, lowerer, IR, inline pass) and its interpreter, which its
18+ # published package `exports` do not expose. Clone it where that relative
19+ # path expects it. Pinned so a change to those internals cannot silently
20+ # break the build — the surface we rely on is written down in
21+ # src/mgpu/numbl.d.ts.
2122 #
2223 # numbl's own dependencies are NOT needed: the slice we import is
2324 # self-contained TypeScript, verified by building against a checkout with no
24- # node_modules.
25+ # node_modules. One file in it is generated rather than committed, though —
26+ # the interpreter's stdlib bundle, which numbl gitignores — so a bare
27+ # checkout is missing it and `executeCode.ts` fails to resolve it. Its
28+ # generator only reads .m files off disk, so plain `node` (type-stripping,
29+ # unflagged since 22.18) runs it without installing anything.
2530 - name: Check out numbl (sibling dependency)
2631 env:
2732 NUMBL_REF: main
@@ -29,6 +34,7 @@ jobs:
2934 git clone --filter=blob:none --no-checkout \
3035 https://github.com/flatironinstitute/numbl.git "$GITHUB_WORKSPACE/../../numbl"
3136 git -C "$GITHUB_WORKSPACE/../../numbl" checkout --quiet "$NUMBL_REF"
37+ node "$GITHUB_WORKSPACE/../../numbl/scripts/bundle-stdlib.ts"
3238 # --ignore-scripts: npm runs a linked package's `prepare` script, and
3339 # numbl's is husky, which is not installed here.
3440 - run: npm ci --ignore-scripts
.github/workflows/deploy.ymlmodified+11−5View file
@@ -26,14 +26,19 @@ jobs:
2626 node-version: 24
2727 cache: npm
2828 # numbl is a `file:../../numbl` dependency: we use its compiler internals
29- # (parser, lowerer, IR, inline pass), which its published package `exports`
30- # do not expose. Clone it where that relative path expects it. Pinned so a
31- # change to those internals cannot silently break the build — the surface we
32- # rely on is written down in src/mgpu/numbl.d.ts.
29+ # (parser, lowerer, IR, inline pass) and its interpreter, which its
30+ # published package `exports` do not expose. Clone it where that relative
31+ # path expects it. Pinned so a change to those internals cannot silently
32+ # break the build — the surface we rely on is written down in
33+ # src/mgpu/numbl.d.ts.
3334 #
3435 # numbl's own dependencies are NOT needed: the slice we import is
3536 # self-contained TypeScript, verified by building against a checkout with no
36- # node_modules.
37+ # node_modules. One file in it is generated rather than committed, though —
38+ # the interpreter's stdlib bundle, which numbl gitignores — so a bare
39+ # checkout is missing it and `executeCode.ts` fails to resolve it. Its
40+ # generator only reads .m files off disk, so plain `node` (type-stripping,
41+ # unflagged since 22.18) runs it without installing anything.
3742 - name: Check out numbl (sibling dependency)
3843 env:
3944 NUMBL_REF: main
@@ -41,6 +46,7 @@ jobs:
4146 git clone --filter=blob:none --no-checkout \
4247 https://github.com/flatironinstitute/numbl.git "$GITHUB_WORKSPACE/../../numbl"
4348 git -C "$GITHUB_WORKSPACE/../../numbl" checkout --quiet "$NUMBL_REF"
49+ node "$GITHUB_WORKSPACE/../../numbl/scripts/bundle-stdlib.ts"
4450 # --ignore-scripts: npm runs a linked package's `prepare` script, and
4551 # numbl's is husky, which is not installed here.
4652 - run: npm ci --ignore-scripts
.github/workflows/preview.ymlmodified+6−1View file
@@ -93,7 +93,11 @@ jobs:
9393 # numbl is a `file:../../numbl` dependency: we use its compiler internals
9494 # (parser, lowerer, IR, inline pass), which its published package
9595 # `exports` do not expose. Clone it where that relative path expects it,
96- # pinned to the same ref as ci.yml and deploy.yml.
96+ # pinned to the same ref as ci.yml and deploy.yml. One file in it is
97+ # generated rather than committed — the interpreter's stdlib bundle,
98+ # which numbl gitignores — so a bare checkout is missing it and
99+ # `executeCode.ts` fails to resolve it; its generator only reads .m files
100+ # off disk, so plain `node` runs it without installing anything.
97101 - name: Check out numbl (sibling dependency)
98102 env:
99103 NUMBL_REF: main
@@ -101,6 +105,7 @@ jobs:
101105 git clone --filter=blob:none --no-checkout \
102106 https://github.com/flatironinstitute/numbl.git "$GITHUB_WORKSPACE/../../numbl"
103107 git -C "$GITHUB_WORKSPACE/../../numbl" checkout --quiet "$NUMBL_REF"
108+ node "$GITHUB_WORKSPACE/../../numbl/scripts/bundle-stdlib.ts"
104109 # --ignore-scripts: npm runs a linked package's `prepare` script, and
105110 # numbl's is husky, which is not installed here.
106111 - run: npm ci --ignore-scripts
.gitignoremodified+1−0View file
@@ -1,3 +1,4 @@
1+tmp/
12 node_modules/
23 dist/
34 *.log
README.mdmodified+48−0View file
@@ -68,6 +68,16 @@ solver and does not disturb the run: the geometry is data whose shape in the
6868 bindings depends only on the grid, so a swap is sixteen buffer writes and the
6969 pattern carries straight on.
7070
71+A sixth kind of geometry arrives from outside: reharm (the sibling
72+spherical-harmonic fitting app) can hand a fitted surface — a scanned mesh, a
73+brain, a point cloud — to this page with its **Export to turing-surface**
74+button. The surface arrives as coefficients by `postMessage` (there is no .m;
75+`Geometry` is built from them directly, re-indexed onto whatever band is
76+selected), lands as an **imported** entry in the geometry dropdown at its own
77+lmax, and behaves like any other shape from there — except that the editor,
78+the benchmark command line and the MATLAB export, all of which need a .m, say
79+so instead.
80+
7181 A **morph** slider blends the drawn surface back to the unit sphere. The
7282 parametrization is the sphere's either way, so sweeping it shows which point
7383 went where.
@@ -497,6 +507,12 @@ package alone. Its binaries need glibc 2.29+. Other flags: `--steps`,
497507 `--warmup`, `--batch`, `--json`, `--help`; `DAWN_FLAGS='backend=vulkan'`
498508 (`;`-separated) passes Dawn options through.
499509
510+### The same run in MATLAB
511+
512+A run in the page needs a browser and a GPU; further analysis usually wants neither. The app therefore exports the run on screen as one self-contained MATLAB function file: **The same run as a standalone MATLAB script**, under the benchmark command, shows the script for copying and downloads it as `turing_surface_run.m`. The current model and geometry `.m` go in verbatim, edits in the page included, with the parameter values baked in; around them the file carries double-precision ports of everything the host provides: the transforms and their derivative shuffles, the metric weights, the seeded random field, and the run loop ([`src/export/`](src/export/)). It needs base MATLAB only, R2020b or newer, no toolboxes.
513+
514+Two deliberate differences from the page are stated in the script's own header: it runs in f64 where the GPU path is f32, and random draws use MATLAB's own `rng`, so a seed value picks a different member of the same random ensemble than the same value in the app. The script plots the pattern live and writes its initial and final spectral state to HDF5 in the reference-run layout of [docs/ellipsoid-reference-spec.md](docs/ellipsoid-reference-spec.md), so a MATLAB run can be loaded back into the page (**Compare against uploaded data**) or checked with `npm run ref -- --in turing_surface_run.h5`. Exported at the defaults, a 60-step Schnakenberg run on the ellipsoid replayed that way agrees with the app to relative L2 of about 1e-7, which is fp32 accumulation; the exported flux-form and Algorithm-4 models track each other to about 3e-10 in f64.
515+
500516 ## Tests
501517
502518 There is no second implementation of the solver to diff against, so the `.m`
@@ -591,6 +607,38 @@ Other commands:
591607 - `node scripts/check-live.mjs [url]` — smoke-check a deployed URL.
592608 - `test.html?soak=<steps>&lmax=<n>` — solver-only soak with no rendering.
593609
610+### Testing against a reference implementation
611+
612+Reference solutions live in the sibling
613+[turing-surface-test-data](https://github.com/concept-collection/turing-surface-test-data)
614+repo, so an independently-written solver never has to depend on this one.
615+`cases/schnakenberg-ellipsoid.md` there specifies the one case this repo
616+currently ships a reference for;
617+[`docs/ellipsoid-reference-spec.md`](docs/ellipsoid-reference-spec.md)
618+restates it in this repo's own terms.
619+
620+`npm run ref -- --in <file>` (`scripts/ref.ts`) loads a reference file, runs
621+the solver from its exact initial spectral state to the same physical end
622+time, and reports the relative-L2 and relative-L-infinity (max-norm) error
623+against its final state (plus a geometry sanity check). `--niter` overrides
624+the surface-correction iteration count independent of the file, and
625+`--tolerance`/`--tolerance-linf` each independently turn their metric into a
626+pass/fail for CI.
627+
628+The same check runs in the page: **Compare to reference…** picks a `.h5` and
629+opens the comparison in one step — the file's own settings (its recorded
630+niter, its band, its dt) as the single variant, paused at the file's exact
631+initial state, ready to Run. The file defines the whole problem — model,
632+parameters, geometry, initial state — and the run stops at the file's end
633+time, measured against one extra static row showing its final state on its
634+own surface. Watching *where* a variant leaves the reference (rather than
635+just reading one number per run) is the point. To widen the study, stop
636+comparing, pick more chips, and press Compare — the file stays loaded, with
637+the lmax choices floored at its band, since a narrower one could not hold
638+its initial state. Reading the file uses
639+[h5wasm](https://github.com/usnistgov/h5wasm)'s wasm build, loaded lazily on
640+the first file opened.
641+
594642 ## Development
595643
596644 ```
docs/ellipsoid-reference-spec.mdadded+127−0View file
@@ -0,0 +1,127 @@
1+# Reference test case: Schnakenberg on a triaxial ellipsoid
2+
3+For validating this repo's Laplace-Beltrami surface correction against an
4+independently-implemented reference solver, comparing final state in
5+spherical-harmonic (SH) coefficient space.
6+
7+## Geometry
8+
9+A triaxial ellipsoid, `gx = ax·sinθ·cosφ`, `gy = ay·sinθ·sinφ`,
10+`gz = az·cosθ` (`geometries/ellipsoid.m`; defaults `ax=1.5, ay=1.0, az=0.6`).
11+
12+**Important**: the solver does not run on this analytic surface — it
13+band-limits it first, analysing `(gx, gy, gz)` into SH coefficients truncated
14+at degree `lmax` and re-synthesizing before use (`src/geom/geometry.ts`). To
15+remove geometry-representation error as a confound, a reference file
16+supplies these coefficients directly as `/geometry/Gx`, `/geometry/Gy`,
17+`/geometry/Gz`. **The reference solver must reconstruct its surface (and
18+induced metric) by synthesizing these coefficients, not by evaluating the
19+analytic formula above.**
20+
21+## Equations
22+
23+Schnakenberg reaction-diffusion with the true surface Laplace-Beltrami
24+operator `Δ_g` (`models/schnakenberg.m`):
25+
26+```
27+du/dt = D1·Δ_g(u) + a - u + u²v
28+dv/dt = D2·Δ_g(v) + b - u²v
29+```
30+
31+This repo's internal discretization (`niter` Richardson-iteration count for
32+its own `Δ_g` approximation, `dt` for its IMEX-Euler timestep) is not part of
33+the equations being tested — the reference solver may use any consistent
34+method for `Δ_g` and any timestep. It only needs to reach the same physical
35+end time `T = steps · dt`.
36+
37+## Initial condition
38+
39+Loaded from the reference file's `/initial/U` / `/initial/V` (t=0,
40+immediately after seeding, before any step), not regenerated — avoids
41+needing to reimplement this repo's PRNG (`src/mgpu/noise.ts`) to get a
42+matching initial condition.
43+
44+## Output convention (must match exactly, from `src/sht/layout.ts`)
45+
46+- Orthonormal spherical harmonics **including Condon-Shortley phase**.
47+- Real field ⇒ complex coefficients stored for `m ≥ 0` only:
48+ `Q_{l,-m} = (-1)^m · conj(Q_lm)`; `m=0` coefficients have zero imaginary part.
49+- **m-major ordering**: for `m = 0..lmax`, for `l = m..lmax`.
50+ `index(l,m) = m·(lmax+1) − m·(m−1)/2 + (l−m)`.
51+- Flat array, length `2·nlm` with `nlm = (lmax+1)(lmax+2)/2`, `[re,im]`
52+ interleaved per coefficient (`qlm[2·index(l,m)]`, `qlm[2·index(l,m)+1]`).
53+
54+The reference solver must project its final `u`, `v` onto this same
55+convention/truncation and report flat `2·nlm` arrays, to diff directly
56+against the reference file's `/final/U` / `/final/V`.
57+
58+## HDF5 file layout
59+
60+Each reference file is one `.h5` file per run (written with
61+[h5wasm](https://github.com/usnistgov/h5wasm); readable from Python with
62+`h5py.File(path, "r")`). Coefficient datasets are `float32`, each of length
63+`2·nlm` in the convention above. Metadata is stored as attributes, grouped by
64+what it describes rather than as a single flat namespace:
65+
66+```
67+/ (attrs: command, model, species)
68+├─ backend/ (attrs: adapter, runtime, precision)
69+├─ spec/ (attrs: preset, geometry, lmax, seed, steps, warmup, niter)
70+│ ├─ params/ (attrs: the model's own params, e.g. a, b, D1, D2, dt)
71+│ └─ geometry_params/ (attrs: the geometry's own params, e.g. ax, ay, az)
72+├─ grid/ (attrs: lmax, mmax, nlat, nphi, nlm)
73+├─ geometry/
74+│ ├─ Gx dataset, float32[2·nlm]
75+│ ├─ Gy dataset, float32[2·nlm]
76+│ └─ Gz dataset, float32[2·nlm]
77+├─ initial/ one dataset per species (e.g. U, V), float32[2·nlm] each
78+└─ final/ one dataset per species (e.g. U, V), float32[2·nlm] each
79+```
80+
81+`species` (root attribute) names which datasets live under `initial/` and
82+`final/` — `["U", "V"]` for Schnakenberg. `command` is the equivalent
83+`npm run bench --` invocation, for reproducing the run exactly.
84+
85+## Parameters
86+
87+| name | meaning | default |
88+|---|---|---|
89+| `a`, `b` | Schnakenberg kinetics | 0.1, 0.9 |
90+| `D1`, `D2` | diffusion coefficients | 4e-4, 8e-3 |
91+| `ax`, `ay`, `az` | ellipsoid semi-axes | 1.5, 1.0, 0.6 |
92+| `lmax` | SH truncation degree | 63 |
93+| `T = steps·dt` | physical end time | e.g. 2000·0.05 = 100 |
94+| `seed` | provenance only — IC supplied as coefficients | 1 |
95+
96+## Checking a run against a reference file
97+
98+`npm run ref -- --in <file>` loads a reference file, runs this
99+repo's own solver from its exact initial condition to the same physical end
100+time, and reports the relative-L2 and relative-L-infinity (max-norm) error of
101+the resulting state against the file's final state (and, as a sanity check,
102+of the regenerated geometry against the file's own geometry coefficients —
103+this should be ~0 unless geometry construction itself has changed). `--niter
104+<n>` overrides the solve's own iteration count for the surface correction,
105+independent of what the reference file was generated with — useful for seeing
106+how much that correction term actually matters for a given run. `--tolerance
107+<n>` and `--tolerance-linf <n>` each independently turn their metric into a
108+pass/fail (nonzero exit code on failure), for use in CI.
109+
110+The browser demo runs the same check visually: **Compare to reference…**
111+picks a reference file and opens the comparison in one step, with the file's
112+own settings as the single variant, paused at its exact initial state. Run
113+takes it to the file's end time and stops; its final state shows as one
114+extra static row — on the file's own surface, with each variant's
115+relative-L2 distance to it updating live — and more variants can be added
116+from the compare bar's chips. Both readers share one parser
117+(`src/compare/referenceCase.ts`), so the layout above is interpreted
118+identically on the CLI and in the page.
119+
120+Note the files record only the two endpoint states (`initial/`, `final/`) —
121+no intermediate snapshots — so the comparison is meaningful at the end time;
122+the live Δ before that reads as "distance still to the final state".
123+
124+## Caveat
125+
126+This repo runs fp32 on GPU; expect ~1e-4–1e-6 relative floating-point noise
127+on top of any genuine numerical-method disagreement between solvers.
index.htmlmodified+175−60View file
@@ -51,6 +51,19 @@
5151 }
5252 /* display:flex above would otherwise override the UA's [hidden] rule */
5353 .controls[hidden] { display: none; }
54+ .modes {
55+ display: flex; flex-wrap: wrap; gap: 8px;
56+ padding: 4px 0 10px; margin-bottom: 4px;
57+ border-bottom: 1px solid var(--line);
58+ }
59+ .modes .chip { font-size: 13px; padding: 4px 12px; }
60+ .mode-desc {
61+ color: var(--ink); margin: 0 0 12px; font-size: 13.5px;
62+ padding: 10px 14px; border-radius: 6px;
63+ border-left: 3px solid var(--accent);
64+ background: color-mix(in srgb, var(--accent) 10%, var(--bg));
65+ }
66+ .mode-desc:empty { display: none; }
5467 .controls label { color: var(--ink-2); font-size: 13px; white-space: nowrap; }
5568 select, input[type="number"], button {
5669 font: inherit; font-size: 13px;
@@ -104,6 +117,14 @@
104117 font: 12px/1.6 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
105118 color: var(--ink); user-select: all;
106119 }
120+ details.cli > summary { cursor: pointer; }
121+ details.cli > summary::before { content: '▸'; font-size: 10px; color: var(--ink-2); }
122+ details.cli[open] > summary::before { content: '▾'; }
123+ #matlabscript {
124+ margin: 0; padding: 8px 10px; max-height: 30em; overflow: auto;
125+ font: 12px/1.5 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
126+ color: var(--ink); white-space: pre; user-select: text;
127+ }
107128 #blurb { margin-top: 4px; font-size: 13px; color: var(--ink-2); }
108129 #err { color: #b35900; white-space: pre-wrap; font-size: 13px; }
109130 .editor {
@@ -116,10 +137,14 @@
116137 background: var(--sphere-bg); border-bottom: 1px solid var(--line);
117138 }
118139 .editor-head button { padding: 2px 10px; font-size: 12px; }
119- /* Source and compiled-op list side by side, so the editor gets the
120- height rather than sharing it with the list below. */
121- .editor-body { display: flex; align-items: stretch; }
122- .editor-code { position: relative; flex: 1 1 62%; min-width: 0; height: 34em; }
140+ /* Source and compiled-op list side by side. The fixed height lives on
141+ the row itself, not on either child: a child's own `height` would
142+ only be a *hint* stretch fills when unset, and `#compiled` sets its
143+ own smaller font, so the same em value would resolve to a shorter
144+ box than .editor-code's. Sizing the row instead makes both children
145+ stretch to one shared pixel height regardless of either's font. */
146+ .editor-body { display: flex; align-items: stretch; height: 34em; }
147+ .editor-code { position: relative; flex: 1 1 62%; min-width: 0; }
123148 /* The overlay and the textarea must agree on every metric that affects
124149 where a character lands. Keep these two rules together. */
125150 .editor-code > pre,
@@ -150,7 +175,9 @@
150175 color: var(--ink-2); white-space: pre;
151176 }
152177 @media (max-width: 860px) {
153- .editor-body { flex-direction: column; }
178+ /* Stacked, so each panel goes back to managing its own height rather
179+ than sharing the row's fixed one. */
180+ .editor-body { flex-direction: column; height: auto; }
154181 .editor-code { flex: none; height: 26em; }
155182 #compiled { border-left: 0; border-top: 1px solid var(--line); max-height: 12em; }
156183 }
@@ -158,6 +185,12 @@
158185 /* The bar's own layout: three chip rows stacked, then the reference
159186 picker and the button beside them. */
160187 .cmp-axes { display: flex; flex-direction: column; gap: 4px; }
188+ /* Without this, JS setting the `hidden` attribute (vs-sphere mode,
189+ which has no chip grid) does nothing: [hidden] and .cmp-axes tie on
190+ specificity, and the author rule above wins the tie over the
191+ browser's default — the exact opposite of what `hidden` is supposed
192+ to mean. */
193+ .cmp-axes[hidden] { display: none; }
161194 .cmp-axis { display: flex; align-items: center; gap: 8px; }
162195 .cmp-axis > span:first-child {
163196 color: var(--ink-2); font-size: 13px; width: 5.5em; text-align: right;
@@ -206,6 +239,47 @@
206239 border: 1px solid var(--line); border-radius: 2px;
207240 }
208241 .cmp-rangelab { font-variant-numeric: tabular-nums; white-space: nowrap; }
242+ /* The diff row sits right under its variant's value row: same label
243+ width so the columns still line up, but a lighter tone since it names
244+ no new variant, only the difference from one already named above. */
245+ .cmp-diffrow .cmp-rowlabel { color: var(--ink-2); font-style: italic; }
246+ .cmp-diffbox { position: relative; }
247+ .cmp-diffcap {
248+ position: absolute; bottom: 4px; right: 6px;
249+ font-size: 11px; font-variant-numeric: tabular-nums;
250+ color: #fff; background: rgba(0, 0, 0, 0.45);
251+ padding: 1px 5px; border-radius: 4px; pointer-events: none;
252+ }
253+ .cmp-chart {
254+ margin-top: 8px; padding: 8px 10px;
255+ border: 1px solid var(--line); border-radius: 8px;
256+ }
257+ .cmp-chart-legend {
258+ display: flex; flex-wrap: wrap; gap: 6px 18px;
259+ font-size: 12px; color: var(--ink-2); margin-bottom: 6px;
260+ }
261+ .cmp-chart-legend-group { display: flex; flex-wrap: wrap; gap: 12px; }
262+ /* The species group (dash styles) reads as a separate cluster from the
263+ variant group (colors) — a rule between them, not just a gap, since
264+ both groups otherwise look like more of the same kind of chip. */
265+ .cmp-chart-legend-species {
266+ padding-left: 14px; border-left: 1px solid var(--line);
267+ }
268+ .cmp-chart-legend-item { display: inline-flex; align-items: center; gap: 5px; }
269+ .cmp-chart-legend-item i {
270+ display: inline-block; width: 10px; height: 10px; border-radius: 2px;
271+ }
272+ /* Species swatches reuse the color chip's box model but draw a dashed
273+ line instead of a filled square, so the two legend groups still read
274+ as one visual language (a small icon + a name). */
275+ .cmp-chart-legend-species i.cmp-chart-dash {
276+ width: 16px; height: 0; border-radius: 0;
277+ border-top-width: 2px; border-top-color: var(--ink-2);
278+ }
279+ .cmp-chart-dash-0 { border-top-style: solid; }
280+ .cmp-chart-dash-1 { border-top-style: dashed; }
281+ .cmp-chart-dash-2 { border-top-style: dotted; }
282+ .cmp-chart-canvas { width: 100%; height: 240px; display: block; }
209283 @media (max-width: 860px) {
210284 .cmp-row { flex-direction: column; }
211285 .cmp-rowlabel { width: auto; flex-direction: row; gap: 10px; }
@@ -229,16 +303,56 @@
229303 browser by <a href="https://numbl.org">numbl</a>. Edit either and watch
230304 it change. Drag to rotate.
231305 </p>
232- <div class="controls">
233- <label>preset
306+ <div class="modes" id="modebar">
307+ <button type="button" class="chip" id="mode-simulate" aria-pressed="true">Simulate</button>
308+ <button type="button" class="chip" id="mode-effort"
309+ title="Run several solver settings side by side on one clock">Compare computational effort</button>
310+ <button type="button" class="chip" id="mode-vs-sphere"
311+ title="Run this model once on the true geometry and once on the unit sphere, from the same starting state">
312+ Compare against sphere</button>
313+ <button type="button" class="chip" id="mode-vs-upload"
314+ title="Check this solver against a saved reference run">
315+ Compare against uploaded data</button>
316+ <input type="file" id="cmp-file" accept=".h5" hidden>
317+ </div>
318+ <p class="mode-desc" id="mode-desc"></p>
319+ <div class="controls ctrl-group" data-group="surface">
320+ <label>reaction-diffusion model
234321 <select id="model"></select>
235322 </label>
236323 <label title="The surface the pattern is solved on. Swapping it does not recompile the solver or restart the run.">geometry
237324 <select id="geometry"></select>
238325 </label>
239- <label title="Blend between the sphere (0) and the surface (1). Display only.">morph
240- <input type="range" id="morph" min="0" max="1" step="0.01" value="1" />
326+ </div>
327+ <div class="ctrl-group" data-group="surface-params">
328+ <div class="controls" id="params"></div>
329+ <div class="controls" id="geomparams"></div>
330+ </div>
331+ <div class="controls" id="comparebar" hidden>
332+ <div class="cmp-axes" id="cmp-axes">
333+ <div class="cmp-axis">
334+ <span title="Iterations of the implicit diffusion solve">solve iters</span>
335+ <span id="cmp-niter" class="chips"></span>
336+ </div>
337+ <div class="cmp-axis">
338+ <span>lmax</span>
339+ <span id="cmp-lmax" class="chips"></span>
340+ </div>
341+ <div class="cmp-axis">
342+ <span title="Timestep, as a divisor of the model's dt. Divisors keep every variant on the same clock exactly.">dt</span>
343+ <span id="cmp-dt" class="chips"></span>
344+ </div>
345+ </div>
346+ <label title="The run everything else is measured against" id="cmp-reflabel">reference
347+ <select id="cmp-ref"></select>
241348 </label>
349+ <span id="cmp-fileinfo" class="stats" hidden></span>
350+ <button id="cmp-fileclear" hidden
351+ title="Drop the reference file and compare the variants against each other again">×</button>
352+ <button id="cmp-start" class="primary">Compile comparison</button>
353+ <span id="cmp-count" class="stats"></span>
354+ </div>
355+ <div class="controls ctrl-group" data-group="solver">
242356 <label title="Iterations of the implicit diffusion solve. Changing it recompiles.">solve iters
243357 <select id="niter">
244358 <option value="0">0</option>
@@ -260,6 +374,8 @@
260374 <option value="255">255</option>
261375 </select>
262376 </label>
377+ </div>
378+ <div class="controls ctrl-group" data-group="display">
263379 <label title="Render on a finer grid. Display only.">display oversampling
264380 <select id="oversample">
265381 <option value="auto" selected>auto</option>
@@ -272,67 +388,56 @@
272388 <label>colormap
273389 <select id="colormap"></select>
274390 </label>
391+ <label title="Blend between the sphere (0) and the surface (1). Display only.">morph
392+ <input type="range" id="morph" min="0" max="1" step="0.01" value="1" />
393+ </label>
394+ <button id="resetview">Reset view</button>
395+ </div>
396+ <div class="controls ctrl-group" data-group="playback">
275397 <button id="runpause" class="primary">Run</button>
398+ <button id="restart" title="Rewind to the initial condition this run started from, without drawing a new one">Restart</button>
399+ </div>
400+ <div class="controls ctrl-group" data-group="benchmark">
276401 <button id="benchmark">Benchmark</button>
277- <label title="Wavelength of the smooth random field the initial condition is seeded from (chebfun's randnfun3, restricted to the surface). An absolute length in the surface's own units, as in chebfun — not a fraction of its size — so smaller means finer features to grow from. Nothing caps it but memory and patience — 0.02 takes about 3 s to seed, 0.01 about 25 s — but it is only *useful* down to about 2*pi/lmax (0.1 at lmax 63): below that the field carries more detail than the grid holds, init's analys discards it, and the seed gets weaker rather than finer. Raise lmax to go finer.">seed λ
402+ </div>
403+ <div class="controls ctrl-group" data-group="seed">
404+ <label title="Wavelength of the smooth random field generating the initial condition">Initial condition wavelength λ
278405 <input id="lam3" type="number" min="0" step="0.05" value="0.5">
279406 </label>
280407 <button id="reseed">Re-seed</button>
281- <button id="resetview">Reset view</button>
282- <button id="movietoggle" title="Export the run as an MP4 movie">Export movie</button>
283- <button id="comparetoggle" title="Run several solver settings side by side on one clock">Compare</button>
284408 </div>
285- <div class="controls" id="comparebar" hidden>
286- <div class="cmp-axes">
287- <div class="cmp-axis">
288- <span title="Iterations of the implicit diffusion solve">solve iters</span>
289- <span id="cmp-niter" class="chips"></span>
290- </div>
291- <div class="cmp-axis">
292- <span>lmax</span>
293- <span id="cmp-lmax" class="chips"></span>
294- </div>
295- <div class="cmp-axis">
296- <span title="Timestep, as a divisor of the model's dt. Divisors keep every variant on the same clock exactly.">dt</span>
297- <span id="cmp-dt" class="chips"></span>
298- </div>
409+ <div class="controls ctrl-group" data-group="movie">
410+ <button id="movietoggle" title="Export the run as an MP4 movie">Export movie</button>
411+ <div class="controls" id="moviebar" hidden>
412+ <label title="Simulation-time units per second of video">movie speed
413+ <select id="moviespeed">
414+ <option value="0.1">0.1×</option>
415+ <option value="0.5">0.5×</option>
416+ <option value="1">1×</option>
417+ <option value="3">3×</option>
418+ <option value="5">5×</option>
419+ <option value="10" selected>10×</option>
420+ <option value="20">20×</option>
421+ </select>
422+ </label>
423+ <label title="Size of each sphere panel in the video, in pixels">resolution
424+ <select id="movieres">
425+ <option value="480">480</option>
426+ <option value="640">640</option>
427+ <option value="768" selected>768</option>
428+ <option value="1080">1080</option>
429+ <option value="1440">1440</option>
430+ </select>
431+ </label>
432+ <label title="Slowly orbit the camera during the movie">
433+ <input type="checkbox" id="movierotate" checked /> auto-rotate
434+ </label>
435+ <button id="movie" title="Replay the run from t = 0 and download an MP4">Export</button>
299436 </div>
300- <label title="The run everything else is measured against">reference
301- <select id="cmp-ref"></select>
302- </label>
303- <button id="cmp-start" class="primary">Compare</button>
304- <span id="cmp-count" class="stats"></span>
305437 </div>
306- <div class="controls" id="moviebar" hidden>
307- <label title="Simulation-time units per second of video">movie speed
308- <select id="moviespeed">
309- <option value="0.1">0.1×</option>
310- <option value="0.5">0.5×</option>
311- <option value="1">1×</option>
312- <option value="3">3×</option>
313- <option value="5">5×</option>
314- <option value="10" selected>10×</option>
315- <option value="20">20×</option>
316- </select>
317- </label>
318- <label title="Size of each sphere panel in the video, in pixels">resolution
319- <select id="movieres">
320- <option value="480">480</option>
321- <option value="640">640</option>
322- <option value="768" selected>768</option>
323- <option value="1080">1080</option>
324- <option value="1440">1440</option>
325- </select>
326- </label>
327- <label title="Slowly orbit the camera during the movie">
328- <input type="checkbox" id="movierotate" checked /> auto-rotate
329- </label>
330- <button id="movie" title="Replay the run from t = 0 and download an MP4">Export</button>
331- </div>
332- <div class="controls" id="params"></div>
333- <div class="controls" id="geomparams"></div>
334438 <p id="geomnote" class="stats"></p>
335439 <div id="panels"></div>
440+ <div id="cmp-chart" class="cmp-chart" hidden></div>
336441 <p class="stats" id="stats"></p>
337442 <p class="stats" id="benchresult"></p>
338443 <div class="editor">
@@ -367,6 +472,16 @@
367472 </div>
368473 <code id="cmd"></code>
369474 </div>
475+ <details class="cli" id="matlab">
476+ <summary class="cli-head">
477+ <span>The same run as a standalone MATLAB script</span>
478+ <span>
479+ <button id="copymatlab" type="button">Copy</button>
480+ <button id="downloadmatlab" type="button">Download .m</button>
481+ </span>
482+ </summary>
483+ <pre id="matlabscript"></pre>
484+ </details>
370485 <p id="blurb"></p>
371486 <p id="err"></p>
372487 </main>
package-lock.jsonmodified+7−0View file
@@ -9,6 +9,7 @@
99 "version": "0.1.0",
1010 "license": "CECILL-2.1",
1111 "dependencies": {
12+ "h5wasm": "^0.10.3",
1213 "mp4-muxer": "^5.2.2",
1314 "numbl": "file:../../numbl",
1415 "three": "^0.183.0"
@@ -1936,6 +1937,12 @@
19361937 "node": ">= 14"
19371938 }
19381939 },
1940+ "node_modules/h5wasm": {
1941+ "version": "0.10.3",
1942+ "resolved": "https://registry.npmjs.org/h5wasm/-/h5wasm-0.10.3.tgz",
1943+ "integrity": "sha512-W4Jy5ExtX/VNbyD8GdOBckDuj6AL16TemppVNxZsV3rJZEWCv2sxlCzOttZLer3zkMttbDYsWHl0qt1z3Bln+Q==",
1944+ "license": "SEE LICENSE IN LICENSE.txt"
1945+ },
19391946 "node_modules/http-proxy-agent": {
19401947 "version": "7.0.2",
19411948 "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
package.jsonmodified+3−1View file
@@ -14,9 +14,11 @@
1414 "test:gpu": "vite build && node scripts/test-gpu.mjs",
1515 "test": "npm run test:node && npm run test:gpu",
1616 "bench": "vite-node scripts/bench.ts",
17- "bench:sht": "vite-node scripts/bench-sht.ts"
17+ "bench:sht": "vite-node scripts/bench-sht.ts",
18+ "ref": "vite-node scripts/ref.ts"
1819 },
1920 "dependencies": {
21+ "h5wasm": "^0.10.3",
2022 "mp4-muxer": "^5.2.2",
2123 "numbl": "file:../../numbl",
2224 "three": "^0.183.0"
scripts/ref.tsadded+215−0View file
@@ -0,0 +1,215 @@
1+/**
2+ * Import a reference HDF5 file — geometry, initial and final spherical-
3+ * harmonic coefficients for a run of this repo's solver, in the format
4+ * documented alongside the sibling test-data repo's case files (see
5+ * ../turing-surface-test-data/cases/) — run this repo's own solver from that
6+ * file's exact initial condition, and report the numerical error against
7+ * its final state.
8+ *
9+ * This is the regression check for the surface Laplace-Beltrami correction:
10+ * replay a saved-off run and see how far this repo's own output has drifted
11+ * (or use --niter to probe how much the correction term itself matters).
12+ *
13+ * npm run ref -- --in data/schnak-spots.h5
14+ * npm run ref -- --in data/schnak-spots.h5 --niter 0
15+ */
16+import { requestShtDevice, describeAdapter } from '../src/sht/sht.ts';
17+import { ModelSession } from '../src/mgpu/session.ts';
18+import { extractReferenceCase, type H5Node } from '../src/compare/referenceCase.ts';
19+import { relL2, relLinf } from '../src/mgpu/digest.ts';
20+import { installWebGpu, errMsg, NO_ADAPTER_HINT } from './nodeWebGpu.ts';
21+import * as h5wasm from 'h5wasm/node';
22+
23+const USAGE = `usage: npm run ref -- --in <file> [options]
24+
25+ --in <file> the reference HDF5 file to check against (required)
26+ --niter <n> override the solve iteration count (default: the file's own)
27+ --tolerance <n> if given, exit 1 when any reported relL2 meets or exceeds it
28+ --tolerance-linf <n> if given, exit 1 when any reported relLinf meets or exceeds it
29+ --json machine-readable output
30+ --help
31+
32+Runs this repo's solver from the file's exact initial spectral state, to the
33+same physical end time, and reports the relative-L2 and relative-L-infinity
34+(max-norm) error of the resulting state against the file's final state (and,
35+as a sanity check, of the regenerated geometry against the file's own
36+geometry coefficients). --tolerance and --tolerance-linf gate independently:
37+either can fail the run on its own.`;
38+
39+function fail(msg: string, code = 1): never {
40+ console.error(`ref: ${msg}`);
41+ process.exit(code);
42+}
43+
44+const argv = process.argv.slice(2);
45+if (argv.includes('--help') || argv.includes('-h')) {
46+ console.log(USAGE);
47+ process.exit(0);
48+}
49+let inFile: string | null = null;
50+let niterOverride: number | null = null;
51+let tolerance: number | null = null;
52+let toleranceLinf: number | null = null;
53+const wantJson = argv.includes('--json');
54+for (let i = 0; i < argv.length; i++) {
55+ const a = argv[i];
56+ if (a === '--json') continue;
57+ const valued = (name: string): string | null => {
58+ if (a === `--${name}`) return argv[++i];
59+ if (a.startsWith(`--${name}=`)) return a.slice(name.length + 3);
60+ return null;
61+ };
62+ const inv = valued('in');
63+ if (inv !== null) {
64+ inFile = inv;
65+ continue;
66+ }
67+ const niterv = valued('niter');
68+ if (niterv !== null) {
69+ niterOverride = Number(niterv);
70+ if (!Number.isInteger(niterOverride) || niterOverride < 0) {
71+ fail(`--niter must be an integer >= 0 (got '${niterv}')`, 2);
72+ }
73+ continue;
74+ }
75+ const tolLinfv = valued('tolerance-linf');
76+ if (tolLinfv !== null) {
77+ toleranceLinf = Number(tolLinfv);
78+ if (!Number.isFinite(toleranceLinf)) fail(`--tolerance-linf must be a number (got '${tolLinfv}')`, 2);
79+ continue;
80+ }
81+ const tolv = valued('tolerance');
82+ if (tolv !== null) {
83+ tolerance = Number(tolv);
84+ if (!Number.isFinite(tolerance)) fail(`--tolerance must be a number (got '${tolv}')`, 2);
85+ continue;
86+ }
87+ fail(`unrecognized argument '${a}'\n\n${USAGE}`, 2);
88+}
89+if (!inFile) fail(`--in <file> is required\n\n${USAGE}`, 2);
90+
91+let device: GPUDevice | null = null;
92+let session: ModelSession | null = null;
93+let h5file: InstanceType<typeof h5wasm.File> | null = null;
94+
95+try {
96+ await h5wasm.ready;
97+ h5file = new h5wasm.File(inFile, 'r');
98+ const rc = extractReferenceCase(h5file as H5Node, inFile);
99+ h5file.close();
100+ h5file = null;
101+
102+ const { model, geometry: geometryModel, params, geometryParams, lmax, steps } = rc;
103+ const niter = niterOverride ?? rc.niter;
104+ const fileGeom = rc.geometryCoeffs;
105+ const fileInitial = rc.initial;
106+ const fileFinal = rc.final;
107+
108+ const runtime = await installWebGpu();
109+ device = await requestShtDevice().catch((e: unknown) => {
110+ throw new Error(`${errMsg(e)}\n${NO_ADAPTER_HINT}`);
111+ });
112+ const adapter = await describeAdapter(device);
113+
114+ session = await ModelSession.create({
115+ device,
116+ model,
117+ params,
118+ lmax,
119+ geometry: geometryModel,
120+ geometryParams,
121+ niter,
122+ });
123+
124+ const errorOf = (a: Float32Array, b: Float32Array) => ({ relL2: relL2(a, b), relLinf: relLinf(a, b) });
125+
126+ const geometryError = {
127+ Gx: errorOf(session.geometry.X, fileGeom.X),
128+ Gy: errorOf(session.geometry.Y, fileGeom.Y),
129+ Gz: errorOf(session.geometry.Z, fileGeom.Z),
130+ };
131+
132+ session.loadState(fileInitial);
133+ session.step(steps);
134+
135+ const stateError: Record<string, { relL2: number; relLinf: number }> = {};
136+ for (const name of model.state) {
137+ // Sequential: GpuModel.read() shares one staging buffer across calls.
138+ const ours = await session.read(name);
139+ stateError[name] = errorOf(ours, fileFinal[name]);
140+ }
141+
142+ const allErrors = [...Object.values(geometryError), ...Object.values(stateError)];
143+ const worstL2 = Math.max(...allErrors.map((e) => e.relL2));
144+ const worstLinf = Math.max(...allErrors.map((e) => e.relLinf));
145+ const passL2 = tolerance === null ? null : worstL2 < tolerance;
146+ const passLinf = toleranceLinf === null ? null : worstLinf < toleranceLinf;
147+ const checks = [passL2, passLinf].filter((p): p is boolean => p !== null);
148+ const pass = checks.length === 0 ? null : checks.every(Boolean);
149+
150+ if (wantJson) {
151+ console.log(
152+ JSON.stringify(
153+ {
154+ in: inFile,
155+ model: model.key,
156+ geometry: geometryModel.key,
157+ grid: { lmax, nlm: session.sht.nlm },
158+ niter,
159+ steps,
160+ dt: params.dt,
161+ T: steps * (params.dt ?? 0),
162+ backend: { adapter, runtime, precision: 'fp32' },
163+ geometryError,
164+ stateError,
165+ worstL2,
166+ worstLinf,
167+ tolerance,
168+ toleranceLinf,
169+ passL2,
170+ passLinf,
171+ pass,
172+ },
173+ null,
174+ 2,
175+ ),
176+ );
177+ } else {
178+ console.log(`ref: ${inFile}`);
179+ console.log(
180+ ` model ${model.label} (${model.state.join(', ')})\n` +
181+ ` geometry ${geometryModel.label} ` +
182+ geometryModel.params.map((p) => `${p.key}=${geometryParams[p.key]}`).join(' ') +
183+ `\n grid lmax ${lmax} · nlm ${session.sht.nlm}\n` +
184+ ` niter ${niter}${niterOverride !== null ? ` (file: ${rc.niter})` : ''}\n` +
185+ ` run ${steps} steps, dt=${params.dt} (T=${(steps * (params.dt ?? 0)).toFixed(2)})\n`,
186+ );
187+ const fmtErr = (v: { relL2: number; relLinf: number }) =>
188+ `relL2 ${v.relL2.toExponential(3)} relLinf ${v.relLinf.toExponential(3)}`;
189+ console.log(` geometry check (regenerated vs file):`);
190+ for (const [k, v] of Object.entries(geometryError)) console.log(` ${k} ${fmtErr(v)}`);
191+ console.log(`\n final state (this run vs file):`);
192+ for (const [k, v] of Object.entries(stateError)) console.log(` ${k} ${fmtErr(v)}`);
193+ if (tolerance !== null) {
194+ console.log(
195+ `\n worst relL2 ${worstL2.toExponential(3)} vs tolerance ${tolerance.toExponential(3)}: ` +
196+ (passL2 ? 'PASS' : 'FAIL'),
197+ );
198+ }
199+ if (toleranceLinf !== null) {
200+ console.log(
201+ ` worst relLinf ${worstLinf.toExponential(3)} vs tolerance-linf ${toleranceLinf.toExponential(3)}: ` +
202+ (passLinf ? 'PASS' : 'FAIL'),
203+ );
204+ }
205+ }
206+
207+ session.destroy();
208+ device.destroy();
209+ process.exit(pass === false ? 1 : 0);
210+} catch (e) {
211+ h5file?.close();
212+ session?.destroy();
213+ device?.destroy();
214+ fail(errMsg(e));
215+}
scripts/test-node.tsmodified+12−0View file
@@ -8,6 +8,9 @@
88 *
99 * npm run test:node
1010 */
11+import { tmpdir } from 'node:os';
12+import { join } from 'node:path';
13+import * as h5wasm from 'h5wasm/node';
1114 import { requestShtDevice } from '../src/sht/sht.ts';
1215 import { installWebGpu, errMsg, NO_ADAPTER_HINT } from './nodeWebGpu.ts';
1316 import { transformChecks } from '../test/transformChecks.ts';
@@ -16,6 +19,8 @@ import { modelChecks } from '../test/modelChecks.ts';
1619 import { geometryChecks } from '../test/geometryChecks.ts';
1720 import { fluxChecks } from '../test/fluxChecks.ts';
1821 import { compareChecks } from '../test/compareChecks.ts';
22+import { referenceChecks, type H5Rt } from '../test/referenceChecks.ts';
23+import { matlabExportChecks } from '../test/matlabExportChecks.ts';
1924
2025 let failures = 0;
2126 const check = (name: string, ok: boolean, detail: string): void => {
@@ -55,6 +60,13 @@ await modelChecks(device, check, log);
5560 await geometryChecks(device, check, log);
5661 await fluxChecks(device, check, log);
5762 await compareChecks(device, check, log);
63+matlabExportChecks(check, log);
64+await referenceChecks(
65+ h5wasm as unknown as H5Rt,
66+ (name) => join(tmpdir(), `turing-surface-${process.pid}-${name}`),
67+ check,
68+ log,
69+);
5870
5971 console.log(failures === 0 ? '\nAll tests passed.' : `\n${failures} failed.`);
6072 process.exit(failures === 0 ? 0 : 1);
src/compare/compareRun.tsmodified+581−59View file
@@ -41,8 +41,10 @@ import {
4141 import { SphereScene } from '../render/SphereScene.ts';
4242 import { colormaps } from '../render/colormaps.ts';
4343 import { fmtValue, floorRange } from '../render/colorbar.ts';
44-import { sharedModes, sharedNoise } from './sharedStart.ts';
44+import { prolongCoeffs, sharedModes, sharedNoise } from './sharedStart.ts';
4545 import { variantLabel, VARIANT_COLORS, type Variant } from './variants.ts';
46+import type { ReferenceCase } from './referenceCase.ts';
47+import { ErrorChart, type ErrorChartRow } from '../render/errorChart.ts';
4648
4749 /**
4850 * Latitudes of the shared display grid. 256 is the same target the single-run
@@ -75,9 +77,35 @@ export interface CompareOptions {
7577 geometry: MGeometry;
7678 geometryParams: Params;
7779 geometrySource: string;
80+ /** Per-row geometry override, parallel-indexed to `variants` — the
81+ * "several rows on several geometries" case (vs-sphere mode), as opposed
82+ * to every other mode's "several rows, one geometry." Rows without an
83+ * entry (or when this is omitted entirely) fall back to the single
84+ * `geometry`/`geometryParams`/`geometrySource` above. */
85+ geometries?: { geometry: MGeometry; geometryParams: Params; geometrySource: string }[];
86+ /** Render every row — value panels and diff panels alike — on the
87+ * *reference* row's own surface (`coords`/`posBuf`) instead of each row's
88+ * own. For comparing two different geometries where only the *field*
89+ * should read as different, not the displayed shape. */
90+ renderOnReferenceGeometry?: boolean;
91+ /** Row names, overriding `variantLabel(variant, showDt)` — for a mode
92+ * where every row shares the same niter/lmax/dt, so that label alone
93+ * wouldn't tell the rows apart. */
94+ rowLabels?: string[];
7895 variants: Variant[];
79- /** Index into `variants` of the run everything else is measured against. */
96+ /** Index into `variants` of the run everything else is measured against.
97+ * Ignored when `refFile` is given — the file is the reference then. */
8098 reference: number;
99+ /**
100+ * Check against a reference file instead of against each other: its exact
101+ * initial state seeds every variant (so `seed` and `lam3` go unused), a
102+ * static extra row shows its final state, every Δ is measured against that
103+ * row, and the clock stops at the file's end time. Every variant's lmax must
104+ * be >= the file's — a narrower band could not hold the initial state.
105+ */
106+ refFile?: ReferenceCase;
107+ /** Called when a refFile run reaches the file's end time and stops. */
108+ onFinished?: () => void;
81109 seed: number;
82110 /** Wavelength of the seeded random field, shared by every variant — one
83111 * initial condition means one wavelength as much as one seed. */
@@ -86,6 +114,8 @@ export interface CompareOptions {
86114 colormapName: () => string;
87115 /** Where the variant grid goes (the app's #panels). */
88116 container: HTMLElement;
117+ /** Where the error-vs-time chart goes (the app's #cmp-chart). */
118+ chartContainer: HTMLElement;
89119 /** Progress and, afterwards, the standing description of the study. */
90120 onStatus: (html: string) => void;
91121 }
@@ -102,6 +132,21 @@ interface Row {
102132 colorBufs: Float32Array[];
103133 /** Fields read this frame, one per species, on the shared grid. */
104134 fields: Float32Array[];
135+ /** Pointwise difference from the reference, one per species, on the shared
136+ * grid — filled by #measureDifference as it accumulates the norm below.
137+ * Unused (and never touched) for the reference row itself. */
138+ diffFields: Float32Array[];
139+ /** The diff row's own panels, one per species — empty for the reference
140+ * row, whose diff against itself is trivially zero. */
141+ diffScenes: SphereScene[];
142+ diffValueBufs: Float32Array[];
143+ diffColorBufs: Float32Array[];
144+ /** This row's own smoothed symmetric color range per species — each row
145+ * is scaled to its own diff extent, not a range shared across the
146+ * column, so one row's diff panels never affect another's coloring. */
147+ diffRanges: { lo: number; hi: number }[];
148+ /** Each diff panel's "± magnitude" caption, parallel to diffScenes. */
149+ diffCaps: HTMLElement[];
105150 /** Relative difference from the reference, one per species. */
106151 err: number[];
107152 /** False once any species has left the floating-point numbers — the shape a
@@ -111,9 +156,37 @@ interface Row {
111156 statEl: HTMLElement;
112157 }
113158
159+/**
160+ * The reference file's final state, as one more row of panels — with no
161+ * session behind it: its surface and fields are the file's coefficients
162+ * synthesized once on the shared display grid, fixed for the whole run. Only
163+ * its coloring changes, with the shared range.
164+ */
165+interface FileRow {
166+ coords: Float32Array;
167+ posBuf: Float32Array;
168+ scenes: SphereScene[];
169+ valueBufs: Float32Array[];
170+ colorBufs: Float32Array[];
171+ /** The file's final state on the shared grid, one per species. */
172+ fields: Float32Array[];
173+ /** Its extent, precomputed — a candidate for the shared color range. */
174+ bounds: (Bounds | null)[];
175+}
176+
114177 export class CompareRun {
115178 #opts: CompareOptions;
116179 #rows: Row[] = [];
180+ #fileRow: FileRow | null = null;
181+ /** What restart() reloads: the file's fixed state if opts.refFile is set,
182+ * otherwise a snapshot of the coarsest variant's state as of the last
183+ * (re-)seed — see the capture in create() and in reseed()'s plain branch. */
184+ #initial: Record<string, Float32Array>;
185+ #initialLmax: number;
186+ /** Base steps taken since the initial state — the refFile clock. */
187+ #stepsDone = 0;
188+ /** True once a refFile run has reached the file's end time. */
189+ #finished = false;
117190 #topo: SphereMeshTopology;
118191 /** Quadrature weight per grid point of the shared grid, for the L2 norm. */
119192 #weights: Float64Array;
@@ -121,6 +194,7 @@ export class CompareRun {
121194 /** Smoothed color range per species, shared by every variant so the panels
122195 * in a column are directly comparable by eye and not just by number. */
123196 #ranges: { lo: number; hi: number }[] = [];
197+ #errorChart: ErrorChart | null = null;
124198 #resizeObs: ResizeObserver | null = null;
125199
126200 #running = false;
@@ -137,14 +211,18 @@ export class CompareRun {
137211 private constructor(init: {
138212 opts: CompareOptions;
139213 rows: Row[];
214+ fileRow: FileRow | null;
140215 topo: SphereMeshTopology;
141216 weights: Float64Array;
142217 rangeBars: { fill: (lo: number, hi: number) => void }[];
143218 frameSteps: number;
144219 note: string;
220+ initial: Record<string, Float32Array>;
221+ initialLmax: number;
145222 }) {
146223 this.#opts = init.opts;
147224 this.#rows = init.rows;
225+ this.#fileRow = init.fileRow;
148226 this.#topo = init.topo;
149227 this.#weights = init.weights;
150228 this.#rangeBars = init.rangeBars;
@@ -152,6 +230,8 @@ export class CompareRun {
152230 this.#note = init.note;
153231 this.#morph = init.opts.morph;
154232 this.#ranges = init.opts.model.species.map(() => ({ lo: NaN, hi: NaN }));
233+ this.#initial = init.initial;
234+ this.#initialLmax = init.initialLmax;
155235 }
156236
157237 get variants(): Variant[] {
@@ -168,6 +248,11 @@ export class CompareRun {
168248 return this.#opts.reference;
169249 }
170250
251+ /** The reference file this study is checking against, if any. */
252+ get refFile(): ReferenceCase | null {
253+ return this.#opts.refFile ?? null;
254+ }
255+
171256 /** The base timestep a variant's dtDiv divides. */
172257 static baseDt(params: Params): number {
173258 return params.dt ?? 0;
@@ -182,10 +267,13 @@ export class CompareRun {
182267 // after the grid is up has to take them down explicitly — removing their
183268 // canvases from the DOM would leave both running.
184269 let built: Row[] = [];
270+ let builtFile: FileRow | null = null;
271+ let errorChart: ErrorChart | null = null;
185272
186273 try {
187274 for (let i = 0; i < variants.length; i++) {
188275 const v = variants[i];
276+ const g = opts.geometries?.[i];
189277 opts.onStatus(
190278 `compiling ${i + 1}/${variants.length} — ${variantLabel(v, showDt)} ` +
191279 `(a solve iteration is ~15 kernels per species, and there is no ` +
@@ -200,9 +288,9 @@ export class CompareRun {
200288 params: { ...opts.params, dt: baseDt / v.dtDiv },
201289 lmax: v.lmax,
202290 source: opts.source,
203- geometry: opts.geometry,
204- geometryParams: opts.geometryParams,
205- geometrySource: opts.geometrySource,
291+ geometry: g?.geometry ?? opts.geometry,
292+ geometryParams: g?.geometryParams ?? opts.geometryParams,
293+ geometrySource: g?.geometrySource ?? opts.geometrySource,
206294 niter: v.niter,
207295 lam3: opts.lam3,
208296 }),
@@ -211,7 +299,7 @@ export class CompareRun {
211299
212300 // ---- the shared display grid ----------------------------------------
213301 const maxLmax = Math.max(...variants.map((v) => v.lmax));
214- const panels = variants.length * model.species.length;
302+ const panels = (variants.length + (opts.refFile ? 1 : 0)) * model.species.length;
215303 const target = panels > CROWDED_PANELS ? RENDER_NLAT_CROWDED : RENDER_NLAT;
216304 // Never below what the finest band needs to be representable at all
217305 // (ShtPlan requires nlat > lmax), whatever the panel count says.
@@ -221,12 +309,56 @@ export class CompareRun {
221309 for (const s of sessions) await s.setDisplayGrid(nlat, nphi);
222310
223311 // ---- one initial condition, on every grid ---------------------------
224- opts.onStatus('seeding all variants from one band-limited perturbation…');
225- const noise = await sharedNoise(sessions, model.seedAmp, opts.seed);
226- const modes = await sharedModes(sessions[opts.reference] ?? sessions[0], opts.seed);
227- // One at a time: a seed submits its whole mode sum in pieces, and there
228- // is nothing to gain from interleaving several variants' worth of it.
229- for (let i = 0; i < sessions.length; i++) await sessions[i].seedWith(noise[i], modes);
312+ // Also what restart() reloads later — the file's fixed state, or (for
313+ // the plain case) a snapshot of the coarsest variant's own state,
314+ // taken after seeding it: the same lowest-lmax session sharedNoise
315+ // itself draws from, so prolonging it up to any other variant later is
316+ // always widening a band, never narrowing one.
317+ let initial: Record<string, Float32Array>;
318+ let initialLmax: number;
319+ if (opts.refFile) {
320+ // The file's exact spectral state, prolonged into each variant's band.
321+ // Exact, not approximate: the state is band-limited at the file's lmax
322+ // and every variant's band contains it, so each session starts from
323+ // the very field the reference run started from.
324+ opts.onStatus('loading the initial state from the reference file…');
325+ for (const s of sessions) {
326+ s.loadState(prolongState(opts.refFile.initial, model.state, opts.refFile.lmax, s.cfg.lmax));
327+ }
328+ initial = opts.refFile.initial;
329+ initialLmax = opts.refFile.lmax;
330+ } else {
331+ opts.onStatus('seeding all variants from one band-limited perturbation…');
332+ const noise = await sharedNoise(sessions, model.seedAmp, opts.seed);
333+ const modes = await sharedModes(sessions[opts.reference] ?? sessions[0], opts.seed);
334+ // One at a time: a seed submits its whole mode sum in pieces, and there
335+ // is nothing to gain from interleaving several variants' worth of it.
336+ for (let i = 0; i < sessions.length; i++) await sessions[i].seedWith(noise[i], modes);
337+ if (opts.geometries) {
338+ // Several geometries, not several lmax bands: the seeding above
339+ // drew a spatially shared field, but evaluated it on each row's
340+ // own (geometry-dependent) points — a different field per row in
341+ // coefficient space. The reference's exact resulting coefficients
342+ // replace that for every other row, so every row starts from the
343+ // identical spectral state and only the operator applied to it
344+ // differs from then on.
345+ const refSession = sessions[opts.reference];
346+ const refState = await refSession.readState();
347+ for (let i = 0; i < sessions.length; i++) {
348+ if (i === opts.reference) continue;
349+ sessions[i].loadState(
350+ prolongState(refState, model.state, refSession.cfg.lmax, sessions[i].cfg.lmax),
351+ );
352+ }
353+ initial = refState;
354+ initialLmax = refSession.cfg.lmax;
355+ } else {
356+ let coarsest = sessions[0];
357+ for (const s of sessions) if (s.cfg.lmax < coarsest.cfg.lmax) coarsest = s;
358+ initial = await coarsest.readState();
359+ initialLmax = coarsest.cfg.lmax;
360+ }
361+ }
230362
231363 // ---- the mesh, shared; the surface, per variant ---------------------
232364 const view = sessions[0].viewSht;
@@ -256,12 +388,25 @@ export class CompareRun {
256388 frameSteps = Math.max(1, frameSteps);
257389
258390 // ---- the grid of panels ---------------------------------------------
259- const { rows, rangeBars } = await buildGrid(opts, sessions, topo, showDt);
391+ const { rows, fileRow, rangeBars } = await buildGrid(opts, sessions, topo, showDt);
260392 built = rows;
393+ builtFile = fileRow;
394+
395+ // ---- the error-vs-time chart, one line per row with a diff panel ----
396+ const chartRows = rows.filter((r) => r.diffScenes.length > 0);
397+ errorChart = new ErrorChart(
398+ opts.chartContainer,
399+ model.species,
400+ chartRows.map((r): ErrorChartRow => ({ label: variantLabel(r.variant, showDt), color: r.color })),
401+ );
402+ // Nothing to chart with a single variant and no reference file — the
403+ // one row present is the reference itself.
404+ opts.chartContainer.hidden = chartRows.length === 0;
261405
262406 const solverGrid = sessions.map((s) => `${s.cfg.nlat}×${s.cfg.nphi}`);
263407 const note =
264- `${variants.length} variants · display grid ${nlat}×${nphi}` +
408+ `${variants.length} variant${variants.length === 1 ? '' : 's'} · ` +
409+ `display grid ${nlat}×${nphi}` +
265410 (sessions.some((s) => s.cfg.nlat > nlat)
266411 ? ` (below the finest solver grid ${solverGrid[solverGrid.length - 1]} — display only)`
267412 : '') +
@@ -269,15 +414,22 @@ export class CompareRun {
269414 ` · ops/step ${ops.join(', ')}`;
270415
271416 const run = new CompareRun({
272- opts, rows, topo, weights, rangeBars, frameSteps, note,
417+ opts, rows, fileRow, topo, weights, rangeBars, frameSteps, note, initial, initialLmax,
273418 });
419+ run.#errorChart = errorChart;
274420 await run.draw();
275421 run.#observeResize();
276422 run.#status();
277423 return run;
278424 } catch (e) {
279- for (const r of built) for (const s of r.scenes) s.dispose();
425+ for (const r of built) {
426+ for (const s of r.scenes) s.dispose();
427+ for (const s of r.diffScenes) s.dispose();
428+ }
429+ for (const s of builtFile?.scenes ?? []) s.dispose();
280430 for (const s of sessions) s.destroy();
431+ errorChart?.dispose();
432+ opts.chartContainer.hidden = true;
281433 opts.container.replaceChildren();
282434 opts.container.classList.remove('compare');
283435 throw e;
@@ -294,27 +446,102 @@ export class CompareRun {
294446 return this.#running;
295447 }
296448
297- /** Re-seed every variant from one new shared perturbation. */
449+ /** Re-seed every variant from one new shared perturbation — or, against a
450+ * reference file, restart from its initial state (there is nothing to
451+ * draw; the seed is ignored). */
298452 async reseed(seed: number): Promise<void> {
299453 const wasRunning = this.#running;
300454 this.#running = false;
301455 while (this.#pumping) await nextFrame();
302456 if (this.#disposed) return;
303457 const sessions = this.#rows.map((r) => r.session);
304- const noise = await sharedNoise(sessions, this.#opts.model.seedAmp, seed);
305- const modes = await sharedModes(this.referenceSession ?? sessions[0], seed);
306- // Checked per variant, not once: a seed awaits its own submission, so a
307- // dispose can land between two of them and destroy the sessions left.
308- for (let i = 0; i < sessions.length; i++) {
458+ const refFile = this.#opts.refFile;
459+ if (refFile) {
460+ for (const s of sessions) {
461+ s.loadState(prolongState(refFile.initial, this.#opts.model.state, refFile.lmax, s.cfg.lmax));
462+ }
463+ } else {
464+ const noise = await sharedNoise(sessions, this.#opts.model.seedAmp, seed);
465+ const modes = await sharedModes(this.referenceSession ?? sessions[0], seed);
466+ // Checked per variant, not once: a seed awaits its own submission, so a
467+ // dispose can land between two of them and destroy the sessions left.
468+ for (let i = 0; i < sessions.length; i++) {
469+ if (this.#disposed) return;
470+ await sessions[i].seedWith(noise[i], modes);
471+ }
309472 if (this.#disposed) return;
310- await sessions[i].seedWith(noise[i], modes);
473+ // This draw becomes what restart() rewinds to from now on — see the
474+ // identical selection in create(). Recaptured here rather than left
475+ // pointing at the pre-reseed field.
476+ if (this.#opts.geometries) {
477+ // Mirrors create()'s IC block: copy the reference's exact resulting
478+ // coefficients into every other row rather than trusting their own
479+ // (geometry-dependent) seeding to have landed on the same state.
480+ const refSession = sessions[this.#opts.reference];
481+ const refState = await refSession.readState();
482+ for (let i = 0; i < sessions.length; i++) {
483+ if (i === this.#opts.reference) continue;
484+ sessions[i].loadState(
485+ prolongState(refState, this.#opts.model.state, refSession.cfg.lmax, sessions[i].cfg.lmax),
486+ );
487+ }
488+ this.#initial = refState;
489+ this.#initialLmax = refSession.cfg.lmax;
490+ } else {
491+ let coarsest = sessions[0];
492+ for (const s of sessions) if (s.cfg.lmax < coarsest.cfg.lmax) coarsest = s;
493+ this.#initial = await coarsest.readState();
494+ this.#initialLmax = coarsest.cfg.lmax;
495+ }
496+ }
497+ this.#t = 0;
498+ this.#stepsDone = 0;
499+ this.#finished = false;
500+ for (const r of this.#ranges) {
501+ r.lo = NaN;
502+ r.hi = NaN;
503+ }
504+ for (const r of this.#rows) {
505+ for (const rr of r.diffRanges) {
506+ rr.lo = NaN;
507+ rr.hi = NaN;
508+ }
509+ }
510+ this.#errorChart?.reset();
511+ await this.draw();
512+ this.#status();
513+ if (!this.#disposed && wasRunning) this.setRunning(true);
514+ }
515+
516+ /** Rewind every variant to the saved initial condition — the file's fixed
517+ * state, or (for the plain case) the last (re-)seed, not necessarily the
518+ * very first one — without drawing anything new. */
519+ async restart(): Promise<void> {
520+ const wasRunning = this.#running;
521+ this.#running = false;
522+ while (this.#pumping) await nextFrame();
523+ if (this.#disposed) return;
524+ for (const r of this.#rows) {
525+ r.session.loadState(
526+ prolongState(this.#initial, this.#opts.model.state, this.#initialLmax, r.session.cfg.lmax),
527+ );
311528 }
312529 this.#t = 0;
530+ this.#stepsDone = 0;
531+ this.#finished = false;
313532 for (const r of this.#ranges) {
314533 r.lo = NaN;
315534 r.hi = NaN;
316535 }
536+ for (const r of this.#rows) {
537+ for (const rr of r.diffRanges) {
538+ rr.lo = NaN;
539+ rr.hi = NaN;
540+ }
541+ }
542+ this.#errorChart?.reset();
317543 await this.draw();
544+ this.#status();
318545 if (!this.#disposed && wasRunning) this.setRunning(true);
319546 }
320547
@@ -333,6 +560,10 @@ export class CompareRun {
333560
334561 /** Model parameters changed. Each variant keeps its own dt. */
335562 setParams(params: Params): void {
563+ // Against a reference file the parameters *are* the file's — they define
564+ // the problem being checked — and the page's parameter panel edits the
565+ // page's own model, which need not even be this one. Nothing to apply.
566+ if (this.#opts.refFile) return;
336567 this.#opts.params = params;
337568 const baseDt = CompareRun.baseDt(params);
338569 for (const r of this.#rows) {
@@ -345,11 +576,21 @@ export class CompareRun {
345576 for (const r of this.#rows) {
346577 fillPositions(r.posBuf, r.coords, this.#topo, morph);
347578 for (const s of r.scenes) s.updatePositions(r.posBuf);
579+ // The diff row sits on the exact same mesh as the value row above it
580+ // (same coords, same posBuf) — it just never got told to re-render
581+ // when this method was first written, so it stayed fixed at whatever
582+ // shape the study was compiled with.
583+ for (const s of r.diffScenes) s.updatePositions(r.posBuf);
584+ }
585+ const f = this.#fileRow;
586+ if (f) {
587+ fillPositions(f.posBuf, f.coords, this.#topo, morph);
588+ for (const s of f.scenes) s.updatePositions(f.posBuf);
348589 }
349590 }
350591
351592 resetView(): void {
352- for (const r of this.#rows) for (const s of r.scenes) s.resetCamera();
593+ for (const s of this.#allScenes()) s.resetCamera();
353594 }
354595
355596 dispose(): void {
@@ -359,13 +600,26 @@ export class CompareRun {
359600 this.#resizeObs = null;
360601 for (const r of this.#rows) {
361602 for (const s of r.scenes) s.dispose();
603+ for (const s of r.diffScenes) s.dispose();
362604 r.session.destroy();
363605 }
606+ for (const s of this.#fileRow?.scenes ?? []) s.dispose();
364607 this.#rows = [];
608+ this.#fileRow = null;
609+ this.#errorChart?.dispose();
610+ this.#errorChart = null;
611+ this.#opts.chartContainer.hidden = true;
365612 this.#opts.container.replaceChildren();
366613 this.#opts.container.classList.remove('compare');
367614 }
368615
616+ #allScenes(): SphereScene[] {
617+ return [
618+ ...this.#rows.flatMap((r) => [...r.scenes, ...r.diffScenes]),
619+ ...(this.#fileRow?.scenes ?? []),
620+ ];
621+ }
622+
369623 // ----------------------------------------------------------------- drawing
370624 /**
371625 * One frame's readback: every variant's every species, on the shared grid.
@@ -429,7 +683,14 @@ export class CompareRun {
429683 });
430684
431685 for (let k = 0; k < species.length; k++) {
432- const anchor = leastPeak(this.#rows.map((r, i) => (r.healthy ? bounds[i][k] : null)));
686+ // The file row, when there is one, is a candidate like any healthy
687+ // variant: early on the variants' small fields set the scale (it merely
688+ // clips), and if every variant diverges it is the row that keeps the
689+ // grid readable.
690+ const anchor = leastPeak([
691+ ...this.#rows.map((r, i) => (r.healthy ? bounds[i][k] : null)),
692+ this.#fileRow?.bounds[k] ?? null,
693+ ]);
433694 const range = this.#ranges[k];
434695 if (anchor) {
435696 if (!Number.isFinite(range.lo)) {
@@ -456,10 +717,63 @@ export class CompareRun {
456717 fillColors(r.colorBufs[k], r.valueBufs[k], shown.lo, shown.hi, cmap);
457718 r.scenes[k]?.updateColors(r.colorBufs[k]);
458719 }
720+ const f = this.#fileRow;
721+ if (f) {
722+ // Its values never change; only its coloring follows the shared range.
723+ fillColors(f.colorBufs[k], f.valueBufs[k], shown.lo, shown.hi, cmap);
724+ f.scenes[k]?.updateColors(f.colorBufs[k]);
725+ }
459726 }
460727
461728 this.#measureDifference();
729+ this.#colorDiffPanels();
462730 this.#updateRowStats();
731+ this.#errorChart?.push(
732+ this.#t,
733+ this.#rows.filter((r) => r.diffScenes.length > 0).map((r) => r.err),
734+ );
735+ }
736+
737+ /**
738+ * Color every diff panel from #measureDifference's pointwise diffFields, on
739+ * a *symmetric* range that is each row's own — not shared across the
740+ * column. A diverging row's diff explodes, but with a per-row range that
741+ * only saturates its own panels; it can no longer affect how any other
742+ * row's diff panels are scaled, which is a simpler fix for exactly the
743+ * flooding problem the value panels' shared #ranges/leastPeak logic exists
744+ * to manage there. The cost: diff-panel color alone no longer tells you
745+ * which row has more error than another — that comparison now lives in the
746+ * error chart, which has actual numbers. Always drawn with a diverging
747+ * colormap regardless of the user's chosen (sequential) one — a signed
748+ * quantity centered at zero needs a diverging map to read correctly, which
749+ * coolwarm is and viridis etc. are not.
750+ */
751+ #colorDiffPanels(): void {
752+ const species = this.#opts.model.species;
753+ for (const r of this.#rows) {
754+ if (r.diffScenes.length === 0) continue;
755+ for (let k = 0; k < species.length; k++) {
756+ const m = r.healthy ? maxAbsFinite(r.diffFields[k]) : null;
757+ const range = r.diffRanges[k];
758+ if (m !== null) {
759+ if (!Number.isFinite(range.lo)) {
760+ range.lo = -m;
761+ range.hi = m;
762+ } else {
763+ const a = 0.15;
764+ range.lo += a * (-m - range.lo);
765+ range.hi += a * (m - range.hi);
766+ }
767+ }
768+ if (!Number.isFinite(range.lo) || !Number.isFinite(range.hi)) continue;
769+ const shown = floorRange(range.lo, range.hi);
770+ fillFieldValues(r.diffValueBufs[k], r.diffFields[k], this.#topo);
771+ fillColors(r.diffColorBufs[k], r.diffValueBufs[k], shown.lo, shown.hi, colormaps.coolwarm);
772+ r.diffScenes[k]?.updateColors(r.diffColorBufs[k]);
773+ const cap = r.diffCaps[k];
774+ if (cap) cap.textContent = `± ${fmtValue(shown.hi)}`;
775+ }
776+ }
463777 }
464778
465779 /**
@@ -470,8 +784,11 @@ export class CompareRun {
470784 * a physical quantity, which is all it is used for.
471785 */
472786 #measureDifference(): void {
473- const ref = this.#rows[this.#opts.reference];
474- if (!ref) return;
787+ // Against a reference file, every row is measured against its final state;
788+ // otherwise against the chosen reference variant, whose own Δ is zero.
789+ const ref = this.#fileRow ? null : this.#rows[this.#opts.reference];
790+ const refFields = this.#fileRow?.fields ?? ref?.fields;
791+ if (!refFields) return;
475792 const species = this.#opts.model.species;
476793 for (const r of this.#rows) {
477794 for (let k = 0; k < species.length; k++) {
@@ -480,16 +797,18 @@ export class CompareRun {
480797 continue;
481798 }
482799 const a = r.fields[k];
483- const b = ref.fields[k];
800+ const b = refFields[k];
484801 if (!a || !b || a.length !== b.length) {
485802 r.err[k] = NaN;
486803 continue;
487804 }
805+ const diff = r.diffFields[k];
488806 let num = 0;
489807 let den = 0;
490808 for (let i = 0; i < a.length; i++) {
491809 const w = this.#weights[i];
492810 const d = a[i] - b[i];
811+ diff[i] = d;
493812 num += w * d * d;
494813 den += w * b[i] * b[i];
495814 }
@@ -506,44 +825,49 @@ export class CompareRun {
506825 * usually the one that has converged and the fast one the one that has not.
507826 */
508827 #updateRowStats(): void {
509- const species = this.#opts.model.species;
510- const ref = this.#rows[this.#opts.reference];
828+ const ref = this.#fileRow ? null : this.#rows[this.#opts.reference];
511829 for (const r of this.#rows) {
512- const per = species
513- .map((s, k) => `${s} ${Number.isFinite(r.err[k]) ? r.err[k].toExponential(2) : '—'}`)
514- .join('<br>');
515830 // Divergence is said, not implied. Scaled to a healthy row, a blown-up
516831 // variant is a flat saturated panel, which on its own is easy to misread
517- // as a converged uniform state.
832+ // as a converged uniform state. Δ itself now lives in the error chart,
833+ // not here.
518834 const body = !r.healthy
519835 ? '<b class="cmp-diverged">diverged</b>'
520836 : r === ref
521837 ? '<b>reference</b>'
522- : `Δ ${per}`;
523- r.statEl.innerHTML = `${r.session.steps.toLocaleString()} steps<br>${body}`;
838+ : '';
839+ r.statEl.innerHTML =
840+ `${r.session.steps.toLocaleString()} steps` + (body ? `<br>${body}` : '');
524841 }
525842 }
526843
527844 #status(): void {
845+ const refFile = this.#opts.refFile;
846+ const clock = refFile
847+ ? `<b>t = ${this.#t.toFixed(2)} / ${(refFile.steps * CompareRun.baseDt(this.#opts.params)).toFixed(2)}</b>` +
848+ ` · NOTE: vertical axis measures difference from uploaded simulation's end state.`
849+ : `<b>t = ${this.#t.toFixed(2)}</b> (same for every variant)`;
528850 this.#opts.onStatus(
529- `<b>t = ${this.#t.toFixed(2)}</b> (same for every variant) · ` +
851+ `${clock} · ` +
530852 (this.#frameMs > 0 ? `${this.#frameMs.toFixed(1)} ms/frame · ` : '') +
531853 this.#note,
532854 );
533855 }
534856
535857 #observeResize(): void {
536- const scenes = this.#rows.flatMap((r) => r.scenes);
858+ const scenes = this.#allScenes();
537859 this.#resizeObs = new ResizeObserver(() => {
538860 for (const s of scenes) {
539861 const box = s.canvas.parentElement;
540862 if (box) s.resize(box.clientWidth, box.clientHeight);
541863 }
864+ this.#errorChart?.redraw();
542865 });
543866 for (const s of scenes) {
544867 const box = s.canvas.parentElement;
545868 if (box) this.#resizeObs.observe(box);
546869 }
870+ this.#resizeObs.observe(this.#opts.chartContainer);
547871 }
548872
549873 // -------------------------------------------------------------- the clock
@@ -560,13 +884,34 @@ export class CompareRun {
560884 this.#pumping = true;
561885 try {
562886 while (this.#running && !this.#disposed) {
887+ // Against a reference file the run is finite: the last frame takes
888+ // however many base steps remain, so every variant lands exactly on
889+ // the file's end time — where Δ against its final state is the
890+ // comparison — and stops there rather than drifting past it.
891+ const refFile = this.#opts.refFile;
892+ const n = refFile
893+ ? Math.min(this.#frameSteps, refFile.steps - this.#stepsDone)
894+ : this.#frameSteps;
895+ if (n <= 0) {
896+ this.#running = false;
897+ this.#opts.onFinished?.();
898+ break;
899+ }
563900 const t0 = performance.now();
564- for (const r of this.#rows) r.session.step(this.#frameSteps * r.variant.dtDiv);
565- this.#t += this.#frameSteps * CompareRun.baseDt(this.#opts.params);
901+ for (const r of this.#rows) r.session.step(n * r.variant.dtDiv);
902+ this.#stepsDone += n;
903+ this.#t += n * CompareRun.baseDt(this.#opts.params);
566904 await this.draw();
567905 if (this.#disposed) break;
568906 const dt = performance.now() - t0;
569907 this.#frameMs = this.#frameMs === 0 ? dt : this.#frameMs + 0.05 * (dt - this.#frameMs);
908+ if (refFile && this.#stepsDone >= refFile.steps) {
909+ this.#finished = true;
910+ this.#running = false;
911+ this.#status();
912+ this.#opts.onFinished?.();
913+ break;
914+ }
570915 this.#status();
571916 await nextFrame();
572917 }
@@ -582,6 +927,19 @@ export class CompareRun {
582927
583928 const nextFrame = (): Promise<number> => new Promise(requestAnimationFrame);
584929
930+/** A whole spectral state re-indexed into a (wider) band's layout — the
931+ * reference file's initial condition, in the form loadState takes. */
932+function prolongState(
933+ coeffs: Record<string, Float32Array>,
934+ names: string[],
935+ lmaxFrom: number,
936+ lmaxTo: number,
937+): Record<string, Float32Array> {
938+ const out: Record<string, Float32Array> = {};
939+ for (const name of names) out[name] = prolongCoeffs(coeffs[name], lmaxFrom, lmaxTo);
940+ return out;
941+}
942+
585943 /** Whether every entry is an ordinary number — false once a variant has left
586944 * its convergence radius and saturated to infinity or NaN. */
587945 function allFinite(f: Float32Array | undefined): boolean {
@@ -605,6 +963,22 @@ function leastPeak(all: (Bounds | null)[]): Bounds | null {
605963 return best;
606964 }
607965
966+/** Max |value| over the finite entries of a field; null if none are finite —
967+ * the diff panels' analogue of finiteRange below, since a symmetric range
968+ * only needs the one number. */
969+function maxAbsFinite(f: Float32Array): number | null {
970+ let m = -Infinity;
971+ let any = false;
972+ for (let i = 0; i < f.length; i++) {
973+ const v = f[i];
974+ if (!Number.isFinite(v)) continue;
975+ any = true;
976+ const a = Math.abs(v);
977+ if (a > m) m = a;
978+ }
979+ return any ? m : null;
980+}
981+
608982 /** Min and max over the finite entries only; null when there are none. */
609983 function finiteRange(f: Float32Array | undefined): { lo: number; hi: number } | null {
610984 if (!f) return null;
@@ -626,12 +1000,52 @@ function finiteRange(f: Float32Array | undefined): { lo: number; hi: number } |
6261000 * the same bar repeated, and would suggest each panel had its own scaling,
6271001 * which is exactly the thing that would make the comparison a lie.
6281002 */
1003+/** The file row's label color — none of the variant palette, since it is not
1004+ * a variant: it is the thing they are all measured against. */
1005+const FILE_ROW_COLOR = '#57606a';
1006+
1007+/**
1008+ * One sphere panel: a boxed SphereScene plus the value/color buffers that
1009+ * feed it. Shared by the value row, the diff row, and the file row — all
1010+ * three build a panel the same way, only differing in the class on the box
1011+ * (for styling) and in what fills the buffers afterward.
1012+ */
1013+function makeSpherePanel(
1014+ colsEl: HTMLElement,
1015+ topo: SphereMeshTopology,
1016+ posBuf: Float32Array,
1017+ background: string | undefined,
1018+ extraClass = '',
1019+): { box: HTMLElement; scene: SphereScene; valueBuf: Float32Array; colorBuf: Float32Array } {
1020+ const box = document.createElement('div');
1021+ box.className = extraClass ? `sphere-box cmp-box ${extraClass}` : 'sphere-box cmp-box';
1022+ colsEl.append(box);
1023+ const scene = new SphereScene(
1024+ box,
1025+ topo.numVertices,
1026+ topo.indices,
1027+ Float32Array.from(posBuf),
1028+ background,
1029+ );
1030+ scene.fitCamera();
1031+ return {
1032+ box,
1033+ scene,
1034+ valueBuf: new Float32Array(topo.numVertices),
1035+ colorBuf: new Float32Array(topo.numVertices * 3),
1036+ };
1037+}
1038+
6291039 async function buildGrid(
6301040 opts: CompareOptions,
6311041 sessions: ModelSession[],
6321042 topo: SphereMeshTopology,
6331043 showDt: boolean,
634-): Promise<{ rows: Row[]; rangeBars: { fill: (lo: number, hi: number) => void }[] }> {
1044+): Promise<{
1045+ rows: Row[];
1046+ fileRow: FileRow | null;
1047+ rangeBars: { fill: (lo: number, hi: number) => void }[];
1048+}> {
6351049 const { container, model } = opts;
6361050 container.replaceChildren();
6371051 container.classList.add('compare');
@@ -680,13 +1094,28 @@ async function buildGrid(
6801094 .getPropertyValue('--sphere-bg')
6811095 .trim();
6821096
1097+ // When every row should be drawn on the same shape (vs-sphere: the point
1098+ // is to isolate the field, not the surface), fetch that shape once from
1099+ // the reference row's session and hand the identical array to every row.
1100+ // fillPositions/fillFieldValues already treat "whose mesh this is" and
1101+ // "whose field this is" as fully independent buffers, so this is the only
1102+ // place that needs to know about it — every method downstream that reads
1103+ // r.coords/r.posBuf just sees one row's shape reused by every other.
1104+ const sharedCoords = opts.renderOnReferenceGeometry
1105+ ? await sessions[opts.reference].renderPositions()
1106+ : null;
1107+
6831108 const rows: Row[] = [];
6841109 for (let i = 0; i < sessions.length; i++) {
6851110 const session = sessions[i];
6861111 const variant = opts.variants[i];
6871112 const color = VARIANT_COLORS[i % VARIANT_COLORS.length];
1113+ // The reference itself never gets a diff row — its diff against itself
1114+ // is trivially zero, and a flat zero panel would just spend a WebGL
1115+ // context for nothing.
1116+ const isRef = !opts.refFile && i === opts.reference;
6881117
689- const coords = await session.renderPositions();
1118+ const coords = sharedCoords ?? (await session.renderPositions());
6901119 const posBuf = new Float32Array(topo.numVertices * 3);
6911120 fillPositions(posBuf, coords, topo, opts.morph);
6921121
@@ -697,7 +1126,7 @@ async function buildGrid(
6971126 labelEl.style.setProperty('--c', color);
6981127 const nameEl = document.createElement('div');
6991128 nameEl.className = 'cmp-rowname';
700- nameEl.textContent = variantLabel(variant, showDt);
1129+ nameEl.textContent = opts.rowLabels?.[i] ?? variantLabel(variant, showDt);
7011130 const statEl = document.createElement('div');
7021131 statEl.className = 'cmp-rowstat';
7031132 labelEl.append(nameEl, statEl);
@@ -710,32 +1139,125 @@ async function buildGrid(
7101139 const valueBufs: Float32Array[] = [];
7111140 const colorBufs: Float32Array[] = [];
7121141 for (let k = 0; k < model.species.length; k++) {
713- const box = document.createElement('div');
714- box.className = 'sphere-box cmp-box';
715- colsEl.append(box);
716- const scene = new SphereScene(
717- box,
718- topo.numVertices,
719- topo.indices,
720- Float32Array.from(posBuf),
721- sphereBg || undefined,
722- );
723- scene.fitCamera();
1142+ const { scene, valueBuf, colorBuf } = makeSpherePanel(colsEl, topo, posBuf, sphereBg || undefined);
7241143 scenes.push(scene);
725- valueBufs.push(new Float32Array(topo.numVertices));
726- colorBufs.push(new Float32Array(topo.numVertices * 3));
1144+ valueBufs.push(valueBuf);
1145+ colorBufs.push(colorBuf);
7271146 }
7281147
1148+ // ---- its diff row, right underneath ----------------------------------
1149+ const diffFields = model.species.map(() => new Float32Array(topo.nlat * topo.nphi));
1150+ const diffScenes: SphereScene[] = [];
1151+ const diffValueBufs: Float32Array[] = [];
1152+ const diffColorBufs: Float32Array[] = [];
1153+ const diffCaps: HTMLElement[] = [];
1154+ if (!isRef) {
1155+ const diffRowEl = document.createElement('div');
1156+ diffRowEl.className = 'cmp-row cmp-diffrow';
1157+ const diffLabelEl = document.createElement('div');
1158+ diffLabelEl.className = 'cmp-rowlabel';
1159+ diffLabelEl.style.setProperty('--c', color);
1160+ const diffNameEl = document.createElement('div');
1161+ diffNameEl.className = 'cmp-rowname';
1162+ diffNameEl.textContent = 'Δ vs reference';
1163+ diffLabelEl.append(diffNameEl);
1164+ const diffColsEl = document.createElement('div');
1165+ diffColsEl.className = 'cmp-cols';
1166+ diffRowEl.append(diffLabelEl, diffColsEl);
1167+ container.append(diffRowEl);
1168+
1169+ for (let k = 0; k < model.species.length; k++) {
1170+ const { box, scene, valueBuf, colorBuf } = makeSpherePanel(
1171+ diffColsEl, topo, posBuf, sphereBg || undefined, 'cmp-diffbox',
1172+ );
1173+ diffScenes.push(scene);
1174+ diffValueBufs.push(valueBuf);
1175+ diffColorBufs.push(colorBuf);
1176+ const cap = document.createElement('span');
1177+ cap.className = 'cmp-diffcap';
1178+ box.append(cap);
1179+ diffCaps.push(cap);
1180+ }
1181+ }
1182+
1183+ const diffRanges = model.species.map(() => ({ lo: NaN, hi: NaN }));
7291184 rows.push({
7301185 variant, session, color, coords, posBuf, scenes, valueBufs, colorBufs,
731- fields: [], err: model.species.map(() => 0), healthy: true, statEl,
1186+ fields: [], diffFields, diffScenes, diffValueBufs, diffColorBufs, diffCaps, diffRanges,
1187+ err: model.species.map(() => 0), healthy: true, statEl,
7321188 });
7331189 }
7341190
1191+ // ---- the reference file's final state, as one more (static) row ---------
1192+ let fileRow: FileRow | null = null;
1193+ if (opts.refFile) {
1194+ const rf = opts.refFile;
1195+ // Synthesized through the coarsest session's display plan — exact, like
1196+ // every other use of the shared grid: the file's coefficients are
1197+ // band-limited at its lmax, which every variant's band contains.
1198+ const view = sessions[0].viewSht;
1199+ const lmaxTo = sessions[0].cfg.lmax;
1200+ const on = (q: Float32Array): Promise<Float32Array> =>
1201+ view.synth(prolongCoeffs(q, rf.lmax, lmaxTo));
1202+ const [gx, gy, gz] = [
1203+ await on(rf.geometryCoeffs.X),
1204+ await on(rf.geometryCoeffs.Y),
1205+ await on(rf.geometryCoeffs.Z),
1206+ ];
1207+ // The file's own surface, not a regeneration of it — interleaved xyz, the
1208+ // same layout renderPositions() hands back.
1209+ const coords = new Float32Array(3 * gx.length);
1210+ for (let i = 0; i < gx.length; i++) {
1211+ coords[3 * i] = gx[i];
1212+ coords[3 * i + 1] = gy[i];
1213+ coords[3 * i + 2] = gz[i];
1214+ }
1215+ const posBuf = new Float32Array(topo.numVertices * 3);
1216+ fillPositions(posBuf, coords, topo, opts.morph);
1217+
1218+ const rowEl = document.createElement('div');
1219+ rowEl.className = 'cmp-row';
1220+ const labelEl = document.createElement('div');
1221+ labelEl.className = 'cmp-rowlabel';
1222+ labelEl.style.setProperty('--c', FILE_ROW_COLOR);
1223+ const nameEl = document.createElement('div');
1224+ nameEl.className = 'cmp-rowname';
1225+ nameEl.textContent = 'reference file';
1226+ nameEl.title = rf.label;
1227+ const statEl = document.createElement('div');
1228+ statEl.className = 'cmp-rowstat';
1229+ statEl.innerHTML = `${rf.steps.toLocaleString()} steps<br><b>final state</b>`;
1230+ labelEl.append(nameEl, statEl);
1231+ const colsEl = document.createElement('div');
1232+ colsEl.className = 'cmp-cols';
1233+ rowEl.append(labelEl, colsEl);
1234+ container.append(rowEl);
1235+
1236+ const scenes: SphereScene[] = [];
1237+ const valueBufs: Float32Array[] = [];
1238+ const colorBufs: Float32Array[] = [];
1239+ const fields: Float32Array[] = [];
1240+ const bounds: (Bounds | null)[] = [];
1241+ for (let k = 0; k < model.species.length; k++) {
1242+ const { scene, valueBuf, colorBuf } = makeSpherePanel(colsEl, topo, posBuf, sphereBg || undefined);
1243+ scenes.push(scene);
1244+ const field = await on(rf.final[model.state[k]]);
1245+ fields.push(field);
1246+ bounds.push(finiteRange(field));
1247+ fillFieldValues(valueBuf, field, topo);
1248+ valueBufs.push(valueBuf);
1249+ colorBufs.push(colorBuf);
1250+ }
1251+ fileRow = { coords, posBuf, scenes, valueBufs, colorBufs, fields, bounds };
1252+ }
1253+
7351254 // Every panel shares one camera: the study is about the fields, and looking
7361255 // at two of them from different angles is not comparing them.
737- const all = rows.flatMap((r) => r.scenes);
1256+ const all = [
1257+ ...rows.flatMap((r) => [...r.scenes, ...r.diffScenes]),
1258+ ...(fileRow?.scenes ?? []),
1259+ ];
7381260 for (let i = 1; i < all.length; i++) all[0].syncCamerasWith(all[i]);
7391261
740- return { rows, rangeBars };
1262+ return { rows, fileRow, rangeBars };
7411263 }
src/compare/referenceCase.tsadded+124−0View file
@@ -0,0 +1,124 @@
1+/**
2+ * Reading a reference HDF5 file into the pieces a replay needs.
3+ *
4+ * A reference file is a saved run from an independently-implemented solver —
5+ * geometry, initial and final spherical-harmonic coefficients, and the run's
6+ * parameters — in the layout documented in docs/ellipsoid-reference-spec.md.
7+ * Two things read it: the `npm run ref` CLI (through `h5wasm/node`) and the
8+ * browser's compare mode (through `h5wasm`, lazily loaded — see
9+ * referenceFile.ts). Both hand this module the same object shape, so the
10+ * format knowledge lives once.
11+ */
12+import { mModelByKey, defaultParams, type MModel, type Params } from '../mgpu/registry.ts';
13+import { mGeometryByKey, defaultGeometryParams, type MGeometry } from '../geom/registry.ts';
14+import { nlmCalc } from '../sht/layout.ts';
15+
16+/** The slice of h5wasm's File/Group/Dataset API this reader touches — enough
17+ * that the node and browser builds both satisfy it structurally. */
18+export interface H5Node {
19+ attrs: Record<string, { value: unknown }>;
20+ get(name: string): unknown;
21+}
22+
23+export interface ReferenceCase {
24+ /** Where it came from — the file name, for labels and messages. */
25+ label: string;
26+ model: MModel;
27+ geometry: MGeometry;
28+ /** The model's defaults overlaid with the file's own — `dt` included, so
29+ * `steps * params.dt` is the file's end time. */
30+ params: Params;
31+ geometryParams: Params;
32+ lmax: number;
33+ /** The solve-iteration count recorded in the file — the replay's default. */
34+ niter: number;
35+ /** Steps at `params.dt` from the initial state to the final one. */
36+ steps: number;
37+ /** The band-limited surface's own coefficients, [re, im] per (l, m). The
38+ * reference solver ran on this exact surface, not the analytic shape. */
39+ geometryCoeffs: { X: Float32Array; Y: Float32Array; Z: Float32Array };
40+ /** Spectral state per species (keyed by `model.state` name) at t = 0. */
41+ initial: Record<string, Float32Array>;
42+ /** The same, at the end time. */
43+ final: Record<string, Float32Array>;
44+}
45+
46+const attrsOf = (node: H5Node): Record<string, unknown> =>
47+ Object.fromEntries(Object.entries(node.attrs).map(([k, v]) => [k, v.value]));
48+
49+/** Attributes as numbers — h5wasm hands back number or BigInt by dtype. */
50+const numberAttrs = (node: H5Node): Params =>
51+ Object.fromEntries(Object.entries(attrsOf(node)).map(([k, v]) => [k, Number(v)]));
52+
53+function groupOf(node: H5Node, name: string): H5Node {
54+ const g = node.get(name) as H5Node | null;
55+ if (!g || typeof g.get !== 'function') {
56+ throw new Error(`no '${name}/' group — is this a reference file?`);
57+ }
58+ return g;
59+}
60+
61+function coeffsOf(group: H5Node, groupName: string, name: string, nlm: number): Float32Array {
62+ const v = (group.get(name) as { value?: unknown } | null)?.value;
63+ if (!(v instanceof Float32Array)) {
64+ throw new Error(`'${groupName}/${name}' is not a float32 dataset`);
65+ }
66+ if (v.length !== 2 * nlm) {
67+ throw new Error(`'${groupName}/${name}' has ${v.length} values, expected 2*nlm = ${2 * nlm}`);
68+ }
69+ return v;
70+}
71+
72+/** Read an open reference file. Throws with a plain message on anything the
73+ * replay could not act on — unknown model or geometry, missing or misshapen
74+ * coefficients — so both the CLI and the page can just show it. */
75+export function extractReferenceCase(file: H5Node, label: string): ReferenceCase {
76+ const modelKey = String(attrsOf(file).model);
77+ const model = mModelByKey(modelKey);
78+ if (!model) throw new Error(`unknown model '${modelKey}'`);
79+
80+ const spec = groupOf(file, 'spec');
81+ const specAttrs = attrsOf(spec);
82+ const geometryKey = String(specAttrs.geometry);
83+ const geometry = mGeometryByKey(geometryKey);
84+ if (!geometry) throw new Error(`unknown geometry '${geometryKey}'`);
85+
86+ const lmax = Number(specAttrs.lmax);
87+ const steps = Number(specAttrs.steps);
88+ const niter = Number(specAttrs.niter);
89+ if (!Number.isInteger(lmax) || lmax < 1) throw new Error(`bad lmax '${String(specAttrs.lmax)}'`);
90+ if (!Number.isInteger(steps) || steps < 1) throw new Error(`bad steps '${String(specAttrs.steps)}'`);
91+ if (!Number.isInteger(niter) || niter < 0) throw new Error(`bad niter '${String(specAttrs.niter)}'`);
92+ const nlm = nlmCalc(lmax, lmax);
93+
94+ const params: Params = {
95+ ...defaultParams(model),
96+ ...numberAttrs(groupOf(spec, 'params')),
97+ };
98+ if (!(params.dt! > 0)) throw new Error(`bad dt '${params.dt}'`);
99+ const geometryParams: Params = {
100+ ...defaultGeometryParams(geometry),
101+ ...numberAttrs(groupOf(spec, 'geometry_params')),
102+ };
103+
104+ const geom = groupOf(file, 'geometry');
105+ const geometryCoeffs = {
106+ X: coeffsOf(geom, 'geometry', 'Gx', nlm),
107+ Y: coeffsOf(geom, 'geometry', 'Gy', nlm),
108+ Z: coeffsOf(geom, 'geometry', 'Gz', nlm),
109+ };
110+
111+ const initialGroup = groupOf(file, 'initial');
112+ const finalGroup = groupOf(file, 'final');
113+ const initial: Record<string, Float32Array> = {};
114+ const final: Record<string, Float32Array> = {};
115+ for (const name of model.state) {
116+ initial[name] = coeffsOf(initialGroup, 'initial', name, nlm);
117+ final[name] = coeffsOf(finalGroup, 'final', name, nlm);
118+ }
119+
120+ return {
121+ label, model, geometry, params, geometryParams,
122+ lmax, niter, steps, geometryCoeffs, initial, final,
123+ };
124+}
src/compare/referenceFile.tsadded+29−0View file
@@ -0,0 +1,29 @@
1+/**
2+ * Reading a reference .h5 in the page.
3+ *
4+ * h5wasm's browser build carries the whole HDF5 library as embedded wasm —
5+ * about 4 MB — so it is imported here, dynamically, and nowhere else: the page
6+ * pays for it on the first file actually loaded, never on startup. The bytes
7+ * are written into the wasm module's in-memory filesystem under a fixed
8+ * scratch name (loads are sequential — there is one file input), opened,
9+ * extracted, and unlinked.
10+ */
11+import { extractReferenceCase, type H5Node, type ReferenceCase } from './referenceCase.ts';
12+
13+const SCRATCH = '/loaded-reference.h5';
14+
15+export async function loadReferenceFile(file: File): Promise<ReferenceCase> {
16+ const bytes = new Uint8Array(await file.arrayBuffer());
17+ const h5 = await import('h5wasm');
18+ const { FS } = (await h5.ready) as unknown as {
19+ FS: { writeFile(path: string, data: Uint8Array): void; unlink(path: string): void };
20+ };
21+ FS.writeFile(SCRATCH, bytes);
22+ const opened = new h5.File(SCRATCH, 'r');
23+ try {
24+ return extractReferenceCase(opened as unknown as H5Node, file.name);
25+ } finally {
26+ opened.close();
27+ FS.unlink(SCRATCH);
28+ }
29+}
src/export/matlabScript.tsadded+313−0View file
@@ -0,0 +1,313 @@
1+/**
2+ * The run on screen, as one standalone MATLAB script.
3+ *
4+ * The models and geometries are already MATLAB; what the app supplies around
5+ * them — the transforms, the geometry weights, the seeded field, the driver —
6+ * exists only as TypeScript and WGSL. This module assembles a single function
7+ * file carrying all of it: the current model and geometry sources verbatim as
8+ * local functions, double-precision MATLAB ports of the host-provided
9+ * operations (support.m), and a generated driver with the run's settings
10+ * baked in.
11+ *
12+ * Fidelity is method-for-method, not bit-for-bit: the ports run in f64 where
13+ * the GPU path is f32, and random draws use MATLAB's own rng, so a seed value
14+ * selects a different member of the same random ensemble than the same value
15+ * in the app. The script's results file uses the app's reference-run layout
16+ * (docs/ellipsoid-reference-spec.md), so a MATLAB run can be loaded back into
17+ * the page or checked with `npm run ref`.
18+ */
19+import supportSource from './support.m?raw';
20+import randnfun3Source from '../../tools/randnfun3.m?raw';
21+import randnfunsphereSource from '../../tools/randnfunsphere.m?raw';
22+import type { MModel, Params } from '../mgpu/registry.ts';
23+import type { MGeometry } from '../geom/registry.ts';
24+
25+/** The generated function's name — and therefore the file name to save as. */
26+export const MATLAB_SCRIPT_NAME = 'turing_surface_run';
27+
28+export interface MatlabExportSpec {
29+ model: MModel;
30+ /** Model source as running — the editor's working copy when edited. */
31+ modelSource: string;
32+ params: Params;
33+ geometry: MGeometry;
34+ geometrySource: string;
35+ geometryParams: Params;
36+ lmax: number;
37+ niter: number;
38+ /** Wavelength of the seeded random field. */
39+ lam3: number;
40+ seed: number;
41+ /** Preset key, recorded in the results file's /spec. */
42+ preset: string;
43+ /** The equivalent `npm run bench` command, recorded for provenance. */
44+ command: string;
45+ /** The generated script's own run controls; app defaults when omitted. */
46+ controls?: { nsteps?: number; plotEvery?: number; outFile?: string };
47+}
48+
49+interface Signature {
50+ outputs: string[];
51+ params: string[];
52+}
53+
54+/** First `function [outs] = name(args)` line in a .m — the same contract the
55+ * compiler applies, minus everything it checks later. */
56+function parseSignature(source: string, name: string, file: string): Signature {
57+ const re = new RegExp(
58+ String.raw`^[ \t]*function\s+(?:\[([^\]]*)\]|([A-Za-z]\w*))\s*=\s*${name}\s*\(([^)]*)\)`,
59+ 'm',
60+ );
61+ const m = re.exec(source);
62+ if (!m) {
63+ throw new Error(`cannot export: ${file} defines no function named '${name}'`);
64+ }
65+ const split = (s: string): string[] =>
66+ s.split(',').map((t) => t.trim()).filter((t) => t.length > 0);
67+ return {
68+ outputs: m[1] !== undefined ? split(m[1]) : [m[2]],
69+ params: split(m[3]),
70+ };
71+}
72+
73+/** A number as MATLAB source. JS stringification round-trips doubles exactly
74+ * and every form it produces (0.0004, 1e-21, -3) is a MATLAB literal. */
75+const num = (v: number): string => (Number.isFinite(v) ? String(v) : '0');
76+
77+/** A string as a MATLAB char literal. */
78+const str = (s: string): string => `'${s.replace(/'/g, "''")}'`;
79+
80+const banner = (title: string): string => {
81+ const line = `% ${'='.repeat(72)}`;
82+ return `${line}\n% ${title}\n${line}`;
83+};
84+
85+export function generateMatlabScript(spec: MatlabExportSpec): string {
86+ const { model, geometry } = spec;
87+ const controls = {
88+ nsteps: spec.controls?.nsteps ?? 2000,
89+ plotEvery: spec.controls?.plotEvery ?? 10,
90+ outFile: spec.controls?.outFile ?? `${MATLAB_SCRIPT_NAME}.h5`,
91+ };
92+
93+ const init = parseSignature(spec.modelSource, 'init', `models/${model.key}.m`);
94+ const step = parseSignature(spec.modelSource, 'step', `models/${model.key}.m`);
95+ const shape = parseSignature(spec.geometrySource, 'shape', `geometries/${geometry.key}.m`);
96+
97+ // The driver defines every host-provided name the .m may ask for (lam,
98+ // filt, the geometry fields, jhat, niter, ...) under its canonical name,
99+ // so a model call is its own signature read back. Only the tunable
100+ // parameters live elsewhere — in the mp/gp structs, where the person
101+ // running the script edits them — so those names are mapped.
102+ const modelParamKeys = new Set(model.params.map((p) => p.key));
103+ const modelArg = (a: string): string => (modelParamKeys.has(a) ? `mp.${a}` : a);
104+ const shapeArg = (a: string): string =>
105+ a === 'theta' || a === 'phi' ? a : `gp.${a}`;
106+
107+ const stateOuts = [...model.state, ...model.species];
108+ const outs = `[${stateOuts.join(', ')}]`;
109+ const initCall = `${outs} = init(${init.params.map(modelArg).join(', ')});`;
110+ const stepCall = `${outs} = step(${step.params.map(modelArg).join(', ')});`;
111+ const shapeCall = `[gxr, gyr, gzr] = shape(${shape.params.map(shapeArg).join(', ')});`;
112+
113+ const speciesCell = `{${model.species.join(', ')}}`;
114+ const namesCell = `{${model.species.map((s) => str(s)).join(', ')}}`;
115+
116+ // `noise` is the plain seeded grid perturbation, for a .m that takes it
117+ // instead of calling randnfun3 (none of the shipped models do).
118+ const takesNoise = init.params.includes('noise') || step.params.includes('noise');
119+
120+ const mpBlock = model.params
121+ .map((p) => `mp.${p.key} = ${num(spec.params[p.key] ?? p.value)};`)
122+ .join('\n');
123+ const gpBlock = geometry.params
124+ .map((p) => `gp.${p.key} = ${num(spec.geometryParams[p.key] ?? p.value)};`)
125+ .join('\n');
126+
127+ const driver = `function ${MATLAB_SCRIPT_NAME}()
128+% ${model.label} on ${geometry.label} -- a run captured from the
129+% turing-surface app as one standalone MATLAB script.
130+%
131+% The model and geometry .m below are the app's own, verbatim; around them
132+% this file carries double-precision MATLAB ports of everything the app
133+% provides from the host side: the spherical-harmonic transforms and their
134+% derivative shuffles, the metric weights of the surface Laplace-Beltrami
135+% operator, the seeded random field, and the run loop (src/sht and src/geom
136+% in the repository). The scheme is the app's: IMEX Euler, implicit
137+% diffusion preconditioned on the round sphere, the geometric correction
138+% iterated niter times per step.
139+%
140+% Two deliberate differences from the page. Everything here runs in double
141+% precision, where the app's GPU path is single. And random draws use
142+% MATLAB's own rng, so a seed value selects a different member of the same
143+% random ensemble than the same value in the app.
144+%
145+% Save as ${MATLAB_SCRIPT_NAME}.m and run it. The run plots live, and the
146+% final state is written to an HDF5 file in the app's reference-run layout
147+% (docs/ellipsoid-reference-spec.md in the repository), so it can be loaded
148+% back into the page ("Compare against uploaded data") or checked on the
149+% desktop with \`npm run ref -- --in ${controls.outFile}\`.
150+% Needs base MATLAB, R2020b or newer; no toolboxes.
151+
152+% ---- run controls --------------------------------------------------------
153+nsteps = ${controls.nsteps}; % timesteps to run
154+plot_every = ${controls.plotEvery}; % live-plot interval, in steps; 0 disables plotting
155+out_file = ${str(controls.outFile)}; % results file; '' disables
156+seed = ${num(spec.seed)}; % rng seed for the initial condition
157+
158+% ---- captured from the app -----------------------------------------------
159+lmax = ${spec.lmax}; % spherical-harmonic truncation degree
160+niter = ${spec.niter}; % iterations of the implicit solve's geometric correction
161+lam3 = ${num(spec.lam3)}; % wavelength of the seeded random field
162+${model.params.length ? `% ${model.label} parameters\n${mpBlock}` : `% ${model.label} has no parameters`}
163+${geometry.params.length ? `% ${geometry.label} parameters\n${gpBlock}` : `% ${geometry.label} has no parameters`}
164+
165+% ---- grid and transforms -------------------------------------------------
166+% nlat/nphi follow lmax by the app's dealiasing rule (src/sht/layout.ts) for
167+% a reaction of polynomial degree pdeg.
168+pdeg = ${model.pdeg};
169+mmax = lmax;
170+nlat = 2 * ceil(max(lmax + 1, ((pdeg + 1) * lmax + 1) / 2) / 2);
171+nphi = 2 ^ nextpow2((pdeg + 1) * lmax + 1);
172+npts = nlat * nphi;
173+sht_tables(sht_setup(lmax, mmax, nlat, nphi));
174+S = sht_tables();
175+nlm = S.nlm;
176+lam = S.lam;
177+filt = S.filt;
178+theta = S.theta;
179+phi = S.phi;
180+
181+% ---- the surface ---------------------------------------------------------
182+${shapeCall}
183+% A constant coordinate comes back scalar; spread it over the grid.
184+gxr = gxr + zeros(npts, 1);
185+gyr = gyr + zeros(npts, 1);
186+gzr = gzr + zeros(npts, 1);
187+G = surface_tables(gxr, gyr, gzr);
188+gx = G.gx; gy = G.gy; gz = G.gz;
189+Gx = G.Gx; Gy = G.Gy; Gz = G.Gz;
190+p1 = G.p1; p2 = G.p2; q2 = G.q2; r = G.r;
191+dp1 = G.dp1; dq2 = G.dq2; jinv = G.jinv;
192+Vtx = G.Vtx; Vty = G.Vty; Vtz = G.Vtz;
193+Vpx = G.Vpx; Vpy = G.Vpy; Vpz = G.Vpz;
194+jhat = G.Jhat;
195+radius = sqrt(gx.^2 + gy.^2 + gz.^2);
196+fprintf('grid %d x %d, nlm %d, radius %.3f-%.3f, Jhat %.3f\\n', ...
197+ nlat, nphi, nlm, min(radius), max(radius), jhat);
198+
199+% ---- initial condition ---------------------------------------------------
200+rng(seed);
201+${takesNoise ? `noise = ${num(model.seedAmp)} * randn(npts, 1);\n` : ''}${initCall}
202+${model.state.map((s) => `${s}0 = ${s};`).join('\n')}
203+
204+% ---- time loop -----------------------------------------------------------
205+if plot_every > 0
206+ ph = plot_setup(gx, gy, gz, ${speciesCell}, ${namesCell});
207+ plot_update(ph, ${speciesCell}, 0, 0, nsteps);
208+end
209+report_every = max(1, round(nsteps / 10));
210+t = 0;
211+tstart = tic;
212+for k = 1:nsteps
213+ ${stepCall}
214+ t = t + mp.dt;
215+ if plot_every > 0 && (mod(k, plot_every) == 0 || k == nsteps)
216+ plot_update(ph, ${speciesCell}, t, k, nsteps);
217+ end
218+ if mod(k, report_every) == 0 || k == nsteps
219+ fprintf('step %d/%d t = %.3f (%.1f s)\\n', k, nsteps, t, toc(tstart));
220+ end
221+end
222+
223+% ---- results file --------------------------------------------------------
224+% The app's reference-run layout, plus a /fields group with the final grid
225+% fields, the surface and the grid angles (each field stored nphi x nlat,
226+% ring by ring from the north pole).
227+if ~isempty(out_file)
228+ if exist(out_file, 'file') == 2
229+ delete(out_file);
230+ end
231+${['Gx', 'Gy', 'Gz']
232+ .map((c) => ` write_coeffs(out_file, '/geometry/${c}', ${c});`)
233+ .join('\n')}
234+${model.state
235+ .map((s) => ` write_coeffs(out_file, '/initial/${s}', ${s}0);`)
236+ .join('\n')}
237+${model.state
238+ .map((s) => ` write_coeffs(out_file, '/final/${s}', ${s});`)
239+ .join('\n')}
240+${[...model.species.map((s) => [s, s] as const), (['x', 'gx'] as const), (['y', 'gy'] as const), (['z', 'gz'] as const)]
241+ .map(
242+ ([name, v]) =>
243+ ` h5create(out_file, '/fields/${name}', [nphi nlat]);\n` +
244+ ` h5write(out_file, '/fields/${name}', reshape(${v}, nphi, nlat));`,
245+ )
246+ .join('\n')}
247+ h5create(out_file, '/fields/theta', nlat);
248+ h5write(out_file, '/fields/theta', acos(min(1, max(-1, S.ct))));
249+ h5create(out_file, '/fields/phi', nphi);
250+ h5write(out_file, '/fields/phi', 2*pi*(0:nphi-1)'/nphi);
251+ make_group(out_file, '/backend');
252+ make_group(out_file, '/spec');
253+ make_group(out_file, '/spec/params');
254+ make_group(out_file, '/spec/geometry_params');
255+ make_group(out_file, '/grid');
256+ h5writeatt(out_file, '/', 'model', ${str(model.key)});
257+ h5writeatt(out_file, '/', 'species', [${model.state.map((s) => `"${s}"`).join(' ')}]);
258+ h5writeatt(out_file, '/', 'command', ${str(spec.command)});
259+ h5writeatt(out_file, '/backend', 'runtime', 'matlab');
260+ h5writeatt(out_file, '/backend', 'adapter', ['MATLAB ' version]);
261+ h5writeatt(out_file, '/backend', 'precision', 'double');
262+ h5writeatt(out_file, '/spec', 'preset', ${str(spec.preset)});
263+ h5writeatt(out_file, '/spec', 'geometry', ${str(geometry.key)});
264+ h5writeatt(out_file, '/spec', 'lmax', lmax);
265+ h5writeatt(out_file, '/spec', 'seed', seed);
266+ h5writeatt(out_file, '/spec', 'steps', nsteps);
267+ h5writeatt(out_file, '/spec', 'warmup', 0);
268+ h5writeatt(out_file, '/spec', 'niter', niter);
269+ h5writeatt(out_file, '/spec', 'lam3', lam3);
270+${model.params
271+ .map((p) => ` h5writeatt(out_file, '/spec/params', ${str(p.key)}, mp.${p.key});`)
272+ .join('\n')}
273+${geometry.params
274+ .map((p) => ` h5writeatt(out_file, '/spec/geometry_params', ${str(p.key)}, gp.${p.key});`)
275+ .join('\n')}
276+ h5writeatt(out_file, '/grid', 'lmax', lmax);
277+ h5writeatt(out_file, '/grid', 'mmax', mmax);
278+ h5writeatt(out_file, '/grid', 'nlat', nlat);
279+ h5writeatt(out_file, '/grid', 'nphi', nphi);
280+ h5writeatt(out_file, '/grid', 'nlm', nlm);
281+ fprintf('wrote %s\\n', out_file);
282+end
283+end`;
284+
285+ // tools/randnfun3.m verbatim, renamed: the models call the app's builtin
286+ // `randnfun3(lam3, gx, gy, gz)`, which support.m provides as a dispatcher
287+ // over this mode draw.
288+ const modesSource = randnfun3Source.replace(
289+ /function\s*\[\s*k\s*,\s*c\s*\]\s*=\s*randnfun3\s*\(/,
290+ 'function [k, c] = randnfun3_modes(',
291+ );
292+ if (modesSource === randnfun3Source) {
293+ throw new Error('cannot export: tools/randnfun3.m no longer matches the expected signature');
294+ }
295+
296+ const usesSphere = /\brandnfunsphere\b/.test(spec.geometrySource + spec.modelSource);
297+
298+ const parts = [
299+ driver,
300+ banner(`models/${model.key}.m -- the model, verbatim`),
301+ spec.modelSource.trim(),
302+ banner(`geometries/${geometry.key}.m -- the surface, verbatim`),
303+ spec.geometrySource.trim(),
304+ banner('tools/randnfun3.m -- the random-field mode draw, verbatim'),
305+ modesSource.trim(),
306+ ...(usesSphere
307+ ? [banner('tools/randnfunsphere.m -- verbatim'), randnfunsphereSource.trim()]
308+ : []),
309+ banner('host-provided operations, ported from src/sht and src/geom'),
310+ supportSource.trim(),
311+ ];
312+ return parts.join('\n\n') + '\n';
313+}
src/export/support.madded+388−0View file
@@ -0,0 +1,388 @@
1+% ---------------------------------------------------------------- transforms
2+%
3+% Double-precision MATLAB ports of the operations the app provides to a .m
4+% around its compiled GPU pipeline. Conventions follow src/sht/layout.ts:
5+% orthonormal spherical harmonics with the Condon-Shortley phase, coefficients
6+% stored for m >= 0 only in m-major order (m = 0..mmax, l = m..lmax within
7+% each m) -- here as complex nlm x 1 column vectors where the GPU carries
8+% interleaved [re, im] pairs. Grid fields are npts x 1 columns, phi-fastest:
9+% point (itheta, iphi) sits at row (itheta-1)*nphi + iphi, north row first.
10+
11+% Holds the precomputed tables between calls: set once from the top of the
12+% run, read back by every transform below.
13+function S = sht_tables(S)
14+ persistent stored
15+ if nargin > 0
16+ stored = S;
17+ end
18+ S = stored;
19+end
20+
21+% Everything the transforms need for one grid: Gauss nodes and weights,
22+% per-m Legendre tables, the coefficient layout, the derivative shuffles,
23+% and the eigenvalue/filter vectors the models take as `lam` and `filt`.
24+function S = sht_setup(lmax, mmax, nlat, nphi)
25+ S.lmax = lmax;
26+ S.mmax = mmax;
27+ S.nlat = nlat;
28+ S.nphi = nphi;
29+ S.npts = nlat * nphi;
30+ [ct, wg] = gauss_legendre(nlat);
31+ S.ct = ct;
32+ S.st = sqrt(1 - ct.^2);
33+ S.wg = wg;
34+ S.nlm = (mmax + 1) * (lmax + 1) - mmax * (mmax + 1) / 2;
35+
36+ % The grid angles as npts x 1 fields, phi-fastest like everything else.
37+ S.theta = repelem(acos(min(1, max(-1, ct))), nphi);
38+ S.phi = repmat(2*pi*(0:nphi-1)'/nphi, nlat, 1);
39+ S.stpt = repelem(S.st, nphi);
40+
41+ % Degree and order of each coefficient, and each m block's start.
42+ off = zeros(mmax + 1, 1);
43+ lv = zeros(S.nlm, 1);
44+ mv = zeros(S.nlm, 1);
45+ pos = 1;
46+ for m = 0:mmax
47+ n = lmax - m + 1;
48+ off(m + 1) = pos;
49+ lv(pos:pos + n - 1) = (m:lmax)';
50+ mv(pos:pos + n - 1) = m;
51+ pos = pos + n;
52+ end
53+ S.off = off;
54+ S.lv = lv;
55+ S.mv = mv;
56+ % Laplace-Beltrami eigenvalues l(l+1) and the top-mode filter: 1 below
57+ % lmax-2, 0 at the top two degrees, where the derivative recurrences cannot
58+ % exactly represent a derivative (src/mgpu/model.ts).
59+ S.lam = lv .* (lv + 1);
60+ S.filt = double(lv < lmax - 2);
61+
62+ % Orthonormal Legendre tables ytilde_l^m(theta_i), one nlat x (lmax-m+1)
63+ % block per m, by the standard three-term recurrence (src/sht/coeffs.ts;
64+ % SHTNS normalization, Condon-Shortley phase carried in the seed's sign).
65+ S.Y = cell(mmax + 1, 1);
66+ t = 1 / (4*pi);
67+ amm = sqrt(t);
68+ for m = 0:mmax
69+ if m > 0
70+ t = t * (2*m + 1) / (2*m);
71+ amm = (-1)^m * sqrt(t);
72+ end
73+ n = lmax - m + 1;
74+ Y = zeros(nlat, n);
75+ y0 = amm * S.st.^m;
76+ Y(:, 1) = y0;
77+ if n > 1
78+ y1 = sqrt(2*m + 3) * ct .* y0;
79+ Y(:, 2) = y1;
80+ for l = m + 2:lmax
81+ t1 = (l + m) * (l - m);
82+ a = sqrt((2*l + 1) * (2*l - 1) / t1);
83+ b = -sqrt(((2*l + 1) / (2*l - 3)) * ((l - 1 + m) * (l - 1 - m) / t1));
84+ y2 = a * ct .* y1 + b * y0;
85+ Y(:, l - m + 1) = y2;
86+ y0 = y1;
87+ y1 = y2;
88+ end
89+ end
90+ S.Y{m + 1} = Y;
91+ end
92+
93+ % sin(theta)*dtheta in coefficient space: v_l^m = ap(lm) u_{l-1}^m +
94+ % am(lm) u_{l+1}^m (src/sht/derivCoeffs.ts). Neighbors sit at +-1 within
95+ % each m block; ap/am are zero at the block edges, so the clamped index
96+ % vectors never read across a boundary.
97+ l = lv;
98+ m = mv;
99+ ap = (l - 1) .* sqrt(max(0, (l - m) .* (l + m)) ./ ((2*l - 1) .* (2*l + 1)));
100+ ap(l <= m) = 0;
101+ am = -(l + 2) .* sqrt((l + 1 - m) .* (l + 1 + m) ./ ((2*l + 1) .* (2*l + 3)));
102+ am(l >= lmax) = 0;
103+ S.ap = ap;
104+ S.am = am;
105+ S.iprev = max((1:S.nlm)' - 1, 1);
106+ S.inext = min((1:S.nlm)' + 1, S.nlm);
107+
108+ % dphig's Fourier multiplier: i*m on fft's frequency layout, masked past
109+ % the filter's reach (mcut = lmax-3), mirroring src/sht/wgsl/deriv.ts.
110+ freq = [(0:nphi/2)'; (-nphi/2 + 1:-1)'];
111+ S.dmul = 1i * freq .* (abs(freq) <= max(0, lmax - 3));
112+end
113+
114+% Gauss-Legendre nodes cos(theta), in decreasing order (north pole first),
115+% and weights for integration over cos(theta) -- Newton iteration on P_n,
116+% as src/sht/gauss.ts.
117+function [x, w] = gauss_legendre(n)
118+ x = zeros(n, 1);
119+ w = zeros(n, 1);
120+ half = floor((n + 1) / 2);
121+ for i = 1:half
122+ z = cos(pi * (i - 0.25) / (n + 0.5));
123+ pp = 0;
124+ for it = 1:100
125+ p1 = 1;
126+ p2 = 0;
127+ for j = 1:n
128+ p3 = p2;
129+ p2 = p1;
130+ p1 = ((2*j - 1) * z * p2 - (j - 1) * p3) / j;
131+ end
132+ pp = n * (z * p1 - p2) / (z^2 - 1);
133+ dz = p1 / pp;
134+ z = z - dz;
135+ if abs(dz) < 1e-15 * abs(z) + 1e-300
136+ p1 = 1;
137+ p2 = 0;
138+ for j = 1:n
139+ p3 = p2;
140+ p2 = p1;
141+ p1 = ((2*j - 1) * z * p2 - (j - 1) * p3) / j;
142+ end
143+ pp = n * (z * p1 - p2) / (z^2 - 1);
144+ z = z - p1 / pp;
145+ break;
146+ end
147+ end
148+ x(i) = z;
149+ x(n + 1 - i) = -z;
150+ wi = 2 / ((1 - z^2) * pp^2);
151+ w(i) = wi;
152+ w(n + 1 - i) = wi;
153+ end
154+ if mod(n, 2) == 1
155+ x(half) = 0;
156+ end
157+end
158+
159+% Synthesis, spectral -> grid. Grouped calls -- [a, b] = synth(x, y) -- are
160+% the app's batching hint; here each member simply runs in turn.
161+function varargout = synth(varargin)
162+ S = sht_tables();
163+ varargout = cell(1, nargin);
164+ for k = 1:nargin
165+ varargout{k} = synth_one(S, varargin{k});
166+ end
167+end
168+
169+function f = synth_one(S, Q)
170+ % Legendre stage per m, then one inverse FFT per latitude ring with the
171+ % m < 0 modes filled in by conjugate symmetry (the field is real).
172+ G = zeros(S.nphi, S.nlat);
173+ for m = 0:S.mmax
174+ Fm = (S.Y{m + 1} * Q(S.off(m + 1):S.off(m + 1) + S.lmax - m)).';
175+ G(m + 1, :) = Fm;
176+ if m > 0
177+ G(S.nphi + 1 - m, :) = conj(Fm);
178+ end
179+ end
180+ f = S.nphi * real(ifft(G, [], 1));
181+ f = f(:);
182+end
183+
184+% Analysis, grid -> spectral: forward FFT per ring, then Gauss quadrature
185+% against the same Legendre tables.
186+function varargout = analys(varargin)
187+ S = sht_tables();
188+ varargout = cell(1, nargin);
189+ for k = 1:nargin
190+ varargout{k} = analys_one(S, varargin{k});
191+ end
192+end
193+
194+function Q = analys_one(S, f)
195+ F = fft(reshape(f, S.nphi, S.nlat), [], 1) * (2*pi/S.nphi);
196+ Q = complex(zeros(S.nlm, 1));
197+ for m = 0:S.mmax
198+ Q(S.off(m + 1):S.off(m + 1) + S.lmax - m) = S.Y{m + 1}.' * (S.wg .* F(m + 1, :).');
199+ end
200+end
201+
202+% The coefficients of sin(theta)*dtheta(u): the alpha^+/alpha^- shift by one
203+% degree within each m block.
204+function V = dthetac(Q)
205+ S = sht_tables();
206+ V = S.ap .* Q(S.iprev) + S.am .* Q(S.inext);
207+end
208+
209+% The coefficients of dphi(u): i*m, diagonal.
210+function V = dphic(Q)
211+ S = sht_tables();
212+ V = 1i * (S.mv .* Q);
213+end
214+
215+% Grid-space derivatives, coefficients in: compositions of the shuffles and
216+% the synthesis (src/sht/deriv.ts). dtheta divides by sin(theta) afterwards.
217+function f = dtheta(Q)
218+ S = sht_tables();
219+ f = synth(dthetac(Q)) ./ S.stpt;
220+end
221+
222+function f = dphi(Q)
223+ f = synth(dphic(Q));
224+end
225+
226+% Grid-space phi derivative, grid in: two FFT stages and a pointwise i*m,
227+% no Legendre work -- d/dphi is diagonal in the Fourier index.
228+function g = dphig(f)
229+ S = sht_tables();
230+ F = fft(reshape(f, S.nphi, S.nlat), [], 1);
231+ g = real(ifft(S.dmul .* F, [], 1));
232+ g = g(:);
233+end
234+
235+% ---------------------------------------------------------------- the surface
236+%
237+% What the app precomputes from a shape's raw grid values: the band-limited
238+% embedding and both metric formulations built on it (src/geom/geometry.ts,
239+% src/geom/metric.ts). The solver runs on the synthesis of the coefficients,
240+% not on the raw values -- for a shape with sharp features the two differ.
241+function G = surface_tables(gxr, gyr, gzr)
242+ S = sht_tables();
243+ [G.Gx, G.Gy, G.Gz] = analys(gxr, gyr, gzr);
244+ [G.gx, G.gy, G.gz] = synth(G.Gx, G.Gy, G.Gz);
245+
246+ % Flux-form metric weights, from the sin-weighted theta tangent
247+ % sin(theta)*X_theta and X_phi, both smooth on the sphere:
248+ % gtt~ = sin^2 g_tt, gtp~ = sin g_tp, D = J sin^2(theta).
249+ [sXtx, sXty, sXtz] = synth(dthetac(G.Gx), dthetac(G.Gy), dthetac(G.Gz));
250+ [Xpx, Xpy, Xpz] = synth(dphic(G.Gx), dphic(G.Gy), dphic(G.Gz));
251+ gtt = sXtx.^2 + sXty.^2 + sXtz.^2;
252+ gtp = sXtx.*Xpx + sXty.*Xpy + sXtz.*Xpz;
253+ gpp = Xpx.^2 + Xpy.^2 + Xpz.^2;
254+ D = sqrt(gtt .* gpp - gtp.^2);
255+ G.p1 = gpp ./ D;
256+ G.p2 = -gtp ./ D;
257+ G.q2 = gtt ./ D;
258+ G.r = 1 ./ D;
259+
260+ % The sphere-subtracted weights and the bounded 1/J = r sin^2(theta) --
261+ % what keeps the concentrated division off the round sphere's share of the
262+ % flux divergence. Formed here in f64, as the app forms them.
263+ G.jinv = G.r .* S.stpt.^2;
264+ G.dp1 = G.p1 - 1;
265+ G.dq2 = G.q2 - 1;
266+
267+ % Preconditioner scale Jhat = 2/(muMin + muMax) over the eigenvalues of
268+ % the operator's symbol S = (1/J)[[p1, p2], [p2, q2]].
269+ s11 = G.p1 .* G.jinv;
270+ s12 = G.p2 .* G.jinv;
271+ s22 = G.q2 .* G.jinv;
272+ mn = (s11 + s22) / 2;
273+ disc = sqrt(((s11 - s22) / 2).^2 + s12.^2);
274+ G.Jhat = 2 / (min(mn - disc) + max(mn + disc));
275+
276+ % Inverse metric quantities V_theta/V_phi, for the Algorithm-4 models.
277+ Xtx = sXtx ./ S.stpt;
278+ Xty = sXty ./ S.stpt;
279+ Xtz = sXtz ./ S.stpt;
280+ g11 = Xtx.^2 + Xty.^2 + Xtz.^2;
281+ g12 = Xtx.*Xpx + Xty.*Xpy + Xtz.*Xpz;
282+ g22 = gpp;
283+ det = g11 .* g22 - g12.^2;
284+ G.Vtx = (g22 .* Xtx - g12 .* Xpx) ./ det;
285+ G.Vty = (g22 .* Xty - g12 .* Xpy) ./ det;
286+ G.Vtz = (g22 .* Xtz - g12 .* Xpz) ./ det;
287+ G.Vpx = (g11 .* Xpx - g12 .* Xtx) ./ det;
288+ G.Vpy = (g11 .* Xpy - g12 .* Xty) ./ det;
289+ G.Vpz = (g11 .* Xpz - g12 .* Xtz) ./ det;
290+end
291+
292+% ---------------------------------------------------------------- random field
293+%
294+% chebfun-style smooth random field in 3D, restricted to the surface by
295+% evaluating it at the grid points -- the way surfacefun seeds a run. Two
296+% signatures, as in the app:
297+% [k, c] = randnfun3(lambda, dom) the Fourier-mode draw (tools/randnfun3.m)
298+% f = randnfun3(lambda, gx, gy, gz) that draw, summed at the surface points
299+% Seed with rng(...) before calling.
300+function varargout = randnfun3(lambda, varargin)
301+ if nargin == 2
302+ [k, c] = randnfun3_modes(lambda, varargin{1});
303+ varargout = {k, c};
304+ return;
305+ end
306+ [gx, gy, gz] = deal(varargin{1:3});
307+ dom = [min(gx) max(gx) min(gy) max(gy) min(gz) max(gz)];
308+ [k, c] = randnfun3_modes(lambda, dom);
309+ % Summed in blocks of modes: the full npts x nmodes phase matrix can reach
310+ % hundreds of MB at a fine wavelength.
311+ f = zeros(numel(gx), 1);
312+ blk = 2048;
313+ for j0 = 1:blk:size(k, 1)
314+ j1 = min(j0 + blk - 1, size(k, 1));
315+ t = gx * k(j0:j1, 1)' + gy * k(j0:j1, 2)' + gz * k(j0:j1, 3)';
316+ f = f + cos(t) * c(j0:j1, 1) - sin(t) * c(j0:j1, 2);
317+ end
318+ varargout = {f};
319+end
320+
321+% ---------------------------------------------------------------- display
322+%
323+% The pattern on the surface, one panel per species. The solver grid has no
324+% pole rows and an open phi seam; wrap_grid closes both for display, capping
325+% each pole with the mean of its nearest ring.
326+function h = plot_setup(gx, gy, gz, fields, names)
327+ fig = figure('Name', 'turing-surface', 'Color', 'w');
328+ Xs = wrap_grid(gx);
329+ Ys = wrap_grid(gy);
330+ Zs = wrap_grid(gz);
331+ n = numel(fields);
332+ h.surf = gobjects(1, n);
333+ h.ax = gobjects(1, n);
334+ for k = 1:n
335+ ax = subplot(1, n, k, 'Parent', fig);
336+ h.surf(k) = surf(ax, Xs, Ys, Zs, wrap_grid(fields{k}), 'EdgeColor', 'none');
337+ shading(ax, 'interp');
338+ axis(ax, 'equal');
339+ axis(ax, 'off');
340+ colormap(ax, 'jet');
341+ colorbar(ax);
342+ h.ax(k) = ax;
343+ end
344+ h.names = names;
345+end
346+
347+function plot_update(h, fields, t, k, nsteps)
348+ for i = 1:numel(fields)
349+ C = wrap_grid(fields{i});
350+ set(h.surf(i), 'CData', C);
351+ lo = min(C(:));
352+ hi = max(C(:));
353+ if ~(hi > lo)
354+ hi = lo + 1;
355+ end
356+ caxis(h.ax(i), [lo hi]);
357+ title(h.ax(i), sprintf('%s t = %.3f (step %d/%d)', h.names{i}, t, k, nsteps));
358+ end
359+ drawnow;
360+end
361+
362+function M = wrap_grid(f)
363+ S = sht_tables();
364+ M = reshape(f, S.nphi, S.nlat).';
365+ M = [M, M(:, 1)];
366+ M = [mean(M(1, :)) * ones(1, S.nphi + 1); M; mean(M(end, :)) * ones(1, S.nphi + 1)];
367+end
368+
369+% ---------------------------------------------------------------- results file
370+%
371+% Complex coefficients -> flat float32 [re, im] per (l, m), the layout the
372+% app's reference-file reader expects (docs/ellipsoid-reference-spec.md).
373+function write_coeffs(fname, path, Q)
374+ flat = zeros(2 * numel(Q), 1);
375+ flat(1:2:end) = real(Q);
376+ flat(2:2:end) = imag(Q);
377+ h5create(fname, path, numel(flat), 'Datatype', 'single');
378+ h5write(fname, path, single(flat));
379+end
380+
381+% h5writeatt cannot create a bare group, so the attribute-only groups of the
382+% reference layout are made through the low-level API.
383+function make_group(fname, path)
384+ fid = H5F.open(fname, 'H5F_ACC_RDWR', 'H5P_DEFAULT');
385+ gid = H5G.create(fid, path, 'H5P_DEFAULT', 'H5P_DEFAULT', 'H5P_DEFAULT');
386+ H5G.close(gid);
387+ H5F.close(fid);
388+end
src/geom/geometry.tsmodified+28−9View file
@@ -40,8 +40,9 @@ import {
4040 type RuntimeValue,
4141 } from 'numbl-src/numbl-core/runtime/types.ts';
4242 import { ShtPlan } from '../sht/sht.ts';
43-import type { ShtConfig } from '../sht/layout.ts';
43+import { relayoutCoeffs, type ShtConfig } from '../sht/layout.ts';
4444 import type { DerivPlan } from '../sht/deriv.ts';
45+import type { ImportedCoeffs } from './registry.ts';
4546 import { computeMetric, computeFluxMetric } from './metric.ts';
4647 import { toolFiles } from '../tools.ts';
4748 import { inFunction, inModel, ModelCompileError } from '../mgpu/errors.ts';
@@ -61,6 +62,13 @@ export interface GeometryOptions {
6162 params: ModelParams;
6263 /** Computes the theta/phi derivatives the inverse metric quantities need. */
6364 deriv: DerivPlan;
65+ /**
66+ * The surface as coefficients instead of a .m. When set, `source` is never
67+ * evaluated: the coefficients are re-indexed onto this plan's band
68+ * (truncation is exact projection, padding is exact) and everything from
69+ * synthesis onward runs unchanged.
70+ */
71+ coeffs?: ImportedCoeffs;
6472 }
6573
6674 export class Geometry {
@@ -189,16 +197,27 @@ export class Geometry {
189197 const { sht, cfg, source, paramNames, params, deriv } = opts;
190198 const npts = cfg.nlat * cfg.nphi;
191199
192- const { theta, phi } = gridAngles(sht, cfg);
193- const raw = evaluateShape(source, paramNames, params, theta, phi, npts);
194-
195200 // Coefficients first, then back to the grid: what the solver and the
196201 // renderer both see is the band-limited surface, not the raw .m output.
197- const [X, Y, Z] = [
198- await sht.analys(raw[0]),
199- await sht.analys(raw[1]),
200- await sht.analys(raw[2]),
201- ];
202+ // An imported surface arrives already as coefficients, so its .m stage is
203+ // a re-indexing onto this plan's band rather than an evaluation.
204+ let X: Float32Array;
205+ let Y: Float32Array;
206+ let Z: Float32Array;
207+ if (opts.coeffs) {
208+ const from = { lmax: opts.coeffs.lmax, mmax: opts.coeffs.mmax };
209+ X = relayoutCoeffs(opts.coeffs.X, from, cfg);
210+ Y = relayoutCoeffs(opts.coeffs.Y, from, cfg);
211+ Z = relayoutCoeffs(opts.coeffs.Z, from, cfg);
212+ } else {
213+ const { theta, phi } = gridAngles(sht, cfg);
214+ const raw = evaluateShape(source, paramNames, params, theta, phi, npts);
215+ [X, Y, Z] = [
216+ await sht.analys(raw[0]),
217+ await sht.analys(raw[1]),
218+ await sht.analys(raw[2]),
219+ ];
220+ }
202221 const [x, y, z] = [
203222 await sht.synth(X),
204223 await sht.synth(Y),
src/geom/registry.tsmodified+46−0View file
@@ -23,6 +23,23 @@ export interface MGeometry {
2323 params: ParamSpec[];
2424 /** MATLAB source — the shape itself. */
2525 source: string;
26+ /**
27+ * When set, the shape IS these spherical-harmonic coefficients and `source`
28+ * is a display-only stub: Geometry.create re-indexes them onto the session's
29+ * band instead of evaluating any .m. How a surface handed over by another
30+ * app (reharm's "Export to turing-surface") enters the pipeline.
31+ */
32+ coeffs?: ImportedCoeffs;
33+}
34+
35+/** A surface as coefficients of x, y, z — the same three arrays a reference
36+ * file's /geometry group holds, in the shared SHTNS layout (src/sht/layout.ts). */
37+export interface ImportedCoeffs {
38+ lmax: number;
39+ mmax: number;
40+ X: Float32Array;
41+ Y: Float32Array;
42+ Z: Float32Array;
2643 }
2744
2845 const sphere: MGeometry = {
@@ -92,6 +109,35 @@ export const defaultGeometryParams = (g: MGeometry): Params =>
92109 * none gets: the case where the solver is exact. */
93110 export const SPHERE_KEY = 'sphere';
94111
112+/** The dropdown key an imported surface lives under. Not in `mGeometries`:
113+ * the entry exists only after an import arrives, and the page owns it. */
114+export const IMPORTED_GEOMETRY_KEY = 'imported';
115+
116+/**
117+ * Wrap a handed-over surface as a geometry the rest of the app can hold like
118+ * any registry entry. No parameters — the shape is whatever the coefficients
119+ * say — and the .m slot carries a note rather than code, since the import
120+ * path in Geometry.create never evaluates it.
121+ */
122+export function makeImportedGeometry(
123+ name: string,
124+ blurb: string,
125+ coeffs: ImportedCoeffs,
126+): MGeometry {
127+ return {
128+ key: IMPORTED_GEOMETRY_KEY,
129+ label: name,
130+ blurb,
131+ params: [],
132+ source:
133+ `% ${name}\n` +
134+ `% This surface was handed over as spherical-harmonic coefficients\n` +
135+ `% (lmax ${coeffs.lmax}), so there is no .m to edit: the solver uses the\n` +
136+ `% coefficients directly, and edits here have no effect.\n`,
137+ coeffs,
138+ };
139+}
140+
95141 /** What the app and the benchmark start on. Not the sphere: this project
96142 * exists for the other shapes, and opening on the reference case would hide
97143 * the one thing it adds. */
src/main.tsmodified+659−44View file
@@ -1,5 +1,5 @@
11 import { requestShtDevice, describeAdapter } from './sht/sht.ts';
2-import { gridForLmax } from './sht/layout.ts';
2+import { gridForLmax, nlmCalc } from './sht/layout.ts';
33 import { ModelSession } from './mgpu/session.ts';
44 import { mModelByKey, presets, type MModel, type Params } from './mgpu/registry.ts';
55 import { ModelCompileError, formatFailure } from './mgpu/errors.ts';
@@ -18,6 +18,10 @@ import {
1818 mGeometryByKey,
1919 defaultGeometryParams,
2020 DEFAULT_GEOMETRY_KEY,
21+ SPHERE_KEY,
22+ IMPORTED_GEOMETRY_KEY,
23+ makeImportedGeometry,
24+ type ImportedCoeffs,
2125 type MGeometry,
2226 } from './geom/registry.ts';
2327 import {
@@ -39,6 +43,9 @@ import {
3943 variantLabel,
4044 type Variant,
4145 } from './compare/variants.ts';
46+import { loadReferenceFile } from './compare/referenceFile.ts';
47+import type { ReferenceCase } from './compare/referenceCase.ts';
48+import { generateMatlabScript, MATLAB_SCRIPT_NAME } from './export/matlabScript.ts';
4249
4350 const $ = <T extends HTMLElement>(id: string): T =>
4451 document.getElementById(id) as T;
@@ -51,6 +58,7 @@ const elLmax = $<HTMLSelectElement>('lmax');
5158 const elOversample = $<HTMLSelectElement>('oversample');
5259 const elColormap = $<HTMLSelectElement>('colormap');
5360 const elRunPause = $<HTMLButtonElement>('runpause');
61+const elRestart = $<HTMLButtonElement>('restart');
5462 const elBenchmark = $<HTMLButtonElement>('benchmark');
5563 const elReseed = $<HTMLButtonElement>('reseed');
5664 const elLam3 = $<HTMLInputElement>('lam3');
@@ -61,22 +69,36 @@ const elMovieSpeed = $<HTMLSelectElement>('moviespeed');
6169 const elMovieRes = $<HTMLSelectElement>('movieres');
6270 const elMovieRotate = $<HTMLInputElement>('movierotate');
6371 const elMovie = $<HTMLButtonElement>('movie');
64-const elCompareToggle = $<HTMLButtonElement>('comparetoggle');
72+const elModeSimulate = $<HTMLButtonElement>('mode-simulate');
73+const elModeEffort = $<HTMLButtonElement>('mode-effort');
74+const elModeVsSphere = $<HTMLButtonElement>('mode-vs-sphere');
75+const elModeVsUpload = $<HTMLButtonElement>('mode-vs-upload');
76+const elModeDesc = $('mode-desc');
6577 const elCompareBar = $('comparebar');
78+const elCmpAxes = $('cmp-axes');
6679 const elCmpNiter = $('cmp-niter');
6780 const elCmpLmax = $('cmp-lmax');
6881 const elCmpDt = $('cmp-dt');
82+const elCmpRefLabel = $('cmp-reflabel');
6983 const elCmpRef = $<HTMLSelectElement>('cmp-ref');
84+const elCmpFile = $<HTMLInputElement>('cmp-file');
85+const elCmpFileInfo = $('cmp-fileinfo');
86+const elCmpFileClear = $<HTMLButtonElement>('cmp-fileclear');
7087 const elCmpStart = $<HTMLButtonElement>('cmp-start');
7188 const elCmpCount = $('cmp-count');
7289 const elParams = $('params');
7390 const elGeomParams = $('geomparams');
7491 const elGeomNote = $('geomnote');
7592 const elPanels = $('panels');
93+const elCmpChart = $('cmp-chart');
7694 const elStats = $('stats');
7795 const elBenchResult = $('benchresult');
7896 const elCmd = $('cmd');
7997 const elCopyCmd = $<HTMLButtonElement>('copycmd');
98+const elMatlab = $<HTMLDetailsElement>('matlab');
99+const elMatlabScript = $('matlabscript');
100+const elCopyMatlab = $<HTMLButtonElement>('copymatlab');
101+const elDownloadMatlab = $<HTMLButtonElement>('downloadmatlab');
80102 const elBlurb = $('blurb');
81103 const elErr = $('err');
82104 const elSource = $<HTMLTextAreaElement>('source');
@@ -87,6 +109,21 @@ const elEditorFile = $<HTMLSelectElement>('editor-file');
87109 const elRecompile = $<HTMLButtonElement>('recompile');
88110 const elRevert = $<HTMLButtonElement>('revert');
89111
112+/** The named groups the control area is organized into (index.html's
113+ * `.ctrl-group[data-group]` wrappers). Each mode shows a declared subset of
114+ * these — see MODE_GROUPS and applyModeVisibility below. */
115+const GROUP_NAMES = [
116+ 'surface', 'surface-params', 'solver', 'display',
117+ 'playback', 'benchmark', 'seed', 'movie',
118+] as const;
119+type GroupName = (typeof GROUP_NAMES)[number];
120+const groupEls: Record<GroupName, HTMLElement> = Object.fromEntries(
121+ GROUP_NAMES.map((name) => [
122+ name,
123+ document.querySelector(`.ctrl-group[data-group="${name}"]`) as HTMLElement,
124+ ]),
125+) as Record<GroupName, HTMLElement>;
126+
90127 for (const p of presets) {
91128 const o = document.createElement('option');
92129 o.value = p.key;
@@ -254,6 +291,14 @@ let posBuf: Float32Array | null = null;
254291 * mode. While it is non-null there is no `session`: the study owns one per
255292 * variant, and the panels area is its grid. */
256293 let compareRun: CompareRun | null = null;
294+/** The surface handed over by another app (reharm), when one has arrived —
295+ * what the geometry dropdown's 'imported' entry resolves to. */
296+let importedGeometry: MGeometry | null = null;
297+/** `session`'s spectral state as of the last (re-)seed — what "Restart"
298+ * rewinds to. Captured fresh each time a new field is actually established
299+ * (rebuild/reseed), not just once, so Restart reflects the run's current
300+ * starting point rather than permanently the very first draw. */
301+let initialState: Record<string, Float32Array> | null = null;
257302
258303 const source = (): string => editedSource ?? model.source;
259304 const geomSource = (): string => editedGeomSource ?? geometry.source;
@@ -261,6 +306,10 @@ const geomSource = (): string => editedGeomSource ?? geometry.source;
261306 // ---------------------------------------------------------------- UI wiring
262307 function buildParamInputs(): void {
263308 elParams.replaceChildren();
309+ if (model.params.length === 0) return;
310+ const tag = document.createElement('label');
311+ tag.textContent = 'model parameters';
312+ elParams.append(tag);
264313 for (const spec of model.params) {
265314 const label = document.createElement('label');
266315 label.textContent = `${spec.label} `;
@@ -296,7 +345,7 @@ function buildGeomParamInputs(): void {
296345 elGeomParams.replaceChildren();
297346 if (geometry.params.length === 0) return;
298347 const tag = document.createElement('label');
299- tag.textContent = `${geometry.key}.m`;
348+ tag.textContent = 'geometry parameters';
300349 elGeomParams.append(tag);
301350 for (const spec of geometry.params) {
302351 // A random seed picks a draw and means nothing on its own, so it gets a
@@ -316,6 +365,7 @@ function buildGeomParamInputs(): void {
316365 next = spec.min + Math.floor(Math.random() * (span + 1));
317366 }
318367 geomParams[spec.key] = next;
368+ updateCommand();
319369 viewChange = viewChange.then(() => applyGeometry());
320370 });
321371 elGeomParams.append(button);
@@ -332,6 +382,7 @@ function buildGeomParamInputs(): void {
332382 input.addEventListener('change', () => {
333383 const v = Number(input.value);
334384 if (Number.isFinite(v)) geomParams[spec.key] = v;
385+ updateCommand();
335386 viewChange = viewChange.then(() => applyGeometry());
336387 });
337388 label.append(input);
@@ -356,7 +407,10 @@ function applyPreset(presetKey: string): void {
356407 }
357408
358409 function applyGeometryChoice(key: string): void {
359- const next = mGeometryByKey(key);
410+ // The imported entry is the page's own, not the registry's — it exists only
411+ // after a surface has been handed over (see the reharm import block below).
412+ const next =
413+ key === IMPORTED_GEOMETRY_KEY ? importedGeometry : mGeometryByKey(key);
360414 if (!next) {
361415 elErr.textContent = `No .m geometry for '${key}'`;
362416 return;
@@ -366,6 +420,8 @@ function applyGeometryChoice(key: string): void {
366420 editedGeomSource = null;
367421 buildGeomParamInputs();
368422 showEditorFile();
423+ // The command line and the MATLAB export both bake the surface in.
424+ updateCommand();
369425 }
370426
371427 /** Load the chosen file into the editor, keeping any unsaved edit to it. */
@@ -403,7 +459,58 @@ function currentSpec(): RunSpec {
403459 }
404460
405461 function updateCommand(): void {
406- elCmd.textContent = formatCommand(currentSpec());
462+ // A study against a reference file replays the file, so its desktop
463+ // equivalent is the ref checker, not the benchmark.
464+ if (compareRun?.refFile) {
465+ elCmd.textContent = `npm run ref -- --in ${compareRun.refFile.label}`;
466+ } else if (geometry.coeffs) {
467+ // An imported surface exists only as coefficients in this page, so no
468+ // command line can regenerate the run.
469+ elCmd.textContent = '(imported surface — no desktop equivalent)';
470+ } else {
471+ elCmd.textContent = formatCommand(currentSpec());
472+ }
473+ if (elMatlab.open) refreshMatlabScript();
474+}
475+
476+/** The run on screen as one standalone .m — in a study, its reference
477+ * variant, the same choice `currentSpec` makes. Throws on a working copy
478+ * the export cannot parse (no init/step/shape function). */
479+function matlabScriptText(): string {
480+ if (geometry.coeffs) {
481+ throw new Error(
482+ 'The imported surface has no .m, so the MATLAB export cannot bake it in. ' +
483+ 'Export the surface from reharm as .h5 and load its /geometry ' +
484+ 'coefficients with h5read instead.',
485+ );
486+ }
487+ const spec = currentSpec();
488+ return generateMatlabScript({
489+ model,
490+ modelSource: source(),
491+ params: spec.params,
492+ geometry,
493+ geometrySource: geomSource(),
494+ geometryParams: geomParams,
495+ lmax: spec.lmax,
496+ niter: spec.niter,
497+ lam3: Number(elLam3.value),
498+ seed,
499+ preset: spec.preset,
500+ command: formatCommand(spec),
501+ });
502+}
503+
504+/** Regenerate the visible script text; on failure, show why in its place. */
505+function refreshMatlabScript(): string | null {
506+ try {
507+ const text = matlabScriptText();
508+ elMatlabScript.textContent = text;
509+ return text;
510+ } catch (e) {
511+ elMatlabScript.textContent = e instanceof Error ? e.message : String(e);
512+ return null;
513+ }
407514 }
408515
409516 elModel.addEventListener('change', () => {
@@ -436,6 +543,8 @@ elGeometry.addEventListener('change', () => {
436543 elLam3.addEventListener('change', () => {
437544 const v = Number(elLam3.value);
438545 if (!Number.isFinite(v) || v <= 0) return;
546+ // Not in the bench command, but the MATLAB export bakes lam3 in.
547+ updateCommand();
439548 // Changing the wavelength redraws the field, which restarts the run — so
440549 // pause first, exactly as the Re-seed button does. Without it the reseed's
441550 // readback races the pump's own, and the two collide on the staging buffer.
@@ -491,6 +600,10 @@ elReseed.addEventListener('click', () => {
491600 updateCommand();
492601 void reseed();
493602 });
603+elRestart.addEventListener('click', () => {
604+ setRunning(false);
605+ void restart();
606+});
494607 elResetView.addEventListener('click', () => {
495608 compareRun?.resetView();
496609 for (const s of scenes) s.resetCamera();
@@ -535,6 +648,46 @@ elCopyCmd.addEventListener('click', () => {
535648 navigator.clipboard.writeText(text).then(() => flash('Copied'), selectCommand);
536649 });
537650
651+// The MATLAB export: the same run as one self-contained .m. Regenerated from
652+// the current UI state whenever it is shown, copied or downloaded, so the
653+// text always matches the run on screen.
654+elMatlab.addEventListener('toggle', () => {
655+ if (elMatlab.open) refreshMatlabScript();
656+});
657+elCopyMatlab.addEventListener('click', (e) => {
658+ // The buttons live inside the <summary>; without this a click also toggles.
659+ e.preventDefault();
660+ e.stopPropagation();
661+ const text = refreshMatlabScript();
662+ if (text === null || !navigator.clipboard) {
663+ // Open to show the error, or the text to select by hand.
664+ elMatlab.open = true;
665+ return;
666+ }
667+ navigator.clipboard.writeText(text).then(
668+ () => {
669+ elCopyMatlab.textContent = 'Copied';
670+ setTimeout(() => (elCopyMatlab.textContent = 'Copy'), 1200);
671+ },
672+ () => (elMatlab.open = true),
673+ );
674+});
675+elDownloadMatlab.addEventListener('click', (e) => {
676+ e.preventDefault();
677+ e.stopPropagation();
678+ const text = refreshMatlabScript();
679+ if (text === null) {
680+ elMatlab.open = true;
681+ return;
682+ }
683+ const url = URL.createObjectURL(new Blob([text], { type: 'text/x-matlab' }));
684+ const a = document.createElement('a');
685+ a.href = url;
686+ a.download = `${MATLAB_SCRIPT_NAME}.m`;
687+ a.click();
688+ URL.revokeObjectURL(url);
689+});
690+
538691 // ---------------------------------------------------------------- setup
539692 function disposeView(): void {
540693 for (const s of scenes) s.dispose();
@@ -751,6 +904,9 @@ async function rebuild(): Promise<void> {
751904 if (gen !== generation) return;
752905
753906 await session.seed(seed);
907+ if (gen !== generation) return;
908+ initialState = await session.readState();
909+ if (gen !== generation) return;
754910
755911 const plan = session.describe();
756912 elCompiled.textContent =
@@ -785,6 +941,24 @@ async function reseed(): Promise<void> {
785941 const gen = generation;
786942 await session.seed(seed);
787943 if (gen !== generation) return;
944+ initialState = await session.readState();
945+ if (gen !== generation) return;
946+ for (const r of ranges) {
947+ r.lo = NaN;
948+ r.hi = NaN;
949+ }
950+ await draw();
951+ updateStats();
952+}
953+
954+/** Rewind to the field this run is currently starting from — the last
955+ * (re-)seed, not necessarily the very first one — without drawing a new
956+ * one. Unlike reseed(), the seed value and lam3 are untouched, so nothing
957+ * the CLI command line encodes changes. */
958+async function restart(): Promise<void> {
959+ if (compareRun) return compareRun.restart();
960+ if (!session || !initialState) return;
961+ session.loadState(initialState);
788962 for (const r of ranges) {
789963 r.lo = NaN;
790964 r.hi = NaN;
@@ -986,7 +1160,7 @@ function submitSteps(n: number): void {
9861160 function setMovieUi(on: boolean): void {
9871161 const locked = [
9881162 elModel, elGeometry, elMorph, elNiter, elLmax, elOversample, elColormap,
989- elRunPause, elBenchmark, elReseed, elRecompile, elRevert, elEditorFile,
1163+ elRunPause, elRestart, elBenchmark, elReseed, elRecompile, elRevert, elEditorFile,
9901164 elMovieSpeed, elMovieRes, elMovieRotate, elMovieToggle,
9911165 ];
9921166 for (const el of locked) el.disabled = on;
@@ -1203,6 +1377,15 @@ function buildChips(host: HTMLElement, values: number[], selected: Set<number>,
12031377 const cmpVariants = (): Variant[] =>
12041378 crossProduct([...cmpSelected.niter], [...cmpSelected.lmax], [...cmpSelected.dt]);
12051379
1380+/**
1381+ * A loaded reference file, or null. While one is loaded the study checks the
1382+ * variants against it instead of against each other: the file defines the
1383+ * whole problem (model, parameters, geometry, initial state, end time), so
1384+ * the page's own model and geometry choices do not enter the study at all —
1385+ * only the solver knobs above do.
1386+ */
1387+let refCase: ReferenceCase | null = null;
1388+
12061389 /** The reference the user picked, clamped to the current variant list. */
12071390 let cmpRefKey = '';
12081391
@@ -1213,21 +1396,47 @@ function compareRefIndex(): number {
12131396 }
12141397
12151398 function refreshVariants(): void {
1399+ // vs-sphere has no chip grid feeding cmpVariants() — always exactly two
1400+ // fixed rows plus one diff row, regardless of MAX_VARIANTS/MAX_PANELS —
1401+ // so the grid-count logic below doesn't apply here at all.
1402+ if (currentMode === 'vs-sphere') {
1403+ elCmpCount.textContent = `2 rows × ${model.species.length} species + 1 diff row`;
1404+ elCmpCount.style.color = '';
1405+ elCmpStart.disabled = false;
1406+ return;
1407+ }
12161408 const variants = cmpVariants();
12171409 const showDt = cmpSelected.dt.size > 1;
1218- const panels = variants.length * model.species.length;
1410+ // With a file loaded the study's model is the file's, and its final state
1411+ // is one more row of panels.
1412+ const cmpModel = refCase?.model ?? model;
1413+ const rowCount = variants.length + (refCase ? 1 : 0);
1414+ // Every row but the reference variant (or, against a file, every variant)
1415+ // gets a second diff row underneath it — each one more WebGL context per
1416+ // species, so MAX_PANELS has to bound the real total, not just the values.
1417+ const diffRowCount = refCase ? variants.length : Math.max(0, variants.length - 1);
1418+ const panels = (rowCount + diffRowCount) * cmpModel.species.length;
12191419
12201420 const prev = cmpRefKey;
12211421 elCmpRef.replaceChildren();
1222- for (const v of variants) {
1422+ if (refCase) {
1423+ // The file is the reference; the pick among variants means nothing here.
12231424 const o = document.createElement('option');
1224- o.value = variantKey(v);
1225- o.textContent = variantLabel(v, showDt);
1425+ o.textContent = `the file's final state`;
12261426 elCmpRef.append(o);
1427+ elCmpRef.disabled = true;
1428+ } else {
1429+ elCmpRef.disabled = false;
1430+ for (const v of variants) {
1431+ const o = document.createElement('option');
1432+ o.value = variantKey(v);
1433+ o.textContent = variantLabel(v, showDt);
1434+ elCmpRef.append(o);
1435+ }
1436+ const keys = variants.map(variantKey);
1437+ cmpRefKey = keys.includes(prev) ? prev : keys[mostResolved(variants)];
1438+ elCmpRef.value = cmpRefKey;
12271439 }
1228- const keys = variants.map(variantKey);
1229- cmpRefKey = keys.includes(prev) ? prev : keys[mostResolved(variants)];
1230- elCmpRef.value = cmpRefKey;
12311440
12321441 const tooMany =
12331442 variants.length > MAX_VARIANTS
@@ -1237,23 +1446,74 @@ function refreshVariants(): void {
12371446 : '';
12381447 elCmpCount.textContent = tooMany
12391448 ? `too many: ${tooMany}`
1240- : `${variants.length} variants × ${model.species.length} species = ${panels} panels`;
1449+ : `${variants.length} variant${variants.length === 1 ? '' : 's'}` +
1450+ `${refCase ? ' + the file' : ''} × ` +
1451+ `${cmpModel.species.length} species` +
1452+ (diffRowCount > 0 ? ` + ${diffRowCount} diff row${diffRowCount === 1 ? '' : 's'}` : '') +
1453+ ` = ${panels} panels`;
12411454 elCmpCount.style.color = tooMany ? '#b35900' : '';
12421455 elCmpStart.disabled = tooMany !== '' && compareRun === null;
12431456 }
12441457
1245-buildChips(
1246- elCmpNiter,
1247- [...elNiter.options].map((o) => Number(o.value)),
1248- cmpSelected.niter,
1249- String,
1250-);
1251-buildChips(
1252- elCmpLmax,
1253- [...elLmax.options].map((o) => Number(o.value)),
1254- cmpSelected.lmax,
1255- String,
1256-);
1458+/**
1459+ * The niter chips on offer. A loaded reference file adds its own recorded
1460+ * iteration count if the standard list lacks it, so the file's settings are
1461+ * always selectable; clearing the file drops any selection outside the
1462+ * standard list again.
1463+ */
1464+function rebuildNiterChips(): void {
1465+ const all = [...elNiter.options].map((o) => Number(o.value));
1466+ let values = all;
1467+ if (refCase && !all.includes(refCase.niter)) {
1468+ values = [...all, refCase.niter].sort((a, b) => a - b);
1469+ }
1470+ if (!refCase) {
1471+ for (const v of [...cmpSelected.niter]) if (!values.includes(v)) cmpSelected.niter.delete(v);
1472+ if (cmpSelected.niter.size === 0) cmpSelected.niter.add(DEFAULT_NITER);
1473+ }
1474+ buildChips(elCmpNiter, values, cmpSelected.niter, String);
1475+}
1476+
1477+/**
1478+ * The lmax chips on offer. A loaded reference file floors them at its own
1479+ * band: a variant below it could not even hold the file's initial state
1480+ * (prolongation only widens), so those values are not offered rather than
1481+ * offered and refused.
1482+ */
1483+function rebuildLmaxChips(): void {
1484+ const all = [...elLmax.options].map((o) => Number(o.value));
1485+ let values = all;
1486+ if (refCase) {
1487+ const floor = refCase.lmax;
1488+ values = all.filter((v) => v >= floor);
1489+ if (!values.includes(floor)) values = [floor, ...values];
1490+ for (const v of [...cmpSelected.lmax]) if (!values.includes(v)) cmpSelected.lmax.delete(v);
1491+ if (cmpSelected.lmax.size === 0) cmpSelected.lmax.add(floor);
1492+ }
1493+ buildChips(elCmpLmax, values, cmpSelected.lmax, String);
1494+}
1495+
1496+/**
1497+ * The four top-level modes and which control groups each shows (see
1498+ * GROUP_NAMES/groupEls above; `.ctrl-group` wrappers in index.html).
1499+ * `currentMode` tracks which configuration is on screen — the compare bar
1500+ * being open, and in which flavor — not whether a study has actually been
1501+ * started inside it. That match matters: without it, opening the bar
1502+ * (which already shows the right groups) leaves its top-row button
1503+ * unhighlighted until a study happens to start, which is inconsistent with
1504+ * `vs-upload`'s one-click flow and reads as broken.
1505+ *
1506+ * Declared here, ahead of the top-level `refreshVariants()` call just below
1507+ * — that call reads `currentMode` (to know whether to skip its chip-grid
1508+ * counting for vs-sphere), so the declaration has to be in scope by the time
1509+ * this file's top-level code actually runs, not merely by the time
1510+ * `refreshVariants` is later invoked from an event handler.
1511+ */
1512+type Mode = 'simulate' | 'compute-effort' | 'vs-sphere' | 'vs-upload';
1513+let currentMode: Mode = 'simulate';
1514+
1515+rebuildNiterChips();
1516+rebuildLmaxChips();
12571517 buildChips(elCmpDt, DT_DIVISORS, cmpSelected.dt, (v) => (v === 1 ? 'dt' : `dt/${v}`));
12581518 refreshVariants();
12591519
@@ -1262,8 +1522,174 @@ elCmpRef.addEventListener('change', () => {
12621522 if (compareRun) void rebuildCompare();
12631523 });
12641524
1265-elCompareToggle.addEventListener('click', () => {
1266- elCompareBar.hidden = !elCompareBar.hidden;
1525+/** Reflect the loaded (or cleared) reference file in the compare bar. */
1526+function applyRefUi(): void {
1527+ elCmpFileInfo.hidden = elCmpFileClear.hidden = refCase === null;
1528+ if (refCase) {
1529+ const rc = refCase;
1530+ const geomParamText = rc.geometry.params
1531+ .map((p) => `${p.key}=${rc.geometryParams[p.key]}`)
1532+ .join(' ');
1533+ const name = document.createElement('b');
1534+ name.textContent = rc.label;
1535+ const info = document.createElement('span');
1536+ info.textContent =
1537+ ` — ${rc.model.label} on ${rc.geometry.label.toLowerCase()}` +
1538+ (geomParamText ? ` (${geomParamText})` : '') +
1539+ `, lmax ${rc.lmax}, T = ${(rc.steps * (rc.params.dt ?? 0)).toFixed(2)}` +
1540+ ` (${rc.steps} × dt ${rc.params.dt})`;
1541+ elCmpFileInfo.replaceChildren(name, info);
1542+ }
1543+ rebuildNiterChips();
1544+ rebuildLmaxChips();
1545+ refreshVariants();
1546+}
1547+
1548+const MODE_GROUPS: Record<Mode, readonly GroupName[]> = {
1549+ simulate: ['surface', 'surface-params', 'solver', 'display', 'playback', 'benchmark', 'seed', 'movie'],
1550+ 'compute-effort': ['surface', 'surface-params', 'display', 'playback', 'seed'],
1551+ // Unlike compute-effort, there is no separate chip grid for this mode —
1552+ // both rows always mirror whatever niter/lmax the Simulate controls have,
1553+ // so `solver` has to stay visible; it's the only place those get set.
1554+ 'vs-sphere': ['surface', 'surface-params', 'solver', 'display', 'playback', 'seed'],
1555+ // No `seed` here: nothing in that group does anything useful against a
1556+ // loaded file (lam3 is silently absorbed, and Restart already covers what
1557+ // Re-seed would otherwise be doing — reloading the file's fixed initial
1558+ // state) — see CompareRun.restart().
1559+ 'vs-upload': ['display', 'playback'],
1560+};
1561+
1562+const MODE_DESCRIPTIONS: Record<Mode, string> = {
1563+ simulate:
1564+ 'This mode runs one standalone reaction-diffusion solver.',
1565+ 'compute-effort':
1566+ 'When we change the computational effort of the solver by varying solve iterations, lmax, or timestep, ' +
1567+ 'how does the solution change? Find out by running several ' +
1568+ 'so you can see how each setting trades accuracy for speed.',
1569+ 'vs-sphere':
1570+ 'Run this model once on the selected geometry and once on the plain unit sphere, from the exact same ' +
1571+ 'starting state and the same solve iterations, lmax and timestep, so geometry is the only thing that ' +
1572+ 'differs. See how much resolving the true shape actually changes the pattern, versus approximating it ' +
1573+ 'as a sphere.',
1574+ 'vs-upload':
1575+ 'Load a saved reference run (an .h5 file) and run this solver to the ' +
1576+ 'same physical end time from the same initial condition, to check how ' +
1577+ 'closely it reproduces the reference. You can adjust the solver settings ' +
1578+ 'to see how they affect the outcome.',
1579+};
1580+
1581+function setModeButtons(mode: Mode): void {
1582+ elModeSimulate.setAttribute('aria-pressed', String(mode === 'simulate'));
1583+ elModeEffort.setAttribute('aria-pressed', String(mode === 'compute-effort'));
1584+ elModeVsSphere.setAttribute('aria-pressed', String(mode === 'vs-sphere'));
1585+ elModeVsUpload.setAttribute('aria-pressed', String(mode === 'vs-upload'));
1586+ elModeDesc.textContent = MODE_DESCRIPTIONS[mode];
1587+}
1588+
1589+/** Show exactly the groups `mode` declares; hide the rest. */
1590+function applyModeVisibility(mode: Mode): void {
1591+ currentMode = mode;
1592+ const shown = new Set<GroupName>(MODE_GROUPS[mode]);
1593+ for (const name of GROUP_NAMES) groupEls[name].hidden = !shown.has(name);
1594+ setModeButtons(mode);
1595+}
1596+
1597+/**
1598+ * Enter `mode`: groups, top-row buttons, and the compare bar's own
1599+ * visibility (open for the two compare flavors, closed for Simulate).
1600+ * Doesn't touch `compareRun`/`refCase` or start/stop a study — callers
1601+ * decide that; this only decides what's on screen, and it decides it
1602+ * immediately, so the button you clicked lights up right away rather than
1603+ * waiting on a study that may not exist yet (or may never start, if the
1604+ * bar's own Compare is never pressed).
1605+ */
1606+function enterMode(mode: Mode): void {
1607+ applyModeVisibility(mode);
1608+ elCompareBar.hidden = mode === 'simulate';
1609+ // vs-sphere has no chip grid to pick from — both rows mirror the Simulate
1610+ // panel's own niter/lmax — and no reference to pick among variants either,
1611+ // since the reference is always "the selected geometry." Just the
1612+ // description and the Compile button apply.
1613+ elCmpAxes.hidden = mode === 'vs-sphere';
1614+ elCmpRefLabel.hidden = mode === 'vs-sphere';
1615+}
1616+
1617+/** Entering a mode from the top row. */
1618+function setMode(mode: Mode): void {
1619+ if (mode === 'simulate') {
1620+ if (compareRun) void stopCompare();
1621+ enterMode('simulate');
1622+ return;
1623+ }
1624+ if (mode === 'compute-effort' || mode === 'vs-sphere') {
1625+ // Tear down whatever study is running first (mirrors Simulate above) —
1626+ // stopCompare's synchronous prefix disposes it and nulls `compareRun`
1627+ // before its first `await`, so `refCase` is safe to drop right after.
1628+ // vs-sphere never uses a reference file either — its "reference" is
1629+ // always the selected geometry — so the same drop applies there too.
1630+ if (compareRun) void stopCompare();
1631+ if (refCase) {
1632+ refCase = null;
1633+ applyRefUi();
1634+ }
1635+ enterMode(mode);
1636+ return;
1637+ }
1638+ // vs-upload: opens the file picker; entering the mode itself happens once
1639+ // a file is actually chosen (elCmpFile's change handler below) — not here,
1640+ // since cancelling the dialog must leave the current mode untouched.
1641+ elCmpFile.click();
1642+}
1643+
1644+elModeSimulate.addEventListener('click', () => setMode('simulate'));
1645+elModeEffort.addEventListener('click', () => setMode('compute-effort'));
1646+elModeVsSphere.addEventListener('click', () => setMode('vs-sphere'));
1647+elModeVsUpload.addEventListener('click', () => setMode('vs-upload'));
1648+
1649+elCmpFile.addEventListener('change', () => {
1650+ const file = elCmpFile.files?.[0];
1651+ // Cleared so picking the same file again still fires a change event.
1652+ elCmpFile.value = '';
1653+ if (!file) return;
1654+ void (async () => {
1655+ try {
1656+ refCase = await loadReferenceFile(file);
1657+ elErr.textContent = '';
1658+ } catch (e) {
1659+ refCase = null;
1660+ elErr.textContent = `reference file ${file.name}: ${e instanceof Error ? e.message : e}`;
1661+ applyRefUi();
1662+ return;
1663+ }
1664+ // One click, one study: the file's own settings become the single
1665+ // variant — its recorded niter, its band, its dt undivided — and the
1666+ // comparison opens on them, paused at the initial state so what runs is
1667+ // the user's choice. (Widening it is: teardown the comparison, pick more
1668+ // chips, compile it again — the file stays loaded.)
1669+ cmpSelected.niter.clear();
1670+ cmpSelected.niter.add(refCase.niter);
1671+ cmpSelected.lmax.clear();
1672+ cmpSelected.lmax.add(refCase.lmax);
1673+ cmpSelected.dt.clear();
1674+ cmpSelected.dt.add(1);
1675+ applyRefUi();
1676+ enterMode('vs-upload');
1677+ if (compareRun) {
1678+ // A study is already up (this one loaded over it): same teardown as
1679+ // rebuildCompare, then the new file's study takes its place.
1680+ compareRun.dispose();
1681+ compareRun = null;
1682+ setCompareUi(false);
1683+ }
1684+ await startCompare();
1685+ })();
1686+});
1687+elCmpFileClear.addEventListener('click', () => {
1688+ refCase = null;
1689+ applyRefUi();
1690+ // The bar stays open — this only drops back to the plain chip comparison.
1691+ // Only reachable while idle (elCmpFileClear is disabled during a study).
1692+ enterMode('compute-effort');
12671693 });
12681694
12691695 elCmpStart.addEventListener('click', () => {
@@ -1271,23 +1697,69 @@ elCmpStart.addEventListener('click', () => {
12711697 else void startCompare();
12721698 });
12731699
1274-/** Controls the study supersedes or cannot honour while it is running. */
1700+/**
1701+ * Controls the study supersedes or cannot honour while it is running.
1702+ * Mode/group/button state is not this function's job — that's set the
1703+ * moment a mode is entered (enterMode, above), independent of whether a
1704+ * study inside it has actually started or stopped.
1705+ */
12751706 function setCompareUi(on: boolean): void {
1276- for (const el of [elNiter, elLmax, elOversample, elBenchmark, elMovieToggle]) {
1277- el.disabled = on;
1278- }
1707+ // A study picks its own display grid, so oversample stays individually
1708+ // disabled inside the still-visible display group; and clearing a loaded
1709+ // file out from under a running study would leave it checking against one
1710+ // that no longer exists.
1711+ elOversample.disabled = on;
1712+ elCmpFileClear.disabled = on;
12791713 elCmpNiter.querySelectorAll('button').forEach((b) => (b.disabled = on));
12801714 elCmpLmax.querySelectorAll('button').forEach((b) => (b.disabled = on));
12811715 elCmpDt.querySelectorAll('button').forEach((b) => (b.disabled = on));
1282- elCmpStart.textContent = on ? 'Stop comparing' : 'Compare';
1283- elCompareToggle.textContent = on ? 'Comparing' : 'Compare';
1716+ elCmpStart.textContent = on ? 'Teardown comparison' : 'Compile comparison';
1717+ // The movie bar's own hidden flag is independent of the movie *group's* —
1718+ // force it closed so it doesn't reappear open once the group is shown
1719+ // again on returning to Simulate.
12841720 if (on) elMovieBar.hidden = true;
12851721 }
12861722
12871723 async function startCompare(): Promise<void> {
12881724 if (compareRun || !device) return;
1289- const variants = cmpVariants();
1290- if (variants.length > MAX_VARIANTS || variants.length * model.species.length > MAX_PANELS) {
1725+ // Snapshotted for the whole study: `refCase` only changes with no study up
1726+ // (clearing is disabled during one, and loading tears it down first).
1727+ // vs-sphere never has one — its "reference" is always the selected
1728+ // geometry, not a file.
1729+ const rc = currentMode === 'vs-sphere' ? null : refCase;
1730+ const cmpModel = rc?.model ?? model;
1731+
1732+ // vs-sphere: exactly two rows — the selected geometry (the reference) and
1733+ // the plain unit sphere — mirroring whatever niter/lmax the Simulate
1734+ // controls have, so geometry is the only thing that differs between them.
1735+ // Every other mode still drives its rows from the chip grid.
1736+ const isVsSphere = currentMode === 'vs-sphere';
1737+ let variants: Variant[];
1738+ let reference: number;
1739+ let geometries: { geometry: MGeometry; geometryParams: Params; geometrySource: string }[] | undefined;
1740+ let renderOnReferenceGeometry: boolean | undefined;
1741+ let rowLabels: string[] | undefined;
1742+ if (isVsSphere) {
1743+ const niter = Number(elNiter.value);
1744+ const lmax = Number(elLmax.value);
1745+ variants = [{ niter, lmax, dtDiv: 1 }, { niter, lmax, dtDiv: 1 }];
1746+ reference = 0;
1747+ const sphereGeom = mGeometryByKey(SPHERE_KEY)!;
1748+ geometries = [
1749+ { geometry, geometryParams: geomParams, geometrySource: geomSource() },
1750+ { geometry: sphereGeom, geometryParams: defaultGeometryParams(sphereGeom), geometrySource: sphereGeom.source },
1751+ ];
1752+ renderOnReferenceGeometry = true;
1753+ rowLabels = [geometry.label, 'unit sphere'];
1754+ } else {
1755+ variants = cmpVariants();
1756+ reference = rc ? 0 : compareRefIndex();
1757+ }
1758+
1759+ const rowCount = variants.length + (rc ? 1 : 0);
1760+ const diffRowCount = rc ? variants.length : Math.max(0, variants.length - 1);
1761+ const panels = (rowCount + diffRowCount) * cmpModel.species.length;
1762+ if (!isVsSphere && (variants.length > MAX_VARIANTS || panels > MAX_PANELS)) {
12911763 return;
12921764 }
12931765 // Take down the single run first: its pump, its scenes, its session. The
@@ -1303,21 +1775,30 @@ async function startCompare(): Promise<void> {
13031775 setCompareUi(true);
13041776
13051777 try {
1778+ // Against a reference file, the problem is the file's — its model,
1779+ // parameters and geometry, from the registry sources (the editor's
1780+ // working copies describe the page's run, not the file's).
13061781 compareRun = await CompareRun.create({
13071782 device,
1308- model,
1309- params,
1310- source: source(),
1311- geometry,
1312- geometryParams: geomParams,
1313- geometrySource: geomSource(),
1783+ model: cmpModel,
1784+ params: rc ? rc.params : params,
1785+ source: rc ? rc.model.source : source(),
1786+ geometry: rc ? rc.geometry : geometry,
1787+ geometryParams: rc ? rc.geometryParams : geomParams,
1788+ geometrySource: rc ? rc.geometry.source : geomSource(),
13141789 variants,
1315- reference: compareRefIndex(),
1790+ reference,
1791+ geometries,
1792+ renderOnReferenceGeometry,
1793+ rowLabels,
1794+ refFile: rc ?? undefined,
1795+ onFinished: () => setRunning(false),
13161796 seed,
1317- lam3: Number(elLam3.value),
1797+ lam3: rc ? undefined : Number(elLam3.value),
13181798 morph,
13191799 colormapName: () => elColormap.value,
13201800 container: elPanels,
1801+ chartContainer: elCmpChart,
13211802 onStatus: (html) => (elStats.innerHTML = html),
13221803 });
13231804 } catch (e) {
@@ -1354,8 +1835,121 @@ async function rebuildCompare(): Promise<void> {
13541835 await startCompare();
13551836 }
13561837
1838+// ------------------------------------------------------ import from reharm
1839+// reharm's "Export to turing-surface" button opens this page with ?import and
1840+// hands the fitted surface over by postMessage — the two apps live on
1841+// different origins, so a message between opener and opened tab is the only
1842+// channel, and structured clone carries the Float32Arrays without encoding.
1843+// Protocol: the opener pings {type:'reharm-import-ping'} until this page
1844+// answers {type:'reharm-import-ready'} (only once boot has a live session to
1845+// swap the surface into), then posts {type:'reharm-geometry', version, lmax,
1846+// mmax, Gx, Gy, Gz, name, provenance}; this page validates, installs it as
1847+// the dropdown's 'imported' entry, and acks. The payload is data, not code:
1848+// three coefficient arrays and label strings, the strings stripped of markup
1849+// before they reach any innerHTML (updateGeomNote).
1850+
1851+/** null until boot resolves; then '' when imports can proceed, or the reason
1852+ * they cannot (no WebGPU). */
1853+let importGate: string | null = null;
1854+
1855+const cleanLabel = (v: unknown, max: number): string =>
1856+ String(v ?? '')
1857+ .replace(/[<>&"'`]/g, ' ')
1858+ .replace(/\s+/g, ' ')
1859+ .trim()
1860+ .slice(0, max);
1861+
1862+/** Validate a handed-over payload into coefficients, or say what is wrong. */
1863+function importedCoeffsOf(d: Record<string, unknown>): ImportedCoeffs | string {
1864+ const version = Number(d.version);
1865+ if (version !== 1) return `unknown import payload version '${String(d.version)}'`;
1866+ const lmax = Number(d.lmax);
1867+ const mmax = Number(d.mmax);
1868+ if (!Number.isInteger(lmax) || lmax < 1 || lmax > 4096) return `bad lmax '${String(d.lmax)}'`;
1869+ if (!Number.isInteger(mmax) || mmax < 0 || mmax > lmax) return `bad mmax '${String(d.mmax)}'`;
1870+ const nlm = nlmCalc(lmax, mmax);
1871+ const arrays: Float32Array[] = [];
1872+ for (const name of ['Gx', 'Gy', 'Gz']) {
1873+ const q = d[name];
1874+ if (!(q instanceof Float32Array)) return `'${name}' is not a Float32Array`;
1875+ if (q.length !== 2 * nlm) return `'${name}' has ${q.length} values, expected 2*nlm = ${2 * nlm}`;
1876+ if (!q.every(Number.isFinite)) return `'${name}' has non-finite values`;
1877+ arrays.push(q);
1878+ }
1879+ return { lmax, mmax, X: arrays[0], Y: arrays[1], Z: arrays[2] };
1880+}
1881+
1882+/** Adopt the surface: it becomes (or replaces) the dropdown's imported entry
1883+ * and is selected. The run also adopts the surface's own band — truncating a
1884+ * fit to a coarser default would silently smooth the shape that was just
1885+ * exported — so the lmax dropdown gains the exact value when it is not a
1886+ * stock one, and a band change goes through the full rebuild (new grid)
1887+ * rather than the in-place swap. */
1888+function installImportedGeometry(g: MGeometry): void {
1889+ importedGeometry = g;
1890+ let opt = elGeometry.querySelector<HTMLOptionElement>(
1891+ `option[value="${IMPORTED_GEOMETRY_KEY}"]`,
1892+ );
1893+ if (!opt) {
1894+ opt = document.createElement('option');
1895+ opt.value = IMPORTED_GEOMETRY_KEY;
1896+ elGeometry.append(opt);
1897+ }
1898+ opt.textContent = g.label;
1899+ elGeometry.value = IMPORTED_GEOMETRY_KEY;
1900+ applyGeometryChoice(IMPORTED_GEOMETRY_KEY);
1901+ const lmax = g.coeffs!.lmax;
1902+ if (Number(elLmax.value) !== lmax) {
1903+ const options = [...elLmax.options];
1904+ if (!options.some((o) => Number(o.value) === lmax)) {
1905+ const o = document.createElement('option');
1906+ o.value = String(lmax);
1907+ o.textContent = String(lmax);
1908+ elLmax.add(o, options.find((x) => Number(x.value) > lmax) ?? null);
1909+ }
1910+ elLmax.value = String(lmax);
1911+ void rebuild();
1912+ } else {
1913+ viewChange = viewChange.then(() => applyGeometry());
1914+ }
1915+}
1916+
1917+window.addEventListener('message', (ev: MessageEvent) => {
1918+ const d = ev.data as Record<string, unknown> | null;
1919+ if (!d || typeof d !== 'object' || typeof d.type !== 'string') return;
1920+ const reply = (msg: Record<string, unknown>): void => {
1921+ (ev.source as Window | null)?.postMessage(msg, { targetOrigin: ev.origin });
1922+ };
1923+ if (d.type === 'reharm-import-ping') {
1924+ // Silence before boot resolves is fine — the opener keeps pinging.
1925+ if (importGate === '') reply({ type: 'reharm-import-ready' });
1926+ else if (importGate) reply({ type: 'reharm-import-error', message: importGate });
1927+ return;
1928+ }
1929+ if (d.type !== 'reharm-geometry') return;
1930+ if (importGate !== '') {
1931+ reply({ type: 'reharm-import-error', message: importGate ?? 'the page is still starting up' });
1932+ return;
1933+ }
1934+ const coeffs = importedCoeffsOf(d);
1935+ if (typeof coeffs === 'string') {
1936+ reply({ type: 'reharm-import-error', message: coeffs });
1937+ return;
1938+ }
1939+ const p = (d.provenance ?? {}) as Record<string, unknown>;
1940+ const name = `imported: ${cleanLabel(d.name, 40) || 'surface'}`;
1941+ const blurb =
1942+ `Handed over by reharm (lmax ${coeffs.lmax}` +
1943+ (p.map ? `, map ${cleanLabel(p.map, 60)}` : '') +
1944+ (p.filter ? `, filter ${cleanLabel(p.filter, 60)}` : '') +
1945+ `).`;
1946+ installImportedGeometry(makeImportedGeometry(name, blurb, coeffs));
1947+ reply({ type: 'reharm-import-ack' });
1948+});
1949+
13571950 // ---------------------------------------------------------------- boot
13581951 async function boot(): Promise<void> {
1952+ enterMode('simulate');
13591953 elModel.value = presets[0].key;
13601954 // The iteration count is one default shared with the benchmark, like the
13611955 // rest of the RunSpec's — take it from there rather than from the markup, so
@@ -1373,6 +1967,8 @@ async function boot(): Promise<void> {
13731967 elErr.textContent =
13741968 `WebGPU is not available (${e instanceof Error ? e.message : e}). ` +
13751969 `Use a WebGPU-capable browser such as Chrome or Edge.`;
1970+ importGate = 'WebGPU is not available in the opened tab';
1971+ announceImportGate();
13761972 return;
13771973 }
13781974 device.lost.then((info) => {
@@ -1381,6 +1977,25 @@ async function boot(): Promise<void> {
13811977 }
13821978 });
13831979 await rebuild();
1980+ // Imports wait for a live run to swap the surface into; a tab opened by
1981+ // reharm's export button (?import) is told without waiting to be pinged.
1982+ importGate = '';
1983+ announceImportGate();
1984+}
1985+
1986+/** Tell the opener that navigated here with ?import how imports stand. Only
1987+ * a signal — no data — so the opener's origin need not be known. */
1988+function announceImportGate(): void {
1989+ if (!window.opener || !new URLSearchParams(location.search).has('import')) return;
1990+ const msg =
1991+ importGate === ''
1992+ ? { type: 'reharm-import-ready' }
1993+ : { type: 'reharm-import-error', message: importGate };
1994+ try {
1995+ (window.opener as Window).postMessage(msg, { targetOrigin: '*' });
1996+ } catch {
1997+ // The opener may already be gone; the ping path covers the rest.
1998+ }
13841999 }
13852000
13862001 void boot();
src/mgpu/digest.tsmodified+13−0View file
@@ -69,6 +69,19 @@ export function relL2(a: ArrayLike<number>, b: ArrayLike<number>): number {
6969 return Math.sqrt(num / Math.max(den, 1e-300));
7070 }
7171
72+/** Relative L-infinity (max-norm) difference of two states of equal length. */
73+export function relLinf(a: ArrayLike<number>, b: ArrayLike<number>): number {
74+ let num = 0;
75+ let den = 0;
76+ for (let i = 0; i < a.length; i++) {
77+ const d = Math.abs(a[i] - b[i]);
78+ if (d > num) num = d;
79+ const bd = Math.abs(b[i]);
80+ if (bd > den) den = bd;
81+ }
82+ return num / Math.max(den, 1e-300);
83+}
84+
7285 export function formatDigest(d: StateDigest): string {
7386 const g = (v: number): string => v.toPrecision(9);
7487 return (
src/mgpu/session.tsmodified+40−7View file
@@ -155,6 +155,7 @@ export class ModelSession {
155155 paramNames: geometryModel.params.map((p) => p.key),
156156 params: geometryParams,
157157 deriv,
158+ coeffs: geometryModel.coeffs,
158159 });
159160 const gpu = await GpuModel.create({
160161 device,
@@ -211,6 +212,7 @@ export class ModelSession {
211212 paramNames: geometryModel.params.map((p) => p.key),
212213 params,
213214 deriv: this.#deriv,
215+ coeffs: geometryModel.coeffs,
214216 });
215217 this.#geometry = next;
216218 this.#geometryModel = geometryModel;
@@ -314,6 +316,23 @@ export class ModelSession {
314316 this.steps = 0;
315317 }
316318
319+ /**
320+ * Push an exact spectral state into the running model, bypassing seeded
321+ * init, and reset model time like seed() does. `gpu.step(0)` flips which
322+ * of the init/step buffer aliases a read resolves to, without otherwise
323+ * touching the state — see GpuModel's `#lastRan`.
324+ */
325+ loadState(coeffs: Record<string, Float32Array>): void {
326+ for (const name of this.model.state) {
327+ const data = coeffs[name];
328+ if (!data) throw new Error(`loadState: missing state '${name}'`);
329+ this.gpu.upload(name, data);
330+ }
331+ this.gpu.step(0);
332+ this.t = 0;
333+ this.steps = 0;
334+ }
335+
317336 /** The model's parameters plus the ones the host owns. */
318337 #mergedParams(): ModelParams {
319338 return { lam3: this.#lam3, ...this.#params };
@@ -381,18 +400,32 @@ export class ModelSession {
381400 }
382401
383402 /**
384- * Read species `k` at render resolution (`viewSht`'s grid). Without
385- * oversampling this is the grid field the .m returned. With oversampling the
386- * spectral state is synthesized on the finer grid instead — the same field,
387- * since the models define each species as synth of its state, evaluated
388- * exactly on more points.
403+ * Read every state species back to the CPU, in the shape `loadState`
404+ * consumes — the capture side of that method's reload, so a caller can
405+ * hold onto the current spectral state and restore it exactly later
406+ * (e.g. a "restart to this run's initial condition" control). One at a
407+ * time, not `Promise.all`: every `read()` copies into the same shared
408+ * readback buffer (`GpuModel#readback`, model.ts:448-452), so two in
409+ * flight at once race `mapAsync` against each other's `unmap`.
410+ */
411+ async readState(): Promise<Record<string, Float32Array>> {
412+ const out: Record<string, Float32Array> = {};
413+ for (const name of this.model.state) out[name] = await this.read(name);
414+ return out;
415+ }
416+
417+ /**
418+ * Read species `k` at render resolution (`viewSht`'s grid): the spectral
419+ * state synthesized there. The models define each species as synth of its
420+ * state, so this is the field the .m returned — evaluated exactly, whatever
421+ * the grid — and it is current however the state last changed, including a
422+ * `loadState`, which runs no kernel that would write the grid-space fields.
389423 */
390424 readSpecies(k: number): Promise<Float32Array> {
391- if (!this.#displaySht) return this.read(this.model.species[k]);
392425 const state = this.model.state[k];
393426 const buf = this.gpu.valueBuffer(state);
394427 if (!buf) throw new Error(`readSpecies: no buffer for state '${state}'`);
395- return this.#displaySht.synthFrom(buf);
428+ return this.viewSht.synthFrom(buf);
396429 }
397430
398431 describe(): { init: string[]; step: string[] } {
src/render/errorChart.tsadded+328−0View file
@@ -0,0 +1,328 @@
1+/**
2+ * Live Δ(t) chart for a comparison study: one canvas, one line per
3+ * (variant, species) pair, sharing a log-scaled y-axis and an x-axis in
4+ * model time `t`. A variant's lines are colored with that variant's own
5+ * accent color (the same color shown on the left edge of its row of
6+ * panels); species are told apart within one color by line style (solid,
7+ * dashed, dotted, …), matched by the legend's dash swatches.
8+ *
9+ * Deliberately dumb — no library, just a canvas redrawn from scratch on every
10+ * push(). History is unbounded (a study is a "does it converge" question, and
11+ * capping the window would hide exactly the slow drift that question is
12+ * about); only the running log-min/max is maintained incrementally so a
13+ * redraw stays O(points on screen), not O(history) beyond what it already
14+ * draws.
15+ */
16+
17+import { fmtValue } from './colorbar.ts';
18+
19+export interface ErrorChartRow {
20+ label: string;
21+ color: string;
22+}
23+
24+/** Floor for the log scale — well below any error this app ever measures,
25+ * just far enough that log10 never sees zero or a negative. */
26+const MIN_LOG_VALUE = 1e-12;
27+
28+/** Canvas line-dash patterns by species index — solid, dashed, dotted,
29+ * repeating for a fourth-plus species (no shipped model has one). Mirrored
30+ * in index.html's `.cmp-chart-dash-{k}` border-style classes for the
31+ * legend swatches. */
32+const DASH_PATTERNS: number[][] = [[], [7, 4], [2, 3]];
33+
34+const MARGIN_LEFT = 44;
35+const MARGIN_BOTTOM = 38;
36+const MARGIN_TOP = 8;
37+const MARGIN_RIGHT = 10;
38+
39+export class ErrorChart {
40+ #container: HTMLElement;
41+ #species: string[];
42+ #rows: ErrorChartRow[];
43+ #canvas: HTMLCanvasElement | null = null;
44+
45+ #ts: number[] = [];
46+ /** #errs[k][i] is one species' one row's history, same length as #ts. */
47+ #errs: number[][][] = [];
48+ /** Running log10 extent across every (species, row) pushed — one shared
49+ * y-axis now, not one per species. */
50+ #minLog = Infinity;
51+ #maxLog = -Infinity;
52+
53+ constructor(container: HTMLElement, species: string[], rows: ErrorChartRow[]) {
54+ this.#container = container;
55+ this.#species = species;
56+ this.#rows = rows;
57+ this.#resetSeries();
58+ this.#build();
59+ }
60+
61+ #resetSeries(): void {
62+ this.#ts = [];
63+ this.#errs = this.#species.map(() => this.#rows.map(() => []));
64+ this.#minLog = Infinity;
65+ this.#maxLog = -Infinity;
66+ }
67+
68+ #build(): void {
69+ this.#container.replaceChildren();
70+ this.#canvas = null;
71+ if (this.#rows.length === 0 || this.#species.length === 0) return;
72+
73+ const legend = document.createElement('div');
74+ legend.className = 'cmp-chart-legend';
75+
76+ const variantGroup = document.createElement('div');
77+ variantGroup.className = 'cmp-chart-legend-group';
78+ for (const r of this.#rows) {
79+ const item = document.createElement('span');
80+ item.className = 'cmp-chart-legend-item';
81+ const swatch = document.createElement('i');
82+ swatch.style.background = r.color;
83+ item.append(swatch, document.createTextNode(r.label));
84+ variantGroup.append(item);
85+ }
86+
87+ const speciesGroup = document.createElement('div');
88+ speciesGroup.className = 'cmp-chart-legend-group cmp-chart-legend-species';
89+ this.#species.forEach((name, k) => {
90+ const item = document.createElement('span');
91+ item.className = 'cmp-chart-legend-item';
92+ const swatch = document.createElement('i');
93+ swatch.className = `cmp-chart-dash cmp-chart-dash-${k % DASH_PATTERNS.length}`;
94+ item.append(swatch, document.createTextNode(name));
95+ speciesGroup.append(item);
96+ });
97+
98+ legend.append(variantGroup, speciesGroup);
99+ this.#container.append(legend);
100+
101+ const canvas = document.createElement('canvas');
102+ canvas.className = 'cmp-chart-canvas';
103+ this.#container.append(canvas);
104+ this.#canvas = canvas;
105+ }
106+
107+ /** One frame's sample: `t` shared by every row, `perRowErr[i][k]` the
108+ * relative-L2 error of row i's species k against the reference. Rows here
109+ * are exactly the ones passed to the constructor, in the same order — the
110+ * reference row is never included (its Δ against itself is always 0). */
111+ push(t: number, perRowErr: number[][]): void {
112+ this.#ts.push(t);
113+ for (let k = 0; k < this.#species.length; k++) {
114+ for (let i = 0; i < this.#rows.length; i++) {
115+ const v = perRowErr[i]?.[k];
116+ this.#errs[k][i].push(v === undefined ? NaN : v);
117+ if (Number.isFinite(v) && v! > 0) {
118+ const lv = Math.log10(v!);
119+ if (lv < this.#minLog) this.#minLog = lv;
120+ if (lv > this.#maxLog) this.#maxLog = lv;
121+ }
122+ }
123+ }
124+ this.#draw();
125+ }
126+
127+ /** Back to no history — called wherever the study's clock itself resets
128+ * (restart, reseed), so the chart never shows a curve spanning a rewind. */
129+ reset(): void {
130+ this.#resetSeries();
131+ this.#draw();
132+ }
133+
134+ /** Redraw with the data as it stands — for a container resize, where
135+ * nothing new has been measured but the canvas backing buffer has to
136+ * change to match. */
137+ redraw(): void {
138+ this.#draw();
139+ }
140+
141+ dispose(): void {
142+ this.#container.replaceChildren();
143+ this.#canvas = null;
144+ }
145+
146+ #draw(): void {
147+ const canvas = this.#canvas;
148+ if (!canvas) return;
149+ const rect = canvas.getBoundingClientRect();
150+ const dpr = window.devicePixelRatio || 1;
151+ const cssW = Math.max(1, rect.width);
152+ const cssH = Math.max(1, rect.height || 240);
153+ const pxW = Math.max(1, Math.round(cssW * dpr));
154+ const pxH = Math.max(1, Math.round(cssH * dpr));
155+ if (canvas.width !== pxW) canvas.width = pxW;
156+ if (canvas.height !== pxH) canvas.height = pxH;
157+ const ctx = canvas.getContext('2d');
158+ if (!ctx) return;
159+ // Draw in CSS-pixel coordinates throughout; the transform alone accounts
160+ // for devicePixelRatio, rather than scaling every margin/font by hand.
161+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
162+ ctx.clearRect(0, 0, cssW, cssH);
163+
164+ const n = this.#ts.length;
165+ if (n < 2) return;
166+
167+ const rawLo = this.#minLog;
168+ const rawHi = this.#maxLog;
169+ if (!Number.isFinite(rawLo) || !Number.isFinite(rawHi)) return;
170+ let lo = rawLo;
171+ let hi = rawHi;
172+ if (hi - lo < 1e-6) {
173+ lo -= 0.5;
174+ hi += 0.5;
175+ }
176+ const pad = (hi - lo) * 0.08;
177+ lo -= pad;
178+ hi += pad;
179+
180+ const style = getComputedStyle(document.documentElement);
181+ const inkColor = style.getPropertyValue('--ink-2').trim() || '#666';
182+ const gridColor = style.getPropertyValue('--line').trim() || '#ccc';
183+
184+ const plotX = MARGIN_LEFT;
185+ const plotY = MARGIN_TOP;
186+ const plotW = Math.max(1, cssW - MARGIN_LEFT - MARGIN_RIGHT);
187+ const plotH = Math.max(1, cssH - MARGIN_TOP - MARGIN_BOTTOM);
188+
189+ const t0 = this.#ts[0];
190+ const t1 = this.#ts[n - 1];
191+ const tSpan = t1 - t0 || 1;
192+ const xAt = (t: number): number => plotX + ((t - t0) / tSpan) * plotW;
193+ const yAt = (v: number): number => {
194+ const lv = Math.max(lo, Math.min(hi, Math.log10(Math.max(v, MIN_LOG_VALUE))));
195+ return plotY + (1 - (lv - lo) / (hi - lo)) * plotH;
196+ };
197+
198+ ctx.font = '11px sans-serif';
199+
200+ // ---- y-axis: decade gridlines + ticks + labels -----------------------
201+ const yTicks = decadeTicks(lo, hi, rawLo, rawHi);
202+ ctx.textAlign = 'right';
203+ ctx.textBaseline = 'middle';
204+ for (const tick of yTicks) {
205+ const y = yAt(tick.value);
206+ ctx.strokeStyle = gridColor;
207+ ctx.globalAlpha = 0.3;
208+ ctx.lineWidth = 1;
209+ ctx.beginPath();
210+ ctx.moveTo(plotX, y);
211+ ctx.lineTo(plotX + plotW, y);
212+ ctx.stroke();
213+ ctx.globalAlpha = 1;
214+ ctx.beginPath();
215+ ctx.moveTo(plotX - 4, y);
216+ ctx.lineTo(plotX, y);
217+ ctx.stroke();
218+ ctx.fillStyle = inkColor;
219+ ctx.fillText(tick.label, plotX - 6, y);
220+ }
221+
222+ // ---- x-axis: ticks + labels --------------------------------------------
223+ const xTicks = evenTicks(t0, t1, 5);
224+ ctx.textAlign = 'center';
225+ ctx.textBaseline = 'top';
226+ ctx.strokeStyle = gridColor;
227+ for (const t of xTicks) {
228+ const x = xAt(t);
229+ ctx.beginPath();
230+ ctx.moveTo(x, plotY + plotH);
231+ ctx.lineTo(x, plotY + plotH + 4);
232+ ctx.stroke();
233+ ctx.fillStyle = inkColor;
234+ ctx.fillText(fmtValue(t), x, plotY + plotH + 6);
235+ }
236+
237+ // ---- axis frame ---------------------------------------------------------
238+ ctx.strokeStyle = gridColor;
239+ ctx.beginPath();
240+ ctx.moveTo(plotX, plotY);
241+ ctx.lineTo(plotX, plotY + plotH);
242+ ctx.lineTo(plotX + plotW, plotY + plotH);
243+ ctx.stroke();
244+
245+ // ---- axis titles ---------------------------------------------------------
246+ ctx.fillStyle = inkColor;
247+ ctx.textAlign = 'center';
248+ ctx.textBaseline = 'bottom';
249+ ctx.fillText('t', plotX + plotW / 2, cssH - 2);
250+
251+ ctx.save();
252+ ctx.translate(12, plotY + plotH / 2);
253+ ctx.rotate(-Math.PI / 2);
254+ ctx.textAlign = 'center';
255+ ctx.textBaseline = 'alphabetic';
256+ ctx.fillText('relative L2 error', 0, 0);
257+ ctx.restore();
258+
259+ // ---- the data: one line per (species, row) -----------------------------
260+ for (let k = 0; k < this.#species.length; k++) {
261+ const dash = DASH_PATTERNS[k % DASH_PATTERNS.length];
262+ for (let i = 0; i < this.#rows.length; i++) {
263+ const series = this.#errs[k][i];
264+ ctx.setLineDash(dash);
265+ ctx.strokeStyle = this.#rows[i].color;
266+ ctx.lineWidth = 1.5;
267+ ctx.beginPath();
268+ let started = false;
269+ for (let j = 0; j < n; j++) {
270+ const v = series[j];
271+ // A non-finite or non-positive sample (a diverged row, or a norm
272+ // with zero denominator) breaks the line rather than drawing a
273+ // spurious segment through a point that has no place on a log axis.
274+ if (!Number.isFinite(v) || v <= 0) {
275+ started = false;
276+ continue;
277+ }
278+ const x = xAt(this.#ts[j]);
279+ const y = yAt(v);
280+ if (started) ctx.lineTo(x, y);
281+ else ctx.moveTo(x, y);
282+ started = true;
283+ }
284+ ctx.stroke();
285+ }
286+ }
287+ ctx.setLineDash([]);
288+ }
289+}
290+
291+/**
292+ * Y-axis ticks: one per decade spanned by [lo, hi] (the padded plotting
293+ * range), labeled `1e{n}`. If the visible range covers less than a full
294+ * decade — a study that hasn't had time to spread out yet — decade ticks
295+ * would give zero or one of them, so fall back to two ticks at the actual
296+ * (unpadded) data extent instead, labeled with their real value.
297+ */
298+function decadeTicks(
299+ lo: number,
300+ hi: number,
301+ rawLo: number,
302+ rawHi: number,
303+): { value: number; label: string }[] {
304+ const start = Math.ceil(lo);
305+ const end = Math.floor(hi);
306+ const decades: number[] = [];
307+ for (let d = start; d <= end; d++) decades.push(d);
308+ if (decades.length >= 2) {
309+ return decades.map((d) => ({
310+ value: 10 ** d,
311+ label: (10 ** d).toExponential(0).replace('e+', 'e'),
312+ }));
313+ }
314+ const loVal = 10 ** rawLo;
315+ const hiVal = 10 ** rawHi;
316+ if (hiVal <= loVal) return [{ value: loVal, label: fmtValue(loVal) }];
317+ return [
318+ { value: loVal, label: fmtValue(loVal) },
319+ { value: hiVal, label: fmtValue(hiVal) },
320+ ];
321+}
322+
323+/** `count` evenly spaced ticks between t0 and t1 inclusive; just t0 if the
324+ * span is degenerate (a single point pushed so far). */
325+function evenTicks(t0: number, t1: number, count: number): number[] {
326+ if (t1 <= t0) return [t0];
327+ return Array.from({ length: count }, (_, i) => t0 + (i * (t1 - t0)) / (count - 1));
328+}
src/sht/layout.tsmodified+27−0View file
@@ -46,6 +46,33 @@ export function isPowerOfTwo(n: number): boolean {
4646 return n > 0 && (n & (n - 1)) === 0;
4747 }
4848
49+/**
50+ * Re-index coefficients from one (lmax, mmax) layout into another, dropping
51+ * the modes the target cannot hold and zero-filling the ones the source does
52+ * not have. Both truncation and padding are exact spectral operations —
53+ * truncation is orthogonal projection onto the smaller band, padding changes
54+ * nothing — so a surface carried as coefficients can be moved onto any plan.
55+ */
56+export function relayoutCoeffs(
57+ q: Float32Array,
58+ from: { lmax: number; mmax: number },
59+ to: { lmax: number; mmax: number },
60+): Float32Array {
61+ if (from.lmax === to.lmax && from.mmax === to.mmax) return q;
62+ const out = new Float32Array(2 * nlmCalc(to.lmax, to.mmax));
63+ const mTop = Math.min(from.mmax, to.mmax);
64+ const lTop = Math.min(from.lmax, to.lmax);
65+ for (let m = 0; m <= mTop; m++) {
66+ for (let l = m; l <= lTop; l++) {
67+ const src = 2 * lmIndex(from.lmax, l, m);
68+ const dst = 2 * lmIndex(to.lmax, l, m);
69+ out[dst] = q[src];
70+ out[dst + 1] = q[src + 1];
71+ }
72+ }
73+ return out;
74+}
75+
4976 /** Grid sizes for a given lmax, dealiased for a reaction of polynomial degree
5077 * `pdeg` (the rule from websph's reference implementation):
5178 * nlat >= ((pdeg+1)*lmax+1)/2, nphi >= (pdeg+1)*lmax+1. nphi is rounded up to
test/compareChecks.tsmodified+67−0View file
@@ -75,6 +75,73 @@ export async function compareChecks(
7575 );
7676 }
7777
78+ // ---- a file's exact state loads onto every grid --------------------------
79+ // What a reference-file study does instead of seeding: the file's spectral
80+ // state pushed into each variant by loadState, prolonged into its band. The
81+ // load is a plain upload, so the state must come back bit-exact; and read on
82+ // one shared grid the variants must then show one field, because synthesis
83+ // of the same band-limited coefficients is evaluation, not resampling.
84+ {
85+ const model = mModelByKey('allencahn')!;
86+ const params = defaultParams(model);
87+ const sessions: ModelSession[] = [];
88+ try {
89+ for (const lmax of [COARSE, FINE]) {
90+ sessions.push(await ModelSession.create({ device, model, params, lmax, niter: 0 }));
91+ }
92+ const [coarse, fine] = sessions;
93+ // A deterministic band-limited state, decaying like a real spectrum;
94+ // m = 0 imaginary parts stay zero (the state is a real field).
95+ const q = new Float32Array(2 * nlmCalc(COARSE, COARSE));
96+ for (let m = 0; m <= COARSE; m++) {
97+ for (let l = m; l <= COARSE; l++) {
98+ const i = 2 * lmIndex(COARSE, l, m);
99+ const amp = Math.exp(-l / 6);
100+ q[i] = amp * Math.sin(1 + 3 * l + 7 * m);
101+ q[i + 1] = m === 0 ? 0 : amp * Math.cos(2 + 5 * l + 11 * m);
102+ }
103+ }
104+ coarse.loadState({ U: q });
105+ fine.loadState({ U: prolongCoeffs(q, COARSE, FINE) });
106+
107+ const back = await coarse.read('U');
108+ let exact = back.length === q.length;
109+ if (exact) {
110+ for (let i = 0; i < q.length; i++) {
111+ if (back[i] !== q[i]) {
112+ exact = false;
113+ break;
114+ }
115+ }
116+ }
117+ check(
118+ 'compare: loadState puts the exact coefficients in the state',
119+ exact,
120+ `${q.length} float32 values round-tripped bit-exact at lmax ${COARSE}`,
121+ );
122+
123+ // The coarse session's own solver grid, so its display plan is the
124+ // solver's — the branch a crowded study lands on.
125+ for (const s of sessions) await s.setDisplayGrid(64, 128);
126+ const cu = await coarse.readSpecies(0);
127+ const fu = await fine.readSpecies(0);
128+ let maxd = 0;
129+ let scale = 0;
130+ for (let i = 0; i < cu.length; i++) {
131+ maxd = Math.max(maxd, Math.abs(cu[i] - fu[i]));
132+ scale = Math.max(scale, Math.abs(cu[i]));
133+ }
134+ check(
135+ 'compare: one loaded state reads back as one field on a shared grid',
136+ maxd < 1e-4 * scale,
137+ `max |du| = ${maxd.toExponential(2)} vs max |u| = ${scale.toExponential(2)} ` +
138+ `across lmax ${COARSE} vs ${FINE}`,
139+ );
140+ } finally {
141+ for (const s of sessions) s.destroy();
142+ }
143+ }
144+
78145 // ---- one random field across lmax: the shipped models' seeding -----------
79146 {
80147 const model = mModelByKey('schnakenberg')!;
test/geometryChecks.tsmodified+129−2View file
@@ -282,6 +282,127 @@ export async function geometryChecks(
282282 sht.destroy();
283283 }
284284
285+ // ---- a surface handed over as coefficients is the same surface -----------
286+ // The import path (reharm's "Export to turing-surface"): Geometry.create
287+ // with `coeffs` set evaluates no .m — the coefficients are re-indexed onto
288+ // the session's band and everything from synthesis onward runs unchanged.
289+ // Checked in all three band relations: same (must reproduce the original
290+ // geometry, arrays and all), wider (zero-padding; the surface must still
291+ // match its closed form on the finer plan's own grid), and narrower
292+ // (truncation; exact when the content fits the smaller band, as the
293+ // degree-1 sphere does).
294+ {
295+ const importGeometry = async (
296+ coeffs: { lmax: number; mmax: number; X: Float32Array; Y: Float32Array; Z: Float32Array },
297+ lmax: number,
298+ ) => {
299+ const { nlat, nphi } = gridForLmax(lmax, 3);
300+ const cfg = { lmax, mmax: lmax, nlat, nphi };
301+ const sht = await ShtPlan.create(device, cfg);
302+ const deriv = await DerivPlan.create(device, sht);
303+ const geometry = await Geometry.create({
304+ sht, cfg, source: '', paramNames: [], params: {}, deriv, coeffs,
305+ });
306+ return { sht, deriv, cfg, geometry };
307+ };
308+
309+ const peanut = await buildGeometry(device, 'peanut');
310+ const coeffs = {
311+ lmax: peanut.cfg.lmax,
312+ mmax: peanut.cfg.mmax,
313+ X: peanut.geometry.X,
314+ Y: peanut.geometry.Y,
315+ Z: peanut.geometry.Z,
316+ };
317+
318+ // Same band: the identical pipeline on identical inputs, so the surface
319+ // and both metric formulations must come back numerically unchanged.
320+ const same = await importGeometry(coeffs, peanut.cfg.lmax);
321+ let worst = 0;
322+ const pairs: [Float32Array, Float32Array][] = [
323+ [same.geometry.x, peanut.geometry.x],
324+ [same.geometry.y, peanut.geometry.y],
325+ [same.geometry.z, peanut.geometry.z],
326+ [same.geometry.p1, peanut.geometry.p1],
327+ [same.geometry.p2, peanut.geometry.p2],
328+ [same.geometry.q2, peanut.geometry.q2],
329+ [same.geometry.r, peanut.geometry.r],
330+ [same.geometry.Vtx, peanut.geometry.Vtx],
331+ [same.geometry.Vpx, peanut.geometry.Vpx],
332+ ];
333+ for (const [a, b] of pairs) {
334+ for (let i = 0; i < a.length; i++) {
335+ worst = Math.max(worst, Math.abs(a[i] - b[i]));
336+ }
337+ }
338+ check(
339+ 'import: coefficients rebuild the identical geometry on the same band',
340+ worst <= 1e-7,
341+ `max |difference| = ${worst.toExponential(2)} over surface and metric`,
342+ );
343+ same.deriv.destroy();
344+ same.sht.destroy();
345+
346+ // Wider band: zero-padded onto a finer plan, then checked against the
347+ // .m's own closed form on that plan's grid — points the original build
348+ // never evaluated (Gauss latitudes do not nest).
349+ const p = defaultGeometryParams(peanut.g);
350+ const peanutRadius = (ct: number): number => {
351+ const st2 = Math.max(0, 1 - ct * ct);
352+ const r = 1 - p.waist * st2;
353+ return r * Math.hypot(Math.sqrt(st2), (1 + p.stretch) * ct);
354+ };
355+ const wide = await importGeometry(coeffs, 2 * peanut.cfg.lmax + 1);
356+ let dr = 0;
357+ for (let i = 0; i < wide.cfg.nlat; i++) {
358+ const want = peanutRadius(wide.sht.cosTheta[i]);
359+ for (let j = 0; j < wide.cfg.nphi; j++) {
360+ const k = i * wide.cfg.nphi + j;
361+ const got = Math.hypot(wide.geometry.x[k], wide.geometry.y[k], wide.geometry.z[k]);
362+ dr = Math.max(dr, Math.abs(got - want));
363+ }
364+ }
365+ check(
366+ 'import: zero-padding onto a wider band keeps the surface',
367+ dr < 1e-3,
368+ `max |dr| = ${dr.toExponential(2)} at lmax ${wide.cfg.lmax}`,
369+ );
370+ wide.deriv.destroy();
371+ wide.sht.destroy();
372+ peanut.deriv.destroy();
373+ peanut.sht.destroy();
374+
375+ // Narrower band: truncation is orthogonal projection, so a surface whose
376+ // content fits the smaller band comes through exactly — the sphere is
377+ // degree 1 and must still have radius 1 after import at any lmax.
378+ const sphere = await buildGeometry(device, SPHERE_KEY);
379+ const narrow = await importGeometry(
380+ {
381+ lmax: sphere.cfg.lmax,
382+ mmax: sphere.cfg.mmax,
383+ X: sphere.geometry.X,
384+ Y: sphere.geometry.Y,
385+ Z: sphere.geometry.Z,
386+ },
387+ Math.floor(sphere.cfg.lmax / 2),
388+ );
389+ let radiusErr = 0;
390+ for (let k = 0; k < narrow.geometry.x.length; k++) {
391+ const r = Math.hypot(narrow.geometry.x[k], narrow.geometry.y[k], narrow.geometry.z[k]);
392+ radiusErr = Math.max(radiusErr, Math.abs(r - 1));
393+ }
394+ check(
395+ 'import: truncation onto a narrower band is exact when the content fits',
396+ radiusErr < 2e-3,
397+ `sphere from lmax ${sphere.cfg.lmax} coefficients at lmax ${narrow.cfg.lmax}: ` +
398+ `max |r - 1| = ${radiusErr.toExponential(2)}`,
399+ );
400+ narrow.deriv.destroy();
401+ narrow.sht.destroy();
402+ sphere.deriv.destroy();
403+ sphere.sht.destroy();
404+ }
405+
285406 // ---- the unrolled loop: more ops, identical answer ----------------------
286407 {
287408 const model = mModelByKey('schnakenberg')!;
@@ -593,8 +714,14 @@ async function randnfun3Checks(
593714 log(` randnfun3: ${nmodes} modes at lambda ${DEFAULT_LAMBDA}, |perturbation| up to ${amp.toExponential(2)}`);
594715 check(
595716 'randnfun3: the GPU sum matches the same modes summed on the CPU',
596- // fp32 over ~1400 terms against f64, on a field of amplitude ~1e-2.
597- maxErr < 2e-6 && amp > 1e-3,
717+ // fp32 over ~1400 terms against f64. What is being bounded is the
718+ // summation floor, and its size is the backend's accumulation order:
719+ // Metal lands at 2.0e-6, SwiftShader at 3.8e-6, so an absolute constant
720+ // tuned on one is a coin flip on the other. Scale it to the field
721+ // instead. The bug this exists to catch -- a mis-indexed read into the
722+ // packed table, which would still look like a smooth random field -- is
723+ // wrong by O(amp), a thousand times over the bound.
724+ maxErr < 1e-3 * amp && amp > 1e-3,
598725 `max |GPU - CPU| = ${maxErr.toExponential(2)}, perturbation amplitude ${amp.toExponential(2)}`,
599726 );
600727 session.destroy();
test/matlabExportChecks.tsadded+134−0View file
@@ -0,0 +1,134 @@
1+/**
2+ * The MATLAB export (src/export/matlabScript.ts) is string assembly, so these
3+ * checks are cheap and need no GPU: every preset x geometry combination must
4+ * generate, the assembled file must keep its local-function namespace free of
5+ * collisions, and the driver's calls must match the signatures the .m files
6+ * declare. Whether the generated MATLAB actually reproduces a run is checked
7+ * against MATLAB itself, not here: a run exported at defaults and executed in
8+ * MATLAB R2026b lands within fp32 accumulation error of the app's own replay
9+ * (relL2 ~1e-7 over 60 steps via `npm run ref`), and the flux and Algorithm-4
10+ * exports track each other to ~3e-10 in f64.
11+ */
12+import { generateMatlabScript, MATLAB_SCRIPT_NAME } from '../src/export/matlabScript.ts';
13+import { presets, mModelByKey } from '../src/mgpu/registry.ts';
14+import { mGeometries } from '../src/geom/registry.ts';
15+import { formatCommand, resolvePreset, DEFAULT_WARMUP } from '../src/bench/runSpec.ts';
16+
17+type Check = (name: string, ok: boolean, detail: string) => void;
18+type Log = (s: string) => void;
19+
20+export function matlabExportChecks(check: Check, log: Log): void {
21+ log('--- MATLAB export ---');
22+ for (const preset of presets) {
23+ const { model, params } = resolvePreset(preset.key);
24+ for (const geometry of mGeometries) {
25+ const geometryParams = Object.fromEntries(
26+ geometry.params.map((p) => [p.key, p.value]),
27+ );
28+ const spec = {
29+ preset: preset.key,
30+ lmax: 63,
31+ seed: 1,
32+ steps: 2000,
33+ warmup: DEFAULT_WARMUP,
34+ params,
35+ geometry: geometry.key,
36+ geometryParams,
37+ niter: 8,
38+ };
39+ const name = `matlab-export ${preset.key} on ${geometry.key}`;
40+ let text: string;
41+ try {
42+ text = generateMatlabScript({
43+ model,
44+ modelSource: model.source,
45+ params,
46+ geometry,
47+ geometrySource: geometry.source,
48+ geometryParams,
49+ lmax: 63,
50+ niter: 8,
51+ lam3: 0.5,
52+ seed: 1,
53+ preset: preset.key,
54+ command: formatCommand(spec),
55+ });
56+ } catch (e) {
57+ check(name, false, e instanceof Error ? e.message : String(e));
58+ continue;
59+ }
60+
61+ // One file, one namespace: every local function name must be unique,
62+ // or MATLAB silently shadows one definition with another.
63+ const fnNames = [...text.matchAll(/^[ \t]*function\s+(?:\[[^\]]*\]|\w+)\s*=\s*(\w+)\s*\(/gm)]
64+ .map((m) => m[1]);
65+ const dupes = fnNames.filter((n, i) => fnNames.indexOf(n) !== i);
66+
67+ // The driver must define what it calls: the state it steps, the model
68+ // call mapped through the mp struct, and the transform setup.
69+ const wants = [
70+ `function ${MATLAB_SCRIPT_NAME}()`,
71+ 'sht_tables(sht_setup(lmax, mmax, nlat, nphi));',
72+ `= init(`,
73+ `= step(${model.state.join(', ')}, `,
74+ 'surface_tables(gxr, gyr, gzr)',
75+ `'/final/${model.state[0]}'`,
76+ ];
77+ const missing = wants.filter((w) => !text.includes(w));
78+
79+ // randnfunsphere rides along exactly when the geometry draws on it.
80+ const wantsSphereTool = /\brandnfunsphere\b/.test(geometry.source);
81+ const carriesSphereTool = /function f = randnfunsphere\(/.test(text);
82+
83+ const problems = [
84+ ...(dupes.length ? [`duplicate local functions: ${[...new Set(dupes)].join(', ')}`] : []),
85+ ...(missing.length ? [`missing: ${missing.join(' | ')}`] : []),
86+ ...(wantsSphereTool !== carriesSphereTool
87+ ? [`randnfunsphere ${wantsSphereTool ? 'missing' : 'included needlessly'}`]
88+ : []),
89+ ];
90+ check(name, problems.length === 0, problems.join('; ') || `${fnNames.length} local functions`);
91+ }
92+ }
93+
94+ // An edited working copy that dropped a required function is refused with a
95+ // message naming the file, not exported broken.
96+ const { model, params } = resolvePreset(presets[0].key);
97+ const geometry = mGeometries[0];
98+ try {
99+ generateMatlabScript({
100+ model,
101+ modelSource: '% nothing here',
102+ params,
103+ geometry,
104+ geometrySource: geometry.source,
105+ geometryParams: {},
106+ lmax: 63,
107+ niter: 8,
108+ lam3: 0.5,
109+ seed: 1,
110+ preset: presets[0].key,
111+ command: '',
112+ });
113+ check('matlab-export refuses a source without init', false, 'no error thrown');
114+ } catch (e) {
115+ const msg = e instanceof Error ? e.message : String(e);
116+ check(
117+ 'matlab-export refuses a source without init',
118+ msg.includes("'init'") && msg.includes(model.key),
119+ msg,
120+ );
121+ }
122+ // Guard the assumption the model registry makes for stateFor: state names
123+ // are used as `<name>0` initial-capture variables, which must not collide
124+ // with the species names.
125+ for (const p of presets) {
126+ const m = mModelByKey(p.modelKey)!;
127+ const all = new Set([...m.state, ...m.species]);
128+ check(
129+ `matlab-export names disjoint for ${m.key}`,
130+ all.size === m.state.length + m.species.length,
131+ [...all].join(', '),
132+ );
133+ }
134+}
test/referenceChecks.tsadded+132−0View file
@@ -0,0 +1,132 @@
1+/**
2+ * The reference-file reader, against a file this test writes itself.
3+ *
4+ * No GPU: this is about the format — that what h5wasm writes in the
5+ * documented layout (docs/ellipsoid-reference-spec.md) comes back through
6+ * `extractReferenceCase` with nothing renamed, rescaled or truncated, and
7+ * that a file the replay could not act on is refused with a message rather
8+ * than half-read. The h5wasm module is injected: the node harness passes
9+ * `h5wasm/node` (real files), the browser harness `h5wasm` (in-memory wasm
10+ * filesystem) — so the browser run also proves the wasm build actually ships.
11+ */
12+import { extractReferenceCase, type H5Node } from '../src/compare/referenceCase.ts';
13+import { nlmCalc } from '../src/sht/layout.ts';
14+
15+type Check = (name: string, ok: boolean, detail: string) => void;
16+type Log = (line: string) => void;
17+
18+/** The slice of h5wasm's writing API these checks touch — the node and
19+ * browser builds both satisfy it structurally. */
20+interface H5Out {
21+ create_group(name: string): H5Out;
22+ create_attribute(name: string, data: unknown): void;
23+ create_dataset(args: { name: string; data: unknown; dtype?: string }): unknown;
24+}
25+export interface H5Rt {
26+ ready: Promise<unknown>;
27+ File: new (path: string, mode?: string) => H5Out & H5Node & { close(): unknown };
28+}
29+
30+const LMAX = 3;
31+const STEPS = 8;
32+
33+export async function referenceChecks(
34+ h5: H5Rt,
35+ /** Where a named scratch file may live: a temp dir on node, '/' in the
36+ * browser's in-memory filesystem. */
37+ pathFor: (name: string) => string,
38+ check: Check,
39+ log: Log,
40+): Promise<void> {
41+ log('\nreference files (HDF5 layout):');
42+ const mod = (await h5.ready) as { FS?: { unlink(path: string): void } };
43+ const nlm = nlmCalc(LMAX, LMAX);
44+ const series = (offset: number): Float32Array =>
45+ Float32Array.from({ length: 2 * nlm }, (_, i) => offset + i / 16);
46+ const arrays = {
47+ Gx: series(100), Gy: series(200), Gz: series(300),
48+ initialU: series(1), finalU: series(2),
49+ };
50+
51+ // ---- write the documented layout, read it back ---------------------------
52+ const goodPath = pathFor('ref-roundtrip.h5');
53+ {
54+ const f = new h5.File(goodPath, 'w');
55+ f.create_attribute('model', 'allencahn');
56+ f.create_attribute('species', ['U']);
57+ const spec = f.create_group('spec');
58+ spec.create_attribute('geometry', 'ellipsoid');
59+ spec.create_attribute('lmax', LMAX);
60+ spec.create_attribute('steps', STEPS);
61+ spec.create_attribute('niter', 2);
62+ spec.create_attribute('seed', 1);
63+ spec.create_attribute('warmup', 0);
64+ const params = spec.create_group('params');
65+ params.create_attribute('dt', 0.0625);
66+ params.create_attribute('eps2', 0.5);
67+ const geomParams = spec.create_group('geometry_params');
68+ geomParams.create_attribute('ax', 2.5);
69+ geomParams.create_attribute('ay', 1.25);
70+ geomParams.create_attribute('az', 0.75);
71+ const geom = f.create_group('geometry');
72+ geom.create_dataset({ name: 'Gx', data: arrays.Gx, dtype: '<f4' });
73+ geom.create_dataset({ name: 'Gy', data: arrays.Gy, dtype: '<f4' });
74+ geom.create_dataset({ name: 'Gz', data: arrays.Gz, dtype: '<f4' });
75+ f.create_group('initial').create_dataset({ name: 'U', data: arrays.initialU, dtype: '<f4' });
76+ f.create_group('final').create_dataset({ name: 'U', data: arrays.finalU, dtype: '<f4' });
77+ f.close();
78+ }
79+ {
80+ const f = new h5.File(goodPath, 'r');
81+ const rc = extractReferenceCase(f, 'ref-roundtrip.h5');
82+ f.close();
83+ mod.FS?.unlink(goodPath);
84+
85+ check(
86+ 'reference: the run identity survives the round trip',
87+ rc.model.key === 'allencahn' && rc.geometry.key === 'ellipsoid' &&
88+ rc.lmax === LMAX && rc.steps === STEPS && rc.niter === 2,
89+ `${rc.model.key} on ${rc.geometry.key}, lmax ${rc.lmax}, ` +
90+ `${rc.steps} steps, niter ${rc.niter}`,
91+ );
92+ check(
93+ 'reference: the file’s parameters override the defaults',
94+ rc.params.dt === 0.0625 && rc.params.eps2 === 0.5 &&
95+ rc.geometryParams.ax === 2.5 && rc.geometryParams.ay === 1.25 &&
96+ rc.geometryParams.az === 0.75,
97+ `dt ${rc.params.dt}, eps2 ${rc.params.eps2}, ` +
98+ `ax/ay/az ${rc.geometryParams.ax}/${rc.geometryParams.ay}/${rc.geometryParams.az}`,
99+ );
100+ const same = (a: Float32Array, b: Float32Array): boolean =>
101+ a.length === b.length && a.every((v, i) => v === b[i]);
102+ check(
103+ 'reference: every coefficient array comes back bit-exact',
104+ same(rc.geometryCoeffs.X, arrays.Gx) && same(rc.geometryCoeffs.Y, arrays.Gy) &&
105+ same(rc.geometryCoeffs.Z, arrays.Gz) && same(rc.initial.U, arrays.initialU) &&
106+ same(rc.final.U, arrays.finalU),
107+ `5 arrays x ${2 * nlm} float32 values`,
108+ );
109+ }
110+
111+ // ---- a file the replay cannot act on is refused, not half-read -----------
112+ {
113+ const badPath = pathFor('ref-unknown-model.h5');
114+ const f = new h5.File(badPath, 'w');
115+ f.create_attribute('model', 'nosuchmodel');
116+ f.close();
117+ const r = new h5.File(badPath, 'r');
118+ let message = '';
119+ try {
120+ extractReferenceCase(r, 'ref-unknown-model.h5');
121+ } catch (e) {
122+ message = e instanceof Error ? e.message : String(e);
123+ }
124+ r.close();
125+ mod.FS?.unlink(badPath);
126+ check(
127+ 'reference: an unknown model is refused with its name',
128+ message.includes('nosuchmodel'),
129+ message || 'no error thrown',
130+ );
131+ }
132+}
test/test-page.tsmodified+6−0View file
@@ -23,12 +23,15 @@ import {
2323 defaultGeometryParams,
2424 DEFAULT_GEOMETRY_KEY,
2525 } from '../src/geom/registry.ts';
26+import * as h5wasm from 'h5wasm';
2627 import { transformChecks } from './transformChecks.ts';
2728 import { analyticChecks } from './analyticChecks.ts';
2829 import { modelChecks } from './modelChecks.ts';
2930 import { geometryChecks } from './geometryChecks.ts';
3031 import { fluxChecks } from './fluxChecks.ts';
3132 import { compareChecks } from './compareChecks.ts';
33+import { referenceChecks, type H5Rt } from './referenceChecks.ts';
34+import { matlabExportChecks } from './matlabExportChecks.ts';
3235
3336 declare global {
3437 interface Window {
@@ -222,6 +225,9 @@ async function main(): Promise<void> {
222225 await geometryChecks(device, check, log, { sweep: q.has('sweep') });
223226 await fluxChecks(device, check, log, { ab: q.has('sweep') });
224227 await compareChecks(device, check, log);
228+ // '/' is the wasm module's in-memory filesystem — nothing touches disk.
229+ await referenceChecks(h5wasm as unknown as H5Rt, (name) => `/${name}`, check, log);
230+ matlabExportChecks(check, log);
225231
226232 window.__RESULTS__ = { ok: failures === 0, lines };
227233 log(failures === 0 ? 'ALL PASS' : `${failures} FAILURE(S)`);