#!/usr/bin/env node
// Verifier for the stratum "The Tanks That Counted Themselves"
//   page: src/content/strata/the-tanks-that-counted-themselves.md (wrapped markdown)
//   live: https://artwaste.land/strata/the-tanks-that-counted-themselves/
//
// The German tank problem. In WWII the Allies estimated German monthly tank
// production from serial numbers in captured records and on inspected tanks.
// The clean model: a month's tanks are numbered 1..N (N unknown); you observe a
// sample of k distinct serials, the largest being m; estimate N. The page rests
// on three claims, each proven here end to end:
//
//   1. The obvious estimator — "N is at least the biggest serial I've seen", the
//      maximum-likelihood estimate m — is BIASED LOW, by exactly (N-k)/(k+1).
//   2. The minimum-variance unbiased estimator is  N̂ = m + (m-k)/k = m(k+1)/k - 1
//      ("the maximum plus the average gap"). It is unbiased (proven exactly AND by
//      Monte Carlo), and its variance is (N-k)(N+1) / [k(k+2)] — falling like ~N²/k²,
//      vastly tighter than the also-unbiased "twice the sample mean" estimator
//      (variance ~N²/(3k)). One well-chosen statistic beats the average.
//   3. The Bayesian posterior (likelihood ∝ 1/C(N,k), flat prior on N≥m) has mean
//      (m-1)(k-1)/(k-2) for k≥3 — verified against a direct truncated sum — and the
//      frequentist and Bayesian estimates agree closely.
//
// And it checks the HISTORY that makes the method famous: the Ruggles & Brodie
// (1947) monthly-production table: statistical estimate vs. August 1942 Allied
// intelligence estimate vs. the actual German records, recomputing each difference.
// Those three rows and the conditional Panther tyre-mould pair (270 / 276)
// are CITED DATA, stored here and only arithmetic'd upon; their provenance lives in
// the stratum's Sources. Everything else is a property of the model, controlled by
// this file.
//
// Run:  node research/the-tanks-that-counted-themselves/verify.mjs
// Exit: 0 if every check passes, 1 otherwise. No dependencies (Node 18+).

import { writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";

let pass = 0, fail = 0;
function check(label, cond, got) {
  if (cond) { pass++; console.log(`  ok   ${label}`); }
  else { fail++; console.log(`  FAIL ${label}` + (got !== undefined ? `  (got: ${JSON.stringify(got)})` : "")); }
}
const round = (x, d = 4) => Math.round(x * 10 ** d) / 10 ** d;
const approx = (a, b, tol) => Math.abs(a - b) <= tol;

// ---- a small deterministic RNG so every run reproduces the same figures ------
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;
  };
}

// draw k DISTINCT integers from 1..N without replacement (partial Fisher–Yates)
function sampleWithoutReplacement(N, k, rng) {
  const idx = new Map(); // sparse permutation
  const get = (i) => (idx.has(i) ? idx.get(i) : i);
  const out = [];
  for (let i = 0; i < k; i++) {
    const j = i + Math.floor(rng() * (N - i)); // i..N-1
    const vi = get(i), vj = get(j);
    idx.set(i, vj); idx.set(j, vi);
    out.push(vj + 1); // the element now at position i is the one selected — 1-based serial
  }
  return out;
}

// ---- the estimators ----------------------------------------------------------
const mleMax      = (s) => Math.max(...s);                       // biased low
const mvue        = (s) => { const m = Math.max(...s), k = s.length; return m + (m - k) / k; };
const mvueAlt     = (s) => { const m = Math.max(...s), k = s.length; return m * (k + 1) / k - 1; };
const twiceMean   = (s) => 2 * (s.reduce((a, b) => a + b, 0) / s.length) - 1; // unbiased, noisier

// ============================================================================
console.log("\nThe Tanks That Counted Themselves — verifier\n");

// === 0 · the two MVUE forms are the same identity ===========================
{
  let same = true;
  const rng = mulberry32(7);
  for (let t = 0; t < 2000; t++) {
    const N = 50 + Math.floor(rng() * 500), k = 3 + Math.floor(rng() * 20);
    if (k > N) continue;
    const s = sampleWithoutReplacement(N, k, rng);
    if (!approx(mvue(s), mvueAlt(s), 1e-9)) same = false;
  }
  check("MVUE  m + (m-k)/k  ==  m(k+1)/k - 1  (the 'max + average gap' identity)", same);
}

// === 1 · the worked single example the prose narrates ========================
// One simulated month: choose N tanks numbered 1..N, then draw k serials.
const N0 = 270;                 // echoes the Panther road-wheel estimate
const k0 = 15;
const sample0 = sampleWithoutReplacement(N0, k0, mulberry32(20260619));
const m0 = mleMax(sample0);
const est0 = {
  observed: [...sample0].sort((a, b) => a - b),
  max_m: m0,
  k: k0,
  mle_max: m0,
  mvue: round(mvue(sample0), 2),
  twiceMean: round(twiceMean(sample0), 2),
  trueN: N0,
};
check(`worked sample: k=${k0} serials drawn from 1..${N0}, largest seen m=${m0}`, m0 <= N0 && m0 >= k0);
check(`  MLE (= max = ${m0}) is at or below the truth ${N0} (it can never exceed what was seen)`, m0 <= N0);
check(`  MVUE = ${est0.mvue}  (max ${m0} + average gap ${round((m0 - k0) / k0, 2)})`, est0.mvue > m0);

// === 2 · MLE bias is exactly -(N-k)/(k+1)  (exact distribution of the max) ====
// P(max = j) = C(j-1,k-1)/C(N,k),  j = k..N.  E[max] = k(N+1)/(k+1).
function lnFactTable(n) { const t = [0]; for (let i = 1; i <= n; i++) t[i] = t[i - 1] + Math.log(i); return t; }
function exactMaxMoments(N, k) {
  const LF = lnFactTable(N);
  const lnC = (n, r) => (r < 0 || r > n) ? -Infinity : LF[n] - LF[r] - LF[n - r];
  const lnDen = lnC(N, k);
  let E = 0, E2 = 0, psum = 0;
  for (let j = k; j <= N; j++) {
    const p = Math.exp(lnC(j - 1, k - 1) - lnDen);
    psum += p; E += j * p; E2 += j * j * p;
  }
  return { E, E2, varr: E2 - E * E, psum };
}
{
  const N = 270, k = 15;
  const ex = exactMaxMoments(N, k);
  check("max distribution P(max=j)=C(j-1,k-1)/C(N,k) sums to 1", approx(ex.psum, 1, 1e-9), round(ex.psum, 9));
  const expectedMax = k * (N + 1) / (k + 1);
  check(`E[max] = k(N+1)/(k+1) = ${round(expectedMax, 4)}  (exact sum agrees)`, approx(ex.E, expectedMax, 1e-6), round(ex.E, 6));
  const bias = ex.E - N;
  check(`MLE bias = E[max]-N = -(N-k)/(k+1) = ${round(-(N - k) / (k + 1), 4)}`, approx(bias, -(N - k) / (k + 1), 1e-6), round(bias, 6));
  // exact variance of the MVUE estimator = ((k+1)/k)^2 * Var(max)
  const varMVUE_exact = ((k + 1) / k) ** 2 * ex.varr;
  const varMVUE_formula = (N - k) * (N + 1) / (k * (k + 2));
  check(`Var(N̂_MVUE) = (N-k)(N+1)/[k(k+2)] = ${round(varMVUE_formula, 2)}  (exact agrees)`,
        approx(varMVUE_exact, varMVUE_formula, 1e-4), round(varMVUE_exact, 4));
}

// === 3 · Monte Carlo: the MVUE is unbiased; the MLE is not; MVUE far tighter ==
const MC = {};
{
  const N = 270, k = 15, T = 400000;
  const rng = mulberry32(424242);
  let sMle = 0, sMvue = 0, sTwice = 0;
  let s2Mvue = 0, s2Twice = 0, s2Mle = 0;
  for (let t = 0; t < T; t++) {
    const s = sampleWithoutReplacement(N, k, rng);
    const a = mleMax(s), b = mvue(s), c = twiceMean(s);
    sMle += a; sMvue += b; sTwice += c;
    s2Mle += (a - N) ** 2; s2Mvue += (b - N) ** 2; s2Twice += (c - N) ** 2;
  }
  const meanMle = sMle / T, meanMvue = sMvue / T, meanTwice = sTwice / T;
  const mseMvue = s2Mvue / T, mseTwice = s2Twice / T, mseMle = s2Mle / T;
  MC.N = N; MC.k = k; MC.trials = T;
  MC.meanMLE = round(meanMle, 2); MC.meanMVUE = round(meanMvue, 2); MC.meanTwiceMean = round(meanTwice, 2);
  MC.rmseMLE = round(Math.sqrt(mseMle), 2);
  MC.rmseMVUE = round(Math.sqrt(mseMvue), 2);
  MC.rmseTwiceMean = round(Math.sqrt(mseTwice), 2);
  MC.efficiencyVsTwiceMean = round(mseTwice / mseMvue, 2);

  check(`MC: MVUE mean ≈ N (${MC.meanMVUE} ≈ 270) — unbiased`, approx(meanMvue, N, 0.6), MC.meanMVUE);
  check(`MC: "twice the mean" mean ≈ N (${MC.meanTwiceMean} ≈ 270) — also unbiased`, approx(meanTwice, N, 0.6), MC.meanTwiceMean);
  check(`MC: MLE (max) mean = ${MC.meanMLE} < N — biased LOW (predicted ${round(N - (N - k) / (k + 1), 2)})`,
        meanMle < N - 5 && approx(meanMle, N - (N - k) / (k + 1), 0.6), MC.meanMLE);
  check(`MC: MVUE is far tighter than "twice the mean" (RMSE ${MC.rmseMVUE} vs ${MC.rmseTwiceMean}; ${MC.efficiencyVsTwiceMean}× lower MSE)`,
        mseMvue < mseTwice, MC.efficiencyVsTwiceMean);
  // MC RMSE of MVUE should match sqrt of the closed-form variance
  const sdFormula = Math.sqrt((N - k) * (N + 1) / (k * (k + 2)));
  check(`MC: MVUE RMSE ${MC.rmseMVUE} ≈ closed-form SD ${round(sdFormula, 2)}`, approx(Math.sqrt(mseMvue), sdFormula, 0.7), round(sdFormula, 2));
}

// === 3b · the "5.65×" edge is an EXACT closed form: (k+2)/3, free of N =========
// The MC above measured the MVUE's efficiency over "twice the mean" at ≈5.65.
// That number is not empirical: both estimators are unbiased, so their MSEs are
// their variances, and the ratio has a clean closed form. For sampling k distinct
// serials without replacement from 1..N, the sample mean has the finite-population
// variance σ²/k · (N-k)/(N-1) with σ² = (N²-1)/12, so
//   Var(2·mean - 1) = 4·Var(mean) = (N+1)(N-k) / (3k).
// Against Var(N̂_MVUE) = (N-k)(N+1)/[k(k+2)], the ratio is
//   Var(twiceMean) / Var(MVUE) = (k+2)/3   — independent of N entirely.
// So "using all the data" loses by a factor that depends only on how many tanks
// you caught, not on how many were built. (At k=15 that is exactly 17/3 = 5.667,
// which is the ≈5.65 the Monte Carlo lands on, up to sampling noise.)
const EXACT = {};
{
  const N = 270, k = 15;
  const varMVUE      = (N - k) * (N + 1) / (k * (k + 2));
  const varTwiceMean = (N + 1) * (N - k) / (3 * k);
  const ratioFormula = (k + 2) / 3;
  EXACT.k = k; EXACT.N = N;
  EXACT.varMVUE = round(varMVUE, 4);
  EXACT.varTwiceMean = round(varTwiceMean, 4);
  EXACT.sdMVUE = round(Math.sqrt(varMVUE), 2);
  EXACT.sdTwiceMean = round(Math.sqrt(varTwiceMean), 2);
  EXACT.efficiencyRatio_closedForm = round(ratioFormula, 4);
  check(`Var(2·mean-1) = (N+1)(N-k)/(3k) = ${EXACT.varTwiceMean}  (SD ${EXACT.sdTwiceMean}; matches the MC RMSE ${MC.rmseTwiceMean})`,
        approx(Math.sqrt(varTwiceMean), MC.rmseTwiceMean, 0.7), EXACT.varTwiceMean);
  check(`efficiency Var(twiceMean)/Var(MVUE) = (k+2)/3 = ${EXACT.efficiencyRatio_closedForm}  (exact; MC measured ${MC.efficiencyVsTwiceMean}×)`,
        approx(varTwiceMean / varMVUE, ratioFormula, 1e-9) && approx(ratioFormula, MC.efficiencyVsTwiceMean, 0.2),
        round(varTwiceMean / varMVUE, 6));
  // the ratio really is free of N: check it at three wildly different N
  let nFree = true;
  for (const NN of [80, 5000, 999999]) {
    const r = ((NN + 1) * (NN - k) / (3 * k)) / ((NN - k) * (NN + 1) / (k * (k + 2)));
    if (!approx(r, ratioFormula, 1e-9)) nFree = false;
  }
  check(`the (k+2)/3 ratio is independent of N (identical at N=80, 5000, 999999)`, nFree);
}

// === 4 · Bayesian posterior: mean (m-1)(k-1)/(k-2) vs a direct truncated sum ===
const BAYES = {};
{
  const m = m0, k = k0;              // use the worked sample's statistics
  // posterior ∝ t_N = 1/C(N,k) for N ≥ m. Iterate t_{N+1}/t_N = (N+1-k)/(N+1).
  const lnC0 = (() => { // ln C(m,k)
    let s = 0; for (let i = 0; i < k; i++) s += Math.log(m - i) - Math.log(i + 1); return s;
  })();
  let t = Math.exp(-lnC0);          // t_m = 1/C(m,k)
  let Z = 0, ZN = 0, ZN2 = 0;
  const Nmax = m + 200000;          // far out enough that the tail is negligible
  const cdf = [];
  for (let Nn = m; Nn <= Nmax; Nn++) {
    Z += t; ZN += Nn * t; ZN2 += Nn * Nn * t;
    cdf.push([Nn, Z]);
    t *= (Nn + 1 - k) / (Nn + 1);
  }
  const postMean = ZN / Z;
  const postVar = ZN2 / Z - postMean ** 2;
  const closed = (m - 1) * (k - 1) / (k - 2);
  // a nominal 95% credible interval from the 2.5% and 97.5% discrete quantiles
  const q = (p) => { const target = p * Z; for (const [Nn, c] of cdf) if (c >= target) return Nn; return Nmax; };
  BAYES.m = m; BAYES.k = k;
  BAYES.posteriorMean_sum = round(postMean, 2);
  BAYES.posteriorMean_closedForm = round(closed, 2);
  BAYES.credible95 = [q(0.025), q(0.975)];
  BAYES.trueN = N0;
  check(`Bayesian posterior mean (truncated sum) ${BAYES.posteriorMean_sum} matches closed form (m-1)(k-1)/(k-2) = ${BAYES.posteriorMean_closedForm}`,
        approx(postMean, closed, 0.05), BAYES.posteriorMean_sum);
  check(`Bayesian nominal 95% credible interval [${BAYES.credible95[0]}, ${BAYES.credible95[1]}] contains the truth ${N0}`,
        BAYES.credible95[0] <= N0 && N0 <= BAYES.credible95[1], BAYES.credible95);
  check(`frequentist MVUE (${est0.mvue}) and Bayesian mean (${BAYES.posteriorMean_sum}) agree to within a few percent`,
        Math.abs(est0.mvue - postMean) / N0 < 0.06, { mvue: est0.mvue, bayes: BAYES.posteriorMean_sum });
}

// === 5 · the history: Ruggles & Brodie (1947) monthly tank production ==========
// CITED DATA (see Sources). Only arithmetic is performed here.
const HIST = [
  { month: "June 1940",   statistical: 169, intelligence: 1000, german: 122 },
  { month: "June 1941",   statistical: 244, intelligence: 1550, german: 271 },
  { month: "August 1942", statistical: 327, intelligence: 1550, german: 342 },
];
const histRows = HIST.map((r) => ({
  ...r,
  statErrPct: round(100 * (r.statistical - r.german) / r.german, 1),
  intelOverFactor: round(r.intelligence / r.german, 1),
}));
{
  // the statistical method is, in every row, far closer to the truth than intelligence
  let statBeatsIntel = true, intelAlwaysHigh = true;
  for (const r of histRows) {
    if (Math.abs(r.statistical - r.german) >= Math.abs(r.intelligence - r.german)) statBeatsIntel = false;
    if (r.intelligence <= r.german) intelAlwaysHigh = false;
  }
  check("history: in all three months the statistical estimate is closer to the German records than intelligence", statBeatsIntel);
  check("history: intelligence overestimated in all three months (4.5×–8.2× the true figure)", intelAlwaysHigh);
  const meanStatErr = round(histRows.reduce((a, r) => a + Math.abs(r.statErrPct), 0) / histRows.length, 1);
  const meanIntelFactor = round(histRows.reduce((a, r) => a + r.intelOverFactor, 0) / histRows.length, 1);
  check(`history: mean |statistical error| ≈ ${meanStatErr}%, mean intelligence overshoot ≈ ${meanIntelFactor}×`,
        meanStatErr < 25 && meanIntelFactor > 4, { meanStatErr, meanIntelFactor });
  HIST.summary = { meanStatErrPct: meanStatErr, meanIntelOverFactor: meanIntelFactor };
}

// Panther tyre-mould pair (cited, Ruggles and Brodie pp. 82-83).
// 270 per month assumes tank assembly at bogie-wheel production capacity,
// with replacement use allowed for; 276 is recorded output in February 1944.
const PANTHER = {
  month: "February 1944", estimated: 270, actual: 276,
  estimateAssumption: "tank assembly at bogie-wheel production capacity, with replacement use allowed for",
};
PANTHER.relDifferencePct = round(100 * Math.abs(PANTHER.estimated - PANTHER.actual) / PANTHER.actual, 1);
check(`Panther conditional capacity estimate 270 vs recorded output 276: ${PANTHER.relDifferencePct}% difference (cited pair)`, PANTHER.relDifferencePct < 3);

// === artifact ================================================================
const artifact = {
  generatedBy: "research/the-tanks-that-counted-themselves/verify.mjs",
  model: "tanks numbered 1..N; observe k distinct serials, largest m; estimate N",
  estimators: {
    mle_max: "m  — maximum likelihood; biased low by (N-k)/(k+1)",
    mvue: "m + (m-k)/k = m(k+1)/k - 1  — minimum-variance unbiased ('max + average gap')",
    twiceMean: "2·mean - 1  — unbiased but far noisier",
  },
  workedExample: est0,
  exactLaws: {
    expectedMax: "E[max] = k(N+1)/(k+1)",
    mleBias: "-(N-k)/(k+1)",
    mvueVariance: "(N-k)(N+1) / [k(k+2)]  (~ N²/k²)",
  },
  monteCarlo: MC,
  exactEfficiency: EXACT,
  bayes: BAYES,
  history: { rugglesBrodie1947: histRows, summary: HIST.summary, pantherRoadWheels: PANTHER },
};
const here = dirname(fileURLToPath(import.meta.url));
writeFileSync(join(here, "artifact.json"), JSON.stringify(artifact, null, 2) + "\n");

console.log(`\n  artifact → research/the-tanks-that-counted-themselves/artifact.json`);
console.log(`\n${pass}/${pass + fail} checks passed${fail ? `, ${fail} FAILED` : ""}.\n`);
process.exit(fail ? 1 : 0);
