Algorithmadvanced
Homogenization method for topology optimization
Also called Bendsoe-Kikuchi method.
Gives each element a periodic cell with a rectangular hole, gets its effective stiffness from the cell problem of homogenization, and optimizes the hole sizes and the cell angle.
- Solves
- Topology optimization
- Time
- O(k n b^2) loopO(g^2 N^6) table
- Space
- O(n b + N^4) extra
- Where
- N = elements across the cell; b = half bandwidth of the stiffness matrix; g = steps of the table in each width; k = number of iterations; n = number of elements
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Martin P. Bendsøe, Noboru Kikuchi, 1988
The homogenization method was the first method of topology optimization as the distribution of material. Bendsøe and Kikuchi (1988) gave every point of the design domain a fine periodic microstructure: a square cell of solid material with a rectangular hole. The two widths of the solid walls and the angle of the cell are the design variables of the point. The stiffness of such a porous material is not the stiffness of the solid times the density: it depends on the shape of the hole and on the direction of the load. Homogenization theory gives it as the solution of a small finite element problem on one cell with periodic boundary conditions, the cell problem. The method computes this effective stiffness for a table of hole sizes, then iterates on the full design: solve the model, turn each cell along the flow of the load, and update the hole sizes by optimality criteria. When all composites are allowed, the relaxed design problem has a solution, which the pure 0/1 problem in general does not, and the cells with rectangular holes are a practical family inside that relaxation. The price is that the result is full of gray composite regions. This page uses the scalar form of the model (heat conduction), proves what holds for its cell problem and its steps, and measures the rest.
In plain words
Instead of asking "is there material here or not", ask "what kind of sponge is here". Each small patch of the part is a sponge with square holes. The holes can be small, so the patch is nearly solid, or large, so it is nearly empty. They can also be long and thin, and then the patch is stiff in one direction and soft in the other, like wood along and across the grain.
First the method works out how stiff each kind of sponge is, once, by testing a single small cell. Then it repeats: load the part, turn the grain of each patch along the path of the load, and make the walls thicker where they work hard and thinner where they do not, keeping the total material fixed.
The problem
The design domain is a grid of square elements. Element carries a cell with solid walls of width (along ) and (along ), so the hole is and the density is
The cell is turned by the angle . The scalar model is heat conduction: the temperature solves $-\nabla \cdot (B \nabla u) = $ source, with the conductivity tensor . The goal is to minimize the thermal compliance , the analogue of the compliance of a structure, subject to and . The solid has conductivity 1 and the hole a small , so every matrix is positive definite.
The cell problem. Let be the conductivity on the unit cell , 1 in the solid and in the hole. For each unit vector , find a periodic with
The function is the correction of the field inside the cell when the average gradient is , and maps an average gradient to the average flux. The code solves this with bilinear elements on an grid of the cell, with the nodes on opposite sides identified.
Bendsøe and Kikuchi solved the same problem for linear elasticity. There the unknown is a displacement vector, the effective stiffness is a fourth order tensor, and a 2D cell needs three load cases (two stretches and a shear) instead of two. The steps of the method are the same.
The algorithm
HOMOGENIZATION(mesh, f, V*, N, g, m, η)- 1
for μ, γ in {0, 1/g, ..., 1}: solve the cell problem on N × N elements; store A11(μ, γ), A22(μ, γ) - 2
μ_e = γ_e ← s with 1 − (1 − s)² = V*/n; θ_e ← 0 - 3
for k = 1 to maxit do - 4
B_e ← R(θ_e) diag(A11, A22)(μ_e, γ_e) R(θ_e)ᵀ ▷ bilinear interpolation in the table - 5
solve K(B) u = f; c_k ← fᵀu - 6
θ_e ← main direction of S_e = Σ_g ¼ q_g q_gᵀ with q_g = B_e ∇u at the Gauss points; add π/2 if A22 > A11 - 7
∂c/∂μ_e ← −u_eᵀ K_e(R ∂A/∂μ Rᵀ) u_e, and the same for γ_e - 8
μ, γ ← optimality criteria step with move limit m and power η, bisection on λ so that Σ ρ_e ≤ V* - 9
if no width changed by more than tol then stop - 10
return μ, γ, θ
Line L1 is done once, before the loop. The cell is symmetric, so is diagonal in the axes of the cell and . In a periodic cell the place of the hole does not matter, so the code puts it in a corner. Line L4 reads the table by bilinear interpolation, which also gives the derivatives that line L7 needs.
Line L6 is the angle step. It looks at the flux at the four Gauss points of the element and turns the stiffer axis of the cell along the main direction of the flux. Line L8 is the optimality criteria update of the SIMP page, applied to both widths: , clipped to and to the move limit, with . The multiplier is found by bisection on a log scale.
Example
A laminate. A cell made of layers of conductivity 1 and 10, in equal parts, has across the layers, the harmonic mean, and along them, the arithmetic mean. The finite element cell problem gives these values exactly when the layers follow the element edges, and the tests check them in exact rational arithmetic. These two means are also the bounds for every cell made of the same pieces (the Wiener bounds), so a laminate is the stiffest possible material along its layers and the softest across them.
The table. With and , part of the table for is:
| (across the wall) | (along the wall) | arithmetic mean | ||
|---|---|---|---|---|
| 0 | 0.40 | 0.4006 | 0.0017 | 0.4006 |
| 0.2 | 0.52 | 0.4168 | 0.2505 | 0.5205 |
| 0.4 | 0.64 | 0.4569 | 0.4569 | 0.6404 |
| 0.6 | 0.76 | 0.5212 | 0.6562 | 0.7602 |
At the cell is a stack of layers in , and equals the arithmetic mean. With both walls present, the material is clearly softer than its density: at the conductivity is 0.457 in both directions. The cell grid matters. For the value of is 0.7272 on elements, 0.7135 on and 0.7083 on . A finer grid can only lower it, because the coarse functions are among the fine ones.
Checkerboards. A checkerboard with conductivities 1 and 10, one element per square, gives exactly , the arithmetic mean, as if the squares were joined in parallel in both directions. The exact value of this checkerboard is , a classical result of Keller (1964) and Dykhne (1970). With , and elements per square the cell problem gives 4.119, 3.666 and 3.444. This is the checkerboard fault of topology optimization in its simplest form: bilinear elements make a checkerboard look much stiffer than it is.
A bar. On a grid, the left edge is held at and the right edge carries a total load of 1, with volume fraction . No design can do better than , and a laminate along the bar reaches it. The start, square holes everywhere, has . The method stops after 7 iterations with , and in every element: the same laminate, built from the other wall and turned by a right angle. Its compliance is 4.9946, 0.04% above the bound.
A heat sink. On a grid with a uniform heat source and a sink of three nodes in the middle of the left edge, with volume fraction 0.4, the compliance falls from 159,396 at the start to 59,223 after 10 iterations and 58,742 after 60. It fell at every iteration, which is a measurement, not a theorem. The result has 22 solid elements near the sink, 14 empty ones in the far corners, and 164 of the 200 elements are gray, with . With the angle held at 0 the same run ends at 60,363, so turning the cells gains about 3% here.
Correctness
What is proved in the correctness proof, for the scalar model with exact element integrals:
- The cell problem has a solution, unique up to a constant, and is symmetric and equal to a minimum of energy over periodic fields.
- For every direction , the harmonic mean the arithmetic mean. The upper bound comes from the zero correction and the lower bound from the Cauchy-Schwarz inequality, using that a periodic correction has zero mean gradient.
- A laminate whose layers follow the element edges gives the harmonic mean across and the arithmetic mean along, exactly.
- Refining the cell grid by 2 cannot raise , and the one-element checkerboard gives the arithmetic mean.
- For fixed hole sizes, the angle step of line L6 does not raise the compliance. The proof writes the compliance as the least complementary energy over all fluxes in equilibrium, keeps the old flux, and minimizes each element's term over the angle.
- Every design has volume at most , and the loop stops.
- For the bar, the bound above holds for every design of the model, and the laminate attains it.
What is not proved: the loop as a whole is not shown to lower the compliance or to converge, because the size step is a fixed point rule. The rectangular hole is also not an optimal microstructure. The optimal composites for compliance are laminates, of rank 1 for the scalar problem with one load and of rank 2 or 3 for elasticity, so the relaxed problem of this page is smaller than the full relaxation.
What the tests check: the laminate formulas and the Wiener bounds on random cells in exact arithmetic, the checkerboard, the symmetry, bounds and monotonicity of the table, the derivatives of line L7 against central differences, the angle step against 64 sampled angles and against the compliance, the bar against its bound, and the heat sink for feasibility.
Proof: The discrete cell problem gives a symmetric tensor between the harmonic and arithmetic means, exact for laminates, and the design loop keeps the volume, never loses compliance in the angle step, and stopsfull
Setting. All elements are bilinear squares (Q4) of side 1, with the stiffness integrals computed exactly. A cell is an periodic grid of elements with conductivities . Let be the space of continuous functions that are bilinear on each element and periodic on the cell, and . For a unit vector , the cell problem asks for with
and the code returns . The design loop works on a grid of unit elements with tensors , the matrix with , the nodes with removed, and the compliance with .
Claim.
- The cell problem has a solution, unique up to a constant, and the computed is symmetric with for every .
- (Wiener bounds.) For every unit vector , , where is the arithmetic mean and is the harmonic mean of the element values.
- (Laminates.) If depends only on the column of the element, then , and exactly.
- (Refinement.) If every element of a cell is split into elements with the same values, the new tensor is at most the old one in the order of symmetric matrices. In the checkerboard with values and , .
- (The angle step.) For fixed hole sizes, line L6 does not increase the compliance.
- (The volume.) Every design of the loop has , where .
- (The bar.) For the bar problem (left edge at , total load on the right edge, length ), every design of the model has , and a laminate along the bar reaches this bound.
- The loop stops after at most maxit iterations, and each bisection after 100 steps.
Proof of 1. The bilinear form is symmetric and positive semidefinite on . If it is 0 at , then on every element, so is constant on the connected cell. With the value at node 0 fixed to 0 the matrix is positive definite, so (1) has a unique solution with , and adding a constant changes neither (1) nor . Take in (1) for : . Adding this to the definition gives , which is symmetric. For , the function solves (1) for , so . The quadratic functional on has (1) as its condition of stationarity and is convex, so is a minimizer.
Proof of 2. Upper bound: in the minimum of claim 1 gives . Lower bound: for every the integral of over the cell is 0, because is periodic and continuous. So , and by the Cauchy-Schwarz inequality,
So for every , and the minimum is at least .
Proof of 3. Let be the value of column and let be the function of alone that is linear on each column with slope . These slopes sum to , so is periodic, and it is in . Then everywhere, so . This equals the lower bound of claim 2, so is a minimizer and . For , the test (1) with reads , which holds because is periodic in and each column is a full period in . So (up to a constant), , and .
Proof of 4. The bilinear functions on the coarse elements are bilinear on each of the fine ones, so the coarse space is a subspace of the fine space and the conductivity is the same function. The minimum of claim 1 over a larger space is not larger, which is the claim for every . For the checkerboard, every one of the 4 nodes is a corner of all 4 elements, the right corner of the two elements in one column and the left corner of the two in the other. Each column holds one element of value and one of value . The load of (1) at a node is , and with the sign for a right corner. So the load is , and the same holds in . Then and .
Proof of 5. The element integrals of Q4 with a constant tensor are exact under the Gauss rule with weights , so , where maps nodal values to the gradients at all Gauss points and is block diagonal with the blocks . For any fluxes at the Gauss points with , the vector with satisfies , so
So . Fix the old fluxes . The new angles change only , and the term of element is , with over its Gauss points (the function complementary in the code). With and , this is with and . Since , it is least when is largest, that is, when is a main eigenvector of , at the angle of line L6. If the same holds with the angle turned by . So the new is at most .
Proof of 6. The start has , so and the volume is . Assume the old design has volume at most . The bisection keeps at a value whose trial design has volume at most , and returns the trial at . This holds at the start, , as long as wherever (and the same for ), which holds on every example of the page: there each factor with a positive is at most 1, so each such width becomes at most its old value. A width with may grow, but means and before, so does not grow there. In every case , so the trial at is feasible. This is in exact arithmetic; the code adds no tolerance, and the tests allow for rounding.
Proof of 7. At the grid points of the table, the cell is the hole cell on an grid with a multiple of the grid, so its arithmetic mean is exactly , and by claim 2 both and are at most . The map is bilinear, so bilinear interpolation reproduces it, and with nonnegative weights the interpolated are at most . A rotation does not change the eigenvalues, so , and . For a positive definite , , so a smaller gives a larger , and for every that is 0 on the left edge. Take . Then , because all the load is on the right edge at , and . The best gives , and . For the laminate , , in every element (a grid point when is), the hole spans the cell in , the cell is layered in , and by claim 3 . Then satisfies : a linear function with a constant tensor gives zero net flux at the interior and top and bottom nodes, and per unit length of the right edge, which is the consistent load. So , the bound.
Proof of 8. Line L3 runs at most maxit times, and the bisection has a fixed count of 100 halvings.
What is not proved. The loop as a whole is not proved to decrease the compliance or to converge: the size step of line L8 is a fixed point rule, not a descent step. On the heat sink example the compliance fell at every one of the measured iterations, which is a measurement. The rectangular hole is a choice of Bendsøe and Kikuchi, not an optimal microstructure: the optimal composites for compliance are laminates (rank-1 for the scalar problem with one load, rank-2 or rank-3 for elasticity), so the relaxed problem of this page is a restriction of the full relaxation, and its optimum is not proved to be the optimum of the relaxation. Elasticity is a vector problem with three cell load cases in 2D and a fourth order tensor; the claims above are for the scalar problem only.
Complexity
The table has entries, half of them by symmetry, and each is a dense solve with unknowns and two right-hand sides, , so it costs . That is about 0.2 s in Python for and , and it is done once for every problem. With the nodes numbered along the short side, the stiffness matrix of the design is a banded matrix with half bandwidth , so each solve takes . The angle, the derivatives and the 100 steps of the bisection take each. So iterations take . The space is for the matrix and for the dense cell matrix. The number of iterations is not bounded by a formula: the bar stopped after 7, and the heat sink was still changing slowly at 60.
Properties
- Relaxed. Allowing all composites removes the lack of optimal designs of the 0/1 problem, which is why the method was a starting point for the theory. The rectangular hole family is a subset of those composites.
- Gray designs. Most elements end as composites. A manufacturable part needs a penalty, a threshold, or a way to build the microstructure itself.
- Anisotropic. Each element has a direction, and the method uses it: the cells turn along the flow of the load.
- Exact steps, heuristic loop. The cell problem, the angle step and the volume are under proof; the convergence of the loop is not.
- Deterministic. The result depends only on the input and the parameters.
Variants and improvements
- Elasticity. The original method: three cell load cases in 2D, six in 3D, and a fourth order tensor. The angle is set from the principal directions of the stress or the strain, a rule whose optimality for orthotropic materials Pedersen (1989) analysed.
- Optimal microstructures. Replacing the rectangular hole with laminates of rank 2 (or 3 in 3D) gives the full relaxation, where the effective tensor has a closed form and no cell table is needed. Allaire's book develops this approach.
- Penalized densities. Replacing the cell by the power law gives the SIMP method, which is what most codes use today: one variable per element, no table and nearly 0/1 designs.
- De-homogenization. Recent work keeps the composite design and turns it into a fine but manufacturable lattice, by projecting the local cell sizes and angles onto a periodic pattern. This brings the method back for parts that are made by additive manufacturing, where fine infill patterns can be printed.
- Filters. The composite design is less prone to checkerboards than a 0/1 model, but a density filter is still used for a length scale.
When to use it
Use it when the result is meant to be a graded or anisotropic material, such as a printed lattice whose cell sizes and directions vary through the part, or when a well posed relaxed problem is needed as a reference for other methods. For a solid part with clean members, SIMP, BESO or the level set method is simpler and gives a 0/1 design directly.
Pitfalls
- Reading density as stiffness. A porous cell is softer than its density, often much softer, and the tensor depends on the direction. Only a laminate along its layers reaches the density.
- Cell grid too coarse. The finite element cell problem overestimates the stiffness, as the checkerboard and the refinement example show.
- The angle along the gradient instead of the flux. For a fixed field, turning the cells along the temperature gradient raises the energy of that field, which is not the same as lowering the compliance. On the heat sink with fixed random hole sizes, that rule made the compliance rise from the second step on, and inside the full loop it made the run diverge. The flux rule of line L6 never does.
- A hole of full size. When a wall width reaches 0 or 1, the derivative of the density in the other width can vanish. The code treats that case on its own in the update.
- Taking the gray result as the part. The result is a material layout, and turning it into a geometry is a separate step.
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
# Part of https://algorithm.tamnd.com/homogenization-method/. The authors are listed in prov/MKGHFA.jsonl.
"""The homogenization method for topology optimization, scalar form.
Bendsoe and Kikuchi (1988) gave every point of the design domain a periodic
microstructure: a square cell with a rectangular hole. The effective stiffness
of the cell comes from the cell problem of homogenization theory, and the
optimizer changes the hole sizes and the angle of the cell. Their model is
linear elasticity. This file uses the scalar problem (heat conduction, or
antiplane shear), where the conductivity of a point is a 2 x 2 tensor, so the
cell problem has two load cases instead of three and the code stays short.
All finite elements are bilinear squares (Q4) of side 1. The solvers work on
any number type, so the tests run the cell problem exactly in Fraction.
"""
import math
# The corners of the unit element, counterclockwise from the origin.
CORNERS = ((0, 0), (1, 0), (1, 1), (0, 1))
def _hat_product(a, b):
"""The integral over [0, 1] of phi_a phi_b, with phi_0 = 1 - t and phi_1 = t."""
return (1 / 3) if a == b else (1 / 6)
def _exact_tables():
"""Kxx, Kyy, Kxy and the gradient integrals Gx, Gy of the unit Q4 element,
as numerator / 12 integers, so they can be scaled in any number type."""
kxx = [[0] * 4 for _ in range(4)]
kyy = [[0] * 4 for _ in range(4)]
kxy = [[0] * 4 for _ in range(4)]
for i, (xi, yi) in enumerate(CORNERS):
for j, (xj, yj) in enumerate(CORNERS):
sxi, syi, sxj, syj = 2 * xi - 1, 2 * yi - 1, 2 * xj - 1, 2 * yj - 1
kxx[i][j] = sxi * sxj * (4 if yi == yj else 2) # times 1/12: 1/3 or 1/6
kyy[i][j] = syi * syj * (4 if xi == xj else 2)
kxy[i][j] = sxi * syj * 3 # 1/4 = 3/12
gx = [6 * (2 * x - 1) for x, _ in CORNERS] # 1/2 = 6/12
gy = [6 * (2 * y - 1) for _, y in CORNERS]
return kxx, kyy, kxy, gx, gy
KXX, KYY, KXY, GX, GY = _exact_tables()
def element_matrix(a11, a12, a22):
"""The 4 x 4 matrix of the integral of grad N_i . A grad N_j on the unit square."""
return [[(a11 * KXX[i][j] + a22 * KYY[i][j] + a12 * (KXY[i][j] + KXY[j][i])) / 12 for j in range(4)] for i in range(4)]
def solve_spd(k, rhs, bw=None):
"""Solve k x = b for every b in rhs by Gaussian elimination without
pivoting, which is safe for a symmetric positive definite k. Only the
band |i - j| <= bw is touched, so a banded k costs O(n bw^2)."""
n = len(k)
bw = n if bw is None else bw
m = [row[:] for row in k]
bs = [b[:] for b in rhs]
for c in range(n):
top = min(n, c + bw + 1)
piv = m[c][c]
row_c = m[c]
for r in range(c + 1, top):
if m[r][c] == 0:
continue
t = m[r][c] / piv
row_r = m[r]
for j in range(c, top):
row_r[j] -= t * row_c[j]
for b in bs:
b[r] -= t * b[c]
out = []
for b in bs:
x = [b[0] * 0] * n
for r in range(n - 1, -1, -1):
top = min(n, r + bw + 1)
s = b[r]
for j in range(r + 1, top):
s -= m[r][j] * x[j]
x[r] = s / m[r][r]
out.append(x)
return out
def cell_tensor(a):
"""The effective conductivity tensor of a periodic cell.
a[r][c] is the conductivity of the element in row r (y) and column c (x) of
an N x N cell. For each unit vector e_j the cell problem asks for a periodic
chi_j with the integral of a (e_j + grad chi_j) . grad v equal to 0 for all
periodic v. Then A_ij is the mean of a (e_i + grad chi_i) . e_j. Returns
((A11, A12), (A12, A22)).
"""
n = len(a)
zero = a[0][0] * 0
nodes = n * n
def node(i, j):
return (j % n) * n + (i % n)
k = [[zero] * nodes for _ in range(nodes)]
g = [[zero] * nodes, [zero] * nodes]
total = zero
for r in range(n):
for c in range(n):
ae = a[r][c]
total += ae
ids = [node(c + dx, r + dy) for dx, dy in CORNERS]
ke = element_matrix(ae, zero, ae)
for p in range(4):
g[0][ids[p]] += ae * GX[p] / 12
g[1][ids[p]] += ae * GY[p] / 12
for q in range(4):
k[ids[p]][ids[q]] += ke[p][q]
# chi is defined up to a constant: fix the value at node 0.
kf = [row[1:] for row in k[1:]]
chi = solve_spd(kf, [[-v for v in g[0][1:]], [-v for v in g[1][1:]]])
chi = [[zero] + x for x in chi]
out = [[zero, zero], [zero, zero]]
for i in range(2):
for j in range(2):
s = sum(g[j][t] * chi[i][t] for t in range(nodes))
out[i][j] = ((total if i == j else zero) + s) / nodes
return out
def hole_cell(mu, gamma, n, void=1e-3):
"""A cell of N x N elements with a rectangular hole of size (1 - mu) by
(1 - gamma). The material is a wall of width mu along y and a wall of
width gamma along x. The hole sits in a corner: in a periodic cell this is
the same structure as a centered hole. mu N and gamma N must be integers."""
hx = round((1 - mu) * n)
hy = round((1 - gamma) * n)
return [[void if (c < hx and r < hy) else 1.0 for c in range(n)] for r in range(n)]
def make_table(grid=5, n=10, void=1e-3):
"""L1: A11 and A22 of the hole cell for mu, gamma in {0, 1/grid, ..., 1}.
By symmetry A12 = 0 and A22(mu, gamma) = A11(gamma, mu)."""
a11 = [[0.0] * (grid + 1) for _ in range(grid + 1)]
a22 = [[0.0] * (grid + 1) for _ in range(grid + 1)]
for i in range(grid + 1):
for j in range(i, grid + 1):
t = cell_tensor(hole_cell(i / grid, j / grid, n, void))
a11[i][j], a22[i][j] = t[0][0], t[1][1]
a11[j][i], a22[j][i] = t[1][1], t[0][0]
return {"grid": grid, "a11": a11, "a22": a22, "void": void}
def interpolate(table, name, mu, gamma):
"""Bilinear interpolation of a table entry and its derivatives in mu and gamma."""
g = table["grid"]
t = table[name]
s, u = mu * g, gamma * g
i, j = min(int(s), g - 1), min(int(u), g - 1)
fs, fu = s - i, u - j
v00, v10, v01, v11 = t[i][j], t[i + 1][j], t[i][j + 1], t[i + 1][j + 1]
val = (1 - fs) * (1 - fu) * v00 + fs * (1 - fu) * v10 + (1 - fs) * fu * v01 + fs * fu * v11
dmu = g * ((1 - fu) * (v10 - v00) + fu * (v11 - v01))
dga = g * ((1 - fs) * (v01 - v00) + fs * (v11 - v10))
return val, dmu, dga
def density(mu, gamma):
return 1 - (1 - mu) * (1 - gamma)
def rotate(a11, a22, th):
"""R diag(a11, a22) R^T with R the rotation by th: returns (b11, b12, b22)."""
c, s = math.cos(th), math.sin(th)
return a11 * c * c + a22 * s * s, (a11 - a22) * c * s, a11 * s * s + a22 * c * c
class Problem:
"""A grid of nx by ny unit elements. Node (i, j) has the number i (ny + 1) + j,
so the stiffness matrix has half bandwidth ny + 2. fixed: nodes with u = 0.
load: the load vector f over all nodes."""
def __init__(self, nx, ny, fixed, load):
self.nx, self.ny = nx, ny
self.fixed = set(fixed)
self.load = load
self.free = [p for p in range((nx + 1) * (ny + 1)) if p not in self.fixed]
self.pos = {p: t for t, p in enumerate(self.free)}
def element_nodes(self, ex, ey):
h = self.ny + 1
return [(ex + dx) * h + ey + dy for dx, dy in CORNERS]
def elements(self):
for ex in range(self.nx):
for ey in range(self.ny):
yield ex * self.ny + ey, self.element_nodes(ex, ey)
def bar_problem(nx, ny, force=1.0):
"""The left edge is held at u = 0 and the right edge carries the total load
force, spread as consistent nodal loads."""
h = ny + 1
load = [0.0] * ((nx + 1) * h)
for j in range(ny):
load[nx * h + j] += force / ny / 2
load[nx * h + j + 1] += force / ny / 2
return Problem(nx, ny, [j for j in range(h)], load)
def sink_problem(nx, ny):
"""Uniform heat source in every element and a small sink (u = 0) at the
middle of the left edge: the volume to point problem."""
h = ny + 1
load = [0.0] * ((nx + 1) * h)
prob = Problem(nx, ny, [], load)
for _, ids in prob.elements():
for p in ids:
load[p] += 0.25
mid = ny // 2
return Problem(nx, ny, [mid - 1, mid, mid + 1], load)
def solve(prob, tensors):
"""Assemble K from the element tensors (b11, b12, b22), solve K u = f on the
free nodes, and return (u, compliance f . u)."""
nf = len(prob.free)
k = [[0.0] * nf for _ in range(nf)]
for e, ids in prob.elements():
ke = element_matrix(*tensors[e])
for p in range(4):
if ids[p] not in prob.pos:
continue
row = k[prob.pos[ids[p]]]
for q in range(4):
if ids[q] in prob.pos:
row[prob.pos[ids[q]]] += ke[p][q]
f = [prob.load[p] for p in prob.free]
(uf,) = solve_spd(k, [f], prob.ny + 2)
u = [0.0] * len(prob.load)
for p, t in prob.pos.items():
u[p] = uf[t]
return u, sum(prob.load[p] * u[p] for p in range(len(u)))
def energy(ue, b):
"""u_e^T K_e(B) u_e for the element tensor B = (b11, b12, b22)."""
ke = element_matrix(*b)
return sum(ue[p] * ke[p][q] * ue[q] for p in range(4) for q in range(4))
GAUSS = (0.5 - 0.5 / math.sqrt(3), 0.5 + 0.5 / math.sqrt(3))
def gradient(ue, x, y):
"""The gradient of the bilinear u at the point (x, y) of the unit element."""
return (1 - y) * (ue[1] - ue[0]) + y * (ue[2] - ue[3]), (1 - x) * (ue[3] - ue[0]) + x * (ue[2] - ue[1])
def flux_moment(ue, b):
"""S = sum over the 2 x 2 Gauss points of w q q^T, with the flux q = B grad u."""
s11 = s12 = s22 = 0.0
for x in GAUSS:
for y in GAUSS:
gx, gy = gradient(ue, x, y)
qx, qy = b[0] * gx + b[1] * gy, b[1] * gx + b[2] * gy
s11 += qx * qx / 4
s12 += qx * qy / 4
s22 += qy * qy / 4
return s11, s12, s22
def best_angle(ue, b, a11, a22):
"""L6: the angle that puts the stiffer axis of the cell along the main
direction of the flux moment S. It minimizes the complementary energy
tr(R diag(a11, a22)^-1 R^T S) of the old flux over the angle."""
s11, s12, s22 = flux_moment(ue, b)
th = 0.5 * math.atan2(2 * s12, s11 - s22)
return th if a11 >= a22 else th + math.pi / 2
def complementary(ue, b, a11, a22, th):
"""The sum over the Gauss points of w q . A(th)^-1 q, with q the flux of ue under b."""
s11, s12, s22 = flux_moment(ue, b)
c, s = math.cos(th), math.sin(th)
# A(th)^-1 = R diag(1/a11, 1/a22) R^T
i11, i12, i22 = c * c / a11 + s * s / a22, (1 / a11 - 1 / a22) * c * s, s * s / a11 + c * c / a22
return i11 * s11 + 2 * i12 * s12 + i22 * s22
def tensors_of(table, mu, gamma, th):
out = []
for m, g, t in zip(mu, gamma, th):
a11 = interpolate(table, "a11", m, g)[0]
a22 = interpolate(table, "a22", m, g)[0]
out.append(rotate(a11, a22, t))
return out
def sensitivities(prob, table, u, mu, gamma, th):
"""L7: dc/dmu_e and dc/dgamma_e, each equal to -u_e^T (dK_e) u_e."""
dmu, dga = [], []
for e, ids in prob.elements():
ue = [u[p] for p in ids]
_, a11m, a11g = interpolate(table, "a11", mu[e], gamma[e])
_, a22m, a22g = interpolate(table, "a22", mu[e], gamma[e])
dmu.append(-energy(ue, rotate(a11m, a22m, th[e])))
dga.append(-energy(ue, rotate(a11g, a22g, th[e])))
return dmu, dga
def _oc_factor(dc, drho, lam):
"""The optimality criteria factor -dc / (lam drho), with the limits made explicit."""
if drho <= 0:
return math.inf if dc < 0 else 1.0
return max(0.0, -dc) / (lam * drho)
def oc_update(mu, gamma, dmu, dga, volume, move=0.2, eta=0.5):
"""L8: the optimality criteria step for both widths, with a bisection on
the multiplier lam in log scale so that the volume is at most the target."""
def trial(lam):
nm, ng = [], []
for m, g, cm, cg in zip(mu, gamma, dmu, dga):
bm = _oc_factor(cm, 1 - g, lam) ** eta
bg = _oc_factor(cg, 1 - m, lam) ** eta
nm.append(min(1.0, m + move, max(0.0, m - move, m * bm)))
ng.append(min(1.0, g + move, max(0.0, g - move, g * bg)))
return nm, ng
lo, hi = -40.0, 40.0
for _ in range(100):
mid = (lo + hi) / 2
nm, ng = trial(10**mid)
if sum(density(a, b) for a, b in zip(nm, ng)) > volume:
lo = mid
else:
hi = mid
return trial(10**hi)
def homogenize(prob, fraction, table=None, move=0.2, eta=0.5, maxit=60, tol=1e-3):
"""Run the homogenization method. Returns (mu, gamma, theta, history)."""
if table is None:
table = make_table() # @line L1
n = prob.nx * prob.ny
volume = fraction * n
s = 1 - math.sqrt(1 - fraction)
mu, gamma, th = [s] * n, [s] * n, [0.0] * n # @line L2
hist = []
for _ in range(maxit): # @line L3
tens = tensors_of(table, mu, gamma, th) # @line L4
u, c = solve(prob, tens) # @line L5
hist.append(c)
th = [best_angle([u[p] for p in ids], tens[e], interpolate(table, "a11", mu[e], gamma[e])[0], interpolate(table, "a22", mu[e], gamma[e])[0]) for e, ids in prob.elements()] # @line L6
dmu, dga = sensitivities(prob, table, u, mu, gamma, th) # @line L7
nm, ng = oc_update(mu, gamma, dmu, dga, volume, move, eta) # @line L8
change = max(max(abs(a - b) for a, b in zip(nm, mu)), max(abs(a - b) for a, b in zip(ng, gamma)))
mu, gamma = nm, ng
if change < tol: # @line L9
break
return mu, gamma, th, hist # @line L10
def bar_lower_bound(prob, force, volume, void):
"""F^2 L^2 / (V (1 - void) + n void): no design of volume at most V does better."""
n = prob.nx * prob.ny
return force**2 * prob.nx**2 / (volume * (1 - void) + n * void)
test_homogenization_method.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/homogenization-method/. The authors are listed in prov/MKGHFA.jsonl.
import math
import random
from fractions import Fraction as F
from homogenization_method import (
bar_lower_bound,
bar_problem,
best_angle,
cell_tensor,
complementary,
density,
hole_cell,
homogenize,
make_table,
sensitivities,
sink_problem,
solve,
tensors_of,
)
TABLE = make_table()
def harmonic(values):
return len(values) / sum(1 / v for v in values)
def arithmetic(values):
return sum(values) / len(values)
def test_laminate_is_harmonic_across_and_arithmetic_along() -> None:
rng = random.Random(1)
for _ in range(8):
n = rng.randint(2, 6)
cols = [F(rng.randint(1, 9), rng.randint(1, 3)) for _ in range(n)]
layered_in_x = [[cols[c] for c in range(n)] for _ in range(n)] # a depends on x only
a = cell_tensor(layered_in_x)
assert a[0][0] == harmonic(cols) # across the layers
assert a[1][1] == arithmetic(cols) # along the layers
assert a[0][1] == 0 and a[1][0] == 0
layered_in_y = [[cols[r]] * n for r in range(n)]
b = cell_tensor(layered_in_y)
assert b[0][0] == arithmetic(cols) and b[1][1] == harmonic(cols)
def test_wiener_bounds_on_random_cells() -> None:
rng = random.Random(2)
for _ in range(30):
n = rng.randint(2, 4)
a = [[F(rng.randint(1, 20), rng.randint(1, 4)) for _ in range(n)] for _ in range(n)]
values = [v for row in a for v in row]
lo, hi = harmonic(values), arithmetic(values)
t = cell_tensor(a)
assert t[0][1] == t[1][0]
# t - lo I and hi I - t are positive semidefinite (2 x 2: diagonal and determinant)
for s, m in ((1, lo), (-1, hi)):
d11, d22, d12 = s * (t[0][0] - m), s * (t[1][1] - m), s * t[0][1]
assert d11 >= 0 and d22 >= 0 and d11 * d22 - d12 * d12 >= 0
def test_one_element_checkerboard_is_as_stiff_as_the_arithmetic_mean() -> None:
a = [[F(1), F(10)], [F(10), F(1)]]
t = cell_tensor(a)
assert t[0][0] == t[1][1] == F(11, 2) and t[0][1] == 0
# Refining by 2 nests the element spaces, so the values fall. The exact value is sqrt(10).
vals = []
for m in (1, 2, 4, 8):
n = 2 * m
cell = [[1.0 if (r // m + c // m) % 2 == 0 else 10.0 for c in range(n)] for r in range(n)]
vals.append(cell_tensor(cell)[0][0])
assert all(x > y for x, y in zip(vals, vals[1:]))
assert vals[-1] > math.sqrt(10)
assert abs(vals[-1] - 3.444) < 1e-3 # measured: still 9% above sqrt(10) at 16 x 16
def test_hole_cell_symmetry_bounds_and_monotonicity() -> None:
g = TABLE["grid"]
a11, a22, void = TABLE["a11"], TABLE["a22"], TABLE["void"]
for i in range(g + 1):
for j in range(g + 1):
mu, ga = i / g, j / g
rho = density(mu, ga)
assert a11[i][j] <= rho + (1 - rho) * void + 1e-12
assert a22[i][j] <= rho + (1 - rho) * void + 1e-12
assert a11[i][j] >= 1 / (rho + (1 - rho) / void) - 1e-12
if i < g:
assert a11[i + 1][j] >= a11[i][j] - 1e-12 and a22[i + 1][j] >= a22[i][j] - 1e-12
if j < g:
assert a11[i][j + 1] >= a11[i][j] - 1e-12 and a22[i][j + 1] >= a22[i][j] - 1e-12
t = cell_tensor(hole_cell(0.6, 0.2, 10))
s = cell_tensor(hole_cell(0.2, 0.6, 10))
assert abs(t[0][1]) < 1e-12 and abs(t[0][0] - s[1][1]) < 1e-12 and abs(t[1][1] - s[0][0]) < 1e-12
def test_sensitivities_against_central_differences() -> None:
rng = random.Random(3)
prob = sink_problem(5, 4)
n = prob.nx * prob.ny
mu = [rng.choice([0.1, 0.3, 0.5, 0.7]) for _ in range(n)]
ga = [rng.choice([0.1, 0.3, 0.5, 0.7]) for _ in range(n)]
th = [rng.uniform(0, math.pi) for _ in range(n)]
u, _ = solve(prob, tensors_of(TABLE, mu, ga, th))
dmu, dga = sensitivities(prob, TABLE, u, mu, ga, th)
h = 1e-6 # stays inside one interpolation cell
for e in range(n):
for d, var in ((dmu, mu), (dga, ga)):
vp, vm = list(var), list(var)
vp[e] += h
vm[e] -= h
if var is mu:
cp = solve(prob, tensors_of(TABLE, vp, ga, th))[1]
cm = solve(prob, tensors_of(TABLE, vm, ga, th))[1]
else:
cp = solve(prob, tensors_of(TABLE, mu, vp, th))[1]
cm = solve(prob, tensors_of(TABLE, mu, vm, th))[1]
fd = (cp - cm) / (2 * h)
assert abs(d[e] - fd) <= 1e-4 * abs(fd) + 1e-6
def test_angle_step_minimizes_the_complementary_energy_and_never_raises_the_compliance() -> None:
rng = random.Random(4)
for _ in range(100):
ue = [rng.uniform(-1, 1) for _ in range(4)]
b = (rng.uniform(0.1, 1), rng.uniform(-0.05, 0.05), rng.uniform(0.1, 1))
a11, a22 = rng.uniform(0.01, 1), rng.uniform(0.01, 1)
best = complementary(ue, b, a11, a22, best_angle(ue, b, a11, a22))
for k in range(64):
assert best <= complementary(ue, b, a11, a22, k * math.pi / 32) + 1e-12
prob = sink_problem(8, 6)
n = prob.nx * prob.ny
mu = [rng.choice([0.0, 0.2, 0.4, 0.6]) for _ in range(n)]
ga = [rng.choice([0.0, 0.2, 0.4]) for _ in range(n)]
th = [rng.uniform(0, math.pi) for _ in range(n)]
last = math.inf
for _ in range(8):
tens = tensors_of(TABLE, mu, ga, th)
u, c = solve(prob, tens)
assert c <= last * (1 + 1e-12)
last = c
th = []
for e, ids in prob.elements():
a11 = TABLE["a11"][round(mu[e] * 5)][round(ga[e] * 5)]
a22 = TABLE["a22"][round(mu[e] * 5)][round(ga[e] * 5)]
th.append(best_angle([u[p] for p in ids], tens[e], a11, a22))
def test_bar_reaches_the_laminate_bound() -> None:
prob = bar_problem(12, 6)
fraction = 0.4
volume = fraction * 72
mu, ga, th, hist = homogenize(prob, fraction, TABLE)
assert sum(density(a, b) for a, b in zip(mu, ga)) <= volume + 1e-9
c = solve(prob, tensors_of(TABLE, mu, ga, th))[1]
bound = bar_lower_bound(prob, 1.0, volume, TABLE["void"])
assert c >= bound * (1 - 1e-12) # proved: no design does better
assert c <= bound * 1.001 # measured: the method finds the laminate along the flux
assert hist[0] > 1.5 * c # the start (square holes) is much softer
def test_sink_problem_feasible_and_improves() -> None:
prob = sink_problem(10, 6)
mu, ga, th, hist = homogenize(prob, 0.4, TABLE, maxit=30)
assert all(0 <= v <= 1 for v in mu + ga)
assert sum(density(a, b) for a, b in zip(mu, ga)) <= 0.4 * 60 + 1e-9
assert solve(prob, tensors_of(TABLE, mu, ga, th))[1] < 0.6 * hist[0]
History
The mathematical theory of homogenization grew in the 1970s, with the books of Bensoussan, Lions and Papanicolaou (1978) and Sanchez-Palencia (1980). In optimal design, work by Murat and Tartar, Lurie and Cherkaev, and Kohn and Strang in the late 1970s and the 1980s showed that the 0/1 problem has in general no solution and that composites, in particular laminates, give its relaxation. Bendsøe and Kikuchi (1988) turned this into a practical method for structures: a cell with a rectangular hole, the effective tensor from a cell table, rotation along the principal directions and an optimality criteria update. A year later Bendsøe (1989) proposed the simpler power law model that became the SIMP method, and the homogenization method became mostly a theoretical reference. Allaire (2002) gave a full account with laminates. Pantz and Trabelsi (2008) proposed turning a composite design into a fine geometry, and since the late 2010s this de-homogenization has brought composite designs back for lattices in additive manufacturing.
References
- Martin P. Bendsøe and Noboru Kikuchi, Generating optimal topologies in structural design using a homogenization method, Computer Methods in Applied Mechanics and Engineering 71(2), 1988, 197 to 224, the cell with a rectangular hole, the effective elastic tensor from the cell problem, the rotation of the cell and the optimality criteria update of the hole sizes
- Grégoire Allaire, Shape Optimization by the Homogenization Method, Springer, Applied Mathematical Sciences 146, 2002, the cell problem, the Wiener bounds, the laminates and the relaxation of the optimal design problem (general locator)
- Martin P. Bendsøe and Ole Sigmund, Topology Optimization, Theory, Methods and Applications, Springer, 2003, the chapter on the minimum compliance problem and the discussion of microstructures and relaxation
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 MKGHFA Edit this page History Report an error Markdown