#!/usr/bin/env node
// Verification for the stratum "Smoother Than a Billiard Ball".
//
// The viral claim (an old urban legend, tested by Phil Plait, "Ten Things You
// Don't Know About the Earth," Discover/Bad Astronomy, 2008, who added
// "...but not round enough"): if the Earth were shrunk to the size of a
// regulation billiard ball, it would be SMOOTHER than one. This stratum's
// claim is that BOTH adjectives are swapped, and the error is a single
// category mistake — reading the ball's only shape spec, a tolerance on
// its DIAMETER, as if it were a spec on its surface FINISH.
//
//   * The 0.005 in is a diameter (size/roundness) tolerance. The WPA prints it
//     "(+.005)", with no minus; the BCA has given it as +or- .005, and it is read
//     as ± here. Apply it to the thing it actually bounds (Earth's
//     out-of-roundness, the equatorial bulge) and, on the ± reading, the Earth
//     PASSES: it is round enough to be a regulation ball. Read as printed
//     (0.005 in), the bulge is about 50% over and the Earth fails.
//   * The ball's surface FINISH is a different, finer quantity. A polished
//     phenolic ball's roughness is sub-micron; Earth's relief, scaled down, is
//     a ~0.09 mm span, summit to trench: about 100× the 0.86 µm peak-to-valley
//     range measured on a new ball (and about 3,000× its average roughness Ra,
//     which sets an extreme against an average). Earth is NOT smooth enough at
//     its extremes, though patch for patch much of it would be smoother.
//
// So: round, yes; smooth, no — the opposite of the slogan.
//
// Everything the page asserts numerically is recomputed here from published
// constants. Run: node research/smoother-than-a-billiard-ball/verify.mjs
// (exit 0 = all pass).

let pass = 0, fail = 0;
const rel = (got, want) => Math.abs(got - want) / Math.abs(want);
function eq(name, got, want, tol = 0, unit = '') {
  // tol is a RELATIVE tolerance unless want === 0 (then absolute).
  const ok = want === 0 ? Math.abs(got) <= tol : rel(got, want) <= tol;
  const g = typeof got === 'number' ? (Math.abs(got) >= 1000 ? got.toLocaleString('en-US', { maximumFractionDigits: 3 }) : got.toPrecision(6)) : got;
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}\n        got ${g}${unit}${ok ? '' : `  want ≈ ${want}${unit} (±${tol === 0 ? 0 : (tol * 100) + '%'})`}`);
  ok ? pass++ : fail++;
}
function note(s) { console.log(`        · ${s}`); }

// ---------------------------------------------------------------------------
// 0.  PUBLISHED CONSTANTS — every figure below is derived only from these.
// ---------------------------------------------------------------------------
// WGS84 reference ellipsoid (NIMA TR8350.2; the GPS datum).
const A = 6378137.0;              // semi-major axis (equatorial radius), metres — defining constant
const INV_F = 298.257223563;     // inverse flattening 1/f — defining constant
const F = 1 / INV_F;             // flattening
const B = A * (1 - F);           // semi-minor axis (polar radius), metres — derived

// Relief extremes (surface highest above / lowest below sea level).
const EVEREST = 8848.86;          // m — China–Nepal joint survey, announced 2020-12-08
const CHALLENGER = 10935;         // m — Greenaway et al. 2021, Deep-Sea Research I 178:103644 (10,935 ± 6 m)

// Regulation billiard (pool) ball — WPA Equipment Specifications.
const BALL_IN = 2.25;             // inches, nominal diameter (2¼")
const BALL_TOL_IN = 0.005;        // inches, the diameter tolerance: printed "(+.005)" by the WPA (§16), read here as ± (BCA)
const IN_MM = 25.4;               // exact: 1 inch = 25.4 mm
const BALL_MM = BALL_IN * IN_MM;  // 57.15 mm
const BALL_TOL_MM = BALL_TOL_IN * IN_MM; // 0.127 mm

// Aramith (Saluc), "General specifications": "Surface rugosity : average Ra = 0.03 microns".
const BALL_RA_UM = 0.03;          // micrometres, manufacturer figure (NOT a WPA requirement); an AVERAGE (Ra)
// Measured peak-to-valley on a 1 x 1 mm patch of a new Aramith cue ball:
// +0.32 to -0.54 µm (Alciatore, "Is a Pool Ball Smoother Than the Earth?",
// Billiards Digest, June 2013). An EXTREME, like Earth's summit-to-trench relief.
const BALL_PV_UM = 0.32 + 0.54;   // micrometres
// Aramith "General specifications": sphericity / roundness max 0.002
// (high end grade max 0.0012), in inches like its diameters.
const BALL_SPHERICITY_IN = 0.002;
const BALL_SPHERICITY_TOP_IN = 0.0012;

console.log('\n=== I.  WGS84 — the Earth is an ellipsoid, not a sphere ===\n');
eq('polar radius b = a(1-f)', B, 6356752.314245, 1e-9, ' m');
const D_EQ = 2 * A;               // equatorial diameter
const D_POL = 2 * B;              // polar diameter
eq('equatorial diameter 2a', D_EQ, 12756274, 1e-7, ' m');
eq('polar diameter 2b', D_POL, 12713504.629, 1e-7, ' m');
const OUT_OF_ROUND = D_EQ - D_POL; // the bulge, as a diameter difference
eq('out-of-roundness (equatorial − polar diameter)', OUT_OF_ROUND, 42769.37, 1e-4, ' m');
note(`= ${(OUT_OF_ROUND / 1000).toFixed(2)} km — the equatorial bulge, the single biggest way Earth departs from a sphere`);
// Mean radius (IUGG arithmetic mean R1 = (2a+b)/3), used only for context.
const R_MEAN = (2 * A + B) / 3;
eq('mean radius R1=(2a+b)/3', R_MEAN, 6371008.77, 1e-6, ' m');
// The same bulge as a RADIUS difference (the like-for-like basis for relief).
eq('equatorial − polar radius a − b', A - B, 21384.69, 1e-6, ' m');

console.log('\n=== II.  RELIEF — top of Everest to bottom of Challenger Deep ===\n');
const RELIEF = EVEREST + CHALLENGER;
eq('total relief = Everest + Challenger Deep', RELIEF, 19783.86, 1e-9, ' m');
note(`= ${(RELIEF / 1000).toFixed(2)} km, on a planet ${(R_MEAN / 1000).toFixed(0)} km in radius`);
// Relief as a fraction of the DIAMETER (the apples-to-apples basis for scaling).
const RELIEF_FRAC = RELIEF / D_EQ;
eq('relief / equatorial diameter', RELIEF_FRAC, 0.001551, 0.001, '');
note(`one part in ${(1 / RELIEF_FRAC).toFixed(0)} of the diameter`);
// Radius for radius, relief is nearly as large as the bulge: NOT "almost nothing".
eq('relief / (a − b), radius for radius', RELIEF / (A - B), 0.9251, 0.001, '');
note(`the bulge is the larger departure, but only just (relief ${(100 * RELIEF / (A - B)).toFixed(1)}% of a − b)`);

console.log('\n=== III.  THE BALL — what the WPA actually specifies ===\n');
eq('ball diameter 2¼"', BALL_MM, 57.15, 1e-9, ' mm');
eq('diameter tolerance .005" (WPA prints "(+.005)"; read as ±)', BALL_TOL_MM, 0.127, 1e-9, ' mm');
// On the ± reading, the full allowed diameter band a single ball's diameter may
// occupy is 2·tol (from −.005 to +.005), i.e. the maximum out-of-roundness the
// spec permits. Read as printed, "(+.005)", the band is 1·tol.
const BALL_BAND_MM = 2 * BALL_TOL_MM;
eq('full diameter band (2 × tol)', BALL_BAND_MM, 0.254, 1e-9, ' mm');

console.log('\n=== IV.  SCALE THE EARTH DOWN TO A CUE BALL ===\n');
// One scale factor, by diameter, applied to every Earth length.
const S = BALL_MM / D_EQ;          // mm of ball per metre of Earth
note(`scale factor = ${BALL_MM} mm / ${D_EQ.toLocaleString('en-US')} m = ${S.toExponential(4)} (mm per m)`);

// (a) ROUNDNESS: Earth's bulge, scaled, vs the ball's diameter band.
const BULGE_ON_BALL = OUT_OF_ROUND * S;     // mm
eq('Earth bulge on the cue ball', BULGE_ON_BALL, 0.19163, 0.001, ' mm');
note(`vs the spec's full diameter band ${BALL_BAND_MM.toFixed(3)} mm`);
const ROUND_PASS_FULLBAND = BULGE_ON_BALL <= BALL_BAND_MM;       // 0.254 mm
const ROUND_PASS_HALFBAND = BULGE_ON_BALL <= BALL_TOL_MM;        // 0.127 mm
eq('ROUND under full-band reading (bulge ≤ 0.254 mm)?', ROUND_PASS_FULLBAND ? 1 : 0, 1, 0);
note(`Earth's scaled bulge ${BULGE_ON_BALL.toFixed(3)} mm ≤ ${BALL_BAND_MM.toFixed(3)} mm → PASSES as round enough`);
eq('NOT round under half-band reading (bulge > 0.127 mm)?', ROUND_PASS_HALFBAND ? 0 : 1, 1, 0);
note(`the verdict flips on how you read the tolerance: as ±.005 (full band) or as printed, "(+.005)" (0.005 in); the spec is silent on roundness, so this axis is genuinely ambiguous`);
const ALLOWED_KM_LITERAL = (BALL_TOL_MM / BALL_MM) * (D_EQ / 1000);
eq('allowed bulge in km (literal "+.005", 0.005 in)', ALLOWED_KM_LITERAL, 28.347, 0.001, ' km');
eq('bulge ÷ literal allowance', BULGE_ON_BALL / BALL_TOL_MM, 1.5088, 0.001, '×');
note(`read as printed, Earth's bulge is ${((BULGE_ON_BALL / BALL_TOL_MM - 1) * 100).toFixed(0)}% over → NOT round enough`);
// Equivalent km figure the popular sources quote for the allowance.
const ALLOWED_KM_FULLBAND = (BALL_BAND_MM / BALL_MM) * (D_EQ / 1000);
eq('allowed bulge in km (full band)', ALLOWED_KM_FULLBAND, 56.69, 0.001, ' km');
note(`Earth's ${(OUT_OF_ROUND / 1000).toFixed(1)} km bulge < ${ALLOWED_KM_FULLBAND.toFixed(1)} km allowed → round enough`);

// (b) SMOOTHNESS: Earth's relief, scaled, vs the ball's actual finish.
const RELIEF_ON_BALL_MM = RELIEF * S;       // mm
const RELIEF_ON_BALL_UM = RELIEF_ON_BALL_MM * 1000; // micrometres
eq('Earth relief on the cue ball', RELIEF_ON_BALL_MM, 0.08864, 0.001, ' mm');
note(`= ${RELIEF_ON_BALL_UM.toFixed(1)} µm — a summit-to-trench span about the width of a human hair (~70 µm)`);
// The span is two separate features, thousands of km apart: no single point is 88.6 µm deep.
eq('Everest on the cue ball (up)', EVEREST * S * 1000, 39.644, 0.001, ' µm');
eq('Challenger Deep on the cue ball (down)', CHALLENGER * S * 1000, 48.990, 0.001, ' µm');
// The category mistake: relief (a bump height) is SMALLER than the diameter
// tolerance (a size band), which is the whole basis of the "smoother" slogan.
const SLOGAN_BASIS = RELIEF_ON_BALL_MM < BALL_TOL_MM;
eq('relief (0.089 mm) < diameter tolerance (0.127 mm)?  [the slogan\'s basis]', SLOGAN_BASIS ? 1 : 0, 1, 0);
note('TRUE — but it compares a surface BUMP to a SIZE tolerance: apples to oranges');
// Judged against an actual surface, extreme against extreme, Earth is far rougher.
const ROUGHER_THAN_PV = RELIEF_ON_BALL_UM / BALL_PV_UM;
eq('Earth scaled relief ÷ measured peak-to-valley of a new ball', ROUGHER_THAN_PV, 103.06, 0.001, '×');
note(`Earth's scaled extremes are ~${Math.round(ROUGHER_THAN_PV / 10) * 10}× a new ball's measured ${BALL_PV_UM.toFixed(2)} µm peak-to-valley → NOT smooth`);
// The page's former headline ratio, kept because the page still states it, and labelled
// for what it is: an EXTREME divided by an AVERAGE (Ra), so it is NOT a measure of how
// much rougher the Earth is. The like-for-like ratio is the ~100× above.
const EXTREME_OVER_RA = RELIEF_ON_BALL_UM / BALL_RA_UM;
eq('Earth scaled relief ÷ ball average roughness Ra (extreme ÷ average)', EXTREME_OVER_RA, 2955, 0.01, '×');
note(`~${Math.round(EXTREME_OVER_RA / 100) * 100}×, but Ra is an average: mixing parameters inflates the ratio ~${Math.round(EXTREME_OVER_RA / ROUGHER_THAN_PV)}×`);
// Patch for patch: a 1 x 1 mm patch of ball (Alciatore's scan) is ~140 x 140 miles of Earth.
const PATCH_MILES = (1 / BALL_MM) * (D_EQ / 1609.344);
eq('1 mm of ball, in miles of Earth', PATCH_MILES, 138.7, 0.002, ' mi');
note('patch for patch, much of the scaled Earth would be smoother than the ball (Alciatore 2013); the verdict rests on the extremes');

// (c) ROUNDNESS against a real ball (as smoothness is judged), not the rule.
const SPHERICITY_KM = (BALL_SPHERICITY_IN / BALL_IN) * (D_EQ / 1000);
const SPHERICITY_TOP_KM = (BALL_SPHERICITY_TOP_IN / BALL_IN) * (D_EQ / 1000);
eq('Aramith sphericity 0.002 in, at Earth scale', SPHERICITY_KM, 11.339, 0.001, ' km');
eq('Aramith high-end sphericity 0.0012 in, at Earth scale', SPHERICITY_TOP_KM, 6.803, 0.001, ' km');
note(`Earth's ${(OUT_OF_ROUND / 1000).toFixed(1)} km bulge is ${(OUT_OF_ROUND / 1000 / SPHERICITY_KM).toFixed(1)} to ${(OUT_OF_ROUND / 1000 / SPHERICITY_TOP_KM).toFixed(1)}× a real ball's sphericity limit → "round enough" is the rule's verdict, not a real ball's`);

console.log('\n=== V.  THE INVERSION, stated exactly ===\n');
note('Slogan:   "smoother than a billiard ball, but not round enough."');
note('Checked:  round enough (under the ± full-band reading); NOT smoother.');
note('Cause:    the only shape spec is a DIAMETER tolerance (.005", read as ±). Applied to');
note('          roundness, Earth passes. It sets no figure for FINISH; judged on finish, Earth fails.');
note('Honest edges: WPA gives no separate sphericity or roughness spec, so the roundness');
note('          axis is reading-dependent (± full band 0.254 mm vs printed "+.005" 0.127 mm), and');
note('          the finish figures (Aramith Ra ≈ 0.03 µm; 0.86 µm measured) are not a rule.');

console.log(`\n${fail === 0 ? '✅' : '❌'}  ${pass}/${pass + fail} checks passed.\n`);
process.exit(fail === 0 ? 0 : 1);
