/ concept-collection / turing-surface
Sign in
concept-collection / turing-surface
964 lines · 37.6 KBCodeBlameHistory
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 */
31import { ModelSession } from '../mgpu/session.ts';
32import type { MModel, Params } from '../mgpu/registry.ts';
33import type { MGeometry } from '../geom/registry.ts';
34import {
35 buildTopology,
36 fillFieldValues,
37 fillPositions,
38 fillColors,
39 type SphereMeshTopology,
40} from '../render/sphereMesh.ts';
41import { SphereScene } from '../render/SphereScene.ts';
42import { colormaps } from '../render/colormaps.ts';
ef3ae33Do not stretch the colormap across a constant field's roundoffJeremy Magland 43import { fmtValue, floorRange } from '../render/colorbar.ts';
c90d0e2Check reference files in the browser's compare modeJeremy Magland 44import { prolongCoeffs, sharedModes, sharedNoise } from './sharedStart.ts';
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 45import { variantLabel, VARIANT_COLORS, type Variant } from './variants.ts';
c90d0e2Check reference files in the browser's compare modeJeremy Magland 46import type { ReferenceCase } from './referenceCase.ts';
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 */
61const RENDER_NLAT = 256;
62const RENDER_NLAT_CROWDED = 128;
63const CROWDED_PANELS = 6;
65/** See main.ts's DISPATCH_BUDGET — the same watchdog argument, per variant. */
66const DISPATCH_BUDGET = 1000;
67const STEPS_PER_FRAME_BASE = 4;
69export 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[];
c90d0e2Check reference files in the browser's compare modeJeremy Magland 80 /** Index into `variants` of the run everything else is measured against.
81 * Ignored when `refFile` is given — the file is the reference then. */
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 82 reference: number;
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;
beac00aMerge main into random-fieldsJeremy Magland 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;
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;
105interface 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;
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 */
132interface 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)[];
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 144export class CompareRun {
145 #opts: CompareOptions;
146 #rows: Row[] = [];
c90d0e2Check reference files in the browser's compare modeJeremy Magland 147 #fileRow: FileRow | null = null;
148 /** Base steps taken since the initial state — the refFile clock. */
149 #stepsDone = 0;
150 /** True once a refFile run has reached the file's end time. */
151 #finished = false;
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 152 #topo: SphereMeshTopology;
153 /** Quadrature weight per grid point of the shared grid, for the L2 norm. */
154 #weights: Float64Array;
155 #rangeBars: { fill: (lo: number, hi: number) => void }[] = [];
156 /** Smoothed color range per species, shared by every variant so the panels
157 * in a column are directly comparable by eye and not just by number. */
158 #ranges: { lo: number; hi: number }[] = [];
159 #resizeObs: ResizeObserver | null = null;
161 #running = false;
162 #pumping = false;
163 #disposed = false;
164 #morph: number;
165 /** Base steps per frame; variant i takes this times its dtDiv. */
166 #frameSteps = STEPS_PER_FRAME_BASE;
167 /** Model time all variants are at — one number, by construction. */
168 #t = 0;
169 #frameMs = 0;
170 #note: string;
172 private constructor(init: {
173 opts: CompareOptions;
174 rows: Row[];
c90d0e2Check reference files in the browser's compare modeJeremy Magland 175 fileRow: FileRow | null;
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 176 topo: SphereMeshTopology;
177 weights: Float64Array;
178 rangeBars: { fill: (lo: number, hi: number) => void }[];
179 frameSteps: number;
180 note: string;
181 }) {
182 this.#opts = init.opts;
183 this.#rows = init.rows;
c90d0e2Check reference files in the browser's compare modeJeremy Magland 184 this.#fileRow = init.fileRow;
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 185 this.#topo = init.topo;
186 this.#weights = init.weights;
187 this.#rangeBars = init.rangeBars;
188 this.#frameSteps = init.frameSteps;
189 this.#note = init.note;
190 this.#morph = init.opts.morph;
191 this.#ranges = init.opts.model.species.map(() => ({ lo: NaN, hi: NaN }));
192 }
194 get variants(): Variant[] {
195 return this.#rows.map((r) => r.variant);
196 }
198 /** The variant everything else is measured against — the one whose numbers
199 * stand on their own, so the one the app quotes when it has to quote one. */
200 get referenceSession(): ModelSession | null {
201 return this.#rows[this.#opts.reference]?.session ?? null;
202 }
204 get referenceIndex(): number {
205 return this.#opts.reference;
206 }
c90d0e2Check reference files in the browser's compare modeJeremy Magland 208 /** The reference file this study is checking against, if any. */
209 get refFile(): ReferenceCase | null {
210 return this.#opts.refFile ?? null;
211 }
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 213 /** The base timestep a variant's dtDiv divides. */
214 static baseDt(params: Params): number {
215 return params.dt ?? 0;
216 }
218 static async create(opts: CompareOptions): Promise<CompareRun> {
219 const { device, model, variants } = opts;
220 const baseDt = CompareRun.baseDt(opts.params);
221 const showDt = variants.some((v) => v.dtDiv !== variants[0].dtDiv);
222 const sessions: ModelSession[] = [];
223 // Scenes own a WebGL context and an animation frame each, so a failure
224 // after the grid is up has to take them down explicitly — removing their
225 // canvases from the DOM would leave both running.
226 let built: Row[] = [];
c90d0e2Check reference files in the browser's compare modeJeremy Magland 227 let builtFile: FileRow | null = null;
229 try {
230 for (let i = 0; i < variants.length; i++) {
231 const v = variants[i];
232 opts.onStatus(
233 `compiling ${i + 1}/${variants.length}${variantLabel(v, showDt)} ` +
234 `(a solve iteration is ~15 kernels per species, and there is no ` +
235 `pipeline cache across sessions)`,
236 );
237 // Yield, so the status actually paints before the compile blocks.
238 await new Promise<number>(requestAnimationFrame);
239 sessions.push(
240 await ModelSession.create({
241 device,
242 model,
243 params: { ...opts.params, dt: baseDt / v.dtDiv },
244 lmax: v.lmax,
245 source: opts.source,
246 geometry: opts.geometry,
247 geometryParams: opts.geometryParams,
248 geometrySource: opts.geometrySource,
249 niter: v.niter,
beac00aMerge main into random-fieldsJeremy Magland 250 lam3: opts.lam3,
252 );
253 }
255 // ---- the shared display grid ----------------------------------------
256 const maxLmax = Math.max(...variants.map((v) => v.lmax));
c90d0e2Check reference files in the browser's compare modeJeremy Magland 257 const panels = (variants.length + (opts.refFile ? 1 : 0)) * model.species.length;
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 258 const target = panels > CROWDED_PANELS ? RENDER_NLAT_CROWDED : RENDER_NLAT;
259 // Never below what the finest band needs to be representable at all
260 // (ShtPlan requires nlat > lmax), whatever the panel count says.
261 const nlat = Math.max(target, 2 * Math.ceil((maxLmax + 2) / 2));
262 let nphi = 1;
263 while (nphi < Math.max(2 * nlat, 2 * maxLmax + 1)) nphi *= 2;
264 for (const s of sessions) await s.setDisplayGrid(nlat, nphi);
266 // ---- one initial condition, on every grid ---------------------------
c90d0e2Check reference files in the browser's compare modeJeremy Magland 267 if (opts.refFile) {
268 // The file's exact spectral state, prolonged into each variant's band.
269 // Exact, not approximate: the state is band-limited at the file's lmax
270 // and every variant's band contains it, so each session starts from
271 // the very field the reference run started from.
272 opts.onStatus('loading the initial state from the reference file…');
273 for (const s of sessions) {
274 s.loadState(prolongState(opts.refFile.initial, model.state, opts.refFile.lmax, s.cfg.lmax));
275 }
276 } else {
277 opts.onStatus('seeding all variants from one band-limited perturbation…');
278 const noise = await sharedNoise(sessions, model.seedAmp, opts.seed);
279 const modes = await sharedModes(sessions[opts.reference] ?? sessions[0], opts.seed);
280 // One at a time: a seed submits its whole mode sum in pieces, and there
281 // is nothing to gain from interleaving several variants' worth of it.
282 for (let i = 0; i < sessions.length; i++) await sessions[i].seedWith(noise[i], modes);
283 }
285 // ---- the mesh, shared; the surface, per variant ---------------------
286 const view = sessions[0].viewSht;
287 const phi = new Float64Array(nphi);
288 for (let j = 0; j < nphi; j++) phi[j] = (2 * Math.PI * j) / nphi;
289 const topo = buildTopology(view.cosTheta, phi);
290 // Gauss weights carry the sin(theta) of the area element; the constant
291 // 2*pi/nphi is common to every point and cancels in the relative norm.
292 const weights = new Float64Array(nlat * nphi);
293 for (let i = 0; i < nlat; i++) {
294 for (let j = 0; j < nphi; j++) weights[i * nphi + j] = view.gaussWeights[i];
295 }
297 // ---- how many steps a frame may submit ------------------------------
298 // Per variant: its own unrolled step size times its dtDiv, since a ÷K
299 // variant takes K times as many steps to reach the same time.
300 let frameSteps = STEPS_PER_FRAME_BASE;
301 const ops: number[] = [];
302 for (let i = 0; i < sessions.length; i++) {
303 const n = Math.max(1, sessions[i].describe().step.length);
304 ops.push(n);
305 frameSteps = Math.min(
306 frameSteps,
307 Math.max(1, Math.floor(DISPATCH_BUDGET / (n * variants[i].dtDiv))),
308 );
309 }
310 frameSteps = Math.max(1, frameSteps);
312 // ---- the grid of panels ---------------------------------------------
c90d0e2Check reference files in the browser's compare modeJeremy Magland 313 const { rows, fileRow, rangeBars } = await buildGrid(opts, sessions, topo, showDt);
c90d0e2Check reference files in the browser's compare modeJeremy Magland 315 builtFile = fileRow;
317 const solverGrid = sessions.map((s) => `${s.cfg.nlat}×${s.cfg.nphi}`);
318 const note =
3210e7dOpen the reference comparison in one clickJeremy Magland 319 `${variants.length} variant${variants.length === 1 ? '' : 's'} · ` +
320 `display grid ${nlat}×${nphi}` +
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 321 (sessions.some((s) => s.cfg.nlat > nlat)
322 ? ` (below the finest solver grid ${solverGrid[solverGrid.length - 1]} — display only)`
323 : '') +
324 ` · ${frameSteps} base step${frameSteps === 1 ? '' : 's'}/frame` +
325 ` · ops/step ${ops.join(', ')}`;
327 const run = new CompareRun({
c90d0e2Check reference files in the browser's compare modeJeremy Magland 328 opts, rows, fileRow, topo, weights, rangeBars, frameSteps, note,
330 await run.draw();
331 run.#observeResize();
332 run.#status();
333 return run;
334 } catch (e) {
335 for (const r of built) for (const s of r.scenes) s.dispose();
c90d0e2Check reference files in the browser's compare modeJeremy Magland 336 for (const s of builtFile?.scenes ?? []) s.dispose();
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 337 for (const s of sessions) s.destroy();
338 opts.container.replaceChildren();
339 opts.container.classList.remove('compare');
340 throw e;
341 }
342 }
344 // ------------------------------------------------------------------ state
345 setRunning(next: boolean): void {
346 this.#running = next;
347 if (next) void this.#pump();
348 }
350 get running(): boolean {
351 return this.#running;
352 }
c90d0e2Check reference files in the browser's compare modeJeremy Magland 354 /** Re-seed every variant from one new shared perturbation — or, against a
355 * reference file, restart from its initial state (there is nothing to
356 * draw; the seed is ignored). */
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 357 async reseed(seed: number): Promise<void> {
358 const wasRunning = this.#running;
359 this.#running = false;
360 while (this.#pumping) await nextFrame();
361 if (this.#disposed) return;
beac00aMerge main into random-fieldsJeremy Magland 362 const sessions = this.#rows.map((r) => r.session);
c90d0e2Check reference files in the browser's compare modeJeremy Magland 363 const refFile = this.#opts.refFile;
364 if (refFile) {
365 for (const s of sessions) {
366 s.loadState(prolongState(refFile.initial, this.#opts.model.state, refFile.lmax, s.cfg.lmax));
367 }
368 } else {
369 const noise = await sharedNoise(sessions, this.#opts.model.seedAmp, seed);
370 const modes = await sharedModes(this.referenceSession ?? sessions[0], seed);
371 // Checked per variant, not once: a seed awaits its own submission, so a
372 // dispose can land between two of them and destroy the sessions left.
373 for (let i = 0; i < sessions.length; i++) {
374 if (this.#disposed) return;
375 await sessions[i].seedWith(noise[i], modes);
376 }
beac00aMerge main into random-fieldsJeremy Magland 377 }
c90d0e2Check reference files in the browser's compare modeJeremy Magland 379 this.#stepsDone = 0;
380 this.#finished = false;
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 381 for (const r of this.#ranges) {
382 r.lo = NaN;
383 r.hi = NaN;
384 }
385 await this.draw();
c90d0e2Check reference files in the browser's compare modeJeremy Magland 386 this.#status();
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 387 if (!this.#disposed && wasRunning) this.setRunning(true);
388 }
beac00aMerge main into random-fieldsJeremy Magland 390 /** Wavelength of the seeded random field. One number for the study: every
391 * variant seeds from the same field, so they seed at the same wavelength. */
392 get lam3(): number {
393 return this.#rows[0]?.session.lam3 ?? 0;
394 }
396 /** Change it on every variant. Like the single run's, this only takes effect
397 * on the next reseed, which is where the field is drawn. */
398 setLam3(lambda: number): void {
399 this.#opts.lam3 = lambda;
400 for (const r of this.#rows) r.session.setLam3(lambda);
401 }
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 403 /** Model parameters changed. Each variant keeps its own dt. */
404 setParams(params: Params): void {
c90d0e2Check reference files in the browser's compare modeJeremy Magland 405 // Against a reference file the parameters *are* the file's — they define
406 // the problem being checked — and the page's parameter panel edits the
407 // page's own model, which need not even be this one. Nothing to apply.
408 if (this.#opts.refFile) return;
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 409 this.#opts.params = params;
410 const baseDt = CompareRun.baseDt(params);
411 for (const r of this.#rows) {
412 r.session.setParams({ ...params, dt: baseDt / r.variant.dtDiv });
413 }
414 }
416 setMorph(morph: number): void {
417 this.#morph = morph;
418 for (const r of this.#rows) {
419 fillPositions(r.posBuf, r.coords, this.#topo, morph);
420 for (const s of r.scenes) s.updatePositions(r.posBuf);
421 }
c90d0e2Check reference files in the browser's compare modeJeremy Magland 422 const f = this.#fileRow;
423 if (f) {
424 fillPositions(f.posBuf, f.coords, this.#topo, morph);
425 for (const s of f.scenes) s.updatePositions(f.posBuf);
426 }
429 resetView(): void {
c90d0e2Check reference files in the browser's compare modeJeremy Magland 430 for (const s of this.#allScenes()) s.resetCamera();
433 dispose(): void {
434 this.#disposed = true;
435 this.#running = false;
436 this.#resizeObs?.disconnect();
437 this.#resizeObs = null;
438 for (const r of this.#rows) {
439 for (const s of r.scenes) s.dispose();
440 r.session.destroy();
441 }
c90d0e2Check reference files in the browser's compare modeJeremy Magland 442 for (const s of this.#fileRow?.scenes ?? []) s.dispose();
c90d0e2Check reference files in the browser's compare modeJeremy Magland 444 this.#fileRow = null;
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 445 this.#opts.container.replaceChildren();
446 this.#opts.container.classList.remove('compare');
447 }
c90d0e2Check reference files in the browser's compare modeJeremy Magland 449 #allScenes(): SphereScene[] {
450 return [...this.#rows.flatMap((r) => r.scenes), ...(this.#fileRow?.scenes ?? [])];
451 }
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 453 // ----------------------------------------------------------------- drawing
454 /**
455 * One frame's readback: every variant's every species, on the shared grid.
456 * Read first, then color — the range is shared down a column, so no panel can
457 * be filled until the column's range is known.
458 */
459 async draw(): Promise<void> {
460 if (this.#disposed) return;
461 const species = this.#opts.model.species;
462 // Sessions are independent, so their readbacks can be in flight together;
463 // within one session they must not be (they share its staging buffers).
464 await Promise.all(
465 this.#rows.map(async (r) => {
466 for (let k = 0; k < species.length; k++) {
467 r.fields[k] = await r.session.readSpecies(k);
468 }
469 }),
470 );
471 if (this.#disposed) return;
473 const cmap = colormaps[this.#opts.colormapName()] ?? colormaps.viridis;
475 /**
476 * What scales a column is the whole question, and it has three wrong
477 * answers.
478 *
479 * Per panel is wrong: a range each rescales every variant to itself and
480 * hides exactly the difference the grid exists to show. The union over
481 * variants is wrong for the opposite reason: a variant outside the
482 * iteration's convergence radius runs away to 1e20 and then to NaN, and a
483 * union range rescales the *whole column* to it, flattening every panel to
484 * one colour — which reads as "they all blew up" when only one did.
485 *
486 * The reference alone is wrong too, less obviously, and it is the case that
487 * actually bites: outside the convergence radius *more* Richardson
488 * iterations diverge *faster*, so the row that goes first is usually the
489 * highest-niter one — which is the reference.
490 *
491 * So the column is scaled by whichever variant **reaches least far from
492 * zero** — the least-blown-up one. That is a comparison between the rows,
493 * not a threshold on any of them, and the distinction is the whole point:
494 * any "is this value too big?" test has a window in which a diverging field
495 * is still under the limit, and for as long as that window lasts it drags
496 * the scale and flattens the grid, until it finally trips and everything
497 * springs back. A comparison has no such window — a run-away only has to be
498 * *larger* than a healthy row to stop setting the scale, which it is from
499 * its first bad step, and it stays larger no matter how many other rows go
500 * with it. One healthy variant is enough to keep the grid readable.
501 *
502 * The cost is a slight bias: among healthy variants the scale comes from
503 * the one with the smallest peak, so the others clip by however much they
504 * exceed it. They are approximations of the same solution, so that is a
505 * fraction of a percent, and the alternative is a display that a single
506 * divergence can take away.
507 */
508 const bounds = this.#rows.map((r) => species.map((_, k) => finiteRange(r.fields[k])));
509 this.#rows.forEach((r, i) => {
510 // A row with any non-finite value is out of the running entirely: its
511 // finite entries are whatever survived, and no rank over them means much.
512 r.healthy = species.every((_, k) => allFinite(r.fields[k]) && bounds[i][k] !== null);
513 });
515 for (let k = 0; k < species.length; k++) {
c90d0e2Check reference files in the browser's compare modeJeremy Magland 516 // The file row, when there is one, is a candidate like any healthy
517 // variant: early on the variants' small fields set the scale (it merely
518 // clips), and if every variant diverges it is the row that keeps the
519 // grid readable.
520 const anchor = leastPeak([
521 ...this.#rows.map((r, i) => (r.healthy ? bounds[i][k] : null)),
522 this.#fileRow?.bounds[k] ?? null,
523 ]);
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 524 const range = this.#ranges[k];
525 if (anchor) {
526 if (!Number.isFinite(range.lo)) {
527 range.lo = anchor.lo;
528 range.hi = anchor.hi;
529 } else {
530 // Smooth in both directions so the shading evolves gently as the
531 // pattern grows, as the single-run view does.
532 const a = 0.15;
533 range.lo += a * (anchor.lo - range.lo);
534 range.hi += a * (anchor.hi - range.hi);
535 }
536 }
537 // With every row gone, the last good range is kept rather than replaced
538 // by nothing: the panels freeze at a readable scale and the row labels
539 // say what happened, instead of the grid going blank.
540 if (!Number.isFinite(range.lo) || !Number.isFinite(range.hi)) continue;
ef3ae33Do not stretch the colormap across a constant field's roundoffJeremy Magland 541 // The floor is applied to what is drawn, not to what is tracked, so it
542 // never feeds back into the smoothing above.
543 const shown = floorRange(range.lo, range.hi);
544 this.#rangeBars[k]?.fill(shown.lo, shown.hi);
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 545 for (const r of this.#rows) {
546 fillFieldValues(r.valueBufs[k], r.fields[k], this.#topo);
ef3ae33Do not stretch the colormap across a constant field's roundoffJeremy Magland 547 fillColors(r.colorBufs[k], r.valueBufs[k], shown.lo, shown.hi, cmap);
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 548 r.scenes[k]?.updateColors(r.colorBufs[k]);
549 }
c90d0e2Check reference files in the browser's compare modeJeremy Magland 550 const f = this.#fileRow;
551 if (f) {
552 // Its values never change; only its coloring follows the shared range.
553 fillColors(f.colorBufs[k], f.valueBufs[k], shown.lo, shown.hi, cmap);
554 f.scenes[k]?.updateColors(f.colorBufs[k]);
555 }
558 this.#measureDifference();
559 this.#updateRowStats();
560 }
562 /**
563 * Relative L2 difference from the reference, per species, on the shared
564 * grid. Weighted by the Gauss weights, so it is the norm on the parameter
565 * sphere — not on the embedded surface, which would weight by the area
566 * element. That makes it a consistent diagnostic across variants rather than
567 * a physical quantity, which is all it is used for.
568 */
569 #measureDifference(): void {
c90d0e2Check reference files in the browser's compare modeJeremy Magland 570 // Against a reference file, every row is measured against its final state;
571 // otherwise against the chosen reference variant, whose own Δ is zero.
572 const ref = this.#fileRow ? null : this.#rows[this.#opts.reference];
573 const refFields = this.#fileRow?.fields ?? ref?.fields;
574 if (!refFields) return;
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 575 const species = this.#opts.model.species;
576 for (const r of this.#rows) {
577 for (let k = 0; k < species.length; k++) {
578 if (r === ref) {
579 r.err[k] = 0;
580 continue;
581 }
582 const a = r.fields[k];
c90d0e2Check reference files in the browser's compare modeJeremy Magland 583 const b = refFields[k];
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 584 if (!a || !b || a.length !== b.length) {
585 r.err[k] = NaN;
586 continue;
587 }
588 let num = 0;
589 let den = 0;
590 for (let i = 0; i < a.length; i++) {
591 const w = this.#weights[i];
592 const d = a[i] - b[i];
593 num += w * d * d;
594 den += w * b[i] * b[i];
595 }
596 r.err[k] = den > 0 ? Math.sqrt(num / den) : NaN;
597 }
598 }
599 }
601 /**
602 * Each row's standing line: how many of its own steps it took to reach the
603 * common time, and how far it is from the reference right now, per species.
604 * Per species rather than a single worst-case number because the two are
605 * genuinely different questions on a two-species model — the slow species is
606 * usually the one that has converged and the fast one the one that has not.
607 */
608 #updateRowStats(): void {
609 const species = this.#opts.model.species;
c90d0e2Check reference files in the browser's compare modeJeremy Magland 610 const ref = this.#fileRow ? null : this.#rows[this.#opts.reference];
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 611 for (const r of this.#rows) {
612 const per = species
613 .map((s, k) => `${s} ${Number.isFinite(r.err[k]) ? r.err[k].toExponential(2) : '—'}`)
614 .join('<br>');
615 // Divergence is said, not implied. Scaled to a healthy row, a blown-up
616 // variant is a flat saturated panel, which on its own is easy to misread
617 // as a converged uniform state.
618 const body = !r.healthy
619 ? '<b class="cmp-diverged">diverged</b>'
620 : r === ref
621 ? '<b>reference</b>'
622 : ${per}`;
623 r.statEl.innerHTML = `${r.session.steps.toLocaleString()} steps<br>${body}`;
624 }
625 }
627 #status(): void {
c90d0e2Check reference files in the browser's compare modeJeremy Magland 628 const refFile = this.#opts.refFile;
629 const clock = refFile
630 ? `<b>t = ${this.#t.toFixed(2)} / ${(refFile.steps * CompareRun.baseDt(this.#opts.params)).toFixed(2)}</b>` +
631 (this.#finished
632 ? ` — <b>at the file's end time</b>: Δ is the final comparison against its final state`
633 : ` · Δ is the distance still to the file's <i>final</i> state — read it at the end time`)
634 : `<b>t = ${this.#t.toFixed(2)}</b> (same for every variant)`;
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 635 this.#opts.onStatus(
c90d0e2Check reference files in the browser's compare modeJeremy Magland 636 `${clock} · ` +
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 637 (this.#frameMs > 0 ? `${this.#frameMs.toFixed(1)} ms/frame · ` : '') +
638 this.#note,
639 );
640 }
642 #observeResize(): void {
c90d0e2Check reference files in the browser's compare modeJeremy Magland 643 const scenes = this.#allScenes();
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 644 this.#resizeObs = new ResizeObserver(() => {
645 for (const s of scenes) {
646 const box = s.canvas.parentElement;
647 if (box) s.resize(box.clientWidth, box.clientHeight);
648 }
649 });
650 for (const s of scenes) {
651 const box = s.canvas.parentElement;
652 if (box) this.#resizeObs.observe(box);
653 }
654 }
656 // -------------------------------------------------------------- the clock
657 /**
658 * One frame advances every variant by the *same model time*: `frameSteps`
659 * base steps, which a ÷K variant covers in K times as many of its own. That
660 * is the whole reason dt varies by an integer divisor — the alternative is
661 * rounding each variant to the nearest step and comparing fields that are a
662 * fraction of a timestep apart, which would show up as a difference and be
663 * indistinguishable from a real one.
664 */
665 async #pump(): Promise<void> {
666 if (this.#pumping) return;
667 this.#pumping = true;
668 try {
669 while (this.#running && !this.#disposed) {
c90d0e2Check reference files in the browser's compare modeJeremy Magland 670 // Against a reference file the run is finite: the last frame takes
671 // however many base steps remain, so every variant lands exactly on
672 // the file's end time — where Δ against its final state is the
673 // comparison — and stops there rather than drifting past it.
674 const refFile = this.#opts.refFile;
675 const n = refFile
676 ? Math.min(this.#frameSteps, refFile.steps - this.#stepsDone)
677 : this.#frameSteps;
678 if (n <= 0) {
679 this.#running = false;
680 this.#opts.onFinished?.();
681 break;
682 }
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 683 const t0 = performance.now();
c90d0e2Check reference files in the browser's compare modeJeremy Magland 684 for (const r of this.#rows) r.session.step(n * r.variant.dtDiv);
685 this.#stepsDone += n;
686 this.#t += n * CompareRun.baseDt(this.#opts.params);
688 if (this.#disposed) break;
689 const dt = performance.now() - t0;
690 this.#frameMs = this.#frameMs === 0 ? dt : this.#frameMs + 0.05 * (dt - this.#frameMs);
c90d0e2Check reference files in the browser's compare modeJeremy Magland 691 if (refFile && this.#stepsDone >= refFile.steps) {
692 this.#finished = true;
693 this.#running = false;
694 this.#status();
695 this.#opts.onFinished?.();
696 break;
697 }
699 await nextFrame();
700 }
701 if (!this.#disposed) {
702 await this.draw();
703 this.#status();
704 }
705 } finally {
706 this.#pumping = false;
707 }
708 }
711const nextFrame = (): Promise<number> => new Promise(requestAnimationFrame);
c90d0e2Check reference files in the browser's compare modeJeremy Magland 713/** A whole spectral state re-indexed into a (wider) band's layout — the
714 * reference file's initial condition, in the form loadState takes. */
715function prolongState(
716 coeffs: Record<string, Float32Array>,
717 names: string[],
718 lmaxFrom: number,
719 lmaxTo: number,
720): Record<string, Float32Array> {
721 const out: Record<string, Float32Array> = {};
722 for (const name of names) out[name] = prolongCoeffs(coeffs[name], lmaxFrom, lmaxTo);
723 return out;
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 726/** Whether every entry is an ordinary number — false once a variant has left
727 * its convergence radius and saturated to infinity or NaN. */
728function allFinite(f: Float32Array | undefined): boolean {
729 if (!f) return false;
730 for (let i = 0; i < f.length; i++) if (!Number.isFinite(f[i])) return false;
731 return true;
734type Bounds = { lo: number; hi: number };
736/** How far a field reaches from zero — the one number the rows are ranked by
737 * when deciding which of them sets a column's scale. */
738const peak = (b: Bounds): number => Math.max(Math.abs(b.lo), Math.abs(b.hi));
740/** Whichever of the given bounds reaches least far from zero; null if none. */
741function leastPeak(all: (Bounds | null)[]): Bounds | null {
742 let best: Bounds | null = null;
743 for (const b of all) {
744 if (b !== null && (best === null || peak(b) < peak(best))) best = b;
745 }
746 return best;
749/** Min and max over the finite entries only; null when there are none. */
750function finiteRange(f: Float32Array | undefined): { lo: number; hi: number } | null {
751 if (!f) return null;
752 let lo = Infinity;
753 let hi = -Infinity;
754 for (let i = 0; i < f.length; i++) {
755 const v = f[i];
756 if (!Number.isFinite(v)) continue;
757 if (v < lo) lo = v;
758 if (v > hi) hi = v;
759 }
760 return lo <= hi ? { lo, hi } : null;
763/**
764 * The DOM: a header row naming each species and carrying that column's shared
765 * color range, then one row per variant. The colorbar is per *column* rather
766 * than per panel because the range is shared — a bar on every panel would be
767 * the same bar repeated, and would suggest each panel had its own scaling,
768 * which is exactly the thing that would make the comparison a lie.
769 */
c90d0e2Check reference files in the browser's compare modeJeremy Magland 770/** The file row's label color — none of the variant palette, since it is not
771 * a variant: it is the thing they are all measured against. */
772const FILE_ROW_COLOR = '#57606a';
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 774async function buildGrid(
775 opts: CompareOptions,
776 sessions: ModelSession[],
777 topo: SphereMeshTopology,
778 showDt: boolean,
780 rows: Row[];
781 fileRow: FileRow | null;
782 rangeBars: { fill: (lo: number, hi: number) => void }[];
783}> {
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 784 const { container, model } = opts;
785 container.replaceChildren();
786 container.classList.add('compare');
788 const head = document.createElement('div');
789 head.className = 'cmp-row cmp-head';
790 const headSpacer = document.createElement('div');
791 headSpacer.className = 'cmp-rowlabel';
792 const headCols = document.createElement('div');
793 headCols.className = 'cmp-cols';
794 head.append(headSpacer, headCols);
795 container.append(head);
797 const rangeBars = model.species.map((name) => {
798 const col = document.createElement('div');
799 col.className = 'cmp-colhead';
800 const tag = document.createElement('b');
801 tag.textContent = name;
802 const canvas = document.createElement('canvas');
803 canvas.width = 160;
804 canvas.height = 8;
805 canvas.className = 'cmp-rangebar';
806 const lab = document.createElement('span');
807 lab.className = 'cmp-rangelab';
808 col.append(tag, canvas, lab);
809 headCols.append(col);
810 let painted = false;
811 return {
812 fill: (lo: number, hi: number): void => {
813 const ctx = canvas.getContext('2d');
814 if (ctx && !painted) {
815 painted = true;
816 const cmap = colormaps[opts.colormapName()] ?? colormaps.viridis;
817 for (let x = 0; x < canvas.width; x++) {
818 const [r, g, b] = cmap(x / (canvas.width - 1));
819 ctx.fillStyle = `rgb(${r},${g},${b})`;
820 ctx.fillRect(x, 0, 1, canvas.height);
821 }
822 }
823 lab.textContent = `${fmtValue(lo)}${fmtValue(hi)}`;
824 },
825 };
826 });
828 const sphereBg = getComputedStyle(document.documentElement)
829 .getPropertyValue('--sphere-bg')
830 .trim();
832 const rows: Row[] = [];
833 for (let i = 0; i < sessions.length; i++) {
834 const session = sessions[i];
835 const variant = opts.variants[i];
836 const color = VARIANT_COLORS[i % VARIANT_COLORS.length];
838 const coords = await session.renderPositions();
839 const posBuf = new Float32Array(topo.numVertices * 3);
840 fillPositions(posBuf, coords, topo, opts.morph);
842 const rowEl = document.createElement('div');
843 rowEl.className = 'cmp-row';
844 const labelEl = document.createElement('div');
845 labelEl.className = 'cmp-rowlabel';
846 labelEl.style.setProperty('--c', color);
847 const nameEl = document.createElement('div');
848 nameEl.className = 'cmp-rowname';
849 nameEl.textContent = variantLabel(variant, showDt);
850 const statEl = document.createElement('div');
851 statEl.className = 'cmp-rowstat';
852 labelEl.append(nameEl, statEl);
853 const colsEl = document.createElement('div');
854 colsEl.className = 'cmp-cols';
855 rowEl.append(labelEl, colsEl);
856 container.append(rowEl);
858 const scenes: SphereScene[] = [];
859 const valueBufs: Float32Array[] = [];
860 const colorBufs: Float32Array[] = [];
861 for (let k = 0; k < model.species.length; k++) {
862 const box = document.createElement('div');
863 box.className = 'sphere-box cmp-box';
864 colsEl.append(box);
865 const scene = new SphereScene(
866 box,
867 topo.numVertices,
868 topo.indices,
869 Float32Array.from(posBuf),
870 sphereBg || undefined,
871 );
872 scene.fitCamera();
873 scenes.push(scene);
874 valueBufs.push(new Float32Array(topo.numVertices));
875 colorBufs.push(new Float32Array(topo.numVertices * 3));
876 }
878 rows.push({
879 variant, session, color, coords, posBuf, scenes, valueBufs, colorBufs,
880 fields: [], err: model.species.map(() => 0), healthy: true, statEl,
881 });
882 }
c90d0e2Check reference files in the browser's compare modeJeremy Magland 884 // ---- the reference file's final state, as one more (static) row ---------
885 let fileRow: FileRow | null = null;
886 if (opts.refFile) {
887 const rf = opts.refFile;
888 // Synthesized through the coarsest session's display plan — exact, like
889 // every other use of the shared grid: the file's coefficients are
890 // band-limited at its lmax, which every variant's band contains.
891 const view = sessions[0].viewSht;
892 const lmaxTo = sessions[0].cfg.lmax;
893 const on = (q: Float32Array): Promise<Float32Array> =>
894 view.synth(prolongCoeffs(q, rf.lmax, lmaxTo));
895 const [gx, gy, gz] = [
896 await on(rf.geometryCoeffs.X),
897 await on(rf.geometryCoeffs.Y),
898 await on(rf.geometryCoeffs.Z),
899 ];
900 // The file's own surface, not a regeneration of it — interleaved xyz, the
901 // same layout renderPositions() hands back.
902 const coords = new Float32Array(3 * gx.length);
903 for (let i = 0; i < gx.length; i++) {
904 coords[3 * i] = gx[i];
905 coords[3 * i + 1] = gy[i];
906 coords[3 * i + 2] = gz[i];
907 }
908 const posBuf = new Float32Array(topo.numVertices * 3);
909 fillPositions(posBuf, coords, topo, opts.morph);
911 const rowEl = document.createElement('div');
912 rowEl.className = 'cmp-row';
913 const labelEl = document.createElement('div');
914 labelEl.className = 'cmp-rowlabel';
915 labelEl.style.setProperty('--c', FILE_ROW_COLOR);
916 const nameEl = document.createElement('div');
917 nameEl.className = 'cmp-rowname';
918 nameEl.textContent = 'reference file';
919 nameEl.title = rf.label;
920 const statEl = document.createElement('div');
921 statEl.className = 'cmp-rowstat';
922 statEl.innerHTML = `${rf.steps.toLocaleString()} steps<br><b>final state</b>`;
923 labelEl.append(nameEl, statEl);
924 const colsEl = document.createElement('div');
925 colsEl.className = 'cmp-cols';
926 rowEl.append(labelEl, colsEl);
927 container.append(rowEl);
929 const scenes: SphereScene[] = [];
930 const valueBufs: Float32Array[] = [];
931 const colorBufs: Float32Array[] = [];
932 const fields: Float32Array[] = [];
933 const bounds: (Bounds | null)[] = [];
934 for (let k = 0; k < model.species.length; k++) {
935 const box = document.createElement('div');
936 box.className = 'sphere-box cmp-box';
937 colsEl.append(box);
938 const scene = new SphereScene(
939 box,
940 topo.numVertices,
941 topo.indices,
942 Float32Array.from(posBuf),
943 sphereBg || undefined,
944 );
945 scene.fitCamera();
946 scenes.push(scene);
947 const field = await on(rf.final[model.state[k]]);
948 fields.push(field);
949 bounds.push(finiteRange(field));
950 const valueBuf = new Float32Array(topo.numVertices);
951 fillFieldValues(valueBuf, field, topo);
952 valueBufs.push(valueBuf);
953 colorBufs.push(new Float32Array(topo.numVertices * 3));
954 }
955 fileRow = { coords, posBuf, scenes, valueBufs, colorBufs, fields, bounds };
956 }
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 958 // Every panel shares one camera: the study is about the fields, and looking
959 // at two of them from different angles is not comparing them.
c90d0e2Check reference files in the browser's compare modeJeremy Magland 960 const all = [...rows.flatMap((r) => r.scenes), ...(fileRow?.scenes ?? [])];
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 961 for (let i = 1; i < all.length; i++) all[0].syncCamerasWith(all[i]);
c90d0e2Check reference files in the browser's compare modeJeremy Magland 963 return { rows, fileRow, rangeBars };
moveopenescclose