#!/usr/bin/env node
// ─────────────────────────────────────────────────────────────────────────────
// The Curve the Chain Knows — offline verifier
//
// P1 · The Verification Venue.  Every number that appears on the page is
// recomputed here from first principles, with the check shown.  The honesty
// rule of the house: nothing on the page is asserted that does not PASS below.
//
// What we prove, in order:
//   A. The catenary ODE.            y = a·cosh(x/a) satisfies y'' = (1/a)√(1+y'²)
//   B. The energy principle.        Among ALL curves with the same endpoints and
//                                   the same length, the catenary uniquely hangs
//                                   lowest (minimum potential energy). Shown by
//                                   building length-matched competitors and a
//                                   discrete free-hanging chain that settles onto
//                                   cosh with NO assumption it should.
//   C. Galileo's error, made exact. The hanging chain is NOT a parabola — but the
//                                   deviation → 0 as the sag → 0 (he was right in
//                                   the shallow limit, and right about a *different*
//                                   load — the suspension cable).
//   D. The two loads.              Self-weight (per arc length) → catenary;
//                                   uniform horizontal load (a bridge deck) →
//                                   parabola. Both recovered by integrating the ODE.
//   E. The Gateway Arch.           Its published centroid equation reproduces the
//                                   monument's dimensions, and is a *weighted*
//                                   (flattened) catenary — measurably not the
//                                   uniform one. (Osserman 2010; constants pending
//                                   citation confirmation — see facts.md.)
//
// Run:  node research/catenary/verify.mjs
// ─────────────────────────────────────────────────────────────────────────────

let pass = 0, fail = 0;
const fails = [];
function check(name, cond, got, want) {
  if (cond) { pass++; console.log(`  PASS  ${name}`); }
  else { fail++; fails.push(name); console.log(`  FAIL  ${name}${got !== undefined ? `   got ${got}, want ${want}` : ''}`); }
}
const close = (a, b, tol) => Math.abs(a - b) <= tol;

const { cosh, sinh, tanh, sqrt, abs, PI, cos, sin, log } = Math;

// ── numerics ────────────────────────────────────────────────────────────────
// Composite Simpson on [lo,hi] with n (even) panels.
function simpson(f, lo, hi, n = 20000) {
  if (n % 2) n++;
  const h = (hi - lo) / n;
  let s = f(lo) + f(hi);
  for (let i = 1; i < n; i++) s += (i % 2 ? 4 : 2) * f(lo + i * h);
  return (s * h) / 3;
}
// Scalar Newton with numerical derivative.
function newton(f, x0, { tol = 1e-13, it = 200, h = 1e-7 } = {}) {
  let x = x0;
  for (let i = 0; i < it; i++) {
    const fx = f(x);
    if (abs(fx) < tol) return x;
    const d = (f(x + h) - f(x - h)) / (2 * h);
    x -= fx / d;
  }
  return x;
}

console.log('\nThe Curve the Chain Knows — verification\n');

// ═════════════════════════════════════════════════════════════════════════════
console.log("A. The catenary ODE  —  y = a*cosh(x/a) solves y'' = (1/a)*sqrt(1+y'^2)");
// ═════════════════════════════════════════════════════════════════════════════
{
  for (const a of [0.5, 1, 2, 7.3]) {
    let worst = 0;
    for (const x of [-3, -1.2, 0, 0.4, 2.5, 5]) {
      const yp = sinh(x / a);                 // y'
      const ypp = cosh(x / a) / a;            // y''
      const rhs = sqrt(1 + yp * yp) / a;      // (1/a)√(1+y'²)
      worst = Math.max(worst, abs(ypp - rhs) / Math.max(1, abs(rhs)));  // relative residual
    }
    check(`ODE residual a=${a}  (y'' = √(1+y'²)/a)`, worst < 1e-11, worst.toExponential(2), '< 1e-11');
  }
  // The Beltrami first integral: (y) / √(1+y'²) = a  (constant along the curve)
  const a = 1.7;
  let worstB = 0;
  for (const x of [-2, -0.5, 0, 1, 3]) {
    const y = a * cosh(x / a), yp = sinh(x / a);
    worstB = Math.max(worstB, abs(y / sqrt(1 + yp * yp) - a));
  }
  check("Beltrami integral  y/sqrt(1+y'^2) = a  (constant)", worstB < 1e-12, worstB.toExponential(2), '< 1e-12');

  // Arc length s(x) = a·sinh(x/a), measured from the vertex.
  const D = 2.4;
  const sAnalytic = a * sinh(D / a);
  const sNumeric = simpson(x => sqrt(1 + sinh(x / a) ** 2), 0, D);
  check("arc length  int_0^D sqrt(1+y'^2)dx = a*sinh(D/a)", close(sAnalytic, sNumeric, 1e-8), sNumeric.toFixed(9), sAnalytic.toFixed(9));

  // Tension: horizontal H = w·a constant; total tension T(x) = w·y(x) (weight w=1).
  // V(x) = w·s(x) = w·a·sinh(x/a);  T = √(H²+V²) = w·a·cosh(x/a) = w·y.
  let worstT = 0;
  for (const x of [0, 0.7, 1.5, 3]) {
    const V = a * sinh(x / a), Htension = a, T = sqrt(Htension * Htension + V * V), y = a * cosh(x / a);
    worstT = Math.max(worstT, abs(T - y));
  }
  check('tension  T(x)=√(H²+V²)=w·y(x)  (string tension is weight·height)', worstT < 1e-12, worstT.toExponential(2), '< 1e-12');
}

// ═════════════════════════════════════════════════════════════════════════════
console.log('\nB. The energy principle  —  the catenary hangs lowest of all equal-');
console.log('   length curves through the same two pins (minimum potential energy)');
// ═════════════════════════════════════════════════════════════════════════════
// Coordinates: origin at the catenary's centre of curvature, so the potential
// energy of a curve is PE = ∫ y ds  (weight w=1 per unit length), with y the
// height above y=0.  The constrained minimiser of ∫y ds at fixed length L and
// fixed endpoints is exactly y = a·cosh(x/a) (Lagrange/Beltrami, λ=0, C=a).
{
  const a = 1, D = 1;                          // chain of parameter 1 over |x|≤1
  const yEnd = a * cosh(D / a);                // endpoint height
  const L = 2 * a * sinh(D / a);               // its (fixed) length
  // catenary PE, two ways:
  const peCatNum = simpson(x => (a * cosh(x / a)) * cosh(x / a), -D, D);
  const peCatAna = D + a * sinh(D / a) * cosh(D / a);   // a·∫cosh² with a=1
  check('catenary PE = ∫y ds  (numeric = analytic)', close(peCatNum, peCatAna, 1e-7), peCatNum.toFixed(8), peCatAna.toFixed(8));

  // Competitor family: same endpoints (±D, yEnd), shape g(x) with g(±D)=0,
  // sag k tuned by Newton so the competitor's LENGTH equals L exactly. Then its
  // PE is computed in the SAME coordinate system. Catenary must be strictly lower.
  function competitor(gName, g, gp) {
    // y(x) = yEnd - k·g(x);  y' = -k·gp(x)
    const lengthOf = k => simpson(x => sqrt(1 + (k * gp(x)) ** 2), -D, D);
    const k = newton(k => lengthOf(k) - L, 0.6);
    const Lc = lengthOf(k);
    const pe = simpson(x => (yEnd - k * g(x)) * sqrt(1 + (k * gp(x)) ** 2), -D, D);
    check(`competitor "${gName}": length matched to catenary's L`, close(Lc, L, 1e-7), Lc.toFixed(8), L.toFixed(8));
    check(`competitor "${gName}": PE > catenary PE  (catenary hangs lower)`, pe > peCatNum + 1e-6, pe.toFixed(6), `> ${peCatNum.toFixed(6)}`);
  }
  competitor('parabola',  x => 1 - (x / D) ** 2,          x => -2 * x / (D * D));
  competitor('cosine',    x => cos(PI * x / (2 * D)),     x => -(PI / (2 * D)) * sin(PI * x / (2 * D)));
  competitor('quartic',   x => 1 - (x / D) ** 4,          x => -4 * x ** 3 / D ** 4);

  // The decisive demonstration: a FREE discrete chain — N rigid equal links pinned
  // at both ends — relaxed to its lowest-energy configuration with NO assumption
  // that it should be a cosh. Then we fit a·cosh and watch the residual → 0.
  function relaxChain(N) {
    const ell = L / N;                          // each link length
    // angles θ_i (i=0..N-1) measured from horizontal; node positions accumulate.
    // Initialise as a shallow arc. We hold the two endpoint constraints
    //   Σ ell·cosθ = 2D ,  Σ ell·sinθ = 0
    // and minimise PE = Σ ell·(y_{mid of link}). We do projected gradient descent.
    let th = Array.from({ length: N }, (_, i) => -0.9 * cos(PI * (i + 0.5) / N));
    const nodes = th0 => {
      const xs = [-D], ys = [0];
      for (let i = 0; i < N; i++) { xs.push(xs[i] + ell * cos(th0[i])); ys.push(ys[i] + ell * sin(th0[i])); }
      return { xs, ys };
    };
    // PE of a config (heights above 0; absolute origin irrelevant for the SHAPE):
    const PE = th0 => { const { ys } = nodes(th0); let s = 0; for (let i = 0; i < N; i++) s += ell * (ys[i] + ys[i + 1]) / 2; return s; };
    // endpoint miss (must close to (2D, 0)):
    const miss = th0 => { const { xs, ys } = nodes(th0); return [xs[N] - D, ys[N] - 0]; };
    // augmented objective with quadratic penalty on the closure constraint:
    const MU = 4000;
    const F = th0 => { const m = miss(th0); return PE(th0) + MU * (m[0] * m[0] + m[1] * m[1]); };
    const grad = th0 => {
      const g = new Array(N), f0 = F(th0), h = 1e-6;
      for (let i = 0; i < N; i++) { const t = th0.slice(); t[i] += h; g[i] = (F(t) - f0) / h; }
      return g;
    };
    let step = 0.02;
    for (let it = 0; it < 60000; it++) {
      const g = grad(th);
      const nt = th.map((v, i) => v - step * g[i]);
      if (F(nt) < F(th)) { th = nt; step *= 1.02; } else step *= 0.5;
      if (step < 1e-9) break;
    }
    const { xs, ys } = nodes(th);
    // Fit y = c0 + a·cosh(x/a): with symmetric pins the apex is the midpoint; use
    // the known catenary through endpoints (±D, yEnd_chain). Solve a from sag.
    const sag = (ys[0] + ys[N]) / 2 - Math.min(...ys);
    // catenary through pins separation 2D and this sag: sag = a(cosh(D/a)-1)
    const aFit = newton(aa => aa * (cosh(D / aa) - 1) - sag, 1);
    const apex = Math.min(...ys);
    let rms = 0;
    for (let i = 0; i <= N; i++) { const yc = apex + aFit * (cosh(xs[i] / aFit) - 1); rms += (ys[i] - yc) ** 2; }
    rms = sqrt(rms / (N + 1));
    return { rms, aFit, m: miss(th) };
  }
  const r1 = relaxChain(10), r2 = relaxChain(40);
  check('free chain (N=10) closes on its pins', abs(r1.m[0]) < 2e-3 && abs(r1.m[1]) < 2e-3, `(${r1.m[0].toExponential(1)},${r1.m[1].toExponential(1)})`, '~0');
  check('free chain (N=40) closes on its pins', abs(r2.m[0]) < 2e-3 && abs(r2.m[1]) < 2e-3, `(${r2.m[0].toExponential(1)},${r2.m[1].toExponential(1)})`, '~0');
  check('free chain settles onto cosh (N=10 rms small)', r1.rms < 5e-3, r1.rms.toExponential(2), '< 5e-3');
  check('free chain → cosh sharper as N grows (rms₄₀ < rms₁₀)', r2.rms < r1.rms + 1e-9, `${r2.rms.toExponential(2)} vs ${r1.rms.toExponential(2)}`, 'decreasing');
  check('recovered parameter a ≈ 1 (the chain we hung)', close(r2.aFit, 1, 0.05), r2.aFit.toFixed(4), '1.000 ± 0.05');
}

// ═════════════════════════════════════════════════════════════════════════════
console.log('\nC. Galileo, made exact  —  chain ≠ parabola, but → parabola as sag→0');
// ═════════════════════════════════════════════════════════════════════════════
{
  // For span [-D,D], match a parabola to the catenary at vertex AND both endpoints
  // (the natural "Galileo" comparison). Measure the maximum gap, as a fraction of
  // the sag, vs the shape ratio sag/span. It must shrink monotonically toward 0.
  function maxGap(a, D) {
    const sag = a * (cosh(D / a) - 1);
    // parabola p(x) = sag·(x/D)²  matches vertex(0)=0 and endpoints(±D)=sag
    let g = 0;
    for (let i = 0; i <= 4000; i++) { const x = -D + (2 * D * i) / 4000; const cat = a * (cosh(x / a) - 1); const par = sag * (x / D) ** 2; g = Math.max(g, abs(cat - par)); }
    return { rel: g / sag, ratio: sag / (2 * D), sag };
  }
  const D = 1;
  const rows = [10, 4, 2, 1, 0.5].map(a => maxGap(a, D)); // a large→shallow, a small→deep
  console.log('     sag/span      max|chain−parabola|/sag');
  for (const r of rows) console.log(`     ${r.ratio.toFixed(4)}        ${(r.rel * 100).toFixed(3)} %`);
  let mono = true;
  for (let i = 1; i < rows.length; i++) if (!(rows[i].rel > rows[i - 1].rel)) mono = false; // deeper ⇒ bigger gap
  check('deviation grows monotonically with sag (deeper chain, worse parabola)', mono);
  check('shallow limit: sag/span≈0.04 ⇒ gap < 0.2% of sag (Galileo nearly right)', rows[0].rel < 0.002, (rows[0].rel * 100).toFixed(3) + '%', '< 0.2%');
  check('deep chain: sag/span≈0.7 ⇒ gap > 4% of sag (Galileo clearly wrong)', rows[4].rel > 0.04, (rows[4].rel * 100).toFixed(2) + '%', '> 4%');

  // Why: the Taylor series. cosh(u) = 1 + u²/2 + u⁴/24 + …  The parabola captures
  // the u² term exactly; the first discrepancy is the u⁴ term. Verify the series.
  const u = 0.37;
  const series = 1 + u ** 2 / 2 + u ** 4 / 24 + u ** 6 / 720;
  check('cosh Taylor 1+u²/2+u⁴/24+u⁶/720 matches cosh(u)', close(series, cosh(u), 1e-7), series.toFixed(9), cosh(u).toFixed(9));
}

// ═════════════════════════════════════════════════════════════════════════════
console.log('\nD. The two loads  —  self-weight ⇒ catenary, uniform deck ⇒ parabola');
// ═════════════════════════════════════════════════════════════════════════════
{
  // Integrate the cable equilibrium ODE both ways with RK4 from the vertex
  // (y(0)=given, y'(0)=0) and confirm the resulting shape.
  // Self-weight (load per unit ARC length):   y'' = (1/a)·√(1+y'²)   → cosh
  // Uniform horizontal load (per unit x):      y'' = 1/a (const)      → parabola
  function integrate(ypp, a, D, h = 1e-4) {
    // state s=[y,y'] ; returns array of [x,y]
    let y = a, yp = 0; const pts = [[0, y]];
    const f = (st) => [st[1], ypp(st[1], a)];
    for (let x = 0; x < D - 1e-12; x += h) {
      const k1 = f([y, yp]);
      const k2 = f([y + h / 2 * k1[0], yp + h / 2 * k1[1]]);
      const k3 = f([y + h / 2 * k2[0], yp + h / 2 * k2[1]]);
      const k4 = f([y + h * k3[0], yp + h * k3[1]]);
      y += h / 6 * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0]);
      yp += h / 6 * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1]);
      pts.push([x + h, y]);
    }
    return pts;
  }
  const a = 1.5, D = 2;
  const self = integrate((yp) => sqrt(1 + yp * yp) / a, a, D);
  let eSelf = 0; for (const [x, y] of self) eSelf = Math.max(eSelf, abs(y - a * cosh(x / a)));
  check('self-weight ODE integrates to a·cosh(x/a)  (catenary)', eSelf < 1e-5, eSelf.toExponential(2), '< 1e-5');

  const uni = integrate(() => 1 / a, a, D);
  let eUni = 0; for (const [x, y] of uni) eUni = Math.max(eUni, abs(y - (a + x * x / (2 * a))));
  check('uniform-load ODE integrates to a parabola  a + x²/2a  (bridge cable)', eUni < 1e-6, eUni.toExponential(2), '< 1e-6');

  // And they are genuinely different curves over the same span (not a rounding tie):
  let sep = 0; for (let i = 0; i < self.length; i++) sep = Math.max(sep, abs(self[i][1] - uni[i][1]));
  check('catenary and parabola diverge over the span (max gap > 0.02)', sep > 0.02, sep.toFixed(4), '> 0.02');
}

// ═════════════════════════════════════════════════════════════════════════════
console.log('\nE. The Gateway Arch  —  published centroid equation reproduces the');
console.log('   monument, and is a WEIGHTED (flattened) catenary, not the uniform one');
// ═════════════════════════════════════════════════════════════════════════════
{
  // Centroid curve of the arch, in feet (Hannskarl Bandel / NPS; cf. Osserman,
  // Notices AMS 57(2), 2010). y measured up from the springing line:
  //   y = A − B·cosh(C·x),   |x| ≤ Xmax
  const A = 693.8597, B = 68.7672, C = 0.0100333, Xmax = 299.2239;
  const yArch = x => A - B * cosh(C * x);
  const apex = yArch(0);
  check('apex centroid height  A−B = 625.0925 ft', close(apex, 625.0925, 5e-4), apex.toFixed(4), '625.0925');
  // base: y = 0 at x = Xmax  (where the centroid curve meets the springing line)
  const baseRoot = newton(yArch, 290);
  check('centroid meets ground (y=0) at x ≈ ±299.2239 ft', close(baseRoot, Xmax, 0.05), baseRoot.toFixed(4), '299.2239');
  check('centroid span 2·Xmax ≈ 598.45 ft (< the 630 ft outer width)', close(2 * Xmax, 598.4478, 1e-3) && 2 * Xmax < 630, (2 * Xmax).toFixed(2), '598.45');
  // The arch's nominal height/width are 630 ft (to the OUTER surface); the centroid
  // curve is 625.09 ft tall — the difference is the half-depth of the leg sections.
  check('apex centroid (625.09 ft) sits just below the 630 ft nominal height', apex < 630 && 630 - apex < 6, (630 - apex).toFixed(2), '≈ 4.9 ft');

  // THE INVARIANT THAT SETTLES IT.  Any ordinary catenary y = a·cosh(x/a) — even
  // shifted/inverted to A' − B'·cosh(C'·x) — must have amplitude·rate = 1, because
  // B'=a and C'=1/a.  The arch's published constants give B·C = 0.690 ≠ 1, so its
  // centroid is provably NOT an ordinary catenary.  The shortfall from 1 measures
  // how heavily the section is weighted toward the base.
  const BC = B * C;
  check('ordinary-catenary invariant B·C would equal 1; the arch gives 0.690', close(BC, 0.6900, 5e-4) && abs(BC - 1) > 0.2, BC.toFixed(4), '0.690 (≠ 1 ⇒ weighted)');
  console.log(`     amplitude×rate  B·C = ${BC.toFixed(4)}   (=1 for a plain chain; <1 ⇒ base-weighted)`);

  // For the eye: the ordinary catenary pinned to the SAME apex (0,625.0925) and
  // base (±299.2239, 0).  Solve a(cosh(Xmax/a) − 1) = apex for a (the inverted,
  // vertex-up uniform catenary u(x) = apex + a − a·cosh(x/a)).
  const aUni = newton(aa => aa * (cosh(Xmax / aa) - 1) - apex, 120, { tol: 1e-9 });
  const uUni = x => apex + aUni - aUni * cosh(x / aUni);
  check('matched uniform catenary parameter a solves cleanly (~118.6 ft)', aUni > 100 && aUni < 140, aUni.toFixed(2), '100–140');
  let gap = 0, where = 0;
  for (let i = 0; i <= 4000; i++) { const x = (Xmax * i) / 4000; const d = abs(yArch(x) - uUni(x)); if (d > gap) { gap = d; where = x; } }
  check('arch and the same-endpoint ordinary catenary are a DIFFERENT curve', gap > 1, gap.toFixed(2) + ' ft', '> 1 ft separation');
  // crown curvature: arch κ = B·C² ; uniform κ = 1/aUni. Report which is flatter.
  const kArch = B * C * C, kUni = 1 / aUni;
  console.log(`     max |arch − matched catenary| = ${gap.toFixed(2)} ft at x=${where.toFixed(0)} ft;  crown curvature arch ${kArch.toFixed(6)} vs catenary ${kUni.toFixed(6)} (arch ${kArch < kUni ? 'FLATTER' : 'sharper'} at crown)`);

  // Osserman cross-check: D = A·B = 0.690 exceeds √3/3 ≈ 0.5774, so the arch's
  // curvature is MAXIMAL at the apex, with radius of curvature there ≈ 145 ft.
  const curv = x => abs(-B * C * C * cosh(C * x)) / (1 + (B * C * sinh(C * x)) ** 2) ** 1.5;
  let kmax = 0, xmax = 0; for (let i = 0; i <= 4000; i++) { const x = (Xmax * i) / 4000; if (curv(x) > kmax) { kmax = curv(x); xmax = x; } }
  check('arch curvature is maximal at the apex (Osserman: D=0.69 > √3/3)', xmax < 1, xmax.toFixed(1), 'x=0 (apex)');
  const Rapex = 1 / curv(0);
  check('apex radius of curvature ≈ 145 ft (Osserman)', close(Rapex, 145, 1.5), Rapex.toFixed(1) + ' ft', '≈ 145 ft');
}

// ═════════════════════════════════════════════════════════════════════════════
console.log(`\n${fail === 0 ? 'ALL CHECKS PASS' : 'SOME CHECKS FAILED'}  —  ${pass} passed, ${fail} failed`);
if (fail) { console.log('  failed: ' + fails.join('; ')); process.exit(1); }
