// verify-flat-out-of-nothing.mjs - the geometry behind the stratum
// "Flat Out of Nothing" (/strata/flat-out-of-nothing/).
//
// The claim the page shows: you cannot certify a flat surface without a flat
// reference, yet Joseph Whitworth's three-plate method (systematized and
// published in an 1840 paper read to the British Association at Glasgow, and
// reprinted as "A Paper on Plane Metallic Surfaces or True Planes") conjures the
// reference from nothing. Two plates worked against each other converge to a
// MATING pair: one convex, one concave, of ANY common radius. They fit
// perfectly and both are curved. Add a third plate and test all three pairs and
// the only shape that survives is the plane: 1/R forced to 0.
//
// The modern interferometric three-flat test (Schulz & Schwider, 1967) has the
// same three-body structure. Along the flip-axis diameter the three pairwise
// sums form a solvable 3x3 system and recover the ABSOLUTE profile of each flat.
// Off that diameter the flip mirrors the coordinate, and a common odd component
// shared by all three flats is structurally invisible: the null space that
// comparisons in rotated positions exist to pin (Schulz & Schwider's fourth
// interferogram reached any diameter in 1967; Fritz 1984 fit the whole surface
// with Zernike polynomials). The usual laser calibration still runs on this
// bootstrap, moved to nanometres; the routes outside it take a reference that is
// not another solid flat (a liquid surface levelled by gravity, or the straight
// path of a light beam).
//
//   run:  node research/flat-out-of-nothing/verify-flat-out-of-nothing.mjs
//
// No dependencies. Every number the page displays is recomputed here from
// scratch. Free choices (idealized rigid plates, uniform-wear / alternating-
// projection abrasion model, single tested diameter, scraping not lapping) are
// named in the page's check panel and in research/flat-out-of-nothing/README.md.

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

// ── Geometry of the tested plate ────────────────────────────────────────────
// A plate of half-width L, worn to a parabolic dome/bowl of sagitta s (peak
// height at the edge). The osculating radius of that parabola at its centre is
// R = L^2 / (2 s); its curvature is kappa = 1/R = 2 s / L^2.
const L = 0.125;                      // 250 mm surface plate, half-width in metres
const sagToR = (s) => (L * L) / (2 * s);
const sagToKappa = (s) => (2 * s) / (L * L);

// ── 1. The two-plate trap: ANY radius passes ────────────────────────────────
// Lap two plates together. Uniform wear removes the high spots until the gap is
// zero everywhere: the mating condition a(x) + b(x) = const. If plate A ends a
// dome of curvature +kappa, plate B is the exact bowl of curvature -kappa. The
// residual gap is identically zero for EVERY kappa: a one-parameter family of
// false passes.
console.log('\n- two-plate test: mating residual = 0 for every radius -');
const bows_um = [1, 5, 10, 20];       // edge sagitta in micrometres
for (const s_um of bows_um) {
  const s = s_um * 1e-6;
  const kA = sagToKappa(s);           // dome
  const kB = -kA;                     // mating bowl
  const residualCurv = kA + kB;       // mating condition on the power mode
  const R = sagToR(s);
  ok(`bow ${String(s_um).padStart(2)} um  ->  R = ${(R / 1000).toFixed(2)} km, 1/R = ${kA.toExponential(2)} /m, mate residual = ${residualCurv}`,
     residualCurv === 0 && kA > 0);
}
ok('two-plate test passes a NON-zero curvature (both plates curved, fit perfect)',
   sagToKappa(10e-6) > 0);
// the reference numbers the page prints for the default 5 um bow:
{
  const s = 5e-6;
  ok('default 5 um bow -> R = 1.56 km', approx(sagToR(s), 1562.5, 0.5), `R=${sagToR(s).toFixed(1)} m`);
  ok('default 5 um bow -> 1/R = 6.40e-4 /m', approx(sagToKappa(s), 6.4e-4, 1e-7), `k=${sagToKappa(s).toExponential(4)}`);
  // R and kappa are computed by separate expressions, so their product is 1 only
  // to floating-point rounding. Tolerance 1e-12, the same one the page's check
  // panel applies to the identical test.
  ok('R and 1/R are reciprocals (product = 1, tolerance 1e-12)',
     approx(sagToR(s) * sagToKappa(s), 1, 1e-12),
     `R*kappa - 1 = ${(sagToR(s) * sagToKappa(s) - 1).toExponential(2)}`);
}
// The gap RMS and contact fraction the page prints under instrument 1, computed
// the same way there and here: sample plate A's worked face, DERIVE plate B from
// the contact condition faceA + faceB = K, then measure the residual gap.
function matingGap(s_um) {
  const n = 129, faceA = [], faceB = [], K = s_um;
  for (let i = 0; i < n; i++) { const u = (i / (n - 1)) * 2 - 1; faceA.push(s_um * (1 - u * u)); }
  for (let i = 0; i < n; i++) faceB.push(K - faceA[i]);
  let sumsq = 0, touching = 0;
  for (let i = 0; i < n; i++) {
    const g = K - faceA[i] - faceB[i];
    sumsq += g * g;
    if (Math.abs(g) < 1e-3) touching++;      // 1 nm expressed in um
  }
  return { rms: Math.sqrt(sumsq / n), contact: 100 * touching / n };
}
for (const s_um of bows_um) {
  const g = matingGap(s_um);
  ok(`bow ${String(s_um).padStart(2)} um  ->  gap RMS ${g.rms.toFixed(2)} um over ${g.contact.toFixed(0)}% contact`,
     g.rms === 0 && g.contact === 100);
}
// and the same routine on a pair that is NOT mated must report a real gap, so
// the 0.00 above is a measurement and not a constant.
{
  const n = 129, K = 5;
  let sumsq = 0;
  for (let i = 0; i < n; i++) {
    const u = (i / (n - 1)) * 2 - 1;
    const faceA = 5 * (1 - u * u), faceB = 3 * (1 - u * u);   // mismatched bowl
    const g = K - faceA - faceB; sumsq += g * g;
  }
  const rms = Math.sqrt(sumsq / n);
  ok('a mismatched pair reports a NON-zero gap (the residual is measured, not stubbed)',
     rms > 0.1, `rms = ${rms.toFixed(3)} um`);
}

// ── 2. The third plate forces the plane (the little linear system) ──────────
// Three plates, three pairwise matings, on the power (curvature) mode. Each
// mating drives the pair's summed curvature to zero:
//   a + b = 0,   b + c = 0,   c + a = 0.
// Matrix M = [[1,1,0],[0,1,1],[1,0,1]]. Its determinant is 2 (nonzero), so the
// ONLY solution is a = b = c = 0: every plate flat. Two plates leave one free
// parameter; the third removes it.
function det3(m) {
  return m[0][0]*(m[1][1]*m[2][2]-m[1][2]*m[2][1])
       - m[0][1]*(m[1][0]*m[2][2]-m[1][2]*m[2][0])
       + m[0][2]*(m[1][0]*m[2][1]-m[1][1]*m[2][0]);
}
console.log('\n- three-plate system  a+b=0, b+c=0, c+a=0 -');
const M = [[1,1,0],[0,1,1],[1,0,1]];
ok('determinant of the three-mating system = 2 (nonzero -> unique solution)',
   det3(M) === 2, `det=${det3(M)}`);
ok('two matings alone are rank 2 (one free parameter: any common radius survives)',
   det3([[1,1,0],[0,1,1],[0,0,0]]) === 0);
// the unique solution of the full system is the plane. Solve it for real, by
// Gaussian elimination with partial pivoting on the augmented system M x = 0,
// starting from a deliberately non-zero guess so nothing here is assumed.
function solve3(m, rhs) {
  const A3 = m.map((row, i) => row.concat([rhs[i]]));
  for (let col = 0; col < 3; col++) {
    let piv = col;
    for (let r = col + 1; r < 3; r++) if (Math.abs(A3[r][col]) > Math.abs(A3[piv][col])) piv = r;
    if (Math.abs(A3[piv][col]) < 1e-12) return null;          // singular
    [A3[col], A3[piv]] = [A3[piv], A3[col]];
    for (let r = 0; r < 3; r++) {
      if (r === col) continue;
      const f = A3[r][col] / A3[col][col];
      for (let c = col; c < 4; c++) A3[r][c] -= f * A3[col][c];
    }
  }
  return [A3[0][3] / A3[0][0], A3[1][3] / A3[1][1], A3[2][3] / A3[2][2]];
}
{
  const x = solve3(M, [0, 0, 0]);
  ok('solving all three matings gives a=b=c=0 (the plane), by elimination not by assertion',
     x !== null && x.every((v) => v === 0), `x=[${x}]`);
  // and the SAME solver on two matings only is singular: the free parameter survives
  const twoOnly = solve3([[1,1,0],[0,1,1],[0,0,0]], [0,0,0]);
  ok('the same solver on two matings alone reports singular (one free parameter left)',
     twoOnly === null);
  // sanity: the solver is not just returning zeros. Perturb the right-hand side
  // (plates left mating to a nonzero residual) and it must return that shape.
  const y = solve3(M, [2, 2, 2]);
  ok('solver returns a non-trivial answer on a non-zero right-hand side (not a zero stub)',
     y !== null && y.every((v) => approx(v, 1, 1e-12)), `x=[${y.map(v=>v.toFixed(3))}]`);
}

// ── 3. Three-plate lapping converges to flat (alternating projections) ──────
// Model one pairwise lapping as projecting the pair's curvatures onto the line
// {k_i + k_j = 0}: k_i -= (k_i+k_j)/2, k_j -= (k_i+k_j)/2. Cycle the three pairs
// A-B, B-C, C-A. This is projection onto three subspaces of R^3 whose only
// common point is the origin, so it converges to all-flat. (Uniform-wear
// idealization; real scraping removes only at high spots - named on the page.)
function lapPair(k, i, j) {
  const half = (k[i] + k[j]) / 2;
  k[i] -= half; k[j] -= half;
}
function runCycles(start, thresh) {
  const k = start.slice();
  const startMax = Math.max(...k.map(Math.abs));
  let cyc = 0;
  const trace = [startMax];
  while (Math.max(...k.map(Math.abs)) > thresh * startMax && cyc < 1000) {
    lapPair(k, 0, 1); lapPair(k, 1, 2); lapPair(k, 2, 0);
    cyc++; trace.push(Math.max(...k.map(Math.abs)));
  }
  return { k, cyc, startMax, trace };
}
console.log('\n- three-plate lapping converges to the plane -');
const start = [8, -3, 5];             // arbitrary starting bows (um), NOT mated
const r = runCycles(start, 1e-4);     // stop when max bow < 1e-4 of start
ok('lapping drives every plate toward flat (max bow strictly shrinks each cycle)',
   r.trace.every((v, i) => i === 0 || v <= r.trace[i-1] + 1e-15),
   `start ${r.startMax} um`);
ok(`converges below 0.01% of the start bow in ${r.cyc} cycles`,
   Math.max(...r.k.map(Math.abs)) <= 1e-4 * r.startMax, `final ${Math.max(...r.k.map(Math.abs)).toExponential(2)} um`);
ok('the limit is the plane (all curvatures -> 0)',
   r.k.every((v) => Math.abs(v) < 1e-3), `k=[${r.k.map(v=>v.toFixed(4)).join(', ')}]`);
// piston (global height) is a separate mode lapping never touches: the process
// removes curvature (flatness), it can never fix a plate's absolute height.
// The plate is modelled with BOTH modes present, piston p and curvature k, and
// the lapping operator is applied to the plate objects themselves, so it is free
// to disturb the piston if the model lets it. It does not, and the curvatures do
// move, which is what makes this a test rather than a restatement.
function lapPlates(pl, i, j) {
  const half = (pl[i].k + pl[j].k) / 2;
  pl[i].k -= half; pl[j].k -= half;          // contact acts on the shape...
  // ...and nothing here writes pl[*].p: the pair can be brought to a perfect
  // mating at any common height, so the process has no purchase on piston.
}
{
  const plates = [{p: 3.0, k: 8}, {p: -1.0, k: -3}, {p: 2.5, k: 5}];
  const p0 = plates.map((q) => q.p), k0 = plates.map((q) => q.k);
  lapPlates(plates, 0, 1); lapPlates(plates, 1, 2); lapPlates(plates, 2, 0);
  const pistonMoved = plates.some((q, i) => q.p !== p0[i]);
  const curvMoved = plates.some((q, i) => q.k !== k0[i]);
  ok('lapping moves curvature but leaves every plate its arbitrary height offset',
     curvMoved && !pistonMoved,
     `p=[${plates.map(q=>q.p).join(', ')}] (was [${p0.join(', ')}]), k=[${plates.map(q=>q.k.toFixed(3)).join(', ')}]`);
}

// ── 4. Interferometric three-flat: absolute along the flip-axis diameter ────
// Along the axis about which a flat is flipped, the coordinate is unchanged, so
// the three interferometer comparisons are clean pairwise SUMS:
//   P = a + b,  Q = b + c,  T = c + a   (pointwise along the diameter).
// Recover: a = (P + T - Q)/2, b = (P + Q - T)/2, c = (Q + T - P)/2. Exact.
console.log('\n- three-flat solve along the flip-axis diameter (Schulz & Schwider 1967) -');
const a = [ 0, 12, 18, 9, 0, -7, -11, -5, 0]; // true profiles along the diameter (nm)
const b = [ 0, -4, 3, 14, 6, 2, -8, -1, 0];
const c = [ 0, 5, -9, -2, 11, -3, 4, 7, 0];
const P = a.map((v,i)=>v+b[i]);
const Q = b.map((v,i)=>v+c[i]);
const T = c.map((v,i)=>v+a[i]);
const aR = P.map((_,i)=>(P[i]+T[i]-Q[i])/2);
const bR = P.map((_,i)=>(P[i]+Q[i]-T[i])/2);
const cR = P.map((_,i)=>(Q[i]+T[i]-P[i])/2);
const maxErr = Math.max(
  ...aR.map((v,i)=>Math.abs(v-a[i])),
  ...bR.map((v,i)=>Math.abs(v-b[i])),
  ...cR.map((v,i)=>Math.abs(v-c[i])));
ok('three pairwise sums recover all three absolute profiles exactly (max error 0)',
   maxErr === 0, `max|recovered - true| = ${maxErr} nm`);

// ── 5. Off-axis: the common odd mode is structurally invisible (null space) ──
// Off the flip-axis diameter the flip mirrors x -> -x, so the comparison reads
//   m_AB(x) = a(x) + b(-x),  etc.  Add the SAME odd function phi (phi(-x) =
// -phi(x)) to all three flats. Every measurement is unchanged, because
//   Delta m_AB(x) = phi(x) + phi(-x) = 0.  The shared odd bow cannot be seen by
// any pairwise flip comparison; this is why comparisons in rotated positions are
// needed beyond the one diameter (Schulz & Schwider's fourth interferogram, 1967;
// Fritz's full-surface Zernike fit, 1984). For the usual calibration the
// bootstrap moved, it did not go.
console.log('\n- off-axis null space: a shared odd bow is invisible to every pair -');
const xs = [-4,-3,-2,-1,0,1,2,3,4];
const idxMirror = xs.map((x)=>xs.indexOf(-x)); // index of -x
function mirror(f){ return idxMirror.map((j)=>f[j]); }
function meas(f,g){ const gm = mirror(g); return f.map((v,i)=>v+gm[i]); } // f(x)+g(-x)
// a phantom common odd mode:
const phi = xs.map((x)=> x*x*x*0.5 );        // odd: phi(-x) = -phi(x)
ok('phantom is odd (phi(-x) = -phi(x))',
   xs.every((x,i)=>approx(phi[i], -phi[idxMirror[i]], 1e-12)));
const a2 = a.map((v,i)=>v+phi[i]);
const b2 = b.map((v,i)=>v+phi[i]);
const c2 = c.map((v,i)=>v+phi[i]);
const m1 = meas(a,b),  m2 = meas(b,c),  m3 = meas(c,a);
const m1b = meas(a2,b2), m2b = meas(b2,c2), m3b = meas(c2,a2);
const dMeas = Math.max(
  ...m1.map((v,i)=>Math.abs(v-m1b[i])),
  ...m2.map((v,i)=>Math.abs(v-m2b[i])),
  ...m3.map((v,i)=>Math.abs(v-m3b[i])));
const dSurf = Math.max(...phi.map(Math.abs));
ok('adding a shared odd bow leaves EVERY pairwise measurement bit-identical',
   dMeas === 0, `max|delta measurement| = ${dMeas} nm`);
ok('...while the surfaces themselves are visibly warped (kernel is nontrivial)',
   dSurf > 0, `max|delta surface| = ${dSurf} nm`);
// the even part IS recovered; only the shared odd part is lost:
const evenA = a.map((v,i)=>(v+a[idxMirror[i]])/2);
const oddA  = a.map((v,i)=>(v-a[idxMirror[i]])/2);
ok('every profile splits into a recoverable even part and an ambiguous odd part',
   evenA.every((v,i)=>approx(v+oddA[i], a[i], 1e-12)));

console.log(`\n${fails === 0 ? 'ALL CHECKS PASSED' : fails + ' CHECK(S) FAILED'}\n`);
process.exit(fails === 0 ? 0 : 1);
