Scientific Machine Learning:
Sparse Identification of Nonlinear Dynamics

A measured trajectory is the solution of a differential equation that nobody has written down. The previous notebook, Sparse Regression for Equation Discovery, showed how to pick the few terms of an algebraic law out of a library of candidates. This notebook puts a time derivative on the left-hand side. The data are the states of a system sampled in time; the unknown is the function that maps the state to its rate of change; and the claim, which holds for a great many physical systems, is that this function is a short combination of simple terms. The method that follows from this claim is called SINDy, sparse identification of nonlinear dynamics, and in its simplest form it is the sequential thresholded least squares of the previous notebook applied once per state variable.


What is new is not the regression but what has to be done before it. A derivative has to be estimated from measurements, and that step decides the outcome more often than the regression does. The notebook first identifies oscillators and a chaotic system from exact data, where the derivative is harmless and the method works in a few lines; then it adds measurement noise and watches the identification fail, traces the failure to the derivative, and spends the middle chapters on the remedies: smoothing, the integral formulation that avoids the derivative altogether, and a neural network that interpolates the noisy data and is differentiated exactly, which ties discovery back to the physics-informed networks of the earlier notebooks. It closes by extending the library to spatial derivatives and identifying two partial differential equations.


Learning Objectives

After studying this notebook, you should be able to

  • distinguish parameter identification, where the form of the equation is known, from structure discovery, where it is not, and write the SINDy problem $\dot X = \Phi(X)\,\Theta$;
  • identify an ordinary differential equation from a trajectory with a polynomial library and sequential thresholded least squares;
  • explain why a finite difference of noisy data amplifies the noise by $1/\Delta t$, and estimate a derivative by local polynomial smoothing instead;
  • explain which part of the regression is harmed by noise in the derivative and which by noise in the library, and what smoothing each requires;
  • derive the weak form of a dynamical system with compactly supported test functions, implement it, and say why it tolerates noise better than the strong form;
  • use a neural network fitted to noisy data, differentiated by automatic differentiation, as the input to sparse regression;
  • extend the library to spatial derivatives and identify a partial differential equation from a space–time field; and
  • validate an identified equation by simulating it and comparing with the data.

Setup

NumPy, Matplotlib, the ODE integrator and the Savitzky–Golay filter from SciPy. PyTorch is imported in Chapter 5, where it is first needed.

In [ ]:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
from scipy.signal import savgol_filter

Sparse regression

The sequential thresholded least squares of Sparse Regression for Equation Discovery, unchanged except for a guard that stops the loop if every coefficient has been removed, and a helper print_model that prints an identified system one equation per line.

In [ ]:
def stls(Phi, y, threshold, n_iter = 10):
    theta = np.linalg.inv(Phi.T @ Phi) @ Phi.T @ y
    for it in range(n_iter):
        small = np.abs(theta) < threshold                   # coefficients to drop
        big = ~small                                        # columns to keep
        theta[small] = 0
        if np.sum(big) == 0:
            break
        Phi_big = Phi[:, big]
        theta[big] = np.linalg.inv(Phi_big.T @ Phi_big) @ Phi_big.T @ y    # refit the survivors
    return theta

def print_model(Theta, names, lhs):                         # one equation per column of Theta
    for j in range(Theta.shape[1]):
        terms = ['%+.4f %s' % (Theta[k, j], names[k]) for k in range(len(names)) if abs(Theta[k, j]) > 1e-10]
        print('%s = %s' % (lhs[j], ' '.join(terms) if terms else '0'))




1. From Parameter Identification to Structure Discovery

1.1. Two Kinds of Inverse Problem

Physics-Informed Neural Networks solved inverse problems: the form of the governing equation was known, one or two of its coefficients were not, and a network trained on observations and on the residual recovered them. The thermal diffusivity of a plate, the damping of a beam, the infection rate of an epidemic were all found this way. In every case the equation was written down first, and the data filled in the numbers.


Structure discovery drops the first step. The data are the same, a trajectory or a field sampled in time, but the equation is not given; what is given is a list of terms that might appear in it, and the task is to find which do and with what coefficients. The difference matters in practice. A parameter-identification problem with the wrong form returns a confident wrong answer, because a network can always lower a residual by adjusting the coefficients it is offered. A discovery problem can return "none of these", or a combination nobody expected. The price is that discovery needs more from the data: enough variety in the states to separate the candidates from one another, and enough accuracy in the derivatives to see which candidates the rate of change actually depends on.


The two problems meet in the middle. A discovered equation can be handed to a PINN as a known form for refinement, and a PINN's failure to fit data with a given form is a signal that discovery is needed. This notebook stays on the discovery side.


1.2. The SINDy Formulation

Consider a system whose state at time $t$ is a vector of $n$ quantities, $x(t) = (x_1(t), \ldots, x_n(t))$, and suppose that it obeys an autonomous system of ordinary differential equations,


$$ \frac{dx}{dt} = f(x) , $$


with $f$ unknown. The aim is to find $f$ from measurements of $x(t)$. The formulation goes in four steps.


Step 1: the data. What is measured is the state at $m$ sampling times $t_1, \ldots, t_m$. Stacking the measurements as rows gives the data matrix


$$ X = \begin{bmatrix} x_1(t_1) & x_2(t_1) & \cdots & x_n(t_1) \\ x_1(t_2) & x_2(t_2) & \cdots & x_n(t_2) \\ \vdots & \vdots & & \vdots \\ x_1(t_m) & x_2(t_m) & \cdots & x_n(t_m) \end{bmatrix} \in \mathbb{R}^{m\times n} , $$


one row per sampling time and one column per state variable. For a pendulum recorded by a motion sensor, $n = 2$ (angle and angular velocity) and $m$ is the number of frames; this is the only input the method has.


Step 2: the derivatives. The left-hand side of the equation, $\dot x$, is not measured, but it can be computed from $X$: each column of $X$ is a time series, and differencing it in time, for instance by the central difference $\dot x_j(t_i) \approx (x_j(t_{i+1}) - x_j(t_{i-1}))/2\Delta t$, gives an estimate of $\dot x_j$ at every sampling time. Stacking these in the same way gives $\dot X \in \mathbb{R}^{m\times n}$, whose $(i, j)$ entry is the rate of change of the $j$th state variable at time $t_i$. This step is simple on exact data and treacherous on noisy data, which is why Chapter 3 is devoted to it.


$$\dot x_j(t_i) \approx \frac{(x_j(t_{i+1}) - x_j(t_{i-1}))}{2\Delta t}$$


Step 3: the library. The unknown $f$ is sought as a combination of candidate functions of the state, $b_1(x), \ldots, b_d(x)$, typically the constant and the monomials up to some degree: for $n = 2$ and degree two, $1, x_1, x_2, x_1^2, x_1x_2, x_2^2$. Evaluating every candidate at every sample, that is, at every row of $X$, gives the $m\times d$ design matrix


$$ \Phi(X) = \begin{bmatrix} | & | & & | \\ b_1(X) & b_2(X) & \cdots & b_d(X) \\ | & | & & | \end{bmatrix} , $$


exactly the library of the previous notebook, with the rows of $X$ in place of the scalar inputs $x_i$.


Step 4: the regression. The hypothesis that every component of $f$ is a short combination of the candidates is the matrix equation


$$ \dot X = \Phi(X)\,\Theta , \qquad \begin{bmatrix} | & & | \\ \dot x_1 & \cdots & \dot x_n \\ | & & | \end{bmatrix} = \begin{bmatrix} | & | & & | \\ b_1(X) & b_2(X) & \cdots & b_d(X) \\ | & | & & | \end{bmatrix} \begin{bmatrix} | & & | \\ \theta_1 & \cdots & \theta_n \\ | & & | \end{bmatrix} , $$


in which the coefficient matrix $\Theta$ is $d\times n$ and sparse. Reading it column by column shows that it is nothing new. The $j$th column says


$$ \dot x_j = \Phi(X)\,\theta_j , $$


where $\dot x_j$, the $j$th column of $\dot X$, is a vector of $m$ numbers computed in Step 2, and $\Phi(X)$ is the $m\times d$ matrix built in Step 3. With $y = \dot x_j$ this is the problem $y = \Phi\theta$ of Sparse Regression for Equation Discovery: $m$ observations, $d$ candidates, a sparse coefficient vector $\theta_j$ to be found, and sequential thresholded least squares,


$$ \theta_j \leftarrow (\Phi^T\Phi)^{-1}\Phi^T\dot x_j , \qquad \text{threshold, refit, repeat,} $$


to find it. The $j$th equation of the system is then $\dot x_j = \sum_k (\theta_j)_k\, b_k(x)$, with only the few surviving terms. For $n$ state variables this is $n$ independent regressions on the same matrix $\Phi(X)$, one per column of $\dot X$. The library is shared; the sparsity patterns are not.

Remark (symbols). The SINDy papers write the library as $\Theta(X)$ and the coefficients as $\Xi$. This notebook keeps the symbols of Machine Learning and of the previous notebook, $\Phi$ for the design matrix and $\theta$ for a coefficient vector, so that $\Theta$ here is the matrix whose columns are the coefficient vectors $\theta_1, \ldots, \theta_n$, one per equation.


To summarize what has to be supplied: the states, which are measured; the derivatives, which are computed from the states; and the library, which is chosen, and Chapters 2 to 6 show the choice being made for several systems. Of the three, the derivatives decide the outcome most often; Chapter 2 first shows the method at work on exact data, where they are easy, and Chapter 3 shows what happens when they are not.




2. SINDy for Ordinary Differential Equations

2.1. A Damped Oscillator

The first system is one whose answer is known, so that every step can be checked: a damped linear oscillator, mass, spring and dashpot, whose equation of motion is second order in the position $x$,


$$ \ddot x + 0.1\,\dot x + x = 0 . $$


SINDy works with first-order systems, so the velocity $v = \dot x$ is introduced as a second state variable. Then $\dot x = v$ by definition, and the equation of motion gives $\dot v = \ddot x = -x - 0.1\,v$. The two together are a first-order system in the state vector $z = (x, v)$,


$$ \frac{d}{dt}\begin{bmatrix} x \\ v \end{bmatrix} = \begin{bmatrix} v \\ -x - 0.1\,v \end{bmatrix} = \begin{bmatrix} 0 & 1 \\ -1 & -0.1 \end{bmatrix} \begin{bmatrix} x \\ v \end{bmatrix} , \qquad\text{that is}\qquad \dot z = f(z) = A z , $$


and because the system is linear, $f$ is a matrix. In the notation of Section 1.2, with $n = 2$ state variables sampled at $m = 2000$ times, the states fill the $2000\times 2$ matrix $X$, whose rows are $(x(t_i), v(t_i))$, and their derivatives fill $\dot X$. A library of the constant and the monomials up to degree three has $d = 10$ columns, and the equation $\dot X = \Phi(X)\,\Theta$ that SINDy has to recover reads


$$ \begin{bmatrix} | & | \\ \dot x & \dot v \\ | & | \end{bmatrix} = \begin{bmatrix} | & | & | & | & & | \\ 1 & x & v & x^2 & \cdots & v^3 \\ | & | & | & | & & | \end{bmatrix} \begin{bmatrix} 0 & 0 \\ 0 & -1 \\ 1 & -0.1 \\ 0 & 0 \\ \vdots & \vdots \\ 0 & 0 \end{bmatrix} , $$


so that the true $\Theta$ is a $10\times 2$ matrix with three nonzero entries: the rows of $A^T$ sitting in the positions of the columns $x$ and $v$, and zeros everywhere else. The task is to find those three entries, and the seven zero rows, from $X$ and $\dot X$ alone. The trajectory is integrated from $x = 2$, $v = 0$ for $20$ time units at $\Delta t = 0.01$. The data are exact in this chapter, so a plain central difference serves for the derivatives; noise arrives in Chapter 3.

In [ ]:
def oscillator(t, z):
    x, v = z
    return [v, -x - 0.1*v]

dt = 0.01
t = np.arange(0, 20, dt)
X = solve_ivp(oscillator, (0, 20), [2.0, 0.0], t_eval = t, rtol = 1e-10, atol = 1e-10).y.T    # columns: x, v

plt.figure(figsize = (6, 4))
plt.plot(t, X[:, 0], 'b', label = 'x')
plt.plot(t, X[:, 1], 'r', label = 'v')
plt.xlabel('t')
plt.ylabel('X')
plt.xlim([0, 20])
plt.legend()
plt.grid(True)
plt.show()

print('X shape :', X.shape)
No description has been provided for this image
X shape : (2000, 2)

The derivatives

$\dot X$ is not part of the data. Each column of $X$ is differenced in time with a central difference, which is what np.gradient computes, and the two columns of $\dot X$ are plotted. The first column of $\dot X$ has the shape of the second column of $X$: the data already show $\dot x = v$, and the regression will confirm it.

In [ ]:
dX = np.zeros_like(X)
dX[:, 0] = np.gradient(X[:, 0], dt)                        # central difference in time
dX[:, 1] = np.gradient(X[:, 1], dt)

plt.figure(figsize = (6, 4))
plt.plot(t, dX[:, 0], 'b', label = 'dx/dt')
plt.plot(t, dX[:, 1], 'r', label = 'dv/dt')
plt.xlabel('t')
plt.ylabel('dX/dt (finite difference)')
plt.xlim([0, 20])
plt.legend()
plt.grid(True)
plt.show()

print('dX shape :', dX.shape)
No description has been provided for this image
dX shape : (2000, 2)

The library

The library is every monomial in the state variables up to a chosen degree. For two variables and degree three that is

$1$, $x$, $v$, $x^2$, $xv$, $v^2$, $x^3$, $x^2v$, $xv^2$, $v^3$, ten columns, of which the true system uses three. The function builds the columns by nested loops over the variables and names them so that the printed result can be read as an equation.

In [ ]:
def library(X, degree):
    m, n = X.shape
    columns = [np.ones((m, 1))]
    names = ['1']
    var = ['x', 'v', 'w'][:n]
    if degree >= 1:
        for i in range(n):
            columns.append(X[:, i:i+1])
            names.append(var[i])
    if degree >= 2:
        for i in range(n):
            for j in range(i, n):
                columns.append(X[:, i:i+1]*X[:, j:j+1])
                names.append(var[i] + var[j])
    if degree >= 3:
        for i in range(n):
            for j in range(i, n):
                for k in range(j, n):
                    columns.append(X[:, i:i+1]*X[:, j:j+1]*X[:, k:k+1])
                    names.append(var[i] + var[j] + var[k])
    return np.hstack(columns), names

Phi, names = library(X, 3)
print('library columns:', names)
library columns: ['1', 'x', 'v', 'xx', 'xv', 'vv', 'xxx', 'xxv', 'xvv', 'vvv']

Identification

One sparse regression per state variable, with threshold $0.05$.

In [ ]:
Theta = np.zeros((len(names), 2))
for j in range(2):
    Theta[:, j] = stls(Phi, dX[:, j], threshold = 0.05)

print_model(Theta, names, ['dx/dt', 'dv/dt'])
dx/dt = +1.0000 v
dv/dt = -1.0000 x -0.1000 v

The identified system is $\dot x = 1.0000\,v$ and $\dot v = -1.0000\,x - 0.1000\,v$, the equations that generated the data, to four decimals. The seven quadratic and cubic columns were offered and refused. What the thresholding did is visible in the least-squares fit without it.

In [ ]:
Theta_ls = np.linalg.inv(Phi.T @ Phi) @ Phi.T @ dX
print('least squares without thresholding (dv/dt column):')
for k in range(len(names)):
    print('%6s : %10.5f' % (names[k], Theta_ls[k, 1]))
least squares without thresholding (dv/dt column):
     1 :   -0.00001
     x :   -0.99999
     v :   -0.09999
    xx :    0.00000
    xv :    0.00000
    vv :    0.00000
   xxx :    0.00000
   xxv :    0.00000
   xvv :    0.00000
   vvv :   -0.00000

Even on exact data, least squares puts coefficients of order $10^{-5}$ to $10^{-6}$ on the nonlinear columns, the residue of the finite difference's truncation error. They are a hundred times below the threshold and the first pass removes them all. This is the easy case, and it establishes the pattern: a library wider than the truth, a threshold between the true coefficients and the noise, and a refit that returns the true coefficients once the noise columns are gone.


2.2. The Van der Pol Oscillator

The Van der Pol oscillator is nonlinear and has a cubic term the linear library would miss,


$$ \dot x = v , \qquad \dot v = \mu\,(1 - x^2)\,v - x , \qquad \mu = 2 , $$


whose solutions spiral out from near the origin onto a limit cycle. In the monomial library the right-hand side of $\dot v$ is $2v - 2x^2v - x$, three terms of the ten.

In [ ]:
def vanderpol(t, z):
    x, v = z
    return [v, 2*(1 - x**2)*v - x]

t = np.arange(0, 20, 0.01)
X = solve_ivp(vanderpol, (0, 20), [0.5, 0.0], t_eval = t, rtol = 1e-10, atol = 1e-10).y.T

dX = np.zeros_like(X)
dX[:, 0] = np.gradient(X[:, 0], 0.01)
dX[:, 1] = np.gradient(X[:, 1], 0.01)

plt.figure(figsize = (9, 4))
plt.subplot(1, 2, 1)
plt.plot(t, X[:, 0], 'b', label = 'x')
plt.plot(t, X[:, 1], 'r', label = 'v')
plt.xlabel('t')
plt.xlim([0, 20])
plt.legend()
plt.grid(True)
plt.subplot(1, 2, 2)
plt.plot(X[:, 0], X[:, 1], 'k', linewidth = 1)
plt.xlabel('x')
plt.ylabel('v')
plt.grid(True)
plt.show()

Phi, names = library(X, 3)
Theta = np.zeros((len(names), 2))
for j in range(2):
    Theta[:, j] = stls(Phi, dX[:, j], threshold = 0.1)
print_model(Theta, names, ['dx/dt', 'dv/dt'])
No description has been provided for this image
dx/dt = +0.9999 v
dv/dt = -0.9999 x +1.9993 v -1.9990 xxv

The trajectory shows the relaxation oscillation, slow drifts in $x$ punctuated by fast swings of $v$, and the phase portrait shows the spiral from $(0.5, 0)$ onto the closed curve. SINDy returns $\dot v = -0.9999\,x + 1.9993\,v - 1.9990\,x^2v$: the three true terms, coefficients within $0.05\%$, and the term $x^2v$, which is not a function a person would guess from the time series, picked out of the library because the data demanded it. The threshold was raised to $0.1$ because the finite-difference error is larger on the fast swings, and the smallest true coefficient is $1$, so there was room.


A coefficient table is not the final test of an identified equation. The final test is whether the equation, integrated from the same initial condition, reproduces the trajectory. The identified right-hand side is assembled from the library and the coefficient matrix and handed to the integrator.

In [ ]:
def identified(t, z):
    Phi_z, _ = library(np.array(z).reshape(1, -1), 3)
    return (Phi_z @ Theta).ravel()

X_id = solve_ivp(identified, (0, 20), [0.5, 0.0], t_eval = t, rtol = 1e-10, atol = 1e-10).y.T

plt.figure(figsize = (6, 4))
plt.plot(t, X[:, 0], 'k', alpha = 0.3, linewidth = 4, label = 'True x(t)')
plt.plot(t, X_id[:, 0], 'r--', label = 'Identified model')
plt.xlabel('t')
plt.ylabel('x')
plt.xlim([0, 20])
plt.legend()
plt.grid(True)
plt.show()

print('max difference between true and identified trajectory: %.2e' % np.max(np.abs(X - X_id)))
No description has been provided for this image
max difference between true and identified trajectory: 7.84e-03

The identified model and the true one are indistinguishable over the twenty time units, with a maximum difference of $8\times10^{-3}$, which is the accumulated effect of the $0.05\%$ coefficient errors over several periods. This simulate-and-compare step is cheap and should always be done: it catches a model that has the right terms with coefficients slightly off, which looks fine in a table and drifts out of phase in a simulation, and it catches a model that is unstable, which no table reveals.


2.3. The Lorenz System

The Lorenz system is the classical test of SINDy, three coupled equations with two quadratic terms and chaotic solutions,


$$ \begin{align*} \dot x &= 10\,(y - x) \\ \dot y &= x\ (28 - z) - y \\ \dot z &= xy - \tfrac{8}{3}\,z \end{align*} $$


sampled for $20$ time units at $\Delta t = 0.002$. Chaos is not an obstacle to identification; it is an asset, because a chaotic trajectory wanders over a large region of state space and gives the regression the variety it needs to separate the candidates.

In [ ]:
def lorenz(t, z):
    x, y, w = z
    return [10*(y - x), x*(28 - w) - y, x*y - 8/3*w]

dt = 0.002
t = np.arange(0, 20, dt)
X = solve_ivp(lorenz, (0, 20), [-8.0, 7.0, 27.0], t_eval = t, rtol = 1e-10, atol = 1e-10).y.T

ax = plt.figure(figsize = (6, 5)).add_subplot(projection = '3d')
ax.plot(X[:, 0], X[:, 1], X[:, 2], 'k', linewidth = 0.5)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()
No description has been provided for this image

Identification

A quadratic library in three variables has ten columns. The threshold is $0.2$, well below the smallest true coefficient of $1$.

In [ ]:
dX = np.zeros_like(X)
for j in range(3):
    dX[:, j] = np.gradient(X[:, j], dt)

Phi, names_L = library(X, 2)
names_L = [n.replace('v', 'y').replace('w', 'z') for n in names_L]          # Lorenz variables are x, y, z

Theta = np.zeros((len(names_L), 3))
for j in range(3):
    Theta[:, j] = stls(Phi, dX[:, j], threshold = 0.2)
print_model(Theta, names_L, ['dx/dt', 'dy/dt', 'dz/dt'])
dx/dt = -9.9990 x +9.9990 y
dy/dt = +27.9924 x -0.9986 y -0.9998 xz
dz/dt = -2.6663 z +0.9999 xy

The identified system is


$$ \begin{aligned} \dot x &= -9.999\,x + 9.999\,y , \\ \dot y &= 27.992\,x - 0.999\,y - 1.000\,xz , \\ \dot z &= -2.666\,z + 1.000\,xy , \end{aligned} \qquad\text{against}\qquad \begin{aligned} \dot x &= -10\,x + 10\,y , \\ \dot y &= 28\,x - y - xz , \\ \dot z &= -\tfrac{8}{3}\,z + xy . \end{aligned} $$


All seven terms are found with coefficients within $0.03$ of the truth, and the three remaining columns, $x^2$, $y^2$, $yz$, and the constant are absent. This is the result that made SINDy well known, and on clean data it is easy. The notebook now makes it hard, by adding measurement noise; the first casualty is the derivative, and that is where the next chapter begins.




3. Noise

3.1. Finite Differences Amplify Noise

Every derivative in Chapter 2 was a central difference of exact data, and the identified coefficients were correct to four decimals. Measured data are not exact, and the first thing noise does to SINDy is to pass through that difference. PINN: Derivatives by Automatic Differentiation and Finite Differences derived the central difference


$$ \dot{x}(t_i) \approx \frac{x_{i+1} - x_{i-1}}{2\Delta t} $$


and showed its truncation error to be $O(\Delta t^2)$: on an exact signal, a smaller step is a better derivative. On a measured signal the opposite pull appears. If each sample carries an independent error of standard deviation $\sigma$, the difference $x_{i+1} - x_{i-1}$ carries an error of standard deviation $\sqrt{2}\sigma$, and dividing by $2\Delta t$ gives a derivative error of


$$ \sigma_{\dot x} = \frac{\sqrt{2}\,\sigma}{2\Delta t} = \frac{\sigma}{\sqrt{2}\,\Delta t} . $$


The noise is amplified by $1/\Delta t$. A signal sampled at $\Delta t = 0.01$ with $1\%$ noise yields a derivative with about $70\%$ noise. The test signal is a decaying sine, the kind of signal the oscillator of Section 2.1 produces,


$$ x(t) = e^{-0.1t}\sin t , \qquad \dot x(t) = e^{-0.1t}\bigl(\cos t - 0.1\sin t\bigr) , $$


sampled at $\Delta t = 0.01$ for $0 \le t \le 10$ with Gaussian noise of standard deviation $0.01$ added to $x$. The exact derivative is kept for comparison.

In [ ]:
np.random.seed(0)
dt = 0.01
t = np.arange(0, 10, dt)
x_clean = np.sin(t)*np.exp(-0.1*t)
dx_clean = np.cos(t)*np.exp(-0.1*t) - 0.1*np.sin(t)*np.exp(-0.1*t)

x = x_clean + 0.01*np.random.randn(len(t))              # 1 % noise

plt.figure(figsize = (6, 4))
plt.plot(t, x_clean, 'k', alpha = 0.3, linewidth = 4, label = 'Clean signal')
plt.plot(t, x, 'b.', markersize = 1, label = 'Measured (1 % noise)')
plt.xlabel('t')
plt.ylabel('x')
plt.xlim([0, 10])
plt.legend()
plt.grid(True)
plt.show()
No description has been provided for this image

The measurement looks clean. The noise is a slight fuzz on a curve of amplitude close to one, and nobody would hesitate to use these data as they stand. The central difference of the same data is shown next.

In [ ]:
dx_fd = np.gradient(x, dt)                                # central difference

plt.figure(figsize = (6, 4))
plt.plot(t, dx_clean, 'k', alpha = 0.3, linewidth = 4, label = 'True derivative')
plt.plot(t, dx_fd, 'r', alpha = 0.6, linewidth = 0.8, label = 'Finite difference')
plt.xlabel('t')
plt.ylabel('dx/dt')
plt.xlim([0, 10])
plt.ylim([-3, 3])
plt.legend()
plt.grid(True)
plt.show()

print('noise in x       : %.4f' % np.std(x - x_clean))
print('error in dx/dt   : %.4f   (noise/(sqrt 2 dt) = %.4f)' % (np.std(dx_fd - dx_clean), 0.01/(np.sqrt(2)*dt)))
No description has been provided for this image
noise in x       : 0.0099
error in dx/dt   : 0.6935   (noise/(sqrt 2 dt) = 0.7071)

The derivative is buried. The true $\dot x$ has amplitude about one; the finite difference scatters over $\pm 2$ with a standard deviation of $0.69$, which is what the formula predicts, $0.01/(\sqrt{2}\times0.01) = 0.71$. The $1\%$ noise in $x$ has become $70\%$ noise in $\dot x$, and a regression on this derivative would be a regression on noise. Coarsening the sampling helps the noise and hurts the truncation error, and the table shows both.

In [ ]:
print('   dt   | FD error (clean) | FD error (noisy)')
for step in [1, 2, 5, 10, 20, 50]:
    tt = t[::step]
    e_clean = np.std(np.gradient(x_clean[::step], dt*step) - dx_clean[::step])
    e_noisy = np.std(np.gradient(x[::step], dt*step) - dx_clean[::step])
    print(' %5.2f  | %14.4f   | %14.4f' % (dt*step, e_clean, e_noisy))
   dt   | FD error (clean) | FD error (noisy)
  0.01  |         0.0001   |         0.6935
  0.02  |         0.0001   |         0.3560
  0.05  |         0.0006   |         0.1472
  0.10  |         0.0018   |         0.0773
  0.20  |         0.0054   |         0.0534
  0.50  |         0.0263   |         0.0372

On the clean signal the error grows as $\Delta t^2$, from $10^{-4}$ at $\Delta t = 0.01$ to $0.026$ at $\Delta t = 0.5$. On the noisy signal it falls as $1/\Delta t$, from $0.69$ to $0.037$, and the best value in the table, at the coarsest step, is still $4\%$ of the signal's derivative. There is no good step: a fine step resolves the signal and amplifies the noise, a coarse step suppresses the noise and loses the signal. The finite difference uses two points and is at the mercy of both; the way out is to use many.


3.2. Smoothing Before Differentiating

Noise averages out, and a derivative estimated from many points averages it. The Savitzky–Golay filter does this with the least squares of Machine Learning. Around the sample $t_i$ take a window of $w$ consecutive samples, $w$ odd, so that $h = (w - 1)/2$ samples lie on each side, and fit them with a low-degree polynomial in the local time $s = t - t_i$,


$$ x(t_i + s) \approx p(s) = c_0 + c_1 s + c_2 s^2 + c_3 s^3 , \qquad \begin{bmatrix} x_{i-h} \\ \vdots \\ x_{i+h} \end{bmatrix} \approx \begin{bmatrix} 1 & s_{-h} & s_{-h}^2 & s_{-h}^3 \\ \vdots & \vdots & \vdots & \vdots \\ 1 & s_{h} & s_{h}^2 & s_{h}^3 \end{bmatrix} \begin{bmatrix} c_0 \\ c_1 \\ c_2 \\ c_3 \end{bmatrix} , \qquad s_k = k\,\Delta t , $$


a polynomial regression with $w$ observations and four coefficients, solved by the normal equation $c = (\Phi^T\Phi)^{-1}\Phi^T x$. The fitted polynomial is then evaluated at the center of the window, $s = 0$, where all the higher powers vanish:


$$ \begin{align*} x_i &\approx p(0) = c_0 ,\\ \\ \dot x_i &\approx p'(0) = \bigl[c_1 + 2c_2 s + 3c_3 s^2\bigr]_{s = 0} = c_1 . \end{align*} $$


The constant term is a smoothed version of the sample and the linear coefficient is the derivative estimate: the slope of the best-fitting cubic at the middle of the window. Sliding the window one sample along and repeating gives the derivative everywhere. Because the least-squares solution is linear in the data, $c_1$ is a fixed weighted sum of the $w$ samples in the window, with weights that depend only on $w$ and the degree; the filter is therefore a convolution, and savgol_filter applies it in one call. Each derivative is now an average over $w$ samples instead of a difference of two, so the noise is reduced by roughly $\sqrt{w}$, and the truncation error is set by how well a cubic follows the signal over the window rather than by $\Delta t$.


One window

The algebra above describes a single window. The picture below is that window and nothing else: five measurements, the cubic fitted to them, and the value and the slope of that cubic at the centre.

The demonstration uses a window of $w = 5$ samples, short enough that every point and every coefficient can be counted; the filter used everywhere else in this notebook keeps the same cubic and widens the window to $51$ or $101$ samples. Only the number of points changes.

In [ ]:
np.random.seed(0)
k = np.arange(1, 11)                                            # the sample index
u = 300 - 160*np.exp(-(k - 6)**2/5) + 25*np.random.randn(10)    # a noisy signal

s = np.array([-2, -1, 0, 1, 2])                                 # local coordinate of the 5 points around k = 6
c = np.polyfit(s, u[3:8], 3)                                    # cubic fit: p(s) = c3 s^3 + c2 s^2 + c1 s + c0

ss = np.linspace(-2, 2, 100)

plt.figure(figsize = (6, 4))
plt.plot(k, u, 'o-', color = 'gray', alpha = 0.5)
plt.plot(k[3:8], u[3:8], 'bo-', alpha = 0.5, label = 'the 5 points in the window')
plt.plot(6 + ss, np.polyval(c, ss), 'r', label = 'cubic fit to those points')
plt.plot(6, c[-1], 'ro', label = 'smoothed value  $p(0) = c_0$')
plt.plot(6 + ss, c[-1] + c[-2]*ss, 'r--', label = "slope at the centre  $p'(0) = c_1$")
plt.xticks(k)
plt.ylim([0, 500])
plt.xlabel('sample index')
plt.ylabel('measured value')
plt.legend()
plt.grid(True, alpha = 0.3)
plt.show()

print('p(s) = %.2f s^3 + %.2f s^2 %.2f s + %.1f' % tuple(c))
print('measured value at k = 6 : %.1f | smoothed value c0 : %.1f | slope c1 : %.2f' % (u[5], c[-1], c[-2]))
print('savgol_filter at k = 6  : value %.1f | derivative %.2f' % (savgol_filter(u, 5, 3)[5], savgol_filter(u, 5, 3, deriv = 1)[5]))
No description has been provided for this image
p(s) = -1.16 s^3 + 26.95 s^2 -10.31 s + 152.6
measured value at k = 6 : 115.6 | smoothed value c0 : 152.6 | slope c1 : -10.31
savgol_filter at k = 6  : value 152.6 | derivative -10.31

Five measurements go in and four coefficients come out. For the window drawn above they are


$$ p(s) = -1.16\,s^3 + 26.95\,s^2 - 10.31\,s + 152.6 , $$


and the two that matter are read off without any further work. The constant is the fitted curve at the centre of the window, $p(0) = c_0 = 152.6$, and it replaces the measurement there, $115.6$: the filter has judged that sample to lie $37$ below where its four neighbours say the signal is, and the gap between the grey point and the red one is that correction. The linear coefficient is the slope of the same curve at the same point, $p'(0) = c_1 = -10.3$ per sample, and it is the derivative estimate that the rest of this chapter uses. One fit supplies both, which is why a smoothed value and a smoothed derivative always come from the same window.


Both numbers are exactly what savgol_filter returns for this sample, as the last line of the output confirms. Sliding the fit along the record, one window per sample, is the whole of the filter.

Remark (the degree is not really a second parameter). Fitting the same five points with a quadratic instead returns the same smoothed value, $152.6$, although the cubic coefficient above is not zero. This is exact rather than a coincidence. On a symmetric window the odd powers $s$ and $s^3$ are orthogonal to the even powers $1$ and $s^2$, so $p(0)$ is decided by the even terms alone and raising the degree from $2$ to $3$ cannot change it; by the same argument, raising it from $3$ to $4$ cannot change $p'(0)$. Degrees come in pairs, and the window length is the only choice that really has to be made.


The filter is now compared with the finite difference on the decaying sine of Section 3.1, with a window of $51$ points and a cubic.

In [ ]:
dx_sg = savgol_filter(x, window_length = 51, polyorder = 3, deriv = 1, delta = dt)      # local cubic fit, 51 points

plt.figure(figsize = (9, 3))
plt.subplot(1, 2, 1)
plt.plot(t, dx_clean, 'k', alpha = 0.3, linewidth = 4, label = 'True derivative')
plt.plot(t, dx_sg, 'r', label = 'Savitzky-Golay')
plt.xlabel('t')
plt.ylabel('dx/dt')
plt.xlim([0, 10])
plt.legend()
plt.grid(True)

plt.subplot(1, 2, 2)
plt.plot(t, dx_fd - dx_clean, 'gray', linewidth = 0.5, label = 'Finite difference')
plt.plot(t, dx_sg - dx_clean, 'r', label = 'Savitzky-Golay')
plt.xlabel('t')
plt.ylabel('error')
plt.xlim([0, 10])
plt.ylim([-0.2, 0.2])
plt.legend()
plt.grid(True)
plt.show()

print('error in dx/dt : finite difference %.4f | Savitzky-Golay %.4f' % (np.std(dx_fd - dx_clean), np.std(dx_sg - dx_clean)))
No description has been provided for this image
error in dx/dt : finite difference 0.6935 | Savitzky-Golay 0.0233

The smoothed derivative lies on the true one. The error of the finite difference, in grey, fills the whole band; the Savitzky–Golay error is a thin ripple of standard deviation $0.023$, thirty times smaller. The filter has one parameter, the window length, and the rest of the notebook uses it for every derivative that has to be taken from noisy data.

In [ ]:
print(' window | SG error')
for w in [5, 11, 21, 51, 101, 201, 401]:
    dxw = savgol_filter(x, window_length = w, polyorder = 3, deriv = 1, delta = dt)
    print(' %5d  | %.4f' % (w, np.std(dxw - dx_clean)))
 window | SG error
     5  | 0.9432
    11  | 0.2434
    21  | 0.0897
    51  | 0.0233
   101  | 0.0117
   201  | 0.0063
   401  | 0.0724

A window of $5$ points is worse than the finite difference: a cubic through five points leaves only one degree of freedom for averaging, and its slope is more sensitive to noise than a plain difference of two samples. The error falls steadily to $0.006$ at $201$ points, a window two seconds long on a signal of period about six, and then rises again at $401$ points, where the cubic can no longer follow the curvature of the signal inside a four-second window and the truncation error returns. The window is the step size of Chapter 3 of the derivatives notebook in a new guise, with the same two errors pulling in opposite directions. A window of a tenth to a quarter of the shortest period in the signal is a reasonable starting point, and the Savitzky–Golay filter with a window around $100$ points at $\Delta t$ of $0.002$ to $0.01$ is used for most of what follows.

Remark (the derivative is the weak point). Every error made in this chapter enters the regression of Chapter 2 on the left-hand side, and a library cannot fit noise with a sparse model; the next section shows what that does to the Lorenz identification. In practice the failure of a SINDy run is traced to the derivative more often than to anything else, and the first question to ask of a bad result is how $\dot X$ was obtained. Chapter 4 removes the derivative from the problem altogether, at the cost of a little more algebra.


3.3. Where the Noise Does Its Damage

The filters of Section 3.2 are now applied where they matter, to an identification. The system is the Lorenz system of Section 2.3,


$$ \begin{aligned} \dot x &= 10\,(y - x) , \\ \dot y &= x\,(28 - z) - y , \\ \dot z &= xy - \tfrac{8}{3}\,z , \end{aligned} $$


which was identified to within $0.03$ from exact data. Gaussian noise of standard deviation $0.5$ is now added to every state, a little over $1\%$ of the range of each, and the identification is run three ways, which differ only in where the noise is allowed to remain:

  • Finite-difference derivatives, raw states. Noise in $\dot X$, amplified by $1/\Delta t$, and noise in $\Phi(X)$.
  • Savitzky–Golay derivatives, raw states. Noise in $\dot X$ removed by the filter; noise in $\Phi(X)$ untouched.
  • Savitzky–Golay derivatives, smoothed states. Noise removed from both sides with the same window, so that $\dot X$ and $\Phi(X)$ describe the same smooth signal.

The threshold is raised to $0.5$, still half the smallest true coefficient.

In [ ]:
def lorenz(t, z):
    x, y, w = z
    return [10*(y - x), x*(28 - w) - y, x*y - 8/3*w]

dt = 0.002
t = np.arange(0, 20, dt)
X = solve_ivp(lorenz, (0, 20), [-8.0, 7.0, 27.0], t_eval = t, rtol = 1e-10, atol = 1e-10).y.T

np.random.seed(1)
X_true = X.copy()
X_noisy = X_true + 0.5*np.random.randn(*X_true.shape)        # noise of 0.5 on states of size ~ 10-40

ax = plt.figure(figsize = (6, 5)).add_subplot(projection = '3d')
ax.plot(X_noisy[:, 0], X_noisy[:, 1], X_noisy[:, 2], 'k', linewidth = 0.5)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()
No description has been provided for this image

The attractor is still recognizable, but the thin line of Section 2.3 has become a fuzzy band, and every column of $X$ and of $\Phi(X)$ now carries that fuzz. The three identifications follow, in the order of the list above.

In [ ]:
dX_fd = np.zeros_like(X_noisy)
dX_sg = np.zeros_like(X_noisy)
X_sm = np.zeros_like(X_noisy)
for j in range(3):
    dX_fd[:, j] = np.gradient(X_noisy[:, j], dt)                                                     # finite difference
    dX_sg[:, j] = savgol_filter(X_noisy[:, j], window_length = 101, polyorder = 3, deriv = 1, delta = dt)   # smoothed derivative
    X_sm[:, j] = savgol_filter(X_noisy[:, j], window_length = 101, polyorder = 3)                    # smoothed state, same window

Phi_noisy, _ = library(X_noisy, 2)
Phi_sm, _ = library(X_sm, 2)

Theta_fd = np.zeros((len(names_L), 3))
Theta_sg = np.zeros((len(names_L), 3))
Theta_sm = np.zeros((len(names_L), 3))
for j in range(3):
    Theta_fd[:, j] = stls(Phi_noisy, dX_fd[:, j], threshold = 0.5)
    Theta_sg[:, j] = stls(Phi_noisy, dX_sg[:, j], threshold = 0.5)
    Theta_sm[:, j] = stls(Phi_sm, dX_sg[:, j], threshold = 0.5)

print('finite-difference derivatives, raw states:')
print_model(Theta_fd, names_L, ['dx/dt', 'dy/dt', 'dz/dt'])
print('\nSavitzky-Golay derivatives, raw states:')
print_model(Theta_sg, names_L, ['dx/dt', 'dy/dt', 'dz/dt'])
print('\nSavitzky-Golay derivatives, smoothed states:')
print_model(Theta_sm, names_L, ['dx/dt', 'dy/dt', 'dz/dt'])
finite-difference derivatives, raw states:
dx/dt = -9.5171 x +9.5596 y
dy/dt = +25.3640 x -0.9448 xz
dz/dt = -2.6519 z +0.9948 xy

Savitzky-Golay derivatives, raw states:
dx/dt = -9.6281 x +9.6648 y
dy/dt = +24.8192 x -0.9265 xz
dz/dt = -2.6211 z +0.9836 xy

Savitzky-Golay derivatives, smoothed states:
dx/dt = -10.0294 x +10.0255 y
dy/dt = +28.1216 x -1.0145 y -1.0054 xz
dz/dt = -2.6703 z +1.0051 xy

The first two runs tell the same story: a true term is lost and the surviving coefficients are pulled towards zero, and it makes little difference whether the derivatives were raw or smoothed. The damage, then, is not done by the derivative. It is done by the library. Noise on the left-hand side of the regression, in $\dot X$, is averaged away by the least squares over thousands of samples; noise on the right-hand side, in $\Phi(X)$, is not. A noisy column cannot explain the data as well as the clean one would, so it is given a smaller coefficient than it deserves, and a product of two noisy columns is worse still. The third run smooths the states as well, with the same window that produced the derivatives, and the identification is restored. The pairing is the point: $\dot X$ and $\Phi(X)$ must come from the same smoothed signal, or the regression is asked to relate the rate of change of one function to the values of another.




4. Weak-Form SINDy

4.1. Moving the Derivative onto a Test Function

The derivative was the weak point: a finite difference subtracts two neighbouring noisy samples and divides by a small $\Delta t$, so the noise is amplified. The opposite operation, adding many samples together, averages noise out. The idea of this chapter is to rewrite the equation $\dot x = f(x)$ so that it contains only sums of the data and no differences, and the tool for doing so is integration by parts. It takes three steps.


Step 1: a test function. Start from the equation to be identified,


$$ \dot x = f(x) . $$


Choose a smooth function $\psi(t)$ that is positive inside a short window $[a, b]$ and exactly zero outside it, including at the two ends, $\psi(a) = \psi(b) = 0$. It is called a test function and is chosen by us, not by the data, so everything about it is known exactly, including its derivative $\dot\psi$. Multiply both sides of the equation by $\psi$ and integrate over the window:


$$ \int_a^b \psi\,\dot x\,dt = \int_a^b \psi\,f(x)\,dt . $$


Step 2: move the derivative. The left-hand side still contains $\dot x$, the quantity that cannot be measured well. Integration by parts, $\int u\,dv = uv - \int v\,du$ with $u = \psi$ and $dv = \dot x\,dt$, gives


$$ \int_a^b \psi\,\dot x\,dt = \Bigl[\psi\,x\Bigr]_a^b - \int_a^b \dot\psi\,x\,dt = -\int_a^b \dot\psi\,x\,dt , $$


where the boundary term vanishes because $\psi$ is zero at both ends of the window. The derivative has moved from $x$, which is measured and noisy, onto $\psi$, which is known exactly. The left-hand side is now an integral of the data $x$ weighted by $\dot\psi$: no derivative of the data is ever taken.


Step 3: the regression. Substituting the library expansion $f(x) = \sum_k \theta_k b_k(x)$ on the right-hand side, the equation for one window becomes


$$ -\int_a^b \dot\psi\,x\,dt = \sum_k \theta_k\int_a^b \psi\,b_k(x)\,dt . $$


Everything in it is computable from the data: $x$ at the samples inside the window, the library columns $b_k(x)$ at the same samples, and the known functions $\psi$ and $\dot\psi$. The integrals are evaluated as sums over those samples, multiplied by $\Delta t$. The result is one number on the left and one number per candidate on the right, that is, one linear equation in the unknown coefficients $\theta_k$. Repeating this for $K$ windows, placed at $K$ different centres along the record, gives $K$ such equations, which stack into


$$ \Phi_w\,\theta = y_w , \qquad (\Phi_w)_{ik} = \int \psi_i\,b_k(x)\,dt , \qquad (y_w)_i = -\int \dot\psi_i\,x\,dt , $$


a $K\times d$ linear system of exactly the form $\Phi\theta = y$ that sequential thresholded least squares has solved throughout. Nothing changes in the regression; only the rows have changed their meaning. In the strong form a row is one instant, $\dot x(t_i) = \sum_k \theta_k b_k(x(t_i))$. In the weak form a row is one window, and every entry in it is a weighted sum over all the samples in that window, hundreds of them, so that the noise in each sample is averaged rather than differenced. This is weak-form SINDy, and the word "weak" is used in the same sense as in the finite element method, where equations are enforced in integrated rather than pointwise form.


4.2. The Weak Form at Work

The theory is now applied to the noisy Lorenz data of Section 3.3, the same $X_{\text{noisy}}$ with noise of standard deviation $0.5$, and nothing else: no smoothing of the states and no derivative of the data anywhere. Two things have to be decided before the regression can run, the test functions and the way the integrals are evaluated, and both are settled in the two steps that follow.

The test functions

The test functions are bumps,


$$ \psi(s) = (1 - s^2)^4 , \qquad s = \frac{t - t_i}{w} \in (-1, 1) , $$


and zero outside, with $200$ centres $t_i$ spread evenly over the record and a half-width $w = 0.5$, so that each window covers $500$ samples at $\Delta t = 0.002$. The derivative needed in Step 2 is known exactly, $\dot\psi = -8s(1 - s^2)^3/w$.

Remark (why this test function). Any function that is smooth inside the window and exactly zero outside it will do, and $(1 - s^2)^p$ is the simplest polynomial with that property. The exponent sets how smoothly the function dies away at the edges: with $p = 1$ the derivative $\dot\psi = -2s$ jumps at $s = \pm 1$, which puts large weights on the two end samples and brings some of the finite difference's noise amplification back; with $p = 4$ both $\psi$ and $\dot\psi$ fade to zero smoothly, so the weights are concentrated in the middle of the window and vanish at its ends. A larger exponent narrows the effective window and averages fewer samples. Being a polynomial, $\psi$ has an exact derivative in one line of code, which matters because the derivative of the test function is the only derivative the weak form ever takes.

In [ ]:
def test_functions(t, n_windows, width):        # bumps psi(t) = (1 - s^2)^4 on windows of the given width, and their derivatives
    centers = np.linspace(t[0] + width, t[-1] - width, n_windows)
    psi = np.zeros((n_windows, len(t)))
    dpsi = np.zeros((n_windows, len(t)))
    for i in range(n_windows):
        s = (t - centers[i])/width                                      # local coordinate, -1 < s < 1 inside the window
        inside = np.abs(s) < 1
        psi[i, inside] = (1 - s[inside]**2)**4                          # psi = (1 - s^2)^4, zero outside the window
        dpsi[i, inside] = -8*s[inside]*(1 - s[inside]**2)**3/width      # d psi/dt = d psi/ds * ds/dt, with ds/dt = 1/width
    return psi, dpsi

psi, dpsi = test_functions(t, n_windows = 200, width = 0.5)

plt.figure(figsize = (6, 4))
plt.plot(t, psi[10, :], 'b', label = r'$\psi(t)$')
plt.plot(t, dpsi[10, :], 'r--', label = r'$\dot\psi(t)$')
plt.xlabel('t')
plt.xlim([0, 3])
plt.legend()
plt.grid(True)
plt.show()
No description has been provided for this image

One of the $200$ bumps is drawn with its derivative. The derivative is positive where the bump rises and negative where it falls, and both are zero outside the window. Multiplying the data by $\dot\psi$ and integrating weighs the early part of the window against the late part, which is what a derivative does, but with a weight that spreads over $500$ samples rather than two. The $200$ windows are spaced about $0.1$ apart and each is $1.0$ wide, so they overlap heavily, and each one gives one row of the weak system. These bumps and their derivatives are the only new ingredient; the rest is the regression of Chapter 2.

The weak system

The two integrals of Step 3 are sums over the samples times $\Delta t$, and for all windows at once they are matrix products: the right-hand side $\int\psi_i\,b_k$ is the product of the test functions with the library, $\Phi_w = \psi\,\Phi(X)\,\Delta t$, and the left-hand side $-\int\dot\psi_i\,x$ is the product of the derivatives of the test functions with the states, $y_w = -\dot\psi\,X\,\Delta t$. Two lines build both, and sequential thresholded least squares is then run on $\Phi_w$ and each column of $y_w$ exactly as it was on $\Phi(X)$ and $\dot X$.

In [ ]:
Phi, _ = library(X_noisy, 2)                  # the library at the noisy samples, as in the strong form

Phi_w = (psi @ Phi)*dt                        # integral of psi_i * b_k(x) over every window:  K x d
y_w = -(dpsi @ X_noisy)*dt                    # integral of -dpsi_i * x over every window:    K x n

Theta_weak = np.zeros((len(names_L), 3))
for j in range(3):
    Theta_weak[:, j] = stls(Phi_w, y_w[:, j], threshold = 0.5)
print_model(Theta_weak, names_L, ['dx/dt', 'dy/dt', 'dz/dt'])
dx/dt = -9.9973 x +9.9907 y
dy/dt = +27.9126 x -0.9641 y -0.9978 xz
dz/dt = -2.6664 z +1.0003 xy

Every term is recovered and every coefficient is close to the truth, from data on which the strong form without smoothing lost a term and the strong form with its best smoothing did slightly worse. Nothing was smoothed and nothing was differentiated; the integrals did the averaging. This is the meaning of moving the derivative onto the test function: the noise that a finite difference would have amplified by $1/\Delta t$ is instead summed over $500$ samples with smooth weights, and what reaches the regression is its average. The weak form is not immune to noise: the products of noisy states in the library carry a bias that the integral averages but does not remove, and at a high enough noise level that bias crosses the threshold. But it moves the limit a long way, and in the current practice of equation discovery it is the default.




5. A Neural Network in the Loop

5.1. Interpolate, Then Differentiate

Smoothing filters and test functions are two ways of replacing a noisy signal by a smooth one before taking its derivative. A neural network is a third. A network trained to fit the measured trajectory, $\hat x(t_i) \approx x(t_i)$, is a smooth interpolant whose derivative with respect to its input is available exactly by automatic differentiation, as in every PINN of the earlier notebooks; and because a network with a few thousand parameters cannot follow sample-by-sample noise, the fit is a denoised version of the data. The states are read from the network, the derivatives from autograd, and both go into the sparse regression. This construction, in various forms, underlies several published methods, and it connects discovery back to the tools of Physics-Informed Neural Networks.


The data are the Van der Pol trajectory of Section 2.2 with Gaussian noise of standard deviation $0.1$ on both states, about $3\%$ of their range.

In [ ]:
import torch
import torch.nn as nn

np.random.seed(4)
t_vdp = np.arange(0, 20, 0.01)
X_vdp = solve_ivp(vanderpol, (0, 20), [0.5, 0.0], t_eval = t_vdp, rtol = 1e-10, atol = 1e-10).y.T
X_vdp_noisy = X_vdp + 0.1*np.random.randn(*X_vdp.shape)          # noise of 0.1 on states of size ~ 2-3

plt.figure(figsize = (6, 4))
plt.plot(t_vdp, X_vdp[:, 0], 'k', alpha = 0.3, linewidth = 4, label = 'True x(t)')
plt.plot(t_vdp, X_vdp_noisy[:, 0], 'b.', markersize = 2, label = 'Measured')
plt.xlabel('t')
plt.ylabel('x')
plt.xlim([0, 20])
plt.legend()
plt.grid(True)
plt.show()
No description has been provided for this image

Fitting the network

A $\tanh$ network $1 \to 64 \to 64 \to 64 \to 2$ maps time, scaled to $[0, 1]$, to the two states, and is trained on the mean squared error against the noisy samples for $5000$ epochs of Adam.

In [ ]:
def new_net():
    torch.manual_seed(0)
    return nn.Sequential(nn.Linear(1, 64), nn.Tanh(),
                         nn.Linear(64, 64), nn.Tanh(),
                         nn.Linear(64, 64), nn.Tanh(),
                         nn.Linear(64, 2))

def derivative(u, x):
    return torch.autograd.grad(u, x, torch.ones_like(u), create_graph = True)[0]

t_in = torch.tensor(t_vdp/20, dtype = torch.float32).reshape(-1, 1).requires_grad_(True)      # time scaled to [0, 1]
X_meas = torch.tensor(X_vdp_noisy, dtype = torch.float32)

net = new_net()
optimizer = torch.optim.Adam(net.parameters(), lr = 1e-3)

for epoch in range(1, 5001):
    loss = torch.mean((net(t_in) - X_meas)**2)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    if epoch % 1000 == 0:
        print('epoch %6d | loss %.4e' % (epoch, loss.item()))
epoch   1000 | loss 1.1237e-02
epoch   2000 | loss 9.6509e-03
epoch   3000 | loss 9.5421e-03
epoch   4000 | loss 9.4859e-03
epoch   5000 | loss 9.4530e-03

The loss settles at $9.5\times10^{-3}$, which is the variance of the noise, $0.1^2 = 0.01$: the network has fitted the signal and stopped short of the noise, as a smooth function must. The derivatives follow by autograd, with the chain rule factor $1/20$ for the time scaling.

In [ ]:
X_pred = net(t_in)
dX_pred = torch.zeros_like(X_pred)
dX_pred[:, 0] = derivative(X_pred[:, 0:1], t_in)[:, 0]/20          # chain rule: d/dt = (1/20) d/d(t/20)
dX_pred[:, 1] = derivative(X_pred[:, 1:2], t_in)[:, 0]/20

X_nn = X_pred.detach().numpy()
dX_nn = dX_pred.detach().numpy()

dX_true = np.array([vanderpol(0, z) for z in X_vdp])
dX_fd = np.zeros_like(X_vdp)
dX_fd[:, 0] = np.gradient(X_vdp_noisy[:, 0], 0.01)
dX_fd[:, 1] = np.gradient(X_vdp_noisy[:, 1], 0.01)

plt.figure(figsize = (6, 6))
plt.subplot(2, 1, 1)
plt.plot(t_vdp, dX_true[:, 1], 'k', alpha = 0.3, linewidth = 4, label = 'True dv/dt')
plt.plot(t_vdp, dX_fd[:, 1], 'k', alpha = 0.3, linewidth = 0.5, label = 'Finite difference')
plt.ylabel('dv/dt')
plt.xlim([5, 15])
plt.ylim([-20, 20])
plt.legend()
plt.grid(True)

plt.subplot(2, 1, 2)
plt.plot(t_vdp, dX_true[:, 1], 'k', alpha = 0.3, linewidth = 4, label = 'True dv/dt')
plt.plot(t_vdp, dX_nn[:, 1], 'r--', label = 'Network + autograd')
plt.xlabel('t')
plt.ylabel('dv/dt')
plt.xlim([5, 15])
plt.ylim([-20, 20])
plt.legend()
plt.grid(True)
plt.show()

print('error in dv/dt : finite difference %.3f | network %.3f' % (np.std(dX_fd[:, 1] - dX_true[:, 1]), np.std(dX_nn[:, 1] - dX_true[:, 1])))
No description has been provided for this image
error in dv/dt : finite difference 7.020 | network 0.246

The finite-difference derivative of the noisy velocity is a band of width $\pm 15$ around a true signal of amplitude $10$, with a standard deviation of $7.0$. The network's derivative lies on the true one with an error of $0.25$, nearly thirty times smaller, including at the fast swings where a smoothing window would have had to be short. The network has done, in one fit, what the Savitzky–Golay filter does with a window length chosen by hand, and it has done it without a window length, at the cost of a training run.


5.2. Sparse Regression on the Network

The regression is run twice, on the noisy data with finite differences and on the network's states and derivatives, with the same cubic library and threshold.

In [ ]:
Phi_fd, names = library(X_vdp_noisy, 3)
Phi_nn, _ = library(X_nn, 3)

print('finite differences on noisy data:')
Theta_fd = np.zeros((len(names), 2))
for j in range(2):
    Theta_fd[:, j] = stls(Phi_fd, dX_fd[:, j], threshold = 0.1)
print_model(Theta_fd, names, ['dx/dt', 'dv/dt'])

print('\nnetwork states and autograd derivatives:')
Theta_nn = np.zeros((len(names), 2))
for j in range(2):
    Theta_nn[:, j] = stls(Phi_nn, dX_nn[:, j], threshold = 0.1)
print_model(Theta_nn, names, ['dx/dt', 'dv/dt'])
finite differences on noisy data:
dx/dt = +1.0178 v
dv/dt = -1.0085 x +1.8914 v -1.8927 xxv

network states and autograd derivatives:
dx/dt = +0.9975 v
dv/dt = -1.0029 x +1.9791 v -1.9751 xxv

Both runs find the correct three terms in $\dot v$, because the Van der Pol coefficients are large and the library is small, but the coefficients differ: finite differences give $1.89\,v - 1.89\,x^2v$, attenuated by $5\%$ through the noise in the library columns, while the network gives $1.98\,v - 1.98\,x^2v$, within $1.5\%$. The network's advantage is the same as that of smoothing the states in Section 3.3, obtained with a single interpolant for states and derivatives alike. Its disadvantages are the training time and the risk, on data with sharp features, that the network smooths them away as a wide window would. There is a natural next step that this notebook only names: train the network and the sparse coefficients together, with the identified equation as a residual term in the network's loss, so that the interpolant is pulled towards functions that satisfy a sparse equation. That is a PINN whose physics is being discovered while it trains, and it is where the two halves of this course meet.




6. SINDy for Partial Differential Equations

So far the unknown function $f$ has taken the state $x$ at one instant and returned its rate of change. A partial differential equation has the same shape with one more ingredient: the state is a whole function of space, $u(x, t)$, and its rate of change at a point may depend on the values of $u$ near that point, that is, on the spatial derivatives $u_x$, $u_{xx}$, and so on,


$$ u_t = F(u, u_x, u_{xx}, \ldots) . $$


The heat equation is $u_t = 0.5\,u_{xx}$, the Burgers equation $u_t = -uu_x + 0.1\,u_{xx}$, and the task is to find which of the candidate terms appear in $F$ and with what coefficients. The formulation of Section 1.2 goes through with three changes.


Step 1: the data. The field is sampled on a grid of $n_x$ points in space and $n_t$ instants in time, and stored as a matrix $U$ with one row per instant and one column per grid point,


$$ U = \begin{bmatrix} u(x_1, t_1) & \cdots & u(x_{n_x}, t_1) \\ \vdots & & \vdots \\ u(x_1, t_{n_t}) & \cdots & u(x_{n_x}, t_{n_t}) \end{bmatrix} \in \mathbb{R}^{n_t\times n_x} . $$


Each row is a snapshot of the field at one instant; each column is the time history at one grid point. This is the only input.


Step 2: the derivatives. Two kinds are needed, and the grid supplies both. The time derivative $u_t$ is taken along each column of $U$, that is, down the time axis at a fixed grid point, exactly as $\dot X$ was in Chapter 2. The spatial derivatives $u_x$ and $u_{xx}$ are taken along each row of $U$, that is, across the space axis at a fixed instant. All three are central differences, np.gradient with axis = 0 for time and axis = 1 for space, and all three are arrays of the same shape as $U$.


Step 3: one row per grid point. The regression treats every point $(x_j, t_i)$ of the space–time grid as one observation, because the equation $u_t = F(u, u_x, u_{xx}, \ldots)$ holds at every one of them. The $n_t\times n_x$ arrays $u$, $u_x$, $u_{xx}$ and $u_t$ are therefore flattened into vectors of length $m = n_t n_x$, in the same order, so that the $i$th entry of each refers to the same grid point. The library is built from the flattened arrays, with columns such as $u$, $u^2$, $u_x$, $u_{xx}$, $uu_x$, and the regression is


$$ u_t = \Phi\,\theta , \qquad \Phi \in \mathbb{R}^{m\times d} , \qquad m = n_t n_x , $$


with $m$ rows, one per grid point, and $d$ columns, one per candidate: one sparse regression, since there is one equation, with $u_t$ in the place of $y$. Nothing else changes: the same stls, the same threshold logic, the same reading of the result.

6.1. The Heat Equation

The first field is a solution of the heat equation $u_t = 0.5\,u_{xx}$ on a periodic interval of length $2\pi$ with $n_x = 128$ grid points, computed spectrally so that it is accurate to roundoff, and sampled at $n_t = 201$ instants over $0 \le t \le 5$, long enough for the field to flatten out almost completely. The matrix U has one row per instant and one column per grid point, as in Step 1.

In [ ]:
nx = 128
L = 2*np.pi
x = np.linspace(0, L, nx, endpoint = False)
dx = x[1] - x[0]
k = np.fft.fftfreq(nx, d = dx)*2*np.pi

def heat_rhs(t, u):
    u_hat = np.fft.fft(u)
    return np.real(np.fft.ifft(-0.5*k**2*u_hat))          # u_t = 0.5 u_xx, spectral derivative

t = np.linspace(0, 5, 201)
u0 = np.exp(-(x - np.pi)**2) + 0.5*np.sin(2*x)
U = solve_ivp(heat_rhs, (0, 5), u0, t_eval = t, rtol = 1e-10, atol = 1e-10).y.T      # (time, space)

plt.figure(figsize = (6, 4))
plt.imshow(U.T, extent = [0, 5, 0, L], origin = 'lower', aspect = 'auto', cmap = 'jet')
plt.colorbar()
plt.xlabel('t')
plt.ylabel('x')
plt.show()
No description has been provided for this image

The colour map shows all $201$ rows of U side by side, time running left to right. The animation plays the same rows one at a time: each frame is one snapshot $u(x, t_i)$, and the bump and the ripple spread and fade until the field is nearly flat.

In [ ]:
from matplotlib import animation
from IPython.display import HTML

fig = plt.figure(figsize = (6, 4))
line = plt.plot(x, U[0], 'k')[0]
title = plt.title('t = 0')
plt.xlabel('x')
plt.ylabel('u(x, t)')
plt.xlim([0, L])
plt.ylim([U.min() - 0.1, U.max() + 0.1])
plt.grid(True)
plt.close()                                                 # the frames are shown by the animation, not here

def update(i):                                              # redraw the line and the title for frame i
    line.set_ydata(U[i])
    title.set_text('t = %.2f' % t[i])
    return line, title

anim = animation.FuncAnimation(fig, update, frames = range(0, len(t), 2), interval = 50)     # every second snapshot
HTML(anim.to_jshtml())
Out[ ]:
No description has been provided for this image

A library of derivatives

Eight candidates are offered,


$$ b_1 = 1 , \quad b_2 = u , \quad b_3 = u^2 , \quad b_4 = u_x , \quad b_5 = u_{xx} , \quad b_6 = uu_x , \quad b_7 = uu_{xx} , \quad b_8 = u_x^2 , $$


enough to express the heat equation ($b_5$ alone), the Burgers equation ($b_5$ and $b_6$) and several others. The function pde_library does Steps 2 and 3 at once, in four moves.

First, the derivatives. np.gradient(U, dx, axis = 1) differences each row of $U$ across the space axis and returns $u_x$ on the whole grid; applying it twice gives $u_{xx}$. np.gradient(U, dt, axis = 0) differences each column down the time axis and returns $u_t$. All of these are $n_t\times n_x$ arrays, like $U$ itself.

Second, the flattening. ravel unrolls an $n_t\times n_x$ array into a vector of length $m = n_t n_x$, row after row, so that the first $n_x$ entries are the first snapshot, the next $n_x$ the second, and so on. Because the same ravel is applied to $u$, $u_x$, $u_{xx}$ and $u_t$, the $i$th entry of each vector refers to the same grid point.

Third, the products. Columns such as $uu_x$ are formed by multiplying the flattened vectors entry by entry, which is the value of the product at each grid point.

Fourth, the stacking. np.column_stack places the eight vectors side by side as the columns of $\Phi$, and u_t is returned separately as the left-hand side $y$. The result is a regression with $m = 201\times128 = 25728$ rows, one per grid point, and $d = 8$ columns, one per candidate; the true law uses one of them.

In [ ]:
def pde_library(U, dx, dt):
    u = U.ravel()                                                        # (n_t, n_x) -> one entry per grid point
    u_x = np.gradient(U, dx, axis = 1).ravel()                           # along the space axis, at every instant
    u_xx = np.gradient(np.gradient(U, dx, axis = 1), dx, axis = 1).ravel()
    u_t = np.gradient(U, dt, axis = 0).ravel()                           # along the time axis, at every grid point
    Phi = np.column_stack([np.ones_like(u), u, u**2, u_x, u_xx, u*u_x, u*u_xx, u_x**2])
    names = ['1', 'u', 'u^2', 'u_x', 'u_xx', 'u u_x', 'u u_xx', 'u_x^2']
    return Phi, u_t, names

Phi, u_t, names = pde_library(U, dx, t[1] - t[0])
theta = stls(Phi, u_t, threshold = 0.01)
print_model(theta.reshape(-1, 1), names, ['u_t'])
u_t = +0.5009 u_xx

The result is $u_t = 0.5009\,u_{xx}$: the heat equation, with the diffusivity to three figures. The small excess over $0.5$ is the truncation error of the second difference on a $128$-point grid. Nothing distinguished this problem from the ordinary differential equations of Chapter 2 except that the library columns were derivatives in $x$ rather than powers of $v$.


6.2. The Burgers Equation

The Burgers equation adds a nonlinear advection term to the heat equation, here with a smaller diffusivity, $0.1$, so that the front it produces stays sharp,


$$ u_t = -u\,u_x + 0.1\,u_{xx} . $$


The two terms on the right do different things, and it helps to see each alone. With only the diffusion term the equation is the heat equation of Section 6.1: a bump spreads out and sinks, and nothing moves sideways. With only the advection term, $u_t = -u\,u_x$, every point of the profile travels to the right at a speed equal to its own height $u$. The crest of a bump, where $u$ is largest, therefore runs ahead of its foot, where $u$ is small; the back of the bump stretches out and the front piles up, steeper and steeper, until the crest would overtake the foot and the profile would fold over. With both terms present, the advection keeps steepening the front and the diffusion keeps smoothing it, and the two settle on a front of fixed thickness: the smaller the diffusivity, the thinner the front. This is the simplest model of a shock wave, and the same mechanism makes traffic jams and sonic booms.


The field is computed on the same periodic grid of $n_x = 128$ points, from an initial bump $u(x, 0) = 2e^{-2(x - \pi)^2}$, and sampled at $n_t = 201$ instants over $0 \le t \le 2$, long enough for the front to form and short enough that the bump does not reach the right edge of the periodic domain; the matrix U has the same layout as before.

In [ ]:
def burgers_rhs(t, u):
    u_hat = np.fft.fft(u)
    u_x = np.real(np.fft.ifft(1j*k*u_hat))
    u_xx = np.real(np.fft.ifft(-k**2*u_hat))
    return -u*u_x + 0.1*u_xx                                 # u_t = -u u_x + 0.1 u_xx, spectral derivatives

t = np.linspace(0, 2, 201)
u0 = 2*np.exp(-2*(x - np.pi)**2)
U = solve_ivp(burgers_rhs, (0, 2), u0, t_eval = t, rtol = 1e-10, atol = 1e-10).y.T      # (time, space)

plt.figure(figsize = (6, 4))
plt.imshow(U.T, extent = [0, 2, 0, L], origin = 'lower', aspect = 'auto', cmap = 'jet')
plt.colorbar()
plt.xlabel('t')
plt.ylabel('x')
plt.show()
No description has been provided for this image

The colour map shows the bump drifting to the right as time runs; the animation shows what the drift does to its shape. The leading edge steepens into a front, because the crest moves faster than the foot, while the viscosity keeps the front from becoming a step and spreads the whole bump out.

In [ ]:
fig = plt.figure(figsize = (6, 4))
line = plt.plot(x, U[0], 'k')[0]
title = plt.title('t = 0')
plt.xlabel('x')
plt.ylabel('u(x, t)')
plt.xlim([0, L])
plt.ylim([U.min() - 0.1, U.max() + 0.1])
plt.grid(True)
plt.close()

def update(i):
    line.set_ydata(U[i])
    title.set_text('t = %.2f' % t[i])
    return line, title

anim = animation.FuncAnimation(fig, update, frames = range(0, len(t), 2), interval = 50)
HTML(anim.to_jshtml())
Out[ ]:
No description has been provided for this image

Identification

The library is the same eight candidates, built by the same pde_library, and the threshold is raised to $0.05$ because the front makes the finite-difference columns a little rougher than in the heat equation. The true law uses two of the eight, $u_{xx}$ and $uu_x$.

In [ ]:
Phi, u_t, names = pde_library(U, dx, t[1] - t[0])
theta = stls(Phi, u_t, threshold = 0.05)
print_model(theta.reshape(-1, 1), names, ['u_t'])
u_t = +0.1038 u_xx -1.0038 u u_x

SINDy returns $u_t = 0.1038\,u_{xx} - 1.0038\,uu_x$, both terms, with the diffusivity $4\%$ high. The error is larger than for the heat equation because the front is steep and the second difference on a $128$-point grid underestimates the curvature there; the regression compensates with a slightly larger coefficient. A finer grid, or a spectral estimate of $u_{xx}$, would bring it down. Noise affects a PDE library as it did the ODE libraries of Chapter 3, and more severely, because derivatives of the data now appear on both sides of the equation; the remedies are those of Chapters 3 to 5, smoothing in space and time with a window shorter than the sharpest feature, the weak form with test functions in both variables, or a network interpolant of the field.




Summary

Key takeaways

  • SINDy writes a dynamical system as $\dot X = \Phi(X)\,\Theta$ with a sparse coefficient matrix and solves one sparse regression per state variable; the library, the thresholding and the diagnostics are those of the previous notebook.
  • A finite difference amplifies measurement noise by $1/\Delta t$. Derivatives for discovery come from a local polynomial fit over a window shorter than the sharpest feature in the signal, from a network interpolant, or from the weak form.
  • Noise in the derivative averages out in the regression; noise in the library columns biases the coefficients towards zero and can push small terms under the threshold. The states must be smoothed as well as the derivatives, with the same filter.
  • The weak form integrates the equation against compactly supported test functions and moves the derivative onto them; it identified the Lorenz system from noisy data with no smoothing and no derivative of the data.
  • A network fitted to noisy data is a third smooth interpolant, differentiated exactly by autograd; it supplies states and derivatives from one fit, and it is the point where discovery meets the physics-informed networks of the earlier notebooks.
  • A partial differential equation is identified with a library of spatial derivatives, one regression row per space–time grid point; the time derivative is taken down the columns of the field and the spatial derivatives across its rows.
  • A coefficient table is not the final test of an identified equation; simulating the equation and comparing with the data is.

Looking ahead. Every method here required a library, and found only what the library contained: the term $x^2v$ of the Van der Pol oscillator was discovered because the cubic monomials were offered, and a library without them would have returned an imitation. Symbolic Regression removes that requirement by searching the space of expressions themselves, building formulas from operators and variables with no list of candidates fixed in advance, and the next notebook shows what that freedom costs and what it buys.