// verify.mjs: checks for /strata/invisible-exactly-in-focus/.
// Run: node research/invisible-exactly-in-focus/verify.mjs
//
// Imports the page's own engine (public/strata/invisible-exactly-in-focus/engine.mjs) and holds
// it against things computed another way: a plain DFT, closed-form images of a phase grating
// written out from Bessel functions, the transport-of-intensity equation, three exact symmetry
// theorems about which images cannot tell a bump from a dent, and the numbers in Zernike's
// 1953 Nobel lecture. Then it reads the page's printed numbers back out of its HTML and
// recomputes each one. No network needed.
//
// ENGINE=<path> swaps in another engine file; mutate.mjs uses that to show a broken engine
// makes this fail.

import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import * as PageEngine from '../../public/strata/invisible-exactly-in-focus/engine.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const E = process.env.ENGINE ? await import(pathToFileURL(process.env.ENGINE).href) : PageEngine;
const N = E.N;
const LAM = 0.55;
const RING = 0.55 * 0.65;                                           // the page's ring at its default aperture

let pass = 0, fail = 0;
const lines = [];
function ok(name, cond, detail = '') {
  cond ? pass++ : fail++;
  lines.push(`${cond ? 'PASS' : 'FAIL'}  ${name}${detail ? '  :  ' + detail : ''}`);
}
const head = (t) => lines.push('', `-- ${t}`);
const fx = (v, d = 3) => Number(v).toFixed(d);
const maxDiff = (a, b) => { let m = 0; for (let k = 0; k < a.length; k++) m = Math.max(m, Math.abs(a[k] - b[k])); return m; };
const negate = (sp) => E.finish({ ...sp, phi: sp.phi.map((v) => -v), Tre: undefined, Tim: undefined });

// Bessel functions by their power series (fine for the small arguments used here).
function J(n, x) {
  let s = 0, term = Math.pow(x / 2, n);
  for (let k = 1; k <= n; k++) term /= k;
  for (let k = 0; k < 60; k++) { s += term; term *= -(x * x / 4) / ((k + 1) * (k + 1 + n)); }
  return s;
}

// The shared measurements the page prints; computed once, checked, and compared with the page.
const printed = {};

// ---------------------------------------------------------------------------
head('1. The transform');
{
  let seed = 3; const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647) - 0.5;
  const n = 64, re = new Float64Array(n), im = new Float64Array(n);
  for (let i = 0; i < n; i++) { re[i] = rnd(); im[i] = rnd(); }
  const dr = new Float64Array(n), di = new Float64Array(n);
  for (let k = 0; k < n; k++) for (let j = 0; j < n; j++) {
    const a = (-2 * Math.PI * k * j) / n;
    dr[k] += re[j] * Math.cos(a) - im[j] * Math.sin(a);
    di[k] += re[j] * Math.sin(a) + im[j] * Math.cos(a);
  }
  const fr = Float64Array.from(re), fi = Float64Array.from(im);
  E.fft1(fr, fi, false);
  ok('1-D FFT equals the DFT sum (n = 64, random complex input)', Math.max(maxDiff(fr, dr), maxDiff(fi, di)) < 1e-10, maxDiff(fr, dr).toExponential(1));
  const R = new Float64Array(N * N), I = new Float64Array(N * N);
  for (let k = 0; k < N * N; k++) { R[k] = rnd(); I[k] = rnd(); }
  const R0 = Float64Array.from(R), I0 = Float64Array.from(I);
  E.fft2(R, I, N, false); E.fft2(R, I, N, true);
  ok('2-D forward then inverse returns the input (256 x 256)', Math.max(maxDiff(R, R0), maxDiff(I, I0)) < 1e-12, maxDiff(R, R0).toExponential(1));
}

// ---------------------------------------------------------------------------
head('2. Lummer\'s ideal case: a perfect, unlimited lens shows a transparent object as nothing');
{
  const c = E.cells({ lambda: LAM });
  const b = c.L / LAM;
  const NAall = (Math.SQRT2 * (N / 2)) / b + 0.01;                  // a pupil that keeps every bin
  const { I, pupilBins } = E.image(c, { lambda: LAM, NA: NAall });
  let dev = 0; for (const v of I) dev = Math.max(dev, Math.abs(v - 1));
  ok('every one of the 65,536 pixels of the drawn cells comes out at exactly the background', pupilBins === N * N && dev < 1e-12, `${pupilBins} beams kept, largest deviation ${dev.toExponential(1)}`);
  let mx = 0; for (const v of c.phi) mx = Math.max(mx, v);
  ok('... although the light through the thickest part is delayed by more than a tenth of a period', mx > 0.1 * 2 * Math.PI, `${fx(mx, 2)} rad = ${fx(mx / (2 * Math.PI), 2)} of a period`);
  printed.maxPhase = mx;
}

// ---------------------------------------------------------------------------
head('3. A real lens: what little shows is what the aperture threw away, and a better lens shows less');
{
  const c = E.cells({ lambda: LAM });
  const NAs = [0.1, 0.25, 0.4, 0.65, 0.95];
  const r = NAs.map((NA) => { const { I } = E.image(c, { lambda: LAM, NA }); return E.rmsAll(I, 1); });
  printed.bfByNA = r;
  ok('rms contrast of the in-focus brightfield image falls every time the aperture opens (point light)', r.every((v, i) => i === 0 || v < r[i - 1]), NAs.map((n, i) => `NA ${n}: ${fx(r[i] * 100, 2)}%`).join(', '));
  ok('at NA 0.95 the whole field varies by less than 1% rms', r[4] < 0.01, fx(r[4] * 100, 2) + '%');
  const cOpen = E.image(c, { lambda: LAM, NA: 0.65, source: { type: 'disc', sigma: 0.7 } });
  const cShut = E.image(c, { lambda: LAM, NA: 0.65, source: { type: 'disc', sigma: 0.2 } });
  const o = E.rmsAll(cOpen.I, 1), s = E.rmsAll(cShut.I, 1);
  printed.condenser = [o, s];
  ok('closing the condenser diaphragm (sigma 0.7 to 0.2) raises it, as microscopists were taught', s > o, `${fx(o * 100, 2)}% to ${fx(s * 100, 2)}%`);
}

// ---------------------------------------------------------------------------
head('4. Zernike\'s stripes: a phase grating is invisible exactly in focus, and appears either side');
{
  const eps = 0.05, d = 3;
  const g = E.phaseGrating({ d, eps });
  const opts = { lambda: LAM, NA: 0.3 };
  const k = Math.round(g.L / g.d), half = N / (2 * k);
  const amp = (z) => { const { I } = E.image(g, { ...opts, z }); return (I[N * 7] - I[N * 7 + half]) / 2; };
  const a0 = amp(0);
  ok('in exact focus the grating\'s image has no stripes at all', Math.abs(a0) < 1e-12, `fringe amplitude ${a0.toExponential(1)}`);
  // closed form: orders 0 and +-1 only (NA 0.3 keeps 1/d = 0.33/um, i.e. NA 0.18, and not 2/d, NA 0.37)
  let worst = 0;
  for (const z of [-20, -7, 3, 5, 11, 14, 22]) {
    const del = E.talbotDelta(z, g.d, LAM);
    // field = J0 + 2 i J1 cos(kx) e^{-i del}; (crest - trough) / 2 = 4 J0 J1 sin(del)
    const want = 4 * J(0, eps) * J(1, eps) * Math.sin(del);
    worst = Math.max(worst, Math.abs(amp(z) - want));
  }
  ok('defocused, the stripes match the Bessel-function closed form at seven focus settings', worst < 1e-12, `max error ${worst.toExponential(1)}`);
  const dz = E.vanishSpacing(g.d, LAM);
  printed.vanish = dz; printed.parax = (g.d * g.d) / LAM;
  const a1 = amp(dz), a2 = amp(2 * dz), aHalf = amp(dz / 2), aNeg = amp(-dz / 2);
  ok(`they vanish again every ${fx(dz, 2)} um of focus`, Math.abs(a1) < 1e-12 && Math.abs(a2) < 1e-12, `${a1.toExponential(1)}, ${a2.toExponential(1)}`);
  ok('... which is d^2 / lambda to within 1% (the paraxial Talbot spacing)', Math.abs(dz / printed.parax - 1) < 0.01, `${fx(dz, 3)} vs ${fx(printed.parax, 3)}`);
  ok('half way between they are strongest, and opposite in sign either side of focus', aHalf > 0.09 && Math.abs(aHalf + aNeg) < 1e-12, `${fx(aHalf, 4)} and ${fx(aNeg, 4)} (2 eps = ${2 * eps})`);
}

// ---------------------------------------------------------------------------
head('5. The fine adjustment: a little defocus shows the curvature of the phase (transport of intensity)');
{
  // A smooth weak specimen: ripples, scaled to 0.05 rad, looked at with a pupil that keeps them all.
  const r = E.ripples({ opd: 0.05 / (2 * Math.PI) });
  const z = 0.4;
  const { I } = E.image(r, { lambda: LAM, NA: 0.95, z });
  // -(lambda z / 2 pi) laplacian(phi), computed spectrally from phi itself
  const re = Float64Array.from(r.phi), im = new Float64Array(N * N);
  E.fft2(re, im, N, false);
  for (let k = 0; k < N * N; k++) {
    const fx_ = E.fb(k % N) / r.L, fy_ = E.fb(Math.floor(k / N)) / r.L;
    const lap = -4 * Math.PI * Math.PI * (fx_ * fx_ + fy_ * fy_);
    re[k] *= (-LAM * z / (2 * Math.PI)) * lap; im[k] *= (-LAM * z / (2 * Math.PI)) * lap;
  }
  E.fft2(re, im, N, true);
  let num = 0, den = 0;
  for (let k = 0; k < N * N; k++) { num += (I[k] - 1 - re[k]) ** 2; den += re[k] ** 2; }
  const relErr = Math.sqrt(num / den);
  printed.tie = relErr;
  ok('I - 1 = -(lambda z / 2 pi) laplacian(phi), to within 5% rms', relErr < 0.05, `relative rms error ${fx(relErr * 100, 2)}%`);
}

// ---------------------------------------------------------------------------
head('6. Three images that cannot tell a bump from a dent, and one that can');
{
  const p = E.pitAndPlateau({ phi0: 0.3 });
  const q = negate(p);
  const base = { lambda: LAM, NA: 0.65, source: { type: 'ring', r: RING } };
  const bfA = E.image(p, base).I, bfB = E.image(q, base).I;
  ok('in-focus brightfield: the slide and its exact opposite give the same image', maxDiff(bfA, bfB) < 1e-12, maxDiff(bfA, bfB).toExponential(1));
  const df = { ...base, plate: { region: 'ring', r: RING, w: 0.03, a: 0, theta: 0 } };
  const dfA = E.image(p, df).I, dfB = E.image(q, df).I;
  ok('dark field: the same, to the last digit', maxDiff(dfA, dfB) < 1e-12, maxDiff(dfA, dfB).toExponential(1));
  const zA = E.image(p, { ...base, z: 2 }).I, zB = E.image(q, { ...base, z: -2 }).I;
  ok('defocused: a bump 2 um above focus looks exactly like a dent 2 um below it', maxDiff(zA, zB) < 1e-12, maxDiff(zA, zB).toExponential(1));
  const zC = E.image(q, { ...base, z: 2 }).I;
  ok('... but not like a dent at the same focus (so focus direction carries the sign)', maxDiff(zA, zC) > 0.05, fx(maxDiff(zA, zC), 3));
  const ph = { ...base, plate: { region: 'ring', r: RING, w: 0.03, a: 0.5, theta: 90 } };
  const I = E.image(p, ph).I, bg = E.background(p, ph);
  const up = E.measure(I, bg, p.mask, 1), down = E.measure(I, bg, p.mask, 2);
  ok('phase contrast: the plateau comes out darker than the glass, the pit brighter', up.mean < -0.1 && down.mean > 0.1, `plateau ${fx(up.mean * 100, 1)}%, pit ${fx(down.mean * 100, 1)}%`);
  const dfm1 = E.measure(dfA, 0, p.mask, 1), dfm2 = E.measure(dfA, 0, p.mask, 2);
  printed.signTest = { plateau: up.mean, pit: down.mean, dfPlateau: dfm1.mean, dfPit: dfm2.mean };
  ok('in dark field the two squares carry the same light', Math.abs(dfm1.mean - dfm2.mean) < 1e-12, `${dfm1.mean.toExponential(3)} and ${dfm2.mean.toExponential(3)}`);
}

// ---------------------------------------------------------------------------
head('7. The quarter period: Zernike\'s strip against the closed form');
{
  // A phase grating with only orders 0 and +-1 inside the aperture, a point source, and a small
  // disc plate over the zeroth order: the image is exactly |a e^{-i th} J0 + 2 i J1 cos kx|^2.
  const eps = 0.2, g = E.phaseGrating({ d: 3, eps });
  const k = Math.round(g.L / g.d);
  let worst = 0;
  for (const a of [1, 0.5, 0.2]) for (const th of [0, 45, 90, 180, 270]) {
    const { I } = E.image(g, { lambda: LAM, NA: 0.2, plate: { region: 'disc', r: 0.02, a, theta: th } });
    const t = (th * Math.PI) / 180;
    for (const x of [0, 5, 16, 33]) {
      const c = Math.cos((2 * Math.PI * k * x) / N);
      const re = a * Math.cos(-t) * J(0, eps), im = a * Math.sin(-t) * J(0, eps) + 2 * J(1, eps) * c;
      worst = Math.max(worst, Math.abs(I[N * 3 + x] - (re * re + im * im)));
    }
  }
  ok('engine = closed form for 3 plate transmissions x 5 plate phases x 4 points', worst < 1e-12, `max error ${worst.toExponential(1)}`);
  // retarded crest (x = 0, phi = +eps) under an advancing strip: darker, as Zernike says
  const at = (a, th) => { const { I } = E.image(g, { lambda: LAM, NA: 0.2, plate: { region: 'disc', r: 0.02, a, theta: th } }); return { crest: I[0] / (a * a), bg: 1 }; };
  ok('the retarded crest under a strip that advances the direct light by 90 degrees is darker ("darker than the background")', at(1, 90).crest < 1, fx(at(1, 90).crest, 4));
  ok('retard the direct light instead (theta = -90) and the same crest is brighter', at(1, -90).crest > 1, fx(at(1, -90).crest, 4));
  const c0 = at(1, 0).crest, c180 = at(1, 180).crest;
  ok('with no quarter-period shift (0 or 180 degrees) the crest differs from the background only in second order', Math.abs(c0 - 1) < 0.05 && Math.abs(c180 - 1) < 0.05 && Math.abs(c0 - 1) < 0.2 * Math.abs(at(1, 90).crest - 1), `${fx(c0 - 1, 4)}, ${fx(c180 - 1, 4)} vs ${fx(at(1, 90).crest - 1, 4)}`);
}

// ---------------------------------------------------------------------------
head('8. The absorbing strip: Zernike\'s "doubled", "five times", and Lyot\'s one-thirtieth');
{
  const eps = 0.01, g = E.phaseGrating({ d: 3, eps });
  const contrast = (a) => {
    const o = { lambda: LAM, NA: 0.2, plate: { region: 'disc', r: 0.02, a, theta: 90 } };
    const { I } = E.image(g, o), bg = E.background(g, o);
    const k = Math.round(g.L / g.d);
    return (I[N / (2 * k)] - I[0]) / 2 / bg;                         // half the trough-crest difference, relative
  };
  const c1 = contrast(1), c05 = contrast(0.5), c02 = contrast(0.2), c30 = contrast(1 / 30);
  printed.absorb = { c1, c05, c02, c30 };
  ok('a strip transmitting 25% of the energy (amplitude 1/2) doubles the contrast of a thin detail', Math.abs(c05 / c1 - 2) < 0.02, fx(c05 / c1, 3) + 'x');
  ok('4% transmission (amplitude 1/5) gives five times', Math.abs(c02 / c1 - 5) < 0.1, fx(c02 / c1, 3) + 'x');
  ok('Lyot\'s amplitude of one thirtieth gives about thirty times', Math.abs(c30 / c1 - 30) < 1.5, fx(c30 / c1, 2) + 'x');
  // Lyot 1946 (C. R. 222, p. 767), his own worked example: a mirror defect 2 angstroms deep moves
  // the reflected wave 4 angstroms, "et apparait avec un contraste de 4 pi . 4/5000 = 1 %".
  const lyotSays = (4 * Math.PI * 4) / 5000;
  const gm = E.phaseGrating({ d: 3, eps: (2 * Math.PI * 4) / 5000 });
  const om = { lambda: LAM, NA: 0.2, plate: { region: 'disc', r: 0.02, a: 1, theta: 90 } };
  const Im = E.image(gm, om).I, km = Math.round(gm.L / gm.d);
  const cm = (Im[N / (2 * km)] - Im[0]) / 2;
  printed.lyotMirror = { says: lyotSays, engine: cm, thousand: Math.sqrt(1000) };
  ok('Lyot\'s own arithmetic: 4 pi x 4 / 5000 = 1.005%, and the engine gives a 4-angstrom wave step that contrast', Math.abs(lyotSays - 0.01005) < 1e-5 && Math.abs(cm / lyotSays - 1) < 0.001, `${fx(lyotSays * 100, 3)}% stated, ${fx(cm * 100, 3)}% computed`);
  const g1000 = (() => { const o = { ...om, plate: { ...om.plate, a: Math.sqrt(0.001) } }; const I1 = E.image(gm, o).I; return (I1[N / (2 * km)] - I1[0]) / 2 / 0.001; })();
  ok('his first plates weakened the direct light "un millier de fois": sqrt(1000) = 31.6 times the contrast', Math.abs(g1000 / cm - Math.sqrt(1000)) < 0.1, fx(g1000 / cm, 2) + 'x');
  // Lyot's ripples: a thousandth of a wavelength of path is 2 pi / 1000 rad
  const rp = E.ripples({ opd: 0.001 });
  const rim = (a) => { const o = { lambda: LAM, NA: 0.4, plate: { region: 'disc', r: 0.02, a, theta: 90 } }; const { I } = E.image(rp, o); const bg = E.background(rp, o); let lo = Infinity, hi = -Infinity; for (const v of I) { lo = Math.min(lo, v / bg); hi = Math.max(hi, v / bg); } return [lo, hi]; };
  const [l1, h1] = rim(1), [l30, h30] = rim(1 / 30);
  const bfr = E.image(rp, { lambda: LAM, NA: 0.4 }).I; let bdev = 0; for (const v of bfr) bdev = Math.max(bdev, Math.abs(v - 1));
  printed.lyot = { bf: bdev, full: [l1, h1], lyot: [l30, h30] };
  ok('ripples of a thousandth of a wavelength: brightfield in focus moves no pixel by even 0.01%', bdev < 1e-4, `largest change ${fx(bdev * 100, 5)}%`);
  ok('... a plain quarter-wave strip shows them at about 1%', h1 - l1 > 0.01 && h1 - l1 < 0.04, `range ${fx(l1, 4)} to ${fx(h1, 4)}`);
  ok('... and a strip that also cuts the direct light to 1/30 shows them at tens of per cent ("in good contrast")', h30 - l30 > 0.3, `range ${fx(l30, 3)} to ${fx(h30, 3)} of the background`);
}

// ---------------------------------------------------------------------------
head('9. The halo, and why Zernike made his strips round');
{
  const p = E.pitAndPlateau({ phi0: 0.3 });
  const ringOpts = (w) => ({ lambda: LAM, NA: 0.65, source: { type: 'ring', r: RING }, plate: { region: 'ring', r: RING, w, a: 0.5, theta: 90 } });
  const profile = (w) => {
    const o = ringOpts(w), { I } = E.image(p, o), bg = E.background(p, o);
    const y = N / 2, h = p.L / N, row = [];
    for (let x = 0; x < N; x++) row.push(I[y * N + x] / bg - 1);
    // plateau spans X in [-L/4 - 6, -L/4 + 6]
    const xc = Math.round(N / 2 - (p.L / 4) / h), half = Math.round(6 / h);
    const centre = row[xc], edgeIn = Math.min(...row.slice(xc - half + 1, xc - half + 5));
    const out = Math.max(...row.slice(xc - half - 6, xc - half));
    return { centre, edgeIn, out };
  };
  const w3 = profile(0.03);
  printed.halo = w3;
  ok('outside the dark plateau, the glass comes out brighter than bare glass: the halo', w3.out > 0.05, `peak just outside the edge ${fx(w3.out * 100, 1)}% above background`);
  ok('inside, the middle of the plateau is paler than its rim: the shade-off', Math.abs(w3.centre) < 0.6 * Math.abs(w3.edgeIn), `middle ${fx(w3.centre * 100, 1)}%, just inside the edge ${fx(w3.edgeIn * 100, 1)}%`);
  // straight strip + line source vs ring + ring source, on small particles: the halo's shape
  const pt = E.particles({ phi0: 0.6 });
  const halo2nd = (o) => {
    const { I } = E.image(pt, o), bg = E.background(pt, o);
    const h = pt.L / N, c = N / 2; let sxx = 0, syy = 0;
    for (let y = c - 40; y < c + 40; y++) for (let x = c - 40; x < c + 40; x++) {
      const X = (x - c + 0.5) * h, Y = (y - c + 0.5) * h;
      if (Math.hypot(X, Y) < 1.6) continue;                          // leave out the particle itself
      const v = Math.max(0, I[y * N + x] / bg - 1);                  // the bright halo only
      sxx += v * X * X; syy += v * Y * Y;
    }
    return sxx / syy;
  };
  const strip = halo2nd({ lambda: LAM, NA: 0.65, source: { type: 'line' }, plate: { region: 'strip', w: 0.03, a: 0.5, theta: 90 } });
  const ring = halo2nd(ringOpts(0.03));
  printed.streak = { strip, ring };
  ok('with a straight strip (along y) the halo of a small particle is drawn out across it, along x ("short crossing pencil streaks")', strip > 3, `x-spread / y-spread = ${fx(strip, 2)}`);
  ok('with an annular strip it spreads evenly', Math.abs(Math.log(ring)) < Math.log(1.3), `x-spread / y-spread = ${fx(ring, 2)}`);
}

// ---------------------------------------------------------------------------
head('10. Where "optically stained" stops being true: thick specimens');
{
  // Grating crest minus trough under a quarter-wave strip is -8 a J0(eps) J1(eps) (x 1/2 for amplitude):
  // proportional to eps only while eps is small, largest near eps = 1.08, and reversed past 2.405.
  let best = 0, bestE = 0, zero = 0;
  for (let e = 0.001; e < 3.5; e += 0.001) {
    const v = J(0, e) * J(1, e);
    if (v > best) { best = v; bestE = e; }
    if (!zero && J(0, e) < 0) zero = e;
  }
  printed.thick = { peak: bestE, reverse: zero };
  const amp = (eps) => { const g = E.phaseGrating({ d: 3, eps }); const o = { lambda: LAM, NA: 0.2, plate: { region: 'disc', r: 0.02, a: 1, theta: 90 } }; const { I } = E.image(g, o); const k = Math.round(g.L / g.d); return (I[N / (2 * k)] - I[0]) / 2; };
  ok('the engine agrees: stripe contrast is 4 J0 J1 at eps = 0.5, 1.08, 2.0, 3.0', [0.5, 1.08, 2, 3].every((e) => Math.abs(amp(e) - 4 * J(0, e) * J(1, e)) < 1e-8));
  ok(`contrast stops growing at a swing of ${fx(bestE, 2)} rad`, Math.abs(bestE - 1.08) < 0.01, `${fx(bestE, 3)} rad = ${fx(bestE / (2 * Math.PI), 3)} of a period`);
  ok(`and reverses (crests turn bright) past ${fx(zero, 3)} rad, where J0 = 0`, Math.abs(zero - 2.405) < 0.001 && amp(3) < 0 && amp(2) > 0, `amp(2) = ${fx(amp(2), 3)}, amp(3) = ${fx(amp(3), 3)}`);
  // the drawn cells: nucleus region contrast as the whole drawing is thickened
  const series = [0.25, 0.5, 1, 2, 3].map((s) => {
    const c = E.cells({ lambda: LAM, scale: s });
    const o = { lambda: LAM, NA: 0.65, source: { type: 'ring', r: RING }, plate: { region: 'ring', r: RING, w: 0.03, a: 0.5, theta: 90 } };
    const { I } = E.image(c, o), bg = E.background(c, o);
    return E.measure(I, bg, c.mask, 3).mean;                         // the rounded cell
  });
  printed.roundSeries = series;
  ok('the rounded cell does not get steadily darker as it is drawn thicker', !series.every((v, i) => i === 0 || v < series[i - 1]), series.map((v) => fx(v * 100, 1) + '%').join(', '));
}

// ---------------------------------------------------------------------------
head('11. The drawing\'s stated dimensions');
{
  const c = E.cells({ lambda: LAM });
  let hmax = 0, rodMax = 0, roundMax = 0;
  for (let k = 0; k < N * N; k++) {
    if (c.mask[k] === 1) hmax = Math.max(hmax, c.H[k]);
    if (c.mask[k] === 2) rodMax = Math.max(rodMax, c.H[k]);
    if (c.mask[k] === 3) roundMax = Math.max(roundMax, c.H[k]);
  }
  printed.dims = { hmax, rodMax, roundMax };
  ok('adherent cell: at most 4 um high (lamella 1 um + nucleus dome 3 um)', hmax <= 4.0001 && hmax > 3.8, fx(hmax, 2) + ' um');
  ok('rods: 1 um thick', Math.abs(rodMax - 1) < 0.05, fx(rodMax, 2) + ' um');
  ok('rounded cell: 6 um high', Math.abs(roundMax - 6) < 0.05, fx(roundMax, 2) + ' um');
}

// ---------------------------------------------------------------------------
head('12. The page\'s printed numbers, read back out of its HTML');
{
  const html = readFileSync(join(HERE, '../../public/strata/invisible-exactly-in-focus/index.html'), 'utf8');
  const expect = {
    'bf-na-010': fx(printed.bfByNA[0] * 100, 2), 'bf-na-025': fx(printed.bfByNA[1] * 100, 2), 'bf-na-040': fx(printed.bfByNA[2] * 100, 2),
    'bf-na-065': fx(printed.bfByNA[3] * 100, 2), 'bf-na-095': fx(printed.bfByNA[4] * 100, 2),
    'lyot-mirror': fx(printed.lyotMirror.engine * 100, 3), 'x-1000': fx(printed.lyotMirror.thousand, 1),
    'round-3x': fx(printed.roundSeries[4] * 100, 0), 'round-2x': fx(printed.roundSeries[3] * 100, 0),
    'vanish': fx(printed.vanish, 1), 'parax': fx(printed.parax, 1),
    'max-phase': fx(printed.maxPhase / (2 * Math.PI), 2),
    'x-half': fx(printed.absorb.c05 / printed.absorb.c1, 2), 'x-fifth': fx(printed.absorb.c02 / printed.absorb.c1, 2), 'x-lyot': fx(printed.absorb.c30 / printed.absorb.c1, 1),
    'lyot-full': fx((printed.lyot.full[1] - printed.lyot.full[0]) * 100, 1), 'lyot-30': fx((printed.lyot.lyot[1] - printed.lyot.lyot[0]) * 100, 0),
    'thick-peak': fx(printed.thick.peak, 2), 'thick-rev': fx(printed.thick.reverse, 3),
    'streak-strip': fx(printed.streak.strip, 1), 'streak-ring': fx(printed.streak.ring, 2),
    'halo-out': fx(printed.halo.out * 100, 0), 'tie': fx(printed.tie * 100, 2),
  };
  const found = {};
  for (const m of html.matchAll(/data-v="([a-z0-9-]+)"[^>]*>([^<]*)</g)) found[m[1]] = m[2].trim();
  let bad = [];
  for (const [k, v] of Object.entries(expect)) if (found[k] !== v) bad.push(`${k}: page "${found[k]}" vs computed "${v}"`);
  ok(`all ${Object.keys(expect).length} numbers the page prints (marked data-v) equal the recomputation`, bad.length === 0, bad.join('; '));
  const extra = Object.keys(found).filter((k) => !(k in expect));
  ok('and the page prints no data-v number that this file does not check', extra.length === 0, extra.join(', '));
}

// ---------------------------------------------------------------------------
const out = [`verify.mjs: /strata/invisible-exactly-in-focus/`, ...lines, '', `${pass} passed, ${fail} failed`].join('\n');
console.log(out);
if (process.env.PRINT_NUMBERS) console.log(JSON.stringify(printed, null, 1));
process.exit(fail ? 1 : 0);
