// 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, and the loss constants of the // material (from which the decay is derived, loss.ts). // 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 { type Grid, type Material, type Plate, type Thermal, ROOM_TEMPERATURE, 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; /** Temperature of the plate [K], for the thermoelastic damping. */ temperature: number; source: string; } /** 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 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, lossFactor, and the thermal constants alpha, cp, k"); const has = (s: RuntimeStruct, k: string) => field(s, k) !== undefined && !isEmpty(field(s, k)); const thermalKeys = ["alpha", "cp", "k"]; const given = thermalKeys.filter((k) => has(m, k)); let thermal: Thermal | null = null; if (given.length === 3) { 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) }; } else if (given.length > 0) { 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"); } 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), eta: has(m, "lossFactor") ? num(field(m, "lossFactor"), "design.material.lossFactor", 0) : 0, thermal, }; if (material.nu >= 0.5) throw new DesignError("design.material.nu must be below 0.5"); if (material.eta >= 0.1) throw new DesignError("design.material.lossFactor must be small (metals have loss factors of 1e-4 to 1e-3)"); 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"); const temperature = has(d, "temperature") ? num(field(d, "temperature"), "design.temperature (K)", 1) : ROOM_TEMPERATURE; 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)"); } } return { name, material, Lx, Ly, hasInside, thicknessConst, profileConst, temperature, source }; } // ---------- 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") : "", "", ].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. 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); } 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, temperature: d.temperature }; } /** 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 }; }