Comparing changes
main is 31 commits ahead of reduced-transforms.
Create pull request
export standalone matlab
Jeremy Magland committed
9b71d5bMerge 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
87ad61eMerge pull request #8 from concept-collection/flux-polar-conditioning
Jeremy Magland committed
7d4ff58Split the flux-form divergence against the round sphere
Dan Fortunato committed
3d078cfMerge main into random-fields
Jeremy Magland committed
beac00aDrop the work-in-progress banner
Dan Fortunato committed
f132fe4Seed runs from smooth random fields, and add the blob geometry
Dan Fortunato committed
0ae15cfMerge pull request #5 from concept-collection/compare-solver-settings
Jeremy Magland committed
f03ab93Changed local node to version 24; updated package-lock.json accordingly
Owen Melia committed
f4de749Do not stretch the colormap across a constant field's roundoff
Jeremy Magland committed
ef3ae33Updated command now tracks L_infty error too.
Owen Melia committed
66ae13eCompare several solver settings side by side, on one clock
Jeremy Magland committed
f467ffaMerge branch 'main' into reference_soln
Owen Melia committed
b460a9fCommand for testing against a reference implementation
Owen Melia committed
90108a6Merge pull request #3 from concept-collection/reduced-transforms
Jeremy Magland committed
ae74084Use numbl main branch instead of a pinned commit in workflows
Jeremy Magland committed
79878d955 changed files+6107−422
.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+188−27View file
@@ -36,10 +36,12 @@ function [gx, gy, gz] = shape(theta, phi, waist, stretch)
3636 end
3737 ```
3838
39-That is ordinary element-wise MATLAB and goes through the same compiler and the
40-same WGSL backend the models do. It is evaluated once on the solver's grid, and
41-then **analysed into coefficients**, which is the form everything downstream
42-uses. Two things follow from going through the coefficients rather than keeping
39+That is ordinary MATLAB. Unlike the models it is not compiled to WGSL: a shape
40+is evaluated exactly once at build time, so it runs through numbl's CPU
41+interpreter instead, in f64, with the full MATLAB subset available — loops,
42+arrays, `min`/`max`, `legendre`, seeded randomness via `rng`/`randn`. The
43+result is then **analysed into coefficients**, which is the form everything
44+downstream uses. Two things follow from going through the coefficients rather than keeping
4345 the pointwise values:
4446
4547 - **It is exactly band-limited at lmax.** The surface has as many derivatives as
@@ -52,10 +54,16 @@ the pointwise values:
5254 That is exact interpolation, not subdivision — the same argument that lets the
5355 species fields be oversampled, and it is checked directly in the tests.
5456
55-Four geometries ship: [sphere](geometries/sphere.m) (the reference case),
57+Five geometries ship: [sphere](geometries/sphere.m) (the reference case),
5658 [ellipsoid](geometries/ellipsoid.m), [peanut](geometries/peanut.m) — a dumbbell
57-whose waist is a saddle — and [bumpy](geometries/bumpy.m). Each is editable in
58-the page, with its own parameters. Changing a shape does not recompile the
59+whose waist is a saddle — [bumpy](geometries/bumpy.m), and one random one:
60+[blob](geometries/blob.m), surfacefun's blob — the sphere warped by a smooth
61+random function built from chebfun's `randnfunsphere` construction (random
62+spherical-harmonic coefficients up to degree ⌊2π/λ⌋, rescaled to [−1, 1]).
63+It is seeded, so the same seed always gives the same shape; `amp` sets how far
64+it departs from the sphere, `λ` how fine its lobes are, and **Re-seed shape**
65+draws another one. Each geometry is
66+editable in the page, with its own parameters. Changing a shape does not recompile the
5967 solver and does not disturb the run: the geometry is data whose shape in the
6068 bindings depends only on the grid, so a swap is sixteen buffer writes and the
6169 pattern carries straight on.
@@ -64,6 +72,104 @@ A **morph** slider blends the drawn surface back to the unit sphere. The
6472 parametrization is the sphere's either way, so sweeping it shows which point
6573 went where.
6674
75+### Seeding, and `tools/`
76+
77+A run starts from the uniform steady state plus a small perturbation, and that
78+perturbation is a *smooth* random field rather than white noise: chebfun's
79+[`randnfun3`](tools/randnfun3.m) on the surface's bounding box, restricted to
80+the surface by evaluating it at the grid points — the way surfacefun seeds a
81+run. Each model's `init` says so itself:
82+
83+```matlab
84+function [U, V, u, v] = init(lam3, gx, gy, gz, a, b)
85+ f = randnfun3(lam3, gx, gy, gz);
86+ ...
87+```
88+
89+A band-limited seed is fully resolved by the grid, where white noise is
90+whatever the grid happened to alias: the tests measure its energy above degree
91+20 at 5e-14 of the total, and the flux-form and Algorithm-4 operators now
92+track each other to 3e-6 through a run instead of 4e-4. The **seed λ** control
93+sets the field's wavelength; smaller means finer features to grow from. It is
94+an *absolute* length in the surface's own units, as in chebfun — not a
95+fraction of the surface's size — so a larger surface draws more modes at the
96+same λ.
97+
98+**λ is useful down to about 2π/lmax, and no further.** A field of wavelength λ
99+on a unit-radius surface carries angular content up to degree ≈ 2π/λ, so at
100+the default lmax 63 the grid holds everything down to λ ≈ 0.1. Past that,
101+`init`'s own `analys` discards what the grid cannot represent, and the seed
102+gets *weaker* rather than finer while costing eight times as much per halving:
103+
104+| λ | 2π/λ | rms of the resolved seed | energy above l=55 | peak degree |
105+|---|---|---|---|---|
106+| 0.5 | 13 | 2.6e-2 | 1e-8 | 8 |
107+| 0.2 | 31 | 2.6e-2 | 1e-8 | 10 |
108+| 0.1 | 63 | 2.4e-2 | 0.10 | 44 |
109+| 0.05 | 126 | 1.5e-2 | 0.20 | 48 |
110+| 0.03 | 209 | 9.6e-3 | 0.27 | 63 |
111+
112+Raising lmax moves that floor down, and the seed really does get finer: at
113+lmax 127 the same λ=0.05 keeps its full amplitude (2.5e-2 against 1.5e-2 at
114+lmax 63) with its peak at degree 79 instead of pinned to the band edge, and
115+λ=0.1 becomes *fully* resolved (2e-8 of its energy in the top decile, against
116+1e-1 at lmax 63 — so even 0.1 is slightly under-resolved on the default grid).
117+
118+Note that lmax cuts both ways: it quadruples npts, so every λ also costs four
119+times as much to sum.
120+
121+**Nothing caps λ but memory and patience.** The mode table grows to whatever
122+is asked for and the only refusal is a table that could not be built at all,
123+reported with the mode count it wanted rather than silently truncated. On a
124+128×256 grid:
125+
126+| λ | modes | seed time |
127+|---|---|---|
128+| 0.05 | 480,431 | 0.26 s |
129+| 0.03 | 2,094,657 | 0.98 s |
130+| 0.02 | 6,882,185 | 3.1 s |
131+| 0.015 | 16,092,829 | 7.4 s |
132+| 0.01 | 53,574,764 | 25.6 s |
133+
134+Being slow is the caller's business; **freezing the browser is not**, and at
135+these times neither half of the work can be left where it was:
136+
137+- The draw is synchronous interpreter time — 13 s at λ=0.01 — which on the
138+ main thread stops the page painting and gets it offered up for killing. It
139+ runs on a worker instead
140+ ([`randnfun3.worker.ts`](src/mgpu/randnfun3.worker.ts)); it touches no GPU
141+ and no DOM, so nothing about it needed that thread. Measured during a seed:
142+ 731 animation frames, no stalled sample.
143+- The GPU sum is split across a fixed 16 dispatches (`randnfun3Chunks`)
144+ accumulating into the same output, and `submitYielding` ends the submission
145+ at each one. A browser's GPU process is shared with compositing, so a single
146+ submission running tens of seconds stops *every* tab painting, and one
147+ dispatch that long risks the watchdog killing the device outright. Slices
148+ past the end of a small table exit immediately, so a coarse λ pays nothing.
149+
150+The device is also asked for the adapter's full storage-buffer limit at
151+creation ([`src/sht/sht.ts`](src/sht/sht.ts)), so a browser's 128 MB default
152+is not what decides how fine λ can be. `seed()` is consequently async.
153+
154+`randnfun3` splits across the CPU/GPU line, and the split is forced rather
155+than chosen. Drawing the modes needs `randn` and a `sqrt(nnz)` normalization,
156+neither of which exists in the compiled WGSL dialect, so the draw is MATLAB in
157+[`tools/randnfun3.m`](tools/randnfun3.m) run by the interpreter — a few
158+thousand coefficients, ~5 ms. Evaluating is `npts × nmodes` (~6e7 terms at the
159+default λ), so that is a WGSL kernel
160+([`src/mgpu/randnfun3.ts`](src/mgpu/randnfun3.ts)) reached as an external
161+operation, the way `synth` is. The coefficient table is filled in behind the
162+call, as `synth` hides its Legendre matrices; λ is not hidden, and the plan
163+records which parameter the `.m` asked with so the host draws from that value.
164+
165+[`tools/`](tools/) is the shared MATLAB every interpreter run can call, by file
166+name, as on MATLAB's path — currently `randnfun3` and
167+[`randnfunsphere`](tools/randnfunsphere.m), which `blob.m` is written on. Both
168+keep their upstream signatures, including options nothing shipped uses yet
169+(`randnfunsphere`'s `'monochromatic'`), because the point of a tool is that a
170+geometry you write next can reach for it. Tools are not available to the
171+models' *step*, which compiles to WGSL where none of this exists.
172+
67173 ## The scheme, and where the geometry enters
68174
69175 It solves the N-species system
@@ -167,15 +273,21 @@ Two formulations ship:
167273
168274 1. **The flux form** (above, all three models): `lap_g u` as the weighted
169275 divergence of two weighted fluxes of the sin-scaled derivatives. The
170- weights `p1, p2, q2, r` are grid arrays precomputed once per surface from
171- the embedding's θ/φ tangents
276+ weights `p2, r, dp1, dq2, jinv` are grid arrays precomputed once per
277+ surface from the embedding's θ/φ tangents
172278 ([`src/geom/metric.ts`](src/geom/metric.ts)), chosen so that **every field
173279 that gets analysed is a smooth function on the sphere** — the property
174280 that makes spherical-harmonic analysis meaningful, and the entire
175- difficulty near the poles. Cost: **5 Legendre transforms** per species
176- per iteration (3 syntheses + 2 analyses; the phi flux never needs the
177- Legendre basis — `dphig` differentiates it on the grid with two FFT
178- stages, masking m past the top-degree filter — and `dthetac`/`dphic`
281+ difficulty near the poles. The divergence is split against the round
282+ sphere: the sphere's share of it is `-jinv .* lap_s(u)`, exact in
283+ spectral space, so `r ~ 1/sin²θ` multiplies only the geometry deviation.
284+ Without that split `r` amplifies the polar round-off of the whole flux
285+ into a static forcing that nucleates a spot at the pole on every seed.
286+ Cost: **6 Legendre transforms** per species per iteration (4 syntheses —
287+ two gradient, one divergence, one for the sphere's `-lam .* u`, which
288+ rides in the gradient's batch — plus 2 analyses; the phi flux never needs
289+ the Legendre basis, `dphig` differentiates it on the grid with two FFT
290+ stages, masking m past the top-degree filter, and `dthetac`/`dphic`
179291 are O(nlm) coefficient shuffles). The derivation, the smoothness
180292 argument and the fp32 error analysis are in
181293 [docs/reduced-transforms.md](docs/reduced-transforms.md).
@@ -222,13 +334,14 @@ Two consequences worth stating:
222334 each loop body assigns before the pass and refuses the ones that escape, so
223335 that case is a compile error rather than a stale read.
224336
225-Unrolling is exactly linear in the trip count: 19 GPU ops per species per
226-iteration (6 transforms, 4 coefficient shuffles, 9 kernels), asserted in the
337+Unrolling is exactly linear in the trip count: 18 GPU ops per species per
338+iteration (7 transforms, 3 coefficient shuffles, 8 kernels), asserted in the
227339 tests.
228340
229341 ## MATLAB, compiled to WebGPU
230342
231-Unchanged from turing-sphere, and it now compiles the geometry files too. numbl
343+Unchanged from turing-sphere. This is the models' path — the geometry files
344+instead run once through numbl's CPU interpreter, as above. numbl
232345 parses and lowers each function for the concrete argument types of the current
233346 grid; its inline pass folds single-use temps back into their consumer, so one
234347 line of MATLAB becomes one expression tree; and this repo emits one WGSL compute
@@ -238,8 +351,8 @@ operations whose type rules numbl learns from a `.mtoc2.js` workspace file, and
238351 which the backend maps onto the spherical-harmonic pipelines. Anything it cannot
239352 express is refused at compile time with a source position.
240353
241-The Schnakenberg step compiles to 51 GPU operations at one solve iteration:
242-16 transforms, 8 coefficient-space shuffles, 25 generated kernels, and 2
354+The Schnakenberg step compiles to 50 GPU operations at one solve iteration:
355+18 transforms, 6 coefficient-space shuffles, 24 generated kernels, and 2
243356 buffer copies feeding the new state back.
244357
245358 **Transforms batch.** The expensive part of every Legendre stage is
@@ -249,7 +362,7 @@ take multiple fields, and a grouped call runs as one batched dispatch: one
249362 walk of the recurrence, one accumulator lane per field —
250363
251364 ```matlab
252-[Ftu, Fpu, Ftv, Fpv] = synth(vtu, vpu, vtv, vpv); % one Legendre dispatch
365+[Ftu, Fpu, Ftv, Fpv, Su, Sv] = synth(vtu, vpu, vtv, vpv, lam .* Fu, lam .* Fv);
253366 ```
254367
255368 The grouping is a promise of independence, never of a lane width: the
@@ -260,7 +373,7 @@ the same source runs anywhere. Ungrouped transforms that happen to sit on
260373 consecutive independent lines are batched the same way. Per-lane arithmetic
261374 is identical to the scalar kernels', so batched and scalar plans produce
262375 bit-identical states, asserted in the tests along with compile-time refusal
263-of a group that drops one of its outputs. All 16 transforms of the step
376+of a group that drops one of its outputs. All 16 Legendre transforms of the step
264377 above land in batches, worth ~25% of the whole step (0.88 vs 1.14 ms/step at
265378 lmax 127, 2 iterations, on bumpy).
266379
@@ -309,12 +422,14 @@ there is no CPU fallback (the f64 CPU transform remains, for tests).
309422 - Spectral layout: SHTNS conventions — orthonormal + Condon–Shortley, complex
310423 coefficients for m ≥ 0, m-major ordering.
311424 - fp32 transforms introduce ~1e-6 relative error per step; for pattern formation
312- from 1e-2 seeded noise this is inconsequential. The geometry goes through one
425+ from a 1e-2 seeded perturbation this is inconsequential. The geometry goes through one
313426 analysis/synthesis round trip and picks up the same round-off: the unit sphere
314427 comes back with radius 1 to ~2e-5 under Dawn, ~4e-4 under SwiftShader.
315-- The shipped geometries are all degree ≤ 5, far below any lmax the app offers,
316- so band-limiting removes nothing from them. A shape you write yourself may not
317- be so lucky — see the note in [`geometries/bumpy.m`](geometries/bumpy.m).
428+- The shipped analytic geometries are all degree ≤ 5, and the random ones stay
429+ near degree 13 at their finest slider settings — far below any lmax the app
430+ offers, so band-limiting removes little to nothing from them. A shape you
431+ write yourself may not be so lucky — see the note in
432+ [`geometries/bumpy.m`](geometries/bumpy.m).
318433
319434 ## Desktop vs browser
320435
@@ -382,6 +497,12 @@ package alone. Its binaries need glibc 2.29+. Other flags: `--steps`,
382497 `--warmup`, `--batch`, `--json`, `--help`; `DAWN_FLAGS='backend=vulkan'`
383498 (`;`-separated) passes Dawn options through.
384499
500+### The same run in MATLAB
501+
502+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.
503+
504+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.
505+
385506 ## Tests
386507
387508 There is no second implementation of the solver to diff against, so the `.m`
@@ -403,9 +524,10 @@ about the round sphere, so all three build on the sphere geometry:
403524 Looser (~4e-3) because fp32 keeps about four digits of a perturbation that
404525 small.
405526
406-[`test/geometryChecks.ts`](test/geometryChecks.ts) — the surface and the loop:
527+[`test/geometryChecks.ts`](test/geometryChecks.ts) — the surface, the loop, and
528+the seed:
407529
408-- every geometry compiles and closes; the sphere has radius 1 everywhere and is
530+- every geometry evaluates and closes; the sphere has radius 1 everywhere and is
409531 **exactly degree 1** in the harmonics, which is what makes the reference case
410532 exact rather than merely accurate;
411533 - the peanut matches its own closed-form radial profile at every grid point, and
@@ -416,7 +538,14 @@ about the round sphere, so all three build on the sphere geometry:
416538 the geometric correction is mathematically zero — the state after 20 steps
417539 stays within fp32 round-off of the 0-iteration one at 1 and 4 iterations;
418540 - a runtime loop bound is refused at compile time;
419-- swapping the surface mid-run leaves the spectral state untouched.
541+- swapping the surface mid-run leaves the spectral state untouched;
542+- the seed field's **WGSL sum matches the same modes summed in f64 on the
543+ CPU** (1.8e-6 over ~1,400 terms) — a kernel misreading the packed mode table
544+ would still produce a smooth random-looking field, which no "looks patterned"
545+ check would catch; the same seed redraws the same field and a different one
546+ does not; the field is band-limited (5e-14 of its energy above degree 20)
547+ with λ setting the scale; and a λ finer than the mode table holds is refused
548+ rather than silently truncated.
420549
421550 [`test/fluxChecks.ts`](test/fluxChecks.ts) — the six-transform flux-form
422551 Laplace-Beltrami scheme
@@ -468,6 +597,38 @@ Other commands:
468597 - `node scripts/check-live.mjs [url]` — smoke-check a deployed URL.
469598 - `test.html?soak=<steps>&lmax=<n>` — solver-only soak with no rendering.
470599
600+### Testing against a reference implementation
601+
602+Reference solutions live in the sibling
603+[turing-surface-test-data](https://github.com/concept-collection/turing-surface-test-data)
604+repo, so an independently-written solver never has to depend on this one.
605+`cases/schnakenberg-ellipsoid.md` there specifies the one case this repo
606+currently ships a reference for;
607+[`docs/ellipsoid-reference-spec.md`](docs/ellipsoid-reference-spec.md)
608+restates it in this repo's own terms.
609+
610+`npm run ref -- --in <file>` (`scripts/ref.ts`) loads a reference file, runs
611+the solver from its exact initial spectral state to the same physical end
612+time, and reports the relative-L2 and relative-L-infinity (max-norm) error
613+against its final state (plus a geometry sanity check). `--niter` overrides
614+the surface-correction iteration count independent of the file, and
615+`--tolerance`/`--tolerance-linf` each independently turn their metric into a
616+pass/fail for CI.
617+
618+The same check runs in the page: **Compare to reference…** picks a `.h5` and
619+opens the comparison in one step — the file's own settings (its recorded
620+niter, its band, its dt) as the single variant, paused at the file's exact
621+initial state, ready to Run. The file defines the whole problem — model,
622+parameters, geometry, initial state — and the run stops at the file's end
623+time, measured against one extra static row showing its final state on its
624+own surface. Watching *where* a variant leaves the reference (rather than
625+just reading one number per run) is the point. To widen the study, stop
626+comparing, pick more chips, and press Compare — the file stays loaded, with
627+the lmax choices floored at its band, since a narrower one could not hold
628+its initial state. Reading the file uses
629+[h5wasm](https://github.com/usnistgov/h5wasm)'s wasm build, loaded lazily on
630+the first file opened.
631+
471632 ## Development
472633
473634 ```
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.
docs/reduced-transforms.mdmodified+42−8View file
@@ -2,7 +2,8 @@
22
33 **Summary.** Algorithm 4 costs 12 transforms per matvec (8 syntheses, 4 analyses). A flux-form
44 reformulation, with weights chosen so that every analyzed field is smooth on $S^2$, evaluates the
5-same operator in **6 transforms** (4 syntheses, 2 analyses). Notation follows `algos.pdf`.
5+same operator in **6 transforms** (4 syntheses, 2 analyses), or **7** with the divergence split
6+against the round sphere that §5 turned out to require. Notation follows `algos.pdf`.
67
78 ---
89
@@ -167,14 +168,47 @@ every node alike, multiplying by $r \sim L^2$ recovers the signal and inflates t
167168 | Algorithm 4 | $\sin\theta$, $\sin\theta$ | separated by $\mathcal{A}$ | $\varepsilon L$ |
168169 | Six-transform | $\sin^2\theta$ | all at the end | $\varepsilon L^2$ |
169170
170-**This likely does not reach the returned coefficients.** Step 7's analysis suppresses the spike
171-exactly as line 5 does today: $L^{-2}\cdot L^{1/2}\cdot\varepsilon L^2 = \varepsilon L^{1/2}$,
172-comparable to the ordinary $\varepsilon\sqrt{L}$ accumulation of a transform pair — and the new
173-scheme runs half as many transforms, lowering that baseline. Inside the implicit solve, GMRES sees
174-only coefficients, so the extra power should be invisible.
171+**It does reach the returned coefficients, and it matters.** The suppression argument above is
172+right as far as it goes — step 7's analysis knocks the spike down to $\varepsilon L^{1/2}$, and this
173+document originally concluded from that the extra power would be invisible inside the solve. It is
174+not, and the reason is not about accuracy. Measured on the default ellipsoid at $L=63$: starting
175+from the exact uniform steady state, three Richardson iterations per step leave a standing
176+coefficient-space perturbation $50\times$ the no-correction floor ($1.4\times10^{-5}$ vs
177+$2.8\times10^{-7}$), against $\sim\!1\times$ for Algorithm 4. That perturbation is static, polar,
178+and re-injected every step. In a Turing problem the pattern is seeded by whatever is largest in the
179+unstable band, so a forcing four orders below the field selects the nucleation site: the run grows a
180+spot at the pole, on every seed, regardless of the initial condition.
181+
182+**The fix is to keep $r$ off the round sphere.** Write $p_1 = 1 + \delta p_1$, $q_2 = 1 + \delta q_2$
183+($p_2$ is already zero on the sphere). The sphere's share of the divergence is the cancelling part,
184+and it is known in closed form: $\sin\theta\,\partial_\theta A + \partial_\varphi B =
185+-\sin^2\theta\,\Delta_{S^2}u$, and $\Delta_{S^2}$ is diagonal. So
186+
187+$$\Delta_\Gamma u = -\frac{1}{J}\,\Delta_{S^2}u \;+\; r\,(\sin\theta\,\partial_\theta P'
188+ + \partial_\varphi \tilde{Q}'), \qquad P' = \delta p_1 A + p_2 B, \quad
189+ \tilde{Q}' = p_2 A + \delta q_2 B$$
190+
191+with $1/J = r\sin^2\theta$ bounded. Only the geometry *deviation* now meets the concentrated
192+division. Cost: one extra synthesis per species per iteration for $-\lambda u$ — 7 transforms, not
193+6 — which batches into the gradient's existing grouped call and measures at ~10% of a step, against
194+$3\times$ for reverting to Algorithm 4. $\delta p_1$ and $\delta q_2$ must be formed in float64 at
195+precompute time (`src/geom/geometry.ts`): on a near-sphere they *are* the small quantity, and
196+subtracting 1 in float32 on device would lose them.
197+
198+Measured against Algorithm 4 through a real run (relative $L^2$ of $u$ at $t=8$, $\texttt{niter}=6$):
199+
200+| | plain flux | sphere-split |
201+|---|---|---|
202+| ellipsoid, $L=63$ | $3.5\times10^{-4}$ | $8.9\times10^{-6}$ |
203+| blob, $L=63$ | $4.4\times10^{-4}$ | $8.5\times10^{-6}$ |
204+| ellipsoid, $L=127$ | $7.2\times10^{-3}$ | $6.0\times10^{-6}$ |
205+
206+and the polar noise gain is asserted in `test/fluxChecks.ts`, which fails at $50\times$ on the
207+unsplit form.
175208
176-It matters only if grid values of $\Delta_\Gamma u$ are consumed directly: a nonlinear reaction
177-term, max-norm diagnostics, or an adaptive error estimator.
209+The residual $\varepsilon L^2$ still applies to grid values of $\Delta_\Gamma u$ consumed directly
210+— a nonlinear reaction term, max-norm diagnostics, an adaptive error estimator — for the deviation
211+part alone.
178212
179213 Algorithm 1 line 7 already divides by $\sin^2\theta$, so the code is exposed to $\varepsilon L^2$
180214 today — just on the second-derivative path, which the Laplacian never touches.
geometries/blob.madded+19−0View file
@@ -0,0 +1,19 @@
1+% A random blob: the sphere, radius-modulated by a smooth random function
2+% on the sphere — surfacefun's blob, built on chebfun's randnfunsphere
3+% (tools/randnfunsphere.m).
4+%
5+% `seed` picks the draw; the same seed always gives the same blob. `scale`
6+% is the random function's wavelength, so smaller means finer lobes.
7+
8+function [gx, gy, gz] = shape(theta, phi, amp, scale, seed)
9+ rng(seed);
10+ f = randnfunsphere(scale, theta, phi);
11+ % blob.m's normalization: shift nonnegative, rescale to [-1, 1].
12+ f = f + abs(min(f));
13+ f = 2*(f/max(f)) - 1;
14+ r = 1 + amp*f;
15+ st = sin(theta);
16+ gx = r .* (st .* cos(phi));
17+ gy = r .* (st .* sin(phi));
18+ gz = r .* cos(theta);
19+end
geometries/sphere.mmodified+5−3View file
@@ -1,9 +1,11 @@
11 % The unit sphere — the reference case.
22 %
33 % A geometry file defines shape(theta, phi, ...) -> gx, gy, gz: the surface
4-% over the solver's grid (all npts x 1), compiled to WebGPU like the models.
5-% The host analyses the result into spherical-harmonic coefficients,
6-% band-limited at lmax.
4+% over the solver's grid (all npts x 1). Unlike the models it runs once, on
5+% the CPU through numbl's interpreter, so the full MATLAB subset is
6+% available — loops, arrays, min/max, legendre, seeded randomness via
7+% rng/randn. The host analyses the result into spherical-harmonic
8+% coefficients, band-limited at lmax.
79
810 function [gx, gy, gz] = shape(theta, phi)
911 st = sin(theta);
index.htmlmodified+189−64View file
@@ -18,9 +18,6 @@
1818 --tok-num: #0550ae;
1919 --tok-kw: #cf222e;
2020 --tok-ext: #8250df;
21- --warn-bg: #fff8e5;
22- --warn-line: #e3c37a;
23- --warn-edge: #bf8700;
2421 color-scheme: light dark;
2522 }
2623 @media (prefers-color-scheme: dark) {
@@ -36,9 +33,6 @@
3633 --tok-num: #79c0ff;
3734 --tok-kw: #ff7b72;
3835 --tok-ext: #d2a8ff;
39- --warn-bg: #2b2410;
40- --warn-line: #6b5518;
41- --warn-edge: #e3b341;
4236 }
4337 }
4438 body {
@@ -57,6 +51,19 @@
5751 }
5852 /* display:flex above would otherwise override the UA's [hidden] rule */
5953 .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; }
6067 .controls label { color: var(--ink-2); font-size: 13px; white-space: nowrap; }
6168 select, input[type="number"], button {
6269 font: inherit; font-size: 13px;
@@ -110,18 +117,15 @@
110117 font: 12px/1.6 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
111118 color: var(--ink); user-select: all;
112119 }
113- #blurb { margin-top: 4px; font-size: 13px; color: var(--ink-2); }
114- .warn {
115- margin: 0 0 14px;
116- padding: 10px 14px;
117- border: 1px solid var(--warn-line);
118- border-left: 5px solid var(--warn-edge);
119- border-radius: 6px;
120- background: var(--warn-bg);
121- color: var(--ink);
122- font-size: 13.5px; line-height: 1.5;
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;
123127 }
124- .warn b { color: var(--warn-edge); }
128+ #blurb { margin-top: 4px; font-size: 13px; color: var(--ink-2); }
125129 #err { color: #b35900; white-space: pre-wrap; font-size: 13px; }
126130 .editor {
127131 margin-top: 12px; border: 1px solid var(--line); border-radius: 8px;
@@ -133,10 +137,14 @@
133137 background: var(--sphere-bg); border-bottom: 1px solid var(--line);
134138 }
135139 .editor-head button { padding: 2px 10px; font-size: 12px; }
136- /* Source and compiled-op list side by side, so the editor gets the
137- height rather than sharing it with the list below. */
138- .editor-body { display: flex; align-items: stretch; }
139- .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; }
140148 /* The overlay and the textarea must agree on every metric that affects
141149 where a character lands. Keep these two rules together. */
142150 .editor-code > pre,
@@ -167,10 +175,69 @@
167175 color: var(--ink-2); white-space: pre;
168176 }
169177 @media (max-width: 860px) {
170- .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; }
171181 .editor-code { flex: none; height: 26em; }
172182 #compiled { border-left: 0; border-top: 1px solid var(--line); max-height: 12em; }
173183 }
184+ /* ---- compare mode ------------------------------------------------ */
185+ /* The bar's own layout: three chip rows stacked, then the reference
186+ picker and the button beside them. */
187+ .cmp-axes { display: flex; flex-direction: column; gap: 4px; }
188+ .cmp-axis { display: flex; align-items: center; gap: 8px; }
189+ .cmp-axis > span:first-child {
190+ color: var(--ink-2); font-size: 13px; width: 5.5em; text-align: right;
191+ }
192+ .chips { display: flex; flex-wrap: wrap; gap: 4px; }
193+ .chip {
194+ font: inherit; font-size: 12px; padding: 2px 8px;
195+ border: 1px solid var(--line); border-radius: 999px;
196+ background: var(--bg); color: var(--ink-2); cursor: pointer;
197+ }
198+ .chip:hover { border-color: var(--accent); }
199+ .chip[aria-pressed="true"] {
200+ border-color: var(--accent); color: var(--accent);
201+ background: color-mix(in srgb, var(--accent) 12%, transparent);
202+ font-weight: 600;
203+ }
204+ /* The panel area becomes a stack of labelled rows. Overrides the flex
205+ wrap the single-run view uses. */
206+ #panels.compare { flex-direction: column; gap: 8px; }
207+ .cmp-row { display: flex; align-items: stretch; gap: 8px; }
208+ .cmp-rowlabel {
209+ flex: none; width: 13em; padding: 6px 8px;
210+ border-left: 4px solid var(--c, var(--line));
211+ font-size: 12px; color: var(--ink-2);
212+ display: flex; flex-direction: column; justify-content: center; gap: 3px;
213+ }
214+ .cmp-rowname { color: var(--ink); font-weight: 600; }
215+ .cmp-rowstat { font-variant-numeric: tabular-nums; line-height: 1.35; }
216+ .cmp-diverged { color: var(--warn-edge); }
217+ /* The header row's label cell is a spacer, not a variant — no swatch. */
218+ .cmp-head .cmp-rowlabel { border-left-color: transparent; padding: 0 8px; }
219+ .cmp-cols { flex: 1; display: flex; gap: 8px; min-width: 0; }
220+ .cmp-box {
221+ flex: 1 1 0; min-width: 0;
222+ border: 1px solid var(--line); border-radius: 8px; overflow: hidden;
223+ max-height: 42vh;
224+ }
225+ .cmp-head { align-items: flex-end; }
226+ .cmp-colhead {
227+ flex: 1 1 0; min-width: 0;
228+ display: flex; align-items: center; gap: 8px;
229+ font-size: 12px; color: var(--ink-2);
230+ }
231+ .cmp-rangebar {
232+ flex: 1 1 auto; min-width: 0; height: 8px;
233+ border: 1px solid var(--line); border-radius: 2px;
234+ }
235+ .cmp-rangelab { font-variant-numeric: tabular-nums; white-space: nowrap; }
236+ @media (max-width: 860px) {
237+ .cmp-row { flex-direction: column; }
238+ .cmp-rowlabel { width: auto; flex-direction: row; gap: 10px; }
239+ .cmp-head { display: none; }
240+ }
174241 .tok-com { color: var(--tok-com); }
175242 .tok-str { color: var(--tok-str); }
176243 .tok-num { color: var(--tok-num); }
@@ -181,36 +248,69 @@
181248 <body>
182249 <main>
183250 <h1>turing-surface</h1>
184- <p class="warn">
185- <b>⚠ Work in progress: the geometry is drawn, not solved on.</b>
186- The solver still uses the round sphere's Laplace–Beltrami operator, so
187- on other shapes you see the sphere's pattern painted onto that surface.
188- </p>
189251 <p class="sub">
190252 Reaction-diffusion on closed surfaces, solved live with spherical
191253 harmonics on WebGPU via
192254 <a href="https://github.com/concept-collection/shtns-webgpu">shtns-webgpu</a>.
193- Both the solver and the shape are the MATLAB below, compiled in your
255+ Both the solver and the shape are the MATLAB below, run in your
194256 browser by <a href="https://numbl.org">numbl</a>. Edit either and watch
195257 it change. Drag to rotate.
196258 </p>
197- <div class="controls">
198- <label>preset
259+ <div class="modes" id="modebar">
260+ <button type="button" class="chip" id="mode-simulate" aria-pressed="true">Simulate</button>
261+ <button type="button" class="chip" id="mode-effort"
262+ title="Run several solver settings side by side on one clock">Compare computational effort</button>
263+ <button type="button" class="chip" id="mode-vs-sphere" disabled title="Coming soon">Compare against sphere (Coming soon)</button>
264+ <button type="button" class="chip" id="mode-vs-upload"
265+ title="Check this solver against a saved reference run">
266+ Compare against uploaded data</button>
267+ <input type="file" id="cmp-file" accept=".h5" hidden>
268+ </div>
269+ <p class="mode-desc" id="mode-desc"></p>
270+ <div class="controls ctrl-group" data-group="surface">
271+ <label>reaction-diffusion model
199272 <select id="model"></select>
200273 </label>
201- <label title="The surface. Rendered, but not yet in the operator.">geometry
274+ <label title="The surface the pattern is solved on. Swapping it does not recompile the solver or restart the run.">geometry
202275 <select id="geometry"></select>
203276 </label>
204- <label title="Blend between the sphere (0) and the surface (1). Display only.">morph
205- <input type="range" id="morph" min="0" max="1" step="0.01" value="1" />
277+ </div>
278+ <div class="ctrl-group" data-group="surface-params">
279+ <div class="controls" id="params"></div>
280+ <div class="controls" id="geomparams"></div>
281+ </div>
282+ <div class="controls" id="comparebar" hidden>
283+ <div class="cmp-axes">
284+ <div class="cmp-axis">
285+ <span title="Iterations of the implicit diffusion solve">solve iters</span>
286+ <span id="cmp-niter" class="chips"></span>
287+ </div>
288+ <div class="cmp-axis">
289+ <span>lmax</span>
290+ <span id="cmp-lmax" class="chips"></span>
291+ </div>
292+ <div class="cmp-axis">
293+ <span title="Timestep, as a divisor of the model's dt. Divisors keep every variant on the same clock exactly.">dt</span>
294+ <span id="cmp-dt" class="chips"></span>
295+ </div>
296+ </div>
297+ <label title="The run everything else is measured against">reference
298+ <select id="cmp-ref"></select>
206299 </label>
300+ <span id="cmp-fileinfo" class="stats" hidden></span>
301+ <button id="cmp-fileclear" hidden
302+ title="Drop the reference file and compare the variants against each other again">×</button>
303+ <button id="cmp-start" class="primary">Compile comparison</button>
304+ <span id="cmp-count" class="stats"></span>
305+ </div>
306+ <div class="controls ctrl-group" data-group="solver">
207307 <label title="Iterations of the implicit diffusion solve. Changing it recompiles.">solve iters
208308 <select id="niter">
209309 <option value="0">0</option>
210- <option value="1" selected>1</option>
310+ <option value="1">1</option>
211311 <option value="2">2</option>
212312 <option value="4">4</option>
213- <option value="8">8</option>
313+ <option value="8" selected>8</option>
214314 <option value="16">16</option>
215315 <option value="32">32</option>
216316 <option value="64">64</option>
@@ -225,6 +325,8 @@
225325 <option value="255">255</option>
226326 </select>
227327 </label>
328+ </div>
329+ <div class="controls ctrl-group" data-group="display">
228330 <label title="Render on a finer grid. Display only.">display oversampling
229331 <select id="oversample">
230332 <option value="auto" selected>auto</option>
@@ -237,40 +339,53 @@
237339 <label>colormap
238340 <select id="colormap"></select>
239341 </label>
342+ <label title="Blend between the sphere (0) and the surface (1). Display only.">morph
343+ <input type="range" id="morph" min="0" max="1" step="0.01" value="1" />
344+ </label>
345+ <button id="resetview">Reset view</button>
346+ </div>
347+ <div class="controls ctrl-group" data-group="playback">
240348 <button id="runpause" class="primary">Run</button>
349+ <button id="restart" title="Rewind to the initial condition this run started from, without drawing a new one">Restart</button>
350+ </div>
351+ <div class="controls ctrl-group" data-group="benchmark">
241352 <button id="benchmark">Benchmark</button>
242- <button id="reseed">Re-seed</button>
243- <button id="resetview">Reset view</button>
244- <button id="movietoggle" title="Export the run as an MP4 movie">Export movie</button>
245353 </div>
246- <div class="controls" id="moviebar" hidden>
247- <label title="Simulation-time units per second of video">movie speed
248- <select id="moviespeed">
249- <option value="0.1">0.1×</option>
250- <option value="0.5">0.5×</option>
251- <option value="1">1×</option>
252- <option value="3">3×</option>
253- <option value="5">5×</option>
254- <option value="10" selected>10×</option>
255- <option value="20">20×</option>
256- </select>
257- </label>
258- <label title="Size of each sphere panel in the video, in pixels">resolution
259- <select id="movieres">
260- <option value="480">480</option>
261- <option value="640">640</option>
262- <option value="768" selected>768</option>
263- <option value="1080">1080</option>
264- <option value="1440">1440</option>
265- </select>
266- </label>
267- <label title="Slowly orbit the camera during the movie">
268- <input type="checkbox" id="movierotate" checked /> auto-rotate
354+ <div class="controls ctrl-group" data-group="seed">
355+ <label title="Wavelength of the smooth random field generating the initial condition">Initial condition wavelength λ
356+ <input id="lam3" type="number" min="0" step="0.05" value="0.5">
269357 </label>
270- <button id="movie" title="Replay the run from t = 0 and download an MP4">Export</button>
358+ <button id="reseed">Re-seed</button>
359+ </div>
360+ <div class="controls ctrl-group" data-group="movie">
361+ <button id="movietoggle" title="Export the run as an MP4 movie">Export movie</button>
362+ <div class="controls" id="moviebar" hidden>
363+ <label title="Simulation-time units per second of video">movie speed
364+ <select id="moviespeed">
365+ <option value="0.1">0.1×</option>
366+ <option value="0.5">0.5×</option>
367+ <option value="1">1×</option>
368+ <option value="3">3×</option>
369+ <option value="5">5×</option>
370+ <option value="10" selected>10×</option>
371+ <option value="20">20×</option>
372+ </select>
373+ </label>
374+ <label title="Size of each sphere panel in the video, in pixels">resolution
375+ <select id="movieres">
376+ <option value="480">480</option>
377+ <option value="640">640</option>
378+ <option value="768" selected>768</option>
379+ <option value="1080">1080</option>
380+ <option value="1440">1440</option>
381+ </select>
382+ </label>
383+ <label title="Slowly orbit the camera during the movie">
384+ <input type="checkbox" id="movierotate" checked /> auto-rotate
385+ </label>
386+ <button id="movie" title="Replay the run from t = 0 and download an MP4">Export</button>
387+ </div>
271388 </div>
272- <div class="controls" id="params"></div>
273- <div class="controls" id="geomparams"></div>
274389 <p id="geomnote" class="stats"></p>
275390 <div id="panels"></div>
276391 <p class="stats" id="stats"></p>
@@ -307,6 +422,16 @@
307422 </div>
308423 <code id="cmd"></code>
309424 </div>
425+ <details class="cli" id="matlab">
426+ <summary class="cli-head">
427+ <span>The same run as a standalone MATLAB script</span>
428+ <span>
429+ <button id="copymatlab" type="button">Copy</button>
430+ <button id="downloadmatlab" type="button">Download .m</button>
431+ </span>
432+ </summary>
433+ <pre id="matlabscript"></pre>
434+ </details>
310435 <p id="blurb"></p>
311436 <p id="err"></p>
312437 </main>
models/allencahn.mmodified+9−8View file
@@ -2,14 +2,15 @@
22 %
33 % du/dt = eps2*lap_g(u) + u - u^3
44 %
5-% Same scheme as models/schnakenberg.m.
5+% Same scheme as models/schnakenberg.m, sphere-split flux divergence included.
66
7-function [U, u] = init(noise)
8- U = analys(noise);
7+% Seeded from a smooth random field -- see models/schnakenberg.m.
8+function [U, u] = init(lam3, gx, gy, gz)
9+ U = analys(0.01 * randnfun3(lam3, gx, gy, gz));
910 u = synth(U);
1011 end
1112
12-function [Un, u] = step(U, lam, filt, gx, gy, gz, p1, p2, q2, r, jhat, eps2, dt, niter)
13+function [Un, u] = step(U, lam, filt, gx, gy, gz, p2, r, dp1, dq2, jinv, jhat, eps2, dt, niter)
1314 u = synth(U);
1415
1516 Bu = U + dt * analys(u - u.^3);
@@ -26,15 +27,15 @@ function [Un, u] = step(U, lam, filt, gx, gy, gz, p1, p2, q2, r, jhat, eps2, dt,
2627 Fu = Un .* filt;
2728 vtu = dthetac(Fu);
2829 vpu = dphic(Fu);
29- [Ftu, Fpu] = synth(vtu, vpu);
30- Pu = p1 .* Ftu + p2 .* Fpu;
31- Qu = p2 .* Ftu + q2 .* Fpu;
30+ [Ftu, Fpu, Su] = synth(vtu, vpu, lam .* Fu);
31+ Pu = dp1 .* Ftu + p2 .* Fpu;
32+ Qu = p2 .* Ftu + dq2 .* Fpu;
3233 PAu = analys(Pu);
3334 Pcu = PAu .* filt;
3435 scu = dthetac(Pcu);
3536 Lu = synth(scu);
3637 dQu = dphig(Qu);
37- lapu = r .* (Lu + dQu);
38+ lapu = r .* (Lu + dQu) - jinv .* Su;
3839 dLu = (analys(lapu) + lamJ .* Un) .* filt;
3940
4041 Un = (Bu + (dt * eps2) * dLu) ./ (1 + (dt * eps2) * lamJ);
models/brusselator.mmodified+15−11View file
@@ -4,14 +4,18 @@
44 % dv/dt = D2*lap_g(v) + B*u - u^2*v
55 %
66 % Same scheme as models/schnakenberg.m, including the grouped transforms:
7-% [a, b] = synth(x, y) runs the group as batched Legendre dispatches.
7+% [a, b] = synth(x, y) runs the group as batched Legendre dispatches, and the
8+% sphere-split flux divergence that keeps r ~ 1/sin^2(theta) off the round
9+% sphere's share of the operator.
810
9-function [U, V, u, v] = init(noise, A, B)
10- [U, V] = analys(A + noise, (B / A) * ones(numel(noise), 1));
11+% Seeded from a smooth random field -- see models/schnakenberg.m.
12+function [U, V, u, v] = init(lam3, gx, gy, gz, A, B)
13+ f = randnfun3(lam3, gx, gy, gz);
14+ [U, V] = analys(A + 0.01*f, (B / A) * ones(numel(f), 1));
1115 [u, v] = synth(U, V);
1216 end
1317
14-function [Un, Vn, u, v] = step(U, V, lam, filt, gx, gy, gz, p1, p2, q2, r, jhat, A, B, D1, D2, dt, niter)
18+function [Un, Vn, u, v] = step(U, V, lam, filt, gx, gy, gz, p2, r, dp1, dq2, jinv, jhat, A, B, D1, D2, dt, niter)
1519 [u, v] = synth(U, V);
1620 uuv = u .* u .* v;
1721
@@ -36,11 +40,11 @@ function [Un, Vn, u, v] = step(U, V, lam, filt, gx, gy, gz, p1, p2, q2, r, jhat,
3640 vpu = dphic(Fu);
3741 vtv = dthetac(Fv);
3842 vpv = dphic(Fv);
39- [Ftu, Fpu, Ftv, Fpv] = synth(vtu, vpu, vtv, vpv);
40- Pu = p1 .* Ftu + p2 .* Fpu;
41- Qu = p2 .* Ftu + q2 .* Fpu;
42- Pv = p1 .* Ftv + p2 .* Fpv;
43- Qv = p2 .* Ftv + q2 .* Fpv;
43+ [Ftu, Fpu, Ftv, Fpv, Su, Sv] = synth(vtu, vpu, vtv, vpv, lam .* Fu, lam .* Fv);
44+ Pu = dp1 .* Ftu + p2 .* Fpu;
45+ Qu = p2 .* Ftu + dq2 .* Fpu;
46+ Pv = dp1 .* Ftv + p2 .* Fpv;
47+ Qv = p2 .* Ftv + dq2 .* Fpv;
4448 [PAu, PAv] = analys(Pu, Pv);
4549 Pcu = PAu .* filt;
4650 Pcv = PAv .* filt;
@@ -49,8 +53,8 @@ function [Un, Vn, u, v] = step(U, V, lam, filt, gx, gy, gz, p1, p2, q2, r, jhat,
4953 [Lu, Lv] = synth(scu, scv);
5054 dQu = dphig(Qu);
5155 dQv = dphig(Qv);
52- lapu = r .* (Lu + dQu);
53- lapv = r .* (Lv + dQv);
56+ lapu = r .* (Lu + dQu) - jinv .* Su;
57+ lapv = r .* (Lv + dQv) - jinv .* Sv;
5458 [LAu, LAv] = analys(lapu, lapv);
5559 dLu = (LAu + lamJ .* Un) .* filt;
5660 dLv = (LAv + lamJ .* Vn) .* filt;
models/schnakenberg.mmodified+43−16View file
@@ -9,20 +9,35 @@
99 % geometric correction dlap from that exact solve. Grid fields are npts x 1;
1010 % spectral fields are real 2 x nlm. See docs/richardson-iteration.md.
1111 %
12-% The correction evaluates lap_g in flux form -- 6 transforms per species
12+% The correction evaluates lap_g in flux form -- 7 transforms per species
1313 % per iteration where the Cartesian-gradient form (Algorithm 4 of
1414 % evolving_surface/notes/algos.tex) needs 12. See
1515 % docs/reduced-transforms.md, and models/schnakenberg_alg4.m
1616 % for the original form kept as a live reference.
17+%
18+% The flux divergence is split against the round sphere: the sphere's share
19+% of it is -jinv*lap_s(u), exact in spectral space, and only the geometry
20+% *deviation* meets r ~ 1/sin^2(theta). Without that split the concentrated
21+% division amplifies the polar roundoff of the whole flux, and since a
22+% Turing pattern is seeded by whatever is largest in its unstable band, the
23+% amplified polar noise -- static, and re-injected every step -- picks the
24+% nucleation site and grows a spot at the pole. See docs/reduced-transforms.md
25+% Sec 5.
1726
18-function [U, V, u, v] = init(noise, a, b)
27+% The uniform steady state, perturbed by a smooth random field: chebfun's
28+% randnfun3 on the surface's bounding box, restricted to the surface by
29+% evaluating it at the grid points -- the way surfacefun seeds a run. lam3
30+% is its wavelength; the draw is seeded on the host, the sum over its
31+% Fourier modes runs on the GPU (src/mgpu/randnfun3.ts).
32+function [U, V, u, v] = init(lam3, gx, gy, gz, a, b)
33+ f = randnfun3(lam3, gx, gy, gz);
1934 us = a + b;
2035 vs = b / (us * us);
21- [U, V] = analys(us + noise, vs * ones(numel(noise), 1));
36+ [U, V] = analys(us + 0.01*f, vs * ones(numel(f), 1));
2237 [u, v] = synth(U, V);
2338 end
2439
25-function [Un, Vn, u, v] = step(U, V, lam, filt, gx, gy, gz, p1, p2, q2, r, jhat, a, b, D1, D2, dt, niter)
40+function [Un, Vn, u, v] = step(U, V, lam, filt, gx, gy, gz, p2, r, dp1, dq2, jinv, jhat, a, b, D1, D2, dt, niter)
2641 % Grouped transforms -- [a, b] = synth(x, y) -- are explicit batching:
2742 % output k is the transform of input k, and the whole group runs as one
2843 % batched Legendre dispatch, or as many as the device's lane width allows
@@ -55,16 +70,28 @@ function [Un, Vn, u, v] = step(U, V, lam, filt, gx, gy, gz, p1, p2, q2, r, jhat,
5570 for k = 1:niter
5671 % dlap = lap_g - lap_s at the current iterate, in flux form
5772 % (docs/reduced-transforms.md Sec 4). The sin-weighted derivatives
58- % sin(theta)*dtheta(u) and dphi(u) -- both smooth on the sphere,
73+ % A = sin(theta)*dtheta(u) and B = dphi(u) -- both smooth on the sphere,
5974 % synthesized straight from the dthetac/dphic coefficient shuffles --
60- % are combined pointwise through the precomputed weights p1,p2,q2 into
61- % two fluxes P,Q, also smooth. The theta flux P goes back to
75+ % are combined pointwise through the precomputed weights into two
76+ % fluxes P,Q, also smooth. The theta flux P goes back to
6277 % coefficients, through the same shuffle again, and is synthesized as
6378 % sin(theta)*dtheta(P); the phi flux Q never leaves the grid -- d/dphi
6479 % is diagonal in the Fourier index, so dphig differentiates it with two
6580 % FFT stages and no Legendre work (masking m past filt's reach). Their
6681 % sum, scaled by r, is lap_g(u). The only division by sin(theta)
67- % anywhere is folded into p1,p2,q2,r at precompute time.
82+ % anywhere is folded into the weights at precompute time.
83+ %
84+ % The weights here are the *sphere-subtracted* ones: p1 = 1 + dp1 and
85+ % q2 = 1 + dq2 (p2 is zero on the sphere already), so P,Q below are the
86+ % deviation fluxes P' = P - A, Q' = Q - B. What that leaves out is the
87+ % round sphere's own divergence, sin(theta)*dtheta(A) + dphi(B) =
88+ % -sin^2(theta)*lap_s(u), which needs no flux machinery at all: lap_s is
89+ % diagonal, so it is -lam.*Fu synthesized once (S below, riding along in
90+ % the gradient's batched synthesis) and scaled by the bounded
91+ % jinv = 1/J = r*sin^2(theta). r therefore multiplies only the deviation
92+ % -- the difference between this and multiplying the whole flux is two
93+ % orders of magnitude of polar roundoff, and it is what keeps a pattern
94+ % from nucleating at the pole (src/geom/geometry.ts, dp1/dq2/jinv).
6895 % lamJ.*Un adds back the preconditioner's -lap_s(Un)/jhat, since lam
6996 % holds +l(l+1). filt zeroes the top two degrees, where the derivative
7097 % recurrences cannot exactly represent a derivative -- and the correction
@@ -74,7 +101,7 @@ function [Un, Vn, u, v] = step(U, V, lam, filt, gx, gy, gz, p1, p2, q2, r, jhat,
74101 % point is the undiffused Bu), and the two species un-diffuse at
75102 % different rates -- a spurious Turing band at the band edge.
76103 %
77- % The two species share each grouped call: the four gradient
104+ % The two species share each grouped call: the six gradient-and-sphere
78105 % syntheses, the two theta-flux analyses, the two divergence syntheses
79106 % and the two final analyses each run as one batched dispatch.
80107 Fu = Un .* filt;
@@ -83,11 +110,11 @@ function [Un, Vn, u, v] = step(U, V, lam, filt, gx, gy, gz, p1, p2, q2, r, jhat,
83110 vpu = dphic(Fu);
84111 vtv = dthetac(Fv);
85112 vpv = dphic(Fv);
86- [Ftu, Fpu, Ftv, Fpv] = synth(vtu, vpu, vtv, vpv);
87- Pu = p1 .* Ftu + p2 .* Fpu;
88- Qu = p2 .* Ftu + q2 .* Fpu;
89- Pv = p1 .* Ftv + p2 .* Fpv;
90- Qv = p2 .* Ftv + q2 .* Fpv;
113+ [Ftu, Fpu, Ftv, Fpv, Su, Sv] = synth(vtu, vpu, vtv, vpv, lam .* Fu, lam .* Fv);
114+ Pu = dp1 .* Ftu + p2 .* Fpu;
115+ Qu = p2 .* Ftu + dq2 .* Fpu;
116+ Pv = dp1 .* Ftv + p2 .* Fpv;
117+ Qv = p2 .* Ftv + dq2 .* Fpv;
91118 [PAu, PAv] = analys(Pu, Pv);
92119 Pcu = PAu .* filt;
93120 Pcv = PAv .* filt;
@@ -96,8 +123,8 @@ function [Un, Vn, u, v] = step(U, V, lam, filt, gx, gy, gz, p1, p2, q2, r, jhat,
96123 [Lu, Lv] = synth(scu, scv);
97124 dQu = dphig(Qu);
98125 dQv = dphig(Qv);
99- lapu = r .* (Lu + dQu);
100- lapv = r .* (Lv + dQv);
126+ lapu = r .* (Lu + dQu) - jinv .* Su;
127+ lapv = r .* (Lv + dQv) - jinv .* Sv;
101128 [LAu, LAv] = analys(lapu, lapv);
102129 dLu = (LAu + lamJ .* Un) .* filt;
103130 dLv = (LAv + lamJ .* Vn) .* filt;
models/schnakenberg_alg4.mmodified+5−3View file
@@ -17,11 +17,13 @@
1717 % (docs/reduced-transforms.md); this variant is kept live
1818 % for A/B comparison, in the app and in the tests.
1919
20-function [U, V, u, v] = init(noise, a, b)
20+% Seeded from a smooth random field -- see models/schnakenberg.m.
21+function [U, V, u, v] = init(lam3, gx, gy, gz, a, b)
22+ f = randnfun3(lam3, gx, gy, gz);
2123 us = a + b;
2224 vs = b / (us * us);
23- U = analys(us + noise);
24- V = analys(vs * ones(numel(noise), 1));
25+ U = analys(us + 0.01*f);
26+ V = analys(vs * ones(numel(f), 1));
2527 u = synth(U);
2628 v = synth(V);
2729 end
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/bench.tsmodified+2−2View file
@@ -176,7 +176,7 @@ try {
176176 geometryParams: spec.geometryParams,
177177 niter: spec.niter,
178178 });
179- session.seed(spec.seed);
179+ await session.seed(spec.seed);
180180
181181 const plan = session.describe();
182182 const kernels = plan.step.filter((l) => l.startsWith('kernel')).length;
@@ -259,7 +259,7 @@ try {
259259 let digest = null;
260260 let state: Float32Array | null = null;
261261 if (wantDigest) {
262- session.seed(spec.seed);
262+ await session.seed(spec.seed);
263263 session.step(spec.steps);
264264 await done();
265265 state = await session.read(model.state[0]);
scripts/longrun-node.tsmodified+1−1View file
@@ -19,7 +19,7 @@ const device = await requestShtDevice().catch((e: unknown) => {
1919 throw new Error(`${errMsg(e)}\n${NO_ADAPTER_HINT}`);
2020 });
2121 const session = await ModelSession.create({ device, model, params, lmax });
22-session.seed(1);
22+await session.seed(1);
2323 console.log(`longrun — models/${model.key}.m at lmax ${lmax}, ${runtime}\n`);
2424
2525 const nsteps = Math.round(100 / params.dt);
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+14−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';
@@ -15,6 +18,9 @@ import { analyticChecks } from '../test/analyticChecks.ts';
1518 import { modelChecks } from '../test/modelChecks.ts';
1619 import { geometryChecks } from '../test/geometryChecks.ts';
1720 import { fluxChecks } from '../test/fluxChecks.ts';
21+import { compareChecks } from '../test/compareChecks.ts';
22+import { referenceChecks, type H5Rt } from '../test/referenceChecks.ts';
23+import { matlabExportChecks } from '../test/matlabExportChecks.ts';
1824
1925 let failures = 0;
2026 const check = (name: string, ok: boolean, detail: string): void => {
@@ -53,6 +59,14 @@ await analyticChecks(device, check, log);
5359 await modelChecks(device, check, log);
5460 await geometryChecks(device, check, log);
5561 await fluxChecks(device, check, log);
62+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+);
5670
5771 console.log(failures === 0 ? '\nAll tests passed.' : `\n${failures} failed.`);
5872 process.exit(failures === 0 ? 0 : 1);
src/bench/runSpec.tsmodified+3−1View file
@@ -46,7 +46,9 @@ export interface RunSpec {
4646 niter: number;
4747 }
4848
49-export const DEFAULT_NITER = 1;
49+/** Iterations of the implicit solve, everywhere that does not say otherwise:
50+ * the app's `solve iters` control, `npm run bench`, and the soak. */
51+export const DEFAULT_NITER = 8;
5052
5153 /** Geometry + starting parameters of a geometry key. */
5254 export function resolveGeometry(key: string): { geometry: MGeometry; params: Params } {
src/compare/compareRun.tsadded+1019−0View file
@@ -0,0 +1,1019 @@
1+/**
2+ * Several solver settings, one problem, one clock.
3+ *
4+ * A convergence study of the knobs that decide how well the implicit solve is
5+ * resolved — `niter`, `lmax`, `dt` — run side by side so the answer to "does it
6+ * matter?" is visible rather than argued. Every variant is its own
7+ * `ModelSession` (both `niter` and `lmax` are structural: they change the
8+ * compiled step and the grid), and what makes the set a comparison rather than
9+ * a collection is three things they are forced to share:
10+ *
11+ * - **One initial condition.** Band-limited at the coarsest variant's lmax and
12+ * evaluated on each variant's own grid, so every session starts from the same
13+ * *function* rather than from the same random seed — see sharedStart.ts for
14+ * why the seed alone is not enough.
15+ *
16+ * - **One clock.** Variants differ in dt only by an integer power-of-two
17+ * divisor, and a frame advances each of them by `frameSteps * dtDiv` steps.
18+ * Every variant therefore lands on exactly the same model time at the end of
19+ * every frame, having taken a different number of steps to get there. Nothing
20+ * is ever compared across a time offset.
21+ *
22+ * - **One grid to look at.** Each session's *display* plan is pointed at a
23+ * common grid (ModelSession.setDisplayGrid), which is exact evaluation rather
24+ * than resampling because the state is band-limited. So the fields come back
25+ * directly comparable point by point, one mesh topology serves every panel,
26+ * and the difference norm is an ordinary weighted sum.
27+ *
28+ * What is *not* shared is the surface: each variant carries the geometry
29+ * band-limited at its own lmax, and renders the surface it actually solves on.
30+ */
31+import { ModelSession } from '../mgpu/session.ts';
32+import type { MModel, Params } from '../mgpu/registry.ts';
33+import type { MGeometry } from '../geom/registry.ts';
34+import {
35+ buildTopology,
36+ fillFieldValues,
37+ fillPositions,
38+ fillColors,
39+ type SphereMeshTopology,
40+} from '../render/sphereMesh.ts';
41+import { SphereScene } from '../render/SphereScene.ts';
42+import { colormaps } from '../render/colormaps.ts';
43+import { fmtValue, floorRange } from '../render/colorbar.ts';
44+import { prolongCoeffs, sharedModes, sharedNoise } from './sharedStart.ts';
45+import { variantLabel, VARIANT_COLORS, type Variant } from './variants.ts';
46+import type { ReferenceCase } from './referenceCase.ts';
47+
48+/**
49+ * Latitudes of the shared display grid. 256 is the same target the single-run
50+ * view uses for 'auto' oversampling, and for the same reason — beyond it a
51+ * finer mesh costs vertices without showing anything.
52+ *
53+ * Here it is a ceiling as well as a target, in two directions. At lmax 255 the
54+ * solver grid is finer than this, so the panels sample the (exact) state more
55+ * coarsely than the solver carries it; and past a handful of panels the mesh is
56+ * paid for once per panel, in vertices, normals and a WebGL context each, so it
57+ * halves. Both are display choices, both are reported in the status line, and
58+ * neither touches the difference norm's meaning: that is computed on this same
59+ * grid for every variant, so it stays a consistent comparison whatever the grid.
60+ */
61+const RENDER_NLAT = 256;
62+const RENDER_NLAT_CROWDED = 128;
63+const CROWDED_PANELS = 6;
64+
65+/** See main.ts's DISPATCH_BUDGET — the same watchdog argument, per variant. */
66+const DISPATCH_BUDGET = 1000;
67+const STEPS_PER_FRAME_BASE = 4;
68+
69+export interface CompareOptions {
70+ device: GPUDevice;
71+ model: MModel;
72+ /** The model's parameters, with `dt` read as the *base* timestep that each
73+ * variant's dtDiv divides. */
74+ params: Params;
75+ source: string;
76+ geometry: MGeometry;
77+ geometryParams: Params;
78+ geometrySource: string;
79+ variants: Variant[];
80+ /** Index into `variants` of the run everything else is measured against.
81+ * Ignored when `refFile` is given — the file is the reference then. */
82+ reference: number;
83+ /**
84+ * Check against a reference file instead of against each other: its exact
85+ * initial state seeds every variant (so `seed` and `lam3` go unused), a
86+ * static extra row shows its final state, every Δ is measured against that
87+ * row, and the clock stops at the file's end time. Every variant's lmax must
88+ * be >= the file's — a narrower band could not hold the initial state.
89+ */
90+ refFile?: ReferenceCase;
91+ /** Called when a refFile run reaches the file's end time and stops. */
92+ onFinished?: () => void;
93+ seed: number;
94+ /** Wavelength of the seeded random field, shared by every variant — one
95+ * initial condition means one wavelength as much as one seed. */
96+ lam3?: number;
97+ morph: number;
98+ colormapName: () => string;
99+ /** Where the variant grid goes (the app's #panels). */
100+ container: HTMLElement;
101+ /** Progress and, afterwards, the standing description of the study. */
102+ onStatus: (html: string) => void;
103+}
104+
105+interface Row {
106+ variant: Variant;
107+ session: ModelSession;
108+ color: string;
109+ /** Surface coordinates on the shared render grid — this variant's own. */
110+ coords: Float32Array;
111+ posBuf: Float32Array;
112+ scenes: SphereScene[];
113+ valueBufs: Float32Array[];
114+ colorBufs: Float32Array[];
115+ /** Fields read this frame, one per species, on the shared grid. */
116+ fields: Float32Array[];
117+ /** Relative difference from the reference, one per species. */
118+ err: number[];
119+ /** False once any species has left the floating-point numbers — the shape a
120+ * variant outside the convergence radius eventually fails in. Such a row is
121+ * never used to scale a column, and its label says so. */
122+ healthy: boolean;
123+ statEl: HTMLElement;
124+}
125+
126+/**
127+ * The reference file's final state, as one more row of panels — with no
128+ * session behind it: its surface and fields are the file's coefficients
129+ * synthesized once on the shared display grid, fixed for the whole run. Only
130+ * its coloring changes, with the shared range.
131+ */
132+interface FileRow {
133+ coords: Float32Array;
134+ posBuf: Float32Array;
135+ scenes: SphereScene[];
136+ valueBufs: Float32Array[];
137+ colorBufs: Float32Array[];
138+ /** The file's final state on the shared grid, one per species. */
139+ fields: Float32Array[];
140+ /** Its extent, precomputed — a candidate for the shared color range. */
141+ bounds: (Bounds | null)[];
142+}
143+
144+export class CompareRun {
145+ #opts: CompareOptions;
146+ #rows: Row[] = [];
147+ #fileRow: FileRow | null = null;
148+ /** What restart() reloads: the file's fixed state if opts.refFile is set,
149+ * otherwise a snapshot of the coarsest variant's state as of the last
150+ * (re-)seed — see the capture in create() and in reseed()'s plain branch. */
151+ #initial: Record<string, Float32Array>;
152+ #initialLmax: number;
153+ /** Base steps taken since the initial state — the refFile clock. */
154+ #stepsDone = 0;
155+ /** True once a refFile run has reached the file's end time. */
156+ #finished = false;
157+ #topo: SphereMeshTopology;
158+ /** Quadrature weight per grid point of the shared grid, for the L2 norm. */
159+ #weights: Float64Array;
160+ #rangeBars: { fill: (lo: number, hi: number) => void }[] = [];
161+ /** Smoothed color range per species, shared by every variant so the panels
162+ * in a column are directly comparable by eye and not just by number. */
163+ #ranges: { lo: number; hi: number }[] = [];
164+ #resizeObs: ResizeObserver | null = null;
165+
166+ #running = false;
167+ #pumping = false;
168+ #disposed = false;
169+ #morph: number;
170+ /** Base steps per frame; variant i takes this times its dtDiv. */
171+ #frameSteps = STEPS_PER_FRAME_BASE;
172+ /** Model time all variants are at — one number, by construction. */
173+ #t = 0;
174+ #frameMs = 0;
175+ #note: string;
176+
177+ private constructor(init: {
178+ opts: CompareOptions;
179+ rows: Row[];
180+ fileRow: FileRow | null;
181+ topo: SphereMeshTopology;
182+ weights: Float64Array;
183+ rangeBars: { fill: (lo: number, hi: number) => void }[];
184+ frameSteps: number;
185+ note: string;
186+ initial: Record<string, Float32Array>;
187+ initialLmax: number;
188+ }) {
189+ this.#opts = init.opts;
190+ this.#rows = init.rows;
191+ this.#fileRow = init.fileRow;
192+ this.#topo = init.topo;
193+ this.#weights = init.weights;
194+ this.#rangeBars = init.rangeBars;
195+ this.#frameSteps = init.frameSteps;
196+ this.#note = init.note;
197+ this.#morph = init.opts.morph;
198+ this.#ranges = init.opts.model.species.map(() => ({ lo: NaN, hi: NaN }));
199+ this.#initial = init.initial;
200+ this.#initialLmax = init.initialLmax;
201+ }
202+
203+ get variants(): Variant[] {
204+ return this.#rows.map((r) => r.variant);
205+ }
206+
207+ /** The variant everything else is measured against — the one whose numbers
208+ * stand on their own, so the one the app quotes when it has to quote one. */
209+ get referenceSession(): ModelSession | null {
210+ return this.#rows[this.#opts.reference]?.session ?? null;
211+ }
212+
213+ get referenceIndex(): number {
214+ return this.#opts.reference;
215+ }
216+
217+ /** The reference file this study is checking against, if any. */
218+ get refFile(): ReferenceCase | null {
219+ return this.#opts.refFile ?? null;
220+ }
221+
222+ /** The base timestep a variant's dtDiv divides. */
223+ static baseDt(params: Params): number {
224+ return params.dt ?? 0;
225+ }
226+
227+ static async create(opts: CompareOptions): Promise<CompareRun> {
228+ const { device, model, variants } = opts;
229+ const baseDt = CompareRun.baseDt(opts.params);
230+ const showDt = variants.some((v) => v.dtDiv !== variants[0].dtDiv);
231+ const sessions: ModelSession[] = [];
232+ // Scenes own a WebGL context and an animation frame each, so a failure
233+ // after the grid is up has to take them down explicitly — removing their
234+ // canvases from the DOM would leave both running.
235+ let built: Row[] = [];
236+ let builtFile: FileRow | null = null;
237+
238+ try {
239+ for (let i = 0; i < variants.length; i++) {
240+ const v = variants[i];
241+ opts.onStatus(
242+ `compiling ${i + 1}/${variants.length} — ${variantLabel(v, showDt)} ` +
243+ `(a solve iteration is ~15 kernels per species, and there is no ` +
244+ `pipeline cache across sessions)`,
245+ );
246+ // Yield, so the status actually paints before the compile blocks.
247+ await new Promise<number>(requestAnimationFrame);
248+ sessions.push(
249+ await ModelSession.create({
250+ device,
251+ model,
252+ params: { ...opts.params, dt: baseDt / v.dtDiv },
253+ lmax: v.lmax,
254+ source: opts.source,
255+ geometry: opts.geometry,
256+ geometryParams: opts.geometryParams,
257+ geometrySource: opts.geometrySource,
258+ niter: v.niter,
259+ lam3: opts.lam3,
260+ }),
261+ );
262+ }
263+
264+ // ---- the shared display grid ----------------------------------------
265+ const maxLmax = Math.max(...variants.map((v) => v.lmax));
266+ const panels = (variants.length + (opts.refFile ? 1 : 0)) * model.species.length;
267+ const target = panels > CROWDED_PANELS ? RENDER_NLAT_CROWDED : RENDER_NLAT;
268+ // Never below what the finest band needs to be representable at all
269+ // (ShtPlan requires nlat > lmax), whatever the panel count says.
270+ const nlat = Math.max(target, 2 * Math.ceil((maxLmax + 2) / 2));
271+ let nphi = 1;
272+ while (nphi < Math.max(2 * nlat, 2 * maxLmax + 1)) nphi *= 2;
273+ for (const s of sessions) await s.setDisplayGrid(nlat, nphi);
274+
275+ // ---- one initial condition, on every grid ---------------------------
276+ // Also what restart() reloads later — the file's fixed state, or (for
277+ // the plain case) a snapshot of the coarsest variant's own state,
278+ // taken after seeding it: the same lowest-lmax session sharedNoise
279+ // itself draws from, so prolonging it up to any other variant later is
280+ // always widening a band, never narrowing one.
281+ let initial: Record<string, Float32Array>;
282+ let initialLmax: number;
283+ if (opts.refFile) {
284+ // The file's exact spectral state, prolonged into each variant's band.
285+ // Exact, not approximate: the state is band-limited at the file's lmax
286+ // and every variant's band contains it, so each session starts from
287+ // the very field the reference run started from.
288+ opts.onStatus('loading the initial state from the reference file…');
289+ for (const s of sessions) {
290+ s.loadState(prolongState(opts.refFile.initial, model.state, opts.refFile.lmax, s.cfg.lmax));
291+ }
292+ initial = opts.refFile.initial;
293+ initialLmax = opts.refFile.lmax;
294+ } else {
295+ opts.onStatus('seeding all variants from one band-limited perturbation…');
296+ const noise = await sharedNoise(sessions, model.seedAmp, opts.seed);
297+ const modes = await sharedModes(sessions[opts.reference] ?? sessions[0], opts.seed);
298+ // One at a time: a seed submits its whole mode sum in pieces, and there
299+ // is nothing to gain from interleaving several variants' worth of it.
300+ for (let i = 0; i < sessions.length; i++) await sessions[i].seedWith(noise[i], modes);
301+ let coarsest = sessions[0];
302+ for (const s of sessions) if (s.cfg.lmax < coarsest.cfg.lmax) coarsest = s;
303+ initial = await coarsest.readState();
304+ initialLmax = coarsest.cfg.lmax;
305+ }
306+
307+ // ---- the mesh, shared; the surface, per variant ---------------------
308+ const view = sessions[0].viewSht;
309+ const phi = new Float64Array(nphi);
310+ for (let j = 0; j < nphi; j++) phi[j] = (2 * Math.PI * j) / nphi;
311+ const topo = buildTopology(view.cosTheta, phi);
312+ // Gauss weights carry the sin(theta) of the area element; the constant
313+ // 2*pi/nphi is common to every point and cancels in the relative norm.
314+ const weights = new Float64Array(nlat * nphi);
315+ for (let i = 0; i < nlat; i++) {
316+ for (let j = 0; j < nphi; j++) weights[i * nphi + j] = view.gaussWeights[i];
317+ }
318+
319+ // ---- how many steps a frame may submit ------------------------------
320+ // Per variant: its own unrolled step size times its dtDiv, since a ÷K
321+ // variant takes K times as many steps to reach the same time.
322+ let frameSteps = STEPS_PER_FRAME_BASE;
323+ const ops: number[] = [];
324+ for (let i = 0; i < sessions.length; i++) {
325+ const n = Math.max(1, sessions[i].describe().step.length);
326+ ops.push(n);
327+ frameSteps = Math.min(
328+ frameSteps,
329+ Math.max(1, Math.floor(DISPATCH_BUDGET / (n * variants[i].dtDiv))),
330+ );
331+ }
332+ frameSteps = Math.max(1, frameSteps);
333+
334+ // ---- the grid of panels ---------------------------------------------
335+ const { rows, fileRow, rangeBars } = await buildGrid(opts, sessions, topo, showDt);
336+ built = rows;
337+ builtFile = fileRow;
338+
339+ const solverGrid = sessions.map((s) => `${s.cfg.nlat}×${s.cfg.nphi}`);
340+ const note =
341+ `${variants.length} variant${variants.length === 1 ? '' : 's'} · ` +
342+ `display grid ${nlat}×${nphi}` +
343+ (sessions.some((s) => s.cfg.nlat > nlat)
344+ ? ` (below the finest solver grid ${solverGrid[solverGrid.length - 1]} — display only)`
345+ : '') +
346+ ` · ${frameSteps} base step${frameSteps === 1 ? '' : 's'}/frame` +
347+ ` · ops/step ${ops.join(', ')}`;
348+
349+ const run = new CompareRun({
350+ opts, rows, fileRow, topo, weights, rangeBars, frameSteps, note, initial, initialLmax,
351+ });
352+ await run.draw();
353+ run.#observeResize();
354+ run.#status();
355+ return run;
356+ } catch (e) {
357+ for (const r of built) for (const s of r.scenes) s.dispose();
358+ for (const s of builtFile?.scenes ?? []) s.dispose();
359+ for (const s of sessions) s.destroy();
360+ opts.container.replaceChildren();
361+ opts.container.classList.remove('compare');
362+ throw e;
363+ }
364+ }
365+
366+ // ------------------------------------------------------------------ state
367+ setRunning(next: boolean): void {
368+ this.#running = next;
369+ if (next) void this.#pump();
370+ }
371+
372+ get running(): boolean {
373+ return this.#running;
374+ }
375+
376+ /** Re-seed every variant from one new shared perturbation — or, against a
377+ * reference file, restart from its initial state (there is nothing to
378+ * draw; the seed is ignored). */
379+ async reseed(seed: number): Promise<void> {
380+ const wasRunning = this.#running;
381+ this.#running = false;
382+ while (this.#pumping) await nextFrame();
383+ if (this.#disposed) return;
384+ const sessions = this.#rows.map((r) => r.session);
385+ const refFile = this.#opts.refFile;
386+ if (refFile) {
387+ for (const s of sessions) {
388+ s.loadState(prolongState(refFile.initial, this.#opts.model.state, refFile.lmax, s.cfg.lmax));
389+ }
390+ } else {
391+ const noise = await sharedNoise(sessions, this.#opts.model.seedAmp, seed);
392+ const modes = await sharedModes(this.referenceSession ?? sessions[0], seed);
393+ // Checked per variant, not once: a seed awaits its own submission, so a
394+ // dispose can land between two of them and destroy the sessions left.
395+ for (let i = 0; i < sessions.length; i++) {
396+ if (this.#disposed) return;
397+ await sessions[i].seedWith(noise[i], modes);
398+ }
399+ if (this.#disposed) return;
400+ // This draw becomes what restart() rewinds to from now on — see the
401+ // identical selection in create(). Recaptured here rather than left
402+ // pointing at the pre-reseed field.
403+ let coarsest = sessions[0];
404+ for (const s of sessions) if (s.cfg.lmax < coarsest.cfg.lmax) coarsest = s;
405+ this.#initial = await coarsest.readState();
406+ this.#initialLmax = coarsest.cfg.lmax;
407+ }
408+ this.#t = 0;
409+ this.#stepsDone = 0;
410+ this.#finished = false;
411+ for (const r of this.#ranges) {
412+ r.lo = NaN;
413+ r.hi = NaN;
414+ }
415+ await this.draw();
416+ this.#status();
417+ if (!this.#disposed && wasRunning) this.setRunning(true);
418+ }
419+
420+ /** Rewind every variant to the saved initial condition — the file's fixed
421+ * state, or (for the plain case) the last (re-)seed, not necessarily the
422+ * very first one — without drawing anything new. */
423+ async restart(): Promise<void> {
424+ const wasRunning = this.#running;
425+ this.#running = false;
426+ while (this.#pumping) await nextFrame();
427+ if (this.#disposed) return;
428+ for (const r of this.#rows) {
429+ r.session.loadState(
430+ prolongState(this.#initial, this.#opts.model.state, this.#initialLmax, r.session.cfg.lmax),
431+ );
432+ }
433+ this.#t = 0;
434+ this.#stepsDone = 0;
435+ this.#finished = false;
436+ for (const r of this.#ranges) {
437+ r.lo = NaN;
438+ r.hi = NaN;
439+ }
440+ await this.draw();
441+ this.#status();
442+ if (!this.#disposed && wasRunning) this.setRunning(true);
443+ }
444+
445+ /** Wavelength of the seeded random field. One number for the study: every
446+ * variant seeds from the same field, so they seed at the same wavelength. */
447+ get lam3(): number {
448+ return this.#rows[0]?.session.lam3 ?? 0;
449+ }
450+
451+ /** Change it on every variant. Like the single run's, this only takes effect
452+ * on the next reseed, which is where the field is drawn. */
453+ setLam3(lambda: number): void {
454+ this.#opts.lam3 = lambda;
455+ for (const r of this.#rows) r.session.setLam3(lambda);
456+ }
457+
458+ /** Model parameters changed. Each variant keeps its own dt. */
459+ setParams(params: Params): void {
460+ // Against a reference file the parameters *are* the file's — they define
461+ // the problem being checked — and the page's parameter panel edits the
462+ // page's own model, which need not even be this one. Nothing to apply.
463+ if (this.#opts.refFile) return;
464+ this.#opts.params = params;
465+ const baseDt = CompareRun.baseDt(params);
466+ for (const r of this.#rows) {
467+ r.session.setParams({ ...params, dt: baseDt / r.variant.dtDiv });
468+ }
469+ }
470+
471+ setMorph(morph: number): void {
472+ this.#morph = morph;
473+ for (const r of this.#rows) {
474+ fillPositions(r.posBuf, r.coords, this.#topo, morph);
475+ for (const s of r.scenes) s.updatePositions(r.posBuf);
476+ }
477+ const f = this.#fileRow;
478+ if (f) {
479+ fillPositions(f.posBuf, f.coords, this.#topo, morph);
480+ for (const s of f.scenes) s.updatePositions(f.posBuf);
481+ }
482+ }
483+
484+ resetView(): void {
485+ for (const s of this.#allScenes()) s.resetCamera();
486+ }
487+
488+ dispose(): void {
489+ this.#disposed = true;
490+ this.#running = false;
491+ this.#resizeObs?.disconnect();
492+ this.#resizeObs = null;
493+ for (const r of this.#rows) {
494+ for (const s of r.scenes) s.dispose();
495+ r.session.destroy();
496+ }
497+ for (const s of this.#fileRow?.scenes ?? []) s.dispose();
498+ this.#rows = [];
499+ this.#fileRow = null;
500+ this.#opts.container.replaceChildren();
501+ this.#opts.container.classList.remove('compare');
502+ }
503+
504+ #allScenes(): SphereScene[] {
505+ return [...this.#rows.flatMap((r) => r.scenes), ...(this.#fileRow?.scenes ?? [])];
506+ }
507+
508+ // ----------------------------------------------------------------- drawing
509+ /**
510+ * One frame's readback: every variant's every species, on the shared grid.
511+ * Read first, then color — the range is shared down a column, so no panel can
512+ * be filled until the column's range is known.
513+ */
514+ async draw(): Promise<void> {
515+ if (this.#disposed) return;
516+ const species = this.#opts.model.species;
517+ // Sessions are independent, so their readbacks can be in flight together;
518+ // within one session they must not be (they share its staging buffers).
519+ await Promise.all(
520+ this.#rows.map(async (r) => {
521+ for (let k = 0; k < species.length; k++) {
522+ r.fields[k] = await r.session.readSpecies(k);
523+ }
524+ }),
525+ );
526+ if (this.#disposed) return;
527+
528+ const cmap = colormaps[this.#opts.colormapName()] ?? colormaps.viridis;
529+
530+ /**
531+ * What scales a column is the whole question, and it has three wrong
532+ * answers.
533+ *
534+ * Per panel is wrong: a range each rescales every variant to itself and
535+ * hides exactly the difference the grid exists to show. The union over
536+ * variants is wrong for the opposite reason: a variant outside the
537+ * iteration's convergence radius runs away to 1e20 and then to NaN, and a
538+ * union range rescales the *whole column* to it, flattening every panel to
539+ * one colour — which reads as "they all blew up" when only one did.
540+ *
541+ * The reference alone is wrong too, less obviously, and it is the case that
542+ * actually bites: outside the convergence radius *more* Richardson
543+ * iterations diverge *faster*, so the row that goes first is usually the
544+ * highest-niter one — which is the reference.
545+ *
546+ * So the column is scaled by whichever variant **reaches least far from
547+ * zero** — the least-blown-up one. That is a comparison between the rows,
548+ * not a threshold on any of them, and the distinction is the whole point:
549+ * any "is this value too big?" test has a window in which a diverging field
550+ * is still under the limit, and for as long as that window lasts it drags
551+ * the scale and flattens the grid, until it finally trips and everything
552+ * springs back. A comparison has no such window — a run-away only has to be
553+ * *larger* than a healthy row to stop setting the scale, which it is from
554+ * its first bad step, and it stays larger no matter how many other rows go
555+ * with it. One healthy variant is enough to keep the grid readable.
556+ *
557+ * The cost is a slight bias: among healthy variants the scale comes from
558+ * the one with the smallest peak, so the others clip by however much they
559+ * exceed it. They are approximations of the same solution, so that is a
560+ * fraction of a percent, and the alternative is a display that a single
561+ * divergence can take away.
562+ */
563+ const bounds = this.#rows.map((r) => species.map((_, k) => finiteRange(r.fields[k])));
564+ this.#rows.forEach((r, i) => {
565+ // A row with any non-finite value is out of the running entirely: its
566+ // finite entries are whatever survived, and no rank over them means much.
567+ r.healthy = species.every((_, k) => allFinite(r.fields[k]) && bounds[i][k] !== null);
568+ });
569+
570+ for (let k = 0; k < species.length; k++) {
571+ // The file row, when there is one, is a candidate like any healthy
572+ // variant: early on the variants' small fields set the scale (it merely
573+ // clips), and if every variant diverges it is the row that keeps the
574+ // grid readable.
575+ const anchor = leastPeak([
576+ ...this.#rows.map((r, i) => (r.healthy ? bounds[i][k] : null)),
577+ this.#fileRow?.bounds[k] ?? null,
578+ ]);
579+ const range = this.#ranges[k];
580+ if (anchor) {
581+ if (!Number.isFinite(range.lo)) {
582+ range.lo = anchor.lo;
583+ range.hi = anchor.hi;
584+ } else {
585+ // Smooth in both directions so the shading evolves gently as the
586+ // pattern grows, as the single-run view does.
587+ const a = 0.15;
588+ range.lo += a * (anchor.lo - range.lo);
589+ range.hi += a * (anchor.hi - range.hi);
590+ }
591+ }
592+ // With every row gone, the last good range is kept rather than replaced
593+ // by nothing: the panels freeze at a readable scale and the row labels
594+ // say what happened, instead of the grid going blank.
595+ if (!Number.isFinite(range.lo) || !Number.isFinite(range.hi)) continue;
596+ // The floor is applied to what is drawn, not to what is tracked, so it
597+ // never feeds back into the smoothing above.
598+ const shown = floorRange(range.lo, range.hi);
599+ this.#rangeBars[k]?.fill(shown.lo, shown.hi);
600+ for (const r of this.#rows) {
601+ fillFieldValues(r.valueBufs[k], r.fields[k], this.#topo);
602+ fillColors(r.colorBufs[k], r.valueBufs[k], shown.lo, shown.hi, cmap);
603+ r.scenes[k]?.updateColors(r.colorBufs[k]);
604+ }
605+ const f = this.#fileRow;
606+ if (f) {
607+ // Its values never change; only its coloring follows the shared range.
608+ fillColors(f.colorBufs[k], f.valueBufs[k], shown.lo, shown.hi, cmap);
609+ f.scenes[k]?.updateColors(f.colorBufs[k]);
610+ }
611+ }
612+
613+ this.#measureDifference();
614+ this.#updateRowStats();
615+ }
616+
617+ /**
618+ * Relative L2 difference from the reference, per species, on the shared
619+ * grid. Weighted by the Gauss weights, so it is the norm on the parameter
620+ * sphere — not on the embedded surface, which would weight by the area
621+ * element. That makes it a consistent diagnostic across variants rather than
622+ * a physical quantity, which is all it is used for.
623+ */
624+ #measureDifference(): void {
625+ // Against a reference file, every row is measured against its final state;
626+ // otherwise against the chosen reference variant, whose own Δ is zero.
627+ const ref = this.#fileRow ? null : this.#rows[this.#opts.reference];
628+ const refFields = this.#fileRow?.fields ?? ref?.fields;
629+ if (!refFields) return;
630+ const species = this.#opts.model.species;
631+ for (const r of this.#rows) {
632+ for (let k = 0; k < species.length; k++) {
633+ if (r === ref) {
634+ r.err[k] = 0;
635+ continue;
636+ }
637+ const a = r.fields[k];
638+ const b = refFields[k];
639+ if (!a || !b || a.length !== b.length) {
640+ r.err[k] = NaN;
641+ continue;
642+ }
643+ let num = 0;
644+ let den = 0;
645+ for (let i = 0; i < a.length; i++) {
646+ const w = this.#weights[i];
647+ const d = a[i] - b[i];
648+ num += w * d * d;
649+ den += w * b[i] * b[i];
650+ }
651+ r.err[k] = den > 0 ? Math.sqrt(num / den) : NaN;
652+ }
653+ }
654+ }
655+
656+ /**
657+ * Each row's standing line: how many of its own steps it took to reach the
658+ * common time, and how far it is from the reference right now, per species.
659+ * Per species rather than a single worst-case number because the two are
660+ * genuinely different questions on a two-species model — the slow species is
661+ * usually the one that has converged and the fast one the one that has not.
662+ */
663+ #updateRowStats(): void {
664+ const species = this.#opts.model.species;
665+ const ref = this.#fileRow ? null : this.#rows[this.#opts.reference];
666+ for (const r of this.#rows) {
667+ const per = species
668+ .map((s, k) => `${s} ${Number.isFinite(r.err[k]) ? r.err[k].toExponential(2) : '—'}`)
669+ .join('<br>');
670+ // Divergence is said, not implied. Scaled to a healthy row, a blown-up
671+ // variant is a flat saturated panel, which on its own is easy to misread
672+ // as a converged uniform state.
673+ const body = !r.healthy
674+ ? '<b class="cmp-diverged">diverged</b>'
675+ : r === ref
676+ ? '<b>reference</b>'
677+ : `Δ ${per}`;
678+ r.statEl.innerHTML = `${r.session.steps.toLocaleString()} steps<br>${body}`;
679+ }
680+ }
681+
682+ #status(): void {
683+ const refFile = this.#opts.refFile;
684+ const clock = refFile
685+ ? `<b>t = ${this.#t.toFixed(2)} / ${(refFile.steps * CompareRun.baseDt(this.#opts.params)).toFixed(2)}</b>` +
686+ (this.#finished
687+ ? ` — <b>at the file's end time</b>: Δ is the final comparison against its final state`
688+ : ` · Δ is the distance still to the file's <i>final</i> state — read it at the end time`)
689+ : `<b>t = ${this.#t.toFixed(2)}</b> (same for every variant)`;
690+ this.#opts.onStatus(
691+ `${clock} · ` +
692+ (this.#frameMs > 0 ? `${this.#frameMs.toFixed(1)} ms/frame · ` : '') +
693+ this.#note,
694+ );
695+ }
696+
697+ #observeResize(): void {
698+ const scenes = this.#allScenes();
699+ this.#resizeObs = new ResizeObserver(() => {
700+ for (const s of scenes) {
701+ const box = s.canvas.parentElement;
702+ if (box) s.resize(box.clientWidth, box.clientHeight);
703+ }
704+ });
705+ for (const s of scenes) {
706+ const box = s.canvas.parentElement;
707+ if (box) this.#resizeObs.observe(box);
708+ }
709+ }
710+
711+ // -------------------------------------------------------------- the clock
712+ /**
713+ * One frame advances every variant by the *same model time*: `frameSteps`
714+ * base steps, which a ÷K variant covers in K times as many of its own. That
715+ * is the whole reason dt varies by an integer divisor — the alternative is
716+ * rounding each variant to the nearest step and comparing fields that are a
717+ * fraction of a timestep apart, which would show up as a difference and be
718+ * indistinguishable from a real one.
719+ */
720+ async #pump(): Promise<void> {
721+ if (this.#pumping) return;
722+ this.#pumping = true;
723+ try {
724+ while (this.#running && !this.#disposed) {
725+ // Against a reference file the run is finite: the last frame takes
726+ // however many base steps remain, so every variant lands exactly on
727+ // the file's end time — where Δ against its final state is the
728+ // comparison — and stops there rather than drifting past it.
729+ const refFile = this.#opts.refFile;
730+ const n = refFile
731+ ? Math.min(this.#frameSteps, refFile.steps - this.#stepsDone)
732+ : this.#frameSteps;
733+ if (n <= 0) {
734+ this.#running = false;
735+ this.#opts.onFinished?.();
736+ break;
737+ }
738+ const t0 = performance.now();
739+ for (const r of this.#rows) r.session.step(n * r.variant.dtDiv);
740+ this.#stepsDone += n;
741+ this.#t += n * CompareRun.baseDt(this.#opts.params);
742+ await this.draw();
743+ if (this.#disposed) break;
744+ const dt = performance.now() - t0;
745+ this.#frameMs = this.#frameMs === 0 ? dt : this.#frameMs + 0.05 * (dt - this.#frameMs);
746+ if (refFile && this.#stepsDone >= refFile.steps) {
747+ this.#finished = true;
748+ this.#running = false;
749+ this.#status();
750+ this.#opts.onFinished?.();
751+ break;
752+ }
753+ this.#status();
754+ await nextFrame();
755+ }
756+ if (!this.#disposed) {
757+ await this.draw();
758+ this.#status();
759+ }
760+ } finally {
761+ this.#pumping = false;
762+ }
763+ }
764+}
765+
766+const nextFrame = (): Promise<number> => new Promise(requestAnimationFrame);
767+
768+/** A whole spectral state re-indexed into a (wider) band's layout — the
769+ * reference file's initial condition, in the form loadState takes. */
770+function prolongState(
771+ coeffs: Record<string, Float32Array>,
772+ names: string[],
773+ lmaxFrom: number,
774+ lmaxTo: number,
775+): Record<string, Float32Array> {
776+ const out: Record<string, Float32Array> = {};
777+ for (const name of names) out[name] = prolongCoeffs(coeffs[name], lmaxFrom, lmaxTo);
778+ return out;
779+}
780+
781+/** Whether every entry is an ordinary number — false once a variant has left
782+ * its convergence radius and saturated to infinity or NaN. */
783+function allFinite(f: Float32Array | undefined): boolean {
784+ if (!f) return false;
785+ for (let i = 0; i < f.length; i++) if (!Number.isFinite(f[i])) return false;
786+ return true;
787+}
788+
789+type Bounds = { lo: number; hi: number };
790+
791+/** How far a field reaches from zero — the one number the rows are ranked by
792+ * when deciding which of them sets a column's scale. */
793+const peak = (b: Bounds): number => Math.max(Math.abs(b.lo), Math.abs(b.hi));
794+
795+/** Whichever of the given bounds reaches least far from zero; null if none. */
796+function leastPeak(all: (Bounds | null)[]): Bounds | null {
797+ let best: Bounds | null = null;
798+ for (const b of all) {
799+ if (b !== null && (best === null || peak(b) < peak(best))) best = b;
800+ }
801+ return best;
802+}
803+
804+/** Min and max over the finite entries only; null when there are none. */
805+function finiteRange(f: Float32Array | undefined): { lo: number; hi: number } | null {
806+ if (!f) return null;
807+ let lo = Infinity;
808+ let hi = -Infinity;
809+ for (let i = 0; i < f.length; i++) {
810+ const v = f[i];
811+ if (!Number.isFinite(v)) continue;
812+ if (v < lo) lo = v;
813+ if (v > hi) hi = v;
814+ }
815+ return lo <= hi ? { lo, hi } : null;
816+}
817+
818+/**
819+ * The DOM: a header row naming each species and carrying that column's shared
820+ * color range, then one row per variant. The colorbar is per *column* rather
821+ * than per panel because the range is shared — a bar on every panel would be
822+ * the same bar repeated, and would suggest each panel had its own scaling,
823+ * which is exactly the thing that would make the comparison a lie.
824+ */
825+/** The file row's label color — none of the variant palette, since it is not
826+ * a variant: it is the thing they are all measured against. */
827+const FILE_ROW_COLOR = '#57606a';
828+
829+async function buildGrid(
830+ opts: CompareOptions,
831+ sessions: ModelSession[],
832+ topo: SphereMeshTopology,
833+ showDt: boolean,
834+): Promise<{
835+ rows: Row[];
836+ fileRow: FileRow | null;
837+ rangeBars: { fill: (lo: number, hi: number) => void }[];
838+}> {
839+ const { container, model } = opts;
840+ container.replaceChildren();
841+ container.classList.add('compare');
842+
843+ const head = document.createElement('div');
844+ head.className = 'cmp-row cmp-head';
845+ const headSpacer = document.createElement('div');
846+ headSpacer.className = 'cmp-rowlabel';
847+ const headCols = document.createElement('div');
848+ headCols.className = 'cmp-cols';
849+ head.append(headSpacer, headCols);
850+ container.append(head);
851+
852+ const rangeBars = model.species.map((name) => {
853+ const col = document.createElement('div');
854+ col.className = 'cmp-colhead';
855+ const tag = document.createElement('b');
856+ tag.textContent = name;
857+ const canvas = document.createElement('canvas');
858+ canvas.width = 160;
859+ canvas.height = 8;
860+ canvas.className = 'cmp-rangebar';
861+ const lab = document.createElement('span');
862+ lab.className = 'cmp-rangelab';
863+ col.append(tag, canvas, lab);
864+ headCols.append(col);
865+ let painted = false;
866+ return {
867+ fill: (lo: number, hi: number): void => {
868+ const ctx = canvas.getContext('2d');
869+ if (ctx && !painted) {
870+ painted = true;
871+ const cmap = colormaps[opts.colormapName()] ?? colormaps.viridis;
872+ for (let x = 0; x < canvas.width; x++) {
873+ const [r, g, b] = cmap(x / (canvas.width - 1));
874+ ctx.fillStyle = `rgb(${r},${g},${b})`;
875+ ctx.fillRect(x, 0, 1, canvas.height);
876+ }
877+ }
878+ lab.textContent = `${fmtValue(lo)} … ${fmtValue(hi)}`;
879+ },
880+ };
881+ });
882+
883+ const sphereBg = getComputedStyle(document.documentElement)
884+ .getPropertyValue('--sphere-bg')
885+ .trim();
886+
887+ const rows: Row[] = [];
888+ for (let i = 0; i < sessions.length; i++) {
889+ const session = sessions[i];
890+ const variant = opts.variants[i];
891+ const color = VARIANT_COLORS[i % VARIANT_COLORS.length];
892+
893+ const coords = await session.renderPositions();
894+ const posBuf = new Float32Array(topo.numVertices * 3);
895+ fillPositions(posBuf, coords, topo, opts.morph);
896+
897+ const rowEl = document.createElement('div');
898+ rowEl.className = 'cmp-row';
899+ const labelEl = document.createElement('div');
900+ labelEl.className = 'cmp-rowlabel';
901+ labelEl.style.setProperty('--c', color);
902+ const nameEl = document.createElement('div');
903+ nameEl.className = 'cmp-rowname';
904+ nameEl.textContent = variantLabel(variant, showDt);
905+ const statEl = document.createElement('div');
906+ statEl.className = 'cmp-rowstat';
907+ labelEl.append(nameEl, statEl);
908+ const colsEl = document.createElement('div');
909+ colsEl.className = 'cmp-cols';
910+ rowEl.append(labelEl, colsEl);
911+ container.append(rowEl);
912+
913+ const scenes: SphereScene[] = [];
914+ const valueBufs: Float32Array[] = [];
915+ const colorBufs: Float32Array[] = [];
916+ for (let k = 0; k < model.species.length; k++) {
917+ const box = document.createElement('div');
918+ box.className = 'sphere-box cmp-box';
919+ colsEl.append(box);
920+ const scene = new SphereScene(
921+ box,
922+ topo.numVertices,
923+ topo.indices,
924+ Float32Array.from(posBuf),
925+ sphereBg || undefined,
926+ );
927+ scene.fitCamera();
928+ scenes.push(scene);
929+ valueBufs.push(new Float32Array(topo.numVertices));
930+ colorBufs.push(new Float32Array(topo.numVertices * 3));
931+ }
932+
933+ rows.push({
934+ variant, session, color, coords, posBuf, scenes, valueBufs, colorBufs,
935+ fields: [], err: model.species.map(() => 0), healthy: true, statEl,
936+ });
937+ }
938+
939+ // ---- the reference file's final state, as one more (static) row ---------
940+ let fileRow: FileRow | null = null;
941+ if (opts.refFile) {
942+ const rf = opts.refFile;
943+ // Synthesized through the coarsest session's display plan — exact, like
944+ // every other use of the shared grid: the file's coefficients are
945+ // band-limited at its lmax, which every variant's band contains.
946+ const view = sessions[0].viewSht;
947+ const lmaxTo = sessions[0].cfg.lmax;
948+ const on = (q: Float32Array): Promise<Float32Array> =>
949+ view.synth(prolongCoeffs(q, rf.lmax, lmaxTo));
950+ const [gx, gy, gz] = [
951+ await on(rf.geometryCoeffs.X),
952+ await on(rf.geometryCoeffs.Y),
953+ await on(rf.geometryCoeffs.Z),
954+ ];
955+ // The file's own surface, not a regeneration of it — interleaved xyz, the
956+ // same layout renderPositions() hands back.
957+ const coords = new Float32Array(3 * gx.length);
958+ for (let i = 0; i < gx.length; i++) {
959+ coords[3 * i] = gx[i];
960+ coords[3 * i + 1] = gy[i];
961+ coords[3 * i + 2] = gz[i];
962+ }
963+ const posBuf = new Float32Array(topo.numVertices * 3);
964+ fillPositions(posBuf, coords, topo, opts.morph);
965+
966+ const rowEl = document.createElement('div');
967+ rowEl.className = 'cmp-row';
968+ const labelEl = document.createElement('div');
969+ labelEl.className = 'cmp-rowlabel';
970+ labelEl.style.setProperty('--c', FILE_ROW_COLOR);
971+ const nameEl = document.createElement('div');
972+ nameEl.className = 'cmp-rowname';
973+ nameEl.textContent = 'reference file';
974+ nameEl.title = rf.label;
975+ const statEl = document.createElement('div');
976+ statEl.className = 'cmp-rowstat';
977+ statEl.innerHTML = `${rf.steps.toLocaleString()} steps<br><b>final state</b>`;
978+ labelEl.append(nameEl, statEl);
979+ const colsEl = document.createElement('div');
980+ colsEl.className = 'cmp-cols';
981+ rowEl.append(labelEl, colsEl);
982+ container.append(rowEl);
983+
984+ const scenes: SphereScene[] = [];
985+ const valueBufs: Float32Array[] = [];
986+ const colorBufs: Float32Array[] = [];
987+ const fields: Float32Array[] = [];
988+ const bounds: (Bounds | null)[] = [];
989+ for (let k = 0; k < model.species.length; k++) {
990+ const box = document.createElement('div');
991+ box.className = 'sphere-box cmp-box';
992+ colsEl.append(box);
993+ const scene = new SphereScene(
994+ box,
995+ topo.numVertices,
996+ topo.indices,
997+ Float32Array.from(posBuf),
998+ sphereBg || undefined,
999+ );
1000+ scene.fitCamera();
1001+ scenes.push(scene);
1002+ const field = await on(rf.final[model.state[k]]);
1003+ fields.push(field);
1004+ bounds.push(finiteRange(field));
1005+ const valueBuf = new Float32Array(topo.numVertices);
1006+ fillFieldValues(valueBuf, field, topo);
1007+ valueBufs.push(valueBuf);
1008+ colorBufs.push(new Float32Array(topo.numVertices * 3));
1009+ }
1010+ fileRow = { coords, posBuf, scenes, valueBufs, colorBufs, fields, bounds };
1011+ }
1012+
1013+ // Every panel shares one camera: the study is about the fields, and looking
1014+ // at two of them from different angles is not comparing them.
1015+ const all = [...rows.flatMap((r) => r.scenes), ...(fileRow?.scenes ?? [])];
1016+ for (let i = 1; i < all.length; i++) all[0].syncCamerasWith(all[i]);
1017+
1018+ return { rows, fileRow, rangeBars };
1019+}
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/compare/sharedStart.tsadded+101−0View file
@@ -0,0 +1,101 @@
1+/**
2+ * One initial condition, on every variant's grid.
3+ *
4+ * The host's seeded perturbation is one normal deviate per *grid point*
5+ * (src/mgpu/noise.ts), so two sessions at different lmax seeded from the same
6+ * integer do not start from the same field — they start from unrelated fields
7+ * that merely share a random seed. Comparing them would compare two different
8+ * problems, and every number the comparison produced would be meaningless.
9+ *
10+ * So the field is built once, band-limited at the *coarsest* variant's lmax,
11+ * and evaluated on each variant's own grid:
12+ *
13+ * 1. white noise on the coarsest grid
14+ * 2. analysed there -> coefficients up to lmax_min
15+ * 3. zero-padded into each variant's coefficient layout
16+ * 4. synthesized on that variant's grid
17+ *
18+ * Steps 3 and 4 are exact: the field is band-limited at lmax_min, and every
19+ * variant's band contains that, so each one receives the *same function*
20+ * sampled where it needs it. Running each model's own `init` on it then leaves
21+ * every session holding the identical spectral state (zero-padded), which is
22+ * what makes a pointwise comparison at later times mean something.
23+ *
24+ * The coarsest variant gets the projected field too, not the raw white noise
25+ * it was analysed from — otherwise it alone would start somewhere slightly
26+ * different from the others.
27+ *
28+ * A model whose `init` calls `randnfun3` (all of the shipped ones do) draws its
29+ * perturbation from a Fourier series on the surface's bounding box instead, and
30+ * that needs no projection: it is a function of space, evaluated wherever it is
31+ * asked, so one coefficient table *is* one field on every variant's grid. It
32+ * still has to be drawn once rather than per session — see `sharedModes`.
33+ */
34+import { lmIndex, nlmCalc } from '../sht/layout.ts';
35+import { seededNoise } from '../mgpu/noise.ts';
36+import type { ModelSession } from '../mgpu/session.ts';
37+
38+/**
39+ * Re-index coefficients from a band limit into a wider one's layout, zero-
40+ * filling the degrees the source does not have. Both layouts are SHTNS
41+ * m-major with mmax = lmax, so nothing but the index mapping changes.
42+ */
43+export function prolongCoeffs(
44+ q: Float32Array,
45+ lmaxFrom: number,
46+ lmaxTo: number,
47+): Float32Array {
48+ if (lmaxTo === lmaxFrom) return q;
49+ if (lmaxTo < lmaxFrom) {
50+ throw new Error(`prolongCoeffs: cannot widen ${lmaxFrom} into a smaller ${lmaxTo}`);
51+ }
52+ const out = new Float32Array(2 * nlmCalc(lmaxTo, lmaxTo));
53+ for (let m = 0; m <= lmaxFrom; m++) {
54+ for (let l = m; l <= lmaxFrom; l++) {
55+ const from = 2 * lmIndex(lmaxFrom, l, m);
56+ const to = 2 * lmIndex(lmaxTo, l, m);
57+ out[to] = q[from];
58+ out[to + 1] = q[from + 1];
59+ }
60+ }
61+ return out;
62+}
63+
64+/**
65+ * The same band-limited perturbation, sampled on each session's grid. Order
66+ * follows `sessions`. Nothing may be in flight on any session's transform
67+ * plan — the one-off analys/synth here use the plan's own scratch buffers.
68+ */
69+export async function sharedNoise(
70+ sessions: ModelSession[],
71+ amp: number,
72+ seed: number,
73+): Promise<Float32Array[]> {
74+ let base = sessions[0];
75+ for (const s of sessions) if (s.cfg.lmax < base.cfg.lmax) base = s;
76+ const coeffs = await base.sht.analys(seededNoise(base.npts, amp, seed));
77+ const out: Float32Array[] = [];
78+ for (const s of sessions) {
79+ out.push(await s.sht.synth(prolongCoeffs(coeffs, base.cfg.lmax, s.cfg.lmax)));
80+ }
81+ return out;
82+}
83+
84+/**
85+ * The random field every variant seeds from, drawn once — from `reference`,
86+ * whose numbers the study quotes — or null for a model that does not call
87+ * `randnfun3`.
88+ *
89+ * One table for all of them is not merely an economy (the draw is interpreter
90+ * time, and at a fine wavelength seconds of it). Each session would otherwise
91+ * draw from *its own* bounding box, and a box comes from grid samples of the
92+ * surface: at different lmax those differ in the last digits, and the draw is
93+ * sensitive to the box — a different mode count consumes the RNG differently
94+ * and the fields stop being the same one. Drawing once removes the question.
95+ */
96+export function sharedModes(
97+ reference: ModelSession,
98+ seed: number,
99+): Promise<Float32Array | null> {
100+ return reference.drawSeedModes(seed);
101+}
src/compare/variants.tsadded+81−0View file
@@ -0,0 +1,81 @@
1+/**
2+ * One point of a convergence study: a choice of the three knobs that decide
3+ * *how well* the same problem is being solved, rather than what the problem is.
4+ *
5+ * niter iterations of the implicit solve (structural — it unrolls into the
6+ * compiled step, so each value is its own compiled session)
7+ * lmax the spectral band, and with it the grid (also structural)
8+ * dtDiv the timestep, as an integer divisor of the model's own dt
9+ *
10+ * dt is a *divisor* rather than a free value on purpose, and it is the whole
11+ * reason the comparison can be trusted: variants have to be compared at the
12+ * same model time, and with dt = dtBase/K every variant lands exactly on the
13+ * same t after K times as many steps — no rounding, no drift, no interpolation
14+ * in time. A free dt would put each variant on its own timeline and every
15+ * difference reported would be part real and part "these are 0.003 apart".
16+ */
17+
18+export interface Variant {
19+ /** Iterations of the implicit solve. */
20+ niter: number;
21+ /** Spectral band limit. */
22+ lmax: number;
23+ /** Timestep divisor: this variant runs at dtBase / dtDiv. */
24+ dtDiv: number;
25+}
26+
27+/** Stable identity of a variant, for keying maps and the reference <select>. */
28+export const variantKey = (v: Variant): string => `${v.niter}/${v.lmax}/${v.dtDiv}`;
29+
30+/** Human label. The dt term is dropped when nothing varies it, so the common
31+ * case (niter x lmax) reads as just those two. */
32+export const variantLabel = (v: Variant, showDt: boolean): string =>
33+ `niter ${v.niter} · lmax ${v.lmax}` + (showDt ? ` · dt/${v.dtDiv}` : '');
34+
35+/**
36+ * Every combination of the selected values, in a stable order: coarsest first,
37+ * so the grid reads top-to-bottom from least to most resolved and the
38+ * reference (the last row) is the one everything is measured against.
39+ */
40+export function crossProduct(
41+ niters: number[],
42+ lmaxes: number[],
43+ dtDivs: number[],
44+): Variant[] {
45+ const out: Variant[] = [];
46+ for (const lmax of [...lmaxes].sort((a, b) => a - b)) {
47+ for (const dtDiv of [...dtDivs].sort((a, b) => a - b)) {
48+ for (const niter of [...niters].sort((a, b) => a - b)) {
49+ out.push({ niter, lmax, dtDiv });
50+ }
51+ }
52+ }
53+ return out;
54+}
55+
56+/**
57+ * Index of the most-resolved variant: the natural reference, since it is the
58+ * one every other choice is an approximation of. Finer band first (it bounds
59+ * what can be represented at all), then more solve iterations, then smaller
60+ * timestep.
61+ */
62+export function mostResolved(variants: Variant[]): number {
63+ let best = 0;
64+ for (let i = 1; i < variants.length; i++) {
65+ const a = variants[i];
66+ const b = variants[best];
67+ if (
68+ a.lmax > b.lmax ||
69+ (a.lmax === b.lmax && a.niter > b.niter) ||
70+ (a.lmax === b.lmax && a.niter === b.niter && a.dtDiv > b.dtDiv)
71+ ) {
72+ best = i;
73+ }
74+ }
75+ return best;
76+}
77+
78+/** Distinguishable line/label colors, one per variant row. */
79+export const VARIANT_COLORS = [
80+ '#0969da', '#bf8700', '#1a7f37', '#cf222e', '#8250df', '#0f7c8a',
81+];
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+230−143View file
@@ -6,9 +6,13 @@
66 *
77 * function [gx, gy, gz] = shape(theta, phi, <parameters>)
88 *
9- * over the solver's (theta, phi) grid — the same element-wise MATLAB the models
10- * are written in, compiled by the same backend into the same kind of WGSL
11- * kernel. It is evaluated once, on the CPU's behalf, and then *analysed*: the
9+ * over the solver's (theta, phi) grid. Unlike the models it is *not* compiled
10+ * to WGSL: a model's step runs every frame and must lower to a fixed sequence
11+ * of GPU dispatches, but a shape is evaluated exactly once at build time and
12+ * survives only as coefficients. So it runs through numbl's CPU interpreter
13+ * instead, which buys the full MATLAB subset — loops, arrays, reductions,
14+ * `legendre`, seeded randomness via `rng`/`randn` — and f64 evaluation, where
15+ * the step dialect is element-wise f32. The result is then *analysed*: the
1216 * canonical geometry this project carries is the three sets of coefficients
1317 * `X`, `Y`, `Z`, one per Cartesian component of the embedding.
1418 *
@@ -28,20 +32,25 @@
2832 * The unit sphere is the case where `x`, `y`, `z` are pure degree-1 harmonics
2933 * and everything downstream reduces to turing-sphere.
3034 */
35+import { parseMFile, type FunctionStmt } from 'numbl-src/numbl-core/parser/index.ts';
36+import { executeCode } from 'numbl-src/numbl-core/executeCode.ts';
37+import {
38+ RuntimeTensor,
39+ isRuntimeTensor,
40+ type RuntimeValue,
41+} from 'numbl-src/numbl-core/runtime/types.ts';
3142 import { ShtPlan } from '../sht/sht.ts';
3243 import type { ShtConfig } from '../sht/layout.ts';
3344 import type { DerivPlan } from '../sht/deriv.ts';
3445 import { computeMetric, computeFluxMetric } from './metric.ts';
35-import { HostBuffers, ModelPlan } from '../mgpu/plan.ts';
36-import { CompiledModel, type Binding } from '../mgpu/compile.ts';
37-import { inFunction, inFunctionAsync, inModel } from '../mgpu/errors.ts';
46+import { toolFiles } from '../tools.ts';
47+import { inFunction, inModel, ModelCompileError } from '../mgpu/errors.ts';
3848 import type { ModelParams } from '../mgpu/model.ts';
3949
4050 /** The function a geometry file must define. */
4151 export const SHAPE_FN = 'shape';
4252
4353 export interface GeometryOptions {
44- device: GPUDevice;
4554 /** The solver's transform plan — the grid the shape is evaluated on. */
4655 sht: ShtPlan;
4756 cfg: ShtConfig;
@@ -85,6 +94,27 @@ export class Geometry {
8594 readonly p2: Float32Array;
8695 readonly q2: Float32Array;
8796 readonly r: Float32Array;
97+ /**
98+ * The same flux weights with the round sphere subtracted off, plus the
99+ * bounded 1/J — what lets a model evaluate lap_g without ever multiplying
100+ * the *whole* flux divergence by r ~ 1/sin^2(theta). Writing p1 = 1 + dp1,
101+ * q2 = 1 + dq2 (p2 is already a pure deviation, zero on the sphere) splits
102+ * the divergence into a round-sphere part, whose cancelling bracket
103+ * sin(theta) dtheta(A) + dphi(B) = -sin^2(theta) lap_s u is known exactly in
104+ * spectral space, and a remainder:
105+ *
106+ * lap_g u = -jinv * lap_s u + r * (sin(theta) dtheta(P') + dphi(Q'))
107+ *
108+ * with P' = dp1*A + p2*B, Q' = p2*A + dq2*B. Only the remainder meets the
109+ * concentrated division, so the polar roundoff gain drops by |P'|/|P|
110+ * instead of applying to the full flux. Subtracting 1 in f64 here is the
111+ * point: on a near-sphere dp1 is the small quantity, and forming it as an
112+ * f32 difference in the .m would lose it. See docs/reduced-transforms.md
113+ * Sec 5 and models/schnakenberg.m.
114+ */
115+ readonly dp1: Float32Array;
116+ readonly dq2: Float32Array;
117+ readonly jinv: Float32Array;
88118 /**
89119 * Preconditioner scale for the implicit solve (docs/reduced-transforms.md
90120 * Sec 10). At high degree the Richardson iteration's per-mode factor is
@@ -120,6 +150,7 @@ export class Geometry {
120150 Vtx: Float32Array; Vty: Float32Array; Vtz: Float32Array;
121151 Vpx: Float32Array; Vpy: Float32Array; Vpz: Float32Array;
122152 p1: Float32Array; p2: Float32Array; q2: Float32Array; r: Float32Array;
153+ dp1: Float32Array; dq2: Float32Array; jinv: Float32Array;
123154 Jhat: number; muMin: number; muMax: number; Jmin: number; Jmax: number;
124155 }) {
125156 this.x = init.x;
@@ -138,6 +169,9 @@ export class Geometry {
138169 this.p2 = init.p2;
139170 this.q2 = init.q2;
140171 this.r = init.r;
172+ this.dp1 = init.dp1;
173+ this.dq2 = init.dq2;
174+ this.jinv = init.jinv;
141175 this.Jhat = init.Jhat;
142176 this.muMin = init.muMin;
143177 this.muMax = init.muMax;
@@ -146,125 +180,99 @@ export class Geometry {
146180 }
147181
148182 /**
149- * Compile the shape file, evaluate it once on the solver grid, and reduce it
150- * to coefficients. Everything here happens at build time — a geometry never
151- * takes part in the timestep — so it reads back through the CPU freely.
183+ * Evaluate the shape file once on the solver grid and reduce it to
184+ * coefficients. Everything here happens at build time — a geometry never
185+ * takes part in the timestep — so the .m runs on the CPU (see
186+ * `evaluateShape`) and only the analysis onward touches the GPU.
152187 */
153188 static async create(opts: GeometryOptions): Promise<Geometry> {
154- const { device, sht, cfg, source, paramNames, params, deriv } = opts;
189+ const { sht, cfg, source, paramNames, params, deriv } = opts;
155190 const npts = cfg.nlat * cfg.nphi;
156- const nlm = sht.nlm;
157-
158- const bindings: Record<string, Binding> = {
159- theta: { kind: 'tensor', shape: [npts, 1] },
160- phi: { kind: 'tensor', shape: [npts, 1] },
161- npts: { kind: 'const', value: npts },
162- };
163- for (const p of paramNames) bindings[p] = { kind: 'param' };
164-
165- const compiled = inModel(() => new CompiledModel(source, bindings, { npts, nlm }));
166- const fn = inFunction(SHAPE_FN, () => compiled.specialize(SHAPE_FN, 3));
167- compiled.finish();
168-
169- const host = new HostBuffers(device);
170- host.ensure('theta', npts);
171- host.ensure('phi', npts);
172-
173- const plan = await inFunctionAsync(SHAPE_FN, () =>
174- // Nothing feeds back: the three outputs are read once and the plan is
175- // thrown away.
176- ModelPlan.create(device, sht, { fn, feedback: [null, null, null] }, host),
177- );
178-
179- try {
180- const { theta, phi } = gridAngles(sht, cfg);
181- host.upload('theta', theta);
182- host.upload('phi', phi);
183- plan.setParams(params);
184191
185- const enc = device.createCommandEncoder({ label: 'geometry-shape' });
186- plan.encodeSteps(enc, 1);
187- device.queue.submit([enc.finish()]);
192+ const { theta, phi } = gridAngles(sht, cfg);
193+ const raw = evaluateShape(source, paramNames, params, theta, phi, npts);
188194
189- const raw = await Promise.all(
190- fn.outputs.map((out) => readBuffer(device, plan, out.name, npts)),
191- );
192- // Coefficients first, then back to the grid: what the solver and the
193- // renderer both see is the band-limited surface, not the raw .m output.
194- const [X, Y, Z] = [
195- await sht.analys(raw[0]),
196- await sht.analys(raw[1]),
197- await sht.analys(raw[2]),
198- ];
199- const [x, y, z] = [
200- await sht.synth(X),
201- await sht.synth(Y),
202- await sht.synth(Z),
203- ];
195+ // Coefficients first, then back to the grid: what the solver and the
196+ // 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+ const [x, y, z] = [
203+ await sht.synth(X),
204+ await sht.synth(Y),
205+ await sht.synth(Z),
206+ ];
204207
205- // Inverse metric quantities (algos.tex Algorithm 2): theta/phi
206- // derivatives of the embedding's coefficients, contracted through the
207- // inverse first fundamental form. Depends only on the geometry, so
208- // this is a one-off alongside x,y,z above, not per-step work.
209- const Xt = await deriv.dtheta(X);
210- const Xp = await deriv.dphi(X);
211- const Yt = await deriv.dtheta(Y);
212- const Yp = await deriv.dphi(Y);
213- const Zt = await deriv.dtheta(Z);
214- const Zp = await deriv.dphi(Z);
215- const { Vtx, Vty, Vtz, Vpx, Vpy, Vpz } = computeMetric(npts, Xt, Xp, Yt, Yp, Zt, Zp);
208+ // Inverse metric quantities (algos.tex Algorithm 2): theta/phi
209+ // derivatives of the embedding's coefficients, contracted through the
210+ // inverse first fundamental form. Depends only on the geometry, so
211+ // this is a one-off alongside x,y,z above, not per-step work.
212+ const Xt = await deriv.dtheta(X);
213+ const Xp = await deriv.dphi(X);
214+ const Yt = await deriv.dtheta(Y);
215+ const Yp = await deriv.dphi(Y);
216+ const Zt = await deriv.dtheta(Z);
217+ const Zp = await deriv.dphi(Z);
218+ const { Vtx, Vty, Vtz, Vpx, Vpy, Vpz } = computeMetric(npts, Xt, Xp, Yt, Yp, Zt, Zp);
216219
217- // Flux-form metric weights for the six-transform scheme, built from the
218- // *undivided* theta tangents sin(theta)*X_theta (smooth on the sphere,
219- // unlike X_theta itself) and the same X_phi as above. Also a one-off;
220- // the f64 combination happens on the CPU, rounded to f32 for upload.
221- const sXtx = await deriv.sinDtheta(X);
222- const sXty = await deriv.sinDtheta(Y);
223- const sXtz = await deriv.sinDtheta(Z);
224- const flux = computeFluxMetric(npts, sXtx, sXty, sXtz, Xp, Yp, Zp);
220+ // Flux-form metric weights for the six-transform scheme, built from the
221+ // *undivided* theta tangents sin(theta)*X_theta (smooth on the sphere,
222+ // unlike X_theta itself) and the same X_phi as above. Also a one-off;
223+ // the f64 combination happens on the CPU, rounded to f32 for upload.
224+ const sXtx = await deriv.sinDtheta(X);
225+ const sXty = await deriv.sinDtheta(Y);
226+ const sXtz = await deriv.sinDtheta(Z);
227+ const flux = computeFluxMetric(npts, sXtx, sXty, sXtz, Xp, Yp, Zp);
225228
226- // The preconditioner scale — see the Jhat field comment. The symbol
227- // matrix in the orthonormal frame is S = (1/J)[[p1,p2],[p2,q2]] with
228- // 1/J = r sin^2(theta); its entries are the bounded quantities
229- // g^tt, sin g^tp, sin^2 g^pp, so the eigenvalue extremes are clean to
230- // take over the grid. det S = 1/J^2, so the area factor comes along
231- // for free. f64 throughout.
232- let muMin = Infinity;
233- let muMax = 0;
234- let Jmin = Infinity;
235- let Jmax = 0;
236- for (let i = 0; i < cfg.nlat; i++) {
237- const ct = sht.cosTheta[i];
238- const st2 = Math.max(0, 1 - ct * ct);
239- for (let j = 0; j < cfg.nphi; j++) {
240- const k = i * cfg.nphi + j;
241- const invJ = flux.r[k] * st2;
242- const s11 = flux.p1[k] * invJ;
243- const s12 = flux.p2[k] * invJ;
244- const s22 = flux.q2[k] * invJ;
245- const mean = (s11 + s22) / 2;
246- const disc = Math.sqrt(((s11 - s22) / 2) ** 2 + s12 * s12);
247- if (mean - disc < muMin) muMin = mean - disc;
248- if (mean + disc > muMax) muMax = mean + disc;
249- const J = 1 / invJ;
250- if (J < Jmin) Jmin = J;
251- if (J > Jmax) Jmax = J;
252- }
229+ // The preconditioner scale — see the Jhat field comment. The symbol
230+ // matrix in the orthonormal frame is S = (1/J)[[p1,p2],[p2,q2]] with
231+ // 1/J = r sin^2(theta); its entries are the bounded quantities
232+ // g^tt, sin g^tp, sin^2 g^pp, so the eigenvalue extremes are clean to
233+ // take over the grid. det S = 1/J^2, so the area factor comes along
234+ // for free. f64 throughout.
235+ let muMin = Infinity;
236+ let muMax = 0;
237+ let Jmin = Infinity;
238+ let Jmax = 0;
239+ // The sphere-subtracted weights ride along on this loop: 1/J is already
240+ // being formed here, and dp1/dq2 want the same f64 arithmetic.
241+ const dp1 = new Float32Array(npts);
242+ const dq2 = new Float32Array(npts);
243+ const jinv = new Float32Array(npts);
244+ for (let i = 0; i < cfg.nlat; i++) {
245+ const ct = sht.cosTheta[i];
246+ const st2 = Math.max(0, 1 - ct * ct);
247+ for (let j = 0; j < cfg.nphi; j++) {
248+ const k = i * cfg.nphi + j;
249+ const invJ = flux.r[k] * st2;
250+ dp1[k] = flux.p1[k] - 1;
251+ dq2[k] = flux.q2[k] - 1;
252+ jinv[k] = invJ;
253+ const s11 = flux.p1[k] * invJ;
254+ const s12 = flux.p2[k] * invJ;
255+ const s22 = flux.q2[k] * invJ;
256+ const mean = (s11 + s22) / 2;
257+ const disc = Math.sqrt(((s11 - s22) / 2) ** 2 + s12 * s12);
258+ if (mean - disc < muMin) muMin = mean - disc;
259+ if (mean + disc > muMax) muMax = mean + disc;
260+ const J = 1 / invJ;
261+ if (J < Jmin) Jmin = J;
262+ if (J > Jmax) Jmax = J;
253263 }
254- const Jhat = 2 / (muMin + muMax);
255-
256- return new Geometry({
257- x, y, z, X, Y, Z, Vtx, Vty, Vtz, Vpx, Vpy, Vpz,
258- p1: new Float32Array(flux.p1),
259- p2: new Float32Array(flux.p2),
260- q2: new Float32Array(flux.q2),
261- r: new Float32Array(flux.r),
262- Jhat, muMin, muMax, Jmin, Jmax,
263- });
264- } finally {
265- plan.destroy();
266- host.destroy();
267264 }
265+ const Jhat = 2 / (muMin + muMax);
266+
267+ return new Geometry({
268+ x, y, z, X, Y, Z, Vtx, Vty, Vtz, Vpx, Vpy, Vpz,
269+ p1: new Float32Array(flux.p1),
270+ p2: new Float32Array(flux.p2),
271+ q2: new Float32Array(flux.q2),
272+ r: new Float32Array(flux.r),
273+ dp1, dq2, jinv,
274+ Jhat, muMin, muMax, Jmin, Jmax,
275+ });
268276 }
269277
270278 /**
@@ -300,14 +308,15 @@ export class Geometry {
300308 }
301309 }
302310
303-/** The (theta, phi) of every grid point, flattened phi-fastest as the fields are. */
311+/** The (theta, phi) of every grid point, flattened phi-fastest as the fields
312+ * are — in f64, the precision the shape is evaluated at. */
304313 function gridAngles(
305314 sht: ShtPlan,
306315 cfg: ShtConfig,
307-): { theta: Float32Array; phi: Float32Array } {
316+): { theta: Float64Array; phi: Float64Array } {
308317 const { nlat, nphi } = cfg;
309- const theta = new Float32Array(nlat * nphi);
310- const phi = new Float32Array(nlat * nphi);
318+ const theta = new Float64Array(nlat * nphi);
319+ const phi = new Float64Array(nlat * nphi);
311320 for (let i = 0; i < nlat; i++) {
312321 const th = Math.acos(Math.max(-1, Math.min(1, sht.cosTheta[i])));
313322 for (let j = 0; j < nphi; j++) {
@@ -318,30 +327,108 @@ function gridAngles(
318327 return { theta, phi };
319328 }
320329
321-async function readBuffer(
322- device: GPUDevice,
323- plan: ModelPlan,
330+/**
331+ * Evaluate the shape file on the grid, through numbl's CPU interpreter.
332+ *
333+ * The .m keeps the same contract it had as a compiled model: it names the
334+ * arguments it wants — `theta`, `phi`, and any of the registry's parameters —
335+ * and the host supplies them by name, so their order in the signature is the
336+ * .m's own business. A one-line driver script calls `shape` with exactly the
337+ * arguments its signature declares, with those names pre-bound in the
338+ * driver's workspace.
339+ */
340+function evaluateShape(
341+ source: string,
342+ paramNames: string[],
343+ params: ModelParams,
344+ theta: Float64Array,
345+ phi: Float64Array,
346+ npts: number,
347+): [Float32Array, Float32Array, Float32Array] {
348+ const file = `${SHAPE_FN}.m`;
349+ const ast = inModel(() => parseMFile(source, file));
350+ const fn = ast.body.find(
351+ (s): s is FunctionStmt =>
352+ s.type === 'Function' && (s as FunctionStmt).name === SHAPE_FN,
353+ );
354+ if (!fn) {
355+ throw new ModelCompileError(
356+ `the geometry defines no function named '${SHAPE_FN}'`,
357+ );
358+ }
359+ if (fn.outputs.length !== 3) {
360+ throw new ModelCompileError(
361+ `'${SHAPE_FN}' must return three outputs [gx, gy, gz], not ${fn.outputs.length}`,
362+ { fn: SHAPE_FN, start: fn.span.start, end: fn.span.end },
363+ );
364+ }
365+ const known = new Set(['theta', 'phi', ...paramNames]);
366+ for (const p of fn.params) {
367+ if (!known.has(p)) {
368+ throw new ModelCompileError(
369+ `'${SHAPE_FN}' takes an argument '${p}' that is neither the grid ` +
370+ `(theta, phi) nor one of this geometry's parameters` +
371+ (paramNames.length ? ` (${paramNames.join(', ')})` : ''),
372+ { fn: SHAPE_FN, start: fn.span.start, end: fn.span.end },
373+ );
374+ }
375+ }
376+
377+ const vars: Record<string, RuntimeValue> = {
378+ theta: new RuntimeTensor(theta, [npts, 1]),
379+ phi: new RuntimeTensor(phi, [npts, 1]),
380+ };
381+ for (const name of paramNames) {
382+ const v = params[name];
383+ // Missing parameters read as 0, as ModelPlan.setParams has it.
384+ vars[name] = Number.isFinite(v) ? v : 0;
385+ }
386+
387+ const driver = `[gx__, gy__, gz__] = ${SHAPE_FN}(${fn.params.join(', ')});`;
388+ const result = inFunction(SHAPE_FN, () =>
389+ executeCode(
390+ driver,
391+ { initialVariableValues: vars, displayResults: false, implicitCwdPath: null },
392+ [...toolFiles, { name: file, source }],
393+ 'geometry-driver.m',
394+ ),
395+ );
396+
397+ return [
398+ toGridField(result.variableValues['gx__'], fn.outputs[0], npts),
399+ toGridField(result.variableValues['gy__'], fn.outputs[1], npts),
400+ toGridField(result.variableValues['gz__'], fn.outputs[2], npts),
401+ ];
402+}
403+
404+/** One returned coordinate → npts values, rounded to the transforms' f32. */
405+function toGridField(
406+ value: RuntimeValue | undefined,
324407 name: string,
325- count: number,
326-): Promise<Float32Array> {
327- const buffer = plan.buffer(name);
328- if (!buffer) {
329- throw new Error(`the geometry never assigns '${name}'`);
408+ npts: number,
409+): Float32Array {
410+ // A constant coordinate stays scalar in MATLAB; spread it over the grid.
411+ if (typeof value === 'number') return new Float32Array(npts).fill(value);
412+ if (value !== undefined && isRuntimeTensor(value)) {
413+ if (value.imag) {
414+ throw new ModelCompileError(
415+ `the geometry's '${name}' is complex; coordinates must be real`,
416+ { fn: SHAPE_FN },
417+ );
418+ }
419+ // A vector of npts values, either orientation. A 2-D reshape is refused
420+ // rather than reordered: the tensor's column-major layout would not match
421+ // the grid's phi-fastest rows.
422+ if (value.data.length === npts && value.shape.every((d) => d === 1 || d === npts)) {
423+ return new Float32Array(value.data);
424+ }
425+ throw new ModelCompileError(
426+ `the geometry's '${name}' is ${value.shape.join(' x ')}, but the grid ` +
427+ `wants one value per point (${npts} x 1)`,
428+ { fn: SHAPE_FN },
429+ );
330430 }
331- const staging = device.createBuffer({
332- label: `geometry-read-${name}`,
333- size: 4 * count,
334- usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
431+ throw new ModelCompileError(`the geometry's '${name}' is not numeric`, {
432+ fn: SHAPE_FN,
335433 });
336- try {
337- const enc = device.createCommandEncoder({ label: `geometry-read-${name}` });
338- enc.copyBufferToBuffer(buffer, 0, staging, 0, 4 * count);
339- device.queue.submit([enc.finish()]);
340- await staging.mapAsync(GPUMapMode.READ);
341- const out = new Float32Array(staging.getMappedRange().slice(0));
342- staging.unmap();
343- return out;
344- } finally {
345- staging.destroy();
346- }
347434 }
src/geom/registry.tsmodified+14−1View file
@@ -13,6 +13,7 @@ import sphereSource from '../../geometries/sphere.m?raw';
1313 import ellipsoidSource from '../../geometries/ellipsoid.m?raw';
1414 import peanutSource from '../../geometries/peanut.m?raw';
1515 import bumpySource from '../../geometries/bumpy.m?raw';
16+import blobSource from '../../geometries/blob.m?raw';
1617 import type { ParamSpec, Params } from '../mgpu/registry.ts';
1718
1819 export interface MGeometry {
@@ -67,7 +68,19 @@ const bumpy: MGeometry = {
6768 source: bumpySource,
6869 };
6970
70-export const mGeometries: MGeometry[] = [sphere, ellipsoid, peanut, bumpy];
71+const blob: MGeometry = {
72+ key: 'blob',
73+ label: 'Blob',
74+ blurb: 'The sphere warped by a smooth random function — a fresh shape per seed.',
75+ params: [
76+ { key: 'amp', label: 'amp', value: 0.5, min: 0, max: 0.8, step: 0.05 },
77+ { key: 'scale', label: 'λ', value: 1, min: 0.5, max: 3, step: 0.1 },
78+ { key: 'seed', label: 'seed', value: 1, min: 0, max: 9999, step: 1, reseed: true },
79+ ],
80+ source: blobSource,
81+};
82+
83+export const mGeometries: MGeometry[] = [sphere, ellipsoid, peanut, bumpy, blob];
7184
7285 export const mGeometryByKey = (key: string): MGeometry | undefined =>
7386 mGeometries.find((g) => g.key === key);
src/main.tsmodified+743−29View file
@@ -8,6 +8,7 @@ import { CodeEditor } from './editor/codeEditor.ts';
88 import {
99 formatCommand,
1010 resolvePreset,
11+ DEFAULT_NITER,
1112 DEFAULT_STEPS,
1213 DEFAULT_WARMUP,
1314 type RunSpec,
@@ -16,7 +17,6 @@ import {
1617 mGeometries,
1718 mGeometryByKey,
1819 defaultGeometryParams,
19- SPHERE_KEY,
2020 DEFAULT_GEOMETRY_KEY,
2121 type MGeometry,
2222 } from './geom/registry.ts';
@@ -28,9 +28,20 @@ import {
2828 type SphereMeshTopology,
2929 } from './render/sphereMesh.ts';
3030 import { SphereScene } from './render/SphereScene.ts';
31-import { Colorbar, fmtValue } from './render/colorbar.ts';
31+import { Colorbar, fmtValue, floorRange } from './render/colorbar.ts';
3232 import { colormaps, colormapNames } from './render/colormaps.ts';
3333 import { MovieRecorder } from './render/movie.ts';
34+import { CompareRun } from './compare/compareRun.ts';
35+import {
36+ crossProduct,
37+ mostResolved,
38+ variantKey,
39+ variantLabel,
40+ type Variant,
41+} from './compare/variants.ts';
42+import { loadReferenceFile } from './compare/referenceFile.ts';
43+import type { ReferenceCase } from './compare/referenceCase.ts';
44+import { generateMatlabScript, MATLAB_SCRIPT_NAME } from './export/matlabScript.ts';
3445
3546 const $ = <T extends HTMLElement>(id: string): T =>
3647 document.getElementById(id) as T;
@@ -43,8 +54,10 @@ const elLmax = $<HTMLSelectElement>('lmax');
4354 const elOversample = $<HTMLSelectElement>('oversample');
4455 const elColormap = $<HTMLSelectElement>('colormap');
4556 const elRunPause = $<HTMLButtonElement>('runpause');
57+const elRestart = $<HTMLButtonElement>('restart');
4658 const elBenchmark = $<HTMLButtonElement>('benchmark');
4759 const elReseed = $<HTMLButtonElement>('reseed');
60+const elLam3 = $<HTMLInputElement>('lam3');
4861 const elResetView = $<HTMLButtonElement>('resetview');
4962 const elMovieToggle = $<HTMLButtonElement>('movietoggle');
5063 const elMovieBar = $('moviebar');
@@ -52,6 +65,20 @@ const elMovieSpeed = $<HTMLSelectElement>('moviespeed');
5265 const elMovieRes = $<HTMLSelectElement>('movieres');
5366 const elMovieRotate = $<HTMLInputElement>('movierotate');
5467 const elMovie = $<HTMLButtonElement>('movie');
68+const elModeSimulate = $<HTMLButtonElement>('mode-simulate');
69+const elModeEffort = $<HTMLButtonElement>('mode-effort');
70+const elModeVsUpload = $<HTMLButtonElement>('mode-vs-upload');
71+const elModeDesc = $('mode-desc');
72+const elCompareBar = $('comparebar');
73+const elCmpNiter = $('cmp-niter');
74+const elCmpLmax = $('cmp-lmax');
75+const elCmpDt = $('cmp-dt');
76+const elCmpRef = $<HTMLSelectElement>('cmp-ref');
77+const elCmpFile = $<HTMLInputElement>('cmp-file');
78+const elCmpFileInfo = $('cmp-fileinfo');
79+const elCmpFileClear = $<HTMLButtonElement>('cmp-fileclear');
80+const elCmpStart = $<HTMLButtonElement>('cmp-start');
81+const elCmpCount = $('cmp-count');
5582 const elParams = $('params');
5683 const elGeomParams = $('geomparams');
5784 const elGeomNote = $('geomnote');
@@ -60,6 +87,10 @@ const elStats = $('stats');
6087 const elBenchResult = $('benchresult');
6188 const elCmd = $('cmd');
6289 const elCopyCmd = $<HTMLButtonElement>('copycmd');
90+const elMatlab = $<HTMLDetailsElement>('matlab');
91+const elMatlabScript = $('matlabscript');
92+const elCopyMatlab = $<HTMLButtonElement>('copymatlab');
93+const elDownloadMatlab = $<HTMLButtonElement>('downloadmatlab');
6394 const elBlurb = $('blurb');
6495 const elErr = $('err');
6596 const elSource = $<HTMLTextAreaElement>('source');
@@ -70,6 +101,21 @@ const elEditorFile = $<HTMLSelectElement>('editor-file');
70101 const elRecompile = $<HTMLButtonElement>('recompile');
71102 const elRevert = $<HTMLButtonElement>('revert');
72103
104+/** The named groups the control area is organized into (index.html's
105+ * `.ctrl-group[data-group]` wrappers). Each mode shows a declared subset of
106+ * these — see MODE_GROUPS and applyModeVisibility below. */
107+const GROUP_NAMES = [
108+ 'surface', 'surface-params', 'solver', 'display',
109+ 'playback', 'benchmark', 'seed', 'movie',
110+] as const;
111+type GroupName = (typeof GROUP_NAMES)[number];
112+const groupEls: Record<GroupName, HTMLElement> = Object.fromEntries(
113+ GROUP_NAMES.map((name) => [
114+ name,
115+ document.querySelector(`.ctrl-group[data-group="${name}"]`) as HTMLElement,
116+ ]),
117+) as Record<GroupName, HTMLElement>;
118+
73119 for (const p of presets) {
74120 const o = document.createElement('option');
75121 o.value = p.key;
@@ -233,6 +279,15 @@ let generation = 0; // bumped on every rebuild to cancel stale pumps
233279 * re-synthesizing. */
234280 let coords: Float32Array | null = null;
235281 let posBuf: Float32Array | null = null;
282+/** The convergence study, when one is running; null in ordinary single-run
283+ * mode. While it is non-null there is no `session`: the study owns one per
284+ * variant, and the panels area is its grid. */
285+let compareRun: CompareRun | null = null;
286+/** `session`'s spectral state as of the last (re-)seed — what "Restart"
287+ * rewinds to. Captured fresh each time a new field is actually established
288+ * (rebuild/reseed), not just once, so Restart reflects the run's current
289+ * starting point rather than permanently the very first draw. */
290+let initialState: Record<string, Float32Array> | null = null;
236291
237292 const source = (): string => editedSource ?? model.source;
238293 const geomSource = (): string => editedGeomSource ?? geometry.source;
@@ -240,6 +295,10 @@ const geomSource = (): string => editedGeomSource ?? geometry.source;
240295 // ---------------------------------------------------------------- UI wiring
241296 function buildParamInputs(): void {
242297 elParams.replaceChildren();
298+ if (model.params.length === 0) return;
299+ const tag = document.createElement('label');
300+ tag.textContent = 'model parameters';
301+ elParams.append(tag);
243302 for (const spec of model.params) {
244303 const label = document.createElement('label');
245304 label.textContent = `${spec.label} `;
@@ -253,8 +312,11 @@ function buildParamInputs(): void {
253312 const v = Number(input.value);
254313 if (Number.isFinite(v)) params[spec.key] = v;
255314 // Parameters are uniforms, not constants baked into the kernels, so a
256- // change costs an upload rather than a recompile.
315+ // change costs an upload rather than a recompile. In compare mode `dt`
316+ // is the *base* timestep each variant's divisor divides, so the study
317+ // re-derives every variant's dt from it.
257318 session?.setParams(params);
319+ compareRun?.setParams(params);
258320 updateCommand();
259321 });
260322 label.append(input);
@@ -272,9 +334,32 @@ function buildGeomParamInputs(): void {
272334 elGeomParams.replaceChildren();
273335 if (geometry.params.length === 0) return;
274336 const tag = document.createElement('label');
275- tag.textContent = `${geometry.key}.m`;
337+ tag.textContent = 'geometry parameters';
276338 elGeomParams.append(tag);
277339 for (const spec of geometry.params) {
340+ // A random seed picks a draw and means nothing on its own, so it gets a
341+ // button to the next one rather than a box to type a number into. The
342+ // shape changes; the simulation running on it does not restart.
343+ if (spec.reseed) {
344+ const button = document.createElement('button');
345+ button.textContent = 'Re-seed shape';
346+ button.title =
347+ `Draw another ${geometry.label.toLowerCase()} — a new random surface, ` +
348+ `leaving the pattern running on it alone.`;
349+ button.addEventListener('click', () => {
350+ const span = spec.max - spec.min;
351+ let next = geomParams[spec.key];
352+ // Never hand back the shape that is already on screen.
353+ while (next === geomParams[spec.key]) {
354+ next = spec.min + Math.floor(Math.random() * (span + 1));
355+ }
356+ geomParams[spec.key] = next;
357+ updateCommand();
358+ viewChange = viewChange.then(() => applyGeometry());
359+ });
360+ elGeomParams.append(button);
361+ continue;
362+ }
278363 const label = document.createElement('label');
279364 label.textContent = `${spec.label} `;
280365 const input = document.createElement('input');
@@ -286,6 +371,7 @@ function buildGeomParamInputs(): void {
286371 input.addEventListener('change', () => {
287372 const v = Number(input.value);
288373 if (Number.isFinite(v)) geomParams[spec.key] = v;
374+ updateCommand();
289375 viewChange = viewChange.then(() => applyGeometry());
290376 });
291377 label.append(input);
@@ -320,6 +406,8 @@ function applyGeometryChoice(key: string): void {
320406 editedGeomSource = null;
321407 buildGeomParamInputs();
322408 showEditorFile();
409+ // The command line and the MATLAB export both bake the surface in.
410+ updateCommand();
323411 }
324412
325413 /** Load the chosen file into the editor, keeping any unsaved edit to it. */
@@ -334,23 +422,70 @@ function showEditorFile(): void {
334422 }
335423 }
336424
337-/** The run currently on screen, as the benchmark's RunSpec. */
425+/**
426+ * The run currently on screen, as the benchmark's RunSpec. While a study is
427+ * running there is no single run, so this describes its *reference* variant —
428+ * the one the other rows are measured against, and the only one of them whose
429+ * numbers mean anything on their own.
430+ */
338431 function currentSpec(): RunSpec {
432+ const ref = compareRun?.variants[compareRefIndex()];
433+ const dt = ref ? { dt: (params.dt ?? 0) / ref.dtDiv } : null;
339434 return {
340435 preset: elModel.value,
341- lmax: Number(elLmax.value),
436+ lmax: ref ? ref.lmax : Number(elLmax.value),
342437 seed,
343438 steps: DEFAULT_STEPS,
344439 warmup: DEFAULT_WARMUP,
345- params,
440+ params: dt ? { ...params, ...dt } : params,
346441 geometry: geometry.key,
347442 geometryParams: geomParams,
348- niter: Number(elNiter.value),
443+ niter: ref ? ref.niter : Number(elNiter.value),
349444 };
350445 }
351446
352447 function updateCommand(): void {
353- elCmd.textContent = formatCommand(currentSpec());
448+ // A study against a reference file replays the file, so its desktop
449+ // equivalent is the ref checker, not the benchmark.
450+ if (compareRun?.refFile) {
451+ elCmd.textContent = `npm run ref -- --in ${compareRun.refFile.label}`;
452+ } else {
453+ elCmd.textContent = formatCommand(currentSpec());
454+ }
455+ if (elMatlab.open) refreshMatlabScript();
456+}
457+
458+/** The run on screen as one standalone .m — in a study, its reference
459+ * variant, the same choice `currentSpec` makes. Throws on a working copy
460+ * the export cannot parse (no init/step/shape function). */
461+function matlabScriptText(): string {
462+ const spec = currentSpec();
463+ return generateMatlabScript({
464+ model,
465+ modelSource: source(),
466+ params: spec.params,
467+ geometry,
468+ geometrySource: geomSource(),
469+ geometryParams: geomParams,
470+ lmax: spec.lmax,
471+ niter: spec.niter,
472+ lam3: Number(elLam3.value),
473+ seed,
474+ preset: spec.preset,
475+ command: formatCommand(spec),
476+ });
477+}
478+
479+/** Regenerate the visible script text; on failure, show why in its place. */
480+function refreshMatlabScript(): string | null {
481+ try {
482+ const text = matlabScriptText();
483+ elMatlabScript.textContent = text;
484+ return text;
485+ } catch (e) {
486+ elMatlabScript.textContent = e instanceof Error ? e.message : String(e);
487+ return null;
488+ }
354489 }
355490
356491 elModel.addEventListener('change', () => {
@@ -366,23 +501,69 @@ elNiter.addEventListener('change', () => void rebuild());
366501 // one chain: a rapid second change waits its turn.
367502 let viewChange = Promise.resolve();
368503 elOversample.addEventListener('change', () => {
504+ // The study picks its own display grid — one grid common to every variant is
505+ // what makes their fields comparable — so this control is inert (and
506+ // disabled) while one is running.
507+ if (compareRun) return;
369508 viewChange = viewChange.then(() => applyOversample());
370509 });
371510 elGeometry.addEventListener('change', () => {
372511 applyGeometryChoice(elGeometry.value);
373512 viewChange = viewChange.then(() => applyGeometry());
374513 });
514+// The seed field's wavelength: a uniform plus a host-side redraw, so it
515+// reseeds the run in place rather than recompiling it. Too small a value asks
516+// for more Fourier modes than the table holds, which `drawModes` refuses —
517+// report that like any other failure instead of leaving the run half-seeded.
518+elLam3.addEventListener('change', () => {
519+ const v = Number(elLam3.value);
520+ if (!Number.isFinite(v) || v <= 0) return;
521+ // Not in the bench command, but the MATLAB export bakes lam3 in.
522+ updateCommand();
523+ // Changing the wavelength redraws the field, which restarts the run — so
524+ // pause first, exactly as the Re-seed button does. Without it the reseed's
525+ // readback races the pump's own, and the two collide on the staging buffer.
526+ setRunning(false);
527+ viewChange = viewChange.then(async () => {
528+ // A study seeds every variant from one field at one wavelength, so this is
529+ // the same control there — set on each variant, redrawn by the one reseed.
530+ const target = compareRun ?? session;
531+ if (!target) return;
532+ const previous = target.lam3;
533+ try {
534+ target.setLam3(v);
535+ await reseed();
536+ elErr.textContent = '';
537+ } catch (e) {
538+ // Too fine a wavelength asks for more Fourier modes than the table
539+ // holds. Put the working value back rather than leaving the run seeded
540+ // from a field that was never drawn.
541+ elErr.textContent = e instanceof Error ? e.message : String(e);
542+ target.setLam3(previous);
543+ elLam3.value = String(previous);
544+ await reseed();
545+ }
546+ });
547+});
375548 // Morph is pure rendering: no readback, no GPU work, just the vertex buffer.
376549 elMorph.addEventListener('input', () => {
377550 morph = Number(elMorph.value);
378- applyMorph();
551+ if (compareRun) compareRun.setMorph(morph);
552+ else applyMorph();
553+});
554+elColormap.addEventListener('change', () => {
555+ if (compareRun) void compareRun.draw();
556+ else void draw();
379557 });
380-elColormap.addEventListener('change', () => void draw());
381558 elEditorFile.addEventListener('change', () => showEditorFile());
382559
383560 function setRunning(next: boolean): void {
384561 running = next;
385562 elRunPause.textContent = running ? 'Pause' : 'Run';
563+ if (compareRun) {
564+ compareRun.setRunning(next);
565+ return;
566+ }
386567 if (running) void pump();
387568 }
388569
@@ -394,7 +575,12 @@ elReseed.addEventListener('click', () => {
394575 updateCommand();
395576 void reseed();
396577 });
578+elRestart.addEventListener('click', () => {
579+ setRunning(false);
580+ void restart();
581+});
397582 elResetView.addEventListener('click', () => {
583+ compareRun?.resetView();
398584 for (const s of scenes) s.resetCamera();
399585 });
400586 elMovieToggle.addEventListener('click', () => {
@@ -437,6 +623,46 @@ elCopyCmd.addEventListener('click', () => {
437623 navigator.clipboard.writeText(text).then(() => flash('Copied'), selectCommand);
438624 });
439625
626+// The MATLAB export: the same run as one self-contained .m. Regenerated from
627+// the current UI state whenever it is shown, copied or downloaded, so the
628+// text always matches the run on screen.
629+elMatlab.addEventListener('toggle', () => {
630+ if (elMatlab.open) refreshMatlabScript();
631+});
632+elCopyMatlab.addEventListener('click', (e) => {
633+ // The buttons live inside the <summary>; without this a click also toggles.
634+ e.preventDefault();
635+ e.stopPropagation();
636+ const text = refreshMatlabScript();
637+ if (text === null || !navigator.clipboard) {
638+ // Open to show the error, or the text to select by hand.
639+ elMatlab.open = true;
640+ return;
641+ }
642+ navigator.clipboard.writeText(text).then(
643+ () => {
644+ elCopyMatlab.textContent = 'Copied';
645+ setTimeout(() => (elCopyMatlab.textContent = 'Copy'), 1200);
646+ },
647+ () => (elMatlab.open = true),
648+ );
649+});
650+elDownloadMatlab.addEventListener('click', (e) => {
651+ e.preventDefault();
652+ e.stopPropagation();
653+ const text = refreshMatlabScript();
654+ if (text === null) {
655+ elMatlab.open = true;
656+ return;
657+ }
658+ const url = URL.createObjectURL(new Blob([text], { type: 'text/x-matlab' }));
659+ const a = document.createElement('a');
660+ a.href = url;
661+ a.download = `${MATLAB_SCRIPT_NAME}.m`;
662+ a.click();
663+ URL.revokeObjectURL(url);
664+});
665+
440666 // ---------------------------------------------------------------- setup
441667 function disposeView(): void {
442668 for (const s of scenes) s.dispose();
@@ -547,6 +773,10 @@ async function applyOversample(): Promise<void> {
547773 * can be changed mid-run. Only the mesh is rebuilt.
548774 */
549775 async function applyGeometry(): Promise<void> {
776+ // The in-place swap below is a single session's trick. Each variant carries
777+ // the surface band-limited at its own lmax, and the study's meshes are built
778+ // from those, so a shape change goes through the full rebuild instead.
779+ if (compareRun) return rebuildCompare();
550780 if (!session) return;
551781 const gen = generation;
552782 const wasRunning = running;
@@ -581,18 +811,19 @@ function applyMorph(): void {
581811 for (const s of scenes) s.updatePositions(posBuf);
582812 }
583813
584-/** What the surface is, and the standing caveat about where it is not. */
814+/** What the surface is, and how far it departs from the sphere. */
585815 function updateGeomNote(): void {
586- if (!session) {
816+ // In compare mode each variant carries the surface band-limited at its own
817+ // lmax; the reference's is the one quoted, as everywhere else.
818+ const s = session ?? compareRun?.referenceSession ?? null;
819+ if (!s) {
587820 elGeomNote.textContent = '';
588821 return;
589822 }
590- const { lo, hi } = session.geometry.radiusRange();
591- const isSphere = session.geometryModel.key === SPHERE_KEY;
823+ const { lo, hi } = s.geometry.radiusRange();
592824 elGeomNote.innerHTML =
593- `<b>${session.geometryModel.label}</b> — ${session.geometryModel.blurb} ` +
594- `Radius ${lo.toFixed(3)}–${hi.toFixed(3)}.` +
595- (isSphere ? '' : ' <b>Rendered only</b> — not yet in the operator.');
825+ `<b>${s.geometryModel.label}</b> — ${s.geometryModel.blurb} ` +
826+ `Radius ${lo.toFixed(3)}–${hi.toFixed(3)}.`;
596827 }
597828
598829 /** Report a compile failure, and select the offending text in the editor. */
@@ -605,6 +836,10 @@ function reportCompileError(e: unknown): void {
605836 }
606837
607838 async function rebuild(): Promise<void> {
839+ // A study is several runs, so "rebuild the run" means rebuild all of them.
840+ // Everything that recompiles — a model or preset change, an edit to either
841+ // .m, a revert — arrives here, and none of it needs to know which mode is up.
842+ if (compareRun) return rebuildCompare();
608843 generation++;
609844 const gen = generation;
610845 setRunning(false);
@@ -635,6 +870,7 @@ async function rebuild(): Promise<void> {
635870 geometryParams: geomParams,
636871 geometrySource: geomSource(),
637872 niter: Number(elNiter.value),
873+ lam3: Number(elLam3.value),
638874 });
639875 } catch (e) {
640876 reportCompileError(e);
@@ -642,7 +878,10 @@ async function rebuild(): Promise<void> {
642878 }
643879 if (gen !== generation) return;
644880
645- session.seed(seed);
881+ await session.seed(seed);
882+ if (gen !== generation) return;
883+ initialState = await session.readState();
884+ if (gen !== generation) return;
646885
647886 const plan = session.describe();
648887 elCompiled.textContent =
@@ -670,9 +909,14 @@ async function rebuild(): Promise<void> {
670909 }
671910
672911 async function reseed(): Promise<void> {
912+ // One new perturbation for the whole study, band-limited at its coarsest
913+ // variant and evaluated on each grid — see src/compare/sharedStart.ts.
914+ if (compareRun) return compareRun.reseed(seed);
673915 if (!session) return;
674916 const gen = generation;
675- session.seed(seed);
917+ await session.seed(seed);
918+ if (gen !== generation) return;
919+ initialState = await session.readState();
676920 if (gen !== generation) return;
677921 for (const r of ranges) {
678922 r.lo = NaN;
@@ -682,6 +926,22 @@ async function reseed(): Promise<void> {
682926 updateStats();
683927 }
684928
929+/** Rewind to the field this run is currently starting from — the last
930+ * (re-)seed, not necessarily the very first one — without drawing a new
931+ * one. Unlike reseed(), the seed value and lam3 are untouched, so nothing
932+ * the CLI command line encodes changes. */
933+async function restart(): Promise<void> {
934+ if (compareRun) return compareRun.restart();
935+ if (!session || !initialState) return;
936+ session.loadState(initialState);
937+ for (const r of ranges) {
938+ r.lo = NaN;
939+ r.hi = NaN;
940+ }
941+ await draw();
942+ updateStats();
943+}
944+
685945 // ---------------------------------------------------------------- drawing
686946 async function draw(): Promise<void> {
687947 if (!session || !topo) return;
@@ -717,14 +977,13 @@ async function draw(): Promise<void> {
717977 r.lo += a * (lo - r.lo);
718978 r.hi += a * (hi - r.hi);
719979 }
720- if (r.hi - r.lo < 1e-9) {
721- const mid = (r.hi + r.lo) / 2;
722- r.lo = mid - 5e-10;
723- r.hi = mid + 5e-10;
724- }
725- fillColors(colorBufs[k], valueBufs[k], r.lo, r.hi, cmap);
980+ // A field that is uniform to fp32 precision — Schnakenberg's v at t = 0 is
981+ // exactly constant — would otherwise have the colormap stretched across its
982+ // roundoff and be drawn as vivid noise. See floorRange.
983+ const shown = floorRange(r.lo, r.hi);
984+ fillColors(colorBufs[k], valueBufs[k], shown.lo, shown.hi, cmap);
726985 scenes[k]?.updateColors(colorBufs[k]);
727- colorbars[k]?.update(cmap, r.lo, r.hi);
986+ colorbars[k]?.update(cmap, shown.lo, shown.hi);
728987 }
729988 }
730989
@@ -876,7 +1135,7 @@ function submitSteps(n: number): void {
8761135 function setMovieUi(on: boolean): void {
8771136 const locked = [
8781137 elModel, elGeometry, elMorph, elNiter, elLmax, elOversample, elColormap,
879- elRunPause, elBenchmark, elReseed, elRecompile, elRevert, elEditorFile,
1138+ elRunPause, elRestart, elBenchmark, elReseed, elRecompile, elRevert, elEditorFile,
8801139 elMovieSpeed, elMovieRes, elMovieRotate, elMovieToggle,
8811140 ];
8821141 for (const el of locked) el.disabled = on;
@@ -957,7 +1216,7 @@ async function recordMovie(): Promise<void> {
9571216 try {
9581217 // Reset the color-range smoothing as a re-seed does, so the shading
9591218 // evolves in the movie the way it did live.
960- session.seed(seed);
1219+ await session.seed(seed);
9611220 seeded = true;
9621221 for (const r of ranges) {
9631222 r.lo = NaN;
@@ -1029,9 +1288,464 @@ async function recordMovie(): Promise<void> {
10291288 }
10301289 }
10311290
1291+// ---------------------------------------------------------------- compare
1292+/**
1293+ * Comparing several solver settings at once.
1294+ *
1295+ * Deliberately a mode rather than a widening of the ordinary controls: the
1296+ * single-run path above is untouched, and with the bar closed nothing about
1297+ * using this page has changed. Opening it and pressing Compare tears down the
1298+ * one session and hands the panels area to a CompareRun, which owns a session
1299+ * per variant; pressing it again puts the single run back.
1300+ *
1301+ * The ceilings below are not arbitrary. Each variant compiles its whole
1302+ * unrolled step with no pipeline cache between sessions (a solve iteration is
1303+ * ~15 kernels per species), so the variant count is what you wait for; and
1304+ * each panel is a WebGL context and a full mesh, so the panel count is what
1305+ * the browser has to keep alive at once.
1306+ */
1307+const MAX_VARIANTS = 6;
1308+const MAX_PANELS = 12;
1309+/** dt divisors. Powers of two so that dtBase/K is exact in binary and every
1310+ * variant lands on the same model time with no accumulated drift. */
1311+const DT_DIVISORS = [1, 2, 4, 8];
1312+
1313+/**
1314+ * What the bar opens on: the default iteration count against the next step up,
1315+ * at the default band. Two variants, so the first study is quick to compile,
1316+ * and it asks the question the control exists for — is the default already
1317+ * converged? A flat, low curve says yes; one that climbs says the answer is
1318+ * still moving at niter 8 and the default is not enough for this shape.
1319+ */
1320+const cmpSelected = {
1321+ niter: new Set<number>([DEFAULT_NITER, 2 * DEFAULT_NITER]),
1322+ lmax: new Set<number>([63]),
1323+ dt: new Set<number>([1]),
1324+};
1325+
1326+/** A row of toggle chips backed by a Set. At least one stays selected — an
1327+ * empty axis has no meaning here, and silently falling back to a default
1328+ * would hide which values are actually being run. */
1329+function buildChips(host: HTMLElement, values: number[], selected: Set<number>, label: (v: number) => string): void {
1330+ host.replaceChildren();
1331+ for (const value of values) {
1332+ const chip = document.createElement('button');
1333+ chip.type = 'button';
1334+ chip.className = 'chip';
1335+ chip.textContent = label(value);
1336+ const paint = (): void => chip.setAttribute('aria-pressed', String(selected.has(value)));
1337+ paint();
1338+ chip.addEventListener('click', () => {
1339+ if (selected.has(value)) {
1340+ if (selected.size === 1) return;
1341+ selected.delete(value);
1342+ } else {
1343+ selected.add(value);
1344+ }
1345+ paint();
1346+ refreshVariants();
1347+ });
1348+ host.append(chip);
1349+ }
1350+}
1351+
1352+const cmpVariants = (): Variant[] =>
1353+ crossProduct([...cmpSelected.niter], [...cmpSelected.lmax], [...cmpSelected.dt]);
1354+
1355+/**
1356+ * A loaded reference file, or null. While one is loaded the study checks the
1357+ * variants against it instead of against each other: the file defines the
1358+ * whole problem (model, parameters, geometry, initial state, end time), so
1359+ * the page's own model and geometry choices do not enter the study at all —
1360+ * only the solver knobs above do.
1361+ */
1362+let refCase: ReferenceCase | null = null;
1363+
1364+/** The reference the user picked, clamped to the current variant list. */
1365+let cmpRefKey = '';
1366+
1367+/** Index of the reference in the current variant list, never negative. */
1368+function compareRefIndex(): number {
1369+ const i = cmpVariants().map(variantKey).indexOf(cmpRefKey);
1370+ return i < 0 ? 0 : i;
1371+}
1372+
1373+function refreshVariants(): void {
1374+ const variants = cmpVariants();
1375+ const showDt = cmpSelected.dt.size > 1;
1376+ // With a file loaded the study's model is the file's, and its final state
1377+ // is one more row of panels.
1378+ const cmpModel = refCase?.model ?? model;
1379+ const rowCount = variants.length + (refCase ? 1 : 0);
1380+ const panels = rowCount * cmpModel.species.length;
1381+
1382+ const prev = cmpRefKey;
1383+ elCmpRef.replaceChildren();
1384+ if (refCase) {
1385+ // The file is the reference; the pick among variants means nothing here.
1386+ const o = document.createElement('option');
1387+ o.textContent = `the file's final state`;
1388+ elCmpRef.append(o);
1389+ elCmpRef.disabled = true;
1390+ } else {
1391+ elCmpRef.disabled = false;
1392+ for (const v of variants) {
1393+ const o = document.createElement('option');
1394+ o.value = variantKey(v);
1395+ o.textContent = variantLabel(v, showDt);
1396+ elCmpRef.append(o);
1397+ }
1398+ const keys = variants.map(variantKey);
1399+ cmpRefKey = keys.includes(prev) ? prev : keys[mostResolved(variants)];
1400+ elCmpRef.value = cmpRefKey;
1401+ }
1402+
1403+ const tooMany =
1404+ variants.length > MAX_VARIANTS
1405+ ? `${variants.length} variants — at most ${MAX_VARIANTS}`
1406+ : panels > MAX_PANELS
1407+ ? `${panels} panels — at most ${MAX_PANELS}`
1408+ : '';
1409+ elCmpCount.textContent = tooMany
1410+ ? `too many: ${tooMany}`
1411+ : `${variants.length} variant${variants.length === 1 ? '' : 's'}` +
1412+ `${refCase ? ' + the file' : ''} × ` +
1413+ `${cmpModel.species.length} species = ${panels} panels`;
1414+ elCmpCount.style.color = tooMany ? '#b35900' : '';
1415+ elCmpStart.disabled = tooMany !== '' && compareRun === null;
1416+}
1417+
1418+/**
1419+ * The niter chips on offer. A loaded reference file adds its own recorded
1420+ * iteration count if the standard list lacks it, so the file's settings are
1421+ * always selectable; clearing the file drops any selection outside the
1422+ * standard list again.
1423+ */
1424+function rebuildNiterChips(): void {
1425+ const all = [...elNiter.options].map((o) => Number(o.value));
1426+ let values = all;
1427+ if (refCase && !all.includes(refCase.niter)) {
1428+ values = [...all, refCase.niter].sort((a, b) => a - b);
1429+ }
1430+ if (!refCase) {
1431+ for (const v of [...cmpSelected.niter]) if (!values.includes(v)) cmpSelected.niter.delete(v);
1432+ if (cmpSelected.niter.size === 0) cmpSelected.niter.add(DEFAULT_NITER);
1433+ }
1434+ buildChips(elCmpNiter, values, cmpSelected.niter, String);
1435+}
1436+
1437+/**
1438+ * The lmax chips on offer. A loaded reference file floors them at its own
1439+ * band: a variant below it could not even hold the file's initial state
1440+ * (prolongation only widens), so those values are not offered rather than
1441+ * offered and refused.
1442+ */
1443+function rebuildLmaxChips(): void {
1444+ const all = [...elLmax.options].map((o) => Number(o.value));
1445+ let values = all;
1446+ if (refCase) {
1447+ const floor = refCase.lmax;
1448+ values = all.filter((v) => v >= floor);
1449+ if (!values.includes(floor)) values = [floor, ...values];
1450+ for (const v of [...cmpSelected.lmax]) if (!values.includes(v)) cmpSelected.lmax.delete(v);
1451+ if (cmpSelected.lmax.size === 0) cmpSelected.lmax.add(floor);
1452+ }
1453+ buildChips(elCmpLmax, values, cmpSelected.lmax, String);
1454+}
1455+
1456+rebuildNiterChips();
1457+rebuildLmaxChips();
1458+buildChips(elCmpDt, DT_DIVISORS, cmpSelected.dt, (v) => (v === 1 ? 'dt' : `dt/${v}`));
1459+refreshVariants();
1460+
1461+elCmpRef.addEventListener('change', () => {
1462+ cmpRefKey = elCmpRef.value;
1463+ if (compareRun) void rebuildCompare();
1464+});
1465+
1466+/** Reflect the loaded (or cleared) reference file in the compare bar. */
1467+function applyRefUi(): void {
1468+ elCmpFileInfo.hidden = elCmpFileClear.hidden = refCase === null;
1469+ if (refCase) {
1470+ const rc = refCase;
1471+ const geomParamText = rc.geometry.params
1472+ .map((p) => `${p.key}=${rc.geometryParams[p.key]}`)
1473+ .join(' ');
1474+ const name = document.createElement('b');
1475+ name.textContent = rc.label;
1476+ const info = document.createElement('span');
1477+ info.textContent =
1478+ ` — ${rc.model.label} on ${rc.geometry.label.toLowerCase()}` +
1479+ (geomParamText ? ` (${geomParamText})` : '') +
1480+ `, lmax ${rc.lmax}, T = ${(rc.steps * (rc.params.dt ?? 0)).toFixed(2)}` +
1481+ ` (${rc.steps} × dt ${rc.params.dt})`;
1482+ elCmpFileInfo.replaceChildren(name, info);
1483+ }
1484+ rebuildNiterChips();
1485+ rebuildLmaxChips();
1486+ refreshVariants();
1487+}
1488+
1489+/**
1490+ * The four top-level modes and which control groups each shows (see
1491+ * GROUP_NAMES/groupEls above; `.ctrl-group` wrappers in index.html).
1492+ * `currentMode` tracks which configuration is on screen — the compare bar
1493+ * being open, and in which flavor — not whether a study has actually been
1494+ * started inside it. That match matters: without it, opening the bar
1495+ * (which already shows the right groups) leaves its top-row button
1496+ * unhighlighted until a study happens to start, which is inconsistent with
1497+ * `vs-upload`'s one-click flow and reads as broken.
1498+ */
1499+type Mode = 'simulate' | 'compute-effort' | 'vs-sphere' | 'vs-upload';
1500+let currentMode: Mode = 'simulate';
1501+
1502+const MODE_GROUPS: Record<Mode, readonly GroupName[]> = {
1503+ simulate: ['surface', 'surface-params', 'solver', 'display', 'playback', 'benchmark', 'seed', 'movie'],
1504+ 'compute-effort': ['surface', 'surface-params', 'display', 'playback', 'seed'],
1505+ 'vs-sphere': [], // unreachable — the button is disabled, no listener ever calls setMode with this
1506+ // No `seed` here: nothing in that group does anything useful against a
1507+ // loaded file (lam3 is silently absorbed, and Restart already covers what
1508+ // Re-seed would otherwise be doing — reloading the file's fixed initial
1509+ // state) — see CompareRun.restart().
1510+ 'vs-upload': ['display', 'playback'],
1511+};
1512+
1513+const MODE_DESCRIPTIONS: Record<Mode, string> = {
1514+ simulate:
1515+ 'This mode runs one standalone reaction-diffusion solver.',
1516+ 'compute-effort':
1517+ 'When we change the computational effort of the solver by varying solve iterations, lmax, or timestep, ' +
1518+ 'how does the solution change? Find out by running several ' +
1519+ 'so you can see how each setting trades accuracy for speed.',
1520+ 'vs-sphere': '',
1521+ 'vs-upload':
1522+ 'Load a saved reference run (an .h5 file) and run this solver to the ' +
1523+ 'same physical end time from the same initial condition, to check how ' +
1524+ 'closely it reproduces the reference. You can adjust the solver settings ' +
1525+ 'to see how they affect the outcome.',
1526+};
1527+
1528+function setModeButtons(mode: Mode): void {
1529+ elModeSimulate.setAttribute('aria-pressed', String(mode === 'simulate'));
1530+ elModeEffort.setAttribute('aria-pressed', String(mode === 'compute-effort'));
1531+ elModeVsUpload.setAttribute('aria-pressed', String(mode === 'vs-upload'));
1532+ elModeDesc.textContent = MODE_DESCRIPTIONS[mode];
1533+}
1534+
1535+/** Show exactly the groups `mode` declares; hide the rest. */
1536+function applyModeVisibility(mode: Mode): void {
1537+ currentMode = mode;
1538+ const shown = new Set<GroupName>(MODE_GROUPS[mode]);
1539+ for (const name of GROUP_NAMES) groupEls[name].hidden = !shown.has(name);
1540+ setModeButtons(mode);
1541+}
1542+
1543+/**
1544+ * Enter `mode`: groups, top-row buttons, and the compare bar's own
1545+ * visibility (open for the two compare flavors, closed for Simulate).
1546+ * Doesn't touch `compareRun`/`refCase` or start/stop a study — callers
1547+ * decide that; this only decides what's on screen, and it decides it
1548+ * immediately, so the button you clicked lights up right away rather than
1549+ * waiting on a study that may not exist yet (or may never start, if the
1550+ * bar's own Compare is never pressed).
1551+ */
1552+function enterMode(mode: Mode): void {
1553+ applyModeVisibility(mode);
1554+ elCompareBar.hidden = mode === 'simulate';
1555+}
1556+
1557+/** Entering a mode from the top row. */
1558+function setMode(mode: Mode): void {
1559+ if (mode === 'vs-sphere') return; // unreachable — button is disabled
1560+ if (mode === 'simulate') {
1561+ if (compareRun) void stopCompare();
1562+ enterMode('simulate');
1563+ return;
1564+ }
1565+ if (mode === 'compute-effort') {
1566+ // Tear down whatever study is running first (mirrors Simulate above) —
1567+ // stopCompare's synchronous prefix disposes it and nulls `compareRun`
1568+ // before its first `await`, so `refCase` is safe to drop right after.
1569+ if (compareRun) void stopCompare();
1570+ if (refCase) {
1571+ refCase = null;
1572+ applyRefUi();
1573+ }
1574+ enterMode('compute-effort');
1575+ return;
1576+ }
1577+ // vs-upload: opens the file picker; entering the mode itself happens once
1578+ // a file is actually chosen (elCmpFile's change handler below) — not here,
1579+ // since cancelling the dialog must leave the current mode untouched.
1580+ elCmpFile.click();
1581+}
1582+
1583+elModeSimulate.addEventListener('click', () => setMode('simulate'));
1584+elModeEffort.addEventListener('click', () => setMode('compute-effort'));
1585+elModeVsUpload.addEventListener('click', () => setMode('vs-upload'));
1586+
1587+elCmpFile.addEventListener('change', () => {
1588+ const file = elCmpFile.files?.[0];
1589+ // Cleared so picking the same file again still fires a change event.
1590+ elCmpFile.value = '';
1591+ if (!file) return;
1592+ void (async () => {
1593+ try {
1594+ refCase = await loadReferenceFile(file);
1595+ elErr.textContent = '';
1596+ } catch (e) {
1597+ refCase = null;
1598+ elErr.textContent = `reference file ${file.name}: ${e instanceof Error ? e.message : e}`;
1599+ applyRefUi();
1600+ return;
1601+ }
1602+ // One click, one study: the file's own settings become the single
1603+ // variant — its recorded niter, its band, its dt undivided — and the
1604+ // comparison opens on them, paused at the initial state so what runs is
1605+ // the user's choice. (Widening it is: teardown the comparison, pick more
1606+ // chips, compile it again — the file stays loaded.)
1607+ cmpSelected.niter.clear();
1608+ cmpSelected.niter.add(refCase.niter);
1609+ cmpSelected.lmax.clear();
1610+ cmpSelected.lmax.add(refCase.lmax);
1611+ cmpSelected.dt.clear();
1612+ cmpSelected.dt.add(1);
1613+ applyRefUi();
1614+ enterMode('vs-upload');
1615+ if (compareRun) {
1616+ // A study is already up (this one loaded over it): same teardown as
1617+ // rebuildCompare, then the new file's study takes its place.
1618+ compareRun.dispose();
1619+ compareRun = null;
1620+ setCompareUi(false);
1621+ }
1622+ await startCompare();
1623+ })();
1624+});
1625+elCmpFileClear.addEventListener('click', () => {
1626+ refCase = null;
1627+ applyRefUi();
1628+ // The bar stays open — this only drops back to the plain chip comparison.
1629+ // Only reachable while idle (elCmpFileClear is disabled during a study).
1630+ enterMode('compute-effort');
1631+});
1632+
1633+elCmpStart.addEventListener('click', () => {
1634+ if (compareRun) void stopCompare();
1635+ else void startCompare();
1636+});
1637+
1638+/**
1639+ * Controls the study supersedes or cannot honour while it is running.
1640+ * Mode/group/button state is not this function's job — that's set the
1641+ * moment a mode is entered (enterMode, above), independent of whether a
1642+ * study inside it has actually started or stopped.
1643+ */
1644+function setCompareUi(on: boolean): void {
1645+ // A study picks its own display grid, so oversample stays individually
1646+ // disabled inside the still-visible display group; and clearing a loaded
1647+ // file out from under a running study would leave it checking against one
1648+ // that no longer exists.
1649+ elOversample.disabled = on;
1650+ elCmpFileClear.disabled = on;
1651+ elCmpNiter.querySelectorAll('button').forEach((b) => (b.disabled = on));
1652+ elCmpLmax.querySelectorAll('button').forEach((b) => (b.disabled = on));
1653+ elCmpDt.querySelectorAll('button').forEach((b) => (b.disabled = on));
1654+ elCmpStart.textContent = on ? 'Teardown comparison' : 'Compile comparison';
1655+ // The movie bar's own hidden flag is independent of the movie *group's* —
1656+ // force it closed so it doesn't reappear open once the group is shown
1657+ // again on returning to Simulate.
1658+ if (on) elMovieBar.hidden = true;
1659+}
1660+
1661+async function startCompare(): Promise<void> {
1662+ if (compareRun || !device) return;
1663+ // Snapshotted for the whole study: `refCase` only changes with no study up
1664+ // (clearing is disabled during one, and loading tears it down first).
1665+ const rc = refCase;
1666+ const cmpModel = rc?.model ?? model;
1667+ const variants = cmpVariants();
1668+ const rowCount = variants.length + (rc ? 1 : 0);
1669+ if (variants.length > MAX_VARIANTS || rowCount * cmpModel.species.length > MAX_PANELS) {
1670+ return;
1671+ }
1672+ // Take down the single run first: its pump, its scenes, its session. The
1673+ // generation bump makes any readback already in flight drop its result.
1674+ generation++;
1675+ setRunning(false);
1676+ while (pumping) await nextFrame();
1677+ disposeView();
1678+ session?.destroy();
1679+ session = null;
1680+ elBenchResult.textContent = '';
1681+ elErr.textContent = '';
1682+ setCompareUi(true);
1683+
1684+ try {
1685+ // Against a reference file, the problem is the file's — its model,
1686+ // parameters and geometry, from the registry sources (the editor's
1687+ // working copies describe the page's run, not the file's).
1688+ compareRun = await CompareRun.create({
1689+ device,
1690+ model: cmpModel,
1691+ params: rc ? rc.params : params,
1692+ source: rc ? rc.model.source : source(),
1693+ geometry: rc ? rc.geometry : geometry,
1694+ geometryParams: rc ? rc.geometryParams : geomParams,
1695+ geometrySource: rc ? rc.geometry.source : geomSource(),
1696+ variants,
1697+ reference: rc ? 0 : compareRefIndex(),
1698+ refFile: rc ?? undefined,
1699+ onFinished: () => setRunning(false),
1700+ seed,
1701+ lam3: rc ? undefined : Number(elLam3.value),
1702+ morph,
1703+ colormapName: () => elColormap.value,
1704+ container: elPanels,
1705+ onStatus: (html) => (elStats.innerHTML = html),
1706+ });
1707+ } catch (e) {
1708+ compareRun = null;
1709+ setCompareUi(false);
1710+ refreshVariants();
1711+ reportCompileError(e);
1712+ await rebuild();
1713+ return;
1714+ }
1715+ updateGeomNote();
1716+ // The command describes the reference variant, which only exists now.
1717+ updateCommand();
1718+ elRunPause.textContent = 'Run';
1719+}
1720+
1721+async function stopCompare(): Promise<void> {
1722+ if (!compareRun) return;
1723+ compareRun.dispose();
1724+ compareRun = null;
1725+ setCompareUi(false);
1726+ refreshVariants();
1727+ elStats.textContent = '';
1728+ await rebuild();
1729+}
1730+
1731+/** Rebuild the study in place — after a model, geometry, source or reference
1732+ * change. Same teardown as stopping, without leaving the mode. */
1733+async function rebuildCompare(): Promise<void> {
1734+ if (!compareRun) return;
1735+ compareRun.dispose();
1736+ compareRun = null;
1737+ setCompareUi(false);
1738+ await startCompare();
1739+}
1740+
10321741 // ---------------------------------------------------------------- boot
10331742 async function boot(): Promise<void> {
1743+ enterMode('simulate');
10341744 elModel.value = presets[0].key;
1745+ // The iteration count is one default shared with the benchmark, like the
1746+ // rest of the RunSpec's — take it from there rather than from the markup, so
1747+ // the page and `npm run bench` cannot start out disagreeing about it.
1748+ elNiter.value = String(DEFAULT_NITER);
10351749 elGeometry.value = DEFAULT_GEOMETRY_KEY;
10361750 elMorph.value = String(morph);
10371751 applyGeometryChoice(DEFAULT_GEOMETRY_KEY);
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/externals.tsmodified+61−1View file
@@ -153,10 +153,70 @@ export function externalOpFiles(g: GridSizes): { name: string; source: string }[
153153 name: 'dphig.mtoc2.js',
154154 source: transformSource('dphig', g.npts, 1, g.npts, 1),
155155 },
156+ {
157+ // The seeded random field a model's `init` starts from
158+ // (src/mgpu/randnfun3.ts): a wavelength and the three surface
159+ // coordinates in, one value per grid point out.
160+ name: 'randnfun3.mtoc2.js',
161+ source: randnfun3Source(g),
162+ },
156163 ];
157164 }
158165
166+/** Source for `randnfun3`'s `.mtoc2.js`: `f = randnfun3(lambda, x, y, z)`. */
167+function randnfun3Source(g: GridSizes): string {
168+ return `
169+exports.name = "randnfun3";
170+
171+exports.transfer = function (argTypes, nargout) {
172+ if (argTypes.length !== 4) {
173+ throw new Error(
174+ "randnfun3 takes a wavelength and the three surface coordinates -- " +
175+ "randnfun3(lambda, gx, gy, gz) -- got " + argTypes.length + " argument(s)"
176+ );
177+ }
178+ if (nargout > 1) {
179+ throw new Error("randnfun3 returns one value, but " + nargout + " were requested");
180+ }
181+ var lam = argTypes[0];
182+ if (!lam || lam.kind !== "Numeric" || lam.isComplex) {
183+ throw new Error("randnfun3's wavelength must be a real number");
184+ }
185+ var ls = lam.shape;
186+ if (!ls || ls.length !== 2 || ls[0] !== 1 || ls[1] !== 1) {
187+ throw new Error(
188+ "randnfun3's wavelength must be a single number, not a " +
189+ (ls ? ls.join("x") : "unknown shape") + " array"
190+ );
191+ }
192+ var names = ["gx", "gy", "gz"];
193+ for (var i = 1; i < 4; i++) {
194+ var a = argTypes[i];
195+ if (!a || a.kind !== "Numeric" || a.isComplex) {
196+ throw new Error("randnfun3 requires real numeric arrays (" + names[i - 1] + ")");
197+ }
198+ var s = a.shape;
199+ if (!s || s.length !== 2 || s[0] !== ${g.npts} || s[1] !== 1) {
200+ throw new Error(
201+ "randnfun3 evaluates on the grid, so " + names[i - 1] +
202+ " must be ${g.npts}x1, not " + (s ? s.join("x") : "unknown shape")
203+ );
204+ }
205+ }
206+ return [${numericType(g.npts, 1)}];
207+};
208+
209+// Never called: this project executes the IR on WebGPU and emits no C.
210+exports.emit = function () {
211+ throw new Error("randnfun3: no C backend (this runs on WebGPU)");
212+};
213+exports.cBody = function () {
214+ return "";
215+};
216+`;
217+}
218+
159219 /** Names the WGSL backend must implement as GPU encodes rather than kernels. */
160220 export const EXTERNAL_OPS = new Set([
161- 'synth', 'analys', 'dtheta', 'dphi', 'dthetac', 'dphic', 'dphig',
221+ 'synth', 'analys', 'dtheta', 'dphi', 'dthetac', 'dphic', 'dphig', 'randnfun3',
162222 ]);
src/mgpu/model.tsmodified+39−8View file
@@ -20,7 +20,8 @@
2020 import { ShtPlan } from '../sht/sht.ts';
2121 import type { DerivPlan } from '../sht/deriv.ts';
2222 import { lmIndex, type ShtConfig } from '../sht/layout.ts';
23-import { HostBuffers, ModelPlan } from './plan.ts';
23+import { HostBuffers, ModelPlan, type Randnfun3Lambda } from './plan.ts';
24+import { MODE_BUFFER } from './randnfun3.ts';
2425 import { inFunction, inFunctionAsync, inModel } from './errors.ts';
2526 import { CompiledModel, type Binding } from './compile.ts';
2627
@@ -83,6 +84,12 @@ export interface GeometryBuffers {
8384 p2: Float32Array;
8485 q2: Float32Array;
8586 r: Float32Array;
87+ /** The same weights with the round sphere subtracted (Geometry.dp1/dq2/jinv)
88+ * — the sphere-split form of the flux divergence, which keeps r off the
89+ * round-sphere part of the operator. */
90+ dp1: Float32Array;
91+ dq2: Float32Array;
92+ jinv: Float32Array;
8693 /** Mean-J preconditioner scale (Geometry.Jhat): folded into every
8794 * setParams upload as the 'jhat' uniform, so a .m that takes jhat is
8895 * never left with the zero a missing parameter would default to. An
@@ -98,7 +105,7 @@ export const GEOMETRY_SPECTRAL_NAMES = ['Gx', 'Gy', 'Gz'] as const;
98105 export const METRIC_GRID_NAMES = ['Vtx', 'Vty', 'Vtz', 'Vpx', 'Vpy', 'Vpz'] as const;
99106 /** Names the .m may take for the flux-form metric weights (six-transform
100107 * scheme). A model asks for whichever set its loop uses; both are uploaded. */
101-export const FLUX_METRIC_GRID_NAMES = ['p1', 'p2', 'q2', 'r'] as const;
108+export const FLUX_METRIC_GRID_NAMES = ['p1', 'p2', 'q2', 'r', 'dp1', 'dq2', 'jinv'] as const;
102109
103110 /** Laplace-Beltrami eigenvalues l(l+1), duplicated across re/im so the array
104111 * matches the 2 x nlm spectral layout element for element. */
@@ -208,6 +215,10 @@ export class GpuModel {
208215 // so swapping the surface updates it with no recompile. The session
209216 // folds the current geometry's value into every setParams call.
210217 bindings['jhat'] = { kind: 'param' };
218+ // The wavelength of the seeded random field (src/mgpu/randnfun3.ts).
219+ // A uniform like jhat, not a const: changing it redraws the field
220+ // without recompiling the step.
221+ bindings['lam3'] = { kind: 'param' };
211222 }
212223 for (const s of state) bindings[s] = { kind: 'tensor', shape: [2, nlm] };
213224 for (const p of paramNames) bindings[p] = { kind: 'param' };
@@ -265,6 +276,9 @@ export class GpuModel {
265276 host.upload('p2', geometry.p2);
266277 host.upload('q2', geometry.q2);
267278 host.upload('r', geometry.r);
279+ host.upload('dp1', geometry.dp1);
280+ host.upload('dq2', geometry.dq2);
281+ host.upload('jinv', geometry.jinv);
268282 }
269283
270284 const readback = device.createBuffer({
@@ -315,6 +329,7 @@ export class GpuModel {
315329 ['Vpx', geometry.Vpx], ['Vpy', geometry.Vpy], ['Vpz', geometry.Vpz],
316330 ['p1', geometry.p1], ['p2', geometry.p2],
317331 ['q2', geometry.q2], ['r', geometry.r],
332+ ['dp1', geometry.dp1], ['dq2', geometry.dq2], ['jinv', geometry.jinv],
318333 ];
319334 for (const [name, data] of fields) {
320335 if (this.#host.get(name)) this.#host.upload(name, data);
@@ -324,12 +339,28 @@ export class GpuModel {
324339 this.#jhat = geometry.Jhat;
325340 }
326341
327- /** Upload the seeded perturbation and run `init`. */
328- init(noise: Float32Array): void {
329- this.#host.upload('noise', noise);
330- const enc = this.#device.createCommandEncoder({ label: 'mgpu-init' });
331- this.#initPlan.encodeSteps(enc, 1);
332- this.#device.queue.submit([enc.finish()]);
342+ /** The wavelength this model's `init` asked `randnfun3` for, or null if it
343+ * seeds some other way. The session resolves it and draws the modes. */
344+ get randnfun3Lambda(): Randnfun3Lambda | null {
345+ return this.#initPlan.randnfun3Lambda;
346+ }
347+
348+ /**
349+ * Upload the seeded initial data and run `init`.
350+ *
351+ * Both inputs are optional in the sense that a .m uses one or the other:
352+ * `modes` is the random field's coefficient table for a model that calls
353+ * `randnfun3`, `noise` the plain grid field for one that takes `noise`
354+ * directly (the analytic test models inject exact initial conditions that
355+ * way). Only what the plan actually bound is uploaded.
356+ */
357+ async init(noise: Float32Array, modes: Float32Array | null): Promise<void> {
358+ if (this.#host.get('noise')) this.#host.upload('noise', noise);
359+ // Sized to the wavelength, so this may reallocate and rebind.
360+ if (modes) this.#initPlan.uploadRandnfun3Table(this.#host, modes);
361+ // Submitted in pieces: a fine seed wavelength makes the mode sum long
362+ // enough that one submission would stall the browser's compositor.
363+ await this.#initPlan.submitYielding('mgpu-init');
333364 this.#lastRan = 'init';
334365 }
335366
src/mgpu/numbl.d.tsmodified+90−5View file
@@ -1,10 +1,12 @@
11 /**
22 * The numbl compiler surface this project depends on.
33 *
4- * We reach past numbl's published entry points into its JIT internals (parser,
5- * lowerer, IR, inline pass), which its package `exports` map does not expose.
6- * Those imports resolve through the `numbl-src` alias in vite.config.ts; these
7- * declarations are what TypeScript checks against.
4+ * We reach past numbl's published entry points into its internals — the JIT
5+ * side (parser, lowerer, IR, inline pass) that compiles the models, and the
6+ * interpreter side (executeCode, runtime values) that evaluates the
7+ * geometries — which its package `exports` map does not expose. Those imports
8+ * resolve through the `numbl-src` alias in vite.config.ts; these declarations
9+ * are what TypeScript checks against.
810 *
911 * Declaring the surface here rather than type-checking numbl's sources
1012 * directly keeps this project's compiler settings independent of numbl's, and
@@ -192,13 +194,96 @@ declare module 'numbl-src/numbl-core/jit/lowering/ir.ts' {
192194 }
193195
194196 declare module 'numbl-src/numbl-core/parser/index.ts' {
197+ export interface ParseSpan {
198+ start: number;
199+ end: number;
200+ }
201+
202+ /** The one parse-tree node this project inspects (src/geom/geometry.ts,
203+ * finding `shape` and its argument names). */
204+ export interface FunctionStmt {
205+ type: 'Function';
206+ name: string;
207+ params: string[];
208+ outputs: string[];
209+ span: ParseSpan;
210+ }
211+
212+ /** Any other statement in a file's body — opaque to this project. Its
213+ * `type` is some other literal; narrowing to FunctionStmt goes through an
214+ * explicit type guard rather than the discriminant. */
215+ export interface OtherParseStmt {
216+ type: string;
217+ span: ParseSpan;
218+ }
219+
220+ export type Stmt = FunctionStmt | OtherParseStmt;
221+
195222 export interface AbstractSyntaxTree {
196- body: unknown[];
223+ body: Stmt[];
197224 }
198225 export function parseMFile(input: string, fileName?: string): AbstractSyntaxTree;
199226 export class SyntaxError extends Error {}
200227 }
201228
229+declare module 'numbl-src/numbl-core/runtime/types.ts' {
230+ /** A numeric array: f64 data in column-major order, with its shape. */
231+ export class RuntimeTensor {
232+ readonly kind: 'tensor';
233+ data: Float64Array;
234+ /** Present iff the value is complex. */
235+ imag: Float64Array | undefined;
236+ shape: number[];
237+ constructor(data: Float64Array, shape: number[], imag?: Float64Array);
238+ }
239+
240+ /** Every other value kind the interpreter can hold, collapsed. */
241+ export interface OtherRuntimeValue {
242+ readonly kind: string;
243+ }
244+
245+ export type RuntimeValue =
246+ | number
247+ | boolean
248+ | string
249+ | RuntimeTensor
250+ | OtherRuntimeValue;
251+
252+ export function isRuntimeTensor(value: RuntimeValue): value is RuntimeTensor;
253+}
254+
255+declare module 'numbl-src/numbl-core/executeCode.ts' {
256+ import type { RuntimeValue } from 'numbl-src/numbl-core/runtime/types.ts';
257+
258+ export interface ExecOptions {
259+ /** Variables pre-bound in the script's workspace before it runs. */
260+ initialVariableValues?: Record<string, RuntimeValue>;
261+ displayResults?: boolean;
262+ onOutput?: (text: string) => void;
263+ /** null opts out of scanning a working directory for .m files. */
264+ implicitCwdPath?: string | null;
265+ }
266+
267+ export interface ExecWorkspaceFile {
268+ name: string;
269+ source: string;
270+ }
271+
272+ export interface ExecResult {
273+ output: string[];
274+ /** The script's workspace after it ran. */
275+ variableValues: Record<string, RuntimeValue>;
276+ }
277+
278+ /** Run a script through numbl's interpreter (with its JS-JIT), CPU-side. */
279+ export function executeCode(
280+ source: string,
281+ options?: ExecOptions,
282+ workspaceFiles?: ExecWorkspaceFile[],
283+ mainFileName?: string,
284+ ): ExecResult;
285+}
286+
202287 declare module 'numbl-src/numbl-core/jit/index.ts' {
203288 import type { AbstractSyntaxTree } from 'numbl-src/numbl-core/parser/index.ts';
204289 import type { IRProgram, IRFunc, Span } from 'numbl-src/numbl-core/jit/lowering/ir.ts';
src/mgpu/plan.tsmodified+291−12View file
@@ -21,6 +21,13 @@ import { ShtPlan, type ShtBinding, type ShtBatchBinding, type ShtDphigBinding }
2121 import { DerivPlan, type DerivBinding } from '../sht/deriv.ts';
2222 import type { CompiledFunction } from './compile.ts';
2323 import { EXTERNAL_OPS } from './externals.ts';
24+import {
25+ MODE_BUFFER,
26+ INITIAL_MODES,
27+ modeTableLength,
28+ randnfun3Chunks,
29+ randnfun3WGSL,
30+} from './randnfun3.ts';
2431 import {
2532 buildKernel,
2633 UnsupportedOnGpu,
@@ -96,6 +103,35 @@ export class HostBuffers {
96103 return this.#slots.get(name);
97104 }
98105
106+ /**
107+ * Replace a slot's buffer with a larger one. Only for buffers whose size is
108+ * not fixed by the grid — the randnfun3 mode table, which grows with the
109+ * wavelength asked for. The caller must rebuild any bind group holding the
110+ * old buffer; it is destroyed here.
111+ */
112+ resize(name: string, count: number): Slot {
113+ const existing = this.#slots.get(name);
114+ if (!existing) throw new Error(`resize: no buffer named '${name}'`);
115+ if (count <= existing.count) return existing;
116+ existing.buffer.destroy();
117+ const slot = { buffer: makeBuffer(this.#device, `mgpu-${name}`, count), count };
118+ this.#slots.set(name, slot);
119+ return slot;
120+ }
121+
122+ /** Upload into the front of a slot, leaving any tail as it was. For a
123+ * variable-length payload in a buffer sized to its high-water mark. */
124+ uploadInto(name: string, data: Float32Array): void {
125+ const slot = this.#slots.get(name);
126+ if (!slot) throw new Error(`uploadInto: no buffer named '${name}'`);
127+ if (data.length > slot.count) {
128+ throw new Error(
129+ `uploadInto '${name}': ${data.length} elements into a ${slot.count}-element buffer`,
130+ );
131+ }
132+ this.#device.queue.writeBuffer(slot.buffer, 0, data as Float32Array<ArrayBuffer>);
133+ }
134+
99135 /** Upload initial data for a host binding. */
100136 upload(name: string, data: Float32Array): void {
101137 const slot = this.#slots.get(name);
@@ -124,6 +160,9 @@ type Op =
124160 /** Set when the kernel had to write to scratch because its output
125161 * aliases one of its inputs; copied back after the dispatch. */
126162 copyBack?: { from: GPUBuffer; to: GPUBuffer; bytes: number };
163+ /** End the submission here when run through `submitYielding`, so the
164+ * GPU is handed back between chunks of a long seed. */
165+ yieldAfter?: boolean;
127166 }
128167 | { kind: 'synth' | 'analys'; binding: ShtBinding; label: string }
129168 | { kind: 'synth-batch' | 'analys-batch'; binding: ShtBatchBinding; labels: string[] }
@@ -295,6 +334,9 @@ async function makePipeline(
295334 export class ModelPlan {
296335 /** Scalar parameter names, in the order the params buffer expects them. */
297336 readonly paramNames: string[];
337+ /** The wavelength this plan's `randnfun3` call asked for, or null if it
338+ * makes none. The host draws the coefficient table from it. */
339+ readonly randnfun3Lambda: Randnfun3Lambda | null;
298340
299341 #device: GPUDevice;
300342 #sht: ShtPlan;
@@ -303,6 +345,7 @@ export class ModelPlan {
303345 #owned: GPUBuffer[];
304346 #paramBuf: GPUBuffer;
305347 #paramData: Float32Array;
348+ #rebindRandnfun3: ((table: GPUBuffer) => void) | null;
306349 /** Public name -> buffer, for uploading initial state and reading results. */
307350 #byName: Map<string, Slot>;
308351
@@ -316,6 +359,8 @@ export class ModelPlan {
316359 paramBuf: GPUBuffer;
317360 paramData: Float32Array;
318361 paramNames: string[];
362+ randnfun3Lambda: Randnfun3Lambda | null;
363+ rebindRandnfun3: ((table: GPUBuffer) => void) | null;
319364 }) {
320365 this.#device = init.device;
321366 this.#sht = init.sht;
@@ -326,6 +371,30 @@ export class ModelPlan {
326371 this.#paramBuf = init.paramBuf;
327372 this.#paramData = init.paramData;
328373 this.paramNames = init.paramNames;
374+ this.randnfun3Lambda = init.randnfun3Lambda;
375+ this.#rebindRandnfun3 = init.rebindRandnfun3;
376+ }
377+
378+ /**
379+ * Point the randnfun3 dispatch at a mode table big enough for `data`,
380+ * growing the buffer if this wavelength needs more modes than the last one,
381+ * and upload it.
382+ */
383+ uploadRandnfun3Table(host: HostBuffers, data: Float32Array): void {
384+ const slot = host.get(MODE_BUFFER);
385+ if (!slot || !this.#rebindRandnfun3) return;
386+ if (data.length > slot.count) {
387+ const max = this.#device.limits.maxStorageBufferBindingSize;
388+ if (4 * data.length > max) {
389+ throw new Error(
390+ `randnfun3: this wavelength needs a ${(4 * data.length / 1e6).toFixed(0)} MB ` +
391+ `mode table, past this device's ${(max / 1e6).toFixed(0)} MB limit ` +
392+ `on a single buffer. Use a larger lambda.`,
393+ );
394+ }
395+ this.#rebindRandnfun3(host.resize(MODE_BUFFER, data.length).buffer);
396+ }
397+ host.uploadInto(MODE_BUFFER, data);
329398 }
330399
331400 static async create(
@@ -375,6 +444,14 @@ export class ModelPlan {
375444 usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
376445 });
377446
447+ /** Set when the .m calls `randnfun3`: which wavelength it asked for, so
448+ * the host draws the coefficient table the kernel reads from exactly
449+ * that value (src/mgpu/randnfun3.ts). */
450+ let randnfun3Lambda: Randnfun3Lambda | null = null;
451+ /** Rebuilds the randnfun3 dispatch's bind group after the mode table is
452+ * reallocated for a finer wavelength. */
453+ let rebindRandnfun3: ((table: GPUBuffer) => void) | null = null;
454+
378455 const planned: Planned[] = [];
379456 for (const stmt of fn.body) {
380457 await planStatement(stmt);
@@ -413,6 +490,7 @@ export class ModelPlan {
413490
414491 return new ModelPlan({
415492 device, sht, deriv, ops, byName, owned, paramBuf, paramData, paramNames,
493+ randnfun3Lambda, rebindRandnfun3,
416494 });
417495
418496 async function planStatement(stmt: IRStmt): Promise<void> {
@@ -457,14 +535,19 @@ export class ModelPlan {
457535
458536 const ext = externalCall(stmt);
459537 if (ext) {
460- const argSlot = slots.get(ext.argCName);
538+ if (ext.name === 'randnfun3') {
539+ await planRandnfun3(stmt, ext.args, dest);
540+ return;
541+ }
542+ const arg = ext.args[0] as IRExpr & { kind: 'Var' };
543+ const argSlot = slots.get(arg.cName);
461544 if (!argSlot) {
462545 throw new UnsupportedOnGpu(
463- `'${ext.name}' reads '${ext.argName}', which has no buffer`,
546+ `'${ext.name}' reads '${arg.name}', which has no buffer`,
464547 stmt.span,
465548 );
466549 }
467- const label = `${stmt.name} = ${ext.name}(${ext.argName})`;
550+ const label = `${stmt.name} = ${ext.name}(${arg.name})`;
468551 if (ext.name === 'dphig') {
469552 // Grid -> grid, staged through the plan's fm scratch; safe even
470553 // in place, so no aliasing guard is needed.
@@ -504,7 +587,7 @@ export class ModelPlan {
504587 // silently reroute.
505588 if (argSlot.buffer === dest.buffer) {
506589 throw new UnsupportedOnGpu(
507- `'${stmt.name} = ${ext.name}(${ext.argName})' reads and ` +
590+ `'${stmt.name} = ${ext.name}(${arg.name})' reads and ` +
508591 `writes the same buffer; assign to a new name instead`,
509592 stmt.span,
510593 );
@@ -658,6 +741,115 @@ export class ModelPlan {
658741 }
659742 }
660743
744+ /**
745+ * `f = randnfun3(lambda, gx, gy, gz)`: the seeded random field, summed
746+ * over its Fourier modes at every surface point.
747+ *
748+ * One dispatch, one thread per point. The coefficient table is not an
749+ * argument — it is a host buffer this plan binds and the host refills per
750+ * seed, the way `synth` reads Legendre matrices the .m never names. What
751+ * the .m *does* choose is the wavelength, which is recorded here so the
752+ * host draws the table for exactly that value.
753+ */
754+ async function planRandnfun3(
755+ stmt: Assign,
756+ args: IRExpr[],
757+ dest: Slot,
758+ ): Promise<void> {
759+ const lam = args[0];
760+ const lambda: Randnfun3Lambda | null =
761+ lam.kind === 'NumLit'
762+ ? { kind: 'const', value: lam.value }
763+ : lam.kind === 'Var' && paramSlots.has(lam.cName)
764+ ? { kind: 'param', name: lam.name }
765+ : null;
766+ if (!lambda) {
767+ throw new UnsupportedOnGpu(
768+ `randnfun3's wavelength is drawn on the host before the step runs, ` +
769+ `so it must be a number or a model parameter — not a value ` +
770+ `computed on the GPU`,
771+ stmt.span,
772+ );
773+ }
774+ if (randnfun3Lambda && !sameLambda(randnfun3Lambda, lambda)) {
775+ throw new UnsupportedOnGpu(
776+ `this function calls randnfun3 with two different wavelengths; ` +
777+ `one coefficient table is drawn per plan, so only one is supported`,
778+ stmt.span,
779+ );
780+ }
781+ randnfun3Lambda = lambda;
782+
783+ const points = args.slice(1).map((a) => {
784+ const v = a as IRExpr & { kind: 'Var' };
785+ const slot = slots.get(v.cName);
786+ if (!slot) {
787+ throw new UnsupportedOnGpu(
788+ `randnfun3 reads '${v.name}', which has no buffer`,
789+ stmt.span,
790+ );
791+ }
792+ return { slot, name: v.name };
793+ });
794+
795+ const modes = host.ensure(MODE_BUFFER, modeTableLength(INITIAL_MODES));
796+ const label =
797+ `${stmt.name} = randnfun3(${
798+ lambda.kind === 'const' ? lambda.value : lambda.name
799+ }, ${points.map((p) => p.name).join(', ')})`;
800+
801+ const bindGroupLayout = device.createBindGroupLayout({
802+ label: 'mgpu-randnfun3',
803+ entries: [0, 1, 2, 3, 4].map((binding) => ({
804+ binding,
805+ visibility: GPUShaderStage.COMPUTE,
806+ buffer: { type: binding === 0 ? ('storage' as const) : ('read-only-storage' as const) },
807+ })),
808+ });
809+ // The table is sized to whatever wavelength is actually asked for, so a
810+ // finer one reallocates it — and with it these bind groups, which are
811+ // the only things holding the old buffer.
812+ const bind = (table: GPUBuffer): GPUBindGroup =>
813+ device.createBindGroup({
814+ layout: bindGroupLayout,
815+ entries: [
816+ { binding: 0, resource: { buffer: dest.buffer } },
817+ ...points.map((p, i) => ({
818+ binding: i + 1,
819+ resource: { buffer: p.slot.buffer },
820+ })),
821+ { binding: 4, resource: { buffer: table } },
822+ ],
823+ });
824+
825+ // One dispatch per slice of the mode table — see randnfun3Chunks. Each
826+ // reads the same table and accumulates into the same output, so they
827+ // share a bind group and differ only in their compiled slice index.
828+ const ops: (Op & { kind: 'kernel' })[] = [];
829+ for (let chunk = 0; chunk < randnfun3Chunks; chunk++) {
830+ const chunkLabel = `${label} [${chunk + 1}/${randnfun3Chunks}]`;
831+ const op = {
832+ kind: 'kernel' as const,
833+ pipeline: await makePipeline(
834+ device,
835+ randnfun3WGSL(dest.count, chunk),
836+ chunkLabel,
837+ bindGroupLayout,
838+ ),
839+ bindGroup: bind(modes.buffer),
840+ count: dest.count,
841+ label: chunkLabel,
842+ yieldAfter: true,
843+ };
844+ ops.push(op);
845+ planned.push(op);
846+ }
847+ rebindRandnfun3 = (table: GPUBuffer): void => {
848+ const group = bind(table);
849+ for (const op of ops) op.bindGroup = group;
850+ };
851+ }
852+
661853 /**
662854 * Unroll a counted loop into the op sequence.
663855 *
@@ -739,13 +931,64 @@ export class ModelPlan {
739931 return this.#byName.get(name)?.count;
740932 }
741933
934+ /**
935+ * Run one pass of this plan, submitting in pieces so the GPU is not held for
936+ * the whole of it.
937+ *
938+ * For `init` only, and only because the seed field's mode sum can be huge:
939+ * at a fine wavelength the dispatches add up to tens of seconds, and a
940+ * browser's GPU process is shared with compositing, so one submission that
941+ * long stops the whole browser painting — the user's tabs included. Ops
942+ * marked `yieldAfter` (the randnfun3 chunks) end their submission and give
943+ * the queue back before the next one is recorded, which turns a freeze into
944+ * a wait. Everything else is recorded exactly as `encodeSteps` would.
945+ */
946+ async submitYielding(label: string): Promise<void> {
947+ let encoder = this.#device.createCommandEncoder({ label });
948+ let any = false;
949+ for (const group of this.#yieldGroups()) {
950+ if (any) {
951+ // Let the queue drain, then hand the event loop back, so compositing
952+ // and input get a turn between chunks.
953+ await this.#device.queue.onSubmittedWorkDone();
954+ await new Promise((r) => setTimeout(r, 0));
955+ encoder = this.#device.createCommandEncoder({ label });
956+ }
957+ this.#encodeOps(encoder, group);
958+ this.#device.queue.submit([encoder.finish()]);
959+ any = true;
960+ }
961+ if (!any) {
962+ this.#encodeOps(encoder, []);
963+ this.#device.queue.submit([encoder.finish()]);
964+ }
965+ }
966+
967+ /** The op list split at every `yieldAfter` boundary. */
968+ *#yieldGroups(): Generator<Op[]> {
969+ let group: Op[] = [];
970+ for (const op of this.#ops) {
971+ group.push(op);
972+ if (op.kind === 'kernel' && op.yieldAfter) {
973+ yield group;
974+ group = [];
975+ }
976+ }
977+ if (group.length) yield group;
978+ }
979+
742980 /**
743981 * Record `steps` timesteps. Synchronous: no awaits, no readback. All of the
744982 * ops share one compute pass, which WebGPU executes in submission order
745983 * with a barrier between dispatches.
746984 */
747985 encodeSteps(encoder: GPUCommandEncoder, steps: number): void {
748- for (let s = 0; s < steps; s++) {
986+ for (let s = 0; s < steps; s++) this.#encodeOps(encoder, this.#ops);
987+ }
988+
989+ /** Record one pass over `ops` into `encoder`. */
990+ #encodeOps(encoder: GPUCommandEncoder, ops: Op[]): void {
991+ {
749992 let pass: GPUComputePassEncoder | null = null;
750993 const inPass = (): GPUComputePassEncoder => {
751994 if (!pass) pass = encoder.beginComputePass({ label: 'mgpu-step' });
@@ -757,7 +1000,7 @@ export class ModelPlan {
7571000 pass = null;
7581001 }
7591002 };
760- for (const op of this.#ops) {
1003+ for (const op of ops) {
7611004 switch (op.kind) {
7621005 case 'kernel': {
7631006 const p = inPass();
@@ -847,22 +1090,58 @@ export class ModelPlan {
8471090 }
8481091 }
8491092
850-/** `x = synth(y)` / `x = analys(y)` -> the call's name and argument. */
1093+/**
1094+ * `x = synth(y)` / `x = randnfun3(lam, gx, gy, gz)` -> the call's name and
1095+ * arguments.
1096+ *
1097+ * Every external op but `randnfun3` takes exactly one array; `randnfun3`
1098+ * takes a wavelength and the three surface coordinates. Its wavelength may
1099+ * be a literal, so arguments are returned as expressions and the caller
1100+ * decides which it needs as a buffer.
1101+ */
8511102 function externalCall(
8521103 stmt: Assign,
853-): { name: string; argCName: string; argName: string } | null {
1104+): { name: string; args: IRExpr[] } | null {
8541105 const e = stmt.expr;
8551106 if (e.kind !== 'Call' || !EXTERNAL_OPS.has(e.name)) return null;
856- if (e.args.length !== 1 || e.args[0].kind !== 'Var') {
1107+ const arity = e.name === 'randnfun3' ? 4 : 1;
1108+ if (e.args.length !== arity) {
8571109 throw new UnsupportedOnGpu(
858- `'${e.name}' must be applied to a single variable`,
1110+ arity === 1
1111+ ? `'${e.name}' must be applied to a single variable`
1112+ : `'${e.name}' takes ${arity} arguments, got ${e.args.length}`,
8591113 stmt.span,
8601114 );
8611115 }
862- const arg = e.args[0];
863- return { name: e.name, argCName: arg.cName, argName: arg.name };
1116+ // Only the wavelength may be something other than a plain variable.
1117+ for (let i = e.name === 'randnfun3' ? 1 : 0; i < e.args.length; i++) {
1118+ if (e.args[i].kind !== 'Var') {
1119+ throw new UnsupportedOnGpu(
1120+ `'${e.name}' must be applied to variables, not expressions`,
1121+ stmt.span,
1122+ );
1123+ }
1124+ }
1125+ return { name: e.name, args: e.args };
8641126 }
8651127
1128+/** A `randnfun3` wavelength argument: a literal, or the parameter to read it
1129+ * from when the host fills the coefficient table. */
1130+export type Randnfun3Lambda =
1131+ | { kind: 'const'; value: number }
1132+ | { kind: 'param'; name: string };
1133+
1134+const sameLambda = (a: Randnfun3Lambda, b: Randnfun3Lambda): boolean =>
1135+ a.kind === 'const' && b.kind === 'const'
1136+ ? a.value === b.value
1137+ : a.kind === 'param' && b.kind === 'param' && a.name === b.name;
1138+
1139+/** The wavelength value a plan's `randnfun3` call resolves to. */
1140+export const resolveLambda = (
1141+ lambda: Randnfun3Lambda,
1142+ params: Record<string, number>,
1143+): number => (lambda.kind === 'const' ? lambda.value : params[lambda.name]);
1144+
8661145 function collectTensorVars(e: IRExpr, visit: (cName: string) => void): void {
8671146 const walk = (x: IRExpr): void => {
8681147 switch (x.kind) {
src/mgpu/randnfun3.tsadded+294−0View file
@@ -0,0 +1,294 @@
1+/**
2+ * `randnfun3` — a smooth random function in 3D, evaluated at the surface.
3+ *
4+ * chebfun's randnfun3 is a random trig series on a box: a few thousand
5+ * Fourier modes with independent normal coefficients, confined to a ball for
6+ * isotropy and normalized to unit variance. Restricting it to a surface is
7+ * just evaluating it at the surface's points, which is what a model's `init`
8+ * wants for a seeded initial condition (surfacefun seeds exactly this way).
9+ *
10+ * The work splits in two, and the split is forced rather than chosen:
11+ *
12+ * - **Drawing the modes needs `randn`**, which the compiled WGSL dialect has
13+ * no counterpart for, and `sqrt(nnz)` normalization, which is a reduction.
14+ * Both are a few lines of MATLAB, so the draw lives in
15+ * `tools/randnfun3.m` and runs in numbl's interpreter — a few thousand
16+ * numbers, ~5 ms.
17+ * - **Evaluating is npts x nmodes**, ~6e7 terms at the default lambda. That
18+ * is the whole cost, and it is what this file's kernel does on the GPU.
19+ *
20+ * So the .m calls `f = randnfun3(lambda, gx, gy, gz)` — chebfun's signature,
21+ * lambda in and values out — and the coefficient table is filled in behind it
22+ * by the host, the way `synth` hides its Legendre matrices. lambda is not
23+ * decorative: the plan records which parameter the .m passed, and the host
24+ * draws the table from *that* parameter's value (src/mgpu/plan.ts,
25+ * `randnfun3Lambda`), so changing it in the .m changes the field.
26+ */
27+import { executeCode } from 'numbl-src/numbl-core/executeCode.ts';
28+import { isRuntimeTensor } from 'numbl-src/numbl-core/runtime/types.ts';
29+import { toolFiles } from '../tools.ts';
30+
31+/**
32+ * Dispatches the mode sum is split across.
33+ *
34+ * lambda is an absolute length and the mode count goes as its inverse cube,
35+ * so halving lambda costs eight times the work — there is no natural ceiling
36+ * to put on that, and nothing in the method breaks as it grows. It just gets
37+ * slower, which is the caller's business. What is *not* the caller's business
38+ * is a browser's GPU-process watchdog, which kills the device outright when a
39+ * single dispatch runs too long; a fine wavelength would otherwise turn "this
40+ * takes a while" into "device lost".
41+ *
42+ * So the sum is split into a fixed number of dispatches, each covering its own
43+ * slice of the table and accumulating into the same output. The count is fixed
44+ * at plan time (the op sequence has no runtime branching) and the slice bounds
45+ * come from the table's header, so one plan serves any wavelength. Slices that
46+ * fall past the end of a small table exit immediately, which is why a coarse
47+ * wavelength pays nothing for the split.
48+ */
49+const CHUNKS = 16;
50+
51+/** Floats the table needs for `nmodes` modes. */
52+export const modeTableLength = (nmodes: number): number =>
53+ HEADER + STRIDE * nmodes;
54+
55+/** Modes a table holds, from its header. */
56+export const modeCount = (table: Float32Array): number => table[0];
57+
58+/**
59+ * Largest table this will try to build, in f32. Not a policy about how fine a
60+ * wavelength is sensible — that is the caller's call, and a fine one is
61+ * merely slow — but the point past which the draw would fail anyway: the
62+ * host-side Float32Array alone would be 8 GB. The device's own
63+ * storage-buffer limit is checked separately, when the buffer is allocated.
64+ */
65+const MAX_TABLE_FLOATS = 2 ** 31;
66+
67+/** What the table starts at, before any seed has been drawn. Big enough for
68+ * the default wavelength on the shipped surfaces, so the common case never
69+ * reallocates. */
70+export const INITIAL_MODES = 4096;
71+
72+/** Wavelength of the seeded field when the app names none. Fine enough to
73+ * give a Turing pattern plenty to grow from, coarse enough that the draw is
74+ * ~1,400 modes rather than the ~11,500 of the slider's finest setting. */
75+export const DEFAULT_LAMBDA = 0.5;
76+
77+/** Floats before the first mode: `[nmodes, 0, 0, 0]`. The count travels in
78+ * the buffer rather than a second binding, so the kernel needs one storage
79+ * buffer and the host one write. */
80+const HEADER = 4;
81+/** Floats per mode: kx, ky, kz, real, imag. */
82+const STRIDE = 5;
83+
84+/** The name the coefficient buffer takes in the plan's HostBuffers. */
85+export const MODE_BUFFER = 'randnfun3_modes';
86+
87+/** How many dispatches `randnfun3WGSL` must be planned as. */
88+export const randnfun3Chunks = CHUNKS;
89+
90+/**
91+ * One thread per surface point, summing this chunk's slice of the modes.
92+ *
93+ * The inner loop is a dot product, a cos, a sin and two multiply-adds, over a
94+ * table small enough (~1,400 modes at the default lambda) to sit in cache for
95+ * every thread. Chunk 0 initializes the output and the rest accumulate onto
96+ * it; dispatches within one compute pass are ordered, so the reads see the
97+ * previous chunk's writes. Nothing here is per-step work: `init` runs once a
98+ * seed.
99+ */
100+export function randnfun3WGSL(npts: number, chunk: number): string {
101+ return `
102+@group(0) @binding(0) var<storage, read_write> outf: array<f32>;
103+@group(0) @binding(1) var<storage, read> px: array<f32>;
104+@group(0) @binding(2) var<storage, read> py: array<f32>;
105+@group(0) @binding(3) var<storage, read> pz: array<f32>;
106+// [nmodes, _, _, _], then kx, ky, kz, re, im per mode.
107+@group(0) @binding(4) var<storage, read> modes: array<f32>;
108+
109+@compute @workgroup_size(64)
110+fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
111+ let i = gid.x;
112+ if (i >= ${npts}u) { return; }
113+ let n = u32(modes[0]);
114+ // This chunk's slice. Ceiling division, so the last slices are the short
115+ // ones and an empty slice costs a single comparison.
116+ let per = (n + ${CHUNKS}u - 1u) / ${CHUNKS}u;
117+ let lo = min(${chunk}u * per, n);
118+ let hi = min(lo + per, n);
119+ var acc = 0.0;
120+ if (lo < hi) {
121+ let x = px[i];
122+ let y = py[i];
123+ let z = pz[i];
124+ for (var m = lo; m < hi; m = m + 1u) {
125+ let b = ${HEADER}u + m * ${STRIDE}u;
126+ let t = modes[b] * x + modes[b + 1u] * y + modes[b + 2u] * z;
127+ acc = acc + modes[b + 3u] * cos(t) - modes[b + 4u] * sin(t);
128+ }
129+ }
130+${chunk === 0 ? ' outf[i] = acc;' : ' outf[i] = outf[i] + acc;'}
131+}
132+`;
133+}
134+
135+/**
136+ * Modes a wavelength will draw on a box, without drawing them: chebfun's
137+ * cube size, times the fraction its isotropy ball keeps (pi/6 of a cube,
138+ * approached from below at small m). Used to price a wavelength up front.
139+ */
140+function plannedModes(lambda: number, box: BoundingBox): number {
141+ const side = (w: number): number => 2 * Math.round((1.2 * w) / lambda + 2) + 1;
142+ const cube =
143+ side(box.x1 - box.x0) * side(box.y1 - box.y0) * side(box.z1 - box.z0);
144+ return Math.ceil((Math.PI / 6) * cube);
145+}
146+
147+/** The box a random field is drawn over: the surface's own bounding box. */
148+export interface BoundingBox {
149+ x0: number; x1: number;
150+ y0: number; y1: number;
151+ z0: number; z1: number;
152+}
153+
154+/** The bounding box of a surface, as `Geometry` holds its coordinates. */
155+export function boundingBox(
156+ x: Float32Array,
157+ y: Float32Array,
158+ z: Float32Array,
159+): BoundingBox {
160+ const box = {
161+ x0: Infinity, x1: -Infinity,
162+ y0: Infinity, y1: -Infinity,
163+ z0: Infinity, z1: -Infinity,
164+ };
165+ for (let i = 0; i < x.length; i++) {
166+ if (x[i] < box.x0) box.x0 = x[i];
167+ if (x[i] > box.x1) box.x1 = x[i];
168+ if (y[i] < box.y0) box.y0 = y[i];
169+ if (y[i] > box.y1) box.y1 = y[i];
170+ if (z[i] < box.z0) box.z0 = z[i];
171+ if (z[i] > box.z1) box.z1 = z[i];
172+ }
173+ return box;
174+}
175+
176+/**
177+ * Draw a field's modes and pack them for the GPU: `tools/randnfun3.m` run
178+ * through the interpreter, seeded, then interleaved into the buffer layout
179+ * above. Column-major out of MATLAB, interleaved on the way in.
180+ */
181+export function drawModes(
182+ lambda: number,
183+ box: BoundingBox,
184+ seed: number,
185+ /** Points the field will be summed at, for the cost budget. */
186+ npts: number,
187+): Float32Array {
188+ if (!(lambda > 0) || !Number.isFinite(lambda)) {
189+ throw new Error(`randnfun3: lambda must be a positive number, got ${lambda}`);
190+ }
191+ // The mode count follows from lambda and the box alone, so a table that
192+ // cannot be built is refused before anything is drawn. The only ceiling is
193+ // what fits: how slow a fine wavelength is, is the caller's to decide.
194+ const planned = plannedModes(lambda, box);
195+ if (modeTableLength(planned) > MAX_TABLE_FLOATS) {
196+ throw new Error(
197+ `randnfun3: lambda ${lambda} needs about ` +
198+ `${planned.toLocaleString()} Fourier modes on this surface, a ` +
199+ `${((4 * modeTableLength(planned)) / 1e9).toFixed(1)} GB table. ` +
200+ `lambda is an absolute length, so a larger surface needs more modes ` +
201+ `for the same value, and halving it costs eight times as many.`,
202+ );
203+ }
204+ const result = executeCode(
205+ 'rng(seed); [k, c] = randnfun3(lambda, [x0 x1 y0 y1 z0 z1]);',
206+ {
207+ initialVariableValues: { lambda, seed, ...box },
208+ displayResults: false,
209+ implicitCwdPath: null,
210+ },
211+ toolFiles,
212+ 'randnfun3-driver.m',
213+ );
214+ const k = result.variableValues['k'];
215+ const c = result.variableValues['c'];
216+ if (!k || !c || !isRuntimeTensor(k) || !isRuntimeTensor(c)) {
217+ throw new Error("randnfun3: tools/randnfun3.m did not return [k, c] arrays");
218+ }
219+ const nmodes = k.shape[0];
220+ const out = new Float32Array(modeTableLength(nmodes));
221+ out[0] = nmodes;
222+ for (let i = 0; i < nmodes; i++) {
223+ const b = HEADER + STRIDE * i;
224+ out[b] = k.data[i]; // kx
225+ out[b + 1] = k.data[nmodes + i]; // ky
226+ out[b + 2] = k.data[2 * nmodes + i]; // kz
227+ out[b + 3] = c.data[i]; // real
228+ out[b + 4] = c.data[nmodes + i]; // imag
229+ }
230+ return out;
231+}
232+
233+/**
234+ * `drawModes` on a worker thread, so a fine wavelength does not freeze the
235+ * page (src/mgpu/randnfun3.worker.ts).
236+ *
237+ * Falls back to drawing in place where there is no `Worker` — the node test
238+ * runner and the desktop benchmark, neither of which has an event loop it
239+ * would matter to. Failures surface as a rejection either way, so a caller
240+ * never has to know which path ran.
241+ */
242+export function drawModesAsync(
243+ lambda: number,
244+ box: BoundingBox,
245+ seed: number,
246+ npts: number,
247+): Promise<Float32Array> {
248+ if (typeof Worker === 'undefined') {
249+ try {
250+ return Promise.resolve(drawModes(lambda, box, seed, npts));
251+ } catch (e) {
252+ return Promise.reject(e instanceof Error ? e : new Error(String(e)));
253+ }
254+ }
255+ const w = drawWorker();
256+ const id = nextDrawId++;
257+ return new Promise((resolve, reject) => {
258+ pendingDraws.set(id, { resolve, reject });
259+ w.postMessage({ id, lambda, box, seed, npts });
260+ });
261+}
262+
263+let worker: Worker | null = null;
264+let nextDrawId = 1;
265+const pendingDraws = new Map<
266+ number,
267+ { resolve: (t: Float32Array) => void; reject: (e: Error) => void }
268+>();
269+
270+/** The draw worker, started on first use and kept for the session — starting
271+ * one re-parses numbl, which costs more than a coarse draw does. */
272+function drawWorker(): Worker {
273+ if (worker) return worker;
274+ worker = new Worker(new URL('./randnfun3.worker.ts', import.meta.url), {
275+ type: 'module',
276+ });
277+ worker.onmessage = (e: MessageEvent<{ id: number; table?: Float32Array; error?: string }>): void => {
278+ const waiting = pendingDraws.get(e.data.id);
279+ if (!waiting) return;
280+ pendingDraws.delete(e.data.id);
281+ if (e.data.error !== undefined) waiting.reject(new Error(e.data.error));
282+ else waiting.resolve(e.data.table!);
283+ };
284+ worker.onerror = (e: ErrorEvent): void => {
285+ // A worker that died takes every outstanding draw with it.
286+ for (const [, waiting] of pendingDraws) {
287+ waiting.reject(new Error(`randnfun3 draw worker failed: ${e.message}`));
288+ }
289+ pendingDraws.clear();
290+ worker?.terminate();
291+ worker = null;
292+ };
293+ return worker;
294+}
src/mgpu/randnfun3.worker.tsadded+40−0View file
@@ -0,0 +1,40 @@
1+/**
2+ * Drawing a seed field's Fourier modes, off the main thread.
3+ *
4+ * The draw is `tools/randnfun3.m` in numbl's interpreter, and its cost goes as
5+ * the inverse cube of the wavelength: milliseconds at the default lambda, but
6+ * ~13 s at lambda 0.01. Synchronous JS that long does not merely feel slow —
7+ * it blocks the event loop outright, so the page stops painting and the
8+ * browser offers to kill it. Nothing about the draw needs the main thread
9+ * (it touches no GPU and no DOM), so it runs here and the result is
10+ * transferred back.
11+ */
12+import { drawModes, type BoundingBox } from './randnfun3.ts';
13+
14+export interface DrawRequest {
15+ id: number;
16+ lambda: number;
17+ box: BoundingBox;
18+ seed: number;
19+ npts: number;
20+}
21+
22+export type DrawReply =
23+ | { id: number; table: Float32Array; error?: undefined }
24+ | { id: number; table?: undefined; error: string };
25+
26+self.onmessage = (e: MessageEvent<DrawRequest>): void => {
27+ const { id, lambda, box, seed, npts } = e.data;
28+ let reply: DrawReply;
29+ let transfer: Transferable[] = [];
30+ try {
31+ const table = drawModes(lambda, box, seed, npts);
32+ reply = { id, table };
33+ transfer = [table.buffer];
34+ } catch (err) {
35+ reply = { id, error: err instanceof Error ? err.message : String(err) };
36+ }
37+ (self as unknown as {
38+ postMessage: (m: DrawReply, t: Transferable[]) => void;
39+ }).postMessage(reply, transfer);
40+};
src/mgpu/registry.tsmodified+7−0View file
@@ -26,6 +26,13 @@ export interface ParamSpec {
2626 min: number;
2727 max: number;
2828 step: number;
29+ /**
30+ * This parameter is a random seed: its value picks a draw and means nothing
31+ * on its own, so the UI offers a button that jumps to another one rather
32+ * than a box to type a number into. `min`/`max` still bound what the button
33+ * picks.
34+ */
35+ reseed?: boolean;
2936 }
3037
3138 export interface MModel {
src/mgpu/session.tsmodified+144−25View file
@@ -11,6 +11,8 @@ import { DerivPlan } from '../sht/deriv.ts';
1111 import { gridForLmax, type ShtConfig } from '../sht/layout.ts';
1212 import { GpuModel, type ModelParams } from './model.ts';
1313 import { seededNoise } from './noise.ts';
14+import { boundingBox, drawModesAsync, DEFAULT_LAMBDA } from './randnfun3.ts';
15+import { resolveLambda } from './plan.ts';
1416 import type { MModel } from './registry.ts';
1517 import { Geometry } from '../geom/geometry.ts';
1618 import { mGeometryByKey, defaultGeometryParams, SPHERE_KEY, type MGeometry } from '../geom/registry.ts';
@@ -36,6 +38,9 @@ export interface ModelSessionOptions {
3638 * is unrolled into the op sequence, so a change recompiles.
3739 */
3840 niter?: number;
41+ /** Wavelength of the seeded random field a model's `init` draws
42+ * (src/mgpu/randnfun3.ts). Redrawn on the next seed, never recompiled. */
43+ lam3?: number;
3944 }
4045
4146 export class ModelSession {
@@ -62,6 +67,10 @@ export class ModelSession {
6267 /** Display-only transforms on the oversampled grid; null at 1x. */
6368 #displaySht: ShtPlan | null;
6469 #oversample: number;
70+ /** Wavelength of the seeded random field, and the seed it was drawn from —
71+ * kept so changing one can redraw with the other unchanged. */
72+ #lam3: number;
73+ #seed = 1;
6574
6675 private constructor(init: {
6776 device: GPUDevice;
@@ -76,6 +85,7 @@ export class ModelSession {
7685 geometryModel: MGeometry;
7786 deriv: DerivPlan;
7887 niter: number;
88+ lam3: number;
7989 }) {
8090 this.device = init.device;
8191 this.model = init.model;
@@ -90,6 +100,7 @@ export class ModelSession {
90100 this.#geometryModel = init.geometryModel;
91101 this.#deriv = init.deriv;
92102 this.niter = init.niter;
103+ this.#lam3 = init.lam3;
93104 }
94105
95106 get geometry(): Geometry {
@@ -138,7 +149,6 @@ export class ModelSession {
138149 // buffers of numbers (the embedding, and both metric formulations built
139150 // on it: the inverse metric quantities and the flux-form weights).
140151 const geometry = await Geometry.create({
141- device,
142152 sht,
143153 cfg,
144154 source: opts.geometrySource ?? geometryModel.source,
@@ -158,10 +168,11 @@ export class ModelSession {
158168 deriv,
159169 niter,
160170 });
161- gpu.setParams(params);
171+ const lam3 = opts.lam3 ?? DEFAULT_LAMBDA;
172+ gpu.setParams({ lam3, ...params });
162173 return new ModelSession({
163174 device, model, cfg, sht, displaySht, gpu, params, oversample,
164- geometry, geometryModel, deriv, niter,
175+ geometry, geometryModel, deriv, niter, lam3,
165176 });
166177 } catch (e) {
167178 // The transform plans own GPU buffers; do not leak them on a compile error.
@@ -194,7 +205,6 @@ export class ModelSession {
194205 source?: string,
195206 ): Promise<void> {
196207 const next = await Geometry.create({
197- device: this.device,
198208 sht: this.sht,
199209 cfg: this.cfg,
200210 source: source ?? geometryModel.source,
@@ -224,32 +234,127 @@ export class ModelSession {
224234 */
225235 async setOversample(oversample: number): Promise<void> {
226236 const os = Math.max(1, Math.round(oversample));
227- if (os === this.#oversample) return;
228- const next =
229- os > 1
230- ? await ShtPlan.create(this.device, {
231- lmax: this.cfg.lmax,
232- mmax: this.cfg.mmax,
233- nlat: os * this.cfg.nlat,
234- nphi: os * this.cfg.nphi,
235- })
236- : null;
237+ await this.setDisplayGrid(os * this.cfg.nlat, os * this.cfg.nphi);
238+ }
239+
240+ /**
241+ * Point the display plan at an arbitrary grid, rather than an integer
242+ * multiple of the solver's. Same contract as setOversample — display-only,
243+ * no readback may be in flight — and the same exactness argument, which does
244+ * not care about the ratio: the state is band-limited at lmax, so
245+ * synthesizing it anywhere is evaluation, not resampling. What this adds is a
246+ * grid that need not be *finer*: several sessions at different lmax can be
247+ * put on one common grid, which is what makes their fields directly
248+ * comparable point by point and lets one mesh serve all of them.
249+ */
250+ async setDisplayGrid(nlat: number, nphi: number): Promise<void> {
251+ const view = this.viewSht.cfg;
252+ if (nlat === view.nlat && nphi === view.nphi) return;
253+ const onSolverGrid = nlat === this.cfg.nlat && nphi === this.cfg.nphi;
254+ const next = onSolverGrid
255+ ? null
256+ : await ShtPlan.create(this.device, {
257+ lmax: this.cfg.lmax,
258+ mmax: this.cfg.mmax,
259+ nlat,
260+ nphi,
261+ });
237262 const old = this.#displaySht;
238263 this.#displaySht = next;
239- this.#oversample = os;
264+ this.#oversample = nlat / this.cfg.nlat;
240265 old?.destroy();
241266 }
242267
268+ /**
269+ * The coefficient table a model that calls `randnfun3` seeds from — drawn
270+ * over the current surface's bounding box, at the wavelength its own .m asked
271+ * for — or null for a model that seeds some other way. The draw is host-side
272+ * MATLAB (a few ms); the evaluation at every grid point is the GPU kernel
273+ * inside `init`.
274+ *
275+ * Separate from `seed` because the table is a function of space, not of a
276+ * grid: drawn once, it is the *same field* wherever it is evaluated, which is
277+ * how every variant of a comparison across lmax seeds from one random field
278+ * (see src/compare/sharedStart.ts).
279+ */
280+ drawSeedModes(seed: number): Promise<Float32Array | null> {
281+ const lambda = this.gpu.randnfun3Lambda;
282+ if (!lambda) return Promise.resolve(null);
283+ // Drawn on a worker: at a fine wavelength this is seconds of interpreter
284+ // time, and it must not be seconds of frozen page.
285+ return drawModesAsync(
286+ resolveLambda(lambda, this.#mergedParams()),
287+ boundingBox(this.#geometry.x, this.#geometry.y, this.#geometry.z),
288+ seed,
289+ this.npts,
290+ );
291+ }
292+
243293 /** Run `init` from a seeded perturbation, resetting model time. */
244- seed(seed: number): void {
245- this.gpu.init(seededNoise(this.npts, this.model.seedAmp, seed));
294+ async seed(seed: number): Promise<void> {
295+ const modes = await this.drawSeedModes(seed);
296+ await this.seedWith(seededNoise(this.npts, this.model.seedAmp, seed), modes);
297+ this.#seed = seed;
298+ }
299+
300+ /**
301+ * Run `init` from a caller-supplied perturbation, resetting model time.
302+ * `seed()` is this with what this session would draw for itself: the host
303+ * RNG's field on its own grid, and its own random-field table. Supplying them
304+ * instead is how several sessions on *different* grids can be started from
305+ * the same initial condition, which is the only way a comparison across lmax
306+ * compares one problem rather than two (see src/compare/sharedStart.ts).
307+ */
308+ async seedWith(noise: Float32Array, modes: Float32Array | null = null): Promise<void> {
309+ if (noise.length !== this.npts) {
310+ throw new Error(`seedWith: noise must have length ${this.npts} (got ${noise.length})`);
311+ }
312+ await this.gpu.init(noise, modes);
313+ this.t = 0;
314+ this.steps = 0;
315+ }
316+
317+ /**
318+ * Push an exact spectral state into the running model, bypassing seeded
319+ * init, and reset model time like seed() does. `gpu.step(0)` flips which
320+ * of the init/step buffer aliases a read resolves to, without otherwise
321+ * touching the state — see GpuModel's `#lastRan`.
322+ */
323+ loadState(coeffs: Record<string, Float32Array>): void {
324+ for (const name of this.model.state) {
325+ const data = coeffs[name];
326+ if (!data) throw new Error(`loadState: missing state '${name}'`);
327+ this.gpu.upload(name, data);
328+ }
329+ this.gpu.step(0);
246330 this.t = 0;
247331 this.steps = 0;
248332 }
249333
334+ /** The model's parameters plus the ones the host owns. */
335+ #mergedParams(): ModelParams {
336+ return { lam3: this.#lam3, ...this.#params };
337+ }
338+
250339 setParams(params: ModelParams): void {
251340 this.#params = params;
252- this.gpu.setParams(params);
341+ this.gpu.setParams(this.#mergedParams());
342+ }
343+
344+ /** Wavelength of the seeded random field. Redraws on the next seed. */
345+ get lam3(): number {
346+ return this.#lam3;
347+ }
348+
349+ /**
350+ * Change the random field's wavelength. Nothing recompiles — lam3 is a
351+ * uniform and the coefficient table is host-drawn — but the field itself
352+ * only changes on the next `seed`, which is where it is drawn.
353+ */
354+ setLam3(lambda: number): void {
355+ if (lambda === this.#lam3) return;
356+ this.#lam3 = lambda;
357+ this.gpu.setParams(this.#mergedParams());
253358 }
254359
255360 /** Advance `n` steps. Synchronous: records and submits, nothing read back. */
@@ -293,18 +398,32 @@ export class ModelSession {
293398 }
294399
295400 /**
296- * Read species `k` at render resolution (`viewSht`'s grid). Without
297- * oversampling this is the grid field the .m returned. With oversampling the
298- * spectral state is synthesized on the finer grid instead — the same field,
299- * since the models define each species as synth of its state, evaluated
300- * exactly on more points.
401+ * Read every state species back to the CPU, in the shape `loadState`
402+ * consumes — the capture side of that method's reload, so a caller can
403+ * hold onto the current spectral state and restore it exactly later
404+ * (e.g. a "restart to this run's initial condition" control). One at a
405+ * time, not `Promise.all`: every `read()` copies into the same shared
406+ * readback buffer (`GpuModel#readback`, model.ts:448-452), so two in
407+ * flight at once race `mapAsync` against each other's `unmap`.
408+ */
409+ async readState(): Promise<Record<string, Float32Array>> {
410+ const out: Record<string, Float32Array> = {};
411+ for (const name of this.model.state) out[name] = await this.read(name);
412+ return out;
413+ }
414+
415+ /**
416+ * Read species `k` at render resolution (`viewSht`'s grid): the spectral
417+ * state synthesized there. The models define each species as synth of its
418+ * state, so this is the field the .m returned — evaluated exactly, whatever
419+ * the grid — and it is current however the state last changed, including a
420+ * `loadState`, which runs no kernel that would write the grid-space fields.
301421 */
302422 readSpecies(k: number): Promise<Float32Array> {
303- if (!this.#displaySht) return this.read(this.model.species[k]);
304423 const state = this.model.state[k];
305424 const buf = this.gpu.valueBuffer(state);
306425 if (!buf) throw new Error(`readSpecies: no buffer for state '${state}'`);
307- return this.#displaySht.synthFrom(buf);
426+ return this.viewSht.synthFrom(buf);
308427 }
309428
310429 describe(): { init: string[]; step: string[] } {
src/raw.d.tsmodified+10−0View file
@@ -3,3 +3,13 @@ declare module '*?raw' {
33 const source: string;
44 export default source;
55 }
6+
7+/** Vite's `import.meta.glob`, used to load every .m in tools/ at once
8+ * (src/tools.ts). Only the eager + `?raw` form this project uses is
9+ * declared — it returns each match's text, keyed by path. */
10+interface ImportMeta {
11+ glob(
12+ pattern: string,
13+ options: { query: '?raw'; eager: true; import: 'default' },
14+ ): Record<string, string>;
15+}
src/render/colorbar.tsmodified+52−0View file
@@ -4,6 +4,58 @@ import type { ColormapFunc } from './colormaps.ts';
44 export const fmtValue = (v: number): string =>
55 Number.isFinite(v) ? v.toPrecision(3).replace(/\.?0+$/, '') : '—';
66
7+/**
8+ * Smallest span the colormap may be stretched across, relative to the field's
9+ * own magnitude.
10+ *
11+ * Set from measurement, not taste. A constant field analysed and re-synthesized
12+ * in fp32 comes back constant only to
13+ *
14+ * lmax 63: 2.9e-5 relative lmax 127: 9.6e-5 lmax 255: 2.4e-4
15+ *
16+ * and the residue is not white noise — it is concentrated in a few rings at the
17+ * poles (74x the equatorial level at lmax 63, 1710x at lmax 255), because what
18+ * survives the analysis is high-degree m = 0 content whose Legendre functions
19+ * all peak at the poles *and add in phase there*. The same round trip in f64 is
20+ * 2.4e-8 and flat, so this is fp32, not the algorithm.
21+ *
22+ * A floor of 1e-2 puts the worst of that (about 5e-4 of span at lmax 255) into
23+ * roughly 5% of the colormap rather than all of it, while the variation these
24+ * models actually carry — a few percent of the field's magnitude and up — is
25+ * left alone entirely.
26+ */
27+const RANGE_FLOOR_REL = 1e-2;
28+/** And an absolute floor, for a field whose magnitude is itself near zero. */
29+const RANGE_FLOOR_ABS = 1e-9;
30+
31+/**
32+ * Widen a value range so that a field which is uniform to numerical precision
33+ * is drawn as uniform.
34+ *
35+ * Scaling the colormap to a field's own extremes gives full contrast to
36+ * whatever variation it has — including none. Schnakenberg's `v` at t = 0 is
37+ * literally constant (`vs * ones(...)`), so its extremes are set purely by the
38+ * roundoff described above; painting that across the whole colormap produces a
39+ * vivid pole-capped picture that reads as structure, and since the residue
40+ * belongs to the grid, two runs at different lmax produce two entirely
41+ * different pictures of the same constant — which looks exactly like a broken
42+ * initial condition, and is not one.
43+ *
44+ * A floor rather than an "is this field constant?" test, so nothing ever jumps:
45+ * a real pattern growing up through the floor hands the range over from the
46+ * floor to its own data gradually, and once it is any larger than roundoff the
47+ * floor has no effect at all.
48+ */
49+export function floorRange(lo: number, hi: number): { lo: number; hi: number } {
50+ const minSpan = Math.max(
51+ RANGE_FLOOR_ABS,
52+ RANGE_FLOOR_REL * Math.max(Math.abs(lo), Math.abs(hi)),
53+ );
54+ if (hi - lo >= minSpan) return { lo, hi };
55+ const mid = (lo + hi) / 2;
56+ return { lo: mid - minSpan / 2, hi: mid + minSpan / 2 };
57+}
58+
759 /** Vertical colorbar drawn on a small canvas, with min/max labels. */
860 export class Colorbar {
961 #canvas: HTMLCanvasElement;
src/sht/sht.tsmodified+13−1View file
@@ -776,8 +776,20 @@ export async function requestShtDevice(): Promise<GPUDevice> {
776776 // timestamp-query is only used by the profiling scripts, but it has to be
777777 // requested at device creation, and asking costs nothing when unused.
778778 if (adapter.features.has('timestamp-query')) features.push('timestamp-query');
779+ // The seed field's mode table is the one buffer whose size is not fixed by
780+ // the grid — it grows with how fine a wavelength is asked for
781+ // (src/mgpu/randnfun3.ts), and a browser's default 128 MB storage-buffer
782+ // limit is well below what the adapter will actually give. Ask for the
783+ // adapter's own maximum so the wavelength is limited by the hardware rather
784+ // than by a default.
785+ const maxStorage = adapter.limits.maxStorageBufferBindingSize;
786+ const maxBuffer = adapter.limits.maxBufferSize;
779787 return adapter.requestDevice({
780788 requiredFeatures: features,
781- requiredLimits: { maxComputeWorkgroupStorageSize: wgStorage },
789+ requiredLimits: {
790+ maxComputeWorkgroupStorageSize: wgStorage,
791+ maxStorageBufferBindingSize: maxStorage,
792+ maxBufferSize: maxBuffer,
793+ },
782794 });
783795 }
src/tools.tsadded+27−0View file
@@ -0,0 +1,27 @@
1+/**
2+ * The shared MATLAB utilities in `tools/`, as interpreter workspace files.
3+ *
4+ * A geometry or a seeding draw is evaluated by numbl's interpreter (see
5+ * src/geom/geometry.ts), which resolves a call like `randnfunsphere(...)`
6+ * against the workspace files it is handed. Everything in `tools/` is handed
7+ * to every such run, so any .m can call any tool by name — MATLAB's own path
8+ * semantics, where the file name is the function name.
9+ *
10+ * These are *not* available to the models: a model's step compiles to WGSL,
11+ * where none of this exists.
12+ */
13+const sources = import.meta.glob('../tools/*.m', {
14+ query: '?raw',
15+ eager: true,
16+ import: 'default',
17+}) as Record<string, string>;
18+
19+export interface ToolFile {
20+ name: string;
21+ source: string;
22+}
23+
24+/** Every tool, named as MATLAB wants it (`randnfunsphere.m`). */
25+export const toolFiles: ToolFile[] = Object.entries(sources)
26+ .map(([path, source]) => ({ name: path.slice(path.lastIndexOf('/') + 1), source }))
27+ .sort((a, b) => a.name.localeCompare(b.name));
test/analyticChecks.tsmodified+2−3View file
@@ -65,7 +65,6 @@ async function makeModel(
6565 const sht = await ShtPlan.create(device, cfg);
6666 const deriv = await DerivPlan.create(device, sht);
6767 const geometry = await Geometry.create({
68- device,
6968 sht,
7069 cfg,
7170 source: mGeometryByKey(SPHERE_KEY)!.source,
@@ -163,7 +162,7 @@ export async function analyticChecks(
163162
164163 // Uniform initial field: stays uniform, and diffusion cannot touch it.
165164 const field = new Float32Array(npts).fill(u0);
166- gpu.init(field);
165+ await gpu.init(field, null);
167166 const Ustart = await gpu.read('U');
168167 gpu.step(nsteps);
169168 const Uend = await gpu.read('U');
@@ -220,7 +219,7 @@ export async function analyticChecks(
220219
221220 // Seed the exact homogeneous fixed point by handing init a zero
222221 // perturbation, then add a small single-mode bump to u only.
223- gpu.init(new Float32Array(npts));
222+ await gpu.init(new Float32Array(npts), null);
224223 const l = 24;
225224 const m = 7;
226225 const idx = lmIndex(lmax, l, m);
test/compareChecks.tsadded+371−0View file
@@ -0,0 +1,371 @@
1+/**
2+ * The two things a side-by-side comparison of solver settings rests on.
3+ *
4+ * Both are silent when broken: the panels still animate, the difference norm
5+ * still produces a number, and the number is simply wrong — it reports a
6+ * disagreement between two runs that were never solving the same problem, or
7+ * that were never at the same time. Neither failure looks like a failure, which
8+ * is exactly why they are pinned here.
9+ *
10+ * 1. One initial condition, in both of the ways a model can seed. A model
11+ * that calls `randnfun3` — every shipped one does — gets a field in space,
12+ * so one table drawn once is one field on every grid; the control is the
13+ * per-session draw the study must not do. A model that takes `noise` gets
14+ * one deviate per grid point, which sharedNoise has to project; the
15+ * control there is starker, since the same integer seed on two grids is
16+ * simply two unrelated fields.
17+ *
18+ * 2. One clock. dt varies by a power-of-two divisor, so `steps * dt` is
19+ * bit-identical across variants and no comparison is ever made across a
20+ * fraction of a timestep.
21+ *
22+ * Deliberately small — pairs of sessions at niter 1, lmax 31 and 63 — because a
23+ * session compiles its whole unrolled step and this suite has to stay short.
24+ */
25+import { ModelSession } from '../src/mgpu/session.ts';
26+import { mModelByKey, defaultParams, type MModel, type ParamSpec } from '../src/mgpu/registry.ts';
27+import { prolongCoeffs, sharedNoise, sharedModes } from '../src/compare/sharedStart.ts';
28+import linearSource from './models/linear.m?raw';
29+import { lmIndex, nlmCalc } from '../src/sht/layout.ts';
30+import { crossProduct, mostResolved } from '../src/compare/variants.ts';
31+import { floorRange } from '../src/render/colorbar.ts';
32+
33+type Check = (name: string, ok: boolean, detail: string) => void;
34+type Log = (line: string) => void;
35+
36+const COARSE = 31;
37+const FINE = 63;
38+
39+export async function compareChecks(
40+ device: GPUDevice,
41+ check: Check,
42+ log: Log,
43+): Promise<void> {
44+ log('\ncompare mode (convergence study):');
45+
46+ // ---- prolongCoeffs: every (l, m) lands on itself -------------------------
47+ {
48+ const src = new Float32Array(2 * nlmCalc(COARSE, COARSE));
49+ for (let m = 0; m <= COARSE; m++) {
50+ for (let l = m; l <= COARSE; l++) {
51+ const i = 2 * lmIndex(COARSE, l, m);
52+ src[i] = l + m / 100;
53+ src[i + 1] = -l - m / 100;
54+ }
55+ }
56+ const out = prolongCoeffs(src, COARSE, FINE);
57+ let moved = 0;
58+ let leaked = 0;
59+ for (let m = 0; m <= FINE; m++) {
60+ for (let l = m; l <= FINE; l++) {
61+ const j = 2 * lmIndex(FINE, l, m);
62+ if (l <= COARSE && m <= COARSE) {
63+ const i = 2 * lmIndex(COARSE, l, m);
64+ if (out[j] !== src[i] || out[j + 1] !== src[i + 1]) moved++;
65+ } else if (out[j] !== 0 || out[j + 1] !== 0) {
66+ leaked++;
67+ }
68+ }
69+ }
70+ check(
71+ 'compare: prolongation puts every coefficient at its own (l, m)',
72+ moved === 0 && leaked === 0,
73+ `${moved} misplaced, ${leaked} non-zero above the source band ` +
74+ `(${nlmCalc(COARSE, COARSE)} -> ${nlmCalc(FINE, FINE)} coefficients)`,
75+ );
76+ }
77+
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+
145+ // ---- one random field across lmax: the shipped models' seeding -----------
146+ {
147+ const model = mModelByKey('schnakenberg')!;
148+ const params = defaultParams(model);
149+ const sessions: ModelSession[] = [];
150+ try {
151+ for (const lmax of [COARSE, FINE]) {
152+ sessions.push(await ModelSession.create({ device, model, params, lmax, niter: 1 }));
153+ }
154+ const [coarse, fine] = sessions;
155+
156+ // What the study does: one coefficient table, drawn once, summed on each
157+ // variant's own grid points. The residual is the coarse grid's analysis of
158+ // a field with a little content above its band, not a difference in the
159+ // field -- so it is bounded by the perturbation, not by |U|, which is why
160+ // compareStates measures against the non-constant part.
161+ const noise = await sharedNoise(sessions, model.seedAmp, 1);
162+ const modes = await sharedModes(fine, 1);
163+ check(
164+ 'compare: a randnfun3 model seeds every variant from one drawn table',
165+ modes !== null,
166+ modes ? `${modes[0]} Fourier modes, one table for both grids` : 'no table drawn',
167+ );
168+ for (let i = 0; i < sessions.length; i++) await sessions[i].seedWith(noise[i], modes);
169+ const shared = compareStates(
170+ prolongCoeffs(await coarse.read('U'), COARSE, FINE),
171+ await fine.read('U'),
172+ );
173+ check(
174+ 'compare: one shared random field gives both grids the same state',
175+ shared.rel < 1e-3,
176+ `max |dU| = ${shared.abs.toExponential(2)} ` +
177+ `(${(100 * shared.rel).toFixed(3)}% of the perturbation, max ` +
178+ `${shared.scale.toExponential(2)}) across lmax ${COARSE} vs ${FINE}`,
179+ );
180+
181+ // The control, and the reason `sharedModes` exists: left to seed itself
182+ // each session draws over *its own* bounding box, and a box is grid
183+ // samples of the surface, so the two draws are near neighbours rather than
184+ // one field. A tolerance is not what separates them — the shared table is
185+ // simply closer, and would be however either number moved.
186+ await coarse.seed(1);
187+ await fine.seed(1);
188+ const own = compareStates(
189+ prolongCoeffs(await coarse.read('U'), COARSE, FINE),
190+ await fine.read('U'),
191+ );
192+ check(
193+ 'compare: control — a per-session draw is not the same field',
194+ own.abs > shared.abs,
195+ `per-session draws differ by ${own.abs.toExponential(2)}, ` +
196+ `${(own.abs / Math.max(shared.abs, 1e-30)).toFixed(1)}x the shared table's ` +
197+ `${shared.abs.toExponential(2)}`,
198+ );
199+ } finally {
200+ for (const s of sessions) s.destroy();
201+ }
202+ }
203+
204+ // ---- one grid-point perturbation across lmax, and the control ------------
205+ // The other way a model can seed: `init(noise)` takes the host's field
206+ // directly, one deviate per grid point (the test models here, and any .m
207+ // edited to do it). Nothing about it is a function of space, so this is the
208+ // case sharedNoise's projection is for — and the case where the same integer
209+ // seed on two grids gives two entirely unrelated initial conditions.
210+ {
211+ const params = { c: 0, D: 1e-3, dt: 0.05 };
212+ const model = noiseModel();
213+ const sessions: ModelSession[] = [];
214+ try {
215+ for (const lmax of [COARSE, FINE]) {
216+ sessions.push(await ModelSession.create({ device, model, params, lmax, niter: 1 }));
217+ }
218+ const [coarse, fine] = sessions;
219+
220+ const noise = await sharedNoise(sessions, model.seedAmp, 1);
221+ for (let i = 0; i < sessions.length; i++) await sessions[i].seedWith(noise[i]);
222+ const shared = compareStates(
223+ prolongCoeffs(await coarse.read('U'), COARSE, FINE),
224+ await fine.read('U'),
225+ );
226+ check(
227+ 'compare: one shared perturbation gives both grids the same state',
228+ shared.rel < 5e-5,
229+ `max |dU| = ${shared.abs.toExponential(2)} ` +
230+ `(${(100 * shared.rel).toFixed(4)}% of max |U| = ${shared.scale.toExponential(2)}) ` +
231+ `across lmax ${COARSE} vs ${FINE}`,
232+ );
233+
234+ await coarse.seed(1);
235+ await fine.seed(1);
236+ const plain = compareStates(
237+ prolongCoeffs(await coarse.read('U'), COARSE, FINE),
238+ await fine.read('U'),
239+ );
240+ check(
241+ 'compare: control — the same integer seed alone does not do it',
242+ plain.abs > 20 * shared.abs,
243+ `per-grid seeding differs by ${plain.abs.toExponential(2)}, ` +
244+ `${(plain.abs / Math.max(shared.abs, 1e-30)).toExponential(1)}x the shared start's ` +
245+ `(seed amplitude ${model.seedAmp})`,
246+ );
247+ log(
248+ ` shared start: ${shared.abs.toExponential(2)}, ` +
249+ `per-grid seeds: ${plain.abs.toExponential(2)}`,
250+ );
251+ } finally {
252+ for (const s of sessions) s.destroy();
253+ }
254+ }
255+
256+ // ---- one clock: steps * dt is bit-identical across the divisors ----------
257+ {
258+ const divisors = [1, 2, 4, 8];
259+ const steps = 4;
260+ let worst = 0;
261+ const cases: string[] = [];
262+ for (const model of ['schnakenberg', 'brusselator', 'allencahn']) {
263+ const dt = defaultParams(mModelByKey(model)!).dt;
264+ for (const div of divisors) {
265+ // A variant at dt/div takes div times as many steps to cover the same
266+ // span. Powers of two only touch the exponent, so both the divide and
267+ // the multiply back are exact and the two spans are the same float.
268+ const span = (steps * div) * (dt / div);
269+ const ulps = Math.abs(span - steps * dt);
270+ if (ulps > worst) worst = ulps;
271+ if (div === divisors[divisors.length - 1]) {
272+ cases.push(`${model} dt ${dt} -> ${dt / div}`);
273+ }
274+ }
275+ }
276+ check(
277+ 'compare: a power-of-two dt divisor keeps every variant on one clock',
278+ worst === 0,
279+ `exact for every shipped dt x ${divisors.join('/')} (${cases.join(', ')})`,
280+ );
281+ }
282+
283+ // ---- a uniform field is drawn uniform, on every grid --------------------
284+ // Schnakenberg seeds v as a literal constant (`vs * ones(...)`), so its whole
285+ // spread is the fp32 residue of the analys/synth round trip -- pole-localized
286+ // and grid-dependent, so scaled to its own extremes it paints two unrelated
287+ // pictures of the same constant, which is what a broken seeding would look
288+ // like. The spans below are measured (worst |deviation| x 2, on vs = 0.9):
289+ // lmax 63, 127, 255. See floorRange for where they come from.
290+ {
291+ const vs = 0.9;
292+ const spans = [5.2e-5, 1.8e-4, 4.4e-4];
293+ // Each must end up a small slice of the drawn range rather than all of it.
294+ const shares = spans.map((sp) => sp / (floorRange(vs - sp / 2, vs + sp / 2).hi -
295+ floorRange(vs - sp / 2, vs + sp / 2).lo));
296+ // ...while real structure keeps its own range exactly. v once the spots
297+ // have formed spans ~0.03 on the same 0.9, two orders above the residue.
298+ const real = floorRange(0.895, 0.924);
299+ check(
300+ 'compare: fp32 residue on a constant field does not become a picture',
301+ shares.every((s) => s < 0.1) && real.lo === 0.895 && real.hi === 0.924,
302+ `residue uses ${shares.map((s) => `${(100 * s).toFixed(1)}%`).join(', ')} ` +
303+ `of the colormap at lmax 63/127/255; real pattern ` +
304+ `[${real.lo}, ${real.hi}] left untouched`,
305+ );
306+ }
307+
308+ // ---- the variant grid and its reference ---------------------------------
309+ {
310+ const variants = crossProduct([1, 4], [31, 63], [1, 2]);
311+ const ref = variants[mostResolved(variants)];
312+ check(
313+ 'compare: the reference is the most-resolved corner of the grid',
314+ variants.length === 8 &&
315+ ref.niter === 4 && ref.lmax === 63 && ref.dtDiv === 2 &&
316+ new Set(variants.map((v) => `${v.niter}/${v.lmax}/${v.dtDiv}`)).size === 8,
317+ `${variants.length} distinct variants, reference niter ${ref.niter} · ` +
318+ `lmax ${ref.lmax} · dt/${ref.dtDiv}`,
319+ );
320+ }
321+}
322+
323+/**
324+ * The one-species linear test model, seeded from `noise` rather than from a
325+ * random field — `init(noise)`, so the host's grid-point field is what reaches
326+ * the state (test/models/linear.m). Never stepped here; the parameters exist
327+ * because the .m names them.
328+ */
329+function noiseModel(): MModel {
330+ const param = (key: string): ParamSpec => ({
331+ key, label: key, value: 0, min: -1e9, max: 1e9, step: 1,
332+ });
333+ return {
334+ key: 'linear',
335+ label: 'linear',
336+ blurb: '',
337+ species: ['u'],
338+ state: ['U'],
339+ params: ['c', 'D', 'dt'].map(param),
340+ pdeg: 1,
341+ seedAmp: 1e-2,
342+ source: linearSource,
343+ };
344+}
345+
346+/**
347+ * Max absolute difference of two equal-length spectral states, and that
348+ * difference relative to the scale of the reference's *non-constant* part —
349+ * every coefficient but (l, m) = (0, 0), which is index 0 in either layout.
350+ *
351+ * Normalizing against the whole state would hide the question. A model seeded as
352+ * a perturbation of a uniform steady state puts that state in (0, 0) alone, two
353+ * orders above everything else, so |dU| / max |U| would report a comfortable
354+ * fraction of the *background* however unrelated the two perturbations were —
355+ * including when no perturbation arrived at all, which is what a table that
356+ * never reaches a session looks like. Against the perturbation, that failure
357+ * reads as a ratio of 1.
358+ */
359+function compareStates(
360+ a: Float32Array,
361+ b: Float32Array,
362+): { abs: number; rel: number; scale: number } {
363+ let abs = 0;
364+ let scale = 0;
365+ const n = Math.min(a.length, b.length);
366+ for (let i = 0; i < n; i++) {
367+ abs = Math.max(abs, Math.abs(a[i] - b[i]));
368+ if (i >= 2) scale = Math.max(scale, Math.abs(b[i]));
369+ }
370+ return { abs, rel: scale > 0 ? abs / scale : Infinity, scale };
371+}
test/fluxChecks.tsmodified+79−6View file
@@ -30,6 +30,17 @@
3030 * non-axisymmetric surface, where the off-diagonal weight p2 actually does
3131 * something. The headline transform count (6 vs 12 per species per
3232 * iteration) is asserted from the compiled op sequences, not the doc.
33+ *
34+ * 3. The polar conditioning of the divergence (doc Sec 5). r ~ 1/sin^2(theta)
35+ * multiplies a bracket that must cancel to O(sin^2(theta)) at the poles,
36+ * so it amplifies the polar round-off of whatever it is handed. Splitting
37+ * the round sphere out of the divergence (models/schnakenberg.m, and
38+ * dp1/dq2/jinv in src/geom/geometry.ts) keeps r off all but the geometry
39+ * deviation; without the split, the amplified round-off is a static polar
40+ * forcing that a Turing instability grows into a spot at the pole,
41+ * regardless of the seed. That is the failure this checks for: it is
42+ * invisible to 1 and 2, which compare operators rather than watch what a
43+ * run nucleates from.
3344 */
3445 import { ShtPlan } from '../src/sht/sht.ts';
3546 import { DerivPlan } from '../src/sht/deriv.ts';
@@ -239,7 +250,7 @@ export async function fluxChecks(
239250 const sht = await ShtPlan.create(device, cfg);
240251 const deriv = await DerivPlan.create(device, sht);
241252 const geometry = await Geometry.create({
242- device, sht, cfg,
253+ sht, cfg,
243254 source: g.source,
244255 paramNames: g.params.map((p) => p.key),
245256 params: defaultGeometryParams(g),
@@ -359,7 +370,7 @@ export async function fluxChecks(
359370 ).length,
360371 );
361372 if (niter === 1) {
362- session.seed(1);
373+ await session.seed(1);
363374 session.step(STEPS);
364375 states.push(await session.read('U'));
365376 }
@@ -368,13 +379,15 @@ export async function fluxChecks(
368379 xformsPerIter.push(counts[1] - counts[0]);
369380 }
370381
371- // The headline number, from the compiled op sequences: 5 Legendre
382+ // The headline number, from the compiled op sequences: 6 Legendre
372383 // transforms per species per iteration against Algorithm 4's 12
373- // (2 species here). The phi flux's derivative runs as dphig -- two
384+ // (2 species here). Five of the six are the flux matvec; the sixth is
385+ // the round-sphere synthesis the divergence split buys its polar
386+ // conditioning with. The phi flux's derivative runs as dphig -- two
374387 // Fourier stages, no Legendre work -- and is deliberately not counted.
375388 check(
376- 'flux: 5 Legendre transforms per species per iteration, versus 12',
377- xformsPerIter[0] === 10 && xformsPerIter[1] === 24,
389+ 'flux: 6 Legendre transforms per species per iteration, versus 12',
390+ xformsPerIter[0] === 12 && xformsPerIter[1] === 24,
378391 `flux form adds ${xformsPerIter[0]} transforms/iteration, ` +
379392 `Algorithm 4 adds ${xformsPerIter[1]}`,
380393 );
@@ -399,5 +412,65 @@ export async function fluxChecks(
399412 `max |U_flux - U_alg4| = ${worst.toExponential(2)} after ${STEPS} steps ` +
400413 `on bumpy at lmax ${LMAX_AB}`,
401414 );
415+
416+ // ---- 3. the correction must not manufacture its own perturbation -----
417+ //
418+ // From the exact uniform steady state, with the Turing band switched off
419+ // (D1 = D2) so nothing can grow on its own, the only thing driving the
420+ // state away from uniform is round-off. niter = 0 never touches the flux
421+ // machinery and sets the floor; niter = 3 runs it three times per step.
422+ // The ratio is the correction's noise gain. Sphere-split it is O(1); with
423+ // r multiplying the whole divergence it was ~50 at lmax 63, and that
424+ // margin is what decides where a pattern nucleates. The ellipsoid is the
425+ // case to run it on: axisymmetric grid, strongly non-spherical geometry.
426+ const model = mModelByKey('schnakenberg')!;
427+ const quiet = model.source.replace(
428+ /function \[U, V, u, v\] = init\([\s\S]*?\nend/,
429+ `function [U, V, u, v] = init(lam3, gx, gy, gz, a, b)
430+ us = a + b;
431+ vs = b / (us * us);
432+ [U, V] = analys(us * ones(numel(gx), 1), vs * ones(numel(gx), 1));
433+ [u, v] = synth(U, V);
434+end`,
435+ );
436+ if (quiet === model.source) throw new Error('quiet-start fixture no longer matches schnakenberg.m');
437+ const ell = mGeometryByKey('ellipsoid')!;
438+ const noise: number[] = [];
439+ for (const niter of [0, 3]) {
440+ const session = await ModelSession.create({
441+ device,
442+ model,
443+ params: { ...defaultParams(model), D2: defaultParams(model).D1 },
444+ lmax: LMAX_AB,
445+ source: quiet,
446+ niter,
447+ geometry: ell,
448+ geometryParams: defaultGeometryParams(ell),
449+ });
450+ await session.seed(1);
451+ session.step(400);
452+ const U = await session.read('U');
453+ // Everything above the mean: l = 0, m = 0 is the uniform state itself.
454+ let sum = 0;
455+ for (let m = 0; m <= LMAX_AB; m++) {
456+ for (let l = Math.max(m, 1); l <= LMAX_AB; l++) {
457+ const i = lmIndex(LMAX_AB, l, m);
458+ sum += (U[2 * i] ** 2 + U[2 * i + 1] ** 2) * (m === 0 ? 1 : 2);
459+ }
460+ }
461+ noise.push(Math.sqrt(sum));
462+ session.destroy();
463+ }
464+ const gain = noise[1] / noise[0];
465+ log(
466+ ` flux polar noise gain on ellipsoid: ||U'|| ${noise[0].toExponential(2)} ` +
467+ `at niter 0, ${noise[1].toExponential(2)} at niter 3`,
468+ );
469+ check(
470+ 'flux: the geometric correction does not amplify polar round-off',
471+ Number.isFinite(gain) && gain < 5,
472+ `niter-3 round-off is ${gain.toFixed(1)}x the niter-0 floor ` +
473+ `(sphere-split: ~1; r on the whole divergence: ~50)`,
474+ );
402475 }
403476 }
test/geometryChecks.tsmodified+186−12View file
@@ -37,6 +37,7 @@ import {
3737 SPHERE_KEY,
3838 } from '../src/geom/registry.ts';
3939 import { ModelCompileError } from '../src/mgpu/errors.ts';
40+import { boundingBox, drawModes, DEFAULT_LAMBDA } from '../src/mgpu/randnfun3.ts';
4041 import type { Check, Log } from './analyticChecks.ts';
4142
4243 const LMAX = 31;
@@ -56,7 +57,6 @@ async function buildGeometry(device: GPUDevice, key: string) {
5657 const sht = await ShtPlan.create(device, cfg);
5758 const deriv = await DerivPlan.create(device, sht);
5859 const geometry = await Geometry.create({
59- device,
6060 sht,
6161 cfg,
6262 source: g.source,
@@ -295,7 +295,7 @@ export async function geometryChecks(
295295 device, model, params, lmax: LMAX, niter,
296296 });
297297 ops.push(session.describe().step.length);
298- session.seed(1);
298+ await session.seed(1);
299299 session.step(STEPS);
300300 states.push(await session.read('U'));
301301 session.destroy();
@@ -310,14 +310,15 @@ export async function geometryChecks(
310310 `${ops.join(' < ')} ops for ${counts.join(', ')} iterations`,
311311 );
312312 // Unrolling has to be exactly linear in the trip count: the body planned
313- // once per iteration, no more and no less. Per species per iteration: 3
313+ // once per iteration, no more and no less. Per species per iteration: 4
314314 // synths + 2 analyses (the flux-form matvec's five Legendre transforms,
315- // docs/reduced-transforms.md Sec 4 with the dphig variation) + the
316- // grid-space phi-derivative + 3 coefficient-space shuffles plus 7
317- // generated kernels -- see test/modelChecks.ts's KERNELS_PER_ITERATION,
318- // which counts the kernels alone; this counts every op.
315+ // docs/reduced-transforms.md Sec 4 with the dphig variation, plus the
316+ // round-sphere synthesis of the divergence split) + the grid-space
317+ // phi-derivative + 3 coefficient-space shuffles plus 8 generated kernels
318+ // -- see test/modelChecks.ts's KERNELS_PER_ITERATION, which counts the
319+ // kernels alone; this counts every op.
319320 const perIteration = ops[1] - ops[0];
320- const want = 32;
321+ const want = 36;
321322 check(
322323 'loop: unrolling is exactly linear in the trip count',
323324 perIteration === want && ops[2] - ops[0] === 4 * perIteration,
@@ -361,7 +362,7 @@ export async function geometryChecks(
361362 device, model, params, lmax: SWEEP_LMAX,
362363 geometry: peanut, geometryParams: peanutParams, niter,
363364 });
364- session.seed(1);
365+ await session.seed(1);
365366 session.step(STEPS);
366367 states.push(await session.read('U'));
367368 session.destroy();
@@ -416,7 +417,7 @@ export async function geometryChecks(
416417 geometry: geomSpec, geometryParams: defaultGeometryParams(geomSpec),
417418 niter,
418419 });
419- session.seed(1);
420+ await session.seed(1);
420421 session.step(STEPS);
421422 const values = await session.read('u');
422423 const finite = values.every((v) => Number.isFinite(v));
@@ -469,7 +470,7 @@ export async function geometryChecks(
469470 `rate ${((g.muMax - g.muMin) / (g.muMax + g.muMin)).toFixed(3)} ` +
470471 `vs plain ${(g.muMax - 1).toFixed(2)}`;
471472 }
472- session.seed(1);
473+ await session.seed(1);
473474 session.step(STEPS);
474475 const values = await session.read('u');
475476 outcomes.push(values.every((v) => Number.isFinite(v)));
@@ -512,7 +513,7 @@ export async function geometryChecks(
512513 const session = await ModelSession.create({
513514 device, model, params: defaultParams(model), lmax: LMAX,
514515 });
515- session.seed(1);
516+ await session.seed(1);
516517 session.step(STEPS);
517518 const before = await session.read('U');
518519
@@ -534,6 +535,179 @@ export async function geometryChecks(
534535 );
535536 session.destroy();
536537 }
538+
539+ await randnfun3Checks(device, check, log);
540+}
541+
542+/**
543+ * The seeded initial condition: chebfun's randnfun3, drawn on the host and
544+ * summed on the GPU (src/mgpu/randnfun3.ts).
545+ *
546+ * The split is the thing worth testing. The draw is MATLAB whose distribution
547+ * is checked directly, and the sum is a WGSL kernel checked against the same
548+ * modes evaluated in f64 on the CPU — if the kernel's indexing into the packed
549+ * mode table were wrong it would still produce a smooth random-looking field,
550+ * which is exactly the kind of wrong no "looks patterned" check would catch.
551+ */
552+async function randnfun3Checks(
553+ device: GPUDevice,
554+ check: Check,
555+ log: Log,
556+): Promise<void> {
557+ const model = mModelByKey('schnakenberg')!;
558+ const params = defaultParams(model);
559+ const make = (lam3: number): Promise<ModelSession> =>
560+ ModelSession.create({ device, model, params, lmax: LMAX, lam3 });
561+
562+ // ---- the GPU sum matches the same modes evaluated on the CPU -----------
563+ {
564+ const session = await make(DEFAULT_LAMBDA);
565+ await session.seed(3);
566+ // `u` after init is the steady state plus 0.01*f, so the field is
567+ // recovered by removing the model's own uniform offset.
568+ const u = await session.read('u');
569+ const g = session.geometry;
570+ const modes = drawModes(
571+ DEFAULT_LAMBDA,
572+ boundingBox(g.x, g.y, g.z),
573+ 3,
574+ g.x.length,
575+ );
576+ const nmodes = modes[0];
577+
578+ // The same sum in f64, straight from the packed table the GPU read.
579+ let maxErr = 0;
580+ let amp = 0;
581+ const us = params.a + params.b;
582+ for (let i = 0; i < g.x.length; i++) {
583+ let f = 0;
584+ for (let j = 0; j < nmodes; j++) {
585+ const b = 4 + 5 * j;
586+ const t = modes[b] * g.x[i] + modes[b + 1] * g.y[i] + modes[b + 2] * g.z[i];
587+ f += modes[b + 3] * Math.cos(t) - modes[b + 4] * Math.sin(t);
588+ }
589+ const want = us + 0.01 * f;
590+ maxErr = Math.max(maxErr, Math.abs(u[i] - want));
591+ amp = Math.max(amp, Math.abs(0.01 * f));
592+ }
593+ log(` randnfun3: ${nmodes} modes at lambda ${DEFAULT_LAMBDA}, |perturbation| up to ${amp.toExponential(2)}`);
594+ check(
595+ 'randnfun3: the GPU sum matches the same modes summed on the CPU',
596+ // fp32 over ~1400 terms against f64. What is being bounded is the
597+ // summation floor, and its size is the backend's accumulation order:
598+ // Metal lands at 2.0e-6, SwiftShader at 3.8e-6, so an absolute constant
599+ // tuned on one is a coin flip on the other. Scale it to the field
600+ // instead. The bug this exists to catch -- a mis-indexed read into the
601+ // packed table, which would still look like a smooth random field -- is
602+ // wrong by O(amp), a thousand times over the bound.
603+ maxErr < 1e-3 * amp && amp > 1e-3,
604+ `max |GPU - CPU| = ${maxErr.toExponential(2)}, perturbation amplitude ${amp.toExponential(2)}`,
605+ );
606+ session.destroy();
607+ }
608+
609+ // ---- a seed reproduces, a different seed does not ----------------------
610+ {
611+ const a = await make(DEFAULT_LAMBDA);
612+ await a.seed(11);
613+ const first = await a.read('u');
614+ await a.seed(11);
615+ const again = await a.read('u');
616+ await a.seed(12);
617+ const other = await a.read('u');
618+ let same = true;
619+ let differs = false;
620+ for (let i = 0; i < first.length; i++) {
621+ if (first[i] !== again[i]) same = false;
622+ if (first[i] !== other[i]) differs = true;
623+ }
624+ check(
625+ 'randnfun3: the same seed redraws the same field, a different one does not',
626+ same && differs,
627+ same ? (differs ? 'reproducible and seed-dependent' : 'seed 12 gave seed 11 back') : 'not reproducible',
628+ );
629+ a.destroy();
630+ }
631+
632+ // ---- the field is smooth, and lambda sets how smooth -------------------
633+ //
634+ // This is what randnfun3 buys over the white noise it replaced: the seed is
635+ // band-limited, so it is fully resolved by the grid instead of being
636+ // whatever the grid happened to alias. Measured as the share of spectral
637+ // energy above degree 20 — near zero for a smooth field, and larger for a
638+ // shorter wavelength, which is the direction lambda is supposed to move it.
639+ {
640+ const tail = async (lam3: number): Promise<number> => {
641+ const session = await make(lam3);
642+ await session.seed(5);
643+ const U = await session.read('U');
644+ let lo = 0;
645+ let hi = 0;
646+ for (let m = 0; m <= LMAX; m++) {
647+ for (let l = m; l <= LMAX; l++) {
648+ const i = lmIndex(LMAX, l, m);
649+ const e = U[2 * i] ** 2 + U[2 * i + 1] ** 2;
650+ if (l > 20) hi += e;
651+ else lo += e;
652+ }
653+ }
654+ session.destroy();
655+ return hi / (lo + hi);
656+ };
657+ const coarse = await tail(1);
658+ const fine = await tail(0.4);
659+ log(` randnfun3: energy above l=20 is ${coarse.toExponential(2)} at lambda 1, ${fine.toExponential(2)} at lambda 0.4`);
660+ check(
661+ 'randnfun3: the seed is band-limited, and lambda sets its scale',
662+ coarse < 1e-3 && fine > coarse,
663+ `tail ${coarse.toExponential(2)} (lambda 1) < ${fine.toExponential(2)} (lambda 0.4)`,
664+ );
665+ }
666+
667+ // ---- a finer wavelength grows the table rather than being capped -------
668+ //
669+ // The mode table is sized to the wavelength asked for, so going finer
670+ // reallocates it and rebinds the dispatch. Getting that wrong would leave
671+ // the kernel reading a destroyed buffer or a stale one, so check that a
672+ // fine field is actually there and actually different.
673+ {
674+ const session = await make(DEFAULT_LAMBDA);
675+ await session.seed(21);
676+ const coarse = await session.read('u');
677+ session.setLam3(0.12);
678+ await session.seed(21);
679+ const fine = await session.read('u');
680+ let differs = false;
681+ let finite = true;
682+ for (let i = 0; i < fine.length; i++) {
683+ if (!Number.isFinite(fine[i])) finite = false;
684+ if (fine[i] !== coarse[i]) differs = true;
685+ }
686+ check(
687+ 'randnfun3: a finer wavelength grows the mode table and rebinds',
688+ finite && differs,
689+ finite ? 'redrew finer, buffer rebound' : 'field went non-finite after resize',
690+ );
691+ session.destroy();
692+ }
693+
694+ // ---- a wavelength past the cost budget is refused, not truncated -------
695+ {
696+ const session = await make(DEFAULT_LAMBDA);
697+ let message = '';
698+ try {
699+ session.setLam3(1e-4);
700+ await session.seed(1);
701+ } catch (e) {
702+ message = e instanceof Error ? e.message : String(e);
703+ }
704+ check(
705+ 'randnfun3: a wavelength whose table could not be built is refused',
706+ message.includes('Fourier modes on this surface'),
707+ message ? `refused: ${message.slice(0, 62)}…` : 'drew it anyway',
708+ );
709+ session.destroy();
710+ }
537711 }
538712
539713 /** Index of the entry minimizing `score`, over the first `n` entries. */
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/modelChecks.tsmodified+23−17View file
@@ -41,15 +41,19 @@ const EXPECTED_KERNELS: Record<string, number> = {
4141 * docs/reduced-transforms.md Sec 4: the two sin-weighted
4242 * derivative synths, the pointwise flux combination through p1/p2/q2, the
4343 * two flux analyses, the re-shifted divergence and its r-scaled synthesis,
44- * plus the round-sphere eigenvalue added back — see models/schnakenberg.m
44+ * the round-sphere share of the divergence subtracted off through jinv, plus
45+ * the round-sphere eigenvalue added back — see models/schnakenberg.m
4546 * and docs/richardson-iteration.md. `schnakenberg-alg4` keeps the original
4647 * Cartesian-gradient form (Algorithm 3/4 of evolving_surface/notes/algos.tex)
4748 * as a live reference, with its original counts.
4849 */
4950 const KERNELS_PER_ITERATION: Record<string, number> = {
50- schnakenberg: 14,
51- brusselator: 14,
52- allencahn: 7,
51+ // 14 / 14 / 7 before the divergence was split against the round sphere:
52+ // forming lam .* F for the sphere term, and subtracting jinv .* S from the
53+ // deviation's r-scaled divergence, is one extra kernel per species.
54+ schnakenberg: 16,
55+ brusselator: 16,
56+ allencahn: 8,
5357 // 30 before the correction gained its band projection (.* filt on dLu):
5458 // that line fused into the state update in this model's expression shape,
5559 // and no longer does — one extra 2 x nlm kernel per species per iteration.
@@ -119,7 +123,7 @@ export async function modelChecks(
119123 `${kernels} kernels (expected ${expected})`,
120124 );
121125
122- session.seed(1);
126+ await session.seed(1);
123127 session.step(STEPS);
124128
125129 // Every rendered field must be finite and have developed some contrast.
@@ -168,7 +172,7 @@ export async function modelChecks(
168172 .describe()
169173 .step.filter((l) => l.includes('[batch lane')).length;
170174 }
171- session.seed(1);
175+ await session.seed(1);
172176 session.step(STEPS);
173177 states.push(await session.read('U'));
174178 session.destroy();
@@ -178,15 +182,16 @@ export async function modelChecks(
178182 }
179183 // Every batchable run at one solve iteration: the u/v syntheses and the
180184 // reaction analyses outside the loop (2 + 2), the four gradient
181- // syntheses, two theta-flux analyses, two divergence syntheses and two
182- // final analyses inside it (4 + 2 + 2 + 2; the phi flux goes through
183- // dphig, which has no Legendre stage to batch). Lane counts are
184- // batch-width invariant: a x4 run is one batch at K = 4 and two at
185- // K = 2, but the lanes annotated are the same 14 either way.
185+ // syntheses and the two round-sphere syntheses riding in the same group,
186+ // two theta-flux analyses, two divergence syntheses and two final
187+ // analyses inside it (6 + 2 + 2 + 2; the phi flux goes through dphig,
188+ // which has no Legendre stage to batch). Lane counts are batch-width
189+ // invariant: a x4 run is one batch at K = 4 and two at K = 2, but the
190+ // lanes annotated are the same 16 either way.
186191 check(
187192 'batch: the compiled step batches every adjacent transform pair',
188- batchedLanes === 14,
189- `${batchedLanes} batched transform lanes (expected 14)`,
193+ batchedLanes === 16,
194+ `${batchedLanes} batched transform lanes (expected 16)`,
190195 );
191196 let worst = 0;
192197 for (let i = 0; i < states[0].length; i++) {
@@ -208,7 +213,7 @@ export async function modelChecks(
208213 const cases: [string, string, string][] = [
209214 [
210215 'a single output bound to a grouped call',
211- 'Ftu = synth(vtu, vpu);',
216+ 'Ftu = synth(vtu, vpu, lam .* Fu);',
212217 'bind each one',
213218 ],
214219 [
@@ -216,12 +221,13 @@ export async function modelChecks(
216221 // Fpu is reassigned so the only error left is the dropped slot
217222 // itself, which the planner refuses (numbl would otherwise catch
218223 // the undefined 'Fpu' first, masking the check under test).
219- '[Ftu, ~] = synth(vtu, vpu);\n Fpu = Ftu;',
224+ '[Ftu, ~, Su] = synth(vtu, vpu, lam .* Fu);\n Fpu = Ftu;',
220225 'must be bound',
221226 ],
222227 ];
223228 for (const [what, bad, expect] of cases) {
224- const source = model.source.replace('[Ftu, Fpu] = synth(vtu, vpu);', bad);
229+ const source = model.source.replace('[Ftu, Fpu, Su] = synth(vtu, vpu, lam .* Fu);', bad);
230+ if (source === model.source) throw new Error('grouped-call fixture no longer matches allencahn.m');
225231 let message = '';
226232 try {
227233 const session = await ModelSession.create({
@@ -252,7 +258,7 @@ export async function modelChecks(
252258 lmax: LMAX,
253259 oversample: 2,
254260 });
255- session.seed(1);
261+ await session.seed(1);
256262 session.step(STEPS);
257263
258264 const fine = await session.readSpecies(0);
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+10−2View file
@@ -23,11 +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';
32+import { compareChecks } from './compareChecks.ts';
33+import { referenceChecks, type H5Rt } from './referenceChecks.ts';
34+import { matlabExportChecks } from './matlabExportChecks.ts';
3135
3236 declare global {
3337 interface Window {
@@ -87,7 +91,7 @@ async function soak(steps: number, lmax: number): Promise<void> {
8791 geometryParams: defaultGeometryParams(geometry),
8892 niter: DEFAULT_NITER,
8993 });
90- session.seed(5);
94+ await session.seed(5);
9195 log(
9296 `soak: ${steps} steps at lmax ${lmax} ` +
9397 `(grid ${session.cfg.nlat}x${session.cfg.nphi}, ${geometry.key}, ` +
@@ -191,7 +195,7 @@ async function dumpState(q: URLSearchParams): Promise<void> {
191195 geometryParams: spec.geometryParams,
192196 niter: spec.niter,
193197 });
194- session.seed(spec.seed);
198+ await session.seed(spec.seed);
195199 session.step(spec.steps);
196200 await session.sync();
197201 const state = await session.read(model.state[0]);
@@ -220,6 +224,10 @@ async function main(): Promise<void> {
220224 // but minutes in a browser, where each session recompiles its unrolled step.
221225 await geometryChecks(device, check, log, { sweep: q.has('sweep') });
222226 await fluxChecks(device, check, log, { ab: q.has('sweep') });
227+ 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);
223231
224232 window.__RESULTS__ = { ok: failures === 0, lines };
225233 log(failures === 0 ? 'ALL PASS' : `${failures} FAILURE(S)`);
tools/randnfun3.madded+66−0View file
@@ -0,0 +1,66 @@
1+% Smooth random function in 3D — chebfun's randnfun3, as the Fourier modes
2+% it is built from rather than as a chebfun3.
3+%
4+% [K, C] = randnfun3(LAMBDA, DOM) draws a random trig series on the box
5+% DOM = [x0 x1 y0 y1 z0 z1] with maximum frequency about 2*pi/LAMBDA in
6+% each direction and standard normal distribution N(0,1) at each point.
7+% K is nmodes x 3 (angular wavenumbers) and C is nmodes x 2 (real and
8+% imaginary parts), defining
9+%
10+% f(x,y,z) = sum_j C(j,1)*cos(K(j,:)*[x;y;z]) - C(j,2)*sin(K(j,:)*[x;y;z])
11+%
12+% Seed the draw with rng(...) before calling.
13+%
14+% chebfun returns a chebfun3 and evaluates it later; this project has no
15+% such object, and the sum above is what the GPU evaluates at the surface
16+% points (src/mgpu/randnfun3.ts). Splitting it here is also what keeps the
17+% draw in MATLAB: randn has no counterpart in the compiled WGSL dialect.
18+
19+function [k, c] = randnfun3(lambda, dom)
20+ % chebfun's nonperiodic path builds a periodic function on a domain about
21+ % 20% larger and restricts it. Restriction is free when evaluating at
22+ % points, so we keep the enlarged period and never form the smaller one.
23+ m = round(1.2*(dom(2)-dom(1))/lambda + 2);
24+ n = round(1.2*(dom(4)-dom(3))/lambda + 2);
25+ p = round(1.2*(dom(6)-dom(5))/lambda + 2);
26+ m2 = 2*m+1;
27+ n2 = 2*n+1;
28+ p2 = 2*p+1;
29+ N = m2*n2*p2;
30+
31+ % chebfun draws the whole cube (column-major) before masking; drawing in
32+ % that same order keeps a seed meaning the same thing here as there.
33+ cr = randn(N, 1);
34+ ci = randn(N, 1);
35+
36+ % The cube's integer wavenumbers, -m:m x -n:n x -p:p in column-major order.
37+ i = (0:N-1).';
38+ jx = mod(i, m2) - m;
39+ jy = mod(floor(i/m2), n2) - n;
40+ jz = floor(i/(m2*n2)) - p;
41+
42+ % Confine to a ball for isotropy.
43+ keep = ((jx/m).^2 + (jy/n).^2 + (jz/p).^2) <= 1;
44+ jx = jx(keep);
45+ jy = jy(keep);
46+ jz = jz(keep);
47+ cr = cr(keep);
48+ ci = ci(keep);
49+
50+ % Normalize so the variance is 1 at each point.
51+ s = 1/sqrt(numel(cr));
52+ cr = s*cr;
53+ ci = s*ci;
54+
55+ % Angular wavenumbers on the enlarged period, which is a whole number of
56+ % wavelengths on each side.
57+ kx = 2*pi*jx/(m*lambda);
58+ ky = 2*pi*jy/(n*lambda);
59+ kz = 2*pi*jz/(p*lambda);
60+
61+ % Fold the box's origin into the phase, so evaluating is a plain sum over
62+ % cos(k.x) and sin(k.x) with no offset left to carry.
63+ ph = -(kx*dom(1) + ky*dom(3) + kz*dom(5));
64+ k = [kx, ky, kz];
65+ c = [cr.*cos(ph) - ci.*sin(ph), cr.*sin(ph) + ci.*cos(ph)];
66+end
tools/randnfunsphere.madded+59−0View file
@@ -0,0 +1,59 @@
1+% Smooth random function on the unit sphere — chebfun's randnfunsphere,
2+% evaluated at the given (theta, phi) instead of returned as a spherefun.
3+%
4+% F = randnfunsphere(LAMBDA, THETA, PHI) is a combination of all spherical
5+% harmonics up to degree floor(2*pi/LAMBDA) with independent N(0,1)
6+% coefficients, normalized so the variance is 1 at each point.
7+%
8+% randnfunsphere(LAMBDA, THETA, PHI, 'monochromatic') uses only the
9+% harmonics of that one degree, so every component has the same wave
10+% number — chebfun's 'monochrome' option.
11+%
12+% Seed the draw with rng(...) before calling. This project has no chebfun
13+% objects: what would be a spherefun there is returned here as values on the
14+% grid the caller passes in.
15+
16+function f = randnfunsphere(lambda, theta, phi, type)
17+ if ( nargin < 4 )
18+ type = 'white';
19+ end
20+ % The unit sphere has circumference 2*pi, matching randnfun's deg = L/lambda.
21+ deg = floor(2*pi/lambda);
22+ if ( strncmpi(type, 'm', 1) )
23+ c = randn(2*deg+1, 1);
24+ c = sqrt(4*pi/numel(c)) * c; % normalize so the variance is 1
25+ f = sphHarmSumFixedDeg(theta, phi, deg, c);
26+ else
27+ c = randn((deg+1)^2, 1);
28+ c = sqrt(4*pi/numel(c)) * c; % normalize so the variance is 1
29+ f = sphHarmSum(theta, phi, deg, c);
30+ end
31+end
32+
33+% All spherical harmonics up to degree deg, with coefficients ordered by
34+% degree and order (0, -1,0,1, -2,-1,0,1,2, ...). Order +m carries
35+% cos(m*phi), order -m carries sin(m*phi).
36+function f = sphHarmSum(theta, phi, deg, c)
37+ f = 1/sqrt(4*pi) * c(1) * ones(size(theta));
38+ k = 1; % coefficients consumed so far
39+ for l = 1:deg
40+ cl = c(k+1 : k+2*l+1); % this degree's orders, -l..l
41+ k = k + 2*l + 1;
42+ f = f + sphHarmSumFixedDeg(theta, phi, l, cl);
43+ end
44+end
45+
46+% All spherical harmonics of the single degree l.
47+function f = sphHarmSumFixedDeg(theta, phi, l, c)
48+ m = (0:l).';
49+ a = (-1).^m ./ sqrt((1 + double(m==0)) * pi);
50+ costh = cos(theta(:)).'; % legendre wants cos(theta), in a row
51+ G = legendre(l, costh, 'norm'); % (l+1) x npts
52+ f = 0 * theta;
53+ for mm = 0:l
54+ f = f + a(mm+1) * c(l+1+mm) * (G(mm+1,:).' .* cos(mm*phi));
55+ if mm > 0
56+ f = f + a(mm+1) * c(l+1-mm) * (G(mm+1,:).' .* sin(mm*phi));
57+ end
58+ end
59+end
vite.config.tsmodified+6−1View file
@@ -1,4 +1,5 @@
11 import { defineConfig } from 'vite';
2+import { realpathSync } from 'node:fs';
23 import { resolve } from 'node:path';
34
45 // numbl is a local `file:` dependency, so node_modules/numbl is a symlink to
@@ -8,7 +9,11 @@ import { resolve } from 'node:path';
89 // express this — Node rejects node_modules targets — and plain Node could not
910 // resolve numbl's internal `.js`->`.ts` imports anyway, which is why the GPU
1011 // tests run in the browser harness rather than under `node`.)
11-const numblSrc = resolve(import.meta.dirname, 'node_modules/numbl/src');
12+// Realpath'd through the symlink: dev serves modules under their real ids, so
13+// aliasing the node_modules path would give the same file two identities (one
14+// per spelling) and run its side effects twice — the interpreter's builtin
15+// registry throws on the second.
16+const numblSrc = realpathSync(resolve(import.meta.dirname, 'node_modules/numbl/src'));
1217
1318 export default defineConfig({
1419 base: './',