@rulecad/fea 0.2.4 → 0.2.8
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 +15 -0
- package/fea.d.mts +18 -3
- package/fea.mjs +81 -9
- package/package.json +5 -1
- package/threads.d.mts +10 -0
- package/threads.mjs +11 -5
package/README.md
CHANGED
|
@@ -16,6 +16,7 @@ r.u[0]; // each node's movement: x at 2n, y at 2n + 1
|
|
|
16
16
|
r.compliance[0]; // the load times how far it moved (N·mm): lower is stiffer
|
|
17
17
|
r.stress[0]; // each cell's von Mises stress (MPa)
|
|
18
18
|
r.deflection[0]; // { most, at }: the largest movement of solid material, and where
|
|
19
|
+
r.thin; // { share, cells }: how much of the part is in members under 4 cells thick (thinShare), where a cell's stiffness is rough
|
|
19
20
|
```
|
|
20
21
|
|
|
21
22
|
- **3D:** give the grid `nz` too (`grid({ nx, ny, nz, h })`) and every node has x, y and z.
|
|
@@ -46,6 +47,20 @@ r.deflection[0]; // { most, at }: the largest movement of solid material, and
|
|
|
46
47
|
Tested against beam theory: a cantilever's tip moves within 1% of `F L³ / 3 E I` in 2D, and within 2% in 3D.
|
|
47
48
|
Multigrid is tested against the direct solver with stiffnesses a millionfold apart.
|
|
48
49
|
|
|
50
|
+
**How fine a grid.** The cells are exact for a part that only stretches, and converge on beam theory with shear
|
|
51
|
+
(Timoshenko's) as they shrink. What matters is how many cells cross the depth of whatever bends:
|
|
52
|
+
|
|
53
|
+
| Cells through the depth | Too stiff by |
|
|
54
|
+
|---|---|
|
|
55
|
+
| 1 | about 32% |
|
|
56
|
+
| 2 | about 11% |
|
|
57
|
+
| 4 | about 3% |
|
|
58
|
+
| 10 | under 1% |
|
|
59
|
+
|
|
60
|
+
So give every member that bends at least four cells, and check a final shape on cells half the size: if the
|
|
61
|
+
stiffness moves by more than a few percent, the grid was too coarse. (Measured on cantilevers and a simply supported
|
|
62
|
+
beam, in 2D and 3D.)
|
|
63
|
+
|
|
49
64
|
## Sources
|
|
50
65
|
|
|
51
66
|
- Amir, Aage, Lazarov (2014). On multigrid-CG for efficient topology optimization. *Structural and Multidisciplinary
|
package/fea.d.mts
CHANGED
|
@@ -18,16 +18,18 @@ export function assemble(g: any, pat: any, cellMatrices: any, ke: any, scale: an
|
|
|
18
18
|
/**
|
|
19
19
|
* Solve K u = f for each load. K is every cell's stiffness (cellStiffness) times scale[cell]; fixed dofs don't move.
|
|
20
20
|
* @param {Grid} g
|
|
21
|
-
* @param {{ scale: Float64Array, ke: Float64Array, fixed: Uint8Array, loads: Float64Array[], method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend, tol?: number, maxIter?: number, start?: Float64Array[] }} o
|
|
21
|
+
* @param {{ scale: Float64Array, ke: Float64Array, fixed: Uint8Array, loads: Float64Array[], springs?: Float64Array, method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend, tol?: number, maxIter?: number, start?: Float64Array[] }} o
|
|
22
|
+
* springs: a stiffness added on each dof (N/mm), as a mechanism's input and output springs
|
|
22
23
|
* start: a first guess for the iterative solvers (the last solution, when solving again after a small change)
|
|
23
|
-
* @returns {{ u: Float64Array[], iterations: number, again: (loads: Float64Array[]) => Float64Array[] }} again: more
|
|
24
|
+
* @returns {{ u: Float64Array[], iterations: number, again: (loads: Float64Array[]) => Float64Array[], warning?: string }} warning: multigrid on a grid it couldn't halve far (slow); again: more
|
|
24
25
|
* loads on the same matrix (an adjoint), reusing its factor or preconditioner
|
|
25
26
|
*/
|
|
26
|
-
export function solve(g: Grid, { scale, ke, fixed, loads, method, backend, tol, maxIter, start }: {
|
|
27
|
+
export function solve(g: Grid, { scale, ke, fixed, loads, springs, method, backend, tol, maxIter, start }: {
|
|
27
28
|
scale: Float64Array;
|
|
28
29
|
ke: Float64Array;
|
|
29
30
|
fixed: Uint8Array;
|
|
30
31
|
loads: Float64Array[];
|
|
32
|
+
springs?: Float64Array;
|
|
31
33
|
method?: "direct" | "cg" | "mg";
|
|
32
34
|
backend?: typeof jsBackend;
|
|
33
35
|
tol?: number;
|
|
@@ -37,6 +39,7 @@ export function solve(g: Grid, { scale, ke, fixed, loads, method, backend, tol,
|
|
|
37
39
|
u: Float64Array[];
|
|
38
40
|
iterations: number;
|
|
39
41
|
again: (loads: Float64Array[]) => Float64Array[];
|
|
42
|
+
warning?: string;
|
|
40
43
|
};
|
|
41
44
|
/**
|
|
42
45
|
* Stress at a cell's centre from its corners' movements, for Young's modulus 1: a matrix (rows × cell dofs, row by row;
|
|
@@ -85,6 +88,18 @@ export function analyse({ grid: g, density, material, thickness, fixed, loads, p
|
|
|
85
88
|
at: number[];
|
|
86
89
|
}[];
|
|
87
90
|
};
|
|
91
|
+
/**
|
|
92
|
+
* How much of the part lies in members too thin for the grid to carry truthfully: the share of its solid cells (density
|
|
93
|
+
* 0.5 or more) that an opening of `k` cells takes away (eroded k times, then grown back: a member under 2k cells thick
|
|
94
|
+
* vanishes, a corner loses a little). A cell's stiffness across a member two or three cells thick is a rough
|
|
95
|
+
* figure (the READMEs' tables); four cells and up it settles. { share, cells: 2k }.
|
|
96
|
+
* @param {Grid} g @param {ArrayLike<number>} density @param {number} [k] erosions, 2 (members under 4 cells)
|
|
97
|
+
* @returns {{ share: number, cells: number }}
|
|
98
|
+
*/
|
|
99
|
+
export function thinShare(g: Grid, density: ArrayLike<number>, k?: number): {
|
|
100
|
+
share: number;
|
|
101
|
+
cells: number;
|
|
102
|
+
};
|
|
88
103
|
/**
|
|
89
104
|
* Each node's position in mm, [x, y] (or [x, y, z]), by node number.
|
|
90
105
|
* @param {Grid} g
|
package/fea.mjs
CHANGED
|
@@ -129,7 +129,12 @@ export const jsBackend = {
|
|
|
129
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
130
|
if (dim === 2) {
|
|
131
131
|
const det = D[0] * D[3] - D[1] * D[2];
|
|
132
|
-
if (!(Math.abs(det) > 0))
|
|
132
|
+
if (!(Math.abs(det) > 0)) {
|
|
133
|
+
// One dof fixed (a roller, a symmetry edge): the block is singular, so invert the free dof on its own,
|
|
134
|
+
// as the 3D branch does. (Skipped, the node was never smoothed, and multigrid never converged)
|
|
135
|
+
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];
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
133
138
|
inv[b] = D[3] / det; inv[b + 1] = -D[1] / det; inv[b + 2] = -D[2] / det; inv[b + 3] = D[0] / det;
|
|
134
139
|
} else {
|
|
135
140
|
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;
|
|
@@ -266,29 +271,49 @@ export function assemble(g, pat, cellMatrices, ke, scale, into) {
|
|
|
266
271
|
/**
|
|
267
272
|
* Solve K u = f for each load. K is every cell's stiffness (cellStiffness) times scale[cell]; fixed dofs don't move.
|
|
268
273
|
* @param {Grid} g
|
|
269
|
-
* @param {{ scale: Float64Array, ke: Float64Array, fixed: Uint8Array, loads: Float64Array[], method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend, tol?: number, maxIter?: number, start?: Float64Array[] }} o
|
|
274
|
+
* @param {{ scale: Float64Array, ke: Float64Array, fixed: Uint8Array, loads: Float64Array[], springs?: Float64Array, method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend, tol?: number, maxIter?: number, start?: Float64Array[] }} o
|
|
275
|
+
* springs: a stiffness added on each dof (N/mm), as a mechanism's input and output springs
|
|
270
276
|
* start: a first guess for the iterative solvers (the last solution, when solving again after a small change)
|
|
271
|
-
* @returns {{ u: Float64Array[], iterations: number, again: (loads: Float64Array[]) => Float64Array[] }} again: more
|
|
277
|
+
* @returns {{ u: Float64Array[], iterations: number, again: (loads: Float64Array[]) => Float64Array[], warning?: string }} warning: multigrid on a grid it couldn't halve far (slow); again: more
|
|
272
278
|
* loads on the same matrix (an adjoint), reusing its factor or preconditioner
|
|
273
279
|
*/
|
|
274
|
-
export function solve(g, { scale, ke, fixed, loads, method = 'direct', backend = jsBackend, tol = 1e-9, maxIter = 20000, start }) {
|
|
280
|
+
export function solve(g, { scale, ke, fixed, loads, springs, method = 'direct', backend = jsBackend, tol = 1e-9, maxIter = 20000, start }) {
|
|
281
|
+
// What's wrong with what was handed in is said here, by name: further in, it comes out as a part "not held still",
|
|
282
|
+
// or as an answer that looks like one
|
|
283
|
+
if (!['direct', 'cg', 'mg'].includes(method)) throw new Error(`no solver "${method}": direct, cg or mg`);
|
|
275
284
|
if (scale.length !== g.cells) throw new Error(`scale has ${scale.length} values for ${g.cells} cells`);
|
|
285
|
+
if (fixed.length !== g.dofs) throw new Error(`fixed has ${fixed.length} values for ${g.dofs} unknowns (${g.dim} a node)`);
|
|
286
|
+
loads.forEach((l, c) => { if (l.length !== g.dofs) throw new Error(`load ${c + 1} has ${l.length} values for ${g.dofs} unknowns (${g.dim} a node)`); });
|
|
287
|
+
if (springs && springs.length !== g.dofs) throw new Error(`springs has ${springs.length} values for ${g.dofs} unknowns`);
|
|
288
|
+
for (let e = 0; e < scale.length; e++) if (!(scale[e] > 0) || !Number.isFinite(scale[e])) throw new Error(`cell ${e}'s stiffness is ${scale[e]}: every cell needs a stiffness above 0 (a density, modulus or thickness is 0, negative or not a number)`);
|
|
289
|
+
for (let i = 0; i < ke.length; i++) if (!Number.isFinite(ke[i])) throw new Error("the cell's stiffness matrix isn't numbers: Poisson's ratio must be between -1 and 0.5");
|
|
290
|
+
loads.forEach((l, c) => { for (let i = 0; i < l.length; i++) if (!Number.isFinite(l[i])) throw new Error(`load ${c + 1} has a force that isn't a number`); });
|
|
276
291
|
if (!fixed.some((f) => f)) throw new Error('nothing is held: fix at least one support, or the part just moves');
|
|
277
292
|
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; });
|
|
278
293
|
if (method === 'direct') {
|
|
279
|
-
const L = factor(g, { scale, ke }, fixed), again = (ls) => held(ls).map((b) => L.solve(b));
|
|
294
|
+
const L = factor(g, { scale, ke, springs }, fixed), again = (ls) => held(ls).map((b) => L.solve(b));
|
|
280
295
|
return { u: again(loads), iterations: 0, again };
|
|
281
296
|
}
|
|
282
|
-
const
|
|
297
|
+
const cells = backend.operator(g, ke); // one for the solver and its preconditioner: the matrix is assembled once
|
|
298
|
+
// Springs on dofs (a mechanism's input and output): added to the product and the diagonal; the smoother, where the
|
|
299
|
+
// backend has one, doesn't know them, so Jacobi then (the preconditioner needn't be exact)
|
|
300
|
+
const op = springs ? {
|
|
301
|
+
multiply(s, x, y) { cells.multiply(s, x, y); for (let i = 0; i < y.length; i++) if (springs[i]) y[i] += springs[i] * x[i]; },
|
|
302
|
+
diagonal(s, d) { cells.diagonal(s, d); for (let i = 0; i < d.length; i++) d[i] += springs[i]; },
|
|
303
|
+
} : cells;
|
|
283
304
|
const precondition = method === 'mg' ? multigrid(g, { scale, ke, fixed, backend, op }) : jacobi(g, { scale, fixed, op });
|
|
305
|
+
// Multigrid halves each side while it can: a grid with an odd side stops early, and its coarsest grid, solved
|
|
306
|
+
// directly, can be most of the work (33 × 17 × 17 cells took 80 times 32 × 16 × 16). Said, with the sides to give
|
|
307
|
+
const coarse = method === 'mg' ? hierarchy(g).grids.at(-1) : null, slow = coarse && coarse.dofs > 20 * COARSEST;
|
|
308
|
+
const warning = slow ? `multigrid stopped at ${[coarse.nx, coarse.ny, coarse.nz].filter(Boolean).join(' × ')} cells (${coarse.dofs} unknowns, solved directly): a side that can't be halved again; give each side a multiple of 8 cells for a fast solve` : null;
|
|
284
309
|
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 };
|
|
310
|
+
return { ...conjugateGradients(g, { scale, fixed, loads: held(loads), backend, tol, maxIter, start, precondition, op }), again, ...(warning ? { warning } : {}) };
|
|
286
311
|
}
|
|
287
312
|
|
|
288
313
|
// The banded Cholesky factor of K (cells' matrices: ke × scale, or each its own), fixed dofs as identity rows. Lenient
|
|
289
314
|
// (a preconditioner's coarsest grid, where a coarse unknown over next to nothing can come out singular to rounding), a
|
|
290
315
|
// 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 } = {}) {
|
|
316
|
+
function factor(g, { scale, ke, cellMatrices, springs }, fixed, { lenient = false } = {}) {
|
|
292
317
|
const { edof, dofs, cells, cellDofs: m } = g, mm = m * m;
|
|
293
318
|
let b = 0;
|
|
294
319
|
for (let e = 0; e < cells; e++) {
|
|
@@ -309,6 +334,7 @@ function factor(g, { scale, ke, cellMatrices }, fixed, { lenient = false } = {})
|
|
|
309
334
|
}
|
|
310
335
|
}
|
|
311
336
|
}
|
|
337
|
+
if (springs) for (let i = 0; i < dofs; i++) if (!fixed[i]) L[i * w + b] += springs[i];
|
|
312
338
|
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
339
|
const dropped = lenient ? new Uint8Array(dofs) : null;
|
|
314
340
|
for (let i = 0; i < dofs; i++) {
|
|
@@ -372,7 +398,8 @@ function conjugateGradients(g, { scale, fixed, loads, backend, tol, maxIter, sta
|
|
|
372
398
|
let rz = backend.dot(r, z), it = 0;
|
|
373
399
|
while (Math.sqrt(backend.dot(r, r)) > limit && it < maxIter) {
|
|
374
400
|
apply(p, q);
|
|
375
|
-
const
|
|
401
|
+
const pq = backend.dot(p, q), a = rz / pq;
|
|
402
|
+
if (!(pq > 0) || !Number.isFinite(a)) throw new Error('the part is not held still (it can slide or turn under this load): add supports, or join loose pieces to it'); // (a direction with no stiffness: the search would go on for ever, or stop on nonsense)
|
|
376
403
|
backend.axpy(a, p, x); backend.axpy(-a, q, r);
|
|
377
404
|
precondition(r, z);
|
|
378
405
|
const next = backend.dot(r, z);
|
|
@@ -619,15 +646,30 @@ export function stress(g, u, modulus, nu) {
|
|
|
619
646
|
* of any node in solid material, and where.
|
|
620
647
|
*/
|
|
621
648
|
export function analyse({ grid: g, density, material, thickness = 1, fixed, loads, penal = 1, method = g.dim === 3 ? 'mg' : 'direct', backend }) {
|
|
649
|
+
if (!(material?.E > 0)) throw new Error(`the material needs a modulus E above 0, in MPa (got ${material?.E})`);
|
|
650
|
+
if (!(material.nu > -1 && material.nu < 0.5)) throw new Error(`the material needs a Poisson's ratio nu between -1 and 0.5 (got ${material.nu}): about 0.35 for printed plastics`);
|
|
651
|
+
if (g.dim === 2 && !(thickness > 0)) throw new Error(`a flat part needs a thickness above 0 mm (got ${thickness})`);
|
|
652
|
+
if (density.length !== g.cells) throw new Error(`density has ${density.length} values for ${g.cells} cells`);
|
|
653
|
+
for (let e = 0; e < density.length; e++) if (!(density[e] >= 0 && density[e] <= 1)) throw new Error(`cell ${e}'s density is ${density[e]}: each is a share from 0 (empty) to 1 (solid)`);
|
|
622
654
|
const { E, nu } = material, Emin = E * 1e-9, ke = cellStiffness(nu, g.dim);
|
|
623
655
|
const modulus = Float64Array.from(density, (x) => Emin + Math.pow(x, penal) * (E - Emin));
|
|
624
656
|
const scale = modulus.map((mod) => mod * (g.dim === 3 ? g.h : thickness));
|
|
625
657
|
const { u } = solve(g, { scale, ke, fixed, loads, method, backend });
|
|
626
658
|
const solidNode = new Uint8Array(g.nodes), corners = CORNERS[g.dim].length;
|
|
627
659
|
for (let e = 0; e < density.length; e++) if (density[e] >= 0.5) for (let k = 0; k < corners; k++) solidNode[g.edof[e * g.cellDofs + g.dim * k] / g.dim] = 1;
|
|
660
|
+
// A part that can still slide or turn is solved all the same, by a hair's stiffness of rounding: it then "moves"
|
|
661
|
+
// many times its own size. No real part does, so that is said, not handed back as a deflection. (Most of the
|
|
662
|
+
// part, that is: a loose piece beside a held part, such as a disc lying in a mechanism, is the caller's business.)
|
|
663
|
+
const span = Math.max(g.nx, g.ny, g.nz || 1) * g.h;
|
|
664
|
+
for (const x of u) {
|
|
665
|
+
let solid = 0, adrift = 0;
|
|
666
|
+
for (let n = 0; n < g.nodes; n++) if (solidNode[n]) { solid++; for (let d = 0; d < g.dim; d++) if (!(Math.abs(x[g.dim * n + d]) < 1e4 * span)) { adrift++; break; } }
|
|
667
|
+
if (adrift > solid / 2) throw Object.assign(new Error('the part is not held still (it can slide or turn under this load): fix more of it, in each direction it could move'), { code: 'fea.unheld' });
|
|
668
|
+
}
|
|
628
669
|
const position = positions(g);
|
|
629
670
|
return {
|
|
630
671
|
u,
|
|
672
|
+
thin: thinShare(g, density),
|
|
631
673
|
compliance: u.map((x, c) => jsBackend.dot(loads[c], x)),
|
|
632
674
|
stress: u.map((x) => stress(g, x, modulus, nu)),
|
|
633
675
|
deflection: u.map((x) => {
|
|
@@ -642,6 +684,36 @@ export function analyse({ grid: g, density, material, thickness = 1, fixed, load
|
|
|
642
684
|
};
|
|
643
685
|
}
|
|
644
686
|
|
|
687
|
+
/**
|
|
688
|
+
* How much of the part lies in members too thin for the grid to carry truthfully: the share of its solid cells (density
|
|
689
|
+
* 0.5 or more) that an opening of `k` cells takes away (eroded k times, then grown back: a member under 2k cells thick
|
|
690
|
+
* vanishes, a corner loses a little). A cell's stiffness across a member two or three cells thick is a rough
|
|
691
|
+
* figure (the READMEs' tables); four cells and up it settles. { share, cells: 2k }.
|
|
692
|
+
* @param {Grid} g @param {ArrayLike<number>} density @param {number} [k] erosions, 2 (members under 4 cells)
|
|
693
|
+
* @returns {{ share: number, cells: number }}
|
|
694
|
+
*/
|
|
695
|
+
export function thinShare(g, density, k = 2) {
|
|
696
|
+
const nx = g.nx, ny = g.ny, nz = g.dim === 3 ? g.nz : 1, N = nx * ny * nz, at = (i, j, l) => (l * ny + j) * nx + i;
|
|
697
|
+
let mask = new Uint8Array(N);
|
|
698
|
+
for (let e = 0; e < N; e++) mask[e] = density[e] >= 0.5 ? 1 : 0;
|
|
699
|
+
const solid = mask.reduce((a, b) => a + b, 0);
|
|
700
|
+
if (!solid) return { share: 0, cells: 2 * k };
|
|
701
|
+
const pass = (m, keep) => { // keep: every face-neighbour solid (erode) or any (dilate); outside the grid counts as the cell itself
|
|
702
|
+
const out = new Uint8Array(N);
|
|
703
|
+
for (let l = 0; l < nz; l++) for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) {
|
|
704
|
+
const e = at(i, j, l), n = [i > 0 ? m[at(i - 1, j, l)] : m[e], i + 1 < nx ? m[at(i + 1, j, l)] : m[e], j > 0 ? m[at(i, j - 1, l)] : m[e], j + 1 < ny ? m[at(i, j + 1, l)] : m[e], ...(nz > 1 ? [l > 0 ? m[at(i, j, l - 1)] : m[e], l + 1 < nz ? m[at(i, j, l + 1)] : m[e]] : [])];
|
|
705
|
+
out[e] = keep === 'all' ? (m[e] && n.every((x) => x) ? 1 : 0) : (m[e] || n.some((x) => x) ? 1 : 0);
|
|
706
|
+
}
|
|
707
|
+
return out;
|
|
708
|
+
};
|
|
709
|
+
let m = mask;
|
|
710
|
+
for (let i = 0; i < k; i++) m = pass(m, 'all');
|
|
711
|
+
for (let i = 0; i < k; i++) m = pass(m, 'any');
|
|
712
|
+
let lost = 0;
|
|
713
|
+
for (let e = 0; e < N; e++) if (mask[e] && !m[e]) lost++;
|
|
714
|
+
return { share: lost / solid, cells: 2 * k };
|
|
715
|
+
}
|
|
716
|
+
|
|
645
717
|
/**
|
|
646
718
|
* Each node's position in mm, [x, y] (or [x, y, z]), by node number.
|
|
647
719
|
* @param {Grid} g
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulecad/fea",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.8",
|
|
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": {
|
|
@@ -38,6 +38,10 @@
|
|
|
38
38
|
"url": "git+https://github.com/JoniBach/rulecad.git",
|
|
39
39
|
"directory": "packages/fea"
|
|
40
40
|
},
|
|
41
|
+
"homepage": "https://github.com/JoniBach/rulecad/tree/main/packages/fea#readme",
|
|
42
|
+
"bugs": {
|
|
43
|
+
"url": "https://github.com/JoniBach/rulecad/issues"
|
|
44
|
+
},
|
|
41
45
|
"scripts": {
|
|
42
46
|
"test": "node --test"
|
|
43
47
|
},
|
package/threads.d.mts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export namespace threadsBackend {
|
|
2
|
+
let name: string;
|
|
3
|
+
let precision: number;
|
|
4
|
+
function operator(g: any, ke: any, cellMatrices: any): {
|
|
5
|
+
multiply(scale: any, x: any, y: any): void;
|
|
6
|
+
diagonal(scale: any, d: any): void;
|
|
7
|
+
};
|
|
8
|
+
let dot: (a: Float64Array, b: Float64Array) => number;
|
|
9
|
+
let axpy: (a: number, x: Float64Array, y: Float64Array) => void;
|
|
10
|
+
}
|
package/threads.mjs
CHANGED
|
@@ -8,11 +8,14 @@ import os from 'node:os';
|
|
|
8
8
|
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
9
9
|
import { jsBackend, pattern, assemble } from './fea.mjs';
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
// FEA_THREADS: a whole number of worker threads, 1 to 8; anything else is refused by name (2.5 was taken as 2.5)
|
|
12
|
+
const asked = process.env.FEA_THREADS;
|
|
13
|
+
if (asked != null && asked !== '' && !/^[1-8]$/.test(asked.trim())) throw new Error(`FEA_THREADS is "${asked}": give a whole number of threads from 1 to 8, or leave it unset`);
|
|
14
|
+
const THREADS = asked ? Number(asked) : Math.max(1, Math.min(8, os.cpus().length - 1));
|
|
12
15
|
// How many operators each worker keeps: an optimisation step registers one per multigrid level (four or so), and
|
|
13
16
|
// their arrays are large (the bin's: 160 MB), so the workers let go of all but the last few. Before this, a run
|
|
14
17
|
// kept every step's and swapped itself to a crawl.
|
|
15
|
-
const KEPT =
|
|
18
|
+
const KEPT = 8;
|
|
16
19
|
|
|
17
20
|
// The pool: made on first use, kept for the process (unref'd, so it doesn't keep the process alive). Each operator
|
|
18
21
|
// registers its arrays with every worker under an id; a product then signals the id and waits for every worker's done.
|
|
@@ -30,7 +33,7 @@ function workers() {
|
|
|
30
33
|
Atomics.store(ctl, 3, 0);
|
|
31
34
|
for (const w of list) w.postMessage({ id, ...arrays });
|
|
32
35
|
// Wake the workers to take the message (a product with no operator), then wait for every one to hold the arrays
|
|
33
|
-
pool.multiply(0);
|
|
36
|
+
pool.multiply(0); Atomics.store(ctl, 4, 0);
|
|
34
37
|
while (Atomics.load(ctl, 3) < THREADS) Atomics.wait(ctl, 3, Atomics.load(ctl, 3), 50);
|
|
35
38
|
return id;
|
|
36
39
|
},
|
|
@@ -38,7 +41,8 @@ function workers() {
|
|
|
38
41
|
Atomics.store(ctl, 2, 0); Atomics.store(ctl, 1, id);
|
|
39
42
|
Atomics.add(ctl, 0, 1); Atomics.notify(ctl, 0);
|
|
40
43
|
while (Atomics.load(ctl, 2) < THREADS) Atomics.wait(ctl, 2, Atomics.load(ctl, 2), 50);
|
|
41
|
-
if (Atomics.load(ctl, 4)) { Atomics.store(ctl, 4, 0);
|
|
44
|
+
if (Atomics.load(ctl, 4)) { Atomics.store(ctl, 4, 0); return false; } // (an operator the workers had let go: the caller registers it again)
|
|
45
|
+
return true;
|
|
42
46
|
},
|
|
43
47
|
};
|
|
44
48
|
return pool;
|
|
@@ -57,7 +61,9 @@ export const threadsBackend = {
|
|
|
57
61
|
if (id === null) id = workers().register({ dim, nodes: n, rows: pat.rows, cols: pat.cols, values, xs, ys });
|
|
58
62
|
};
|
|
59
63
|
return {
|
|
60
|
-
|
|
64
|
+
// (a solve's again() kept past several others finds its operator let go by the workers, who keep the last few:
|
|
65
|
+
// registered again, from the arrays this side still holds, and the product taken)
|
|
66
|
+
multiply(scale, x, y) { ready(scale); xs.set(x); if (!workers().multiply(id)) { id = workers().register({ dim, nodes: n, rows: pat.rows, cols: pat.cols, values, xs, ys }); workers().multiply(id); } y.set(ys); },
|
|
61
67
|
diagonal(scale, d) {
|
|
62
68
|
ready(scale);
|
|
63
69
|
const { rows, self } = pat;
|