Algorithmadvanced
Weak greedy algorithm for reduced bases
Builds a reduced basis by adding the parameter with the largest error bound. If the Kolmogorov n-width decays like n^-a or exp(-c n^a), the greedy error decays at a rate of the same type.
- Time
- O(Q^2 r^2 n + m r^4 + m Q^2 r^3) offlineO(Q r^2 + r^3 + Q^2 r^2) online
- Space
- O(Q r n + Q^2 r^2 + m) extra
- Where
- Q = the number of affine terms; m = the number of training parameters; n = the number of finite element unknowns, with banded matrices in 1D; r = the final size of the reduced basis
- Model
- Real RAM
- Properties
- certifieddeterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Karen Veroy, Christophe Prud'homme, Dimitrios V. Rovas, Anthony T. Patera, 2003
The weak greedy algorithm builds the basis of a reduced basis method one parameter at a time. It starts from an empty basis. At each step it evaluates the cheap a posteriori error bound at every parameter of a finite training set , picks the parameter where the bound is largest, solves the full problem there once and adds that solution to the basis. It stops when the largest bound is below a tolerance. So it needs only full solves for a basis of size , and it returns a certified error bound on all of . The word "weak" means that the algorithm does not pick the worst approximated solution, which it cannot know, but a solution whose error is at least a fixed fraction of the worst one. The Kolmogorov width is the best error that any -dimensional space can give. The theory compares the greedy error with : if decays like a power of or like an exponential of a power, then decays in the same way, with other constants. The POD-Galerkin model builds its basis from many snapshots and needs no error bound.
In plain words
You want a few full solutions that describe the solutions at all parameters. A good plan is to look where the current basis is worst and to add the solution there. You cannot measure the true error at every parameter, because that needs a full solve at each one. But the reduced basis method gives a cheap bound for each parameter, and the bound is never smaller than the error and never larger than a fixed multiple of it. So you look where the bound is largest. That point is not always the worst one, but it is never much better than the worst one, and this is enough to make the basis almost as good as the best possible basis of the same size.
The problem
The setting is the one of the reduced basis method. A truth space has the inner product . For each parameter , the truth solution solves with . The form is coercive and continuous with constants and , and a lower bound is known. For a space , is the Galerkin solution in , and
is the residual bound, with . The books write for the reduced size and or for the truth size. This page writes and .
The input is the affine data, a finite training set with points, a tolerance and a largest size . The output is a nested sequence with , the offline tables for , and the number , which bounds the error on .
The example uses the model problem of the reduced basis page: on with zero boundary values, P1 elements with , , with , and . Then , so for .
The algorithm
WEAK-GREEDY(A_1..A_Q, F, X, α_LB, Ξ, ε_tol, r_max)- 1
μ ← argmax over μ' in Ξ of ‖F‖_X' / α_LB(μ') ▷ the bound of the empty basis - 2
repeat - 3
solve A(μ) u = F; add u to the X-orthonormal basis Z and extend the offline tables - 4
Δ(μ') ← the online bound of the reduced basis method, for each μ' in Ξ - 5
k ← the index of the largest Δ(μ') over Ξ - 6
if Δ(μ_k) ≤ ε_tol or Z has r_max columns then - 7
return Z, the tables, the chosen parameters and ε_r = Δ(μ_k) - 8
μ ← μ_k
Line L1 uses the bound of the empty basis, , whose residual is . So the first parameter is the one with the smallest , here . Line L3 is the only full solve of a step. It orthonormalizes the new snapshot against in the inner product, two passes of Gram-Schmidt, and adds the new rows and columns to the tables , and of the reduced basis method. Line L4 is the online stage of that method, run times. It uses only the small tables, so its cost does not depend on . Lines L5 and L6 find the largest bound and test it. Line L8 moves to the chosen parameter, and the loop solves there next.
Example
A strong greedy step by hand. The strong greedy algorithm uses the true distance in place of the bound. Take three vectors in with the Euclidean norm: , and . Their norms are , and , so step 1 takes with . After the projection onto , the remainders are and , so step 2 takes with . The remainder of after the projection onto is , so . A weak greedy step with could also take in step 2, because its distance 1 is at least .
The model problem. The training set has the points , , from 1 to 100, and . The table is a measurement from the test file. Step adds ; the columns give the largest bound and the largest true error over after the step, and the range of the effectivity over (at the parameters with an error above ).
| at | effectivity | ||||
|---|---|---|---|---|---|
| 0 | 2.047 | 0.371 | 1 | ||
| 1 | 1 | 35.48 | 1.00 to 8.15 | ||
| 2 | 100 | 17.78 | 1.00 to 8.50 | ||
| 3 | 3.981 | 44.67 | 1.00 to 8.72 | ||
| 4 | 44.67 | 70.80 | 1.00 to 9.72 | ||
| 5 | 70.80 | 19.95 | 1.01 to 44.2 |
The loop stops at , with 5 full solves. The bound falls by about two orders of magnitude per step. Up to the effectivity is below , as the theory says. At the largest effectivity is 44: the bound has reached the rounding floor of the residual, see the pitfalls. The bound is still above the error. The algorithm does not pick the worst point: after step 1 the worst error is at , but the largest bound is at , so step 2 takes . A strong greedy run with the true errors picks , and its largest errors after steps 2, 3 and 4 are , and . So the weak choice costs little. On 1000 test points in that are not in , the largest error after step 5 is and the largest bound is .
Correctness
The proof file shows three facts, in exact arithmetic. First, the loop stops after at most steps, and line L3 never adds a snapshot that is already in the span. The reason is that at each chosen parameter, because the reduced solution reproduces the truth there. So a bound above is never at a chosen point. Second, if the loop stops by the tolerance, then for every , because the bound is reliable. Third, each step is a weak greedy step: with ,
The proof chains Cea's lemma, , with the two sides of the bound. In the example , and the test checks this inequality at each step.
The rates are theorems of the cited papers, for a weak greedy algorithm with the parameter on a compact set of a Hilbert space, here . Let and let be the Kolmogorov -width of . DeVore, Petrova and Wojtaszczyk prove that gives with , and that gives with . So the exponent of a polynomial rate is kept, and the exponential rate is kept with a smaller constant in the exponent. The rates do not say that is close to for each .
Proof: The weak greedy loop stops, certifies the error on the training set, and makes weak greedy stepsfull
We assume exact arithmetic and the setting of the reduced basis method: with a symmetric positive definite , , coercivity , continuity and . For a subspace , is the Galerkin solution, , and is the bound of the reduced basis method. The empty space has . We use three facts that the proof file of the reduced basis method shows, and that hold for in the same way, with residual .
- (R) Reliability and effectivity: .
- (P) Reproduction: if , then and .
- (E) Line L4 computes exactly from the tables, and line L3 keeps an -orthonormal basis of as long as each new snapshot is not in .
Lemma 1 (Cea in the X norm). .
Proof. Galerkin orthogonality gives for all . For any , , so . Divide by (the claim is clear if it is 0) and take the infimum over .
Lemma 2 (no repeated choice). Suppose the loop does not stop at step , so the largest bound is above . Then , and in particular is not one of .
Proof. If , then (P) gives , a contradiction. Each chosen , , is in .
The first parameter comes from line L1. Its snapshot is not 0 when , since is invertible. (If , all bounds are 0 and the first test stops the loop with exact.) So by Lemma 2 and induction, each snapshot that line L3 adds is outside the current span, the dimension grows by one at each step, and (E) holds at each step.
Theorem 1 (termination). The loop stops after at most steps.
Proof. By Lemma 2 the chosen parameters are distinct points of , so there are at most of them. After steps, every with is in , so by (P) every bound is 0 and the test of line L6 holds. The test also holds when has columns.
Theorem 2 (certification). At the return of line L7 with vectors, for all . If the loop stops by the tolerance, .
Proof. is the largest bound over (line L5), and each bound is at least the error by (R).
Theorem 3 (weak greedy step). Let . The parameter that the algorithm chooses after (by line L1 for , by line L5 for ) satisfies
Proof. For each , by the choice. Then
The first step is Lemma 1. The second and the fourth are the two sides of (R). The third is the choice and the definition of . The last holds because . Take the maximum over . For the bound of the empty basis is and line L1 maximizes it, so the same chain holds.
Corollary (the model problem). For , and , the reduced basis proof file shows . With , , which is for and .
By Theorem 3, the algorithm is a weak greedy algorithm with parameter on the compact set in the sense of Binev et al. and of DeVore, Petrova and Wojtaszczyk, so their rate theorems apply to .
Complexity
In the real RAM model, with banded matrices in 1D, step costs one full solve, , Gram-Schmidt against vectors, , solves with , , and the new table entries, . The online solves of line L4 cost . The sum over is . The main gain over POD is the number of full solves: in place of . Memory is for the representers, for the tables and for the bounds. The implementation stores the matrices dense for simplicity, so its products with cost ; only its solves are tridiagonal.
Properties
- Few full solves. One per basis vector.
- Certified on the training set. The returned bounds the error at every .
- Nested. Each basis contains the earlier ones, so a larger tolerance gives a prefix of the same basis.
- Rate of the width. Polynomial and exponential decay of carry over to .
- Not optimal for each . always, and the constants of the rate theorems can be large.
- Deterministic. The same input gives the same basis. Ties in line L5 go to the first index.
Variants and improvements
- Strong greedy. Use the true error or the projection error in place of the bound. This needs a full solve at each training point, so it is a tool for analysis or for small problems.
- POD-greedy. For a time-dependent problem, add the leading POD modes of the error trajectory at the chosen parameter.
- Adaptive training sets. Refine near the chosen points, or draw a new random at each step, to control the error away from the training points.
- Goal-oriented greedy. Drive the loop with an output bound in place of the bound on the field.
- Interpolation points. The empirical interpolation method and DEIM use the same greedy idea to choose functions and points.
- Compressed sensing analogue. Orthogonal matching pursuit also adds, at each step, the element that is most correlated with the residual.
When to use it
Use the weak greedy algorithm to build a reduced basis when a cheap and reliable error bound exists, when each full solve is costly and when the training set must be large. It is the standard offline stage of the certified reduced basis method. When no error bound exists, use POD on snapshots or a strong greedy run on a small training set. When the solution set has a slowly decaying width, for example for transport with a moving front, no linear basis is small, and the greedy loop only shows this by a slow decay of .
Pitfalls
- The rounding floor. The bound is computed from , a difference of numbers of size , so it cannot go much below , about here. A tolerance below the floor makes the loop run to , and at the floor the bound can choose a point at random. In the example the effectivity jumps to 44 at .
- Certified only on . The bound is computed at the training points only. A coarse can miss a region with a large error. Check the bound on a fresh test set, as in the example.
- A bad lower bound. If is too small, the bound and are large, the greedy choice is driven by the stability factor and not by the error, and the loop picks too many points where is small.
- Dependent snapshots in floating point. Near the floor, the chosen snapshot can be almost in the span. The implementation raises an error when the orthogonal part is below times the snapshot norm.
- Online work on the mesh. If line L4 forms the reduced matrix or the residual from vectors of length , each step costs , and the training sweep becomes as slow as a sweep of full solves.
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
# 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)]
weak_greedy_reduced_basis.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weak-greedy-reduced-basis/. The authors are listed in prov/3WNNGB.jsonl.
"""Weak greedy construction of a reduced basis, driven by the residual based error bound.
The model problem is -u'' + mu u = 1 on (0, 1) with u(0) = u(1) = 0 and mu > 0, in P1 finite
elements: A(mu) = K + mu M. All matrices are tridiagonal, so the truth solves cost O(n).
"""
import math
from scimat import dot, matvec, solve
Matrix = list[list[float]]
Vector = list[float]
def fe_model(n: int) -> tuple[list[Matrix], Vector]:
"""Return ([K, M], F) for P1 elements with n interior nodes and h = 1/(n+1)."""
h = 1.0 / (n + 1)
k = [[0.0] * n for _ in range(n)]
m = [[0.0] * n for _ in range(n)]
for i in range(n):
k[i][i] = 2.0 / h
m[i][i] = 4.0 * h / 6.0
if i > 0:
k[i][i - 1] = k[i - 1][i] = -1.0 / h
m[i][i - 1] = m[i - 1][i] = h / 6.0
return [k, m], [h] * n
def combine(aq: list[Matrix], th: Vector) -> Matrix:
"""Return sum over q of th[q] A_q."""
n = len(aq[0])
return [[sum(t * a[i][j] for t, a in zip(th, aq)) for j in range(n)] for i in range(n)]
def tridiag_solve(a: Matrix, b: Vector) -> Vector:
"""Solve a x = b for a tridiagonal a (stored dense) by elimination without pivoting."""
n = len(b)
c = [0.0] * n
d = [0.0] * n
for i in range(n):
lo = a[i][i - 1] if i > 0 else 0.0
den = a[i][i] - (lo * c[i - 1] if i > 0 else 0.0)
c[i] = (a[i][i + 1] / den) if i < n - 1 else 0.0
d[i] = (b[i] - (lo * d[i - 1] if i > 0 else 0.0)) / den
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = d[i] - (c[i] * x[i + 1] if i < n - 1 else 0.0)
return x
class ReducedBasis:
"""A reduced basis with its offline tables, grown one snapshot at a time."""
def __init__(self, aq: list[Matrix], f: Vector, x: Matrix, mu_bar: float):
self.aq, self.f, self.x, self.mu_bar = aq, f, x, mu_bar
nq = len(aq)
self.z: list[Vector] = [] # X-orthonormal basis vectors
self.az: list[list[Vector]] = [[] for _ in aq] # A_q z_j
self.ez: list[list[Vector]] = [[] for _ in aq] # X^-1 A_q z_j
# small tables of the online stage; their sizes do not depend on n
self.ar: list[Matrix] = [[] for _ in aq] # ar[q][i][j] = z_i^T A_q z_j
self.fr: Vector = [] # fr[j] = F^T z_j
self.g: list[Vector] = [[] for _ in aq] # g[q][j] = F^T X^-1 A_q z_j
self.gg: list[list[Matrix]] = [[[] for _ in aq] for _ in range(nq)] # gg[q][p][i][j] = (A_q z_i)^T X^-1 A_p z_j
ef = tridiag_solve(x, f)
self.gff = dot(f, ef)
def truth(self, mu: float) -> Vector:
return tridiag_solve(combine(self.aq, [1.0, mu]), self.f)
def add(self, u: Vector) -> None:
"""Add a snapshot: Gram-Schmidt in X (two passes) and the new table entries."""
w = list(u)
for _ in range(2):
for zj in self.z:
c = dot(zj, matvec(self.x, w))
w = [wi - c * zi for wi, zi in zip(w, zj)]
nw = math.sqrt(dot(w, matvec(self.x, w)))
if nw <= 1e-10 * math.sqrt(dot(u, matvec(self.x, u))):
raise ValueError("the new snapshot is in the span of the basis")
z = [wi / nw for wi in w]
self.z.append(z)
k = len(self.z) - 1
for q, a in enumerate(self.aq):
v = matvec(a, z)
self.az[q].append(v)
self.ez[q].append(tridiag_solve(self.x, v))
self.fr.append(dot(self.f, z))
nq = len(self.aq)
for q in range(nq):
for i in range(k):
self.ar[q][i].append(dot(self.z[i], self.az[q][k]))
self.ar[q].append([dot(z, self.az[q][j]) for j in range(k + 1)])
self.g[q].append(dot(self.f, self.ez[q][k]))
for p in range(nq):
for i in range(k):
self.gg[q][p][i].append(dot(self.az[q][i], self.ez[p][k]))
self.gg[q][p].append([dot(self.az[q][k], self.ez[p][j]) for j in range(k + 1)])
def online(self, mu: float) -> tuple[Vector, float]:
"""Return the coefficients c of u_r(mu) = Z c and the bound Delta(mu), from the small tables only."""
th = [1.0, mu]
r = len(self.z)
nq = len(th)
ar = [[sum(th[q] * self.ar[q][i][j] for q in range(nq)) for j in range(r)] for i in range(r)]
c = solve(ar, self.fr)
res2 = self.gff
for q in range(nq):
res2 -= 2.0 * th[q] * sum(c[j] * self.g[q][j] for j in range(r))
for p in range(nq):
res2 += th[q] * th[p] * sum(c[i] * c[j] * self.gg[q][p][i][j] for i in range(r) for j in range(r))
alpha_lb = min(1.0, mu / self.mu_bar)
return c, math.sqrt(max(res2, 0.0)) / alpha_lb
def lift(self, c: Vector) -> Vector:
return [sum(cj * zj[i] for cj, zj in zip(c, self.z)) for i in range(len(self.f))]
def weak_greedy(aq: list[Matrix], f: Vector, x: Matrix, mu_bar: float, train: list[float], tol: float, r_max: int) -> tuple[ReducedBasis, list[float], list[float]]:
"""Build a reduced basis by the weak greedy algorithm over the training set train.
Return the basis, the chosen parameters and the list eps_0, eps_1, ... of the largest
bound over train after each step (eps_0 is the bound of the empty basis, ||F||_X' / alpha_LB).
Stop when the largest bound is at most tol or the basis has r_max vectors.
"""
rb = ReducedBasis(aq, f, x, mu_bar)
chosen: list[float] = []
eps = [max(math.sqrt(rb.gff) / min(1.0, mu / mu_bar) for mu in train)]
mu = max(train, key=lambda m: math.sqrt(rb.gff) / min(1.0, m / mu_bar)) # @line L1: mu_1 maximizes the bound of the empty basis
while True: # @line L2
rb.add(rb.truth(mu)) # @line L3: one truth solve, then extend the basis and the tables
chosen.append(mu)
bounds = [rb.online(m)[1] for m in train] # @line L4: the bound at every training point, online
k = max(range(len(train)), key=lambda i: bounds[i]) # @line L5
eps.append(bounds[k])
if bounds[k] <= tol or len(chosen) >= r_max: # @line L6
return rb, chosen, eps # @line L7
mu = train[k] # @line L8
test_weak_greedy_reduced_basis.py 97 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weak-greedy-reduced-basis/. The authors are listed in prov/3WNNGB.jsonl.
import math
import random
import pytest
from scimat import dot, matvec, solve
from weak_greedy_reduced_basis import ReducedBasis, combine, fe_model, tridiag_solve, weak_greedy
N = 99
MU_BAR = 10.0
AQ, F = fe_model(N)
X = combine(AQ, [1.0, MU_BAR])
TRAIN = [10 ** (i / 20) for i in range(41)] # 41 points, log-spaced in [1, 100]
def x_norm(v):
return math.sqrt(dot(v, matvec(X, v)))
def dist_to_basis(rb, u):
"""X-distance of u to the span of the X-orthonormal basis."""
w = list(u)
for z in rb.z:
c = dot(z, matvec(X, w))
w = [wi - c * zi for wi, zi in zip(w, z)]
return x_norm(w)
def test_tridiagonal_solver_against_dense():
rng = random.Random(5)
a = combine(AQ, [1.0, 7.0])
b = [rng.gauss(0, 1) for _ in range(N)]
assert tridiag_solve(a, b) == pytest.approx(solve(a, b), rel=1e-9, abs=1e-12)
def test_strong_greedy_hand_example():
# the strong greedy step with the true distance, on three vectors in R^3
vecs = [(2.0, 0.0, 0.0), (1.0, 1.0, 0.0), (1.0, 1.0, 0.5)]
basis, sigmas = [], []
for _ in range(3):
d = []
for v in vecs:
w = list(v)
for b in basis:
c = sum(x * y for x, y in zip(b, w))
w = [x - c * y for x, y in zip(w, b)]
d.append(math.sqrt(sum(x * x for x in w)))
k = max(range(3), key=lambda i: d[i])
sigmas.append(d[k])
w = list(vecs[k])
for b in basis:
c = sum(x * y for x, y in zip(b, w))
w = [x - c * y for x, y in zip(w, b)]
basis.append([x / d[k] for x in w])
assert sigmas == pytest.approx([2.0, math.sqrt(1.25), math.sqrt(0.2)])
def test_example_run():
rb, chosen, eps = weak_greedy(AQ, F, X, MU_BAR, TRAIN, 1e-6, 20)
assert chosen == pytest.approx([1.0, 100.0, 10 ** 0.6, 10 ** 1.65, 10 ** 1.85])
assert eps[0] == pytest.approx(2.047, rel=1e-3)
assert eps[-1] <= 1e-6 < eps[-2]
assert all(eps[i + 1] < eps[i] for i in range(len(eps) - 1))
# at termination the true error on the training set is below the tolerance
for mu in TRAIN:
c, d = rb.online(mu)
err = x_norm([a - b for a, b in zip(rb.truth(mu), rb.lift(c))])
assert err <= d * (1 + 1e-9) + 1e-12 <= 1e-6 + 1e-12
def test_weak_greedy_property():
# dist(u(mu_(j+1)), X_j) >= max over train of dist(u(mu), X_j) / kappa, kappa = max (gamma / alpha_LB)^2 = 100
truths = [ReducedBasis(AQ, F, X, MU_BAR).truth(mu) for mu in TRAIN]
rb, chosen, eps = weak_greedy(AQ, F, X, MU_BAR, TRAIN, 1e-6, 20)
partial = ReducedBasis(AQ, F, X, MU_BAR)
for mu in chosen:
best = max(dist_to_basis(partial, u) for u in truths)
picked = dist_to_basis(partial, partial.truth(mu))
assert picked >= best / 100.0
partial.add(partial.truth(mu))
def test_termination_on_a_small_training_set():
rng = random.Random(9)
for _ in range(3):
train = sorted(rng.uniform(1.0, 100.0) for _ in range(3))
rb, chosen, eps = weak_greedy(AQ, F, X, MU_BAR, train, 1e-6, 50)
assert len(chosen) <= len(train)
assert len(set(chosen)) == len(chosen)
assert eps[-1] <= 1e-6
def test_r_max_stops_the_loop():
rb, chosen, eps = weak_greedy(AQ, F, X, MU_BAR, TRAIN, 0.0, 2)
assert len(chosen) == 2 and len(eps) == 3
History
The greedy choice of parameters, driven by the a posteriori error bound, is part of the reduced basis methods of Patera, Maday and coworkers, and is usually traced to a 2003 conference paper of Veroy, Prud'homme, Rovas and Patera. Buffa, Maday, Patera, Prud'homme and Turinici gave the first a priori convergence result in 2012, with a factor that grows like . Binev, Cohen, Dahmen, DeVore, Petrova and Wojtaszczyk introduced the parameter of a weak greedy algorithm and proved in 2011 that it keeps a polynomial rate of the Kolmogorov width. DeVore, Petrova and Wojtaszczyk gave in 2013 a short direct proof that also covers exponential rates and Banach spaces.
References
- Peter Binev, Albert Cohen, Wolfgang Dahmen, Ronald DeVore, Guergana Petrova and Przemyslaw Wojtaszczyk, Convergence rates for greedy algorithms in reduced basis methods, SIAM Journal on Mathematical Analysis 43(3), 2011, 1457-1472, the weak greedy algorithm with a parameter gamma, and the polynomial rate of the greedy error under a polynomial decay of the Kolmogorov width
- Annalisa Buffa, Yvon Maday, Anthony T. Patera, Christophe Prud'homme and Gabriel Turinici, A priori convergence of the greedy algorithm for the parametrized reduced basis method, ESAIM Mathematical Modelling and Numerical Analysis 46(3), 2012, 595-603, the first a priori bound of the greedy error, by a factor that grows like 2^n times the Kolmogorov width
- Ronald DeVore, Guergana Petrova and Przemyslaw Wojtaszczyk, Greedy algorithms for reduced bases in Banach spaces, Constructive Approximation 37(3), 2013, 455-466, Section 3, the comparison of the greedy error with the Kolmogorov width and its corollaries for polynomial and exponential decay (Theorem 3.2 and Corollary 3.3 in the arXiv version 1204.2290)
- Jan S. Hesthaven, Gianluigi Rozza and Benjamin Stamm, Certified Reduced Basis Methods for Parametrized Partial Differential Equations, SpringerBriefs in Mathematics, Springer, 2016, Chapter 3 (the greedy basis generation) and Chapter 4 (the error bounds that drive it)
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 3WNNGB Edit this page History Report an error Markdown