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
- Model
- Real RAM
- Properties
- deterministicenergy orthogonalexponential localizationno scale separation
- Evidence
- Proof sketchCode in 1 languages
- 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 , the kernel of a quasi-interpolation , and corrects each coarse basis function so that the coarse space becomes orthogonal to 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 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 , a coefficient with that may vary arbitrarily on a fine mesh of width , a source , a coarse mesh of width that the fine mesh refines, and a number of layers , find an approximation of the fine solution of
in a space with one unknown per coarse node, with energy error of order that does not depend on how oscillates.
Let be the coarse P1 space with hat functions . LOD uses a quasi-interpolation that is a projection, local and stable. A common choice, used here, is : is the projection onto piecewise linear functions on each coarse element, and takes the mean of the values at each coarse node. The fine-scale space is , and .
The algorithm
LOD(a, f, coarse mesh, fine mesh, k)- 1
for each coarse element K do - 2
U ← K and k layers of coarse elements around it - 3
for 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) - 4
for each coarse node i do φ_i ← λ_i - Σ_K q_{K,i} - 5
solve the Galerkin equations Σ_j a(φ_j, φ_i) U_j = (f, φ_i) for all i - 6
return u_ms = Σ_i U_i φ_i
Here is the energy integral over alone, and is the set of functions of that vanish outside the patch . Line L3 is a fine finite element problem on the patch with the constraints , one per coarse node in . 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 and the meshes, so the basis is reused for any . Lines L5 and L6 are the Galerkin method on the coarse mesh with the corrected basis.
If is the whole domain, the sum is the -orthogonal projection of onto , and the corrected space is -orthogonal to . This is the ideal method. The patches make it practical.
Example
Take with fine cells and constant on each fine cell, equal to , or at random and multiplied by a random factor in (seed 1), so the contrast is about 300 and there is no period. Take . The fine solution has energy norm . The table lists energy errors against the fine solution.
| standard P1 | 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 decreases. The ideal LOD error decreases by more than a factor of 2 each time is halved, as the theorem below requires. For the energy difference between the localized and the ideal solution for is , , , and : each extra layer divides it by 5 or more. The column also shows that a fixed number of layers is not enough: at one layer is worse than at , because the localization error grows relative to the ideal error as decreases.
Correctness
The proof covers the 1D method of the code. The quasi-interpolation is a projection onto and satisfies with . The ideal correctors lie in , and the corrected space is -orthogonal to , with . Then the error lies in , so and
with no dependence on the oscillation of or on . For patches of layers, the Cea lemma bounds the error by the ideal error plus the localization error . Malqvist and Peterseim proved that this term decays exponentially in , at a rate that depends on the contrast . Hence of order keeps the order 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 on , , with piecewise constant on the fine mesh and no other assumption on . Let be the fine P1 space with zero boundary values, the coarse P1 space, , , and the P1 interpolant of . The reference is the fine solution with for all .
Lemma 1 ( is a projection onto ). for every .
Proof. On each coarse element is linear, so the elementwise projection returns it unchanged. Its two one-sided values at an interior coarse node agree, so their mean is the nodal value, and is 0 at the boundary nodes, where is 0.
Let . By Lemma 1, every splits as with , so .
Lemma 2 (the interpolation estimate). For every , with .
Proof. Fix a coarse element . Since is the best approximation in the linear functions, which contain the constants, the Poincare-Wirtinger inequality gives . For the second part, two facts on an interval of length : a linear has and , because the element mass matrix has eigenvalues and . Let be an end of and on . With , , so and
by the bound on , the stability of the projection and the Poincare inequality for a function that vanishes at one end, with constant . On , is linear with end values . At an interior node, is half the jump of , which is for the neighbor because is continuous. At a boundary node, , since . In both cases , with at the boundary. So , and the sum over all counts each at most four times:
The triangle inequality gives .
Lemma 3 (the ideal correctors). Let with and for all , which is line L3 with the whole domain as the patch. Then for all and , and the space satisfies with the two parts -orthogonal.
Proof. Each exists and is unique, because is an inner product on the subspace (Riesz, or the positive definite Gram matrix). Summing over , , which is the orthogonality. In the code, line L3 imposes with Lagrange multipliers; when the saddle point matrix is nonsingular (the elimination in solve stops with an error otherwise), its solution is this , because the first block row says for in the kernel of the constraints and the second says . For the splitting: for by Lemma 1 and , so is one to one on . For , write ; then , so . A function in both and is -orthogonal to itself, hence zero.
Theorem (the ideal method). Let be the Galerkin solution of lines L4 to L6 with global patches. Then
Proof. By Lemma 3, with and . For , , so solves the Galerkin problem, whose matrix is the Gram matrix of a basis and is nonsingular, and . Then , and gives
by , Lemma 2 and . Divide by .
The constant depends only on and not on , on how 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 layers, lines L1 to L3 give correctors and the space , and lines L4 to L6 are the Galerkin method in it. By the Cea lemma, for any choice of ,
taking and using . The first term is the error of the theorem. The second is the localization error. Malqvist and Peterseim proved that it decays like times factors of polynomial size, with depending on the contrast ; we use that result and do not prove it here. If the patch of every element is the whole domain, which happens for , then and the localized method equals the ideal one, as the tests check.
Complexity
In the real RAM model with fine cells per coarse element and , a patch has fine unknowns and constraints. The code solves each of the at most distinct patch systems by dense Gaussian elimination, in time, which is in all. It forms the coarse matrix with fine energy sums over the whole domain in . The extra space is the dense patch matrix, , and the basis, .
A sparse code solves each patch problem in time nearly linear in its size, and each corrected basis function is nonzero on coarse elements in dimensions, so the coarse matrix is sparse with 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 and , with no period and no separation of scales.
- Energy orthogonal. In the ideal method, the coarse space is -orthogonal to the fine-scale space, and the Galerkin solution is the part of in it.
- Exponential localization. The correctors decay exponentially in units of , at a rate that depends on the contrast.
- Reusable basis. The basis depends on and not on .
- Conforming. The basis functions lie in , so the method is a Galerkin method in a subspace of , 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 projections as here, weighted Clement operators, or projections onto ; the choice changes 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 error, so must grow like . The example shows the loss for .
- High contrast. The decay rate degrades with 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.
# 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag DNA9DW Edit this page History Report an error Markdown