Parameter fitting¶
A fit changes parameters of a model until its simulations match measured data. You tell sbmlsim which data belongs to which simulation (fit mappings), which parameters it may change and within which bounds (fit parameters), and how to compare simulation and data (settings). It runs local or global optimizers of SciPy from many start points, and a report shows how well the fitted model describes the data.
This page continues the fit at the end of the Tutorial. The examples use examples/hctz_fitting, the HCTZ model with the clinical studies of Patel et al. (1984) and Beermann et al. (1976). It is part of the repository, not of the installed package, so run the code from the root of a clone of sbmlsim.
A first fit¶
Define the problem¶
The study of Patel et al. (1984) gave single oral doses of HCTZ to healthy volunteers and measured HCTZ in the plasma and the amount excreted into the urine. The simulation experiment Patel1984 describes the study, and its fit mappings pair each measured curve with the simulated variable, e.g. fm_25_tab is the plasma concentration after a 25 mg tablet.
An OptimizationProblem collects the data and the parameters of a fit. Here the data of the 25 mg tablet is fitted (training data), and the 50 mg tablet is kept back to check the fit on data it was not fitted to (validation data). The fit estimates the dissolution rate of the tablet and the excretion rate of the kidneys:
from examples.hctz_fitting import DATA_PATH, HCTZ_PATH
from examples.hctz_fitting.experiments.studies import Patel1984
from sbmlsim.fit import FitMappingCollection, FitParameter, MappingKind
from sbmlsim.fit.optimization import OptimizationProblem
problem = OptimizationProblem(
opid="hctz_patel",
mapping_collections=[
FitMappingCollection(Patel1984, mappings=["fm_25_tab", "fm_25_tab_urine"]),
FitMappingCollection(
Patel1984,
mappings=["fm_50_tab", "fm_50_tab_urine"],
kind=MappingKind.VALIDATION,
),
],
fit_parameters=[
FitParameter(pid="Ka_dis_hctz", lower_bound=0.01, upper_bound=10, unit="1/hr"),
FitParameter(pid="KI__HCTZEX_k", lower_bound=1e-5, upper_bound=1, unit="1/ml"),
],
base_path=HCTZ_PATH,
data_path=DATA_PATH,
)
base_path is the directory the models of the experiments are relative to, data_path the directory of their datasets.
Run the optimization¶
FitSettings say how simulation and data are compared. The settings below divide every residual by the mean of its curve, so the plasma concentration and the amount in urine count the same although their values differ by orders of magnitude. Every curve gets the same weight whatever its number of points, and a point measured with a small standard deviation counts more than an uncertain one. run_optimization draws size random start points within the bounds, runs the local least squares optimizer from each and collects the results:
from sbmlsim.fit import FitSettings
from sbmlsim.fit.options import ResidualType, WeightingCurvesType, WeightingPointsType
from sbmlsim.fit.runner import run_optimization
settings = FitSettings(
residual=ResidualType.NORMALIZED,
weighting_curves=(WeightingCurvesType.POINTS,),
weighting_points=WeightingPointsType.ERROR_WEIGHTING,
)
fit = run_optimization(problem, settings, size=4, seed=1, show_progress=False)
print(fit.df_fits[["run", "cost", "Ka_dis_hctz", "KI__HCTZEX_k"]])
π Optimization ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
π Parameters (2) βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
parameter start lower upper unit
βββββββββββββββββββββββββββββββββββββββββββ
Ka_dis_hctz - 0.01 10 1/hr
KI__HCTZEX_k - 1e-05 1 1/ml
runs 4
workers 1 (threads of the engine, one fit)
converged 4/4 runs
best cost 0.0496035
optimizer time 0.0 s
run cost Ka_dis_hctz KI__HCTZEX_k
0 1 0.049603 0.304811 0.005028
1 0 0.049603 0.304812 0.005028
2 2 0.049603 0.304812 0.005028
3 3 0.049603 0.304795 0.005028
show_progress says whether the fit reports what it does: on a terminal a bar per activity (the runs of the fit and the points of their jacobians), without one a line every 30 seconds, each with the count, the elapsed time, the estimate of the time which is left and the cores, the CPU and the memory of the run, see Progress. The setting is the same everywhere, --progress of python -m sbmlsim.run or SBMLSIM_PROGRESS.
Every run ends at about the same parameters, so the optimum is well defined. With a seed the start points, and therefore the result, are the same in every session.
Look at the report¶
A FitReport evaluates parameter sets on the problem: metrics, figures and an HTML page. from_optimization_result reports the best parameter set of a fit:
from pathlib import Path
from sbmlsim.fit.report import FitReport
report = FitReport.from_optimization_result(problem, fit, mapping_figures=False)
metrics = report.metrics_df()
print(metrics[["kind", "n", "NRMSE", "R2", "GMFE", "within_2fold"]].round(2))
report.create(Path("results"), name="hctz_patel")
kind n NRMSE R2 GMFE within_2fold
0 training 21 0.15 0.98 1.19 95.0
1 validation 21 0.20 0.93 1.24 95.0
π Report ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
directory hctz_patel
parameter sets hctz_patel_0
mappings 2 training, 2 validation
report file://./results/hctz_patel/index.html
The metrics are computed separately for the training data and the validation data. GMFE is the geometric mean fold error and within_2fold the percentage of points whose prediction is within a factor of two of the data, see Metrics. create writes the report into results/hctz_patel, with index.html as its page. mapping_figures=False skips the figure of every fit mapping to keep this example fast. Without it, the report has a figure per mapping with the data and the simulated curve.
report.points is the table behind the figures of the report: one row per data point with its time x, the data DV, its standard deviation DV_SD and the prediction IPRED, all in the units of the model, which the columns x_unit and unit give. To draw the fitted curves against the data, simulate the doses with the fitted values and turn both into quantities:
from sbmlsim import Q
from sbmlsim.plot import Chart, ChartAxis
from sbmlsim.resources import HCTZ_SBML
from sbmlsim.simulation import Simulation
from sbmlsim.simulator import Simulator
fitted = fit.parameter_set()
fitted_changes = {pid: Q(v, fitted.units[pid]) for pid, v in fitted.values.items()}
points = report.points(fitted)
simulator = Simulator()
model = simulator.load(HCTZ_SBML)
chart = Chart(width=720, height=300, columns=2)
time_axis = ChartAxis(label="time", unit="hr")
ax1 = chart.plot(0, 0, x=time_axis, y=ChartAxis(label="HCTZ plasma", unit="Β΅M"))
ax2 = chart.plot(0, 1, x=time_axis, y=ChartAxis(label="HCTZ urine", unit="Β΅mol"))
for dose, kind, marker, color in [
(25, "training", "circle", "#1f77b4"),
(50, "validation", "square", "#ff7f0e"),
]:
tablet = Simulation(
time_unit="hr",
end=48,
preinit_changes={**fitted_changes, "PODOSE_hctz": Q(dose, "mg")},
)
res = simulator.run(model, tablet)
for ax, key, yid, unit in [
(ax1, f"fm_{dose}_tab", "[Cve_hctz]", "Β΅M"),
(ax2, f"fm_{dose}_tab_urine", "Aurine_hctz", "Β΅mol"),
]:
label = f"{dose} mg ({kind})"
ax.curve(res.q["time"], res.q[yid], label=label, color=color)
data = points[points.mapping == key]
time = Q(data.x.to_numpy(), data.x_unit.iloc[0])
dv = Q(data.DV.to_numpy(), data.unit.iloc[0])
sd = Q(data.DV_SD.to_numpy(), data.unit.iloc[0])
ax.curve(time, dv, yerr=sd, line="none", marker=marker, color=color)
The fitted model follows the 25 mg data, although in the urine it rises faster than the data between 12 and 36 hours. For the 50 mg tablet, which the fit has not seen, it predicts about 10 % more HCTZ in the urine than was measured. The goodness of fit plots every prediction against its measurement on logarithmic axes, so plasma and urine fit into one plot. Points on the diagonal are perfect predictions, and the dotted lines mark a factor of two:
positive = points[(points.DV > 0) & (points.IPRED > 0)]
limits = [positive[["DV", "IPRED"]].min().min() / 2, positive.DV.max() * 2]
chart = Chart(width=420, height=420)
plot = chart.plot(
x=ChartAxis(
label="measurement [model units]", scale="log", min=limits[0], max=limits[1]
),
y=ChartAxis(
label="prediction [model units]", scale="log", min=limits[0], max=limits[1]
),
)
for (kind, data), color in zip(positive.groupby("kind"), ["#1f77b4", "#ff7f0e"]):
plot.curve(
data.DV.to_numpy(),
data.IPRED.to_numpy(),
line="none",
marker="circle",
opacity=0.7,
color=color,
label=kind,
)
plot.curve(limits, limits, color="#000000", width=1)
for factor in [2, 0.5]:
plot.curve(limits, [factor * v for v in limits], line="dotted", color="#8b0000")
The report draws this figure and a Bland-Altman plot with a panel per kind of data, see Report of a fit.
Fit mappings¶
A FitMapping is defined in the fit_mappings() of a SimulationExperiment and pairs a reference, usually the measured data, with an observable, the simulated variable. Both are FitData: the reference reads columns of a dataset (dataset=), the observable a variable or observable of a task (task=). The Tutorial defines a complete experiment with one mapping, and examples/hctz_fitting/experiments/studies/patel1984.py has many.
xidandyidare the x (usuallytime) and the y of the data.yid_sdoryid_seis the column of the standard deviation or the standard error of the data. A standard error is converted to a standard deviation with the number of subjects,count, an integer or a column of the dataset.yid_gsdis the column of the geometric standard deviation of data which are geometric means, a factor without a unit:log(gmean)has the standard deviationlog(gsd). The fit treats such a point as a mean with the coefficient of variation of the log-normal distribution,sqrt(exp(log(gsd)^2) - 1), i.e. with the standard deviationgmean * sqrt(exp(log(gsd)^2) - 1), so the weights ofERROR_WEIGHTINGcompare it with the means of other data. Its noise in the log-likelihood and in the PEtab export is log-normal with the standard deviationlog(gsd), and the report draws its error bars fromgmean / gsdtogmean * gsd. It cannot be combined withyid_sdoryid_se.selselects labels of the dimensions of a scan, or rows of a dataset by the values of its columns, see Data.FitMapping(metadata=...)attaches aMappingMetaDatato describe the curve, e.g. the tissue, the route or the dosing. Filters can select data by it, and reports show it and can group by it.examples/hctz_fitting/experiments/metadata.pyis an example of a subclass.
sbmlsim checks that reference and observable have compatible units and converts the data to the units of the model.
Values per simulation and over a dimension¶
A fit mapping does not have to be a timecourse. Its kind follows from the dimensions of the observable after sel:
- A timecourse has the time as x.
- A value per simulation has no x, e.g. the peak concentration of a
PKobservable:FitData(self, task="task_doses", xid=None, yid="pk.cmax", sel={"dose": "standard"}). Its reference is one or several rows of a dataset, e.g. the subjects of a study group selected withsel={"group": "25mg"}. - Values over a dimension of a scan have the values of the dimension as x, e.g.
FitData(self, task="task_doses", xid="dose.PODOSE", yid="pk.cmax")against data with the doses as x. The simulated values are interpolated linearly to the x of the data, so the dimension must be monotonic and cover the data.
Anything else raises when the problem is initialized and asks you to select a label with sel=. A prediction which is NaN, e.g. a PK parameter of a curve without a terminal phase, gets a large failure residual. A value of a dimension replaces a fitted parameter with the same target, so such a parameter has no effect on the points of the scan; the problem warns about it. examples/experiment_scans.py fits the metabolism of midazolam to a table of cmax over the dose. These mappings cannot be exported to PEtab.
Training, validation and outlier data¶
What a fit does with a curve is decided by the MappingKind of its FitMappingCollection, so the same curve can be training data of one fit and validation data of another:
| kind | fitted | in the report | use it for |
|---|---|---|---|
TRAINING (default) |
yes | yes | the data the parameters are estimated from |
VALIDATION |
no | yes | checking the fit on data it has not seen |
OUTLIER |
no | yes | data which is not usable, but which you want to compare with the model |
EXCLUDED |
no | no | data the model does not describe, e.g. a study arm with a second drug the model knows nothing about |
With many studies, writing the collections by hand gets tedious. FitMappings (in sbmlsim.fit.helpers) loads all fit mappings of the experiments once, and select assigns the kinds in three steps:
- Filters select the training data. A filter is a function of the key of a mapping and the
FitMapping, e.g. a test of its metadata. A mapping which fails a filter is excluded. - Outliers are named by their keys. An outlier stays excluded if the filters exclude it.
- Validation data is chosen from the rest, by keys or by a filter.
Here the fit uses all HCTZ amounts in urine of the two studies, drops one curve as an outlier and validates on the highest dose:
from examples.hctz_fitting.experiments.studies import Beermann1976
from sbmlsim.fit.helpers import FitMappings
fit_mappings = FitMappings(
experiment_classes=[Beermann1976, Patel1984],
base_path=HCTZ_PATH,
data_path=DATA_PATH,
)
selection = fit_mappings.select(
filters=[lambda key, fit_mapping: key.endswith("_urine")],
outliers={"fm_hctz_iv1_5_urine"},
validation={"fm_200_tab_urine", "fm_200_sus_urine"},
print_info=False,
)
selection.print(detail=False)
π Data (44 fit mappings) ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
experiment training validation outlier excluded mappings
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Beermann1976 8 0 1 9 18
Patel1984 6 2 0 18 26
total 14 2 1 27 44
selection.collections holds the FitMappingCollections, one per experiment and kind, and selection.df a table of every mapping with its kind and metadata. select_mapping_collections does it all in one call, select_mappings(project, experiment_classes, ...) with the paths of a project. examples/hctz_fitting/fitting/mapping_collections.py names the outliers and the validation data once and defines each fit as a list of filters on the metadata.
sbmlsim.fit.filters has the filters of the common cases, frozen dataclasses which compare, pickle into the workers of a parallel fit and say what they select: metadata_filter(HCTZMappingMetaData, route={Route.PO}, excluded={"dosing": {Dosing.MULTI}}) selects by the fields of the metadata of a mapping, a dataclass derived from MappingMetaData, and checks the names of the fields and that the values are sets when it is built; observable_filter({"Cve_hctz"}) selects by the observable of a mapping (observable_id, the index of its data), named_filter({"Beermann1976": {"fm_hctz_iv1_5_urine"}}) by the key of a mapping in its study and filter_keys by the key in any study. The value of a field which metadata_filter compares is MappingMetaData.filter_value(name), the field itself, which a metadata class overrides for a field it compares in another form, e.g. a sampling site which follows the tissue when it is not stated.
On an initialized problem, mapping_counts() gives the number of mappings of each kind.
Parameters¶
A FitParameter names an entity of the model (pid) with its bounds and unit:
lower_boundandupper_boundare the box the optimizer searches.unitis a unit of pint or of the unit ids of the model, e.g.per_min. Without it the value is in the unit of the model.start_valueis where every run starts withsampling=SamplingType.START(see Running the optimization). A parameter with an infinite bound is not sampled and needs it as well.descriptiondescribes the parameter in the report. Without it, the report uses its name in the model.prioris a prior of PEtab v2, a distribution of sampling or anUncertainvalue, e.g.Uncertain(Q(1.2, "1/hr"), cv=0.3). A fit of the objectiveposteriorminimizes the negative log posterior with it (see The objective), the other objectives leave it out. It is exported to PEtab and evaluated bylog_priorof the PEtab layer.FitDefinition(prior_correlation=...)correlates the priors of some parameters, see Priors and the posterior of a fit.
The optimizer searches the parameters on the parameter_scale of the settings: LOG10 by default, because a rate constant often spans orders of magnitude, or LOG and LINEAR. A logarithmic scale needs finite positive bounds. FitParameter(scale=...) sets the scale of a single parameter, e.g. LINEAR for one which can be zero or negative. Bounds, start values and results are always in the units of the model.
One parameter for part of the data¶
Sometimes a parameter should be estimated from only part of the data. The dissolution rate of a tablet, for example, has no effect after an intravenous dose. target names the entity of the model the value is written to, and mappings is a filter (or a list of filters) of the fit mappings the parameter applies to. Simulations the parameter does not reach keep the value of the model. Several parameters with the same target can cover different parts of the data, e.g. a dissolution rate for tablets and another for capsules.
from examples.hctz_fitting.experiments.metadata import Route
from sbmlsim.fit import FitMapping
from sbmlsim.fit.display import print_parameters
def is_oral(key: str, fit_mapping: FitMapping) -> bool:
"""Select the oral data."""
return fit_mapping.metadata.route == Route.PO
by_route = OptimizationProblem(
opid="hctz_routes",
mapping_collections=[
FitMappingCollection(
Beermann1976, mappings=["fm_hctz_iv35_4_urine", "fm_hctz_po5_1_urine"]
),
],
fit_parameters=[
FitParameter(
pid="Ka_dis_hctz_po",
target="Ka_dis_hctz",
mappings=is_oral,
lower_bound=0.01,
upper_bound=10,
unit="1/hr",
),
FitParameter(pid="KI__HCTZEX_k", lower_bound=1e-5, upper_bound=1, unit="1/ml"),
],
base_path=HCTZ_PATH,
data_path=DATA_PATH,
)
by_route.initialize(settings)
print_parameters(by_route.parameters, by_route.parameter_mapping.coverage())
π Parameters (2) βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
parameter target start lower upper unit
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Ka_dis_hctz_po Ka_dis_hctz - 0.01 10 1/hr
KI__HCTZEX_k KI__HCTZEX_k - 1e-05 1 1/ml
parameter target simulations not covered
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Ka_dis_hctz_po Ka_dis_hctz 1 of 2 Beermann1976|fm_hctz_iv35_4_urine
KI__HCTZEX_k KI__HCTZEX_k 2 of 2 -
The coverage table shows that Ka_dis_hctz_po reaches one of the two simulations and leaves out the intravenous one. The fit and its report print the same table. The problem checks the parameters when it is initialized: two parameters must not write the same target in one simulation, a filter must select either all or none of the mappings which share a simulation, and the parameters of one target must have the same unit. A filter which selects nothing only warns.
A filter must be a function defined at the top level of a module, not a lambda: the workers of a parallel fit unpickle it. The PEtab export writes the selected mappings, not the filter, see PEtab.
Settings¶
FitSettings decide how the cost is computed and how the simulations of the fit are integrated. A fit stores its settings with its result, and its report uses the same ones.
β Settings βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
setting value
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
objective least_squares
residual NORMALIZED
loss function LINEAR
weighting curves POINTS
weighting points ERROR_WEIGHTING
relative tolerance 1.0e-06
absolute tolerance amount 1.0e-10, concentration 1.0e-10, other 1.0e-10
variable step size True
initial time step 0
data at a change before
The objective¶
objective decides what the fit minimizes (ObjectiveType, a string is converted):
least_squares(default): the weighted least squares of the residuals, see Residuals and weights. The spread of the data weights the points, it is data and not a parameter.likelihood: the negative log-likelihood of the training data, i.e. the maximum likelihood estimate. Every fit mapping has a noise model, thenoiseof itsFitMapping(aNoiseModel: a noise formula and a distribution,normal,log-normal,laplaceorlog-laplace), or without one the normal noise of the standard deviations of its data, see The log-likelihood. A parameter of a noise formula is estimated with the parameters of the model, e.g. the standard deviation of an observable:NoiseModel(formula="sd_cp")with aFitParameter("sd_cp", ...), a parameter the model gets withAbstractModel(parameters={"sd_cp": 1.0}). The residual type, the weights and the loss function do not enter.posterior: the negative log posterior, the negative log-likelihood minus the log density of the priors of the parameters (FitParameter(prior=...)), i.e. the maximum a posteriori estimate. A parameter without a prior has the uniform prior over its bounds, which is a constant. Correlated priors (prior_correlation) are whitened, see Priors and the posterior of a fit, whose Laplace approximation of the posterior is the uncertainty of the estimate.
The cost of a fit of the likelihood is the negative log-likelihood or log posterior itself, so the threshold of the profile likelihood is the one of the likelihood ratio. The least squares optimizer minimizes it as a sum of squares: every data point has the residual of its data, (y - m) / Ο, and one of the scale of its noise, sqrt(log(2 Ο ΟΒ²) + c) with a constant c, which is not part of the cost. A problem of PEtab which is read without the sbmlsim extension is fitted with likelihood, as PEtab defines its objective. A likelihood needs the data as it was measured, it cannot be combined with the residuals relative to the baseline.
A likelihood runs in sbmlsim-core (#613, #626), whatever its noise distribution and whether or not the fit moves the scale of the noise. A normal or log-normal noise whose scale the fit does not move is a curve of noise that scale: the term of the scale is constant, so the residual of every point is the one of a weighted least squares. Every other noise model is the likelihood of its curve (sbmlsim-core 0.24.0), the distribution of its noise, which gives the curve a second row per measurement for the scale of that noise, and the scale of a noise the fit moves, e.g. sd_cp or a formula which reads the observable, is a column of the model of the fit (the noise_column of the curve) and no number, which the engine reads in the row of every measurement as python evaluates the formula there. A log kind reads the logarithm of its observable off a column of the model of the fit and compares it with the logarithms of its measurements. The cost of such a run is shifted by the constants of those rows, so a fit in the engine reports the same negative log-likelihood as a fit in python, and the engine simulates the data of the fit bitwise; the row of the scale is the one row whose logarithm the engine evaluates itself, so it agrees with python to within an ulp. A posterior runs in the engine as well: the prior of a parameter is one row of the request, the kind of the prior with the parameters of PEtab, the offset which keeps that row positive and the logarithm of the mass of the prior between the bounds of its parameter, which the engine subtracts from the density of the kind, since a distribution function is no term of a density; the correlated priors are one block, the multivariate normal of their scores, whose rows are the whitened scores and one more per log-normal prior. Those rows come after every row of the curves and are the last residuals of the problem, which is why the Fisher information drops them and stays the information of the data alone (the curvature of the priors belongs to the Laplace posterior); a prior row is the other row whose logarithm the engine evaluates itself, so it agrees with python to within an ulp as well. The optimizer stays in python for a prior of a kind the engine does not evaluate, e.g. a gamma prior, for a prior of a parameter whose unit is not the one of its target, since the engine holds the value of the target, for a prior whose support does not cover the bounds of its parameter, e.g. a uniform prior narrower than them, whose zero density between them is a penalty the optimizer of python walks out of and a row of NaN in a request, for a noise whose placeholder has a value per measurement and for a measurement of a log kind which is not positive.
Residuals and weights¶
The cost of least_squares is 0.5 * sum(w * r**2) over the data points of the training data, with the residuals r and the weights w:
residual:ABSOLUTE(default), the data minus the prediction, orNORMALIZED, divided by the mean of the curve. UseNORMALIZEDwhen curves of very different magnitude enter one fit.weighting_curves:MAPPINGmultiplies a curve by theweightsof itsFitMappingCollection, or withFitMappingCollection(use_mapping_weights=True)by theweightof itsFitMapping, which defaults to the number of subjects (count).POINTSdivides a curve by its number of points, so that a curve with many points does not dominate. Both can be combined; without either, every point counts the same.-
weighting_points:NO_WEIGHTING(default) orERROR_WEIGHTING, which weights a point bymean / SD, the inverse of its coefficient of variation. A curve without standard deviations gets the weight of a coefficient of variation of 0.5. A row with a standard error and no count raises when the problem is initialized.A weight of exactly zero is a measurement which carries no information:
ERROR_WEIGHTINGgives it to a measurement of zero, a zero baseline, and the weight of aFitMappinggives it to every point of that mapping. Such a point is carried as a curve of an infinite standard deviation (sbmlsim-core 0.21.0), whose residual and whose row of the jacobian are zero, so it stays in the residual vector of the request in its place and the fit of the engine is still the fit of the problem. An infinite weight, which is an error of exactly zero, is a standard deviation of0.0and keeps the fit in python. -loss_function:LINEAR(default) or the robustSOFT_L1,CAUCHYandARCTANofscipy.optimize.least_squares, which reduce the influence of outliers.
The settings relative_tolerance, absolute_tolerance, variable_step_size and initial_time_step are those of the integrator, see Simulations.
Data at the time of a change¶
At the time of a Change, e.g. a dose or the emptying of the bladder, a simulation has two states: the one before the change and the one after it (see Simulations). Most measurements at that time are taken before the change: cumulative urine at the end of a collection period is the amount collected until then, not 0, and a sample at the time of a dose is a pre-dose sample. So by default a data point at the time of a change after the start is compared with the state before the change (data_at_change=DataAtChangeType.BEFORE).
The first point of a curve is the exception: if a curve has later points, its first point takes the state after the change, because the curve starts there, e.g. a urine collection which starts at 0 at a reset. A curve of a single point takes the state before the change, e.g. the total amount of urine at the end of a collection. A data point counts as at the time of the change if it is within the resolution of the time of the simulation, and data at the start of a simulation always sees the state after the changes at the start. An event of the model is a jump as well: data at the time of an event takes the state after it.
DataAtChangeType.AFTER compares every data point at a change with the state after it, which is what PEtab does. A PEtab problem read without the sbmlsim extension uses AFTER. problem.times_before_changes(k) lists the times of the data of mapping k which take the state before a change.
Running the optimization¶
run_optimization(problem, settings, size, ...) runs size optimizations and returns an OptimizationResult:
algorithm:OptimizationAlgorithmType.LEAST_SQUARE(default, fromsbmlsim.fit.options), the localscipy.optimize.least_squares, which needs many start points, orDIFFERENTIAL_EVOLUTION, the globalscipy.optimize.differential_evolution, which needs few runs and finite bounds. Further keyword arguments go to the SciPy function, e.g.max_nfev. Alossorf_scaleof SciPy is refused, the loss belongs in the settings. Least squares from many start points is the default for every fit: on the fits of the HCTZ example it reached the optimum at a 4th to a 17th of the evaluations of differential evolution with the defaults of SciPy, and closer to it; differential evolution is the global check of a final fit.diff_step: the relative step of the finite differences of the Jacobian of the least squares optimizer. It defaults to the square root ofrelative_toleranceof the settings,1e-3for the default1e-6: a simulation is exact only to the tolerance of the integrator, and a smaller step, such as the default of SciPy, measures the noise of the integrator instead of the slope, so the optimizer stops next to its start.ftol,xtol,gtol: the tolerances of the least squares optimizer. They default torelative_toleranceof the settings, at least1e-8, the default of SciPy: the cost is exact only to the tolerance of the integrator, steps below it chase its noise. On the fits of the HCTZ example this took 13 to 27 % fewer evaluations to the same optima.sampling: how the start points are drawn within the bounds,SamplingType.LOGUNIFORM_LHS(default, fromsbmlsim.fit.sampling), the Latin hypercube of the logarithms,LOGUNIFORM,UNIFORMandUNIFORM_LHS. Bounds over several decades need logarithmic start points: uniform ones lie almost all in the top decade, and on the fits of the HCTZ example 25 to 30 % of the uniform starts reached the optimum against 60 to 70 % of the logarithmic ones.STARTstarts every run from the start values, to improve a known solution; one run is then enough for the local optimizer. Settingproblem.x0changes the start values of a problem.seed: the seed of the start points. The start points are drawn before the runs start, so the result does not depend on the number of workers.-
n_cores: the number of worker processes;1(default) runs in the calling process,Noneuses all cores but one.serial=Trueruns serially whatevern_coressays, which is what a debugger needs. A worker cannot start workers of its own, so the workers go either to the runs or to the evaluations of a single run (split_coresofsbmlsim.fit.runner): with as many runs as one run spreads over or more, every worker optimizes a run of its own; a fit with fewer runs, e.g. a single optimization, runs its runs one after another and every run evaluates on all workers. Differential evolution evaluates the members of its population; the polishing of the best member by least squares evaluates in the calling process (withpolish=True, the L-BFGS-B of SciPy, the points of its gradients are evaluated on the workers together and its line search in the calling process). Least squares evaluates the points of the finite differences of its Jacobian, one per parameter, which are the whole cost of a fit of many parameters: the Jacobian is the Jacobian of a serial run bitwise, since its points are evaluated at the same step either way. A run spreads over as many workers as its Jacobian has points, so a fit of two parameters on twelve workers runs its runs in parallel instead. The workers start and initialize the problem before the timeout of a run starts. Every worker holds the problem, the memory of a fit grows withn_coreseither way.sbmlsim-core simulates a batch of parameter vectors on threads of its own, so a run of that engine evaluates the whole population of a generation, or the whole Jacobian of a step, in one task of one worker which runs on the cores of the fit, where the other engines evaluate one point per worker (
OptimizationProblem.evaluate_residuals_many): the simulations of the batch are one fan out over the threads of the engine instead of a task of a process per point, with the same numbers, and one worker holds the problem instead of one per core. On the PK fit of the HCTZ example one Jacobian of 4 vectors takes 4.5 ms instead of 9.5 ms and one of 21 vectors 12.9 ms instead of 44.3 ms on 20 threads, against a loop in one process; what a batch is worth grows with the conditions and the parameters of the problem, see the batch of the engine. A worker which dies takes its batch with it, whose vectors are then evaluated one per task, so a vector which kills a worker fails alone as it does with the other engines. -engine_fit: whether the whole fit runs in the engine, i.e. its optimizer, the runs of its starts and their evaluations. A fit of a problem of sbmlsim-core runs there by itself (engine_fit=None), where the fits of the other engines optimize in python as they always did. The engine builds the objective of the problem once, as a request of the contractfit/1(sbmlsim.fit.fit_core), and runs the starts of the fit next to each other on the threads of one batch, so a fit costs one call instead of a step of the optimizer per evaluation and a process per run: the fit of the iv data of the HCTZ example (three parameters, four curves, four starts) takes 0.05 s against 0.09 s of the optimizer in python on one core and 0.40 s on twenty, where the processes of the pool cost more than the fit, and the fit of its PK data of eight starts takes 0.21 s against 1.14 s and 0.79 s. Both paths put five of those eight runs on the optimum. A fit of forty starts on twenty cores takes 1.6 s against 12.1 s on the iv data and 6.6 s against 9.2 s on its PK data, where the integrations of the model and not the calls of python are what a run costs, and where the engine puts 33 of the forty runs on the optimum against 23 of the scans in python. The times are the medians of three fits on a busy twenty core machine, and the first fit of a model in a process pays the pool and the compilation of the model in every worker of it, which is about a second more on the twenty cores of the iv fit.The whole fit is one request, which fills the pool of the engine with its starts, and the engine reports a run of it as soon as that run finished: every run is stored and counted while the fit runs, so the progress of a long fit says how far it is and a fit which is interrupted (Ctrl-C) keeps the runs which finished, as a fit in python keeps the repeats which finished. Chunks of starts, a request each, would cost the fit more than they are worth: the runs are not equally long and a chunk ends with its longest run while the threads beside it idle, which costs 1.07x of the PK fit and 1.34x of the iv fit of sixteen starts in chunks of four on four threads, and more the wider the runs of a fit spread.
The residuals the engine computes are the residuals of the problem, point for point, so the fit of the engine is the fit of the problem: the weighting of the curves and of the points is the noise of a curve of the request, and the parameters are searched in the scale of the problem. What the engine has not keeps a fit in python, and the gaps are logged so a fit says why: an objective whose residuals are not the ones of a curve or of a prior (a prior of a kind the engine does not evaluate, e.g. a gamma prior; a prior of a parameter whose unit is not the one of its target, whose value the engine holds; a prior whose support does not cover the bounds of its parameter, whose zero density between them is a penalty in python and no number of a request; a likelihood whose noise has a placeholder with a value per measurement, which is no one column of the simulation; a likelihood whose noise formula the model of the fit cannot carry as an observable of its own, e.g. one which reads a symbol which is no entity of the model, or one which reads the observable of a mapping which is more than one curve; a likelihood of a log kind whose measurement is not positive, whose logarithm is no value of a curve; and, on bindings older than
OBJECTIVE_VERSION(sbmlsim-core 0.24.0), every likelihood whose curve would carry the distribution of its noise and every posterior which would carry its priors, which such bindings would ignore), a loss function which is not linear and a residual which is not absolute or normalized (neither of which a likelihood applies, so neither is a gap of one), a derived mapping, a parameter whose bounds are not finite and increasing, e.g. a parameter which has a prior and no bounds of its own, an argument of the optimizer which is no setting of the engine, e.g.max_nfev, a differential evolution of more than one run, whose population the engine draws from one seed, so the runs of the fit would be the same run, and whatever the engine itself does not simulate (unsupported), which is the same for a fit as for a simulation: a value before the initialization or at a change which it cannot evaluate as a number, and the rest of the list in the module docstring ofsbmlsim.simulator.executor_core. That last check builds the request and reports what the engine refuses, so a problem the engine would not simulate is fitted in python instead of failing.engine_fit=Truerequires the fit of the engine and names the gaps of a fit it cannot run,engine_fit=Falsekeeps the optimizer in python, which evaluates its points through the engine. The command line of a fit has them as--engine-fitand--no-engine-fit, the kindfitof the run layer as the fieldengine_fitof its spec (Analyses), so a workflow requires the fit of the engine instead of falling back to python without a word. Where the optimizer ran is recorded with the fit,OptimizationResult.optimizer_of(engineorpython,mixedfor a result whose pieces did not all run in one place, nothing for a record of sbmlsim 0.27 or earlier), which the overview of its report and the summary of a run of the kind name.A fit whose mappings read more than one model, e.g. the two builds of a model of a drug, runs in the engine as well: every condition of the request names the model of its simulation,
sbmlsim.fit.fit_core.model_idsbeing the ids the conditions name them by, and the parameters of the fit are the same in every model it reads, each applied to its target in the model of every condition it reaches. Bindings older thanMULTI_MODEL_VERSION(sbmlsim-core 0.22.0) fit one model, where such a problem keeps the gapmodels.A value at a change which is a formula over the entities of the model is carried by the condition as a form, not folded into a number (the field
formsofsimulation/1, sbmlsim-core 0.20.0). A form is linear,constant + sum(factor * target), and the engine evaluates it from its own state at the change, so-0.5 * Aurineof a collection which is halved follows the state the optimizer moves instead of holding the number of the point the request was built at. An older binding would not ignore the field but fail on it, since a change of the contract denies unknown fields, so the version check gives a clear message and no other cost is computed silently. The conversion is all or nothing per plan: when any formula at a change of a plan is no linear form, nothing of it is written as a form and every formula folds, so a form and a fold never meet in one request. What is left is the gapchange_value, decided in three steps: a formula which reads constants of the simulation only folds into the same number at every parameter vector and is no gap,timebeing one of those constants since 0.41.0, a formula the engine can carry as a form is no gap, and every other formula is a gap, reported once per formula. A formula is no form when it is not linear (Aurine * Aurine) or reads the rate of a reaction, and the fit then runs in python. A term oftimeis no term of a form but its constant: the time at a change is known where the request is built, so0.5 * Aurine + timeat the change at 10 is the form10 + 0.5 * Aurine(0.41.0, #650). A formula at a change of a formed plan may read the entity a parameter of the fit writes, which the engine sets on the model before the simulation and which the form reads from its own state, so it is no gap either (0.41.0); the pre-initialization of a steady state is folded and keeps the gapparameter_value. The concentration of a species,[C], is a term like any other since 0.40.0:linear_formescapes the selections of roadrunner for the parser of the math of PEtab, which reads neither the brackets of a concentration nor a dotted name, the way the compiled formula of a run escapes them.A measurement at the time of a change is no gap in either direction: the curve of the request carries one flag per point (
after_changeoffit/1, sbmlsim-core 0.16.0), so the engine reads the state before or after the change exactly as thedata_at_changeof the fit says. An observable which is a formula of the selections is no gap either: it is written into the model of the fit as a global parameter of an assignment rule (sbmlsim.fit.observable_sbml), so the engine reads it as it reads the math of the model, and the placeholders of a PEtab observable become parameters of their values. A placeholder whose value differs between the points of one curve makes the mapping one curve per run of points which share their values, in the order of the points, so the residuals stay the residuals of the problem in their places. An observable of the experiment of a group is no gap either, as long as its value at a time of the data does not depend on the other output times, i.e. aFormulawhich is a timecourse without a reduction: every such observable of a group is written into the model of the fit as a parameter of its own, under an id which carries its group, so two experiments which define an observable of one id with different formulas keep their own columns, an observable which reads another one reads that parameter, and the factor of a declared unit is part of the parameter, so its column is the value python computes. A group whose data reads a value per simulation keeps the output of its simulation, e.g. the steps of the integrator, and is a condition of the engine as well, whose curve reads areductionof a column (sbmlsim.fit.reductions, sbmlsim-core 0.32.0): aFormulawhich is one reduction of a column,max(x),min(x),mean(x)orat(x, t)of a numbert, is a curve of that reduction, times the factor of its declared unit; a parameter<id>.<parameter>of aPKobservable is a curve of the analysis of pkpdutils in the engine, the batch python analyses with the kernel of pkpdutils (pkpdutils-core) and its options; a timecourse of such a group is a curve interpolated at the times of its data with the jumps python interpolates with. Every time of a reduction is the time of the output, the shift of the plan included, so the residuals of the engine are the ones of python bitwise on the tests oftests/fit/test_fit_core.py. A group whose simulation is a scan is a condition of the engine per point of the scan, the plan of the point with its values applied after the values of the parameters, as python simulates it, and a mapping over a dimension of the scan is a curve per point its data is at, or one curve over the points of the dimension for data between two points, which the engine interpolates between their conditions as numpy interpolates between the simulations of python, with the reduction of every point (the dose of aPKbatch is the one of the point); the request grows with the points, about 6 kB per condition of a simple model, and holds at a thousand points. A dimension which sets the target of a fitted parameter before the simulation wins over the parameter in python, so the condition of every point pins the parameter at the value of the point, and the parameter has no effect there; a dimension withatis a change after the parameter in both. Both are fields offit/1(curve.dimension,condition.pinned) which sbmlsim-core reads from 0.35.0 on, the floor of sbmlsim. A formula before the simulation which reads the target a scan pins reads the value of the point, as in python, which evaluates it after the values of the point: the condition of the point carries it with the number of the point in place of the parameter, a derived value of the other parameters of the fit or a number of the request, so its derivative by the pinned parameter is zero there;100 * ke * kawithkepinned is a linear form overkaat every point. What is still fitted in python is a formula of more than one reduction such asAurine / max(Aurine), a time ofatwhich is no number, aPKparameter whose dose the fit moves or which the kernel of pkpdutils does not analyse, and aCustomfunction.A fit in the engine has no workers of its own, so
n_coresare the threads of its batch, and it has no trajectory of the cost of its steps and no run which is written while it runs: the runs of aruns_dirare written when the answer is there. A run reports the code it stopped with as its message, and a run which stopped where its optimizer cannot improve the cost any further, the step of a trust region which collapsed included, counts as a converged run, which is what thextolofscipy.optimize.least_squaresstops at and reports as a success. -popsize,polish: differential evolution has a population of5members per parameter (DE_POPSIZEofsbmlsim.fit.optimization,15in SciPy), and its best member is polished by a least squares optimization of the residuals (polish="least_squares",LEAST_SQUARES_POLISH), unless they are given. On the fits of the HCTZ example this reached the optimum from every seed at a quarter of the evaluations of the defaults of SciPy, whose polishing by L-BFGS-B on the cost cost 360 evaluations without improving it;polish=Trueis the polishing of SciPy. -updating: differential evolution updates its population once per generation (updating="deferred", the scheme of Storn and Price), which the fit sets unless it is given, so a seed gives the same result for any number of workers.updating="immediate", the default of SciPy, updates the best member after every trial vector and evaluates the population serially;workersof SciPy is refused for either optimizer, except its defaults1andNone,n_coresgives the workers. -timeout: seconds per run; a run which runs out of time keeps the best parameters it reached. -runs_dir: a directory every run is written to as JSON as soon as it finishes, so an interrupted fit keeps its finished runs.OptimizationResult.from_directoryreads them back.
A run which fails, e.g. with an error of the integrator, keeps its message in the result and does not stop the other runs. Running a fit from the command line shows runs_dir in use.
A parallel fit starts worker processes which import your script again. In a script, put the fit under if __name__ == "__main__":, otherwise the workers start the fit again:
cat > fit.py << 'EOF'
from sbmlsim.fit.runner import run_optimization
from my_fit import problem, settings # your definitions
if __name__ == "__main__":
fit = run_optimization(problem, settings, size=20, n_cores=4, seed=1)
EOF
python fit.py
A worker which crashes loses only the run it was working on; a member of a population whose worker crashes runs again alone, and one which crashes its worker alone counts as a failed simulation, with an infinite cost. If workers crash more than three times in one generation, the run ends with a PoolError and keeps the best parameters it reached. While the runs go on, the console shows how many are done and an estimate of the total time.
Results and parameter sets¶
The OptimizationResult holds every run: df_fits is a table with the cost, the parameters and the message of every run, the best first, and df_traces the cost of every step. It is saved with to_json and to_tsv, read with OptimizationResult.from_json, and OptimizationResult.combine merges the results of several fits.
A report is made from parameter sets. fit.parameter_set() is the best one and fit.parameter_sets(size=n) the n best, as ParameterSets, which you can store and read back as JSON:
from sbmlsim.fit import ParameterSets
parameter_sets = fit.parameter_sets(size=2)
parameter_sets.to_json(Path("parameters.json"))
print(ParameterSets.from_json(Path("parameters.json")).to_df())
parameter unit hctz_patel_0 hctz_patel_1
0 Ka_dis_hctz 1/hr 0.304811 0.304812
1 KI__HCTZEX_k 1/ml 0.005028 0.005028
A parameter set has the values, their units, the cost and its origin. problem.parameter_set_model() is the set of the values in the model, the natural reference to compare a fit with. The values of a set are converted to the units of the problem; an incompatible unit raises a ValueError.
Report of a fit¶
A FitReport is made from a problem, its settings and one or more parameter sets. It does not need the fit, so you can report stored parameters later, or compare several sets in one report: every set is a column of the tables and a curve in the figures, and the first set is the reference.
FitReport.from_optimization_result(problem, fit) is the shortcut for a finished fit: it takes the settings from the result and adds the figures of the runs. with_model=True adds the values of the model as a reference set, so the report shows what the fit changed. report.create(output_dir, name) writes a folder with:
index.html, an interactive page with the methods, the results and the figures of the fit, with search, filters by kind of data, sortable tables and figures whose legend entries toggle their curves and whose points are read out under the pointer (the scriptfigures.jsbeside it). It works offline and can be archived or sent withfigures.js; without it the figures are static.report.pdfwith its sourcesreport.typand LaTeX (report.texfor\inputin a manuscript,report_standalone.tex), andreferences.bib. Typst compiles the PDF, no LaTeX installation is needed; if it fails, the page says why and everything else is written.- the figures in
plots/: the optimization runs (traces and waterfall), goodness of fit, Bland-Altman plot, and a figure per fit mapping with the data and the simulation, linear and logarithmic. Every figure is a chart of the renderer of sbmlsim-core, saved assvg(orpngwithimage_format="png") with its spec asjsonbeside it, andindex.htmlshows the SVG inline with its spec; the figures of the report document are written aspngas well, which LaTeX includes, atcreate(png_dpi=300). report.txt,parameters.json, the metrics as TSV (metrics.tsv,metrics_mappings.tsv,metrics_observables.tsv,datapoints.tsv), and the records of the fit (optimization_result.json,fisher.json,fisher.tsv,identifiability.json,posterior.json,posterior.tsv) where the report has them.
The methods describe only what the fit used: the parameters, the data per kind, the objective (the weighted least squares, or the negative log-likelihood with the noise models of the data and, for the posterior, the priors and their correlation), the optimizer and its options, the identifiability analysis, the posterior and the provenance. The references are those it cites, see References.
The goodness of fit and the Bland-Altman plot have one panel per kind of data, training, validation and outliers, with the points colored by study. The Bland-Altman plot shows the ratio of prediction and measurement against their mean, with the bias and the limits of agreement of the training data as fold factors. Both draw this band from the training data in every panel, so the validation data and the outliers are read against what the fit agrees to. Data points which are zero or negative have no ratio and are not drawn.
FitReport takes further options:
mapping_figures=Falseleaves out the figures of the fit mappings, a figure per mapping, which are milliseconds each.groupings=[Grouping.by("tissue")](fromsbmlsim.fit.evaluation) adds figures and metrics per group of a column of the data points, e.g. a field of the metadata.Grouping.of_subsets("route", Subset("oral", is_oral), ...)groups by named filters.error_bars=Truedraws the standard deviations of the data,color_by="tissue"colors the points by a column instead of the study.context=ReportContext(title=..., description=..., parameter_descriptions=...)(fromsbmlsim.fit.methods) sets the title of the report and the text about the fit.identifiability=andfisher=add the results of the identifiability analysis,posterior=the section of the Laplace posterior.
To report a stored fit, report_from_records(definition, directory, opid=...) of sbmlsim.fit.cli reads the records of a report folder (parameters.json, optimization_result.json, identifiability.json, fisher.json) and returns the FitReport. It uses the settings the fit ran with and warns if the definition has changed since.
Metrics¶
FitMetrics(problem, parameter_set) computes the metrics of a parameter set on an initialized problem, and report.metrics(parameter_set) does the same for a set of a report. The table of the data points uses the names of population pharmacokinetics: DV is the measured value, IPRED the prediction, IRES the residual DV - IPRED, NRES the residual divided by the mean of its curve, and IWRES the weighted residual of the cost.
columns = ["mapping", "kind", "n", "NRMSE", "GMFE", "AFE", "within_2fold"]
print(report.metrics(fitted).mappings_df()[columns].round(2))
mapping kind n NRMSE GMFE AFE within_2fold
0 fm_25_tab training 11 0.15 1.29 0.98 90.91
1 fm_25_tab_urine training 10 0.14 1.09 1.07 100.00
2 fm_50_tab validation 11 0.16 1.30 0.93 90.91
3 fm_50_tab_urine validation 10 0.23 1.17 1.14 100.00
MSE,RMSEandR2are computed from the values as they are, so curves with large values dominate them. RΒ² isNaNfor fewer than two points.NRMSEis the root mean square ofNRES, so every curve counts the same whatever its magnitude.RMSE_wis the root mean square ofIWRES, i.e. what the fit minimizes: the cost of the training data is0.5 * n * RMSE_w**2.GMFE(geometric mean fold error),AFE(average fold error, the bias: below 1 when the model predicts too low) andwithin_2foldare the usual criteria of pharmacokinetic predictions.within_2foldis the percentage of points within twofold of the data,0.5 <= IPRED / DV <= 2. Only points with a positive value and prediction count for them.within_1sdandwithin_2sdare the percentages of points within one and two standard deviations of the data.AICandBICcompare models fitted to the same data; only their differences mean something.
The functions of sbmlsim.fit.metrics also work on plain arrays, e.g. within_fold(data, predictions, fold=2.0) and rmse(residuals). summary_df() has one row per kind of data, mappings_df() one per fit mapping and observables_df() one per observable, e.g. plasma and urine. There is no row over all data, which would pool the data the fit was fitted to with data it dropped. A report writes these tables as TSV.
Variability and the predictive check¶
A fit predicts every curve with one subject, the typical subject of its study group, while the subjects of a study differ from each other. Variability (from sbmlsim.fit.variability) declares how: a relative distribution per target, e.g. LogNormal(cv=0.3), a factor with the median 1 and a coefficient of variation of 30 %. A subject has every target at its factor times the value its simulation gives the target, the value of the study group, of a fitted parameter or of the model, so the inputs of the studies stay as they are and the subjects vary around them (problem.predictions(x, factors={...})). Covariances of the uncertainty correlate the factors, e.g. the omega matrix of the logarithms with scale="log". The studies differ as well, in their populations, assays and protocols: between=Variability(...) is the variability between the studies, a factor per target which all subjects of a study share and multiply with their own.
predictive_check evaluates the mappings for many subjects and compares every data point with the distribution of its prediction over them. A data point of N subjects, the count of a group, is a mean, so it is compared with the means of virtual groups of N subjects (the geometric mean for data with a geometric standard deviation); a point without a count is one subject. The quantiles of the distribution are the band of a visual predictive check, and the coverage is the share of the data inside the outer quantiles, about 90 % for a model whose variability is the one of the data. With a variability between the studies the subjects of a parameter vector are studies studies of n_subjects subjects each, and a virtual group is drawn from one study. Given several parameter vectors, e.g. draws of the uncertainty of the fit, the studies and their subjects are nested in them and the distributions pooled. The factors of the subjects and the members of the groups are drawn by sbmlsim-core from the seed (its Sobol' sequence and xoshiro256++, the groups of every mapping, size of a group and study on a stream of their own), the same on every platform; up to sbmlsim 0.54.0 they came from scipy and numpy, so a seed gives other subjects and groups than in those releases:
import numpy as np
from sbmlsim.fit.variability import Variability, predictive_check
from sbmlsim.simulation.sampling import LogNormal
variability = Variability(
{"Ka_dis_hctz": LogNormal(cv=0.5), "KI__HCTZEX_k": LogNormal(cv=0.3)},
between=Variability({"KI__HCTZEX_k": LogNormal(cv=0.2)}),
)
x = np.array([fitted.values[pid] for pid in problem.pids])
check = predictive_check(problem, x, variability, n_subjects=16, studies=8, seed=1)
print(check.points[["mapping", "x", "N", "DV", "q5", "q50", "q95", "inside"]].head(4))
print(check.coverage_by_mapping().round(2))
mapping x N DV q5 q50 q95 inside
0 fm_25_tab 30.0 12 0.000077 0.000118 0.000150 0.000193 False
1 fm_25_tab 60.0 12 0.000241 0.000223 0.000288 0.000368 True
2 fm_25_tab 90.0 12 0.000329 0.000268 0.000351 0.000442 True
3 fm_25_tab 120.0 12 0.000359 0.000277 0.000366 0.000453 True
experiment mapping n coverage
0 Patel1984 fm_25_tab 11 0.91
1 Patel1984 fm_25_tab_urine 10 0.60
2 Patel1984 fm_50_tab 11 0.91
3 Patel1984 fm_50_tab_urine 10 0.50
The subjects alone give the mean of 12 subjects a band of about a third of the one of a single subject, the variability between the studies widens it. Here the bands hold 91 % of the points of the plasma and 60 % of the points of the urine; the first point of the plasma lies below its band. The scatter of the means of the studies is the variability of their subjects and between them plus the error of the measurements and of the model, so a low coverage says that the declared variability does not explain the data, or that the typical predictions are biased. The subjects of a vector are evaluated one after the other, so a check costs n_subjects times the vectors evaluations of the mappings. check.points has a row per data point with its band, the prediction PRED of the typical subject and whether the point is inside, check.subjects the factors and the predictions of every subject.
Identifiability¶
A fit always returns numbers, but the data may not determine them. The profile likelihood and the Fisher information answer how well each parameter is determined, see Identifiability.
Running a fit from the command line¶
Most of a fit is the same for every model, so sbmlsim.fit.cli provides it and a model only defines its fits. A FitDefinition is everything a fit needs: a function which returns the mapping collections, the parameters, the paths and the settings. jit_optimization of a definition is the optimization level its problems compile their models with, in the process and in every worker, see Compilation speed; a project gives its fits the level of its simulator settings. run_fit builds the problem, runs it and records its provenance; with output_dir every run is written to <output_dir>/<opid>/runs:
from sbmlsim.fit.cli import FitDefinition, run_fit
from sbmlsim.fit.result import OptimizationResult
def urine_collections() -> dict[str, list[FitMappingCollection]]:
"""Select the data of the fit."""
return selection.collections
definition = FitDefinition(
mapping_collections=urine_collections,
parameters=problem.parameters,
base_path=HCTZ_PATH,
data_path=DATA_PATH,
settings=settings,
)
fits = run_fit(definition, opid="hctz_urine", size=2, seed=1, output_dir=Path("fits"))
recovered = OptimizationResult.from_directory(Path("fits/hctz_urine/runs"))
print(recovered.size, "runs read back")
provenance = recovered.provenance
print("versions:", ", ".join(provenance.versions))
print("checksums of", len(provenance.files), "files")
π Optimization ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
π Parameters (2) βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
parameter start lower upper unit
βββββββββββββββββββββββββββββββββββββββββββ
Ka_dis_hctz - 0.01 10 1/hr
KI__HCTZEX_k - 1e-05 1 1/ml
runs 2
workers 1 (threads of the engine, one fit)
converged 2/2 runs
best cost 1.09898
optimizer time 0.1 s
2 runs read back
versions: python, sbmlsim, libroadrunner, scipy, numpy, sbmlsim-core
checksums of 10 files
The provenance records the arguments and seeds of the fit, the versions of python, sbmlsim, libroadrunner, SciPy and NumPy, the git revision of the model repository, and the SHA-256 checksums of the models and data files. It is stored in every run and in the result, and the report shows it. run_fit(strategy=OptimizationStrategy.SINGLE) fits every experiment on its own instead of all together. A FitRun creates its report with report(), its identifiability analyses with fisher() and identifiability() and the Laplace approximation of its posterior with posterior().
fit_cli and report_cli turn a dictionary of definitions into command line tools. examples/hctz_fitting/fitting/fitting.py defines the fits of the HCTZ model and calls fit_cli; run_report.py calls report_cli:
# fit the PK data with 10 runs on 4 cores
python -m examples.hctz_fitting.fitting.fitting --subset=PK --runs=10 --cores=4 \
--seed=1234 --method=LSQ --strategy=ALL --name=PK_LSQ_ALL
# report a finished fit again, or compare the parameters of two fits
python -m examples.hctz_fitting.fitting.run_report results/fit/<fit id>/parameters.json
python -m examples.hctz_fitting.fitting.run_report run1/parameters.json run2/parameters.json
Every fit gets an id when it starts, <problem>_<date>_<time>__<hash>, e.g. PK_20260908_144538__ea1ff, which names its result and its report folder. sbmlsim.fit.result.fit_subset reads the problem back from an id and fit_date its day. Both tools take --no-mapping-figures for a fast report and --group-by tissue for the groupings of the report; --help lists all options.
Adopted fits¶
The fits of a project whose parameters the model uses are its adopted fits, one per subset. The fit kind of the run layer adopts a fit with adopt, together with identifiability: it writes the record of the fit, its parameters, profiles, Fisher information and report (sbmlsim.fit.records.adopt_fit), into fits/<fit id> of its output and adopted.json with the fit adopted for its subset, which a person commits into the directory of the fit records of the project, fits_dir. Project.fit_records() reads the records (AdoptedRecords): the fitted value of every parameter with its uncertainty, ParameterUncertainty, the confidence interval of the profile likelihood (the Fisher information for a parameter without a profile), the standard error of the Fisher information and the distribution of its draws as a formula of distrib, lognormal(mu, sigma, lower, upper) on a logarithmic scale, normal(...) on the linear one and uniform(lower, upper) for a profile open on both sides. A factory gives a parameter of the model its value and its uncertainty with fit_records().parameter("k", unit=U.per_min), the keyword arguments of a Parameter of sbmlutils; sbmlsim.simulation.sampling.parameter_distributions reads the distributions back from the SBML and uncertainty_dimension draws them into a dimension of a scan.
A fit of one subset keeps the adopted fits of the other subsets fixed at the values of their records: its problem simulates them as pre-initialization changes (fixed_values of OptimizationProblem, on the path of python and in the request of the engine), whatever the models hold, so the order of an adoption and of the factory does not matter, and a model which holds other values, because the factory has not run since an adoption, is named in a warning (sbmlsim.fit.project_fits.stale_values). The fit records these fits and their values in its provenance and its report names them (record_adopted); a problem built from the records of a fit (its report, profiles, Fisher information and PEtab problem, problem_of_records) keeps the values the fit kept fixed, and the credibility evaluates every adopted fit with the adopted fits of the other subsets now, the model the assessment is about; start starts least squares from a point, a finished fit or an adopted fit, which the plan resolves into the point; the plan of a fit refuses bounds which let a remainder 1 - a - b of a model become negative. The kind adopt adopts a fit which finished without adopt. sbmlsim.fit.project_fits has these functions for a script of its own, report_context and records_context of sbmlsim.fit.cli the context of the report of a fit of a project, and the report kind with adopted reports the adopted fits from their records.
PEtab¶
A fit can be exchanged with the tools of the PEtab ecosystem as a PEtab v2 problem, which sbmlsim.fit.petab_v2 writes and reads, see PEtab. A fit with neural networks is a problem of PEtab SciML. sbmlsim.fit.petab_omex packages a problem as a COMBINE archive.