Skip to content

Models and their commands

A model package describes itself once, in its __init__.py, as a PKPDModel, a project of sbmlsim (sbmlsim.project.Project, see Projects of sbmlsim for its fields, references, variants, analyses and checks) with what a PBPK/PD model adds. The commands, the verification and the tests of pkpdsim work with this object; what stays in the package is what is the model's own: its factory, the registry of its experiments, its fit definitions and parameters, the filters of its mapping collections and its tolerances. The base class of its experiments, the vocabulary of their metadata and the filters of the fits are described in Experiments and their metadata.

# not executed
from pathlib import Path

from sbmlsim.project import SimulatorSettings

from pkpdsim.model import FigureSettings, PKPDModel

HCTZ_PATH = Path(__file__).parent
MODEL_BASE_PATH = HCTZ_PATH / "models" / "results" / "models"
MODEL_PATH = MODEL_BASE_PATH / "hctz_body_flat.xml"
DATA_PATHS = [HCTZ_PATH / "data" / "hydrochlorothiazide"]

MODEL = PKPDModel(
    name="hctz",
    package=__name__,
    title="HCTZ PBPK/PD model",
    path=HCTZ_PATH,
    model_path=MODEL_PATH,
    data_paths=DATA_PATHS,
    archive_path=MODEL_BASE_PATH.parent / "hctz_model.omex",
    factory=".models.factory:create_hctz_models",
    experiments=".simulations:EXPERIMENTS",
    fit_definitions=".fitting.fitting:FIT_DEFINITIONS",
    simulator=SimulatorSettings(absolute_tolerance=1e-10, relative_tolerance=1e-10),
    figures=FigureSettings(formats=("svg",), savefig_dpi=300, legend_fontsize=10),
    fit_identifiability=True,
)

PKPDModel, FigureSettings, SimulatorSettings and ExtraAction take keyword arguments only, so the order of their fields is not API. The keywords of a model package are the fields of the project by other names: path is root (the property path), model_path and female_model_path are the variants male and female, data_paths is data_path (the property data_paths), fit_definitions is fits, fits as a sequence of fit ids is adopted_ids, and a FigureSettings as figures is split into the figure_settings (sbmlsim's) and the figures (a FigureOutputs, the formats and the resolution) of the project. A keyword and its field are not given together. A model is a frozen pydantic model: model.replace(**fields) gives a changed copy by the names of the fields, e.g. model.replace(adopted_ids=[...]); the directory of the factory and the folder of the adopted fits, which a model derives from its male build, are derived again for other builds or another root, unless they are given or were given when the model was created. SimulatorSettings and CheckSettings are those of sbmlsim.project, the release settings are sbmlsim.release.settings.

Builds per sex

A model is built for one sex: the PBPK library takes the reference values of the sex when it builds a model (the ICRP 89 anatomy, the hematocrit, the partition coefficients, the GFR, see Physiology). A model whose studies include women has a female build next to the male one, from the same definition (create_archive(..., sexes=(Sex.MALE, Sex.FEMALE)), see PBPK library), and its model object holds both:

# not executed
MODEL_PATH = MODEL_BASE_PATH / "hctz_flat.xml"
FEMALE_MODEL_PATH = MODEL_BASE_PATH / "hctz_female_flat.xml"

MODEL = PKPDModel(
    name="hctz",
    ...,
    model_path=MODEL_PATH,
    female_model_path=FEMALE_MODEL_PATH,
)

model_path is the male build, the model of every experiment and every caller which does not ask for a sex (model_path of the project, variant_path(variant) gives any build); model_paths maps every sex to its build (the male one only for a model without a female build) and model_path_of(sex) gives the build of a sex, with a ValueError naming the model for a sex it has no build of. The builds have the same ids, so the changes of an experiment and the parameters of a fit apply to both. An experiment chooses its build by the sex of its subjects (sex, see Experiments and their metadata), and the commands handle both builds:

command the builds per sex
run_simulation, run_report, sbmlsim.project_checks every task runs the build of the sex of its simulation
run_fit one parameter set for both builds; the remainders of the fitted fractions are checked in every build
--uncertainty the draws of the fitted parameters are those of the male build, the default variant, and run on every build; check_fit_parameters of sbmlsim.experiment.draws checks the fitted values and the distributions in every build, a variant
sensitivity a group runs the build of its sex, a variant of the project (SensitivityGroup(variant=Sex.FEMALE) of sbmlsim.sensitivity.runner): a local analysis varies the values of that build, a global design (sampling, Sobol, FAST) is the same relative design around the values of that build (the values of the table, read from the male build, times the ratio of the value in the build, design_factors; a value of the table which is zero or of another sign is refused before anything runs), and the table of the parameters has the column value_female
pkpdsim-verify a dump records the sex of the build of every task (builds), compare reports a task which moved to the build of another sex

References

factory, experiments, fit_definitions and credibility are references "module:attribute", resolved when a command uses them. The experiments of a model import its __init__.py for the paths, so the model object cannot import them; a module which starts with a dot is relative to package.

field the reference names
factory a function which creates the models in a directory
experiments the registry: groups of experiment classes by name, with the group all
fit_definitions the fit problems by name (sbmlsim.fit.cli.FitDefinition)
credibility the declaration of the contexts of use (sbmlsim.credibility.Credibility), e.g. ".credibility:CREDIBILITY"; None for a model without one
credibility_settings the credibility settings of sbmlsim (sbmlsim.project.CredibilitySettings), pkpdsim.model.CREDIBILITY_SETTINGS by default: the metadata PKPDMappingMetaData, the fields of a domain (DOMAIN_FIELDS), the evidence extensions and the PK battery of pkpdsim.credibility; battery_settings sets the battery, e.g. {"steady_state": False} for a model which does not start at its steady state

Settings

  • SimulatorSettings (of sbmlsim.project): the engine, the absolute tolerance (one value, or an AbsoluteTolerance of sbmlsim per kind and state), the relative tolerance, the optimization level of the compilation, jit_optimization ("O0" to "O3"), and other settings of the integrator; a model without them has SimulatorSettings(absolute_tolerance=1e-10, relative_tolerance=1e-10). The processes are no setting of the model, they belong to a run (n_workers). A run creates an sbmlsim Simulator from them and compiles the model at the level, as the tests of sbmlsim.project_checks do; the problems of the fits, their reports and the identifiability analysis and pkpdsim-verify load their models at the level too, in the process and in every worker (load_fit_definitions() gives the fit definitions with the level, FitDefinition.jit_optimization of sbmlsim, which carry it into their problems and their workers), and a test of a model loads the model at the level with MODEL.load_roadrunner(sex) instead of a plain roadrunner.RoadRunner. sbmlsim compiles every model with LLJIT: O0 compiles a model with large initial assignments several times faster and simulates a little slower (the creatinine model of pkdb_models loads in 4.5 s at O0, 24 s at O2 and 53 s with the MCJIT of a plain roadrunner.RoadRunner; the reference models of the tests of the PBPK library load in 7 to 11 s at O0 and in 28 to 57 s at O2, and integrate at most a few percent slower), so the level of a model which names none is O0, DEFAULT_JIT_OPTIMIZATION of pkpdsim, which the creation of a model writes into its settings: the optimization pays for itself only after tens of thousands of integrations in the process which compiled the model, so a model whose fits simulate that much names SimulatorSettings(jit_optimization="O2") itself. The environment variable SBMLSIM_JIT_OPTIMIZATION names the level of every model which names none, pkpdsim then writes nothing into the settings and sbmlsim resolves the variable when it loads a model. O0 gives the results of the MCJIT of roadrunner bitwise, the other levels differ from them in the last bits, by about the tolerance of the integrator, so the results of a model move when its level changes (pkpdsim-verify compare shows it).
  • FigureSettings: sbmlsim's FigureSettings (the resolution, the sizes of the panels, the fonts and the legends, with the defaults of sbmlsim) and the two fields of a model, the formats of the figures (svg and png, SVG only by default, and json; the JSON spec of a figure is always written beside its images, html is refused) and the resolution of the PNG images (savefig_dpi, which applies to PNG only); the model keeps them as its figure_settings (sbmlsim_settings()) and its figures (outputs()). A run hands the settings of sbmlsim to every figure; an experiment (figure_settings) and a figure (Figure(settings=...)) override them. Nothing is applied to the process, so nothing has to be restored after a run.
  • reduced_selections, save_results, fit_identifiability: what a run simulates, whether it stores its results, whether a fit analyses the identifiability of its parameters by default.
  • fits (the field adopted_ids): the ids of the adopted fits, one per fit problem, whose records in fits_dir (fits next to the output directory of the factory by default) give the fitted values and their uncertainty to the factory (fit_records()), see Uncertainty of the fitted parameters.
  • credibility (see above) is loaded by load_credibility() and assessed by run_credibility, which writes into credibility_dir (results/credibility); see Context of use and credibility.
  • sensitivities (a field of the project of sbmlsim): the sensitivity analyses of the model over the groups of its simulations by their name, a SensitivityRunner of sbmlsim.sensitivity.runner, the runners of its simulations by their subfolder, or a reference to either, e.g. {"sensitivity": ".sensitivity.sensitivity_analysis:SENSITIVITY"}; run_sensitivity runs them into results/<name>, see Commands.
  • pipeline: the pipeline of the model, its analysis as steps of the commands of pkpdsim (pkpdsim.pipeline.Pipeline) or a reference to it, e.g. ".pipeline:PIPELINE", loaded by load_pipeline() and run by run_pipeline, see Commands; None (the default) for a model without one.
  • release: the release metadata of the model (ReleaseSettings: the repository, the Docker image, the authors, ...), which pkpd_release needs to make the release of its model repository, see Release of a model repository; None (the default) for a model without a release repository.

A run of a model is sbmlsim.project.Project.run_experiments with the settings and the result directories of the model. Its processes are n_workers, the pool of the experiments, and scan_workers, the scans of an experiment, of run_experiments and run_simulation_experiments: by default the experiments run in a pool of a worker per four experiments, at most one per CPU, and serially below (n_workers=None; the 28 experiments of HCTZ take 12 s instead of 21 s), and the scans of every experiment serially in its worker (scan_workers=1, RUN_WORKERS), which is faster than scans in a pool for many experiments of small scans. n_workers=1 runs every experiment in the process, scan_workers=None gives the scans n_workers, the processes of the whole run as sbmlsim counts them (n_workers=4, scan_workers=None: the experiments in a pool of four, a single experiment with its scans in a pool of four). A pool needs the guard if __name__ == "__main__": in the script which runs the model (the processes of the pool import it again; the commands of pkpdsim have it), and the memory of a run grows with every process, about 330 MB for a PBPK model. run_simulation runs the kind simulate of sbmlsim, whose processes are --workers, see Commands:

from sbmlsim.project import SimulatorSettings

from pkpdsim.model import RUN_WORKERS, FigureSettings

serial = SimulatorSettings(absolute_tolerance=1e-10, relative_tolerance=1e-10)
assert RUN_WORKERS == 1
print(serial.simulator(4).n_workers)

figures = FigureSettings(savefig_dpi=300, legend_fontsize=10)
assert figures.formats == ("svg",)
print(figures.sbmlsim_settings().legend_fontsize)
print(figures.outputs())

Commands

The commands of pkpdsim run every model by the dotted name of its package; the package registers no commands of its own:

run_simulation pkdb_models.models.hctz --action simulate --experiments all
run_fit pkdb_models.models.hctz --subset PK --identifiability
run_report pkdb_models.models.hctz --subset PK results/fit/PK_<fit id>/parameters.json
run_identifiability pkdb_models.models.hctz --subset PK results/fit/PK_<fit id>/parameters.json

The model object gives everything which differs between two models: the actions of run_simulation (the extra actions of extra_actions, an ExtraAction with name, help, the function called with the model, the parsed arguments and the folder of the results, and in_all to run it with --action all; their options are added by the function of extra_arguments), the fit problems of the fit commands, the settings of the simulator and the figures and the folders of the results. See Commands for the commands, their options and their errors.

Tests

sbmlsim.project_checks holds the tests of a model as functions over its project, see Checks of a project: the registry is complete (check_registry), the model object belongs to its package and its references resolve (check_model), the experiments initialize (initialize_experiments), all experiments run (run_all_experiments) and every fit starts (start_fits). A function which checks several things raises one AssertionError which names every failure, not only the first.

check_battery(model, run) of sbmlsim runs a battery of the checks of the builds and fails for every failed check the model does not know, checks.battery; the PK battery of pkpdsim (mass balance, non-negativity, zero dose, steady state, superposition, a second simulator, plausibility and rebuild, see Battery of the builds) is the battery hook of every model, so check_battery(MODEL, run_battery) with the battery of sbmlsim, sbmlsim.credibility.battery.run_battery, runs it.

The known exceptions of a model (experiments which are not registered, modules which do not import, experiments which run one at a time, checks of the battery which fail) are its checks, see Experiments and their metadata.

check_model also checks that the model is an attribute of its package, that the builds (the variants, model_path and female_model_path), the factory directory and the folder of the adopted fits lie below the path of the model, and that the data paths exist.

Verification of a change

pkpdsim-verify is a thin wrapper of python -m sbmlsim.run verify (sbmlsim.verify, which holds the subcommands, their options and the exit codes) for the model objects of pkpdsim: --model PACKAGE is --project PACKAGE:MODEL, a dump records the sex of the build of every task through PKPDSimulationExperiment.variant_of, and scorecard judges with the evidence extensions of pkpdsim and pools the ratio pairs by --field (health by default) in the wording of the limits of Guest et al. It dumps the experiments of a model in two checkouts and compares them, writes the fit definitions and the settings of a run as json, compares figures and SBML, and compares the credibility of many models with a baseline (scorecard, see Across models):

pkpdsim-verify dump --root ../base --model pkdb_models.models.hctz --out base.pkl --atol model
pkpdsim-verify dump --root . --model pkdb_models.models.hctz --out new.pkl --order base.pkl --atol model
pkpdsim-verify compare base.pkl new.pkl
pkpdsim-verify definitions --root . --model pkdb_models.models.hctz --out new.json
pkpdsim-verify settings --root ../base --model pkdb_models.models.hctz --out base.json
pkpdsim-verify settings --root . --model pkdb_models.models.hctz --out new.json
diff base.json new.json
pkpdsim-verify png old/results/simulation new/results/simulation
pkpdsim-verify sbml old.xml new.xml

--atol model and --rtol model take the tolerances of the model object; any other value which is not a number exits with 2. A package without a model object exits with 2, and compare --renames FILE applies the expected renames of a migration to the old dump (see Experiments and their metadata and Comparing two dumps). An experiment which cannot be initialized is recorded in the dump as an error and the command exits with 1 after the other experiments are stored. A dump records the sex of the build which every task of an experiment of pkpdsim ran (builds, see Builds per sex); compare compares them exactly when both dumps have them, a difference is expected with the pattern experiment/task of the part builds.

settings captures what a run of the experiments hands to sbmlsim, bound to the signatures: the arguments of Simulator (its tolerances and n_workers), of ExperimentRunner (without the simulator) and of the run, with its figure_settings (without the output path), the formats and the resolution of the PNG of the run and the counts of the calls. It exits with 2 for a run which did not complete. The json has run.figure_settings.

Comparing two dumps

A dump records the versions of sbmlsim and pkpdsim it was made with, and compare prints them. The comparison itself is that of sbmlsim.verify:

  • The arrays are matched by the names of their dimensions, the time (or the scan point of the ragged layout) first. A dimension of size 1 which only one array has is squeezed, different names of the dimensions are an infinite difference.
  • A change keeps the state before and after it at the time of the change (a second dose). Two dumps with the same time vectors are compared row by row. Otherwise the rows of a repeated time are matched from the last one, the k-th last old row with the k-th last new row, and only the rows which one dump has more of at a time are left out: the summary counts them and names the experiments with changes: <experiment> <rows> rows.
  • The rows of every point of a scan are matched by the times of that point. The points of a grid share their times; in the ragged layout (_point, every point with its own times, padded with NaN) a point is matched and its times are compared on its own.
  • A row at a time which only the old dump has is always a difference, and no pattern of expected hides it. A row at a time which only the new dump has (a new output time of a task) is a difference as well, which is printed per task (times of <experiment>/<task>: <n> rows only in new, at <times>) and which the pattern experiment/task/time of expected names.

The expected differences of a change of a model package, e.g. a rename of its ids, are said in the renames file instead of weakening the comparison, which then passes with exit code 0 or fails. The ids of a task, a dataset, a figure or a mapping are SIds (see Keys):

part content
ids an old id to its new id: the task of a result, the dataset, the figure and mapping keys and the references to them in a figure
sids true: every id of the old dump becomes sbmlsim.experiment.to_sid(id) (after ids)
figure_fields the keys of the specification of a figure which are left out of both dumps, at the level of the figure only (not in its plots, curves or axes), a field of a figure which compare cannot map. The specification is the attributes of sbmlsim's Figure and its objects as json (sbmlsim.verify.dump.serialize, figure_spec), so the fields are those of the version of sbmlsim which made the dump.
expected a part (results, datasets, mappings, figures, ranges) to the patterns of the keys of the differences which are expected
metadata, strings as in Experiments and their metadata
{
  "sids": true,
  "expected": {
    "results": ["Anderson1961/task_po_2p5/time"],
    "mappings": ["Anderson1961/Fig1_hctz"]
  }
}

The patterns of expected are fnmatch patterns of the keys:

part key
results experiment/task/variable
datasets experiment/dataset/column
mappings, ranges experiment/mapping
figures experiment/figure

* and ? are wildcards, a bracket is literal: Anderson1961/task_po_2p5/[Cve_hctz] names the variable [Cve_hctz] of the task task_po_2p5 (the base names the task of a simulation task_<simulation>). A difference which matches is printed as expected and not counted, a pattern which matches no difference is counted, so the file says exactly what changes. Two old ids with one new id, a strings rename which merges two keys of a part and two mappings of one experiment with one key are errors (exit code 2). The renames are applied to the content of the parts of the old dump, never to the names of the parts, and the loaded dump is not changed.

png compares the PNG figures of two directories by their file names; a model draws SVG only by default, so both runs ask for PNG (run_simulation <package> --formats png). After the renames to SIds the old file A_fig 2.5.png is A_fig_2p5.png: png --sids pairs an old figure with the new figure of the SId of its name (the stem through to_sid) and exits with 2 when two old figures have one SId:

pkpdsim-verify png --sids old/results/simulation new/results/simulation