/ music / acoustic-base
Sign in
music / acoustic-base
acoustic-base / scripts / test_engine.ts
122 lines · 6.7 KBCodeBlameHistory
087c169Physically simulated pizzicato double bass and an SF2 built from itJeremy Magland 1// Verification of the time-domain engine against analytic results.
2// 1. rigid bridge, modal string: partial frequencies f_n = n f0 sqrt(1 + B n^2) and decay rates = Valette's
3// 2. the FD string against the same analytic partials
4// 3. one body mode at the bridge: bridge-loss decay of the fundamental vs 1/Q = (2/(n pi)) Z0 Re Y (weak coupling)
5// 4. stability: hardest pluck, nonlinear, all strings, 6 s: no growth
6// node scripts/test_engine.ts
7import { defaultParams, type Params } from "../src/core/params.ts";
8import { renderNote } from "../src/core/engine.ts";
9import { stringConst, stringModes, fingering } from "../src/core/strings.ts";
10import { bandFrequency, fft } from "../src/core/dsp.ts";
11import type { BodyModel, BodyMode } from "../src/core/types.ts";
13let fails = 0;
14const check = (name: string, ok: boolean, detail: string) => { console.log(`${ok ? "PASS" : "FAIL"} ${name}: ${detail}`); if (!ok) fails++; };
16const rigid: BodyModel = { name: "rigid", source: "parametric", modes: [] };
17function base(): Params {
18 const p = defaultParams();
19 p.engine.sympathetic = false; p.engine.nonlinear = false; p.engine.oversample = 2;
20 p.output.micMix = 0; p.output.pickupMix = 1; p.output.pickupLateral = 0;
21 p.pluck.angleDeg = 90; // vertical pull only, so the vertical pickup sees everything
22 return p;
25/** frequency and decay of the spectral peak near f (zoomed DFT on two windows) */
26function peak(x: Float32Array, fs: number, f: number, t0: number, t1: number, win = 1.0): { f: number; sigma: number } {
27 const n = 1 << Math.ceil(Math.log2(win * fs * 4));
28 const amp = (t: number) => {
29 const re = new Float64Array(n), im = new Float64Array(n), w = Math.round(win * fs), s = Math.round(t * fs);
30 for (let i = 0; i < w; i++) re[i] = (x[s + i] ?? 0) * (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / w));
31 fft(re, im);
32 const b0 = Math.round((f * 0.98 * n) / fs), b1 = Math.round((f * 1.02 * n) / fs);
33 let bb = b0, bv = 0;
34 for (let b = b0; b <= b1; b++) { const v = Math.hypot(re[b], im[b]); if (v > bv) { bv = v; bb = b; } }
35 // parabolic interpolation on log magnitude
36 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]));
37 const d = (0.5 * (l - r)) / (l - 2 * c + r);
38 return { f: ((bb + d) * fs) / n, a: bv };
39 };
40 const A = amp(t0), B = amp(t1);
41 return { f: A.f, sigma: Math.log(A.a / B.a) / (t1 - t0) };
44// 1 + 2. rigid bridge: modal and FD vs analytic
45for (const model of ["modal", "fd"] as const) {
46 const p = base(); p.engine.stringModel = model;
47 const note = 33;
48 const r = renderNote(p, rigid, { note, velocity: 100, duration: 4 });
49 const fg = fingering(p, note);
50 const sc = stringConst(p, fg.string);
51 const an = stringModes(p, sc, fg.length, 20000);
52 const errs: string[] = [];
53 let maxCents = 0, maxSig = 0;
54 for (const n of [1, 2, 3, 5, 8, 12]) {
55 const fa = an.w[n - 1] / (2 * Math.PI), sa = an.sigma[n - 1];
56 const m = peak(r.pickup, r.sampleRate, fa, 0.3, 2.3);
57 const cents = 1200 * Math.log2(m.f / fa);
58 maxCents = Math.max(maxCents, Math.abs(cents));
59 maxSig = Math.max(maxSig, Math.abs(m.sigma - sa) / sa);
60 errs.push(`n${n} ${fa.toFixed(1)} Hz ${cents.toFixed(2)}c sigma ${m.sigma.toFixed(3)}/${sa.toFixed(3)}`);
61 }
62 // the FD string uses a two-parameter loss (sigma0 + sigma1 beta^2) fitted to Valette, so its decay rates are approximate
63 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("; ")}`);
66// 3. one body mode: weak-coupling bridge loss of the fundamental
68 const p = base();
69 const note = 33, fg = fingering(p, note), sc = stringConst(p, fg.string);
70 const f1 = stringModes(p, sc, fg.length, 100).w[0] / (2 * Math.PI);
71 const fm = 80, zeta = 0.03, meff = 1.5, b = 1 / Math.sqrt(meff);
72 const mode: BodyMode = { f: fm, zeta, by: [b, b, b, b], bz: [0, 0, 0, 0], radRe: 0, radIm: 0 };
73 const r = renderNote(p, { name: "one", source: "parametric", modes: [mode] }, { note, velocity: 100, duration: 4 });
74 const m = peak(r.pickup, r.sampleRate, f1, 0.3, 2.3);
75 const w = 2 * Math.PI * m.f, wm = 2 * Math.PI * fm;
76 const reY = (w * b * b * 2 * zeta * wm * w) / ((wm * wm - w * w) ** 2 + (2 * zeta * wm * w) ** 2);
77 const Z0 = Math.sqrt(sc.T * sc.mu);
78 const sigBridge = (Math.PI * m.f) * ((2 / Math.PI) * Z0 * reY);
79 const sigString = stringModes(p, sc, fg.length, 100).sigma[0];
80 const pred = sigString + sigBridge;
81 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)})`);
84// 4. stability: hardest pluck, nonlinear, sympathetic strings, FE-like heavy body thinning off
86 const p = defaultParams();
87 p.engine.bodyModel = "parametric"; p.pluck.forceMax = 30; p.engine.oversample = 1;
88 const { parametricBody } = await import("../src/core/body.ts");
89 for (const note of [28, 43, 60]) {
90 const r = renderNote(p, parametricBody(p), { note, velocity: 127, duration: 6 });
91 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; };
92 const a = seg(0, 0.5), b = seg(5, 6);
93 check(`stability, note ${note} at 30 N`, isFinite(b) && b < a, `peak first 0.5 s ${a.toExponential(2)}, last second ${b.toExponential(2)}`);
94 }
96// 5. tuning by ear with the FE body: the first partial (power-weighted over its split peaks, in the
97// output mix, 0.5-2.5 s, soft pluck) on pitch
99 const fs0 = await import("node:fs");
100 const path = await import("node:path");
101 const f = path.join(import.meta.dirname, "..", "bodies", "fe_default.json");
102 if (fs0.existsSync(f)) {
103 const fe = JSON.parse(fs0.readFileSync(f, "utf8")) as BodyModel;
104 for (const intonate of [false, true]) {
105 const p = defaultParams();
106 p.engine.intonate = intonate;
107 const res: string[] = [];
108 let worst = 0;
109 for (const note of [28, 30, 33, 38, 43, 47, 52, 57]) {
110 const r = renderNote(p, fe, { note, velocity: 40, duration: 3 });
111 const f0 = 440 * Math.pow(2, (note - 69) / 12);
112 const c = 1200 * Math.log2(bandFrequency(r.audio, r.sampleRate, f0, 0.5, 2) / f0);
113 worst = Math.max(worst, Math.abs(c));
114 res.push(`${note}: ${c >= 0 ? "+" : ""}${c.toFixed(1)}c`);
115 }
116 if (intonate) check("tuning by ear (FE body)", worst < 6, `worst ${worst.toFixed(1)} cents | ${res.join(" ")}`);
117 else console.log(` without tuning by ear: ${res.join(" ")}`);
118 }
119 }
121console.log(fails ? `${fails} FAILED` : "all passed");
122process.exit(fails ? 1 : 0);
↑↓ move↵openescclose