#!/usr/bin/env node
// Numerical checks of specified Gaussian combs. These are target-parameter
// calculations, not measurements of perceived pitch height, audibility or audio.
// Run: node research/shepard-tone/verify.mjs
import { pathToFileURL } from 'node:url';

const FBASE = 20, MU = Math.log2(640), SIGMA = 1.3;
export function envelope(f) {
  const d = Math.log2(f) - MU;
  return Math.exp(-(d * d) / (2 * SIGMA * SIGMA));
}
export function widePartials(theta) {
  return Array.from({ length: 23 }, (_, i) => {
    const f = FBASE * 2 ** (theta + (i - 6));
    return { f, a: envelope(f) };
  });
}
// Independently construct a sorted target comb. The page uses rotating voice
// identities; integer-octave transposition permutes them. Low sample rates mute
// components at or above Nyquist and clamp their silent frequency targets.
export function finitePartials(theta, stepped = false, ceiling = 20480) {
  const t = stepped ? Math.floor(theta * 12) / 12 : theta;
  const phase = t - Math.floor(t);
  return Array.from({ length: 10 }, (_, k) => {
    const f = FBASE * 2 ** (phase + k);
    return { f: Math.min(f, ceiling), a: f < ceiling ? envelope(f) : 0 };
  });
}
export function meanLog(partials) {
  let num = 0, den = 0;
  for (const { f, a } of partials) { num += a * Math.log2(f); den += a; }
  return num / den;
}
function sweep(partials, count = 20000) {
  let min = Infinity, max = -Infinity, tritoneGap = 0;
  for (let i = 0; i < count; i++) {
    const phase = i / count, h = meanLog(partials(phase));
    min = Math.min(min, h); max = Math.max(max, h);
    tritoneGap = Math.max(tritoneGap, Math.abs(h - meanLog(partials((phase + 0.5) % 1))) * 1200);
  }
  return { minHz: 2 ** min, maxHz: 2 ** max, ripple: (max - min) * 1200, tritoneGap };
}
export function check() {
  const wide = sweep(widePartials), finite = sweep(finitePartials);
  const stepped = sweep((phase) => finitePartials(phase, true));
  let loopGap = 0, edgeMax = 0, targetLoopGap = 0;
  for (let i = 0; i < 20000; i++) {
    const t = i / 20000;
    if (i % 10 === 0) loopGap = Math.max(loopGap, Math.abs(meanLog(widePartials(t)) - meanLog(widePartials(t + 1))) * 1200);
    for (const { f, a } of widePartials(t)) if (f < 20 || f > 20000) edgeMax = Math.max(edgeMax, a);
    const a = finitePartials(t), b = finitePartials(t + 1);
    for (let k = 0; k < a.length; k++) targetLoopGap = Math.max(targetLoopGap, Math.abs(Math.log2(a[k].f / b[k].f)) * 1200);
  }
  const pairGap = Math.abs(meanLog(widePartials(0)) - meanLog(widePartials(0.5))) * 1200;
  const ok = wide.ripple < 0.01 && loopGap < 0.01 && pairGap < 0.01
    && finite.ripple < 3 && finite.tritoneGap < 3 && stepped.ripple < 3 && targetLoopGap < 1e-8;
  const lines = [
    'Shepard tone: Gaussian model and scheduled-target checks',
    'Statistic: amplitude-weighted mean log-frequency, converted to Hz',
    'Gaussian centre 640 Hz; standard deviation 1.3 octaves',
    '',
    'Wide reference model: 23 uncut partials, slots -6 through 16',
    `cycle ripple (20000 phases)       : ${wide.ripple.toExponential(3)} cents`,
    `octave mean-log mismatch          : ${loopGap.toExponential(3)} cents`,
    `pair at phases 0 and 0.5          : ${pairGap.toExponential(3)} cents`,
    `outside 20 Hz to 20 kHz           : ${(20 * Math.log10(edgeMax)).toFixed(1)} dB relative to envelope peak`,
    '',
    'Finite targets: 10 partials, 20 Hz <= f < 20480 Hz (sample rate >= 40960 Hz)',
    `gliding mean-log range as Hz      : ${finite.minHz.toFixed(6)} to ${finite.maxHz.toFixed(6)}`,
    `gliding cycle ripple             : ${finite.ripple.toFixed(6)} cents`,
    `stepped cycle ripple             : ${stepped.ripple.toFixed(6)} cents`,
    `largest sampled tritone gap       : ${finite.tritoneGap.toFixed(6)} cents`,
    `octave target-frequency mismatch  : ${targetLoopGap.toExponential(3)} cents`,
    '',
    'Tolerances: wide model 0.01 cent; finite ripple/tritone 3 cents; target loop 1e-8 cent.',
    'No inference about perception, absolute audibility or waveform continuity.',
    ok ? 'PASS: the numerical checks meet their stated tolerances.' : 'FAIL: a numerical check exceeded its tolerance.',
  ];
  return { ok, lines, wide, finite, stepped, pairGap, loopGap, targetLoopGap };
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  const result = check();
  console.log(result.lines.join('\n'));
  process.exitCode = result.ok ? 0 : 1;
}
