/ forks / turing-surface
Sign in
forks / turing-surface
forked from github.com/concept-collection/turing-surface
678 lines · 35.9 KBPreviewCodeBlameHistoryRaw
1# turing-surface
3Reaction–diffusion systems (Turing patterns) on **closed surfaces given by
4spherical-harmonic embeddings**, solved live in the browser with a spectral
5method whose transforms run on the GPU via WebGPU.
7This is the sibling of
8[turing-sphere](https://github.com/concept-collection/turing-sphere), which
9solves the same systems on the round sphere. Everything there is here; what is
10added is a *surface*.
12The geometry is in the operator: the models evaluate the surface
13Laplace–Beltrami operator `lap_g` inside the implicit solve, in a **flux form
14that costs 5 spherical-harmonic transforms per species per iteration** (plus
15one Legendre-free FFT derivative) where the textbook Cartesian-gradient form
16needs 12. See
17[The geometry in the operator](#the-geometry-in-the-operator) and
18[docs/reduced-transforms.md](docs/reduced-transforms.md).
20## What a surface is here
22A geometry is an embedding of the sphere into R³: three scalar fields x, y, z
23over the (θ, φ) parametrization, each carried as spherical-harmonic
24coefficients. The unit sphere is the case where all three are pure degree-1
25harmonics.
27You write one down as MATLAB, in [`geometries/`](geometries/):
29```matlab
30function [gx, gy, gz] = shape(theta, phi, waist, stretch)
31 st = sin(theta);
32 r = 1 - waist * (st .^ 2);
33 gx = r .* (st .* cos(phi));
34 gy = r .* (st .* sin(phi));
35 gz = (1 + stretch) * (r .* cos(theta));
36end
37```
39That is ordinary MATLAB. Unlike the models it is not compiled to WGSL: a shape
40is evaluated exactly once at build time, so it runs through numbl's CPU
41interpreter instead, in f64, with the full MATLAB subset available — loops,
42arrays, `min`/`max`, `legendre`, seeded randomness via `rng`/`randn`. The
43result is then **analysed into coefficients**, which is the form everything
44downstream uses. Two things follow from going through the coefficients rather than keeping
45the pointwise values:
47- **It is exactly band-limited at lmax.** The surface has as many derivatives as
48 the scheme needs and no aliased content the solver cannot see. What the solver
49 and the renderer both use is the *synthesis* of the coefficients, so for a
50 shape with sharp features the surface being solved on is not quite the one
51 that was written down — which is the honest thing for a spectral method to do.
52- **It can be evaluated on any grid.** The renderer draws the surface on the
53 (possibly finer) display grid by synthesizing the same coefficients there.
54 That is exact interpolation, not subdivision — the same argument that lets the
55 species fields be oversampled, and it is checked directly in the tests.
57Five geometries ship: [sphere](geometries/sphere.m) (the reference case),
58[ellipsoid](geometries/ellipsoid.m), [peanut](geometries/peanut.m) — a dumbbell
59whose 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
61random function built from chebfun's `randnfunsphere` construction (random
62spherical-harmonic coefficients up to degree ⌊2π/λ⌋, rescaled to [−1, 1]).
63It is seeded, so the same seed always gives the same shape; `amp` sets how far
64it departs from the sphere, `λ` how fine its lobes are, and **Re-seed shape**
65draws another one. Each geometry is
66editable in the page, with its own parameters. Changing a shape does not recompile the
67solver and does not disturb the run: the geometry is data whose shape in the
68bindings depends only on the grid, so a swap is sixteen buffer writes and the
69pattern carries straight on.
71A sixth kind of geometry arrives from outside: reharm (the sibling
72spherical-harmonic fitting app) can hand a fitted surface — a scanned mesh, a
73brain, a point cloud — to this page with its **Export to turing-surface**
74button. The surface arrives as coefficients by `postMessage` (there is no .m;
75`Geometry` is built from them directly, re-indexed onto whatever band is
76selected), lands as an **imported** entry in the geometry dropdown at its own
77lmax, and behaves like any other shape from there — except that the editor,
78the benchmark command line and the MATLAB export, all of which need a .m, say
79so instead.
81A **morph** slider blends the drawn surface back to the unit sphere. The
82parametrization is the sphere's either way, so sweeping it shows which point
83went where.
85### Seeding, and `tools/`
87A run starts from the uniform steady state plus a small perturbation, and that
88perturbation is a *smooth* random field rather than white noise: chebfun's
89[`randnfun3`](tools/randnfun3.m) on the surface's bounding box, restricted to
90the surface by evaluating it at the grid points — the way surfacefun seeds a
91run. Each model's `init` says so itself:
93```matlab
94function [U, V, u, v] = init(lam3, gx, gy, gz, a, b)
95 f = randnfun3(lam3, gx, gy, gz);
96 ...
97```
99A band-limited seed is fully resolved by the grid, where white noise is
100whatever the grid happened to alias: the tests measure its energy above degree
10120 at 5e-14 of the total, and the flux-form and Algorithm-4 operators now
102track each other to 3e-6 through a run instead of 4e-4. The **seed λ** control
103sets the field's wavelength; smaller means finer features to grow from. It is
104an *absolute* length in the surface's own units, as in chebfun — not a
105fraction of the surface's size — so a larger surface draws more modes at the
106same λ.
108**λ is useful down to about 2π/lmax, and no further.** A field of wavelength λ
109on a unit-radius surface carries angular content up to degree ≈ 2π/λ, so at
110the default lmax 63 the grid holds everything down to λ ≈ 0.1. Past that,
111`init`'s own `analys` discards what the grid cannot represent, and the seed
112gets *weaker* rather than finer while costing eight times as much per halving:
114| λ | 2π/λ | rms of the resolved seed | energy above l=55 | peak degree |
115|---|---|---|---|---|
116| 0.5 | 13 | 2.6e-2 | 1e-8 | 8 |
117| 0.2 | 31 | 2.6e-2 | 1e-8 | 10 |
118| 0.1 | 63 | 2.4e-2 | 0.10 | 44 |
119| 0.05 | 126 | 1.5e-2 | 0.20 | 48 |
120| 0.03 | 209 | 9.6e-3 | 0.27 | 63 |
122Raising lmax moves that floor down, and the seed really does get finer: at
123lmax 127 the same λ=0.05 keeps its full amplitude (2.5e-2 against 1.5e-2 at
124lmax 63) with its peak at degree 79 instead of pinned to the band edge, and
125λ=0.1 becomes *fully* resolved (2e-8 of its energy in the top decile, against
1261e-1 at lmax 63 — so even 0.1 is slightly under-resolved on the default grid).
128Note that lmax cuts both ways: it quadruples npts, so every λ also costs four
129times as much to sum.
131**Nothing caps λ but memory and patience.** The mode table grows to whatever
132is asked for and the only refusal is a table that could not be built at all,
133reported with the mode count it wanted rather than silently truncated. On a
134128×256 grid:
136| λ | modes | seed time |
137|---|---|---|
138| 0.05 | 480,431 | 0.26 s |
139| 0.03 | 2,094,657 | 0.98 s |
140| 0.02 | 6,882,185 | 3.1 s |
141| 0.015 | 16,092,829 | 7.4 s |
142| 0.01 | 53,574,764 | 25.6 s |
144Being slow is the caller's business; **freezing the browser is not**, and at
145these times neither half of the work can be left where it was:
147- The draw is synchronous interpreter time — 13 s at λ=0.01 — which on the
148 main thread stops the page painting and gets it offered up for killing. It
149 runs on a worker instead
150 ([`randnfun3.worker.ts`](src/mgpu/randnfun3.worker.ts)); it touches no GPU
151 and no DOM, so nothing about it needed that thread. Measured during a seed:
152 731 animation frames, no stalled sample.
153- The GPU sum is split across a fixed 16 dispatches (`randnfun3Chunks`)
154 accumulating into the same output, and `submitYielding` ends the submission
155 at each one. A browser's GPU process is shared with compositing, so a single
156 submission running tens of seconds stops *every* tab painting, and one
157 dispatch that long risks the watchdog killing the device outright. Slices
158 past the end of a small table exit immediately, so a coarse λ pays nothing.
160The device is also asked for the adapter's full storage-buffer limit at
161creation ([`src/sht/sht.ts`](src/sht/sht.ts)), so a browser's 128 MB default
162is not what decides how fine λ can be. `seed()` is consequently async.
164`randnfun3` splits across the CPU/GPU line, and the split is forced rather
165than chosen. Drawing the modes needs `randn` and a `sqrt(nnz)` normalization,
166neither of which exists in the compiled WGSL dialect, so the draw is MATLAB in
167[`tools/randnfun3.m`](tools/randnfun3.m) run by the interpreter — a few
168thousand coefficients, ~5 ms. Evaluating is `npts × nmodes` (~6e7 terms at the
169default λ), so that is a WGSL kernel
170([`src/mgpu/randnfun3.ts`](src/mgpu/randnfun3.ts)) reached as an external
171operation, the way `synth` is. The coefficient table is filled in behind the
172call, as `synth` hides its Legendre matrices; λ is not hidden, and the plan
173records which parameter the `.m` asked with so the host draws from that value.
175[`tools/`](tools/) is the shared MATLAB every interpreter run can call, by file
176name, as on MATLAB's path — currently `randnfun3` and
177[`randnfunsphere`](tools/randnfunsphere.m), which `blob.m` is written on. Both
178keep their upstream signatures, including options nothing shipped uses yet
179(`randnfunsphere`'s `'monochromatic'`), because the point of a tool is that a
180geometry you write next can reach for it. Tools are not available to the
181models' *step*, which compiles to WGSL where none of this exists.
183## The scheme, and where the geometry enters
185It solves the N-species system
187```
188d(u_k)/dt = D_k*lap_g(u_k) + f_k(t, u_1, ..., u_N), k = 1, ..., N
189```
191where `lap_g` is the Laplace–Beltrami operator of the surface. On the round
192sphere `lap_g` is diagonal in spherical-harmonic space with eigenvalues
193`-l(l+1)`, which is what makes turing-sphere's implicit diffusion a single
194divide. On a general surface it is not diagonal, and not even constant-
195coefficient, so that divide has to become a solve.
197The models split the operator:
199```
200lap_g = lap_s + dlap
201```
203with `lap_s` the round-sphere one. `(I - dt*D*lap_s)` is still exactly
204invertible, so the implicit step
206```
207(I - dt*D*lap_g) Unew = B
208```
210rearranges into a fixed point that keeps the whole geometry on the right-hand
211side,
213```
214Unew = (B + dt*D*dlap(Unew)) ./ (1 + dt*D*lam)
215```
217and the loop iterates it from the round-sphere answer. That is preconditioned
218Richardson, with the operator we can invert exactly as the preconditioner; it
219converges while `dt*D*dlap` stays small against `(I - dt*D*lap_s)`, which is
220what keeps the cost to a few transforms per step rather than a full elliptic
221solve (see [docs/richardson-iteration.md](docs/richardson-iteration.md)). One
222species of [`models/schnakenberg.m`](models/schnakenberg.m)'s solve loop:
224```matlab
225lamJ = lam ./ jhat; % mean-J preconditioner eigenvalues (below)
226...
227for k = 1:niter
228 Fu = Un .* filt; % zero the top 2 degrees before differentiating
229 vtu = dthetac(Fu);
230 vpu = dphic(Fu);
231 [Ftu, Fpu] = synth(vtu, vpu); % sin(theta)*dtheta(u), dphi(u) -- smooth on
232 % the sphere, one batched dispatch
233 Pu = p1 .* Ftu + p2 .* Fpu; % the two fluxes, also smooth: the precomputed
234 Qu = p2 .* Ftu + q2 .* Fpu; % weights carry every 1/sin(theta) there is
235 PAu = analys(Pu);
236 Pcu = PAu .* filt;
237 scu = dthetac(Pcu); % theta part of the divergence, coefficients
238 Lu = synth(scu); % sin(theta) * dtheta(P) on the grid
239 dQu = dphig(Qu); % d/dphi is diagonal in the Fourier index:
240 % two FFT stages, no Legendre work at all
241 lapu = r .* (Lu + dQu); % = lap_g(u) on the grid
242 dLu = (analys(lapu) + lamJ .* Un) .* filt; % dlap, projected onto the band
243 Un = (Bu + (dt * D1) * dLu) ./ (1 + (dt * D1) * lamJ);
244end
245```
247On the sphere `dlap` is mathematically zero — `p1 = q2 = 1`, `p2 = 0`,
248`r = 1/sin²θ`, `jhat = 1`, and the composition collapses to `lap_s` — so the
249sphere case reproduces turing-sphere to fp32 round-off, and the tests assert
250the state stays put across 0, 1 and 4 iterations.
252**The preconditioner folds in the symbol of the operator.** `jhat` is the
253host's minimax scale `2/(μmin + μmax)` over the eigenvalues `μ(x)` of the
254operator's principal symbol — the inverse squared principal stretches of
255the embedding, direction included, read straight off the flux-metric
256arrays (`S = (1/J)·[[p1,p2],[p2,q2]]`). Preconditioning with `lam/jhat`
257then contracts every mode *and every direction* at rate
258`(μmax − μmin)/(μmax + μmin) < 1` on any surface, where the plain `lam`
259diverges wherever `μ > 2` — peanut reaches `μ = 6.2`. A det-based mean of
260the area factor (μ's geometric mean, exact only for conformal surfaces) is
261not enough: it under-corrects anisotropic stretching and leaves directional
262high-degree bands with amplification > 1, which surfaced as patterns going
263high-frequency and diverging as `niter` or `lmax` grew. The answer never
264depends on `jhat` — the `lamJ` term added inside `dLu` is the term divided
265back out — only the convergence rate does.
267**The correction is projected onto the band** (`.* filt` on `dLu`,
268matching algos.tex Algorithm 5's zeroing of the top coefficients). Without
269it the top two degrees iterate toward the *undiffused* `Bu` — each solve
270iteration strips a bit more of their implicit diffusion, at species-
271dependent rates, which manufactures a spurious Turing band at the band
272edge: visible on the round sphere as top-degree energy growing ~3%/step at
273`lmax 127, niter 8`. With both fixes the whole niter × geometry sweep
274converges, the spectral centroid of the pattern is resolution-independent
275(l ≈ 26 at lmax 63 and 127 alike), and `jhat: 1` is kept as the divergent
276control in the tests.
278### The geometry in the operator
280`dlap = lap_g - lap_s` is applied to the current iterate at every solve
281iteration, so its transform count is what the whole step's cost scales with.
282Two formulations ship:
2841. **The flux form** (above, all three models): `lap_g u` as the weighted
285 divergence of two weighted fluxes of the sin-scaled derivatives. The
286 weights `p2, r, dp1, dq2, jinv` are grid arrays precomputed once per
287 surface from the embedding's θ/φ tangents
288 ([`src/geom/metric.ts`](src/geom/metric.ts)), chosen so that **every field
289 that gets analysed is a smooth function on the sphere** — the property
290 that makes spherical-harmonic analysis meaningful, and the entire
291 difficulty near the poles. The divergence is split against the round
292 sphere: the sphere's share of it is `-jinv .* lap_s(u)`, exact in
293 spectral space, so `r ~ 1/sin²θ` multiplies only the geometry deviation.
294 Without that split `r` amplifies the polar round-off of the whole flux
295 into a static forcing that nucleates a spot at the pole on every seed.
296 Cost: **6 Legendre transforms** per species per iteration (4 syntheses —
297 two gradient, one divergence, one for the sphere's `-lam .* u`, which
298 rides in the gradient's batch — plus 2 analyses; the phi flux never needs
299 the Legendre basis, `dphig` differentiates it on the grid with two FFT
300 stages, masking m past the top-degree filter, and `dthetac`/`dphic`
301 are O(nlm) coefficient shuffles). The derivation, the smoothness
302 argument and the fp32 error analysis are in
303 [docs/reduced-transforms.md](docs/reduced-transforms.md).
3042. **The Cartesian-gradient form** (Algorithm 4 of `docs/algos.pdf`), kept as
305 a live reference in
306 [`models/schnakenberg_alg4.m`](models/schnakenberg_alg4.m) and selectable
307 in the app: the surface gradient carried as three ambient components
308 through the inverse metric quantities `Vt*/Vp*`. Cost: **12 transforms**
309 per species per iteration. The tests hold both forms to the same answer on
310 a curved surface, and both metric formulations are precomputed and
311 uploaded for every geometry, so either kind of model runs.
313The θ-derivative machinery both forms need — the α± recurrence
314(`sin θ ∂θ Y_l^m = α⁺Y_{l+1}^m + α⁻Y_{l-1}^m`) as a coefficient-space shuffle
315feeding the existing scalar synthesis — lives in
316[`src/sht/deriv.ts`](src/sht/deriv.ts); no Legendre-derivative tables are
317required.
319### `for` loops, unrolled
321A plan is a fixed list of GPU operations with no branching, which is what makes
322a timestep pure command recording — one submit, no CPU in the loop. A counted
323loop still fits: the planner
324([`src/mgpu/plan.ts`](src/mgpu/plan.ts)) unrolls it, planning the body once per
325iteration.
327Nothing else had to change for that, because numbl gives a variable one cName
328for every assignment to it: the buffer an iteration writes is the buffer the
329next one reads, which is exactly a loop-carried value. The loop variable gets no
330buffer at all — it is bound as a derived scalar to that iteration's literal, so
331a kernel reading `k` folds the number in.
333Two consequences worth stating:
335- **The bounds must be known when the model compiles.** `niter` is supplied as a
336 fixed scalar rather than a tunable one, so changing it recompiles — unlike a
337 parameter, which is a uniform. A runtime bound is refused at compile time with
338 a source position, not silently mis-compiled, and there is a test for that.
339- **Fusion survives.** numbl's inline pass recurses into loop bodies, so a line
340 inside the loop is still one kernel. It runs there with no protected names,
341 though, which means an assignment whose only visible use is later in the same
342 body can be elided — correct for a body-local temp, wrong if something outside
343 the loop wanted it. [`src/mgpu/compile.ts`](src/mgpu/compile.ts) snapshots what
344 each loop body assigns before the pass and refuses the ones that escape, so
345 that case is a compile error rather than a stale read.
347Unrolling is exactly linear in the trip count: 18 GPU ops per species per
348iteration (7 transforms, 3 coefficient shuffles, 8 kernels), asserted in the
349tests.
351## MATLAB, compiled to WebGPU
353Unchanged from turing-sphere. This is the models' path — the geometry files
354instead run once through numbl's CPU interpreter, as above. numbl
355parses and lowers each function for the concrete argument types of the current
356grid; its inline pass folds single-use temps back into their consumer, so one
357line of MATLAB becomes one expression tree; and this repo emits one WGSL compute
358kernel per element-wise statement
359([`src/mgpu/wgsl.ts`](src/mgpu/wgsl.ts)). `synth` / `analys` are external
360operations whose type rules numbl learns from a `.mtoc2.js` workspace file, and
361which the backend maps onto the spherical-harmonic pipelines. Anything it cannot
362express is refused at compile time with a source position.
364The Schnakenberg step compiles to 50 GPU operations at one solve iteration:
36518 transforms, 6 coefficient-space shuffles, 24 generated kernels, and 2
366buffer copies feeding the new state back.
368**Transforms batch.** The expensive part of every Legendre stage is
369generating the associated Legendre values on the fly by recurrence — work
370that depends only on the grid, not on the field. `synth`/`analys` therefore
371take multiple fields, and a grouped call runs as one batched dispatch: one
372walk of the recurrence, one accumulator lane per field —
374```matlab
375[Ftu, Fpu, Ftv, Fpv, Su, Sv] = synth(vtu, vpu, vtv, vpv, lam .* Fu, lam .* Fv);
376```
378The grouping is a promise of independence, never of a lane width: the
379planner ([`src/mgpu/plan.ts`](src/mgpu/plan.ts), `materializeTransforms`)
380chunks each group into whatever the device supports — one ×4 batch under the
381default WebGPU limits, or scalar dispatches with `SHT_BATCH=0` for A/B — so
382the same source runs anywhere. Ungrouped transforms that happen to sit on
383consecutive independent lines are batched the same way. Per-lane arithmetic
384is identical to the scalar kernels', so batched and scalar plans produce
385bit-identical states, asserted in the tests along with compile-time refusal
386of a group that drops one of its outputs. All 16 Legendre transforms of the step
387above land in batches, worth ~25% of the whole step (0.88 vs 1.14 ms/step at
388lmax 127, 2 iterations, on bumpy).
390Two consequences carried over:
392- **The step is synchronous.** WebGPU's encode path is synchronous and every
393 pipeline is built once at compile time, so a timestep is pure command
394 recording; the only `await` in the loop is the single readback per rendered
395 frame.
396- **Parameters are uniforms, not constants.** Moving a slider rewrites a small
397 buffer instead of triggering a recompile. Editing the MATLAB recompiles;
398 changing `dt` does not. `niter` is the deliberate exception, above.
400## Provenance
402- **turing-sphere**, which this is a fork of: the solver, the transforms
403 backend, the compilation path, the benchmarks and the analytic tests.
404- **Transforms:** [shtns-webgpu](https://github.com/concept-collection/shtns-webgpu) —
405 fp32 spherical harmonic transforms in WGSL compute shaders, modeled on
406 [SHTNS](https://nschaeff.bitbucket.io/shtns/). Vendored under
407 [`src/sht/`](src/sht/) (CECILL-2.1), including the f64 CPU reference transform
408 used for testing.
409- **Rendering:** three.js meshes with per-vertex colormaps, adapted from the
410 `SphereEmbedding` view in
411 [figpack](https://github.com/flatironinstitute/figpack)'s experimental
412 extension package ([`src/render/`](src/render/)). That view displays a
413 time-varying embedded geometry with fields on it, which is the same picture
414 this draws — including its sphere/surface morph, which turing-sphere had
415 dropped as having nothing to morph to.
417turing-sphere additionally carries a comparison against a native build of
418upstream SHTNS ([`bench/shtns/`](https://github.com/concept-collection/turing-sphere/tree/main/bench/shtns)).
419That is not duplicated here: the transforms are the same code, and its C-side
420transcription of the model would have to be maintained against a step this
421project intends to change.
423Because the algorithm is compiled to compute shaders, **WebGPU is required** —
424there is no CPU fallback (the f64 CPU transform remains, for tests).
426## Numerics
428- Grid: Gauss–Legendre × equispaced-φ, dealiased for the cubic reactions with
429 the `(pdeg+1)` rule: `nlat ≥ ((pdeg+1)·lmax+1)/2`, `nphi ≥ (pdeg+1)·lmax+1`
430 (rounded up to a power of two for the GPU FFT path). At the default lmax 63
431 that is a 128×256 grid.
432- Spectral layout: SHTNS conventions — orthonormal + Condon–Shortley, complex
433 coefficients for m ≥ 0, m-major ordering.
434- fp32 transforms introduce ~1e-6 relative error per step; for pattern formation
435 from a 1e-2 seeded perturbation this is inconsequential. The geometry goes through one
436 analysis/synthesis round trip and picks up the same round-off: the unit sphere
437 comes back with radius 1 to ~2e-5 under Dawn, ~4e-4 under SwiftShader.
438- The shipped analytic geometries are all degree ≤ 5, and the random ones stay
439 near degree 13 at their finest slider settings — far below any lmax the app
440 offers, so band-limiting removes little to nothing from them. A shape you
441 write yourself may not be so lucky — see the note in
442 [`geometries/bumpy.m`](geometries/bumpy.m).
444## Desktop vs browser
446[`scripts/bench.ts`](scripts/bench.ts) runs the same thing the app runs — same
447`.m`, same generated WGSL, same transforms — from Node on desktop WebGPU (Google
448Dawn), and the app prints the command line that reproduces whatever it is
449currently simulating:
451```
452npm run bench -- --preset schnak-spots --geometry ellipsoid --lmax 63 --niter 1 \
453 --steps 2000 --seed 1 --a 0.1 --b 0.9 --D1 0.0004 --D2 0.008 --dt 0.05 \
454 --gax 1.5 --gay 1 --gaz 0.6
455```
457Copy it from under the stats line and compare the `ms/step` it reports with the
458app's. Both sides go through the one shared
459[`src/bench/runSpec.ts`](src/bench/runSpec.ts) — the app formats a run into that
460command, the benchmark parses it back — so there is no second copy of the
461defaults for the two runs to drift apart on. Geometry parameters take a `g`
462prefix (`--gwaist`) so a shape parameter can never collide with a model one.
464The app reports **two** numbers and only the first is comparable to the
465benchmark: `solver` is the batch of steps alone, waited for but not read back;
466`ms/frame` additionally carries a GPU→CPU readback per species, the
467colormapping, and the vertex upload. Those per-frame costs are fixed and do not
468shrink when the GPU gets faster, so on a quick GPU a frame can easily cost ten
469times the steps inside it. That is expected and is not the solver being slower
470in the browser.
472To attribute the gap rather than guess at it:
474```
475node scripts/compare-perf.mjs [--lmax 63] [--steps 300]
476```
478measures the same solver work in both — batched, nothing read back, no rendering
479on either side — and reports each with its CPU-encoding share, the Fourier
480stage, and the adapter. It stops you first if the two are not even the same
481device, which is a common cause of "the browser is much slower". Both sides
482resolve the geometry and the iteration count from the same constants, because
483the iteration count is unrolled into the step and a mismatch would compare two
484different amounts of work.
486The app's **Benchmark** button runs the same measurement in the page, plus the
487**ramp** — the first third of the run against the last. GPUs downclock when
488idle and an animation-paced loop leaves them idle most of every frame, so a
489large ramp means the steady-state number is limited by clocks rather than work.
491### Is it really the same computation?
493```
494node scripts/compare-env.mjs [--lmax 31] [--steps 200] [--preset schnak-spots]
495```
497runs one identical spec on the desktop and in a real browser and compares the
498final spectral state. The pipeline is deterministic given (model source,
499geometry, parameters, lmax, niter, seed, steps), so the two should agree to fp32
500round-off — not bit for bit, since GPUs differ in fused-multiply-add and other
501latitude fp32 allows. It also reports which Fourier stage each side chose, since
502FFT and DFT are genuinely different algorithms that round differently.
504Desktop WebGPU comes from the `webgpu` package (prebuilt Dawn, ~70 MB), an
505optional dependency so that an unsupported platform fails the install of that
506package alone. Its binaries need glibc 2.29+. Other flags: `--steps`,
507`--warmup`, `--batch`, `--json`, `--help`; `DAWN_FLAGS='backend=vulkan'`
508(`;`-separated) passes Dawn options through.
510### The same run in MATLAB
512A 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.
514Two 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.
516## Tests
518There is no second implementation of the solver to diff against, so the `.m`
519path is checked against **closed-form answers** and against **exact structural
520properties**. Five modules, run in both environments:
522[`test/analyticChecks.ts`](test/analyticChecks.ts) — cases whose evolution is
523known exactly, run through the whole real pipeline. All three are statements
524about the round sphere, so all three build on the sphere geometry:
526- **A** — a linear reaction leaves every mode independent, growing by exactly
527 `(1 + dt*c) / (1 + dt*D*l(l+1))` per step. Pins the transform round trip, the
528 eigenvalue mapping, the IMEX update and the state feedback at once. ~2e-7 over
529 20 steps.
530- **B** — a nonlinear reaction on a uniform field stays uniform, so each step is
531 exactly the scalar ODE map. 1.5e-8 over 25 steps.
532- **C** — a 1e-6 perturbation of the Schnakenberg fixed point follows the
533 linearized 2×2 IMEX recurrence, and `(l=24, m=7)` is confirmed unstable.
534 Looser (~4e-3) because fp32 keeps about four digits of a perturbation that
535 small.
537[`test/geometryChecks.ts`](test/geometryChecks.ts) — the surface, the loop, and
538the seed:
540- every geometry evaluates and closes; the sphere has radius 1 everywhere and is
541 **exactly degree 1** in the harmonics, which is what makes the reference case
542 exact rather than merely accurate;
543- the peanut matches its own closed-form radial profile at every grid point, and
544 **the same coefficients give the same surface on a 2× grid** — the 2× Gauss
545 latitudes share no point with the 1× ones, so agreeing there is agreeing
546 everywhere, which is what "rendered exactly, not subdivided" means;
547- unrolling is **exactly linear** in the trip count, and on the sphere — where
548 the geometric correction is mathematically zero — the state after 20 steps
549 stays within fp32 round-off of the 0-iteration one at 1 and 4 iterations;
550- a runtime loop bound is refused at compile time;
551- swapping the surface mid-run leaves the spectral state untouched;
552- the seed field's **WGSL sum matches the same modes summed in f64 on the
553 CPU** (1.8e-6 over ~1,400 terms) — a kernel misreading the packed mode table
554 would still produce a smooth random-looking field, which no "looks patterned"
555 check would catch; the same seed redraws the same field and a different one
556 does not; the field is band-limited (5e-14 of its energy above degree 20)
557 with λ setting the scale; and a λ finer than the mode table holds is refused
558 rather than silently truncated.
560[`test/fluxChecks.ts`](test/fluxChecks.ts) — the six-transform flux-form
561Laplace-Beltrami scheme
562([docs/reduced-transforms.md](docs/reduced-transforms.md)):
564- on the sphere, the precomputed weights match their closed form and the
565 analysed fluxes are **exactly band-limited** (beyond-band tails at f64
566 round-off, ~1e-13), while the deliberately non-smooth control
567 `Q̃/sin θ` keeps a fat tail (~1e-2) — the discrimination the whole scheme
568 rests on;
569- on a non-axisymmetric surface, the flux tails match the Cartesian gradient
570 component's, the doc's §7.1 criterion;
571- the compiled op sequences add **5 Legendre transforms per species per
572 iteration against Algorithm 4's 12**, and a real simulation driven by
573 each stays within fp32 accumulation of the other.
575[`test/modelChecks.ts`](test/modelChecks.ts) compiles every model the app offers
576and asserts **how many kernels it compiles to**, split into the base step and
577what one solve iteration adds. That is a fusion guard: if numbl's inline pass
578stops folding, the results stay correct while every operator becomes its own
579dispatch, which is invisible in the numbers.
581[`test/transformChecks.ts`](test/transformChecks.ts) compares the WGSL transforms
582against shtns-webgpu's f64 CPU twin, and holds every compiled batch width to
583the scalar transforms lane by lane; a model run with `SHT_BATCH=0` must
584reproduce the batched run's state exactly.
586- `npm run test:node` — under Dawn on the desktop, via `vite-node`. Needs a GPU;
587 `--skip-without-gpu` lets a machine without one say so and move on (which is
588 what CI does, since the browser suite covers the same modules).
589- `npm run test:gpu` — builds and drives headless Chrome, on SwiftShader in CI.
590 Also runs the soak. A few geometry tolerances are set by SwiftShader's fp32,
591 which is about an order of magnitude looser than Dawn's.
593Other commands:
595- `npm run bench -- --help` — the desktop benchmark.
596- `npm run bench:sht -- --help` — the transforms alone, no solver.
597- `npx vite-node scripts/diagnose-sht.ts` — when the transform tests fail on a
598 GPU, say *which* stage is wrong.
599- `npx vite-node scripts/diagnose-leg.ts [--m 0]` — read the Legendre recurrence
600 out of the production shader term by term.
601- `npx vite-node scripts/longrun-node.ts [lmax]` — run to t = 100 and confirm the
602 pattern saturates rather than decaying or diverging.
603- `node scripts/soak.mjs [steps] [lmax]` — drive the demo for many steps,
604 sampling JS heap and catching crashes.
605- `node scripts/screenshot.mjs out.png [light|dark] [minSteps]` — screenshot the
606 demo after a number of steps.
607- `node scripts/check-live.mjs [url]` — smoke-check a deployed URL.
608- `test.html?soak=<steps>&lmax=<n>` — solver-only soak with no rendering.
610### Testing against a reference implementation
612Reference solutions live in the sibling
613[turing-surface-test-data](https://github.com/concept-collection/turing-surface-test-data)
614repo, so an independently-written solver never has to depend on this one.
615`cases/schnakenberg-ellipsoid.md` there specifies the one case this repo
616currently ships a reference for;
617[`docs/ellipsoid-reference-spec.md`](docs/ellipsoid-reference-spec.md)
618restates it in this repo's own terms.
620`npm run ref -- --in <file>` (`scripts/ref.ts`) loads a reference file, runs
621the solver from its exact initial spectral state to the same physical end
622time, and reports the relative-L2 and relative-L-infinity (max-norm) error
623against its final state (plus a geometry sanity check). `--niter` overrides
624the surface-correction iteration count independent of the file, and
625`--tolerance`/`--tolerance-linf` each independently turn their metric into a
626pass/fail for CI.
628The same check runs in the page: **Compare to reference…** picks a `.h5` and
629opens the comparison in one step — the file's own settings (its recorded
630niter, its band, its dt) as the single variant, paused at the file's exact
631initial state, ready to Run. The file defines the whole problem — model,
632parameters, geometry, initial state — and the run stops at the file's end
633time, measured against one extra static row showing its final state on its
634own surface. Watching *where* a variant leaves the reference (rather than
635just reading one number per run) is the point. To widen the study, stop
636comparing, pick more chips, and press Compare — the file stays loaded, with
637the lmax choices floored at its band, since a narrower one could not hold
638its initial state. Reading the file uses
639[h5wasm](https://github.com/usnistgov/h5wasm)'s wasm build, loaded lazily on
640the first file opened.
642## Development
644```
645npm install
646npm run dev # local dev server
647npm run build # type-check + production build to dist/
648```
650### The numbl dependency
652numbl is a local `file:../../numbl` dependency, so a sibling checkout of
653[numbl](https://github.com/flatironinstitute/numbl) is required. We use its
654compiler internals — parser, lowerer, IR, inline pass — which its package
655`exports` map does not publish, so they are reached through the `numbl-src` path
656alias in [`vite.config.ts`](vite.config.ts).
658The exact surface we depend on is written down in
659[`src/mgpu/numbl.d.ts`](src/mgpu/numbl.d.ts) and TypeScript checks against
660*that*, not against numbl's sources. This keeps this project's compiler settings
661independent of numbl's, and means a change to one of those shapes upstream
662breaks the build here with a clear diff rather than deep inside numbl's tree.
663The `For` IR node is spelled out there, since the planner now walks it.
665CI clones numbl to the sibling path that the `file:` dependency expects, pinned
666to a commit, with `--ignore-scripts` (npm runs a linked package's `prepare`
667script, and numbl's is husky). numbl's own `node_modules` are not needed: the
668slice we import is self-contained TypeScript.
670The `scripts/*.ts` entry points that touch the compiler go through `vite-node`,
671so they resolve imports exactly as the browser build does. Plain `node` cannot:
672numbl's sources import each other as `./foo.js` while the files are `.ts`.
674Deployed to GitHub Pages by `.github/workflows/deploy.yml` on push to `main`.
676## License
678CECILL-2.1 (inherited from SHTNS via shtns-webgpu, whose sources are vendored).
↑↓ move↵openescclose