#!/usr/bin/env node
// verify.mjs — the check behind the stratum "Why does a curveball curve?"
//
// Integrates the flight of a pitched baseball under the three forces every
// physicist of the game agrees on — gravity, aerodynamic drag, and the Magnus
// (lift) force from spin — and reproduces the numbers the instrument surfaces:
//   • how much LESS a backspinning fastball drops than a spinless ball
//     (Statcast's "induced vertical break", IVB), for realistic inputs;
//   • how much MORE a topspinning curveball drops;
//   • the spin rate a fastball would need for the Magnus force to equal
//     gravity — the honest threshold for a *literally* rising fastball;
//   • that no real MLB fastball reaches it, so "rising" is an illusion.
//
// The SAME force model and constants are used verbatim by the in-browser
// instrument at /strata/why-does-a-curveball-curve/ — this file is the
// ground truth that the page's live numbers are checked against.
//
// ---- Sources (every constant is cited; ranges are named, not hidden) --------
//   [Nathan08]  A. M. Nathan, "The effect of spin on the flight of a baseball,"
//               Am. J. Phys. 76 (2008) 119-124 (arXiv:physics/0605041).  Uses
//               F_D = ½C_D ρAv², F_L = ½C_L ρAv² (his Eq. 1) and the SHS
//               (Sawicki-Hubbard-Stronge) lift parametrization (his Eq. 2),
//               C_L = 0.09 + 0.6·S for S>0.1 (giving C_L=0.21 at S=0.2, stated
//               verbatim in the paper), which Nathan's own data confirm S<0.3.
//   [NathanTA]  A. M. Nathan, "Analysis of Baseball Trajectories," the
//               parametrization behind his public trajectory calculator
//               (baseball.physics.illinois.edu/TrajectoryAnalysis.pdf):
//                 lift:  C_L = 1.120·S / (0.583 + 2.333·S)          (S = Rω/v)
//                 drag:  C_D = 0.297 + 0.0292·(ω_rpm / 1000)
//               This is the model USED HERE (it stays valid up to the higher
//               spin factors a curveball reaches, S≈0.28); the SHS form is
//               carried alongside as an independent cross-check — the two agree
//               to ~0.01 in C_L across the pitching range.  Both fits are
//               reproduced against Nathan's stated values below.
//   [Adair]     R. K. Adair, "The Physics of Baseball," 3rd ed. (2002).
//   [MLB]       Official Baseball Rules 3.01/3.02: weight 5-5.25 oz,
//               circumference 9-9.25 in.
//   [Statcast]  MLB Statcast pitch-tracking, league-average pitch shapes
//               (Baseball Savant), used only as an external sanity target.
//
//   Confidence is flagged inline: [solid] exact/definitional, [approx] a
//   representative value inside a real measured range, [target] an external
//   number we aim to land near (not an input).
//
// Run:  node research/curveball/verify.mjs
'use strict';

// ===========================================================================
// 1.  Constants
// ===========================================================================
const g = 9.80665;              // m/s^2   standard gravity                [solid]
// Regulation baseball: midpoints of the MLB legal ranges.                  [MLB]
const massOz  = 5.125;          // oz   (legal 5.00-5.25)                   [approx]
const circIn  = 9.125;          // in   (legal 9.00-9.25)                   [approx]
const m = massOz * 0.0283495;   // kg
const circ = circIn * 0.0254;   // m
const R = circ / (2 * Math.PI); // m   radius from circumference
const A = Math.PI * R * R;      // m^2 cross-sectional area
// Air density.  Sea-level standard; Denver (Coors, ~1580 m) ~0.86x.        [approx]
const RHO_SEA    = 1.225;       // kg/m^3  ISA sea level, 15 C
const RHO_DENVER = 1.048;       // kg/m^3  ~1580 m, warm day (see note below)

// Drag coefficient for a pitched baseball.  Nathan's spin-dependent fit; the
// real per-pitch value scatters ~0.28-0.58 with weather/seams/Reynolds (a real
// drag crisis), so this is a good central model, NOT a constant of nature.
const cDrag = (rpm) => 0.297 + 0.0292 * (rpm / 1000);        // [NathanTA]

// Lift coefficient vs spin factor S = R*omega/v (surface speed / forward
// speed).  Nathan's rational trajectory-calculator fit:
const cLift = (S) => (1.120 * S) / (0.583 + 2.333 * S);      // [NathanTA]
// SHS cross-check (independent fit, agrees to ~0.01 across the range):
const cLiftSHS = (S) => (S < 0.1 ? 1.5 * S : 0.09 + 0.6 * S);// [Nathan08]

// Geometry of the throw.  Rubber-to-plate 60.5 ft; release ~5.5 ft in front,
// so the ball flies ~55 ft.  Standard in the pitch-tracking literature.
const FT = 0.3048;
const FLIGHT_FT = 55.0;         // [approx]  (release-to-plate distance)    [Statcast]
const FLIGHT_M  = FLIGHT_FT * FT;

// ===========================================================================
// 2.  The force model  (accelerations, per unit mass)
// ===========================================================================
// Coordinates:  x toward the plate, y up, z to the catcher's right.
// Drag:   a = -(rho*A*C_D / 2m) |v| v            (opposes velocity)
// Magnus: a =  (rho*A*C_L / 2m) |v|^2 (w_hat x v_hat)
//         with |a_M| = (rho*A*C_L/2m)|v|^2 and direction the unit spin axis
//         crossed into the unit velocity.  For pure backspin (spin axis to the
//         catcher's right, +z) crossed into forward motion (+x): +y, i.e. up.
function accel(v, spinAxis, omega, rho) {
  const speed = Math.hypot(v[0], v[1], v[2]);
  if (speed === 0) return [0, -g, 0];
  const S = (R * omega) / speed;                 // spin factor
  const CL = omega > 0 ? cLift(S) : 0;
  const rpm = omega * 60 / (2 * Math.PI);
  // drag (spin-dependent; a spinless ball still drags at C_D≈0.297)
  const kD = (rho * A * cDrag(rpm)) / (2 * m);
  const ad = [-kD * speed * v[0], -kD * speed * v[1], -kD * speed * v[2]];
  // magnus:  direction = wHat x vHat
  const vh = [v[0] / speed, v[1] / speed, v[2] / speed];
  const cx = spinAxis[1] * vh[2] - spinAxis[2] * vh[1];
  const cy = spinAxis[2] * vh[0] - spinAxis[0] * vh[2];
  const cz = spinAxis[0] * vh[1] - spinAxis[1] * vh[0];
  const cmag = Math.hypot(cx, cy, cz) || 1;      // |wHat x vHat| (unit axes -> sin angle)
  const kM = (rho * A * CL) / (2 * m) * speed * speed;
  const am = [kM * cx / cmag, kM * cy / cmag, kM * cz / cmag];
  return [ad[0] + am[0], ad[1] + am[1] - g, ad[2] + am[2]];
}

// RK4 integrate until the ball has travelled FLIGHT_M in +x (crosses the plate).
// Returns {drop_m, lateral_m, t, vEnd} where drop is downward-positive.
function fly({ mph, rpm, tiltDeg = 0, rho = RHO_SEA, y0 = 1.8 }) {
  const v0 = mph * 0.44704;                       // mph -> m/s
  const omega = (rpm * 2 * Math.PI) / 60;         // rpm -> rad/s
  // Launch HORIZONTALLY.  This makes "does it ever rise?" a clean question —
  // the ball rises only if Magnus lift beats gravity — and the spin-vs-no-spin
  // breaks are launch-angle-independent to first order anyway, so reporting
  // relative to a horizontal release keeps the model honest and unambiguous.
  let r = [0, y0, 0];
  let v = [v0, 0, 0];
  // Spin axis in the y-z plane: tilt=0 => pure backspin (+z), 90 => sidespin.
  const t = tiltDeg * Math.PI / 180;
  const spinAxis = [0, Math.sin(t), Math.cos(t)]; // unit
  const dt = 0.0002;
  let time = 0;
  const step = (rr, vv) => {
    const a = accel(vv, spinAxis, omega, rho);
    return { dr: vv, dv: a };
  };
  while (r[0] < FLIGHT_M && time < 2) {
    const k1 = step(r, v);
    const r2 = r.map((x, i) => x + k1.dr[i] * dt / 2);
    const v2 = v.map((x, i) => x + k1.dv[i] * dt / 2);
    const k2 = step(r2, v2);
    const r3 = r.map((x, i) => x + k2.dr[i] * dt / 2);
    const v3 = v.map((x, i) => x + k2.dv[i] * dt / 2);
    const k3 = step(r3, v3);
    const r4 = r.map((x, i) => x + k3.dr[i] * dt);
    const v4 = v.map((x, i) => x + k3.dv[i] * dt);
    const k4 = step(r4, v4);
    r = r.map((x, i) => x + (k1.dr[i] + 2 * k2.dr[i] + 2 * k3.dr[i] + k4.dr[i]) * dt / 6);
    v = v.map((x, i) => x + (k1.dv[i] + 2 * k2.dv[i] + 2 * k3.dv[i] + k4.dv[i]) * dt / 6);
    time += dt;
  }
  return {
    y: r[1], z: r[2], t: time,
    riseDrop_m: y0 - r[1],     // downward-positive vertical displacement
    lateral_m: r[2],
    vEnd_mph: Math.hypot(v[0], v[1], v[2]) / 0.44704,
    maxY: r[1],
  };
}

const M2IN = 39.3701;
const pass = [];
const check = (name, got, lo, hi, unit = '') => {
  const ok = got >= lo && got <= hi;
  pass.push(ok);
  console.log(
    `  ${ok ? 'ok  ' : 'FAIL'} ${name.padEnd(46)} ${got.toFixed(2).padStart(8)} ${unit}   [${lo}, ${hi}]`
  );
};

console.log('\nBaseball, from the regulation ranges:');
console.log(`  mass    = ${(m * 1000).toFixed(1)} g   (${massOz} oz)`);
console.log(`  circum  = ${(circ * 100).toFixed(2)} cm  (${circIn} in)`);
console.log(`  radius  = ${(R * 1000).toFixed(2)} mm`);
console.log(`  area A  = ${(A * 1e4).toFixed(2)} cm^2`);

// ===========================================================================
// 0.  Primary-source anchor: the lift model must reproduce Nathan's value
// ===========================================================================
console.log('\n[0] Lift & drag models vs the papers');
// Nathan's rational fit must reproduce his stated calculator outputs:
check('C_L at S=0.215 (Nathan calc: 0.222)', cLift(0.215), 0.218, 0.226, '');
check('C_L at S=0.281 (Nathan calc: 0.254)', cLift(0.281), 0.250, 0.258, '');
// and the independent SHS fit must agree with it to ~0.01 across the range:
check('rational vs SHS agree at S=0.2', Math.abs(cLift(0.2) - cLiftSHS(0.2)), 0, 0.012, '');
check('rational vs SHS agree at S=0.28', Math.abs(cLift(0.28) - cLiftSHS(0.28)), 0, 0.012, '');
// SHS's own anchor: C_L(0.2)=0.21 verbatim in Nathan 2008:
check('SHS C_L at S=0.2 (paper states 0.21)', cLiftSHS(0.2), 0.209, 0.211, '');
// drag at a fastball's spin:
check('C_D at 2300 rpm (Nathan fit ~0.36)', cDrag(2300), 0.35, 0.37, '');

// ===========================================================================
// 3.  Induced vertical break — fastball  (spin vs no-spin, same everything)
// ===========================================================================
// IVB = drop of a spinless ball minus drop of the real ball, at the plate
// (gravity removed).  The instrument models an IDEALISED pitch: 100% of the
// spin is useful backspin.  Statcast's 2024 numbers: four-seam LEAGUE AVERAGE
// +16 in, ELITE "ride" fastballs +20-21 in.  A perfect 95 mph / 2300 rpm
// backspinner should land at the elite end (~18-22 in), and it does — real
// pitches fall below only because they lose spin to gyro and average slower.
console.log('\n[1] 4-seam fastball: 95 mph, 2300 rpm, 100% backspin (idealised)');
{
  const spun   = fly({ mph: 95, rpm: 2300, tiltDeg: 0 });
  const spinless = fly({ mph: 95, rpm: 0, tiltDeg: 0 });
  const ivb_in = (spinless.riseDrop_m - spun.riseDrop_m) * M2IN;
  console.log(`     spinless drops ${(spinless.riseDrop_m * M2IN).toFixed(1)} in; with backspin ${(spun.riseDrop_m * M2IN).toFixed(1)} in`);
  check('fastball IVB (elite range, 18-22 in)', ivb_in, 17, 23, 'in');
  check('fastball still net DROPS (never rises)', spun.riseDrop_m * M2IN, 0.5, 30, 'in');
  check('flight time', spun.t, 0.36, 0.46, 's');
  check('speed lost to drag at plate', 95 - spun.vEnd_mph, 5, 12, 'mph');
}

// ===========================================================================
// 4.  The curveball — topspin adds drop
// ===========================================================================
console.log('\n[2] 12-6 curveball: 78 mph, 2500 rpm pure topspin');
{
  const curve    = fly({ mph: 78, rpm: 2500, tiltDeg: 180 });  // spin axis -> down Magnus
  const spinless = fly({ mph: 78, rpm: 0, tiltDeg: 0 });
  const extra_in = (curve.riseDrop_m - spinless.riseDrop_m) * M2IN;
  console.log(`     spinless drops ${(spinless.riseDrop_m * M2IN).toFixed(1)} in; with topspin ${(curve.riseDrop_m * M2IN).toFixed(1)} in`);
  check('curveball EXTRA drop from topspin', extra_in, 18, 32, 'in');
  check('curveball total drop', curve.riseDrop_m * M2IN, 40, 90, 'in');
}

// ===========================================================================
// 5.  The rising fastball — the honest threshold
// ===========================================================================
// A ball literally rises only if, somewhere in flight, Magnus lift exceeds
// gravity: (rho*A*C_L/2)|v|^2 > m g.  Solve at release speed for the spin.
console.log('\n[3] The rising fastball: what spin would it take?');
{
  const v = 95 * 0.44704;
  // need C_L* such that (rho*A*C_L/2) v^2 = m g
  const CLstar = (2 * m * g) / (RHO_SEA * A * v * v);
  // invert the rational fit  C_L = 1.120 S / (0.583 + 2.333 S)
  //   ->  S = 0.583 C_L / (1.120 - 2.333 C_L)
  const Sstar = (0.583 * CLstar) / (1.120 - 2.333 * CLstar);
  const omegaStar = (Sstar * v) / R;              // rad/s
  const rpmStar = omegaStar * 60 / (2 * Math.PI);
  console.log(`     Magnus = gravity needs C_L = ${CLstar.toFixed(3)}, S = ${Sstar.toFixed(3)}`);
  console.log(`     -> ${rpmStar.toFixed(0)} rpm at 95 mph just to FLOAT (lift = weight)`);
  // Nathan's rational fit gives ~4700 rpm at 95 mph (research-confirmed);
  // Adair's model ~3600; the literature spread is real and honest.
  check('float-threshold spin at 95 mph', rpmStar, 4200, 5200, 'rpm');
  // MLB fastball spin tops out ~2600-3000 rpm; confirm the model never rises there.
  const hot = fly({ mph: 95, rpm: 2900, tiltDeg: 0 });
  check('even a 2900 rpm heater still net drops', hot.riseDrop_m * M2IN, 0.1, 30, 'in');
}

// ===========================================================================
// 6.  Altitude — Coors Field carries less break
// ===========================================================================
console.log('\n[4] Thin air (Denver) reduces break');
{
  const sea = fly({ mph: 95, rpm: 2300, tiltDeg: 0 });
  const den = fly({ mph: 95, rpm: 2300, tiltDeg: 0, rho: RHO_DENVER });
  const ivbSea = (fly({ mph: 95, rpm: 0 }).riseDrop_m - sea.riseDrop_m) * M2IN;
  const ivbDen = (fly({ mph: 95, rpm: 0, rho: RHO_DENVER }).riseDrop_m - den.riseDrop_m) * M2IN;
  console.log(`     IVB sea-level ${ivbSea.toFixed(1)} in  ->  Denver ${ivbDen.toFixed(1)} in`);
  check('Denver break is smaller than sea-level break', ivbSea - ivbDen, 0.5, 8, 'in');
}

// ===========================================================================
// 7.  Numerical self-check — the RK4 result must be converged, not an artefact
// ===========================================================================
// Re-integrate the fastball at dt and dt/4; a correct RK4 solution changes by
// far less than the physics we report (require < 0.05 in of drift).
console.log('\n[5] Integration is converged (dt vs dt/4)');
{
  const flyDt = (dt) => {
    const v0 = 95 * 0.44704, omega = 2300 * 2 * Math.PI / 60;
    let r = [0, 1.8, 0], v = [v0, 0, 0];
    const axis = [0, 0, 1];
    const st = (rr, vv) => ({ dr: vv, dv: accel(vv, axis, omega, RHO_SEA) });
    let t = 0;
    while (r[0] < FLIGHT_M && t < 2) {
      const k1 = st(r, v);
      const k2 = st(r.map((x, i) => x + k1.dr[i] * dt / 2), v.map((x, i) => x + k1.dv[i] * dt / 2));
      const k3 = st(r.map((x, i) => x + k2.dr[i] * dt / 2), v.map((x, i) => x + k2.dv[i] * dt / 2));
      const k4 = st(r.map((x, i) => x + k3.dr[i] * dt), v.map((x, i) => x + k3.dv[i] * dt));
      r = r.map((x, i) => x + (k1.dr[i] + 2 * k2.dr[i] + 2 * k3.dr[i] + k4.dr[i]) * dt / 6);
      v = v.map((x, i) => x + (k1.dv[i] + 2 * k2.dv[i] + 2 * k3.dv[i] + k4.dv[i]) * dt / 6);
      t += dt;
    }
    return r[1];
  };
  const drift_in = Math.abs(flyDt(0.0002) - flyDt(0.00005)) * M2IN;
  check('drop drift dt→dt/4 (numerically converged)', drift_in, 0, 0.05, 'in');
}

// ===========================================================================
console.log('\n' + '='.repeat(64));
const allOk = pass.every(Boolean);
console.log(allOk
  ? `ALL ${pass.length} CHECKS PASS`
  : `FAILED ${pass.filter(x => !x).length} / ${pass.length}`);
process.exit(allOk ? 0 : 1);
