@rulecad/fea 0.2.14 → 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/layout.mjs CHANGED
@@ -52,8 +52,10 @@ const DIMS = ['x', 'y', 'z'];
52
52
  const KEYS = ['nodes', 'grid', 'supports', 'loads', 'cases', 'strength', 'density', 'joint', 'reach', 'avoid', 'plane'];
53
53
  const OPTIONS = ['keep', 'start', 'add', 'tolerance', 'adding'];
54
54
  /** @returns {never} */
55
- const refuse = (code, text, more) => { throw Object.assign(new Error(text), { code: `fea.layout.${code}`, ...more }); };
56
- const said = (v) => (typeof v === 'string' ? `"${v}"` : JSON.stringify(v) ?? String(v));
55
+ const refuse = (code, text, more) => {
56
+ throw Object.assign(new Error(text), { code: `fea.layout.${code}`, ...more });
57
+ };
58
+ const said = (v) => (typeof v === 'string' ? `"${v}"` : (JSON.stringify(v) ?? String(v)));
57
59
  const isPoint = (v) => Array.isArray(v) && (v.length === 2 || v.length === 3) && v.every(Number.isFinite);
58
60
  const round = (v, d = 6) => Number(v.toPrecision(d));
59
61
 
@@ -66,14 +68,28 @@ const round = (v, d = 6) => Number(v.toPrecision(d));
66
68
  * @returns {Record<string, Vec3>}
67
69
  */
68
70
  export function nodeGrid(g) {
69
- if (!g || typeof g !== 'object' || !isPoint(g.from) || !isPoint(g.to) || g.from.length !== g.to.length) refuse('input', `grid is { from, to, pitch }: two corners [x, y] or [x, y, z] in mm and a spacing (got ${said(g)})`);
70
- if (!(g.pitch > 0) || !Number.isFinite(g.pitch)) refuse('input', `grid.pitch is the spacing in mm, above 0 (got ${said(g.pitch)})`);
71
- const d = g.from.length, counts = g.from.map((v, i) => Math.round(Math.abs(g.to[i] - v) / g.pitch));
72
- if (counts.reduce((t, c) => t * (c + 1), 1) > 20000) refuse('input', `grid makes ${counts.reduce((t, c) => t * (c + 1), 1)} nodes: at most 20000 (a coarser pitch, or a smaller box)`);
71
+ if (!g || typeof g !== 'object' || !isPoint(g.from) || !isPoint(g.to) || g.from.length !== g.to.length)
72
+ refuse(
73
+ 'input',
74
+ `grid is { from, to, pitch }: two corners [x, y] or [x, y, z] in mm and a spacing (got ${said(g)})`,
75
+ );
76
+ if (!(g.pitch > 0) || !Number.isFinite(g.pitch))
77
+ refuse('input', `grid.pitch is the spacing in mm, above 0 (got ${said(g.pitch)})`);
78
+ const d = g.from.length,
79
+ counts = g.from.map((v, i) => Math.round(Math.abs(g.to[i] - v) / g.pitch));
80
+ if (counts.reduce((t, c) => t * (c + 1), 1) > 20000)
81
+ refuse(
82
+ 'input',
83
+ `grid makes ${counts.reduce((t, c) => t * (c + 1), 1)} nodes: at most 20000 (a coarser pitch, or a smaller box)`,
84
+ );
73
85
  const out = {};
74
86
  const walk = (i, at, idx) => {
75
- if (i === d) { out[idx.join(',')] = /** @type {Vec3} */ ([at[0], at[1], at[2] ?? 0]); return; }
76
- for (let c = 0; c <= counts[i]; c++) walk(i + 1, [...at, counts[i] ? g.from[i] + ((g.to[i] - g.from[i]) * c) / counts[i] : g.from[i]], [...idx, c]);
87
+ if (i === d) {
88
+ out[idx.join(',')] = /** @type {Vec3} */ ([at[0], at[1], at[2] ?? 0]);
89
+ return;
90
+ }
91
+ for (let c = 0; c <= counts[i]; c++)
92
+ walk(i + 1, [...at, counts[i] ? g.from[i] + ((g.to[i] - g.from[i]) * c) / counts[i] : g.from[i]], [...idx, c]);
77
93
  };
78
94
  walk(0, [], []);
79
95
  return out;
@@ -81,7 +97,9 @@ export function nodeGrid(g) {
81
97
 
82
98
  // the segment from p to q passes within r of c (strictly inside the ball)
83
99
  const crosses = (p, q, c, r) => {
84
- const d = [q[0] - p[0], q[1] - p[1], q[2] - p[2]], w = [c[0] - p[0], c[1] - p[1], c[2] - p[2]], dd = d[0] ** 2 + d[1] ** 2 + d[2] ** 2;
100
+ const d = [q[0] - p[0], q[1] - p[1], q[2] - p[2]],
101
+ w = [c[0] - p[0], c[1] - p[1], c[2] - p[2]],
102
+ dd = d[0] ** 2 + d[1] ** 2 + d[2] ** 2;
85
103
  const t = Math.min(1, Math.max(0, dd ? (w[0] * d[0] + w[1] * d[1] + w[2] * d[2]) / dd : 0));
86
104
  return Math.hypot(w[0] - t * d[0], w[1] - t * d[1], w[2] - t * d[2]) < r * (1 - 1e-9);
87
105
  };
@@ -96,26 +114,45 @@ const crosses = (p, q, c, r) => {
96
114
  * each node in turn; members by node index
97
115
  */
98
116
  export function groundStructure(nodes, o = {}) {
99
- const ids = Object.keys(nodes), n = ids.length, at = new Float64Array(3 * n);
100
- ids.forEach((id, i) => { const p = nodes[id]; if (!isPoint(p)) refuse('node', `node ${said(id)} is at ${said(p)}: a place [x, y] or [x, y, z] in mm`, { node: id }); at.set([p[0], p[1], p[2] ?? 0], 3 * i); });
101
- const reach = o.reach ?? Infinity, avoid = (o.avoid ?? []).filter((v) => !v.through).map((v) => ({ c: [v.at[0], v.at[1], v.at[2] ?? 0], r: v.r }));
117
+ const ids = Object.keys(nodes),
118
+ n = ids.length,
119
+ at = new Float64Array(3 * n);
120
+ ids.forEach((id, i) => {
121
+ const p = nodes[id];
122
+ if (!isPoint(p))
123
+ refuse('node', `node ${said(id)} is at ${said(p)}: a place [x, y] or [x, y, z] in mm`, { node: id });
124
+ at.set([p[0], p[1], p[2] ?? 0], 3 * i);
125
+ });
126
+ const reach = o.reach ?? Infinity,
127
+ avoid = (o.avoid ?? []).filter((v) => !v.through).map((v) => ({ c: [v.at[0], v.at[1], v.at[2] ?? 0], r: v.r }));
102
128
  let span = 0;
103
- for (let i = 0; i < 3; i++) { let lo = Infinity, hi = -Infinity; for (let p = 0; p < n; p++) { lo = Math.min(lo, at[3 * p + i]); hi = Math.max(hi, at[3 * p + i]); } span = Math.max(span, hi - lo); }
129
+ for (let i = 0; i < 3; i++) {
130
+ let lo = Infinity,
131
+ hi = -Infinity;
132
+ for (let p = 0; p < n; p++) {
133
+ lo = Math.min(lo, at[3 * p + i]);
134
+ hi = Math.max(hi, at[3 * p + i]);
135
+ }
136
+ span = Math.max(span, hi - lo);
137
+ }
104
138
  const members = [];
105
139
  for (let a = 0; a < n; a++) {
106
140
  // from a, the nearest node in each direction: a member to any further one there passes through it
107
141
  const nearest = new Map();
108
142
  for (let b = 0; b < n; b++) {
109
143
  if (b === a) continue;
110
- const d = [at[3 * b] - at[3 * a], at[3 * b + 1] - at[3 * a + 1], at[3 * b + 2] - at[3 * a + 2]], L = Math.hypot(...d);
111
- if (!(L > 1e-9 * span)) refuse('node', `nodes ${said(ids[a])} and ${said(ids[b])} are at the same place`, { nodes: [ids[a], ids[b]] });
144
+ const d = [at[3 * b] - at[3 * a], at[3 * b + 1] - at[3 * a + 1], at[3 * b + 2] - at[3 * a + 2]],
145
+ L = Math.hypot(...d);
146
+ if (!(L > 1e-9 * span))
147
+ refuse('node', `nodes ${said(ids[a])} and ${said(ids[b])} are at the same place`, { nodes: [ids[a], ids[b]] });
112
148
  const key = d.map((v) => Math.round((v / L) * 1e6)).join(',');
113
149
  const was = nearest.get(key);
114
150
  if (!was || L < was.L) nearest.set(key, { b, L });
115
151
  }
116
152
  for (const { b, L } of nearest.values()) {
117
153
  if (b < a || L > reach * (1 + 1e-9)) continue;
118
- const p = [at[3 * a], at[3 * a + 1], at[3 * a + 2]], q = [at[3 * b], at[3 * b + 1], at[3 * b + 2]];
154
+ const p = [at[3 * a], at[3 * a + 1], at[3 * a + 2]],
155
+ q = [at[3 * b], at[3 * b + 1], at[3 * b + 2]];
119
156
  if (avoid.some((v) => crosses(p, q, v.c, v.r))) continue;
120
157
  members.push({ a, b, length: L });
121
158
  }
@@ -129,65 +166,159 @@ export function groundStructure(nodes, o = {}) {
129
166
  // (a member's rows, one a case), and each column touches at most one block. The normal matrix A D Aᵀ is then solved
130
167
  // by eliminating the blocks first: a dense Schur complement over the global rows, and small blocks.
131
168
  function interior({ cost, start, rows, vals, G, blockOf, blocks, b, tol = 1e-9, loose = 1e-6, most = 120 }) {
132
- const N = cost.length, R = b.length;
169
+ const N = cost.length,
170
+ R = b.length;
133
171
  // each block's global rows touched, and each column's block
134
- const colBlock = new Int32Array(N).fill(-1), touched = blocks.map(() => new Map());
135
- for (let j = 0; j < N; j++) for (let e = start[j]; e < start[j + 1]; e++) { const r = rows[e]; if (r >= G) colBlock[j] = blockOf[r - G]; }
136
- for (let j = 0; j < N; j++) { const k = colBlock[j]; if (k < 0) continue; for (let e = start[j]; e < start[j + 1]; e++) { const r = rows[e]; if (r < G && !touched[k].has(r)) touched[k].set(r, touched[k].size); } }
172
+ const colBlock = new Int32Array(N).fill(-1),
173
+ touched = blocks.map(() => new Map());
174
+ for (let j = 0; j < N; j++)
175
+ for (let e = start[j]; e < start[j + 1]; e++) {
176
+ const r = rows[e];
177
+ if (r >= G) colBlock[j] = blockOf[r - G];
178
+ }
179
+ for (let j = 0; j < N; j++) {
180
+ const k = colBlock[j];
181
+ if (k < 0) continue;
182
+ for (let e = start[j]; e < start[j + 1]; e++) {
183
+ const r = rows[e];
184
+ if (r < G && !touched[k].has(r)) touched[k].set(r, touched[k].size);
185
+ }
186
+ }
137
187
  const local = new Int32Array(R - G); // a local row's place in its block
138
- for (const rowsOf of blocks) rowsOf.forEach((r, i) => { local[r - G] = i; });
139
- const Ax = (x) => { const y = new Float64Array(R); for (let j = 0; j < N; j++) { const v = x[j]; if (v) for (let e = start[j]; e < start[j + 1]; e++) y[rows[e]] += vals[e] * v; } return y; };
140
- const ATy = (y) => { const x = new Float64Array(N); for (let j = 0; j < N; j++) { let s = 0; for (let e = start[j]; e < start[j + 1]; e++) s += vals[e] * y[rows[e]]; x[j] = s; } return x; };
188
+ for (const rowsOf of blocks)
189
+ rowsOf.forEach((r, i) => {
190
+ local[r - G] = i;
191
+ });
192
+ const Ax = (x) => {
193
+ const y = new Float64Array(R);
194
+ for (let j = 0; j < N; j++) {
195
+ const v = x[j];
196
+ if (v) for (let e = start[j]; e < start[j + 1]; e++) y[rows[e]] += vals[e] * v;
197
+ }
198
+ return y;
199
+ };
200
+ const ATy = (y) => {
201
+ const x = new Float64Array(N);
202
+ for (let j = 0; j < N; j++) {
203
+ let s = 0;
204
+ for (let e = start[j]; e < start[j + 1]; e++) s += vals[e] * y[rows[e]];
205
+ x[j] = s;
206
+ }
207
+ return x;
208
+ };
141
209
  // factorise A D Aᵀ, returning its solve
142
210
  const factor = (D) => {
143
- const S = new Float64Array(G * G), H = blocks.map((r) => new Float64Array(r.length ** 2)), C = blocks.map((r, k) => new Float64Array(touched[k].size * r.length));
211
+ const S = new Float64Array(G * G),
212
+ H = blocks.map((r) => new Float64Array(r.length ** 2)),
213
+ C = blocks.map((r, k) => new Float64Array(touched[k].size * r.length));
144
214
  for (let j = 0; j < N; j++) {
145
- const d = D[j], k = colBlock[j], s0 = start[j], s1 = start[j + 1];
215
+ const d = D[j],
216
+ k = colBlock[j],
217
+ s0 = start[j],
218
+ s1 = start[j + 1];
146
219
  for (let e = s0; e < s1; e++) {
147
- const r = rows[e], v = d * vals[e];
220
+ const r = rows[e],
221
+ v = d * vals[e];
148
222
  for (let f = s0; f < s1; f++) {
149
223
  const q = rows[f];
150
- if (r < G && q < G) { if (q <= r) S[r * G + q] += v * vals[f]; }
151
- else if (r >= G && q >= G) H[k][local[r - G] * blocks[k].length + local[q - G]] += v * vals[f];
224
+ if (r < G && q < G) {
225
+ if (q <= r) S[r * G + q] += v * vals[f];
226
+ } else if (r >= G && q >= G) H[k][local[r - G] * blocks[k].length + local[q - G]] += v * vals[f];
152
227
  else if (r < G) C[k][touched[k].get(r) * blocks[k].length + local[q - G]] += v * vals[f];
153
228
  }
154
229
  }
155
230
  }
156
231
  // each block's inverse, and its part of the Schur complement S − C H⁻¹ Cᵀ
157
- const Hinv = H.map((h, k) => invert(h, blocks[k].length)), W = C.map((c, k) => mul(c, Hinv[k], touched[k].size, blocks[k].length));
232
+ const Hinv = H.map((h, k) => invert(h, blocks[k].length)),
233
+ W = C.map((c, k) => mul(c, Hinv[k], touched[k].size, blocks[k].length));
158
234
  blocks.forEach((rowsOf, k) => {
159
- const m = rowsOf.length, g = [...touched[k].keys()];
160
- g.forEach((r, i) => g.forEach((q, p) => { if (q > r) return; let s = 0; for (let t = 0; t < m; t++) s += W[k][i * m + t] * C[k][p * m + t]; S[r * G + q] -= s; }));
235
+ const m = rowsOf.length,
236
+ g = [...touched[k].keys()];
237
+ g.forEach((r, i) =>
238
+ g.forEach((q, p) => {
239
+ if (q > r) return;
240
+ let s = 0;
241
+ for (let t = 0; t < m; t++) s += W[k][i * m + t] * C[k][p * m + t];
242
+ S[r * G + q] -= s;
243
+ }),
244
+ );
161
245
  });
162
246
  const L = cholesky(S, G);
163
247
  return (rhs) => {
164
248
  const t = rhs.slice(0, G);
165
- blocks.forEach((rowsOf, k) => { const m = rowsOf.length, g = [...touched[k].keys()]; g.forEach((r, i) => { let s = 0; for (let q = 0; q < m; q++) s += W[k][i * m + q] * rhs[rowsOf[q]]; t[r] -= s; }); });
166
- const yG = cholSolve(L, t, G), y = new Float64Array(R);
249
+ blocks.forEach((rowsOf, k) => {
250
+ const m = rowsOf.length,
251
+ g = [...touched[k].keys()];
252
+ g.forEach((r, i) => {
253
+ let s = 0;
254
+ for (let q = 0; q < m; q++) s += W[k][i * m + q] * rhs[rowsOf[q]];
255
+ t[r] -= s;
256
+ });
257
+ });
258
+ const yG = cholSolve(L, t, G),
259
+ y = new Float64Array(R);
167
260
  y.set(yG);
168
261
  blocks.forEach((rowsOf, k) => {
169
- const m = rowsOf.length, g = [...touched[k].keys()], u = rowsOf.map((r) => rhs[r]);
170
- g.forEach((r, i) => { for (let q = 0; q < m; q++) u[q] -= C[k][i * m + q] * yG[r]; });
171
- for (let p = 0; p < m; p++) { let s = 0; for (let q = 0; q < m; q++) s += Hinv[k][p * m + q] * u[q]; y[rowsOf[p]] = s; }
262
+ const m = rowsOf.length,
263
+ g = [...touched[k].keys()],
264
+ u = rowsOf.map((r) => rhs[r]);
265
+ g.forEach((r, i) => {
266
+ for (let q = 0; q < m; q++) u[q] -= C[k][i * m + q] * yG[r];
267
+ });
268
+ for (let p = 0; p < m; p++) {
269
+ let s = 0;
270
+ for (let q = 0; q < m; q++) s += Hinv[k][p * m + q] * u[q];
271
+ y[rowsOf[p]] = s;
272
+ }
172
273
  });
173
274
  return y;
174
275
  };
175
276
  };
176
- const norm = (v) => Math.sqrt(v.reduce((t, x) => t + x * x, 0)), nb = norm(b), nc = norm(cost);
277
+ const norm = (v) => Math.sqrt(v.reduce((t, x) => t + x * x, 0)),
278
+ nb = norm(b),
279
+ nc = norm(cost);
177
280
  // Mehrotra's starting point
178
- const one = new Float64Array(N).fill(1), solve0 = factor(one);
179
- const x = ATy(solve0(b)), y = solve0(Ax(cost)), z = Float64Array.from(ATy(y), (v, j) => cost[j] - v);
180
- const dx0 = Math.max(-1.5 * Math.min(...x), 0), dz0 = Math.max(-1.5 * Math.min(...z), 0);
181
- for (let j = 0; j < N; j++) { x[j] += dx0; z[j] += dz0; }
182
- let xz = 0, sx = 0, sz = 0;
183
- for (let j = 0; j < N; j++) { xz += x[j] * z[j]; sx += x[j]; sz += z[j]; }
184
- for (let j = 0; j < N; j++) { x[j] += (0.5 * xz) / sz + 1e-12; z[j] += (0.5 * xz) / sx + 1e-12; }
185
- const stepTo = (v, dv) => { let a = 1; for (let j = 0; j < N; j++) if (dv[j] < 0) a = Math.min(a, -v[j] / dv[j]); return a; };
281
+ const one = new Float64Array(N).fill(1),
282
+ solve0 = factor(one);
283
+ const x = ATy(solve0(b)),
284
+ y = solve0(Ax(cost)),
285
+ z = Float64Array.from(ATy(y), (v, j) => cost[j] - v);
286
+ const dx0 = Math.max(-1.5 * Math.min(...x), 0),
287
+ dz0 = Math.max(-1.5 * Math.min(...z), 0);
288
+ for (let j = 0; j < N; j++) {
289
+ x[j] += dx0;
290
+ z[j] += dz0;
291
+ }
292
+ let xz = 0,
293
+ sx = 0,
294
+ sz = 0;
295
+ for (let j = 0; j < N; j++) {
296
+ xz += x[j] * z[j];
297
+ sx += x[j];
298
+ sz += z[j];
299
+ }
300
+ for (let j = 0; j < N; j++) {
301
+ x[j] += (0.5 * xz) / sz + 1e-12;
302
+ z[j] += (0.5 * xz) / sx + 1e-12;
303
+ }
304
+ const stepTo = (v, dv) => {
305
+ let a = 1;
306
+ for (let j = 0; j < N; j++) if (dv[j] < 0) a = Math.min(a, -v[j] / dv[j]);
307
+ return a;
308
+ };
186
309
  let best = { x, y, z, value: NaN, iterations: 0, err: Infinity, at: 0 };
187
310
  for (let it = 0; it < most; it++) {
188
- const Axv = Ax(x), rp = Float64Array.from(b, (v, i) => v - Axv[i]), Aty = ATy(y), rd = Float64Array.from(cost, (v, j) => v - Aty[j] - z[j]);
189
- let gap = 0, cx = 0, by = 0;
190
- for (let j = 0; j < N; j++) { gap += x[j] * z[j]; cx += cost[j] * x[j]; }
311
+ const Axv = Ax(x),
312
+ rp = Float64Array.from(b, (v, i) => v - Axv[i]),
313
+ Aty = ATy(y),
314
+ rd = Float64Array.from(cost, (v, j) => v - Aty[j] - z[j]);
315
+ let gap = 0,
316
+ cx = 0,
317
+ by = 0;
318
+ for (let j = 0; j < N; j++) {
319
+ gap += x[j] * z[j];
320
+ cx += cost[j] * x[j];
321
+ }
191
322
  for (let i = 0; i < R; i++) by += b[i] * y[i];
192
323
  const mu = gap / N;
193
324
  // the worst of the three relative errors: equilibrium, the members' limits, and the gap between the two values
@@ -196,23 +327,35 @@ function interior({ cost, start, rows, vals, G, blockOf, blocks, b, tol = 1e-9,
196
327
  if (!(cx < 1e14) || !Number.isFinite(mu)) break;
197
328
  if (err < best.err) best = { x: x.slice(), y: y.slice(), z: z.slice(), value: cx, iterations: it, err, at: it };
198
329
  else if (it - best.at > 15) break; // stalled: rounding in a nearly singular normal matrix stops further progress
199
- const D = Float64Array.from(x, (v, j) => v / z[j]), solve = factor(D);
330
+ const D = Float64Array.from(x, (v, j) => v / z[j]),
331
+ solve = factor(D);
200
332
  const direction = (rc) => {
201
333
  const t = new Float64Array(N);
202
334
  for (let j = 0; j < N; j++) t[j] = D[j] * rd[j] - rc[j] / z[j];
203
- const At = Ax(t), dy = solve(Float64Array.from(rp, (v, i) => v + At[i])), Atdy = ATy(dy);
204
- const dx = new Float64Array(N), dz = new Float64Array(N);
205
- for (let j = 0; j < N; j++) { dx[j] = D[j] * (Atdy[j] - rd[j]) + rc[j] / z[j]; dz[j] = rd[j] - Atdy[j]; }
335
+ const At = Ax(t),
336
+ dy = solve(Float64Array.from(rp, (v, i) => v + At[i])),
337
+ Atdy = ATy(dy);
338
+ const dx = new Float64Array(N),
339
+ dz = new Float64Array(N);
340
+ for (let j = 0; j < N; j++) {
341
+ dx[j] = D[j] * (Atdy[j] - rd[j]) + rc[j] / z[j];
342
+ dz[j] = rd[j] - Atdy[j];
343
+ }
206
344
  return { dx, dy, dz };
207
345
  };
208
346
  const aff = direction(Float64Array.from(x, (v, j) => -v * z[j]));
209
- const ap = stepTo(x, aff.dx), ad = stepTo(z, aff.dz);
347
+ const ap = stepTo(x, aff.dx),
348
+ ad = stepTo(z, aff.dz);
210
349
  let muAff = 0;
211
350
  for (let j = 0; j < N; j++) muAff += (x[j] + ap * aff.dx[j]) * (z[j] + ad * aff.dz[j]);
212
351
  const sigma = (muAff / N / mu) ** 3;
213
352
  const { dx, dy, dz } = direction(Float64Array.from(x, (v, j) => sigma * mu - v * z[j] - aff.dx[j] * aff.dz[j]));
214
- const sp = Math.min(1, 0.995 * stepTo(x, dx)), sd = Math.min(1, 0.995 * stepTo(z, dz));
215
- for (let j = 0; j < N; j++) { x[j] += sp * dx[j]; z[j] += sd * dz[j]; }
353
+ const sp = Math.min(1, 0.995 * stepTo(x, dx)),
354
+ sd = Math.min(1, 0.995 * stepTo(z, dz));
355
+ for (let j = 0; j < N; j++) {
356
+ x[j] += sp * dx[j];
357
+ z[j] += sd * dz[j];
358
+ }
216
359
  for (let i = 0; i < R; i++) y[i] += sd * dy[i];
217
360
  }
218
361
  // else the best point, if it met a looser test (a millionth): its value is good to about that share
@@ -220,11 +363,26 @@ function interior({ cost, start, rows, vals, G, blockOf, blocks, b, tol = 1e-9,
220
363
  }
221
364
  // a small symmetric positive definite matrix's inverse (m × m, row by row)
222
365
  function invert(h, m) {
223
- const L = cholesky(Float64Array.from(h), m), out = new Float64Array(m * m);
224
- for (let c = 0; c < m; c++) { const e = new Float64Array(m); e[c] = 1; const v = cholSolve(L, e, m); for (let r = 0; r < m; r++) out[r * m + c] = v[r]; }
366
+ const L = cholesky(Float64Array.from(h), m),
367
+ out = new Float64Array(m * m);
368
+ for (let c = 0; c < m; c++) {
369
+ const e = new Float64Array(m);
370
+ e[c] = 1;
371
+ const v = cholSolve(L, e, m);
372
+ for (let r = 0; r < m; r++) out[r * m + c] = v[r];
373
+ }
225
374
  return out;
226
375
  }
227
- const mul = (c, h, rows, m) => { const out = new Float64Array(rows * m); for (let i = 0; i < rows; i++) for (let j = 0; j < m; j++) { let s = 0; for (let t = 0; t < m; t++) s += c[i * m + t] * h[t * m + j]; out[i * m + j] = s; } return out; };
376
+ const mul = (c, h, rows, m) => {
377
+ const out = new Float64Array(rows * m);
378
+ for (let i = 0; i < rows; i++)
379
+ for (let j = 0; j < m; j++) {
380
+ let s = 0;
381
+ for (let t = 0; t < m; t++) s += c[i * m + t] * h[t * m + j];
382
+ out[i * m + j] = s;
383
+ }
384
+ return out;
385
+ };
228
386
  // Cholesky of a dense symmetric matrix from its lower triangle, in place. A pivot that is nothing beside its own
229
387
  // row's diagonal (a row no column reaches, or one that depends on the rows before it, so all but rounding cancelled)
230
388
  // is made huge, so that direction is solved as 0 (as Zhang's LIPSOL does). The test is against the row's own
@@ -236,7 +394,11 @@ function cholesky(S, n) {
236
394
  let d = S[rj + j];
237
395
  const own = d;
238
396
  for (let k = 0; k < j; k++) d -= S[rj + k] * S[rj + k];
239
- if (!(d > 1e-30 + 1e-13 * own)) { S[rj + j] = 1e64; for (let i = j + 1; i < n; i++) S[i * n + j] = 0; continue; }
397
+ if (!(d > 1e-30 + 1e-13 * own)) {
398
+ S[rj + j] = 1e64;
399
+ for (let i = j + 1; i < n; i++) S[i * n + j] = 0;
400
+ continue;
401
+ }
240
402
  const p = Math.sqrt(d);
241
403
  S[rj + j] = p;
242
404
  for (let i = j + 1; i < n; i++) {
@@ -250,8 +412,16 @@ function cholesky(S, n) {
250
412
  }
251
413
  function cholSolve(L, b, n) {
252
414
  const y = Float64Array.from(b);
253
- for (let i = 0; i < n; i++) { let s = y[i]; for (let k = 0; k < i; k++) s -= L[i * n + k] * y[k]; y[i] = s / L[i * n + i]; }
254
- for (let i = n - 1; i >= 0; i--) { let s = y[i]; for (let k = i + 1; k < n; k++) s -= L[k * n + i] * y[k]; y[i] = s / L[i * n + i]; }
415
+ for (let i = 0; i < n; i++) {
416
+ let s = y[i];
417
+ for (let k = 0; k < i; k++) s -= L[i * n + k] * y[k];
418
+ y[i] = s / L[i * n + i];
419
+ }
420
+ for (let i = n - 1; i >= 0; i--) {
421
+ let s = y[i];
422
+ for (let k = i + 1; k < n; k++) s -= L[k * n + i] * y[k];
423
+ y[i] = s / L[i * n + i];
424
+ }
255
425
  return y;
256
426
  }
257
427
 
@@ -281,80 +451,179 @@ function cholSolve(L, b, n) {
281
451
  * by its own length
282
452
  */
283
453
  export function layout(problem, o = {}) {
284
- if (!problem || typeof problem !== 'object') refuse('input', 'layout takes { nodes or grid, supports, loads or cases, strength }');
285
- for (const k of Object.keys(problem)) if (!KEYS.includes(k)) refuse('input', `a layout has no "${k}": it takes ${KEYS.join(', ')}`);
286
- for (const k of Object.keys(o)) if (!OPTIONS.includes(k)) refuse('input', `layout has no option "${k}": it takes ${OPTIONS.join(', ')}`);
454
+ if (!problem || typeof problem !== 'object')
455
+ refuse('input', 'layout takes { nodes or grid, supports, loads or cases, strength }');
456
+ for (const k of Object.keys(problem))
457
+ if (!KEYS.includes(k)) refuse('input', `a layout has no "${k}": it takes ${KEYS.join(', ')}`);
458
+ for (const k of Object.keys(o))
459
+ if (!OPTIONS.includes(k)) refuse('input', `layout has no option "${k}": it takes ${OPTIONS.join(', ')}`);
287
460
  // the strengths
288
- const st = problem.strength, strength = typeof st === 'number' ? { tension: st, compression: st } : st;
289
- if (!strength || !(strength.tension > 0) || !(strength.compression > 0) || !Number.isFinite(strength.tension) || !Number.isFinite(strength.compression)) refuse('strength', `strength is MPa above 0, one number or { tension, compression } (got ${said(st)})`);
290
- for (const [k, v] of [['density', problem.density], ['joint', problem.joint], ['reach', problem.reach]]) if (v != null && !(v >= 0 && Number.isFinite(v) && (k !== 'reach' || v > 0))) refuse('input', `${k} is ${k === 'density' ? 'g/cm³' : 'mm'}, ${k === 'reach' ? 'above 0' : '0 or more'} (got ${said(v)})`);
291
- const keep = o.keep ?? 1e-4, tolerance = o.tolerance ?? 1e-5;
292
- if (!(keep >= 0 && keep < 1)) refuse('input', `keep is a share of the thickest member, 0 to under 1 (got ${said(o.keep)})`);
293
- for (const [k, v] of [['start', o.start], ['add', o.add]]) if (v != null && !(Number.isInteger(v) && v >= 1)) refuse('input', `${k} is a whole number from 1 (got ${said(v)})`);
461
+ const st = problem.strength,
462
+ strength = typeof st === 'number' ? { tension: st, compression: st } : st;
463
+ if (
464
+ !strength ||
465
+ !(strength.tension > 0) ||
466
+ !(strength.compression > 0) ||
467
+ !Number.isFinite(strength.tension) ||
468
+ !Number.isFinite(strength.compression)
469
+ )
470
+ refuse('strength', `strength is MPa above 0, one number or { tension, compression } (got ${said(st)})`);
471
+ for (const [k, v] of [
472
+ ['density', problem.density],
473
+ ['joint', problem.joint],
474
+ ['reach', problem.reach],
475
+ ])
476
+ if (v != null && !(v >= 0 && Number.isFinite(v) && (k !== 'reach' || v > 0)))
477
+ refuse(
478
+ 'input',
479
+ `${k} is ${k === 'density' ? 'g/cm³' : 'mm'}, ${k === 'reach' ? 'above 0' : '0 or more'} (got ${said(v)})`,
480
+ );
481
+ const keep = o.keep ?? 1e-4,
482
+ tolerance = o.tolerance ?? 1e-5;
483
+ if (!(keep >= 0 && keep < 1))
484
+ refuse('input', `keep is a share of the thickest member, 0 to under 1 (got ${said(o.keep)})`);
485
+ for (const [k, v] of [
486
+ ['start', o.start],
487
+ ['add', o.add],
488
+ ])
489
+ if (v != null && !(Number.isInteger(v) && v >= 1))
490
+ refuse('input', `${k} is a whole number from 1 (got ${said(v)})`);
294
491
  // the nodes: named ones, then the grid's
295
- if (!problem.nodes && !problem.grid) refuse('input', 'a layout needs candidate nodes: nodes, or a grid of them, or both');
296
- const named = Array.isArray(problem.nodes) ? Object.fromEntries(problem.nodes.map((p, i) => [String(i), p])) : { ...(problem.nodes ?? {}) };
297
- for (const [id, p] of Object.entries(named)) if (!isPoint(p)) refuse('node', `node ${said(id)} is at ${said(p)}: a place [x, y] or [x, y, z] in mm`, { node: id });
492
+ if (!problem.nodes && !problem.grid)
493
+ refuse('input', 'a layout needs candidate nodes: nodes, or a grid of them, or both');
494
+ const named = Array.isArray(problem.nodes)
495
+ ? Object.fromEntries(problem.nodes.map((p, i) => [String(i), p]))
496
+ : { ...(problem.nodes ?? {}) };
497
+ for (const [id, p] of Object.entries(named))
498
+ if (!isPoint(p))
499
+ refuse('node', `node ${said(id)} is at ${said(p)}: a place [x, y] or [x, y, z] in mm`, { node: id });
298
500
  const avoid = problem.avoid ?? [];
299
501
  if (!Array.isArray(avoid)) refuse('input', 'avoid is a list of { at, r }: balls no node or member may enter');
300
- avoid.forEach((v, i) => { if (!v || !isPoint(v.at) || !(v.r > 0) || (v.through != null && typeof v.through !== 'boolean') || Object.keys(v).some((k) => !['at', 'r', 'through'].includes(k))) refuse('input', `avoid ${i + 1} is { at, r, through }: a centre in mm, a radius above 0, and through true where members may pass through it (got ${said(v)})`); });
301
- const inside = (p, solid) => avoid.some((v) => (!solid || !v.through) && Math.hypot(p[0] - v.at[0], p[1] - v.at[1], (p[2] ?? 0) - (v.at[2] ?? 0)) < v.r * (1 - 1e-9));
502
+ avoid.forEach((v, i) => {
503
+ if (
504
+ !v ||
505
+ !isPoint(v.at) ||
506
+ !(v.r > 0) ||
507
+ (v.through != null && typeof v.through !== 'boolean') ||
508
+ Object.keys(v).some((k) => !['at', 'r', 'through'].includes(k))
509
+ )
510
+ refuse(
511
+ 'input',
512
+ `avoid ${i + 1} is { at, r, through }: a centre in mm, a radius above 0, and through true where members may pass through it (got ${said(v)})`,
513
+ );
514
+ });
515
+ const inside = (p, solid) =>
516
+ avoid.some(
517
+ (v) =>
518
+ (!solid || !v.through) &&
519
+ Math.hypot(p[0] - v.at[0], p[1] - v.at[1], (p[2] ?? 0) - (v.at[2] ?? 0)) < v.r * (1 - 1e-9),
520
+ );
302
521
  // a named node may sit inside a region members pass through (the axle of a wheel the stays straddle); the grid's may not
303
- for (const [id, p] of Object.entries(named)) if (inside(p, true)) refuse('node', `node ${said(id)} is inside an avoided region`, { node: id });
522
+ for (const [id, p] of Object.entries(named))
523
+ if (inside(p, true)) refuse('node', `node ${said(id)} is inside an avoided region`, { node: id });
304
524
  const nodes = /** @type {Record<string, number[]>} */ ({ ...named });
305
525
  if (problem.grid) {
306
- const g = nodeGrid(problem.grid), near = problem.grid.pitch / 100, list = Object.values(named);
307
- for (const [id, p] of Object.entries(g)) if (!inside(p) && !list.some((q) => Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - (q[2] ?? 0)) < near) && !(id in nodes)) nodes[id] = p;
526
+ const g = nodeGrid(problem.grid),
527
+ near = problem.grid.pitch / 100,
528
+ list = Object.values(named);
529
+ for (const [id, p] of Object.entries(g))
530
+ if (
531
+ !inside(p) &&
532
+ !list.some((q) => Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - (q[2] ?? 0)) < near) &&
533
+ !(id in nodes)
534
+ )
535
+ nodes[id] = p;
308
536
  }
309
537
  // supports and load cases
310
- if (!problem.supports || typeof problem.supports !== 'object' || !Object.keys(problem.supports).length) refuse('support', 'supports is { node: "pinned" or { x, y, z } }: at least one');
538
+ if (!problem.supports || typeof problem.supports !== 'object' || !Object.keys(problem.supports).length)
539
+ refuse('support', 'supports is { node: "pinned" or { x, y, z } }: at least one');
311
540
  for (const [id, s] of Object.entries(problem.supports)) {
312
541
  if (!(id in nodes)) refuse('support', `a support names node ${said(id)}, which is not a node`, { node: id });
313
- if (s !== 'pinned' && !(s && typeof s === 'object' && Object.keys(s).every((k) => DIMS.includes(k) && typeof s[k] === 'boolean'))) refuse('support', `the support at ${said(id)} is ${said(s)}: "pinned", or { x, y, z } each true (held) or false`, { node: id });
542
+ if (
543
+ s !== 'pinned' &&
544
+ !(s && typeof s === 'object' && Object.keys(s).every((k) => DIMS.includes(k) && typeof s[k] === 'boolean'))
545
+ )
546
+ refuse(
547
+ 'support',
548
+ `the support at ${said(id)} is ${said(s)}: "pinned", or { x, y, z } each true (held) or false`,
549
+ { node: id },
550
+ );
314
551
  }
315
552
  if (problem.loads && problem.cases) refuse('input', 'give loads (one case) or cases, not both');
316
- const cases = problem.cases ? problem.cases.map((c, i) => ({ label: c?.label ?? `case ${i + 1}`, loads: c?.loads })) : [{ label: 'load', loads: problem.loads }];
553
+ const cases = problem.cases
554
+ ? problem.cases.map((c, i) => ({ label: c?.label ?? `case ${i + 1}`, loads: c?.loads }))
555
+ : [{ label: 'load', loads: problem.loads }];
317
556
  if (!cases.length) refuse('load', 'cases is a list of { label, loads }: at least one');
318
557
  for (const c of cases) {
319
- if (!Array.isArray(c.loads) || !c.loads.length) refuse('load', `${c.label} has no loads: a list of { node, force }`);
558
+ if (!Array.isArray(c.loads) || !c.loads.length)
559
+ refuse('load', `${c.label} has no loads: a list of { node, force }`);
320
560
  for (const l of c.loads) {
321
- if (!l || (typeof l.node !== 'string' && typeof l.node !== 'number') || !(String(l.node) in nodes)) refuse('load', `a load in ${c.label} names node ${said(l?.node)}, which is not a node`, { node: l?.node });
322
- if (!isPoint(l.force)) refuse('load', `the load at ${said(l.node)} in ${c.label} has force ${said(l.force)}: [x, y] or [x, y, z] in N`, { node: l.node });
561
+ if (!l || (typeof l.node !== 'string' && typeof l.node !== 'number') || !(String(l.node) in nodes))
562
+ refuse('load', `a load in ${c.label} names node ${said(l?.node)}, which is not a node`, { node: l?.node });
563
+ if (!isPoint(l.force))
564
+ refuse(
565
+ 'load',
566
+ `the load at ${said(l.node)} in ${c.label} has force ${said(l.force)}: [x, y] or [x, y, z] in N`,
567
+ { node: l.node },
568
+ );
323
569
  }
324
570
  }
325
571
  const flat = Object.values(nodes).every((p) => !p[2]) && cases.every((c) => c.loads.every((l) => !l.force[2]));
326
- if (problem.plane != null && typeof problem.plane !== 'boolean') refuse('input', `plane is true or false (got ${said(problem.plane)})`);
572
+ if (problem.plane != null && typeof problem.plane !== 'boolean')
573
+ refuse('input', `plane is true or false (got ${said(problem.plane)})`);
327
574
  const plane = problem.plane ?? flat;
328
- if (plane && !flat) refuse('input', 'plane is true, and a node or a load is off z = 0: a flat layout lies in x and y');
575
+ if (plane && !flat)
576
+ refuse('input', 'plane is true, and a node or a load is off z = 0: a flat layout lies in x and y');
329
577
  const dim = plane ? 2 : 3;
330
578
 
331
579
  // the ground structure, and the free freedoms' rows
332
- const gs = groundStructure(nodes, { reach: problem.reach, avoid }), { ids, at } = gs, n = ids.length, index = new Map(ids.map((id, i) => [id, i]));
580
+ const gs = groundStructure(nodes, { reach: problem.reach, avoid }),
581
+ { ids, at } = gs,
582
+ n = ids.length,
583
+ index = new Map(ids.map((id, i) => [id, i]));
333
584
  const held = new Uint8Array(dim * n);
334
- for (const [id, s] of Object.entries(problem.supports)) for (let d = 0; d < dim; d++) held[dim * index.get(id) + d] = s === 'pinned' || s[DIMS[d]] ? 1 : 0;
585
+ for (const [id, s] of Object.entries(problem.supports))
586
+ for (let d = 0; d < dim; d++) held[dim * index.get(id) + d] = s === 'pinned' || s[DIMS[d]] ? 1 : 0;
335
587
  const row = new Int32Array(dim * n).fill(-1);
336
588
  let free = 0;
337
589
  for (let i = 0; i < dim * n; i++) if (!held[i]) row[i] = free++;
338
- const K = cases.length, forces = cases.map((c) => {
339
- const f = new Float64Array(free);
340
- for (const l of c.loads) for (let d = 0; d < dim; d++) { const i = dim * index.get(String(l.node)) + d; if (row[i] >= 0) f[row[i]] += l.force[d] ?? 0; }
341
- return f;
342
- });
590
+ const K = cases.length,
591
+ forces = cases.map((c) => {
592
+ const f = new Float64Array(free);
593
+ for (const l of c.loads)
594
+ for (let d = 0; d < dim; d++) {
595
+ const i = dim * index.get(String(l.node)) + d;
596
+ if (row[i] >= 0) f[row[i]] += l.force[d] ?? 0;
597
+ }
598
+ return f;
599
+ });
343
600
  const F0 = Math.max(...forces.map((f) => Math.max(0, ...Array.from(f, Math.abs))));
344
601
  if (!(F0 > 0)) refuse('load', 'every load falls on a support: there is nothing for a frame to carry');
345
- const cand = gs.members, m = cand.length;
346
- if (!m) refuse('unstable', 'there are no candidate members: two nodes or more, out of each other\'s way and within reach');
347
- const L0 = Math.max(...cand.map((c) => c.length)), rho = strength.tension / strength.compression, joint = problem.joint ?? 0;
602
+ const cand = gs.members,
603
+ m = cand.length;
604
+ if (!m)
605
+ refuse('unstable', "there are no candidate members: two nodes or more, out of each other's way and within reach");
606
+ const L0 = Math.max(...cand.map((c) => c.length)),
607
+ rho = strength.tension / strength.compression,
608
+ joint = problem.joint ?? 0;
348
609
  // each candidate's unit direction a → b, and its cost (length plus a joint's) over L0
349
- const dir = new Float64Array(3 * m), cost = new Float64Array(m);
350
- cand.forEach((c, i) => { for (let d = 0; d < 3; d++) dir[3 * i + d] = (at[3 * c.b + d] - at[3 * c.a + d]) / c.length; cost[i] = (c.length + joint) / L0; });
610
+ const dir = new Float64Array(3 * m),
611
+ cost = new Float64Array(m);
612
+ cand.forEach((c, i) => {
613
+ for (let d = 0; d < 3; d++) dir[3 * i + d] = (at[3 * c.b + d] - at[3 * c.a + d]) / c.length;
614
+ cost[i] = (c.length + joint) / L0;
615
+ });
351
616
  // a member's virtual strain over its limit: Σ_k max(0, b·u_k, −b·u_k / ρ) over its cost (b·u in F0 L0 / σt units)
352
617
  const strainOf = (i, u) => {
353
618
  const c = cand[i];
354
619
  let s = 0;
355
620
  for (let k = 0; k < K; k++) {
356
621
  let e = 0;
357
- for (let d = 0; d < dim; d++) { const ra = row[dim * c.a + d], rb = row[dim * c.b + d]; e += dir[3 * i + d] * ((rb >= 0 ? u[k][rb] : 0) - (ra >= 0 ? u[k][ra] : 0)); }
622
+ for (let d = 0; d < dim; d++) {
623
+ const ra = row[dim * c.a + d],
624
+ rb = row[dim * c.b + d];
625
+ e += dir[3 * i + d] * ((rb >= 0 ? u[k][rb] : 0) - (ra >= 0 ? u[k][ra] : 0));
626
+ }
358
627
  s += Math.max(0, e, -e / rho);
359
628
  }
360
629
  return s / cost[i];
@@ -362,54 +631,134 @@ export function layout(problem, o = {}) {
362
631
 
363
632
  // one programme over the members in `act`
364
633
  const solveOver = (act) => {
365
- const M = act.length, G = K * free, N = M * (1 + 3 * K), start = new Int32Array(N + 1), rowsL = [], valsL = [], c = new Float64Array(N);
366
- const blockOf = new Int32Array(M * K), blocks = [];
634
+ const M = act.length,
635
+ G = K * free,
636
+ N = M * (1 + 3 * K),
637
+ start = new Int32Array(N + 1),
638
+ rowsL = [],
639
+ valsL = [],
640
+ c = new Float64Array(N);
641
+ const blockOf = new Int32Array(M * K),
642
+ blocks = [];
367
643
  let j = 0;
368
- const col = (entries, cj) => { for (const [r, v] of entries) { rowsL.push(r); valsL.push(v); } c[j] = cj; start[++j] = rowsL.length; };
644
+ const col = (entries, cj) => {
645
+ for (const [r, v] of entries) {
646
+ rowsL.push(r);
647
+ valsL.push(v);
648
+ }
649
+ c[j] = cj;
650
+ start[++j] = rowsL.length;
651
+ };
369
652
  act.forEach((i, s) => {
370
- const mrow = (k) => G + s * K + k, bcol = (k, sign) => {
371
- const e = [];
372
- for (const [node, side] of [[cand[i].a, -1], [cand[i].b, 1]]) for (let d = 0; d < dim; d++) { const r = row[dim * node + d]; if (r >= 0 && dir[3 * i + d]) e.push([k * free + r, sign * side * dir[3 * i + d]]); }
373
- return e;
374
- };
375
- blocks.push(Array.from({ length: K }, (_, k) => { blockOf[s * K + k] = s; return mrow(k); }));
376
- col(Array.from({ length: K }, (_, k) => [mrow(k), 1]), cost[i]); // a
377
- for (let k = 0; k < K; k++) { col([...bcol(k, 1), [mrow(k), -1]], 0); col([...bcol(k, -1), [mrow(k), -rho]], 0); col([[mrow(k), -1]], 0); } // p, n, slack
653
+ const mrow = (k) => G + s * K + k,
654
+ bcol = (k, sign) => {
655
+ const e = [];
656
+ for (const [node, side] of [
657
+ [cand[i].a, -1],
658
+ [cand[i].b, 1],
659
+ ])
660
+ for (let d = 0; d < dim; d++) {
661
+ const r = row[dim * node + d];
662
+ if (r >= 0 && dir[3 * i + d]) e.push([k * free + r, sign * side * dir[3 * i + d]]);
663
+ }
664
+ return e;
665
+ };
666
+ blocks.push(
667
+ Array.from({ length: K }, (_, k) => {
668
+ blockOf[s * K + k] = s;
669
+ return mrow(k);
670
+ }),
671
+ );
672
+ col(
673
+ Array.from({ length: K }, (_, k) => [mrow(k), 1]),
674
+ cost[i],
675
+ ); // a
676
+ for (let k = 0; k < K; k++) {
677
+ col([...bcol(k, 1), [mrow(k), -1]], 0);
678
+ col([...bcol(k, -1), [mrow(k), -rho]], 0);
679
+ col([[mrow(k), -1]], 0);
680
+ } // p, n, slack
378
681
  });
379
682
  const b = new Float64Array(G + M * K);
380
- forces.forEach((f, k) => { for (let r = 0; r < free; r++) b[k * free + r] = f[r] / F0; });
381
- const r = interior({ cost: c, start, rows: Int32Array.from(rowsL), vals: Float64Array.from(valsL), G, blockOf, blocks, b });
683
+ forces.forEach((f, k) => {
684
+ for (let r = 0; r < free; r++) b[k * free + r] = f[r] / F0;
685
+ });
686
+ const r = interior({
687
+ cost: c,
688
+ start,
689
+ rows: Int32Array.from(rowsL),
690
+ vals: Float64Array.from(valsL),
691
+ G,
692
+ blockOf,
693
+ blocks,
694
+ b,
695
+ });
382
696
  const u = Array.from({ length: K }, (_, k) => r.y.subarray(k * free, (k + 1) * free));
383
697
  return { ...r, u, M };
384
698
  };
385
699
  // the first programme: each node's nearest candidates; then members added where they would help
386
700
  const byNode = Array.from({ length: n }, () => []);
387
- cand.forEach((c, i) => { byNode[c.a].push(i); byNode[c.b].push(i); });
701
+ cand.forEach((c, i) => {
702
+ byNode[c.a].push(i);
703
+ byNode[c.b].push(i);
704
+ });
388
705
  for (const list of byNode) list.sort((p, q) => cand[p].length - cand[q].length);
389
706
  const loaded = new Set(cases.flatMap((cs) => cs.loads.map((l) => index.get(String(l.node)))));
390
- let first = o.start ?? (plane ? 8 : 18), act, r, rounds = 0;
707
+ let first = o.start ?? (plane ? 8 : 18),
708
+ act,
709
+ r,
710
+ rounds = 0;
391
711
  const adding = o.adding !== false;
392
712
  for (;;) {
393
- act = adding ? [...new Set(byNode.flatMap((list) => list.slice(0, first)))].sort((p, q) => p - q) : cand.map((_, i) => i);
713
+ act = adding
714
+ ? [...new Set(byNode.flatMap((list) => list.slice(0, first)))].sort((p, q) => p - q)
715
+ : cand.map((_, i) => i);
394
716
  // a loaded freedom no member reaches cannot be carried
395
717
  const reached = new Uint8Array(free);
396
- for (const i of act) for (const node of [cand[i].a, cand[i].b]) for (let d = 0; d < dim; d++) if (dir[3 * i + d] && row[dim * node + d] >= 0) reached[row[dim * node + d]] = 1;
397
- const unreached = [...loaded].some((p) => { for (let d = 0; d < dim; d++) { const q = row[dim * p + d]; if (q >= 0 && !reached[q] && forces.some((f) => f[q])) return true; } return false; });
398
- if (!unreached) { r = solveOver(act); rounds++; if (r.ok) break; }
399
- if (!adding || first >= n) refuse('unstable', 'no frame of the candidate members carries the loads to the supports: hold more freedoms, or add nodes and members (a larger reach, a finer grid, or less avoided)', { rounds });
718
+ for (const i of act)
719
+ for (const node of [cand[i].a, cand[i].b])
720
+ for (let d = 0; d < dim; d++) if (dir[3 * i + d] && row[dim * node + d] >= 0) reached[row[dim * node + d]] = 1;
721
+ const unreached = [...loaded].some((p) => {
722
+ for (let d = 0; d < dim; d++) {
723
+ const q = row[dim * p + d];
724
+ if (q >= 0 && !reached[q] && forces.some((f) => f[q])) return true;
725
+ }
726
+ return false;
727
+ });
728
+ if (!unreached) {
729
+ r = solveOver(act);
730
+ rounds++;
731
+ if (r.ok) break;
732
+ }
733
+ if (!adding || first >= n)
734
+ refuse(
735
+ 'unstable',
736
+ 'no frame of the candidate members carries the loads to the supports: hold more freedoms, or add nodes and members (a larger reach, a finer grid, or less avoided)',
737
+ { rounds },
738
+ );
400
739
  first = Math.min(2 * first, n);
401
740
  }
402
741
  for (const most = o.add ?? 0; adding;) {
403
742
  const inside = new Uint8Array(m);
404
743
  for (const i of act) inside[i] = 1;
405
744
  const over = [];
406
- for (let i = 0; i < m; i++) if (!inside[i]) { const s = strainOf(i, r.u); if (s > 1 + tolerance) over.push([i, s]); }
745
+ for (let i = 0; i < m; i++)
746
+ if (!inside[i]) {
747
+ const s = strainOf(i, r.u);
748
+ if (s > 1 + tolerance) over.push([i, s]);
749
+ }
407
750
  if (!over.length) break;
408
751
  over.sort((p, q) => q[1] - p[1]);
409
752
  const take = most || Math.max(100, Math.ceil(act.length / 10));
410
753
  act = [...act, ...over.slice(0, take).map(([i]) => i)].sort((p, q) => p - q);
411
- r = solveOver(act); rounds++;
412
- if (!r.ok) refuse('unstable', 'the programme did not settle after adding members: the problem may be badly scaled (forces or lengths over many orders)', { rounds });
754
+ r = solveOver(act);
755
+ rounds++;
756
+ if (!r.ok)
757
+ refuse(
758
+ 'unstable',
759
+ 'the programme did not settle after adding members: the problem may be badly scaled (forces or lengths over many orders)',
760
+ { rounds },
761
+ );
413
762
  }
414
763
 
415
764
  // the proof: no candidate's virtual strain is past its limit (1 at the limit)
@@ -417,29 +766,90 @@ export function layout(problem, o = {}) {
417
766
  for (let i = 0; i < m; i++) strain = Math.max(strain, strainOf(i, r.u));
418
767
  // the answer, back in mm², N and mm³
419
768
  const scaleA = F0 / strength.tension;
420
- let volume = 0, amax = 0;
769
+ let volume = 0,
770
+ amax = 0;
421
771
  const all = act.map((i, s) => {
422
- const base = s * (1 + 3 * K), area = r.x[base] * scaleA, f = Array.from({ length: K }, (_, k) => (r.x[base + 1 + 3 * k] - r.x[base + 2 + 3 * k]) * F0);
423
- volume += area * cand[i].length; amax = Math.max(amax, area);
772
+ const base = s * (1 + 3 * K),
773
+ area = r.x[base] * scaleA,
774
+ f = Array.from({ length: K }, (_, k) => (r.x[base + 1 + 3 * k] - r.x[base + 2 + 3 * k]) * F0);
775
+ volume += area * cand[i].length;
776
+ amax = Math.max(amax, area);
424
777
  return { i, area, f };
425
778
  });
426
779
  let thin = 0;
427
- const members = all.filter((e) => { const k = e.area > keep * amax; if (!k) thin += e.area * cand[e.i].length; return k; }).sort((p, q) => q.area - p.area).map(({ i, area, f }) => {
428
- const c = cand[i], big = Math.max(...f.map(Math.abs)), t = f.some((v) => v > 1e-9 * big), cmp = f.some((v) => v < -1e-9 * big);
429
- return { id: `${ids[c.a]}-${ids[c.b]}`, a: ids[c.a], b: ids[c.b], length: round(c.length, 9), area: round(area, 9), forces: f.map((v) => round(v, 9)), kind: /** @type {LayoutMember['kind']} */ (t && cmp ? 'both' : cmp ? 'compression' : 'tension') };
430
- });
431
- const used = new Set([...members.flatMap((e) => [e.a, e.b]), ...Object.keys(problem.supports), ...cases.flatMap((c) => c.loads.map((l) => String(l.node)))]);
780
+ const members = all
781
+ .filter((e) => {
782
+ const k = e.area > keep * amax;
783
+ if (!k) thin += e.area * cand[e.i].length;
784
+ return k;
785
+ })
786
+ .sort((p, q) => q.area - p.area)
787
+ .map(({ i, area, f }) => {
788
+ const c = cand[i],
789
+ big = Math.max(...f.map(Math.abs)),
790
+ t = f.some((v) => v > 1e-9 * big),
791
+ cmp = f.some((v) => v < -1e-9 * big);
792
+ return {
793
+ id: `${ids[c.a]}-${ids[c.b]}`,
794
+ a: ids[c.a],
795
+ b: ids[c.b],
796
+ length: round(c.length, 9),
797
+ area: round(area, 9),
798
+ forces: f.map((v) => round(v, 9)),
799
+ kind: /** @type {LayoutMember['kind']} */ (t && cmp ? 'both' : cmp ? 'compression' : 'tension'),
800
+ };
801
+ });
802
+ const used = new Set([
803
+ ...members.flatMap((e) => [e.a, e.b]),
804
+ ...Object.keys(problem.supports),
805
+ ...cases.flatMap((c) => c.loads.map((l) => String(l.node))),
806
+ ]);
432
807
  const pos = (id) => /** @type {Vec3} */ (Array.from(at.subarray(3 * index.get(id), 3 * index.get(id) + 3)));
433
808
  // the virtual displacements, mm, scaled so a member at its tension limit stretches by its own length (a strain of
434
809
  // 1), one at its compression limit shortens by σc / σt of it
435
- const virtual = r.u.map((u) => Object.fromEntries([...used].map((id) => [id, Array.from({ length: dim }, (_, d) => { const q = row[dim * index.get(id) + d]; return q >= 0 ? round(u[q] * L0, 9) : 0; })])));
436
- return { volume, mass: problem.density != null ? (volume * problem.density) / 1e6 : null, members, nodes: Object.fromEntries([...used].map((id) => [id, pos(id)])), cases: cases.map((c) => c.label), plane, candidates: m, programme: act.length, rounds, strain: round(strain, 9), left: volume ? thin / volume : 0,
437
- virtual, strength: { ...strength }, joint, supports: Object.fromEntries(Object.entries(problem.supports).map(([id, s]) => [id, s === 'pinned' ? 'pinned' : DIMS.filter((d) => s[d]).join('')])), loads: cases.map((c) => ({ label: c.label, loads: c.loads })) };
810
+ const virtual = r.u.map((u) =>
811
+ Object.fromEntries(
812
+ [...used].map((id) => [
813
+ id,
814
+ Array.from({ length: dim }, (_, d) => {
815
+ const q = row[dim * index.get(id) + d];
816
+ return q >= 0 ? round(u[q] * L0, 9) : 0;
817
+ }),
818
+ ]),
819
+ ),
820
+ );
821
+ return {
822
+ volume,
823
+ mass: problem.density != null ? (volume * problem.density) / 1e6 : null,
824
+ members,
825
+ nodes: Object.fromEntries([...used].map((id) => [id, pos(id)])),
826
+ cases: cases.map((c) => c.label),
827
+ plane,
828
+ candidates: m,
829
+ programme: act.length,
830
+ rounds,
831
+ strain: round(strain, 9),
832
+ left: volume ? thin / volume : 0,
833
+ virtual,
834
+ strength: { ...strength },
835
+ joint,
836
+ supports: Object.fromEntries(
837
+ Object.entries(problem.supports).map(([id, s]) => [
838
+ id,
839
+ s === 'pinned' ? 'pinned' : DIMS.filter((d) => s[d]).join(''),
840
+ ]),
841
+ ),
842
+ loads: cases.map((c) => ({ label: c.label, loads: c.loads })),
843
+ };
438
844
  }
439
845
 
440
846
  // ---- handing the layout on: a frame to size, and joints to optimise ----
441
847
 
442
- const isLayout = (r, what) => { if (!r || !Array.isArray(r.members) || !r.nodes || !r.loads) refuse('input', `${what} takes a layout's result (what layout() returns)`); return r; };
848
+ const isLayout = (r, what) => {
849
+ if (!r || !Array.isArray(r.members) || !r.nodes || !r.loads)
850
+ refuse('input', `${what} takes a layout's result (what layout() returns)`);
851
+ return r;
852
+ };
443
853
  const vec3 = (f) => /** @type {Vec3} */ ([f[0] ?? 0, f[1] ?? 0, f[2] ?? 0]);
444
854
 
445
855
  /**
@@ -458,18 +868,44 @@ const vec3 = (f) => /** @type {Vec3} */ ([f[0] ?? 0, f[1] ?? 0, f[2] ?? 0]);
458
868
  */
459
869
  export function layoutFrame(result, o = {}) {
460
870
  const r = isLayout(result, 'layoutFrame');
461
- if (!o.material || !(o.material.E > 0)) refuse('input', `layoutFrame needs the members' material: { E, nu, density, strength } with E in MPa above 0 (got ${said(o.material)})`);
462
- if (o.ends != null && !['rigid', 'pinned'].includes(o.ends)) refuse('input', `ends is 'rigid' or 'pinned' (got ${said(o.ends)})`);
463
- const bar = (A) => { const d = Math.sqrt((4 * A) / Math.PI), I = (Math.PI * d ** 4) / 64; return { A, Iy: I, Iz: I, J: 2 * I, cy: d / 2, cz: d / 2 }; };
871
+ if (!o.material || !(o.material.E > 0))
872
+ refuse(
873
+ 'input',
874
+ `layoutFrame needs the members' material: { E, nu, density, strength } with E in MPa above 0 (got ${said(o.material)})`,
875
+ );
876
+ if (o.ends != null && !['rigid', 'pinned'].includes(o.ends))
877
+ refuse('input', `ends is 'rigid' or 'pinned' (got ${said(o.ends)})`);
878
+ const bar = (A) => {
879
+ const d = Math.sqrt((4 * A) / Math.PI),
880
+ I = (Math.PI * d ** 4) / 64;
881
+ return { A, Iy: I, Iz: I, J: 2 * I, cy: d / 2, cz: d / 2 };
882
+ };
464
883
  const ends = o.ends === 'pinned' ? { a: 'ball', b: 'pinned' } : undefined;
465
- const elements = r.members.map((m) => ({ id: m.id, a: m.a, b: m.b, section: o.section ?? bar(m.area), material: { ...o.material }, ...(ends ? { ends } : {}) }));
466
- const supports = Object.fromEntries(Object.entries(r.supports).map(([id, s]) => {
467
- const held = s === 'pinned' ? 'xyz' : s, out = { x: held.includes('x'), y: held.includes('y'), z: held.includes('z') || r.plane };
468
- if (r.plane) Object.assign(out, { rx: true, ry: true });
469
- return [id, out];
884
+ const elements = r.members.map((m) => ({
885
+ id: m.id,
886
+ a: m.a,
887
+ b: m.b,
888
+ section: o.section ?? bar(m.area),
889
+ material: { ...o.material },
890
+ ...(ends ? { ends } : {}),
470
891
  }));
471
- const cases = r.loads.map((c) => ({ label: c.label, loads: c.loads.map((l) => ({ node: String(l.node), force: vec3(l.force) })) }));
472
- return { model: { nodes: { ...r.nodes }, elements, supports, loads: cases[0].loads, loose: 'hold' }, cases, members: elements.map((e) => e.id) };
892
+ const supports = Object.fromEntries(
893
+ Object.entries(r.supports).map(([id, s]) => {
894
+ const held = s === 'pinned' ? 'xyz' : s,
895
+ out = { x: held.includes('x'), y: held.includes('y'), z: held.includes('z') || r.plane };
896
+ if (r.plane) Object.assign(out, { rx: true, ry: true });
897
+ return [id, out];
898
+ }),
899
+ );
900
+ const cases = r.loads.map((c) => ({
901
+ label: c.label,
902
+ loads: c.loads.map((l) => ({ node: String(l.node), force: vec3(l.force) })),
903
+ }));
904
+ return {
905
+ model: { nodes: { ...r.nodes }, elements, supports, loads: cases[0].loads, loose: 'hold' },
906
+ cases,
907
+ members: elements.map((e) => e.id),
908
+ };
473
909
  }
474
910
 
475
911
  /**
@@ -490,46 +926,110 @@ export function layoutFrame(result, o = {}) {
490
926
  */
491
927
  export function layoutJoints(result, o = {}) {
492
928
  const r = isLayout(result, 'layoutJoints');
493
- if (typeof o.material !== 'string' || !o.material) refuse('input', `layoutJoints needs the joints' material, a rule set's name such as "pla" or "al6061" (got ${said(o.material)})`);
494
- for (const k of ['stub', 'cell', 'volume']) if (o[k] != null && !(o[k] > 0 && Number.isFinite(o[k]) && (k !== 'volume' || o[k] < 1))) refuse('input', `${k} is ${k === 'volume' ? 'a share above 0 and under 1' : 'mm above 0'} (got ${said(o[k])})`);
495
- const dia = (m) => { const d = o.diameters?.[m.id]; if (d != null && !(d > 0)) refuse('input', `diameters.${m.id} is mm above 0 (got ${said(d)})`); return d ?? Math.sqrt((4 * m.area) / Math.PI); };
496
- // each member's force in each case: the layout's (one set the strengths allow), or the frame's own, solved
497
- const K = r.loads.length, forcesOf = (m) => {
498
- const f = o.forces?.[m.id];
499
- if (f == null) return m.forces;
500
- if (!Array.isArray(f) || f.length !== K || !f.every(Number.isFinite)) refuse('input', `forces.${m.id} is its force in each of the ${K} cases, N, tension positive (got ${said(f)})`);
501
- return f.map((v) => round(v, 9));
929
+ if (typeof o.material !== 'string' || !o.material)
930
+ refuse(
931
+ 'input',
932
+ `layoutJoints needs the joints' material, a rule set's name such as "pla" or "al6061" (got ${said(o.material)})`,
933
+ );
934
+ for (const k of ['stub', 'cell', 'volume'])
935
+ if (o[k] != null && !(o[k] > 0 && Number.isFinite(o[k]) && (k !== 'volume' || o[k] < 1)))
936
+ refuse('input', `${k} is ${k === 'volume' ? 'a share above 0 and under 1' : 'mm above 0'} (got ${said(o[k])})`);
937
+ const dia = (m) => {
938
+ const d = o.diameters?.[m.id];
939
+ if (d != null && !(d > 0)) refuse('input', `diameters.${m.id} is mm above 0 (got ${said(d)})`);
940
+ return d ?? Math.sqrt((4 * m.area) / Math.PI);
502
941
  };
503
- for (const id of Object.keys(o.forces ?? {})) if (!r.members.some((m) => m.id === id)) refuse('input', `forces names member ${said(id)}, which is not in the layout`);
942
+ // each member's force in each case: the layout's (one set the strengths allow), or the frame's own, solved
943
+ const K = r.loads.length,
944
+ forcesOf = (m) => {
945
+ const f = o.forces?.[m.id];
946
+ if (f == null) return m.forces;
947
+ if (!Array.isArray(f) || f.length !== K || !f.every(Number.isFinite))
948
+ refuse('input', `forces.${m.id} is its force in each of the ${K} cases, N, tension positive (got ${said(f)})`);
949
+ return f.map((v) => round(v, 9));
950
+ };
951
+ for (const id of Object.keys(o.forces ?? {}))
952
+ if (!r.members.some((m) => m.id === id))
953
+ refuse('input', `forces names member ${said(id)}, which is not in the layout`);
504
954
  const meets = new Map();
505
- for (const m of r.members) for (const [here, there] of [[m.a, m.b], [m.b, m.a]]) { if (!meets.has(here)) meets.set(here, []); meets.get(here).push({ m, there }); }
955
+ for (const m of r.members)
956
+ for (const [here, there] of [
957
+ [m.a, m.b],
958
+ [m.b, m.a],
959
+ ]) {
960
+ if (!meets.has(here)) meets.set(here, []);
961
+ meets.get(here).push({ m, there });
962
+ }
506
963
  const which = o.nodes ?? [...meets.keys()].filter((id) => meets.get(id).length >= 2);
507
- for (const id of which) if (!meets.has(id)) refuse('node', `layoutJoints names node ${said(id)}, where no member meets`, { node: id });
508
- const dim = r.plane ? 2 : 3, fig = (v) => round(v, 6);
964
+ for (const id of which)
965
+ if (!meets.has(id)) refuse('node', `layoutJoints names node ${said(id)}, where no member meets`, { node: id });
966
+ const dim = r.plane ? 2 : 3,
967
+ fig = (v) => round(v, 6);
509
968
  return which.map((id) => {
510
- const p = r.nodes[id], list = meets.get(id);
969
+ const p = r.nodes[id],
970
+ list = meets.get(id);
511
971
  const members = list.map(({ m, there }) => {
512
- const q = r.nodes[there], L = Math.hypot(q[0] - p[0], q[1] - p[1], q[2] - p[2]);
513
- return { id: m.id, to: there, direction: [0, 1, 2].slice(0, dim).map((d) => fig((q[d] - p[d]) / L)), forces: forcesOf(m), diameter: fig(dia(m)) };
972
+ const q = r.nodes[there],
973
+ L = Math.hypot(q[0] - p[0], q[1] - p[1], q[2] - p[2]);
974
+ return {
975
+ id: m.id,
976
+ to: there,
977
+ direction: [0, 1, 2].slice(0, dim).map((d) => fig((q[d] - p[d]) / L)),
978
+ forces: forcesOf(m),
979
+ diameter: fig(dia(m)),
980
+ };
514
981
  });
515
- const widest = Math.max(...members.map((e) => e.diameter)), narrowest = Math.min(...members.map((e) => e.diameter));
516
- const stub = o.stub ?? 2 * widest, cell = o.cell ?? fig(narrowest / 4), end = (e) => e.direction.map((v) => fig(v * stub));
982
+ const widest = Math.max(...members.map((e) => e.diameter)),
983
+ narrowest = Math.min(...members.map((e) => e.diameter));
984
+ const stub = o.stub ?? 2 * widest,
985
+ cell = o.cell ?? fig(narrowest / 4),
986
+ end = (e) => e.direction.map((v) => fig(v * stub));
517
987
  // the stub that carries the most, in its worst case, is held; the others' forces load the joint
518
- const held = members.reduce((b, e) => (Math.max(...e.forces.map(Math.abs)) > Math.max(...b.forces.map(Math.abs)) ? e : b), members[0]);
988
+ const held = members.reduce(
989
+ (b, e) => (Math.max(...e.forces.map(Math.abs)) > Math.max(...b.forces.map(Math.abs)) ? e : b),
990
+ members[0],
991
+ );
519
992
  const loads = [];
520
993
  r.loads.forEach((c, k) => {
521
- for (const e of members) if (e !== held && e.forces[k]) loads.push({ at: end(e), r: fig(e.diameter / 2), force: e.direction.map((v) => fig(v * e.forces[k])), case: c.label, label: `${e.id}: ${fig(e.forces[k])} N ${e.forces[k] > 0 ? 'tension' : 'compression'}` });
522
- for (const l of c.loads) if (String(l.node) === id) loads.push({ at: Array(dim).fill(0), r: fig(widest / 2), force: [0, 1, 2].slice(0, dim).map((d) => l.force[d] ?? 0), case: c.label, label: 'the outside load at the joint' });
994
+ for (const e of members)
995
+ if (e !== held && e.forces[k])
996
+ loads.push({
997
+ at: end(e),
998
+ r: fig(e.diameter / 2),
999
+ force: e.direction.map((v) => fig(v * e.forces[k])),
1000
+ case: c.label,
1001
+ label: `${e.id}: ${fig(e.forces[k])} N ${e.forces[k] > 0 ? 'tension' : 'compression'}`,
1002
+ });
1003
+ for (const l of c.loads)
1004
+ if (String(l.node) === id)
1005
+ loads.push({
1006
+ at: Array(dim).fill(0),
1007
+ r: fig(widest / 2),
1008
+ force: [0, 1, 2].slice(0, dim).map((d) => l.force[d] ?? 0),
1009
+ case: c.label,
1010
+ label: 'the outside load at the joint',
1011
+ });
523
1012
  });
524
1013
  const problem = {
525
1014
  title: `Joint ${id} of a frame layout`,
526
1015
  description: `The joint where ${members.map((e) => e.id).join(', ')} meet, centred on the node (at ${p.map(fig).join(', ')} mm in the layout). Each member is a stub ${fig(stub)} mm long; ${held.id} is held, and the others carry their forces from the layout in each case.`,
527
- material: o.material, cell, volume: o.volume ?? 0.3,
1016
+ material: o.material,
1017
+ cell,
1018
+ volume: o.volume ?? 0.3,
528
1019
  ...(dim === 2 ? { thickness: fig(widest) } : {}),
529
1020
  space: { at: Array(dim).fill(0), size: Array(dim).fill(fig(2 * (stub + widest))) },
530
1021
  keep: members.map((e) => ({ at: end(e), r: fig(e.diameter / 2), label: `${e.id}'s end` })),
531
1022
  supports: [{ at: end(held), r: fig(held.diameter / 2), label: `${held.id}: the frame beyond it` }],
532
- loads: loads.length ? loads : [{ at: end(members[0]), r: fig(members[0].diameter / 2), force: Array(dim).fill(0), label: 'nothing: no member carries a force here' }],
1023
+ loads: loads.length
1024
+ ? loads
1025
+ : [
1026
+ {
1027
+ at: end(members[0]),
1028
+ r: fig(members[0].diameter / 2),
1029
+ force: Array(dim).fill(0),
1030
+ label: 'nothing: no member carries a force here',
1031
+ },
1032
+ ],
533
1033
  };
534
1034
  return { node: id, at: vec3(p), members, problem };
535
1035
  });