Algorithm Search⌘K

Algorithmadvanced

SIMP method

Also called solid isotropic material with penalization.

Gives each element a density between 0 and 1 and a stiffness that grows as a power of it, so intermediate densities are penalized, and updates by optimality criteria.

Time
O(k n (h^2 + r^2)) worst
Space
O(n (h + r^2)) extra
Where
h = number of elements across the short side; k = number of iterations; n = number of elements; r = filter radius in elements
Properties
deterministicnot exactiterative
Origin
Martin P. Bendsøe, 1989

The SIMP method (solid isotropic material with penalization) is the most used method for topology optimization. It divides the design domain into finite elements and gives each element ee a density xex_e between a small xmin⁡x_{\min} and 1. The Young's modulus of the element is xepE0x_e^p E_0 with a power p>1p > 1, usually p=3p = 3. Because of the power, a gray element with xe=1/2x_e = 1/2 costs half the material of a solid one but gives only 1/81/8 of its stiffness, so the optimizer is pushed toward densities near 0 or 1. Each iteration solves the finite element model, computes the derivative of the compliance with respect to every density, smooths these derivatives with a filter, and updates all densities at once with the optimality criteria rule, with a bisection on the Lagrange multiplier of the volume bound. Bendsøe (1989) proposed the power law, and the 99 line code of Sigmund (2001) made the method a standard. SIMP finds a local optimum of a penalized problem. It does not give the global optimum of the 0/1 problem, and this page shows a small case where it does not.

In plain words

Cut the space that the part may fill into many small squares. Each square gets a dial from almost empty to full. A full square is stiff, and a square that is half full is much less than half as stiff. So half full squares are a bad deal, and the method learns to avoid them.

Now repeat a few dozen times. Compute how the part bends under the load. Find out which squares do the most work. Turn those dials up and the others down, but keep the total material fixed. Smooth the result a little, so that tiny patterns do not appear. At the end, the full squares show a structure of bars and holes that carries the load well.

The problem

The domain is a grid of n=nxnyn = n_x n_y unit square elements with bilinear (Q4) plane stress elements. The element stiffness matrix for E=1E = 1 is k0k_0, an 8×88 \times 8 matrix that depends on Poisson's ratio ν\nu. Given a load vector ff, supports that remove all rigid body motions, a volume fraction vv and a power p≥1p \ge 1, the method looks for densities x=(xe)x = (x_e) that solve

min⁡x c(x)=fTu(x)subject toK(x) u=f,∑exe≤v n,xmin⁡≤xe≤1,\min_x\ c(x) = f^{\mathsf T} u(x) \quad\text{subject to}\quad K(x)\, u = f,\quad \sum_e x_e \le v\, n,\quad x_{\min} \le x_e \le 1,

with K(x)=∑exepKeK(x) = \sum_e x_e^p K_e, where KeK_e is k0k_0 placed at the degrees of freedom of element ee. The compliance cc is the work done by the load, and a small compliance is a stiff structure. The lower bound xmin⁡=10−3x_{\min} = 10^{-3} keeps K(x)K(x) positive definite.

The sensitivity. Differentiate Ku=fK u = f: K ∂u=−(∂K) uK\,\partial u = -(\partial K)\,u. Then ∂c=fT∂u=−uT(∂K) u\partial c = f^{\mathsf T} \partial u = -u^{\mathsf T} (\partial K)\, u, so

∂c∂xe=−p xep−1 ueTk0 ue≤0,\frac{\partial c}{\partial x_e} = -p\, x_e^{p-1}\, u_e^{\mathsf T} k_0\, u_e \le 0,

where ueu_e holds the 8 displacements of element ee. More material never makes the structure softer. No extra linear solve is needed, because compliance is self-adjoint.

The algorithm

The filter uses the weights Hef=max⁡(0,r−dist⁡(e,f))H_{ef} = \max(0, r - \operatorname{dist}(e, f)) between the centers of the elements, with rr the filter radius rmin⁡r_{\min} in element widths. The update uses a move limit m=0.2m = 0.2 and a damping power η=1/2\eta = 1/2.

  1. SIMP(grid, f, supports, v, p, r)
  2. 1x_e ← v for every element e
  3. 2for it = 1 to maxit do
  4. 3solve K(x) u = f; c ← fᵀu ▷ banded LDLᵀ factorization
  5. 4record c
  6. 5dc_e ← −p x_e^(p−1) u_eᵀ k₀ u_e
  7. 6dc_e ← Σ_f H_ef x_f dc_f / (x_e Σ_f H_ef) ▷ sensitivity filter
  8. 7x' ← OC(x, dc)
  9. 8change ← max_e |x'_e − x_e|
  10. 9x ← x'; if change < tol then stop
  11. 10return x
  12. OC(x, dc) ▷ V = v n
  13. 11l1 ← 0; l2 ← 1
  14. 12while Σ TRIAL(l2) > V do (l1, l2) ← (l2, 2 l2)
  15. 13repeat at most 100 times
  16. 14λ ← (l1 + l2) / 2
  17. 15if Σ TRIAL(λ) > V then l1 ← λ else l2 ← λ
  18. 16if l2 − l1 ≤ tol_λ · l2 then stop
  19. 17return TRIAL(l2)
  20. TRIAL(λ)
  21. 18x'_e ← max(x_min, x_e − m, min(1, x_e + m, x_e (−dc_e / λ)^η)) for every e

The rule of line L18 comes from the optimality condition. At an optimum with xmin⁡<xe<1x_{\min} < x_e < 1, the KKT conditions say −∂c/∂xe=λ-\partial c / \partial x_e = \lambda: every element that is not at a bound does the same work per unit of material. So Be=−dce/λB_e = -dc_e / \lambda should be 1. If Be>1B_e > 1 the element is worth more than it costs and its density grows, and if Be<1B_e < 1 it shrinks. The power η\eta and the move limit make the steps small enough to be stable.

The volume of TRIAL(λ)(\lambda) never increases with λ\lambda. Line L12 doubles l2l_2 until the trial design meets the volume bound, and lines L13 to L16 are a bisection that keeps l2l_2 feasible. The result is the trial design at l2l_2, so it always meets the bound. The stop test of line L16 is relative, because the scale of dcdc, and so of λ\lambda, changes with the load and the mesh. The code of Sigmund (2001) starts with l2=105l_2 = 10^5 and uses an absolute tolerance, which works for his scaling only.

The filter. Line L6 is the mesh-independency filter of Sigmund (2001). It replaces each sensitivity by a weighted average over the elements within distance rr. With r≤1r \le 1 only the element itself has a positive weight and the filter does nothing. The filter is a heuristic: the filtered values are not the derivatives of any function that the method minimizes.

Example

The half MBB beam. This is the test case of Sigmund (2001). A beam on two supports carries a load at the middle of its top edge. By symmetry only the left half is modeled: the left edge cannot move in xx, the bottom right corner rests on a roller, and a unit load points down at the top left corner. With 24×824 \times 8 elements, v=1/2v = 1/2, p=3p = 3, r=1.5r = 1.5 and ν=0.3\nu = 0.3, the code of this page stops after 41 iterations, when no density changes by more than 0.01. The elements with xe>1/2x_e > 1/2 are:

#################.......
#####......#######......
..###........##..##.....
...###......##....###...
....###...###......###..
.....###.###.........##.
###########..........###
########################

The top and bottom rows are the flanges of a truss, and the diagonals carry the shear to the roller at the right.

iteration 1 2 3 4 5 6 41
compliance 975.83 585.85 427.58 366.15 347.62 338.64 264.72

The run takes about 0.6 s in pure Python.

What the filter does. On a 30×1030 \times 10 half MBB beam with v=1/2v = 1/2 and at most 100 iterations, the test counts the 2×22 \times 2 blocks of elements that form a checkerboard (solid and void on the diagonals):

filter radius rr iterations final compliance checkerboard blocks
0.9 (no filter) 100 190.9 51
1.5 72 225.6 0
2.0 35 265.0 0

Without the filter the compliance is lowest, but the design is full of checkerboards. They are an error of the Q4 element, which makes a checkerboard look stiffer than it is. They are not a better structure. A larger radius gives thicker members and a larger compliance. These are measurements on this one case.

Against brute force. A 5×25 \times 2 cantilever is clamped on the left edge and loaded down at the bottom right corner. There are (105)=252\binom{10}{5} = 252 designs with 5 solid elements and 5 elements at xmin⁡x_{\min}. The test computes all of them: the best is the bottom row of 5 elements, with compliance 347.38. Every other design has a compliance above 10910^9, because its solid elements do not form a stiff path from the load to the clamp, and only the elements at xmin⁡x_{\min} hold it. SIMP with p=3p = 3, r=1.5r = 1.5 and the same volume stops at a gray design with compliance about 388, about 12% worse. SIMP with p=1p = 1 and no filter reaches about 107. That value is lower than every 0/1 design, as it must be, because with p=1p = 1 the problem is convex and the 0/1 designs are feasible points of it.

Correctness

SIMP is a heuristic for the 0/1 problem, and the statements that can be proved are about the steps. With xmin⁡<v≤1x_{\min} < v \le 1 and supports that remove the rigid body motions, every iterate satisfies xmin⁡≤xe≤1x_{\min} \le x_e \le 1 and ∑exe≤vn\sum_e x_e \le v n. The stiffness matrix is positive definite, because every element has a stiffness of at least xmin⁡px_{\min}^p, so line L3 is defined. The sensitivities are at most 0, the filter keeps that sign, and the volume of TRIAL(λ)(\lambda) decreases with λ\lambda. So line L12 stops, the bisection keeps a feasible l2l_2, and OC returns a feasible design. The main loop stops after at most maxit iterations.

If the update has a fixed point and r≤1r \le 1, the fixed point satisfies the KKT conditions of the penalized problem: −∂c/∂xe=λ-\partial c/\partial x_e = \lambda where xmin⁡<xe<1x_{\min} < x_e < 1, at most λ\lambda where xe=xmin⁡x_e = x_{\min}, and at least λ\lambda where xe=1x_e = 1. For p=1p = 1 the compliance is a convex function of xx, so such a point is a global minimum. For p>1p > 1 it is only a stationary point. With the filter the fixed point satisfies the same conditions for the filtered values, which are not true derivatives. The full proof is below. The convergence of the iterates themselves is not proved here, and the code stops on a tolerance.

Proof: The SIMP iteration keeps feasible designs, its OC update stops, and its fixed points are KKT pointsfull

Setting. The grid has nn elements. The element matrix k0k_0 is symmetric positive semidefinite, because k0=∫BTDBk_0 = \int B^{\mathsf T} D B with DD positive definite. The supports fix enough degrees of freedom that ∑eseKe\sum_e s_e K_e, restricted to the free degrees of freedom, is positive definite whenever every se>0s_e > 0. Let 0<xmin⁡<v≤10 < x_{\min} < v \le 1, p≥1p \ge 1, m>0m > 0, η>0\eta > 0, V=vnV = v n, and let r>0r > 0 be the filter radius. The proof uses exact real arithmetic.

Claim.

  1. Every design xx that the method computes satisfies xmin⁡≤xe≤1x_{\min} \le x_e \le 1 and ∑exe≤V\sum_e x_e \le V, and every linear system of line L3 has a unique solution.
  2. Each call of OC stops, and the main loop stops after at most maxit iterations.
  3. If a design xx with ∑exe=V\sum_e x_e = V satisfies x=TRIAL(λ)x = \text{TRIAL}(\lambda) for some λ>0\lambda > 0, with dcdc computed from xx itself and r≤1r \le 1, then xx satisfies the KKT conditions of the penalized problem with the multiplier λ\lambda.
  4. For p=1p = 1 the compliance is convex in xx, so such a point is a global minimum of the problem with p=1p = 1.

Step 1 (signs). Let xx satisfy xmin⁡≤xe≤1x_{\min} \le x_e \le 1. Then K(x)=∑exepKeK(x) = \sum_e x_e^p K_e has all scales xep≥xmin⁡p>0x_e^p \ge x_{\min}^p > 0, so it is positive definite and line L3 has a unique solution uu. Line L5 gives dce=−p xep−1 ueTk0ue≤0dc_e = -p\,x_e^{p-1}\, u_e^{\mathsf T} k_0 u_e \le 0, because k0k_0 is positive semidefinite. In line L6, Hef≥0H_{ef} \ge 0 for all ff and Hee=r>0H_{ee} = r > 0, so the denominator xe∑fHefx_e \sum_f H_{ef} is positive and the numerator ∑fHefxf dcf\sum_f H_{ef} x_f\, dc_f is at most 0. So the filtered values also satisfy dce≤0dc_e \le 0.

Step 2 (TRIAL is monotone and stays in the box). Fix xx in the box and dc≤0dc \le 0. For λ>0\lambda > 0 let ge(λ)=xe(−dce/λ)ηg_e(\lambda) = x_e(-dc_e/\lambda)^\eta and

Te(λ)=max⁡(xmin⁡, xe−m, min⁡(1, xe+m, ge(λ))).T_e(\lambda) = \max\bigl(x_{\min},\ x_e - m,\ \min(1,\ x_e + m,\ g_e(\lambda))\bigr).

The function geg_e does not increase with λ\lambda, and min and max are nondecreasing in each argument, so TeT_e and S(λ)=∑eTe(λ)S(\lambda) = \sum_e T_e(\lambda) do not increase with λ\lambda. Each TeT_e is continuous for λ>0\lambda > 0, so SS is too. Each of the three arguments of the outer max is at most 1 (since xmin⁡<1x_{\min} < 1 and xe−m<1x_e - m < 1), so Te≤1T_e \le 1, and Te≥xmin⁡T_e \ge x_{\min}. Also Te≥xe−mT_e \ge x_e - m and Te≤max⁡(xmin⁡,xe−m,xe+m)=xe+mT_e \le \max(x_{\min}, x_e - m, x_e + m) = x_e + m, so the move limit holds.

Step 3 (line L12 stops). Let Le=max⁡(xmin⁡,xe−m)L_e = \max(x_{\min}, x_e - m). Then Le≤xeL_e \le x_e, with equality only if xe=xmin⁡x_e = x_{\min}. If some xe>xmin⁡x_e > x_{\min}, then ∑eLe<∑exe≤V\sum_e L_e < \sum_e x_e \le V. If every xe=xmin⁡x_e = x_{\min}, then ∑eLe=nxmin⁡<nv=V\sum_e L_e = n x_{\min} < n v = V. So ∑eLe<V\sum_e L_e < V in both cases. Let Λ=max⁡e(−dce)(xe/xmin⁡)1/η\Lambda = \max_e (-dc_e)(x_e / x_{\min})^{1/\eta}. For λ≥Λ\lambda \ge \Lambda and every ee, ge(λ)≤xe⋅xmin⁡/xe=xmin⁡g_e(\lambda) \le x_e \cdot x_{\min}/x_e = x_{\min} (and ge=0g_e = 0 if dce=0dc_e = 0), so the inner min is at most xmin⁡x_{\min} and Te(λ)=LeT_e(\lambda) = L_e. Hence S(λ)<VS(\lambda) < V for λ≥Λ\lambda \ge \Lambda. Line L12 sets l2=2jl_2 = 2^j after jj doublings, so it stops after at most max⁡(0,⌈log⁡2Λ⌉)\max(0, \lceil \log_2 \Lambda \rceil) doublings. When it stops, S(l2)≤VS(l_2) \le V, and l1=0l_1 = 0 or S(l1)>VS(l_1) > V.

Step 4 (the bisection keeps a feasible end). Lines L13 to L16 keep the invariant 0≤l1<l20 \le l_1 < l_2 and S(l2)≤VS(l_2) \le V. Line L14 picks λ\lambda strictly between l1l_1 and l2l_2, so λ>0\lambda > 0. If S(λ)>VS(\lambda) > V, line L15 moves l1l_1 and leaves l2l_2. Otherwise it sets l2=λl_2 = \lambda, and then S(l2)≤VS(l_2) \le V. The loop runs at most 100 times. Line L17 returns T(l2)T(l_2), so by Step 2 the result is in the box, within the move limit, and meets the volume bound. If l1>0l_1 > 0 at the end, then S(l1)>V≥S(l2)S(l_1) > V \ge S(l_2), and by continuity some λ∗∈(l1,l2]\lambda^* \in (l_1, l_2] has S(λ∗)=VS(\lambda^*) = V, so l2l_2 is within the relative distance tolλ_\lambda of a multiplier that makes the volume bound tight when line L16 ended the loop.

Step 5 (claims 1 and 2). Line L1 sets xe=vx_e = v, which is in the box with ∑exe=V\sum_e x_e = V. By Steps 1 to 4, if the current design is feasible, then the design of line L9 is feasible. By induction every design is feasible, and line L3 is always solvable. Each OC call stops by Steps 3 and 4, and the loop of line L2 runs at most maxit times.

Step 6 (claim 3). With r≤1r \le 1, every f≠ef \ne e has dist⁡(e,f)≥1≥r\operatorname{dist}(e, f) \ge 1 \ge r, so Hef=0H_{ef} = 0 and line L6 returns dcedc_e unchanged. So dce=∂c/∂xedc_e = \partial c / \partial x_e. Let x=T(λ)x = T(\lambda). Since xe−m<xex_e - m < x_e, the outer max equals xex_e in one of two ways.

  • xe=xmin⁡x_e = x_{\min} and min⁡(1,xe+m,ge)≤xmin⁡\min(1, x_e + m, g_e) \le x_{\min}, or xe=min⁡(1,xe+m,ge)x_e = \min(1, x_e + m, g_e).
  • In the second way, xe+m>xex_e + m > x_e, so xe=1≤gex_e = 1 \le g_e or xe=gex_e = g_e.

If xmin⁡<xe<1x_{\min} < x_e < 1, then xe=ge=xe(−dce/λ)ηx_e = g_e = x_e(-dc_e/\lambda)^\eta, and since xe>0x_e > 0, −dce=λ-dc_e = \lambda. If xe=xmin⁡x_e = x_{\min}, then ge≤xmin⁡=xeg_e \le x_{\min} = x_e in both ways, because the bounds 1 and xe+mx_e + m are above xmin⁡x_{\min}, so (−dce/λ)η≤1(-dc_e/\lambda)^\eta \le 1 and −dce≤λ-dc_e \le \lambda. If xe=1x_e = 1, then ge≥1g_e \ge 1, so −dce≥λ-dc_e \ge \lambda. Now set μe=λ+dce≥0\mu_e = \lambda + dc_e \ge 0 where xe=xmin⁡x_e = x_{\min}, νe=−dce−λ≥0\nu_e = -dc_e - \lambda \ge 0 where xe=1x_e = 1, and μe=νe=0\mu_e = \nu_e = 0 elsewhere. Then

∂c∂xe+λ−μe+νe=0,μe(xe−xmin⁡)=0,νe(1−xe)=0,λ(∑exe−V)=0,\frac{\partial c}{\partial x_e} + \lambda - \mu_e + \nu_e = 0, \quad \mu_e (x_e - x_{\min}) = 0, \quad \nu_e (1 - x_e) = 0, \quad \lambda \Bigl(\sum_e x_e - V\Bigr) = 0,

with λ,μ,ν≥0\lambda, \mu, \nu \ge 0. These are the KKT conditions of min⁡c(x)\min c(x) subject to ∑exe≤V\sum_e x_e \le V and xmin⁡≤xe≤1x_{\min} \le x_e \le 1.

Step 7 (claim 4). For a positive definite KK and every ff, fTK−1f=max⁡u (2fTu−uTKu)f^{\mathsf T} K^{-1} f = \max_u\, (2 f^{\mathsf T} u - u^{\mathsf T} K u), because the concave quadratic on the right has its maximum at u=K−1fu = K^{-1} f. For p=1p = 1, K(x)=∑exeKeK(x) = \sum_e x_e K_e is linear in xx, so for each fixed uu the function x↦2fTu−uTK(x)ux \mapsto 2 f^{\mathsf T} u - u^{\mathsf T} K(x) u is affine. A pointwise maximum of affine functions is convex, so c(x)c(x) is convex on the box. The constraints are linear, so a KKT point of a convex problem is a global minimum. The same formula shows that cc does not increase when KK grows in the positive semidefinite order, because each uTKuu^{\mathsf T} K u grows.

Remark. The claims hold in exact arithmetic. In floating point the sums of Steps 3 and 4 are rounded, and the test checks the volume bound with a relative tolerance of 10−1210^{-12}. Claim 3 is about exact fixed points. The code stops when no density changes by more than a tolerance, so its result is only near such a point. With r>1r > 1 the same argument gives the conditions for the filtered values, which are not the derivatives of cc. For p>1p > 1 the function cc is not convex in general, and a KKT point need not be a global minimum. ■\blacksquare

Complexity

Number the nodes along the short side, with hh elements across it. Then the stiffness matrix has a half bandwidth of 2h+52h + 5, and the banded LDLᵀ factorization of about 2n2n unknowns takes O(nh2)O(n h^2) time and O(nh)O(n h) space. The filter has O(r2)O(r^2) weights per element. The OC update calls TRIAL O(log⁡λ+100)O(\log \lambda + 100) times at O(n)O(n) each. So one iteration takes O(n(h2+r2))O(n(h^2 + r^2)) time, and kk iterations take O(k n(h2+r2))O(k\, n (h^2 + r^2)).

The number of iterations is not bounded by a formula. It is measured: 41 on the 24×824 \times 8 beam above. Large models replace the direct solver by an iterative one, such as the conjugate gradient method with a multigrid preconditioner, and the solve is then most of the cost.

Properties

  • Feasible iterates. Every design meets the volume bound and the box bounds.
  • Monotone sensitivities. More material in any element never increases the compliance.
  • Convex for p=1p = 1. The compliance fTK(x)−1ff^{\mathsf T} K(x)^{-1} f is convex when KK is linear in xx. Then the method solves a convex problem, but the optimum is gray.
  • Local for p>1p > 1. The penalized problem has many local minima, and the result depends on pp, rr, the start and the mesh.
  • Not exact. The answer is a density field that is close to 0/1, not a proved optimum, and the final design is a threshold of it.
  • Simple. The OC update needs one solve per iteration and no line search.

Variants and improvements

  • Modified SIMP. Use E=Emin⁡+xep(E0−Emin⁡)E = E_{\min} + x_e^p (E_0 - E_{\min}) with 0≤xe≤10 \le x_e \le 1 and a small Emin⁡E_{\min}. Void elements then have an exact density 0. The 88 line code of Andreassen and coauthors (2011) uses this form.
  • Density filter. Filter the densities instead of the sensitivities, and use the filtered density in the model. Then the sensitivities are exact derivatives of a well defined problem.
  • Projection. A smooth Heaviside step on the filtered densities gives crisp 0/1 designs with a minimum member size.
  • Continuation. Start with p=1p = 1 and increase pp slowly, which often finds better local optima.
  • Other updates. The OC rule needs sensitivities of one sign and one constraint. For several constraints, or sensitivities that change sign as in compliant mechanisms, the method of moving asymptotes of Svanberg (1987) is the usual choice.
  • The choice of pp. Bendsøe and Sigmund relate the power to the bounds on composite materials of Hashin and Shtrikman, so that every gray density has a physical meaning. In 2D with ν=1/3\nu = 1/3 this asks for p≥3p \ge 3.
  • Manufacturing constraints. Overhang limits for additive manufacturing (see support structure generation), minimum and maximum member sizes, and symmetry.

When to use it

Use SIMP for minimum compliance and similar problems on a fixed mesh, when a density field is a good model and the result will be turned into a part afterwards. It is easy to code, robust, and fast enough for large 3D models with an iterative solver. If a crisp boundary is needed during the optimization, for example for loads that follow the surface, consider level set topology optimization, which moves a boundary instead of densities.

Pitfalls

  • No filter. Without a filter or a projection, the result has checkerboards and depends on the mesh: a finer mesh gives finer members. The 30×1030 \times 10 case above shows 51 checkerboard blocks.
  • A zero lower bound. With xmin⁡=0x_{\min} = 0 in the classic form, K(x)K(x) can be singular, and the filter divides by xex_e.
  • An absolute bisection tolerance. The multiplier scales with the compliance. A fixed interval and an absolute tolerance can stop too early or never reach the right value.
  • Reading gray as material. The final design has gray elements. A threshold at 1/21/2 can change the compliance much, so compute the compliance of the 0/1 design that is built.
  • Trusting the optimum. The brute force case above shows a SIMP result 12% worse than the best 0/1 design of the same volume. On large meshes there is no way to check this.
  • Wrong sign. Compliance sensitivities are at most 0. Code that uses ++ in line L5 moves material away from where it is needed.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

fem2d.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the cm1 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Plane stress finite elements on a grid of unit square bilinear (Q4) elements.

The grid has nelx x nely elements. Node (i, j), with 0 <= i <= nelx and
0 <= j <= nely, is at the point (i, j) and has the number i (nely + 1) + j.
Its degrees of freedom are 2 n (x displacement) and 2 n + 1 (y displacement).
Element (ex, ey) has the number ex nely + ey and the nodes (ex, ey),
(ex + 1, ey), (ex + 1, ey + 1), (ex, ey + 1), counterclockwise.

The helper has no optimization in it. It builds the element stiffness matrix
exactly, assembles the global matrix with one factor per element, and solves
it with a banded LDL^T factorization that works with float or Fraction.
"""

from fractions import Fraction
from operator import mul


def q4_stiffness(nu):
    """The 8 x 8 stiffness matrix of a unit square Q4 element for E = 1.

    The integrand B^T D B is a polynomial of degree at most 2 in each
    coordinate, so the 3 x 3 Simpson rule is exact, and the result is an
    exact Fraction matrix.
    """
    nu = Fraction(nu)
    c = 1 / (1 - nu * nu)
    d = [[c, c * nu, 0], [c * nu, c, 0], [0, 0, c * (1 - nu) / 2]]
    rule = [(Fraction(0), Fraction(1, 6)), (Fraction(1, 2), Fraction(2, 3)), (Fraction(1), Fraction(1, 6))]
    corners = [(0, 0), (1, 0), (1, 1), (0, 1)]
    ke = [[Fraction(0)] * 8 for _ in range(8)]
    for x, wx in rule:
        for y, wy in rule:
            b = [[Fraction(0)] * 8 for _ in range(3)]
            for a, (cx, cy) in enumerate(corners):
                fx, gx = (x, 1) if cx else (1 - x, -1)
                fy, gy = (y, 1) if cy else (1 - y, -1)
                dx, dy = gx * fy, fx * gy  # derivatives of N_a = fx fy
                b[0][2 * a] = dx
                b[1][2 * a + 1] = dy
                b[2][2 * a] = dy
                b[2][2 * a + 1] = dx
            db = [[sum(d[r][s] * b[s][k] for s in range(3)) for k in range(8)] for r in range(3)]
            for i in range(8):
                for j in range(8):
                    ke[i][j] += wx * wy * sum(b[r][i] * db[r][j] for r in range(3))
    return ke


def node(nely, i, j):
    return i * (nely + 1) + j


def element_dofs(nelx, nely):
    """The 8 degrees of freedom of every element, in element order."""
    out = []
    for ex in range(nelx):
        for ey in range(nely):
            ns = [node(nely, ex, ey), node(nely, ex + 1, ey), node(nely, ex + 1, ey + 1), node(nely, ex, ey + 1)]
            out.append([k for n in ns for k in (2 * n, 2 * n + 1)])
    return out


def element_center(nely, e):
    ex, ey = divmod(e, nely)
    return ex + 0.5, ey + 0.5


def ldl_band(rows, b):
    """Factor a symmetric positive definite band matrix as L D L^T.

    rows[i] holds the entries K[i][s], ..., K[i][i] with s = max(0, i - b).
    Returns (low, diag): low[i] holds L[i][s .. i-1] and diag holds D.
    """
    m = len(rows)
    low, diag = [], []
    for i in range(m):
        s = max(0, i - b)
        a = rows[i]
        w = []  # w[l - s] = L[i][l] D[l]
        li = []
        for j in range(s, i):
            sj = max(0, j - b)
            t = a[j - s] - sum(map(mul, w[: j - s], low[j][s - sj: j - sj]))
            w.append(t)
            li.append(t / diag[j])
        diag.append(a[i - s] - sum(map(mul, w, li)))
        low.append(li)
    return low, diag


def ldl_solve(low, diag, f, b):
    m = len(diag)
    y = list(f)
    for i in range(m):
        s = max(0, i - b)
        y[i] -= sum(map(mul, low[i], y[s:i]))
    z = [y[i] / diag[i] for i in range(m)]
    for i in range(m - 1, -1, -1):
        s = max(0, i - b)
        zi = z[i]
        for k, lik in enumerate(low[i]):
            z[s + k] -= lik * zi
    return z


def solve(nelx, nely, ke, scale, force, fixed):
    """Solve K u = f with K = sum_e scale[e] ke_e and u = 0 on the fixed dofs.

    force is a dict {dof: value}; returns the full displacement list.
    """
    ndof = 2 * (nelx + 1) * (nely + 1)
    fixed = set(fixed)
    index, free = {}, []
    for k in range(ndof):
        if k not in fixed:
            index[k] = len(free)
            free.append(k)
    edofs = element_dofs(nelx, nely)
    b = 2 * nely + 5
    zero = 0 * scale[0]
    rows = [[zero] * (min(i, b) + 1) for i in range(len(free))]
    for e, dofs in enumerate(edofs):
        se = scale[e]
        for p in range(8):
            gi = index.get(dofs[p])
            if gi is None:
                continue
            row, s = rows[gi], max(0, gi - b)
            for q in range(8):
                gj = index.get(dofs[q])
                if gj is not None and gj <= gi:
                    row[gj - s] += se * ke[p][q]
    f = [force.get(k, zero) for k in free]
    low, diag = ldl_band(rows, b)
    uf = ldl_solve(low, diag, f, b)
    u = [zero] * ndof
    for k, v in zip(free, uf):
        u[k] = v
    return u


def element_energies(nelx, nely, ke, u):
    """u_e^T ke u_e for every element (twice the strain energy for E = 1)."""
    out = []
    for dofs in element_dofs(nelx, nely):
        ue = [u[k] for k in dofs]
        out.append(sum(ue[p] * sum(map(mul, ke[p], ue)) for p in range(8)))
    return out


def dense_solve(a, f):
    """Gaussian elimination with partial pivoting, a reference for the tests."""
    n = len(f)
    m = [list(a[i]) + [f[i]] for i in range(n)]
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        m[c], m[p] = m[p], m[c]
        for r in range(c + 1, n):
            t = m[r][c] / m[c][c]
            if t:
                for k in range(c, n + 1):
                    m[r][k] -= t * m[c][k]
    x = [0] * n
    for r in range(n - 1, -1, -1):
        x[r] = (m[r][n] - sum(m[r][k] * x[k] for k in range(r + 1, n))) / m[r][r]
    return x
simp_method.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simp-method/. The authors are listed in prov/KDKEWF.jsonl.

"""SIMP topology optimization with the optimality criteria update, after Sigmund (2001).

Each element e has a density x_e in [xmin, 1] and the Young's modulus
x_e^p E0 (solid isotropic material with penalization). The method minimizes
the compliance f^T u under the volume bound sum x_e <= f N. Each iteration
solves the finite element model, computes the sensitivities, smooths them with
the mesh-independency filter, and updates the densities with the optimality
criteria (OC) rule, with a bisection on the Lagrange multiplier.

The finite element part is in fem2d.py, a shared helper. Floats are used for
the densities and displacements; the tests state their tolerances.
"""

import math

from fem2d import element_energies, q4_stiffness, solve


def mbb_half_beam(nelx, nely):
    """Loads and supports of the half MBB beam: a unit load down at the top left,
    symmetry (no x motion) on the left edge, and a roller at the bottom right."""
    top_left = nely  # node (0, nely)
    force = {2 * top_left + 1: -1.0}
    fixed = [2 * j for j in range(nely + 1)]  # x dofs of the left edge
    fixed.append(2 * (nelx * (nely + 1)) + 1)  # y dof of node (nelx, 0)
    return force, fixed


def filter_weights(nelx, nely, rmin):
    """H_ef = max(0, rmin - dist(e, f)) for the neighbours f of each element e."""
    n = nelx * nely
    r = int(math.ceil(rmin))
    out = []
    for e in range(n):
        ex, ey = divmod(e, nely)
        row = []
        for fx in range(max(0, ex - r), min(nelx, ex + r + 1)):
            for fy in range(max(0, ey - r), min(nely, ey + r + 1)):
                h = rmin - math.hypot(ex - fx, ey - fy)
                if h > 0:
                    row.append((fx * nely + fy, h))
        out.append(row)
    return out


def filter_sensitivities(weights, x, dc):
    """dc~_e = sum_f H_ef x_f dc_f / (x_e sum_f H_ef)."""
    return [sum(h * x[f] * dc[f] for f, h in row) / (x[e] * sum(h for _, h in row))
            for e, row in enumerate(weights)]


def oc_trial(x, dc, lam, move, xmin, eta):
    """The OC fixed point step for the multiplier lam, inside the move limits."""
    return [max(xmin, xi - move, min(1.0, xi + move, xi * (max(0.0, -d) / lam) ** eta))  # @line L18
            for xi, d in zip(x, dc)]


def oc_update(x, dc, volfrac, move=0.2, xmin=1e-3, eta=0.5, tol=1e-9, steps=100):
    """The optimality criteria update with a bisection on the multiplier.

    The volume of oc_trial(lam) does not increase with lam. The loop keeps
    l2 feasible (volume at most volfrac N) and l1 infeasible or 0, and it
    returns the trial design at l2, so the result meets the volume bound.
    """
    bound = volfrac * len(x)
    l1, l2 = 0.0, 1.0  # @line L11
    while sum(oc_trial(x, dc, l2, move, xmin, eta)) > bound:  # @line L12
        l1, l2 = l2, 2 * l2
    for _ in range(steps):  # @line L13
        lam = (l1 + l2) / 2  # @line L14
        if sum(oc_trial(x, dc, lam, move, xmin, eta)) > bound:  # @line L15
            l1 = lam
        else:
            l2 = lam
        if l2 - l1 <= tol * l2:  # @line L16
            break
    return oc_trial(x, dc, l2, move, xmin, eta)  # @line L17


def compliance(nelx, nely, ke, x, p, force, fixed):
    u = solve(nelx, nely, ke, [xi ** p for xi in x], force, fixed)
    return sum(v * u[k] for k, v in force.items()), u


def simp(nelx, nely, volfrac, p=3, rmin=1.5, force=None, fixed=None, nu=0.3,
         maxit=60, tol=0.01, move=0.2, xmin=1e-3):
    """Return (x, history) with the final densities and the compliance of each iteration."""
    if force is None:
        force, fixed = mbb_half_beam(nelx, nely)
    ke = [[float(v) for v in row] for row in q4_stiffness(nu)]
    weights = filter_weights(nelx, nely, rmin)
    x = [float(volfrac)] * (nelx * nely)  # @line L1
    history = []
    for _ in range(maxit):  # @line L2
        c, u = compliance(nelx, nely, ke, x, p, force, fixed)  # @line L3
        history.append(c)  # @line L4
        energy = element_energies(nelx, nely, ke, u)
        dc = [-p * xi ** (p - 1) * en for xi, en in zip(x, energy)]  # @line L5
        dc = filter_sensitivities(weights, x, dc)  # @line L6
        xnew = oc_update(x, dc, volfrac, move, xmin)  # @line L7
        change = max(abs(a - b) for a, b in zip(xnew, x))  # @line L8
        x = xnew
        if change < tol:  # @line L9
            break
    return x, history  # @line L10


def show(x, nelx, nely):
    """Rows from top to bottom; '#' for x > 0.5."""
    return "\n".join("".join("#" if x[ex * nely + ey] > 0.5 else "." for ex in range(nelx))
                     for ey in range(nely - 1, -1, -1))


if __name__ == "__main__":
    x, hist = simp(24, 8, 0.5)
    print(show(x, 24, 8))
    print("iterations", len(hist), "first", round(hist[0], 3), "last", round(hist[-1], 3))
test_simp_method.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simp-method/. The authors are listed in prov/KDKEWF.jsonl.

import itertools
import random
from fractions import Fraction as F

from fem2d import dense_solve, element_dofs, element_energies, node, q4_stiffness, solve
from simp_method import compliance, filter_sensitivities, filter_weights, oc_update, simp

KE = [[float(v) for v in row] for row in q4_stiffness(F(3, 10))]


def cantilever(nelx, nely):
    """Left edge clamped, unit load down at the bottom right node."""
    force = {2 * node(nely, nelx, 0) + 1: -1.0}
    fixed = [k for j in range(nely + 1) for k in (2 * node(nely, 0, j), 2 * node(nely, 0, j) + 1)]
    return force, fixed


def checkerboards(x, nelx, nely):
    count = 0
    for ex in range(nelx - 1):
        for ey in range(nely - 1):
            a, b = x[ex * nely + ey] > 0.5, x[(ex + 1) * nely + ey] > 0.5
            c, d = x[ex * nely + ey + 1] > 0.5, x[(ex + 1) * nely + ey + 1] > 0.5
            count += a == d and b == c and a != b
    return count


def test_element_stiffness_matches_sigmund():
    nu = F(3, 10)
    k = [F(1, 2) - nu / 6, F(1, 8) + nu / 8, -F(1, 4) - nu / 12, -F(1, 8) + 3 * nu / 8,
         -F(1, 4) + nu / 12, -F(1, 8) - nu / 8, nu / 6, F(1, 8) - 3 * nu / 8]
    idx = [[0, 1, 2, 3, 4, 5, 6, 7], [1, 0, 7, 6, 5, 4, 3, 2], [2, 7, 0, 5, 6, 3, 4, 1], [3, 6, 5, 0, 7, 2, 1, 4],
           [4, 5, 6, 7, 0, 1, 2, 3], [5, 4, 3, 2, 1, 0, 7, 6], [6, 3, 4, 1, 2, 7, 0, 5], [7, 2, 1, 4, 3, 6, 5, 0]]
    assert q4_stiffness(nu) == [[k[idx[i][j]] / (1 - nu * nu) for j in range(8)] for i in range(8)]
    assert q4_stiffness(nu)[0][0] == F(45, 91)


def test_banded_solver_against_dense_elimination():
    rng = random.Random(1)
    ke = q4_stiffness(F(1, 4))
    for nelx, nely in [(2, 1), (3, 2), (2, 3)]:
        scale = [F(rng.randint(1, 9), rng.randint(1, 4)) for _ in range(nelx * nely)]
        force, fixed = cantilever(nelx, nely)
        force = {k: F(rng.randint(-5, 5)) for k in range(2 * (nelx + 1) * (nely + 1)) if k not in fixed}
        u = solve(nelx, nely, ke, scale, force, fixed)
        ndof = 2 * (nelx + 1) * (nely + 1)
        big = [[F(0)] * ndof for _ in range(ndof)]
        for e, dofs in enumerate(element_dofs(nelx, nely)):
            for p in range(8):
                for q in range(8):
                    big[dofs[p]][dofs[q]] += scale[e] * ke[p][q]
        free = [k for k in range(ndof) if k not in set(fixed)]
        ref = dense_solve([[big[i][j] for j in free] for i in free], [force.get(i, F(0)) for i in free])
        assert [u[k] for k in free] == ref  # exact equality in Fraction
        assert all(u[k] == 0 for k in fixed)


def test_patch_test_uniform_tension():
    # Plane stress bar under the stress sigma_x = 1: u_x = x, u_y = -nu y for E = 1.
    nu = F(1, 3)
    ke = q4_stiffness(nu)
    nelx, nely = 3, 2
    force = {}
    for j in range(nely + 1):  # consistent nodal forces of a unit traction on the right edge
        force[2 * node(nely, nelx, j)] = F(1, 2) if j in (0, nely) else F(1)
    fixed = [2 * node(nely, 0, j) for j in range(nely + 1)] + [1]  # u_x = 0 at x = 0, u_y = 0 at the origin
    u = solve(nelx, nely, ke, [F(1)] * (nelx * nely), force, fixed)
    for i in range(nelx + 1):
        for j in range(nely + 1):
            n = node(nely, i, j)
            assert (u[2 * n], u[2 * n + 1]) == (F(i), -nu * j)


def test_sensitivity_against_finite_differences():
    rng = random.Random(2)
    nelx, nely, p = 4, 3, 3
    force, fixed = cantilever(nelx, nely)
    x = [rng.uniform(0.3, 1.0) for _ in range(nelx * nely)]
    c, u = compliance(nelx, nely, KE, x, p, force, fixed)
    energy = element_energies(nelx, nely, KE, u)
    assert abs(c - sum(xi ** p * en for xi, en in zip(x, energy))) < 1e-9 * c  # c = f.u = u^T K u
    h = 1e-6
    for e in range(nelx * nely):
        xp, xm = list(x), list(x)
        xp[e] += h
        xm[e] -= h
        fd = (compliance(nelx, nely, KE, xp, p, force, fixed)[0] - compliance(nelx, nely, KE, xm, p, force, fixed)[0]) / (2 * h)
        assert abs(fd - (-p * x[e] ** (p - 1) * energy[e])) < 1e-5 * abs(fd)


def test_filter_keeps_uniform_fields_and_identity_for_small_radius():
    w = filter_weights(5, 4, 1.5)
    x = [0.4] * 20
    assert all(abs(v + 2.0) < 1e-12 for v in filter_sensitivities(w, x, [-2.0] * 20))
    rng = random.Random(3)
    dc = [-rng.random() for _ in range(20)]
    xs = [rng.uniform(0.1, 1) for _ in range(20)]
    assert all(abs(a - b) < 1e-12 for a, b in zip(filter_sensitivities(filter_weights(5, 4, 0.9), xs, dc), dc))


def test_oc_update_meets_the_volume_bound_and_stops():
    rng = random.Random(4)
    for scale in (1e-6, 1.0, 1e6):
        for _ in range(50):
            n = rng.randint(2, 30)
            x = [rng.uniform(1e-3, 1.0) for _ in range(n)]
            volfrac = rng.uniform(sum(x) / n, 1.0)  # the old design is feasible
            dc = [-scale * rng.random() for _ in range(n)]
            xnew = oc_update(x, dc, volfrac)
            assert sum(xnew) <= volfrac * n * (1 + 1e-12)
            assert all(max(1e-3, a - 0.2) - 1e-12 <= b <= min(1.0, a + 0.2) + 1e-12 for a, b in zip(x, xnew))
            # brute force on the multiplier: a slightly smaller lam breaks the bound,
            # unless every element is already at its upper move limit
            upper = sum(min(1.0, a + 0.2) for a in x)
            if upper > volfrac * n * (1 + 1e-6):
                assert sum(xnew) > volfrac * n * (1 - 1e-6)
    # zero sensitivities: every lam is feasible, the loop still stops
    x = [0.5] * 4
    assert oc_update(x, [0.0] * 4, 0.9) == [0.3] * 4


def test_oc_on_a_bar_gives_densities_proportional_to_force():
    # A bar of 6 elements in series, clamped at the left, with loads at the nodes.
    # With p = 1, c = sum N_e^2 / x_e and the optimum is x_e = V |N_e| / sum |N|.
    loads = [1.0, 2.0, 0.5, 1.0, 3.0, 1.5]
    normal = [sum(loads[e:]) for e in range(6)]
    volfrac = 0.4
    x = [volfrac] * 6
    for _ in range(80):
        dc = [-(n * n) / (xe * xe) for n, xe in zip(normal, x)]
        x = oc_update(x, dc, volfrac, move=0.2, xmin=1e-3)
    want = [volfrac * 6 * n / sum(normal) for n in normal]
    assert all(abs(a - b) < 1e-6 for a, b in zip(x, want))


def test_p1_is_a_lower_bound_and_brute_force_on_5x2():
    nelx, nely, xmin = 5, 2, 1e-3
    force, fixed = cantilever(nelx, nely)
    best = None
    for solid in itertools.combinations(range(10), 5):  # all 252 designs with 5 solid elements
        x = [1.0 if e in solid else xmin for e in range(10)]
        c = compliance(nelx, nely, KE, x, 3, force, fixed)[0]
        best = c if best is None else min(best, c)
    assert abs(best - 347.3777) < 1e-3  # the bottom row of 5 elements
    volfrac = (5 + 5 * xmin) / 10  # the same volume as a 0/1 design
    x1, h1 = simp(nelx, nely, volfrac, p=1, rmin=0.9, force=force, fixed=fixed, maxit=300, tol=1e-6)
    assert h1[-1] <= best  # p = 1 is convex, so its optimum is below every 0/1 design
    _, u = compliance(nelx, nely, KE, x1, 1, force, fixed)
    energy = element_energies(nelx, nely, KE, u)
    inner = [en for xe, en in zip(x1, energy) if 0.01 < xe < 0.99]
    assert max(inner) - min(inner) < 1e-4 * max(inner)  # KKT: equal energy where xmin < x < 1
    x3, h3 = simp(nelx, nely, volfrac, p=3, rmin=1.5, force=force, fixed=fixed, maxit=300, tol=1e-4)
    # x^3 <= x, so the p = 3 compliance of x3 is at least its p = 1 compliance, which is at least h1.
    assert h1[-1] <= h3[-1] * (1 + 1e-9)
    assert 1.0 < h3[-1] / best < 1.3  # measured: about 388 against 347, a local optimum with gray elements


def test_mbb_beam_filter_removes_checkerboards():
    nelx, nely, volfrac = 30, 10, 0.5
    x0, h0 = simp(nelx, nely, volfrac, rmin=0.9, maxit=100)
    x1, h1 = simp(nelx, nely, volfrac, rmin=1.5, maxit=100)
    for x, h in ((x0, h0), (x1, h1)):
        assert sum(x) <= volfrac * nelx * nely + 1e-6
        assert h[-1] < 0.3 * h[0]
    assert checkerboards(x0, nelx, nely) > 20  # measured 51 without the filter
    assert checkerboards(x1, nelx, nely) == 0

History

Bendsøe and Kikuchi (1988) started material distribution methods with a homogenization model of microstructures with holes. Bendsøe (1989) proposed the simpler model of this page, a density with a stiffness that is a power of it. The name SIMP came into use a few years later, in work by Rozvany, Zhou and coauthors. Sigmund (2001) published a complete Matlab code of 99 lines, with the MBB beam, the optimality criteria update and the sensitivity filter. That code made the method the common start for teaching and research, and the 88 line code of Andreassen, Clausen, Schevenels, Lazarov and Sigmund (2011) made it faster. Commercial tools for design for additive manufacturing use density methods of this kind.

References

  1. Martin P. Bendsøe, Optimal shape design as a material distribution problem, Structural Optimization 1(4), 1989, 193 to 202, the density of each point with the stiffness given as a power of the density, which penalizes intermediate densities
  2. Ole Sigmund, A 99 line topology optimization code written in Matlab, Structural and Multidisciplinary Optimization 21(2), 2001, 120 to 127, the MBB beam problem, the optimality criteria update with move limit 0.2 and damping 1/2, the bisection on the multiplier and the mesh-independency filter
  3. Martin P. Bendsøe and Ole Sigmund, Topology Optimization, Theory, Methods and Applications, Springer, 2003, the chapter on the minimum compliance problem (the SIMP interpolation, the optimality criteria method, checkerboards and filters)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example