// Verification of the time-domain engine against analytic results. // 1. rigid bridge, modal string: partial frequencies f_n = n f0 sqrt(1 + B n^2) and decay rates = Valette's // 2. the FD string against the same analytic partials // 3. one body mode at the bridge: bridge-loss decay of the fundamental vs 1/Q = (2/(n pi)) Z0 Re Y (weak coupling) // 4. stability: hardest pluck, nonlinear, all strings, 6 s: no growth // node scripts/test_engine.ts import { defaultParams, type Params } from "../src/core/params.ts"; import { renderNote } from "../src/core/engine.ts"; import { stringConst, stringModes, fingering } from "../src/core/strings.ts"; import { bandFrequency, fft } from "../src/core/dsp.ts"; import type { BodyModel, BodyMode } from "../src/core/types.ts"; let fails = 0; const check = (name: string, ok: boolean, detail: string) => { console.log(`${ok ? "PASS" : "FAIL"} ${name}: ${detail}`); if (!ok) fails++; }; const rigid: BodyModel = { name: "rigid", source: "parametric", modes: [] }; function base(): Params { const p = defaultParams(); p.engine.sympathetic = false; p.engine.nonlinear = false; p.engine.oversample = 2; p.output.micMix = 0; p.output.pickupMix = 1; p.output.pickupLateral = 0; p.pluck.angleDeg = 90; // vertical pull only, so the vertical pickup sees everything return p; } /** frequency and decay of the spectral peak near f (zoomed DFT on two windows) */ function peak(x: Float32Array, fs: number, f: number, t0: number, t1: number, win = 1.0): { f: number; sigma: number } { const n = 1 << Math.ceil(Math.log2(win * fs * 4)); const amp = (t: number) => { const re = new Float64Array(n), im = new Float64Array(n), w = Math.round(win * fs), s = Math.round(t * fs); for (let i = 0; i < w; i++) re[i] = (x[s + i] ?? 0) * (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / w)); fft(re, im); const b0 = Math.round((f * 0.98 * n) / fs), b1 = Math.round((f * 1.02 * n) / fs); let bb = b0, bv = 0; for (let b = b0; b <= b1; b++) { const v = Math.hypot(re[b], im[b]); if (v > bv) { bv = v; bb = b; } } // parabolic interpolation on log magnitude const l = Math.log(Math.hypot(re[bb - 1], im[bb - 1])), c = Math.log(bv), r = Math.log(Math.hypot(re[bb + 1], im[bb + 1])); const d = (0.5 * (l - r)) / (l - 2 * c + r); return { f: ((bb + d) * fs) / n, a: bv }; }; const A = amp(t0), B = amp(t1); return { f: A.f, sigma: Math.log(A.a / B.a) / (t1 - t0) }; } // 1 + 2. rigid bridge: modal and FD vs analytic for (const model of ["modal", "fd"] as const) { const p = base(); p.engine.stringModel = model; const note = 33; const r = renderNote(p, rigid, { note, velocity: 100, duration: 4 }); const fg = fingering(p, note); const sc = stringConst(p, fg.string); const an = stringModes(p, sc, fg.length, 20000); const errs: string[] = []; let maxCents = 0, maxSig = 0; for (const n of [1, 2, 3, 5, 8, 12]) { const fa = an.w[n - 1] / (2 * Math.PI), sa = an.sigma[n - 1]; const m = peak(r.pickup, r.sampleRate, fa, 0.3, 2.3); const cents = 1200 * Math.log2(m.f / fa); maxCents = Math.max(maxCents, Math.abs(cents)); maxSig = Math.max(maxSig, Math.abs(m.sigma - sa) / sa); errs.push(`n${n} ${fa.toFixed(1)} Hz ${cents.toFixed(2)}c sigma ${m.sigma.toFixed(3)}/${sa.toFixed(3)}`); } // the FD string uses a two-parameter loss (sigma0 + sigma1 beta^2) fitted to Valette, so its decay rates are approximate check(`${model} string, rigid bridge`, maxCents < (model === "modal" ? 0.5 : 3) && maxSig < (model === "modal" ? 0.05 : 0.5), `max ${maxCents.toFixed(2)} cents, max decay error ${(100 * maxSig).toFixed(0)}% | ${errs.join("; ")}`); } // 3. one body mode: weak-coupling bridge loss of the fundamental { const p = base(); const note = 33, fg = fingering(p, note), sc = stringConst(p, fg.string); const f1 = stringModes(p, sc, fg.length, 100).w[0] / (2 * Math.PI); const fm = 80, zeta = 0.03, meff = 1.5, b = 1 / Math.sqrt(meff); const mode: BodyMode = { f: fm, zeta, by: [b, b, b, b], bz: [0, 0, 0, 0], radRe: 0, radIm: 0 }; const r = renderNote(p, { name: "one", source: "parametric", modes: [mode] }, { note, velocity: 100, duration: 4 }); const m = peak(r.pickup, r.sampleRate, f1, 0.3, 2.3); const w = 2 * Math.PI * m.f, wm = 2 * Math.PI * fm; const reY = (w * b * b * 2 * zeta * wm * w) / ((wm * wm - w * w) ** 2 + (2 * zeta * wm * w) ** 2); const Z0 = Math.sqrt(sc.T * sc.mu); const sigBridge = (Math.PI * m.f) * ((2 / Math.PI) * Z0 * reY); const sigString = stringModes(p, sc, fg.length, 100).sigma[0]; const pred = sigString + sigBridge; check("bridge loss (one body mode)", Math.abs(m.sigma - pred) / pred < 0.15, `decay ${m.sigma.toFixed(3)} 1/s vs predicted ${pred.toFixed(3)} (string ${sigString.toFixed(3)} + bridge ${sigBridge.toFixed(3)})`); } // 4. stability: hardest pluck, nonlinear, sympathetic strings, FE-like heavy body thinning off { const p = defaultParams(); p.engine.bodyModel = "parametric"; p.pluck.forceMax = 30; p.engine.oversample = 1; const { parametricBody } = await import("../src/core/body.ts"); for (const note of [28, 43, 60]) { const r = renderNote(p, parametricBody(p), { note, velocity: 127, duration: 6 }); const seg = (t0: number, t1: number) => { let m = 0; for (let i = Math.round(t0 * 44100); i < Math.round(t1 * 44100); i++) m = Math.max(m, Math.abs(r.audio[i])); return m; }; const a = seg(0, 0.5), b = seg(5, 6); check(`stability, note ${note} at 30 N`, isFinite(b) && b < a, `peak first 0.5 s ${a.toExponential(2)}, last second ${b.toExponential(2)}`); } } // 5. tuning by ear with the FE body: the first partial (power-weighted over its split peaks, in the // output mix, 0.5-2.5 s, soft pluck) on pitch { const fs0 = await import("node:fs"); const path = await import("node:path"); const f = path.join(import.meta.dirname, "..", "bodies", "fe_default.json"); if (fs0.existsSync(f)) { const fe = JSON.parse(fs0.readFileSync(f, "utf8")) as BodyModel; for (const intonate of [false, true]) { const p = defaultParams(); p.engine.intonate = intonate; const res: string[] = []; let worst = 0; for (const note of [28, 30, 33, 38, 43, 47, 52, 57]) { const r = renderNote(p, fe, { note, velocity: 40, duration: 3 }); const f0 = 440 * Math.pow(2, (note - 69) / 12); const c = 1200 * Math.log2(bandFrequency(r.audio, r.sampleRate, f0, 0.5, 2) / f0); worst = Math.max(worst, Math.abs(c)); res.push(`${note}: ${c >= 0 ? "+" : ""}${c.toFixed(1)}c`); } if (intonate) check("tuning by ear (FE body)", worst < 6, `worst ${worst.toFixed(1)} cents | ${res.join(" ")}`); else console.log(` without tuning by ear: ${res.join(" ")}`); } } } // 6. recording for the physics view: does not change the sound; frames in time order; the energy // balance after the pluck (no source) only falls { const { parametricBody } = await import("../src/core/body.ts"); const p = defaultParams(); p.engine.bodyModel = "parametric"; const body = parametricBody(p); const plain = renderNote(p, body, { note: 33, velocity: 90, duration: 0.5 }); const r = renderNote(p, body, { note: 33, velocity: 90, duration: 0.5, record: { denseFrom: 0, denseTo: Infinity, denseAfterRelease: 0.02, maxDense: 4000, sparseDt: 0.001, stringPoints: 64, sympPoints: 16, shapeModes: 0 } }); const R = r.recording!; let same = plain.audio.length === r.audio.length; for (let i = 0; same && i < plain.audio.length; i++) same = plain.audio[i] === r.audio[i]; let sorted = true; for (let i = 1; i < R.frameTimes.length; i++) if (!(R.frameTimes[i] > R.frameTimes[i - 1])) sorted = false; const E = (j: number) => R.channels.eString[j] + R.channels.eSymp[j] + R.channels.eBody[j] + R.channels.eAir[j]; const j0 = Math.ceil((R.tRelease + R.slipTime + 0.005) / R.dt), j1 = R.nSteps - 1; const step = Math.round(0.05 / R.dt); let falls = true; for (let j = j0 + step; j <= j1; j += step) if (E(j) > E(j - step) * 1.02) falls = false; check("recording", same && sorted && falls && R.dense[0] >= 0, `audio identical ${same}, ${R.frameTimes.length} frames in order ${sorted}, energy ${E(j0).toExponential(2)} -> ${E(j1).toExponential(2)} J, falling ${falls}`); } console.log(fails ? `${fails} FAILED` : "all passed"); process.exit(fails ? 1 : 0);