Skip to content

Calibration workflows

A calibration workflow is an ordered set of steps (calibrations, and the analyses around them) whose results are merged into one target model; see Calibration workflows for the how-to. WorkflowBuilder makes a workflow with API calls and runs it; the functions below it run, plan and read a workflow file however it was written.

Building a workflow

libcuflynx.calibration_workflow.builder.WorkflowBuilder

WorkflowBuilder(
    name,
    target,
    *,
    directory,
    description=None,
    module_library_dirs=(),
    settings=None
)

A calibration workflow made by API calls, written as an ordinary calibration_workflow.json and run from Python.

Creating a builder writes nothing: files are written by :meth:write (which :meth:run, :meth:plan, :meth:status, :meth:model and :meth:plot_step call).

Parameters:

Name Type Description Default
name

the workflow's name (workflow_name). It names the functions files and the run's default output directory.

required
target

the model the calibrated values are merged into, and the model of each step that names none: a module array path, :func:module_array, :func:library_module, :func:external_model or :func:cellml_model.

required
directory

where the workflow file, its data/ and its functions files are written; created by :meth:write. Relative paths given to the builder are relative to the working directory at the time of the call.

required
description

the workflow's description.

None
module_library_dirs

the module libraries (directories) the models' modules come from. Needed whenever a model names a library module, a module array's too.

()
settings

the workflow's settings, user_inputs.yaml keys (spec.ALLOWED_SETTINGS: param_id_method, optimiser_options, dt, ...), checked at once. A step's own settings are merged over them.

None

Raises:

Type Description
WorkflowError

an unknown setting, or a name or target the schema refuses.

Attributes:

Name Type Description
directory Path

the absolute directory the workflow is written to.

path Path

the workflow file, <directory>/calibration_workflow.json.

settings dict

the workflow's settings, paths absolute. Change them with :meth:update_settings, which checks them.

directory property

directory

The absolute directory the workflow is written to (a pathlib.Path).

path property

path

The workflow file (a pathlib.Path).

name property

name

The workflow's name (workflow_name).

target property

target

The target model, as given (a copy; paths absolute).

module_library_dirs property

module_library_dirs

The module libraries the models come from (absolute paths).

output_dir property

output_dir

Where :meth:run writes unless told otherwise: <directory>/workflow_output/<name> (a pathlib.Path), which is also where the cuflynx-calibration-workflow command runs the written file.

steps property

steps

The step ids (a list), in the order they were added.

load classmethod

load(path)

A builder for an existing workflow, written back to the same file.

Parameters:

Name Type Description Default
path

the workflow file, or the directory holding its calibration_workflow.json.

required

The functions files a builder wrote beside it are read back (their functions and imports), so functions can be added, replaced or removed. Returns the builder.

update_settings

update_settings(**settings)

Set workflow settings (the keys of spec.ALLOWED_SETTINGS), checked against the schema at once. A dict setting is merged one level deep, as a step's are: update_settings(optimiser_options={'seed': 2}) keeps the other optimiser options. A setting given as None is removed. Nothing is written until :meth:write.

Raises:

Type Description
WorkflowError

an unknown setting, or one the schema refuses.

add_calibration

add_calibration(
    id,
    *,
    obs_data,
    params_for_id=None,
    params_for_id_from=None,
    model=None,
    fixed_from=(),
    priors_from=(),
    store_distribution=False,
    start_from=None,
    emulator_from=None,
    emulator_dir=None,
    module=None,
    submodule=None,
    module_map=None,
    settings=None,
    description=None,
    comment=None
)

Add a calibration: fit parameters of a model to an obs_data.

Nothing is written or run by this call; the step is checked against the schema, and the dicts given are copied. A step with this id already is replaced in place, so to change a step, change what you pass and call this again.

Parameters:

Name Type Description Default
id

the step's name: other steps refer to it and its results go to <output_dir>/<id>/. No / or \; at most 80 characters; unlike every other id whatever the case.

required
obs_data

what to fit: a path to an obs_data JSON file, an obs_data dict, or an ObsDataCreator. A dict is written to data/<id>_obs_data.json by :meth:write.

required
params_for_id

what to calibrate: a path to a params_for_id JSON file, a list of {vessel_name, param_name, min, max} entries (as CVS0DParamID takes), a list of {targets, min, max} entries, or a {"version", "params"} document. Not a path: written to data/<id>_params_for_id.json.

None
params_for_id_from

instead of params_for_id, the reduction step (:meth:add_reduction) whose chosen parameters are calibrated.

None
model

the model the step runs on: a module array path, :func:module_array, :func:library_module or :func:selection. Default: the target.

None
fixed_from

calibration or set step ids, or :func:fixed entries for only some of a step's values (one, or a list), whose values are fixed in this step's model; this step runs after them.

()
priors_from

step ids or :func:prior entries whose stored distributions become this step's priors (those steps set store_distribution).

()
store_distribution

after the fit, sample the posterior by MCMC (needs the UQ_options setting) and store it for later steps.

False
start_from

a calibration or set step at whose values this step's own parameters start.

None
emulator_from

an emulation step (:meth:add_emulation) whose emulator this step is evaluated on; give the same model, obs_data and params_for_id. With params_for_id_from a reduction of that emulator's params_for_id, the step calibrates the parameters the reduction kept and holds the emulator's others at their values in the emulation step's model.

None
emulator_dir

instead of emulator_from, the directory of an emulator trained outside the workflow.

None
module

for a library module in a module-array target, the module it is (inferred when the module occurs once).

None
submodule

for a library module in a library supermodule target, where it sits (inferred when the module occurs once).

None
module_map

for a module-array model, {its module name: the target's}.

None
settings

this step's settings, merged over the workflow's one dict level deep.

None
description

free text, shown in reports.

None
comment

free text, kept in the file.

None

Returns:

Type Description

id.

Raises:

Type Description
WorkflowError

the step does not fit the schema (the message names the key).

add_sensitivity

add_sensitivity(
    id,
    *,
    obs_data,
    params_for_id,
    sa_options,
    model=None,
    fixed_from=(),
    result_from=None,
    emulator_from=None,
    emulator_dir=None,
    module=None,
    submodule=None,
    module_map=None,
    settings=None,
    description=None,
    comment=None
)

Add a sensitivity analysis of params_for_id against obs_data.

Parameters:

Name Type Description Default
sa_options

the analysis options (the sa_options setting: method, num_samples, sample_type, ...), written into the step's settings.

required
result_from

a calibration step whose values the model is generated with, so the analysis is at that result.

None

The other arguments, what is returned and when files are written are as for :meth:add_calibration.

add_reduction

add_reduction(
    id,
    *,
    sensitivity_from=None,
    param_reduction_options=None,
    params_for_id=None,
    method=None,
    n_params=None,
    parameters=None,
    reason=None,
    index_type=None,
    criterion=None,
    threshold=None,
    min_mode_std=None,
    variance_fraction=None,
    min_index=None,
    redundancy_check=None,
    redundancy_statistic=None,
    redundancy_converged_only=None,
    redundancy_convergence_tol=None,
    description=None,
    comment=None
)

Add a reduction: choose the parameters a later step calibrates (its params_for_id_from) from the Sobol indices of a sensitivity step, or by hand (method='manual').

Parameters:

Name Type Description Default
id

the step's name (see :meth:add_calibration).

required
sensitivity_from

the sensitivity step whose results are reduced (not for 'manual').

None
param_reduction_options

the reduction's options (the schema's param_reduction_options), written as the step's settings.param_reduction_options; a key left out takes the schema's default, and method is 'pca' unless given:

  • method: 'pca' (one parameter per informative mode of the Sobol outputs), 'sobol' (the n_params parameters with the highest index) or 'manual' (the parameters named, chosen by hand);
  • parameters: manual: the parameters to keep, each named as its params_for_id entry is labelled ('heart/E_lv_A');
  • reason: manual: why these parameters were chosen;
  • n_params: how many parameters to keep (pca: at most; sobol: required);
  • index_type: 'ST' (total, the default) or 'S1' (first-order);
  • criterion: sobol: a parameter's score, the 'max' or 'mean' of its index;
  • threshold: sobol: drop parameters scoring below this;
  • min_mode_std: pca: a mode is informative when its std over the samples is at least this many obs_data stds (default 1);
  • variance_fraction: pca: only the leading modes explaining this fraction of the variance (default 1, no cut);
  • min_index: pca: skip a mode whose largest index is below this (default 0.05);
  • redundancy_check: the check for parameters with the same effect on the outputs;
  • redundancy_statistic: pca with redundancy_check: 'median' (default) or 'rms' of a parameter's unexplained effect over the local Jacobian points;
  • redundancy_converged_only: pca with redundancy_check: leave out the points whose derivatives change with the step (needs sa_options.jacobian_check_steps);
  • redundancy_convergence_tol: the largest relative change between the two steps (default 0.1).
None
params_for_id

manual: the params_for_id whose entries, with their ranges, are kept (what :meth:add_calibration takes).

None
description, comment

free text.

required

Returns id.

Raises:

Type Description
WorkflowError

an option is given both ways with different values, or the step does not fit the schema.

add_emulation

add_emulation(
    id,
    *,
    obs_data,
    emulator_settings=None,
    params_for_id=None,
    params_for_id_from=None,
    model=None,
    fixed_from=(),
    module=None,
    submodule=None,
    module_map=None,
    settings=None,
    description=None,
    comment=None
)

Add an emulator training: a surrogate of the obs_data's features over the params_for_id ranges, for calibration and sensitivity steps that name this step as their emulator_from.

Parameters:

Name Type Description Default
emulator_settings

the training options (the emulator_settings setting), written into the step's settings. Default: the workflow's, else the engine's defaults.

None

The other arguments, what is returned and when files are written are as for :meth:add_calibration.

add_identifiability

add_identifiability(
    id,
    *,
    obs_data,
    params_for_id,
    ia_options,
    result_from=None,
    model=None,
    fixed_from=(),
    emulator_from=None,
    emulator_dir=None,
    module=None,
    submodule=None,
    module_map=None,
    settings=None,
    description=None,
    comment=None
)

Add an identifiability analysis of params_for_id at a step's values.

Parameters:

Name Type Description Default
ia_options

the analysis options (the ia_options setting; method, 'Laplace' or 'profile_likelihood', is required), written into the step's settings.

required
result_from

the calibration or set step whose values the analysis is at. Default: the model's own values.

None
emulator_from, emulator_dir

the emulator the analysis runs on, as for :meth:add_calibration (emulator_from not with result_from).

required

The other arguments, what is returned and when files are written are as for :meth:add_calibration.

add_uq

add_uq(
    id,
    *,
    obs_data,
    params_for_id,
    uq_options={},
    result_from=None,
    model=None,
    fixed_from=(),
    emulator_from=None,
    emulator_dir=None,
    module=None,
    submodule=None,
    module_map=None,
    settings=None,
    description=None,
    comment=None
)

Add an uncertainty quantification of params_for_id at a step's values, with no fit of its own. Its distribution is stored, for a later step's priors_from, and checked by a posterior predictive check unless posterior_predictive is false.

Parameters:

Name Type Description Default
uq_options

the options (the UQ_options setting; method is 'mcmc' or 'laplace'), written into the step's settings (copied, never changed). Default {}: the workflow's, else MCMC with the engine's defaults.

{}
result_from

the calibration or set step whose values it is at. Default: the model's own values.

None

The other arguments, what is returned and when files are written are as for :meth:add_calibration.

add_set

add_set(
    id,
    entries,
    *,
    point=False,
    description=None,
    comment=None
)

Add a set step: values of the target set by hand, each with its reason (which goes into the provenance).

Parameters:

Name Type Description Default
id

the step's name (see :meth:add_calibration).

required
entries

a list of :func:set_value, :func:scale_value and, with point, :func:set_theta entries.

required
point

the values are only a point for start_from, result_from or fixed_from: they are not merged into the target.

False
description, comment

free text.

required

Returns id.

add_combine

add_combine(
    id,
    combine_from,
    *,
    method="best_fit",
    description=None,
    comment=None
)

Add a combine step: one value per parameter from several steps that give the same parameters and do not take from each other. Later steps and the target take its values in place of theirs.

Parameters:

Name Type Description Default
id

the step's name (see :meth:add_calibration).

required
combine_from

the ids of the calibration, set or combine steps combined (two or more).

required
method

'best_fit': the values of the calibration with the lowest cost (the steps are calibrations of the same obs_data, with the same cost_type and parameters). 'mean': each parameter's mean over the steps that give it.

'best_fit'
description, comment

free text.

required

Returns id.

add_sweep

add_sweep(
    id,
    *,
    parameters,
    model=None,
    on_target=False,
    obs_data=None,
    design=None,
    outputs=None,
    zip=None,
    fixed_from=(),
    result_from=None,
    module=None,
    submodule=None,
    module_map=None,
    settings=None,
    description=None,
    comment=None
)

Add a parameter sweep: simulate a model over a grid of parameter values.

Parameters:

Name Type Description Default
parameters

{name: [min, max] | {min, max, points, scale} | {values} | {factors}}, the ranges swept.

required
model

the model swept. Default: the target.

None
on_target

sweep the target with every calibrated and set value merged, after every calibration and set step. Then give no model, fixed_from or result_from.

False
obs_data

gives the protocol, and its prediction items a feature per point; without one, the settings give dt and sim_time.

None
design

how the points are laid out (the schema's sweep.design).

None
outputs

what each point records (the schema's sweep.outputs).

None
zip

parameters varied together rather than crossed.

None
result_from

a calibration step whose values the model is generated with.

None

The other arguments, what is returned and when files are written are as for :meth:add_calibration.

add_simulate

add_simulate(
    id,
    *,
    model=None,
    on_target=False,
    obs_data=None,
    outputs=None,
    fixed_from=(),
    result_from=None,
    module=None,
    submodule=None,
    module_map=None,
    settings=None,
    description=None,
    comment=None
)

Add a simulate step: one run of a model through its protocol (a sweep of no parameters), for a figure step to read.

Parameters:

Name Type Description Default
outputs

the variables recorded over time (the schema's simulate.outputs).

None

The other arguments are as for :meth:add_sweep.

add_figure

add_figure(
    id,
    *,
    function,
    inputs,
    files=None,
    description=None,
    comment=None
)

Add a figure step: a Python function that draws from other steps' results (calibration_workflow/figures.py has the contract).

Parameters:

Name Type Description Default
function

'<script.py>:<function>', the script's path relative to the working directory (written relative to the workflow file).

required
inputs

{parameter: {input kind: step id}}, one per parameter of the function but out_dir.

required
files

other files the script reads (helpers, a style module); editing one makes the figure out of date.

None
description, comment

free text.

required

Returns id.

add_step

add_step(id, kind='calibration', **raw)

Add a step of any kind from its raw schema keys (model, obs_data, settings, ...; see schemas/calibration_workflow.schema.json). The add_* methods call this.

Parameters:

Name Type Description Default
id

the step's name (see :meth:add_calibration).

required
kind

'calibration', 'sensitivity', 'reduction', 'emulation', 'identifiability', 'uq', 'set', 'combine', 'sweep', 'simulate' or 'figure'.

'calibration'
**raw

the step's keys. obs_data and params_for_id take what :meth:add_calibration takes; model defaults to the target for the kinds that run a model (not for a sweep with on_target); a key given as None is left out.

{}

A step with this id already is replaced in place. Returns id.

Raises:

Type Description
WorkflowError

the id cannot be used, or the step does not fit the schema.

remove_step

remove_step(id)

Remove step id from the workflow. Its data files and results stay on disk.

Raises:

Type Description
WorkflowError

there is no such step.

add_operation

add_operation(*funcs, overwrite=False)

Add functions an obs_data item can name as its operation.

Each function's source is copied (now) and written by :meth:write into <name>_operation_funcs.py beside the workflow, which the workflow's operation_funcs_external_path setting then names, so every rank, the command line and CUFLynx load it. A function added again replaces its earlier source: edit it where it is defined and add it again.

Parameters:

Name Type Description Default
*funcs

functions defined with def at the top level of a cell or module. A helper another function calls is added too (name it with a leading _ and it is not registered as an operation).

()
overwrite

replace a functions file that was edited by hand, or that no builder wrote. Without it such a file is refused, so its edits are not lost.

False

Raises:

Type Description
WorkflowError

a function cannot be written to a file (a lambda, a closure, a name defined only in the session), the workflow names another functions file, or the file on disk would lose hand edits.

add_cost_func

add_cost_func(*funcs, overwrite=False)

As :meth:add_operation, for cost functions an obs_data item names as its cost_type: written to <name>_cost_funcs.py, named by cost_funcs_external_path.

add_modifier_func

add_modifier_func(*funcs, overwrite=False)

As :meth:add_operation, for modifier functions a params_for_id entry names as its modifier: written to <name>_modifier_funcs.py, named by modifier_funcs_external_path. Each must carry @modifier_func.

remove_operation

remove_operation(*names)

Remove operations by name (or by the function), so :meth:write leaves them out of the functions file. Removing the last one removes the setting naming the file; the file itself stays on disk.

remove_cost_func

remove_cost_func(*names)

As :meth:remove_operation, for cost functions.

remove_modifier_func

remove_modifier_func(*names)

As :meth:remove_operation, for modifier functions.

functions

functions(kind='operation')

The names of the functions added so far, in the order they are written. kind is 'operation', 'cost' or 'modifier'.

funcs_source

funcs_source(kind='operation')

The text of the kind ('operation', 'cost', 'modifier') functions file as :meth:write writes it, or None when no function of that kind was added: utilities.user_funcs_file's layout, which CUFLynx writes too. Writes nothing.

to_dict

to_dict()

The workflow as :meth:write writes it: the raw dict of calibration_workflow.json, its paths relative to :attr:directory (with /) and each dict input as the data/ file it goes to. Writes nothing.

check

check()

Check the workflow without writing or running anything.

Runs every check of the file (the schema, and those across steps such as an unknown fixed_from), then what a run needs beyond the file: a module library when a model names library modules, and the settings the chosen calibration method requires.

Returns:

Type Description

the parsed :class:~libcuflynx.calibration_workflow.spec.Workflow.

Raises:

Type Description
WorkflowError

naming each problem and how to fix it.

write

write(overwrite=False)

Write the workflow to :attr:directory, after checking it.

Writes calibration_workflow.json, a data/<step>_obs_data.json or data/<step>_params_for_id.json for each input given as a dict or entries, and a <name>_<kind>_funcs.py for the functions given to :meth:add_operation, :meth:add_cost_func and :meth:add_modifier_func. A file whose content is unchanged is left as it is, so its steps do not become stale. :meth:run, :meth:plan, :meth:status, :meth:model and :meth:plot_step call this first.

Parameters:

Name Type Description Default
overwrite

replace a functions file that was edited by hand, or that no builder wrote, with the functions given to this builder.

False

Returns:

Type Description

the workflow file's path (a pathlib.Path).

Raises:

Type Description
WorkflowError

the workflow does not pass its checks, a functions file would lose hand edits, or a step names as its own a file in data/ that the builder writes.

plan

plan()

What a run would do, without running anything: :meth:check, :meth:write, then :func:~libcuflynx.calibration_workflow.plan_workflow.

Returns:

Type Description

``{'workflow_name', 'target', 'target_parameters', 'module_library_dirs',

'steps'};stepsis in run order, each{'id', 'kind', 'model', 'place',

'depends_on', 'obs_data', 'params_for_id', 'calibrates' (each parameter and where

it lands in the target), 'fixed_from', 'priors_from', 'store_distribution',

'settings'}``.

show_plan

show_plan()

Print :meth:plan as a table, one line per step in run order: its kind, its model, the steps it takes from, and the parameters it calibrates or sets. Runs nothing; returns None (:meth:plan returns the dict).

run

run(
    *,
    only=None,
    from_step=None,
    force=False,
    output_dir=None,
    dry_run=False,
    write_calibrated=False,
    ranks=1,
    progress=None,
    verbose=False
)

Check and write the workflow (:meth:check, :meth:write), then run it.

Without only and from_step, the steps that are done and current are kept (one line is printed for each) and only those that have not run, or are stale, are run: running the same cell or script again repeats no calibration. A step is stale when its obs_data, params_for_id, parameters, settings or functions file changed since it ran, or a step it takes values from is stale or ran again (:meth:status).

Parameters:

Name Type Description Default
only

run just this step, reusing the results it depends on (which must be current).

None
from_step

run this step and every step after it, whether or not they are current.

None
force

run every step again, current or not.

False
output_dir

where the run goes. Default :attr:output_dir.

None
dry_run

run nothing; return the plan (as :meth:plan).

False
write_calibrated

also write the merged values beside the target's parameters file, as <name>_calibrated_parameters.json (complete runs only).

False
ranks

the number of MPI ranks. More than one runs mpiexec -n <ranks> python -m libcuflynx.scripts.calibration_workflow_run_script on the written file.

1
progress

callable(event) called for each step event (one rank only). Default: print one [workflow] line per event. False: print no such line.

None
verbose

also print everything the steps write (the optimiser's iterations, compiler output, warnings) as it comes. By default only the [workflow] lines are printed; the rest is in the log files either way.

False

Returns:

Type Description

the workflow result, also written as <output_dir>/workflow_result.json:

{'workflow_name', 'complete', 'order', 'steps', 'merged_parameters', ...}.

With dry_run, the plan.

The run writes <output_dir>/<step id>/ for each step (step_result.json, the generated model, the calibration's outputs), workflow_result.json, the provenance graph and _target/, the target generated with every merged value.

Everything the run writes to the terminal is kept: a step's output in <output_dir>/<step id>/log.txt (<output_dir>/step_log.<step id>.txt while the step runs), and what is written outside the steps, with every [workflow] line, in <output_dir>/workflow_log.txt. Each run replaces the logs of the steps it runs.

Raises:

Type Description
WorkflowError

the workflow cannot run (see :meth:check), a result only needs is missing or stale, or the launched command failed.

status

status(output_dir=None)

Where each step stands in the run in output_dir (default :attr:output_dir), after :meth:write; nothing is run (:func:workflow_status).

Returns:

Type Description

{'workflow_name', 'order', 'complete', 'steps'}: complete is True when

every step is done and current, and steps is ``{id: {'status' ('done' or

'not_run'), 'stale', 'library_changed', 'best_cost', 'finished',

'point_estimate'}}.stale`` is True when the step's obs_data, params_for_id,

parameters, settings or functions file changed since it ran, or a step it takes

values from is stale or ran again after it.

show_status

show_status(output_dir=None)

Print :meth:status as a table, one line per step in run order: done, stale (done, but something it depends on changed) or not run, a calibration's best cost, and when it finished. Runs nothing; returns None (:meth:status returns the dict).

result

result(id, output_dir=None)

What step id recorded when it ran into output_dir (default :attr:output_dir): the content of its step_result.json, read with :func:~libcuflynx.calibration_workflow.load_workflow_run. Writes nothing.

Returns:

Type Description

a dict with, for every kind, 'step', 'kind', 'status', 'started',

'finished', 'duration_s', 'inputs' and 'step_dir', and the kind's

own keys, its files and directories as absolute pathlib.Path:

  • calibration: 'values' ({"<module>/<parameter>": best value}), 'best_cost', 'calibrated' (each value with its units and where it lands in the target), 'fixed', 'point_estimate', 'param_id_output_dir', 'distribution_dir';
  • sensitivity: 'sensitivity_dir', 'sobol_indices';
  • reduction: 'parameters' (the names chosen), 'selected' (each with its score), 'params_for_id' (the file a later step calibrates), 'report' (param_reduction.json);
  • emulation: 'emulator_dir'; identifiability: 'laplace';
  • sweep: 'sweep_dir', 'sweep_results' (sweep_results.npz).

Raises:

Type Description
WorkflowError

there is no such step, or it has not run into output_dir.

step_dir

step_dir(id, output_dir=None)

The output directory of step id in the run in output_dir (default :attr:output_dir), as a pathlib.Path; it exists once the step has run.

plot_step

plot_step(id, output_dir=None, *, formats=('png',))

Plot a calibration step's best fit against its obs_data, after :meth:write: the model is simulated with the step's best values and plot_outputs of the param_id run writes the figures under the step's param_id/ directory.

Parameters:

Name Type Description Default
id

a calibration step that has run.

required
output_dir

the run. Default :attr:output_dir.

None
formats

the file formats each figure is saved in: any of 'png', 'pdf' and 'eps' (one name, or several).

('png',)

Returns:

Type Description

the image files written (a sorted list of pathlib.Path).

Raises:

Type Description
WorkflowError

the step has not run, or is not a calibration, or a format is not one of the three.

model

model(view, output_dir=None, work_dir=None)

Generate the model of step view, or of 'target', with the values found so far in output_dir (:func:workflow_model), after :meth:write.

Parameters:

Name Type Description Default
view

a step id, or 'target'.

required
output_dir

the run to take values from. Default :attr:output_dir.

None
work_dir

where the model is generated. Default <output_dir>/models, giving <output_dir>/models/<view>/.

None

Returns:

Type Description

``{'view', 'kind' ('step' or 'target'), 'model_path', 'flat_model_path' (one

self-contained CellML file), 'parameters_path', 'obs_data_path',

'params_for_id_path', 'fixed', 'calibrated', 'waiting_for' (steps whose results

it should have but that have not run), 'stale', ...}; each*_path`` is a

pathlib.Path.

clean

clean(delete=False)

The files this workflow's builder wrote into :attr:directory that no workflow there uses any more (the data file of a step that was removed or renamed, a functions file whose functions were all removed), and, with delete=True, their removal.

A file is listed only when all of these hold: a builder wrote it for this workflow file (write() records each file it writes, with its checksum, in .workflow_builder_files.json); its content is still what the builder wrote; and no JSON file at the top of the directory, nor this builder as it stands, names it. Nothing under workflow_output/ is ever listed: a run's results are not the builder's files. A workflow in another directory that names these files is not seen.

Parameters:

Name Type Description Default
delete

False (the default) only lists the files. True moves them to data/removed/ under the directory, keeping their relative paths; nothing is deleted, so moving a file back restores it.

False

Returns:

Type Description

the files (a list of pathlib.Path): where they are, or with delete=True

where they were moved to. One line per file is printed.

Raises:

Type Description
WorkflowError

a JSON file in the directory cannot be read, so what it uses is not known.

What a step is made of

libcuflynx.calibration_workflow.builder.library_module

library_module(module_type, version, parameterisation)

A model that is a module of a module library, for target= or a step's model=.

Parameters:

Name Type Description Default
module_type

the module's type (its directory in the library).

required
version

the version of that module.

required
parameterisation

the parameterisation of that version.

required

Returns:

Type Description

{'module_type', 'version', 'parameterisation'}, the schema's form.

libcuflynx.calibration_workflow.builder.module_array

module_array(path, parameters=None)

A model that is a module array file, for target= or a step's model=.

Parameters:

Name Type Description Default
path

the <prefix>_module_array.json (or .csv) file.

required
parameters

its parameters file, when that is not <prefix>_parameters.json beside it.

None

Returns:

Type Description

the path, or {'module_array', 'parameters'} with parameters.

libcuflynx.calibration_workflow.builder.external_model

external_model(path)

A model that is an external Python model, for target=. A workflow with one has it as its target and as every step's model.

Parameters:

Name Type Description Default
path

the .py file defining SIM_HELPER.

required

Returns:

Type Description

{'external_model_path': path}, the schema's form.

libcuflynx.calibration_workflow.builder.cellml_model

cellml_model(path, parameters=None)

A model that is a CellML file, for target=. A workflow with one has it as its target and as every step's model.

Parameters:

Name Type Description Default
path

the CellML file.

required
parameters

a parameters file whose values replace the CellML's.

None

Returns:

Type Description

{'cellml_model_path': path[, 'parameters']}, the schema's form.

libcuflynx.calibration_workflow.builder.selection

selection(*instances)

A step model that is a selection of the target's instances.

Parameters:

Name Type Description Default
*instances

record names of the target's module array, or paths into a super instance such as heart/lv (or one list of them).

()

Returns:

Type Description

{'select': [...]}, the schema's form.

libcuflynx.calibration_workflow.builder.fixed

fixed(step, parameters=None)

A fixed_from entry: the values of an earlier step, fixed in this step's model.

Parameters:

Name Type Description Default
step

the calibration or set step.

required
parameters

only these of the values it calibrated or set (model names in that step). Default: every value, and the values it was itself given as fixed.

None

Returns:

Type Description

the step id, or {'step', 'parameters'}.

libcuflynx.calibration_workflow.builder.prior

prior(step, kind=None, inflate=None, parameters=None)

A priors_from entry: the stored distribution of an earlier step as a prior.

Parameters:

Name Type Description Default
step

the step, which sets store_distribution.

required
kind

how the stored samples are represented: 'mvnormal' (the default), 'normal' or 'kde'.

None
inflate

multiplies the distribution's variance (default 1).

None
parameters

only these parameters (model names in the source step).

None

Returns:

Type Description

the step id, or {'step', ...} with the options given.

libcuflynx.calibration_workflow.builder.set_value

set_value(parameter, value, *, reason, units=None)

An entry of :meth:WorkflowBuilder.add_set: a value set by hand.

Parameters:

Name Type Description Default
parameter

<module>/<parameter> in the target.

required
value

the value.

required
reason

why it is set by hand (required; shown in the provenance).

required
units

the value's units; by default those the target gives it.

None

Returns:

Type Description

the entry, {'parameter', 'value', 'reason'[, 'units']}.

libcuflynx.calibration_workflow.builder.scale_value

scale_value(parameter, scale, *, of, reason, units=None)

An entry of :meth:WorkflowBuilder.add_set: a value scaled by hand.

Parameters:

Name Type Description Default
parameter

<module>/<parameter> in the target.

required
scale

the factor.

required
of

the step whose value of the parameter is scaled, or "inherited" for the target's own value.

required
reason

why (required; shown in the provenance).

required
units

the value's units; by default those the target or the of step gives it.

None

Returns:

Type Description

the entry, {'parameter', 'scale', 'of', 'reason'[, 'units']}.

Running and reading a workflow file

libcuflynx.calibration_workflow.runner.run_calibration_workflow

run_calibration_workflow(
    source,
    *,
    output_dir=None,
    module_library_dirs=None,
    from_step=None,
    only=None,
    stale_only=False,
    dry_run=False,
    write_calibrated=False,
    progress=None,
    comm=None
)

Run the calibration workflow source (a calibration_workflow.json path or its dict).

Parameters:

Name Type Description Default
output_dir

where the run goes (default workflow_output/<workflow_name> beside the workflow file; under the working directory for a workflow given as a dict).

None
module_library_dirs

module libraries, added to the file's own.

None
from_step

run this step and every step after it in the order; earlier steps' results are reused from output_dir (an error if missing, or if their obs_data, params_for_id or parameters changed since).

None
only

run just this step, reusing the results it depends on.

None
stale_only

without from_step and only, run just the steps that have not run or are stale (:func:workflow_status), keeping the results that are current.

False
dry_run

resolve and check everything, run nothing; returns :func:plan_workflow.

False
write_calibrated

write the merged set as the target parameterisation's <parameterisation>_calibrated_parameters.json (complete runs only).

False
progress

callable(event_dict), called on rank 0 with event in workflow_started, step_started, step_finished, step_failed, step_skipped (with has_result, and current True for a step stale_only left alone or a figure step that is up to date), workflow_finished.

None
comm

an MPI communicator (default COMM_WORLD, or a one-rank stand-in).

None

Returns the workflow_result dict (also written as workflow_result.json).

libcuflynx.calibration_workflow.runner.plan_workflow

plan_workflow(source, module_library_dirs=None)

What running the workflow would do, without running anything: the order, each step's files, where its values land in the target, and what it is given by earlier steps. target_overlap is the message a run of every step would refuse the workflow with when steps that do not take from each other give the target one parameter (also a UserWarning here), else None.

libcuflynx.calibration_workflow.runner.workflow_status

workflow_status(
    source, output_dir, module_library_dirs=None
)

Where each step of a workflow stands in output_dir, cheaply (no generation).

Returns {'workflow_name', 'order', 'complete', 'steps': {id: {'status', 'stale', 'library_changed', 'best_cost', 'finished', 'point_estimate'}}} with status 'done' or 'not_run'; stale is True when the step's obs_data, params_for_id, parameters or settings changed since it ran, or a step it takes values from is stale or was rerun after it. library_changed says the module library changed; a library holds far more than a model uses, so that alone does not make a step stale.

libcuflynx.calibration_workflow.runner.workflow_model

workflow_model(
    source,
    view,
    *,
    output_dir,
    work_dir,
    module_library_dirs=None,
    with_own_results=True,
    validate=True
)

Generate the model one tab of a workflow shows, from whatever results exist so far.

view is a step id, or 'target' for the workflow's target. A step's model gets the values its fixed_from and result_from steps calibrated (those that have run into output_dir) and, with with_own_results, its own calibrated values once it has run. The target gets every calibrated value there is, mapped into its naming. Nothing is calibrated, and nothing in output_dir is written but the model, under work_dir (which may be <output_dir>/models, :data:MODELS_DIR, a folder no step's output can have).

validate=False skips the trial run generation ends with (a Myokit compile, about half the time of a view), for a caller that compiles or runs the model itself straight after. A model with parameters left unset is still refused.

Returns {view, kind ('step' or 'target'), target, submodule_path, model_path, flat_model_path (one self-contained CellML file), parameters_path, obs_data_path, params_for_id_path, fixed, calibrated, waiting_for, stale, result, param_id_output_dir}. fixed lists the values given by earlier steps, but not result_from's values of the parameters the step analyses; calibrated the view's own (for the target, the merged set: each value from the last step that set it, with origin and reason when it was set by hand); waiting_for the steps whose results it should have but that have not run; stale those whose inputs changed since they ran. obs_data / params_for_id are None when the parameterisation has none (a target with no step of its own). For the target, step_id, its obs_data, params_for_id, result and param_id_output_dir are those of the last calibration on the target that has run, or of the last one when none has.

libcuflynx.calibration_workflow.runner.load_workflow_run

load_workflow_run(output_dir)

A workflow run read back from output_dir: {'workflow': dict, 'result': dict or None, 'steps': {step id: step_result or None}} -- a partial run has some steps None.

libcuflynx.calibration_workflow.pack.pack_workflow

pack_workflow(
    source,
    dest_dir,
    module_library_dirs=None,
    overwrite=False,
)

Copy what the calibration workflow source (a calibration_workflow.json path) needs to run into dest_dir (see the module docstring), checking it first as a run would.

dest_dir is a new or empty directory. With overwrite=True it may also hold an earlier pack, which is replaced: a directory holding anything a pack does not write (PACKED_NAMES) is still refused, so nothing else is ever removed.

Returns {'workflow': the packed workflow file, 'files': [every file written, relative to dest_dir], 'modules': [the module version directories packed, relative to dest_dir], 'sources': {the real path of each input file or settings directory: its path relative to dest_dir}}. Running the packed workflow gives what running source does.

A calibration workflow run packs its workflow into <output_dir>/inputs/workflows/<name>/<first used>/ (runner.packed_inputs), so its working dir holds every input it was run from.

The functions file

libcuflynx.utilities.user_funcs_file

The files of user functions -- operations, cost functions, modifiers -- that the operation_funcs_external_path, cost_funcs_external_path and modifier_funcs_external_path settings name.

One layout for every writer (CUFLynx's "Custom funcs" dialog, and calibration_workflow.WorkflowBuilder.add_operation), so either can read and rewrite what the other wrote::

"""<the kind's header docstring>"""
import numpy as np
from libcuflynx... import <the kind's decorators>
mb = make_math_backend("numpy")         (operations and cost functions)
# libcuflynx-generated sha256: <hex>     (the checksum of the rest of the file)

import scipy.signal as signal           (the imports the functions use, if any)

CUFLYNX_OPERATIONS = ["peak_count", "half_mean"]     (the functions, in order)


@series_to_constant
def half_mean(x, series_output=False):
    ...

The decorators are imported, never defined, so libcuflynx registers only the functions below them (param_id.external_funcs.register_funcs_from_file keeps the callables whose module is the file). :func:read_funcs_file reads such a file back: its functions (each with its decorators) in order, and the imports beyond the header's.

The checksum line is a comment, so Python and any reader of the functions ignore it. It is the sha256 of the file without that line: while it matches (:func:is_unedited), the file is exactly what a writer generated and can be generated again without losing anything. A file holds only the header, imports and functions: :func:unkept_statements lists what a rewrite would drop (constants, classes), so a writer can refuse instead.

funcs_file_source

funcs_file_source(kind, sources, imports=())

The text of a kind (operation, cost, modifier) functions file, with its checksum line after the header.

Parameters:

Name Type Description Default
sources

{name: source}, each one top-level def with its decorators, in order.

required
imports

import statements the functions use, beyond the header's.

()

write_funcs_file

write_funcs_file(path, kind, sources, imports=())

Write :func:funcs_file_source to path (only when its text changes). Returns path.

read_funcs_file

read_funcs_file(path, kind)

(sources, imports) of a functions file in this layout: {name: source} of its top-level functions (with their decorators) in the listed order, and the top-level import statements beyond the header's. None when the file has no kind list marker.

is_unedited

is_unedited(text)

True when text (a functions file's content) is as a writer generated it: it records a checksum and the rest of it still has that checksum.

unkept_statements

unkept_statements(path, kind)

The top-level statements of the functions file path that :func:read_funcs_file does not return, so a rewrite from what it returns would drop them: everything but the header (its docstring, imports and mb), the list marker, imports and def functions. Each as "<first line> (line N)".