#!/usr/bin/env node
// verify.mjs — the physics behind "Why does helium make your voice high?"
//
// The claim the page makes, in one line: helium does NOT raise the PITCH of your
// voice. The pitch (the fundamental F0) is set by how fast your vocal folds slap
// together, which is biomechanics — it barely moves. What helium changes is the
// FILTER: its resonances shift upward as sound travels faster in the gas.
// In the ideal model with fixed geometry, rigid walls and gas-independent ideal
// open ends, every resonance scales exactly with sound speed. Real-tract scaling
// is approximate. Pure helium's ideal-gas sound speed is about 2.9x that of air.
//
// This file checks ideal-gas and tube-model arithmetic. It does not test human
// physiology; source/filter independence is an explicit model assumption.
// Every number in the page's check table is printed here.
//
//   node research/helium-voice/verify.mjs          # run the checks
//   node research/helium-voice/verify.mjs --json    # emit the page's numbers as JSON
//
// No dependencies; pure arithmetic on textbook constants.

const R = 8.314462618;        // J/(mol·K), molar gas constant (CODATA)
const T0 = 273.15;            // K, 0 °C
const T20 = 293.15;           // K, 20 °C (room temperature, the page's default)

// --- the two gases, as ideal gases -----------------------------------------
// gamma = Cp/Cv = adiabatic index. Air is ~diatomic (Cv = 5/2 R, gamma = 7/5).
// Helium is monatomic (Cv = 3/2 R, gamma = 5/3). M = molar mass, kg/mol.
const AIR = { name: 'air',    gamma: 7 / 5, M: 0.0289647, Cv: 2.5 * R };
const HE  = { name: 'helium', gamma: 5 / 3, M: 0.00400260, Cv: 1.5 * R };

// Speed of sound in an ideal gas: c = sqrt(gamma * R * T / M).
const speedOfSound = (gas, T) => Math.sqrt((gas.gamma * R * T) / gas.M);

// Formant of an ideal rigid uniform tube, closed at one end and open at the other:
// quarter-wave resonances f_n = (2n-1) * c / (4L), n = 1, 2, 3, ...
// L ≈ 0.175 m is a typical adult-male vocal-tract length; the neutral "schwa" vowel.
const L = 0.175;
const formant = (c, n) => ((2 * n - 1) * c) / (4 * L);

// Speed of sound in an ideal-gas MIXTURE (mole fraction x of helium, rest air).
// The 80% and 60% presets are illustrative compositions, not measurements of
// balloon breaths. Actual tract compositions and formant shifts vary.
function mixSpeed(xHe, T) {
  const xAir = 1 - xHe;
  const M = xHe * HE.M + xAir * AIR.M;          // mean molar mass
  const Cv = xHe * HE.Cv + xAir * AIR.Cv;        // molar heat capacities are additive
  const Cp = Cv + R;                              // ideal-gas relation Cp = Cv + R
  const gamma = Cp / Cv;
  return Math.sqrt((gamma * R * T) / M);
}

// --- run the checks ---------------------------------------------------------
let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok  ' : 'FAIL  '}${name}${extra ? '   ' + extra : ''}`);
};
const near = (a, b, tol) => Math.abs(a - b) <= tol;

const cAir20 = speedOfSound(AIR, T20);
const cHe20 = speedOfSound(HE, T20);
const cAir0 = speedOfSound(AIR, T0);
const cHe0 = speedOfSound(HE, T0);

console.log('\n— speed of sound reproduces the textbook values —');
ok('c(air, 20°C) ≈ 343 m/s (published 343.2)', near(cAir20, 343.2, 1.0), `got ${cAir20.toFixed(1)}`);
ok('c(helium, 0°C) ≈ 972 m/s (published 972)', near(cHe0, 972, 4), `got ${cHe0.toFixed(1)}`);
ok('c(air, 0°C) ≈ 331 m/s (published 331.3)', near(cAir0, 331.3, 1.0), `got ${cAir0.toFixed(1)}`);
ok('c(helium, 20°C) ≈ 1007 m/s', near(cHe20, 1007, 4), `got ${cHe20.toFixed(1)}`);

const ratio20 = cHe20 / cAir20;
const ratio0 = cHe0 / cAir0;
console.log('\n— the helium/air speed ratio is set by gamma and M alone (T cancels) —');
// c_He/c_air = sqrt( (gamma_He / gamma_air) * (M_air / M_He) ), independent of T.
const ratioClosed = Math.sqrt((HE.gamma / AIR.gamma) * (AIR.M / HE.M));
ok('ratio(20°C) == ratio(0°C) (temperature cancels)', near(ratio20, ratio0, 1e-9), `${ratio20.toFixed(6)} vs ${ratio0.toFixed(6)}`);
ok('ratio == sqrt((γ_He/γ_air)(M_air/M_He)) closed form', near(ratio20, ratioClosed, 1e-9), `${ratio20.toFixed(4)}`);
ok('pure-helium speed ratio ≈ 2.94 (ideal-model resonance multiplier)', near(ratio20, 2.94, 0.02), `got ${ratio20.toFixed(3)}`);

console.log('\n— the neutral-vowel formants land on the textbook ~500/1500/2500 Hz —');
const fAir = [1, 2, 3].map((n) => formant(cAir20, n));
ok('air F1 ≈ 490 Hz', near(fAir[0], 490, 12), `got ${Math.round(fAir[0])}`);
ok('air F2 ≈ 1470 Hz', near(fAir[1], 1470, 30), `got ${Math.round(fAir[1])}`);
ok('air F3 ≈ 2450 Hz', near(fAir[2], 2450, 50), `got ${Math.round(fAir[2])}`);

console.log('\n- ideal rigid-cavity model: resonances scale with the sound-speed ratio -');
// For a uniform gas and fixed geometry, with rigid reflecting walls and ideal
// open-end conditions that do not change with the gas, the wave equation gives
// eigenfrequencies proportional to c. This is an ideal-boundary result, not a
// theorem about every linear cavity or a measurement of real vocal tracts.
// The uniform-tube formula has that scaling for all n; below we check F1-F3.
const fHe = [1, 2, 3].map((n) => formant(cHe20, n));
let allScale = true;
for (let n = 0; n < 3; n++) {
  if (!near(fHe[n] / fAir[n], ratio20, 1e-9)) allScale = false;
}
ok('ideal uniform tube: F_n(He)/F_n(air) == c-ratio for F1-F3', allScale, `e.g. F1: ${Math.round(fAir[0])}→${Math.round(fHe[0])} Hz`);

// A chosen two-section resonance function D(f,c), under ideal fixed boundaries.
// It is written in f/c, so D(f,c) = D(kf,kc) by construction. This check illustrates
// the model's homogeneity; it does not establish exact scaling for arbitrary
// cavities with gas-dependent or yielding boundaries.
const L1 = 0.09, L2 = 0.085; // an asymmetric tract, deliberately non-uniform
const Dfn = (f, c) => Math.tan((2 * Math.PI * f * L1) / c) * Math.tan((2 * Math.PI * f * L2) / c) - 1;
let homogeneous = true, tested = 0;
for (let i = 0; i < 400 && tested < 200; i++) {
  const f = 50 + ((i * 137.5) % 3000);       // deterministic spread, no RNG flakiness
  const k = 0.5 + ((i * 0.0173) % 3);         // any positive rescale
  const a = Dfn(f, cAir20), b = Dfn(k * f, k * cAir20);
  if (!isFinite(a) || !isFinite(b)) continue; // skip samples landing on a tan pole
  tested++;
  if (!near(a, b, 1e-9)) homogeneous = false;
}
ok('chosen two-section model: D(f,c)=D(kf,kc)', homogeneous && tested > 100,
  `homogeneity of this model only (${tested} samples)`);

console.log('\n- model assumption: the source pitch is independent of the gas -');
// The constant-true line records the source/filter assumption explicitly.
// It is not an empirical check of vocal-fold behavior or an independent test.
ok('model assumption (not a physiological test): source/filter are separable', true,
  'F0 is absent from the model formulas above');

console.log('\n- illustrative helium-air mixtures in the ideal model -');
const cMix80 = mixSpeed(0.80, T20);
const cMix60 = mixSpeed(0.60, T20);
ok('illustrative 80% helium / 20% air → ideal-model shift ≈ 1.9x', near(cMix80 / cAir20, 1.91, 0.05), `got ${(cMix80 / cAir20).toFixed(2)}x`);
ok('illustrative 60% helium / 40% air → ideal-model shift ≈ 1.5x', near(cMix60 / cAir20, 1.5, 0.05), `got ${(cMix60 / cAir20).toFixed(2)}x`);
ok('pure helium is the ceiling the mixture approaches', cMix80 / cAir20 < ratio20, `${(cMix80 / cAir20).toFixed(2)} < ${ratio20.toFixed(2)}`);

console.log('\n— sulfur hexafluoride (the heavy gas) does the OPPOSITE: formants DROP —');
// SF6: gamma ≈ 1.09 (polyatomic), M = 0.146 kg/mol. Heavy + soft → slow sound → low formants.
const SF6 = { gamma: 1.09, M: 0.146059 };
const cSF6 = speedOfSound(SF6, T20);
ok('c(SF6, 20°C) ≈ 134 m/s (published ~134)', near(cSF6, 134, 6), `got ${cSF6.toFixed(0)}`);
ok('SF6 lowers formants ~0.39x (the "demon voice")', near(cSF6 / cAir20, 0.39, 0.03), `got ${(cSF6 / cAir20).toFixed(2)}x`);

console.log(`\n${fails === 0 ? '✓ all checks passed' : '✗ ' + fails + ' check(s) FAILED'}`);

// --- the canonical numbers the page is allowed to print --------------------
const PAGE = {
  L_cm: L * 100,
  T_C: 20,
  c_air: round(cAir20),
  c_he: round(cHe20),
  ratio_pure: round2(ratio20),
  ratio_mix80: round2(cMix80 / cAir20),
  formants_air: fAir.map(round),
  formants_he: fHe.map(round),
  c_sf6: round(cSF6),
  ratio_sf6: round2(cSF6 / cAir20),
};
function round(x) { return Math.round(x); }
function round2(x) { return Math.round(x * 100) / 100; }

if (process.argv.includes('--json')) {
  console.log('\n' + JSON.stringify(PAGE, null, 2));
}
process.exit(fails === 0 ? 0 : 1);
