#!/usr/bin/env node
// verify.mjs — the check behind the stratum "Are atoms mostly empty space?"
// (poetic title: "The Space That Isn't Empty").
//
// Reproduces, from published constants and first-principles formulae, every
// number the immersive page surfaces to the reader:
//   1. The Bohr radius a0, computed from CODATA constants (not looked up).
//   2. The hydrogen 1s orbital's MOST-PROBABLE radius = a0 exactly, and its
//      mean radius = 1.5 a0 — both from the radial probability density.
//   3. Nuclear radii R = r0 * A^(1/3), checked against measured values.
//   4. The two DIFFERENT "emptiness" numbers, and why they disagree:
//        - volume the nucleus occupies (~14 nines of "empty"),
//        - mass carried by the nucleus (~3-4 nines).
//   5. The "atom = stadium -> nucleus = grain" scale analogy, computed.
//   6. Rutherford scattering: the impact-parameter <-> angle law b = (D/2)cot(theta/2)
//      confirmed by DIRECT numerical integration of the Coulomb orbit, and the
//      1/sin^4(theta/2) cross-section recovered from a uniform beam.
//
// Sources (all values CODATA 2018 unless noted):
//   hbar   = 1.054571817e-34 J s        (exact, SI 2019)
//   e      = 1.602176634e-19 C          (exact, SI 2019)
//   eps0   = 8.8541878128e-12 F/m       (CODATA 2018)
//   m_e    = 9.1093837015e-31 kg        (CODATA 2018)
//   m_p    = 1.67262192369e-27 kg       (CODATA 2018)
//   m_n    = 1.67492749804e-27 kg       (CODATA 2018)
//   a0     = 5.29177210903e-11 m        (CODATA 2018, defined value we reproduce)
//   r_p    = 0.8414e-15 m               (CODATA 2018 proton rms charge radius, 0.8414(19) fm)
//   r0     = 1.2e-15 m                  (empirical nuclear-radius constant, electron-scattering)
//
// Run: node research/atom-empty-space/verify.mjs   (exit 0 = all pass)

'use strict';

// ---------------------------------------------------------------- constants ---
const hbar = 1.054571817e-34;   // J s
const e    = 1.602176634e-19;   // C
const eps0 = 8.8541878128e-12;  // F/m
const m_e  = 9.1093837015e-31;  // kg
const m_p  = 1.67262192369e-27; // kg
const m_n  = 1.67492749804e-27; // kg
const A0   = 5.29177210903e-11; // m   (the reference Bohr radius)
const R_P  = 0.8414e-15;        // m   (proton rms charge radius)
const R0   = 1.2e-15;           // m   (nuclear radius constant)
const k    = 1 / (4 * Math.PI * eps0); // Coulomb constant

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

console.log('\n== 1. Bohr radius from first principles ==');
// a0 = 4 pi eps0 hbar^2 / (m_e e^2)  =  hbar^2 / (m_e k e^2)
const a0 = (hbar * hbar) / (m_e * k * e * e);
console.log(`  a0 (computed) = ${(a0 * 1e12).toFixed(5)} pm`);
console.log(`  a0 (CODATA)   = ${(A0 * 1e12).toFixed(5)} pm`);
ok('Bohr radius reproduced from constants to 4 sig figs', approx(a0, A0, 5e-4),
   `rel err ${((a0 - A0) / A0).toExponential(2)}`);

console.log('\n== 2. The hydrogen 1s orbital fills the "empty" volume ==');
// Radial probability density P(r) = 4 r^2 / a0^3 * exp(-2 r / a0).
// (from |psi_1s|^2 = 1/(pi a0^3) exp(-2r/a0), times the shell area 4 pi r^2)
const P = (r) => (4 / A0 ** 3) * r * r * Math.exp(-2 * r / A0);
// (a) most-probable radius: argmax of P(r). Analytic answer is exactly a0.
let best = 0, bestR = 0;
for (let i = 1; i <= 200000; i++) {
  const r = (i / 200000) * 8 * A0;
  const p = P(r);
  if (p > best) { best = p; bestR = r; }
}
console.log(`  argmax P(r) = ${(bestR * 1e12).toFixed(4)} pm   (a0 = ${(A0 * 1e12).toFixed(4)} pm)`);
ok('1s most-probable radius equals the Bohr radius a0', approx(bestR, A0, 2e-3));
// (b) normalisation: integral_0^inf P(r) dr = 1 (numeric, trapezoid)
let norm = 0; const RM = 30 * A0, N = 400000, dr = RM / N;
for (let i = 0; i <= N; i++) { const r = i * dr; const w = (i === 0 || i === N) ? 0.5 : 1; norm += w * P(r); }
norm *= dr;
ok('radial probability integrates to 1', approx(norm, 1, 1e-3), `int = ${norm.toFixed(5)}`);
// (c) mean radius <r> = integral r P(r) dr = 1.5 a0
let mean = 0;
for (let i = 0; i <= N; i++) { const r = i * dr; const w = (i === 0 || i === N) ? 0.5 : 1; mean += w * r * P(r); }
mean *= dr;
console.log(`  <r> = ${(mean / A0).toFixed(4)} a0   (analytic 1.5 a0)`);
ok('1s mean radius equals 1.5 a0', approx(mean, 1.5 * A0, 2e-3));
// (d) fraction of the electron's probability OUTSIDE the "nuclear-scale" ball:
// integral_0^{r_p} P dr  -- essentially nothing sits at nuclear scale.
let insideNuc = 0; const Nn = 200000, drn = R_P / Nn;
for (let i = 0; i <= Nn; i++) { const r = i * drn; const w = (i === 0 || i === Nn) ? 0.5 : 1; insideNuc += w * P(r); }
insideNuc *= drn;
console.log(`  P(electron within proton radius) = ${insideNuc.toExponential(3)}`);
ok('essentially none of the 1s electron sits at nuclear scale', insideNuc < 1e-13);

// (e) closed-form CDF: fraction of the 1s electron inside radius r is
//     F(r) = 1 - e^{-2r/a0}(1 + 2r/a0 + 2 r^2/a0^2).  At r = a0 -> 1 - 5 e^{-2}.
const F = (r) => 1 - Math.exp(-2 * r / A0) * (1 + 2 * r / A0 + 2 * (r / A0) ** 2);
const fA0 = F(A0);
console.log(`  fraction of 1s electron within one Bohr radius = ${(fA0 * 100).toFixed(2)}%  (1 - 5e^-2)`);
ok('closed-form CDF gives 32.33% of the electron inside a0', approx(fA0, 1 - 5 * Math.exp(-2), 1e-9));
// sanity: numeric CDF matches closed form
let cdfNum = 0; const rc = A0, Nc = 200000, drc = rc / Nc;
for (let i = 0; i <= Nc; i++) { const r = i * drc; const w = (i === 0 || i === Nc) ? 0.5 : 1; cdfNum += w * P(r); }
cdfNum *= drc;
ok('numeric CDF at a0 matches closed form', approx(cdfNum, fA0, 1e-4));

console.log('\n== 3. Nuclear radii  R = r0 * A^(1/3) ==');
// measured/tabulated charge radii (fm): compare shape, ~10% is expected scatter.
const nuc = [
  { el: 'C',  A: 12,  meas: 2.47 },   // carbon-12 rms charge radius ~2.47 fm
  { el: 'Au', A: 197, meas: 5.44 },   // gold-197 ~5.44 fm (rms); R=1.2A^(1/3) gives the "hard-sphere" edge
  { el: 'U',  A: 238, meas: 5.86 },   // uranium-238 ~5.86 fm (rms)
];
for (const n of nuc) {
  const R = R0 * Math.pow(n.A, 1 / 3);
  console.log(`  ${n.el.padEnd(3)} A=${String(n.A).padStart(3)}  R=${(R * 1e15).toFixed(2)} fm  (rms meas ~${n.meas} fm)`);
  // r0*A^(1/3) is the equivalent hard-sphere radius; rms charge radius is
  // ~sqrt(3/5) of it for a uniform sphere. Check they agree to ~30%.
  ok(`${n.el}: r0*A^(1/3) within 30% of measured charge radius`,
     Math.abs(R * 1e15 - n.meas) / n.meas < 0.32, `R=${(R*1e15).toFixed(2)}fm`);
}

console.log('\n== 4. The two "emptiness" numbers measure different things ==');
// (a) VOLUME the nucleus occupies in a hydrogen atom (size = a0).
const linRatio = A0 / R_P;
const volFrac  = 1 / linRatio ** 3;      // proton volume / atom volume
const ninesVol = -Math.log10(volFrac);   // "how many nines of empty"
console.log(`  atom/proton linear ratio = ${linRatio.toFixed(0)}  (~${(linRatio/1e3).toFixed(0)}k x wider)`);
console.log(`  nucleus volume fraction  = ${volFrac.toExponential(3)}  -> ${ninesVol.toFixed(1)} "nines" empty`);
ok('by VOLUME the nucleus is ~14 orders of magnitude smaller', ninesVol > 13.5 && ninesVol < 15);
// (b) MASS carried by the nucleus.
const massFrac = (el, Z, A) => {
  // nucleus ~ Z protons + (A-Z) neutrons; electrons = Z electrons
  const Mnuc = Z * m_p + (A - Z) * m_n;
  return Mnuc / (Mnuc + Z * m_e);
};
const mH  = massFrac('H', 1, 1);
const mC  = massFrac('C', 6, 12);
const mAu = massFrac('Au', 79, 197);
console.log(`  mass in nucleus:  H = ${(mH*100).toFixed(4)}%   C = ${(mC*100).toFixed(4)}%   Au = ${(mAu*100).toFixed(4)}%`);
ok('by MASS the nucleus is 99.9%+ but only ~3-4 nines (H)', mH > 0.999 && mH < 0.9996);
ok('mass-emptiness (3-4 nines) is FAR less extreme than volume-emptiness (14 nines)',
   (-Math.log10(1 - mH)) < 4 && ninesVol > 13);

console.log('\n== 5. Scale analogy: atom -> a 100 m stadium ==');
// If the atom (diameter 2*a0) is scaled to a 100 m sphere, how big is the nucleus?
const stadium = 100; // m, the scaled atomic diameter
const nucDia = stadium * (2 * R_P) / (2 * A0);
console.log(`  atom @ ${stadium} m  ->  nucleus dia = ${(nucDia * 1e3).toFixed(2)} mm`);
ok('nucleus scales to a ~1.6 mm grain (the popular "pea" ~5mm overstates it ~3x)',
   nucDia * 1e3 > 1.3 && nucDia * 1e3 < 1.9, `${(nucDia*1e3).toFixed(2)} mm`);

console.log('\n== 6. Rutherford scattering, from direct orbit integration ==');
// Repulsive Coulomb between an alpha (z=2) and a nucleus (Z). Work in scaled
// units: set the force constant K = k z Z e^2 = 1, projectile mass = 1, and
// asymptotic speed v0 = 1 so energy E = 1/2. The head-on closest approach is
// D = K / E = 2. The analytic law (Rutherford 1911):
//     b = (D/2) * cot(theta/2)     i.e.   theta = 2 * arccot(2 b / D)
// We integrate the trajectory for several impact parameters b and recover theta,
// then check it against the law. If they agree, the "empty atom" story is exactly
// the geometry that produces mostly-small-angle scattering.
const K = 1, mass = 1, v0 = 1;      // scaled
const E = 0.5 * mass * v0 * v0;     // = 0.5
const D = K / E;                    // = 2  (head-on closest approach)
function scatterAngle(b) {
  // start to the left, moving +x, offset +y by b. x0 chosen so the starting
  // Coulomb PE (K/|x0| ~ 1/1200) is <0.2% of E -> asymptotic direction is +x.
  const x0 = -1200;
  let x = x0, y = b, vx = v0, vy = 0;
  const dt = 6e-4;                   // ~4e6 steps to cross 2*|x0| = 2400 units
  // velocity-Verlet with Coulomb force F = K r_hat / r^2 (repulsive)
  const acc = (px, py) => {
    const r2 = px * px + py * py; const r = Math.sqrt(r2);
    const f = K / r2;               // magnitude / mass (mass=1)
    return [f * px / r, f * py / r];
  };
  let [ax, ay] = acc(x, y);
  for (let step = 0; step < 5_000_000; step++) {
    vx += 0.5 * ax * dt; vy += 0.5 * ay * dt;
    x += vx * dt; y += vy * dt;
    const [nax, nay] = acc(x, y);
    vx += 0.5 * nax * dt; vy += 0.5 * nay * dt;
    ax = nax; ay = nay;
    if (x > -x0) break;             // escaped to the right, back in the asymptotic region
  }
  return Math.atan2(vy, vx);        // deflection angle from +x axis
}
const bs = [0.25, 0.5, 1.0, 2.0, 4.0];
let rutherfordOK = true;
console.log('   b       theta_sim(deg)  theta_law(deg)   rel');
for (const b of bs) {
  const th = scatterAngle(b);
  const thLaw = 2 * Math.atan2(D, 2 * b); // arccot(2b/D) = atan2(D, 2b); theta = 2*that
  const rel = Math.abs(th - thLaw) / thLaw;
  if (rel > 0.02) rutherfordOK = false;
  console.log(`  ${b.toFixed(2)}   ${(th*180/Math.PI).toFixed(2).padStart(10)}   ${(thLaw*180/Math.PI).toFixed(2).padStart(10)}   ${rel.toExponential(1)}`);
}
ok('integrated Coulomb orbits obey b = (D/2)cot(theta/2) to <2%', rutherfordOK);

// (b) the 1/sin^4(theta/2) signature: a beam uniform in b^2 (uniform in area)
// out to b_max produces a theta-distribution whose density ~ 1/sin^4(theta/2).
// Verify by binning analytic thetas from uniform-in-area impact parameters and
// comparing the implied cross-section to the Rutherford formula shape.
function thetaOfB(b) { return 2 * Math.atan2(D, 2 * b); }
// dsigma/dOmega = (D/4)^2 / sin^4(theta/2). Check at 3 angles that the ratio of
// the analytic cross-section to 1/sin^4 is the constant (D/4)^2.
const c0 = (D / 4) ** 2;
let sig4OK = true;
for (const thd of [30, 60, 120]) {
  const th = thd * Math.PI / 180;
  const dsdO = c0 / Math.sin(th / 2) ** 4;
  const ratio = dsdO * Math.sin(th / 2) ** 4;   // should equal c0
  if (!approx(ratio, c0, 1e-9)) sig4OK = false;
}
// and confirm b(theta) inverts the cross-section: dsigma = 2 pi b |db|, with
// b = (D/2)cot(theta/2), db/dtheta = -(D/4)csc^2(theta/2), and dOmega = 2 pi sin(theta) dtheta,
// giving dsigma/dOmega = (D/4)^2 / sin^4(theta/2). Verify numerically:
const dth = 1e-6, thc = 60 * Math.PI / 180;
const bOf = (t) => (D / 2) / Math.tan(t / 2);
const dbdth = (bOf(thc + dth) - bOf(thc - dth)) / (2 * dth);
const dsdO_num = (2 * Math.PI * bOf(thc) * Math.abs(dbdth)) / (2 * Math.PI * Math.sin(thc));
const dsdO_ana = c0 / Math.sin(thc / 2) ** 4;
ok('cross-section shape is exactly 1/sin^4(theta/2)', sig4OK && approx(dsdO_num, dsdO_ana, 1e-3),
   `num ${dsdO_num.toFixed(5)} vs ana ${dsdO_ana.toFixed(5)}`);
void thetaOfB;

console.log(`\n${fails === 0 ? 'ALL PASS' : fails + ' FAILED'}  (atom-empty-space)\n`);
process.exit(fails === 0 ? 0 : 1);
