@rulecad/fea 0.2.0 → 0.2.2
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/README.md +11 -1
- package/fea.d.mts +21 -2
- package/fea.mjs +195 -76
- package/package.json +12 -4
- package/threads.mjs +101 -0
package/README.md
CHANGED
|
@@ -29,9 +29,19 @@ r.deflection[0]; // { most, at }: the largest movement of solid material, and
|
|
|
29
29
|
coarse cell's matrix is built from its children's exactly (Galerkin), so it stays accurate when cells'
|
|
30
30
|
stiffnesses differ a millionfold, as they do in topology optimisation. A cantilever of 16,000 cubes takes 9
|
|
31
31
|
iterations, where plain `cg` takes 371.
|
|
32
|
+
- **Solving again:** `solve(...)` returns `again(loads)`, which solves more right-hand sides on the same matrix,
|
|
33
|
+
reusing its factorisation or preconditioner: an adjoint, for a gradient.
|
|
34
|
+
- **Stress at a point:** `centreStress(h, nu, dim)` is the matrix from a cell's movements to the stress at its centre
|
|
35
|
+
(for Young's modulus 1), and `vonMises(s, dim, grad)` gives von Mises stress and, optionally, its gradient. Stress
|
|
36
|
+
limits in @rulecad/topopt use both.
|
|
32
37
|
- **Backends:** the few operations `cg` repeats (the stiffness product, its diagonal, dot products) sit behind a small
|
|
33
38
|
interface. `jsBackend`, plain JavaScript in 64-bit floats, is the reference; a WebGPU or TensorFlow.js backend
|
|
34
|
-
implements the same and passes `backend-suite.mjs` in this repository.
|
|
39
|
+
implements the same and passes `backend-suite.mjs` in this repository. The matrix is assembled in blocks (a node's
|
|
40
|
+
rows: a 3 × 3 block for each node it shares a cell with), so a product is a plain sweep, and multigrid's sweeps are
|
|
41
|
+
symmetric Gauss-Seidel through those blocks.
|
|
42
|
+
- **Threads:** `import { threadsBackend } from '@rulecad/fea/threads'` (Node only) shares each product over the
|
|
43
|
+
machine's cores (`FEA_THREADS` to say how many), the rest as `jsBackend`. On a 134,000-unknown grid a product takes
|
|
44
|
+
6.8 ms on seven threads against 19 ms on one, and an optimisation step about a third of the time.
|
|
35
45
|
|
|
36
46
|
Tested against beam theory: a cantilever's tip moves within 1% of `F L³ / 3 E I` in 2D, and within 2% in 3D.
|
|
37
47
|
Multigrid is tested against the direct solver with stiffnesses a millionfold apart.
|
package/fea.d.mts
CHANGED
|
@@ -13,12 +13,15 @@ export function grid({ nx, ny, nz, h }: GridSize): Grid;
|
|
|
13
13
|
* @returns {Float64Array}
|
|
14
14
|
*/
|
|
15
15
|
export function cellStiffness(nu: number, dim?: 2 | 3): Float64Array;
|
|
16
|
+
export function pattern(g: any): any;
|
|
17
|
+
export function assemble(g: any, pat: any, cellMatrices: any, ke: any, scale: any, into: any): any;
|
|
16
18
|
/**
|
|
17
19
|
* Solve K u = f for each load. K is every cell's stiffness (cellStiffness) times scale[cell]; fixed dofs don't move.
|
|
18
20
|
* @param {Grid} g
|
|
19
21
|
* @param {{ scale: Float64Array, ke: Float64Array, fixed: Uint8Array, loads: Float64Array[], method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend, tol?: number, maxIter?: number, start?: Float64Array[] }} o
|
|
20
22
|
* start: a first guess for the iterative solvers (the last solution, when solving again after a small change)
|
|
21
|
-
* @returns {{ u: Float64Array[], iterations: number }}
|
|
23
|
+
* @returns {{ u: Float64Array[], iterations: number, again: (loads: Float64Array[]) => Float64Array[] }} again: more
|
|
24
|
+
* loads on the same matrix (an adjoint), reusing its factor or preconditioner
|
|
22
25
|
*/
|
|
23
26
|
export function solve(g: Grid, { scale, ke, fixed, loads, method, backend, tol, maxIter, start }: {
|
|
24
27
|
scale: Float64Array;
|
|
@@ -33,7 +36,21 @@ export function solve(g: Grid, { scale, ke, fixed, loads, method, backend, tol,
|
|
|
33
36
|
}): {
|
|
34
37
|
u: Float64Array[];
|
|
35
38
|
iterations: number;
|
|
39
|
+
again: (loads: Float64Array[]) => Float64Array[];
|
|
36
40
|
};
|
|
41
|
+
/**
|
|
42
|
+
* Stress at a cell's centre from its corners' movements, for Young's modulus 1: a matrix (rows × cell dofs, row by row;
|
|
43
|
+
* rows: σx, σy, τxy in 2D; σx, σy, σz, τxy, τyz, τzx in 3D). Times a cell's movements and its modulus, it's the stress.
|
|
44
|
+
* @param {number} h cell size (mm) @param {number} nu @param {2 | 3} dim
|
|
45
|
+
* @returns {Float64Array}
|
|
46
|
+
*/
|
|
47
|
+
export function centreStress(h: number, nu: number, dim: 2 | 3): Float64Array;
|
|
48
|
+
/**
|
|
49
|
+
* Von Mises stress from a stress (as centreStress's rows); with grad, also its gradient with respect to the stress.
|
|
50
|
+
* @param {ArrayLike<number>} s @param {2 | 3} dim @param {Float64Array} [grad]
|
|
51
|
+
* @returns {number}
|
|
52
|
+
*/
|
|
53
|
+
export function vonMises(s: ArrayLike<number>, dim: 2 | 3, grad?: Float64Array): number;
|
|
37
54
|
/**
|
|
38
55
|
* Each cell's von Mises stress (MPa) at its centre, from a solution u.
|
|
39
56
|
* @param {Grid} g @param {Float64Array} u @param {Float64Array} modulus each cell's Young's modulus (MPa) @param {number} nu
|
|
@@ -78,7 +95,9 @@ export function positions(g: Grid): number[][];
|
|
|
78
95
|
* The plain JavaScript backend: the operations the iterative solvers repeat, on Float64Arrays. Another backend
|
|
79
96
|
* (WebGPU, TensorFlow.js) provides the same and is tested against this one (backend-suite.mjs).
|
|
80
97
|
* operator(g, ke): every cell's stiffness is ke (a cell matrix, shared) times scale[cell]; or with cellMatrices, each
|
|
81
|
-
* cell has its own matrix (cells × m × m), as multigrid's coarser grids do.
|
|
98
|
+
* cell has its own matrix (cells × m × m), as multigrid's coarser grids do. The matrix is assembled, in blocks (a
|
|
99
|
+
* node's rows: a dim × dim block for each node it shares a cell with), once for each scale array it is given (so one
|
|
100
|
+
* changed in place needs a new operator), or once from the cells' own matrices; each product is then a plain sweep.
|
|
82
101
|
* @type {{ name: string, precision: number, operator: (g: Grid, ke: Float64Array | null, cellMatrices?: Float64Array) => { multiply: (scale: Float64Array | null, x: Float64Array, y: Float64Array) => void, diagonal: (scale: Float64Array | null, d: Float64Array) => void }, dot: (a: Float64Array, b: Float64Array) => number, axpy: (a: number, x: Float64Array, y: Float64Array) => void }}
|
|
83
102
|
*/
|
|
84
103
|
export const jsBackend: {
|
package/fea.mjs
CHANGED
|
@@ -103,53 +103,103 @@ export function cellStiffness(nu, dim = 2) {
|
|
|
103
103
|
* The plain JavaScript backend: the operations the iterative solvers repeat, on Float64Arrays. Another backend
|
|
104
104
|
* (WebGPU, TensorFlow.js) provides the same and is tested against this one (backend-suite.mjs).
|
|
105
105
|
* operator(g, ke): every cell's stiffness is ke (a cell matrix, shared) times scale[cell]; or with cellMatrices, each
|
|
106
|
-
* cell has its own matrix (cells × m × m), as multigrid's coarser grids do.
|
|
106
|
+
* cell has its own matrix (cells × m × m), as multigrid's coarser grids do. The matrix is assembled, in blocks (a
|
|
107
|
+
* node's rows: a dim × dim block for each node it shares a cell with), once for each scale array it is given (so one
|
|
108
|
+
* changed in place needs a new operator), or once from the cells' own matrices; each product is then a plain sweep.
|
|
107
109
|
* @type {{ name: string, precision: number, operator: (g: Grid, ke: Float64Array | null, cellMatrices?: Float64Array) => { multiply: (scale: Float64Array | null, x: Float64Array, y: Float64Array) => void, diagonal: (scale: Float64Array | null, d: Float64Array) => void }, dot: (a: Float64Array, b: Float64Array) => number, axpy: (a: number, x: Float64Array, y: Float64Array) => void }}
|
|
108
110
|
*/
|
|
109
111
|
export const jsBackend = {
|
|
110
112
|
name: 'js',
|
|
111
113
|
precision: 64,
|
|
112
114
|
operator(g, ke, cellMatrices) {
|
|
113
|
-
const
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
//
|
|
117
|
-
|
|
118
|
-
let
|
|
115
|
+
const pat = pattern(g), { dim } = g, bb = dim * dim;
|
|
116
|
+
let values = cellMatrices ? assemble(g, pat, cellMatrices, null, null) : null, assembledFor = cellMatrices ? undefined : {};
|
|
117
|
+
const ready = (scale) => { if (!cellMatrices && assembledFor !== scale) { values = assemble(g, pat, null, ke, scale, values); assembledFor = scale; } };
|
|
118
|
+
// Each node's diagonal block, inverted, with fixed dofs left out (their rows and columns zero, so they don't move);
|
|
119
|
+
// a node with nothing round it (no stiffness) doesn't move either. Kept until the values or the fixed dofs change.
|
|
120
|
+
let invFor = null, invValues = null, inv = null;
|
|
121
|
+
function inverses(fixed) {
|
|
122
|
+
if (inv && invFor === fixed && invValues === values) return inv;
|
|
123
|
+
const { rows, self } = pat, n = g.nodes;
|
|
124
|
+
inv = new Float64Array(n * bb); invFor = fixed; invValues = values;
|
|
125
|
+
const D = new Float64Array(bb);
|
|
126
|
+
for (let i = 0; i < n; i++) {
|
|
127
|
+
const o = (rows[i] + self[i]) * bb, b = i * bb;
|
|
128
|
+
for (let q = 0; q < bb; q++) D[q] = values[o + q];
|
|
129
|
+
for (let q = 0; q < dim; q++) if (fixed[dim * i + q]) { for (let f = 0; f < dim; f++) { D[q * dim + f] = 0; D[f * dim + q] = 0; } }
|
|
130
|
+
if (dim === 2) {
|
|
131
|
+
const det = D[0] * D[3] - D[1] * D[2];
|
|
132
|
+
if (!(Math.abs(det) > 0)) continue;
|
|
133
|
+
inv[b] = D[3] / det; inv[b + 1] = -D[1] / det; inv[b + 2] = -D[2] / det; inv[b + 3] = D[0] / det;
|
|
134
|
+
} else {
|
|
135
|
+
const c0 = D[4] * D[8] - D[5] * D[7], c1 = D[5] * D[6] - D[3] * D[8], c2 = D[3] * D[7] - D[4] * D[6], det = D[0] * c0 + D[1] * c1 + D[2] * c2;
|
|
136
|
+
if (!(Math.abs(det) > 0)) {
|
|
137
|
+
// Some dofs fixed: invert what's left, dof by dof where the block is diagonal there
|
|
138
|
+
for (let q = 0; q < dim; q++) if (!fixed[dim * i + q] && D[q * dim + q] > 0) inv[b + q * dim + q] = 1 / D[q * dim + q];
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
inv[b] = c0 / det; inv[b + 1] = (D[2] * D[7] - D[1] * D[8]) / det; inv[b + 2] = (D[1] * D[5] - D[2] * D[4]) / det;
|
|
142
|
+
inv[b + 3] = c1 / det; inv[b + 4] = (D[0] * D[8] - D[2] * D[6]) / det; inv[b + 5] = (D[2] * D[3] - D[0] * D[5]) / det;
|
|
143
|
+
inv[b + 6] = c2 / det; inv[b + 7] = (D[1] * D[6] - D[0] * D[7]) / det; inv[b + 8] = (D[0] * D[4] - D[1] * D[3]) / det;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return inv;
|
|
147
|
+
}
|
|
119
148
|
return {
|
|
120
149
|
multiply(scale, x, y) {
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
for (let
|
|
127
|
-
|
|
150
|
+
ready(scale);
|
|
151
|
+
const { rows, cols } = pat, n = g.nodes, v = values;
|
|
152
|
+
if (dim === 3) {
|
|
153
|
+
for (let i = 0; i < n; i++) {
|
|
154
|
+
let y0 = 0, y1 = 0, y2 = 0;
|
|
155
|
+
for (let t = rows[i], end = rows[i + 1]; t < end; t++) {
|
|
156
|
+
const j = cols[t] * 3, o = t * 9, x0 = x[j], x1 = x[j + 1], x2 = x[j + 2];
|
|
157
|
+
y0 += v[o] * x0 + v[o + 1] * x1 + v[o + 2] * x2;
|
|
158
|
+
y1 += v[o + 3] * x0 + v[o + 4] * x1 + v[o + 5] * x2;
|
|
159
|
+
y2 += v[o + 6] * x0 + v[o + 7] * x1 + v[o + 8] * x2;
|
|
160
|
+
}
|
|
161
|
+
y[3 * i] = y0; y[3 * i + 1] = y1; y[3 * i + 2] = y2;
|
|
128
162
|
}
|
|
129
|
-
|
|
130
|
-
for (let i = 0; i <
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
const K = cellMatrices || ke, base = cellMatrices ? e * mm : 0;
|
|
138
|
-
for (let a = 0; a < m; a++) u[a] = x[edof[o + a]];
|
|
139
|
-
for (let a = 0; a < m; a++) {
|
|
140
|
-
let f = 0;
|
|
141
|
-
const r = base + a * m;
|
|
142
|
-
for (let b = 0; b < m; b++) f += K[r + b] * u[b];
|
|
143
|
-
y[edof[o + a]] += s * f;
|
|
163
|
+
} else {
|
|
164
|
+
for (let i = 0; i < n; i++) {
|
|
165
|
+
let y0 = 0, y1 = 0;
|
|
166
|
+
for (let t = rows[i], end = rows[i + 1]; t < end; t++) {
|
|
167
|
+
const j = cols[t] * 2, o = t * 4, x0 = x[j], x1 = x[j + 1];
|
|
168
|
+
y0 += v[o] * x0 + v[o + 1] * x1; y1 += v[o + 2] * x0 + v[o + 3] * x1;
|
|
169
|
+
}
|
|
170
|
+
y[2 * i] = y0; y[2 * i + 1] = y1;
|
|
144
171
|
}
|
|
145
172
|
}
|
|
146
173
|
},
|
|
147
174
|
diagonal(scale, d) {
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
175
|
+
ready(scale);
|
|
176
|
+
const { rows, self } = pat;
|
|
177
|
+
for (let i = 0; i < g.nodes; i++) { const o = (rows[i] + self[i]) * bb; for (let q = 0; q < dim; q++) d[dim * i + q] = values[o + q * dim + q]; }
|
|
178
|
+
},
|
|
179
|
+
// One symmetric Gauss-Seidel sweep on K x = r, in place: forward through the nodes, then back, each node's dofs
|
|
180
|
+
// solved together through its diagonal block's inverse, with its neighbours' latest values. Fixed dofs stay.
|
|
181
|
+
// Symmetric, so a multigrid cycle smoothed with it can precondition conjugate gradients.
|
|
182
|
+
smooth(scale, fixed, r, x) {
|
|
183
|
+
ready(scale);
|
|
184
|
+
const inv = inverses(fixed), { rows, cols } = pat, n = g.nodes, v = values;
|
|
185
|
+
const node = dim === 3
|
|
186
|
+
? (i) => {
|
|
187
|
+
let y0 = 0, y1 = 0, y2 = 0;
|
|
188
|
+
for (let t = rows[i], end = rows[i + 1]; t < end; t++) {
|
|
189
|
+
const j = cols[t] * 3, o = t * 9, x0 = x[j], x1 = x[j + 1], x2 = x[j + 2];
|
|
190
|
+
y0 += v[o] * x0 + v[o + 1] * x1 + v[o + 2] * x2; y1 += v[o + 3] * x0 + v[o + 4] * x1 + v[o + 5] * x2; y2 += v[o + 6] * x0 + v[o + 7] * x1 + v[o + 8] * x2;
|
|
191
|
+
}
|
|
192
|
+
const k = 3 * i, b = 9 * i, r0 = r[k] - y0, r1 = r[k + 1] - y1, r2 = r[k + 2] - y2;
|
|
193
|
+
x[k] += inv[b] * r0 + inv[b + 1] * r1 + inv[b + 2] * r2; x[k + 1] += inv[b + 3] * r0 + inv[b + 4] * r1 + inv[b + 5] * r2; x[k + 2] += inv[b + 6] * r0 + inv[b + 7] * r1 + inv[b + 8] * r2;
|
|
194
|
+
}
|
|
195
|
+
: (i) => {
|
|
196
|
+
let y0 = 0, y1 = 0;
|
|
197
|
+
for (let t = rows[i], end = rows[i + 1]; t < end; t++) { const j = cols[t] * 2, o = t * 4, x0 = x[j], x1 = x[j + 1]; y0 += v[o] * x0 + v[o + 1] * x1; y1 += v[o + 2] * x0 + v[o + 3] * x1; }
|
|
198
|
+
const k = 2 * i, b = 4 * i, r0 = r[k] - y0, r1 = r[k + 1] - y1;
|
|
199
|
+
x[k] += inv[b] * r0 + inv[b + 1] * r1; x[k + 1] += inv[b + 2] * r0 + inv[b + 3] * r1;
|
|
200
|
+
};
|
|
201
|
+
for (let i = 0; i < n; i++) node(i);
|
|
202
|
+
for (let i = n - 1; i >= 0; i--) node(i);
|
|
153
203
|
},
|
|
154
204
|
};
|
|
155
205
|
},
|
|
@@ -157,47 +207,60 @@ export const jsBackend = {
|
|
|
157
207
|
axpy(a, x, y) { for (let i = 0; i < y.length; i++) y[i] += a * x[i]; },
|
|
158
208
|
};
|
|
159
209
|
|
|
160
|
-
//
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
210
|
+
// Memory worker threads can share, where there is such a thing (Node; browsers only when cross-origin isolated)
|
|
211
|
+
const Shared = typeof SharedArrayBuffer === 'function' ? SharedArrayBuffer : ArrayBuffer;
|
|
212
|
+
// A copy of a typed array on it
|
|
213
|
+
const shared = (a) => { const out = new a.constructor(new Shared(a.byteLength)); out.set(a); return out; };
|
|
214
|
+
|
|
215
|
+
// The assembled matrix's shape for a grid, worked out once per grid: for each node, the nodes it shares a cell with
|
|
216
|
+
// (the 3 × 3 (× 3) round it, in node order: rows, cols), which of them is itself (self), and where each of its
|
|
217
|
+
// neighbourhood's offsets sits in its row (slot), so a cell's entries find their blocks without searching.
|
|
218
|
+
const patterns = new WeakMap();
|
|
219
|
+
export function pattern(g) {
|
|
164
220
|
if (patterns.has(g)) return patterns.get(g);
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
const
|
|
168
|
-
const coords = new Int32Array(g.nodes * 3), id = (i, j, k) => (dim === 3 ? g.node(i, j, k) : g.node(i, j));
|
|
221
|
+
const { dim, nodes, cellDofs: m, edof } = g, nk = dim === 3 ? g.nz : 0, corners = CORNERS[dim];
|
|
222
|
+
const id = (i, j, k) => (dim === 3 ? g.node(i, j, k) : g.node(i, j));
|
|
223
|
+
const coords = new Int32Array(nodes * 3);
|
|
169
224
|
for (let k = 0; k <= nk; k++) for (let j = 0; j <= g.ny; j++) for (let i = 0; i <= g.nx; i++) { const n = id(i, j, k); coords[3 * n] = i; coords[3 * n + 1] = j; coords[3 * n + 2] = k; }
|
|
170
225
|
const offsets = [];
|
|
171
226
|
for (let c = dim === 3 ? -1 : 0; c <= (dim === 3 ? 1 : 0); c++) for (let b = -1; b <= 1; b++) for (let a = -1; a <= 1; a++) offsets.push([a, b, c]);
|
|
172
|
-
const
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
const near = [];
|
|
176
|
-
offsets.forEach(([a, b, c], o) => {
|
|
177
|
-
const I = i + a, J = j + b, K = k + c;
|
|
178
|
-
if (I >= 0 && I <= g.nx && J >= 0 && J <= g.ny && K >= 0 && K <= nk) near.push([id(I, J, K), o]);
|
|
179
|
-
});
|
|
227
|
+
const O = offsets.length, offsetIndex = (a, b, c) => (dim === 3 ? (c + 1) * 9 : 0) + (b + 1) * 3 + (a + 1);
|
|
228
|
+
const slot = new Int32Array(nodes * O).fill(-1), rows = new Int32Array(nodes + 1), self = new Int32Array(nodes), cols = [];
|
|
229
|
+
for (let n = 0; n < nodes; n++) {
|
|
230
|
+
const [i, j, k] = [coords[3 * n], coords[3 * n + 1], coords[3 * n + 2]], near = [];
|
|
231
|
+
offsets.forEach(([a, b, c], o) => { const I = i + a, J = j + b, K = k + c; if (I >= 0 && I <= g.nx && J >= 0 && J <= g.ny && K >= 0 && K <= nk) near.push([id(I, J, K), o]); });
|
|
180
232
|
near.sort((p, q) => p[0] - q[0]);
|
|
181
|
-
near.forEach(([, o], t) => {
|
|
182
|
-
|
|
183
|
-
for (const [nb] of near) for (let e = 0; e < dim; e++) columns.push(dim * nb + e);
|
|
184
|
-
rows[dim * n + d + 1] = columns.length;
|
|
185
|
-
}
|
|
233
|
+
near.forEach(([nb, o], t) => { slot[n * O + o] = t; if (nb === n) self[n] = t; cols.push(nb); });
|
|
234
|
+
rows[n + 1] = cols.length;
|
|
186
235
|
}
|
|
187
|
-
|
|
188
|
-
const
|
|
236
|
+
// For a cell's corner pair (p, q), the offset of q's node from p's
|
|
237
|
+
const C = corners.length, pairOffset = new Int32Array(C * C);
|
|
238
|
+
for (let p = 0; p < C; p++) for (let q = 0; q < C; q++) pairOffset[p * C + q] = offsetIndex(corners[q][0] - corners[p][0], corners[q][1] - corners[p][1], (corners[q][2] || 0) - (corners[p][2] || 0));
|
|
239
|
+
const out = { rows: shared(rows), cols: shared(Int32Array.from(cols)), slot, self, pairOffset, O };
|
|
240
|
+
patterns.set(g, out);
|
|
241
|
+
return out;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// The matrix's values, assembled from the cells: each its own matrix (cellMatrices), or ke times its scale (1 with no
|
|
245
|
+
// scale). Into the buffer given, if any.
|
|
246
|
+
export function assemble(g, pat, cellMatrices, ke, scale, into) {
|
|
247
|
+
const { rows, cols, slot, pairOffset, O } = pat, { dim, cells, cellDofs: m, edof } = g, C = CORNERS[dim].length, bb = dim * dim, mm = m * m;
|
|
248
|
+
const values = into || new Float64Array(new Shared(cols.length * bb * 8));
|
|
249
|
+
if (into) values.fill(0);
|
|
250
|
+
const K = cellMatrices || ke;
|
|
189
251
|
for (let e = 0; e < cells; e++) {
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
252
|
+
const s = scale ? scale[e] : 1;
|
|
253
|
+
if (s === 0) continue;
|
|
254
|
+
const base = cellMatrices ? e * mm : 0, eo = e * m;
|
|
255
|
+
for (let p = 0; p < C; p++) {
|
|
256
|
+
const na = edof[eo + p * dim] / dim, row = rows[na], sb = na * O, pb = p * C;
|
|
257
|
+
for (let q = 0; q < C; q++) {
|
|
258
|
+
const t = (row + slot[sb + pairOffset[pb + q]]) * bb, kb = base + p * dim * m + q * dim;
|
|
259
|
+
for (let d = 0; d < dim; d++) for (let f = 0; f < dim; f++) values[t + d * dim + f] += s * K[kb + d * m + f];
|
|
195
260
|
}
|
|
196
261
|
}
|
|
197
262
|
}
|
|
198
|
-
|
|
199
|
-
patterns.set(g, out);
|
|
200
|
-
return out;
|
|
263
|
+
return values;
|
|
201
264
|
}
|
|
202
265
|
|
|
203
266
|
/**
|
|
@@ -205,19 +268,21 @@ function pattern(g) {
|
|
|
205
268
|
* @param {Grid} g
|
|
206
269
|
* @param {{ scale: Float64Array, ke: Float64Array, fixed: Uint8Array, loads: Float64Array[], method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend, tol?: number, maxIter?: number, start?: Float64Array[] }} o
|
|
207
270
|
* start: a first guess for the iterative solvers (the last solution, when solving again after a small change)
|
|
208
|
-
* @returns {{ u: Float64Array[], iterations: number }}
|
|
271
|
+
* @returns {{ u: Float64Array[], iterations: number, again: (loads: Float64Array[]) => Float64Array[] }} again: more
|
|
272
|
+
* loads on the same matrix (an adjoint), reusing its factor or preconditioner
|
|
209
273
|
*/
|
|
210
274
|
export function solve(g, { scale, ke, fixed, loads, method = 'direct', backend = jsBackend, tol = 1e-9, maxIter = 20000, start }) {
|
|
211
275
|
if (scale.length !== g.cells) throw new Error(`scale has ${scale.length} values for ${g.cells} cells`);
|
|
212
276
|
if (!fixed.some((f) => f)) throw new Error('nothing is held: fix at least one support, or the part just moves');
|
|
213
|
-
const
|
|
277
|
+
const held = (ls) => ls.map((l) => { const c = Float64Array.from(l); for (let i = 0; i < c.length; i++) if (fixed[i]) c[i] = 0; return c; });
|
|
214
278
|
if (method === 'direct') {
|
|
215
|
-
const L = factor(g, { scale, ke }, fixed);
|
|
216
|
-
return { u:
|
|
279
|
+
const L = factor(g, { scale, ke }, fixed), again = (ls) => held(ls).map((b) => L.solve(b));
|
|
280
|
+
return { u: again(loads), iterations: 0, again };
|
|
217
281
|
}
|
|
218
282
|
const op = backend.operator(g, ke); // one for the solver and its preconditioner: the matrix is assembled once
|
|
219
283
|
const precondition = method === 'mg' ? multigrid(g, { scale, ke, fixed, backend, op }) : jacobi(g, { scale, fixed, op });
|
|
220
|
-
|
|
284
|
+
const again = (ls) => conjugateGradients(g, { scale, fixed, loads: held(ls), backend, tol, maxIter, precondition, op }).u;
|
|
285
|
+
return { ...conjugateGradients(g, { scale, fixed, loads: held(loads), backend, tol, maxIter, start, precondition, op }), again };
|
|
221
286
|
}
|
|
222
287
|
|
|
223
288
|
// The banded Cholesky factor of K (cells' matrices: ke × scale, or each its own), fixed dofs as identity rows
|
|
@@ -319,7 +384,7 @@ function conjugateGradients(g, { scale, fixed, loads, backend, tol, maxIter, sta
|
|
|
319
384
|
// (Pᵀ K P), with fixed dofs left out, so the coarse problem is the fine one seen at half the resolution. The cycle is a
|
|
320
385
|
// V: two damped Jacobi sweeps down, the coarsest grid solved exactly (banded Cholesky), two sweeps on the way up.
|
|
321
386
|
// It's symmetric, so conjugate gradients can use it as a preconditioner.
|
|
322
|
-
const SWEEPS = 2, DAMPING = 0.5, COARSEST =
|
|
387
|
+
const SWEEPS = 2, DAMPING = 0.5, COARSEST = 600;
|
|
323
388
|
|
|
324
389
|
// The coarser grids under a grid, and the maps between each pair, worked out once per grid (they don't change as the
|
|
325
390
|
// cells' stiffnesses do)
|
|
@@ -361,13 +426,16 @@ function multigrid(g, { scale, ke, fixed, backend, op }) {
|
|
|
361
426
|
const l = levels[k];
|
|
362
427
|
if (k === levels.length - 1) { const x = coarse.solve(r); for (let i = 0; i < x.length; i++) if (l.fixed[i]) x[i] = 0; return x; }
|
|
363
428
|
const n = l.g.dofs, x = new Float64Array(n), Ax = new Float64Array(n), res = new Float64Array(n);
|
|
364
|
-
|
|
365
|
-
|
|
429
|
+
// Smoothed by a symmetric Gauss-Seidel sweep where the backend has one (once each way is about as much work as
|
|
430
|
+
// two Jacobi sweeps, and smooths better), else by damped Jacobi
|
|
431
|
+
const sweep = () => { if (l.op.smooth) l.op.smooth(l.scale, l.fixed, r, x); else { apply(l, x, Ax); for (let i = 0; i < n; i++) x[i] += l.inv[i] * (r[i] - Ax[i]); } };
|
|
432
|
+
const sweeps = l.op.smooth ? 1 : SWEEPS;
|
|
433
|
+
for (let s = 0; s < sweeps; s++) sweep();
|
|
366
434
|
apply(l, x, Ax);
|
|
367
435
|
for (let i = 0; i < n; i++) res[i] = l.fixed[i] ? 0 : r[i] - Ax[i];
|
|
368
436
|
const e = maps[k].prolong(cycle(k + 1, maps[k].restrict(res)));
|
|
369
437
|
for (let i = 0; i < n; i++) x[i] += l.fixed[i] ? 0 : e[i];
|
|
370
|
-
for (let s = 0; s <
|
|
438
|
+
for (let s = 0; s < sweeps; s++) sweep();
|
|
371
439
|
return x;
|
|
372
440
|
};
|
|
373
441
|
return (r, z) => {
|
|
@@ -400,9 +468,26 @@ function childInterpolation(dim) {
|
|
|
400
468
|
// Each coarse cell's matrix: Σ over its children of P_oᵀ (child's matrix, fixed rows and columns left out) P_o, using
|
|
401
469
|
// only P_o's nonzero weights (about one in seven)
|
|
402
470
|
const interpolations = { 2: null, 3: null };
|
|
471
|
+
// On the fine level every cell's matrix is the one cell matrix scaled, so each child position's carried-up matrix
|
|
472
|
+
// (P_oᵀ ke P_o) is the same for every coarse cell: worked out once per cell matrix, and scaled. Only a child with a
|
|
473
|
+
// fixed dof (few: on the supports) is carried up the long way, with those left out.
|
|
474
|
+
const carried = new WeakMap();
|
|
475
|
+
function carriedUp(ke, dim) {
|
|
476
|
+
if (carried.has(ke)) return carried.get(ke);
|
|
477
|
+
const m = CORNERS[dim].length * dim, mm = m * m, P = interpolations[dim] || (interpolations[dim] = childInterpolation(dim)), KP = new Float64Array(mm);
|
|
478
|
+
const out = P.map(([rows, cols, wts]) => {
|
|
479
|
+
const o = new Float64Array(mm);
|
|
480
|
+
KP.fill(0);
|
|
481
|
+
for (let t = 0; t < wts.length; t++) { const b = rows[t], c = cols[t], w = wts[t]; for (let a = 0; a < m; a++) KP[a * m + c] += ke[a * m + b] * w; }
|
|
482
|
+
for (let t = 0; t < wts.length; t++) { const a = rows[t], r = cols[t], w = wts[t]; for (let c = 0; c < m; c++) o[r * m + c] += w * KP[a * m + c]; }
|
|
483
|
+
return o;
|
|
484
|
+
});
|
|
485
|
+
carried.set(ke, out);
|
|
486
|
+
return out;
|
|
487
|
+
}
|
|
403
488
|
function coarsen(fg, cg, K, scale, fixed) {
|
|
404
489
|
const dim = fg.dim, m = fg.cellDofs, mm = m * m, corners = CORNERS[dim];
|
|
405
|
-
const P = interpolations[dim] || (interpolations[dim] = childInterpolation(dim));
|
|
490
|
+
const P = interpolations[dim] || (interpolations[dim] = childInterpolation(dim)), ready = scale ? carriedUp(K, dim) : null;
|
|
406
491
|
const out = new Float64Array(cg.cells * mm), KP = new Float64Array(mm), held = new Uint8Array(m);
|
|
407
492
|
const shared = scale ? K : null; // fine level: one matrix scaled per cell; coarser: each cell its own
|
|
408
493
|
const offset = corners.map((o) => ((o[2] || 0) * fg.ny + o[1]) * fg.nx + o[0]); // a child's cell number from its first
|
|
@@ -411,7 +496,10 @@ function coarsen(fg, cg, K, scale, fixed) {
|
|
|
411
496
|
const first = (2 * Kz * fg.ny + 2 * J) * fg.nx + 2 * I, o0 = E * mm;
|
|
412
497
|
for (let oi = 0; oi < corners.length; oi++) {
|
|
413
498
|
const e = first + offset[oi], s = scale ? scale[e] : 1, base = shared ? 0 : e * mm, src = shared || K;
|
|
414
|
-
|
|
499
|
+
if (s === 0) continue;
|
|
500
|
+
let any = 0;
|
|
501
|
+
for (let a = 0; a < m; a++) { held[a] = fixed[fg.edof[e * m + a]]; any |= held[a]; }
|
|
502
|
+
if (ready && !any) { const R = ready[oi]; for (let t = 0; t < mm; t++) out[o0 + t] += s * R[t]; continue; }
|
|
415
503
|
const [rows, cols, wts] = P[oi];
|
|
416
504
|
KP.fill(0);
|
|
417
505
|
for (let t = 0; t < wts.length; t++) { // KP = child × P_o
|
|
@@ -464,6 +552,37 @@ function transfer(fg, cg) {
|
|
|
464
552
|
};
|
|
465
553
|
}
|
|
466
554
|
|
|
555
|
+
/**
|
|
556
|
+
* Stress at a cell's centre from its corners' movements, for Young's modulus 1: a matrix (rows × cell dofs, row by row;
|
|
557
|
+
* rows: σx, σy, τxy in 2D; σx, σy, σz, τxy, τyz, τzx in 3D). Times a cell's movements and its modulus, it's the stress.
|
|
558
|
+
* @param {number} h cell size (mm) @param {number} nu @param {2 | 3} dim
|
|
559
|
+
* @returns {Float64Array}
|
|
560
|
+
*/
|
|
561
|
+
export function centreStress(h, nu, dim) {
|
|
562
|
+
const m = CORNERS[dim].length * dim, rows = dim === 3 ? 6 : 3, B = strains(new Array(dim).fill(0), h, dim), D = elasticity(nu, dim), S = new Float64Array(rows * m);
|
|
563
|
+
for (let p = 0; p < rows; p++) for (let a = 0; a < m; a++) { let t = 0; for (let q = 0; q < rows; q++) t += D[p * rows + q] * B[q * m + a]; S[p * m + a] = t; }
|
|
564
|
+
return S;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* Von Mises stress from a stress (as centreStress's rows); with grad, also its gradient with respect to the stress.
|
|
569
|
+
* @param {ArrayLike<number>} s @param {2 | 3} dim @param {Float64Array} [grad]
|
|
570
|
+
* @returns {number}
|
|
571
|
+
*/
|
|
572
|
+
export function vonMises(s, dim, grad) {
|
|
573
|
+
const v = dim === 2 ? Math.sqrt(Math.max(0, s[0] * s[0] - s[0] * s[1] + s[1] * s[1] + 3 * s[2] * s[2]))
|
|
574
|
+
: Math.sqrt(Math.max(0, ((s[0] - s[1]) ** 2 + (s[1] - s[2]) ** 2 + (s[2] - s[0]) ** 2) / 2 + 3 * (s[3] ** 2 + s[4] ** 2 + s[5] ** 2)));
|
|
575
|
+
if (grad) {
|
|
576
|
+
const k = v > 0 ? 1 / (2 * v) : 0;
|
|
577
|
+
if (dim === 2) { grad[0] = k * (2 * s[0] - s[1]); grad[1] = k * (2 * s[1] - s[0]); grad[2] = k * 6 * s[2]; }
|
|
578
|
+
else {
|
|
579
|
+
grad[0] = k * (2 * s[0] - s[1] - s[2]); grad[1] = k * (2 * s[1] - s[0] - s[2]); grad[2] = k * (2 * s[2] - s[0] - s[1]);
|
|
580
|
+
grad[3] = k * 6 * s[3]; grad[4] = k * 6 * s[4]; grad[5] = k * 6 * s[5];
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
return v;
|
|
584
|
+
}
|
|
585
|
+
|
|
467
586
|
/**
|
|
468
587
|
* Each cell's von Mises stress (MPa) at its centre, from a solution u.
|
|
469
588
|
* @param {Grid} g @param {Float64Array} u @param {Float64Array} modulus each cell's Young's modulus (MPa) @param {number} nu
|
package/package.json
CHANGED
|
@@ -1,17 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulecad/fea",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
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, in plain JavaScript.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
7
|
-
"
|
|
8
|
-
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./fea.d.mts",
|
|
9
|
+
"default": "./fea.mjs"
|
|
10
|
+
},
|
|
11
|
+
"./threads": {
|
|
12
|
+
"types": "./threads.d.mts",
|
|
13
|
+
"default": "./threads.mjs"
|
|
14
|
+
}
|
|
9
15
|
},
|
|
10
16
|
"files": [
|
|
11
17
|
"fea.mjs",
|
|
12
18
|
"fea.d.mts",
|
|
13
19
|
"README.md",
|
|
14
|
-
"LICENSE"
|
|
20
|
+
"LICENSE",
|
|
21
|
+
"threads.mjs",
|
|
22
|
+
"threads.d.mts"
|
|
15
23
|
],
|
|
16
24
|
"license": "MIT",
|
|
17
25
|
"keywords": [
|
package/threads.mjs
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// The threads backend: the stiffness product (what the iterative solvers spend their time on) shared out over worker
|
|
2
|
+
// threads, each sweeping a range of the nodes. Node only (worker_threads and shared memory); the rest is the plain
|
|
3
|
+
// JavaScript backend's. Each product costs a handoff to the workers and back (tens of microseconds), so it pays on grids
|
|
4
|
+
// of more than a few thousand cells, which is where the time goes anyway.
|
|
5
|
+
// import { threadsBackend } from '@rulecad/fea/threads';
|
|
6
|
+
// solve(g, { ..., method: 'mg', backend: threadsBackend });
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
9
|
+
import { jsBackend, pattern, assemble } from './fea.mjs';
|
|
10
|
+
|
|
11
|
+
const THREADS = Math.max(1, Math.min(8, Number(process.env.FEA_THREADS) || os.cpus().length - 1));
|
|
12
|
+
|
|
13
|
+
// The pool: made on first use, kept for the process (unref'd, so it doesn't keep the process alive). Each operator
|
|
14
|
+
// registers its arrays with every worker under an id; a product then signals the id and waits for every worker's done.
|
|
15
|
+
let pool = null;
|
|
16
|
+
function workers() {
|
|
17
|
+
if (pool) return pool;
|
|
18
|
+
// ctl: [0] the product generation, [1] the operator id, [2] workers done, [3] registrations acknowledged
|
|
19
|
+
const ctl = new Int32Array(new SharedArrayBuffer(16)), list = [];
|
|
20
|
+
for (let w = 0; w < THREADS; w++) { const worker = new Worker(new URL(import.meta.url), { workerData: { ctl, index: w, count: THREADS } }); worker.unref(); list.push(worker); }
|
|
21
|
+
let nextId = 1;
|
|
22
|
+
pool = {
|
|
23
|
+
register(arrays) {
|
|
24
|
+
const id = nextId++;
|
|
25
|
+
Atomics.store(ctl, 3, 0);
|
|
26
|
+
for (const w of list) w.postMessage({ id, ...arrays });
|
|
27
|
+
// Wake the workers to take the message (a product with no operator), then wait for every one to hold the arrays
|
|
28
|
+
pool.multiply(0);
|
|
29
|
+
while (Atomics.load(ctl, 3) < THREADS) Atomics.wait(ctl, 3, Atomics.load(ctl, 3), 50);
|
|
30
|
+
return id;
|
|
31
|
+
},
|
|
32
|
+
multiply(id) {
|
|
33
|
+
Atomics.store(ctl, 2, 0); Atomics.store(ctl, 1, id);
|
|
34
|
+
Atomics.add(ctl, 0, 1); Atomics.notify(ctl, 0);
|
|
35
|
+
while (Atomics.load(ctl, 2) < THREADS) Atomics.wait(ctl, 2, Atomics.load(ctl, 2), 50);
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
return pool;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const threadsBackend = {
|
|
42
|
+
name: `threads (${THREADS})`,
|
|
43
|
+
precision: 64,
|
|
44
|
+
operator(g, ke, cellMatrices) {
|
|
45
|
+
const pat = pattern(g), { dim } = g, bb = dim * dim, n = g.nodes;
|
|
46
|
+
const xs = new Float64Array(new SharedArrayBuffer(g.dofs * 8)), ys = new Float64Array(new SharedArrayBuffer(g.dofs * 8));
|
|
47
|
+
let values = cellMatrices ? assemble(g, pat, cellMatrices, null, null) : new Float64Array(new SharedArrayBuffer(pat.cols.length * bb * 8));
|
|
48
|
+
let assembledFor = cellMatrices ? undefined : {}, id = null;
|
|
49
|
+
const ready = (scale) => {
|
|
50
|
+
if (!cellMatrices && assembledFor !== scale) { assemble(g, pat, null, ke, scale, values); assembledFor = scale; }
|
|
51
|
+
if (id === null) id = workers().register({ dim, nodes: n, rows: pat.rows, cols: pat.cols, values, xs, ys });
|
|
52
|
+
};
|
|
53
|
+
return {
|
|
54
|
+
multiply(scale, x, y) { ready(scale); xs.set(x); workers().multiply(id); y.set(ys); },
|
|
55
|
+
diagonal(scale, d) {
|
|
56
|
+
ready(scale);
|
|
57
|
+
const { rows, self } = pat;
|
|
58
|
+
for (let i = 0; i < n; i++) { const o = (rows[i] + self[i]) * bb; for (let q = 0; q < dim; q++) d[dim * i + q] = values[o + q * dim + q]; }
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
},
|
|
62
|
+
dot: jsBackend.dot,
|
|
63
|
+
axpy: jsBackend.axpy,
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
if (!isMainThread && workerData?.ctl) {
|
|
67
|
+
const { ctl, index, count } = workerData, ops = new Map();
|
|
68
|
+
parentPort.on('message', (m) => { ops.set(m.id, m); Atomics.add(ctl, 3, 1); Atomics.notify(ctl, 3); });
|
|
69
|
+
// Products: wait for the generation to change, sweep this worker's share of the nodes, say so
|
|
70
|
+
let seen = 0;
|
|
71
|
+
const run = () => {
|
|
72
|
+
for (;;) {
|
|
73
|
+
const r = Atomics.wait(ctl, 0, seen, 1000); // (timed, so a message gets through now and then regardless)
|
|
74
|
+
if (r === 'timed-out') return setImmediate(run);
|
|
75
|
+
seen = Atomics.load(ctl, 0);
|
|
76
|
+
const id = Atomics.load(ctl, 1), op = ops.get(id);
|
|
77
|
+
if (!id) { Atomics.add(ctl, 2, 1); Atomics.notify(ctl, 2); return setImmediate(run); } // woken to take a message
|
|
78
|
+
if (op) {
|
|
79
|
+
const { dim, nodes, rows, cols, values: v, xs: x, ys: y } = op, from = Math.floor((nodes * index) / count), to = Math.floor((nodes * (index + 1)) / count);
|
|
80
|
+
if (dim === 3) {
|
|
81
|
+
for (let i = from; i < to; i++) {
|
|
82
|
+
let y0 = 0, y1 = 0, y2 = 0;
|
|
83
|
+
for (let t = rows[i], end = rows[i + 1]; t < end; t++) {
|
|
84
|
+
const j = cols[t] * 3, o = t * 9, x0 = x[j], x1 = x[j + 1], x2 = x[j + 2];
|
|
85
|
+
y0 += v[o] * x0 + v[o + 1] * x1 + v[o + 2] * x2; y1 += v[o + 3] * x0 + v[o + 4] * x1 + v[o + 5] * x2; y2 += v[o + 6] * x0 + v[o + 7] * x1 + v[o + 8] * x2;
|
|
86
|
+
}
|
|
87
|
+
y[3 * i] = y0; y[3 * i + 1] = y1; y[3 * i + 2] = y2;
|
|
88
|
+
}
|
|
89
|
+
} else {
|
|
90
|
+
for (let i = from; i < to; i++) {
|
|
91
|
+
let y0 = 0, y1 = 0;
|
|
92
|
+
for (let t = rows[i], end = rows[i + 1]; t < end; t++) { const j = cols[t] * 2, o = t * 4, x0 = x[j], x1 = x[j + 1]; y0 += v[o] * x0 + v[o + 1] * x1; y1 += v[o + 2] * x0 + v[o + 3] * x1; }
|
|
93
|
+
y[2 * i] = y0; y[2 * i + 1] = y1;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
Atomics.add(ctl, 2, 1); Atomics.notify(ctl, 2);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
run();
|
|
101
|
+
}
|