@rulecad/fea 0.2.1 → 0.2.3
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 +6 -1
- package/fea.d.mts +5 -1
- package/fea.mjs +169 -75
- package/package.json +12 -4
- package/threads.mjs +101 -0
package/README.md
CHANGED
|
@@ -36,7 +36,12 @@ r.deflection[0]; // { most, at }: the largest movement of solid material, and
|
|
|
36
36
|
limits in @rulecad/topopt use both.
|
|
37
37
|
- **Backends:** the few operations `cg` repeats (the stiffness product, its diagonal, dot products) sit behind a small
|
|
38
38
|
interface. `jsBackend`, plain JavaScript in 64-bit floats, is the reference; a WebGPU or TensorFlow.js backend
|
|
39
|
-
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.
|
|
40
45
|
|
|
41
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.
|
|
42
47
|
Multigrid is tested against the direct solver with stiffnesses a millionfold apart.
|
package/fea.d.mts
CHANGED
|
@@ -13,6 +13,8 @@ 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
|
|
@@ -93,7 +95,9 @@ export function positions(g: Grid): number[][];
|
|
|
93
95
|
* The plain JavaScript backend: the operations the iterative solvers repeat, on Float64Arrays. Another backend
|
|
94
96
|
* (WebGPU, TensorFlow.js) provides the same and is tested against this one (backend-suite.mjs).
|
|
95
97
|
* operator(g, ke): every cell's stiffness is ke (a cell matrix, shared) times scale[cell]; or with cellMatrices, each
|
|
96
|
-
* 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.
|
|
97
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 }}
|
|
98
102
|
*/
|
|
99
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
|
/**
|
|
@@ -222,8 +285,10 @@ export function solve(g, { scale, ke, fixed, loads, method = 'direct', backend =
|
|
|
222
285
|
return { ...conjugateGradients(g, { scale, fixed, loads: held(loads), backend, tol, maxIter, start, precondition, op }), again };
|
|
223
286
|
}
|
|
224
287
|
|
|
225
|
-
// The banded Cholesky factor of K (cells' matrices: ke × scale, or each its own), fixed dofs as identity rows
|
|
226
|
-
|
|
288
|
+
// The banded Cholesky factor of K (cells' matrices: ke × scale, or each its own), fixed dofs as identity rows. Lenient
|
|
289
|
+
// (a preconditioner's coarsest grid, where a coarse unknown over next to nothing can come out singular to rounding), a
|
|
290
|
+
// pivot that isn't positive is dropped: an identity row with no couplings, so the unknown stays put.
|
|
291
|
+
function factor(g, { scale, ke, cellMatrices }, fixed, { lenient = false } = {}) {
|
|
227
292
|
const { edof, dofs, cells, cellDofs: m } = g, mm = m * m;
|
|
228
293
|
let b = 0;
|
|
229
294
|
for (let e = 0; e < cells; e++) {
|
|
@@ -245,16 +310,21 @@ function factor(g, { scale, ke, cellMatrices }, fixed) {
|
|
|
245
310
|
}
|
|
246
311
|
}
|
|
247
312
|
for (let i = 0; i < dofs; i++) if (fixed[i] || L[i * w + b] === 0) L[i * w + b] = 1; // fixed, or touching no cell
|
|
313
|
+
const dropped = lenient ? new Uint8Array(dofs) : null;
|
|
248
314
|
for (let i = 0; i < dofs; i++) {
|
|
249
315
|
const from = Math.max(0, i - b), ri = i * w + b - i; // L[i][k] is at ri + k
|
|
250
316
|
for (let j = from; j <= i; j++) {
|
|
317
|
+
if (dropped && dropped[j]) { L[ri + j] = 0; continue; }
|
|
251
318
|
const rj = j * w + b - j;
|
|
252
319
|
let s = L[ri + j], s1 = 0, s2 = 0, s3 = 0, k = from;
|
|
253
320
|
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
|
|
254
321
|
for (; k < j; k++) s -= L[ri + k] * L[rj + k];
|
|
255
322
|
s -= s1 + s2 + s3;
|
|
256
323
|
if (j === i) {
|
|
257
|
-
if (!(s > 0))
|
|
324
|
+
if (!(s > 0)) {
|
|
325
|
+
if (!dropped) throw new Error('the part is not held still: add supports, or join loose pieces to it');
|
|
326
|
+
dropped[i] = 1; s = 1; for (let k = from; k < i; k++) L[ri + k] = 0;
|
|
327
|
+
}
|
|
258
328
|
L[i * w + b] = Math.sqrt(s);
|
|
259
329
|
} else L[ri + j] = s / L[j * w + b];
|
|
260
330
|
}
|
|
@@ -272,6 +342,7 @@ function factor(g, { scale, ke, cellMatrices }, fixed) {
|
|
|
272
342
|
for (let k = i + 1; k <= Math.min(dofs - 1, i + b); k++) s -= L[k * w + b - k + i] * x[k];
|
|
273
343
|
x[i] = s / L[i * w + b];
|
|
274
344
|
}
|
|
345
|
+
if (dropped) for (let i = 0; i < dofs; i++) if (dropped[i]) x[i] = 0;
|
|
275
346
|
return x;
|
|
276
347
|
},
|
|
277
348
|
};
|
|
@@ -321,7 +392,7 @@ function conjugateGradients(g, { scale, fixed, loads, backend, tol, maxIter, sta
|
|
|
321
392
|
// (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
|
|
322
393
|
// V: two damped Jacobi sweeps down, the coarsest grid solved exactly (banded Cholesky), two sweeps on the way up.
|
|
323
394
|
// It's symmetric, so conjugate gradients can use it as a preconditioner.
|
|
324
|
-
const SWEEPS = 2, DAMPING = 0.5, COARSEST =
|
|
395
|
+
const SWEEPS = 2, DAMPING = 0.5, COARSEST = 600;
|
|
325
396
|
|
|
326
397
|
// The coarser grids under a grid, and the maps between each pair, worked out once per grid (they don't change as the
|
|
327
398
|
// cells' stiffnesses do)
|
|
@@ -356,20 +427,23 @@ function multigrid(g, { scale, ke, fixed, backend, op }) {
|
|
|
356
427
|
l.op.diagonal(l.scale, l.inv);
|
|
357
428
|
for (let i = 0; i < l.inv.length; i++) l.inv[i] = l.fixed[i] || !(l.inv[i] > 0) ? 0 : DAMPING / l.inv[i];
|
|
358
429
|
}
|
|
359
|
-
const last = levels.at(-1), coarse = factor(last.g, { scale: last.scale, ke, cellMatrices: last.mats }, last.fixed);
|
|
430
|
+
const last = levels.at(-1), coarse = factor(last.g, { scale: last.scale, ke, cellMatrices: last.mats }, last.fixed, { lenient: levels.length > 1 });
|
|
360
431
|
const apply = (l, x, y) => { l.op.multiply(l.scale, x, y); for (let i = 0; i < y.length; i++) if (l.fixed[i]) y[i] = 0; };
|
|
361
432
|
|
|
362
433
|
const cycle = (k, r) => {
|
|
363
434
|
const l = levels[k];
|
|
364
435
|
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; }
|
|
365
436
|
const n = l.g.dofs, x = new Float64Array(n), Ax = new Float64Array(n), res = new Float64Array(n);
|
|
366
|
-
|
|
367
|
-
|
|
437
|
+
// Smoothed by a symmetric Gauss-Seidel sweep where the backend has one (once each way is about as much work as
|
|
438
|
+
// two Jacobi sweeps, and smooths better), else by damped Jacobi
|
|
439
|
+
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]); } };
|
|
440
|
+
const sweeps = l.op.smooth ? 1 : SWEEPS;
|
|
441
|
+
for (let s = 0; s < sweeps; s++) sweep();
|
|
368
442
|
apply(l, x, Ax);
|
|
369
443
|
for (let i = 0; i < n; i++) res[i] = l.fixed[i] ? 0 : r[i] - Ax[i];
|
|
370
444
|
const e = maps[k].prolong(cycle(k + 1, maps[k].restrict(res)));
|
|
371
445
|
for (let i = 0; i < n; i++) x[i] += l.fixed[i] ? 0 : e[i];
|
|
372
|
-
for (let s = 0; s <
|
|
446
|
+
for (let s = 0; s < sweeps; s++) sweep();
|
|
373
447
|
return x;
|
|
374
448
|
};
|
|
375
449
|
return (r, z) => {
|
|
@@ -402,9 +476,26 @@ function childInterpolation(dim) {
|
|
|
402
476
|
// Each coarse cell's matrix: Σ over its children of P_oᵀ (child's matrix, fixed rows and columns left out) P_o, using
|
|
403
477
|
// only P_o's nonzero weights (about one in seven)
|
|
404
478
|
const interpolations = { 2: null, 3: null };
|
|
479
|
+
// On the fine level every cell's matrix is the one cell matrix scaled, so each child position's carried-up matrix
|
|
480
|
+
// (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
|
|
481
|
+
// fixed dof (few: on the supports) is carried up the long way, with those left out.
|
|
482
|
+
const carried = new WeakMap();
|
|
483
|
+
function carriedUp(ke, dim) {
|
|
484
|
+
if (carried.has(ke)) return carried.get(ke);
|
|
485
|
+
const m = CORNERS[dim].length * dim, mm = m * m, P = interpolations[dim] || (interpolations[dim] = childInterpolation(dim)), KP = new Float64Array(mm);
|
|
486
|
+
const out = P.map(([rows, cols, wts]) => {
|
|
487
|
+
const o = new Float64Array(mm);
|
|
488
|
+
KP.fill(0);
|
|
489
|
+
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; }
|
|
490
|
+
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]; }
|
|
491
|
+
return o;
|
|
492
|
+
});
|
|
493
|
+
carried.set(ke, out);
|
|
494
|
+
return out;
|
|
495
|
+
}
|
|
405
496
|
function coarsen(fg, cg, K, scale, fixed) {
|
|
406
497
|
const dim = fg.dim, m = fg.cellDofs, mm = m * m, corners = CORNERS[dim];
|
|
407
|
-
const P = interpolations[dim] || (interpolations[dim] = childInterpolation(dim));
|
|
498
|
+
const P = interpolations[dim] || (interpolations[dim] = childInterpolation(dim)), ready = scale ? carriedUp(K, dim) : null;
|
|
408
499
|
const out = new Float64Array(cg.cells * mm), KP = new Float64Array(mm), held = new Uint8Array(m);
|
|
409
500
|
const shared = scale ? K : null; // fine level: one matrix scaled per cell; coarser: each cell its own
|
|
410
501
|
const offset = corners.map((o) => ((o[2] || 0) * fg.ny + o[1]) * fg.nx + o[0]); // a child's cell number from its first
|
|
@@ -413,7 +504,10 @@ function coarsen(fg, cg, K, scale, fixed) {
|
|
|
413
504
|
const first = (2 * Kz * fg.ny + 2 * J) * fg.nx + 2 * I, o0 = E * mm;
|
|
414
505
|
for (let oi = 0; oi < corners.length; oi++) {
|
|
415
506
|
const e = first + offset[oi], s = scale ? scale[e] : 1, base = shared ? 0 : e * mm, src = shared || K;
|
|
416
|
-
|
|
507
|
+
if (s === 0) continue;
|
|
508
|
+
let any = 0;
|
|
509
|
+
for (let a = 0; a < m; a++) { held[a] = fixed[fg.edof[e * m + a]]; any |= held[a]; }
|
|
510
|
+
if (ready && !any) { const R = ready[oi]; for (let t = 0; t < mm; t++) out[o0 + t] += s * R[t]; continue; }
|
|
417
511
|
const [rows, cols, wts] = P[oi];
|
|
418
512
|
KP.fill(0);
|
|
419
513
|
for (let t = 0; t < wts.length; t++) { // KP = child × P_o
|
package/package.json
CHANGED
|
@@ -1,17 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulecad/fea",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.3",
|
|
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
|
+
}
|