@rulecad/fea 0.2.10 → 0.2.11

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 ADDED
@@ -0,0 +1,15 @@
1
+ # Changelog: @rulecad/fea
2
+
3
+ What changed in each release, for someone upgrading a workspace.
4
+
5
+ ## 0.2.11: frames held, sized and their modes said (Frames 3)
6
+
7
+ ### Added
8
+
9
+ - `frame(model, { loose: 'hold' })` holds each way a frame could move that nothing resists and its loads do not push,
10
+ names it in `frame().loose`, and refuses a solve whose loads would move the frame that way. The default is unchanged.
11
+ - Modes and buckling on a held frame count the held ways as free: a way the frame moves mass with nothing resisting is
12
+ a 0 Hz mode marked `free`, and a frame its squeezed members lean further over tips at factor 0 (`tipped`).
13
+ - `sizing()`: the lightest section for each group of members that meets limits on deflection, stress, buckling and
14
+ frequency in every load case, by trying every design where there are few, else by steps; each group says the limit
15
+ that set it.
package/README.md CHANGED
@@ -125,8 +125,19 @@ result carries its `axes`, so nothing has to be guessed.
125
125
  **What each solve returns.**
126
126
 
127
127
  - `frame(model, { shear })` reads and checks the model, assembles and factorises it, and returns `{ statics,
128
- buckling, modes, freedoms, nodes }`. `shear: false` ignores the shear areas. `statics(model)`, `buckling(model)`
129
- and `modes(model)` do it in one call.
128
+ buckling, modes, freedoms, nodes, loose }`. `shear: false` ignores the shear areas. `statics(model)`, `buckling(model)`
129
+ and `modes(model)` do it in one call. A model with `loose: 'hold'` is solved even where part of it can move with
130
+ nothing resisting (a frame in one plane on pinned feet sways out of that plane; a beam pinned at both ends spins on
131
+ its axis): each such freedom is held, `loose` names it by node, and a solve whose loads would do work moving the
132
+ frame that way is refused (`fea.frame.mechanism`, with `driven: true`). The modes count those freedoms free:
133
+ each way that moves mass unresisted comes back as a mode of 0 Hz, marked `free: true`, and the rest are the
134
+ frame's own, whichever freedom was held. They are the modes of `K + s M` (s the held frame's lowest eigenvalue),
135
+ which has the same shapes as `K` against `M` with every eigenvalue raised by s. Buckling gives a factor of 0 when
136
+ the loads lean the frame the way it is free (its squeezed members turning with it, `vᵀ B v > 0` for that way v,
137
+ B the geometric stiffness's negative): the frame tips over under any share of its loads before anything buckles,
138
+ and `tipped` names the freedoms. When the loads pull it back (a frame hanging from its pins), the factors are of
139
+ the frame held there, so they can only be higher than the true ones, and `rests` names the freedoms. When the
140
+ loads leave that way alone (a strut spinning on its axis), the factors are exact.
130
141
  - `statics({ loads, gravity, masses, samples })`: `displacements` and `reactions` by node, each `[x, y, z, rx, ry,
131
142
  rz]` in global axes; `deflection: { most, node }`; and `elements`, each with its `length`, `axes`, the `ends`
132
143
  forces its nodes put on it (local axes), `axial` (its mean axial force, tension positive), and `along`: at each
@@ -138,7 +149,10 @@ result carries its `axes`, so nothing has to be guessed.
138
149
  - `buckling({ count })`: `factors`, lowest first, and `modes`, each `{ factor, shape }`: the loads times the factor
139
150
  buckle the frame into the shape (by node, largest movement 1). `statics` is the solve it came from. The first
140
151
  factor is always quick; more of them cost more when slender members are in tension.
141
- - `modes({ count })`: `frequencies` in Hz, lowest first, and `modes`, each `{ frequency, shape }`.
152
+ - `modes({ count })`: `frequencies` in Hz, lowest first, and `modes`, each `{ frequency, shape }` (and `free: true`
153
+ on a mode of 0 Hz where the frame moves with nothing resisting).
154
+ - `sizing(model, o)`: each group of members given the lightest section from a list that meets limits on
155
+ deflection, stress, buckling and frequency (below).
142
156
  - `subdivide(model, pieces)` cuts every element into equal pieces. One element cannot bow between its own ends, so
143
157
  buckling and modes want members in pieces: a pinned column's Euler load is 22% out with one element, 0.8% with
144
158
  two and 0.05% with four. Statics is exact with one.
@@ -208,6 +222,61 @@ A braced box of 50 beams (108 unknowns) solves statically in about 3 ms on a lap
208
222
  - Behind a spring or a release, mass and geometric stiffness are reduced as at rest (Guyan's reduction), which
209
223
  is why buckling and modes want members cut into pieces.
210
224
 
225
+ ### Sizing: the lightest sections that meet the limits
226
+
227
+ `sizing(model, o)` chooses a section for each group of members (members that must match: a pair of rails, four
228
+ posts) from a list, so the frame meets its limits for the least mass, or the least cost where every choice gives
229
+ one. Each design is the same frame with its groups' sections, materials and rolls changed, solved under every load
230
+ case. A frame of tubes from a layout optimiser and a frame of extrusions from an assembly go through the same solver
231
+ and the same limits.
232
+
233
+ ```js
234
+ import { sizing } from '@rulecad/fea/frame';
235
+
236
+ const bar = (b) => ({ name: `bar ${b}`, section: { A: b * b, Iy: b ** 4 / 12, Iz: b ** 4 / 12, J: 0.141 * b ** 4, cy: b / 2, cz: b / 2 },
237
+ material: { E: 70000, nu: 0.33, density: 2.7, strength: 205 } });
238
+ // model: a table, four 700 mm legs on pinned feet and a ring of rails 600 x 400 mm joined rigidly, its own weight
239
+ // and 20 kg at the middle of each long rail (nodes m1 and m2)
240
+ const r = sizing(model, {
241
+ groups: { legs: ['z1', 'z2', 'z3', 'z4'], rails: ['x1', 'x2'], ends: ['y1', 'y2'] }, // by element id, or by `of`
242
+ choices: [10, 15, 20, 25, 30].map(bar),
243
+ limits: { deflection: [{ node: 'm1', limit: 1.7 }, { node: 'm2', limit: 1.7 }], stress: { margin: 2 }, buckling: { factor: 2, euler: 1 } },
244
+ });
245
+ r.groups[1]; // { name: 'rails', choice: 'bar 20', mass: 1.296, lighter: 'bar 15',
246
+ // governs: { limit: 'deflection', where: 'm1', value: 0.92, allowed: 1.7, broken: 1.51 }, margin: 1.84 }
247
+ r.groups[0]; // { name: 'legs', choice: 'bar 10', lighter: null, governs: null }: the lightest in the list meets them
248
+ ```
249
+
250
+ | Part | Shape | Notes |
251
+ |---|---|---|
252
+ | `groups` | `{ name: [members] }` | Each member an element's `id`, or the member its pieces came from (`of`). Members in no group keep their sections |
253
+ | `choices` | `[{ name, section, material, mass, cost, roll }]` | `material` its own (the member's if left out), with `strength` in MPa for the stress limit; `mass` and `cost` per metre (mass from the area and density if left out); `roll` degrees added to the member's roll, the same section turned (a 20 x 40 on edge) |
254
+ | `only` | `{ group: [choice names] }` | The choices a group may take (all of them if left out) |
255
+ | `limits.deflection` | `[{ node, limit, along }]` or `[{ member, limit, from, to, along }]` | mm, along `along` (gravity's direction, else the whole movement); a member between two distances from its start |
256
+ | `limits.stress` | `{ margin }` | Each member's peak `abs(N)/A + abs(My)/Wy + abs(Mz)/Wz`, times the margin, under its material's strength |
257
+ | `limits.buckling` | `{ factor, euler }` | The whole frame's first buckling factor at least `factor` (members cut into `pieces`, 4); with `euler` (the effective length factor K) each grouped member in compression also carries `factor` times its force under `π² E I / (K L)²`, I the lesser second moment |
258
+ | `limits.frequency` | `{ Hz }` | The lowest mode at least this |
259
+ | `cases` | `[{ label, loads, masses, inertia }]` | Load cases: `loads` and `masses` as `statics` takes them; `inertia` masses whose weight is already in `loads` and which ring in the modes only |
260
+ | a model list | `[frame, ...others]` | The others are the same frame joined other ways (its joins rigid), same elements in the same order: each is held to the stress limit too |
261
+
262
+ **The search.** With few designs (`every`, 512, or `search: 'every'`), every design is ranked by mass and solved in
263
+ that order until one meets every limit, which makes it the lightest; a design is dropped at the first stage
264
+ (statics, then buckling, then modes) that breaks a limit. With more, `search: 'steps'`: from every group at its
265
+ lightest, each group looks up its list for the lightest heavier choice that cuts the worst limit's use (passing over
266
+ one that is heavier but weaker this way, a 30 x 30 after a 20 x 40 on edge), and the group that cuts it most for its
267
+ added mass steps up to it, until the limits are met; then each group, the heaviest first, steps down as far as the limits allow, until nothing moves. Steps
268
+ solve far fewer designs and land near the lightest, not always on it (a table in the tests: within a fifth).
269
+
270
+ **What set each choice.** A group's `governs` is the limit its next lighter choice breaks with the other groups as
271
+ chosen, the worst there by `broken` (its use of the limit, over 1). A choice of the same weight (the same section
272
+ turned) is not lighter. `margin` is how many times inside that limit the chosen design is. A group at the lightest
273
+ choice has no `governs`, and its margin is its own members' nearest check. Where no design meets the limits, `ok` is
274
+ false and the result is the design that came nearest, with `worst` saying which limit it breaks and by how much.
275
+
276
+ **Limits of sizing.** The geometry stays as drawn: a deeper section moves no node, so joints that hang off a
277
+ member's face by its width keep their drawn offsets. The search is over the list given; it does not invent a section.
278
+
279
+
211
280
  ## Sources
212
281
 
213
282
  - Amir, Aage, Lazarov (2014). On multigrid-CG for efficient topology optimization. *Structural and Multidisciplinary
package/frame.d.mts CHANGED
@@ -23,12 +23,19 @@ export function elementMatrices(section: FrameSection, material: FrameMaterial,
23
23
  * @param {{ shear?: boolean }} [o] shear: false ignores the sections' shear areas (Euler-Bernoulli beams)
24
24
  * @returns {{
25
25
  * statics: (o?: { loads?: FrameLoad[], gravity?: Vec3, masses?: Record<string, number>, samples?: number }) => StaticResult,
26
- * buckling: (o?: { count?: number, loads?: FrameLoad[], gravity?: Vec3, masses?: Record<string, number> }) => { factors: number[], modes: BucklingMode[], statics: StaticResult },
26
+ * buckling: (o?: { count?: number, loads?: FrameLoad[], gravity?: Vec3, masses?: Record<string, number> }) => { factors: number[], modes: BucklingMode[], statics: StaticResult, tipped?: { node: string, freedom: string }[], rests?: { node: string, freedom: string }[] },
27
27
  * modes: (o?: { count?: number, masses?: Record<string, number> }) => { frequencies: number[], modes: VibrationMode[] },
28
- * freedoms: number, nodes: string[] }}
28
+ * freedoms: number, nodes: string[], loose: { node: string, freedom: string }[] }}
29
29
  * statics, buckling and modes use the model's own loads, gravity and masses unless given others (another load case
30
30
  * on the same factorisation). samples: stations along each element (11). count: how many modes (1 for buckling, 6
31
- * for vibration; fewer come back if the frame has fewer). freedoms: how many unknowns were solved for.
31
+ * for vibration; fewer come back if the frame has fewer). freedoms: how many unknowns were solved for. loose: the
32
+ * freedoms held where nothing resists them (the model's loose: 'hold'), by node; none otherwise. The statics stand
33
+ * with them held, as the loads do no work there. The modes count them free: each way that moves mass unresisted
34
+ * is a mode of 0 Hz (marked free), and the rest are the frame's own, whatever freedom was held. Buckling where the
35
+ * loads lean the frame that way (its squeezed members turning with it) gives a factor of 0, the frame tipping over
36
+ * before anything buckles, with the ways named as `tipped`; where the loads pull it back (a frame hanging from its
37
+ * pins), the factors are of the frame held there, so at most the true ones, and the ways are named as `rests`;
38
+ * where the loads leave it alone (a strut spinning on its axis), the factors are exact.
32
39
  */
33
40
  export function frame(model: FrameModel, o?: {
34
41
  shear?: boolean;
@@ -48,6 +55,14 @@ export function frame(model: FrameModel, o?: {
48
55
  factors: number[];
49
56
  modes: BucklingMode[];
50
57
  statics: StaticResult;
58
+ tipped?: {
59
+ node: string;
60
+ freedom: string;
61
+ }[];
62
+ rests?: {
63
+ node: string;
64
+ freedom: string;
65
+ }[];
51
66
  };
52
67
  modes: (o?: {
53
68
  count?: number;
@@ -58,6 +73,10 @@ export function frame(model: FrameModel, o?: {
58
73
  };
59
74
  freedoms: number;
60
75
  nodes: string[];
76
+ loose: {
77
+ node: string;
78
+ freedom: string;
79
+ }[];
61
80
  };
62
81
  /**
63
82
  * The same frame with every element cut into `pieces` equal lengths, for buckling and modes: one element cannot bow
@@ -68,6 +87,73 @@ export function frame(model: FrameModel, o?: {
68
87
  * @returns {FrameModel}
69
88
  */
70
89
  export function subdivide(model: FrameModel, pieces?: number): FrameModel;
90
+ /**
91
+ * The lightest section for each group of members that meets the limits: each group (members that must match, a pair
92
+ * of rails, four posts) is given one of the choices, and the frame is solved under each load case for every design
93
+ * tried. With few designs (every, 512) every one is ranked by mass and the first that meets the limits is the
94
+ * lightest; with more, the lightest is found by steps (each group up to its lightest heavier choice that helps, the one that helps most for its mass, until
95
+ * the limits are met, then each down as far as the limits allow), which is near the lightest but not proven so. Each
96
+ * group's result names the limit that set it: the one its next lighter choice would break, with the other groups as
97
+ * chosen. The geometry stays as drawn: only sections, materials and rolls change, and members outside every group
98
+ * keep theirs. Refused by name: unknown options, a member in no element or in two groups, a choice with no section,
99
+ * a limit that is not above 0, and sizing by cost where a choice has none.
100
+ * @param {FrameModel | FrameModel[]} model the frame; or a list, the first the frame and the rest the same frame
101
+ * joined other ways (its joins rigid), whose stress is checked too, as a join's moment grows as it stiffens
102
+ * @param {{ groups: Record<string, (string | number)[]>, choices: SizingChoice[], only?: Record<string, string[]>,
103
+ * limits: SizingLimits, cases?: { label?: string, loads?: FrameLoad[], masses?: Record<string, number>, inertia?: Record<string, number> }[],
104
+ * by?: 'mass' | 'cost', pieces?: number, search?: 'every' | 'steps', every?: number }} o
105
+ * groups: members by group name, each an element's id or the member its pieces came from (`of`); only: the
106
+ * choices a group may take, by name (all of them if left out); cases: load cases (the model's own if left out),
107
+ * loads and masses as statics takes them, and inertia: masses whose weight is already in loads, which ring in the
108
+ * modes only; by: what is least (mass); pieces: each member cut into this many for buckling and modes (4)
109
+ * @returns {{ ok: boolean, by: 'mass' | 'cost', search: 'every' | 'steps', tried: number, total: number,
110
+ * groups: { name: string, members: (string | number)[], choice: string, length: number, mass: number, cost: number | null,
111
+ * lighter: string | null, governs: (SizingCheck & { lighter: string, broken: number }) | null, margin: number | null }[],
112
+ * checks: SizingCheck[], worst: SizingCheck | null, model: FrameModel }}
113
+ * ok: the limits are met (else the design that came nearest, and its checks say by how much); total: kg (or cost) of
114
+ * the grouped members; tried: designs solved; each group's length (mm), mass (kg) and cost; lighter: the next choice
115
+ * that weighs (or costs) less; governs: the limit that lighter choice breaks, its ratio there as `broken`; margin: how many times inside
116
+ * that limit the design is, as chosen; model: the frame with the chosen sections
117
+ */
118
+ export function sizing(model: FrameModel | FrameModel[], o?: {
119
+ groups: Record<string, (string | number)[]>;
120
+ choices: SizingChoice[];
121
+ only?: Record<string, string[]>;
122
+ limits: SizingLimits;
123
+ cases?: {
124
+ label?: string;
125
+ loads?: FrameLoad[];
126
+ masses?: Record<string, number>;
127
+ inertia?: Record<string, number>;
128
+ }[];
129
+ by?: "mass" | "cost";
130
+ pieces?: number;
131
+ search?: "every" | "steps";
132
+ every?: number;
133
+ }): {
134
+ ok: boolean;
135
+ by: "mass" | "cost";
136
+ search: "every" | "steps";
137
+ tried: number;
138
+ total: number;
139
+ groups: {
140
+ name: string;
141
+ members: (string | number)[];
142
+ choice: string;
143
+ length: number;
144
+ mass: number;
145
+ cost: number | null;
146
+ lighter: string | null;
147
+ governs: (SizingCheck & {
148
+ lighter: string;
149
+ broken: number;
150
+ }) | null;
151
+ margin: number | null;
152
+ }[];
153
+ checks: SizingCheck[];
154
+ worst: SizingCheck | null;
155
+ model: FrameModel;
156
+ };
71
157
  export function statics(model: FrameModel, o?: {
72
158
  shear?: boolean;
73
159
  samples?: number;
@@ -79,6 +165,14 @@ export function buckling(model: FrameModel, o?: {
79
165
  factors: number[];
80
166
  modes: BucklingMode[];
81
167
  statics: StaticResult;
168
+ tipped?: {
169
+ node: string;
170
+ freedom: string;
171
+ }[];
172
+ rests?: {
173
+ node: string;
174
+ freedom: string;
175
+ }[];
82
176
  };
83
177
  export function modes(model: FrameModel, o?: {
84
178
  shear?: boolean;
@@ -258,6 +352,13 @@ export type FrameModel = {
258
352
  * lumped masses by node, kg (weight under gravity, and inertia in modes)
259
353
  */
260
354
  masses?: Record<string, number>;
355
+ /**
356
+ * what a mechanism does: 'refuse' (left out) refuses the model; 'hold' holds
357
+ * each freedom nothing resists and solves on, so long as the loads of each solve do no work moving it that way (a
358
+ * frame in one plane on pinned feet, free to sway out of it, under loads in its plane): the frame's `loose` names
359
+ * them, and a solve whose loads would move one is refused
360
+ */
361
+ loose?: "refuse" | "hold";
261
362
  };
262
363
  /**
263
364
  * x, y, z, then about x, y, z
@@ -359,9 +460,110 @@ export type BucklingMode = {
359
460
  shape: Record<string, Six>;
360
461
  };
361
462
  /**
362
- * Hz, and the shape (largest movement 1)
463
+ * Hz, and the shape (largest movement 1); free: a mode of 0 Hz, the frame moving where nothing holds it (loose: 'hold')
363
464
  */
364
465
  export type VibrationMode = {
365
466
  frequency: number;
366
467
  shape: Record<string, Six>;
468
+ free?: true;
469
+ };
470
+ /**
471
+ * One section a group of members may be given
472
+ */
473
+ export type SizingChoice = {
474
+ /**
475
+ * its name in the results (a profile's, a tube's size)
476
+ */
477
+ name: string;
478
+ /**
479
+ * in the member's own axes, as drawn
480
+ */
481
+ section: FrameSection;
482
+ /**
483
+ * its own material (the member's if left out); strength
484
+ * in MPa, for the stress limit
485
+ */
486
+ material?: FrameMaterial & {
487
+ strength?: number;
488
+ };
489
+ /**
490
+ * kg per metre (else the section's area times the material's density)
491
+ */
492
+ mass?: number;
493
+ /**
494
+ * per metre, in any one currency, for sizing by cost
495
+ */
496
+ cost?: number;
497
+ /**
498
+ * degrees added to the member's roll: the same section turned about its length (a 20 x 40
499
+ * standing on edge in place of lying flat)
500
+ */
501
+ roll?: number;
502
+ };
503
+ /**
504
+ * What every design must meet; leave one out and it sets nothing
505
+ */
506
+ export type SizingLimits = {
507
+ /**
508
+ * a node, or a member between two distances from its start (mm, its whole length if left out), moves no more than
509
+ * limit mm along `along` (gravity's direction, else the whole movement)
510
+ */
511
+ deflection?: ({
512
+ node: string | number;
513
+ limit: number;
514
+ along?: Vec3;
515
+ } | {
516
+ member: string | number;
517
+ limit: number;
518
+ from?: number;
519
+ to?: number;
520
+ along?: Vec3;
521
+ })[];
522
+ /**
523
+ * each member's peak stress times margin stays under its material's strength
524
+ */
525
+ stress?: {
526
+ margin: number;
527
+ };
528
+ /**
529
+ * the whole frame's first buckling factor is at least
530
+ * factor; with euler (the effective length factor K), each member in compression also carries factor times its
531
+ * force under Euler's load π² E I / (K L)², I the lesser second moment (the grouped members only)
532
+ */
533
+ buckling?: {
534
+ factor: number;
535
+ euler?: number;
536
+ };
537
+ /**
538
+ * the lowest mode is at least this
539
+ */
540
+ frequency?: {
541
+ Hz: number;
542
+ };
543
+ };
544
+ /**
545
+ * one limit's figure in one design
546
+ */
547
+ export type SizingCheck = {
548
+ limit: "deflection" | "stress" | "buckling" | "frequency";
549
+ /**
550
+ * the node, member or 'frame' it is about
551
+ */
552
+ where: string;
553
+ /**
554
+ * the figure: mm, MPa, a factor or Hz
555
+ */
556
+ value: number;
557
+ /**
558
+ * what the limit allows of it
559
+ */
560
+ allowed: number;
561
+ /**
562
+ * how much of the limit it uses (1 is at the limit; over 1 fails)
563
+ */
564
+ ratio: number;
565
+ /**
566
+ * the load case it is worst in
567
+ */
568
+ case?: string;
367
569
  };
package/frame.mjs CHANGED
@@ -69,6 +69,10 @@
69
69
  * @property {FrameLoad[]} [loads]
70
70
  * @property {Vec3} [gravity] N/kg (m/s²), acting on every element's mass and every lumped mass: [0, 0, -9.81]
71
71
  * @property {Record<string, number>} [masses] lumped masses by node, kg (weight under gravity, and inertia in modes)
72
+ * @property {'refuse' | 'hold'} [loose] what a mechanism does: 'refuse' (left out) refuses the model; 'hold' holds
73
+ * each freedom nothing resists and solves on, so long as the loads of each solve do no work moving it that way (a
74
+ * frame in one plane on pinned feet, free to sway out of it, under loads in its plane): the frame's `loose` names
75
+ * them, and a solve whose loads would move one is refused
72
76
  */
73
77
  /** @typedef {[number, number, number, number, number, number]} Six x, y, z, then about x, y, z */
74
78
  /**
@@ -97,7 +101,7 @@
97
101
  * @property {{ most: number, node: string }} deflection the largest movement of any node, and which
98
102
  */
99
103
  /** @typedef {{ factor: number, shape: Record<string, Six> }} BucklingMode the loads times `factor` buckle the frame into `shape` (largest movement 1) */
100
- /** @typedef {{ frequency: number, shape: Record<string, Six> }} VibrationMode Hz, and the shape (largest movement 1) */
104
+ /** @typedef {{ frequency: number, shape: Record<string, Six>, free?: true }} VibrationMode Hz, and the shape (largest movement 1); free: a mode of 0 Hz, the frame moving where nothing holds it (loose: 'hold') */
101
105
 
102
106
  const FREEDOMS = ['x', 'y', 'z', 'rx', 'ry', 'rz'];
103
107
  /** @returns {never} */
@@ -450,12 +454,19 @@ const condensedLoad = (el, fb) => { if (!el.T) return fb; const fc = new Float64
450
454
  * @param {{ shear?: boolean }} [o] shear: false ignores the sections' shear areas (Euler-Bernoulli beams)
451
455
  * @returns {{
452
456
  * statics: (o?: { loads?: FrameLoad[], gravity?: Vec3, masses?: Record<string, number>, samples?: number }) => StaticResult,
453
- * buckling: (o?: { count?: number, loads?: FrameLoad[], gravity?: Vec3, masses?: Record<string, number> }) => { factors: number[], modes: BucklingMode[], statics: StaticResult },
457
+ * buckling: (o?: { count?: number, loads?: FrameLoad[], gravity?: Vec3, masses?: Record<string, number> }) => { factors: number[], modes: BucklingMode[], statics: StaticResult, tipped?: { node: string, freedom: string }[], rests?: { node: string, freedom: string }[] },
454
458
  * modes: (o?: { count?: number, masses?: Record<string, number> }) => { frequencies: number[], modes: VibrationMode[] },
455
- * freedoms: number, nodes: string[] }}
459
+ * freedoms: number, nodes: string[], loose: { node: string, freedom: string }[] }}
456
460
  * statics, buckling and modes use the model's own loads, gravity and masses unless given others (another load case
457
461
  * on the same factorisation). samples: stations along each element (11). count: how many modes (1 for buckling, 6
458
- * for vibration; fewer come back if the frame has fewer). freedoms: how many unknowns were solved for.
462
+ * for vibration; fewer come back if the frame has fewer). freedoms: how many unknowns were solved for. loose: the
463
+ * freedoms held where nothing resists them (the model's loose: 'hold'), by node; none otherwise. The statics stand
464
+ * with them held, as the loads do no work there. The modes count them free: each way that moves mass unresisted
465
+ * is a mode of 0 Hz (marked free), and the rest are the frame's own, whatever freedom was held. Buckling where the
466
+ * loads lean the frame that way (its squeezed members turning with it) gives a factor of 0, the frame tipping over
467
+ * before anything buckles, with the ways named as `tipped`; where the loads pull it back (a frame hanging from its
468
+ * pins), the factors are of the frame held there, so at most the true ones, and the ways are named as `rests`;
469
+ * where the loads leave it alone (a strut spinning on its axis), the factors are exact.
459
470
  */
460
471
  export function frame(model, o = {}) {
461
472
  const f = read(model, o), { ids, N, els, held, ground } = f;
@@ -494,12 +505,31 @@ export function frame(model, o = {}) {
494
505
  }
495
506
  }
496
507
  const factor = n ? factorise(K) : { solve: (b) => new Float64Array(0), loose: [] };
497
- if (factor.loose.length) {
498
- const loose = factor.loose.map((i) => ({ node: ids[Math.floor(back[i] / 6)], freedom: FREEDOMS[back[i] % 6] }));
499
- const by = new Map(); for (const l of loose) by.set(l.node, [...(by.get(l.node) || []), l.freedom]);
500
- const list = [...by].slice(0, 8).map(([node, fr]) => `node ${said(node)} (${fr.join(', ')})`).join('; ');
501
- refuse('mechanism', `the frame is a mechanism: it can still move with nothing resisting, at ${list}${by.size > 8 ? `, and ${by.size - 8} more nodes` : ''}. Hold those freedoms with a support, or join the elements there more stiffly (a pinned end frees its bending rotations and still carries twist, so a strut pinned at both ends can spin: make one end 'ball')`, { loose });
502
- }
508
+ if (model.loose !== undefined && model.loose !== 'refuse' && model.loose !== 'hold') refuse('input', `loose is ${said(model.loose)}: 'refuse' (a mechanism refuses the model) or 'hold' (each freedom nothing resists is held, while the loads do not move it)`);
509
+ const loose = factor.loose.map((i) => ({ node: ids[Math.floor(back[i] / 6)], freedom: FREEDOMS[back[i] % 6] }));
510
+ const listOf = (ls) => { const by = new Map(); for (const l of ls) by.set(l.node, [...(by.get(l.node) || []), l.freedom]); return `${[...by].slice(0, 8).map(([node, fr]) => `node ${said(node)} (${fr.join(', ')})`).join('; ')}${by.size > 8 ? `, and ${by.size - 8} more nodes` : ''}`; };
511
+ if (loose.length && model.loose !== 'hold') refuse('mechanism', `the frame is a mechanism: it can still move with nothing resisting, at ${listOf(loose)}. Hold those freedoms with a support, or join the elements there more stiffly (a pinned end frees its bending rotations and still carries twist, so a strut pinned at both ends can spin: make one end 'ball')`, { loose });
512
+ // Each loose freedom i was held by a pivot many orders stiffer than the frame, which is K + D eᵢ eᵢᵀ; then
513
+ // (K + D eᵢ eᵢᵀ)⁻¹ eᵢ is the way the frame moves unresisted (K's null vector v, over D vᵢ). Scaled so it moves
514
+ // 1 mm at most (or turns 1 / span where nothing moves), a load p does p · v of work moving it: none, and the hold
515
+ // carries nothing, so the solve stands as the frame's own.
516
+ const span0 = f.span || 1;
517
+ const ways = factor.loose.map((i, k) => {
518
+ const e = new Float64Array(n); e[i] = 1;
519
+ const v = factor.solve(e);
520
+ let most = 0, turn = 0;
521
+ for (let q = 0; q < n; q++) { const a = Math.abs(v[q]); if (back[q] % 6 < 3) most = Math.max(most, a); else turn = Math.max(turn, a); }
522
+ const s = most > 1e-9 * turn * span0 ? 1 / most : 1 / (turn * span0);
523
+ for (let q = 0; q < n; q++) v[q] *= s;
524
+ return { ...loose[k], v };
525
+ });
526
+ // the loads (as the free freedoms' forces) that move the frame where it is held only by the hold: refused by name
527
+ const driven = (p) => {
528
+ let size = 0;
529
+ for (let q = 0; q < n; q++) size += Math.abs(p[q]) * (back[q] % 6 < 3 ? 1 : 1 / span0);
530
+ return ways.filter((w) => { let work = 0; for (let q = 0; q < n; q++) work += p[q] * w.v[q]; return Math.abs(work) > 1e-6 * size; });
531
+ };
532
+ const refuseDriven = (p) => { const d = driven(p); if (d.length) refuse('mechanism', `the loads move the frame where nothing holds it, at ${listOf(d)}: it would move with nothing resisting. Hold those freedoms with a support, or join the elements there more stiffly`, { loose: d.map(({ node, freedom }) => ({ node, freedom })), driven: true }); };
503
533
  const shapeOf = (x) => { // a vector over the free freedoms as each node's six: its largest movement 1, and that one positive
504
534
  const u = new Float64Array(6 * N);
505
535
  for (let i = 0; i < n; i++) u[back[i]] = x[i];
@@ -522,7 +552,9 @@ export function frame(model, o = {}) {
522
552
  for (let q = 0; q < 4; q++) { const g = toGlobal3(el.R, fc, 3 * q), at = 6 * (q < 2 ? el.a : el.b) + 3 * (q % 2); for (let k = 0; k < 3; k++) p[at + k] += g[k]; }
523
553
  return { fb, fc };
524
554
  });
525
- const x = factor.solve(Float64Array.from(back, (d) => p[d])), u = new Float64Array(6 * N), residual = Float64Array.from(nodal, (v) => -v);
555
+ const pf = Float64Array.from(back, (d) => p[d]);
556
+ if (ways.length) refuseDriven(pf);
557
+ const x = factor.solve(pf), u = new Float64Array(6 * N), residual = Float64Array.from(nodal, (v) => -v);
526
558
  for (let i = 0; i < n; i++) u[back[i]] = x[i];
527
559
  for (const { node, v } of idle) { const o = 6 * node + 3, along = u[o] * v[0] + u[o + 1] * v[1] + u[o + 2] * v[2]; for (let c = 0; c < 3; c++) u[o + c] = held[o + c] || Math.abs(v[c]) === 1 ? 0 : u[o + c] - along * v[c]; }
528
560
  let most = 0, mostAt = 0;
@@ -575,6 +607,30 @@ export function frame(model, o = {}) {
575
607
  const s = statics(c), axial = s.elements.map((e) => e.axial), size = Math.max(...axial.map(Math.abs));
576
608
  if (!axial.some((a) => a < -1e-9 * Math.max(size, 1e-300))) refuse('compression', 'no element is in compression under these loads, so nothing can buckle: buckling needs a load that squeezes at least one element along its length');
577
609
  const B = assemble((el) => toGlobal(el.kg, el.R), axial.map((a) => -a)), block = 2 * count + 16;
610
+ // Where the frame is held only by the hold (loose: 'hold'), K v = 0 along the way v it moves unresisted, so
611
+ // vᵀ (K − λ B) v = −λ vᵀ B v. If the loads lean on that way (vᵀ B v > 0, as a frame on pinned feet with its posts
612
+ // squeezed leans over), K − λ B loses its positive definiteness at any λ above 0: the frame tips over under any
613
+ // share of its loads, before anything buckles, and the factor is 0. A way the loads leave alone (B v = 0) does not
614
+ // change the factors: each shape has one copy with the held freedom at 0, of the same energies, so the hold is
615
+ // exact. A way the loads hold up (vᵀ B v < 0, a frame hanging from its pins) is stiffer held than it is: the
616
+ // factors are then at most the true ones' upper bound, and the ways are named as `rests`.
617
+ const rests = [];
618
+ if (ways.length) {
619
+ let bmax = 0;
620
+ for (let i = 0; i < n; i++) bmax = Math.max(bmax, Math.abs(B.v[diagonal(B, i)]));
621
+ const tipped = [];
622
+ for (const w of ways) {
623
+ const Bv = multiply(B, w.v);
624
+ let g = 0, vv = 0, bb = 0;
625
+ for (let q = 0; q < n; q++) { g += w.v[q] * Bv[q]; vv += w.v[q] * w.v[q]; bb += Bv[q] * Bv[q]; }
626
+ const tol = 1e-6 * bmax * vv;
627
+ if (g > tol || (g >= -tol && Math.sqrt(bb) > 1e-6 * bmax * Math.sqrt(vv))) tipped.push(w); else if (g < -tol) rests.push({ node: w.node, freedom: w.freedom });
628
+ }
629
+ if (tipped.length) {
630
+ const shown = tipped.slice(0, count).map((w) => ({ factor: 0, shape: shapeOf(w.v) }));
631
+ return { factors: shown.map((m) => m.factor), modes: shown, statics: s, tipped: tipped.map(({ node, freedom }) => ({ node, freedom })) };
632
+ }
633
+ }
578
634
  // K φ = λ B φ, B = −Kg, for the smallest λ above 0. B is indefinite: with the loads reversed, whatever is in
579
635
  // tension would buckle, and those (negative) factors can be far smaller in size and crowd the iteration. So it
580
636
  // is shifted to just under the first factor: K − σ B has a Cholesky factor exactly when σ is under it (and over
@@ -594,7 +650,7 @@ export function frame(model, o = {}) {
594
650
  }
595
651
  const { values, vectors } = lowest(shifted.solve, B, count, block);
596
652
  const modes = values.map((mu, i) => ({ factor: low + 1 / mu, shape: shapeOf(vectors[i]) }));
597
- return { factors: modes.map((m) => m.factor), modes, statics: s };
653
+ return { factors: modes.map((m) => m.factor), modes, statics: s, ...(rests.length ? { rests } : {}) };
598
654
  }
599
655
 
600
656
  function modes(c = {}) {
@@ -604,13 +660,30 @@ export function frame(model, o = {}) {
604
660
  if (!els.some((el) => el.perLength > 0) && !lumped.some((m) => m > 0)) refuse('mass', 'nothing in the frame has mass, so it has no frequencies: give the materials a density (g/cm³), or lump masses (kg) at nodes');
605
661
  const M = assemble((el) => toGlobal(el.m, el.R));
606
662
  for (let i = 0; i < n; i++) if (back[i] % 6 < 3) M.v[diagonal(M, i)] += lumped[Math.floor(back[i] / 6)];
607
- const { values, vectors } = lowest(factor.solve, M, count);
608
- // K in N/mm against M in kg: ω² = 1000 / μ (a newton is a kg·m/s², and the lengths are mm)
609
- const found = values.map((mu, i) => ({ frequency: Math.sqrt(1000 / mu) / (2 * Math.PI), shape: shapeOf(vectors[i]) }));
663
+ // Where the frame is held only by the hold (loose: 'hold'), the hold would stand in for a support that is not
664
+ // there and lift every frequency (by how much depends on where it lands). So the modes are those of K + s M
665
+ // instead, positive definite wherever the free way moves mass, with s the held frame's lowest λ (ω² / 1000):
666
+ // K x = λ M x exactly when (K + s M) x = (λ + s) M x, so each way that moves mass unresisted comes back as a
667
+ // mode of λ = 0 (0 Hz, marked free) and the rest are the frame's own, with nothing held. A way that moves no
668
+ // mass is still held in K + s M, which changes nothing (K v = M v = 0: each shape has a copy with it at 0).
669
+ let solveM = factor.solve, shift = 0;
670
+ if (factor.loose.length) {
671
+ const rough = lowest(factor.solve, M, 1, undefined, 1e-3, 60);
672
+ shift = rough.values.length ? 1 / rough.values[0] : 1;
673
+ const A = profile(first);
674
+ for (let i = 0; i < A.v.length; i++) A.v[i] = K.v[i] + shift * M.v[i];
675
+ solveM = factorise(A).solve;
676
+ }
677
+ const { values, vectors } = lowest(solveM, M, count);
678
+ // K in N/mm against M in kg: ω² = 1000 λ, λ = 1 / μ − s (a newton is a kg·m/s², and the lengths are mm)
679
+ const found = values.map((mu, i) => {
680
+ const lambda = 1 / mu - shift, free = shift > 0 && lambda < 1e-6 * shift;
681
+ return { frequency: free ? 0 : Math.sqrt(1000 * lambda) / (2 * Math.PI), shape: shapeOf(vectors[i]), ...(free ? { free: true } : {}) };
682
+ });
610
683
  return { frequencies: found.map((m) => m.frequency), modes: found };
611
684
  }
612
685
 
613
- return { statics, buckling, modes, freedoms: n, nodes: ids };
686
+ return { statics, buckling, modes, freedoms: n, nodes: ids, loose };
614
687
  }
615
688
 
616
689
  /**
@@ -624,7 +697,8 @@ export const statics = (model, o = {}) => frame(model, o).statics(o);
624
697
  * buckling, from the geometric stiffness of each element's axial force in the static solve. The first factor is
625
698
  * always quick to find; asking for more costs more where slender members are in tension.
626
699
  * @param {FrameModel} model @param {{ shear?: boolean, count?: number }} [o] count: how many modes (1)
627
- * @returns {{ factors: number[], modes: BucklingMode[], statics: StaticResult }}
700
+ * @returns {{ factors: number[], modes: BucklingMode[], statics: StaticResult, tipped?: { node: string, freedom: string }[], rests?: { node: string, freedom: string }[] }}
701
+ * tipped and rests: with loose: 'hold', as `frame` says
628
702
  */
629
703
  export const buckling = (model, o = {}) => frame(model, o).buckling(o);
630
704
  /**
@@ -658,3 +732,292 @@ export function subdivide(model, pieces = 4) {
658
732
  const loads = (model.loads || []).flatMap((l) => (l && 'element' in l && parts.has(String(l.element)) ? parts.get(String(l.element)).map((element) => ({ ...l, element })) : [l]));
659
733
  return { ...model, nodes, elements, ...(model.loads ? { loads } : {}) };
660
734
  }
735
+
736
+ // ---- sizing: the lightest section for each group of members that meets the limits ----
737
+
738
+ /**
739
+ * @typedef {object} SizingChoice One section a group of members may be given
740
+ * @property {string} name its name in the results (a profile's, a tube's size)
741
+ * @property {FrameSection} section in the member's own axes, as drawn
742
+ * @property {FrameMaterial & { strength?: number }} [material] its own material (the member's if left out); strength
743
+ * in MPa, for the stress limit
744
+ * @property {number} [mass] kg per metre (else the section's area times the material's density)
745
+ * @property {number} [cost] per metre, in any one currency, for sizing by cost
746
+ * @property {number} [roll] degrees added to the member's roll: the same section turned about its length (a 20 x 40
747
+ * standing on edge in place of lying flat)
748
+ */
749
+ /**
750
+ * @typedef {object} SizingLimits What every design must meet; leave one out and it sets nothing
751
+ * @property {({ node: string | number, limit: number, along?: Vec3 } | { member: string | number, limit: number, from?: number, to?: number, along?: Vec3 })[]} [deflection]
752
+ * a node, or a member between two distances from its start (mm, its whole length if left out), moves no more than
753
+ * limit mm along `along` (gravity's direction, else the whole movement)
754
+ * @property {{ margin: number }} [stress] each member's peak stress times margin stays under its material's strength
755
+ * @property {{ factor: number, euler?: number }} [buckling] the whole frame's first buckling factor is at least
756
+ * factor; with euler (the effective length factor K), each member in compression also carries factor times its
757
+ * force under Euler's load π² E I / (K L)², I the lesser second moment (the grouped members only)
758
+ * @property {{ Hz: number }} [frequency] the lowest mode is at least this
759
+ */
760
+ /**
761
+ * @typedef {object} SizingCheck one limit's figure in one design
762
+ * @property {'deflection' | 'stress' | 'buckling' | 'frequency'} limit
763
+ * @property {string} where the node, member or 'frame' it is about
764
+ * @property {number} value the figure: mm, MPa, a factor or Hz
765
+ * @property {number} allowed what the limit allows of it
766
+ * @property {number} ratio how much of the limit it uses (1 is at the limit; over 1 fails)
767
+ * @property {string} [case] the load case it is worst in
768
+ */
769
+
770
+ const dot = (u, v) => u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
771
+ const named = (v, table) => (typeof v === 'string' ? table?.[v] : v);
772
+ const SIZE_LIMITS = ['deflection', 'stress', 'buckling', 'frequency'];
773
+ const SIZE_KEYS = ['groups', 'choices', 'only', 'limits', 'cases', 'bounds', 'by', 'pieces', 'search', 'every'];
774
+
775
+ /**
776
+ * The lightest section for each group of members that meets the limits: each group (members that must match, a pair
777
+ * of rails, four posts) is given one of the choices, and the frame is solved under each load case for every design
778
+ * tried. With few designs (every, 512) every one is ranked by mass and the first that meets the limits is the
779
+ * lightest; with more, the lightest is found by steps (each group up to its lightest heavier choice that helps, the one that helps most for its mass, until
780
+ * the limits are met, then each down as far as the limits allow), which is near the lightest but not proven so. Each
781
+ * group's result names the limit that set it: the one its next lighter choice would break, with the other groups as
782
+ * chosen. The geometry stays as drawn: only sections, materials and rolls change, and members outside every group
783
+ * keep theirs. Refused by name: unknown options, a member in no element or in two groups, a choice with no section,
784
+ * a limit that is not above 0, and sizing by cost where a choice has none.
785
+ * @param {FrameModel | FrameModel[]} model the frame; or a list, the first the frame and the rest the same frame
786
+ * joined other ways (its joins rigid), whose stress is checked too, as a join's moment grows as it stiffens
787
+ * @param {{ groups: Record<string, (string | number)[]>, choices: SizingChoice[], only?: Record<string, string[]>,
788
+ * limits: SizingLimits, cases?: { label?: string, loads?: FrameLoad[], masses?: Record<string, number>, inertia?: Record<string, number> }[],
789
+ * by?: 'mass' | 'cost', pieces?: number, search?: 'every' | 'steps', every?: number }} o
790
+ * groups: members by group name, each an element's id or the member its pieces came from (`of`); only: the
791
+ * choices a group may take, by name (all of them if left out); cases: load cases (the model's own if left out),
792
+ * loads and masses as statics takes them, and inertia: masses whose weight is already in loads, which ring in the
793
+ * modes only; by: what is least (mass); pieces: each member cut into this many for buckling and modes (4)
794
+ * @returns {{ ok: boolean, by: 'mass' | 'cost', search: 'every' | 'steps', tried: number, total: number,
795
+ * groups: { name: string, members: (string | number)[], choice: string, length: number, mass: number, cost: number | null,
796
+ * lighter: string | null, governs: (SizingCheck & { lighter: string, broken: number }) | null, margin: number | null }[],
797
+ * checks: SizingCheck[], worst: SizingCheck | null, model: FrameModel }}
798
+ * ok: the limits are met (else the design that came nearest, and its checks say by how much); total: kg (or cost) of
799
+ * the grouped members; tried: designs solved; each group's length (mm), mass (kg) and cost; lighter: the next choice
800
+ * that weighs (or costs) less; governs: the limit that lighter choice breaks, its ratio there as `broken`; margin: how many times inside
801
+ * that limit the design is, as chosen; model: the frame with the chosen sections
802
+ */
803
+ export function sizing(model, o = {}) {
804
+ const models = Array.isArray(model) ? model : [model], base = models[0];
805
+ if (!base || typeof base !== 'object' || !Array.isArray(base.elements)) refuse('input', 'sizing takes a frame, { nodes, elements, supports, loads }, or a list of frames: the first the frame, the rest it joined other ways');
806
+ if (!o || typeof o !== 'object') refuse('input', 'sizing takes { groups, choices, limits }');
807
+ for (const k of Object.keys(o)) if (!SIZE_KEYS.includes(k)) refuse('input', `sizing has no option "${k}": it takes ${SIZE_KEYS.join(', ')}`);
808
+ const by = o.by ?? 'mass', pieces = o.pieces ?? 4, every = o.every ?? 512;
809
+ if (!['mass', 'cost'].includes(by)) refuse('input', `by is 'mass' or 'cost' (got ${said(o.by)})`);
810
+ if (!(Number.isInteger(pieces) && pieces >= 1)) refuse('input', `pieces is a whole number from 1 (got ${said(o.pieces)})`);
811
+ if (o.search != null && !['every', 'steps'].includes(o.search)) refuse('input', `search is 'every' (rank every design by mass and take the first that meets the limits) or 'steps' (got ${said(o.search)})`);
812
+ // the choices
813
+ if (!Array.isArray(o.choices) || !o.choices.length) refuse('input', 'choices is a list of { name, section, material, mass }: the sections a group may be given');
814
+ const choices = new Map();
815
+ for (const [i, c] of o.choices.entries()) {
816
+ if (!c || typeof c !== 'object' || typeof c.name !== 'string' || !c.name) refuse('input', `choice ${i + 1} is ${said(c)}: a choice is { name, section, material, mass, cost, roll }`);
817
+ if (choices.has(c.name)) refuse('input', `choice ${said(c.name)} is listed twice`);
818
+ if (!c.section || typeof c.section !== 'object') refuse('section', `choice ${said(c.name)} has no section: { A, Iy, Iz, J } in mm² and mm⁴`);
819
+ for (const key of ['A', 'Iy', 'Iz', 'J']) if (!(c.section[key] > 0)) refuse('section', `choice ${said(c.name)}'s section has ${key} = ${said(c.section[key])}: it needs ${key} above 0`);
820
+ if (c.material != null && !(c.material?.E > 0)) refuse('material', `choice ${said(c.name)}'s material has no E above 0 (got ${said(c.material)})`);
821
+ for (const key of ['mass', 'cost']) if (c[key] != null && !(c[key] >= 0)) refuse('input', `choice ${said(c.name)}'s ${key} is per metre, 0 or more (got ${said(c[key])})`);
822
+ if (c.roll != null && !Number.isFinite(c.roll)) refuse('axes', `choice ${said(c.name)}'s roll is degrees (got ${said(c.roll)})`);
823
+ if (by === 'cost' && !(c.cost >= 0)) refuse('input', `sizing by cost, and choice ${said(c.name)} gives no cost per metre: give every choice a cost, or size by mass`);
824
+ choices.set(c.name, c);
825
+ }
826
+ // the groups: each member's elements
827
+ if (!o.groups || typeof o.groups !== 'object' || Array.isArray(o.groups) || !Object.keys(o.groups).length) refuse('input', 'groups is { name: [members] }: the members that must take one section, by element id or by the member their pieces came from');
828
+ const els = base.elements, whose = new Map(), groups = [];
829
+ for (const [name, list] of Object.entries(o.groups)) {
830
+ if (!Array.isArray(list) || !list.length) refuse('input', `group ${said(name)} is a list of members (got ${said(list)})`);
831
+ const idx = [];
832
+ for (const m of list) {
833
+ const mine = els.map((e, i) => (String(e.of ?? e.id ?? i) === String(m) || String(e.id ?? i) === String(m) ? i : -1)).filter((i) => i >= 0);
834
+ if (!mine.length) refuse('input', `group ${said(name)} names member ${said(m)}, and no element is it or a piece of it`);
835
+ if (whose.has(String(m))) refuse('input', `member ${said(m)} is in group ${said(whose.get(String(m)))} and in group ${said(name)}: a member takes one section`);
836
+ whose.set(String(m), name); idx.push(...mine);
837
+ }
838
+ const allowed = o.only?.[name] ?? [...choices.keys()];
839
+ if (!Array.isArray(allowed) || !allowed.length) refuse('input', `only.${name} is a list of the choices group ${said(name)} may take`);
840
+ for (const c of allowed) if (!choices.has(c)) refuse('input', `only.${name} names ${said(c)}, which is not a choice (choices: ${[...choices.keys()].join(', ')})`);
841
+ groups.push({ name, members: list, idx, allowed });
842
+ }
843
+ for (const k of Object.keys(o.only ?? {})) if (!groups.some((g) => g.name === k)) refuse('input', `only names group ${said(k)}, and there is no such group`);
844
+ // the limits
845
+ const L = o.limits;
846
+ if (!L || typeof L !== 'object' || !Object.keys(L).length) refuse('input', `limits is { ${SIZE_LIMITS.join(', ')} }: at least one`);
847
+ for (const k of Object.keys(L)) if (!SIZE_LIMITS.includes(k)) refuse('input', `limits has no "${k}": it takes ${SIZE_LIMITS.join(', ')}`);
848
+ const pos = (v, what) => { if (!(v > 0) || !Number.isFinite(v)) refuse('input', `${what} is above 0 (got ${said(v)})`); return v; };
849
+ const nodePos = (n) => { const p = base.nodes[n]; if (!isVec3(p)) refuse('node', `a deflection limit names node ${said(n)}, which is not in nodes`, { node: n }); return p; };
850
+ const g0 = base.gravity && Math.hypot(...base.gravity) > 0 ? base.gravity.map((v) => v / Math.hypot(...base.gravity)) : null;
851
+ const deflection = (L.deflection ?? []).map((d, i) => {
852
+ if (!d || typeof d !== 'object') refuse('input', `limits.deflection ${i + 1} is { node, limit } or { member, limit, from, to } (got ${said(d)})`);
853
+ pos(d.limit, `limits.deflection ${i + 1}'s limit (mm)`);
854
+ if (d.along != null && !(isVec3(d.along) && Math.hypot(...d.along) > 0)) refuse('input', `limits.deflection ${i + 1}'s along is a direction [x, y, z] (got ${said(d.along)})`);
855
+ const along = d.along ? d.along.map((v) => v / Math.hypot(...d.along)) : g0;
856
+ if (d.node != null) { nodePos(d.node); return { ...d, along }; }
857
+ const mine = els.filter((e, k) => String(e.of ?? e.id ?? k) === String(d.member));
858
+ if (!mine.length) refuse('input', `limits.deflection ${i + 1} names member ${said(d.member)}, and no element is a piece of it`);
859
+ const start = nodePos(mine[0].a), end = nodePos(mine[mine.length - 1].b), len = Math.hypot(...end.map((v, k) => v - start[k]));
860
+ return { ...d, along, start, dir: end.map((v, k) => (v - start[k]) / len), from: d.from ?? 0, to: d.to ?? len };
861
+ });
862
+ if (L.stress) pos(L.stress.margin, 'limits.stress.margin');
863
+ if (L.buckling) { pos(L.buckling.factor, 'limits.buckling.factor'); if (L.buckling.euler != null) pos(L.buckling.euler, 'limits.buckling.euler'); }
864
+ if (L.frequency) pos(L.frequency.Hz, 'limits.frequency.Hz');
865
+ const cases = (o.cases ?? [{}]).map((c, i) => ({ label: c.label ?? (o.cases ? `case ${i + 1}` : 'as given'), loads: c.loads, masses: c.masses, inertia: c.inertia }));
866
+ if (!cases.length) refuse('input', 'cases is a list of load cases, at least one');
867
+
868
+ // each group's choices, lightest first, and what one weighs and costs over the group's length
869
+ const lengthOf = (i) => { const e = els[i], a = nodePos(e.a), b = nodePos(e.b); return Math.hypot(...a.map((v, k) => v - b[k])); };
870
+ const materialOf = (i) => named(els[i].material, base.materials);
871
+ const perMetre = (c, i, key) => (key === 'cost' ? c.cost ?? null : c.mass ?? (c.section.A * ((c.material ?? materialOf(i))?.density ?? 0)) / 1000);
872
+ for (const g of groups) {
873
+ g.length = g.idx.reduce((t, i) => t + lengthOf(i), 0);
874
+ g.price = (c, key = by) => { const v = g.idx.map((i) => perMetre(c, i, key)); return v.some((x) => x == null) ? null : g.idx.reduce((t, i, k) => t + (v[k] * lengthOf(i)) / 1000, 0); };
875
+ g.list = g.allowed.map((n) => choices.get(n)).sort((p, q) => g.price(p) - g.price(q));
876
+ }
877
+ const measure = (pick) => groups.reduce((t, g, k) => t + g.price(g.list[pick[k]]), 0);
878
+
879
+ // a design: the frame with each group's choice in place
880
+ const apply = (m, pick) => {
881
+ const out = m.elements.map((e) => ({ ...e }));
882
+ groups.forEach((g, k) => { const c = g.list[pick[k]]; for (const i of g.idx) {
883
+ const e = out[i], mat = { ...(c.material ?? materialOf(i)) };
884
+ if (c.mass != null) mat.density = (c.mass / c.section.A) * 1000; // (kg/m over mm² is g/mm³, a thousand g/cm³)
885
+ e.section = c.section; e.material = mat; if (c.roll) e.roll = (e.roll ?? 0) + c.roll;
886
+ } });
887
+ return { ...m, elements: out };
888
+ };
889
+ const strengthOf = (m, e) => { const mat = named(e.material, m.materials); return mat?.strength > 0 ? mat.strength : null; };
890
+ const memberOf = (e, i) => String(e.of ?? e.id ?? i);
891
+ const memo = new Map();
892
+ let tried = 0;
893
+ // every limit's figures for a design; with quick, stop at the first stage that breaks one
894
+ const evaluate = (pick, quick = false) => {
895
+ const key = pick.join(',') + (quick ? '' : '!');
896
+ if (memo.has(key)) return memo.get(key);
897
+ if (!quick && memo.has(pick.join(',')) && memo.get(pick.join(',')).complete) return memo.get(pick.join(','));
898
+ tried++;
899
+ const m = apply(base, pick), checks = [], worse = (c) => { const was = checks.find((q) => q.limit === c.limit && q.where === c.where); if (!was) checks.push(c); else if (c.ratio > was.ratio) Object.assign(was, c); };
900
+ const solved = frame(m), stats = cases.map((c) => solved.statics({ loads: c.loads, masses: c.masses }));
901
+ // deflection
902
+ stats.forEach((s, ci) => {
903
+ for (const d of deflection) {
904
+ let v = 0;
905
+ const along = (u) => Math.abs(d.along ? dot(u, d.along) : Math.hypot(...u));
906
+ if (d.node != null) v = along(s.displacements[d.node].slice(0, 3));
907
+ else s.elements.forEach((r, i) => { if (memberOf(m.elements[i], i) !== String(d.member)) return; const a = m.nodes[m.elements[i].a]; r.along.x.forEach((x, k) => { const p = a.map((c, j) => c + r.axes[0][j] * x), z = dot(p.map((c, j) => c - d.start[j]), d.dir); if (z >= d.from - 1e-6 && z <= d.to + 1e-6) v = Math.max(v, along(r.along.d[k])); }); });
908
+ worse({ limit: 'deflection', where: d.node != null ? String(d.node) : String(d.member), value: v, allowed: d.limit, ratio: v / d.limit, case: cases[ci].label });
909
+ }
910
+ });
911
+ // stress, in the frame and every other way of joining it
912
+ if (L.stress) {
913
+ const sets = [{ m, stats }, ...models.slice(1).map((b) => { const mb = apply(b, pick), fb = frame(mb); return { m: mb, stats: cases.map((c) => fb.statics({ loads: c.loads, masses: c.masses })) }; })];
914
+ for (const { m: mm, stats: ss } of sets) ss.forEach((s, ci) => s.elements.forEach((r, i) => {
915
+ const e = mm.elements[i], st = strengthOf(mm, e);
916
+ if (!r.stress || !st) return;
917
+ worse({ limit: 'stress', where: memberOf(e, i), value: r.stress.peak, allowed: st / L.stress.margin, ratio: (r.stress.peak * L.stress.margin) / st, case: cases[ci].label });
918
+ }));
919
+ }
920
+ // each member against Euler's load
921
+ if (L.buckling?.euler) {
922
+ const per = new Map();
923
+ const grouped = new Set(groups.flatMap((g) => g.idx));
924
+ stats.forEach((s, ci) => s.elements.forEach((r, i) => { if (!grouped.has(i)) return; const id = memberOf(m.elements[i], i), p = per.get(id) ?? { N: 0, L: 0, I: Infinity, E: 0, ci }; if (ci === 0) p.L += r.length; const sec = named(m.elements[i].section, m.sections), mat = named(m.elements[i].material, m.materials); p.I = Math.min(p.I, sec.Iy, sec.Iz); p.E = mat.E; if (-r.axial > p.N) { p.N = -r.axial; p.ci = ci; } per.set(id, p); }));
925
+ for (const [id, p] of per) if (p.N > 0) { const Pcr = (Math.PI ** 2 * p.E * p.I) / (L.buckling.euler * p.L) ** 2; worse({ limit: 'buckling', where: `${id} (Euler)`, value: Pcr / p.N, allowed: L.buckling.factor, ratio: (L.buckling.factor * p.N) / Pcr, case: cases[p.ci].label }); }
926
+ }
927
+ const broke = () => checks.some((c) => c.ratio > 1);
928
+ if (quick && broke()) { const r = { checks, ok: false, complete: false }; memo.set(key, r); return r; }
929
+ const fine = (L.buckling || L.frequency) ? frame(subdivide(m, pieces)) : null;
930
+ if (L.buckling) cases.forEach((c, ci) => {
931
+ try { const f = fine.buckling({ loads: c.loads, masses: c.masses, count: 1 }).factors[0]; worse({ limit: 'buckling', where: 'frame', value: f, allowed: L.buckling.factor, ratio: L.buckling.factor / f, case: c.label }); }
932
+ catch (e) { if (e.code !== 'fea.frame.compression') throw e; }
933
+ });
934
+ if (quick && broke()) { const r = { checks, ok: false, complete: false }; memo.set(key, r); return r; }
935
+ if (L.frequency) cases.forEach((c) => {
936
+ const masses = { ...(c.masses ?? base.masses ?? {}) };
937
+ for (const [n, kg] of Object.entries(c.inertia ?? {})) masses[n] = (masses[n] ?? 0) + kg;
938
+ const hz = fine.modes({ count: 1, masses }).frequencies[0];
939
+ worse({ limit: 'frequency', where: 'frame', value: hz, allowed: L.frequency.Hz, ratio: L.frequency.Hz / hz, case: c.label });
940
+ });
941
+ const r = { checks, ok: !broke(), complete: true, model: m };
942
+ memo.set(pick.join(','), r); memo.set(key, r);
943
+ return r;
944
+ };
945
+ const worstOf = (checks) => checks.reduce((p, q) => (!p || q.ratio > p.ratio ? q : p), null);
946
+ // how far past the limits a design is in all: what still separates two designs whose worst figures tie
947
+ const excess = (checks) => checks.reduce((t, c) => t + Math.max(0, c.ratio - 1), 0);
948
+
949
+ // the search
950
+ const sizes = groups.map((g) => g.list.length), combos = sizes.reduce((t, n) => t * n, 1);
951
+ const search = o.search ?? (combos <= every ? 'every' : 'steps');
952
+ let pick = null, best = null;
953
+ if (search === 'every') {
954
+ const all = [];
955
+ const walk = (k, p) => { if (k === groups.length) { all.push(p); return; } for (let i = 0; i < sizes[k]; i++) walk(k + 1, [...p, i]); };
956
+ walk(0, []);
957
+ all.sort((p, q) => measure(p) - measure(q));
958
+ const near = [];
959
+ for (const p of all) {
960
+ const r = evaluate(p, true);
961
+ if (r.ok && evaluate(p).ok) { pick = p; break; }
962
+ near.push({ p, low: worstOf(r.checks)?.ratio ?? 0 });
963
+ }
964
+ // nothing fits: the nearest by every limit's figure, not by the quick look that stops at the first stage that
965
+ // breaks one. The quick look's worst is never more than the whole's, so designs are taken in its order and
966
+ // stop once no later one can come nearer
967
+ if (!pick) for (const c of near.sort((a, b) => a.low - b.low)) {
968
+ if (best && c.low >= best.w.ratio) break;
969
+ const w = worstOf(evaluate(c.p).checks);
970
+ if (!best || (w && w.ratio < best.w.ratio)) best = { p: c.p, w };
971
+ }
972
+ } else {
973
+ let p = groups.map(() => 0);
974
+ for (let n = 0; n < 100 * groups.length; n++) {
975
+ const r = evaluate(p), w = worstOf(r.checks)?.ratio ?? 0, e = excess(r.checks);
976
+ if (r.ok) break;
977
+ // each group up to the lightest heavier choice that helps (and those of the same weight, a section turned): a
978
+ // choice heavier but weaker this way (a 30 x 30 after a 20 x 40 on edge, a 20 x 60 lying flat) is passed over.
979
+ // It helps where it lowers the worst figure; where two groups tie for the worst, neither can alone, so a step
980
+ // that leaves the worst as it was and lowers how far past the limits the design is in all helps too (less)
981
+ let step = null;
982
+ groups.forEach((g, k) => {
983
+ let found = null;
984
+ for (let j = p[k] + 1; j < sizes[k]; j++) {
985
+ if (found != null && g.price(g.list[j]) > found * (1 + 1e-9)) break;
986
+ const q = [...p]; q[k] = j;
987
+ const rq = evaluate(q), wq = worstOf(rq.checks)?.ratio ?? 0, eq = excess(rq.checks), dm = Math.max(measure(q) - measure(p), 1e-12);
988
+ const better = wq < w * (1 - 1e-9) ? (w - wq) / dm : wq <= w * (1 + 1e-9) && eq < e * (1 - 1e-9) ? (1e-9 * (e - eq)) / dm : null;
989
+ if (better != null) { found ??= g.price(g.list[j]); if (!step || better > step.gain) step = { q, gain: better }; }
990
+ }
991
+ });
992
+ if (!step) break;
993
+ p = step.q;
994
+ }
995
+ if (evaluate(p).ok) {
996
+ // then each group down as far as the limits allow, the heaviest first, until nothing moves
997
+ for (let moved = true; moved;) {
998
+ moved = false;
999
+ const order = groups.map((g, k) => k).sort((a, b) => groups[b].price(groups[b].list[p[b]]) - groups[a].price(groups[a].list[p[a]]));
1000
+ for (const k of order) for (let i = 0; i < p[k]; i++) { const q = [...p]; q[k] = i; if (evaluate(q).ok) { p = q; moved = true; break; } }
1001
+ }
1002
+ pick = p;
1003
+ } else best = { p, w: worstOf(evaluate(p).checks) };
1004
+ }
1005
+ const ok = !!pick;
1006
+ if (!pick) pick = best.p;
1007
+ const final = evaluate(pick);
1008
+ const results = groups.map((g, k) => {
1009
+ // the next lighter choice: the heaviest that weighs less (one of the same weight, a section turned, is no lighter)
1010
+ const c = g.list[pick[k]], at = g.list.findLastIndex((x) => g.price(x) < g.price(c) * (1 - 1e-9)), lighter = at >= 0 ? g.list[at] : null;
1011
+ let governs = null, margin = null;
1012
+ if (lighter) {
1013
+ const q = [...pick]; q[k] = at;
1014
+ const w = worstOf(evaluate(q).checks.filter((x) => x.ratio > 1));
1015
+ if (w) { const now = final.checks.find((x) => x.limit === w.limit && x.where === w.where); governs = { ...(now ?? w), lighter: lighter.name, broken: w.ratio }; margin = now ? 1 / now.ratio : null; }
1016
+ }
1017
+ // no lighter choice: the margin is the group's own checks', its members' and the nodes its members run between
1018
+ const mine = new Set(g.idx.flatMap((i) => [String(els[i].a), String(els[i].b)]));
1019
+ if (margin == null) { const own = final.checks.filter((x) => g.members.some((m) => x.where === String(m) || x.where === `${m} (Euler)`) || (x.limit === 'deflection' && mine.has(x.where))), w = worstOf(own.length ? own : final.checks); margin = w ? 1 / w.ratio : null; }
1020
+ return { name: g.name, members: g.members, choice: c.name, length: g.length, mass: g.price(c, 'mass'), cost: g.price(c, 'cost'), lighter: lighter?.name ?? null, governs, margin };
1021
+ });
1022
+ return { ok, by, search, tried, total: measure(pick), groups: results, checks: final.checks, worst: worstOf(final.checks), model: final.model ?? apply(base, pick) };
1023
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/fea",
3
- "version": "0.2.10",
3
+ "version": "0.2.11",
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": {
@@ -25,7 +25,8 @@
25
25
  "threads.mjs",
26
26
  "threads.d.mts",
27
27
  "frame.mjs",
28
- "frame.d.mts"
28
+ "frame.d.mts",
29
+ "CHANGELOG.md"
29
30
  ],
30
31
  "license": "MIT",
31
32
  "keywords": [