Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bayesian SINDy #440

Merged
merged 60 commits into from
Feb 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
60 commits
Select commit Hold shift + click to select a range
79a4fa0
Added Sparse Bayesian Regression (SBR) optimizer
mikkelbue Dec 13, 2023
5c5ee4e
Added Bayesian SINDy notebook
mikkelbue Dec 13, 2023
acab720
Blacked Sparse Bayesian Regression code
mikkelbue Dec 13, 2023
66112bb
Renamed BayesianSparseRegression to SparseBayesianRegression
mikkelbue Dec 13, 2023
cc89101
Added numpyro as an optional dependency
mikkelbue Dec 14, 2023
22fac95
Removed reference to PEP 690 from SBR import
mikkelbue Dec 14, 2023
a681ae8
Renamed SBR hyperparameters to something more interpretable
mikkelbue Dec 14, 2023
8da636a
Renamed Bayesian SINDy notebook
mikkelbue Dec 14, 2023
f209b54
Moved methods from SparseBayesianRegression into SBR optimizer
mikkelbue Dec 14, 2023
5b60afe
Vectorized sampling of SINDy coefficients in numpyro for optimization
mikkelbue Dec 21, 2023
b827dab
Added docstring to Sparse Bayesian Regression optimizer
mikkelbue Dec 21, 2023
f56e9e1
Added some documentation and testing mode to the Bayesian SINDy notebook
mikkelbue Jan 8, 2024
5ab7932
Added jax as optional dependency for Bayesian SINDy
mikkelbue Jan 9, 2024
83c6a17
Added numpyro dependecy group to github workflow
mikkelbue Jan 10, 2024
8c1a923
Removed misplaced space in github workflow
mikkelbue Jan 10, 2024
66c0f15
Fixed bug in SBR docstring.
mikkelbue Jan 11, 2024
754722a
Removed reference in docstring.
mikkelbue Jan 11, 2024
1f17975
Update pyproject.toml
mikkelbue Jan 22, 2024
b391898
Update pysindy/optimizers/sbr.py
mikkelbue Jan 22, 2024
cc30881
Update pysindy/optimizers/sbr.py
mikkelbue Jan 22, 2024
f0a6823
Rename numpyro dependency group to sbr
mikkelbue Jan 22, 2024
80fc151
Remove reference to numpyro implementation and add horseshoe descript…
mikkelbue Jan 22, 2024
cacb02b
Reorganize SBR kwargs for MCMC and super
mikkelbue Jan 22, 2024
12e5677
Reran SBR notebooks after updating the kwargs logic
mikkelbue Jan 22, 2024
7af3848
Moved horseshoe hyperparameter sampling into _numpyro_model routine
mikkelbue Jan 22, 2024
01698be
Updated documenation for SBR after refactording the kwargs
mikkelbue Jan 22, 2024
952b989
RemovedJAX key splitting since it's not necessary for SBR
mikkelbue Jan 23, 2024
ae9325b
Renamed mcmc to mcmc_ in SBR oprimizer
mikkelbue Jan 23, 2024
890ad58
Reran SBR notebooks after recent updates
mikkelbue Jan 23, 2024
6e9b003
Added type hints to SBR
mikkelbue Jan 23, 2024
28dd0f3
Trip initilialisation of SBR of unbias=True, since it's incompatible
mikkelbue Jan 23, 2024
8df9665
Added discrete time example
mikkelbue Jan 25, 2024
52b9070
Changed discrete time example to harmonic oscillator
mikkelbue Jan 29, 2024
ab2641b
Add note about the SBR modelling assumptions in the docstring
mikkelbue Jan 30, 2024
0b25e65
Added some more clarification to SBR docstring
mikkelbue Feb 5, 2024
57f4178
Added SBR optimizer to a bunch of tests
mikkelbue Feb 5, 2024
98fa0fd
Merge branch 'master' into bayesian_sindy
mikkelbue Feb 5, 2024
17f4d65
Removed strict versioning for numpyro
mikkelbue Feb 5, 2024
85a5db1
Remove reference marker from mcmc in SBR docstring
mikkelbue Feb 6, 2024
1ec2523
Added some bad argument calue checking to SBR
mikkelbue Feb 6, 2024
73c2fd5
Added tests got bad arguments to SBR optimizer
mikkelbue Feb 6, 2024
5ff20a1
Black test_optimizers.py
mikkelbue Feb 6, 2024
8c0c019
Added simple test of SBR fitting
mikkelbue Feb 6, 2024
4fb02a0
Black test_optimizers.py
mikkelbue Feb 6, 2024
9ef48d7
Added pickle test for SBR optimizer
mikkelbue Feb 6, 2024
d8b93b1
Updated test_sbr_fit so Flake8 isn't tripped
mikkelbue Feb 6, 2024
eced555
Rephrase docstring of SBR for clarity.
mikkelbue Feb 12, 2024
ad38749
Rephrase description of "slab_shape_nu" in SBR for clarity
mikkelbue Feb 12, 2024
cd4ecee
Rephrase desciption of "slab_shape_s" in SBR for clarity
mikkelbue Feb 12, 2024
54422da
Add docstring and type hints to "_sample_reg_horseshoe"
mikkelbue Feb 12, 2024
ed358cb
Remove superfluous function definition from "_sample_reg_horseshoe"
mikkelbue Feb 12, 2024
b2579bb
Fixed bug in type hints for "_sample_reg_horseshoe"
mikkelbue Feb 12, 2024
a13ce82
Changed SBR test to also test for coefficient values
mikkelbue Feb 12, 2024
6426f6c
Removed discrete example from Bayesian SINDy
mikkelbue Feb 13, 2024
f20fd1e
Added comment about the limitations of the current SBR method to exam…
mikkelbue Feb 13, 2024
3c37bf0
Added SBR example script
mikkelbue Feb 13, 2024
6bf64e3
Ran publish_notebook.py on SBR example
mikkelbue Feb 13, 2024
9aeadea
Tidied up and reran SBR notebook example after publishing it.
mikkelbue Feb 13, 2024
b855006
Added arviz to SBR dependencies
mikkelbue Feb 13, 2024
2060875
Added high-level import of SBR
mikkelbue Feb 13, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ jobs:
- name: Install dependencies
run: |
pip install --upgrade pip
pip install .[dev,miosr,cvxpy]
pip install .[dev,miosr,cvxpy,sbr]
- name: Build the docs
# Not exactly how RTD does it, but close.
run: |
Expand Down
1,312 changes: 1,312 additions & 0 deletions examples/19_bayesian_sindy/example.ipynb

Large diffs are not rendered by default.

197 changes: 197 additions & 0 deletions examples/19_bayesian_sindy/example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
#!/usr/bin/env python
# coding: utf-8
# # Bayesian UQ-SINDy
# In[1]:
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import solve_ivp

import pysindy as ps


# In[2]:


# set seed for reproducibility
np.random.seed(987)


# ### Lotka-Volterra Predator-Prey Model
#
# In this example, we generate the data using the Lotka-Volterra equations, which is a simplified model of Predator-Prey interactions. They specify a system of Ordinary Differential Equations (ODEs):
# \begin{align}
# \frac{dP}{dt} &= a P - b P Q\\
# \frac{dQ}{dt} &= c P Q - d Q
# \end{align}
# where $P$ is the concentration of prey, $Q$ is the concentration of predators, $a$ is the birth rate of prey, $b$ is the death rate of prey, $c$ is the birth rate of predators and $d$ is the death rate of predators.
#
# For more details, see e.g. Rockwood L. L. and Witt J. W. (2015). *Introduction to population ecology*. Wiley Blackwell, Chichester, West Sussex, UK, 2nd edition

# In[3]:


# set up a class that defines the Lotka-Volterra equations
class PredatorPreyModel:
def __init__(self, a=1.0, b=0.3, c=0.2, d=1.0):
# internalise the model parameters.
self.a = a
self.b = b
self.c = c
self.d = d

def dydx(self, t, y):
# Lotka-Volterra Model model, see e.g. https://en.wikipedia.org/wiki/Lotka%E2%80%93Volterra_equations.}
return np.array(
[self.a * y[0] - self.b * y[0] * y[1], self.c * y[0] * y[1] - self.d * y[1]]
)

def solve(self, **kwargs):
# solve the system of ODEs.
return solve_ivp(self.dydx, **kwargs)


# In[4]:


# set some hyperparameters.
t_span = [0, 30]
y0 = np.array([10, 5])
max_step = 0.1

# initialise the model and solve.
my_model = PredatorPreyModel()
sol = my_model.solve(t_span=t_span, y0=y0, max_step=max_step)


# In[5]:


# the noise level.
noise = 0.1

# extract the timesteps and perturb the solution with noise.
t = sol.t
P = sol.y[0, :] + np.random.normal(scale=noise, size=sol.t.size)
Q = sol.y[1, :] + np.random.normal(scale=noise, size=sol.t.size)


# In[6]:


# plot the solution.
plt.figure(figsize=(12, 4))
plt.plot(sol.t, sol.y[0, :], label="Prey")
plt.scatter(t, P)
plt.plot(sol.t, sol.y[1, :], label="Predators")
plt.scatter(t, Q)
plt.legend()
plt.show()


# ### Bayesian UQ-SINDy
#
# Here we recover the governing equations using UQ-SINDy. For more details on the theory of the method, see Hirsh, S. M., Barajas-Solano, D. A., & Kutz, J. N. (2021). *Sparsifying Priors for Bayesian Uncertainty Quantification in Model Discovery* (arXiv:2107.02107). arXiv. http://arxiv.org/abs/2107.02107
#
# Note that the current implementation differs from the method described in Hirsh et al. (2021) by imposing the error model directly on the derivatives, rather than on the states, circumventing the need to integrate the equation to evaluate the posterior density. One consequence of this is that the noise standard deviation "sigma" is with respect to the derivatives instead of the states and hence should not be interpreted.
#
# The underlying code used to find the posterior distribution of model parameters is `numpyro.infer.MCMC` using the `numpyro.infer.NUTS` kernel. Note that all keyword arguments passed to `pysindy.optimizers.SBR` are sent forward to the [MCMC sampler](https://num.pyro.ai/en/stable/mcmc.html).

# In[7]:


# set sampler hyperparameters
sampling_seed = 123

if __name__ == "testing":
num_warmup = 10
num_samples = 100
num_chains = 1
else:
num_warmup = 500
num_samples = 2000
num_chains = 2


# In[8]:


# initialise the Sparse bayesian Regression optimizer.
optimizer = ps.optimizers.SBR(
num_warmup=num_warmup,
num_samples=num_samples,
mcmc_kwargs={"seed": sampling_seed, "num_chains": num_chains},
)

# use the standard polynomial features.
feature_library = ps.feature_library.polynomial_library.PolynomialLibrary(
include_interaction=True
)

# initialise SINDy and fit to the data.
sindy = ps.SINDy(optimizer, feature_library, feature_names=["P", "Q"])
sindy.fit(np.c_[P, Q], t=t)


# In[9]:


# set up a new differential equation that uses the Bayesian SINDy predictions.
def surrogate_dydt(t, y):
_y = y[np.newaxis, :]
return sindy.predict(x=_y)


# solve using the Bayesian SINDy equations.
surrogate_sol = solve_ivp(surrogate_dydt, t_span=t_span, y0=y0, max_step=max_step)


# In[10]:


# plot the surrogate solution.
plt.figure(figsize=(12, 4))

plt.plot(surrogate_sol.t, surrogate_sol.y[0, :], label="Prey")
plt.scatter(t, P)

plt.plot(surrogate_sol.t, surrogate_sol.y[1, :], label="Predators")
plt.scatter(t, Q)

plt.legend()
plt.show()


# ### Get MCMC diagnostics
#
# We can inspect the posterior samples in more detail using `arviz`. Note that this is not included as a dependency of `pysindy` and must be installed separately.

# In[11]:


# import arviz.
import arviz as az


# In[12]:


# convert the numpyro samples to an arviz.InferenceData object.
samples = az.from_numpyro(sindy.optimizer.mcmc_)

# have a look at the summray.
az.summary(samples)


# In[13]:


# plot the traces.
az.plot_trace(samples, divergences=False)
plt.tight_layout()
plt.plot()


# In[ ]:


# In[ ]:
5 changes: 5 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@ cvxpy = [
"cvxpy",
"scs>=2.1, !=2.1.4"
]
sbr = [
"numpyro",
"jax",
"arviz"
]

[tool.black]
line-length = 88
Expand Down
4 changes: 4 additions & 0 deletions pysindy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@
from .optimizers import StableLinearSR3
except ImportError:
pass
try:
from .optimizers import SBR
except ImportError:
pass

Check warning on line 55 in pysindy/__init__.py

View check run for this annotation

Codecov / codecov/patch

pysindy/__init__.py#L54-L55

Added lines #L54 - L55 were not covered by tests
from .optimizers import WrappedOptimizer
from .optimizers import SR3
from .optimizers import SSR
Expand Down
5 changes: 5 additions & 0 deletions pysindy/optimizers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
from .stable_linear_sr3 import StableLinearSR3
except ImportError:
pass
try:
from .sbr import SBR
except ImportError:
pass

Check warning on line 25 in pysindy/optimizers/__init__.py

View check run for this annotation

Codecov / codecov/patch

pysindy/optimizers/__init__.py#L24-L25

Added lines #L24 - L25 were not covered by tests
from .wrapped_optimizer import WrappedOptimizer
from .sr3 import SR3
from .ssr import SSR
Expand All @@ -37,4 +41,5 @@
"FROLS",
"SINDyPI",
"MIOSR",
"SBR",
]