/ concept-collection / turing-surface
Sign in
concept-collection / turing-surface
721 lines · 27.2 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';
43import { fmtValue } 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 if (range.hi - range.lo < 1e-9) {
429 const mid = (range.hi + range.lo) / 2;
430 range.lo = mid - 5e-10;
431 range.hi = mid + 5e-10;
432 }
433 this.#rangeBars[k]?.fill(range.lo, range.hi);
434 for (const r of this.#rows) {
435 fillFieldValues(r.valueBufs[k], r.fields[k], this.#topo);
436 fillColors(r.colorBufs[k], r.valueBufs[k], range.lo, range.hi, cmap);
437 r.scenes[k]?.updateColors(r.colorBufs[k]);
438 }
439 }
441 this.#measureDifference();
442 this.#updateRowStats();
443 }
445 /**
446 * Relative L2 difference from the reference, per species, on the shared
447 * grid. Weighted by the Gauss weights, so it is the norm on the parameter
448 * sphere — not on the embedded surface, which would weight by the area
449 * element. That makes it a consistent diagnostic across variants rather than
450 * a physical quantity, which is all it is used for.
451 */
452 #measureDifference(): void {
453 const ref = this.#rows[this.#opts.reference];
454 if (!ref) return;
455 const species = this.#opts.model.species;
456 for (const r of this.#rows) {
457 for (let k = 0; k < species.length; k++) {
458 if (r === ref) {
459 r.err[k] = 0;
460 continue;
461 }
462 const a = r.fields[k];
463 const b = ref.fields[k];
464 if (!a || !b || a.length !== b.length) {
465 r.err[k] = NaN;
466 continue;
467 }
468 let num = 0;
469 let den = 0;
470 for (let i = 0; i < a.length; i++) {
471 const w = this.#weights[i];
472 const d = a[i] - b[i];
473 num += w * d * d;
474 den += w * b[i] * b[i];
475 }
476 r.err[k] = den > 0 ? Math.sqrt(num / den) : NaN;
477 }
478 }
479 }
481 /**
482 * Each row's standing line: how many of its own steps it took to reach the
483 * common time, and how far it is from the reference right now, per species.
484 * Per species rather than a single worst-case number because the two are
485 * genuinely different questions on a two-species model — the slow species is
486 * usually the one that has converged and the fast one the one that has not.
487 */
488 #updateRowStats(): void {
489 const species = this.#opts.model.species;
490 const ref = this.#rows[this.#opts.reference];
491 for (const r of this.#rows) {
492 const per = species
493 .map((s, k) => `${s} ${Number.isFinite(r.err[k]) ? r.err[k].toExponential(2) : '—'}`)
494 .join('<br>');
495 // Divergence is said, not implied. Scaled to a healthy row, a blown-up
496 // variant is a flat saturated panel, which on its own is easy to misread
497 // as a converged uniform state.
498 const body = !r.healthy
499 ? '<b class="cmp-diverged">diverged</b>'
500 : r === ref
501 ? '<b>reference</b>'
502 : ${per}`;
503 r.statEl.innerHTML = `${r.session.steps.toLocaleString()} steps<br>${body}`;
504 }
505 }
507 #status(): void {
508 this.#opts.onStatus(
509 `<b>t = ${this.#t.toFixed(2)}</b> (same for every variant) · ` +
510 (this.#frameMs > 0 ? `${this.#frameMs.toFixed(1)} ms/frame · ` : '') +
511 this.#note,
512 );
513 }
515 #observeResize(): void {
516 const scenes = this.#rows.flatMap((r) => r.scenes);
517 this.#resizeObs = new ResizeObserver(() => {
518 for (const s of scenes) {
519 const box = s.canvas.parentElement;
520 if (box) s.resize(box.clientWidth, box.clientHeight);
521 }
522 });
523 for (const s of scenes) {
524 const box = s.canvas.parentElement;
525 if (box) this.#resizeObs.observe(box);
526 }
527 }
529 // -------------------------------------------------------------- the clock
530 /**
531 * One frame advances every variant by the *same model time*: `frameSteps`
532 * base steps, which a ÷K variant covers in K times as many of its own. That
533 * is the whole reason dt varies by an integer divisor — the alternative is
534 * rounding each variant to the nearest step and comparing fields that are a
535 * fraction of a timestep apart, which would show up as a difference and be
536 * indistinguishable from a real one.
537 */
538 async #pump(): Promise<void> {
539 if (this.#pumping) return;
540 this.#pumping = true;
541 try {
542 while (this.#running && !this.#disposed) {
543 const t0 = performance.now();
544 for (const r of this.#rows) r.session.step(this.#frameSteps * r.variant.dtDiv);
545 this.#t += this.#frameSteps * CompareRun.baseDt(this.#opts.params);
546 await this.draw();
547 if (this.#disposed) break;
548 const dt = performance.now() - t0;
549 this.#frameMs = this.#frameMs === 0 ? dt : this.#frameMs + 0.05 * (dt - this.#frameMs);
550 this.#status();
551 await nextFrame();
552 }
553 if (!this.#disposed) {
554 await this.draw();
555 this.#status();
556 }
557 } finally {
558 this.#pumping = false;
559 }
560 }
563const nextFrame = (): Promise<number> => new Promise(requestAnimationFrame);
565/** Whether every entry is an ordinary number — false once a variant has left
566 * its convergence radius and saturated to infinity or NaN. */
567function allFinite(f: Float32Array | undefined): boolean {
568 if (!f) return false;
569 for (let i = 0; i < f.length; i++) if (!Number.isFinite(f[i])) return false;
570 return true;
573type Bounds = { lo: number; hi: number };
575/** How far a field reaches from zero — the one number the rows are ranked by
576 * when deciding which of them sets a column's scale. */
577const peak = (b: Bounds): number => Math.max(Math.abs(b.lo), Math.abs(b.hi));
579/** Whichever of the given bounds reaches least far from zero; null if none. */
580function leastPeak(all: (Bounds | null)[]): Bounds | null {
581 let best: Bounds | null = null;
582 for (const b of all) {
583 if (b !== null && (best === null || peak(b) < peak(best))) best = b;
584 }
585 return best;
588/** Min and max over the finite entries only; null when there are none. */
589function finiteRange(f: Float32Array | undefined): { lo: number; hi: number } | null {
590 if (!f) return null;
591 let lo = Infinity;
592 let hi = -Infinity;
593 for (let i = 0; i < f.length; i++) {
594 const v = f[i];
595 if (!Number.isFinite(v)) continue;
596 if (v < lo) lo = v;
597 if (v > hi) hi = v;
598 }
599 return lo <= hi ? { lo, hi } : null;
602/**
603 * The DOM: a header row naming each species and carrying that column's shared
604 * color range, then one row per variant. The colorbar is per *column* rather
605 * than per panel because the range is shared — a bar on every panel would be
606 * the same bar repeated, and would suggest each panel had its own scaling,
607 * which is exactly the thing that would make the comparison a lie.
608 */
609async function buildGrid(
610 opts: CompareOptions,
611 sessions: ModelSession[],
612 topo: SphereMeshTopology,
613 showDt: boolean,
614): Promise<{ rows: Row[]; rangeBars: { fill: (lo: number, hi: number) => void }[] }> {
615 const { container, model } = opts;
616 container.replaceChildren();
617 container.classList.add('compare');
619 const head = document.createElement('div');
620 head.className = 'cmp-row cmp-head';
621 const headSpacer = document.createElement('div');
622 headSpacer.className = 'cmp-rowlabel';
623 const headCols = document.createElement('div');
624 headCols.className = 'cmp-cols';
625 head.append(headSpacer, headCols);
626 container.append(head);
628 const rangeBars = model.species.map((name) => {
629 const col = document.createElement('div');
630 col.className = 'cmp-colhead';
631 const tag = document.createElement('b');
632 tag.textContent = name;
633 const canvas = document.createElement('canvas');
634 canvas.width = 160;
635 canvas.height = 8;
636 canvas.className = 'cmp-rangebar';
637 const lab = document.createElement('span');
638 lab.className = 'cmp-rangelab';
639 col.append(tag, canvas, lab);
640 headCols.append(col);
641 let painted = false;
642 return {
643 fill: (lo: number, hi: number): void => {
644 const ctx = canvas.getContext('2d');
645 if (ctx && !painted) {
646 painted = true;
647 const cmap = colormaps[opts.colormapName()] ?? colormaps.viridis;
648 for (let x = 0; x < canvas.width; x++) {
649 const [r, g, b] = cmap(x / (canvas.width - 1));
650 ctx.fillStyle = `rgb(${r},${g},${b})`;
651 ctx.fillRect(x, 0, 1, canvas.height);
652 }
653 }
654 lab.textContent = `${fmtValue(lo)}${fmtValue(hi)}`;
655 },
656 };
657 });
659 const sphereBg = getComputedStyle(document.documentElement)
660 .getPropertyValue('--sphere-bg')
661 .trim();
663 const rows: Row[] = [];
664 for (let i = 0; i < sessions.length; i++) {
665 const session = sessions[i];
666 const variant = opts.variants[i];
667 const color = VARIANT_COLORS[i % VARIANT_COLORS.length];
669 const coords = await session.renderPositions();
670 const posBuf = new Float32Array(topo.numVertices * 3);
671 fillPositions(posBuf, coords, topo, opts.morph);
673 const rowEl = document.createElement('div');
674 rowEl.className = 'cmp-row';
675 const labelEl = document.createElement('div');
676 labelEl.className = 'cmp-rowlabel';
677 labelEl.style.setProperty('--c', color);
678 const nameEl = document.createElement('div');
679 nameEl.className = 'cmp-rowname';
680 nameEl.textContent = variantLabel(variant, showDt);
681 const statEl = document.createElement('div');
682 statEl.className = 'cmp-rowstat';
683 labelEl.append(nameEl, statEl);
684 const colsEl = document.createElement('div');
685 colsEl.className = 'cmp-cols';
686 rowEl.append(labelEl, colsEl);
687 container.append(rowEl);
689 const scenes: SphereScene[] = [];
690 const valueBufs: Float32Array[] = [];
691 const colorBufs: Float32Array[] = [];
692 for (let k = 0; k < model.species.length; k++) {
693 const box = document.createElement('div');
694 box.className = 'sphere-box cmp-box';
695 colsEl.append(box);
696 const scene = new SphereScene(
697 box,
698 topo.numVertices,
699 topo.indices,
700 Float32Array.from(posBuf),
701 sphereBg || undefined,
702 );
703 scene.fitCamera();
704 scenes.push(scene);
705 valueBufs.push(new Float32Array(topo.numVertices));
706 colorBufs.push(new Float32Array(topo.numVertices * 3));
707 }
709 rows.push({
710 variant, session, color, coords, posBuf, scenes, valueBufs, colorBufs,
711 fields: [], err: model.species.map(() => 0), healthy: true, statEl,
712 });
713 }
715 // Every panel shares one camera: the study is about the fields, and looking
716 // at two of them from different angles is not comparing them.
717 const all = rows.flatMap((r) => r.scenes);
718 for (let i = 1; i < all.length; i++) all[0].syncCamerasWith(all[i]);
720 return { rows, rangeBars };
moveopenescclose