@rulecad/fea 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +44 -2
- package/fea.d.mts +118 -0
- package/fea.mjs +529 -0
- package/package.json +35 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 JoniBach and contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,45 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @rulecad/fea
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
How far a part bends under load. Finite elements on a grid of cells, each with its own stiffness: flat parts loaded
|
|
4
|
+
in their own plane (2D, plane stress, square cells) and solid parts (3D, cubes). Plain JavaScript in typed arrays, no dependencies: it runs in browsers
|
|
5
|
+
and Node alike. Units are millimetres and newtons, so Young's modulus is in MPa and movement in mm.
|
|
6
|
+
|
|
7
|
+
```js
|
|
8
|
+
import { grid, analyse } from '@rulecad/fea';
|
|
9
|
+
|
|
10
|
+
const g = grid({ nx: 100, ny: 10, h: 1 }); // 100 × 10 cells of 1 mm
|
|
11
|
+
const fixed = new Uint8Array(g.dofs), load = new Float64Array(g.dofs);
|
|
12
|
+
for (let j = 0; j <= 10; j++) { fixed[2 * g.node(0, j)] = 1; fixed[2 * g.node(0, j) + 1] = 1; } // hold the left edge
|
|
13
|
+
load[2 * g.node(100, 5) + 1] = -10; // 10 N down at the right end
|
|
14
|
+
const r = analyse({ grid: g, density: new Float64Array(1000).fill(1), material: { E: 2680, nu: 0.36 }, thickness: 5, fixed, loads: [load] });
|
|
15
|
+
r.u[0]; // each node's movement: x at 2n, y at 2n + 1
|
|
16
|
+
r.compliance[0]; // the load times how far it moved (N·mm): lower is stiffer
|
|
17
|
+
r.stress[0]; // each cell's von Mises stress (MPa)
|
|
18
|
+
r.deflection[0]; // { most, at }: the largest movement of solid material, and where
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
- **3D:** give the grid `nz` too (`grid({ nx, ny, nz, h })`) and every node has x, y and z.
|
|
22
|
+
- **Cells:** 4-node squares (bilinear, integrated at 2 × 2 Gauss points) or 8-node cubes (trilinear, 2 × 2 × 2). Each cell's density, 0 to 1, scales its
|
|
23
|
+
stiffness (by `density ** penal`), so the same code analyses a part, a part filling only some of its thickness, and
|
|
24
|
+
a topology optimisation's in-between designs.
|
|
25
|
+
- **Solvers:**
|
|
26
|
+
- `direct`: a banded Cholesky factorisation. Exact; quick for 2D grids up to about 100,000 cells and small 3D ones.
|
|
27
|
+
- `cg`: conjugate gradients with a diagonal preconditioner.
|
|
28
|
+
- `mg`: conjugate gradients with a multigrid preconditioner, the default in 3D. Coarser grids halve each side. Each
|
|
29
|
+
coarse cell's matrix is built from its children's exactly (Galerkin), so it stays accurate when cells'
|
|
30
|
+
stiffnesses differ a millionfold, as they do in topology optimisation. A cantilever of 16,000 cubes takes 9
|
|
31
|
+
iterations, where plain `cg` takes 371.
|
|
32
|
+
- **Backends:** the few operations `cg` repeats (the stiffness product, its diagonal, dot products) sit behind a small
|
|
33
|
+
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.
|
|
35
|
+
|
|
36
|
+
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
|
+
Multigrid is tested against the direct solver with stiffnesses a millionfold apart.
|
|
38
|
+
|
|
39
|
+
## Sources
|
|
40
|
+
|
|
41
|
+
- Amir, Aage, Lazarov (2014). On multigrid-CG for efficient topology optimization. *Structural and Multidisciplinary
|
|
42
|
+
Optimization* 49, 815–829.
|
|
43
|
+
- Andreassen, Clausen, Schevenels, Lazarov, Sigmund (2011). Efficient topology optimization in MATLAB using 88 lines
|
|
44
|
+
of code. *Structural and Multidisciplinary Optimization* 43, 1–16.
|
|
45
|
+
- Cook, Malkus, Plesha, Witt (2002). *Concepts and Applications of Finite Element Analysis*, 4th ed. Wiley.
|
package/fea.d.mts
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A grid of square (2D) or cube (3D) cells, with each cell's unknowns: its corners in order, x, y (and z) for each.
|
|
3
|
+
* @param {GridSize} size
|
|
4
|
+
* @returns {Grid}
|
|
5
|
+
*/
|
|
6
|
+
export function grid({ nx, ny, nz, h }: GridSize): Grid;
|
|
7
|
+
/**
|
|
8
|
+
* A cell's stiffness matrix (8 × 8 in 2D, 24 × 24 in 3D, row by row) for Young's modulus 1 and a cell of side 1 (in
|
|
9
|
+
* 2D, thickness 1). In 2D it's the same for any cell size; in 3D it scales with the side. Integrated at 2 × 2 (× 2)
|
|
10
|
+
* Gauss points, as for any bilinear (trilinear) element.
|
|
11
|
+
* @param {number} nu Poisson's ratio
|
|
12
|
+
* @param {2 | 3} [dim]
|
|
13
|
+
* @returns {Float64Array}
|
|
14
|
+
*/
|
|
15
|
+
export function cellStiffness(nu: number, dim?: 2 | 3): Float64Array;
|
|
16
|
+
/**
|
|
17
|
+
* Solve K u = f for each load. K is every cell's stiffness (cellStiffness) times scale[cell]; fixed dofs don't move.
|
|
18
|
+
* @param {Grid} g
|
|
19
|
+
* @param {{ scale: Float64Array, ke: Float64Array, fixed: Uint8Array, loads: Float64Array[], method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend, tol?: number, maxIter?: number, start?: Float64Array[] }} o
|
|
20
|
+
* start: a first guess for the iterative solvers (the last solution, when solving again after a small change)
|
|
21
|
+
* @returns {{ u: Float64Array[], iterations: number }}
|
|
22
|
+
*/
|
|
23
|
+
export function solve(g: Grid, { scale, ke, fixed, loads, method, backend, tol, maxIter, start }: {
|
|
24
|
+
scale: Float64Array;
|
|
25
|
+
ke: Float64Array;
|
|
26
|
+
fixed: Uint8Array;
|
|
27
|
+
loads: Float64Array[];
|
|
28
|
+
method?: "direct" | "cg" | "mg";
|
|
29
|
+
backend?: typeof jsBackend;
|
|
30
|
+
tol?: number;
|
|
31
|
+
maxIter?: number;
|
|
32
|
+
start?: Float64Array[];
|
|
33
|
+
}): {
|
|
34
|
+
u: Float64Array[];
|
|
35
|
+
iterations: number;
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Each cell's von Mises stress (MPa) at its centre, from a solution u.
|
|
39
|
+
* @param {Grid} g @param {Float64Array} u @param {Float64Array} modulus each cell's Young's modulus (MPa) @param {number} nu
|
|
40
|
+
* @returns {Float64Array}
|
|
41
|
+
*/
|
|
42
|
+
export function stress(g: Grid, u: Float64Array, modulus: Float64Array, nu: number): Float64Array;
|
|
43
|
+
/**
|
|
44
|
+
* Analyse a part: each cell's density (0 empty to 1 solid; Young's modulus scales with density^penal, never below
|
|
45
|
+
* E × 1e-9 so empty cells don't leave the matrix singular), supports and loads. In 2D the part is a plate of the given
|
|
46
|
+
* thickness; in 3D thickness is not used.
|
|
47
|
+
* @param {{ grid: Grid, density: Float64Array, material: Material, thickness?: number, fixed: Uint8Array, loads: Float64Array[], penal?: number, method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend }} o
|
|
48
|
+
* @returns {{ u: Float64Array[], compliance: number[], stress: Float64Array[], deflection: { most: number, at: number[] }[] }}
|
|
49
|
+
* compliance: f · u per load (N·mm): the work the load does; lower is stiffer. deflection: the largest movement
|
|
50
|
+
* of any node in solid material, and where.
|
|
51
|
+
*/
|
|
52
|
+
export function analyse({ grid: g, density, material, thickness, fixed, loads, penal, method, backend }: {
|
|
53
|
+
grid: Grid;
|
|
54
|
+
density: Float64Array;
|
|
55
|
+
material: Material;
|
|
56
|
+
thickness?: number;
|
|
57
|
+
fixed: Uint8Array;
|
|
58
|
+
loads: Float64Array[];
|
|
59
|
+
penal?: number;
|
|
60
|
+
method?: "direct" | "cg" | "mg";
|
|
61
|
+
backend?: typeof jsBackend;
|
|
62
|
+
}): {
|
|
63
|
+
u: Float64Array[];
|
|
64
|
+
compliance: number[];
|
|
65
|
+
stress: Float64Array[];
|
|
66
|
+
deflection: {
|
|
67
|
+
most: number;
|
|
68
|
+
at: number[];
|
|
69
|
+
}[];
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* Each node's position in mm, [x, y] (or [x, y, z]), by node number.
|
|
73
|
+
* @param {Grid} g
|
|
74
|
+
* @returns {number[][]}
|
|
75
|
+
*/
|
|
76
|
+
export function positions(g: Grid): number[][];
|
|
77
|
+
/**
|
|
78
|
+
* The plain JavaScript backend: the operations the iterative solvers repeat, on Float64Arrays. Another backend
|
|
79
|
+
* (WebGPU, TensorFlow.js) provides the same and is tested against this one (backend-suite.mjs).
|
|
80
|
+
* 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.
|
|
82
|
+
* @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
|
+
*/
|
|
84
|
+
export const jsBackend: {
|
|
85
|
+
name: string;
|
|
86
|
+
precision: number;
|
|
87
|
+
operator: (g: Grid, ke: Float64Array | null, cellMatrices?: Float64Array) => {
|
|
88
|
+
multiply: (scale: Float64Array | null, x: Float64Array, y: Float64Array) => void;
|
|
89
|
+
diagonal: (scale: Float64Array | null, d: Float64Array) => void;
|
|
90
|
+
};
|
|
91
|
+
dot: (a: Float64Array, b: Float64Array) => number;
|
|
92
|
+
axpy: (a: number, x: Float64Array, y: Float64Array) => void;
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* cells along x, y (and z for 3D), and their side in mm
|
|
96
|
+
*/
|
|
97
|
+
export type GridSize = {
|
|
98
|
+
nx: number;
|
|
99
|
+
ny: number;
|
|
100
|
+
nz?: number;
|
|
101
|
+
h: number;
|
|
102
|
+
};
|
|
103
|
+
export type Grid = GridSize & {
|
|
104
|
+
dim: 2 | 3;
|
|
105
|
+
cells: number;
|
|
106
|
+
nodes: number;
|
|
107
|
+
dofs: number;
|
|
108
|
+
cellDofs: number;
|
|
109
|
+
edof: Int32Array;
|
|
110
|
+
node: (i: number, j: number, k?: number) => number;
|
|
111
|
+
};
|
|
112
|
+
/**
|
|
113
|
+
* Young's modulus (MPa) and Poisson's ratio
|
|
114
|
+
*/
|
|
115
|
+
export type Material = {
|
|
116
|
+
E: number;
|
|
117
|
+
nu: number;
|
|
118
|
+
};
|
package/fea.mjs
ADDED
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
// Finite elements on a grid of cells, each with its own stiffness: flat parts loaded in their own plane (2D, plane
|
|
2
|
+
// stress, square cells) and solid parts (3D, cubes). Plain numbers in typed arrays, no dependencies: it runs in
|
|
3
|
+
// browsers and Node alike. Units are millimetres and newtons, so stiffness (Young's modulus) is in MPa (N/mm²) and
|
|
4
|
+
// displacement in mm.
|
|
5
|
+
//
|
|
6
|
+
// The grid: nx × ny (× nz) cells of side h, cell (i, j, k) with i along x, j along y and k along z, its lowest corner
|
|
7
|
+
// at (i h, j h, k h). Nodes are the cells' corners, with an unknown for each direction they can move (2 in 2D, 3 in
|
|
8
|
+
// 3D): node n's x is dof d n, its y d n + 1 (and z d n + 2), d the dimension. Nodes are numbered with the grid's
|
|
9
|
+
// longest side changing slowest, which keeps the stiffness matrix's band narrow.
|
|
10
|
+
//
|
|
11
|
+
// Three ways to solve:
|
|
12
|
+
// "direct" banded Cholesky factorisation: exact; quick for 2D grids up to about 100,000 cells and small 3D ones
|
|
13
|
+
// "cg" conjugate gradients, never assembling the matrix, with a diagonal (Jacobi) preconditioner
|
|
14
|
+
// "mg" conjugate gradients with a multigrid preconditioner: for big grids, and 3D. Each coarser grid's cells are
|
|
15
|
+
// built from the finer grid's exactly (Galerkin: R K P, cell by cell), so it stays accurate when cells'
|
|
16
|
+
// stiffnesses differ a millionfold, as they do in topology optimisation (Amir, Aage, Lazarov 2014)
|
|
17
|
+
// The work the solvers repeat (a stiffness product, its diagonal, dot products) sits behind a backend, so a GPU can do
|
|
18
|
+
// it; plain JavaScript in 64-bit floats is the reference.
|
|
19
|
+
|
|
20
|
+
/** @typedef {{ nx: number, ny: number, nz?: number, h: number }} GridSize cells along x, y (and z for 3D), and their side in mm */
|
|
21
|
+
/** @typedef {GridSize & { dim: 2 | 3, cells: number, nodes: number, dofs: number, cellDofs: number, edof: Int32Array, node: (i: number, j: number, k?: number) => number }} Grid */
|
|
22
|
+
/** @typedef {{ E: number, nu: number }} Material Young's modulus (MPa) and Poisson's ratio */
|
|
23
|
+
|
|
24
|
+
// A cell's corners, in order: counter-clockwise from the lowest (then the same again a layer up, in 3D)
|
|
25
|
+
const CORNERS = { 2: [[0, 0], [1, 0], [1, 1], [0, 1]], 3: [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]] };
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* A grid of square (2D) or cube (3D) cells, with each cell's unknowns: its corners in order, x, y (and z) for each.
|
|
29
|
+
* @param {GridSize} size
|
|
30
|
+
* @returns {Grid}
|
|
31
|
+
*/
|
|
32
|
+
export function grid({ nx, ny, nz, h = 1 }) {
|
|
33
|
+
const dim = nz ? 3 : 2, n = dim === 3 ? [nx, ny, nz] : [nx, ny];
|
|
34
|
+
if (!n.every((c) => c >= 1 && Number.isInteger(c))) throw new Error(`a grid needs whole numbers of cells (got ${n.join(' × ')})`);
|
|
35
|
+
// Strides: the longest side changes slowest (ties: x slowest, then y)
|
|
36
|
+
const axes = n.map((c, a) => a).sort((a, b) => n[a] - n[b] || b - a), stride = new Array(dim);
|
|
37
|
+
let s = 1;
|
|
38
|
+
for (const a of axes) { stride[a] = s; s *= n[a] + 1; }
|
|
39
|
+
const nodes = s;
|
|
40
|
+
const node = dim === 3 ? (i, j, k) => i * stride[0] + j * stride[1] + k * stride[2] : (i, j) => i * stride[0] + j * stride[1];
|
|
41
|
+
const corners = CORNERS[dim], cellDofs = corners.length * dim, cells = n.reduce((p, c) => p * c, 1);
|
|
42
|
+
const edof = new Int32Array(cells * cellDofs);
|
|
43
|
+
for (let e = 0; e < cells; e++) {
|
|
44
|
+
const i = e % nx, j = Math.floor(e / nx) % ny, k = dim === 3 ? Math.floor(e / (nx * ny)) : 0;
|
|
45
|
+
corners.forEach((c, q) => {
|
|
46
|
+
const m = node(i + c[0], j + c[1], k + (c[2] || 0));
|
|
47
|
+
for (let d = 0; d < dim; d++) edof[e * cellDofs + q * dim + d] = dim * m + d;
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
return { nx, ny, ...(dim === 3 ? { nz } : {}), h, dim, cells, nodes, dofs: dim * nodes, cellDofs, edof, node };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// The strain-displacement matrix of a cell of side h at natural coordinates p (each -1 to 1), row by row: 3 × 8 in 2D
|
|
54
|
+
// (εx, εy, γxy), 6 × 24 in 3D (εx, εy, εz, γxy, γyz, γzx)
|
|
55
|
+
function strains(p, h, dim) {
|
|
56
|
+
const corners = CORNERS[dim], m = corners.length * dim, rows = dim === 3 ? 6 : 3, B = new Float64Array(rows * m);
|
|
57
|
+
corners.forEach((c, q) => {
|
|
58
|
+
const sign = c.map((x) => 2 * x - 1);
|
|
59
|
+
// dN/dx along each axis: the corner's sign along it, times (1 + sign p) along the others, over 2^dim, times 2 / h
|
|
60
|
+
const g = sign.map((sa, a) => sa * sign.reduce((f, sb, b) => (b === a ? f : f * (1 + sb * p[b])), 1) / (1 << dim) * (2 / h));
|
|
61
|
+
const col = q * dim;
|
|
62
|
+
if (dim === 2) {
|
|
63
|
+
B[col] = g[0]; B[m + col + 1] = g[1]; B[2 * m + col] = g[1]; B[2 * m + col + 1] = g[0];
|
|
64
|
+
} else {
|
|
65
|
+
B[col] = g[0]; B[m + col + 1] = g[1]; B[2 * m + col + 2] = g[2];
|
|
66
|
+
B[3 * m + col] = g[1]; B[3 * m + col + 1] = g[0];
|
|
67
|
+
B[4 * m + col + 1] = g[2]; B[4 * m + col + 2] = g[1];
|
|
68
|
+
B[5 * m + col] = g[2]; B[5 * m + col + 2] = g[0];
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
return B;
|
|
72
|
+
}
|
|
73
|
+
// Stress from strain for Young's modulus 1: plane stress in 2D, isotropic in 3D
|
|
74
|
+
function elasticity(nu, dim) {
|
|
75
|
+
if (dim === 2) { const f = 1 / (1 - nu * nu); return [f, f * nu, 0, f * nu, f, 0, 0, 0, f * (1 - nu) / 2]; }
|
|
76
|
+
const f = 1 / ((1 + nu) * (1 - 2 * nu)), a = f * (1 - nu), b = f * nu, c = f * (1 - 2 * nu) / 2, D = new Array(36).fill(0);
|
|
77
|
+
for (let r = 0; r < 3; r++) for (let q = 0; q < 3; q++) D[r * 6 + q] = r === q ? a : b;
|
|
78
|
+
for (let r = 3; r < 6; r++) D[r * 6 + r] = c;
|
|
79
|
+
return D;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* A cell's stiffness matrix (8 × 8 in 2D, 24 × 24 in 3D, row by row) for Young's modulus 1 and a cell of side 1 (in
|
|
84
|
+
* 2D, thickness 1). In 2D it's the same for any cell size; in 3D it scales with the side. Integrated at 2 × 2 (× 2)
|
|
85
|
+
* Gauss points, as for any bilinear (trilinear) element.
|
|
86
|
+
* @param {number} nu Poisson's ratio
|
|
87
|
+
* @param {2 | 3} [dim]
|
|
88
|
+
* @returns {Float64Array}
|
|
89
|
+
*/
|
|
90
|
+
export function cellStiffness(nu, dim = 2) {
|
|
91
|
+
const D = elasticity(nu, dim), m = CORNERS[dim].length * dim, rows = dim === 3 ? 6 : 3, K = new Float64Array(m * m);
|
|
92
|
+
const g = 1 / Math.sqrt(3), weight = 1 / (1 << dim); // side 1: the Jacobian is (1/2)^dim
|
|
93
|
+
const points = dim === 3 ? [-g, g].flatMap((a) => [-g, g].flatMap((b) => [-g, g].map((c) => [a, b, c]))) : [-g, g].flatMap((a) => [-g, g].map((b) => [a, b]));
|
|
94
|
+
for (const p of points) {
|
|
95
|
+
const B = strains(p, 1, dim), DB = new Float64Array(rows * m);
|
|
96
|
+
for (let r = 0; r < rows; r++) for (let c = 0; c < m; c++) { let s = 0; for (let t = 0; t < rows; t++) s += D[r * rows + t] * B[t * m + c]; DB[r * m + c] = s; }
|
|
97
|
+
for (let a = 0; a < m; a++) for (let b = 0; b < m; b++) { let s = 0; for (let r = 0; r < rows; r++) s += B[r * m + a] * DB[r * m + b]; K[a * m + b] += s * weight; }
|
|
98
|
+
}
|
|
99
|
+
return K;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The plain JavaScript backend: the operations the iterative solvers repeat, on Float64Arrays. Another backend
|
|
104
|
+
* (WebGPU, TensorFlow.js) provides the same and is tested against this one (backend-suite.mjs).
|
|
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.
|
|
107
|
+
* @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
|
+
*/
|
|
109
|
+
export const jsBackend = {
|
|
110
|
+
name: 'js',
|
|
111
|
+
precision: 64,
|
|
112
|
+
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;
|
|
119
|
+
return {
|
|
120
|
+
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;
|
|
128
|
+
}
|
|
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;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
},
|
|
147
|
+
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
|
+
}
|
|
153
|
+
},
|
|
154
|
+
};
|
|
155
|
+
},
|
|
156
|
+
dot(a, b) { let s = 0; for (let i = 0; i < a.length; i++) s += a[i] * b[i]; return s; },
|
|
157
|
+
axpy(a, x, y) { for (let i = 0; i < y.length; i++) y[i] += a * x[i]; },
|
|
158
|
+
};
|
|
159
|
+
|
|
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) {
|
|
164
|
+
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));
|
|
169
|
+
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
|
+
const offsets = [];
|
|
171
|
+
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
|
+
});
|
|
180
|
+
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
|
+
}
|
|
186
|
+
}
|
|
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);
|
|
189
|
+
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;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
const out = { rows, columns: Int32Array.from(columns), slot };
|
|
199
|
+
patterns.set(g, out);
|
|
200
|
+
return out;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Solve K u = f for each load. K is every cell's stiffness (cellStiffness) times scale[cell]; fixed dofs don't move.
|
|
205
|
+
* @param {Grid} g
|
|
206
|
+
* @param {{ scale: Float64Array, ke: Float64Array, fixed: Uint8Array, loads: Float64Array[], method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend, tol?: number, maxIter?: number, start?: Float64Array[] }} o
|
|
207
|
+
* start: a first guess for the iterative solvers (the last solution, when solving again after a small change)
|
|
208
|
+
* @returns {{ u: Float64Array[], iterations: number }}
|
|
209
|
+
*/
|
|
210
|
+
export function solve(g, { scale, ke, fixed, loads, method = 'direct', backend = jsBackend, tol = 1e-9, maxIter = 20000, start }) {
|
|
211
|
+
if (scale.length !== g.cells) throw new Error(`scale has ${scale.length} values for ${g.cells} cells`);
|
|
212
|
+
if (!fixed.some((f) => f)) throw new Error('nothing is held: fix at least one support, or the part just moves');
|
|
213
|
+
const f = loads.map((l) => { const c = Float64Array.from(l); for (let i = 0; i < c.length; i++) if (fixed[i]) c[i] = 0; return c; });
|
|
214
|
+
if (method === 'direct') {
|
|
215
|
+
const L = factor(g, { scale, ke }, fixed);
|
|
216
|
+
return { u: f.map((b) => L.solve(b)), iterations: 0 };
|
|
217
|
+
}
|
|
218
|
+
const op = backend.operator(g, ke); // one for the solver and its preconditioner: the matrix is assembled once
|
|
219
|
+
const precondition = method === 'mg' ? multigrid(g, { scale, ke, fixed, backend, op }) : jacobi(g, { scale, fixed, op });
|
|
220
|
+
return conjugateGradients(g, { scale, fixed, loads: f, backend, tol, maxIter, start, precondition, op });
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// The banded Cholesky factor of K (cells' matrices: ke × scale, or each its own), fixed dofs as identity rows
|
|
224
|
+
function factor(g, { scale, ke, cellMatrices }, fixed) {
|
|
225
|
+
const { edof, dofs, cells, cellDofs: m } = g, mm = m * m;
|
|
226
|
+
let b = 0;
|
|
227
|
+
for (let e = 0; e < cells; e++) {
|
|
228
|
+
let lo = Infinity, hi = -Infinity;
|
|
229
|
+
for (let a = 0; a < m; a++) { lo = Math.min(lo, edof[e * m + a]); hi = Math.max(hi, edof[e * m + a]); }
|
|
230
|
+
b = Math.max(b, hi - lo);
|
|
231
|
+
}
|
|
232
|
+
const w = b + 1, L = new Float64Array(dofs * w); // L[i][j] (j ≤ i, i - j ≤ b) at i * w + b - i + j: a row's band in order
|
|
233
|
+
for (let e = 0; e < cells; e++) {
|
|
234
|
+
const s = scale ? scale[e] : 1, K = cellMatrices || ke, base = cellMatrices ? e * mm : 0;
|
|
235
|
+
for (let p = 0; p < m; p++) {
|
|
236
|
+
const i = edof[e * m + p];
|
|
237
|
+
if (fixed[i]) continue;
|
|
238
|
+
for (let q = 0; q < m; q++) {
|
|
239
|
+
const j = edof[e * m + q];
|
|
240
|
+
if (j > i || fixed[j]) continue;
|
|
241
|
+
L[i * w + b - i + j] += s * K[base + p * m + q];
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
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
|
|
246
|
+
for (let i = 0; i < dofs; i++) {
|
|
247
|
+
const from = Math.max(0, i - b), ri = i * w + b - i; // L[i][k] is at ri + k
|
|
248
|
+
for (let j = from; j <= i; j++) {
|
|
249
|
+
const rj = j * w + b - j;
|
|
250
|
+
let s = L[ri + j], s1 = 0, s2 = 0, s3 = 0, k = from;
|
|
251
|
+
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
|
|
252
|
+
for (; k < j; k++) s -= L[ri + k] * L[rj + k];
|
|
253
|
+
s -= s1 + s2 + s3;
|
|
254
|
+
if (j === i) {
|
|
255
|
+
if (!(s > 0)) throw new Error('the part is not held still: add supports, or join loose pieces to it');
|
|
256
|
+
L[i * w + b] = Math.sqrt(s);
|
|
257
|
+
} else L[ri + j] = s / L[j * w + b];
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
return {
|
|
261
|
+
solve(f) {
|
|
262
|
+
const x = Float64Array.from(f);
|
|
263
|
+
for (let i = 0; i < dofs; i++) {
|
|
264
|
+
let s = x[i];
|
|
265
|
+
for (let k = Math.max(0, i - b); k < i; k++) s -= L[i * w + b - i + k] * x[k];
|
|
266
|
+
x[i] = s / L[i * w + b];
|
|
267
|
+
}
|
|
268
|
+
for (let i = dofs - 1; i >= 0; i--) {
|
|
269
|
+
let s = x[i];
|
|
270
|
+
for (let k = i + 1; k <= Math.min(dofs - 1, i + b); k++) s -= L[k * w + b - k + i] * x[k];
|
|
271
|
+
x[i] = s / L[i * w + b];
|
|
272
|
+
}
|
|
273
|
+
return x;
|
|
274
|
+
},
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// The diagonal preconditioner: each residual over its diagonal
|
|
279
|
+
function jacobi(g, { scale, fixed, op }) {
|
|
280
|
+
const d = new Float64Array(g.dofs);
|
|
281
|
+
op.diagonal(scale, d);
|
|
282
|
+
for (let i = 0; i < d.length; i++) d[i] = fixed[i] || !(d[i] > 0) ? 1 : 1 / d[i];
|
|
283
|
+
return (r, z) => { for (let i = 0; i < r.length; i++) z[i] = d[i] * r[i]; };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// Conjugate gradients, matrix-free: fixed dofs stay at 0 (their rows act as the identity)
|
|
287
|
+
function conjugateGradients(g, { scale, fixed, loads, backend, tol, maxIter, start, precondition, op }) {
|
|
288
|
+
const n = g.dofs;
|
|
289
|
+
const apply = (x, y) => { op.multiply(scale, x, y); for (let i = 0; i < n; i++) if (fixed[i]) y[i] = x[i]; };
|
|
290
|
+
let total = 0;
|
|
291
|
+
const u = loads.map((f, c) => {
|
|
292
|
+
const x = start?.[c] ? Float64Array.from(start[c]) : new Float64Array(n);
|
|
293
|
+
for (let i = 0; i < n; i++) if (fixed[i]) x[i] = 0;
|
|
294
|
+
const r = new Float64Array(n), z = new Float64Array(n), p = new Float64Array(n), q = new Float64Array(n);
|
|
295
|
+
apply(x, q);
|
|
296
|
+
for (let i = 0; i < n; i++) r[i] = f[i] - q[i];
|
|
297
|
+
const limit = tol * Math.sqrt(backend.dot(f, f));
|
|
298
|
+
precondition(r, z); p.set(z);
|
|
299
|
+
let rz = backend.dot(r, z), it = 0;
|
|
300
|
+
while (Math.sqrt(backend.dot(r, r)) > limit && it < maxIter) {
|
|
301
|
+
apply(p, q);
|
|
302
|
+
const a = rz / backend.dot(p, q);
|
|
303
|
+
backend.axpy(a, p, x); backend.axpy(-a, q, r);
|
|
304
|
+
precondition(r, z);
|
|
305
|
+
const next = backend.dot(r, z);
|
|
306
|
+
for (let i = 0; i < n; i++) p[i] = z[i] + (next / rz) * p[i];
|
|
307
|
+
rz = next; it++;
|
|
308
|
+
}
|
|
309
|
+
if (it >= maxIter) throw new Error(`the solver didn't settle in ${maxIter} steps: the part may be barely held, or a piece of it loose`);
|
|
310
|
+
total += it;
|
|
311
|
+
return x;
|
|
312
|
+
});
|
|
313
|
+
return { u, iterations: total };
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// ---------- multigrid ----------
|
|
317
|
+
// Coarser grids halve each side while every side is even and the grid has more than about 3,000 unknowns. A coarse
|
|
318
|
+
// cell's matrix is its 2^d children's, carried up by the trilinear (bilinear) interpolation from its corners to theirs
|
|
319
|
+
// (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
|
+
// V: two damped Jacobi sweeps down, the coarsest grid solved exactly (banded Cholesky), two sweeps on the way up.
|
|
321
|
+
// It's symmetric, so conjugate gradients can use it as a preconditioner.
|
|
322
|
+
const SWEEPS = 2, DAMPING = 0.5, COARSEST = 3000;
|
|
323
|
+
|
|
324
|
+
// The coarser grids under a grid, and the maps between each pair, worked out once per grid (they don't change as the
|
|
325
|
+
// cells' stiffnesses do)
|
|
326
|
+
const hierarchies = new WeakMap();
|
|
327
|
+
function hierarchy(g) {
|
|
328
|
+
if (hierarchies.has(g)) return hierarchies.get(g);
|
|
329
|
+
const grids = [g];
|
|
330
|
+
for (;;) {
|
|
331
|
+
const fg = grids.at(-1), sides = fg.dim === 3 ? [fg.nx, fg.ny, fg.nz] : [fg.nx, fg.ny];
|
|
332
|
+
if (fg.dofs <= COARSEST || sides.some((s) => s % 2)) break;
|
|
333
|
+
grids.push(grid({ nx: fg.nx / 2, ny: fg.ny / 2, ...(fg.dim === 3 ? { nz: fg.nz / 2 } : {}), h: fg.h * 2 }));
|
|
334
|
+
}
|
|
335
|
+
const maps = grids.slice(1).map((cg, l) => transfer(grids[l], cg));
|
|
336
|
+
const out = { grids, maps };
|
|
337
|
+
hierarchies.set(g, out);
|
|
338
|
+
return out;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function multigrid(g, { scale, ke, fixed, backend, op }) {
|
|
342
|
+
const { grids, maps } = hierarchy(g);
|
|
343
|
+
const levels = [{ g, op, scale, fixed: Uint8Array.from(fixed), mats: null }];
|
|
344
|
+
for (let l = 1; l < grids.length; l++) {
|
|
345
|
+
const f = levels.at(-1), fg = f.g, cg = grids[l];
|
|
346
|
+
const mats = coarsen(fg, cg, f.mats || ke, f.mats ? null : f.scale, f.fixed);
|
|
347
|
+
const cfixed = new Uint8Array(cg.dofs), diag = new Float64Array(cg.dofs), m = cg.cellDofs;
|
|
348
|
+
for (let e = 0; e < cg.cells; e++) for (let a = 0; a < m; a++) diag[cg.edof[e * m + a]] += mats[e * m * m + a * (m + 1)];
|
|
349
|
+
for (let i = 0; i < cg.dofs; i++) if (!(diag[i] > 0)) cfixed[i] = 1; // nothing below moves it: held
|
|
350
|
+
levels.push({ g: cg, op: backend.operator(cg, null, mats), scale: null, fixed: cfixed, mats });
|
|
351
|
+
}
|
|
352
|
+
for (const l of levels) { // each level's diagonal, for its Jacobi sweeps
|
|
353
|
+
l.inv = new Float64Array(l.g.dofs);
|
|
354
|
+
l.op.diagonal(l.scale, l.inv);
|
|
355
|
+
for (let i = 0; i < l.inv.length; i++) l.inv[i] = l.fixed[i] || !(l.inv[i] > 0) ? 0 : DAMPING / l.inv[i];
|
|
356
|
+
}
|
|
357
|
+
const last = levels.at(-1), coarse = factor(last.g, { scale: last.scale, ke, cellMatrices: last.mats }, last.fixed);
|
|
358
|
+
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; };
|
|
359
|
+
|
|
360
|
+
const cycle = (k, r) => {
|
|
361
|
+
const l = levels[k];
|
|
362
|
+
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
|
+
const n = l.g.dofs, x = new Float64Array(n), Ax = new Float64Array(n), res = new Float64Array(n);
|
|
364
|
+
const sweep = () => { apply(l, x, Ax); for (let i = 0; i < n; i++) x[i] += l.inv[i] * (r[i] - Ax[i]); };
|
|
365
|
+
for (let s = 0; s < SWEEPS; s++) sweep();
|
|
366
|
+
apply(l, x, Ax);
|
|
367
|
+
for (let i = 0; i < n; i++) res[i] = l.fixed[i] ? 0 : r[i] - Ax[i];
|
|
368
|
+
const e = maps[k].prolong(cycle(k + 1, maps[k].restrict(res)));
|
|
369
|
+
for (let i = 0; i < n; i++) x[i] += l.fixed[i] ? 0 : e[i];
|
|
370
|
+
for (let s = 0; s < SWEEPS; s++) sweep();
|
|
371
|
+
return x;
|
|
372
|
+
};
|
|
373
|
+
return (r, z) => {
|
|
374
|
+
const x = cycle(0, r);
|
|
375
|
+
for (let i = 0; i < z.length; i++) z[i] = fixed[i] ? r[i] : x[i];
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// The interpolation weights from a coarse cell's corners to one child's corners: for child offset o (each 0 or 1),
|
|
380
|
+
// a (cellDofs × cellDofs) matrix P_o with child dof = Σ P_o[child][coarse] × coarse dof, kept as its nonzero entries
|
|
381
|
+
function childInterpolation(dim) {
|
|
382
|
+
const corners = CORNERS[dim], m = corners.length * dim, out = [];
|
|
383
|
+
for (const o of corners) {
|
|
384
|
+
const P = new Float64Array(m * m);
|
|
385
|
+
corners.forEach((c, q) => { // the child's corner q, at (o + c) / 2 in the coarse cell
|
|
386
|
+
const at = c.map((x, a) => (o[a] + x) / 2);
|
|
387
|
+
corners.forEach((C, Q) => {
|
|
388
|
+
const wgt = at.reduce((p, x, a) => p * (C[a] ? x : 1 - x), 1);
|
|
389
|
+
if (wgt) for (let d = 0; d < dim; d++) P[(q * dim + d) * m + Q * dim + d] = wgt;
|
|
390
|
+
});
|
|
391
|
+
});
|
|
392
|
+
// As its nonzero entries: rows, columns, weights
|
|
393
|
+
const rows = [], cols = [], wts = [];
|
|
394
|
+
for (let r = 0; r < m; r++) for (let c = 0; c < m; c++) if (P[r * m + c]) { rows.push(r); cols.push(c); wts.push(P[r * m + c]); }
|
|
395
|
+
out.push([Int32Array.from(rows), Int32Array.from(cols), Float64Array.from(wts)]);
|
|
396
|
+
}
|
|
397
|
+
return out;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// Each coarse cell's matrix: Σ over its children of P_oᵀ (child's matrix, fixed rows and columns left out) P_o, using
|
|
401
|
+
// only P_o's nonzero weights (about one in seven)
|
|
402
|
+
const interpolations = { 2: null, 3: null };
|
|
403
|
+
function coarsen(fg, cg, K, scale, fixed) {
|
|
404
|
+
const dim = fg.dim, m = fg.cellDofs, mm = m * m, corners = CORNERS[dim];
|
|
405
|
+
const P = interpolations[dim] || (interpolations[dim] = childInterpolation(dim));
|
|
406
|
+
const out = new Float64Array(cg.cells * mm), KP = new Float64Array(mm), held = new Uint8Array(m);
|
|
407
|
+
const shared = scale ? K : null; // fine level: one matrix scaled per cell; coarser: each cell its own
|
|
408
|
+
const offset = corners.map((o) => ((o[2] || 0) * fg.ny + o[1]) * fg.nx + o[0]); // a child's cell number from its first
|
|
409
|
+
for (let E = 0; E < cg.cells; E++) {
|
|
410
|
+
const I = E % cg.nx, J = Math.floor(E / cg.nx) % cg.ny, Kz = dim === 3 ? Math.floor(E / (cg.nx * cg.ny)) : 0;
|
|
411
|
+
const first = (2 * Kz * fg.ny + 2 * J) * fg.nx + 2 * I, o0 = E * mm;
|
|
412
|
+
for (let oi = 0; oi < corners.length; oi++) {
|
|
413
|
+
const e = first + offset[oi], s = scale ? scale[e] : 1, base = shared ? 0 : e * mm, src = shared || K;
|
|
414
|
+
for (let a = 0; a < m; a++) held[a] = fixed[fg.edof[e * m + a]];
|
|
415
|
+
const [rows, cols, wts] = P[oi];
|
|
416
|
+
KP.fill(0);
|
|
417
|
+
for (let t = 0; t < wts.length; t++) { // KP = child × P_o
|
|
418
|
+
const b = rows[t];
|
|
419
|
+
if (held[b]) continue;
|
|
420
|
+
const c = cols[t], w = s * wts[t];
|
|
421
|
+
for (let a = 0; a < m; a++) if (!held[a]) KP[a * m + c] += src[base + a * m + b] * w;
|
|
422
|
+
}
|
|
423
|
+
for (let t = 0; t < wts.length; t++) { // out += P_oᵀ × KP
|
|
424
|
+
const a = rows[t], r = cols[t], w = wts[t], ro = o0 + r * m, ka = a * m;
|
|
425
|
+
for (let c = 0; c < m; c++) out[ro + c] += w * KP[ka + c];
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
return out;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// Between a fine grid and the next coarser: prolong (coarse to fine: each fine node takes the interpolation of the
|
|
433
|
+
// coarse nodes round it, 1, 2, 4 or 8 of them) and restrict, its transpose. Each fine node's coarse nodes and weights
|
|
434
|
+
// are listed once, as flat arrays.
|
|
435
|
+
function transfer(fg, cg) {
|
|
436
|
+
const dim = fg.dim, nk = dim === 3 ? fg.nz : 0, start = new Int32Array(fg.nodes + 1), from = [], weight = [];
|
|
437
|
+
const order = new Int32Array(fg.nodes);
|
|
438
|
+
let n = 0;
|
|
439
|
+
for (let k = 0; k <= nk; k++) for (let j = 0; j <= fg.ny; j++) for (let i = 0; i <= fg.nx; i++) {
|
|
440
|
+
const node = dim === 3 ? fg.node(i, j, k) : fg.node(i, j);
|
|
441
|
+
let picks = [[i >> 1, j >> 1, k >> 1]];
|
|
442
|
+
[i, j, k].slice(0, dim).forEach((c, a) => { if (c & 1) picks = picks.flatMap((p) => [p, p.map((v, b) => (b === a ? v + 1 : v))]); });
|
|
443
|
+
for (const c of picks) { from.push(dim === 3 ? cg.node(c[0], c[1], c[2]) : cg.node(c[0], c[1])); weight.push(1 / picks.length); }
|
|
444
|
+
order[n] = node; start[++n] = from.length;
|
|
445
|
+
}
|
|
446
|
+
const F = Int32Array.from(from), W = Float64Array.from(weight);
|
|
447
|
+
return {
|
|
448
|
+
prolong(xc) {
|
|
449
|
+
const xf = new Float64Array(fg.dofs);
|
|
450
|
+
for (let q = 0; q < fg.nodes; q++) {
|
|
451
|
+
const o = dim * order[q];
|
|
452
|
+
for (let t = start[q]; t < start[q + 1]; t++) { const c = dim * F[t], w = W[t]; for (let d = 0; d < dim; d++) xf[o + d] += w * xc[c + d]; }
|
|
453
|
+
}
|
|
454
|
+
return xf;
|
|
455
|
+
},
|
|
456
|
+
restrict(rf) {
|
|
457
|
+
const rc = new Float64Array(cg.dofs);
|
|
458
|
+
for (let q = 0; q < fg.nodes; q++) {
|
|
459
|
+
const o = dim * order[q];
|
|
460
|
+
for (let t = start[q]; t < start[q + 1]; t++) { const c = dim * F[t], w = W[t]; for (let d = 0; d < dim; d++) rc[c + d] += w * rf[o + d]; }
|
|
461
|
+
}
|
|
462
|
+
return rc;
|
|
463
|
+
},
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* Each cell's von Mises stress (MPa) at its centre, from a solution u.
|
|
469
|
+
* @param {Grid} g @param {Float64Array} u @param {Float64Array} modulus each cell's Young's modulus (MPa) @param {number} nu
|
|
470
|
+
* @returns {Float64Array}
|
|
471
|
+
*/
|
|
472
|
+
export function stress(g, u, modulus, nu) {
|
|
473
|
+
const dim = g.dim, m = g.cellDofs, rows = dim === 3 ? 6 : 3, B = strains(new Array(dim).fill(0), g.h, dim), D = elasticity(nu, dim), out = new Float64Array(g.cells);
|
|
474
|
+
const strain = new Float64Array(rows);
|
|
475
|
+
for (let e = 0; e < g.cells; e++) {
|
|
476
|
+
strain.fill(0);
|
|
477
|
+
for (let p = 0; p < rows; p++) for (let a = 0; a < m; a++) strain[p] += B[p * m + a] * u[g.edof[e * m + a]];
|
|
478
|
+
const s = new Array(rows).fill(0).map((_, p) => { let t = 0; for (let q = 0; q < rows; q++) t += D[p * rows + q] * strain[q]; return modulus[e] * t; });
|
|
479
|
+
out[e] = dim === 2 ? Math.sqrt(s[0] * s[0] - s[0] * s[1] + s[1] * s[1] + 3 * s[2] * s[2])
|
|
480
|
+
: Math.sqrt(((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));
|
|
481
|
+
}
|
|
482
|
+
return out;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Analyse a part: each cell's density (0 empty to 1 solid; Young's modulus scales with density^penal, never below
|
|
487
|
+
* E × 1e-9 so empty cells don't leave the matrix singular), supports and loads. In 2D the part is a plate of the given
|
|
488
|
+
* thickness; in 3D thickness is not used.
|
|
489
|
+
* @param {{ grid: Grid, density: Float64Array, material: Material, thickness?: number, fixed: Uint8Array, loads: Float64Array[], penal?: number, method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend }} o
|
|
490
|
+
* @returns {{ u: Float64Array[], compliance: number[], stress: Float64Array[], deflection: { most: number, at: number[] }[] }}
|
|
491
|
+
* compliance: f · u per load (N·mm): the work the load does; lower is stiffer. deflection: the largest movement
|
|
492
|
+
* of any node in solid material, and where.
|
|
493
|
+
*/
|
|
494
|
+
export function analyse({ grid: g, density, material, thickness = 1, fixed, loads, penal = 1, method = g.dim === 3 ? 'mg' : 'direct', backend }) {
|
|
495
|
+
const { E, nu } = material, Emin = E * 1e-9, ke = cellStiffness(nu, g.dim);
|
|
496
|
+
const modulus = Float64Array.from(density, (x) => Emin + Math.pow(x, penal) * (E - Emin));
|
|
497
|
+
const scale = modulus.map((mod) => mod * (g.dim === 3 ? g.h : thickness));
|
|
498
|
+
const { u } = solve(g, { scale, ke, fixed, loads, method, backend });
|
|
499
|
+
const solidNode = new Uint8Array(g.nodes), corners = CORNERS[g.dim].length;
|
|
500
|
+
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;
|
|
501
|
+
const position = positions(g);
|
|
502
|
+
return {
|
|
503
|
+
u,
|
|
504
|
+
compliance: u.map((x, c) => jsBackend.dot(loads[c], x)),
|
|
505
|
+
stress: u.map((x) => stress(g, x, modulus, nu)),
|
|
506
|
+
deflection: u.map((x) => {
|
|
507
|
+
let most = 0, at = position[0];
|
|
508
|
+
for (let n = 0; n < g.nodes; n++) if (solidNode[n]) {
|
|
509
|
+
let s = 0;
|
|
510
|
+
for (let d = 0; d < g.dim; d++) s += x[g.dim * n + d] ** 2;
|
|
511
|
+
if (Math.sqrt(s) > most) { most = Math.sqrt(s); at = position[n]; }
|
|
512
|
+
}
|
|
513
|
+
return { most, at };
|
|
514
|
+
}),
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* Each node's position in mm, [x, y] (or [x, y, z]), by node number.
|
|
520
|
+
* @param {Grid} g
|
|
521
|
+
* @returns {number[][]}
|
|
522
|
+
*/
|
|
523
|
+
export function positions(g) {
|
|
524
|
+
const out = new Array(g.nodes), nk = g.dim === 3 ? g.nz : 0;
|
|
525
|
+
for (let k = 0; k <= nk; k++) for (let j = 0; j <= g.ny; j++) for (let i = 0; i <= g.nx; i++) {
|
|
526
|
+
if (g.dim === 3) out[g.node(i, j, k)] = [i * g.h, j * g.h, k * g.h]; else out[g.node(i, j)] = [i * g.h, j * g.h];
|
|
527
|
+
}
|
|
528
|
+
return out;
|
|
529
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulecad/fea",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
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
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
"types": "./fea.d.mts",
|
|
8
|
+
"default": "./fea.mjs"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"fea.mjs",
|
|
12
|
+
"fea.d.mts",
|
|
13
|
+
"README.md",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"keywords": [
|
|
18
|
+
"fea",
|
|
19
|
+
"finite-elements",
|
|
20
|
+
"stiffness",
|
|
21
|
+
"stress",
|
|
22
|
+
"plane-stress"
|
|
23
|
+
],
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=20"
|
|
26
|
+
},
|
|
27
|
+
"sideEffects": false,
|
|
28
|
+
"repository": {
|
|
29
|
+
"type": "git",
|
|
30
|
+
"url": "git+https://github.com/JoniBach/rulecad.git",
|
|
31
|
+
"directory": "packages/fea"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"test": "node --test"
|
|
35
|
+
},
|
|
36
|
+
"types": "./fea.d.mts"
|
|
37
|
+
}
|