@rulecad/fea 0.1.0 → 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/README.md +15 -6
- package/fea.d.mts +35 -29
- package/fea.mjs +364 -97
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# @rulecad/fea
|
|
2
2
|
|
|
3
|
-
How far a
|
|
4
|
-
|
|
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
5
|
and Node alike. Units are millimetres and newtons, so Young's modulus is in MPa and movement in mm.
|
|
6
6
|
|
|
7
7
|
```js
|
|
@@ -18,19 +18,28 @@ 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
19
|
```
|
|
20
20
|
|
|
21
|
-
- **
|
|
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
|
|
22
23
|
stiffness (by `density ** penal`), so the same code analyses a part, a part filling only some of its thickness, and
|
|
23
24
|
a topology optimisation's in-between designs.
|
|
24
|
-
- **Solvers:**
|
|
25
|
-
`
|
|
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.
|
|
26
32
|
- **Backends:** the few operations `cg` repeats (the stiffness product, its diagonal, dot products) sit behind a small
|
|
27
33
|
interface. `jsBackend`, plain JavaScript in 64-bit floats, is the reference; a WebGPU or TensorFlow.js backend
|
|
28
34
|
implements the same and passes `backend-suite.mjs` in this repository.
|
|
29
35
|
|
|
30
|
-
Tested against beam theory: a cantilever's tip moves within 1% of `F L³ / 3 E I
|
|
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.
|
|
31
38
|
|
|
32
39
|
## Sources
|
|
33
40
|
|
|
41
|
+
- Amir, Aage, Lazarov (2014). On multigrid-CG for efficient topology optimization. *Structural and Multidisciplinary
|
|
42
|
+
Optimization* 49, 815–829.
|
|
34
43
|
- Andreassen, Clausen, Schevenels, Lazarov, Sigmund (2011). Efficient topology optimization in MATLAB using 88 lines
|
|
35
44
|
of code. *Structural and Multidisciplinary Optimization* 43, 1–16.
|
|
36
45
|
- Cook, Malkus, Plesha, Witt (2002). *Concepts and Applications of Finite Element Analysis*, 4th ed. Wiley.
|
package/fea.d.mts
CHANGED
|
@@ -1,24 +1,23 @@
|
|
|
1
|
-
/** @typedef {{ nx: number, ny: number, h: number }} GridSize cells along x and y, and their side in mm */
|
|
2
|
-
/** @typedef {GridSize & { nodes: number, dofs: number, edof: Int32Array, node: (i: number, j: number) => number }} Grid */
|
|
3
|
-
/** @typedef {{ E: number, nu: number }} Material Young's modulus (MPa) and Poisson's ratio */
|
|
4
1
|
/**
|
|
5
|
-
* A grid of square cells, with each cell's
|
|
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.
|
|
6
3
|
* @param {GridSize} size
|
|
7
4
|
* @returns {Grid}
|
|
8
5
|
*/
|
|
9
|
-
export function grid({ nx, ny, h }: GridSize): Grid;
|
|
6
|
+
export function grid({ nx, ny, nz, h }: GridSize): Grid;
|
|
10
7
|
/**
|
|
11
|
-
* A
|
|
12
|
-
*
|
|
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.
|
|
13
11
|
* @param {number} nu Poisson's ratio
|
|
12
|
+
* @param {2 | 3} [dim]
|
|
14
13
|
* @returns {Float64Array}
|
|
15
14
|
*/
|
|
16
|
-
export function cellStiffness(nu: number): Float64Array;
|
|
15
|
+
export function cellStiffness(nu: number, dim?: 2 | 3): Float64Array;
|
|
17
16
|
/**
|
|
18
17
|
* Solve K u = f for each load. K is every cell's stiffness (cellStiffness) times scale[cell]; fixed dofs don't move.
|
|
19
18
|
* @param {Grid} g
|
|
20
|
-
* @param {{ scale: Float64Array, ke: Float64Array, fixed: Uint8Array, loads: Float64Array[], method?: 'direct' | 'cg', backend?: typeof jsBackend, tol?: number, maxIter?: number, start?: Float64Array[] }} o
|
|
21
|
-
* start: a first guess for
|
|
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)
|
|
22
21
|
* @returns {{ u: Float64Array[], iterations: number }}
|
|
23
22
|
*/
|
|
24
23
|
export function solve(g: Grid, { scale, ke, fixed, loads, method, backend, tol, maxIter, start }: {
|
|
@@ -26,7 +25,7 @@ export function solve(g: Grid, { scale, ke, fixed, loads, method, backend, tol,
|
|
|
26
25
|
ke: Float64Array;
|
|
27
26
|
fixed: Uint8Array;
|
|
28
27
|
loads: Float64Array[];
|
|
29
|
-
method?: "direct" | "cg";
|
|
28
|
+
method?: "direct" | "cg" | "mg";
|
|
30
29
|
backend?: typeof jsBackend;
|
|
31
30
|
tol?: number;
|
|
32
31
|
maxIter?: number;
|
|
@@ -42,10 +41,11 @@ export function solve(g: Grid, { scale, ke, fixed, loads, method, backend, tol,
|
|
|
42
41
|
*/
|
|
43
42
|
export function stress(g: Grid, u: Float64Array, modulus: Float64Array, nu: number): Float64Array;
|
|
44
43
|
/**
|
|
45
|
-
* Analyse a
|
|
46
|
-
* E × 1e-9 so empty cells don't leave the matrix singular),
|
|
47
|
-
*
|
|
48
|
-
* @
|
|
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
49
|
* compliance: f · u per load (N·mm): the work the load does; lower is stiffer. deflection: the largest movement
|
|
50
50
|
* of any node in solid material, and where.
|
|
51
51
|
*/
|
|
@@ -53,11 +53,11 @@ export function analyse({ grid: g, density, material, thickness, fixed, loads, p
|
|
|
53
53
|
grid: Grid;
|
|
54
54
|
density: Float64Array;
|
|
55
55
|
material: Material;
|
|
56
|
-
thickness
|
|
56
|
+
thickness?: number;
|
|
57
57
|
fixed: Uint8Array;
|
|
58
58
|
loads: Float64Array[];
|
|
59
59
|
penal?: number;
|
|
60
|
-
method?: "direct" | "cg";
|
|
60
|
+
method?: "direct" | "cg" | "mg";
|
|
61
61
|
backend?: typeof jsBackend;
|
|
62
62
|
}): {
|
|
63
63
|
u: Float64Array[];
|
|
@@ -65,43 +65,49 @@ export function analyse({ grid: g, density, material, thickness, fixed, loads, p
|
|
|
65
65
|
stress: Float64Array[];
|
|
66
66
|
deflection: {
|
|
67
67
|
most: number;
|
|
68
|
-
at: [
|
|
68
|
+
at: number[];
|
|
69
69
|
}[];
|
|
70
70
|
};
|
|
71
71
|
/**
|
|
72
|
-
* Each node's position in mm, [x, y], by node number.
|
|
72
|
+
* Each node's position in mm, [x, y] (or [x, y, z]), by node number.
|
|
73
73
|
* @param {Grid} g
|
|
74
|
-
* @returns {[
|
|
74
|
+
* @returns {number[][]}
|
|
75
75
|
*/
|
|
76
|
-
export function positions(g: Grid): [
|
|
76
|
+
export function positions(g: Grid): number[][];
|
|
77
77
|
/**
|
|
78
|
-
* The plain JavaScript backend: the operations
|
|
79
|
-
* TensorFlow.js) provides the same and is tested against this one.
|
|
80
|
-
*
|
|
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 }}
|
|
81
83
|
*/
|
|
82
84
|
export const jsBackend: {
|
|
83
85
|
name: string;
|
|
84
86
|
precision: number;
|
|
85
|
-
operator: (g: Grid, ke: Float64Array) => {
|
|
86
|
-
multiply: (scale: Float64Array, x: Float64Array, y: Float64Array) => void;
|
|
87
|
-
diagonal: (scale: Float64Array, d: Float64Array) => void;
|
|
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;
|
|
88
90
|
};
|
|
89
91
|
dot: (a: Float64Array, b: Float64Array) => number;
|
|
90
92
|
axpy: (a: number, x: Float64Array, y: Float64Array) => void;
|
|
91
93
|
};
|
|
92
94
|
/**
|
|
93
|
-
* cells along x and
|
|
95
|
+
* cells along x, y (and z for 3D), and their side in mm
|
|
94
96
|
*/
|
|
95
97
|
export type GridSize = {
|
|
96
98
|
nx: number;
|
|
97
99
|
ny: number;
|
|
100
|
+
nz?: number;
|
|
98
101
|
h: number;
|
|
99
102
|
};
|
|
100
103
|
export type Grid = GridSize & {
|
|
104
|
+
dim: 2 | 3;
|
|
105
|
+
cells: number;
|
|
101
106
|
nodes: number;
|
|
102
107
|
dofs: number;
|
|
108
|
+
cellDofs: number;
|
|
103
109
|
edof: Int32Array;
|
|
104
|
-
node: (i: number, j: number) => number;
|
|
110
|
+
node: (i: number, j: number, k?: number) => number;
|
|
105
111
|
};
|
|
106
112
|
/**
|
|
107
113
|
* Young's modulus (MPa) and Poisson's ratio
|
package/fea.mjs
CHANGED
|
@@ -1,96 +1,155 @@
|
|
|
1
|
-
// Finite elements
|
|
2
|
-
// square cells
|
|
3
|
-
// Node alike. Units are millimetres and newtons, so stiffness (Young's modulus) is in MPa (N/mm²) and
|
|
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.
|
|
4
5
|
//
|
|
5
|
-
// The grid: nx × ny
|
|
6
|
-
// (i h, j h). Nodes are the cells' corners,
|
|
7
|
-
// y
|
|
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.
|
|
8
10
|
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
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.
|
|
12
19
|
|
|
13
|
-
/** @typedef {{ nx: number, ny: number, h: number }} GridSize cells along x and
|
|
14
|
-
/** @typedef {GridSize & { nodes: number, dofs: number, edof: Int32Array, node: (i: number, j: number) => number }} Grid */
|
|
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 */
|
|
15
22
|
/** @typedef {{ E: number, nu: number }} Material Young's modulus (MPa) and Poisson's ratio */
|
|
16
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
|
+
|
|
17
27
|
/**
|
|
18
|
-
* A grid of square cells, with each cell's
|
|
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.
|
|
19
29
|
* @param {GridSize} size
|
|
20
30
|
* @returns {Grid}
|
|
21
31
|
*/
|
|
22
|
-
export function grid({ nx, ny, h = 1 }) {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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
|
+
});
|
|
30
49
|
}
|
|
31
|
-
|
|
32
|
-
return { nx, ny, h, nodes, dofs: 2 * nodes, edof, node };
|
|
50
|
+
return { nx, ny, ...(dim === 3 ? { nz } : {}), h, dim, cells, nodes, dofs: dim * nodes, cellDofs, edof, node };
|
|
33
51
|
}
|
|
34
52
|
|
|
35
|
-
// The strain-displacement matrix of a
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
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
|
+
});
|
|
42
71
|
return B;
|
|
43
72
|
}
|
|
44
|
-
//
|
|
45
|
-
|
|
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
|
+
}
|
|
46
81
|
|
|
47
82
|
/**
|
|
48
|
-
* A
|
|
49
|
-
*
|
|
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.
|
|
50
86
|
* @param {number} nu Poisson's ratio
|
|
87
|
+
* @param {2 | 3} [dim]
|
|
51
88
|
* @returns {Float64Array}
|
|
52
89
|
*/
|
|
53
|
-
export function cellStiffness(nu) {
|
|
54
|
-
const D = elasticity(nu),
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
}
|
|
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; }
|
|
62
98
|
}
|
|
63
99
|
return K;
|
|
64
100
|
}
|
|
65
101
|
|
|
66
102
|
/**
|
|
67
|
-
* The plain JavaScript backend: the operations
|
|
68
|
-
* TensorFlow.js) provides the same and is tested against this one.
|
|
69
|
-
*
|
|
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 }}
|
|
70
108
|
*/
|
|
71
109
|
export const jsBackend = {
|
|
72
110
|
name: 'js',
|
|
73
111
|
precision: 64,
|
|
74
|
-
operator(g, ke) {
|
|
75
|
-
const { edof
|
|
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;
|
|
76
119
|
return {
|
|
77
|
-
// y = K x, K the stiffness of every cell scaled by scale[cell] (its modulus times thickness)
|
|
78
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
|
+
}
|
|
79
133
|
y.fill(0);
|
|
80
134
|
for (let e = 0; e < cells; e++) {
|
|
81
|
-
const s = scale[e], o = e *
|
|
135
|
+
const s = scale ? scale[e] : 1, o = e * m;
|
|
82
136
|
if (s === 0) continue;
|
|
83
|
-
|
|
84
|
-
for (let a = 0; a <
|
|
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++) {
|
|
85
140
|
let f = 0;
|
|
86
|
-
|
|
141
|
+
const r = base + a * m;
|
|
142
|
+
for (let b = 0; b < m; b++) f += K[r + b] * u[b];
|
|
87
143
|
y[edof[o + a]] += s * f;
|
|
88
144
|
}
|
|
89
145
|
}
|
|
90
146
|
},
|
|
91
147
|
diagonal(scale, d) {
|
|
92
148
|
d.fill(0);
|
|
93
|
-
for (let e = 0; e < cells; e++)
|
|
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
|
+
}
|
|
94
153
|
},
|
|
95
154
|
};
|
|
96
155
|
},
|
|
@@ -98,47 +157,92 @@ export const jsBackend = {
|
|
|
98
157
|
axpy(a, x, y) { for (let i = 0; i < y.length; i++) y[i] += a * x[i]; },
|
|
99
158
|
};
|
|
100
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
|
+
|
|
101
203
|
/**
|
|
102
204
|
* Solve K u = f for each load. K is every cell's stiffness (cellStiffness) times scale[cell]; fixed dofs don't move.
|
|
103
205
|
* @param {Grid} g
|
|
104
|
-
* @param {{ scale: Float64Array, ke: Float64Array, fixed: Uint8Array, loads: Float64Array[], method?: 'direct' | 'cg', backend?: typeof jsBackend, tol?: number, maxIter?: number, start?: Float64Array[] }} o
|
|
105
|
-
* start: a first guess for
|
|
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)
|
|
106
208
|
* @returns {{ u: Float64Array[], iterations: number }}
|
|
107
209
|
*/
|
|
108
210
|
export function solve(g, { scale, ke, fixed, loads, method = 'direct', backend = jsBackend, tol = 1e-9, maxIter = 20000, start }) {
|
|
109
|
-
if (scale.length !== g.
|
|
211
|
+
if (scale.length !== g.cells) throw new Error(`scale has ${scale.length} values for ${g.cells} cells`);
|
|
110
212
|
if (!fixed.some((f) => f)) throw new Error('nothing is held: fix at least one support, or the part just moves');
|
|
111
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; });
|
|
112
214
|
if (method === 'direct') {
|
|
113
|
-
const L = factor(g, scale, ke, fixed);
|
|
215
|
+
const L = factor(g, { scale, ke }, fixed);
|
|
114
216
|
return { u: f.map((b) => L.solve(b)), iterations: 0 };
|
|
115
217
|
}
|
|
116
|
-
|
|
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 });
|
|
117
221
|
}
|
|
118
222
|
|
|
119
|
-
// The banded Cholesky factor of K
|
|
120
|
-
function factor(g, scale, ke, fixed) {
|
|
121
|
-
const { edof, dofs } = g,
|
|
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;
|
|
122
226
|
let b = 0;
|
|
123
227
|
for (let e = 0; e < cells; e++) {
|
|
124
228
|
let lo = Infinity, hi = -Infinity;
|
|
125
|
-
for (let a = 0; a <
|
|
229
|
+
for (let a = 0; a < m; a++) { lo = Math.min(lo, edof[e * m + a]); hi = Math.max(hi, edof[e * m + a]); }
|
|
126
230
|
b = Math.max(b, hi - lo);
|
|
127
231
|
}
|
|
128
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
|
|
129
233
|
for (let e = 0; e < cells; e++) {
|
|
130
|
-
const s = scale[e];
|
|
131
|
-
for (let p = 0; p <
|
|
132
|
-
const i = edof[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];
|
|
133
237
|
if (fixed[i]) continue;
|
|
134
|
-
for (let q = 0; q <
|
|
135
|
-
const j = edof[e *
|
|
238
|
+
for (let q = 0; q < m; q++) {
|
|
239
|
+
const j = edof[e * m + q];
|
|
136
240
|
if (j > i || fixed[j]) continue;
|
|
137
|
-
L[i * w + b - i + j] += s *
|
|
241
|
+
L[i * w + b - i + j] += s * K[base + p * m + q];
|
|
138
242
|
}
|
|
139
243
|
}
|
|
140
244
|
}
|
|
141
|
-
for (let i = 0; i < dofs; i++) if (fixed[i]) L[i * w + b] = 1;
|
|
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
|
|
142
246
|
for (let i = 0; i < dofs; i++) {
|
|
143
247
|
const from = Math.max(0, i - b), ri = i * w + b - i; // L[i][k] is at ri + k
|
|
144
248
|
for (let j = from; j <= i; j++) {
|
|
@@ -171,11 +275,17 @@ function factor(g, scale, ke, fixed) {
|
|
|
171
275
|
};
|
|
172
276
|
}
|
|
173
277
|
|
|
174
|
-
//
|
|
175
|
-
function
|
|
176
|
-
const
|
|
278
|
+
// The diagonal preconditioner: each residual over its diagonal
|
|
279
|
+
function jacobi(g, { scale, fixed, op }) {
|
|
280
|
+
const d = new Float64Array(g.dofs);
|
|
177
281
|
op.diagonal(scale, d);
|
|
178
|
-
for (let i = 0; i <
|
|
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;
|
|
179
289
|
const apply = (x, y) => { op.multiply(scale, x, y); for (let i = 0; i < n; i++) if (fixed[i]) y[i] = x[i]; };
|
|
180
290
|
let total = 0;
|
|
181
291
|
const u = loads.map((f, c) => {
|
|
@@ -185,13 +295,13 @@ function conjugateGradients(g, { scale, ke, fixed, loads, backend, tol, maxIter,
|
|
|
185
295
|
apply(x, q);
|
|
186
296
|
for (let i = 0; i < n; i++) r[i] = f[i] - q[i];
|
|
187
297
|
const limit = tol * Math.sqrt(backend.dot(f, f));
|
|
188
|
-
|
|
298
|
+
precondition(r, z); p.set(z);
|
|
189
299
|
let rz = backend.dot(r, z), it = 0;
|
|
190
300
|
while (Math.sqrt(backend.dot(r, r)) > limit && it < maxIter) {
|
|
191
301
|
apply(p, q);
|
|
192
302
|
const a = rz / backend.dot(p, q);
|
|
193
303
|
backend.axpy(a, p, x); backend.axpy(-a, q, r);
|
|
194
|
-
|
|
304
|
+
precondition(r, z);
|
|
195
305
|
const next = backend.dot(r, z);
|
|
196
306
|
for (let i = 0; i < n; i++) p[i] = z[i] + (next / rz) * p[i];
|
|
197
307
|
rz = next; it++;
|
|
@@ -203,47 +313,202 @@ function conjugateGradients(g, { scale, ke, fixed, loads, backend, tol, maxIter,
|
|
|
203
313
|
return { u, iterations: total };
|
|
204
314
|
}
|
|
205
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
|
+
|
|
206
467
|
/**
|
|
207
468
|
* Each cell's von Mises stress (MPa) at its centre, from a solution u.
|
|
208
469
|
* @param {Grid} g @param {Float64Array} u @param {Float64Array} modulus each cell's Young's modulus (MPa) @param {number} nu
|
|
209
470
|
* @returns {Float64Array}
|
|
210
471
|
*/
|
|
211
472
|
export function stress(g, u, modulus, nu) {
|
|
212
|
-
const B = strains(
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
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));
|
|
218
481
|
}
|
|
219
482
|
return out;
|
|
220
483
|
}
|
|
221
484
|
|
|
222
485
|
/**
|
|
223
|
-
* Analyse a
|
|
224
|
-
* E × 1e-9 so empty cells don't leave the matrix singular),
|
|
225
|
-
*
|
|
226
|
-
* @
|
|
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[] }[] }}
|
|
227
491
|
* compliance: f · u per load (N·mm): the work the load does; lower is stiffer. deflection: the largest movement
|
|
228
492
|
* of any node in solid material, and where.
|
|
229
493
|
*/
|
|
230
|
-
export function analyse({ grid: g, density, material, thickness, fixed, loads, penal = 1, method = 'direct', backend }) {
|
|
231
|
-
const { E, nu } = material, Emin = E * 1e-9, ke = cellStiffness(nu);
|
|
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);
|
|
232
496
|
const modulus = Float64Array.from(density, (x) => Emin + Math.pow(x, penal) * (E - Emin));
|
|
233
|
-
const scale = modulus.map((
|
|
497
|
+
const scale = modulus.map((mod) => mod * (g.dim === 3 ? g.h : thickness));
|
|
234
498
|
const { u } = solve(g, { scale, ke, fixed, loads, method, backend });
|
|
235
|
-
const solidNode = new Uint8Array(g.nodes);
|
|
236
|
-
for (let e = 0; e < density.length; e++) if (density[e] >= 0.5) for (let k = 0; k <
|
|
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;
|
|
237
501
|
const position = positions(g);
|
|
238
502
|
return {
|
|
239
503
|
u,
|
|
240
504
|
compliance: u.map((x, c) => jsBackend.dot(loads[c], x)),
|
|
241
505
|
stress: u.map((x) => stress(g, x, modulus, nu)),
|
|
242
506
|
deflection: u.map((x) => {
|
|
243
|
-
let most = 0, at = [0
|
|
507
|
+
let most = 0, at = position[0];
|
|
244
508
|
for (let n = 0; n < g.nodes; n++) if (solidNode[n]) {
|
|
245
|
-
|
|
246
|
-
|
|
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]; }
|
|
247
512
|
}
|
|
248
513
|
return { most, at };
|
|
249
514
|
}),
|
|
@@ -251,12 +516,14 @@ export function analyse({ grid: g, density, material, thickness, fixed, loads, p
|
|
|
251
516
|
}
|
|
252
517
|
|
|
253
518
|
/**
|
|
254
|
-
* Each node's position in mm, [x, y], by node number.
|
|
519
|
+
* Each node's position in mm, [x, y] (or [x, y, z]), by node number.
|
|
255
520
|
* @param {Grid} g
|
|
256
|
-
* @returns {[
|
|
521
|
+
* @returns {number[][]}
|
|
257
522
|
*/
|
|
258
523
|
export function positions(g) {
|
|
259
|
-
const out = new Array(g.nodes);
|
|
260
|
-
for (let
|
|
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
|
+
}
|
|
261
528
|
return out;
|
|
262
529
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulecad/fea",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "How far a
|
|
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
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
7
7
|
"types": "./fea.d.mts",
|