Algorithm Search⌘K

Algorithmresearch

Dynamic mode decomposition

Also called DMD.

Fits a linear operator that maps each snapshot of a system to the next by a truncated SVD, and returns its eigenvalues and modes.

Time
O(q M min(q, M) + q M r + r^4) worst
Space
O(q M) extra
Where
M = the number of snapshot pairs; q = the length of a snapshot; r = the rank kept
Properties
deterministicexactnot iterativeoffline
Origin
Peter J. Schmid, 2010

Dynamic mode decomposition (DMD) takes a sequence of snapshots x0,x1,…,xMx_0, x_1, \ldots, x_M of a system, taken at equal time steps hh, and fits the linear map AA with xk+1≈Axkx_{k+1} \approx A x_k in the least squares sense. The snapshots can be long, for example a flow field with q=106q = 10^6 values, so DMD never forms AA. It projects AA onto the leading left singular vectors of the data, which gives a small r×rr \times r matrix, and returns its eigenvalues and the matching modes in the full space. Each eigenvalue gives a frequency and a growth or decay rate, and each mode gives a spatial shape. DMD differs from the eigensystem realization algorithm, which uses Markov parameters of a system with inputs and returns a state-space model, and from SINDy, which fits a sparse nonlinear model. DMD has no input in its basic form and gives only a linear model of the snapshots.

In plain words

Put the snapshots side by side as the columns of a matrix XX, and the same snapshots one step later as the columns of X′X'. Look for one matrix that moves every column of XX to the matching column of X′X'. The snapshots are usually much longer than they are many, so first compress them: the SVD gives a few directions that describe the data well. Write the one-step map in these few directions. Its eigenvalues tell how each pattern turns and decays from one snapshot to the next, and each eigenvector, taken back to the full space, is a pattern that only changes by a factor at each step.

The problem

Input. Snapshots x0,…,xM∈Rqx_0, \ldots, x_M \in \mathbb{R}^q at equal time steps hh, and a rank rr or a threshold to choose it.

Output. Eigenvalues λ1,…,λr\lambda_1, \ldots, \lambda_r and modes φ1,…,φr∈Cq\varphi_1, \ldots, \varphi_r \in \mathbb{C}^q, and the singular values of the data. The continuous-time eigenvalues are ωl=ln⁡(λl)/h\omega_l = \ln(\lambda_l) / h.

Notation. X=(x0,…,xM−1)X = (x_0, \ldots, x_{M-1}) and X′=(x1,…,xM)X' = (x_1, \ldots, x_M), both q×Mq \times M. X+X^{+} is the pseudoinverse.

The algorithm

  1. EXACT-DMD(x_0, ..., x_M, r)
  2. 1X ← (x_0, ..., x_(M-1)); X' ← (x_1, ..., x_M)
  3. 2(U, S, V) ← the SVD of X
  4. 3choose r (the numerical rank of X, or given)
  5. 4Ã ← U_r^T X' V_r S_r⁻¹
  6. 5(λ_1, ..., λ_r) ← the eigenvalues of Ã
  7. 6for each λ_l ≠ 0, with à w_l = λ_l w_l: φ_l ← X' V_r S_r⁻¹ w_l / λ_l
  8. 7return (λ, φ, S)

The least squares map of minimum norm with AX=X′A X = X' is A=X′X+A = X' X^{+}. With X=UrSrVrTX = U_r S_r V_r^T, A~=UrTAUr\tilde A = U_r^T A U_r is its compression to the range of UrU_r, an r×rr \times r matrix. L6 gives the exact DMD modes of Tu et al. (2014): every pair (λl,φl)(\lambda_l, \varphi_l) with λl≠0\lambda_l \ne 0 is an eigenpair of X′X+X' X^{+}. Schmid's original projected DMD uses the modes UrwlU_r w_l instead; for linear data with an invariant range the two are the same.

The code computes the SVD with the one-sided Jacobi method, the eigenvalues as the roots of the characteristic polynomial of A~\tilde A, and each wlw_l by two steps of inverse iteration. For a model of the data, solve for amplitudes bb with x0≈∑lblφlx_0 \approx \sum_l b_l \varphi_l; then xk≈∑lblλlkφlx_k \approx \sum_l b_l \lambda_l^k \varphi_l.

Example

Take q=32q = 32 points gi=2πi/32g_i = 2 \pi i / 32 on a circle and the snapshots

xk(gi)=Re⁡(μ1keigi)+0.5Re⁡(μ2ke3igi),μ1=e(−0.1+2i)h,μ2=e(−0.3+5i)h,x_k(g_i) = \operatorname{Re}\big(\mu_1^k e^{\mathrm{i} g_i}\big) + 0.5 \operatorname{Re}\big(\mu_2^k e^{3 \mathrm{i} g_i}\big), \qquad \mu_1 = e^{(-0.1 + 2 \mathrm{i}) h}, \quad \mu_2 = e^{(-0.3 + 5 \mathrm{i}) h},

with h=0.1h = 0.1 and k=0,…,20k = 0, \ldots, 20. These are two waves that turn and decay at different rates. The data lie in the 4-dimensional space spanned by cos⁡g\cos g, sin⁡g\sin g, cos⁡3g\cos 3g and sin⁡3g\sin 3g, and the map from one snapshot to the next is linear on that space.

Exact data. The singular values of the 32×2032 \times 20 matrix XX are

12.648775,10.407223,5.010935,4.580128,0,…12.648775, \quad 10.407223, \quad 5.010935, \quad 4.580128, \quad 0, \ldots

So r=4r = 4. The continuous-time eigenvalues ln⁡(λ)/h\ln(\lambda) / h are −0.1±2i-0.1 \pm 2 \mathrm{i} and −0.3±5i-0.3 \pm 5 \mathrm{i} to 13 digits.

Noisy data (measurement). Add Gaussian noise with standard deviation 0.050.05 to every value and keep r=4r = 4. With seed 1 the eigenvalues are −0.0891±2.0079i-0.0891 \pm 2.0079 \mathrm{i} and −0.3284±5.0044i-0.3284 \pm 5.0044 \mathrm{i}. With seeds 2 and 3 they are −0.1161±1.9914i-0.1161 \pm 1.9914 \mathrm{i}, −0.3338±4.9795i-0.3338 \pm 4.9795 \mathrm{i} and −0.1059±2.0090i-0.1059 \pm 2.0090 \mathrm{i}, −0.3162±5.0322i-0.3162 \pm 5.0322 \mathrm{i}. The frequencies are good to about 1 percent; the decay rates have larger errors, and for the fast wave all three seeds give too much damping.

Correctness

Claim. With rr equal to the rank of XX, every returned pair with λ≠0\lambda \ne 0 is an eigenpair of X′X+X' X^{+}. If the snapshots satisfy xk+1=Axkx_{k+1} = A x_k and xMx_M lies in the span of x0,…,xM−1x_0, \ldots, x_{M-1}, then every returned λ\lambda is an eigenvalue of AA and φ\varphi is an eigenvector of AA for it.

Key invariant. A~=UrTX′X+Ur\tilde A = U_r^T X' X^{+} U_r, and UrTφ=wU_r^T \varphi = w. For linear data with an invariant range, AUr=UrA~A U_r = U_r \tilde A.

The first statement follows from X′X+φ=X′VrSr−1UrTφ=X′VrSr−1w=λφX' X^{+} \varphi = X' V_r S_r^{-1} U_r^T \varphi = X' V_r S_r^{-1} w = \lambda \varphi. For the second, X′=AXX' = A X gives X′VrSr−1=AUrX' V_r S_r^{-1} = A U_r. The full proof is below.

Proof: Exact DMD returns eigenpairs of the least squares operator, and of A for linear datafull

We work in exact real arithmetic, as in the real RAM, and assume that the SVD and the eigenvalue computation are exact. The snapshots are x0,…,xM∈Rqx_0, \ldots, x_M \in \mathbb{R}^q. Let X=(x0,…,xM−1)X = (x_0, \ldots, x_{M-1}) and X′=(x1,…,xM)X' = (x_1, \ldots, x_M), both q×Mq \times M (L1). Let X=UΣVTX = U \Sigma V^T be the SVD of L2, let rr be the rank chosen in L3, and let UrU_r, SrS_r, VrV_r be the first rr left singular vectors, singular values and right singular vectors, with SrS_r nonsingular. Then L4 computes

A~=UrTX′VrSr−1,\tilde A = U_r^T X' V_r S_r^{-1},

and for an eigenpair A~w=λw\tilde A w = \lambda w with λ≠0\lambda \ne 0, L6 computes the exact DMD mode φ=λ−1X′VrSr−1w\varphi = \lambda^{-1} X' V_r S_r^{-1} w.

Write Xr=UrSrVrTX_r = U_r S_r V_r^T for the truncated SVD and Xr+=VrSr−1UrTX_r^{+} = V_r S_r^{-1} U_r^T for its pseudoinverse.

Lemma 1 (the least squares operator). Among all q×qq \times q matrices BB that minimize ∥X′−BXr∥F\lVert X' - B X_r \rVert_F, the one of smallest Frobenius norm is Ar=X′Xr+A_r = X' X_r^{+}. If r=rank⁡Xr = \operatorname{rank} X, then Xr=XX_r = X and Ar=X′X+A_r = X' X^{+}.

Proof. The minimization splits into independent least squares problems, one for each row bTb^T of BB: minimize ∥x′T−bTXr∥\lVert x'^T - b^T X_r \rVert, where x′Tx'^T is the matching row of X′X'. The minimum norm solution is bT=x′TXr+b^T = x'^T X_r^{+}, a standard property of the pseudoinverse. If rr is the rank of XX, the discarded singular values are zero, so Xr=XX_r = X. □\square

Lemma 2 (the compressed operator). A~=UrTArUr\tilde A = U_r^T A_r U_r. So A~\tilde A is the matrix of ArA_r restricted and projected to the range of UrU_r.

Proof. UrTArUr=UrTX′VrSr−1UrTUr=UrTX′VrSr−1U_r^T A_r U_r = U_r^T X' V_r S_r^{-1} U_r^T U_r = U_r^T X' V_r S_r^{-1}, because UrTUr=IrU_r^T U_r = I_r. □\square

Theorem 1 (Tu et al. 2014). If A~w=λw\tilde A w = \lambda w with w≠0w \ne 0 and λ≠0\lambda \ne 0, then φ=λ−1X′VrSr−1w\varphi = \lambda^{-1} X' V_r S_r^{-1} w is nonzero and Arφ=λφA_r \varphi = \lambda \varphi. In particular, for r=rank⁡Xr = \operatorname{rank} X, (λ,φ)(\lambda, \varphi) is an eigenpair of X′X+X' X^{+}.

Proof. First, UrTφ=λ−1UrTX′VrSr−1w=λ−1A~w=w≠0U_r^T \varphi = \lambda^{-1} U_r^T X' V_r S_r^{-1} w = \lambda^{-1} \tilde A w = w \ne 0, so φ≠0\varphi \ne 0. Then

Arφ=X′VrSr−1UrTφ=X′VrSr−1w=λφ.A_r \varphi = X' V_r S_r^{-1} U_r^T \varphi = X' V_r S_r^{-1} w = \lambda \varphi.

The last case follows from Lemma 1. □\square

Lemma 3 (invariant range). Suppose xk+1=Axkx_{k+1} = A x_k for k=0,…,M−1k = 0, \ldots, M-1 and some q×qq \times q matrix AA, so X′=AXX' = A X. Then the range of XX is invariant under AA if and only if xMx_M lies in the range of XX.

Proof. The range of XX is spanned by x0,…,xM−1x_0, \ldots, x_{M-1}. For k<M−1k < M - 1, Axk=xk+1A x_k = x_{k+1} is one of these vectors. So the range is invariant if and only if AxM−1=xMA x_{M-1} = x_M lies in it. □\square

Theorem 2 (linear data). Let X′=AXX' = A X, let r=rank⁡Xr = \operatorname{rank} X, and let the range of XX be invariant under AA. Then AUr=UrA~A U_r = U_r \tilde A. Every eigenvalue λ\lambda of A~\tilde A is an eigenvalue of AA, and for λ≠0\lambda \ne 0 the exact DMD mode is φ=Urw\varphi = U_r w and satisfies Aφ=λφA \varphi = \lambda \varphi.

Proof. With r=rank⁡Xr = \operatorname{rank} X, XVrSr−1=UrX V_r S_r^{-1} = U_r. So X′VrSr−1=AXVrSr−1=AUrX' V_r S_r^{-1} = A X V_r S_r^{-1} = A U_r and A~=UrTAUr\tilde A = U_r^T A U_r. The columns of UrU_r span the range of XX, which is invariant, so AUr=UrCA U_r = U_r C for some r×rr \times r matrix CC, and C=UrTAUr=A~C = U_r^T A U_r = \tilde A. If A~w=λw\tilde A w = \lambda w with w≠0w \ne 0, then AUrw=UrA~w=λUrwA U_r w = U_r \tilde A w = \lambda U_r w and Urw≠0U_r w \ne 0, so λ\lambda is an eigenvalue of AA with eigenvector UrwU_r w. For λ≠0\lambda \ne 0, φ=λ−1AUrw=λ−1UrA~w=Urw\varphi = \lambda^{-1} A U_r w = \lambda^{-1} U_r \tilde A w = U_r w. □\square

Theorem (correctness of DMD). Let L3 choose r=rank⁡Xr = \operatorname{rank} X. For every nonzero eigenvalue λ\lambda of A~\tilde A, DMD returns λ\lambda and a nonzero vector φ\varphi with X′X+φ=λφX' X^{+} \varphi = \lambda \varphi. If the snapshots satisfy xk+1=Axkx_{k+1} = A x_k and xMx_M lies in the span of x0,…,xM−1x_0, \ldots, x_{M-1}, then every returned λ\lambda is an eigenvalue of AA and every returned φ\varphi is an eigenvector of AA for it.

Proof. L5 returns the eigenvalues of A~\tilde A, the inverse iteration of L6 returns an eigenvector ww for each, and the mode is λ−1X′VrSr−1w\lambda^{-1} X' V_r S_r^{-1} w. Theorem 1 gives the first statement. Lemma 3 and Theorem 2 give the second. ■\blacksquare

Remark 1 (which eigenvalues are found). In the setting of Theorem 2, the eigenvalues of A~\tilde A are those of AA restricted to the range of XX, the smallest AA-invariant subspace that contains x0x_0. An eigenvalue whose mode is not excited by x0x_0 is not found. If AA is diagonalizable and x0=∑lblvlx_0 = \sum_l b_l v_l with eigenvectors vlv_l and all bl≠0b_l \ne 0 for distinct eigenvalues, then this subspace is spanned by the vlv_l, and MM at least equal to their number is enough.

Remark 2 (truncation and noise). If L3 chooses rr smaller than the rank of XX, Theorem 1 still holds for the truncated operator ArA_r of Lemma 1, but Theorem 2 does not apply. With noise in the snapshots, X′=AXX' = A X fails and the least squares operator is biased; the page reports the effect as a measurement.

Complexity

In the real RAM. L2 is an SVD of a q×Mq \times M matrix, O(qMmin⁡(q,M))O(q M \min(q, M)) in the usual dense count. The Jacobi method of the code does this much work per sweep, and the number of sweeps depends on the data. L4 costs O(qMr)O(q M r). L5 uses the Faddeev-LeVerrier recursion, O(r4)O(r^4), and a polynomial root finder; a QR algorithm would cost O(r3)O(r^3). L6 costs O(qr2)O(q r^2). The extra space is O(qM)O(q M) for the matrices.

For q≫Mq \gg M, the cost is linear in qq, which is why DMD works on large flow fields. The method of snapshots computes the SVD from the M×MM \times M matrix XTXX^T X for the same reason, with a loss of accuracy for small singular values.

Properties

  • Exact for linear data (theorem). If xk+1=Axkx_{k+1} = A x_k and the range of XX is invariant under AA, the eigenvalues are eigenvalues of AA and the modes are its eigenvectors.
  • Eigenpairs of the least squares map (theorem). For any data, the exact DMD pairs are eigenpairs of X′X+X' X^{+} (Tu et al. 2014).
  • Only the excited modes. DMD finds only the eigenvalues whose modes appear in the data. A mode that x0x_0 does not excite is not found.
  • Biased by noise (measurement). Noise in the snapshots biases the eigenvalues, mainly the decay rates, as in the example. The noise enters XX as well as X′X', so this is an errors-in-variables problem, and plain least squares is biased.
  • Linear model. For a nonlinear system, DMD fits a linear model to the data. Rowley et al. (2009) relate the eigenvalues to the eigenvalues of the Koopman operator, which acts linearly on functions of the state; whether the linear model is accurate depends on the observables in the snapshots.
  • Standing waves need more. A standing wave xk=cos⁡(ωkh)vx_k = \cos(\omega k h) v gives data of rank 1, and DMD returns one real eigenvalue, not the pair e±iωhe^{\pm \mathrm{i} \omega h}. Stack delayed snapshots (Hankel DMD) to get enough rank.

Variants and improvements

  • Projected DMD. Schmid's original modes UrwU_r w. They are in the range of the data but are not eigenvectors of X′X+X' X^{+} in general.
  • Total least squares DMD and forward-backward DMD. Reduce the noise bias by treating XX and X′X' symmetrically.
  • Optimized DMD. Fits xk≈∑lbleωlkhφlx_k \approx \sum_l b_l e^{\omega_l k h} \varphi_l by nonlinear least squares, with less noise bias, at the cost of an iterative search.
  • DMD with control. Fits xk+1≈Axk+Bukx_{k+1} \approx A x_k + B u_k from snapshots and inputs.
  • Extended DMD. Uses a dictionary of nonlinear functions of the state as observables, as an approximation of the Koopman operator.
  • Hankel DMD. Uses delayed copies of a short measurement vector, which connects DMD with the eigensystem realization algorithm and the Prony method.
  • Streaming and compressed DMD. Update the SVD as snapshots arrive, or work on random projections of very long snapshots.

When to use it

Use DMD to find the dominant frequencies, growth rates and spatial patterns in a large set of snapshots, for example from a flow simulation or a video, when there is no input or the input is not recorded. It is fast, needs only linear algebra, and has one tuning choice, the rank. It is a good first look at the data. For a model with inputs, use DMD with control or a subspace method. For noisy data and accurate damping, use a variant with less bias. For nonlinear dynamics with few states, a sparse model from SINDy can be more accurate.

Pitfalls

  • The rank. A rank that is too high fits the noise and gives spurious eigenvalues; a rank that is too low merges modes. Look at the singular values.
  • Too few snapshots. If xMx_M is not in the span of the earlier snapshots, Theorem 2 of the proof does not apply, and the eigenvalues can be wrong even without noise.
  • Transient and steady data. A mean value in the data is a mode with λ=1\lambda = 1. Subtract the mean if you do not want it, and know that this changes the problem.
  • Eigenvalues and time step. ω=ln⁡(λ)/h\omega = \ln(\lambda) / h is defined up to multiples of 2πi/h2 \pi \mathrm{i} / h. A frequency above the Nyquist limit π/h\pi / h aliases.
  • Zero eigenvalues. The exact mode is not defined for λ=0\lambda = 0; the code rejects it. Use the projected mode or lower the rank.
  • Interpreting modes. Modes are not orthogonal and their scale is arbitrary. Compare amplitudes blb_l, not the norms of the modes.

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.

ctlmat.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra and polynomial routines for the control pages.

Conventions:
- A matrix is a list of rows. Entries are int, float, Fraction or complex.
- A vector is a flat list of scalars. matvec, dot, solve (with a vector
  right side), vec and unvec use flat lists.
- A polynomial is a list of coefficients, highest power first, so
  [1, 3, 2] is s^2 + 3 s + 2.
- Routines that divide (solve, inv, det, charpoly) compute in Fraction when
  every entry is an int or a Fraction, so the result is exact. With float or
  complex entries they compute in floating point.
- transpose does not conjugate complex entries.

Floating point tolerances:
- expm: scaling and squaring with a Taylor series; the scaled matrix has
  infinity norm at most 1/2 and the series stops when a term is below
  2^-60 times the sum. For matrices that are not far from normal the relative
  error is near 1e-14.
- polyroots: Durand-Kerner iteration, then a Newton polish. Simple roots of a
  well conditioned polynomial come out with a relative error near 1e-12 (the
  tests ask for 1e-9). A root of multiplicity k is ill conditioned: its error
  grows like 1e-16^(1/k), about 1e-8 for a double root and 1e-3 for a
  fourfold root. For real coefficients the output is closed under
  conjugation.
- is_pos_def with float entries: the matrix must be symmetric within
  1e-12 times its largest entry, and the Cholesky pivots of A - margin I must
  be positive.

This file holds no algorithm of a control page.
"""

import cmath
import math
from fractions import Fraction

__all__ = [
    "zeros", "eye", "add", "sub", "scale", "mul", "transpose", "matvec",
    "dot", "norm2", "block", "kron", "vec", "unvec", "solve", "inv", "det",
    "trace", "charpoly", "polyval", "polyadd", "polymul", "polyder",
    "polyroots", "expm", "mat_power", "is_symmetric", "is_pos_def",
]


def _is_exact(v):
    return isinstance(v, (int, Fraction))


def _all_exact(*mats):
    for m in mats:
        for row in m:
            if isinstance(row, list):
                for v in row:
                    if not _is_exact(v):
                        return False
            elif not _is_exact(row):
                return False
    return True


def _to_fraction(a):
    return [[Fraction(v) for v in row] for row in a]


def _shape(a):
    return len(a), (len(a[0]) if a else 0)


def zeros(n, m=None):
    """Return the n by m zero matrix (n by n if m is None), with int entries."""
    if m is None:
        m = n
    return [[0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix, with int entries."""
    return [[1 if i == j else 0 for j in range(n)] for i in range(n)]


def add(a, b):
    """Return a + b."""
    if _shape(a) != _shape(b):
        raise ValueError("add: shapes differ")
    return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def sub(a, b):
    """Return a - b."""
    if _shape(a) != _shape(b):
        raise ValueError("sub: shapes differ")
    return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def scale(c, a):
    """Return the scalar c times the matrix a."""
    return [[c * x for x in row] for row in a]


def mul(a, b):
    """Return the matrix product a b."""
    n, k = _shape(a)
    k2, m = _shape(b)
    if k != k2:
        raise ValueError("mul: inner dimensions differ")
    bt = list(zip(*b)) if b else []
    out = []
    for row in a:
        out_row = []
        for col in bt:
            s = 0
            for x, y in zip(row, col):
                s += x * y
            out_row.append(s)
        out.append(out_row)
    return out


def transpose(a):
    """Return the transpose of a (no complex conjugation)."""
    return [list(col) for col in zip(*a)]


def matvec(a, x):
    """Return the vector a x, for a flat list x."""
    if a and len(a[0]) != len(x):
        raise ValueError("matvec: dimensions differ")
    out = []
    for row in a:
        s = 0
        for v, w in zip(row, x):
            s += v * w
        out.append(s)
    return out


def dot(x, y):
    """Return sum of x_i y_i (no complex conjugation)."""
    if len(x) != len(y):
        raise ValueError("dot: lengths differ")
    s = 0
    for v, w in zip(x, y):
        s += v * w
    return s


def _sym_eigvals(s):
    """Eigenvalues of a real symmetric float matrix by cyclic Jacobi."""
    n = len(s)
    a = [list(map(float, row)) for row in s]
    for _ in range(100):
        off = sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        diag = sum(a[i][i] ** 2 for i in range(n))
        if off <= 1e-30 * max(diag, 1e-300):
            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 = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(n):
                    akp, akq = a[k][p], a[k][q]
                    a[k][p] = c * akp - sn * akq
                    a[k][q] = sn * akp + c * akq
                for k in range(n):
                    apk, aqk = a[p][k], a[q][k]
                    a[p][k] = c * apk - sn * aqk
                    a[q][k] = sn * apk + c * aqk
    return [a[i][i] for i in range(n)]


def norm2(x):
    """Return the 2-norm.

    For a flat vector this is the Euclidean norm. For a matrix it is the
    induced 2-norm (the largest singular value), computed from the
    eigenvalues of M^T M by the Jacobi method, where M is a real matrix with
    the same singular values. The result is a float.
    """
    if not x:
        return 0.0
    if not isinstance(x[0], list):
        return math.sqrt(sum(abs(complex(v)) ** 2 for v in x))
    if any(isinstance(v, complex) for row in x for v in row):
        re = [[complex(v).real for v in row] for row in x]
        im = [[complex(v).imag for v in row] for row in x]
        m = block([[re, scale(-1, im)], [im, re]])
    else:
        m = [[float(v) for v in row] for row in x]
    g = mul(transpose(m), m)
    lam = max(_sym_eigvals(g))
    return math.sqrt(max(lam, 0.0))


def block(rows):
    """Build a matrix from a list of rows of blocks.

    A block is a matrix, or the int 0 for a zero block whose size is taken
    from the other blocks in its block row and block column.
    """
    heights = []
    for r in rows:
        h = None
        for b in r:
            if isinstance(b, list):
                h = len(b)
                break
        if h is None:
            raise ValueError("block: a block row has no matrix block")
        heights.append(h)
    ncols = len(rows[0])
    widths = []
    for j in range(ncols):
        w = None
        for r in rows:
            if isinstance(r[j], list):
                w = len(r[j][0]) if r[j] else 0
                break
        if w is None:
            raise ValueError("block: a block column has no matrix block")
        widths.append(w)
    out = []
    for r, h in zip(rows, heights):
        if len(r) != ncols:
            raise ValueError("block: block rows have different lengths")
        for i in range(h):
            line = []
            for b, w in zip(r, widths):
                if isinstance(b, list):
                    if len(b) != h or (b and len(b[0]) != w):
                        raise ValueError("block: block sizes do not match")
                    line.extend(b[i])
                elif b == 0:
                    line.extend([0] * w)
                else:
                    raise ValueError("block: a scalar block must be 0")
            out.append(line)
    return out


def kron(a, b):
    """Return the Kronecker product of a and b."""
    n, m = _shape(a)
    p, q = _shape(b)
    return [[a[i // p][j // q] * b[i % p][j % q] for j in range(m * q)] for i in range(n * p)]


def vec(a):
    """Stack the columns of a into one flat list."""
    n, m = _shape(a)
    return [a[i][j] for j in range(m) for i in range(n)]


def unvec(v, n, m=None):
    """Inverse of vec: return the n by m matrix whose stacked columns are v."""
    if m is None:
        m = len(v) // n
    if n * m != len(v):
        raise ValueError("unvec: length does not match the shape")
    return [[v[j * n + i] for j in range(m)] for i in range(n)]


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a flat vector or a matrix; the result has the same form. With int
    and Fraction entries the result is exact (Fraction). Raises ValueError
    if a is singular (an exactly zero pivot).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("solve: matrix is not square")
    is_vec = not (b and isinstance(b[0], list))
    rhs = [[v] for v in b] if is_vec else [list(row) for row in b]
    if len(rhs) != n:
        raise ValueError("solve: right side has the wrong length")
    if _all_exact(a, rhs):
        aa = _to_fraction(a)
        rhs = _to_fraction(rhs)
    else:
        aa = [list(row) for row in a]
    k = len(rhs[0]) if rhs else 0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            raise ValueError("solve: matrix is singular")
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            rhs[c], rhs[p] = rhs[p], rhs[c]
        piv = aa[c][c]
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            row_r, row_c = aa[r], aa[c]
            for j in range(c, n):
                row_r[j] -= f * row_c[j]
            rr, rc = rhs[r], rhs[c]
            for j in range(k):
                rr[j] -= f * rc[j]
    x = [[0] * k for _ in range(n)]
    for c in range(n - 1, -1, -1):
        for j in range(k):
            s = rhs[c][j]
            for t in range(c + 1, n):
                s -= aa[c][t] * x[t][j]
            x[c][j] = s / aa[c][c]
    return [row[0] for row in x] if is_vec else x


def inv(a):
    """Return the inverse of a (exact with int and Fraction entries)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of a by elimination with partial pivoting.

    With int and Fraction entries the result is an exact Fraction.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("det: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    d = Fraction(1) if _all_exact(a) else 1.0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            return d * 0
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            d = -d
        piv = aa[c][c]
        d *= piv
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            for j in range(c, n):
                aa[r][j] -= f * aa[c][j]
    return d


def trace(a):
    """Return the sum of the diagonal entries of a."""
    s = 0
    for i in range(len(a)):
        s += a[i][i]
    return s


def charpoly(a):
    """Return [1, a_1, ..., a_n] with det(s I - A) = s^n + a_1 s^(n-1) + ... + a_n.

    Uses the Faddeev-LeVerrier recursion M_k = A M_(k-1) + a_(k-1) I,
    a_k = -trace(A M_k) / k. Exact with int and Fraction entries.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("charpoly: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    coeffs = [1]
    mk = zeros(n)
    for k in range(1, n + 1):
        mk = mul(aa, mk)
        c = coeffs[-1]
        for i in range(n):
            mk[i][i] += c
        am = mul(aa, mk)
        coeffs.append(-trace(am) / k)
    return coeffs


def polyval(p, x):
    """Evaluate the polynomial p at x by Horner's rule."""
    s = 0
    for c in p:
        s = s * x + c
    return s


def _strip(p):
    i = 0
    while i < len(p) - 1 and p[i] == 0:
        i += 1
    return list(p[i:]) if p else [0]


def polyadd(p, q):
    """Return p + q, with exactly zero leading coefficients removed."""
    n = max(len(p), len(q))
    pp = [0] * (n - len(p)) + list(p)
    qq = [0] * (n - len(q)) + list(q)
    return _strip([x + y for x, y in zip(pp, qq)])


def polymul(p, q):
    """Return the product p q."""
    if not p or not q:
        return [0]
    out = [0] * (len(p) + len(q) - 1)
    for i, x in enumerate(p):
        for j, y in enumerate(q):
            out[i + j] += x * y
    return _strip(out)


def polyder(p):
    """Return the derivative of p."""
    n = len(p) - 1
    if n <= 0:
        return [0]
    return _strip([c * (n - i) for i, c in enumerate(p[:-1])])


def polyroots(p, tol=1e-15, maxiter=1000):
    """Return the complex roots of p, sorted by real part, then imaginary part.

    Durand-Kerner (Weierstrass) iteration from points on a circle, stopped
    when every relative correction is below tol, then a Newton polish of
    each root. For real coefficients the roots are made exactly real or
    exact conjugate pairs. See the module notes for the accuracy.
    """
    c = [complex(v) for v in p]
    while c and c[0] == 0:
        c.pop(0)
    if not c:
        raise ValueError("polyroots: zero polynomial")
    real_coeffs = all(v.imag == 0 for v in c)
    origin = 0
    while len(c) > 1 and c[-1] == 0:
        c.pop()
        origin += 1
    n = len(c) - 1
    a = [v / c[0] for v in c]
    if n == 0:
        z = []
    elif n == 1:
        z = [-a[1]]
    else:
        r = 2.0 * max(abs(a[k]) ** (1.0 / k) for k in range(1, n + 1))
        if r == 0:
            r = 1.0
        z = [r * cmath.exp(1j * (2 * math.pi * k / n + 0.4)) for k in range(n)]
        for _ in range(maxiter):
            worst = 0.0
            for i in range(n):
                den = 1.0 + 0j
                for j in range(n):
                    if j != i:
                        den *= z[i] - z[j]
                if den == 0:
                    z[i] += 1e-8 * (1 + abs(z[i])) * cmath.exp(1j * (i + 1))
                    worst = 1.0
                    continue
                d = polyval(a, z[i]) / den
                z[i] -= d
                worst = max(worst, abs(d) / (1.0 + abs(z[i])))
            if worst < tol:
                break
        dp = polyder(a)
        for i in range(n):
            zi = z[i]
            fz = abs(polyval(a, zi))
            for _ in range(5):
                der = polyval(dp, zi)
                if der == 0 or fz == 0:
                    break
                step = polyval(a, zi) / der
                if abs(step) > 1e-6 * (1.0 + abs(zi)):
                    break
                znew = zi - step
                fnew = abs(polyval(a, znew))
                if fnew >= fz:
                    break
                zi, fz = znew, fnew
            z[i] = zi
    z = z + [0j] * origin
    if real_coeffs:
        thr = 1e-9
        upper = [v for v in z if v.imag > thr * (1 + abs(v))]
        lower = [v for v in z if v.imag < -thr * (1 + abs(v))]
        reals = [complex(v.real, 0.0) for v in z if abs(v.imag) <= thr * (1 + abs(v))]
        # A cluster of close roots can leave more roots above the real axis
        # than below it (or the other way). The extra roots nearest to the
        # axis are then taken as real, so the output is closed under
        # conjugation.
        if len(upper) < len(lower):
            upper, lower = [v.conjugate() for v in lower], [v.conjugate() for v in upper]
        upper.sort(key=lambda v: v.imag)
        extra = len(upper) - len(lower)
        reals += [complex(v.real, 0.0) for v in upper[:extra]]
        upper = upper[extra:]
        out = list(reals)
        rest = list(lower)
        for u in upper:
            w = min(rest, key=lambda v: abs(v - u.conjugate()))
            rest.remove(w)
            re = (u.real + w.real) / 2
            im = (u.imag - w.imag) / 2
            out.append(complex(re, im))
            out.append(complex(re, -im))
        z = out
    return sorted(z, key=lambda v: (v.real, v.imag))


def _norm_inf(a):
    return max((sum(abs(v) for v in row) for row in a), default=0.0)


def expm(a):
    """Return e^A in floating point by scaling and squaring with a Taylor series.

    A is scaled by 2^-s so that its infinity norm is at most 1/2, the Taylor
    series of the scaled matrix is summed until a term is below 2^-60 of the
    sum, and the result is squared s times. Entries of the result are float
    (complex if A has complex entries).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("expm: matrix is not square")
    cplx = any(isinstance(v, complex) for row in a for v in row)
    conv = complex if cplx else float
    x = [[conv(v) for v in row] for row in a]
    nrm = _norm_inf(x)
    s = 0
    while nrm > 0.5:
        nrm /= 2.0
        s += 1
    x = scale(conv(2.0 ** -s), x)
    e = [[conv(1.0 if i == j else 0.0) for j in range(n)] for i in range(n)]
    term = [row[:] for row in e]
    for k in range(1, 60):
        term = scale(1.0 / k, mul(term, x))
        e = add(e, term)
        tn = _norm_inf(term)
        if tn == 0.0 or tn <= 2.0 ** -60 * _norm_inf(e):
            break
    for _ in range(s):
        e = mul(e, e)
    return e


def mat_power(a, k):
    """Return A^k for an int k by repeated squaring (A^0 = I; k < 0 uses inv)."""
    n, m = _shape(a)
    if n != m:
        raise ValueError("mat_power: matrix is not square")
    if k < 0:
        a = inv(a)
        k = -k
    result = eye(n)
    base = [list(row) for row in a]
    while k:
        if k & 1:
            result = mul(result, base)
        k >>= 1
        if k:
            base = mul(base, base)
    return result


def is_symmetric(a, tol=0):
    """Return True if a is square and |a_ij - a_ji| <= tol for all i, j."""
    n, m = _shape(a)
    if n != m:
        return False
    return all(abs(a[i][j] - a[j][i]) <= tol for i in range(n) for j in range(i + 1, n))


def is_pos_def(a, margin=0):
    """Return True if a is symmetric and a - margin I is positive definite.

    With int and Fraction entries (and an exact margin) the test is exact:
    every leading principal minor of a - margin I must be positive
    (Sylvester's criterion), computed in Fraction. With float entries the
    matrix must be symmetric within 1e-12 times its largest entry, and the
    Cholesky factorization of a - margin I must have positive pivots.
    Complex entries are not accepted.
    """
    n, m = _shape(a)
    if n != m:
        return False
    if any(isinstance(v, complex) for row in a for v in row):
        raise ValueError("is_pos_def: complex entries are not accepted")
    if _all_exact(a) and _is_exact(margin):
        b = [[Fraction(a[i][j]) - (Fraction(margin) if i == j else 0) for j in range(n)] for i in range(n)]
        if not is_symmetric(b):
            return False
        return all(det([row[:k] for row in b[:k]]) > 0 for k in range(1, n + 1))
    b = [[float(a[i][j]) - (float(margin) if i == j else 0.0) for j in range(n)] for i in range(n)]
    big = max((abs(float(v)) for row in a for v in row), default=0.0)
    if not is_symmetric(b, 1e-12 * max(big, 1e-300)):
        return False
    low = [[0.0] * n for _ in range(n)]
    for j in range(n):
        d = b[j][j] - sum(low[j][k] ** 2 for k in range(j))
        if not d > 0.0:
            return False
        low[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            low[i][j] = (b[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
    return True


def _self_test():
    a = [[0, 1], [-2, -3]]
    assert charpoly(a) == [1, 3, 2]
    assert det(a) == 2
    assert mul(inv(a), a) == eye(2)
    assert solve(a, [1, 0]) == [Fraction(-3, 2), Fraction(1)]
    r = polyroots([1, 3, 2])
    assert abs(r[0] + 2) < 1e-12 and abs(r[1] + 1) < 1e-12
    t = 0.7
    e = expm([[0.0, t], [-t, 0.0]])
    want = [[math.cos(t), math.sin(t)], [-math.sin(t), math.cos(t)]]
    assert max(abs(e[i][j] - want[i][j]) for i in range(2) for j in range(2)) < 1e-14
    assert is_pos_def([[Fraction(5, 4), Fraction(1, 4)], [Fraction(1, 4), Fraction(1, 4)]])
    assert not is_pos_def([[1, 2], [2, 1]])
    assert abs(norm2([[3.0, 0.0], [0.0, -4.0]]) - 4.0) < 1e-12
    return True


if __name__ == "__main__":
    _self_test()
dynamic_mode_decomposition.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dynamic-mode-decomposition/. The authors are listed in prov/BZWTTE.jsonl.

"""Exact dynamic mode decomposition (Schmid, 2010; Tu et al., 2014).

Input: snapshots x_0, ..., x_M (real vectors of length q, the state or a
measurement of it at equally spaced times) and the rank r (or None to pick
the rank of X from the singular values with the relative threshold tol).

With X = [x_0 ... x_(M-1)], X' = [x_1 ... x_M] and the truncated SVD
X = U_r S_r V_r^T, the method computes the r by r matrix

    A_tilde = U_r^T X' V_r S_r^-1,

the eigenpairs A_tilde w = lambda w, and the exact DMD modes

    phi = X' V_r S_r^-1 w / lambda    (lambda nonzero).

Each (lambda, phi) with lambda nonzero is an eigenpair of X' X^+ (Tu et al.).
If the data come from x_(k+1) = A x_k and the range of X is invariant under A,
then each pair is an eigenpair of A.

The SVD is a one-sided Jacobi (Hestenes) method. The eigenvalues of A_tilde
are the roots of its characteristic polynomial; each eigenvector comes from
two steps of inverse iteration. All in floating point.
"""

import cmath
import math

from ctlmat import charpoly, mul, polyroots, solve, transpose

__all__ = ["jacobi_svd", "dmd", "amplitudes", "eigenvector"]


def jacobi_svd(a, tol=1e-15, max_sweeps=80):
    """Return (U, s, V) with a = U diag(s) V^T and s sorted in decreasing order.

    a is r by c. U is r by k and V is c by k, with k = min(r, c), as lists of
    rows. A column of U that belongs to a zero singular value is zero. A
    column whose squared norm is below 1e-30 times the squared Frobenius norm
    of a counts as zero and is not rotated.
    """
    r, c = len(a), len(a[0])
    if r < c:
        v, s, u = jacobi_svd(transpose(a), tol, max_sweeps)
        return u, s, v
    cols = [[float(a[i][j]) for i in range(r)] for j in range(c)]
    vcols = [[1.0 if i == j else 0.0 for i in range(c)] for j in range(c)]
    tiny = 1e-30 * sum(t * t for col in cols for t in col)
    for _ in range(max_sweeps):
        rotated = False
        for p in range(c - 1):
            for q in range(p + 1, c):
                x, y = cols[p], cols[q]
                alpha = sum(t * t for t in x)
                beta = sum(t * t for t in y)
                gamma = sum(s * t for s, t in zip(x, y))
                if min(alpha, beta) <= tiny or abs(gamma) <= tol * math.sqrt(alpha * beta):
                    continue
                rotated = True
                zeta = (beta - alpha) / (2.0 * gamma)
                t = math.copysign(1.0, zeta) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
                cs = 1.0 / math.sqrt(1.0 + t * t)
                sn = cs * t
                cols[p] = [cs * xi - sn * yi for xi, yi in zip(x, y)]
                cols[q] = [sn * xi + cs * yi for xi, yi in zip(x, y)]
                vx, vy = vcols[p], vcols[q]
                vcols[p] = [cs * xi - sn * yi for xi, yi in zip(vx, vy)]
                vcols[q] = [sn * xi + cs * yi for xi, yi in zip(vx, vy)]
        if not rotated:
            break
    sv = [math.sqrt(sum(t * t for t in col)) for col in cols]
    order = sorted(range(c), key=lambda j: -sv[j])
    s = [sv[j] for j in order]
    ucols = [[t / sv[j] for t in cols[j]] if sv[j] > 0.0 else [0.0] * r for j in order]
    return transpose(ucols), s, transpose([vcols[j] for j in order])


def eigenvector(a, lam):
    """Return a unit eigenvector of a for the eigenvalue lam, by two steps of inverse iteration."""
    n = len(a)
    shift = lam + 1e-10 * (1.0 + abs(lam))
    m = [[complex(a[i][j]) - (shift if i == j else 0.0) for j in range(n)] for i in range(n)]
    w = [complex(1.0, 0.1 * (k + 1)) for k in range(n)]
    for _ in range(2):
        w = solve(m, w)
        size = math.sqrt(sum(abs(v) ** 2 for v in w))
        w = [v / size for v in w]
    return w


def dmd(snapshots, r=None, tol=1e-10):
    """Return (eigenvalues, modes, s): the DMD eigenvalues, the modes as columns, and the singular values of X."""
    X = transpose(snapshots[:-1])  # @line L1
    Xp = transpose(snapshots[1:])
    U, s, V = jacobi_svd(X)  # @line L2
    if r is None:  # @line L3
        r = sum(1 for v in s if v > tol * s[0])
    if r < 1 or s[r - 1] <= 0.0:
        raise ValueError("dmd: the rank r must be at least 1 and at most the rank of X")
    Ur = [row[:r] for row in U]
    W = [[V[k][j] / s[j] for j in range(r)] for k in range(len(V))]  # V_r S_r^-1
    XpW = mul(Xp, W)
    At = mul(transpose(Ur), XpW)  # @line L4
    lams = polyroots(charpoly(At))  # @line L5
    modes = []
    for lam in lams:
        w = eigenvector(At, lam)
        if abs(lam) == 0.0:
            raise ValueError("dmd: a zero eigenvalue has no exact DMD mode")
        modes.append([sum(XpW[i][t] * w[t] for t in range(r)) / lam for i in range(len(XpW))])  # @line L6
    return lams, transpose(modes), s  # @line L7


def amplitudes(modes, x0):
    """Return b with modes b closest to x0 in the least squares sense (normal equations)."""
    r = len(modes[0])
    gram = [[sum(modes[i][a].conjugate() * modes[i][b] for i in range(len(modes))) for b in range(r)]
            for a in range(r)]
    rhs = [sum(modes[i][a].conjugate() * x0[i] for i in range(len(modes))) for a in range(r)]
    return solve(gram, rhs)


def continuous_eigenvalues(lams, h):
    """Return omega = ln(lambda) / h for snapshots taken every h time units."""
    return [cmath.log(complex(z)) / h for z in lams]
test_dynamic_mode_decomposition.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dynamic-mode-decomposition/. The authors are listed in prov/BZWTTE.jsonl.

import cmath
import math
import random

from ctlmat import charpoly, matvec, mul, polyroots, transpose
from dynamic_mode_decomposition import amplitudes, continuous_eigenvalues, dmd, jacobi_svd


def _orbit(A, x0, M):
    out = [list(x0)]
    for _ in range(M):
        out.append(matvec(A, out[-1]))
    return out


def _column(m, k):
    return [row[k] for row in m]


def _wave_snapshots(M, h=0.1, q=32):
    lam = [cmath.exp(complex(-0.1, 2.0) * h), cmath.exp(complex(-0.3, 5.0) * h)]
    grid = [2 * math.pi * i / q for i in range(q)]
    return [[(lam[0] ** k * cmath.exp(1j * g)).real + 0.5 * (lam[1] ** k * cmath.exp(3j * g)).real for g in grid]
            for k in range(M + 1)]


def _x_plus_times(snaps, v):
    # X' X^+ v with X^+ = V S^-1 U^T over the nonzero singular values
    X = transpose(snaps[:-1])
    Xp = transpose(snaps[1:])
    U, s, V = jacobi_svd(X)
    r = sum(1 for t in s if t > 1e-10 * s[0])
    coef = [sum(U[i][k] * v[i] for i in range(len(U))) / s[k] for k in range(r)]
    z = [sum(V[j][k] * coef[k] for k in range(r)) for j in range(len(V))]
    return [sum(Xp[i][j] * z[j] for j in range(len(z))) for i in range(len(Xp))]


def test_full_state_linear_system():
    A = [[0.9, 0.2, 0.0], [-0.2, 0.9, 0.1], [0.0, 0.0, 0.5]]
    snaps = _orbit(A, [1.0, 0.0, 1.0], 6)
    lams, modes, s = dmd(snaps)
    assert len(lams) == 3
    true = polyroots(charpoly(A))
    assert max(abs(a - b) for a, b in zip(lams, true)) < 1e-9
    for k, lam in enumerate(lams):
        phi = _column(modes, k)
        lhs = [sum(A[i][j] * phi[j] for j in range(3)) for i in range(3)]
        assert max(abs(lhs[i] - lam * phi[i]) for i in range(3)) < 1e-9


def test_wave_data_recovers_the_frequencies():
    h = 0.1
    snaps = _wave_snapshots(20, h)
    lams, modes, s = dmd(snaps)
    assert len(lams) == 4
    assert s[4] < 1e-12 * s[0]
    want = sorted([complex(-0.1, 2.0), complex(-0.1, -2.0), complex(-0.3, 5.0), complex(-0.3, -5.0)],
                  key=lambda w: (w.real, w.imag))
    got = sorted(continuous_eigenvalues(lams, h), key=lambda w: (w.real, w.imag))
    assert max(abs(a - b) for a, b in zip(got, want)) < 1e-9
    # every pair is an eigenpair of X' X^+
    for k, lam in enumerate(lams):
        phi = _column(modes, k)
        lhs = _x_plus_times(snaps, phi)
        assert max(abs(a - lam * b) for a, b in zip(lhs, phi)) < 1e-9
    # the modes and amplitudes rebuild every snapshot
    b = amplitudes(modes, snaps[0])
    for k in (0, 7, 20):
        rebuilt = [sum(modes[i][j] * lams[j] ** k * b[j] for j in range(4)) for i in range(len(modes))]
        assert max(abs(a - c) for a, c in zip(rebuilt, snaps[k])) < 1e-9


def test_too_few_snapshots():
    # two snapshot pairs of a three-state system: rank 2, so the result is not
    # the spectrum of A, but each pair is still an eigenpair of X' X^+
    A = [[0.9, 0.2, 0.0], [-0.2, 0.9, 0.1], [0.0, 0.0, 0.5]]
    snaps = _orbit(A, [1.0, 0.0, 1.0], 2)
    lams, modes, s = dmd(snaps)
    assert len(lams) == 2
    true = polyroots(charpoly(A))
    assert max(min(abs(a - b) for b in true) for a in lams) > 1e-3
    for k, lam in enumerate(lams):
        phi = _column(modes, k)
        lhs = _x_plus_times(snaps, phi)
        assert max(abs(a - lam * b) for a, b in zip(lhs, phi)) < 1e-9


def test_noisy_snapshots():
    # measurement: noise with standard deviation 0.05 on every entry, 21 snapshots
    h = 0.1
    snaps = _wave_snapshots(20, h)
    want = [complex(-0.3, -5.0), complex(-0.1, -2.0), complex(-0.1, 2.0), complex(-0.3, 5.0)]
    for seed in (1, 2, 3):
        rng = random.Random(seed)
        noisy = [[v + rng.gauss(0.0, 0.05) for v in row] for row in snaps]
        lams, modes, s = dmd(noisy, r=4)
        got = continuous_eigenvalues(lams, h)
        for w in want:
            best = min(got, key=lambda g: abs(g - w))
            assert abs(best.imag - w.imag) < 0.1
            assert abs(best.real - w.real) < 0.05


def test_rank_above_data_rank_is_rejected():
    snaps = _orbit([[0.5, 0.0], [0.0, 0.5]], [1.0, 1.0], 4)
    try:
        dmd(snaps, r=2)
    except ValueError:
        return
    assert False, "a rank above the rank of X must be rejected"

History

Schmid published dynamic mode decomposition in the Journal of Fluid Mechanics in 2010, as a way to extract coherent structures and their frequencies from flow data. Rowley, Mezic, Bagheri, Schlatter and Henningson (2009) related the method to the spectral analysis of the Koopman operator for nonlinear systems. Tu, Rowley, Luchtenburg, Brunton and Kutz (2014) defined exact DMD and proved that its eigenpairs are those of the least squares operator. Kutz, Brunton, Brunton and Proctor wrote a book on the method in 2016. The algebra is close to older methods: Prony's method, the Arnoldi iteration and realization from a Hankel matrix.

References

  1. Peter J. Schmid, Dynamic mode decomposition of numerical and experimental data, Journal of Fluid Mechanics 656, 5-28, 2010, the definition of DMD from a sequence of snapshots and the SVD-based computation of the projected operator
  2. Jonathan H. Tu, Clarence W. Rowley, Dirk M. Luchtenburg, Steven L. Brunton and J. Nathan Kutz, On dynamic mode decomposition: Theory and applications, Journal of Computational Dynamics 1(2), 391-421, 2014, the definition of exact DMD, the theorem that its eigenpairs are eigenpairs of X' X^+, and the relation to linear consistency
  3. Clarence W. Rowley, Igor Mezic, Shervin Bagheri, Philipp Schlatter and Dan S. Henningson, Spectral analysis of nonlinear flows, Journal of Fluid Mechanics 641, 115-127, 2009, the relation between the Arnoldi-type snapshot method and the eigenvalues of the Koopman operator
  4. J. Nathan Kutz, Steven L. Brunton, Bingni W. Brunton and Joshua L. Proctor, Dynamic Mode Decomposition: Data-Driven Modeling of Complex Systems, SIAM, 2016, the chapter that introduces the DMD algorithm, and the chapter on DMD with control

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.worst
  • 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