Algorithm Search⌘K

Techniqueadvanced

Density filtering in topology optimization

Also called sensitivity filtering, checkerboard control.

Replaces each element density by a weighted average over a radius, with cone weights, and runs the model on the averaged field, so designs lose checkerboards and gain a length scale.

In plain words

A design made of small squares, each solid or empty, can cheat. A pattern of squares that touch only at their corners, like a chessboard, looks stiff to the computer even though it would fall apart. And when the squares get smaller, the computer draws thinner and thinner members, so the answer depends on the grid.

The density filter stops both. The optimizer still chooses a value for every square, but the structure that is analyzed is a blurred copy: each square takes the average of its neighbors within a fixed distance, the near ones counting more. A chessboard blurs to an even gray, which is soft, so the cheat no longer pays. A member thinner than the blur distance turns gray too, so members stay thick, however fine the grid.

When it applies

Setting. A design domain is divided into elements ee with centers cec_e, volumes vev_e and design variables xe∈[xmin⁡,1]x_e \in [x_{\min}, 1], as in topology optimization. The filter radius rmin⁡>0r_{\min} > 0 is a length, not a number of elements. The weights are the cone

Hef=max⁡(0,  rmin⁡−∣ce−cf∣),De=∑fHefvf,H_{ef} = \max\big(0,\; r_{\min} - |c_e - c_f|\big), \qquad D_e = \sum_f H_{ef} v_f,

and the filtered densities are

x~e=1De∑fHef vf xf,x~=Wx with W=D−1HV.\tilde x_e = \frac{1}{D_e} \sum_f H_{ef}\, v_f\, x_f, \qquad \tilde x = W x \text{ with } W = D^{-1} H V.

The finite element model, the objective and the constraints are all evaluated at x~\tilde x, and x~\tilde x is the design that is built. The variables xx are only the handles the optimizer turns. This is the density filter of Bruns and Tortorelli (2001). Bourdin (2001) studied the same idea as a convolution and proved that the filtered continuum problem has a solution, which the unfiltered 0/1 problem in general does not.

It applies to any density method where the response is a differentiable function of the element densities: SIMP for stiffness, heat conduction, compliant mechanisms, eigenvalues. It needs a mesh where the neighbors of an element within rmin⁡r_{\min} can be found, and on a regular grid they are a fixed stencil.

The template

  1. FILTERED-DESIGN(x, r_min, ⟨kernel⟩, ⟨model⟩, ⟨update⟩, ⟨stop⟩)
  2. 1H_ef ← ⟨kernel⟩(|c_e − c_f|) for the pairs within r_min; D_e ← Σ_f H_ef v_f
  3. 2repeat
  4. 3x̃_e ← Σ_f H_ef v_f x_f / D_e
  5. 4c, ∂c/∂x̃ ← ⟨model⟩(x̃) ▷ e.g. a finite element solve with the SIMP stiffness of x̃
  6. 5∂c/∂x_f ← v_f Σ_e H_ef (∂c/∂x̃_e) / D_e ▷ the transpose of the filter; the same for every constraint
  7. 6x ← ⟨update⟩(x, ∂c/∂x)
  8. 7until ⟨stop⟩
  9. 8return x̃ ▷ the physical design is x̃, not x

The holes are:

  • Kernel (L1). The cone max⁡(0,rmin⁡−d)\max(0, r_{\min} - d) is the usual choice. A Gaussian, as in the Gaussian filter of image processing, or a constant over the disk, also work. Every proof below needs only Hef=Hfe≥0H_{ef} = H_{fe} \ge 0 and Hee>0H_{ee} > 0.
  • Model (L4). Any response that is differentiable in x~\tilde x, with its gradient from the adjoint method.
  • Update (L6). Optimality criteria with a bisection on the volume multiplier, the method of moving asymptotes, or a projected gradient step.
  • Stop (L7). A bound on the change of xx or of the objective, and a maximum count.

Walk-through. On a grid of unit squares with rmin⁡=1.5r_{\min} = 1.5, an element has 9 neighbors with positive weight: itself with 1.5, the 4 edge neighbors at distance 1 with 0.5, and the 4 diagonal ones at 2\sqrt 2 with 1.5−2≈0.08581.5 - \sqrt 2 \approx 0.0858. So D=3.843D = 3.843 inside the grid, 3.172 on an edge and 2.586 in a corner. A single solid element in a void filters to 0.390 at its center and 0.130 at its edge neighbors. A solid bar two elements wide filters to the profile 0.175, 0.825, 0.825, 0.175 across it: its volume is kept, but no element is fully solid. With the neighbors stored as a sparse matrix, lines L3 and L5 take O(nr2)O(n r^2) time on a 2D grid with rr the radius in elements, and the tests check both against the direct weighted sum over all pairs.

What is proved. The statements below are for a grid of equal elements, ve=1v_e = 1, so W=D−1HW = D^{-1} H, and they use the inner product ⟨a,b⟩D=∑eDeaebe\langle a, b \rangle_D = \sum_e D_e a_e b_e. For elements of different volumes only the weights change, as noted under Variations.

  1. A convex combination. Each row of WW has entries Hef/De≥0H_{ef} / D_e \ge 0 that sum to 1. So x~e\tilde x_e is a weighted mean of the xfx_f, and min⁡fxf≤x~e≤max⁡fxf\min_f x_f \le \tilde x_e \le \max_f x_f. If every xfx_f is in [xmin⁡,1][x_{\min}, 1], so is every x~e\tilde x_e, and no clipping is needed. A constant design is not changed.
  2. Self-adjoint in the DD inner product. ⟨Wx,y⟩D=∑eDe1De∑fHefxfye=xTHy\langle W x, y \rangle_D = \sum_e D_e \frac{1}{D_e} \sum_f H_{ef} x_f y_e = x^{\mathsf T} H y. Since HH is symmetric, this equals ⟨x,Wy⟩D\langle x, W y \rangle_D. In the plain inner product the adjoint is WT=HD−1=DWD−1W^{\mathsf T} = H D^{-1} = D W D^{-1}, which is not WW unless DD is constant.
  3. The chain rule. With c(x)=c^(Wx)c(x) = \hat c(W x), ∇c=WT∇c^=HD−1∇c^\nabla c = W^{\mathsf T} \nabla \hat c = H D^{-1} \nabla \hat c, which is line L5. By claim 2 the same statement reads: in the DD inner product the gradient is the filter itself applied to the DD-gradient D−1∇c^D^{-1} \nabla \hat c. Applying WW to the plain gradient, a common error, gives the same numbers only at elements whose whole neighborhood has the same DD, that is, far enough from the boundary.
  4. The volume. ∑ex~e=(WT1)⋅x\sum_e \tilde x_e = (W^{\mathsf T} \mathbf 1) \cdot x. The column sums WT1W^{\mathsf T} \mathbf 1 are 1 inside the grid, where all DD are equal, and not at the boundary. So the volume of x~\tilde x is not the volume of xx, and a volume bound on x~\tilde x needs the derivative WT1W^{\mathsf T} \mathbf 1 from line L5.
  5. Checkerboards. For the pattern xe=(−1)i+jx_e = (-1)^{i + j} inside the grid, every neighbor has sign −- at distance 1 and ++ at 2\sqrt 2, so x~=λx\tilde x = \lambda x with λ=(r−4(r−1)+4(r−2))/(r+4(r−1)+4(r−2))\lambda = (r - 4(r - 1) + 4(r - \sqrt 2)) / (r + 4(r - 1) + 4(r - \sqrt 2)) for 2≤r≤2\sqrt 2 \le r \le 2. For 1<r≤21 < r \le \sqrt 2 the diagonal neighbors have weight 0, and λ=(4−3r)/(5r−4)\lambda = (4 - 3r) / (5r - 4). For r=1.5r = 1.5, λ=−0.0408\lambda = -0.0408: the model sees an element checkerboard at 4% of its amplitude, and a checkerboard of 0 and 1 as a uniform gray near 1/21/2.

What is measured, on a 10×1010 \times 10 grid with rmin⁡=1.5r_{\min} = 1.5: a corner element has column sum 0.918, so a unit of material there counts as 0.918 in the volume, and a solid bottom row of 10 elements filters to a volume of 9.62. On a 20×1020 \times 10 grid, applying WW instead of WTW^{\mathsf T} to a random gradient is off by up to 11% for rmin⁡=1.5r_{\min} = 1.5, 36% for 2.5 and 51% for 4, always at the boundary. In the tests, a projected gradient run that tries to match a checkerboard target through the filter lowers the misfit at every step and ends with a filtered field that is nearly flat inside the grid.

Classic examples

  • SIMP. The density filter is the standard partner of the SIMP model. The page on SIMP uses the older sensitivity filter of Sigmund, which averages ∂c/∂x\partial c / \partial x weighted by the densities and is not the gradient of any function. The density filter gives the exact gradient of the filtered problem, so any gradient method, and any check by finite differences, applies. The 88 line code of Andreassen and coauthors (2011) offers both filters.
  • BESO. The sensitivity numbers are smoothed with the same cone weights before the elements are ranked. This also gives void elements a number from their solid neighbors, which is what lets material come back.
  • The homogenization method. Composite designs have fewer checkerboards than 0/1 models, but the hole sizes are often filtered to fix a length scale for the lattice that is built from them.
  • Projection. A smooth step xˉ=Pβ(x~)\bar x = P_\beta(\tilde x) after the filter, with a steepness β\beta raised during the run, pushes the gray band of the filter back to 0 or 1 while the filter keeps the length scale. Guest, Prévost and Belytschko (2004) introduced this Heaviside projection. The chain rule gains one factor: ∇c=WTdiag⁡(Pβ′(x~))∇c^\nabla c = W^{\mathsf T} \operatorname{diag}(P_\beta'(\tilde x)) \nabla \hat c.
  • Morphology. Sigmund (2007) replaced the weighted mean by smooth versions of the minimum and the maximum, the erosion and dilation of mathematical morphology, to get black and white designs with a length scale in the solid or in the void.

Variations

  • The PDE filter. Lazarov and Sigmund (2011) replaced the explicit sum by the solution of a Helmholtz type equation −r2Δx~+x~=x-r^2 \Delta \tilde x + \tilde x = x on the mesh. It needs one sparse solve instead of a neighbor search, which is cheaper on unstructured meshes and on parallel computers, and its kernel is close to the cone for a matching rr.
  • Weights with volumes. On a mesh with elements of different size, the weights include vfv_f as in line L3, and the inner product of claim 2 becomes ∑eDeveaebe\sum_e D_e v_e a_e b_e.
  • Boundary padding. Extending the domain by rmin⁡r_{\min} with elements of fixed density before filtering gives every design element the same DD. Then W=H/DW = H / D is symmetric on the design elements, and the two forms of claim 3 agree. Void padding treats the outside as empty, which makes the edge of the design grayer; solid padding is used next to supports and loads.
  • Convolution by FFT. On a regular grid the sum of line L3 is a convolution, which can be done by fast Fourier transform when rmin⁡r_{\min} is large.

Pitfalls

  • Applying the filter to the gradient. Line L5 uses the transpose HD−1H D^{-1}. Using the filter D−1HD^{-1} H instead is correct only inside the grid and gives errors of 11% to 51% at the boundary in the cases above, enough to stall a gradient method or fail a finite difference check.
  • Reporting xx instead of x~\tilde x. The model was solved for x~\tilde x. The raw variables can still hold checkerboards that the filter hides, and they are not the design.
  • A radius in elements. If rmin⁡r_{\min} is fixed in elements, a finer mesh gives thinner members and the length scale is lost. Fix it in units of length.
  • Volume on the wrong field. The volume of xx and of x~\tilde x differ at the boundary (8% for a corner element above). Put the bound on x~\tilde x, with the derivative of claim 4.
  • Gray boundaries. The filter turns every solid to void transition into a band about 2rmin⁡2 r_{\min} wide. Without a projection or a threshold the design never becomes 0/1.
  • Confusing it with checkerboard control in general. The filter is one way to remove checkerboards; higher order elements, perimeter bounds and slope bounds are others.

Code

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.

density_filtering.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/density-filtering/. The authors are listed in prov/FZQT96.jsonl.

"""The density filter of topology optimization on a grid of unit elements.

Element (i, j) of an nx by ny grid has its center at (i + 1/2, j + 1/2) and
the number i ny + j. The cone weights are H_ef = max(0, rmin - dist(e, f)),
D_e = sum_f H_ef, and the filtered density is x~ = D^-1 H x. All elements
have the same volume, so the volume factors of the general formula cancel.
"""

import math


class DensityFilter:
    def __init__(self, nx, ny, rmin):
        """L1: the sparse rows of H within the radius, and the row sums D."""
        self.nx, self.ny, self.rmin = nx, ny, rmin
        reach = math.ceil(rmin)
        self.rows = []
        for i in range(nx):
            for j in range(ny):
                row = []
                for k in range(max(0, i - reach), min(nx, i + reach + 1)):
                    for m in range(max(0, j - reach), min(ny, j + reach + 1)):
                        w = rmin - math.hypot(i - k, j - m)
                        if w > 0:
                            row.append((k * ny + m, w))
                self.rows.append(row)
        self.d = [sum(w for _, w in row) for row in self.rows]

    def apply(self, x):
        """L3: x~_e = sum_f H_ef x_f / D_e."""
        return [sum(w * x[f] for f, w in row) / d for row, d in zip(self.rows, self.d)]

    def transpose(self, g):
        """L5: the chain rule, dc/dx_f = sum_e H_ef (dc/dx~_e) / D_e. H is
        symmetric, so row f of H lists the same pairs as column f."""
        scaled = [ge / d for ge, d in zip(g, self.d)]
        return [sum(w * scaled[e] for e, w in row) for row in self.rows]


def direct_matrix(nx, ny, rmin):
    """The dense filter matrix W = D^-1 H from all pairs of elements, O(n^2)."""
    centers = [(i + 0.5, j + 0.5) for i in range(nx) for j in range(ny)]
    h = [[max(0.0, rmin - math.dist(a, b)) for b in centers] for a in centers]
    return [[v / sum(row) for v in row] for row in h], [sum(row) for row in h]


def matvec(m, x):
    return [sum(a * b for a, b in zip(row, x)) for row in m]


def matvec_transpose(m, g):
    n = len(m)
    return [sum(m[e][f] * g[e] for e in range(n)) for f in range(n)]


def filtered_descent(flt, x, model, update, maxit=100, tol=1e-9):
    """The template with the filter in place: model(xt) returns (c, dc/dxt),
    update(x, dc/dx) returns the new design."""
    hist = []
    for _ in range(maxit):  # @line L2
        xt = flt.apply(x)  # @line L3
        c, gt = model(xt)  # @line L4
        hist.append(c)
        g = flt.transpose(gt)  # @line L5
        new = update(x, g)  # @line L6
        done = max(abs(a - b) for a, b in zip(new, x)) < tol
        x = new
        if done:  # @line L7
            break
    return flt.apply(x), hist  # @line L8


def build(nx, ny, rmin):
    return DensityFilter(nx, ny, rmin)  # @line L1
test_density_filtering.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/density-filtering/. The authors are listed in prov/FZQT96.jsonl.

import math
import random

from density_filtering import build, direct_matrix, filtered_descent, matvec, matvec_transpose

CASES = [(6, 4, 1.5), (7, 5, 2.5), (5, 5, 3.2), (9, 3, 2.0), (4, 6, 1.0)]


def test_sparse_filter_equals_the_direct_weighted_sum() -> None:
    rng = random.Random(1)
    for nx, ny, r in CASES:
        flt = build(nx, ny, r)
        w, d = direct_matrix(nx, ny, r)
        assert max(abs(a - b) for a, b in zip(flt.d, d)) < 1e-12
        for _ in range(5):
            x = [rng.random() for _ in range(nx * ny)]
            assert max(abs(a - b) for a, b in zip(flt.apply(x), matvec(w, x))) < 1e-12
            assert max(abs(a - b) for a, b in zip(flt.transpose(x), matvec_transpose(w, x))) < 1e-12


def test_rows_are_convex_weights_so_the_box_is_kept() -> None:
    rng = random.Random(2)
    for nx, ny, r in CASES:
        w, _ = direct_matrix(nx, ny, r)
        assert all(v >= 0 for row in w for v in row)
        assert all(abs(sum(row) - 1) < 1e-12 for row in w)
        flt = build(nx, ny, r)
        for _ in range(20):
            x = [rng.choice([0.0, 1.0, rng.random()]) for _ in range(nx * ny)]
            xt = flt.apply(x)
            assert min(x) - 1e-12 <= min(xt) and max(xt) <= max(x) + 1e-12


def test_radius_at_most_one_is_the_identity() -> None:
    flt = build(5, 4, 1.0)
    x = [i / 19 for i in range(20)]
    assert flt.apply(x) == x


def test_filter_is_self_adjoint_in_the_d_weighted_inner_product() -> None:
    rng = random.Random(3)
    for nx, ny, r in CASES:
        flt = build(nx, ny, r)
        x = [rng.uniform(-1, 1) for _ in range(nx * ny)]
        y = [rng.uniform(-1, 1) for _ in range(nx * ny)]
        wx, wy = flt.apply(x), flt.apply(y)
        left = sum(d * a * b for d, a, b in zip(flt.d, wx, y))
        right = sum(d * a * b for d, a, b in zip(flt.d, x, wy))
        assert abs(left - right) < 1e-12
        # and in the plain inner product the adjoint is the transpose, not the filter itself
        assert abs(sum(a * b for a, b in zip(wx, y)) - sum(a * b for a, b in zip(x, flt.transpose(y)))) < 1e-12


def test_chain_rule_against_central_differences() -> None:
    rng = random.Random(4)
    nx, ny, r = 8, 5, 2.2
    flt = build(nx, ny, r)
    n = nx * ny
    wts = [rng.uniform(0.5, 2) for _ in range(n)]

    def phi(xt):
        return sum(w * v**3 for w, v in zip(wts, xt))

    x = [rng.uniform(0.2, 0.8) for _ in range(n)]
    xt = flt.apply(x)
    gt = [3 * w * v * v for w, v in zip(wts, xt)]
    right = flt.transpose(gt)
    wrong = flt.apply(gt)  # filtering the gradient with the filter itself
    h = 1e-6
    worst_wrong = 0.0
    for f in range(n):
        xp, xm = list(x), list(x)
        xp[f] += h
        xm[f] -= h
        fd = (phi(flt.apply(xp)) - phi(flt.apply(xm))) / (2 * h)
        assert abs(right[f] - fd) < 1e-7
        worst_wrong = max(worst_wrong, abs(wrong[f] - fd) / abs(fd))
    assert worst_wrong > 0.05  # measured: the wrong rule is off by more than 5% near the boundary


def test_checkerboard_is_damped_by_the_closed_form_factor() -> None:
    nx, ny, r = 12, 12, 1.5
    flt = build(nx, ny, r)
    x = [(-1.0) ** (i + j) for i in range(nx) for j in range(ny)]
    xt = flt.apply(x)
    diag = r - math.sqrt(2)
    factor = (r - 4 * (r - 1) + 4 * diag) / (r + 4 * (r - 1) + 4 * diag)
    for i in range(2, nx - 2):
        for j in range(2, ny - 2):
            assert abs(xt[i * ny + j] - factor * x[i * ny + j]) < 1e-12
    assert abs(factor + 0.040814) < 1e-6


def test_volume_is_kept_inside_but_not_at_the_boundary() -> None:
    nx, ny, r = 10, 10, 1.5
    flt = build(nx, ny, r)
    n = nx * ny

    def column_sum(f):
        x = [0.0] * n
        x[f] = 1.0
        return sum(flt.apply(x))

    assert abs(column_sum(5 * ny + 5) - 1) < 1e-12  # interior: the mass is kept
    corner = column_sum(0)
    assert abs(corner - 0.9177) < 1e-4  # measured: the mass of a corner element shrinks by about 8%
    # the column sums are the chain rule applied to the volume sum(x~)
    assert abs(flt.transpose([1.0] * n)[0] - corner) < 1e-12


def test_filtered_descent_decreases_and_cannot_reach_a_checkerboard() -> None:
    nx, ny, r = 10, 8, 1.5
    flt = build(nx, ny, r)
    n = nx * ny
    target = [float((i + j) % 2) for i in range(nx) for j in range(ny)]

    def model(xt):
        return sum((a - b) ** 2 for a, b in zip(xt, target)), [2 * (a - b) for a, b in zip(xt, target)]

    def update(x, g):
        return [min(1.0, max(0.0, a - 0.25 * b)) for a, b in zip(x, g)]

    xt, hist = filtered_descent(flt, [0.5] * n, model, update, maxit=200)
    assert all(b <= a + 1e-12 for a, b in zip(hist, hist[1:]))
    inner = [xt[i * ny + j] for i in range(2, nx - 2) for j in range(2, ny - 2)]
    assert max(inner) - min(inner) < 0.2  # the filtered field stays nearly flat inside

Exercises

  1. Show that W=D−1HW = D^{-1} H is similar to the symmetric matrix D−1/2HD−1/2D^{-1/2} H D^{-1/2}, so its eigenvalues are real, and that they lie in [−1,1][-1, 1] because the rows of WW are nonnegative and sum to 1.
  2. Compute the checkerboard factor λ\lambda of claim 5 for rmin⁡=2r_{\min} = 2, where the neighbors at distance 2 have weight 0. Check that it is about +0.041+0.041, and explain why the sign changed from rmin⁡=1.5r_{\min} = 1.5.
  3. Derive the chain rule for the projected design xˉ=Pβ(Wx)\bar x = P_\beta(W x) and check it by central differences on a small grid.
  4. Sigmund's sensitivity filter maps a gradient gg to g^e=∑fHefxfgf/(xeDe)\hat g_e = \sum_f H_{ef} x_f g_f / (x_e D_e). Show by a two element example that the map x↦g^(x)x \mapsto \hat g(x), with g=∇ϕ(x)g = \nabla \phi(x) for ϕ(x)=12∥x∥2\phi(x) = \frac12 \|x\|^2, has a Jacobian that is not symmetric, so g^\hat g is not the gradient of any function.
  5. On a 10×1010 \times 10 grid with rmin⁡=1.5r_{\min} = 1.5, compute the column sum of an element on an edge (not a corner) and of the element next to it, inward. Explain why one is below 1 and the other above 1, and check that the sum of all column sums is 100.

References

  1. Tyler E. Bruns and Daniel A. Tortorelli, Topology optimization of non-linear elastic structures and compliant mechanisms, Computer Methods in Applied Mechanics and Engineering 190(26-27), 2001, 3443 to 3459, the filter applied to the densities with a weighting function that decays linearly with the distance, and the use of the filtered densities in the model
  2. Blaise Bourdin, Filters in topology optimization, International Journal for Numerical Methods in Engineering 50(9), 2001, 2143 to 2158, the filtered problem, with the density replaced by its convolution with a kernel, and the proof that it has at least one solution
  3. Ole Sigmund, On the design of compliant mechanisms using topology optimization, Mechanics of Structures and Machines 25(4), 1997, 493 to 524, the mesh-independency filter, which averages the sensitivities instead of the densities
  4. Martin P. Bendsøe and Ole Sigmund, Topology Optimization, Theory, Methods and Applications, Springer, 2003, the chapter on the minimum compliance problem (checkerboards, mesh dependence and the filters that remove them)

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW0 stub
  • the lead paragraph