PySINDy Documentation

repository·main·Indexed 23 days ago

https://github.com/dynamicslab/pysindy

A Python package for Sparse Identification of Nonlinear Dynamics (SINDy). It enables the discovery of governing dynamical equations, including ODEs, implicit ODEs, and PDEs, from measurement data. PySINDy implements a sparse regression approach using candidate feature libraries and numerical differentiation to produce interpretable and generalizable models. The core SINDy model is scikit-learn compatible and supports customizable differentiation methods, feature libraries, and sparse regression algorithms.

Tokens
16.3K
Snippets
20
Records
70
Agent score
83%

What's inside PySINDy

  1. What is PySINDy and how does it work?

    main

    PySINDy is a Python package designed for the discovery of governing dynamical systems models from data using the Sparse Identification of Nonlinear Dynamics (SINDy) approach.

    Given state measurements $\mathbf{x}(t)$, PySINDy seeks to find a function $\mathbf{f}$ such that $\frac{d}{dt}\mathbf{x}(t) = \mathbf{f}(\mathbf{x}(t))$. It treats model discovery as a sparse regression problem, selecting relevant terms for the model from a library of candidate functions. This results in parsimonious, interpretable, and generalizable models that avoid overfitting.

    Key characteristics:

    • Scikit-learn compatible: The core SINDy model class is implemented as a scikit-learn estimator, allowing it to be used in standard machine learning pipelines (e.g., for parameter tuning or model selection).
    • Extensible: Users can customize the differentiation methods, feature libraries, and sparse regression algorithms.
  2. What is PySINDy and how does SINDy work?

    main

    PySINDy is a Python package for Sparse Identification of Nonlinear Dynamics (SINDy), a method for discovering the governing equations of a dynamical system directly from data.

    The Core Concept

    SINDy assumes that the dynamical evolution of a state variable $\mathbf{q}(t)$ follows an Ordinary Differential Equation (ODE) of the form: $$\frac{d}{dt} \mathbf{q} = \mathbf{f}(\mathbf{q})$$

    The method approximates the function $\mathbf{f}(\mathbf{q})$ as a sparse combination of terms from a library of candidate basis functions $\boldsymbol{\theta}(\mathbf{q})$: $$\mathbf{f}(\mathbf{q}) \approx \sum_{k=1}^{p}\theta_k(\mathbf{q})\boldsymbol\xi_k, \quad \text{or} \quad \frac{d}{dt}\mathbf{q} \approx \mathbf{\Theta}(\mathbf{q})\mathbf{\Xi}$$

    Where:

    • $\mathbf{\Theta}(\mathbf{q})$ is the library of candidate terms.
    • $\mathbf{\Xi}$ contains the sparse coefficients to be identified.

    The Workflow

    1. Data Collection: Collect state measurements $\mathbf{Q}$ sampled at time steps $t_1, ..., t_m$.
    2. Derivative Computation: Compute a matrix of time derivatives $\mathbf{Q}_t$ from the data $\mathbf{Q}$. PySINDy supports various methods including finite differences, Savitzky-Golay, spectral, spline, and total variational derivatives.
    3. Sparse Regression: Solve the optimization problem to find coefficients $\mathbf{\Xi}$ that minimize the error while promoting sparsity (using regularizers like $l_0$ or $l_1$ and algorithms like SR3): $$\text{argmin}_{\boldsymbol\Xi}|\mathbf Q_t - \boldsymbol\Theta(\mathbf{Q}) \boldsymbol\Xi|^2 + R(\boldsymbol\Xi)$$
  3. What is SINDy and how does PySINDy work?

    main

    SINDy (Sparse Identification of Nonlinear Dynamical systems) is a method used to discover the governing equations of a dynamical system from measurement data. It assumes that the time evolution of a system $\dot{x}(t) = f(x(t))$ can be represented as a sparse linear combination of basis functions.

    In PySINDy, the approximation problem $\dot{X} \approx \Theta(X)\Xi$ is decomposed into three main functional areas:

    1. Numerical Differentiation: Computing the time derivatives $\dot{X}$ from the state measurements $X$.
    2. Feature Library: Constructing the library matrix $\Theta(X)$, which contains the chosen set of basis functions (e.g., polynomials, trigonometric functions) applied to the data.
    3. Sparse Regression: Using optimizers to solve for the sparse coefficient matrix $\Xi$ that best fits the data.

    The main SINDy class encapsulates these three components to automate the discovery process.

  4. Identify PDEs and algebraic systems using PySINDy

    main

    PySINDy can approximate algebraic systems of PDEs (and their weak forms) in an arbitrary number of spatial dimensions. The library handles these by treating the system as a function $\mathbf{g}(\mathbf{q}, \mathbf{q}_t, \mathbf{q}_x, \mathbf{q}y, \mathbf{q}{xx}, ..., \mathbf{u}) = 0$.

    To accommodate control terms ($\mathbf{u}$) and partial derivatives (e.g., $\mathbf{q}x, \mathbf{q}{xx}$), you add them as columns to the candidate library $\mathbf{\Theta}(\mathbf{Q})$, resulting in $\mathbf{\Theta}(\mathbf{Q}, \mathbf{Q}_t, \mathbf{Q}_x, ..., \mathbf{u})$. This approach allows the identification of ODEs, implicit ODEs, and PDEs within a unified framework.

  5. Advanced modeling features in PySINDy

    main

    PySINDy supports several advanced modeling and validation techniques:

    • Trapping SINDy: Used for promoting/ensuring provably stable ODE models (e.g., for fluid dynamics).
    • Multiple Trajectories: Training models using data from multiple dynamic trajectories.
    • Ensembling and Sub-sampling: Generating multiple models via sub-sampling and ensembling methods for cross-validation and probabilistic system identification.
  6. Select and customize library functions

    main

    The SINDy method assumes dynamics can be represented as a sparse linear combination of library functions.

    Library Selection Strategies:

    • Polynomials: A good starting point for smooth functions (Taylor series approximation).
    • Custom/Specific Bases: Use Chebyshev polynomials if you expect the dynamics to be better represented by them.
    • Incremental Expansion: Start with a small library (e.g., linear terms) and gradually add higher-order terms (quadratic, cubic) to avoid ill-conditioning.

    Available Library Classes:

    • CustomLibrary: Use this when you have a set of functions to apply to each measurement variable or combinations of variables.
    • IdentityLibrary: The most customizable. It expects all features to be pre-computed and present in X before calling SINDy.fit. It simply applies an identity map.
    • BaseFeatureLibrary: Inherit from this class to implement your own custom library class.
  7. Understand the PySINDy Object Model

    main

    PySINDy is built around the abstract base class _BaseSINDy, which represents the problem of fitting a dynamical system $X' = \Xi^T \Theta(X)$.

    The primary concrete implementation is the SINDy class, which follows a traditional approach by composing three main components:

    1. Differentiation Method (BaseDifferentiation): Computes the derivative $X'$. These are often callable objects and may accept axis and order arguments.
    2. Feature Library (BaseFeatureLibrary): Specifies the candidate basis functions $\Theta(X)$. The fit() method determines the number and string format of features. You can inspect features using get_feature_names() or n_features_out_.
    3. Optimizer (BaseOptimizer): Implements sparse regression to solve for $\Xi$. Optimizers share a history_ of coefficient values and a coef_ array of final coefficients.

    Once a SINDy object is created, it follows a scikit-learn style workflow:

    • fit(X, t): Fit the model to measurement data.
    • predict(X): Predict derivatives given new measurements.
    • simulate(x0, t): Evolve novel initial conditions forward in time.
    • score(X, t): Evaluate the model performance.
  8. Configure SINDy modeling decisions

    main

    When applying the SINDy model, you can customize three primary components to suit your specific dynamical system:

    1. Numerical Differentiation: Methods used to compute derivatives from data. Standard options include:

      • Finite difference
      • Smoothed finite difference
    2. Feature Libraries: The set of candidate functions used to construct the model. Standard options include:

      • Polynomial libraries
      • Fourier libraries
      • Custom libraries (via a dedicated class for user-defined functions)
    3. Sparse Regression Algorithms: The technique used to learn the model coefficients. Standard options include:

      • Sequentially thresholded least squares
      • LASSO
      • Sparse relaxed regularized regression

    Users can implement their own differentiation, library, or regression objects to extend the package functionality.

  9. Getting started with PySINDy tutorials

    main

    PySINDy provides several introductory tutorials to help you learn how to fit and evaluate models.

    • Fitting a model: The recommended starting point for beginners. It demonstrates how to use PySINDy to learn a model for a simple linear differential equation.
    • Evaluating a model fit: Covers different methods to evaluate and visualize how well a model fits your data, depending on your specific use case.
    • Feature overview: A comprehensive reference notebook that provides an exhaustive overview of available features, including how to configure various options and work with different dataset types.
  10. Use SINDy methods for fitting and prediction

    main

    After initializing a SINDy model with a differentiation method, feature library, and optimizer, use the following API to interact with your discovered system:

    # Example workflow (conceptual)
    model = SINDy(
        differentiation_method=diff_method, 
        feature_library=library, 
        optimizer=opt
    )
    
    # Fit to data
    model.fit(X, t)
    
    # Inspect discovered equations
    print(model.equations())
    
    # Predict derivatives for new data
    derivatives = model.predict(X_new)
    
    # Simulate dynamics from initial conditions
    trajectories = model.simulate(x0, t_range)
    
    # Score the model
    score = model.score(X_test, t_test)
  11. Use pre-commit for code styling

    main

    PySINDy uses pre-commit to enforce PEP8 and other coding guidelines.

    • Automatic: When you run git add and git commit, pre-commit runs automatically.
    • Manual: To manually trigger the reformatting of all staged code, run pre-commit.

    Important: If pre-commit makes changes to your code, you must re-stage those changes (git add) before committing.

  12. Advanced research applications in PySINDy

    main

    PySINDy includes examples derived from external research papers to demonstrate specific, high-level applications:

    • Original SINDy Paper: Recreates results for various systems including Linear/Cubic 2D/3D ODEs, the Lorenz system, fluid wakes, the Logistic map, and the Hopf system.
    • Plasma Physics: Uses the ConstrainedSR3 optimizer to build constrained models for temporal POD modes in plasma simulations.
    • Advanced PDEs: Demonstrates PDEFind and WeakSINDy on complex 2D and 3D reaction-diffusion systems.
    • Stability and Trapping: Uses the TrappingSR3 optimizer to discover stable quadratic models for canonical fluid systems.
    • Cavity Flow: Demonstrates learning quasiperiodic dynamics in shear-driven cavity flows.
    • Noise Robustness: Benchmarks PySINDy performance on low-dimensional chaotic systems subject to noise.