@rulecad/fea 0.2.13 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,33 @@
2
2
 
3
3
  What changed in each release, for someone upgrading a workspace.
4
4
 
5
+ ## 0.3.0: the stress at a part's surface, and a warning where the grid is too coarse to read it
6
+
7
+ ### Added
8
+
9
+ - `analyse()` returns `surface`: each solid cell's von Mises stress at the part's surface, beside `stress`. `stress` is read at each cell's centre, half a cell inside the part, so where the part bends it reads the peak stress low by about one cell's share of the member's depth: 27 to 30% low at the four cells through that the README recommends, 10% at ten. `surface` comes within 2% of beam theory from four cells through, in 2D and 3D. Read a part's strength from `surface`.
10
+ - `surfaceStress(g, u, modulus, nu, density)` gives the same reading for any solution, with each node's value as well as each cell's.
11
+ - `analyse()` returns `findings`: a warning (`fea.coarse-stress`, in the kit's shape `{ level, text, code, values, at, box }`) for each load whose peak stress is in a member under eight cells through, where even the surface reading can be a few percent out.
12
+ - The README's grid-fineness table now says how far each stress reading is out at each number of cells through the depth.
13
+
14
+ ### Changed
15
+
16
+ - The package's tests compare a cantilever's tip with beam theory including shear (Timoshenko's), and no longer check a field (`converged`) that `solve` never returned.
17
+
18
+ Upgrading: nothing changes for existing results. `stress`, `u`, `compliance` and `deflection` keep their values; `surface` and `findings` are new. A check that judges strength from `stress` reads low: move it to `surface` (the kit's own checks move in the next release). No printed size changes.
19
+
20
+ ## 0.2.14: motor reactions, racking and joins in frame sizing
21
+ ### Added
22
+
23
+ - `frame().mechanisms`: for each freedom a held frame (`loose: 'hold'`) holds, the way the frame moves there with
24
+ nothing resisting, as each node's six, so a caller can say how it moves (a portal tipping over out of its plane)
25
+ rather than name a freedom at a node.
26
+ - `sizing({ fits })`: a function of each group's choice that lists what does not go together (a join one profile
27
+ cannot make with another). Designs that do not fit are never solved; a group whose next lighter choice does not fit
28
+ says so (`governs.limit: 'fit'`, with where and why); none fitting is refused (`fea.frame.fit`).
29
+ - `sizing` cases take their own `gravity` (a side push alone) and `limits` (the limits they are held to), and a
30
+ deflection limit takes `cases`, the load cases it holds in: a racking sway held under a push alone.
31
+
5
32
  ## 0.2.13: frame layout optimisation
6
33
  ### Added
7
34
 
package/README.md CHANGED
@@ -18,7 +18,9 @@ load[2 * g.node(100, 5) + 1] = -10; // 10 N down at the right en
18
18
  const r = analyse({ grid: g, density: new Float64Array(1000).fill(1), material: { E: 2680, nu: 0.36 }, thickness: 5, fixed, loads: [load] });
19
19
  r.u[0]; // each node's movement: x at 2n, y at 2n + 1
20
20
  r.compliance[0]; // the load times how far it moved (N·mm): lower is stiffer
21
- r.stress[0]; // each cell's von Mises stress (MPa)
21
+ r.stress[0]; // each cell's von Mises stress (MPa) at its centre: reads bending stress low (see How fine a grid)
22
+ r.surface[0]; // each solid cell's von Mises stress (MPa) at the part's surface: use this for strength
23
+ r.findings; // [{ level, text, code, values, at, box }]: a warning where the peak stress is in a member under 8 cells through
22
24
  r.deflection[0]; // { most, at }: the largest movement of solid material, and where
23
25
  r.thin; // { share, cells }: how much of the part is in members under 4 cells thick (thinShare), where a cell's stiffness is rough
24
26
  ```
@@ -36,6 +38,17 @@ r.thin; // { share, cells }: how much of the part is in members under
36
38
  iterations, where plain `cg` takes 371.
37
39
  - **Solving again:** `solve(...)` returns `again(loads)`, which solves more right-hand sides on the same matrix,
38
40
  reusing its factorisation or preconditioner: an adjoint, for a gradient.
41
+ - **Stress at the surface:** `stress` is read at each cell's centre, half a cell inside the part. In bending the
42
+ stress peaks at the surface, so in a member n cells through the centre stress reads low by about one cell's share:
43
+ 27 to 30% low at 4 cells, 10% at 10. `surface` (and `surfaceStress(g, u, modulus, nu, density)`, which also gives
44
+ each node's value) reads each cell at its corners and averages each stress component over the solid cells round
45
+ each node. At a corner it takes two thirds of what the cell's strains say and one third of the stress that
46
+ reproduces the forces on the cell's corners: square cells bend a little too stiffly, so their strains alone read
47
+ low (6% at 4 cells in 3D), and the second reading errs the other way by about twice as much. A cell under half
48
+ density keeps its centre stress. `analyse` adds a warning to `findings` (code `fea.coarse-stress`) for each load
49
+ whose peak surface stress is in a member under 8 cells through, counted along the directions the stress changes
50
+ fastest there (the shortest of them). At a sharp inside corner, or a curved edge stepped into cells, the peak keeps rising as cells shrink:
51
+ the stress concentrates there beyond what any grid settles on, so read it with care (a real part has a fillet).
39
52
  - **Stress at a point:** `centreStress(h, nu, dim)` is the matrix from a cell's movements to the stress at its centre
40
53
  (for Young's modulus 1), and `vonMises(s, dim, grad)` gives von Mises stress and, optionally, its gradient. Stress
41
54
  limits in @rulecad/topopt use both.
@@ -51,22 +64,28 @@ r.thin; // { share, cells }: how much of the part is in members under
51
64
  memory (a few solves in sixty, more with more threads, none on Node 22 or 24), so there it is plain JavaScript
52
65
  under another name (its `name` says so).
53
66
 
54
- Tested against beam theory: a cantilever's tip moves within 1% of `F L³ / 3 E I` in 2D, and within 2% in 3D.
67
+ Tested against beam theory with shear (Timoshenko's, `F L³ / 3 E I + F L / κ G A`): a cantilever's tip moves within
68
+ 1% of it in 2D at 10 cells through, and within 3% in 3D at 8, never more. The surface stress of a cantilever 4, 8 or
69
+ 10 cells deep is tested within 5% of `M c / I` at mid-span and a beam's depth from the support, in 2D and 3D (it
70
+ comes within 2%); right at a clamped edge the stress concentrates, and beam theory doesn't hold.
55
71
  Multigrid is tested against the direct solver with stiffnesses a millionfold apart.
56
72
 
57
73
  **How fine a grid.** The cells are exact for a part that only stretches, and converge on beam theory with shear
58
74
  (Timoshenko's) as they shrink. What matters is how many cells cross the depth of whatever bends:
59
75
 
60
- | Cells through the depth | Too stiff by |
61
- |---|---|
62
- | 1 | about 32% |
63
- | 2 | about 11% |
64
- | 4 | about 3% |
65
- | 10 | under 1% |
76
+ | Cells through the depth | Too stiff by | `stress` (cell centres) reads low by | `surface` is out by |
77
+ |---|---|---|---|
78
+ | 1 | about 32% | about 94% | about 24% low |
79
+ | 2 | about 11% | about 55% | about 5% low |
80
+ | 4 | about 3% (4% in 3D) | about 27% (29% in 3D) | under 1% |
81
+ | 8 | about 1% | about 13% | about 1% high |
82
+ | 10 | under 1% | about 10% | about 1% high |
83
+ | 20 | under 0.5% | about 5% | under 1% high |
66
84
 
67
- So give every member that bends at least four cells, and check a final shape on cells half the size: if the
68
- stiffness moves by more than a few percent, the grid was too coarse. (Measured on cantilevers and a simply supported
69
- beam, in 2D and 3D.)
85
+ So give every member that bends at least four cells, read its strength from `surface`, not `stress`, and check a
86
+ final shape on cells half the size: if the stiffness or the peak stress moves by more than a few percent, the grid
87
+ was too coarse. (Stiffness measured on cantilevers and a simply supported beam, in 2D and 3D; stress on a cantilever
88
+ 100 × 10 mm at mid-span, against `M c / I`, in 2D, and in 3D where they differ.)
70
89
 
71
90
  ## Frames of beams
72
91
 
@@ -127,10 +146,11 @@ result carries its `axes`, so nothing has to be guessed.
127
146
  **What each solve returns.**
128
147
 
129
148
  - `frame(model, { shear })` reads and checks the model, assembles and factorises it, and returns `{ statics,
130
- buckling, modes, freedoms, nodes, loose }`. `shear: false` ignores the shear areas. `statics(model)`, `buckling(model)`
149
+ buckling, modes, freedoms, nodes, loose, mechanisms }`. `shear: false` ignores the shear areas. `statics(model)`, `buckling(model)`
131
150
  and `modes(model)` do it in one call. A model with `loose: 'hold'` is solved even where part of it can move with
132
151
  nothing resisting (a frame in one plane on pinned feet sways out of that plane; a beam pinned at both ends spins on
133
- its axis): each such freedom is held, `loose` names it by node, and a solve whose loads would do work moving the
152
+ its axis): each such freedom is held, `loose` names it by node, `mechanisms` gives the way the frame moves there
153
+ (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
134
154
  frame that way is refused (`fea.frame.mechanism`, with `driven: true`). The modes count those freedoms free:
135
155
  each way that moves mass unresisted comes back as a mode of 0 Hz, marked `free: true`, and the rest are the
136
156
  frame's own, whichever freedom was held. They are the modes of `K + s M` (s the held frame's lowest eigenvalue),
@@ -254,11 +274,12 @@ r.groups[0]; // { name: 'legs', choice: 'bar 10', lighter: null, governs: null
254
274
  | `groups` | `{ name: [members] }` | Each member an element's `id`, or the member its pieces came from (`of`). Members in no group keep their sections |
255
275
  | `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) |
256
276
  | `only` | `{ group: [choice names] }` | The choices a group may take (all of them if left out) |
257
- | `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 |
277
+ | `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 |
278
+ | `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) |
258
279
  | `limits.stress` | `{ margin }` | Each member's peak `abs(N)/A + abs(My)/Wy + abs(Mz)/Wz`, times the margin, under its material's strength |
259
280
  | `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 |
260
281
  | `limits.frequency` | `{ Hz }` | The lowest mode at least this |
261
- | `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 |
282
+ | `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) |
262
283
  | 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 |
263
284
 
264
285
  **The search.** With few designs (`every`, 512, or `search: 'every'`), every design is ranked by mass and solved in
@@ -266,15 +287,22 @@ that order until one meets every limit, which makes it the lightest; a design is
266
287
  (statics, then buckling, then modes) that breaks a limit. With more, `search: 'steps'`: from every group at its
267
288
  lightest, each group looks up its list for the lightest heavier choice that cuts the worst limit's use (passing over
268
289
  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
269
- 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
290
+ added mass steps up to it, until the limits are met (a choice that does not fit the others' takes them along: the
291
+ 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
270
292
  solve far fewer designs and land near the lightest, not always on it (a table in the tests: within a fifth).
271
293
 
272
294
  **What set each choice.** A group's `governs` is the limit its next lighter choice breaks with the other groups as
273
295
  chosen, the worst there by `broken` (its use of the limit, over 1). A choice of the same weight (the same section
274
296
  turned) is not lighter. `margin` is how many times inside that limit the chosen design is. A group at the lightest
275
- choice has no `governs`, and its margin is its own members' nearest check. Where no design meets the limits, `ok` is
297
+ choice has no `governs`, and its margin is its own members' nearest check. Where the next lighter choice does not go
298
+ with the others' (`fits` lists something), that set it: `governs` is `{ limit: 'fit', where, why, lighter }`, and the
299
+ margin is its own members' nearest check. Where no design meets the limits, `ok` is
276
300
  false and the result is the design that came nearest, with `worst` saying which limit it breaks and by how much.
277
301
 
302
+ **Designs that fit.** With `fits`, only designs whose choices go together are solved: the steps start from the
303
+ lightest design that fits, found lightest first. Where none of the list's designs fits, sizing is refused
304
+ (`fea.frame.fit`, with the first thing that does not fit).
305
+
278
306
  **Limits of sizing.** The geometry stays as drawn: a deeper section moves no node, so joints that hang off a
279
307
  member's face by its width keep their drawn offsets. The search is over the list given; it does not invent a section.
280
308
 
package/fea.d.mts CHANGED
@@ -60,14 +60,38 @@ export function vonMises(s: ArrayLike<number>, dim: 2 | 3, grad?: Float64Array):
60
60
  * @returns {Float64Array}
61
61
  */
62
62
  export function stress(g: Grid, u: Float64Array, modulus: Float64Array, nu: number): Float64Array;
63
+ /**
64
+ * The stress at the part's surface, where bending puts its peak. `stress` reads each cell at its centre, half a cell
65
+ * inside the surface: in a member n cells through it reads the bending stress low by about one cell's share (27% at 4
66
+ * cells, 10% at 10). This reads each cell's stress at its corners instead, averages each stress component over the
67
+ * solid cells (density 0.5 or more) round each node, and gives von Mises there (patch recovery). Averaging over the
68
+ * cells round a node cancels the false shear a square cell shows at its corners when it bends. At a corner the stress
69
+ * is two thirds the cell's strains read there, and one third the stress field that reproduces the forces on its corners
70
+ * (BALANCED_SHARE): the strains alone read low where the cells bend too stiffly. A 4-cell-deep cantilever's surface
71
+ * stress is within 2% of M c / I, in 2D and 3D, away from the clamped end. At a sharp inside corner, or a curved edge stepped into cells, the
72
+ * peak keeps rising as the cells shrink: the stress there is concentrated beyond what any grid settles on. A node
73
+ * with no solid cell round it is averaged over the cells it has.
74
+ * @param {Grid} g @param {Float64Array} u @param {Float64Array} modulus each cell's Young's modulus (MPa) @param {number} nu
75
+ * @param {ArrayLike<number>} [density] each cell's density, 0 to 1 (all solid if left out)
76
+ * @returns {{ nodes: Float64Array, cells: Float64Array }} nodes: von Mises (MPa) at each node; cells: for a solid cell,
77
+ * the largest of its corners' (its surface stress), and for a cell under 0.5, its centre stress (as `stress`)
78
+ */
79
+ export function surfaceStress(g: Grid, u: Float64Array, modulus: Float64Array, nu: number, density?: ArrayLike<number>): {
80
+ nodes: Float64Array;
81
+ cells: Float64Array;
82
+ };
63
83
  /**
64
84
  * Analyse a part: each cell's density (0 empty to 1 solid; Young's modulus scales with density^penal, never below
65
85
  * E × 1e-9 so empty cells don't leave the matrix singular), supports and loads. In 2D the part is a plate of the given
66
86
  * thickness; in 3D thickness is not used.
67
87
  * @param {{ grid: Grid, density: Float64Array, material: Material, thickness?: number, fixed: Uint8Array, loads: Float64Array[], penal?: number, method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend }} o
68
- * @returns {{ u: Float64Array[], compliance: number[], stress: Float64Array[], deflection: { most: number, at: number[] }[] }}
69
- * compliance: f · u per load (N·mm): the work the load does; lower is stiffer. deflection: the largest movement
70
- * of any node in solid material, and where.
88
+ * @returns {{ u: Float64Array[], thin: { share: number, cells: number }, compliance: number[], stress: Float64Array[], surface: Float64Array[], findings: { level: 'warn', text: string, code: string, values: { surface: number, centre: number, cells: number, need: number, load: number }, at: number[], box: { lo: number[], hi: number[] } }[], deflection: { most: number, at: number[] }[] }}
89
+ * compliance: f · u per load (N·mm): the work the load does; lower is stiffer. stress: each cell's von Mises stress
90
+ * (MPa) at its centre, which reads bending stress low by about one cell's share of the member's depth (27% at 4
91
+ * cells through, 10% at 10). surface: each solid cell's von Mises stress at its surface, the largest of its corners'
92
+ * (surfaceStress): within 2% of beam theory at 4 cells through; use it for strength. findings: a warning
93
+ * (fea.coarse-stress) for each load whose peak surface stress is in a member under 8 cells through. deflection: the
94
+ * largest movement of any node in solid material, and where.
71
95
  */
72
96
  export function analyse({ grid: g, density, material, thickness, fixed, loads, penal, method, backend }: {
73
97
  grid: Grid;
@@ -81,8 +105,30 @@ export function analyse({ grid: g, density, material, thickness, fixed, loads, p
81
105
  backend?: typeof jsBackend;
82
106
  }): {
83
107
  u: Float64Array[];
108
+ thin: {
109
+ share: number;
110
+ cells: number;
111
+ };
84
112
  compliance: number[];
85
113
  stress: Float64Array[];
114
+ surface: Float64Array[];
115
+ findings: {
116
+ level: "warn";
117
+ text: string;
118
+ code: string;
119
+ values: {
120
+ surface: number;
121
+ centre: number;
122
+ cells: number;
123
+ need: number;
124
+ load: number;
125
+ };
126
+ at: number[];
127
+ box: {
128
+ lo: number[];
129
+ hi: number[];
130
+ };
131
+ }[];
86
132
  deflection: {
87
133
  most: number;
88
134
  at: number[];
package/fea.mjs CHANGED
@@ -636,14 +636,191 @@ export function stress(g, u, modulus, nu) {
636
636
  return out;
637
637
  }
638
638
 
639
+ // The stress field a cell carries, as few terms as it has ways to deform (5 in 2D, 18 in 3D): each term a stress
640
+ // component times a product of the natural coordinates (Pian and Sumihara 1984 in 2D, Pian and Tong 1986 in 3D).
641
+ // Each term: [component, power of ξ, power of η, power of ζ].
642
+ const STRESS_TERMS = {
643
+ 2: [[0, 0, 0], [1, 0, 0], [2, 0, 0], [0, 0, 1], [1, 1, 0]].map(([c, a, b]) => [c, a, b, 0]),
644
+ 3: [[0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 1, 1], [1, 0, 0, 0], [1, 0, 0, 1], [1, 1, 0, 0], [1, 1, 0, 1],
645
+ [2, 0, 0, 0], [2, 1, 0, 0], [2, 0, 1, 0], [2, 1, 1, 0], [3, 0, 0, 0], [3, 0, 0, 1], [4, 0, 0, 0], [4, 1, 0, 0], [5, 0, 0, 0], [5, 0, 1, 0]],
646
+ };
647
+ const termsAt = (p, dim) => STRESS_TERMS[dim].map(([c, ...pow]) => [c, pow.slice(0, dim).reduce((f, k, a) => f * (k ? p[a] : 1), 1)]);
648
+
649
+ // For each corner of a cell of side 1 and modulus 1, the matrix (rows × cell dofs) from its movements to the stress at
650
+ // that corner, read from the forces the cell puts on its corners (K u) rather than from its strains: the stress field
651
+ // (in STRESS_TERMS) whose work over the cell's strains gives exactly those forces. The cells' forces balance the load,
652
+ // so across a section this field carries the whole bending moment, even where square cells bend too stiffly and their
653
+ // strains read low; but it puts too much of the moment at each cell's edges, so alone it reads high (by about 9% at 4
654
+ // cells through, 4% at 10). See surfaceStress.
655
+ const balanced = new Map();
656
+ function balancedCorners(nu, dim) {
657
+ const key = `${dim} ${nu}`;
658
+ if (balanced.has(key)) return balanced.get(key);
659
+ const m = CORNERS[dim].length * dim, n = STRESS_TERMS[dim].length, ke = cellStiffness(nu, dim), gp = 1 / Math.sqrt(3), w = 1 / (1 << dim);
660
+ const points = dim === 3 ? [-gp, gp].flatMap((a) => [-gp, gp].flatMap((b) => [-gp, gp].map((c) => [a, b, c]))) : [-gp, gp].flatMap((a) => [-gp, gp].map((b) => [a, b]));
661
+ const G = new Float64Array(n * m); // ∫ Pᵀ B over the cell: term t's work over dof a's strain
662
+ for (const p of points) {
663
+ const B = strains(p, 1, dim);
664
+ termsAt(p, dim).forEach(([c, v], t) => { for (let a = 0; a < m; a++) G[t * m + a] += w * v * B[c * m + a]; });
665
+ }
666
+ // R = (G Gᵀ)⁻¹ G ke: the terms whose forces Gᵀ β are the cell's K u (exactly: K u has no rigid part, and G's rows span the rest)
667
+ const A = new Float64Array(n * n), GK = new Float64Array(n * m);
668
+ for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) { let t = 0; for (let a = 0; a < m; a++) t += G[i * m + a] * G[j * m + a]; A[i * n + j] = t; }
669
+ for (let i = 0; i < n; i++) for (let b = 0; b < m; b++) { let t = 0; for (let a = 0; a < m; a++) t += G[i * m + a] * ke[a * m + b]; GK[i * m + b] = t; }
670
+ const R = solveDense(A, GK, n, m);
671
+ const out = CORNERS[dim].map((c) => {
672
+ const S = new Float64Array((dim === 3 ? 6 : 3) * m);
673
+ termsAt(c.map((x) => 2 * x - 1), dim).forEach(([comp, v], t) => { for (let a = 0; a < m; a++) S[comp * m + a] += v * R[t * m + a]; });
674
+ return S;
675
+ });
676
+ balanced.set(key, out);
677
+ return out;
678
+ }
679
+ // A X = B for a small dense A (n × n, symmetric positive definite) and B (n × m), by Gaussian elimination
680
+ function solveDense(A, B, n, m) {
681
+ const a = Float64Array.from(A), x = Float64Array.from(B);
682
+ for (let k = 0; k < n; k++) {
683
+ let piv = k;
684
+ for (let i = k + 1; i < n; i++) if (Math.abs(a[i * n + k]) > Math.abs(a[piv * n + k])) piv = i;
685
+ if (piv !== k) { for (let j = 0; j < n; j++) [a[k * n + j], a[piv * n + j]] = [a[piv * n + j], a[k * n + j]]; for (let j = 0; j < m; j++) [x[k * m + j], x[piv * m + j]] = [x[piv * m + j], x[k * m + j]]; }
686
+ for (let i = k + 1; i < n; i++) {
687
+ const f = a[i * n + k] / a[k * n + k];
688
+ if (!f) continue;
689
+ for (let j = k; j < n; j++) a[i * n + j] -= f * a[k * n + j];
690
+ for (let j = 0; j < m; j++) x[i * m + j] -= f * x[k * m + j];
691
+ }
692
+ }
693
+ for (let k = n - 1; k >= 0; k--) {
694
+ for (let j = 0; j < m; j++) { let t = x[k * m + j]; for (let i = k + 1; i < n; i++) t -= a[k * n + i] * x[i * m + j]; x[k * m + j] = t / a[k * n + k]; }
695
+ }
696
+ return x;
697
+ }
698
+
699
+ // How much of the force-balanced reading (balancedCorners) goes into the surface stress; the rest is the strain
700
+ // reading. Square cells bend too stiffly (3% at 4 cells through in 2D, 4% in 3D), so the strains read low (4% and 6%
701
+ // at 4 cells), and the force-balanced field reads high by about twice that: a third of one and two thirds of the other
702
+ // cancel the two errors. Measured on cantilevers and a beam under pure moment, 2D and 3D, Poisson's ratio 0 to 0.45, 4
703
+ // to 20 cells through: within 2% of beam theory at mid-span and a beam's depth from the support (test/surface-
704
+ // stress.test.mjs; right at a clamped edge the stress is concentrated, and reads higher as cells shrink). Both
705
+ // readings are exact for a cell in uniform stress, so the blend is too.
706
+ const BALANCED_SHARE = 1 / 3;
707
+
708
+ /**
709
+ * The stress at the part's surface, where bending puts its peak. `stress` reads each cell at its centre, half a cell
710
+ * inside the surface: in a member n cells through it reads the bending stress low by about one cell's share (27% at 4
711
+ * cells, 10% at 10). This reads each cell's stress at its corners instead, averages each stress component over the
712
+ * solid cells (density 0.5 or more) round each node, and gives von Mises there (patch recovery). Averaging over the
713
+ * cells round a node cancels the false shear a square cell shows at its corners when it bends. At a corner the stress
714
+ * is two thirds the cell's strains read there, and one third the stress field that reproduces the forces on its corners
715
+ * (BALANCED_SHARE): the strains alone read low where the cells bend too stiffly. A 4-cell-deep cantilever's surface
716
+ * stress is within 2% of M c / I, in 2D and 3D, away from the clamped end. At a sharp inside corner, or a curved edge stepped into cells, the
717
+ * peak keeps rising as the cells shrink: the stress there is concentrated beyond what any grid settles on. A node
718
+ * with no solid cell round it is averaged over the cells it has.
719
+ * @param {Grid} g @param {Float64Array} u @param {Float64Array} modulus each cell's Young's modulus (MPa) @param {number} nu
720
+ * @param {ArrayLike<number>} [density] each cell's density, 0 to 1 (all solid if left out)
721
+ * @returns {{ nodes: Float64Array, cells: Float64Array }} nodes: von Mises (MPa) at each node; cells: for a solid cell,
722
+ * the largest of its corners' (its surface stress), and for a cell under 0.5, its centre stress (as `stress`)
723
+ */
724
+ export function surfaceStress(g, u, modulus, nu, density) { return recover(g, u, modulus, nu, density, null); }
725
+ // surfaceStress, given the centre stress where it is already worked out (analyse)
726
+ function recover(g, u, modulus, nu, density, centres) {
727
+ const dim = g.dim, m = g.cellDofs, rows = dim === 3 ? 6 : 3, corners = CORNERS[dim], C = corners.length, D = elasticity(nu, dim);
728
+ // Each corner's matrix from the cell's movements to its stress there (modulus 1): D B at the corner, blended with the
729
+ // force-balanced field there (which scales as 1 / h, as B does)
730
+ const W = BALANCED_SHARE, bal = balancedCorners(nu, dim);
731
+ const S = corners.map((c, q) => {
732
+ const B = strains(c.map((x) => 2 * x - 1), g.h, dim), out = new Float64Array(rows * m);
733
+ for (let p = 0; p < rows; p++) for (let a = 0; a < m; a++) { let t = 0; for (let r = 0; r < rows; r++) t += D[p * rows + r] * B[r * m + a]; out[p * m + a] = (1 - W) * t + W * bal[q][p * m + a] / g.h; }
734
+ return out;
735
+ });
736
+ const solid = (e) => !density || density[e] >= 0.5;
737
+ const sumSolid = new Float64Array(g.nodes * rows), nSolid = new Uint8Array(g.nodes), sumAll = new Float64Array(g.nodes * rows), nAll = new Uint8Array(g.nodes);
738
+ const ue = new Float64Array(m);
739
+ for (let e = 0; e < g.cells; e++) {
740
+ const eo = e * m, inside = solid(e);
741
+ for (let a = 0; a < m; a++) ue[a] = u[g.edof[eo + a]];
742
+ for (let q = 0; q < C; q++) {
743
+ const n = g.edof[eo + q * dim] / dim, Sq = S[q];
744
+ for (let p = 0; p < rows; p++) {
745
+ let t = 0;
746
+ for (let a = 0, o = p * m; a < m; a++) t += Sq[o + a] * ue[a];
747
+ t *= modulus[e];
748
+ sumAll[n * rows + p] += t;
749
+ if (inside) sumSolid[n * rows + p] += t;
750
+ }
751
+ nAll[n]++;
752
+ if (inside) nSolid[n]++;
753
+ }
754
+ }
755
+ const nodes = new Float64Array(g.nodes), s = new Float64Array(rows);
756
+ for (let n = 0; n < g.nodes; n++) {
757
+ const [sum, k] = nSolid[n] ? [sumSolid, nSolid[n]] : [sumAll, nAll[n]];
758
+ if (!k) continue;
759
+ for (let p = 0; p < rows; p++) s[p] = sum[n * rows + p] / k;
760
+ nodes[n] = vonMises(s, dim);
761
+ }
762
+ const centre = density ? centres || stress(g, u, modulus, nu) : null, cells = new Float64Array(g.cells);
763
+ for (let e = 0; e < g.cells; e++) {
764
+ if (!solid(e)) { cells[e] = centre[e]; continue; }
765
+ let most = 0;
766
+ for (let q = 0; q < C; q++) most = Math.max(most, nodes[g.edof[e * m + q * dim] / dim]);
767
+ cells[e] = most;
768
+ }
769
+ return { nodes, cells };
770
+ }
771
+
772
+ // Members under this many cells through, at the peak stress, are said: the grid reads stress there roughly
773
+ const STRESS_CELLS = 8;
774
+
775
+ // Where a load's peak surface stress is in a member under STRESS_CELLS cells through, a finding saying so. The member's
776
+ // thickness is counted in solid cells, from the peak cell to the first cell under 0.5 or the grid's edge each way, along
777
+ // the axes the stress changes fastest across the peak cell (through the depth, for a beam that bends): the shortest.
778
+ function coarsePeak(g, density, surface, centre, load, loads) {
779
+ const dim = g.dim, m = g.cellDofs, corners = CORNERS[dim], nz = dim === 3 ? g.nz : 1;
780
+ let peak = -1;
781
+ for (let e = 0; e < g.cells; e++) if (density[e] >= 0.5 && (peak < 0 || surface.cells[e] > surface.cells[peak])) peak = e;
782
+ if (peak < 0 || !(surface.cells[peak] > 0)) return null;
783
+ const at = [peak % g.nx, Math.floor(peak / g.nx) % g.ny, dim === 3 ? Math.floor(peak / (g.nx * g.ny)) : 0], sides = [g.nx, g.ny, nz];
784
+ const change = [...Array(dim)].map((_, a) => { // the corners' stress on the cell's far face less its near face, along each axis
785
+ let d = 0;
786
+ corners.forEach((c, q) => { d += (c[a] ? 1 : -1) * surface.nodes[g.edof[peak * m + q * dim] / dim]; });
787
+ return Math.abs(d);
788
+ });
789
+ const steepest = Math.max(...change), cell = (p) => (p[2] * g.ny + p[1]) * g.nx + p[0];
790
+ const run = (axis) => {
791
+ let n = 1;
792
+ for (const step of [-1, 1]) for (let p = at.slice(); ;) { p[axis] += step; if (p[axis] < 0 || p[axis] >= sides[axis] || !(density[cell(p)] >= 0.5)) break; n++; }
793
+ return n;
794
+ };
795
+ // At a clamped end the stress also changes fast along the member (the held face reads low), so the steepest axis
796
+ // alone can be the length: count each axis the stress changes across by at least half as much, and take the shortest
797
+ let through = Infinity;
798
+ for (let a = 0; a < dim; a++) if (change[a] >= steepest / 2) through = Math.min(through, run(a));
799
+ if (through >= STRESS_CELLS) return null;
800
+ const lo = at.slice(0, dim).map((i) => i * g.h), hi = lo.map((x) => x + g.h), r = (x) => Math.round(x * 1000) / 1000;
801
+ const most = surface.cells[peak], low = Math.max(0, Math.round((1 - centre[peak] / most) * 100));
802
+ return {
803
+ level: 'warn',
804
+ code: 'fea.coarse-stress',
805
+ text: `the highest stress${loads > 1 ? ` under load ${load + 1}` : ''}, ${r(most)} MPa at the part's surface, is in a member only ${through} cell${through === 1 ? '' : 's'} through, under the ${STRESS_CELLS} it takes to read stress closely: there the centre stress reads ${low}% lower, and even the surface stress can be some percent out. Check it on cells half the size, or with a member ${STRESS_CELLS} cells through`,
806
+ values: { surface: r(most), centre: r(centre[peak]), cells: through, need: STRESS_CELLS, load },
807
+ at: lo.map((x) => r(x + g.h / 2)),
808
+ box: { lo: lo.map(r), hi: hi.map(r) },
809
+ };
810
+ }
811
+
639
812
  /**
640
813
  * Analyse a part: each cell's density (0 empty to 1 solid; Young's modulus scales with density^penal, never below
641
814
  * E × 1e-9 so empty cells don't leave the matrix singular), supports and loads. In 2D the part is a plate of the given
642
815
  * thickness; in 3D thickness is not used.
643
816
  * @param {{ grid: Grid, density: Float64Array, material: Material, thickness?: number, fixed: Uint8Array, loads: Float64Array[], penal?: number, method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend }} o
644
- * @returns {{ u: Float64Array[], compliance: number[], stress: Float64Array[], deflection: { most: number, at: number[] }[] }}
645
- * compliance: f · u per load (N·mm): the work the load does; lower is stiffer. deflection: the largest movement
646
- * of any node in solid material, and where.
817
+ * @returns {{ u: Float64Array[], thin: { share: number, cells: number }, compliance: number[], stress: Float64Array[], surface: Float64Array[], findings: { level: 'warn', text: string, code: string, values: { surface: number, centre: number, cells: number, need: number, load: number }, at: number[], box: { lo: number[], hi: number[] } }[], deflection: { most: number, at: number[] }[] }}
818
+ * compliance: f · u per load (N·mm): the work the load does; lower is stiffer. stress: each cell's von Mises stress
819
+ * (MPa) at its centre, which reads bending stress low by about one cell's share of the member's depth (27% at 4
820
+ * cells through, 10% at 10). surface: each solid cell's von Mises stress at its surface, the largest of its corners'
821
+ * (surfaceStress): within 2% of beam theory at 4 cells through; use it for strength. findings: a warning
822
+ * (fea.coarse-stress) for each load whose peak surface stress is in a member under 8 cells through. deflection: the
823
+ * largest movement of any node in solid material, and where.
647
824
  */
648
825
  export function analyse({ grid: g, density, material, thickness = 1, fixed, loads, penal = 1, method = g.dim === 3 ? 'mg' : 'direct', backend }) {
649
826
  if (!(material?.E > 0)) throw new Error(`the material needs a modulus E above 0, in MPa (got ${material?.E})`);
@@ -666,12 +843,14 @@ export function analyse({ grid: g, density, material, thickness = 1, fixed, load
666
843
  for (let n = 0; n < g.nodes; n++) if (solidNode[n]) { solid++; for (let d = 0; d < g.dim; d++) if (!(Math.abs(x[g.dim * n + d]) < 1e4 * span)) { adrift++; break; } }
667
844
  if (adrift > solid / 2) throw Object.assign(new Error('the part is not held still (it can slide or turn under this load): fix more of it, in each direction it could move'), { code: 'fea.unheld' });
668
845
  }
669
- const position = positions(g);
846
+ const position = positions(g), centre = u.map((x) => stress(g, x, modulus, nu)), surface = u.map((x, c) => recover(g, x, modulus, nu, density, centre[c]));
670
847
  return {
671
848
  u,
672
849
  thin: thinShare(g, density),
673
850
  compliance: u.map((x, c) => jsBackend.dot(loads[c], x)),
674
- stress: u.map((x) => stress(g, x, modulus, nu)),
851
+ stress: centre,
852
+ surface: surface.map((s) => s.cells),
853
+ findings: surface.map((s, c) => coarsePeak(g, density, s, centre[c], c, loads.length)).filter(Boolean),
675
854
  deflection: u.map((x) => {
676
855
  let most = 0, at = position[0];
677
856
  for (let n = 0; n < g.nodes; n++) if (solidNode[n]) {
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; }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/fea",
3
- "version": "0.2.13",
3
+ "version": "0.3.0",
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": {
@@ -22,17 +22,15 @@
22
22
  }
23
23
  },
24
24
  "files": [
25
- "fea.mjs",
26
- "fea.d.mts",
25
+ "*.mjs",
26
+ "*.d.mts",
27
27
  "README.md",
28
28
  "LICENSE",
29
- "threads.mjs",
30
- "threads.d.mts",
31
- "frame.mjs",
32
- "frame.d.mts",
33
- "layout.mjs",
34
- "layout.d.mts",
35
- "CHANGELOG.md"
29
+ "CHANGELOG.md",
30
+ "!backend-suite.mjs",
31
+ "!frame-cases.mjs",
32
+ "!layout-cases.mjs",
33
+ "!test.mjs"
36
34
  ],
37
35
  "license": "MIT",
38
36
  "keywords": [