#!/usr/bin/env node
// Offline verifier for the stratum "One Dimension Too Many" (Pólya's recurrence theorem).
//
// Pólya (1921) proved the simple symmetric random walk on the integer lattice Z^d
// is RECURRENT (returns to its start with probability 1) for d = 1 and d = 2, but
// TRANSIENT for d >= 3. This file checks selected return counts, asymptotics, and
// constants for d = 3, 4, 5 using independent methods with explicit tolerances:
//
//   A. Exact lattice return probabilities p_{2n} = P(S_{2n} = 0) for d = 1,2,3, by
//      exact integer (BigInt) counting:
//        - d=1:  p_{2n} = C(2n,n) / 4^n
//        - d=2:  p_{2n} = ( C(2n,n) / 4^n )^2        (x±y decoupling into two 1-D walks)
//        - d=3:  p_{2n} = (1/6^{2n}) * sum_{i+j+k=n} (2n)! / (i!^2 j!^2 k!^2)
//   B. The local-CLT asymptotic p_{2n} ~ 2 (d/(4 pi n))^{d/2}, and the convergence test
//      it implies:  sum p_{2n} diverges for d<=2 (recurrent), converges for d>=3 (transient).
//   C. The 3-D Green's function (expected visits to 0) u(3) = sum_{n>=0} p_{2n}, by an
//      exact partial sum (engine A) + an asymptotic tail, approximately 1.51624.
//   D. u(3) from Watson's triple integral by numerical quadrature:  u(3) = 3 * W,
//      W = (1/pi^3) INT_{[0,pi]^3} dx dy dz / (3 - cos x - cos y - cos z) ~ 0.5054620197.
//   E. u(3) from Glasser and Zucker's (1977) Gamma form of Watson's integral:
//        u(3) = (sqrt 6 / (32 pi^3)) * Gamma(1/24) Gamma(5/24) Gamma(7/24) Gamma(11/24).
//   F. The return probability  p(3) = 1 - 1/u(3) ~ 0.3405373296, cross-checked all ways,
//      plus the higher-dimensional Pólya constants p(4) ~ 0.193, p(5) ~ 0.135 by quadrature.
//   G. Monte-Carlo: a finite-horizon return fraction in 3-D lands near a third, while the
//      1-D fraction is far higher (recurrence vs transience, seen rather than assumed).
//
// Run:  node research/polya-recurrence/verify.mjs
// Pure Node, no dependencies. Prints "PASS n/n" or throws on the first failed check.

let pass = 0, total = 0;
const log = [];
function check(name, cond, detail = '') {
  total++;
  if (cond) { pass++; log.push(`  ok   ${name}${detail ? '  —  ' + detail : ''}`); }
  else { log.push(`  FAIL ${name}${detail ? '  —  ' + detail : ''}`); throw new Error('CHECK FAILED: ' + name + ' :: ' + detail); }
}
const near = (a, b, eps) => Math.abs(a - b) <= eps;
const PI = Math.PI;

// ── BigInt helpers ────────────────────────────────────────────────────────────
const NMAX = 420;                                // up to 2n = 400 steps, exactly
const fact = [1n];
for (let i = 1; i <= NMAX; i++) fact[i] = fact[i - 1] * BigInt(i);
// high-precision BigInt ratio -> double
function ratio(num, den) {
  const SCALE = 10n ** 30n;
  return Number((num * SCALE) / den) / 1e30;
}

// Engine A1: d=1 exact  p_{2n} = C(2n,n)/4^n
function p1(n) { return ratio(fact[2 * n], fact[n] * fact[n] * (4n ** BigInt(n))); }
// Engine A2: d=2 exact  p_{2n} = (C(2n,n)/4^n)^2
function p2(n) { const c = p1(n); return c * c; }
// Engine A3: d=3 exact  p_{2n} = (1/6^{2n}) sum_{i+j+k=n} (2n)!/(i!^2 j!^2 k!^2)
function p3(n) {
  const twoN = fact[2 * n];
  let s = 0n;                                     // sum * (smallest common structure) handled by ratio
  // accumulate sum_{i+j+k=n} (2n)!/(i!^2 j!^2 k!^2) as a BigInt by summing integer terms
  // each term (2n)!/(i!^2 j!^2 k!^2) is an integer (multinomial * multinomial), so sum is integer
  for (let i = 0; i <= n; i++) {
    for (let j = 0; j <= n - i; j++) {
      const k = n - i - j;
      const den = fact[i] * fact[i] * fact[j] * fact[j] * fact[k] * fact[k];
      s += twoN / den;
    }
  }
  return ratio(s, (6n ** BigInt(2 * n)));
}

// ── Engine E: Gamma via Lanczos (g=7), accurate to ~1e-14 on the real axis ──────
const G_LANCZOS = 7;
const LANC = [
  0.99999999999980993, 676.5203681218851, -1259.1392167224028,
  771.32342877765313, -176.61502916214059, 12.507343278686905,
  -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7,
];
function gamma(z) {
  if (z < 0.5) return PI / (Math.sin(PI * z) * gamma(1 - z));
  z -= 1;
  let x = LANC[0];
  for (let i = 1; i < G_LANCZOS + 2; i++) x += LANC[i] / (z + i);
  const t = z + G_LANCZOS + 0.5;
  return Math.sqrt(2 * PI) * Math.pow(t, z + 0.5) * Math.exp(-t) * x;
}

// ════════════════════════════════════════════════════════════════════════════
// A. EXACT LATTICE RETURN PROBABILITIES
// ════════════════════════════════════════════════════════════════════════════
// d=1 sanity: p_0 = 1, p_2 = 1/2, p_4 = 3/8
check('1D p_2 = 1/2', near(p1(1), 0.5, 1e-15), p1(1).toString());
check('1D p_4 = 3/8', near(p1(2), 0.375, 1e-15), p1(2).toString());
// d=2 identity vs the (C(2n,n)/4^n)^2 form, checked against a tiny brute force
function brute2D(n) {
  // exhaustive count of 2n-step 2D walks (4 dirs) ending at origin / 4^{2n}
  const steps = 2 * n; let total = 0, ret = 0;
  const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
  function rec(s, x, y) {
    if (s === steps) { total++; if (x === 0 && y === 0) ret++; return; }
    for (const [dx, dy] of dirs) rec(s + 1, x + dx, y + dy);
  }
  rec(0, 0, 0); return ret / total;
}
for (const n of [1, 2, 3]) check(`2D p_${2 * n} matches brute force`, near(p2(n), brute2D(n), 1e-12), `${p2(n)} vs ${brute2D(n)}`);
// d=3 sanity vs brute force
function brute3D(n) {
  const steps = 2 * n; let total = 0, ret = 0;
  const dirs = [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]];
  function rec(s, x, y, z) {
    if (s === steps) { total++; if (!x && !y && !z) ret++; return; }
    for (const [dx, dy, dz] of dirs) rec(s + 1, x + dx, y + dy, z + dz);
  }
  rec(0, 0, 0, 0); return ret / total;
}
for (const n of [1, 2, 3]) check(`3D p_${2 * n} matches brute force`, near(p3(n), brute3D(n), 1e-12), `${p3(n)} vs ${brute3D(n)}`);
// 3D p_2 = 1/6 (one step out, one back, any of 3 axes / 6 dirs each way -> 6/36)
check('3D p_2 = 1/6', near(p3(1), 1 / 6, 1e-15), p3(1).toString());

// ════════════════════════════════════════════════════════════════════════════
// B. LOCAL CLT ASYMPTOTIC  p_{2n} ~ 2 (d/(4 pi n))^{d/2}
// ════════════════════════════════════════════════════════════════════════════
const asymp = (d, n) => 2 * Math.pow(d / (4 * PI * n), d / 2);
for (const [d, pf, n, eps] of [[1, p1, 100, 0.01], [2, p2, 100, 0.02], [3, p3, 80, 0.03]]) {
  const r = pf(n) / asymp(d, n);
  check(`${d}D LCLT ratio -> 1 at n=${n}`, near(r, 1, eps), `exact/asymp = ${r.toFixed(5)}`);
}

// ════════════════════════════════════════════════════════════════════════════
// C. 3-D GREEN'S FUNCTION u(3) BY SERIES  (exact partial sum + asymptotic tail)
// ════════════════════════════════════════════════════════════════════════════
const U3_REF = 1.5163860591519782;               // OEIS A086231
const P3_REF = 0.3405373295510104;               // 1 - 1/U3_REF  (OEIS A086230)
let Spart = 0;
const N0 = 100;
for (let n = 0; n <= N0; n++) Spart += p3(n);
// asymptotic tail  sum_{n>N0} 2 (3/(4 pi n))^{3/2}  ~  a * sum n^{-3/2},  a = 2 (3/4pi)^{3/2}
const a = 2 * Math.pow(3 / (4 * PI), 1.5);
let tail = 0; for (let n = N0 + 1; n <= 5_000_000; n++) tail += a * Math.pow(n, -1.5);
const u3series = Spart + tail;
check('3D u(3) by series ≈ 1.51639', near(u3series, U3_REF, 5e-3), `series=${u3series.toFixed(5)}`);
// divergence side: 1-D and 2-D partial sums keep growing (no finite Green's function)
let s1 = 0, s2 = 0; for (let n = 0; n <= N0; n++) { s1 += p1(n); s2 += p2(n); }
let s1b = 0, s2b = 0; for (let n = 0; n <= 2 * N0; n++) { s1b += p1(n); s2b += p2(n); }
check('1D partial sum still climbing (recurrent)', s1b > s1 + 0.5, `${s1.toFixed(3)} -> ${s1b.toFixed(3)}`);
check('2D partial sum still climbing (recurrent)', s2b > s2 + 0.1, `${s2.toFixed(3)} -> ${s2b.toFixed(3)}`);

// ════════════════════════════════════════════════════════════════════════════
// D. u(3) BY WATSON'S TRIPLE INTEGRAL (numerical)   u(3) = 3 W
// ════════════════════════════════════════════════════════════════════════════
// W = (1/pi^3) INT_{[0,pi]^3} dx dy dz / (3 - cos x - cos y - cos z),  midpoint rule.
function watsonW(N) {
  const h = PI / N; let acc = 0;
  // precompute cos at midpoints
  const cs = new Float64Array(N);
  for (let i = 0; i < N; i++) cs[i] = Math.cos((i + 0.5) * h);
  for (let i = 0; i < N; i++) {
    const ci = cs[i];
    for (let j = 0; j < N; j++) {
      const cij = ci + cs[j];
      for (let k = 0; k < N; k++) acc += 1 / (3 - cij - cs[k]);
    }
  }
  return acc * h * h * h / (PI * PI * PI);
}
const W = watsonW(160);
const u3int = 3 * W;
check("Watson W ≈ 0.50546", near(W, 0.5054620197, 6e-3), `W=${W.toFixed(5)}`);
check('3D u(3) by integral = 3W ≈ 1.5164', near(u3int, U3_REF, 2e-2), `u=${u3int.toFixed(4)}`);

// ════════════════════════════════════════════════════════════════════════════
// E. u(3) BY GLASSER AND ZUCKER'S GAMMA FORM (1977)
// ════════════════════════════════════════════════════════════════════════════
const u3gamma = (Math.sqrt(6) / (32 * PI ** 3)) * gamma(1 / 24) * gamma(5 / 24) * gamma(7 / 24) * gamma(11 / 24);
check('Gamma(1/2) = sqrt(pi) (Lanczos sanity)', near(gamma(0.5), Math.sqrt(PI), 1e-12));
check('Gamma(5) = 24 (Lanczos sanity)', near(gamma(5), 24, 1e-9));
check('3D u(3) closed form ≈ 1.5163860592', near(u3gamma, U3_REF, 1e-7), `closed=${u3gamma.toFixed(10)}`);
// Compare series/integral and integral/Gamma within absolute tolerance 0.02.
check('u(3): series/integral and integral/Gamma differ by at most 0.02', near(u3series, u3int, 2e-2) && near(u3int, u3gamma, 2e-2), `${u3series.toFixed(4)} / ${u3int.toFixed(4)} / ${u3gamma.toFixed(4)}`);

// ════════════════════════════════════════════════════════════════════════════
// F. RETURN PROBABILITY p(d) = 1 - 1/u(d)
// ════════════════════════════════════════════════════════════════════════════
const p3val = 1 - 1 / u3gamma;
check('3D return prob p(3) ≈ 0.3405373296', near(p3val, P3_REF, 1e-7), `p3=${p3val.toFixed(10)}`);
check('3D escape prob 1-p ≈ 0.6594626704', near(1 - p3val, 0.6594626704, 1e-7), (1 - p3val).toFixed(10));
// higher-d Pólya constants by engine A on a d-dim walk: u(d) = sum p_{2n}^{(d)} (series), p=1-1/u
function pd_series(d, N0d) {
  // p_{2n} in d dims by exact convolution of the per-axis step over 2n steps is heavy;
  // use the d-dim multinomial only for the return count via repeated 1-D characteristic powers
  // numerically through the integral mean of ((sum cos)/d)^{2n}. For a citable cross-check we
  // instead confirm p(4),p(5) against literature values via the integral Green's function.
  return null;
}
// u(d) by Watson-type integral (Monte-Carlo quadrature is noisy in high-d; use a deterministic
// product-grid for d=4,5 at modest resolution to confirm the literature return probs to ~1%).
function uD_integral(d, N) {
  // u(d) = (1/(2pi)^d) INT_{[-pi,pi]^d} 1/(1 - (sum cos)/d) ; reduce to [0,pi]^d via symmetry:
  // u(d) = (1/pi^d) INT_{[0,pi]^d} 1/(1 - (sum cos)/d).  Deterministic grid, midpoint rule.
  const h = PI / N;
  const cs = new Float64Array(N);
  for (let i = 0; i < N; i++) cs[i] = Math.cos((i + 0.5) * h);
  let acc = 0;
  const idx = new Int32Array(d);
  const total = Math.pow(N, d);
  for (let t = 0; t < total; t++) {
    let r = t, sum = 0;
    for (let a2 = 0; a2 < d; a2++) { sum += cs[r % N]; r = (r / N) | 0; }
    acc += 1 / (1 - sum / d);
  }
  return acc * Math.pow(h / PI, d);
}
const u4 = uD_integral(4, 60), p4 = 1 - 1 / u4;
const u5 = uD_integral(5, 34), p5 = 1 - 1 / u5;
check('4D return prob p(4) ≈ 0.193', near(p4, 0.1932016732, 6e-3), `p4=${p4.toFixed(4)}`);
check('5D return prob p(5) ≈ 0.135', near(p5, 0.1351786098, 8e-3), `p5=${p5.toFixed(4)}`);
// monotone: returning gets harder as dimension grows
check('return prob falls with dimension: p3>p4>p5', p3val > p4 && p4 > p5, `${p3val.toFixed(3)} > ${p4.toFixed(3)} > ${p5.toFixed(3)}`);

// ════════════════════════════════════════════════════════════════════════════
// G. MONTE-CARLO — recurrence vs transience, seen not assumed
// ════════════════════════════════════════════════════════════════════════════
function mclcg(seed) { let s = seed >>> 0; return () => (s = (1103515245 * s + 12345) >>> 0) / 4294967296; }
function returnFraction3D(trials, horizon, seed) {
  const rnd = mclcg(seed); let ret = 0;
  for (let t = 0; t < trials; t++) {
    let x = 0, y = 0, z = 0;
    for (let s = 0; s < horizon; s++) {
      const r = (rnd() * 6) | 0;
      if (r === 0) x++; else if (r === 1) x--; else if (r === 2) y++; else if (r === 3) y--; else if (r === 4) z++; else z--;
      if (x === 0 && y === 0 && z === 0) { ret++; break; }
    }
  }
  return ret / trials;
}
function returnFraction1D(trials, horizon, seed) {
  const rnd = mclcg(seed); let ret = 0;
  for (let t = 0; t < trials; t++) {
    let x = 0;
    for (let s = 0; s < horizon; s++) { x += rnd() < 0.5 ? 1 : -1; if (x === 0) { ret++; break; } }
  }
  return ret / trials;
}
const mc3 = returnFraction3D(60000, 6000, 12345);
const mc1 = returnFraction1D(20000, 6000, 6789);
// This seeded sample is below p(3). A finite horizon misses late returns, but
// sampling variation can put other samples above the infinite-time probability.
check('MC 3D return fraction near a third', mc3 > 0.30 && mc3 < 0.345, `frac=${mc3.toFixed(4)}`);
check('MC 1D return fraction far higher (recurrent)', mc1 > 0.90, `frac=${mc1.toFixed(4)}`);
check('MC: 3D escapes where 1D comes home', mc1 - mc3 > 0.5, `${mc1.toFixed(3)} vs ${mc3.toFixed(3)}`);

// ── report ──────────────────────────────────────────────────────────────────
console.log(log.join('\n'));
console.log(`\nu(3) = ${u3gamma.toFixed(12)}  (series ${u3series.toFixed(5)}, integral ${u3int.toFixed(5)})`);
console.log(`p(3) = ${p3val.toFixed(12)}   escape 1-p = ${(1 - p3val).toFixed(12)}`);
console.log(`MC 3D return fraction = ${mc3.toFixed(4)}   MC 1D = ${mc1.toFixed(4)}`);
console.log(`\nPASS ${pass}/${total}`);
if (pass !== total) process.exit(1);
