#!/usr/bin/env node
// verify.mjs — The ergodicity gap: a positive-expected-value gamble that ruins
// almost every individual player. Every number the page shows is recomputed here
// from first principles (exact where a closed form exists; a seeded Monte-Carlo
// cross-check where it helps). Run:  node research/ergodicity-gap/verify.mjs
//
// THE GAMBLE (Peters' canonical multiplicative coin, Phil. Trans. R. Soc. A 2011):
//   each round, wealth is multiplied by U=1.5 with prob 1/2, or D=0.6 with prob 1/2.
//   Bet a fraction f of wealth and the per-round factor is (1 + f*0.5) or (1 - f*0.4);
//   f = 1 is the all-in game (1.5 / 0.6).
//
// THE TWO GROWTH RATES that must NOT be conflated:
//   · ENSEMBLE-average growth  = ln E[m]      (the mean over parallel players)
//   · TIME-average growth      = E[ln m]      (what one player gets over time)
//   For an ADDITIVE process these coincide (ergodic). For this MULTIPLICATIVE one
//   they diverge — the process is NON-ergodic — and that gap is the whole story.
//
// Sources: J. L. Kelly Jr., "A New Interpretation of Information Rate," Bell Syst.
//   Tech. J. 35 (1956) 917-926. D. Bernoulli (1738), Sommer trans., Econometrica 22
//   (1954) 23-36. O. Peters, "The time resolution of the St Petersburg paradox,"
//   Phil. Trans. R. Soc. A 369 (2011) 4913-4931; O. Peters, "The ergodicity
//   problem in economics," Nature Physics 15 (2019) 1216-1221. T. Cover & J. Thomas,
//   Elements of Information Theory (2006), ch. 6 (gambling & data compression).

'use strict';

const U = 1.5;      // up factor  (+50%)
const D = 0.6;      // down factor (-40%)
const P = 0.5;      // fair coin
const UP_RET = U - 1;   // +0.5  gain per unit staked on an up move
const DN_RET = 1 - D;   // +0.4  loss per unit staked on a down move

let pass = 0, fail = 0;
const near = (a, b, tol = 1e-9) => Math.abs(a - b) <= tol;
function check(name, got, want, tol = 1e-9) {
  const ok = (typeof want === 'number') ? near(got, want, tol) : (got === want);
  (ok ? pass++ : fail++);
  const g = typeof got === 'number' ? got.toPrecision(10) : String(got);
  const w = typeof want === 'number' ? want.toPrecision(10) : String(want);
  console.log(`${ok ? '  ok  ' : ' FAIL '} ${name}: ${g}${ok ? '' : `   (want ${w})`}`);
}

// ---- exact-ish rational for E[m] = 1.05 ----------------------------------
// E[m] = 1/2*3/2 + 1/2*3/5 = 3/4 + 3/10 = 15/20 + 6/20 = 21/20.
const Em = P * U + (1 - P) * D;
console.log('== 1. The ensemble average (the mean over parallel players) ==');
check('E[m] = 21/20', Em, 21 / 20);
check('ensemble growth per round = +5%', Em - 1, 0.05);
check('ensemble wealth after 100 rounds = 1.05^100', Math.pow(Em, 100), 131.5012578, 5e-6);

// ---- the time-average growth: E[ln m] ------------------------------------
const gTime = P * Math.log(U) + (1 - P) * Math.log(D);   // per round, in log-space
const factorTime = Math.exp(gTime);                       // typical per-round factor
console.log('\n== 2. The time average (what one player gets over time) ==');
check('E[ln m] per round', gTime, -0.05268026, 1e-7);
check('typical per-round factor = sqrt(U*D) = sqrt(0.9)', factorTime, Math.sqrt(U * D), 1e-12);
check('U*D = 0.9 (a down+up pair loses 10%)', U * D, 0.9);
check('time-average growth per round = -5.13%', factorTime - 1, -0.05131670, 1e-7);
check('time and ensemble growth have OPPOSITE sign', Math.sign(gTime) * Math.sign(Math.log(Em)), -1);

// ---- almost every path decays; the mean is carried by rare winners --------
// You need up-fraction phi = ln(1/D)/ln(U/D) just to break even, but a fair coin
// delivers only 1/2 < phi, so P(ahead) -> 0 as n -> infinity.
const phi = Math.log(1 / D) / Math.log(U / D);
console.log('\n== 3. The break-even fraction of heads (a fair coin never reaches it) ==');
check('break-even up-fraction phi = ln(1/0.6)/ln(2.5)', phi, 0.5574929, 1e-6);
check('phi > 1/2  (so the typical path loses)', phi > 0.5, true);

// smallest k of n=100 up-moves that leaves you at or above your start
function kNeeded(n) {
  for (let k = 0; k <= n; k++) if (k * Math.log(U) + (n - k) * Math.log(D) >= -1e-12) return k;
  return n + 1;
}
check('n=100: need k>=56 up-moves to break even', kNeeded(100), 56);

// exact binomial tail P(Bin(100,1/2) >= 56), computed in BigInt rationals
function binomAtLeast(n, kmin) {
  // returns exact fraction {num, den} = sum_{k=kmin}^{n} C(n,k) / 2^n
  const C = new Array(n + 1).fill(0n);
  C[0] = 1n;
  // Pascal row
  const row = new Array(n + 1).fill(0n);
  row[0] = 1n;
  for (let i = 1; i <= n; i++) for (let j = i; j >= 1; j--) row[j] = row[j] + row[j - 1];
  let num = 0n;
  for (let k = kmin; k <= n; k++) num += row[k];
  const den = 1n << BigInt(n);
  return Number(num) / Number(den);
}
const pAhead100 = binomAtLeast(100, 56);
console.log('\n== 4. After 100 rounds: the mean is up 131x, the median down 99.5% ==');
check('P(ahead after 100 rounds) = binomial tail', pAhead100, 0.1356265, 1e-6);
check('so ~86% of players have LOST money', 1 - pAhead100, 0.8643735, 1e-6);
const medianWealth100 = Math.pow(U, 50) * Math.pow(D, 50);   // k = n/2 = 50
check('median wealth after 100 = 0.9^50', medianWealth100, Math.pow(0.9, 50), 1e-12);
check('   median player keeps ~0.515% of the stake', medianWealth100, 0.005153775, 1e-8);
const meanWealth100 = Math.pow(Em, 100);
check('mean / median ratio after 100 rounds', meanWealth100 / medianWealth100, 25515.5, 1);

// ---- the resolution: bet a fraction f (Kelly) ----------------------------
// g(f) = 1/2 ln(1 + f*UP_RET) + 1/2 ln(1 - f*DN_RET)
function g(f) { return P * Math.log(1 + f * UP_RET) + (1 - P) * Math.log(1 - f * DN_RET); }
console.log('\n== 5. The fix: bet a fraction. Kelly turns the ruin into growth ==');
// analytic argmax:  f* = p/DN_RET - q/UP_RET   (Kelly)
const fStarFormula = P / DN_RET - (1 - P) / UP_RET;
check('Kelly f* (formula p/b - q/a)', fStarFormula, 0.25);
// numeric argmax on a fine grid, as an independent confirmation
let best = 0, bestG = -Infinity;
for (let i = 0; i <= 100000; i++) { const f = i / 100000 * 2.5; const gg = g(f); if (gg > bestG) { bestG = gg; best = f; } }
check('numeric argmax of g(f) matches f* = 0.25', best, 0.25, 5e-5);
check('g(f*) growth per round > 0', g(0.25) > 0, true);
check('g(0.25) per-round factor = +0.623%', Math.exp(g(0.25)) - 1, 0.006230590, 1e-7);
check('g(1) reproduces the all-in time-average', g(1), gTime, 1e-12);
check('g(0.5) = 0 exactly  (double Kelly = break-even)', g(0.5), 0, 1e-12);
check('   because (1+0.5*0.5)(1-0.4*0.5) = 1.25*0.8 = 1', 1.25 * 0.8, 1.0);
check('over-betting (f=2.0) is worse than not playing', g(2.0) < 0, true);

// ---- seeded Monte-Carlo cross-check (same PRNG the page ships) ------------
// mulberry32 — deterministic, so the page's live sim reproduces these to noise.
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;
  };
}
console.log('\n== 6. Seeded Monte-Carlo cross-check (20,000 players x 100 rounds, f=1) ==');
const rng = mulberry32(0x9E3779B9);
const PLAYERS = 20000, ROUNDS = 100;
let ahead = 0, sumLog = 0;
const finals = [];
for (let pI = 0; pI < PLAYERS; pI++) {
  let w = 1, ups = 0;
  for (let r = 0; r < ROUNDS; r++) { if (rng() < P) { w *= U; ups++; } else { w *= D; } }
  if (w > 1) ahead++;
  sumLog += Math.log(w);
  finals.push(w);
}
finals.sort((a, b) => a - b);
const empAhead = ahead / PLAYERS;
const empLogPerRound = sumLog / PLAYERS / ROUNDS;
const empMedian = finals[Math.floor(PLAYERS / 2)];
check('MC fraction-ahead ~ binomial tail', empAhead, pAhead100, 0.01);
check('MC mean log-growth per round ~ E[ln m]', empLogPerRound, gTime, 2e-3);
check('MC median wealth ~ 0.9^50 (order of magnitude)', Math.log10(empMedian), Math.log10(medianWealth100), 0.35);
// PRNG determinism anchor (so the browser reproduces the same stream)
const r2 = mulberry32(0x9E3779B9);
check('mulberry32 first draw is deterministic', r2(), 0.3588899802, 1e-9);

// NOTE (honesty): the ensemble MEAN wealth is NOT estimated by MC here on purpose.
// A sample mean of a fat-tailed multiplicative variable is itself unreliable — a
// single ultra-lucky path dominates 20,000 samples — so the page shows the EXACT
// analytic mean 1.05^n and says so. This is the whole point: the mean is real but
// almost nobody realises it.

console.log(`\n${fail === 0 ? 'ALL' : fail + ' FAILED /'} ${pass + fail} checks — ${pass} pass, ${fail} fail`);
process.exit(fail === 0 ? 0 : 1);
