Algorithm Search⌘K

Algorithmresearch

Localized orthogonal decomposition

Corrects coarse basis functions by local fine-scale problems that decay exponentially, giving optimal coarse rates for rough coefficients.

Time
Θ(k³ N³ / M² + M² N) worst
Space
Θ(k² N² / M² + M N) extra
Where
M = the number of coarse elements; N = the number of fine cells; k = the number of patch layers
Properties
deterministicenergy orthogonalexponential localizationno scale separation
Origin
Axel Malqvist, Daniel Peterseim, 2014

The localized orthogonal decomposition (LOD) is a coarse finite element method for elliptic problems whose coefficient varies on a scale much finer than the coarse mesh. It needs no periodicity and no separation of scales. It splits the fine finite element space into a coarse part and a fine-scale part WW, the kernel of a quasi-interpolation IHI_H, and corrects each coarse basis function so that the coarse space becomes orthogonal to WW in the energy inner product. The corrections decay exponentially away from their element, so each one is computed on a patch of a few coarse layers. The result is a Galerkin method on the coarse mesh with error of order HH in the energy norm for any bounded coefficient, where the standard coarse method can fail to converge at all.

In plain words

A coarse mesh cannot see the fine structure of a rough material, so its hat functions are the wrong shape and the coarse answer can be badly wrong. LOD bends each hat function to fit the material. It finds the bend by solving a small fine-mesh problem near the hat function, with a rule that the bend adds nothing that the coarse mesh can see. The ideal bend spreads over the whole domain, but it fades fast, so a patch of two or three coarse elements is enough. The bent hat functions then give an accurate coarse solution with a small number of unknowns.

The problem

Given a domain DD, a coefficient aa with 0<α≤a≤β0 < \alpha \le a \le \beta that may vary arbitrarily on a fine mesh of width hh, a source ff, a coarse mesh of width HH that the fine mesh refines, and a number of layers kk, find an approximation of the fine solution uh∈Vhu_h \in V_h of

a(uh,v)=∫Da∇uh⋅∇v=(f,v)for all v∈Vh,a(u_h, v) = \int_D a \nabla u_h \cdot \nabla v = (f, v) \quad \text{for all } v \in V_h,

in a space with one unknown per coarse node, with energy error of order HH that does not depend on how aa oscillates.

Let VH⊂VhV_H \subset V_h be the coarse P1 space with hat functions λi\lambda_i. LOD uses a quasi-interpolation IH:Vh→VHI_H : V_h \to V_H that is a projection, local and stable. A common choice, used here, is IH=EH∘ΠHI_H = E_H \circ \Pi_H: ΠH\Pi_H is the L2L^2 projection onto piecewise linear functions on each coarse element, and EHE_H takes the mean of the values at each coarse node. The fine-scale space is W=ker⁡IHW = \ker I_H, and Vh=VH⊕WV_h = V_H \oplus W.

The algorithm

  1. LOD(a, f, coarse mesh, fine mesh, k)
  2. 1for each coarse element K do
  3. 2U ← K and k layers of coarse elements around it
  4. 3for each vertex i of K find q_{K,i} ∈ W(U) with a(q_{K,i}, w) = a_K(λ_i, w) for all w ∈ W(U)
  5. 4for each coarse node i do φ_i ← λ_i - Σ_K q_{K,i}
  6. 5solve the Galerkin equations Σ_j a(φ_j, φ_i) U_j = (f, φ_i) for all i
  7. 6return u_ms = Σ_i U_i φ_i

Here aKa_K is the energy integral over KK alone, and W(U)W(U) is the set of functions of WW that vanish outside the patch UU. Line L3 is a fine finite element problem on the patch with the constraints IHw=0I_H w = 0, one per coarse node in UU. It is solved as a saddle point system with Lagrange multipliers, or in the kernel of the constraints. All right sides of one patch share one matrix. Lines L1 to L4 depend only on aa and the meshes, so the basis is reused for any ff. Lines L5 and L6 are the Galerkin method on the coarse mesh with the corrected basis.

If UU is the whole domain, the sum Q=∑KqK,⋅Q = \sum_K q_{K, \cdot} is the aa-orthogonal projection of VHV_H onto WW, and the corrected space (1−Q)VH(1 - Q) V_H is aa-orthogonal to WW. This is the ideal method. The patches make it practical.

Example

Take (0,1)(0, 1) with N=64N = 64 fine cells and aa constant on each fine cell, equal to 0.10.1, 11 or 1010 at random and multiplied by a random factor in [0.5,1.5][0.5, 1.5] (seed 1), so the contrast is about 300 and there is no period. Take f=1+sin⁡3xf = 1 + \sin 3x. The fine solution has energy norm 1.1331.133. The table lists energy errors against the fine solution.

MM standard P1 k=1k = 1 k=2k = 2 k=3k = 3 ideal
4 1.094 0.1666 0.1053 0.1052 0.1052
8 1.043 0.1273 0.0406 0.0372 0.0370
16 1.000 0.2387 0.0334 0.0112 0.0094

The standard coarse method has an error near 90% of the solution and does not improve as HH decreases. The ideal LOD error decreases by more than a factor of 2 each time HH is halved, as the theorem below requires. For M=8M = 8 the energy difference between the localized and the ideal solution for k=1,2,3,4,5k = 1, 2, 3, 4, 5 is 0.1200.120, 0.01790.0179, 0.002540.00254, 4.80×10−44.80 \times 10^{-4} and 4.0×10−54.0 \times 10^{-5}: each extra layer divides it by 5 or more. The column k=1k = 1 also shows that a fixed number of layers is not enough: at M=16M = 16 one layer is worse than at M=8M = 8, because the localization error grows relative to the ideal error as HH decreases.

Correctness

The proof covers the 1D method of the code. The quasi-interpolation is a projection onto VHV_H and satisfies ∥v−IHv∥L2≤CIH∥v′∥L2\|v - I_H v\|_{L^2} \le C_I H \|v'\|_{L^2} with CI<2.53C_I < 2.53. The ideal correctors lie in WW, and the corrected space is aa-orthogonal to WW, with Vh=Vms⊕WV_h = V_{ms} \oplus W. Then the error e=uh−umse = u_h - u_{ms} lies in WW, so IHe=0I_H e = 0 and

∥e∥a2=(f,e−IHe)≤CIH∥f∥∥e′∥gives∥e∥a≤CIHα∥f∥,\|e\|_a^2 = (f, e - I_H e) \le C_I H \|f\| \|e'\| \quad \text{gives} \quad \|e\|_a \le \frac{C_I H}{\sqrt \alpha} \|f\|,

with no dependence on the oscillation of aa or on β\beta. For patches of kk layers, the Cea lemma bounds the error by the ideal error plus the localization error ∥(Q−Qk)IHums∥a\|(Q - Q_k) I_H u_{ms}\|_a. Malqvist and Peterseim proved that this term decays exponentially in kk, at a rate that depends on the contrast β/α\beta / \alpha. Hence kk of order log⁡(1/H)\log(1/H) keeps the order HH rate. The proof page cites this decay and does not prove it.

Proof: The ideal localized orthogonal decomposition has an energy error of order H for any rough coefficientfull

We prove the properties of the 1D method of the page, in exact arithmetic. The problem is −(au′)′=f-(a u')' = f on (0,1)(0, 1), u(0)=u(1)=0u(0) = u(1) = 0, with α≤a≤β\alpha \le a \le \beta piecewise constant on the fine mesh and no other assumption on aa. Let VhV_h be the fine P1 space with zero boundary values, VH⊂VhV_H \subset V_h the coarse P1 space, a(v,w)=∫av′w′a(v, w) = \int a v' w', ∥v∥a=a(v,v)1/2\|v\|_a = a(v, v)^{1/2}, and fhf_h the P1 interpolant of ff. The reference is the fine solution uh∈Vhu_h \in V_h with a(uh,v)=(fh,v)a(u_h, v) = (f_h, v) for all v∈Vhv \in V_h.

Lemma 1 (IHI_H is a projection onto VHV_H). IHvH=vHI_H v_H = v_H for every vH∈VHv_H \in V_H.

Proof. On each coarse element vHv_H is linear, so the elementwise L2L^2 projection ΠH\Pi_H returns it unchanged. Its two one-sided values at an interior coarse node agree, so their mean EHE_H is the nodal value, and EHE_H is 0 at the boundary nodes, where vHv_H is 0. □\square

Let W={w∈Vh:IHw=0}W = \{ w \in V_h : I_H w = 0 \}. By Lemma 1, every v∈Vhv \in V_h splits as v=IHv+(v−IHv)v = I_H v + (v - I_H v) with v−IHv∈Wv - I_H v \in W, so Vh=VH⊕WV_h = V_H \oplus W.

Lemma 2 (the interpolation estimate). For every v∈Vhv \in V_h, ∥v−IHv∥L2≤CIH∥v′∥L2\|v - I_H v\|_{L^2} \le C_I H \|v'\|_{L^2} with CI=(1+43)/π<2.53C_I = (1 + 4\sqrt 3)/\pi < 2.53.

Proof. Fix a coarse element KK. Since ΠH\Pi_H is the best L2L^2 approximation in the linear functions, which contain the constants, the Poincare-Wirtinger inequality gives ∥v−ΠHv∥K≤(H/π)∥v′∥K\|v - \Pi_H v\|_K \le (H/\pi) \|v'\|_K. For the second part, two facts on an interval of length HH: a linear pp has ∥p∥K2≤(H/2)(pl2+pr2)\|p\|_K^2 \le (H/2)(p_l^2 + p_r^2) and pl2+pr2≤(6/H)∥p∥K2p_l^2 + p_r^2 \le (6/H) \|p\|_K^2, because the element mass matrix (H/6)(2112)(H/6)\begin{pmatrix} 2 & 1 \\ 1 & 2 \end{pmatrix} has eigenvalues H/6H/6 and H/2H/2. Let xix_i be an end of KK and g=v−ΠHvg = v - \Pi_H v on KK. With w=v−v(xi)w = v - v(x_i), g=w−ΠHwg = w - \Pi_H w, so g(xi)=−(ΠHw)(xi)g(x_i) = -(\Pi_H w)(x_i) and

∣g(xi)∣≤6/H ∥ΠHw∥K≤6/H ∥w∥K≤6/H 2Hπ∥v′∥K,|g(x_i)| \le \sqrt{6/H}\, \|\Pi_H w\|_K \le \sqrt{6/H}\, \|w\|_K \le \sqrt{6/H}\, \frac{2H}{\pi} \|v'\|_K,

by the bound on pl2+pr2p_l^2 + p_r^2, the stability of the projection and the Poincare inequality for a function that vanishes at one end, with constant 2H/π2H/\pi. On KK, ΠHv−EHΠHv\Pi_H v - E_H \Pi_H v is linear with end values δ\delta. At an interior node, δ\delta is half the jump of ΠHv\Pi_H v, which is 12(gK′(xi)−gK(xi))\tfrac12 (g_{K'}(x_i) - g_K(x_i)) for the neighbor K′K' because vv is continuous. At a boundary node, δ=(ΠHv)(xi)=−g(xi)\delta = (\Pi_H v)(x_i) = -g(x_i), since v(xi)=0v(x_i) = 0. In both cases δ2≤(24H/π2)(∥v′∥K2+∥v′∥K′2)\delta^2 \le (24 H/\pi^2)(\|v'\|_K^2 + \|v'\|_{K'}^2), with K′=KK' = K at the boundary. So ∥ΠHv−IHv∥K2≤(H/2)(δl2+δr2)\|\Pi_H v - I_H v\|_K^2 \le (H/2)(\delta_l^2 + \delta_r^2), and the sum over all KK counts each ∥v′∥K2\|v'\|_K^2 at most four times:

∥ΠHv−IHv∥L22≤H2⋅24Hπ2⋅4∥v′∥2=48H2π2∥v′∥2.\|\Pi_H v - I_H v\|_{L^2}^2 \le \frac{H}{2} \cdot \frac{24 H}{\pi^2} \cdot 4 \|v'\|^2 = \frac{48 H^2}{\pi^2} \|v'\|^2.

The triangle inequality gives ∥v−IHv∥≤(H/π)(1+48)∥v′∥\|v - I_H v\| \le (H/\pi)(1 + \sqrt{48}) \|v'\|. □\square

Lemma 3 (the ideal correctors). Let Q=∑KQKQ = \sum_K Q_K with QKv∈WQ_K v \in W and a(QKv,w)=aK(v,w)a(Q_K v, w) = a_K(v, w) for all w∈Ww \in W, which is line L3 with the whole domain as the patch. Then a(v−Qv,w)=0a(v - Q v, w) = 0 for all v∈VHv \in V_H and w∈Ww \in W, and the space Vms=(1−Q)VHV_{ms} = (1 - Q) V_H satisfies Vh=Vms⊕WV_h = V_{ms} \oplus W with the two parts aa-orthogonal.

Proof. Each QKvQ_K v exists and is unique, because aa is an inner product on the subspace WW (Riesz, or the positive definite Gram matrix). Summing over KK, a(Qv,w)=∑KaK(v,w)=a(v,w)a(Q v, w) = \sum_K a_K(v, w) = a(v, w), which is the orthogonality. In the code, line L3 imposes IHw=0I_H w = 0 with Lagrange multipliers; when the saddle point matrix is nonsingular (the elimination in solve stops with an error otherwise), its solution is this QKvQ_K v, because the first block row says a(QKv,w)=aK(v,w)a(Q_K v, w) = a_K(v, w) for ww in the kernel of the constraints and the second says QKv∈WQ_K v \in W. For the splitting: IH(1−Q)v=vI_H (1 - Q) v = v for v∈VHv \in V_H by Lemma 1 and Qv∈WQ v \in W, so 1−Q1 - Q is one to one on VHV_H. For v∈Vhv \in V_h, write v=(1−Q)IHv+rv = (1 - Q) I_H v + r; then IHr=IHv−IHv=0I_H r = I_H v - I_H v = 0, so r∈Wr \in W. A function in both VmsV_{ms} and WW is aa-orthogonal to itself, hence zero. □\square

Theorem (the ideal method). Let umsu_{ms} be the Galerkin solution of lines L4 to L6 with global patches. Then

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

Proof. By Lemma 3, uh=v+eu_h = v + e with v∈Vmsv \in V_{ms} and e∈We \in W. For ϕ∈Vms\phi \in V_{ms}, a(v,ϕ)=a(uh,ϕ)−a(e,ϕ)=(fh,ϕ)a(v, \phi) = a(u_h, \phi) - a(e, \phi) = (f_h, \phi), so vv solves the Galerkin problem, whose matrix is the Gram matrix of a basis and is nonsingular, and v=umsv = u_{ms}. Then e=uh−ums∈We = u_h - u_{ms} \in W, and a(ums,e)=0a(u_{ms}, e) = 0 gives

∥e∥a2=a(uh,e)=(fh,e)=(fh,e−IHe)≤∥fh∥ CIH ∥e′∥≤∥fh∥ CIHα∥e∥a,\|e\|_a^2 = a(u_h, e) = (f_h, e) = (f_h, e - I_H e) \le \|f_h\|\, C_I H\, \|e'\| \le \|f_h\|\, \frac{C_I H}{\sqrt \alpha} \|e\|_a,

by IHe=0I_H e = 0, Lemma 2 and a≥αa \ge \alpha. Divide by ∥e∥a\|e\|_a. □\square

The constant depends only on α\alpha and not on β\beta, on how aa oscillates, or on any period. This is the difference from the multiscale finite element method in several dimensions, whose error has a resonance term.

The localized method. With patches of kk layers, lines L1 to L3 give correctors QkQ_k and the space Vms,k=(1−Qk)VHV_{ms, k} = (1 - Q_k) V_H, and lines L4 to L6 are the Galerkin method in it. By the Cea lemma, for any choice of v∈Vms,kv \in V_{ms, k},

∥uh−ums,k∥a≤∥uh−v∥a≤∥uh−ums∥a+∥(Q−Qk)IHums∥a,\|u_h - u_{ms, k}\|_a \le \|u_h - v\|_a \le \|u_h - u_{ms}\|_a + \|(Q - Q_k) I_H u_{ms}\|_a,

taking v=(1−Qk)IHumsv = (1 - Q_k) I_H u_{ms} and using ums=(1−Q)IHumsu_{ms} = (1 - Q) I_H u_{ms}. The first term is the error of the theorem. The second is the localization error. Malqvist and Peterseim proved that it decays like exp⁡(−ck)\exp(-c k) times H−1H^{-1} factors of polynomial size, with cc depending on the contrast β/α\beta/\alpha; we use that result and do not prove it here. If the patch of every element is the whole domain, which happens for k≥M−1k \ge M - 1, then Qk=QQ_k = Q and the localized method equals the ideal one, as the tests check.

Complexity

In the real RAM model with n=N/Mn = N / M fine cells per coarse element and k≤Mk \le M, a patch has Θ(kn)\Theta(k n) fine unknowns and Θ(k)\Theta(k) constraints. The code solves each of the at most MM distinct patch systems by dense Gaussian elimination, in Θ(k3n3)\Theta(k^3 n^3) time, which is Θ(k3N3/M2)\Theta(k^3 N^3 / M^2) in all. It forms the coarse matrix with fine energy sums over the whole domain in Θ(M2N)\Theta(M^2 N). The extra space is the dense patch matrix, Θ(k2N2/M2)\Theta(k^2 N^2 / M^2), and the basis, Θ(MN)\Theta(M N).

A sparse code solves each patch problem in time nearly linear in its size, and each corrected basis function is nonzero on Θ(kd)\Theta(k^d) coarse elements in dd dimensions, so the coarse matrix is sparse with Θ(kd)\Theta(k^d) entries per row. The patch problems are independent and run in parallel, and they are computed once for all right sides.

Properties

  • No scale assumption. The error bound holds for any coefficient between α\alpha and β\beta, with no period and no separation of scales.
  • Energy orthogonal. In the ideal method, the coarse space is aa-orthogonal to the fine-scale space, and the Galerkin solution is the part of uhu_h in it.
  • Exponential localization. The correctors decay exponentially in units of HH, at a rate that depends on the contrast.
  • Reusable basis. The basis depends on aa and not on ff.
  • Conforming. The basis functions lie in VhV_h, so the method is a Galerkin method in a subspace of VhV_h, and its energy error is never larger than the error of the best function in that subspace.

Variants and improvements

  • Other quasi-interpolations. Nodal averages of local L2L^2 projections as here, weighted Clement operators, or L2L^2 projections onto VHV_H; the choice changes WW and the constants, not the structure.
  • Element correctors or node correctors. Correctors can be computed per element and summed, as here, or as one corrector per basis function on a patch around its node. The two choices give different localization errors and patch counts.
  • Other problems. The same construction applies to linear elasticity, the Helmholtz equation in the regime where a pollution free coarse method is needed, eigenvalue problems, parabolic and wave equations, and problems with high contrast after a change of the interpolation.
  • Petrov-Galerkin LOD. Test with the plain hat functions and solve with the corrected ones, which gives a sparser coarse matrix that is not symmetric.
  • Operator-adapted wavelets. Owhadi's gamblets build a hierarchy of localized bases with similar decay properties and connect the method to Gaussian process estimation.

When to use it

Use LOD when the coefficient is rough on a scale the coarse mesh cannot resolve, there is no period or scale separation to exploit, and the problem must be solved many times with different sources, or a small coarse model is needed for a time loop or an inverse problem. If the coefficient is periodic with a small period, periodic homogenization or the heterogeneous multiscale method is cheaper. If one solve is all that is needed, a good fine solver such as multigrid or domain decomposition on the fine mesh may cost less than the patch problems.

Pitfalls

  • A fixed number of layers. The localization error must fall below the order HH error, so kk must grow like log⁡(1/H)\log(1/H). The example shows the loss for k=1k = 1.
  • High contrast. The decay rate degrades with β/α\beta / \alpha for the standard interpolation, so more layers are needed, or an interpolation adapted to the high-conductivity channels.
  • Singular patch systems. Each constraint must act on the patch unknowns; a constraint of a coarse node whose functional is zero on the patch makes the saddle point matrix singular.
  • Cost of the offline phase. The patch problems together cost more than one fine solve. The method pays off only when the basis is reused.
  • Truncation at the boundary of the patch. Setting the corrector to zero outside the patch is the source of the localization error; patches that are too small for the contrast give errors near the standard coarse method.

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.

localized_orthogonal_decomposition.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/localized-orthogonal-decomposition/. The authors are listed in prov/DNA9DW.jsonl.
"""Localized orthogonal decomposition (Malqvist and Peterseim 2014) in 1D.

Model problem: -(a u')' = f on (0, 1), u(0) = u(1) = 0, with a rough
coefficient a >= alpha > 0 and no assumption of periodicity or scale
separation.

The fine mesh has N = M n cells (one value a[j] per cell) and the coarse
mesh M elements. V_h is the fine P1 space, V_H the coarse P1 space, both
with zero boundary values. The quasi-interpolation is I_H = E_H o Pi_H:
Pi_H is the L2 projection onto P1 on each coarse element (discontinuous),
and E_H takes the mean of the two one-sided values at each interior coarse
node. The fine-scale space is W = {w in V_h : I_H w = 0}.

For each coarse element K and each vertex i of K, the element corrector
q_{K,i} in W(U) solves

    a(q_{K,i}, w) = a_K(lambda_i, w)   for every w in W(U),

where U is the patch of k layers of coarse elements around K (k = None:
the whole domain) and a_K is the energy restricted to K. The constraint
I_H w = 0 is imposed by Lagrange multipliers. The multiscale basis is
lambda_i - sum over K of q_{K,i}, and the method is the Galerkin method in
its span.

The patch problems are solved by dense Gaussian elimination (scimat.solve),
with all right sides of one patch in one call. This is for small checks;
a real code uses sparse solvers.
"""

from scimat import solve


def _cell_moments(v0, v1, t0, t1, h):
    """Exact integral over one fine cell of v * t, with v and t linear on the cell."""
    return h * (2 * v0 * t0 + v0 * t1 + v1 * t0 + 2 * v1 * t1) / 6


def interpolation_rows(N, M):
    """The functionals I_H(.)(x_i) for the interior coarse nodes i = 1 .. M - 1.

    Returns a list of M - 1 rows; row i - 1 has N + 1 coefficients, one per
    fine nodal value.
    """
    n = N // M
    h, H = 1.0 / N, 1.0 / M
    rows = []
    for i in range(1, M):
        row = [0.0] * (N + 1)
        # p_r on element i - 1 and p_l on element i, each with weight 1/2
        for e, side in ((i - 1, "r"), (i, "l")):
            for c in range(n):
                t0, t1 = c / n, (c + 1) / n
                j = e * n + c
                for node, (v0, v1) in ((j, (1.0, 0.0)), (j + 1, (0.0, 1.0))):
                    m_r = _cell_moments(v0, v1, t0, t1, h)
                    m_l = _cell_moments(v0, v1, 1 - t0, 1 - t1, h)
                    p = (2 / H) * (2 * m_r - m_l) if side == "r" else (2 / H) * (2 * m_l - m_r)
                    row[node] += p / 2
        rows.append(row)
    return rows


def coarse_hat(N, M, i):
    """Fine nodal values of the coarse hat function of node i."""
    n = N // M
    v = [0.0] * (N + 1)
    for j in range(max(0, (i - 1) * n), min(N, (i + 1) * n) + 1):
        v[j] = max(0.0, 1 - abs(j - i * n) / n)
    return v


def energy(a, v, w, cells=None):
    """a(v, w) over the given fine cells (all cells if None)."""
    N = len(a)
    if cells is None:
        cells = range(N)
    return sum(a[c] * (v[c + 1] - v[c]) * (w[c + 1] - w[c]) * N for c in cells)


def correctors(a, M, k):
    """All element correctors q_{K,i}. Returns a dict (e, i) -> fine nodal values."""
    N = len(a)
    n = N // M
    rows = interpolation_rows(N, M)
    jobs = {}
    for e in range(M):                                                         # @line L1
        lo_e, hi_e = (0, M - 1) if k is None else (max(0, e - k), min(M - 1, e + k))  # @line L2
        for i in (e, e + 1):
            if 1 <= i <= M - 1:
                jobs.setdefault((lo_e, hi_e), []).append((e, i))
    out = {}
    for (lo_e, hi_e), items in jobs.items():
        nodes = list(range(lo_e * n + 1, (hi_e + 1) * n))                      # @line L3
        cons = [i for i in range(max(1, lo_e), min(M - 1, hi_e + 1) + 1)]      # @line L3
        p, q = len(nodes), len(cons)
        pos = {j: r for r, j in enumerate(nodes)}
        S = [[0.0] * (p + q) for _ in range(p + q)]                            # @line L3
        for r, j in enumerate(nodes):                                          # @line L3
            S[r][r] = (a[j - 1] + a[j]) * N                                    # @line L3
            if j - 1 in pos:
                S[r][pos[j - 1]] = -a[j - 1] * N                               # @line L3
            if j + 1 in pos:
                S[r][pos[j + 1]] = -a[j] * N                                   # @line L3
        for s, i in enumerate(cons):                                           # @line L3
            for r, j in enumerate(nodes):                                      # @line L3
                S[p + s][r] = S[r][p + s] = rows[i - 1][j]                     # @line L3
        rhs = [[0.0] * len(items) for _ in range(p + q)]
        for col, (e, i) in enumerate(items):                                   # @line L3
            lam = coarse_hat(N, M, i)
            for c in range(e * n, (e + 1) * n):                                # a_K(lambda_i, phi_j)
                d = (lam[c + 1] - lam[c]) * N * a[c]
                if c in pos:
                    rhs[pos[c]][col] -= d                                      # @line L3
                if c + 1 in pos:
                    rhs[pos[c + 1]][col] += d                                  # @line L3
        sol = solve(S, rhs)                                                    # @line L3
        for col, (e, i) in enumerate(items):
            v = [0.0] * (N + 1)
            for r, j in enumerate(nodes):
                v[j] = sol[r][col]
            out[(e, i)] = v
    return out


def lod_1d(a, f, M, k):
    """Solve -(a u')' = f with the LOD basis on M coarse elements and patches of k layers.

    a: N fine cell values, f: N + 1 fine nodal values. k = None gives the
    ideal method with global correctors. Returns (U, u, basis).
    """
    N = len(a)
    q = correctors(a, M, k)
    basis = []
    for i in range(1, M):                                                      # @line L4
        phi = coarse_hat(N, M, i)                                              # @line L4
        for (e, ii), v in q.items():                                           # @line L4
            if ii == i:
                phi = [x - y for x, y in zip(phi, v)]                          # @line L4
        basis.append(phi)
    load = fine_load(f)
    A = [[energy(a, bi, bj) for bj in basis] for bi in basis]                  # @line L5
    F = [sum(bi[j] * load[j] for j in range(N + 1)) for bi in basis]           # @line L5
    U = solve(A, F) if basis else []                                           # @line L5
    u = [sum(U[m] * basis[m][j] for m in range(M - 1)) for j in range(N + 1)]  # @line L6
    return U, u, basis


def fine_load(f):
    """Exact integrals of the P1 interpolant of f against the fine hat functions."""
    N = len(f) - 1
    h = 1.0 / N
    load = [0.0] * (N + 1)
    for c in range(N):
        load[c] += h * (2 * f[c] + f[c + 1]) / 6
        load[c + 1] += h * (f[c] + 2 * f[c + 1]) / 6
    return load


def fine_solve(a, f):
    """Reference: the fine P1 solution."""
    N = len(a)
    load = fine_load(f)
    A = [[0.0] * (N - 1) for _ in range(N - 1)]
    for r in range(N - 1):
        j = r + 1
        A[r][r] = (a[j - 1] + a[j]) * N
        if r > 0:
            A[r][r - 1] = -a[j - 1] * N
        if r < N - 2:
            A[r][r + 1] = -a[j] * N
    return [0.0] + solve(A, load[1:N]) + [0.0]


def p1_solve(a, f, M):
    """Standard coarse P1 with exact element integrals of a (for comparison)."""
    N = len(a)
    basis = [coarse_hat(N, M, i) for i in range(1, M)]
    load = fine_load(f)
    A = [[energy(a, bi, bj) for bj in basis] for bi in basis]
    F = [sum(bi[j] * load[j] for j in range(N + 1)) for bi in basis]
    U = solve(A, F)
    return [sum(U[m] * basis[m][j] for m in range(M - 1)) for j in range(N + 1)]
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)]
test_localized_orthogonal_decomposition.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/localized-orthogonal-decomposition/. The authors are listed in prov/DNA9DW.jsonl.
import math
import random

from localized_orthogonal_decomposition import (
    coarse_hat,
    correctors,
    energy,
    fine_solve,
    interpolation_rows,
    lod_1d,
    p1_solve,
)

N = 64


def rough(seed):
    rng = random.Random(seed)
    return [rng.choice([0.1, 1.0, 10.0]) * rng.uniform(0.5, 1.5) for _ in range(N)]


def source():
    return [1.0 + math.sin(3 * j / N) for j in range(N + 1)]


def enorm(a, u, v):
    d = [x - y for x, y in zip(u, v)]
    return energy(a, d, d) ** 0.5


def apply_rows(rows, v):
    return [sum(r[j] * v[j] for j in range(N + 1)) for r in rows]


def test_quasi_interpolation_is_a_projection_onto_the_coarse_space():
    for M in (4, 8):
        rows = interpolation_rows(N, M)
        for i in range(1, M):
            vals = apply_rows(rows, coarse_hat(N, M, i))
            for m, v in enumerate(vals):
                assert abs(v - (1.0 if m == i - 1 else 0.0)) < 1e-13


def test_correctors_lie_in_the_kernel_and_the_ideal_basis_is_orthogonal_to_it():
    a, M = rough(1), 8
    rows = interpolation_rows(N, M)
    for v in correctors(a, M, 2).values():
        assert max(abs(x) for x in apply_rows(rows, v)) < 1e-11
    _, _, basis = lod_1d(a, source(), M, None)
    rng = random.Random(4)
    for _ in range(3):
        v = [0.0] + [rng.uniform(-1, 1) for _ in range(N - 1)] + [0.0]
        coef = apply_rows(rows, v)
        w = list(v)
        for i in range(1, M):
            hat = coarse_hat(N, M, i)
            w = [x - coef[i - 1] * y for x, y in zip(w, hat)]
        assert max(abs(x) for x in apply_rows(rows, w)) < 1e-12
        scale = energy(a, w, w) ** 0.5
        for phi in basis:
            assert abs(energy(a, phi, w)) < 1e-9 * scale * energy(a, phi, phi) ** 0.5


def test_ideal_method_converges_at_least_linearly_and_beats_p1():
    a, f = rough(1), source()
    ref = fine_solve(a, f)
    errors = []
    for M in (4, 8, 16):
        _, u, _ = lod_1d(a, f, M, None)
        err = enorm(a, u, ref)
        assert err < 0.2 * enorm(a, p1_solve(a, f, M), ref)
        errors.append(err)
    for e1, e2 in zip(errors, errors[1:]):
        assert e1 / e2 > 1.8


def test_localization_error_decays_exponentially_in_the_layers():
    a, f = rough(1), source()
    for M in (8, 16):
        _, ideal, _ = lod_1d(a, f, M, None)
        diffs = [enorm(a, lod_1d(a, f, M, k)[1], ideal) for k in (1, 2, 3, 4)]
        for d1, d2 in zip(diffs, diffs[1:]):
            assert d1 / d2 > 3
        _, whole, _ = lod_1d(a, f, M, M)
        assert enorm(a, whole, ideal) < 1e-12


def test_two_layers_already_give_most_of_the_ideal_accuracy():
    a, f = rough(2), source()
    ref = fine_solve(a, f)
    M = 8
    _, ideal, _ = lod_1d(a, f, M, None)
    _, local, _ = lod_1d(a, f, M, 2)
    assert enorm(a, local, ref) < 2 * enorm(a, ideal, ref)

History

Malqvist and Peterseim introduced the localized orthogonal decomposition in a 2014 paper in Mathematics of Computation. They built on the variational multiscale method of Hughes and on the multiscale finite element method of Hou and Wu, and proved that the ideal fine-scale correctors decay exponentially. Henning, Peterseim and others extended the method to many other problems, and Kornhuber and Yserentant gave an analysis by subspace decomposition. Malqvist and Peterseim collected the theory in a 2020 book.

References

  1. Axel Malqvist and Daniel Peterseim, Localization of elliptic multiscale problems, Mathematics of Computation 83(290), 2014, 2583-2603, the quasi-interpolation, the fine-scale space as its kernel, the element correctors on patches and the proof of their exponential decay, with patches of size of order H log(1/H)
  2. Axel Malqvist and Daniel Peterseim, Numerical Homogenization by Localized Orthogonal Decomposition, SIAM Spotlights 5, 2020, the ideal method and its error estimate, the localization of the correctors and the implementation of the patch problems

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
  • at least three sources
  • a scene preset for the example