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
- Model
- Real RAM
- Properties
- deterministicnot exactintrusivenot iterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- John L. Lumley, Lawrence Sirovich, Philip Holmes, Gal Berkooz, 1987
A POD-Galerkin reduced-order model replaces a large linear system of ODEs with unknowns by a system with unknowns, where is much smaller than . It runs the full model once and stores the states as snapshots. It takes the leading proper orthogonal decomposition (POD) modes of the snapshots as an orthonormal basis . 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 (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 unknowns instead of . 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 with a constant by matrix , a constant vector and an initial value . It is stepped with the backward Euler method with step :
The snapshot matrix has columns , one per stored state; in the example they are the states of a training run, so . For , the POD basis of size is an by matrix with orthonormal columns that minimizes the projection error
The output is the reduced trajectory , where solves the Galerkin reduced system: the full equation with , multiplied by . This page writes for the reduced size and for the full size. The books of Hesthaven, Rozza and Stamm and of Quarteroni, Manzoni and Negri write for the reduced size and or for the full size.
The algorithm
POD-GALERKIN(A, f, x_0, dt, K, S, r)- 1
C ← S^T S ▷ m by m correlation matrix - 2
(λ_i, w_i) ← eigenpairs of C, λ_1 ≥ λ_2 ≥ ... ≥ λ_m ≥ 0, with orthonormal w_i - 3
v_i ← S w_i / sqrt(λ_i) for i = 1..r; V ← [v_1 ... v_r] - 4
A_r ← V^T A V; f_r ← V^T f; z_0 ← V^T x_0 ▷ offline stage - 5
for k = 0 to K - 1 do ▷ online stage - 6
z_(k+1) ← (I - dt A_r)^(-1) (z_k + dt f_r) - 7
return 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 , not , which is cheap when there are fewer snapshots than unknowns. Line L2 needs ; the implementation raises an error otherwise, and it finds the eigenpairs with the Jacobi eigenvalue algorithm. Line L3 maps each eigenvector of back to a mode in ; the division by 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 apart from the last line. Lines L5 and L6 are backward Euler on the reduced system; the implementation forms the by 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 to project the ODE first and then step it, or to step it first and then project.
Example
A hand example. Take , two snapshots and , the matrix of the heat equation on three interior points with , and .
| line | result |
|---|---|
| L1 | |
| L2 | , ; , |
| L3 | |
| L4 | , so |
The projection error with is , which is , as the correctness section says. With the second mode is , the two modes span both snapshots, and the error is 0. One online step with , and gives and , so . The full step gives ; one mode cannot hold the third component.
A measurement. The full model is the heat equation on with at both ends and a source , on interior points (), with and steps. The initial value is 1 at the 12 grid points in 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.
| measured | ||||
|---|---|---|---|---|
| 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 | |||
| 5 | ||||
| 6 | ||||
| 7 |
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 , where the step in the initial value is hardest to represent. Seven modes give an error of against . 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 from line L3 are orthonormal. Second, the projection error of the snapshots is exactly , the sum of the discarded squared singular values of . Third, if is symmetric and negative semidefinite, as for the heat equation, the matrix in line L6 is invertible for every and its inverse has norm at most 1. Fourth, with , the error of the reduced model obeys
So if every state of the run lies in the span of , the reduced model reproduces the run exactly. The proof that minimizes 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 , not , so a small projection error can still give a large reduced model error when 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. is an by real matrix with columns , and (line L1). is symmetric and positive semidefinite, so it has orthonormal eigenvectors with eigenvalues (line L2). Let with , and let for (line L3). For each with we define in the same way, and .
Lemma 1 (orthonormal modes). For with , . For , .
Proof. , because the are orthonormal. If , then .
Lemma 2 (the projection error). .
Proof. Let , an orthogonal matrix. Then . By Lemma 1 the terms with vanish, so
By Lemma 1, for and for with . Hence and . 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 are orthonormal in the Frobenius inner product, because . So the squared norm is .
The formula is a singular value decomposition of , with singular values . So Lemma 2 says that the error is the sum of the discarded . That no other by matrix with orthonormal columns gives a smaller error is the Schmidt-Eckart-Young theorem, which we do not prove here.
Now let be an by matrix, and . The full states satisfy . Line L4 sets , and , and line L6 sets .
Lemma 3 (stability). If is negative semidefinite, then for every , . So is invertible and .
Proof. , so . Then
A matrix with this property has a zero kernel, so it is invertible, and follows with .
A symmetric negative semidefinite , such as the central difference matrix of with zero boundary values, satisfies the hypothesis.
Theorem (the error of the reduced model). Let and . Then
- for each ;
- , with ;
- if is negative semidefinite, .
Proof. (1) . The vector is orthogonal to the range of , because , and . The claim is the theorem of Pythagoras.
(2) Multiply the full step by : . Write , so . This gives
Subtract the reduced step of line L6. by line L4.
(3) By (2) and Lemma 3, , because for a matrix with orthonormal columns. Sum over and use .
Corollary (exact reproduction). If every state lies in the range of , for example when the snapshots are these states and , then for all .
Proof. Then for all . By part (2), for all and . If is invertible (for example under the hypothesis of Lemma 3), induction gives , and part (1) gives .
Complexity
In the real RAM model, line L1 costs , an eigen solver for the symmetric by matrix costs (each sweep of the Jacobi method costs , and a few sweeps are enough), and line L3 costs . Line L4 costs for a dense and for a banded such as the heat matrix. The online stage costs once for the inverse and per step, so , with no dependence on . Each lifted state costs , 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 memory and the basis .
Properties
- Exact projection error. The error of the snapshots is the sum of the discarded eigenvalues, so the user can pick before running the reduced model.
- Optimal for the snapshots. No other basis of size has a smaller error (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 is symmetric and negative semidefinite, then so is , and backward Euler on the reduced system does not grow (proved). If only holds, the same argument works for the symmetric part.
- Intrusive. Line L4 needs and , not just the outputs of the full code. Operator inference learns 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 instead of the eigenpairs of . 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 with the mass matrix . Then line L1 is , the modes are -orthonormal and the projection is .
- 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 , the term costs per step. The discrete empirical interpolation method evaluates 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 in line L4 ( with ) 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 must be large.
Pitfalls
- A Galerkin model of a stable non-normal system can be unstable. Line L4 does not keep the stability of unless . For , with both eigenvalues equal to , and , the reduced matrix is , and the reduced model grows.
- Small eigenvalues in line L3. If is at the level of rounding, is mostly noise and is not orthogonal to the other modes. Choose below the numerical rank, or use the SVD of .
- The energy rule is a rule. Choosing so that is a common rule of thumb, not a bound on the error of the reduced model. The bound depends on (see the correctness section).
- An online stage that depends on . If depends on a parameter or the model has a nonlinear term, and line L4 is done again at each step, the online cost is 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.
# 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
- 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)
- 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)
- 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)
- 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.
| 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 9GPP7P Edit this page History Report an error Markdown