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 . Proper orthogonal decomposition (POD) seeks an orthonormal basis minimizing total squared error:
The solution consists of the leading left vectors of the SVD . The fraction 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 and recovers spatial modes, avoiding division by numerically zero singular values.
On a nonuniform FEM mesh the physical norm may be , with a positive definite mass matrix. If , compute the SVD of and solve ; then . The projection is , not in general. Whether snapshots are centered changes the problem and the meaning of 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 , approximate and require the residual to be orthogonal to the basis:
If , offline work computes and the reduced loads. Online work combines matrices of size 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 . 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 evaluated at all components destroys independence of online cost from . Discrete empirical interpolation constructs a basis of nonlinear snapshots and selects indices with an extraction matrix :
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 , the error is bounded by . An ill-conditioned interpolation matrix amplifies error. If the nonlinearity is pointwise, such as , only solution values at selected indices are needed. Operators with spatial stencils may need additional neighbors.
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 , and ,
These are exact DMD modes for the truncated fit; amplitudes are fitted to the first snapshot and prediction uses . Only singular values well separated from zero are inverted. For interval , 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.
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 on , with endpoints fixed at zero. We use finite differences, , 400 interior nodes, explicit Euler and step 0.002; the initial condition is a prescribed bell. The diffusive stability condition 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 and uses DEIM for . Each integration ends by reconstructing full snapshots; that reconstruction costs per output, although reduced pointwise nonlinear evaluation does not traverse all 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-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)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']]))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))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))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)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'])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 , and 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.
"""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-7npm run lab and open the connection link.Exercises
Step 1 of 3. What class of matrices contains the reconstruction VVᵀX?
import numpy as np
def deim_indices(U):
# U contiene columnas ortonormales.
return []