@rulecad/topopt

Topology optimisation for flat and solid parts: the stiffest layout of the material you give, or the lightest under a stress limit, printable without supports if asked.

npm 0.3.9sourceMITNode >=20runs in this page
npm install @rulecad/topopt

Try it

The package's own code, running in this page: the MBB beam, a beam on two supports pushed down in the middle, optimised in a worker so the page stays free. It works on half the beam (the other half is its mirror image) on 60 × 20 cells, as Andreassen and others' 88-line code does, and fills the share of the beam you choose. Each step moves material to where it stiffens the beam most; the compliance, how much the beam gives under its load, falls as it does.

Reference

Topology optimisation for flat parts (2D) and solid ones (3D): where to put a fixed amount of material in a region so the part is as stiff as possible under its loads. Give it the space a part may fill, the bosses it must keep, the holes it must avoid, where it's held and how it's loaded. It returns outlines ready to extrude (2D), or a closed surface ready to print (3D). No dependencies but @rulecad/fea; runs in browsers and Node.

import { discretise, optimise, outlines } from '@rulecad/topopt';

const spec = discretise({
  space: { at: [60, 0], size: [140, 40] },                         // where material may go (mm)
  keep: [{ at: [0, 0], r: 6 }, { at: [120, 0], r: 5 }],            // must stay solid
  avoid: [{ at: [0, 0], r: 2.8 }, { at: [120, 0], r: 2.3 }],       // must stay empty
  supports: [{ at: [0, 0], r: 2.8 }],                              // held here
  loads: [{ at: [120, 0], r: 2.3, force: [0, -20], case: 'down' }], // pushed here (N)
  material: { E: 2680, nu: 0.36 }, thickness: 6, cell: 1, volume: 0.5, filter: 2.5,
});
const result = optimise(spec, { onStep: (s) => console.log(s.step, s.compliance) });
result.unsupported; // with overhang: the share of the kept regions' material nothing holds up (0: all held up)
result.cases;      // [{ name: 'down', deflection (mm along the load), stiffness (N/mm) }]; a twist (forces adding
                   // to nothing): { name, moment (N·mm), angle (radians), torsion (N·mm a radian) }
const loops = outlines(spec.grid, result.density, spec.origin);   // closed loops, solid on the left

In 3D

Regions take a z. A region can be a box (size), a cylinder (r, length, axis), a ball (r), or a closed triangle mesh (triangles). A cylinder can be a teardrop: teardrop: '-z' for a boss, '+z' for a hole, or any direction across its axis. It gets a 45° point that way, so it prints without support. Supports and loads can be any region.

A part's mesh can be a region of a flat problem too: { triangles, flat: true } is its section halfway up (a plate's outline, its holes open), so a flat part can be optimised within the blank it's cut from.

const spec = discretise({
  space: { at: [10, 0, 43], size: [40, 40, 86] },
  keep: [{ at: [10, 0, 80], r: 5, length: 16, axis: 'x', teardrop: '-z' }],
  supports: [{ at: [10, 0, 1], size: [40, 40, 2] }],
  loads: [{ at: [10, 0, 80], r: 2.4, length: 16, axis: 'x', force: [0, -20, 0] }],
  material: { E: 2680, nu: 0.36 }, cell: 2.5, volume: 0.2, filter: 5,
  overhang: '+z',                                    // printable standing this way up: no supports
});
const result = optimise(spec);                       // multigrid solves each step
const { vertices, faces } = surface(spec.grid, result.density, spec.origin, { overhang: { up: '+z', angle: 45 } });

How it works

The density method (SIMP: solid isotropic material with penalisation). Each cell has a density from 0 to 1, starting even. On each step:

  1. Analyse the part (@rulecad/fea).
  2. Work out each cell's effect on the compliance. Compliance is how much the part gives under its loads, so lower is stiffer; each cell's effect is its gradient.
  3. Move material towards the cells that stiffen the part most, keeping the total fixed (the optimality criteria update).

Stiffness grows as density cubed, so part-solid cells are poor value and the result settles into solid and empty. Two more steps shape the result:

Milled from above, the 3D cantilever (24 × 8 × 8 cubes, volume 0.3, 200 steps) has no undercuts from the tool's side and a compliance of 3227 against 2989 optimised freely, 8% less stiff, with 5.3% of its cells grey; the free design has over 100 cells hidden under material from above. A 2D cantilever (30 × 20 squares, 200 steps) milled from its top edge has no undercuts either, but over 30% of it is grey. Mirrored across its middle, a cantilever loaded at one corner comes out the same both sides to the last digit.

FigureFormulaSource
Smooth maximum over a disc or ball of N cells(1/β) ln(Σ exp(β x) / N), β = 10 ln N + 10Sigmund (2007)
Smooth minimum1 − smooth maximum of (1 − x)Sigmund (2007)
Tool (closing)smooth minimum of the smooth maximum, over a disc of the tool's radius in each layerSigmund (2007); Langelaar (2019)
Feature (opening)smooth maximum of the smooth minimum, over a ball of r cells; r = ⌈(feature / h − 1) / 2⌉Sigmund (2007)
Several sidessmooth minimum of two: ½(a + b − √((a − b)² + ε)) + ½√ε, ε = 10⁻⁶Langelaar (2019)
Drafta cell's step out every ⌊1 / tan(draft)⌋ layersthe draw after Gersborg and Andreassen (2011); the step is this package's choice
Virtual temperaturek = kₛ + (1 − kₛ)(1 − ρ)³, heat 1 − ρ, faces at 0; p-mean of T, p = 8Liu and others (2015)

Several load cases are optimised together by weight. A case weighted 0 is solved only at the end, for its figures. model(spec) exposes the analysis and its gradient, for other update methods.

outlines traces a 2D result's edges at density 0.5 (marching squares), smooths them (Taubin, which keeps the size), and drops holes and islands smaller than minArea.

surface does the same for a 3D result: a closed triangle mesh at density 0.5, by marching tetrahedra. Every cube is split along the same diagonal, so neighbouring cubes cut their shared faces the same way and the surface has no gaps. Then it's smoothed. With overhang, the smoothed surface is made printable: faces left steeper than the limit are tipped back to it, and tips left hanging in mid-air (the lowest point of a dip under an edge, which a printer has nothing to lay down on) are lifted level with their neighbours, in turn until neither finds any.

reduce gives a closed surface fewer triangles. It collapses edges one at a time, cheapest first, by the quadric error of Garland and Heckbert (1997): each corner keeps the planes of the faces it came from, and the sum of its squared distances to them must stay under the tolerance squared, so no corner moves further than the tolerance from any of those planes. A collapse is refused if it would open or pinch the surface (the two ends must share exactly the two corners across their edge: the link condition of Dey and others, 1999), fold a face over, or leave a sliver with no area. Corners on the grid's faces stay on them. Given the build direction and the printer's limit, it also refuses a collapse that adds to the area hanging past the limit or leaves a corner lower than all its neighbours (a tip, which slices as an island). On the bracket bench's printable result, 0.1 mm (a quarter of a print line) took 75,592 triangles to 21,124, the volume from 27.808 to 27.806 cm³, with no islands before or after.

const fewer = reduce({ vertices, faces }, { tolerance: 0.1, lo, hi, overhang: { up: '+z', angle: 45 } }); // lo, hi: the grid's corners
FigureFormulaSource
A corner's error at pΣ over its faces' planes (n · p + d)², n the unit normalGarland and Heckbert (1997)
Collapse allowederror ≤ tolerance², ends share exactly two corners, no face turned over 70°Garland and Heckbert (1997); Dey and others (1999)
A face hangsits normal points down more than sin(limit) from level, and it isn't on the bedthe printer's overhang limit, degrees from vertical

printable makes a result printable before it's drawn, the hard way: built up layer by layer from the bed, a cell stays only if something holds it up (a cell in the layer below, straight under it or diagonally next to that; or, within reach cells along its own layer, one that is: a short bridge); kept regions always stay. Whatever's left hanging is emptied, and with it, layer by layer, whatever rested on it. It's what cad optimise does to every 3D result with a build direction.

Stress limits

Stiffness alone puts material in sharp inside corners, where stress concentrates and cracks start. Give a stress limit (MPa) instead of a volume, and optimise finds the lightest layout that keeps every cell's von Mises stress under it:

const spec = discretise({ ...problem, volume: undefined, stress: 13 }); // pla.strength / 3
const result = optimise(spec);
result.stress;     // { peak, limit }: the largest stress in the result's solid cells (MPa)

The L-bracket (reference/lbracket.mjs), the usual test: a 100 mm square less its top-right 60 mm, held along the 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 result is re-analysed as it would be made: its smoothed outline, on 0.5 mm cells.

Space usedCompliancePeak stress, on its cellsPeak stress, as made
Stiffest at 40%40.0%373 N·mm–67.2 MPa
Lightest under 25 MPa39.4%426 N·mm26.2 MPa36.6 MPa

!The L-bracket, stiffest and stress-limited

For the same material, the stress-limited bracket draws its members together with filleted joints, and its peak stress falls by 46%. Two things to know:

Robust stress limits

A part is never printed exactly as drawn: an edge comes out a little in or a little out. Give robust: true with the limit and the layout is optimised as three copies at once: the design as made, an eroded copy (thinner, projected at 0.7) and a dilated one (thicker, at 0.3), with the limit held on every cell of all three (Wang, Lazarov and Sigmund 2011; with stress limits, da Silva, Beck and Sigmund 2019). The lightest of the design as made is what's sought. result.stress.copies gives the eroded and dilated copies' peaks for every lightest layout, robust or not.

The cantilever of the tests, 20 MPa, 2 mm cellsSpace usedPeak as madeMade thinMade thick
Plain76.1%20.3 MPa103 MPa19.9 MPa
Robust89.1%19.9 MPa20.0 MPa19.8 MPa

The plain layout keeps a member that is just thick enough as drawn; a little thinner, its peak is five times the limit. On the L-bracket at 25 MPa, re-analysed as made on cells half the size:

L-bracket, 25 MPaSpace usedPeak as made (half cells)Settled
Plain, 2 mm cells44.9%33.7 MPayes
Robust, 2 mm cells56.9%32.1 MPayes, 619 steps
Plain, 1.6 mm cells41.9%794 MPa (a member left too thin to carry)no, 800 steps
Robust, 1.6 mm cells52.8%27.5 MPayes, 584 steps

Robust costs three solves and three adjoints a step, and more material. What it buys is a result that is what it claims to be when made: on 1.6 mm cells the plain result came apart as made, the robust one stayed 10% over the limit, at the inside corner. That corner still stays sharp: robustness does not round the space's own corners, since the filter counts the cut-out as empty and the design as made keeps a solid cell there. Three more ways were tried on 2 mm cells with the robust copies, and none is built in: limiting each cell at its four corners (the corner cell emptied and the peak as made fell to 23.9 MPa, but the space used rose to 76%, and 1,000 steps did not settle), at its four Gauss points (21.3 MPa as made, the corner cell emptied, 72% of the space, 1,500 steps unsettled, the space used still rising) and at the space's inside corners only (68%, unsettled). Each limit at a sharp corner is a stress that rises without end as cells shrink, so it keeps the augmented Lagrangian's penalty growing, and the optimiser answers it with material everywhere. A rounded inside corner with the peak under the limit as made, as the published results show, is still to be met.

Mechanisms

A compliant mechanism is a part that moves by bending: push here, and there moves, with no joints. Give the problem an output (where it should move, along one axis, against a spring) and the first load becomes the input (with input_spring, a spring it pushes against); the optimiser then makes the layout that moves the output furthest (Sigmund 1997), by the method of moving asymptotes under the volume.

const spec = discretise({
  space: { at: [20, 10], size: [40, 20] }, cell: 1, volume: 0.3, filter: 1.5, material: { E: 1, nu: 0.3 }, thickness: 1,
  supports: [{ at: [0.5, 0.5], size: [1, 1] }, { at: [0.5, 19.5], size: [1, 1] }],
  loads: [{ at: [0.5, 10], size: [1, 2], force: [1, 0] }], input_spring: 0.1,   // pushed to the right at the left edge
  output: { at: [39.5, 10], size: [1, 2], direction: [-1, 0], spring: 0.1 },    // the right edge should move left
});
const result = optimise(spec);
result.mechanism;  // { travel (mm, the output along its direction), input (mm, the input along the push), advantage (travel / input) }

That one is the force inverter, the classic test: a block pushed at its left edge whose right edge moves the other way. The springs matter: the output's stands for what the mechanism works against, the input's for what pushes it; softer springs give more travel and a smaller advantage. The travel's gradient (an adjoint solve with the output's direction as the load) agrees with finite differences.

Left to itself, mechanism synthesis makes point hinges: a joint one cell wide and half empty is the most compliant there is, and no printer makes it. So a mechanism is optimised robustly (Wang, Lazarov and Sigmund 2011): its travel on an eroded copy of the design (projected at a threshold of 0.7), its volume on a dilated one (0.3), the design as made between them. A hinge that survives erosion has real width, and the result is one piece, cell to cell. The price: the design as made is stiffer than the eroded copy it was optimised on, by a hinge width's worth of stiffness (which goes as the width cubed), so result.mechanism reports what the design as made does, and it moves less than the run's progress figures suggested. result.mechanism.copies gives the eroded and dilated copies' travels.

The eroded copy alone leaves the dilated one free to stiffen: made a little thick, the hinges of the PLA inverter below fill in and its output moves 0.023 mm against 1.81 mm as made. With robust: true the worst of the three copies is optimised, by the bound formulation (Bendsøe, Olhoff and Taylor 1983, as Wang, Lazarov and Sigmund 2011 use it): one more variable z is minimised under each copy's minus travel over the first step's, z for each, so whichever copy moves least is the one improved. Two more things come with it, as in da Silva, Beck and Sigmund (2019): the filter counts the cells past the grid's edges as empty (Clausen and Andreassen 2017), else a member one cell thick along an edge survives erosion and the copies cheat there; and so the cells at the supports, input and output are kept solid.

PLA inverter, 1 mm cells, 10 NTravel as madeMade thinMade thickSpace used
Eroded copy (default)1.81 mm0.92 mm0.023 mm30%
Worst of three (robust)2.99 mm0.92 mm0.93 mm23.3%

The worst copy moves 40 times as far. The robust layout leaves its volume unused (more material would not move the worst copy further). On these cells, with a 1.5 mm filter, it keeps two joints where cells meet only at a corner, in all three copies: a hinge a node wide. A wider filter is the cure in principle; at 2.5 mm on 1 mm cells the inverter moved 0.02 mm, so on cells this coarse the robust inverter is a layout to read, not a part to print: its members are one and two cells wide, and the smoothed outline (outlines) loses them, drawing it in pieces.

A mechanism's strength

A mechanism bends, so its hinges are where it breaks. Give a mechanism a stress limit (MPa), or a strain limit (a share of the length, times the material's E: a printed plastic's strain at yield is about its strength over its modulus), and once optimised it is checked against it at its input force:

const result = optimise(discretise({ ...inverter, material: { E: 2680, nu: 0.36 }, strain: 0.003 })); // PLA, 0.3%
result.stress; // { peak, limit, strain, strainLimit, force, travel }

peak is the largest von Mises stress in the design as made (cells at least half solid) under the input force; force is the input force that takes the peak to the limit, and travel how far the output moves then. The part is linear, so both are the input force and the output's travel times limit over peak. For the PLA inverter above (40 by 20 mm, 4 mm thick, pushed with 10 N against springs of 0.268 N/mm), the peak is 12.1 MPa and the output moves 1.81 mm, so at 0.3% (8.04 MPa) it may be pushed with 10 × 8.04 / 12.1 = 6.6 N, its output then 1.2 mm along.

Without robust, the limit checks the layout and does not shape it. With robust: true the mechanism is optimised under it, as in da Silva, Beck and Sigmund (2019): every cell's limit on each of the three copies, kept by the augmented Lagrangian the lightest layout uses (its penalty starting at 1), added to z. Two choices make it work, each found by trial on the inverter: the cells at the supports, input and output are not limited (a force on a small pad is a stress there, whatever the layout, as the paper also sets it), and each limit is relaxed by the cell's density cubed rather than its density. With density alone the empty cells between moving parts, which stretch far and as if solid carry huge stresses, held the output still: the travel went to 0 at every limit tried, 2% included.

PLA inverter, 10 N, limit 0.15% (4.02 MPa)Peak as madeMade thinMade thickTravel as madeWorst copy
Checked only (default)12.1 MPa1.81 mm0.023 mm
Optimised under it (robust)4.03 MPa0.72 MPa6.66 MPa1.90 mm1.28 mm

Experimental: the figures above are one machine's. A mechanism optimised under a limit is sensitive to the floating point of the machine it runs on. The same problem in CI ended within 2% of the limit with the worst copy moving 0.55 mm and in more than one piece (macOS), 5.7% over (Linux), and within 2% (Windows). It always cuts the checked-only layout's peak by more than half, but check the result as drawn (cad check finds loose pieces) before printing it, and read its peak in result.stress. Making it hold the same on every machine is left.

On the machine above, the design as made keeps to the limit and still moves its output 1.9 mm. Made a little thick, its peak is 66% over: the dilated copy's limits are in the problem but did not hold by the time it settled (its stopping test is the travel, not the limit). So read result.stress.copies before trusting a thick print, and keep the input force under the force reported. Earlier tries, without the three copies: the augmented Lagrangian added to the eroded copy's travel (the travel went to 0), and the stresses' p-norm (p = 8) as a second limit after de Leon, Alexandersen, Fonseca and Sigmund (2015), with Le et al.'s (2010) correction (the final peaks missed the limit by up to 80%).

Checked against the published code

With projection off, it matches the 88-line MATLAB code of Andreassen and others (2011), top88.m, step for step:

The docs site runs the same MBB beam live in the browser, in a worker, to the same 127 steps and 218.80.

In 3D it matches Liu and Tovar's top3d.m (2014) step for step: a cantilever of 24 × 8 × 8 cubes, 145 steps to 4906.73. The overhang filter's gradient agrees with finite differences.

The numbers in the tests were worked out with Python copies of the two MATLAB codes, kept outside this repository: top88.m's authors reserve all rights to it, and top3d.m's terms were not checked. To work them out again, fetch the original codes, which each paper prints in full (top88.m is also offered at www.topopt.mek.dtu.dk), and run them on the problems the comments in test.mjs give. Both papers are listed under References.

Its gradients agree with finite differences through the filter and the projection.

Glossary

Sources

Licence

MIT (see LICENSE), except the method of moving asymptotes: mma, subsolve and gauss in topopt.mjs follow Krister Svanberg's MATLAB code, which is under the GNU General Public License version 3 or later. Until they are rewritten, read THIRD-PARTY.md before you copy or reuse them.