Algorithm Search⌘K

Algorithmadvanced

Multiscale finite element method

Also called MsFEM.

Builds basis functions by solving the fine-scale equation on each coarse element, so a coarse solve captures the fine structure.

Time
Θ(N) worst
Space
Θ(N) extra
Where
M = the number of coarse elements; N = the number of fine cells
Properties
conformingdeterministicexact at coarse nodes in 1dnot needs scale separation
Origin
Thomas Y. Hou, Xiao Hui Wu, 1997

The multiscale finite element method (MsFEM) solves an elliptic equation with a rough coefficient, such as −∇⋅(a(x)∇u)=f-\nabla \cdot (a(x) \nabla u) = f with aa that varies on a scale ε\varepsilon, on a coarse mesh of size H≫εH \gg \varepsilon. It does not use the standard linear basis functions. On each coarse element it solves the equation itself, without the source, on a fine local mesh, with the linear hat functions as boundary data. These multiscale basis functions carry the fine oscillations of the solution, so the Galerkin solution in their span is accurate on the coarse mesh. The local problems are independent of each other and of ff, so they run in parallel and can be reused for many right-hand sides. In 1D the method gives the fine solution exactly at the coarse nodes.

In plain words

Picture a slab of rock with thin layers that let water through at very different rates. A coarse mesh with standard elements treats each big element as if its rock were uniform, and it gets the flow wrong by a fixed amount however fine the layers become. MsFEM keeps the coarse mesh but changes the shape functions. For each big element, it solves the flow equation on a fine mesh inside that element only, once, with simple values on the border. The result is a shape function that bends exactly where the rock is tight or open. The coarse problem then has few unknowns, but its shape functions know the layers. You pay for the small local problems once and solve a small global problem.

The problem

Given a domain Ω\Omega, a coefficient a(x)a(x) with 0<α≤a≤β0 < \alpha \le a \le \beta that may vary on a scale ε\varepsilon, a source ff and a coarse mesh TH\mathcal T_H whose elements each carry a fine mesh of size h≤εh \le \varepsilon, compute umsu_{ms} in a space of dimension equal to the number of coarse nodes such that umsu_{ms} approximates the solution of

−∇⋅(a∇u)=f in Ω,u=0 on ∂Ω,-\nabla \cdot (a \nabla u) = f \text{ in } \Omega, \qquad u = 0 \text{ on } \partial \Omega,

with an error that does not grow when ε\varepsilon is smaller than HH. The reference is the fine solution uhu_h on the whole domain, which is the best that the fine mesh allows and costs a solve with all fine unknowns.

The algorithm

  1. MSFEM(a, f, T_H, fine mesh in each K)
  2. 1for each coarse element K in T_H do
  3. 2for each vertex i of K: solve -div(a grad φ_i^K) = 0 in K, φ_i^K = λ_i on ∂K, on the fine mesh of K
  4. 3A_K[i][j] ← ∫_K a grad φ_j^K · grad φ_i^K and F_K[i] ← ∫_K f φ_i^K
  5. 4add A_K into A and F_K into F
  6. 5solve A U = F with U = 0 at the boundary nodes
  7. 6return U and u_ms = Σ_i U_i φ_i on the fine meshes

Here λi\lambda_i is the standard linear hat function of coarse node ii, and ϕi\phi_i is the function that equals ϕiK\phi_i^K on each element KK next to node ii. Since the local problems on two elements next to an edge have the same linear boundary data on that edge, ϕi\phi_i is continuous and the method is conforming. Lines L1 to L4 are a normal finite element assembly, with the integrals done on the fine mesh; line L5 is a sparse solve with one unknown per coarse node.

In 1D the local problem of line L2 is a tridiagonal system that the Thomas algorithm solves, and the basis function of the left vertex is 1−ϕ1 - \phi when ϕ\phi is that of the right vertex. The flux aϕ′a \phi' is then constant on KK, so ϕ′=aˉK/(Ha)\phi' = \bar a_K / (H a), where aˉK\bar a_K is the harmonic mean of aa over KK, and line L3 gives the element stiffness aˉK/H\bar a_K / H. In 1D the MsFEM matrix is the linear element matrix with the harmonic means in place of the arithmetic ones.

Example

Take a(x)=2+sin⁡(2πx/ε)a(x) = 2 + \sin(2\pi x / \varepsilon) with ε=1/32\varepsilon = 1/32, f=1f = 1, a fine mesh of N=512N = 512 cells with the midpoint value of aa on each cell, and coarse meshes of MM elements. The fine solution has uh(1/2)=0.0721688u_h(1/2) = 0.0721688, which agrees with the homogenized value 1/(83)1/(8\sqrt 3) to 10−1010^{-10}, and the energy norm ∥uh∥a=0.2193\|u_h\|_a = 0.2193.

MM HH MsFEM, ∥uh−ums∥a\lVert u_h - u_{ms} \rVert_a standard P1, ∥uh−uH∥a\lVert u_h - u_H \rVert_a P1 at x=1/2x = 1/2
4 1/4 0.0548 0.0951 0.0625
8 1/8 0.0273 0.0842 0.0625
16 1/16 0.0135 0.0813 0.0625
32 1/32 0.0065 0.0805 0.0625

The MsFEM values at the coarse nodes agree with uhu_h up to rounding, below 10−1210^{-12}, for every MM, and the energy error halves with HH. The standard linear elements use the mean 2 of aa on each element, so their midpoint value is 1/161/16, which is 13% low, and their energy error stays above 36% of ∥uh∥a\|u_h\|_a.

By hand, take one coarse element of length H=12H = \tfrac12 with four fine cells and a=1,4,1,4a = 1, 4, 1, 4. The harmonic mean is 1/(12(1+14))=1.61/(\tfrac12 (1 + \tfrac14)) = 1.6, so the flux aϕ′a \phi' is 1.6/H=3.21.6 / H = 3.2, and ϕ\phi rises by 3.2⋅18=0.43.2 \cdot \tfrac18 = 0.4 on the cells with a=1a = 1 and by 0.10.1 on the cells with a=4a = 4: ϕ=0,0.4,0.5,0.9,1\phi = 0, 0.4, 0.5, 0.9, 1.

Correctness

The proof covers the 1D method. The key fact is that the fine space splits into the multiscale space and the space BB of fine functions that vanish at all coarse nodes, and the two are orthogonal in the energy inner product, because each basis function solves the homogeneous equation inside each element. So the MsFEM solution is the multiscale interpolant of the fine solution, which proves the nodal exactness. The error uh−umsu_h - u_{ms} lies in BB and solves local problems with source ff, and the Poincare inequality on each element gives

∥uh−ums∥a≤Hπα∥f∥L2,\|u_h - u_{ms}\|_a \le \frac{H}{\pi \sqrt \alpha} \|f\|_{L^2},

a bound that does not depend on how aa oscillates.

In 2D and 3D this splitting fails, and the analysis of Hou, Wu and Cai for periodic coefficients gives an error of order HH plus terms in ε\varepsilon and a resonance term that grows with ε/H\varepsilon / H. The resonance comes from the linear boundary data of line L2, which force the basis functions to be linear on the coarse edges, while the true solution oscillates there.

Proof: In 1D the multiscale finite element method is exact at the coarse nodes and has an energy error of order Hfull

We prove two facts about the 1D method of the page, in exact arithmetic. The problem is −(au′)′=f-(a u')' = f on (0,1)(0, 1) with u(0)=u(1)=0u(0) = u(1) = 0 and a≥α>0a \ge \alpha > 0 piecewise constant on the fine mesh. Let VhV_h be the fine P1 space with zero boundary values and a(v,w)=∫01av′w′a(v, w) = \int_0^1 a v' w'. The fine solution uh∈Vhu_h \in V_h solves a(uh,v)=(fh,v)a(u_h, v) = (f_h, v) for all v∈Vhv \in V_h, where fhf_h is the P1 interpolant of ff. This is what fine_solve_1d computes.

The multiscale space. On a coarse element K=[xe,xe+1]K = [x_e, x_{e+1}], line L2 computes ϕK∈P1\phi_K \in P1 on the fine cells of KK with ϕK(xe)=0\phi_K(x_e) = 0, ϕK(xe+1)=1\phi_K(x_{e+1}) = 1 and

∫Ka ϕK′v′=0for every fine P1 function v on K with v(xe)=v(xe+1)=0.(1)\int_K a\, \phi_K' v' = 0 \quad \text{for every fine P1 function } v \text{ on } K \text{ with } v(x_e) = v(x_{e+1}) = 0. \tag{1}

The system of line L2 is tridiagonal with a positive diagonal that dominates the row sums of the absolute values of the off-diagonal entries, with strict dominance in the first and last rows, so it has one solution and the Thomas algorithm needs no pivoting. The basis function ψi\psi_i of coarse node xix_i is ϕK\phi_K on the element to the left of xix_i, 1−ϕK1 - \phi_K on the element to the right, and 0 elsewhere. Let VmsV_{ms} be the span of ψ1,…,ψM−1\psi_1, \ldots, \psi_{M-1}. Lines L3 to L5 compute the Galerkin solution ums∈Vmsu_{ms} \in V_{ms}:

a(ums,ψ)=(fh,ψ)for every ψ∈Vms.(2)a(u_{ms}, \psi) = (f_h, \psi) \quad \text{for every } \psi \in V_{ms}. \tag{2}

Lines L3 compute a(ψj,ψi)a(\psi_j, \psi_i) and (fh,ψi)(f_h, \psi_i) element by element without error: on a fine cell, ψi′\psi_i' is constant and fhψif_h \psi_i is a product of two linear functions, whose integral is the formula of _fine_cell_load. Line L4 adds the element values, and line L6 writes umsu_{ms} on the fine mesh.

Lemma 1 (the splitting). Let B={v∈Vh:v(xi)=0 at every coarse node}B = \{ v \in V_h : v(x_i) = 0 \text{ at every coarse node} \}. Then Vh=Vms⊕BV_h = V_{ms} \oplus B, and a(ψ,b)=0a(\psi, b) = 0 for all ψ∈Vms\psi \in V_{ms} and b∈Bb \in B.

Proof. A function in VmsV_{ms} is fixed by its values at the coarse nodes, since ψi(xj)=δij\psi_i(x_j) = \delta_{ij}. For v∈Vhv \in V_h, let Πv=∑iv(xi)ψi\Pi v = \sum_i v(x_i) \psi_i. Then v−Πvv - \Pi v vanishes at every coarse node, so v−Πv∈Bv - \Pi v \in B, and the sum is direct because a function of VmsV_{ms} that vanishes at all coarse nodes is zero. For the orthogonality, b∈Bb \in B restricted to KK is a fine P1 function with zero values at the ends of KK, and on KK the function ψ\psi is a constant plus a multiple of ϕK\phi_K. A constant has zero derivative, and (1) gives ∫Ka ϕK′b′=0\int_K a\, \phi_K' b' = 0. Summing over KK gives a(ψ,b)=0a(\psi, b) = 0. □\square

Theorem 1 (nodal exactness). ums(xi)=uh(xi)u_{ms}(x_i) = u_h(x_i) at every coarse node, and ums=Πuhu_{ms} = \Pi u_h.

Proof. Write uh=Πuh+bu_h = \Pi u_h + b with b∈Bb \in B by Lemma 1. For ψ∈Vms\psi \in V_{ms},

a(Πuh,ψ)=a(uh,ψ)−a(b,ψ)=(fh,ψ)−0,a(\Pi u_h, \psi) = a(u_h, \psi) - a(b, \psi) = (f_h, \psi) - 0,

because ψ∈Vh\psi \in V_h and by Lemma 1. So Πuh\Pi u_h solves (2). The matrix of (2) is the Gram matrix of the linearly independent functions ψi\psi_i in the inner product aa, so (2) has one solution, and ums=Πuhu_{ms} = \Pi u_h. At a coarse node, Πuh(xi)=uh(xi)\Pi u_h(x_i) = u_h(x_i). □\square

Theorem 2 (energy error). With ∥v∥a=a(v,v)1/2\|v\|_a = a(v, v)^{1/2} and HH the largest coarse element,

∥uh−ums∥a≤Hπα ∥fh∥L2.\|u_h - u_{ms}\|_a \le \frac{H}{\pi \sqrt \alpha}\, \|f_h\|_{L^2}.

Proof. By Theorem 1, e=uh−ums=b∈Be = u_h - u_{ms} = b \in B. For v∈Bv \in B, Lemma 1 gives a(ums,v)=0a(u_{ms}, v) = 0, so a(e,v)=a(uh,v)=(fh,v)a(e, v) = a(u_h, v) = (f_h, v). Take v=ev = e and restrict to one element KK of length HKH_K; the function ee vanishes at both ends of KK, and e∣Ke|_K extended by zero lies in BB, so

∥e∥a,K2=(fh,e)K≤∥fh∥L2(K)∥e∥L2(K)≤∥fh∥L2(K)HKπ∥e′∥L2(K)≤∥fh∥L2(K)HKπα∥e∥a,K.\|e\|_{a, K}^2 = (f_h, e)_K \le \|f_h\|_{L^2(K)} \|e\|_{L^2(K)} \le \|f_h\|_{L^2(K)} \frac{H_K}{\pi} \|e'\|_{L^2(K)} \le \|f_h\|_{L^2(K)} \frac{H_K}{\pi \sqrt \alpha} \|e\|_{a, K}.

The second step is the Poincare inequality ∥w∥L2(0,L)≤(L/π)∥w′∥L2(0,L)\|w\|_{L^2(0, L)} \le (L/\pi) \|w'\|_{L^2(0, L)} for w∈H01(0,L)w \in H^1_0(0, L), whose best constant is the inverse square root of the first Dirichlet eigenvalue (π/L)2(\pi/L)^2. The third uses a≥αa \ge \alpha. Divide by ∥e∥a,K\|e\|_{a, K}, square, and add over KK. □\square

The bound does not depend on the fine structure of aa, only on its lower bound. This is the point of the method: the coarse space carries the oscillations of uhu_h, and what it misses is a sum of local bubbles driven by ff. In 2D and 3D, Lemma 1 fails: a fine function that vanishes at the coarse nodes need not vanish on the coarse edges, so it is not aa-orthogonal to VmsV_{ms}, and the boundary data of the local problems add an extra resonance error. The proof above is for 1D only.

Complexity

In the real RAM model, line L2 in 1D costs Θ(n)\Theta(n) on an element with nn fine cells, and lines L1 to L4 together cost Θ(N)\Theta(N) for N=MnN = M n fine cells. Line L5 is a tridiagonal solve in Θ(M)\Theta(M). The total is Θ(N)\Theta(N) time and Θ(N)\Theta(N) space for the basis functions, the same order as the fine solve, but the local work is independent across elements and reusable.

In dd dimensions with ndn^d fine cells per element, each local problem is a sparse solve of size ndn^d with d+1d + 1 or 2d2^d right-hand sides. The coarse problem has MM unknowns. For a new source ff only lines L3 to L5 are repeated.

Properties

  • Conforming and symmetric. With linear boundary data the basis functions are continuous, and the coarse matrix is symmetric positive definite.
  • Local and parallel. Each element needs only its own fine mesh and coefficient.
  • No periodicity needed. The method uses the actual coefficient, not a cell problem, so it works for random or channelized media. It still works best when HH is well above or well below ε\varepsilon, not near it.
  • Partition of unity. The basis functions add up to 1, since the constant solves the local problem.

Variants and improvements

  • Oversampling. Solve the local problems on a larger patch around KK and restrict the result to KK. The boundary layer of the local solution then lies outside KK, and the resonance error is much smaller. The basis functions are no longer continuous, so the method is nonconforming; Efendiev, Hou and Wu analyzed it in 2000.
  • Reduced boundary conditions. Replace the linear edge data by the solution of a 1D problem along each edge, which follows the oscillations of aa along the edge.
  • Mixed MsFEM. Build multiscale velocity basis functions for the Darcy flux. This is common in reservoir simulation, where mass conservation matters.
  • Generalized MsFEM. Use several local eigenfunctions per element for high-contrast coefficients with channels, which a single basis function per node cannot resolve.
  • Localized orthogonal decomposition. Correct the hat functions by fine-scale problems on patches of a few layers, with a constraint that removes the resonance and gives an error of order HH without scale separation.

When to use it

Use MsFEM when the coefficient is rough on a scale far below any affordable coarse mesh, when the same coefficient is used with many sources or in many time steps, and when the local problems can be solved in parallel: subsurface flow, composites, heat conduction in heterogeneous media. If the coefficient is periodic and only the effective behavior is needed, periodic homogenization is cheaper. If the macroscopic equation is known but its data are not, the heterogeneous multiscale method samples small micro cells instead of covering each element. If a guaranteed rate without scale separation is needed, use localized orthogonal decomposition.

Pitfalls

  • Resonance. When HH is a small multiple of ε\varepsilon, the linear boundary data create a boundary layer in each element and the error does not decrease as expected. Oversampling or a smaller H/εH / \varepsilon ratio is needed.
  • An unresolved fine mesh. The local problems must resolve aa. A local mesh with h>εh > \varepsilon gives basis functions that are wrong in the same way as standard elements.
  • Inexact integrals. Line L3 must integrate on the fine mesh. A coarse quadrature rule with one point per element loses the information in the basis functions.
  • High contrast. If aa contains thin channels of high value that cross many elements, one basis function per node is not enough; the error depends on the contrast β/α\beta / \alpha.

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.

multiscale_finite_element_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multiscale-finite-element-method/. The authors are listed in prov/6V214F.jsonl.
"""The multiscale finite element method (Hou and Wu 1997) in 1D.

Model problem: -(a(x) u')' = f on (0, 1), u(0) = u(1) = 0, with a rough
coefficient a >= alpha > 0.

The fine mesh has N = M n cells of size h = 1 / N, with one value a[j] of
the coefficient on cell j. The coarse mesh has M elements; coarse element
e holds the fine cells e n .. e n + n - 1. f is given by its values at the
N + 1 fine nodes and is used through its P1 interpolant, so every integral
below is exact.

On each coarse element the basis function of the right vertex solves the
local problem -(a phi')' = 0 with phi = 0 at the left end and 1 at the
right end, by fine P1 elements. The basis function of the left vertex is
1 - phi. The coarse Galerkin problem in the span of these functions has M - 1
unknowns.

Cost: Theta(N) for the local solves and the element integrals, and
Theta(M) for the coarse solve. Fraction input gives exact output.
"""

from scisparse import thomas


def _fine_cell_load(h, f_left, f_right):
    """Exact integrals of the P1 interpolant of f against the two hat functions of one fine cell."""
    return h * (2 * f_left + f_right) / 6, h * (f_left + 2 * f_right) / 6


def local_basis(a_local, h, kind="msfem"):
    """Nodal values phi_0 .. phi_n of the right-vertex basis function on one coarse element.

    kind = "msfem": the discrete solution of -(a phi')' = 0, phi(0) = 0, phi(n h) = 1.
    kind = "linear": phi_k = k / n, the standard P1 basis (for comparison).
    """
    n = len(a_local)
    if kind == "linear":
        return [type(h)(k) / n for k in range(n + 1)]
    if n == 1:
        return [0 * h, 1 + 0 * h]
    sub = [0] + [-a_local[k - 1] / h for k in range(2, n)]                    # @line L2
    diag = [(a_local[k - 1] + a_local[k]) / h for k in range(1, n)]           # @line L2
    sup = [-a_local[k] / h for k in range(1, n - 1)] + [0]                    # @line L2
    rhs = [0 * h] * (n - 2) + [a_local[n - 1] / h]                            # @line L2
    inner = thomas(sub, diag, sup, rhs)                                       # @line L2
    return [0 * h] + inner + [1 + 0 * h]


def msfem_1d(a, f, M, kind="msfem"):
    """Solve -(a u')' = f, u(0) = u(1) = 0, with M coarse elements.

    a: list of N fine cell values, N a multiple of M.
    f: list of N + 1 nodal values of f on the fine mesh.
    Returns (U, u_fine): U the M + 1 coarse nodal values and u_fine the
    N + 1 fine nodal values of the multiscale solution.
    """
    N = len(a)
    if N % M != 0 or len(f) != N + 1:
        raise ValueError("need len(a) = M n and len(f) = len(a) + 1")
    n = N // M
    zero = 0 * a[0] * f[0]
    h = (1 + zero) / N
    diag = [zero] * (M + 1)
    off = [zero] * M
    F = [zero] * (M + 1)
    basis = []
    for e in range(M):                                                        # @line L1
        lo = e * n
        phi = local_basis(a[lo:lo + n], h, kind)                              # @line L2
        basis.append(phi)
        # psi_right = phi and psi_left = 1 - phi, so psi_left' = -phi'
        k_e = sum(a[lo + k] * (phi[k + 1] - phi[k]) ** 2 / h for k in range(n))  # @line L3
        f_left, f_right = zero, zero
        for k in range(n):                                                    # @line L3
            b0, b1 = _fine_cell_load(h, f[lo + k], f[lo + k + 1])             # @line L3
            f_right += phi[k] * b0 + phi[k + 1] * b1                          # @line L3
            f_left += (1 - phi[k]) * b0 + (1 - phi[k + 1]) * b1               # @line L3
        diag[e] += k_e                                                        # @line L4
        diag[e + 1] += k_e                                                    # @line L4
        off[e] -= k_e                                                         # @line L4
        F[e] += f_left                                                        # @line L4
        F[e + 1] += f_right                                                   # @line L4
    # Dirichlet conditions: the unknowns are U_1 .. U_(M-1).
    m = M - 1
    inner = thomas([zero] + off[1:m], diag[1:M], off[1:m] + [zero], F[1:M]) if m > 0 else []  # @line L5
    U = [zero] + inner + [zero]
    u_fine = [zero] * (N + 1)
    for e in range(M):                                                        # @line L6
        phi = basis[e]                                                        # @line L6
        for k in range(n + 1):                                                # @line L6
            u_fine[e * n + k] = U[e] * (1 - phi[k]) + U[e + 1] * phi[k]       # @line L6
    return U, u_fine


def fine_solve_1d(a, f):
    """Reference: the fine P1 solution of the same problem on all N cells."""
    N = len(a)
    zero = 0 * a[0] * f[0]
    h = (1 + zero) / N
    load = [zero] * (N + 1)
    for j in range(N):
        b0, b1 = _fine_cell_load(h, f[j], f[j + 1])
        load[j] += b0
        load[j + 1] += b1
    sub = [zero] + [-a[j - 1] / h for j in range(2, N)]
    diag = [(a[j - 1] + a[j]) / h for j in range(1, N)]
    sup = [-a[j] / h for j in range(1, N - 1)] + [zero]
    return [zero] + thomas(sub, diag, sup, load[1:N]) + [zero]


def energy_norm(a, v):
    """sqrt of the sum over fine cells of a[j] ((v[j+1] - v[j]) / h)^2 h, in float."""
    N = len(a)
    return sum(float(a[j]) * float(v[j + 1] - v[j]) ** 2 * N for j in range(N)) ** 0.5
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_multiscale_finite_element_method.py 75 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multiscale-finite-element-method/. The authors are listed in prov/6V214F.jsonl.
import math
import random
from fractions import Fraction

from multiscale_finite_element_method import energy_norm, fine_solve_1d, local_basis, msfem_1d


def oscillating(N, eps):
    return [2 + math.sin(2 * math.pi * (j + 0.5) / N / eps) for j in range(N)]


def test_coarse_values_equal_the_fine_solution_exactly():
    rng = random.Random(11)
    N, M = 12, 3
    a = [Fraction(rng.randint(1, 20), rng.randint(1, 5)) for _ in range(N)]
    f = [Fraction(rng.randint(-5, 5), rng.randint(1, 3)) for _ in range(N + 1)]
    U, u_fine = msfem_1d(a, f, M)
    ref = fine_solve_1d(a, f)
    n = N // M
    assert U == [ref[i * n] for i in range(M + 1)]
    assert u_fine[0] == 0 and u_fine[N] == 0


def test_local_basis_is_discrete_harmonic_with_constant_flux():
    a = [Fraction(1), Fraction(4), Fraction(1), Fraction(4)]
    h = Fraction(1, 8)
    phi = local_basis(a, h)
    flux = [a[k] * (phi[k + 1] - phi[k]) / h for k in range(4)]
    assert phi[0] == 0 and phi[-1] == 1
    assert len(set(flux)) == 1
    # the flux is the harmonic mean over the element divided by its length
    assert flux[0] == Fraction(8, 5) / (4 * h)


def test_energy_error_is_of_order_H_and_below_the_bound():
    N, eps = 512, 1 / 32
    a = oscillating(N, eps)
    f = [1.0] * (N + 1)
    ref = fine_solve_1d(a, f)
    errors = []
    for M in (4, 8, 16, 32):
        _, u = msfem_1d(a, f, M)
        err = energy_norm(a, [u[j] - ref[j] for j in range(N + 1)])
        bound = (1 / M) / (math.pi * math.sqrt(min(a))) * 1.0
        assert err <= bound
        errors.append(err)
    for e1, e2 in zip(errors, errors[1:]):
        assert 1.8 < e1 / e2 < 2.2


def test_standard_p1_on_a_coarse_mesh_is_wrong_and_msfem_is_not():
    N, eps, M = 512, 1 / 16, 8
    a = oscillating(N, eps)
    f = [1.0] * (N + 1)
    ref = fine_solve_1d(a, f)
    n = N // M
    U_ms, _ = msfem_1d(a, f, M)
    U_p1, _ = msfem_1d(a, f, M, kind="linear")
    err_ms = max(abs(U_ms[i] - ref[i * n]) for i in range(M + 1))
    err_p1 = max(abs(U_p1[i] - ref[i * n]) for i in range(M + 1))
    assert err_ms < 1e-12
    # P1 sees the arithmetic mean 2 instead of the harmonic mean sqrt(3)
    assert abs(U_p1[M // 2] / ref[N // 2] - math.sqrt(3) / 2) < 1e-3
    assert err_p1 > 0.005


def test_basis_is_a_partition_of_unity_and_monotone():
    rng = random.Random(5)
    a = [rng.uniform(0.1, 10.0) for _ in range(16)]
    phi = local_basis(a, 1 / 64)
    assert all(phi[k] < phi[k + 1] for k in range(16))
    U, u = msfem_1d(a * 4, [0.0] * 65, 4)
    assert U == [0.0] * 5 and u == [0.0] * 65

History

Hou and Wu introduced the multiscale finite element method in 1997, for elliptic problems in composite materials and porous media, together with the oversampling technique. Babuska and Osborn had used special basis functions from local problems for 1D problems with rough coefficients in 1983. Hou, Wu and Cai proved convergence for periodic coefficients in 1999 and identified the resonance error. Efendiev, Hou and Wu analyzed the nonconforming oversampling method in 2000. Later work produced mixed and generalized versions, and the method became a standard tool of numerical homogenization and reservoir simulation.

References

  1. Thomas Y. Hou and Xiao-Hui Wu, A multiscale finite element method for elliptic problems in composite materials and porous media, Journal of Computational Physics 134(1), 1997, 169-189, the multiscale basis functions from local problems on each coarse element, the oversampling technique and the numerical tests for composites and porous media
  2. Thomas Y. Hou, Xiao-Hui Wu and Zhiqiang Cai, Convergence of a multiscale finite element method for elliptic problems with rapidly oscillating coefficients, Mathematics of Computation 68(227), 1999, 913-943, the error analysis for periodic coefficients, with the resonance error when the coarse mesh size is close to the period
  3. Yalchin R. Efendiev, Thomas Y. Hou and Xiao-Hui Wu, Convergence of a nonconforming multiscale finite element method, SIAM Journal on Numerical Analysis 37(3), 2000, 888-910, the analysis of the oversampling method, which is nonconforming, and the reduction of the resonance error

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.

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