from __future__ import annotations
import numpy as np
import pandas as pd
from example_models import get_linear_chain_2v
from mxlpy import Simulator, fit, make_protocol, plot
from mxlpy.distributions import LogNormal, Normal
Bayesian inference (MCMC)¶
A fit returns the single parameter set that best describes the data. It doesn't tell you how well the data constrain each parameter: often a whole range of values fits almost equally well.
mxlpy can instead sample the posterior distribution of the parameters given the data, using Markov chain Monte Carlo (MCMC). From the samples you get credible intervals, correlations between parameters and the uncertainty of predictions.
The posterior combines two ingredients:
- the likelihood of the data: the data are assumed to be the model's prediction plus Gaussian measurement noise with a known standard deviation
sigma - a prior per sampled parameter: what you know about the parameter before seeing the data, given as a distribution from
mxlpy.distributions
Creating synthetic data¶
As in the fitting tutorial, we create noisy synthetic data from a model with known parameters.
model_fn = get_linear_chain_2v
true_pars = {"k1": 1.0, "k2": 2.0, "k_out": 1.0}
sigma = 0.05
clean = (
Simulator(model_fn())
.update_parameters(true_pars)
.simulate_time_course(np.linspace(0, 10, 21))
.get_result()
.unwrap_or_err()
.variables
)
rng = np.random.default_rng(42)
data = clean + rng.normal(0, sigma, clean.shape)
fig, ax = plot.one_axes()
for name in data.columns:
ax.plot(data.index, data[name], "o", label=name)
ax.legend()
plot.show()
Sampling the posterior¶
fit.mcmc takes the data, a prior for every parameter to sample and the measurement noise (here its standard deviation sigma).
The keys of prior are the sampled parameters; all other parameters keep their model values.
Rate constants are positive and can span orders of magnitude, so a log-normal prior is a natural choice.
Parameters whose prior lives on (0, inf) are sampled as their logarithm internally, which makes the sampler much more efficient; all results are reported in natural units.
Several independent chains run in parallel. A seed makes the samples reproducible.
res = fit.mcmc(
model_fn(),
data=data,
prior={
"k1": LogNormal(mean=0, sigma=1),
"k2": LogNormal(mean=0, sigma=1),
"k_out": LogNormal(mean=0, sigma=1),
},
noise=sigma,
n_samples=2000,
n_chains=4,
seed=0,
).unwrap_or_err()
res.chains.shape # (chains, samples, parameters)
(4, 2000, 3)
Checking convergence¶
Before interpreting the samples, check that the chains have converged to the same distribution.
- R-hat compares the chains with each other; values below about 1.01 indicate convergence
- the effective sample size (ESS) estimates how many independent samples the correlated chain samples are worth; a few hundred are enough for intervals
- the acceptance rate of the sampler should be roughly between 0.15 and 0.5
pd.DataFrame({"r_hat": res.r_hat(), "ess": res.ess()})
| r_hat | ess | |
|---|---|---|
| k1 | 1.007560 | 618.899824 |
| k2 | 1.005565 | 608.295415 |
| k_out | 1.005272 | 638.544797 |
res.acceptance_rates
array([0.314 , 0.1725, 0.265 , 0.264 ])
Trace plots should look like stationary noise, with all chains overlapping.
_ = res.plot_traces()
Credible intervals¶
credible_intervals gives equal-tailed intervals containing level of the posterior mass, and the median.
res.credible_intervals(level=0.95).assign(true=pd.Series(true_pars))
| lower | median | upper | true | |
|---|---|---|---|---|
| k1 | 0.876294 | 1.144935 | 1.510668 | 1.0 |
| k2 | 1.716410 | 2.231607 | 2.903399 | 2.0 |
| k_out | 0.885182 | 1.139038 | 1.489602 | 1.0 |
_ = res.plot_marginals()
All samples are available as a pandas.DataFrame, one row per chain and draw.
Correlations between parameters show which combinations of parameters the data constrain.
Here all three rate constants are strongly correlated: the data mostly fix their ratios.
Strong correlations also make the chains mix more slowly, which is why we drew 2000 samples per chain; if R-hat is too high, draw more.
samples = res.samples()
samples.corr()
| k1 | k2 | k_out | |
|---|---|---|---|
| k1 | 1.000000 | 0.987886 | 0.996534 |
| k2 | 0.987886 | 1.000000 | 0.984949 |
| k_out | 0.996534 | 0.984949 | 1.000000 |
Prediction uncertainty¶
Simulating the model for a random subset of the posterior samples propagates the parameter uncertainty to the predictions.
subset = samples.sample(50, random_state=0)
predictions = pd.concat(
{
i: Simulator(model_fn().update_parameters(pars.to_dict()))
.simulate_time_course(np.linspace(0, 10, 101))
.get_result()
.unwrap_or_err()
.variables
for i, pars in subset.iterrows()
}
)
fig, ax = plot.one_axes()
for name, color in zip(data.columns, ["C0", "C1"], strict=True):
per_time = predictions[name].unstack(level=-1)
ax.fill_between(
per_time.columns,
per_time.quantile(0.025),
per_time.quantile(0.975),
color=color,
alpha=0.3,
)
ax.plot(data.index, data[name], "o", color=color, label=name)
ax.legend()
plot.show()
Steady states and protocols¶
Like the fit functions, fit.mcmc simulates whatever the data needs: a pandas.Series is a steady state, a pandas.DataFrame a time course, and with a protocol a protocol time course.
The noise can also be given per data column (or entry, for steady states) as a pandas.Series, or per data point as a pandas.DataFrame.
Missing data (NaN) are ignored.
Here the steady state only constrains the ratios of the rate constants, so we fix k1 and only sample the others.
steady_state = clean.iloc[-1]
res_ss = fit.mcmc(
model_fn(),
data=steady_state,
prior={"k2": LogNormal(0, 1), "k_out": LogNormal(0, 1)},
noise=pd.Series({"x": 0.02, "y": 0.02}),
n_samples=1000,
seed=0,
).unwrap_or_err()
res_ss.credible_intervals()
| lower | median | upper | |
|---|---|---|---|
| k2 | 1.866802 | 2.007542 | 2.163379 |
| k_out | 0.964023 | 1.000896 | 1.043311 |
protocol = make_protocol([(4, {"k1": 1.0}), (4, {"k1": 2.0})])
data_protocol = (
Simulator(model_fn())
.update_parameters(true_pars)
.simulate_protocol_time_course(protocol, time_points=np.linspace(0, 8, 33))
.get_result()
.unwrap_or_err()
.variables
)
res_protocol = fit.mcmc(
model_fn(),
data=data_protocol + rng.normal(0, sigma, data_protocol.shape),
protocol=protocol,
prior={
"k2": LogNormal(0, 1),
"k_out": LogNormal(0, 1),
}, # k1 is set by the protocol
noise=sigma,
n_samples=1000,
seed=0,
).unwrap_or_err()
res_protocol.credible_intervals()
| lower | median | upper | |
|---|---|---|---|
| k2 | 1.997740 | 2.041822 | 2.090721 |
| k_out | 0.988663 | 1.002787 | 1.016704 |
First finish line
With that you now know how to quantify parameter uncertainty with mxlpy.Congratulations!
Several experiments¶
Usually the parameters are constrained by several experiments, e.g. a wild type and a mutant.
fit.mcmc takes a mapping of names to data or fit.Conditions, like the identify functions: every data set is simulated in its own condition, and the posterior is conditioned on all of them.
A fit.Condition can set parameters, initial values and a protocol, and with local estimate a parameter separately in it: here the mutant has its own k_out, sampled as k_out_mut.
data_mutant = (
Simulator(model_fn())
.update_parameters(true_pars | {"k_out": 2.0})
.simulate_time_course(np.linspace(0, 10, 41))
.get_result()
.unwrap_or_err()
.variables
)
data_mutant = data_mutant + rng.normal(0, sigma, data_mutant.shape)
res_joint = fit.mcmc(
model_fn(),
{"wt": data, "mutant": fit.Condition(data_mutant, local={"k_out": "k_out_mut"})},
prior={k: LogNormal(0, 1) for k in [*true_pars, "k_out_mut"]},
noise=sigma,
n_samples=1000,
seed=0,
).unwrap_or_err()
res_joint.credible_intervals()
| lower | median | upper | |
|---|---|---|---|
| k1 | 0.909324 | 1.042809 | 1.211403 |
| k2 | 1.795583 | 2.068460 | 2.377097 |
| k_out | 0.916693 | 1.051694 | 1.206538 |
| k_out_mut | 1.849291 | 2.080975 | 2.381769 |
Normal(loc=0, scale=1).log_pdf(0.5), Normal(loc=0, scale=1).positive_support
(-1.0439385332046727, False)
Starting point¶
By default the chains start (slightly spread out) at the model's current parameter values.
Starting from a previous fit with x0 saves warm-up time.
best = fit.time_course(
model_fn(),
p0={"k1": 1.5, "k2": 1.5, "k_out": 1.5},
data=data,
minimizer=fit.LocalScipyMinimizer(),
).unwrap_or_err()
res = fit.mcmc(
model_fn(),
data=data,
prior={k: LogNormal(0, 1) for k in best.best_pars},
noise=sigma,
x0=best.best_pars,
n_samples=500,
seed=0,
).unwrap_or_err()
Sampler¶
The default sampler is fit.AdaptiveMetropolis (Haario et al. 2001): during a warm-up it adapts the covariance of its Gaussian proposals to the shape of the posterior, then it samples with the proposal frozen.
The warm-up is discarded and defaults to as many steps as samples.
Any callable following the fit.McmcSampler protocol can be passed as sampler.
res = fit.mcmc(
model_fn(),
data=data,
prior={k: LogNormal(0, 1) for k in true_pars},
noise=sigma,
n_samples=500,
sampler=fit.AdaptiveMetropolis(n_warmup=1000, adaptation_interval=50),
seed=0,
).unwrap_or_err()
res.acceptance_rates
array([0.294, 0.21 , 0.266, 0.298])