@rulecad/topopt 0.2.1 → 0.2.3
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 +46 -0
- package/package.json +2 -2
- package/topopt.d.mts +21 -1
- package/topopt.mjs +271 -37
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
|
+

|
|
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.
|
|
3
|
+
"version": "0.2.3",
|
|
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.
|
|
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".
|
|
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
|
|
|
@@ -54,14 +58,21 @@ export function discretise(p) {
|
|
|
54
58
|
const space = [p.space].flat(), keep = p.keep || [], avoid = p.avoid || [], dim = dimension(space[0]);
|
|
55
59
|
if (!(p.cell > 0)) throw new Error('the cell size must be more than 0 mm');
|
|
56
60
|
for (const r of [...space, ...keep, ...avoid]) if (dimension(r) !== dim) throw new Error(`a ${dimension(r)}D region in a ${dim}D problem: give every region ${dim === 3 ? 'x, y and z' : 'x and y'}`);
|
|
57
|
-
const all = [...space, ...keep].map(bounds), lo = [], n = [];
|
|
61
|
+
const all = [...space, ...keep].map(bounds), lo = [], hi = [], n = [];
|
|
58
62
|
for (let a = 0; a < dim; a++) {
|
|
59
|
-
lo.push(Math.min(...all.map((b) => b[a])));
|
|
60
|
-
n.push(Math.max(1, Math.round((
|
|
63
|
+
lo.push(Math.min(...all.map((b) => b[a]))); hi.push(Math.max(...all.map((b) => b[dim + a])));
|
|
64
|
+
n.push(Math.max(1, Math.round((hi[a] - lo[a]) / p.cell)));
|
|
61
65
|
}
|
|
62
66
|
if (dim === 3) { // whole numbers of 2, 4 or 8 cells along every side, for multigrid
|
|
63
|
-
const q = Math.min(...n) >= 16 ? 8 : Math.min(...n) >= 8 ? 4 : 2;
|
|
64
|
-
for (let a = 0; a < 3; a++)
|
|
67
|
+
const q = Math.min(...n) >= 16 ? 8 : Math.min(...n) >= 8 ? 4 : 2, build = /^([+-])([xyz])$/.exec(p.overhang ?? '');
|
|
68
|
+
for (let a = 0; a < 3; a++) {
|
|
69
|
+
n[a] = Math.ceil(n[a] / q) * q;
|
|
70
|
+
// The padding split evenly round the space, so a round space sits in the middle of its grid (all on one side, a
|
|
71
|
+
// round wall ran along the grid's edge there and drew as flat blocks). Along the build direction the bed's side
|
|
72
|
+
// stays flush, so the first layer sits on the bed.
|
|
73
|
+
const pad = n[a] * p.cell - (hi[a] - lo[a]);
|
|
74
|
+
lo[a] -= build && 'xyz'.indexOf(build[2]) === a ? (build[1] === '-' ? pad : 0) : pad / 2;
|
|
75
|
+
}
|
|
65
76
|
}
|
|
66
77
|
const size = dim === 3 ? { nx: n[0], ny: n[1], nz: n[2], h: p.cell } : { nx: n[0], ny: n[1], h: p.cell };
|
|
67
78
|
const g = makeGrid(size), origin = lo, h = p.cell;
|
|
@@ -103,8 +114,8 @@ export function discretise(p) {
|
|
|
103
114
|
return {
|
|
104
115
|
grid: size, origin, passive, fixed, loads,
|
|
105
116
|
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 } : {}),
|
|
117
|
+
filter: p.filter ?? p.cell * 1.5, penal: p.penal ?? 3, projection: p.projection ?? true, steps: p.steps ?? (p.stress ? 1000 : 300),
|
|
118
|
+
...(p.overhang ? { overhang: p.overhang } : {}), ...(p.stress ? { stress: p.stress } : {}),
|
|
108
119
|
regions: { keep, avoid },
|
|
109
120
|
};
|
|
110
121
|
}
|
|
@@ -227,11 +238,11 @@ export function model(spec, { method, backend = jsBackend } = {}) {
|
|
|
227
238
|
};
|
|
228
239
|
let last = null;
|
|
229
240
|
// 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 } = {}) => {
|
|
241
|
+
const evaluate = (x, beta, { all = false, multipliers } = {}) => {
|
|
231
242
|
physical(x, beta);
|
|
232
243
|
for (let e = 0; e < cells; e++) scale[e] = size * (Emin + Math.pow(phys[e], penal) * (E - Emin));
|
|
233
244
|
const active = spec.loads.map((l, c) => (all || l.weight > 0 ? c : -1)).filter((c) => c >= 0);
|
|
234
|
-
const
|
|
245
|
+
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
246
|
const u = spec.loads.map((_, c) => (active.includes(c) ? solved[active.indexOf(c)] : last?.[c] || null));
|
|
236
247
|
last = u;
|
|
237
248
|
// Compliance, and its gradient with respect to each cell's physical density: −p ρ^(p−1) (E − Emin) size · uₑᵀ kₑ uₑ
|
|
@@ -252,17 +263,209 @@ export function model(spec, { method, backend = jsBackend } = {}) {
|
|
|
252
263
|
// Back through the projection, the overhang filter and the density filter to the design densities; kept and
|
|
253
264
|
// avoided cells don't change
|
|
254
265
|
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(
|
|
256
|
-
|
|
257
|
-
|
|
266
|
+
const toDesign = (d) => { if (print) { print.adjoint(d, back); d.set(back); } filter.adjoint(d, back); d.set(back); };
|
|
267
|
+
toDesign(dc); toDesign(dv);
|
|
268
|
+
const stress = Ss ? stressLimits(u, active, run.again, multipliers || { lam: active.map(() => new Float64Array(cells * Ss.length)), mu: 1 }) : null;
|
|
258
269
|
const cases = spec.loads.map((l, c) => {
|
|
259
270
|
if (!u[c]) return { name: l.name, compliance: NaN, deflection: NaN, stiffness: NaN };
|
|
260
271
|
const ci = jsBackend.dot(l.force, u[c]), deflection = l.size ? ci / l.size : 0;
|
|
261
272
|
return { name: l.name, compliance: ci, deflection, stiffness: deflection ? l.size / deflection : Infinity };
|
|
262
273
|
});
|
|
263
|
-
|
|
274
|
+
if (stress) { for (let e = 0; e < cells; e++) stress.d[e] *= passive[e] ? 0 : slope(made[e], beta); toDesign(stress.d); }
|
|
275
|
+
return { compliance, dc, dv, u, cases, ...(stress ? { stress } : {}) };
|
|
276
|
+
};
|
|
277
|
+
// Stress limits on every cell (Senhora, Giraldo-Londoño, Menezes, Paulino 2020): each cell's von Mises stress at its
|
|
278
|
+
// centre, as if solid, over the limit, less 1, times the cell's density, so an empty cell's limit vanishes. They're
|
|
279
|
+
// kept by an augmented Lagrangian: J = Σ (λ h + μ h² / 2) / N, h = max(g, −λ/μ), whose gradient takes one adjoint
|
|
280
|
+
// solve per load case. Every cell in the space is limited, those where supports and loads act too: a load on a
|
|
281
|
+
// point is a stress there, so give supports and loads some area (a hole's edge, a pad).
|
|
282
|
+
const rows = dim === 3 ? 6 : 3, Ss = spec.stress ? [centreStress(g.h, spec.material.nu, dim)] : null;
|
|
283
|
+
const limited = Uint8Array.from(passive, (p) => (p >= 0 ? 1 : 0));
|
|
284
|
+
const stressLimits = (u, active, again, { lam, mu }) => {
|
|
285
|
+
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);
|
|
286
|
+
const d = new Float64Array(cells), h = active.map(() => new Float64Array(cells * P));
|
|
287
|
+
let J = 0, peak = 0;
|
|
288
|
+
const rhs = active.map((c, k) => {
|
|
289
|
+
const r = new Float64Array(g.dofs);
|
|
290
|
+
for (let e = 0; e < cells; e++) {
|
|
291
|
+
if (!limited[e]) continue;
|
|
292
|
+
const o = e * m;
|
|
293
|
+
Ss.forEach((S, pi) => {
|
|
294
|
+
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; }
|
|
295
|
+
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);
|
|
296
|
+
h[k][j] = he; J += (l * he + (mu / 2) * he * he) / N;
|
|
297
|
+
if (phys[e] >= 0.5) peak = Math.max(peak, vm);
|
|
298
|
+
if (ge <= -l / mu) return;
|
|
299
|
+
const w = (l + mu * he) / N, f = (w * phys[e] * E) / spec.stress;
|
|
300
|
+
d[e] += w * (over - 1);
|
|
301
|
+
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; }
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
return r;
|
|
305
|
+
});
|
|
306
|
+
const adjoint = again(rhs);
|
|
307
|
+
active.forEach((c, k) => {
|
|
308
|
+
const uc = u[c], lc = adjoint[k];
|
|
309
|
+
for (let e = 0; e < cells; e++) {
|
|
310
|
+
if (passive[e]) continue;
|
|
311
|
+
let t = 0;
|
|
312
|
+
const o = e * m;
|
|
313
|
+
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; }
|
|
314
|
+
d[e] -= penal * Math.pow(phys[e], penal - 1) * (E - Emin) * size * t;
|
|
315
|
+
}
|
|
316
|
+
});
|
|
317
|
+
return { J, d, h, peak };
|
|
264
318
|
};
|
|
265
|
-
return { physical, evaluate, cells, passive };
|
|
319
|
+
return { physical, evaluate, cells, passive, limits: Ss ? cells * Ss.length : 0 };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* The method of moving asymptotes (Svanberg 1987, as his 2007 mmasub and subsolv): one step of minimising f0(x)
|
|
324
|
+
* subject to fi(x) ≤ 0, i = 1..m, xmin ≤ x ≤ xmax, from values and gradients at x. Each step solves a convex
|
|
325
|
+
* approximation, separable in x, by a primal-dual interior-point method. Keeps its asymptotes between steps.
|
|
326
|
+
* @param {{ n: number, m: number, xmin: Float64Array, xmax: Float64Array, move?: number }} o
|
|
327
|
+
*/
|
|
328
|
+
export function mma({ n, m, xmin, xmax, move = 0.5 }) {
|
|
329
|
+
const low = new Float64Array(n), upp = new Float64Array(n), xold1 = new Float64Array(n), xold2 = new Float64Array(n);
|
|
330
|
+
const a0 = 1, a = new Float64Array(m), c = new Float64Array(m).fill(1000), d = new Float64Array(m).fill(1);
|
|
331
|
+
let iter = 0;
|
|
332
|
+
/**
|
|
333
|
+
* @param {Float64Array} x the design (changed in place to the next)
|
|
334
|
+
* @param {number} f0 @param {Float64Array} df0 @param {number[]} f @param {Float64Array[]} df
|
|
335
|
+
* @param {number} [stepMove] this step's move limit, a share of xmax − xmin
|
|
336
|
+
*/
|
|
337
|
+
return function step(x, f0, df0, f, df, stepMove = move) {
|
|
338
|
+
iter++;
|
|
339
|
+
const raa0 = 1e-5, albefa = 0.1, asyinit = 0.5, asyincr = 1.2, asydecr = 0.7;
|
|
340
|
+
const alfa = new Float64Array(n), beta = new Float64Array(n), p0 = new Float64Array(n), q0 = new Float64Array(n);
|
|
341
|
+
const P = df.map(() => new Float64Array(n)), Q = df.map(() => new Float64Array(n)), b = new Float64Array(m);
|
|
342
|
+
for (let j = 0; j < n; j++) {
|
|
343
|
+
const span = xmax[j] - xmin[j];
|
|
344
|
+
if (iter <= 2) { low[j] = x[j] - asyinit * span; upp[j] = x[j] + asyinit * span; }
|
|
345
|
+
else {
|
|
346
|
+
const zzz = (x[j] - xold1[j]) * (xold1[j] - xold2[j]), f = zzz > 0 ? asyincr : zzz < 0 ? asydecr : 1;
|
|
347
|
+
low[j] = Math.min(x[j] - 0.01 * span, Math.max(x[j] - 10 * span, x[j] - f * (xold1[j] - low[j])));
|
|
348
|
+
upp[j] = Math.max(x[j] + 0.01 * span, Math.min(x[j] + 10 * span, x[j] + f * (upp[j] - xold1[j])));
|
|
349
|
+
}
|
|
350
|
+
alfa[j] = Math.max(low[j] + albefa * (x[j] - low[j]), x[j] - stepMove * span, xmin[j]);
|
|
351
|
+
beta[j] = Math.min(upp[j] - albefa * (upp[j] - x[j]), x[j] + stepMove * span, xmax[j]);
|
|
352
|
+
const inv = 1 / Math.max(span, 1e-5), ux2 = (upp[j] - x[j]) ** 2, xl2 = (x[j] - low[j]) ** 2;
|
|
353
|
+
const pp = Math.max(df0[j], 0), qq = Math.max(-df0[j], 0), pq = 0.001 * (pp + qq) + raa0 * inv;
|
|
354
|
+
p0[j] = (pp + pq) * ux2; q0[j] = (qq + pq) * xl2;
|
|
355
|
+
for (let i = 0; i < m; i++) {
|
|
356
|
+
const pi = Math.max(df[i][j], 0), qi = Math.max(-df[i][j], 0), pqi = 0.001 * (pi + qi) + raa0 * inv;
|
|
357
|
+
P[i][j] = (pi + pqi) * ux2; Q[i][j] = (qi + pqi) * xl2;
|
|
358
|
+
b[i] += P[i][j] / (upp[j] - x[j]) + Q[i][j] / (x[j] - low[j]);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
for (let i = 0; i < m; i++) b[i] -= f[i];
|
|
362
|
+
xold2.set(xold1); xold1.set(x);
|
|
363
|
+
x.set(subsolve({ n, m, low, upp, alfa, beta, p0, q0, P, Q, a0, a, b, c, d }));
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// The MMA subproblem, by a primal-dual Newton method with the barrier ε shrinking tenfold each round (Svanberg's subsolv)
|
|
368
|
+
function subsolve({ n, m, low, upp, alfa, beta, p0, q0, P, Q, a0, a, b, c, d }) {
|
|
369
|
+
let x = new Float64Array(n), xsi = new Float64Array(n), eta = new Float64Array(n);
|
|
370
|
+
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;
|
|
371
|
+
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])); }
|
|
372
|
+
for (let i = 0; i < m; i++) mu[i] = Math.max(1, c[i] / 2);
|
|
373
|
+
const residual = (epsi, x, y, z, lam, xsi, eta, mu, zet, s) => {
|
|
374
|
+
let sum = 0, most = 0;
|
|
375
|
+
const add = (r) => { sum += r * r; most = Math.max(most, Math.abs(r)); };
|
|
376
|
+
const gvec = new Float64Array(m);
|
|
377
|
+
for (let j = 0; j < n; j++) {
|
|
378
|
+
const ux = upp[j] - x[j], xl = x[j] - low[j];
|
|
379
|
+
let plam = p0[j], qlam = q0[j];
|
|
380
|
+
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; }
|
|
381
|
+
add(plam / (ux * ux) - qlam / (xl * xl) - xsi[j] + eta[j]);
|
|
382
|
+
add(xsi[j] * (x[j] - alfa[j]) - epsi); add(eta[j] * (beta[j] - x[j]) - epsi);
|
|
383
|
+
}
|
|
384
|
+
let rez = a0 - zet;
|
|
385
|
+
for (let i = 0; i < m; i++) {
|
|
386
|
+
rez -= a[i] * lam[i];
|
|
387
|
+
add(c[i] + d[i] * y[i] - mu[i] - lam[i]); add(gvec[i] - a[i] * z - y[i] + s[i] - b[i]);
|
|
388
|
+
add(mu[i] * y[i] - epsi); add(s[i] * lam[i] - epsi);
|
|
389
|
+
}
|
|
390
|
+
add(rez); add(zet * z - epsi);
|
|
391
|
+
return [Math.sqrt(sum), most];
|
|
392
|
+
};
|
|
393
|
+
for (let epsi = 1; epsi > 1e-7; epsi *= 0.1) {
|
|
394
|
+
let [norm, most] = residual(epsi, x, y, z, lam, xsi, eta, mu, zet, s);
|
|
395
|
+
for (let it = 0; most > 0.9 * epsi && it < 200; it++) {
|
|
396
|
+
// The Newton step, reduced to m + 1 unknowns (dλ, dz)
|
|
397
|
+
const diagx = new Float64Array(n), delx = new Float64Array(n), gvec = new Float64Array(m), GG = Array.from({ length: m }, () => new Float64Array(n));
|
|
398
|
+
for (let j = 0; j < n; j++) {
|
|
399
|
+
const ux = upp[j] - x[j], xl = x[j] - low[j];
|
|
400
|
+
let plam = p0[j], qlam = q0[j];
|
|
401
|
+
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); }
|
|
402
|
+
delx[j] = plam / (ux * ux) - qlam / (xl * xl) - epsi / (x[j] - alfa[j]) + epsi / (beta[j] - x[j]);
|
|
403
|
+
diagx[j] = 2 * (plam / (ux * ux * ux) + qlam / (xl * xl * xl)) + xsi[j] / (x[j] - alfa[j]) + eta[j] / (beta[j] - x[j]);
|
|
404
|
+
}
|
|
405
|
+
const dely = new Float64Array(m), dellam = new Float64Array(m), diagy = new Float64Array(m), diaglamyi = new Float64Array(m);
|
|
406
|
+
let delz = a0 - epsi / z;
|
|
407
|
+
for (let i = 0; i < m; i++) {
|
|
408
|
+
dely[i] = c[i] + d[i] * y[i] - lam[i] - epsi / y[i];
|
|
409
|
+
delz -= a[i] * lam[i];
|
|
410
|
+
dellam[i] = gvec[i] - a[i] * z - y[i] - b[i] + epsi / lam[i];
|
|
411
|
+
diagy[i] = d[i] + mu[i] / y[i];
|
|
412
|
+
diaglamyi[i] = s[i] / lam[i] + 1 / diagy[i];
|
|
413
|
+
}
|
|
414
|
+
// [Alam a; aᵀ −ζ/z] [dλ; dz] = [bλ; δz]
|
|
415
|
+
const A = Array.from({ length: m + 1 }, () => new Float64Array(m + 2));
|
|
416
|
+
for (let i = 0; i < m; i++) {
|
|
417
|
+
let bl = dellam[i] + dely[i] / diagy[i];
|
|
418
|
+
for (let j = 0; j < n; j++) bl -= (GG[i][j] * delx[j]) / diagx[j];
|
|
419
|
+
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); }
|
|
420
|
+
A[i][m] = a[i]; A[m][i] = a[i]; A[i][m + 1] = bl;
|
|
421
|
+
}
|
|
422
|
+
A[m][m] = -zet / z; A[m][m + 1] = delz;
|
|
423
|
+
const sol = gauss(A), dlam = sol.slice(0, m), dz = sol[m];
|
|
424
|
+
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);
|
|
425
|
+
for (let j = 0; j < n; j++) {
|
|
426
|
+
let g = 0; for (let i = 0; i < m; i++) g += GG[i][j] * dlam[i];
|
|
427
|
+
dx[j] = -delx[j] / diagx[j] - g / diagx[j];
|
|
428
|
+
dxsi[j] = -xsi[j] + epsi / (x[j] - alfa[j]) - (xsi[j] * dx[j]) / (x[j] - alfa[j]);
|
|
429
|
+
deta[j] = -eta[j] + epsi / (beta[j] - x[j]) + (eta[j] * dx[j]) / (beta[j] - x[j]);
|
|
430
|
+
}
|
|
431
|
+
for (let i = 0; i < m; i++) {
|
|
432
|
+
dy[i] = -dely[i] / diagy[i] + dlam[i] / diagy[i];
|
|
433
|
+
dmu[i] = -mu[i] + epsi / y[i] - (mu[i] * dy[i]) / y[i];
|
|
434
|
+
ds[i] = -s[i] + epsi / lam[i] - (s[i] * dlam[i]) / lam[i];
|
|
435
|
+
}
|
|
436
|
+
const dzet = -zet + epsi / z - (zet * dz) / z;
|
|
437
|
+
// The longest step that keeps everything positive and x inside [α, β], then halved until the residual falls
|
|
438
|
+
let most2 = 1;
|
|
439
|
+
const ratio = (v, dv) => { for (let k = 0; k < v.length; k++) most2 = Math.max(most2, (-1.01 * dv[k]) / v[k]); };
|
|
440
|
+
ratio(y, dy); ratio([z], [dz]); ratio(lam, dlam); ratio(xsi, dxsi); ratio(eta, deta); ratio(mu, dmu); ratio([zet], [dzet]); ratio(s, ds);
|
|
441
|
+
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]));
|
|
442
|
+
let steg = 1 / most2, next, tries = 0, resinew = 2 * norm;
|
|
443
|
+
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; };
|
|
444
|
+
while (resinew > norm && tries < 50) {
|
|
445
|
+
tries++;
|
|
446
|
+
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)];
|
|
447
|
+
[resinew, most] = residual(epsi, ...next);
|
|
448
|
+
steg /= 2;
|
|
449
|
+
}
|
|
450
|
+
[x, y, z, lam, xsi, eta, mu, zet, s] = next;
|
|
451
|
+
norm = resinew;
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
return x;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// A small dense system by Gaussian elimination with partial pivoting: A is the augmented matrix [M | rhs]
|
|
458
|
+
function gauss(A) {
|
|
459
|
+
const k = A.length;
|
|
460
|
+
for (let c = 0; c < k; c++) {
|
|
461
|
+
let p = c;
|
|
462
|
+
for (let r = c + 1; r < k; r++) if (Math.abs(A[r][c]) > Math.abs(A[p][c])) p = r;
|
|
463
|
+
[A[c], A[p]] = [A[p], A[c]];
|
|
464
|
+
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]; }
|
|
465
|
+
}
|
|
466
|
+
const x = new Array(k).fill(0);
|
|
467
|
+
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]; }
|
|
468
|
+
return x;
|
|
266
469
|
}
|
|
267
470
|
|
|
268
471
|
/**
|
|
@@ -276,39 +479,70 @@ export function model(spec, { method, backend = jsBackend } = {}) {
|
|
|
276
479
|
export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01, move = 0.2 } = {}) {
|
|
277
480
|
const started = Date.now(), m = model(spec, { method, backend }), { cells, passive } = m;
|
|
278
481
|
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)
|
|
280
|
-
|
|
281
|
-
|
|
482
|
+
const free = passive.reduce((s, p) => s + (p === 0 ? 1 : 0), 0);
|
|
483
|
+
// A stress limit asks for the lightest layout that keeps to it; a volume, for the stiffest that fills it
|
|
484
|
+
const lightest = spec.stress > 0;
|
|
485
|
+
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');
|
|
486
|
+
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})`);
|
|
487
|
+
const target = lightest ? 0 : spec.volume * inSpace;
|
|
488
|
+
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
489
|
if (!free) throw new Error('no free cells: the keep and avoid regions cover the whole space');
|
|
283
490
|
|
|
284
|
-
const betaMax = spec.projection ? 16 : 1, fixedValue = (p) => (p === 1 ? 1 : 0);
|
|
491
|
+
const betaMax = spec.projection ? (lightest ? 8 : 16) : 1, fixedValue = (p) => (p === 1 ? 1 : 0);
|
|
285
492
|
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;
|
|
493
|
+
for (let e = 0; e < cells; e++) x[e] = passive[e] ? fixedValue(passive[e]) : lightest ? 0.5 : (target - kept) / free;
|
|
287
494
|
const history = [];
|
|
288
|
-
|
|
495
|
+
// The lightest layout: the method of moving asymptotes on the material used plus the stress limits' augmented
|
|
496
|
+
// Lagrangian term, its multipliers raised every INNER steps (λ += μ h) and its penalty grown (μ × 1.1, at most 10⁴)
|
|
497
|
+
const INNER = 5, freeCells = Int32Array.from(Array.from(passive).flatMap((p, e) => (p ? [] : [e]))), n = freeCells.length;
|
|
498
|
+
const mmaStep = lightest ? mma({ n, m: 0, xmin: new Float64Array(n), xmax: new Float64Array(n).fill(1) }) : null;
|
|
499
|
+
const multipliers = lightest ? { lam: spec.loads.filter((l) => l.weight > 0).map(() => new Float64Array(m.limits)), mu: 10 } : undefined;
|
|
500
|
+
const xf = new Float64Array(n), pick = (d) => Float64Array.from(freeCells, (e) => d[e]);
|
|
501
|
+
let step = 0, change = 1, converged = false, beta = 1, sinceBeta = 0, peak = null;
|
|
289
502
|
while (step < spec.steps) {
|
|
290
503
|
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
|
|
504
|
+
const { compliance, dc, dv, stress } = m.evaluate(x, beta, { multipliers });
|
|
295
505
|
// A sharper projection magnifies each change, so the move limit shrinks with it (else the design flickers)
|
|
296
506
|
const limit = move * Math.min(1, 2 / beta);
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
507
|
+
if (lightest) {
|
|
508
|
+
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);
|
|
509
|
+
history.push(used); peak = stress.peak;
|
|
510
|
+
// Done at full sharpness when the material used has stopped changing (within 0.2% over 100 steps) and the limit
|
|
511
|
+
// holds (within 2%): this design, as just analysed
|
|
512
|
+
if (beta >= betaMax && sinceBeta > 100 && Math.abs(history.at(-101) - used) <= 0.002 * used && peak <= spec.stress * 1.02) { converged = true; break; }
|
|
513
|
+
xf.set(pick(x));
|
|
514
|
+
mmaStep(xf, used + stress.J, dvf.map((v, k) => v / inSpace + d[k]), [], [], limit);
|
|
515
|
+
xnew.set(x);
|
|
516
|
+
freeCells.forEach((e, k) => { xnew[e] = xf[k]; });
|
|
517
|
+
if (step % INNER === 0) {
|
|
518
|
+
multipliers.lam.forEach((l, k) => { for (let j = 0; j < l.length; j++) l[j] += multipliers.mu * stress.h[k][j]; });
|
|
519
|
+
multipliers.mu = Math.min(1.1 * multipliers.mu, 1e4);
|
|
520
|
+
}
|
|
521
|
+
} else {
|
|
522
|
+
history.push(compliance);
|
|
523
|
+
// Optimality criteria: scale each cell by √(−dc/dv/λ), within the move limit, finding λ by bisection so the
|
|
524
|
+
// physical densities fill exactly the volume
|
|
525
|
+
let lo = 0, hi = 1e9;
|
|
526
|
+
while ((hi - lo) / (hi + lo) > 1e-3) { // as the 88-line code
|
|
527
|
+
const mid = (lo + hi) / 2;
|
|
528
|
+
for (let e = 0; e < cells; e++) {
|
|
529
|
+
if (passive[e]) { xnew[e] = fixedValue(passive[e]); continue; }
|
|
530
|
+
const b = Math.sqrt(Math.max(0, -dc[e]) / Math.max(1e-30, dv[e]) / mid);
|
|
531
|
+
xnew[e] = Math.max(0, Math.max(x[e] - limit, Math.min(1, Math.min(x[e] + limit, x[e] * b))));
|
|
532
|
+
}
|
|
533
|
+
const filled = m.physical(xnew, beta).reduce((s, v) => s + v, 0);
|
|
534
|
+
if (filled > target) lo = mid; else hi = mid;
|
|
304
535
|
}
|
|
305
|
-
const filled = m.physical(xnew, beta).reduce((s, v) => s + v, 0);
|
|
306
|
-
if (filled > target) lo = mid; else hi = mid;
|
|
307
536
|
}
|
|
308
537
|
change = 0;
|
|
309
538
|
for (let e = 0; e < cells; e++) change = Math.max(change, Math.abs(xnew[e] - x[e]));
|
|
310
539
|
x.set(xnew);
|
|
311
|
-
onStep?.({ step, steps: spec.steps, compliance, change, beta, density: m.physical(x, beta) });
|
|
540
|
+
onStep?.({ step, steps: spec.steps, compliance, change, beta, density: m.physical(x, beta), ...(lightest ? { stress: peak, volume: history.at(-1) } : {}) });
|
|
541
|
+
if (lightest) {
|
|
542
|
+
// Sharper every 25 rounds of the multipliers
|
|
543
|
+
if (beta < betaMax && sinceBeta >= 25 * INNER) { beta *= 2; sinceBeta = 0; }
|
|
544
|
+
continue;
|
|
545
|
+
}
|
|
312
546
|
// Sharpen: double the projection's steepness when the design settles (or every 50 steps), until it's at its sharpest
|
|
313
547
|
if (beta < betaMax && (change < tol || sinceBeta >= 50)) { beta *= 2; sinceBeta = 0; continue; }
|
|
314
548
|
// Done when nothing moves, or at full sharpness the compliance has stopped improving (within 0.1% over 10 steps)
|
|
@@ -318,7 +552,7 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
|
|
|
318
552
|
// The final design, analysed as it is
|
|
319
553
|
const final = m.evaluate(x, beta, { all: true }), phys = Float64Array.from(m.physical(x, beta));
|
|
320
554
|
return {
|
|
321
|
-
density: phys, compliance: final.compliance, cases: final.cases,
|
|
555
|
+
density: phys, compliance: final.compliance, cases: final.cases, ...(final.stress ? { stress: { peak: final.stress.peak, limit: spec.stress } } : {}),
|
|
322
556
|
volume: phys.reduce((s, v, e) => s + (passive[e] !== -2 ? v : 0), 0) / inSpace, steps: step, converged, history, seconds: (Date.now() - started) / 1000,
|
|
323
557
|
};
|
|
324
558
|
}
|