/ concept-collection / turing-surface
concept-collection / turing-surface
719 lines · 27.3 KBBlameHistoryRaw
1/**
2 * Several solver settings, one problem, one clock.
3 *
4 * A convergence study of the knobs that decide how well the implicit solve is
5 * resolved — `niter`, `lmax`, `dt` — run side by side so the answer to "does it
6 * matter?" is visible rather than argued. Every variant is its own
7 * `ModelSession` (both `niter` and `lmax` are structural: they change the
8 * compiled step and the grid), and what makes the set a comparison rather than
9 * a collection is three things they are forced to share:
10 *
11 * - **One initial condition.** Band-limited at the coarsest variant's lmax and
12 * evaluated on each variant's own grid, so every session starts from the same
13 * *function* rather than from the same random seed — see sharedStart.ts for
14 * why the seed alone is not enough.
15 *
16 * - **One clock.** Variants differ in dt only by an integer power-of-two
17 * divisor, and a frame advances each of them by `frameSteps * dtDiv` steps.
18 * Every variant therefore lands on exactly the same model time at the end of
19 * every frame, having taken a different number of steps to get there. Nothing
20 * is ever compared across a time offset.
21 *
22 * - **One grid to look at.** Each session's *display* plan is pointed at a
23 * common grid (ModelSession.setDisplayGrid), which is exact evaluation rather
24 * than resampling because the state is band-limited. So the fields come back
25 * directly comparable point by point, one mesh topology serves every panel,
26 * and the difference norm is an ordinary weighted sum.
27 *
28 * What is *not* shared is the surface: each variant carries the geometry
29 * band-limited at its own lmax, and renders the surface it actually solves on.
30 */
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';
43import { fmtValue, floorRange } from '../render/colorbar.ts';
44import { sharedNoise } from './sharedStart.ts';
45import { variantLabel, VARIANT_COLORS, type Variant } from './variants.ts';
47/**
48 * Latitudes of the shared display grid. 256 is the same target the single-run
49 * view uses for 'auto' oversampling, and for the same reason — beyond it a
50 * finer mesh costs vertices without showing anything.
51 *
52 * Here it is a ceiling as well as a target, in two directions. At lmax 255 the
53 * solver grid is finer than this, so the panels sample the (exact) state more
54 * coarsely than the solver carries it; and past a handful of panels the mesh is
55 * paid for once per panel, in vertices, normals and a WebGL context each, so it
56 * halves. Both are display choices, both are reported in the status line, and
57 * neither touches the difference norm's meaning: that is computed on this same
58 * grid for every variant, so it stays a consistent comparison whatever the grid.
59 */
60const RENDER_NLAT = 256;
61const RENDER_NLAT_CROWDED = 128;
62const CROWDED_PANELS = 6;
64/** See main.ts's DISPATCH_BUDGET — the same watchdog argument, per variant. */
65const DISPATCH_BUDGET = 1000;
66const STEPS_PER_FRAME_BASE = 4;
68export interface CompareOptions {
69 device: GPUDevice;
70 model: MModel;
71 /** The model's parameters, with `dt` read as the *base* timestep that each
72 * variant's dtDiv divides. */
73 params: Params;
74 source: string;
75 geometry: MGeometry;
76 geometryParams: Params;
77 geometrySource: string;
78 variants: Variant[];
79 /** Index into `variants` of the run everything else is measured against. */
80 reference: number;
81 seed: number;
82 morph: number;
83 colormapName: () => string;
84 /** Where the variant grid goes (the app's #panels). */
85 container: HTMLElement;
86 /** Progress and, afterwards, the standing description of the study. */
87 onStatus: (html: string) => void;
90interface Row {
91 variant: Variant;
92 session: ModelSession;
93 color: string;
94 /** Surface coordinates on the shared render grid — this variant's own. */
95 coords: Float32Array;
96 posBuf: Float32Array;
97 scenes: SphereScene[];
98 valueBufs: Float32Array[];
99 colorBufs: Float32Array[];
100 /** Fields read this frame, one per species, on the shared grid. */
101 fields: Float32Array[];
102 /** Relative difference from the reference, one per species. */
103 err: number[];
104 /** False once any species has left the floating-point numbers — the shape a
105 * variant outside the convergence radius eventually fails in. Such a row is
106 * never used to scale a column, and its label says so. */
107 healthy: boolean;
108 statEl: HTMLElement;
111export class CompareRun {
112 #opts: CompareOptions;
113 #rows: Row[] = [];
114 #topo: SphereMeshTopology;
115 /** Quadrature weight per grid point of the shared grid, for the L2 norm. */
116 #weights: Float64Array;
117 #rangeBars: { fill: (lo: number, hi: number) => void }[] = [];
118 /** Smoothed color range per species, shared by every variant so the panels
119 * in a column are directly comparable by eye and not just by number. */
120 #ranges: { lo: number; hi: number }[] = [];
121 #resizeObs: ResizeObserver | null = null;
123 #running = false;
124 #pumping = false;
125 #disposed = false;
126 #morph: number;
127 /** Base steps per frame; variant i takes this times its dtDiv. */
128 #frameSteps = STEPS_PER_FRAME_BASE;
129 /** Model time all variants are at — one number, by construction. */
130 #t = 0;
131 #frameMs = 0;
132 #note: string;
134 private constructor(init: {
135 opts: CompareOptions;
136 rows: Row[];
137 topo: SphereMeshTopology;
138 weights: Float64Array;
139 rangeBars: { fill: (lo: number, hi: number) => void }[];
140 frameSteps: number;
141 note: string;
142 }) {
143 this.#opts = init.opts;
144 this.#rows = init.rows;
145 this.#topo = init.topo;
146 this.#weights = init.weights;
147 this.#rangeBars = init.rangeBars;
148 this.#frameSteps = init.frameSteps;
149 this.#note = init.note;
150 this.#morph = init.opts.morph;
151 this.#ranges = init.opts.model.species.map(() => ({ lo: NaN, hi: NaN }));
152 }
154 get variants(): Variant[] {
155 return this.#rows.map((r) => r.variant);
156 }
158 /** The variant everything else is measured against — the one whose numbers
159 * stand on their own, so the one the app quotes when it has to quote one. */
160 get referenceSession(): ModelSession | null {
161 return this.#rows[this.#opts.reference]?.session ?? null;
162 }
164 get referenceIndex(): number {
165 return this.#opts.reference;
166 }
168 /** The base timestep a variant's dtDiv divides. */
169 static baseDt(params: Params): number {
170 return params.dt ?? 0;
171 }
173 static async create(opts: CompareOptions): Promise<CompareRun> {
174 const { device, model, variants } = opts;
175 const baseDt = CompareRun.baseDt(opts.params);
176 const showDt = variants.some((v) => v.dtDiv !== variants[0].dtDiv);
177 const sessions: ModelSession[] = [];
178 // Scenes own a WebGL context and an animation frame each, so a failure
179 // after the grid is up has to take them down explicitly — removing their
180 // canvases from the DOM would leave both running.
181 let built: Row[] = [];
183 try {
184 for (let i = 0; i < variants.length; i++) {
185 const v = variants[i];
186 opts.onStatus(
187 `compiling ${i + 1}/${variants.length}${variantLabel(v, showDt)} ` +
188 `(a solve iteration is ~15 kernels per species, and there is no ` +
189 `pipeline cache across sessions)`,
190 );
191 // Yield, so the status actually paints before the compile blocks.
192 await new Promise<number>(requestAnimationFrame);
193 sessions.push(
194 await ModelSession.create({
195 device,
196 model,
197 params: { ...opts.params, dt: baseDt / v.dtDiv },
198 lmax: v.lmax,
199 source: opts.source,
200 geometry: opts.geometry,
201 geometryParams: opts.geometryParams,
202 geometrySource: opts.geometrySource,
203 niter: v.niter,
204 }),
205 );
206 }
208 // ---- the shared display grid ----------------------------------------
209 const maxLmax = Math.max(...variants.map((v) => v.lmax));
210 const panels = variants.length * model.species.length;
211 const target = panels > CROWDED_PANELS ? RENDER_NLAT_CROWDED : RENDER_NLAT;
212 // Never below what the finest band needs to be representable at all
213 // (ShtPlan requires nlat > lmax), whatever the panel count says.
214 const nlat = Math.max(target, 2 * Math.ceil((maxLmax + 2) / 2));
215 let nphi = 1;
216 while (nphi < Math.max(2 * nlat, 2 * maxLmax + 1)) nphi *= 2;
217 for (const s of sessions) await s.setDisplayGrid(nlat, nphi);
219 // ---- one initial condition, on every grid ---------------------------
220 opts.onStatus('seeding all variants from one band-limited perturbation…');
221 const noise = await sharedNoise(sessions, model.seedAmp, opts.seed);
222 sessions.forEach((s, i) => s.seedWith(noise[i]));
224 // ---- the mesh, shared; the surface, per variant ---------------------
225 const view = sessions[0].viewSht;
226 const phi = new Float64Array(nphi);
227 for (let j = 0; j < nphi; j++) phi[j] = (2 * Math.PI * j) / nphi;
228 const topo = buildTopology(view.cosTheta, phi);
229 // Gauss weights carry the sin(theta) of the area element; the constant
230 // 2*pi/nphi is common to every point and cancels in the relative norm.
231 const weights = new Float64Array(nlat * nphi);
232 for (let i = 0; i < nlat; i++) {
233 for (let j = 0; j < nphi; j++) weights[i * nphi + j] = view.gaussWeights[i];
234 }
236 // ---- how many steps a frame may submit ------------------------------
237 // Per variant: its own unrolled step size times its dtDiv, since a ÷K
238 // variant takes K times as many steps to reach the same time.
239 let frameSteps = STEPS_PER_FRAME_BASE;
240 const ops: number[] = [];
241 for (let i = 0; i < sessions.length; i++) {
242 const n = Math.max(1, sessions[i].describe().step.length);
243 ops.push(n);
244 frameSteps = Math.min(
245 frameSteps,
246 Math.max(1, Math.floor(DISPATCH_BUDGET / (n * variants[i].dtDiv))),
247 );
248 }
249 frameSteps = Math.max(1, frameSteps);
251 // ---- the grid of panels ---------------------------------------------
252 const { rows, rangeBars } = await buildGrid(opts, sessions, topo, showDt);
253 built = rows;
255 const solverGrid = sessions.map((s) => `${s.cfg.nlat}×${s.cfg.nphi}`);
256 const note =
257 `${variants.length} variants · display grid ${nlat}×${nphi}` +
258 (sessions.some((s) => s.cfg.nlat > nlat)
259 ? ` (below the finest solver grid ${solverGrid[solverGrid.length - 1]} — display only)`
260 : '') +
261 ` · ${frameSteps} base step${frameSteps === 1 ? '' : 's'}/frame` +
262 ` · ops/step ${ops.join(', ')}`;
264 const run = new CompareRun({
265 opts, rows, topo, weights, rangeBars, frameSteps, note,
266 });
267 await run.draw();
268 run.#observeResize();
269 run.#status();
270 return run;
271 } catch (e) {
272 for (const r of built) for (const s of r.scenes) s.dispose();
273 for (const s of sessions) s.destroy();
274 opts.container.replaceChildren();
275 opts.container.classList.remove('compare');
276 throw e;
277 }
278 }
280 // ------------------------------------------------------------------ state
281 setRunning(next: boolean): void {
282 this.#running = next;
283 if (next) void this.#pump();
284 }
286 get running(): boolean {
287 return this.#running;
288 }
290 /** Re-seed every variant from one new shared perturbation. */
291 async reseed(seed: number): Promise<void> {
292 const wasRunning = this.#running;
293 this.#running = false;
294 while (this.#pumping) await nextFrame();
295 if (this.#disposed) return;
296 const noise = await sharedNoise(
297 this.#rows.map((r) => r.session),
298 this.#opts.model.seedAmp,
299 seed,
300 );
301 if (this.#disposed) return;
302 this.#rows.forEach((r, i) => r.session.seedWith(noise[i]));
303 this.#t = 0;
304 for (const r of this.#ranges) {
305 r.lo = NaN;
306 r.hi = NaN;
307 }
308 await this.draw();
309 if (!this.#disposed && wasRunning) this.setRunning(true);
310 }
312 /** Model parameters changed. Each variant keeps its own dt. */
313 setParams(params: Params): void {
314 this.#opts.params = params;
315 const baseDt = CompareRun.baseDt(params);
316 for (const r of this.#rows) {
317 r.session.setParams({ ...params, dt: baseDt / r.variant.dtDiv });
318 }
319 }
321 setMorph(morph: number): void {
322 this.#morph = morph;
323 for (const r of this.#rows) {
324 fillPositions(r.posBuf, r.coords, this.#topo, morph);
325 for (const s of r.scenes) s.updatePositions(r.posBuf);
326 }
327 }
329 resetView(): void {
330 for (const r of this.#rows) for (const s of r.scenes) s.resetCamera();
331 }
333 dispose(): void {
334 this.#disposed = true;
335 this.#running = false;
336 this.#resizeObs?.disconnect();
337 this.#resizeObs = null;
338 for (const r of this.#rows) {
339 for (const s of r.scenes) s.dispose();
340 r.session.destroy();
341 }
342 this.#rows = [];
343 this.#opts.container.replaceChildren();
344 this.#opts.container.classList.remove('compare');
345 }
347 // ----------------------------------------------------------------- drawing
348 /**
349 * One frame's readback: every variant's every species, on the shared grid.
350 * Read first, then color — the range is shared down a column, so no panel can
351 * be filled until the column's range is known.
352 */
353 async draw(): Promise<void> {
354 if (this.#disposed) return;
355 const species = this.#opts.model.species;
356 // Sessions are independent, so their readbacks can be in flight together;
357 // within one session they must not be (they share its staging buffers).
358 await Promise.all(
359 this.#rows.map(async (r) => {
360 for (let k = 0; k < species.length; k++) {
361 r.fields[k] = await r.session.readSpecies(k);
362 }
363 }),
364 );
365 if (this.#disposed) return;
367 const cmap = colormaps[this.#opts.colormapName()] ?? colormaps.viridis;
369 /**
370 * What scales a column is the whole question, and it has three wrong
371 * answers.
372 *
373 * Per panel is wrong: a range each rescales every variant to itself and
374 * hides exactly the difference the grid exists to show. The union over
375 * variants is wrong for the opposite reason: a variant outside the
376 * iteration's convergence radius runs away to 1e20 and then to NaN, and a
377 * union range rescales the *whole column* to it, flattening every panel to
378 * one colour — which reads as "they all blew up" when only one did.
379 *
380 * The reference alone is wrong too, less obviously, and it is the case that
381 * actually bites: outside the convergence radius *more* Richardson
382 * iterations diverge *faster*, so the row that goes first is usually the
383 * highest-niter one — which is the reference.
384 *
385 * So the column is scaled by whichever variant **reaches least far from
386 * zero** — the least-blown-up one. That is a comparison between the rows,
387 * not a threshold on any of them, and the distinction is the whole point:
388 * any "is this value too big?" test has a window in which a diverging field
389 * is still under the limit, and for as long as that window lasts it drags
390 * the scale and flattens the grid, until it finally trips and everything
391 * springs back. A comparison has no such window — a run-away only has to be
392 * *larger* than a healthy row to stop setting the scale, which it is from
393 * its first bad step, and it stays larger no matter how many other rows go
394 * with it. One healthy variant is enough to keep the grid readable.
395 *
396 * The cost is a slight bias: among healthy variants the scale comes from
397 * the one with the smallest peak, so the others clip by however much they
398 * exceed it. They are approximations of the same solution, so that is a
399 * fraction of a percent, and the alternative is a display that a single
400 * divergence can take away.
401 */
402 const bounds = this.#rows.map((r) => species.map((_, k) => finiteRange(r.fields[k])));
403 this.#rows.forEach((r, i) => {
404 // A row with any non-finite value is out of the running entirely: its
405 // finite entries are whatever survived, and no rank over them means much.
406 r.healthy = species.every((_, k) => allFinite(r.fields[k]) && bounds[i][k] !== null);
407 });
409 for (let k = 0; k < species.length; k++) {
410 const anchor = leastPeak(this.#rows.map((r, i) => (r.healthy ? bounds[i][k] : null)));
411 const range = this.#ranges[k];
412 if (anchor) {
413 if (!Number.isFinite(range.lo)) {
414 range.lo = anchor.lo;
415 range.hi = anchor.hi;
416 } else {
417 // Smooth in both directions so the shading evolves gently as the
418 // pattern grows, as the single-run view does.
419 const a = 0.15;
420 range.lo += a * (anchor.lo - range.lo);
421 range.hi += a * (anchor.hi - range.hi);
422 }
423 }
424 // With every row gone, the last good range is kept rather than replaced
425 // by nothing: the panels freeze at a readable scale and the row labels
426 // say what happened, instead of the grid going blank.
427 if (!Number.isFinite(range.lo) || !Number.isFinite(range.hi)) continue;
428 // The floor is applied to what is drawn, not to what is tracked, so it
429 // never feeds back into the smoothing above.
430 const shown = floorRange(range.lo, range.hi);
431 this.#rangeBars[k]?.fill(shown.lo, shown.hi);
432 for (const r of this.#rows) {
433 fillFieldValues(r.valueBufs[k], r.fields[k], this.#topo);
434 fillColors(r.colorBufs[k], r.valueBufs[k], shown.lo, shown.hi, cmap);
435 r.scenes[k]?.updateColors(r.colorBufs[k]);
436 }
437 }
439 this.#measureDifference();
440 this.#updateRowStats();
441 }
443 /**
444 * Relative L2 difference from the reference, per species, on the shared
445 * grid. Weighted by the Gauss weights, so it is the norm on the parameter
446 * sphere — not on the embedded surface, which would weight by the area
447 * element. That makes it a consistent diagnostic across variants rather than
448 * a physical quantity, which is all it is used for.
449 */
450 #measureDifference(): void {
451 const ref = this.#rows[this.#opts.reference];
452 if (!ref) return;
453 const species = this.#opts.model.species;
454 for (const r of this.#rows) {
455 for (let k = 0; k < species.length; k++) {
456 if (r === ref) {
457 r.err[k] = 0;
458 continue;
459 }
460 const a = r.fields[k];
461 const b = ref.fields[k];
462 if (!a || !b || a.length !== b.length) {
463 r.err[k] = NaN;
464 continue;
465 }
466 let num = 0;
467 let den = 0;
468 for (let i = 0; i < a.length; i++) {
469 const w = this.#weights[i];
470 const d = a[i] - b[i];
471 num += w * d * d;
472 den += w * b[i] * b[i];
473 }
474 r.err[k] = den > 0 ? Math.sqrt(num / den) : NaN;
475 }
476 }
477 }
479 /**
480 * Each row's standing line: how many of its own steps it took to reach the
481 * common time, and how far it is from the reference right now, per species.
482 * Per species rather than a single worst-case number because the two are
483 * genuinely different questions on a two-species model — the slow species is
484 * usually the one that has converged and the fast one the one that has not.
485 */
486 #updateRowStats(): void {
487 const species = this.#opts.model.species;
488 const ref = this.#rows[this.#opts.reference];
489 for (const r of this.#rows) {
490 const per = species
491 .map((s, k) => `${s} ${Number.isFinite(r.err[k]) ? r.err[k].toExponential(2) : '—'}`)
492 .join('<br>');
493 // Divergence is said, not implied. Scaled to a healthy row, a blown-up
494 // variant is a flat saturated panel, which on its own is easy to misread
495 // as a converged uniform state.
496 const body = !r.healthy
497 ? '<b class="cmp-diverged">diverged</b>'
498 : r === ref
499 ? '<b>reference</b>'
500 : ${per}`;
501 r.statEl.innerHTML = `${r.session.steps.toLocaleString()} steps<br>${body}`;
502 }
503 }
505 #status(): void {
506 this.#opts.onStatus(
507 `<b>t = ${this.#t.toFixed(2)}</b> (same for every variant) · ` +
508 (this.#frameMs > 0 ? `${this.#frameMs.toFixed(1)} ms/frame · ` : '') +
509 this.#note,
510 );
511 }
513 #observeResize(): void {
514 const scenes = this.#rows.flatMap((r) => r.scenes);
515 this.#resizeObs = new ResizeObserver(() => {
516 for (const s of scenes) {
517 const box = s.canvas.parentElement;
518 if (box) s.resize(box.clientWidth, box.clientHeight);
519 }
520 });
521 for (const s of scenes) {
522 const box = s.canvas.parentElement;
523 if (box) this.#resizeObs.observe(box);
524 }
525 }
527 // -------------------------------------------------------------- the clock
528 /**
529 * One frame advances every variant by the *same model time*: `frameSteps`
530 * base steps, which a ÷K variant covers in K times as many of its own. That
531 * is the whole reason dt varies by an integer divisor — the alternative is
532 * rounding each variant to the nearest step and comparing fields that are a
533 * fraction of a timestep apart, which would show up as a difference and be
534 * indistinguishable from a real one.
535 */
536 async #pump(): Promise<void> {
537 if (this.#pumping) return;
538 this.#pumping = true;
539 try {
540 while (this.#running && !this.#disposed) {
541 const t0 = performance.now();
542 for (const r of this.#rows) r.session.step(this.#frameSteps * r.variant.dtDiv);
543 this.#t += this.#frameSteps * CompareRun.baseDt(this.#opts.params);
544 await this.draw();
545 if (this.#disposed) break;
546 const dt = performance.now() - t0;
547 this.#frameMs = this.#frameMs === 0 ? dt : this.#frameMs + 0.05 * (dt - this.#frameMs);
548 this.#status();
549 await nextFrame();
550 }
551 if (!this.#disposed) {
552 await this.draw();
553 this.#status();
554 }
555 } finally {
556 this.#pumping = false;
557 }
558 }
561const nextFrame = (): Promise<number> => new Promise(requestAnimationFrame);
563/** Whether every entry is an ordinary number — false once a variant has left
564 * its convergence radius and saturated to infinity or NaN. */
565function allFinite(f: Float32Array | undefined): boolean {
566 if (!f) return false;
567 for (let i = 0; i < f.length; i++) if (!Number.isFinite(f[i])) return false;
568 return true;
571type Bounds = { lo: number; hi: number };
573/** How far a field reaches from zero — the one number the rows are ranked by
574 * when deciding which of them sets a column's scale. */
575const peak = (b: Bounds): number => Math.max(Math.abs(b.lo), Math.abs(b.hi));
577/** Whichever of the given bounds reaches least far from zero; null if none. */
578function leastPeak(all: (Bounds | null)[]): Bounds | null {
579 let best: Bounds | null = null;
580 for (const b of all) {
581 if (b !== null && (best === null || peak(b) < peak(best))) best = b;
582 }
583 return best;
586/** Min and max over the finite entries only; null when there are none. */
587function finiteRange(f: Float32Array | undefined): { lo: number; hi: number } | null {
588 if (!f) return null;
589 let lo = Infinity;
590 let hi = -Infinity;
591 for (let i = 0; i < f.length; i++) {
592 const v = f[i];
593 if (!Number.isFinite(v)) continue;
594 if (v < lo) lo = v;
595 if (v > hi) hi = v;
596 }
597 return lo <= hi ? { lo, hi } : null;
600/**
601 * The DOM: a header row naming each species and carrying that column's shared
602 * color range, then one row per variant. The colorbar is per *column* rather
603 * than per panel because the range is shared — a bar on every panel would be
604 * the same bar repeated, and would suggest each panel had its own scaling,
605 * which is exactly the thing that would make the comparison a lie.
606 */
607async function buildGrid(
608 opts: CompareOptions,
609 sessions: ModelSession[],
610 topo: SphereMeshTopology,
611 showDt: boolean,
612): Promise<{ rows: Row[]; rangeBars: { fill: (lo: number, hi: number) => void }[] }> {
613 const { container, model } = opts;
614 container.replaceChildren();
615 container.classList.add('compare');
617 const head = document.createElement('div');
618 head.className = 'cmp-row cmp-head';
619 const headSpacer = document.createElement('div');
620 headSpacer.className = 'cmp-rowlabel';
621 const headCols = document.createElement('div');
622 headCols.className = 'cmp-cols';
623 head.append(headSpacer, headCols);
624 container.append(head);
626 const rangeBars = model.species.map((name) => {
627 const col = document.createElement('div');
628 col.className = 'cmp-colhead';
629 const tag = document.createElement('b');
630 tag.textContent = name;
631 const canvas = document.createElement('canvas');
632 canvas.width = 160;
633 canvas.height = 8;
634 canvas.className = 'cmp-rangebar';
635 const lab = document.createElement('span');
636 lab.className = 'cmp-rangelab';
637 col.append(tag, canvas, lab);
638 headCols.append(col);
639 let painted = false;
640 return {
641 fill: (lo: number, hi: number): void => {
642 const ctx = canvas.getContext('2d');
643 if (ctx && !painted) {
644 painted = true;
645 const cmap = colormaps[opts.colormapName()] ?? colormaps.viridis;
646 for (let x = 0; x < canvas.width; x++) {
647 const [r, g, b] = cmap(x / (canvas.width - 1));
648 ctx.fillStyle = `rgb(${r},${g},${b})`;
649 ctx.fillRect(x, 0, 1, canvas.height);
650 }
651 }
652 lab.textContent = `${fmtValue(lo)}${fmtValue(hi)}`;
653 },
654 };
655 });
657 const sphereBg = getComputedStyle(document.documentElement)
658 .getPropertyValue('--sphere-bg')
659 .trim();
661 const rows: Row[] = [];
662 for (let i = 0; i < sessions.length; i++) {
663 const session = sessions[i];
664 const variant = opts.variants[i];
665 const color = VARIANT_COLORS[i % VARIANT_COLORS.length];
667 const coords = await session.renderPositions();
668 const posBuf = new Float32Array(topo.numVertices * 3);
669 fillPositions(posBuf, coords, topo, opts.morph);
671 const rowEl = document.createElement('div');
672 rowEl.className = 'cmp-row';
673 const labelEl = document.createElement('div');
674 labelEl.className = 'cmp-rowlabel';
675 labelEl.style.setProperty('--c', color);
676 const nameEl = document.createElement('div');
677 nameEl.className = 'cmp-rowname';
678 nameEl.textContent = variantLabel(variant, showDt);
679 const statEl = document.createElement('div');
680 statEl.className = 'cmp-rowstat';
681 labelEl.append(nameEl, statEl);
682 const colsEl = document.createElement('div');
683 colsEl.className = 'cmp-cols';
684 rowEl.append(labelEl, colsEl);
685 container.append(rowEl);
687 const scenes: SphereScene[] = [];
688 const valueBufs: Float32Array[] = [];
689 const colorBufs: Float32Array[] = [];
690 for (let k = 0; k < model.species.length; k++) {
691 const box = document.createElement('div');
692 box.className = 'sphere-box cmp-box';
693 colsEl.append(box);
694 const scene = new SphereScene(
695 box,
696 topo.numVertices,
697 topo.indices,
698 Float32Array.from(posBuf),
699 sphereBg || undefined,
700 );
701 scene.fitCamera();
702 scenes.push(scene);
703 valueBufs.push(new Float32Array(topo.numVertices));
704 colorBufs.push(new Float32Array(topo.numVertices * 3));
705 }
707 rows.push({
708 variant, session, color, coords, posBuf, scenes, valueBufs, colorBufs,
709 fields: [], err: model.species.map(() => 0), healthy: true, statEl,
710 });
711 }
713 // Every panel shares one camera: the study is about the fields, and looking
714 // at two of them from different angles is not comparing them.
715 const all = rows.flatMap((r) => r.scenes);
716 for (let i = 1; i < all.length; i++) all[0].syncCamerasWith(all[i]);
718 return { rows, rangeBars };