Techniquecore
Periodic homogenization
Also called two-scale asymptotic expansion.
Replaces a PDE with rapidly oscillating periodic coefficients by an effective PDE whose coefficients come from cell problems on one period.
Periodic homogenization replaces an elliptic equation , whose coefficient is periodic with a small period , by an equation with a constant effective matrix . The matrix comes from cell problems on one period, which do not depend on or on the domain. The solution is the limit of as , and a first-order corrector gives back the gradient of . The effective coefficient is not the average of : in 1D it is the harmonic mean, and for it is , while the average is 2.
In plain words
Think of a plate made of many thin layers of two metals that conduct heat differently. A computer model that resolves every layer needs a very fine mesh. Far from the layers, though, the plate acts like one uniform material with some effective conductivity. Homogenization computes that effective value from a single repeating piece of the material, called the cell. You solve a small problem on the cell once, and you get the constants of a simple model that has no layers in it. The simple model gives the large-scale behavior. A correction term adds back the small ripples when you need them. The effective value is not a plain average. Across the layers, the poor conductor controls the result, as resistors in series do. Along the layers, the good conductor carries most of the heat, as resistors in parallel do.
When it applies
- The coefficients are periodic, or periodic after a smooth change of variables, with a period much smaller than the size of the domain and the scale of . Random stationary media need the stochastic version (see the representative volume element).
- Only the large-scale solution, or averages of fluxes, are of interest. Pointwise gradients need the corrector.
- The equation is elliptic or parabolic in divergence form: heat conduction in composites, flow in porous media (Darcy's law), linear elasticity of composites. Wave equations and nonlinear problems have their own forms of the cell problem.
- A direct fine mesh would need many cells per period, so for any affordable mesh size .
The template
Let be the unit cell and symmetric, -periodic, with .
PERIODIC-HOMOGENIZATION(A, f, Ω, ε)- 1
for j ← 1 to d do - 2
solve -div_y(A(y)(e_j + grad_y χ_j)) = 0 in Y, χ_j periodic with mean 0 - 3
A*_ij ← mean over Y of e_i · A(y)(e_j + grad_y χ_j), for i, j = 1..d - 4
solve -div(A* grad u_0) = f in Ω, u_0 = 0 on the boundary of Ω - 5
grad u_ε ≈ Σ_j (e_j + grad_y χ_j(x/ε)) ∂u_0/∂x_j ▷ first-order corrector - 6
return A*, u_0 and the corrected gradient
Where the cell problem comes from. Put with every periodic in , and use . At order the equation is , so does not depend on . At order it is , which is solved by with the cell problems of line L2. At order , the equation for has a periodic solution only if the mean over of the remaining terms is zero. That condition is the equation of line L4, with from line L3.
Two facts about . First, over periodic , and is the minimizer. So is symmetric and positive definite. Second, with the mean over ,
in the order of symmetric matrices. The upper bound takes in the minimum. The lower bound comes from the same argument for the complementary energy with a constant flux. These are the Voigt and Reuss bounds.
The 1D case. For the flux is a constant . Periodicity of gives , so and
Validity. For smooth , and , and . The rate comes from a boundary layer, because does not vanish on . Without the corrector, does not go to zero in ; it only goes to zero weakly. The rigorous proof of the limit uses two-scale convergence or Tartar's energy method.
Classic examples
- The 1D bar. For , , so . With on the limit is and . The largest error over the interior is 0.00948, 0.00525, 0.00247 and 0.00134 for , so it is of order . A P1 element method on a coarse mesh with and , with exact element integrals of , uses the average 2 on each element and gives . That value is 13% too small for every that divides , and it does not improve as .
- Two phases by hand. Let on and on . Then , and in the first phase and in the second. The flux is 1.6 in both phases, and is periodic because the two slopes cancel.
- A laminate in 2D. Let with the two phases of the last example. For the cell solution is , because has zero divergence, so . For the problem is the 1D one, so . The off-diagonal terms are zero. Both bounds above are attained, each in one direction.
- Composites and porous media. The same cell problem gives the effective elasticity tensor of a fiber composite and the permeability of a periodic porous medium. In numerical form it is the micro problem of the FE2 method and of the heterogeneous multiscale method.
Variations
- Random stationary coefficients. The cell problem lives on all of , and in practice on a large sample. The error of the truncated sample leads to the representative volume element.
- Locally periodic coefficients . Solve one cell problem for each macroscopic point ; then depends on .
- Numerical homogenization without periodicity. The multiscale finite element method and localized orthogonal decomposition build coarse spaces from local fine problems and need no cell or scale separation (LOD), or only a weak form of it (MsFEM).
- Higher-order and boundary-layer correctors. A second corrector and a boundary-layer term restore higher rates near .
- Topology optimization. The homogenization method of structural design uses the same effective tensors of microstructures, but it is a different topic: it optimizes the microstructure, it does not approximate a given one.
Pitfalls
- Averaging the coefficient. The arithmetic mean is only an upper bound. In 1D it is always wrong unless is constant. The coarse element example above shows a 13% error that does not go away as .
- Expecting strong convergence of the gradient. oscillates at scale with an amplitude of order 1. Stresses and fluxes need the corrector of line L5, and even then the error near the boundary is of order in .
- The wrong boundary conditions in the cell. The cell problem of line L2 is periodic. Dirichlet or Neumann conditions on the cell give an upper or a lower bound of , which converge only as the cell grows over many periods.
- No scale separation. If is not small compared with the scale of , of the domain or of the mesh, is a poor model.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/periodic-homogenization/. The authors are listed in prov/W15DY8.jsonl.
"""Periodic homogenization: cell problems, the effective coefficient and the corrector.
The model problem is -div(A(x / eps) grad u) = f in a domain, u = 0 on its
boundary, with A(y) symmetric, bounded and uniformly positive, and
1-periodic in each variable y_i. The technique replaces A(x / eps) by a
constant matrix A* computed from cell problems on one period Y = [0, 1)^d.
1D: the cell problem is solved with P1 elements on a periodic mesh of n
cells with one value of a per cell. Its result is the harmonic mean of
the cell values, exactly in Fraction arithmetic.
2D: the cell problem is solved by finite volumes on a periodic n by n grid
of cells, with one value of a per cell and the harmonic mean of the two
cell values on each face. For a laminate this gives the exact A*.
Cost: 1D, Theta(n) with the Thomas algorithm. 2D, the dense solve of
n^2 - 1 unknowns costs Theta(n^6); this is for small checks only.
"""
from fractions import Fraction
from scimat import solve
from scisparse import thomas
def _one(values):
"""1 as a Fraction when the data are exact, else 1.0."""
return Fraction(1) if all(isinstance(v, (int, Fraction)) for v in values) else 1.0
def cell_problem_1d(a):
"""Solve -(a (1 + chi'))' = 0 on the periodic cell [0, 1) with mean(chi) = 0.
a[k] is the coefficient on cell k = [k h, (k + 1) h], h = 1 / n.
Returns (a_star, chi) with chi the nodal values at k h, k = 0..n - 1.
"""
n = len(a)
one = _one(a)
h = one / n
# In 1D a periodic chi with chi(0) = 0 also has chi(1) = 0, so the
# unknowns are chi_1 .. chi_(n-1) with zero values at both ends.
sub = [0] + [-a[i - 1] / h for i in range(2, n)] # @line L2
diag = [(a[i - 1] + a[i]) / h for i in range(1, n)] # @line L2
sup = [-a[i] / h for i in range(1, n - 1)] + [0] # @line L2
rhs = [a[i] - a[i - 1] for i in range(1, n)] # @line L2
inner = thomas(sub, diag, sup, rhs) if n > 1 else [] # @line L2
chi = [0 * one] + inner
mean = sum(chi) / n
chi = [c - mean for c in chi] # @line L2
chi_ext = chi + [chi[0]]
flux = [a[k] * (1 + (chi_ext[k + 1] - chi_ext[k]) / h) for k in range(n)] # @line L3
a_star = sum(flux) * h # @line L3
return a_star, chi
def cell_problem_2d(a):
"""Effective 2 by 2 matrix of an isotropic coefficient a[j][i] on a periodic n by n grid.
Cell (i, j) is [i h, (i + 1) h] x [j h, (j + 1) h], i along y_1, j along y_2.
Returns (A_star, chi1, chi2) with chi_m the cell values of the corrector
for direction e_m, normalized to mean zero.
"""
n = len(a)
one = _one([v for row in a for v in row])
h = one / n
N = n * n
def idx(i, j):
return (i % n) + n * (j % n)
def face(p, q):
return 2 * p * q / (p + q)
mat = [[0 * one] * N for _ in range(N)]
rhs = [[0 * one, 0 * one] for _ in range(N)]
for j in range(n):
for i in range(n):
k = idx(i, j)
east, west = face(a[j][i], a[j][(i + 1) % n]), face(a[j][i], a[j][(i - 1) % n])
north, south = face(a[j][i], a[(j + 1) % n][i]), face(a[j][i], a[(j - 1) % n][i])
for m, w in ((idx(i + 1, j), east), (idx(i - 1, j), west), (idx(i, j + 1), north), (idx(i, j - 1), south)):
mat[k][k] += w / (h * h) # @line L2
mat[k][m] -= w / (h * h) # @line L2
rhs[k][0] = (east - west) / h # @line L2
rhs[k][1] = (north - south) / h # @line L2
# The periodic system is singular (constants); fix chi = 0 in cell 0.
red = [row[1:] for row in mat[1:]]
sol = solve(red, [r for r in rhs[1:]]) # @line L2
chis = []
for m in range(2): # @line L1
chi = [0 * one] + [row[m] for row in sol]
mean = sum(chi) / N
chis.append([c - mean for c in chi]) # @line L2
A_star = [[0 * one, 0 * one], [0 * one, 0 * one]]
for j in range(n):
for i in range(n):
k = idx(i, j)
east = face(a[j][i], a[j][(i + 1) % n])
north = face(a[j][i], a[(j + 1) % n][i])
for m in range(2):
gx = (chis[m][idx(i + 1, j)] - chis[m][k]) / h + (1 if m == 0 else 0)
gy = (chis[m][idx(i, j + 1)] - chis[m][k]) / h + (1 if m == 1 else 0)
A_star[0][m] += east * gx / N # @line L3
A_star[1][m] += north * gy / N # @line L3
return A_star, chis[0], chis[1] # @line L6
def homogenized_solve_1d(a_star, f, n):
"""P1 solution of -(a_star u0')' = f on (0, 1), u0(0) = u0(1) = 0, on n cells.
f is a constant. Returns the nodal values at k / n, k = 0..n. For a
constant coefficient and a constant f the nodal values are exact.
"""
one = _one([a_star, f])
h = one / n
m = n - 1
sub = [0] + [-a_star / h] * (m - 1) # @line L4
diag = [2 * a_star / h] * m # @line L4
sup = [-a_star / h] * (m - 1) + [0] # @line L4
load = [f * h] * m # @line L4
return [0 * one] + thomas(sub, diag, sup, load) + [0 * one] # @line L4
def corrector_gradient(a, a_star, du0, x, eps):
"""Gradient of u0 + eps u1 with u1 = chi(x / eps) u0'(x), up to O(eps).
In 1D chi' = a_star / a - 1, so the leading term of the gradient is
u0'(x) (1 + chi'(x / eps)) = u0'(x) a_star / a(x / eps). a is a
function of the fast variable y.
"""
return du0 * a_star / a(x / eps) # @line L5
scimat.py 227 lines
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra and error norms for the scientific-computing pages.
A matrix is a list of rows and a vector is a list. Entries may be int,
float or fractions.Fraction. The routines that do not take a square root
(solve, inv, det and the arithmetic) keep Fraction entries exact.
cholesky, cholesky_solve and norm2 take square roots and return floats.
API (fixed; other pages copy this file byte for byte):
zeros(m, n=None) m by n zero matrix (n = m if not given)
eye(n) n by n identity
add(A, B), sub(A, B) entrywise sum and difference (vectors or matrices)
scale(c, A) c times A (vector or matrix)
matmul(A, B) matrix product
matvec(A, x) matrix times vector
transpose(A) transpose
dot(x, y) inner product of two vectors
norm2(x) Euclidean norm of a vector, as a float
outer(x, y) outer product x y^T
solve(A, b) Gaussian elimination with partial pivoting;
b is a vector or a matrix of right sides
inv(A) inverse of A
det(A) determinant of A
cholesky(A) lower triangular L with A = L L^T (floats)
cholesky_solve(L, b) solve L L^T x = b for a vector b
err_l1(e, dx=1) sum |e_j| dx
err_l2(e, dx=1) sqrt(sum e_j^2 dx), as a float
err_linf(e, dx=1) max |e_j| (dx is not used)
observed_order(errors) [log2(E_i / E_(i+1)) for successive errors]
"""
import math
def zeros(m, n=None):
"""Return an m by n matrix of zeros (n = m if n is None)."""
if n is None:
n = m
return [[0] * n for _ in range(m)]
def eye(n):
"""Return the n by n identity matrix."""
out = zeros(n, n)
for i in range(n):
out[i][i] = 1
return out
def _is_matrix(a):
return len(a) > 0 and isinstance(a[0], list)
def add(a, b):
"""Return a + b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a, b):
"""Return a - b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(c, a):
"""Return c times a, for a vector or a matrix a."""
if _is_matrix(a):
return [[c * x for x in row] for row in a]
return [c * x for x in a]
def transpose(a):
"""Return the transpose of the matrix a."""
return [list(col) for col in zip(*a)]
def matmul(a, b):
"""Return the matrix product a b."""
bt = transpose(b)
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""Return the product of the matrix a and the vector x."""
return [sum(aij * xj for aij, xj in zip(row, x)) for row in a]
def dot(x, y):
"""Return the inner product of the vectors x and y."""
return sum(a * b for a, b in zip(x, y))
def norm2(x):
"""Return the Euclidean norm of the vector x, as a float."""
return math.sqrt(float(dot(x, x)))
def outer(x, y):
"""Return the outer product x y^T as a matrix."""
return [[a * b for b in y] for a in x]
def _eliminate(a, rhs):
"""Reduce a to upper triangular form with partial pivoting.
a is a copy of the square matrix, rhs a list of right side rows (one
row per row of a) that receives the same row operations. Return the
number of row swaps. Raise ValueError if a pivot is zero.
"""
n = len(a)
swaps = 0
for k in range(n):
p = max(range(k, n), key=lambda i: abs(a[i][k]))
if a[p][k] == 0:
raise ValueError("matrix is singular")
if p != k:
a[k], a[p] = a[p], a[k]
rhs[k], rhs[p] = rhs[p], rhs[k]
swaps += 1
for i in range(k + 1, n):
f = a[i][k] / a[k][k]
if f == 0:
continue
for j in range(k, n):
a[i][j] -= f * a[k][j]
for j in range(len(rhs[i])):
rhs[i][j] -= f * rhs[k][j]
return swaps
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a vector (the result is a vector) or a matrix with one column per
right side (the result is a matrix). Fraction entries stay exact.
Raise ValueError if a is singular.
"""
n = len(a)
work = [list(row) for row in a]
vector = not _is_matrix(b)
rhs = [[v] for v in b] if vector else [list(row) for row in b]
_eliminate(work, rhs)
m = len(rhs[0]) if n else 0
x = [[0] * m for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(m):
s = rhs[i][j]
for k in range(i + 1, n):
s -= work[i][k] * x[k][j]
x[i][j] = s / work[i][i]
if vector:
return [row[0] for row in x]
return x
def inv(a):
"""Return the inverse of the square matrix a."""
return solve(a, eye(len(a)))
def det(a):
"""Return the determinant of the square matrix a (0 if singular)."""
work = [list(row) for row in a]
rhs = [[] for _ in a]
try:
swaps = _eliminate(work, rhs)
except ValueError:
return 0
d = -1 if swaps % 2 else 1
for i in range(len(a)):
d *= work[i][i]
return d
def cholesky(a):
"""Return the lower triangular L with a = L L^T, in floats.
Raise ValueError if a is not symmetric positive definite.
"""
n = len(a)
low = [[0.0] * n for _ in range(n)]
for j in range(n):
s = float(a[j][j]) - sum(low[j][k] ** 2 for k in range(j))
if s <= 0.0:
raise ValueError("matrix is not positive definite")
low[j][j] = math.sqrt(s)
for i in range(j + 1, n):
t = float(a[i][j]) - sum(low[i][k] * low[j][k] for k in range(j))
low[i][j] = t / low[j][j]
return low
def cholesky_solve(low, b):
"""Solve L L^T x = b, with L from cholesky, for a vector b."""
n = len(low)
y = [0.0] * n
for i in range(n):
y[i] = (float(b[i]) - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
return x
def err_l1(e, dx=1):
"""Return the discrete L1 norm sum |e_j| dx."""
return sum(abs(v) for v in e) * dx
def err_l2(e, dx=1):
"""Return the discrete L2 norm sqrt(sum e_j^2 dx), as a float."""
return math.sqrt(float(sum(v * v for v in e) * dx))
def err_linf(e, dx=1):
"""Return the max norm max |e_j|. dx is accepted for a uniform call and not used."""
return max(abs(v) for v in e)
def observed_order(errors):
"""Return [log2(E_i / E_(i+1))] for a list of errors on meshes h, h/2, h/4, ..."""
return [math.log2(float(errors[i]) / float(errors[i + 1])) for i in range(len(errors) - 1)]
scisparse.py 189 lines
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Tridiagonal solvers, sparse matrices and simple iterative solvers.
A vector is a list. A sparse matrix is a list of rows, and each row is a
dict that maps a column index to a value. Entries may be int, float or
fractions.Fraction. thomas, thomas_periodic, spmatvec, from_dense and
to_dense keep Fraction entries exact. cg takes square roots and works in
float.
API (fixed; other pages copy this file byte for byte):
thomas(a, b, c, d) solve a tridiagonal system. Row i reads
a[i] x[i-1] + b[i] x[i] + c[i] x[i+1] = d[i];
a[0] and c[n-1] are not used.
thomas_periodic(a, b, c, d) solve a cyclic tridiagonal system: as
thomas, but a[0] multiplies x[n-1] and
c[n-1] multiplies x[0]. Uses the
Sherman-Morrison formula. n >= 3.
from_dense(A) sparse copy of a dense matrix (drops zeros)
to_dense(A, ncols=None) dense copy of a sparse matrix
spmatvec(A, x) A times x
poisson2d(nx, ny, dx, dy, bc="dirichlet")
the matrix of MINUS the 5-point Laplacian
on nx by ny unknowns, numbered
k = i + nx * j (i along x, j along y).
bc = "dirichlet": unknowns at the interior
nodes ((i + 1) dx, (j + 1) dy) with zero
values outside; the matrix is symmetric
positive definite.
bc = "periodic": the grid wraps around in
both directions; the matrix is symmetric
positive semidefinite, and its null space
is the constant vectors.
bc = "neumann": unknowns at cell centers,
zero normal derivative at the walls (a
missing neighbor drops out of the
stencil); null space as for "periodic".
cg(A, b, tol=1e-10, maxit=None, x0=None)
conjugate gradient for a symmetric
positive (semi)definite A. Stops when
||b - A x||_2 <= tol * ||b||_2. Returns
(x, iterations). For a singular A, b must
be in the range of A (for the Poisson
matrices above: sum(b) = 0).
gauss_seidel(A, b, iters, x0=None)
iters forward Gauss-Seidel sweeps; every
row needs a nonzero diagonal entry.
"""
import math
def thomas(a, b, c, d):
n = len(d)
if n == 0:
return []
cp = [0] * n
dp = [0] * n
cp[0] = c[0] / b[0] if n > 1 else 0
dp[0] = d[0] / b[0]
for i in range(1, n):
m = b[i] - a[i] * cp[i - 1]
if i < n - 1:
cp[i] = c[i] / m
dp[i] = (d[i] - a[i] * dp[i - 1]) / m
x = [0] * n
x[n - 1] = dp[n - 1]
for i in range(n - 2, -1, -1):
x[i] = dp[i] - cp[i] * x[i + 1]
return x
def thomas_periodic(a, b, c, d):
"""Cyclic tridiagonal solve. A = T + u v^T with u = (gamma, 0, .., 0, c[n-1])
and v = (1, 0, .., 0, a[0] / gamma), so T is tridiagonal."""
n = len(d)
if n < 3:
raise ValueError("thomas_periodic needs n >= 3")
gamma = -b[0]
bb = list(b)
bb[0] = b[0] - gamma
bb[n - 1] = b[n - 1] - c[n - 1] * a[0] / gamma
y = thomas(a, bb, c, d)
u = [0] * n
u[0] = gamma
u[n - 1] = c[n - 1]
z = thomas(a, bb, c, u)
vy = y[0] + a[0] * y[n - 1] / gamma
vz = z[0] + a[0] * z[n - 1] / gamma
f = vy / (1 + vz)
return [y[i] - f * z[i] for i in range(n)]
def from_dense(A):
return [{j: v for j, v in enumerate(row) if v != 0} for row in A]
def to_dense(A, ncols=None):
if ncols is None:
ncols = len(A)
out = []
for row in A:
r = [0] * ncols
for j, v in row.items():
r[j] = v
out.append(r)
return out
def spmatvec(A, x):
return [sum(v * x[j] for j, v in row.items()) for row in A]
def poisson2d(nx, ny, dx, dy, bc="dirichlet"):
if bc not in ("dirichlet", "periodic", "neumann"):
raise ValueError("bc must be dirichlet, periodic or neumann")
cx = 1 / (dx * dx)
cy = 1 / (dy * dy)
A = []
for j in range(ny):
for i in range(nx):
row = {}
k = i + nx * j
for (ii, jj, w) in ((i - 1, j, cx), (i + 1, j, cx), (i, j - 1, cy), (i, j + 1, cy)):
inside = 0 <= ii < nx and 0 <= jj < ny
if bc == "periodic":
ii %= nx
jj %= ny
inside = True
if bc == "neumann" and not inside:
continue
row[k] = row.get(k, 0) + w
if inside:
m = ii + nx * jj
row[m] = row.get(m, 0) - w
A.append({m: v for m, v in row.items() if v != 0})
return A
def cg(A, b, tol=1e-10, maxit=None, x0=None):
n = len(b)
if maxit is None:
maxit = 10 * n
x = [0.0] * n if x0 is None else [float(v) for v in x0]
if x0 is None:
r = [float(v) for v in b]
else:
ax = spmatvec(A, x)
r = [b[i] - ax[i] for i in range(n)]
bnorm = math.sqrt(sum(float(v) * float(v) for v in b))
stop = tol * bnorm
rr = sum(v * v for v in r)
if math.sqrt(rr) <= stop:
return x, 0
p = list(r)
for it in range(1, maxit + 1):
ap = spmatvec(A, p)
pap = sum(p[i] * ap[i] for i in range(n))
if pap <= 0:
return x, it
alpha = rr / pap
for i in range(n):
x[i] += alpha * p[i]
r[i] -= alpha * ap[i]
rr_new = sum(v * v for v in r)
if math.sqrt(rr_new) <= stop:
return x, it
beta = rr_new / rr
rr = rr_new
p = [r[i] + beta * p[i] for i in range(n)]
return x, maxit
def gauss_seidel(A, b, iters, x0=None):
n = len(b)
x = [0] * n if x0 is None else list(x0)
for _ in range(iters):
for i in range(n):
row = A[i]
s = b[i]
diag = 0
for j, v in row.items():
if j == i:
diag = v
else:
s -= v * x[j]
x[i] = s / diag
return x
test_periodic_homogenization.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/periodic-homogenization/. The authors are listed in prov/W15DY8.jsonl.
import math
import random
from fractions import Fraction
from periodic_homogenization import (
cell_problem_1d,
cell_problem_2d,
corrector_gradient,
homogenized_solve_1d,
)
def a_sin(y):
return 2 + math.sin(2 * math.pi * y)
def harmonic(values):
return len(values) / sum(1 / v for v in values)
def simpson(g, lo, hi, m):
h = (hi - lo) / m
s = g(lo) + g(hi)
for i in range(1, m):
s += (4 if i % 2 else 2) * g(lo + i * h)
return s * h / 3
def exact_u_eps(eps, x, m=4000):
"""u for -(a(x / eps) u')' = 1, u(0) = u(1) = 0: a u' = C - x, so u(x) = int_0^x (C - s) / a(s / eps) ds."""
inv = simpson(lambda s: 1 / a_sin(s / eps), 0.0, 1.0, m)
mom = simpson(lambda s: s / a_sin(s / eps), 0.0, 1.0, m)
c = mom / inv
k = max(2, 2 * round(m * x / 2))
return simpson(lambda s: (c - s) / a_sin(s / eps), 0.0, x, k), c
def test_1d_cell_problem_gives_the_harmonic_mean_exactly():
rng = random.Random(3)
a = [Fraction(rng.randint(1, 9), rng.randint(1, 4)) for _ in range(12)]
a_star, chi = cell_problem_1d(a)
assert a_star == Fraction(len(a)) / sum(1 / v for v in a)
assert sum(chi) == 0
assert a_star <= sum(a) / len(a)
def test_two_phase_1d_by_hand():
a_star, _ = cell_problem_1d([Fraction(1), Fraction(4)])
assert a_star == Fraction(8, 5)
def test_sine_coefficient_gives_sqrt3():
for n in (16, 32, 64):
a = [a_sin((k + 0.5) / n) for k in range(n)]
a_star, _ = cell_problem_1d(a)
assert abs(a_star - math.sqrt(3)) < 1e-6
a_star, _ = cell_problem_1d([a_sin((k + 0.5) / 64) for k in range(64)])
assert abs(a_star - 1.7320508075688772) < 1e-12
def test_laminate_2d_is_harmonic_across_and_arithmetic_along():
n = 4
a = [[Fraction(1) if i < n // 2 else Fraction(4) for i in range(n)] for _ in range(n)]
A, chi1, chi2 = cell_problem_2d(a)
assert A == [[Fraction(8, 5), 0], [0, Fraction(5, 2)]]
assert all(c == 0 for c in chi2)
assert sum(chi1) == 0
def test_random_2d_cell_is_symmetric_and_within_the_bounds():
rng = random.Random(7)
n = 6
a = [[rng.uniform(1.0, 10.0) for _ in range(n)] for _ in range(n)]
A, _, _ = cell_problem_2d(a)
flat = [v for row in a for v in row]
lower, upper = harmonic(flat), sum(flat) / len(flat)
assert abs(A[0][1] - A[1][0]) < 1e-12
for d in range(2):
assert lower - 1e-12 <= A[d][d] <= upper + 1e-12
assert A[0][0] * A[1][1] - A[0][1] ** 2 > 0
def test_homogenized_solution_at_the_midpoint():
u0 = homogenized_solve_1d(math.sqrt(3), 1.0, 8)
assert abs(u0[4] - 1 / (8 * math.sqrt(3))) < 1e-14
exact = homogenized_solve_1d(Fraction(2), Fraction(1), 4)
assert exact == [0, Fraction(3, 64), Fraction(1, 16), Fraction(3, 64), 0]
def test_u_eps_converges_to_u0_at_rate_eps():
a_star = math.sqrt(3)
errors = []
for eps in (1 / 4, 1 / 8, 1 / 16, 1 / 32):
err = 0.0
for x in [0.05 + 0.9 * k / 37 for k in range(38)]:
u, _ = exact_u_eps(eps, x)
err = max(err, abs(u - x * (1 - x) / (2 * a_star)))
errors.append(err)
for e1, e2 in zip(errors, errors[1:]):
assert 1.5 < e1 / e2 < 2.6
def test_corrector_fixes_the_gradient():
a_star = math.sqrt(3)
for eps in (1 / 8, 1 / 32):
_, c = exact_u_eps(eps, 0.5)
plain, corrected = 0.0, 0.0
for x in (0.1, 0.23, 0.37, 0.61, 0.83):
du_eps = (c - x) / a_sin(x / eps)
du0 = (0.5 - x) / a_star
plain = max(plain, abs(du_eps - du0))
corrected = max(corrected, abs(du_eps - corrector_gradient(a_sin, a_star, du0, x, eps)))
assert plain > 0.05
assert corrected < eps
Exercises
- For , show that and that the arithmetic mean is .
- Show that for a laminate in 3D, .
- Prove the lower bound for from the dual minimum principle over periodic divergence-free fluxes with mean .
References
- Alain Bensoussan, Jacques-Louis Lions and George Papanicolaou, Asymptotic Analysis for Periodic Structures, AMS Chelsea Publishing 374, 2011 (reprint of the North-Holland edition of 1978), the elliptic problems with periodic coefficients, the two-scale expansion, the cell problem and the error of the first-order corrector
- Grigorios A. Pavliotis and Andrew M. Stuart, Multiscale Methods, Averaging and Homogenization, Texts in Applied Mathematics 53, Springer, 2008, the chapters on homogenization of elliptic PDEs (the formal expansion, the cell problem, the 1D harmonic mean and the layered media)
- Weinan E, Principles of Multiscale Modeling, Cambridge University Press, 2011, Chapter 2 (analytical methods, homogenization) and Chapter 8 (elliptic equations with multiscale coefficients)
- Gregoire Allaire, Homogenization and two-scale convergence, SIAM Journal on Mathematical Analysis 23(6), 1992, 1482-1518, the proof of the homogenized equation by two-scale convergence
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag W15DY8 Edit this page History Report an error Markdown