#!/usr/bin/env node
// verify.mjs — Luria–Delbrück / Lea–Coulson fluctuation analysis, checked from scratch.
//
// Checks two exact distribution calculations and a separate growth simulation.
// Page simulation runs use different settings and do not reproduce these figures.
// Run: node research/luria-delbruck/verify.mjs
//
// Two exact calculations plus a separate growth simulation:
//   (A) the Ma–Sandri–Sarkar (1992) recursion          p0=e^-m, p_n=(m/n)Σ p_i/(n-i+1)
//   (B) the compound-Poisson convolution definition     p = Σ_j e^-m m^j/j! · c^{*j}
//   (C) a seeded stochastic simulation of a binary-growth model
//
// (A) and (B) are genuinely different algorithms (a linear recurrence vs. a sum of
// convolution powers of the clone-size law c_k = 1/(k(k+1))); they must agree to
// machine precision. (C) uses a different, powers-of-two clone law. It checks
// the fluctuation signature and shared zero probability, not all probabilities.
//
// The biology — the thing the 1943 experiment actually decided — is the variance:
// the *induced* (Lamarckian) hypothesis predicts a Poisson count (variance ≈ mean);
// the *spontaneous* (Darwinian) hypothesis predicts the Luria–Delbrück distribution
// (variance ≫ mean, with jackpots). Both are simulated and their variance/mean ratio
// checked. The p0 estimator m = −ln(p0) is checked by recovery; the idealized mean is
// shown to diverge (∼ m·ln N). The finite growth simulation has a finite mean;
// the 1943 paper used both zero-culture and average-based estimators.

let PASS = 0, FAIL = 0;
const approx = (a, b, tol, msg) => {
  const ok = Math.abs(a - b) <= tol;
  console.log(`${ok ? '✓' : '✗'} ${msg}  (${(+a).toPrecision(7)} vs ${(+b).toPrecision(7)}, tol ${tol})`);
  ok ? PASS++ : FAIL++;
};
const assert = (ok, msg, detail = '') => {
  console.log(`${ok ? '✓' : '✗'} ${msg}${detail ? '  (' + detail + ')' : ''}`);
  ok ? PASS++ : FAIL++;
};

const { exp, log } = Math;

/* ───────────────────── (A) Ma–Sandri–Sarkar recursion ───────────────────── */
// p0 = e^-m ;  p_n = (m/n) Σ_{i=0}^{n-1} p_i / (n - i + 1)
function mss(m, N) {
  const p = new Float64Array(N + 1);
  p[0] = exp(-m);
  for (let n = 1; n <= N; n++) {
    let s = 0;
    for (let i = 0; i < n; i++) s += p[i] / (n - i + 1);
    p[n] = (m / n) * s;
  }
  return p;
}

/* ─────────────── (B) compound-Poisson convolution definition ─────────────── */
// A culture's mutant count r = Σ (clone sizes), over Poisson(m) clones, each clone
// size drawn from c_k = 1/(k(k+1)), k ≥ 1 (the discretised 1/s² jackpot law).
// p_n = Σ_{j≥0} e^-m m^j/j! · c^{*j}(n).  c^{*j} is supported on n ≥ j, so summing
// j = 0..N captures every contribution to p_n for n ≤ N exactly.
function convPoisson(m, N) {
  const c = new Float64Array(N + 1);
  for (let k = 1; k <= N; k++) c[k] = 1 / (k * (k + 1));
  let term = new Float64Array(N + 1); term[0] = 1; // c^{*0} = δ_0
  const p = new Float64Array(N + 1);
  let coef = exp(-m);                                // e^-m · m^0/0!
  for (let j = 0; j <= N; j++) {
    for (let n = 0; n <= N; n++) p[n] += coef * term[n];
    const nt = new Float64Array(N + 1);              // term ← term * c
    for (let a = 0; a <= N; a++) {
      if (term[a] === 0) continue;
      for (let b = 1; a + b <= N; b++) nt[a + b] += term[a] * c[b];
    }
    term = nt;
    coef *= m / (j + 1);
  }
  return p;
}

/* ───────────────────────── clone-size law sanity ────────────────────────── */
{
  let s = 0; for (let k = 1; k <= 200000; k++) s += 1 / (k * (k + 1));
  // Σ_{k=1}^K 1/(k(k+1)) = 1 - 1/(K+1) → 1
  approx(s, 1 - 1 / 200001, 1e-12, 'clone-size law Σ 1/(k(k+1)) telescopes to 1');
}

/* ─────────────────── (A) vs (B): the two exact algorithms ─────────────────── */
for (const m of [0.5, 1, 2, 3]) {
  const N = 400;
  const a = mss(m, N), b = convPoisson(m, N);
  let maxerr = 0; for (let n = 0; n <= N; n++) maxerr = Math.max(maxerr, Math.abs(a[n] - b[n]));
  assert(maxerr < 1e-12, `m=${m}: recursion (A) and convolution (B) agree`, `max|Δp_n| = ${maxerr.toExponential(2)}`);
  approx(a[0], exp(-m), 1e-15, `m=${m}: p0 = e^-m exactly`);
}

/* ───────────────────────── named probabilities (printed on the page) ──────── */
{
  // m = 1
  const p = mss(1, 10);
  approx(p[0], 0.367879, 1e-5, 'm=1: p0 = 0.367879');
  approx(p[1], 0.183940, 1e-5, 'm=1: p1 = 0.183940 (= m/2 · e^-m)');
  approx(p[1], (1 / 2) * exp(-1), 1e-12, 'm=1: p1 closed form m/2·e^-m');
  approx(p[2], 0.107298, 1e-5, 'm=1: p2 = 0.107298');
  // m = 2
  const q = mss(2, 10);
  approx(q[0], 0.135335, 1e-5, 'm=2: p0 = e^-2 = 0.135335');
}

/* ───────────────── total mass & the c/n² jackpot tail (exact) ─────────────── */
for (const m of [1, 2]) {
  const N = 400, p = mss(m, N);
  let mass = 0; for (let n = 0; n <= N; n++) mass += p[n];
  assert(mass < 1 && mass > 0.99, `m=${m}: truncated mass ∈ (0.99,1) — slow tail keeps mass below 1`, `Σ_{n≤400} p_n = ${mass.toFixed(6)}`);
  // n² p_n → m  (the Ma–Sandri–Sarkar asymptotic p_n ~ m/n²)
  const t = N * N * p[N];
  approx(t, m, 0.15 * m, `m=${m}: n²·p_n → m as n→∞ (jackpot tail p_n ~ m/n²)`);
}

/* ──────────────── the idealized mean diverges (∼ m·ln N) ──────────────────── */
// Because the clone tail is 1/s², E[clone size] = Σ k·c_k = Σ 1/(k+1) diverges, so
// the Luria–Delbrück mean is infinite. Any real culture is capped at N cells; the
// truncated mean grows like m·ln N as the cap increases. This is a statement
// about the ideal law, not the finite-mean binary-growth simulation below.
{
  const m = 1, N = 20000, p = mss(m, N);
  const meanAt = (T) => { let s = 0; for (let n = 0; n <= T; n++) s += n * p[n]; return s; };
  const m100 = meanAt(100), m10k = meanAt(10000);
  assert(m100 < m10k && m10k > 8, 'truncated mean keeps growing with the cap (mean is infinite)', `mean(≤100)=${m100.toFixed(2)} < mean(≤10⁴)=${m10k.toFixed(2)}`);
  // grows roughly like m·ln N — check the increment matches the log increment within 25%
  const dEmp = m10k - m100, dLog = m * (log(10000) - log(100));
  approx(dEmp, dLog, 0.25 * dLog, 'mean increment tracks m·ln(N) (logarithmic divergence)');
}

/* ───────────────────────── (C) the stochastic model ──────────────────────── */
function mulberry32(seed) {
  let s = (seed >>> 0) || 1;
  return function () {
    s = (s + 0x6D2B79F5) >>> 0; let t = s;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
function poisson(rng, lam) {
  if (lam < 30) { const L = exp(-lam); let k = 0, p = 1; do { k++; p *= rng(); } while (p > L); return k - 1; }
  const u1 = rng(), u2 = rng(); const z = Math.sqrt(-2 * log(u1)) * Math.cos(2 * Math.PI * u2);
  return Math.max(0, Math.round(lam + Math.sqrt(lam) * z));
}
// SPONTANEOUS: a culture grows 1 → 2^G by binary fission. Each of the Poisson(m)
// mutational events happens at generation t (weight 2^{t-1}, ∝ cells dividing then)
// and founds a clone that doubles for the remaining G−t generations → size 2^{G-t}.
function ldCulture(rng, m, G) {
  const J = poisson(rng, m);
  const total = Math.pow(2, G) - 1;
  let r = 0;
  for (let j = 0; j < J; j++) {
    let u = rng() * total, c = 0, t = 1;
    for (t = 1; t <= G; t++) { c += Math.pow(2, t - 1); if (u <= c) break; }
    r += Math.pow(2, G - t);
  }
  return r;
}
function stats(arr) {
  const n = arr.length, mean = arr.reduce((a, b) => a + b, 0) / n;
  const v = arr.reduce((a, b) => a + (b - mean) * (b - mean), 0) / n;
  const zeros = arr.filter((x) => x === 0).length;
  return { mean, v, vm: v / mean, p0: zeros / n, max: Math.max(...arr) };
}
{
  const rng = mulberry32(424242), G = 22, m = 2, K = 4000;
  const ld = []; for (let i = 0; i < K; i++) ld.push(ldCulture(rng, m, G));
  const s1 = stats(ld);
  const ind = []; for (let i = 0; i < K; i++) ind.push(poisson(rng, m));
  const s2 = stats(ind);

  assert(s1.vm > 100, 'SPONTANEOUS sim: variance/mean ≫ 1 (jackpots) — the Darwinian signature', `var/mean = ${s1.vm.toFixed(0)}, max clone-sum = ${s1.max}`);
  assert(s2.vm > 0.9 && s2.vm < 1.1, 'INDUCED sim: variance/mean ≈ 1 (Poisson) — the Lamarckian prediction', `var/mean = ${s2.vm.toFixed(2)}`);
  approx(s1.p0, exp(-m), 0.02, 'SPONTANEOUS sim: p0 ≈ e^-m (both hypotheses share p0 — the VARIANCE decides)');
  approx(s2.p0, exp(-m), 0.02, 'INDUCED sim: p0 ≈ e^-m');
  assert(s1.vm / s2.vm > 100, 'the fluctuation test: spontaneous var/mean exceeds induced by ≥100×', `ratio = ${(s1.vm / s2.vm).toFixed(0)}×`);
}

/* ─────────────────── p0 estimator vs the raw sample mean ────────────── */
{
  const rng = mulberry32(20260617), G = 22, m = 2, EXPTS = 200, CULTURES = 100;
  const mhats = [], means = [];
  for (let e = 0; e < EXPTS; e++) {
    const c = []; for (let i = 0; i < CULTURES; i++) c.push(ldCulture(rng, m, G));
    const z = c.filter((x) => x === 0).length / CULTURES;
    mhats.push(z > 0 ? -log(z) : NaN);
    means.push(c.reduce((a, b) => a + b, 0) / CULTURES);
  }
  const valid = mhats.filter((x) => !Number.isNaN(x));
  const mhat = valid.reduce((a, b) => a + b, 0) / valid.length;
  const mm = means.reduce((a, b) => a + b, 0) / means.length;
  const msd = Math.sqrt(means.reduce((a, b) => a + (b - mm) ** 2, 0) / means.length);
  approx(mhat, m, 0.15, 'p0 estimator m = −ln(p0) recovers the true m', `m̂ = ${mhat.toFixed(3)} from ${valid.length} experiments`);
  assert(msd > 0.5 * mm, 'raw sample means vary widely across these finite-growth experiments', `mean ≈ ${mm.toFixed(1)}, sd across experiments ≈ ${msd.toFixed(1)}`);
}

/* ─────────────────────────────── summary ─────────────────────────────────── */
console.log(`\n${PASS}/${PASS + FAIL} checks pass.`);
process.exit(FAIL ? 1 : 0);
