Algorithmresearch
Level set topology optimization
Also called level set structural optimization.
Allaire's and Wang's method that moves the boundary of the structure as the zero set of a level set function with the shape derivative as speed.
- Solves
- Topology optimization
- Time
- O(k n (h^2 + n)) worst
- Space
- O(n h) extra
- Where
- h = number of elements across the short side; k = number of iterations; n = number of elements
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Michael Yu Wang, Xiaoming Wang, Dongming Guo, Grégoire Allaire, François Jouve, Anca Maria Toader, 2003
Level set topology optimization represents a structure by a function on the design domain: the structure is the set where , and its boundary is the zero set of . To improve the structure, the method moves the boundary in its normal direction with a speed that comes from the shape derivative of the objective. Moving the boundary with a normal speed is the same as solving a Hamilton-Jacobi equation for , which the level set method does on a fixed grid. Holes can merge, split from the boundary or vanish, so the topology changes without any special code. The response is computed with the finite element method on the same fixed mesh, with a weak ersatz material in the holes. Wang, Wang and Guo (2003) and Allaire, Jouve and Toader (2004) proposed this approach for topology optimization. Unlike the SIMP method, every design has a crisp boundary and no gray elements. The method finds a local optimum that depends on the start, and in 2D it does not create new holes inside solid regions. This page gives a toy version on a grid of square elements, as a demonstration.
In plain words
Think of the part as an island on a map. The coastline is the edge of the part. The method keeps a height for every point of the map: below 0 is land, above 0 is water. The coastline is where the height is 0.
Each round, the method computes how the part bends under its load. Where the material near the coast works hard, the land grows into the water. Where it does little, the water eats into the land. One rule keeps the total land area within its limit. Changing the heights moves the coastline, and two lakes can join, or a lake can open to the sea. Every few rounds, the heights are reset to the distance from the coast, so that they stay well behaved.
The problem
The input is a design domain divided into unit square bilinear plane stress elements, a load , supports, and a bound on the number of solid elements. A design is the set for a level set function with one value per element. The element stiffness is in and outside, the ersatz material, so that is always invertible. The goal is a design with and a small compliance , where .
The shape derivative. Allaire, Jouve and Toader (2004) show that, if a part of the boundary that carries no load moves with the normal velocity , then the compliance changes by
where is twice the strain energy density. For the Lagrangian with a multiplier , the derivative is . So the normal speed is a descent direction: the boundary moves out where the energy density is above , and in where it is below.
The level set equation. If the zero set of moves with the normal speed , with inside, then satisfies the Hamilton-Jacobi equation
The algorithm
The code uses the element energies , where is the element matrix for , as the values of on the element. In the holes it uses the same formula with the ersatz displacement, which extends the speed off the boundary. It smooths once with the mean over the 4 neighbours and divides it by its maximum, so that . The multiplier is , so , and the time step is .
LEVEL-SET-TO(grid, f, supports, B, φ₀) ▷ at most B elements with φ₀ < 0- 1
φ ← φ₀ - 2
for it = 1 to iters do - 3
s_e ← 1 if φ_e < 0, else ε - 4
solve K(s) u = f; c ← fᵀu - 5
w_e ← u_eᵀ k₀ u_e, smoothed and divided by its maximum - 6
ℓ ← the smallest ℓ in [0, 1], by bisection, with #{e : STEP(φ, w − ℓ)_e < 0} ≤ B - 7
φ ← STEP(φ, w − ℓ) - 8
if it is a multiple of R then φ ← REINIT(φ) - 9
return φ STEP(φ, V) ▷ grid spacing 1- 10
D⁻x, D⁺x, D⁻y, D⁺y ← one-sided differences of φ, with edge values repeated - 11
∇⁺ ← (max(D⁻x,0)² + min(D⁺x,0)² + max(D⁻y,0)² + min(D⁺y,0)²)^½; ∇⁻ likewise with max and min swapped - 12
φ_e ← φ_e − Δt (max(V_e, 0) ∇⁺_e + min(V_e, 0) ∇⁻_e) REINIT(φ)- 13
P ← the zero crossings of φ on the segments between the centers of neighbouring elements - 14
φ_e ← min over q ∈ P of |center_e − q|, with the sign of φ_e
Lines L10 to L12 are the first order upwind scheme of Osher and Sethian for the Hamilton-Jacobi equation. Where the boundary moves out (), information comes from the inside, so takes the differences from the side of smaller . The step is stable when , which holds with equality here.
Line L6 keeps the volume bound. A larger lowers every speed, so it can only remove solid elements. With every speed is at most 0 and nothing grows. So if the current design meets the bound, a feasible exists, and the bisection finds the smallest one up to . The real methods use a Lagrange multiplier that is updated from step to step, or an augmented Lagrangian.
Line L14 makes close to a signed distance function again. The upwind steps make steep or flat near the boundary, and a flat moves its zero set too fast. The code finds the distance by brute force over all zero crossings. Real codes solve the eikonal equation , for example with the fast marching method, or a reinitialization equation.
Example
A cantilever. A grid is clamped on its left edge and has a unit load down at the middle of its right edge. The bound is , half of the elements. Because the method in 2D does not create holes, the start has a regular pattern of holes, shifted so that exactly 144 elements are solid. The pictures show the solid elements, top row first.
start after 40 iterations
##....####....####....## ##################......
..####....####....####.. .##################.....
..####....####....####.. ...###...#####...###....
..####....####....####.. ....##....#.##....####..
##....####....####....## ......####....####...###
##....####....####....## .......###.....###....##
##....####....####....## .......###.....###....##
..####....####....####.. ......####.....###...##.
..####....####....####.. .....#....#..##...####..
..####....####....####.. ...###....####....##....
##....####....####....## .##################.....
##....####....####....## #################.......
The final design has a top and a bottom chord and diagonals that carry the load to the clamp, with 144 solid elements.
| iteration | 1 | 2 | 6 | 11 | 21 | 31 | 40 |
|---|---|---|---|---|---|---|---|
| compliance | 237.4 | 2637.2 | 1525.0 | 199.5 | 125.2 | 82.0 | 72.0 |
The compliance is not monotone. The blocks of the start touch only at corners, the first steps move them, and the compliance jumps to 2637.2 in the second iteration. It first falls below the start value in iteration 11. The run takes about 2 s of Python. All these numbers are measured on this one case.
Against brute force. A cantilever is clamped on the left and loaded at the bottom right corner, with and void stiffness . The test computes all 638 designs with at most 5 solid elements: the best is the bottom row, with compliance 344.52. From three different start patterns, every design that the method visits has a compliance of at least 344.52, as it must. One start reaches 344.52 during the run but ends at 3938.45, and another ends with the top row, at 2804.6. On a grid this coarse the boundary moves a whole element at a time, and the result depends on the start.
Correctness
The method is a descent heuristic, and its descent is not proved for the discrete code. What is proved is the bookkeeping: if the start has at most solid elements, every design has at most solid elements. The reason is that the update of line L12 is monotone in the speed, so the number of solid elements after a step does not increase with , and never adds a solid element. Line L14 keeps the sign of every element, so reinitialization does not change the design. On a linear , both upwind gradients equal exactly away from the edges of the grid, so the scheme moves a straight boundary at the right speed. The loop stops after iters iterations. The full proof is below.
The shape derivative of Allaire, Jouve and Toader is a statement about smooth boundaries and exact solutions. On a grid of 0/1 elements with an ersatz material, the speed is only an estimate of it, and the measured compliance can go up, as the example shows.
Proof: The level set iteration keeps the volume bound, keeps the design under reinitialization, and is exact on linear functionsfull
Setting. The grid has elements and has one value per element. An element is solid if . Let . The load is not zero, the supports remove the rigid body motions, , , and . The proof uses exact real arithmetic.
Claim.
- Every system of line L4 has a unique solution, and the values of line L5 satisfy .
- Every design of the iteration has at most solid elements.
- REINIT does not change the set of solid elements.
- If on the element , then at every element that is not on the edge of the grid, , and STEP gives .
- The method stops after iters iterations.
Step 1 (claim 1). Every element has a stiffness factor , so is positive definite on the free degrees of freedom and line L4 has a unique solution . Since , , and . The matrix is positive semidefinite, so every and at least one is positive. The mean over neighbours keeps the values at least 0 and keeps a positive value positive (each mean includes the element itself). So the maximum is positive, and after the division .
Step 2 (STEP is monotone in the speed). Fix . The values and of line L11 depend only on and are at least 0. Let . For , , and for , . Both pieces are nondecreasing and agree at 0, so is nondecreasing. Line L12 gives , which is nonincreasing in . With , the new value is nondecreasing in . So if , every element that is solid after the step with is solid after the step with , and .
Step 3 (claim 2). Suppose at the start of an iteration. With , by Step 1, so and the new is at least the old one. So no element becomes solid, and . The code tests first, and this test passes. The bisection keeps the invariant for its upper end : it moves only to a midpoint where the count is at most . Line L7 uses , so the new design has at most solid elements. By Step 4 below, line L8 does not change the count. By induction from , claim 2 holds. By Step 2, the count is nonincreasing in , so the set of feasible in is an interval that contains 1, and the bisection approaches its left end.
Step 4 (claim 3). A point of lies on the segment from the center of an element with to the center of a neighbour with , at the fraction from . Since , the denominator is negative and . So no point of is the center of a solid element: a point with is strictly inside a segment of length 1, and a point with is the center of , which is not solid. Hence for a solid element , the distance to the nearest point of is positive, and line L14 sets . For an element with , line L14 sets . So the set of solid elements does not change. If is empty, the code leaves unchanged.
Step 5 (claim 4). For and an element away from the edge of the grid, and . If , then , and if it is . The same holds with max and min swapped, and for . So both squared gradients are . Then line L12 gives , which is the exact solution of for a constant speed over the time on a linear .
Step 6 (claim 5). The loop of line L2 runs iters times. Each iteration has one solve, at most steps calls of STEP, and at most one REINIT, each with a finite number of operations.
Remark. The claims are about the bookkeeping of the method. The compliance of the iterates is not proved to decrease, and the tests measure that it can rise. The test of claim 4 uses exact fractions, and the other tests use floats.
Complexity
One finite element solve with a band of width takes time and space. One STEP takes time, and line L6 calls it about 40 times. The brute force reinitialization compares elements with crossings, time. So iterations take time. With a fast marching reinitialization the second term drops to .
The number of iterations is chosen by the user. The method has no proved rate, and in the example the compliance settles after about 30 iterations.
Properties
- Crisp designs. Every design is a set of elements, with no gray densities.
- Topology changes. Holes merge, open to the outside, or vanish, with no special code.
- No new holes in 2D. The zero set only moves, so a solid region without a hole cannot get one. The result depends on the holes of the start.
- Feasible iterates. In this code every design meets the volume bound, given a feasible start.
- Not monotone. The compliance of the iterates can rise, sometimes by a large factor.
- Local. The method finds a local optimum, and different starts give different designs.
Variants and improvements
- Topological derivative. Adds a term that predicts where a small new hole lowers the objective, and nucleates holes there. This removes the dependence on the holes of the start.
- Velocity extension and regularization. Smooth the speed in a Sobolev space or extend it off the boundary with the eikonal equation, for more stable steps.
- Parametric level sets. Write as a sum of radial basis functions and optimize their weights with a standard optimizer, in place of the Hamilton-Jacobi step.
- Reaction-diffusion and phase field updates. Replace the transport equation by a diffusion equation for , which also nucleates holes.
- Body fitted meshes. Remesh along the zero set in each iteration in place of the ersatz material, for an exact boundary in the finite element model.
- Other objectives. Eigenfrequencies, stress, compliant mechanisms and multiple materials, each with its own shape derivative.
When to use it
Use a level set method when a crisp boundary matters during the optimization: for loads or conditions on the boundary itself, such as pressure, contact or flow, or when the result goes straight to a CAD model. For plain minimum compliance on a fixed mesh, the SIMP method is simpler and less sensitive to the start. The method needs a start with many holes in 2D, or a topological derivative.
Pitfalls
- Too few holes in the start. The method cannot add holes in 2D, so a full start stays a block with a moved outer edge.
- Flat or steep . Without reinitialization, loses its distance property and the boundary moves at the wrong speed.
- Large time steps. A step above the stability limit makes the scheme oscillate. Even at the limit, as here, the boundary can jump a whole element per step.
- Cutting a member. A thin member can disappear in one step, and the compliance jumps up, as in the example. Keep the best design seen, or use smaller steps.
- Ersatz stiffness too large or too small. A large lets holes carry load, and a tiny one makes the stiffness matrix badly conditioned.
- Speed in the holes. The energy in the ersatz material is not the energy that the solid would carry there. The extension of the speed off the boundary is a modeling choice.
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
level_set_topology_optimization.py 174 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/level-set-topology-optimization/. The authors are listed in prov/H8FVX0.jsonl.
"""A toy level set method for minimum compliance, after Wang, Wang and Guo (2003)
and Allaire, Jouve and Toader (2004). This is a demonstration, not a production code.
The level set function phi has one value per element of an nelx x nely grid of
unit square Q4 elements. Element e is solid if phi_e < 0 and is ersatz material
of stiffness eps otherwise. Each iteration solves the finite element model,
takes the strain energy density w_e = u_e^T k0 u_e as the shape sensitivity,
and moves the boundary with one upwind step of the Hamilton-Jacobi equation
phi_t + V |grad phi| = 0 with the normal speed V = w / max(w) - l. The
multiplier l in [0, 1] is found by bisection so that the solid volume stays at
most the bound. Every few iterations phi is reset to a signed distance by a
brute force search over the zero crossings.
The finite element part is in fem2d.py, a shared helper.
"""
import math
from fem2d import element_energies, q4_stiffness, solve
def at(phi, nelx, nely, i, j):
"""phi at the element (i, j), with the edge values repeated outside the grid."""
i = min(max(i, 0), nelx - 1)
j = min(max(j, 0), nely - 1)
return phi[i * nely + j]
def upwind_gradients_sq(phi, nelx, nely, i, j):
"""The squares of the Osher-Sethian upwind gradient norms (grad+, grad-) at (i, j)."""
c = at(phi, nelx, nely, i, j)
dxm = c - at(phi, nelx, nely, i - 1, j) # @line L10
dxp = at(phi, nelx, nely, i + 1, j) - c
dym = c - at(phi, nelx, nely, i, j - 1)
dyp = at(phi, nelx, nely, i, j + 1) - c
zero = 0 * c
gp = max(dxm, zero) ** 2 + min(dxp, zero) ** 2 + max(dym, zero) ** 2 + min(dyp, zero) ** 2 # @line L11
gm = min(dxm, zero) ** 2 + max(dxp, zero) ** 2 + min(dym, zero) ** 2 + max(dyp, zero) ** 2
return gp, gm
def hj_step(phi, nelx, nely, speed, dt, sqrt=math.sqrt):
"""One explicit upwind step of phi_t + V |grad phi| = 0 (grid spacing 1)."""
out = []
for i in range(nelx):
for j in range(nely):
e = i * nely + j
gp, gm = upwind_gradients_sq(phi, nelx, nely, i, j)
v = speed[e]
out.append(phi[e] - dt * (max(v, 0) * sqrt(gp) + min(v, 0) * sqrt(gm))) # @line L12
return out
def zero_crossings(phi, nelx, nely):
"""Points where phi changes sign between the centers of neighbouring elements."""
pts = []
for i in range(nelx):
for j in range(nely):
a = phi[i * nely + j]
for di, dj in ((1, 0), (0, 1)):
if i + di < nelx and j + dj < nely:
b = phi[(i + di) * nely + j + dj]
if (a < 0) != (b < 0):
t = a / (a - b) # in (0, 1]
pts.append((i + 0.5 + di * t, j + 0.5 + dj * t))
return pts
def reinitialize(phi, nelx, nely):
"""Replace phi by the signed distance to its zero crossings; the sign of each element is kept."""
pts = zero_crossings(phi, nelx, nely) # @line L13
if not pts:
return list(phi)
out = []
for i in range(nelx):
for j in range(nely):
d = min(math.hypot(i + 0.5 - x, j + 0.5 - y) for x, y in pts)
out.append(-d if phi[i * nely + j] < 0 else d) # @line L14
return out
def smooth_field(w, nelx, nely):
"""The mean over the element and its 4 neighbours inside the grid."""
out = []
for i in range(nelx):
for j in range(nely):
vals = [w[a * nely + b] for a, b in ((i, j), (i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1))
if 0 <= a < nelx and 0 <= b < nely]
out.append(sum(vals) / len(vals))
return out
def solid_count(phi):
return sum(1 for v in phi if v < 0)
def compliance_of(nelx, nely, ke, solid, force, fixed, eps):
scale = [1.0 if s else eps for s in solid]
u = solve(nelx, nely, ke, scale, force, fixed)
return sum(v * u[k] for k, v in force.items()), u
def level_set_topology(nelx, nely, volfrac, phi0, force, fixed, iters=60, dt=0.5,
eps=1e-3, reinit_every=5, nu=0.3, steps=40, smooth=1):
"""Return (phi, history): the final level set and the compliance of each iteration."""
ke = [[float(v) for v in row] for row in q4_stiffness(nu)]
bound = int(volfrac * nelx * nely)
phi = list(phi0) # @line L1
history = []
for it in range(1, iters + 1): # @line L2
solid = [v < 0 for v in phi] # @line L3
c, u = compliance_of(nelx, nely, ke, solid, force, fixed, eps) # @line L4
history.append(c)
w = element_energies(nelx, nely, ke, u)
for _ in range(smooth):
w = smooth_field(w, nelx, nely)
top = max(w)
w = [x / top for x in w] # @line L5
def trial(lam):
return hj_step(phi, nelx, nely, [x - lam for x in w], dt)
lo, hi = 0.0, 1.0 # @line L6
if solid_count(trial(hi)) <= bound:
for _ in range(steps):
mid = (lo + hi) / 2
if solid_count(trial(mid)) <= bound:
hi = mid
else:
lo = mid
phi = trial(hi) # @line L7
if it % reinit_every == 0: # @line L8
phi = reinitialize(phi, nelx, nely)
solid = [v < 0 for v in phi]
history.append(compliance_of(nelx, nely, ke, solid, force, fixed, eps)[0])
return phi, history # @line L9
def holes_start(nelx, nely, volfrac, kx=4, ky=2):
"""A start with a regular pattern of holes, shifted so that the solid volume meets the bound."""
base = [-math.cos(2 * math.pi * kx * (i + 0.5) / nelx) * math.cos(2 * math.pi * ky * (j + 0.5) / nely)
for i in range(nelx) for j in range(nely)]
bound = int(volfrac * nelx * nely)
# the shift that leaves exactly `bound` negative values (ties are broken by the sort)
order = sorted(base)
shift = (order[bound - 1] + order[bound]) / 2 if bound < len(order) else order[-1] + 1
return [b - shift for b in base]
def cantilever(nelx, nely):
"""Left edge clamped, unit load down at the middle of the right edge."""
n = nelx * (nely + 1) + nely // 2
force = {2 * n + 1: -1.0}
fixed = [k for j in range(nely + 1) for k in (2 * j, 2 * j + 1)]
return force, fixed
def show(phi, nelx, nely):
return "\n".join("".join("#" if phi[i * nely + j] < 0 else "." for i in range(nelx))
for j in range(nely - 1, -1, -1))
if __name__ == "__main__":
nelx, nely, vf = 32, 16, 0.5
force, fixed = cantilever(nelx, nely)
phi0 = holes_start(nelx, nely, vf)
print(show(phi0, nelx, nely))
phi, hist = level_set_topology(nelx, nely, vf, phi0, force, fixed)
print(show(phi, nelx, nely))
print("start", round(hist[0], 2), "end", round(hist[-1], 2), "min", round(min(hist), 2),
"solid", solid_count(phi), "of", nelx * nely)
test_level_set_topology_optimization.py 98 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/level-set-topology-optimization/. The authors are listed in prov/H8FVX0.jsonl.
import itertools
import math
import random
from fractions import Fraction as F
from fem2d import node, q4_stiffness
from level_set_topology_optimization import (cantilever, compliance_of, hj_step, holes_start, level_set_topology,
reinitialize, solid_count, upwind_gradients_sq)
KE = [[float(v) for v in row] for row in q4_stiffness(F(3, 10))]
def exact_sqrt(q):
q = F(q)
a, b = math.isqrt(q.numerator), math.isqrt(q.denominator)
assert a * a == q.numerator and b * b == q.denominator
return F(a, b)
def test_upwind_step_is_exact_on_a_linear_function():
nelx, nely = 6, 5
for a, b in ((3, 4), (-3, 4), (F(-5, 2), -6), (0, F(7, 3))):
phi = [a * i + b * j + F(1, 7) for i in range(nelx) for j in range(nely)]
norm_sq = F(a) ** 2 + F(b) ** 2
for i in range(1, nelx - 1):
for j in range(1, nely - 1):
assert upwind_gradients_sq(phi, nelx, nely, i, j) == (norm_sq, norm_sq)
speed = [F(random.Random(5).choice([-2, 1, 3]))] * (nelx * nely)
out = hj_step(phi, nelx, nely, speed, F(1, 4), sqrt=exact_sqrt)
for i in range(1, nelx - 1):
for j in range(1, nely - 1):
e = i * nely + j
assert out[e] == phi[e] - F(1, 4) * speed[e] * exact_sqrt(norm_sq)
def test_circle_grows_with_unit_speed():
n, r0 = 30, 4
phi = [math.hypot(i + 0.5 - 15, j + 0.5 - 15) - r0 for i in range(n) for j in range(n)]
counts = [solid_count(phi)]
for _ in range(8): # 8 steps of dt = 0.5 at speed 1: the radius should grow to 8
phi = hj_step(phi, n, n, [1.0] * (n * n), 0.5)
counts.append(solid_count(phi))
assert counts == sorted(counts)
radius = math.sqrt(counts[-1] / math.pi)
assert abs(radius - 8) < 0.5 # measured 7.74: first order upwind lags a little
def test_reinitialize_keeps_signs_and_gives_distances_to_a_line():
nelx, nely = 20, 7
phi = [3 * (i + 0.5 - 10.3) for i in range(nelx) for j in range(nely)]
out = reinitialize(phi, nelx, nely)
for e, (a, b) in enumerate(zip(phi, out)):
assert (a < 0) == (b < 0)
i = e // nely
assert abs(b - (i + 0.5 - 10.3)) < 1e-12 # the true signed distance to the line x = 10.3
rng = random.Random(6)
phi = [rng.uniform(-1, 1) for _ in range(nelx * nely)]
out = reinitialize(phi, nelx, nely)
assert all((a < 0) == (b < 0) for a, b in zip(phi, out))
def test_solid_volume_is_monotone_in_the_multiplier():
rng = random.Random(7)
nelx, nely = 8, 6
for _ in range(20):
phi = [rng.uniform(-2, 2) for _ in range(nelx * nely)]
w = [rng.random() for _ in range(nelx * nely)]
counts = [solid_count(hj_step(phi, nelx, nely, [x - lam / 20 for x in w], 0.5)) for lam in range(21)]
assert counts == sorted(counts, reverse=True)
assert counts[-1] <= solid_count(phi) # with l = 1 the speed is at most 0, so nothing grows
def test_never_below_the_brute_force_optimum_on_5x2():
nelx, nely, eps = 5, 2, 1e-3
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)]
best = min(compliance_of(nelx, nely, KE, [e in s for e in range(10)], force, fixed, eps)[0]
for k in range(6) for s in itertools.combinations(range(10), k))
for kx, ky in ((1, 1), (2, 1), (1, 2)):
phi0 = holes_start(nelx, nely, 0.5, kx, ky)
phi, hist = level_set_topology(nelx, nely, 0.5, phi0, force, fixed, iters=30, eps=eps)
assert solid_count(phi) <= 5
assert min(hist) >= best * (1 - 1e-9) # every design has at most 5 solid elements
assert abs(best - 344.52) < 0.01 # the bottom row, with void stiffness 1e-3
def test_cantilever_improves_and_keeps_the_volume():
nelx, nely, vf = 24, 12, 0.5
force, fixed = cantilever(nelx, nely)
phi0 = holes_start(nelx, nely, vf, kx=3, ky=2)
assert solid_count(phi0) == 144
phi, hist = level_set_topology(nelx, nely, vf, phi0, force, fixed, iters=40)
assert solid_count(phi) <= 144
assert hist[-1] < 0.4 * hist[0] # measured 237.4 to 72.0
assert max(hist) > hist[0] # measured: the compliance is not monotone (2637 at iteration 2)
History
The level set method of Osher and Sethian (1988) tracks moving fronts with an implicit function. Sethian and Wiegmann (2000) used it for structural boundaries. Wang, Wang and Guo (2003) proposed a level set method for structural topology optimization with a speed from the strain energy. Allaire, Jouve and Toader (2004) gave the method its form based on the shape derivative, with an ersatz material on a fixed mesh. Later work added the topological derivative to nucleate holes, parametric level sets, and body fitted meshes.
References
- Michael Yu Wang, Xiaoming Wang and Dongming Guo, A level set method for structural topology optimization, Computer Methods in Applied Mechanics and Engineering 192(1-2), 2003, 227 to 246, the boundary as the zero set of a level set function, the speed from the strain energy, and the upwind Hamilton-Jacobi step on a fixed grid
- Grégoire Allaire, François Jouve and Anca-Maria Toader, Structural optimization using sensitivity analysis and a level-set method, Journal of Computational Physics 194(1), 2004, 363 to 393, the shape derivative of the compliance, the ersatz material on a fixed mesh, the reinitialization, and the remark that the method does not create new holes in 2D
- Martin P. Bendsøe and Ole Sigmund, Topology Optimization, Theory, Methods and Applications, Springer, 2003, the minimum compliance problem that the method solves (general locator)
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 H8FVX0 Edit this page History Report an error Markdown