@rulecad/fea 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/frame.mjs CHANGED
@@ -41,6 +41,8 @@
41
41
  * @property {number} [G] shear modulus, MPa (or give nu)
42
42
  * @property {number} [nu] Poisson's ratio, for G = E / 2(1 + nu)
43
43
  * @property {number} [density] g/cm³ (for gravity and modes; left out: weightless)
44
+ * @property {number} [strength] MPa, what sizing's stress limit holds each member's peak stress to (a member whose
45
+ * material has none is not held to it; a choice a group may take needs one, its own or the member's)
44
46
  */
45
47
  /** @typedef {'rigid' | 'free' | number} Fixity how one rotation at an element's end is joined to its node: rigidly, not at all (a hinge), or through a spring of that many N·mm/rad */
46
48
  /** @typedef {'rigid' | 'pinned' | 'ball' | { rx?: Fixity, ry?: Fixity, rz?: Fixity }} EndJoin 'pinned' frees both bending rotations (ry, rz) and carries twist; 'ball' frees all three; or say each, about the element's local axes */
@@ -105,42 +107,146 @@
105
107
 
106
108
  const FREEDOMS = ['x', 'y', 'z', 'rx', 'ry', 'rz'];
107
109
  /** @returns {never} */
108
- const refuse = (code, text, more) => { throw Object.assign(new Error(text), { code: `fea.frame.${code}`, ...more }); };
109
- const isVec3 = (v) => (Array.isArray(v) || ArrayBuffer.isView(v)) && v.length === 3 && Number.isFinite(v[0]) && Number.isFinite(v[1]) && Number.isFinite(v[2]);
110
- const said = (v) => (typeof v === 'string' ? `"${v}"` : JSON.stringify(v) ?? String(v));
110
+ const refuse = (code, text, more) => {
111
+ throw Object.assign(new Error(text), { code: `fea.frame.${code}`, ...more });
112
+ };
113
+ const isVec3 = (v) =>
114
+ (Array.isArray(v) || ArrayBuffer.isView(v)) &&
115
+ v.length === 3 &&
116
+ Number.isFinite(v[0]) &&
117
+ Number.isFinite(v[1]) &&
118
+ Number.isFinite(v[2]);
119
+ const said = (v) => (typeof v === 'string' ? `"${v}"` : (JSON.stringify(v) ?? String(v)));
120
+ // How many one-letter changes (put in, take out, or swap one for another) turn a into b: Levenshtein's distance
121
+ const edits = (a, b) => {
122
+ let row = Array.from({ length: b.length + 1 }, (_, j) => j);
123
+ for (let i = 1; i <= a.length; i++) {
124
+ const next = [i];
125
+ for (let j = 1; j <= b.length; j++)
126
+ next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
127
+ row = next;
128
+ }
129
+ return row[b.length];
130
+ };
131
+ // the known key a misspelt one is nearest, if it is near enough to be what was meant (a change for every three letters)
132
+ const nearest = (key, known) => {
133
+ let best = null,
134
+ least = Infinity;
135
+ for (const k of known) {
136
+ const d = edits(key.toLowerCase(), k.toLowerCase());
137
+ if (d < least) {
138
+ least = d;
139
+ best = k;
140
+ }
141
+ }
142
+ return least <= Math.max(1, Math.round(key.length / 3)) ? best : null;
143
+ };
144
+ // A key a frame does not know is refused, never passed over: a frame given `load:` for `loads:` would not move, and
145
+ // read as perfectly stiff. `what` names the object ("a frame", "statics"), and the nearest known key is suggested.
146
+ const onlyKeys = (o, known, what) => {
147
+ for (const k of Object.keys(o))
148
+ if (!known.includes(k)) {
149
+ const guess = nearest(k, known);
150
+ refuse(
151
+ 'input',
152
+ `${what} has no "${k}"${guess ? ` (did you mean "${guess}"?)` : ''}: it takes ${known.join(', ')}`,
153
+ { key: k, ...(guess ? { suggest: guess } : {}) },
154
+ );
155
+ }
156
+ };
157
+ // the options of a call: an object (none if left out) with only the keys it knows
158
+ const options = (o, known, what) => {
159
+ if (o === undefined) return {};
160
+ if (!o || typeof o !== 'object' || Array.isArray(o))
161
+ refuse('input', `${what} takes its options as an object, { ${known.join(', ')} }: got ${said(o)}`);
162
+ onlyKeys(o, known, what);
163
+ return o;
164
+ };
165
+ const MODEL_KEYS = ['nodes', 'elements', 'sections', 'materials', 'supports', 'loads', 'gravity', 'masses', 'loose'];
166
+ const ELEMENT_KEYS = ['id', 'a', 'b', 'section', 'material', 'roll', 'up', 'ends', 'of'];
167
+ const NODE_LOAD_KEYS = ['node', 'force', 'moment'],
168
+ SPREAD_LOAD_KEYS = ['element', 'spread', 'axes'];
169
+ const FRAME_OPTIONS = ['shear'];
170
+ const STATICS_OPTIONS = ['loads', 'gravity', 'masses', 'samples'],
171
+ BUCKLING_OPTIONS = ['count', 'loads', 'gravity', 'masses'],
172
+ MODES_OPTIONS = ['count', 'masses'];
111
173
 
112
174
  // ---- one element, in its own axes: [u, v, w, θx, θy, θz] at a, then the same at b ----
113
175
 
114
176
  // 4-point Gauss on 0..1: exact to degree 7 (the mass matrix's integrand is degree 6)
115
- const GAUSS = [[0.5 - 0.4305681557970263, 0.1739274225687269], [0.5 - 0.16999052179242816, 0.3260725774312731], [0.5 + 0.16999052179242816, 0.3260725774312731], [0.5 + 0.4305681557970263, 0.1739274225687269]];
116
- const XY = [1, 5, 7, 11], XZ = [2, 4, 8, 10], FLIP = [1, -1, 1, -1]; // bending in the x-y plane (v, θz) and in x-z (w, θy = −dw/dx: its rotations change sign)
177
+ const GAUSS = [
178
+ [0.5 - 0.4305681557970263, 0.1739274225687269],
179
+ [0.5 - 0.16999052179242816, 0.3260725774312731],
180
+ [0.5 + 0.16999052179242816, 0.3260725774312731],
181
+ [0.5 + 0.4305681557970263, 0.1739274225687269],
182
+ ];
183
+ const XY = [1, 5, 7, 11],
184
+ XZ = [2, 4, 8, 10],
185
+ FLIP = [1, -1, 1, -1]; // bending in the x-y plane (v, θz) and in x-z (w, θy = −dw/dx: its rotations change sign)
117
186
 
118
187
  // The Timoshenko element's shape functions in one bending plane at ξ = x / L, for [v1, θ1, v2, θ2]: the deflection N,
119
188
  // and with `all` its slope D and the section's rotation R (Friedman and Kosmatka 1993). Φ = 0 gives the Hermite cubics.
120
189
  function shape(xi, L, phi, all) {
121
- const f = 1 / (1 + phi), x2 = xi * xi, x3 = x2 * xi;
122
- const N = [f * (2 * x3 - 3 * x2 - phi * xi + 1 + phi), f * L * (x3 - (2 + phi / 2) * x2 + (1 + phi / 2) * xi), -f * (2 * x3 - 3 * x2 - phi * xi), f * L * (x3 - (1 - phi / 2) * x2 - (phi / 2) * xi)];
190
+ const f = 1 / (1 + phi),
191
+ x2 = xi * xi,
192
+ x3 = x2 * xi;
193
+ const N = [
194
+ f * (2 * x3 - 3 * x2 - phi * xi + 1 + phi),
195
+ f * L * (x3 - (2 + phi / 2) * x2 + (1 + phi / 2) * xi),
196
+ -f * (2 * x3 - 3 * x2 - phi * xi),
197
+ f * L * (x3 - (1 - phi / 2) * x2 - (phi / 2) * xi),
198
+ ];
123
199
  if (!all) return { N };
124
- const D = [f * (6 * x2 - 6 * xi - phi) / L, f * (3 * x2 - (4 + phi) * xi + 1 + phi / 2), -f * (6 * x2 - 6 * xi - phi) / L, f * (3 * x2 - (2 - phi) * xi - phi / 2)];
125
- const R = [f * 6 * (x2 - xi) / L, f * (3 * x2 - (4 + phi) * xi + 1 + phi), -f * 6 * (x2 - xi) / L, f * (3 * x2 - (2 - phi) * xi)];
200
+ const D = [
201
+ (f * (6 * x2 - 6 * xi - phi)) / L,
202
+ f * (3 * x2 - (4 + phi) * xi + 1 + phi / 2),
203
+ (-f * (6 * x2 - 6 * xi - phi)) / L,
204
+ f * (3 * x2 - (2 - phi) * xi - phi / 2),
205
+ ];
206
+ const R = [
207
+ (f * 6 * (x2 - xi)) / L,
208
+ f * (3 * x2 - (4 + phi) * xi + 1 + phi),
209
+ (-f * 6 * (x2 - xi)) / L,
210
+ f * (3 * x2 - (2 - phi) * xi),
211
+ ];
126
212
  return { N, D, R };
127
213
  }
128
214
  // ∫ DᵀD (geometric stiffness for a tension of 1), ∫ NᵀN (mass, for 1 a length) and ∫ RᵀR (rotary inertia), each 4 × 4
129
215
  function planeForms(L, phi) {
130
- const g = new Float64Array(16), m = new Float64Array(16), r = new Float64Array(16);
216
+ const g = new Float64Array(16),
217
+ m = new Float64Array(16),
218
+ r = new Float64Array(16);
131
219
  for (const [xi, wt] of GAUSS) {
132
- const { N, D, R } = shape(xi, L, phi, true), w = wt * L;
133
- for (let i = 0; i < 4; i++) for (let j = 0; j < 4; j++) { g[4 * i + j] += w * D[i] * D[j]; m[4 * i + j] += w * N[i] * N[j]; r[4 * i + j] += w * R[i] * R[j]; }
220
+ const { N, D, R } = shape(xi, L, phi, true),
221
+ w = wt * L;
222
+ for (let i = 0; i < 4; i++)
223
+ for (let j = 0; j < 4; j++) {
224
+ g[4 * i + j] += w * D[i] * D[j];
225
+ m[4 * i + j] += w * N[i] * N[j];
226
+ r[4 * i + j] += w * R[i] * R[j];
227
+ }
134
228
  }
135
229
  return { g, m, r };
136
230
  }
137
231
  // One bending plane's stiffness for [v1, θ1, v2, θ2]: Przemieniecki (1968) eq. 5.116
138
232
  function planeStiffness(EI, L, phi) {
139
- const c = EI / ((1 + phi) * L ** 3), a = 12 * c, b = 6 * L * c, d = (4 + phi) * L * L * c, e = (2 - phi) * L * L * c;
233
+ const c = EI / ((1 + phi) * L ** 3),
234
+ a = 12 * c,
235
+ b = 6 * L * c,
236
+ d = (4 + phi) * L * L * c,
237
+ e = (2 - phi) * L * L * c;
140
238
  return [a, b, -a, b, b, d, -b, e, -a, -b, a, -b, b, e, -b, d];
141
239
  }
142
- const put = (K, m4, idx, flip, scale) => { for (let i = 0; i < 4; i++) for (let j = 0; j < 4; j++) K[idx[i] * 12 + idx[j]] += scale * m4[4 * i + j] * (flip ? FLIP[i] * FLIP[j] : 1); };
143
- const bar = (K, i, j, s, t = -s) => { K[i * 12 + i] += s; K[j * 12 + j] += s; K[i * 12 + j] += t; K[j * 12 + i] += t; };
240
+ const put = (K, m4, idx, flip, scale) => {
241
+ for (let i = 0; i < 4; i++)
242
+ for (let j = 0; j < 4; j++) K[idx[i] * 12 + idx[j]] += scale * m4[4 * i + j] * (flip ? FLIP[i] * FLIP[j] : 1);
243
+ };
244
+ const bar = (K, i, j, s, t = -s) => {
245
+ K[i * 12 + i] += s;
246
+ K[j * 12 + j] += s;
247
+ K[i * 12 + j] += t;
248
+ K[j * 12 + i] += t;
249
+ };
144
250
  const shearModulus = (material) => material.G ?? material.E / (2 * (1 + material.nu));
145
251
 
146
252
  /**
@@ -153,36 +259,90 @@ const shearModulus = (material) => material.G ?? material.E / (2 * (1 + material
153
259
  * 12 E Iz / (G Asy L²) and 12 E Iy / (G Asz L²)
154
260
  */
155
261
  export function elementMatrices(section, material, L, { shear = true } = {}) {
156
- const { A, Iy, Iz, J } = section, { E } = material, G = shearModulus(material), rho = (material.density || 0) * 1e-6; // kg/mm³
157
- const phiY = shear && section.Asy ? (12 * E * Iz) / (G * section.Asy * L * L) : 0, phiZ = shear && section.Asz ? (12 * E * Iy) / (G * section.Asz * L * L) : 0;
158
- const k = new Float64Array(144), kg = new Float64Array(144), m = new Float64Array(144), fy = planeForms(L, phiY), fz = planeForms(L, phiZ);
159
- bar(k, 0, 6, (E * A) / L); bar(k, 3, 9, (G * J) / L);
160
- put(k, planeStiffness(E * Iz, L, phiY), XY, false, 1); put(k, planeStiffness(E * Iy, L, phiZ), XZ, true, 1);
161
- put(kg, fy.g, XY, false, 1); put(kg, fz.g, XZ, true, 1);
162
- bar(m, 0, 6, (rho * A * L) / 3, (rho * A * L) / 6); bar(m, 3, 9, (rho * (Iy + Iz) * L) / 3, (rho * (Iy + Iz) * L) / 6);
163
- put(m, fy.m, XY, false, rho * A); put(m, fy.r, XY, false, rho * Iz); put(m, fz.m, XZ, true, rho * A); put(m, fz.r, XZ, true, rho * Iy);
262
+ const { A, Iy, Iz, J } = section,
263
+ { E } = material,
264
+ G = shearModulus(material),
265
+ rho = (material.density || 0) * 1e-6; // kg/mm³
266
+ const phiY = shear && section.Asy ? (12 * E * Iz) / (G * section.Asy * L * L) : 0,
267
+ phiZ = shear && section.Asz ? (12 * E * Iy) / (G * section.Asz * L * L) : 0;
268
+ const k = new Float64Array(144),
269
+ kg = new Float64Array(144),
270
+ m = new Float64Array(144),
271
+ fy = planeForms(L, phiY),
272
+ fz = planeForms(L, phiZ);
273
+ bar(k, 0, 6, (E * A) / L);
274
+ bar(k, 3, 9, (G * J) / L);
275
+ put(k, planeStiffness(E * Iz, L, phiY), XY, false, 1);
276
+ put(k, planeStiffness(E * Iy, L, phiZ), XZ, true, 1);
277
+ put(kg, fy.g, XY, false, 1);
278
+ put(kg, fz.g, XZ, true, 1);
279
+ bar(m, 0, 6, (rho * A * L) / 3, (rho * A * L) / 6);
280
+ bar(m, 3, 9, (rho * (Iy + Iz) * L) / 3, (rho * (Iy + Iz) * L) / 6);
281
+ put(m, fy.m, XY, false, rho * A);
282
+ put(m, fy.r, XY, false, rho * Iz);
283
+ put(m, fz.m, XZ, true, rho * A);
284
+ put(m, fz.r, XZ, true, rho * Iy);
164
285
  return { k, kg, m, phi: [phiY, phiZ] };
165
286
  }
166
287
 
167
288
  // The inverse of a small matrix (n ≤ 6) by Gauss-Jordan with pivoting; null if it has none
168
289
  function invert(A, n) {
169
- const a = Float64Array.from(A), inv = new Float64Array(n * n);
290
+ const a = Float64Array.from(A),
291
+ inv = new Float64Array(n * n);
170
292
  let big = 0;
171
- for (let i = 0; i < n; i++) { inv[i * n + i] = 1; big = Math.max(big, Math.abs(a[i * n + i])); }
293
+ for (let i = 0; i < n; i++) {
294
+ inv[i * n + i] = 1;
295
+ big = Math.max(big, Math.abs(a[i * n + i]));
296
+ }
172
297
  for (let c = 0; c < n; c++) {
173
298
  let p = c;
174
299
  for (let r = c + 1; r < n; r++) if (Math.abs(a[r * n + c]) > Math.abs(a[p * n + c])) p = r;
175
300
  if (!(Math.abs(a[p * n + c]) > 1e-12 * big)) return null;
176
- if (p !== c) for (let j = 0; j < n; j++) { let t = a[c * n + j]; a[c * n + j] = a[p * n + j]; a[p * n + j] = t; t = inv[c * n + j]; inv[c * n + j] = inv[p * n + j]; inv[p * n + j] = t; }
301
+ if (p !== c)
302
+ for (let j = 0; j < n; j++) {
303
+ let t = a[c * n + j];
304
+ a[c * n + j] = a[p * n + j];
305
+ a[p * n + j] = t;
306
+ t = inv[c * n + j];
307
+ inv[c * n + j] = inv[p * n + j];
308
+ inv[p * n + j] = t;
309
+ }
177
310
  const d = a[c * n + c];
178
- for (let j = 0; j < n; j++) { a[c * n + j] /= d; inv[c * n + j] /= d; }
179
- for (let r = 0; r < n; r++) if (r !== c) { const f = a[r * n + c]; if (f) for (let j = 0; j < n; j++) { a[r * n + j] -= f * a[c * n + j]; inv[r * n + j] -= f * inv[c * n + j]; } }
311
+ for (let j = 0; j < n; j++) {
312
+ a[c * n + j] /= d;
313
+ inv[c * n + j] /= d;
314
+ }
315
+ for (let r = 0; r < n; r++)
316
+ if (r !== c) {
317
+ const f = a[r * n + c];
318
+ if (f)
319
+ for (let j = 0; j < n; j++) {
320
+ a[r * n + j] -= f * a[c * n + j];
321
+ inv[r * n + j] -= f * inv[c * n + j];
322
+ }
323
+ }
180
324
  }
181
325
  return inv;
182
326
  }
183
- const mul12 = (A, B) => { const C = new Float64Array(144); for (let i = 0; i < 12; i++) for (let k = 0; k < 12; k++) { const a = A[i * 12 + k]; if (a) for (let j = 0; j < 12; j++) C[i * 12 + j] += a * B[k * 12 + j]; } return C; };
184
- const transpose12 = (A) => { const C = new Float64Array(144); for (let i = 0; i < 12; i++) for (let j = 0; j < 12; j++) C[j * 12 + i] = A[i * 12 + j]; return C; };
185
- const symmetric12 = (A) => { for (let i = 0; i < 12; i++) for (let j = 0; j < i; j++) A[i * 12 + j] = A[j * 12 + i] = (A[i * 12 + j] + A[j * 12 + i]) / 2; return A; };
327
+ const mul12 = (A, B) => {
328
+ const C = new Float64Array(144);
329
+ for (let i = 0; i < 12; i++)
330
+ for (let k = 0; k < 12; k++) {
331
+ const a = A[i * 12 + k];
332
+ if (a) for (let j = 0; j < 12; j++) C[i * 12 + j] += a * B[k * 12 + j];
333
+ }
334
+ return C;
335
+ };
336
+ const transpose12 = (A) => {
337
+ const C = new Float64Array(144);
338
+ for (let i = 0; i < 12; i++) for (let j = 0; j < 12; j++) C[j * 12 + i] = A[i * 12 + j];
339
+ return C;
340
+ };
341
+ const symmetric12 = (A) => {
342
+ for (let i = 0; i < 12; i++)
343
+ for (let j = 0; j < i; j++) A[i * 12 + j] = A[j * 12 + i] = (A[i * 12 + j] + A[j * 12 + i]) / 2;
344
+ return A;
345
+ };
186
346
 
187
347
  // Springs and releases at an element's ends, condensed out. `springs` has a stiffness for each of the 12 freedoms:
188
348
  // Infinity where the end is rigid, 0 where it is released. With s the sprung freedoms and H = (K_ss + k)⁻¹, the
@@ -192,35 +352,77 @@ function condense({ k, kg, m }, springs) {
192
352
  const s = [];
193
353
  for (let i = 0; i < 12; i++) if (springs[i] !== Infinity) s.push(i);
194
354
  if (!s.length) return { k, kg, m, T: null, H: null, s };
195
- const n = s.length, A = new Float64Array(n * n);
196
- for (let p = 0; p < n; p++) for (let q = 0; q < n; q++) A[p * n + q] = k[s[p] * 12 + s[q]] + (p === q ? springs[s[p]] : 0);
355
+ const n = s.length,
356
+ A = new Float64Array(n * n);
357
+ for (let p = 0; p < n; p++)
358
+ for (let q = 0; q < n; q++) A[p * n + q] = k[s[p] * 12 + s[q]] + (p === q ? springs[s[p]] : 0);
197
359
  const H = invert(A, n);
198
360
  if (!H) return null;
199
361
  const T = new Float64Array(144);
200
362
  for (let i = 0; i < 12; i++) T[i * 13] = 1;
201
- for (let p = 0; p < n; p++) for (let j = 0; j < 12; j++) { let sum = 0; for (let q = 0; q < n; q++) sum += H[p * n + q] * k[s[q] * 12 + j]; T[s[p] * 12 + j] -= sum; }
363
+ for (let p = 0; p < n; p++)
364
+ for (let j = 0; j < 12; j++) {
365
+ let sum = 0;
366
+ for (let q = 0; q < n; q++) sum += H[p * n + q] * k[s[q] * 12 + j];
367
+ T[s[p] * 12 + j] -= sum;
368
+ }
202
369
  const Tt = transpose12(T);
203
- return { k: symmetric12(mul12(k, T)), kg: symmetric12(mul12(Tt, mul12(kg, T))), m: symmetric12(mul12(Tt, mul12(m, T))), T, H, s };
370
+ return {
371
+ k: symmetric12(mul12(k, T)),
372
+ kg: symmetric12(mul12(Tt, mul12(kg, T))),
373
+ m: symmetric12(mul12(Tt, mul12(m, T))),
374
+ T,
375
+ H,
376
+ s,
377
+ };
204
378
  }
205
379
 
206
380
  // Λᵀ K Λ: a 12 × 12 matrix from local to global axes, R's rows being the local axes
207
381
  function toGlobal(K, R) {
208
- const t = new Float64Array(144), out = new Float64Array(144);
209
- for (let i = 0; i < 12; i++) for (let q = 0; q < 12; q += 3) for (let c = 0; c < 3; c++) t[i * 12 + q + c] = K[i * 12 + q] * R[c] + K[i * 12 + q + 1] * R[3 + c] + K[i * 12 + q + 2] * R[6 + c];
210
- for (let p = 0; p < 12; p += 3) for (let r = 0; r < 3; r++) for (let j = 0; j < 12; j++) out[(p + r) * 12 + j] = R[r] * t[p * 12 + j] + R[3 + r] * t[(p + 1) * 12 + j] + R[6 + r] * t[(p + 2) * 12 + j];
382
+ const t = new Float64Array(144),
383
+ out = new Float64Array(144);
384
+ for (let i = 0; i < 12; i++)
385
+ for (let q = 0; q < 12; q += 3)
386
+ for (let c = 0; c < 3; c++)
387
+ t[i * 12 + q + c] = K[i * 12 + q] * R[c] + K[i * 12 + q + 1] * R[3 + c] + K[i * 12 + q + 2] * R[6 + c];
388
+ for (let p = 0; p < 12; p += 3)
389
+ for (let r = 0; r < 3; r++)
390
+ for (let j = 0; j < 12; j++)
391
+ out[(p + r) * 12 + j] = R[r] * t[p * 12 + j] + R[3 + r] * t[(p + 1) * 12 + j] + R[6 + r] * t[(p + 2) * 12 + j];
211
392
  return out;
212
393
  }
213
- const toLocal3 = (R, v, o = 0) => [R[0] * v[o] + R[1] * v[o + 1] + R[2] * v[o + 2], R[3] * v[o] + R[4] * v[o + 1] + R[5] * v[o + 2], R[6] * v[o] + R[7] * v[o + 1] + R[8] * v[o + 2]];
214
- const toGlobal3 = (R, v, o = 0) => [R[0] * v[o] + R[3] * v[o + 1] + R[6] * v[o + 2], R[1] * v[o] + R[4] * v[o + 1] + R[7] * v[o + 2], R[2] * v[o] + R[5] * v[o + 1] + R[8] * v[o + 2]];
394
+ const toLocal3 = (R, v, o = 0) => [
395
+ R[0] * v[o] + R[1] * v[o + 1] + R[2] * v[o + 2],
396
+ R[3] * v[o] + R[4] * v[o + 1] + R[5] * v[o + 2],
397
+ R[6] * v[o] + R[7] * v[o + 1] + R[8] * v[o + 2],
398
+ ];
399
+ const toGlobal3 = (R, v, o = 0) => [
400
+ R[0] * v[o] + R[3] * v[o + 1] + R[6] * v[o + 2],
401
+ R[1] * v[o] + R[4] * v[o + 1] + R[7] * v[o + 2],
402
+ R[2] * v[o] + R[5] * v[o + 1] + R[8] * v[o + 2],
403
+ ];
215
404
 
216
405
  // ---- the frame's matrix: symmetric, each row kept from its first non-zero column to the diagonal ----
217
406
 
218
407
  // Nodes in an order that keeps joined nodes close (reverse Cuthill-McKee), so rows are short
219
408
  function ordering(n, pairs) {
220
409
  const adj = Array.from({ length: n }, () => []);
221
- for (const [a, b] of pairs) { adj[a].push(b); adj[b].push(a); }
222
- const seen = new Uint8Array(n), out = [];
223
- const sweep = (start, mark) => { const q = [start]; mark[start] = 1; for (let h = 0; h < q.length; h++) for (const m of adj[q[h]].filter((v) => !mark[v]).sort((a, b) => adj[a].length - adj[b].length)) { mark[m] = 1; q.push(m); } return q; };
410
+ for (const [a, b] of pairs) {
411
+ adj[a].push(b);
412
+ adj[b].push(a);
413
+ }
414
+ const seen = new Uint8Array(n),
415
+ out = [];
416
+ const sweep = (start, mark) => {
417
+ const q = [start];
418
+ mark[start] = 1;
419
+ for (let h = 0; h < q.length; h++)
420
+ for (const m of adj[q[h]].filter((v) => !mark[v]).sort((a, b) => adj[a].length - adj[b].length)) {
421
+ mark[m] = 1;
422
+ q.push(m);
423
+ }
424
+ return q;
425
+ };
224
426
  for (const s of [...adj.keys()].sort((a, b) => adj[a].length - adj[b].length)) {
225
427
  if (seen[s]) continue;
226
428
  const far = sweep(s, new Uint8Array(n)).at(-1); // start from an end of the frame, not its middle
@@ -229,24 +431,38 @@ function ordering(n, pairs) {
229
431
  return out.reverse();
230
432
  }
231
433
  function profile(first) {
232
- const n = first.length, start = new Int32Array(n + 1);
434
+ const n = first.length,
435
+ start = new Int32Array(n + 1);
233
436
  for (let i = 0; i < n; i++) start[i + 1] = start[i] + i - first[i] + 1;
234
437
  return { n, first, start, v: new Float64Array(start[n]) };
235
438
  }
236
439
  const multiply = (P, x, y = new Float64Array(P.n)) => {
237
440
  const { n, first, start, v } = P;
238
441
  y.fill(0);
239
- for (let i = 0; i < n; i++) { const o = start[i] - first[i], xi = x[i]; let s = 0; for (let j = first[i]; j < i; j++) { s += v[o + j] * x[j]; y[j] += v[o + j] * xi; } y[i] += s + v[o + i] * xi; }
442
+ for (let i = 0; i < n; i++) {
443
+ const o = start[i] - first[i],
444
+ xi = x[i];
445
+ let s = 0;
446
+ for (let j = first[i]; j < i; j++) {
447
+ s += v[o + j] * x[j];
448
+ y[j] += v[o + j] * xi;
449
+ }
450
+ y[i] += s + v[o + i] * xi;
451
+ }
240
452
  return y;
241
453
  };
242
454
  // Cholesky, L Lᵀ, in the same rows. A pivot that all but vanishes is a freedom nothing holds: it is noted, held,
243
455
  // and the factorisation goes on, so every loose freedom is found in one pass.
244
456
  function factorise(P) {
245
- const { n, first, start } = P, v = Float64Array.from(P.v), loose = [];
457
+ const { n, first, start } = P,
458
+ v = Float64Array.from(P.v),
459
+ loose = [];
246
460
  for (let i = 0; i < n; i++) {
247
- const fi = first[i], ri = start[i] - fi;
461
+ const fi = first[i],
462
+ ri = start[i] - fi;
248
463
  for (let j = fi; j < i; j++) {
249
- const fj = first[j], rj = start[j] - fj;
464
+ const fj = first[j],
465
+ rj = start[j] - fj;
250
466
  let s = v[ri + j];
251
467
  for (let k = fi > fj ? fi : fj; k < j; k++) s -= v[ri + k] * v[rj + k];
252
468
  v[ri + j] = s / v[rj + j];
@@ -254,12 +470,26 @@ function factorise(P) {
254
470
  const a = v[ri + i];
255
471
  let d = a;
256
472
  for (let k = fi; k < i; k++) d -= v[ri + k] * v[ri + k];
257
- if (!(d > 1e-11 * a)) { loose.push(i); d = Math.max(a, 1) * 1e20; }
473
+ if (!(d > 1e-11 * a)) {
474
+ loose.push(i);
475
+ d = Math.max(a, 1) * 1e20;
476
+ }
258
477
  v[ri + i] = Math.sqrt(d);
259
478
  }
260
479
  const solve = (b, x = new Float64Array(n)) => {
261
- for (let i = 0; i < n; i++) { const fi = first[i], ri = start[i] - fi; let s = b[i]; for (let k = fi; k < i; k++) s -= v[ri + k] * x[k]; x[i] = s / v[ri + i]; }
262
- for (let i = n - 1; i >= 0; i--) { const fi = first[i], ri = start[i] - fi, xi = (x[i] /= v[ri + i]); for (let k = fi; k < i; k++) x[k] -= v[ri + k] * xi; }
480
+ for (let i = 0; i < n; i++) {
481
+ const fi = first[i],
482
+ ri = start[i] - fi;
483
+ let s = b[i];
484
+ for (let k = fi; k < i; k++) s -= v[ri + k] * x[k];
485
+ x[i] = s / v[ri + i];
486
+ }
487
+ for (let i = n - 1; i >= 0; i--) {
488
+ const fi = first[i],
489
+ ri = start[i] - fi,
490
+ xi = (x[i] /= v[ri + i]);
491
+ for (let k = fi; k < i; k++) x[k] -= v[ri + k] * xi;
492
+ }
263
493
  return x;
264
494
  };
265
495
  return { solve, loose };
@@ -270,17 +500,42 @@ function jacobi(A, n) {
270
500
  const V = new Float64Array(n * n);
271
501
  for (let i = 0; i < n; i++) V[i * n + i] = 1;
272
502
  for (let sweep = 0; sweep < 80; sweep++) {
273
- let off = 0, all = 0;
274
- for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) { const a = A[i * n + j] * A[i * n + j]; all += a; if (i !== j) off += a; }
503
+ let off = 0,
504
+ all = 0;
505
+ for (let i = 0; i < n; i++)
506
+ for (let j = 0; j < n; j++) {
507
+ const a = A[i * n + j] * A[i * n + j];
508
+ all += a;
509
+ if (i !== j) off += a;
510
+ }
275
511
  if (!(off > 1e-26 * all)) break; // (the off-diagonal part is under 1e-13 of the whole)
276
- for (let p = 0; p < n - 1; p++) for (let q = p + 1; q < n; q++) {
277
- const apq = A[p * n + q];
278
- if (apq === 0) continue;
279
- const theta = (A[q * n + q] - A[p * n + p]) / (2 * apq), t = (theta < 0 ? -1 : 1) / (Math.abs(theta) + Math.sqrt(theta * theta + 1)), c = 1 / Math.sqrt(t * t + 1), s = t * c;
280
- for (let k = 0; k < n; k++) { const kp = A[k * n + p], kq = A[k * n + q]; A[k * n + p] = c * kp - s * kq; A[k * n + q] = s * kp + c * kq; }
281
- for (let k = 0; k < n; k++) { const pk = A[p * n + k], qk = A[q * n + k]; A[p * n + k] = c * pk - s * qk; A[q * n + k] = s * pk + c * qk; }
282
- for (let k = 0; k < n; k++) { const kp = V[k * n + p], kq = V[k * n + q]; V[k * n + p] = c * kp - s * kq; V[k * n + q] = s * kp + c * kq; }
283
- }
512
+ for (let p = 0; p < n - 1; p++)
513
+ for (let q = p + 1; q < n; q++) {
514
+ const apq = A[p * n + q];
515
+ if (apq === 0) continue;
516
+ const theta = (A[q * n + q] - A[p * n + p]) / (2 * apq),
517
+ t = (theta < 0 ? -1 : 1) / (Math.abs(theta) + Math.sqrt(theta * theta + 1)),
518
+ c = 1 / Math.sqrt(t * t + 1),
519
+ s = t * c;
520
+ for (let k = 0; k < n; k++) {
521
+ const kp = A[k * n + p],
522
+ kq = A[k * n + q];
523
+ A[k * n + p] = c * kp - s * kq;
524
+ A[k * n + q] = s * kp + c * kq;
525
+ }
526
+ for (let k = 0; k < n; k++) {
527
+ const pk = A[p * n + k],
528
+ qk = A[q * n + k];
529
+ A[p * n + k] = c * pk - s * qk;
530
+ A[q * n + k] = s * pk + c * qk;
531
+ }
532
+ for (let k = 0; k < n; k++) {
533
+ const kp = V[k * n + p],
534
+ kq = V[k * n + q];
535
+ V[k * n + p] = c * kp - s * kq;
536
+ V[k * n + q] = s * kp + c * kq;
537
+ }
538
+ }
284
539
  }
285
540
  return { values: Float64Array.from({ length: n }, (_, i) => A[i * n + i]), V };
286
541
  }
@@ -297,159 +552,477 @@ function jacobi(A, n) {
297
552
  function lowest(solveK, B, want, block = Math.max(2 * want, want + 8), tol = 1e-9, limit = 400) {
298
553
  const n = B.n;
299
554
  let seed = 12345;
300
- const random = () => { let t = (seed += 0x6D2B79F5); t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 2147483648 - 1; };
555
+ const random = () => {
556
+ let t = (seed += 0x6d2b79f5);
557
+ t = Math.imul(t ^ (t >>> 15), t | 1);
558
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
559
+ return ((t ^ (t >>> 14)) >>> 0) / 2147483648 - 1;
560
+ };
301
561
  const fresh = () => multiply(B, Float64Array.from({ length: n }, random));
302
- let q = Math.min(n, block), Y = Array.from({ length: q }, fresh), last = null, exhausted = false;
562
+ let q = Math.min(n, block),
563
+ Y = Array.from({ length: q }, fresh),
564
+ last = null,
565
+ exhausted = false;
303
566
  for (let step = 0, since = 1; ; step++, since++) {
304
567
  const offered = Y.length;
305
- let Z = Y.map((y) => solveK(y)), BZ = Z.map((z) => multiply(B, z));
568
+ let Z = Y.map((y) => solveK(y)),
569
+ BZ = Z.map((z) => multiply(B, z));
306
570
  // each vector's size in K (zᵀ K z = zᵀ y): scaled to 1, or dropped if B gave it nothing
307
571
  const keep = [];
308
- Z.forEach((z, i) => { let e = 0; for (let k = 0; k < n; k++) e += z[k] * Y[i][k]; if (e > 0 && Number.isFinite(e)) { const s = 1 / Math.sqrt(e); for (let k = 0; k < n; k++) { z[k] *= s; BZ[i][k] *= s; Y[i][k] *= s; } keep.push(i); } });
309
- Z = keep.map((i) => Z[i]); BZ = keep.map((i) => BZ[i]); Y = keep.map((i) => Y[i]);
572
+ Z.forEach((z, i) => {
573
+ let e = 0;
574
+ for (let k = 0; k < n; k++) e += z[k] * Y[i][k];
575
+ if (e > 0 && Number.isFinite(e)) {
576
+ const s = 1 / Math.sqrt(e);
577
+ for (let k = 0; k < n; k++) {
578
+ z[k] *= s;
579
+ BZ[i][k] *= s;
580
+ Y[i][k] *= s;
581
+ }
582
+ keep.push(i);
583
+ }
584
+ });
585
+ Z = keep.map((i) => Z[i]);
586
+ BZ = keep.map((i) => BZ[i]);
587
+ Y = keep.map((i) => Y[i]);
310
588
  const m = Z.length;
311
589
  if (!m) return { values: [], vectors: [] };
312
- const Kr = new Float64Array(m * m), Br = new Float64Array(m * m);
313
- for (let i = 0; i < m; i++) for (let j = i; j < m; j++) { let a = 0, b = 0; const zi = Z[i], yj = Y[j], bj = BZ[j]; for (let k = 0; k < n; k++) { a += zi[k] * yj[k]; b += zi[k] * bj[k]; } Kr[i * m + j] = Kr[j * m + i] = a; Br[i * m + j] = Br[j * m + i] = b; }
590
+ const Kr = new Float64Array(m * m),
591
+ Br = new Float64Array(m * m);
592
+ for (let i = 0; i < m; i++)
593
+ for (let j = i; j < m; j++) {
594
+ let a = 0,
595
+ b = 0;
596
+ const zi = Z[i],
597
+ yj = Y[j],
598
+ bj = BZ[j];
599
+ for (let k = 0; k < n; k++) {
600
+ a += zi[k] * yj[k];
601
+ b += zi[k] * bj[k];
602
+ }
603
+ Kr[i * m + j] = Kr[j * m + i] = a;
604
+ Br[i * m + j] = Br[j * m + i] = b;
605
+ }
314
606
  // an orthonormal basis of the block in K: Kr = V Λ Vᵀ, W = V Λ^-½, leaving out directions the block repeats
315
- const kr = jacobi(Kr, m), top = Math.max(...kr.values), cols = [...kr.values.keys()].filter((i) => kr.values[i] > 1e-12 * top), r = cols.length;
316
- const W = new Float64Array(m * r), BW = new Float64Array(m * r), C = new Float64Array(r * r);
317
- cols.forEach((c, j) => { const s = 1 / Math.sqrt(kr.values[c]); for (let i = 0; i < m; i++) W[i * r + j] = kr.V[i * m + c] * s; });
318
- for (let i = 0; i < m; i++) for (let j = 0; j < r; j++) { let s = 0; for (let k = 0; k < m; k++) s += Br[i * m + k] * W[k * r + j]; BW[i * r + j] = s; }
319
- for (let i = 0; i < r; i++) for (let j = 0; j < r; j++) { let s = 0; for (let k = 0; k < m; k++) s += W[k * r + i] * BW[k * r + j]; C[i * r + j] = s; }
320
- const ritz = jacobi(C, r), by = [...ritz.values.keys()].sort((a, b) => ritz.values[b] - ritz.values[a]);
607
+ const kr = jacobi(Kr, m),
608
+ top = Math.max(...kr.values),
609
+ cols = [...kr.values.keys()].filter((i) => kr.values[i] > 1e-12 * top),
610
+ r = cols.length;
611
+ const W = new Float64Array(m * r),
612
+ BW = new Float64Array(m * r),
613
+ C = new Float64Array(r * r);
614
+ cols.forEach((c, j) => {
615
+ const s = 1 / Math.sqrt(kr.values[c]);
616
+ for (let i = 0; i < m; i++) W[i * r + j] = kr.V[i * m + c] * s;
617
+ });
618
+ for (let i = 0; i < m; i++)
619
+ for (let j = 0; j < r; j++) {
620
+ let s = 0;
621
+ for (let k = 0; k < m; k++) s += Br[i * m + k] * W[k * r + j];
622
+ BW[i * r + j] = s;
623
+ }
624
+ for (let i = 0; i < r; i++)
625
+ for (let j = 0; j < r; j++) {
626
+ let s = 0;
627
+ for (let k = 0; k < m; k++) s += W[k * r + i] * BW[k * r + j];
628
+ C[i * r + j] = s;
629
+ }
630
+ const ritz = jacobi(C, r),
631
+ by = [...ritz.values.keys()].sort((a, b) => ritz.values[b] - ritz.values[a]);
321
632
  // the Ritz vectors (or their B products) from the block: column c = Σ_i S_i (W U)[i][c]
322
- const mix = (S, count = r) => by.slice(0, count).map((c) => { const x = new Float64Array(n); for (let i = 0; i < m; i++) { let w = 0; for (let j = 0; j < r; j++) w += W[i * r + j] * ritz.V[j * r + c]; if (w) { const si = S[i]; for (let k = 0; k < n; k++) x[k] += w * si[k]; } } return x; });
323
- const values = by.map((c) => ritz.values[c]), size = Math.max(Math.abs(values[0]), Math.abs(values[r - 1])), wanted = values.filter((v) => v > 1e-12 * size).slice(0, want);
633
+ const mix = (S, count = r) =>
634
+ by.slice(0, count).map((c) => {
635
+ const x = new Float64Array(n);
636
+ for (let i = 0; i < m; i++) {
637
+ let w = 0;
638
+ for (let j = 0; j < r; j++) w += W[i * r + j] * ritz.V[j * r + c];
639
+ if (w) {
640
+ const si = S[i];
641
+ for (let k = 0; k < n; k++) x[k] += w * si[k];
642
+ }
643
+ }
644
+ return x;
645
+ });
646
+ const values = by.map((c) => ritz.values[c]),
647
+ size = Math.max(Math.abs(values[0]), Math.abs(values[r - 1])),
648
+ wanted = values.filter((v) => v > 1e-12 * size).slice(0, want);
324
649
  if (since === 1 && r < offered) exhausted = true; // fresh vectors added nothing new: the block already holds all B can reach
325
650
  const settled = !!last && last.length === wanted.length && wanted.every((v, i) => Math.abs(v - last[i]) <= tol * v);
326
- if (r >= n || (settled && (wanted.length >= want || exhausted || q >= n)) || step + 1 >= limit) return { values: wanted, vectors: mix(Z, wanted.length) };
651
+ if (r >= n || (settled && (wanted.length >= want || exhausted || q >= n)) || step + 1 >= limit)
652
+ return { values: wanted, vectors: mix(Z, wanted.length) };
327
653
  last = wanted;
328
654
  Y = mix(BZ);
329
- if ((settled || since >= 30) && q < n) { const more = Math.min(n, 2 * q) - q; for (let i = 0; i < more; i++) Y.push(fresh()); q += more; since = 0; last = null; }
655
+ if ((settled || since >= 30) && q < n) {
656
+ const more = Math.min(n, 2 * q) - q;
657
+ for (let i = 0; i < more; i++) Y.push(fresh());
658
+ q += more;
659
+ since = 0;
660
+ last = null;
661
+ }
330
662
  }
331
663
  }
332
664
 
333
665
  // ---- the model, read and refused by name ----
334
666
 
335
667
  function read(model, { shear = true } = {}) {
336
- if (!model || typeof model !== 'object') refuse('input', 'a frame is { nodes, elements, supports, loads }: got ' + said(model));
668
+ if (!model || typeof model !== 'object')
669
+ refuse('input', 'a frame is { nodes, elements, supports, loads }: got ' + said(model));
670
+ onlyKeys(model, MODEL_KEYS, 'a frame');
337
671
  const { nodes, elements } = model;
338
- if (!nodes || typeof nodes !== 'object') refuse('input', 'a frame needs nodes: positions in mm by name, { a: [0, 0, 0], b: [0, 0, 300] }, or a list of positions');
339
- const ids = Array.isArray(nodes) ? nodes.map((_, i) => String(i)) : Object.keys(nodes), at = Array.isArray(nodes) ? nodes : Object.values(nodes), index = new Map(ids.map((id, i) => [id, i]));
340
- if (!ids.length) refuse('input', 'a frame needs nodes: positions in mm by name, { a: [0, 0, 0], b: [0, 0, 300] }, or a list of positions');
341
- at.forEach((p, i) => { if (!isVec3(p)) refuse('node', `node ${said(ids[i])} is at ${said(p)}: a node needs a position [x, y, z] in mm`, { node: ids[i] }); });
342
- if (!Array.isArray(elements) || !elements.length) refuse('input', 'a frame needs elements: a list of { a, b, section, material }, each between two nodes');
343
- const nodeOf = (name, what) => index.get(String(name)) ?? refuse('node', `${what} names node ${said(name)}, which is not in nodes (there ${ids.length === 1 ? 'is' : 'are'} ${ids.slice(0, 12).join(', ')}${ids.length > 12 ? ', ...' : ''})`, { node: name });
344
- const named = (v, table, what, whose) => (typeof v === 'string' ? table?.[v] ?? refuse(what, `${whose} names ${what} "${v}", which is not in the model's ${what}s${table ? ` (there ${Object.keys(table).length === 1 ? 'is' : 'are'} ${Object.keys(table).join(', ')})` : ''}`) : v);
345
- const N = ids.length, elementIds = new Map();
672
+ if (!nodes || typeof nodes !== 'object')
673
+ refuse(
674
+ 'input',
675
+ 'a frame needs nodes: positions in mm by name, { a: [0, 0, 0], b: [0, 0, 300] }, or a list of positions',
676
+ );
677
+ const ids = Array.isArray(nodes) ? nodes.map((_, i) => String(i)) : Object.keys(nodes),
678
+ at = Array.isArray(nodes) ? nodes : Object.values(nodes),
679
+ index = new Map(ids.map((id, i) => [id, i]));
680
+ if (!ids.length)
681
+ refuse(
682
+ 'input',
683
+ 'a frame needs nodes: positions in mm by name, { a: [0, 0, 0], b: [0, 0, 300] }, or a list of positions',
684
+ );
685
+ at.forEach((p, i) => {
686
+ if (!isVec3(p))
687
+ refuse('node', `node ${said(ids[i])} is at ${said(p)}: a node needs a position [x, y, z] in mm`, {
688
+ node: ids[i],
689
+ });
690
+ });
691
+ if (!Array.isArray(elements) || !elements.length)
692
+ refuse('input', 'a frame needs elements: a list of { a, b, section, material }, each between two nodes');
693
+ const nodeOf = (name, what) =>
694
+ index.get(String(name)) ??
695
+ refuse(
696
+ 'node',
697
+ `${what} names node ${said(name)}, which is not in nodes (there ${ids.length === 1 ? 'is' : 'are'} ${ids.slice(0, 12).join(', ')}${ids.length > 12 ? ', ...' : ''})`,
698
+ { node: name },
699
+ );
700
+ const named = (v, table, what, whose) =>
701
+ typeof v === 'string'
702
+ ? (table?.[v] ??
703
+ refuse(
704
+ what,
705
+ `${whose} names ${what} "${v}", which is not in the model's ${what}s${table ? ` (there ${Object.keys(table).length === 1 ? 'is' : 'are'} ${Object.keys(table).join(', ')})` : ''}`,
706
+ ))
707
+ : v;
708
+ const N = ids.length,
709
+ elementIds = new Map();
346
710
  const els = elements.map((e, i) => {
347
- const id = e?.id ?? i, whose = `element ${said(id)}`;
348
- if (!e || typeof e !== 'object') refuse('input', `element ${i} is ${said(e)}: an element is { a, b, section, material }`);
711
+ const id = e?.id ?? i,
712
+ whose = `element ${said(id)}`;
713
+ if (!e || typeof e !== 'object')
714
+ refuse('input', `element ${i} is ${said(e)}: an element is { a, b, section, material }`);
715
+ onlyKeys(e, ELEMENT_KEYS, whose);
349
716
  if (elementIds.has(String(id))) refuse('input', `two elements are called ${said(id)}: each needs its own id`);
350
717
  elementIds.set(String(id), i);
351
- const a = nodeOf(e.a, whose), b = nodeOf(e.b, whose), pa = at[a], pb = at[b], dx = [pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2]], L = Math.hypot(...dx);
352
- if (a === b || !(L > 1e-9)) refuse('length', `${whose} has no length: it runs from node ${said(e.a)} to node ${said(e.b)}${a === b ? '' : ', which are at the same place'}. An element joins two nodes some way apart`, { element: id });
353
- const section = named(e.section, model.sections, 'section', whose), material = named(e.material, model.materials, 'material', whose);
354
- if (!section || typeof section !== 'object') refuse('section', `${whose} needs a section: { A, Iy, Iz, J } in mm² and mm⁴`, { element: id });
355
- for (const key of ['A', 'Iy', 'Iz', 'J']) if (!(section[key] > 0) || !Number.isFinite(section[key])) refuse('section', `${whose}'s section has ${key} = ${said(section[key])}: it needs ${key} above 0 (A in mm²; Iy, Iz and J in mm⁴)`, { element: id, property: key });
356
- for (const key of ['Asy', 'Asz', 'cy', 'cz', 'Wy', 'Wz']) if (section[key] !== undefined && (!(section[key] > 0) || !Number.isFinite(section[key]))) refuse('section', `${whose}'s section has ${key} = ${said(section[key])}: leave it out, or give it above 0`, { element: id, property: key });
357
- if (!material || typeof material !== 'object') refuse('material', `${whose} needs a material: { E, nu or G, density }`, { element: id });
358
- if (!(material.E > 0) || !Number.isFinite(material.E)) refuse('material', `${whose}'s material has E = ${said(material.E)}: it needs a Young's modulus above 0, in MPa`, { element: id, property: 'E' });
359
- if (material.G !== undefined ? !(material.G > 0 && Number.isFinite(material.G)) : !(material.nu > -1 && material.nu < 0.5)) refuse('material', `${whose}'s material has G = ${said(material.G)} and nu = ${said(material.nu)}: it needs a shear modulus G above 0 in MPa, or a Poisson's ratio nu between -1 and 0.5`, { element: id, property: 'G' });
360
- if (material.density !== undefined && !(material.density >= 0 && Number.isFinite(material.density))) refuse('material', `${whose}'s material has density = ${said(material.density)}: leave it out (weightless), or give it in g/cm³, 0 or more`, { element: id, property: 'density' });
718
+ const a = nodeOf(e.a, whose),
719
+ b = nodeOf(e.b, whose),
720
+ pa = at[a],
721
+ pb = at[b],
722
+ dx = [pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2]],
723
+ L = Math.hypot(...dx);
724
+ if (a === b || !(L > 1e-9))
725
+ refuse(
726
+ 'length',
727
+ `${whose} has no length: it runs from node ${said(e.a)} to node ${said(e.b)}${a === b ? '' : ', which are at the same place'}. An element joins two nodes some way apart`,
728
+ { element: id },
729
+ );
730
+ const section = named(e.section, model.sections, 'section', whose),
731
+ material = named(e.material, model.materials, 'material', whose);
732
+ if (!section || typeof section !== 'object')
733
+ refuse('section', `${whose} needs a section: { A, Iy, Iz, J } in mm² and mm⁴`, { element: id });
734
+ for (const key of ['A', 'Iy', 'Iz', 'J'])
735
+ if (!(section[key] > 0) || !Number.isFinite(section[key]))
736
+ refuse(
737
+ 'section',
738
+ `${whose}'s section has ${key} = ${said(section[key])}: it needs ${key} above 0 (A in mm²; Iy, Iz and J in mm⁴)`,
739
+ { element: id, property: key },
740
+ );
741
+ for (const key of ['Asy', 'Asz', 'cy', 'cz', 'Wy', 'Wz'])
742
+ if (section[key] !== undefined && (!(section[key] > 0) || !Number.isFinite(section[key])))
743
+ refuse('section', `${whose}'s section has ${key} = ${said(section[key])}: leave it out, or give it above 0`, {
744
+ element: id,
745
+ property: key,
746
+ });
747
+ if (!material || typeof material !== 'object')
748
+ refuse('material', `${whose} needs a material: { E, nu or G, density }`, { element: id });
749
+ if (!(material.E > 0) || !Number.isFinite(material.E))
750
+ refuse(
751
+ 'material',
752
+ `${whose}'s material has E = ${said(material.E)}: it needs a Young's modulus above 0, in MPa`,
753
+ { element: id, property: 'E' },
754
+ );
755
+ if (
756
+ material.G !== undefined
757
+ ? !(material.G > 0 && Number.isFinite(material.G))
758
+ : !(material.nu > -1 && material.nu < 0.5)
759
+ )
760
+ refuse(
761
+ 'material',
762
+ `${whose}'s material has G = ${said(material.G)} and nu = ${said(material.nu)}: it needs a shear modulus G above 0 in MPa, or a Poisson's ratio nu between -1 and 0.5`,
763
+ { element: id, property: 'G' },
764
+ );
765
+ if (material.density !== undefined && !(material.density >= 0 && Number.isFinite(material.density)))
766
+ refuse(
767
+ 'material',
768
+ `${whose}'s material has density = ${said(material.density)}: leave it out (weightless), or give it in g/cm³, 0 or more`,
769
+ { element: id, property: 'density' },
770
+ );
361
771
  // local axes
362
772
  const x = dx.map((c) => c / L);
363
- if (e.up !== undefined && !isVec3(e.up)) refuse('axes', `${whose}'s up is ${said(e.up)}: it is a direction [x, y, z] that local z leans towards`, { element: id });
364
- if (e.roll !== undefined && !Number.isFinite(e.roll)) refuse('axes', `${whose}'s roll is ${said(e.roll)}: it is an angle in degrees about the element's own axis`, { element: id });
365
- const up = e.up ?? (Math.abs(x[2]) > 0.999 ? [1, 0, 0] : [0, 0, 1]), along = up[0] * x[0] + up[1] * x[1] + up[2] * x[2];
773
+ if (e.up !== undefined && !isVec3(e.up))
774
+ refuse('axes', `${whose}'s up is ${said(e.up)}: it is a direction [x, y, z] that local z leans towards`, {
775
+ element: id,
776
+ });
777
+ if (e.roll !== undefined && !Number.isFinite(e.roll))
778
+ refuse('axes', `${whose}'s roll is ${said(e.roll)}: it is an angle in degrees about the element's own axis`, {
779
+ element: id,
780
+ });
781
+ const up = e.up ?? (Math.abs(x[2]) > 0.999 ? [1, 0, 0] : [0, 0, 1]),
782
+ along = up[0] * x[0] + up[1] * x[1] + up[2] * x[2];
366
783
  let z = [up[0] - along * x[0], up[1] - along * x[1], up[2] - along * x[2]];
367
784
  const zl = Math.hypot(...z);
368
- if (!(zl > 1e-6 * Math.hypot(...up))) refuse('axes', `${whose}'s up, ${said(Array.from(up))}, runs along the element, so it does not say which way local z points: give a direction across it`, { element: id });
785
+ if (!(zl > 1e-6 * Math.hypot(...up)))
786
+ refuse(
787
+ 'axes',
788
+ `${whose}'s up, ${said(Array.from(up))}, runs along the element, so it does not say which way local z points: give a direction across it`,
789
+ { element: id },
790
+ );
369
791
  z = z.map((c) => c / zl);
370
792
  let y = [z[1] * x[2] - z[2] * x[1], z[2] * x[0] - z[0] * x[2], z[0] * x[1] - z[1] * x[0]];
371
- if (e.roll) { const c = Math.cos((e.roll * Math.PI) / 180), s = Math.sin((e.roll * Math.PI) / 180), y0 = y, z0 = z; y = y0.map((v, k) => c * v + s * z0[k]); z = z0.map((v, k) => c * z0[k] - s * y0[k]); }
793
+ if (e.roll) {
794
+ const c = Math.cos((e.roll * Math.PI) / 180),
795
+ s = Math.sin((e.roll * Math.PI) / 180),
796
+ y0 = y,
797
+ z0 = z;
798
+ y = y0.map((v, k) => c * v + s * z0[k]);
799
+ z = z0.map((v, k) => c * z0[k] - s * y0[k]);
800
+ }
372
801
  // how each end is joined
373
802
  const springs = new Float64Array(12).fill(Infinity);
374
- for (const [end, o] of [['a', 3], ['b', 9]]) {
375
- const j = e.ends?.[end] ?? 'rigid', each = j === 'rigid' ? {} : j === 'pinned' ? { ry: 'free', rz: 'free' } : j === 'ball' ? { rx: 'free', ry: 'free', rz: 'free' } : j;
376
- if (!each || typeof each !== 'object') refuse('join', `${whose}'s end ${end} is joined ${said(j)}: 'rigid', 'pinned' (both bending rotations free), 'ball' (all three free), or { rx, ry, rz } each 'rigid', 'free' or a spring in N·mm/rad`, { element: id });
803
+ for (const [end, o] of [
804
+ ['a', 3],
805
+ ['b', 9],
806
+ ]) {
807
+ const j = e.ends?.[end] ?? 'rigid',
808
+ each =
809
+ j === 'rigid'
810
+ ? {}
811
+ : j === 'pinned'
812
+ ? { ry: 'free', rz: 'free' }
813
+ : j === 'ball'
814
+ ? { rx: 'free', ry: 'free', rz: 'free' }
815
+ : j;
816
+ if (!each || typeof each !== 'object')
817
+ refuse(
818
+ 'join',
819
+ `${whose}'s end ${end} is joined ${said(j)}: 'rigid', 'pinned' (both bending rotations free), 'ball' (all three free), or { rx, ry, rz } each 'rigid', 'free' or a spring in N·mm/rad`,
820
+ { element: id },
821
+ );
377
822
  for (const [key, f] of Object.entries(each)) {
378
823
  const d = ['rx', 'ry', 'rz'].indexOf(key);
379
- if (d < 0) refuse('join', `${whose}'s end ${end} has "${key}": an end's rotations are rx (twist), ry and rz, about the element's own axes`, { element: id });
824
+ if (d < 0)
825
+ refuse(
826
+ 'join',
827
+ `${whose}'s end ${end} has "${key}": an end's rotations are rx (twist), ry and rz, about the element's own axes`,
828
+ { element: id },
829
+ );
380
830
  if (f === 'rigid' || f === Infinity || f === undefined) continue;
381
- if (f !== 'free' && !(f >= 0)) refuse('join', `${whose}'s end ${end} has ${key} = ${said(f)}: 'rigid', 'free', or a spring's stiffness in N·mm/rad, 0 or more`, { element: id });
831
+ if (f !== 'free' && !(f >= 0))
832
+ refuse(
833
+ 'join',
834
+ `${whose}'s end ${end} has ${key} = ${said(f)}: 'rigid', 'free', or a spring's stiffness in N·mm/rad, 0 or more`,
835
+ { element: id },
836
+ );
382
837
  springs[o + d] = f === 'free' ? 0 : f;
383
838
  }
384
839
  }
385
- const R = Float64Array.of(...x, ...y, ...z), raw = elementMatrices(section, material, L, { shear });
840
+ const R = Float64Array.of(...x, ...y, ...z),
841
+ raw = elementMatrices(section, material, L, { shear });
386
842
  // free to twist at both ends (a strut on two ball joints): it carries no torque, and its own spin is nobody's business
387
- if (springs[3] === 0 && springs[9] === 0) { springs[3] = springs[9] = Infinity; for (const i of [3, 9]) for (const j of [3, 9]) raw.k[i * 12 + j] = raw.m[i * 12 + j] = 0; }
843
+ if (springs[3] === 0 && springs[9] === 0) {
844
+ springs[3] = springs[9] = Infinity;
845
+ for (const i of [3, 9]) for (const j of [3, 9]) raw.k[i * 12 + j] = raw.m[i * 12 + j] = 0;
846
+ }
388
847
  const c = condense(raw, springs);
389
848
  if (!c) refuse('join', `${whose}'s end joints leave it loose: carry more of its rotations`, { element: id });
390
- const G = shearModulus(material), Wy = section.Wy ?? (section.cz ? section.Iy / section.cz : undefined), Wz = section.Wz ?? (section.cy ? section.Iz / section.cy : undefined);
391
- return { id, of: e.of, a, b, L, R, raw, ...c, phi: raw.phi, EA: material.E * section.A, EIy: material.E * section.Iy, EIz: material.E * section.Iz, GAy: shear && section.Asy ? G * section.Asy : 0, GAz: shear && section.Asz ? G * section.Asz : 0,
392
- A: section.A, Wy, Wz, perLength: (material.density || 0) * 1e-6 * section.A, K: toGlobal(c.k, R) };
849
+ const G = shearModulus(material),
850
+ Wy = section.Wy ?? (section.cz ? section.Iy / section.cz : undefined),
851
+ Wz = section.Wz ?? (section.cy ? section.Iz / section.cy : undefined);
852
+ return {
853
+ id,
854
+ of: e.of,
855
+ a,
856
+ b,
857
+ L,
858
+ R,
859
+ raw,
860
+ ...c,
861
+ phi: raw.phi,
862
+ EA: material.E * section.A,
863
+ EIy: material.E * section.Iy,
864
+ EIz: material.E * section.Iz,
865
+ GAy: shear && section.Asy ? G * section.Asy : 0,
866
+ GAz: shear && section.Asz ? G * section.Asz : 0,
867
+ A: section.A,
868
+ Wy,
869
+ Wz,
870
+ perLength: (material.density || 0) * 1e-6 * section.A,
871
+ K: toGlobal(c.k, R),
872
+ };
393
873
  });
394
874
  // supports
395
- const held = new Uint8Array(6 * N), ground = new Float64Array(6 * N), supported = [];
396
- if (model.supports !== undefined && (typeof model.supports !== 'object' || !model.supports)) refuse('support', `supports is ${said(model.supports)}: give each supported node 'fixed', 'pinned' or { x, y, z, rx, ry, rz }`);
875
+ const held = new Uint8Array(6 * N),
876
+ ground = new Float64Array(6 * N),
877
+ supported = [];
878
+ if (model.supports !== undefined && (typeof model.supports !== 'object' || !model.supports))
879
+ refuse(
880
+ 'support',
881
+ `supports is ${said(model.supports)}: give each supported node 'fixed', 'pinned' or { x, y, z, rx, ry, rz }`,
882
+ );
397
883
  for (const [name, s] of Object.entries(model.supports || {})) {
398
- const n = nodeOf(name, 'a support'), each = s === 'fixed' ? Object.fromEntries(FREEDOMS.map((f) => [f, true])) : s === 'pinned' ? { x: true, y: true, z: true } : s;
399
- if (!each || typeof each !== 'object') refuse('support', `node ${said(name)}'s support is ${said(s)}: 'fixed' (all six freedoms), 'pinned' (its three movements), or { x, y, z, rx, ry, rz } each true (held), false, or a spring to ground in N/mm or N·mm/rad`, { node: name });
884
+ const n = nodeOf(name, 'a support'),
885
+ each =
886
+ s === 'fixed'
887
+ ? Object.fromEntries(FREEDOMS.map((f) => [f, true]))
888
+ : s === 'pinned'
889
+ ? { x: true, y: true, z: true }
890
+ : s;
891
+ if (!each || typeof each !== 'object')
892
+ refuse(
893
+ 'support',
894
+ `node ${said(name)}'s support is ${said(s)}: 'fixed' (all six freedoms), 'pinned' (its three movements), or { x, y, z, rx, ry, rz } each true (held), false, or a spring to ground in N/mm or N·mm/rad`,
895
+ { node: name },
896
+ );
400
897
  let any = false;
401
898
  for (const [key, h] of Object.entries(each)) {
402
899
  const d = FREEDOMS.indexOf(key);
403
- if (d < 0) refuse('support', `node ${said(name)}'s support has "${key}": a node's freedoms are ${FREEDOMS.join(', ')}`, { node: name });
404
- if (h === true || h === 'fixed' || h === Infinity) { held[6 * n + d] = 1; any = true; } else if (typeof h === 'number' && h > 0) { ground[6 * n + d] = h; any = true; } else if (!(h === false || h === 'free' || h === 0 || h === undefined)) refuse('support', `node ${said(name)}'s support has ${key} = ${said(h)}: true (held), false (free), or a spring to ground of 0 or more`, { node: name });
900
+ if (d < 0)
901
+ refuse('support', `node ${said(name)}'s support has "${key}": a node's freedoms are ${FREEDOMS.join(', ')}`, {
902
+ node: name,
903
+ });
904
+ if (h === true || h === 'fixed' || h === Infinity) {
905
+ held[6 * n + d] = 1;
906
+ any = true;
907
+ } else if (typeof h === 'number' && h > 0) {
908
+ ground[6 * n + d] = h;
909
+ any = true;
910
+ } else if (!(h === false || h === 'free' || h === 0 || h === undefined))
911
+ refuse(
912
+ 'support',
913
+ `node ${said(name)}'s support has ${key} = ${said(h)}: true (held), false (free), or a spring to ground of 0 or more`,
914
+ { node: name },
915
+ );
405
916
  }
406
917
  if (any) supported.push(n);
407
918
  }
408
- if (!supported.length) refuse('unheld', 'nothing is held: give at least one node a support (supports: { a: \'fixed\' }), or the frame just moves');
919
+ if (!supported.length)
920
+ refuse(
921
+ 'unheld',
922
+ "nothing is held: give at least one node a support (supports: { a: 'fixed' }), or the frame just moves",
923
+ );
409
924
  const span = Math.max(...[0, 1, 2].map((c) => Math.max(...at.map((p) => p[c])) - Math.min(...at.map((p) => p[c]))));
410
925
  return { ids, at, index, N, els, elementIds, held, ground, supported, nodeOf, span };
411
926
  }
412
927
 
413
928
  // The loads of one case: forces on every freedom, and each element's spread load in its own axes
414
929
  function loadCase(f, { loads = [], gravity, masses = {} }) {
415
- const { N, els, elementIds, nodeOf } = f, nodal = new Float64Array(6 * N), spread = new Float64Array(3 * els.length), lumped = new Float64Array(N);
416
- if (!Array.isArray(loads)) refuse('load', `loads is ${said(loads)}: a list of { node, force, moment } and { element, spread }`);
417
- if (gravity !== undefined && !isVec3(gravity)) refuse('load', `gravity is ${said(gravity)}: a direction and size [x, y, z] in N/kg (m/s²), [0, 0, -9.81] for down`);
418
- if (!masses || typeof masses !== 'object') refuse('mass', `masses is ${said(masses)}: lumped masses in kg by node, { head: 0.4 }`);
930
+ const { N, els, elementIds, nodeOf } = f,
931
+ nodal = new Float64Array(6 * N),
932
+ spread = new Float64Array(3 * els.length),
933
+ lumped = new Float64Array(N);
934
+ if (!Array.isArray(loads))
935
+ refuse('load', `loads is ${said(loads)}: a list of { node, force, moment } and { element, spread }`);
936
+ if (gravity !== undefined && !isVec3(gravity))
937
+ refuse(
938
+ 'load',
939
+ `gravity is ${said(gravity)}: a direction and size [x, y, z] in N/kg (m/s²), [0, 0, -9.81] for down`,
940
+ );
941
+ if (!masses || typeof masses !== 'object')
942
+ refuse('mass', `masses is ${said(masses)}: lumped masses in kg by node, { head: 0.4 }`);
419
943
  for (const [name, kg] of Object.entries(masses)) {
420
944
  const n = nodeOf(name, 'a lumped mass');
421
- if (!(kg >= 0) || !Number.isFinite(kg)) refuse('mass', `the lumped mass at node ${said(name)} is ${said(kg)}: a mass in kg, 0 or more`, { node: name });
945
+ if (!(kg >= 0) || !Number.isFinite(kg))
946
+ refuse('mass', `the lumped mass at node ${said(name)} is ${said(kg)}: a mass in kg, 0 or more`, { node: name });
422
947
  lumped[n] += kg;
423
948
  if (gravity) for (let c = 0; c < 3; c++) nodal[6 * n + c] += kg * gravity[c];
424
949
  }
425
950
  loads.forEach((l, i) => {
951
+ if (l && typeof l === 'object')
952
+ onlyKeys(
953
+ l,
954
+ l.node !== undefined
955
+ ? NODE_LOAD_KEYS
956
+ : l.element !== undefined
957
+ ? SPREAD_LOAD_KEYS
958
+ : [...NODE_LOAD_KEYS, ...SPREAD_LOAD_KEYS],
959
+ `load ${i + 1}`,
960
+ );
426
961
  if (l && l.node !== undefined) {
427
962
  const n = nodeOf(l.node, `load ${i + 1}`);
428
- for (const [key, o] of [['force', 0], ['moment', 3]]) if (l[key] !== undefined) { if (!isVec3(l[key])) refuse('load', `load ${i + 1}'s ${key} is ${said(l[key])}: [x, y, z] in ${o ? 'N·mm' : 'N'}, in global axes`); for (let c = 0; c < 3; c++) nodal[6 * n + o + c] += l[key][c]; }
429
- if (l.force === undefined && l.moment === undefined) refuse('load', `load ${i + 1}, at node ${said(l.node)}, has neither a force nor a moment`);
963
+ for (const [key, o] of [
964
+ ['force', 0],
965
+ ['moment', 3],
966
+ ])
967
+ if (l[key] !== undefined) {
968
+ if (!isVec3(l[key]))
969
+ refuse(
970
+ 'load',
971
+ `load ${i + 1}'s ${key} is ${said(l[key])}: [x, y, z] in ${o ? 'N·mm' : 'N'}, in global axes`,
972
+ );
973
+ for (let c = 0; c < 3; c++) nodal[6 * n + o + c] += l[key][c];
974
+ }
975
+ if (l.force === undefined && l.moment === undefined)
976
+ refuse('load', `load ${i + 1}, at node ${said(l.node)}, has neither a force nor a moment`);
430
977
  } else if (l && l.element !== undefined) {
431
- const e = elementIds.get(String(l.element)) ?? refuse('load', `load ${i + 1} names element ${said(l.element)}, which is not in elements`);
432
- if (!isVec3(l.spread)) refuse('load', `load ${i + 1}'s spread is ${said(l.spread)}: [x, y, z] in N per mm of the element's length`);
433
- if (l.axes !== undefined && l.axes !== 'global' && l.axes !== 'local') refuse('load', `load ${i + 1}'s axes is ${said(l.axes)}: 'global' or 'local' (the element's own)`);
978
+ const e =
979
+ elementIds.get(String(l.element)) ??
980
+ refuse('load', `load ${i + 1} names element ${said(l.element)}, which is not in elements`);
981
+ if (!isVec3(l.spread))
982
+ refuse('load', `load ${i + 1}'s spread is ${said(l.spread)}: [x, y, z] in N per mm of the element's length`);
983
+ if (l.axes !== undefined && l.axes !== 'global' && l.axes !== 'local')
984
+ refuse('load', `load ${i + 1}'s axes is ${said(l.axes)}: 'global' or 'local' (the element's own)`);
434
985
  const w = l.axes === 'local' ? l.spread : toLocal3(els[e].R, l.spread);
435
986
  for (let c = 0; c < 3; c++) spread[3 * e + c] += w[c];
436
987
  } else refuse('load', `load ${i + 1} is ${said(l)}: { node, force, moment } or { element, spread }`);
437
988
  });
438
- if (gravity) els.forEach((el, e) => { const w = toLocal3(el.R, gravity); for (let c = 0; c < 3; c++) spread[3 * e + c] += el.perLength * w[c]; });
989
+ if (gravity)
990
+ els.forEach((el, e) => {
991
+ const w = toLocal3(el.R, gravity);
992
+ for (let c = 0; c < 3; c++) spread[3 * e + c] += el.perLength * w[c];
993
+ });
439
994
  return { nodal, spread, lumped };
440
995
  }
441
996
  // A spread load's forces at the element's (rigid) ends, in its own axes: w L / 2 each, and moments of w L² / 12
442
997
  function spreadEnds(L, wx, wy, wz) {
443
- const fb = new Float64Array(12), h = L / 2, m = (L * L) / 12;
444
- fb[0] = fb[6] = wx * h; fb[1] = fb[7] = wy * h; fb[2] = fb[8] = wz * h; fb[5] = wy * m; fb[11] = -wy * m; fb[4] = -wz * m; fb[10] = wz * m;
998
+ const fb = new Float64Array(12),
999
+ h = L / 2,
1000
+ m = (L * L) / 12;
1001
+ fb[0] = fb[6] = wx * h;
1002
+ fb[1] = fb[7] = wy * h;
1003
+ fb[2] = fb[8] = wz * h;
1004
+ fb[5] = wy * m;
1005
+ fb[11] = -wy * m;
1006
+ fb[4] = -wz * m;
1007
+ fb[10] = wz * m;
445
1008
  return fb;
446
1009
  }
447
- const condensedLoad = (el, fb) => { if (!el.T) return fb; const fc = new Float64Array(12); for (let i = 0; i < 12; i++) { const v = fb[i]; if (v) for (let j = 0; j < 12; j++) fc[j] += el.T[i * 12 + j] * v; } return fc; };
1010
+ const condensedLoad = (el, fb) => {
1011
+ if (!el.T) return fb;
1012
+ const fc = new Float64Array(12);
1013
+ for (let i = 0; i < 12; i++) {
1014
+ const v = fb[i];
1015
+ if (v) for (let j = 0; j < 12; j++) fc[j] += el.T[i * 12 + j] * v;
1016
+ }
1017
+ return fc;
1018
+ };
448
1019
 
449
1020
  /**
450
1021
  * A frame, read, checked and factorised once, ready for its solves. What is wrong with the model is said here, by
451
1022
  * name, before any solve: each refusal is an Error with a `code` ("fea.frame." then node, length, section, material,
452
- * axes, join, support, load, mass, input, unheld or mechanism; buckling adds compression, and sizing fit).
1023
+ * axes, join, support, load, mass, input, unheld or mechanism; buckling adds compression, and sizing fit). A key the
1024
+ * model, an element, a load, these options or a solve's options do not have is refused as input, with the nearest
1025
+ * key it has: `load` for `loads` would otherwise leave the frame unloaded, and read as perfectly stiff.
453
1026
  * @param {FrameModel} model
454
1027
  * @param {{ shear?: boolean }} [o] shear: false ignores the sections' shear areas (Euler-Bernoulli beams)
455
1028
  * @returns {{
@@ -471,11 +1044,22 @@ const condensedLoad = (el, fb) => { if (!el.T) return fb; const fc = new Float64
471
1044
  * where the loads leave it alone (a strut spinning on its axis), the factors are exact.
472
1045
  */
473
1046
  export function frame(model, o = {}) {
474
- const f = read(model, o), { ids, N, els, held, ground } = f;
1047
+ const f = read(model, options(o, FRAME_OPTIONS, 'frame()')),
1048
+ { ids, N, els, held, ground } = f;
475
1049
  // free freedoms, numbered node by node in an order that keeps the matrix's rows short
476
- const free = new Int32Array(6 * N).fill(-1), back = [];
477
- for (const n of ordering(N, els.map((e) => [e.a, e.b]))) for (let d = 0; d < 6; d++) if (!held[6 * n + d]) { free[6 * n + d] = back.length; back.push(6 * n + d); }
478
- const n = back.length, first = Int32Array.from({ length: n }, (_, i) => i);
1050
+ const free = new Int32Array(6 * N).fill(-1),
1051
+ back = [];
1052
+ for (const n of ordering(
1053
+ N,
1054
+ els.map((e) => [e.a, e.b]),
1055
+ ))
1056
+ for (let d = 0; d < 6; d++)
1057
+ if (!held[6 * n + d]) {
1058
+ free[6 * n + d] = back.length;
1059
+ back.push(6 * n + d);
1060
+ }
1061
+ const n = back.length,
1062
+ first = Int32Array.from({ length: n }, (_, i) => i);
479
1063
  for (const el of els) {
480
1064
  el.dofs = Int32Array.from({ length: 12 }, (_, i) => free[6 * (i < 6 ? el.a : el.b) + (i % 6)]);
481
1065
  let lo = n;
@@ -483,8 +1067,22 @@ export function frame(model, o = {}) {
483
1067
  for (const d of el.dofs) if (d >= 0 && lo < first[d]) first[d] = lo;
484
1068
  }
485
1069
  const assemble = (matrix, scale) => {
486
- const P = profile(first), { start, v } = P;
487
- els.forEach((el, e) => { const s = scale ? scale[e] : 1, G = matrix(el), dofs = el.dofs; if (s) for (let i = 0; i < 12; i++) { const di = dofs[i]; if (di >= 0) for (let j = 0; j < 12; j++) { const dj = dofs[j]; if (dj >= 0 && dj <= di) v[start[di] + dj - first[di]] += s * G[i * 12 + j]; } } });
1070
+ const P = profile(first),
1071
+ { start, v } = P;
1072
+ els.forEach((el, e) => {
1073
+ const s = scale ? scale[e] : 1,
1074
+ G = matrix(el),
1075
+ dofs = el.dofs;
1076
+ if (s)
1077
+ for (let i = 0; i < 12; i++) {
1078
+ const di = dofs[i];
1079
+ if (di >= 0)
1080
+ for (let j = 0; j < 12; j++) {
1081
+ const dj = dofs[j];
1082
+ if (dj >= 0 && dj <= di) v[start[di] + dj - first[di]] += s * G[i * 12 + j];
1083
+ }
1084
+ }
1085
+ });
488
1086
  return P;
489
1087
  };
490
1088
  const diagonal = (P, i) => P.start[i] + i - P.first[i];
@@ -493,34 +1091,80 @@ export function frame(model, o = {}) {
493
1091
  // A rotation of a node that no element end there carries (every end at it pinned that way) leaves the matrix
494
1092
  // singular though nothing is wrong with the frame: nothing turns the node, and nothing depends on it. Such a
495
1093
  // rotation is held still (and reported as 0); a moment put on it is refused, as nothing would carry it.
496
- const idle = [], turn = new Float64Array(9 * N), stiff = new Float64Array(N);
497
- for (const el of els) for (const [p, o] of [[el.a, 3], [el.b, 9]]) for (let i = 0; i < 3; i++) { stiff[p] = Math.max(stiff[p], el.raw.k[(o + i) * 13]); for (let j = 0; j < 3; j++) turn[9 * p + 3 * i + j] += el.K[(o + i) * 12 + o + j]; }
1094
+ const idle = [],
1095
+ turn = new Float64Array(9 * N),
1096
+ stiff = new Float64Array(N);
1097
+ for (const el of els)
1098
+ for (const [p, o] of [
1099
+ [el.a, 3],
1100
+ [el.b, 9],
1101
+ ])
1102
+ for (let i = 0; i < 3; i++) {
1103
+ stiff[p] = Math.max(stiff[p], el.raw.k[(o + i) * 13]);
1104
+ for (let j = 0; j < 3; j++) turn[9 * p + 3 * i + j] += el.K[(o + i) * 12 + o + j];
1105
+ }
498
1106
  for (let p = 0; p < N; p++) {
499
- const fr = [3, 4, 5].filter((d) => !held[6 * p + d]), m = fr.length;
1107
+ const fr = [3, 4, 5].filter((d) => !held[6 * p + d]),
1108
+ m = fr.length;
500
1109
  if (!m || !(stiff[p] > 0)) continue;
501
- const S = Float64Array.from({ length: m * m }, (_, q) => { const i = Math.floor(q / m), j = q % m; return turn[9 * p + 3 * (fr[i] - 3) + fr[j] - 3] + (i === j ? ground[6 * p + fr[i]] : 0); }), { values, V } = jacobi(S, m);
502
- for (let c = 0; c < m; c++) if (values[c] < 1e-9 * stiff[p]) {
503
- const v = [0, 0, 0];
504
- fr.forEach((d, i) => { v[d - 3] = V[i * m + c]; });
505
- idle.push({ node: p, v });
506
- for (const di of fr) for (const dj of fr) { const a = free[6 * p + di], b = free[6 * p + dj]; if (b <= a) K.v[K.start[a] + b - first[a]] += stiff[p] * v[di - 3] * v[dj - 3]; }
507
- }
1110
+ const S = Float64Array.from({ length: m * m }, (_, q) => {
1111
+ const i = Math.floor(q / m),
1112
+ j = q % m;
1113
+ return turn[9 * p + 3 * (fr[i] - 3) + fr[j] - 3] + (i === j ? ground[6 * p + fr[i]] : 0);
1114
+ }),
1115
+ { values, V } = jacobi(S, m);
1116
+ for (let c = 0; c < m; c++)
1117
+ if (values[c] < 1e-9 * stiff[p]) {
1118
+ const v = [0, 0, 0];
1119
+ fr.forEach((d, i) => {
1120
+ v[d - 3] = V[i * m + c];
1121
+ });
1122
+ idle.push({ node: p, v });
1123
+ for (const di of fr)
1124
+ for (const dj of fr) {
1125
+ const a = free[6 * p + di],
1126
+ b = free[6 * p + dj];
1127
+ if (b <= a) K.v[K.start[a] + b - first[a]] += stiff[p] * v[di - 3] * v[dj - 3];
1128
+ }
1129
+ }
508
1130
  }
509
- const factor = n ? factorise(K) : { solve: (b) => new Float64Array(0), loose: [] };
510
- if (model.loose !== undefined && model.loose !== 'refuse' && model.loose !== 'hold') refuse('input', `loose is ${said(model.loose)}: 'refuse' (a mechanism refuses the model) or 'hold' (each freedom nothing resists is held, while the loads do not move it)`);
1131
+ const factor = n ? factorise(K) : { solve: () => new Float64Array(0), loose: [] };
1132
+ if (model.loose !== undefined && model.loose !== 'refuse' && model.loose !== 'hold')
1133
+ refuse(
1134
+ 'input',
1135
+ `loose is ${said(model.loose)}: 'refuse' (a mechanism refuses the model) or 'hold' (each freedom nothing resists is held, while the loads do not move it)`,
1136
+ );
511
1137
  const loose = factor.loose.map((i) => ({ node: ids[Math.floor(back[i] / 6)], freedom: FREEDOMS[back[i] % 6] }));
512
- const listOf = (ls) => { const by = new Map(); for (const l of ls) by.set(l.node, [...(by.get(l.node) || []), l.freedom]); return `${[...by].slice(0, 8).map(([node, fr]) => `node ${said(node)} (${fr.join(', ')})`).join('; ')}${by.size > 8 ? `, and ${by.size - 8} more nodes` : ''}`; };
513
- if (loose.length && model.loose !== 'hold') refuse('mechanism', `the frame is a mechanism: it can still move with nothing resisting, at ${listOf(loose)}. Hold those freedoms with a support, or join the elements there more stiffly (a pinned end frees its bending rotations and still carries twist, so a strut pinned at both ends can spin: make one end 'ball')`, { loose });
1138
+ const listOf = (ls) => {
1139
+ const by = new Map();
1140
+ for (const l of ls) by.set(l.node, [...(by.get(l.node) || []), l.freedom]);
1141
+ return `${[...by]
1142
+ .slice(0, 8)
1143
+ .map(([node, fr]) => `node ${said(node)} (${fr.join(', ')})`)
1144
+ .join('; ')}${by.size > 8 ? `, and ${by.size - 8} more nodes` : ''}`;
1145
+ };
1146
+ if (loose.length && model.loose !== 'hold')
1147
+ refuse(
1148
+ 'mechanism',
1149
+ `the frame is a mechanism: it can still move with nothing resisting, at ${listOf(loose)}. Hold those freedoms with a support, or join the elements there more stiffly (a pinned end frees its bending rotations and still carries twist, so a strut pinned at both ends can spin: make one end 'ball')`,
1150
+ { loose },
1151
+ );
514
1152
  // Each loose freedom i was held by a pivot many orders stiffer than the frame, which is K + D eᵢ eᵢᵀ; then
515
1153
  // (K + D eᵢ eᵢᵀ)⁻¹ eᵢ is the way the frame moves unresisted (K's null vector v, over D vᵢ). Scaled so it moves
516
1154
  // 1 mm at most (or turns 1 / span where nothing moves), a load p does p · v of work moving it: none, and the hold
517
1155
  // carries nothing, so the solve stands as the frame's own.
518
1156
  const span0 = f.span || 1;
519
1157
  const ways = factor.loose.map((i, k) => {
520
- const e = new Float64Array(n); e[i] = 1;
1158
+ const e = new Float64Array(n);
1159
+ e[i] = 1;
521
1160
  const v = factor.solve(e);
522
- let most = 0, turn = 0;
523
- for (let q = 0; q < n; q++) { const a = Math.abs(v[q]); if (back[q] % 6 < 3) most = Math.max(most, a); else turn = Math.max(turn, a); }
1161
+ let most = 0,
1162
+ turn = 0;
1163
+ for (let q = 0; q < n; q++) {
1164
+ const a = Math.abs(v[q]);
1165
+ if (back[q] % 6 < 3) most = Math.max(most, a);
1166
+ else turn = Math.max(turn, a);
1167
+ }
524
1168
  const s = most > 1e-9 * turn * span0 ? 1 / most : 1 / (turn * span0);
525
1169
  for (let q = 0; q < n; q++) v[q] *= s;
526
1170
  return { ...loose[k], v };
@@ -529,86 +1173,247 @@ export function frame(model, o = {}) {
529
1173
  const driven = (p) => {
530
1174
  let size = 0;
531
1175
  for (let q = 0; q < n; q++) size += Math.abs(p[q]) * (back[q] % 6 < 3 ? 1 : 1 / span0);
532
- return ways.filter((w) => { let work = 0; for (let q = 0; q < n; q++) work += p[q] * w.v[q]; return Math.abs(work) > 1e-6 * size; });
1176
+ return ways.filter((w) => {
1177
+ let work = 0;
1178
+ for (let q = 0; q < n; q++) work += p[q] * w.v[q];
1179
+ return Math.abs(work) > 1e-6 * size;
1180
+ });
533
1181
  };
534
- const refuseDriven = (p) => { const d = driven(p); if (d.length) refuse('mechanism', `the loads move the frame where nothing holds it, at ${listOf(d)}: it would move with nothing resisting. Hold those freedoms with a support, or join the elements there more stiffly`, { loose: d.map(({ node, freedom }) => ({ node, freedom })), driven: true }); };
535
- const shapeOf = (x) => { // a vector over the free freedoms as each node's six: its largest movement 1, and that one positive
1182
+ const refuseDriven = (p) => {
1183
+ const d = driven(p);
1184
+ if (d.length)
1185
+ refuse(
1186
+ 'mechanism',
1187
+ `the loads move the frame where nothing holds it, at ${listOf(d)}: it would move with nothing resisting. Hold those freedoms with a support, or join the elements there more stiffly`,
1188
+ { loose: d.map(({ node, freedom }) => ({ node, freedom })), driven: true },
1189
+ );
1190
+ };
1191
+ const shapeOf = (x) => {
1192
+ // a vector over the free freedoms as each node's six: its largest movement 1, and that one positive
536
1193
  const u = new Float64Array(6 * N);
537
1194
  for (let i = 0; i < n; i++) u[back[i]] = x[i];
538
- let most = 0, lead = 0;
1195
+ let most = 0,
1196
+ lead = 0;
539
1197
  for (let p = 0; p < N; p++) most = Math.max(most, Math.hypot(u[6 * p], u[6 * p + 1], u[6 * p + 2]));
540
1198
  const moves = most > 0; // (a shape that only turns, such as a shaft's twist, is scaled by its largest rotation)
541
- for (let i = 0; i < 6 * N; i++) if ((!moves || i % 6 < 3) && Math.abs(u[i]) > Math.abs(lead) * (1 + 1e-9)) lead = u[i];
1199
+ for (let i = 0; i < 6 * N; i++)
1200
+ if ((!moves || i % 6 < 3) && Math.abs(u[i]) > Math.abs(lead) * (1 + 1e-9)) lead = u[i];
542
1201
  const scale = (lead < 0 ? -1 : 1) / ((moves ? most : Math.abs(lead)) || 1);
543
- return Object.fromEntries(ids.map((id, p) => [id, /** @type {Six} */ (Array.from(u.subarray(6 * p, 6 * p + 6), (v) => v * scale))]));
1202
+ return Object.fromEntries(
1203
+ ids.map((id, p) => [id, /** @type {Six} */ (Array.from(u.subarray(6 * p, 6 * p + 6), (v) => v * scale))]),
1204
+ );
544
1205
  };
545
- const caseOf = (c = {}) => ({ loads: c.loads ?? model.loads, gravity: c.gravity ?? model.gravity, masses: c.masses ?? model.masses });
1206
+ const caseOf = (c = {}) => ({
1207
+ loads: c.loads ?? model.loads,
1208
+ gravity: c.gravity ?? model.gravity,
1209
+ masses: c.masses ?? model.masses,
1210
+ });
546
1211
 
547
- function statics(c = {}) {
1212
+ // each solve refuses an option it does not know (statics({ load }) would solve the model's own loads instead)
1213
+ const statics = (c) => solveStatics(options(c, STATICS_OPTIONS, 'statics'));
1214
+ const buckling = (c) => solveBuckling(options(c, BUCKLING_OPTIONS, 'buckling'));
1215
+ const modes = (c) => solveModes(options(c, MODES_OPTIONS, 'modes'));
1216
+
1217
+ function solveStatics(c) {
548
1218
  const samples = c.samples ?? 11;
549
- if (!(Number.isInteger(samples) && samples >= 2)) refuse('input', `samples is ${said(samples)}: a whole number of stations along each element, 2 or more`);
550
- const { nodal, spread } = loadCase(f, caseOf(c)), p = Float64Array.from(nodal);
551
- for (const { node, v } of idle) { const m = [nodal[6 * node + 3], nodal[6 * node + 4], nodal[6 * node + 5]]; if (Math.abs(m[0] * v[0] + m[1] * v[1] + m[2] * v[2]) > 1e-9 * Math.hypot(...m)) refuse('load', `a moment is put on node ${said(ids[node])} about a direction no element there carries (every end at it is pinned that way): join an end to it rigidly or through a spring, or hold that rotation with a support`, { node: ids[node] }); }
1219
+ if (!(Number.isInteger(samples) && samples >= 2))
1220
+ refuse('input', `samples is ${said(samples)}: a whole number of stations along each element, 2 or more`);
1221
+ const { nodal, spread } = loadCase(f, caseOf(c)),
1222
+ p = Float64Array.from(nodal);
1223
+ for (const { node, v } of idle) {
1224
+ const m = [nodal[6 * node + 3], nodal[6 * node + 4], nodal[6 * node + 5]];
1225
+ if (Math.abs(m[0] * v[0] + m[1] * v[1] + m[2] * v[2]) > 1e-9 * Math.hypot(...m))
1226
+ refuse(
1227
+ 'load',
1228
+ `a moment is put on node ${said(ids[node])} about a direction no element there carries (every end at it is pinned that way): join an end to it rigidly or through a spring, or hold that rotation with a support`,
1229
+ { node: ids[node] },
1230
+ );
1231
+ }
552
1232
  const ends = els.map((el, e) => {
553
- const fb = spreadEnds(el.L, spread[3 * e], spread[3 * e + 1], spread[3 * e + 2]), fc = condensedLoad(el, fb);
554
- for (let q = 0; q < 4; q++) { const g = toGlobal3(el.R, fc, 3 * q), at = 6 * (q < 2 ? el.a : el.b) + 3 * (q % 2); for (let k = 0; k < 3; k++) p[at + k] += g[k]; }
1233
+ const fb = spreadEnds(el.L, spread[3 * e], spread[3 * e + 1], spread[3 * e + 2]),
1234
+ fc = condensedLoad(el, fb);
1235
+ for (let q = 0; q < 4; q++) {
1236
+ const g = toGlobal3(el.R, fc, 3 * q),
1237
+ at = 6 * (q < 2 ? el.a : el.b) + 3 * (q % 2);
1238
+ for (let k = 0; k < 3; k++) p[at + k] += g[k];
1239
+ }
555
1240
  return { fb, fc };
556
1241
  });
557
1242
  const pf = Float64Array.from(back, (d) => p[d]);
558
1243
  if (ways.length) refuseDriven(pf);
559
- const x = factor.solve(pf), u = new Float64Array(6 * N), residual = Float64Array.from(nodal, (v) => -v);
1244
+ const x = factor.solve(pf),
1245
+ u = new Float64Array(6 * N),
1246
+ residual = Float64Array.from(nodal, (v) => -v);
560
1247
  for (let i = 0; i < n; i++) u[back[i]] = x[i];
561
- for (const { node, v } of idle) { const o = 6 * node + 3, along = u[o] * v[0] + u[o + 1] * v[1] + u[o + 2] * v[2]; for (let c = 0; c < 3; c++) u[o + c] = held[o + c] || Math.abs(v[c]) === 1 ? 0 : u[o + c] - along * v[c]; }
562
- let most = 0, mostAt = 0;
563
- for (let q = 0; q < N; q++) { const d = Math.hypot(u[6 * q], u[6 * q + 1], u[6 * q + 2]); if (d > most) { most = d; mostAt = q; } }
564
- if (!x.every(Number.isFinite) || most > 1e6 * (f.span || 1)) refuse('mechanism', 'the frame is barely held: under this load it moves many times its own size. Add supports, or join its elements more stiffly', { loose: [] });
1248
+ for (const { node, v } of idle) {
1249
+ const o = 6 * node + 3,
1250
+ along = u[o] * v[0] + u[o + 1] * v[1] + u[o + 2] * v[2];
1251
+ for (let c = 0; c < 3; c++) u[o + c] = held[o + c] || Math.abs(v[c]) === 1 ? 0 : u[o + c] - along * v[c];
1252
+ }
1253
+ let most = 0,
1254
+ mostAt = 0;
1255
+ for (let q = 0; q < N; q++) {
1256
+ const d = Math.hypot(u[6 * q], u[6 * q + 1], u[6 * q + 2]);
1257
+ if (d > most) {
1258
+ most = d;
1259
+ mostAt = q;
1260
+ }
1261
+ }
1262
+ if (!x.every(Number.isFinite) || most > 1e6 * (f.span || 1))
1263
+ refuse(
1264
+ 'mechanism',
1265
+ 'the frame is barely held: under this load it moves many times its own size. Add supports, or join its elements more stiffly',
1266
+ { loose: [] },
1267
+ );
565
1268
  const elements = els.map((el, e) => {
566
- const { L, R } = el, { fb, fc } = ends[e], w = [spread[3 * e], spread[3 * e + 1], spread[3 * e + 2]], d = new Float64Array(12), F = new Float64Array(12);
1269
+ const { L, R } = el,
1270
+ { fb, fc } = ends[e],
1271
+ w = [spread[3 * e], spread[3 * e + 1], spread[3 * e + 2]],
1272
+ d = new Float64Array(12),
1273
+ F = new Float64Array(12);
567
1274
  for (let q = 0; q < 4; q++) d.set(toLocal3(R, u, 6 * (q < 2 ? el.a : el.b) + 3 * (q % 2)), 3 * q);
568
- for (let i = 0; i < 12; i++) { let s = -fc[i]; for (let j = 0; j < 12; j++) s += el.k[i * 12 + j] * d[j]; F[i] = s; }
569
- for (let q = 0; q < 4; q++) { const g = toGlobal3(R, F, 3 * q), at = 6 * (q < 2 ? el.a : el.b) + 3 * (q % 2); for (let k = 0; k < 3; k++) residual[at + k] += g[k]; }
1275
+ for (let i = 0; i < 12; i++) {
1276
+ let s = -fc[i];
1277
+ for (let j = 0; j < 12; j++) s += el.k[i * 12 + j] * d[j];
1278
+ F[i] = s;
1279
+ }
1280
+ for (let q = 0; q < 4; q++) {
1281
+ const g = toGlobal3(R, F, 3 * q),
1282
+ at = 6 * (q < 2 ? el.a : el.b) + 3 * (q % 2);
1283
+ for (let k = 0; k < 3; k++) residual[at + k] += g[k];
1284
+ }
570
1285
  // the beam's own end freedoms, behind any springs: d_beam = T d + H f_s
571
1286
  let db = d;
572
- if (el.T) { db = new Float64Array(12); for (let i = 0; i < 12; i++) { let s = 0; for (let j = 0; j < 12; j++) s += el.T[i * 12 + j] * d[j]; db[i] = s; } el.s.forEach((sp, a) => { el.s.forEach((sq, b) => { db[sp] += el.H[a * el.s.length + b] * fb[sq]; }); }); }
1287
+ if (el.T) {
1288
+ db = new Float64Array(12);
1289
+ for (let i = 0; i < 12; i++) {
1290
+ let s = 0;
1291
+ for (let j = 0; j < 12; j++) s += el.T[i * 12 + j] * d[j];
1292
+ db[i] = s;
1293
+ }
1294
+ el.s.forEach((sp, a) => {
1295
+ el.s.forEach((sq, b) => {
1296
+ db[sp] += el.H[a * el.s.length + b] * fb[sq];
1297
+ });
1298
+ });
1299
+ }
573
1300
  // N, V and M as polynomials in x, from the forces on end a and the spread load between
574
- const poly = { N: [-F[0], -w[0], 0], Vy: [-F[1], -w[1], 0], Vz: [-F[2], -w[2], 0], T: [-F[3], 0, 0], My: [-F[4], -F[2], -w[2] / 2], Mz: [-F[5], F[1], w[1] / 2] };
575
- const value = (c, s) => c[0] + s * (c[1] + s * c[2]), inside = (s) => s > 1e-9 * L && s < L * (1 - 1e-9);
1301
+ const poly = {
1302
+ N: [-F[0], -w[0], 0],
1303
+ Vy: [-F[1], -w[1], 0],
1304
+ Vz: [-F[2], -w[2], 0],
1305
+ T: [-F[3], 0, 0],
1306
+ My: [-F[4], -F[2], -w[2] / 2],
1307
+ Mz: [-F[5], F[1], w[1] / 2],
1308
+ };
1309
+ const value = (c, s) => c[0] + s * (c[1] + s * c[2]),
1310
+ inside = (s) => s > 1e-9 * L && s < L * (1 - 1e-9);
576
1311
  const xs = Array.from({ length: samples }, (_, i) => (L * i) / (samples - 1));
577
1312
  for (const c of [poly.My, poly.Mz]) if (c[2] !== 0 && inside(-c[1] / (2 * c[2]))) xs.push(-c[1] / (2 * c[2]));
578
1313
  xs.sort((a, b) => a - b);
579
- const along = { x: xs, N: [], Vy: [], Vz: [], T: [], My: [], Mz: [], d: [] }, peak = {};
580
- for (const key of ['N', 'Vy', 'Vz', 'T', 'My', 'Mz']) { along[key] = xs.map((s) => value(poly[key], s)); let b = 0; along[key].forEach((v, i) => { if (Math.abs(v) > Math.abs(along[key][b])) b = i; }); peak[key] = { value: along[key][b], x: xs[b] }; }
1314
+ const along = { x: xs, N: [], Vy: [], Vz: [], T: [], My: [], Mz: [], d: [] },
1315
+ peak = {};
1316
+ for (const key of ['N', 'Vy', 'Vz', 'T', 'My', 'Mz']) {
1317
+ along[key] = xs.map((s) => value(poly[key], s));
1318
+ let b = 0;
1319
+ along[key].forEach((v, i) => {
1320
+ if (Math.abs(v) > Math.abs(along[key][b])) b = i;
1321
+ });
1322
+ peak[key] = { value: along[key][b], x: xs[b] };
1323
+ }
581
1324
  along.d = xs.map((s) => {
582
- const xi = s / L, ny = shape(xi, L, el.phi[0]).N, nz = shape(xi, L, el.phi[1]).N, bend = (s * s * (L - s) * (L - s)) / 24, sh = (s * (L - s)) / 2;
583
- const local = [(1 - xi) * db[0] + xi * db[6] + (w[0] * sh) / el.EA,
584
- ny[0] * db[1] + ny[1] * db[5] + ny[2] * db[7] + ny[3] * db[11] + (w[1] * bend) / el.EIz + (el.GAy ? (w[1] * sh) / el.GAy : 0),
585
- nz[0] * db[2] - nz[1] * db[4] + nz[2] * db[8] - nz[3] * db[10] + (w[2] * bend) / el.EIy + (el.GAz ? (w[2] * sh) / el.GAz : 0)];
1325
+ const xi = s / L,
1326
+ ny = shape(xi, L, el.phi[0]).N,
1327
+ nz = shape(xi, L, el.phi[1]).N,
1328
+ bend = (s * s * (L - s) * (L - s)) / 24,
1329
+ sh = (s * (L - s)) / 2;
1330
+ const local = [
1331
+ (1 - xi) * db[0] + xi * db[6] + (w[0] * sh) / el.EA,
1332
+ ny[0] * db[1] +
1333
+ ny[1] * db[5] +
1334
+ ny[2] * db[7] +
1335
+ ny[3] * db[11] +
1336
+ (w[1] * bend) / el.EIz +
1337
+ (el.GAy ? (w[1] * sh) / el.GAy : 0),
1338
+ nz[0] * db[2] -
1339
+ nz[1] * db[4] +
1340
+ nz[2] * db[8] -
1341
+ nz[3] * db[10] +
1342
+ (w[2] * bend) / el.EIy +
1343
+ (el.GAz ? (w[2] * sh) / el.GAz : 0),
1344
+ ];
586
1345
  return /** @type {Vec3} */ (toGlobal3(R, local));
587
1346
  });
588
- const result = { id: el.id, ...(el.of !== undefined ? { of: el.of } : {}), length: L, axes: /** @type {[Vec3, Vec3, Vec3]} */ ([0, 3, 6].map((o) => Array.from(R.subarray(o, o + 3)))),
589
- ends: { a: /** @type {Six} */ (Array.from(F.subarray(0, 6))), b: /** @type {Six} */ (Array.from(F.subarray(6, 12))) }, along, peak: /** @type {ElementResult['peak']} */ (peak), axial: value(poly.N, L / 2) };
1347
+ const result = {
1348
+ id: el.id,
1349
+ ...(el.of !== undefined ? { of: el.of } : {}),
1350
+ length: L,
1351
+ axes: /** @type {[Vec3, Vec3, Vec3]} */ ([0, 3, 6].map((o) => Array.from(R.subarray(o, o + 3)))),
1352
+ ends: {
1353
+ a: /** @type {Six} */ (Array.from(F.subarray(0, 6))),
1354
+ b: /** @type {Six} */ (Array.from(F.subarray(6, 12))),
1355
+ },
1356
+ along,
1357
+ peak: /** @type {ElementResult['peak']} */ (peak),
1358
+ axial: value(poly.N, L / 2),
1359
+ };
590
1360
  if (el.Wy && el.Wz) {
591
1361
  // |N|/A + |My|/Wy + |Mz|/Wz is a quadratic wherever no term changes sign: its peak is at an end, where a
592
1362
  // moment peaks (both already stations), or where one of the signed sums is level
593
- const terms = [[poly.N, 1 / el.A], [poly.My, 1 / el.Wy], [poly.Mz, 1 / el.Wz]], at = (s) => terms.reduce((sum, [c, k]) => sum + Math.abs(value(c, s)) * k, 0), tries = [...xs];
594
- for (const sy of [1, -1]) for (const sz of [1, -1]) { const c1 = poly.N[1] / el.A + (sy * poly.My[1]) / el.Wy + (sz * poly.Mz[1]) / el.Wz, c2 = (sy * poly.My[2]) / el.Wy + (sz * poly.Mz[2]) / el.Wz; if (c2 !== 0 && inside(-c1 / (2 * c2))) tries.push(-c1 / (2 * c2)); }
595
- let best = 0, bending = 0;
596
- for (const s of tries) { if (at(s) > at(best)) best = s; bending = Math.max(bending, Math.abs(value(poly.My, s)) / el.Wy + Math.abs(value(poly.Mz, s)) / el.Wz); }
1363
+ const terms = [
1364
+ [poly.N, 1 / el.A],
1365
+ [poly.My, 1 / el.Wy],
1366
+ [poly.Mz, 1 / el.Wz],
1367
+ ],
1368
+ at = (s) => terms.reduce((sum, [c, k]) => sum + Math.abs(value(c, s)) * k, 0),
1369
+ tries = [...xs];
1370
+ for (const sy of [1, -1])
1371
+ for (const sz of [1, -1]) {
1372
+ const c1 = poly.N[1] / el.A + (sy * poly.My[1]) / el.Wy + (sz * poly.Mz[1]) / el.Wz,
1373
+ c2 = (sy * poly.My[2]) / el.Wy + (sz * poly.Mz[2]) / el.Wz;
1374
+ if (c2 !== 0 && inside(-c1 / (2 * c2))) tries.push(-c1 / (2 * c2));
1375
+ }
1376
+ let best = 0,
1377
+ bending = 0;
1378
+ for (const s of tries) {
1379
+ if (at(s) > at(best)) best = s;
1380
+ bending = Math.max(bending, Math.abs(value(poly.My, s)) / el.Wy + Math.abs(value(poly.Mz, s)) / el.Wz);
1381
+ }
597
1382
  result.stress = { peak: at(best), bending, axial: value(poly.N, best) / el.A, x: best };
598
1383
  }
599
1384
  return result;
600
1385
  });
601
1386
  const six = (v, q) => /** @type {Six} */ (Array.from(v.subarray(6 * q, 6 * q + 6)));
602
- return { displacements: Object.fromEntries(ids.map((id, q) => [id, six(u, q)])), reactions: Object.fromEntries(f.supported.map((q) => [ids[q], six(residual, q).map((v, d) => (held[6 * q + d] || ground[6 * q + d] ? v : 0))])),
603
- elements, deflection: { most, node: ids[mostAt] } };
1387
+ return {
1388
+ displacements: Object.fromEntries(ids.map((id, q) => [id, six(u, q)])),
1389
+ reactions: Object.fromEntries(
1390
+ f.supported.map((q) => [
1391
+ ids[q],
1392
+ six(residual, q).map((v, d) => (held[6 * q + d] || ground[6 * q + d] ? v : 0)),
1393
+ ]),
1394
+ ),
1395
+ elements,
1396
+ deflection: { most, node: ids[mostAt] },
1397
+ };
604
1398
  }
605
1399
 
606
- function buckling(c = {}) {
1400
+ function solveBuckling(c) {
607
1401
  const count = c.count ?? 1;
608
- if (!(Number.isInteger(count) && count >= 1)) refuse('input', `count is ${said(count)}: how many buckling modes, a whole number from 1`);
609
- const s = statics(c), axial = s.elements.map((e) => e.axial), size = Math.max(...axial.map(Math.abs));
610
- if (!axial.some((a) => a < -1e-9 * Math.max(size, 1e-300))) refuse('compression', 'no element is in compression under these loads, so nothing can buckle: buckling needs a load that squeezes at least one element along its length');
611
- const B = assemble((el) => toGlobal(el.kg, el.R), axial.map((a) => -a)), block = 2 * count + 16;
1402
+ if (!(Number.isInteger(count) && count >= 1))
1403
+ refuse('input', `count is ${said(count)}: how many buckling modes, a whole number from 1`);
1404
+ const s = solveStatics(c),
1405
+ axial = s.elements.map((e) => e.axial),
1406
+ size = Math.max(...axial.map(Math.abs));
1407
+ if (!axial.some((a) => a < -1e-9 * Math.max(size, 1e-300)))
1408
+ refuse(
1409
+ 'compression',
1410
+ 'no element is in compression under these loads, so nothing can buckle: buckling needs a load that squeezes at least one element along its length',
1411
+ );
1412
+ const B = assemble(
1413
+ (el) => toGlobal(el.kg, el.R),
1414
+ axial.map((a) => -a),
1415
+ ),
1416
+ block = 2 * count + 16;
612
1417
  // Where the frame is held only by the hold (loose: 'hold'), K v = 0 along the way v it moves unresisted, so
613
1418
  // vᵀ (K − λ B) v = −λ vᵀ B v. If the loads lean on that way (vᵀ B v > 0, as a frame on pinned feet with its posts
614
1419
  // squeezed leans over), K − λ B loses its positive definiteness at any λ above 0: the frame tips over under any
@@ -623,14 +1428,26 @@ export function frame(model, o = {}) {
623
1428
  const tipped = [];
624
1429
  for (const w of ways) {
625
1430
  const Bv = multiply(B, w.v);
626
- let g = 0, vv = 0, bb = 0;
627
- for (let q = 0; q < n; q++) { g += w.v[q] * Bv[q]; vv += w.v[q] * w.v[q]; bb += Bv[q] * Bv[q]; }
1431
+ let g = 0,
1432
+ vv = 0,
1433
+ bb = 0;
1434
+ for (let q = 0; q < n; q++) {
1435
+ g += w.v[q] * Bv[q];
1436
+ vv += w.v[q] * w.v[q];
1437
+ bb += Bv[q] * Bv[q];
1438
+ }
628
1439
  const tol = 1e-6 * bmax * vv;
629
- if (g > tol || (g >= -tol && Math.sqrt(bb) > 1e-6 * bmax * Math.sqrt(vv))) tipped.push(w); else if (g < -tol) rests.push({ node: w.node, freedom: w.freedom });
1440
+ if (g > tol || (g >= -tol && Math.sqrt(bb) > 1e-6 * bmax * Math.sqrt(vv))) tipped.push(w);
1441
+ else if (g < -tol) rests.push({ node: w.node, freedom: w.freedom });
630
1442
  }
631
1443
  if (tipped.length) {
632
1444
  const shown = tipped.slice(0, count).map((w) => ({ factor: 0, shape: shapeOf(w.v) }));
633
- return { factors: shown.map((m) => m.factor), modes: shown, statics: s, tipped: tipped.map(({ node, freedom }) => ({ node, freedom })) };
1445
+ return {
1446
+ factors: shown.map((m) => m.factor),
1447
+ modes: shown,
1448
+ statics: s,
1449
+ tipped: tipped.map(({ node, freedom }) => ({ node, freedom })),
1450
+ };
634
1451
  }
635
1452
  }
636
1453
  // K φ = λ B φ, B = −Kg, for the smallest λ above 0. B is indefinite: with the loads reversed, whatever is in
@@ -640,26 +1457,45 @@ export function frame(model, o = {}) {
640
1457
  // iteration on (K − σ B)⁻¹ B then finds 1 / (λ − σ), where the first factor leads every negative one at least
641
1458
  // fourfold. (Factors more than about twice the first still have to outlast the negative ones, by a wider block:
642
1459
  // the first is always quick, the rest only when little is in tension.)
643
- let high = Infinity, low = 0, shifted = factor;
644
- for (let i = 0; i < n; i++) { const b = B.v[diagonal(B, i)]; if (b > 0) high = Math.min(high, K.v[diagonal(K, i)] / b); } // one freedom moved alone: no frame buckles later than that
1460
+ let high = Infinity,
1461
+ low = 0,
1462
+ shifted = factor;
1463
+ for (let i = 0; i < n; i++) {
1464
+ const b = B.v[diagonal(B, i)];
1465
+ if (b > 0) high = Math.min(high, K.v[diagonal(K, i)] / b);
1466
+ } // one freedom moved alone: no frame buckles later than that
645
1467
  const rough = lowest(factor.solve, B, 1, block, 1e-3, 4);
646
1468
  if (rough.values.length) high = Math.min(high, 1 / rough.values[0]); // (a Ritz value is never under the true one)
647
- if (Number.isFinite(high)) for (let tries = 0, sigma = 0.9 * high; tries < 60 && low < 0.8 * high; tries++, sigma = low ? (low + high) / 2 : high / 2) {
648
- const A = profile(first);
649
- for (let i = 0; i < A.v.length; i++) A.v[i] = K.v[i] - sigma * B.v[i];
650
- const fa = factorise(A);
651
- if (fa.loose.length) high = sigma; else { low = sigma; shifted = fa; }
652
- }
1469
+ if (Number.isFinite(high))
1470
+ for (
1471
+ let tries = 0, sigma = 0.9 * high;
1472
+ tries < 60 && low < 0.8 * high;
1473
+ tries++, sigma = low ? (low + high) / 2 : high / 2
1474
+ ) {
1475
+ const A = profile(first);
1476
+ for (let i = 0; i < A.v.length; i++) A.v[i] = K.v[i] - sigma * B.v[i];
1477
+ const fa = factorise(A);
1478
+ if (fa.loose.length) high = sigma;
1479
+ else {
1480
+ low = sigma;
1481
+ shifted = fa;
1482
+ }
1483
+ }
653
1484
  const { values, vectors } = lowest(shifted.solve, B, count, block);
654
1485
  const modes = values.map((mu, i) => ({ factor: low + 1 / mu, shape: shapeOf(vectors[i]) }));
655
1486
  return { factors: modes.map((m) => m.factor), modes, statics: s, ...(rests.length ? { rests } : {}) };
656
1487
  }
657
1488
 
658
- function modes(c = {}) {
1489
+ function solveModes(c) {
659
1490
  const count = c.count ?? 6;
660
- if (!(Number.isInteger(count) && count >= 1)) refuse('input', `count is ${said(count)}: how many modes, a whole number from 1`);
1491
+ if (!(Number.isInteger(count) && count >= 1))
1492
+ refuse('input', `count is ${said(count)}: how many modes, a whole number from 1`);
661
1493
  const { lumped } = loadCase(f, { masses: c.masses ?? model.masses });
662
- if (!els.some((el) => el.perLength > 0) && !lumped.some((m) => m > 0)) refuse('mass', 'nothing in the frame has mass, so it has no frequencies: give the materials a density (g/cm³), or lump masses (kg) at nodes');
1494
+ if (!els.some((el) => el.perLength > 0) && !lumped.some((m) => m > 0))
1495
+ refuse(
1496
+ 'mass',
1497
+ 'nothing in the frame has mass, so it has no frequencies: give the materials a density (g/cm³), or lump masses (kg) at nodes',
1498
+ );
663
1499
  const M = assemble((el) => toGlobal(el.m, el.R));
664
1500
  for (let i = 0; i < n; i++) if (back[i] % 6 < 3) M.v[diagonal(M, i)] += lumped[Math.floor(back[i] / 6)];
665
1501
  // Where the frame is held only by the hold (loose: 'hold'), the hold would stand in for a support that is not
@@ -668,7 +1504,8 @@ export function frame(model, o = {}) {
668
1504
  // K x = λ M x exactly when (K + s M) x = (λ + s) M x, so each way that moves mass unresisted comes back as a
669
1505
  // mode of λ = 0 (0 Hz, marked free) and the rest are the frame's own, with nothing held. A way that moves no
670
1506
  // mass is still held in K + s M, which changes nothing (K v = M v = 0: each shape has a copy with it at 0).
671
- let solveM = factor.solve, shift = 0;
1507
+ let solveM = factor.solve,
1508
+ shift = 0;
672
1509
  if (factor.loose.length) {
673
1510
  const rough = lowest(factor.solve, M, 1, undefined, 1e-3, 60);
674
1511
  shift = rough.values.length ? 1 / rough.values[0] : 1;
@@ -679,8 +1516,13 @@ export function frame(model, o = {}) {
679
1516
  const { values, vectors } = lowest(solveM, M, count);
680
1517
  // K in N/mm against M in kg: ω² = 1000 λ, λ = 1 / μ − s (a newton is a kg·m/s², and the lengths are mm)
681
1518
  const found = values.map((mu, i) => {
682
- const lambda = 1 / mu - shift, free = shift > 0 && lambda < 1e-6 * shift;
683
- return { frequency: free ? 0 : Math.sqrt(1000 * lambda) / (2 * Math.PI), shape: shapeOf(vectors[i]), ...(free ? { free: true } : {}) };
1519
+ const lambda = 1 / mu - shift,
1520
+ free = shift > 0 && lambda < 1e-6 * shift;
1521
+ return {
1522
+ frequency: free ? 0 : Math.sqrt(1000 * lambda) / (2 * Math.PI),
1523
+ shape: shapeOf(vectors[i]),
1524
+ ...(free ? { free: true } : {}),
1525
+ };
684
1526
  });
685
1527
  return { frequencies: found.map((m) => m.frequency), modes: found };
686
1528
  }
@@ -690,27 +1532,45 @@ export function frame(model, o = {}) {
690
1532
  return { statics, buckling, modes, freedoms: n, nodes: ids, loose, mechanisms };
691
1533
  }
692
1534
 
1535
+ // statics, buckling and modes as one call take frame()'s options and the solve's: split here, each refused by the call's name
1536
+ const oneCall = (o, own, what) => {
1537
+ const { shear, ...rest } = options(o, [...FRAME_OPTIONS, ...own], what);
1538
+ return [shear === undefined ? {} : { shear }, rest];
1539
+ };
1540
+
693
1541
  /**
694
1542
  * How far a frame moves under its loads, and what each element carries. The same as `frame(model).statics()`.
695
- * @param {FrameModel} model @param {{ shear?: boolean, samples?: number }} [o]
1543
+ * @param {FrameModel} model @param {{ shear?: boolean, loads?: FrameLoad[], gravity?: Vec3, masses?: Record<string, number>, samples?: number }} [o]
1544
+ * frame()'s option and statics'; any other key is refused (`fea.frame.input`)
696
1545
  * @returns {StaticResult}
697
1546
  */
698
- export const statics = (model, o = {}) => frame(model, o).statics(o);
1547
+ export const statics = (model, o = {}) => {
1548
+ const [fo, so] = oneCall(o, STATICS_OPTIONS, 'statics');
1549
+ return frame(model, fo).statics(so);
1550
+ };
699
1551
  /**
700
1552
  * The factors by which a frame's loads must grow to buckle it, lowest first, and the shapes it buckles into: linear
701
1553
  * buckling, from the geometric stiffness of each element's axial force in the static solve. The first factor is
702
1554
  * always quick to find; asking for more costs more where slender members are in tension.
703
- * @param {FrameModel} model @param {{ shear?: boolean, count?: number }} [o] count: how many modes (1)
1555
+ * @param {FrameModel} model @param {{ shear?: boolean, count?: number, loads?: FrameLoad[], gravity?: Vec3, masses?: Record<string, number> }} [o]
1556
+ * count: how many modes (1); any other key is refused (`fea.frame.input`)
704
1557
  * @returns {{ factors: number[], modes: BucklingMode[], statics: StaticResult, tipped?: { node: string, freedom: string }[], rests?: { node: string, freedom: string }[] }}
705
1558
  * tipped and rests: with loose: 'hold', as `frame` says
706
1559
  */
707
- export const buckling = (model, o = {}) => frame(model, o).buckling(o);
1560
+ export const buckling = (model, o = {}) => {
1561
+ const [fo, bo] = oneCall(o, BUCKLING_OPTIONS, 'buckling');
1562
+ return frame(model, fo).buckling(bo);
1563
+ };
708
1564
  /**
709
1565
  * A frame's lowest natural frequencies, in Hz, and their shapes, from the elements' consistent mass and the lumped masses.
710
- * @param {FrameModel} model @param {{ shear?: boolean, count?: number }} [o] count: how many modes (6)
1566
+ * @param {FrameModel} model @param {{ shear?: boolean, count?: number, masses?: Record<string, number> }} [o] count: how
1567
+ * many modes (6); any other key is refused (`fea.frame.input`)
711
1568
  * @returns {{ frequencies: number[], modes: VibrationMode[] }}
712
1569
  */
713
- export const modes = (model, o = {}) => frame(model, o).modes(o);
1570
+ export const modes = (model, o = {}) => {
1571
+ const [fo, mo] = oneCall(o, MODES_OPTIONS, 'modes');
1572
+ return frame(model, fo).modes(mo);
1573
+ };
714
1574
 
715
1575
  /**
716
1576
  * The same frame with every element cut into `pieces` equal lengths, for buckling and modes: one element cannot bow
@@ -721,19 +1581,49 @@ export const modes = (model, o = {}) => frame(model, o).modes(o);
721
1581
  * @returns {FrameModel}
722
1582
  */
723
1583
  export function subdivide(model, pieces = 4) {
724
- if (!(Number.isInteger(pieces) && pieces >= 1)) refuse('input', `pieces is ${said(pieces)}: a whole number of pieces for each element, 1 or more`);
725
- if (!model || typeof model !== 'object' || !model.nodes || !Array.isArray(model.elements)) refuse('input', 'a frame is { nodes, elements, supports, loads }');
726
- const list = Array.isArray(model.nodes), nodes = list ? [...model.nodes] : { ...model.nodes }, parts = new Map();
1584
+ if (!(Number.isInteger(pieces) && pieces >= 1))
1585
+ refuse('input', `pieces is ${said(pieces)}: a whole number of pieces for each element, 1 or more`);
1586
+ if (!model || typeof model !== 'object' || !model.nodes || !Array.isArray(model.elements))
1587
+ refuse('input', 'a frame is { nodes, elements, supports, loads }');
1588
+ const list = Array.isArray(model.nodes),
1589
+ nodes = list ? [...model.nodes] : { ...model.nodes },
1590
+ parts = new Map();
727
1591
  const elements = model.elements.flatMap((e, i) => {
728
- const id = e.id ?? i, pa = model.nodes[e.a], pb = model.nodes[e.b];
729
- for (const [end, p] of [[e.a, pa], [e.b, pb]]) if (!isVec3(p)) refuse('node', `element ${said(id)} names node ${said(end)}, which is not in nodes`, { node: end });
730
- const mid = Array.from({ length: pieces - 1 }, (_, k) => { const t = (k + 1) / pieces, p = /** @type {Vec3} */ (pa.map((v, c) => v + t * (pb[c] - v))); if (list) return nodes.push(p) - 1; nodes[`${id}/${k + 1}`] = p; return `${id}/${k + 1}`; });
731
- const made = Array.from({ length: pieces }, (_, k) => ({ ...e, id: pieces === 1 ? id : `${id}/${k + 1}`, of: e.of ?? id, a: k ? mid[k - 1] : e.a, b: k < pieces - 1 ? mid[k] : e.b,
732
- ends: { a: k ? 'rigid' : e.ends?.a ?? 'rigid', b: k < pieces - 1 ? 'rigid' : e.ends?.b ?? 'rigid' } }));
733
- parts.set(String(id), made.map((m) => m.id));
1592
+ const id = e.id ?? i,
1593
+ pa = model.nodes[e.a],
1594
+ pb = model.nodes[e.b];
1595
+ for (const [end, p] of [
1596
+ [e.a, pa],
1597
+ [e.b, pb],
1598
+ ])
1599
+ if (!isVec3(p))
1600
+ refuse('node', `element ${said(id)} names node ${said(end)}, which is not in nodes`, { node: end });
1601
+ const mid = Array.from({ length: pieces - 1 }, (_, k) => {
1602
+ const t = (k + 1) / pieces,
1603
+ p = /** @type {Vec3} */ (pa.map((v, c) => v + t * (pb[c] - v)));
1604
+ if (list) return nodes.push(p) - 1;
1605
+ nodes[`${id}/${k + 1}`] = p;
1606
+ return `${id}/${k + 1}`;
1607
+ });
1608
+ const made = Array.from({ length: pieces }, (_, k) => ({
1609
+ ...e,
1610
+ id: pieces === 1 ? id : `${id}/${k + 1}`,
1611
+ of: e.of ?? id,
1612
+ a: k ? mid[k - 1] : e.a,
1613
+ b: k < pieces - 1 ? mid[k] : e.b,
1614
+ ends: { a: k ? 'rigid' : (e.ends?.a ?? 'rigid'), b: k < pieces - 1 ? 'rigid' : (e.ends?.b ?? 'rigid') },
1615
+ }));
1616
+ parts.set(
1617
+ String(id),
1618
+ made.map((m) => m.id),
1619
+ );
734
1620
  return made;
735
1621
  });
736
- const loads = (model.loads || []).flatMap((l) => (l && 'element' in l && parts.has(String(l.element)) ? parts.get(String(l.element)).map((element) => ({ ...l, element })) : [l]));
1622
+ const loads = (model.loads || []).flatMap((l) =>
1623
+ l && 'element' in l && parts.has(String(l.element))
1624
+ ? parts.get(String(l.element)).map((element) => ({ ...l, element }))
1625
+ : [l],
1626
+ );
737
1627
  return { ...model, nodes, elements, ...(model.loads ? { loads } : {}) };
738
1628
  }
739
1629
 
@@ -749,13 +1639,16 @@ export function subdivide(model, pieces = 4) {
749
1639
  * @property {number} [cost] per metre, in any one currency, for sizing by cost
750
1640
  * @property {number} [roll] degrees added to the member's roll: the same section turned about its length (a 20 x 40
751
1641
  * standing on edge in place of lying flat)
1642
+ * @property {string} [profile] carried along for the caller, not read (profileChoices gives the profile's name)
1643
+ * @property {string} [title] carried along for the caller, not read; any key not listed here is refused by name
752
1644
  */
753
1645
  /**
754
1646
  * @typedef {object} SizingLimits What every design must meet; leave one out and it sets nothing
755
1647
  * @property {({ node: string | number, limit: number, along?: Vec3 } | { member: string | number, limit: number, from?: number, to?: number, along?: Vec3 })[]} [deflection]
756
1648
  * a node, or a member between two distances from its start (mm, its whole length if left out), moves no more than
757
1649
  * limit mm along `along` (gravity's direction, else the whole movement)
758
- * @property {{ margin: number }} [stress] each member's peak stress times margin stays under its material's strength
1650
+ * @property {{ margin: number }} [stress] each member's peak stress times margin stays under its material's strength:
1651
+ * every choice a group may take needs a strength and a section modulus, or sizing is refused
759
1652
  * @property {{ factor: number, euler?: number }} [buckling] the whole frame's first buckling factor is at least
760
1653
  * factor; with euler (the effective length factor K), each member in compression also carries factor times its
761
1654
  * force under Euler's load π² E I / (K L)², I the lesser second moment (the grouped members only)
@@ -774,7 +1667,12 @@ export function subdivide(model, pieces = 4) {
774
1667
  const dot = (u, v) => u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
775
1668
  const named = (v, table) => (typeof v === 'string' ? table?.[v] : v);
776
1669
  const SIZE_LIMITS = ['deflection', 'stress', 'buckling', 'frequency'];
777
- const SIZE_KEYS = ['groups', 'choices', 'only', 'fits', 'limits', 'cases', 'bounds', 'by', 'pieces', 'search', 'every'];
1670
+ const SIZE_KEYS = ['groups', 'choices', 'only', 'fits', 'ends', 'limits', 'cases', 'by', 'pieces', 'search', 'every'];
1671
+ const CASE_KEYS = ['label', 'loads', 'masses', 'inertia', 'gravity', 'limits'];
1672
+ // a choice's keys: the ones sizing reads, and two a caller may carry along for its own use (profileChoices gives both)
1673
+ const CHOICE_KEYS = ['name', 'section', 'material', 'mass', 'cost', 'roll', 'profile', 'title'];
1674
+ const LIMIT_KEYS = { stress: ['margin'], buckling: ['factor', 'euler'], frequency: ['Hz'] },
1675
+ DEFLECTION_KEYS = ['node', 'member', 'limit', 'from', 'to', 'along', 'cases'];
778
1676
 
779
1677
  /**
780
1678
  * The lightest section for each group of members that meets the limits: each group (members that must match, a pair
@@ -784,19 +1682,28 @@ const SIZE_KEYS = ['groups', 'choices', 'only', 'fits', 'limits', 'cases', 'boun
784
1682
  * the limits are met, then each down as far as the limits allow), which is near the lightest but not proven so. Each
785
1683
  * group's result names the limit that set it: the one its next lighter choice would break, with the other groups as
786
1684
  * chosen. The geometry stays as drawn: only sections, materials and rolls change, and members outside every group
787
- * keep theirs. Refused by name: unknown options, a member in no element or in two groups, a choice with no section,
788
- * a limit that is not above 0, and sizing by cost where a choice has none.
1685
+ * keep theirs; with ends, each design's element end springs are its own too (a join's spring follows the size of the
1686
+ * beams it joins). Refused by name: unknown options (and unknown keys in a choice, a load case or a limit; a choice
1687
+ * may also carry profile and title, which sizing does not read), a member in no element
1688
+ * or in two groups, a choice with no section, a limit that is not above 0, sizing by cost where a choice has none,
1689
+ * and, under a stress limit, a choice a group may take with no strength (its material's, or the member's where it
1690
+ * has none: fea.frame.material) or no section modulus (cy and cz, or Wy and Wz: fea.frame.section). A member outside
1691
+ * every group with either missing is not refused but cannot be held to the stress limit: it is named in `unchecked`.
789
1692
  * @param {FrameModel | FrameModel[]} model the frame; or a list, the first the frame and the rest the same frame
790
1693
  * joined other ways (its joins rigid), whose stress is checked too, as a join's moment grows as it stiffens
791
1694
  * @param {{ groups: Record<string, (string | number)[]>, choices: SizingChoice[], only?: Record<string, string[]>,
792
1695
  * fits?: (design: Record<string, string>) => { where: string, why: string }[],
1696
+ * ends?: (design: Record<string, string>) => Record<string, { a?: EndJoin, b?: EndJoin }>,
793
1697
  * limits: SizingLimits, cases?: { label?: string, loads?: FrameLoad[], masses?: Record<string, number>, inertia?: Record<string, number>, gravity?: Vec3, limits?: string[] }[],
794
1698
  * by?: 'mass' | 'cost', pieces?: number, search?: 'every' | 'steps', every?: number }} o
795
1699
  * groups: members by group name, each an element's id or the member its pieces came from (`of`); only: the
796
1700
  * choices a group may take, by name (all of them if left out); fits: whether a design's choices go together, given
797
1701
  * each group's choice by name: what does not (a join between two groups that one's choice cannot make with the
798
1702
  * other's), each { where, why }, none where it fits; a design that does not fit is never solved, and a group
799
- * whose next lighter choice does not fit says so as the limit that set it (limit 'fit'); cases: load cases (the
1703
+ * whose next lighter choice does not fit says so as the limit that set it (limit 'fit'); ends: each design's own
1704
+ * end springs, given each group's choice by name: the ends that change with the design, by element id, each end
1705
+ * given in place of the frame's own and the rest kept; asked once a design, for the frame alone (the others,
1706
+ * joined other ways, keep theirs); cases: load cases (the
800
1707
  * model's own if left out), loads and masses as statics takes them, inertia: masses whose weight is already in
801
1708
  * loads, which ring in the modes only, gravity: the case's own (a side push alone: [0, 0, 0]), and limits: the
802
1709
  * limits it is held to, by name (every limit where left out; a deflection limit's own cases narrow it further);
@@ -804,108 +1711,318 @@ const SIZE_KEYS = ['groups', 'choices', 'only', 'fits', 'limits', 'cases', 'boun
804
1711
  * @returns {{ ok: boolean, by: 'mass' | 'cost', search: 'every' | 'steps', tried: number, total: number,
805
1712
  * groups: { name: string, members: (string | number)[], choice: string, length: number, mass: number, cost: number | null,
806
1713
  * lighter: string | null, governs: (SizingCheck & { lighter: string, broken: number }) | { limit: 'fit', where: string, why: string, lighter: string, broken: null } | null, margin: number | null }[],
807
- * checks: SizingCheck[], worst: SizingCheck | null, model: FrameModel }}
1714
+ * checks: SizingCheck[], unchecked: { member: string, why: 'no strength' | 'no section modulus' | 'no strength and no section modulus' }[],
1715
+ * worst: SizingCheck | null, model: FrameModel }}
808
1716
  * ok: the limits are met (else the design that came nearest, and its checks say by how much); total: kg (or cost) of
809
1717
  * the grouped members; tried: designs solved; each group's length (mm), mass (kg) and cost; lighter: the next choice
810
1718
  * that weighs (or costs) less; governs: the limit that lighter choice breaks, its ratio there as `broken`; margin: how many times inside
811
- * that limit the design is, as chosen; model: the frame with the chosen sections
1719
+ * that limit the design is, as chosen; unchecked: under a stress limit, the members outside every group whose stress
1720
+ * it could not check, each once (by the member its pieces came from) with why: its material has no strength, or its
1721
+ * section no section modulus, so no stress is read in it (a join's rigid link, a panel); empty with no stress limit;
1722
+ * model: the frame with the chosen sections
812
1723
  */
813
1724
  export function sizing(model, o = {}) {
814
- const models = Array.isArray(model) ? model : [model], base = models[0];
815
- if (!base || typeof base !== 'object' || !Array.isArray(base.elements)) refuse('input', 'sizing takes a frame, { nodes, elements, supports, loads }, or a list of frames: the first the frame, the rest it joined other ways');
1725
+ const models = Array.isArray(model) ? model : [model],
1726
+ base = models[0];
1727
+ if (!base || typeof base !== 'object' || !Array.isArray(base.elements))
1728
+ refuse(
1729
+ 'input',
1730
+ 'sizing takes a frame, { nodes, elements, supports, loads }, or a list of frames: the first the frame, the rest it joined other ways',
1731
+ );
816
1732
  if (!o || typeof o !== 'object') refuse('input', 'sizing takes { groups, choices, limits }');
817
- for (const k of Object.keys(o)) if (!SIZE_KEYS.includes(k)) refuse('input', `sizing has no option "${k}": it takes ${SIZE_KEYS.join(', ')}`);
818
- const by = o.by ?? 'mass', pieces = o.pieces ?? 4, every = o.every ?? 512;
1733
+ for (const k of Object.keys(o))
1734
+ if (!SIZE_KEYS.includes(k)) refuse('input', `sizing has no option "${k}": it takes ${SIZE_KEYS.join(', ')}`);
1735
+ const by = o.by ?? 'mass',
1736
+ pieces = o.pieces ?? 4,
1737
+ every = o.every ?? 512;
819
1738
  if (!['mass', 'cost'].includes(by)) refuse('input', `by is 'mass' or 'cost' (got ${said(o.by)})`);
820
- if (!(Number.isInteger(pieces) && pieces >= 1)) refuse('input', `pieces is a whole number from 1 (got ${said(o.pieces)})`);
821
- if (o.search != null && !['every', 'steps'].includes(o.search)) refuse('input', `search is 'every' (rank every design by mass and take the first that meets the limits) or 'steps' (got ${said(o.search)})`);
1739
+ if (!(Number.isInteger(pieces) && pieces >= 1))
1740
+ refuse('input', `pieces is a whole number from 1 (got ${said(o.pieces)})`);
1741
+ if (o.search != null && !['every', 'steps'].includes(o.search))
1742
+ refuse(
1743
+ 'input',
1744
+ `search is 'every' (rank every design by mass and take the first that meets the limits) or 'steps' (got ${said(o.search)})`,
1745
+ );
822
1746
  // the choices
823
- if (!Array.isArray(o.choices) || !o.choices.length) refuse('input', 'choices is a list of { name, section, material, mass }: the sections a group may be given');
1747
+ if (!Array.isArray(o.choices) || !o.choices.length)
1748
+ refuse('input', 'choices is a list of { name, section, material, mass }: the sections a group may be given');
824
1749
  const choices = new Map();
825
1750
  for (const [i, c] of o.choices.entries()) {
826
- if (!c || typeof c !== 'object' || typeof c.name !== 'string' || !c.name) refuse('input', `choice ${i + 1} is ${said(c)}: a choice is { name, section, material, mass, cost, roll }`);
1751
+ if (!c || typeof c !== 'object' || typeof c.name !== 'string' || !c.name)
1752
+ refuse('input', `choice ${i + 1} is ${said(c)}: a choice is { name, section, material, mass, cost, roll }`);
827
1753
  if (choices.has(c.name)) refuse('input', `choice ${said(c.name)} is listed twice`);
828
- if (!c.section || typeof c.section !== 'object') refuse('section', `choice ${said(c.name)} has no section: { A, Iy, Iz, J } in mm² and mm⁴`);
829
- for (const key of ['A', 'Iy', 'Iz', 'J']) if (!(c.section[key] > 0)) refuse('section', `choice ${said(c.name)}'s section has ${key} = ${said(c.section[key])}: it needs ${key} above 0`);
830
- if (c.material != null && !(c.material?.E > 0)) refuse('material', `choice ${said(c.name)}'s material has no E above 0 (got ${said(c.material)})`);
831
- for (const key of ['mass', 'cost']) if (c[key] != null && !(c[key] >= 0)) refuse('input', `choice ${said(c.name)}'s ${key} is per metre, 0 or more (got ${said(c[key])})`);
832
- if (c.roll != null && !Number.isFinite(c.roll)) refuse('axes', `choice ${said(c.name)}'s roll is degrees (got ${said(c.roll)})`);
833
- if (by === 'cost' && !(c.cost >= 0)) refuse('input', `sizing by cost, and choice ${said(c.name)} gives no cost per metre: give every choice a cost, or size by mass`);
1754
+ // (a misspelt key, `mas` for `mass`, would be passed over and the choice weighed from its density instead)
1755
+ onlyKeys(c, CHOICE_KEYS, `choice ${said(c.name)}`);
1756
+ if (!c.section || typeof c.section !== 'object')
1757
+ refuse('section', `choice ${said(c.name)} has no section: { A, Iy, Iz, J } in mm² and mm⁴`);
1758
+ for (const key of ['A', 'Iy', 'Iz', 'J'])
1759
+ if (!(c.section[key] > 0))
1760
+ refuse(
1761
+ 'section',
1762
+ `choice ${said(c.name)}'s section has ${key} = ${said(c.section[key])}: it needs ${key} above 0`,
1763
+ );
1764
+ if (c.material != null && !(c.material?.E > 0))
1765
+ refuse('material', `choice ${said(c.name)}'s material has no E above 0 (got ${said(c.material)})`);
1766
+ for (const key of ['mass', 'cost'])
1767
+ if (c[key] != null && !(c[key] >= 0))
1768
+ refuse('input', `choice ${said(c.name)}'s ${key} is per metre, 0 or more (got ${said(c[key])})`);
1769
+ if (c.roll != null && !Number.isFinite(c.roll))
1770
+ refuse('axes', `choice ${said(c.name)}'s roll is degrees (got ${said(c.roll)})`);
1771
+ if (by === 'cost' && !(c.cost >= 0))
1772
+ refuse(
1773
+ 'input',
1774
+ `sizing by cost, and choice ${said(c.name)} gives no cost per metre: give every choice a cost, or size by mass`,
1775
+ );
834
1776
  choices.set(c.name, c);
835
1777
  }
836
1778
  // the groups: each member's elements
837
- if (!o.groups || typeof o.groups !== 'object' || Array.isArray(o.groups) || !Object.keys(o.groups).length) refuse('input', 'groups is { name: [members] }: the members that must take one section, by element id or by the member their pieces came from');
838
- const els = base.elements, whose = new Map(), groups = [];
1779
+ if (!o.groups || typeof o.groups !== 'object' || Array.isArray(o.groups) || !Object.keys(o.groups).length)
1780
+ refuse(
1781
+ 'input',
1782
+ 'groups is { name: [members] }: the members that must take one section, by element id or by the member their pieces came from',
1783
+ );
1784
+ const els = base.elements,
1785
+ whose = new Map(),
1786
+ groups = [];
839
1787
  for (const [name, list] of Object.entries(o.groups)) {
840
- if (!Array.isArray(list) || !list.length) refuse('input', `group ${said(name)} is a list of members (got ${said(list)})`);
1788
+ if (!Array.isArray(list) || !list.length)
1789
+ refuse('input', `group ${said(name)} is a list of members (got ${said(list)})`);
841
1790
  const idx = [];
842
1791
  for (const m of list) {
843
- const mine = els.map((e, i) => (String(e.of ?? e.id ?? i) === String(m) || String(e.id ?? i) === String(m) ? i : -1)).filter((i) => i >= 0);
844
- if (!mine.length) refuse('input', `group ${said(name)} names member ${said(m)}, and no element is it or a piece of it`);
845
- if (whose.has(String(m))) refuse('input', `member ${said(m)} is in group ${said(whose.get(String(m)))} and in group ${said(name)}: a member takes one section`);
846
- whose.set(String(m), name); idx.push(...mine);
1792
+ const mine = els
1793
+ .map((e, i) => (String(e.of ?? e.id ?? i) === String(m) || String(e.id ?? i) === String(m) ? i : -1))
1794
+ .filter((i) => i >= 0);
1795
+ if (!mine.length)
1796
+ refuse('input', `group ${said(name)} names member ${said(m)}, and no element is it or a piece of it`);
1797
+ if (whose.has(String(m)))
1798
+ refuse(
1799
+ 'input',
1800
+ `member ${said(m)} is in group ${said(whose.get(String(m)))} and in group ${said(name)}: a member takes one section`,
1801
+ );
1802
+ whose.set(String(m), name);
1803
+ idx.push(...mine);
847
1804
  }
848
1805
  const allowed = o.only?.[name] ?? [...choices.keys()];
849
- if (!Array.isArray(allowed) || !allowed.length) refuse('input', `only.${name} is a list of the choices group ${said(name)} may take`);
850
- for (const c of allowed) if (!choices.has(c)) refuse('input', `only.${name} names ${said(c)}, which is not a choice (choices: ${[...choices.keys()].join(', ')})`);
1806
+ if (!Array.isArray(allowed) || !allowed.length)
1807
+ refuse('input', `only.${name} is a list of the choices group ${said(name)} may take`);
1808
+ for (const c of allowed)
1809
+ if (!choices.has(c))
1810
+ refuse(
1811
+ 'input',
1812
+ `only.${name} names ${said(c)}, which is not a choice (choices: ${[...choices.keys()].join(', ')})`,
1813
+ );
851
1814
  groups.push({ name, members: list, idx, allowed });
852
1815
  }
853
- for (const k of Object.keys(o.only ?? {})) if (!groups.some((g) => g.name === k)) refuse('input', `only names group ${said(k)}, and there is no such group`);
854
- if (o.fits != null && typeof o.fits !== 'function') refuse('input', `fits is a function of a design (each group's choice by name) that lists what does not go together, each { where, why } (got ${said(o.fits)})`);
1816
+ for (const k of Object.keys(o.only ?? {}))
1817
+ if (!groups.some((g) => g.name === k)) refuse('input', `only names group ${said(k)}, and there is no such group`);
1818
+ if (o.fits != null && typeof o.fits !== 'function')
1819
+ refuse(
1820
+ 'input',
1821
+ `fits is a function of a design (each group's choice by name) that lists what does not go together, each { where, why } (got ${said(o.fits)})`,
1822
+ );
1823
+ if (o.ends != null && typeof o.ends !== 'function')
1824
+ refuse(
1825
+ 'input',
1826
+ `ends is a function of a design (each group's choice by name) that gives the element end springs that change with it, { [element id]: { a, b } } (got ${said(o.ends)})`,
1827
+ );
855
1828
  // the limits
856
1829
  const L = o.limits;
857
- if (!L || typeof L !== 'object' || !Object.keys(L).length) refuse('input', `limits is { ${SIZE_LIMITS.join(', ')} }: at least one`);
858
- for (const k of Object.keys(L)) if (!SIZE_LIMITS.includes(k)) refuse('input', `limits has no "${k}": it takes ${SIZE_LIMITS.join(', ')}`);
859
- const pos = (v, what) => { if (!(v > 0) || !Number.isFinite(v)) refuse('input', `${what} is above 0 (got ${said(v)})`); return v; };
860
- const nodePos = (n) => { const p = base.nodes[n]; if (!isVec3(p)) refuse('node', `a deflection limit names node ${said(n)}, which is not in nodes`, { node: n }); return p; };
861
- const g0 = base.gravity && Math.hypot(...base.gravity) > 0 ? base.gravity.map((v) => v / Math.hypot(...base.gravity)) : null;
1830
+ if (!L || typeof L !== 'object' || !Object.keys(L).length)
1831
+ refuse('input', `limits is { ${SIZE_LIMITS.join(', ')} }: at least one`);
1832
+ for (const k of Object.keys(L))
1833
+ if (!SIZE_LIMITS.includes(k)) refuse('input', `limits has no "${k}": it takes ${SIZE_LIMITS.join(', ')}`);
1834
+ const pos = (v, what) => {
1835
+ if (!(v > 0) || !Number.isFinite(v)) refuse('input', `${what} is above 0 (got ${said(v)})`);
1836
+ return v;
1837
+ };
1838
+ const nodePos = (n) => {
1839
+ const p = base.nodes[n];
1840
+ if (!isVec3(p)) refuse('node', `a deflection limit names node ${said(n)}, which is not in nodes`, { node: n });
1841
+ return p;
1842
+ };
1843
+ const g0 =
1844
+ base.gravity && Math.hypot(...base.gravity) > 0 ? base.gravity.map((v) => v / Math.hypot(...base.gravity)) : null;
1845
+ if (L.deflection != null && !Array.isArray(L.deflection))
1846
+ refuse(
1847
+ 'input',
1848
+ `limits.deflection is a list of { node, limit } and { member, limit, from, to } (got ${said(L.deflection)})`,
1849
+ );
862
1850
  const deflection = (L.deflection ?? []).map((d, i) => {
863
- if (!d || typeof d !== 'object') refuse('input', `limits.deflection ${i + 1} is { node, limit } or { member, limit, from, to } (got ${said(d)})`);
1851
+ if (!d || typeof d !== 'object')
1852
+ refuse('input', `limits.deflection ${i + 1} is { node, limit } or { member, limit, from, to } (got ${said(d)})`);
1853
+ onlyKeys(d, DEFLECTION_KEYS, `limits.deflection ${i + 1}`);
864
1854
  pos(d.limit, `limits.deflection ${i + 1}'s limit (mm)`);
865
- if (d.along != null && !(isVec3(d.along) && Math.hypot(...d.along) > 0)) refuse('input', `limits.deflection ${i + 1}'s along is a direction [x, y, z] (got ${said(d.along)})`);
866
- if (d.cases != null && !(Array.isArray(d.cases) && d.cases.length && d.cases.every((c) => typeof c === 'string'))) refuse('input', `limits.deflection ${i + 1}'s cases is a list of the load cases it holds in, by label (got ${said(d.cases)})`);
1855
+ if (d.along != null && !(isVec3(d.along) && Math.hypot(...d.along) > 0))
1856
+ refuse('input', `limits.deflection ${i + 1}'s along is a direction [x, y, z] (got ${said(d.along)})`);
1857
+ if (d.cases != null && !(Array.isArray(d.cases) && d.cases.length && d.cases.every((c) => typeof c === 'string')))
1858
+ refuse(
1859
+ 'input',
1860
+ `limits.deflection ${i + 1}'s cases is a list of the load cases it holds in, by label (got ${said(d.cases)})`,
1861
+ );
867
1862
  const along = d.along ? d.along.map((v) => v / Math.hypot(...d.along)) : g0;
868
- if (d.node != null) { nodePos(d.node); return { ...d, along }; }
1863
+ if (d.node != null) {
1864
+ nodePos(d.node);
1865
+ return { ...d, along };
1866
+ }
869
1867
  const mine = els.filter((e, k) => String(e.of ?? e.id ?? k) === String(d.member));
870
- if (!mine.length) refuse('input', `limits.deflection ${i + 1} names member ${said(d.member)}, and no element is a piece of it`);
871
- const start = nodePos(mine[0].a), end = nodePos(mine[mine.length - 1].b), len = Math.hypot(...end.map((v, k) => v - start[k]));
1868
+ if (!mine.length)
1869
+ refuse('input', `limits.deflection ${i + 1} names member ${said(d.member)}, and no element is a piece of it`);
1870
+ const start = nodePos(mine[0].a),
1871
+ end = nodePos(mine[mine.length - 1].b),
1872
+ len = Math.hypot(...end.map((v, k) => v - start[k]));
872
1873
  return { ...d, along, start, dir: end.map((v, k) => (v - start[k]) / len), from: d.from ?? 0, to: d.to ?? len };
873
1874
  });
1875
+ for (const [k, known] of Object.entries(LIMIT_KEYS))
1876
+ if (L[k] != null) {
1877
+ if (typeof L[k] !== 'object') refuse('input', `limits.${k} is { ${known.join(', ')} } (got ${said(L[k])})`);
1878
+ onlyKeys(L[k], known, `limits.${k}`);
1879
+ }
874
1880
  if (L.stress) pos(L.stress.margin, 'limits.stress.margin');
875
- if (L.buckling) { pos(L.buckling.factor, 'limits.buckling.factor'); if (L.buckling.euler != null) pos(L.buckling.euler, 'limits.buckling.euler'); }
1881
+ if (L.buckling) {
1882
+ pos(L.buckling.factor, 'limits.buckling.factor');
1883
+ if (L.buckling.euler != null) pos(L.buckling.euler, 'limits.buckling.euler');
1884
+ }
876
1885
  if (L.frequency) pos(L.frequency.Hz, 'limits.frequency.Hz');
877
- const cases = (o.cases ?? [{}]).map((c, i) => ({ label: c.label ?? (o.cases ? `case ${i + 1}` : 'as given'), loads: c.loads, masses: c.masses, inertia: c.inertia, gravity: c.gravity, limits: c.limits }));
1886
+ if (o.cases != null && !Array.isArray(o.cases))
1887
+ refuse(
1888
+ 'input',
1889
+ `cases is a list of load cases, { label, loads, masses, inertia, gravity, limits } (got ${said(o.cases)})`,
1890
+ );
1891
+ for (const [i, c] of (o.cases ?? []).entries()) {
1892
+ if (!c || typeof c !== 'object')
1893
+ refuse('input', `case ${i + 1} is ${said(c)}: a load case is { label, loads, masses, inertia, gravity, limits }`);
1894
+ onlyKeys(c, CASE_KEYS, `case ${c.label != null ? said(c.label) : i + 1}`);
1895
+ }
1896
+ const cases = (o.cases ?? [{}]).map((c, i) => ({
1897
+ label: c.label ?? (o.cases ? `case ${i + 1}` : 'as given'),
1898
+ loads: c.loads,
1899
+ masses: c.masses,
1900
+ inertia: c.inertia,
1901
+ gravity: c.gravity,
1902
+ limits: c.limits,
1903
+ }));
878
1904
  if (!cases.length) refuse('input', 'cases is a list of load cases, at least one');
879
1905
  for (const c of cases) {
880
- if (c.gravity != null && !isVec3(c.gravity)) refuse('input', `case ${said(c.label)}'s gravity is [x, y, z] in m/s² (got ${said(c.gravity)})`);
881
- if (c.limits != null && !(Array.isArray(c.limits) && c.limits.length && c.limits.every((k) => SIZE_LIMITS.includes(k)))) refuse('input', `case ${said(c.label)}'s limits is a list of the limits it is held to: ${SIZE_LIMITS.join(', ')} (got ${said(c.limits)})`);
1906
+ if (c.gravity != null && !isVec3(c.gravity))
1907
+ refuse('input', `case ${said(c.label)}'s gravity is [x, y, z] in m/s² (got ${said(c.gravity)})`);
1908
+ if (
1909
+ c.limits != null &&
1910
+ !(Array.isArray(c.limits) && c.limits.length && c.limits.every((k) => SIZE_LIMITS.includes(k)))
1911
+ )
1912
+ refuse(
1913
+ 'input',
1914
+ `case ${said(c.label)}'s limits is a list of the limits it is held to: ${SIZE_LIMITS.join(', ')} (got ${said(c.limits)})`,
1915
+ );
882
1916
  }
883
- for (const [i, d] of deflection.entries()) for (const c of d.cases ?? []) if (!cases.some((q) => q.label === c)) refuse('input', `limits.deflection ${i + 1} names case ${said(c)}, and there is no such case (cases: ${cases.map((q) => q.label).join(', ')})`);
1917
+ for (const [i, d] of deflection.entries())
1918
+ for (const c of d.cases ?? [])
1919
+ if (!cases.some((q) => q.label === c))
1920
+ refuse(
1921
+ 'input',
1922
+ `limits.deflection ${i + 1} names case ${said(c)}, and there is no such case (cases: ${cases.map((q) => q.label).join(', ')})`,
1923
+ );
884
1924
  // which cases each limit is held in: a case's own list, then a deflection limit's
885
- const holds = (c, limit) => !c.limits || c.limits.includes(limit), stCase = (c) => ({ loads: c.loads, masses: c.masses, ...(c.gravity ? { gravity: c.gravity } : {}) });
1925
+ const holds = (c, limit) => !c.limits || c.limits.includes(limit),
1926
+ stCase = (c) => ({ loads: c.loads, masses: c.masses, ...(c.gravity ? { gravity: c.gravity } : {}) });
886
1927
 
887
1928
  // each group's choices, lightest first, and what one weighs and costs over the group's length
888
- const lengthOf = (i) => { const e = els[i], a = nodePos(e.a), b = nodePos(e.b); return Math.hypot(...a.map((v, k) => v - b[k])); };
1929
+ const lengthOf = (i) => {
1930
+ const e = els[i],
1931
+ a = nodePos(e.a),
1932
+ b = nodePos(e.b);
1933
+ return Math.hypot(...a.map((v, k) => v - b[k]));
1934
+ };
889
1935
  const materialOf = (i) => named(els[i].material, base.materials);
890
- const perMetre = (c, i, key) => (key === 'cost' ? c.cost ?? null : c.mass ?? (c.section.A * ((c.material ?? materialOf(i))?.density ?? 0)) / 1000);
1936
+ const memberOfBase = (i) => els[i].of ?? els[i].id ?? i;
1937
+ const perMetre = (c, i, key) =>
1938
+ key === 'cost'
1939
+ ? (c.cost ?? null)
1940
+ : (c.mass ?? (c.section.A * ((c.material ?? materialOf(i))?.density ?? 0)) / 1000);
891
1941
  for (const g of groups) {
892
1942
  g.length = g.idx.reduce((t, i) => t + lengthOf(i), 0);
893
- g.price = (c, key = by) => { const v = g.idx.map((i) => perMetre(c, i, key)); return v.some((x) => x == null) ? null : g.idx.reduce((t, i, k) => t + (v[k] * lengthOf(i)) / 1000, 0); };
1943
+ g.price = (c, key = by) => {
1944
+ const v = g.idx.map((i) => perMetre(c, i, key));
1945
+ return v.some((x) => x == null) ? null : g.idx.reduce((t, i, k) => t + (v[k] * lengthOf(i)) / 1000, 0);
1946
+ };
894
1947
  g.list = g.allowed.map((n) => choices.get(n)).sort((p, q) => g.price(p) - g.price(q));
895
1948
  }
896
1949
  const measure = (pick) => groups.reduce((t, g, k) => t + g.price(g.list[pick[k]]), 0);
1950
+ // A stress limit reads each member's peak stress against its material's strength, through its section modulus.
1951
+ // A choice without either would be passed over, and the lightest come back as meeting the limit: so each choice a
1952
+ // group may take is asked for both, before anything is solved
1953
+ if (L.stress)
1954
+ for (const g of groups)
1955
+ for (const c of g.list) {
1956
+ const s = c.section;
1957
+ if (!((s.Wy > 0 || s.cz > 0) && (s.Wz > 0 || s.cy > 0)))
1958
+ refuse(
1959
+ 'section',
1960
+ `choice ${said(c.name)}'s section has no section modulus, so its stress cannot be held to limits.stress: give it cy and cz (mm from its centre to its furthest fibre each way) or Wy and Wz (mm³)`,
1961
+ { choice: c.name, group: g.name },
1962
+ );
1963
+ for (const i of g.idx) {
1964
+ const mat = c.material ?? materialOf(i);
1965
+ if (mat?.strength > 0 && Number.isFinite(mat.strength)) continue;
1966
+ const got =
1967
+ mat?.strength === undefined ? 'no strength' : `strength ${said(mat.strength)}, not a strength above 0`;
1968
+ refuse(
1969
+ 'material',
1970
+ c.material
1971
+ ? `choice ${said(c.name)}'s material has ${got}, so its stress cannot be held to limits.stress: give it strength in MPa`
1972
+ : `choice ${said(c.name)} has no material of its own, and member ${said(memberOfBase(i))}'s material, which it takes, has ${got}, so its stress cannot be held to limits.stress: give either a strength in MPa`,
1973
+ { choice: c.name, group: g.name },
1974
+ );
1975
+ }
1976
+ }
897
1977
 
898
- // a design: the frame with each group's choice in place
1978
+ // each design's own end springs (o.ends: a join's spring that follows the beams it joins), asked once a design
1979
+ const endsMemo = new Map(),
1980
+ elementIds = new Set(els.map((e, i) => String(e.id ?? i)));
1981
+ const endsOf = (pick) => {
1982
+ const key = pick.join(',');
1983
+ if (endsMemo.has(key)) return endsMemo.get(key);
1984
+ const r = o.ends(Object.fromEntries(groups.map((g, k) => [g.name, g.list[pick[k]].name])));
1985
+ if (!r || typeof r !== 'object' || Array.isArray(r))
1986
+ refuse(
1987
+ 'input',
1988
+ `ends returns the end springs that change with the design, { [element id]: { a, b } }, empty where none does (got ${said(r)})`,
1989
+ );
1990
+ for (const [id, v] of Object.entries(r)) {
1991
+ if (!elementIds.has(id)) refuse('input', `ends names element ${said(id)}, and the frame has no such element`);
1992
+ if (!v || typeof v !== 'object' || Array.isArray(v))
1993
+ refuse('input', `ends.${id} is { a, b }: how each end of the element is joined (got ${said(v)})`);
1994
+ onlyKeys(v, ['a', 'b'], `ends.${id}`);
1995
+ }
1996
+ endsMemo.set(key, r);
1997
+ return r;
1998
+ };
1999
+ // a design: the frame with each group's choice in place (and, in the frame itself, the design's own end springs)
899
2000
  const apply = (m, pick) => {
900
2001
  const out = m.elements.map((e) => ({ ...e }));
901
- groups.forEach((g, k) => { const c = g.list[pick[k]]; for (const i of g.idx) {
902
- const e = out[i], mat = { ...(c.material ?? materialOf(i)) };
903
- if (c.mass != null) mat.density = (c.mass / c.section.A) * 1000; // (kg/m over mm² is g/mm³, a thousand g/cm³)
904
- e.section = c.section; e.material = mat; if (c.roll) e.roll = (e.roll ?? 0) + c.roll;
905
- } });
2002
+ groups.forEach((g, k) => {
2003
+ const c = g.list[pick[k]];
2004
+ for (const i of g.idx) {
2005
+ const e = out[i],
2006
+ mat = { ...(c.material ?? materialOf(i)) };
2007
+ if (c.mass != null) mat.density = (c.mass / c.section.A) * 1000; // (kg/m over mm² is g/mm³, a thousand g/cm³)
2008
+ e.section = c.section;
2009
+ e.material = mat;
2010
+ if (c.roll) e.roll = (e.roll ?? 0) + c.roll;
2011
+ }
2012
+ });
2013
+ if (o.ends && m === base) {
2014
+ const own = endsOf(pick);
2015
+ out.forEach((e, i) => {
2016
+ const v = own[String(e.id ?? i)];
2017
+ if (v) e.ends = { ...e.ends, ...v };
2018
+ });
2019
+ }
906
2020
  return { ...m, elements: out };
907
2021
  };
908
- const strengthOf = (m, e) => { const mat = named(e.material, m.materials); return mat?.strength > 0 ? mat.strength : null; };
2022
+ const strengthOf = (m, e) => {
2023
+ const mat = named(e.material, m.materials);
2024
+ return mat?.strength > 0 ? mat.strength : null;
2025
+ };
909
2026
  const memberOf = (e, i) => String(e.of ?? e.id ?? i);
910
2027
  const memo = new Map();
911
2028
  let tried = 0;
@@ -915,8 +2032,16 @@ export function sizing(model, o = {}) {
915
2032
  if (memo.has(key)) return memo.get(key);
916
2033
  if (!quick && memo.has(pick.join(',')) && memo.get(pick.join(',')).complete) return memo.get(pick.join(','));
917
2034
  tried++;
918
- const m = apply(base, pick), checks = [], worse = (c) => { const was = checks.find((q) => q.limit === c.limit && q.where === c.where); if (!was) checks.push(c); else if (c.ratio > was.ratio) Object.assign(was, c); };
919
- const solved = frame(m), stats = cases.map((c) => solved.statics(stCase(c)));
2035
+ const m = apply(base, pick),
2036
+ checks = [],
2037
+ unchecked = new Map(),
2038
+ worse = (c) => {
2039
+ const was = checks.find((q) => q.limit === c.limit && q.where === c.where);
2040
+ if (!was) checks.push(c);
2041
+ else if (c.ratio > was.ratio) Object.assign(was, c);
2042
+ };
2043
+ const solved = frame(m),
2044
+ stats = cases.map((c) => solved.statics(stCase(c)));
920
2045
  // deflection
921
2046
  stats.forEach((s, ci) => {
922
2047
  if (!holds(cases[ci], 'deflection')) return;
@@ -925,103 +2050,255 @@ export function sizing(model, o = {}) {
925
2050
  let v = 0;
926
2051
  const along = (u) => Math.abs(d.along ? dot(u, d.along) : Math.hypot(...u));
927
2052
  if (d.node != null) v = along(s.displacements[d.node].slice(0, 3));
928
- else s.elements.forEach((r, i) => { if (memberOf(m.elements[i], i) !== String(d.member)) return; const a = m.nodes[m.elements[i].a]; r.along.x.forEach((x, k) => { const p = a.map((c, j) => c + r.axes[0][j] * x), z = dot(p.map((c, j) => c - d.start[j]), d.dir); if (z >= d.from - 1e-6 && z <= d.to + 1e-6) v = Math.max(v, along(r.along.d[k])); }); });
929
- worse({ limit: 'deflection', where: d.node != null ? String(d.node) : String(d.member), value: v, allowed: d.limit, ratio: v / d.limit, case: cases[ci].label });
2053
+ else
2054
+ s.elements.forEach((r, i) => {
2055
+ if (memberOf(m.elements[i], i) !== String(d.member)) return;
2056
+ const a = m.nodes[m.elements[i].a];
2057
+ r.along.x.forEach((x, k) => {
2058
+ const p = a.map((c, j) => c + r.axes[0][j] * x),
2059
+ z = dot(
2060
+ p.map((c, j) => c - d.start[j]),
2061
+ d.dir,
2062
+ );
2063
+ if (z >= d.from - 1e-6 && z <= d.to + 1e-6) v = Math.max(v, along(r.along.d[k]));
2064
+ });
2065
+ });
2066
+ worse({
2067
+ limit: 'deflection',
2068
+ where: d.node != null ? String(d.node) : String(d.member),
2069
+ value: v,
2070
+ allowed: d.limit,
2071
+ ratio: v / d.limit,
2072
+ case: cases[ci].label,
2073
+ });
930
2074
  }
931
2075
  });
932
2076
  // stress, in the frame and every other way of joining it
933
2077
  if (L.stress) {
934
- const sets = [{ m, stats }, ...models.slice(1).map((b) => { const mb = apply(b, pick), fb = frame(mb); return { m: mb, stats: cases.map((c) => (holds(c, 'stress') ? fb.statics(stCase(c)) : null)) }; })];
935
- for (const { m: mm, stats: ss } of sets) ss.forEach((s, ci) => holds(cases[ci], 'stress') && s.elements.forEach((r, i) => {
936
- const e = mm.elements[i], st = strengthOf(mm, e);
937
- if (!r.stress || !st) return;
938
- worse({ limit: 'stress', where: memberOf(e, i), value: r.stress.peak, allowed: st / L.stress.margin, ratio: (r.stress.peak * L.stress.margin) / st, case: cases[ci].label });
939
- }));
2078
+ const sets = [
2079
+ { m, stats },
2080
+ ...models.slice(1).map((b) => {
2081
+ const mb = apply(b, pick),
2082
+ fb = frame(mb);
2083
+ return { m: mb, stats: cases.map((c) => (holds(c, 'stress') ? fb.statics(stCase(c)) : null)) };
2084
+ }),
2085
+ ];
2086
+ for (const { m: mm, stats: ss } of sets)
2087
+ ss.forEach(
2088
+ (s, ci) =>
2089
+ holds(cases[ci], 'stress') &&
2090
+ s.elements.forEach((r, i) => {
2091
+ const e = mm.elements[i],
2092
+ st = strengthOf(mm, e);
2093
+ if (!r.stress || !st) {
2094
+ // passed over, and said so: a member outside every group (a join's link, a panel) with no strength
2095
+ // or no section modulus (so no stress is read in it)
2096
+ const u = unchecked.get(memberOf(e, i)) ?? { strength: false, modulus: false };
2097
+ if (!st) u.strength = true;
2098
+ if (!r.stress) u.modulus = true;
2099
+ unchecked.set(memberOf(e, i), u);
2100
+ return;
2101
+ }
2102
+ worse({
2103
+ limit: 'stress',
2104
+ where: memberOf(e, i),
2105
+ value: r.stress.peak,
2106
+ allowed: st / L.stress.margin,
2107
+ ratio: (r.stress.peak * L.stress.margin) / st,
2108
+ case: cases[ci].label,
2109
+ });
2110
+ }),
2111
+ );
940
2112
  }
941
2113
  // each member against Euler's load
942
2114
  if (L.buckling?.euler) {
943
2115
  const per = new Map();
944
- const grouped = new Set(groups.flatMap((g) => g.idx)), counted = new Set();
2116
+ const grouped = new Set(groups.flatMap((g) => g.idx)),
2117
+ counted = new Set();
945
2118
  // a member's length is the sum of its elements' lengths, each counted once, whichever cases hold buckling
946
- stats.forEach((s, ci) => holds(cases[ci], 'buckling') && s.elements.forEach((r, i) => { if (!grouped.has(i)) return; const id = memberOf(m.elements[i], i), p = per.get(id) ?? { N: 0, L: 0, I: Infinity, E: 0, ci }; if (!counted.has(i)) { counted.add(i); p.L += r.length; } const sec = named(m.elements[i].section, m.sections), mat = named(m.elements[i].material, m.materials); p.I = Math.min(p.I, sec.Iy, sec.Iz); p.E = mat.E; if (-r.axial > p.N) { p.N = -r.axial; p.ci = ci; } per.set(id, p); }));
947
- for (const [id, p] of per) if (p.N > 0) { const Pcr = (Math.PI ** 2 * p.E * p.I) / (L.buckling.euler * p.L) ** 2; worse({ limit: 'buckling', where: `${id} (Euler)`, value: Pcr / p.N, allowed: L.buckling.factor, ratio: (L.buckling.factor * p.N) / Pcr, case: cases[p.ci].label }); }
2119
+ stats.forEach(
2120
+ (s, ci) =>
2121
+ holds(cases[ci], 'buckling') &&
2122
+ s.elements.forEach((r, i) => {
2123
+ if (!grouped.has(i)) return;
2124
+ const id = memberOf(m.elements[i], i),
2125
+ p = per.get(id) ?? { N: 0, L: 0, I: Infinity, E: 0, ci };
2126
+ if (!counted.has(i)) {
2127
+ counted.add(i);
2128
+ p.L += r.length;
2129
+ }
2130
+ const sec = named(m.elements[i].section, m.sections),
2131
+ mat = named(m.elements[i].material, m.materials);
2132
+ p.I = Math.min(p.I, sec.Iy, sec.Iz);
2133
+ p.E = mat.E;
2134
+ if (-r.axial > p.N) {
2135
+ p.N = -r.axial;
2136
+ p.ci = ci;
2137
+ }
2138
+ per.set(id, p);
2139
+ }),
2140
+ );
2141
+ for (const [id, p] of per)
2142
+ if (p.N > 0) {
2143
+ const Pcr = (Math.PI ** 2 * p.E * p.I) / (L.buckling.euler * p.L) ** 2;
2144
+ worse({
2145
+ limit: 'buckling',
2146
+ where: `${id} (Euler)`,
2147
+ value: Pcr / p.N,
2148
+ allowed: L.buckling.factor,
2149
+ ratio: (L.buckling.factor * p.N) / Pcr,
2150
+ case: cases[p.ci].label,
2151
+ });
2152
+ }
948
2153
  }
949
2154
  const broke = () => checks.some((c) => c.ratio > 1);
950
- if (quick && broke()) { const r = { checks, ok: false, complete: false }; memo.set(key, r); return r; }
951
- const fine = (L.buckling || L.frequency) ? frame(subdivide(m, pieces)) : null;
952
- if (L.buckling) cases.forEach((c, ci) => {
953
- if (!holds(c, 'buckling')) return;
954
- try { const f = fine.buckling({ ...stCase(c), count: 1 }).factors[0]; worse({ limit: 'buckling', where: 'frame', value: f, allowed: L.buckling.factor, ratio: L.buckling.factor / f, case: c.label }); }
955
- catch (e) { if (e.code !== 'fea.frame.compression') throw e; }
956
- });
957
- if (quick && broke()) { const r = { checks, ok: false, complete: false }; memo.set(key, r); return r; }
958
- if (L.frequency) cases.forEach((c) => {
959
- if (!holds(c, 'frequency')) return;
960
- const masses = { ...(c.masses ?? base.masses ?? {}) };
961
- for (const [n, kg] of Object.entries(c.inertia ?? {})) masses[n] = (masses[n] ?? 0) + kg;
962
- const hz = fine.modes({ count: 1, masses }).frequencies[0];
963
- worse({ limit: 'frequency', where: 'frame', value: hz, allowed: L.frequency.Hz, ratio: L.frequency.Hz / hz, case: c.label });
964
- });
965
- const r = { checks, ok: !broke(), complete: true, model: m };
966
- memo.set(pick.join(','), r); memo.set(key, r);
2155
+ const passed = [...unchecked].map(([member, u]) => ({
2156
+ member,
2157
+ why:
2158
+ u.strength && u.modulus
2159
+ ? 'no strength and no section modulus'
2160
+ : u.strength
2161
+ ? 'no strength'
2162
+ : 'no section modulus',
2163
+ }));
2164
+ if (quick && broke()) {
2165
+ const r = { checks, unchecked: passed, ok: false, complete: false };
2166
+ memo.set(key, r);
2167
+ return r;
2168
+ }
2169
+ const fine = L.buckling || L.frequency ? frame(subdivide(m, pieces)) : null;
2170
+ if (L.buckling)
2171
+ cases.forEach((c) => {
2172
+ if (!holds(c, 'buckling')) return;
2173
+ try {
2174
+ const f = fine.buckling({ ...stCase(c), count: 1 }).factors[0];
2175
+ worse({
2176
+ limit: 'buckling',
2177
+ where: 'frame',
2178
+ value: f,
2179
+ allowed: L.buckling.factor,
2180
+ ratio: L.buckling.factor / f,
2181
+ case: c.label,
2182
+ });
2183
+ } catch (e) {
2184
+ if (e.code !== 'fea.frame.compression') throw e;
2185
+ }
2186
+ });
2187
+ if (quick && broke()) {
2188
+ const r = { checks, unchecked: passed, ok: false, complete: false };
2189
+ memo.set(key, r);
2190
+ return r;
2191
+ }
2192
+ if (L.frequency)
2193
+ cases.forEach((c) => {
2194
+ if (!holds(c, 'frequency')) return;
2195
+ const masses = { ...(c.masses ?? base.masses ?? {}) };
2196
+ for (const [n, kg] of Object.entries(c.inertia ?? {})) masses[n] = (masses[n] ?? 0) + kg;
2197
+ const hz = fine.modes({ count: 1, masses }).frequencies[0];
2198
+ worse({
2199
+ limit: 'frequency',
2200
+ where: 'frame',
2201
+ value: hz,
2202
+ allowed: L.frequency.Hz,
2203
+ ratio: L.frequency.Hz / hz,
2204
+ case: c.label,
2205
+ });
2206
+ });
2207
+ const r = { checks, unchecked: passed, ok: !broke(), complete: true, model: m };
2208
+ memo.set(pick.join(','), r);
2209
+ memo.set(key, r);
967
2210
  return r;
968
2211
  };
969
2212
  const worstOf = (checks) => checks.reduce((p, q) => (!p || q.ratio > p.ratio ? q : p), null);
970
2213
  // what does not go together in a design (o.fits), asked once a design: a design that does not fit is never solved
971
- const fitMemo = new Map(), nameOf = (pick) => Object.fromEntries(groups.map((g, k) => [g.name, g.list[pick[k]].name]));
2214
+ const fitMemo = new Map(),
2215
+ nameOf = (pick) => Object.fromEntries(groups.map((g, k) => [g.name, g.list[pick[k]].name]));
972
2216
  const misfits = (pick) => {
973
2217
  if (!o.fits) return [];
974
2218
  const key = pick.join(',');
975
2219
  if (!fitMemo.has(key)) {
976
2220
  const r = o.fits(nameOf(pick));
977
- if (!Array.isArray(r) || !r.every((x) => x && typeof x.where === 'string' && typeof x.why === 'string')) refuse('input', `fits returns a list of what does not go together, each { where, why }, empty where the design fits (got ${said(r)})`);
2221
+ if (!Array.isArray(r) || !r.every((x) => x && typeof x.where === 'string' && typeof x.why === 'string'))
2222
+ refuse(
2223
+ 'input',
2224
+ `fits returns a list of what does not go together, each { where, why }, empty where the design fits (got ${said(r)})`,
2225
+ );
978
2226
  fitMemo.set(key, r);
979
2227
  }
980
2228
  return fitMemo.get(key);
981
2229
  };
982
2230
  const fitting = (pick) => !misfits(pick).length;
983
- const noneFits = (pick) => { const m = misfits(pick)[0]; refuse('fit', `no design of these choices goes together: ${m ? `${m.where}: ${m.why}` : 'every one is refused by fits'}. Give the groups choices that fit each other (only), or join them another way`, { misfits: misfits(pick) }); };
2231
+ const noneFits = (pick) => {
2232
+ const m = misfits(pick)[0];
2233
+ refuse(
2234
+ 'fit',
2235
+ `no design of these choices goes together: ${m ? `${m.where}: ${m.why}` : 'every one is refused by fits'}. Give the groups choices that fit each other (only), or join them another way`,
2236
+ { misfits: misfits(pick) },
2237
+ );
2238
+ };
984
2239
  // how far past the limits a design is in all: what still separates two designs whose worst figures tie
985
2240
  const excess = (checks) => checks.reduce((t, c) => t + Math.max(0, c.ratio - 1), 0);
986
2241
 
987
2242
  // the search
988
- const sizes = groups.map((g) => g.list.length), combos = sizes.reduce((t, n) => t * n, 1);
2243
+ const sizes = groups.map((g) => g.list.length),
2244
+ combos = sizes.reduce((t, n) => t * n, 1);
989
2245
  const search = o.search ?? (combos <= every ? 'every' : 'steps');
990
- let pick = null, best = null;
2246
+ let pick = null,
2247
+ best = null;
991
2248
  if (search === 'every') {
992
2249
  const all = [];
993
- const walk = (k, p) => { if (k === groups.length) { all.push(p); return; } for (let i = 0; i < sizes[k]; i++) walk(k + 1, [...p, i]); };
2250
+ const walk = (k, p) => {
2251
+ if (k === groups.length) {
2252
+ all.push(p);
2253
+ return;
2254
+ }
2255
+ for (let i = 0; i < sizes[k]; i++) walk(k + 1, [...p, i]);
2256
+ };
994
2257
  walk(0, []);
995
2258
  all.sort((p, q) => measure(p) - measure(q));
996
2259
  const near = [];
997
2260
  for (const p of all) {
998
2261
  if (!fitting(p)) continue;
999
2262
  const r = evaluate(p, true);
1000
- if (r.ok && evaluate(p).ok) { pick = p; break; }
2263
+ if (r.ok && evaluate(p).ok) {
2264
+ pick = p;
2265
+ break;
2266
+ }
1001
2267
  near.push({ p, low: worstOf(r.checks)?.ratio ?? 0 });
1002
2268
  }
1003
2269
  // nothing fits: the nearest by every limit's figure, not by the quick look that stops at the first stage that
1004
2270
  // breaks one. The quick look's worst is never more than the whole's, so designs are taken in its order and
1005
2271
  // stop once no later one can come nearer
1006
2272
  if (!pick && !near.length) noneFits(all[0]);
1007
- if (!pick) for (const c of near.sort((a, b) => a.low - b.low)) {
1008
- if (best && c.low >= best.w.ratio) break;
1009
- const w = worstOf(evaluate(c.p).checks);
1010
- if (!best || (w && w.ratio < best.w.ratio)) best = { p: c.p, w };
1011
- }
2273
+ if (!pick)
2274
+ for (const c of near.sort((a, b) => a.low - b.low)) {
2275
+ if (best && c.low >= best.w.ratio) break;
2276
+ const w = worstOf(evaluate(c.p).checks);
2277
+ if (!best || (w && w.ratio < best.w.ratio)) best = { p: c.p, w };
2278
+ }
1012
2279
  } else {
1013
2280
  // the lightest design that fits, from q up: each group at its choice in q or a heavier one, group k kept as it is
1014
2281
  // (-1: none kept), found lightest first over the designs from q (each group's list is in order of weight); null
1015
2282
  // where none is found in a few thousand
1016
2283
  const repair = (q, keep) => {
1017
2284
  if (fitting(q)) return q;
1018
- const seen = new Set([q.join(',')]), open = [{ t: q, w: measure(q) }];
2285
+ const seen = new Set([q.join(',')]),
2286
+ open = [{ t: q, w: measure(q) }];
1019
2287
  for (let n = 0; open.length && n < 4000; n++) {
1020
2288
  let i = 0;
1021
2289
  for (let k = 1; k < open.length; k++) if (open[k].w < open[i].w) i = k;
1022
2290
  const { t } = open.splice(i, 1)[0];
1023
2291
  if (fitting(t)) return t;
1024
- groups.forEach((g, k) => { if (k === keep || t[k] + 1 >= sizes[k]) return; const u = [...t]; u[k]++; const key = u.join(','); if (!seen.has(key)) { seen.add(key); open.push({ t: u, w: measure(u) }); } });
2292
+ groups.forEach((g, k) => {
2293
+ if (k === keep || t[k] + 1 >= sizes[k]) return;
2294
+ const u = [...t];
2295
+ u[k]++;
2296
+ const key = u.join(',');
2297
+ if (!seen.has(key)) {
2298
+ seen.add(key);
2299
+ open.push({ t: u, w: measure(u) });
2300
+ }
2301
+ });
1025
2302
  }
1026
2303
  return null;
1027
2304
  };
@@ -1029,7 +2306,9 @@ export function sizing(model, o = {}) {
1029
2306
  // a start that fits, from the lightest
1030
2307
  if (!fitting(p)) p = repair(p, -1) ?? noneFits(p);
1031
2308
  for (let n = 0; n < 100 * groups.length; n++) {
1032
- const r = evaluate(p), w = worstOf(r.checks)?.ratio ?? 0, e = excess(r.checks);
2309
+ const r = evaluate(p),
2310
+ w = worstOf(r.checks)?.ratio ?? 0,
2311
+ e = excess(r.checks);
1033
2312
  if (r.ok) break;
1034
2313
  // each group up to the lightest heavier choice that helps (and those of the same weight, a section turned): a
1035
2314
  // choice heavier but weaker this way (a 30 x 30 after a 20 x 40 on edge, a 20 x 60 lying flat) is passed over.
@@ -1040,13 +2319,25 @@ export function sizing(model, o = {}) {
1040
2319
  let found = null;
1041
2320
  for (let j = p[k] + 1; j < sizes[k]; j++) {
1042
2321
  if (found != null && g.price(g.list[j]) > found * (1 + 1e-9)) break;
1043
- let q = [...p]; q[k] = j;
2322
+ let q = [...p];
2323
+ q[k] = j;
1044
2324
  // (a choice that does not go with the others' takes them along: the others made to fit it)
1045
2325
  if (!fitting(q)) q = repair(q, k);
1046
2326
  if (!q) continue;
1047
- const rq = evaluate(q), wq = worstOf(rq.checks)?.ratio ?? 0, eq = excess(rq.checks), dm = Math.max(measure(q) - measure(p), 1e-12);
1048
- const better = wq < w * (1 - 1e-9) ? (w - wq) / dm : wq <= w * (1 + 1e-9) && eq < e * (1 - 1e-9) ? (1e-9 * (e - eq)) / dm : null;
1049
- if (better != null) { found ??= g.price(g.list[j]); if (!step || better > step.gain) step = { q, gain: better }; }
2327
+ const rq = evaluate(q),
2328
+ wq = worstOf(rq.checks)?.ratio ?? 0,
2329
+ eq = excess(rq.checks),
2330
+ dm = Math.max(measure(q) - measure(p), 1e-12);
2331
+ const better =
2332
+ wq < w * (1 - 1e-9)
2333
+ ? (w - wq) / dm
2334
+ : wq <= w * (1 + 1e-9) && eq < e * (1 - 1e-9)
2335
+ ? (1e-9 * (e - eq)) / dm
2336
+ : null;
2337
+ if (better != null) {
2338
+ found ??= g.price(g.list[j]);
2339
+ if (!step || better > step.gain) step = { q, gain: better };
2340
+ }
1050
2341
  }
1051
2342
  });
1052
2343
  if (!step) break;
@@ -1056,8 +2347,20 @@ export function sizing(model, o = {}) {
1056
2347
  // then each group down as far as the limits allow, the heaviest first, until nothing moves
1057
2348
  for (let moved = true; moved;) {
1058
2349
  moved = false;
1059
- const order = groups.map((g, k) => k).sort((a, b) => groups[b].price(groups[b].list[p[b]]) - groups[a].price(groups[a].list[p[a]]));
1060
- for (const k of order) for (let i = 0; i < p[k]; i++) { let q = [...p]; q[k] = i; if (!fitting(q)) q = repair(q, k); if (q && measure(q) < measure(p) * (1 - 1e-12) && evaluate(q).ok) { p = q; moved = true; break; } }
2350
+ const order = groups
2351
+ .map((g, k) => k)
2352
+ .sort((a, b) => groups[b].price(groups[b].list[p[b]]) - groups[a].price(groups[a].list[p[a]]));
2353
+ for (const k of order)
2354
+ for (let i = 0; i < p[k]; i++) {
2355
+ let q = [...p];
2356
+ q[k] = i;
2357
+ if (!fitting(q)) q = repair(q, k);
2358
+ if (q && measure(q) < measure(p) * (1 - 1e-12) && evaluate(q).ok) {
2359
+ p = q;
2360
+ moved = true;
2361
+ break;
2362
+ }
2363
+ }
1061
2364
  }
1062
2365
  pick = p;
1063
2366
  } else best = { p, w: worstOf(evaluate(p).checks) };
@@ -1067,21 +2370,58 @@ export function sizing(model, o = {}) {
1067
2370
  const final = evaluate(pick);
1068
2371
  const results = groups.map((g, k) => {
1069
2372
  // the next lighter choice: the heaviest that weighs less (one of the same weight, a section turned, is no lighter)
1070
- const c = g.list[pick[k]], at = g.list.findLastIndex((x) => g.price(x) < g.price(c) * (1 - 1e-9)), lighter = at >= 0 ? g.list[at] : null;
1071
- let governs = null, margin = null;
2373
+ const c = g.list[pick[k]],
2374
+ at = g.list.findLastIndex((x) => g.price(x) < g.price(c) * (1 - 1e-9)),
2375
+ lighter = at >= 0 ? g.list[at] : null;
2376
+ let governs = null,
2377
+ margin = null;
1072
2378
  if (lighter && !fitting(Object.assign([...pick], { [k]: at }))) {
1073
2379
  // the lighter choice does not go with the others: that, not a limit, set this group
1074
2380
  const m = misfits(Object.assign([...pick], { [k]: at }))[0];
1075
2381
  governs = { limit: 'fit', where: m.where, why: m.why, lighter: lighter.name, broken: null };
1076
2382
  } else if (lighter) {
1077
- const q = [...pick]; q[k] = at;
2383
+ const q = [...pick];
2384
+ q[k] = at;
1078
2385
  const w = worstOf(evaluate(q).checks.filter((x) => x.ratio > 1));
1079
- if (w) { const now = final.checks.find((x) => x.limit === w.limit && x.where === w.where); governs = { ...(now ?? w), lighter: lighter.name, broken: w.ratio }; margin = now ? 1 / now.ratio : null; }
2386
+ if (w) {
2387
+ const now = final.checks.find((x) => x.limit === w.limit && x.where === w.where);
2388
+ governs = { ...(now ?? w), lighter: lighter.name, broken: w.ratio };
2389
+ margin = now ? 1 / now.ratio : null;
2390
+ }
1080
2391
  }
1081
2392
  // no lighter choice: the margin is the group's own checks', its members' and the nodes its members run between
1082
2393
  const mine = new Set(g.idx.flatMap((i) => [String(els[i].a), String(els[i].b)]));
1083
- if (margin == null) { const own = final.checks.filter((x) => g.members.some((m) => x.where === String(m) || x.where === `${m} (Euler)`) || (x.limit === 'deflection' && mine.has(x.where))), w = worstOf(own.length ? own : final.checks); margin = w ? 1 / w.ratio : null; }
1084
- return { name: g.name, members: g.members, choice: c.name, length: g.length, mass: g.price(c, 'mass'), cost: g.price(c, 'cost'), lighter: lighter?.name ?? null, governs, margin };
2394
+ if (margin == null) {
2395
+ const own = final.checks.filter(
2396
+ (x) =>
2397
+ g.members.some((m) => x.where === String(m) || x.where === `${m} (Euler)`) ||
2398
+ (x.limit === 'deflection' && mine.has(x.where)),
2399
+ ),
2400
+ w = worstOf(own.length ? own : final.checks);
2401
+ margin = w ? 1 / w.ratio : null;
2402
+ }
2403
+ return {
2404
+ name: g.name,
2405
+ members: g.members,
2406
+ choice: c.name,
2407
+ length: g.length,
2408
+ mass: g.price(c, 'mass'),
2409
+ cost: g.price(c, 'cost'),
2410
+ lighter: lighter?.name ?? null,
2411
+ governs,
2412
+ margin,
2413
+ };
1085
2414
  });
1086
- return { ok, by, search, tried, total: measure(pick), groups: results, checks: final.checks, worst: worstOf(final.checks), model: final.model ?? apply(base, pick) };
2415
+ return {
2416
+ ok,
2417
+ by,
2418
+ search,
2419
+ tried,
2420
+ total: measure(pick),
2421
+ groups: results,
2422
+ checks: final.checks,
2423
+ unchecked: final.unchecked,
2424
+ worst: worstOf(final.checks),
2425
+ model: final.model ?? apply(base, pick),
2426
+ };
1087
2427
  }