Algorithm Search⌘K

Algorithmresearch

Sparse identification of nonlinear dynamics

Also called SINDy.

Finds the few terms of a library of candidate functions that explain the measured derivatives, by sparse regression.

Time
O(n M p^3) worst
Space
O(M p) extra
Where
M = the number of samples; n = the number of states; p = the number of library functions
Properties
deterministicexactiterativeoffline
Origin
Steven L. Brunton, Joshua L. Proctor, J. Nathan Kutz, 2016

SINDy (sparse identification of nonlinear dynamics) finds the equations x˙=f(x)\dot x = f(x) of a nonlinear system from samples of the state and its derivative. It assumes that each component of ff is a sum of a few terms from a library of candidate functions, for example all monomials of degree at most 2. It writes the derivatives as a linear combination of the library, x˙≈ΞTθ(x)\dot x \approx \Xi^T \theta(x), and finds a sparse coefficient matrix Ξ\Xi by sequentially thresholded least squares: fit, set the small coefficients to zero, fit again on the rest, and repeat. The result is a short equation that a person can read. SINDy differs from dynamic mode decomposition, which fits a linear map between snapshots and returns eigenvalues and modes, and from black-box nonlinear models such as neural networks, which fit ff well but do not give a short formula.

In plain words

Measure the state of a system and how fast each component changes. Make a long list of guesses for the terms that could appear in the equations: a constant, each variable, each product of two variables, and so on. Fit the measured rates of change with all guesses at once by least squares. Most guesses get a small coefficient that only fits the noise. Remove every term whose coefficient is smaller than a threshold, and fit again with the terms that are left. Repeat until no term is removed. What is left is a short equation with only the important terms.

The problem

Input. Samples x(t0),…,x(tM−1)∈Rnx(t_0), \ldots, x(t_{M-1}) \in \mathbb{R}^n of the state, the derivatives x˙(ti)\dot x(t_i) (measured, or estimated from the samples), a library θ(x)=(θ1(x),…,θp(x))\theta(x) = (\theta_1(x), \ldots, \theta_p(x)) of candidate functions, and a threshold λ>0\lambda > 0.

Output. A p×np \times n coefficient matrix Ξ\Xi with few nonzero entries, such that x˙≈ΞTθ(x)\dot x \approx \Xi^T \theta(x) at the samples. Column jj gives the equation for x˙j\dot x_j.

Notation. Θ\Theta is the M×pM \times p matrix with Θik=θk(x(ti))\Theta_{ik} = \theta_k(x(t_i)). For a set SS of library indices, ΘS\Theta_S is the matrix of the columns in SS.

The algorithm

  1. SINDY(x, ẋ, θ, λ)
  2. 1Θ ← the M × p matrix of the library functions at the samples
  3. 2for each state component j = 1, ..., n:
  4. 3ξ ← the least squares solution of Θ ξ = ẋ_j; S ← {1, ..., p}
  5. 4repeat
  6. 5S_new ← {k ∈ S : |ξ_k| ≥ λ}
  7. 6if S_new ≠ S: S ← S_new; ξ ← 0; ξ_S ← the least squares solution of Θ_S ξ_S = ẋ_j
  8. 7until S did not change
  9. 8return Ξ, with column j equal to the final ξ of component j

The set SS can only shrink, and the loop goes on only while it shrinks, so there are at most p+1p + 1 fits for each component. On exit, every kept coefficient is at least λ\lambda in size and the kept coefficients are the least squares fit on their own columns. The code builds the library of all monomials of total degree at most dd and solves each least squares problem by a Householder QR decomposition, which is more accurate than the normal equations. When only the states are measured, the code estimates the derivatives by central differences (xk+1−xk−1)/(2h)(x_{k+1} - x_{k-1}) / (2h).

Example

Take the Lorenz system

x˙0=10(x1−x0),x˙1=x0(28−x2)−x1,x˙2=x0x1−83x2,\dot x_0 = 10 (x_1 - x_0), \qquad \dot x_1 = x_0 (28 - x_2) - x_1, \qquad \dot x_2 = x_0 x_1 - \tfrac{8}{3} x_2,

from x(0)=(−8,7,27)x(0) = (-8, 7, 27). Simulate it with the classical Runge-Kutta method with step 0.0020.002 up to t=5t = 5, and keep every fifth point, so h=0.01h = 0.01 and M=501M = 501. The library is the p=10p = 10 monomials of degree at most 2 in x0x_0, x1x_1, x2x_2, and λ=0.5\lambda = 0.5. The true Ξ\Xi has 7 nonzero entries.

Exact derivatives. With x˙\dot x from the right side of the equations, SINDy returns the 7 true coefficients to 10 digits and sets the other 23 entries to zero.

Central differences. With derivatives from central differences (M=499M = 499), it finds the right 7 terms:

term x˙0\dot x_0 x˙1\dot x_1 x˙2\dot x_2
x0x_0 −9.9825-9.9825 27.813727.8137
x1x_1 9.98209.9820 −0.9659-0.9659
x2x_2 −2.6596-2.6596
x0x1x_0 x_1 0.99730.9973
x0x2x_0 x_2 −0.9947-0.9947

Noisy derivatives (measurement). Add Gaussian noise with standard deviation 1 to the exact derivatives (seed 1). With λ=0.5\lambda = 0.5 SINDy again finds the right 7 terms, for example 28.0126 x0−1.0086 x1−1.0002 x0x228.0126\, x_0 - 1.0086\, x_1 - 1.0002\, x_0 x_2 for x˙1\dot x_1. With λ=0.05\lambda = 0.05 it keeps two wrong constant terms, −0.0630-0.0630 in x˙0\dot x_0 and 0.10350.1035 in x˙2\dot x_2. With λ=2\lambda = 2 it removes the true terms of size 1: the equation for x˙1\dot x_1 becomes −2.7256 x0-2.7256\, x_0 and the equation for x˙2\dot x_2 loses all its terms.

Correctness

Claim. For each component, the loop stops after at most p+1p + 1 fits, and the result ξ\xi is the least squares fit on its support with every nonzero entry at least λ\lambda in size. If Θ\Theta has full column rank, the derivatives are exact, x˙=Ξ∗Tθ(x)\dot x = \Xi^{*T} \theta(x), and λ\lambda is at most the smallest nonzero entry of Ξ∗\Xi^* in size, SINDy returns Ξ∗\Xi^*.

Key invariant. S0⊋S1⊋⋯S_0 \supsetneq S_1 \supsetneq \cdots until the stop, and ξ=LS⁡(S)\xi = \operatorname{LS}(S), the least squares fit on the current set.

For exact derivatives, the first fit already gives ξ∗\xi^*, the threshold keeps exactly its support, and the second fit gives ξ∗\xi^* again. If the error in the derivatives, mapped through Θ+\Theta^{+} and ΘS∗+\Theta_{S^*}^{+}, is smaller than both λ\lambda and the gap between λ\lambda and the smallest true coefficient, the same steps give the least squares fit on the true support. The full proof is below.

Proof: Sequentially thresholded least squares stops after at most p + 1 fits and recovers a sparse model from exact or slightly perturbed derivativesfull

We work in exact real arithmetic, as in the real RAM, and assume that each least squares fit is exact. Fix one state component. Θ\Theta is the M×pM \times p library matrix of L1 and b∈RMb \in \mathbb{R}^M is the vector of derivatives of this component. For a set S⊆{1,…,p}S \subseteq \{1, \ldots, p\}, ΘS\Theta_S is the matrix of the columns in SS, and LS⁡(S)\operatorname{LS}(S) is the vector ξ\xi with ξS=ΘS+b\xi_S = \Theta_S^{+} b and ξk=0\xi_k = 0 for k∉Sk \notin S. The threshold is λ>0\lambda > 0. We assume that Θ\Theta has full column rank pp, so every ΘS\Theta_S has full column rank and ΘS+=(ΘSTΘS)−1ΘST\Theta_S^{+} = (\Theta_S^T \Theta_S)^{-1} \Theta_S^T.

The iteration. STLSQ starts with S0={1,…,p}S_0 = \{1, \ldots, p\} and ξ(0)=LS⁡(S0)\xi^{(0)} = \operatorname{LS}(S_0) (L3). For t=0,1,…t = 0, 1, \ldots it sets St+1={k∈St:∣ξk(t)∣≥λ}S_{t+1} = \{k \in S_t : |\xi^{(t)}_k| \ge \lambda\} (L5). If St+1=StS_{t+1} = S_t it stops and returns ξ(t)\xi^{(t)} (L7); otherwise it sets ξ(t+1)=LS⁡(St+1)\xi^{(t+1)} = \operatorname{LS}(S_{t+1}) (L6). The code also stops after p+1p + 1 fits.

Lemma 1 (termination). The sets satisfy S0⊋S1⊋⋯S_0 \supsetneq S_1 \supsetneq \cdots until the stop, so STLSQ stops after at most p+1p + 1 least squares fits, and the cap of p+1p + 1 fits never ends the loop before the stop rule would.

Proof. By definition St+1⊆StS_{t+1} \subseteq S_t, and the loop continues only if St+1≠StS_{t+1} \ne S_t, so each continued step removes at least one index. Since ∣S0∣=p|S_0| = p, there are at most pp such steps, each followed by one fit, plus the first fit: at most p+1p + 1 fits. If p+1p + 1 fits are done, then pp indices were removed, so the set is empty and ξ=0\xi = 0. The next test would give the same empty set and stop with the same ξ=0\xi = 0. So the cap does not change the result. □\square

Lemma 2 (fixed point). The returned ξ\xi satisfies ξ=LS⁡(S)\xi = \operatorname{LS}(S) for its final set SS, ∣ξk∣≥λ|\xi_k| \ge \lambda for every k∈Sk \in S, and ξk=0\xi_k = 0 for every k∉Sk \notin S.

Proof. At the stop, ξ=ξ(t)=LS⁡(St)\xi = \xi^{(t)} = \operatorname{LS}(S_t) and {k∈St:∣ξk∣≥λ}=St\{k \in S_t : |\xi_k| \ge \lambda\} = S_t. Entries outside StS_t are zero by the definition of LS⁡\operatorname{LS}. In the capped case of Lemma 1, S=∅S = \emptyset and ξ=0\xi = 0, and the statement holds trivially. □\square

So every returned coefficient is either zero or at least λ\lambda in size, and the nonzero ones are the least squares fit on their own columns. Zhang and Schaeffer (2019) prove that such fixed points approximate local minimizers of the problem min⁡ξ∥Θξ−b∥2+λ2∥ξ∥0\min_\xi \lVert \Theta \xi - b \rVert^2 + \lambda^2 \lVert \xi \rVert_0 and give conditions for convergence; that analysis is not repeated here.

Theorem 1 (exact recovery). Let b=Θξ∗b = \Theta \xi^* with support S∗={k:ξk∗≠0}S^* = \{k : \xi^*_k \ne 0\}, and let 0<λ≤min⁡k∈S∗∣ξk∗∣0 < \lambda \le \min_{k \in S^*} |\xi^*_k|. Then STLSQ returns ξ∗\xi^* after at most two fits.

Proof. Θ\Theta has full column rank and Θξ∗=b\Theta \xi^* = b, so the first fit gives ξ(0)=Θ+b=ξ∗\xi^{(0)} = \Theta^{+} b = \xi^*. Then S1=S∗S_1 = S^*, because every k∈S∗k \in S^* has ∣ξk∗∣≥λ|\xi^*_k| \ge \lambda and every other kk has ξk∗=0<λ\xi^*_k = 0 < \lambda. If S∗=S0S^* = S_0, the loop stops with ξ∗\xi^*. Otherwise the second fit gives LS⁡(S∗)\operatorname{LS}(S^*); ΘS∗ξS∗∗=b\Theta_{S^*} \xi^*_{S^*} = b and ΘS∗\Theta_{S^*} has full column rank, so the fit is again ξ∗\xi^*, and the next test gives S∗S^* again and stops. □\square

Theorem 2 (recovery under a small perturbation). Let b=Θξ∗+eb = \Theta \xi^* + e, let μ=min⁡k∈S∗∣ξk∗∣>λ\mu = \min_{k \in S^*} |\xi^*_k| > \lambda, and let

δ=max⁡(∥Θ+e∥∞,∥ΘS∗+e∥∞)<min⁡(λ,μ−λ).\delta = \max\big(\lVert \Theta^{+} e \rVert_\infty, \lVert \Theta_{S^*}^{+} e \rVert_\infty\big) < \min(\lambda, \mu - \lambda).

Then STLSQ returns LS⁡(S∗)\operatorname{LS}(S^*), the least squares fit on the true support, whose nonzero entries are ξS∗∗+ΘS∗+e\xi^*_{S^*} + \Theta_{S^*}^{+} e.

Proof. The first fit is ξ(0)=Θ+(Θξ∗+e)=ξ∗+Θ+e\xi^{(0)} = \Theta^{+} (\Theta \xi^* + e) = \xi^* + \Theta^{+} e. For k∈S∗k \in S^*, ∣ξk(0)∣≥μ−δ>λ|\xi^{(0)}_k| \ge \mu - \delta > \lambda. For k∉S∗k \notin S^*, ∣ξk(0)∣≤δ<λ|\xi^{(0)}_k| \le \delta < \lambda. So S1=S∗S_1 = S^*. If S∗=S0S^* = S_0 the loop stops. Otherwise the second fit is LS⁡(S∗)\operatorname{LS}(S^*) with entries ξS∗∗+ΘS∗+e\xi^*_{S^*} + \Theta_{S^*}^{+} e on S∗S^*, since ΘS∗+ΘS∗=I\Theta_{S^*}^{+} \Theta_{S^*} = I. Each has size at least μ−δ>λ\mu - \delta > \lambda, so S2=S∗S_2 = S^* and the loop stops. □\square

Theorem (correctness of SINDy). L2 runs STLSQ once for each of the nn state components with the same Θ\Theta. Under the full rank assumption, SINDy returns after at most n(p+1)n(p + 1) least squares fits a coefficient matrix whose columns have the property of Lemma 2. If the derivatives are exact, x˙=Ξ∗Tθ(x)\dot x = \Xi^{*T} \theta(x) holds at the samples and λ\lambda is at most the smallest nonzero entry of Ξ∗\Xi^* in size, SINDy returns Ξ∗\Xi^*. With perturbed derivatives, the conclusion of Theorem 2 holds column by column.

Proof. Apply Lemmas 1 and 2 and Theorems 1 and 2 to each column. ■\blacksquare

Remark (the error in the derivatives). With central differences, ee is the difference error, of order h2h^2 times the third derivative of the state, plus the effect of measurement noise divided by hh. Theorem 2 then says that the model structure is right when this error, mapped through Θ+\Theta^{+}, is smaller than both λ\lambda and the gap μ−λ\mu - \lambda. The page shows this case and the failures for λ\lambda too small or too large as measurements.

Complexity

In the real RAM. L1 evaluates pp functions at MM samples; for monomials this costs O(Mpn)O(M p n). Each least squares fit with k≤pk \le p columns costs O(Mk2)O(M k^2) with Householder QR. There are at most p+1p + 1 fits per component and nn components, so the total is O(nMp3)O(n M p^3) in the worst case. In practice the loop stops after a few fits, and the cost is close to O(nMp2)O(n M p^2). The extra space is O(Mp)O(M p) for Θ\Theta.

The library size grows fast: all monomials of degree at most dd in nn variables give p=(n+dd)p = \binom{n + d}{d} functions.

Properties

  • At most p + 1 fits (theorem). The kept set shrinks at every step that does not stop.
  • Exact recovery (theorem). With exact derivatives, a full rank library matrix and λ\lambda at most the smallest true coefficient in size, the result is the true model.
  • Robust recovery (theorem). If the derivative error is small enough compared with λ\lambda and with the gap to the smallest true coefficient, the support is right and the result is the least squares fit on the true support.
  • Link to an l0 penalty (theorem). Zhang and Schaeffer (2019) prove that the iteration approximates local minimizers of ∥Θξ−b∥2+λ2∥ξ∥0\lVert \Theta \xi - b \rVert^2 + \lambda^2 \lVert \xi \rVert_0, and give conditions for convergence and one-step recovery.
  • Sensitive to the threshold (measurement). In the example, λ=0.05\lambda = 0.05 kept wrong terms and λ=2\lambda = 2 removed true terms. The right range depends on the size of the true coefficients and on the noise.
  • Interpretable. The result is a short formula in the library functions, which can be checked against physical laws.

Variants and improvements

  • Lasso and other sparse regressions. Lasso regression or orthogonal matching pursuit in place of thresholded least squares. Ridge regularization inside each fit helps when the library columns are nearly dependent.
  • SINDy with control. Adds the inputs to the library, x˙≈ΞTθ(x,u)\dot x \approx \Xi^T \theta(x, u).
  • Implicit SINDy. For rational right sides, such as in enzyme kinetics, the equations are written in implicit form.
  • Weak or integral forms. Multiply by test functions and integrate by parts, so no derivative of noisy data is needed.
  • Ensemble SINDy. Fit on many subsamples of the data and keep the terms that appear often, which also gives a measure of uncertainty.
  • Model selection. Run SINDy for several λ\lambda and choose with cross-validation or the Akaike information criterion.
  • Discrete time. Fit xk+1≈ΞTθ(xk)x_{k+1} \approx \Xi^T \theta(x_k) directly, with no derivatives.

When to use it

Use SINDy when the state is measured, the dynamics are nonlinear, and you expect the equations to be a short combination of known kinds of terms, as for many mechanical, chemical and fluid systems. It needs good derivatives, so the sampling must be fast and the noise small, or a variant that avoids derivatives. It does not work well when the true right side is not sparse in the library, when only some states are measured, or when the library columns are nearly dependent on the data. For a linear model of many measurements, use dynamic mode decomposition or a subspace method.

Pitfalls

  • Noisy derivatives. Finite differences make noise larger by a factor of about 1/h1/h. Smooth the data first, use total variation differentiation, or use a weak form.
  • Collinear library columns. If the trajectory stays near an attractor, some library functions are nearly linear combinations of others on the data. Then Θ\Theta is badly conditioned and the selected terms are not reliable. Use several initial states or richer inputs.
  • Scaling. Coefficients of different library functions have different units. One threshold for all of them favors large-scale terms. Normalize the columns of Θ\Theta, or use a threshold for each term.
  • The library must contain the true terms. If a needed term is missing, SINDy returns the best sparse fit in the wrong library, often with many terms.
  • Too few samples. The least squares problems need M≥pM \ge p and a library matrix of full column rank. The code raises an error when it meets an exactly zero pivot.
  • Validation. Simulate the identified model and compare with data that were not used for the fit. A small fit error on the derivatives does not guarantee a correct long-time simulation.

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.

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

"""Fixed step simulation for the control pages.

Conventions:
- A continuous-time system is a function f(t, x, u) that returns x' as a
  flat list. x is a flat list. u is whatever the control returns (a flat
  list, a scalar, or None when there is no control).
- A discrete-time system is a function F(k, x, u) that returns x_(k+1).
- The integrator is the classical 4th order Runge-Kutta method with a fixed
  step dt. The input is held constant over each step.
- Time t_k = t0 + k dt is computed by multiplication, not by summation.
- The number of steps round((t1 - t0) / dt) and the hold ratio
  round(hold / dt) must match the real ratios within 1e-9 (relative), or
  ValueError is raised.

This file holds no controller or observer of a control page.
"""

__all__ = ["rk4_step", "simulate", "simulate_discrete", "lti"]


def _axpy(a, x, y):
    return [yi + a * xi for xi, yi in zip(x, y)]


def rk4_step(f, t, x, u, dt):
    """Return x(t + dt) after one RK4 step of x' = f(t, x, u), u held constant."""
    k1 = f(t, x, u)
    k2 = f(t + dt / 2, _axpy(dt / 2, k1, x), u)
    k3 = f(t + dt / 2, _axpy(dt / 2, k2, x), u)
    k4 = f(t + dt, _axpy(dt, k3, x), u)
    return [xi + dt / 6 * (a + 2 * b + 2 * c + d) for xi, a, b, c, d in zip(x, k1, k2, k3, k4)]


def _ratio(num, den, what):
    r = round(num / den)
    if abs(r * den - num) > 1e-9 * max(abs(num), abs(den)):
        raise ValueError(what + " is not an integer multiple of dt")
    return r


def simulate(f, x0, t0, t1, dt, control=None, hold=None):
    """Simulate x' = f(t, x, u) from x(t0) = x0 to t1 with RK4 and step dt.

    control(t, x) gives the input. It is called at each sampling instant
    t0 + j hold, and its value is held (zero-order hold) until the next
    instant. hold must be an integer multiple of dt; hold = None means
    hold = dt. With control = None the input is None.

    Returns (ts, xs, us): ts has N + 1 times, xs the N + 1 states, and us the
    N inputs, where us[k] acts on [ts[k], ts[k + 1]].
    """
    if dt <= 0:
        raise ValueError("dt must be positive")
    n_steps = _ratio(t1 - t0, dt, "t1 - t0")
    if n_steps < 0:
        raise ValueError("t1 is before t0")
    r = 1 if hold is None else _ratio(hold, dt, "hold")
    if r < 1:
        raise ValueError("hold must be at least dt")
    x = list(x0)
    ts = [t0]
    xs = [list(x)]
    us = []
    u = None
    for k in range(n_steps):
        t = t0 + k * dt
        if control is not None and k % r == 0:
            u = control(t, list(x))
        x = rk4_step(f, t, x, u, dt)
        ts.append(t0 + (k + 1) * dt)
        xs.append(x)
        us.append(u)
    return ts, xs, us


def simulate_discrete(F, x0, N, control=None):
    """Run x_(k+1) = F(k, x_k, u_k) for k = 0, ..., N - 1.

    u_k = control(k, x_k), or None if control is None. Returns (xs, us) with
    N + 1 states and N inputs. Exact if F and control are exact.
    """
    x = list(x0)
    xs = [list(x)]
    us = []
    for k in range(N):
        u = control(k, list(x)) if control is not None else None
        x = list(F(k, x, u))
        xs.append(x)
        us.append(u)
    return xs, us


def lti(A, B=None):
    """Return f(t, x, u) = A x + B u for the system x' = A x + B u.

    u may be a flat list, a scalar (one input) or None (zero input). B may
    be None for a system with no input.
    """
    def f(t, x, u):
        dx = [sum(a * xi for a, xi in zip(row, x)) for row in A]
        if B is None or u is None:
            return dx
        uu = u if isinstance(u, (list, tuple)) else [u]
        return [d + sum(b * ui for b, ui in zip(row, uu)) for d, row in zip(dx, B)]
    return f


def _self_test():
    import math
    f = lti([[-1.0]])
    _, xs, _ = simulate(f, [1.0], 0.0, 1.0, 0.01)
    assert abs(xs[-1][0] - math.exp(-1.0)) < 1e-9
    return True


if __name__ == "__main__":
    _self_test()
sindy.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sindy/. The authors are listed in prov/5WMZP5.jsonl.

"""Sparse identification of nonlinear dynamics (SINDy) with sequentially
thresholded least squares (STLSQ), after Brunton, Proctor and Kutz (2016).

Input: states x(t_0), ..., x(t_(M-1)) (vectors of length n), their time
derivatives (measured, or estimated by central differences), a library of
candidate functions (here all monomials of total degree at most d), and a
threshold lam > 0.

Model: x' = Xi^T theta(x), where theta(x) is the vector of the p library
functions and Xi is a sparse p by n matrix. With Theta the M by p matrix of
library values at the samples, each column xi of Xi solves

    xi = argmin ||Theta xi - dx||_2,

then every entry with |xi_k| < lam is set to zero and the least squares fit
is repeated on the remaining columns of Theta, until the set of kept
columns does not change. The kept set never grows, so there are at most
p + 1 fits per column.

Least squares uses a Householder QR factorization in floating point.
"""

import math
from itertools import combinations_with_replacement

__all__ = ["monomials", "library", "lstsq_qr", "stlsq", "sindy", "central_difference"]


def monomials(n, degree):
    """Return the exponent tuples of all monomials in n variables with total degree <= degree."""
    out = []
    for d in range(degree + 1):
        for combo in combinations_with_replacement(range(n), d):
            e = [0] * n
            for v in combo:
                e[v] += 1
            out.append(tuple(e))
    return out


def term_name(e):
    """Return a readable name such as '1', 'x0', 'x0 x2' or 'x1^2'."""
    parts = []
    for v, k in enumerate(e):
        if k == 1:
            parts.append("x%d" % v)
        elif k > 1:
            parts.append("x%d^%d" % (v, k))
    return " ".join(parts) if parts else "1"


def library(xs, exps):
    """Return Theta: one row per sample, one column per exponent tuple."""
    return [[math.prod(x[v] ** k for v, k in enumerate(e)) for e in exps] for x in xs]


def lstsq_qr(a, b):
    """Return x that minimizes ||a x - b||_2 for an M by p matrix a of full column rank (M >= p).

    Householder QR: p reflections reduce a to upper triangular R and turn b
    into Q^T b; then R x = (Q^T b)[0:p] is solved by back substitution.
    Cost: O(M p^2).
    """
    m, p = len(a), len(a[0]) if a else 0
    if p == 0:
        return []
    cols = [[float(a[i][j]) for i in range(m)] for j in range(p)]
    rhs = [float(v) for v in b]
    for k in range(p):
        v = cols[k][k:]
        normx = math.sqrt(sum(t * t for t in v))
        if normx == 0.0:
            raise ValueError("lstsq_qr: the matrix does not have full column rank")
        alpha = -math.copysign(normx, v[0])
        v[0] -= alpha
        vv = sum(t * t for t in v)
        for j in range(k, p):
            col = cols[j]
            f = 2.0 * sum(col[k + t] * v[t] for t in range(len(v))) / vv
            for t in range(len(v)):
                col[k + t] -= f * v[t]
        f = 2.0 * sum(rhs[k + t] * v[t] for t in range(len(v))) / vv
        for t in range(len(v)):
            rhs[k + t] -= f * v[t]
    x = [0.0] * p
    for k in range(p - 1, -1, -1):
        s = rhs[k] - sum(cols[j][k] * x[j] for j in range(k + 1, p))
        if cols[k][k] == 0.0:
            raise ValueError("lstsq_qr: the matrix does not have full column rank")
        x[k] = s / cols[k][k]
    return x


def stlsq(theta, dx, lam, max_iter=None):
    """Return (xi, fits): the STLSQ solution for one state and the number of least squares fits."""
    p = len(theta[0])
    if max_iter is None:
        max_iter = p + 1
    xi = lstsq_qr(theta, dx)  # @line L3
    fits = 1
    keep = list(range(p))
    while fits < max_iter:  # @line L4
        new_keep = [k for k in keep if abs(xi[k]) >= lam]  # @line L5
        if new_keep == keep:  # @line L7
            break
        keep = new_keep
        xi = [0.0] * p  # @line L6
        if keep:
            sol = lstsq_qr([[row[k] for k in keep] for row in theta], dx)
            for k, v in zip(keep, sol):
                xi[k] = v
        fits += 1
    return xi, fits


def sindy(xs, dxs, degree, lam):
    """Return (Xi, exps): the p by n coefficient matrix and the exponent tuples of its rows."""
    n = len(xs[0])
    exps = monomials(n, degree)
    theta = library(xs, exps)  # @line L1
    cols = []
    for j in range(n):  # @line L2
        xi, _ = stlsq(theta, [d[j] for d in dxs], lam)
        cols.append(xi)
    Xi = [[cols[j][k] for j in range(n)] for k in range(len(exps))]
    return Xi, exps  # @line L8


def central_difference(xs, dt):
    """Return (x_k, (x_(k+1) - x_(k-1)) / (2 dt)) for k = 1, ..., M - 2."""
    inner = xs[1:-1]
    d = [[(b - a) / (2.0 * dt) for a, b in zip(xs[k - 1], xs[k + 1])] for k in range(1, len(xs) - 1)]
    return inner, d
test_sindy.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sindy/. The authors are listed in prov/5WMZP5.jsonl.

import random

from ctlsim import simulate
from sindy import central_difference, library, lstsq_qr, monomials, sindy, stlsq, term_name


def _lorenz(t, x, u):
    return [10.0 * (x[1] - x[0]), x[0] * (28.0 - x[2]) - x[1], x[0] * x[1] - 8.0 / 3.0 * x[2]]


def _true_xi(exps):
    want = {
        (1, 0, 0): [-10.0, 28.0, 0.0],
        (0, 1, 0): [10.0, -1.0, 0.0],
        (0, 0, 1): [0.0, 0.0, -8.0 / 3.0],
        (1, 1, 0): [0.0, 0.0, 1.0],
        (1, 0, 1): [0.0, -1.0, 0.0],
    }
    return [want.get(e, [0.0, 0.0, 0.0]) for e in exps]


def _samples(t1=3.0, dt=0.005, every=2):
    _, xs, _ = simulate(_lorenz, [-8.0, 7.0, 27.0], 0.0, t1, dt)
    return xs[::every], dt * every


def test_monomials_and_names():
    exps = monomials(3, 2)
    assert len(exps) == 10
    assert [term_name(e) for e in exps[:4]] == ["1", "x0", "x1", "x2"]
    assert term_name((1, 0, 1)) == "x0 x2"
    assert term_name((0, 2, 0)) == "x1^2"
    assert library([[2.0, 3.0]], monomials(2, 2)) == [[1.0, 2.0, 3.0, 4.0, 6.0, 9.0]]


def test_lstsq_qr_matches_normal_equations():
    rng = random.Random(4)
    a = [[rng.uniform(-1, 1) for _ in range(4)] for _ in range(12)]
    b = [rng.uniform(-1, 1) for _ in range(12)]
    x = lstsq_qr(a, b)
    # the residual is orthogonal to every column
    r = [bi - sum(row[j] * x[j] for j in range(4)) for row, bi in zip(a, b)]
    assert all(abs(sum(a[i][j] * r[i] for i in range(12))) < 1e-12 for j in range(4))


def test_exact_derivatives_give_exact_model():
    xs, _ = _samples()
    dxs = [_lorenz(0.0, x, None) for x in xs]
    Xi, exps = sindy(xs, dxs, 2, 0.5)
    want = _true_xi(exps)
    assert all(abs(a - b) < 1e-9 for ra, rb in zip(Xi, want) for a, b in zip(ra, rb))
    # the zero entries are exactly zero
    assert all(a == 0.0 for ra, rb in zip(Xi, want) for a, b in zip(ra, rb) if b == 0.0)


def test_central_differences():
    # measurement: derivatives from central differences with step 0.01;
    # the right terms, each coefficient within 5 percent
    xs, h = _samples()
    inner, d = central_difference(xs, h)
    Xi, exps = sindy(inner, d, 2, 0.5)
    want = _true_xi(exps)
    for ra, rb in zip(Xi, want):
        for a, b in zip(ra, rb):
            assert (a == 0.0) == (b == 0.0)
            assert abs(a - b) <= 0.05 * abs(b)


def test_noisy_derivatives_and_threshold():
    # measurement: Gaussian noise with standard deviation 1 on the derivatives
    xs, _ = _samples()
    rng = random.Random(1)
    dxs = [[v + rng.gauss(0.0, 1.0) for v in _lorenz(0.0, x, None)] for x in xs]
    Xi, exps = sindy(xs, dxs, 2, 0.5)
    want = _true_xi(exps)
    for ra, rb in zip(Xi, want):
        for a, b in zip(ra, rb):
            assert (a == 0.0) == (b == 0.0)
            assert abs(a - b) <= 0.03 * abs(b)
    # a threshold above the smallest true coefficient (1) removes true terms
    Xi_big, _ = sindy(xs, dxs, 2, 3.0)
    assert any(a == 0.0 and b != 0.0 for ra, rb in zip(Xi_big, want) for a, b in zip(ra, rb))


def test_number_of_fits_is_at_most_p_plus_one():
    rng = random.Random(6)
    theta = [[rng.uniform(-1, 1) for _ in range(8)] for _ in range(40)]
    for _ in range(10):
        dx = [rng.uniform(-1, 1) for _ in range(40)]
        xi, fits = stlsq(theta, dx, 0.1)
        assert fits <= 9
        # on exit, every kept coefficient is at least the threshold
        assert all(v == 0.0 or abs(v) >= 0.1 for v in xi)

History

Fitting equations to data by searching over terms has a long history, from regression on candidate terms to symbolic regression by genetic programming, for example by Schmidt and Lipson in 2009. Brunton, Proctor and Kutz (2016) made the search a sparse linear regression over a fixed library and solved it by sequentially thresholded least squares, which is fast and simple. They showed it on the Lorenz system, on vortex shedding behind a cylinder and on other examples. Many extensions followed, for control, implicit equations, weak forms and model selection. Zhang and Schaeffer (2019) gave a convergence analysis of the thresholded least squares iteration.

References

  1. Steven L. Brunton, Joshua L. Proctor and J. Nathan Kutz, Discovering governing equations from data by sparse identification of nonlinear dynamical systems, Proceedings of the National Academy of Sciences 113(15), 3932-3937, 2016, the library of candidate functions, the sequentially thresholded least squares algorithm, and the Lorenz system example
  2. Linan Zhang and Hayden Schaeffer, On the convergence of the SINDy algorithm, Multiscale Modeling and Simulation 17(3), 948-972, 2019, the proof that the algorithm approximates local minimizers of a least squares problem with an l0 penalty, and the conditions for convergence and one-step recovery

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
  • at least three sources
  • a scene preset for the example