Algorithm Search⌘K

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
Properties
certifieddeterministicnot exactiterative
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 Δ(μ)\Delta(\mu) at every parameter of a finite training set Ξ\Xi, 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 rr full solves for a basis of size rr, and it returns a certified error bound on all of Ξ\Xi. 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 1/κ1/\kappa of the worst one. The Kolmogorov width dnd_n is the best error that any nn-dimensional space can give. The theory compares the greedy error σn\sigma_n with dnd_n: if dnd_n decays like a power of nn or like an exponential of a power, then σn\sigma_n 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 X=RnX = \mathbb{R}^n has the inner product (u,v)X=uTXv(u, v)_X = u^T X v. For each parameter μ\mu, the truth solution u(μ)u(\mu) solves A(μ)u=FA(\mu) u = F with A(μ)=∑q=1Qθq(μ)AqA(\mu) = \sum_{q=1}^{Q} \theta_q(\mu) A_q. The form a(u,v;μ)=vTA(μ)ua(u, v; \mu) = v^T A(\mu) u is coercive and continuous with constants α(μ)\alpha(\mu) and γ(μ)\gamma(\mu), and a lower bound 0<αLB(μ)≤α(μ)0 < \alpha_{LB}(\mu) \le \alpha(\mu) is known. For a space XjX_j, uj(μ)u_j(\mu) is the Galerkin solution in XjX_j, and

Δj(μ)=∥X−1(F−A(μ)uj(μ))∥XαLB(μ)\Delta_j(\mu) = \frac{\|X^{-1}(F - A(\mu) u_j(\mu))\|_X}{\alpha_{LB}(\mu)}

is the residual bound, with ∥u(μ)−uj(μ)∥X≤Δj(μ)≤(γ(μ)/αLB(μ))∥u(μ)−uj(μ)∥X\|u(\mu) - u_j(\mu)\|_X \le \Delta_j(\mu) \le (\gamma(\mu)/\alpha_{LB}(\mu)) \|u(\mu) - u_j(\mu)\|_X. The books write NN for the reduced size and NhN_h or N\mathcal{N} for the truth size. This page writes rr and nn.

The input is the affine data, a finite training set Ξ⊂P\Xi \subset \mathcal{P} with mm points, a tolerance εtol≥0\varepsilon_{tol} \ge 0 and a largest size rmaxr_{max}. The output is a nested sequence X1⊂X2⊂⋯⊂XrX_1 \subset X_2 \subset \cdots \subset X_r with Xj=span⁡{u(μ1),…,u(μj)}X_j = \operatorname{span}\{u(\mu_1), \ldots, u(\mu_j)\}, the offline tables for XrX_r, and the number εr=max⁡μ∈ΞΔr(μ)\varepsilon_r = \max_{\mu \in \Xi} \Delta_r(\mu), which bounds the error on Ξ\Xi.

The example uses the model problem of the reduced basis page: −u′′+μu=1-u'' + \mu u = 1 on (0,1)(0, 1) with zero boundary values, P1 elements with n=99n = 99, A(μ)=K+μMA(\mu) = K + \mu M, X=K+μˉMX = K + \bar{\mu} M with μˉ=10\bar{\mu} = 10, and αLB(μ)=min⁡(1,μ/μˉ)\alpha_{LB}(\mu) = \min(1, \mu/\bar{\mu}). Then γ(μ)≤max⁡(1,μ/μˉ)\gamma(\mu) \le \max(1, \mu/\bar{\mu}), so γ(μ)/αLB(μ)≤10\gamma(\mu)/\alpha_{LB}(\mu) \le 10 for μ∈[1,100]\mu \in [1, 100].

The algorithm

  1. WEAK-GREEDY(A_1..A_Q, F, X, α_LB, Ξ, ε_tol, r_max)
  2. 1μ ← argmax over μ' in Ξ of ‖F‖_X' / α_LB(μ') ▷ the bound of the empty basis
  3. 2repeat
  4. 3solve A(μ) u = F; add u to the X-orthonormal basis Z and extend the offline tables
  5. 4Δ(μ') ← the online bound of the reduced basis method, for each μ' in Ξ
  6. 5k ← the index of the largest Δ(μ') over Ξ
  7. 6if Δ(μ_k) ≤ ε_tol or Z has r_max columns then
  8. 7return Z, the tables, the chosen parameters and ε_r = Δ(μ_k)
  9. 8μ ← μ_k

Line L1 uses the bound of the empty basis, u0=0u_0 = 0, whose residual is FF. So the first parameter is the one with the smallest αLB\alpha_{LB}, here μ=1\mu = 1. Line L3 is the only full solve of a step. It orthonormalizes the new snapshot against ZZ in the XX inner product, two passes of Gram-Schmidt, and adds the new rows and columns to the tables ZTAqZZ^T A_q Z, FTX−1AqzjF^T X^{-1} A_q z_j and (Aqzi)TX−1Apzj(A_q z_i)^T X^{-1} A_p z_j of the reduced basis method. Line L4 is the online stage of that method, run mm times. It uses only the small tables, so its cost does not depend on nn. 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 R3\mathbb{R}^3 with the Euclidean norm: v1=(2,0,0)v_1 = (2, 0, 0), v2=(1,1,0)v_2 = (1, 1, 0) and v3=(1,1,0.5)v_3 = (1, 1, 0.5). Their norms are 22, 2\sqrt{2} and 1.51.5, so step 1 takes v1v_1 with σ0=2\sigma_0 = 2. After the projection onto e1e_1, the remainders are (0,1,0)(0, 1, 0) and (0,1,0.5)(0, 1, 0.5), so step 2 takes v3v_3 with σ1=1.25≈1.118\sigma_1 = \sqrt{1.25} \approx 1.118. The remainder of v2v_2 after the projection onto (0,1,0.5)/1.25(0, 1, 0.5)/\sqrt{1.25} is (0,0.2,−0.4)(0, 0.2, -0.4), so σ2=0.2≈0.447\sigma_2 = \sqrt{0.2} \approx 0.447. A weak greedy step with κ=2\kappa = 2 could also take v2v_2 in step 2, because its distance 1 is at least σ1/2\sigma_1/2.

The model problem. The training set has the m=41m = 41 points μ=10i/20\mu = 10^{i/20}, i=0,…,40i = 0, \ldots, 40, from 1 to 100, and εtol=10−6\varepsilon_{tol} = 10^{-6}. The table is a measurement from the test file. Step jj adds μj\mu_j; the columns give the largest bound and the largest true error ∥u−uj∥X\|u - u_j\|_X over Ξ\Xi after the step, and the range of the effectivity Δj/∥u−uj∥X\Delta_j / \|u - u_j\|_X over Ξ\Xi (at the parameters with an error above 10−910^{-9}).

jj μj\mu_j εj=max⁡ΞΔj\varepsilon_j = \max_\Xi \Delta_j max⁡Ξ∥u−uj∥X\max_\Xi \|u - u_j\|_X at μ\mu effectivity
0 2.047 0.371 1
1 1 2.671×10−22.671 \times 10^{-2} 1.845×10−21.845 \times 10^{-2} 35.48 1.00 to 8.15
2 100 3.336×10−33.336 \times 10^{-3} 2.790×10−32.790 \times 10^{-3} 17.78 1.00 to 8.50
3 3.981 1.262×10−41.262 \times 10^{-4} 1.171×10−41.171 \times 10^{-4} 44.67 1.00 to 8.72
4 44.67 1.851×10−61.851 \times 10^{-6} 1.708×10−61.708 \times 10^{-6} 70.80 1.00 to 9.72
5 70.80 6.448×10−86.448 \times 10^{-8} 4.219×10−84.219 \times 10^{-8} 19.95 1.01 to 44.2

The loop stops at r=5r = 5, with 5 full solves. The bound falls by about two orders of magnitude per step. Up to j=4j = 4 the effectivity is below γ/αLB≤10\gamma/\alpha_{LB} \le 10, as the theory says. At j=5j = 5 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 μ=35.48\mu = 35.48, but the largest bound is at μ=100\mu = 100, so step 2 takes μ=100\mu = 100. A strong greedy run with the true errors picks 1,35.48,100,10,70.801, 35.48, 100, 10, 70.80, and its largest errors after steps 2, 3 and 4 are 1.934×10−31.934 \times 10^{-3}, 9.861×10−59.861 \times 10^{-5} and 2.108×10−62.108 \times 10^{-6}. So the weak choice costs little. On 1000 test points in [1,100][1, 100] that are not in Ξ\Xi, the largest error after step 5 is 4.232×10−84.232 \times 10^{-8} and the largest bound is 7.273×10−87.273 \times 10^{-8}.

Correctness

The proof file shows three facts, in exact arithmetic. First, the loop stops after at most mm steps, and line L3 never adds a snapshot that is already in the span. The reason is that Δj(μi)=0\Delta_j(\mu_i) = 0 at each chosen parameter, because the reduced solution reproduces the truth there. So a bound above εtol\varepsilon_{tol} is never at a chosen point. Second, if the loop stops by the tolerance, then ∥u(μ)−ur(μ)∥X≤εtol\|u(\mu) - u_r(\mu)\|_X \le \varepsilon_{tol} for every μ∈Ξ\mu \in \Xi, because the bound is reliable. Third, each step is a weak greedy step: with κ=max⁡Ξγ(μ)2/(α(μ) αLB(μ))\kappa = \max_{\Xi} \gamma(\mu)^2 / (\alpha(\mu)\, \alpha_{LB}(\mu)),

dist⁡X(u(μj+1),Xj)≥1κmax⁡μ∈Ξdist⁡X(u(μ),Xj).\operatorname{dist}_X(u(\mu_{j+1}), X_j) \ge \frac{1}{\kappa} \max_{\mu \in \Xi} \operatorname{dist}_X(u(\mu), X_j) .

The proof chains Cea's lemma, ∥u−uj∥X≤(γ/α)dist⁡X(u,Xj)\|u - u_j\|_X \le (\gamma/\alpha) \operatorname{dist}_X(u, X_j), with the two sides of the bound. In the example κ≤100\kappa \le 100, 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 1/κ1/\kappa on a compact set K\mathcal{K} of a Hilbert space, here K={u(μ):μ∈Ξ}\mathcal{K} = \{u(\mu) : \mu \in \Xi\}. Let σn=max⁡Kdist⁡(u,Xn)\sigma_n = \max_{\mathcal{K}} \operatorname{dist}(u, X_n) and let dnd_n be the Kolmogorov nn-width of K\mathcal{K}. DeVore, Petrova and Wojtaszczyk prove that dn≤C0n−ad_n \le C_0 n^{-a} gives σn≤C1n−a\sigma_n \le C_1 n^{-a} with C1=25a+1κ2C0C_1 = 2^{5a+1} \kappa^2 C_0, and that dn≤C0e−c0nad_n \le C_0 e^{-c_0 n^a} gives σn≤Ce−c1na\sigma_n \le C e^{-c_1 n^a} with c1=2−1−2ac0c_1 = 2^{-1-2a} c_0. 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 σn\sigma_n is close to dnd_n for each nn.

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: (u,v)X=uTXv(u, v)_X = u^T X v with a symmetric positive definite XX, a(u,v;μ)=vTA(μ)ua(u, v; \mu) = v^T A(\mu) u, coercivity a(v,v;μ)≥α(μ)∥v∥X2a(v, v; \mu) \ge \alpha(\mu) \|v\|_X^2, continuity ∣a(u,v;μ)∣≤γ(μ)∥u∥X∥v∥X|a(u, v; \mu)| \le \gamma(\mu) \|u\|_X \|v\|_X and 0<αLB(μ)≤α(μ)0 < \alpha_{LB}(\mu) \le \alpha(\mu). For a subspace XjX_j, uj(μ)∈Xju_j(\mu) \in X_j is the Galerkin solution, ej(μ)=u(μ)−uj(μ)e_j(\mu) = u(\mu) - u_j(\mu), and Δj(μ)\Delta_j(\mu) is the bound of the reduced basis method. The empty space X0={0}X_0 = \{0\} has u0=0u_0 = 0. We use three facts that the proof file of the reduced basis method shows, and that hold for X0X_0 in the same way, with residual FF.

  • (R) Reliability and effectivity: ∥ej(μ)∥X≤Δj(μ)≤(γ(μ)/αLB(μ))∥ej(μ)∥X\|e_j(\mu)\|_X \le \Delta_j(\mu) \le (\gamma(\mu)/\alpha_{LB}(\mu)) \|e_j(\mu)\|_X.
  • (P) Reproduction: if u(μ)∈Xju(\mu) \in X_j, then uj(μ)=u(μ)u_j(\mu) = u(\mu) and Δj(μ)=0\Delta_j(\mu) = 0.
  • (E) Line L4 computes Δj\Delta_j exactly from the tables, and line L3 keeps ZZ an XX-orthonormal basis of Xj=span⁡{u(μ1),…,u(μj)}X_j = \operatorname{span}\{u(\mu_1), \ldots, u(\mu_j)\} as long as each new snapshot is not in Xj−1X_{j-1}.

Lemma 1 (Cea in the X norm). ∥ej(μ)∥X≤(γ(μ)/α(μ))dist⁡X(u(μ),Xj)\|e_j(\mu)\|_X \le (\gamma(\mu)/\alpha(\mu)) \operatorname{dist}_X(u(\mu), X_j).

Proof. Galerkin orthogonality gives a(ej,w;μ)=0a(e_j, w; \mu) = 0 for all w∈Xjw \in X_j. For any v∈Xjv \in X_j, uj−v∈Xju_j - v \in X_j, so α∥ej∥X2≤a(ej,ej;μ)=a(ej,u−v;μ)≤γ∥ej∥X∥u−v∥X\alpha \|e_j\|_X^2 \le a(e_j, e_j; \mu) = a(e_j, u - v; \mu) \le \gamma \|e_j\|_X \|u - v\|_X. Divide by ∥ej∥X\|e_j\|_X (the claim is clear if it is 0) and take the infimum over vv. □\square

Lemma 2 (no repeated choice). Suppose the loop does not stop at step jj, so the largest bound Δj(μk)\Delta_j(\mu_k) is above εtol≥0\varepsilon_{tol} \ge 0. Then u(μk)∉Xju(\mu_k) \notin X_j, and in particular μk\mu_k is not one of μ1,…,μj\mu_1, \ldots, \mu_j.

Proof. If u(μk)∈Xju(\mu_k) \in X_j, then (P) gives Δj(μk)=0≤εtol\Delta_j(\mu_k) = 0 \le \varepsilon_{tol}, a contradiction. Each chosen u(μi)u(\mu_i), i≤ji \le j, is in XjX_j. □\square

The first parameter comes from line L1. Its snapshot u(μ1)u(\mu_1) is not 0 when F≠0F \ne 0, since A(μ1)A(\mu_1) is invertible. (If F=0F = 0, all bounds are 0 and the first test stops the loop with u=0u = 0 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 min⁡(m,rmax)\min(m, r_{max}) steps.

Proof. By Lemma 2 the chosen parameters are distinct points of Ξ\Xi, so there are at most mm of them. After mm steps, every u(μ)u(\mu) with μ∈Ξ\mu \in \Xi is in XmX_m, so by (P) every bound is 0 and the test of line L6 holds. The test also holds when ZZ has rmaxr_{max} columns. □\square

Theorem 2 (certification). At the return of line L7 with rr vectors, ∥u(μ)−ur(μ)∥X≤εr\|u(\mu) - u_r(\mu)\|_X \le \varepsilon_r for all μ∈Ξ\mu \in \Xi. If the loop stops by the tolerance, εr≤εtol\varepsilon_r \le \varepsilon_{tol}.

Proof. εr\varepsilon_r is the largest bound over Ξ\Xi (line L5), and each bound is at least the error by (R). □\square

Theorem 3 (weak greedy step). Let κ=max⁡μ∈Ξγ(μ)2/(α(μ) αLB(μ))\kappa = \max_{\mu \in \Xi} \gamma(\mu)^2 / (\alpha(\mu)\, \alpha_{LB}(\mu)). The parameter μ∗\mu^\ast that the algorithm chooses after XjX_j (by line L1 for j=0j = 0, by line L5 for j≥1j \ge 1) satisfies

dist⁡X(u(μ∗),Xj)≥1κmax⁡μ∈Ξdist⁡X(u(μ),Xj).\operatorname{dist}_X(u(\mu^\ast), X_j) \ge \frac{1}{\kappa} \max_{\mu \in \Xi} \operatorname{dist}_X(u(\mu), X_j) .

Proof. For each μ∈Ξ\mu \in \Xi, Δj(μ∗)≥Δj(μ)\Delta_j(\mu^\ast) \ge \Delta_j(\mu) by the choice. Then

dist⁡X(u(μ∗),Xj)≥α(μ∗)γ(μ∗)∥ej(μ∗)∥X≥α(μ∗) αLB(μ∗)γ(μ∗)2Δj(μ∗)≥1κΔj(μ)≥1κ∥ej(μ)∥X≥1κdist⁡X(u(μ),Xj).\operatorname{dist}_X(u(\mu^\ast), X_j) \ge \frac{\alpha(\mu^\ast)}{\gamma(\mu^\ast)} \|e_j(\mu^\ast)\|_X \ge \frac{\alpha(\mu^\ast)\, \alpha_{LB}(\mu^\ast)}{\gamma(\mu^\ast)^2} \Delta_j(\mu^\ast) \ge \frac{1}{\kappa} \Delta_j(\mu) \ge \frac{1}{\kappa} \|e_j(\mu)\|_X \ge \frac{1}{\kappa} \operatorname{dist}_X(u(\mu), X_j) .

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 κ\kappa. The last holds because uj(μ)∈Xju_j(\mu) \in X_j. Take the maximum over μ\mu. For j=0j = 0 the bound of the empty basis is ∥F∥X′/αLB(μ)\|F\|_{X'}/\alpha_{LB}(\mu) and line L1 maximizes it, so the same chain holds. □\square

Corollary (the model problem). For A(μ)=K+μMA(\mu) = K + \mu M, X=K+μˉMX = K + \bar{\mu} M and αLB(μ)=min⁡(1,μ/μˉ)\alpha_{LB}(\mu) = \min(1, \mu/\bar{\mu}), the reduced basis proof file shows γ(μ)≤max⁡(1,μ/μˉ)\gamma(\mu) \le \max(1, \mu/\bar{\mu}). With α≥αLB\alpha \ge \alpha_{LB}, κ≤max⁡Ξ(γ/αLB)2\kappa \le \max_{\Xi} (\gamma/\alpha_{LB})^2, which is 102=10010^2 = 100 for μˉ=10\bar{\mu} = 10 and Ξ⊂[1,100]\Xi \subset [1, 100].

By Theorem 3, the algorithm is a weak greedy algorithm with parameter 1/κ1/\kappa on the compact set {u(μ):μ∈Ξ}\{u(\mu) : \mu \in \Xi\} in the sense of Binev et al. and of DeVore, Petrova and Wojtaszczyk, so their rate theorems apply to σn=max⁡Ξdist⁡X(u(μ),Xn)\sigma_n = \max_{\Xi} \operatorname{dist}_X(u(\mu), X_n). ■\blacksquare

Complexity

In the real RAM model, with banded matrices in 1D, step jj costs one full solve, O(n)O(n), Gram-Schmidt against jj vectors, O(jn)O(j n), QQ solves with XX, O(Qn)O(Q n), and the new table entries, O(Q2jn)O(Q^2 j n). The mm online solves of line L4 cost O(m(Qj2+j3+Q2j2))O(m(Q j^2 + j^3 + Q^2 j^2)). The sum over j≤rj \le r is O(Q2r2n+mr4+mQ2r3)O(Q^2 r^2 n + m r^4 + m Q^2 r^3). The main gain over POD is the number of full solves: rr in place of mm. Memory is O(Qrn)O(Q r n) for the representers, O(Q2r2)O(Q^2 r^2) for the tables and O(m)O(m) for the bounds. The implementation stores the matrices dense for simplicity, so its products with XX cost O(n2)O(n^2); only its solves are tridiagonal.

Properties

  • Few full solves. One per basis vector.
  • Certified on the training set. The returned εr\varepsilon_r bounds the error at every μ∈Ξ\mu \in \Xi.
  • 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 dnd_n carry over to σn\sigma_n.
  • Not optimal for each nn. σn≥dn\sigma_n \ge d_n 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 Ξ\Xi near the chosen points, or draw a new random Ξ\Xi 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 εj\varepsilon_j.

Pitfalls

  • The rounding floor. The bound is computed from ρ2\rho^2, a difference of numbers of size ∥F∥X′2\|F\|_{X'}^2, so it cannot go much below εmach ∥F∥X′/αLB\sqrt{\varepsilon_{mach}}\, \|F\|_{X'} / \alpha_{LB}, about 10−810^{-8} here. A tolerance below the floor makes the loop run to rmaxr_{max}, and at the floor the bound can choose a point at random. In the example the effectivity jumps to 44 at r=5r = 5.
  • Certified only on Ξ\Xi. The bound is computed at the training points only. A coarse Ξ\Xi 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 αLB\alpha_{LB} is too small, the bound and κ\kappa are large, the greedy choice is driven by the stability factor and not by the error, and the loop picks too many points where αLB\alpha_{LB} 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 10−1010^{-10} times the snapshot norm.
  • Online work on the mesh. If line L4 forms the reduced matrix or the residual from vectors of length nn, each step costs O(mQ2r2n)O(m Q^2 r^2 n), 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.

scimat.pyI0RawGitHub
# 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 2n2^n. Binev, Cohen, Dahmen, DeVore, Petrova and Wojtaszczyk introduced the parameter γ\gamma 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

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

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