5778036cymbalsim: scripted plate and cymbal designer with a modal linear model and a von Karman GPU modelJeremy Magland 1// The design: a MATLAB-syntax script, run by numbl, that fills in a struct
2// named `design` with the material, the bounding box, the outline, the
2a1a6daDerive the losses from physical constants instead of a prescribed decay curveJeremy Magland 3// thickness field, the stress-free profile, the stand, and the loss
4// constants of the material (from which the decay is derived, loss.ts).
5778036cymbalsim: scripted plate and cymbal designer with a modal linear model and a von Karman GPU modelJeremy Magland 5// The outline, the thickness, and the profile are function handles
6// @(x, y, r, theta), vectorized over grid matrices (or plain numbers).
7// compileDesign runs the script and checks the struct; evaluatePlate runs it
8// again with a short trailer that samples the fields on meshgrid matrices of
9// the requested spacing, inside numbl, and reads the matrices back.
10//
11// Lengths are meters throughout. A script is self-contained: nothing is in
12// scope but numbl's own functions and whatever the script defines itself,
13// including ordinary MATLAB functions written at its bottom (numbl hoists
14// them, so the trailer may still follow them).
16import { executeCode, type RuntimeValue, type RuntimeTensor, type RuntimeStruct } from "numbl";
17import { RUNTIME_FILES } from "./mruntime.ts";
18import {
19 type Grid,
20 type Material,
21 type Pad,
22 type Plate,
23 type Stand,
2a1a6daDerive the losses from physical constants instead of a prescribed decay curveJeremy Magland 24 type Thermal,
25 ROOM_TEMPERATURE,
5778036cymbalsim: scripted plate and cymbal designer with a modal linear model and a von Karman GPU modelJeremy Magland 26 insideNode,
27 makeGrid,
28 nodeWeight,
29 nodeX,
30 nodeY,
31 withCellMask,
32} from "./params.ts";
34/** A compiled design: the checked contents of the `design` struct, plus the script that produced it. */
35export interface Design {
36 name: string;
37 material: Material;
38 Lx: number;
39 Ly: number;
40 /** Whether the script gave an outline; without one the plate is the whole bounding box. */
41 hasInside: boolean;
42 /** The thickness when it is a plain number; null for a function. */
43 thicknessConst: number | null;
44 /** The profile when it is a plain number (or absent); null for a function. */
45 profileConst: number | null;
46 stand: Stand | null;
2a1a6daDerive the losses from physical constants instead of a prescribed decay curveJeremy Magland 47 /** Temperature of the plate [K], for the thermoelastic damping. */
48 temperature: number;
5778036cymbalsim: scripted plate and cymbal designer with a modal linear model and a von Karman GPU modelJeremy Magland 49 source: string;
50}
52/** Defaults of the pad of a stand, a typical felt washer. */
53export const DEFAULT_PAD: Pad = { innerRadius: 7e-3, outerRadius: 20e-3, thickness: 12e-3, E: 0.5e6, lossFactor: 0.3 };
54export const DEFAULT_PRELOAD = 1e-3;
56/** Message of an error thrown by the script or by the checks. */
57export class DesignError extends Error {}
59const FILE_NAME = "design.m";
61/**
62 * Runs a design script and returns its workspace variables. `userLines` is
63 * the length of the part of the source the user wrote, so that an error in
64 * the appended trailer is not reported at a line the user cannot see.
65 */
66export function runDesignScript(source: string, userLines = Infinity): Record<string, RuntimeValue> {
67 try {
68 return executeCode(source, { displayResults: false, onOutput: () => {} }, RUNTIME_FILES, FILE_NAME).variableValues;
69 } catch (e) {
70 throw new DesignError(describeError(e, Math.min(source.split("\n").length, userLines)));
71 }
72}
74function describeError(e: unknown, userLines: number): string {
75 if (!(e instanceof Error)) return String(e);
76 const { line, file } = e as { line?: unknown; file?: unknown };
77 const inScript = file === undefined || file === null || file === FILE_NAME;
78 const where = inScript && typeof line === "number" && line >= 1 && line <= userLines ? `line ${line}: ` : "";
79 return `${where}${e.message}`;
80}
82// ---------- Reading runtime values ----------
84function isStruct(v: RuntimeValue | undefined): v is RuntimeStruct {
85 return typeof v === "object" && v !== null && (v as { kind?: string }).kind === "struct";
86}
87function isTensor(v: RuntimeValue | undefined): v is RuntimeTensor {
88 return typeof v === "object" && v !== null && (v as { kind?: string }).kind === "tensor";
89}
90function isFunction(v: RuntimeValue | undefined): boolean {
91 return typeof v === "object" && v !== null && (v as { kind?: string }).kind === "function";
92}
93function isEmpty(v: RuntimeValue | undefined): boolean {
94 return v === undefined || (isTensor(v) && v.data.length === 0);
95}
97/** A scalar number from a runtime value, or null when it is not one. */
98function scalar(v: RuntimeValue | undefined): number | null {
99 if (typeof v === "number") return v;
100 if (typeof v === "boolean") return v ? 1 : 0;
101 if (isTensor(v) && v.data.length === 1 && (!v.imag || v.imag[0] === 0)) return v.data[0];
102 return null;
103}
105function num(v: RuntimeValue | undefined, what: string, min = -Infinity): number {
106 const s = scalar(v);
107 if (s === null || !isFinite(s)) throw new DesignError(`${what} must be a finite number`);
108 if (s < min) throw new DesignError(`${what} must be at least ${min}`);
109 return s;
110}
112function bool(v: RuntimeValue | undefined, what: string, dflt: boolean): boolean {
113 if (v === undefined || isEmpty(v)) return dflt;
114 const s = scalar(v);
115 if (s === null) throw new DesignError(`${what} must be true or false`);
116 return s !== 0;
117}
119function field(s: RuntimeStruct, name: string): RuntimeValue | undefined {
120 return s.fields.get(name);
121}
123function text(v: RuntimeValue | undefined): string | null {
124 if (typeof v === "string") return v;
125 if (typeof v === "object" && v !== null && (v as { kind?: string }).kind === "char") return (v as { value: string }).value;
126 return null;
127}
129// ---------- Compilation ----------
131/**
132 * Runs the script and checks the `design` struct it leaves in the
133 * workspace. The field functions are not called here; evaluatePlate samples
134 * them on the grid.
135 */
136export function compileDesign(source: string): Design {
137 const vars = runDesignScript(source);
138 const d = vars.design;
139 if (d === undefined) throw new DesignError("the script must fill in a struct named design (design.material, design.bounds, design.thickness, ...)");
140 if (!isStruct(d)) throw new DesignError("design must be a struct");
142 const nameV = field(d, "name");
143 const name = (nameV !== undefined ? text(nameV) : null)?.trim() || "Untitled design";
145 const m = field(d, "material");
2a1a6daDerive the losses from physical constants instead of a prescribed decay curveJeremy Magland 146 if (!isStruct(m)) throw new DesignError("design.material must be a struct with fields E, nu, rho, lossFactor, and the thermal constants alpha, cp, k");
147 const has = (s: RuntimeStruct, k: string) => field(s, k) !== undefined && !isEmpty(field(s, k));
148 const thermalKeys = ["alpha", "cp", "k"];
149 const given = thermalKeys.filter((k) => has(m, k));
150 let thermal: Thermal | null = null;
151 if (given.length === 3) {
152 thermal = { alpha: num(field(m, "alpha"), "design.material.alpha (thermal expansion, 1/K)", 0), cp: num(field(m, "cp"), "design.material.cp (specific heat, J/(kg K))", 1), k: num(field(m, "k"), "design.material.k (thermal conductivity, W/(m K))", 1e-3) };
153 } else if (given.length > 0) {
154 throw new DesignError("design.material needs all three thermal constants for the thermoelastic damping, alpha (1/K), cp (J/(kg K)) and k (W/(m K)), or none of them");
155 }
156 const material: Material = {
157 E: num(field(m, "E"), "design.material.E", 1e6),
158 nu: num(field(m, "nu"), "design.material.nu", 0),
159 rho: num(field(m, "rho"), "design.material.rho", 1),
160 eta: has(m, "lossFactor") ? num(field(m, "lossFactor"), "design.material.lossFactor", 0) : 0,
161 thermal,
162 };
5778036cymbalsim: scripted plate and cymbal designer with a modal linear model and a von Karman GPU modelJeremy Magland 163 if (material.nu >= 0.5) throw new DesignError("design.material.nu must be below 0.5");
2a1a6daDerive the losses from physical constants instead of a prescribed decay curveJeremy Magland 164 if (material.eta >= 0.1) throw new DesignError("design.material.lossFactor must be small (metals have loss factors of 1e-4 to 1e-3)");
165 if (field(d, "loss") !== undefined) throw new DesignError("design.loss is no longer used: the decay of each mode follows from design.material.lossFactor, the thermal constants alpha, cp and k, the radiation of the plate, and the felt of the stand");
166 const temperature = has(d, "temperature") ? num(field(d, "temperature"), "design.temperature (K)", 1) : ROOM_TEMPERATURE;
5778036cymbalsim: scripted plate and cymbal designer with a modal linear model and a von Karman GPU modelJeremy Magland 167
168 const b = field(d, "bounds");
169 if (!isStruct(b)) throw new DesignError("design.bounds must be a struct with fields width, height");
170 const Lx = num(field(b, "width"), "design.bounds.width", 1e-3), Ly = num(field(b, "height"), "design.bounds.height", 1e-3);
172 const inside = field(d, "inside");
173 let hasInside = false;
174 if (!isEmpty(inside)) {
175 if (!isFunction(inside)) throw new DesignError("design.inside must be a function handle @(x, y, r, theta) returning true inside the plate, for example @(x, y, r, theta) r <= D/2");
176 hasInside = true;
177 }
179 const th = field(d, "thickness");
180 if (th === undefined) throw new DesignError("design.thickness is required (a number in meters, or a function handle @(x, y, r, theta))");
181 let thicknessConst: number | null = null;
182 if (!isFunction(th)) {
183 thicknessConst = scalar(th);
184 if (thicknessConst === null || !isFinite(thicknessConst)) throw new DesignError("design.thickness must be a number or a function handle @(x, y, r, theta)");
185 if (thicknessConst <= 0) throw new DesignError("design.thickness must be positive");
186 }
188 const pr = field(d, "profile");
189 let profileConst: number | null = 0;
190 if (pr !== undefined && !isEmpty(pr)) {
191 if (isFunction(pr)) profileConst = null;
192 else {
193 profileConst = scalar(pr);
194 if (profileConst === null || !isFinite(profileConst)) throw new DesignError("design.profile must be a number or a function handle @(x, y, r, theta)");
195 }
196 }
198 const stand = readStand(field(d, "stand"));
2a1a6daDerive the losses from physical constants instead of a prescribed decay curveJeremy Magland 200 return { name, material, Lx, Ly, hasInside, thicknessConst, profileConst, stand, temperature, source };
5778036cymbalsim: scripted plate and cymbal designer with a modal linear model and a von Karman GPU modelJeremy Magland 201}
203function readStand(st: RuntimeValue | undefined): Stand | null {
204 if (st === undefined || isEmpty(st) || st === false) return null;
205 if (!isStruct(st)) throw new DesignError("design.stand must be a struct (design.stand.pad, design.stand.topPad, design.stand.preload), or [] for a free plate");
206 const opt = (s: RuntimeStruct, k: string, what: string, dflt: number, min = -Infinity) => (field(s, k) === undefined || isEmpty(field(s, k)) ? dflt : num(field(s, k), what, min));
207 const padV = field(st, "pad");
208 let pad: Pad = { ...DEFAULT_PAD };
209 if (padV !== undefined && !isEmpty(padV)) {
210 if (!isStruct(padV)) throw new DesignError("design.stand.pad must be a struct with fields innerRadius, outerRadius, thickness, E, lossFactor");
211 pad = {
212 innerRadius: opt(padV, "innerRadius", "design.stand.pad.innerRadius", DEFAULT_PAD.innerRadius, 0),
213 outerRadius: opt(padV, "outerRadius", "design.stand.pad.outerRadius", DEFAULT_PAD.outerRadius, 0),
214 thickness: opt(padV, "thickness", "design.stand.pad.thickness", DEFAULT_PAD.thickness, 1e-5),
215 E: opt(padV, "E", "design.stand.pad.E", DEFAULT_PAD.E, 1),
216 lossFactor: opt(padV, "lossFactor", "design.stand.pad.lossFactor", DEFAULT_PAD.lossFactor, 0),
217 };
218 if (pad.outerRadius <= pad.innerRadius) throw new DesignError("design.stand.pad.outerRadius must exceed innerRadius");
219 }
220 return {
221 x: opt(st, "x", "design.stand.x", 0),
222 y: opt(st, "y", "design.stand.y", 0),
223 pad,
224 topPad: bool(field(st, "topPad"), "design.stand.topPad", true),
225 preload: opt(st, "preload", "design.stand.preload", DEFAULT_PRELOAD, 0),
226 };
227}
229// ---------- Evaluation on a grid ----------
231/** Subtracts the weighted least-squares plane a + b x + c y from f over the plate nodes. */
232export function removePlane(f: Float64Array, g: Grid): void {
233 let sw = 0, sx = 0, sy = 0, sxx = 0, sxy = 0, syy = 0, sf = 0, sxf = 0, syf = 0;
234 for (let j = 0; j < g.ny; j++) {
235 for (let i = 0; i < g.nx; i++) {
236 const wgt = nodeWeight(g, i, j);
237 if (wgt === 0) continue;
238 const x = nodeX(g, i), y = nodeY(g, j), v = f[j * g.nx + i];
239 sw += wgt; sx += wgt * x; sy += wgt * y;
240 sxx += wgt * x * x; sxy += wgt * x * y; syy += wgt * y * y;
241 sf += wgt * v; sxf += wgt * x * v; syf += wgt * y * v;
242 }
243 }
244 if (sw === 0) return;
245 const det = sw * (sxx * syy - sxy * sxy) - sx * (sx * syy - sxy * sy) + sy * (sx * sxy - sxx * sy);
246 if (Math.abs(det) < 1e-300) return;
247 const a = (sf * (sxx * syy - sxy * sxy) - sx * (sxf * syy - sxy * syf) + sy * (sxf * sxy - sxx * syf)) / det;
248 const b = (sw * (sxf * syy - sxy * syf) - sf * (sx * syy - sxy * sy) + sy * (sx * syf - sxf * sy)) / det;
249 const c = (sw * (sxx * syf - sxf * sxy) - sx * (sx * syf - sxf * sy) + sf * (sx * sxy - sxx * sy)) / det;
250 for (let j = 0; j < g.ny; j++) for (let i = 0; i < g.nx; i++) f[j * g.nx + i] -= a + b * nodeX(g, i) + c * nodeY(g, j);
251}
253/** The trailer appended to the script to sample the fields on the grid (all names start with cymbalsim_). */
254function trailer(d: Design, g: Grid): string {
255 const fmt = (v: number) => v.toPrecision(17);
256 return [
257 "",
258 "% ---- appended by the simulator: sample the fields on the grid ----",
259 `cymbalsim_nx = ${g.nx}; cymbalsim_ny = ${g.ny};`,
260 `cymbalsim_hx = ${fmt(g.hx)}; cymbalsim_hy = ${fmt(g.hy)};`,
261 `[cymbalsim_X, cymbalsim_Y] = meshgrid(((0:cymbalsim_nx-1) - (cymbalsim_nx-1)/2) * cymbalsim_hx, ((0:cymbalsim_ny-1) - (cymbalsim_ny-1)/2) * cymbalsim_hy);`,
262 "cymbalsim_R = hypot(cymbalsim_X, cymbalsim_Y); cymbalsim_T = atan2(cymbalsim_Y, cymbalsim_X);",
263 "cymbalsim_H = cymbalsim_field(design.thickness, 'thickness', cymbalsim_X, cymbalsim_Y, cymbalsim_R, cymbalsim_T);",
264 d.profileConst === null
265 ? "cymbalsim_Z = cymbalsim_field(design.profile, 'profile', cymbalsim_X, cymbalsim_Y, cymbalsim_R, cymbalsim_T);"
266 : `cymbalsim_Z = ${fmt(d.profileConst)} * ones(cymbalsim_ny, cymbalsim_nx);`,
267 d.hasInside
268 ? [
269 `[cymbalsim_XC, cymbalsim_YC] = meshgrid(((0:cymbalsim_nx-2) - (cymbalsim_nx-2)/2) * cymbalsim_hx, ((0:cymbalsim_ny-2) - (cymbalsim_ny-2)/2) * cymbalsim_hy);`,
270 "cymbalsim_IN = cymbalsim_field(design.inside, 'inside', cymbalsim_XC, cymbalsim_YC, hypot(cymbalsim_XC, cymbalsim_YC), atan2(cymbalsim_YC, cymbalsim_XC));",
271 ].join("\n")
272 : "",
273 "",
274 ].join("\n");
275}
277/** A real [rows, cols] matrix from the workspace as a Float64Array in column-major order. */
278function matrix(vars: Record<string, RuntimeValue>, name: string, rows: number, cols: number, what: string): Float64Array {
279 const v = vars[name];
280 if (!isTensor(v) || v.shape.length !== 2 || v.shape[0] !== rows || v.shape[1] !== cols) throw new DesignError(`${what} did not produce a ${rows} x ${cols} matrix`);
281 if (v.imag && v.imag.some((x) => x !== 0)) throw new DesignError(`${what} returned complex values`);
282 return v.data;
283}
285/**
286 * Samples the design on a grid of about the requested spacing: the mask from
287 * the outline at the cell centers, the thickness at the nodes (which must be
288 * positive on the plate), the profile at the nodes with its mean plane
2a1a6daDerive the losses from physical constants instead of a prescribed decay curveJeremy Magland 289 * removed. Only the slopes of
5778036cymbalsim: scripted plate and cymbal designer with a modal linear model and a von Karman GPU modelJeremy Magland 290 * the profile enter the physics, so its mean is immaterial, but its tilt is
291 * not: the von Karman strains are not invariant under rotation, and a tilted
292 * stress-free shape would add a spurious membrane coupling.
293 */
294export function evaluatePlate(d: Design, spacing: number): Plate {
295 const full = makeGrid(d.Lx, d.Ly, spacing);
296 const { nx, ny } = full;
297 const vars = runDesignScript(d.source + trailer(d, full), d.source.split("\n").length);
298 // meshgrid matrices are [ny, nx] in column-major order: entry (i, j) sits at i * ny + j.
299 const H = matrix(vars, "cymbalsim_H", ny, nx, "thickness");
300 const Z = matrix(vars, "cymbalsim_Z", ny, nx, "profile");
301 let g = full;
302 if (d.hasInside) {
303 const IN = matrix(vars, "cymbalsim_IN", ny - 1, nx - 1, "inside");
304 g = withCellMask(full, (ci, cj) => IN[ci * (ny - 1) + cj] !== 0);
305 }
306 const h = new Float64Array(g.n), w0 = new Float64Array(g.n);
307 let any = false;
308 for (let j = 0; j < ny; j++) {
309 for (let i = 0; i < nx; i++) {
310 if (!insideNode(g, i, j)) continue;
311 any = true;
312 const k = j * nx + i, m = i * ny + j;
313 const x = nodeX(g, i), y = nodeY(g, j);
314 const at = `(${x.toFixed(4)}, ${y.toFixed(4)})`;
315 if (!isFinite(H[m])) throw new DesignError(`thickness is ${H[m]} at ${at}`);
316 if (H[m] <= 0) throw new DesignError(`thickness must be positive; it is ${H[m]} at ${at}`);
317 if (!isFinite(Z[m])) throw new DesignError(`profile is ${Z[m]} at ${at}`);
318 h[k] = H[m];
319 w0[k] = Z[m];
320 }
321 }
322 if (!any) throw new DesignError("the outline contains no grid cells; enlarge it or reduce the grid spacing");
323 removePlane(w0, g);
324 for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) if (!insideNode(g, i, j)) w0[j * nx + i] = 0;
2a1a6daDerive the losses from physical constants instead of a prescribed decay curveJeremy Magland 325 return { name: d.name, Lx: d.Lx, Ly: d.Ly, grid: g, mat: d.material, h, w0, stand: d.stand, temperature: d.temperature };
5778036cymbalsim: scripted plate and cymbal designer with a modal linear model and a von Karman GPU modelJeremy Magland 326}
328/** Whether the plate is flat (no profile), in which case bending and in-plane motion decouple in the linear model. */
329export function isFlat(pl: Plate): boolean {
330 for (let k = 0; k < pl.w0.length; k++) if (pl.w0[k] !== 0) return false;
331 return true;
332}
334/** Peak-to-peak height and the largest slope of the profile over the plate nodes. */
335export function profileStats(pl: Plate): { peakToPeak: number; maxSlope: number } {
336 const g = pl.grid, w0 = pl.w0;
337 let lo = Infinity, hi = -Infinity, maxSlope = 0;
338 const at = (i: number, j: number) => w0[j * g.nx + i];
339 const slope = (i: number, j: number, di: number, dj: number, hg: number) => {
340 const hasP = insideNode(g, i + di, j + dj), hasM = insideNode(g, i - di, j - dj);
341 if (hasP && hasM) return (at(i + di, j + dj) - at(i - di, j - dj)) / (2 * hg);
342 if (hasP) return (at(i + di, j + dj) - at(i, j)) / hg;
343 if (hasM) return (at(i, j) - at(i - di, j - dj)) / hg;
344 return 0;
345 };
346 for (let j = 0; j < g.ny; j++) {
347 for (let i = 0; i < g.nx; i++) {
348 if (!insideNode(g, i, j)) continue;
349 const v = at(i, j);
350 lo = Math.min(lo, v); hi = Math.max(hi, v);
351 maxSlope = Math.max(maxSlope, Math.hypot(slope(i, j, 1, 0, g.hx), slope(i, j, 0, 1, g.hy)));
352 }
353 }
354 return { peakToPeak: isFinite(hi - lo) ? hi - lo : 0, maxSlope };
355}