Fitting
from __future__ import annotations
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from example_models import get_linear_chain_2v
from mxlpy import Simulator, fit, make_protocol, plot
Fitting¶
Almost every model at some point needs to be fitted to experimental data to be validated.

mxlpy offers highly customisable local and global routines for fitting either time series or steady-states.
The entire set of currently supported routines is
Single model, single data
steady_statetime_courseprotocol_time_course
Single model, single data, multiple initial guesses (a.k.a. multi-start optimisation)
group_steady_stategroup_time_coursegroup_protocol_time_course
Multiple model, single data
ensemble_steady_stateensemble_time_courseensemble_protocol_time_course
A carousel is a special case of an ensemble, where the general structure (e.g. stoichiometries) is the same, while the reactions kinetics can vary
carousel_steady_statecarousel_time_coursecarousel_protocol_time_course
Multiple model, multiple data
joint_steady_statejoint_time_coursejoint_protocol_time_course
Multiple model, multiple data, multiple methods
Here we also allow to run different methods (e.g. steady-state vs time courses) for each combination of model:data.
joint_mixed
Minimizers¶
- LocalScipyMinimizer, including common methods such as Nelder-Mead or L-BFGS-B
- GlobalScipyMinimizer, including common methods such as basin hopping or dual annealing
For this tutorial we are going to use the fit module to optimise our parameter values and the plot module to plot some results.
Let's get started!
Creating synthetic data¶
Normally, you would fit your model to experimental data.
Here, for the sake of simplicity, we will generate some synthetic data.
Checkout the basics tutorial if you need a refresher on building and simulating models.
# As a small trick, let's define a variable for the model function
# That way, we can re-use it all over the file and easily replace
# it with another model
model_fn = get_linear_chain_2v
res = (
Simulator(model_fn())
.update_parameters({"k1": 1.0, "k2": 2.0, "k_out": 1.0})
.simulate_time_course(np.linspace(0, 10, 101))
.get_result()
.unwrap_or_err()
).get_combined()
fig, ax = plot.lines(res)
ax.set(xlabel="time / a.u.", ylabel="Conc. & Flux / a.u.")
plt.show()
# Create data for protocol fitting
protocol = make_protocol(
[
(1, {"k1": 1.0}),
(1, {"k1": 2.0}),
(1, {"k1": 1.0}),
]
)
res_protocol = (
Simulator(model_fn())
.update_parameters({"k1": 1.0, "k2": 2.0, "k_out": 1.0})
.simulate_protocol(
protocol,
time_points_per_step=10,
)
.get_result()
.unwrap_or_err()
).get_combined()
fig, ax = plot.lines(res_protocol)
ax.set(xlabel="time / a.u.", ylabel="Conc. & Flux / a.u.")
plt.show()
Steady-states¶
For the steady-state fit we need two inputs:
- the steady state data, which we supply as a
pandas.Series - an initial parameter guess
The fitting routine will compare all data contained in that series to the model output.
Note that the data both contains concentrations and fluxes!
data = res.iloc[-1]
data.head()
x 0.500000 y 1.000045 v1 1.000000 v2 1.000000 v3 1.000045 Name: 10.0, dtype: float64
fit_result = fit.steady_state(
model_fn(),
p0={"k1": 1.038, "k2": 1.87, "k_out": 1.093},
data=res.iloc[-1],
minimizer=fit.LocalScipyMinimizer(),
).unwrap_or_err()
fit_result.best_pars
{'k1': np.float64(1.0000151370121395),
'k2': np.float64(2.0000302923452478),
'k_out': np.float64(0.9999697001966185)}
If only some of the data is required, you can use a subset of it.
The fitting routine will only try to fit concentrations and fluxes contained in that series.
fit_result = fit.steady_state(
model_fn(),
p0={"k1": 1.038, "k2": 1.87, "k_out": 1.093},
data=data.loc[["x", "y"]],
minimizer=fit.LocalScipyMinimizer(),
).unwrap_or_err()
fit_result.best_pars
{'k1': np.float64(0.9840909534736749),
'k2': np.float64(1.9681833703314742),
'k_out': np.float64(0.9840462172306368)}
By default, mxlpy will apply standard scaling to all fitting functions.
Specifically, it will calculate loss_fn(data - data.mean()) / data.std(), (pred - data.mean()) / data.std()).
To turn off this behaviour, set standard_scale=False in the fit functions
fit_result = fit.steady_state(
model_fn(),
p0={"k1": 1.038, "k2": 1.87, "k_out": 1.093},
data=data.loc[["x", "y"]],
minimizer=fit.LocalScipyMinimizer(),
standard_scale=False, # opt-out of standard scaling
).unwrap_or_err()
fit_result.best_pars
{'k1': np.float64(0.9829447162972054),
'k2': np.float64(1.9658848799451814),
'k_out': np.float64(0.9829008098837866)}
Time course¶
For the time course fit we need again need two inputs
- the time course data, which we supply as a
pandas.DataFrame - an initial parameter guess
The fitting routine will create data at every time points specified in the DataFrame and compare all of them.
Other than that, the same rules of the steady-state fitting apply.
fit_result = fit.time_course(
model_fn(),
p0={"k1": 1.038, "k2": 1.87, "k_out": 1.093},
data=res,
minimizer=fit.LocalScipyMinimizer(),
).unwrap_or_err()
fit_result.best_pars
{'k1': np.float64(1.0000001045209317),
'k2': np.float64(2.0000007550433407),
'k_out': np.float64(1.0000000436488663)}
Protocol time courses¶
For the protocol time course fit we need three inputs
- an initial parameter guess
- the time course data, which we supply as a
pandas.DataFrame - the protocol, which we supply as a
pandas.DataFrame
Note that the parameter given by the protocol cannot be fitted anymore
You can use the make_protocol function to create a protocol (see above).
The protocol DataFrame should preferrably use a pd.TimedeltaIndex and is interpreted as "use the parameter values of that row until the given end point."
Here a second corresponds to a unit of simulation time, regardless of model time scale.
mxlpy will attempt to convert other indices, again assuming that a second in your data corresponds to a second of simulation time.
protocol
| k1 | |
|---|---|
| Timedelta | |
| 0 days 00:00:01 | 1.0 |
| 0 days 00:00:02 | 2.0 |
| 0 days 00:00:03 | 1.0 |
fit_result = fit.protocol_time_course(
model_fn(),
p0={"k2": 1.87, "k_out": 1.093}, # note that k1 is given by the protocol
data=res_protocol,
protocol=protocol,
minimizer=fit.LocalScipyMinimizer(),
).unwrap_or_err()
fit_result.best_pars
{'k2': np.float64(1.9999999051296486), 'k_out': np.float64(1.0000002314720036)}
Group fitting (multi-start optimisation)¶
mxlpy supports group fitting, which is a single-model, single-data approach where the same model is fitted to the same data from many different initial parameter guesses.
This is exactly what is commonly called multi-start (or multistart) optimisation: each row of the p0 DataFrame is one start, the starts are run in parallel, and a GroupFit is returned. Use get_best_fit() to retrieve the best result and get_losses() to inspect the loss of every start.
A convenient way to generate diverse start guesses is
mxlpy.distributions.sample, as shown in the monte-carlo combination further down.
group_fit = fit.group_steady_state(
model_fn(),
data=res.iloc[-1],
p0=pd.DataFrame(
{
"k1": [1.037, 1.038, 1.039],
"k2": [1.86, 1.87, 1.88],
"k_out": [1.092, 1.093, 1.094],
}
),
minimizer=fit.LocalScipyMinimizer(tol=1e-6),
)
0%| | 0/3 [00:00<?, ?it/s]
33%|███▎ | 1/3 [00:03<00:06, 3.48s/it]
100%|██████████| 3/3 [00:03<00:00, 1.16s/it]
Time course¶
Time course fits are adjusted just the same
group_fit = fit.group_time_course(
model_fn(),
data=res,
p0=pd.DataFrame(
{
"k1": [1.037, 1.038, 1.039],
"k2": [1.86, 1.87, 1.88],
"k_out": [1.092, 1.093, 1.094],
}
),
minimizer=fit.LocalScipyMinimizer(tol=1e-6),
)
0%| | 0/3 [00:00<?, ?it/s]
33%|███▎ | 1/3 [00:04<00:08, 4.41s/it]
67%|██████▋ | 2/3 [00:04<00:02, 2.15s/it]
100%|██████████| 3/3 [00:04<00:00, 1.66s/it]
Protocol time course¶
As are protocol time courses
group_fit = fit.group_protocol_time_course(
model_fn(),
data=res_protocol,
protocol=protocol,
p0=pd.DataFrame(
{
"k1": [1.037, 1.038, 1.039],
"k2": [1.86, 1.87, 1.88],
"k_out": [1.092, 1.093, 1.094],
}
),
minimizer=fit.LocalScipyMinimizer(tol=1e-6),
)
0%| | 0/3 [00:00<?, ?it/s]
33%|███▎ | 1/3 [00:06<00:12, 6.02s/it]
100%|██████████| 3/3 [00:06<00:00, 2.01s/it]
Combining with monte-carlo approaches¶
An especially useful combination is combining group fitting with the monte-carlo capabilities of mxlpy to quickly get multiple fits from randomly selected initial conditions
from mxlpy.distributions import Uniform, sample
group_fit = fit.group_steady_state(
model_fn(),
data=res.iloc[-1],
p0=sample(
{
"k1": Uniform(1.037, 1.039),
"k2": Uniform(1.86, 1.88),
"k_out": Uniform(1.092, 1.094),
},
n=3,
),
minimizer=fit.LocalScipyMinimizer(tol=1e-6),
)
0%| | 0/3 [00:00<?, ?it/s]
33%|███▎ | 1/3 [00:03<00:06, 3.45s/it]
100%|██████████| 3/3 [00:03<00:00, 1.15s/it]
group_fit.get_losses()
0 0.000074 1 0.000074 2 0.000074 dtype: float64
best_model = group_fit.get_best_fit().model
Ensemble fitting¶
mxlpy supports ensemble fitting, which is a multi-model single data approach, where shared parameters will be applied to all models at the same time.
Here you supply an iterable of models instead of just one, otherwise the API stays the same.
ensemble_fit = fit.ensemble_steady_state(
[
model_fn(),
model_fn(),
],
data=res.iloc[-1],
p0={"k1": 1.038, "k2": 1.87, "k_out": 1.093},
minimizer=fit.LocalScipyMinimizer(tol=1e-6),
)
0%| | 0/2 [00:00<?, ?it/s]
50%|█████ | 1/2 [00:02<00:02, 2.54s/it]
100%|██████████| 2/2 [00:02<00:00, 1.27s/it]
To get the best fitting model, you can use get_best_fit on the ensemble fit
fit_result = ensemble_fit.get_best_fit()
And you can of course also access all other fits
[i.loss for i in ensemble_fit.fits]
[np.float64(7.416006594446728e-05), np.float64(7.416006594446728e-05)]
Time course¶
Time course fits are adjusted just the same
ensemble_fit = fit.ensemble_time_course(
[
model_fn(),
model_fn(),
],
data=res,
p0={"k1": 1.038, "k2": 1.87, "k_out": 1.093},
minimizer=fit.LocalScipyMinimizer(tol=1e-6),
)
0%| | 0/2 [00:00<?, ?it/s]
50%|█████ | 1/2 [00:03<00:03, 3.59s/it]
100%|██████████| 2/2 [00:03<00:00, 1.60s/it]
100%|██████████| 2/2 [00:03<00:00, 1.90s/it]
Protocol time course¶
As are protocol time courses
ensemble_fit = fit.ensemble_protocol_time_course(
[
model_fn(),
model_fn(),
],
data=res_protocol,
protocol=protocol,
p0={"k2": 1.87, "k_out": 1.093}, # note that k1 is given by the protocol
minimizer=fit.LocalScipyMinimizer(tol=1e-6),
)
0%| | 0/2 [00:00<?, ?it/s]
50%|█████ | 1/2 [00:03<00:03, 3.54s/it]
100%|██████████| 2/2 [00:03<00:00, 1.70s/it]
100%|██████████| 2/2 [00:03<00:00, 1.98s/it]
Joint fitting¶
Next, we support joint fitting, which is a combined multi-model multi-data approach, where shared parameters will be applied to all models at the same time
fit.joint_steady_state(
[
fit.FitSettings(model=model_fn(), data=res.iloc[-1]),
fit.FitSettings(model=model_fn(), data=res.iloc[-1]),
],
p0={"k1": 1.038, "k2": 1.87, "k_out": 1.093},
minimizer=fit.LocalScipyMinimizer(tol=1e-6),
)
Result(value=JointFit(
best_pars={
'k1': np.float64(1.000015151074822),
'k2': np.float64(2.0000303018865564),
'k_out': np.float64(0.9999697428737846)
},
loss=np.float64(0.00014832012817668331)
))
fit.joint_time_course(
[
fit.FitSettings(model=model_fn(), data=res),
fit.FitSettings(model=model_fn(), data=res),
],
p0={"k1": 1.038, "k2": 1.87, "k_out": 1.093},
minimizer=fit.LocalScipyMinimizer(tol=1e-6),
)
Result(value=JointFit(
best_pars={
'k1': np.float64(0.9999999830050853),
'k2': np.float64(2.0000001299926833),
'k_out': np.float64(0.9999999165993357)
},
loss=np.float64(1.0740812708609785e-06)
))
fit.joint_protocol_time_course(
[
fit.FitSettings(model=model_fn(), data=res_protocol, protocol=protocol),
fit.FitSettings(model=model_fn(), data=res_protocol, protocol=protocol),
],
p0={"k2": 1.87, "k_out": 1.093},
minimizer=fit.LocalScipyMinimizer(tol=1e-6),
)
Result(value=JointFit(
best_pars={
'k2': np.float64(2.000000270289329), 'k_out': np.float64(0.9999999526471528)
},
loss=np.float64(7.927485767173361e-07)
))
Mixed joint fitting¶
Lastly, we support mixed-joint fitting, where each analysis takes it's own residual function to allow fitting both time series and steady-state data for multiple models at the same time.
fit.joint_mixed(
[
fit.MixedSettings(
model=model_fn(),
data=res.iloc[-1],
residual_fn=fit.steady_state_residual,
),
fit.MixedSettings(
model=model_fn(),
data=res,
residual_fn=fit.time_course_residual,
),
fit.MixedSettings(
model=model_fn(),
data=res_protocol,
protocol=protocol,
residual_fn=fit.protocol_time_course_residual,
),
],
p0={"k2": 1.87, "k_out": 1.093},
minimizer=fit.LocalScipyMinimizer(tol=1e-6),
)
Result(value=JointFit(
best_pars={
'k2': np.float64(2.0000000585238116), 'k_out': np.float64(1.0000000660533466)
},
loss=np.float64(0.0001292142375263089)
))
First finish line
With that you now know most of what you will need from a day-to-day basis about fitting in mxlpy.Congratulations!
Advanced topics / customisation¶
All fitting routines internally are build in a way that they will call a tree of functions.
minimizerresidual_fnintegratorloss_fn
You can therefore use dependency injection to overwrite the minimisation function, the loss function, the residual function and the integrator if need be.
from functools import partial
from typing import cast
from mxlpy.integrators import Scipy
Parameterising scipy optimise¶
optimizer = fit.LocalScipyMinimizer(tol=1e-6, method="Nelder-Mead")
Gradient-based fitting¶
With the built-in residual functions, fits give minimizers the exact gradient, the residual Jacobian and a Gauss-Newton Hessian, computed only when a minimizer asks for them.
The runner computes them, so runner=KineticRunner(derivatives=...) chooses how:
derivatives="auto"(the default) integrates the forward sensitivitiesdS/dt = J·S + ∂f/∂θalongside the model (see parameter sensitivities); for steady-state fits it uses the implicit function theorem. Models that can't be differentiated symbolically (surrogates, events, the Native or Diffrax integrators) fall back to finite differences, as do protocol fits and fits with apostprocess_fn.derivatives="finite_difference"always uses central finite differences,derivatives="forward"warns when it can't be used.
Gradient methods of LocalScipyMinimizer (e.g. L-BFGS-B, the default for more than one parameter) and FixedNMinimizer receive jac=; methods using a Hessian like method="trust-constr" also get the Gauss-Newton approximation of the Hessian (for the rmse and mean_squared losses).
LeastSquaresMinimizer wraps scipy.optimize.least_squares (method="trf"|"dogbox"|"lm") and works directly on the residual vector, which usually converges in far fewer simulations.
fit_result = fit.time_course(
model_fn(),
p0={"k1": 1.038, "k2": 1.87, "k_out": 1.093},
data=res,
minimizer=fit.LeastSquaresMinimizer(),
).unwrap_or_err()
fit_result.best_pars
{'k1': np.float64(1.0),
'k2': np.float64(2.0),
'k_out': np.float64(0.9999999999999999)}
Rate constants often span several orders of magnitude.
With transform="log" (or a per-parameter mapping like {"k1": "log"}) the minimizer works in log10 space, which keeps parameters positive and makes steps scale-free.
Log-transformed parameters without explicit bounds get the bounds (1e-6, 1e6).
Transforms are opt-in, since a quasi-Newton method like L-BFGS-B can overshoot by a factor of ten on its first log-space step.
fit_result = fit.time_course(
model_fn(),
p0={"k1": 10.0, "k2": 0.1, "k_out": 5.0},
data=res,
minimizer=fit.LeastSquaresMinimizer(),
transform="log",
).unwrap_or_err()
fit_result.best_pars
{'k1': np.float64(1.0000000000000002),
'k2': np.float64(1.9999999999999967),
'k_out': np.float64(0.9999999999999993)}
Priors and maximum-a-posteriori estimation¶
Prior knowledge about parameters, e.g. literature values from mxlpy.parameterise, can enter a point fit as prior={name: distribution}, the same mapping fit.mcmc takes.
The fit then minimises loss + Σ penalty, where each penalty is the negative log density of the prior: Normal and LogNormal pull towards their centre, SoftBounds only penalises values outside a range (a smooth alternative to hard bounds), Laplace is an L1 penalty.
Parameters without a prior are unpenalised.
Distributions defined on a log scale (LogNormal, LogUniform, SoftBounds(log=True)) are penalised on log(θ), so LogNormal(np.log(0.5), 0.2) pulls towards 0.5 and LogUniform is flat.
The penalty doesn't depend on transform, so neither does the optimum.
The penalty is only on the same scale as the loss for a likelihood: with loss_fn=fit.GaussianNll(noise), the negative log-likelihood of Gaussian measurement noise (a standard deviation as a scalar, one per observable or one per data point, or a fit.Noise, see below), the fit is a proper maximum-a-posteriori estimate.
With heuristic losses like the default rmse the prior acts as a regularisation, whose strength you set with penalty=fit.PriorPenalty(prior, weight=...).
LeastSquaresMinimizer minimises exactly the same loss + penalty, which needs a loss that is a sum of squares (GaussianNll or mean_squared); for other losses use e.g. LocalScipyMinimizer.
from mxlpy.distributions import LogNormal, SoftBounds
fit_result = fit.time_course(
model_fn(),
p0={"k1": 10.0, "k2": 0.1, "k_out": 5.0},
data=res,
minimizer=fit.LeastSquaresMinimizer(),
loss_fn=fit.GaussianNll(0.05),
prior={
"k1": LogNormal(mean=np.log(1.0), sigma=0.5),
"k_out": SoftBounds(lower=0.1, upper=10.0, scale=0.2, log=True),
},
transform="log",
).unwrap_or_err()
fit_result.best_pars, fit_result.loss, fit_result.penalty
({'k1': np.float64(1.0),
'k2': np.float64(2.0),
'k_out': np.float64(0.9999999999999997)},
8.852498470777042e-27,
0.0)
Fit.loss is the loss of the data alone and Fit.penalty the prior's contribution at the optimum, so multi-start fits pick their best fit by fit_result.objective = loss + penalty.
Penalties coupling several parameters (e.g. for regularising differences between conditions) implement the fit.Penalty protocol and are passed as penalty=.
With the Native integrator's llvm backend installed (mxlpy[native]), LeastSquaresMinimizer(method="lm", backend="native") runs the whole Levenberg-Marquardt fit in compiled code: the model, its sensitivities and the fit loop.
It usually is several times faster than the scipy backend, and integrates with the method and tolerances of the runner's Native integrator (Radau or LSODA).
Like any method="lm" fit it ignores bounds, so use transform="log" for parameters that have to stay positive.
Fits it can't compile (e.g. with a postprocess_fn or fitted initial values) fall back to the scipy backend with a warning.
fit_result = fit.time_course(
model_fn(),
p0={"k1": 10.0, "k2": 0.1, "k_out": 5.0},
data=res,
minimizer=fit.LeastSquaresMinimizer(method="lm", backend="native"),
transform="log",
).unwrap_or_err()
fit_result.best_pars
{'k1': 1.000000020362066,
'k2': 2.0000000512926563,
'k_out': 1.0000000091392347}
Measurement noise: relative errors and detection limits¶
Most assays don't have a constant measurement error: blots, fluorescence and metabolomics typically have an error proportional to the signal.
fit.Noise describes a known noise per observable with an absolute part a and a relative part b, combined as \(\sigma^2 = a^2 + b^2 \hat{y}^2\) (or \(\sigma = a + b|\hat{y}|\) with form="sd").
\(\sigma\) is evaluated on the model's prediction \(\hat{y}\), not on the noisy data, so the negative log-likelihood includes the \(\log \sigma\) terms.
Both parts are known constants, nothing is estimated.
The same object is used everywhere a noise is needed: fit.GaussianNll(noise), fit.Condition(data, noise=noise), fit.mcmc(noise=noise) and identify.fisher_information(noise=noise).
A plain number (or a Series per observable) still works and means an absolute noise.
noise = fit.Noise(absolute=0.01, relative=0.1)
rng = np.random.default_rng(0)
truth = res.loc[:, ["x", "y"]]
noisy = truth + noise.sigma(truth) * rng.standard_normal(truth.shape)
fit_result = fit.time_course(
model_fn(),
p0={"k1": 10.0, "k2": 0.1, "k_out": 5.0},
data=noisy,
loss_fn=fit.GaussianNll(noise),
minimizer=fit.LeastSquaresMinimizer(),
transform="log",
).unwrap_or_err()
fit_result.best_pars
{'k1': np.float64(1.023125984084383),
'k2': np.float64(2.062501464988465),
'k_out': np.float64(1.0130455954867896)}
Measurements below a limit of detection (or above a saturation limit) only tell that the value lies beyond the limit.
Dropping them hides the information that the value is low, imputing e.g. half the limit pretends a precision the data doesn't have.
With lower_limit (and upper_limit), censored entries enter the likelihood through the normal cumulative distribution, \(-\log \Phi((L - \hat{y}) / \sigma)\).
By default every value at or below the limit counts as censored; a boolean censored mask marks them explicitly, and then their data may be missing (NaN).
# a detection limit per observable, censoring its lowest fifth
limit = noisy.quantile(0.2)
below = noisy <= limit
censored_data = noisy.where(~below)
print(f"{int(below.to_numpy().sum())} of {below.size} values censored")
censored_fit = fit.time_course(
model_fn(),
p0={"k1": 10.0, "k2": 0.1, "k_out": 5.0},
data=censored_data,
loss_fn=fit.GaussianNll(
fit.Noise(absolute=0.01, relative=0.1, lower_limit=limit, censored=below)
),
minimizer=fit.LeastSquaresMinimizer(),
transform="log",
).unwrap_or_err()
censored_fit.best_pars
42 of 202 values censored
{'k1': np.float64(1.0291805610046205),
'k2': np.float64(2.0731214868724077),
'k_out': np.float64(1.018985434462759)}
Least squares minimise these likelihoods exactly, with a second block of residuals for the \(\log \sigma\) terms.
Purely relative noise (no absolute part) can't be written as least squares, use e.g. LocalScipyMinimizer for it.
The Fisher information evaluates \(\sigma\) on the prediction as well, and weights observables with detection limits by the expected information of a censored measurement, so a measurement far below the limit carries almost none.
variance_term=True adds the information that a prediction-dependent \(\sigma\) carries about the parameters.
from mxlpy import identify
fim = identify.fisher_information(
model_fn(), noisy, fit_result, noise=noise, variance_term=True
)
fim.wald_ci()
| value | std_error | lower | upper | |
|---|---|---|---|---|
| k1 | 1.023126 | 0.099450 | 0.828208 | 1.218044 |
| k2 | 2.062501 | 0.194383 | 1.681517 | 2.443486 |
| k_out | 1.013046 | 0.094079 | 0.828654 | 1.197437 |
Custom loss function¶
You can change the loss function that is being passed to the minimsation function using the loss_fn keyword.
Depending on the use case (time course vs steady state) this function will be passed two pandas DataFrames or Series.
def mean_absolute_error(
x: pd.DataFrame | pd.Series,
y: pd.DataFrame | pd.Series,
) -> float:
"""Mean absolute error between two dataframes."""
return cast(float, np.mean(np.abs(x - y)))
(
fit.time_course(
model_fn(),
p0={"k1": 1.038, "k2": 1.87, "k_out": 1.093},
data=res,
loss_fn=mean_absolute_error,
minimizer=fit.LocalScipyMinimizer(),
)
.unwrap_or_err()
.best_pars
)
{'k1': np.float64(1.0000000004897749),
'k2': np.float64(1.9999999969474105),
'k_out': np.float64(1.0000000022874433)}
Post-processing the simulation¶
Derived values and readouts are calculated per time point, so quantities that depend on the whole time course (e.g. NPQ, which normalises the maximal fluorescence of every pulse by the first one) can't be expressed in the model itself.
For these you can pass a postprocess_fn to every fitting routine.
It receives the combined simulation result (variables, derived values, readouts and fluxes) at the time points of the data and has to return a DataFrame containing the data columns, which is then compared to the data by the loss function.
Here, for example, we fit to data that was normalised by its last value.
def relative_to_steady_state(df: pd.DataFrame) -> pd.DataFrame:
"""Normalise every column by its last value."""
return df / df.iloc[-1]
(
fit.time_course(
model_fn(),
p0={"k1": 1.038, "k2": 1.87, "k_out": 1.093},
data=relative_to_steady_state(res),
postprocess_fn=relative_to_steady_state,
minimizer=fit.LocalScipyMinimizer(),
)
.unwrap_or_err()
.best_pars
)
{'k1': np.float64(1.0000018022076322),
'k2': np.float64(2.000004076376832),
'k_out': np.float64(1.0000019942575444)}
Custom integrator¶
How the model is simulated during fitting is configured by a runner (see the integrator configuration). You can change the default integrator to an integrator of your choice by passing a runner with a partial application of the class of any of the existing ones.
Here, for example, we choose the Scipy solver suite and set the default relative and absolute tolerances to 1e-6 respectively.
from mxlpy import KineticRunner
(
fit.time_course(
model_fn(),
p0={"k1": 1.038, "k2": 1.87, "k_out": 1.093},
data=res,
runner=KineticRunner(integrator=partial(Scipy, rtol=1e-6, atol=1e-6)),
minimizer=fit.LocalScipyMinimizer(),
)
.unwrap_or_err()
.best_pars
)
{'k1': np.float64(1.000000180229277),
'k2': np.float64(2.0000005304435757),
'k_out': np.float64(1.0000001345414582)}