#!/usr/bin/env node
// verify-cordic.mjs — recompute every number shown on /strata/cordic/ from first
// principles, using only the real CORDIC recurrences. No dependencies. Plain node.
//
// Run:  node research/cordic/verify-cordic.mjs
// Prints "<pass>/<total> PASS" and exits 0 iff all checks pass (nonzero on mismatch).
//
// PRIMARY SOURCES (page numbers pinned):
//   Volder, "The CORDIC Trigonometric Computing Technique," IRE Trans. Electronic
//     Computers, EC-8(3):330-334, Sept 1959.  (circular rotation/vectoring)
//   Walther, "A unified algorithm for elementary functions," Proc. AFIPS Spring Joint
//     Computer Conference, 1971, pp. 379-385.  (m in {+1,0,-1}; three geometries)
//   Mitchell, "Computer Multiplication and Division Using Binary Logarithms," IRE
//     Trans. Electronic Computers, EC-11(4):512-517, 1962.  (the bit-log sibling)
//
// The journal was "IRE Transactions on Electronic Computers" through 1962 and became
// "IEEE Transactions on Electronic Computers" in 1963 — Volder(1959) and Mitchell(1962)
// are both IRE, despite frequent mislabelling of Mitchell as IEEE.

let pass = 0, total = 0;
const results = [];
function check(name, got, want, tol) {
  total++;
  let ok;
  if (typeof want === 'number' && typeof got === 'number' && tol !== undefined) {
    ok = Math.abs(got - want) <= tol;
  } else {
    ok = Object.is(got, want) || got === want;
  }
  if (ok) pass++;
  results.push([ok, name, got, want]);
}

// ─────────────────────────────────────────────────────────────────────────────
// The angle tables — swapped per geometry, everything else identical.
// ─────────────────────────────────────────────────────────────────────────────
const N = 60;
const atanTab  = Array.from({length:N}, (_, i) => Math.atan(2 ** -i));   // m=+1
const linTab   = Array.from({length:N}, (_, i) => 2 ** -i);              // m= 0
const atanhTab = Array.from({length:N}, (_, i) => Math.atanh(2 ** -i));  // m=-1 (i>=1)

// ─────────────────────────────────────────────────────────────────────────────
// 1. The gain K and its reciprocal A = 1/K.
//    K = prod cos(atan 2^-i) = prod 1/sqrt(1+2^-2i)   (circular, m=+1)
// ─────────────────────────────────────────────────────────────────────────────
let A = 1;
for (let i = 0; i < N; i++) A *= Math.sqrt(1 + 2 ** (-2 * i));
const K = 1 / A;
check('K = prod 1/sqrt(1+2^-2i) = 0.6072529350088813', K, 0.6072529350088813, 1e-15);
check('1/K = A = 1.6467602581210656', A, 1.6467602581210656, 1e-13);

// K equals prod cos(atan 2^-i) (the same constant, the other way)
let Kcos = 1;
for (let i = 0; i < N; i++) Kcos *= Math.cos(Math.atan(2 ** -i));
check('K = prod cos(atan 2^-i) (identical route)', Kcos, K, 1e-15);

// ─────────────────────────────────────────────────────────────────────────────
// 2. The per-step scale factor s_i = sqrt(1+2^-2i) is INDEPENDENT of the sign d.
//    This is the heart: |v_{i+1}|^2 = (x - d y 2^-i)^2 + (y + d x 2^-i)^2
//                                   = (x^2+y^2)(1+2^-2i), because d^2=1 and the
//    two cross terms (-2 d x y 2^-i) and (+2 d x y 2^-i) cancel for EITHER sign.
// ─────────────────────────────────────────────────────────────────────────────
function stepLenRatio(x, y, i, d) {
  const xn = x - d * y * 2 ** -i;
  const yn = y + d * x * 2 ** -i;
  return Math.sqrt(xn * xn + yn * yn) / Math.sqrt(x * x + y * y);
}
{
  // an arbitrary, non-axis-aligned vector, so cross terms are genuinely nonzero
  const x = 0.37, y = 0.81;
  const i = 3;
  const sPlus  = stepLenRatio(x, y, i, +1);
  const sMinus = stepLenRatio(x, y, i, -1);
  const sTheory = Math.sqrt(1 + 2 ** (-2 * i));
  check('scale(d=+1) = sqrt(1+2^-2i)', sPlus, sTheory, 1e-14);
  check('scale(d=-1) = sqrt(1+2^-2i)', sMinus, sTheory, 1e-14);
  check('scale(d=+1) == scale(d=-1)  (K-constancy proof)', sPlus, sMinus, 1e-15);
}

// displayed scale-factor rows (i=0..3): sqrt(2), sqrt(1.25), sqrt(1.0625), sqrt(1.015625)
check('s_0 = sqrt(2)      = 1.4142135624', Math.sqrt(1 + 2 ** 0),  1.4142135623730951, 1e-12);
check('s_1 = sqrt(1.25)   = 1.1180339887', Math.sqrt(1 + 2 ** -2), 1.118033988749895,  1e-12);
check('s_2 = sqrt(1.0625) = 1.0307764064', Math.sqrt(1 + 2 ** -4), 1.0307764064044152, 1e-12);

// displayed arctan-table rows
check('atan(2^0)  = 0.7853981634', atanTab[0], 0.7853981633974483, 1e-12);
check('atan(2^-1) = 0.4636476090', atanTab[1], 0.4636476090008061, 1e-12);
check('atan(2^-2) = 0.2449786631', atanTab[2], 0.24497866312686414, 1e-12);

// ─────────────────────────────────────────────────────────────────────────────
// 3. Native circular convergence range = sum atan(2^-i) = 1.7432866 rad = 99.883 deg.
// ─────────────────────────────────────────────────────────────────────────────
let range = 0;
for (let i = 0; i < N; i++) range += atanTab[i];
check('circular range = 1.7432866 rad', range, 1.74328662047234, 1e-11);
check('circular range = 99.883 deg', range * 180 / Math.PI, 99.88, 1e-2);

// ─────────────────────────────────────────────────────────────────────────────
// 4. Circular CORDIC, rotation mode: (K,0,theta) -> (cos theta, sin theta, ~0).
//    x_{i+1} = x - d y 2^-i ;  y_{i+1} = y + d x 2^-i ;  z_{i+1} = z - d atan(2^-i)
//    d = sign(z).  No multiplies: 2^-i is a shift.
// ─────────────────────────────────────────────────────────────────────────────
function cordicCircular(theta, n) {
  let x = K, y = 0, z = theta;
  for (let i = 0; i < n; i++) {
    const d = z >= 0 ? 1 : -1;
    const xn = x - d * y * 2 ** -i;
    const yn = y + d * x * 2 ** -i;
    z -= d * atanTab[i];
    x = xn; y = yn;
  }
  return { cos: x, sin: y, z };
}
// cross-check sin & cos against Math.* across the full reduced range
{
  let worst = 0;
  for (let t = -1.74; t <= 1.74; t += 0.01) {
    const r = cordicCircular(t, 40);
    worst = Math.max(worst, Math.abs(r.sin - Math.sin(t)), Math.abs(r.cos - Math.cos(t)));
  }
  check('circular sin/cos vs Math.*, n=40, |theta|<=1.74 (worst < 1e-11)', worst < 1e-11, true);
}

// ─────────────────────────────────────────────────────────────────────────────
// 5. The error-collapse curve at theta = 0.7 (shown as tabulated checkpoints).
//    Roughly one bit per iteration overall, with a rebound from n=24 to n=28.
//    Longer runs improve further; that rebound does not establish a precision floor.
// ─────────────────────────────────────────────────────────────────────────────
function sinErr(theta, n) { return Math.abs(cordicCircular(theta, n).sin - Math.sin(theta)); }
const e4  = sinErr(0.7, 4);
const e16 = sinErr(0.7, 16);
const e20 = sinErr(0.7, 20);
const e24 = sinErr(0.7, 24);
const e28 = sinErr(0.7, 28);
const e40 = sinErr(0.7, 40);
const e56 = sinErr(0.7, 56);
check('sinErr(0.7, n=4)  ~ 8.5e-3', e4,  8.50e-3, 5e-4);
check('sinErr(0.7, n=16) ~ 1.3e-5', e16, 1.32e-5, 5e-6);
check('sinErr(0.7, n=20) ~ 9.3e-8', e20, 9.27e-8, 5e-8);
check('error IMPROVES 4 -> 20 (n=20 err < n=4 err)', e20 < e4, true);
check('24 -> 28 rebound is not a floor: n=40 improves, n=56 < 1e-14',
  e28 > e24 && e40 < e24 && e56 < 1e-14, true);
// roughly one bit per iteration between n=8 and n=20: log2(e8/e20) ~ 12 bits over 12 iters
{
  const e8 = sinErr(0.7, 8);
  const bitsPerIter = Math.log2(e8 / e20) / (20 - 8);
  check('~1 bit/iteration (0.7..1.5 bits/iter over n=8..20)', bitsPerIter >= 0.7 && bitsPerIter <= 1.6, true);
}

// ─────────────────────────────────────────────────────────────────────────────
// 6. Circular VECTORING mode computes atan2(y0,x0): drive y->0, z accumulates.
// ─────────────────────────────────────────────────────────────────────────────
function cordicAtan2(y0, x0, n) {
  let x = x0, y = y0, z = 0;
  for (let i = 0; i < n; i++) {
    const d = y >= 0 ? -1 : 1;      // drive y toward 0
    const xn = x - d * y * 2 ** -i;
    const yn = y + d * x * 2 ** -i;
    z -= d * atanTab[i];
    x = xn; y = yn;
  }
  return z;
}
{
  let worst = 0;
  for (let a = -1.5; a <= 1.5; a += 0.05) {
    const got = cordicAtan2(Math.sin(a), Math.cos(a), 40);
    worst = Math.max(worst, Math.abs(got - a));
  }
  check('vectoring atan2 vs Math.atan2, n=40 (worst < 1e-11)', worst < 1e-11, true);
}

// ─────────────────────────────────────────────────────────────────────────────
// 7. WALTHER UNIFIED, m=0 (LINEAR): multiply. Gain = 1, range = sum 2^-i = 2.
//    x const; y_{i+1} = y + d x 2^-i; z_{i+1} = z - d 2^-i; drive z->0 => y = x*z0.
// ─────────────────────────────────────────────────────────────────────────────
let linRange = 0;
for (let i = 0; i < N; i++) linRange += linTab[i];
check('linear range = sum 2^-i = 2.0', linRange, 2.0, 1e-12);
function cordicMul(a, b, n) {         // returns a*b (b is the driven angle z0)
  let x = a, y = 0, z = b;
  for (let i = 0; i < n; i++) {
    const d = z >= 0 ? 1 : -1;
    y += d * x * 2 ** -i;
    z -= d * 2 ** -i;
  }
  return y;
}
{
  let worst = 0;
  const pairs = [[0.6, 1.3], [0.9, -1.7], [1.5, 1.2], [-0.4, 1.9], [0.75, -0.75]];
  for (const [a, b] of pairs) worst = Math.max(worst, Math.abs(cordicMul(a, b, 45) - a * b));
  check('linear multiply vs a*b, n=45 (worst < 1e-11)', worst < 1e-11, true);
  // linear gain is exactly 1: sqrt(1 + m*2^-2i) with m=0 is sqrt(1) = 1
  check('linear gain = prod sqrt(1+0) = 1.0', (() => { let g = 1; for (let i = 0; i < N; i++) g *= Math.sqrt(1 + 0 * 2 ** (-2 * i)); return g; })(), 1.0, 0);
}

// ─────────────────────────────────────────────────────────────────────────────
// 8. WALTHER UNIFIED, m=-1 (HYPERBOLIC): exp/sinh/cosh.
//    i starts at 1; iterations 4,13,40,121,... (i_{k+1}=3 i_k+1) are REPEATED.
//    Gain 1/Ah = 1.2074970678, range = sum atanh(2^-i) (w/ repeats) = 1.1182 rad.
// ─────────────────────────────────────────────────────────────────────────────
function hypSeq(nDistinct) {
  const seq = []; let nextRepeat = 4;
  for (let i = 1; i <= nDistinct; i++) {
    seq.push(i);
    if (i === nextRepeat) { seq.push(i); nextRepeat = 3 * nextRepeat + 1; }
  }
  return seq;
}
// the repeated indices themselves (first four): 4, 13, 40, 121
{
  const reps = []; let r = 4;
  for (let k = 0; k < 4; k++) { reps.push(r); r = 3 * r + 1; }
  check('hyperbolic repeated indices = 4,13,40,121', reps.join(','), '4,13,40,121');
}
let Ah = 1, rangeH = 0;
for (const i of hypSeq(40)) { Ah *= Math.sqrt(1 - 2 ** (-2 * i)); rangeH += Math.atanh(2 ** -i); }
check('hyperbolic 1/Ah = 1.2074970678', 1 / Ah, 1.207497067763072, 1e-12);
check('hyperbolic range = 1.1181730 rad', rangeH, 1.1181730118332, 1e-8);
function cordicHyp(theta, nDistinct) {
  const seq = hypSeq(nDistinct);
  let g = 1; for (const i of seq) g *= Math.sqrt(1 - 2 ** (-2 * i));
  let x = 1 / g, y = 0, z = theta;
  for (const i of seq) {
    const d = z >= 0 ? 1 : -1;
    const xn = x + d * y * 2 ** -i;   // m=-1
    const yn = y + d * x * 2 ** -i;
    z -= d * Math.atanh(2 ** -i);
    x = xn; y = yn;
  }
  return { cosh: x, sinh: y, exp: x + y };
}
{
  let worst = 0;
  for (let t = -1.1; t <= 1.1; t += 0.02) {
    const r = cordicHyp(t, 40);
    worst = Math.max(worst,
      Math.abs(r.cosh - Math.cosh(t)),
      Math.abs(r.sinh - Math.sinh(t)),
      Math.abs(r.exp - Math.exp(t)));
  }
  check('hyperbolic exp/sinh/cosh vs Math.*, |theta|<=1.1 (worst < 1e-9)', worst < 1e-9, true);
  // WITHOUT the repeats, hyperbolic CORDIC does NOT converge — worst error over the
  // range blows up to ~0.1 (vs ~1e-11 with repeats). The divergence hides at single
  // easy points, so we measure worst-case across the whole range.
  function cordicHypNoRepeat(theta, nDistinct) {
    const seq = []; for (let i = 1; i <= nDistinct; i++) seq.push(i);
    let g = 1; for (const i of seq) g *= Math.sqrt(1 - 2 ** (-2 * i));
    let x = 1 / g, y = 0, z = theta;
    for (const i of seq) {
      const d = z >= 0 ? 1 : -1;
      const xn = x + d * y * 2 ** -i, yn = y + d * x * 2 ** -i;
      z -= d * Math.atanh(2 ** -i); x = xn; y = yn;
    }
    return x + y;
  }
  let badWorst = 0, goodWorst = 0;
  for (let t = -1.1; t <= 1.1; t += 0.01) {
    badWorst  = Math.max(badWorst,  Math.abs(cordicHypNoRepeat(t, 40) - Math.exp(t)));
    goodWorst = Math.max(goodWorst, Math.abs(cordicHyp(t, 40).exp - Math.exp(t)));
  }
  check('repeats matter: no-repeat worst error (~0.1) >> with-repeat (~1e-11)', badWorst > goodWorst * 1e6, true);
}

// ─────────────────────────────────────────────────────────────────────────────
// 9. The bit-log sibling (Mitchell 1962 / fast-inverse-sqrt): DIFFERENT mechanism.
//    A single float reinterpretation approximates log2 — no iteration. We only
//    assert the *relationship the page states*: Mitchell's log2 approximation
//    log2(1+f) ~ f is exact at f=0 and f=1 and worst near the middle. This is NOT
//    a CORDIC computation; it is the contrast the page draws.
// ─────────────────────────────────────────────────────────────────────────────
{
  const mitchell = (f) => f;                 // approx of log2(1+f) on [0,1)
  const truth    = (f) => Math.log2(1 + f);
  check('Mitchell log2 approx exact at f=0', Math.abs(mitchell(0) - truth(0)), 0, 1e-15);
  check('Mitchell log2 approx exact at f->1', Math.abs(mitchell(1) - truth(1)), 0, 1e-15);
  // max error of ~0.0860 near f ~ 0.4427 (1/ln2 - 1) — the well-known Mitchell bound
  let maxErr = 0;
  for (let f = 0; f < 1; f += 1e-4) maxErr = Math.max(maxErr, Math.abs(mitchell(f) - truth(f)));
  check('Mitchell max |error| ~ 0.0860 on [0,1)', maxErr, 0.08607133, 5e-4);
}

// ─────────────────────────────────────────────────────────────────────────────
const label = `${pass}/${total} PASS`;
for (const [ok, name, got, want] of results) {
  const g = typeof got === 'number' ? (Math.abs(got) < 1e-3 && got !== 0 ? got.toExponential(4) : got) : got;
  console.log(`${ok ? 'ok  ' : 'FAIL'}  ${name}${ok ? '' : `   got=${g} want=${want}`}`);
}
console.log('\n' + label);
process.exit(pass === total ? 0 : 1);
