Algorithmadvanced
Heterogeneous multiscale method
Runs a macroscale solver whose missing data, such as fluxes or forces, are estimated on the fly by short microscale simulations near each point.
- Time
- Θ(M n) worst
- Space
- Θ(M + n) extra
- Where
- M = the number of macro elements; n = the number of micro cells in one micro problem
- Model
- Real RAM
- Properties
- concurrent couplingcost independent of epsdeterministicneeds scale separation
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Weinan E, Bjorn Engquist, 2003
The heterogeneous multiscale method (HMM) solves a problem whose macroscale equation has a known form but unknown data. It runs a macroscale solver, for example finite elements on a coarse mesh, and whenever the solver needs a datum, such as the effective flux at a quadrature point, it sets up a small microscale problem near that point, constrained by the current macro state, and estimates the datum from it. For an elliptic equation with a coefficient , each micro problem is the fine equation on a cell of size with the macro gradient as boundary data, and the averaged flux replaces the unknown effective coefficient. The cost depends on the number of macro points and on the size of a micro cell in units of , not on itself.
In plain words
Suppose you know that heat in a composite plate follows the usual heat equation, but you do not know the effective conductivity, because the plate is made of fibers. One way is to resolve every fiber, which costs too much. HMM instead runs a coarse heat solver. At each point where the coarse solver needs the conductivity, it cuts out a tiny window of the real material, imposes the current coarse temperature slope on the edges of the window, solves the detailed problem in the window and measures the heat flow. The ratio of flow to slope is the conductivity at that point. The windows are tiny and independent, so they are cheap and run in parallel. The coarse solver never needs the full detailed model.
The problem
Given a fine model, here in with on and varying on a scale , and given the form of the macro model, with an unknown matrix , compute a macro solution on a mesh of size that approximates the homogenized solution , the limit of as . The method assumes scale separation: at a point depends only on the fine model near that point.
The algorithm
HMM(a_ε, f, T_H, δ)- 1
for each macro element K with quadrature point x_K do - 2
for each unit gradient e_j: solve -div(a_ε grad v_j) = 0 in I_δ(x_K), v_j - e_j · (x - x_K) = 0 on ∂I_δ - 3
A_K e_j ← mean over I_δ(x_K) of a_ε grad v_j ▷ the estimated flux for gradient e_j - 4
add |K| A_K grad λ_m · grad λ_l to the macro matrix, and ∫_K f λ_l to the load - 5
solve the macro system for U with U = 0 at the boundary nodes - 6
return U and the estimated data A_K
Lines L1, L4 and L5 are a standard finite element method with one quadrature point per element. Lines L2 and L3 are the estimator: the micro problem is a cell problem of periodic homogenization on a cell of size , with Dirichlet data in place of periodic data, and its mean flux is the response to a unit macro gradient. Since the macro model is linear in the gradient, micro problems per point give the full matrix . For a nonlinear macro model, line L2 uses the current macro gradient instead of , and the macro solve becomes a Newton iteration with micro problems in each step.
In 1D the micro problem is tridiagonal and the Thomas algorithm solves it. Its flux is constant on , so is the harmonic mean of over . If holds a whole number of periods, this is the homogenized coefficient exactly.
Example
Take with , and macro elements. The homogenized coefficient is and the homogenized solution is , with .
- With and 16 micro cells, every agrees with to , and the nodal values of agree with to . The whole run uses micro cells. A fine mesh with 16 cells per period on would need 16000 cells, and the HMM count stays at 128 for .
- With one micro cell, line L2 sees only the midpoint value , and , which is 13% low. The micro problem must resolve .
- With and , so that a half period is left over, the error of the estimate is at a point one quarter of a period after a period boundary. For this gives : the error decreases like .
Correctness
The proof has two steps. First, the macro error splits into the error of the macro solver for the homogenized problem and a term from the error of the data: with and the finite element solution with the true ,
Second, in 1D the micro estimate is the harmonic mean over , and for periodic its error obeys , with for whole periods. The general analysis of E, Ming and Zhang has the same structure in several dimensions: the total error is the macro error plus the data error , which they bound in terms of , and the micro discretization. In several dimensions the Dirichlet data of line L2 add a boundary layer of width around , so does not vanish for whole periods; periodic micro data on a cell of whole periods of a periodic medium remove this term.
Proof: The 1D heterogeneous multiscale method has an error controlled by the error of its estimated coefficientsfull
We prove three facts about the 1D method of the page, in exact arithmetic. The problem is on , , with . For the periodic case, with 1-periodic, and the homogenized coefficient is the harmonic mean , so .
Lemma 1 (the micro estimate is a harmonic mean). Let the micro cell have cells of length with values . Lines L2 and L3 return
Proof. The P1 equation of line L2 at an interior micro node reads , so the flux is the same on every cell. Then , and the boundary values give . Line L3 returns , and . The tridiagonal system has one solution, because it is the stiffness matrix of a positive coefficient with Dirichlet conditions.
The same argument for the exact micro problem on , at the ends, gives . The micro mesh of line L2 computes this value with the midpoint rule.
Lemma 2 (the error of the estimate). For the exact micro problem and periodic ,
If is a whole multiple of , then .
Proof. Write with an integer and , and split into intervals of length and a rest of length . The integral of over an interval of length is by periodicity. So
whose absolute value is at most . For the right side is zero. The second bound follows from and , since a harmonic mean of values in lies in .
Theorem (the macro error). Let be the result of lines L4 to L6, and let be the P1 solution of the homogenized problem on the same mesh with the same load. With ,
Proof. Lines L4 and L5 compute the Galerkin solution of for all , with and the load of line L4. The homogenized solution satisfies with . Put . Then
by the Cauchy-Schwarz inequality on each element and then for the sum. Divide by .
Consequences. In 1D with a constant coefficient, the P1 solution is exact at the nodes when the load is exact, and Simpson's rule in line L4 is exact for of degree at most 2 times a linear hat function. So for such , equals the homogenized solution at the nodes, and the HMM error at the nodes comes only from . By Lemma 2, when the micro cell holds whole periods, and is of order otherwise. By Lemma 1 the micro mesh adds the error of the midpoint rule for , which for a smooth periodic over whole periods decreases faster than any power of . This is the structure of the general HMM analysis: the total error is the error of the macro solver for the homogenized problem plus a term controlled by the error of the estimated data.
The proof does not show that is close to ; that is the homogenization theorem, and the HMM approximates , not the fine oscillations of .
Complexity
In the real RAM model, each micro problem in 1D costs with micro cells, and there are of them, so lines L1 to L4 cost . Line L5 is a tridiagonal solve in . The extra space is , since a micro problem is dropped after line L3.
In dimensions with micro cells and right-hand sides per point, the work per macro point is that of sparse solves of size , and depends only on and the micro accuracy. The total cost is independent of , while a direct fine solve costs at least .
Properties
- Top-down. The form of the macro model is chosen first, and the micro model only supplies its data. The method does not discover a new macro equation.
- Independent micro problems. The micro problems at different points do not interact, and they run in parallel.
- Sampling, not covering. The micro cells cover a fraction about of the domain, which is the source of the saving and also the reason that the method needs scale separation.
- The approximation is of . The method computes the homogenized solution. The fine oscillations of can be rebuilt locally from the micro solutions when needed.
Variants and improvements
- Periodic or oversampled micro cells. Periodic data remove the boundary layer for periodic media. For other media, solve on a larger cell and average only over an inner part, which reduces the boundary error.
- Weighted averages. Averaging line L3 with a smooth kernel in place of a plain mean gives faster convergence in for nonperiodic microstructure.
- Nonlinear and time-dependent problems. For a nonlinear flux, the micro problem depends on the current macro gradient, as in the FE2 method. For parabolic problems, the micro problems may be stationary or short time-dependent runs.
- Stiff ODEs and dynamics. For a system with slow and fast variables, the macro solver is an ODE integrator for the slow variables, and its force is a time average over a short run of the full system with the slow variables fixed. Engquist and Tsai studied this case in 2005. Coarse projective integration is a related equation-free approach that extrapolates in time instead.
When to use it
Use HMM when the form of the macroscale equation is known, its data are not known in closed form, and the scales are well separated: elliptic and parabolic problems with fine-scale coefficients, continuum models whose stress comes from molecular dynamics, and slow-fast ODE systems. Use the multiscale finite element method or localized orthogonal decomposition when there is no scale separation, or when the fine solution itself is needed, since they cover the whole domain with local problems. Use periodic homogenization with one cell problem when the medium is exactly periodic and the same everywhere.
Pitfalls
- An unresolved micro problem. A micro mesh that does not resolve gives the wrong data, as the example with one micro cell shows. The error does not decrease with .
- The size of the cell. For a cell with Dirichlet data, the error decreases only like . A cell of a few periods leaves an error of several percent.
- No scale separation. If has features on scales between and , such as long channels, a small cell does not see them, and the estimated data are wrong.
- Expecting the fine solution. approximates . Its gradient is the macro gradient, not the oscillating gradient of , so pointwise fluxes need the micro solutions.
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/heterogeneous-multiscale-method/. The authors are listed in prov/HVHGX1.jsonl.
"""The heterogeneous multiscale method (E and Engquist 2003) for a 1D elliptic problem.
Model problem: -(a_eps(x) u')' = f on (0, 1), u(0) = u(1) = 0, where
a_eps(x) varies on a small scale eps. The macroscale solver is the P1
finite element method on M elements. Its coefficient on element K is not
known; it is estimated at the midpoint x_K by a micro problem on the cell
I = [x_K - delta / 2, x_K + delta / 2]:
-(a_eps v')' = 0 in I, v(x) = x - x_K at both ends of I,
solved by P1 elements on `cells` micro cells with the midpoint value of
a_eps on each. The estimate is the mean flux (1 / delta) * integral of
a_eps v' over I, the response to a unit macro gradient.
In 1D the flux of the micro problem is constant, and the estimate is the
harmonic mean of a_eps over I. If I holds a whole number of periods of a
periodic a_eps, this is the homogenized coefficient a*.
Cost: M micro problems of `cells` unknowns each, Theta(M cells), and one
tridiagonal macro solve, Theta(M). Nothing depends on eps.
"""
from scisparse import thomas
def micro_coefficient(a_eps, x_k, delta, cells):
"""Estimate the macro coefficient at x_k from the micro problem on a cell of size delta."""
eta = delta / cells
left = x_k - delta / 2
a = [a_eps(left + (j + 0.5) * eta) for j in range(cells)]
# Unknowns v_1 .. v_(cells-1); v_0 = -delta / 2 and v_cells = delta / 2.
v0, vn = -delta / 2, delta / 2 # @line L2
if cells == 1:
v = [v0, vn]
else:
sub = [0.0] + [-a[j - 1] / eta for j in range(2, cells)] # @line L2
diag = [(a[j - 1] + a[j]) / eta for j in range(1, cells)] # @line L2
sup = [-a[j] / eta for j in range(1, cells - 1)] + [0.0] # @line L2
rhs = [0.0] * (cells - 1) # @line L2
rhs[0] += a[0] / eta * v0 # @line L2
rhs[-1] += a[cells - 1] / eta * vn # @line L2
v = [v0] + thomas(sub, diag, sup, rhs) + [vn] # @line L2
flux = sum(a[j] * (v[j + 1] - v[j]) for j in range(cells)) # @line L3
return flux / delta # @line L3
def hmm_1d(a_eps, f, M, delta, cells):
"""Macro P1 solve with coefficients from micro problems at the element midpoints.
a_eps, f: functions of x. Returns (U, a_K): the M + 1 nodal values and
the M estimated coefficients.
"""
H = 1.0 / M
a_K = []
diag = [0.0] * (M + 1)
off = [0.0] * M
F = [0.0] * (M + 1)
for e in range(M): # @line L1
xl, xr = e * H, (e + 1) * H
xm = (xl + xr) / 2
ak = micro_coefficient(a_eps, xm, delta, cells) # @line L2
a_K.append(ak)
k = ak / H # @line L4
diag[e] += k # @line L4
diag[e + 1] += k # @line L4
off[e] -= k # @line L4
# Simpson's rule for the load, exact for f of degree 2
F[e] += H * (f(xl) + 2 * f(xm)) / 6 # @line L4
F[e + 1] += H * (2 * f(xm) + f(xr)) / 6 # @line L4
m = M - 1
inner = thomas([0.0] + off[1:m], diag[1:M], off[1:m] + [0.0], F[1:M]) if m > 0 else [] # @line L5
return [0.0] + inner + [0.0], a_K # @line L6
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_heterogeneous_multiscale_method.py 75 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/heterogeneous-multiscale-method/. The authors are listed in prov/HVHGX1.jsonl.
import math
from heterogeneous_multiscale_method import hmm_1d, micro_coefficient
S3 = math.sqrt(3)
def sine(eps):
return lambda x: 2 + math.sin(2 * math.pi * x / eps)
def test_one_period_gives_the_homogenized_coefficient():
for eps in (1 / 64, 1e-3, 1e-5):
a = sine(eps)
assert abs(micro_coefficient(a, 0.3, eps, 16) - S3) < 1e-8
assert abs(micro_coefficient(a, 0.3, eps, 32) - S3) < 1e-11
def test_whole_periods_are_exact_and_the_estimate_is_the_harmonic_mean():
eps = 1 / 64
a = sine(eps)
for p in (1, 2, 3, 4):
assert abs(micro_coefficient(a, 0.41, p * eps, 32 * p) - S3) < 1e-12
delta, cells = 0.37 * eps, 10
eta = delta / cells
left = 0.2 - delta / 2
harmonic = cells / sum(1 / a(left + (j + 0.5) * eta) for j in range(cells))
assert abs(micro_coefficient(a, 0.2, delta, cells) - harmonic) < 1e-13
def test_error_of_a_partial_period_decays_like_eps_over_delta():
eps = 1 / 64
a = sine(eps)
x_k = 0.5 + eps / 4
worst = max(abs(1 / a(k * eps / 1000) - 1 / S3) for k in range(1000))
scaled = []
for p in (1, 2, 4, 8, 16):
delta = (p + 0.5) * eps
ak = micro_coefficient(a, x_k, delta, int(32 * (p + 0.5)))
err = abs(1 / ak - 1 / S3)
assert 0 < err <= (eps / delta) * worst
scaled.append(err * delta / eps)
assert max(scaled) - min(scaled) < 1e-10
assert abs(scaled[0] - 0.0963528) < 1e-6
def test_macro_solution_matches_the_homogenized_solution():
U, a_K = hmm_1d(sine(1e-3), lambda x: 1.0, 8, 1e-3, 16)
for i in range(9):
x = i / 8
assert abs(U[i] - x * (1 - x) / (2 * S3)) < 1e-9
assert all(abs(v - S3) < 1e-8 for v in a_K)
def test_an_unresolved_micro_cell_gives_the_wrong_answer():
U, a_K = hmm_1d(sine(1e-3), lambda x: 1.0, 8, 1e-3, 1)
assert abs(U[4] - 1 / 16) < 1e-12
assert abs(U[4] - 1 / (8 * S3)) > 0.009
def test_cost_does_not_depend_on_eps():
counts = []
for eps in (1e-2, 1e-4, 1e-6):
calls = [0]
base = sine(eps)
def a(x, base=base, calls=calls):
calls[0] += 1
return base(x)
hmm_1d(a, lambda x: 1.0, 10, eps, 16)
counts.append(calls[0])
assert counts == [160, 160, 160]
History
E and Engquist proposed the heterogeneous multiscale method in 2003 as a general framework for problems in which a macroscale model of known form needs data from a microscale model, with applications to homogenization, to molecular dynamics and to ODEs with fast and slow variables. E, Ming and Zhang analyzed the finite element version for elliptic homogenization problems in 2005. Abdulle, E, Engquist and Vanden-Eijnden surveyed the method, its analysis and its applications in Acta Numerica in 2012.
References
- Weinan E and Bjorn Engquist, The heterogeneous multiscale methods, Communications in Mathematical Sciences 1(1), 2003, 87-132, the framework of a macroscale solver with data estimated from microscale problems, with examples for elliptic homogenization and for ODEs with fast and slow variables
- Weinan E, Pingbing Ming and Pingwen Zhang, Analysis of the heterogeneous multiscale method for elliptic homogenization problems, Journal of the American Mathematical Society 18(1), 2005, 121-156, the finite element HMM with micro cells at the quadrature points, and the estimate of the total error by the macro error and the error of the estimated coefficients
- Assyr Abdulle, Weinan E, Bjorn Engquist and Eric Vanden-Eijnden, The heterogeneous multiscale method, Acta Numerica 21, 2012, 1-87, the survey of the method, its error analysis for elliptic, parabolic and dynamical problems, and the choice of micro boundary conditions
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 HVHGX1 Edit this page History Report an error Markdown