@rulecad/fea 0.1.0 → 0.2.1

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.
Files changed (4) hide show
  1. package/README.md +20 -6
  2. package/fea.d.mts +51 -30
  3. package/fea.mjs +400 -100
  4. package/package.json +2 -2
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @rulecad/fea
2
2
 
3
- How far a flat part bends under load. Finite elements for a plate loaded in its own plane (plane stress) on a grid
4
- of square cells, each with its own stiffness. Plain JavaScript in typed arrays, no dependencies: it runs in browsers
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,33 @@ 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
- - **Cells:** 4-node squares (bilinear, integrated at 2 × 2 Gauss points). Each cell's density, 0 to 1, scales its
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:** `direct`, a banded Cholesky factorisation (exact; quick for 2D grids up to about 100,000 cells), or
25
- `cg`, conjugate gradients that never assemble the matrix (for bigger grids, and what faster backends speed up).
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
+ - **Solving again:** `solve(...)` returns `again(loads)`, which solves more right-hand sides on the same matrix,
33
+ reusing its factorisation or preconditioner: an adjoint, for a gradient.
34
+ - **Stress at a point:** `centreStress(h, nu, dim)` is the matrix from a cell's movements to the stress at its centre
35
+ (for Young's modulus 1), and `vonMises(s, dim, grad)` gives von Mises stress and, optionally, its gradient. Stress
36
+ limits in @rulecad/topopt use both.
26
37
  - **Backends:** the few operations `cg` repeats (the stiffness product, its diagonal, dot products) sit behind a small
27
38
  interface. `jsBackend`, plain JavaScript in 64-bit floats, is the reference; a WebGPU or TensorFlow.js backend
28
39
  implements the same and passes `backend-suite.mjs` in this repository.
29
40
 
30
- Tested against beam theory: a cantilever's tip moves within 1% of `F L³ / 3 E I`.
41
+ Tested against beam theory: a cantilever's tip moves within 1% of `F L³ / 3 E I` in 2D, and within 2% in 3D.
42
+ Multigrid is tested against the direct solver with stiffnesses a millionfold apart.
31
43
 
32
44
  ## Sources
33
45
 
46
+ - Amir, Aage, Lazarov (2014). On multigrid-CG for efficient topology optimization. *Structural and Multidisciplinary
47
+ Optimization* 49, 815–829.
34
48
  - Andreassen, Clausen, Schevenels, Lazarov, Sigmund (2011). Efficient topology optimization in MATLAB using 88 lines
35
49
  of code. *Structural and Multidisciplinary Optimization* 43, 1–16.
36
50
  - Cook, Malkus, Plesha, Witt (2002). *Concepts and Applications of Finite Element Analysis*, 4th ed. Wiley.
package/fea.d.mts CHANGED
@@ -1,32 +1,32 @@
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 eight unknowns (its corners counter-clockwise from lower left, x then y).
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 square cell's stiffness matrix (8 × 8, row by row) for Young's modulus 1 and thickness 1: the same for any cell
12
- * size. Integrated with 2 × 2 Gauss points, as for any bilinear element.
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 cg (the last solution, when solving again after a small change)
22
- * @returns {{ u: Float64Array[], iterations: number }}
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, again: (loads: Float64Array[]) => Float64Array[] }} again: more
22
+ * loads on the same matrix (an adjoint), reusing its factor or preconditioner
23
23
  */
24
24
  export function solve(g: Grid, { scale, ke, fixed, loads, method, backend, tol, maxIter, start }: {
25
25
  scale: Float64Array;
26
26
  ke: Float64Array;
27
27
  fixed: Uint8Array;
28
28
  loads: Float64Array[];
29
- method?: "direct" | "cg";
29
+ method?: "direct" | "cg" | "mg";
30
30
  backend?: typeof jsBackend;
31
31
  tol?: number;
32
32
  maxIter?: number;
@@ -34,7 +34,21 @@ export function solve(g: Grid, { scale, ke, fixed, loads, method, backend, tol,
34
34
  }): {
35
35
  u: Float64Array[];
36
36
  iterations: number;
37
+ again: (loads: Float64Array[]) => Float64Array[];
37
38
  };
39
+ /**
40
+ * Stress at a cell's centre from its corners' movements, for Young's modulus 1: a matrix (rows × cell dofs, row by row;
41
+ * rows: σx, σy, τxy in 2D; σx, σy, σz, τxy, τyz, τzx in 3D). Times a cell's movements and its modulus, it's the stress.
42
+ * @param {number} h cell size (mm) @param {number} nu @param {2 | 3} dim
43
+ * @returns {Float64Array}
44
+ */
45
+ export function centreStress(h: number, nu: number, dim: 2 | 3): Float64Array;
46
+ /**
47
+ * Von Mises stress from a stress (as centreStress's rows); with grad, also its gradient with respect to the stress.
48
+ * @param {ArrayLike<number>} s @param {2 | 3} dim @param {Float64Array} [grad]
49
+ * @returns {number}
50
+ */
51
+ export function vonMises(s: ArrayLike<number>, dim: 2 | 3, grad?: Float64Array): number;
38
52
  /**
39
53
  * Each cell's von Mises stress (MPa) at its centre, from a solution u.
40
54
  * @param {Grid} g @param {Float64Array} u @param {Float64Array} modulus each cell's Young's modulus (MPa) @param {number} nu
@@ -42,10 +56,11 @@ export function solve(g: Grid, { scale, ke, fixed, loads, method, backend, tol,
42
56
  */
43
57
  export function stress(g: Grid, u: Float64Array, modulus: Float64Array, nu: number): Float64Array;
44
58
  /**
45
- * Analyse a plate: each cell's density (0 empty to 1 solid; Young's modulus scales with density^penal, never below
46
- * E × 1e-9 so empty cells don't leave the matrix singular), its thickness, supports and loads.
47
- * @param {{ grid: Grid, density: Float64Array, material: Material, thickness: number, fixed: Uint8Array, loads: Float64Array[], penal?: number, method?: 'direct' | 'cg', backend?: typeof jsBackend }} o
48
- * @returns {{ u: Float64Array[], compliance: number[], stress: Float64Array[], deflection: { most: number, at: [number, number] }[] }}
59
+ * Analyse a part: each cell's density (0 empty to 1 solid; Young's modulus scales with density^penal, never below
60
+ * 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
61
+ * thickness; in 3D thickness is not used.
62
+ * @param {{ grid: Grid, density: Float64Array, material: Material, thickness?: number, fixed: Uint8Array, loads: Float64Array[], penal?: number, method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend }} o
63
+ * @returns {{ u: Float64Array[], compliance: number[], stress: Float64Array[], deflection: { most: number, at: number[] }[] }}
49
64
  * compliance: f · u per load (N·mm): the work the load does; lower is stiffer. deflection: the largest movement
50
65
  * of any node in solid material, and where.
51
66
  */
@@ -53,11 +68,11 @@ export function analyse({ grid: g, density, material, thickness, fixed, loads, p
53
68
  grid: Grid;
54
69
  density: Float64Array;
55
70
  material: Material;
56
- thickness: number;
71
+ thickness?: number;
57
72
  fixed: Uint8Array;
58
73
  loads: Float64Array[];
59
74
  penal?: number;
60
- method?: "direct" | "cg";
75
+ method?: "direct" | "cg" | "mg";
61
76
  backend?: typeof jsBackend;
62
77
  }): {
63
78
  u: Float64Array[];
@@ -65,43 +80,49 @@ export function analyse({ grid: g, density, material, thickness, fixed, loads, p
65
80
  stress: Float64Array[];
66
81
  deflection: {
67
82
  most: number;
68
- at: [number, number];
83
+ at: number[];
69
84
  }[];
70
85
  };
71
86
  /**
72
- * Each node's position in mm, [x, y], by node number.
87
+ * Each node's position in mm, [x, y] (or [x, y, z]), by node number.
73
88
  * @param {Grid} g
74
- * @returns {[number, number][]}
89
+ * @returns {number[][]}
75
90
  */
76
- export function positions(g: Grid): [number, number][];
91
+ export function positions(g: Grid): number[][];
77
92
  /**
78
- * The plain JavaScript backend: the operations conjugate gradients repeats, on Float64Arrays. Another backend (WebGPU,
79
- * TensorFlow.js) provides the same and is tested against this one.
80
- * @type {{ name: string, precision: number, operator: (g: Grid, ke: Float64Array) => { multiply: (scale: Float64Array, x: Float64Array, y: Float64Array) => void, diagonal: (scale: Float64Array, d: Float64Array) => void }, dot: (a: Float64Array, b: Float64Array) => number, axpy: (a: number, x: Float64Array, y: Float64Array) => void }}
93
+ * The plain JavaScript backend: the operations the iterative solvers repeat, on Float64Arrays. Another backend
94
+ * (WebGPU, TensorFlow.js) provides the same and is tested against this one (backend-suite.mjs).
95
+ * operator(g, ke): every cell's stiffness is ke (a cell matrix, shared) times scale[cell]; or with cellMatrices, each
96
+ * cell has its own matrix (cells × m × m), as multigrid's coarser grids do.
97
+ * @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
98
  */
82
99
  export const jsBackend: {
83
100
  name: string;
84
101
  precision: number;
85
- operator: (g: Grid, ke: Float64Array) => {
86
- multiply: (scale: Float64Array, x: Float64Array, y: Float64Array) => void;
87
- diagonal: (scale: Float64Array, d: Float64Array) => void;
102
+ operator: (g: Grid, ke: Float64Array | null, cellMatrices?: Float64Array) => {
103
+ multiply: (scale: Float64Array | null, x: Float64Array, y: Float64Array) => void;
104
+ diagonal: (scale: Float64Array | null, d: Float64Array) => void;
88
105
  };
89
106
  dot: (a: Float64Array, b: Float64Array) => number;
90
107
  axpy: (a: number, x: Float64Array, y: Float64Array) => void;
91
108
  };
92
109
  /**
93
- * cells along x and y, and their side in mm
110
+ * cells along x, y (and z for 3D), and their side in mm
94
111
  */
95
112
  export type GridSize = {
96
113
  nx: number;
97
114
  ny: number;
115
+ nz?: number;
98
116
  h: number;
99
117
  };
100
118
  export type Grid = GridSize & {
119
+ dim: 2 | 3;
120
+ cells: number;
101
121
  nodes: number;
102
122
  dofs: number;
123
+ cellDofs: number;
103
124
  edof: Int32Array;
104
- node: (i: number, j: number) => number;
125
+ node: (i: number, j: number, k?: number) => number;
105
126
  };
106
127
  /**
107
128
  * Young's modulus (MPa) and Poisson's ratio
package/fea.mjs CHANGED
@@ -1,96 +1,155 @@
1
- // Finite elements for flat parts: how far a plate bends under load in its own plane (plane stress), on a grid of
2
- // square cells, each with its own stiffness. Plain numbers in typed arrays, no dependencies: it runs in browsers and
3
- // Node alike. Units are millimetres and newtons, so stiffness (Young's modulus) is in MPa (N/mm²) and displacement in mm.
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 square cells of side h, cell (i, j) with i along x and j along y, its lower-left corner at
6
- // (i h, j h). Nodes are the cells' corners, two unknowns each (x and y displacement): dof 2n is node n's x, 2n + 1 its
7
- // y. Nodes are numbered along the grid's shorter side, which keeps the stiffness matrix's band narrow.
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
- // Two ways to solve: "direct" (banded Cholesky factorisation: exact, and quick for 2D grids up to about 100,000
10
- // cells) and "cg" (conjugate gradients, never assembling the matrix: for big grids, and what faster backends speed up).
11
- // The work cg repeats sits behind a backend, so a GPU can do it; plain JavaScript in 64-bit floats is the reference.
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 y, and their side in mm */
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 eight unknowns (its corners counter-clockwise from lower left, x then y).
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
- if (!(nx >= 1 && ny >= 1 && Number.isInteger(nx) && Number.isInteger(ny))) throw new Error(`a grid needs whole numbers of cells (got ${nx} × ${ny})`);
24
- const alongY = ny <= nx; // number nodes along the shorter side
25
- const node = alongY ? (i, j) => i * (ny + 1) + j : (i, j) => j * (nx + 1) + i;
26
- const edof = new Int32Array(nx * ny * 8);
27
- for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) {
28
- const e = j * nx + i, corners = [node(i, j), node(i + 1, j), node(i + 1, j + 1), node(i, j + 1)];
29
- for (let k = 0; k < 4; k++) { edof[e * 8 + 2 * k] = 2 * corners[k]; edof[e * 8 + 2 * k + 1] = 2 * corners[k] + 1; }
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
- const nodes = (nx + 1) * (ny + 1);
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 square cell of side h at natural coordinates (s, t), 3 × 8, row by row
36
- function strains(s, t, h) {
37
- const corner = [[-1, -1], [1, -1], [1, 1], [-1, 1]], B = new Float64Array(24);
38
- for (let k = 0; k < 4; k++) {
39
- const [a, b] = corner[k], dx = (a * (1 + b * t)) / 4 * (2 / h), dy = (b * (1 + a * s)) / 4 * (2 / h);
40
- B[2 * k] = dx; B[8 + 2 * k + 1] = dy; B[16 + 2 * k] = dy; B[16 + 2 * k + 1] = dx;
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
- // Plane stress: stress from strain for Young's modulus 1
45
- const elasticity = (nu) => { const f = 1 / (1 - nu * nu); return [f, f * nu, 0, f * nu, f, 0, 0, 0, f * (1 - nu) / 2]; };
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 square cell's stiffness matrix (8 × 8, row by row) for Young's modulus 1 and thickness 1: the same for any cell
49
- * size. Integrated with 2 × 2 Gauss points, as for any bilinear element.
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), K = new Float64Array(64), g = 1 / Math.sqrt(3), area = 1 / 4; // h = 1: the Jacobian is 1/4
55
- for (const s of [-g, g]) for (const t of [-g, g]) {
56
- const B = strains(s, t, 1);
57
- for (let a = 0; a < 8; a++) for (let b = 0; b < 8; b++) {
58
- let sum = 0;
59
- for (let p = 0; p < 3; p++) for (let q = 0; q < 3; q++) sum += B[p * 8 + a] * D[p * 3 + q] * B[q * 8 + b];
60
- K[a * 8 + b] += sum * area;
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 conjugate gradients repeats, on Float64Arrays. Another backend (WebGPU,
68
- * TensorFlow.js) provides the same and is tested against this one.
69
- * @type {{ name: string, precision: number, operator: (g: Grid, ke: Float64Array) => { multiply: (scale: Float64Array, x: Float64Array, y: Float64Array) => void, diagonal: (scale: Float64Array, d: Float64Array) => void }, dot: (a: Float64Array, b: Float64Array) => number, axpy: (a: number, x: Float64Array, y: Float64Array) => void }}
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 } = g, cells = g.nx * g.ny, u = new Float64Array(8);
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 * 8;
135
+ const s = scale ? scale[e] : 1, o = e * m;
82
136
  if (s === 0) continue;
83
- for (let a = 0; a < 8; a++) u[a] = x[edof[o + a]];
84
- for (let a = 0; a < 8; 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
- for (let b = 0; b < 8; b++) f += ke[a * 8 + b] * u[b];
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++) for (let a = 0; a < 8; a++) d[edof[e * 8 + a]] += scale[e] * ke[a * 9];
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,94 @@ 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 cg (the last solution, when solving again after a small change)
106
- * @returns {{ u: Float64Array[], iterations: number }}
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, again: (loads: Float64Array[]) => Float64Array[] }} again: more
209
+ * loads on the same matrix (an adjoint), reusing its factor or preconditioner
107
210
  */
108
211
  export function solve(g, { scale, ke, fixed, loads, method = 'direct', backend = jsBackend, tol = 1e-9, maxIter = 20000, start }) {
109
- if (scale.length !== g.nx * g.ny) throw new Error(`scale has ${scale.length} values for ${g.nx * g.ny} cells`);
212
+ if (scale.length !== g.cells) throw new Error(`scale has ${scale.length} values for ${g.cells} cells`);
110
213
  if (!fixed.some((f) => f)) throw new Error('nothing is held: fix at least one support, or the part just moves');
111
- 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
+ const held = (ls) => ls.map((l) => { const c = Float64Array.from(l); for (let i = 0; i < c.length; i++) if (fixed[i]) c[i] = 0; return c; });
112
215
  if (method === 'direct') {
113
- const L = factor(g, scale, ke, fixed);
114
- return { u: f.map((b) => L.solve(b)), iterations: 0 };
216
+ const L = factor(g, { scale, ke }, fixed), again = (ls) => held(ls).map((b) => L.solve(b));
217
+ return { u: again(loads), iterations: 0, again };
115
218
  }
116
- return conjugateGradients(g, { scale, ke, fixed, loads: f, backend, tol, maxIter, start });
219
+ const op = backend.operator(g, ke); // one for the solver and its preconditioner: the matrix is assembled once
220
+ const precondition = method === 'mg' ? multigrid(g, { scale, ke, fixed, backend, op }) : jacobi(g, { scale, fixed, op });
221
+ const again = (ls) => conjugateGradients(g, { scale, fixed, loads: held(ls), backend, tol, maxIter, precondition, op }).u;
222
+ return { ...conjugateGradients(g, { scale, fixed, loads: held(loads), backend, tol, maxIter, start, precondition, op }), again };
117
223
  }
118
224
 
119
- // The banded Cholesky factor of K: K's lower band (half-bandwidth b) assembled, then factored in place
120
- function factor(g, scale, ke, fixed) {
121
- const { edof, dofs } = g, cells = g.nx * g.ny;
225
+ // The banded Cholesky factor of K (cells' matrices: ke × scale, or each its own), fixed dofs as identity rows
226
+ function factor(g, { scale, ke, cellMatrices }, fixed) {
227
+ const { edof, dofs, cells, cellDofs: m } = g, mm = m * m;
122
228
  let b = 0;
123
229
  for (let e = 0; e < cells; e++) {
124
230
  let lo = Infinity, hi = -Infinity;
125
- for (let a = 0; a < 8; a++) { lo = Math.min(lo, edof[e * 8 + a]); hi = Math.max(hi, edof[e * 8 + a]); }
231
+ for (let a = 0; a < m; a++) { lo = Math.min(lo, edof[e * m + a]); hi = Math.max(hi, edof[e * m + a]); }
126
232
  b = Math.max(b, hi - lo);
127
233
  }
128
234
  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
235
  for (let e = 0; e < cells; e++) {
130
- const s = scale[e];
131
- for (let p = 0; p < 8; p++) {
132
- const i = edof[e * 8 + p];
236
+ const s = scale ? scale[e] : 1, K = cellMatrices || ke, base = cellMatrices ? e * mm : 0;
237
+ for (let p = 0; p < m; p++) {
238
+ const i = edof[e * m + p];
133
239
  if (fixed[i]) continue;
134
- for (let q = 0; q < 8; q++) {
135
- const j = edof[e * 8 + q];
240
+ for (let q = 0; q < m; q++) {
241
+ const j = edof[e * m + q];
136
242
  if (j > i || fixed[j]) continue;
137
- L[i * w + b - i + j] += s * ke[p * 8 + q];
243
+ L[i * w + b - i + j] += s * K[base + p * m + q];
138
244
  }
139
245
  }
140
246
  }
141
- for (let i = 0; i < dofs; i++) if (fixed[i]) L[i * w + b] = 1;
247
+ 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
248
  for (let i = 0; i < dofs; i++) {
143
249
  const from = Math.max(0, i - b), ri = i * w + b - i; // L[i][k] is at ri + k
144
250
  for (let j = from; j <= i; j++) {
@@ -171,11 +277,17 @@ function factor(g, scale, ke, fixed) {
171
277
  };
172
278
  }
173
279
 
174
- // Jacobi-preconditioned conjugate gradients, matrix-free: fixed dofs stay at 0 (their rows act as the identity)
175
- function conjugateGradients(g, { scale, ke, fixed, loads, backend, tol, maxIter, start }) {
176
- const op = backend.operator(g, ke), n = g.dofs, d = new Float64Array(n);
280
+ // The diagonal preconditioner: each residual over its diagonal
281
+ function jacobi(g, { scale, fixed, op }) {
282
+ const d = new Float64Array(g.dofs);
177
283
  op.diagonal(scale, d);
178
- for (let i = 0; i < n; i++) d[i] = fixed[i] || !(d[i] > 0) ? 1 : 1 / d[i];
284
+ for (let i = 0; i < d.length; i++) d[i] = fixed[i] || !(d[i] > 0) ? 1 : 1 / d[i];
285
+ return (r, z) => { for (let i = 0; i < r.length; i++) z[i] = d[i] * r[i]; };
286
+ }
287
+
288
+ // Conjugate gradients, matrix-free: fixed dofs stay at 0 (their rows act as the identity)
289
+ function conjugateGradients(g, { scale, fixed, loads, backend, tol, maxIter, start, precondition, op }) {
290
+ const n = g.dofs;
179
291
  const apply = (x, y) => { op.multiply(scale, x, y); for (let i = 0; i < n; i++) if (fixed[i]) y[i] = x[i]; };
180
292
  let total = 0;
181
293
  const u = loads.map((f, c) => {
@@ -185,13 +297,13 @@ function conjugateGradients(g, { scale, ke, fixed, loads, backend, tol, maxIter,
185
297
  apply(x, q);
186
298
  for (let i = 0; i < n; i++) r[i] = f[i] - q[i];
187
299
  const limit = tol * Math.sqrt(backend.dot(f, f));
188
- for (let i = 0; i < n; i++) p[i] = z[i] = d[i] * r[i];
300
+ precondition(r, z); p.set(z);
189
301
  let rz = backend.dot(r, z), it = 0;
190
302
  while (Math.sqrt(backend.dot(r, r)) > limit && it < maxIter) {
191
303
  apply(p, q);
192
304
  const a = rz / backend.dot(p, q);
193
305
  backend.axpy(a, p, x); backend.axpy(-a, q, r);
194
- for (let i = 0; i < n; i++) z[i] = d[i] * r[i];
306
+ precondition(r, z);
195
307
  const next = backend.dot(r, z);
196
308
  for (let i = 0; i < n; i++) p[i] = z[i] + (next / rz) * p[i];
197
309
  rz = next; it++;
@@ -203,47 +315,233 @@ function conjugateGradients(g, { scale, ke, fixed, loads, backend, tol, maxIter,
203
315
  return { u, iterations: total };
204
316
  }
205
317
 
318
+ // ---------- multigrid ----------
319
+ // Coarser grids halve each side while every side is even and the grid has more than about 3,000 unknowns. A coarse
320
+ // cell's matrix is its 2^d children's, carried up by the trilinear (bilinear) interpolation from its corners to theirs
321
+ // (Pᵀ K P), with fixed dofs left out, so the coarse problem is the fine one seen at half the resolution. The cycle is a
322
+ // V: two damped Jacobi sweeps down, the coarsest grid solved exactly (banded Cholesky), two sweeps on the way up.
323
+ // It's symmetric, so conjugate gradients can use it as a preconditioner.
324
+ const SWEEPS = 2, DAMPING = 0.5, COARSEST = 3000;
325
+
326
+ // The coarser grids under a grid, and the maps between each pair, worked out once per grid (they don't change as the
327
+ // cells' stiffnesses do)
328
+ const hierarchies = new WeakMap();
329
+ function hierarchy(g) {
330
+ if (hierarchies.has(g)) return hierarchies.get(g);
331
+ const grids = [g];
332
+ for (;;) {
333
+ const fg = grids.at(-1), sides = fg.dim === 3 ? [fg.nx, fg.ny, fg.nz] : [fg.nx, fg.ny];
334
+ if (fg.dofs <= COARSEST || sides.some((s) => s % 2)) break;
335
+ grids.push(grid({ nx: fg.nx / 2, ny: fg.ny / 2, ...(fg.dim === 3 ? { nz: fg.nz / 2 } : {}), h: fg.h * 2 }));
336
+ }
337
+ const maps = grids.slice(1).map((cg, l) => transfer(grids[l], cg));
338
+ const out = { grids, maps };
339
+ hierarchies.set(g, out);
340
+ return out;
341
+ }
342
+
343
+ function multigrid(g, { scale, ke, fixed, backend, op }) {
344
+ const { grids, maps } = hierarchy(g);
345
+ const levels = [{ g, op, scale, fixed: Uint8Array.from(fixed), mats: null }];
346
+ for (let l = 1; l < grids.length; l++) {
347
+ const f = levels.at(-1), fg = f.g, cg = grids[l];
348
+ const mats = coarsen(fg, cg, f.mats || ke, f.mats ? null : f.scale, f.fixed);
349
+ const cfixed = new Uint8Array(cg.dofs), diag = new Float64Array(cg.dofs), m = cg.cellDofs;
350
+ 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)];
351
+ for (let i = 0; i < cg.dofs; i++) if (!(diag[i] > 0)) cfixed[i] = 1; // nothing below moves it: held
352
+ levels.push({ g: cg, op: backend.operator(cg, null, mats), scale: null, fixed: cfixed, mats });
353
+ }
354
+ for (const l of levels) { // each level's diagonal, for its Jacobi sweeps
355
+ l.inv = new Float64Array(l.g.dofs);
356
+ l.op.diagonal(l.scale, l.inv);
357
+ for (let i = 0; i < l.inv.length; i++) l.inv[i] = l.fixed[i] || !(l.inv[i] > 0) ? 0 : DAMPING / l.inv[i];
358
+ }
359
+ const last = levels.at(-1), coarse = factor(last.g, { scale: last.scale, ke, cellMatrices: last.mats }, last.fixed);
360
+ const apply = (l, x, y) => { l.op.multiply(l.scale, x, y); for (let i = 0; i < y.length; i++) if (l.fixed[i]) y[i] = 0; };
361
+
362
+ const cycle = (k, r) => {
363
+ const l = levels[k];
364
+ if (k === levels.length - 1) { const x = coarse.solve(r); for (let i = 0; i < x.length; i++) if (l.fixed[i]) x[i] = 0; return x; }
365
+ const n = l.g.dofs, x = new Float64Array(n), Ax = new Float64Array(n), res = new Float64Array(n);
366
+ const sweep = () => { apply(l, x, Ax); for (let i = 0; i < n; i++) x[i] += l.inv[i] * (r[i] - Ax[i]); };
367
+ for (let s = 0; s < SWEEPS; s++) sweep();
368
+ apply(l, x, Ax);
369
+ for (let i = 0; i < n; i++) res[i] = l.fixed[i] ? 0 : r[i] - Ax[i];
370
+ const e = maps[k].prolong(cycle(k + 1, maps[k].restrict(res)));
371
+ for (let i = 0; i < n; i++) x[i] += l.fixed[i] ? 0 : e[i];
372
+ for (let s = 0; s < SWEEPS; s++) sweep();
373
+ return x;
374
+ };
375
+ return (r, z) => {
376
+ const x = cycle(0, r);
377
+ for (let i = 0; i < z.length; i++) z[i] = fixed[i] ? r[i] : x[i];
378
+ };
379
+ }
380
+
381
+ // The interpolation weights from a coarse cell's corners to one child's corners: for child offset o (each 0 or 1),
382
+ // a (cellDofs × cellDofs) matrix P_o with child dof = Σ P_o[child][coarse] × coarse dof, kept as its nonzero entries
383
+ function childInterpolation(dim) {
384
+ const corners = CORNERS[dim], m = corners.length * dim, out = [];
385
+ for (const o of corners) {
386
+ const P = new Float64Array(m * m);
387
+ corners.forEach((c, q) => { // the child's corner q, at (o + c) / 2 in the coarse cell
388
+ const at = c.map((x, a) => (o[a] + x) / 2);
389
+ corners.forEach((C, Q) => {
390
+ const wgt = at.reduce((p, x, a) => p * (C[a] ? x : 1 - x), 1);
391
+ if (wgt) for (let d = 0; d < dim; d++) P[(q * dim + d) * m + Q * dim + d] = wgt;
392
+ });
393
+ });
394
+ // As its nonzero entries: rows, columns, weights
395
+ const rows = [], cols = [], wts = [];
396
+ 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]); }
397
+ out.push([Int32Array.from(rows), Int32Array.from(cols), Float64Array.from(wts)]);
398
+ }
399
+ return out;
400
+ }
401
+
402
+ // Each coarse cell's matrix: Σ over its children of P_oᵀ (child's matrix, fixed rows and columns left out) P_o, using
403
+ // only P_o's nonzero weights (about one in seven)
404
+ const interpolations = { 2: null, 3: null };
405
+ function coarsen(fg, cg, K, scale, fixed) {
406
+ const dim = fg.dim, m = fg.cellDofs, mm = m * m, corners = CORNERS[dim];
407
+ const P = interpolations[dim] || (interpolations[dim] = childInterpolation(dim));
408
+ const out = new Float64Array(cg.cells * mm), KP = new Float64Array(mm), held = new Uint8Array(m);
409
+ const shared = scale ? K : null; // fine level: one matrix scaled per cell; coarser: each cell its own
410
+ const offset = corners.map((o) => ((o[2] || 0) * fg.ny + o[1]) * fg.nx + o[0]); // a child's cell number from its first
411
+ for (let E = 0; E < cg.cells; E++) {
412
+ const I = E % cg.nx, J = Math.floor(E / cg.nx) % cg.ny, Kz = dim === 3 ? Math.floor(E / (cg.nx * cg.ny)) : 0;
413
+ const first = (2 * Kz * fg.ny + 2 * J) * fg.nx + 2 * I, o0 = E * mm;
414
+ for (let oi = 0; oi < corners.length; oi++) {
415
+ const e = first + offset[oi], s = scale ? scale[e] : 1, base = shared ? 0 : e * mm, src = shared || K;
416
+ for (let a = 0; a < m; a++) held[a] = fixed[fg.edof[e * m + a]];
417
+ const [rows, cols, wts] = P[oi];
418
+ KP.fill(0);
419
+ for (let t = 0; t < wts.length; t++) { // KP = child × P_o
420
+ const b = rows[t];
421
+ if (held[b]) continue;
422
+ const c = cols[t], w = s * wts[t];
423
+ for (let a = 0; a < m; a++) if (!held[a]) KP[a * m + c] += src[base + a * m + b] * w;
424
+ }
425
+ for (let t = 0; t < wts.length; t++) { // out += P_oᵀ × KP
426
+ const a = rows[t], r = cols[t], w = wts[t], ro = o0 + r * m, ka = a * m;
427
+ for (let c = 0; c < m; c++) out[ro + c] += w * KP[ka + c];
428
+ }
429
+ }
430
+ }
431
+ return out;
432
+ }
433
+
434
+ // Between a fine grid and the next coarser: prolong (coarse to fine: each fine node takes the interpolation of the
435
+ // coarse nodes round it, 1, 2, 4 or 8 of them) and restrict, its transpose. Each fine node's coarse nodes and weights
436
+ // are listed once, as flat arrays.
437
+ function transfer(fg, cg) {
438
+ const dim = fg.dim, nk = dim === 3 ? fg.nz : 0, start = new Int32Array(fg.nodes + 1), from = [], weight = [];
439
+ const order = new Int32Array(fg.nodes);
440
+ let n = 0;
441
+ for (let k = 0; k <= nk; k++) for (let j = 0; j <= fg.ny; j++) for (let i = 0; i <= fg.nx; i++) {
442
+ const node = dim === 3 ? fg.node(i, j, k) : fg.node(i, j);
443
+ let picks = [[i >> 1, j >> 1, k >> 1]];
444
+ [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))]); });
445
+ 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); }
446
+ order[n] = node; start[++n] = from.length;
447
+ }
448
+ const F = Int32Array.from(from), W = Float64Array.from(weight);
449
+ return {
450
+ prolong(xc) {
451
+ const xf = new Float64Array(fg.dofs);
452
+ for (let q = 0; q < fg.nodes; q++) {
453
+ const o = dim * order[q];
454
+ 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]; }
455
+ }
456
+ return xf;
457
+ },
458
+ restrict(rf) {
459
+ const rc = new Float64Array(cg.dofs);
460
+ for (let q = 0; q < fg.nodes; q++) {
461
+ const o = dim * order[q];
462
+ 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]; }
463
+ }
464
+ return rc;
465
+ },
466
+ };
467
+ }
468
+
469
+ /**
470
+ * Stress at a cell's centre from its corners' movements, for Young's modulus 1: a matrix (rows × cell dofs, row by row;
471
+ * rows: σx, σy, τxy in 2D; σx, σy, σz, τxy, τyz, τzx in 3D). Times a cell's movements and its modulus, it's the stress.
472
+ * @param {number} h cell size (mm) @param {number} nu @param {2 | 3} dim
473
+ * @returns {Float64Array}
474
+ */
475
+ export function centreStress(h, nu, dim) {
476
+ const m = CORNERS[dim].length * dim, rows = dim === 3 ? 6 : 3, B = strains(new Array(dim).fill(0), h, dim), D = elasticity(nu, dim), S = new Float64Array(rows * m);
477
+ for (let p = 0; p < rows; p++) for (let a = 0; a < m; a++) { let t = 0; for (let q = 0; q < rows; q++) t += D[p * rows + q] * B[q * m + a]; S[p * m + a] = t; }
478
+ return S;
479
+ }
480
+
481
+ /**
482
+ * Von Mises stress from a stress (as centreStress's rows); with grad, also its gradient with respect to the stress.
483
+ * @param {ArrayLike<number>} s @param {2 | 3} dim @param {Float64Array} [grad]
484
+ * @returns {number}
485
+ */
486
+ export function vonMises(s, dim, grad) {
487
+ const v = dim === 2 ? Math.sqrt(Math.max(0, s[0] * s[0] - s[0] * s[1] + s[1] * s[1] + 3 * s[2] * s[2]))
488
+ : Math.sqrt(Math.max(0, ((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)));
489
+ if (grad) {
490
+ const k = v > 0 ? 1 / (2 * v) : 0;
491
+ if (dim === 2) { grad[0] = k * (2 * s[0] - s[1]); grad[1] = k * (2 * s[1] - s[0]); grad[2] = k * 6 * s[2]; }
492
+ else {
493
+ grad[0] = k * (2 * s[0] - s[1] - s[2]); grad[1] = k * (2 * s[1] - s[0] - s[2]); grad[2] = k * (2 * s[2] - s[0] - s[1]);
494
+ grad[3] = k * 6 * s[3]; grad[4] = k * 6 * s[4]; grad[5] = k * 6 * s[5];
495
+ }
496
+ }
497
+ return v;
498
+ }
499
+
206
500
  /**
207
501
  * Each cell's von Mises stress (MPa) at its centre, from a solution u.
208
502
  * @param {Grid} g @param {Float64Array} u @param {Float64Array} modulus each cell's Young's modulus (MPa) @param {number} nu
209
503
  * @returns {Float64Array}
210
504
  */
211
505
  export function stress(g, u, modulus, nu) {
212
- const B = strains(0, 0, g.h), D = elasticity(nu), out = new Float64Array(g.nx * g.ny);
213
- for (let e = 0; e < out.length; e++) {
214
- const strain = [0, 0, 0];
215
- for (let p = 0; p < 3; p++) for (let a = 0; a < 8; a++) strain[p] += B[p * 8 + a] * u[g.edof[e * 8 + a]];
216
- const [sx, sy, txy] = [0, 1, 2].map((p) => modulus[e] * (D[p * 3] * strain[0] + D[p * 3 + 1] * strain[1] + D[p * 3 + 2] * strain[2]));
217
- out[e] = Math.sqrt(sx * sx - sx * sy + sy * sy + 3 * txy * txy);
506
+ 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);
507
+ const strain = new Float64Array(rows);
508
+ for (let e = 0; e < g.cells; e++) {
509
+ strain.fill(0);
510
+ 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]];
511
+ 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; });
512
+ out[e] = dim === 2 ? Math.sqrt(s[0] * s[0] - s[0] * s[1] + s[1] * s[1] + 3 * s[2] * s[2])
513
+ : 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
514
  }
219
515
  return out;
220
516
  }
221
517
 
222
518
  /**
223
- * Analyse a plate: each cell's density (0 empty to 1 solid; Young's modulus scales with density^penal, never below
224
- * E × 1e-9 so empty cells don't leave the matrix singular), its thickness, supports and loads.
225
- * @param {{ grid: Grid, density: Float64Array, material: Material, thickness: number, fixed: Uint8Array, loads: Float64Array[], penal?: number, method?: 'direct' | 'cg', backend?: typeof jsBackend }} o
226
- * @returns {{ u: Float64Array[], compliance: number[], stress: Float64Array[], deflection: { most: number, at: [number, number] }[] }}
519
+ * Analyse a part: each cell's density (0 empty to 1 solid; Young's modulus scales with density^penal, never below
520
+ * 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
521
+ * thickness; in 3D thickness is not used.
522
+ * @param {{ grid: Grid, density: Float64Array, material: Material, thickness?: number, fixed: Uint8Array, loads: Float64Array[], penal?: number, method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend }} o
523
+ * @returns {{ u: Float64Array[], compliance: number[], stress: Float64Array[], deflection: { most: number, at: number[] }[] }}
227
524
  * compliance: f · u per load (N·mm): the work the load does; lower is stiffer. deflection: the largest movement
228
525
  * of any node in solid material, and where.
229
526
  */
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);
527
+ export function analyse({ grid: g, density, material, thickness = 1, fixed, loads, penal = 1, method = g.dim === 3 ? 'mg' : 'direct', backend }) {
528
+ const { E, nu } = material, Emin = E * 1e-9, ke = cellStiffness(nu, g.dim);
232
529
  const modulus = Float64Array.from(density, (x) => Emin + Math.pow(x, penal) * (E - Emin));
233
- const scale = modulus.map((m) => m * thickness);
530
+ const scale = modulus.map((mod) => mod * (g.dim === 3 ? g.h : thickness));
234
531
  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 < 4; k++) solidNode[g.edof[e * 8 + 2 * k] / 2] = 1;
532
+ const solidNode = new Uint8Array(g.nodes), corners = CORNERS[g.dim].length;
533
+ 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
534
  const position = positions(g);
238
535
  return {
239
536
  u,
240
537
  compliance: u.map((x, c) => jsBackend.dot(loads[c], x)),
241
538
  stress: u.map((x) => stress(g, x, modulus, nu)),
242
539
  deflection: u.map((x) => {
243
- let most = 0, at = [0, 0];
540
+ let most = 0, at = position[0];
244
541
  for (let n = 0; n < g.nodes; n++) if (solidNode[n]) {
245
- const m = Math.hypot(x[2 * n], x[2 * n + 1]);
246
- if (m > most) { most = m; at = position[n]; }
542
+ let s = 0;
543
+ for (let d = 0; d < g.dim; d++) s += x[g.dim * n + d] ** 2;
544
+ if (Math.sqrt(s) > most) { most = Math.sqrt(s); at = position[n]; }
247
545
  }
248
546
  return { most, at };
249
547
  }),
@@ -251,12 +549,14 @@ export function analyse({ grid: g, density, material, thickness, fixed, loads, p
251
549
  }
252
550
 
253
551
  /**
254
- * Each node's position in mm, [x, y], by node number.
552
+ * Each node's position in mm, [x, y] (or [x, y, z]), by node number.
255
553
  * @param {Grid} g
256
- * @returns {[number, number][]}
554
+ * @returns {number[][]}
257
555
  */
258
556
  export function positions(g) {
259
- const out = new Array(g.nodes);
260
- for (let j = 0; j <= g.ny; j++) for (let i = 0; i <= g.nx; i++) out[g.node(i, j)] = [i * g.h, j * g.h];
557
+ const out = new Array(g.nodes), nk = g.dim === 3 ? g.nz : 0;
558
+ for (let k = 0; k <= nk; k++) for (let j = 0; j <= g.ny; j++) for (let i = 0; i <= g.nx; i++) {
559
+ 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];
560
+ }
261
561
  return out;
262
562
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@rulecad/fea",
3
- "version": "0.1.0",
4
- "description": "How far a flat part bends under load: finite elements on a grid of square cells, in plain JavaScript.",
3
+ "version": "0.2.1",
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",