// The design: a MATLAB-syntax script, run by numbl, that fills in a struct // named `design` with the material, the bounding box, the outline, the // thickness field, the stress-free profile, the stand, and the losses. // The outline, the thickness, and the profile are function handles // @(x, y, r, theta), vectorized over grid matrices (or plain numbers). // compileDesign runs the script and checks the struct; evaluatePlate runs it // again with a short trailer that samples the fields on meshgrid matrices of // the requested spacing, inside numbl, and reads the matrices back. // // Lengths are meters throughout. A script is self-contained: nothing is in // scope but numbl's own functions and whatever the script defines itself, // including ordinary MATLAB functions written at its bottom (numbl hoists // them, so the trailer may still follow them). import { executeCode, type RuntimeValue, type RuntimeTensor, type RuntimeStruct } from "numbl"; import { RUNTIME_FILES } from "./mruntime.ts"; import { LOSS_FREQS, constantLoss, defaultLoss, lossFromTable } from "./loss.ts"; import { type Grid, type Loss, type Material, type Pad, type Plate, type Stand, insideNode, makeGrid, nodeWeight, nodeX, nodeY, withCellMask, } from "./params.ts"; /** A compiled design: the checked contents of the `design` struct, plus the script that produced it. */ export interface Design { name: string; material: Material; Lx: number; Ly: number; /** Whether the script gave an outline; without one the plate is the whole bounding box. */ hasInside: boolean; /** The thickness when it is a plain number; null for a function. */ thicknessConst: number | null; /** The profile when it is a plain number (or absent); null for a function. */ profileConst: number | null; stand: Stand | null; /** The losses when they do not need the script (a number, a table, or the default); null for a function handle. */ lossConst: Loss | null; source: string; } /** Defaults of the pad of a stand, a typical felt washer. */ export const DEFAULT_PAD: Pad = { innerRadius: 7e-3, outerRadius: 20e-3, thickness: 12e-3, E: 0.5e6, lossFactor: 0.3 }; export const DEFAULT_PRELOAD = 1e-3; /** Message of an error thrown by the script or by the checks. */ export class DesignError extends Error {} const FILE_NAME = "design.m"; /** * Runs a design script and returns its workspace variables. `userLines` is * the length of the part of the source the user wrote, so that an error in * the appended trailer is not reported at a line the user cannot see. */ export function runDesignScript(source: string, userLines = Infinity): Record { try { return executeCode(source, { displayResults: false, onOutput: () => {} }, RUNTIME_FILES, FILE_NAME).variableValues; } catch (e) { throw new DesignError(describeError(e, Math.min(source.split("\n").length, userLines))); } } function describeError(e: unknown, userLines: number): string { if (!(e instanceof Error)) return String(e); const { line, file } = e as { line?: unknown; file?: unknown }; const inScript = file === undefined || file === null || file === FILE_NAME; const where = inScript && typeof line === "number" && line >= 1 && line <= userLines ? `line ${line}: ` : ""; return `${where}${e.message}`; } // ---------- Reading runtime values ---------- function isStruct(v: RuntimeValue | undefined): v is RuntimeStruct { return typeof v === "object" && v !== null && (v as { kind?: string }).kind === "struct"; } function isTensor(v: RuntimeValue | undefined): v is RuntimeTensor { return typeof v === "object" && v !== null && (v as { kind?: string }).kind === "tensor"; } function isFunction(v: RuntimeValue | undefined): boolean { return typeof v === "object" && v !== null && (v as { kind?: string }).kind === "function"; } function isEmpty(v: RuntimeValue | undefined): boolean { return v === undefined || (isTensor(v) && v.data.length === 0); } /** A scalar number from a runtime value, or null when it is not one. */ function scalar(v: RuntimeValue | undefined): number | null { if (typeof v === "number") return v; if (typeof v === "boolean") return v ? 1 : 0; if (isTensor(v) && v.data.length === 1 && (!v.imag || v.imag[0] === 0)) return v.data[0]; return null; } function num(v: RuntimeValue | undefined, what: string, min = -Infinity): number { const s = scalar(v); if (s === null || !isFinite(s)) throw new DesignError(`${what} must be a finite number`); if (s < min) throw new DesignError(`${what} must be at least ${min}`); return s; } function bool(v: RuntimeValue | undefined, what: string, dflt: boolean): boolean { if (v === undefined || isEmpty(v)) return dflt; const s = scalar(v); if (s === null) throw new DesignError(`${what} must be true or false`); return s !== 0; } function field(s: RuntimeStruct, name: string): RuntimeValue | undefined { return s.fields.get(name); } function text(v: RuntimeValue | undefined): string | null { if (typeof v === "string") return v; if (typeof v === "object" && v !== null && (v as { kind?: string }).kind === "char") return (v as { value: string }).value; return null; } // ---------- Compilation ---------- /** * Runs the script and checks the `design` struct it leaves in the * workspace. The field functions are not called here; evaluatePlate samples * them on the grid. */ export function compileDesign(source: string): Design { const vars = runDesignScript(source); const d = vars.design; if (d === undefined) throw new DesignError("the script must fill in a struct named design (design.material, design.bounds, design.thickness, ...)"); if (!isStruct(d)) throw new DesignError("design must be a struct"); const nameV = field(d, "name"); const name = (nameV !== undefined ? text(nameV) : null)?.trim() || "Untitled design"; const m = field(d, "material"); if (!isStruct(m)) throw new DesignError("design.material must be a struct with fields E, nu, rho"); const material: Material = { E: num(field(m, "E"), "design.material.E", 1e6), nu: num(field(m, "nu"), "design.material.nu", 0), rho: num(field(m, "rho"), "design.material.rho", 1) }; if (material.nu >= 0.5) throw new DesignError("design.material.nu must be below 0.5"); const b = field(d, "bounds"); if (!isStruct(b)) throw new DesignError("design.bounds must be a struct with fields width, height"); const Lx = num(field(b, "width"), "design.bounds.width", 1e-3), Ly = num(field(b, "height"), "design.bounds.height", 1e-3); const inside = field(d, "inside"); let hasInside = false; if (!isEmpty(inside)) { 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"); hasInside = true; } const th = field(d, "thickness"); if (th === undefined) throw new DesignError("design.thickness is required (a number in meters, or a function handle @(x, y, r, theta))"); let thicknessConst: number | null = null; if (!isFunction(th)) { thicknessConst = scalar(th); if (thicknessConst === null || !isFinite(thicknessConst)) throw new DesignError("design.thickness must be a number or a function handle @(x, y, r, theta)"); if (thicknessConst <= 0) throw new DesignError("design.thickness must be positive"); } const pr = field(d, "profile"); let profileConst: number | null = 0; if (pr !== undefined && !isEmpty(pr)) { if (isFunction(pr)) profileConst = null; else { profileConst = scalar(pr); if (profileConst === null || !isFinite(profileConst)) throw new DesignError("design.profile must be a number or a function handle @(x, y, r, theta)"); } } const stand = readStand(field(d, "stand")); const lossConst = readLoss(field(d, "loss")); return { name, material, Lx, Ly, hasInside, thicknessConst, profileConst, stand, lossConst, source }; } function readStand(st: RuntimeValue | undefined): Stand | null { if (st === undefined || isEmpty(st) || st === false) return null; 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"); 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)); const padV = field(st, "pad"); let pad: Pad = { ...DEFAULT_PAD }; if (padV !== undefined && !isEmpty(padV)) { if (!isStruct(padV)) throw new DesignError("design.stand.pad must be a struct with fields innerRadius, outerRadius, thickness, E, lossFactor"); pad = { innerRadius: opt(padV, "innerRadius", "design.stand.pad.innerRadius", DEFAULT_PAD.innerRadius, 0), outerRadius: opt(padV, "outerRadius", "design.stand.pad.outerRadius", DEFAULT_PAD.outerRadius, 0), thickness: opt(padV, "thickness", "design.stand.pad.thickness", DEFAULT_PAD.thickness, 1e-5), E: opt(padV, "E", "design.stand.pad.E", DEFAULT_PAD.E, 1), lossFactor: opt(padV, "lossFactor", "design.stand.pad.lossFactor", DEFAULT_PAD.lossFactor, 0), }; if (pad.outerRadius <= pad.innerRadius) throw new DesignError("design.stand.pad.outerRadius must exceed innerRadius"); } return { x: opt(st, "x", "design.stand.x", 0), y: opt(st, "y", "design.stand.y", 0), pad, topPad: bool(field(st, "topPad"), "design.stand.topPad", true), preload: opt(st, "preload", "design.stand.preload", DEFAULT_PRELOAD, 0), }; } /** The losses when they can be read without the script: null when T60 is a function handle. */ function readLoss(lo: RuntimeValue | undefined): Loss | null { if (lo === undefined || isEmpty(lo)) return defaultLoss(); if (!isStruct(lo)) throw new DesignError("design.loss must be a struct with the field T60: a decay time in seconds, a table [f T60; ...], or a function handle @(f)"); const t = field(lo, "T60"); if (t === undefined || isEmpty(t)) return defaultLoss(); if (isFunction(t)) return null; const s = scalar(t); if (s !== null) { if (!(s > 0) || !isFinite(s)) throw new DesignError("design.loss.T60 must be a positive decay time in seconds"); return constantLoss(s); } if (isTensor(t) && t.shape.length === 2 && t.shape[1] === 2 && t.shape[0] >= 1) { const rows = t.shape[0]; const fs: number[] = [], ts: number[] = []; for (let r = 0; r < rows; r++) { const f = t.data[r], t60 = t.data[rows + r]; // column-major if (!(f > 0) || !(t60 > 0) || !isFinite(f) || !isFinite(t60)) throw new DesignError("design.loss.T60 table rows must be [frequency T60] with positive values"); fs.push(f); ts.push(t60); } return lossFromTable(fs, ts); } throw new DesignError("design.loss.T60 must be a number, a two-column table [f T60; ...], or a function handle @(f)"); } // ---------- Evaluation on a grid ---------- /** Subtracts the weighted least-squares plane a + b x + c y from f over the plate nodes. */ export function removePlane(f: Float64Array, g: Grid): void { let sw = 0, sx = 0, sy = 0, sxx = 0, sxy = 0, syy = 0, sf = 0, sxf = 0, syf = 0; for (let j = 0; j < g.ny; j++) { for (let i = 0; i < g.nx; i++) { const wgt = nodeWeight(g, i, j); if (wgt === 0) continue; const x = nodeX(g, i), y = nodeY(g, j), v = f[j * g.nx + i]; sw += wgt; sx += wgt * x; sy += wgt * y; sxx += wgt * x * x; sxy += wgt * x * y; syy += wgt * y * y; sf += wgt * v; sxf += wgt * x * v; syf += wgt * y * v; } } if (sw === 0) return; const det = sw * (sxx * syy - sxy * sxy) - sx * (sx * syy - sxy * sy) + sy * (sx * sxy - sxx * sy); if (Math.abs(det) < 1e-300) return; const a = (sf * (sxx * syy - sxy * sxy) - sx * (sxf * syy - sxy * syf) + sy * (sxf * sxy - sxx * syf)) / det; const b = (sw * (sxf * syy - sxy * syf) - sf * (sx * syy - sxy * sy) + sy * (sx * syf - sxf * sy)) / det; const c = (sw * (sxx * syf - sxf * sxy) - sx * (sx * syf - sxf * sy) + sf * (sx * sxy - sxx * sy)) / det; 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); } /** The trailer appended to the script to sample the fields on the grid (all names start with cymbalsim_). */ function trailer(d: Design, g: Grid): string { const fmt = (v: number) => v.toPrecision(17); return [ "", "% ---- appended by the simulator: sample the fields on the grid ----", `cymbalsim_nx = ${g.nx}; cymbalsim_ny = ${g.ny};`, `cymbalsim_hx = ${fmt(g.hx)}; cymbalsim_hy = ${fmt(g.hy)};`, `[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);`, "cymbalsim_R = hypot(cymbalsim_X, cymbalsim_Y); cymbalsim_T = atan2(cymbalsim_Y, cymbalsim_X);", "cymbalsim_H = cymbalsim_field(design.thickness, 'thickness', cymbalsim_X, cymbalsim_Y, cymbalsim_R, cymbalsim_T);", d.profileConst === null ? "cymbalsim_Z = cymbalsim_field(design.profile, 'profile', cymbalsim_X, cymbalsim_Y, cymbalsim_R, cymbalsim_T);" : `cymbalsim_Z = ${fmt(d.profileConst)} * ones(cymbalsim_ny, cymbalsim_nx);`, d.hasInside ? [ `[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);`, "cymbalsim_IN = cymbalsim_field(design.inside, 'inside', cymbalsim_XC, cymbalsim_YC, hypot(cymbalsim_XC, cymbalsim_YC), atan2(cymbalsim_YC, cymbalsim_XC));", ].join("\n") : "", d.lossConst === null ? [`cymbalsim_F = [${Array.from(LOSS_FREQS, fmt).join(" ")}];`, "cymbalsim_T60 = cymbalsim_t60(design.loss.T60, cymbalsim_F);"].join("\n") : "", "", ].join("\n"); } /** A real [rows, cols] matrix from the workspace as a Float64Array in column-major order. */ function matrix(vars: Record, name: string, rows: number, cols: number, what: string): Float64Array { const v = vars[name]; 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`); if (v.imag && v.imag.some((x) => x !== 0)) throw new DesignError(`${what} returned complex values`); return v.data; } /** * Samples the design on a grid of about the requested spacing: the mask from * the outline at the cell centers, the thickness at the nodes (which must be * positive on the plate), the profile at the nodes with its mean plane * removed, and the decay times when they are a function. Only the slopes of * the profile enter the physics, so its mean is immaterial, but its tilt is * not: the von Karman strains are not invariant under rotation, and a tilted * stress-free shape would add a spurious membrane coupling. */ export function evaluatePlate(d: Design, spacing: number): Plate { const full = makeGrid(d.Lx, d.Ly, spacing); const { nx, ny } = full; const vars = runDesignScript(d.source + trailer(d, full), d.source.split("\n").length); // meshgrid matrices are [ny, nx] in column-major order: entry (i, j) sits at i * ny + j. const H = matrix(vars, "cymbalsim_H", ny, nx, "thickness"); const Z = matrix(vars, "cymbalsim_Z", ny, nx, "profile"); let g = full; if (d.hasInside) { const IN = matrix(vars, "cymbalsim_IN", ny - 1, nx - 1, "inside"); g = withCellMask(full, (ci, cj) => IN[ci * (ny - 1) + cj] !== 0); } let loss = d.lossConst; if (loss === null) { const T = matrix(vars, "cymbalsim_T60", 1, LOSS_FREQS.length, "design.loss.T60"); for (let i = 0; i < T.length; i++) if (!(T[i] > 0) || !isFinite(T[i])) throw new DesignError(`design.loss.T60 must be positive; it is ${T[i]} at ${LOSS_FREQS[i].toFixed(0)} Hz`); loss = { freqs: LOSS_FREQS, t60: Float64Array.from(T) }; } const h = new Float64Array(g.n), w0 = new Float64Array(g.n); let any = false; for (let j = 0; j < ny; j++) { for (let i = 0; i < nx; i++) { if (!insideNode(g, i, j)) continue; any = true; const k = j * nx + i, m = i * ny + j; const x = nodeX(g, i), y = nodeY(g, j); const at = `(${x.toFixed(4)}, ${y.toFixed(4)})`; if (!isFinite(H[m])) throw new DesignError(`thickness is ${H[m]} at ${at}`); if (H[m] <= 0) throw new DesignError(`thickness must be positive; it is ${H[m]} at ${at}`); if (!isFinite(Z[m])) throw new DesignError(`profile is ${Z[m]} at ${at}`); h[k] = H[m]; w0[k] = Z[m]; } } if (!any) throw new DesignError("the outline contains no grid cells; enlarge it or reduce the grid spacing"); removePlane(w0, g); for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) if (!insideNode(g, i, j)) w0[j * nx + i] = 0; return { name: d.name, Lx: d.Lx, Ly: d.Ly, grid: g, mat: d.material, h, w0, stand: d.stand, loss }; } /** Whether the plate is flat (no profile), in which case bending and in-plane motion decouple in the linear model. */ export function isFlat(pl: Plate): boolean { for (let k = 0; k < pl.w0.length; k++) if (pl.w0[k] !== 0) return false; return true; } /** Peak-to-peak height and the largest slope of the profile over the plate nodes. */ export function profileStats(pl: Plate): { peakToPeak: number; maxSlope: number } { const g = pl.grid, w0 = pl.w0; let lo = Infinity, hi = -Infinity, maxSlope = 0; const at = (i: number, j: number) => w0[j * g.nx + i]; const slope = (i: number, j: number, di: number, dj: number, hg: number) => { const hasP = insideNode(g, i + di, j + dj), hasM = insideNode(g, i - di, j - dj); if (hasP && hasM) return (at(i + di, j + dj) - at(i - di, j - dj)) / (2 * hg); if (hasP) return (at(i + di, j + dj) - at(i, j)) / hg; if (hasM) return (at(i, j) - at(i - di, j - dj)) / hg; return 0; }; for (let j = 0; j < g.ny; j++) { for (let i = 0; i < g.nx; i++) { if (!insideNode(g, i, j)) continue; const v = at(i, j); lo = Math.min(lo, v); hi = Math.max(hi, v); maxSlope = Math.max(maxSlope, Math.hypot(slope(i, j, 1, 0, g.hx), slope(i, j, 0, 1, g.hy))); } } return { peakToPeak: isFinite(hi - lo) ? hi - lo : 0, maxSlope }; }