#!/usr/bin/env node
// ─────────────────────────────────────────────────────────────────────────────
// The Helen of Geometers — offline verifier
//
// P1 · The Verification Venue.  One curve — the cycloid, traced by a point on a
// rolling wheel — is, at the same time, the answer to two unrelated-looking
// problems and the heart of a 17th-century clock.  Every number that appears on
// the page is recomputed here from first principles, with the check shown.  The
// house rule: nothing is asserted on the page that does not PASS below.
//
// What we prove, in order:
//   A. The curve.            x=R(θ−sinθ), y=R(1−cosθ): the locus of a rim point on
//                            a wheel of radius R rolling a distance Rθ.
//   B. Brachistochrone.      Among candidate paths between the SAME two points, the
//                            cycloid gives the least descent time under gravity from
//                            rest — beating the straight line, a circular arc, and a
//                            parabola — and its time matches the closed form √(R/g)·θ.
//   C. Tautochrone.          On ONE cycloid, a bead released from rest reaches the
//                            bottom in the SAME time π√(R/g) from ANY starting height.
//   D. Huygens's clock.      A bob constrained to a cycloid is a perfect harmonic
//                            oscillator: period 4π√(R/g) at EVERY amplitude. A bob on
//                            a circular arc (an ordinary pendulum) slows as it swings
//                            wider — the "circular error", 4√(L/g)·K(sin(θ₀/2)).
//   E. Wren's length.        One arch of the cycloid is exactly 8R long (Wren 1658 —
//                            the first rectification of a non-trivial curve).
//   F. Roberval's area.      The area under one arch is exactly 3πR² — three times
//                            the rolling circle (Galileo weighed it; Roberval proved).
//   G. The seam.             The tautochrone descent time is exactly one quarter of
//                            the cycloidal pendulum's period — the two "perfect"
//                            properties are the same fact seen twice.
//
// Run:  node research/cycloid/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 g = 9.80665;            // standard gravity, m/s² — the only physical constant
const R = 1.0;                // generating-circle radius (units cancel in every ratio)

console.log('\nThe Helen of Geometers — verifier\n' + '─'.repeat(60));

// ── A. The curve is a rolling-wheel locus ───────────────────────────────────
// A wheel of radius R that has rolled through angle θ has its centre at (Rθ, R)
// and the marked rim point at centre + R·(−sinθ, −cosθ). Measuring y downward
// from the top of the wheel gives the standard cusp-up cycloid.
console.log('\nA. The curve = a point on a rolling wheel');
{
  const x = (t) => R * (t - Math.sin(t));
  const y = (t) => R * (1 - Math.cos(t));
  // The rolling construction, derived independently:
  const roll = (t) => {
    const cx = R * t, cy = R;                 // hub travels horizontally as it rolls
    const px = cx - R * Math.sin(t);          // rim point, starting at the bottom (cusp)
    const py = cy - R * Math.cos(t);          // y downward from the top
    return [px, py];
  };
  let okx = true, oky = true;
  for (let t = 0; t <= 2 * Math.PI + 1e-9; t += 0.013) {
    const [px, py] = roll(t);
    if (!close(px, x(t), 1e-12)) okx = false;
    if (!close(py, y(t), 1e-12)) oky = false;
  }
  check('rolling-wheel locus reproduces x = R(θ − sinθ)', okx);
  check('rolling-wheel locus reproduces y = R(1 − cosθ)', oky);
  // The cusps land one circumference apart (the wheel has turned once): 2πR.
  check('cusp-to-cusp span = 2πR (one circumference)', close(x(2 * Math.PI), 2 * Math.PI * R, 1e-12),
        x(2 * Math.PI), 2 * Math.PI * R);
}

// ── helper: a singularity-free descent-time integrator ──────────────────────
// Time down a path, integrated in the VERTICAL coordinate y (the drop below the
// release height), with the path given as x(y):
//      T = ∫₀^{yB} √(1 + (dx/dy)²) / √(2 g y) dy.
// Every descent curve has the same mild 1/√y singularity at the launch point, so
// the substitution y = yB·u² (dy = 2 yB u du, √y = √yB·u) cancels it EXACTLY and
// uniformly for every competitor — the integrand √(1+(dx/dy)²)·2√yB/√(2g) is
// bounded. (Integrating in x instead would leave a stronger u^(−1/2) tail at any
// vertical-launch curve and silently *under*-count its time; this avoids that.)
function descentTimeY(xdash, yB, N = 40000) {   // xdash(y) = dx/dy along the path
  const c = 2 * Math.sqrt(yB) / Math.sqrt(2 * g);
  const f = (u) => Math.sqrt(1 + xdash(yB * u * u) ** 2);
  let s = f(0) + f(1);
  for (let i = 1; i < N; i++) s += (i % 2 ? 4 : 2) * f(i / N);
  return c * s / (3 * N);
}

// ── B. The cycloid is the brachistochrone ───────────────────────────────────
console.log('\nB. Brachistochrone — least time of descent');
{
  // Fix the cycloid through A=(0,0) (the cusp) and a target angle θB; read off B.
  const thetaB = 2.0;                          // any 0<θB≤π puts B below-and-beside A
  const xB = R * (thetaB - Math.sin(thetaB));
  const yB = R * (1 - Math.cos(thetaB));

  // Closed form: descent time along the cycloid from the cusp to θ is √(R/g)·θ.
  const T_cyc_exact = Math.sqrt(R / g) * thetaB;

  // The cycloid as x(y): y = R(1−cosθ) ⇒ θ = arccos(1 − y/R); then dx/dy =
  // (dx/dθ)/(dy/dθ) = (1−cosθ)/sinθ. (At the cusp y→0 this → 0: a vertical launch.)
  const dxdyCyc = (y) => {
    if (y <= 0) return 0;
    const th = Math.acos(Math.max(-1, 1 - y / R));
    return (1 - Math.cos(th)) / Math.sin(th);
  };
  const T_cyc_num = descentTimeY(dxdyCyc, yB);

  check('cycloid descent time matches closed form √(R/g)·θ', close(T_cyc_num, T_cyc_exact, 1e-4),
        T_cyc_num.toFixed(6), T_cyc_exact.toFixed(6));

  // Competitor 1 — the straight line A→B.   x = (xB/yB)·y ⇒ dx/dy = xB/yB.
  const T_line = descentTimeY(() => xB / yB, yB);

  // Competitor 2 — a circular arc through A and B, tangent to the vertical at A
  // (the steep launch a naive optimiser favours). Centre on the x-axis at (cx,0)
  // with cx fixed by passing through B; the A-branch is x = cx − √(cx²−y²), so
  // dx/dy = y/√(cx²−y²).
  const cx = (xB * xB + yB * yB) / (2 * xB);
  const T_arc = descentTimeY((y) => y / Math.sqrt(Math.max(1e-12, cx * cx - y * y)), yB);

  // Competitor 3 — a parabola y = k√x through B (also a vertical launch at A).
  // x = (y/k)² ⇒ dx/dy = 2y/k², with k = yB/√xB.
  const k = yB / Math.sqrt(xB);
  const T_par = descentTimeY((y) => 2 * y / (k * k), yB);

  console.log(`     times (s):  cycloid ${T_cyc_num.toFixed(5)} | parabola ${T_par.toFixed(5)} | arc ${T_arc.toFixed(5)} | line ${T_line.toFixed(5)}`);
  check('cycloid beats the straight line', T_cyc_num < T_line, T_cyc_num.toFixed(5), '< ' + T_line.toFixed(5));
  check('cycloid beats the circular arc', T_cyc_num < T_arc, T_cyc_num.toFixed(5), '< ' + T_arc.toFixed(5));
  check('cycloid beats the y=k√x parabola', T_cyc_num < T_par, T_cyc_num.toFixed(5), '< ' + T_par.toFixed(5));
  // And the line is the longest-time of the smooth descents (the obvious guess is worst).
  check('the straight line is the slowest of the four', T_line > T_arc && T_line > T_par && T_line > T_cyc_num);
}

// ── C. The cycloid is the tautochrone ───────────────────────────────────────
console.log('\nC. Tautochrone — equal descent time from any height');
{
  // Bead released from rest at angle θ0, sliding to the bottom at θ=π.
  // ds/dθ = 2R sin(θ/2);  speed v(θ) = √(2gR(cosθ0 − cosθ)) by energy.
  const T_bottom = (theta0) => {
    const a = Math.cos(theta0);
    // singularity at θ=θ0 (v=0): substitute θ = θ0 + (π−θ0)·u² to regularise.
    const lo = theta0, span = Math.PI - theta0, N = 40000;
    const f = (u) => {
      const th = lo + span * u * u, dth_du = 2 * span * u;
      const denom = 2 * g * R * (a - Math.cos(th));
      if (denom <= 0) return 0;
      return (2 * R * Math.sin(th / 2)) / Math.sqrt(denom) * dth_du;
    };
    let s = f(0) + f(1);
    for (let i = 1; i < N; i++) s += (i % 2 ? 4 : 2) * f(i / N);
    return s / (3 * N);
  };
  const T_predict = Math.PI * Math.sqrt(R / g);    // independent of θ0
  let allEqual = true;
  const probes = [0.2, 0.6, 1.1, 1.8, 2.6, Math.PI - 0.05];
  for (const th0 of probes) {
    const T = T_bottom(th0);
    const ok = close(T, T_predict, 3e-3);
    if (!ok) allEqual = false;
    console.log(`     release at θ0=${th0.toFixed(2)} → bottom in ${T.toFixed(5)} s  (predict ${T_predict.toFixed(5)})`);
  }
  check('descent time to the bottom is π√(R/g) from every start', allEqual);
  // Contrast: on a CIRCULAR arc the descent time DOES depend on the start (not a tautochrone).
  // Time to bottom of a circular bowl radius ρ from angle φ0: quarter-period-like,
  // grows with φ0 — we just show two starts differ by > 3%.
  const circBottom = (phi0) => {
    // bowl: position angle φ from bottom; height above bottom h=ρ(1−cosφ); v=√(2g ρ(cosφ−cosφ0))... wait sign
    const rho = 1.0, N = 40000, span = phi0;
    const f = (u) => {
      const phi = phi0 - span * u * u; // integrate from φ0 (rest) down to 0
      const dphi_du = -2 * span * u;
      const denom = 2 * g * rho * (Math.cos(phi) - Math.cos(phi0));
      if (denom <= 0) return 0;
      return Math.abs(rho / Math.sqrt(denom) * dphi_du);
    };
    let s = f(0) + f(1);
    for (let i = 1; i < N; i++) s += (i % 2 ? 4 : 2) * f(i / N);
    return s / (3 * N);
  };
  const c_small = circBottom(0.3), c_big = circBottom(2.0);
  console.log(`     circular bowl: from 0.30 rad ${c_small.toFixed(5)} s vs from 2.0 rad ${c_big.toFixed(5)} s`);
  check('a circular bowl is NOT a tautochrone (times differ by >3%)', (c_big - c_small) / c_small > 0.03);
}

// ── elliptic integral K(k) by the arithmetic-geometric mean ─────────────────
function ellipK(k) {            // complete elliptic integral of the 1st kind, modulus k
  let a = 1, b = Math.sqrt(1 - k * k);
  for (let i = 0; i < 60; i++) { const an = (a + b) / 2, bn = Math.sqrt(a * b); a = an; b = bn; }
  return Math.PI / (2 * a);
}

// ── D. Huygens: the cycloidal pendulum keeps perfect time ───────────────────
console.log('\nD. Huygens — the perfect (isochronous) pendulum');
{
  // Cycloidal pendulum: a bob constrained to a cycloid is exact SHM in arc length.
  // Measuring arc length σ from the bottom, height above bottom h = σ²/(8R), so the
  // potential is quadratic ⇒ harmonic. Verify by integrating the quarter-period from
  // several amplitudes (expressed as a starting angle θ0) and showing it is constant.
  const cycQuarter = (theta0) => {        // = the tautochrone descent time, by construction
    const a = Math.cos(theta0), lo = theta0, span = Math.PI - theta0, N = 40000;
    const f = (u) => {
      const th = lo + span * u * u, dth_du = 2 * span * u;
      const d = 2 * g * R * (a - Math.cos(th));
      return d <= 0 ? 0 : (2 * R * Math.sin(th / 2)) / Math.sqrt(d) * dth_du;
    };
    let s = f(0) + f(1); for (let i = 1; i < N; i++) s += (i % 2 ? 4 : 2) * f(i / N);
    return s / (3 * N);
  };
  const T_cyc = (th0) => 4 * cycQuarter(th0);   // full period = 4 × quarter
  const T_cyc_predict = 4 * Math.PI * Math.sqrt(R / g);
  let iso = true;
  for (const th0 of [0.2, 1.0, 2.0, 3.0]) {
    const T = T_cyc(th0);
    if (!close(T, T_cyc_predict, 6e-3)) iso = false;
    console.log(`     cycloidal pendulum, amplitude θ0=${th0.toFixed(1)} → period ${T.toFixed(5)} s  (predict ${T_cyc_predict.toFixed(5)})`);
  }
  check('cycloidal pendulum period = 4π√(R/g) at EVERY amplitude', iso);

  // The ordinary (circular) pendulum: period T = 4√(L/g)·K(sin(θ0/2)) — grows with swing.
  const L = 1.0;
  const T_circ = (th0) => 4 * Math.sqrt(L / g) * ellipK(Math.sin(th0 / 2));
  const T_small = 2 * Math.PI * Math.sqrt(L / g);           // small-angle limit
  check('circular pendulum → 2π√(L/g) as amplitude → 0', close(T_circ(0.001), T_small, 1e-4),
        T_circ(0.001).toFixed(6), T_small.toFixed(6));
  // The circular error at a wide swing is real and computable.
  const err30 = (T_circ(Math.PI / 6) - T_small) / T_small * 100;   // 30° amplitude
  const err90 = (T_circ(Math.PI / 2) - T_small) / T_small * 100;   // 90° amplitude
  console.log(`     circular pendulum runs slow:  +${err30.toFixed(3)}% at 30°,  +${err90.toFixed(2)}% at 90°`);
  check('circular pendulum gains ~1.74% period at 30° amplitude', close(err30, 1.7402, 0.01), err30.toFixed(4), '1.7402');
  check('circular pendulum gains ~18.03% period at 90° amplitude', close(err90, 18.034, 0.02), err90.toFixed(3), '18.034');
  check('a wider swing always makes the circular pendulum slower', T_circ(0.5) < T_circ(1.0) && T_circ(1.0) < T_circ(1.5));
}

// ── E. Wren's rectification: one arch is 8R long ────────────────────────────
console.log("\nE. Wren (1658) — the arch length is exactly 8R");
{
  // arc length L = ∫₀^{2π} √(x'² + y'²) dθ = ∫₀^{2π} 2R sin(θ/2) dθ = 8R.
  const N = 200000; let s = 0;
  const f = (t) => 2 * R * Math.sin(t / 2);
  s = f(0) + f(2 * Math.PI);
  for (let i = 1; i < N; i++) s += (i % 2 ? 4 : 2) * f(i / N * 2 * Math.PI);
  const Lnum = s * (2 * Math.PI / N) / 3;
  check('one cycloid arch has length 8R', close(Lnum, 8 * R, 1e-6), Lnum.toFixed(8), (8 * R).toFixed(8));
}

// ── F. Roberval's quadrature: area under one arch is 3πR² ────────────────────
console.log('\nF. Roberval — the area under one arch is 3πR²');
{
  // A = ∫ y dx over one arch = ∫₀^{2π} R(1−cosθ)·R(1−cosθ) dθ = R²∫(1−cosθ)² dθ = 3πR².
  const N = 200000; const f = (t) => R * (1 - Math.cos(t)) * R * (1 - Math.cos(t));
  let s = f(0) + f(2 * Math.PI);
  for (let i = 1; i < N; i++) s += (i % 2 ? 4 : 2) * f(i / N * 2 * Math.PI);
  const Anum = s * (2 * Math.PI / N) / 3;
  check('area under one arch = 3πR² (three rolling circles)', close(Anum, 3 * Math.PI * R * R, 1e-6),
        Anum.toFixed(8), (3 * Math.PI * R * R).toFixed(8));
  check('that is exactly 3× the rolling circle πR²', close(Anum / (Math.PI * R * R), 3, 1e-6));
}

// ── G. The seam: one fact, seen twice ───────────────────────────────────────
console.log('\nG. The seam — tautochrone time = ¼ of the pendulum period');
{
  const T_drop = Math.PI * Math.sqrt(R / g);          // time to fall to the bottom from rest
  const T_period = 4 * Math.PI * Math.sqrt(R / g);    // cycloidal pendulum period
  check('π√(R/g) (descent) is exactly ¼ of 4π√(R/g) (period)', close(T_drop, T_period / 4, 1e-12),
        T_drop.toFixed(8), (T_period / 4).toFixed(8));
}

// ─────────────────────────────────────────────────────────────────────────────
console.log('\n' + '─'.repeat(60));
console.log(`RESULT: ${pass}/${pass + fail} checks passed.` + (fail ? `  FAILED: ${fails.join(', ')}` : '  All clear.'));
process.exit(fail ? 1 : 0);
