Algorithm Search⌘K

Algorithmcore

POD-Galerkin reduced-order model

Also called POD-Galerkin model.

Projects the equations of a large model onto the leading proper orthogonal decomposition modes of its snapshots, which gives a small system of ODEs that runs fast.

Time
O(n r) liftO(n m^2 + m^3 + n^2 r) offlineO(r^3 + K r^2) online
Space
O(n m + n r + r^2) extra
Where
K = the number of time steps; m = the number of snapshots; n = the state dimension; r = the size of the reduced basis
Properties
deterministicnot exactintrusivenot iterative
Origin
John L. Lumley, Lawrence Sirovich, Philip Holmes, Gal Berkooz, 1987

A POD-Galerkin reduced-order model replaces a large linear system of ODEs x′=Ax+fx' = A x + f with nn unknowns by a system with rr unknowns, where rr is much smaller than nn. It runs the full model once and stores the states as snapshots. It takes the rr leading proper orthogonal decomposition (POD) modes of the snapshots as an orthonormal basis VV. Then it projects the equations onto that basis by a Galerkin method. The POD modes are the leading left singular vectors of the snapshot matrix SS (see singular value decomposition). They are the vectors that principal component analysis finds when the snapshots are not centered. POD alone only compresses data. The Galerkin step makes a model that you can run again, for example with new initial values. Dynamic mode decomposition fits a linear map to the snapshots and needs no equations, and its modes are not orthogonal. Balanced truncation also reduces linear systems, but it takes its basis from the Gramians of an input-output system and has an a priori error bound. POD uses only the states that it saw. The reduced basis method uses the same projection for problems with parameters, with snapshots chosen by a weak greedy search.

In plain words

A heat simulation on a fine grid has thousands of numbers per time step, but the temperature profiles it goes through look alike. A few basic shapes, added with the right weights, describe each of them well. POD finds these shapes from a set of stored profiles: the first shape is the one that matches all the profiles best, the second one adds the most to the first, and so on.

Then the model changes its unknowns. It does not track the temperature at each grid point. It tracks only the weights of the few shapes. The equations are projected onto the shapes, which gives a small system with rr unknowns instead of nn. Each time step of the small system costs almost nothing. The price is a single run of the full model, plus the risk that the shapes do not fit states the model never saw.

The problem

The full model is the linear system x′(t)=Ax(t)+fx'(t) = A x(t) + f with a constant nn by nn matrix AA, a constant vector ff and an initial value x0x_0. It is stepped with the backward Euler method with step dtdt:

(I−dt A) xk+1=xk+dt f,k=0,…,K−1.(I - dt\, A)\, x_{k+1} = x_k + dt\, f, \qquad k = 0, \ldots, K - 1.

The snapshot matrix SS has mm columns s1,…,sm∈Rns_1, \ldots, s_m \in \mathbb{R}^n, one per stored state; in the example they are the states x0,…,xKx_0, \ldots, x_K of a training run, so m=K+1m = K + 1. For r≤rank⁡Sr \le \operatorname{rank} S, the POD basis of size rr is an nn by rr matrix VV with orthonormal columns that minimizes the projection error

E(V)=∑j=1m∥sj−VVTsj∥22.E(V) = \sum_{j=1}^{m} \| s_j - V V^T s_j \|_2^2.

The output is the reduced trajectory x~k=Vzk\tilde{x}_k = V z_k, where zk∈Rrz_k \in \mathbb{R}^r solves the Galerkin reduced system: the full equation with x=Vzx = V z, multiplied by VTV^T. This page writes rr for the reduced size and nn for the full size. The books of Hesthaven, Rozza and Stamm and of Quarteroni, Manzoni and Negri write NN for the reduced size and NhN_h or N\mathcal{N} for the full size.

The algorithm

  1. POD-GALERKIN(A, f, x_0, dt, K, S, r)
  2. 1C ← S^T S ▷ m by m correlation matrix
  3. 2(λ_i, w_i) ← eigenpairs of C, λ_1 ≥ λ_2 ≥ ... ≥ λ_m ≥ 0, with orthonormal w_i
  4. 3v_i ← S w_i / sqrt(λ_i) for i = 1..r; V ← [v_1 ... v_r]
  5. 4A_r ← V^T A V; f_r ← V^T f; z_0 ← V^T x_0 ▷ offline stage
  6. 5for k = 0 to K - 1 do ▷ online stage
  7. 6z_(k+1) ← (I - dt A_r)^(-1) (z_k + dt f_r)
  8. 7return x̃_k = V z_k for k = 0..K

Lines L1 to L3 are the method of snapshots of Sirovich. They solve an eigenvalue problem of size mm, not nn, which is cheap when there are fewer snapshots than unknowns. Line L2 needs λr>0\lambda_r > 0; the implementation raises an error otherwise, and it finds the eigenpairs with the Jacobi eigenvalue algorithm. Line L3 maps each eigenvector of CC back to a mode in Rn\mathbb{R}^n; the division by λi\sqrt{\lambda_i} makes the mode a unit vector. Line L4 builds the reduced operators once. This is the offline stage, and it is the only part that touches vectors of length nn apart from the last line. Lines L5 and L6 are backward Euler on the reduced system; the implementation forms the rr by rr inverse once and reuses it. Line L7 lifts the reduced states back to the full space. For backward Euler on a linear system, it gives the same zkz_k to project the ODE first and then step it, or to step it first and then project.

Example

A hand example. Take n=3n = 3, two snapshots s1=(1,1,1)s_1 = (1, 1, 1) and s2=(1,1,−1)s_2 = (1, 1, -1), the matrix A=16tridiag⁡(1,−2,1)A = 16 \operatorname{tridiag}(1, -2, 1) of the heat equation ut=uxxu_t = u_{xx} on three interior points with h=1/4h = 1/4, and r=1r = 1.

line result
L1 C=(3113)C = \begin{pmatrix} 3 & 1 \\ 1 & 3 \end{pmatrix}
L2 λ1=4\lambda_1 = 4, w1=(1,1)/2w_1 = (1, 1)/\sqrt{2}; λ2=2\lambda_2 = 2, w2=(1,−1)/2w_2 = (1, -1)/\sqrt{2}
L3 v1=Sw1/2=(2,2,0)/(22)=(1,1,0)/2v_1 = S w_1 / 2 = (2, 2, 0) / (2\sqrt{2}) = (1, 1, 0)/\sqrt{2}
L4 Av1=16(−1,−1,1)/2A v_1 = 16 (-1, -1, 1)/\sqrt{2}, so Ar=v1TAv1=−16A_r = v_1^T A v_1 = -16

The projection error with r=1r = 1 is ∥s1−v1v1Ts1∥2+∥s2−v1v1Ts2∥2=∥(0,0,1)∥2+∥(0,0,−1)∥2=2\|s_1 - v_1 v_1^T s_1\|^2 + \|s_2 - v_1 v_1^T s_2\|^2 = \|(0, 0, 1)\|^2 + \|(0, 0, -1)\|^2 = 2, which is λ2\lambda_2, as the correctness section says. With r=2r = 2 the second mode is v2=Sw2/2=(0,0,1)v_2 = S w_2 / \sqrt{2} = (0, 0, 1), the two modes span both snapshots, and the error is 0. One online step with x0=s1x_0 = s_1, f=0f = 0 and dt=1/16dt = 1/16 gives z0=2z_0 = \sqrt{2} and z1=2/(1+16 dt)=2/2z_1 = \sqrt{2} / (1 + 16\, dt) = \sqrt{2}/2, so x~1=(1/2,1/2,0)\tilde{x}_1 = (1/2, 1/2, 0). The full step gives x1=(4/7,5/7,4/7)x_1 = (4/7, 5/7, 4/7); one mode cannot hold the third component.

A measurement. The full model is the heat equation on (0,1)(0, 1) with u=0u = 0 at both ends and a source f=1f = 1, on n=60n = 60 interior points (h=1/61h = 1/61), with dt=0.002dt = 0.002 and K=20K = 20 steps. The initial value is 1 at the 12 grid points in [0.2,0.4][0.2, 0.4] and 0 elsewhere. The snapshots are the 21 states of this run, and the reduced model then runs the same problem. The script is the test file of the implementation.

rr λr\lambda_r ∑i>rλi\sum_{i > r} \lambda_i measured ∑j∥sj−VVTsj∥2\sum_j \|s_j - V V^T s_j\|^2 max⁡k∥xk−Vzk∥2\max_k \|x_k - V z_k\|_2
1 78.851 7.5391 7.5391 1.8074
2 6.5374 1.0016 1.0016 0.60535
3 0.85575 0.14589 0.14589 0.31229
4 0.13956 6.3318×10−36.3318 \times 10^{-3} 6.3318×10−36.3318 \times 10^{-3} 4.9508×10−24.9508 \times 10^{-2}
5 5.9171×10−35.9171 \times 10^{-3} 4.1472×10−44.1472 \times 10^{-4} 4.1472×10−44.1472 \times 10^{-4} 1.3277×10−21.3277 \times 10^{-2}
6 3.9203×10−43.9203 \times 10^{-4} 2.2684×10−52.2684 \times 10^{-5} 2.2684×10−52.2684 \times 10^{-5} 2.6899×10−32.6899 \times 10^{-3}
7 2.1838×10−52.1838 \times 10^{-5} 8.4650×10−78.4650 \times 10^{-7} 8.4650×10−78.4650 \times 10^{-7} 4.7749×10−44.7749 \times 10^{-4}

The third and fourth columns agree to all printed digits, which is the identity of Lemma 2 in the proof. The eigenvalues fall by a factor of 10 to 40 per mode, because diffusion damps the short waves fast. The largest error of the reduced model is at k=0k = 0, where the step in the initial value is hardest to represent. Seven modes give an error of 4.8×10−44.8 \times 10^{-4} against ∥x0∥2=3.46\|x_0\|_2 = 3.46. This is the easy case: the reduced model runs the problem that made its snapshots.

Correctness

The proof file shows four facts. First, the columns of VV from line L3 are orthonormal. Second, the projection error of the snapshots is exactly ∑i>rλi\sum_{i > r} \lambda_i, the sum of the discarded squared singular values of SS. Third, if AA is symmetric and negative semidefinite, as for the heat equation, the matrix I−dt ArI - dt\, A_r in line L6 is invertible for every dt>0dt > 0 and its inverse has norm at most 1. Fourth, with ρk=xk−VVTxk\rho_k = x_k - V V^T x_k, the error of the reduced model obeys

∥xk−Vzk∥22=∥ρk∥22+∥VTxk−zk∥22,∥VTxK−zK∥2≤dt∑k=1K∥Aρk∥2.\|x_k - V z_k\|_2^2 = \|\rho_k\|_2^2 + \|V^T x_k - z_k\|_2^2, \qquad \|V^T x_K - z_K\|_2 \le dt \sum_{k=1}^{K} \|A \rho_k\|_2 .

So if every state of the run lies in the span of VV, the reduced model reproduces the run exactly. The proof that VV minimizes E(V)E(V) is the Schmidt-Eckart-Young theorem for the singular value decomposition, and the page cites it; the tests check the identity of the second fact and a random basis against POD. The bound has the factor ∥Aρk∥\|A \rho_k\|, not ∥ρk∥\|\rho_k\|, so a small projection error can still give a large reduced model error when AA has a large norm. For nonlinear flows there is no such bound in general, and the reduced model can be unstable.

Proof: The POD basis is orthonormal, its snapshot error is the sum of the discarded eigenvalues, and the reduced model error is bounded by the projection errorfull

We assume exact arithmetic. SS is an nn by mm real matrix with columns s1,…,sms_1, \ldots, s_m, and C=STSC = S^T S (line L1). CC is symmetric and positive semidefinite, so it has orthonormal eigenvectors w1,…,wmw_1, \ldots, w_m with eigenvalues λ1≥⋯≥λm≥0\lambda_1 \ge \cdots \ge \lambda_m \ge 0 (line L2). Let r≥1r \ge 1 with λr>0\lambda_r > 0, and let vi=Swi/λiv_i = S w_i / \sqrt{\lambda_i} for i≤ri \le r (line L3). For each ii with λi>0\lambda_i > 0 we define viv_i in the same way, and V=[v1,…,vr]V = [v_1, \ldots, v_r].

Lemma 1 (orthonormal modes). For i,ji, j with λi,λj>0\lambda_i, \lambda_j > 0, viTvj=δijv_i^T v_j = \delta_{ij}. For λi=0\lambda_i = 0, Swi=0S w_i = 0.

Proof. viTvj=wiTSTSwj/λiλj=λj wiTwj/λiλj=δijv_i^T v_j = w_i^T S^T S w_j / \sqrt{\lambda_i \lambda_j} = \lambda_j\, w_i^T w_j / \sqrt{\lambda_i \lambda_j} = \delta_{ij}, because the wiw_i are orthonormal. If λi=0\lambda_i = 0, then ∥Swi∥2=wiTCwi=0\|S w_i\|^2 = w_i^T C w_i = 0. □\square

Lemma 2 (the projection error). ∑j=1m∥sj−VVTsj∥22=∑i=r+1mλi\sum_{j=1}^{m} \|s_j - V V^T s_j\|_2^2 = \sum_{i = r+1}^{m} \lambda_i.

Proof. Let W=[w1,…,wm]W = [w_1, \ldots, w_m], an orthogonal matrix. Then S=SWWT=∑i=1m(Swi)wiTS = S W W^T = \sum_{i=1}^{m} (S w_i) w_i^T. By Lemma 1 the terms with λi=0\lambda_i = 0 vanish, so

S=∑λi>0λi viwiT.S = \sum_{\lambda_i > 0} \sqrt{\lambda_i}\, v_i w_i^T .

By Lemma 1, VTvi=eiV^T v_i = e_i for i≤ri \le r and VTvi=0V^T v_i = 0 for i>ri > r with λi>0\lambda_i > 0. Hence VVTS=∑i≤rλi viwiTV V^T S = \sum_{i \le r} \sqrt{\lambda_i}\, v_i w_i^T and S−VVTS=∑i>r,λi>0λi viwiTS - V V^T S = \sum_{i > r, \lambda_i > 0} \sqrt{\lambda_i}\, v_i w_i^T. The left side of the claim is the squared Frobenius norm of this matrix, which is the sum of the squared norms of its columns. The matrices viwiTv_i w_i^T are orthonormal in the Frobenius inner product, because tr⁡((viwiT)TvjwjT)=(viTvj)(wjTwi)=δij\operatorname{tr}((v_i w_i^T)^T v_j w_j^T) = (v_i^T v_j)(w_j^T w_i) = \delta_{ij}. So the squared norm is ∑i>rλi\sum_{i > r} \lambda_i. □\square

The formula S=∑iλi viwiTS = \sum_i \sqrt{\lambda_i}\, v_i w_i^T is a singular value decomposition of SS, with singular values σi=λi\sigma_i = \sqrt{\lambda_i}. So Lemma 2 says that the error is the sum of the discarded σi2\sigma_i^2. That no other nn by rr matrix with orthonormal columns gives a smaller error is the Schmidt-Eckart-Young theorem, which we do not prove here.

Now let AA be an nn by nn matrix, f∈Rnf \in \mathbb{R}^n and dt>0dt > 0. The full states satisfy (I−dtA)xk+1=xk+dtf(I - dt A) x_{k+1} = x_k + dt f. Line L4 sets Ar=VTAVA_r = V^T A V, fr=VTff_r = V^T f and z0=VTx0z_0 = V^T x_0, and line L6 sets (I−dtAr)zk+1=zk+dtfr(I - dt A_r) z_{k+1} = z_k + dt f_r.

Lemma 3 (stability). If A+ATA + A^T is negative semidefinite, then for every z∈Rrz \in \mathbb{R}^r, ∥(I−dtAr)z∥2≥∥z∥2\|(I - dt A_r) z\|_2 \ge \|z\|_2. So I−dtArI - dt A_r is invertible and ∥(I−dtAr)−1∥2≤1\|(I - dt A_r)^{-1}\|_2 \le 1.

Proof. Ar+ArT=VT(A+AT)VA_r + A_r^T = V^T (A + A^T) V, so zT(Ar+ArT)z=(Vz)T(A+AT)(Vz)≤0z^T (A_r + A_r^T) z = (V z)^T (A + A^T)(V z) \le 0. Then

∥(I−dtAr)z∥2=∥z∥2−dt zT(Ar+ArT)z+dt2∥Arz∥2≥∥z∥2.\|(I - dt A_r) z\|^2 = \|z\|^2 - dt\, z^T (A_r + A_r^T) z + dt^2 \|A_r z\|^2 \ge \|z\|^2 .

A matrix with this property has a zero kernel, so it is invertible, and ∥(I−dtAr)−1y∥≤∥y∥\|(I - dt A_r)^{-1} y\| \le \|y\| follows with y=(I−dtAr)zy = (I - dt A_r) z. □\square

A symmetric negative semidefinite AA, such as the central difference matrix of uxxu_{xx} with zero boundary values, satisfies the hypothesis.

Theorem (the error of the reduced model). Let ρk=xk−VVTxk\rho_k = x_k - V V^T x_k and θk=VTxk−zk\theta_k = V^T x_k - z_k. Then

  1. ∥xk−Vzk∥22=∥ρk∥22+∥θk∥22\|x_k - V z_k\|_2^2 = \|\rho_k\|_2^2 + \|\theta_k\|_2^2 for each kk;
  2. (I−dtAr) θk+1=θk+dt VTAρk+1(I - dt A_r)\, \theta_{k+1} = \theta_k + dt\, V^T A \rho_{k+1}, with θ0=0\theta_0 = 0;
  3. if A+ATA + A^T is negative semidefinite, ∥θK∥2≤dt∑k=1K∥Aρk∥2\|\theta_K\|_2 \le dt \sum_{k=1}^{K} \|A \rho_k\|_2.

Proof. (1) xk−Vzk=ρk+Vθkx_k - V z_k = \rho_k + V \theta_k. The vector ρk\rho_k is orthogonal to the range of VV, because VTρk=VTxk−VTVVTxk=0V^T \rho_k = V^T x_k - V^T V V^T x_k = 0, and ∥Vθk∥=∥θk∥\|V \theta_k\| = \|\theta_k\|. The claim is the theorem of Pythagoras.

(2) Multiply the full step by VTV^T: VTxk+1−dt VTAxk+1=VTxk+dt frV^T x_{k+1} - dt\, V^T A x_{k+1} = V^T x_k + dt\, f_r. Write xk+1=VVTxk+1+ρk+1x_{k+1} = V V^T x_{k+1} + \rho_{k+1}, so VTAxk+1=ArVTxk+1+VTAρk+1V^T A x_{k+1} = A_r V^T x_{k+1} + V^T A \rho_{k+1}. This gives

(I−dtAr)VTxk+1=VTxk+dt fr+dt VTAρk+1.(I - dt A_r) V^T x_{k+1} = V^T x_k + dt\, f_r + dt\, V^T A \rho_{k+1} .

Subtract the reduced step of line L6. θ0=VTx0−z0=0\theta_0 = V^T x_0 - z_0 = 0 by line L4.

(3) By (2) and Lemma 3, ∥θk+1∥≤∥θk+dt VTAρk+1∥≤∥θk∥+dt∥Aρk+1∥\|\theta_{k+1}\| \le \|\theta_k + dt\, V^T A \rho_{k+1}\| \le \|\theta_k\| + dt \|A \rho_{k+1}\|, because ∥VTy∥≤∥y∥\|V^T y\| \le \|y\| for a matrix with orthonormal columns. Sum over k=0,…,K−1k = 0, \ldots, K-1 and use θ0=0\theta_0 = 0. ■\blacksquare

Corollary (exact reproduction). If every state x0,…,xKx_0, \ldots, x_K lies in the range of VV, for example when the snapshots are these states and r=rank⁡Sr = \operatorname{rank} S, then Vzk=xkV z_k = x_k for all kk.

Proof. Then ρk=0\rho_k = 0 for all kk. By part (2), (I−dtAr)θk+1=θk(I - dt A_r) \theta_{k+1} = \theta_k for all kk and θ0=0\theta_0 = 0. If I−dtArI - dt A_r is invertible (for example under the hypothesis of Lemma 3), induction gives θk=0\theta_k = 0, and part (1) gives xk=Vzkx_k = V z_k. □\square

Complexity

In the real RAM model, line L1 costs O(nm2)O(n m^2), an eigen solver for the symmetric mm by mm matrix costs O(m3)O(m^3) (each sweep of the Jacobi method costs O(m3)O(m^3), and a few sweeps are enough), and line L3 costs O(nmr)O(n m r). Line L4 costs O(n2r)O(n^2 r) for a dense AA and O(nr2)O(n r^2) for a banded AA such as the heat matrix. The online stage costs O(r3)O(r^3) once for the inverse and O(r2)O(r^2) per step, so O(r3+Kr2)O(r^3 + K r^2), with no dependence on nn. Each lifted state VzkV z_k costs O(nr)O(n r), and a user who needs only a few outputs, such as a mean or a point value, can lift only those. The snapshot matrix takes O(nm)O(n m) memory and the basis O(nr)O(n r).

Properties

  • Exact projection error. The error of the snapshots is the sum of the discarded eigenvalues, so the user can pick rr before running the reduced model.
  • Optimal for the snapshots. No other basis of size rr has a smaller error E(V)E(V) (a theorem, Schmidt-Eckart-Young). It is optimal for the snapshots, not for the states of a new run.
  • Stable for symmetric dissipative systems. If AA is symmetric and negative semidefinite, then so is ArA_r, and backward Euler on the reduced system does not grow (proved). If only A+AT≤0A + A^T \le 0 holds, the same argument works for the symmetric part.
  • Intrusive. Line L4 needs AA and ff, not just the outputs of the full code. Operator inference learns ArA_r from data instead.
  • Deterministic. The basis depends on the snapshots only up to the sign of each mode.

Variants and improvements

  • Direct SVD. Compute the thin SVD of SS instead of the eigenpairs of STSS^T S. This avoids squaring the condition number and gives accurate modes for small singular values.
  • A weighted inner product. For finite elements, the physical norm is ∥u∥M2=uTMu\|u\|_M^2 = u^T M u with the mass matrix MM. Then line L1 is C=STMSC = S^T M S, the modes are MM-orthonormal and the projection is VTMV^T M.
  • Mean subtraction. Subtract the mean of the snapshots, or a lifting function that carries the boundary values, and find the modes of the rest.
  • Nonlinear terms. For x′=Ax+g(x)x' = A x + g(x), the term VTg(Vz)V^T g(V z) costs O(n)O(n) per step. The discrete empirical interpolation method evaluates gg at a few points only.
  • Parameters. With snapshots at several parameter values, the same projection gives a parametric model; the reduced basis method adds an a posteriori error bound and a greedy choice of the parameters.
  • Petrov-Galerkin projection. A test basis W≠VW \ne V in line L4 (Ar=WTAVA_r = W^T A V with WTV=IW^T V = I) can restore stability for convection problems.

When to use it

Use a POD-Galerkin model when you must run the same large linear or mildly nonlinear model many times, at inputs close to those of the training runs, and you have access to the operators of the full code. The offline cost is one or more full runs, so the method pays only after many online runs. Use balanced truncation for a linear input-output system of moderate size where you want an error bound. Use operator inference or dynamic mode decomposition when you have only the outputs of the code. Use the reduced basis method when the problem has parameters and you need a certified error. Do not use POD-Galerkin for flows with moving fronts or shocks: the singular values of such snapshots decay slowly, and rr must be large.

Pitfalls

  • A Galerkin model of a stable non-normal system can be unstable. Line L4 does not keep the stability of AA unless A+AT≤0A + A^T \le 0. For A=(−140−1)A = \begin{pmatrix} -1 & 4 \\ 0 & -1 \end{pmatrix}, with both eigenvalues equal to −1-1, and v=(1,1)/2v = (1, 1)/\sqrt{2}, the reduced matrix is vTAv=1>0v^T A v = 1 > 0, and the reduced model grows.
  • Small eigenvalues in line L3. If λi\lambda_i is at the level of rounding, Swi/λiS w_i / \sqrt{\lambda_i} is mostly noise and is not orthogonal to the other modes. Choose rr below the numerical rank, or use the SVD of SS.
  • The energy rule is a rule. Choosing rr so that ∑i≤rλi/∑iλi≥99.9%\sum_{i \le r} \lambda_i / \sum_i \lambda_i \ge 99.9\% is a common rule of thumb, not a bound on the error of the reduced model. The bound depends on ∥Aρk∥\|A \rho_k\| (see the correctness section).
  • An online stage that depends on nn. If AA depends on a parameter or the model has a nonlinear term, and line L4 is done again at each step, the online cost is O(n)O(n) or more, and the reduced model is not faster. Use an affine decomposition or DEIM.
  • Extrapolation. The snapshots come from one run. A new initial value or source with shapes that the run did not contain gives a large error, with no warning.
  • The wrong inner product in line L1. On a non-uniform mesh, the Euclidean product weights small cells too little. The modes are then optimal in the wrong norm.

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.

pod_galerkin_reduced_model.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pod-galerkin-reduced-model/. The authors are listed in prov/9GPP7P.jsonl.
"""POD-Galerkin reduced-order model of x' = A x + f, with the method of snapshots and backward Euler steps."""

import math

from scimat import eye, inv, matmul, matvec, scale, sub, transpose

Matrix = list[list[float]]
Vector = list[float]


def heat_matrix(n: int) -> Matrix:
    """Return A = (n+1)^2 tridiag(1, -2, 1), the central difference form of u_xx on (0, 1) with u = 0 at both ends."""
    h2 = float((n + 1) ** 2)
    a = [[0.0] * n for _ in range(n)]
    for i in range(n):
        a[i][i] = -2.0 * h2
        if i > 0:
            a[i][i - 1] = h2
        if i < n - 1:
            a[i][i + 1] = h2
    return a


def backward_euler(a: Matrix, f: Vector, x0: Vector, dt: float, steps: int) -> list[Vector]:
    """Return the states x_0, ..., x_K of (I - dt A) x_(k+1) = x_k + dt f, with K = steps."""
    m = inv(sub(eye(len(a)), scale(dt, a)))
    xs = [list(x0)]
    for _ in range(steps):
        xs.append(matvec(m, [x + dt * g for x, g in zip(xs[-1], f)]))
    return xs


def jacobi_eigen(c: Matrix, tol: float = 1e-15, max_sweeps: int = 60) -> tuple[Vector, list[Vector]]:
    """Return the eigenvalues of the symmetric matrix c in non-increasing order and their orthonormal eigenvectors.

    Cyclic Jacobi rotations: each rotation sets one off-diagonal entry to zero.
    """
    m = len(c)
    a = [[float(x) for x in row] for row in c]
    v = [[1.0 if i == j else 0.0 for j in range(m)] for i in range(m)]
    total = sum(a[i][j] ** 2 for i in range(m) for j in range(m))
    for _ in range(max_sweeps):
        off = sum(a[i][j] ** 2 for i in range(m) for j in range(m) if i != j)
        if off <= tol * tol * total:
            break
        for p in range(m - 1):
            for q in range(p + 1, m):
                if a[p][q] == 0.0:
                    continue
                theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
                t = (1.0 if theta >= 0.0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                cs = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * cs
                for k in range(m):
                    akp, akq = a[k][p], a[k][q]
                    a[k][p] = cs * akp - sn * akq
                    a[k][q] = sn * akp + cs * akq
                for k in range(m):
                    apk, aqk = a[p][k], a[q][k]
                    a[p][k] = cs * apk - sn * aqk
                    a[q][k] = sn * apk + cs * aqk
                for k in range(m):
                    vkp, vkq = v[k][p], v[k][q]
                    v[k][p] = cs * vkp - sn * vkq
                    v[k][q] = sn * vkp + cs * vkq
    order = sorted(range(m), key=lambda i: -a[i][i])
    return [a[i][i] for i in order], [[v[k][i] for k in range(m)] for i in order]


def pod_basis(s: Matrix, r: int, rank_tol: float = 1e-13) -> tuple[Matrix, Vector]:
    """Return the n by r POD basis V of the snapshot matrix s (one column per snapshot) and all eigenvalues of S^T S.

    Raise ValueError if r < 1 or if lambda_r is not above rank_tol * lambda_1.
    """
    st = transpose(s)
    c = matmul(st, s)  # @line L1: the m by m correlation matrix C = S^T S
    lam, w = jacobi_eigen(c)  # @line L2
    if r < 1 or r > len(lam) or lam[r - 1] <= rank_tol * max(lam[0], 0.0):
        raise ValueError("r must be between 1 and the numerical rank of S")
    cols = []
    for i in range(r):  # @line L3: v_i = S w_i / sqrt(lambda_i)
        sw = matvec(s, w[i])
        cols.append([x / math.sqrt(lam[i]) for x in sw])
    return transpose(cols), lam


def pod_galerkin(a: Matrix, f: Vector, x0: Vector, dt: float, steps: int, s: Matrix, r: int) -> tuple[list[Vector], Matrix, Vector]:
    """Run the rank-r POD-Galerkin model of x' = A x + f for K = steps backward Euler steps.

    Return the lifted states V z_0, ..., V z_K, the basis V and the eigenvalues of S^T S.
    """
    v, lam = pod_basis(s, r)
    vt = transpose(v)
    ar = matmul(vt, matmul(a, v))  # @line L4: offline, A_r = V^T A V, f_r = V^T f, z_0 = V^T x_0
    fr = matvec(vt, f)
    z = matvec(vt, x0)
    mr = inv(sub(eye(r), scale(dt, ar)))  # the r by r inverse, formed once
    zs = [z]
    for _ in range(steps):  # @line L5
        z = matvec(mr, [zi + dt * gi for zi, gi in zip(z, fr)])  # @line L6
        zs.append(z)
    return [matvec(v, zk) for zk in zs], v, lam  # @line L7: lift x~_k = V z_k
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_pod_galerkin_reduced_model.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pod-galerkin-reduced-model/. The authors are listed in prov/9GPP7P.jsonl.
import math
import random

import pytest

from pod_galerkin_reduced_model import backward_euler, heat_matrix, jacobi_eigen, pod_basis, pod_galerkin
from scimat import matmul, matvec, norm2, scale, transpose


def diff(x, y):
    return [a - b for a, b in zip(x, y)]


def proj_error(states, v):
    vt = transpose(v)
    return sum(norm2(diff(x, matvec(v, matvec(vt, x)))) ** 2 for x in states)


def heat_example():
    n, dt, steps = 60, 0.002, 20
    grid = [(j + 1) / (n + 1) for j in range(n)]
    x0 = [1.0 if 0.2 <= x <= 0.4 else 0.0 for x in grid]
    f = [1.0] * n
    a = heat_matrix(n)
    return a, f, x0, dt, steps, backward_euler(a, f, x0, dt, steps)


def test_hand_example():
    s = [[1, 1], [1, 1], [1, -1]]  # snapshots (1, 1, 1) and (1, 1, -1)
    v, lam = pod_basis(s, 2)
    assert lam[0] == pytest.approx(4.0) and lam[1] == pytest.approx(2.0)
    v1 = [row[0] for row in v]
    v2 = [row[1] for row in v]
    sgn = 1.0 if v1[0] > 0 else -1.0
    assert [sgn * x for x in v1] == pytest.approx([1 / math.sqrt(2), 1 / math.sqrt(2), 0.0], abs=1e-12)
    assert [abs(x) for x in v2] == pytest.approx([0.0, 0.0, 1.0], abs=1e-12)
    a = heat_matrix(3)
    assert sum(v1[i] * matvec(a, v1)[i] for i in range(3)) == pytest.approx(-16.0)
    assert proj_error([[1, 1, 1], [1, 1, -1]], [[x] for x in v1]) == pytest.approx(2.0)


def test_jacobi_against_definition():
    rng = random.Random(7)
    m = 7
    b = [[rng.uniform(-1, 1) for _ in range(m)] for _ in range(m)]
    c = matmul(transpose(b), b)
    lam, w = jacobi_eigen(c)
    assert all(lam[i] >= lam[i + 1] for i in range(m - 1))
    for i in range(m):
        assert norm2(diff(matvec(c, w[i]), scale(lam[i], w[i]))) < 1e-10
        for j in range(m):
            assert sum(x * y for x, y in zip(w[i], w[j])) == pytest.approx(1.0 if i == j else 0.0, abs=1e-12)
    assert sum(lam) == pytest.approx(sum(c[i][i] for i in range(m)))


def test_projection_error_is_sum_of_discarded_eigenvalues():
    a, f, x0, dt, steps, full = heat_example()
    s = transpose(full)
    for r in range(1, 7):
        v, lam = pod_basis(s, r)
        vt = transpose(v)
        g = matmul(vt, v)
        for i in range(r):
            for j in range(r):
                assert g[i][j] == pytest.approx(1.0 if i == j else 0.0, abs=1e-9)
        assert proj_error(full, v) == pytest.approx(sum(lam[r:]), rel=1e-8, abs=1e-12)


def test_error_falls_as_r_grows_and_obeys_the_bound():
    a, f, x0, dt, steps, full = heat_example()
    s = transpose(full)
    errs = []
    for r in range(1, 8):
        rom, v, lam = pod_galerkin(a, f, x0, dt, steps, s, r)
        errs.append(max(norm2(diff(x, y)) for x, y in zip(full, rom)))
        # ||V^T x_K - z_K|| <= dt sum_k ||A rho_k|| with rho_k = x_k - V V^T x_k
        vt = transpose(v)
        theta = norm2(diff(matvec(vt, full[-1]), matvec(vt, rom[-1])))
        rho = [diff(x, matvec(v, matvec(vt, x))) for x in full]
        assert theta <= dt * sum(norm2(matvec(a, rk)) for rk in rho[1:]) * (1 + 1e-9) + 1e-12
    assert all(errs[i + 1] < errs[i] for i in range(len(errs) - 1))
    assert errs[0] == pytest.approx(1.8074, rel=1e-3)
    assert errs[-1] < 1e-3 * errs[0]


def test_exact_on_a_rank_two_trajectory():
    n, dt, steps = 12, 0.01, 15
    grid = [(j + 1) / (n + 1) for j in range(n)]
    x0 = [math.sin(math.pi * x) for x in grid]
    f = [3.0 * math.sin(2 * math.pi * x) for x in grid]
    a = heat_matrix(n)
    full = backward_euler(a, f, x0, dt, steps)
    rom, v, lam = pod_galerkin(a, f, x0, dt, steps, transpose(full), 2)
    assert lam[2] < 1e-12 * lam[0]
    assert max(norm2(diff(x, y)) for x, y in zip(full, rom)) < 1e-10
    with pytest.raises(ValueError):
        pod_basis(transpose(full), 3)


def test_random_snapshots_against_direct_projection():
    rng = random.Random(2025)
    for _ in range(5):
        n = rng.randint(5, 9)
        m = rng.randint(2, 5)  # m <= n, so S has rank m
        s = [[rng.gauss(0, 1) for _ in range(m)] for _ in range(n)]
        states = transpose(s)
        for r in range(1, m + 1):
            v, lam = pod_basis(s, r)
            assert proj_error(states, v) == pytest.approx(sum(lam[r:]), rel=1e-9, abs=1e-10)
        # a basis from a random orthonormal set never beats POD (Schmidt-Eckart-Young)
        q = [[rng.gauss(0, 1)] for _ in range(n)]
        nq = norm2([row[0] for row in q])
        q = [[row[0] / nq] for row in q]
        assert proj_error(states, q) >= sum(lam[1:]) - 1e-10


def test_bad_rank_is_rejected():
    s = [[1.0, 2.0], [2.0, 4.0]]  # rank one
    with pytest.raises(ValueError):
        pod_basis(s, 0)
    with pytest.raises(ValueError):
        pod_basis(s, 2)

History

The proper orthogonal decomposition is the discrete form of the Karhunen-Loeve expansion of the 1940s (Kosambi, Loeve and Karhunen). Lumley brought it to turbulence in 1967 as a way to define coherent structures. Sirovich gave the method of snapshots in 1987, which made POD practical for large simulations. Aubry, Holmes, Lumley and Stone built a Galerkin model of the turbulent wall layer on POD modes in 1988. Holmes, Lumley and Berkooz wrote the standard book in 1996, and its second edition of 2012 adds Rowley. In the 2000s, POD-Galerkin models became one of the main tools of projection-based model reduction, next to balanced truncation and the reduced basis method, as the survey of Benner, Gugercin and Willcox describes.

References

  1. Lawrence Sirovich, Turbulence and the dynamics of coherent structures. I. Coherent structures, Quarterly of Applied Mathematics 45(3), 1987, 561-571, the method of snapshots (the eigenvalue problem of the m by m correlation matrix)
  2. Philip Holmes, John L. Lumley, Gal Berkooz and Clarence W. Rowley, Turbulence, Coherent Structures, Dynamical Systems and Symmetry, 2nd edition, Cambridge University Press, 2012, the chapters on the proper orthogonal decomposition and on Galerkin projection (the 1st edition of 1996 is by Holmes, Lumley and Berkooz)
  3. Alfio Quarteroni, Andrea Manzoni and Federico Negri, Reduced Basis Methods for Partial Differential Equations, An Introduction, UNITEXT 92, Springer, 2016, Chapter 6 (construction of reduced basis spaces by SVD-POD)
  4. Peter Benner, Serkan Gugercin and Karen Willcox, A survey of projection-based model reduction methods for parametric dynamical systems, SIAM Review 57(4), 2015, 483-531, the sections on projection and on basis computation by POD

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.lift
  • 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