#!/usr/bin/env node
// verify.mjs — the exact check behind "The Fittest Cannot Breed True"
// (heterozygote advantage / balancing selection at one diploid locus).
//
// Model: one locus, two alleles A (wild-type β-globin, HbA) and S (sickle, HbS),
// random mating (Hardy–Weinberg genotype proportions each generation), constant
// viability selection. Relative genotype fitnesses, heterozygote normalised to 1:
//     w_AA = 1 - s   (s = selection against AA; malaria mortality)
//     w_AS = 1
//     w_SS = 1 - t   (t = selection against SS; sickle-cell anaemia)
// with p = freq(A), q = freq(S) = 1 - p.
//
// The whole page reads its numbers from THIS recursion. Every claim it makes is a
// check below. Run:  node research/heterozygote-advantage/verify.mjs
//
// Sources for the empirical anchor (numbers, not narrative):
//   Haldane JBS (1949) — the malaria hypothesis (mutation & disease resistance).
//   Allison AC (1954) BMJ 1:290 — HbS carriers resist P. falciparum; balanced polymorphism.
//   Textbook fitness estimates for holoendemic malaria (e.g. Hartl & Clark,
//     Principles of Population Genetics; Cavalli-Sforza & Bodmer): w_AA≈0.88, w_SS≈0.1–0.2.

'use strict';

// ---- the shared engine (identical to the one the page runs client-side) --------
// One generation of viability selection. Returns next-gen freq of A.
function stepP(p, s, t) {
  const q = 1 - p;
  const wbar = 1 - s * p * p - t * q * q;      // mean fitness = p²(1-s)+2pq+q²(1-t)
  // p' = (p²·w_AA + pq·w_AS) / wbar = p(1 - s·p)/wbar
  return (p * (1 - s * p)) / wbar;
}
function meanFitness(p, s, t) {
  const q = 1 - p;
  return 1 - s * p * p - t * q * q;
}
// closed-form interior equilibrium (overdominance): p* = t/(s+t), q* = s/(s+t)
function pStar(s, t) { return t / (s + t); }

function iterate(p0, s, t, gens) {
  let p = p0;
  const traj = [p];
  for (let g = 0; g < gens; g++) { p = stepP(p, s, t); traj.push(p); }
  return traj;
}

// ---- test harness --------------------------------------------------------------
let passed = 0, failed = 0;
const fails = [];
function ok(name, cond, detail) {
  if (cond) { passed++; }
  else { failed++; fails.push(name + (detail ? ' — ' + detail : '')); }
}
const close = (a, b, tol = 1e-9) => Math.abs(a - b) <= tol;

// A small, fixed, deterministic PRNG (mulberry32) — no Math.random, so runs are
// bit-for-bit reproducible.
function mulberry32(seed) {
  let a = seed >>> 0;
  return function () {
    a |= 0; a = (a + 0x6D2B79F5) | 0;
    let x = Math.imul(a ^ (a >>> 15), 1 | a);
    x = (x + Math.imul(x ^ (x >>> 7), 61 | x)) ^ x;
    return ((x ^ (x >>> 14)) >>> 0) / 4294967296;
  };
}

// === 1. Allele frequencies are conserved (p' + q' = 1) ==========================
{
  const rng = mulberry32(1);
  let worst = 0;
  for (let i = 0; i < 5000; i++) {
    const p = rng(), s = rng(), t = rng();      // s,t in [0,1)
    const q = 1 - p;
    const wbar = 1 - s * p * p - t * q * q;
    const pn = stepP(p, s, t);
    const qn = (q * (1 - t * q)) / wbar;         // q' recomputed independently as q(1-t·q)/w̄
    worst = Math.max(worst, Math.abs(pn + qn - 1)); // p'+q' must be exactly 1
  }
  ok('1. conservation p\'+q\'=1 (5000 random states)', worst < 1e-12, 'max |p\'+q\'-1| = ' + worst.toExponential(2));
}

// === 2. Closed-form equilibrium p*=t/(s+t) is a fixed point =====================
{
  const cases = [[0.12, 0.86], [0.15, 0.85], [0.3, 0.3], [0.05, 0.95], [0.5, 0.2], [0.9, 0.1]];
  let allFixed = true, detail = '';
  for (const [s, t] of cases) {
    const ps = pStar(s, t);
    const moved = Math.abs(stepP(ps, s, t) - ps);
    if (moved > 1e-12) { allFixed = false; detail = `s=${s},t=${t} moved ${moved.toExponential(2)}`; }
  }
  ok('2. p*=t/(s+t) is an exact fixed point (6 cases)', allFixed, detail);
}

// === 3. Overdominance ⇒ that interior equilibrium is GLOBALLY attracting ========
{
  const s = 0.12, t = 0.86, ps = pStar(s, t);
  let allConverge = true, detail = '';
  for (let k = 1; k <= 99; k++) {                 // start from p0 = 0.01 … 0.99
    const p0 = k / 100;
    const traj = iterate(p0, s, t, 2000);
    const end = traj[traj.length - 1];
    if (!close(end, ps, 1e-6)) { allConverge = false; detail = `p0=${p0} → ${end.toFixed(6)} ≠ p*=${ps.toFixed(6)}`; break; }
  }
  ok('3. overdominance: all 99 interior starts converge to p*', allConverge, detail);
}

// === 4. The equilibrium is a POLYMORPHISM — both alleles kept forever ============
//   q* strictly in (0,1): selection never removes S, and never fixes it either.
{
  const s = 0.12, t = 0.86, qs = 1 - pStar(s, t);
  ok('4. q* is a genuine polymorphism 0<q*<1', qs > 0 && qs < 1, 'q* = ' + qs.toFixed(4));
}

// === 5. Mean fitness increases monotonically to its maximum at p* ===============
//   (the one-locus fundamental theorem: constant-fitness selection hill-climbs w̄.)
{
  const s = 0.12, t = 0.86, ps = pStar(s, t);
  const traj = iterate(0.01, s, t, 3000);
  let monotone = true, detail = '';
  for (let g = 1; g < traj.length; g++) {
    const dw = meanFitness(traj[g], s, t) - meanFitness(traj[g - 1], s, t);
    if (dw < -1e-12) { monotone = false; detail = `Δw̄=${dw.toExponential(2)} at gen ${g}`; break; }
  }
  ok('5a. mean fitness w̄ is non-decreasing every generation', monotone, detail);
  // and the maximum over a fine grid is at p* (± grid spacing)
  let argmax = 0, best = -Infinity;
  for (let k = 0; k <= 100000; k++) { const p = k / 100000; const w = meanFitness(p, s, t); if (w > best) { best = w; argmax = p; } }
  ok('5b. argmax_p w̄(p) equals p* (grid 1e-5)', close(argmax, ps, 1e-4), `argmax=${argmax.toFixed(5)} p*=${ps.toFixed(5)}`);
  // analytic: dw̄/dp = -2sp + 2t(1-p) = 0 ⇒ p = t/(s+t)
  const dwdp = (p) => -2 * s * p + 2 * t * (1 - p);
  ok('5c. dw̄/dp = 0 exactly at p*', close(dwdp(ps), 0, 1e-12), 'dw̄/dp(p*) = ' + dwdp(ps).toExponential(2));
}

// === 6. The genetic (segregation) load — the price paid forever =================
//   At equilibrium w̄* = 1 - s·p*² - t·q*². Load L = 1 - w̄* (het = 1 is the ceiling
//   the population can never reach, because it cannot breed the heterozygote true).
//   Closed form: L = s·t/(s+t).
{
  const s = 0.12, t = 0.86, ps = pStar(s, t), qs = 1 - ps;
  const wbarStar = meanFitness(ps, s, t);
  const L = 1 - wbarStar;
  const Lclosed = (s * t) / (s + t);
  ok('6a. segregation load L = 1 - w̄* = s·t/(s+t)', close(L, Lclosed, 1e-12), `L=${L.toFixed(5)} closed=${Lclosed.toFixed(5)}`);
  // fraction of every generation's births that are the "unfit" homozygotes:
  const tollSS = qs * qs, tollAA = ps * ps;
  ok('6b. births are perpetually re-made unfit: q*²>0 SS and p*²>0 AA each gen',
     tollSS > 0 && tollAA > 0, `SS=${(tollSS * 100).toFixed(1)}%  AA=${(tollAA * 100).toFixed(1)}% of births`);
}

// === 7. Change the environment, change the verdict: malaria off (s=0) ⇒ S purged =
//   The SAME allele that was maintained now declines to extinction. "Fitness" was
//   never a property of the gene — it was a property of gene × environment.
{
  const s = 0, t = 0.86;
  const traj = iterate(0.12, s, t, 5000);   // start at the old equilibrium q≈0.12 (p≈0.88)
  const endQ = 1 - traj[traj.length - 1];
  ok('7. malaria off (s=0): S declines toward extinction', endQ < 0.02 && endQ < (1 - 0.88),
     'q after 5000 gens = ' + endQ.toExponential(2));
  // and it lingers: once malaria is gone S is cost-free in carriers (only SS pays t),
  // so selection sees it only in the rare q² homozygotes — the recessive tail is long.
  // Each further tenfold drop in q takes ~10× as many generations as the last.
  const gensToQ = (target) => { const i = traj.findIndex((p) => (1 - p) <= target); return i < 0 ? Infinity : i; };
  const g06 = gensToQ(0.06), g01 = gensToQ(0.01), g001 = gensToQ(0.001);
  // the tail lengthens: 0.06→0.01 must cost far more generations than 0.12→0.06.
  ok('7b. …but slowly — the recessive tail lengthens as S rarefies',
     (g01 - g06) > (g06 - 0) && g001 > 200,
     `gens to q≤0.06:${g06}  ≤0.01:${g01}  ≤0.001:${g001}`);
}

// === 8. Underdominance is the mirror image: interior equilibrium is UNSTABLE =====
//   If the heterozygote is the WORST genotype (w_AS below both homozygotes), the
//   same interior root exists but repels — outcome depends on the starting side.
{
  const wAA = 1, wAS = 0.7, wSS = 1;         // heterozygote inferior
  function stepGeneral(p) {
    const q = 1 - p;
    const wbar = p * p * wAA + 2 * p * q * wAS + q * q * wSS;
    return (p * p * wAA + p * q * wAS) / wbar;
  }
  // interior root where marginal fitnesses equal: p*(wAA-wAS)+ q*(wAS-wSS)=0
  const a = wAS - wAA, b = wAS - wSS;        // both < 0 (underdominance)
  const pu = b / (a + b);                    // = 0.5 here by symmetry
  function itr(p0) { let p = p0; for (let g = 0; g < 4000; g++) p = stepGeneral(p); return p; }
  const below = itr(pu - 0.02), above = itr(pu + 0.02);
  ok('8. underdominance: interior eq is unstable (bistable fixation)',
     close(below, 0, 1e-4) && close(above, 1, 1e-4),
     `p0=${(pu - 0.02).toFixed(2)}→${below.toFixed(4)}, p0=${(pu + 0.02).toFixed(2)}→${above.toFixed(4)}`);
}

// === 9. The empirical anchor: sickle cell reproduces observed HbS frequency ======
//   With malaria selection s≈0.10–0.15 and SS historically near-lethal (t≈0.8–1.0),
//   q* = s/(s+t) predicts HbS ≈ 0.10–0.16 — the band actually observed in
//   holoendemic-malaria populations (carrier freq 2p*q* ≈ 0.18–0.28).
{
  const band = [];
  for (const s of [0.10, 0.12, 0.15]) {
    for (const t of [0.80, 0.86, 1.0]) {
      band.push(1 - pStar(s, t)); // q* = HbS frequency
    }
  }
  const lo = Math.min(...band), hi = Math.max(...band);
  ok('9. sickle-cell anchor: predicted HbS q* falls in the observed 0.09–0.16 band',
     lo >= 0.09 && hi <= 0.16, `predicted q* range = ${lo.toFixed(3)}–${hi.toFixed(3)}`);
  // the canonical single point (s=0.12, t=0.86): q*≈0.122, carrier 2p*q*≈0.215
  const s = 0.12, t = 0.86, ps = pStar(s, t), qs = 1 - ps;
  ok('9b. canonical point q*≈0.122, carriers 2p*q*≈0.21',
     close(qs, 0.1224, 2e-3) && close(2 * ps * qs, 0.215, 3e-3),
     `q*=${qs.toFixed(4)} carriers=${(2 * ps * qs).toFixed(4)}`);
}

// === 10. The deterministic recursion is the large-N limit of stochastic W–F =====
//   Ties the page to its sibling THE DRIFT: a finite population with selection,
//   averaged over many replicates, tracks the deterministic p'. (Selection here,
//   pure sampling there.)
{
  const s = 0.12, t = 0.86, N = 4000, reps = 400, p0 = 0.4;
  const rng = mulberry32(12345);
  // one stochastic generation: expected genotype (post-selection) freq, then binomial-ish
  // resample 2N gene copies. We use the deterministic post-selection p' as the sampling
  // mean and draw copies ~ Binomial(2N, p') via inverse-CDF-free counting.
  function wfGen(p) {
    const pPrime = stepP(p, s, t);
    let a = 0;
    for (let i = 0; i < 2 * N; i++) if (rng() < pPrime) a++;
    return a / (2 * N);
  }
  let sum = 0;
  for (let r = 0; r < reps; r++) {
    let p = p0; for (let g = 0; g < 30; g++) p = wfGen(p);
    sum += p;
  }
  const meanStoch = sum / reps;
  let pDet = p0; for (let g = 0; g < 30; g++) pDet = stepP(pDet, s, t);
  ok('10. stochastic W–F (N=4000, 400 reps) tracks the deterministic trajectory',
     Math.abs(meanStoch - pDet) < 0.02, `E[p_30] stoch=${meanStoch.toFixed(4)} det=${pDet.toFixed(4)}`);
}

// ---- report --------------------------------------------------------------------
console.log('\nThe Fittest Cannot Breed True — verifier');
console.log('one-locus two-allele viability selection, w_AS = 1, w_AA = 1-s, w_SS = 1-t\n');
console.log(`  p* = t/(s+t),  q* = s/(s+t),  load L = s·t/(s+t)`);
{
  const s = 0.12, t = 0.86, ps = pStar(s, t), qs = 1 - ps;
  console.log(`  canonical sickle point s=${s} t=${t}:  q*(HbS)=${qs.toFixed(4)}  carriers 2p*q*=${(2 * ps * qs).toFixed(4)}  load=${((s * t) / (s + t)).toFixed(4)}\n`);
}
console.log(`  ${passed}/${passed + failed} checks passed`);
if (failed) { console.log('\nFAILED:'); for (const f of fails) console.log('  ✗ ' + f); process.exit(1); }
console.log('  ✓ all checks passed\n');
