@rulecad/topopt 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -72,6 +72,46 @@ and drops holes and islands smaller than `minArea`.
72
72
  is split along the same diagonal, so neighbouring cubes cut their shared faces the same way and the surface has no
73
73
  gaps. Then it's smoothed.
74
74
 
75
+ ## Stress limits
76
+
77
+ Stiffness alone puts material in sharp inside corners, where stress concentrates and cracks start. Give a stress limit
78
+ (MPa) instead of a volume, and `optimise` finds the lightest layout that keeps every cell's von Mises stress under it:
79
+
80
+ ```js
81
+ const spec = discretise({ ...problem, volume: undefined, stress: 13 }); // pla.strength / 3
82
+ const result = optimise(spec);
83
+ result.stress; // { peak, limit }: the largest stress in the result's solid cells (MPa)
84
+ ```
85
+
86
+ - **How:** each cell's stress at its centre, as if solid, gets its own limit, scaled by its density so an empty cell's
87
+ limit vanishes (Senhora, Giraldo-Londoño, Menezes, Paulino 2020). An augmented Lagrangian keeps them all: every 5
88
+ steps its multipliers are raised where a limit is broken, and its penalty grows. Each step is a step of the method
89
+ of moving asymptotes (`mma`, after Svanberg's 2007 code, also exported), and needs one more solve, for the adjoint.
90
+ - **Cost:** about a thousand steps, each with two solves, against about two hundred with one for the stiffest layout.
91
+ Start on coarse cells.
92
+ - **Supports and loads:** every cell is limited, those where the part is held and loaded too, so give them some area
93
+ (a hole's edge, a pad): a force on a point is an unlimited stress there.
94
+
95
+ The L-bracket (`reference/lbracket.mjs`), the usual test: a 100 mm square less its top-right 60 mm, held along the
96
+ top of its upright arm and pushed down with 100 N at the end of its lower one, PLA 2 mm thick, on 1 mm cells. Each
97
+ result is re-analysed as it would be made: its smoothed outline, on 0.5 mm cells.
98
+
99
+ | | Space used | Compliance | Peak stress, on its cells | Peak stress, as made |
100
+ |---|---|---|---|---|
101
+ | Stiffest at 40% | 40.0% | 373 N·mm | – | 67.2 MPa |
102
+ | Lightest under 25 MPa | 39.4% | 426 N·mm | 26.2 MPa | 36.6 MPa |
103
+
104
+ ![The L-bracket, stiffest and stress-limited](reference/lbracket.svg)
105
+
106
+ For the same material, the stress-limited bracket draws its members together with filleted joints, and its peak stress
107
+ falls by 46%. Two things to know:
108
+
109
+ - **A sharp corner in the space stays sharp.** The domain's inside corner is where both arms meet, and both results
110
+ keep material there; on finer cells its stress keeps rising. The limit holds to within 5% on the optimiser's own
111
+ cells, not on finer ones. Check the final part on finer cells (cad's `analysis` with a `cell`), and set the limit
112
+ with that margin in mind.
113
+ - **It may not settle within its steps.** This one ran its 1,000 steps with the peak hovering 5% over the limit.
114
+
75
115
  ## Checked against the published code
76
116
 
77
117
  With projection off, it matches a line-by-line port of the 88-line MATLAB code (`reference/top88.py`) step for step:
@@ -89,6 +129,8 @@ Its gradients agree with finite differences through the filter and the projectio
89
129
  - **Compliance:** the load times how far it moves (N·mm); the inverse of stiffness.
90
130
  - **Volume:** the share of the space the result fills, 0 to 1.
91
131
  - **Filter radius:** about the thinnest member, in mm.
132
+ - **Von Mises stress:** one number for how hard a point of material is worked, from all its stresses together; it's
133
+ compared with the material's strength.
92
134
 
93
135
  ## Sources
94
136
 
@@ -102,3 +144,7 @@ Its gradients agree with finite differences through the filter and the projectio
102
144
  - Langelaar (2017). An additive manufacturing filter for topology optimization of print-ready designs. *Structural and
103
145
  Multidisciplinary Optimization* 55, 871–883.
104
146
  - Taubin (1995). A signal processing approach to fair surface design. *SIGGRAPH '95*, 351–358.
147
+ - Senhora, Giraldo-Londoño, Menezes, Paulino (2020). Topology optimization with local stress constraints: a stress
148
+ aggregation-free approach. *Structural and Multidisciplinary Optimization* 62, 1639–1668.
149
+ - Svanberg (1987). The method of moving asymptotes: a new method for structural optimization. *International Journal
150
+ for Numerical Methods in Engineering* 24, 359–373.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/topopt",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "Topology optimisation for flat and solid parts: the stiffest layout of a fixed amount of material, printable without supports if asked, as outlines or a surface ready to print.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -33,7 +33,7 @@
33
33
  "test": "node --test"
34
34
  },
35
35
  "dependencies": {
36
- "@rulecad/fea": "^0.2.0"
36
+ "@rulecad/fea": "^0.2.1"
37
37
  },
38
38
  "types": "./topopt.d.mts"
39
39
  }
package/topopt.d.mts CHANGED
@@ -74,9 +74,15 @@ export function model(spec: ReturnType<typeof discretise>, { method, backend }?:
74
74
  backend?: typeof jsBackend;
75
75
  }): {
76
76
  physical: (x: any, beta: any) => Float64Array<ArrayBuffer>;
77
- evaluate: (x: any, beta: any, { all }?: {
77
+ evaluate: (x: any, beta: any, { all, multipliers }?: {
78
78
  all?: boolean;
79
79
  }) => {
80
+ stress?: {
81
+ J: number;
82
+ d: Float64Array<ArrayBuffer>;
83
+ h: any;
84
+ peak: number;
85
+ };
80
86
  compliance: number;
81
87
  dc: Float64Array<ArrayBuffer>;
82
88
  dv: Float64Array<ArrayBuffer>;
@@ -85,7 +91,21 @@ export function model(spec: ReturnType<typeof discretise>, { method, backend }?:
85
91
  };
86
92
  cells: number;
87
93
  passive: any;
94
+ limits: number;
88
95
  };
96
+ /**
97
+ * The method of moving asymptotes (Svanberg 1987, as his 2007 mmasub and subsolv): one step of minimising f0(x)
98
+ * subject to fi(x) ≤ 0, i = 1..m, xmin ≤ x ≤ xmax, from values and gradients at x. Each step solves a convex
99
+ * approximation, separable in x, by a primal-dual interior-point method. Keeps its asymptotes between steps.
100
+ * @param {{ n: number, m: number, xmin: Float64Array, xmax: Float64Array, move?: number }} o
101
+ */
102
+ export function mma({ n, m, xmin, xmax, move }: {
103
+ n: number;
104
+ m: number;
105
+ xmin: Float64Array;
106
+ xmax: Float64Array;
107
+ move?: number;
108
+ }): (x: Float64Array, f0: number, df0: Float64Array, f: number[], df: Float64Array[], stepMove?: number) => void;
89
109
  /**
90
110
  * The optimisation: from an even spread, step by step, until the densities stop changing (less than tol per step)
91
111
  * with projection at full sharpness, or steps run out.
package/topopt.mjs CHANGED
@@ -6,13 +6,17 @@
6
6
  // optional overhang filter (only material a printer can build without supports), and Heaviside projection (it sharpens
7
7
  // the result). After Andreassen et al. (2011), "Efficient topology optimization in MATLAB using 88 lines of code",
8
8
  // Wang, Lazarov and Sigmund (2011), and Langelaar (2017), "An additive manufacturing filter for topology optimization
9
- // of print-ready designs". No dependencies but @rulecad/fea; runs in browsers and Node. Millimetres, newtons, MPa.
9
+ // of print-ready designs". Or, given a stress limit instead of an amount of material, the lightest layout that keeps
10
+ // every cell under it: an augmented Lagrangian on the cells' limits (Senhora, Giraldo-Londoño, Menezes, Paulino 2020),
11
+ // stepped by the method of moving asymptotes (Svanberg 1987). No dependencies but @rulecad/fea; runs in browsers and
12
+ // Node. Millimetres, newtons, MPa.
10
13
  //
11
14
  // optimise(spec) the method itself, on a grid: densities, supports and loads by dof
15
+ // mma(...) the method of moving asymptotes, for other problems with limits
12
16
  // discretise(problem) a problem in shapes (a region, bosses to keep, holes to avoid, loads at points) to a spec
13
17
  // outlines(result) a 2D result's edges as closed loops in mm, solid on the left, smoothed: ready to extrude
14
18
  // surface(result) a 3D result's surface as a closed triangle mesh in mm, smoothed: ready to print
15
- import { grid as makeGrid, cellStiffness, solve, positions, jsBackend } from '@rulecad/fea';
19
+ import { grid as makeGrid, cellStiffness, solve, positions, jsBackend, centreStress, vonMises } from '@rulecad/fea';
16
20
 
17
21
  export { jsBackend };
18
22
 
@@ -103,8 +107,8 @@ export function discretise(p) {
103
107
  return {
104
108
  grid: size, origin, passive, fixed, loads,
105
109
  material: p.material, thickness: p.thickness, volume: p.volume,
106
- filter: p.filter ?? p.cell * 1.5, penal: p.penal ?? 3, projection: p.projection ?? true, steps: p.steps ?? 300,
107
- ...(p.overhang ? { overhang: p.overhang } : {}),
110
+ filter: p.filter ?? p.cell * 1.5, penal: p.penal ?? 3, projection: p.projection ?? true, steps: p.steps ?? (p.stress ? 1000 : 300),
111
+ ...(p.overhang ? { overhang: p.overhang } : {}), ...(p.stress ? { stress: p.stress } : {}),
108
112
  regions: { keep, avoid },
109
113
  };
110
114
  }
@@ -227,11 +231,11 @@ export function model(spec, { method, backend = jsBackend } = {}) {
227
231
  };
228
232
  let last = null;
229
233
  // Each step solves only the load cases it optimises for (weight above 0); every case is solved when all is set
230
- const evaluate = (x, beta, { all = false } = {}) => {
234
+ const evaluate = (x, beta, { all = false, multipliers } = {}) => {
231
235
  physical(x, beta);
232
236
  for (let e = 0; e < cells; e++) scale[e] = size * (Emin + Math.pow(phys[e], penal) * (E - Emin));
233
237
  const active = spec.loads.map((l, c) => (all || l.weight > 0 ? c : -1)).filter((c) => c >= 0);
234
- const solved = solve(g, { scale, ke, fixed: spec.fixed, loads: active.map((c) => spec.loads[c].force), method: solver, backend, start: last && active.map((c) => last[c]), ...(tol ? { tol } : {}) }).u;
238
+ const run = solve(g, { scale, ke, fixed: spec.fixed, loads: active.map((c) => spec.loads[c].force), method: solver, backend, start: last && active.map((c) => last[c]), ...(tol ? { tol } : {}) }), solved = run.u;
235
239
  const u = spec.loads.map((_, c) => (active.includes(c) ? solved[active.indexOf(c)] : last?.[c] || null));
236
240
  last = u;
237
241
  // Compliance, and its gradient with respect to each cell's physical density: −p ρ^(p−1) (E − Emin) size · uₑᵀ kₑ uₑ
@@ -252,17 +256,209 @@ export function model(spec, { method, backend = jsBackend } = {}) {
252
256
  // Back through the projection, the overhang filter and the density filter to the design densities; kept and
253
257
  // avoided cells don't change
254
258
  for (let e = 0; e < cells; e++) { const s = passive[e] ? 0 : slope(made[e], beta); dc[e] *= s; dv[e] = s; }
255
- if (print) { print.adjoint(dc, back); dc.set(back); print.adjoint(dv, back); dv.set(back); }
256
- filter.adjoint(dc, back); dc.set(back);
257
- filter.adjoint(dv, back); dv.set(back);
259
+ const toDesign = (d) => { if (print) { print.adjoint(d, back); d.set(back); } filter.adjoint(d, back); d.set(back); };
260
+ toDesign(dc); toDesign(dv);
261
+ const stress = Ss ? stressLimits(u, active, run.again, multipliers || { lam: active.map(() => new Float64Array(cells * Ss.length)), mu: 1 }) : null;
258
262
  const cases = spec.loads.map((l, c) => {
259
263
  if (!u[c]) return { name: l.name, compliance: NaN, deflection: NaN, stiffness: NaN };
260
264
  const ci = jsBackend.dot(l.force, u[c]), deflection = l.size ? ci / l.size : 0;
261
265
  return { name: l.name, compliance: ci, deflection, stiffness: deflection ? l.size / deflection : Infinity };
262
266
  });
263
- return { compliance, dc, dv, u, cases };
267
+ if (stress) { for (let e = 0; e < cells; e++) stress.d[e] *= passive[e] ? 0 : slope(made[e], beta); toDesign(stress.d); }
268
+ return { compliance, dc, dv, u, cases, ...(stress ? { stress } : {}) };
264
269
  };
265
- return { physical, evaluate, cells, passive };
270
+ // Stress limits on every cell (Senhora, Giraldo-Londoño, Menezes, Paulino 2020): each cell's von Mises stress at its
271
+ // centre, as if solid, over the limit, less 1, times the cell's density, so an empty cell's limit vanishes. They're
272
+ // kept by an augmented Lagrangian: J = Σ (λ h + μ h² / 2) / N, h = max(g, −λ/μ), whose gradient takes one adjoint
273
+ // solve per load case. Every cell in the space is limited, those where supports and loads act too: a load on a
274
+ // point is a stress there, so give supports and loads some area (a hole's edge, a pad).
275
+ const rows = dim === 3 ? 6 : 3, Ss = spec.stress ? [centreStress(g.h, spec.material.nu, dim)] : null;
276
+ const limited = Uint8Array.from(passive, (p) => (p >= 0 ? 1 : 0));
277
+ const stressLimits = (u, active, again, { lam, mu }) => {
278
+ const P = Ss.length, N = Math.max(1, limited.reduce((a, b) => a + b, 0) * active.length * P), st = new Float64Array(rows), gr = new Float64Array(rows);
279
+ const d = new Float64Array(cells), h = active.map(() => new Float64Array(cells * P));
280
+ let J = 0, peak = 0;
281
+ const rhs = active.map((c, k) => {
282
+ const r = new Float64Array(g.dofs);
283
+ for (let e = 0; e < cells; e++) {
284
+ if (!limited[e]) continue;
285
+ const o = e * m;
286
+ Ss.forEach((S, pi) => {
287
+ for (let q = 0; q < rows; q++) { let t = 0; for (let a = 0; a < m; a++) t += S[q * m + a] * u[c][g.edof[o + a]]; st[q] = E * t; }
288
+ const vm = vonMises(st, dim, gr), over = vm / spec.stress, ge = phys[e] * (over - 1), j = e * P + pi, l = lam[k][j], he = Math.max(ge, -l / mu);
289
+ h[k][j] = he; J += (l * he + (mu / 2) * he * he) / N;
290
+ if (phys[e] >= 0.5) peak = Math.max(peak, vm);
291
+ if (ge <= -l / mu) return;
292
+ const w = (l + mu * he) / N, f = (w * phys[e] * E) / spec.stress;
293
+ d[e] += w * (over - 1);
294
+ for (let a = 0; a < m; a++) { let t = 0; for (let q = 0; q < rows; q++) t += S[q * m + a] * gr[q]; r[g.edof[o + a]] += f * t; }
295
+ });
296
+ }
297
+ return r;
298
+ });
299
+ const adjoint = again(rhs);
300
+ active.forEach((c, k) => {
301
+ const uc = u[c], lc = adjoint[k];
302
+ for (let e = 0; e < cells; e++) {
303
+ if (passive[e]) continue;
304
+ let t = 0;
305
+ const o = e * m;
306
+ for (let a = 0; a < m; a++) { let q = 0; for (let b = 0; b < m; b++) q += ke[a * m + b] * uc[g.edof[o + b]]; t += lc[g.edof[o + a]] * q; }
307
+ d[e] -= penal * Math.pow(phys[e], penal - 1) * (E - Emin) * size * t;
308
+ }
309
+ });
310
+ return { J, d, h, peak };
311
+ };
312
+ return { physical, evaluate, cells, passive, limits: Ss ? cells * Ss.length : 0 };
313
+ }
314
+
315
+ /**
316
+ * The method of moving asymptotes (Svanberg 1987, as his 2007 mmasub and subsolv): one step of minimising f0(x)
317
+ * subject to fi(x) ≤ 0, i = 1..m, xmin ≤ x ≤ xmax, from values and gradients at x. Each step solves a convex
318
+ * approximation, separable in x, by a primal-dual interior-point method. Keeps its asymptotes between steps.
319
+ * @param {{ n: number, m: number, xmin: Float64Array, xmax: Float64Array, move?: number }} o
320
+ */
321
+ export function mma({ n, m, xmin, xmax, move = 0.5 }) {
322
+ const low = new Float64Array(n), upp = new Float64Array(n), xold1 = new Float64Array(n), xold2 = new Float64Array(n);
323
+ const a0 = 1, a = new Float64Array(m), c = new Float64Array(m).fill(1000), d = new Float64Array(m).fill(1);
324
+ let iter = 0;
325
+ /**
326
+ * @param {Float64Array} x the design (changed in place to the next)
327
+ * @param {number} f0 @param {Float64Array} df0 @param {number[]} f @param {Float64Array[]} df
328
+ * @param {number} [stepMove] this step's move limit, a share of xmax − xmin
329
+ */
330
+ return function step(x, f0, df0, f, df, stepMove = move) {
331
+ iter++;
332
+ const raa0 = 1e-5, albefa = 0.1, asyinit = 0.5, asyincr = 1.2, asydecr = 0.7;
333
+ const alfa = new Float64Array(n), beta = new Float64Array(n), p0 = new Float64Array(n), q0 = new Float64Array(n);
334
+ const P = df.map(() => new Float64Array(n)), Q = df.map(() => new Float64Array(n)), b = new Float64Array(m);
335
+ for (let j = 0; j < n; j++) {
336
+ const span = xmax[j] - xmin[j];
337
+ if (iter <= 2) { low[j] = x[j] - asyinit * span; upp[j] = x[j] + asyinit * span; }
338
+ else {
339
+ const zzz = (x[j] - xold1[j]) * (xold1[j] - xold2[j]), f = zzz > 0 ? asyincr : zzz < 0 ? asydecr : 1;
340
+ low[j] = Math.min(x[j] - 0.01 * span, Math.max(x[j] - 10 * span, x[j] - f * (xold1[j] - low[j])));
341
+ upp[j] = Math.max(x[j] + 0.01 * span, Math.min(x[j] + 10 * span, x[j] + f * (upp[j] - xold1[j])));
342
+ }
343
+ alfa[j] = Math.max(low[j] + albefa * (x[j] - low[j]), x[j] - stepMove * span, xmin[j]);
344
+ beta[j] = Math.min(upp[j] - albefa * (upp[j] - x[j]), x[j] + stepMove * span, xmax[j]);
345
+ const inv = 1 / Math.max(span, 1e-5), ux2 = (upp[j] - x[j]) ** 2, xl2 = (x[j] - low[j]) ** 2;
346
+ const pp = Math.max(df0[j], 0), qq = Math.max(-df0[j], 0), pq = 0.001 * (pp + qq) + raa0 * inv;
347
+ p0[j] = (pp + pq) * ux2; q0[j] = (qq + pq) * xl2;
348
+ for (let i = 0; i < m; i++) {
349
+ const pi = Math.max(df[i][j], 0), qi = Math.max(-df[i][j], 0), pqi = 0.001 * (pi + qi) + raa0 * inv;
350
+ P[i][j] = (pi + pqi) * ux2; Q[i][j] = (qi + pqi) * xl2;
351
+ b[i] += P[i][j] / (upp[j] - x[j]) + Q[i][j] / (x[j] - low[j]);
352
+ }
353
+ }
354
+ for (let i = 0; i < m; i++) b[i] -= f[i];
355
+ xold2.set(xold1); xold1.set(x);
356
+ x.set(subsolve({ n, m, low, upp, alfa, beta, p0, q0, P, Q, a0, a, b, c, d }));
357
+ };
358
+ }
359
+
360
+ // The MMA subproblem, by a primal-dual Newton method with the barrier ε shrinking tenfold each round (Svanberg's subsolv)
361
+ function subsolve({ n, m, low, upp, alfa, beta, p0, q0, P, Q, a0, a, b, c, d }) {
362
+ let x = new Float64Array(n), xsi = new Float64Array(n), eta = new Float64Array(n);
363
+ let y = new Float64Array(m).fill(1), lam = new Float64Array(m).fill(1), mu = new Float64Array(m), s = new Float64Array(m).fill(1), z = 1, zet = 1;
364
+ for (let j = 0; j < n; j++) { x[j] = (alfa[j] + beta[j]) / 2; xsi[j] = Math.max(1, 1 / (x[j] - alfa[j])); eta[j] = Math.max(1, 1 / (beta[j] - x[j])); }
365
+ for (let i = 0; i < m; i++) mu[i] = Math.max(1, c[i] / 2);
366
+ const residual = (epsi, x, y, z, lam, xsi, eta, mu, zet, s) => {
367
+ let sum = 0, most = 0;
368
+ const add = (r) => { sum += r * r; most = Math.max(most, Math.abs(r)); };
369
+ const gvec = new Float64Array(m);
370
+ for (let j = 0; j < n; j++) {
371
+ const ux = upp[j] - x[j], xl = x[j] - low[j];
372
+ let plam = p0[j], qlam = q0[j];
373
+ for (let i = 0; i < m; i++) { plam += P[i][j] * lam[i]; qlam += Q[i][j] * lam[i]; gvec[i] += P[i][j] / ux + Q[i][j] / xl; }
374
+ add(plam / (ux * ux) - qlam / (xl * xl) - xsi[j] + eta[j]);
375
+ add(xsi[j] * (x[j] - alfa[j]) - epsi); add(eta[j] * (beta[j] - x[j]) - epsi);
376
+ }
377
+ let rez = a0 - zet;
378
+ for (let i = 0; i < m; i++) {
379
+ rez -= a[i] * lam[i];
380
+ add(c[i] + d[i] * y[i] - mu[i] - lam[i]); add(gvec[i] - a[i] * z - y[i] + s[i] - b[i]);
381
+ add(mu[i] * y[i] - epsi); add(s[i] * lam[i] - epsi);
382
+ }
383
+ add(rez); add(zet * z - epsi);
384
+ return [Math.sqrt(sum), most];
385
+ };
386
+ for (let epsi = 1; epsi > 1e-7; epsi *= 0.1) {
387
+ let [norm, most] = residual(epsi, x, y, z, lam, xsi, eta, mu, zet, s);
388
+ for (let it = 0; most > 0.9 * epsi && it < 200; it++) {
389
+ // The Newton step, reduced to m + 1 unknowns (dλ, dz)
390
+ const diagx = new Float64Array(n), delx = new Float64Array(n), gvec = new Float64Array(m), GG = Array.from({ length: m }, () => new Float64Array(n));
391
+ for (let j = 0; j < n; j++) {
392
+ const ux = upp[j] - x[j], xl = x[j] - low[j];
393
+ let plam = p0[j], qlam = q0[j];
394
+ for (let i = 0; i < m; i++) { plam += P[i][j] * lam[i]; qlam += Q[i][j] * lam[i]; gvec[i] += P[i][j] / ux + Q[i][j] / xl; GG[i][j] = P[i][j] / (ux * ux) - Q[i][j] / (xl * xl); }
395
+ delx[j] = plam / (ux * ux) - qlam / (xl * xl) - epsi / (x[j] - alfa[j]) + epsi / (beta[j] - x[j]);
396
+ diagx[j] = 2 * (plam / (ux * ux * ux) + qlam / (xl * xl * xl)) + xsi[j] / (x[j] - alfa[j]) + eta[j] / (beta[j] - x[j]);
397
+ }
398
+ const dely = new Float64Array(m), dellam = new Float64Array(m), diagy = new Float64Array(m), diaglamyi = new Float64Array(m);
399
+ let delz = a0 - epsi / z;
400
+ for (let i = 0; i < m; i++) {
401
+ dely[i] = c[i] + d[i] * y[i] - lam[i] - epsi / y[i];
402
+ delz -= a[i] * lam[i];
403
+ dellam[i] = gvec[i] - a[i] * z - y[i] - b[i] + epsi / lam[i];
404
+ diagy[i] = d[i] + mu[i] / y[i];
405
+ diaglamyi[i] = s[i] / lam[i] + 1 / diagy[i];
406
+ }
407
+ // [Alam a; aᵀ −ζ/z] [dλ; dz] = [bλ; δz]
408
+ const A = Array.from({ length: m + 1 }, () => new Float64Array(m + 2));
409
+ for (let i = 0; i < m; i++) {
410
+ let bl = dellam[i] + dely[i] / diagy[i];
411
+ for (let j = 0; j < n; j++) bl -= (GG[i][j] * delx[j]) / diagx[j];
412
+ for (let k = 0; k < m; k++) { let t = 0; for (let j = 0; j < n; j++) t += (GG[i][j] * GG[k][j]) / diagx[j]; A[i][k] = t + (i === k ? diaglamyi[i] : 0); }
413
+ A[i][m] = a[i]; A[m][i] = a[i]; A[i][m + 1] = bl;
414
+ }
415
+ A[m][m] = -zet / z; A[m][m + 1] = delz;
416
+ const sol = gauss(A), dlam = sol.slice(0, m), dz = sol[m];
417
+ const dx = new Float64Array(n), dy = new Float64Array(m), dxsi = new Float64Array(n), deta = new Float64Array(n), dmu = new Float64Array(m), ds = new Float64Array(m);
418
+ for (let j = 0; j < n; j++) {
419
+ let g = 0; for (let i = 0; i < m; i++) g += GG[i][j] * dlam[i];
420
+ dx[j] = -delx[j] / diagx[j] - g / diagx[j];
421
+ dxsi[j] = -xsi[j] + epsi / (x[j] - alfa[j]) - (xsi[j] * dx[j]) / (x[j] - alfa[j]);
422
+ deta[j] = -eta[j] + epsi / (beta[j] - x[j]) + (eta[j] * dx[j]) / (beta[j] - x[j]);
423
+ }
424
+ for (let i = 0; i < m; i++) {
425
+ dy[i] = -dely[i] / diagy[i] + dlam[i] / diagy[i];
426
+ dmu[i] = -mu[i] + epsi / y[i] - (mu[i] * dy[i]) / y[i];
427
+ ds[i] = -s[i] + epsi / lam[i] - (s[i] * dlam[i]) / lam[i];
428
+ }
429
+ const dzet = -zet + epsi / z - (zet * dz) / z;
430
+ // The longest step that keeps everything positive and x inside [α, β], then halved until the residual falls
431
+ let most2 = 1;
432
+ const ratio = (v, dv) => { for (let k = 0; k < v.length; k++) most2 = Math.max(most2, (-1.01 * dv[k]) / v[k]); };
433
+ ratio(y, dy); ratio([z], [dz]); ratio(lam, dlam); ratio(xsi, dxsi); ratio(eta, deta); ratio(mu, dmu); ratio([zet], [dzet]); ratio(s, ds);
434
+ for (let j = 0; j < n; j++) most2 = Math.max(most2, (-1.01 * dx[j]) / (x[j] - alfa[j]), (1.01 * dx[j]) / (beta[j] - x[j]));
435
+ let steg = 1 / most2, next, tries = 0, resinew = 2 * norm;
436
+ const at = (v, dv, t) => { const o = new Float64Array(v.length); for (let k = 0; k < v.length; k++) o[k] = v[k] + t * dv[k]; return o; };
437
+ while (resinew > norm && tries < 50) {
438
+ tries++;
439
+ next = [at(x, dx, steg), at(y, dy, steg), z + steg * dz, at(lam, dlam, steg), at(xsi, dxsi, steg), at(eta, deta, steg), at(mu, dmu, steg), zet + steg * dzet, at(s, ds, steg)];
440
+ [resinew, most] = residual(epsi, ...next);
441
+ steg /= 2;
442
+ }
443
+ [x, y, z, lam, xsi, eta, mu, zet, s] = next;
444
+ norm = resinew;
445
+ }
446
+ }
447
+ return x;
448
+ }
449
+
450
+ // A small dense system by Gaussian elimination with partial pivoting: A is the augmented matrix [M | rhs]
451
+ function gauss(A) {
452
+ const k = A.length;
453
+ for (let c = 0; c < k; c++) {
454
+ let p = c;
455
+ for (let r = c + 1; r < k; r++) if (Math.abs(A[r][c]) > Math.abs(A[p][c])) p = r;
456
+ [A[c], A[p]] = [A[p], A[c]];
457
+ for (let r = c + 1; r < k; r++) { const f = A[r][c] / A[c][c]; for (let q = c; q <= k; q++) A[r][q] -= f * A[c][q]; }
458
+ }
459
+ const x = new Array(k).fill(0);
460
+ for (let r = k - 1; r >= 0; r--) { let t = A[r][k]; for (let q = r + 1; q < k; q++) t -= A[r][q] * x[q]; x[r] = t / A[r][r]; }
461
+ return x;
266
462
  }
267
463
 
268
464
  /**
@@ -276,39 +472,70 @@ export function model(spec, { method, backend = jsBackend } = {}) {
276
472
  export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01, move = 0.2 } = {}) {
277
473
  const started = Date.now(), m = model(spec, { method, backend }), { cells, passive } = m;
278
474
  const inSpace = passive.reduce((s, p) => s + (p !== -2 ? 1 : 0), 0), kept = passive.reduce((s, p) => s + (p === 1 ? 1 : 0), 0);
279
- const free = passive.reduce((s, p) => s + (p === 0 ? 1 : 0), 0), target = spec.volume * inSpace;
280
- if (!(spec.volume > 0 && spec.volume <= 1)) throw new Error(`the volume is a share of the space, from 0 to 1 (got ${spec.volume})`);
281
- if (kept > target) throw new Error(`the keep regions alone fill ${fmt((kept / inSpace) * 100)}% of the space, more than the volume (${fmt(spec.volume * 100)}%): raise the volume`);
475
+ const free = passive.reduce((s, p) => s + (p === 0 ? 1 : 0), 0);
476
+ // A stress limit asks for the lightest layout that keeps to it; a volume, for the stiffest that fills it
477
+ const lightest = spec.stress > 0;
478
+ if (lightest && spec.volume != null) throw new Error('give a volume (the stiffest layout that fills it) or a stress limit (the lightest that keeps to it), not both');
479
+ if (!lightest && !(spec.volume > 0 && spec.volume <= 1)) throw new Error(`the volume is a share of the space, from 0 to 1 (got ${spec.volume})`);
480
+ const target = lightest ? 0 : spec.volume * inSpace;
481
+ if (!lightest && kept > target) throw new Error(`the keep regions alone fill ${fmt((kept / inSpace) * 100)}% of the space, more than the volume (${fmt(spec.volume * 100)}%): raise the volume`);
282
482
  if (!free) throw new Error('no free cells: the keep and avoid regions cover the whole space');
283
483
 
284
- const betaMax = spec.projection ? 16 : 1, fixedValue = (p) => (p === 1 ? 1 : 0);
484
+ const betaMax = spec.projection ? (lightest ? 8 : 16) : 1, fixedValue = (p) => (p === 1 ? 1 : 0);
285
485
  const x = new Float64Array(cells), xnew = new Float64Array(cells);
286
- for (let e = 0; e < cells; e++) x[e] = passive[e] ? fixedValue(passive[e]) : (target - kept) / free;
486
+ for (let e = 0; e < cells; e++) x[e] = passive[e] ? fixedValue(passive[e]) : lightest ? 0.5 : (target - kept) / free;
287
487
  const history = [];
288
- let step = 0, change = 1, converged = false, beta = 1, sinceBeta = 0;
488
+ // The lightest layout: the method of moving asymptotes on the material used plus the stress limits' augmented
489
+ // Lagrangian term, its multipliers raised every INNER steps (λ += μ h) and its penalty grown (μ × 1.1, at most 10⁴)
490
+ const INNER = 5, freeCells = Int32Array.from(Array.from(passive).flatMap((p, e) => (p ? [] : [e]))), n = freeCells.length;
491
+ const mmaStep = lightest ? mma({ n, m: 0, xmin: new Float64Array(n), xmax: new Float64Array(n).fill(1) }) : null;
492
+ const multipliers = lightest ? { lam: spec.loads.filter((l) => l.weight > 0).map(() => new Float64Array(m.limits)), mu: 10 } : undefined;
493
+ const xf = new Float64Array(n), pick = (d) => Float64Array.from(freeCells, (e) => d[e]);
494
+ let step = 0, change = 1, converged = false, beta = 1, sinceBeta = 0, peak = null;
289
495
  while (step < spec.steps) {
290
496
  step++; sinceBeta++;
291
- const { compliance, dc, dv } = m.evaluate(x, beta);
292
- history.push(compliance);
293
- // Optimality criteria: scale each cell by √(−dc/dv/λ), within the move limit, finding λ by bisection so the
294
- // physical densities fill exactly the volume
497
+ const { compliance, dc, dv, stress } = m.evaluate(x, beta, { multipliers });
295
498
  // A sharper projection magnifies each change, so the move limit shrinks with it (else the design flickers)
296
499
  const limit = move * Math.min(1, 2 / beta);
297
- let lo = 0, hi = 1e9;
298
- while ((hi - lo) / (hi + lo) > 1e-3) { // as the 88-line code
299
- const mid = (lo + hi) / 2;
300
- for (let e = 0; e < cells; e++) {
301
- if (passive[e]) { xnew[e] = fixedValue(passive[e]); continue; }
302
- const b = Math.sqrt(Math.max(0, -dc[e]) / Math.max(1e-30, dv[e]) / mid);
303
- xnew[e] = Math.max(0, Math.max(x[e] - limit, Math.min(1, Math.min(x[e] + limit, x[e] * b))));
500
+ if (lightest) {
501
+ const used = m.physical(x, beta).reduce((s, v, e) => s + (passive[e] !== -2 ? v : 0), 0) / inSpace, d = pick(stress.d), dvf = pick(dv);
502
+ history.push(used); peak = stress.peak;
503
+ // Done at full sharpness when the material used has stopped changing (within 0.2% over 100 steps) and the limit
504
+ // holds (within 2%): this design, as just analysed
505
+ if (beta >= betaMax && sinceBeta > 100 && Math.abs(history.at(-101) - used) <= 0.002 * used && peak <= spec.stress * 1.02) { converged = true; break; }
506
+ xf.set(pick(x));
507
+ mmaStep(xf, used + stress.J, dvf.map((v, k) => v / inSpace + d[k]), [], [], limit);
508
+ xnew.set(x);
509
+ freeCells.forEach((e, k) => { xnew[e] = xf[k]; });
510
+ if (step % INNER === 0) {
511
+ multipliers.lam.forEach((l, k) => { for (let j = 0; j < l.length; j++) l[j] += multipliers.mu * stress.h[k][j]; });
512
+ multipliers.mu = Math.min(1.1 * multipliers.mu, 1e4);
513
+ }
514
+ } else {
515
+ history.push(compliance);
516
+ // Optimality criteria: scale each cell by √(−dc/dv/λ), within the move limit, finding λ by bisection so the
517
+ // physical densities fill exactly the volume
518
+ let lo = 0, hi = 1e9;
519
+ while ((hi - lo) / (hi + lo) > 1e-3) { // as the 88-line code
520
+ const mid = (lo + hi) / 2;
521
+ for (let e = 0; e < cells; e++) {
522
+ if (passive[e]) { xnew[e] = fixedValue(passive[e]); continue; }
523
+ const b = Math.sqrt(Math.max(0, -dc[e]) / Math.max(1e-30, dv[e]) / mid);
524
+ xnew[e] = Math.max(0, Math.max(x[e] - limit, Math.min(1, Math.min(x[e] + limit, x[e] * b))));
525
+ }
526
+ const filled = m.physical(xnew, beta).reduce((s, v) => s + v, 0);
527
+ if (filled > target) lo = mid; else hi = mid;
304
528
  }
305
- const filled = m.physical(xnew, beta).reduce((s, v) => s + v, 0);
306
- if (filled > target) lo = mid; else hi = mid;
307
529
  }
308
530
  change = 0;
309
531
  for (let e = 0; e < cells; e++) change = Math.max(change, Math.abs(xnew[e] - x[e]));
310
532
  x.set(xnew);
311
- onStep?.({ step, steps: spec.steps, compliance, change, beta, density: m.physical(x, beta) });
533
+ onStep?.({ step, steps: spec.steps, compliance, change, beta, density: m.physical(x, beta), ...(lightest ? { stress: peak, volume: history.at(-1) } : {}) });
534
+ if (lightest) {
535
+ // Sharper every 25 rounds of the multipliers
536
+ if (beta < betaMax && sinceBeta >= 25 * INNER) { beta *= 2; sinceBeta = 0; }
537
+ continue;
538
+ }
312
539
  // Sharpen: double the projection's steepness when the design settles (or every 50 steps), until it's at its sharpest
313
540
  if (beta < betaMax && (change < tol || sinceBeta >= 50)) { beta *= 2; sinceBeta = 0; continue; }
314
541
  // Done when nothing moves, or at full sharpness the compliance has stopped improving (within 0.1% over 10 steps)
@@ -318,7 +545,7 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
318
545
  // The final design, analysed as it is
319
546
  const final = m.evaluate(x, beta, { all: true }), phys = Float64Array.from(m.physical(x, beta));
320
547
  return {
321
- density: phys, compliance: final.compliance, cases: final.cases,
548
+ density: phys, compliance: final.compliance, cases: final.cases, ...(final.stress ? { stress: { peak: final.stress.peak, limit: spec.stress } } : {}),
322
549
  volume: phys.reduce((s, v, e) => s + (passive[e] !== -2 ? v : 0), 0) / inSpace, steps: step, converged, history, seconds: (Date.now() - started) / 1000,
323
550
  };
324
551
  }