Algorithm Search⌘K

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
Properties
concurrent couplingcost independent of epsdeterministicneeds scale separation
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 a(x/ε)a(x/\varepsilon), each micro problem is the fine equation on a cell of size δ\delta 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 ε\varepsilon, not on ε\varepsilon 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 −∇⋅(aε∇uε)=f-\nabla \cdot (a_\varepsilon \nabla u_\varepsilon) = f in Ω\Omega with uε=0u_\varepsilon = 0 on ∂Ω\partial \Omega and aεa_\varepsilon varying on a scale ε\varepsilon, and given the form of the macro model, −∇⋅(A(x)∇U)=f-\nabla \cdot (A(x) \nabla U) = f with an unknown matrix AA, compute a macro solution UU on a mesh of size H≫εH \gg \varepsilon that approximates the homogenized solution u0u_0, the limit of uεu_\varepsilon as ε→0\varepsilon \to 0. The method assumes scale separation: AA at a point depends only on the fine model near that point.

The algorithm

  1. HMM(a_ε, f, T_H, δ)
  2. 1for each macro element K with quadrature point x_K do
  3. 2for 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_δ
  4. 3A_K e_j ← mean over I_δ(x_K) of a_ε grad v_j ▷ the estimated flux for gradient e_j
  5. 4add |K| A_K grad λ_m · grad λ_l to the macro matrix, and ∫_K f λ_l to the load
  6. 5solve the macro system for U with U = 0 at the boundary nodes
  7. 6return 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 IδI_\delta of size δ\delta, 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, dd micro problems per point give the full matrix AKA_K. For a nonlinear macro model, line L2 uses the current macro gradient ∇U(xK)\nabla U(x_K) instead of eje_j, 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 IδI_\delta, so AKA_K is the harmonic mean of aεa_\varepsilon over IδI_\delta. If IδI_\delta holds a whole number of periods, this is the homogenized coefficient a∗a^* exactly.

Example

Take aε(x)=2+sin⁡(2πx/ε)a_\varepsilon(x) = 2 + \sin(2\pi x/\varepsilon) with ε=10−3\varepsilon = 10^{-3}, f=1f = 1 and M=8M = 8 macro elements. The homogenized coefficient is a∗=3a^* = \sqrt 3 and the homogenized solution is u0=x(1−x)/(23)u_0 = x(1 - x)/(2\sqrt 3), with u0(1/2)=0.0721688u_0(1/2) = 0.0721688.

  • With δ=ε\delta = \varepsilon and 16 micro cells, every AKA_K agrees with 3\sqrt 3 to 3×10−93 \times 10^{-9}, and the nodal values of UU agree with u0u_0 to 10−1010^{-10}. The whole run uses 8⋅16=1288 \cdot 16 = 128 micro cells. A fine mesh with 16 cells per period on (0,1)(0, 1) would need 16000 cells, and the HMM count stays at 128 for ε=10−6\varepsilon = 10^{-6}.
  • With one micro cell, line L2 sees only the midpoint value aε(xK)=2a_\varepsilon(x_K) = 2, and U(1/2)=1/16=0.0625U(1/2) = 1/16 = 0.0625, which is 13% low. The micro problem must resolve ε\varepsilon.
  • With ε=1/64\varepsilon = 1/64 and δ=(p+12)ε\delta = (p + \tfrac12)\varepsilon, so that a half period is left over, the error of the estimate is ∣1/AK−1/a∗∣=0.0963528/(p+12)|1/A_K - 1/a^*| = 0.0963528/(p + \tfrac12) at a point xKx_K one quarter of a period after a period boundary. For p=1,2,4,8,16p = 1, 2, 4, 8, 16 this gives AK−3=−0.1734,0.1239,0.0667,0.0347,0.0177A_K - \sqrt 3 = -0.1734, 0.1239, 0.0667, 0.0347, 0.0177: the error decreases like ε/δ\varepsilon/\delta.

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 e=max⁡K∣AK−a∗∣e = \max_K |A_K - a^*| and uHu_H the finite element solution with the true a∗a^*,

∥(uH−U)′∥L2≤ea∗∥U′∥L2.\|(u_H - U)'\|_{L^2} \le \frac{e}{a^*} \|U'\|_{L^2}.

Second, in 1D the micro estimate is the harmonic mean over IδI_\delta, and for periodic aa its error obeys ∣1/AK−1/a∗∣≤(ε/δ)max⁡y∣1/a(y)−1/a∗∣|1/A_K - 1/a^*| \le (\varepsilon/\delta) \max_y |1/a(y) - 1/a^*|, with e=0e = 0 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 ee, which they bound in terms of ε\varepsilon, δ\delta and the micro discretization. In several dimensions the Dirichlet data of line L2 add a boundary layer of width ε\varepsilon around ∂Iδ\partial I_\delta, so ee 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 −(aεu′)′=f-(a_\varepsilon u')' = f on (0,1)(0, 1), u(0)=u(1)=0u(0) = u(1) = 0, with 0<α≤aε≤β0 < \alpha \le a_\varepsilon \le \beta. For the periodic case, aε(x)=a(x/ε)a_\varepsilon(x) = a(x/\varepsilon) with aa 1-periodic, and the homogenized coefficient is the harmonic mean a∗=(∫01dy/a(y))−1a^* = (\int_0^1 dy / a(y))^{-1}, so α≤a∗≤β\alpha \le a^* \le \beta.

Lemma 1 (the micro estimate is a harmonic mean). Let the micro cell I=[xK−δ/2,xK+δ/2]I = [x_K - \delta/2, x_K + \delta/2] have cc cells of length η=δ/c\eta = \delta / c with values a1,…,aca_1, \ldots, a_c. Lines L2 and L3 return

aK=(1c∑j=1c1aj)−1.a_K = \Big( \frac1c \sum_{j=1}^{c} \frac{1}{a_j} \Big)^{-1}.

Proof. The P1 equation of line L2 at an interior micro node jj reads aj(vj−vj−1)/η=aj+1(vj+1−vj)/ηa_j (v_j - v_{j-1})/\eta = a_{j+1} (v_{j+1} - v_j)/\eta, so the flux q=aj(vj−vj−1)/ηq = a_j (v_j - v_{j-1})/\eta is the same on every cell. Then vj−vj−1=qη/ajv_j - v_{j-1} = q \eta / a_j, and the boundary values give δ=vc−v0=qη∑j1/aj\delta = v_c - v_0 = q \eta \sum_j 1/a_j. Line L3 returns δ−1∑jaj(vj−vj−1)=δ−1c qη=q\delta^{-1} \sum_j a_j (v_j - v_{j-1}) = \delta^{-1} c\, q \eta = q, and q=c/∑j(1/aj)q = c / \sum_j (1/a_j). The tridiagonal system has one solution, because it is the stiffness matrix of a positive coefficient with Dirichlet conditions. □\square

The same argument for the exact micro problem −(aεv′)′=0-(a_\varepsilon v')' = 0 on II, v=x−xKv = x - x_K at the ends, gives aK=(δ−1∫Idx/aε)−1a_K = (\delta^{-1} \int_I dx / a_\varepsilon)^{-1}. 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 aεa_\varepsilon,

∣1aK−1a∗∣≤εδmax⁡y∣1a(y)−1a∗∣,∣aK−a∗∣≤β2εδmax⁡y∣1a(y)−1a∗∣.\Big| \frac{1}{a_K} - \frac{1}{a^*} \Big| \le \frac{\varepsilon}{\delta} \max_y \Big| \frac{1}{a(y)} - \frac{1}{a^*} \Big|, \qquad |a_K - a^*| \le \beta^2 \frac{\varepsilon}{\delta} \max_y \Big| \frac{1}{a(y)} - \frac{1}{a^*} \Big|.

If δ\delta is a whole multiple of ε\varepsilon, then aK=a∗a_K = a^*.

Proof. Write δ=pε+r\delta = p \varepsilon + r with an integer p≥0p \ge 0 and 0≤r<ε0 \le r < \varepsilon, and split II into pp intervals of length ε\varepsilon and a rest RR of length rr. The integral of 1/aε1/a_\varepsilon over an interval of length ε\varepsilon is ε/a∗\varepsilon / a^* by periodicity. So

1aK−1a∗=1δ∫I(1aε−1a∗)dx=1δ∫R(1aε−1a∗)dx,\frac{1}{a_K} - \frac{1}{a^*} = \frac{1}{\delta} \int_I \Big( \frac{1}{a_\varepsilon} - \frac{1}{a^*} \Big) dx = \frac{1}{\delta} \int_R \Big( \frac{1}{a_\varepsilon} - \frac{1}{a^*} \Big) dx,

whose absolute value is at most (r/δ)max⁡∣1/a−1/a∗∣≤(ε/δ)max⁡∣1/a−1/a∗∣(r / \delta) \max |1/a - 1/a^*| \le (\varepsilon / \delta) \max |1/a - 1/a^*|. For r=0r = 0 the right side is zero. The second bound follows from ∣aK−a∗∣=aKa∗∣1/aK−1/a∗∣|a_K - a^*| = a_K a^* |1/a_K - 1/a^*| and aK,a∗≤βa_K, a^* \le \beta, since a harmonic mean of values in [α,β][\alpha, \beta] lies in [α,β][\alpha, \beta]. □\square

Theorem (the macro error). Let UU be the result of lines L4 to L6, and let uHu_H be the P1 solution of the homogenized problem −(a∗u′)′=f-(a^* u')' = f on the same mesh with the same load. With e=max⁡K∣aK−a∗∣e = \max_K |a_K - a^*|,

∥(uH−U)′∥L2≤ea∗∥U′∥L2.\| (u_H - U)' \|_{L^2} \le \frac{e}{a^*} \| U' \|_{L^2}.

Proof. Lines L4 and L5 compute the Galerkin solution U∈VHU \in V_H of A(U,v)=F(v)A(U, v) = F(v) for all v∈VHv \in V_H, with A(w,v)=∑KaK∫Kw′v′A(w, v) = \sum_K a_K \int_K w' v' and the load FF of line L4. The homogenized solution satisfies A∗(uH,v)=F(v)A^*(u_H, v) = F(v) with A∗(w,v)=a∗∫01w′v′A^*(w, v) = a^* \int_0^1 w' v'. Put v=uH−U∈VHv = u_H - U \in V_H. Then

a∗∥v′∥2=A∗(uH,v)−A∗(U,v)=A(U,v)−A∗(U,v)=∑K(aK−a∗)∫KU′v′≤e ∥U′∥ ∥v′∥a^* \| v' \|^2 = A^*(u_H, v) - A^*(U, v) = A(U, v) - A^*(U, v) = \sum_K (a_K - a^*) \int_K U' v' \le e\, \| U' \|\, \| v' \|

by the Cauchy-Schwarz inequality on each element and then for the sum. Divide by a∗∥v′∥a^* \| v' \|. □\square

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 ff of degree at most 2 times a linear hat function. So for such ff, uHu_H equals the homogenized solution u0u_0 at the nodes, and the HMM error at the nodes comes only from ee. By Lemma 2, e=0e = 0 when the micro cell holds whole periods, and ee is of order ε/δ\varepsilon / \delta otherwise. By Lemma 1 the micro mesh adds the error of the midpoint rule for ∫Idx/aε\int_I dx / a_\varepsilon, which for a smooth periodic aa over whole periods decreases faster than any power of η/ε\eta / \varepsilon. 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 ee of the estimated data.

The proof does not show that uεu_\varepsilon is close to u0u_0; that is the homogenization theorem, and the HMM approximates u0u_0, not the fine oscillations of uεu_\varepsilon.

Complexity

In the real RAM model, each micro problem in 1D costs Θ(n)\Theta(n) with nn micro cells, and there are MM of them, so lines L1 to L4 cost Θ(Mn)\Theta(M n). Line L5 is a tridiagonal solve in Θ(M)\Theta(M). The extra space is Θ(M+n)\Theta(M + n), since a micro problem is dropped after line L3.

In dd dimensions with ndn^d micro cells and dd right-hand sides per point, the work per macro point is that of dd sparse solves of size ndn^d, and nn depends only on δ/ε\delta/\varepsilon and the micro accuracy. The total cost is independent of ε\varepsilon, while a direct fine solve costs at least (1/ε)d(1/\varepsilon)^d.

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 (δ/H)d(\delta/H)^d of the domain, which is the source of the saving and also the reason that the method needs scale separation.
  • The approximation is of u0u_0. The method computes the homogenized solution. The fine oscillations of uεu_\varepsilon 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 δ/ε\delta/\varepsilon 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 ε\varepsilon gives the wrong data, as the example with one micro cell shows. The error does not decrease with HH.
  • The size of the cell. For a cell with Dirichlet data, the error decreases only like ε/δ\varepsilon/\delta. A cell of a few periods leaves an error of several percent.
  • No scale separation. If aεa_\varepsilon has features on scales between ε\varepsilon and HH, such as long channels, a small cell does not see them, and the estimated data are wrong.
  • Expecting the fine solution. UU approximates u0u_0. Its gradient is the macro gradient, not the oscillating gradient of uεu_\varepsilon, 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.

heterogeneous_multiscale_method.pyI0RawGitHub
# 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

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example