@rulecad/topopt 0.2.0 → 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 +49 -3
- package/package.json +2 -2
- package/topopt.d.mts +33 -7
- package/topopt.mjs +303 -41
package/README.md
CHANGED
|
@@ -25,8 +25,8 @@ const loops = outlines(spec.grid, result.density, spec.origin); // closed loop
|
|
|
25
25
|
### In 3D
|
|
26
26
|
|
|
27
27
|
Regions take a z. A region can be a box (`size`), a cylinder (`r`, `length`, `axis`), a ball (`r`), or a closed
|
|
28
|
-
triangle mesh (`triangles`). A cylinder
|
|
29
|
-
|
|
28
|
+
triangle mesh (`triangles`). A cylinder can be a teardrop: `teardrop: '-z'` for a boss, `'+z'` for a hole, or any
|
|
29
|
+
direction across its axis. It gets a 45° point that way, so it prints without support. Supports and loads can be any region.
|
|
30
30
|
|
|
31
31
|
```js
|
|
32
32
|
const spec = discretise({
|
|
@@ -38,7 +38,7 @@ const spec = discretise({
|
|
|
38
38
|
overhang: '+z', // printable standing this way up: no supports
|
|
39
39
|
});
|
|
40
40
|
const result = optimise(spec); // multigrid solves each step
|
|
41
|
-
const { vertices, faces } = surface(spec.grid, result.density, spec.origin);
|
|
41
|
+
const { vertices, faces } = surface(spec.grid, result.density, spec.origin, { overhang: { up: '+z', angle: 45 } });
|
|
42
42
|
```
|
|
43
43
|
|
|
44
44
|
## How it works
|
|
@@ -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.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.
|
|
36
|
+
"@rulecad/fea": "^0.2.1"
|
|
37
37
|
},
|
|
38
38
|
"types": "./topopt.d.mts"
|
|
39
39
|
}
|
package/topopt.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @typedef {{ at: number[], r: number } | { at: number[], size: number[] } | { at: number[], r: number, length: number, axis?: 'x' | 'y' | 'z', teardrop?:
|
|
2
|
+
* @typedef {{ at: number[], r: number } | { at: number[], size: number[] } | { at: number[], r: number, length: number, axis?: 'x' | 'y' | 'z', teardrop?: string } | { points: [number, number][] } | { triangles: number[][][] }} Region
|
|
3
3
|
* in mm: a circle (2D) or sphere (3D) at, r; a box at (its centre), size; a cylinder at (its centre), r, length,
|
|
4
|
-
* along axis (default z; teardrop '
|
|
4
|
+
* along axis (default z; teardrop '+z', '-y', …: a 45° point that way, across the axis, so it prints); a polygon (2D);
|
|
5
5
|
* or a closed triangle mesh (3D: a design's part)
|
|
6
6
|
*/
|
|
7
7
|
/** @typedef {Region & { fix?: string }} Support holds the nodes in the region (on material): fix the directions, 'xy' or 'xyz' (default all) */
|
|
@@ -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.
|
|
@@ -165,7 +185,9 @@ export function area(loop: [number, number][]): number;
|
|
|
165
185
|
* @param {{ nx: number, ny: number, nz: number, h: number }} size @param {ArrayLike<number>} density @param {number[]} origin
|
|
166
186
|
* Vertices on the grid's outer faces stay where they are as it's smoothed, so a part that fills its space to a face (a
|
|
167
187
|
* base on the bed) keeps that face flat, and the walls rising from it don't lean out.
|
|
168
|
-
* @param {{ smooth?: number, iso?: number }} [options] iso: the density the
|
|
188
|
+
* @param {{ smooth?: number, iso?: number, overhang?: { up: string, angle: number } }} [options] iso: the density the
|
|
189
|
+
* surface is drawn at (0.5). overhang: the build direction ('+z') and the printer's overhang limit (degrees from
|
|
190
|
+
* vertical): faces smoothing left past it are tipped back to it.
|
|
169
191
|
* @returns {{ vertices: number[][], faces: number[][] }}
|
|
170
192
|
*/
|
|
171
193
|
export function surface({ nx, ny, nz, h }: {
|
|
@@ -173,9 +195,13 @@ export function surface({ nx, ny, nz, h }: {
|
|
|
173
195
|
ny: number;
|
|
174
196
|
nz: number;
|
|
175
197
|
h: number;
|
|
176
|
-
}, density: ArrayLike<number>, origin?: number[], { smooth, iso }?: {
|
|
198
|
+
}, density: ArrayLike<number>, origin?: number[], { smooth, iso, overhang }?: {
|
|
177
199
|
smooth?: number;
|
|
178
200
|
iso?: number;
|
|
201
|
+
overhang?: {
|
|
202
|
+
up: string;
|
|
203
|
+
angle: number;
|
|
204
|
+
};
|
|
179
205
|
}): {
|
|
180
206
|
vertices: number[][];
|
|
181
207
|
faces: number[][];
|
|
@@ -184,7 +210,7 @@ export { jsBackend };
|
|
|
184
210
|
export function inside(r: Region, pt: number[]): boolean;
|
|
185
211
|
/**
|
|
186
212
|
* in mm: a circle (2D) or sphere (3D) at, r; a box at (its centre), size; a cylinder at (its centre), r, length,
|
|
187
|
-
* along axis (default z; teardrop '
|
|
213
|
+
* along axis (default z; teardrop '+z', '-y', …: a 45° point that way, across the axis, so it prints); a polygon (2D);
|
|
188
214
|
* or a closed triangle mesh (3D: a design's part)
|
|
189
215
|
*/
|
|
190
216
|
export type Region = {
|
|
@@ -198,7 +224,7 @@ export type Region = {
|
|
|
198
224
|
r: number;
|
|
199
225
|
length: number;
|
|
200
226
|
axis?: "x" | "y" | "z";
|
|
201
|
-
teardrop?:
|
|
227
|
+
teardrop?: string;
|
|
202
228
|
} | {
|
|
203
229
|
points: [number, number][];
|
|
204
230
|
} | {
|
package/topopt.mjs
CHANGED
|
@@ -6,20 +6,24 @@
|
|
|
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
|
|
|
19
23
|
/**
|
|
20
|
-
* @typedef {{ at: number[], r: number } | { at: number[], size: number[] } | { at: number[], r: number, length: number, axis?: 'x' | 'y' | 'z', teardrop?:
|
|
24
|
+
* @typedef {{ at: number[], r: number } | { at: number[], size: number[] } | { at: number[], r: number, length: number, axis?: 'x' | 'y' | 'z', teardrop?: string } | { points: [number, number][] } | { triangles: number[][][] }} Region
|
|
21
25
|
* in mm: a circle (2D) or sphere (3D) at, r; a box at (its centre), size; a cylinder at (its centre), r, length,
|
|
22
|
-
* along axis (default z; teardrop '
|
|
26
|
+
* along axis (default z; teardrop '+z', '-y', …: a 45° point that way, across the axis, so it prints); a polygon (2D);
|
|
23
27
|
* or a closed triangle mesh (3D: a design's part)
|
|
24
28
|
*/
|
|
25
29
|
/** @typedef {Region & { fix?: string }} Support holds the nodes in the region (on material): fix the directions, 'xy' or 'xyz' (default all) */
|
|
@@ -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
|
|
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(
|
|
256
|
-
|
|
257
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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)
|
|
280
|
-
|
|
281
|
-
|
|
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
|
-
|
|
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
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
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
|
}
|
|
@@ -360,13 +587,13 @@ function insider(r) {
|
|
|
360
587
|
if (r.size) return (pt) => r.size.every((s, a) => Math.abs(pt[a] - r.at[a]) <= s / 2);
|
|
361
588
|
if (r.length != null) {
|
|
362
589
|
const ax = 'xyz'.indexOf(r.axis || 'z'), others = [0, 1, 2].filter((a) => a !== ax);
|
|
363
|
-
// A teardrop: a cylinder across the build
|
|
364
|
-
//
|
|
365
|
-
const
|
|
590
|
+
// A teardrop: a cylinder across the build with a 45° point below it (a boss) or above it (a hole), so it prints
|
|
591
|
+
// unsupported. Along the build, it's a plain cylinder.
|
|
592
|
+
const pa = r.teardrop ? 'xyz'.indexOf(r.teardrop[1]) : -1, point = pa >= 0 && pa !== ax ? (r.teardrop[0] === '-' ? -1 : 1) : 0, side = others.find((a) => a !== pa);
|
|
366
593
|
return (pt) => {
|
|
367
594
|
if (Math.abs(pt[ax] - r.at[ax]) > r.length / 2) return false;
|
|
368
595
|
if (Math.hypot(pt[others[0]] - r.at[others[0]], pt[others[1]] - r.at[others[1]]) <= r.r) return true;
|
|
369
|
-
const out = point * (pt[
|
|
596
|
+
const out = point * (pt[pa] - r.at[pa]);
|
|
370
597
|
return point !== 0 && out > 0 && Math.abs(pt[side] - r.at[side]) + out <= r.r * Math.SQRT2;
|
|
371
598
|
};
|
|
372
599
|
}
|
|
@@ -421,7 +648,8 @@ export function bounds(r) {
|
|
|
421
648
|
const half = r.size ? r.size.map((s) => s / 2) : r.length != null ? [0, 1, 2].map((a) => (a === 'xyz'.indexOf(r.axis || 'z') ? r.length / 2 : r.r)) : new Array(dim).fill(r.r);
|
|
422
649
|
const lo = r.at.map((c, a) => c - half[a]);
|
|
423
650
|
const hi = r.at.map((c, a) => c + half[a]);
|
|
424
|
-
|
|
651
|
+
const pa = r.teardrop && r.length != null ? 'xyz'.indexOf(r.teardrop[1]) : -1;
|
|
652
|
+
if (pa >= 0 && pa !== 'xyz'.indexOf(r.axis || 'z')) { if (r.teardrop[0] === '-') lo[pa] = r.at[pa] - r.r * Math.SQRT2; else hi[pa] = r.at[pa] + r.r * Math.SQRT2; } // its point
|
|
425
653
|
return [...lo, ...hi];
|
|
426
654
|
}
|
|
427
655
|
|
|
@@ -525,10 +753,12 @@ function simplify(loop, tolerance) {
|
|
|
525
753
|
* @param {{ nx: number, ny: number, nz: number, h: number }} size @param {ArrayLike<number>} density @param {number[]} origin
|
|
526
754
|
* Vertices on the grid's outer faces stay where they are as it's smoothed, so a part that fills its space to a face (a
|
|
527
755
|
* base on the bed) keeps that face flat, and the walls rising from it don't lean out.
|
|
528
|
-
* @param {{ smooth?: number, iso?: number }} [options] iso: the density the
|
|
756
|
+
* @param {{ smooth?: number, iso?: number, overhang?: { up: string, angle: number } }} [options] iso: the density the
|
|
757
|
+
* surface is drawn at (0.5). overhang: the build direction ('+z') and the printer's overhang limit (degrees from
|
|
758
|
+
* vertical): faces smoothing left past it are tipped back to it.
|
|
529
759
|
* @returns {{ vertices: number[][], faces: number[][] }}
|
|
530
760
|
*/
|
|
531
|
-
export function surface({ nx, ny, nz, h }, density, origin = [0, 0, 0], { smooth = 4, iso = 0.5 } = {}) {
|
|
761
|
+
export function surface({ nx, ny, nz, h }, density, origin = [0, 0, 0], { smooth = 4, iso = 0.5, overhang } = {}) {
|
|
532
762
|
const W = nx + 3, H = ny + 3, D = nz + 3, v = new Float64Array(W * H * D), id = (i, j, k) => (k * H + j) * W + i;
|
|
533
763
|
// Each corner: the average of the cubes round it that are in the grid (on the grid's faces, only those inside it, so
|
|
534
764
|
// material reaching a face reads as solid there, not half)
|
|
@@ -593,7 +823,39 @@ export function surface({ nx, ny, nz, h }, density, origin = [0, 0, 0], { smooth
|
|
|
593
823
|
return held[n] ? p : p.map((x, q) => Math.min(hi[q], Math.max(lo[q], x + f * (avg[q] - x))));
|
|
594
824
|
});
|
|
595
825
|
}
|
|
826
|
+
if (overhang) steepen(pts, faces, held, overhang, lo, hi);
|
|
596
827
|
return { vertices: pts, faces };
|
|
597
828
|
}
|
|
598
829
|
|
|
830
|
+
// Faces past the overhang limit, tipped back to it. Optimised in cubes, a printable slope is a staircase of 45°, and
|
|
831
|
+
// smoothing leaves small faces either side of 45°. Each face facing down more steeply than the limit is turned about
|
|
832
|
+
// its centre, moving its corners along the build direction only, until it's a little inside the limit: about as much
|
|
833
|
+
// material is added as taken away. A corner shared by several such faces moves by their average; it's repeated until
|
|
834
|
+
// none are left. Flat faces (a bridge) and faces held on the grid's sides stay as they are.
|
|
835
|
+
function steepen(pts, faces, held, { up, angle }, lo, hi, passes = 200) {
|
|
836
|
+
const q = 'xyz'.indexOf(up[1]), s = up[0] === '-' ? -1 : 1, [a, b] = [0, 1, 2].filter((x) => x !== q);
|
|
837
|
+
const limit = Math.sin((angle * Math.PI) / 180), slope = 1.03 / Math.tan((angle * Math.PI) / 180);
|
|
838
|
+
for (let pass = 0; pass < passes; pass++) {
|
|
839
|
+
const move = new Float64Array(pts.length), count = new Uint16Array(pts.length);
|
|
840
|
+
let left = 0;
|
|
841
|
+
for (const f of faces) {
|
|
842
|
+
if (held[f[0]] && held[f[1]] && held[f[2]]) continue;
|
|
843
|
+
const [p, r, t] = f.map((n) => pts[n]), u = [r[0] - p[0], r[1] - p[1], r[2] - p[2]], w = [t[0] - p[0], t[1] - p[1], t[2] - p[2]];
|
|
844
|
+
const n = [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]], len = Math.hypot(...n);
|
|
845
|
+
if (!len || (s * n[q]) / len >= -limit) continue;
|
|
846
|
+
// The face's plane as a height along the build direction over the other two: x_q = c + ga x_a + gb x_b
|
|
847
|
+
const ga = -n[a] / n[q], gb = -n[b] / n[q], g = Math.hypot(ga, gb);
|
|
848
|
+
if (g < 0.05) continue; // flat: a bridge, which turning won't help
|
|
849
|
+
left++;
|
|
850
|
+
const c = [0, 1, 2].map((x) => (p[x] + r[x] + t[x]) / 3), k = slope / g;
|
|
851
|
+
for (const m of f) {
|
|
852
|
+
const v = pts[m];
|
|
853
|
+
move[m] += c[q] + k * (ga * (v[a] - c[a]) + gb * (v[b] - c[b])) - v[q]; count[m]++;
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
if (!left) break;
|
|
857
|
+
for (let m = 0; m < pts.length; m++) if (count[m] && !held[m]) pts[m][q] = Math.min(hi[q], Math.max(lo[q], pts[m][q] + move[m] / count[m]));
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
|
|
599
861
|
const fmt = (n) => String(Number(n.toFixed(2)));
|