// verify.mjs — offline verification for the stratum "All Edge, No Middle"
// (high-dimensional geometry / the curse of dimensionality).
//
// Every headline number on the page is recomputed here two independent ways
// where possible (a closed form AND a from-scratch recursion or Monte-Carlo
// estimate), and the two must agree. Run:
//
//     node research/high-dimensional-geometry/verify.mjs
//
// Exit code 0 == all checks green. Nonzero == a mismatch to investigate.
//
// The mathematics (all standard; anchored in Blum, Hopcroft & Kannan,
// "Foundations of Data Science", ch. 2, "High-Dimensional Space"):
//   * Volume of the unit n-ball:  V_n = pi^(n/2) / Gamma(n/2 + 1).
//   * Inscribed ball / cube [-1,1]^n ratio:  R_n = V_n / 2^n.
//   * Uniform point in the ball: radius CDF F(r)=r^n, median r = (1/2)^(1/n).
//   * Two random unit vectors: E[cos] = 0, Var[cos] = 1/n.
//   * Distance concentration (Beyer et al. 1999): relative contrast -> 0.

'use strict';

let fails = 0;
const approx = (a, b, tol) => Math.abs(a - b) <= tol;
function check(name, cond, detail = '') {
  const tag = cond ? '  ok ' : 'FAIL ';
  if (!cond) fails++;
  console.log(`${tag} ${name}${detail ? '   ' + detail : ''}`);
}
function section(t) { console.log('\n' + t); console.log('-'.repeat(t.length)); }

// ---- Lanczos approximation for ln Gamma (independent of any library) --------
const G = 7;
const C = [
  0.99999999999980993, 676.5203681218851, -1259.1392167224028,
  771.32342877765313, -176.61502916214059, 12.507343278686905,
  -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7,
];
function lnGamma(z) {
  if (z < 0.5) {
    // reflection
    return Math.log(Math.PI / Math.sin(Math.PI * z)) - lnGamma(1 - z);
  }
  z -= 1;
  let x = C[0];
  for (let i = 1; i < G + 2; i++) x += C[i] / (z + i);
  const t = z + G + 0.5;
  return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(x);
}
const lnVolBall = (n) => (n / 2) * Math.log(Math.PI) - lnGamma(n / 2 + 1);
const volBallClosed = (n) => Math.exp(lnVolBall(n));

// ---- Independent cross-check: the two-step recursion V_n = (2*pi/n)*V_{n-2} --
// with V_0 = 1 (a point has "volume" 1) and V_1 = 2 (the segment [-1,1]).
function volBallRecursion(nMax) {
  const V = new Array(nMax + 1);
  V[0] = 1; V[1] = 2;
  for (let n = 2; n <= nMax; n++) V[n] = (2 * Math.PI / n) * V[n - 2];
  return V;
}

// ============================================================================
section('1. Volume of the unit n-ball V_n — closed form vs. recursion');
// ============================================================================
const Vrec = volBallRecursion(24);
const knownV = {
  1: 2, 2: Math.PI, 3: 4 * Math.PI / 3, 4: Math.PI ** 2 / 2,
  5: 8 * Math.PI ** 2 / 15, 6: Math.PI ** 3 / 6,
};
for (const n of [1, 2, 3, 4, 5, 6]) {
  const c = volBallClosed(n);
  check(`V_${n} closed form = known exact`, approx(c, knownV[n], 1e-9),
    `${c.toFixed(6)} vs ${knownV[n].toFixed(6)}`);
}
for (const n of [1, 2, 3, 4, 5, 6, 7, 10, 15, 20, 24]) {
  check(`V_${n}: closed form == recursion`, approx(volBallClosed(n), Vrec[n], 1e-8 * Math.max(1, Vrec[n])),
    `${volBallClosed(n).toExponential(6)}`);
}
// The volume peaks at n=5 among integers, then falls to zero.
const vols = [];
for (let n = 1; n <= 24; n++) vols.push(volBallClosed(n));
let argmax = 1, vmax = 0;
for (let n = 1; n <= 24; n++) if (vols[n - 1] > vmax) { vmax = vols[n - 1]; argmax = n; }
check('unit-ball volume is maximised at n = 5', argmax === 5, `argmax=${argmax}, V_5=${vmax.toFixed(6)}`);
check('V_5 ≈ 5.263789', approx(volBallClosed(5), 5.2637890139, 1e-6));
check('V_n keeps falling: V_24 < V_20 < V_10 < V_5',
  volBallClosed(24) < volBallClosed(20) && volBallClosed(20) < volBallClosed(10) && volBallClosed(10) < volBallClosed(5));
check('V_20 ≈ 0.0258069', approx(volBallClosed(20), 0.0258069, 1e-5), volBallClosed(20).toFixed(7));

// ============================================================================
section('2. The box is all corner — R_n = V_n / 2^n  (inscribed ball / cube)');
// ============================================================================
const Rn = (n) => Math.exp(lnVolBall(n) - n * Math.log(2));
const knownR = {
  1: 1, 2: Math.PI / 4, 3: Math.PI / 6, 4: Math.PI ** 2 / 32, 5: Math.PI ** 2 / 60,
};
for (const n of [1, 2, 3, 4, 5]) {
  check(`R_${n} = V_${n}/2^${n} matches exact`, approx(Rn(n), knownR[n], 1e-9),
    `${Rn(n).toFixed(6)} (=${(Rn(n) * 100).toFixed(3)}%)`);
}
check('R_2 = pi/4 ≈ 0.785398 (disk fills 78.5% of the square)', approx(Rn(2), 0.7853982, 1e-6));
check('R_3 = pi/6 ≈ 0.523599 (ball fills 52.4% of the cube)', approx(Rn(3), 0.5235988, 1e-6));
check('R_10 ≈ 0.0024904 (~0.25% of the box)', approx(Rn(10), 0.0024904, 1e-6), Rn(10).toExponential(5));
// extreme dimensions via logs
const logR100 = (lnVolBall(100) - 100 * Math.log(2)) / Math.log(10);
check('R_100 ≈ 10^(-70) (log10 in [-71,-69])', logR100 < -69 && logR100 > -71, `log10 R_100 = ${logR100.toFixed(3)}`);

// Monte-Carlo cross-check of R_n for small n: throw points into [-1,1]^n, count inside ball.
function mcRatio(n, N) {
  let inside = 0;
  for (let i = 0; i < N; i++) {
    let s = 0;
    for (let d = 0; d < n; d++) { const x = 2 * Math.random() - 1; s += x * x; }
    if (s <= 1) inside++;
  }
  return inside / N;
}
for (const n of [2, 3, 4, 6]) {
  const est = mcRatio(n, 400000);
  check(`Monte-Carlo R_${n} matches closed form (±0.01)`, approx(est, Rn(n), 0.01),
    `MC=${est.toFixed(4)} exact=${Rn(n).toFixed(4)}`);
}

// ============================================================================
section('3. The orange is all peel — radius of a uniform point in the ball');
// ============================================================================
// CDF F(r) = r^n, so median radius = (1/2)^(1/n), mean radius = n/(n+1).
const median = (n) => Math.pow(0.5, 1 / n);
const meanR = (n) => n / (n + 1);
check('median radius, n=1 = 0.5', approx(median(1), 0.5, 1e-12));
check('median radius, n=100 ≈ 0.99309 (half the volume in the outer 0.69% of r)',
  approx(median(100), 0.9930925, 1e-6), median(100).toFixed(7));
check('mean radius -> 1: n=100 gives 100/101 ≈ 0.990099', approx(meanR(100), 0.990099, 1e-6));
// fraction of volume within relative radius 0.9 for n=100 is 0.9^100
check('n=100: fraction of volume within r<0.9 is 0.9^100 ≈ 2.66e-5',
  approx(Math.pow(0.9, 100), 2.6561398e-5, 1e-9), Math.pow(0.9, 100).toExponential(4));
// outer shell of relative thickness eps holds 1-(1-eps)^n; for n=100, eps=0.045:
const shell = 1 - Math.pow(1 - 0.045, 100);
check('n=100: outer 4.5% of the radius holds ≈ 99% of the volume',
  shell > 0.98, `${(shell * 100).toFixed(2)}%`);

// Monte-Carlo: sample uniform-in-ball radii and compare the sample median to (1/2)^(1/n).
// Uniform in ball = (Gaussian direction) * U^(1/n).
function gauss() { // Box-Muller
  let u = 0, v = 0;
  while (u === 0) u = Math.random();
  while (v === 0) v = Math.random();
  return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
}
function mcMedianRadius(n, N) {
  const rs = new Array(N);
  for (let i = 0; i < N; i++) rs[i] = Math.pow(Math.random(), 1 / n); // radius alone; direction irrelevant
  rs.sort((a, b) => a - b);
  return rs[Math.floor(N / 2)];
}
for (const n of [2, 10, 100]) {
  const est = mcMedianRadius(n, 200000);
  check(`Monte-Carlo median radius matches (1/2)^(1/n), n=${n}`, approx(est, median(n), 0.01),
    `MC=${est.toFixed(4)} exact=${median(n).toFixed(4)}`);
}

// ============================================================================
section('4. Everything is a right angle — cosine of two random unit vectors');
// ============================================================================
// For u,v uniform on S^(n-1): E[cos] = 0, Var[cos] = 1/n.
function mcCosStats(n, pairs) {
  let sum = 0, sumSq = 0;
  for (let p = 0; p < pairs; p++) {
    const a = new Array(n), b = new Array(n);
    let na = 0, nb = 0;
    for (let d = 0; d < n; d++) { a[d] = gauss(); b[d] = gauss(); na += a[d] * a[d]; nb += b[d] * b[d]; }
    na = Math.sqrt(na); nb = Math.sqrt(nb);
    let dot = 0;
    for (let d = 0; d < n; d++) dot += (a[d] / na) * (b[d] / nb);
    sum += dot; sumSq += dot * dot;
  }
  const mean = sum / pairs;
  const varc = sumSq / pairs - mean * mean;
  return { mean, varc };
}
for (const n of [2, 10, 100, 1000]) {
  const { mean, varc } = mcCosStats(n, 20000);
  check(`n=${n}: mean cosine ≈ 0`, approx(mean, 0, 0.02), `mean=${mean.toFixed(4)}`);
  // Var should be ~1/n; MC tolerance loosens for small n. Relative check.
  check(`n=${n}: Var[cos] ≈ 1/n = ${(1 / n).toFixed(5)}`, approx(varc, 1 / n, Math.max(0.02 / n * n, 0.15 / Math.sqrt(n)) + 0.5 / n),
    `Var=${varc.toFixed(5)}`);
}
// The angle: std of cosine = 1/sqrt(n). n=1000 -> ~0.0316 -> within ~1.8 deg of 90.
const stdCos1000 = 1 / Math.sqrt(1000);
const degOff = Math.acos(stdCos1000) * 180 / Math.PI; // angle whose cosine is one std away
check('n=1000: one std of cosine = 1/sqrt(1000) ≈ 0.0316', approx(stdCos1000, 0.0316228, 1e-6));
check('n=1000: a typical pair sits within ~1.8° of a right angle', approx(90 - degOff, 1.812, 0.05),
  `${(90 - degOff).toFixed(3)} deg`);

// ============================================================================
section('5. The curse for nearest-neighbour — distance concentration');
// ============================================================================
// Beyer et al. 1999: for iid points, relative contrast (Dmax - Dmin)/Dmin -> 0.
// Sample m Gaussian points in R^n, measure all pairwise distances.
function relativeContrast(n, m) {
  const pts = [];
  for (let i = 0; i < m; i++) { const v = new Array(n); for (let d = 0; d < n; d++) v[d] = gauss(); pts.push(v); }
  let dmin = Infinity, dmax = 0, dsum = 0, cnt = 0;
  for (let i = 0; i < m; i++) for (let j = i + 1; j < m; j++) {
    let s = 0; for (let d = 0; d < n; d++) { const t = pts[i][d] - pts[j][d]; s += t * t; }
    const dist = Math.sqrt(s);
    if (dist < dmin) dmin = dist; if (dist > dmax) dmax = dist; dsum += dist; cnt++;
  }
  return { contrast: (dmax - dmin) / dmin, meanDist: dsum / cnt, expected: Math.sqrt(2 * n) };
}
// The exact mean pairwise distance, not the asymptotic. X-Y ~ N(0, 2I_n), so
// ||X-Y|| = sqrt(2)*chi_n and E||X-Y|| = 2*Gamma((n+1)/2)/Gamma(n/2). The page's
// "≈ sqrt(2n)" is that quantity's LARGE-n limit and is right about the subject;
// checking a Monte Carlo against it at n=2 was not, because the two differ by
// 11.4% there (1.7725 vs 2.0000) and the 15% tolerance covered the gap with only
// ~1.1 standard errors to spare. The check therefore failed on roughly one run in
// six, from noise alone. Found 2026-07-26 by research/self-check/, which ran every
// verifier the site cites and caught this one disagreeing with itself.
const LANCZOS = [676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059,
  12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7];
function lgamma(z) {
  if (z < 0.5) return Math.log(Math.PI / Math.sin(Math.PI * z)) - lgamma(1 - z);
  z -= 1;
  let x = 0.99999999999980993;
  for (let i = 0; i < 8; i++) x += LANCZOS[i] / (z + i + 1);
  const t = z + 7.5;
  return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(x);
}
const exactMeanDist = (n) => 2 * Math.exp(lgamma((n + 1) / 2) - lgamma(n / 2));

// Sample size and tolerance per n, sized from the estimator's MEASURED spread
// rather than a guessed percentage. The 200 points give only 200 independent
// draws however many pairs they make, so the standard error falls like 1/sqrt(m),
// not 1/sqrt(pairs). Measured over 40 replications on 2026-07-26 the relative
// standard error was 3.34% at (n=2, m=200) and 1.15% at (n=2, m=2000); each
// tolerance below is at least six of those, so a green run is evidence and a red
// one is a real disagreement. The contrast check keeps m=200 so its comparison
// across n stays like for like.
const MEAN_SAMPLE = { 2: [2000, 0.08], 10: [1500, 0.05], 100: [400, 0.03], 1000: [200, 0.015] };

let prevContrast = Infinity;
for (const n of [2, 10, 100, 1000]) {
  const { contrast, expected } = relativeContrast(n, 200);
  const [m, tol] = MEAN_SAMPLE[n];
  const { meanDist } = relativeContrast(n, m);
  const exact = exactMeanDist(n);
  check(`n=${n}: mean pairwise distance matches the exact 2G((n+1)/2)/G(n/2) = ${exact.toFixed(3)}`,
    approx(meanDist, exact, tol * exact), `mean=${meanDist.toFixed(3)} over ${m} points (tol ${(tol * 100).toFixed(1)}%)`);
  check(`n=${n}: and sqrt(2n) = ${expected.toFixed(2)} is that value's large-n limit (ratio -> 1)`,
    exact / expected <= 1 && exact / expected > (n >= 100 ? 0.995 : n >= 10 ? 0.97 : 0.88),
    `exact/sqrt(2n)=${(exact / expected).toFixed(5)}`);
  check(`n=${n}: relative contrast (Dmax-Dmin)/Dmin shrinks with n`, contrast < prevContrast + 1e-9,
    `contrast=${contrast.toFixed(3)}`);
  prevContrast = contrast;
}

// ============================================================================
section('SUMMARY');
// ============================================================================
if (fails === 0) {
  console.log('\nALL CHECKS GREEN — every headline number on the page is reproduced here.');
  process.exit(0);
} else {
  console.log(`\n${fails} CHECK(S) FAILED.`);
  process.exit(1);
}
