Skip to content

experiment.experiment

SimulationExperiments and helpers.

SimulationExperiment

SimulationExperiment(
    sid=None,
    base_path=None,
    data_path=None,
    ureg=None,
    **kwargs,
)

Generic simulation experiment.

Consists of models, datasets, simulations, tasks, results, processing, figures

SimulationExperiement.

:param sid: :param base_path: :param data_path: :param ureg: :param kwargs:

uncertainty property

uncertainty

The draws of the fitted parameters of a run over them, None otherwise.

The setting uncertainty of the experiment, which a run over the draws gives every experiment, see sbmlsim.experiment.draws.

Raises:

Type Description
TypeError

if the setting uncertainty is no UncertaintyRun.

results property

results

Access simulation results.

Results are mapped on tasks based on the task_ids. E.g. to get the results for the task with id 'task_glciv' use

    simexp.results["task_glciv"]
    self.results["task_glciv"]

preload_in_forkserver classmethod

preload_in_forkserver()

Load what every worker which runs the experiment loads, once for all.

The forkserver of a pool calls it for every experiment class it imported (the modules of preload, see sbmlsim.parallel), after its imports, and the workers it forks inherit what it loaded, e.g. a model compiled in a cache of the process, instead of loading it each. Nothing else calls it, and under the start method spawn there is no forkserver. It does nothing by default.

An override loads into a cache which the experiments read (a model loaded in the forkserver is the one a worker would load, so the results do not change), keys it by what decides its content (e.g. the modification time of a file), starts no thread (a fork of a process which runs threads may deadlock) and raises for nothing it cannot load: the forkserver logs the error and goes on, and a worker loads it itself.

initialize

initialize()

Initialize SimulationExperiment.

Initialization must be separated from object construction due to the parallel execution of the problem later on. Certain objects cannot be serialized and must be initialized.

With the setting uncertainty, an UncertaintyRun, every simulation runs over the draws of the fitted parameters and the curves of the simulations become bands, see sbmlsim.experiment.draws.apply_uncertainty.

across

across()

Get the dimension of the draws of the fitted parameters, None without.

The dimension over which a run over the draws (uncertainty) varies the fitted parameters, which a figure or an analysis of a scan of the experiment leaves out of its own dimensions or makes a band of, e.g. sbmlsim.result.scan.point_band(result, ..., across=self.across()).

Q

Q(value, unit=None, model=None)

Create a quantity in a unit of pint and of the unit ids of the models.

The runner loads the models of an experiment before initialize, so the unit ids of a model are known in simulations() and later, e.g. self.Q(10, "mg_per_min"); a unit id is replaced by its expression, see UnitsInformation.quantity. Before the models are loaded Q takes the units of pint. sbmlsim.Q takes the units of pint only. A unit of pint, e.g. the units of a quantity, is taken as it is.

Parameters:

Name Type Description Default
value Any

the magnitude, a number or an array.

required
unit str | PlainUnit | None

the unit, a string or a unit of pint, dimensionless without one.

None
model str | None

the id of the model whose unit ids the unit has. Without it a unit id must have the same expression in every model of the experiment which has it.

None

Returns:

Type Description
Quantity

The quantity.

Raises:

Type Description
ValueError

for a model which is no loaded model of the experiment, and without model for a unit id which models of the experiment define differently.

UndefinedUnitError

for a unit which is neither a unit of pint nor a unit id of the models.

variant_of

variant_of(simulation)

Get the variant of the model of the project a simulation runs on.

The hook of a framework which builds a model per group of subjects (a variant of the model of a Project, e.g. a build per population), which sbmlsim.run verify dump stores per task, so that a study which moves to another build is found. A class method of a subclass may implement it as well. By default the experiment says nothing and verify takes the variant whose file is the source of the model of the task.

Parameters:

Name Type Description Default
simulation str

the key of the simulation of a task.

required

Returns:

Type Description
str | None

The name of the variant, None to leave it to the project.

models

models()

Define model definitions.

The child classes fill out the information.

datasets

datasets()

Define dataset definitions (experimental data).

The child classes fill out the information.

simulations

simulations()

Define simulation definitions.

The child classes fill out the information.

observables

observables()

Define the observables of the experiment, by their id.

A Formula, PK or Custom of sbmlsim.simulation.observables. A Data of a task reads an observable by its id and a parameter of a PK observable as <id>.<parameter>; a task computes the observables its data read, see _run_tasks. The child classes fill out the information.

tasks

tasks()

Define task definitions.

The child classes fill out the information.

data

data()

Define the data of the experiment, including functions of other data.

This determines the selection in the model.

The data of tasks, fit mappings and figures determines the selections of a simulation experiment; registering the data of a figure here is no longer needed. Registered data of a task which no figure or mapping reads still counts, e.g. via add_selections_data.

figures

figures()

Figure definition.

The data the curves and areas of the figures read counts for the selections of the tasks, it needs no registration in data().

Most figures do not require access to concrete data, but only abstract data concepts.

figures_mpl

figures_mpl()

Figures drawn after the run, outside of the figure model.

The hook of figures the figure model cannot describe, called after the tasks ran, so the figures read the results. Every figure is a Chart (sbmlsim.plot.Chart), drawn by the renderer of sbmlsim-core as the figures of figures() are and written with its spec. Any other object, e.g. a figure of matplotlib, fails under its key with a TypeError, see hook_figures.

Selections accessed in these figures must be registered beforehand via the data of the experiment.

A figure is styled with the settings of the experiment, FigureSettings.resolve(experiment=self.figure_settings), e.g. its fig_titlesize; the settings of a run (figure_settings= of run) do not reach this method.

fit_mappings

fit_mappings()

Define fit mappings.

Mapping reference data on observables. Used for the optimization of parameters. The child classes fill out the information.

add_data

add_data(d)

Add data to the tracked data.

add_selections_data

add_selections_data(selections, task_ids=None)

Add selections to given tasks.

The data for the selections will be part of the results.

Selections are necessary to access data from simulations. Here these selections are added to the tasks. If no tasks are given, the selections are added to all tasks.

:param reset: drop and reset all selections.

run

run(
    simulator,
    output_path=None,
    show_figures=False,
    save_results=False,
    figure_formats=None,
    reduced_selections=True,
    keep_results=True,
    on_error="raise",
    figure_settings=None,
    png_dpi=None,
)

Execute given experiment and store results.

A figure which failed in this run, and every figure of a failed experiment which this run did not write, leaves no file of an earlier run in the output path, so that no figure looks like one of this run.

Parameters:

Name Type Description Default
simulator Simulator | None

the simulator of the tasks.

required
output_path Path | None

directory of the outputs (the datasets in its folder DATASETS_DIR, results, figures and the serialization), none are written without it.

None
show_figures bool

show the figures in a notebook, those of figures_mpl() included, also without an output path.

False
save_results bool

write the results of the tasks into the output path.

False
figure_formats list[str] | None

formats of the figures, see sbmlsim.figure_formats.figure_formats_of; the spec of a figure is written beside it in any case.

None
reduced_selections bool

simulate only the selections the experiment uses.

True
keep_results bool

keep the results of the tasks after the outputs are written. Without them an experiment holds only what its report needs, and a run of many experiments only the results of the one it runs; results then raises.

True
on_error Literal['raise', 'log']

what an error does. "raise" (the default) raises it, so a user who runs one experiment sees it. "log" logs it with its traceback and records it in the result, which is what the ExperimentRunner uses: a failing figure is skipped and the others are written (ExperimentResult.failed_figures), an error of the experiment ends its run (ExperimentResult.error).

'raise'
figure_settings FigureSettings | Mapping[str, Any] | None

the settings of the figures of the run, a FigureSettings or overrides of its defaults, which the figure_settings of the experiment and the settings of a figure override.

None
png_dpi float | None

the resolution of every PNG, the fig_dpi of the settings of each figure without.

None

Returns:

Type Description
ExperimentResult

The result of the experiment, which the report is created from,

ExperimentResult

with the seconds of its phases, see ExperimentResult.timings.

Raises:

Type Description
ValueError

if a key of figure_settings is no setting or a format is no figure format, e.g. html, also with on_error="log".

scan_dimension

scan_dimension(task, dim)

Get a dimension of the scan of a task by its id, None if it has none of it.

model_units

model_units(task)

Get the units of the symbols of the model of a task, {} for a model which is not loaded.

evaluate_fit_mappings

evaluate_fit_mappings()

Evaluate fit mappings.

to_json

to_json(path=None, indent=2)

Convert experiment to JSON for exchange.

The experiment is encoded before the file is written, so a value which cannot be encoded leaves no truncated file.

:param path: path for file, if None JSON str is returned :return: :raises TypeError: for a value which ObjectJSONEncoder cannot encode

to_dict

to_dict()

Convert to dictionary.

This is the basis for the JSON serialization. engine is the engine of the simulator which ran the tasks, None before they ran.

dataset_file

dataset_file(key)

Get the file of a dataset relative to the output path of a run.

Parameters:

Name Type Description Default
key str

the key of the dataset.

required

Returns:

Type Description
Path

datasets/<sid>_<key>.tsv, see DATASETS_DIR.

save_datasets

save_datasets(results_path)

Save the datasets as TSV into the folder DATASETS_DIR.

Parameters:

Name Type Description Default
results_path Path

the output path of the run, see dataset_file.

required

save_results

save_results(results_path)

Save the result of every task as netCDF, see ScanResult.to_netcdf.

Parameters:

Name Type Description Default
results_path Path

directory of the files, <sid>_<task>.nc.

required

create_figures

create_figures(
    on_error="raise", failed=None, figure_settings=None
)

Resolve the figures of the experiment into charts of the renderer.

Every figure of figures() reads its data from the results of the run, see sbmlsim.plot.resolve.figure_chart.

Parameters:

Name Type Description Default
on_error Literal['raise', 'log']

"raise" raises the error of a figure, "log" logs it, skips the figure and goes on with the next.

'raise'
failed dict[str, str] | None

collects the failed figures as {key: error}.

None
figure_settings FigureSettings | Mapping[str, Any] | None

the settings of the run, see run.

None

Returns:

Type Description
dict[str, Chart]

The charts by the keys of their figures, without the failed ones.

save_figures

save_figures(
    results_path,
    charts,
    figure_formats=None,
    on_error="raise",
    failed=None,
    dpi=None,
)

Draw charts with the renderer and write their files.

A chart is written as <sid>_<key>.<format> in every format of the run, its spec (SPEC_FORMAT) included, see figure_formats_of.

Parameters:

Name Type Description Default
results_path Path

directory of the files.

required
charts Mapping[str, Chart]

the charts by their keys, see create_figures.

required
figure_formats Sequence[str] | None

formats of the files, see figure_formats_of.

None
on_error Literal['raise', 'log']

"raise" raises the error of a figure, "log" logs it and goes on with the next figure.

'raise'
failed dict[str, str] | None

collects the failed figures as {key: error}.

None
dpi float | None

the resolution of a PNG, the one of its chart without.

None

Returns:

Type Description
dict[str, list[Path]]

The files of every chart which was written, by its key.

hook_figures

hook_figures(on_error='raise', failed=None)

Get the charts of figures_mpl().

A failing figures_mpl() fails all of its figures under the key HOOK_FAILURE, which is no valid figure key. A figure which is no Chart fails under its own key with a TypeError which names the chart builder; the other figures are kept.

Parameters:

Name Type Description Default
on_error Literal['raise', 'log']

"raise" raises the error, "log" logs it.

'raise'
failed dict[str, str] | None

collects the failures as {key: error}.

None

Returns:

Type Description
dict[str, Chart]

The charts by their keys, none after an error of the hook.

save_hook_figures

save_hook_figures(
    results_path,
    formats=None,
    on_error="raise",
    failed=None,
    dpi=None,
    figures=None,
)

Write the charts of figures_mpl(), as save_figures does.

Parameters:

Name Type Description Default
results_path Path

directory of the files.

required
formats Sequence[str] | None

formats of the files, see figure_formats_of.

None
on_error Literal['raise', 'log']

"raise" raises the error of a figure, "log" logs it and goes on with the next figure.

'raise'
failed dict[str, str] | None

collects the failed figures as {key: error}.

None
dpi float | None

the resolution of a PNG, the one of each chart without.

None
figures Mapping[str, Chart] | None

the charts, hook_figures() without.

None

Returns:

Type Description
dict[str, list[Path]]

The files of every chart which was written, by its key.

ExperimentRunError

ExperimentRunError(results)

Bases: Exception

One or more experiments or figures of a run failed.

Raised by ExperimentRunner.run_experiments(raise_on_failure=True) after every experiment ran.

Attributes:

Name Type Description
results

the results of all experiments of the run, empty in a copy which was pickled.

failures

the failed experiments and figures, one line each.

Create the error from the results of a run.

ExperimentResult dataclass

ExperimentResult(
    experiment,
    output_path,
    error=None,
    failed_figures=dict(),
    figures=dict(),
    datasets=list(),
    timings=dict(),
)

Result of a simulation experiment.

failed property

failed

Check whether the experiment or one of its figures failed.

to_dict

to_dict()

Conversion to dictionary.

Used in serialization and required for reports.