@rulecad/topopt 0.2.5 → 0.2.7

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
@@ -62,7 +62,9 @@ Two more steps shape the result:
62
62
  - **Heaviside projection** sharpens the result, more on each pass, until cells are solid or empty.
63
63
  - **The overhang filter** (optional, after Langelaar 2017) applies the printer's limit. Layer by layer from the bed, a
64
64
  cell can only be as solid as the material under it: the cell below and its neighbours, so nothing overhangs more
65
- than 45°. The result prints without supports in that direction. Kept regions must print too: a kept cell that
65
+ than 45°. With `bridge` (the widest gap the printer spans, mm), a cell is also held up by a bridge: a run of solid
66
+ cells along its own layer, up to half that long, ending on a held cell. The result prints without supports in that
67
+ direction. Kept regions must print too: a kept cell that
66
68
  nothing holds up costs the optimiser as much as the whole part's compliance (shared over the kept cells), so it grows
67
69
  what holds it up; `result.unsupported` says how much of the kept material is still left hanging, which means there
68
70
  wasn't material enough to stand it on.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/topopt",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
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": {
package/topopt.d.mts CHANGED
@@ -22,6 +22,8 @@
22
22
  * @property {number} [penal] the penalty (default 3)
23
23
  * @property {boolean} [projection] sharpen with Heaviside projection (default true)
24
24
  * @property {string} [overhang] printed this way up ('+z', '-y', …): only material supported from below at 45° or less
25
+ * @property {number} [bridge] with overhang, the widest gap the printer bridges (mm): material may also be held up by a run
26
+ * of solid cells along its own layer, half that long, ending on a held cell
25
27
  * @property {number} [steps] at most this many steps (default 300)
26
28
  */
27
29
  /**
@@ -50,6 +52,7 @@ export function discretise(p: any): {
50
52
  avoid: any;
51
53
  };
52
54
  stress?: any;
55
+ bridge?: any;
53
56
  overhang?: any;
54
57
  grid: {
55
58
  nx: number;
@@ -98,13 +101,17 @@ export function densityFilter({ nx, ny, nz }: {
98
101
  * material under it: the cell itself and its neighbours along each side, in the layer below (3 cells in 2D, 5 in 3D,
99
102
  * so nothing overhangs by more than 45°). Smooth minimum and maximum keep it differentiable. apply gives the printable
100
103
  * densities; adjoint carries sensitivities back through it.
104
+ * With reach, a cell is also held up by a bridge: a run of up to reach solid cells along its own layer, each way along
105
+ * each axis, ending on a cell that something below holds up (the run's cells and that cell's support, all through the
106
+ * smooth minimum). That's what a printer spans: give reach as half the printer's bridge, in cells.
101
107
  * @param {{ nx: number, ny: number, nz?: number }} size @param {string} up the build direction: '+z', '-x', …
108
+ * @param {number} [reach] how many cells a bridge may run from a held cell (0: none)
102
109
  */
103
110
  export function overhangFilter({ nx, ny, nz }: {
104
111
  nx: number;
105
112
  ny: number;
106
113
  nz?: number;
107
- }, up: string): {
114
+ }, up: string, reach?: number): {
108
115
  apply(x: any, out: any): any;
109
116
  adjoint(g: any, out: any): any;
110
117
  };
@@ -372,6 +379,11 @@ export type Problem = {
372
379
  * printed this way up ('+z', '-y', …): only material supported from below at 45° or less
373
380
  */
374
381
  overhang?: string;
382
+ /**
383
+ * with overhang, the widest gap the printer bridges (mm): material may also be held up by a run
384
+ * of solid cells along its own layer, half that long, ending on a held cell
385
+ */
386
+ bridge?: number;
375
387
  /**
376
388
  * at most this many steps (default 300)
377
389
  */
package/topopt.mjs CHANGED
@@ -44,6 +44,8 @@ export { jsBackend };
44
44
  * @property {number} [penal] the penalty (default 3)
45
45
  * @property {boolean} [projection] sharpen with Heaviside projection (default true)
46
46
  * @property {string} [overhang] printed this way up ('+z', '-y', …): only material supported from below at 45° or less
47
+ * @property {number} [bridge] with overhang, the widest gap the printer bridges (mm): material may also be held up by a run
48
+ * of solid cells along its own layer, half that long, ending on a held cell
47
49
  * @property {number} [steps] at most this many steps (default 300)
48
50
  */
49
51
 
@@ -135,7 +137,7 @@ export function discretise(p) {
135
137
  grid: size, origin, passive, fixed, loads,
136
138
  material: p.material, thickness: p.thickness, volume: p.volume,
137
139
  filter: p.filter ?? p.cell * 1.5, penal: p.penal ?? 3, projection: p.projection ?? true, steps: p.steps ?? (p.stress ? 1000 : 300),
138
- ...(p.overhang ? { overhang: p.overhang } : {}), ...(p.stress ? { stress: p.stress } : {}),
140
+ ...(p.overhang ? { overhang: p.overhang } : {}), ...(p.bridge ? { bridge: p.bridge } : {}), ...(p.stress ? { stress: p.stress } : {}),
139
141
  regions: { keep, avoid },
140
142
  };
141
143
  }
@@ -176,19 +178,24 @@ export function densityFilter({ nx, ny, nz = 1 }, radius) {
176
178
  * material under it: the cell itself and its neighbours along each side, in the layer below (3 cells in 2D, 5 in 3D,
177
179
  * so nothing overhangs by more than 45°). Smooth minimum and maximum keep it differentiable. apply gives the printable
178
180
  * densities; adjoint carries sensitivities back through it.
181
+ * With reach, a cell is also held up by a bridge: a run of up to reach solid cells along its own layer, each way along
182
+ * each axis, ending on a cell that something below holds up (the run's cells and that cell's support, all through the
183
+ * smooth minimum). That's what a printer spans: give reach as half the printer's bridge, in cells.
179
184
  * @param {{ nx: number, ny: number, nz?: number }} size @param {string} up the build direction: '+z', '-x', …
185
+ * @param {number} [reach] how many cells a bridge may run from a held cell (0: none)
180
186
  */
181
- export function overhangFilter({ nx, ny, nz = 1 }, up) {
187
+ export function overhangFilter({ nx, ny, nz = 1 }, up, reach = 0) {
182
188
  const n = nz > 1 ? [nx, ny, nz] : [nx, ny], dim = n.length, ax = 'xyz'.indexOf(up.at(-1)), sign = up[0] === '-' ? -1 : 1;
183
189
  if (ax < 0 || ax >= dim) throw new Error(`overhang: the build direction is ${dim === 3 ? '+x, -x, +y, -y, +z or -z' : '+x, -x, +y or -y'} (got ${up})`);
184
190
  const cells = n.reduce((p, c) => p * c, 1), stride = [1, nx, nx * ny];
185
- const P = 40, eps = 1e-4, xi0 = 0.5;
191
+ const P = 40, eps = 1e-4, xi0 = 0.5, halfRootEps = 0.5 * Math.sqrt(eps);
186
192
  // Layers in build order, and each cell's supports: the cell below it and that cell's neighbours along each other axis
187
- const layer = (e) => { const c = Math.floor(e / stride[ax]) % n[ax]; return sign > 0 ? c : n[ax] - 1 - c; };
188
- const order = Array.from({ length: cells }, (_, e) => e).sort((a, b) => layer(a) - layer(b));
189
- const supports = new Array(cells);
193
+ const layerOf = (e) => { const c = Math.floor(e / stride[ax]) % n[ax]; return sign > 0 ? c : n[ax] - 1 - c; };
194
+ const layers = Array.from({ length: n[ax] }, () => []);
195
+ for (let e = 0; e < cells; e++) layers[layerOf(e)].push(e);
196
+ const supports = new Array(cells), chains = new Array(cells);
190
197
  for (let e = 0; e < cells; e++) {
191
- if (layer(e) === 0) { supports[e] = null; continue; }
198
+ if (layerOf(e) === 0) { supports[e] = null; chains[e] = []; continue; }
192
199
  const below = e - sign * stride[ax], list = [below];
193
200
  for (let a = 0; a < dim; a++) if (a !== ax) {
194
201
  const c = Math.floor(below / stride[a]) % n[a];
@@ -196,38 +203,102 @@ export function overhangFilter({ nx, ny, nz = 1 }, up) {
196
203
  if (c < n[a] - 1) list.push(below + stride[a]);
197
204
  }
198
205
  supports[e] = Int32Array.from(list);
206
+ // Bridges: along each other axis, each way, the runs of 1 to reach cells (the nearest first)
207
+ const runs = [];
208
+ for (let a = 0; a < dim; a++) if (a !== ax) {
209
+ const c = Math.floor(e / stride[a]) % n[a];
210
+ for (const dir of [-1, 1]) for (let d = 1; d <= reach; d++) {
211
+ if (dir < 0 ? c - d < 0 : c + d >= n[a]) break;
212
+ runs.push(Int32Array.from({ length: d }, (_, k) => e + dir * (k + 1) * stride[a]));
213
+ }
214
+ }
215
+ chains[e] = runs;
199
216
  }
200
- const printed = new Float64Array(cells), dSum = new Float64Array(cells), dX = new Float64Array(cells), sums = new Float64Array(cells);
217
+ // What's kept from apply for adjoint: each cell's printed density and its P-th power, the sums under the smooth
218
+ // maxima (base: the cells below; support: those and the bridges), the smooth minima's slopes, and each bridge's
219
+ // running minima
220
+ const printed = new Float64Array(cells), powP = new Float64Array(cells), base = new Float64Array(cells), baseSum = new Float64Array(cells);
221
+ const support = new Float64Array(cells), sums = new Float64Array(cells), dSum = new Float64Array(cells), dX = new Float64Array(cells);
222
+ const steps = chains.map((runs) => runs.map((r) => new Float64Array(r.length + 1)));
223
+ let lastX = null;
224
+ const smax = (sum, count) => (sum > 0 ? Math.pow(sum, 1 / (P + Math.log(count) / Math.log(xi0))) : 0);
225
+ const Q = (count) => P + Math.log(count) / Math.log(xi0);
226
+ const smin = (a, b) => { const d = a - b; return 0.5 * (a + b - Math.sqrt(d * d + eps)) + halfRootEps; };
227
+ const dsmin = (a, b) => { const d = a - b, root = Math.sqrt(d * d + eps); return [0.5 * (1 - d / root), 0.5 * (1 + d / root)]; }; // d/da, d/db
201
228
  return {
202
229
  apply(x, out) {
203
- for (const e of order) {
204
- const sup = supports[e];
205
- if (!sup) { printed[e] = x[e]; dX[e] = 1; continue; }
206
- let s = 0;
207
- for (const q of sup) s += Math.pow(printed[q], P);
208
- if (s < 1e-200) s = 0; // nothing worth the name below (and no denormals for the gradient to blow up on)
209
- const Q = P + Math.log(sup.length) / Math.log(xi0), smax = s > 0 ? Math.pow(s, 1 / Q) : 0;
210
- sums[e] = s;
211
- const d = x[e] - smax, root = Math.sqrt(d * d + eps);
212
- printed[e] = 0.5 * (x[e] + smax - root + Math.sqrt(eps));
213
- dX[e] = 0.5 * (1 - d / root); dSum[e] = 0.5 * (1 + d / root); // d printed / d x, d printed / d smax
230
+ lastX = x;
231
+ for (const layer of layers) {
232
+ // What the layer below holds up, cell by cell (a bridge rests on that, not on another bridge)
233
+ for (const e of layer) {
234
+ const sup = supports[e];
235
+ if (!sup) { printed[e] = x[e]; powP[e] = Math.pow(x[e], P); dX[e] = 1; base[e] = 1; continue; }
236
+ let s = 0;
237
+ for (const q of sup) s += powP[q];
238
+ if (s < 1e-200) s = 0; // nothing worth the name below (and no denormals for the gradient to blow up on)
239
+ baseSum[e] = s; base[e] = smax(s, sup.length);
240
+ }
241
+ for (const e of layer) {
242
+ const sup = supports[e];
243
+ if (!sup) continue;
244
+ // The cell's support: the cells below, and each bridge's running minimum (the run's cells, from the far end's
245
+ // base), all under one smooth maximum
246
+ let s = baseSum[e], count = sup.length;
247
+ chains[e].forEach((run, k) => {
248
+ const m = steps[e][k], far = run[run.length - 1];
249
+ let v = base[far];
250
+ m[0] = v;
251
+ for (let t = run.length - 1; t >= 0; t--) { v = smin(v, x[run[t]]); m[run.length - t] = v; }
252
+ s += Math.pow(v, P); count++;
253
+ });
254
+ sums[e] = s; support[e] = smax(s, count);
255
+ const d = x[e] - support[e], root = Math.sqrt(d * d + eps);
256
+ printed[e] = 0.5 * (x[e] + support[e] - root) + halfRootEps; powP[e] = Math.pow(printed[e], P);
257
+ dX[e] = 0.5 * (1 - d / root); dSum[e] = 0.5 * (1 + d / root); // d printed / d x, d printed / d support
258
+ }
214
259
  }
215
260
  out.set(printed);
216
261
  return out;
217
262
  },
218
- // Back from the last layer: each cell's sensitivity, plus what it passes on to the cells it supports
263
+ // Back from the last layer: each cell's sensitivity, plus what it passes on to the cells holding it up
219
264
  adjoint(g, out) {
220
- const lambda = Float64Array.from(g);
221
- for (let t = cells - 1; t >= 0; t--) {
222
- const e = order[t], sup = supports[e];
223
- if (!sup || !sums[e]) continue;
224
- const Q = P + Math.log(sup.length) / Math.log(xi0), common = lambda[e] * dSum[e] * (1 / Q) * Math.pow(sums[e], 1 / Q - 1) * P;
225
- for (const q of sup) lambda[q] += common * Math.pow(printed[q], P - 1);
265
+ const lambda = Float64Array.from(g), dBase = new Float64Array(cells);
266
+ out.fill(0);
267
+ for (let L = layers.length - 1; L >= 0; L--) {
268
+ const layer = layers[L];
269
+ dBase.fill(0);
270
+ for (const e of layer) {
271
+ const sup = supports[e];
272
+ if (!sup) { out[e] += lambda[e] * dX[e]; continue; }
273
+ out[e] += lambda[e] * dX[e];
274
+ if (!sums[e]) continue;
275
+ const count = sup.length + chains[e].length, common = lambda[e] * dSum[e] * (1 / Q(count)) * Math.pow(sums[e], 1 / Q(count) - 1) * P;
276
+ for (const q of sup) if (printed[q] > 0) lambda[q] += (common * powP[q]) / printed[q];
277
+ chains[e].forEach((run, k) => {
278
+ const m = steps[e][k], v = m[run.length];
279
+ if (!(v > 0)) return;
280
+ let gv = common * Math.pow(v, P - 1);
281
+ // Back along the run: each step was smin(the running minimum so far, the run cell's density)
282
+ for (let t = 0; t < run.length; t++) {
283
+ const [da, db] = dsmin(m[run.length - t - 1], x_of(run[t]));
284
+ out[run[t]] += gv * db; gv *= da;
285
+ }
286
+ dBase[run[run.length - 1]] += gv;
287
+ });
288
+ }
289
+ // What the bridges asked of this layer's bases: on to the cells below
290
+ for (const e of layer) {
291
+ const sup = supports[e];
292
+ if (!sup || !dBase[e] || !baseSum[e]) continue;
293
+ const common = dBase[e] * (1 / Q(sup.length)) * Math.pow(baseSum[e], 1 / Q(sup.length) - 1) * P;
294
+ for (const q of sup) if (printed[q] > 0) lambda[q] += (common * powP[q]) / printed[q];
295
+ }
226
296
  }
227
- for (let e = 0; e < cells; e++) out[e] = lambda[e] * dX[e];
228
297
  return out;
229
298
  },
230
299
  };
300
+ // (the densities apply was last given: kept for adjoint's bridges)
301
+ function x_of(e) { return lastX[e]; }
231
302
  }
232
303
 
233
304
  /**
@@ -245,7 +316,7 @@ export function model(spec, { method, backend = jsBackend } = {}) {
245
316
  const g = makeGrid(spec.grid), dim = g.dim, cells = g.cells, m = g.cellDofs, ke = cellStiffness(spec.material.nu, dim);
246
317
  const { passive, penal } = spec, E = spec.material.E, Emin = E * 1e-9, eta = 0.5, size = dim === 3 ? g.h : spec.thickness;
247
318
  const solver = method || (dim === 3 ? 'mg' : 'direct'), tol = solver === 'direct' ? undefined : 1e-6;
248
- const filter = densityFilter(spec.grid, spec.filter / spec.grid.h), print = spec.overhang ? overhangFilter(spec.grid, spec.overhang) : null;
319
+ const filter = densityFilter(spec.grid, spec.filter / spec.grid.h), print = spec.overhang ? overhangFilter(spec.grid, spec.overhang, spec.bridge ? Math.floor(spec.bridge / 2 / spec.grid.h) : 0) : null;
249
320
  const tilde = new Float64Array(cells), made = new Float64Array(cells), phys = new Float64Array(cells), scale = new Float64Array(cells), back = new Float64Array(cells);
250
321
  const fixedValue = (p) => (p === 1 ? 1 : 0);
251
322
  // Heaviside projection about eta: steeper as beta grows, so densities are pushed to 0 or 1 (Wang, Lazarov, Sigmund 2011)
@@ -542,6 +613,7 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
542
613
  const multipliers = lightest ? { lam: spec.loads.filter((l) => l.weight > 0).map(() => new Float64Array(m.limits)), mu: 10 } : undefined;
543
614
  const xf = new Float64Array(n), pick = (d) => Float64Array.from(freeCells, (e) => d[e]);
544
615
  let step = 0, change = 1, converged = false, beta = 1, sinceBeta = 0, peak = null;
616
+ const tried = new Float64Array(cells); // the last design the bisection analysed, and how much it filled
545
617
  while (step < spec.steps) {
546
618
  step++; sinceBeta++;
547
619
  const { compliance, dc, dv, stress } = m.evaluate(x, beta, { multipliers });
@@ -565,16 +637,20 @@ export function optimise(spec, { onStep, method, backend = jsBackend, tol = 0.01
565
637
  history.push(compliance);
566
638
  // Optimality criteria: scale each cell by √(−dc/dv/λ), within the move limit, finding λ by bisection so the
567
639
  // physical densities fill exactly the volume
568
- let lo = 0, hi = 1e9;
640
+ let lo = 0, hi = 1e9, triedFilled = NaN;
641
+ tried.fill(-1);
569
642
  while ((hi - lo) / (hi + lo) > 1e-3) { // as the 88-line code
570
643
  const mid = (lo + hi) / 2;
644
+ let same = true;
571
645
  for (let e = 0; e < cells; e++) {
572
646
  if (passive[e]) { xnew[e] = fixedValue(passive[e]); continue; }
573
647
  const b = Math.sqrt(Math.max(0, -dc[e]) / Math.max(1e-30, dv[e]) / mid);
574
648
  xnew[e] = Math.max(0, Math.max(x[e] - limit, Math.min(1, Math.min(x[e] + limit, x[e] * b))));
649
+ if (xnew[e] !== tried[e]) same = false;
575
650
  }
576
- const filled = m.physical(xnew, beta).reduce((s, v) => s + v, 0);
577
- if (filled > target) lo = mid; else hi = mid;
651
+ // (far from the answer every cell is at its move limit, the same design as the last try: not analysed again)
652
+ if (!same) { triedFilled = m.physical(xnew, beta).reduce((s, v) => s + v, 0); tried.set(xnew); }
653
+ if (triedFilled > target) lo = mid; else hi = mid;
578
654
  }
579
655
  }
580
656
  change = 0;