// verify.mjs — recompute Fisher 1936's analysis of Mendel 1866 from scratch
// and cross-check the chi-squared engine at known landmarks.
//
//   node research/closer-than-chance/verify.mjs
//
// What this proves:
//   1.  The chi-squared cumulative distribution computed from the regularised
//       lower incomplete gamma is correct at canonical critical values
//       (df=1, P=0.95 → x=3.841; df=7, P=0.95 → x=14.067; df=84, P=0.5
//       → x ≈ 83.33; etc.).
//   2.  Each of Mendel's seven monohybrid F2 ratios reproduces a small
//       chi-squared; reported individually so a reader can check the cell.
//   3.  The SUM of the seven monohybrid chi-squared values is ≈ 2.14 on
//       7 df, and the lower-tail probability ("at least this close") is
//       ≈ 0.05 — a one-in-twenty closeness, *just from the seven F2s*.
//   4.  The dihybrid 9:3:3:1 chi-squared on Mendel's (315,108,101,32)
//       is ≈ 0.470 on 3 df, lower-tail ≈ 0.075.
//   5.  Fisher's headline combined figure (χ² ≈ 41.6 on 84 df, printed
//       p_upper ·99993) is quoted from his Table V (p. 131). Computed exactly
//       the tail is 0.99997 (lower 2.87e-5, about 3 in 100,000), as Pires &
//       Branco (2010) also found; the engine is checked against the exact
//       closed form (df even, a Poisson sum), not against Fisher's rounding.
//       (Corrected 2026-09-29: this check accepted 0.0000287 as "≈ 7e-5".)
//   6.  Monte Carlo: 200,000 honest re-runs of Mendel's seven monohybrid
//       experiments give an empirical "≤ observed" fraction that agrees with
//       the analytic chi2CDF lower tail to <0.5% — independent confirmation
//       that the analytic result is right.
//
// Every datum cited in the page is asserted here. If a number on the page
// disagrees with a number here, this file is the source of truth.

import {
  chi2CDF, gammaP, chi2GoF,
  sevenMonohybrid, dihybridAB, honestSevenDistribution,
} from './analysis.mjs';
import { SEVEN, DIHYBRID_AB, FISHER_COMBINED } from './data.mjs';

let pass = 0, fail = 0;
const T = (name, ok, extra = '') => {
  console.log((ok ? '  ok   ' : '  FAIL ') + name + (extra ? '  ' + extra : ''));
  if (ok) pass++; else fail++;
};
const sec = (s) => console.log('\n=== ' + s + ' ===');
const close = (a, b, eps = 1e-4) => Math.abs(a - b) < eps;
const f = (x, n=4) => Number(x).toFixed(n);

/* ─── 1. chi-squared CDF at canonical landmarks ─── */
sec('chi-squared CDF — landmark crit. values');
// Source: Pearson & Hartley, Biometrika Tables, Vol. I, Table 8.
// We assert P(X ≤ x | df) = target, with x the published critical value.
const crit = [
  { df:  1, P: 0.95,    x: 3.84146  },   // 95th percentile, df=1
  { df:  1, P: 0.99,    x: 6.63490  },
  { df:  1, P: 0.50,    x: 0.45494  },
  { df:  3, P: 0.95,    x: 7.81473  },
  { df:  7, P: 0.95,    x: 14.0671  },
  { df:  7, P: 0.50,    x: 6.34581  },
  { df: 84, P: 0.50,    x: 83.3330  },   // approx median ≈ df·(1-2/(9df))^3
];
for (const c of crit){
  const got = chi2CDF(c.x, c.df);
  T(`chi2CDF(x=${c.x}, df=${c.df}) ≈ ${c.P}`,
    close(got, c.P, 5e-4), `got ${f(got, 5)}`);
}

// Gamma function spot-check: P(1/2, ∞) = 1, P(1, 1) = 1 - 1/e ≈ 0.6321.
T('gammaP(1, 1) ≈ 1 − 1/e',
  close(gammaP(1, 1), 1 - 1/Math.E, 1e-8),
  `got ${f(gammaP(1, 1), 8)}`);

/* ─── 2. each of Mendel's seven, individually ─── */
sec('Mendel 1866 §3 — the seven F2 ratios, each chi-squared');
const seven = sevenMonohybrid();
// Hand-computed targets (see data.mjs comments; values for verify only):
const TARGETS = {
  'seed-form':         0.2629,
  'seed-albumen':      0.0150,
  'flower-color':      0.3907,
  'pod-form':          0.0635,
  'unripe-pod-color':  0.4506,
  'flower-position':   0.3497,
  'stem-length':       0.6065,
};
for (const r of seven.rows){
  const exp = TARGETS[r.key];
  T(`${r.label.padEnd(28)} χ²=${f(r.chi2,4)} (df=1)`,
    close(r.chi2, exp, 1e-3),
    `target ${f(exp,4)}`);
}

/* ─── 3. their sum, and the lower-tail probability ─── */
sec('combined: the seven F2 ratios as one body');
T('combined chi² ≈ 2.139 (df=7)',
  close(seven.chi2, 2.139, 0.02),
  `got ${f(seven.chi2,4)}`);
T('combined df = 7',  seven.df === 7);
// The lower tail: "P(honest run lands at least this close)".
T('P(chi² ≤ observed | df=7) ≈ 0.0476  (about 1 in 21)',
  close(seven.p_lower, 0.0476, 5e-3),
  `got ${f(seven.p_lower,4)}`);
T('upper-tail p ≈ 0.952 (the usual GoF p-value)',
  close(seven.p_upper, 0.9524, 5e-3),
  `got ${f(seven.p_upper,4)}`);

/* ─── 4. the dihybrid 9:3:3:1 from §6 ─── */
sec('Mendel §6 — dihybrid (A×B), 9:3:3:1');
const dih = dihybridAB();
T('total = 556',                    dih.N === 556);
// Hand computation:
//   E = 556·{9,3,3,1}/16 = {312.75, 104.25, 104.25, 34.75}
//   χ² = (315-312.75)²/312.75 + (101-104.25)²/104.25
//      + (108-104.25)²/104.25 + (32-34.75)²/34.75
//      = 5.0625/312.75 + 10.5625/104.25 + 14.0625/104.25 + 7.5625/34.75
//      = 0.01619 + 0.10132 + 0.13489 + 0.21763 = 0.47002
T('chi² ≈ 0.470 (df=3)', close(dih.chi2, 0.4700, 1e-3), `got ${f(dih.chi2,4)}`);
T('df=3',                dih.df === 3);
// Lower tail at chi²=0.470, df=3 → 0.0746
T('lower-tail p ≈ 0.075 (about 1 in 13)',
  close(dih.p_lower, 0.0746, 5e-3),
  `got ${f(dih.p_lower,4)}`);

/* ─── 6. Fisher's combined headline figure, sanity-checked through the engine ─── */
sec('Fisher 1936 Table V: quoted combined χ² = 41.6, df = 84');
T('Fisher reports χ² = 41.6056 on 84 df', FISHER_COMBINED.df === 84);
const fisherUpper = 1 - chi2CDF(FISHER_COMBINED.chi2, FISHER_COMBINED.df);
// The exact lower tail for even df = 2k is 1 − e^(−x/2) Σ_{j<k} (x/2)^j / j!.
const exactLower = (() => { const l = FISHER_COMBINED.chi2 / 2; let t = Math.exp(-l), s = t;
  for (let j = 1; j < FISHER_COMBINED.df / 2; j++) { t *= l / j; s += t; } return 1 - s; })();
T('engine: P(X ≥ 41.6 | df=84) = 0.99997 (Fisher printed ·99993)',
  close(fisherUpper, 1 - exactLower, 1e-9) && close(fisherUpper, 0.99997, 5e-6),
  `got ${f(fisherUpper, 6)}`);
// Said the other way: an honest run lands ≥ this close with probability ≈ 2.9e-5, about 3 in 100,000.
const fisherLower = chi2CDF(FISHER_COMBINED.chi2, FISHER_COMBINED.df);
T('engine: P(X ≤ 41.6 | df=84) ≈ 2.87e-5 (about 3 in 100,000)',
  close(fisherLower, exactLower, 1e-9) && close(fisherLower, 2.87e-5, 1e-7),
  `got ${f(fisherLower, 7)}`);

/* ─── 7. Monte Carlo: honest reruns of Mendel's seven F2 experiments ─── */
sec('Monte Carlo — 200,000 honest reruns of the seven F2 experiments');
const dist = honestSevenDistribution(200_000, 42);
T('M = 200,000', dist.M === 200_000);
T('observed combined chi² ≈ 2.139', close(dist.observed, 2.139, 0.02));
// Agreement between empirical and analytic lower-tail probability:
const analytic = chi2CDF(dist.observed, 7);
T(`empirical P(≤observed) ≈ analytic to <0.5%`,
  Math.abs(dist.empirical_p_lower - analytic) < 0.005,
  `empirical ${f(dist.empirical_p_lower,4)}  analytic ${f(analytic,4)}`);

// And: the empirical distribution's mean should be near the df (E[χ²]=df):
let sum = 0;
for (let i = 0; i < dist.samples.length; i++) sum += dist.samples[i];
const mean = sum / dist.samples.length;
T('mean of simulated chi² ≈ 7 (df)', Math.abs(mean - 7) < 0.05,
  `got mean ${f(mean,4)}`);

/* ─── Done. ─── */
console.log(`\n${pass} ok · ${fail} fail`);
process.exit(fail === 0 ? 0 : 1);
