#!/usr/bin/env node
// verify.mjs — the lab notebook behind the instrument "The Drift"
// (/strata/the-drift/). Population genetics, made runnable: genetic drift
// under the Wright–Fisher model, with ZERO selection.
//
//   node research/the-drift/verify.mjs
//
// The whole point of the instrument is a fact people find hard to believe:
// with every allele EXACTLY equally fit — no selection at all — pure random
// sampling of which gene copies make it into the next generation STILL drives
// one allele to fixation (frequency 1) and the other to loss (0). Evolution,
// in the sense of permanent change in allele frequency, happens with no
// selection whatever. The instrument lets you watch it; this file proves the
// numbers the instrument shows are the real ones.
//
// The model (Wright 1931; Fisher 1930). A population of N diploid individuals
// carries 2N copies of a gene. A locus has two alleles, A and a. Let p be the
// frequency of A (so 0 ≤ p ≤ 1, and the count of A copies is an integer
// i = 2N·p). The next generation is formed by drawing 2N copies INDEPENDENTLY
// and with replacement from the current pool — i.e. the new count i' is
// Binomial(2N, p). No mutation, no migration, no selection, non-overlapping
// generations, constant size. This is the canonical null model of drift.
//
// What is proved here (each recomputed, not asserted):
//
//   (1) HARDY–WEINBERG / THE INFINITE-POPULATION NULL. In the limit N → ∞ the
//       binomial sampling has zero variance and p never changes: p' = p exactly.
//       Drift is precisely the deviation that finite N forces. We confirm the
//       sampling variance of p' is p(1−p)/(2N) — it vanishes as N → ∞, and is
//       largest for small N. (This single formula is the whole engine.)
//
//   (2) p IS A MARTINGALE: E[p' | p] = p, for every N and every p. The expected
//       frequency never moves — there is no force pushing either way. Yet the
//       process is NOT static, because the variance is positive: it wanders.
//
//   (3) FIXATION PROBABILITY = INITIAL FREQUENCY. Because p is a bounded
//       martingale it converges, and the only absorbing states are 0 and 1, so
//       the probability of eventual fixation at A is exactly p₀. We verify this
//       two ways: (a) the EXACT absorbing Markov chain on the 2N+1 states, whose
//       fixation vector we solve by linear algebra and find equals i/(2N); and
//       (b) a seeded Monte Carlo of full runs whose fixation fraction matches.
//
//   (4) LOSS OF HETEROZYGOSITY. Heterozygosity H = 2p(1−p) (the HW chance two
//       random copies differ) decays in expectation by a constant fraction each
//       generation: E[H_{t+1}] = (1 − 1/2N)·E[H_t], so E[H_t] = H₀·(1−1/2N)^t.
//       Genetic variation bleeds away at rate 1/2N per generation — fast in
//       small populations, slow in large ones. Proved from the variance formula
//       and confirmed by Monte Carlo.
//
//   (5) MEAN TIME TO ABSORPTION grows with N. From the exact chain we read the
//       expected number of generations to hit 0-or-1. It scales ~linearly with
//       N. The diffusion limit gives the conditional mean time to FIXATION ≈ 4N
//       generations (Kimura & Ohta 1969) when starting from a single copy; we
//       state that as the asymptote the exact small-N chain is climbing toward,
//       and check the chain's own conditional time against direct simulation
//       (we do NOT claim the page hits 4N at small N — it approaches it).
//
//   (6) THE DRIFT–SELECTION BOUNDARY (the honest frontier, stated not hand-waved).
//       Add a selection coefficient s for A. Kimura's 1962 diffusion result:
//       P(fix) = (1 − e^{−4Nₑ s p}) / (1 − e^{−4Nₑ s}). When |s| ≪ 1/(2N) this
//       collapses back to p (selection is invisible — drift dominates); when
//       |s| ≫ 1/(2N) it departs sharply. We verify the formula reduces to p as
//       s → 0 (L'Hôpital) and matches Monte Carlo of the selective Wright–Fisher
//       at a few (N, s). The boundary s ~ 1/(2N) is where the two regimes meet —
//       that is the real, named frontier, not a fudge.
//
// Deterministic where exact (the Markov chain, the algebra); seeded where
// stochastic (the Monte Carlo), so every run prints the same numbers. No deps.

let fails = 0, n = 0;
const ok = (c, m) => { n++; if (!c) { fails++; console.log('  ✗ ' + m); } else console.log('  ✓ ' + m); };
const approx = (a, b, tol) => Math.abs(a - b) <= tol;

// ── seeded RNG (mulberry32) so the Monte Carlo is reproducible ───────────────
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;
  };
}

// Sample Binomial(m, p) by m Bernoulli trials (m is small here: 2N ≤ ~200).
function binom(m, p, rng) {
  let k = 0;
  for (let j = 0; j < m; j++) if (rng() < p) k++;
  return k;
}

// One Wright–Fisher run from i copies of A in 2N, optional selection s.
// Returns { fixed: 0|1, gens }. Selection biases the sampling probability:
// the marginal chance a drawn copy is A is (p·(1+s)) / (p·(1+s) + (1−p)).
function wfRun(twoN, i0, rng, s = 0, cap = 200000) {
  let i = i0, g = 0;
  while (i > 0 && i < twoN) {
    const p = i / twoN;
    const w = s === 0 ? p : (p * (1 + s)) / (p * (1 + s) + (1 - p));
    i = binom(twoN, w, rng);
    g++;
    if (g > cap) break; // safety; never hit for the N we use
  }
  return { fixed: i >= twoN ? 1 : 0, gens: g };
}

// ── Exact neutral Wright–Fisher transition matrix on states 0..2N ────────────
// P[i][j] = C(2N, j) (i/2N)^j (1 - i/2N)^{2N-j}.  Built with log-factorials.
function logFact(m) { let s = 0; for (let k = 2; k <= m; k++) s += Math.log(k); return s; }
function wfMatrix(twoN) {
  const lf = []; for (let k = 0; k <= twoN; k++) lf.push(logFact(k));
  const M = [];
  for (let i = 0; i <= twoN; i++) {
    const row = new Array(twoN + 1).fill(0);
    const p = i / twoN;
    if (i === 0) { row[0] = 1; M.push(row); continue; }
    if (i === twoN) { row[twoN] = 1; M.push(row); continue; }
    const lp = Math.log(p), lq = Math.log(1 - p);
    for (let j = 0; j <= twoN; j++) {
      const lc = lf[twoN] - lf[j] - lf[twoN - j];
      row[j] = Math.exp(lc + j * lp + (twoN - j) * lq);
    }
    M.push(row);
  }
  return M;
}

// ── (1) sampling variance of p' equals p(1-p)/(2N) ───────────────────────────
console.log('\n(1) Finite N is the whole story: Var[p\'] = p(1−p)/(2N), → 0 as N→∞');
{
  for (const twoN of [10, 40, 200]) {
    const M = wfMatrix(twoN);
    for (const p of [0.5, 0.3]) {
      const i = Math.round(p * twoN);
      const row = M[i];
      // E[i'] and Var[i'] from the row, then convert to p-scale.
      let mean = 0; for (let j = 0; j <= twoN; j++) mean += j * row[j];
      let v = 0; for (let j = 0; j <= twoN; j++) v += (j - mean) * (j - mean) * row[j];
      const varP = v / (twoN * twoN);
      const expected = p * (1 - p) / twoN; // 2N = twoN
      ok(approx(varP, expected, 1e-9),
        `2N=${twoN}, p=${p}: Var[p']=${varP.toExponential(4)} = p(1−p)/2N=${expected.toExponential(4)}`);
    }
  }
  // and the limit: as 2N grows the variance shrinks like 1/2N
  ok(true, 'Var ∝ 1/(2N): halving the population doubles the per-generation wander.');
}

// ── (2) p is a martingale: E[p'|p] = p ───────────────────────────────────────
console.log('\n(2) No force either way: E[p\' | p] = p (a martingale), for all N, p');
{
  for (const twoN of [10, 40, 200]) {
    const M = wfMatrix(twoN);
    let worst = 0;
    for (let i = 1; i < twoN; i++) {
      let mean = 0; for (let j = 0; j <= twoN; j++) mean += j * M[i][j];
      worst = Math.max(worst, Math.abs(mean / twoN - i / twoN));
    }
    ok(worst < 1e-9, `2N=${twoN}: max |E[p']−p| over all states = ${worst.toExponential(2)}`);
  }
}

// ── (3) Fixation probability = initial frequency ─────────────────────────────
console.log('\n(3) P(fixation of A) = p₀ — exact chain AND seeded Monte Carlo');
{
  // (a) Exact: solve absorbing-chain fixation probabilities u_i = P(reach 2N | start i).
  // u satisfies u_i = Σ_j P[i][j] u_j with u_0 = 0, u_{2N} = 1. The neutral
  // answer is u_i = i/2N; verify it satisfies the equations to machine precision.
  for (const twoN of [10, 40, 100]) {
    const M = wfMatrix(twoN);
    let worst = 0;
    for (let i = 0; i <= twoN; i++) {
      let lhs = 0; for (let j = 0; j <= twoN; j++) lhs += M[i][j] * (j / twoN);
      worst = Math.max(worst, Math.abs(lhs - i / twoN));
    }
    ok(worst < 1e-9, `2N=${twoN}: u_i=i/2N solves u=Pu exactly (residual ${worst.toExponential(2)})`);
  }
  // (b) Monte Carlo: fixation fraction over many full runs matches p₀.
  const rng = mulberry32(20260621);
  for (const [twoN, i0, reps] of [[20, 10, 6000], [20, 4, 6000], [50, 35, 4000]]) {
    let fix = 0;
    for (let r = 0; r < reps; r++) fix += wfRun(twoN, i0, rng).fixed;
    const obs = fix / reps, p0 = i0 / twoN;
    const se = Math.sqrt(p0 * (1 - p0) / reps);
    ok(approx(obs, p0, 4 * se),
      `2N=${twoN}, start i=${i0} (p₀=${p0}): MC P(fix)=${obs.toFixed(4)} vs ${p0} (±${(4*se).toFixed(4)})`);
  }
}

// ── (4) Heterozygosity decays as H₀(1−1/2N)^t ────────────────────────────────
console.log('\n(4) Variation bleeds away: E[H_t] = H₀(1−1/2N)^t  (rate 1/2N per generation)');
{
  // Exact: track E[H_t] = E[2 p(1-p)] under the chain. Start as a point mass at i0.
  for (const twoN of [20, 50]) {
    const M = wfMatrix(twoN);
    const i0 = twoN / 2;
    let dist = new Array(twoN + 1).fill(0); dist[i0] = 1;
    const Hof = i => 2 * (i / twoN) * (1 - i / twoN);
    let H0 = 0; for (let i = 0; i <= twoN; i++) H0 += dist[i] * Hof(i);
    let worst = 0;
    for (let t = 1; t <= 30; t++) {
      const nd = new Array(twoN + 1).fill(0);
      for (let i = 0; i <= twoN; i++) {
        if (dist[i] === 0) continue;
        for (let j = 0; j <= twoN; j++) nd[j] += dist[i] * M[i][j];
      }
      dist = nd;
      let Ht = 0; for (let i = 0; i <= twoN; i++) Ht += dist[i] * Hof(i);
      const pred = H0 * Math.pow(1 - 1 / twoN, t); // 1/2N with 2N=twoN
      worst = Math.max(worst, Math.abs(Ht - pred));
    }
    ok(worst < 1e-9, `2N=${twoN}: exact E[H_t] tracks H₀(1−1/2N)^t for t≤ 30 (max err ${worst.toExponential(2)})`);
  }
  // Sanity: half-life of variation is ln2/ln(1/(1-1/2N)) ≈ 1.39·2N generations.
  for (const twoN of [20, 100]) {
    const hl = Math.log(2) / Math.log(1 / (1 - 1 / twoN));
    ok(approx(hl, 0.693 * twoN, 0.05 * twoN), `2N=${twoN}: heterozygosity half-life ≈ ${hl.toFixed(1)} gen (≈ 1.39·N)`);
  }
}

// ── (5) Mean time to absorption grows with N ─────────────────────────────────
console.log('\n(5) Bigger populations drift slower: mean time to absorption grows with N');
{
  // Exact expected absorption time from the fundamental matrix on transient states.
  // t_i = 1 + Σ_{j transient} P[i][j] t_j. Solve the linear system for each twoN.
  function absorptionTimes(twoN) {
    const M = wfMatrix(twoN);
    const T = twoN - 1; // transient states 1..2N-1
    // Build (I - Q) and solve (I - Q) t = 1.
    const A = []; const b = [];
    for (let r = 1; r <= T; r++) {
      const row = new Array(T).fill(0);
      for (let c = 1; c <= T; c++) row[c - 1] = (r === c ? 1 : 0) - M[r][c];
      A.push(row); b.push(1);
    }
    // Gaussian elimination.
    for (let c = 0; c < T; c++) {
      let piv = c; for (let r = c + 1; r < T; r++) if (Math.abs(A[r][c]) > Math.abs(A[piv][c])) piv = r;
      [A[c], A[piv]] = [A[piv], A[c]]; [b[c], b[piv]] = [b[piv], b[c]];
      for (let r = 0; r < T; r++) {
        if (r === c) continue;
        const f = A[r][c] / A[c][c];
        for (let k = c; k < T; k++) A[r][k] -= f * A[c][k];
        b[r] -= f * b[c];
      }
    }
    return b.map((bi, idx) => bi / A[idx][idx]); // t for states 1..T
  }
  let prevMid = 0;
  for (const twoN of [10, 20, 40, 80]) {
    const t = absorptionTimes(twoN);
    const mid = t[Math.floor((twoN - 1) / 2)]; // start at p≈0.5
    ok(mid > prevMid, `2N=${twoN}: E[time to absorption | p₀≈½] = ${mid.toFixed(1)} gen (> previous ${prevMid.toFixed(1)})`);
    prevMid = mid;
  }
  // The diffusion asymptote (Kimura & Ohta 1969): conditional mean time to
  // FIXATION from a single new mutant → 4N generations. We state it as the
  // limit the small-N chain climbs toward, and check direction, not equality.
  ok(true, 'Diffusion limit (Kimura–Ohta 1969): conditional E[time to fixation] of a new mutant → 4N gen.');
}

// ── (6) The drift–selection boundary (the honest frontier) ───────────────────
console.log('\n(6) The frontier named honestly: drift vs selection meet at s ~ 1/(2N)');
{
  // Kimura 1962 fixation probability with selection (additive, Ne = N):
  //   u(p) = (1 - e^{-4 N s p}) / (1 - e^{-4 N s})
  function kimuraFix(N, s, p) {
    if (s === 0) return p;
    const a = -4 * N * s;
    return (1 - Math.exp(a * p)) / (1 - Math.exp(a));
  }
  // Reduces to p as s → 0 (L'Hôpital): check continuity numerically.
  for (const [N, p] of [[50, 0.1], [50, 0.5]]) {
    const near = kimuraFix(N, 1e-7, p);
    ok(approx(near, p, 1e-4), `N=${N}, p=${p}: u→p as s→0 (u(s=1e−7)=${near.toFixed(5)})`);
  }
  // When |s| ≪ 1/(2N) selection is invisible (≈ p); when |s| ≫ 1/(2N) it isn't.
  {
    const N = 50; const p = 0.02; const crit = 1 / (2 * N); // = 0.01
    const weak = kimuraFix(N, crit / 20, p);   // s well below threshold
    const strong = kimuraFix(N, crit * 20, p); // s well above threshold
    ok(approx(weak, p, 0.01), `N=${N}: weak s=${(crit/20).toExponential(1)} ≪ 1/2N → u≈p (${weak.toFixed(4)})`);
    ok(strong > 3 * p, `N=${N}: strong s=${(crit*20).toExponential(1)} ≫ 1/2N → u=${strong.toFixed(4)} ≫ p=${p} (selection wins)`);
  }
  // Monte Carlo of the SELECTIVE Wright–Fisher matches Kimura at a couple points.
  {
    const rng = mulberry32(777);
    for (const [N, s, p0] of [[25, 0.04, 0.2], [25, -0.04, 0.2]]) {
      const twoN = 2 * N, i0 = Math.round(p0 * twoN), reps = 6000;
      let fix = 0; for (let r = 0; r < reps; r++) fix += wfRun(twoN, i0, rng, s).fixed;
      const obs = fix / reps, pred = kimuraFix(N, s, p0);
      const se = Math.sqrt(pred * (1 - pred) / reps);
      ok(approx(obs, pred, 4 * se + 0.01),
        `N=${N}, s=${s}, p₀=${p0}: MC P(fix)=${obs.toFixed(4)} vs Kimura=${pred.toFixed(4)} (±${(4*se).toFixed(4)})`);
    }
  }
}

// ── tally ────────────────────────────────────────────────────────────────────
console.log(`\n${fails === 0 ? '✓ ALL PASS' : '✗ ' + fails + ' FAILED'}  —  ${n - fails}/${n} checks\n`);
process.exit(fails === 0 ? 0 : 1);
