@rulecad/fea 0.2.14 → 0.4.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/fea.mjs CHANGED
@@ -22,7 +22,24 @@
22
22
  /** @typedef {{ E: number, nu: number }} Material Young's modulus (MPa) and Poisson's ratio */
23
23
 
24
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]] };
25
+ const CORNERS = {
26
+ 2: [
27
+ [0, 0],
28
+ [1, 0],
29
+ [1, 1],
30
+ [0, 1],
31
+ ],
32
+ 3: [
33
+ [0, 0, 0],
34
+ [1, 0, 0],
35
+ [1, 1, 0],
36
+ [0, 1, 0],
37
+ [0, 0, 1],
38
+ [1, 0, 1],
39
+ [1, 1, 1],
40
+ [0, 1, 1],
41
+ ],
42
+ };
26
43
 
27
44
  /**
28
45
  * A grid of square (2D) or cube (3D) cells, with each cell's unknowns: its corners in order, x, y (and z) for each.
@@ -30,18 +47,29 @@ const CORNERS = { 2: [[0, 0], [1, 0], [1, 1], [0, 1]], 3: [[0, 0, 0], [1, 0, 0],
30
47
  * @returns {Grid}
31
48
  */
32
49
  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(' × ')})`);
50
+ const dim = nz ? 3 : 2,
51
+ n = dim === 3 ? [nx, ny, nz] : [nx, ny];
52
+ if (!n.every((c) => c >= 1 && Number.isInteger(c)))
53
+ throw new Error(`a grid needs whole numbers of cells (got ${n.join(' × ')})`);
35
54
  // 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);
55
+ const axes = n.map((c, a) => a).sort((a, b) => n[a] - n[b] || b - a),
56
+ stride = new Array(dim);
37
57
  let s = 1;
38
- for (const a of axes) { stride[a] = s; s *= n[a] + 1; }
58
+ for (const a of axes) {
59
+ stride[a] = s;
60
+ s *= n[a] + 1;
61
+ }
39
62
  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);
63
+ const node =
64
+ dim === 3 ? (i, j, k) => i * stride[0] + j * stride[1] + k * stride[2] : (i, j) => i * stride[0] + j * stride[1];
65
+ const corners = CORNERS[dim],
66
+ cellDofs = corners.length * dim,
67
+ cells = n.reduce((p, c) => p * c, 1);
42
68
  const edof = new Int32Array(cells * cellDofs);
43
69
  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;
70
+ const i = e % nx,
71
+ j = Math.floor(e / nx) % ny,
72
+ k = dim === 3 ? Math.floor(e / (nx * ny)) : 0;
45
73
  corners.forEach((c, q) => {
46
74
  const m = node(i + c[0], j + c[1], k + (c[2] || 0));
47
75
  for (let d = 0; d < dim; d++) edof[e * cellDofs + q * dim + d] = dim * m + d;
@@ -53,27 +81,47 @@ export function grid({ nx, ny, nz, h = 1 }) {
53
81
  // 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
82
  // (εx, εy, γxy), 6 × 24 in 3D (εx, εy, εz, γxy, γyz, γzx)
55
83
  function strains(p, h, dim) {
56
- const corners = CORNERS[dim], m = corners.length * dim, rows = dim === 3 ? 6 : 3, B = new Float64Array(rows * m);
84
+ const corners = CORNERS[dim],
85
+ m = corners.length * dim,
86
+ rows = dim === 3 ? 6 : 3,
87
+ B = new Float64Array(rows * m);
57
88
  corners.forEach((c, q) => {
58
89
  const sign = c.map((x) => 2 * x - 1);
59
90
  // 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));
91
+ const g = sign.map(
92
+ (sa, a) => ((sa * sign.reduce((f, sb, b) => (b === a ? f : f * (1 + sb * p[b])), 1)) / (1 << dim)) * (2 / h),
93
+ );
61
94
  const col = q * dim;
62
95
  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];
96
+ B[col] = g[0];
97
+ B[m + col + 1] = g[1];
98
+ B[2 * m + col] = g[1];
99
+ B[2 * m + col + 1] = g[0];
64
100
  } 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];
101
+ B[col] = g[0];
102
+ B[m + col + 1] = g[1];
103
+ B[2 * m + col + 2] = g[2];
104
+ B[3 * m + col] = g[1];
105
+ B[3 * m + col + 1] = g[0];
106
+ B[4 * m + col + 1] = g[2];
107
+ B[4 * m + col + 2] = g[1];
108
+ B[5 * m + col] = g[2];
109
+ B[5 * m + col + 2] = g[0];
69
110
  }
70
111
  });
71
112
  return B;
72
113
  }
73
114
  // Stress from strain for Young's modulus 1: plane stress in 2D, isotropic in 3D
74
115
  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);
116
+ if (dim === 2) {
117
+ const f = 1 / (1 - nu * nu);
118
+ return [f, f * nu, 0, f * nu, f, 0, 0, 0, (f * (1 - nu)) / 2];
119
+ }
120
+ const f = 1 / ((1 + nu) * (1 - 2 * nu)),
121
+ a = f * (1 - nu),
122
+ b = f * nu,
123
+ c = (f * (1 - 2 * nu)) / 2,
124
+ D = new Array(36).fill(0);
77
125
  for (let r = 0; r < 3; r++) for (let q = 0; q < 3; q++) D[r * 6 + q] = r === q ? a : b;
78
126
  for (let r = 3; r < 6; r++) D[r * 6 + r] = c;
79
127
  return D;
@@ -88,13 +136,31 @@ function elasticity(nu, dim) {
88
136
  * @returns {Float64Array}
89
137
  */
90
138
  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]));
139
+ const D = elasticity(nu, dim),
140
+ m = CORNERS[dim].length * dim,
141
+ rows = dim === 3 ? 6 : 3,
142
+ K = new Float64Array(m * m);
143
+ const g = 1 / Math.sqrt(3),
144
+ weight = 1 / (1 << dim); // side 1: the Jacobian is (1/2)^dim
145
+ const points =
146
+ dim === 3
147
+ ? [-g, g].flatMap((a) => [-g, g].flatMap((b) => [-g, g].map((c) => [a, b, c])))
148
+ : [-g, g].flatMap((a) => [-g, g].map((b) => [a, b]));
94
149
  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; }
150
+ const B = strains(p, 1, dim),
151
+ DB = new Float64Array(rows * m);
152
+ for (let r = 0; r < rows; r++)
153
+ for (let c = 0; c < m; c++) {
154
+ let s = 0;
155
+ for (let t = 0; t < rows; t++) s += D[r * rows + t] * B[t * m + c];
156
+ DB[r * m + c] = s;
157
+ }
158
+ for (let a = 0; a < m; a++)
159
+ for (let b = 0; b < m; b++) {
160
+ let s = 0;
161
+ for (let r = 0; r < rows; r++) s += B[r * m + a] * DB[r * m + b];
162
+ K[a * m + b] += s * weight;
163
+ }
98
164
  }
99
165
  return K;
100
166
  }
@@ -112,40 +178,74 @@ export const jsBackend = {
112
178
  name: 'js',
113
179
  precision: 64,
114
180
  operator(g, ke, cellMatrices) {
115
- const pat = pattern(g), { dim } = g, bb = dim * dim;
116
- let values = cellMatrices ? assemble(g, pat, cellMatrices, null, null) : null, assembledFor = cellMatrices ? undefined : {};
117
- const ready = (scale) => { if (!cellMatrices && assembledFor !== scale) { values = assemble(g, pat, null, ke, scale, values); assembledFor = scale; } };
181
+ const pat = pattern(g),
182
+ { dim } = g,
183
+ bb = dim * dim;
184
+ let values = cellMatrices ? assemble(g, pat, cellMatrices, null, null) : null,
185
+ assembledFor = cellMatrices ? undefined : {};
186
+ const ready = (scale) => {
187
+ if (!cellMatrices && assembledFor !== scale) {
188
+ values = assemble(g, pat, null, ke, scale, values);
189
+ assembledFor = scale;
190
+ }
191
+ };
118
192
  // Each node's diagonal block, inverted, with fixed dofs left out (their rows and columns zero, so they don't move);
119
193
  // a node with nothing round it (no stiffness) doesn't move either. Kept until the values or the fixed dofs change.
120
- let invFor = null, invValues = null, inv = null;
194
+ let invFor = null,
195
+ invValues = null,
196
+ inv = null;
121
197
  function inverses(fixed) {
122
198
  if (inv && invFor === fixed && invValues === values) return inv;
123
- const { rows, self } = pat, n = g.nodes;
124
- inv = new Float64Array(n * bb); invFor = fixed; invValues = values;
199
+ const { rows, self } = pat,
200
+ n = g.nodes;
201
+ inv = new Float64Array(n * bb);
202
+ invFor = fixed;
203
+ invValues = values;
125
204
  const D = new Float64Array(bb);
126
205
  for (let i = 0; i < n; i++) {
127
- const o = (rows[i] + self[i]) * bb, b = i * bb;
206
+ const o = (rows[i] + self[i]) * bb,
207
+ b = i * bb;
128
208
  for (let q = 0; q < bb; q++) D[q] = values[o + q];
129
- for (let q = 0; q < dim; q++) if (fixed[dim * i + q]) { for (let f = 0; f < dim; f++) { D[q * dim + f] = 0; D[f * dim + q] = 0; } }
209
+ for (let q = 0; q < dim; q++)
210
+ if (fixed[dim * i + q]) {
211
+ for (let f = 0; f < dim; f++) {
212
+ D[q * dim + f] = 0;
213
+ D[f * dim + q] = 0;
214
+ }
215
+ }
130
216
  if (dim === 2) {
131
217
  const det = D[0] * D[3] - D[1] * D[2];
132
218
  if (!(Math.abs(det) > 0)) {
133
219
  // One dof fixed (a roller, a symmetry edge): the block is singular, so invert the free dof on its own,
134
220
  // as the 3D branch does. (Skipped, the node was never smoothed, and multigrid never converged)
135
- for (let q = 0; q < dim; q++) if (!fixed[dim * i + q] && D[q * dim + q] > 0) inv[b + q * dim + q] = 1 / D[q * dim + q];
221
+ for (let q = 0; q < dim; q++)
222
+ if (!fixed[dim * i + q] && D[q * dim + q] > 0) inv[b + q * dim + q] = 1 / D[q * dim + q];
136
223
  continue;
137
224
  }
138
- inv[b] = D[3] / det; inv[b + 1] = -D[1] / det; inv[b + 2] = -D[2] / det; inv[b + 3] = D[0] / det;
225
+ inv[b] = D[3] / det;
226
+ inv[b + 1] = -D[1] / det;
227
+ inv[b + 2] = -D[2] / det;
228
+ inv[b + 3] = D[0] / det;
139
229
  } else {
140
- const c0 = D[4] * D[8] - D[5] * D[7], c1 = D[5] * D[6] - D[3] * D[8], c2 = D[3] * D[7] - D[4] * D[6], det = D[0] * c0 + D[1] * c1 + D[2] * c2;
230
+ const c0 = D[4] * D[8] - D[5] * D[7],
231
+ c1 = D[5] * D[6] - D[3] * D[8],
232
+ c2 = D[3] * D[7] - D[4] * D[6],
233
+ det = D[0] * c0 + D[1] * c1 + D[2] * c2;
141
234
  if (!(Math.abs(det) > 0)) {
142
235
  // Some dofs fixed: invert what's left, dof by dof where the block is diagonal there
143
- for (let q = 0; q < dim; q++) if (!fixed[dim * i + q] && D[q * dim + q] > 0) inv[b + q * dim + q] = 1 / D[q * dim + q];
236
+ for (let q = 0; q < dim; q++)
237
+ if (!fixed[dim * i + q] && D[q * dim + q] > 0) inv[b + q * dim + q] = 1 / D[q * dim + q];
144
238
  continue;
145
239
  }
146
- inv[b] = c0 / det; inv[b + 1] = (D[2] * D[7] - D[1] * D[8]) / det; inv[b + 2] = (D[1] * D[5] - D[2] * D[4]) / det;
147
- inv[b + 3] = c1 / det; inv[b + 4] = (D[0] * D[8] - D[2] * D[6]) / det; inv[b + 5] = (D[2] * D[3] - D[0] * D[5]) / det;
148
- inv[b + 6] = c2 / det; inv[b + 7] = (D[1] * D[6] - D[0] * D[7]) / det; inv[b + 8] = (D[0] * D[4] - D[1] * D[3]) / det;
240
+ inv[b] = c0 / det;
241
+ inv[b + 1] = (D[2] * D[7] - D[1] * D[8]) / det;
242
+ inv[b + 2] = (D[1] * D[5] - D[2] * D[4]) / det;
243
+ inv[b + 3] = c1 / det;
244
+ inv[b + 4] = (D[0] * D[8] - D[2] * D[6]) / det;
245
+ inv[b + 5] = (D[2] * D[3] - D[0] * D[5]) / det;
246
+ inv[b + 6] = c2 / det;
247
+ inv[b + 7] = (D[1] * D[6] - D[0] * D[7]) / det;
248
+ inv[b + 8] = (D[0] * D[4] - D[1] * D[3]) / det;
149
249
  }
150
250
  }
151
251
  return inv;
@@ -153,69 +253,128 @@ export const jsBackend = {
153
253
  return {
154
254
  multiply(scale, x, y) {
155
255
  ready(scale);
156
- const { rows, cols } = pat, n = g.nodes, v = values;
256
+ const { rows, cols } = pat,
257
+ n = g.nodes,
258
+ v = values;
157
259
  if (dim === 3) {
158
260
  for (let i = 0; i < n; i++) {
159
- let y0 = 0, y1 = 0, y2 = 0;
261
+ let y0 = 0,
262
+ y1 = 0,
263
+ y2 = 0;
160
264
  for (let t = rows[i], end = rows[i + 1]; t < end; t++) {
161
- const j = cols[t] * 3, o = t * 9, x0 = x[j], x1 = x[j + 1], x2 = x[j + 2];
265
+ const j = cols[t] * 3,
266
+ o = t * 9,
267
+ x0 = x[j],
268
+ x1 = x[j + 1],
269
+ x2 = x[j + 2];
162
270
  y0 += v[o] * x0 + v[o + 1] * x1 + v[o + 2] * x2;
163
271
  y1 += v[o + 3] * x0 + v[o + 4] * x1 + v[o + 5] * x2;
164
272
  y2 += v[o + 6] * x0 + v[o + 7] * x1 + v[o + 8] * x2;
165
273
  }
166
- y[3 * i] = y0; y[3 * i + 1] = y1; y[3 * i + 2] = y2;
274
+ y[3 * i] = y0;
275
+ y[3 * i + 1] = y1;
276
+ y[3 * i + 2] = y2;
167
277
  }
168
278
  } else {
169
279
  for (let i = 0; i < n; i++) {
170
- let y0 = 0, y1 = 0;
280
+ let y0 = 0,
281
+ y1 = 0;
171
282
  for (let t = rows[i], end = rows[i + 1]; t < end; t++) {
172
- const j = cols[t] * 2, o = t * 4, x0 = x[j], x1 = x[j + 1];
173
- y0 += v[o] * x0 + v[o + 1] * x1; y1 += v[o + 2] * x0 + v[o + 3] * x1;
283
+ const j = cols[t] * 2,
284
+ o = t * 4,
285
+ x0 = x[j],
286
+ x1 = x[j + 1];
287
+ y0 += v[o] * x0 + v[o + 1] * x1;
288
+ y1 += v[o + 2] * x0 + v[o + 3] * x1;
174
289
  }
175
- y[2 * i] = y0; y[2 * i + 1] = y1;
290
+ y[2 * i] = y0;
291
+ y[2 * i + 1] = y1;
176
292
  }
177
293
  }
178
294
  },
179
295
  diagonal(scale, d) {
180
296
  ready(scale);
181
297
  const { rows, self } = pat;
182
- for (let i = 0; i < g.nodes; i++) { const o = (rows[i] + self[i]) * bb; for (let q = 0; q < dim; q++) d[dim * i + q] = values[o + q * dim + q]; }
298
+ for (let i = 0; i < g.nodes; i++) {
299
+ const o = (rows[i] + self[i]) * bb;
300
+ for (let q = 0; q < dim; q++) d[dim * i + q] = values[o + q * dim + q];
301
+ }
183
302
  },
184
303
  // One symmetric Gauss-Seidel sweep on K x = r, in place: forward through the nodes, then back, each node's dofs
185
304
  // solved together through its diagonal block's inverse, with its neighbours' latest values. Fixed dofs stay.
186
305
  // Symmetric, so a multigrid cycle smoothed with it can precondition conjugate gradients.
187
306
  smooth(scale, fixed, r, x) {
188
307
  ready(scale);
189
- const inv = inverses(fixed), { rows, cols } = pat, n = g.nodes, v = values;
190
- const node = dim === 3
191
- ? (i) => {
192
- let y0 = 0, y1 = 0, y2 = 0;
193
- for (let t = rows[i], end = rows[i + 1]; t < end; t++) {
194
- const j = cols[t] * 3, o = t * 9, x0 = x[j], x1 = x[j + 1], x2 = x[j + 2];
195
- y0 += v[o] * x0 + v[o + 1] * x1 + v[o + 2] * x2; y1 += v[o + 3] * x0 + v[o + 4] * x1 + v[o + 5] * x2; y2 += v[o + 6] * x0 + v[o + 7] * x1 + v[o + 8] * x2;
196
- }
197
- const k = 3 * i, b = 9 * i, r0 = r[k] - y0, r1 = r[k + 1] - y1, r2 = r[k + 2] - y2;
198
- x[k] += inv[b] * r0 + inv[b + 1] * r1 + inv[b + 2] * r2; x[k + 1] += inv[b + 3] * r0 + inv[b + 4] * r1 + inv[b + 5] * r2; x[k + 2] += inv[b + 6] * r0 + inv[b + 7] * r1 + inv[b + 8] * r2;
199
- }
200
- : (i) => {
201
- let y0 = 0, y1 = 0;
202
- for (let t = rows[i], end = rows[i + 1]; t < end; t++) { const j = cols[t] * 2, o = t * 4, x0 = x[j], x1 = x[j + 1]; y0 += v[o] * x0 + v[o + 1] * x1; y1 += v[o + 2] * x0 + v[o + 3] * x1; }
203
- const k = 2 * i, b = 4 * i, r0 = r[k] - y0, r1 = r[k + 1] - y1;
204
- x[k] += inv[b] * r0 + inv[b + 1] * r1; x[k + 1] += inv[b + 2] * r0 + inv[b + 3] * r1;
205
- };
308
+ const inv = inverses(fixed),
309
+ { rows, cols } = pat,
310
+ n = g.nodes,
311
+ v = values;
312
+ const node =
313
+ dim === 3
314
+ ? (i) => {
315
+ let y0 = 0,
316
+ y1 = 0,
317
+ y2 = 0;
318
+ for (let t = rows[i], end = rows[i + 1]; t < end; t++) {
319
+ const j = cols[t] * 3,
320
+ o = t * 9,
321
+ x0 = x[j],
322
+ x1 = x[j + 1],
323
+ x2 = x[j + 2];
324
+ y0 += v[o] * x0 + v[o + 1] * x1 + v[o + 2] * x2;
325
+ y1 += v[o + 3] * x0 + v[o + 4] * x1 + v[o + 5] * x2;
326
+ y2 += v[o + 6] * x0 + v[o + 7] * x1 + v[o + 8] * x2;
327
+ }
328
+ const k = 3 * i,
329
+ b = 9 * i,
330
+ r0 = r[k] - y0,
331
+ r1 = r[k + 1] - y1,
332
+ r2 = r[k + 2] - y2;
333
+ x[k] += inv[b] * r0 + inv[b + 1] * r1 + inv[b + 2] * r2;
334
+ x[k + 1] += inv[b + 3] * r0 + inv[b + 4] * r1 + inv[b + 5] * r2;
335
+ x[k + 2] += inv[b + 6] * r0 + inv[b + 7] * r1 + inv[b + 8] * r2;
336
+ }
337
+ : (i) => {
338
+ let y0 = 0,
339
+ y1 = 0;
340
+ for (let t = rows[i], end = rows[i + 1]; t < end; t++) {
341
+ const j = cols[t] * 2,
342
+ o = t * 4,
343
+ x0 = x[j],
344
+ x1 = x[j + 1];
345
+ y0 += v[o] * x0 + v[o + 1] * x1;
346
+ y1 += v[o + 2] * x0 + v[o + 3] * x1;
347
+ }
348
+ const k = 2 * i,
349
+ b = 4 * i,
350
+ r0 = r[k] - y0,
351
+ r1 = r[k + 1] - y1;
352
+ x[k] += inv[b] * r0 + inv[b + 1] * r1;
353
+ x[k + 1] += inv[b + 2] * r0 + inv[b + 3] * r1;
354
+ };
206
355
  for (let i = 0; i < n; i++) node(i);
207
356
  for (let i = n - 1; i >= 0; i--) node(i);
208
357
  },
209
358
  };
210
359
  },
211
- dot(a, b) { let s = 0; for (let i = 0; i < a.length; i++) s += a[i] * b[i]; return s; },
212
- axpy(a, x, y) { for (let i = 0; i < y.length; i++) y[i] += a * x[i]; },
360
+ dot(a, b) {
361
+ let s = 0;
362
+ for (let i = 0; i < a.length; i++) s += a[i] * b[i];
363
+ return s;
364
+ },
365
+ axpy(a, x, y) {
366
+ for (let i = 0; i < y.length; i++) y[i] += a * x[i];
367
+ },
213
368
  };
214
369
 
215
370
  // Memory worker threads can share, where there is such a thing (Node; browsers only when cross-origin isolated)
216
371
  const Shared = typeof SharedArrayBuffer === 'function' ? SharedArrayBuffer : ArrayBuffer;
217
372
  // A copy of a typed array on it
218
- const shared = (a) => { const out = new a.constructor(new Shared(a.byteLength)); out.set(a); return out; };
373
+ const shared = (a) => {
374
+ const out = new a.constructor(new Shared(a.byteLength));
375
+ out.set(a);
376
+ return out;
377
+ };
219
378
 
220
379
  // The assembled matrix's shape for a grid, worked out once per grid: for each node, the nodes it shares a cell with
221
380
  // (the 3 × 3 (× 3) round it, in node order: rows, cols), which of them is itself (self), and where each of its
@@ -223,24 +382,55 @@ const shared = (a) => { const out = new a.constructor(new Shared(a.byteLength));
223
382
  const patterns = new WeakMap();
224
383
  export function pattern(g) {
225
384
  if (patterns.has(g)) return patterns.get(g);
226
- const { dim, nodes, cellDofs: m, edof } = g, nk = dim === 3 ? g.nz : 0, corners = CORNERS[dim];
385
+ const { dim, nodes } = g,
386
+ nk = dim === 3 ? g.nz : 0,
387
+ corners = CORNERS[dim];
227
388
  const id = (i, j, k) => (dim === 3 ? g.node(i, j, k) : g.node(i, j));
228
389
  const coords = new Int32Array(nodes * 3);
229
- 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; }
390
+ for (let k = 0; k <= nk; k++)
391
+ for (let j = 0; j <= g.ny; j++)
392
+ for (let i = 0; i <= g.nx; i++) {
393
+ const n = id(i, j, k);
394
+ coords[3 * n] = i;
395
+ coords[3 * n + 1] = j;
396
+ coords[3 * n + 2] = k;
397
+ }
230
398
  const offsets = [];
231
- 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]);
232
- const O = offsets.length, offsetIndex = (a, b, c) => (dim === 3 ? (c + 1) * 9 : 0) + (b + 1) * 3 + (a + 1);
233
- const slot = new Int32Array(nodes * O).fill(-1), rows = new Int32Array(nodes + 1), self = new Int32Array(nodes), cols = [];
399
+ for (let c = dim === 3 ? -1 : 0; c <= (dim === 3 ? 1 : 0); c++)
400
+ for (let b = -1; b <= 1; b++) for (let a = -1; a <= 1; a++) offsets.push([a, b, c]);
401
+ const O = offsets.length,
402
+ offsetIndex = (a, b, c) => (dim === 3 ? (c + 1) * 9 : 0) + (b + 1) * 3 + (a + 1);
403
+ const slot = new Int32Array(nodes * O).fill(-1),
404
+ rows = new Int32Array(nodes + 1),
405
+ self = new Int32Array(nodes),
406
+ cols = [];
234
407
  for (let n = 0; n < nodes; n++) {
235
- const [i, j, k] = [coords[3 * n], coords[3 * n + 1], coords[3 * n + 2]], near = [];
236
- offsets.forEach(([a, b, c], o) => { const I = i + a, J = j + b, K = k + c; if (I >= 0 && I <= g.nx && J >= 0 && J <= g.ny && K >= 0 && K <= nk) near.push([id(I, J, K), o]); });
408
+ const [i, j, k] = [coords[3 * n], coords[3 * n + 1], coords[3 * n + 2]],
409
+ near = [];
410
+ offsets.forEach(([a, b, c], o) => {
411
+ const I = i + a,
412
+ J = j + b,
413
+ K = k + c;
414
+ if (I >= 0 && I <= g.nx && J >= 0 && J <= g.ny && K >= 0 && K <= nk) near.push([id(I, J, K), o]);
415
+ });
237
416
  near.sort((p, q) => p[0] - q[0]);
238
- near.forEach(([nb, o], t) => { slot[n * O + o] = t; if (nb === n) self[n] = t; cols.push(nb); });
417
+ near.forEach(([nb, o], t) => {
418
+ slot[n * O + o] = t;
419
+ if (nb === n) self[n] = t;
420
+ cols.push(nb);
421
+ });
239
422
  rows[n + 1] = cols.length;
240
423
  }
241
424
  // For a cell's corner pair (p, q), the offset of q's node from p's
242
- const C = corners.length, pairOffset = new Int32Array(C * C);
243
- for (let p = 0; p < C; p++) for (let q = 0; q < C; q++) pairOffset[p * C + q] = offsetIndex(corners[q][0] - corners[p][0], corners[q][1] - corners[p][1], (corners[q][2] || 0) - (corners[p][2] || 0));
425
+ const C = corners.length,
426
+ pairOffset = new Int32Array(C * C);
427
+ for (let p = 0; p < C; p++)
428
+ for (let q = 0; q < C; q++)
429
+ pairOffset[p * C + q] = offsetIndex(
430
+ corners[q][0] - corners[p][0],
431
+ corners[q][1] - corners[p][1],
432
+ (corners[q][2] || 0) - (corners[p][2] || 0),
433
+ );
244
434
  const out = { rows: shared(rows), cols: shared(Int32Array.from(cols)), slot, self, pairOffset, O };
245
435
  patterns.set(g, out);
246
436
  return out;
@@ -249,18 +439,27 @@ export function pattern(g) {
249
439
  // The matrix's values, assembled from the cells: each its own matrix (cellMatrices), or ke times its scale (1 with no
250
440
  // scale). Into the buffer given, if any.
251
441
  export function assemble(g, pat, cellMatrices, ke, scale, into) {
252
- const { rows, cols, slot, pairOffset, O } = pat, { dim, cells, cellDofs: m, edof } = g, C = CORNERS[dim].length, bb = dim * dim, mm = m * m;
442
+ const { rows, cols, slot, pairOffset, O } = pat,
443
+ { dim, cells, cellDofs: m, edof } = g,
444
+ C = CORNERS[dim].length,
445
+ bb = dim * dim,
446
+ mm = m * m;
253
447
  const values = into || new Float64Array(new Shared(cols.length * bb * 8));
254
448
  if (into) values.fill(0);
255
449
  const K = cellMatrices || ke;
256
450
  for (let e = 0; e < cells; e++) {
257
451
  const s = scale ? scale[e] : 1;
258
452
  if (s === 0) continue;
259
- const base = cellMatrices ? e * mm : 0, eo = e * m;
453
+ const base = cellMatrices ? e * mm : 0,
454
+ eo = e * m;
260
455
  for (let p = 0; p < C; p++) {
261
- const na = edof[eo + p * dim] / dim, row = rows[na], sb = na * O, pb = p * C;
456
+ const na = edof[eo + p * dim] / dim,
457
+ row = rows[na],
458
+ sb = na * O,
459
+ pb = p * C;
262
460
  for (let q = 0; q < C; q++) {
263
- const t = (row + slot[sb + pairOffset[pb + q]]) * bb, kb = base + p * dim * m + q * dim;
461
+ const t = (row + slot[sb + pairOffset[pb + q]]) * bb,
462
+ kb = base + p * dim * m + q * dim;
264
463
  for (let d = 0; d < dim; d++) for (let f = 0; f < dim; f++) values[t + d * dim + f] += s * K[kb + d * m + f];
265
464
  }
266
465
  }
@@ -277,53 +476,101 @@ export function assemble(g, pat, cellMatrices, ke, scale, into) {
277
476
  * @returns {{ u: Float64Array[], iterations: number, again: (loads: Float64Array[]) => Float64Array[], warning?: string }} warning: multigrid on a grid it couldn't halve far (slow); again: more
278
477
  * loads on the same matrix (an adjoint), reusing its factor or preconditioner
279
478
  */
280
- export function solve(g, { scale, ke, fixed, loads, springs, method = 'direct', backend = jsBackend, tol = 1e-9, maxIter = 20000, start }) {
479
+ export function solve(
480
+ g,
481
+ { scale, ke, fixed, loads, springs, method = 'direct', backend = jsBackend, tol = 1e-9, maxIter = 20000, start },
482
+ ) {
281
483
  // What's wrong with what was handed in is said here, by name: further in, it comes out as a part "not held still",
282
484
  // or as an answer that looks like one
283
485
  if (!['direct', 'cg', 'mg'].includes(method)) throw new Error(`no solver "${method}": direct, cg or mg`);
284
486
  if (scale.length !== g.cells) throw new Error(`scale has ${scale.length} values for ${g.cells} cells`);
285
- if (fixed.length !== g.dofs) throw new Error(`fixed has ${fixed.length} values for ${g.dofs} unknowns (${g.dim} a node)`);
286
- loads.forEach((l, c) => { if (l.length !== g.dofs) throw new Error(`load ${c + 1} has ${l.length} values for ${g.dofs} unknowns (${g.dim} a node)`); });
287
- if (springs && springs.length !== g.dofs) throw new Error(`springs has ${springs.length} values for ${g.dofs} unknowns`);
288
- for (let e = 0; e < scale.length; e++) if (!(scale[e] > 0) || !Number.isFinite(scale[e])) throw new Error(`cell ${e}'s stiffness is ${scale[e]}: every cell needs a stiffness above 0 (a density, modulus or thickness is 0, negative or not a number)`);
289
- for (let i = 0; i < ke.length; i++) if (!Number.isFinite(ke[i])) throw new Error("the cell's stiffness matrix isn't numbers: Poisson's ratio must be between -1 and 0.5");
290
- loads.forEach((l, c) => { for (let i = 0; i < l.length; i++) if (!Number.isFinite(l[i])) throw new Error(`load ${c + 1} has a force that isn't a number`); });
487
+ if (fixed.length !== g.dofs)
488
+ throw new Error(`fixed has ${fixed.length} values for ${g.dofs} unknowns (${g.dim} a node)`);
489
+ loads.forEach((l, c) => {
490
+ if (l.length !== g.dofs)
491
+ throw new Error(`load ${c + 1} has ${l.length} values for ${g.dofs} unknowns (${g.dim} a node)`);
492
+ });
493
+ if (springs && springs.length !== g.dofs)
494
+ throw new Error(`springs has ${springs.length} values for ${g.dofs} unknowns`);
495
+ for (let e = 0; e < scale.length; e++)
496
+ if (!(scale[e] > 0) || !Number.isFinite(scale[e]))
497
+ throw new Error(
498
+ `cell ${e}'s stiffness is ${scale[e]}: every cell needs a stiffness above 0 (a density, modulus or thickness is 0, negative or not a number)`,
499
+ );
500
+ for (let i = 0; i < ke.length; i++)
501
+ if (!Number.isFinite(ke[i]))
502
+ throw new Error("the cell's stiffness matrix isn't numbers: Poisson's ratio must be between -1 and 0.5");
503
+ loads.forEach((l, c) => {
504
+ for (let i = 0; i < l.length; i++)
505
+ if (!Number.isFinite(l[i])) throw new Error(`load ${c + 1} has a force that isn't a number`);
506
+ });
291
507
  if (!fixed.some((f) => f)) throw new Error('nothing is held: fix at least one support, or the part just moves');
292
- const held = (ls) => ls.map((l) => { const c = Float64Array.from(l); for (let i = 0; i < c.length; i++) if (fixed[i]) c[i] = 0; return c; });
508
+ const held = (ls) =>
509
+ ls.map((l) => {
510
+ const c = Float64Array.from(l);
511
+ for (let i = 0; i < c.length; i++) if (fixed[i]) c[i] = 0;
512
+ return c;
513
+ });
293
514
  if (method === 'direct') {
294
- const L = factor(g, { scale, ke, springs }, fixed), again = (ls) => held(ls).map((b) => L.solve(b));
515
+ const L = factor(g, { scale, ke, springs }, fixed),
516
+ again = (ls) => held(ls).map((b) => L.solve(b));
295
517
  return { u: again(loads), iterations: 0, again };
296
518
  }
297
519
  const cells = backend.operator(g, ke); // one for the solver and its preconditioner: the matrix is assembled once
298
520
  // Springs on dofs (a mechanism's input and output): added to the product and the diagonal; the smoother, where the
299
521
  // backend has one, doesn't know them, so Jacobi then (the preconditioner needn't be exact)
300
- const op = springs ? {
301
- multiply(s, x, y) { cells.multiply(s, x, y); for (let i = 0; i < y.length; i++) if (springs[i]) y[i] += springs[i] * x[i]; },
302
- diagonal(s, d) { cells.diagonal(s, d); for (let i = 0; i < d.length; i++) d[i] += springs[i]; },
303
- } : cells;
304
- const precondition = method === 'mg' ? multigrid(g, { scale, ke, fixed, backend, op }) : jacobi(g, { scale, fixed, op });
522
+ const op = springs
523
+ ? {
524
+ multiply(s, x, y) {
525
+ cells.multiply(s, x, y);
526
+ for (let i = 0; i < y.length; i++) if (springs[i]) y[i] += springs[i] * x[i];
527
+ },
528
+ diagonal(s, d) {
529
+ cells.diagonal(s, d);
530
+ for (let i = 0; i < d.length; i++) d[i] += springs[i];
531
+ },
532
+ }
533
+ : cells;
534
+ const precondition =
535
+ method === 'mg' ? multigrid(g, { scale, ke, fixed, backend, op }) : jacobi(g, { scale, fixed, op });
305
536
  // Multigrid halves each side while it can: a grid with an odd side stops early, and its coarsest grid, solved
306
537
  // directly, can be most of the work (33 × 17 × 17 cells took 80 times 32 × 16 × 16). Said, with the sides to give
307
- const coarse = method === 'mg' ? hierarchy(g).grids.at(-1) : null, slow = coarse && coarse.dofs > 20 * COARSEST;
308
- const warning = slow ? `multigrid stopped at ${[coarse.nx, coarse.ny, coarse.nz].filter(Boolean).join(' × ')} cells (${coarse.dofs} unknowns, solved directly): a side that can't be halved again; give each side a multiple of 8 cells for a fast solve` : null;
309
- const again = (ls) => conjugateGradients(g, { scale, fixed, loads: held(ls), backend, tol, maxIter, precondition, op }).u;
310
- return { ...conjugateGradients(g, { scale, fixed, loads: held(loads), backend, tol, maxIter, start, precondition, op }), again, ...(warning ? { warning } : {}) };
538
+ const coarse = method === 'mg' ? hierarchy(g).grids.at(-1) : null,
539
+ slow = coarse && coarse.dofs > 20 * COARSEST;
540
+ const warning = slow
541
+ ? `multigrid stopped at ${[coarse.nx, coarse.ny, coarse.nz].filter(Boolean).join(' × ')} cells (${coarse.dofs} unknowns, solved directly): a side that can't be halved again; give each side a multiple of 8 cells for a fast solve`
542
+ : null;
543
+ const again = (ls) =>
544
+ conjugateGradients(g, { scale, fixed, loads: held(ls), backend, tol, maxIter, precondition, op }).u;
545
+ return {
546
+ ...conjugateGradients(g, { scale, fixed, loads: held(loads), backend, tol, maxIter, start, precondition, op }),
547
+ again,
548
+ ...(warning ? { warning } : {}),
549
+ };
311
550
  }
312
551
 
313
552
  // The banded Cholesky factor of K (cells' matrices: ke × scale, or each its own), fixed dofs as identity rows. Lenient
314
553
  // (a preconditioner's coarsest grid, where a coarse unknown over next to nothing can come out singular to rounding), a
315
554
  // pivot that isn't positive is dropped: an identity row with no couplings, so the unknown stays put.
316
555
  function factor(g, { scale, ke, cellMatrices, springs }, fixed, { lenient = false } = {}) {
317
- const { edof, dofs, cells, cellDofs: m } = g, mm = m * m;
556
+ const { edof, dofs, cells, cellDofs: m } = g,
557
+ mm = m * m;
318
558
  let b = 0;
319
559
  for (let e = 0; e < cells; e++) {
320
- let lo = Infinity, hi = -Infinity;
321
- for (let a = 0; a < m; a++) { lo = Math.min(lo, edof[e * m + a]); hi = Math.max(hi, edof[e * m + a]); }
560
+ let lo = Infinity,
561
+ hi = -Infinity;
562
+ for (let a = 0; a < m; a++) {
563
+ lo = Math.min(lo, edof[e * m + a]);
564
+ hi = Math.max(hi, edof[e * m + a]);
565
+ }
322
566
  b = Math.max(b, hi - lo);
323
567
  }
324
- 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
568
+ const w = b + 1,
569
+ 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
325
570
  for (let e = 0; e < cells; e++) {
326
- const s = scale ? scale[e] : 1, K = cellMatrices || ke, base = cellMatrices ? e * mm : 0;
571
+ const s = scale ? scale[e] : 1,
572
+ K = cellMatrices || ke,
573
+ base = cellMatrices ? e * mm : 0;
327
574
  for (let p = 0; p < m; p++) {
328
575
  const i = edof[e * m + p];
329
576
  if (fixed[i]) continue;
@@ -338,18 +585,33 @@ function factor(g, { scale, ke, cellMatrices, springs }, fixed, { lenient = fals
338
585
  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
339
586
  const dropped = lenient ? new Uint8Array(dofs) : null;
340
587
  for (let i = 0; i < dofs; i++) {
341
- const from = Math.max(0, i - b), ri = i * w + b - i; // L[i][k] is at ri + k
588
+ const from = Math.max(0, i - b),
589
+ ri = i * w + b - i; // L[i][k] is at ri + k
342
590
  for (let j = from; j <= i; j++) {
343
- if (dropped && dropped[j]) { L[ri + j] = 0; continue; }
591
+ if (dropped && dropped[j]) {
592
+ L[ri + j] = 0;
593
+ continue;
594
+ }
344
595
  const rj = j * w + b - j;
345
- let s = L[ri + j], s1 = 0, s2 = 0, s3 = 0, k = from;
346
- for (; k + 3 < j; k += 4) { s -= L[ri + k] * L[rj + k]; s1 += L[ri + k + 1] * L[rj + k + 1]; s2 += L[ri + k + 2] * L[rj + k + 2]; s3 += L[ri + k + 3] * L[rj + k + 3]; } // four running sums: a little faster
596
+ let s = L[ri + j],
597
+ s1 = 0,
598
+ s2 = 0,
599
+ s3 = 0,
600
+ k = from;
601
+ for (; k + 3 < j; k += 4) {
602
+ s -= L[ri + k] * L[rj + k];
603
+ s1 += L[ri + k + 1] * L[rj + k + 1];
604
+ s2 += L[ri + k + 2] * L[rj + k + 2];
605
+ s3 += L[ri + k + 3] * L[rj + k + 3];
606
+ } // four running sums: a little faster
347
607
  for (; k < j; k++) s -= L[ri + k] * L[rj + k];
348
608
  s -= s1 + s2 + s3;
349
609
  if (j === i) {
350
610
  if (!(s > 0)) {
351
611
  if (!dropped) throw new Error('the part is not held still: add supports, or join loose pieces to it');
352
- dropped[i] = 1; s = 1; for (let k = from; k < i; k++) L[ri + k] = 0;
612
+ dropped[i] = 1;
613
+ s = 1;
614
+ for (let k = from; k < i; k++) L[ri + k] = 0;
353
615
  }
354
616
  L[i * w + b] = Math.sqrt(s);
355
617
  } else L[ri + j] = s / L[j * w + b];
@@ -379,34 +641,53 @@ function jacobi(g, { scale, fixed, op }) {
379
641
  const d = new Float64Array(g.dofs);
380
642
  op.diagonal(scale, d);
381
643
  for (let i = 0; i < d.length; i++) d[i] = fixed[i] || !(d[i] > 0) ? 1 : 1 / d[i];
382
- return (r, z) => { for (let i = 0; i < r.length; i++) z[i] = d[i] * r[i]; };
644
+ return (r, z) => {
645
+ for (let i = 0; i < r.length; i++) z[i] = d[i] * r[i];
646
+ };
383
647
  }
384
648
 
385
649
  // Conjugate gradients, matrix-free: fixed dofs stay at 0 (their rows act as the identity)
386
650
  function conjugateGradients(g, { scale, fixed, loads, backend, tol, maxIter, start, precondition, op }) {
387
651
  const n = g.dofs;
388
- const apply = (x, y) => { op.multiply(scale, x, y); for (let i = 0; i < n; i++) if (fixed[i]) y[i] = x[i]; };
652
+ const apply = (x, y) => {
653
+ op.multiply(scale, x, y);
654
+ for (let i = 0; i < n; i++) if (fixed[i]) y[i] = x[i];
655
+ };
389
656
  let total = 0;
390
657
  const u = loads.map((f, c) => {
391
658
  const x = start?.[c] ? Float64Array.from(start[c]) : new Float64Array(n);
392
659
  for (let i = 0; i < n; i++) if (fixed[i]) x[i] = 0;
393
- const r = new Float64Array(n), z = new Float64Array(n), p = new Float64Array(n), q = new Float64Array(n);
660
+ const r = new Float64Array(n),
661
+ z = new Float64Array(n),
662
+ p = new Float64Array(n),
663
+ q = new Float64Array(n);
394
664
  apply(x, q);
395
665
  for (let i = 0; i < n; i++) r[i] = f[i] - q[i];
396
666
  const limit = tol * Math.sqrt(backend.dot(f, f));
397
- precondition(r, z); p.set(z);
398
- let rz = backend.dot(r, z), it = 0;
667
+ precondition(r, z);
668
+ p.set(z);
669
+ let rz = backend.dot(r, z),
670
+ it = 0;
399
671
  while (Math.sqrt(backend.dot(r, r)) > limit && it < maxIter) {
400
672
  apply(p, q);
401
- const pq = backend.dot(p, q), a = rz / pq;
402
- if (!(pq > 0) || !Number.isFinite(a)) throw new Error('the part is not held still (it can slide or turn under this load): add supports, or join loose pieces to it'); // (a direction with no stiffness: the search would go on for ever, or stop on nonsense)
403
- backend.axpy(a, p, x); backend.axpy(-a, q, r);
673
+ const pq = backend.dot(p, q),
674
+ a = rz / pq;
675
+ if (!(pq > 0) || !Number.isFinite(a))
676
+ throw new Error(
677
+ 'the part is not held still (it can slide or turn under this load): add supports, or join loose pieces to it',
678
+ ); // (a direction with no stiffness: the search would go on for ever, or stop on nonsense)
679
+ backend.axpy(a, p, x);
680
+ backend.axpy(-a, q, r);
404
681
  precondition(r, z);
405
682
  const next = backend.dot(r, z);
406
683
  for (let i = 0; i < n; i++) p[i] = z[i] + (next / rz) * p[i];
407
- rz = next; it++;
684
+ rz = next;
685
+ it++;
408
686
  }
409
- if (it >= maxIter) throw new Error(`the solver didn't settle in ${maxIter} steps: the part may be barely held, or a piece of it loose`);
687
+ if (it >= maxIter)
688
+ throw new Error(
689
+ `the solver didn't settle in ${maxIter} steps: the part may be barely held, or a piece of it loose`,
690
+ );
410
691
  total += it;
411
692
  return x;
412
693
  });
@@ -419,7 +700,9 @@ function conjugateGradients(g, { scale, fixed, loads, backend, tol, maxIter, sta
419
700
  // (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
420
701
  // V: two damped Jacobi sweeps down, the coarsest grid solved exactly (banded Cholesky), two sweeps on the way up.
421
702
  // It's symmetric, so conjugate gradients can use it as a preconditioner.
422
- const SWEEPS = 2, DAMPING = 0.5, COARSEST = 600;
703
+ const SWEEPS = 2,
704
+ DAMPING = 0.5,
705
+ COARSEST = 600;
423
706
 
424
707
  // The coarser grids under a grid, and the maps between each pair, worked out once per grid (they don't change as the
425
708
  // cells' stiffnesses do)
@@ -428,7 +711,8 @@ function hierarchy(g) {
428
711
  if (hierarchies.has(g)) return hierarchies.get(g);
429
712
  const grids = [g];
430
713
  for (;;) {
431
- const fg = grids.at(-1), sides = fg.dim === 3 ? [fg.nx, fg.ny, fg.nz] : [fg.nx, fg.ny];
714
+ const fg = grids.at(-1),
715
+ sides = fg.dim === 3 ? [fg.nx, fg.ny, fg.nz] : [fg.nx, fg.ny];
432
716
  if (fg.dofs <= COARSEST || sides.some((s) => s % 2)) break;
433
717
  grids.push(grid({ nx: fg.nx / 2, ny: fg.ny / 2, ...(fg.dim === 3 ? { nz: fg.nz / 2 } : {}), h: fg.h * 2 }));
434
718
  }
@@ -442,28 +726,53 @@ function multigrid(g, { scale, ke, fixed, backend, op }) {
442
726
  const { grids, maps } = hierarchy(g);
443
727
  const levels = [{ g, op, scale, fixed: Uint8Array.from(fixed), mats: null }];
444
728
  for (let l = 1; l < grids.length; l++) {
445
- const f = levels.at(-1), fg = f.g, cg = grids[l];
729
+ const f = levels.at(-1),
730
+ fg = f.g,
731
+ cg = grids[l];
446
732
  const mats = coarsen(fg, cg, f.mats || ke, f.mats ? null : f.scale, f.fixed);
447
- const cfixed = new Uint8Array(cg.dofs), diag = new Float64Array(cg.dofs), m = cg.cellDofs;
448
- 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)];
733
+ const cfixed = new Uint8Array(cg.dofs),
734
+ diag = new Float64Array(cg.dofs),
735
+ m = cg.cellDofs;
736
+ for (let e = 0; e < cg.cells; e++)
737
+ for (let a = 0; a < m; a++) diag[cg.edof[e * m + a]] += mats[e * m * m + a * (m + 1)];
449
738
  for (let i = 0; i < cg.dofs; i++) if (!(diag[i] > 0)) cfixed[i] = 1; // nothing below moves it: held
450
739
  levels.push({ g: cg, op: backend.operator(cg, null, mats), scale: null, fixed: cfixed, mats });
451
740
  }
452
- for (const l of levels) { // each level's diagonal, for its Jacobi sweeps
741
+ for (const l of levels) {
742
+ // each level's diagonal, for its Jacobi sweeps
453
743
  l.inv = new Float64Array(l.g.dofs);
454
744
  l.op.diagonal(l.scale, l.inv);
455
745
  for (let i = 0; i < l.inv.length; i++) l.inv[i] = l.fixed[i] || !(l.inv[i] > 0) ? 0 : DAMPING / l.inv[i];
456
746
  }
457
- const last = levels.at(-1), coarse = factor(last.g, { scale: last.scale, ke, cellMatrices: last.mats }, last.fixed, { lenient: levels.length > 1 });
458
- 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; };
747
+ const last = levels.at(-1),
748
+ coarse = factor(last.g, { scale: last.scale, ke, cellMatrices: last.mats }, last.fixed, {
749
+ lenient: levels.length > 1,
750
+ });
751
+ const apply = (l, x, y) => {
752
+ l.op.multiply(l.scale, x, y);
753
+ for (let i = 0; i < y.length; i++) if (l.fixed[i]) y[i] = 0;
754
+ };
459
755
 
460
756
  const cycle = (k, r) => {
461
757
  const l = levels[k];
462
- 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; }
463
- const n = l.g.dofs, x = new Float64Array(n), Ax = new Float64Array(n), res = new Float64Array(n);
758
+ if (k === levels.length - 1) {
759
+ const x = coarse.solve(r);
760
+ for (let i = 0; i < x.length; i++) if (l.fixed[i]) x[i] = 0;
761
+ return x;
762
+ }
763
+ const n = l.g.dofs,
764
+ x = new Float64Array(n),
765
+ Ax = new Float64Array(n),
766
+ res = new Float64Array(n);
464
767
  // Smoothed by a symmetric Gauss-Seidel sweep where the backend has one (once each way is about as much work as
465
768
  // two Jacobi sweeps, and smooths better), else by damped Jacobi
466
- const sweep = () => { if (l.op.smooth) l.op.smooth(l.scale, l.fixed, r, x); else { apply(l, x, Ax); for (let i = 0; i < n; i++) x[i] += l.inv[i] * (r[i] - Ax[i]); } };
769
+ const sweep = () => {
770
+ if (l.op.smooth) l.op.smooth(l.scale, l.fixed, r, x);
771
+ else {
772
+ apply(l, x, Ax);
773
+ for (let i = 0; i < n; i++) x[i] += l.inv[i] * (r[i] - Ax[i]);
774
+ }
775
+ };
467
776
  const sweeps = l.op.smooth ? 1 : SWEEPS;
468
777
  for (let s = 0; s < sweeps; s++) sweep();
469
778
  apply(l, x, Ax);
@@ -482,10 +791,13 @@ function multigrid(g, { scale, ke, fixed, backend, op }) {
482
791
  // The interpolation weights from a coarse cell's corners to one child's corners: for child offset o (each 0 or 1),
483
792
  // a (cellDofs × cellDofs) matrix P_o with child dof = Σ P_o[child][coarse] × coarse dof, kept as its nonzero entries
484
793
  function childInterpolation(dim) {
485
- const corners = CORNERS[dim], m = corners.length * dim, out = [];
794
+ const corners = CORNERS[dim],
795
+ m = corners.length * dim,
796
+ out = [];
486
797
  for (const o of corners) {
487
798
  const P = new Float64Array(m * m);
488
- corners.forEach((c, q) => { // the child's corner q, at (o + c) / 2 in the coarse cell
799
+ corners.forEach((c, q) => {
800
+ // the child's corner q, at (o + c) / 2 in the coarse cell
489
801
  const at = c.map((x, a) => (o[a] + x) / 2);
490
802
  corners.forEach((C, Q) => {
491
803
  const wgt = at.reduce((p, x, a) => p * (C[a] ? x : 1 - x), 1);
@@ -493,8 +805,16 @@ function childInterpolation(dim) {
493
805
  });
494
806
  });
495
807
  // As its nonzero entries: rows, columns, weights
496
- const rows = [], cols = [], wts = [];
497
- 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]); }
808
+ const rows = [],
809
+ cols = [],
810
+ wts = [];
811
+ for (let r = 0; r < m; r++)
812
+ for (let c = 0; c < m; c++)
813
+ if (P[r * m + c]) {
814
+ rows.push(r);
815
+ cols.push(c);
816
+ wts.push(P[r * m + c]);
817
+ }
498
818
  out.push([Int32Array.from(rows), Int32Array.from(cols), Float64Array.from(wts)]);
499
819
  }
500
820
  return out;
@@ -509,42 +829,81 @@ const interpolations = { 2: null, 3: null };
509
829
  const carried = new WeakMap();
510
830
  function carriedUp(ke, dim) {
511
831
  if (carried.has(ke)) return carried.get(ke);
512
- const m = CORNERS[dim].length * dim, mm = m * m, P = interpolations[dim] || (interpolations[dim] = childInterpolation(dim)), KP = new Float64Array(mm);
832
+ const m = CORNERS[dim].length * dim,
833
+ mm = m * m,
834
+ P = interpolations[dim] || (interpolations[dim] = childInterpolation(dim)),
835
+ KP = new Float64Array(mm);
513
836
  const out = P.map(([rows, cols, wts]) => {
514
837
  const o = new Float64Array(mm);
515
838
  KP.fill(0);
516
- for (let t = 0; t < wts.length; t++) { const b = rows[t], c = cols[t], w = wts[t]; for (let a = 0; a < m; a++) KP[a * m + c] += ke[a * m + b] * w; }
517
- for (let t = 0; t < wts.length; t++) { const a = rows[t], r = cols[t], w = wts[t]; for (let c = 0; c < m; c++) o[r * m + c] += w * KP[a * m + c]; }
839
+ for (let t = 0; t < wts.length; t++) {
840
+ const b = rows[t],
841
+ c = cols[t],
842
+ w = wts[t];
843
+ for (let a = 0; a < m; a++) KP[a * m + c] += ke[a * m + b] * w;
844
+ }
845
+ for (let t = 0; t < wts.length; t++) {
846
+ const a = rows[t],
847
+ r = cols[t],
848
+ w = wts[t];
849
+ for (let c = 0; c < m; c++) o[r * m + c] += w * KP[a * m + c];
850
+ }
518
851
  return o;
519
852
  });
520
853
  carried.set(ke, out);
521
854
  return out;
522
855
  }
523
856
  function coarsen(fg, cg, K, scale, fixed) {
524
- const dim = fg.dim, m = fg.cellDofs, mm = m * m, corners = CORNERS[dim];
525
- const P = interpolations[dim] || (interpolations[dim] = childInterpolation(dim)), ready = scale ? carriedUp(K, dim) : null;
526
- const out = new Float64Array(cg.cells * mm), KP = new Float64Array(mm), held = new Uint8Array(m);
857
+ const dim = fg.dim,
858
+ m = fg.cellDofs,
859
+ mm = m * m,
860
+ corners = CORNERS[dim];
861
+ const P = interpolations[dim] || (interpolations[dim] = childInterpolation(dim)),
862
+ ready = scale ? carriedUp(K, dim) : null;
863
+ const out = new Float64Array(cg.cells * mm),
864
+ KP = new Float64Array(mm),
865
+ held = new Uint8Array(m);
527
866
  const shared = scale ? K : null; // fine level: one matrix scaled per cell; coarser: each cell its own
528
867
  const offset = corners.map((o) => ((o[2] || 0) * fg.ny + o[1]) * fg.nx + o[0]); // a child's cell number from its first
529
868
  for (let E = 0; E < cg.cells; E++) {
530
- const I = E % cg.nx, J = Math.floor(E / cg.nx) % cg.ny, Kz = dim === 3 ? Math.floor(E / (cg.nx * cg.ny)) : 0;
531
- const first = (2 * Kz * fg.ny + 2 * J) * fg.nx + 2 * I, o0 = E * mm;
869
+ const I = E % cg.nx,
870
+ J = Math.floor(E / cg.nx) % cg.ny,
871
+ Kz = dim === 3 ? Math.floor(E / (cg.nx * cg.ny)) : 0;
872
+ const first = (2 * Kz * fg.ny + 2 * J) * fg.nx + 2 * I,
873
+ o0 = E * mm;
532
874
  for (let oi = 0; oi < corners.length; oi++) {
533
- const e = first + offset[oi], s = scale ? scale[e] : 1, base = shared ? 0 : e * mm, src = shared || K;
875
+ const e = first + offset[oi],
876
+ s = scale ? scale[e] : 1,
877
+ base = shared ? 0 : e * mm,
878
+ src = shared || K;
534
879
  if (s === 0) continue;
535
880
  let any = 0;
536
- for (let a = 0; a < m; a++) { held[a] = fixed[fg.edof[e * m + a]]; any |= held[a]; }
537
- if (ready && !any) { const R = ready[oi]; for (let t = 0; t < mm; t++) out[o0 + t] += s * R[t]; continue; }
881
+ for (let a = 0; a < m; a++) {
882
+ held[a] = fixed[fg.edof[e * m + a]];
883
+ any |= held[a];
884
+ }
885
+ if (ready && !any) {
886
+ const R = ready[oi];
887
+ for (let t = 0; t < mm; t++) out[o0 + t] += s * R[t];
888
+ continue;
889
+ }
538
890
  const [rows, cols, wts] = P[oi];
539
891
  KP.fill(0);
540
- for (let t = 0; t < wts.length; t++) { // KP = child × P_o
892
+ for (let t = 0; t < wts.length; t++) {
893
+ // KP = child × P_o
541
894
  const b = rows[t];
542
895
  if (held[b]) continue;
543
- const c = cols[t], w = s * wts[t];
896
+ const c = cols[t],
897
+ w = s * wts[t];
544
898
  for (let a = 0; a < m; a++) if (!held[a]) KP[a * m + c] += src[base + a * m + b] * w;
545
899
  }
546
- for (let t = 0; t < wts.length; t++) { // out += P_oᵀ × KP
547
- const a = rows[t], r = cols[t], w = wts[t], ro = o0 + r * m, ka = a * m;
900
+ for (let t = 0; t < wts.length; t++) {
901
+ // out += P_oᵀ × KP
902
+ const a = rows[t],
903
+ r = cols[t],
904
+ w = wts[t],
905
+ ro = o0 + r * m,
906
+ ka = a * m;
548
907
  for (let c = 0; c < m; c++) out[ro + c] += w * KP[ka + c];
549
908
  }
550
909
  }
@@ -556,23 +915,40 @@ function coarsen(fg, cg, K, scale, fixed) {
556
915
  // coarse nodes round it, 1, 2, 4 or 8 of them) and restrict, its transpose. Each fine node's coarse nodes and weights
557
916
  // are listed once, as flat arrays.
558
917
  function transfer(fg, cg) {
559
- const dim = fg.dim, nk = dim === 3 ? fg.nz : 0, start = new Int32Array(fg.nodes + 1), from = [], weight = [];
918
+ const dim = fg.dim,
919
+ nk = dim === 3 ? fg.nz : 0,
920
+ start = new Int32Array(fg.nodes + 1),
921
+ from = [],
922
+ weight = [];
560
923
  const order = new Int32Array(fg.nodes);
561
924
  let n = 0;
562
- for (let k = 0; k <= nk; k++) for (let j = 0; j <= fg.ny; j++) for (let i = 0; i <= fg.nx; i++) {
563
- const node = dim === 3 ? fg.node(i, j, k) : fg.node(i, j);
564
- let picks = [[i >> 1, j >> 1, k >> 1]];
565
- [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))]); });
566
- 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); }
567
- order[n] = node; start[++n] = from.length;
568
- }
569
- const F = Int32Array.from(from), W = Float64Array.from(weight);
925
+ for (let k = 0; k <= nk; k++)
926
+ for (let j = 0; j <= fg.ny; j++)
927
+ for (let i = 0; i <= fg.nx; i++) {
928
+ const node = dim === 3 ? fg.node(i, j, k) : fg.node(i, j);
929
+ let picks = [[i >> 1, j >> 1, k >> 1]];
930
+ [i, j, k].slice(0, dim).forEach((c, a) => {
931
+ if (c & 1) picks = picks.flatMap((p) => [p, p.map((v, b) => (b === a ? v + 1 : v))]);
932
+ });
933
+ for (const c of picks) {
934
+ from.push(dim === 3 ? cg.node(c[0], c[1], c[2]) : cg.node(c[0], c[1]));
935
+ weight.push(1 / picks.length);
936
+ }
937
+ order[n] = node;
938
+ start[++n] = from.length;
939
+ }
940
+ const F = Int32Array.from(from),
941
+ W = Float64Array.from(weight);
570
942
  return {
571
943
  prolong(xc) {
572
944
  const xf = new Float64Array(fg.dofs);
573
945
  for (let q = 0; q < fg.nodes; q++) {
574
946
  const o = dim * order[q];
575
- 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]; }
947
+ for (let t = start[q]; t < start[q + 1]; t++) {
948
+ const c = dim * F[t],
949
+ w = W[t];
950
+ for (let d = 0; d < dim; d++) xf[o + d] += w * xc[c + d];
951
+ }
576
952
  }
577
953
  return xf;
578
954
  },
@@ -580,7 +956,11 @@ function transfer(fg, cg) {
580
956
  const rc = new Float64Array(cg.dofs);
581
957
  for (let q = 0; q < fg.nodes; q++) {
582
958
  const o = dim * order[q];
583
- 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]; }
959
+ for (let t = start[q]; t < start[q + 1]; t++) {
960
+ const c = dim * F[t],
961
+ w = W[t];
962
+ for (let d = 0; d < dim; d++) rc[c + d] += w * rf[o + d];
963
+ }
584
964
  }
585
965
  return rc;
586
966
  },
@@ -594,8 +974,17 @@ function transfer(fg, cg) {
594
974
  * @returns {Float64Array}
595
975
  */
596
976
  export function centreStress(h, nu, dim) {
597
- 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);
598
- 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; }
977
+ const m = CORNERS[dim].length * dim,
978
+ rows = dim === 3 ? 6 : 3,
979
+ B = strains(new Array(dim).fill(0), h, dim),
980
+ D = elasticity(nu, dim),
981
+ S = new Float64Array(rows * m);
982
+ for (let p = 0; p < rows; p++)
983
+ for (let a = 0; a < m; a++) {
984
+ let t = 0;
985
+ for (let q = 0; q < rows; q++) t += D[p * rows + q] * B[q * m + a];
986
+ S[p * m + a] = t;
987
+ }
599
988
  return S;
600
989
  }
601
990
 
@@ -605,14 +994,29 @@ export function centreStress(h, nu, dim) {
605
994
  * @returns {number}
606
995
  */
607
996
  export function vonMises(s, dim, grad) {
608
- 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]))
609
- : 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)));
997
+ const v =
998
+ dim === 2
999
+ ? Math.sqrt(Math.max(0, s[0] * s[0] - s[0] * s[1] + s[1] * s[1] + 3 * s[2] * s[2]))
1000
+ : Math.sqrt(
1001
+ Math.max(
1002
+ 0,
1003
+ ((s[0] - s[1]) ** 2 + (s[1] - s[2]) ** 2 + (s[2] - s[0]) ** 2) / 2 +
1004
+ 3 * (s[3] ** 2 + s[4] ** 2 + s[5] ** 2),
1005
+ ),
1006
+ );
610
1007
  if (grad) {
611
1008
  const k = v > 0 ? 1 / (2 * v) : 0;
612
- 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]; }
613
- else {
614
- 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]);
615
- grad[3] = k * 6 * s[3]; grad[4] = k * 6 * s[4]; grad[5] = k * 6 * s[5];
1009
+ if (dim === 2) {
1010
+ grad[0] = k * (2 * s[0] - s[1]);
1011
+ grad[1] = k * (2 * s[1] - s[0]);
1012
+ grad[2] = k * 6 * s[2];
1013
+ } else {
1014
+ grad[0] = k * (2 * s[0] - s[1] - s[2]);
1015
+ grad[1] = k * (2 * s[1] - s[0] - s[2]);
1016
+ grad[2] = k * (2 * s[2] - s[0] - s[1]);
1017
+ grad[3] = k * 6 * s[3];
1018
+ grad[4] = k * 6 * s[4];
1019
+ grad[5] = k * 6 * s[5];
616
1020
  }
617
1021
  }
618
1022
  return v;
@@ -624,61 +1028,392 @@ export function vonMises(s, dim, grad) {
624
1028
  * @returns {Float64Array}
625
1029
  */
626
1030
  export function stress(g, u, modulus, nu) {
627
- 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);
1031
+ const dim = g.dim,
1032
+ m = g.cellDofs,
1033
+ rows = dim === 3 ? 6 : 3,
1034
+ B = strains(new Array(dim).fill(0), g.h, dim),
1035
+ D = elasticity(nu, dim),
1036
+ out = new Float64Array(g.cells);
628
1037
  const strain = new Float64Array(rows);
629
1038
  for (let e = 0; e < g.cells; e++) {
630
1039
  strain.fill(0);
631
1040
  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]];
632
- 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; });
633
- out[e] = dim === 2 ? Math.sqrt(s[0] * s[0] - s[0] * s[1] + s[1] * s[1] + 3 * s[2] * s[2])
634
- : 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));
1041
+ const s = new Array(rows).fill(0).map((_, p) => {
1042
+ let t = 0;
1043
+ for (let q = 0; q < rows; q++) t += D[p * rows + q] * strain[q];
1044
+ return modulus[e] * t;
1045
+ });
1046
+ out[e] = vonMises(s, dim);
1047
+ }
1048
+ return out;
1049
+ }
1050
+
1051
+ // The stress field a cell carries, as few terms as it has ways to deform (5 in 2D, 18 in 3D): each term a stress
1052
+ // component times a product of the natural coordinates (Pian and Sumihara 1984 in 2D, Pian and Tong 1986 in 3D).
1053
+ // Each term: [component, power of ξ, power of η, power of ζ].
1054
+ const STRESS_TERMS = {
1055
+ 2: [
1056
+ [0, 0, 0],
1057
+ [1, 0, 0],
1058
+ [2, 0, 0],
1059
+ [0, 0, 1],
1060
+ [1, 1, 0],
1061
+ ].map(([c, a, b]) => [c, a, b, 0]),
1062
+ 3: [
1063
+ [0, 0, 0, 0],
1064
+ [0, 0, 1, 0],
1065
+ [0, 0, 0, 1],
1066
+ [0, 0, 1, 1],
1067
+ [1, 0, 0, 0],
1068
+ [1, 0, 0, 1],
1069
+ [1, 1, 0, 0],
1070
+ [1, 1, 0, 1],
1071
+ [2, 0, 0, 0],
1072
+ [2, 1, 0, 0],
1073
+ [2, 0, 1, 0],
1074
+ [2, 1, 1, 0],
1075
+ [3, 0, 0, 0],
1076
+ [3, 0, 0, 1],
1077
+ [4, 0, 0, 0],
1078
+ [4, 1, 0, 0],
1079
+ [5, 0, 0, 0],
1080
+ [5, 0, 1, 0],
1081
+ ],
1082
+ };
1083
+ const termsAt = (p, dim) =>
1084
+ STRESS_TERMS[dim].map(([c, ...pow]) => [c, pow.slice(0, dim).reduce((f, k, a) => f * (k ? p[a] : 1), 1)]);
1085
+
1086
+ // For each corner of a cell of side 1 and modulus 1, the matrix (rows × cell dofs) from its movements to the stress at
1087
+ // that corner, read from the forces the cell puts on its corners (K u) rather than from its strains: the stress field
1088
+ // (in STRESS_TERMS) whose work over the cell's strains gives exactly those forces. The cells' forces balance the load,
1089
+ // so across a section this field carries the whole bending moment, even where square cells bend too stiffly and their
1090
+ // strains read low; but it puts too much of the moment at each cell's edges, so alone it reads high (by about 9% at 4
1091
+ // cells through, 4% at 10). See surfaceStress.
1092
+ const balanced = new Map();
1093
+ function balancedCorners(nu, dim) {
1094
+ const key = `${dim} ${nu}`;
1095
+ if (balanced.has(key)) return balanced.get(key);
1096
+ const m = CORNERS[dim].length * dim,
1097
+ n = STRESS_TERMS[dim].length,
1098
+ ke = cellStiffness(nu, dim),
1099
+ gp = 1 / Math.sqrt(3),
1100
+ w = 1 / (1 << dim);
1101
+ const points =
1102
+ dim === 3
1103
+ ? [-gp, gp].flatMap((a) => [-gp, gp].flatMap((b) => [-gp, gp].map((c) => [a, b, c])))
1104
+ : [-gp, gp].flatMap((a) => [-gp, gp].map((b) => [a, b]));
1105
+ const G = new Float64Array(n * m); // ∫ Pᵀ B over the cell: term t's work over dof a's strain
1106
+ for (const p of points) {
1107
+ const B = strains(p, 1, dim);
1108
+ termsAt(p, dim).forEach(([c, v], t) => {
1109
+ for (let a = 0; a < m; a++) G[t * m + a] += w * v * B[c * m + a];
1110
+ });
635
1111
  }
1112
+ // R = (G Gᵀ)⁻¹ G ke: the terms whose forces Gᵀ β are the cell's K u (exactly: K u has no rigid part, and G's rows span the rest)
1113
+ const A = new Float64Array(n * n),
1114
+ GK = new Float64Array(n * m);
1115
+ for (let i = 0; i < n; i++)
1116
+ for (let j = 0; j < n; j++) {
1117
+ let t = 0;
1118
+ for (let a = 0; a < m; a++) t += G[i * m + a] * G[j * m + a];
1119
+ A[i * n + j] = t;
1120
+ }
1121
+ for (let i = 0; i < n; i++)
1122
+ for (let b = 0; b < m; b++) {
1123
+ let t = 0;
1124
+ for (let a = 0; a < m; a++) t += G[i * m + a] * ke[a * m + b];
1125
+ GK[i * m + b] = t;
1126
+ }
1127
+ const R = solveDense(A, GK, n, m);
1128
+ const out = CORNERS[dim].map((c) => {
1129
+ const S = new Float64Array((dim === 3 ? 6 : 3) * m);
1130
+ termsAt(
1131
+ c.map((x) => 2 * x - 1),
1132
+ dim,
1133
+ ).forEach(([comp, v], t) => {
1134
+ for (let a = 0; a < m; a++) S[comp * m + a] += v * R[t * m + a];
1135
+ });
1136
+ return S;
1137
+ });
1138
+ balanced.set(key, out);
636
1139
  return out;
637
1140
  }
1141
+ // A X = B for a small dense A (n × n, symmetric positive definite) and B (n × m), by Gaussian elimination
1142
+ function solveDense(A, B, n, m) {
1143
+ const a = Float64Array.from(A),
1144
+ x = Float64Array.from(B);
1145
+ for (let k = 0; k < n; k++) {
1146
+ let piv = k;
1147
+ for (let i = k + 1; i < n; i++) if (Math.abs(a[i * n + k]) > Math.abs(a[piv * n + k])) piv = i;
1148
+ if (piv !== k) {
1149
+ for (let j = 0; j < n; j++) [a[k * n + j], a[piv * n + j]] = [a[piv * n + j], a[k * n + j]];
1150
+ for (let j = 0; j < m; j++) [x[k * m + j], x[piv * m + j]] = [x[piv * m + j], x[k * m + j]];
1151
+ }
1152
+ for (let i = k + 1; i < n; i++) {
1153
+ const f = a[i * n + k] / a[k * n + k];
1154
+ if (!f) continue;
1155
+ for (let j = k; j < n; j++) a[i * n + j] -= f * a[k * n + j];
1156
+ for (let j = 0; j < m; j++) x[i * m + j] -= f * x[k * m + j];
1157
+ }
1158
+ }
1159
+ for (let k = n - 1; k >= 0; k--) {
1160
+ for (let j = 0; j < m; j++) {
1161
+ let t = x[k * m + j];
1162
+ for (let i = k + 1; i < n; i++) t -= a[k * n + i] * x[i * m + j];
1163
+ x[k * m + j] = t / a[k * n + k];
1164
+ }
1165
+ }
1166
+ return x;
1167
+ }
1168
+
1169
+ // How much of the force-balanced reading (balancedCorners) goes into the surface stress; the rest is the strain
1170
+ // reading. Square cells bend too stiffly (3% at 4 cells through in 2D, 4% in 3D), so the strains read low (4% and 6%
1171
+ // at 4 cells), and the force-balanced field reads high by about twice that: a third of one and two thirds of the other
1172
+ // cancel the two errors. Measured on cantilevers and a beam under pure moment, 2D and 3D, Poisson's ratio 0 to 0.45, 4
1173
+ // to 20 cells through: within 2% of beam theory at mid-span and a beam's depth from the support (test/surface-
1174
+ // stress.test.mjs; right at a clamped edge the stress is concentrated, and reads higher as cells shrink). Both
1175
+ // readings are exact for a cell in uniform stress, so the blend is too.
1176
+ const BALANCED_SHARE = 1 / 3;
1177
+
1178
+ /**
1179
+ * The stress at the part's surface, where bending puts its peak. `stress` reads each cell at its centre, half a cell
1180
+ * inside the surface: in a member n cells through it reads the bending stress low by about one cell's share (27% at 4
1181
+ * cells, 10% at 10). This reads each cell's stress at its corners instead, averages each stress component over the
1182
+ * solid cells (density 0.5 or more) round each node, and gives von Mises there (patch recovery). Averaging over the
1183
+ * cells round a node cancels the false shear a square cell shows at its corners when it bends. At a corner the stress
1184
+ * is two thirds the cell's strains read there, and one third the stress field that reproduces the forces on its corners
1185
+ * (BALANCED_SHARE): the strains alone read low where the cells bend too stiffly. A 4-cell-deep cantilever's surface
1186
+ * stress is within 2% of M c / I, in 2D and 3D, away from the clamped end. At a sharp inside corner, or a curved edge stepped into cells, the
1187
+ * peak keeps rising as the cells shrink: the stress there is concentrated beyond what any grid settles on. A node
1188
+ * with no solid cell round it is averaged over the cells it has.
1189
+ * @param {Grid} g @param {Float64Array} u @param {Float64Array} modulus each cell's Young's modulus (MPa) @param {number} nu
1190
+ * @param {ArrayLike<number>} [density] each cell's density, 0 to 1 (all solid if left out)
1191
+ * @returns {{ nodes: Float64Array, cells: Float64Array }} nodes: von Mises (MPa) at each node; cells: for a solid cell,
1192
+ * the largest of its corners' (its surface stress), and for a cell under 0.5, its centre stress (as `stress`)
1193
+ */
1194
+ export function surfaceStress(g, u, modulus, nu, density) {
1195
+ return recover(g, u, modulus, nu, density, null);
1196
+ }
1197
+ // surfaceStress, given the centre stress where it is already worked out (analyse)
1198
+ function recover(g, u, modulus, nu, density, centres) {
1199
+ const dim = g.dim,
1200
+ m = g.cellDofs,
1201
+ rows = dim === 3 ? 6 : 3,
1202
+ corners = CORNERS[dim],
1203
+ C = corners.length,
1204
+ D = elasticity(nu, dim);
1205
+ // Each corner's matrix from the cell's movements to its stress there (modulus 1): D B at the corner, blended with the
1206
+ // force-balanced field there (which scales as 1 / h, as B does)
1207
+ const W = BALANCED_SHARE,
1208
+ bal = balancedCorners(nu, dim);
1209
+ const S = corners.map((c, q) => {
1210
+ const B = strains(
1211
+ c.map((x) => 2 * x - 1),
1212
+ g.h,
1213
+ dim,
1214
+ ),
1215
+ out = new Float64Array(rows * m);
1216
+ for (let p = 0; p < rows; p++)
1217
+ for (let a = 0; a < m; a++) {
1218
+ let t = 0;
1219
+ for (let r = 0; r < rows; r++) t += D[p * rows + r] * B[r * m + a];
1220
+ out[p * m + a] = (1 - W) * t + (W * bal[q][p * m + a]) / g.h;
1221
+ }
1222
+ return out;
1223
+ });
1224
+ const solid = (e) => !density || density[e] >= 0.5;
1225
+ const sumSolid = new Float64Array(g.nodes * rows),
1226
+ nSolid = new Uint8Array(g.nodes),
1227
+ sumAll = new Float64Array(g.nodes * rows),
1228
+ nAll = new Uint8Array(g.nodes);
1229
+ const ue = new Float64Array(m);
1230
+ for (let e = 0; e < g.cells; e++) {
1231
+ const eo = e * m,
1232
+ inside = solid(e);
1233
+ for (let a = 0; a < m; a++) ue[a] = u[g.edof[eo + a]];
1234
+ for (let q = 0; q < C; q++) {
1235
+ const n = g.edof[eo + q * dim] / dim,
1236
+ Sq = S[q];
1237
+ for (let p = 0; p < rows; p++) {
1238
+ let t = 0;
1239
+ for (let a = 0, o = p * m; a < m; a++) t += Sq[o + a] * ue[a];
1240
+ t *= modulus[e];
1241
+ sumAll[n * rows + p] += t;
1242
+ if (inside) sumSolid[n * rows + p] += t;
1243
+ }
1244
+ nAll[n]++;
1245
+ if (inside) nSolid[n]++;
1246
+ }
1247
+ }
1248
+ const nodes = new Float64Array(g.nodes),
1249
+ s = new Float64Array(rows);
1250
+ for (let n = 0; n < g.nodes; n++) {
1251
+ const [sum, k] = nSolid[n] ? [sumSolid, nSolid[n]] : [sumAll, nAll[n]];
1252
+ if (!k) continue;
1253
+ for (let p = 0; p < rows; p++) s[p] = sum[n * rows + p] / k;
1254
+ nodes[n] = vonMises(s, dim);
1255
+ }
1256
+ const centre = density ? centres || stress(g, u, modulus, nu) : null,
1257
+ cells = new Float64Array(g.cells);
1258
+ for (let e = 0; e < g.cells; e++) {
1259
+ if (!solid(e)) {
1260
+ cells[e] = centre[e];
1261
+ continue;
1262
+ }
1263
+ let most = 0;
1264
+ for (let q = 0; q < C; q++) most = Math.max(most, nodes[g.edof[e * m + q * dim] / dim]);
1265
+ cells[e] = most;
1266
+ }
1267
+ return { nodes, cells };
1268
+ }
1269
+
1270
+ // Members under this many cells through, at the peak stress, are said: the grid reads stress there roughly
1271
+ const STRESS_CELLS = 8;
1272
+
1273
+ // Where a load's peak surface stress is in a member under STRESS_CELLS cells through, a finding saying so. The member's
1274
+ // thickness is counted in solid cells, from the peak cell to the first cell under 0.5 or the grid's edge each way, along
1275
+ // the axes the stress changes fastest across the peak cell (through the depth, for a beam that bends): the shortest.
1276
+ function coarsePeak(g, density, surface, centre, load, loads) {
1277
+ const dim = g.dim,
1278
+ m = g.cellDofs,
1279
+ corners = CORNERS[dim],
1280
+ nz = dim === 3 ? g.nz : 1;
1281
+ let peak = -1;
1282
+ for (let e = 0; e < g.cells; e++)
1283
+ if (density[e] >= 0.5 && (peak < 0 || surface.cells[e] > surface.cells[peak])) peak = e;
1284
+ if (peak < 0 || !(surface.cells[peak] > 0)) return null;
1285
+ const at = [peak % g.nx, Math.floor(peak / g.nx) % g.ny, dim === 3 ? Math.floor(peak / (g.nx * g.ny)) : 0],
1286
+ sides = [g.nx, g.ny, nz];
1287
+ const change = [...Array(dim)].map((_, a) => {
1288
+ // the corners' stress on the cell's far face less its near face, along each axis
1289
+ let d = 0;
1290
+ corners.forEach((c, q) => {
1291
+ d += (c[a] ? 1 : -1) * surface.nodes[g.edof[peak * m + q * dim] / dim];
1292
+ });
1293
+ return Math.abs(d);
1294
+ });
1295
+ const steepest = Math.max(...change),
1296
+ cell = (p) => (p[2] * g.ny + p[1]) * g.nx + p[0];
1297
+ const run = (axis) => {
1298
+ let n = 1;
1299
+ for (const step of [-1, 1])
1300
+ for (let p = at.slice(); ;) {
1301
+ p[axis] += step;
1302
+ if (p[axis] < 0 || p[axis] >= sides[axis] || !(density[cell(p)] >= 0.5)) break;
1303
+ n++;
1304
+ }
1305
+ return n;
1306
+ };
1307
+ // At a clamped end the stress also changes fast along the member (the held face reads low), so the steepest axis
1308
+ // alone can be the length: count each axis the stress changes across by at least half as much, and take the shortest
1309
+ let through = Infinity;
1310
+ for (let a = 0; a < dim; a++) if (change[a] >= steepest / 2) through = Math.min(through, run(a));
1311
+ if (through >= STRESS_CELLS) return null;
1312
+ const lo = at.slice(0, dim).map((i) => i * g.h),
1313
+ hi = lo.map((x) => x + g.h),
1314
+ r = (x) => Math.round(x * 1000) / 1000;
1315
+ const most = surface.cells[peak],
1316
+ low = Math.max(0, Math.round((1 - centre[peak] / most) * 100));
1317
+ return {
1318
+ level: 'warn',
1319
+ code: 'fea.coarse-stress',
1320
+ text: `the highest stress${loads > 1 ? ` under load ${load + 1}` : ''}, ${r(most)} MPa at the part's surface, is in a member only ${through} cell${through === 1 ? '' : 's'} through, under the ${STRESS_CELLS} it takes to read stress closely: there the centre stress reads ${low}% lower, and even the surface stress can be some percent out. Check it on cells half the size, or with a member ${STRESS_CELLS} cells through`,
1321
+ values: { surface: r(most), centre: r(centre[peak]), cells: through, need: STRESS_CELLS, load },
1322
+ at: lo.map((x) => r(x + g.h / 2)),
1323
+ box: { lo: lo.map(r), hi: hi.map(r) },
1324
+ };
1325
+ }
638
1326
 
639
1327
  /**
640
1328
  * Analyse a part: each cell's density (0 empty to 1 solid; Young's modulus scales with density^penal, never below
641
1329
  * 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
642
1330
  * thickness; in 3D thickness is not used.
643
1331
  * @param {{ grid: Grid, density: Float64Array, material: Material, thickness?: number, fixed: Uint8Array, loads: Float64Array[], penal?: number, method?: 'direct' | 'cg' | 'mg', backend?: typeof jsBackend }} o
644
- * @returns {{ u: Float64Array[], compliance: number[], stress: Float64Array[], deflection: { most: number, at: number[] }[] }}
645
- * compliance: f · u per load (N·mm): the work the load does; lower is stiffer. deflection: the largest movement
646
- * of any node in solid material, and where.
1332
+ * @returns {{ u: Float64Array[], thin: { share: number, cells: number }, compliance: number[], stress: Float64Array[], surface: Float64Array[], findings: { level: 'warn', text: string, code: string, values: { surface: number, centre: number, cells: number, need: number, load: number }, at: number[], box: { lo: number[], hi: number[] } }[], deflection: { most: number, at: number[] }[] }}
1333
+ * compliance: f · u per load (N·mm): the work the load does; lower is stiffer. stress: each cell's von Mises stress
1334
+ * (MPa) at its centre, which reads bending stress low by about one cell's share of the member's depth (27% at 4
1335
+ * cells through, 10% at 10). surface: each solid cell's von Mises stress at its surface, the largest of its corners'
1336
+ * (surfaceStress): within 2% of beam theory at 4 cells through; use it for strength. findings: a warning
1337
+ * (fea.coarse-stress) for each load whose peak surface stress is in a member under 8 cells through. deflection: the
1338
+ * largest movement of any node in solid material, and where.
647
1339
  */
648
- export function analyse({ grid: g, density, material, thickness = 1, fixed, loads, penal = 1, method = g.dim === 3 ? 'mg' : 'direct', backend }) {
1340
+ export function analyse({
1341
+ grid: g,
1342
+ density,
1343
+ material,
1344
+ thickness = 1,
1345
+ fixed,
1346
+ loads,
1347
+ penal = 1,
1348
+ method = g.dim === 3 ? 'mg' : 'direct',
1349
+ backend,
1350
+ }) {
649
1351
  if (!(material?.E > 0)) throw new Error(`the material needs a modulus E above 0, in MPa (got ${material?.E})`);
650
- if (!(material.nu > -1 && material.nu < 0.5)) throw new Error(`the material needs a Poisson's ratio nu between -1 and 0.5 (got ${material.nu}): about 0.35 for printed plastics`);
1352
+ if (!(material.nu > -1 && material.nu < 0.5))
1353
+ throw new Error(
1354
+ `the material needs a Poisson's ratio nu between -1 and 0.5 (got ${material.nu}): about 0.35 for printed plastics`,
1355
+ );
651
1356
  if (g.dim === 2 && !(thickness > 0)) throw new Error(`a flat part needs a thickness above 0 mm (got ${thickness})`);
652
1357
  if (density.length !== g.cells) throw new Error(`density has ${density.length} values for ${g.cells} cells`);
653
- for (let e = 0; e < density.length; e++) if (!(density[e] >= 0 && density[e] <= 1)) throw new Error(`cell ${e}'s density is ${density[e]}: each is a share from 0 (empty) to 1 (solid)`);
654
- const { E, nu } = material, Emin = E * 1e-9, ke = cellStiffness(nu, g.dim);
1358
+ for (let e = 0; e < density.length; e++)
1359
+ if (!(density[e] >= 0 && density[e] <= 1))
1360
+ throw new Error(`cell ${e}'s density is ${density[e]}: each is a share from 0 (empty) to 1 (solid)`);
1361
+ const { E, nu } = material,
1362
+ Emin = E * 1e-9,
1363
+ ke = cellStiffness(nu, g.dim);
655
1364
  const modulus = Float64Array.from(density, (x) => Emin + Math.pow(x, penal) * (E - Emin));
656
1365
  const scale = modulus.map((mod) => mod * (g.dim === 3 ? g.h : thickness));
657
1366
  const { u } = solve(g, { scale, ke, fixed, loads, method, backend });
658
- const solidNode = new Uint8Array(g.nodes), corners = CORNERS[g.dim].length;
659
- for (let e = 0; e < density.length; e++) if (density[e] >= 0.5) for (let k = 0; k < corners; k++) solidNode[g.edof[e * g.cellDofs + g.dim * k] / g.dim] = 1;
1367
+ const solidNode = new Uint8Array(g.nodes),
1368
+ corners = CORNERS[g.dim].length;
1369
+ for (let e = 0; e < density.length; e++)
1370
+ if (density[e] >= 0.5) for (let k = 0; k < corners; k++) solidNode[g.edof[e * g.cellDofs + g.dim * k] / g.dim] = 1;
660
1371
  // A part that can still slide or turn is solved all the same, by a hair's stiffness of rounding: it then "moves"
661
1372
  // many times its own size. No real part does, so that is said, not handed back as a deflection. (Most of the
662
1373
  // part, that is: a loose piece beside a held part, such as a disc lying in a mechanism, is the caller's business.)
663
1374
  const span = Math.max(g.nx, g.ny, g.nz || 1) * g.h;
664
1375
  for (const x of u) {
665
- let solid = 0, adrift = 0;
666
- for (let n = 0; n < g.nodes; n++) if (solidNode[n]) { solid++; for (let d = 0; d < g.dim; d++) if (!(Math.abs(x[g.dim * n + d]) < 1e4 * span)) { adrift++; break; } }
667
- if (adrift > solid / 2) throw Object.assign(new Error('the part is not held still (it can slide or turn under this load): fix more of it, in each direction it could move'), { code: 'fea.unheld' });
1376
+ let solid = 0,
1377
+ adrift = 0;
1378
+ for (let n = 0; n < g.nodes; n++)
1379
+ if (solidNode[n]) {
1380
+ solid++;
1381
+ for (let d = 0; d < g.dim; d++)
1382
+ if (!(Math.abs(x[g.dim * n + d]) < 1e4 * span)) {
1383
+ adrift++;
1384
+ break;
1385
+ }
1386
+ }
1387
+ if (adrift > solid / 2)
1388
+ throw Object.assign(
1389
+ new Error(
1390
+ 'the part is not held still (it can slide or turn under this load): fix more of it, in each direction it could move',
1391
+ ),
1392
+ { code: 'fea.unheld' },
1393
+ );
668
1394
  }
669
- const position = positions(g);
1395
+ const position = positions(g),
1396
+ centre = u.map((x) => stress(g, x, modulus, nu)),
1397
+ surface = u.map((x, c) => recover(g, x, modulus, nu, density, centre[c]));
670
1398
  return {
671
1399
  u,
672
1400
  thin: thinShare(g, density),
673
1401
  compliance: u.map((x, c) => jsBackend.dot(loads[c], x)),
674
- stress: u.map((x) => stress(g, x, modulus, nu)),
1402
+ stress: centre,
1403
+ surface: surface.map((s) => s.cells),
1404
+ findings: surface.map((s, c) => coarsePeak(g, density, s, centre[c], c, loads.length)).filter(Boolean),
675
1405
  deflection: u.map((x) => {
676
- let most = 0, at = position[0];
677
- for (let n = 0; n < g.nodes; n++) if (solidNode[n]) {
678
- let s = 0;
679
- for (let d = 0; d < g.dim; d++) s += x[g.dim * n + d] ** 2;
680
- if (Math.sqrt(s) > most) { most = Math.sqrt(s); at = position[n]; }
681
- }
1406
+ let most = 0,
1407
+ at = position[0];
1408
+ for (let n = 0; n < g.nodes; n++)
1409
+ if (solidNode[n]) {
1410
+ let s = 0;
1411
+ for (let d = 0; d < g.dim; d++) s += x[g.dim * n + d] ** 2;
1412
+ if (Math.sqrt(s) > most) {
1413
+ most = Math.sqrt(s);
1414
+ at = position[n];
1415
+ }
1416
+ }
682
1417
  return { most, at };
683
1418
  }),
684
1419
  };
@@ -693,17 +1428,31 @@ export function analyse({ grid: g, density, material, thickness = 1, fixed, load
693
1428
  * @returns {{ share: number, cells: number }}
694
1429
  */
695
1430
  export function thinShare(g, density, k = 2) {
696
- const nx = g.nx, ny = g.ny, nz = g.dim === 3 ? g.nz : 1, N = nx * ny * nz, at = (i, j, l) => (l * ny + j) * nx + i;
1431
+ const nx = g.nx,
1432
+ ny = g.ny,
1433
+ nz = g.dim === 3 ? g.nz : 1,
1434
+ N = nx * ny * nz,
1435
+ at = (i, j, l) => (l * ny + j) * nx + i;
697
1436
  let mask = new Uint8Array(N);
698
1437
  for (let e = 0; e < N; e++) mask[e] = density[e] >= 0.5 ? 1 : 0;
699
1438
  const solid = mask.reduce((a, b) => a + b, 0);
700
1439
  if (!solid) return { share: 0, cells: 2 * k };
701
- const pass = (m, keep) => { // keep: every face-neighbour solid (erode) or any (dilate); outside the grid counts as the cell itself
1440
+ const pass = (m, keep) => {
1441
+ // keep: every face-neighbour solid (erode) or any (dilate); outside the grid counts as the cell itself
702
1442
  const out = new Uint8Array(N);
703
- for (let l = 0; l < nz; l++) for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) {
704
- const e = at(i, j, l), n = [i > 0 ? m[at(i - 1, j, l)] : m[e], i + 1 < nx ? m[at(i + 1, j, l)] : m[e], j > 0 ? m[at(i, j - 1, l)] : m[e], j + 1 < ny ? m[at(i, j + 1, l)] : m[e], ...(nz > 1 ? [l > 0 ? m[at(i, j, l - 1)] : m[e], l + 1 < nz ? m[at(i, j, l + 1)] : m[e]] : [])];
705
- out[e] = keep === 'all' ? (m[e] && n.every((x) => x) ? 1 : 0) : (m[e] || n.some((x) => x) ? 1 : 0);
706
- }
1443
+ for (let l = 0; l < nz; l++)
1444
+ for (let j = 0; j < ny; j++)
1445
+ for (let i = 0; i < nx; i++) {
1446
+ const e = at(i, j, l),
1447
+ n = [
1448
+ i > 0 ? m[at(i - 1, j, l)] : m[e],
1449
+ i + 1 < nx ? m[at(i + 1, j, l)] : m[e],
1450
+ j > 0 ? m[at(i, j - 1, l)] : m[e],
1451
+ j + 1 < ny ? m[at(i, j + 1, l)] : m[e],
1452
+ ...(nz > 1 ? [l > 0 ? m[at(i, j, l - 1)] : m[e], l + 1 < nz ? m[at(i, j, l + 1)] : m[e]] : []),
1453
+ ];
1454
+ out[e] = keep === 'all' ? (m[e] && n.every((x) => x) ? 1 : 0) : m[e] || n.some((x) => x) ? 1 : 0;
1455
+ }
707
1456
  return out;
708
1457
  };
709
1458
  let m = mask;
@@ -720,9 +1469,13 @@ export function thinShare(g, density, k = 2) {
720
1469
  * @returns {number[][]}
721
1470
  */
722
1471
  export function positions(g) {
723
- const out = new Array(g.nodes), nk = g.dim === 3 ? g.nz : 0;
724
- for (let k = 0; k <= nk; k++) for (let j = 0; j <= g.ny; j++) for (let i = 0; i <= g.nx; i++) {
725
- 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];
726
- }
1472
+ const out = new Array(g.nodes),
1473
+ nk = g.dim === 3 ? g.nz : 0;
1474
+ for (let k = 0; k <= nk; k++)
1475
+ for (let j = 0; j <= g.ny; j++)
1476
+ for (let i = 0; i <= g.nx; i++) {
1477
+ if (g.dim === 3) out[g.node(i, j, k)] = [i * g.h, j * g.h, k * g.h];
1478
+ else out[g.node(i, j)] = [i * g.h, j * g.h];
1479
+ }
727
1480
  return out;
728
1481
  }