1// 3D FDTD check of a bar: voxelize the bar in air, run two force-impulse simulations
2// (js/fdtd.js), and turn the recorded top-face velocities into a bar model in the same form
3// as the FE model: frequencies, radiation decay, and mass-normalized shapes on a grid.
5import { thickness } from './bar.js';
6import { runFDTD, timeStep } from './fdtd.js';
7import { fft, nextPow2, hann } from './fft.js';
9const MARGIN = 20, SPONGE = 10; // mm of air around the bar, sponge cells
11export function isWood(b, x, y, z) {
12 if (x < 0 || x > b.L || y < 0 || y > b.W || z > b.h0) return false;
13 return z >= b.h0 - thickness(b, x);
14}
16/** Voxel grid (dx in mm). Top-face nodes are recorded on a coarser sampling (~6 mm). */
17export function buildGrid(b, dx) {
18 const pad = SPONGE + Math.ceil(MARGIN / dx);
19 const nbx = Math.ceil(b.L / dx), nby = Math.ceil(b.W / dx), nbz = Math.ceil(b.h0 / dx);
20 const nx = nbx + 2 * pad, ny = nby + 2 * pad, nz = nbz + 2 * pad;
21 const o = pad * dx;
22 const N = nx * ny * nz;
23 const mat = new Uint32Array(N);
24 const id = (i, j, k) => i + nx * (j + ny * k);
25 for (let k = 0; k < nz; k++) {
26 const z = (k + 0.5) * dx - o;
27 for (let j = 0; j < ny; j++) {
28 const y = (j + 0.5) * dx - o;
29 for (let i = 0; i < nx; i++) {
30 if (isWood(b, (i + 0.5) * dx - o, y, z)) mat[id(i, j, k)] = 1;
31 }
32 }
33 }
34 // top-face vz nodes (node above the topmost wood cell of each column)
35 const kTop = new Int32Array(nbx * nby).fill(-1);
36 for (let jb = 0; jb < nby; jb++) {
37 for (let ib = 0; ib < nbx; ib++) {
38 for (let k = nz - 2; k > 0; k--) if (mat[id(ib + pad, jb + pad, k)] === 1) { kTop[ib + nbx * jb] = k; break; }
39 }
40 }
41 const st = Math.max(1, Math.round(6 / dx));
42 const sIdx = [], sPos = [];
43 const colSurf = new Int32Array(nbx * nby).fill(-1);
44 for (let jb = Math.floor(st / 2); jb < nby; jb += st) {
45 for (let ib = Math.floor(st / 2); ib < nbx; ib += st) {
46 const k = kTop[ib + nbx * jb];
47 if (k < 0) continue;
48 colSurf[ib + nbx * jb] = sIdx.length;
49 sIdx.push(id(ib + pad, jb + pad, k));
50 sPos.push([(ib + 0.5) * dx, (jb + 0.5) * dx]);
51 }
52 }
53 let nWood = 0;
54 for (let n = 0; n < N; n++) nWood += mat[n];
55 return { nx, ny, nz, N, dx, ns: SPONGE, pad, o, nbx, nby, mat, kTop, surf: Uint32Array.from(sIdx), sPos, colSurf, micIdx: 0, nWood, id };
56}
58// Gaussian force patch around a top-face point (mm), on all top-face columns.
59export function strikePatch(grid, sx, sy) {
60 const ib0 = Math.round(sx / grid.dx - 0.5), jb0 = Math.round(sy / grid.dx - 0.5);
61 const idx = [], w = [];
62 for (let dj = -2; dj <= 2; dj++) {
63 for (let di = -2; di <= 2; di++) {
64 const ib = ib0 + di, jb = jb0 + dj;
65 if (ib < 0 || jb < 0 || ib >= grid.nbx || jb >= grid.nby) continue;
66 const k = grid.kTop[ib + grid.nbx * jb];
67 if (k < 0) continue;
68 idx.push(grid.id(ib + grid.pad, jb + grid.pad, k));
69 w.push(Math.exp(-(di * di + dj * dj) / 2));
70 }
71 }
72 const sum = w.reduce((a, c) => a + c, 0);
73 return { idx: Uint32Array.from(idx), w: Float32Array.from(w.map((v) => v / sum)) };
74}
76// Two reference points away from the nodes of most bending and torsion modes.
77export function refPoints(b) {
78 return [[0.06, 0.2], [0.37, 0.88]].map(([fx, fy]) => [fx * b.L, fy * b.W]);
79}
81export const analysisDuration = (f1) => Math.min(0.1, Math.max(0.03, 6 / f1));
83// Estimated cost, for the UI.
84export function analysisCost(b, mat, dx, f1) {
85 const pad = SPONGE + Math.ceil(MARGIN / dx);
86 const cells = (Math.ceil(b.L / dx) + 2 * pad) * (Math.ceil(b.W / dx) + 2 * pad) * (Math.ceil(b.h0 / dx) + 2 * pad);
87 const steps = 2 * Math.ceil(analysisDuration(f1) / timeStep(mat, dx));
88 return { cells, steps };
89}
91/**
92 * Run the analysis. Returns a bar model { source: 'FDTD', design, nx, ny, modes } or null
93 * if cancelled. onProgress(label, frac, sec), isCancelled().
94 */
95export async function analyzeBar(b, mat, dx, f1, { onProgress, isCancelled, nx = 120, ny = 8 } = {}) {
96 const grid = buildGrid(b, dx);
97 const runs = [];
98 const refs = refPoints(b).map(([x, y]) => {
99 const ib = Math.round(x / dx - 0.5), jb = Math.round(y / dx - 0.5);
100 // nearest recorded sample to the reference point
101 let best = 0, bd = Infinity;
102 grid.sPos.forEach((p, s) => { const d = Math.hypot(p[0] - x, p[1] - y); if (d < bd) { bd = d; best = s; } });
103 return { x, y, ib, jb, surf: best, patch: strikePatch(grid, x, y) };
104 });
105 let seconds = 0;
106 for (let k = 0; k < refs.length; k++) {
107 const res = await runFDTD({
108 mat, grid, mode: 'impulse', patch: refs[k].patch, duration: analysisDuration(f1), stiffScale: 1, recRate: 48000,
109 onProgress: (f, sec) => onProgress?.(`FDTD run ${k + 1}/${refs.length}`, (k + f) / refs.length, seconds + sec, f), isCancelled,
110 });
111 if (!res) return null;
112 seconds += res.seconds;
113 runs.push(res);
114 }
115 onProgress?.('Extracting modes…', 1, seconds, 1);
116 await new Promise((r) => setTimeout(r, 20));
117 const modes = extractModes(runs, refs, { fmin: 0.3 * f1 });
118 // resample each mode onto the regular top-face grid used by the FE model
119 const st = Math.max(1, Math.round(6 / dx));
120 const sx = st * dx, x0 = (Math.floor(st / 2) + 0.5) * dx;
121 const cols = Math.ceil((grid.nbx - Math.floor(st / 2)) / st), rows = Math.ceil((grid.nby - Math.floor(st / 2)) / st);
122 const at = (i, j) => grid.colSurf[(Math.floor(st / 2) + i * st) + grid.nbx * (Math.floor(st / 2) + j * st)];
123 const out = modes.map((m) => {
124 const phi = new Float32Array(nx * ny);
125 for (let j = 0; j < ny; j++) {
126 const v = Math.min(rows - 1.0001, Math.max(0, (((j + 0.5) / ny) * b.W - x0) / sx));
127 const j0 = Math.floor(v), fv = v - j0, j1 = Math.min(rows - 1, j0 + 1);
128 for (let i = 0; i < nx; i++) {
129 const u = Math.min(cols - 1.0001, Math.max(0, (((i + 0.5) / nx) * b.L - x0) / sx));
130 const i0 = Math.floor(u), fu = u - i0, i1 = Math.min(cols - 1, i0 + 1);
131 const g = (ii, jj) => { const s = at(ii, jj); return s >= 0 ? m.phi[s] : 0; };
132 phi[j * nx + i] = g(i0, j0) * (1 - fu) * (1 - fv) + g(i1, j0) * fu * (1 - fv) + g(i0, j1) * (1 - fu) * fv + g(i1, j1) * fu * fv;
133 }
134 }
135 return { f: m.f, sigRad: m.sigRad, phi, label: '' };
136 });
137 return { source: 'FDTD', design: { ...b }, nx, ny, modes: out, seconds, grid: { nx: grid.nx, ny: grid.ny, nz: grid.nz } };
138}
140/**
141 * Poles from the combined spectrum, radiation decay from two half windows, then a
142 * least-squares fit of complex amplitudes with those poles. The mobility V(ref → P) of a
143 * mass-normalized mode is -φ(ref)φ(P) (force down, velocity up), which gives φ(P).
144 */
145export function extractModes(runs, refs, { maxModes = 60, fmin = 50, fmax = 16000 } = {}) {
146 const { nRec, nSurf, recRate } = runs[0];
147 const t = Float64Array.from({ length: nRec }, (_, r) => (r + 0.5) / recRate);
148 const win = hann(nRec);
150 const nfft = nextPow2(nRec) * 4;
151 const Ptot = new Float64Array(nfft / 2);
152 const stride = Math.max(1, Math.floor(nSurf / 300));
153 const re = new Float64Array(nfft), im = new Float64Array(nfft);
154 for (const run of runs) {
155 const P = new Float64Array(nfft / 2);
156 for (let n = 0; n < nSurf; n += stride) {
157 re.fill(0); im.fill(0);
158 for (let r = 0; r < nRec; r++) re[r] = run.data[r * nSurf + n] * win[r];
159 fft(re, im);
160 for (let k = 0; k < nfft / 2; k++) P[k] += re[k] * re[k] + im[k] * im[k];
161 }
162 let m = 0;
163 for (let k = 0; k < nfft / 2; k++) m = Math.max(m, P[k]);
164 for (let k = 0; k < nfft / 2; k++) Ptot[k] += P[k] / m;
165 }
166 const df = recRate / nfft;
167 const k0 = Math.max(2, Math.floor(fmin / df));
168 const k1 = Math.min(nfft / 2 - 2, Math.floor(Math.min(fmax, 0.45 * recRate) / df));
169 let pmax = 0;
170 for (let k = k0; k <= k1; k++) pmax = Math.max(pmax, Ptot[k]);
171 const span = Math.round(3 * (nfft / nRec));
172 const peaks = [];
173 for (let k = k0; k <= k1; k++) {
174 if (Ptot[k] < pmax * 1e-7) continue;
175 let ok = true;
176 for (let q = Math.max(0, k - span); q <= Math.min(nfft / 2 - 1, k + span); q++) {
177 if (q !== k && Ptot[q] > Ptot[k]) { ok = false; break; }
178 }
179 if (!ok) continue;
180 const a = Math.log(Ptot[k - 1]), bb = Math.log(Ptot[k]), c = Math.log(Ptot[k + 1]);
181 const d = (0.5 * (a - c)) / (a - 2 * bb + c);
182 peaks.push({ f: (k + (Number.isFinite(d) ? d : 0)) * df, p: Ptot[k] });
183 }
184 peaks.sort((x, y) => y.p - x.p);
185 const poles = peaks.slice(0, maxModes).sort((x, y) => x.f - y.f).map((pk) => ({ f: pk.f, w: 2 * Math.PI * pk.f }));
187 // radiation decay from two half-window DFTs
188 const half = Math.floor(nRec / 2);
189 const w1 = hann(half);
190 const Dt = half / recRate;
191 const sstride = Math.max(1, Math.floor(nSurf / 150));
192 for (const pole of poles) {
193 let P1 = 0, P2 = 0;
194 for (const run of runs) {
195 for (let n = 0; n < nSurf; n += sstride) {
196 let ar = 0, ai = 0, br = 0, bi = 0;
197 for (let r = 0; r < 2 * half; r++) {
198 const c = Math.cos(pole.w * t[r]), s = Math.sin(pole.w * t[r]);
199 const v = run.data[r * nSurf + n] * (r < half ? w1[r] : w1[r - half]);
200 if (r < half) { ar += v * c; ai += v * s; } else { br += v * c; bi += v * s; }
201 }
202 P1 += ar * ar + ai * ai; P2 += br * br + bi * bi;
203 }
204 }
205 const sig = P2 > 0 ? (0.5 * Math.log(P1 / P2)) / Dt : 0;
206 pole.sig = Math.min(300, Math.max(0, Number.isFinite(sig) ? sig : 0));
207 }
209 const r0 = Math.ceil(2 * runs[0].pulseT * recRate);
210 const fits = runs.map((run) => lsFit(run.data, nRec, nSurf, t, r0, poles, recRate));
212 return poles.map((pole, n) => {
213 let best = null;
214 for (let k = 0; k < runs.length; k++) {
215 const [fr, fi] = halfSineFT(runs[k].pulseA, runs[k].pulseT, pole.w);
216 const f2 = fr * fr + fi * fi;
217 const Vre = new Float64Array(nSurf), Vim = new Float64Array(nSurf);
218 let vmax = 0;
219 for (let s = 0; s < nSurf; s++) {
220 const ar = fits[k].re[n * nSurf + s], ai = fits[k].im[n * nSurf + s];
221 Vre[s] = (ar * fr + ai * fi) / f2;
222 Vim[s] = (ai * fr - ar * fi) / f2;
223 vmax = Math.max(vmax, Math.hypot(Vre[s], Vim[s]));
224 }
225 const sr = refs[k].surf;
226 const vr = Math.hypot(Vre[sr], Vim[sr]);
227 const ratio = vr / (vmax || 1);
228 if (!best || ratio > best.ratio) best = { ratio, Vre, Vim, sr, vr };
229 }
230 // φ(P) = Re(V(P) e^{-i arg V(ref)}) / sqrt|V(ref)|
231 const { Vre, Vim, sr, vr } = best;
232 const cr = Vre[sr] / vr, ci = -Vim[sr] / vr, sc = 1 / Math.sqrt(vr || 1e-30);
233 const phi = new Float64Array(nSurf);
234 for (let s = 0; s < nSurf; s++) phi[s] = (Vre[s] * cr - Vim[s] * ci) * sc;
235 return { f: pole.f, sigRad: pole.sig, phi, quality: best.ratio };
236 }).filter((m) => m.quality > 0.05);
237}
239// Fourier transform of a half-sine pulse A sin(πt/T), 0<t<T, at angular frequency w.
240function halfSineFT(A, T, w) {
241 const a = Math.PI / T;
242 const den = a * a - w * w;
243 if (Math.abs(den) < 1e-6 * a * a) return [0, (-A * T) / 2];
244 return [(A * a * (1 + Math.cos(w * T))) / den, (-A * a * Math.sin(w * T)) / den];
245}
247// Fit h(t) = Σ Re(Aₙ e^{(iωₙ - σₙ)t}) for every surface point (columns of data).
248function lsFit(data, nRec, nSurf, t, r0, poles, recRate) {
249 const M = poles.length, K = 2 * M, nT = nRec - r0;
250 const B = new Float64Array(nT * K);
251 for (let r = 0; r < nT; r++) {
252 const tt = t[r + r0];
253 for (let n = 0; n < M; n++) {
254 const e = Math.exp(-poles[n].sig * tt);
255 const x = poles[n].w / (2 * recRate), bc = Math.sin(x) / x; // boxcar decimation response
256 B[r * K + 2 * n] = bc * e * Math.cos(poles[n].w * tt);
257 B[r * K + 2 * n + 1] = -bc * e * Math.sin(poles[n].w * tt);
258 }
259 }
260 const G = new Float64Array(K * K);
261 for (let r = 0; r < nT; r++) {
262 const o = r * K;
263 for (let i = 0; i < K; i++) {
264 const bi = B[o + i];
265 for (let j = i; j < K; j++) G[i * K + j] += bi * B[o + j];
266 }
267 }
268 let tr = 0;
269 for (let i = 0; i < K; i++) tr += G[i * K + i];
270 for (let i = 0; i < K; i++) {
271 G[i * K + i] += (1e-9 * tr) / K;
272 for (let j = 0; j < i; j++) G[i * K + j] = G[j * K + i];
273 }
274 const L = cholesky(G, K);
275 const C = new Float64Array(K * nSurf);
276 for (let r = 0; r < nT; r++) {
277 const o = (r + r0) * nSurf;
278 for (let i = 0; i < K; i++) {
279 const b = B[r * K + i];
280 const ci = i * nSurf;
281 for (let s = 0; s < nSurf; s++) C[ci + s] += b * data[o + s];
282 }
283 }
284 const col = new Float64Array(K);
285 const out = { re: new Float32Array(M * nSurf), im: new Float32Array(M * nSurf) };
286 for (let s = 0; s < nSurf; s++) {
287 for (let i = 0; i < K; i++) col[i] = C[i * nSurf + s];
288 for (let i = 0; i < K; i++) {
289 let v = col[i];
290 for (let j = 0; j < i; j++) v -= L[i * K + j] * col[j];
291 col[i] = v / L[i * K + i];
292 }
293 for (let i = K - 1; i >= 0; i--) {
294 let v = col[i];
295 for (let j = i + 1; j < K; j++) v -= L[j * K + i] * col[j];
296 col[i] = v / L[i * K + i];
297 }
298 for (let n = 0; n < M; n++) {
299 out.re[n * nSurf + s] = col[2 * n];
300 out.im[n * nSurf + s] = col[2 * n + 1];
301 }
302 }
303 return out;
304}
306function cholesky(A, n) {
307 const L = new Float64Array(n * n);
308 for (let i = 0; i < n; i++) {
309 for (let j = 0; j <= i; j++) {
310 let s = A[i * n + j];
311 for (let k = 0; k < j; k++) s -= L[i * n + k] * L[j * n + k];
312 L[i * n + j] = i === j ? Math.sqrt(Math.max(s, 1e-300)) : s / L[j * n + j];
313 }
314 }
315 return L;
316}
318/**
319 * Label FDTD modes by the FE mode they resemble most (shape correlation on the grid).
320 * Returns rows [{ fe, fd, corr, cents }] for the FE modes that found a partner.
321 */
322export function matchModes(fe, fd) {
323 const norm = (p) => Math.sqrt(p.reduce((a, v) => a + v * v, 0)) || 1;
324 const rows = [];
325 for (const m of fd.modes) {
326 let best = null;
327 for (const q of fe.modes) {
328 let s = 0;
329 for (let i = 0; i < m.phi.length; i++) s += m.phi[i] * q.phi[i];
330 const c = Math.abs(s) / (norm(m.phi) * norm(q.phi));
331 if (!best || c > best.c) best = { q, c };
332 }
333 if (best && best.c > 0.7) {
334 m.label = best.q.label;
335 rows.push({ fe: best.q, fd: m, corr: best.c, cents: 1200 * Math.log2(m.f / best.q.f) });
336 } else m.label = '?';
337 }
338 // keep the best match per FE mode; number the rest
339 const seen = new Map();
340 for (const r of rows) if (!seen.has(r.fe.label) || seen.get(r.fe.label).corr < r.corr) seen.set(r.fe.label, r);
341 for (const m of fd.modes) if (m.label !== '?' && seen.get(m.label)?.fd !== m) m.label += "'";
342 return [...seen.values()].sort((a, b) => a.fe.f - b.fe.f);
343}