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.
- Solves
- Topology optimization
- 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
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 a density between a small and 1. The Young's modulus of the element is with a power , usually . Because of the power, a gray element with costs half the material of a solid one but gives only 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 unit square elements with bilinear (Q4) plane stress elements. The element stiffness matrix for is , an matrix that depends on Poisson's ratio . Given a load vector , supports that remove all rigid body motions, a volume fraction and a power , the method looks for densities that solve
with , where is placed at the degrees of freedom of element . The compliance is the work done by the load, and a small compliance is a stiff structure. The lower bound keeps positive definite.
The sensitivity. Differentiate : . Then , so
where holds the 8 displacements of element . 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 between the centers of the elements, with the filter radius in element widths. The update uses a move limit and a damping power .
SIMP(grid, f, supports, v, p, r)- 1
x_e ← v for every element e - 2
for it = 1 to maxit do - 3
solve K(x) u = f; c ← fᵀu ▷ banded LDLᵀ factorization - 4
record c - 5
dc_e ← −p x_e^(p−1) u_eᵀ k₀ u_e - 6
dc_e ← Σ_f H_ef x_f dc_f / (x_e Σ_f H_ef) ▷ sensitivity filter - 7
x' ← OC(x, dc) - 8
change ← max_e |x'_e − x_e| - 9
x ← x'; if change < tol then stop - 10
return x OC(x, dc) ▷ V = v n- 11
l1 ← 0; l2 ← 1 - 12
while Σ TRIAL(l2) > V do (l1, l2) ← (l2, 2 l2) - 13
repeat at most 100 times - 14
λ ← (l1 + l2) / 2 - 15
if Σ TRIAL(λ) > V then l1 ← λ else l2 ← λ - 16
if l2 − l1 ≤ tol_λ · l2 then stop - 17
return TRIAL(l2) TRIAL(λ)- 18
x'_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 , the KKT conditions say : every element that is not at a bound does the same work per unit of material. So should be 1. If the element is worth more than it costs and its density grows, and if it shrinks. The power and the move limit make the steps small enough to be stable.
The volume of TRIAL never increases with . Line L12 doubles until the trial design meets the volume bound, and lines L13 to L16 are a bisection that keeps feasible. The result is the trial design at , so it always meets the bound. The stop test of line L16 is relative, because the scale of , and so of , changes with the load and the mesh. The code of Sigmund (2001) starts with 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 . With 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 , the bottom right corner rests on a roller, and a unit load points down at the top left corner. With elements, , , and , the code of this page stops after 41 iterations, when no density changes by more than 0.01. The elements with 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 half MBB beam with and at most 100 iterations, the test counts the blocks of elements that form a checkerboard (solid and void on the diagonals):
| filter radius | 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 cantilever is clamped on the left edge and loaded down at the bottom right corner. There are designs with 5 solid elements and 5 elements at . 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 , because its solid elements do not form a stiff path from the load to the clamp, and only the elements at hold it. SIMP with , and the same volume stops at a gray design with compliance about 388, about 12% worse. SIMP with and no filter reaches about 107. That value is lower than every 0/1 design, as it must be, because with 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 and supports that remove the rigid body motions, every iterate satisfies and . The stiffness matrix is positive definite, because every element has a stiffness of at least , so line L3 is defined. The sensitivities are at most 0, the filter keeps that sign, and the volume of TRIAL decreases with . So line L12 stops, the bisection keeps a feasible , and OC returns a feasible design. The main loop stops after at most maxit iterations.
If the update has a fixed point and , the fixed point satisfies the KKT conditions of the penalized problem: where , at most where , and at least where . For the compliance is a convex function of , so such a point is a global minimum. For 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 elements. The element matrix is symmetric positive semidefinite, because with positive definite. The supports fix enough degrees of freedom that , restricted to the free degrees of freedom, is positive definite whenever every . Let , , , , , and let be the filter radius. The proof uses exact real arithmetic.
Claim.
- Every design that the method computes satisfies and , and every linear system of line L3 has a unique solution.
- Each call of OC stops, and the main loop stops after at most maxit iterations.
- If a design with satisfies for some , with computed from itself and , then satisfies the KKT conditions of the penalized problem with the multiplier .
- For the compliance is convex in , so such a point is a global minimum of the problem with .
Step 1 (signs). Let satisfy . Then has all scales , so it is positive definite and line L3 has a unique solution . Line L5 gives , because is positive semidefinite. In line L6, for all and , so the denominator is positive and the numerator is at most 0. So the filtered values also satisfy .
Step 2 (TRIAL is monotone and stays in the box). Fix in the box and . For let and
The function does not increase with , and min and max are nondecreasing in each argument, so and do not increase with . Each is continuous for , so is too. Each of the three arguments of the outer max is at most 1 (since and ), so , and . Also and , so the move limit holds.
Step 3 (line L12 stops). Let . Then , with equality only if . If some , then . If every , then . So in both cases. Let . For and every , (and if ), so the inner min is at most and . Hence for . Line L12 sets after doublings, so it stops after at most doublings. When it stops, , and or .
Step 4 (the bisection keeps a feasible end). Lines L13 to L16 keep the invariant and . Line L14 picks strictly between and , so . If , line L15 moves and leaves . Otherwise it sets , and then . The loop runs at most 100 times. Line L17 returns , so by Step 2 the result is in the box, within the move limit, and meets the volume bound. If at the end, then , and by continuity some has , so is within the relative distance tol of a multiplier that makes the volume bound tight when line L16 ended the loop.
Step 5 (claims 1 and 2). Line L1 sets , which is in the box with . 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 , every has , so and line L6 returns unchanged. So . Let . Since , the outer max equals in one of two ways.
- and , or .
- In the second way, , so or .
If , then , and since , . If , then in both ways, because the bounds 1 and are above , so and . If , then , so . Now set where , where , and elsewhere. Then
with . These are the KKT conditions of subject to and .
Step 7 (claim 4). For a positive definite and every , , because the concave quadratic on the right has its maximum at . For , is linear in , so for each fixed the function is affine. A pointwise maximum of affine functions is convex, so 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 does not increase when grows in the positive semidefinite order, because each 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 . 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 the same argument gives the conditions for the filtered values, which are not the derivatives of . For the function is not convex in general, and a KKT point need not be a global minimum.
Complexity
Number the nodes along the short side, with elements across it. Then the stiffness matrix has a half bandwidth of , and the banded LDLᵀ factorization of about unknowns takes time and space. The filter has weights per element. The OC update calls TRIAL times at each. So one iteration takes time, and iterations take .
The number of iterations is not bounded by a formula. It is measured: 41 on the 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 . The compliance is convex when is linear in . Then the method solves a convex problem, but the optimum is gray.
- Local for . The penalized problem has many local minima, and the result depends on , , 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 with and a small . 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 and increase 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 . 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 this asks for .
- 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 case above shows 51 checkerboard blocks.
- A zero lower bound. With in the classic form, can be singular, and the filter divides by .
- 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 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag KDKEWF Edit this page History Report an error Markdown