// verify.mjs — the check for "The Balance on the Island" (island biogeography).
// Every number the interactive page prints is computed here, and every quantitative
// claim it makes is put to an analytic or Monte-Carlo test. Run:
//     node verify.mjs        # prints the checklist, writes data.json, exits nonzero on fail.
//
// The stratum's thesis, made testable — the MacArthur–Wilson equilibrium theory
// of island biogeography (MacArthur & Wilson 1963, Evolution 17:373; 1967, "The
// Theory of Island Biogeography", Princeton):
//
//   The number of species S on an island is set by a DYNAMIC EQUILIBRIUM between
//   the rate at which NEW species arrive (immigration I, which FALLS as S rises —
//   fewer of the mainland pool are still missing) and the rate at which resident
//   species die out (extinction E, which RISES as S rises — more species, smaller
//   populations each). Where the curves cross, S* is stable — but TURNOVER never
//   stops: species keep being lost and replaced at rate T* = I(S*) = E(S*). A
//   steady mean with a fluctuating count and a churning identity.
//
//   The microscopic engine (this file's spine): treat the P mainland species as
//   independent. A species not on the island colonises at per-species rate m; a
//   resident goes locally extinct at per-species rate e. Then each species is an
//   independent two-state Markov chain, present with stationary probability
//   p = m/(m+e). Therefore the island's species count is EXACTLY
//        S ~ Binomial(P, p),   mean S* = P·m/(m+e),   var = P·p·(1−p),
//   and the macroscopic rates are linear: I(S) = m(P−S), E(S) = e·S, giving the
//   same crossing S* and turnover T* = P·m·e/(m+e). We RECOVER all of this from a
//   from-scratch continuous-time simulation of the P independent chains — the count
//   fluctuates around S* after settling, while the SET keeps turning over.
//
//   The geography:  DISTANCE lowers immigration (smaller m) ⇒ fewer species;
//   AREA lowers extinction (smaller e) ⇒ more species. The near-large corner is
//   richest, the far-small corner poorest — checked by sign of the exact partials.
//
//   The empirical companion: the species–area relation S = c·A^z. The "tenfold
//   area for a doubling of species" rule of thumb is EXACTLY z = log10 2 = 0.30103.
//   The canonical-lognormal theory (Preston 1962; May 1975) predicts z ≈ 0.25 for
//   isolated islands; the empirical band for true islands is ~0.20–0.35. We build a
//   sampled lognormal community, subsample it by "area", and recover
//   z in that band for this seeded example.
//
//   Refs: R. H. MacArthur & E. O. Wilson, Evolution 17 (1963) 373; "The Theory of
//   Island Biogeography", Princeton U.P. (1967). F. W. Preston, Ecology 43 (1962)
//   185 & 410 ("The canonical distribution of commonness and rarity"). R. M. May,
//   in "Ecology and Evolution of Communities" (1975), the z≈0.25 canonical value.
//   M. L. Rosenzweig, "Species Diversity in Space and Time" (1995), the z bands.
//
// Nothing about the answer is assumed. S*, T*, the binomial law, the turnover, the
// monotone geography, and the species–area exponent are all recovered numerically
// and checked against the closed forms.

import { writeFileSync } from 'node:fs';

const checks = [];
const check = (name, pass, detail) => { checks.push({ name, pass: !!pass, detail }); };
const near = (a, b, tol) => Math.abs(a - b) <= tol;

// ── a small seeded PRNG (mulberry32) so pass/fail is reproducible, no Math.random ──
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;
  };
}
const rng = mulberry32(0x15ABCDEF); // a fixed seed, reproducible pass/fail
const expRand = (rate) => -Math.log(1 - rng()) / rate; // exponential waiting time

// ─────────────────────────────────────────────────────────────────────────────
// Closed forms for the linear-rate model.  I(S)=m(P−S)=I0(1−S/P), E(S)=e·S=E0·S/P
// with I0=mP, E0=eP.  Crossing where m(P−S)=eS.
// ─────────────────────────────────────────────────────────────────────────────
const Sstar = (P, m, e) => P * m / (m + e);          // = P·p, p = m/(m+e)
const Tstar = (P, m, e) => P * m * e / (m + e);       // = I(S*) = E(S*)
const pOcc  = (m, e) => m / (m + e);                  // stationary occupancy per species

// ═══ A. the equilibrium — exact algebra vs a numerical root ═════════════════════
{
  const P = 100, m = 0.6, e = 0.9;
  // numeric root of I(S) − E(S) = 0 by bisection, independent of the formula
  const f = (S) => m * (P - S) - e * S;
  let lo = 0, hi = P;
  for (let i = 0; i < 80; i++) { const mid = (lo + hi) / 2; if (f(mid) > 0) lo = mid; else hi = mid; }
  const Snum = (lo + hi) / 2;
  check('S* = P·m/(m+e) matches a from-scratch bisection root of I(S)=E(S)',
    near(Snum, Sstar(P, m, e), 1e-6),
    `bisection S=${Snum.toFixed(6)}, formula P·m/(m+e)=${Sstar(P, m, e).toFixed(6)} (P=${P}, m=${m}, e=${e})`);

  // turnover: at S*, I(S*) must equal E(S*), and both equal T*
  const I_at = m * (P - Sstar(P, m, e)), E_at = e * Sstar(P, m, e);
  check('turnover T* = I(S*) = E(S*) = P·m·e/(m+e) — inflow balances outflow at the crossing',
    near(I_at, E_at, 1e-9) && near(I_at, Tstar(P, m, e), 1e-9),
    `I(S*)=${I_at.toFixed(5)}, E(S*)=${E_at.toFixed(5)}, formula=${Tstar(P, m, e).toFixed(5)}`);
}

// ═══ B. the microscopic engine — a from-scratch CTMC of P independent species ═══
//   Each species flips absent→present (rate m) / present→absent (rate e). We run
//   the exact continuous-time chain by next-event sampling, record the time-average
//   of S(t) and its variance, and count colonisation/extinction events (turnover).
//   Prediction: S is time-stationary Binomial(P,p); mean=S*, var=P·p·(1−p);
//   arrivals and losses together accrue at rate 2·T* on average.
// ─────────────────────────────────────────────────────────────────────────────
let simSummary;
{
  const P = 80, m = 0.5, e = 0.7;
  const present = new Array(P).fill(false); // start empty — like a sterilised island
  let S = 0, t = 0;
  const Tmax = 60000;                        // long run for tight Monte-Carlo error
  const burn = 2000;                          // discard the approach to equilibrium
  let tw = 0, sumS = 0, sumS2 = 0;            // time-weighted moments after burn-in
  let colonis = 0, extinct = 0;               // event counts after burn-in
  let identityChurnPairs = 0;                 // for the "changing identity" check
  const snapAt = 20000; let snapSet = null, snapCount = 0, snapChanged = 0;

  while (t < Tmax) {
    // total rates
    const Rc = m * (P - S), Re = e * S, Rtot = Rc + Re;
    const dt = expRand(Rtot);
    // accumulate time-average over [t, t+dt] at current S (after burn-in)
    if (t >= burn) { const w = Math.min(dt, Tmax - t); tw += w; sumS += S * w; sumS2 += S * S * w; }
    t += dt;
    // choose event
    if (rng() * Rtot < Rc) {
      // a colonisation: pick a uniformly-random ABSENT species
      let k = Math.floor(rng() * (P - S));
      for (let i = 0; i < P; i++) { if (!present[i]) { if (k-- === 0) { present[i] = true; break; } } }
      S++; if (t >= burn) colonis++;
    } else {
      // an extinction: pick a uniformly-random PRESENT species
      let k = Math.floor(rng() * S);
      for (let i = 0; i < P; i++) { if (present[i]) { if (k-- === 0) { present[i] = false; break; } } }
      S--; if (t >= burn) extinct++;
    }
    // snapshot the identity set once, to measure churn a fixed time later
    if (snapSet === null && t >= snapAt) { snapSet = present.slice(); snapCount = S; }
    if (snapSet !== null && snapChanged === 0 && t >= snapAt + 400) {
      for (let i = 0; i < P; i++) if (present[i] !== snapSet[i]) snapChanged++;
      identityChurnPairs = 1;
    }
  }
  const meanS = sumS / tw, varS = sumS2 / tw - meanS * meanS;
  const eventRate = (colonis + extinct) / (Tmax - burn); // = 2·T*
  const p = pOcc(m, e);
  const S_pred = Sstar(P, m, e), var_pred = P * p * (1 - p), rate_pred = 2 * Tstar(P, m, e);

  check('simulated island count settles onto S* = P·m/(m+e) (independent-species CTMC, from empty)',
    near(meanS, S_pred, 0.6),
    `time-avg S = ${meanS.toFixed(3)} vs S* = ${S_pred.toFixed(3)} (P=${P}, m=${m}, e=${e})`);
  check('its fluctuations match the exact Binomial(P,p) variance P·p·(1−p) — the count is a binomial, not a constant',
    near(varS, var_pred, var_pred * 0.12),
    `Var(S) = ${varS.toFixed(2)} vs P·p(1−p) = ${var_pred.toFixed(2)}`);
  check('turnover never stops: events accrue at 2·T* even though the count is stationary',
    near(eventRate, rate_pred, rate_pred * 0.06),
    `colonisations+extinctions per unit time = ${eventRate.toFixed(2)} vs 2·T* = ${rate_pred.toFixed(2)}`);
  check('species identity changes after a snapshot near S*',
    snapChanged > 0 && Math.abs(snapCount - S_pred) < 3 * Math.sqrt(var_pred),
    `${snapChanged} of ${P} species changed presence over a short window; snapshot count ${snapCount} (S*≈${S_pred.toFixed(0)})`);

  simSummary = { P, m, e, meanS: +meanS.toFixed(3), Sstar: +S_pred.toFixed(3),
    varS: +varS.toFixed(2), varPred: +var_pred.toFixed(2),
    eventRate: +eventRate.toFixed(2), ratePred: +rate_pred.toFixed(2),
    identitySwapped: snapChanged, of: P };
}

// ═══ C. the geography — the sign of the exact partials (distance & area effects) ═
{
  const P = 100;
  // Distance lowers immigration m. Area lowers extinction e. Sign of dS*/dm, dS*/de.
  const dS_dm = (P, m, e) => P * e / ((m + e) * (m + e)); // > 0  ⇒ less distance (bigger m) ⇒ more species
  const dS_de = (P, m, e) => -P * m / ((m + e) * (m + e)); // < 0  ⇒ less area (bigger e) ⇒ fewer species
  const m0 = 0.5, e0 = 0.5;
  check('DISTANCE effect: dS*/dm > 0 — a nearer island (higher immigration m) holds MORE species',
    dS_dm(P, m0, e0) > 0,
    `dS*/dm = P·e/(m+e)² = ${dS_dm(P, m0, e0).toFixed(2)} > 0`);
  check('AREA effect: dS*/de < 0 — a larger island (lower extinction e) holds MORE species',
    dS_de(P, m0, e0) < 0,
    `dS*/de = −P·m/(m+e)² = ${dS_de(P, m0, e0).toFixed(2)} < 0`);

  // the 2×2 corners: near/far × large/small, ordered richest→poorest
  const mNear = 0.9, mFar = 0.3, eLarge = 0.3, eSmall = 0.9;
  const NL = Sstar(P, mNear, eLarge), NS = Sstar(P, mNear, eSmall),
        FL = Sstar(P, mFar, eLarge),  FS = Sstar(P, mFar, eSmall);
  check('the 2×2 ordering holds: near-large richest, far-small poorest (S*_NL > S*_NS,S*_FL > S*_FS)',
    NL > NS && NL > FL && NS > FS && FL > FS,
    `near-large ${NL.toFixed(0)} > {near-small ${NS.toFixed(0)}, far-large ${FL.toFixed(0)}} > far-small ${FS.toFixed(0)}`);
}

// ═══ D. the species–area exponent z ═════════════════════════════════════════════
// D1. the "×10 area ⇒ ×2 species" rule of thumb IS exactly z = log10 2.
{
  const z = Math.log10(2);
  check('the "tenfold area for a doubling of species" rule is EXACTLY z = log₁₀2 = 0.30103…',
    near(z, 0.30103, 1e-5) && near(Math.pow(10, z), 2.0, 1e-9),
    `z = log₁₀2 = ${z.toFixed(5)}, and 10^z = ${Math.pow(10, z).toFixed(6)}`);
}
// D2. empirical band z∈[0.20,0.35] ⇒ tenfold area multiplies species by [1.585, 2.239].
{
  const lo = Math.pow(10, 0.20), hi = Math.pow(10, 0.35);
  check('empirical island band z ∈ [0.20, 0.35] ⇒ ×10 area multiplies species by ×[1.58, 2.24]',
    near(lo, 1.5849, 1e-3) && near(hi, 2.2387, 1e-3),
    `10^0.20 = ${lo.toFixed(4)}, 10^0.35 = ${hi.toFixed(4)}`);
}
// D3. build a sampled lognormal community, subsample by area, and fit z.
//   In this example, "area" ∝ number of individuals
//   sampled; count species present (≥1 individual); regress log10 S on log10 A.
let zFit;
{
  const nSpeciesPool = 4000;
  // sampled lognormal: log-abundances ~ Normal. Draw abundances (relative), then
  // give the community a huge individual count and sample fractions ∝ area.
  const logAb = [];
  for (let i = 0; i < nSpeciesPool; i++) {
    // Box–Muller normal from the seeded rng
    const u1 = Math.max(1e-12, rng()), u2 = rng();
    const g = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
    logAb.push(g * 2.0);                 // log-abundance standard deviation = 2
  }
  const ab = logAb.map((x) => Math.exp(x));
  const tot = ab.reduce((s, x) => s + x, 0);
  const prob = ab.map((x) => x / tot);   // relative abundance = P(an individual is species i)
  // areas span three decades; individuals sampled ∝ area
  const areas = [], Scount = [];
  const Nfull = 2_000_000;               // individuals on the largest "island"
  for (let d = 0; d <= 12; d++) {
    const A = Math.pow(10, d / 4);        // area, ×10 every 4 steps → 3 decades
    const Nind = Nfull * A / Math.pow(10, 3);
    // expected species with ≥1 individual = Σ (1 − (1−p_i)^Nind); use the exact expectation
    let Sexp = 0;
    for (let i = 0; i < nSpeciesPool; i++) Sexp += 1 - Math.pow(1 - prob[i], Nind);
    if (Sexp > 2 && Sexp < nSpeciesPool - 2) { areas.push(Math.log10(A)); Scount.push(Math.log10(Sexp)); }
  }
  // ordinary least squares slope = z
  const n = areas.length, mx = areas.reduce((s, x) => s + x, 0) / n, my = Scount.reduce((s, x) => s + x, 0) / n;
  let sxy = 0, sxx = 0;
  for (let i = 0; i < n; i++) { sxy += (areas[i] - mx) * (Scount[i] - my); sxx += (areas[i] - mx) * (areas[i] - mx); }
  zFit = sxy / sxx;
  check('a sampled lognormal community, subsampled by area, recovers z in the island band [0.20,0.35]',
    zFit >= 0.20 && zFit <= 0.35,
    `OLS slope of log₁₀S on log₁₀A over 3 decades: z = ${zFit.toFixed(3)} (sampled lognormal community)`);
}

// ═══ report ═════════════════════════════════════════════════════════════════════
const data = {
  model: 'MacArthur–Wilson dynamic equilibrium; P independent species, colonise at m, go extinct at e',
  equilibrium: {
    Sstar_formula: 'S* = P·m/(m+e) = P·p,  p = m/(m+e)',
    Tstar_formula: 'T* = I(S*) = E(S*) = P·m·e/(m+e)',
    stationaryLaw: 'S ~ Binomial(P, p): mean P·p, variance P·p·(1−p)',
  },
  simulation: simSummary,
  geography: {
    distanceEffect: 'dS*/dm = P·e/(m+e)² > 0  (nearer ⇒ more species)',
    areaEffect: 'dS*/de = −P·m/(m+e)² < 0  (larger ⇒ more species)',
    corners: 'near-large richest → far-small poorest',
  },
  speciesArea: {
    ruleOfThumb: '×10 area ⇒ ×2 species  ⟺  z = log₁₀2 = 0.30103',
    empiricalBand: 'true islands z ≈ 0.20–0.35 (Rosenzweig 1995)',
    sampledCommunity: '4000 species; log-abundances sampled from Normal(0, 2²); expected richness from samples proportional to area',
    zRecovered: +zFit.toFixed(3),
  },
};
writeFileSync(new URL('./data.json', import.meta.url), JSON.stringify(data, null, 2));

const pass = checks.filter((c) => c.pass).length;
console.log('\n  THE BALANCE ON THE ISLAND — verification (island biogeography)');
console.log('  ' + '─'.repeat(66));
for (const c of checks) console.log(`  ${c.pass ? '✓' : '✗'} ${c.name}\n      ${c.detail}`);
console.log('  ' + '─'.repeat(66));
console.log(`  ${pass}/${checks.length} checks green\n`);
console.log('  key numbers (all printed on the page):');
console.log(`    equilibrium         S* = P·m/(m+e)      turnover T* = P·m·e/(m+e)`);
console.log(`    stationary law      S ~ Binomial(P, m/(m+e)): count fluctuates around S*, identity churns`);
console.log(`    simulation          mean S = ${simSummary.meanS} vs S* = ${simSummary.Sstar}; ${simSummary.identitySwapped}/${simSummary.of} species changed presence since a snapshot`);
console.log(`    species–area law    ×10 area ⇒ ×2 species  ⟺  z = log₁₀2 = 0.30103`);
console.log(`    z recovered         ${zFit.toFixed(3)}  (sampled lognormal community; island band 0.20–0.35)`);
process.exit(pass === checks.length ? 0 : 1);
