// verify-highest-pitch-you-can-hear.mjs - the signal math and every sourced number
// behind the stratum "The First Note the Years Take"
// (/strata/highest-pitch-you-can-hear/), recomputed from first principles.
//
// The claim the page makes, and honestly scopes:
//   Human hearing nominally spans 20 Hz to 20 kHz, but the top of that band is the
//   first thing age takes, on a steep, well-measured schedule. Only ~52% of healthy
//   21-30-year-olds still hear 20 kHz, essentially none past ~40, and by ~25 most
//   people can no longer hear the 17.4 kHz "mosquito" tone. WHY: presbycusis kills
//   the outer hair cells of the BASAL (high-frequency) turn of the tonotopic cochlea
//   first. BUT: the browser test measures the speaker/DAC/room (capped by the
//   sample-rate Nyquist ceiling) as much as the ear, and ISO 7029, the standard cited
//   for "ear age", does not even reach these frequencies.
//
// What this script proves, offline, recomputing every number the page shows:
//   1. TONE FIDELITY: synthesize a pure sine at each detent, DFT it, assert the peak
//      bin lands on the requested frequency within one bin; assert an above-Nyquist
//      request folds (aliases); confirm Nyquist ceilings 22050 @44100, 24000 @48000.
//   2. ISO 7029 SHAPE: DeltaH = alpha*(Y-18)^2 is 0 at 18, strictly increasing,
//      quadratic (constant 2nd difference), and the domain guard refuses 15-20 kHz.
//   3. PRIMARY-NUMBER LEDGER: the Wang 2021 anchors match the cited tables verbatim.
//   4. MAPPING: the cutoff-to-age-band lookup is monotonic and carries the caveat.
//
//   run:  node research/highest-pitch-you-can-hear/verify-highest-pitch-you-can-hear.mjs
//
// No dependencies. Every displayed number is recomputed here, the same way the page does.

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

// ============================================================
// SOURCED CONSTANTS (mirror the page's data block verbatim)
// ============================================================
const NOMINAL_LOW = 20, NOMINAL_HIGH = 20000;   // Hz, nominal human range (Wikipedia "Hearing range")
const MOSQUITO_HZ = 17400, MOSQUITO_LOW_HZ = 8000;   // The Mosquito, Stapleton 2005

// Wang et al. 2021 (DOI 10.1186/s40463-021-00534-w), median thresholds dB HL; null = NA (<=20% response)
const WANG_FREQS = [12500, 14000, 16000, 18000, 20000];
const WANG_THR = {
  12500: [15, 50, 55, 65, 75],
  14000: [20, 60, 65, 70, 75],
  16000: [25, 50, 55, 55, null],
  18000: [20, null, null, null, null],
  20000: [10, null, null, null, null]
};
const WANG_16K_RESP = 1.00;                 // 100% of under-30s responsive at 16 kHz
const WANG_20K_PCT = 52.2;                  // %
const WANG_20K_N = 24, WANG_UNDER30_N = 46; // 24 of 46 ears (Wang 2021 Table 2 counts ears)
const GRADIENT_CAVEAT = 'A cutoff is a soft gradient with wide individual scatter, not a wall or a birth date.';

// ============================================================
// 1. TONE FIDELITY - a real DFT of synthesized sines
// ============================================================
console.log('\n- 1. tone fidelity: DFT of synthesized pure sines -');

function synthSine(f, fs, N) {
  const buf = new Float64Array(N);
  for (let n = 0; n < N; n++) buf[n] = Math.sin(2 * Math.PI * f * n / fs);
  return buf;
}
// method A: full magnitude DFT, argmax over 0..N/2
function dftPeakHz(buf, fs) {
  const N = buf.length, half = Math.floor(N / 2);
  let best = 0, bestMag = -1;
  for (let k = 0; k <= half; k++) {
    let re = 0, im = 0; const w = 2 * Math.PI * k / N;
    for (let n = 0; n < N; n++) { re += buf[n] * Math.cos(w * n); im -= buf[n] * Math.sin(w * n); }
    const mag = re * re + im * im;
    if (mag > bestMag) { bestMag = mag; best = k; }
  }
  return best * fs / N;
}
// method B (independent): Goertzel power at a target bin, checked > neighbours
function goertzelPower(buf, fs, f) {
  const N = buf.length;
  const k = Math.round(f * N / fs);
  const w = 2 * Math.PI * k / N;
  const coeff = 2 * Math.cos(w);
  let s0 = 0, s1 = 0, s2 = 0;
  for (let n = 0; n < N; n++) { s0 = buf[n] + coeff * s1 - s2; s2 = s1; s1 = s0; }
  return s1 * s1 + s2 * s2 - coeff * s1 * s2;
}

const fs1 = 44100, N1 = 4096, binHz = fs1 / N1;
for (const f of [8000, 15000, 17400, 20000]) {
  const buf = synthSine(f, fs1, N1);
  const pk = dftPeakHz(buf, fs1);
  ok(`tone ${f} Hz: DFT peak within one bin (${binHz.toFixed(1)} Hz)`, Math.abs(pk - f) <= binHz + 1e-6, `peak ${pk.toFixed(2)} Hz`);
  // method B: power at the target bin exceeds power one bin either side
  const pAt = goertzelPower(buf, fs1, f);
  const pLo = goertzelPower(buf, fs1, f - binHz);
  const pHi = goertzelPower(buf, fs1, f + binHz);
  ok(`tone ${f} Hz: Goertzel power peaks at the target bin (independent check)`, pAt > pLo && pAt > pHi);
}

// aliasing: a 30 kHz request at 44.1 kHz folds to fs - f = 14100 Hz (below Nyquist)
const alias = dftPeakHz(synthSine(30000, fs1, N1), fs1);
ok('above-Nyquist 30 kHz @44.1k aliases (folds to ~14100, not 30000)',
  approx(alias, fs1 - 30000, binHz + 1e-6) && Math.abs(alias - 30000) > 1000, `peak ${alias.toFixed(1)} Hz`);
// general aliasing identity for fs/2 < f < fs
for (const [f, fsx] of [[23000, 44100], [25000, 48000], [30000, 44100]]) {
  const expect = fsx - f;
  const pk = dftPeakHz(synthSine(f, fsx, 2048), fsx);
  ok(`alias identity: ${f} Hz @${fsx} -> ${expect} Hz`, approx(pk, expect, fsx / 2048 + 1e-6), `peak ${pk.toFixed(1)} Hz`);
}
// Nyquist ceilings
ok('Nyquist ceiling 22050 Hz @44100', 44100 / 2 === 22050);
ok('Nyquist ceiling 24000 Hz @48000', 48000 / 2 === 24000);
// the near-ceiling flag (0.85 * Nyquist) lands in the 18-20 kHz danger band at 44.1 kHz
const flagAt441 = 0.85 * (44100 / 2);
ok('near-ceiling flag trips inside the top test band at 44.1 kHz', flagAt441 > 18000 && flagAt441 < 20000, `${flagAt441.toFixed(0)} Hz`);

// ============================================================
// 2. ISO 7029 SHAPE - DeltaH = alpha*(Y-18)^2, with a domain guard
// ============================================================
console.log('\n- 2. ISO 7029 shape: DeltaH = alpha*(Y-18)^2, domain-guarded -');

function isoShift(freqHz, Y, alpha) {
  if (freqHz > 12500) return null;           // ISO 7029 does not cover above 12.5 kHz
  if (Y < 18) Y = 18;
  return alpha * (Y - 18) * (Y - 18);
}
ok('ISO shape is exactly 0 at Y=18', isoShift(4000, 18, 0.01) === 0);
ok('ISO shape strictly increasing with age (alpha>0)',
  isoShift(4000, 30, 0.01) < isoShift(4000, 50, 0.01) && isoShift(4000, 50, 0.01) < isoShift(4000, 70, 0.01));
// quadratic: second difference is constant = 2*alpha at every age
let quadOK = true;
for (let Y = 20; Y <= 78; Y++) {
  const d2 = isoShift(4000, Y + 1, 0.01) - 2 * isoShift(4000, Y, 0.01) + isoShift(4000, Y - 1, 0.01);
  if (Math.abs(d2 - 0.02) > 1e-9) quadOK = false;
}
ok('ISO shape is quadratic (2nd difference constant = 2*alpha)', quadOK);
// domain guard: refuses the 15-20 kHz test band, still emits at <=12.5 kHz
ok('ISO domain guard refuses 15-20 kHz (returns null; shape only, not a reading)',
  isoShift(15000, 60, 0.01) === null && isoShift(17400, 60, 0.01) === null &&
  isoShift(20000, 60, 0.01) === null && isoShift(12500, 60, 0.01) !== null);

// ============================================================
// 3. PRIMARY-NUMBER LEDGER - Wang 2021 verbatim + range + mosquito
// ============================================================
console.log('\n- 3. primary-number ledger (Wang 2021, Stapleton 2005, nominal range) -');

ok('Wang under-30 responsiveness = 100% at 16 kHz', WANG_16K_RESP === 1.00);
ok('Wang under-30 = 52.2% at 20 kHz, and 24/46 ears reproduces it',
  approx(WANG_20K_N / WANG_UNDER30_N * 100, WANG_20K_PCT, 0.1), `${(WANG_20K_N / WANG_UNDER30_N * 100).toFixed(2)}%`);
ok('12.5 kHz ladder = 15/50/55/65/75 dB HL', WANG_THR[12500].join('/') === '15/50/55/65/75');
ok('14 kHz ladder = 20/60/65/70/75 dB HL', WANG_THR[14000].join('/') === '20/60/65/70/75');
ok('16 kHz ladder = 25/50/55/55/NA', WANG_THR[16000].map(v => v === null ? 'NA' : v).join('/') === '25/50/55/55/NA');
ok('18 kHz ladder = 20/NA/NA/NA/NA (only youngest band responds)',
  WANG_THR[18000].map(v => v === null ? 'NA' : v).join('/') === '20/NA/NA/NA/NA');
ok('20 kHz ladder = 10/NA/NA/NA/NA (only youngest band responds)',
  WANG_THR[20000].map(v => v === null ? 'NA' : v).join('/') === '10/NA/NA/NA/NA');
// monotonic worsening down each age column at 12.5 and 14 kHz (thresholds never improve with age)
for (const f of [12500, 14000]) {
  let mono = true;
  for (let i = 1; i < WANG_THR[f].length; i++) if (WANG_THR[f][i] < WANG_THR[f][i - 1]) mono = false;
  ok(`age worsens thresholds monotonically at ${f / 1000} kHz`, mono);
}
// the top two frequencies collapse to NA for everyone over 30 (the "top goes first")
ok('at 18 and 20 kHz only the 21-30 band has a measurable threshold',
  WANG_THR[18000].slice(1).every(v => v === null) && WANG_THR[20000].slice(1).every(v => v === null));
ok('nominal human range = 20 Hz to 20 kHz', NOMINAL_LOW === 20 && NOMINAL_HIGH === 20000);
ok('mosquito = 17.4 kHz primary, 8 kHz secondary', MOSQUITO_HZ === 17400 && MOSQUITO_LOW_HZ === 8000);
ok('mosquito 17.4 kHz sits above the 16 kHz all-heard line and below 20 kHz nominal ceiling',
  MOSQUITO_HZ > 16000 && MOSQUITO_HZ < NOMINAL_HIGH);

// ============================================================
// 4. MAPPING - cutoff -> age band, monotonic + caveat
// ============================================================
console.log('\n- 4. cutoff-to-age-band mapping: monotonic + caveat -');

function ageContext(cutHz) {
  if (cutHz >= 17400) return 0;
  if (cutHz >= 16000) return 1;
  if (cutHz >= 15000) return 2;
  if (cutHz >= 12500) return 3;
  return 4;
}
let mono = true, last = -1;
for (let f = 20000; f >= 8000; f -= 100) {
  const idx = ageContext(f);
  if (idx < last) mono = false;   // as cutoff falls, band index must never decrease (never map younger)
  last = idx;
}
ok('mapping monotonic (a higher cutoff never maps to an older band)', mono);
ok('mapping carries the gradient caveat', GRADIENT_CAVEAT.length > 0 && /gradient/.test(GRADIENT_CAVEAT));
// spot checks of the ladder placement the page states in words
ok('17.4 kHz cutoff -> youthful side of the mosquito line (band 0)', ageContext(17400) === 0);
ok('16 kHz cutoff -> universal-under-30 band (band 1)', ageContext(16000) === 1);
ok('below 12.5 kHz -> off the bottom of ISO extended coverage (band 4)', ageContext(12000) === 4);

// ============================================================
// TONOTOPY sanity: Greenwood place is monotone (base=high, apex=low)
// ============================================================
console.log('\n- tonotopy: Greenwood frequency-place map is monotone (base high, apex low) -');
function greenwoodPlaceFromApex(f) { const A = 165.4, a = 2.1, k = 0.88; return Math.log10(f / A + k) / a; }
ok('higher frequency maps nearer the base (larger place fraction)',
  greenwoodPlaceFromApex(20000) > greenwoodPlaceFromApex(1000) &&
  greenwoodPlaceFromApex(1000) > greenwoodPlaceFromApex(100));
ok('the test band (8-20 kHz) all maps into the basal third (place > 0.66)',
  greenwoodPlaceFromApex(8000) > 0.66 && greenwoodPlaceFromApex(20000) <= 1.0001);

console.log(`\n${fails === 0 ? 'ALL CHECKS PASSED' : fails + ' CHECK(S) FAILED'}\n`);
process.exit(fails === 0 ? 0 : 1);
