Skip to main content

Lab 3 — Design, analyze and optimize a bracket

📍 Where we are: Part IV · Virtual Labs: Build Without Hardware — Chapter 12 of 16. Lab 2 takes a model and slices and checks a print; this lab makes the model, and asks the computer whether it will hold and whether it can be lighter.

The simple version

Before you bake an expensive cake you can weigh the ingredients and check the oven. Before you print a part you can do the same: draw it as code, ask a program whether the printer can make it, and ask a second program how much it bends under load. But a program that bends your bracket is only useful if you first test it on something with a known answer, like a ruler pressed over a table edge. This lab does that testing first, and only then trusts the programs on the bracket.

What this chapter covers​

We build one small pipeline, all inside Docker and all run for this chapter: CadQuery draws a shelf bracket; a printability check flags overhangs and thin walls; gmsh meshes it and scikit-fem computes how it deflects, after we have proved that chain on a cantilever beam whose answer is known in closed form. Then we port the two classic compact topology-optimization codes to Python, check them iteration by iteration against the published MATLAB code, use them to redesign the bracket's rib, and bring the result back into CAD. Every number below is output from our run on 2026-11-15 (Docker 29.9 on Apple silicon, linux/aarch64).

Why simulate before printing​

Topology optimization finds shapes that carry load with little material, and additive manufacturing can make shapes that machining cannot; that match is why the two are so often paired [1]. But a simulation is a model, and a wrong model gives confident nonsense. So the lab is organised around gates: each stage must pass a test with a known answer before the next stage is trusted. The gates here are: the CAD solid is valid, the solver matches beam theory, the optimizer matches the published code, and the printability lint passes.

Five stages (CadQuery design, gmsh mesh, scikit-fem solve, SIMP optimize, trimesh check), each with a green verification gate, and a loop returning the optimized rib to CAD. The lab pipeline: five open tools in a row, one verification gate under each, and the optimizer's output returning to CAD. Original diagram by the authors, created with AI assistance.

Step 0 — Build the environment​

The stack is CadQuery 2.8.0 on OpenCASCADE [2] for geometry, gmsh [3] for meshing, scikit-fem [4] for the finite element solve, and trimesh [5] for mesh inspection. Python is 3.12 in the official python:3.12-slim image. gmsh has no PyPI wheel for aarch64 Linux (our first pip install gmsh failed with "No matching distribution"), so the Dockerfile installs Debian's gmsh 4.13.1 [6] and we call its command line; everything else is a pinned wheel.

cd examples/lab-design-and-simulate
make image # docker build -t amguide-lab3-lab .
make run # the whole lab, then read ./out
make test # six pytest self-tests

The first image build took 7 min 13 s with a cold cache (it is network-bound: OpenCASCADE plus VTK are large wheels), and the image is 2.34 GB. make run took 3 min 46 s and 3 min 20 s in two full runs; make test takes about 10 s. An independent re-run on 2026-11-15 from a clean copy (image rebuilt with --no-cache, 2 min 28 s on a warm network; make run 3 min 4 s; make test 9 s, six passed) reproduced every number in this chapter exactly. We tested only on aarch64; the pins are in requirements.txt and the stack versions are listed in the example's README.

Step 1 — Design the bracket as code​

bracket.py builds a shelf bracket from a Params record: a 4 mm wall plate (40 wide, 50 high), a 4 mm shelf 40 mm deep on top, a 3 mm inner fillet, four 5 mm mounting holes, and a triangular gusset (28 by 30 mm, 4 mm thick) under the shelf. It exports STEP, STL and 3MF, as in Open CAD and code-driven design.

python bracket.py out
valid=True volume=15137.9 mm3 bbox=40.0x40.0x50.0 mm solids=1
wrote out/bracket.step (62840 bytes)
wrote out/bracket.stl (116084 bytes)
wrote out/bracket.3mf (30160 bytes)

Two checks are automated in make test: the CAD solid is valid and single, and the STL volume and the volume computed from the 3MF file both agree with the CAD volume (the STL gave 15138.1 mm³ against 15137.9 mm³).

Step 2 — An automated printability check​

printcheck.py is a lint with two rules. Overhang: a triangle that faces downward more steeply than a limit (default 45 degrees from vertical, a rule of thumb for self-supporting FDM geometry [7]) needs support, unless it lies on the bed. Minimum wall: from each triangle's centre we shoot a ray inward and measure the distance to the opposite wall; anything under 1.2 mm (three 0.4 mm lines, our assumption) is flagged. --sweep tries the six axis-aligned orientations.

python printcheck.py out/bracket.stl --sweep
orientation height overhang oblique ceiling frac minwall support? (areas in mm2)
+Z up (as modelled) 50.0 1368.5 111.5 1257.0 0.158 4.00 YES
-Z up (flipped) 50.0 61.8 47.9 14.0 0.007 4.00 YES
+X up 40.0 0.0 0.0 0.0 0.000 4.00 no
-X up 40.0 1781.8 224.9 1556.8 0.205 4.00 YES
+Y up 40.0 467.5 51.9 415.7 0.054 4.00 YES
-Y up 40.0 467.5 51.9 415.7 0.054 4.00 YES

Read it like a designer. As modelled, the shelf's underside is a 1257 mm² flat roof. Flipped, so the shelf lies on the bed, only the round holes remain (61.8 mm²): the top of a horizontal circle is an overhang. A teardrop hole (a circle with a 45-degree point) fixes that, and bracket.py --teardrop -1 points it the right way for the flipped print:

-Z up (flipped) 50.0 0.0 0.0 0.0 0.000 4.00 no

The tempting orientation is "+X up", which also shows zero overhang. But the check does not know about layers: FDM parts are weaker across layer boundaries than along them [8], and in "+X up" the shelf's bending stress runs across them. That is a simplification of the tool, not a flaw in the part; see the list at the end of the chapter.

Step 3 — Prove the FEA chain on a cantilever​

A finite element model is only as good as its setup (units, boundary conditions, element choice). Before the bracket, validate_beam.py runs the same pipeline (CadQuery box, STEP, gmsh tetrahedra, quadratic tets in scikit-fem, direct solve) on a 100 by 10 by 10 mm cantilever clamped at one end with a 10 N tip load and E = 3000 MPa, nu = 0.35. The reference is Timoshenko beam theory: bending PL³/(3EI) plus a shear term PL/(κGA) with κ = 5/6 for a rectangle (the shear correction goes back to Timoshenko [9]). We fixed the pass criteria before running: tip deflection within 2 % on the finest mesh, error not growing as the mesh is refined, mid-length stress within 5 % of beam theory.

Euler-Bernoulli bending term = 1.33333 mm, shear term = 0.01080 mm, Timoshenko total = 1.34413 mm
h= 10.0 mm tets= 203 dofs= 1380 tip deflection=1.31934 mm error=-1.84 % stress ratio (FEA/beam, 40-60 % of L)=0.999
h= 5.0 mm tets= 434 dofs= 2997 tip deflection=1.32633 mm error=-1.32 % stress ratio (FEA/beam, 40-60 % of L)=1.000
h= 2.5 mm tets= 3631 dofs= 20064 tip deflection=1.32926 mm error=-1.11 % stress ratio (FEA/beam, 40-60 % of L)=1.000
L=200 mm, h=5 mm: tets=790 tip deflection=10.61823 mm vs Timoshenko 10.68827 mm, error=-0.66 %
PASS

The error does not go to zero, and that is expected, not a bug: the 3D model clamps the whole end face, which also stops the cross-section from contracting and warping, so it is slightly stiffer than the one-dimensional beam theory. A longer, more slender beam should shrink that gap, and it does (-0.66 % at 200 mm against -1.32 % at the same mesh size for 100 mm). We did not run a second independent solver (for example CalculiX) on the cantilever, so what is verified here is agreement with theory, not with another code.

Step 4 — Analyze the bracket​

fea_bracket.py clamps the surfaces of the four mounting holes (an idealised, stiff screw), spreads a 50 N downward load over the outer 10 mm of the shelf, and uses E = 3000 MPa, nu = 0.35 and 1.24 g/cm³. These are plausible plastic-like values chosen for the exercise, not measured properties of any filament.

no gusset tets= 9400 vol= 13523.1 mm3 mass=16.77 g defl=1.3708 mm stiffness= 36.5 N/mm vM max= 23.60 MPa (away from holes 10.66)
gusset 28x30 tets= 8629 vol= 15137.9 mm3 mass=18.77 g defl=0.2219 mm stiffness= 225.3 N/mm vM max= 6.32 MPa (away from holes 6.29)
h= 6.0 mm tets= 4497 dofs= 25890 defl=0.2150 mm vM max= 6.41 MPa (away from holes 5.02)
h= 4.0 mm tets= 6593 dofs= 37257 defl=0.2196 mm vM max= 6.43 MPa (away from holes 5.62)
h= 3.0 mm tets= 8629 dofs= 48438 defl=0.2219 mm vM max= 6.32 MPa (away from holes 6.29)
h= 2.0 mm tets= 15068 dofs= 81141 defl=0.2197 mm vM max= 7.27 MPa (away from holes 7.27)

The gusset makes the bracket six times stiffer for 12 % more material. Look at the convergence rows too: the tip deflection settles near 0.22 mm (within about 1 % from h = 4 mm down), but the maximum von Mises stress keeps creeping up (6.4 to 7.3 MPa) as the mesh is refined, because stress at a rigidly clamped edge has no finite limit. Trust the deflection; treat peak stress with suspicion unless the supports are modelled realistically. We do not compare to a material strength, because we have no measured one.

Step 5 — Topology optimization, ported and verified​

The SIMP method (solid isotropic material with penalization) gives every element a density x between 0 and 1 and sets its stiffness to Emin plus x^p (E0 - Emin), with p = 3 so that intermediate densities are inefficient and the optimizer pushes toward solid or void [10][11]. It minimises compliance (how much the structure bends under the load) subject to a volume fraction, using sensitivities and an optimality-criteria update, plus a filter to prevent checkerboards. Sigmund's 99-line MATLAB code [12] and the 88-line successor, which adds a density filter [13] (the filter itself is from [14][15]), made this teachable. topopt.py has top99 and top88 in NumPy and SciPy.

A port is only trustworthy if it reproduces the original. The 88-line paper states that top88(60,20,0.5,3,1.5,1) yields practically the same result as the 99-line code and reproduces the MBB beam of the 99-line paper, with a slight difference from a different SIMP formulation [13]. The papers print pictures and timings, not compliance values, so our reference is the output of the published listings themselves: we transcribed them from the papers, ran them in GNU Octave 9.2.0 (gnuoctave/octave:9.2.0, amd64 under emulation) [16], and saved their logs in expected/. The sensitivity-filter run took 7 min 10 s of wall time including the first pull of the 4.3 GB image. Then:

python verify_topopt.py
PASS top88 ft=1 (sensitivity filter): iterations ref=94 python=94, matching lines 94/94, max |dObj|=5.0e-05, final Obj ref=203.1925 python=203.1925
PASS top88 ft=2 (density filter): iterations ref=127 python=127, matching lines 127/127, max |dObj|=4.9e-05, final Obj ref=218.8032 python=218.8032
PASS top99: iterations ref=94 python=94, matching lines 94/94, max |dObj|=4.9e-05, final Obj ref=203.3061 python=203.3061

Every iteration line (iteration count, compliance to four decimals, volume, change) matches; the residual 5e-5 is the rounding of the printed digits. The 88-line sensitivity-filter result (203.1925) and the 99-line result (203.3061) differ in the third digit, as the 88-line paper says they should. The 99-line paper's listing and the 88-line one are both reproduced; we did not check against MATLAB itself, only Octave.

Step 6 — Optimize the rib and bring it back to CAD​

topo_bracket.py turns the bracket's side profile into a 2D plane-stress problem on 0.5 mm elements: the wall strip and shelf strip are forced solid, the screws clamp the wall edge at the hole heights, and a downward load acts on the outer 10 mm of the shelf. We give the optimizer exactly the material of the hand-made triangle (volume fraction 0.382) and a filter radius of 2 mm. The passive/solid masks are our extension; the original codes have none. Then it traces the 0.5 density contour, simplifies it, extrudes it 4 mm and unions it with the exact plates.

topology optimization: 109 iterations in 19.4 s, compliance 66.4 -> 20.8, volume fraction 0.382, last change 0.006
grey (0.1 < x < 0.9) share of material elements: 0.274
2D plane-stress compliance (lower = stiffer): optimized 18.67 at area 752 mm2; triangle 70.95 at area 764 mm2
traced 3 loops, 176 vertices after simplification
valid=True volume=15150.5 mm3 solids=1

The optimizer finds a main strut running from the shelf tip down to the wall near the lower screws, with a second thinner arm joining it from the upper wall: a familiar truss-like bracket. Does it help in 3D? The same fea_bracket.py, same load and clamps, on the STEP file it just wrote:

gusset 28x30 tets= 8629 vol= 15137.9 mm3 mass=18.77 g defl=0.2219 mm stiffness= 225.3 N/mm
SIMP rib tets= 17798 vol= 15150.5 mm3 mass=18.79 g defl=0.1458 mm stiffness= 342.9 N/mm

At equal mass the optimized rib is 1.5 times stiffer than the triangle (in 2D the gain is much larger, 18.67 against 70.95, because plane stress overstates what a 4 mm rib can do in a 40 mm wide part). The 3D comparison is one load case with one rib thickness. It is also not print-ready: printcheck.py on the flipped part reports 113.8 mm² of overhang against 61.8 mm² for the plain bracket, because plain SIMP knows nothing about printing. Methods that put an overhang rule inside the optimization exist [17][7]; we did not run any.

Step 7 — A slicing sanity check, then the real slicer​

slice_check.py cuts the optimized STL into 0.2 mm layers and compares the sum of layer area times height with the mesh volume. It is not a slicer; it catches broken meshes cheaply.

out/bracket_topo.stl: 250 layers of 0.2 mm, height 50.00 mm
mesh volume 15150.7 mm3; sum(layer area) x 0.2 = 15153.5 mm3 (+0.02 %)
layer area min 130.7 mm2, max 1600.0 mm2; empty layers: 0

Slice the real thing with an open slicer and compare predicted time with a simulated print in Lab 2; this chapter's out/bracket_topo.stl is a ready input.

Simplifications and limits​

  • Overhang: facet normals only. No bridging allowance (horizontal holes can bridge small spans), no support footprint, no thermal effects, and the 45 degrees is a rule of thumb whose value depends on process and material.
  • Minimum wall: one ray per facet, counted only when the opposite facet is nearly anti-parallel (dot product below -0.85), so corners are not mistaken for walls; it ignores thin features that never face another wall, and gaps (it measures material, not channels).
  • Orientation: the sweep tries six axis-aligned orientations only, and ignores layer anisotropy.
  • FEA: linear, isotropic, small strain; screws idealised as clamped surfaces; no contact, preload or fatigue; invented-for-the-exercise material and load.
  • Topology optimization: 2D plane stress extruded into one rib; one load case; passive/solid masks are our additions; grey regions (27 % of material elements here) are thresholded at 0.5, which changes the compliance slightly.

When it breaks​

  • pip install gmsh fails on aarch64 Linux with "No matching distribution found": use the distribution package and call the gmsh CLI, as the Dockerfile does.
  • lib3mf is not installable from PyPI here; we do not need it, because test_lab.py reads 3MF with the standard library (zipfile and xml).
  • trimesh raised ModuleNotFoundError for rtree (ray casting), then shapely and networkx (layer sections); all three are pinned in requirements.txt.
  • A teardrop hole with sides exactly at 45 degrees was first flagged as overhang (40 mm²) because STL stores float32 and the angle came out a hair over 45; the check now has a 0.5 degree tolerance.
  • NumPy 2 removed 2D np.cross; the contour simplifier computes the cross product by hand.
  • If apt or pip fails with odd errors ("repository ... is not signed", "No space left on device"), check the free space of the Docker VM first (docker run --rm ubuntu:24.04 df -h /); a full disk produced exactly these errors for us, and docker builder prune -af fixed it.
  • The Octave image exists only for amd64: add --platform linux/amd64 on Apple silicon, and expect minutes.
  • The 99-line and 88-line codes stop when the largest density change is below 0.01; a run that never gets there needs a larger filter radius or a cap on iterations (maxit).

What to try next​

  1. Rerun topo_bracket.py with other volume fractions (pass a number) and plot compliance against material to see the trade-off curve.
  2. Add an overhang-aware step: implement Langelaar's layerwise filter [7] in topopt.py, rerun, and see what printcheck.py says.
  3. Model the screws: clamp only the hole's lower half (bearing side) and watch the peak stress and deflection change.
  4. Cross-check fea_bracket.py with a second solver such as CalculiX on the same STEP file, and publish the difference.
  5. Measure it: print the plain and optimized brackets, load them with a known weight and compare the deflections with Step 4. Calibrate E first from a printed cantilever, as in Step 3.

Why it matters​

This is the shape of a research workflow: a model, a check against something known, then a result you can defend. The same habit (validate on a case with a known answer, state the pass criterion before the run, report the residual honestly) is what lets you trust a simulation of a part nobody has printed yet.

In the real world​

Topology optimization is usually met inside larger CAD and simulation packages; we tested none of them for this lab. The value of the open 88-line lineage is that every step is readable and can be checked, as we did here. The caution applies to all of them: a smooth, confident picture can hide a wrong boundary condition.

Key terms​

  • Finite element analysis (FEA) — splitting a part into small elements and solving for how each moves under load.
  • Mesh — the set of small elements (here tetrahedra) that represent the part for the solver.
  • Cantilever — a beam clamped at one end and loaded at the other; its deflection has a closed-form answer.
  • Validation — checking a tool against a case with a known answer before trusting it on a new one.
  • Von Mises stress — a single number summarising a 3D stress state, compared with a material's yield strength.
  • SIMP — a topology-optimization scheme where element stiffness grows as density raised to a power, which pushes designs toward solid or void.
  • Compliance — the load times the displacement it causes; lower compliance means a stiffer structure.
  • Optimality criteria (OC) — a simple iterative update that moves densities toward lower compliance at fixed volume.
  • Overhang angle — the angle of a downward-facing surface from the vertical; steep ones need support.
  • Teardrop hole — a circular hole with a 45-degree point so a horizontal hole prints without support.

Where this leads​

Next: Open materials and recycling, where the material you assumed in this lab (a modulus and density chosen for the exercise) meets real filament, pellets and recycled feedstock.