/ proof-of-concept / cymbalsim
Sign in
proof-of-concept / cymbalsim
cymbalsim / src / design.ts
313 lines · 15.1 KBBlameHistoryRaw
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
3// thickness field, the stress-free profile, and the loss constants of the
4// material (from which the decay is derived, loss.ts).
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 Plate,
22 type Thermal,
23 ROOM_TEMPERATURE,
24 insideNode,
25 makeGrid,
26 nodeWeight,
27 nodeX,
28 nodeY,
29 withCellMask,
30} from "./params.ts";
32/** A compiled design: the checked contents of the `design` struct, plus the script that produced it. */
33export interface Design {
34 name: string;
35 material: Material;
36 Lx: number;
37 Ly: number;
38 /** Whether the script gave an outline; without one the plate is the whole bounding box. */
39 hasInside: boolean;
40 /** The thickness when it is a plain number; null for a function. */
41 thicknessConst: number | null;
42 /** The profile when it is a plain number (or absent); null for a function. */
43 profileConst: number | null;
44 /** Temperature of the plate [K], for the thermoelastic damping. */
45 temperature: number;
46 source: string;
49/** Message of an error thrown by the script or by the checks. */
50export class DesignError extends Error {}
52const FILE_NAME = "design.m";
54/**
55 * Runs a design script and returns its workspace variables. `userLines` is
56 * the length of the part of the source the user wrote, so that an error in
57 * the appended trailer is not reported at a line the user cannot see.
58 */
59export function runDesignScript(source: string, userLines = Infinity): Record<string, RuntimeValue> {
60 try {
61 return executeCode(source, { displayResults: false, onOutput: () => {} }, RUNTIME_FILES, FILE_NAME).variableValues;
62 } catch (e) {
63 throw new DesignError(describeError(e, Math.min(source.split("\n").length, userLines)));
64 }
67function describeError(e: unknown, userLines: number): string {
68 if (!(e instanceof Error)) return String(e);
69 const { line, file } = e as { line?: unknown; file?: unknown };
70 const inScript = file === undefined || file === null || file === FILE_NAME;
71 const where = inScript && typeof line === "number" && line >= 1 && line <= userLines ? `line ${line}: ` : "";
72 return `${where}${e.message}`;
75// ---------- Reading runtime values ----------
77function isStruct(v: RuntimeValue | undefined): v is RuntimeStruct {
78 return typeof v === "object" && v !== null && (v as { kind?: string }).kind === "struct";
80function isTensor(v: RuntimeValue | undefined): v is RuntimeTensor {
81 return typeof v === "object" && v !== null && (v as { kind?: string }).kind === "tensor";
83function isFunction(v: RuntimeValue | undefined): boolean {
84 return typeof v === "object" && v !== null && (v as { kind?: string }).kind === "function";
86function isEmpty(v: RuntimeValue | undefined): boolean {
87 return v === undefined || (isTensor(v) && v.data.length === 0);
90/** A scalar number from a runtime value, or null when it is not one. */
91function scalar(v: RuntimeValue | undefined): number | null {
92 if (typeof v === "number") return v;
93 if (typeof v === "boolean") return v ? 1 : 0;
94 if (isTensor(v) && v.data.length === 1 && (!v.imag || v.imag[0] === 0)) return v.data[0];
95 return null;
98function num(v: RuntimeValue | undefined, what: string, min = -Infinity): number {
99 const s = scalar(v);
100 if (s === null || !isFinite(s)) throw new DesignError(`${what} must be a finite number`);
101 if (s < min) throw new DesignError(`${what} must be at least ${min}`);
102 return s;
105function field(s: RuntimeStruct, name: string): RuntimeValue | undefined {
106 return s.fields.get(name);
109function text(v: RuntimeValue | undefined): string | null {
110 if (typeof v === "string") return v;
111 if (typeof v === "object" && v !== null && (v as { kind?: string }).kind === "char") return (v as { value: string }).value;
112 return null;
115// ---------- Compilation ----------
117/**
118 * Runs the script and checks the `design` struct it leaves in the
119 * workspace. The field functions are not called here; evaluatePlate samples
120 * them on the grid.
121 */
122export function compileDesign(source: string): Design {
123 const vars = runDesignScript(source);
124 const d = vars.design;
125 if (d === undefined) throw new DesignError("the script must fill in a struct named design (design.material, design.bounds, design.thickness, ...)");
126 if (!isStruct(d)) throw new DesignError("design must be a struct");
128 const nameV = field(d, "name");
129 const name = (nameV !== undefined ? text(nameV) : null)?.trim() || "Untitled design";
131 const m = field(d, "material");
132 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");
133 const has = (s: RuntimeStruct, k: string) => field(s, k) !== undefined && !isEmpty(field(s, k));
134 const thermalKeys = ["alpha", "cp", "k"];
135 const given = thermalKeys.filter((k) => has(m, k));
136 let thermal: Thermal | null = null;
137 if (given.length === 3) {
138 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) };
139 } else if (given.length > 0) {
140 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");
141 }
142 const material: Material = {
143 E: num(field(m, "E"), "design.material.E", 1e6),
144 nu: num(field(m, "nu"), "design.material.nu", 0),
145 rho: num(field(m, "rho"), "design.material.rho", 1),
146 eta: has(m, "lossFactor") ? num(field(m, "lossFactor"), "design.material.lossFactor", 0) : 0,
147 thermal,
148 };
149 if (material.nu >= 0.5) throw new DesignError("design.material.nu must be below 0.5");
150 if (material.eta >= 0.1) throw new DesignError("design.material.lossFactor must be small (metals have loss factors of 1e-4 to 1e-3)");
151 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, and the radiation of the plate");
152 const temperature = has(d, "temperature") ? num(field(d, "temperature"), "design.temperature (K)", 1) : ROOM_TEMPERATURE;
154 const b = field(d, "bounds");
155 if (!isStruct(b)) throw new DesignError("design.bounds must be a struct with fields width, height");
156 const Lx = num(field(b, "width"), "design.bounds.width", 1e-3), Ly = num(field(b, "height"), "design.bounds.height", 1e-3);
158 const inside = field(d, "inside");
159 let hasInside = false;
160 if (!isEmpty(inside)) {
161 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");
162 hasInside = true;
163 }
165 const th = field(d, "thickness");
166 if (th === undefined) throw new DesignError("design.thickness is required (a number in meters, or a function handle @(x, y, r, theta))");
167 let thicknessConst: number | null = null;
168 if (!isFunction(th)) {
169 thicknessConst = scalar(th);
170 if (thicknessConst === null || !isFinite(thicknessConst)) throw new DesignError("design.thickness must be a number or a function handle @(x, y, r, theta)");
171 if (thicknessConst <= 0) throw new DesignError("design.thickness must be positive");
172 }
174 const pr = field(d, "profile");
175 let profileConst: number | null = 0;
176 if (pr !== undefined && !isEmpty(pr)) {
177 if (isFunction(pr)) profileConst = null;
178 else {
179 profileConst = scalar(pr);
180 if (profileConst === null || !isFinite(profileConst)) throw new DesignError("design.profile must be a number or a function handle @(x, y, r, theta)");
181 }
182 }
184 return { name, material, Lx, Ly, hasInside, thicknessConst, profileConst, temperature, source };
187// ---------- Evaluation on a grid ----------
189/** Subtracts the weighted least-squares plane a + b x + c y from f over the plate nodes. */
190export function removePlane(f: Float64Array, g: Grid): void {
191 let sw = 0, sx = 0, sy = 0, sxx = 0, sxy = 0, syy = 0, sf = 0, sxf = 0, syf = 0;
192 for (let j = 0; j < g.ny; j++) {
193 for (let i = 0; i < g.nx; i++) {
194 const wgt = nodeWeight(g, i, j);
195 if (wgt === 0) continue;
196 const x = nodeX(g, i), y = nodeY(g, j), v = f[j * g.nx + i];
197 sw += wgt; sx += wgt * x; sy += wgt * y;
198 sxx += wgt * x * x; sxy += wgt * x * y; syy += wgt * y * y;
199 sf += wgt * v; sxf += wgt * x * v; syf += wgt * y * v;
200 }
201 }
202 if (sw === 0) return;
203 const det = sw * (sxx * syy - sxy * sxy) - sx * (sx * syy - sxy * sy) + sy * (sx * sxy - sxx * sy);
204 if (Math.abs(det) < 1e-300) return;
205 const a = (sf * (sxx * syy - sxy * sxy) - sx * (sxf * syy - sxy * syf) + sy * (sxf * sxy - sxx * syf)) / det;
206 const b = (sw * (sxf * syy - sxy * syf) - sf * (sx * syy - sxy * sy) + sy * (sx * syf - sxf * sy)) / det;
207 const c = (sw * (sxx * syf - sxf * sxy) - sx * (sx * syf - sxf * sy) + sf * (sx * sxy - sxx * sy)) / det;
208 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);
211/** The trailer appended to the script to sample the fields on the grid (all names start with cymbalsim_). */
212function trailer(d: Design, g: Grid): string {
213 const fmt = (v: number) => v.toPrecision(17);
214 return [
215 "",
216 "% ---- appended by the simulator: sample the fields on the grid ----",
217 `cymbalsim_nx = ${g.nx}; cymbalsim_ny = ${g.ny};`,
218 `cymbalsim_hx = ${fmt(g.hx)}; cymbalsim_hy = ${fmt(g.hy)};`,
219 `[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);`,
220 "cymbalsim_R = hypot(cymbalsim_X, cymbalsim_Y); cymbalsim_T = atan2(cymbalsim_Y, cymbalsim_X);",
221 "cymbalsim_H = cymbalsim_field(design.thickness, 'thickness', cymbalsim_X, cymbalsim_Y, cymbalsim_R, cymbalsim_T);",
222 d.profileConst === null
223 ? "cymbalsim_Z = cymbalsim_field(design.profile, 'profile', cymbalsim_X, cymbalsim_Y, cymbalsim_R, cymbalsim_T);"
224 : `cymbalsim_Z = ${fmt(d.profileConst)} * ones(cymbalsim_ny, cymbalsim_nx);`,
225 d.hasInside
226 ? [
227 `[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);`,
228 "cymbalsim_IN = cymbalsim_field(design.inside, 'inside', cymbalsim_XC, cymbalsim_YC, hypot(cymbalsim_XC, cymbalsim_YC), atan2(cymbalsim_YC, cymbalsim_XC));",
229 ].join("\n")
230 : "",
231 "",
232 ].join("\n");
235/** A real [rows, cols] matrix from the workspace as a Float64Array in column-major order. */
236function matrix(vars: Record<string, RuntimeValue>, name: string, rows: number, cols: number, what: string): Float64Array {
237 const v = vars[name];
238 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`);
239 if (v.imag && v.imag.some((x) => x !== 0)) throw new DesignError(`${what} returned complex values`);
240 return v.data;
243/**
244 * Samples the design on a grid of about the requested spacing: the mask from
245 * the outline at the cell centers, the thickness at the nodes (which must be
246 * positive on the plate), the profile at the nodes with its mean plane
247 * removed. Only the slopes of
248 * the profile enter the physics, so its mean is immaterial, but its tilt is
249 * not: the von Karman strains are not invariant under rotation, and a tilted
250 * stress-free shape would add a spurious membrane coupling.
251 */
252export function evaluatePlate(d: Design, spacing: number): Plate {
253 const full = makeGrid(d.Lx, d.Ly, spacing);
254 const { nx, ny } = full;
255 const vars = runDesignScript(d.source + trailer(d, full), d.source.split("\n").length);
256 // meshgrid matrices are [ny, nx] in column-major order: entry (i, j) sits at i * ny + j.
257 const H = matrix(vars, "cymbalsim_H", ny, nx, "thickness");
258 const Z = matrix(vars, "cymbalsim_Z", ny, nx, "profile");
259 let g = full;
260 if (d.hasInside) {
261 const IN = matrix(vars, "cymbalsim_IN", ny - 1, nx - 1, "inside");
262 g = withCellMask(full, (ci, cj) => IN[ci * (ny - 1) + cj] !== 0);
263 }
264 const h = new Float64Array(g.n), w0 = new Float64Array(g.n);
265 let any = false;
266 for (let j = 0; j < ny; j++) {
267 for (let i = 0; i < nx; i++) {
268 if (!insideNode(g, i, j)) continue;
269 any = true;
270 const k = j * nx + i, m = i * ny + j;
271 const x = nodeX(g, i), y = nodeY(g, j);
272 const at = `(${x.toFixed(4)}, ${y.toFixed(4)})`;
273 if (!isFinite(H[m])) throw new DesignError(`thickness is ${H[m]} at ${at}`);
274 if (H[m] <= 0) throw new DesignError(`thickness must be positive; it is ${H[m]} at ${at}`);
275 if (!isFinite(Z[m])) throw new DesignError(`profile is ${Z[m]} at ${at}`);
276 h[k] = H[m];
277 w0[k] = Z[m];
278 }
279 }
280 if (!any) throw new DesignError("the outline contains no grid cells; enlarge it or reduce the grid spacing");
281 removePlane(w0, g);
282 for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) if (!insideNode(g, i, j)) w0[j * nx + i] = 0;
283 return { name: d.name, Lx: d.Lx, Ly: d.Ly, grid: g, mat: d.material, h, w0, temperature: d.temperature };
286/** Whether the plate is flat (no profile), in which case bending and in-plane motion decouple in the linear model. */
287export function isFlat(pl: Plate): boolean {
288 for (let k = 0; k < pl.w0.length; k++) if (pl.w0[k] !== 0) return false;
289 return true;
292/** Peak-to-peak height and the largest slope of the profile over the plate nodes. */
293export function profileStats(pl: Plate): { peakToPeak: number; maxSlope: number } {
294 const g = pl.grid, w0 = pl.w0;
295 let lo = Infinity, hi = -Infinity, maxSlope = 0;
296 const at = (i: number, j: number) => w0[j * g.nx + i];
297 const slope = (i: number, j: number, di: number, dj: number, hg: number) => {
298 const hasP = insideNode(g, i + di, j + dj), hasM = insideNode(g, i - di, j - dj);
299 if (hasP && hasM) return (at(i + di, j + dj) - at(i - di, j - dj)) / (2 * hg);
300 if (hasP) return (at(i + di, j + dj) - at(i, j)) / hg;
301 if (hasM) return (at(i, j) - at(i - di, j - dj)) / hg;
302 return 0;
303 };
304 for (let j = 0; j < g.ny; j++) {
305 for (let i = 0; i < g.nx; i++) {
306 if (!insideNode(g, i, j)) continue;
307 const v = at(i, j);
308 lo = Math.min(lo, v); hi = Math.max(hi, v);
309 maxSlope = Math.max(maxSlope, Math.hypot(slope(i, j, 1, 0, g.hx), slope(i, j, 0, 1, g.hy)));
310 }
311 }
312 return { peakToPeak: isFinite(hi - lo) ? hi - lo : 0, maxSlope };
↑↓ move↵openescclose