// verify-moire.mjs — the analytical spine of the moiré stratum.
//
// Two independent kinds of check, so no number on the page is asserted:
//   (A) SYMBOLIC/NUMERIC: the master period formula
//           D = p1·p2 / sqrt(p1² + p2² − 2·p1·p2·cos θ)
//       reduces exactly to the two textbook special cases (rotation-only and
//       pitch-difference-only), across many random (p1, p2, θ).
//   (B) EMPIRICAL (non-circular): render two binary line gratings, take their
//       ink-overlap product, run a real 2D FFT, and read the *measured* moiré
//       period straight off the lowest spatial-frequency peak. The perceived
//       pattern's period must equal the derived D — measured, not assumed.
//   (C) THE AMPLIFIER: nudging one grating by δ shifts the moiré fringe by
//       exactly M·δ, where M = D/p is the magnification. Verified by tracking
//       the moiré phase before/after a sub-pixel nudge.
//   (D) MAGIC ANGLE: the same formula, applied to two honeycomb lattices at
//       θ = 1.1°, gives the ~13 nm graphene moiré superlattice (Cao et al. 2018;
//       Bistritzer–MacDonald 2011). One equation, printer to superconductor.
//
//   node research/moire/verify-moire.mjs
'use strict';

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok  ' : 'FAIL '} ${name}${extra ? '   ' + extra : ''}`);
};
const approx = (a, b, tol) => Math.abs(a - b) <= tol;

// ---------------------------------------------------------------------------
// The three period laws.
const D_master = (p1, p2, theta) =>
  (p1 * p2) / Math.sqrt(p1 * p1 + p2 * p2 - 2 * p1 * p2 * Math.cos(theta));
// Algebraically identical, but numerically STABLE near p1≈p2 / θ≈0: both terms
// under the root are ≥0, so there is no cancellation. Use this form in code.
const D_master_stable = (p1, p2, theta) =>
  (p1 * p2) / Math.sqrt((p1 - p2) * (p1 - p2) + 2 * p1 * p2 * (1 - Math.cos(theta)));
const D_rotation = (p, theta) => p / (2 * Math.sin(theta / 2));       // same pitch, angle θ
const D_beat     = (p1, p2)   => (p1 * p2) / Math.abs(p1 - p2);       // parallel, Δpitch

// ---------------------------------------------------------------------------
// (A) The master formula contains both special cases exactly.
console.log('\n(A) master formula reduces to both textbook cases');
{
  let worstRot = 0, worstBeat = 0, worstNaive = 0, worstStable = 0;
  // mulberry32 deterministic PRNG (no Math.random — reproducible).
  let s = 0x9e3779b9;
  const rnd = () => {
    s |= 0; s = (s + 0x6D2B79F5) | 0;
    let t = Math.imul(s ^ (s >>> 15), 1 | s);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
  for (let i = 0; i < 200000; i++) {
    const p  = 0.5 + rnd() * 20;
    const th = (0.3 + rnd() * 80) * Math.PI / 180;   // 0.3°..80.3°
    const dr = D_rotation(p, th);
    worstRot = Math.max(worstRot, Math.abs(D_master(p, p, th) - dr) / dr);
    const p1 = 0.5 + rnd() * 20, p2 = 0.5 + rnd() * 20;
    const db = D_beat(p1, p2);
    worstBeat   = Math.max(worstBeat,   Math.abs(D_master_stable(p1, p2, 0) - db) / db);
    worstNaive  = Math.max(worstNaive,  Math.abs(D_master(p1, p2, 0)        - db) / db);
    worstStable = Math.max(worstStable, Math.abs(D_master_stable(p1, p2, 0) - db) / db);
  }
  // NB: the master expression p1²+p2²−2p1p2cosθ suffers catastrophic float
  // cancellation as p1→p2 at θ=0 (it is (p1−p2)² computed the unstable way), so
  // the identity is exact but its numeric residual scales with D — compare
  // RELATIVE error, and note the cancellation caveat on the page.
  ok('master == rotation-only when p1==p2 (200k random)', worstRot < 1e-6, `max rel err ${worstRot.toExponential(2)}`);
  ok('STABLE master == beat when θ==0 (200k random)',     worstStable < 1e-9, `max rel err ${worstStable.toExponential(2)}`);
  ok('naive master loses precision near p1≈p2 (the caveat)', worstNaive > 1e-6 && worstNaive < 1e-2,
     `naive ${worstNaive.toExponential(2)} vs stable ${worstStable.toExponential(2)}`);
}

// ---------------------------------------------------------------------------
// A minimal radix-2 iterative FFT (Cooley–Tukey), plus a 2D transform.
function fft(re, im, inverse = false) {
  const n = re.length;
  for (let i = 1, j = 0; i < n; i++) {                 // bit-reversal permutation
    let bit = n >> 1;
    for (; j & bit; bit >>= 1) j ^= bit;
    j ^= bit;
    if (i < j) { [re[i], re[j]] = [re[j], re[i]]; [im[i], im[j]] = [im[j], im[i]]; }
  }
  for (let len = 2; len <= n; len <<= 1) {
    const ang = (inverse ? 2 : -2) * Math.PI / len;
    const wr = Math.cos(ang), wi = Math.sin(ang);
    for (let i = 0; i < n; i += len) {
      let cr = 1, ci = 0;
      for (let k = 0; k < len / 2; k++) {
        const a = i + k, b = i + k + len / 2;
        const tr = re[b] * cr - im[b] * ci;
        const ti = re[b] * ci + im[b] * cr;
        re[b] = re[a] - tr; im[b] = im[a] - ti;
        re[a] += tr;        im[a] += ti;
        const ncr = cr * wr - ci * wi;
        ci = cr * wi + ci * wr; cr = ncr;
      }
    }
  }
  if (inverse) for (let i = 0; i < n; i++) { re[i] /= n; im[i] /= n; }
}
function fft2(re, im, N) {
  const row = new Float64Array(N), rowI = new Float64Array(N);
  for (let y = 0; y < N; y++) {
    for (let x = 0; x < N; x++) { row[x] = re[y * N + x]; rowI[x] = im[y * N + x]; }
    fft(row, rowI);
    for (let x = 0; x < N; x++) { re[y * N + x] = row[x]; im[y * N + x] = rowI[x]; }
  }
  const col = new Float64Array(N), colI = new Float64Array(N);
  for (let x = 0; x < N; x++) {
    for (let y = 0; y < N; y++) { col[y] = re[y * N + x]; colI[y] = im[y * N + x]; }
    fft(col, colI);
    for (let y = 0; y < N; y++) { re[y * N + x] = col[y]; im[y * N + x] = colI[y]; }
  }
}

// Render two binary gratings, AND them (ink overlaps), measure the lowest-freq
// peak of the 2D spectrum, return the empirical moiré period in pixels.
function measureMoirePeriod(N, p1, p2, angle1, angle2, duty = 0.5) {
  const re = new Float64Array(N * N), im = new Float64Array(N * N);
  const k1x = Math.cos(angle1) / p1, k1y = Math.sin(angle1) / p1;   // cycles/pixel
  const k2x = Math.cos(angle2) / p2, k2y = Math.sin(angle2) / p2;
  const frac = (v) => v - Math.floor(v);
  // Hann window (separable) suppresses spectral leakage from the strong DC
  // overlap term, so the moiré difference peak stands clear near the origin.
  const win = new Float64Array(N);
  for (let i = 0; i < N; i++) win[i] = 0.5 - 0.5 * Math.cos(2 * Math.PI * i / (N - 1));
  for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) {
    const g1 = frac(x * k1x + y * k1y) < duty ? 1 : 0;
    const g2 = frac(x * k2x + y * k2y) < duty ? 1 : 0;
    re[y * N + x] = g1 * g2 * win[y] * win[x];                      // windowed ink overlap
  }
  fft2(re, im, N);
  const mag = (x, y) => Math.hypot(re[y * N + x], im[y * N + x]);
  // The genuine moiré peak is the STRONGEST spectral peak in the annulus below
  // the grating fundamental (radius N/min(p)) and clear of the DC leakage core.
  const gratingR = N / Math.min(p1, p2);
  const rMin = 4.0, rMax = gratingR * 0.6;
  let bx = 0, by = 0, bmag = -1;
  for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) {
    const fx = x <= N / 2 ? x : x - N;
    const fy = y <= N / 2 ? y : y - N;
    const r = Math.hypot(fx, fy);
    if (r < rMin || r > rMax) continue;
    const m = mag(x, y);
    if (m > bmag) { bmag = m; bx = x; by = y; }
  }
  // Magnitude-weighted centroid over a 5×5 neighbourhood → sub-bin frequency.
  let sfx = 0, sfy = 0, sw = 0;
  for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) {
    const xx = (bx + dx + N) % N, yy = (by + dy + N) % N;
    const fx = xx <= N / 2 ? xx : xx - N;
    const fy = yy <= N / 2 ? yy : yy - N;
    const m = mag(xx, yy);
    sfx += fx * m; sfy += fy * m; sw += m;
  }
  const fcyc = Math.hypot(sfx / sw, sfy / sw) / N;                  // cycles/pixel
  return { period: 1 / fcyc, fx: sfx / sw, fy: sfy / sw };
}

// ---------------------------------------------------------------------------
// (B) Empirical period matches the formula — measured off a rendered pattern.
console.log('\n(B) FFT-measured moiré period matches the derived formula');
{
  const N = 512;   // larger frame → moiré radius comfortably clear of DC leakage
  const cases = [
    // rotation-only: p=8px, θ chosen so the moiré fits the frame and D>>p
    { label: 'rotation θ=7.18°', p1: 8, p2: 8, a1: 0, a2: 7.18 * Math.PI / 180 },
    { label: 'rotation θ=9.00°', p1: 8, p2: 8, a1: 0, a2: 9.00 * Math.PI / 180 },
    // beat-only: parallel, slightly different pitch
    { label: 'beat 8px vs 9px',  p1: 8, p2: 9, a1: 0, a2: 0 },
    { label: 'beat 10px vs 11px',p1: 10, p2: 11, a1: 0, a2: 0 },
    // general: both pitch difference AND angle
    { label: 'general 8/9 @4°',  p1: 8, p2: 9, a1: 0, a2: 4 * Math.PI / 180 },
  ];
  for (const c of cases) {
    const theta = c.a2 - c.a1;
    const Dform = D_master(c.p1, c.p2, theta);
    const { period } = measureMoirePeriod(N, c.p1, c.p2, c.a1, c.a2);
    // tolerance ~ one FFT bin: the measured radius is integer, so period has
    // quantised resolution ΔD ≈ D²/N. Accept within 1.5 bins.
    const binTol = 1.5 * Dform * Dform / N;
    ok(`${c.label}: formula ${Dform.toFixed(2)}px vs FFT ${period.toFixed(2)}px`,
       approx(period, Dform, binTol + 0.5), `tol ±${binTol.toFixed(2)}px`);
  }
}

// ---------------------------------------------------------------------------
// (C) The amplifier: nudge one grating by δ, the moiré shifts by M·δ, M = D/p.
console.log('\n(C) the amplifier — a δ nudge moves the moiré by M·δ');
{
  // Analytic phase argument, then a discrete confirmation.
  // Grating 2 phase offset φ shifts its lines by φ·p2 pixels. The moiré bright
  // fringe sits where the two gratings' phases coincide; a shift s of grating 2
  // moves that coincidence by s·(D/p2) — the magnification. Verify by tracking
  // the moiré-fringe centroid across a sub-pixel sweep of grating-2 offset.
  const N = 512, p = 8, theta = 5 * Math.PI / 180;
  const D = D_rotation(p, theta), M = D / p;
  const frac = (v) => v - Math.floor(v);
  // 1-D slice along x through the moiré (angle bisector ≈ x for small θ).
  function moireCentroid(offsetPx) {
    const k1x = Math.cos(0) / p, k1y = 0;
    const k2x = Math.cos(theta) / p, k2y = Math.sin(theta) / p;
    let num = 0, den = 0;
    const y = N / 2;
    for (let x = 0; x < N; x++) {
      const g1 = frac(x * k1x + y * k1y) < 0.5 ? 1 : 0;
      const g2 = frac((x + offsetPx) * k2x + y * k2y) < 0.5 ? 1 : 0;
      const overlap = g1 * g2;
      // weight by proximity to image centre to isolate one fringe
      const w = Math.max(0, 1 - Math.abs(x - N / 2) / (D * 0.9));
      num += overlap * w * x; den += overlap * w;
    }
    return den > 0 ? num / den : NaN;
  }
  const c0 = moireCentroid(0);
  const delta = 0.5;                     // half-pixel nudge of one grating
  const c1 = moireCentroid(delta);
  const observedShift = Math.abs(c1 - c0);   // sign is a direction convention; magnitude is the law
  const predictedShift = M * delta;
  ok(`M = D/p = ${M.toFixed(1)}× (θ=5°, p=8px)`, approx(M, D / p, 1e-9));
  ok(`δ=0.5px nudge → moiré shift ≈ M·δ = ${predictedShift.toFixed(1)}px`,
     approx(observedShift, predictedShift, Math.max(2, 0.15 * predictedShift)),
     `observed ${observedShift.toFixed(1)}px`);
}

// ---------------------------------------------------------------------------
// (D) Magic angle: the SAME formula → the graphene moiré superlattice.
console.log('\n(D) magic-angle graphene is the same period law');
{
  const a = 0.246;                       // graphene lattice constant, nm
  const magic = 1.1 * Math.PI / 180;     // ≈ magic angle (Cao et al. 2018)
  const L = D_rotation(a, magic);        // moiré superlattice wavelength, nm
  ok(`moiré wavelength at 1.1° = ${L.toFixed(2)} nm (reported ~13 nm)`,
     approx(L, 12.8, 1.0), `a=0.246nm`);
  const ratio = D_rotation(a, magic) / a;
  ok(`superlattice is ${ratio.toFixed(0)}× the atomic spacing`,
     approx(ratio, 52, 3));
  // The Bistritzer–MacDonald small-angle form L ≈ a/θ agrees to <1%.
  const Lsmall = a / magic;
  ok(`small-angle a/θ = ${Lsmall.toFixed(2)} nm agrees with exact to <1%`,
     Math.abs(Lsmall - L) / L < 0.01, `Δ=${((Lsmall - L) / L * 100).toFixed(3)}%`);
}

// ---------------------------------------------------------------------------
// (E) The printing cross-check: our rotation law reproduces the exact moiré
// magnifications the halftone industry quotes for its screen angles.
console.log('\n(E) halftone screen angles — our law matches the print literature');
{
  const m15 = D_rotation(1, 15 * Math.PI / 180);   // yellow at 15° from cyan/magenta
  const m30 = D_rotation(1, 30 * Math.PI / 180);   // the 30°-apart rosette (C,M,K)
  ok(`15° screens → moiré = ${m15.toFixed(2)}× pitch (industry quotes 3.83×)`,
     approx(m15, 3.83, 0.01));
  ok(`30° screens → moiré = ${m30.toFixed(2)}× pitch (tight rosette, least visible)`,
     approx(m30, 1.93, 0.01));
}

// ---------------------------------------------------------------------------
console.log('\n' + (fails === 0
  ? 'ALL CHECKS PASSED — every on-page number is reproduced here.'
  : `${fails} CHECK(S) FAILED`));
process.exit(fails === 0 ? 0 : 1);
