/ concept-collection / turing-surface
Sign in
concept-collection / turing-surface
963 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 =
319 `${variants.length} variants · display grid ${nlat}×${nphi}` +
320 (sessions.some((s) => s.cfg.nlat > nlat)
321 ? ` (below the finest solver grid ${solverGrid[solverGrid.length - 1]} — display only)`
322 : '') +
323 ` · ${frameSteps} base step${frameSteps === 1 ? '' : 's'}/frame` +
324 ` · ops/step ${ops.join(', ')}`;
326 const run = new CompareRun({
c90d0e2Check reference files in the browser's compare modeJeremy Magland 327 opts, rows, fileRow, topo, weights, rangeBars, frameSteps, note,
329 await run.draw();
330 run.#observeResize();
331 run.#status();
332 return run;
333 } catch (e) {
334 for (const r of built) for (const s of r.scenes) s.dispose();
c90d0e2Check reference files in the browser's compare modeJeremy Magland 335 for (const s of builtFile?.scenes ?? []) s.dispose();
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 336 for (const s of sessions) s.destroy();
337 opts.container.replaceChildren();
338 opts.container.classList.remove('compare');
339 throw e;
340 }
341 }
343 // ------------------------------------------------------------------ state
344 setRunning(next: boolean): void {
345 this.#running = next;
346 if (next) void this.#pump();
347 }
349 get running(): boolean {
350 return this.#running;
351 }
c90d0e2Check reference files in the browser's compare modeJeremy Magland 353 /** Re-seed every variant from one new shared perturbation — or, against a
354 * reference file, restart from its initial state (there is nothing to
355 * draw; the seed is ignored). */
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 356 async reseed(seed: number): Promise<void> {
357 const wasRunning = this.#running;
358 this.#running = false;
359 while (this.#pumping) await nextFrame();
360 if (this.#disposed) return;
beac00aMerge main into random-fieldsJeremy Magland 361 const sessions = this.#rows.map((r) => r.session);
c90d0e2Check reference files in the browser's compare modeJeremy Magland 362 const refFile = this.#opts.refFile;
363 if (refFile) {
364 for (const s of sessions) {
365 s.loadState(prolongState(refFile.initial, this.#opts.model.state, refFile.lmax, s.cfg.lmax));
366 }
367 } else {
368 const noise = await sharedNoise(sessions, this.#opts.model.seedAmp, seed);
369 const modes = await sharedModes(this.referenceSession ?? sessions[0], seed);
370 // Checked per variant, not once: a seed awaits its own submission, so a
371 // dispose can land between two of them and destroy the sessions left.
372 for (let i = 0; i < sessions.length; i++) {
373 if (this.#disposed) return;
374 await sessions[i].seedWith(noise[i], modes);
375 }
beac00aMerge main into random-fieldsJeremy Magland 376 }
c90d0e2Check reference files in the browser's compare modeJeremy Magland 378 this.#stepsDone = 0;
379 this.#finished = false;
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 380 for (const r of this.#ranges) {
381 r.lo = NaN;
382 r.hi = NaN;
383 }
384 await this.draw();
c90d0e2Check reference files in the browser's compare modeJeremy Magland 385 this.#status();
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 386 if (!this.#disposed && wasRunning) this.setRunning(true);
387 }
beac00aMerge main into random-fieldsJeremy Magland 389 /** Wavelength of the seeded random field. One number for the study: every
390 * variant seeds from the same field, so they seed at the same wavelength. */
391 get lam3(): number {
392 return this.#rows[0]?.session.lam3 ?? 0;
393 }
395 /** Change it on every variant. Like the single run's, this only takes effect
396 * on the next reseed, which is where the field is drawn. */
397 setLam3(lambda: number): void {
398 this.#opts.lam3 = lambda;
399 for (const r of this.#rows) r.session.setLam3(lambda);
400 }
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 402 /** Model parameters changed. Each variant keeps its own dt. */
403 setParams(params: Params): void {
c90d0e2Check reference files in the browser's compare modeJeremy Magland 404 // Against a reference file the parameters *are* the file's — they define
405 // the problem being checked — and the page's parameter panel edits the
406 // page's own model, which need not even be this one. Nothing to apply.
407 if (this.#opts.refFile) return;
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 408 this.#opts.params = params;
409 const baseDt = CompareRun.baseDt(params);
410 for (const r of this.#rows) {
411 r.session.setParams({ ...params, dt: baseDt / r.variant.dtDiv });
412 }
413 }
415 setMorph(morph: number): void {
416 this.#morph = morph;
417 for (const r of this.#rows) {
418 fillPositions(r.posBuf, r.coords, this.#topo, morph);
419 for (const s of r.scenes) s.updatePositions(r.posBuf);
420 }
c90d0e2Check reference files in the browser's compare modeJeremy Magland 421 const f = this.#fileRow;
422 if (f) {
423 fillPositions(f.posBuf, f.coords, this.#topo, morph);
424 for (const s of f.scenes) s.updatePositions(f.posBuf);
425 }
428 resetView(): void {
c90d0e2Check reference files in the browser's compare modeJeremy Magland 429 for (const s of this.#allScenes()) s.resetCamera();
432 dispose(): void {
433 this.#disposed = true;
434 this.#running = false;
435 this.#resizeObs?.disconnect();
436 this.#resizeObs = null;
437 for (const r of this.#rows) {
438 for (const s of r.scenes) s.dispose();
439 r.session.destroy();
440 }
c90d0e2Check reference files in the browser's compare modeJeremy Magland 441 for (const s of this.#fileRow?.scenes ?? []) s.dispose();
c90d0e2Check reference files in the browser's compare modeJeremy Magland 443 this.#fileRow = null;
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 444 this.#opts.container.replaceChildren();
445 this.#opts.container.classList.remove('compare');
446 }
c90d0e2Check reference files in the browser's compare modeJeremy Magland 448 #allScenes(): SphereScene[] {
449 return [...this.#rows.flatMap((r) => r.scenes), ...(this.#fileRow?.scenes ?? [])];
450 }
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 452 // ----------------------------------------------------------------- drawing
453 /**
454 * One frame's readback: every variant's every species, on the shared grid.
455 * Read first, then color — the range is shared down a column, so no panel can
456 * be filled until the column's range is known.
457 */
458 async draw(): Promise<void> {
459 if (this.#disposed) return;
460 const species = this.#opts.model.species;
461 // Sessions are independent, so their readbacks can be in flight together;
462 // within one session they must not be (they share its staging buffers).
463 await Promise.all(
464 this.#rows.map(async (r) => {
465 for (let k = 0; k < species.length; k++) {
466 r.fields[k] = await r.session.readSpecies(k);
467 }
468 }),
469 );
470 if (this.#disposed) return;
472 const cmap = colormaps[this.#opts.colormapName()] ?? colormaps.viridis;
474 /**
475 * What scales a column is the whole question, and it has three wrong
476 * answers.
477 *
478 * Per panel is wrong: a range each rescales every variant to itself and
479 * hides exactly the difference the grid exists to show. The union over
480 * variants is wrong for the opposite reason: a variant outside the
481 * iteration's convergence radius runs away to 1e20 and then to NaN, and a
482 * union range rescales the *whole column* to it, flattening every panel to
483 * one colour — which reads as "they all blew up" when only one did.
484 *
485 * The reference alone is wrong too, less obviously, and it is the case that
486 * actually bites: outside the convergence radius *more* Richardson
487 * iterations diverge *faster*, so the row that goes first is usually the
488 * highest-niter one — which is the reference.
489 *
490 * So the column is scaled by whichever variant **reaches least far from
491 * zero** — the least-blown-up one. That is a comparison between the rows,
492 * not a threshold on any of them, and the distinction is the whole point:
493 * any "is this value too big?" test has a window in which a diverging field
494 * is still under the limit, and for as long as that window lasts it drags
495 * the scale and flattens the grid, until it finally trips and everything
496 * springs back. A comparison has no such window — a run-away only has to be
497 * *larger* than a healthy row to stop setting the scale, which it is from
498 * its first bad step, and it stays larger no matter how many other rows go
499 * with it. One healthy variant is enough to keep the grid readable.
500 *
501 * The cost is a slight bias: among healthy variants the scale comes from
502 * the one with the smallest peak, so the others clip by however much they
503 * exceed it. They are approximations of the same solution, so that is a
504 * fraction of a percent, and the alternative is a display that a single
505 * divergence can take away.
506 */
507 const bounds = this.#rows.map((r) => species.map((_, k) => finiteRange(r.fields[k])));
508 this.#rows.forEach((r, i) => {
509 // A row with any non-finite value is out of the running entirely: its
510 // finite entries are whatever survived, and no rank over them means much.
511 r.healthy = species.every((_, k) => allFinite(r.fields[k]) && bounds[i][k] !== null);
512 });
514 for (let k = 0; k < species.length; k++) {
c90d0e2Check reference files in the browser's compare modeJeremy Magland 515 // The file row, when there is one, is a candidate like any healthy
516 // variant: early on the variants' small fields set the scale (it merely
517 // clips), and if every variant diverges it is the row that keeps the
518 // grid readable.
519 const anchor = leastPeak([
520 ...this.#rows.map((r, i) => (r.healthy ? bounds[i][k] : null)),
521 this.#fileRow?.bounds[k] ?? null,
522 ]);
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 523 const range = this.#ranges[k];
524 if (anchor) {
525 if (!Number.isFinite(range.lo)) {
526 range.lo = anchor.lo;
527 range.hi = anchor.hi;
528 } else {
529 // Smooth in both directions so the shading evolves gently as the
530 // pattern grows, as the single-run view does.
531 const a = 0.15;
532 range.lo += a * (anchor.lo - range.lo);
533 range.hi += a * (anchor.hi - range.hi);
534 }
535 }
536 // With every row gone, the last good range is kept rather than replaced
537 // by nothing: the panels freeze at a readable scale and the row labels
538 // say what happened, instead of the grid going blank.
539 if (!Number.isFinite(range.lo) || !Number.isFinite(range.hi)) continue;
ef3ae33Do not stretch the colormap across a constant field's roundoffJeremy Magland 540 // The floor is applied to what is drawn, not to what is tracked, so it
541 // never feeds back into the smoothing above.
542 const shown = floorRange(range.lo, range.hi);
543 this.#rangeBars[k]?.fill(shown.lo, shown.hi);
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 544 for (const r of this.#rows) {
545 fillFieldValues(r.valueBufs[k], r.fields[k], this.#topo);
ef3ae33Do not stretch the colormap across a constant field's roundoffJeremy Magland 546 fillColors(r.colorBufs[k], r.valueBufs[k], shown.lo, shown.hi, cmap);
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 547 r.scenes[k]?.updateColors(r.colorBufs[k]);
548 }
c90d0e2Check reference files in the browser's compare modeJeremy Magland 549 const f = this.#fileRow;
550 if (f) {
551 // Its values never change; only its coloring follows the shared range.
552 fillColors(f.colorBufs[k], f.valueBufs[k], shown.lo, shown.hi, cmap);
553 f.scenes[k]?.updateColors(f.colorBufs[k]);
554 }
557 this.#measureDifference();
558 this.#updateRowStats();
559 }
561 /**
562 * Relative L2 difference from the reference, per species, on the shared
563 * grid. Weighted by the Gauss weights, so it is the norm on the parameter
564 * sphere — not on the embedded surface, which would weight by the area
565 * element. That makes it a consistent diagnostic across variants rather than
566 * a physical quantity, which is all it is used for.
567 */
568 #measureDifference(): void {
c90d0e2Check reference files in the browser's compare modeJeremy Magland 569 // Against a reference file, every row is measured against its final state;
570 // otherwise against the chosen reference variant, whose own Δ is zero.
571 const ref = this.#fileRow ? null : this.#rows[this.#opts.reference];
572 const refFields = this.#fileRow?.fields ?? ref?.fields;
573 if (!refFields) return;
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 574 const species = this.#opts.model.species;
575 for (const r of this.#rows) {
576 for (let k = 0; k < species.length; k++) {
577 if (r === ref) {
578 r.err[k] = 0;
579 continue;
580 }
581 const a = r.fields[k];
c90d0e2Check reference files in the browser's compare modeJeremy Magland 582 const b = refFields[k];
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 583 if (!a || !b || a.length !== b.length) {
584 r.err[k] = NaN;
585 continue;
586 }
587 let num = 0;
588 let den = 0;
589 for (let i = 0; i < a.length; i++) {
590 const w = this.#weights[i];
591 const d = a[i] - b[i];
592 num += w * d * d;
593 den += w * b[i] * b[i];
594 }
595 r.err[k] = den > 0 ? Math.sqrt(num / den) : NaN;
596 }
597 }
598 }
600 /**
601 * Each row's standing line: how many of its own steps it took to reach the
602 * common time, and how far it is from the reference right now, per species.
603 * Per species rather than a single worst-case number because the two are
604 * genuinely different questions on a two-species model — the slow species is
605 * usually the one that has converged and the fast one the one that has not.
606 */
607 #updateRowStats(): void {
608 const species = this.#opts.model.species;
c90d0e2Check reference files in the browser's compare modeJeremy Magland 609 const ref = this.#fileRow ? null : this.#rows[this.#opts.reference];
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 610 for (const r of this.#rows) {
611 const per = species
612 .map((s, k) => `${s} ${Number.isFinite(r.err[k]) ? r.err[k].toExponential(2) : '—'}`)
613 .join('<br>');
614 // Divergence is said, not implied. Scaled to a healthy row, a blown-up
615 // variant is a flat saturated panel, which on its own is easy to misread
616 // as a converged uniform state.
617 const body = !r.healthy
618 ? '<b class="cmp-diverged">diverged</b>'
619 : r === ref
620 ? '<b>reference</b>'
621 : ${per}`;
622 r.statEl.innerHTML = `${r.session.steps.toLocaleString()} steps<br>${body}`;
623 }
624 }
626 #status(): void {
c90d0e2Check reference files in the browser's compare modeJeremy Magland 627 const refFile = this.#opts.refFile;
628 const clock = refFile
629 ? `<b>t = ${this.#t.toFixed(2)} / ${(refFile.steps * CompareRun.baseDt(this.#opts.params)).toFixed(2)}</b>` +
630 (this.#finished
631 ? ` — <b>at the file's end time</b>: Δ is the final comparison against its final state`
632 : ` · Δ is the distance still to the file's <i>final</i> state — read it at the end time`)
633 : `<b>t = ${this.#t.toFixed(2)}</b> (same for every variant)`;
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 634 this.#opts.onStatus(
c90d0e2Check reference files in the browser's compare modeJeremy Magland 635 `${clock} · ` +
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 636 (this.#frameMs > 0 ? `${this.#frameMs.toFixed(1)} ms/frame · ` : '') +
637 this.#note,
638 );
639 }
641 #observeResize(): void {
c90d0e2Check reference files in the browser's compare modeJeremy Magland 642 const scenes = this.#allScenes();
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 643 this.#resizeObs = new ResizeObserver(() => {
644 for (const s of scenes) {
645 const box = s.canvas.parentElement;
646 if (box) s.resize(box.clientWidth, box.clientHeight);
647 }
648 });
649 for (const s of scenes) {
650 const box = s.canvas.parentElement;
651 if (box) this.#resizeObs.observe(box);
652 }
653 }
655 // -------------------------------------------------------------- the clock
656 /**
657 * One frame advances every variant by the *same model time*: `frameSteps`
658 * base steps, which a ÷K variant covers in K times as many of its own. That
659 * is the whole reason dt varies by an integer divisor — the alternative is
660 * rounding each variant to the nearest step and comparing fields that are a
661 * fraction of a timestep apart, which would show up as a difference and be
662 * indistinguishable from a real one.
663 */
664 async #pump(): Promise<void> {
665 if (this.#pumping) return;
666 this.#pumping = true;
667 try {
668 while (this.#running && !this.#disposed) {
c90d0e2Check reference files in the browser's compare modeJeremy Magland 669 // Against a reference file the run is finite: the last frame takes
670 // however many base steps remain, so every variant lands exactly on
671 // the file's end time — where Δ against its final state is the
672 // comparison — and stops there rather than drifting past it.
673 const refFile = this.#opts.refFile;
674 const n = refFile
675 ? Math.min(this.#frameSteps, refFile.steps - this.#stepsDone)
676 : this.#frameSteps;
677 if (n <= 0) {
678 this.#running = false;
679 this.#opts.onFinished?.();
680 break;
681 }
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 682 const t0 = performance.now();
c90d0e2Check reference files in the browser's compare modeJeremy Magland 683 for (const r of this.#rows) r.session.step(n * r.variant.dtDiv);
684 this.#stepsDone += n;
685 this.#t += n * CompareRun.baseDt(this.#opts.params);
687 if (this.#disposed) break;
688 const dt = performance.now() - t0;
689 this.#frameMs = this.#frameMs === 0 ? dt : this.#frameMs + 0.05 * (dt - this.#frameMs);
c90d0e2Check reference files in the browser's compare modeJeremy Magland 690 if (refFile && this.#stepsDone >= refFile.steps) {
691 this.#finished = true;
692 this.#running = false;
693 this.#status();
694 this.#opts.onFinished?.();
695 break;
696 }
698 await nextFrame();
699 }
700 if (!this.#disposed) {
701 await this.draw();
702 this.#status();
703 }
704 } finally {
705 this.#pumping = false;
706 }
707 }
710const nextFrame = (): Promise<number> => new Promise(requestAnimationFrame);
c90d0e2Check reference files in the browser's compare modeJeremy Magland 712/** A whole spectral state re-indexed into a (wider) band's layout — the
713 * reference file's initial condition, in the form loadState takes. */
714function prolongState(
715 coeffs: Record<string, Float32Array>,
716 names: string[],
717 lmaxFrom: number,
718 lmaxTo: number,
719): Record<string, Float32Array> {
720 const out: Record<string, Float32Array> = {};
721 for (const name of names) out[name] = prolongCoeffs(coeffs[name], lmaxFrom, lmaxTo);
722 return out;
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 725/** Whether every entry is an ordinary number — false once a variant has left
726 * its convergence radius and saturated to infinity or NaN. */
727function allFinite(f: Float32Array | undefined): boolean {
728 if (!f) return false;
729 for (let i = 0; i < f.length; i++) if (!Number.isFinite(f[i])) return false;
730 return true;
733type Bounds = { lo: number; hi: number };
735/** How far a field reaches from zero — the one number the rows are ranked by
736 * when deciding which of them sets a column's scale. */
737const peak = (b: Bounds): number => Math.max(Math.abs(b.lo), Math.abs(b.hi));
739/** Whichever of the given bounds reaches least far from zero; null if none. */
740function leastPeak(all: (Bounds | null)[]): Bounds | null {
741 let best: Bounds | null = null;
742 for (const b of all) {
743 if (b !== null && (best === null || peak(b) < peak(best))) best = b;
744 }
745 return best;
748/** Min and max over the finite entries only; null when there are none. */
749function finiteRange(f: Float32Array | undefined): { lo: number; hi: number } | null {
750 if (!f) return null;
751 let lo = Infinity;
752 let hi = -Infinity;
753 for (let i = 0; i < f.length; i++) {
754 const v = f[i];
755 if (!Number.isFinite(v)) continue;
756 if (v < lo) lo = v;
757 if (v > hi) hi = v;
758 }
759 return lo <= hi ? { lo, hi } : null;
762/**
763 * The DOM: a header row naming each species and carrying that column's shared
764 * color range, then one row per variant. The colorbar is per *column* rather
765 * than per panel because the range is shared — a bar on every panel would be
766 * the same bar repeated, and would suggest each panel had its own scaling,
767 * which is exactly the thing that would make the comparison a lie.
768 */
c90d0e2Check reference files in the browser's compare modeJeremy Magland 769/** The file row's label color — none of the variant palette, since it is not
770 * a variant: it is the thing they are all measured against. */
771const FILE_ROW_COLOR = '#57606a';
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 773async function buildGrid(
774 opts: CompareOptions,
775 sessions: ModelSession[],
776 topo: SphereMeshTopology,
777 showDt: boolean,
779 rows: Row[];
780 fileRow: FileRow | null;
781 rangeBars: { fill: (lo: number, hi: number) => void }[];
782}> {
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 783 const { container, model } = opts;
784 container.replaceChildren();
785 container.classList.add('compare');
787 const head = document.createElement('div');
788 head.className = 'cmp-row cmp-head';
789 const headSpacer = document.createElement('div');
790 headSpacer.className = 'cmp-rowlabel';
791 const headCols = document.createElement('div');
792 headCols.className = 'cmp-cols';
793 head.append(headSpacer, headCols);
794 container.append(head);
796 const rangeBars = model.species.map((name) => {
797 const col = document.createElement('div');
798 col.className = 'cmp-colhead';
799 const tag = document.createElement('b');
800 tag.textContent = name;
801 const canvas = document.createElement('canvas');
802 canvas.width = 160;
803 canvas.height = 8;
804 canvas.className = 'cmp-rangebar';
805 const lab = document.createElement('span');
806 lab.className = 'cmp-rangelab';
807 col.append(tag, canvas, lab);
808 headCols.append(col);
809 let painted = false;
810 return {
811 fill: (lo: number, hi: number): void => {
812 const ctx = canvas.getContext('2d');
813 if (ctx && !painted) {
814 painted = true;
815 const cmap = colormaps[opts.colormapName()] ?? colormaps.viridis;
816 for (let x = 0; x < canvas.width; x++) {
817 const [r, g, b] = cmap(x / (canvas.width - 1));
818 ctx.fillStyle = `rgb(${r},${g},${b})`;
819 ctx.fillRect(x, 0, 1, canvas.height);
820 }
821 }
822 lab.textContent = `${fmtValue(lo)}${fmtValue(hi)}`;
823 },
824 };
825 });
827 const sphereBg = getComputedStyle(document.documentElement)
828 .getPropertyValue('--sphere-bg')
829 .trim();
831 const rows: Row[] = [];
832 for (let i = 0; i < sessions.length; i++) {
833 const session = sessions[i];
834 const variant = opts.variants[i];
835 const color = VARIANT_COLORS[i % VARIANT_COLORS.length];
837 const coords = await session.renderPositions();
838 const posBuf = new Float32Array(topo.numVertices * 3);
839 fillPositions(posBuf, coords, topo, opts.morph);
841 const rowEl = document.createElement('div');
842 rowEl.className = 'cmp-row';
843 const labelEl = document.createElement('div');
844 labelEl.className = 'cmp-rowlabel';
845 labelEl.style.setProperty('--c', color);
846 const nameEl = document.createElement('div');
847 nameEl.className = 'cmp-rowname';
848 nameEl.textContent = variantLabel(variant, showDt);
849 const statEl = document.createElement('div');
850 statEl.className = 'cmp-rowstat';
851 labelEl.append(nameEl, statEl);
852 const colsEl = document.createElement('div');
853 colsEl.className = 'cmp-cols';
854 rowEl.append(labelEl, colsEl);
855 container.append(rowEl);
857 const scenes: SphereScene[] = [];
858 const valueBufs: Float32Array[] = [];
859 const colorBufs: Float32Array[] = [];
860 for (let k = 0; k < model.species.length; k++) {
861 const box = document.createElement('div');
862 box.className = 'sphere-box cmp-box';
863 colsEl.append(box);
864 const scene = new SphereScene(
865 box,
866 topo.numVertices,
867 topo.indices,
868 Float32Array.from(posBuf),
869 sphereBg || undefined,
870 );
871 scene.fitCamera();
872 scenes.push(scene);
873 valueBufs.push(new Float32Array(topo.numVertices));
874 colorBufs.push(new Float32Array(topo.numVertices * 3));
875 }
877 rows.push({
878 variant, session, color, coords, posBuf, scenes, valueBufs, colorBufs,
879 fields: [], err: model.species.map(() => 0), healthy: true, statEl,
880 });
881 }
c90d0e2Check reference files in the browser's compare modeJeremy Magland 883 // ---- the reference file's final state, as one more (static) row ---------
884 let fileRow: FileRow | null = null;
885 if (opts.refFile) {
886 const rf = opts.refFile;
887 // Synthesized through the coarsest session's display plan — exact, like
888 // every other use of the shared grid: the file's coefficients are
889 // band-limited at its lmax, which every variant's band contains.
890 const view = sessions[0].viewSht;
891 const lmaxTo = sessions[0].cfg.lmax;
892 const on = (q: Float32Array): Promise<Float32Array> =>
893 view.synth(prolongCoeffs(q, rf.lmax, lmaxTo));
894 const [gx, gy, gz] = [
895 await on(rf.geometryCoeffs.X),
896 await on(rf.geometryCoeffs.Y),
897 await on(rf.geometryCoeffs.Z),
898 ];
899 // The file's own surface, not a regeneration of it — interleaved xyz, the
900 // same layout renderPositions() hands back.
901 const coords = new Float32Array(3 * gx.length);
902 for (let i = 0; i < gx.length; i++) {
903 coords[3 * i] = gx[i];
904 coords[3 * i + 1] = gy[i];
905 coords[3 * i + 2] = gz[i];
906 }
907 const posBuf = new Float32Array(topo.numVertices * 3);
908 fillPositions(posBuf, coords, topo, opts.morph);
910 const rowEl = document.createElement('div');
911 rowEl.className = 'cmp-row';
912 const labelEl = document.createElement('div');
913 labelEl.className = 'cmp-rowlabel';
914 labelEl.style.setProperty('--c', FILE_ROW_COLOR);
915 const nameEl = document.createElement('div');
916 nameEl.className = 'cmp-rowname';
917 nameEl.textContent = 'reference file';
918 nameEl.title = rf.label;
919 const statEl = document.createElement('div');
920 statEl.className = 'cmp-rowstat';
921 statEl.innerHTML = `${rf.steps.toLocaleString()} steps<br><b>final state</b>`;
922 labelEl.append(nameEl, statEl);
923 const colsEl = document.createElement('div');
924 colsEl.className = 'cmp-cols';
925 rowEl.append(labelEl, colsEl);
926 container.append(rowEl);
928 const scenes: SphereScene[] = [];
929 const valueBufs: Float32Array[] = [];
930 const colorBufs: Float32Array[] = [];
931 const fields: Float32Array[] = [];
932 const bounds: (Bounds | null)[] = [];
933 for (let k = 0; k < model.species.length; k++) {
934 const box = document.createElement('div');
935 box.className = 'sphere-box cmp-box';
936 colsEl.append(box);
937 const scene = new SphereScene(
938 box,
939 topo.numVertices,
940 topo.indices,
941 Float32Array.from(posBuf),
942 sphereBg || undefined,
943 );
944 scene.fitCamera();
945 scenes.push(scene);
946 const field = await on(rf.final[model.state[k]]);
947 fields.push(field);
948 bounds.push(finiteRange(field));
949 const valueBuf = new Float32Array(topo.numVertices);
950 fillFieldValues(valueBuf, field, topo);
951 valueBufs.push(valueBuf);
952 colorBufs.push(new Float32Array(topo.numVertices * 3));
953 }
954 fileRow = { coords, posBuf, scenes, valueBufs, colorBufs, fields, bounds };
955 }
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 957 // Every panel shares one camera: the study is about the fields, and looking
958 // at two of them from different angles is not comparing them.
c90d0e2Check reference files in the browser's compare modeJeremy Magland 959 const all = [...rows.flatMap((r) => r.scenes), ...(fileRow?.scenes ?? [])];
f467ffaCompare several solver settings side by side, on one clockJeremy Magland 960 for (let i = 1; i < all.length; i++) all[0].syncCamerasWith(all[i]);
c90d0e2Check reference files in the browser's compare modeJeremy Magland 962 return { rows, fileRow, rangeBars };
moveopenescclose