Algorithm Search⌘K

Algorithmadvanced

Discrete empirical interpolation method

Also called DEIM.

Picks interpolation indices greedily from POD modes of snapshots of the nonlinear term, so a reduced model evaluates it at few points.

Time
O(m^2) onlineO(n m^2 + m^4) selection
Space
O(n m) extra
Where
m = the number of basis vectors and indices; n = the length of the vectors
Properties
deterministicnot exactinterpolatorynot iterative
Origin
Saifon Chaturantabut, Danny C. Sorensen, 2010

The discrete empirical interpolation method (DEIM) chooses mm entries of a vector of length nn, so that the vector can be rebuilt from those entries alone. It works with a basis U=[u1,…,um]U = [u_1, \ldots, u_m] that is given, usually the leading POD modes of snapshots of a nonlinear term F(y)F(y). The approximation is

f≈f^=U(PTU)−1PTf,f \approx \hat{f} = U (P^T U)^{-1} P^T f ,

where PTfP^T f picks the chosen entries. DEIM picks the indices one at a time. The first index is where ∣u1∣|u_1| is largest. Each later index is where the residual of ulu_l is largest, after ulu_l is interpolated by the earlier vectors at the earlier indices. In a POD-Galerkin model this means that the nonlinear term is computed at mm entries in place of nn, so the online cost no longer depends on nn when each entry of FF depends on a few entries of yy. DEIM is the discrete form of the empirical interpolation method. The difference is in the basis: EIM builds the basis from the functions in the same greedy loop that picks the points, and controls the max-norm error on a training set. DEIM takes a basis that is already computed, often by an SVD, and only picks the indices, and its error bound is in the 2-norm, relative to the POD projection error.

In plain words

A reduced model has a few unknowns, but its nonlinear term is still a long vector, and computing it touches the whole mesh. If that vector always looks like a mix of a few known shapes, then a few of its entries are enough to know the mix. DEIM decides which entries to look at. It looks where the shapes are large and where each new shape differs most from what the earlier shapes can already explain at the earlier entries. Then the full vector is rebuilt from those few entries.

The problem

The input is a matrix U∈Rn×mU \in \mathbb{R}^{n \times m} with linearly independent columns u1,…,umu_1, \ldots, u_m. The output is a list of distinct indices p1,…,pmp_1, \ldots, p_m such that PTUP^T U is invertible, where P=[ep1,…,epm]P = [e_{p_1}, \ldots, e_{p_m}]. For a vector ff, the DEIM approximation f^\hat{f} is the vector in the range of UU that agrees with ff at the chosen indices.

In a model y˙=Ay+F(y)\dot{y} = A y + F(y) with a Galerkin basis V∈Rn×rV \in \mathbb{R}^{n \times r} and y≈Vay \approx V a, the reduced nonlinear term VTF(Va)V^T F(V a) becomes VTU(PTU)−1⋅PTF(Va)V^T U (P^T U)^{-1} \cdot P^T F(V a). The r×mr \times m matrix VTU(PTU)−1V^T U (P^T U)^{-1} is computed once. If FF acts entry by entry, PTF(Va)=F(PTVa)P^T F(V a) = F(P^T V a) needs only the mm rows PTVP^T V. For a stencil, it needs the rows of the neighbours too.

The algorithm

  1. DEIM(u_1..u_m) ▷ columns of length n, linearly independent
  2. 1p_1 ← the index of the largest |u_1(i)|; U ← [u_1]; P ← [e_p1]
  3. 2for l ← 2 to m do
  4. 3solve (P^T U) c = P^T u_l
  5. 4r ← u_l - U c
  6. 5p_l ← the index of the largest |r(i)|; U ← [U u_l]; P ← [P e_pl]
  7. 6return p_1..p_m

Line L3 interpolates ulu_l by the first l−1l - 1 columns at the first l−1l - 1 indices. Line L4 forms the residual, which is 0 at those indices. Line L5 picks the index where the residual is largest. The order of the columns matters: the POD modes come in the order of their singular values, so the first indices serve the most important modes. The online stage stores an LU factorization of PTUP^T U and solves with it for each new ff, in O(m2)O(m^2), plus the cost of the mm entries of ff.

Example

By hand. Take u1=(1,3,2)u_1 = (1, 3, 2) and u2=(2,1,4)u_2 = (2, 1, 4). The largest entry of ∣u1∣|u_1| is the second, so p1=2p_1 = 2. Interpolation of u2u_2 at index 2 gives c=u2(2)/u1(2)=1/3c = u_2(2)/u_1(2) = 1/3, and the residual is u2−u1/3=(5/3,0,10/3)u_2 - u_1/3 = (5/3, 0, 10/3). Its largest entry is the third, so p2=3p_2 = 3. Then PTU=(3124)P^T U = \begin{pmatrix} 3 & 1 \\ 2 & 4 \end{pmatrix}. For f=(1,1,1)f = (1, 1, 1), PTf=(1,1)P^T f = (1, 1) gives c=(3/10,1/10)c = (3/10, 1/10) and f^=0.3u1+0.1u2=(0.5,1,1)\hat{f} = 0.3 u_1 + 0.1 u_2 = (0.5, 1, 1), which agrees with ff at the indices 2 and 3.

A parametrized function. Take s(x;μ)=(1−x)cos⁡(3πμ(x+1)) e−(1+x)μs(x; \mu) = (1 - x) \cos(3\pi\mu(x + 1))\, e^{-(1 + x)\mu} on n=100n = 100 equispaced points of [−1,1][-1, 1], a test function of the kind that Chaturantabut and Sorensen use, with 51 snapshots at equispaced μ∈[1,π]\mu \in [1, \pi]. The singular values of the snapshot matrix fall from 24.8 to 0.476 at the 11th and to 4.8×10−54.8 \times 10^{-5} at the 21st. The first six DEIM indices are at x=−1,−0.758,−0.677,−0.576,−0.495,−0.232x = -1, -0.758, -0.677, -0.576, -0.495, -0.232, near the left end, where the functions are largest. The table is a measurement from the test file. It gives the largest 2-norm error over 20 test values of μ\mu between the snapshots, where ∥f∥2≤5.72\|f\|_2 \le 5.72.

mm ∥(PTU)−1∥2\|(P^T U)^{-1}\|_2 DEIM error POD projection error ratio
2 2.79 3.744 3.555 1.05
6 3.68 0.7186 0.6316 1.14
10 7.11 0.1645 0.1051 1.57
15 5.31 7.947×10−37.947 \times 10^{-3} 5.003×10−35.003 \times 10^{-3} 1.59
20 5.66 3.135×10−53.135 \times 10^{-5} 1.389×10−51.389 \times 10^{-5} 2.26

The DEIM error is within a factor 2.3 of the best error in the same space, and the factor ∥(PTU)−1∥2\|(P^T U)^{-1}\|_2 stays below 8, while the proved bound (1+2n)m−1/∥u1∥∞(1 + \sqrt{2n})^{m-1} / \|u_1\|_\infty of Chaturantabut and Sorensen is 4.7×10224.7 \times 10^{22} for m=20m = 20, and the bound nm/3 2m\sqrt{nm/3}\, 2^m of Sorensen and Embree is 2.7×1072.7 \times 10^7.

Correctness

The proof file shows, in exact arithmetic:

  1. The indices are distinct and PTUP^T U is invertible at each step. In fact PTU=LTP^T U = L T, where LL is lower triangular with the nonzero residual values rl(pl)r_l(p_l) on its diagonal and TT is upper triangular with a unit diagonal, so line L3 can always be solved.
  2. f^\hat{f} is the unique vector in the range of UU with PTf^=PTfP^T \hat{f} = P^T f, and f^=f\hat{f} = f when ff is in the range.
  3. If UU has orthonormal columns, then
∥f−f^∥2≤∥(PTU)−1∥2 ∥(I−UUT)f∥2.\|f - \hat{f}\|_2 \le \|(P^T U)^{-1}\|_2\, \|(I - U U^T) f\|_2 .

So the DEIM error is the POD projection error times a factor that depends only on UU and the indices. The proof writes f−f^f - \hat{f} in terms of w=(I−UUT)fw = (I - U U^T) f only, splits it into a part orthogonal to the range of UU and a part in it, and uses that the rows of PT[U,U⊥]P^T [U, U_\perp] are orthonormal. The bounds of the factor, (1+2n)m−1/∥u1∥∞(1 + \sqrt{2n})^{m-1} / \|u_1\|_\infty and nm/3 2m\sqrt{nm/3}\, 2^m, are cited, not proved here. The tests check the error bound, both factor bounds and, by brute force over all index sets for n≤8n \le 8, that the best index set is not worse than DEIM.

Proof: DEIM picks distinct indices with an invertible P^T U, and its error is at most the norm of (P^T U)^-1 times the POD projection errorfull

We assume exact arithmetic. Ul=[u1,…,ul]U_l = [u_1, \ldots, u_l] and Pl=[ep1,…,epl]P_l = [e_{p_1}, \ldots, e_{p_l}] are the matrices after step ll, the columns u1,…,umu_1, \ldots, u_m of length nn are linearly independent, and rlr_l is the residual of step ll, with r1=u1r_1 = u_1.

Lemma 1 (the selection is well defined). For each l≤ml \le m: Pl−1TUl−1P_{l-1}^T U_{l-1} is invertible, rl≠0r_l \ne 0, rl(pi)=0r_l(p_i) = 0 for i<li < l, rl(pl)≠0r_l(p_l) \ne 0, and plp_l differs from p1,…,pl−1p_1, \ldots, p_{l-1}. Moreover PlTUl=LlTlP_l^T U_l = L_l T_l, where LlL_l is lower triangular with the diagonal r1(p1),…,rl(pl)r_1(p_1), \ldots, r_l(p_l) and TlT_l is upper triangular with a unit diagonal. So PlTUlP_l^T U_l is invertible.

Proof. By induction on ll. For l=1l = 1, u1≠0u_1 \ne 0 by independence, so its largest entry in absolute value is not 0, and P1TU1=(u1(p1))P_1^T U_1 = (u_1(p_1)). Let l≥2l \ge 2 and assume the claim for l−1l - 1. Then line L3 has a unique solution cc. The residual rl=ul−Ul−1cr_l = u_l - U_{l-1} c is not 0, since ulu_l is not in the range of Ul−1U_{l-1}. Its entries at the old indices are Pl−1Trl=Pl−1Tul−(Pl−1TUl−1)c=0P_{l-1}^T r_l = P_{l-1}^T u_l - (P_{l-1}^T U_{l-1}) c = 0. Line L5 picks plp_l with ∣rl(pl)∣=max⁡i∣rl(i)∣>0|r_l(p_l)| = \max_i |r_l(i)| > 0, so plp_l is not an old index. Let Rl=[r1,…,rl]R_l = [r_1, \ldots, r_l]. Each uj=rj+Uj−1c(j)u_j = r_j + U_{j-1} c^{(j)}, and by induction each column of Uj−1U_{j-1} is a combination of r1,…,rj−1r_1, \ldots, r_{j-1}, so Ul=RlTlU_l = R_l T_l with TlT_l upper triangular with a unit diagonal. The entry (i,j)(i, j) of PlTRlP_l^T R_l is rj(pi)r_j(p_i), which is 0 for i<ji < j and rj(pj)≠0r_j(p_j) \ne 0 for i=ji = j. So Ll=PlTRlL_l = P_l^T R_l is lower triangular with a nonzero diagonal, and PlTUl=LlTlP_l^T U_l = L_l T_l has the determinant ∏jrj(pj)≠0\prod_j r_j(p_j) \ne 0. □\square

Write U=UmU = U_m, P=PmP = P_m, M=PTUM = P^T U and P=UM−1PT\mathbb{P} = U M^{-1} P^T.

Lemma 2 (interpolation and reproduction). f^=Pf\hat{f} = \mathbb{P} f is the unique vector in the range of UU with PTf^=PTfP^T \hat{f} = P^T f. In particular PU=U\mathbb{P} U = U, and f^=f\hat{f} = f if ff is in the range of UU.

Proof. PTPf=MM−1PTf=PTfP^T \mathbb{P} f = M M^{-1} P^T f = P^T f. If UaU a and UbU b both agree with ff at the indices, then M(a−b)=0M (a - b) = 0, so a=ba = b. For f=Uaf = U a, PUa=UM−1Ma=Ua\mathbb{P} U a = U M^{-1} M a = U a. □\square

Theorem (error bound). If the columns of UU are orthonormal, then for every f∈Rnf \in \mathbb{R}^n

∥f−f^∥2≤∥M−1∥2 ∥(I−UUT)f∥2.\|f - \hat{f}\|_2 \le \|M^{-1}\|_2\, \|(I - U U^T) f\|_2 .

Proof. If m=nm = n, then UUT=IU U^T = I and f^=f\hat{f} = f by Lemma 2, and both sides are 0. Let m<nm < n, and complete UU to an orthogonal matrix [U,U⊥][U, U_\perp] with U⊥∈Rn×(n−m)U_\perp \in \mathbb{R}^{n \times (n-m)}. Let w=(I−UUT)f=U⊥tw = (I - U U^T) f = U_\perp t with t=U⊥Tft = U_\perp^T f, so ∥w∥2=∥t∥2\|w\|_2 = \|t\|_2. Since PU=U\mathbb{P} U = U (Lemma 2), (I−P)(UUTf)=0(I - \mathbb{P})(U U^T f) = 0, so

f−f^=(I−P)f=(I−P)w=U⊥t−Uz,z=M−1PTU⊥t=M−1Nt,f - \hat{f} = (I - \mathbb{P}) f = (I - \mathbb{P}) w = U_\perp t - U z, \qquad z = M^{-1} P^T U_\perp t = M^{-1} N t ,

with N=PTU⊥∈Rm×(n−m)N = P^T U_\perp \in \mathbb{R}^{m \times (n-m)}. The two parts are orthogonal, so ∥f−f^∥22=∥t∥22+∥z∥22\|f - \hat{f}\|_2^2 = \|t\|_2^2 + \|z\|_2^2.

The matrix PT[U,U⊥]=[M,N]P^T [U, U_\perp] = [M, N] has orthonormal rows, because PTP=IP^T P = I and [U,U⊥][U, U_\perp] is orthogonal. So MMT+NNT=IM M^T + N N^T = I. Since MM is invertible (Lemma 1), MMTM M^T is positive definite, so every eigenvalue of NNTN N^T is below 1, and so is every eigenvalue of NTNN^T N, because the two matrices have the same nonzero eigenvalues. Let β=∥N∥22<1\beta = \|N\|_2^2 < 1. Then I−NTNI - N^T N is invertible, and the identity (I−NTN)NT=NT(I−NNT)(I - N^T N) N^T = N^T (I - N N^T) gives NT(I−NNT)−1=(I−NTN)−1NTN^T (I - N N^T)^{-1} = (I - N^T N)^{-1} N^T. So

∥z∥22=tTNT(MMT)−1Nt=tTNT(I−NNT)−1Nt=tT((I−NTN)−1NTN)t=tT((I−NTN)−1−I)t.\|z\|_2^2 = t^T N^T (M M^T)^{-1} N t = t^T N^T (I - N N^T)^{-1} N t = t^T \big((I - N^T N)^{-1} N^T N\big) t = t^T \big((I - N^T N)^{-1} - I\big) t .

Hence ∥f−f^∥22=tT(I−NTN)−1t≤∥t∥22/(1−β)\|f - \hat{f}\|_2^2 = t^T (I - N^T N)^{-1} t \le \|t\|_2^2 / (1 - \beta), since the eigenvalues of I−NTNI - N^T N are at least 1−β1 - \beta. On the other side, ∥M−1∥22=1/λmin⁡(MMT)=1/λmin⁡(I−NNT)=1/(1−β)\|M^{-1}\|_2^2 = 1 / \lambda_{\min}(M M^T) = 1 / \lambda_{\min}(I - N N^T) = 1/(1 - \beta). So ∥f−f^∥22≤∥M−1∥22∥w∥22\|f - \hat{f}\|_2^2 \le \|M^{-1}\|_2^2 \|w\|_2^2. ■\blacksquare

The bound is attained: with tt an eigenvector of NTNN^T N for the eigenvalue β\beta, the inequality in the last step is an equality, so the factor ∥M−1∥2\|M^{-1}\|_2 cannot be lowered for the given indices. The bounds ∥M−1∥2≤(1+2n)m−1/∥u1∥∞\|M^{-1}\|_2 \le (1 + \sqrt{2n})^{m-1} / \|u_1\|_\infty of Chaturantabut and Sorensen and ∥M−1∥2<nm/3 2m\|M^{-1}\|_2 < \sqrt{nm/3}\, 2^m of Sorensen and Embree are cited, not proved here, and the tests check both on random bases.

Complexity

In the real RAM model, step ll of the selection solves a system of size l−1l - 1 in O(l3)O(l^3) and forms the residual in O(nl)O(n l), so the selection costs O(nm2+m4)O(n m^2 + m^4). An LU factorization that grows by one row and one column per step gives O(nm2+m3)O(n m^2 + m^3). The POD basis costs more than the selection: O(nk2+k3)O(n k^2 + k^3) for kk snapshots by the method of snapshots, as in the implementation. The online stage needs mm entries of ff and O(m2)O(m^2) for the two triangular solves. Memory is O(nm)O(n m) for UU.

Properties

  • Interpolatory. f^\hat{f} equals ff at the chosen indices and is exact on the range of UU.
  • Greedy and deterministic. No search over index sets; the result depends on the order of the columns.
  • Error relative to POD. The error is at most ∥(PTU)−1∥2\|(P^T U)^{-1}\|_2 times the best 2-norm error in the range of UU.
  • Independent of the basis scaling of each column. Scaling a column does not change the indices, because the residual of line L4 scales with it.
  • Online cost independent of nn. For an entry-wise or local nonlinear term.

Variants and improvements

  • Q-DEIM. Choose the indices by a QR factorization with column pivoting of UTU^T. It gives a better worst-case bound of the factor and uses standard QR software.
  • Oversampling. Take more than mm indices and use least squares, which lowers the factor and makes the approximation less sensitive to noise.
  • Localized and adaptive DEIM. Use several local bases for different regions of the state space, or update the basis and the indices online.
  • DEIM for CUR. The same indices, applied to the left and right singular vectors, choose the rows and columns of a CUR factorization of a matrix.
  • Unassembled DEIM. For finite elements, apply DEIM to the element contributions, so each chosen entry needs one element.

When to use it

Use DEIM in a POD-Galerkin model, such as a reduced model of Burgers' equation, when the nonlinear term is local, so that a few of its entries need a few entries of the state, and when snapshots of the nonlinear term have fast singular value decay. Use EIM when you work with functions and want the basis and the points from the same greedy loop. Use operator inference when the nonlinearity is polynomial and you cannot change the code; then the reduced operators are learned and no entries are sampled. Do not use DEIM for a dense nonlinear term, such as an integral operator, because each entry then needs the whole state.

Pitfalls

  • Snapshots of the wrong quantity. The basis must come from snapshots of F(y)F(y), not of yy. A basis of the state can represent the nonlinear term badly.
  • Too few modes for the nonlinear term. If mm is smaller than the Galerkin size rr, the DEIM error can dominate and the reduced model can become unstable. Choose mm from the singular values of the nonlinear snapshots.
  • Stencils. For a finite difference term, FiF_i depends on yi−1,yi,yi+1y_{i-1}, y_i, y_{i+1}. The rows of VV for all these entries must be kept, so the cost is a small multiple of mm.
  • Forming the factor online. Solve with a stored LU factorization of PTUP^T U; do not form (PTU)−1(P^T U)^{-1} and do not recompute the selection.
  • Loss of accuracy in the POD. The method of snapshots squares the singular values, so modes with σj<εmach σ1\sigma_j < \sqrt{\varepsilon_{mach}}\, \sigma_1 are inaccurate. Use an SVD of the snapshot matrix for very small singular values.

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.

discrete_empirical_interpolation_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/discrete-empirical-interpolation-method/. The authors are listed in prov/RHRTRM.jsonl.
"""The discrete empirical interpolation method (DEIM) of Chaturantabut and Sorensen.

A basis U = [u_1 .. u_m] of R^n is given as a list of m columns. DEIM chooses m row indices
p_1..p_m, and the DEIM approximation of a vector f is U (P^T U)^-1 P^T f, which needs only the
m entries f[p_1], .., f[p_m]. The POD basis of the example is computed from the Gram matrix of
the snapshots with the cyclic Jacobi eigenvalue method.
"""

import math

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


def argmax_abs(v: Vector) -> int:
    """Index of the largest |v_i|; ties go to the first index."""
    best = 0
    for i in range(1, len(v)):
        if abs(v[i]) > abs(v[best]):
            best = i
    return best


def gauss_solve(a: Matrix, b: Vector) -> Vector:
    """Solve a x = b by Gaussian elimination with partial pivoting."""
    n = len(b)
    m = [list(row) + [bi] for row, bi in zip(a, b)]
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(m[i][k]))
        if m[p][k] == 0.0:
            raise ValueError("P^T U is singular")
        m[k], m[p] = m[p], m[k]
        for i in range(k + 1, n):
            f = m[i][k] / m[k][k]
            for j in range(k, n + 1):
                m[i][j] -= f * m[k][j]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (m[i][n] - sum(m[i][j] * x[j] for j in range(i + 1, n))) / m[i][i]
    return x


def deim(u: list[Vector]) -> list[int]:
    """Return the DEIM indices of the basis u (a list of m linearly independent columns)."""
    p = [argmax_abs(u[0])]  # @line L1
    for l in range(1, len(u)):  # @line L2
        a = [[u[j][pi] for j in range(l)] for pi in p]  # the l by l matrix P^T U
        c = gauss_solve(a, [u[l][pi] for pi in p])  # @line L3: (P^T U) c = P^T u_l
        r = [u[l][i] - sum(c[j] * u[j][i] for j in range(l)) for i in range(len(u[0]))]  # @line L4
        p.append(argmax_abs(r))  # @line L5: the new index, where r is largest
    return p  # @line L6


def deim_approx(u: list[Vector], p: list[int], fp: Vector) -> Vector:
    """The DEIM approximation U (P^T U)^-1 (f at p), from the m values fp = P^T f."""
    a = [[u[j][pi] for j in range(len(u))] for pi in p]
    c = gauss_solve(a, fp)
    return [sum(cj * uj[i] for cj, uj in zip(c, u)) for i in range(len(u[0]))]


def jacobi_eigh(a: Matrix, tol: float = 1e-15, sweeps: int = 60) -> tuple[Vector, Matrix]:
    """Eigenvalues (in decreasing order) and eigenvectors (as columns of v) of a symmetric a."""
    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))
        scale = math.sqrt(sum(a[i][i] ** 2 for i in range(n))) or 1.0
        if off <= tol * scale:
            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):
                    akp, akq = a[k][p], a[k][q]
                    a[k][p], a[k][q] = c * akp - s * akq, s * akp + c * akq
                for k in range(n):
                    apk, aqk = a[p][k], a[q][k]
                    a[p][k], a[q][k] = c * apk - s * aqk, s * apk + c * aqk
                for k in range(n):
                    vkp, vkq = v[k][p], v[k][q]
                    v[k][p], v[k][q] = c * vkp - s * vkq, s * vkp + c * vkq
    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(snaps: list[Vector], m: int) -> tuple[list[Vector], Vector]:
    """The first m POD modes (orthonormal columns) and all singular values of the snapshots,
    by the method of snapshots: eigenvectors of the Gram matrix S^T S."""
    k = len(snaps)
    gram = [[sum(a * b for a, b in zip(snaps[i], snaps[j])) for j in range(k)] for i in range(k)]
    lam, w = jacobi_eigh(gram)
    sig = [math.sqrt(max(t, 0.0)) for t in lam]
    modes = []
    for j in range(m):
        col = [sum(w[i][j] * snaps[i][x] for i in range(k)) / sig[j] for x in range(len(snaps[0]))]
        nrm = math.sqrt(sum(t * t for t in col))
        modes.append([t / nrm for t in col])
    return modes, sig


def inv_norm2(a: Matrix) -> float:
    """The spectral norm of a^-1, that is 1 / sigma_min(a), from the eigenvalues of a^T a."""
    n = len(a)
    ata = [[sum(a[k][i] * a[k][j] for k in range(n)) for j in range(n)] for i in range(n)]
    lam, _ = jacobi_eigh(ata)
    return 1.0 / math.sqrt(lam[-1])
test_discrete_empirical_interpolation_method.py 138 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/discrete-empirical-interpolation-method/. The authors are listed in prov/RHRTRM.jsonl.
import itertools
import math
import random

import pytest

from discrete_empirical_interpolation_method import deim, deim_approx, gauss_solve, inv_norm2, jacobi_eigh, pod

N = 100
XS = [-1 + 2 * i / (N - 1) for i in range(N)]
MUS = [1 + (math.pi - 1) * i / 50 for i in range(51)]
TEST = [1 + (math.pi - 1) * (i + 0.5) / 20 for i in range(20)]


def s(x, mu):
    return (1 - x) * math.cos(3 * math.pi * mu * (x + 1)) * math.exp(-(1 + x) * mu)


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


def orthonormal(cols):
    out = []
    for c in cols:
        w = list(c)
        for _ in range(2):
            for q in out:
                d = sum(a * b for a, b in zip(q, w))
                w = [a - d * b for a, b in zip(w, q)]
        nw = norm(w)
        out.append([t / nw for t in w])
    return out


def proj_err(u, f):
    c = [sum(a * b for a, b in zip(uj, f)) for uj in u]
    return norm([f[i] - sum(cj * uj[i] for cj, uj in zip(c, u)) for i in range(len(f))])


def factor(u, p):
    return inv_norm2([[u[j][pi] for j in range(len(u))] for pi in p])


def test_hand_example():
    u = [[1.0, 3.0, 2.0], [2.0, 1.0, 4.0]]
    p = deim(u)
    assert p == [1, 2]
    assert deim_approx(u, p, [1.0, 1.0]) == pytest.approx([0.5, 1.0, 1.0])


def test_jacobi_against_the_definition():
    rng = random.Random(4)
    for n in (2, 3, 6):
        b = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(n)]
        a = [[b[i][j] + b[j][i] for j in range(n)] for i in range(n)]
        lam, v = jacobi_eigh(a)
        assert all(lam[i] >= lam[i + 1] for i in range(n - 1))
        assert sum(lam) == pytest.approx(sum(a[i][i] for i in range(n)))
        for k in range(n):
            col = [v[i][k] for i in range(n)]
            av = [sum(a[i][j] * col[j] for j in range(n)) for i in range(n)]
            assert av == pytest.approx([lam[k] * t for t in col], abs=1e-10)
            for k2 in range(n):
                col2 = [v[i][k2] for i in range(n)]
                assert sum(x * y for x, y in zip(col, col2)) == pytest.approx(1.0 if k == k2 else 0.0, abs=1e-12)
    # 2 by 2 closed form
    lam, _ = jacobi_eigh([[2.0, 1.0], [1.0, 2.0]])
    assert lam == pytest.approx([3.0, 1.0])


def test_pod_projection_error_is_the_tail_of_the_singular_values():
    rng = random.Random(5)
    snaps = [[rng.gauss(0, 1) for _ in range(12)] for _ in range(7)]
    for m in (1, 3, 5):
        u, sig = pod(snaps, m)
        assert sum(proj_err(u, f) ** 2 for f in snaps) == pytest.approx(sum(t * t for t in sig[m:]), rel=1e-8)


def test_structure_on_random_bases():
    rng = random.Random(6)
    for _ in range(30):
        n, m = rng.randint(6, 12), rng.randint(1, 5)
        u = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(m)]
        p = deim(u)
        assert len(set(p)) == m
        # P^T U is nonsingular, the approximation interpolates at p and reproduces the span
        f = [rng.gauss(0, 1) for _ in range(n)]
        fh = deim_approx(u, p, [f[i] for i in p])
        assert [fh[i] for i in p] == pytest.approx([f[i] for i in p], abs=1e-9)
        a = [rng.gauss(0, 1) for _ in range(m)]
        v = [sum(aj * uj[i] for aj, uj in zip(a, u)) for i in range(n)]
        assert deim_approx(u, p, [v[i] for i in p]) == pytest.approx(v, abs=1e-8)


def test_error_bound_and_factor_bounds_against_brute_force():
    rng = random.Random(7)
    for _ in range(20):
        n, m = rng.randint(5, 8), rng.randint(1, 4)
        u = orthonormal([[rng.gauss(0, 1) for _ in range(n)] for _ in range(m)])
        p = deim(u)
        fac = factor(u, p)
        for _ in range(5):
            f = [rng.gauss(0, 1) for _ in range(n)]
            fh = deim_approx(u, p, [f[i] for i in p])
            assert norm([a - b for a, b in zip(f, fh)]) <= fac * proj_err(u, f) * (1 + 1e-9) + 1e-12
        # the best index set by brute force is at least as good; DEIM is within the proved bounds
        best = min(_safe_factor(u, list(q)) for q in itertools.combinations(range(n), m))
        assert best <= fac * (1 + 1e-9)
        assert fac <= (1 + math.sqrt(2 * n)) ** (m - 1) / max(abs(t) for t in u[0]) * (1 + 1e-9)
        assert fac < math.sqrt(n * m / 3) * 2 ** m


def _safe_factor(u, q):
    """||(P^T U)^-1||_2 for the index set q, or infinity if P^T U is singular."""
    try:
        gauss_solve([[u[j][pi] for j in range(len(u))] for pi in q], [1.0] * len(q))
        return factor(u, q)
    except (ValueError, ZeroDivisionError):
        return math.inf


def test_example_run():
    snaps = [[s(x, mu) for x in XS] for mu in MUS]
    modes, sig = pod(snaps, 20)
    assert sig[0] == pytest.approx(24.8, rel=1e-2) and sig[10] == pytest.approx(0.476, rel=1e-2)
    p = deim(modes)
    assert p[:6] == [0, 12, 16, 21, 25, 38]
    for m, fac_ref in ((2, 2.79), (10, 7.11), (20, 5.66)):
        u, pm = modes[:m], p[:m]
        fac = factor(u, pm)
        assert fac == pytest.approx(fac_ref, rel=1e-2)
        for mu in TEST:
            f = [s(x, mu) for x in XS]
            fh = deim_approx(u, pm, [f[i] for i in pm])
            assert norm([a - b for a, b in zip(f, fh)]) <= fac * proj_err(u, f) * (1 + 1e-6) + 1e-12

History

Chaturantabut and Sorensen introduced DEIM in 2010, as a discrete version of the empirical interpolation method of Barrault, Maday, Nguyen and Patera from 2004, made for POD-Galerkin models of systems of ODEs from discretized nonlinear PDEs. They proved the error bound with the factor ∥(PTU)−1∥2\|(P^T U)^{-1}\|_2 and a first bound of this factor. Sorensen and Embree used the same index selection for CUR factorizations in 2014 and gave a sharper bound of the factor.

References

  1. Saifon Chaturantabut and Danny C. Sorensen, Nonlinear model reduction via discrete empirical interpolation, SIAM Journal on Scientific Computing 32(5), 2010, 2737-2764, the DEIM index selection, the error bound with the factor of the inverse of P^T U, and the bound (1 + sqrt(2n))^(m-1) / |u_1|_inf of that factor (Lemma 3.2)
  2. Danny C. Sorensen and Mark Embree, A DEIM induced CUR factorization, 2014 (published in SIAM Journal on Scientific Computing, 2016), Lemma 4.4 of the arXiv version, the sharper bound sqrt(n m / 3) 2^m of the DEIM factor
  3. Maxime Barrault, Yvon Maday, Ngoc Cuong Nguyen and Anthony T. Patera, An empirical interpolation method, application to efficient reduced-basis discretization of partial differential equations, Comptes Rendus Mathematique 339(9), 2004, 667-672, the greedy choice of interpolation points that DEIM applies to vectors

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.online
  • a full proof of time.selection
  • 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