Discovering Equations from Data with PythonSymbolic regression, genetic programming and the eqdisco toolbox

Chapter 7
Dynamic systems

GP-OLS was proposed for the identification of dynamical systems, and equation discovery is at its most useful when the equations describe how a system evolves in time. This chapter treats the two classical routes. Input–output models express the next output as a function of past outputs and inputs; they are identified from sampled data by any regressor of the book, and they are validated by simulation, not only by one-step prediction. State-space models in continuous time express the derivatives of the states as functions of the states; they need derivative estimates, which are identified by sparse regression (SINDy) or by genetic programming, one equation at a time.

7.1 Problem and idea

A dynamical system has memory: its output at a time depends on its past. A static regression of the output on the current input misses this dependence. Two representations make it explicit (fig. 7.1). In discrete time, a nonlinear autoregressive model with exogenous inputs (NARX) [58, 59] predicts

y(k) = F (y(k −1),…,y(k −na),u(k −nk),…,u(k −nk −nb + 1) ) + e(k),
(7.1)

where na and nb are the output and input orders and nk the input delay. Once the lagged values are arranged as the columns of a regressor matrix, identifying F is an ordinary symbolic regression problem. In continuous time, a state-space model z˙ = g(z,u) is identified by regressing estimated derivatives on the states, one state equation at a time; sparse identification of nonlinear dynamics (SINDy) [66] does this over a library of candidate terms, genetic programming over the space of expressions.

Figure 7.1

Figure 7.1. Two routes to dynamic equations. Discrete-time NARX models are identified on lagged regressors; continuous-time models on estimated derivatives. Both are validated by simulating the model on fresh data with its own outputs fed back.

The danger is specific to dynamics. A model that predicts the next sample well from the measured past can still drift away from the system when it is run on its own outputs, because small errors accumulate through the feedback. One-step-ahead prediction is therefore a weak test; the stricter test is free-run simulation, in which the model receives only the input and its own past outputs [59, 82].

7.2 Theory

7.2.1 NARX identification

For a single input, the regressor matrix of (7.1) has the rows [y(k −1),…,y(k −na),u(k −nk),…,u(k −nk −nb + 1)] for k = t0,…,T −1, where t0 = max ⁡ (na,nk + nb −1) is the first sample with a complete history. Any regressor of the book identifies F on these columns; GP-OLS [1] is the natural choice when F is expected to be a polynomial or a sum of a few nonlinear terms, because it returns the terms with their contributions. The model is validated in two ways. The one-step-ahead prediction ŷ(k) uses the measured past outputs; the free-run simulation y~(k) = F(y~(k −1),…,u(⋅)) uses its own. Both are scored by R2 on data not used for identification.

7.2.2 Order selection

The orders na and nb decide which lags enter the regressor matrix. The classical procedure of the NARMAX literature [59] scans a grid of orders, builds a polynomial library of the lagged variables for each pair, selects terms by FROLS with an information criterion, and compares the criteria across the grid. The result depends on the noise structure. If the noise enters the equation, as e(k) in (7.1), the correct orders minimize the criterion. If the noise is added to the measured output, it reaches the equation filtered through the dynamics and becomes colored; an equation-error model then needs extra past outputs to approximate the noise model, and the scan selects higher orders [82]. Output-error identification by simulation, or a NARMAX model with explicit noise terms, avoids this bias.

7.2.3 Derivatives

Continuous-time identification regresses żi on the states, so the derivatives must be estimated from samples. Central finite differences are exact for quadratic signals and cheap, but they amplify noise by the factor 1∕Δt. The Savitzky–Golay filter [83] fits a local polynomial to a window of samples and differentiates it; a wider window suppresses more noise but biases fast dynamics. A smoothing spline with the smoothing parameter chosen by generalized cross-validation balances the two automatically. The choice matters more than the identification method on noisy data.

7.2.4 Sparse identification and symbolic ODEs

SINDy [66] builds a library Θ(Z) of candidate terms of the states (and inputs), typically all monomials up to degree two or three and some trigonometric functions, estimates the derivative matrix Z˙, and solves Z˙ ≈Θ(Z)Ξ with a sparse coefficient matrix Ξ by the STLSQ algorithm of algorithm 5.1, one column per state. When the right-hand side is not a sparse combination of library terms, SymbolicODE fits any symbolic regressor to each derivative instead. The identified right-hand sides form an ODEModel, which is integrated by SciPy’s stiff-capable solver for simulation and validation.

Algorithm

In a nutshell: Dynamic systems

  • NARX models (7.1) turn dynamic identification into regression on lagged variables; GP-OLS returns the terms with their contributions.
  • One-step prediction is a weak test; free-run simulation is the decisive one.
  • Order scans with FROLS and BIC select the lags; measurement noise colors the equation error and inflates the selected order.
  • Continuous-time models need derivative estimates; smoothing splines are robust to noise, finite differences accurate on clean, dense data.
  • SINDy solves a sparse regression per state (algorithm 7.1); SymbolicODE uses any symbolic regressor when the library is not enough.

7.3 Using it in eqdisco

NARXRegressor(estimator=None, na=2, nb=2, nk=1, input_names=None, output_name="y")

fit(u, y)

builds the lagged regressors and fits the estimator (GP-OLS by default); u=None gives an autonomous model.

predict(u, y), simulate(u, y_init)

one-step prediction from measured outputs, free-run simulation from initial outputs; score(u, y, mode) with mode="prediction" or "simulation".

Results

equation_ with variables named y(k-1), u(k-1), …; estimator_.

Related

dynamics.lagged_regressors, dynamics.narx_order_scan(u, y, max_na, max_nb, degree, criterion), dynamics.derivative(x, t, method), SINDy(degree, functions, method, threshold, derivative_method), SymbolicODE(estimator, derivative_method), ODEModel.simulate(z0, t, u), viz.plot_simulation, viz.plot_phase_portrait.

7.4 Examples

Identification with GP-OLS. The benchmark system of Narendra and Parthasarathy [84], y(k + 1) = y(k)∕(1 + y(k)2) + u(k)3, is excited by a uniform random input. GP-OLS with the function set {+,×,÷} is fitted on 300 samples with na = nb = 1:

narx = eq.NARXRegressor(eq.GPOLSRegressor(population_size=250, generations=30, functions=("add", "mul", "div"), max_genes=5, random_state=0), na=1, nb=1, nk=1) 
narx.fit(u_tr, y_tr) 
print("y(k) =", narx.equation_) 
print(f"one-step R2 {narx.score(u_te, y_te, ’prediction’):.4f}, free-run R2 {narx.score(u_te, y_te, ’simulation’):.4f}")
   

The identified model is

y(k) = 1 ⋅u(k −1)3 + 1 ⋅ y(k −1) y(k −1)2 + u(k −1)∕u(k −1) + 3 ⋅10−11,

the true system: GP-OLS without constants builds the number 1 as u∕u, which the simplifier removes. On 300 fresh samples both the one-step prediction and the free-run simulation reach R2 = 1.0000 (fig. 7.2). With fewer data and a smaller budget, the free-run R2 is 0.900 after identification on 50 samples and rises to 0.987, 0.989 and 0.989 with 100, 200 and 300 samples.

Figure 7.2

Figure 7.2. A NARX model of the Narendra–Parthasarathy system identified by GP-OLS. Top: one-step-ahead prediction on validation data. Bottom: free-run simulation, in which the model receives only the input and its own outputs.

Open in ColabExample plot_22_narx_gpols.py in the gallery

Which lags? A second-order Hammerstein system, y(k) = 1.2y(k −1) −0.5y(k −2) + 0.4v(k −1) + e(k) with v = u + 0.5u2 and equation-error noise, is scanned for na ≤4 and nb ≤3 with a second-degree polynomial library:

scan = narx_order_scan(u, y, max_na=4, max_nb=3, degree=2) 
print(scan.head(5)[["na", "nb", "n_terms", "r2", "bic", "terms"]])
   

The BIC is lowest for na = 2 and nb = 1 (fig. 7.3), and FROLS selects exactly the terms y(k −1), y(k −2), u(k −1) and u(k −1)2 of the true system, with R2 = 0.9995; larger orders select the same terms and are penalized for the larger library. The free run of this model on validation data follows the system closely. The parameter study adds measurement noise to the output instead. With noise of standard deviation 0.05 and 0.2, the scan selects na = 4: the colored equation error is compensated by extra past outputs, as section 7.2.2 predicts.

Figure 7.3

Figure 7.3. Order selection for a NARX model. Left: BIC of FROLS models over the grid of orders; the minimum is at na = 2, nb = 1. Right: free-run simulation of the selected model on validation data.

Open in ColabExample plot_23_order_selection.py in the gallery

SINDy on the Lorenz system. A single trajectory of the Lorenz system [85] over 10 time units, sampled every 0.002, is regressed on a quadratic library of the three states:

sindy = eq.SINDy(degree=2, threshold=0.05, feature_names=["x", "y", "z"]).fit(Z, t) 
print(sindy.model_) 
Zs = sindy.simulate(Z[0], t)
   

The identified equations,

ẋ = −9.999x + 9.999y, ẏ = 27.99x −0.9985y −0.9998xz, ż = −2.666z + 0.9999xy,

are the Lorenz equations with σ = 10, ρ = 28 and β = 8∕3 to three or four digits, plus intercepts below 10−3 (fig. 7.4). Simulated from the same initial state, the model follows the data for a few time units and then diverges, as two trajectories of a chaotic system always do, but it stays on the same attractor. The parameter study adds Gaussian noise, given as a fraction of the standard deviation of each state. With finite differences the relative error of the coefficient −10 of x is 10−4, 5 ⋅10−4, 2.6 ⋅10−3 and 1.3 ⋅10−2 at noise levels 0, 0.002, 0.01 and 0.03; with a Savitzky–Golay window of 41 samples it is smaller at moderate noise (10−4 and 6 ⋅10−4 at 0.002 and 0.01) but larger at the highest noise (7.6 ⋅10−2), where the wide window biases the fast part of the dynamics.

Figure 7.4

Figure 7.4. SINDy identifies the Lorenz system. Left: absolute values of the coefficient matrix, with the nonzero coefficients printed. Middle: the measured and the simulated trajectory in the (x,z) plane. Right: the x coordinate over time; the trajectories separate after a few time units, as chaotic trajectories do.

Open in ColabExample plot_24_sindy_lorenz.py in the gallery

Genetic programming for an ODE. The predator–prey model of Lotka and Volterra, ẋ = x −0.4xy, ẏ = 0.1xy −0.4y, is sampled every 0.05 time units with Gaussian noise of 0.5% of the standard deviation of each state; the derivatives are estimated by a smoothing spline, and each right-hand side is identified by genetic programming with parameter optimization over {+,−,×}:

gp = eq.SymbolicRegressor(population_size=250, generations=25, functions=("add", "sub", "mul"), optimize="lm", random_state=0) 
ode = eq.SymbolicODE(gp, derivative_method="spline", feature_names=["prey", "predator"]).fit(Z, t) 
print(ode.model_) 
Zs = ode.simulate(Z[0], t)
   

The identified equations are ẋ = −0.2001(y −2.5)(2x) = 1.0x −0.400xy and ẏ = −0.0997y(4.004 −x) = 0.0997xy −0.399y, the true model in factored form (fig. 7.5). The derivative estimate is the critical step. Relative to the true derivatives, the root-mean-square error of finite differences is 0.1%, 8.9%, 36% and 89% at noise levels 0, 0.5, 2 and 5%; of the Savitzky–Golay filter 0.4%, 2.0%, 7.9% and 20%; of the smoothing spline 0.1%, 1.6%, 3.8% and 6.6%.

Figure 7.5

Figure 7.5. Lotka–Volterra equations identified by genetic programming. Left: measured (solid) and simulated (dashed) populations of prey and predator. Right: the phase portrait of the data and of the identified model.

Open in ColabExample plot_25_symbolic_ode.py in the gallery

7.5 Further reading

Ljung [82] is the standard text on system identification; Billings [59] covers NARMAX models, FROLS and model validation in depth; Leontaritis and Billings [58] introduced the NARMAX representation. Narendra and Parthasarathy [84] proposed the benchmark systems that are still used to test nonlinear identification. Hinchliffe and Willis [61] and Madár, Abonyi and Szeifert [1] applied genetic programming to dynamic process models. Brunton, Proctor and Kutz [66] introduced SINDy, and Kaptanoglu et al. [27] describe its Python implementation with many extensions; Schmidt and Lipson [17] identified conservation laws of mechanical systems with genetic programming.