@rulecad/fea 0.2.11 → 0.2.13

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/CHANGELOG.md CHANGED
@@ -2,6 +2,31 @@
2
2
 
3
3
  What changed in each release, for someone upgrading a workspace.
4
4
 
5
+ ## 0.2.13: frame layout optimisation
6
+ ### Added
7
+
8
+ - `@rulecad/fea/layout`, a new entry: `layout(problem)` finds the least-volume pin-jointed frame that carries the
9
+ loads to the supports, choosing members from every pair of candidate nodes (a ground structure) and giving each its
10
+ area. It solves the plastic layout programme by an interior point method and adds members a few at a time where
11
+ the solution's virtual strains say they would help (Gilbert and Tyas 2003), so it proves the least volume over
12
+ every candidate while holding a small share of them. Several load cases share one set of areas; strengths may
13
+ differ in tension and compression; a joint can be given a cost as a length of member (fewer, longer members);
14
+ balls can be kept clear of nodes and members, or of nodes only (`through`, a wheel the stays straddle). Flat
15
+ layouts (every node and load at z = 0) and layouts in space.
16
+ - `groundStructure(nodes)` (the candidates, less members through a third node) and `nodeGrid({ from, to, pitch })`.
17
+ - `layoutFrame(result, { material })`: the layout as a frame of beams with its load cases, for `sizing` to pick each
18
+ member from tubes that can be bought. `layoutJoints(result, { material })`: each joint as a problem file for the
19
+ voxel optimiser, the members as stubs carrying their forces in each case (the layout's, or the sized frame's).
20
+ - Refused by name (`fea.layout.input`, `node`, `support`, `load`, `strength`) before any maths, and
21
+ `fea.layout.unstable` when the programme has no answer. A load may name its node by number, as nodes given as a list
22
+ are named by place.
23
+ - The interior point method stops at a relative error of 1e-9 in equilibrium, the members' limits and the gap. Its
24
+ factorisation drops a pivot only when it has cancelled to a 1e-13 share of its own row's diagonal, not of the
25
+ largest: near the optimum the diagonal spans many orders, and the old test also dropped the sound small pivots of
26
+ lightly loaded joints, so equilibrium stalled short of 1e-9 and some solvable problems in space with several cases
27
+ were refused as unstable. As a last guard, a run that still stalls keeps its best point and answers if that point
28
+ is within 1e-6.
29
+
5
30
  ## 0.2.11: frames held, sized and their modes said (Frames 3)
6
31
 
7
32
  ### Added
package/README.md CHANGED
@@ -5,6 +5,8 @@ in their own plane (2D, plane stress, square cells) and solid parts (3D, cubes).
5
5
  and Node alike. Units are millimetres and newtons, so Young's modulus is in MPa and movement in mm.
6
6
 
7
7
  Frames of beams joined at nodes have their own solver, `@rulecad/fea/frame`: see [Frames of beams](#frames-of-beams).
8
+ Which members such a frame should have, and how thick, is found by `@rulecad/fea/layout`: see
9
+ [Frame layout](#frame-layout-which-members-and-how-thick).
8
10
 
9
11
  ```js
10
12
  import { grid, analyse } from '@rulecad/fea';
@@ -277,6 +279,106 @@ false and the result is the design that came nearest, with `worst` saying which
277
279
  member's face by its width keep their drawn offsets. The search is over the list given; it does not invent a section.
278
280
 
279
281
 
282
+ ## Frame layout: which members, and how thick
283
+
284
+ `@rulecad/fea/layout` designs a frame of tubes or bars from nothing but its loads and supports: given a cloud of
285
+ candidate nodes, it chooses which members to put between them, and how thick each must be, so the frame carries
286
+ every load case to its supports with the least material. A bike frame, a roll cage or a space frame is mostly empty,
287
+ so it is better designed as members joined at nodes than as millions of voxels. The members are pin-jointed and each
288
+ is as thick as its worst case's force over the strength (fully stressed); the frame that comes out is then sized
289
+ from tubes that can be bought (`layoutFrame` and `sizing`), and its joints shaped by the voxel optimiser
290
+ (`layoutJoints`).
291
+
292
+ ```js
293
+ import { layout, layoutFrame, layoutJoints } from '@rulecad/fea/layout';
294
+ import { sizing } from '@rulecad/fea/frame';
295
+
296
+ const r = layout({
297
+ nodes: { A: [0, 300], B: [0, -300], C: [400, 0] }, // mm; or a grid: { from, to, pitch }, or both
298
+ supports: { A: 'pinned', B: 'pinned' }, // or { x: true, y: true, z: false }
299
+ loads: [{ node: 'C', force: [0, -1000] }], // N; or cases: [{ label, loads }, ...]
300
+ strength: 100, // MPa; or { tension, compression }
301
+ });
302
+ r.volume; // 8333.3 mm³: two bars of 8.33 mm², 833 N each
303
+ r.members[0]; // { id: 'B-C', a: 'B', b: 'C', length: 500, area: 8.333, forces: [-833.3], kind: 'compression' }
304
+ const f = layoutFrame(r, { material: { E: 200000, nu: 0.3, density: 7.85, strength: 275 } });
305
+ const sized = sizing(f.model, { groups: { bars: f.members }, choices: tubes, cases: f.cases, limits: { stress: { margin: 2 }, buckling: { factor: 2, euler: 1 } } });
306
+ const joints = layoutJoints(r, { material: 's275' }); // [{ node: 'C', members, problem }]: a problem file for each joint
307
+ ```
308
+
309
+ | Part of the problem | Shape | Notes |
310
+ |---|---|---|
311
+ | `nodes` | `{ name: [x, y] or [x, y, z] }` | Candidate nodes, mm (a list is named by place) |
312
+ | `grid` | `{ from, to, pitch }` | More candidates, every `pitch` mm across a box, named `"i,j"` or `"i,j,k"` by place; one within a hundredth of the pitch of a named node gives way to it |
313
+ | `supports` | `{ node: 'pinned' or { x, y, z } }` | Which movements are held at each |
314
+ | `loads` or `cases` | `[{ node, force }]` or `[{ label, loads }]` | One load case, or several, each carried alone with the same areas |
315
+ | `strength` | MPa, or `{ tension, compression }` | Each member's force over its area stays within it: give the material's strength over your margin |
316
+ | `density` | g/cm³ | For the mass, kg |
317
+ | `joint` | mm | A joint's cost as a length of member (0): above 0, fewer and longer members |
318
+ | `reach` | mm | The longest candidate member |
319
+ | `avoid` | `[{ at, r, through }]` | Balls (circles, flat) no node or member enters; with `through: true` members may pass and only nodes are kept out |
320
+ | `plane` | `true` or `false` | A flat layout in x and y; left out, flat when every node and load is at z = 0 |
321
+
322
+ Options: `keep` (members thinner than this share of the thickest are left out of `members`, 1e-4; the volume counts
323
+ them), `start` (each node's nearest candidates in the first programme: 8 flat, 18 in space), `add` (most members
324
+ added a round), `adding: false` (every candidate in one programme), `tolerance` (1e-5).
325
+
326
+ **What comes back.** `volume` (mm³), `mass` (kg, with a density), `members` (thickest first: area, each case's force,
327
+ tension positive, and `kind`), `nodes` (those the members meet at, with the loaded and supported ones), `candidates`
328
+ (the ground structure's members), `programme` (how many the last programme held), `rounds`, `strain` (the largest
329
+ virtual strain of any candidate over its limit: 1 at most, which proves no left-out member would lower the volume),
330
+ `left` (the volume share under `keep`) and `virtual` (each case's virtual displacements by node, the programme's
331
+ dual). With several cases the areas are unique but the forces in a case may not be (a member thicker than one case
332
+ needs can carry more or less in it): `members[].forces` is one set the strengths allow. For the forces the built frame
333
+ will carry, solve it (`layoutFrame`, then `frame().statics`) and give them to `layoutJoints`.
334
+
335
+ **Handing it on.** `layoutFrame(result, { material, section, ends })` is the layout as a frame model, each member a
336
+ solid round bar of its area (or `section`), joints `'rigid'` (welded, the default) or `'pinned'`, a flat layout held
337
+ out of its plane at its supports, and `cases` as `sizing` takes them. `layoutJoints(result, { material, diameters,
338
+ forces, stub, cell, volume, nodes })` gives each joint (every node where two members or more meet, or those named) as
339
+ a problem file in the form `cad optimise` reads: a space round the node, each member a stub `stub` mm long (twice the
340
+ widest diameter), the stub carrying the most held (the frame beyond it) and the others loaded with their forces in
341
+ each case, plus any outside load at the node. A flat layout's joints are flat problems as thick as the widest tube.
342
+
343
+ **How it works.** Every pair of candidate nodes is a member unless it passes through a third node (two shorter ones
344
+ do the same), is longer than `reach` or enters an avoided ball. The least volume is a linear programme in the areas
345
+ and the forces; it is solved by a primal-dual interior point method, the normal equations' members' rows eliminated
346
+ first so the dense matrix is only the equilibrium rows (free freedoms times cases). The first programme holds each
347
+ node's nearest candidates. Its dual is a virtual displacement field; any left-out member it would strain past its
348
+ limit would lower the volume, so the most strained are added and the programme solved again, until none is. The
349
+ answer is then the least over every candidate (the `strain` figure is the proof), while the programme holds a few
350
+ percent of them.
351
+
352
+ | What | Formula | Source |
353
+ |---|---|---|
354
+ | The least volume | Least `Σ (l_i + s) a_i` such that `B q_k = f_k` and `−σc a_i ≤ q_ik ≤ σt a_i` in every case k | Dorn, Gomory and Greenberg; Hemp (several cases); Parkes (the joint cost s) |
355
+ | Equilibrium | Member i from node a to b, unit direction e: column `−e` at a and `+e` at b, so `B q = f` with tension positive | Statics |
356
+ | Standard form | `q = p − n` with p and n ≥ 0, and a slack per member and case: `a_i σt = p_ik + (σt / σc) n_ik + s_ik` (forces scaled by the largest load, lengths by the longest candidate) | Linear programming |
357
+ | The solver | Primal-dual interior point, Mehrotra's predictor and corrector; a pivot that has cancelled to a 1e-13 share of its own row's diagonal is made huge, so its direction solves as 0 (tested against its own row, as the diagonal spans many orders near the optimum). It stops when equilibrium, the members' limits and the gap between the primal and dual values are each within 1e-9 relative; a run that rounding still stalls short of that takes its best point if within 1e-6 | Mehrotra; Nocedal and Wright, chapter 14; Zhang (LIPSOL) |
358
+ | Adding members | A left-out member would lower the volume if `Σ_k max(0, σt b_i·u_k, −σc b_i·u_k) > l_i + s`, u_k the dual of case k's equilibrium | Gilbert and Tyas |
359
+ | Members through a node | From each node, only the nearest node in each direction | Gilbert and Tyas |
360
+
361
+ **Tested** against hand calculations, each to rounding: two bars to two pins (8333.3 mm³, 833.3 N each), the same
362
+ weaker in compression (12500 mm³), a tripod in space (5625 mm³, 375 N a leg), two load cases sharing areas (3000 mm³,
363
+ not the 4000 of each alone); and against Michell's closed form for a couple carried between two circles (Michell
364
+ 1904: `V = 2 M ln(R / r) / σ`): never under it, 2.6% over with 16 nodes to a ring and 0.65% with 32, the excess
365
+ falling fourfold as the step halves (straight members where his spirals curve). Member adding gives the same volume
366
+ as every candidate in one programme, alone and with two cases. The 32-to-a-ring wheel (224 nodes, 23728
367
+ candidates) takes about half a second on a laptop; the bicycle frame example (`examples/bicycle-frame`, 61 nodes and 1242 candidates,
368
+ three cases) about 4 seconds.
369
+
370
+ **Limits.**
371
+
372
+ - Pin-jointed and plastic: each member is as thick as its force needs, with nothing for buckling or bending. Size the
373
+ result (`layoutFrame` and `sizing`), which checks both.
374
+ - The node positions are fixed: a finer grid gives a better layout, slowly (the dense matrix grows with the free
375
+ freedoms times the cases: a few thousand rows is the practical most).
376
+ - With several cases, the forces within a case may not be unique (above), and members of equal merit may share a
377
+ load: a joint cost (`joint`) settles on fewer.
378
+ - A flat layout's members may cross without meeting (a node is needed where they cross to join them).
379
+ - The joints' problems carry the members' forces as point loads at the stubs' ends, held at one stub: the joint's own
380
+ stiffness against the frame's is not modelled.
381
+
280
382
  ## Sources
281
383
 
282
384
  - Amir, Aage, Lazarov (2014). On multigrid-CG for efficient topology optimization. *Structural and Multidisciplinary
@@ -288,10 +390,21 @@ member's face by its width keep their drawn offsets. The search is over the list
288
390
  - Cook, Malkus, Plesha, Witt (2002). *Concepts and Applications of Finite Element Analysis*, 4th ed. Wiley.
289
391
  - Cuthill, McKee (1969). Reducing the bandwidth of sparse symmetric matrices. *Proceedings of the 24th National
290
392
  Conference of the ACM*, 157–172.
393
+ - Dorn, Gomory, Greenberg (1964). Automatic design of optimal structures. *Journal de Mécanique* 3, 25–52.
291
394
  - Friedman, Kosmatka (1993). An improved two-node Timoshenko beam finite element. *Computers and Structures* 47,
292
395
  473–481.
396
+ - Gilbert, Tyas (2003). Layout optimization of large-scale pin-jointed frames. *Engineering Computations* 20,
397
+ 1044–1064.
293
398
  - Guyan (1965). Reduction of stiffness and mass matrices. *AIAA Journal* 3, 380.
399
+ - Hemp (1973). *Optimum Structures*. Clarendon Press, Oxford.
294
400
  - McGuire, Gallagher, Ziemian (2000). *Matrix Structural Analysis*, 2nd ed. Wiley.
401
+ - Mehrotra (1992). On the implementation of a primal-dual interior point method. *SIAM Journal on Optimization* 2,
402
+ 575–601.
403
+ - Michell (1904). The limits of economy of material in frame-structures. *Philosophical Magazine* 8, 589–597.
404
+ - Nocedal, Wright (2006). *Numerical Optimization*, 2nd ed. Springer.
405
+ - Parkes (1975). Joints in optimum frameworks. *International Journal of Solids and Structures* 11, 1017–1022.
295
406
  - Przemieniecki (1968). *Theory of Matrix Structural Analysis*. McGraw-Hill.
296
407
  - Timoshenko, Gere (1961). *Theory of Elastic Stability*, 2nd ed. McGraw-Hill.
297
408
  - Young, Budynas (2002). *Roark's Formulas for Stress and Strain*, 7th ed. McGraw-Hill.
409
+ - Zhang (1998). Solving large-scale linear programs by interior-point methods under the MATLAB environment.
410
+ *Optimization Methods and Software* 10, 1–31.
package/layout.d.mts ADDED
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Candidate nodes every `pitch` mm across a box, both ends included, by name "i,j" (or "i,j,k"): their places along
3
+ * x, y and z.
4
+ * @param {{ from: number[], to: number[], pitch: number }} g
5
+ * @returns {Record<string, Vec3>}
6
+ */
7
+ export function nodeGrid(g: {
8
+ from: number[];
9
+ to: number[];
10
+ pitch: number;
11
+ }): Record<string, Vec3>;
12
+ /**
13
+ * The candidate members between nodes: every pair, less those that pass through a third node (the same as two
14
+ * shorter ones there, and so never needed: Gilbert and Tyas 2003), those longer than `reach` and those that enter
15
+ * an `avoid` ball (but for one members may pass `through`).
16
+ * @param {Record<string, number[]> | number[][]} nodes mm
17
+ * @param {{ reach?: number, avoid?: LayoutAvoid[] }} [o]
18
+ * @returns {{ ids: string[], at: Float64Array, members: { a: number, b: number, length: number }[] }} at: x, y, z of
19
+ * each node in turn; members by node index
20
+ */
21
+ export function groundStructure(nodes: Record<string, number[]> | number[][], o?: {
22
+ reach?: number;
23
+ avoid?: LayoutAvoid[];
24
+ }): {
25
+ ids: string[];
26
+ at: Float64Array;
27
+ members: {
28
+ a: number;
29
+ b: number;
30
+ length: number;
31
+ }[];
32
+ };
33
+ /**
34
+ * The least-volume pin-jointed frame that carries the loads to the supports, chosen from every member between the
35
+ * candidate nodes (the ground structure), with each member's area. Proven least over every candidate: members are
36
+ * added to the programme until no left-out one would lower the volume. Refused by name before any maths: unknown
37
+ * keys, a node out of place or twice at one spot, a support or load at no node, no strength above 0, a load where
38
+ * nothing can carry it; and after, a frame the candidates cannot make stand (`fea.layout.unstable`).
39
+ * @param {LayoutProblem} problem
40
+ * @param {{ keep?: number, start?: number, add?: number, tolerance?: number, adding?: boolean }} [o] keep: members
41
+ * thinner than this share of the thickest are left out of `members` (1e-4; the volume counts them); start: each
42
+ * node's nearest candidates in the first programme (8 flat, 18 in space); add: most members added a round (a tenth
43
+ * of the programme's, at least 100); adding: false puts every candidate in the one programme
44
+ * @returns {{ volume: number, mass: number | null, members: LayoutMember[], nodes: Record<string, Vec3>,
45
+ * cases: string[], plane: boolean, candidates: number, programme: number, rounds: number, strain: number, left: number,
46
+ * virtual: Record<string, number[]>[], strength: { tension: number, compression: number }, joint: number,
47
+ * supports: Record<string, string>, loads: { label: string, loads: LayoutLoad[] }[] }}
48
+ * volume mm³ (the members' l a, every member counted); mass kg with a density; members the kept ones, thickest
49
+ * first; nodes the ones they meet at, with the loaded and supported ones; candidates how many members the ground
50
+ * structure has, programme how many the last programme held, rounds how many programmes were solved; strain the
51
+ * largest virtual strain of any candidate over its limit, 1 at most (to the tolerance) when the layout is the least
52
+ * over every candidate; left the volume share of the members under `keep`; virtual each case's virtual
53
+ * displacements by node, mm (the programme's dual), scaled so a member at its tension limit in one case stretches
54
+ * by its own length
55
+ */
56
+ export function layout(problem: LayoutProblem, o?: {
57
+ keep?: number;
58
+ start?: number;
59
+ add?: number;
60
+ tolerance?: number;
61
+ adding?: boolean;
62
+ }): {
63
+ volume: number;
64
+ mass: number | null;
65
+ members: LayoutMember[];
66
+ nodes: Record<string, Vec3>;
67
+ cases: string[];
68
+ plane: boolean;
69
+ candidates: number;
70
+ programme: number;
71
+ rounds: number;
72
+ strain: number;
73
+ left: number;
74
+ virtual: Record<string, number[]>[];
75
+ strength: {
76
+ tension: number;
77
+ compression: number;
78
+ };
79
+ joint: number;
80
+ supports: Record<string, string>;
81
+ loads: {
82
+ label: string;
83
+ loads: LayoutLoad[];
84
+ }[];
85
+ };
86
+ /**
87
+ * A layout as a frame of beams (@rulecad/fea/frame's model), with its load cases, ready for `sizing` to pick a tube
88
+ * for each member that can be bought (stress and buckling checked, with bending at stiff joints). Each member is a
89
+ * solid round bar of its layout area until sized (or the `section` given). A flat layout is held out of its plane at
90
+ * its supports (z and the two rotations out of plane) and any other way nothing resists is held while its loads do
91
+ * not push it (`loose: 'hold'`).
92
+ * @param {ReturnType<typeof layout>} result
93
+ * @param {{ material: { E: number, nu?: number, G?: number, density?: number, strength?: number }, section?: object, ends?: 'rigid' | 'pinned' }} o
94
+ * material: the members' (E in MPa); section: one section for every member in place of the round bars; ends:
95
+ * 'rigid' (welded, brazed or bonded: the default) or 'pinned' (each member's ends free to turn: one 'ball', one 'pinned')
96
+ * @returns {{ model: object, cases: { label: string, loads: { node: string, force: Vec3 }[] }[], members: string[] }}
97
+ * model: nodes, elements (ids as the layout's members), supports, the first case's loads and loose: 'hold';
98
+ * cases: every case as sizing takes it; members: the element ids
99
+ */
100
+ export function layoutFrame(result: ReturnType<typeof layout>, o?: {
101
+ material: {
102
+ E: number;
103
+ nu?: number;
104
+ G?: number;
105
+ density?: number;
106
+ strength?: number;
107
+ };
108
+ section?: object;
109
+ ends?: "rigid" | "pinned";
110
+ }): {
111
+ model: object;
112
+ cases: {
113
+ label: string;
114
+ loads: {
115
+ node: string;
116
+ force: Vec3;
117
+ }[];
118
+ }[];
119
+ members: string[];
120
+ };
121
+ /**
122
+ * Each joint of a layout as a problem of its own for the voxel optimiser (cad optimise, @rulecad/topopt), in the
123
+ * problem file's form: the members meeting there as stubs, each member's force in every case as a load on its stub's
124
+ * end, the outside load at the node, and the stub carrying the most held (the frame beyond it). A lug, a dropout or
125
+ * a bracket is then shaped for the forces the layout found. Flat layouts give flat problems, `thickness` the widest
126
+ * member's diameter; the rest give 3D ones. Each problem is centred on its node; `at` says where that is.
127
+ * @param {ReturnType<typeof layout>} result
128
+ * @param {{ material: string, diameters?: Record<string, number>, forces?: Record<string, number[]>, stub?: number, cell?: number, volume?: number, nodes?: string[] }} o
129
+ * material: the rule set the joint is made of (pla, al6061, ...); diameters: each member's outside diameter by id
130
+ * (a solid bar of its area if left out: give the sized tubes'); forces: each member's force in each case, N,
131
+ * tension positive (the layout's own if left out: one set the strengths allow, where a frame with several cases may
132
+ * have many; give the sized frame's, solved, for the forces it will carry); stub: how far each stub reaches from the node, mm
133
+ * (twice the widest diameter); cell: the grid's cell (a quarter of the narrowest diameter); volume: share of the
134
+ * space to fill (0.3); nodes: which joints (every node where two members or more meet)
135
+ * @returns {{ node: string, at: Vec3, members: { id: string, to: string, direction: number[], forces: number[], diameter: number }[], problem: object }[]}
136
+ */
137
+ export function layoutJoints(result: ReturnType<typeof layout>, o?: {
138
+ material: string;
139
+ diameters?: Record<string, number>;
140
+ forces?: Record<string, number[]>;
141
+ stub?: number;
142
+ cell?: number;
143
+ volume?: number;
144
+ nodes?: string[];
145
+ }): {
146
+ node: string;
147
+ at: Vec3;
148
+ members: {
149
+ id: string;
150
+ to: string;
151
+ direction: number[];
152
+ forces: number[];
153
+ diameter: number;
154
+ }[];
155
+ problem: object;
156
+ }[];
157
+ export type Vec3 = [number, number, number];
158
+ /**
159
+ * a ball (a circle in a flat layout) no node or member may enter: centre, mm, and radius; through: members may pass through it and only nodes are kept out (a wheel that stays straddle)
160
+ */
161
+ export type LayoutAvoid = {
162
+ at: number[];
163
+ r: number;
164
+ through?: boolean;
165
+ };
166
+ /**
167
+ * a force, N, at a node: [x, y, z] (or [x, y] in a flat layout)
168
+ */
169
+ export type LayoutLoad = {
170
+ node: string | number;
171
+ force: number[];
172
+ };
173
+ export type LayoutProblem = {
174
+ /**
175
+ * the candidate nodes, mm, by name (or a list, named by place)
176
+ */
177
+ nodes?: Record<string, number[]> | number[][];
178
+ /**
179
+ * more candidate nodes, every `pitch` mm across a
180
+ * box, named "x,y" or "x,y,z" by their place in it; one within a hundredth of the pitch of a named node gives way to it
181
+ */
182
+ grid?: {
183
+ from: number[];
184
+ to: number[];
185
+ pitch: number;
186
+ };
187
+ /**
188
+ * by node: 'pinned' holds
189
+ * every movement, or say which
190
+ */
191
+ supports: Record<string, "pinned" | {
192
+ x?: boolean;
193
+ y?: boolean;
194
+ z?: boolean;
195
+ }>;
196
+ /**
197
+ * the one load case
198
+ */
199
+ loads?: LayoutLoad[];
200
+ /**
201
+ * several load cases, each carried alone, sharing the areas
202
+ */
203
+ cases?: {
204
+ label?: string;
205
+ loads: LayoutLoad[];
206
+ }[];
207
+ /**
208
+ * MPa: one for both, or each
209
+ */
210
+ strength: number | {
211
+ tension: number;
212
+ compression: number;
213
+ };
214
+ /**
215
+ * g/cm³, for the mass
216
+ */
217
+ density?: number;
218
+ /**
219
+ * a joint's cost as a length of member, mm (0): above 0, fewer and longer members
220
+ */
221
+ joint?: number;
222
+ /**
223
+ * the longest candidate member, mm (no limit)
224
+ */
225
+ reach?: number;
226
+ /**
227
+ * balls no node or member may enter
228
+ */
229
+ avoid?: LayoutAvoid[];
230
+ /**
231
+ * a flat layout in x and y (left out: flat when every node and load is at z = 0)
232
+ */
233
+ plane?: boolean;
234
+ };
235
+ export type LayoutMember = {
236
+ /**
237
+ * "a-b"
238
+ */
239
+ id: string;
240
+ a: string;
241
+ /**
242
+ * its nodes
243
+ */
244
+ b: string;
245
+ /**
246
+ * mm
247
+ */
248
+ length: number;
249
+ /**
250
+ * mm²: its worst case's force over the strength
251
+ */
252
+ area: number;
253
+ /**
254
+ * N in each case, tension positive
255
+ */
256
+ forces: number[];
257
+ kind: "tension" | "compression" | "both";
258
+ };
package/layout.mjs ADDED
@@ -0,0 +1,536 @@
1
+ // Layout optimisation of pin-jointed frames: which members to keep between a cloud of candidate nodes, and how thick,
2
+ // so the frame carries its loads to its supports with the least material. The plastic ground structure method:
3
+ // every pair of nodes is a candidate member (Dorn, Gomory and Greenberg 1964), the least volume is a linear
4
+ // programme, and members are added to it a few at a time where the solution's virtual strains say they would help,
5
+ // until none would (Gilbert and Tyas 2003). The answer is then the least volume over every candidate, proven so,
6
+ // while the programme only ever holds a small share of them. Several load cases share one set of areas (each member
7
+ // as thick as its worst case needs). Plain numbers in typed arrays, no dependencies.
8
+ //
9
+ // Units: millimetres, newtons, MPa (N/mm²), so areas are mm² and volumes mm³; densities in g/cm³, masses in kg.
10
+ //
11
+ // The programme, for members i of length l_i and load cases k with forces f_k on the free freedoms:
12
+ // least Σ (l_i + s) a_i such that B q_k = f_k and −σc a_i ≤ q_ik ≤ σt a_i for every case,
13
+ // where B is the equilibrium matrix (a member's column is its unit direction at its two nodes), q_ik the member's
14
+ // force (tension positive), a_i its area, σt and σc the strengths in tension and compression and s a joint's cost
15
+ // as a length (Parkes 1975; 0 by default). It is solved in the standard form, each force split q = p − n with p and
16
+ // n ≥ 0 and a slack per member and case, by a primal-dual interior point method with Mehrotra's predictor and
17
+ // corrector (Nocedal and Wright 2006, chapter 14). The dual's equilibrium rows are the nodes' virtual displacements
18
+ // u_k; a candidate member not in the programme would lower the volume exactly when
19
+ // Σ_k max(0, σt bᵢ·u_k, −σc bᵢ·u_k) > l_i + s,
20
+ // its virtual strain past the limit, which is the test members are added by.
21
+
22
+ /** @typedef {[number, number, number]} Vec3 */
23
+ /** @typedef {{ at: number[], r: number, through?: boolean }} LayoutAvoid a ball (a circle in a flat layout) no node or member may enter: centre, mm, and radius; through: members may pass through it and only nodes are kept out (a wheel that stays straddle) */
24
+ /** @typedef {{ node: string | number, force: number[] }} LayoutLoad a force, N, at a node: [x, y, z] (or [x, y] in a flat layout) */
25
+ /**
26
+ * @typedef {object} LayoutProblem
27
+ * @property {Record<string, number[]> | number[][]} [nodes] the candidate nodes, mm, by name (or a list, named by place)
28
+ * @property {{ from: number[], to: number[], pitch: number }} [grid] more candidate nodes, every `pitch` mm across a
29
+ * box, named "x,y" or "x,y,z" by their place in it; one within a hundredth of the pitch of a named node gives way to it
30
+ * @property {Record<string, 'pinned' | { x?: boolean, y?: boolean, z?: boolean }>} supports by node: 'pinned' holds
31
+ * every movement, or say which
32
+ * @property {LayoutLoad[]} [loads] the one load case
33
+ * @property {{ label?: string, loads: LayoutLoad[] }[]} [cases] several load cases, each carried alone, sharing the areas
34
+ * @property {number | { tension: number, compression: number }} strength MPa: one for both, or each
35
+ * @property {number} [density] g/cm³, for the mass
36
+ * @property {number} [joint] a joint's cost as a length of member, mm (0): above 0, fewer and longer members
37
+ * @property {number} [reach] the longest candidate member, mm (no limit)
38
+ * @property {LayoutAvoid[]} [avoid] balls no node or member may enter
39
+ * @property {boolean} [plane] a flat layout in x and y (left out: flat when every node and load is at z = 0)
40
+ */
41
+ /**
42
+ * @typedef {object} LayoutMember
43
+ * @property {string} id "a-b"
44
+ * @property {string} a @property {string} b its nodes
45
+ * @property {number} length mm
46
+ * @property {number} area mm²: its worst case's force over the strength
47
+ * @property {number[]} forces N in each case, tension positive
48
+ * @property {'tension' | 'compression' | 'both'} kind
49
+ */
50
+
51
+ const DIMS = ['x', 'y', 'z'];
52
+ const KEYS = ['nodes', 'grid', 'supports', 'loads', 'cases', 'strength', 'density', 'joint', 'reach', 'avoid', 'plane'];
53
+ const OPTIONS = ['keep', 'start', 'add', 'tolerance', 'adding'];
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));
57
+ const isPoint = (v) => Array.isArray(v) && (v.length === 2 || v.length === 3) && v.every(Number.isFinite);
58
+ const round = (v, d = 6) => Number(v.toPrecision(d));
59
+
60
+ // ---- candidate nodes and members ----
61
+
62
+ /**
63
+ * Candidate nodes every `pitch` mm across a box, both ends included, by name "i,j" (or "i,j,k"): their places along
64
+ * x, y and z.
65
+ * @param {{ from: number[], to: number[], pitch: number }} g
66
+ * @returns {Record<string, Vec3>}
67
+ */
68
+ 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)`);
73
+ const out = {};
74
+ 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]);
77
+ };
78
+ walk(0, [], []);
79
+ return out;
80
+ }
81
+
82
+ // the segment from p to q passes within r of c (strictly inside the ball)
83
+ 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;
85
+ const t = Math.min(1, Math.max(0, dd ? (w[0] * d[0] + w[1] * d[1] + w[2] * d[2]) / dd : 0));
86
+ return Math.hypot(w[0] - t * d[0], w[1] - t * d[1], w[2] - t * d[2]) < r * (1 - 1e-9);
87
+ };
88
+
89
+ /**
90
+ * The candidate members between nodes: every pair, less those that pass through a third node (the same as two
91
+ * shorter ones there, and so never needed: Gilbert and Tyas 2003), those longer than `reach` and those that enter
92
+ * an `avoid` ball (but for one members may pass `through`).
93
+ * @param {Record<string, number[]> | number[][]} nodes mm
94
+ * @param {{ reach?: number, avoid?: LayoutAvoid[] }} [o]
95
+ * @returns {{ ids: string[], at: Float64Array, members: { a: number, b: number, length: number }[] }} at: x, y, z of
96
+ * each node in turn; members by node index
97
+ */
98
+ 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 }));
102
+ 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); }
104
+ const members = [];
105
+ for (let a = 0; a < n; a++) {
106
+ // from a, the nearest node in each direction: a member to any further one there passes through it
107
+ const nearest = new Map();
108
+ for (let b = 0; b < n; b++) {
109
+ 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]] });
112
+ const key = d.map((v) => Math.round((v / L) * 1e6)).join(',');
113
+ const was = nearest.get(key);
114
+ if (!was || L < was.L) nearest.set(key, { b, L });
115
+ }
116
+ for (const { b, L } of nearest.values()) {
117
+ 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]];
119
+ if (avoid.some((v) => crosses(p, q, v.c, v.r))) continue;
120
+ members.push({ a, b, length: L });
121
+ }
122
+ }
123
+ return { ids, at, members };
124
+ }
125
+
126
+ // ---- the linear programme: least cᵀx with A x = b, x ≥ 0 ----
127
+
128
+ // A is given by columns. Its rows are global (the equilibrium rows) or local: each local row belongs to a small block
129
+ // (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
+ // by eliminating the blocks first: a dense Schur complement over the global rows, and small blocks.
131
+ 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;
133
+ // 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); } }
137
+ 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; };
141
+ // factorise A D Aᵀ, returning its solve
142
+ 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));
144
+ for (let j = 0; j < N; j++) {
145
+ const d = D[j], k = colBlock[j], s0 = start[j], s1 = start[j + 1];
146
+ for (let e = s0; e < s1; e++) {
147
+ const r = rows[e], v = d * vals[e];
148
+ for (let f = s0; f < s1; f++) {
149
+ 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];
152
+ else if (r < G) C[k][touched[k].get(r) * blocks[k].length + local[q - G]] += v * vals[f];
153
+ }
154
+ }
155
+ }
156
+ // 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));
158
+ 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; }));
161
+ });
162
+ const L = cholesky(S, G);
163
+ return (rhs) => {
164
+ 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);
167
+ y.set(yG);
168
+ 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; }
172
+ });
173
+ return y;
174
+ };
175
+ };
176
+ const norm = (v) => Math.sqrt(v.reduce((t, x) => t + x * x, 0)), nb = norm(b), nc = norm(cost);
177
+ // 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; };
186
+ let best = { x, y, z, value: NaN, iterations: 0, err: Infinity, at: 0 };
187
+ 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]; }
191
+ for (let i = 0; i < R; i++) by += b[i] * y[i];
192
+ const mu = gap / N;
193
+ // the worst of the three relative errors: equilibrium, the members' limits, and the gap between the two values
194
+ const err = Math.max(norm(rp) / (1 + nb), norm(rd) / (1 + nc), Math.abs(cx - by) / (1 + Math.abs(cx)));
195
+ if (err <= tol) return { x, y, z, value: cx, iterations: it, ok: true };
196
+ if (!(cx < 1e14) || !Number.isFinite(mu)) break;
197
+ if (err < best.err) best = { x: x.slice(), y: y.slice(), z: z.slice(), value: cx, iterations: it, err, at: it };
198
+ 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);
200
+ const direction = (rc) => {
201
+ const t = new Float64Array(N);
202
+ 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]; }
206
+ return { dx, dy, dz };
207
+ };
208
+ const aff = direction(Float64Array.from(x, (v, j) => -v * z[j]));
209
+ const ap = stepTo(x, aff.dx), ad = stepTo(z, aff.dz);
210
+ let muAff = 0;
211
+ for (let j = 0; j < N; j++) muAff += (x[j] + ap * aff.dx[j]) * (z[j] + ad * aff.dz[j]);
212
+ const sigma = (muAff / N / mu) ** 3;
213
+ 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]; }
216
+ for (let i = 0; i < R; i++) y[i] += sd * dy[i];
217
+ }
218
+ // else the best point, if it met a looser test (a millionth): its value is good to about that share
219
+ return { x: best.x, y: best.y, z: best.z, value: best.value, iterations: best.iterations, ok: best.err <= loose };
220
+ }
221
+ // a small symmetric positive definite matrix's inverse (m × m, row by row)
222
+ 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]; }
225
+ return out;
226
+ }
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; };
228
+ // Cholesky of a dense symmetric matrix from its lower triangle, in place. A pivot that is nothing beside its own
229
+ // row's diagonal (a row no column reaches, or one that depends on the rows before it, so all but rounding cancelled)
230
+ // is made huge, so that direction is solved as 0 (as Zhang's LIPSOL does). The test is against the row's own
231
+ // diagonal, not the matrix's largest: near the optimum the diagonal spans many orders (a lightly loaded joint beside
232
+ // a main member), and a small but sound pivot dropped there leaves its equilibrium error unmended for good.
233
+ function cholesky(S, n) {
234
+ for (let j = 0; j < n; j++) {
235
+ const rj = j * n;
236
+ let d = S[rj + j];
237
+ const own = d;
238
+ 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; }
240
+ const p = Math.sqrt(d);
241
+ S[rj + j] = p;
242
+ for (let i = j + 1; i < n; i++) {
243
+ const ri = i * n;
244
+ let s = S[ri + j];
245
+ for (let k = 0; k < j; k++) s -= S[ri + k] * S[rj + k];
246
+ S[ri + j] = s / p;
247
+ }
248
+ }
249
+ return S;
250
+ }
251
+ function cholSolve(L, b, n) {
252
+ 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]; }
255
+ return y;
256
+ }
257
+
258
+ // ---- the layout ----
259
+
260
+ /**
261
+ * The least-volume pin-jointed frame that carries the loads to the supports, chosen from every member between the
262
+ * candidate nodes (the ground structure), with each member's area. Proven least over every candidate: members are
263
+ * added to the programme until no left-out one would lower the volume. Refused by name before any maths: unknown
264
+ * keys, a node out of place or twice at one spot, a support or load at no node, no strength above 0, a load where
265
+ * nothing can carry it; and after, a frame the candidates cannot make stand (`fea.layout.unstable`).
266
+ * @param {LayoutProblem} problem
267
+ * @param {{ keep?: number, start?: number, add?: number, tolerance?: number, adding?: boolean }} [o] keep: members
268
+ * thinner than this share of the thickest are left out of `members` (1e-4; the volume counts them); start: each
269
+ * node's nearest candidates in the first programme (8 flat, 18 in space); add: most members added a round (a tenth
270
+ * of the programme's, at least 100); adding: false puts every candidate in the one programme
271
+ * @returns {{ volume: number, mass: number | null, members: LayoutMember[], nodes: Record<string, Vec3>,
272
+ * cases: string[], plane: boolean, candidates: number, programme: number, rounds: number, strain: number, left: number,
273
+ * virtual: Record<string, number[]>[], strength: { tension: number, compression: number }, joint: number,
274
+ * supports: Record<string, string>, loads: { label: string, loads: LayoutLoad[] }[] }}
275
+ * volume mm³ (the members' l a, every member counted); mass kg with a density; members the kept ones, thickest
276
+ * first; nodes the ones they meet at, with the loaded and supported ones; candidates how many members the ground
277
+ * structure has, programme how many the last programme held, rounds how many programmes were solved; strain the
278
+ * largest virtual strain of any candidate over its limit, 1 at most (to the tolerance) when the layout is the least
279
+ * over every candidate; left the volume share of the members under `keep`; virtual each case's virtual
280
+ * displacements by node, mm (the programme's dual), scaled so a member at its tension limit in one case stretches
281
+ * by its own length
282
+ */
283
+ 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(', ')}`);
287
+ // 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)})`);
294
+ // 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 });
298
+ const avoid = problem.avoid ?? [];
299
+ 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));
302
+ // 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 });
304
+ const nodes = /** @type {Record<string, number[]>} */ ({ ...named });
305
+ 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;
308
+ }
309
+ // 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');
311
+ for (const [id, s] of Object.entries(problem.supports)) {
312
+ 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 });
314
+ }
315
+ 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 }];
317
+ if (!cases.length) refuse('load', 'cases is a list of { label, loads }: at least one');
318
+ 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 }`);
320
+ 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 });
323
+ }
324
+ }
325
+ 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)})`);
327
+ 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');
329
+ const dim = plane ? 2 : 3;
330
+
331
+ // 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]));
333
+ 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;
335
+ const row = new Int32Array(dim * n).fill(-1);
336
+ let free = 0;
337
+ 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
+ });
343
+ const F0 = Math.max(...forces.map((f) => Math.max(0, ...Array.from(f, Math.abs))));
344
+ 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;
348
+ // 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; });
351
+ // 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
+ const strainOf = (i, u) => {
353
+ const c = cand[i];
354
+ let s = 0;
355
+ for (let k = 0; k < K; k++) {
356
+ 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)); }
358
+ s += Math.max(0, e, -e / rho);
359
+ }
360
+ return s / cost[i];
361
+ };
362
+
363
+ // one programme over the members in `act`
364
+ 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 = [];
367
+ 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; };
369
+ 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
378
+ });
379
+ 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 });
382
+ const u = Array.from({ length: K }, (_, k) => r.y.subarray(k * free, (k + 1) * free));
383
+ return { ...r, u, M };
384
+ };
385
+ // the first programme: each node's nearest candidates; then members added where they would help
386
+ const byNode = Array.from({ length: n }, () => []);
387
+ cand.forEach((c, i) => { byNode[c.a].push(i); byNode[c.b].push(i); });
388
+ for (const list of byNode) list.sort((p, q) => cand[p].length - cand[q].length);
389
+ 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;
391
+ const adding = o.adding !== false;
392
+ for (;;) {
393
+ act = adding ? [...new Set(byNode.flatMap((list) => list.slice(0, first)))].sort((p, q) => p - q) : cand.map((_, i) => i);
394
+ // a loaded freedom no member reaches cannot be carried
395
+ 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 });
400
+ first = Math.min(2 * first, n);
401
+ }
402
+ for (const most = o.add ?? 0; adding;) {
403
+ const inside = new Uint8Array(m);
404
+ for (const i of act) inside[i] = 1;
405
+ 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]); }
407
+ if (!over.length) break;
408
+ over.sort((p, q) => q[1] - p[1]);
409
+ const take = most || Math.max(100, Math.ceil(act.length / 10));
410
+ 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 });
413
+ }
414
+
415
+ // the proof: no candidate's virtual strain is past its limit (1 at the limit)
416
+ let strain = 0;
417
+ for (let i = 0; i < m; i++) strain = Math.max(strain, strainOf(i, r.u));
418
+ // the answer, back in mm², N and mm³
419
+ const scaleA = F0 / strength.tension;
420
+ let volume = 0, amax = 0;
421
+ 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);
424
+ return { i, area, f };
425
+ });
426
+ 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)))]);
432
+ const pos = (id) => /** @type {Vec3} */ (Array.from(at.subarray(3 * index.get(id), 3 * index.get(id) + 3)));
433
+ // the virtual displacements, mm, scaled so a member at its tension limit stretches by its own length (a strain of
434
+ // 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 })) };
438
+ }
439
+
440
+ // ---- handing the layout on: a frame to size, and joints to optimise ----
441
+
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; };
443
+ const vec3 = (f) => /** @type {Vec3} */ ([f[0] ?? 0, f[1] ?? 0, f[2] ?? 0]);
444
+
445
+ /**
446
+ * A layout as a frame of beams (@rulecad/fea/frame's model), with its load cases, ready for `sizing` to pick a tube
447
+ * for each member that can be bought (stress and buckling checked, with bending at stiff joints). Each member is a
448
+ * solid round bar of its layout area until sized (or the `section` given). A flat layout is held out of its plane at
449
+ * its supports (z and the two rotations out of plane) and any other way nothing resists is held while its loads do
450
+ * not push it (`loose: 'hold'`).
451
+ * @param {ReturnType<typeof layout>} result
452
+ * @param {{ material: { E: number, nu?: number, G?: number, density?: number, strength?: number }, section?: object, ends?: 'rigid' | 'pinned' }} o
453
+ * material: the members' (E in MPa); section: one section for every member in place of the round bars; ends:
454
+ * 'rigid' (welded, brazed or bonded: the default) or 'pinned' (each member's ends free to turn: one 'ball', one 'pinned')
455
+ * @returns {{ model: object, cases: { label: string, loads: { node: string, force: Vec3 }[] }[], members: string[] }}
456
+ * model: nodes, elements (ids as the layout's members), supports, the first case's loads and loose: 'hold';
457
+ * cases: every case as sizing takes it; members: the element ids
458
+ */
459
+ export function layoutFrame(result, o = {}) {
460
+ 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 }; };
464
+ 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];
470
+ }));
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) };
473
+ }
474
+
475
+ /**
476
+ * Each joint of a layout as a problem of its own for the voxel optimiser (cad optimise, @rulecad/topopt), in the
477
+ * problem file's form: the members meeting there as stubs, each member's force in every case as a load on its stub's
478
+ * end, the outside load at the node, and the stub carrying the most held (the frame beyond it). A lug, a dropout or
479
+ * a bracket is then shaped for the forces the layout found. Flat layouts give flat problems, `thickness` the widest
480
+ * member's diameter; the rest give 3D ones. Each problem is centred on its node; `at` says where that is.
481
+ * @param {ReturnType<typeof layout>} result
482
+ * @param {{ material: string, diameters?: Record<string, number>, forces?: Record<string, number[]>, stub?: number, cell?: number, volume?: number, nodes?: string[] }} o
483
+ * material: the rule set the joint is made of (pla, al6061, ...); diameters: each member's outside diameter by id
484
+ * (a solid bar of its area if left out: give the sized tubes'); forces: each member's force in each case, N,
485
+ * tension positive (the layout's own if left out: one set the strengths allow, where a frame with several cases may
486
+ * have many; give the sized frame's, solved, for the forces it will carry); stub: how far each stub reaches from the node, mm
487
+ * (twice the widest diameter); cell: the grid's cell (a quarter of the narrowest diameter); volume: share of the
488
+ * space to fill (0.3); nodes: which joints (every node where two members or more meet)
489
+ * @returns {{ node: string, at: Vec3, members: { id: string, to: string, direction: number[], forces: number[], diameter: number }[], problem: object }[]}
490
+ */
491
+ export function layoutJoints(result, o = {}) {
492
+ 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));
502
+ };
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`);
504
+ 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 }); }
506
+ 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);
509
+ return which.map((id) => {
510
+ const p = r.nodes[id], list = meets.get(id);
511
+ 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)) };
514
+ });
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));
517
+ // 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]);
519
+ const loads = [];
520
+ 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' });
523
+ });
524
+ const problem = {
525
+ title: `Joint ${id} of a frame layout`,
526
+ 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,
528
+ ...(dim === 2 ? { thickness: fig(widest) } : {}),
529
+ space: { at: Array(dim).fill(0), size: Array(dim).fill(fig(2 * (stub + widest))) },
530
+ keep: members.map((e) => ({ at: end(e), r: fig(e.diameter / 2), label: `${e.id}'s end` })),
531
+ 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' }],
533
+ };
534
+ return { node: id, at: vec3(p), members, problem };
535
+ });
536
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/fea",
3
- "version": "0.2.11",
3
+ "version": "0.2.13",
4
4
  "description": "How far a part bends under load: finite elements on a grid of squares (2D) or cubes (3D), with a multigrid solver, and frames of beams (static, buckling and modes), in plain JavaScript.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -15,6 +15,10 @@
15
15
  "./frame": {
16
16
  "types": "./frame.d.mts",
17
17
  "default": "./frame.mjs"
18
+ },
19
+ "./layout": {
20
+ "types": "./layout.d.mts",
21
+ "default": "./layout.mjs"
18
22
  }
19
23
  },
20
24
  "files": [
@@ -26,6 +30,8 @@
26
30
  "threads.d.mts",
27
31
  "frame.mjs",
28
32
  "frame.d.mts",
33
+ "layout.mjs",
34
+ "layout.d.mts",
29
35
  "CHANGELOG.md"
30
36
  ],
31
37
  "license": "MIT",
@@ -38,7 +44,9 @@
38
44
  "frames",
39
45
  "beams",
40
46
  "buckling",
41
- "modal-analysis"
47
+ "modal-analysis",
48
+ "layout-optimisation",
49
+ "ground-structure"
42
50
  ],
43
51
  "engines": {
44
52
  "node": ">=20"