Algorithm Search⌘K

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.

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
Properties
deterministicnot exactiterative
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 ϕ\phi on the design domain: the structure is the set where ϕ<0\phi < 0, and its boundary is the zero set of ϕ\phi. 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 ϕ\phi, 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 n=nxnyn = n_x n_y unit square bilinear plane stress elements, a load ff, supports, and a bound BB on the number of solid elements. A design is the set Ω={e:ϕe<0}\Omega = \{e : \phi_e < 0\} for a level set function ϕ\phi with one value per element. The element stiffness is se=1s_e = 1 in Ω\Omega and se=ε=10−3s_e = \varepsilon = 10^{-3} outside, the ersatz material, so that K(s)=∑eseKeK(s) = \sum_e s_e K_e is always invertible. The goal is a design with ∣Ω∣≤B|\Omega| \le B and a small compliance c=fTuc = f^{\mathsf T} u, where K(s) u=fK(s)\, u = f.

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 θ⋅n\theta \cdot n, then the compliance changes by

c′(Ω)(θ)=−∫∂ΩAe(u):e(u) θ⋅n ds,c'(\Omega)(\theta) = -\int_{\partial\Omega} A e(u) : e(u)\ \theta \cdot n \, ds,

where Ae(u):e(u)A e(u) : e(u) is twice the strain energy density. For the Lagrangian c+ℓ ∣Ω∣c + \ell\, |\Omega| with a multiplier ℓ\ell, the derivative is ∫∂Ω(ℓ−Ae(u):e(u)) θ⋅n ds\int_{\partial\Omega} (\ell - A e(u) : e(u))\, \theta \cdot n \, ds. So the normal speed V=Ae(u):e(u)−ℓV = A e(u) : e(u) - \ell is a descent direction: the boundary moves out where the energy density is above ℓ\ell, and in where it is below.

The level set equation. If the zero set of ϕ\phi moves with the normal speed VV, with ϕ<0\phi < 0 inside, then ϕ\phi satisfies the Hamilton-Jacobi equation

∂ϕ∂t+V ∣∇ϕ∣=0.\frac{\partial \phi}{\partial t} + V\, |\nabla \phi| = 0.

The algorithm

The code uses the element energies we=ueTk0uew_e = u_e^{\mathsf T} k_0 u_e, where k0k_0 is the element matrix for E=1E = 1, as the values of Ae(u):e(u)A e(u) : e(u) on the element. In the holes it uses the same formula with the ersatz displacement, which extends the speed off the boundary. It smooths ww once with the mean over the 4 neighbours and divides it by its maximum, so that 0≤we≤10 \le w_e \le 1. The multiplier is ℓ∈[0,1]\ell \in [0, 1], so ∣V∣≤1|V| \le 1, and the time step is Δt=1/2\Delta t = 1/2.

  1. LEVEL-SET-TO(grid, f, supports, B, φ₀) ▷ at most B elements with φ₀ < 0
  2. 1φ ← φ₀
  3. 2for it = 1 to iters do
  4. 3s_e ← 1 if φ_e < 0, else ε
  5. 4solve K(s) u = f; c ← fᵀu
  6. 5w_e ← u_eᵀ k₀ u_e, smoothed and divided by its maximum
  7. 6ℓ ← the smallest ℓ in [0, 1], by bisection, with #{e : STEP(φ, w − ℓ)_e < 0} ≤ B
  8. 7φ ← STEP(φ, w − ℓ)
  9. 8if it is a multiple of R then φ ← REINIT(φ)
  10. 9return φ
  11. STEP(φ, V) ▷ grid spacing 1
  12. 10D⁻x, D⁺x, D⁻y, D⁺y ← one-sided differences of φ, with edge values repeated
  13. 11∇⁺ ← (max(D⁻x,0)² + min(D⁺x,0)² + max(D⁻y,0)² + min(D⁺y,0)²)^½; ∇⁻ likewise with max and min swapped
  14. 12φ_e ← φ_e − Δt (max(V_e, 0) ∇⁺_e + min(V_e, 0) ∇⁻_e)
  15. REINIT(φ)
  16. 13P ← the zero crossings of φ on the segments between the centers of neighbouring elements
  17. 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 (V>0V > 0), information comes from the inside, so ∇+\nabla^+ takes the differences from the side of smaller ϕ\phi. The step is stable when Δt max⁡∣V∣ (1/Δx+1/Δy)≤1\Delta t\, \max|V|\, (1/\Delta x + 1/\Delta y) \le 1, which holds with equality here.

Line L6 keeps the volume bound. A larger ℓ\ell lowers every speed, so it can only remove solid elements. With ℓ=1\ell = 1 every speed is at most 0 and nothing grows. So if the current design meets the bound, a feasible ℓ\ell exists, and the bisection finds the smallest one up to 2−402^{-40}. The real methods use a Lagrange multiplier that is updated from step to step, or an augmented Lagrangian.

Line L14 makes ϕ\phi close to a signed distance function again. The upwind steps make ϕ\phi steep or flat near the boundary, and a flat ϕ\phi moves its zero set too fast. The code finds the distance by brute force over all zero crossings. Real codes solve the eikonal equation ∣∇ϕ∣=1|\nabla \phi| = 1, for example with the fast marching method, or a reinitialization equation.

Example

A cantilever. A 24×1224 \times 12 grid is clamped on its left edge and has a unit load down at the middle of its right edge. The bound is B=144B = 144, 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 5×25 \times 2 cantilever is clamped on the left and loaded at the bottom right corner, with B=5B = 5 and void stiffness 10−310^{-3}. 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 BB solid elements, every design has at most BB 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 ℓ\ell, and ℓ=1\ell = 1 never adds a solid element. Line L14 keeps the sign of every element, so reinitialization does not change the design. On a linear ϕ\phi, both upwind gradients equal ∣∇ϕ∣|\nabla\phi| 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 nn elements and ϕ\phi has one value per element. An element is solid if ϕe<0\phi_e < 0. Let N(ϕ)=#{e:ϕe<0}N(\phi) = \#\{e : \phi_e < 0\}. The load ff is not zero, the supports remove the rigid body motions, ε>0\varepsilon > 0, Δt>0\Delta t > 0, and N(ϕ0)≤BN(\phi_0) \le B. The proof uses exact real arithmetic.

Claim.

  1. Every system of line L4 has a unique solution, and the values wew_e of line L5 satisfy 0≤we≤10 \le w_e \le 1.
  2. Every design of the iteration has at most BB solid elements.
  3. REINIT does not change the set of solid elements.
  4. If ϕe=ai+bj+c\phi_e = a i + b j + c on the element (i,j)(i, j), then at every element that is not on the edge of the grid, ∇+=∇−=a2+b2\nabla^+ = \nabla^- = \sqrt{a^2 + b^2}, and STEP gives ϕe−Δt Vea2+b2\phi_e - \Delta t\, V_e \sqrt{a^2 + b^2}.
  5. The method stops after iters iterations.

Step 1 (claim 1). Every element has a stiffness factor se≥ε>0s_e \ge \varepsilon > 0, so K(s)K(s) is positive definite on the free degrees of freedom and line L4 has a unique solution uu. Since f≠0f \ne 0, u≠0u \ne 0, and uTKu=∑ese ueTk0ue>0u^{\mathsf T} K u = \sum_e s_e\, u_e^{\mathsf T} k_0 u_e > 0. The matrix k0k_0 is positive semidefinite, so every ueTk0ue≥0u_e^{\mathsf T} k_0 u_e \ge 0 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 0≤we≤10 \le w_e \le 1.

Step 2 (STEP is monotone in the speed). Fix ϕ\phi. The values ae=∇e+a_e = \nabla^+_e and be=∇e−b_e = \nabla^-_e of line L11 depend only on ϕ\phi and are at least 0. Let g(v)=max⁡(v,0) ae+min⁡(v,0) beg(v) = \max(v, 0)\, a_e + \min(v, 0)\, b_e. For v≥0v \ge 0, g(v)=aevg(v) = a_e v, and for v≤0v \le 0, g(v)=bevg(v) = b_e v. Both pieces are nondecreasing and agree at 0, so gg is nondecreasing. Line L12 gives ϕe−Δt g(Ve)\phi_e - \Delta t\, g(V_e), which is nonincreasing in VeV_e. With Ve=we−ℓV_e = w_e - \ell, the new value is nondecreasing in ℓ\ell. So if ℓ≤ℓ′\ell \le \ell', every element that is solid after the step with ℓ′\ell' is solid after the step with ℓ\ell, and N(STEP(ϕ,w−ℓ))≥N(STEP(ϕ,w−ℓ′))N(\text{STEP}(\phi, w - \ell)) \ge N(\text{STEP}(\phi, w - \ell')).

Step 3 (claim 2). Suppose N(ϕ)≤BN(\phi) \le B at the start of an iteration. With ℓ=1\ell = 1, Ve=we−1≤0V_e = w_e - 1 \le 0 by Step 1, so g(Ve)≤0g(V_e) \le 0 and the new ϕe\phi_e is at least the old one. So no element becomes solid, and N(STEP(ϕ,w−1))≤N(ϕ)≤BN(\text{STEP}(\phi, w - 1)) \le N(\phi) \le B. The code tests ℓ=1\ell = 1 first, and this test passes. The bisection keeps the invariant N(STEP(ϕ,w−h))≤BN(\text{STEP}(\phi, w - h)) \le B for its upper end hh: it moves hh only to a midpoint where the count is at most BB. Line L7 uses ℓ=h\ell = h, so the new design has at most BB solid elements. By Step 4 below, line L8 does not change the count. By induction from N(ϕ0)≤BN(\phi_0) \le B, claim 2 holds. By Step 2, the count is nonincreasing in ℓ\ell, so the set of feasible ℓ\ell in [0,1][0, 1] is an interval that contains 1, and the bisection approaches its left end.

Step 4 (claim 3). A point of PP lies on the segment from the center of an element aa with ϕa<0\phi_a < 0 to the center of a neighbour bb with ϕb≥0\phi_b \ge 0, at the fraction t=ϕa/(ϕa−ϕb)t = \phi_a / (\phi_a - \phi_b) from aa. Since ϕa<0≤ϕb\phi_a < 0 \le \phi_b, the denominator is negative and 0<t≤10 < t \le 1. So no point of PP is the center of a solid element: a point with t<1t < 1 is strictly inside a segment of length 1, and a point with t=1t = 1 is the center of bb, which is not solid. Hence for a solid element ee, the distance ded_e to the nearest point of PP is positive, and line L14 sets ϕe=−de<0\phi_e = -d_e < 0. For an element with ϕe≥0\phi_e \ge 0, line L14 sets ϕe=de≥0\phi_e = d_e \ge 0. So the set of solid elements does not change. If PP is empty, the code leaves ϕ\phi unchanged.

Step 5 (claim 4). For ϕe=ai+bj+c\phi_e = a i + b j + c and an element away from the edge of the grid, D−x=D+x=aD^-x = D^+x = a and D−y=D+y=bD^-y = D^+y = b. If a≥0a \ge 0, then max⁡(D−x,0)2+min⁡(D+x,0)2=a2+0\max(D^-x, 0)^2 + \min(D^+x, 0)^2 = a^2 + 0, and if a<0a < 0 it is 0+a20 + a^2. The same holds with max and min swapped, and for bb. So both squared gradients are a2+b2a^2 + b^2. Then line L12 gives ϕe−Δt (max⁡(Ve,0)+min⁡(Ve,0))a2+b2=ϕe−Δt Vea2+b2\phi_e - \Delta t\, (\max(V_e, 0) + \min(V_e, 0)) \sqrt{a^2 + b^2} = \phi_e - \Delta t\, V_e \sqrt{a^2 + b^2}, which is the exact solution of ϕt+V∣∇ϕ∣=0\phi_t + V |\nabla \phi| = 0 for a constant speed over the time Δt\Delta t on a linear ϕ\phi.

Step 6 (claim 5). The loop of line L2 runs iters times. Each iteration has one solve, at most steps +1+ 1 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. ■\blacksquare

Complexity

One finite element solve with a band of width O(h)O(h) takes O(nh2)O(n h^2) time and O(nh)O(n h) space. One STEP takes O(n)O(n) time, and line L6 calls it about 40 times. The brute force reinitialization compares nn elements with O(n)O(n) crossings, O(n2)O(n^2) time. So kk iterations take O(k n(h2+n))O(k\, n (h^2 + n)) time. With a fast marching reinitialization the second term drops to O(nlog⁡n)O(n \log n).

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 ϕ\phi 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 ϕ\phi, 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 ϕ\phi. Without reinitialization, ϕ\phi 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 ε\varepsilon 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.

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
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

  1. 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
  2. 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
  3. 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.

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