// verify.mjs: standalone check for /strata/hearing-the-shape/ (no imports, node 22).
// Run from an empty directory:  node verify.mjs      (exit 0 = every check passed)
//
// What it checks, with the same finite-element code the page runs:
//   1. the solver on shapes with known answers (unit square, L-shaped membrane);
//   2. the transplantation matrix T, derived exactly (no numerics) from the two cuts:
//      it satisfies the Dirichlet continuation rules, |T| satisfies the Neumann ones,
//      the solution space is two-dimensional, det T = 24, and the signs follow the
//      black/white colouring rule of Buser, Conway, Doyle and Semmler;
//   3. the two drums: equal discrete spectra to rounding, each converging toward
//      Driscoll's published values, and T carrying Drum A's computed vibrations to
//      vibrations of Drum B;
//   4. negative controls: an earlier non-mirror cut does not give equal discrete
//      spectra, and flipping any one sign of T breaks the transplantation.

const MACROS_A = [[[0,0],[1,0],[0,1]],[[1,1],[1,2],[0,1]],[[1,1],[1,0],[0,1]],[[1,1],[1,2],[2,1]],[[2,2],[1,2],[2,1]],[[2,2],[1,2],[2,3]],[[2,2],[3,2],[2,1]]];
const MACROS_B = [[[1,1],[1,2],[0,1]],[[0,2],[1,2],[0,1]],[[1,1],[1,0],[0,1]],[[1,1],[1,2],[2,1]],[[2,2],[1,2],[2,1]],[[2,2],[3,2],[2,1]],[[2,2],[3,2],[2,3]]];
const T = [[1,1,0,0,1,0,0],[0,-1,1,1,0,0,0],[-1,0,1,0,0,0,1],[-1,0,0,1,0,1,0],[0,0,-1,0,1,-1,0],[0,-1,0,0,0,1,1],[0,0,0,-1,1,0,-1]];
// the cut the page used before 2026-09-28 (same octagons, other diagonals): control only
const OLD_A = [[[0,0],[1,0],[1,1]],[[0,0],[1,1],[0,1]],[[0,1],[1,1],[1,2]],[[1,1],[2,1],[2,2]],[[1,1],[2,2],[1,2]],[[1,2],[2,2],[2,3]],[[2,1],[3,2],[2,2]]];
const OLD_B = [[[1,0],[1,1],[0,1]],[[0,1],[1,1],[1,2]],[[0,1],[1,2],[0,2]],[[1,1],[2,1],[2,2]],[[1,1],[2,2],[1,2]],[[2,1],[3,2],[2,2]],[[2,2],[3,2],[2,3]]];
// Driscoll, SIAM Review 39 (1997), Table 3.1 (his drum is twice this one, so λ here = 4× his)
const DRISCOLL = [2.53794399980,3.65550971352,5.17555935622,6.53755744376,7.24807786256,9.20929499840,10.5969856913,11.5413953956];

let failed = 0;
const check = (ok, msg) => { console.log(`${ok ? 'ok  ' : 'FAIL'}  ${msg}`); if (!ok) failed++; };

// ---------- finite elements (identical to the page) ----------
function meshDomain(macros, n) {
  const idx = new Map(), nodes = [], tris = [], grids = [];
  const key = (x, y) => Math.round(x * 1e6) + ',' + Math.round(y * 1e6);
  const get = (x, y) => { const k = key(x, y); if (idx.has(k)) return idx.get(k); const id = nodes.length; nodes.push([x, y]); idx.set(k, id); return id; };
  for (const [A, B, C] of macros) {
    const g = [];
    for (let i = 0; i <= n; i++) { g[i] = []; for (let j = 0; j <= n - i; j++) { const a = i / n, b = j / n, c = 1 - a - b; g[i][j] = get(a * A[0] + b * B[0] + c * C[0], a * A[1] + b * B[1] + c * C[1]); } }
    for (let i = 0; i < n; i++) for (let j = 0; j < n - i; j++) { tris.push([g[i][j], g[i + 1][j], g[i][j + 1]]); if (j < n - i - 1) tris.push([g[i + 1][j], g[i + 1][j + 1], g[i][j + 1]]); }
    grids.push(g);
  }
  return { nodes, tris, grids };
}
function boundaryNodes(tris) {
  const ec = new Map(), ek = (a, b) => a < b ? a + '_' + b : b + '_' + a;
  for (const [a, b, c] of tris) for (const [u, v] of [[a, b], [b, c], [c, a]]) { const k = ek(u, v); ec.set(k, (ec.get(k) || 0) + 1); }
  const bnd = new Set();
  for (const [k, c] of ec) if (c === 1) { const [u, v] = k.split('_').map(Number); bnd.add(u); bnd.add(v); }
  return bnd;
}
function assemble(macros, n) {
  const { nodes, tris, grids } = meshDomain(macros, n);
  const bnd = boundaryNodes(tris), interior = [];
  for (let i = 0; i < nodes.length; i++) if (!bnd.has(i)) interior.push(i);
  const m = interior.length, g2l = new Int32Array(nodes.length).fill(-1);
  for (let i = 0; i < m; i++) g2l[interior[i]] = i;
  const K = Array.from({ length: m }, () => new Float64Array(m)), M = Array.from({ length: m }, () => new Float64Array(m));
  for (const tri of tris) {
    const [i0, i1, i2] = tri, [x0, y0] = nodes[i0], [x1, y1] = nodes[i1], [x2, y2] = nodes[i2];
    const det = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0), area = 0.5 * Math.abs(det);
    const b = [y1 - y2, y2 - y0, y0 - y1], c = [x2 - x1, x0 - x2, x1 - x0];
    for (let a = 0; a < 3; a++) { const ga = g2l[tri[a]]; if (ga < 0) continue;
      for (let bb = 0; bb < 3; bb++) { const gb = g2l[tri[bb]]; if (gb < 0) continue;
        K[ga][gb] += (b[a] * b[bb] + c[a] * c[bb]) / (4 * area); M[ga][gb] += ((a === bb ? 2 : 1) * area) / 12; } }
  }
  return { K, M, nodes, interior, g2l, grids, n };
}
function cholesky(K) { const n = K.length, L = Array.from({ length: n }, () => new Float64Array(n));
  for (let i = 0; i < n; i++) for (let j = 0; j <= i; j++) { let s = K[i][j]; for (let k = 0; k < j; k++) s -= L[i][k] * L[j][k]; L[i][j] = i === j ? Math.sqrt(s) : s / L[j][j]; } return L; }
function solveChol(L, b) { const n = L.length, y = new Float64Array(n), x = new Float64Array(n);
  for (let i = 0; i < n; i++) { let s = b[i]; for (let k = 0; k < i; k++) s -= L[i][k] * y[k]; y[i] = s / L[i][i]; }
  for (let i = n - 1; i >= 0; i--) { let s = y[i]; for (let k = i + 1; k < n; k++) s -= L[k][i] * x[k]; x[i] = s / L[i][i]; } return x; }
function matVec(A, x) { const n = A.length, y = new Float64Array(n); for (let i = 0; i < n; i++) { let s = 0, Ai = A[i]; for (let j = 0; j < n; j++) s += Ai[j] * x[j]; y[i] = s; } return y; }
function dot(a, b) { let s = 0; for (let i = 0; i < a.length; i++) s += a[i] * b[i]; return s; }
function lowestEig(K, M, count, iters) {
  const n = K.length, L = cholesky(K), vecs = [], mvecs = [], vals = [];
  for (let m = 0; m < count; m++) {
    let x = new Float64Array(n);
    for (let i = 0; i < n; i++) x[i] = Math.sin((i + 1) * (m + 1) * 0.7) + 0.31 * Math.cos((i + 3) * (m + 2));
    let lam = 0;
    for (let it = 0; it < iters; it++) {
      for (let j = 0; j < vecs.length; j++) { const c = dot(x, mvecs[j]); const v = vecs[j]; for (let i = 0; i < n; i++) x[i] -= c * v[i]; }
      const y = solveChol(L, matVec(M, x));
      for (let j = 0; j < vecs.length; j++) { const c = dot(y, mvecs[j]); const v = vecs[j]; for (let i = 0; i < n; i++) y[i] -= c * v[i]; }
      let My = matVec(M, y); const nrm = Math.sqrt(dot(y, My)); for (let i = 0; i < n; i++) y[i] /= nrm;
      My = matVec(M, y);
      const nl = dot(y, matVec(K, y)) / dot(y, My);
      const conv = Math.abs(nl - lam) / Math.max(1, Math.abs(nl));
      x = y; lam = nl; if (conv < 1e-11 && it > 6) break;
    }
    vecs.push(x); mvecs.push(matVec(M, x)); vals.push(lam);
  }
  return { vals, vecs };
}
function solve(macros, n, count = 8) {
  const asm = assemble(macros, n);
  const { vals, vecs } = lowestEig(asm.K, asm.M, count, 260);
  const fields = vecs.map(v => { const f = new Float64Array(asm.nodes.length); for (let i = 0; i < asm.interior.length; i++) f[asm.interior[i]] = v[i]; return f; });
  return { asm, vals, fields };
}
function residual(asm, f, lam) {
  const x = new Float64Array(asm.interior.length); for (let i = 0; i < x.length; i++) x[i] = f[asm.interior[i]];
  const Kx = matVec(asm.K, x), Mx = matVec(asm.M, x); let rn = 0, dn = 0;
  for (let i = 0; i < x.length; i++) { const r = Kx[i] - lam * Mx[i]; rn += r * r; dn += (lam * Mx[i]) ** 2; }
  return Math.sqrt(rn / dn);
}
function transplant(A, B, TT, mode) {
  const f = A.fields[mode], n = A.asm.n, NB = B.asm.nodes.length, v = new Float64Array(NB), seen = new Uint8Array(NB);
  let mx = 0, seam = 0, rim = 0;
  for (let k = 0; k < 7; k++) for (let i = 0; i <= n; i++) for (let j = 0; j <= n - i; j++) {
    let s = 0; for (let l = 0; l < 7; l++) if (TT[k][l]) s += TT[k][l] * f[A.asm.grids[l][i][j]];
    const id = B.asm.grids[k][i][j];
    if (seen[id]) seam = Math.max(seam, Math.abs(v[id] - s)); else { v[id] = s; seen[id] = 1; }
    mx = Math.max(mx, Math.abs(s));
  }
  for (let id = 0; id < NB; id++) if (B.asm.g2l[id] < 0) rim = Math.max(rim, Math.abs(v[id]));
  return { rim: rim / mx, seam: seam / mx, res: residual(B.asm, v, A.vals[mode]) };
}

// ---------- 1. known answers ----------
const SQUARE = [[[0,0],[1,0],[0,1]], [[1,1],[0,1],[1,0]]];
const LSHAPE = [];
for (const [ox, oy] of [[0,0],[1,0],[0,1]]) { LSHAPE.push([[ox,oy],[ox+1,oy],[ox,oy+1]]); LSHAPE.push([[ox+1,oy+1],[ox,oy+1],[ox+1,oy]]); }
{
  const exact = [2, 5, 5, 8].map(k => k * Math.PI ** 2);
  const e = [8, 16].map(n => solve(SQUARE, n, 4).vals.map((v, i) => (v - exact[i]) / exact[i]));
  console.log(`unit square, λ1..λ4 relative error: n=8 ${e[0].map(x => x.toExponential(1)).join(' ')} | n=16 ${e[1].map(x => x.toExponential(1)).join(' ')}`);
  check(e[1].every((x, i) => x > 0 && x < e[0][i] / 3), 'unit square: FEM over-estimates π²(m²+n²) and the error falls about 4× when the mesh is halved');
  const L1 = 9.6397238440;
  const l = [8, 16, 24].map(n => (solve(LSHAPE, n, 1).vals[0] - L1) / L1);
  console.log(`L-shape λ1 relative error: n=8 ${l[0].toExponential(2)} | n=16 ${l[1].toExponential(2)} | n=24 ${l[2].toExponential(2)}`);
  check(l[2] > 0 && l[2] < l[1] && l[1] < l[0] && l[2] < 1e-2, 'L-shaped membrane: λ1 converges to 9.6397238 from above (slowly: the inward corner)');
}

// ---------- 2. the matrix, exactly ----------
{
  const key = p => p[0] + ',' + p[1];
  // edge of type e = edge opposite corner e (corners are listed in type order)
  const nbr = M => M.map((t, l) => [0, 1, 2].map(e => {
    const ed = t.filter((_, i) => i !== e).map(key);
    const j = M.findIndex((u, m) => m !== l && ed.every(k => u.map(key).includes(k)));
    if (j >= 0 && !ed.every(k => t.map(key).indexOf(k) === M[j].map(key).indexOf(k))) throw new Error(`tiles ${l},${j} are not mirror images`);
    return j;
  }));
  const nA = nbr(MACROS_A), nB = nbr(MACROS_B);
  check(true, 'every shared edge in both cuts joins mirror-image triangles, corner types matching');
  // continuation rule as linear constraints on X (7×7): X[k'] = C_e X[k] across a shared edge, C_e X[k] = ∓X[k] at the rim
  const constraints = neumann => { const rows = [];
    for (let k = 0; k < 7; k++) for (let e = 0; e < 3; e++) { const kp = nB[k][e];
      for (let r = 0; r < 7; r++) { const row = Array(49).fill(0);
        for (let l = 0; l < 7; l++) { const j = nA[l][e]; if ((j >= 0 ? j : l) === r) row[k * 7 + l] += (j >= 0 ? 1 : (neumann ? 1 : -1)); }
        if (kp >= 0) row[kp * 7 + r] -= 1; else row[k * 7 + r] += (neumann ? -1 : 1);
        rows.push(row); } }
    return rows; };
  const violations = (rows, X) => rows.filter(r => r.reduce((s, c, i) => s + c * X[Math.floor(i / 7)][i % 7], 0) !== 0).length;
  const D = constraints(false), N = constraints(true);
  check(violations(D, T) === 0, 'Dirichlet: each recipe continues into its neighbours and cancels on the rim (exact, integer arithmetic)');
  check(violations(N, T.map(r => r.map(Math.abs))) === 0, 'Neumann: with every minus turned to plus, the same holds for a free rim');
  // rank of D (exact elimination over rationals via integers)
  const rank = rows => { const M = rows.map(r => r.map(BigInt)); let rk = 0;
    for (let c = 0; c < 49 && rk < M.length; c++) { const p = M.findIndex((r, i) => i >= rk && r[c] !== 0n); if (p < 0) continue; [M[rk], M[p]] = [M[p], M[rk]];
      for (let i = 0; i < M.length; i++) if (i !== rk && M[i][c] !== 0n) { const a = M[rk][c], b = M[i][c]; M[i] = M[i].map((x, j) => x * a - M[rk][j] * b); }
      rk++; } return rk; };
  check(49 - rank(D) === 2, `the Dirichlet solutions form a 2-dimensional space (found ${49 - rank(D)}): this three-piece map and its four-piece complement`);
  const det = M => { M = M.map(r => r.slice()); let d = 1; for (let i = 0; i < 7; i++) { let p = i; for (let r = i; r < 7; r++) if (Math.abs(M[r][i]) > Math.abs(M[p][i])) p = r; if (M[p][i] === 0) return 0; if (p !== i) { [M[p], M[i]] = [M[i], M[p]]; d = -d; } d *= M[i][i]; for (let r = i + 1; r < 7; r++) { const f = M[r][i] / M[i][i]; for (let k = i; k < 7; k++) M[r][k] -= f * M[i][k]; } } return d; };
  const dT = det(T);
  check(Math.abs(dT - 24) < 1e-9, `det T = ${dT.toFixed(6)} (expect 24)`);
  const TT = T.map(r => T.map(q => r.reduce((a, x, i) => a + x * q[i], 0)));
  check(TT.every((r, i) => r.every((x, j) => i === j ? x === 3 : Math.abs(x) === 1)), 'T·Tᵀ has 3 on the diagonal and ±1 off it (T is not orthogonal)');
  const or = t => Math.sign((t[1][0] - t[0][0]) * (t[2][1] - t[0][1]) - (t[2][0] - t[0][0]) * (t[1][1] - t[0][1]));
  const eA = MACROS_A.map(or), eB = MACROS_B.map(or);
  check([1, -1].some(s => T.every((r, k) => r.every((x, l) => x === 0 || x === s * eA[l] * eB[k]))), 'signs follow the black/white colouring rule (minus exactly when a piece changes colour)');
}

// ---------- 3. the drums ----------
const DRUMS = {};
for (const n of [8, 12]) DRUMS[n] = { A: solve(MACROS_A, n), B: solve(MACROS_B, n) };
{
  for (const n of [8, 12]) {
    const { A, B } = DRUMS[n];
    const gap = Math.max(...A.vals.map((a, i) => Math.abs(a - B.vals[i]) / a));
    console.log(`n=${n}: λ/4 A ${A.vals.map(v => (v / 4).toFixed(5)).join(' ')}`);
    console.log(`      λ/4 B ${B.vals.map(v => (v / 4).toFixed(5)).join(' ')}   largest relative A-B gap ${gap.toExponential(1)}`);
    check(gap < 1e-9, `n=${n}: the two drums' eight lowest discrete eigenvalues agree to rounding (${gap.toExponential(1)})`);
  }
  const err = n => DRUMS[n].A.vals.map((v, i) => (v / 4 - DRISCOLL[i]) / DRISCOLL[i]);
  const e8 = err(8), e12 = err(12);
  console.log(`relative error vs Driscoll: n=8 ${e8.map(x => x.toExponential(1)).join(' ')}`);
  console.log(`                            n=12 ${e12.map(x => x.toExponential(1)).join(' ')}`);
  check(e12.every((x, i) => x > 0 && x < e8[i]), 'each eigenvalue approaches Driscoll\'s 12-digit value from above as the mesh is refined');
  const { A, B } = DRUMS[12];
  let worst = 0;
  for (let m = 0; m < 8; m++) {
    const t = transplant(A, B, T, m), own = residual(A.asm, A.fields[m], A.vals[m]);
    worst = Math.max(worst, t.res / own);
    check(t.rim === 0 && t.seam === 0 && t.res < 2 * own + 1e-12, `mode ${m + 1}: T·(A's vibration) is zero on B's rim, continuous at seams, residual ${t.res.toExponential(1)} vs A's own ${own.toExponential(1)}`);
  }
}

// ---------- 4. negative controls ----------
{
  const A = solve(OLD_A, 8), B = solve(OLD_B, 8);
  const gap = Math.max(...A.vals.map((a, i) => Math.abs(a - B.vals[i]) / a));
  check(gap > 1e-3, `control: the old non-mirror cut gives unequal discrete spectra (gap ${gap.toExponential(1)}), so the equality above is not automatic`);
  const { A: a12, B: b12 } = DRUMS[12];
  let least = Infinity;
  for (let k = 0; k < 7; k++) for (let l = 0; l < 7; l++) if (T[k][l]) {
    const F = T.map(r => r.slice()); F[k][l] = -F[k][l];
    for (let m = 0; m < 8; m++) least = Math.min(least, transplant(a12, b12, F, m).res);
  }
  check(least > 0.05, `control: flipping any one of T's 21 signs breaks the transplantation (smallest residual ${least.toFixed(3)})`);
}

console.log(failed ? `\n${failed} CHECK(S) FAILED` : '\nALL CHECKS PASS');
process.exit(failed ? 1 : 0);
