@rulecad/fea 0.2.1 → 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 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 { edof, cells, cellDofs: m } = g, u = new Float64Array(m), mm = m * m;
114
- // With one cell matrix scaled per cell, and a grid that isn't huge, the product goes faster through the assembled
115
- // matrix (compressed rows): assembled once for each scale array it is given (so one changed in place needs a new
116
- // operator), then each product is a plain sweep
117
- const sparse = !cellMatrices && cells * mm <= SPARSE_LIMIT ? pattern(g) : null;
118
- let assembledFor = null, values = null;
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
- if (sparse && scale) {
122
- if (assembledFor !== scale) {
123
- values = values || new Float64Array(sparse.columns.length);
124
- values.fill(0);
125
- const { slot } = sparse;
126
- for (let e = 0; e < cells; e++) { const s = scale[e], o = e * mm; if (s) for (let t = 0; t < mm; t++) values[slot[o + t]] += s * ke[t]; }
127
- assembledFor = scale;
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
- const { rows, columns } = sparse;
130
- for (let i = 0; i < y.length; i++) { let f = 0; for (let t = rows[i]; t < rows[i + 1]; t++) f += values[t] * x[columns[t]]; y[i] = f; }
131
- return;
132
- }
133
- y.fill(0);
134
- for (let e = 0; e < cells; e++) {
135
- const s = scale ? scale[e] : 1, o = e * m;
136
- if (s === 0) continue;
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
- d.fill(0);
149
- for (let e = 0; e < cells; e++) {
150
- const s = scale ? scale[e] : 1, K = cellMatrices || ke, base = cellMatrices ? e * mm : 0;
151
- for (let a = 0; a < m; a++) d[edof[e * m + a]] += s * K[base + a * (m + 1)];
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
- // The assembled matrix's shape for a grid: each row's columns (the dofs its node shares a cell with), and where each
161
- // cell matrix entry goes. Worked out once per grid. Grids whose cells × entries pass SPARSE_LIMIT stay cell by cell.
162
- const SPARSE_LIMIT = 40e6, patterns = new WeakMap();
163
- function pattern(g) {
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
- // On a grid each node's neighbours (the nodes it shares a cell with) are the 3 × 3 (× 3) round it: list them, in node
166
- // order, for each node, with where each offset lands, so a cell's entry finds its place without searching
167
- const { edof, cells, cellDofs: m, dofs, dim } = g, mm = m * m, nk = dim === 3 ? g.nz : 0;
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 slotOf = new Int32Array(g.nodes * offsets.length).fill(-1), rows = new Int32Array(dofs + 1), columns = [];
173
- for (let n = 0; n < g.nodes; n++) {
174
- const [i, j, k] = [coords[3 * n], coords[3 * n + 1], coords[3 * n + 2]];
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) => { slotOf[n * offsets.length + o] = t; });
182
- for (let d = 0; d < dim; d++) {
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
- const offsetIndex = (a, b, c) => ((dim === 3 ? (c + 1) * 9 : 0) + (b + 1) * 3 + (a + 1));
188
- const corners = CORNERS[dim], slot = new Int32Array(cells * mm);
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
- for (let p = 0; p < corners.length; p++) {
191
- const na = edof[e * m + p * dim] / dim;
192
- for (let q = 0; q < corners.length; q++) {
193
- const cp = corners[p], cq = corners[q], t = slotOf[na * offsets.length + offsetIndex(cq[0] - cp[0], cq[1] - cp[1], (cq[2] || 0) - (cp[2] || 0))];
194
- for (let d = 0; d < dim; d++) for (let f = 0; f < dim; f++) slot[e * mm + (p * dim + d) * m + q * dim + f] = rows[dim * na + d] + t * dim + f;
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
- const out = { rows, columns: Int32Array.from(columns), slot };
199
- patterns.set(g, out);
200
- return out;
263
+ return values;
201
264
  }
202
265
 
203
266
  /**
@@ -321,7 +384,7 @@ function conjugateGradients(g, { scale, fixed, loads, backend, tol, maxIter, sta
321
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
322
385
  // V: two damped Jacobi sweeps down, the coarsest grid solved exactly (banded Cholesky), two sweeps on the way up.
323
386
  // It's symmetric, so conjugate gradients can use it as a preconditioner.
324
- const SWEEPS = 2, DAMPING = 0.5, COARSEST = 3000;
387
+ const SWEEPS = 2, DAMPING = 0.5, COARSEST = 600;
325
388
 
326
389
  // The coarser grids under a grid, and the maps between each pair, worked out once per grid (they don't change as the
327
390
  // cells' stiffnesses do)
@@ -363,13 +426,16 @@ function multigrid(g, { scale, ke, fixed, backend, op }) {
363
426
  const l = levels[k];
364
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; }
365
428
  const n = l.g.dofs, x = new Float64Array(n), Ax = new Float64Array(n), res = new Float64Array(n);
366
- const sweep = () => { apply(l, x, Ax); for (let i = 0; i < n; i++) x[i] += l.inv[i] * (r[i] - Ax[i]); };
367
- for (let s = 0; s < SWEEPS; s++) sweep();
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();
368
434
  apply(l, x, Ax);
369
435
  for (let i = 0; i < n; i++) res[i] = l.fixed[i] ? 0 : r[i] - Ax[i];
370
436
  const e = maps[k].prolong(cycle(k + 1, maps[k].restrict(res)));
371
437
  for (let i = 0; i < n; i++) x[i] += l.fixed[i] ? 0 : e[i];
372
- for (let s = 0; s < SWEEPS; s++) sweep();
438
+ for (let s = 0; s < sweeps; s++) sweep();
373
439
  return x;
374
440
  };
375
441
  return (r, z) => {
@@ -402,9 +468,26 @@ function childInterpolation(dim) {
402
468
  // Each coarse cell's matrix: Σ over its children of P_oᵀ (child's matrix, fixed rows and columns left out) P_o, using
403
469
  // only P_o's nonzero weights (about one in seven)
404
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
+ }
405
488
  function coarsen(fg, cg, K, scale, fixed) {
406
489
  const dim = fg.dim, m = fg.cellDofs, mm = m * m, corners = CORNERS[dim];
407
- const P = interpolations[dim] || (interpolations[dim] = childInterpolation(dim));
490
+ const P = interpolations[dim] || (interpolations[dim] = childInterpolation(dim)), ready = scale ? carriedUp(K, dim) : null;
408
491
  const out = new Float64Array(cg.cells * mm), KP = new Float64Array(mm), held = new Uint8Array(m);
409
492
  const shared = scale ? K : null; // fine level: one matrix scaled per cell; coarser: each cell its own
410
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
@@ -413,7 +496,10 @@ function coarsen(fg, cg, K, scale, fixed) {
413
496
  const first = (2 * Kz * fg.ny + 2 * J) * fg.nx + 2 * I, o0 = E * mm;
414
497
  for (let oi = 0; oi < corners.length; oi++) {
415
498
  const e = first + offset[oi], s = scale ? scale[e] : 1, base = shared ? 0 : e * mm, src = shared || K;
416
- for (let a = 0; a < m; a++) held[a] = fixed[fg.edof[e * m + a]];
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; }
417
503
  const [rows, cols, wts] = P[oi];
418
504
  KP.fill(0);
419
505
  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.1",
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
- "types": "./fea.d.mts",
8
- "default": "./fea.mjs"
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
+ }