#!/usr/bin/env node
// verify.mjs — the apparatus behind the portal "A Number That Isn't Whole"
// (the fractal-dimension spine). Every dimension quoted on the page is either
// recomputed here from scratch, or marked as cited-to-a-theorem and NOT
// recomputed. Run: `node research/fractal-dimension/verify.mjs`
//
// The spine's one load-bearing claim: for these objects the ordinary measure
// (length, area) is the wrong question — it diverges, or vanishes, or is
// unknown — and the only scale-stable answer to "how big?" is an exponent,
// the box-counting / Minkowski dimension, which need NOT be a whole number.
// Finite counts estimate dimensions. The cited theorems establish exact
// dimensions for the self-similar sets and the Mandelbrot boundary.
//
// No dependencies. Pure Node. Deterministic.

let pass = 0, fail = 0;
const eps = 1e-12;
function ok(name, cond, detail = '') {
  if (cond) { pass++; console.log(`  ✓ ${name}${detail ? '  — ' + detail : ''}`); }
  else { fail++; console.log(`  ✗ ${name}${detail ? '  — ' + detail : ''}`); }
}
function near(a, b, tol) { return Math.abs(a - b) <= tol; }
const r = (x, n = 6) => Number(x.toFixed(n));

// ---------------------------------------------------------------------------
// Least-squares slope of log(N) against log(s), where s = boxes-per-side
// (so the inverse box size). A finite fitted slope estimates box dimension.
// ---------------------------------------------------------------------------
function slope(points /* [{s,N}] */) {
  const xs = points.map(p => Math.log(p.s));
  const ys = points.map(p => Math.log(p.N));
  const n = xs.length;
  const mx = xs.reduce((a, b) => a + b, 0) / n;
  const my = ys.reduce((a, b) => a + b, 0) / n;
  let num = 0, den = 0;
  for (let i = 0; i < n; i++) { num += (xs[i] - mx) * (ys[i] - my); den += (xs[i] - mx) ** 2; }
  return num / den;
}

console.log('\n=== A. The closed-form dimensions (numerical evaluations) ===\n');
console.log('  Each is D = log(N)/log(s): an attractor made of N copies of itself,');
console.log('  each scaled down by 1/s. None of the four is a whole number.\n');

const FORMS = [
  { name: 'Cantor set',           N: 2, s: 3, D: Math.log(2) / Math.log(3) },
  { name: 'Koch curve',           N: 4, s: 3, D: Math.log(4) / Math.log(3) },
  { name: 'Sierpinski triangle',  N: 3, s: 2, D: Math.log(3) / Math.log(2) },
  { name: 'Sierpinski carpet',    N: 8, s: 3, D: Math.log(8) / Math.log(3) },
];
for (const f of FORMS) {
  const D = Math.log(f.N) / Math.log(f.s);
  ok(`${f.name}: D = log${f.N}/log${f.s} = ${r(D)}`, near(D, f.D, eps));
  ok(`${f.name}: D is NOT an integer`, Math.abs(D - Math.round(D)) > 1e-3,
     `nearest integer is ${Math.round(D)}, off by ${r(Math.abs(D - Math.round(D)), 4)}`);
}
// the values quoted verbatim on the page
ok('quoted: Cantor D = 0.6309', near(Math.log(2) / Math.log(3), 0.6309, 5e-5));
ok('quoted: Koch D = 1.2619', near(Math.log(4) / Math.log(3), 1.2619, 5e-5));
ok('quoted: Sierpinski triangle D = 1.5850', near(Math.log(3) / Math.log(2), 1.5850, 5e-5));
ok('quoted: Sierpinski carpet D = 1.8928', near(Math.log(8) / Math.log(3), 1.8928, 5e-5));

console.log('\n=== B. The box-count recovers those forms EXACTLY (integer counts) ===\n');
console.log('  For the digit-defined self-similar sets, box-counting at the natural');
console.log('  scales is not an approximation: the occupied-box count is an exact');
console.log('  integer, m^k, and the slope is exactly log(m)/log(base).\n');

// --- Cantor set: keep base-3 strings with no digit == 1. At scale 3^-k the
//     set sits in exactly 2^k intervals. Count by enumeration.
{
  const pts = [];
  for (let k = 1; k <= 12; k++) {
    // count length-k base-3 strings using only digits {0,2}
    let count = 0;
    const total = 3 ** k;
    for (let i = 0; i < total; i++) {
      let x = i, good = true;
      for (let d = 0; d < k; d++) { if (x % 3 === 1) { good = false; break; } x = (x / 3) | 0; }
      if (good) count++;
    }
    ok(`Cantor: scale 3^-${k} → ${count} intervals (expect 2^${k}=${2 ** k})`, count === 2 ** k);
    pts.push({ s: 3 ** k, N: count });
  }
  const D = slope(pts);
  ok(`Cantor: box-count slope = ${r(D)} = log2/log3`, near(D, Math.log(2) / Math.log(3), 1e-9));
}

// --- Sierpinski triangle via the bit test (x & y) == 0. At resolution 2^k the
//     occupied-box count is exactly 3^k.
{
  const pts = [];
  for (let k = 1; k <= 9; k++) {
    const side = 1 << k;
    let count = 0;
    for (let y = 0; y < side; y++) for (let x = 0; x < side; x++) if ((x & y) === 0) count++;
    ok(`Sierpinski △: resolution 2^${k} → ${count} cells (expect 3^${k}=${3 ** k})`, count === 3 ** k);
    pts.push({ s: side, N: count });
  }
  const D = slope(pts);
  ok(`Sierpinski △: box-count slope = ${r(D)} = log3/log2`, near(D, Math.log(3) / Math.log(2), 1e-9));
}

// --- Sierpinski carpet via base-3 digits: a cell survives iff no digit position
//     has BOTH coordinates' digit == 1. At resolution 3^k the count is 8^k.
{
  const pts = [];
  for (let k = 1; k <= 6; k++) {
    const side = 3 ** k;
    let count = 0;
    for (let y = 0; y < side; y++) for (let x = 0; x < side; x++) {
      let xx = x, yy = y, good = true;
      for (let d = 0; d < k; d++) { if (xx % 3 === 1 && yy % 3 === 1) { good = false; break; } xx = (xx / 3) | 0; yy = (yy / 3) | 0; }
      if (good) count++;
    }
    ok(`Sierpinski carpet: resolution 3^${k} → ${count} cells (expect 8^${k}=${8 ** k})`, count === 8 ** k);
    pts.push({ s: side, N: count });
  }
  const D = slope(pts);
  ok(`Sierpinski carpet: box-count slope = ${r(D)} = log8/log3`, near(D, Math.log(8) / Math.log(3), 1e-9));
}

console.log('\n=== C. The integer controls (a smooth curve is 1, a filled patch is 2) ===\n');
console.log('  The instrument must give back ordinary integers on ordinary objects,');
console.log('  or its fractions would mean nothing.\n');

// --- Filled square: every box is occupied, so N(scale s) = s^2 exactly → slope 2.
{
  const pts = [];
  for (let k = 1; k <= 8; k++) { const s = 1 << k; pts.push({ s, N: s * s }); }
  const D = slope(pts);
  ok(`filled square: box-count slope = ${r(D)} = 2 exactly`, near(D, 2, 1e-9));
}

// --- A smooth circle (its boundary curve). Rasterize the unit circle onto an
//     R x R grid by dense angular sampling, then box-count. Expect ~1.
function rasterCircle(R) {
  const grid = new Uint8Array(R * R);
  const cx = R / 2, cy = R / 2, rad = R * 0.45;
  const steps = R * 12;
  for (let i = 0; i < steps; i++) {
    const t = (2 * Math.PI * i) / steps;
    const x = Math.floor(cx + rad * Math.cos(t));
    const y = Math.floor(cy + rad * Math.sin(t));
    if (x >= 0 && x < R && y >= 0 && y < R) grid[y * R + x] = 1;
  }
  return grid;
}
// generic box-count on an R x R occupancy grid (R a power of two), over
// box pixel sizes R/2^level for level = lo..hi.
function boxCountGrid(grid, R, lo, hi) {
  const pts = [];
  for (let lvl = lo; lvl <= hi; lvl++) {
    const sPer = 1 << lvl;            // boxes per side
    const box = R / sPer;             // pixels per box
    const occ = new Set();
    for (let y = 0; y < R; y++) for (let x = 0; x < R; x++) {
      if (grid[y * R + x]) occ.add(((y / box) | 0) * sPer + ((x / box) | 0));
    }
    pts.push({ s: sPer, N: occ.size });
  }
  return pts;
}
{
  const R = 1024;
  const grid = rasterCircle(R);
  const pts = boxCountGrid(grid, R, 2, 7);
  const D = slope(pts);
  ok(`smooth circle: box-count slope = ${r(D)} ≈ 1`, near(D, 1, 0.08), `(integer 1, as a curve should be)`);
}

console.log('\n=== D. Koch curve: similarity pieces and a finite estimate ===\n');
console.log('  Two facts. (1) The construction has 4^k similarity pieces scaled by');
console.log('  3^-k. The cited self-similarity theorem gives D = log4/log3.');
console.log('  (2) This rasterized Koch estimate is tested within 0.03 of that value.\n');

// (1) similarity-piece recurrence, not a grid cover: each segment splits into 4.
{
  let segs = 1, good = true;
  for (let k = 1; k <= 8; k++) { segs *= 4; if (segs !== 4 ** k) good = false; }
  ok('Koch: 4^k similarity pieces scaled by 3^-k', good && segs === 4 ** 8,
     `4^8 = ${4 ** 8} segments of length 3^-8`);
  const D = Math.log(4) / Math.log(3);
  ok(`Koch: cited theorem gives D = log4/log3 = ${r(D)}`, near(D, 1.2618595, 1e-6));
}
// (2) generate the Koch curve points (L-system), rasterize, blind box-count.
function kochPoints(iter) {
  let pts = [{ x: 0, y: 0 }, { x: 1, y: 0 }];
  for (let it = 0; it < iter; it++) {
    const next = [];
    for (let i = 0; i < pts.length - 1; i++) {
      const a = pts[i], b = pts[i + 1];
      const dx = b.x - a.x, dy = b.y - a.y;
      const p1 = { x: a.x + dx / 3, y: a.y + dy / 3 };
      const p3 = { x: a.x + 2 * dx / 3, y: a.y + 2 * dy / 3 };
      // apex: rotate (p3-p1) by -60 degrees about p1
      const ux = p3.x - p1.x, uy = p3.y - p1.y;
      const ang = -Math.PI / 3;
      const p2 = { x: p1.x + ux * Math.cos(ang) - uy * Math.sin(ang),
                   y: p1.y + ux * Math.sin(ang) + uy * Math.cos(ang) };
      next.push(a, p1, p2, p3);
    }
    next.push(pts[pts.length - 1]);
    pts = next;
  }
  return pts;
}
{
  const R = 4374; // 2 * 3^7, comfortably finer than the box scales used
  const pts = kochPoints(7);
  const grid = new Uint8Array(R * R);
  // bounding box of the curve
  let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
  for (const p of pts) { minX = Math.min(minX, p.x); maxX = Math.max(maxX, p.x); minY = Math.min(minY, p.y); maxY = Math.max(maxY, p.y); }
  const span = Math.max(maxX - minX, maxY - minY) * 1.04;
  const ox = minX - (span - (maxX - minX)) / 2, oy = minY - (span - (maxY - minY)) / 2;
  const toG = (p) => ({ gx: Math.floor(((p.x - ox) / span) * (R - 1)), gy: Math.floor(((p.y - oy) / span) * (R - 1)) });
  // rasterize each segment by dense sampling
  for (let i = 0; i < pts.length - 1; i++) {
    const A = toG(pts[i]), B = toG(pts[i + 1]);
    const n = Math.max(2, Math.abs(B.gx - A.gx) + Math.abs(B.gy - A.gy));
    for (let t = 0; t <= n; t++) {
      const gx = Math.round(A.gx + (B.gx - A.gx) * t / n);
      const gy = Math.round(A.gy + (B.gy - A.gy) * t / n);
      if (gx >= 0 && gx < R && gy >= 0 && gy < R) grid[gy * R + gx] = 1;
    }
  }
  // box-count at scales s = 3^k (k=2..6), box = R/3^k
  const bc = [];
  for (let k = 2; k <= 6; k++) {
    const sPer = 3 ** k, box = R / sPer, occ = new Set();
    for (let y = 0; y < R; y++) for (let x = 0; x < R; x++) {
      if (grid[y * R + x]) occ.add(((y / box) | 0) * sPer + ((x / box) | 0));
    }
    bc.push({ s: sPer, N: occ.size });
  }
  const D = slope(bc);
  ok(`Koch: blind box-count slope = ${r(D)} ≈ log4/log3 = 1.2619 (within 0.03)`,
     near(D, Math.log(4) / Math.log(3), 0.03), `off by ${r(Math.abs(D - Math.log(4) / Math.log(3)), 4)}`);
}

console.log('\n=== E. The wall — the Mandelbrot boundary, where counting fails ===\n');
console.log('  Shishikura (1991, pub. 1998): the boundary of the Mandelbrot set has');
console.log('  Hausdorff dimension EXACTLY 2 — a curve as large, by this measure, as');
console.log('  an area. That is a THEOREM, cited, not recomputed. What a finite');
console.log('  box-count of a finite-resolution render gives is something else: a');
console.log('  number near 1.1 — barely more than a smooth curve — that comes nowhere');
console.log('  near 2 at the three tested resolutions and 1000 iterations. The');
console.log('  dimension-2 crinkle lives at scales finer, and iteration-depths deeper,');
console.log('  than any finite picture reaches. These finite estimates do not');
console.log('  certify an exact dimension; that rests on the cited theorem.\n');

function mandelBoundary(R, maxIter) {
  // mark cells whose escape status differs from a neighbour: the boundary set.
  const inSet = new Uint8Array(R * R);
  const xmin = -2.0, xmax = 0.6, ymin = -1.3, ymax = 1.3;
  for (let j = 0; j < R; j++) {
    const cy = ymin + (ymax - ymin) * j / (R - 1);
    for (let i = 0; i < R; i++) {
      const cx = xmin + (xmax - xmin) * i / (R - 1);
      let zx = 0, zy = 0, n = 0;
      while (zx * zx + zy * zy <= 4 && n < maxIter) { const t = zx * zx - zy * zy + cx; zy = 2 * zx * zy + cy; zx = t; n++; }
      inSet[j * R + i] = (n >= maxIter) ? 1 : 0;
    }
  }
  const bd = new Uint8Array(R * R);
  for (let j = 1; j < R - 1; j++) for (let i = 1; i < R - 1; i++) {
    const c = inSet[j * R + i];
    if (c !== inSet[j * R + i - 1] || c !== inSet[j * R + i + 1] ||
        c !== inSet[(j - 1) * R + i] || c !== inSet[(j + 1) * R + i]) bd[j * R + i] = 1;
  }
  return bd;
}
{
  const measured = [];
  for (const R of [256, 512, 1024]) {
    const bd = mandelBoundary(R, 1000);
    // box-count the boundary set; scales 2^k boxes per side
    const pts = [];
    for (let lvl = 3; lvl <= 7; lvl++) {
      const sPer = 1 << lvl, box = R / sPer, occ = new Set();
      for (let y = 0; y < R; y++) for (let x = 0; x < R; x++) {
        if (bd[y * R + x]) occ.add(((y / box) | 0) * sPer + ((x / box) | 0));
      }
      pts.push({ s: sPer, N: occ.size });
    }
    const D = slope(pts);
    measured.push({ R, D });
    console.log(`     resolution ${R}² → measured box-dimension ≈ ${r(D, 3)}  (theorem: 2)`);
  }
  ok('Mandelbrot ∂: each of the three tested readings is below 1.4',
     measured.every(m => m.D < 1.4), `got ${measured.map(m => r(m.D, 3)).join(', ')}`);
  ok('Mandelbrot ∂: these three gaps exceed 0.6, without a monotone climb toward 2',
     measured.every(m => 2 - m.D > 0.6) && !(measured[2].D > measured[1].D && measured[1].D > measured[0].D),
     `gap stays ~${r(2 - measured[2].D, 2)}; no monotone climb toward 2`);
  ok('Mandelbrot ∂: D = 2 is Shishikura\'s THEOREM; finite counts do not certify it [cited]', true,
     'M. Shishikura, Ann. of Math. 147 (1998) 225–267');
}

console.log('\n=== F. The cited values (theorems & published numerics, NOT recomputed) ===\n');
// These appear on the page marked as cited. We assert only that the numbers
// quoted match the literature values we attribute them to.
const CITED = [
  ['Mandelbrot boundary D = 2 (Shishikura 1998)', 2, 2, 0],
  ['Apollonian gasket residual set D ≈ 1.305688 (McMullen 1998)', 1.305688, 1.305688, 5e-6],
  ['Britain west coast D ≈ 1.25 (Mandelbrot 1967, from Richardson)', 1.25, 1.25, 0.01],
  ['Norway coast D ≈ 1.52 (Feder 1988)', 1.52, 1.52, 0.02],
];
for (const [name, quoted, lit, tol] of CITED) {
  ok(`cited value internally consistent: ${name}`, near(quoted, lit, tol));
}

// ---------------------------------------------------------------------------
console.log(`\n=== ${pass}/${pass + fail} checks pass ===\n`);
if (fail > 0) { console.log(`${fail} FAILED`); process.exit(1); }
