#!/usr/bin/env node
// verify-wisdom-of-crowds.mjs
// ---------------------------------------------------------------------------
// Show-the-check for the stratum "The Crowd That Watched Itself"
// (the wisdom — and madness — of crowds).
//
// Four things are checked here, in order of how load-bearing they are:
//
//   1. THE EXACT IDENTITY (the spine).  The Diversity Prediction Theorem
//      (Scott E. Page, "The Difference", 2007) is not a tendency, it is an
//      algebraic identity — the parallel-axis / bias-variance decomposition:
//
//          (mean - truth)^2  =  mean_i (x_i - truth)^2  -  mean_i (x_i - mean)^2
//          CROWD ERROR        =  AVERAGE INDIVIDUAL ERR  -  DIVERSITY
//
//      We assert it holds to floating-point precision on thousands of random
//      crowds. If it ever failed, the whole page would be lying.
//
//   2. GALTON 1907 (the history).  We reconstruct the distribution Galton
//      actually published ("Vox Populi", Nature 75, 7 Mar 1907) from his
//      printed centile table, and confirm the median = 1207 lb and the
//      quartiles he reported, and that a mean rebuilt from those centiles
//      lands at ~1197 lb (matching K. Wallis's 2014 reconstruction) against
//      Galton's printed dressed weight of 1198 lb. Wallis's archival check gives
//      weight 1197 lb and median 1208 lb; the reconstruction uses the printed table.
//
//   3. THE COLLAPSE (the madness).  We simulate social influence as DeGroot
//      consensus-averaging and confirm the mechanism the page claims: pulling
//      estimates toward each other destroys diversity monotonically, and since
//      diversity is *exactly* the crowd's edge (by #1), average individual error
//      falls toward the unchanged crowd error. Same equation, run backwards.
//
//   4. CONDORCET (the binary analogue).  Independent voters each right with
//      p>1/2: majority accuracy -> 1 as the crowd grows; shared bias (p<1/2)
//      sends it -> 0. The discrete cousin of the same idea.
//
// Run:  node verify-wisdom-of-crowds.mjs
// Exit non-zero if any assertion fails.
// ---------------------------------------------------------------------------

let failures = 0;
const EPS = 1e-9;
function ok(label, cond, detail = '') {
  const mark = cond ? '  ok ' : 'FAIL ';
  if (!cond) failures++;
  console.log(`${mark} ${label}${detail ? '   ' + detail : ''}`);
}
function approx(a, b, tol = EPS) { return Math.abs(a - b) <= tol; }

// --- crowd statistics -------------------------------------------------------
const mean = a => a.reduce((s, x) => s + x, 0) / a.length;
const crowdError = (a, t) => (mean(a) - t) ** 2;                       // (x̄ - θ)²
const avgIndError = (a, t) => mean(a.map(x => (x - t) ** 2));          // mean (xᵢ - θ)²
const diversity = a => { const m = mean(a); return mean(a.map(x => (x - m) ** 2)); }; // variance

// A tiny deterministic PRNG so the run is reproducible (mulberry32).
function rng(seed) {
  let s = seed >>> 0;
  return () => {
    s |= 0; s = (s + 0x6D2B79F5) | 0;
    let t = Math.imul(s ^ (s >>> 15), 1 | s);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

console.log('\n=== 1. THE EXACT IDENTITY (Diversity Prediction Theorem) ===\n');
{
  const r = rng(20260629);
  let worst = 0;
  const trials = 20000;
  for (let k = 0; k < trials; k++) {
    const n = 2 + Math.floor(r() * 40);
    const truth = (r() - 0.5) * 2000;
    const a = Array.from({ length: n }, () => truth + (r() - 0.5) * 1000);
    const lhs = crowdError(a, truth);
    const rhs = avgIndError(a, truth) - diversity(a);
    worst = Math.max(worst, Math.abs(lhs - rhs));
  }
  ok(`identity holds across ${trials} random crowds`, worst < 1e-6,
     `max |crowdErr - (avgIndErr - diversity)| = ${worst.toExponential(2)}`);

  // The corollary the page leans on: the crowd is NEVER worse than its average
  // member (diversity ≥ 0), and is strictly better whenever members disagree.
  const r2 = rng(7);
  let crowdBeatsAvg = true, strictWhenDiverse = true;
  for (let k = 0; k < 20000; k++) {
    const n = 2 + Math.floor(r2() * 30);
    const truth = (r2() - 0.5) * 2000;
    const a = Array.from({ length: n }, () => truth + (r2() - 0.5) * 1200);
    if (crowdError(a, truth) > avgIndError(a, truth) + EPS) crowdBeatsAvg = false;
    if (diversity(a) > 1 && !(crowdError(a, truth) < avgIndError(a, truth))) strictWhenDiverse = false;
  }
  ok('crowd error ≤ average individual error, always', crowdBeatsAvg);
  ok('strictly better whenever the crowd disagrees', strictWhenDiverse);
  ok('identical guesses give equality, not strict improvement',
     diversity([1, 1]) === 0 && crowdError([1, 1], 0) === 1 && avgIndError([1, 1], 0) === 1);
}

console.log('\n=== 2. GALTON 1907 ("Vox Populi", Nature 75:450) ===\n');
{
  // Galton printed the distribution of the 787 legible estimates as a table of
  // centiles (lb). These are his published numbers, transcribed verbatim.
  // Source: F. Galton, "Vox Populi", Nature 75, 450–451 (7 March 1907), Table.
  const centiles = {
    5:1074, 10:1109, 15:1126, 20:1148, 25:1162, 30:1174, 35:1181, 40:1188,
    45:1197, 50:1207, 55:1214, 60:1219, 65:1225, 70:1230, 75:1236, 80:1243,
    85:1254, 90:1267, 95:1293
  };
  const PRINTED_DRESSED = 1198; // Galton's published weight, not the archival 1197 lb
  ok('printed median (Galton\'s "vox populi") = 1207 lb', centiles[50] === 1207);
  ok('lower quartile q1 = 1162 lb', centiles[25] === 1162);
  ok('upper quartile q3 = 1236 lb', centiles[75] === 1236);
  ok('printed median error vs printed 1198 lb is +9 lb (0.75%)',
     centiles[50] - PRINTED_DRESSED === 9,
     `(${centiles[50]} - ${PRINTED_DRESSED})`);

  // Reconstruct ~787 estimates by interpolating between the printed centiles,
  // then compute the MEAN — the statistic the popular retelling ("the average
  // was almost exact") actually refers to, which Galton himself reported as
  // ~1197 and Wallis (Statistical Science 2014) reconstructed as 1197.
  const N = 787;
  const xs = [];
  const pts = Object.keys(centiles).map(Number).sort((a, b) => a - b);
  for (let i = 0; i < N; i++) {
    const c = (i + 0.5) / N * 100;                 // this point's centile
    // clamp into the printed range and linearly interpolate
    const cc = Math.max(pts[0], Math.min(pts[pts.length - 1], c));
    let lo = pts[0];
    for (const p of pts) if (p <= cc) lo = p;
    let hi = pts[pts.length - 1];
    for (let j = pts.length - 1; j >= 0; j--) if (pts[j] >= cc) hi = pts[j];
    const v = lo === hi ? centiles[lo]
      : centiles[lo] + (centiles[hi] - centiles[lo]) * (cc - lo) / (hi - lo);
    xs.push(v);
  }
  const recMean = mean(xs);
  ok('mean rebuilt from the published centiles ≈ 1197 lb',
     Math.abs(recMean - 1197) < 2.5, `reconstructed mean = ${recMean.toFixed(1)} lb`);

  // In Galton's printed account, the median erred by 9 lb and the reported
  // mean by 1 lb. Wallis's archival values give 11 lb and zero respectively.
  console.log(`       → printed median erred by ${centiles[50] - PRINTED_DRESSED} lb; ` +
              `reconstructed mean vs printed weight by ${Math.abs(recMean - PRINTED_DRESSED).toFixed(1)} lb. ` +
              `Galton reported the MEDIAN; "the average won" is the later gloss.`);
}

console.log('\n=== 3. THE COLLAPSE — social influence kills the diversity (Lorenz et al. 2011) ===\n');
{
  // A crowd of independent noisy estimators around a truth. Then apply DeGroot
  // consensus averaging: each round every estimate moves a fraction λ toward
  // the current mean (the simplest model of "everyone nudges toward the room").
  // The mean is preserved exactly, so this can't help accuracy — it only
  // collapses diversity, and by the identity (#1) that is the crowd's entire
  // edge. We confirm: diversity falls monotonically; average individual error
  // falls toward the unchanged crowd error as the influence accumulates.
  const r = rng(123456);
  const N = 400;
  const truth = 100;
  // estimates: unbiased-ish but noisy (so the crowd starts genuinely wise)
  let a = Array.from({ length: N }, () => truth + (r() - 0.5) * 60 + (r() - 0.5) * 60);
  const lambda = 0.15;

  const div0 = diversity(a), ce0 = crowdError(a, truth), ai0 = avgIndError(a, truth);
  let prevDiv = div0, monotone = true;
  const meanStart = mean(a);
  for (let round = 0; round < 40; round++) {
    const m = mean(a);
    a = a.map(x => x + lambda * (m - x));   // pull each toward the consensus
    const d = diversity(a);
    if (d > prevDiv + EPS) monotone = false;
    prevDiv = d;
  }
  const meanEnd = mean(a);
  const div1 = diversity(a), ce1 = crowdError(a, truth), ai1 = avgIndError(a, truth);

  ok('the consensus average is conserved (influence adds no information)',
     approx(meanStart, meanEnd, 1e-6),
     `mean ${meanStart.toFixed(3)} → ${meanEnd.toFixed(3)}`);
  ok('diversity collapses monotonically under influence', monotone,
     `diversity ${div0.toFixed(1)} → ${div1.toFixed(1)}`);
  ok('average individual error falls toward the (unchanged) crowd error',
     ai1 < ai0 + EPS && approx(ce0, ce1, 1e-6) && ai1 > ce1 - 1e-6,
     `avgIndErr ${ai0.toFixed(1)} → ${ai1.toFixed(1)}; crowdErr stays ${ce1.toFixed(2)}`);
  ok('the crowd\'s edge (avgIndErr − crowdErr = diversity) shrinks to ~0',
     (ai1 - ce1) < (ai0 - ce0) && (ai1 - ce1) < 0.05 * (ai0 - ce0),
     `edge ${(ai0 - ce0).toFixed(1)} → ${(ai1 - ce1).toFixed(2)}`);
  console.log('       → the very term that made the crowd wise (diversity) is the ' +
              'term social influence destroys. Same equation, run backwards.');
}

console.log('\n=== 4. CONDORCET — the binary analogue ===\n');
{
  // P(majority of n independent voters is correct), each correct w.p. p.
  // Exact binomial tail (odd n, no ties). Grows to 1 if p>1/2, falls to 0 if p<1/2.
  function logChoose(n, k) {
    let s = 0;
    for (let i = 1; i <= k; i++) s += Math.log(n - k + i) - Math.log(i);
    return s;
  }
  function majorityCorrect(n, p) {
    // sum_{k>n/2} C(n,k) p^k (1-p)^(n-k)
    let total = 0;
    for (let k = Math.floor(n / 2) + 1; k <= n; k++) {
      total += Math.exp(logChoose(n, k) + k * Math.log(p) + (n - k) * Math.log(1 - p));
    }
    return total;
  }
  const p = 0.6;
  const seq = [1, 3, 9, 31, 101, 501].map(n => ({ n, acc: majorityCorrect(n, p) }));
  let increasing = true;
  for (let i = 1; i < seq.length; i++) if (seq[i].acc <= seq[i - 1].acc) increasing = false;
  ok(`with p=${p}, majority accuracy rises with crowd size`, increasing,
     seq.map(s => `n${s.n}:${(s.acc * 100).toFixed(1)}%`).join('  '));
  ok('a large competent crowd is near-certain (n=501, p=0.6 → >99.9%)',
     majorityCorrect(501, 0.6) > 0.999, `${(majorityCorrect(501, 0.6) * 100).toFixed(3)}%`);
  // shared bias flips the theorem: each voter is wrong more often than right
  ok('shared bias (p=0.4) drives a big crowd to ~0% correct',
     majorityCorrect(501, 0.4) < 0.001, `${(majorityCorrect(501, 0.4) * 100).toExponential(2)}%`);
  console.log('       → these binomial results assume independent, equally competent voters. ' +
              'Shared inputs can limit further gains; below-chance competence reverses the limit.');
}

console.log('\n' + (failures === 0
  ? '✓ all arithmetic checks above passed.'
  : `✗ ${failures} check(s) failed.`) + '\n');
process.exit(failures === 0 ? 0 : 1);
