Module contents
Lesson 23 of 27Advanced 105 min

Reduced-order models: POD, reduced Galerkin and DMD

Calibration, uncertainty quantification and data assimilation require many simulations; reduced-order models approximate a large system with a smaller one. Build POD bases from snapshots, project equations with Galerkin, address nonlinear evaluation with DEIM and study data-driven DMD and its connection to the Koopman operator.

After this lesson you can

  • Compute a POD basis from a snapshot matrix SVD and select its dimension by captured energy.
  • Build a Galerkin ROM for a parametric linear problem using offline and online decomposition.
  • Apply DEIM so online nonlinear evaluation need not depend on the full dimension.
  • Implement exact DMD, interpret its eigenvalues and modes, and use it to predict.
  • Evaluate a ROM beyond training parameters and detect projection instabilities.

Before you start

Many problems, one basis

A ten-minute simulation repeated ten thousand times during calibration has considerable cost before accounting for analysis or data generation. A reduced-order model (ROM) attempts to amortize prior work: gather representative solutions, construct a small space and solve subsequent queries there. Reduction is useful only when preparation cost, queries and error are evaluated together.

POD and the right norm

Collect snapshots as columns of X∈Rn×s\mat X\in\mathbb R^{n\times s}. Proper orthogonal decomposition (POD) seeks an orthonormal basis Vr\mat V_r minimizing total squared error:

min⁡Vr⊤Vr=I∥X−VrVr⊤X∥F2=∑j>rσj2.\min_{\mat V_r\T\mat V_r=\mat I} \|\mat X-\mat V_r\mat V_r\T\mat X\|_F^2 =\sum_{j>r}\sigma_j^2.

The solution consists of the leading left vectors of the SVD X=UΣW⊤\mat X=\mat U\mat\Sigma\mat W\T. The fraction ∑j≤rσj2/∑jσj2\sum_{j\le r}\sigma_j^2/\sum_j\sigma_j^2 measures snapshot energy in the chosen norm; it does not guarantee accuracy at another parameter, for another output or in a future integration. With many variables and few snapshots, the method of snapshots diagonalizes X⊤X\mat X\T\mat X and recovers spatial modes, avoiding division by numerically zero singular values.

On a nonuniform FEM mesh the physical norm may be ∥u∥M2=u⊤Mu\|\vb u\|_{\mat M}^2=\vb u\T\mat M\vb u, with a positive definite mass matrix. If M=LL⊤\mat M=\mat L\mat L\T, compute the SVD of L⊤X\mat L\T\mat X and solve L⊤V=U\mat L\T\mat V=\mat U; then V⊤MV=I\mat V\T\mat M\mat V=\mat I. The projection is VV⊤M\mat V\mat V\T\mat M, not VV⊤\mat V\mat V\T in general. Whether snapshots are centered changes the problem and the meaning of energy.

InteractivePOD modes and captured energy
  • snapshot
  • POD projection

60 snapshots at 120 points. Heat: sin(πx)e⁻ᵗ+0.4 sin(2πx)e⁻⁴ᵗ. Prescribed moving profile: exp(−((x−(0.15+0.7t))/0.055)²). Bases were obtained by SVD; accumulated energy is the fraction of the sum of squared singular values, not an out-of-sample simulation error bound.

Snapshot family
2
Accumulated energy100.00 %
Relative error of this snapshot0.0000
Add modes to two explicit families and compare reconstruction with accumulated energy.

The moving profile here requires many more modes than the heat solution composed of two modes. This compares these families and does not prove a universal decay rate for Kolmogorov width. Transport and fronts often require more attention than a field dominated by a few stationary structures.

Reduced Galerkin and offline/online work

For a stationary formulation A(μ)u(μ)=f(μ)\mat A(\mu)\vb u(\mu)=\vb f(\mu), approximate u≈Vra\vb u\approx\mat V_r\vb a and require the residual to be orthogonal to the basis:

Vr⊤A(μ)Vra=Vr⊤f(μ).\mat V_r\T\mat A(\mu)\mat V_r\vb a =\mat V_r\T\vb f(\mu).

If A(μ)=∑q=1Qθq(μ)Aq\mat A(\mu)=\sum_{q=1}^{Q}\theta_q(\mu)\mat A_q, offline work computes Vr⊤AqVr\mat V_r\T\mat A_q\mat V_r and the reduced loads. Online work combines matrices of size rr and solves the reduced system without assembling the full matrix, provided the affine representation and outputs allow it. Reconstructing the full field still costs at least proportionally to nn. Reduced bases can incorporate a posteriori estimators based on residual and stability; a small residual does not imply a useful bound if the stability constant is very small.

Reduced Galerkin projection does not guarantee stability outside training. In transport or convection, scales and dissipative mechanisms can be lost; a basis that approximates snapshots well does not necessarily reproduce the dynamics. Petrov-Galerkin changes the test space and closures model effects of omitted modes. Both require out-of-sample validation.

DEIM: evaluate fewer entries

A nonlinearity f(Va)\vb f(\mat V\vb a) evaluated at all nn components destroys independence of online cost from nn. Discrete empirical interpolation constructs a basis Um\mat U_m of nonlinear snapshots and selects mm indices with an extraction matrix P\mat P:

f(Va)≈Um(P⊤Um)−1P⊤f(Va).\vb f(\mat V\vb a)\approx \mat U_m(\mat P\T\mat U_m)^{-1}\mat P\T\vb f(\mat V\vb a).

The first index maximizes the absolute value of the first mode; each subsequent index maximizes the residual of the next mode interpolated at previous indices. For orthonormal Um\mat U_m, the error is bounded by ∥(P⊤Um)−1∥2 ∥(I−UmUm⊤)f∥2\|(\mat P\T\mat U_m)^{-1}\|_2\,\|(\mat I-\mat U_m\mat U_m\T)\vb f\|_2. An ill-conditioned interpolation matrix amplifies error. If the nonlinearity is pointwise, such as ui2u_i^2, only solution values at selected indices are needed. Operators with spatial stencils may need additional neighbors.

InteractiveWhere to look with DEIM
  • nonlinearity
  • DEIM interpolant
  • evaluated points

The basis comes from squares of the moving profiles in the previous figure. The indices are greedy and the curve is calculated by solving the interpolation system. The error for one profile need not decrease at every step: oblique interpolation is not an orthogonal projection.

3
Relative interpolation error0.7980
Last grid index34
Step through the greedy indices and interpolation of a known nonlinearity.

The oblique interpolant error for a particular function does not necessarily decrease with each added point, even as the approximation space grows. Also check that the indices interpolate the basis columns and that the reduced system is nonsingular.

DMD and data-driven dynamics

Dynamic mode decomposition (DMD) fits a linear operator that advances snapshots. With X1=[x0,…,xs−2]\mat X_1=[\vb x_0,\ldots,\vb x_{s-2}], X2=[x1,…,xs−1]\mat X_2=[\vb x_1,\ldots,\vb x_{s-1}] and X1≈UrΣrWr⊤\mat X_1\approx\mat U_r\mat\Sigma_r\mat W_r\T,

A~=Ur⊤X2WrΣr−1,A~wj=λjwj,ϕj=X2WrΣr−1wj.\widetilde{\mat A}=\mat U_r\T\mat X_2\mat W_r\mat\Sigma_r^{-1},\qquad \widetilde{\mat A}\vb w_j=\lambda_j\vb w_j,\qquad \vb\phi_j=\mat X_2\mat W_r\mat\Sigma_r^{-1}\vb w_j.

These are exact DMD modes for the truncated fit; amplitudes are fitted to the first snapshot and prediction uses ∑jbjϕjλjk\sum_j b_j\vb\phi_j\lambda_j^k. Only singular values well separated from zero are inverted. For interval Δt\Delta t, ωj=log⁡(λj)/Δt\omega_j=\log(\lambda_j)/\Delta t has a real growth part and imaginary angular-frequency part. The complex logarithm has branches: discrete sampling introduces aliasing, so frequency is not unique without additional assumptions.

InteractiveDMD spectrum
  • |λ| ≤ 1
  • |λ| > 1
  • unit circle

Two discrete oscillators at frequencies 0.24 and 0.52 rad/step; the second decays by a factor of exp(−0.003) per step. There are 100 samples and Gaussian noise with seed 131, the same realization scaled at each level. Size indicates amplitude computed with this mode normalization. In this example noise pushes magnitudes inward; this is not a law for all data.

DMD rank
0
Noise deviation0.00
Reconstruction error0.000
Largest magnitude1.0000
Observe the unit circle, relative amplitude and effect of noise in a reproducible example.

The Koopman perspective applies a linear operator to observables of a dynamical system, even if the state dynamics are nonlinear. In general this operator lives in an infinite-dimensional space and DMD is a finite approximation dependent on observables and data. EDMD expands the dictionary; DMD with control jointly fits the effects of state and inputs. Neither guarantees identification outside observed regimes.

Lab: reaction–diffusion, POD-DEIM and DMD

Consider ∂tu=D∂xxu+μu(1−u)\partial_t u=D\partial_{xx}u+\mu u(1-u) on 0<x<10<x<1, with endpoints fixed at zero. We use finite differences, D=0.001D=0.001, 400 interior nodes, explicit Euler and step 0.002; the initial condition is a prescribed bell. The diffusive stability condition DΔt/Δx2≤1/2D\Delta t/\Delta x^2\le 1/2 is checked, although the reaction term and stability of the complete scheme also need attention. Offline bases use parameters 1, 2 and 3; we test unseen 2.5 and 4 outside that interval.

The ROM projects the affine linear part in μ\mu and uses DEIM for u2u^2. Each integration ends by reconstructing full snapshots; that reconstruction costs O(nr)O(nr) per output, although reduced pointwise nonlinear evaluation does not traverse all nn nodes. We also compare with a ROM evaluating the full nonlinearity and with DMD fitted to the first part of the same trajectory. Times for this small mesh and environment are measurements, not promises of speedup.

[ ]POD, DEIM, Galerkin and DMD from scratchBrowser
"""POD-Galerkin, DEIM y DMD para reacción-difusión 1D."""
import time
import numpy as np
from scipy.linalg import solve_triangular


def laplacian(u,dx):
    out=-2*u.copy()
    out[1:]+=u[:-1]
    out[:-1]+=u[1:]
    return out/dx**2


def initial_profile(n):
    x=np.arange(1,n+1)/(n+1)
    return .8*np.exp(-((x-.3)/.1)**2)


def full_sim(mu,n=400,diffusion=.001,dt=.002,steps=1000,stride=20):
    """Euler explícito; fronteras homogéneas y estado inicial común."""
    dx=1/(n+1)
    if diffusion*dt/dx**2>.5:raise ValueError('Paso difusivo fuera del límite explícito')
    u=initial_profile(n);snapshots=[u.copy()]
    for k in range(steps):
        u=u+dt*(diffusion*laplacian(u,dx)+mu*u*(1-u))
        if (k+1)%stride==0:snapshots.append(u.copy())
    return np.column_stack(snapshots)


def pod(X,r,mass=None):
    """Minimiza el error de proyección con producto de masa opcional."""
    if mass is None:
        U,s,_=np.linalg.svd(X,full_matrices=False)
        return U[:,:r],s
    L=np.linalg.cholesky(mass)
    U,s,_=np.linalg.svd(L.T@X,full_matrices=False)
    V=solve_triangular(L.T,U[:,:r],lower=False)
    return V,s


def deim_indices(U):
    """Selección voraz DEIM para columnas linealmente independientes."""
    ids=[int(np.argmax(abs(U[:,0])))]
    for k in range(1,U.shape[1]):
        coeff=np.linalg.solve(U[ids,:k],U[ids,k])
        residual=U[:,k]-U[:,:k]@coeff
        ids.append(int(np.argmax(abs(residual))))
    return np.array(ids)


def offline(training=(1.,2.,3.),n=400,r=8,m=10):
    snapshots=[full_sim(mu,n=n) for mu in training]
    X=np.column_stack(snapshots);V,s=pod(X,r)
    U,sf=pod(X**2,m);ids=deim_indices(U)
    dx=1/(n+1);A=V.T@laplacian(V,dx)
    # Resolver PᵀU evita invertir explícitamente la matriz de interpolación.
    C=np.linalg.solve(U[ids,:].T,(V.T@U).T).T
    return {'V':V,'U':U,'ids':ids,'A':A,'C':C,'sampleV':V[ids,:],
            'singular':s,'singular_nonlinear':sf,'snapshots':snapshots}


def rom_sim(mu,model,dt=.002,steps=1000,stride=20,diffusion=.001,use_deim=True):
    V=model['V'];a=V.T@initial_profile(V.shape[0]);snapshots=[a.copy()]
    A=diffusion*model['A']+mu*np.eye(V.shape[1])
    for k in range(steps):
        if use_deim:
            nonlin=model['C']@(model['sampleV']@a)**2
        else:
            nonlin=V.T@(V@a)**2
        a=a+dt*(A@a-mu*nonlin)
        if (k+1)%stride==0:snapshots.append(a.copy())
    return [email protected]_stack(snapshots)


def exact_dmd(X,rank):
    X1=X[:,:-1];X2=X[:,1:]
    U,s,Vh=np.linalg.svd(X1,full_matrices=False)
    if rank>len(s) or s[rank-1]<1e-12*s[0]:
        raise ValueError('Rango superior al rango numérico')
    U=U[:,:rank];s=s[:rank];V=Vh[:rank].T
    projected=(U.T@X2@V)/s
    values,W=np.linalg.eig(projected)
    modes=((X2@V)/s)@W
    amplitudes=np.linalg.lstsq(modes,X[:,0],rcond=None)[0]
    return values,modes,amplitudes


def dmd_reconstruct(values,modes,amplitudes,steps):
    return (modes@(amplitudes[:,None]*values[:,None]**np.arange(steps)[None,:])).real


def relative_error(a,b):
    return np.linalg.norm(a-b)/np.linalg.norm(a)
[ ]Offline constructionBrowser
start=time.perf_counter()
model=offline()
print('Preparación offline (s):',time.perf_counter()-start)
print('Primeros valores singulares:',model['singular'][:10])
print('Índices DEIM:',model['ids'])
print('Condición de PᵀU:',np.linalg.cond(model['U'][model['ids']]))
[ ]POD with mass matrixBrowser
rng=np.random.default_rng(99)
X=rng.normal(size=(12,9));M=np.diag(np.linspace(.4,2,12))
V,s=pod(X,4,M);L=np.linalg.cholesky(M)
error=np.linalg.norm(L.T@(X-V@(V.T@M@X)))**2
print('Error de ortonormalidad:',np.max(abs(V.T@[email protected](4))))
print('Error ponderado cuadrado y cola singular:',error,np.sum(s[4:]**2))
assert np.allclose(V.T@M@V,np.eye(4))
assert np.isclose(error,np.sum(s[4:]**2))
[ ]Compare unseen parametersBrowser
for mu in [1.,2.5,4.]:
    truth=full_sim(mu);reduced=rom_sim(mu,model)
    print('μ, error relativo de instantáneas:',mu,relative_error(truth,reduced))
[ ]Verify DEIM interpolation and boundBrowser
truth=full_sim(2.5);U=model['U'];ids=model['ids'];f=truth[:,-1]**2
projection=U@(U.T@f);[email protected](U[ids,:],f[ids])
constant=np.linalg.norm(np.linalg.inv(U[ids,:]),2)
err=np.linalg.norm(f-interpolant);bound=constant*np.linalg.norm(f-projection)
print('Error DEIM y cota:',err,bound)
print('Error en índices:',np.max(abs(interpolant[ids]-f[ids])))
assert err<=bound*(1+1e-10)
[ ]Time the integrationsBrowser
timings={}
for label,fn in [('completo',lambda:full_sim(2.5)),
                 ('ROM con DEIM',lambda:rom_sim(2.5,model)),
                 ('ROM sin DEIM',lambda:rom_sim(2.5,model,use_deim=False))]:
    samples=[]
    for _ in range(5):
        start=time.perf_counter();fn();samples.append(time.perf_counter()-start)
    timings[label]=float(np.median(samples))
print('Medianas (s):',timings)
print('Ratio completo/DEIM:',timings['completo']/timings['ROM con DEIM'])
[ ]DMD fitted on a window and predictionBrowser
truth=full_sim(2.5);train=truth[:,:31]
values,modes,amplitudes=exact_dmd(train,4)
pred=dmd_reconstruct(values,modes,amplitudes,truth.shape[1])
print('Autovalores discretos:',values)
print('Error relativo de entrenamiento:',relative_error(train,pred[:,:31]))
print('Error relativo total, incluida extrapolación temporal:',relative_error(truth,pred))
print('Tasas continuas:',np.log(values)/(20*.002))

In the reference run POD-DEIM relative errors for μ=1\mu=1, 2.52.5 and 44 are approximately 0.000109, 0.000182 and 0.00620, respectively, over all snapshots. Rank-4 DMD gives about 0.00110 in its fitting window and 0.0420 over the entire trajectory; these are different errors measured on different sets. Times vary across environments and exclude offline basis preparation.

The local cell uses PyDMD with identical rank and exact mode, matches eigenvalues by distance and compares reconstruction over the training window. PyDMD may warn that the full snapshot matrix is very ill-conditioned: here we truncate to rank 4 and check the result, but this does not remove the need to examine the spectrum. PyDMD, NumPy and SciPy must be installed in the local environment.

[ ]Comparison with PyDMDLocal GPU
"""POD-Galerkin, DEIM y DMD para reacción-difusión 1D."""
import time
import numpy as np
from scipy.linalg import solve_triangular


def laplacian(u,dx):
    out=-2*u.copy()
    out[1:]+=u[:-1]
    out[:-1]+=u[1:]
    return out/dx**2


def initial_profile(n):
    x=np.arange(1,n+1)/(n+1)
    return .8*np.exp(-((x-.3)/.1)**2)


def full_sim(mu,n=400,diffusion=.001,dt=.002,steps=1000,stride=20):
    """Euler explícito; fronteras homogéneas y estado inicial común."""
    dx=1/(n+1)
    if diffusion*dt/dx**2>.5:raise ValueError('Paso difusivo fuera del límite explícito')
    u=initial_profile(n);snapshots=[u.copy()]
    for k in range(steps):
        u=u+dt*(diffusion*laplacian(u,dx)+mu*u*(1-u))
        if (k+1)%stride==0:snapshots.append(u.copy())
    return np.column_stack(snapshots)


def pod(X,r,mass=None):
    """Minimiza el error de proyección con producto de masa opcional."""
    if mass is None:
        U,s,_=np.linalg.svd(X,full_matrices=False)
        return U[:,:r],s
    L=np.linalg.cholesky(mass)
    U,s,_=np.linalg.svd(L.T@X,full_matrices=False)
    V=solve_triangular(L.T,U[:,:r],lower=False)
    return V,s


def deim_indices(U):
    """Selección voraz DEIM para columnas linealmente independientes."""
    ids=[int(np.argmax(abs(U[:,0])))]
    for k in range(1,U.shape[1]):
        coeff=np.linalg.solve(U[ids,:k],U[ids,k])
        residual=U[:,k]-U[:,:k]@coeff
        ids.append(int(np.argmax(abs(residual))))
    return np.array(ids)


def offline(training=(1.,2.,3.),n=400,r=8,m=10):
    snapshots=[full_sim(mu,n=n) for mu in training]
    X=np.column_stack(snapshots);V,s=pod(X,r)
    U,sf=pod(X**2,m);ids=deim_indices(U)
    dx=1/(n+1);A=V.T@laplacian(V,dx)
    # Resolver PᵀU evita invertir explícitamente la matriz de interpolación.
    C=np.linalg.solve(U[ids,:].T,(V.T@U).T).T
    return {'V':V,'U':U,'ids':ids,'A':A,'C':C,'sampleV':V[ids,:],
            'singular':s,'singular_nonlinear':sf,'snapshots':snapshots}


def rom_sim(mu,model,dt=.002,steps=1000,stride=20,diffusion=.001,use_deim=True):
    V=model['V'];a=V.T@initial_profile(V.shape[0]);snapshots=[a.copy()]
    A=diffusion*model['A']+mu*np.eye(V.shape[1])
    for k in range(steps):
        if use_deim:
            nonlin=model['C']@(model['sampleV']@a)**2
        else:
            nonlin=V.T@(V@a)**2
        a=a+dt*(A@a-mu*nonlin)
        if (k+1)%stride==0:snapshots.append(a.copy())
    return [email protected]_stack(snapshots)


def exact_dmd(X,rank):
    X1=X[:,:-1];X2=X[:,1:]
    U,s,Vh=np.linalg.svd(X1,full_matrices=False)
    if rank>len(s) or s[rank-1]<1e-12*s[0]:
        raise ValueError('Rango superior al rango numérico')
    U=U[:,:rank];s=s[:rank];V=Vh[:rank].T
    projected=(U.T@X2@V)/s
    values,W=np.linalg.eig(projected)
    modes=((X2@V)/s)@W
    amplitudes=np.linalg.lstsq(modes,X[:,0],rcond=None)[0]
    return values,modes,amplitudes


def dmd_reconstruct(values,modes,amplitudes,steps):
    return (modes@(amplitudes[:,None]*values[:,None]**np.arange(steps)[None,:])).real


def relative_error(a,b):
    return np.linalg.norm(a-b)/np.linalg.norm(a)

from pydmd import DMD
from scipy.optimize import linear_sum_assignment
X=full_sim(2.5)[:,:31]
values,modes,amplitudes=exact_dmd(X,4)
lib=DMD(svd_rank=4,exact=True).fit(X)
rows,cols=linear_sum_assignment(abs(values[:,None]-lib.eigs[None,:]))
print('Máxima discrepancia de autovalores:',np.max(abs(values[rows]-lib.eigs[cols])))
ours=dmd_reconstruct(values,modes,amplitudes,X.shape[1])
print('Discrepancia relativa de reconstrucción:',np.linalg.norm(ours-lib.reconstructed_data.real)/np.linalg.norm(X))
assert np.allclose(values[rows],lib.eigs[cols],rtol=1e-7,atol=1e-8)
assert np.linalg.norm(ours-lib.reconstructed_data.real)/np.linalg.norm(X)<1e-7
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofPOD optimality
Prove: Prove the formula for minimum rank-r projection error.
0
X=UΣWᵀ and V has r orthonormal columns.

Step 1 of 3. What class of matrices contains the reconstruction VVᵀX?

Numeric
If λ=0.9e^{0.2i} and Δt=0.1, what is the continuous growth rate on the principal branch?
Numeric
With λ=0.9e^{0.2i} and Δt=0.1, what is the frequency in cycles per unit time on the principal branch?
Quiz
Why can a ROM accurate in training be unstable out of sample in convective flow?
CodeGreedy DEIM selection
Implement deim_indices(U), where U has orthonormal columns and at least one column. Return the distinct greedy indices: first the absolute maximum of the first mode, then the maximum residual from interpolating each new mode at previous indices.
import numpy as np
def deim_indices(U):
  # U contiene columnas ortonormales.
  return []
Shift+Enter to run
Key idea
A POD basis reduces the representation; Galerkin and DEIM reduce dynamical work under specific assumptions. DMD learns an approximate linear evolution from data and also requires out-of-sample validation.

References