// research/mullers-ratchet/verify.mjs
// The check behind /strata/mullers-ratchet/. Recomputes every number the page
// asserts, from scratch, and cross-checks the live simulation against the
// analytic theory of Muller's ratchet.
//
//   node research/mullers-ratchet/verify.mjs
//
// The model (Haigh 1978, "The accumulation of deleterious genes in a population
// — Muller's ratchet", Theor. Popul. Biol. 14:251-267): a finite ASEXUAL
// population of N individuals; each individual carries k >= 0 deleterious
// mutations, all equivalent, with MULTIPLICATIVE fitness w_k = (1-s)^k; each
// generation, N offspring are drawn with probability proportional to fitness
// (Wright-Fisher selection) and then each gains Poisson(U) NEW deleterious
// mutations (U = genome-wide deleterious mutation rate). No back-mutation.
//
// Two exact analytic facts anchor everything, and the file PROVES them (not by
// simulation but by machine-precision arithmetic):
//   (A) The deterministic mutation-selection balance is EXACTLY Poisson(U/s):
//       selection on a Poisson(λ) with weights (1-s)^k returns Poisson(λ(1-s));
//       Poisson mutation convolves in Poisson(U); the fixed point is λ = U/s.
//       => the mutation-free ("least-loaded") class frequency is e^{-U/s},
//          so its expected COUNT is n0 = N·e^{-U/s}  (Haigh 1978).
//   (B) Mean fitness at that balance is w̄ = e^{-U}, INDEPENDENT of s
//       (the Haldane-Muller principle: the mutational load equals the mutation
//        rate, not the severity of each mutation — Haldane 1937; Muller 1950).
//
// Then seeded Monte Carlo confirms: the time-averaged least-loaded class tracks
// n0; the minimum mutation count k_min is a NON-DECREASING staircase (the
// ratchet clicks, irreversibly); n0 governs the click rate (small n0 -> fast,
// large n0 -> frozen); and FREE RECOMBINATION halts the ratchet where clonal
// reproduction lets it turn.

'use strict';

// ────────────────────────────────────────────────────────────────────────────
// Primitives shared, byte-for-byte in spirit, with the browser page.
// ────────────────────────────────────────────────────────────────────────────
function mulberry32(seed) {
  let a = seed >>> 0;
  return function () {
    a |= 0; a = (a + 0x6D2B79F5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
// Knuth's Poisson sampler (fine for the small λ = U we ever draw here).
function poissonSample(rng, lambda) {
  const L = Math.exp(-lambda);
  let k = 0, p = 1;
  do { k++; p *= rng(); } while (p > L);
  return k - 1;
}
function poissonPMF(lambda, k) {
  // exp(k*ln λ − λ − ln k!)
  let lnFact = 0;
  for (let i = 2; i <= k; i++) lnFact += Math.log(i);
  return Math.exp(k * Math.log(lambda) - lambda - lnFact);
}

// Fitness-proportional parent index via cumulative search over a weight array.
function pickWeighted(cum, total, r) {
  const target = r * total;
  // linear scan is fine at these N; the page uses the identical rule.
  let lo = 0, hi = cum.length - 1;
  while (lo < hi) { const mid = (lo + hi) >> 1; if (cum[mid] < target) lo = mid + 1; else hi = mid; }
  return lo;
}

// ────────────────────────────────────────────────────────────────────────────
// COUNT-BASED asexual model — matches Haigh exactly (each individual is an int
// = its mutation count). Used for the analytic-match checks.
// ────────────────────────────────────────────────────────────────────────────
function stepAsexualCounts(pop, s, U, rng) {
  const N = pop.length;
  const w = new Float64Array(N);
  const cum = new Float64Array(N);
  let total = 0;
  const oneMinusS = 1 - s;
  for (let i = 0; i < N; i++) { w[i] = Math.pow(oneMinusS, pop[i]); total += w[i]; cum[i] = total; }
  const next = new Int32Array(N);
  for (let i = 0; i < N; i++) {
    const parent = pickWeighted(cum, total, rng());
    next[i] = pop[parent] + poissonSample(rng, U);
  }
  return next;
}
function kmin(pop) { let m = Infinity; for (let i = 0; i < pop.length; i++) if (pop[i] < m) m = pop[i]; return m; }
function countAt(pop, k) { let c = 0; for (let i = 0; i < pop.length; i++) if (pop[i] === k) c++; return c; }
function mean(pop) { let s = 0; for (let i = 0; i < pop.length; i++) s += pop[i]; return s / pop.length; }
function meanFitness(pop, s) { let t = 0; for (let i = 0; i < pop.length; i++) t += Math.pow(1 - s, pop[i]); return t / pop.length; }

// ────────────────────────────────────────────────────────────────────────────
// LOCI (bit-string) model — needed for recombination. Each individual is a
// Uint8Array of L loci; fitness = (1-s)^{popcount}. When L ≫ typical load the
// count dynamics are identical to the count model (checked below).
// ────────────────────────────────────────────────────────────────────────────
function popcount(g) { let c = 0; for (let i = 0; i < g.length; i++) c += g[i]; return c; }
function mutate(g, U, rng) {
  const m = poissonSample(rng, U);
  const L = g.length;
  for (let j = 0; j < m; j++) {
    const locus = Math.floor(rng() * L);
    g[locus] = 1; // infinite-sites approx: hitting an already-mutated locus is a no-op (rare when L≫load)
  }
}
function stepLoci(pop, s, U, rng, sexual) {
  const N = pop.length, L = pop[0].length;
  const load = new Int32Array(N), cum = new Float64Array(N);
  let total = 0;
  for (let i = 0; i < N; i++) { load[i] = popcount(pop[i]); const wi = Math.pow(1 - s, load[i]); total += wi; cum[i] = total; }
  const next = new Array(N);
  for (let i = 0; i < N; i++) {
    const child = new Uint8Array(L);
    if (sexual) {
      const a = pop[pickWeighted(cum, total, rng())];
      const b = pop[pickWeighted(cum, total, rng())];
      for (let j = 0; j < L; j++) child[j] = (rng() < 0.5) ? a[j] : b[j]; // free recombination
    } else {
      const a = pop[pickWeighted(cum, total, rng())];
      child.set(a); // clone
    }
    mutate(child, U, rng);
    next[i] = child;
  }
  return next;
}
function kminLoci(pop) { let m = Infinity; for (let i = 0; i < pop.length; i++) { const c = popcount(pop[i]); if (c < m) m = c; } return m; }

// ────────────────────────────────────────────────────────────────────────────
// Harness
// ────────────────────────────────────────────────────────────────────────────
let pass = 0, fail = 0;
const near = (a, b, tol) => Math.abs(a - b) <= tol;
function check(name, ok, got, want) {
  if (ok) { pass++; console.log(`  ✓ ${name}`); }
  else { fail++; console.log(`  ✗ ${name}\n      got:  ${got}\n      want: ${want}`); }
}

console.log('\nMuller\'s ratchet — verification\n' + '─'.repeat(60));

// ── (A) The deterministic equilibrium is EXACTLY Poisson(U/s) ────────────────
console.log('\nA. Mutation-selection balance is exactly Poisson(U/s)');
{
  for (const [U, s] of [[0.2, 0.05], [0.1, 0.02], [0.5, 0.1]]) {
    const lambda = U / s;
    const K = 400;
    // build Poisson(λ)
    const f = new Float64Array(K + 1);
    for (let k = 0; k <= K; k++) f[k] = poissonPMF(lambda, k);
    // one deterministic generation: selection (weights (1-s)^k, renormalise), then mutation (⊛ Poisson(U))
    const g = new Float64Array(K + 1);
    let wbar = 0;
    for (let k = 0; k <= K; k++) { g[k] = f[k] * Math.pow(1 - s, k); wbar += g[k]; }
    for (let k = 0; k <= K; k++) g[k] /= wbar;
    const fp = new Float64Array(K + 1);
    // precompute Poisson(U) pmf
    const pm = new Float64Array(K + 1);
    for (let j = 0; j <= K; j++) pm[j] = poissonPMF(U, j);
    for (let m = 0; m <= K; m++) { let acc = 0; for (let k = 0; k <= m; k++) acc += g[k] * pm[m - k]; fp[m] = acc; }
    let maxdiff = 0;
    for (let k = 0; k <= 60; k++) maxdiff = Math.max(maxdiff, Math.abs(fp[k] - f[k]));
    check(`Poisson(${lambda}) is a fixed point of selection∘mutation  (U=${U}, s=${s})`,
      maxdiff < 1e-12, maxdiff.toExponential(2), '< 1e-12');
    // (A2) mean fitness at balance = e^{-U}, independent of s  (Haldane-Muller)
    check(`mean fitness at balance = e^{-U} = ${Math.exp(-U).toFixed(6)}  (independent of s)`,
      near(wbar, Math.exp(-U), 1e-12), wbar, Math.exp(-U));
    // (A3) least-loaded fraction = e^{-U/s}
    check(`least-loaded (mutation-free) fraction = e^{-U/s} = ${Math.exp(-lambda).toExponential(3)}`,
      near(f[0], Math.exp(-lambda), 1e-14), f[0], Math.exp(-lambda));
  }
}

// ── (B) Selection on Poisson(λ) returns exactly Poisson(λ(1-s)) ──────────────
console.log('\nB. Selection maps Poisson(λ) → Poisson(λ(1-s)) exactly');
{
  const lambda = 6, s = 0.08, K = 400;
  const f = new Float64Array(K + 1); for (let k = 0; k <= K; k++) f[k] = poissonPMF(lambda, k);
  const g = new Float64Array(K + 1); let wbar = 0;
  for (let k = 0; k <= K; k++) { g[k] = f[k] * Math.pow(1 - s, k); wbar += g[k]; }
  for (let k = 0; k <= K; k++) g[k] /= wbar;
  let maxdiff = 0;
  for (let k = 0; k <= 60; k++) maxdiff = Math.max(maxdiff, Math.abs(g[k] - poissonPMF(lambda * (1 - s), k)));
  check(`post-selection = Poisson(λ(1-s)) = Poisson(${(lambda * (1 - s)).toFixed(3)})`,
    maxdiff < 1e-12, maxdiff.toExponential(2), '< 1e-12');
}

// ── (C) Monte Carlo: time-averaged least-loaded class tracks n0 = N·e^{-U/s} ─
console.log('\nC. Simulated least-loaded class ≈ N·e^{-U/s}  (slow-ratchet regime)');
{
  // choose a regime where n0 is large (~30) so the class persists and the
  // deterministic balance is a good description of its time average.
  const N = 3000, U = 0.3, s = 0.10; // λ = 3, e^{-3}=0.0498, n0 ≈ 149
  const n0 = N * Math.exp(-U / s);
  const rng = mulberry32(20260712);
  let pop = new Int32Array(N); // start clonal, mutation-free
  // burn-in to balance
  for (let g = 0; g < 400; g++) pop = stepAsexualCounts(pop, s, U, rng);
  // average the size of the CURRENT least-loaded class over a window, measured
  // relative to the running minimum (class = individuals at k_min)
  let acc = 0, samples = 0;
  for (let g = 0; g < 600; g++) {
    pop = stepAsexualCounts(pop, s, U, rng);
    acc += countAt(pop, kmin(pop)); samples++;
  }
  const meanLL = acc / samples;
  // relative match within Monte-Carlo noise (fluctuates ~ sqrt(n0))
  check(`⟨least-loaded class⟩ = ${meanLL.toFixed(1)} vs n0 = ${n0.toFixed(1)}  (within 15%)`,
    Math.abs(meanLL - n0) / n0 < 0.15, meanLL.toFixed(1), n0.toFixed(1));
  // mean load at balance ≈ U/s ; mean fitness ≈ e^{-U}
  const ml = mean(pop), mf = meanFitness(pop, s);
  check(`⟨mutations per individual⟩ = ${ml.toFixed(2)} vs U/s = ${(U / s).toFixed(2)}  (within 12%)`,
    Math.abs(ml - U / s) / (U / s) < 0.12, ml.toFixed(2), (U / s).toFixed(2));
  check(`⟨fitness⟩ = ${mf.toFixed(3)} vs e^{-U} = ${Math.exp(-U).toFixed(3)}  (within 3%)`,
    Math.abs(mf - Math.exp(-U)) / Math.exp(-U) < 0.03, mf.toFixed(3), Math.exp(-U).toFixed(3));
}

// ── (D) The ratchet clicks: k_min is a non-decreasing staircase ──────────────
console.log('\nD. The ratchet is irreversible: k_min never decreases');
{
  const N = 120, U = 0.5, s = 0.03; // n0 = N·e^{-U/s}=120·e^{-16.7}≈tiny -> fast ratchet
  const rng = mulberry32(7);
  let pop = new Int32Array(N);
  let prevMin = 0, clicks = 0, monotone = true;
  for (let g = 0; g < 500; g++) {
    pop = stepAsexualCounts(pop, s, U, rng);
    const m = kmin(pop);
    if (m < prevMin) monotone = false;
    if (m > prevMin) { clicks += (m - prevMin); prevMin = m; }
  }
  check(`k_min non-decreasing over 500 generations (${clicks} clicks recorded)`, monotone, monotone, true);
  check(`fast regime (tiny n0) turns the ratchet: clicks > 0`, clicks > 0, clicks, '> 0');
}

// ── (E) n0 governs the click rate: small n0 fast, large n0 frozen ────────────
console.log('\nE. Smaller n0 turns the ratchet faster');
{
  function clickRate(N, U, s, gens, seed) {
    const rng = mulberry32(seed);
    let pop = new Int32Array(N);
    for (let g = 0; g < 100; g++) pop = stepAsexualCounts(pop, s, U, rng); // settle
    let prevMin = kmin(pop), clicks = 0;
    for (let g = 0; g < gens; g++) {
      pop = stepAsexualCounts(pop, s, U, rng);
      const m = kmin(pop); if (m > prevMin) { clicks += (m - prevMin); prevMin = m; }
    }
    return clicks / gens;
  }
  // hold U,s; vary N so n0 = N·e^{-U/s} spans small→large
  const U = 0.4, s = 0.06, base = Math.exp(-U / s); // e^{-6.67}=1.27e-3
  const small = clickRate(400, U, s, 1500, 11);   // n0 ≈ 0.5  → fast
  const large = clickRate(20000, U, s, 1500, 11);  // n0 ≈ 25   → slow/frozen
  const n0s = 400 * base, n0l = 20000 * base;
  check(`n0=${n0s.toFixed(2)} clicks ${small.toFixed(4)}/gen  >  n0=${n0l.toFixed(1)} clicks ${large.toFixed(4)}/gen`,
    small > large, `${small.toFixed(4)} vs ${large.toFixed(4)}`, 'small-n0 rate greater');
  check(`large-n0 ratchet is (near-)frozen on this horizon`, large < small * 0.5,
    large.toFixed(4), `< ${(small * 0.5).toFixed(4)}`);
}

// ── (F) Loci model reproduces the count dynamics (so recombination is honest) ─
console.log('\nF. Loci model matches the count model at balance (frozen regime, unsaturated L)');
{
  // Frozen-ratchet regime (large n0 = N·e^{-U/s}) so both models sit at the
  // mutation-selection balance mean ≈ U/s rather than on a climbing trajectory
  // whose exact height is seed-dependent. Time-average to damp Monte-Carlo noise.
  const N = 2000, U = 0.3, s = 0.10, L = 600, BURN = 200, WIN = 200; // U/s = 3, n0 ≈ 100 (frozen)
  const target = U / s;
  // count model
  let rc = mulberry32(99), pc = new Int32Array(N), accC = 0;
  for (let g = 0; g < BURN; g++) pc = stepAsexualCounts(pc, s, U, rc);
  for (let g = 0; g < WIN; g++) { pc = stepAsexualCounts(pc, s, U, rc); accC += mean(pc); }
  const meanC = accC / WIN;
  // loci model, asexual
  let rl = mulberry32(99), pl = Array.from({ length: N }, () => new Uint8Array(L)), accL = 0;
  for (let g = 0; g < BURN; g++) pl = stepLoci(pl, s, U, rl, false);
  for (let g = 0; g < WIN; g++) {
    pl = stepLoci(pl, s, U, rl, false);
    let sl = 0; for (let i = 0; i < N; i++) sl += popcount(pl[i]); accL += sl / N;
  }
  const meanL = accL / WIN;
  check(`⟨load⟩ count ${meanC.toFixed(2)} ≈ loci ${meanL.toFixed(2)} ≈ U/s=${target.toFixed(2)}  (both within 8% of U/s)`,
    Math.abs(meanC - target) / target < 0.08 && Math.abs(meanL - target) / target < 0.08,
    `count ${meanC.toFixed(2)} / loci ${meanL.toFixed(2)}`, `both ≈ ${target.toFixed(2)}`);
}

// ── (G) Free recombination halts the ratchet ─────────────────────────────────
console.log('\nG. Sex halts the ratchet: recombination reconstitutes the least-loaded class');
{
  const N = 150, U = 0.4, s = 0.08, L = 1000, GEN = 500; // U/s = 5, n0 = 150·e^{-5} ≈ 1.0 (fast)
  function run(sexual, seed) {
    const rng = mulberry32(seed);
    let pop = Array.from({ length: N }, () => new Uint8Array(L));
    let prevMin = 0, monotone = true, fell = false;
    for (let g = 0; g < GEN; g++) {
      pop = stepLoci(pop, s, U, rng, sexual);
      const m = kminLoci(pop);
      if (m < prevMin) { monotone = false; fell = true; }
      prevMin = m;
    }
    let load = 0; for (let i = 0; i < N; i++) load += popcount(pop[i]);
    return { monotone, fell, finalMin: kminLoci(pop), meanLoad: load / N };
  }
  const asex = run(false, 2024);
  const sex = run(true, 2024);
  // (G1) the clonal minimum is a true ratchet — monotone non-decreasing
  check(`clonal k_min is monotone (a true ratchet); sexual k_min falls back at least once (not a ratchet)`,
    asex.monotone && sex.fell, `clonal monotone=${asex.monotone}, sexual fell=${sex.fell}`, 'clonal monotone & sexual non-monotone');
  // (G2) after GEN generations the clonal load has run away far above the sexual load (≈ U/s)
  check(`clonal ⟨load⟩ ${asex.meanLoad.toFixed(1)} ≫ sexual ⟨load⟩ ${sex.meanLoad.toFixed(1)} (sexual holds near U/s=${(U / s).toFixed(1)})`,
    asex.meanLoad > 2 * sex.meanLoad && Math.abs(sex.meanLoad - U / s) / (U / s) < 0.6,
    `clonal ${asex.meanLoad.toFixed(1)} / sexual ${sex.meanLoad.toFixed(1)}`, 'clonal ≫ sexual, sexual ≈ U/s');
}

// ────────────────────────────────────────────────────────────────────────────
console.log('\n' + '─'.repeat(60));
console.log(`${pass}/${pass + fail} checks passed.`);
if (fail > 0) { console.log('FAILED.'); process.exit(1); }
console.log('All checks passed.');
