@rulecad/fea 0.2.11 → 0.2.14

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,43 @@
2
2
 
3
3
  What changed in each release, for someone upgrading a workspace.
4
4
 
5
+ ## 0.2.14: motor reactions, racking and joins in frame sizing
6
+ ### Added
7
+
8
+ - `frame().mechanisms`: for each freedom a held frame (`loose: 'hold'`) holds, the way the frame moves there with
9
+ nothing resisting, as each node's six, so a caller can say how it moves (a portal tipping over out of its plane)
10
+ rather than name a freedom at a node.
11
+ - `sizing({ fits })`: a function of each group's choice that lists what does not go together (a join one profile
12
+ cannot make with another). Designs that do not fit are never solved; a group whose next lighter choice does not fit
13
+ says so (`governs.limit: 'fit'`, with where and why); none fitting is refused (`fea.frame.fit`).
14
+ - `sizing` cases take their own `gravity` (a side push alone) and `limits` (the limits they are held to), and a
15
+ deflection limit takes `cases`, the load cases it holds in: a racking sway held under a push alone.
16
+
17
+ ## 0.2.13: frame layout optimisation
18
+ ### Added
19
+
20
+ - `@rulecad/fea/layout`, a new entry: `layout(problem)` finds the least-volume pin-jointed frame that carries the
21
+ loads to the supports, choosing members from every pair of candidate nodes (a ground structure) and giving each its
22
+ area. It solves the plastic layout programme by an interior point method and adds members a few at a time where
23
+ the solution's virtual strains say they would help (Gilbert and Tyas 2003), so it proves the least volume over
24
+ every candidate while holding a small share of them. Several load cases share one set of areas; strengths may
25
+ differ in tension and compression; a joint can be given a cost as a length of member (fewer, longer members);
26
+ balls can be kept clear of nodes and members, or of nodes only (`through`, a wheel the stays straddle). Flat
27
+ layouts (every node and load at z = 0) and layouts in space.
28
+ - `groundStructure(nodes)` (the candidates, less members through a third node) and `nodeGrid({ from, to, pitch })`.
29
+ - `layoutFrame(result, { material })`: the layout as a frame of beams with its load cases, for `sizing` to pick each
30
+ member from tubes that can be bought. `layoutJoints(result, { material })`: each joint as a problem file for the
31
+ voxel optimiser, the members as stubs carrying their forces in each case (the layout's, or the sized frame's).
32
+ - Refused by name (`fea.layout.input`, `node`, `support`, `load`, `strength`) before any maths, and
33
+ `fea.layout.unstable` when the programme has no answer. A load may name its node by number, as nodes given as a list
34
+ are named by place.
35
+ - The interior point method stops at a relative error of 1e-9 in equilibrium, the members' limits and the gap. Its
36
+ factorisation drops a pivot only when it has cancelled to a 1e-13 share of its own row's diagonal, not of the
37
+ largest: near the optimum the diagonal spans many orders, and the old test also dropped the sound small pivots of
38
+ lightly loaded joints, so equilibrium stalled short of 1e-9 and some solvable problems in space with several cases
39
+ were refused as unstable. As a last guard, a run that still stalls keeps its best point and answers if that point
40
+ is within 1e-6.
41
+
5
42
  ## 0.2.11: frames held, sized and their modes said (Frames 3)
6
43
 
7
44
  ### 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';
@@ -125,10 +127,11 @@ result carries its `axes`, so nothing has to be guessed.
125
127
  **What each solve returns.**
126
128
 
127
129
  - `frame(model, { shear })` reads and checks the model, assembles and factorises it, and returns `{ statics,
128
- buckling, modes, freedoms, nodes, loose }`. `shear: false` ignores the shear areas. `statics(model)`, `buckling(model)`
130
+ buckling, modes, freedoms, nodes, loose, mechanisms }`. `shear: false` ignores the shear areas. `statics(model)`, `buckling(model)`
129
131
  and `modes(model)` do it in one call. A model with `loose: 'hold'` is solved even where part of it can move with
130
132
  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
133
+ its axis): each such freedom is held, `loose` names it by node, `mechanisms` gives the way the frame moves there
134
+ (each node's six, its largest movement 1: the portal's feet still and its top moving across its plane), and a solve whose loads would do work moving the
132
135
  frame that way is refused (`fea.frame.mechanism`, with `driven: true`). The modes count those freedoms free:
133
136
  each way that moves mass unresisted comes back as a mode of 0 Hz, marked `free: true`, and the rest are the
134
137
  frame's own, whichever freedom was held. They are the modes of `K + s M` (s the held frame's lowest eigenvalue),
@@ -252,11 +255,12 @@ r.groups[0]; // { name: 'legs', choice: 'bar 10', lighter: null, governs: null
252
255
  | `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
256
  | `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
257
  | `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 |
258
+ | `fits` | `(design) => [{ where, why }]` | Whether a design's choices go together, given each group's choice by name: what does not (a join between two groups that one's choice cannot make with the other's), empty where it fits. A design that does not fit is never solved |
259
+ | `limits.deflection` | `[{ node, limit, along, cases }]` or `[{ member, limit, from, to, along, cases }]` | mm, along `along` (gravity's direction, else the whole movement); a member between two distances from its start; `cases` the load cases it holds in, by label (every case where left out) |
256
260
  | `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
261
  | `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
262
  | `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 |
263
+ | `cases` | `[{ label, loads, masses, inertia, gravity, limits }]` | Load cases: `loads` and `masses` as `statics` takes them; `inertia` masses whose weight is already in `loads` and which ring in the modes only; `gravity` the case's own (`[0, 0, 0]` for a side push alone); `limits` the limits it is held to by name (every one where left out) |
260
264
  | 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
265
 
262
266
  **The search.** With few designs (`every`, 512, or `search: 'every'`), every design is ranked by mass and solved in
@@ -264,19 +268,126 @@ that order until one meets every limit, which makes it the lightest; a design is
264
268
  (statics, then buckling, then modes) that breaks a limit. With more, `search: 'steps'`: from every group at its
265
269
  lightest, each group looks up its list for the lightest heavier choice that cuts the worst limit's use (passing over
266
270
  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
271
+ added mass steps up to it, until the limits are met (a choice that does not fit the others' takes them along: the
272
+ lightest design from there in which they fit); then each group, the heaviest first, steps down as far as the limits allow, until nothing moves. Steps
268
273
  solve far fewer designs and land near the lightest, not always on it (a table in the tests: within a fifth).
269
274
 
270
275
  **What set each choice.** A group's `governs` is the limit its next lighter choice breaks with the other groups as
271
276
  chosen, the worst there by `broken` (its use of the limit, over 1). A choice of the same weight (the same section
272
277
  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
278
+ choice has no `governs`, and its margin is its own members' nearest check. Where the next lighter choice does not go
279
+ with the others' (`fits` lists something), that set it: `governs` is `{ limit: 'fit', where, why, lighter }`, and the
280
+ margin is its own members' nearest check. Where no design meets the limits, `ok` is
274
281
  false and the result is the design that came nearest, with `worst` saying which limit it breaks and by how much.
275
282
 
283
+ **Designs that fit.** With `fits`, only designs whose choices go together are solved: the steps start from the
284
+ lightest design that fits, found lightest first. Where none of the list's designs fits, sizing is refused
285
+ (`fea.frame.fit`, with the first thing that does not fit).
286
+
276
287
  **Limits of sizing.** The geometry stays as drawn: a deeper section moves no node, so joints that hang off a
277
288
  member's face by its width keep their drawn offsets. The search is over the list given; it does not invent a section.
278
289
 
279
290
 
291
+ ## Frame layout: which members, and how thick
292
+
293
+ `@rulecad/fea/layout` designs a frame of tubes or bars from nothing but its loads and supports: given a cloud of
294
+ candidate nodes, it chooses which members to put between them, and how thick each must be, so the frame carries
295
+ every load case to its supports with the least material. A bike frame, a roll cage or a space frame is mostly empty,
296
+ so it is better designed as members joined at nodes than as millions of voxels. The members are pin-jointed and each
297
+ is as thick as its worst case's force over the strength (fully stressed); the frame that comes out is then sized
298
+ from tubes that can be bought (`layoutFrame` and `sizing`), and its joints shaped by the voxel optimiser
299
+ (`layoutJoints`).
300
+
301
+ ```js
302
+ import { layout, layoutFrame, layoutJoints } from '@rulecad/fea/layout';
303
+ import { sizing } from '@rulecad/fea/frame';
304
+
305
+ const r = layout({
306
+ nodes: { A: [0, 300], B: [0, -300], C: [400, 0] }, // mm; or a grid: { from, to, pitch }, or both
307
+ supports: { A: 'pinned', B: 'pinned' }, // or { x: true, y: true, z: false }
308
+ loads: [{ node: 'C', force: [0, -1000] }], // N; or cases: [{ label, loads }, ...]
309
+ strength: 100, // MPa; or { tension, compression }
310
+ });
311
+ r.volume; // 8333.3 mm³: two bars of 8.33 mm², 833 N each
312
+ r.members[0]; // { id: 'B-C', a: 'B', b: 'C', length: 500, area: 8.333, forces: [-833.3], kind: 'compression' }
313
+ const f = layoutFrame(r, { material: { E: 200000, nu: 0.3, density: 7.85, strength: 275 } });
314
+ const sized = sizing(f.model, { groups: { bars: f.members }, choices: tubes, cases: f.cases, limits: { stress: { margin: 2 }, buckling: { factor: 2, euler: 1 } } });
315
+ const joints = layoutJoints(r, { material: 's275' }); // [{ node: 'C', members, problem }]: a problem file for each joint
316
+ ```
317
+
318
+ | Part of the problem | Shape | Notes |
319
+ |---|---|---|
320
+ | `nodes` | `{ name: [x, y] or [x, y, z] }` | Candidate nodes, mm (a list is named by place) |
321
+ | `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 |
322
+ | `supports` | `{ node: 'pinned' or { x, y, z } }` | Which movements are held at each |
323
+ | `loads` or `cases` | `[{ node, force }]` or `[{ label, loads }]` | One load case, or several, each carried alone with the same areas |
324
+ | `strength` | MPa, or `{ tension, compression }` | Each member's force over its area stays within it: give the material's strength over your margin |
325
+ | `density` | g/cm³ | For the mass, kg |
326
+ | `joint` | mm | A joint's cost as a length of member (0): above 0, fewer and longer members |
327
+ | `reach` | mm | The longest candidate member |
328
+ | `avoid` | `[{ at, r, through }]` | Balls (circles, flat) no node or member enters; with `through: true` members may pass and only nodes are kept out |
329
+ | `plane` | `true` or `false` | A flat layout in x and y; left out, flat when every node and load is at z = 0 |
330
+
331
+ Options: `keep` (members thinner than this share of the thickest are left out of `members`, 1e-4; the volume counts
332
+ them), `start` (each node's nearest candidates in the first programme: 8 flat, 18 in space), `add` (most members
333
+ added a round), `adding: false` (every candidate in one programme), `tolerance` (1e-5).
334
+
335
+ **What comes back.** `volume` (mm³), `mass` (kg, with a density), `members` (thickest first: area, each case's force,
336
+ tension positive, and `kind`), `nodes` (those the members meet at, with the loaded and supported ones), `candidates`
337
+ (the ground structure's members), `programme` (how many the last programme held), `rounds`, `strain` (the largest
338
+ virtual strain of any candidate over its limit: 1 at most, which proves no left-out member would lower the volume),
339
+ `left` (the volume share under `keep`) and `virtual` (each case's virtual displacements by node, the programme's
340
+ dual). With several cases the areas are unique but the forces in a case may not be (a member thicker than one case
341
+ needs can carry more or less in it): `members[].forces` is one set the strengths allow. For the forces the built frame
342
+ will carry, solve it (`layoutFrame`, then `frame().statics`) and give them to `layoutJoints`.
343
+
344
+ **Handing it on.** `layoutFrame(result, { material, section, ends })` is the layout as a frame model, each member a
345
+ solid round bar of its area (or `section`), joints `'rigid'` (welded, the default) or `'pinned'`, a flat layout held
346
+ out of its plane at its supports, and `cases` as `sizing` takes them. `layoutJoints(result, { material, diameters,
347
+ forces, stub, cell, volume, nodes })` gives each joint (every node where two members or more meet, or those named) as
348
+ a problem file in the form `cad optimise` reads: a space round the node, each member a stub `stub` mm long (twice the
349
+ widest diameter), the stub carrying the most held (the frame beyond it) and the others loaded with their forces in
350
+ each case, plus any outside load at the node. A flat layout's joints are flat problems as thick as the widest tube.
351
+
352
+ **How it works.** Every pair of candidate nodes is a member unless it passes through a third node (two shorter ones
353
+ do the same), is longer than `reach` or enters an avoided ball. The least volume is a linear programme in the areas
354
+ and the forces; it is solved by a primal-dual interior point method, the normal equations' members' rows eliminated
355
+ first so the dense matrix is only the equilibrium rows (free freedoms times cases). The first programme holds each
356
+ node's nearest candidates. Its dual is a virtual displacement field; any left-out member it would strain past its
357
+ limit would lower the volume, so the most strained are added and the programme solved again, until none is. The
358
+ answer is then the least over every candidate (the `strain` figure is the proof), while the programme holds a few
359
+ percent of them.
360
+
361
+ | What | Formula | Source |
362
+ |---|---|---|
363
+ | 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) |
364
+ | 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 |
365
+ | 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 |
366
+ | 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) |
367
+ | 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 |
368
+ | Members through a node | From each node, only the nearest node in each direction | Gilbert and Tyas |
369
+
370
+ **Tested** against hand calculations, each to rounding: two bars to two pins (8333.3 mm³, 833.3 N each), the same
371
+ weaker in compression (12500 mm³), a tripod in space (5625 mm³, 375 N a leg), two load cases sharing areas (3000 mm³,
372
+ not the 4000 of each alone); and against Michell's closed form for a couple carried between two circles (Michell
373
+ 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
374
+ falling fourfold as the step halves (straight members where his spirals curve). Member adding gives the same volume
375
+ as every candidate in one programme, alone and with two cases. The 32-to-a-ring wheel (224 nodes, 23728
376
+ candidates) takes about half a second on a laptop; the bicycle frame example (`examples/bicycle-frame`, 61 nodes and 1242 candidates,
377
+ three cases) about 4 seconds.
378
+
379
+ **Limits.**
380
+
381
+ - Pin-jointed and plastic: each member is as thick as its force needs, with nothing for buckling or bending. Size the
382
+ result (`layoutFrame` and `sizing`), which checks both.
383
+ - The node positions are fixed: a finer grid gives a better layout, slowly (the dense matrix grows with the free
384
+ freedoms times the cases: a few thousand rows is the practical most).
385
+ - With several cases, the forces within a case may not be unique (above), and members of equal merit may share a
386
+ load: a joint cost (`joint`) settles on fewer.
387
+ - A flat layout's members may cross without meeting (a node is needed where they cross to join them).
388
+ - The joints' problems carry the members' forces as point loads at the stubs' ends, held at one stub: the joint's own
389
+ stiffness against the frame's is not modelled.
390
+
280
391
  ## Sources
281
392
 
282
393
  - Amir, Aage, Lazarov (2014). On multigrid-CG for efficient topology optimization. *Structural and Multidisciplinary
@@ -288,10 +399,21 @@ member's face by its width keep their drawn offsets. The search is over the list
288
399
  - Cook, Malkus, Plesha, Witt (2002). *Concepts and Applications of Finite Element Analysis*, 4th ed. Wiley.
289
400
  - Cuthill, McKee (1969). Reducing the bandwidth of sparse symmetric matrices. *Proceedings of the 24th National
290
401
  Conference of the ACM*, 157–172.
402
+ - Dorn, Gomory, Greenberg (1964). Automatic design of optimal structures. *Journal de Mécanique* 3, 25–52.
291
403
  - Friedman, Kosmatka (1993). An improved two-node Timoshenko beam finite element. *Computers and Structures* 47,
292
404
  473–481.
405
+ - Gilbert, Tyas (2003). Layout optimization of large-scale pin-jointed frames. *Engineering Computations* 20,
406
+ 1044–1064.
293
407
  - Guyan (1965). Reduction of stiffness and mass matrices. *AIAA Journal* 3, 380.
408
+ - Hemp (1973). *Optimum Structures*. Clarendon Press, Oxford.
294
409
  - McGuire, Gallagher, Ziemian (2000). *Matrix Structural Analysis*, 2nd ed. Wiley.
410
+ - Mehrotra (1992). On the implementation of a primal-dual interior point method. *SIAM Journal on Optimization* 2,
411
+ 575–601.
412
+ - Michell (1904). The limits of economy of material in frame-structures. *Philosophical Magazine* 8, 589–597.
413
+ - Nocedal, Wright (2006). *Numerical Optimization*, 2nd ed. Springer.
414
+ - Parkes (1975). Joints in optimum frameworks. *International Journal of Solids and Structures* 11, 1017–1022.
295
415
  - Przemieniecki (1968). *Theory of Matrix Structural Analysis*. McGraw-Hill.
296
416
  - Timoshenko, Gere (1961). *Theory of Elastic Stability*, 2nd ed. McGraw-Hill.
297
417
  - Young, Budynas (2002). *Roark's Formulas for Stress and Strain*, 7th ed. McGraw-Hill.
418
+ - Zhang (1998). Solving large-scale linear programs by interior-point methods under the MATLAB environment.
419
+ *Optimization Methods and Software* 10, 1–31.
package/frame.d.mts CHANGED
@@ -18,19 +18,21 @@ export function elementMatrices(section: FrameSection, material: FrameMaterial,
18
18
  /**
19
19
  * A frame, read, checked and factorised once, ready for its solves. What is wrong with the model is said here, by
20
20
  * name, before any solve: each refusal is an Error with a `code` ("fea.frame." then node, length, section, material,
21
- * axes, join, support, load, mass, input, unheld or mechanism; buckling adds compression).
21
+ * axes, join, support, load, mass, input, unheld or mechanism; buckling adds compression, and sizing fit).
22
22
  * @param {FrameModel} model
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
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[], loose: { node: string, freedom: string }[] }}
28
+ * freedoms: number, nodes: string[], loose: { node: string, freedom: string }[], mechanisms: { node: string, freedom: string, shape: Record<string, Six> }[] }}
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
31
  * for vibration; fewer come back if the frame has fewer). freedoms: how many unknowns were solved for. loose: the
32
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
33
+ * with them held, as the loads do no work there. mechanisms: for each held freedom, the way the frame moves
34
+ * there with nothing resisting, as each node's six (its largest movement 1, or its largest turn 1 where nothing
35
+ * moves): a frame in one plane on pinned feet leans over out of it, a strut pinned at both ends spins. The modes count them free: each way that moves mass unresisted
34
36
  * is a mode of 0 Hz (marked free), and the rest are the frame's own, whatever freedom was held. Buckling where the
35
37
  * loads lean the frame that way (its squeezed members turning with it) gives a factor of 0, the frame tipping over
36
38
  * before anything buckles, with the ways named as `tipped`; where the loads pull it back (a frame hanging from its
@@ -77,6 +79,11 @@ export function frame(model: FrameModel, o?: {
77
79
  node: string;
78
80
  freedom: string;
79
81
  }[];
82
+ mechanisms: {
83
+ node: string;
84
+ freedom: string;
85
+ shape: Record<string, Six>;
86
+ }[];
80
87
  };
81
88
  /**
82
89
  * The same frame with every element cut into `pieces` equal lengths, for buckling and modes: one element cannot bow
@@ -100,15 +107,21 @@ export function subdivide(model: FrameModel, pieces?: number): FrameModel;
100
107
  * @param {FrameModel | FrameModel[]} model the frame; or a list, the first the frame and the rest the same frame
101
108
  * joined other ways (its joins rigid), whose stress is checked too, as a join's moment grows as it stiffens
102
109
  * @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> }[],
110
+ * fits?: (design: Record<string, string>) => { where: string, why: string }[],
111
+ * limits: SizingLimits, cases?: { label?: string, loads?: FrameLoad[], masses?: Record<string, number>, inertia?: Record<string, number>, gravity?: Vec3, limits?: string[] }[],
104
112
  * by?: 'mass' | 'cost', pieces?: number, search?: 'every' | 'steps', every?: number }} o
105
113
  * 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)
114
+ * choices a group may take, by name (all of them if left out); fits: whether a design's choices go together, given
115
+ * each group's choice by name: what does not (a join between two groups that one's choice cannot make with the
116
+ * other's), each { where, why }, none where it fits; a design that does not fit is never solved, and a group
117
+ * whose next lighter choice does not fit says so as the limit that set it (limit 'fit'); cases: load cases (the
118
+ * model's own if left out), loads and masses as statics takes them, inertia: masses whose weight is already in
119
+ * loads, which ring in the modes only, gravity: the case's own (a side push alone: [0, 0, 0]), and limits: the
120
+ * limits it is held to, by name (every limit where left out; a deflection limit's own cases narrow it further);
121
+ * by: what is least (mass); pieces: each member cut into this many for buckling and modes (4)
109
122
  * @returns {{ ok: boolean, by: 'mass' | 'cost', search: 'every' | 'steps', tried: number, total: number,
110
123
  * 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 }[],
124
+ * lighter: string | null, governs: (SizingCheck & { lighter: string, broken: number }) | { limit: 'fit', where: string, why: string, lighter: string, broken: null } | null, margin: number | null }[],
112
125
  * checks: SizingCheck[], worst: SizingCheck | null, model: FrameModel }}
113
126
  * ok: the limits are met (else the design that came nearest, and its checks say by how much); total: kg (or cost) of
114
127
  * the grouped members; tried: designs solved; each group's length (mm), mass (kg) and cost; lighter: the next choice
@@ -119,12 +132,18 @@ export function sizing(model: FrameModel | FrameModel[], o?: {
119
132
  groups: Record<string, (string | number)[]>;
120
133
  choices: SizingChoice[];
121
134
  only?: Record<string, string[]>;
135
+ fits?: (design: Record<string, string>) => {
136
+ where: string;
137
+ why: string;
138
+ }[];
122
139
  limits: SizingLimits;
123
140
  cases?: {
124
141
  label?: string;
125
142
  loads?: FrameLoad[];
126
143
  masses?: Record<string, number>;
127
144
  inertia?: Record<string, number>;
145
+ gravity?: Vec3;
146
+ limits?: string[];
128
147
  }[];
129
148
  by?: "mass" | "cost";
130
149
  pieces?: number;
@@ -147,7 +166,13 @@ export function sizing(model: FrameModel | FrameModel[], o?: {
147
166
  governs: (SizingCheck & {
148
167
  lighter: string;
149
168
  broken: number;
150
- }) | null;
169
+ }) | {
170
+ limit: "fit";
171
+ where: string;
172
+ why: string;
173
+ lighter: string;
174
+ broken: null;
175
+ } | null;
151
176
  margin: number | null;
152
177
  }[];
153
178
  checks: SizingCheck[];
package/frame.mjs CHANGED
@@ -449,19 +449,21 @@ const condensedLoad = (el, fb) => { if (!el.T) return fb; const fc = new Float64
449
449
  /**
450
450
  * A frame, read, checked and factorised once, ready for its solves. What is wrong with the model is said here, by
451
451
  * name, before any solve: each refusal is an Error with a `code` ("fea.frame." then node, length, section, material,
452
- * axes, join, support, load, mass, input, unheld or mechanism; buckling adds compression).
452
+ * axes, join, support, load, mass, input, unheld or mechanism; buckling adds compression, and sizing fit).
453
453
  * @param {FrameModel} model
454
454
  * @param {{ shear?: boolean }} [o] shear: false ignores the sections' shear areas (Euler-Bernoulli beams)
455
455
  * @returns {{
456
456
  * statics: (o?: { loads?: FrameLoad[], gravity?: Vec3, masses?: Record<string, number>, samples?: number }) => StaticResult,
457
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 }[] },
458
458
  * modes: (o?: { count?: number, masses?: Record<string, number> }) => { frequencies: number[], modes: VibrationMode[] },
459
- * freedoms: number, nodes: string[], loose: { node: string, freedom: string }[] }}
459
+ * freedoms: number, nodes: string[], loose: { node: string, freedom: string }[], mechanisms: { node: string, freedom: string, shape: Record<string, Six> }[] }}
460
460
  * statics, buckling and modes use the model's own loads, gravity and masses unless given others (another load case
461
461
  * on the same factorisation). samples: stations along each element (11). count: how many modes (1 for buckling, 6
462
462
  * for vibration; fewer come back if the frame has fewer). freedoms: how many unknowns were solved for. loose: the
463
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
464
+ * with them held, as the loads do no work there. mechanisms: for each held freedom, the way the frame moves
465
+ * there with nothing resisting, as each node's six (its largest movement 1, or its largest turn 1 where nothing
466
+ * moves): a frame in one plane on pinned feet leans over out of it, a strut pinned at both ends spins. The modes count them free: each way that moves mass unresisted
465
467
  * is a mode of 0 Hz (marked free), and the rest are the frame's own, whatever freedom was held. Buckling where the
466
468
  * loads lean the frame that way (its squeezed members turning with it) gives a factor of 0, the frame tipping over
467
469
  * before anything buckles, with the ways named as `tipped`; where the loads pull it back (a frame hanging from its
@@ -683,7 +685,9 @@ export function frame(model, o = {}) {
683
685
  return { frequencies: found.map((m) => m.frequency), modes: found };
684
686
  }
685
687
 
686
- return { statics, buckling, modes, freedoms: n, nodes: ids, loose };
688
+ // each way the frame moves unresisted, as each node's six (its largest movement 1): what a caller reads to say how it moves
689
+ const mechanisms = ways.map((w) => ({ node: w.node, freedom: w.freedom, shape: shapeOf(w.v) }));
690
+ return { statics, buckling, modes, freedoms: n, nodes: ids, loose, mechanisms };
687
691
  }
688
692
 
689
693
  /**
@@ -770,7 +774,7 @@ export function subdivide(model, pieces = 4) {
770
774
  const dot = (u, v) => u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
771
775
  const named = (v, table) => (typeof v === 'string' ? table?.[v] : v);
772
776
  const SIZE_LIMITS = ['deflection', 'stress', 'buckling', 'frequency'];
773
- const SIZE_KEYS = ['groups', 'choices', 'only', 'limits', 'cases', 'bounds', 'by', 'pieces', 'search', 'every'];
777
+ const SIZE_KEYS = ['groups', 'choices', 'only', 'fits', 'limits', 'cases', 'bounds', 'by', 'pieces', 'search', 'every'];
774
778
 
775
779
  /**
776
780
  * The lightest section for each group of members that meets the limits: each group (members that must match, a pair
@@ -785,15 +789,21 @@ const SIZE_KEYS = ['groups', 'choices', 'only', 'limits', 'cases', 'bounds', 'by
785
789
  * @param {FrameModel | FrameModel[]} model the frame; or a list, the first the frame and the rest the same frame
786
790
  * joined other ways (its joins rigid), whose stress is checked too, as a join's moment grows as it stiffens
787
791
  * @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> }[],
792
+ * fits?: (design: Record<string, string>) => { where: string, why: string }[],
793
+ * limits: SizingLimits, cases?: { label?: string, loads?: FrameLoad[], masses?: Record<string, number>, inertia?: Record<string, number>, gravity?: Vec3, limits?: string[] }[],
789
794
  * by?: 'mass' | 'cost', pieces?: number, search?: 'every' | 'steps', every?: number }} o
790
795
  * 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)
796
+ * choices a group may take, by name (all of them if left out); fits: whether a design's choices go together, given
797
+ * each group's choice by name: what does not (a join between two groups that one's choice cannot make with the
798
+ * other's), each { where, why }, none where it fits; a design that does not fit is never solved, and a group
799
+ * whose next lighter choice does not fit says so as the limit that set it (limit 'fit'); cases: load cases (the
800
+ * model's own if left out), loads and masses as statics takes them, inertia: masses whose weight is already in
801
+ * loads, which ring in the modes only, gravity: the case's own (a side push alone: [0, 0, 0]), and limits: the
802
+ * limits it is held to, by name (every limit where left out; a deflection limit's own cases narrow it further);
803
+ * by: what is least (mass); pieces: each member cut into this many for buckling and modes (4)
794
804
  * @returns {{ ok: boolean, by: 'mass' | 'cost', search: 'every' | 'steps', tried: number, total: number,
795
805
  * 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 }[],
806
+ * lighter: string | null, governs: (SizingCheck & { lighter: string, broken: number }) | { limit: 'fit', where: string, why: string, lighter: string, broken: null } | null, margin: number | null }[],
797
807
  * checks: SizingCheck[], worst: SizingCheck | null, model: FrameModel }}
798
808
  * ok: the limits are met (else the design that came nearest, and its checks say by how much); total: kg (or cost) of
799
809
  * the grouped members; tried: designs solved; each group's length (mm), mass (kg) and cost; lighter: the next choice
@@ -841,6 +851,7 @@ export function sizing(model, o = {}) {
841
851
  groups.push({ name, members: list, idx, allowed });
842
852
  }
843
853
  for (const k of Object.keys(o.only ?? {})) if (!groups.some((g) => g.name === k)) refuse('input', `only names group ${said(k)}, and there is no such group`);
854
+ if (o.fits != null && typeof o.fits !== 'function') refuse('input', `fits is a function of a design (each group's choice by name) that lists what does not go together, each { where, why } (got ${said(o.fits)})`);
844
855
  // the limits
845
856
  const L = o.limits;
846
857
  if (!L || typeof L !== 'object' || !Object.keys(L).length) refuse('input', `limits is { ${SIZE_LIMITS.join(', ')} }: at least one`);
@@ -852,6 +863,7 @@ export function sizing(model, o = {}) {
852
863
  if (!d || typeof d !== 'object') refuse('input', `limits.deflection ${i + 1} is { node, limit } or { member, limit, from, to } (got ${said(d)})`);
853
864
  pos(d.limit, `limits.deflection ${i + 1}'s limit (mm)`);
854
865
  if (d.along != null && !(isVec3(d.along) && Math.hypot(...d.along) > 0)) refuse('input', `limits.deflection ${i + 1}'s along is a direction [x, y, z] (got ${said(d.along)})`);
866
+ if (d.cases != null && !(Array.isArray(d.cases) && d.cases.length && d.cases.every((c) => typeof c === 'string'))) refuse('input', `limits.deflection ${i + 1}'s cases is a list of the load cases it holds in, by label (got ${said(d.cases)})`);
855
867
  const along = d.along ? d.along.map((v) => v / Math.hypot(...d.along)) : g0;
856
868
  if (d.node != null) { nodePos(d.node); return { ...d, along }; }
857
869
  const mine = els.filter((e, k) => String(e.of ?? e.id ?? k) === String(d.member));
@@ -862,8 +874,15 @@ export function sizing(model, o = {}) {
862
874
  if (L.stress) pos(L.stress.margin, 'limits.stress.margin');
863
875
  if (L.buckling) { pos(L.buckling.factor, 'limits.buckling.factor'); if (L.buckling.euler != null) pos(L.buckling.euler, 'limits.buckling.euler'); }
864
876
  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 }));
877
+ const cases = (o.cases ?? [{}]).map((c, i) => ({ label: c.label ?? (o.cases ? `case ${i + 1}` : 'as given'), loads: c.loads, masses: c.masses, inertia: c.inertia, gravity: c.gravity, limits: c.limits }));
866
878
  if (!cases.length) refuse('input', 'cases is a list of load cases, at least one');
879
+ for (const c of cases) {
880
+ if (c.gravity != null && !isVec3(c.gravity)) refuse('input', `case ${said(c.label)}'s gravity is [x, y, z] in m/s² (got ${said(c.gravity)})`);
881
+ if (c.limits != null && !(Array.isArray(c.limits) && c.limits.length && c.limits.every((k) => SIZE_LIMITS.includes(k)))) refuse('input', `case ${said(c.label)}'s limits is a list of the limits it is held to: ${SIZE_LIMITS.join(', ')} (got ${said(c.limits)})`);
882
+ }
883
+ for (const [i, d] of deflection.entries()) for (const c of d.cases ?? []) if (!cases.some((q) => q.label === c)) refuse('input', `limits.deflection ${i + 1} names case ${said(c)}, and there is no such case (cases: ${cases.map((q) => q.label).join(', ')})`);
884
+ // which cases each limit is held in: a case's own list, then a deflection limit's
885
+ const holds = (c, limit) => !c.limits || c.limits.includes(limit), stCase = (c) => ({ loads: c.loads, masses: c.masses, ...(c.gravity ? { gravity: c.gravity } : {}) });
867
886
 
868
887
  // each group's choices, lightest first, and what one weighs and costs over the group's length
869
888
  const lengthOf = (i) => { const e = els[i], a = nodePos(e.a), b = nodePos(e.b); return Math.hypot(...a.map((v, k) => v - b[k])); };
@@ -897,10 +916,12 @@ export function sizing(model, o = {}) {
897
916
  if (!quick && memo.has(pick.join(',')) && memo.get(pick.join(',')).complete) return memo.get(pick.join(','));
898
917
  tried++;
899
918
  const m = apply(base, pick), checks = [], worse = (c) => { const was = checks.find((q) => q.limit === c.limit && q.where === c.where); if (!was) checks.push(c); else if (c.ratio > was.ratio) Object.assign(was, c); };
900
- const solved = frame(m), stats = cases.map((c) => solved.statics({ loads: c.loads, masses: c.masses }));
919
+ const solved = frame(m), stats = cases.map((c) => solved.statics(stCase(c)));
901
920
  // deflection
902
921
  stats.forEach((s, ci) => {
922
+ if (!holds(cases[ci], 'deflection')) return;
903
923
  for (const d of deflection) {
924
+ if (d.cases && !d.cases.includes(cases[ci].label)) continue;
904
925
  let v = 0;
905
926
  const along = (u) => Math.abs(d.along ? dot(u, d.along) : Math.hypot(...u));
906
927
  if (d.node != null) v = along(s.displacements[d.node].slice(0, 3));
@@ -910,8 +931,8 @@ export function sizing(model, o = {}) {
910
931
  });
911
932
  // stress, in the frame and every other way of joining it
912
933
  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) => {
934
+ const sets = [{ m, stats }, ...models.slice(1).map((b) => { const mb = apply(b, pick), fb = frame(mb); return { m: mb, stats: cases.map((c) => (holds(c, 'stress') ? fb.statics(stCase(c)) : null)) }; })];
935
+ for (const { m: mm, stats: ss } of sets) ss.forEach((s, ci) => holds(cases[ci], 'stress') && s.elements.forEach((r, i) => {
915
936
  const e = mm.elements[i], st = strengthOf(mm, e);
916
937
  if (!r.stress || !st) return;
917
938
  worse({ limit: 'stress', where: memberOf(e, i), value: r.stress.peak, allowed: st / L.stress.margin, ratio: (r.stress.peak * L.stress.margin) / st, case: cases[ci].label });
@@ -920,19 +941,22 @@ export function sizing(model, o = {}) {
920
941
  // each member against Euler's load
921
942
  if (L.buckling?.euler) {
922
943
  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); }));
944
+ const grouped = new Set(groups.flatMap((g) => g.idx)), counted = new Set();
945
+ // a member's length is the sum of its elements' lengths, each counted once, whichever cases hold buckling
946
+ stats.forEach((s, ci) => holds(cases[ci], 'buckling') && s.elements.forEach((r, i) => { if (!grouped.has(i)) return; const id = memberOf(m.elements[i], i), p = per.get(id) ?? { N: 0, L: 0, I: Infinity, E: 0, ci }; if (!counted.has(i)) { counted.add(i); p.L += r.length; } const sec = named(m.elements[i].section, m.sections), mat = named(m.elements[i].material, m.materials); p.I = Math.min(p.I, sec.Iy, sec.Iz); p.E = mat.E; if (-r.axial > p.N) { p.N = -r.axial; p.ci = ci; } per.set(id, p); }));
925
947
  for (const [id, p] of per) if (p.N > 0) { const Pcr = (Math.PI ** 2 * p.E * p.I) / (L.buckling.euler * p.L) ** 2; worse({ limit: 'buckling', where: `${id} (Euler)`, value: Pcr / p.N, allowed: L.buckling.factor, ratio: (L.buckling.factor * p.N) / Pcr, case: cases[p.ci].label }); }
926
948
  }
927
949
  const broke = () => checks.some((c) => c.ratio > 1);
928
950
  if (quick && broke()) { const r = { checks, ok: false, complete: false }; memo.set(key, r); return r; }
929
951
  const fine = (L.buckling || L.frequency) ? frame(subdivide(m, pieces)) : null;
930
952
  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 }); }
953
+ if (!holds(c, 'buckling')) return;
954
+ try { const f = fine.buckling({ ...stCase(c), count: 1 }).factors[0]; worse({ limit: 'buckling', where: 'frame', value: f, allowed: L.buckling.factor, ratio: L.buckling.factor / f, case: c.label }); }
932
955
  catch (e) { if (e.code !== 'fea.frame.compression') throw e; }
933
956
  });
934
957
  if (quick && broke()) { const r = { checks, ok: false, complete: false }; memo.set(key, r); return r; }
935
958
  if (L.frequency) cases.forEach((c) => {
959
+ if (!holds(c, 'frequency')) return;
936
960
  const masses = { ...(c.masses ?? base.masses ?? {}) };
937
961
  for (const [n, kg] of Object.entries(c.inertia ?? {})) masses[n] = (masses[n] ?? 0) + kg;
938
962
  const hz = fine.modes({ count: 1, masses }).frequencies[0];
@@ -943,6 +967,20 @@ export function sizing(model, o = {}) {
943
967
  return r;
944
968
  };
945
969
  const worstOf = (checks) => checks.reduce((p, q) => (!p || q.ratio > p.ratio ? q : p), null);
970
+ // what does not go together in a design (o.fits), asked once a design: a design that does not fit is never solved
971
+ const fitMemo = new Map(), nameOf = (pick) => Object.fromEntries(groups.map((g, k) => [g.name, g.list[pick[k]].name]));
972
+ const misfits = (pick) => {
973
+ if (!o.fits) return [];
974
+ const key = pick.join(',');
975
+ if (!fitMemo.has(key)) {
976
+ const r = o.fits(nameOf(pick));
977
+ if (!Array.isArray(r) || !r.every((x) => x && typeof x.where === 'string' && typeof x.why === 'string')) refuse('input', `fits returns a list of what does not go together, each { where, why }, empty where the design fits (got ${said(r)})`);
978
+ fitMemo.set(key, r);
979
+ }
980
+ return fitMemo.get(key);
981
+ };
982
+ const fitting = (pick) => !misfits(pick).length;
983
+ const noneFits = (pick) => { const m = misfits(pick)[0]; refuse('fit', `no design of these choices goes together: ${m ? `${m.where}: ${m.why}` : 'every one is refused by fits'}. Give the groups choices that fit each other (only), or join them another way`, { misfits: misfits(pick) }); };
946
984
  // how far past the limits a design is in all: what still separates two designs whose worst figures tie
947
985
  const excess = (checks) => checks.reduce((t, c) => t + Math.max(0, c.ratio - 1), 0);
948
986
 
@@ -957,6 +995,7 @@ export function sizing(model, o = {}) {
957
995
  all.sort((p, q) => measure(p) - measure(q));
958
996
  const near = [];
959
997
  for (const p of all) {
998
+ if (!fitting(p)) continue;
960
999
  const r = evaluate(p, true);
961
1000
  if (r.ok && evaluate(p).ok) { pick = p; break; }
962
1001
  near.push({ p, low: worstOf(r.checks)?.ratio ?? 0 });
@@ -964,13 +1003,31 @@ export function sizing(model, o = {}) {
964
1003
  // nothing fits: the nearest by every limit's figure, not by the quick look that stops at the first stage that
965
1004
  // breaks one. The quick look's worst is never more than the whole's, so designs are taken in its order and
966
1005
  // stop once no later one can come nearer
1006
+ if (!pick && !near.length) noneFits(all[0]);
967
1007
  if (!pick) for (const c of near.sort((a, b) => a.low - b.low)) {
968
1008
  if (best && c.low >= best.w.ratio) break;
969
1009
  const w = worstOf(evaluate(c.p).checks);
970
1010
  if (!best || (w && w.ratio < best.w.ratio)) best = { p: c.p, w };
971
1011
  }
972
1012
  } else {
1013
+ // the lightest design that fits, from q up: each group at its choice in q or a heavier one, group k kept as it is
1014
+ // (-1: none kept), found lightest first over the designs from q (each group's list is in order of weight); null
1015
+ // where none is found in a few thousand
1016
+ const repair = (q, keep) => {
1017
+ if (fitting(q)) return q;
1018
+ const seen = new Set([q.join(',')]), open = [{ t: q, w: measure(q) }];
1019
+ for (let n = 0; open.length && n < 4000; n++) {
1020
+ let i = 0;
1021
+ for (let k = 1; k < open.length; k++) if (open[k].w < open[i].w) i = k;
1022
+ const { t } = open.splice(i, 1)[0];
1023
+ if (fitting(t)) return t;
1024
+ groups.forEach((g, k) => { if (k === keep || t[k] + 1 >= sizes[k]) return; const u = [...t]; u[k]++; const key = u.join(','); if (!seen.has(key)) { seen.add(key); open.push({ t: u, w: measure(u) }); } });
1025
+ }
1026
+ return null;
1027
+ };
973
1028
  let p = groups.map(() => 0);
1029
+ // a start that fits, from the lightest
1030
+ if (!fitting(p)) p = repair(p, -1) ?? noneFits(p);
974
1031
  for (let n = 0; n < 100 * groups.length; n++) {
975
1032
  const r = evaluate(p), w = worstOf(r.checks)?.ratio ?? 0, e = excess(r.checks);
976
1033
  if (r.ok) break;
@@ -983,7 +1040,10 @@ export function sizing(model, o = {}) {
983
1040
  let found = null;
984
1041
  for (let j = p[k] + 1; j < sizes[k]; j++) {
985
1042
  if (found != null && g.price(g.list[j]) > found * (1 + 1e-9)) break;
986
- const q = [...p]; q[k] = j;
1043
+ let q = [...p]; q[k] = j;
1044
+ // (a choice that does not go with the others' takes them along: the others made to fit it)
1045
+ if (!fitting(q)) q = repair(q, k);
1046
+ if (!q) continue;
987
1047
  const rq = evaluate(q), wq = worstOf(rq.checks)?.ratio ?? 0, eq = excess(rq.checks), dm = Math.max(measure(q) - measure(p), 1e-12);
988
1048
  const better = wq < w * (1 - 1e-9) ? (w - wq) / dm : wq <= w * (1 + 1e-9) && eq < e * (1 - 1e-9) ? (1e-9 * (e - eq)) / dm : null;
989
1049
  if (better != null) { found ??= g.price(g.list[j]); if (!step || better > step.gain) step = { q, gain: better }; }
@@ -997,7 +1057,7 @@ export function sizing(model, o = {}) {
997
1057
  for (let moved = true; moved;) {
998
1058
  moved = false;
999
1059
  const order = groups.map((g, k) => k).sort((a, b) => groups[b].price(groups[b].list[p[b]]) - groups[a].price(groups[a].list[p[a]]));
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; } }
1060
+ for (const k of order) for (let i = 0; i < p[k]; i++) { let q = [...p]; q[k] = i; if (!fitting(q)) q = repair(q, k); if (q && measure(q) < measure(p) * (1 - 1e-12) && evaluate(q).ok) { p = q; moved = true; break; } }
1001
1061
  }
1002
1062
  pick = p;
1003
1063
  } else best = { p, w: worstOf(evaluate(p).checks) };
@@ -1009,7 +1069,11 @@ export function sizing(model, o = {}) {
1009
1069
  // the next lighter choice: the heaviest that weighs less (one of the same weight, a section turned, is no lighter)
1010
1070
  const c = g.list[pick[k]], at = g.list.findLastIndex((x) => g.price(x) < g.price(c) * (1 - 1e-9)), lighter = at >= 0 ? g.list[at] : null;
1011
1071
  let governs = null, margin = null;
1012
- if (lighter) {
1072
+ if (lighter && !fitting(Object.assign([...pick], { [k]: at }))) {
1073
+ // the lighter choice does not go with the others: that, not a limit, set this group
1074
+ const m = misfits(Object.assign([...pick], { [k]: at }))[0];
1075
+ governs = { limit: 'fit', where: m.where, why: m.why, lighter: lighter.name, broken: null };
1076
+ } else if (lighter) {
1013
1077
  const q = [...pick]; q[k] = at;
1014
1078
  const w = worstOf(evaluate(q).checks.filter((x) => x.ratio > 1));
1015
1079
  if (w) { const now = final.checks.find((x) => x.limit === w.limit && x.where === w.where); governs = { ...(now ?? w), lighter: lighter.name, broken: w.ratio }; margin = now ? 1 / now.ratio : null; }