Algorithm Search⌘K

Algorithmresearch

Operator inference

Learns the matrices of a polynomial reduced model by least squares on projected snapshot data, with no access to the full model code.

Time
O(n^2 K + n^3 + K C + K r^4) offlineO(r^3) online
Space
O(n K + K r^2) extra
Where
C = the cost of one step of the full model; K = the total number of snapshots; n = the number of full unknowns; r = the reduced size
Properties
deterministicnot exactnot intrusivenot iterative
Origin
Benjamin Peherstorfer, Karen Willcox, 2016

Operator inference (OpInf) builds a reduced model of a dynamical system from data, when the code of the full model cannot be changed or read. It assumes that the full model has a known polynomial form, for example a linear term and a quadratic term, as many discretized PDEs do. Then the POD-Galerkin reduced model has the same form, with small matrices A^\hat{A} and H^\hat{H}. The intrusive way computes them as VTAVV^T A V and a projected tensor, which needs the full matrices. OpInf computes a POD basis VV from snapshots, projects the snapshots to reduced states a^k=VTxk\hat{a}_k = V^T x_k, and fits A^\hat{A} and H^\hat{H} by linear least squares so that the reduced states follow the reduced model. With plain projected data, the fit includes a closure error, and the learned model differs from the intrusive one. With re-projected data, each reduced state is the projection of one full step from the lifted previous state, and then the least squares problem has the intrusive model as its exact solution, if the data matrix has full column rank.

Dynamic mode decomposition also fits a matrix to projected snapshot pairs, but only a linear one, with no assumed structure. OpInf is the same kind of fit with the polynomial terms that the physics gives. SINDy chooses a few terms from a large library by sparse regression, often in the original variables, to discover the form of the equations. OpInf knows the form and fits all its terms in the reduced variables. The proper generalized decomposition is intrusive: it builds a separated solution from the operator itself and learns nothing from data.

In plain words

You have a simulator that you can run but not open. You know that its equations have a linear part and a quadratic part. You run it, keep the states, and find a few patterns that describe them, by POD. Then you write each state as a mix of the patterns, and you ask: which small linear and quadratic rule moves one mix to the next? This is a least squares fit of a few numbers. The result is a small model of the same type that a code developer would get by projecting the equations, and with the right data it is exactly that model.

The problem

The full model is a time-discrete system xk+1=f(xk)x_{k+1} = f(x_k) with xk∈Rnx_k \in \mathbb{R}^n and

f(x)=Ax+H(x⊗x)f(x) = A x + H (x \otimes x)

for unknown matrices AA and HH. The user can only evaluate ff. Given initial states and a reduced size rr, the output is a reduced model

ak+1=A^ak+H^s(ak),s(a)=(aiaj)1≤i≤j≤r∈Rr(r+1)/2,a_{k+1} = \hat{A} a_k + \hat{H} s(a_k), \qquad s(a) = (a_i a_j)_{1 \le i \le j \le r} \in \mathbb{R}^{r(r+1)/2},

where A^∈Rr×r\hat{A} \in \mathbb{R}^{r \times r}, H^∈Rr×r(r+1)/2\hat{H} \in \mathbb{R}^{r \times r(r+1)/2}, and VakV a_k approximates xkx_k for an n×rn \times r basis VV with orthonormal columns. The intrusive reduced model, the reference, is the Galerkin projection ak+1=VTf(Vak)a_{k+1} = V^T f(V a_k). It has the same form, since VTf(Va)V^T f(V a) is a quadratic polynomial in aa with no constant term. The vector s(a)s(a) keeps each product aiaja_i a_j once, so the coefficients of the quadratic part are unique.

The model problem of the example is the viscous Burgers equation ut+(u2/2)x=νuxxu_t + (u^2/2)_x = \nu u_{xx} on (0,1)(0, 1) with u=0u = 0 at both ends and ν=0.05\nu = 0.05, with central differences on n=32n = 32 interior points (h=1/33h = 1/33) and explicit Euler steps with Δt=0.002\Delta t = 0.002. So f(x)=x+Δt(Lx+Q(x))f(x) = x + \Delta t (L x + Q(x)), where LL is the scaled second difference and Q(x)i=−(xi+12−xi−12)/(4h)Q(x)_i = -(x_{i+1}^2 - x_{i-1}^2)/(4h).

The algorithm

  1. OPERATOR-INFERENCE(black-box step f, initial states, K, r)
  2. 1V ← the r leading POD modes of the snapshots x_0..x_K of each trajectory
  3. 2â_k ← re-projected states: â_0 = V^T x_0, â_(k+1) = V^T f(V â_k); or projected states â_k = V^T x_k
  4. 3D ← the matrix with a row [â_k^T, s(â_k)^T] for each k < K of each trajectory
  5. 4R ← the matrix with the matching rows â_(k+1)^T
  6. 5O ← the minimizer of ‖D O - R‖_F, by a QR factorization of D
  7. 6[Â Ĥ] ← O^T
  8. 7return the reduced model a_(k+1) = Â a_k + Ĥ s(a_k)

Line L1 runs the full model and takes the POD basis of all snapshots, as for an intrusive reduced model. Line L2 has two choices. Projected states need no extra runs. Re-projected states need KK more calls of ff per trajectory, each started from the lifted reduced state Va^kV \hat{a}_k. Lines L3 and L4 set up a linear least squares problem with r+r(r+1)/2r + r(r+1)/2 unknowns per row of OTO^T; the rr columns of OO share the matrix DD. Line L5 solves it with a QR factorization of DD, here by modified Gram-Schmidt with two passes, which is more stable than the normal equations. The online stage, one step of the reduced model, costs O(r3)O(r^3).

Example

By hand. Take r=1r = 1 and a full model whose reduced step is ak+1=0.5ak+0.25ak2a_{k+1} = 0.5 a_k + 0.25 a_k^2. The data a^0=1\hat{a}_0 = 1, a^1=0.75\hat{a}_1 = 0.75, a^2=0.515625\hat{a}_2 = 0.515625 give D=(110.750.5625)D = \begin{pmatrix} 1 & 1 \\ 0.75 & 0.5625 \end{pmatrix} and R=(0.75,0.515625)TR = (0.75, 0.515625)^T. DD is invertible (det⁡D=−0.1875\det D = -0.1875), so the least squares solution is the solution of DO=RD O = R: A^=0.5\hat{A} = 0.5 and H^=0.25\hat{H} = 0.25, the model that made the data.

Burgers. Three trajectories of K=200K = 200 steps start from sin⁡(πx)\sin(\pi x), 0.8sin⁡(2πx)+0.3sin⁡(πx)0.8 \sin(2\pi x) + 0.3 \sin(\pi x) and 2x(1−x)(1+x)2x(1 - x)(1 + x). The singular values of the 603 snapshots are 66.3, 33.6, 4.28, 2.77, 0.723 and 0.206. The table is a measurement from the test file and a scratch run. "Difference" is the largest entry of the learned [A^,H^][\hat{A}, \hat{H}] minus the intrusive one. The errors are max⁡k∥xk−Vak∥2/max⁡k∥xk∥2\max_k \|x_k - V a_k\|_2 / \max_k \|x_k\|_2 along the first training trajectory and along a test trajectory from 0.6sin⁡(πx)+0.4sin⁡(3πx)0.6 \sin(\pi x) + 0.4 \sin(3\pi x).

rr difference, re-projected difference, projected training error, re-projected training error, projected test error, re-projected test error, projected
3 5.1×10−155.1 \times 10^{-15} 6.2×10−36.2 \times 10^{-3} 5.63×10−25.63 \times 10^{-2} 5.63×10−25.63 \times 10^{-2} 0.124 0.168
4 5.8×10−145.8 \times 10^{-14} 7.7×10−37.7 \times 10^{-3} 1.13×10−21.13 \times 10^{-2} 1.05×10−21.05 \times 10^{-2} 0.102 0.558
5 3.8×10−123.8 \times 10^{-12} 2.6×10−22.6 \times 10^{-2} 3.52×10−33.52 \times 10^{-3} 3.37×10−33.37 \times 10^{-3} 0.0874 overflow
6 8.0×10−118.0 \times 10^{-11} 0.27 2.25×10−32.25 \times 10^{-3} 2.17×10−32.17 \times 10^{-3} 0.0142 0.273

With re-projection the learned model is the intrusive model up to rounding, which grows with the condition number of DD: 4.3×1044.3 \times 10^4 for r=4r = 4 and 1.4×1081.4 \times 10^8 for r=6r = 6. With projected data the fit is a little better on the training trajectory, because it fits that data, but on the test trajectory it is worse, and for r=5r = 5 it blows up. With only the first trajectory, DD is numerically rank deficient for r≥4r \ge 4, and even re-projection does not recover the intrusive model: the difference is 6.9 for r=6r = 6.

Correctness

The proof file shows three facts, in exact arithmetic. First, the intrusive reduced step VTf(Va)V^T f(V a) equals A^inta+H^ints(a)\hat{A}_{int} a + \hat{H}_{int} s(a) for unique matrices, because ff is a quadratic polynomial with f(0)=0f(0) = 0. Second, line L5 returns the unique minimizer of ∥DO−R∥F\|D O - R\|_F when DD has full column rank, and the QR solution equals the solution of the normal equations. Third, the recovery theorem: if the states come from re-projection, then R=DOintR = D O_{int} with OintT=[A^int,H^int]O_{int}^T = [\hat{A}_{int}, \hat{H}_{int}], so the residual at OintO_{int} is 0, and by uniqueness line L5 returns the intrusive model. With projected states, the row kk of RR is VTf(xk)V^T f(x_k), not VTf(VVTxk)V^T f(V V^T x_k), so R=DOint+ER = D O_{int} + E with a closure error EE that is not 0 in general, and the learned model is the intrusive model plus D+ED^+ E.

Proof: With re-projected data and a data matrix of full column rank, operator inference returns the intrusive POD-Galerkin reduced modelfull

We assume exact arithmetic. The full step is f(x)=Ax+H(x⊗x)f(x) = A x + H(x \otimes x) with x∈Rnx \in \mathbb{R}^n, V∈Rn×rV \in \mathbb{R}^{n \times r} has orthonormal columns, and s(a)=(aiaj)i≤js(a) = (a_i a_j)_{i \le j} has q=r(r+1)/2q = r(r+1)/2 entries. Let p=r+qp = r + q.

Lemma 1 (the intrusive model has the assumed form). There are unique matrices A^int∈Rr×r\hat{A}_{int} \in \mathbb{R}^{r \times r} and H^int∈Rr×q\hat{H}_{int} \in \mathbb{R}^{r \times q} with VTf(Va)=A^inta+H^ints(a)V^T f(V a) = \hat{A}_{int} a + \hat{H}_{int} s(a) for all a∈Rra \in \mathbb{R}^r.

Proof. VTf(Va)=VTAVa+VTH(Va⊗Va)V^T f(V a) = V^T A V a + V^T H (V a \otimes V a). The first part is linear in aa. Each entry of Va⊗VaV a \otimes V a is ∑i,jVkiVljaiaj\sum_{i, j} V_{ki} V_{lj} a_i a_j, a quadratic form in aa; collect the terms aiaja_i a_j and ajaia_j a_i for i<ji < j into one coefficient. This gives the form with A^int=VTAV\hat{A}_{int} = V^T A V. For uniqueness, a polynomial Ba+Cs(a)B a + C s(a) that is 0 for all aa has all coefficients 0, because the monomials aia_i and aiaja_i a_j with i≤ji \le j are linearly independent functions. □\square

The implementation reads off the same matrices with ff only. Since f(−x)=−Ax+H(x⊗x)f(-x) = -A x + H(x \otimes x), the odd part (f(x)−f(−x))/2(f(x) - f(-x))/2 is AxA x and the even part (f(x)+f(−x))/2(f(x) + f(-x))/2 is H(x⊗x)H(x \otimes x). The column jj of A^int\hat{A}_{int} is VTV^T times the odd part at vjv_j. For i<ji < j the even part QQ gives Q(vi+vj)−Q(vi)−Q(vj)=H(vi⊗vj+vj⊗vi)Q(v_i + v_j) - Q(v_i) - Q(v_j) = H(v_i \otimes v_j + v_j \otimes v_i), which is the coefficient of aiaja_i a_j after the projection by VTV^T, and Q(vi)Q(v_i) gives the coefficient of ai2a_i^2.

Lemma 2 (least squares by QR). Let D∈RK×pD \in \mathbb{R}^{K \times p} have full column rank and R∈RK×rR \in \mathbb{R}^{K \times r}. Then ∥DO−R∥F\|D O - R\|_F has a unique minimizer O∗O^*, the solution of DTDO=DTRD^T D O = D^T R. If D=Q1TD = Q_1 T with Q1TQ1=IQ_1^T Q_1 = I and TT upper triangular with a positive diagonal, then O∗=T−1Q1TRO^* = T^{-1} Q_1^T R, which line L5 computes.

Proof. ∥DO−R∥F2=∑c∥Doc−rc∥22\|D O - R\|_F^2 = \sum_c \|D o_c - r_c\|_2^2 over the columns, so each column is a separate problem. For one column, g(o)=∥Do−r∥22g(o) = \|D o - r\|_2^2 is a quadratic with the Hessian 2DTD2 D^T D, which is positive definite since DD has full column rank. So gg has a unique minimizer, where the gradient 2DT(Do−r)2 D^T (D o - r) is 0. Gram-Schmidt on independent columns does not divide by 0 and gives D=Q1TD = Q_1 T as stated. Then DTD=TTTD^T D = T^T T and DTr=TTQ1TrD^T r = T^T Q_1^T r, and since TTT^T is invertible, the normal equations become To=Q1TrT o = Q_1^T r, which back substitution solves. □\square

Theorem (exact recovery with re-projection). Let the reduced states be re-projected, a^0=VTx0\hat{a}_0 = V^T x_0 and a^k+1=VTf(Va^k)\hat{a}_{k+1} = V^T f(V \hat{a}_k) for each trajectory, and let the data matrix DD of lines L3 and L4 have full column rank. Then line L6 returns A^=A^int\hat{A} = \hat{A}_{int} and H^=H^int\hat{H} = \hat{H}_{int}.

Proof. Let Oint=[A^int,H^int]T∈Rp×rO_{int} = [\hat{A}_{int}, \hat{H}_{int}]^T \in \mathbb{R}^{p \times r}. The row of DD for the state a^k\hat{a}_k is dkT=[a^kT,s(a^k)T]d_k^T = [\hat{a}_k^T, s(\hat{a}_k)^T], and the matching row of RR is a^k+1T\hat{a}_{k+1}^T. By Lemma 1, a^k+1=VTf(Va^k)=A^inta^k+H^ints(a^k)=OintTdk\hat{a}_{k+1} = V^T f(V \hat{a}_k) = \hat{A}_{int} \hat{a}_k + \hat{H}_{int} s(\hat{a}_k) = O_{int}^T d_k. So R=DOintR = D O_{int}, and ∥DOint−R∥F=0\|D O_{int} - R\|_F = 0. Then OintO_{int} is a minimizer, and by Lemma 2 it is the only one, so O∗=OintO^* = O_{int}. Line L6 takes the first rr rows of O∗O^* as A^T\hat{A}^T and the remaining qq rows as H^T\hat{H}^T. ■\blacksquare

The closure error with projected data. If instead a^k=VTxk\hat{a}_k = V^T x_k with xk+1=f(xk)x_{k+1} = f(x_k), then a^k+1=VTf(xk)\hat{a}_{k+1} = V^T f(x_k), while the intrusive model predicts VTf(VVTxk)V^T f(V V^T x_k). So R=DOint+ER = D O_{int} + E, where the row kk of EE is (VTf(xk)−VTf(VVTxk))T(V^T f(x_k) - V^T f(V V^T x_k))^T, and by Lemma 2 the learned operator is O∗=Oint+(DTD)−1DTEO^* = O_{int} + (D^T D)^{-1} D^T E. E=0E = 0 if every xkx_k is in the range of VV, and then plain projection also recovers the intrusive model. In general E≠0E \ne 0 when the snapshots have a component outside the range of VV, and the learned model differs from the intrusive one. The example on the page measures this difference.

Termination. Every line runs a fixed number of steps: KK calls of ff per trajectory for line L2, pp Gram-Schmidt columns with two passes each, and rr back substitutions of length pp. Lemma 2 shows that no division by 0 occurs when DD has full column rank; the implementation raises an error if a column norm is exactly 0.

Complexity

In the real RAM model, the POD basis of KK snapshots costs O(n2K)O(n^2 K) to form SSTS S^T and O(n3)O(n^3) per Jacobi sweep for its eigenvectors in the implementation; for n>Kn > K the method of snapshots costs O(nK2+K3)O(n K^2 + K^3) instead. Re-projection costs KK calls of ff and O(nr)O(n r) per lift and projection. The data matrix has KK rows and p=r+r(r+1)/2=O(r2)p = r + r(r+1)/2 = O(r^2) columns, so the QR factorization costs O(Kp2)=O(Kr4)O(K p^2) = O(K r^4), and the rr right sides cost O(Krp)O(K r p). An online step costs O(rp)=O(r3)O(r p) = O(r^3) for H^s(a)\hat{H} s(a). Memory is O(nK)O(n K) for the snapshots and O(Kr2)O(K r^2) for DD.

Properties

  • Non-intrusive. It needs only evaluations of the full model, not its matrices.
  • Exact recovery. With re-projected data and a data matrix of full column rank, the learned model is the intrusive POD-Galerkin model.
  • Structure from physics. The reduced model has the polynomial form of the full model, so it can be analysed like an intrusive model.
  • Linear least squares. The fit is a convex problem with a closed-form solution, unlike training a neural network.
  • No error bound. The error of the reduced model is not certified; it is the error of the intrusive model at best.

Variants and improvements

  • Continuous-time data. For x˙=Ax+H(x⊗x)\dot{x} = A x + H(x \otimes x), fit a^˙≈A^a^+H^s(a^)\dot{\hat{a}} \approx \hat{A} \hat{a} + \hat{H} s(\hat{a}), with time derivatives from finite differences of the reduced states. The derivative error then adds to the closure error.
  • Regularization. Add a Tikhonov term λ∥O∥F2\lambda \|O\|_F^2 to line L5 when DD is ill-conditioned or the data is noisy. This trades exact recovery for stability.
  • Inputs and constants. Add columns for an input uku_k and for a constant term, so that the reduced model is A^a+H^s(a)+B^u+c^\hat{A} a + \hat{H} s(a) + \hat{B} u + \hat{c}.
  • Lifting. For a model that is not polynomial, change variables so that it becomes quadratic, then apply OpInf to the lifted variables.
  • Structure-preserving fits. Constrain A^\hat{A} to be symmetric or negative definite, or H^\hat{H} to conserve energy, by a constrained least squares problem.

When to use it

Use operator inference when the full model is a black box that you can run and that has a known polynomial form, and when you want a reduced model that behaves like a POD-Galerkin model, for example for control, design or forward uncertainty propagation. If you can also start the full model from chosen states, use re-projection. Use the intrusive projection when you can access the matrices. Use DMD for a linear model with no known structure, SINDy to find which terms are in the equations, and DEIM for a non-polynomial term in an intrusive model.

Pitfalls

  • Rank-deficient data. One trajectory that decays to a steady state gives nearly dependent rows, and the number of unknowns grows like r2r^2. Use several trajectories or inputs, and check the condition number of DD.
  • The closure error. With projected data, the learned model fits the truncated dynamics with an error that is not the intrusive error. It can fit the training data well and still be unstable, as in the example for r=5r = 5.
  • Inconsistent time stepping. If the data comes from an implicit or adaptive time integrator, the discrete map is not quadratic, and the assumed form is wrong. Fit the form that the data has.
  • Wrong polynomial degree. A cubic term in the full model, or a non-polynomial one, is not in the model class. The fit then hides the error in the other terms.
  • Scaling. The columns of DD for aia_i and for aiaja_i a_j can differ by orders of magnitude. Scale the states before the fit.

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.

operator_inference.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/operator-inference/. The authors are listed in prov/094ATM.jsonl.
"""Operator inference (OpInf) of Peherstorfer and Willcox, for a quadratic discrete-time model.

The full model is the viscous Burgers equation u_t + (u^2 / 2)_x = nu u_xx on (0, 1) with
u = 0 at both ends, central differences on n interior points and explicit Euler steps:
    x_(k+1) = f(x_k) = x_k + dt (L x_k + Q(x_k)),
with the linear part L and the quadratic part Q. The reduced model has the same form,
    a_(k+1) = A_hat a_k + H_hat s(a_k),   s(a) = (a_i a_j for i <= j),
and OpInf learns A_hat and H_hat by least squares from reduced states only. The full model is
used only as a black box that maps a state to the next state.
"""

import math
from typing import Callable

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


def burgers_step(n: int, nu: float, dt: float) -> Callable[[Vector], Vector]:
    """The black-box full model: one explicit Euler step of the discretized Burgers equation."""
    h = 1.0 / (n + 1)

    def f(x: Vector) -> Vector:
        out = []
        for i in range(n):
            left = x[i - 1] if i > 0 else 0.0
            right = x[i + 1] if i < n - 1 else 0.0
            diff = nu * (left - 2.0 * x[i] + right) / (h * h)
            conv = -(right * right - left * left) / (4.0 * h)
            out.append(x[i] + dt * (diff + conv))
        return out

    return f


def trajectory(f: Callable[[Vector], Vector], x0: Vector, k: int) -> list[Vector]:
    xs = [list(x0)]
    for _ in range(k):
        xs.append(f(xs[-1]))
    return xs


def jacobi_eigh(a: Matrix, tol: float = 1e-15, sweeps: int = 60) -> tuple[Vector, Matrix]:
    """Eigenvalues (decreasing) and eigenvectors (columns of v) of a symmetric a, cyclic Jacobi."""
    n = len(a)
    a = [list(row) for row in a]
    v = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
    for _ in range(sweeps):
        off = math.sqrt(sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j))
        if off <= tol * (math.sqrt(sum(a[i][i] ** 2 for i in range(n))) or 1.0):
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                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 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                s = t * c
                for k in range(n):
                    a[k][p], a[k][q] = c * a[k][p] - s * a[k][q], s * a[k][p] + c * a[k][q]
                for k in range(n):
                    a[p][k], a[q][k] = c * a[p][k] - s * a[q][k], s * a[p][k] + c * a[q][k]
                for k in range(n):
                    v[k][p], v[k][q] = c * v[k][p] - s * v[k][q], s * v[k][p] + c * v[k][q]
    order = sorted(range(n), key=lambda i: -a[i][i])
    return [a[i][i] for i in order], [[v[k][i] for i in order] for k in range(n)]


def pod_basis(snaps: list[Vector], r: int) -> tuple[list[Vector], Vector]:
    """r leading POD modes (orthonormal, as a list of columns) and the singular values, from the
    eigenvectors of the n by n matrix S S^T (here n is smaller than the number of snapshots)."""
    n = len(snaps[0])
    cov = [[sum(x[i] * x[j] for x in snaps) for j in range(n)] for i in range(n)]
    lam, w = jacobi_eigh(cov)
    sig = [math.sqrt(max(t, 0.0)) for t in lam]
    modes = [[w[i][j] for i in range(n)] for j in range(r)]
    return modes, sig


def restrict(v: list[Vector], x: Vector) -> Vector:
    """V^T x."""
    return [sum(a * b for a, b in zip(vj, x)) for vj in v]


def lift(v: list[Vector], a: Vector) -> Vector:
    """V a."""
    return [sum(aj * vj[i] for aj, vj in zip(a, v)) for i in range(len(v[0]))]


def sq(a: Vector) -> Vector:
    """The r(r+1)/2 quadratic terms a_i a_j, i <= j."""
    return [a[i] * a[j] for i in range(len(a)) for j in range(i, len(a))]


def reprojected_states(f: Callable[[Vector], Vector], v: list[Vector], x0: Vector, k: int) -> list[Vector]:
    """Re-projection: a_0 = V^T x0 and a_(j+1) = V^T f(V a_j), one black-box step at a time."""
    a = [restrict(v, x0)]
    for _ in range(k):
        a.append(restrict(v, f(lift(v, a[-1]))))
    return a


def lstsq_qr(d: Matrix, rhs: Matrix) -> Matrix:
    """Solve min ||d X - rhs||_F by modified Gram-Schmidt QR (two passes) and back substitution."""
    rows, cols = len(d), len(d[0])
    qcols = [[d[i][j] for i in range(rows)] for j in range(cols)]
    rr = [[0.0] * cols for _ in range(cols)]
    for j in range(cols):
        for _ in range(2):
            for i in range(j):
                c = sum(a * b for a, b in zip(qcols[i], qcols[j]))
                rr[i][j] += c
                qcols[j] = [a - c * b for a, b in zip(qcols[j], qcols[i])]
        nrm = math.sqrt(sum(t * t for t in qcols[j]))
        if nrm == 0.0:
            raise ValueError("the data matrix does not have full column rank")
        rr[j][j] = nrm
        qcols[j] = [t / nrm for t in qcols[j]]
    out = []
    for col in range(len(rhs[0])):
        b = [sum(qcols[j][i] * rhs[i][col] for i in range(rows)) for j in range(cols)]
        x = [0.0] * cols
        for j in range(cols - 1, -1, -1):
            x[j] = (b[j] - sum(rr[j][t] * x[t] for t in range(j + 1, cols))) / rr[j][j]
        out.append(x)
    return [[out[col][j] for col in range(len(rhs[0]))] for j in range(cols)]


def opinf(states: list[list[Vector]], r: int) -> tuple[Matrix, Matrix]:
    """Learn (A_hat, H_hat) from reduced trajectories (each a list of r-vectors a_0..a_K)."""
    d: Matrix = []
    rhs: Matrix = []
    for traj in states:
        for k in range(len(traj) - 1):
            d.append(list(traj[k]) + sq(traj[k]))  # @line L3: the data matrix row [a_k, s(a_k)]
            rhs.append(list(traj[k + 1]))  # @line L4: the right side a_(k+1)
    o = lstsq_qr(d, rhs)  # @line L5: least squares by QR
    a_hat = [[o[j][i] for j in range(r)] for i in range(r)]  # @line L6: O^T = [A_hat H_hat]
    h_hat = [[o[r + j][i] for j in range(len(o) - r)] for i in range(r)]
    return a_hat, h_hat  # @line L7


def learn(f: Callable[[Vector], Vector], x0s: list[Vector], k: int, r: int, reproject: bool) -> tuple[list[Vector], Matrix, Matrix]:
    """The whole method: snapshots, POD basis, reduced data, least squares."""
    snaps = [x for x0 in x0s for x in trajectory(f, x0, k)]
    v, _ = pod_basis(snaps, r)  # @line L1
    if reproject:  # @line L2: reduced states, projected or re-projected
        states = [reprojected_states(f, v, x0, k) for x0 in x0s]
    else:
        states = [[restrict(v, x) for x in trajectory(f, x0, k)] for x0 in x0s]
    a_hat, h_hat = opinf(states, r)
    return v, a_hat, h_hat


def intrusive_rom(f: Callable[[Vector], Vector], v: list[Vector]) -> tuple[Matrix, Matrix]:
    """Reference: the Galerkin projection V^T f(V a) of the full step, read off by polarization.
    f(x) = x + dt (L x + Q(x)) is a polynomial of degree 2 with f(0) = 0."""
    r = len(v)

    def qpart(x: Vector) -> Vector:
        # quadratic part of f: (f(x) + f(-x)) / 2
        fp, fm = f(x), f([-t for t in x])
        return [(a + b) / 2.0 for a, b in zip(fp, fm)]

    def lpart(x: Vector) -> Vector:
        fp, fm = f(x), f([-t for t in x])
        return [(a - b) / 2.0 for a, b in zip(fp, fm)]

    a_hat = [[0.0] * r for _ in range(r)]
    for j in range(r):
        col = restrict(v, lpart(v[j]))
        for i in range(r):
            a_hat[i][j] = col[i]
    pairs = [(i, j) for i in range(r) for j in range(i, r)]
    h_hat = [[0.0] * len(pairs) for _ in range(r)]
    for c, (i, j) in enumerate(pairs):
        if i == j:
            w = qpart(v[i])
        else:
            s = [a + b for a, b in zip(v[i], v[j])]
            w = [a - b - e for a, b, e in zip(qpart(s), qpart(v[i]), qpart(v[j]))]
        col = restrict(v, w)
        for t in range(r):
            h_hat[t][c] = col[t]
    return a_hat, h_hat


def rom_step(a_hat: Matrix, h_hat: Matrix, a: Vector) -> Vector:
    s = sq(a)
    return [sum(ai * x for ai, x in zip(row, a)) + sum(hi * y for hi, y in zip(hrow, s)) for row, hrow in zip(a_hat, h_hat)]


def rom_trajectory(a_hat: Matrix, h_hat: Matrix, a0: Vector, k: int) -> list[Vector]:
    out = [list(a0)]
    for _ in range(k):
        out.append(rom_step(a_hat, h_hat, out[-1]))
    return out
test_operator_inference.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/operator-inference/. The authors are listed in prov/094ATM.jsonl.
import math
import random

import pytest

from operator_inference import (
    burgers_step,
    intrusive_rom,
    learn,
    lift,
    lstsq_qr,
    opinf,
    pod_basis,
    restrict,
    rom_step,
    rom_trajectory,
    sq,
    trajectory,
)

N, NU, DT, K = 32, 0.05, 0.002, 200
F = burgers_step(N, NU, DT)
XG = [(i + 1) / (N + 1) for i in range(N)]
X0S = [
    [math.sin(math.pi * x) for x in XG],
    [0.8 * math.sin(2 * math.pi * x) + 0.3 * math.sin(math.pi * x) for x in XG],
    [2 * x * (1 - x) * (1 + x) for x in XG],
]
TEST_X0 = [0.6 * math.sin(math.pi * x) + 0.4 * math.sin(3 * math.pi * x) for x in XG]


def norm(v):
    return math.sqrt(sum(t * t for t in v))


def max_diff(p, q):
    return max(abs(x - y) for ra, rb in zip(p, q) for x, y in zip(ra, rb))


def rel_traj_err(v, a_hat, h_hat, x0):
    full = trajectory(F, x0, K)
    red = rom_trajectory(a_hat, h_hat, restrict(v, x0), K)
    return max(norm([p - q for p, q in zip(lift(v, a), x)]) for a, x in zip(red, full)) / max(norm(x) for x in full)


def normal_equations(d, rhs):
    """Reference least squares: solve (D^T D) X = D^T rhs by Gaussian elimination."""
    p = len(d[0])
    g = [[sum(row[i] * row[j] for row in d) for j in range(p)] for i in range(p)]
    out = []
    for col in range(len(rhs[0])):
        b = [sum(row[i] * rr[col] for row, rr in zip(d, rhs)) for i in range(p)]
        m = [list(gr) + [bi] for gr, bi in zip(g, b)]
        for k in range(p):
            piv = max(range(k, p), key=lambda i: abs(m[i][k]))
            m[k], m[piv] = m[piv], m[k]
            for i in range(k + 1, p):
                fct = m[i][k] / m[k][k]
                for j in range(k, p + 1):
                    m[i][j] -= fct * m[k][j]
        x = [0.0] * p
        for i in range(p - 1, -1, -1):
            x[i] = (m[i][p] - sum(m[i][j] * x[j] for j in range(i + 1, p))) / m[i][i]
        out.append(x)
    return [[out[c][j] for c in range(len(rhs[0]))] for j in range(p)]


def test_quadratic_terms():
    assert sq([2.0, 3.0, 5.0]) == [4.0, 6.0, 10.0, 9.0, 15.0, 25.0]
    assert len(sq([1.0] * 6)) == 21


def test_least_squares_against_normal_equations():
    rng = random.Random(1)
    d = [[rng.gauss(0, 1) for _ in range(5)] for _ in range(30)]
    rhs = [[rng.gauss(0, 1) for _ in range(2)] for _ in range(30)]
    got, ref = lstsq_qr(d, rhs), normal_equations(d, rhs)
    assert max_diff(got, ref) < 1e-10


def test_planted_quadratic_model_is_recovered():
    rng = random.Random(2)
    r = 3
    a_true = [[0.9 * (i == j) + 0.05 * rng.gauss(0, 1) for j in range(r)] for i in range(r)]
    h_true = [[0.05 * rng.gauss(0, 1) for _ in range(6)] for _ in range(r)]
    # 40 one-step trajectories from random states
    trajs = [rom_trajectory(a_true, h_true, [rng.uniform(-1, 1) for _ in range(r)], 1) for _ in range(40)]
    a_hat, h_hat = opinf(trajs, r)
    assert max_diff(a_hat, a_true) < 1e-10 and max_diff(h_hat, h_true) < 1e-10


def test_intrusive_reference_is_the_galerkin_step():
    rng = random.Random(3)
    v, _ = pod_basis([x for x0 in X0S for x in trajectory(F, x0, 40)], 4)
    a_i, h_i = intrusive_rom(F, v)
    for _ in range(5):
        a = [rng.gauss(0, 1) for _ in range(4)]
        assert rom_step(a_i, h_i, a) == pytest.approx(restrict(v, F(lift(v, a))), abs=1e-10)


def test_reprojection_recovers_the_intrusive_model():
    for r in (3, 4, 5):
        v, a_hat, h_hat = learn(F, X0S, K, r, reproject=True)
        a_i, h_i = intrusive_rom(F, v)
        assert max_diff(a_hat + h_hat, a_i + h_i) < 1e-9


def test_plain_projection_has_a_closure_error():
    v, a_hat, h_hat = learn(F, X0S, K, 4, reproject=False)
    a_i, h_i = intrusive_rom(F, v)
    assert max_diff(a_hat + h_hat, a_i + h_i) > 1e-3


def test_example_errors():
    snaps = [x for x0 in X0S for x in trajectory(F, x0, K)]
    _, sig = pod_basis(snaps, 4)
    assert sig[0] == pytest.approx(66.33, rel=1e-3) and sig[4] == pytest.approx(0.7232, rel=1e-3)
    v, a_hat, h_hat = learn(F, X0S, K, 4, reproject=True)
    assert rel_traj_err(v, a_hat, h_hat, X0S[0]) == pytest.approx(1.13e-2, rel=1e-2)
    assert rel_traj_err(v, a_hat, h_hat, TEST_X0) == pytest.approx(0.102, rel=1e-2)

History

Peherstorfer and Willcox introduced operator inference in 2016, for systems with polynomial terms, and showed that the learned operators converge to the intrusive ones as the projection error goes to 0. In 2020 Peherstorfer introduced re-projection and proved that, for time-discrete polynomial systems, it recovers the intrusive reduced model from data exactly under a rank condition. Later work added regularization, lifting transformations for models that are not polynomial, and structure-preserving fits.

References

  1. Benjamin Peherstorfer and Karen Willcox, Data-driven operator inference for nonintrusive projection-based model reduction, Computer Methods in Applied Mechanics and Engineering 306, 2016, 196-215, the least squares problem for the reduced linear and quadratic operators, and the convergence of the learned operators to the intrusive ones
  2. Benjamin Peherstorfer, Sampling low-dimensional Markovian dynamics for preasymptotically recovering reduced models from data with operator inference, SIAM Journal on Scientific Computing 42(5), 2020, A3489-A3515, the re-projection of trajectories and the exact recovery of the intrusive reduced model for time-discrete polynomial systems
  3. 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, projection-based reduced models and the intrusive construction that operator inference replaces

About this page

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

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