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.
- Solves
- System identification
- 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
- Model
- Real RAM
- Properties
- deterministicexactnot iterativeoffline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Peter J. Schmid, 2010
Dynamic mode decomposition (DMD) takes a sequence of snapshots of a system, taken at equal time steps , and fits the linear map with in the least squares sense. The snapshots can be long, for example a flow field with values, so DMD never forms . It projects onto the leading left singular vectors of the data, which gives a small 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 , and the same snapshots one step later as the columns of . Look for one matrix that moves every column of to the matching column of . 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 at equal time steps , and a rank or a threshold to choose it.
Output. Eigenvalues and modes , and the singular values of the data. The continuous-time eigenvalues are .
Notation. and , both . is the pseudoinverse.
The algorithm
EXACT-DMD(x_0, ..., x_M, r)- 1
X ← (x_0, ..., x_(M-1)); X' ← (x_1, ..., x_M) - 2
(U, S, V) ← the SVD of X - 3
choose r (the numerical rank of X, or given) - 4
à ← U_r^T X' V_r S_r⁻¹ - 5
(λ_1, ..., λ_r) ← the eigenvalues of à - 6
for each λ_l ≠ 0, with à w_l = λ_l w_l: φ_l ← X' V_r S_r⁻¹ w_l / λ_l - 7
return (λ, φ, S)
The least squares map of minimum norm with is . With , is its compression to the range of , an matrix. L6 gives the exact DMD modes of Tu et al. (2014): every pair with is an eigenpair of . Schmid's original projected DMD uses the modes 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 , and each by two steps of inverse iteration. For a model of the data, solve for amplitudes with ; then .
Example
Take points on a circle and the snapshots
with and . These are two waves that turn and decay at different rates. The data lie in the 4-dimensional space spanned by , , and , and the map from one snapshot to the next is linear on that space.
Exact data. The singular values of the matrix are
So . The continuous-time eigenvalues are and to 13 digits.
Noisy data (measurement). Add Gaussian noise with standard deviation to every value and keep . With seed 1 the eigenvalues are and . With seeds 2 and 3 they are , and , . 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 equal to the rank of , every returned pair with is an eigenpair of . If the snapshots satisfy and lies in the span of , then every returned is an eigenvalue of and is an eigenvector of for it.
Key invariant. , and . For linear data with an invariant range, .
The first statement follows from . For the second, gives . 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 . Let and , both (L1). Let be the SVD of L2, let be the rank chosen in L3, and let , , be the first left singular vectors, singular values and right singular vectors, with nonsingular. Then L4 computes
and for an eigenpair with , L6 computes the exact DMD mode .
Write for the truncated SVD and for its pseudoinverse.
Lemma 1 (the least squares operator). Among all matrices that minimize , the one of smallest Frobenius norm is . If , then and .
Proof. The minimization splits into independent least squares problems, one for each row of : minimize , where is the matching row of . The minimum norm solution is , a standard property of the pseudoinverse. If is the rank of , the discarded singular values are zero, so .
Lemma 2 (the compressed operator). . So is the matrix of restricted and projected to the range of .
Proof. , because .
Theorem 1 (Tu et al. 2014). If with and , then is nonzero and . In particular, for , is an eigenpair of .
Proof. First, , so . Then
The last case follows from Lemma 1.
Lemma 3 (invariant range). Suppose for and some matrix , so . Then the range of is invariant under if and only if lies in the range of .
Proof. The range of is spanned by . For , is one of these vectors. So the range is invariant if and only if lies in it.
Theorem 2 (linear data). Let , let , and let the range of be invariant under . Then . Every eigenvalue of is an eigenvalue of , and for the exact DMD mode is and satisfies .
Proof. With , . So and . The columns of span the range of , which is invariant, so for some matrix , and . If with , then and , so is an eigenvalue of with eigenvector . For , .
Theorem (correctness of DMD). Let L3 choose . For every nonzero eigenvalue of , DMD returns and a nonzero vector with . If the snapshots satisfy and lies in the span of , then every returned is an eigenvalue of and every returned is an eigenvector of for it.
Proof. L5 returns the eigenvalues of , the inverse iteration of L6 returns an eigenvector for each, and the mode is . Theorem 1 gives the first statement. Lemma 3 and Theorem 2 give the second.
Remark 1 (which eigenvalues are found). In the setting of Theorem 2, the eigenvalues of are those of restricted to the range of , the smallest -invariant subspace that contains . An eigenvalue whose mode is not excited by is not found. If is diagonalizable and with eigenvectors and all for distinct eigenvalues, then this subspace is spanned by the , and at least equal to their number is enough.
Remark 2 (truncation and noise). If L3 chooses smaller than the rank of , Theorem 1 still holds for the truncated operator of Lemma 1, but Theorem 2 does not apply. With noise in the snapshots, 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 matrix, 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 . L5 uses the Faddeev-LeVerrier recursion, , and a polynomial root finder; a QR algorithm would cost . L6 costs . The extra space is for the matrices.
For , the cost is linear in , which is why DMD works on large flow fields. The method of snapshots computes the SVD from the matrix for the same reason, with a loss of accuracy for small singular values.
Properties
- Exact for linear data (theorem). If and the range of is invariant under , the eigenvalues are eigenvalues of and the modes are its eigenvectors.
- Eigenpairs of the least squares map (theorem). For any data, the exact DMD pairs are eigenpairs of (Tu et al. 2014).
- Only the excited modes. DMD finds only the eigenvalues whose modes appear in the data. A mode that 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 as well as , 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 gives data of rank 1, and DMD returns one real eigenvalue, not the pair . Stack delayed snapshots (Hankel DMD) to get enough rank.
Variants and improvements
- Projected DMD. Schmid's original modes . They are in the range of the data but are not eigenvectors of in general.
- Total least squares DMD and forward-backward DMD. Reduce the noise bias by treating and symmetrically.
- Optimized DMD. Fits by nonlinear least squares, with less noise bias, at the cost of an iterative search.
- DMD with control. Fits 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 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 . Subtract the mean if you do not want it, and know that this changes the problem.
- Eigenvalues and time step. is defined up to multiples of . A frequency above the Nyquist limit aliases.
- Zero eigenvalues. The exact mode is not defined for ; 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 , 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.
# 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag BZWTTE Edit this page History Report an error Markdown