// verify.mjs — the verified spine of "No Number Wrong Anywhere"
// (program P1, the Verification Venue — a PORTAL across four strata).
//
//   node research/no-number-wrong/verify.mjs
//
// The portal's own load-bearing claim, beyond what any of the four source
// strata state, is a structural one about three correlated variables X, Z, Y:
//
//   (A) The three DAGs with the X–Z–Y skeleton and NO collision at Z —
//       the confounder  X ← Z → Y,
//       the mediator     X → Z → Y,
//       the reverse chain X ← Z ← Y —
//       are MARKOV-EQUIVALENT: they impose the single conditional-independence
//       X ⟂ Y | Z and therefore can produce the *identical* correlation matrix.
//       So the observational numbers cannot pick the arrow — yet the causal
//       verdict is opposite (a confounder you MUST condition on; a mediator you
//       must NOT). This is the exact ambiguity under Simpson's paradox.
//
//   (B) The fourth DAG, the COLLIDER X → Z ← Y, is the lone v-structure: it
//       imposes the *complementary* pattern X ⟂ Y but NOT X ⟂ Y | Z. Selecting
//       on Z (a hospital admission, a dating pool, a shortlist) manufactures a
//       correlation from independence. This is Berkson's paradox.
//
//   For the total effect in these models, adjust for the fork's common cause,
//   but leave the mediator and collider unconditioned. The fork and mediator
//   share a matrix; the collider has a different independence pattern.
//
// Everything below is closed-form (no sampling), checked against the partial-
// correlation identity, plus a deterministic reproduction of the four canonical
// numbers the source strata proved, so the portal stands on its own.

let pass = 0, fail = 0;
const ok = (cond, msg) => { (cond ? pass++ : fail++); console.log(`  ${cond ? 'PASS' : 'FAIL'}  ${msg}`); };
const close = (a, b, e = 1e-9) => Math.abs(a - b) <= e;

// ---------------------------------------------------------------------------
// partial correlation of X and Y given Z, from the 3x3 correlation matrix.
//   r_XY.Z = (r_XY - r_XZ r_ZY) / sqrt((1 - r_XZ^2)(1 - r_ZY^2))
const pcorr = (rXY, rXZ, rZY) =>
  (rXY - rXZ * rZY) / Math.sqrt((1 - rXZ * rXZ) * (1 - rZY * rZY));

// A linear-Gaussian SEM returns the three pairwise correlations it implies.
// We build each of the four canonical structures from the SAME two path
// strengths a (X–Z arrow) and b (Z–Y arrow) so the comparison is fair.
const a = 0.6, b = 0.5;

// --- (A) the no-collider trio: all impose X ⟂ Y | Z, all share one matrix ---

// confounder  X ← Z → Y : Z standard; X = aZ + ex, Y = bZ + ey, with the
// noise scaled so Var(X)=Var(Y)=1 (everything standardised). Then
//   r_XZ = a, r_ZY = b, r_XY = a*b.
const confounder = { rXZ: a, rZY: b, rXY: a * b };

// mediator  X → Z → Y : X standard; Z = aX + ez (Var(Z)=1 ⇒ r_XZ=a),
//   Y = bZ + ey (Var(Y)=1 ⇒ r_ZY=b), and r_XY = b*r_XZ = a*b.
const mediator = { rXZ: a, rZY: b, rXY: a * b };

// reverse chain  X ← Z ← Y : Y standard; Z = bY + ez (r_ZY=b),
//   X = aZ + ex (r_XZ=a), r_XY = a*r_ZY = a*b. Same matrix again.
const reverse = { rXZ: a, rZY: b, rXY: a * b };

console.log('[A] the no-collider trio — Markov-equivalent, one matrix, X ⟂ Y | Z\n');
for (const [name, m] of [['confounder X←Z→Y', confounder], ['mediator  X→Z→Y', mediator], ['reverse   X←Z←Y', reverse]]) {
  const p = pcorr(m.rXY, m.rXZ, m.rZY);
  ok(close(m.rXY, a * b) && close(m.rXZ, a) && close(m.rZY, b),
     `${name}: identical correlations  r_XY=${m.rXY.toFixed(2)} r_XZ=${m.rXZ.toFixed(2)} r_ZY=${m.rZY.toFixed(2)}`);
  ok(close(p, 0), `${name}: partial corr(X,Y|Z) = ${p.toFixed(6)} ≈ 0  (conditioning on Z erases the link)`);
}
// the punchline of (A): the three matrices are byte-for-byte equal
ok(JSON.stringify(confounder) === JSON.stringify(mediator) &&
   JSON.stringify(mediator) === JSON.stringify(reverse),
   'the three matrices are identical — observation cannot pick the arrow (Markov equivalence)');

// --- (B) the collider: the lone v-structure, the complementary signature ---
console.log('\n[B] the collider X→Z←Y — X ⟂ Y but NOT X ⟂ Y | Z\n');
// collider  X → Z ← Y : X, Y independent standard; Z = aX + bY + ez.
//   r_XY = 0 (independent by construction);
//   r_XZ = a / sd(Z), r_ZY = b / sd(Z), with Var(Z) = a^2 + b^2 + Var(ez).
// pick Var(ez) so Var(Z)=1 ⇒ sd(Z)=1, r_XZ=a, r_ZY=b (matching the trio's
// edge strengths so only the collision differs).
const collider = { rXZ: a, rZY: b, rXY: 0 };
const pCol = pcorr(collider.rXY, collider.rXZ, collider.rZY);
let colliderDomainOK = true;
for (let ia = 15; ia <= 70; ia++) for (let ib = 15; ib <= 70; ib++) {
  const ca = ia / 100, cb = ib / 100;
  const determinant = 1 - ca * ca - cb * cb;
  const partial = pcorr(0, ca, cb);
  if (!(determinant > 0 && Number.isFinite(partial) && Math.abs(partial) < 1)) colliderDomainOK = false;
}
ok(close(collider.rXY, 0) && colliderDomainOK,
   `collider: marginal corr(X,Y) = 0; all 3,136 allowed slider pairs give positive-definite matrices and valid partials`);
ok(pCol < -0.4 && pCol > -0.5,
   `collider: partial corr(X,Y|Z) = ${pCol.toFixed(6)} < 0  (conditioning MANUFACTURES a link)`);
// the matrices differ from the trio in exactly one cell: the X–Y corner.
ok(close(collider.rXZ, confounder.rXZ) && close(collider.rZY, confounder.rZY) &&
   !close(collider.rXY, confounder.rXY),
   'collider vs trio differ in exactly one number: r_XY (0 vs a·b) — the whole story is one cell');

// --- conditioning reduces the fork's association magnitude and raises the collider's ---
console.log('\n[duality] conditioning moves association magnitude toward versus away from zero\n');
const moveTrio = pcorr(confounder.rXY, confounder.rXZ, confounder.rZY) - confounder.rXY; // toward 0 (down)
const moveCol  = pcorr(collider.rXY,  collider.rXZ,  collider.rZY)  - collider.rXY;       // away from 0 (down past 0)
ok(Math.abs(pcorr(confounder.rXY, confounder.rXZ, confounder.rZY)) < Math.abs(confounder.rXY) &&
   Math.abs(pCol) > Math.abs(collider.rXY),
   `confounder: link 0.30 → 0 (Δ=${moveTrio.toFixed(3)}); collider: link 0 → ${pCol.toFixed(3)} (Δ=${moveCol.toFixed(3)}). Same act, opposite remedy.`);

// ===========================================================================
// the four canonical numbers, reproduced so the portal is self-contained.
// ===========================================================================

// --- (1) ANSCOMBE: a summary is a projection — mean x = 9, sample var x = 11
//     identically, in all four datasets (exact integer arithmetic). -----------
console.log('\n[1] Anscombe — identical first two moments, exact\n');
const xs_I_III = [10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5];        // x shared by I,II,III
const xs_IV    = [8, 8, 8, 8, 8, 8, 8, 19, 8, 8, 8];            // x for IV
const meanInt = arr => arr.reduce((s, v) => s + v, 0) / arr.length;
const sampVar = arr => { const m = meanInt(arr); return arr.reduce((s, v) => s + (v - m) * (v - m), 0) / (arr.length - 1); };
for (const [nm, xs] of [['I–III', xs_I_III], ['IV', xs_IV]]) {
  ok(meanInt(xs) === 9, `dataset ${nm}: mean(x) = ${meanInt(xs)} (exactly 9)`);
  ok(sampVar(xs) === 11, `dataset ${nm}: sample var(x) = ${sampVar(xs)} (exactly 11)`);
}

// --- (2) SIMPSON / Berkeley: pooled gap and per-stratum reversal share a sign
//     pattern. Use a clean 2-department instance proving the reversal exists
//     (the live page reproduces the real UCBAdmissions table; here we prove the
//     mechanism is an honest possibility, not an arithmetic slip). -------------
console.log('\n[2] Simpson — the pooled trend reverses every stratum (toy proof of possibility)\n');
// Women are admitted at the higher rate in BOTH departments, yet men lead the
// pool — because men concentrate in the easy department (A) and women in the
// hard one (B). The classic Berkeley shape, in small honest integers.
const dA = { mA: 240, mN: 300, wA: 41, wN: 50 };    // easy dept (~0.8): men .800, women .820
const dB = { mA: 10,  mN: 50,  wA: 66, wN: 300 };   // hard dept (~0.2): men .200, women .220
const rate = (a, n) => a / n;
const womenWinsA = rate(dA.wA, dA.wN) > rate(dA.mA, dA.mN);
const womenWinsB = rate(dB.wA, dB.wN) > rate(dB.mA, dB.mN);
const mPool = rate(dA.mA + dB.mA, dA.mN + dB.mN);
const wPool = rate(dA.wA + dB.wA, dA.wN + dB.wN);
ok(womenWinsA && womenWinsB, `women admitted at the higher rate in BOTH departments (A: ${(rate(dA.wA,dA.wN)*100).toFixed(0)}% vs ${(rate(dA.mA,dA.mN)*100).toFixed(0)}%, B: ${(rate(dB.wA,dB.wN)*100).toFixed(0)}% vs ${(rate(dB.mA,dB.mN)*100).toFixed(0)}%)`);
ok(mPool > wPool, `yet pooled, MEN lead: ${(mPool*100).toFixed(1)}% vs ${(wPool*100).toFixed(1)}% — the sign flips on aggregation`);

// --- (3) WILL ROGERS: both group means rise ⟺ mB < x < mA (exact identity) ---
console.log('\n[3] Will Rogers — moving one element lifts both means iff it lies in the band\n');
function bothRise(A, B, x) {
  const mA = A.reduce((s, v) => s + v, 0) / A.length;
  const mB = B.reduce((s, v) => s + v, 0) / B.length;
  const A2 = A.slice(), B2 = [...B, x];
  A2.splice(A2.indexOf(x), 1);   // move exactly one copy of x from A to B
  const mA2 = A2.reduce((s, v) => s + v, 0) / A2.length;
  const mB2 = B2.reduce((s, v) => s + v, 0) / B2.length;
  return { rose: mA2 > mA && mB2 > mB, inBand: mB < x && x < mA, mA2, mB2 };
}
let wrAll = true;
// exhaustive-ish: random A (the "good" group), B (the "bad" group), x = a member of A
let seed = 12345; const rnd = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
for (let t = 0; t < 20000; t++) {
  const nA = 2 + (rnd() * 6 | 0), nB = 1 + (rnd() * 6 | 0);
  const A = Array.from({ length: nA }, () => Math.round(rnd() * 100));
  const B = Array.from({ length: nB }, () => Math.round(rnd() * 100));
  const x = A[rnd() * A.length | 0];
  const { rose, inBand } = bothRise(A, B, x);
  if (rose !== inBand) { wrAll = false; break; }
}
const boundary = bothRise([20, 20, 80], [20], 20);
ok(wrAll && !boundary.rose && !boundary.inBand && boundary.mA2 === 50 && boundary.mB2 === 20,
   `"both means rose" iff "mB < x < mA" across 20,000 random configurations, plus an equality boundary with a repeated value`);

// --- (4) BERKSON: median cut on two independent standard normals gives the
//     exact selected correlation −1/(π−1). Reproduce by deterministic 2-D
//     Simpson quadrature over the selected half-plane U+V>0. -------------------
console.log('\n[4] Berkson — median cut on independent (U,V): selected corr = −1/(π−1)\n');
const phi = z => Math.exp(-z * z / 2) / Math.sqrt(2 * Math.PI);
// integrate g(u,v)*phi(u)*phi(v) over the half-plane u+v>0 by composite Simpson.
function selMoment(g) {
  const L = 8, N = 1600, h = 2 * L / N;     // grid on [-L,L]^2
  const w = i => (i === 0 || i === N) ? 1 : (i % 2 ? 4 : 2);
  let s = 0;
  for (let i = 0; i <= N; i++) {
    const u = -L + i * h, wu = w(i);
    for (let j = 0; j <= N; j++) {
      const v = -L + j * h;
      if (u + v <= 0) continue;             // selection: keep upper half
      s += wu * w(j) * g(u, v) * phi(u) * phi(v);
    }
  }
  return s * (h / 3) * (h / 3);
}
const P  = selMoment(() => 1);              // P(selected) → 1/2
const EU = selMoment(u => u) / P;           // E[U | sel]
const EV = selMoment((_, v) => v) / P;
const EUU = selMoment(u => u * u) / P;
const EVV = selMoment((_, v) => v * v) / P;
const EUV = selMoment((u, v) => u * v) / P;
const covS = EUV - EU * EV;
const corrS = covS / Math.sqrt((EUU - EU * EU) * (EVV - EV * EV));
const target = -1 / (Math.PI - 1);
ok(close(P, 0.5, 1e-3), `P(U+V>0) = ${P.toFixed(4)} ≈ 1/2 (the cut keeps half — quadrature sanity)`);
ok(close(corrS, target, 3e-3), `selected corr = ${corrS.toFixed(4)} ≈ −1/(π−1) = ${target.toFixed(4)}`);

// ---------------------------------------------------------------------------
console.log(`\n${fail === 0 ? 'ALL CHECKS PASS' : 'FAILURES PRESENT'} — ${pass} passed, ${fail} failed.`);
process.exit(fail === 0 ? 0 : 1);
