#!/usr/bin/env node
// verify-how-does-a-whispering-gallery-work.mjs: checks /strata/how-does-a-whispering-gallery-work/ ("Heard All the Way Round").
//
//   node verify-how-does-a-whispering-gallery-work.mjs            # geometry, Bessel functions, the wave, the page's prose
//   node verify-how-does-a-whispering-gallery-work.mjs --mutate   # also break the engine on purpose; the checks must go red
//   node verify-how-does-a-whispering-gallery-work.mjs --grids    # also rerun the wave on grids 2, 3 and 4 times finer
//                                                                 # (about twenty minutes; --grids 2 for the first only)
//   ... --write <dir>                                             # keep the finer grids' and the mode sum's numbers as JSON
//
// The page's live grid has 10 cells to a wavelength and its figures are not converged (corrected 2026-10-07). The
// figures the page quotes come from finer grids (section 4b) and from an exact solution with no grid (section 4c).
// Needs only Node 18+. Inside the repository it tests the local files; from an empty directory it downloads
// the page's engine.mjs and index.html from https://artwaste.land into ./how-does-a-whispering-gallery-work-files/
// (the bytes your browser runs). Exit 0 = every check passed. It takes about a minute.

import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { dirname, join, resolve } from 'node:path';

const here = dirname(fileURLToPath(import.meta.url));
const slug = 'how-does-a-whispering-gallery-work';
const MUTATE = process.argv.includes('--mutate');
const gi = process.argv.indexOf('--grids');
const GRIDS = gi < 0 ? [] : (process.argv[gi + 1] && /^[\d,]+$/.test(process.argv[gi + 1]) ? process.argv[gi + 1].split(',').map(Number) : [2, 3, 4]);
const wi = process.argv.indexOf('--write');
const WRITE = wi < 0 ? null : resolve(process.argv[wi + 1]);
if (WRITE) mkdirSync(WRITE, { recursive: true });
let dir = join(here, 'public/strata', slug);
if (!existsSync(join(dir, 'engine.mjs'))) {
  dir = resolve(`${slug}-files`); mkdirSync(dir, { recursive: true });
  for (const f of ['engine.mjs', 'index.html']) {
    const r = await fetch(`https://artwaste.land/strata/${slug}/${f}`);
    if (!r.ok) throw new Error(`could not download ${f}: ${r.status}`);
    writeFileSync(join(dir, f), Buffer.from(await r.arrayBuffer()));
  }
}
console.error(`files: ${dir}`);
const E = await import(pathToFileURL(join(dir, 'engine.mjs')).href);
const html = readFileSync(join(dir, 'index.html'), 'utf8');
const text = html.replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<style[\s\S]*?<\/style>/g, ' ')
  .replace(/<[^>]+>/g, ' ').replace(/&nbsp;/g, ' ').replace(/&middot;/g, '·').replace(/&minus;/g, '−')
  .replace(/&amp;/g, '&').replace(/\s+/g, ' ');

let pass = 0, fail = 0;
function check(name, ok, detail = '') {
  if (ok) pass++; else fail++;
  console.log(`${ok ? 'ok  ' : 'FAIL'} ${name}${detail ? '  (' + detail + ')' : ''}`);
  return ok;
}
const says = (s) => text.includes(s);
const f1 = (x) => x.toFixed(1);

// ------------------------------------------------------------------ 1. rays
{
  const r = E.ellipseFocusTest(1.3, 1, 3600);
  check('ellipse: 3,600 rays from one focus all pass through the other after one bounce', r.worstMiss < 1e-9, `worst miss ${r.worstMiss.toExponential(1)}`);
  check('ellipse: every one of those paths has length 2a', Math.abs(r.maxLen - r.twoA) < 1e-9 && Math.abs(r.minLen - r.twoA) < 1e-9, `${r.minLen} to ${r.maxLen}, 2a = ${r.twoA}`);
  // an independent re-derivation, not the engine: reflect with the focal-bisector property
  // (the normal at P bisects the angle F1-P-F2), so the reflected ray from F1 must point at F2
  let worst = 0;
  const a = 1.3, b = 1, f = Math.sqrt(a * a - b * b);
  for (let i = 0; i < 1000; i++) {
    const t = (2 * Math.PI * i) / 1000, px = a * Math.cos(t), py = b * Math.sin(t);
    const nx = px / (a * a), ny = py / (b * b), nn = Math.hypot(nx, ny);
    let dx = px + f, dy = py; const dl = Math.hypot(dx, dy); dx /= dl; dy /= dl;
    const dn = (dx * nx + dy * ny) / nn; const rx = dx - 2 * dn * nx / nn, ry = dy - 2 * dn * ny / nn;
    const tx = f - px, ty = -py, tl = Math.hypot(tx, ty);
    worst = Math.max(worst, Math.abs(rx * ty / tl - ry * tx / tl));
  }
  check('ellipse, re-derived without the engine: the mirror law at every wall point sends F1 to F2', worst < 1e-12, `worst cross ${worst.toExponential(1)}`);
  for (const al of [5, 10, 30]) {
    const c = E.circleBandTest(1, al, 200);
    const keep = Math.max(...c.angles.map((x) => Math.abs(x - al)));
    check(`circle: a ray leaving the wall at ${al}° meets it at ${al}° on all 200 bounces`, keep < 1e-6, `worst drift ${keep.toExponential(1)}°`);
    check(`circle: and never comes closer to the centre than R cos ${al}°`, Math.abs(c.minR - c.predicted) < 1e-9, `min ${c.minR.toFixed(9)} vs ${c.predicted.toFixed(9)}`);
  }
}

// ------------------------------------------------------------------ 2. Bessel functions
// An independent J_n: Miller's backward recurrence, normalised by J_0 + 2(J_2 + J_4 + ...) = 1.
function millerJ(n, x) {
  const start = 2 * Math.ceil((Math.max(n, x) + 60 + 12 * Math.sqrt(Math.max(n, x))) / 2);
  let jp = 0, j = 1e-300, sum = 0, want = 0;
  for (let k = start; k > 0; k--) {
    const jm = (2 * k / x) * j - jp; jp = j; j = jm;
    if (Math.abs(j) > 1e250) { j *= 1e-250; jp *= 1e-250; sum *= 1e-250; want *= 1e-250; }
    if (k - 1 === n) want = j;
    if ((k - 1) % 2 === 0 && k - 1 > 0) sum += 2 * j;
  }
  sum += j; // J_0
  if (n === 0) want = j;
  return want / sum;
}
{
  let worst = 0;
  for (const [n, x] of [[0, 1], [1, 5], [10, 12.3], [91, 94.2], [300, 305], [600, 610.5], [1000, 1003]]) {
    worst = Math.max(worst, Math.abs(E.besselJ(n, x) - millerJ(n, x)));
  }
  check('Bessel J_n: the engine\'s integral agrees with Miller\'s recurrence (n up to 1000)', worst < 1e-10, `worst ${worst.toExponential(1)}`);
  // first zeros of J_n' printed in Abramowitz and Stegun, Table 9.5 (j'_{n,1}; the table covers n = 0 to 8)
  const table = { 1: 1.84118, 2: 3.05424, 5: 6.41562 };
  let tw = 0;
  for (const [n, z] of Object.entries(table)) tw = Math.max(tw, Math.abs(E.firstZeroJp(Number(n)) - z));
  check('first zeros of J_n\' match the printed table (Abramowitz & Stegun 9.5) to 5 decimals', tw < 6e-6, `worst ${tw.toExponential(1)}`);
  const asym = [100, 500].map((n) => Math.abs(E.firstZeroJp(n) - (n + 0.8086165 * Math.cbrt(n))) / Math.cbrt(n));
  check('and approach the asymptotic n + 0.8086 n^(1/3) for large n', asym.every((x) => x < 0.01), asym.map((x) => x.toExponential(1)).join(', '));
}

// ------------------------------------------------------------------ 3. the band at St Paul's
const R = E.STPAULS.radius;
const band = {};
for (const f of [500, 1000, 2000, 4000]) band[f] = E.whisperBand(R, f);
{
  for (const f of [500, 1000, 2000, 4000]) {
    const b = band[f];
    check(`${f} Hz: the chosen mode resonates within 0.5% of ${f} Hz`, Math.abs(b.fMode - f) / f < 0.005, `n = ${b.n}, ${b.fMode.toFixed(1)} Hz`);
  }
  // Rayleigh's zinc model: a strip about 12 feet long bent into a semicircle (radius 12/pi feet), bird-call wavelength 2 cm
  const rz = E.whisperBand((12 * 0.3048) / Math.PI, E.C_SOUND / 0.02);
  band.rayleighModel = rz;
  check('Rayleigh\'s zinc model: the band holding 90% of the energy is narrower than his 2-inch lath', rz.depth < 0.0508, `band ${(rz.depth * 100).toFixed(1)} cm, lath 5.1 cm`);
  const b250 = E.whisperBand(R, 250);
  check('at 250 Hz the band is still under a metre deep (so a metre out is outside it at every higher pitch)', b250.depth < 1, `${(b250.depth * 100).toFixed(0)} cm`);
  check('St Paul\'s at 1,000 Hz is about 44 wavelengths in radius (the page says so)', Math.round(R / (E.C_SOUND / 1000)) === 44 && says('St Paul\'s at 1,000 Hz is about 44'));
  const ratio = band[500].depth / band[4000].depth, pred = Math.pow(8, 2 / 3);
  check('the band thins as wavelength^(2/3): 500 Hz band / 4,000 Hz band is close to 8^(2/3) = 4', Math.abs(ratio / pred - 1) < 0.1, `ratio ${ratio.toFixed(2)}`);
}

// ------------------------------------------------------------------ 4. the wave, on the page's own grid
// This is the grid the reader's browser runs: 10 cells to a wavelength. Its figures are reported on the page as the
// coarse grid's, beside the converged ones (sections 4b and 4c), because they are not converged.
const { runs, out } = E.standardResults();
const BAND_INSETS = [1, 2, 3, 4, 6, 8, 10, 12, 15, 20, 30];
const halfOf = (prof) => BAND_INSETS.find((x, i) => prof[i] < 0.5 * prof[0]);
{
  check('hard wall: a quarter of the way round, the ear at the wall is louder than the ear in the room by more than 6 dB', out[90].wallVsRoom_hard > 6, `${f1(out[90].wallVsRoom_hard)} dB`);
  check('soft wall (the control): the same two ears differ by less than 1.5 dB', Math.abs(out[90].wallVsRoom_soft) < 1.5, `${f1(out[90].wallVsRoom_soft)} dB`);
  check('hard wall: half way round, the ear at the wall still wins', out[180].wallVsRoom_hard > 3, `${f1(out[180].wallVsRoom_hard)} dB`);
  check('the ear at the wall hears the hard room louder than the soft room, at 90°, 180° and 270°', [90, 180, 270].every((d) => out[d].hardVsSoft_wall > 5), [90, 180, 270].map((d) => f1(out[d].hardVsSoft_wall)).join(', ') + ' dB');
  check('Rayleigh\'s lath (1904): a strip against the wall, 1.2 wavelengths deep, cuts the ear a quarter round by more than 8 dB', out.lath_quarter < -8, `${f1(out.lath_quarter)} dB`);
  check('Rayleigh\'s other obstacle: a screen 4 wavelengths wide across the straight line changes it by less than 1.5 dB', Math.abs(out.screen_quarter) < 1.5, `${f1(out.screen_quarter)} dB`);
  // the band, measured in the wave, against the band computed from Bessel functions
  const w = E.runWhisper({ wall: 'hard', facing: 'along', rings: BAND_INSETS });
  const prof = BAND_INSETS.map((_, i) => E.peakAt(w.ringEars[i], 90));
  const half = halfOf(prof);
  const scaled = E.whisperBand(E.STANDARD.R, E.C_SOUND / E.STANDARD.lambda);
  check('the page prints the model band as measured', says(`half its wall loudness ${half} cells in`) && says(`${scaled.depth.toFixed(1)} cells deep`));
  check('the simulated whisper falls to half its loudness within the Bessel band (90% of energy)', half !== undefined && half <= scaled.depth + 1, `half at ${half} cells; band ${scaled.depth.toFixed(1)} cells`);
  band.sim = { half, depth: scaled.depth, n: scaled.n };
}

// ------------------------------------------------------------------ 4b. the same wave on finer grids (--grids)
// The same room in wavelengths, the same whisper, ears, obstacles and time window, with every length the engine fixes
// in cells (radius, wavelength, the whisperer's inset and the spacing of its two sources, the rings of ears, the lath,
// the screen, the soft wall's sponge) multiplied by k, and the number of steps by k (the Courant number stays 0.5).
// Built from the engine's own exported primitives. Two things the engine does not let a caller scale (placeObstacle's
// LATH and SCREEN, and setupWhisper's source spacing) are restated here with k in them; at k = 1 this must reproduce
// standardResults() exactly, which the first check below asserts.
//
// The finest grid's figures, as the page prints them. Recorded from `--grids` on 2026-10-07 (k = 4 took 673 s on the
// machine that wrote this); a run with --grids recomputes them and must agree.
const FINEST = { k: 4, quarter: 18.2468, half: 12.5363, soft: -0.3555, hardVsSoft: 14.3558, lath: -18.5277, screen: 0.0337, alongVsIn: 0.4581, aheadHard: 14.1044, aheadSoft: 11.0017 };
function gridRun(k, { profile = false } = {}) {
  const S = E.STANDARD;
  const P = { N: S.N * k, R: S.R * k, lambda: S.lambda * k, whisperInset: S.whisperInset * k, rings: S.rings.map((r) => r * k),
    steps: S.steps * k, sep: 3 * k, sponge: 18 * k, LATH: E.LATH * k, SCREEN: E.SCREEN * k };
  function placeObstacle(g, kind, base) {
    const mark = (x, y) => {
      for (const [dx, dy] of [[0, 0], [1, 0], [0, 1], [1, 1]]) {
        const i = Math.round(x) + dx, j = Math.round(y) + dy;
        if (i > 0 && j > 0 && i < g.N - 1 && j < g.N - 1) g.inside[j * g.N + i] = 0;
      }
    };
    if (kind === 'lath') {
      const a = base + Math.PI / 4;
      for (let r = g.R - P.LATH; r <= g.R + 1; r += 0.25) mark(g.cx + r * Math.cos(a), g.cy + r * Math.sin(a));
    } else if (kind === 'screen') {
      const a0 = base, a1 = base + Math.PI / 2, rr = g.R - P.whisperInset;
      const x0 = g.cx + rr * Math.cos(a0), y0 = g.cy + rr * Math.sin(a0);
      const x1 = g.cx + rr * Math.cos(a1), y1 = g.cy + rr * Math.sin(a1);
      const mx = (x0 + x1) / 2, my = (y0 + y1) / 2, L = Math.hypot(x1 - x0, y1 - y0);
      const nx = -(y1 - y0) / L, ny = (x1 - x0) / L;
      for (let s = -P.SCREEN / 2; s <= P.SCREEN / 2; s += 0.25) mark(mx + s * nx, my + s * ny);
    }
  }
  const profIns = []; if (profile) for (let d = 1; d <= 75; d++) profIns.push(d * k);
  function run({ wall = 'hard', facing = 'along', obstacle = 'none', rings = P.rings }) {
    const g = E.makeGallery({ N: P.N, R: P.R, wall, sponge: P.sponge });
    // the sponge's damping is per step; a step is k times shorter, so divide it by k to keep the same sponge in time
    for (let i = 0; i < g.damp.length; i++) g.damp[i] /= k;
    const base = Math.PI / 2;
    if (obstacle !== 'none') placeObstacle(g, obstacle, base);
    const px = g.cx + (P.R - P.whisperInset) * Math.cos(base), py = g.cy + (P.R - P.whisperInset) * Math.sin(base);
    const fa = facing === 'in' ? base + Math.PI : base + Math.PI / 2;
    const src = E.whispererCells(g, { px, py, facing: fa, sep: P.sep });
    const ringEars = rings.map((inset) => E.earRing(g, { baseAngle: base, inset }));
    for (let s = 0; s < P.steps; s++) {
      E.inject(g, src, { lambda: P.lambda, Cn: g.Cn });
      E.stepGallery(g);
      const u = g.u, t = g.t;
      for (const ring of ringEars) for (const e of ring) { const v = Math.abs(u[e.id]); if (v > e.peak) { e.peak = v; e.tPeak = t; } }
    }
    return ringEars;
  }
  const r = {
    'hard-along': run({ wall: 'hard', rings: [...P.rings, ...profIns] }), 'soft-along': run({ wall: 'soft', rings: [...P.rings, ...profIns] }),
    'hard-in': run({ wall: 'hard', facing: 'in' }), lath: run({ obstacle: 'lath' }), screen: run({ obstacle: 'screen' }),
  };
  const at = (key, ring, deg) => E.peakAt(r[key][ring], deg);
  const o = {
    k, quarter: E.dB(at('hard-along', 0, 90) / at('hard-along', 1, 90)), half: E.dB(at('hard-along', 0, 180) / at('hard-along', 1, 180)),
    soft: E.dB(at('soft-along', 0, 90) / at('soft-along', 1, 90)), hardVsSoft: E.dB(at('hard-along', 0, 90) / at('soft-along', 0, 90)),
    lath: E.dB(at('lath', 0, 90) / at('hard-along', 0, 90)), screen: E.dB(at('screen', 0, 90) / at('hard-along', 0, 90)),
    alongVsIn: E.dB(at('hard-along', 0, 90) / at('hard-in', 0, 90)),
    aheadHard: E.dB(at('hard-along', 0, 90) / at('hard-along', 0, 270)), aheadSoft: E.dB(at('soft-along', 0, 90) / at('soft-along', 0, 270)),
  };
  if (profile) o.profile = profIns.map((d, i) => ({ wavelengths: d / P.lambda, hard: at('hard-along', 2 + i, 90), soft: at('soft-along', 2 + i, 90) }));
  return o;
}
const grids = {};
{
  const g1 = gridRun(1);
  check('the scaled grid at k = 1 is the engine\'s own run, figure for figure', [
    [g1.quarter, out[90].wallVsRoom_hard], [g1.half, out[180].wallVsRoom_hard], [g1.soft, out[90].wallVsRoom_soft], [g1.hardVsSoft, out[90].hardVsSoft_wall],
    [g1.lath, out.lath_quarter], [g1.screen, out.screen_quarter], [g1.alongVsIn, out.alongVsIn_quarter], [g1.aheadHard, out.aheadVsBehind_hard], [g1.aheadSoft, out.aheadVsBehind_soft],
  ].every(([a, b]) => a === b));
  grids[1] = g1;
  if (GRIDS.length) {
    for (const k of GRIDS) {
      const t0 = Date.now(); grids[k] = gridRun(k, { profile: !!WRITE }); console.error(`grid k = ${k}: ${((Date.now() - t0) / 1000).toFixed(0)} s`);
      if (WRITE) writeFileSync(join(WRITE, `grid-k${k}.json`), JSON.stringify(grids[k], null, 1) + '\n');
    }
    for (const k of GRIDS) {
      const g = grids[k];
      check(`k = ${k}: the wall holds more than on the page's grid (quarter and half round, the lath, hard against soft)`,
        g.quarter > g1.quarter + 3 && g.half > g1.half + 3 && g.lath < g1.lath - 3 && g.hardVsSoft > g1.hardVsSoft + 3,
        `quarter ${f1(g.quarter)}, half ${f1(g.half)}, lath ${f1(g.lath)}, hard/soft ${f1(g.hardVsSoft)} dB`);
      check(`k = ${k}: the soft wall still erases the wall's advantage, and the screen still does nothing`, Math.abs(g.soft) < 1.5 && Math.abs(g.screen) < 0.5, `${f1(g.soft)}, ${g.screen.toFixed(2)} dB`);
    }
    if (grids[FINEST.k]) {
      const g = grids[FINEST.k];
      const worst = Math.max(...Object.keys(FINEST).filter((x) => x !== 'k').map((x) => Math.abs(g[x] - FINEST[x])));
      check(`the finest grid (k = ${FINEST.k}) reproduces the figures recorded in this file`, worst < 0.01, `worst difference ${worst.toFixed(4)} dB`);
    }
  } else {
    console.log('     (finer grids not rerun: add --grids to recompute k = 2, 3 and 4, about twenty minutes; the finest grid\'s figures below are the ones recorded in this file)');
  }
}

// ------------------------------------------------------------------ 4c. the same wave with no grid at all
// The two-dimensional wave equation in a disk with a rigid wall, solved exactly as a sum of the disk's own normal modes
// J_n(j'_nm r / R) cos/sin(n phi), with J_n'(j'_nm) = 0, each driven by the whisper: two point sources, the rear one
// inverted and delayed, each with the engine's burst() as its time function, at the positions the engine intends
// (unrounded). Units: one cell of the page's grid, one step of its clock. Independent of the engine except for burst()
// and the geometry constants: the Bessel functions here are Miller's recurrence (section 2's), the zeros found by
// scanning and bisection, and the sum is a phasor per mode. The FDTD's injection, written out: adding a(t) to one cell
// before each leapfrog update is the wave equation with a source a(t + dt) per step squared, so a point source with time
// function a(t) is its continuum limit. Overall amplitude cancels in every figure, which are all ratios.
function besselAll(x, nmax) {
  const J = new Float64Array(nmax + 2);
  if (x === 0) { J[0] = 1; return J; }
  const start = 2 * Math.ceil((Math.max(nmax, x) + 40 + 10 * Math.cbrt(Math.max(nmax, x))) / 2);
  const tmp = new Float64Array(start + 2); tmp[start] = 1e-300;
  for (let m = start; m >= 1; m--) {
    tmp[m - 1] = (2 * m / x) * tmp[m] - tmp[m + 1];
    if (Math.abs(tmp[m - 1]) > 1e250) for (let q = m - 1; q <= start; q++) tmp[q] *= 1e-250;
  }
  let norm = tmp[0]; for (let m = 2; m <= start; m += 2) norm += 2 * tmp[m];
  for (let n = 0; n <= nmax + 1; n++) J[n] = tmp[n] / norm;
  return J;
}
const dJ = (J, n) => (n === 0 ? -J[1] : 0.5 * (J[n - 1] - J[n + 1]));
const MODES_CUT = 1.75; // modes up to 1.75 x the whisper's wavenumber; its spectrum there is about 1e-6 of its peak
function modeSum({ wall = 0, profile = true } = {}) {
  // wall: move the rigid wall out (+) or in (-) by this many cells, leaving the whisperer and the ears where they are
  const S = E.STANDARD, R = S.R + wall, R0 = S.R, Cn = 0.5, LAM = S.lambda, T = S.steps, DT = 0.25;
  const XMAX = MODES_CUT * (2 * Math.PI / LAM) * R, NMAX = Math.ceil(XMAX) + 2;
  const zeros = [];
  let prev = null; const h = 0.02;
  for (let x = h; x <= XMAX + h; x += h) {
    const J = besselAll(x, NMAX + 1), cur = new Float64Array(NMAX + 1);
    for (let n = 0; n <= NMAX; n++) cur[n] = dJ(J, n);
    if (prev) for (let n = 0; n <= NMAX; n++) if (Math.sign(cur[n]) !== Math.sign(prev[n]) && n < x + 5) {
      let lo = x - h, hi = x, flo = prev[n];
      for (let it = 0; it < 60; it++) { const mid = 0.5 * (lo + hi), fm = dJ(besselAll(mid, n + 1), n); if (Math.sign(fm) === Math.sign(flo)) { lo = mid; flo = fm; } else hi = mid; }
      const z = 0.5 * (lo + hi); if (z <= XMAX) zeros.push({ n, x: z });
    }
    prev = cur;
  }
  const base = Math.PI / 2;
  const whisperer = (facing) => {
    const rr = R0 - S.whisperInset, px = rr * Math.cos(base), py = rr * Math.sin(base);
    const fa = facing === 'in' ? base + Math.PI : base + Math.PI / 2;
    const bx = px - 3 * Math.cos(fa), by = py - 3 * Math.sin(fa);
    return { front: [px, py], back: [bx, by], delay: Math.hypot(px - bx, py - by) / Cn };
  };
  const polar = ([x, y]) => [Math.hypot(x, y), Math.atan2(y, x)];
  const ear = (inset, deg) => { const a = base + deg * Math.PI / 180, r = R0 - inset; return [r * Math.cos(a), r * Math.sin(a)]; };
  const Q = (w) => { let re = 0, im = 0; for (let t = 0; t < 400; t++) { const a = E.burst(t, { lambda: LAM, Cn }); re += a * Math.cos(w * t); im -= a * Math.sin(w * t); } return [re, im]; };
  const nT = Math.floor(T / DT);
  function solve(facing, ears) {
    const W = whisperer(facing), [rf, pf] = polar(W.front), [rb, pb] = polar(W.back), P = ears.map(polar);
    const o = ears.map(() => new Float64Array(nT));
    for (const { n, x } of zeros) {
      const kap = x / R, w = Cn * kap, Jx = besselAll(x, n + 1)[n];
      const norm = (R * R / 2) * (1 - (n * n) / (x * x)) * Jx * Jx * (n === 0 ? 2 * Math.PI : Math.PI);
      const Jn = (r) => besselAll(kap * r, n + 1)[n];
      const jf = Jn(rf), jb = Jn(rb), [qr, qi] = Q(w), cdr = Math.cos(w * W.delay), cdi = -Math.sin(w * W.delay);
      for (let e = 0; e < ears.length; e++) {
        const [re, pe] = P[e], g = Jn(re) / norm, cf = Math.cos(n * (pe - pf)), cb = Math.cos(n * (pe - pb));
        const Ar = g * (jf * cf * qr - jb * cb * (qr * cdr - qi * cdi)) / w, Ai = g * (jf * cf * qi - jb * cb * (qr * cdi + qi * cdr)) / w;
        const c1 = Math.cos(w * DT), s1 = Math.sin(w * DT); let c = 1, s = 0; const oe = o[e];
        for (let i = 0; i < nT; i++) { oe[i] += Ar * s + Ai * c; const c2 = c * c1 - s * s1; s = s * c1 + c * s1; c = c2; }
      }
    }
    return o;
  }
  const peak = (o) => { let p = 0, ti = 0; for (let i = 0; i < o.length; i++) { const v = Math.abs(o[i]); if (v > p) { p = v; ti = i * DT; } } return { p, t: ti }; };
  const DEGS = [80, 85, 90, 95, 100], mean = (a) => a.reduce((s, x) => s + x, 0) / a.length;
  const group = (pk) => mean(pk.map((x) => x.p));
  const ringAt = (inset, centre) => DEGS.map((d) => ear(inset, d - 90 + centre));
  const profIns = []; if (profile) for (let d = 1; d <= 50; d++) profIns.push(d);
  const along = [...[90, 180, 270].flatMap((c) => [...ringAt(S.rings[0], c), ...ringAt(S.rings[1], c)]), ...profIns.flatMap((d) => ringAt(d, 90))];
  const A = solve('along', along).map(peak), IN = solve('in', ringAt(S.rings[0], 90)).map(peak);
  const g = (i) => group(A.slice(5 * i, 5 * i + 5));
  const prof = profIns.map((d, i) => ({ wavelengths: d / LAM, avg: g(6 + i) }));
  const single = profIns.map((d, i) => A[30 + 5 * i + 2].p); // the ear at 90 degrees
  return {
    zeros, xmax: XMAX, earliestPeak: Math.min(...A.map((x) => x.t)),
    quarter: E.dB(g(0) / g(1)), half: E.dB(g(2) / g(3)), behind: E.dB(g(4) / g(5)),
    ahead: E.dB(g(0) / g(4)), alongVsIn: E.dB(g(0) / group(IN)), profile: prof, single,
  };
}
const M = modeSum();
// how much the exact figures depend on the room's exact size: the wall an eightieth of a wavelength out, and in
const MW = [0.125, -0.125].map((w) => modeSum({ wall: w, profile: false }));
{
  const z = (n, m) => M.zeros.filter((q) => q.n === n).map((q) => q.x)[m - 1];
  // Abramowitz and Stegun, Table 9.5: j'_{0,1} = 3.83171, j'_{1,1} = 1.84118, j'_{1,2} = 5.33144, j'_{2,1} = 3.05424
  const tz = Math.max(Math.abs(z(0, 1) - 3.83171), Math.abs(z(1, 1) - 1.84118), Math.abs(z(1, 2) - 5.33144), Math.abs(z(2, 1) - 3.05424));
  check('the mode sum\'s own zeros of J_n\' match the printed table (Abramowitz & Stegun 9.5) to 5 decimals', tz < 6e-6, `worst ${tz.toExponential(1)}`);
  // Weyl's law with the Neumann boundary term: about x^2/4 + x/2 modes below x = kR, counting cos and sin
  const count = M.zeros.reduce((s, q) => s + (q.n === 0 ? 1 : 2), 0), weyl = M.xmax ** 2 / 4 + M.xmax / 2;
  check('and none is missing: the number of modes found matches Weyl\'s law to within 1%', Math.abs(count / weyl - 1) < 0.01, `${count} modes, Weyl ${weyl.toFixed(0)}`);
  check('every loudest moment comes after the whisper has ended (so the sum, which assumes it has, applies)', M.earliestPeak > 250, `earliest at step ${M.earliestPeak}`);
  check('with no grid, the hard wall\'s advantage a quarter round is larger than on the page\'s grid, by more than 4 dB', M.quarter > out[90].wallVsRoom_hard + 4, `${f1(M.quarter)} against ${f1(out[90].wallVsRoom_hard)} dB`);
  check('and half way round, by more than 4 dB', M.half > out[180].wallVsRoom_hard + 4, `${f1(M.half)} against ${f1(out[180].wallVsRoom_hard)} dB`);
  const range = (key) => [Math.min(...MW.map((m) => m[key]), M[key]), Math.max(...MW.map((m) => m[key]), M[key])];
  M.range = { quarter: range('quarter'), half: range('half') };
  check('the exact figures are sensitive: the wall an eightieth of a wavelength out or in moves the quarter-round figure by more than 1 dB each way, yet it stays above the page\'s grid by more than 3 dB',
    M.range.quarter[0] < M.quarter - 1 && M.range.quarter[1] > M.quarter + 1 && M.range.quarter[0] > out[90].wallVsRoom_hard + 3,
    `quarter ${f1(M.range.quarter[0])} to ${f1(M.range.quarter[1])}, half ${f1(M.range.half[0])} to ${f1(M.range.half[1])} dB`);
  check('the finest grid is closer to the exact solution than the page\'s grid is (quarter, half, ahead, facing)',
    [['quarter', 'quarter'], ['half', 'half'], ['aheadHard', 'ahead'], ['alongVsIn', 'alongVsIn']].every(([gk, mk]) => Math.abs(FINEST[gk] - M[mk]) < Math.abs(grids[1][gk] - M[mk])),
    ['quarter', 'half', 'ahead', 'alongVsIn'].map((mk) => f1(M[mk])).join(', ') + ' dB exact');
  // going in from the wall, a quarter round: one ear at 90 degrees, every cell from 1 to 50 in (the page's claim is about
  // what an ear hears as it moves; the mean over the five ears 80 to 100 degrees round smooths the belts away, so the
  // half-loudness depth, which the page reports as that mean, is checked on the mean)
  const one = M.single, dB1 = (d) => E.dB(one[d - 1] / one[3]); // relative to the ear 4 cells in
  const lowest = [...Array(20).keys()].map((i) => i + 1).filter((d) => d >= 6).reduce((a, d) => (one[d - 1] < one[a - 1] ? d : a), 6);
  const back = [...Array(50).keys()].map((i) => i + 1).filter((d) => d > lowest && d <= lowest + 15).reduce((a, d) => (one[d - 1] > one[a - 1] ? d : a), lowest + 1);
  check('exact: past the first band the loudness rises again (Raman and Sutherland\'s belts): a deep least, then a rise of more than 3 dB',
    dB1(back) - dB1(lowest) > 3, `${dB1(lowest).toFixed(1)} dB at ${lowest} cells, ${dB1(back).toFixed(1)} dB at ${back} cells`);
  const p = M.profile;
  const exactHalf = halfOf(BAND_INSETS.map((d) => p[d - 1].avg));
  check('exact: the whisper falls to half its wall loudness at the same place as on the grid', exactHalf === band.sim.half, `${exactHalf} cells`);
  // and the page's grid, which the page's sentence was first checked on, rises again too
  const w1 = E.runWhisper({ wall: 'hard', facing: 'along', rings: BAND_INSETS });
  const p1 = BAND_INSETS.map((_, i) => E.peakAt(w1.ringEars[i], 90)), dip = p1.indexOf(Math.min(...p1.slice(0, 10)));
  check('the page\'s grid rises again past the first band as well', dip > 0 && dip < 9 && p1[9] > p1[dip] * 1.1, `least at ${BAND_INSETS[dip]} cells`);
  M.walk = { lowest, back, lowestDb: dB1(lowest), backDb: dB1(back) };
  if (WRITE) writeFileSync(join(WRITE, 'modes.json'), JSON.stringify({ ...M, zeros: M.zeros.length }, null, 1) + '\n');
}

// ------------------------------------------------------------------ 5. the page's own sentences
// Each figure is looked for inside the sentence that states it, not anywhere on the page, so a
// number moved to the wrong sentence fails. The dek is checked twice: the visible one and the
// meta description (an attribute, which the text extraction drops).
{
  const meta = (html.match(/<meta name="description" content="([^"]*)"/) || [])[1] || '';
  const dek = (html.match(/<p class="dek">([\s\S]*?)<\/p>/) || [])[1] || '';
  const s1 = (x) => f1(Math.abs(x));
  const F = FINEST, g1 = grids[1];
  const want = [
    [`the ear against the wall hears the whisper ${f1(M.quarter)} dB louder than the ear 2.6 wavelengths into the room (${f1(F.quarter)} dB on the finest grid; the coarse grid in your browser says ${f1(g1.quarter)}); half way round, ${f1(M.half)} dB louder (${f1(F.half)} on the finest grid; the coarse grid says ${f1(g1.half)})`, 'quarter and half round, hard wall'],
    [`the same two ears differ by only ${s1(F.soft)} dB, on the coarse grid and the finest alike (the ear in the room, if anything, is the louder)`, 'soft wall control'],
    [`The hard wall is also ${f1(F.hardVsSoft)} dB louder at the wall than the soft one, a quarter round, on the finest grid (${f1(g1.hardVsSoft)} on the coarse one)`, 'hard vs soft at the wall'],
    [`cuts the whisper a quarter round by ${s1(F.lath)} dB on the finest grid (${s1(g1.lath)} on the coarse one)`, 'the lath'],
    [`changes it by under 0.1 dB (${s1(g1.screen)} on the coarse grid)`, 'the screen'],
    [`by only ${f1(M.alongVsIn)} dB in the exact solution (${f1(F.alongVsIn)} on the finest grid, ${f1(g1.alongVsIn)} on the coarse one)`, 'facing along vs into the room'],
    [`in front of the whisperer hears ${f1(M.ahead)} dB more than the ear a quarter round behind (${f1(F.aheadHard)} on the finest grid)`, 'ahead vs behind, hard'],
    [`But the soft-walled room shows a similar gap, ${f1(F.aheadSoft)} dB, so most of that`, 'ahead vs behind, soft'],
    [`about ${Math.round(M.quarter)} and ${Math.round(M.half)} dB in the exact solution (${f1(F.quarter)} and ${f1(F.half)} on the finest grid), and on the finest grid ${s1(F.lath)}, ${f1(F.hardVsSoft)}, ${f1(F.aheadHard)}, ${f1(F.alongVsIn)} and under 0.1 dB. The soft wall's ${s1(g1.soft)} dB stands`, 'the correction line'],
    [`At 1,000 Hz the band is about ${Math.round(band[1000].depth * 100)} cm deep; at 4,000 Hz, about ${Math.round(band[4000].depth * 100)} cm`, 'bands at 1,000 and 4,000 Hz'],
    [`the band comes out at ${(band.rayleighModel.depth * 100).toFixed(1)} cm`, 'band in Rayleigh\'s zinc model'],
    [`′ nm up to ${Math.round(M.xmax)}, ${M.zeros.length.toLocaleString('en-GB')} of them, ${M.zeros.reduce((s, q) => s + (q.n === 0 ? 1 : 2), 0).toLocaleString('en-GB')} modes counting their sine partners, as Weyl's law predicts`, 'the size of the mode sum'],
    [`between ${f1(M.range.quarter[0])} and ${f1(M.range.quarter[1])} dB a quarter round, and between ${f1(M.range.half[0])} and ${f1(M.range.half[1])} dB half way round`, 'the sensitivity'],
    [`fall to ${f1(-M.walk.lowestDb)} dB below what the ear 4 cells from the wall hears, ${f1(M.walk.lowest / 10)} wavelengths in, then rise again to ${f1(-M.walk.backDb)} dB below, ${M.walk.back / 10} wavelengths in`, 'the belts, exact'],
  ];
  for (const [s, what] of want) check(`the page says: "${s}" (${what})`, says(s));
  check('and the soft-wall difference really does favour the ear in the room, by the same tenth of a decibel on both grids', F.soft < 0 && g1.soft < 0 && s1(F.soft) === s1(g1.soft), `${f1(F.soft)}, ${f1(g1.soft)} dB`);
  check('and the screen really is under 0.1 dB on the finest grid', Math.abs(F.screen) < 0.1);
  check('and the soft room\'s gap really is most of the hard room\'s', F.aheadSoft > M.ahead / 2 && F.aheadSoft > F.aheadHard / 2, `${f1(F.aheadSoft)} soft, ${f1(M.ahead)} exact, ${f1(F.aheadHard)} finest grid`);
  const dekSays = `the ear at the wall hears about ${Math.round(M.quarter)} dB more than an ear 2.6 wavelengths further in, and a narrow lath against the wall cuts it by about ${Math.round(-F.lath)} dB`;
  check('the visible dek carries both wave figures in their own clauses', dek.includes(dekSays));
  check('so does the meta description', meta.includes(dekSays));
  // the model's own dimensions, as the prose names them
  check('the prose names the model as the engine builds it (15, 2.6, 1.2 and 4 wavelengths)',
    E.STANDARD.R / E.STANDARD.lambda === 15 && says('15 wavelengths in radius') &&
    (E.STANDARD.rings[1] - E.STANDARD.rings[0]) / E.STANDARD.lambda === 2.6 &&
    E.LATH / E.STANDARD.lambda === 1.2 && says('reaching 1.2 wavelengths in from the wall') &&
    E.SCREEN / E.STANDARD.lambda === 4 && says('A screen four wavelengths wide'));
  check('the prose names the finer grids as this file builds them (680, 1,020 and 1,360 cells across)', says('680, 1,020 and 1,360 cells across') && E.STANDARD.N * 4 === 1360);
}

// ------------------------------------------------------------------ 6. mutation: the checks must be able to go red
if (MUTATE) {
  const src = readFileSync(join(dir, 'engine.mjs'), 'utf8');
  const mutants = [
    ['the hard wall made soft', src.replace("if (wall === 'hard') { inside[id] = r <= R ? 1 : 0; }", "if (false) { inside[id] = r <= R ? 1 : 0; }")],
    ['wrong reflection law in the circle', src.replace('dx -= 2 * dn * nx; dy -= 2 * dn * ny;\n  }\n  return { pts, minR };', 'dx -= 1.9 * dn * nx; dy -= 1.9 * dn * ny;\n  }\n  return { pts, minR };')],
  ];
  const { tmpdir } = await import('node:os');
  for (const [name, m] of mutants) {
    if (m === src) { check(`mutant "${name}" was applied`, false); continue; }
    const p = join(tmpdir(), `wg-mutant-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`);
    writeFileSync(p, m);
    const M = await import(pathToFileURL(p).href);
    let red = false;
    if (name.includes('wall')) { const o = M.standardResults().out; red = !(o[90].wallVsRoom_hard > 6); }
    else { const c = M.circleBandTest(1, 10, 200); red = !(Math.max(...c.angles.map((x) => Math.abs(x - 10))) < 1e-6); }
    check(`mutant "${name}" turns its check red`, red);
  }
}

console.log(`\n${pass} passed, ${fail} failed`);
console.log(JSON.stringify({ exact: { quarter: M.quarter, half: M.half, ahead: M.ahead, alongVsIn: M.alongVsIn, modes: M.zeros.length, walk: M.walk, range: M.range }, finest: FINEST, grids: Object.keys(grids).map(Number), liveGrid: { quarter: out[90], half: out[180], alongVsIn: out.alongVsIn_quarter, lath: out.lath_quarter, screen: out.screen_quarter, ahead: [out.aheadVsBehind_hard, out.aheadVsBehind_soft], band: Object.fromEntries(Object.entries(band).map(([k, v]) => [k, k === 'sim' ? v : { n: v.n, depthCm: +(v.depth * 100).toFixed(1) }])) } }));
process.exit(fail ? 1 : 0);
