#!/usr/bin/env node
// verify-the-importance-that-points-at-itself.mjs
//
// The check behind the stratum "The Importance That Points at Itself"
// (public/strata/the-importance-that-points-at-itself/index.html) — PageRank
// as the fixed point of a self-referential definition, made operable.
//
// This verifier checks three of the page's fixed graphs: the headline web and
// dead-end graph by all three methods below, and the trap by methods A and B.
// The methods do NOT reuse each other:
//
//   (A) POWER ITERATION on the Google matrix G = d·S + (1-d)/n·J   (what the page runs live)
//   (B) DIRECT LINEAR SOLVE of (G - I)r = 0, sum(r)=1              (Gaussian elimination — no iteration)
//   (C) MONTE-CARLO random surfer, a single seeded random walk     (probability, not linear algebra)
//
// The claim of the piece is that these three utterly different computations land
// on the same vector. If they ever disagree beyond tolerance, the page is lying —
// so this file fails loudly. Deterministic (seeded PRNG); run:  node verify-the-importance-that-points-at-itself.mjs
'use strict';

// ---------------------------------------------------------------------------
// The canonical graphs. `out[i]` = list of nodes that node i links TO.
// These adjacency lists match the headline web, dead end and trap on the page.
// The healthy graph and editable web are outside this verifier's coverage.
// ---------------------------------------------------------------------------
const GRAPHS = {
  // The headline demo: node E has ONE inbound link, from the important node B;
  // node F has THREE inbound links, all from junk nodes (G,H,I). The claim the
  // page makes — a page with fewer links can outrank a page with more, because
  // rank flows from WHO points, not just HOW MANY, must come out true here.
  quality_beats_quantity: {
    labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
    out: {
      0: [1],        // A -> B
      1: [2, 4],     // B -> C, E   (B is important; it anoints E)
      2: [1, 3],     // C -> B, D
      3: [1],        // D -> B
      4: [1],        // E -> B       (E's single sponsor is the strong node B)
      5: [1],        // F -> B
      6: [5],        // G -> F       (junk)
      7: [5],        // H -> F       (junk)
      8: [5],        // I -> F       (junk)
    },
  },

  // A dangling node (D links to nothing). Without a fix, rank pours into D and
  // off the edge of the world — the walk "falls off." The page shows the leak,
  // then shows forced jumps at dead ends plugging it. The FIXED version conserves
  // mass (sum = 1) and that D does NOT hoard everything.
  dangling: {
    labels: ['A', 'B', 'C', 'D'],
    out: {
      0: [1, 2],  // A -> B, C
      1: [2],     // B -> C
      2: [3],     // C -> D
      3: [],      // D -> (nothing): the sink
    },
  },

  // A spider trap: {C,D} form a 2-cycle with no way out. Without teleport, all
  // rank drowns in the trap. With teleport (d<1) the answer is finite and sane.
  trap: {
    labels: ['A', 'B', 'C', 'D'],
    out: {
      0: [1],     // A -> B
      1: [2],     // B -> C
      2: [3],     // C -> D
      3: [2],     // D -> C   (C<->D trap, no exit)
    },
  },
};

const D = 0.85; // Brin & Page's damping factor — an empirical choice, not a law.

// ---------------------------------------------------------------------------
// Build the column-stochastic surf matrix S (dangling columns spread uniformly),
// then the Google matrix G = d*S + (1-d)/n * J.  S[i][j] = P(go to i | at j).
// ---------------------------------------------------------------------------
function googleMatrix(graph, d = D) {
  const n = graph.labels.length;
  const S = Array.from({ length: n }, () => new Array(n).fill(0));
  for (let j = 0; j < n; j++) {
    const links = graph.out[j] || [];
    if (links.length === 0) {
      for (let i = 0; i < n; i++) S[i][j] = 1 / n; // dangling -> uniform
    } else {
      for (const i of links) S[i][j] += 1 / links.length;
    }
  }
  const G = Array.from({ length: n }, () => new Array(n).fill(0));
  for (let i = 0; i < n; i++)
    for (let j = 0; j < n; j++) G[i][j] = d * S[i][j] + (1 - d) / n;
  return G;
}

// (A) Power iteration: r <- G r, from a uniform start, to a tight tolerance.
function powerIteration(G, tol = 1e-13, maxIt = 100000) {
  const n = G.length;
  let r = new Array(n).fill(1 / n);
  let it = 0;
  for (; it < maxIt; it++) {
    const nr = new Array(n).fill(0);
    for (let i = 0; i < n; i++) {
      let s = 0;
      for (let j = 0; j < n; j++) s += G[i][j] * r[j];
      nr[i] = s;
    }
    let delta = 0;
    for (let i = 0; i < n; i++) delta += Math.abs(nr[i] - r[i]);
    r = nr;
    if (delta < tol) break;
  }
  return { r, iters: it };
}

// (B) Direct solve of the eigenproblem G r = r with sum(r)=1, via Gaussian
// elimination on the augmented (G - I) system with the last row = normalization.
function directSolve(G) {
  const n = G.length;
  const M = Array.from({ length: n }, (_, i) =>
    Array.from({ length: n + 1 }, (_, j) => (j < n ? G[i][j] - (i === j ? 1 : 0) : 0))
  );
  // Replace the last equation with sum(r) = 1 (the null space is 1-D; this pins it).
  for (let j = 0; j < n; j++) M[n - 1][j] = 1;
  M[n - 1][n] = 1;
  // Gaussian elimination with partial pivoting.
  for (let col = 0; col < n; col++) {
    let piv = col;
    for (let r = col + 1; r < n; r++) if (Math.abs(M[r][col]) > Math.abs(M[piv][col])) piv = r;
    [M[col], M[piv]] = [M[piv], M[col]];
    const p = M[col][col];
    for (let j = col; j <= n; j++) M[col][j] /= p;
    for (let r = 0; r < n; r++) {
      if (r === col) continue;
      const f = M[r][col];
      if (f === 0) continue;
      for (let j = col; j <= n; j++) M[r][j] -= f * M[col][j];
    }
  }
  return M.map((row) => row[n]);
}

// (C) Monte-Carlo random surfer: one seeded walk, tally the occupancy.
// PRNG: mulberry32 (deterministic, well-distributed).
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;
  };
}
function monteCarlo(graph, d = D, steps = 4_000_000, seed = 0x1234abcd) {
  const n = graph.labels.length;
  const rand = mulberry32(seed);
  const visits = new Array(n).fill(0);
  let cur = Math.floor(rand() * n);
  const burn = 10000;
  for (let s = 0; s < steps + burn; s++) {
    if (s >= burn) visits[cur]++;
    const links = graph.out[cur] || [];
    if (rand() < 1 - d || links.length === 0) {
      cur = Math.floor(rand() * n); // teleport (or forced from a dangling node)
    } else {
      cur = links[Math.floor(rand() * links.length)];
    }
  }
  return visits.map((v) => v / steps);
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
const l1 = (a, b) => a.reduce((s, x, i) => s + Math.abs(x - b[i]), 0);
const linfty = (a, b) => a.reduce((m, x, i) => Math.max(m, Math.abs(x - b[i])), 0);
const sum = (a) => a.reduce((s, x) => s + x, 0);
const f4 = (x) => x.toFixed(4);
const pct = (x) => (100 * x).toFixed(1) + '%';

let failures = 0;
function check(name, cond, detail) {
  const tag = cond ? 'PASS' : 'FAIL';
  if (!cond) failures++;
  console.log(`  [${tag}] ${name}${detail ? '  —  ' + detail : ''}`);
}

console.log('THE IMPORTANCE THAT POINTS AT ITSELF — verifier\n');
console.log(`Damping d = ${D}.  Three methods must agree on the headline and dead-end graphs; two on the trap.\n`);

// ===========================================================================
// 1. The headline graph: three methods agree, and quality beats quantity.
// ===========================================================================
{
  const g = GRAPHS.quality_beats_quantity;
  const G = googleMatrix(g);
  const { r: rA, iters } = powerIteration(G);
  const rB = directSolve(G);
  const rC = monteCarlo(g);

  console.log('GRAPH "quality beats quantity" (9 nodes):');
  console.log('  PageRank (power iteration): ' + g.labels.map((L, i) => `${L}=${f4(rA[i])}`).join('  '));
  console.log('  Random walk  (4M steps):    ' + g.labels.map((L, i) => `${L}=${f4(rC[i])}`).join('  '));

  // Column-stochastic Google matrix.
  const n = G.length;
  let colOK = true;
  for (let j = 0; j < n; j++) { let c = 0; for (let i = 0; i < n; i++) c += G[i][j]; if (Math.abs(c - 1) > 1e-12) colOK = false; }
  check('Google matrix is column-stochastic (every column sums to 1)', colOK);
  check('PageRank is a probability vector (sums to 1, all positive)',
    Math.abs(sum(rA) - 1) < 1e-9 && rA.every((x) => x > 0), `sum=${f4(sum(rA))}`);

  check('(A) power iteration  ≡  (B) direct linear solve',
    linfty(rA, rB) < 1e-9, `max|A-B| = ${linfty(rA, rB).toExponential(2)} over ${iters} iters`);
  check('(A) power iteration  ≡  (C) random-surfer Monte Carlo',
    linfty(rA, rC) < 3e-3, `max|A-C| = ${linfty(rA, rC).toExponential(2)} (4M steps)`);

  // The showing: E (1 inbound, from strong B) outranks F (3 inbound, from junk).
  const E = 4, F = 5;
  const inbound = (t) => g.labels.filter((_, j) => (g.out[j] || []).includes(t)).length;
  check('THE SHOWING: E outranks F despite fewer inbound links',
    rA[E] > rA[F],
    `E: ${inbound(E)} inbound link → ${f4(rA[E])}   vs   F: ${inbound(F)} inbound links → ${f4(rA[F])}`);

  // Convergence rate: the measured error-decay ratio equals |lambda2|, and the
  // theorem (Haveliwala-Kamvar 2003) says |lambda2| <= d. Verify it operationally.
  {
    let r = new Array(n).fill(1 / n);
    const errs = [];
    for (let k = 0; k < 60; k++) {
      const nr = new Array(n).fill(0);
      for (let i = 0; i < n; i++) { let s = 0; for (let j = 0; j < n; j++) s += G[i][j] * r[j]; nr[i] = s; }
      errs.push(l1(nr, rB));
      r = nr;
    }
    // ratio of successive errors in the asymptotic regime
    const ratios = [];
    for (let k = 5; k < errs.length - 1; k++) if (errs[k] > 1e-14) ratios.push(errs[k + 1] / errs[k]);
    const measured = ratios.length ? ratios[ratios.length - 1] : 0;
    check('convergence ratio |λ₂| ≤ d  (the theorem that makes it fast)',
      measured <= D + 1e-6, `measured |λ₂| ≈ ${f4(measured)}  ≤  d = ${D}`);
  }
  console.log('');
}

// ===========================================================================
// 2. Dangling node: forced jumps conserve mass; the sink does not eat everything.
// ===========================================================================
{
  const g = GRAPHS.dangling;
  const G = googleMatrix(g);
  const { r: rA } = powerIteration(G);
  const rB = directSolve(G);
  const rC = monteCarlo(g, D, 4_000_000, 0x51ee7);
  console.log('GRAPH "dangling" (D links to nothing):');
  console.log('  PageRank: ' + g.labels.map((L, i) => `${L}=${f4(rA[i])}`).join('  '));
  check('three methods agree', linfty(rA, rB) < 1e-9 && linfty(rA, rC) < 3e-3);
  check('mass is conserved with the uniform dead-end rule (sum = 1)', Math.abs(sum(rA) - 1) < 1e-9, `sum=${f4(sum(rA))}`);
  check('the sink D does not swallow all rank', rA[3] < 0.6, `D = ${pct(rA[3])} (not ~100%)`);
  console.log('');
}

// ===========================================================================
// 3. Spider trap: with teleport the answer is finite; without it, the trap wins.
// ===========================================================================
{
  const g = GRAPHS.trap;
  const G = googleMatrix(g);
  const { r: rA } = powerIteration(G);
  const rB = directSolve(G);
  console.log('GRAPH "spider trap" (C↔D, no exit):');
  console.log('  PageRank (d=0.85): ' + g.labels.map((L, i) => `${L}=${f4(rA[i])}`).join('  '));
  check('power iteration ≡ direct solve', linfty(rA, rB) < 1e-9);
  const trapMass = rA[2] + rA[3];
  check('the trap holds most — but not all — of the rank', trapMass > 0.5 && trapMass < 1,
    `C+D = ${pct(trapMass)}`);

  // Without teleport (d=1) the trap would take everything. Show the contrast honestly.
  const G1 = googleMatrix(g, 1.0);
  const { r: r1 } = powerIteration(G1, 1e-13, 200000);
  check('without teleport (d=1) the trap swallows ~all the rank', (r1[2] + r1[3]) > 0.999,
    `C+D = ${pct(r1[2] + r1[3])} when d=1`);
  console.log('');
}

// ===========================================================================
console.log(failures === 0
  ? `ALL CHECKS PASSED — the random walk, the eigenvector, and the linear solve are one number.`
  : `${failures} CHECK(S) FAILED.`);
process.exit(failures === 0 ? 0 : 1);
