// verify-not-one-branches-the-same.mjs — the arithmetic behind the stratum
// "Not One Branches the Same" (/strata/not-one-branches-the-same/).
//
// THE SPINE. Five things branch — a compound leaf, an antler, the lung, a river
// network, a lightning stroke — and look like one family called "fractal." But
// each grows by a DIFFERENT rule, and the "it's all fractals" unification is
// either too short-ranged to mean anything (Avnir 1998) or, where it does hold,
// so statistically inevitable it explains nothing (Kirchner 1993).
//
// This script recomputes, offline and from first principles, EVERY number the
// page computes in front of the reader. It uses the identical algorithms and
// the identical seeded PRNG (mulberry32) as the page, so the page's live
// readouts are reproduced here bit-for-bit — not asserted.
//
//   run:  node research/not-one-branches-the-same/verify-not-one-branches-the-same.mjs
//
// No dependencies. What is PROVED here vs merely CITED is stated in each block.

let pass = 0, total = 0;
const ok = (name, cond, extra = '') => {
  total++; if (cond) pass++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const approx = (a, b, eps) => Math.abs(a - b) <= eps;
const gmean = (a) => Math.exp(a.reduce((s, x) => s + Math.log(x), 0) / a.length);
function lsq(xs, ys) { // least-squares slope of ys vs xs
  const n = xs.length, mx = xs.reduce((a, b) => a + b, 0) / n, 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;
}

// ════════════════════════════════════════════════════════════════════════════
// A.  MURRAY'S MINIMUM-WORK LAW  →  the 2^(-1/3) diameter ratio, derived live
// ════════════════════════════════════════════════════════════════════════════
// PROVED in-browser. A vessel of radius r carrying volume flow Q pays two costs:
//   (1) viscous power to push the flow (Poiseuille):  P_flow = 8*mu*L*Q^2/(pi*r^4)
//   (2) metabolic power to keep the blood/lumen alive:  P_meta = b*(pi*r^2*L)
// Minimising the total over r gives r^6 ∝ Q^2, i.e. Q ∝ r^3 — Murray's law.
// At a SYMMETRIC dichotomy the parent's Q splits in two, so each daughter carries
// Q/2 and r_daughter/r_parent = (1/2)^(1/3) = 2^(-1/3). No self-similar cascade
// is assumed; the ratio FALLS OUT of the optimisation.
console.log('\n── A. Murray minimum-work → diameter ratio 2^(-1/3) ──');
function optimalRadius(Q, mu = 1, b = 1) {
  const cost = (r) => 8 * mu * Q * Q / (Math.PI * Math.pow(r, 4)) + b * Math.PI * r * r;
  let lo = 1e-3, hi = 1e3; // ternary search on the convex cost
  for (let i = 0; i < 200; i++) {
    const m1 = lo + (hi - lo) / 3, m2 = hi - (hi - lo) / 3;
    if (cost(m1) < cost(m2)) hi = m2; else lo = m1;
  }
  return (lo + hi) / 2;
}
const rQ1 = optimalRadius(1), rQ2 = optimalRadius(2), rQ8 = optimalRadius(8);
const flowExp = Math.log(rQ8 / rQ1) / Math.log(8);            // d log r / d log Q  → 1/3
const ratioDichotomy = optimalRadius(0.5) / optimalRadius(1); // daughter (Q/2) over parent (Q)
const cubeRoot = Math.pow(2, -1 / 3);
ok('optimal radius scales as Q^(1/3) (Murray)', approx(flowExp, 1 / 3, 1e-3), `exp=${flowExp.toFixed(4)}`);
ok('two daughters, half flow each → r ratio = 2^(-1/3)', approx(ratioDichotomy, cubeRoot, 1e-3),
   `${ratioDichotomy.toFixed(4)} vs ${cubeRoot.toFixed(4)}`);
ok('2^(-1/3) = 0.7937 (the "diameter-halving" constant)', approx(cubeRoot, 0.7937, 5e-4), cubeRoot.toFixed(4));

// ════════════════════════════════════════════════════════════════════════════
// B.  WEIBEL MODEL A  →  the lung is self-similar over ~1 decade, not 23 gens
// ════════════════════════════════════════════════════════════════════════════
// The diameters below are Weibel's idealised symmetric-dichotomy Model A airway
// diameters (cm), generations z=0 (trachea) .. 23 (alveolar sacs). They are
// CITED INPUT DATA (Weibel 1963), not computed — the page marks them "measured."
// What is PROVED: (i) the total diameter span is ~1.6 decades over all 23
// generations; (ii) Murray's 2^(-1/3) ratio is a MID-TREE approximation — the
// measured per-generation ratio is steeper at the trachea (~0.68) and flattens
// toward ~1.0 in the respiratory zone; (iii) the window where the cube-root law
// holds to within 0.05 spans LESS THAN one decade of diameter. This is the
// Avnir point, live: a celebrated "fractal" scaling law over <1 decade.
console.log('\n── B. Weibel Model A: how many decades is the lung "self-similar"? ──');
const WEIBEL = [1.800, 1.220, 0.830, 0.560, 0.450, 0.350, 0.280, 0.230, 0.186,
                0.154, 0.130, 0.109, 0.095, 0.082, 0.074, 0.066, 0.060, 0.054,
                0.050, 0.047, 0.045, 0.043, 0.041, 0.041];
ok('24 generations tabulated (z = 0..23)', WEIBEL.length === 24, `${WEIBEL.length}`);
const spanFactor = WEIBEL[0] / WEIBEL[23];
const spanDecades = Math.log10(spanFactor);
ok('trachea 1.80 cm, alveolar sac 0.041 cm', WEIBEL[0] === 1.800 && WEIBEL[23] === 0.041);
ok('diameter span = factor ~44 = ~1.6 decades', approx(spanDecades, 1.642, 5e-3),
   `${spanFactor.toFixed(1)}× = ${spanDecades.toFixed(3)} decades`);
const ratios = WEIBEL.slice(1).map((d, i) => d / WEIBEL[i]);
const topRatio = gmean(ratios.slice(0, 3));     // z 0->1..2->3 (trachea/bronchi)
const respRatio = gmean(ratios.slice(16));      // z 16->17..22->23 (respiratory)
ok('upper airways fall FASTER than cube-root (ratio ~0.68 < 0.79)', topRatio < 0.72,
   `top gmean ${topRatio.toFixed(3)}`);
ok('respiratory zone PLATEAUS (ratio ~0.95, toward 1.0)', respRatio > 0.90,
   `resp gmean ${respRatio.toFixed(3)}`);
// window where the measured ratio is within 0.05 of Murray's 0.7937
let lawLo = -1, lawHi = -1;
for (let i = 0; i < ratios.length; i++) {
  if (Math.abs(ratios[i] - cubeRoot) <= 0.05) { if (lawLo < 0) lawLo = i; lawHi = i + 1; }
  else if (lawLo >= 0 && i > lawHi) break; // first contiguous run from the top-mid
}
const lawDecades = Math.log10(WEIBEL[lawLo] / WEIBEL[lawHi]);
ok('cube-root law holds (±0.05) over < 1 decade of diameter', lawDecades < 1.0,
   `gens ${lawLo}..${lawHi}, ${lawDecades.toFixed(2)} decades`);
ok('~16 conducting + 7 respiratory = 23 generations of airway', 16 + 7 === 23);

// ════════════════════════════════════════════════════════════════════════════
// C.  STRAHLER ORDERING — correctness on a hand-checked tree
// ════════════════════════════════════════════════════════════════════════════
console.log('\n── C. Strahler ordering (hand-checked) ──');
function leaf() { return { parent: null, l: null, r: null }; }
function join(a, b) { const n = { parent: null, l: a, r: b }; a.parent = n; b.parent = n; return n; }
function strahlerOrder(root) {
  const stack = [root], list = [];
  while (stack.length) { const n = stack.pop(); list.push(n); if (n.l) stack.push(n.l); if (n.r) stack.push(n.r); }
  for (let i = list.length - 1; i >= 0; i--) {
    const n = list[i];
    if (!n.l && !n.r) n.order = 1;
    else { const a = n.l.order, b = n.r.order; n.order = (a === b) ? a + 1 : Math.max(a, b); }
  }
  return list;
}
// A tree: ((L,L),(L,(L,L)))  → left child order 2, right child: (1,(2)) = 2, root: (2,2)=3
{
  const t = join(join(leaf(), leaf()), join(leaf(), join(leaf(), leaf())));
  strahlerOrder(t);
  ok('two order-1 streams meeting make order 2', t.l.order === 2);
  ok('order 2 meeting order 1 stays order 2', t.r.order === 2);
  ok('two order-2 streams meeting make order 3 (the root)', t.order === 3);
}

// ════════════════════════════════════════════════════════════════════════════
// D.  KIRCHNER (the flagship) — random trees pass Horton's laws by pure chance
// ════════════════════════════════════════════════════════════════════════════
// PROVED in-browser. We generate UNIFORMLY RANDOM binary trees with Remy's
// algorithm (every distinct topology of a given size equally likely — this is
// Shreve's 1966 "random topology model"). Nothing in the generator knows about
// Horton's laws. We then Strahler-order each tree and measure the bifurcation
// ratio Rb and length ratio RL by Horton's own regression method. The result:
// they land squarely in the bands geomorphology calls "natural" (Rb 3-5,
// RL 1.5-3.5). So obeying Horton's laws is NOT evidence of special structure —
// it is what almost every branching network does. (Costa-Cabral 1997 filed a
// Comment; the core insensitivity result is broadly accepted.)
console.log('\n── D. Kirchner: uniform random trees vs Horton\'s laws ──');
function mulberry32(a) {
  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 remy(leaves, rng) { // uniform random binary tree, `leaves` leaves
  const root = { parent: null, l: null, r: null };
  const nodes = [root];
  for (let k = 1; k < leaves; k++) {
    const chosen = nodes[(rng() * nodes.length) | 0];
    const par = chosen.parent;
    const nl = { parent: null, l: null, r: null };
    const ni = { parent: par, l: null, r: null };
    if (par) { if (par.l === chosen) par.l = ni; else par.r = ni; }
    if (rng() < 0.5) { ni.l = chosen; ni.r = nl; } else { ni.l = nl; ni.r = chosen; }
    chosen.parent = ni; nl.parent = ni;
    nodes.push(nl, ni);
  }
  let r = root; while (r.parent) r = r.parent; return r;
}
function hortonStats(allNodes) {
  const Nw = {}, edgeCount = {};
  for (const n of allNodes) {
    if (!n.parent) continue; // root has no edge
    const w = n.order;
    edgeCount[w] = (edgeCount[w] || 0) + 1;
    const topBreak = (!n.parent.parent) || (n.parent.order !== w);
    if (topBreak) Nw[w] = (Nw[w] || 0) + 1;
  }
  const orders = Object.keys(Nw).map(Number).sort((a, b) => a - b);
  const meanLen = {}; orders.forEach(w => meanLen[w] = edgeCount[w] / Nw[w]);
  const ln = orders.map(w => Math.log10(Nw[w])), ll = orders.map(w => Math.log10(meanLen[w]));
  const Rb = Math.pow(10, -lsq(orders, ln));
  const RL = Math.pow(10, lsq(orders, ll));
  let totLinks = 0; orders.forEach(w => totLinks += edgeCount[w]);
  return { Nw, meanLen, orders, Rb, RL, totLinks };
}
function treeStats(m, seed) {
  const root = remy(m, mulberry32(seed));
  const list = strahlerOrder(root);
  return hortonStats(list);
}
// (i) conservation: total order-labelled links = edges = 2m - 2
{
  const m = 400, s = treeStats(m, 1000);
  ok('stream lengths conserve total edges (2m-2)', s.totLinks === 2 * m - 2, `${s.totLinks}=${2 * m - 2}`);
}
// (ii) THE ENSEMBLE the page shows: mean Rb, mean RL, pass-fraction (seed 1000, 300 trees, m=400)
const ENS_SEED = 1000, ENS_N = 300, ENS_M = 400;
let sumRb = 0, sumRL = 0, passBoth = 0;
for (let i = 0; i < ENS_N; i++) {
  const s = treeStats(ENS_M, ENS_SEED + i);
  sumRb += s.Rb; sumRL += s.RL;
  if (s.Rb >= 3 && s.Rb <= 5 && s.RL >= 1.5 && s.RL <= 3.5) passBoth++;
}
const meanRb = sumRb / ENS_N, meanRL = sumRL / ENS_N, passFrac = passBoth / ENS_N;
console.log(`   ensemble(seed=${ENS_SEED}, ${ENS_N} trees, m=${ENS_M}): ` +
            `Rb=${meanRb.toFixed(3)} RL=${meanRL.toFixed(3)} pass=${(100 * passFrac).toFixed(1)}%`);
ok('random trees: mean Rb lands in the "natural" band 3-5', meanRb >= 3 && meanRb <= 5, meanRb.toFixed(3));
ok('random trees: mean RL lands in the "natural" band 1.5-3.5', meanRL >= 1.5 && meanRL <= 3.5, meanRL.toFixed(3));
ok('the large majority of random trees pass BOTH Horton bands', passFrac > 0.85, `${(100 * passFrac).toFixed(1)}%`);
ok('mean Rb sits near the random-model value 4 (Shreve 1966)', approx(meanRb, 3.8, 0.4), meanRb.toFixed(3));
ok('mean RL sits near the random-model value 2 (Shreve 1967/69)', approx(meanRL, 2.0, 0.4), meanRL.toFixed(3));
// (iii) the single example tree the page draws by default (seed 23, m=150)
{
  const s = treeStats(150, 23);
  console.log(`   example tree(seed=23, m=150): Nw=${JSON.stringify(s.Nw)} Rb=${s.Rb.toFixed(2)} RL=${s.RL.toFixed(2)}`);
  ok('example tree passes both bands (drawn on the page)',
     s.Rb >= 3 && s.Rb <= 5 && s.RL >= 1.5 && s.RL <= 3.5, `Rb=${s.Rb.toFixed(2)} RL=${s.RL.toFixed(2)}`);
}

// ════════════════════════════════════════════════════════════════════════════
// E.  BOX-COUNTING — validate the collapse instrument on known shapes
// ════════════════════════════════════════════════════════════════════════════
// PROVED. The page box-counts each form to SHOW where its "fractal" scaling
// holds. Here the box-counter is validated against three shapes of KNOWN
// dimension: a line (1), a filled square (2), and the Koch curve (log4/log3 =
// 1.2619). Box-counting is known to over-read slightly on coarse grids; the
// tolerance reflects that.
console.log('\n── E. Box-counting validators ──');
function boxCount(points, grids) {
  return grids.map(g => {
    const set = new Set();
    for (const [x, y] of points) {
      const i = Math.min(g - 1, Math.floor(x * g)), j = Math.min(g - 1, Math.floor(y * g));
      set.add(i * g + j);
    }
    return { g, N: set.size };
  });
}
const boxDim = (bc) => lsq(bc.map(b => Math.log(b.g)), bc.map(b => Math.log(b.N)));
{
  const line = []; for (let i = 0; i <= 4000; i++) line.push([i / 4000, 0.5]);
  ok('box-count of a line ≈ 1', approx(boxDim(boxCount(line, [4, 8, 16, 32, 64, 128, 256])), 1, 0.03));
  const sq = []; for (let i = 0; i < 200; i++) for (let j = 0; j < 200; j++) sq.push([i / 200, j / 200]);
  ok('box-count of a filled square ≈ 2', approx(boxDim(boxCount(sq, [4, 8, 16, 32, 64, 128])), 2, 0.03));
  // Koch curve
  let pts = [[0, 0], [1, 0]];
  for (let d = 0; d < 6; d++) {
    const np = [];
    for (let i = 0; i < pts.length - 1; i++) {
      const [ax, ay] = pts[i], [bx, by] = pts[i + 1], dx = (bx - ax) / 3, dy = (by - ay) / 3;
      const p1 = [ax + dx, ay + dy], p3 = [ax + 2 * dx, ay + 2 * dy], A = Math.PI / 3;
      const ux = p3[0] - p1[0], uy = p3[1] - p1[1];
      const peak = [p1[0] + ux * Math.cos(A) - uy * Math.sin(A), p1[1] + ux * Math.sin(A) + uy * Math.cos(A)];
      np.push(pts[i], p1, peak, p3);
    }
    np.push(pts[pts.length - 1]); pts = np;
  }
  const dense = [];
  for (let i = 0; i < pts.length - 1; i++) {
    const [ax, ay] = pts[i], [bx, by] = pts[i + 1];
    for (let t = 0; t < 1; t += 0.05) dense.push([ax + (bx - ax) * t, ay + (by - ay) * t]);
  }
  const xs = dense.map(p => p[0]), ys = dense.map(p => p[1]);
  const mnx = Math.min(...xs), mxx = Math.max(...xs), mny = Math.min(...ys), mxy = Math.max(...ys);
  const sc = Math.max(mxx - mnx, mxy - mny);
  const norm = dense.map(([x, y]) => [(x - mnx) / sc * 0.999, (y - mny) / sc * 0.999]);
  const kd = boxDim(boxCount(norm, [4, 8, 16, 32, 64, 128, 256]));
  ok('box-count of Koch curve ≈ log4/log3 = 1.262', approx(kd, 1.262, 0.05),
     `${kd.toFixed(3)} vs ${(Math.log(4) / Math.log(3)).toFixed(3)}`);
}

// ════════════════════════════════════════════════════════════════════════════
// F.  DIELECTRIC BREAKDOWN / DLA — the lightning RULE, scale-limited
// ════════════════════════════════════════════════════════════════════════════
// PROVED (seeded, reproducible). The Laplacian growth rule (dielectric-breakdown
// model at eta=1) is in the universality class of diffusion-limited aggregation.
// We grow a DLA cluster with the SAME seed the page uses and estimate its
// dimension from radius-of-gyration vs particle count, R_g ∝ N^(1/D). A finite
// cluster reads a little BELOW the asymptotic 2D value D≈1.71 (Witten-Sander
// 1981) — and it is SCALE-LIMITED: a single lightning stroke has few branch
// levels. We do NOT claim "lightning is a fractal of dimension X over many
// decades"; we claim the RULE produces discharge-like branching.
console.log('\n── F. Dielectric-breakdown / DLA dimension (live, seeded) ──');
function dla(N, rng) {
  const occ = new Set(); const key = (x, y) => (x + 1024) * 8192 + (y + 1024);
  occ.add(key(0, 0));
  const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
  let maxR = 1, sumx = 0, sumy = 0, sx2 = 0, sy2 = 0, cnt = 1;
  const rgN = [];
  for (let n = 1; n < N; n++) {
    const spawnR = maxR + 6, killR = (spawnR * 2.2) | 0;
    let ang = rng() * 2 * Math.PI;
    let x = Math.round(Math.cos(ang) * spawnR), y = Math.round(Math.sin(ang) * spawnR);
    let steps = 0;
    while (true) {
      const d = dirs[(rng() * 4) | 0]; x += d[0]; y += d[1];
      if (x * x + y * y > killR * killR) { ang = rng() * 2 * Math.PI; x = Math.round(Math.cos(ang) * spawnR); y = Math.round(Math.sin(ang) * spawnR); }
      let stick = false;
      for (const dd of dirs) if (occ.has(key(x + dd[0], y + dd[1]))) { stick = true; break; }
      if (stick) {
        occ.add(key(x, y)); cnt++;
        sumx += x; sumy += y; sx2 += x * x; sy2 += y * y;
        const rr = Math.sqrt(x * x + y * y); if (rr > maxR) maxR = rr;
        break;
      }
      if (++steps > 500000) break;
    }
    if (n % 50 === 0) {
      const mx = sumx / cnt, my = sumy / cnt;
      rgN.push([n, Math.sqrt((sx2 / cnt - mx * mx) + (sy2 / cnt - my * my))]);
    }
  }
  return { rgN, maxR };
}
{
  const { rgN, maxR } = dla(1500, mulberry32(7));
  const win = rgN.filter(p => p[0] >= 200);
  const invD = lsq(win.map(p => Math.log(p[0])), win.map(p => Math.log(p[1])));
  const D = 1 / invD;
  console.log(`   DLA(seed=7, N=1500): D=${D.toFixed(3)}, cluster radius ${maxR.toFixed(1)} lattice units`);
  ok('DLA/DBM cluster dimension in the 2D range 1.55-1.75', D >= 1.55 && D <= 1.75, `D=${D.toFixed(3)}`);
  ok('finite cluster reads below the asymptotic 1.71 (Witten-Sander)', D < 1.71, `D=${D.toFixed(3)}`);
  ok('cluster is scale-limited (a stroke spans ~1.5 decades, not many)',
     Math.log10(maxR) < 2.0, `${Math.log10(maxR).toFixed(2)} decades of radius`);
}

// ════════════════════════════════════════════════════════════════════════════
// G.  ANTLER — the ANTI-fractal counterexample
// ════════════════════════════════════════════════════════════════════════════
// PROVED (box-count) + CITED (biology). An antler is 2-5 tines budding from one
// beam under apical/positional control — NO self-similar cascade. Box-counted,
// its silhouette reads as a 1-D curve (D≈1), not a plane-filling fractal. The
// growth rate (~2-2.5 cm/day, the fastest of any mammalian tissue) happens at a
// CARTILAGINOUS apical growth centre that mineralises LATER — we do NOT claim
// osteoblasts lay down bone at 2 cm/day.
console.log('\n── G. Antler: not self-similar (box-count ≈ 1) ──');
function antlerPolyline(tines) {
  // a main beam plus `tines` short tines budding from it — a 1-D figure
  const pts = []; const beam = 40;
  for (let i = 0; i <= beam; i++) pts.push([0.5 + 0.15 * (i / beam), 0.08 + 0.84 * (i / beam)]);
  for (let t = 0; t < tines; t++) {
    const at = 0.2 + 0.7 * (t / Math.max(1, tines)); // fraction up the beam
    const bx = 0.5 + 0.15 * at, by = 0.08 + 0.84 * at;
    const dir = (t % 2 === 0) ? -1 : 1;
    for (let i = 0; i <= 18; i++) pts.push([bx + dir * 0.22 * (i / 18), by + 0.20 * (i / 18)]);
  }
  return pts;
}
{
  const pts = antlerPolyline(3);
  const dense = [];
  for (let i = 0; i < pts.length - 1; i++) {
    const [ax, ay] = pts[i], [bx, by] = pts[i + 1];
    if (Math.hypot(bx - ax, by - ay) > 0.3) continue; // don't connect tine-to-beam jumps
    for (let t = 0; t < 1; t += 0.02) dense.push([ax + (bx - ax) * t, ay + (by - ay) * t]);
  }
  const d = boxDim(boxCount(dense, [4, 8, 16, 32, 64]));
  ok('antler silhouette box-counts as a curve (D ≈ 1, no cascade)', d < 1.25, `D=${d.toFixed(3)}`);
  ok('antler has 2-5 tines (positional control, not recursion)', 3 >= 2 && 3 <= 5);
}

// ════════════════════════════════════════════════════════════════════════════
// H.  L-SYSTEM — a grammar that COMPRESSES the branching, deterministically
// ════════════════════════════════════════════════════════════════════════════
// PROVED. A deterministic (D0L) L-system rewrite reproduces a compound-leaf form
// from a few rules. We check the rewrite is exact by predicting the string
// length two independent ways: (1) actually running the rewrite; (2) iterating
// the symbol-count vector through the substitution matrix. They must agree. The
// point the page makes: the grammar is a COMPRESSION of the form, not the
// plant's mechanism (real leaves canalise auxin via PIN proteins; genes KNOX/
// LEAFY pattern them). And a finitely-iterated L-system is self-similar over a
// FINITE, small range of scale — Avnir again.
console.log('\n── H. L-system rewrite is exact (compression, not mechanism) ──');
{
  // axiom X ; rules  X -> F-[[X]+X]+F[+FX]-X ,  F -> FF   (the grammar the page draws)
  const rules = { X: 'F-[[X]+X]+F[+FX]-X', F: 'FF' };
  function rewrite(s) { let o = ''; for (const c of s) o += (rules[c] !== undefined ? rules[c] : c); return o; }
  // symbol-count recurrence via substitution matrix over the 6 symbols
  const alpha = ['X', 'F', '[', ']', '+', '-'];
  const sub = {}; for (const a of alpha) { const img = rules[a] !== undefined ? rules[a] : a; const v = {}; for (const s of alpha) v[s] = 0; for (const c of img) v[c]++; sub[a] = v; }
  let s = 'X'; let cnt = {}; for (const a of alpha) cnt[a] = 0; cnt.X = 1;
  let allMatch = true;
  for (let n = 1; n <= 5; n++) {
    s = rewrite(s);
    const nc = {}; for (const a of alpha) nc[a] = 0;
    for (const a of alpha) for (const b of alpha) nc[b] += cnt[a] * sub[a][b];
    cnt = nc;
    const predLen = alpha.reduce((t, a) => t + cnt[a], 0);
    if (predLen !== s.length) allMatch = false;
  }
  ok('L-system string length matches substitution-matrix prediction (n=1..5)', allMatch, `final len ${s.length}`);
  // number of scales = number of iterations ⇒ scaling window is finite/bounded
  ok('a 5-iteration L-system is self-similar over a bounded ~1-decade window', Math.log10(Math.pow(2, 5)) < 2,
     `${Math.log10(Math.pow(2, 5)).toFixed(2)} decades of scale`);
}

// ════════════════════════════════════════════════════════════════════════════
// I.  PER-FORM BOX-COUNT DECADES — reproduce the page's live box-tool readouts
// ════════════════════════════════════════════════════════════════════════════
// PROVED. The page's box-count instrument reports, for each real form, the width
// (in decades of grid fineness) of the WIDEST straight (R^2 >= 0.9975) window in
// its log-log box-count. "The check" panel quotes those live readouts. Here we
// reproduce them with the page's IDENTICAL generators, grids and scalingWindow —
// so the quoted numbers are recomputed, not asserted. The point is Avnir's: each
// real form is self-similar over only ~1-2 decades (none past two), while the
// Koch curve — an actual fractal — stays straight across the whole range.
console.log('\n── I. Per-form box-count scaling windows (the page\'s box tool) ──');
function lgrowI(iter){ const R={ X:'F-[[X]+X]+F[+FX]-X', F:'FF' }; let s='X';
  for(let n=0;n<iter;n++){ let o=''; for(const c of s) o+=(R[c]!==undefined?R[c]:c); s=o; } return s; }
function lturtleI(str,angDeg){ const a=angDeg*Math.PI/180; let segs=[],st=[],x=0,y=0,dir=-Math.PI/2;
  for(const c of str){ if(c==='F'){ const nx=x+Math.cos(dir),ny=y+Math.sin(dir); segs.push([x,y,nx,ny]); x=nx;y=ny; }
    else if(c==='+') dir+=a; else if(c==='-') dir-=a; else if(c==='[') st.push([x,y,dir]);
    else if(c===']'){ const s=st.pop(); x=s[0];y=s[1];dir=s[2]; } } return segs; }
function densifySegsI(segs){ const pts=[]; for(const s of segs){ const dx=s[2]-s[0],dy=s[3]-s[1];
  let steps=Math.max(2,Math.ceil(Math.hypot(dx,dy)/0.01)); steps=Math.min(steps,40);
  for(let t=0;t<=steps;t++) pts.push([s[0]+dx*t/steps, s[1]+dy*t/steps]); } return pts; }
function densifyPolysI(polys){ const pts=[]; for(const p of polys) for(let j=0;j<p.length-1;j++){
  const a=p[j],b=p[j+1]; for(let t=0;t<=8;t++) pts.push([a[0]+(b[0]-a[0])*t/8,a[1]+(b[1]-a[1])*t/8]); } return pts; }
function normalizePtsI(pts){ let mnx=Infinity,mxx=-Infinity,mny=Infinity,mxy=-Infinity;
  for(const p of pts){ if(p[0]<mnx)mnx=p[0]; if(p[0]>mxx)mxx=p[0]; if(p[1]<mny)mny=p[1]; if(p[1]>mxy)mxy=p[1]; }
  const sc=Math.max(mxx-mnx,mxy-mny)||1; return pts.map(p=>[(p[0]-mnx)/sc*0.999,(p[1]-mny)/sc*0.999]); }
function kochPtsI(depth){ let pts=[[0,0],[1,0]];
  for(let d=0;d<depth;d++){ const np=[]; for(let i=0;i<pts.length-1;i++){
    const ax=pts[i][0],ay=pts[i][1],bx=pts[i+1][0],by=pts[i+1][1], dx=(bx-ax)/3,dy=(by-ay)/3,
      p1=[ax+dx,ay+dy],p3=[ax+2*dx,ay+2*dy],A=Math.PI/3, ux=p3[0]-p1[0],uy=p3[1]-p1[1],
      peak=[p1[0]+ux*Math.cos(A)-uy*Math.sin(A), p1[1]+ux*Math.sin(A)+uy*Math.cos(A)];
    np.push(pts[i],p1,peak,p3); } np.push(pts[pts.length-1]); pts=np; }
  const dense=[]; for(let i=0;i<pts.length-1;i++){ const a=pts[i],b=pts[i+1];
    for(let t=0;t<1;t+=0.04) dense.push([a[0]+(b[0]-a[0])*t,a[1]+(b[1]-a[1])*t]); } return dense; }
function antlerPolysI(tines){ const beams=[]; const beam=[];
  for(let i=0;i<=40;i++){ const f=i/40; beam.push([0.5+0.18*f+0.05*Math.sin(f*2),0.06+0.86*f]); } beams.push(beam);
  for(let t=0;t<tines;t++){ const at=0.22+0.72*(t/Math.max(1,tines-1||1)),
    bx=0.5+0.18*at+0.05*Math.sin(at*2), by=0.06+0.86*at, dir=(t%2===0)?-1:1, len=0.16+0.10*(1-at), tine=[];
    for(let i=0;i<=16;i++){ const g=i/16; tine.push([bx+dir*len*g*(1+0.3*g), by+0.14*len/0.2*g-0.02*g]); } beams.push(tine); }
  return beams; }
function layoutTreeI(root){ let leafX=0,maxDepth=0;
  (function assign(n,d){ n.depth=d; if(d>maxDepth)maxDepth=d;
    if(!n.l&&!n.r){ n.x=leafX++; n.y=d; return; } assign(n.l,d+1); assign(n.r,d+1); n.x=(n.l.x+n.r.x)/2; n.y=d; })(root,0);
  return {leaves:leafX,maxDepth}; }
function dlaPartsI(N,rng){ const occ=new Set(), key=(x,y)=>(x+1024)*8192+(y+1024); occ.add(key(0,0));
  const parts=[[0,0]], dirs=[[1,0],[-1,0],[0,1],[0,-1]]; let maxR=1;
  for(let n=1;n<N;n++){ const spawnR=maxR+6, killR=(spawnR*2.2)|0;
    let ang=rng()*2*Math.PI, x=Math.round(Math.cos(ang)*spawnR), y=Math.round(Math.sin(ang)*spawnR), steps=0;
    while(true){ const d=dirs[(rng()*4)|0]; x+=d[0]; y+=d[1];
      if(x*x+y*y>killR*killR){ ang=rng()*2*Math.PI; x=Math.round(Math.cos(ang)*spawnR); y=Math.round(Math.sin(ang)*spawnR); }
      let stick=false; for(const dd of dirs) if(occ.has(key(x+dd[0],y+dd[1]))){ stick=true; break; }
      if(stick){ occ.add(key(x,y)); parts.push([x,y]); const rr=Math.sqrt(x*x+y*y); if(rr>maxR)maxR=rr; break; }
      if(++steps>500000) break; } }
  return parts; }
function lsqR2I(xs,ys){ const n=xs.length; let mx=0,my=0; for(let i=0;i<n;i++){mx+=xs[i];my+=ys[i];} mx/=n;my/=n;
  let nu=0,de=0,sy=0; for(let i=0;i<n;i++){nu+=(xs[i]-mx)*(ys[i]-my);de+=(xs[i]-mx)**2;sy+=(ys[i]-my)**2;}
  return {slope:nu/de, r2: sy>0?(nu*nu)/(de*sy):1}; }
function scalingWindowI(bc){ const xs=bc.map(b=>Math.log(b.g)), ys=bc.map(b=>Math.log(b.N)); const n=bc.length; let best=null;
  for(let lo=0;lo<n-2;lo++) for(let hi=lo+2;hi<n;hi++){ const f=lsqR2I(xs.slice(lo,hi+1),ys.slice(lo,hi+1));
    if(f.r2>=0.9975){ if(!best || (hi-lo)>(best.hi-best.lo) || ((hi-lo)===(best.hi-best.lo)&&f.r2>best.r2))
      best={lo,hi,D:f.slope,r2:f.r2,decades:Math.log10(bc[hi].g/bc[lo].g)}; } }
  if(!best){ const g=lsqR2I(xs,ys); best={lo:0,hi:n-1,D:g.slope,r2:g.r2,decades:Math.log10(bc[n-1].g/bc[0].g)}; }
  return best; }
const BOXGRIDS_I=[4,8,16,32,64,128,256,512];
const boltPartsI = dlaPartsI(1500, mulberry32(7)); // identical seed to the page
function riverPtsI(){ const root=remy(400,mulberry32(1000)); const list=strahlerOrder(root); layoutTreeI(root);
  const pts=[]; for(const n of list){ if(!n.parent) continue;
    for(let t=0;t<=6;t++) pts.push([n.x+(n.parent.x-n.x)*t/6, n.y+(n.parent.y-n.y)*t/6]); } return normalizePtsI(pts); }
const boxDecades = {
  leaf:   scalingWindowI(boxCount(normalizePtsI(densifySegsI(lturtleI(lgrowI(5),22.5))), BOXGRIDS_I)),
  antler: scalingWindowI(boxCount(normalizePtsI(densifyPolysI(antlerPolysI(3))),            BOXGRIDS_I)),
  river:  scalingWindowI(boxCount(riverPtsI(),                                              BOXGRIDS_I)),
  bolt:   scalingWindowI(boxCount(normalizePtsI(boltPartsI),                                BOXGRIDS_I)),
  koch:   scalingWindowI(boxCount(normalizePtsI(kochPtsI(6)),                               BOXGRIDS_I)),
};
console.log(`   leaf ${boxDecades.leaf.decades.toFixed(2)} · antler ${boxDecades.antler.decades.toFixed(2)} · ` +
            `river ${boxDecades.river.decades.toFixed(2)} · lightning ${boxDecades.bolt.decades.toFixed(2)} · ` +
            `koch ${boxDecades.koch.decades.toFixed(2)} decades`);
ok('leaf box-count self-similar over ~1.8 decades (matches page readout)',   approx(boxDecades.leaf.decades,   1.81, 0.02), boxDecades.leaf.decades.toFixed(2));
ok('antler box-count self-similar over ~1.5 decades (matches page readout)', approx(boxDecades.antler.decades, 1.51, 0.02), boxDecades.antler.decades.toFixed(2));
ok('river box-count self-similar over ~1.2 decades (matches page readout)',  approx(boxDecades.river.decades,  1.20, 0.02), boxDecades.river.decades.toFixed(2));
ok('lightning box-count self-similar over ~0.9 decades (matches page)',      approx(boxDecades.bolt.decades,   0.90, 0.02), boxDecades.bolt.decades.toFixed(2));
ok('every real form self-similar over only ~1-2 decades, none past two',
   [boxDecades.leaf,boxDecades.antler,boxDecades.river,boxDecades.bolt].every(w => w.decades < 2.0), 'all < 2 dec');
ok('the Koch curve (a true fractal) stays straight over a wider range than any real form',
   boxDecades.koch.decades > boxDecades.leaf.decades, `koch ${boxDecades.koch.decades.toFixed(2)}`);

// ════════════════════════════════════════════════════════════════════════════
console.log(`\n${pass}/${total} PASS`);
process.exit(pass === total ? 0 : 1);
