// verify.mjs — proves the numbers the instrument *The Residual* asserts, before
// the page asserts them. Run: node research/core-sample-no-1/verify.mjs
//
// The rigorous heart is the ANOVA identity. For a field f and its block-mean map,
// with grand mean μ:
//     total SS  = Σ (f − μ)²
//     within SS = Σ (f − map)²        ← the RESIDUAL: what the map cannot carry
//     between SS= Σ (map − μ)²        ← what the map KEEPS
// and exactly  total = between + within  (the cross term vanishes because, inside
// each block, map is the block mean, so Σ(f − map) over the block is zero). So
// "fraction of the territory's variance the map keeps" + "fraction it loses" = 1,
// with no slack — the residual is a measured quantity, not a metaphor. The page
// displays these very numbers; this file recomputes them independently.

import { makeField, blockMap, mapCells } from './field.mjs';

const N = 64;
const BLOCKS = [1, 2, 4, 8, 16, 32];
const f = makeField(N);

let mu = 0; for (let i = 0; i < N * N; i++) mu += f[i]; mu /= N * N;
let totalSS = 0; for (let i = 0; i < N * N; i++) totalSS += (f[i] - mu) ** 2;

let fails = 0;
const ok = (cond, msg) => { console.log(`  ${cond ? '✓' : '✗ FAIL'} ${msg}`); if (!cond) fails++; };
const approx = (a, b, tol = 1e-9) => Math.abs(a - b) <= tol * Math.max(1, Math.abs(a), Math.abs(b));

console.log(`Territory: ${N}×${N} = ${N * N} cells. Grand mean μ = ${mu.toFixed(6)}. Total SS = ${totalSS.toFixed(6)}.\n`);
console.log('  b  | map cells | ratio  | var kept | var lost | residual RMS');
console.log('  ---+-----------+--------+----------+----------+-------------');

const rows = [];
for (const b of BLOCKS) {
  const map = blockMap(f, N, b);
  let withinSS = 0, betweenSS = 0;
  for (let i = 0; i < N * N; i++) { withinSS += (f[i] - map[i]) ** 2; betweenSS += (map[i] - mu) ** 2; }
  const M = mapCells(N, b);
  const ratio = (N * N) / M;
  const fracKept = totalSS > 0 ? betweenSS / totalSS : 1;
  const fracLost = totalSS > 0 ? withinSS / totalSS : 0;
  const rms = Math.sqrt(withinSS / (N * N));
  rows.push({ b, M, ratio, fracKept, fracLost, rms, withinSS, betweenSS });
  console.log(
    `  ${String(b).padStart(2)} | ${String(M).padStart(9)} | ${ratio.toFixed(2).padStart(6)} | ` +
    `${(100 * fracKept).toFixed(3).padStart(7)}% | ${(100 * fracLost).toFixed(3).padStart(7)}% | ${rms.toExponential(4)}`
  );
}

console.log('\nChecks:');
for (const r of rows) {
  // The ANOVA identity — the one that makes "the residual" exact, not rhetorical.
  ok(approx(r.betweenSS + r.withinSS, totalSS), `b=${r.b}: between SS + within SS = total SS (ANOVA identity)`);
  ok(approx(r.fracKept + r.fracLost, 1), `b=${r.b}: variance kept + variance lost = 1`);
  ok(r.M === mapCells(N, r.b), `b=${r.b}: map stores (N/b)² = ${r.M} cells`);
}
// The only lossless map is the one that is the territory (b=1): no compression.
const b1 = rows.find((r) => r.b === 1);
ok(approx(b1.withinSS, 0), 'b=1: residual is exactly zero — the only lossless "map" is the territory itself');
ok(b1.M === N * N && b1.ratio === 1, 'b=1: map cells = territory cells, ratio 1:1 (it stores everything)');
// Monotonicity: a coarser map always loses at least as much as a finer one.
for (let i = 1; i < rows.length; i++) {
  ok(rows[i].fracLost >= rows[i - 1].fracLost - 1e-12,
    `coarsening b=${rows[i - 1].b}→${rows[i].b} does not decrease the loss`);
}

// The pigeonhole bound (counting, not this particular field): if each cell is
// quantized to L levels, there are L^(N²) possible territories and only L^M
// possible maps; M < N² ⇒ strictly fewer maps than territories ⇒ no injection ⇒
// some two distinct territories collapse to one map. Check the inequality holds
// for every lossy setting here (it must, since M < N² whenever b>1).
for (const r of rows) {
  if (r.b > 1) ok(r.M < N * N, `b=${r.b}: map cells (${r.M}) < territory cells (${N * N}) ⇒ pigeonhole forces collisions`);
}

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