@rulecad/fea 0.0.0-stage → 0.1.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.
Files changed (5) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +35 -2
  3. package/fea.d.mts +112 -0
  4. package/fea.mjs +262 -0
  5. package/package.json +35 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 JoniBach and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # @rulecad/fea
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ How far a flat part bends under load. Finite elements for a plate loaded in its own plane (plane stress) on a grid
4
+ of square cells, each with its own stiffness. Plain JavaScript in typed arrays, no dependencies: it runs in browsers
5
+ and Node alike. Units are millimetres and newtons, so Young's modulus is in MPa and movement in mm.
6
+
7
+ ```js
8
+ import { grid, analyse } from '@rulecad/fea';
9
+
10
+ const g = grid({ nx: 100, ny: 10, h: 1 }); // 100 × 10 cells of 1 mm
11
+ const fixed = new Uint8Array(g.dofs), load = new Float64Array(g.dofs);
12
+ for (let j = 0; j <= 10; j++) { fixed[2 * g.node(0, j)] = 1; fixed[2 * g.node(0, j) + 1] = 1; } // hold the left edge
13
+ load[2 * g.node(100, 5) + 1] = -10; // 10 N down at the right end
14
+ const r = analyse({ grid: g, density: new Float64Array(1000).fill(1), material: { E: 2680, nu: 0.36 }, thickness: 5, fixed, loads: [load] });
15
+ r.u[0]; // each node's movement: x at 2n, y at 2n + 1
16
+ r.compliance[0]; // the load times how far it moved (N·mm): lower is stiffer
17
+ r.stress[0]; // each cell's von Mises stress (MPa)
18
+ r.deflection[0]; // { most, at }: the largest movement of solid material, and where
19
+ ```
20
+
21
+ - **Cells:** 4-node squares (bilinear, integrated at 2 × 2 Gauss points). Each cell's density, 0 to 1, scales its
22
+ stiffness (by `density ** penal`), so the same code analyses a part, a part filling only some of its thickness, and
23
+ a topology optimisation's in-between designs.
24
+ - **Solvers:** `direct`, a banded Cholesky factorisation (exact; quick for 2D grids up to about 100,000 cells), or
25
+ `cg`, conjugate gradients that never assemble the matrix (for bigger grids, and what faster backends speed up).
26
+ - **Backends:** the few operations `cg` repeats (the stiffness product, its diagonal, dot products) sit behind a small
27
+ interface. `jsBackend`, plain JavaScript in 64-bit floats, is the reference; a WebGPU or TensorFlow.js backend
28
+ implements the same and passes `backend-suite.mjs` in this repository.
29
+
30
+ Tested against beam theory: a cantilever's tip moves within 1% of `F L³ / 3 E I`.
31
+
32
+ ## Sources
33
+
34
+ - Andreassen, Clausen, Schevenels, Lazarov, Sigmund (2011). Efficient topology optimization in MATLAB using 88 lines
35
+ of code. *Structural and Multidisciplinary Optimization* 43, 1–16.
36
+ - Cook, Malkus, Plesha, Witt (2002). *Concepts and Applications of Finite Element Analysis*, 4th ed. Wiley.
package/fea.d.mts ADDED
@@ -0,0 +1,112 @@
1
+ /** @typedef {{ nx: number, ny: number, h: number }} GridSize cells along x and y, and their side in mm */
2
+ /** @typedef {GridSize & { nodes: number, dofs: number, edof: Int32Array, node: (i: number, j: number) => number }} Grid */
3
+ /** @typedef {{ E: number, nu: number }} Material Young's modulus (MPa) and Poisson's ratio */
4
+ /**
5
+ * A grid of square cells, with each cell's eight unknowns (its corners counter-clockwise from lower left, x then y).
6
+ * @param {GridSize} size
7
+ * @returns {Grid}
8
+ */
9
+ export function grid({ nx, ny, h }: GridSize): Grid;
10
+ /**
11
+ * A square cell's stiffness matrix (8 × 8, row by row) for Young's modulus 1 and thickness 1: the same for any cell
12
+ * size. Integrated with 2 × 2 Gauss points, as for any bilinear element.
13
+ * @param {number} nu Poisson's ratio
14
+ * @returns {Float64Array}
15
+ */
16
+ export function cellStiffness(nu: number): Float64Array;
17
+ /**
18
+ * Solve K u = f for each load. K is every cell's stiffness (cellStiffness) times scale[cell]; fixed dofs don't move.
19
+ * @param {Grid} g
20
+ * @param {{ scale: Float64Array, ke: Float64Array, fixed: Uint8Array, loads: Float64Array[], method?: 'direct' | 'cg', backend?: typeof jsBackend, tol?: number, maxIter?: number, start?: Float64Array[] }} o
21
+ * start: a first guess for cg (the last solution, when solving again after a small change)
22
+ * @returns {{ u: Float64Array[], iterations: number }}
23
+ */
24
+ export function solve(g: Grid, { scale, ke, fixed, loads, method, backend, tol, maxIter, start }: {
25
+ scale: Float64Array;
26
+ ke: Float64Array;
27
+ fixed: Uint8Array;
28
+ loads: Float64Array[];
29
+ method?: "direct" | "cg";
30
+ backend?: typeof jsBackend;
31
+ tol?: number;
32
+ maxIter?: number;
33
+ start?: Float64Array[];
34
+ }): {
35
+ u: Float64Array[];
36
+ iterations: number;
37
+ };
38
+ /**
39
+ * Each cell's von Mises stress (MPa) at its centre, from a solution u.
40
+ * @param {Grid} g @param {Float64Array} u @param {Float64Array} modulus each cell's Young's modulus (MPa) @param {number} nu
41
+ * @returns {Float64Array}
42
+ */
43
+ export function stress(g: Grid, u: Float64Array, modulus: Float64Array, nu: number): Float64Array;
44
+ /**
45
+ * Analyse a plate: each cell's density (0 empty to 1 solid; Young's modulus scales with density^penal, never below
46
+ * E × 1e-9 so empty cells don't leave the matrix singular), its thickness, supports and loads.
47
+ * @param {{ grid: Grid, density: Float64Array, material: Material, thickness: number, fixed: Uint8Array, loads: Float64Array[], penal?: number, method?: 'direct' | 'cg', backend?: typeof jsBackend }} o
48
+ * @returns {{ u: Float64Array[], compliance: number[], stress: Float64Array[], deflection: { most: number, at: [number, number] }[] }}
49
+ * compliance: f · u per load (N·mm): the work the load does; lower is stiffer. deflection: the largest movement
50
+ * of any node in solid material, and where.
51
+ */
52
+ export function analyse({ grid: g, density, material, thickness, fixed, loads, penal, method, backend }: {
53
+ grid: Grid;
54
+ density: Float64Array;
55
+ material: Material;
56
+ thickness: number;
57
+ fixed: Uint8Array;
58
+ loads: Float64Array[];
59
+ penal?: number;
60
+ method?: "direct" | "cg";
61
+ backend?: typeof jsBackend;
62
+ }): {
63
+ u: Float64Array[];
64
+ compliance: number[];
65
+ stress: Float64Array[];
66
+ deflection: {
67
+ most: number;
68
+ at: [number, number];
69
+ }[];
70
+ };
71
+ /**
72
+ * Each node's position in mm, [x, y], by node number.
73
+ * @param {Grid} g
74
+ * @returns {[number, number][]}
75
+ */
76
+ export function positions(g: Grid): [number, number][];
77
+ /**
78
+ * The plain JavaScript backend: the operations conjugate gradients repeats, on Float64Arrays. Another backend (WebGPU,
79
+ * TensorFlow.js) provides the same and is tested against this one.
80
+ * @type {{ name: string, precision: number, operator: (g: Grid, ke: Float64Array) => { multiply: (scale: Float64Array, x: Float64Array, y: Float64Array) => void, diagonal: (scale: Float64Array, d: Float64Array) => void }, dot: (a: Float64Array, b: Float64Array) => number, axpy: (a: number, x: Float64Array, y: Float64Array) => void }}
81
+ */
82
+ export const jsBackend: {
83
+ name: string;
84
+ precision: number;
85
+ operator: (g: Grid, ke: Float64Array) => {
86
+ multiply: (scale: Float64Array, x: Float64Array, y: Float64Array) => void;
87
+ diagonal: (scale: Float64Array, d: Float64Array) => void;
88
+ };
89
+ dot: (a: Float64Array, b: Float64Array) => number;
90
+ axpy: (a: number, x: Float64Array, y: Float64Array) => void;
91
+ };
92
+ /**
93
+ * cells along x and y, and their side in mm
94
+ */
95
+ export type GridSize = {
96
+ nx: number;
97
+ ny: number;
98
+ h: number;
99
+ };
100
+ export type Grid = GridSize & {
101
+ nodes: number;
102
+ dofs: number;
103
+ edof: Int32Array;
104
+ node: (i: number, j: number) => number;
105
+ };
106
+ /**
107
+ * Young's modulus (MPa) and Poisson's ratio
108
+ */
109
+ export type Material = {
110
+ E: number;
111
+ nu: number;
112
+ };
package/fea.mjs ADDED
@@ -0,0 +1,262 @@
1
+ // Finite elements for flat parts: how far a plate bends under load in its own plane (plane stress), on a grid of
2
+ // square cells, each with its own stiffness. Plain numbers in typed arrays, no dependencies: it runs in browsers and
3
+ // Node alike. Units are millimetres and newtons, so stiffness (Young's modulus) is in MPa (N/mm²) and displacement in mm.
4
+ //
5
+ // The grid: nx × ny square cells of side h, cell (i, j) with i along x and j along y, its lower-left corner at
6
+ // (i h, j h). Nodes are the cells' corners, two unknowns each (x and y displacement): dof 2n is node n's x, 2n + 1 its
7
+ // y. Nodes are numbered along the grid's shorter side, which keeps the stiffness matrix's band narrow.
8
+ //
9
+ // Two ways to solve: "direct" (banded Cholesky factorisation: exact, and quick for 2D grids up to about 100,000
10
+ // cells) and "cg" (conjugate gradients, never assembling the matrix: for big grids, and what faster backends speed up).
11
+ // The work cg repeats sits behind a backend, so a GPU can do it; plain JavaScript in 64-bit floats is the reference.
12
+
13
+ /** @typedef {{ nx: number, ny: number, h: number }} GridSize cells along x and y, and their side in mm */
14
+ /** @typedef {GridSize & { nodes: number, dofs: number, edof: Int32Array, node: (i: number, j: number) => number }} Grid */
15
+ /** @typedef {{ E: number, nu: number }} Material Young's modulus (MPa) and Poisson's ratio */
16
+
17
+ /**
18
+ * A grid of square cells, with each cell's eight unknowns (its corners counter-clockwise from lower left, x then y).
19
+ * @param {GridSize} size
20
+ * @returns {Grid}
21
+ */
22
+ export function grid({ nx, ny, h = 1 }) {
23
+ if (!(nx >= 1 && ny >= 1 && Number.isInteger(nx) && Number.isInteger(ny))) throw new Error(`a grid needs whole numbers of cells (got ${nx} × ${ny})`);
24
+ const alongY = ny <= nx; // number nodes along the shorter side
25
+ const node = alongY ? (i, j) => i * (ny + 1) + j : (i, j) => j * (nx + 1) + i;
26
+ const edof = new Int32Array(nx * ny * 8);
27
+ for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) {
28
+ const e = j * nx + i, corners = [node(i, j), node(i + 1, j), node(i + 1, j + 1), node(i, j + 1)];
29
+ for (let k = 0; k < 4; k++) { edof[e * 8 + 2 * k] = 2 * corners[k]; edof[e * 8 + 2 * k + 1] = 2 * corners[k] + 1; }
30
+ }
31
+ const nodes = (nx + 1) * (ny + 1);
32
+ return { nx, ny, h, nodes, dofs: 2 * nodes, edof, node };
33
+ }
34
+
35
+ // The strain-displacement matrix of a square cell of side h at natural coordinates (s, t), 3 × 8, row by row
36
+ function strains(s, t, h) {
37
+ const corner = [[-1, -1], [1, -1], [1, 1], [-1, 1]], B = new Float64Array(24);
38
+ for (let k = 0; k < 4; k++) {
39
+ const [a, b] = corner[k], dx = (a * (1 + b * t)) / 4 * (2 / h), dy = (b * (1 + a * s)) / 4 * (2 / h);
40
+ B[2 * k] = dx; B[8 + 2 * k + 1] = dy; B[16 + 2 * k] = dy; B[16 + 2 * k + 1] = dx;
41
+ }
42
+ return B;
43
+ }
44
+ // Plane stress: stress from strain for Young's modulus 1
45
+ const elasticity = (nu) => { const f = 1 / (1 - nu * nu); return [f, f * nu, 0, f * nu, f, 0, 0, 0, f * (1 - nu) / 2]; };
46
+
47
+ /**
48
+ * A square cell's stiffness matrix (8 × 8, row by row) for Young's modulus 1 and thickness 1: the same for any cell
49
+ * size. Integrated with 2 × 2 Gauss points, as for any bilinear element.
50
+ * @param {number} nu Poisson's ratio
51
+ * @returns {Float64Array}
52
+ */
53
+ export function cellStiffness(nu) {
54
+ const D = elasticity(nu), K = new Float64Array(64), g = 1 / Math.sqrt(3), area = 1 / 4; // h = 1: the Jacobian is 1/4
55
+ for (const s of [-g, g]) for (const t of [-g, g]) {
56
+ const B = strains(s, t, 1);
57
+ for (let a = 0; a < 8; a++) for (let b = 0; b < 8; b++) {
58
+ let sum = 0;
59
+ for (let p = 0; p < 3; p++) for (let q = 0; q < 3; q++) sum += B[p * 8 + a] * D[p * 3 + q] * B[q * 8 + b];
60
+ K[a * 8 + b] += sum * area;
61
+ }
62
+ }
63
+ return K;
64
+ }
65
+
66
+ /**
67
+ * The plain JavaScript backend: the operations conjugate gradients repeats, on Float64Arrays. Another backend (WebGPU,
68
+ * TensorFlow.js) provides the same and is tested against this one.
69
+ * @type {{ name: string, precision: number, operator: (g: Grid, ke: Float64Array) => { multiply: (scale: Float64Array, x: Float64Array, y: Float64Array) => void, diagonal: (scale: Float64Array, d: Float64Array) => void }, dot: (a: Float64Array, b: Float64Array) => number, axpy: (a: number, x: Float64Array, y: Float64Array) => void }}
70
+ */
71
+ export const jsBackend = {
72
+ name: 'js',
73
+ precision: 64,
74
+ operator(g, ke) {
75
+ const { edof } = g, cells = g.nx * g.ny, u = new Float64Array(8);
76
+ return {
77
+ // y = K x, K the stiffness of every cell scaled by scale[cell] (its modulus times thickness)
78
+ multiply(scale, x, y) {
79
+ y.fill(0);
80
+ for (let e = 0; e < cells; e++) {
81
+ const s = scale[e], o = e * 8;
82
+ if (s === 0) continue;
83
+ for (let a = 0; a < 8; a++) u[a] = x[edof[o + a]];
84
+ for (let a = 0; a < 8; a++) {
85
+ let f = 0;
86
+ for (let b = 0; b < 8; b++) f += ke[a * 8 + b] * u[b];
87
+ y[edof[o + a]] += s * f;
88
+ }
89
+ }
90
+ },
91
+ diagonal(scale, d) {
92
+ d.fill(0);
93
+ for (let e = 0; e < cells; e++) for (let a = 0; a < 8; a++) d[edof[e * 8 + a]] += scale[e] * ke[a * 9];
94
+ },
95
+ };
96
+ },
97
+ dot(a, b) { let s = 0; for (let i = 0; i < a.length; i++) s += a[i] * b[i]; return s; },
98
+ axpy(a, x, y) { for (let i = 0; i < y.length; i++) y[i] += a * x[i]; },
99
+ };
100
+
101
+ /**
102
+ * Solve K u = f for each load. K is every cell's stiffness (cellStiffness) times scale[cell]; fixed dofs don't move.
103
+ * @param {Grid} g
104
+ * @param {{ scale: Float64Array, ke: Float64Array, fixed: Uint8Array, loads: Float64Array[], method?: 'direct' | 'cg', backend?: typeof jsBackend, tol?: number, maxIter?: number, start?: Float64Array[] }} o
105
+ * start: a first guess for cg (the last solution, when solving again after a small change)
106
+ * @returns {{ u: Float64Array[], iterations: number }}
107
+ */
108
+ export function solve(g, { scale, ke, fixed, loads, method = 'direct', backend = jsBackend, tol = 1e-9, maxIter = 20000, start }) {
109
+ if (scale.length !== g.nx * g.ny) throw new Error(`scale has ${scale.length} values for ${g.nx * g.ny} cells`);
110
+ if (!fixed.some((f) => f)) throw new Error('nothing is held: fix at least one support, or the part just moves');
111
+ const f = loads.map((l) => { const c = Float64Array.from(l); for (let i = 0; i < c.length; i++) if (fixed[i]) c[i] = 0; return c; });
112
+ if (method === 'direct') {
113
+ const L = factor(g, scale, ke, fixed);
114
+ return { u: f.map((b) => L.solve(b)), iterations: 0 };
115
+ }
116
+ return conjugateGradients(g, { scale, ke, fixed, loads: f, backend, tol, maxIter, start });
117
+ }
118
+
119
+ // The banded Cholesky factor of K: K's lower band (half-bandwidth b) assembled, then factored in place
120
+ function factor(g, scale, ke, fixed) {
121
+ const { edof, dofs } = g, cells = g.nx * g.ny;
122
+ let b = 0;
123
+ for (let e = 0; e < cells; e++) {
124
+ let lo = Infinity, hi = -Infinity;
125
+ for (let a = 0; a < 8; a++) { lo = Math.min(lo, edof[e * 8 + a]); hi = Math.max(hi, edof[e * 8 + a]); }
126
+ b = Math.max(b, hi - lo);
127
+ }
128
+ const w = b + 1, L = new Float64Array(dofs * w); // L[i][j] (j ≤ i, i - j ≤ b) at i * w + b - i + j: a row's band in order
129
+ for (let e = 0; e < cells; e++) {
130
+ const s = scale[e];
131
+ for (let p = 0; p < 8; p++) {
132
+ const i = edof[e * 8 + p];
133
+ if (fixed[i]) continue;
134
+ for (let q = 0; q < 8; q++) {
135
+ const j = edof[e * 8 + q];
136
+ if (j > i || fixed[j]) continue;
137
+ L[i * w + b - i + j] += s * ke[p * 8 + q];
138
+ }
139
+ }
140
+ }
141
+ for (let i = 0; i < dofs; i++) if (fixed[i]) L[i * w + b] = 1;
142
+ for (let i = 0; i < dofs; i++) {
143
+ const from = Math.max(0, i - b), ri = i * w + b - i; // L[i][k] is at ri + k
144
+ for (let j = from; j <= i; j++) {
145
+ const rj = j * w + b - j;
146
+ let s = L[ri + j], s1 = 0, s2 = 0, s3 = 0, k = from;
147
+ for (; k + 3 < j; k += 4) { s -= L[ri + k] * L[rj + k]; s1 += L[ri + k + 1] * L[rj + k + 1]; s2 += L[ri + k + 2] * L[rj + k + 2]; s3 += L[ri + k + 3] * L[rj + k + 3]; } // four running sums: a little faster
148
+ for (; k < j; k++) s -= L[ri + k] * L[rj + k];
149
+ s -= s1 + s2 + s3;
150
+ if (j === i) {
151
+ if (!(s > 0)) throw new Error('the part is not held still: add supports, or join loose pieces to it');
152
+ L[i * w + b] = Math.sqrt(s);
153
+ } else L[ri + j] = s / L[j * w + b];
154
+ }
155
+ }
156
+ return {
157
+ solve(f) {
158
+ const x = Float64Array.from(f);
159
+ for (let i = 0; i < dofs; i++) {
160
+ let s = x[i];
161
+ for (let k = Math.max(0, i - b); k < i; k++) s -= L[i * w + b - i + k] * x[k];
162
+ x[i] = s / L[i * w + b];
163
+ }
164
+ for (let i = dofs - 1; i >= 0; i--) {
165
+ let s = x[i];
166
+ for (let k = i + 1; k <= Math.min(dofs - 1, i + b); k++) s -= L[k * w + b - k + i] * x[k];
167
+ x[i] = s / L[i * w + b];
168
+ }
169
+ return x;
170
+ },
171
+ };
172
+ }
173
+
174
+ // Jacobi-preconditioned conjugate gradients, matrix-free: fixed dofs stay at 0 (their rows act as the identity)
175
+ function conjugateGradients(g, { scale, ke, fixed, loads, backend, tol, maxIter, start }) {
176
+ const op = backend.operator(g, ke), n = g.dofs, d = new Float64Array(n);
177
+ op.diagonal(scale, d);
178
+ for (let i = 0; i < n; i++) d[i] = fixed[i] || !(d[i] > 0) ? 1 : 1 / d[i];
179
+ const apply = (x, y) => { op.multiply(scale, x, y); for (let i = 0; i < n; i++) if (fixed[i]) y[i] = x[i]; };
180
+ let total = 0;
181
+ const u = loads.map((f, c) => {
182
+ const x = start?.[c] ? Float64Array.from(start[c]) : new Float64Array(n);
183
+ for (let i = 0; i < n; i++) if (fixed[i]) x[i] = 0;
184
+ const r = new Float64Array(n), z = new Float64Array(n), p = new Float64Array(n), q = new Float64Array(n);
185
+ apply(x, q);
186
+ for (let i = 0; i < n; i++) r[i] = f[i] - q[i];
187
+ const limit = tol * Math.sqrt(backend.dot(f, f));
188
+ for (let i = 0; i < n; i++) p[i] = z[i] = d[i] * r[i];
189
+ let rz = backend.dot(r, z), it = 0;
190
+ while (Math.sqrt(backend.dot(r, r)) > limit && it < maxIter) {
191
+ apply(p, q);
192
+ const a = rz / backend.dot(p, q);
193
+ backend.axpy(a, p, x); backend.axpy(-a, q, r);
194
+ for (let i = 0; i < n; i++) z[i] = d[i] * r[i];
195
+ const next = backend.dot(r, z);
196
+ for (let i = 0; i < n; i++) p[i] = z[i] + (next / rz) * p[i];
197
+ rz = next; it++;
198
+ }
199
+ if (it >= maxIter) throw new Error(`the solver didn't settle in ${maxIter} steps: the part may be barely held, or a piece of it loose`);
200
+ total += it;
201
+ return x;
202
+ });
203
+ return { u, iterations: total };
204
+ }
205
+
206
+ /**
207
+ * Each cell's von Mises stress (MPa) at its centre, from a solution u.
208
+ * @param {Grid} g @param {Float64Array} u @param {Float64Array} modulus each cell's Young's modulus (MPa) @param {number} nu
209
+ * @returns {Float64Array}
210
+ */
211
+ export function stress(g, u, modulus, nu) {
212
+ const B = strains(0, 0, g.h), D = elasticity(nu), out = new Float64Array(g.nx * g.ny);
213
+ for (let e = 0; e < out.length; e++) {
214
+ const strain = [0, 0, 0];
215
+ for (let p = 0; p < 3; p++) for (let a = 0; a < 8; a++) strain[p] += B[p * 8 + a] * u[g.edof[e * 8 + a]];
216
+ const [sx, sy, txy] = [0, 1, 2].map((p) => modulus[e] * (D[p * 3] * strain[0] + D[p * 3 + 1] * strain[1] + D[p * 3 + 2] * strain[2]));
217
+ out[e] = Math.sqrt(sx * sx - sx * sy + sy * sy + 3 * txy * txy);
218
+ }
219
+ return out;
220
+ }
221
+
222
+ /**
223
+ * Analyse a plate: each cell's density (0 empty to 1 solid; Young's modulus scales with density^penal, never below
224
+ * E × 1e-9 so empty cells don't leave the matrix singular), its thickness, supports and loads.
225
+ * @param {{ grid: Grid, density: Float64Array, material: Material, thickness: number, fixed: Uint8Array, loads: Float64Array[], penal?: number, method?: 'direct' | 'cg', backend?: typeof jsBackend }} o
226
+ * @returns {{ u: Float64Array[], compliance: number[], stress: Float64Array[], deflection: { most: number, at: [number, number] }[] }}
227
+ * compliance: f · u per load (N·mm): the work the load does; lower is stiffer. deflection: the largest movement
228
+ * of any node in solid material, and where.
229
+ */
230
+ export function analyse({ grid: g, density, material, thickness, fixed, loads, penal = 1, method = 'direct', backend }) {
231
+ const { E, nu } = material, Emin = E * 1e-9, ke = cellStiffness(nu);
232
+ const modulus = Float64Array.from(density, (x) => Emin + Math.pow(x, penal) * (E - Emin));
233
+ const scale = modulus.map((m) => m * thickness);
234
+ const { u } = solve(g, { scale, ke, fixed, loads, method, backend });
235
+ const solidNode = new Uint8Array(g.nodes);
236
+ for (let e = 0; e < density.length; e++) if (density[e] >= 0.5) for (let k = 0; k < 4; k++) solidNode[g.edof[e * 8 + 2 * k] / 2] = 1;
237
+ const position = positions(g);
238
+ return {
239
+ u,
240
+ compliance: u.map((x, c) => jsBackend.dot(loads[c], x)),
241
+ stress: u.map((x) => stress(g, x, modulus, nu)),
242
+ deflection: u.map((x) => {
243
+ let most = 0, at = [0, 0];
244
+ for (let n = 0; n < g.nodes; n++) if (solidNode[n]) {
245
+ const m = Math.hypot(x[2 * n], x[2 * n + 1]);
246
+ if (m > most) { most = m; at = position[n]; }
247
+ }
248
+ return { most, at };
249
+ }),
250
+ };
251
+ }
252
+
253
+ /**
254
+ * Each node's position in mm, [x, y], by node number.
255
+ * @param {Grid} g
256
+ * @returns {[number, number][]}
257
+ */
258
+ export function positions(g) {
259
+ const out = new Array(g.nodes);
260
+ for (let j = 0; j <= g.ny; j++) for (let i = 0; i <= g.nx; i++) out[g.node(i, j)] = [i * g.h, j * g.h];
261
+ return out;
262
+ }
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@rulecad/fea",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "How far a flat part bends under load: finite elements on a grid of square cells, in plain JavaScript.",
5
+ "type": "module",
6
+ "exports": {
7
+ "types": "./fea.d.mts",
8
+ "default": "./fea.mjs"
9
+ },
10
+ "files": [
11
+ "fea.mjs",
12
+ "fea.d.mts",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "license": "MIT",
17
+ "keywords": [
18
+ "fea",
19
+ "finite-elements",
20
+ "stiffness",
21
+ "stress",
22
+ "plane-stress"
23
+ ],
24
+ "engines": {
25
+ "node": ">=20"
26
+ },
27
+ "sideEffects": false,
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/JoniBach/rulecad.git",
31
+ "directory": "packages/fea"
32
+ },
33
+ "scripts": {
34
+ "test": "node --test"
35
+ },
36
+ "types": "./fea.d.mts"
37
+ }