#!/usr/bin/env node
// verify.mjs — Sensory dissonance (Plomp–Levelt critical band, Sethares parametric fit).
//
// CLAIM under test, in plain words:
//   1. Sethares' pairwise dissonance d(f1,f2,l1,l2) is well-behaved: zero at unison,
//      rises to a single peak, decays to ~0 well past one critical band, and the peak
//      at 440 Hz sits near 0.357 ERB; ERB differs from classical critical bandwidth.
//   2. For a HARMONIC timbre, the total-dissonance curve D(r), swept over interval
//      ratios r in [1,2], has local MINIMA at (or very near) the simple just ratios —
//      octave 2/1, fifth 3/2, fourth 4/3, major third 5/4 are deep and robust;
//      major sixth 5/3 and minor third 6/5 appear but are shallow (named honestly).
//   3. Sethares' deeper point: the minima follow the SPECTRUM, not integer magic.
//      Stretch the partials (pseudo-octave 2.1) and the deepest minimum moves OFF 3/2
//      and OFF 2/1 — the just ratios stop being special for a non-harmonic timbre.
//
// Sources (constants verified against the literature; see research note):
//   Plomp & Levelt, "Tonal Consonance and Critical Bandwidth," JASA 38:548 (1965).
//   Sethares, "Local consonance and the relationship between timbre and scale,"
//     JASA 94:1218 (1993); Tuning, Timbre, Spectrum, Scale (Springer, 2005).
//   Glasberg & Moore, "Derivation of auditory filter shapes...," Hear. Res. 47:103 (1990).
//
// Run:  node research/critical-band-consonance/verify.mjs
// Exit 0 iff every check passes. The page mirrors this exact math.

let PASS = 0, FAIL = 0;
function ok(name, cond, detail = "") {
  if (cond) { PASS++; console.log(`  ok   ${name}${detail ? "  — " + detail : ""}`); }
  else { FAIL++; console.log(`  FAIL ${name}${detail ? "  — " + detail : ""}`); }
}
const round = (x, n = 6) => Number(x.toFixed(n));

// ─────────────────────────────────────────────────────────────────────────────
// Sethares parametric dissonance of two pure tones.
// d(f1,f2,l1,l2) = l12 * ( exp(-b1*s*df) - exp(-b2*s*df) ),  s = x*/(s1*fmin+s2)
// Published constants: b1=3.5, b2=5.75, x*=0.24, s1=0.0207, s2=18.96.
// Amplitude weight: l12 = min(l1,l2)  (the book's recipe; documented choice).
const B1 = 3.5, B2 = 5.75, XSTAR = 0.24, S1 = 0.0207, S2 = 18.96;

function dissonancePair(f1, f2, l1, l2) {
  const fmin = Math.min(f1, f2);
  const df = Math.abs(f2 - f1);
  const s = XSTAR / (S1 * fmin + S2);
  const l12 = Math.min(l1, l2);
  return l12 * (Math.exp(-B1 * s * df) - Math.exp(-B2 * s * df));
}

// Total dissonance of a set of partials (pooled spectrum): sum over all pairs.
function dissonanceTotal(freqs, amps) {
  let D = 0;
  for (let i = 0; i < freqs.length; i++)
    for (let j = i + 1; j < freqs.length; j++)
      D += dissonancePair(freqs[i], freqs[j], amps[i], amps[j]);
  return D;
}

// A timbre = N partials at base*ratio^... For harmonic: partial k at k*f0.
// For a stretched timbre with pseudo-octave A: partial k at f0 * k^(log2(A)).
// (k=1 -> f0; k=2 -> f0*A; the integer-harmonic case is A=2 => exponent 1.)
function timbrePartials(f0, n, rolloff = 0.88, stretch = 2.0) {
  const expo = Math.log2(stretch); // 1 for harmonic
  const freqs = [], amps = [];
  for (let k = 1; k <= n; k++) {
    freqs.push(f0 * Math.pow(k, expo));
    amps.push(Math.pow(rolloff, k - 1));
  }
  return { freqs, amps };
}

// Dyad dissonance at interval ratio r: tone1 at f0, tone2 at r*f0, same timbre.
function dyadDissonance(r, { f0 = 261.63, n = 7, rolloff = 0.88, stretch = 2.0 } = {}) {
  const a = timbrePartials(f0, n, rolloff, stretch);
  const b = timbrePartials(r * f0, n, rolloff, stretch);
  const freqs = a.freqs.concat(b.freqs);
  const amps = a.amps.concat(b.amps);
  // Subtract the two within-tone offsets so D(r) measures the *interval* dissonance.
  const offset = dissonanceTotal(a.freqs, a.amps) + dissonanceTotal(b.freqs, b.amps);
  return dissonanceTotal(freqs, amps) - offset;
}

// Sweep + find interior local minima of D(r).
function sweepMinima(opts, lo = 1.0, hi = 2.0, steps = 4000) {
  const rs = [], ds = [];
  for (let i = 0; i <= steps; i++) {
    const r = lo + (hi - lo) * i / steps;
    rs.push(r); ds.push(dyadDissonance(r, opts));
  }
  const minima = [];
  for (let i = 1; i < ds.length - 1; i++)
    if (ds[i] < ds[i - 1] && ds[i] <= ds[i + 1]) minima.push({ r: rs[i], d: ds[i] });
  return { rs, ds, minima };
}

// Glasberg–Moore ERB (Hz) — a usable critical-bandwidth proxy.
const ERB = (f) => 24.7 * (4.37 * f / 1000 + 1);

// Run the checks only when invoked directly (`node verify.mjs`); when this
// module is *imported* (e.g. by the companion film's audio, which sonifies
// the very curve checked below) the exports are taken without re-running the
// suite or calling process.exit. `node verify.mjs` behaves exactly as before.
// (Guarded for the browser, which has no `process` — it imports the exports
// only, e.g. the companion film's audio/canvas sonifying this very curve.)
if (typeof process !== "undefined" && process.argv &&
    import.meta.url === `file://${process.argv[1]}`) {
console.log("Sensory dissonance — Plomp–Levelt critical band, Sethares fit\n");

// ── 1. Pairwise curve is well-behaved ───────────────────────────────────────
console.log("[1] Pairwise dissonance d(f1,f2) — shape (Plomp–Levelt)");
{
  const f = 440;
  ok("zero at unison", Math.abs(dissonancePair(f, f, 1, 1)) < 1e-12,
     `d=${dissonancePair(f, f, 1, 1)}`);

  // Sweep df from 0..200 Hz; find the peak; check decays to ~0 by >1 critical band.
  let peakDf = 0, peakVal = -1;
  for (let df = 0; df <= 200; df += 0.1) {
    const v = dissonancePair(f, f + df, 1, 1);
    if (v > peakVal) { peakVal = v; peakDf = df; }
  }
  // Analytic peak: df* = ln(b2/b1)/((b2-b1)*s)
  const s = XSTAR / (S1 * f + S2);
  const dfStarAnalytic = Math.log(B2 / B1) / ((B2 - B1) * s);
  ok("peak matches closed form", Math.abs(peakDf - dfStarAnalytic) < 0.2,
     `numeric ${round(peakDf,2)}Hz vs analytic ${round(dfStarAnalytic,2)}Hz`);

  // At 440 Hz this fit peaks near 0.357 ERB. Do not confuse the ERB with
  // the classical critical bandwidth used for the quarter-band description.
  const erb = ERB(f);
  const fracOfERB = peakDf / erb;
  ok("peak is about 0.357 ERB at 440 Hz", Math.abs(fracOfERB - 0.357) < 0.001,
     `peak/ERB = ${round(fracOfERB,3)} (ERB(440)=${round(erb,1)}Hz)`);

  // The exponential fit has a longer tail than a literal "zero by 1 CB": it is
  // well past its peak and decaying by 1 CB, and effectively gone (<5%) by ~3 CB.
  const cb = 1.3 * erb;
  const tail1 = dissonancePair(f, f + cb, 1, 1);
  const tail3 = dissonancePair(f, f + 3 * cb, 1, 1);
  ok("falling and small (<35% peak) by one critical band", tail1 < 0.35 * peakVal,
     `d(1 CB)/peak = ${round(tail1 / peakVal, 3)}`);
  ok("effectively gone (<5% peak) by ~three critical bands", tail3 < 0.05 * peakVal,
     `d(3 CB)/peak = ${round(tail3 / peakVal, 3)}`);

  // Strictly positive and single-humped between 0 and the peak (monotone up).
  let monoUp = true, prev = 0;
  for (let df = 0.5; df <= peakDf; df += 0.5) {
    const v = dissonancePair(f, f + df, 1, 1);
    if (v < prev - 1e-9) monoUp = false; prev = v;
  }
  ok("rises monotonically to the peak", monoUp);
}

// ── 2. Critical-band scaling: same interval, different register ──────────────
console.log("\n[2] A close interval loses its bite up high (CB grows with f)");
{
  // A minor second (16/15 ≈ 1.067) as a pure-tone dyad, mid vs high register.
  // In the Sethares fit, roughness of a fixed *ratio* peaks where its Hz gap ≈ a
  // quarter critical band (here ~440 Hz) and falls off above: a minor 2nd is much
  // rougher in the mid register than two octaves higher, because up high the Hz gap
  // has outrun the critical band. (The familiar "muddy low thirds, clear high ones".)
  const r = 16 / 15;
  const mid = dissonancePair(440, 440 * r, 1, 1);    // ~A4
  const high = dissonancePair(1760, 1760 * r, 1, 1); // ~A6
  ok("same ratio much rougher in mid than high register", mid > high * 1.3,
     `d(mid440)=${round(mid,4)} >> d(high1760)=${round(high,4)}`);
}

// ── 3. Harmonic timbre: minima land on the just ratios ───────────────────────
console.log("\n[3] Harmonic timbre — dissonance minima at the just ratios");
const JUST = [
  { name: "octave 2/1", r: 2 / 1, robust: true },
  { name: "fifth 3/2", r: 3 / 2, robust: true },
  { name: "fourth 4/3", r: 4 / 3, robust: true },
  { name: "major third 5/4", r: 5 / 4, robust: true },
  { name: "major sixth 5/3", r: 5 / 3, robust: false },
  { name: "minor third 6/5", r: 6 / 5, robust: false },
];
{
  const opts = { f0: 261.63, n: 7, rolloff: 0.88, stretch: 2.0 };
  // Sweep slightly past 2/1 so the octave registers as an interior local minimum.
  const { minima } = sweepMinima(opts, 1.0, 2.05, 6150);
  // Helper: nearest minimum to a target ratio, within tolerance (in cents).
  const cents = (a, b) => 1200 * Math.log2(a / b);
  function nearestMin(target) {
    let best = null;
    for (const m of minima) {
      const c = Math.abs(cents(m.r, target));
      if (best === null || c < best.c) best = { ...m, c };
    }
    return best;
  }
  for (const j of JUST) {
    const nm = nearestMin(j.r);
    const within = nm && nm.c < 18; // within ~18 cents of the just ratio
    if (j.robust) {
      ok(`minimum at ${j.name}`, within,
         nm ? `nearest min r=${round(nm.r,4)} (${round(nm.c,1)} cents off)` : "none");
    } else {
      // Named honestly: present but shallow — we report, don't hard-require centre.
      ok(`minimum near ${j.name} (shallow, reported)`, within || (nm && nm.c < 35),
         nm ? `nearest min r=${round(nm.r,4)} (${round(nm.c,1)} cents off)` : "none");
    }
  }
  // The deepest interior minimum should be the fifth (3/2) for a harmonic timbre.
  let deepest = null;
  for (const m of minima) if (m.r > 1.02 && m.r < 1.98)
    if (deepest === null || m.d < deepest.d) deepest = m;
  ok("deepest interior minimum is the fifth", deepest && Math.abs(cents(deepest.r, 1.5)) < 18,
     deepest ? `r=${round(deepest.r,4)} (${round(cents(deepest.r,1.5),1)} cents from 3/2)` : "none");

  // The equal-tempered tritone (√2 ≈ 1.414) is at best a shallow, non-landmark
  // minimum: a 7-partial harmonic timbre brushes the just 7/5 (1.4) and 10/7 (1.429),
  // so a faint dip can exist near there — but it is FAR shallower than the fifth.
  // Honest claim: any tritone-region minimum is much weaker than the fifth's.
  let triMin = null, fifthMin = null;
  for (const m of minima) {
    if (Math.abs(cents(m.r, Math.SQRT2)) < 40) if (!triMin || m.d < triMin.d) triMin = m;
    if (Math.abs(cents(m.r, 1.5)) < 18)        if (!fifthMin || m.d < fifthMin.d) fifthMin = m;
  }
  ok("any tritone-region dip is far shallower than the fifth",
     !triMin || (fifthMin && triMin.d > fifthMin.d * 2),
     triMin ? `tritone d=${round(triMin.d,3)} vs fifth d=${round(fifthMin.d,3)}` : "no tritone min at all");
}

// ── 4. Sethares' point: stretch the timbre, the minima move ──────────────────
console.log("\n[4] Stretched timbre — the just ratios stop being special");
{
  const cents = (a, b) => 1200 * Math.log2(a / b);
  const stretch = 2.1; // pseudo-octave 2.1:1
  const opts = { f0: 261.63, n: 7, rolloff: 0.88, stretch };
  // Sweep out to the stretched pseudo-octave so its minimum is in range.
  const { minima } = sweepMinima(opts, 1.0, 2.2, 7000);

  // The deepest minimum should have MOVED off the perfect fifth 3/2.
  let deepest = null;
  for (const m of minima) if (m.r > 1.02 && m.r < 2.15)
    if (deepest === null || m.d < deepest.d) deepest = m;
  const movedOffFifth = deepest && Math.abs(cents(deepest.r, 1.5)) > 12;
  ok("deepest minimum no longer at 3/2", movedOffFifth,
     deepest ? `now r=${round(deepest.r,4)} (${round(cents(deepest.r,1.5),1)} cents from 3/2)` : "none");

  // There should be a deep minimum near the stretched pseudo-octave (≈2.1), not 2.0.
  let nearStretchOct = null, nearTrueOct = null;
  for (const m of minima) {
    if (Math.abs(cents(m.r, stretch)) < 25) if (!nearStretchOct || m.d < nearStretchOct.d) nearStretchOct = m;
    if (Math.abs(cents(m.r, 2.0)) < 25)     if (!nearTrueOct || m.d < nearTrueOct.d)    nearTrueOct = m;
  }
  ok("a minimum sits at the stretched pseudo-octave 2.1", !!nearStretchOct,
     nearStretchOct ? `r=${round(nearStretchOct.r,4)}` : "none");
  // And the true octave 2/1 is now NOT a clean minimum (or is shallower than 2.1).
  const trueOctIsClean = nearTrueOct && (!nearStretchOct || nearTrueOct.d <= nearStretchOct.d);
  ok("the true octave 2/1 is no longer the consonant landmark", !trueOctIsClean,
     nearTrueOct ? `2.0 min d=${round(nearTrueOct.d,4)} vs 2.1 d=${nearStretchOct?round(nearStretchOct.d,4):"n/a"}` : "no min at 2.0");
}

// ── 5. Self-consistency: page constants match ────────────────────────────────
console.log("\n[5] Constants (page must use these exact values)");
{
  ok("b1 = 3.5", B1 === 3.5);
  ok("b2 = 5.75", B2 === 5.75);
  ok("x* = 0.24", XSTAR === 0.24);
  ok("s1 = 0.0207", S1 === 0.0207);
  ok("s2 = 18.96", S2 === 18.96);
  ok("ERB(1000Hz) ≈ 132.6 Hz (Glasberg–Moore)", Math.abs(ERB(1000) - 132.639) < 0.01,
     `ERB(1000)=${round(ERB(1000),3)}`);

  // Until 2026-09-26 this section's title promised the page used these values and nothing
  // here opened the page. Now it does: the page is read from the checkout, or else from what
  // artwaste.land serves, and its own model line must carry these five constants.
  const { readFileSync, existsSync } = await import("node:fs");
  const local = new URL("../../public/strata/critical-band-consonance/index.html", import.meta.url);
  let html = "";
  if (existsSync(local)) html = readFileSync(local, "utf8");
  else { const r = await fetch("https://artwaste.land/strata/critical-band-consonance/"); html = r.ok ? await r.text() : ""; }
  const m = html.match(/const B1=([\d.]+), B2=([\d.]+), XSTAR=([\d.]+), S1=([\d.]+), S2=([\d.]+);/);
  const pageC = m ? m.slice(1).map(Number) : [];
  ok("the page's own script carries b1, b2, x*, s1, s2 exactly as here",
     pageC.length === 5 && [B1, B2, XSTAR, S1, S2].every((v, i) => v === pageC[i]), pageC.join(", "));
  const total = PASS + FAIL + 1;
  ok(`the page states this file's count (${total}/${total})`, html.includes(`identical to the offline verifier (${total}/${total})`));
}

console.log(`\n${FAIL === 0 ? "ALL PASS" : "SOME FAILED"} — ${PASS} ok, ${FAIL} fail`);
process.exit(FAIL === 0 ? 0 : 1);
}

// Export for any reuse.
export { dissonancePair, dissonanceTotal, dyadDissonance, timbrePartials, sweepMinima, ERB,
         B1, B2, XSTAR, S1, S2 };
