Parameter Identification
The parameter identification part of Circulatory_Autogen is designed to allow calibration of a model to experimental or clinical data. It implements an optimisation method to find the best fit parameters that give a minimal (local minima) error difference between the model output and the ground truth observables (experimental or clinical data or user specified). The creation of below two configuration files is necessary:
- params_for_id
- param id observables
Those files should be added to the [CA_dir]/resources directory (or your custom resources_dir). Proper names of the files are [file_prefix]_params_for_id.json and [file_prefix]_obs_data.json, respectively. You can also set params_for_id_file in user_inputs.yaml if you want to use a non-standard filename.
Prerequisites
- A generated model (see Model Generation and Simulation).
param_id_obs_pathandparams_for_idfiles in your resources directory.- A Python environment with libcuflynx installed, and the
mpiextra if running in parallel.
Creating params_for_id file
This file defines which parameters (constants and initial_states) within your model that you will vary in the parameter id process and their allowed ranges (prior distribution). It is JSON, a flat list of entries, one per calibrated value:
{
"version": 1,
"params": [
{"targets": ["global/q_lv_init"], "min": 200e-6, "max": 1500e-6, "param_type": "const", "name_for_plotting": "q_{sbv}"},
{"targets": ["aortic_root/C"], "min": 1e-9, "max": 5e-8, "param_type": "const", "name_for_plotting": "C_{ao}"},
{"targets": ["heart/lv/E_A", "heart/rv/E_A"], "min": 1e8, "max": 5e8, "name_for_plotting": "E_A"},
{"name": "R_scale", "modifies": ["venous_svc/R", "venous_ivc/R"], "modifier": "scale", "min": 0.5, "max": 2.0}
]
}
The keys of an entry:
- targets: the model parameters this calibrated value sets, all to the same value, named as in the
[file_prefix]_parameters.jsonfile:<vessel>/<variable>(aortic_root/C), a nested vessel by its path (heart/lv/E_A, a supermodule instance's submodule) and a global constant asglobal/<variable>. - modifies, modifier, inputs (instead of targets): a modifier entry, whose calibrated value acts on the parameters it lists through a modifier function (
scale,remainder, or your own, seemodifier_funcs_external_path). - theta (a modifier entry only): the value the entry starts at in a calibration and is analysed about in a local sensitivity analysis. By default it is the one that leaves the modified parameters at their values in the model (1 for
scale). - name: the entry's name, unique in the file; by default its first target.
- min, max: the range of possible values (the uniform prior's bounds, the optimiser's search box).
- param_type: "state" or "const"; whether the parameter is the initial value of a state or a const.
- name_for_plotting: the name (latex format) used in plots.
- prior, prior_params, unbounded, comment: see below.
The file is flat, not nested by instance like the parameters file, because an entry is not one parameter: it groups parameters or modifies them. An optional "defaults" object gives keys every entry takes unless it sets its own.
Note
param_type will be deprecated. All should be "const". Initial values that need to identified should be defined as constants within the cellml module.
A params_for_id CSV (vessel_name,param_name,min,max,..., the older form) is refused. Convert it once with
cuflynx-upgrade params-for-id <params_for_id CSV | directory>...
which writes the .json beside each CSV and removes the CSV: each row becomes one entry, vessel_name "a b" with param_name "C" becomes "targets": ["a/C", "b/C"] (a nested heart__lv as its path, heart/lv/C), and the prior_* columns go under "prior_params". Name the .json wherever the CSV was named (params_for_id_file, a workflow step's params_for_id).
Priors
Without further keys every parameter has a uniform prior on [min, max]. An optional
prior chooses another, with its settings in prior_params:
prior |
prior_params |
Notes |
|---|---|---|
uniform (default) |
— | flat on [min, max] |
normal |
prior_mean, prior_std |
default mean: the middle of the range; default std: a sixth of it |
exponential |
prior_scale (or prior_lambda), prior_origin |
decays from prior_origin; scale defaults to max / prior_lambda |
Each prior is truncated to [min, max] unless unbounded is true, in which case
the range is derived from the prior. Priors shape the log posterior, so they affect MCMC (do_uq)
and optimisers run with objective_function: likelihood (the genetic algorithm); a calibration
that minimises the cost does not see them. A calibration workflow can also give a step a prior
over several parameters at once, from an earlier step's posterior (see
Calibration workflows).
Schemas
Every input file has a JSON Schema shipped in libcuflynx/schemas/ (params_for_id.schema.json,
obs_data.schema.json, parameters.schema.json, module_config.schema.json,
module_array.schema.json; load one with libcuflynx.schemas.load_schema), describing each key
and its default. libcuflynx checks every file against its schema when it reads it, so editors and
other tools validating against the schema agree with libcuflynx. An error lists every problem,
each with where it is (an item by its name, e.g. data_items[2] ('systolic').value) and what the
field is for.
Creating param id observables file
This file defines the simulation protocol (protocol_info), and ground truth observables that will be used in the cost function for the parameter id optimisation algorithm. It also defines the measurement standard deviation, and weighting for each observable.
Every obs_data is a JSON object with a protocol_info that has pre_times and sim_times. A bare list of data items, or an object without protocol_info, is refused; convert it once with cuflynx-upgrade obs-data [file] --user-inputs [user_inputs.yaml], which writes a one-experiment protocol_info from that yaml's pre_time and sim_time.
File path of the obs_data.json file should be defined as param_id_obs_path in [CA_dir]/user_run_files/user_inputs.yaml. This path can be absolute or relative to the location of your user_inputs.yaml.
Note
IMPORTANT: For creating obs_data.json files in python (strongly recommended over modifying the json by hand
you can use the helper class libcuflynx.utilities.obs_data_helpers.ObsDataCreator. See
libcuflynx/scripts/example_format_obs_data_json_file.py (in a checkout,
src/libcuflynx/scripts/example_format_obs_data_json_file.py) for an example
that you can copy and change for your parameter identification task.
protocol info
The protocol info defines the numerical experiments you will be running. Here is an example for a sympathetic neuron calibration where the input current is changed from 0 to 0.15 pA after 1 second then simulated for 2 seconds with that input current. This was performed in two experiments, the first experiment with a M-type potassium conductance of 0.08 uS and the second experiment with an increased M-type potassium channel conductance of 0.12 uS.

For the protocol we define each experiment as each new full simulation that needs to be run. Each subexperiment is a section of an experiment with its own set of parameters. Subexperiments generally relate to different time periods where the inputs in the experiments that are being used for calibration have a change in value (e.g. change in drug concentration, change in stimulatiion frequency, change in applied force). The entries in the protocol info are:
- pre_times: The amount of simulation that is done before you want to compare to observables or plot (this part of the simulation is thrown away. This is mainly used to simulate for an amout of time to reach steady state or periodic state. shape = (number of experiments)
- offline_pre_time (optional): A single scalar, in seconds. Before any experiment runs, the solver performs one unlogged warmup integration for this duration, then stores the end state as the default state used when
reset_states()is called at the start of each experiment. Use this to separate a long steady-state or periodic warmup from the logged pre_times phase. Calibration runs it once, before the first evaluation, and every evaluation starts from its end state. Supported by theCVODE_myokit,CVODE_libopencor,casadi_python,python(solve_ivp) andaadc_pythonbackends; an emulator ignores it (its training already covered the warmup) and anexternal_pythonmodel raises, because itsrun()always starts from the initial condition. A traced input (protocol_traces/protocol_shapes) is held at its value at the start of experiment 0 during this warmup. It cannot be combined with a calibration parameter that sets a state's initial value: the frozen state would not move with that parameter, so the run stops withOFFLINE_PRE_TIME_INIT_STATE_ERROR(reformulate in terms of a constant parameter, e.g. total volume rather than initial LV volume). Example:offline_pre_time: 19.0withpre_times: [1.0]gives 20 s of total warmup before the first logged segment, equivalent topre_times: [20.0]withoutoffline_pre_time. - sim_times: The length in time of each subexperiment. shape=(number of experiments, number of subexperiments) -- Note: the shape isn't completely correct here, the number of subexperiments can be different for each experiment
- params_to_change: A dictionary where the key is a parameter name and the entry is the assigned value of that parameter in each (experiment_idx, subexperiment_idx).
- params_to_change_factors (optional, calibration workflow steps only): The same shape as
params_to_change, each entry a number that multiplies the value the step's model gives that parameter -- see Protocol factors. - experiment_colors: The line color for the plots of each experiment.
- experiment_labels: The label for each experiment, which is used for plotting and naming plots.
- protocol_traces (optional): Named
{"t": [...], "values": [...]}waveforms. Aparams_to_changeentry may be the name of one instead of a number, and the parameter then follows that waveform over the subexperiment rather than being held constant. - protocol_shapes (optional): The same thing written as events rather than as a table of points --
see below. A name is defined in
protocol_tracesor inprotocol_shapes, whichever suits; both are referred to fromparams_to_changethe same way.
Time-varying inputs: protocol_shapes
A stimulus is easier to write as "1 unit, 2 ms long, every 1000 ms" than as the forty numbers that
describes. protocol_shapes takes the first form, using the same five fields as a Myokit .mmt
[[protocol]] table, so a protocol imported from Myokit needs no translation:
# .mmt # obs_data.json
# Level Start Length Period Mult "protocol_shapes": {
1.0 100 2 1000 0 "stim": {"events": [{"level": 1.0, "start": 100,
"length": 2, "period": 1000,
"multiplier": 0}]}
},
"params_to_change": {"membrane/stim": [["stim"]]}
- level — the value the parameter takes during the event; outside every event it takes baseline
(default
0). - start, length — when the event begins and how long it lasts.
durationis accepted as a synonym forlength(it is what Myokit's Python API calls it). - period — how often it repeats;
0means it happens once. - multiplier — how many times it repeats;
0means "for as long as the subexperiment runs", so the number of beats followssim_timesrather than having to be counted out by hand.
A shape is expanded over the subexperiment that refers to it, so its length comes from sim_times. Give
the shape its own duration if you want to override that, which is also how a shape shared between
subexperiments of different lengths is disambiguated. Overlapping events are rejected, as they are in
Myokit, and so is a stimulus that never fires inside the time it is run over.
A step and a single pulse are just pacing events that do not repeat: a step is {"level": v, "start": ts,
"length": <rest of the subexperiment>, "period": 0} over a baseline, and a pulse is the same with a
shorter length. A linear sweep is not a square event, so it has its own type:
"protocol_shapes": { "load": {"type": "ramp", "from": 0.0, "to": 5.0} }
which runs from from at the start of the subexperiment to to at its end.
The expansion happens when the file is read, so everything downstream -- the solvers, the plots -- sees an
ordinary protocol_traces entry and behaves exactly as it would have if you had written the points out.
data items
Examples of obs_data.json, data_item entries are shown in below figures for constant, constant with operation_kwargs, series, and frequency data types, respectively.

The entries in the data_item list in the obs_data.json file are:
- data_item_name: The user defined name of this observable. It does not need to link to a
cellml variable name, but it must be unique across every
data_itemandprediction_itemin the file: it is the item's identity, and the name an operation_kwargs reference to another item resolves against. Replaces the old variable entry, which also stood in as the operand — the model variable now always goes in operands. - data_type: The format of the data. This can be "constant", "series", or "frequency" as shown above.
- unit: The unit of the observable.
- trace_name_for_plotting: The axis label for the trace this item is drawn from, in latex format. May repeat: the mean and the max of one variable are two features of one series, so they share it. Defaults to the first operand.
- item_name_for_plotting: The label for the item — the scalar feature itself — used in
sensitivity tables and error reports. Defaults to
"<trace_name_for_plotting> (<operation>)". - weight: The weighting to put on this observables entry in the cost function. Default should be 1.0
- std: The standard deviation which is used in the cost function. The cost function is the relative absolute error (AE) or mean squared error (MRE), each normalised by the std.
- value: The value of the ground truth, either a scalar for constant data_type, or a list of values for series or frequency data_types.
- obs_dt: required for series data types and not needed for constant or frequency. It defines the timestep for the observable series values.
- prob_dist_params: the ground truth when it is a distribution rather than a value — see below. An item that sets this needs no value or std; an item that does not, needs both.
- data_reference (optional): where the data come from, as a string — a citation key, DOI
or table reference, as in the
data_referencecolumn of a parameters file.sourcehas been replaced by this key: an item'ssourceis read as itsdata_reference, which wins if the item has both, with one warning per file giving the number of items. libcuflynx never requires it, and refuses a value that is not a string. It is saved beside the error vectors (error_vec_data_references.npy, in the order oferror_vec_names.npy,""where an item has none), shown as aData: ...line at the top of the item's reconstruction plot and on anyprediction_plotsfigure that draws its data, and listed under Sources in the methods text, where a word that is a BibTeX key becomes\cite{key}as in a parameter'sdata_reference. Each item names its own source: there is no file-level default, so items from one paper each carry its key. A module library may require it in its own checks.
Every item is either a scalar or a series, never both. The same rule applies to
prediction_items, and the parser checks it, naming the item:
data_type: constant: value and std are single numbers.data_type: series: value is a list; std is a number or a list of the same length; obs_dt is required. Sample k is atk * obs_dtfrom the start of the item's sub-experiment.frequencykeeps its own rules.
A series may still have an operation, as long as it returns a series. Examples are
addition of two traces, or an operation with series_output.
Ground truth as a distribution (prob_dist_params)
Some observables are not known as a single number plus a standard deviation. A measurement repeated across a cohort is a set of points, and it may not even be unimodal. For these, state the ground truth as prob_dist_params and choose a cost_type that scores against a distribution:
| cost_type | prob_dist_params |
scores the output against |
|---|---|---|
kernel_density_estimation |
{"data_points": [...]} |
a smooth density fitted to the measured points, with no assumption about how many modes there are |
multimodal_gaussian |
{"means": [...], "stds": [...], "scales": [...]} |
a named mixture of gaussians (scales must sum to 1) |
poisson_MLE |
{"k": <count>} |
a Poisson likelihood, where the model output is the rate |
The observable itself is still an ordinary constant: the model produces one scalar, exactly as for gaussian_MLE. Only what it is compared against differs, and that follows from cost_type.
{
"data_item_name": "x_steady_state",
"data_type": "constant",
"operation": "steady_state_avg",
"operands": ["benchmark/x"],
"unit": "dimensionless",
"weight": 1.0,
"cost_type": "kernel_density_estimation",
"prob_dist_params": {"data_points": [1.05, 0.99, 4.08, 3.96, "..."]},
"cost_kwargs": {"bandwidth": 0.1}
}
Anything that tunes the comparison rather than stating the data goes in cost_kwargs — for kernel_density_estimation that is bandwidth, the KDE smoothing width (a number, "scott" or "silverman"; Scott's rule by default), which you can change without touching the measurements.
Series ground truth from .npy files (t_path and value_path)
For large time-series observables you can store arrays in NumPy files instead of embedding long lists in the JSON. On load, Circulatory Autogen reads the files and fills in any missing value and obs_dt fields before calibration runs. You must still set std in the JSON (see below).
- t_path: Path to a
.npyfile containing the time vector (seconds). - value_path: Path to a
.npyfile containing the observable values. This is always the quantity that will be compared to the model .
Paths may be absolute or relative to the process working directory when parameter identification is started. If value is already present in the JSON, the file path should not be set;
Example data_item entry:
{
"data_item_name": "P aortic root",
"data_type": "series",
"operands": ["aortic_root/u"],
"operation": null,
"unit": "Pa",
"weight": 1.0,
"std": 500.0,
"t_path": "/path/to/pressure_time.npy",
"value_path": "/path/to/pressure_values.npy",
"experiment_idx": 0,
"subexperiment_idx": 0
}
If obs_dt is omitted, it is estimated from the mean step in t_path. For std, provide either one positive number (applied to every sample in the series) or a list with one entry per sample (same length as value after load).
Warning
The dt or sample_rate fields are deprecated for series data. Use obs_dt instead.
Not to be confused with the dt for the model simulation outputs.
- operation: This defines the operation that will be done on the operands/variable. The possible operations to be done on model outputs are the built-ins in libcuflynx.param_id.operation_funcs and libcuflynx.funcs.operation_funcs_user, plus any user defined operations in the file named by operation_funcs_external_path in user_inputs.yaml (copy funcs_user/operation_funcs_example.py to start). Since the built-in funcs moved into the package, editing them in place is no longer supported — an upgrade replaces them.
- operation_kwargs: An optional dictionary of keyword arguments (kwargs) and their values, passed to the chosen python operation function on top of the operands. Defaults to {}. See operation_kwargs below for the full contract.
- operands: The model variables the "operation" is applied to — always required, and always
the place the model variable is named. ("operation" may take several.) An item built purely
from other items' values, rather than from a trace, states [""].
- experiment_idx and subexperiment_idx: Optional indices to link a data item to a specific experiment/subexperiment in protocol_info.
operation_kwargs
operation_kwargs is an optional, per-data_item dictionary of keyword arguments for that item's
operation func. It is a supported public field of obs_data.json (it is what the
CUFLynx editor writes when you tune an operation's
options in the GUI), and it behaves identically in calibration, MCMC/UQ and sensitivity analysis.
At run time Circulatory Autogen calls:
operation(*operands, **operation_kwargs)
so the operands fill the operation func's leading positional arguments and operation_kwargs
fills its keyword arguments. For example, with the user operation
@series_to_constant
def mean_in_range(x, start_frac=0.0, end_frac=1.0, series_output=False):
...
a data_item can ask for the mean over the last 20% of the sub-experiment:
{
"data_item_name": "mean late P aortic root",
"trace_name_for_plotting": "u_{ARlate}",
"data_type": "constant",
"operation": "mean_in_range",
"operands": ["aortic_root/u"],
"operation_kwargs": { "start_frac": 0.8, "end_frac": 1.0 },
"unit": "J_per_m3",
"weight": 1.0,
"value": 12000,
"std": 1200
}
The rules are:
- Optional, default
{}. Omittingoperation_kwargs(or leaving it empty/null) calls the operation func with its own defaults, exactly as before. - Keys must be keyword arguments of the operation func. An unknown or misspelled key is an
error, not silently ignored -- otherwise a stale obs_data file would quietly calibrate against
a different feature than you asked for. The error names the data item, the operation func, the
offending key and the accepted keys, and it is raised as soon as the observation data is set,
before any simulation runs. A func that declares
**kwargs(likecalculate_two_observable_difference) accepts any key. - Keys already filled from
operandsare rejected. Ifoperandssupplies the operation's first argumentx, you cannot also pass"x"inoperation_kwargs. series_outputis reserved. Circulatory Autogen sets it itself when it needs the trace for plotting, so adata_itemmust not set it.- String values can reference an earlier observable. A string value that matches the
data_item_nameof an earlierdata_itemis replaced, at run time, by that observable's computed value. This is how an observable is built from other observables -- seecalculate_two_observable_differenceinlibcuflynx/funcs/operation_funcs_user.pyandresources/3compartment_extra_ops_obs_data.json. A string that matches no earlier observable is passed through unchanged, so plain string options still work. Note that the referenced item must appear earlier indata_itemsthan the item that references it. - Type coercion is minimal. JSON has a single number type, so a value written as
20.0where the func's default is the integer20is converted toint, and an integer written where the default is a float is converted tofloat. Nothing else is coerced: strings, booleans, lists andnullreach the operation func as-is.
User-defined operation funcs receive operation_kwargs exactly like the built-ins. This includes
the operations libcuflynx ships in libcuflynx/funcs/operation_funcs_user.py, funcs in a file
pointed to by operation_funcs_external_path in user_inputs.yaml, and funcs registered from
python with
add_user_operation_func().
When building obs data in python rather than as a file, pass the same field through
ObsDataCreator.add_data_item({... , "operation_kwargs": {...}}).
Building an observable from other observables
Sometimes the quantity you want to fit is not something the model reports directly, but a combination of quantities it does. If you have a ground truth for the mean flow and another for the peak flow, what you actually know may be the difference between them -- the pulse amplitude -- and that difference is what you want the cost to see.
An observable can therefore be computed from observables defined earlier in data_items, using
the string-reference rule described above: a string in operation_kwargs that matches an earlier
item's data_item_name is replaced by that item's computed value.
libcuflynx ships calculate_two_observable_difference for the two-term
case. It takes its inputs as pred1 and pred2 and returns pred2 - pred1:
{
"data_item_name": "mean flow aortic root",
"trace_name_for_plotting": "v_{AR}",
"data_type": "constant",
"operation": "mean",
"operands": ["aortic_root/v"],
"unit": "m3_per_s", "weight": 1.0, "value": 0.0001, "std": 1e-05
},
{
"data_item_name": "max flow aortic root",
"trace_name_for_plotting": "v_{AR}",
"data_type": "constant",
"operation": "max",
"operands": ["aortic_root/v"],
"unit": "m3_per_s", "weight": 1.0, "value": 0.0005, "std": 5e-05
},
{
"data_item_name": "aortic root flow, max minus mean",
"trace_name_for_plotting": "v_{ARdelta}",
"data_type": "constant",
"operation": "calculate_two_observable_difference",
"operands": [""],
"operation_kwargs": { "pred1": "mean flow aortic root", "pred2": "max flow aortic root" },
"unit": "m3_per_s", "weight": 1.0, "value": 0.0004, "std": 5e-05
}
resources/3compartment_extra_ops_obs_data.json is this example as a complete, working file.
Three things to get right:
- Order matters. An observable can only reference items that appear before it in
data_items, because the values are computed in file order and the reference is resolved against the ones already computed. A reference to an item that has not been computed yet is an error naming the item to move, rather than the operation quietly receiving the name as a string. -
A reference may cross experiments and sub-experiments. The referenced item does not have to be in the same
experiment_idx/subexperiment_idxas the item referencing it, so the quantity you actually know — how much a treatment moved a feature, the difference between a baseline run and a forced one — can be written down directly:{ "data_item_name": "peak prey, unforced", "operation": "max", "operands": ["Lotka_Volterra_module/x"], "experiment_idx": 0, "data_type": "constant", "unit": "dimensionless", "value": 23.62, "std": 0.5 }, { "data_item_name": "peak prey, forced", "operation": "max", "operands": ["Lotka_Volterra_module/x"], "experiment_idx": 1, "data_type": "constant", "unit": "dimensionless", "value": 21.58, "std": 0.5 }, { "data_item_name": "peak prey, forcing response", "operation": "calculate_two_observable_difference", "operands": [""], "operation_kwargs": { "pred1": "peak prey, unforced", "pred2": "peak prey, forced" }, "experiment_idx": 1, "data_type": "constant", "unit": "dimensionless", "value": -2.04, "std": 0.5 }Ordering still applies, and now spans segments: experiments are evaluated in order, and the sub-experiments within each, so an item may reference anything in an earlier segment.
tests/test_inputs/Lotka_Volterra_forced_cross_exp_obs_data.jsonis the worked example.One limit: the Myokit CVODES FSA and CasADi AD gradients cannot differentiate a cross-segment reference, because each builds its observables from one sub-experiment's operands. They refuse with a message rather than return a gradient for a different feature than the cost. Use finite differences (
do_ad: False) or a gradient-free method, or keep the reference inside one sub-experiment. -operandsis empty, written[""]. The item takes its inputs fromoperation_kwargsrather than from a model variable, so there is no trace to reduce. -data_item_nameis what the reference resolves against, and it must be unique. This is now enforced: a repeateddata_item_nameis rejected when the obs_data is loaded, naming the offenders. Note the two source items above deliberately share atrace_name_for_plotting(v_{AR}) — they are the mean and the max of one trace — and differ only indata_item_name. Before this was split in two, both saidv_{AR}for everything, the reference resolved to whichever was computed last, and the example silently computedmax - max = 0. A name that matches nothing is still passed through to the operation func as a plain string, so a typo shows up as a strange result rather than a failure.
To combine more than two observables, or to combine them some other way, write your own operation
func in a file named by operation_funcs_external_path (see
Creating your own operations) and name it in operation. It
receives the referenced values as keyword arguments, so it needs to accept them -- either by
declaring them explicitly or with **kwargs. @series_to_constant marks it as returning a
single number rather than a trace:
@series_to_constant
def combine_three_observables(x=None, series_output=False, **kwargs):
return kwargs["pred3"] - kwargs["pred2"] - kwargs["pred1"]
and the data_item names it in operation with one operation_kwargs entry per input:
"operation": "combine_three_observables",
"operands": [""],
"operation_kwargs": { "pred1": "v_{ARmean}", "pred2": "v_{ARmax}", "pred3": "v_{ARmin}" }
Note
Older versions could fail with TypeError: operation_funcs.mean() argument after ** must be a
mapping, not float when a data_item had no operation_kwargs. This is fixed: every place
that forwards operation_kwargs now goes through
param_id.operation_funcs.resolve_operation_kwargs, which treats a missing/null/NaN value as
"no kwargs" and raises a descriptive ValueError (naming the data item, the operation and the
accepted keys) for a key the operation func does not accept.
prediction items (optional)
You can include a prediction_items list in obs_data.json to request additional model outputs to plot (not used in the cost function). They take the same vocabulary as a data_item:
- data_item_name: This item's identity, unique across every
data_itemandprediction_itemin the file. - operands: The model variable to record, as a list — e.g.
["heart/u_lv"]. This is what the old variable entry named; it no longer doubles as the item's name. - unit: The unit of the recorded variable.
- experiment_idx (optional; defaults to 0)
- subexperiment_idx (optional): the sub-experiment of
experiment_idxwhose run the item is recorded over. Defaults to that experiment's last sub-experiment, and must exist. - trace_name_for_plotting (optional): The axis label, in latex format. Defaults to the first operand.
- item_name_for_plotting (optional): The item's own label. Defaults to
"<trace_name_for_plotting> (<operation>)". - operation and operation_kwargs (optional): the same operations and the same
operation_kwargschecks as adata_item. On a scalar item the operation reduces the operands to one number. On a series item it returns a series, exactly as for a data_item. See Prediction items as scalar features.
Validation data in prediction items
A prediction item can also carry held-out data: measurements the calibration does not fit, which the calibrated model is then checked against. Give the item:
- value: the data, a number (
data_type: constant) or a list (data_type: series) - data_type:
constantorseries - std (optional): its standard deviation. For a constant this is one number. For a series it is one number for every point, or a list with one per point. Every entry must be greater than 0. Without it, the item is scored by RMSE alone.
- obs_dt: the spacing of a series' samples. They start at the start of the item's sub-experiment, as a data_item series does. With one sub-experiment, that is the start of the experiment.
- data_reference (optional): where the held-out data come from, as for a data_item. It is
written with the item's scores in
validation_results.json.
For example, fit the first 15 years of a series and validate the prediction to year 20, in one file with one experiment that runs to 20:
"prediction_items": [
{"data_item_name": "x_validation", "operands": ["mod/x"], "unit": "dimensionless",
"data_type": "series", "value": [30.0, 47.2, "..."], "std": [7.5, 11.8, "..."], "obs_dt": 1.0}
]
After a calibration, saving the prediction data (plot_param_id) also writes
validation_results.json in the output directory: for each item with data, the RMSE, the RMSE
over the data's range, the mean |model - data|/std and the fraction within 2 std, with the
model and data at the observation times. A series is compared at the times the simulation
reaches. A constant is compared with the model's value at the end of its sub-experiment. An
item with an operation is compared with the operation's result: a scalar for a constant, or
the operation's series (series_output for a @series_to_constant operation) for a series.
Each result item also names its operation (null for an item without one). The traces are
saved as prediction_variable_data_exp_<k>.npy, as before. An item that sets a
subexperiment_idx other than its experiment's last is saved in
prediction_variable_data_exp_<e>_sub_<s>.npy instead. Its rows are the time from the start of
the sub-experiment, then each item's first operand.
Experiments used only for validation
An experiment in protocol_info that no data_item belongs to is not part of the cost. The
calibration does not simulate it: not in any cost evaluation, nor in the best-fit check and the
plots. The run prints one line naming such experiments as prediction/validation only. They
are simulated after calibration, for the prediction data and validation_results.json.
SA and emulator training simulate them only when include_prediction_items needs a feature
measured there. When every experiment has a data_item, nothing changes.
Example: experiment 0 is fitted. Experiment 1 has a different sim_time and a different
params_to_change, and holds only held-out prediction items:
{
"protocol_info": {
"pre_times": [0.0, 0.0],
"sim_times": [[8.0], [3.0]],
"params_to_change": {"benchmark/x_init": [[0.0], [2.0]]}
},
"data_items": [
{"data_item_name": "x_ss", "operands": ["benchmark/x"], "data_type": "constant",
"operation": "steady_state_avg", "unit": "dimensionless", "value": 1.0, "std": 0.1,
"experiment_idx": 0}
],
"prediction_items": [
{"data_item_name": "x_recovery", "operands": ["benchmark/x"], "unit": "dimensionless",
"experiment_idx": 1, "data_type": "series", "value": [2.0, 1.61, 1.37, 1.22, 1.14, 1.08, 1.05],
"std": 0.05, "obs_dt": 0.5},
{"data_item_name": "x_recovery_mean", "operands": ["benchmark/x"], "unit": "dimensionless",
"experiment_idx": 1, "operation": "mean", "data_type": "constant", "value": 1.3, "std": 0.1}
]
}
Prediction items as scalar features
A prediction item with an operation is a scalar feature of the prediction, e.g. the maximum of a pressure over an experiment. It is still not part of the cost. It changes three things:
- Validation. Its held-out
value(data_type: constant) is compared withoperation(operands)over the recorded run rather than with the value at the end of the experiment. Every operand is recorded, so a two-operand operation works. - Sensitivity analysis. With
sa_options.include_prediction_items: trueit is an extra SA output. See Sensitivity analysis. - Emulators. With
emulator_settings.include_prediction_items: truethe emulator is also trained on it. See Emulators.
"prediction_items": [
{"data_item_name": "p_max_validation", "operands": ["aortic_root/u"], "unit": "J_per_m3",
"operation": "max", "data_type": "constant", "value": 16000.0, "std": 800.0}
]
Only a scalar prediction item with an operation becomes a feature. That means
data_type: constant, or no data at all and an operation that reduces a trace to a number
(max, min, mean and the other @series_to_constant ones). Items without an operation,
and series items with or without one, are not features. SA and emulator training skip them,
with a warning that names them. If a feature's operation returns more than one number, the run
stops with an error naming the item. An item's operation_kwargs may refer to an earlier
prediction item by its data_item_name, but not to a data_item. The operation is applied
over the item's (experiment_idx, subexperiment_idx) segment, which by default is the
experiment's last sub-experiment. That is the same segment the prediction data records and
the validation uses.
Plots across experiments (prediction_plots)
A family of experiments is often read as one picture: peak current against step potential
(I–V), a feature against a dose, a clamp protocol beside the current it drives. The optional
top-level prediction_plots list draws one figure per entry. There are four kinds.
Feature kinds: one point per experiment.
"prediction_plots": [
{"name": "Peak I_Na vs step potential", "kind": "feature_vs_input",
"x": {"params_to_change": "clamp/V_cmd", "subexperiment_idx": 1}, "y": "I_peak",
"series": null},
{"name": "Peak I_Na vs mean step", "kind": "feature_vs_feature", "x": "V_step", "y": "I_peak"}
]
- A group is the data_items and prediction_items that share an
item_name_for_plotting(written, or its default). A group has at most one item per experiment, and each item is a scalar feature. - A point is one experiment: y is the
ygroup's item for it; x is thexgroup's item for the same experiment (feature_vs_feature) or the valueparams_to_change[key]takes in that sub-experiment (feature_vs_input). series(an input reference, optional) draws one line per value of that input. Points are sorted by x; an item'svalue/stdis drawn as error bars.- An input reference is
{"params_to_change": <key>, "subexperiment_idx": <i>}with an optional"reduce". A number is used as it is. A trace (aprotocol_tracesorprotocol_shapesname) needsreduceto become one number:"final","mean","max","min", or{"at": <seconds from the start of that sub-experiment>}. These are taken over the trace as the sub-experiment applies it (linear between its points, held past its ends, cut at the end of the sub-experiment). An experiment whose input is a trace with noreducehas no point: it is left out with a warning that names it.
{"name": "Peak I vs ramp end", "kind": "feature_vs_input", "y": "I_peak",
"x": {"params_to_change": "clamp/V_cmd", "subexperiment_idx": 1, "reduce": "final"}}
Time-course kinds: an input and a model output over time.
"prediction_plots": [
{"name": "Clamp and current", "kind": "input_and_output",
"input": {"params_to_change": "clamp/V_cmd"}, "output": "cell/membrane/I_Na",
"experiments": [0, 2]},
{"name": "I-V loop", "kind": "output_vs_input",
"input": {"params_to_change": "clamp/V_cmd"}, "output": "cell/membrane/I_Na"}
]
input_and_outputdraws one figure per experiment,<name>_exp_<idx>.png. The input is on the left y-axis and the model output on the right, against the time since the end of the warm-up. Sub-experiment boundaries are dashed. A data_item that has the output as a series (its first operand, no operation) in that experiment is overlaid.output_vs_inputdraws the output against the input sampled at the same times, one line per experiment (for example an I–V loop under a voltage ramp), in<name>.png.inputis aparams_to_changekey. Across the experiment, a number is drawn as a step and a trace as its waveform.outputis written as an obs_data operand is:<vessel>/<variable>, a nested vessel by its path (SN/soma/membrane/V), or a global's bare name. It is recorded the way prediction items are, in a simulation of those experiments (at the best fit, after a calibration), so any model variable can be drawn. An output the model does not have is refused before anything runs.experiments(optional) lists the experiments to draw. The default is all of them.
The structure is checked when the obs_data is read: a params_to_change key the protocol does
not set, a subexperiment_idx or experiment out of range, a malformed reduce, an at after
the end of its sub-experiment, and the wrong keys for a kind are refused. A feature group that
misses an experiment the other group has is an error, not a gap. save_prediction_data draws
the figures in the output directory after a calibration, with a data_item's model value from
the cost path. cuflynx-run-predictions draws them without a calibration; a data_item point
there shows its data only.
Running external cellml models
Running cellml models that weren't generated with Circulatory_Autogen is also just as straightforward:
Simply set the file_prefix in your user_inputs.yaml file to the name of your cellml model <file_prefix>.cellml. Then set generated_models_dir to the path to the dir where your model subdir is and the subdir where the calibrated model will be generated. Make sure your cellml file/files are in a directory of the same name i.e.:
path/to/your/generated_models_dir/<file_prefix>/<file_prefix>.cellml
After calibration, the following directory will be created with your generated model:
path/to/your/generated_models_dir/<file_prefix>_<obs_file_name>/
Note
Currently the generated model needs to be run in newer OpenCOR with the LibOpenCOR backend because a CellML 2.0 model is generated.
Creating your own operations
To enable flexibility we allow you to create your own user-defined operation functions in python to extract features from your model outputs and compare to data in the calibration.
The operation functions libcuflynx ships can be found in src/libcuflynx/param_id/operation_funcs.py and src/libcuflynx/funcs/operation_funcs_user.py. Those are library files -- do not edit them, since an upgrade replaces them. Write your own in a file of your own and name it with operation_funcs_external_path in user_inputs.yaml; funcs_user/operation_funcs_example.py is a template to copy.
Here is an example of an operation function for calculating the ratio of the two peaks (used for mitral valve flow).

Note:
- kwargs can be used and defined for each entry in your obs_data.json with
operation_kwargs, see above. if series_outputis needed to return the variable trace for plotting.- A more elegant method of returning a high cost if the observable can't be calculated is being discussed.
Creating your own cost functions
To allow even more flexibility, we also allow users to define their own cost functions (or likelihood functions). The ones libcuflynx ships are at src/libcuflynx/funcs/cost_funcs_user.py -- a library file, so do not edit it. Write your own in a file of your own and name it with cost_funcs_external_path in user_inputs.yaml; funcs_user/cost_funcs_example.py is a template to copy.
An example for the maximum likelihood estimator for gaussian noise (equivalent to weighted mean squared error) is:

Note:
- Currently there are no kwargs for user defined cost functions. But there will be: see issue
Solver
Before doing calibration, a solver for the model needs to be chosen
- model_type defaults to
cellml. A config that names a solver but no model_type takes that solver's model_type, sosolver: casadi_integratoralone is acasadi_pythonrun. - solver defines the solver family. Options depend on
model_type:- CellML (
model_type: cellml):CVODE_myokit(Myokit, the default) orCVODE_libopencor(libOpenCOR: thelibopencorextra, Python 3.12 or later; no protocol traces or FSA gradients).CVODEis read asCVODE_myokit. The batched solversBE_batched_candCVODES_batched_calso take CellML models; see Choosing a batched solver below. - Python (
model_type: python):solve_ivpwithsolver_info.methodset toRK45,BDF, etc. - CasADi Python (
model_type: casadi_python):casadi_integratorwithsolver_info.methodset tocvodes(the default),idas,collocation,rk,semi_implicit_euler, orbdf.cvodesandidasintegrate each run as one solve over the output times, pass the model the true time, and can drive a constant from aprotocol_tracestrace asCVODE_myokitdoes.jit(on by default) compiles the model to C (see below). - C++ (
model_type: cpp):CVODE, or the fixed-stepRK4,Heun,midpointorexplEul.
- CellML (
- solver_info defines settings for the chosen solver:
- dt_solver: the step of the fixed-step and C++ solvers; sets
max_step_sizeforcasadi_integratorandmax_stepforsolve_ivpwhen those are not given. The CellML (variable-step) solvers do not read it: giving it with a differentMaximumStepis an error, and giving it withoutMaximumStepwarns that the step is unbounded - MaximumStep: maximum step size (
CVODE_myokit,CVODE_libopencor) - MaximumNumberOfSteps: maximum number of substeps before stepping (
CVODE_libopencorand the C++ solvers) - method: any method for
solve_ivporcasadi_integrator, e.g.RK45,BDF,cvodes, etc. - jit (
casadi_integrator, defaulttrue): generate C for the model's right-hand side and its derivatives and compile it, once per process per model, timeline and options. Needs a C compiler (gcc by default): withjitunset and no compiler, the run continues without jit and warns;jit: truewith no compiler is an error;jit: falseturns it off.compiler(shellorclang) andjit_options(e.g.{compiler: clang, flags: ['-O3']}) choose the compiler. It speeds up forward runs; the AD gradient's symbolic graph uses the interpreted integrator, since CasADi 3.7 does not differentiate through a jit-compiled CVODES integrator.
- dt_solver: the step of the fixed-step and C++ solvers; sets
Choosing a batched solver (BE_batched_c, CVODES_batched_c)
CVODE_myokit is the more general-purpose solver, and the one to start with. BE_batched_c and
CVODES_batched_c are good when you have many perturbations through time: inputs that change at
many points in a run (a protocol trace with many breakpoints, or a game that changes an input every
macro step). CVODE has to stop and restart its adaptive time steps at each of those changes, while
the batched solvers integrate the model as independent blocks of states in generated C (one block
per unconnected part, such as each cell of a module array) and restart only the blocks whose inputs
changed. They are opt-in: they run only when you name them in the config, e.g.
solver_info:
solver: BE_batched_c # or CVODES_batched_c
method: trbdf2 # BE_batched_c: backward_euler (default) or trbdf2
They have no sensitivities (no do_ad gradient), and do not take models with algebraic loops or
external variables. BE_batched_c suits moderate tolerances (default rtol 1e-4);
CVODES_batched_c uses CVODE_myokit's tolerances and needs SUNDIALS 6 or later (SUNDIALS_DIR).
The settings of each are listed in src/libcuflynx/solver_wrappers/batched_c_helper.py, and
timings are in benchmarks/README.md (Batched CellML solvers).
Automatic differentiation supports constant and series observables only
With do_ad: true the cost is built symbolically. constant and series data items are
both supported, and dt does not have to equal a series item's obs_dt: the simulated
series is linearly interpolated onto the observation times, which is a multiply by a matrix
of weights fixed by the two time grids, so it stays differentiable. Frequency (amp /
phase) observables cannot be differentiated yet, and raise rather than silently
contributing nothing to the cost.
Gradients: do_ad, Myokit FSA and CasADi AD
With do_ad: true the gradient-based methods take the model's analytic gradient: Myokit
CVODES forward sensitivities (FSA) for cellml on CVODE_myokit, CasADi AD for
casadi_python. On cvodes or idas CasADi AD is computed by CVODES forward sensitivities
(one per calibrated parameter), which match finite differences on the stiff 3compartment
model, warm-up included. (The CVODES adjoint, CasADi's reverse mode, fails there with
CV_TOO_MUCH_WORK, so it is not used.) do_ad: false, the default, uses finite
differences. gradient_sources(model_type, solver) lists the choices for a model and marks
the one to pre-select; default_gradient_source(model_type, solver) returns it.
CasADi semi_implicit_euler — a fixed-step AD method (verify with a convergence study)
semi_implicit_euler differentiates by reverse mode through a fixed-step graph rather than
by CVODES sensitivities. To use it set solver_info.method: semi_implicit_euler. This is a fixed-step,
linearly-implicit (semi-implicit) Euler scheme with diagonal-Jacobian damping:
x_{n+1} = x_n + dt * f(x_n) / (1 - dt * d f_i / d x_i)
The damping term stabilises the stiff modes at the model dt, and because the whole
integrator is built as a single symbolic graph, CasADi differentiates the cost by ordinary
reverse-mode AD, with no ODE solver in the gradient.
model_type: casadi_python
solver_info:
solver: casadi_integrator
method: semi_implicit_euler
max_step_size: 0.001
Less accurate than cvodes — do a convergence study
semi_implicit_euler is a first-order, fixed-step scheme that damps using only
the diagonal of the Jacobian, so it is less accurate than the adaptive cvodes
integrator and, on a stiff model, can noticeably differ from the true (CVODE)
trajectory at a practical dt. It is not the accurate choice.
Do not trust the results at a single dt. Perform a convergence study: rerun
with progressively smaller dt (e.g. halve it) and confirm the trajectories and the
identified parameters stop changing meaningfully before relying on them. cvodes
remains the more accurate default.
CasADi bdf — a fixed-step AD method for stiff models
bdf is a fixed-step, symbolic implicit BDF2 scheme (a rootfinder per step, differentiated
through the implicit-function theorem). Like semi_implicit_euler it is built as a single
symbolic graph, so CasADi produces exact gradients by reverse-mode AD — but it is second
order and full-Jacobian implicit, so it tracks a stiff trajectory far more accurately than
the first-order, diagonally-damped semi_implicit_euler at the same dt. Prefer bdf over
semi_implicit_euler; still do a convergence study in dt.
model_type: casadi_python
solver: casadi_integrator
do_ad: true
solver_info:
method: bdf
max_step_size: 0.001
Myokit CVODES forward sensitivity — AD gradients for cellml models
A cellml model run through the Myokit backend can produce an exact gradient without
converting to casadi_python, using Myokit's native CVODES forward-sensitivity analysis
(FSA). Set model_type: cellml, solver: CVODE_myokit, do_ad: true, and a
gradient-based param_id_method (sp_minimize or multi_start_sp_minimize). FSA integrates
the state and sensitivity equations together with the adaptive stiff CVODES solver, so it
handles stiff dynamics and a long pre_time warmup natively while staying as accurate as
the forward simulation itself.
model_type: cellml
solver: CVODE_myokit
do_ad: true
param_id_method: multi_start_sp_minimize
solver_info:
rtol: 1e-9
atol: 1e-9 # tight tolerances keep the sensitivities out of the integrator noise floor
A parameter that only sets a state's initial value cannot be a CVODES sensitivity
independent; such parameters automatically fall back to finite differences (a one-line warning
reports how many and which). Tighten rtol/atol when using FSA so the sensitivities are well
resolved.
our AADC wrapper is not yet suitable for stiff models or general observables
The AADC tape backend (model_type: aadc_python) records a fixed-step integrator, which is
inaccurate or unstable on stiff models — on the 3compartment cardiovascular model its
fixed-step implicit solve deviates from CVODE by orders of magnitude. Every AADC run now probes
the first second of dynamics and prints a loud warning if the model is stiff, pointing you at
CasADi bdf or Myokit CVODES FSA instead.
AADC puts only some observables on the tape. The operand may be a state or an algebraic variable (a pressure or flow computed from the states, which the tape recomputes from them at each step), and the observable must be one of:
- a
constantwith operationmean,max,minormax_minus_min(or no operation, which takes the final value) — on the tape-consistent methods (rk4,semi_implicit,implicit_euler_ift,implicit_newton); - a
serieson a state or algebraic variable — on the tape-consistent methods only; - a
constantwith operationmean,max,minormax_minus_min— onsemi_implicit_signedwithgradient_strategy: kernel(aadc-ode). A series is not supported there.
Any other observable — a user operation such as steady_state_avg, another data type, or an
operand that names neither a state nor a variable — makes the gradient raise an error on
those paths, naming the observables it cannot tape, rather than silently minimising a reduced
cost. The bdf_newton method and the semi_implicit_signed tape strategy do not check yet:
they leave such an observable out of the cost, or cost it wrongly, so keep to the observables
above there. For
other observables use casadi_python (method: bdf) or a Myokit CVODES FSA run.
Multiple sub-experiments / experiments are not yet supported by the AADC wrapper. The tape
records one straight-line integration, so a protocol with more than one sub-experiment (or more
than one experiment) raises rather than silently differentiating the wrong thing. The Myokit
CVODES FSA gradient (model_type: cellml + solver: CVODE_myokit) does support multi-sub
protocols; the AADC equivalent is tracked as future work.
Parameter Identification Settings
To run the parameter identification we need to set a few entries in the [CA_dir]/user_run_files/user_inputs.yaml file:
- param_id_method: this defines the optimisation method we use. Currently supported methods are:
- CMA-ES: Covariance Matrix Adaptation Evolution Strategy using Nevergrad (the default when
param_id_methodis not set; supports parallel execution) - genetic_algorithm: Genetic algorithm optimizer (well-tested; its default population is 744 per generation, so it needs a budget of at least that many evaluations)
- bayesian: Bayesian optimization using scikit-optimize (deprecated, untested)
- sp_minimize: Gradient-based optimizer (L-BFGS-B, local only)
- multi_start_sp_minimize: Multi-start L-BFGS-B — a gradient-based descent from many scattered starting points, so it exploits the gradient but still escapes local minima
- CMA-ES: Covariance Matrix Adaptation Evolution Strategy using Nevergrad (the default when
- pre_time: the unlogged time a plain simulation (no obs_data) runs to reach steady state. A calibration is timed by the
pre_timesandsim_timesin the obs_data'sprotocol_info, which every obs_data must have (see the next section). - sim_time: the logged duration of a plain simulation (no obs_data). A calibration takes its durations from the obs_data's
sim_times. - dt: The output (sample) time step for model outputs
- solver_info.MaximumStep: The CVODE maximum step size (
CVODE_myokit,CVODE_libopencor) - solver_info.dt_solver: The step of the fixed-step and C++ solvers. A CellML solver does not
read it, and refuses a
dt_solverthat differs fromMaximumStep - param_id_obs_path: the path to the
obs_data.jsonfile described above (absolute or relative to youruser_inputs.yaml). -
optimiser_options: Dictionary for optimizer-specific options. Common options shared across optimisers:
- num_calls_to_function: Maximum number of function evaluations (default: 10000)
- cost_convergence: Convergence tolerance for cost (default: 0.0001)
- max_patience: Stop after this many generations without an improvement in cost (default: 10). For CMA-ES a generation is one population of candidates (4 for two bounded parameters, and at least the MPI rank count + 1), on any number of ranks
- cost_type: Cost function type (e.g., 'MSE')
CMA-ES specific options:
- The initial step is not an option: Nevergrad's CMA-ES picks it itself, in a space scaled per parameter to (max - min) / 6.
sigma0was removed; a config that names it is refused - Note:
- The number of parallel workers is automatically determined from the number of MPI processes
- Initial parameter values are automatically loaded from
{file_prefix}_parameters.json - The start value is evaluated first, as one of
num_calls_to_function, so a run never ends with a worse cost than its start (a warm start or a profile likelihood point stays at least as good)
sp_minimize specific options:
- do_ad: Boolean value to determine whether to use automatic differentiation for gradient calculation. If it's set to False, gradients will be estimated using finite difference approximation.
multi_start_sp_minimize specific options:
- num_starts: Number of L-BFGS-B descents to run (default: 10, or 4 when
DEBUGis true). The starts are spread round-robin over the MPI ranks; makenum_startsseveral times the rank count so the work balances (see the note under "Multi-start Gradient-based Optimizer" below). - start_sampling: How the starting points are scattered over the parameter bounds:
sobol(default),latin_hypercubeorrandom. - include_init_point: If true (default), the first start is the initial parameter values from
{file_prefix}_parameters.json, so this method can never do worse than a single-startsp_minimizerun. - seed: Seed for the start sampler (default: 0), so a run is repeatable.
- fd_step: Finite-difference step used when an automatic-differentiation gradient isn't available — i.e. any configuration without an AD backend (see the gradient-backend note below), or when
do_ad: false(default: 1e-4). - cost_convergence: Once any start reaches this cost, every MPI rank stops launching new starts (signalled between ranks with a non-blocking message), so no rank keeps working after a good-enough solution has been found. (Set
no_new_starts_on_convergence: falseto disable this.) - no_new_starts_on_convergence:
true(default) is the behaviour above — stop launching starts once one converges. Set tofalseto run every start regardless, then report how many converged and how many landed in each distinct minimum. That maps the basin structure of a multi-modal problem (which minima exist, and how the starts split between them); the counts are written tomulti_start_convergence_clusters.csvand printed at the end of the run. - convergence_cluster_tol_frac: When counting how many starts reached each minimum, two converged starts are treated as the same solution if every parameter agrees to within this fraction of that parameter's range (default: 0.02, i.e. 2%).
Automatic-differentiation gradient backends
Gradient-based calibration (
do_ad: true) is provided by two open-source backends: CasADi (model_type: casadi_python, LGPL — symbolic differentiation) and Myokit CVODES forward sensitivity (model_type: cellml+solver: CVODE_myokit). Both require no proprietary licence and both handle stiff models; see the Solver section for which method to pick.Circulatory Autogen also ships an optional adapter for AADC (Matlogica), which is third-party proprietary software, not part of Circulatory Autogen, not bundled with it, and restricted to academic/non-commercial use under Matlogica's own licence. It is not required. It can drive
sp_minimize/multi_start_sp_minimizeonly for non-stiff, state-observable, single-experiment problems (its tape records a fixed-step integrator); it is unsuitable for stiff models such as the full cardiovascular model. See Optional third-party backends if you already hold a Matlogica licence.
Choosing an Optimization Method
Genetic Algorithm (genetic_algorithm)
- Pros: Well-tested, robust, handles non-smooth cost functions well
- Cons: Can be slower, requires more function evaluations
- Best for: Complex, multi-modal optimization problems, when you have many function evaluations available
CMA-ES (CMA-ES)
- Pros: Efficient gradient-free optimization, supports parallel execution, good convergence properties
- Cons: Requires Nevergrad package (
pip install nevergrad) - Best for: Smooth optimization landscapes, when you want faster convergence with parallel execution
- One parameter: Nevergrad runs a different search (OnePlusOne) in one dimension, which can stall on a
parameter's bounds, so a one-parameter calibration searches a second, unused variable beside it and runs
CMA-ES (
benchmarks/cmaes_one_parameter.py). For a single parameter of a smooth cost,sp_minimizeis usually faster.
Example configuration for CMA-ES:
param_id_method: CMA-ES
optimiser_options:
num_calls_to_function: 10000 # shared option
cost_convergence: 0.001 # shared option
# Note: Initial parameter values are automatically loaded from {file_prefix}_parameters.json
Gradient-based Optimizer (sp_minimize)
- Pros: Efficient gradient-based optimization, fast convergence
- Cons: Can get stuck in local minima
- Best for: Smooth optimization landscapes, when you want faster convergence
For an AD gradient use model_type: casadi_python (CasADi symbolic differentiation) or a
cellml model run through solver: CVODE_myokit with do_ad: true (Myokit CVODES forward
sensitivity — see the Solver section). Any other configuration falls back to a finite-difference
gradient.
Multi-start Gradient-based Optimizer (multi_start_sp_minimize)
L-BFGS-B only ever finds the minimum of the basin it starts in, so on a multi-modal cost surface sp_minimize is at the mercy of the initial parameter values. This method scatters num_starts starting points over the parameter bounds and runs a bounded L-BFGS-B descent from each one, keeping the best minimum found. It explores globally, like the population-based optimisers, while still using the gradient to descend each basin quickly and accurately.
- Pros: Escapes local minima while still exploiting the gradient; the starts are independent so they are distributed over the MPI ranks with no communication; typically reaches a far lower cost than a gradient-free global search for the same wall-clock time.
- Cons: Cost scales with
num_starts; a very rugged surface may need many starts. - Best for: Multi-modal cost surfaces — the common case when calibrating oscillatory models, where a wrong rate constant puts the simulation out of phase with the data.
Parallel multi-start pays off only for many starts
The starts are distributed statically round-robin over the MPI ranks (run_param_id.sh with num_processors > 1). Because individual L-BFGS-B descents vary a lot in length — some converge in a handful of iterations, some take many — the per-rank workloads only even out when each rank runs many starts, i.e. when num_starts is much larger than the number of ranks. With num_starts ≤ num_processors each rank runs a single descent and the wall-clock is bounded by the slowest one, so extra ranks buy little. As a rule of thumb, run with several times as many starts as ranks. Measured on a 20-core host with 100 starts: ~3.8× on 4 ranks, ~4× on 8. Once any start reaches cost_convergence, every rank stops launching new starts, so a converged run doesn't keep the other ranks busy needlessly. run() reports the achieved speedup in its final log line.
This works for any model_type. The gradient comes from get_gradient(), which has an AD backend for casadi_python (symbolic jacobian), cellml run through CVODE_myokit with do_ad: true (Myokit CVODES forward sensitivity), and aadc_python (tape reverse pass — non-stiff, single-experiment problems with the observables listed in the AADC caveat in the Solver section). For every other configuration there is no AD gradient, so the cost is evaluated with the usual simulation cost and the gradient falls back to finite differences.
Example configuration:
param_id_method: multi_start_sp_minimize
model_type: casadi_python # for AD gradients; other model types use finite differences
solver: casadi_integrator
do_ad: true
optimiser_options:
cost_convergence: 0.0001
num_starts: 10 # number of L-BFGS-B descents
start_sampling: sobol # sobol | latin_hypercube | random
include_init_point: true # first start is the x0 from {file_prefix}_parameters.json
seed: 0
Alongside the usual best_cost_history.csv / best_param_vals_history.csv (written as a running-best curve over the concatenated starts), this optimiser writes a multi_start_summary.csv with one row per start — its initial cost, final cost, iteration count and final parameter values. That tells you how many distinct basins your starts fell into, which is the quickest way to see whether num_starts is high enough.
It also streams three live per-start histories during the run, appended one row per L-BFGS-B iteration (iteration 0 is the start point), independent of DEBUG: multi_start_cost_history.csv (start_idx, iteration, cost), multi_start_param_vals_history.csv (start_idx, iteration, then one named column per parameter, holding the actual parameter values — same columns as multi_start_summary.csv) and multi_start_gradient_history.csv (start_idx, iteration, then one named column per parameter, holding the cost gradient dJ/dp in real parameter space at that iterate). Group by start_idx and order by iteration to plot a cost-, parameter- and gradient-vs-iteration line per start while the run is still going. The three files share the same (start_idx, iteration) keys, and start_idx is a stable global index, so rows from starts running concurrently on different MPI ranks demux cleanly regardless of interleaving.
Benchmark: FitzHugh-Nagumo
resources/FitzHugh_Nagumo_* is a deliberately multi-modal benchmark. The FitzHugh-Nagumo excitable-cell model
$$\dot V = c\left(V - \tfrac{V^3}{3} + R\right), \qquad \dot R = -\tfrac{1}{c}\left(V - a + bR\right)$$
is a standard hard case for parameter estimation: its least-squares surface has many local minima, because a wrong recovery rate c puts the simulated spike train out of phase with the data (Ramsay et al. 2007, J. R. Statist. Soc. B 69(5), "Parameter estimation for differential equations: a generalized smoothing approach"). The supplied FitzHugh_Nagumo_parameters.json starts at (a, b, c) = (0.8, 0.9, 2.0), which sits inside a local basin; the true values are (0.2, 0.2, 3.0).
sp_minimize never leaves the basin it starts in. The genetic algorithm escapes it but, being gradient-free, converges slowly. The multi-start finds the global basin and refines it with the gradient — whatever gradient backend drives it (finite differences, CasADi AD, or Myokit CVODES FSA). The table below is regenerated by the benchmark runner (python benchmarks/run_benchmarks.py --update-docs) and by the Benchmarks GitHub Actions workflow, so the published numbers stay current; they depend on the hardware and MPI rank count used.
Generated by benchmarks/run_benchmarks.py; numbers depend on the hardware and MPI rank count used.
FitzHugh-Nagumo (non-stiff, multi-modal)
Gradient-free global searches (genetic algorithm, CMA-ES) vs multi-start L-BFGS-B driven by four gradient sources. Holding the optimiser fixed and varying only the gradient isolates what the gradient buys.
1 MPI rank(s); 30000 cost evaluations for the population methods; 16 starts for multi-start.
| method | best cost | time (s) | max param err |
|---|---|---|---|
genetic_algorithm |
1.9049e-03 | 257.9 | 0.0125 |
CMA-ES |
1.4413e+02 | 286.2 | 4.0000 |
multi_start (FD) |
2.4545e-03 | 40.0 | 0.0359 |
multi_start (CasADi AD) |
9.6440e-06 | 66.0 | 0.0019 |
multi_start (Myokit FSA) |
2.0599e-06 | 86.8 | 0.0021 |
multi_start (AADC AD) |
skipped — no Matlogica licence in this environment |
True parameters: a=0.2, b=0.2, c=3.
Goodwin oscillator (external PMR CellML, non-stiff, multimodal)
Gradient-free global searches (genetic algorithm, CMA-ES) vs multi-start L-BFGS-B (finite differences and Myokit CVODES FSA) recovering rate constants of the Goodwin 1965 oscillator, taken directly from the Physiome Model Repository as external CellML. Oscillatory dynamics make the least-squares surface multimodal.
1 MPI rank(s); 30000 cost evaluations for the population methods; 16 starts for multi-start.
| method | best cost | time (s) | max param err |
|---|---|---|---|
genetic_algorithm |
2.0251e-04 | 83.6 | 0.0046 |
CMA-ES |
2.7517e-06 | 112.0 | 0.0017 |
multi_start (FD) |
9.1452e-15 | 26.7 | 0.0000 |
multi_start (Myokit FSA) |
1.3269e-13 | 117.6 | 0.0000 |
multi_start (CasADi AD) |
1.3147e-12 | 69.7 | 0.0000 |
True parameters: a_i=72, b_i=2, A_i=36.
Teusink 2000 yeast glycolysis (external PMR CellML, 14 states, stiff regions)
The realistic, many-parameter case: recover four enzyme v_max values from metabolite time courses of the Teusink 2000 glycolysis model, taken from the Physiome Model Repository as external CellML (originally a BioModels SBML export). 14 coupled metabolite states and 90 constants, with stiff regions in the search box -- a much harder calibration than the small oscillator benchmarks. Multi-start finite differences also run on the batched C solvers (CVODES_batched_c, BE_batched_c).
1 MPI rank(s); 5000 cost evaluations for the population methods; 16 starts for multi-start.
| method | best cost | time (s) | max param err |
|---|---|---|---|
genetic_algorithm |
8.9298e-04 | 29.0 | 0.0799 |
CMA-ES |
7.1010e-09 | 3.6 | 0.0003 |
multi_start (FD) |
3.2838e-15 | 35.2 | 0.0000 |
multi_start (Myokit FSA) |
3.8772e-15 | 2500.2 | 0.0000 |
multi_start (FD, CVODES_batched_c) |
3.9399e-15 | 23.5 | 0.0000 |
multi_start (FD, BE_batched_c) |
8.5629e-07 | 24.2 | 0.0001 |
True parameters: Vmax_GLK=226.452, Vmax_PGI=339.677, Vmax_PYK=1088.71, Vmax_GAPDH_f=1184.52.
The stiff 3compartment cardiovascular benchmark (long warmup, Myokit/CasADi) runs in the same set; it is slower, so the workflow schedule is weekly. See benchmarks/README.md.
Running parameter identification
After creating the params_for_id file and the param id observables file, and configuring the above settings, run the parameter identification using the below command.
./run_param_id.sh <NUM_CORES>
Following a successful parameter id process, the model with updated parameters can be generated with:
./run_autogeneration_with_id_params.sh
Note
IMPORTANT: After running the calibration, you should plot the simulation outputs vs the ground truth to analyse the fits!! This can be done with:
./plot_param_id.sh
The generated models will be saved in generated_models/ and plots will be saved in param_id_output/.
Full model time-series dumps (all states and variables) are written as NumPy archives in the param_id output directory:
all_outputs_with_best_param_vals_exp_{i}.npz— written when calibration completes successfully.all_outputs_with_best_param_vals_exp_{i}_plot.npz— written at the start of everyplot_outputs()call. Use these to recover trajectories after an interrupted run as long asbest_param_vals.npyexists in the same output folder.
The study working dir
param_id_output_dir is the study's working dir: every calibration, MCMC, sensitivity
analysis and emulator run from one config records itself in the study manifest
<param_id_output_dir>/<study_name>_cuflynx_study.json, and every input it was run from is
copied into the same folder. So the one folder holds the whole study: zip it, send it, unzip it
anywhere and open the manifest (or the folder, as the working dir) in CUFLynx.
<param_id_output_dir>/
<study_name>_cuflynx_study.json the manifest: inputs, solver settings, runs, sensitivity, emulator
inputs/
index.json every version stored below: its kind, file, folder,
content hash, when it was first used and the runs that used it
<kind>/<yyyy-mm-dd_HHMMSS>/ one version of one input, in a folder named for the local
date-time it was first used. The kinds:
model/ the model, with the CellML files it imports
obs_data/, params_for_id/ the obs_data and params_for_id files
user_inputs/ the user_inputs.yaml given
funcs/ the *_funcs_external_path files
system/ a generated model's module array and parameters file, with
modules/ (each module library version it uses) and
external_modules/ (its external_modules_dir)
emulator/ an emulator trained elsewhere
workflows/<workflow_name>/ a calibration workflow, packed (see Calibration workflows)
user_inputs/user_inputs_<yymmdd>.yaml each day's resolved config
<prefix>_calibrated.cellml the model with the best fit written in, from
CVS0DParamID.write_calibrated_model (a pipeline bundle's
run_pipeline.py writes it after its calibration)
<method>_<prefix>_<obs_data>/ each calibration, <method> its param_id_method
mcmc_<prefix>_<obs_data>/ the MCMC run (mcmc_chain.npy, its statistics and plots),
a directory of its own beside the calibration it follows
sensitivity/ Sobol and local sensitivity output
emulators/ trained emulators
A calibration and the MCMC run that follows it each have a directory and an entry in the
manifest's runs. The obs_data and params_for_id a run used are the copies in inputs/ that
its manifest entry names; a run with no working dir (write_cuflynx_study: false or
cuflynx_study_copy_inputs: false) copies them into its run directory instead, with a
_<yymmdd>_<HHMMSS> suffix.
A pipeline bundle written by cuflynx-generate-pipeline is a working dir too: its
run_pipeline.py writes the manifest, the run directories, sensitivity/ and inputs/ into
the bundle folder.
An input is copied when the manifest is written, once per content, into a folder named for the
date-time (local time) it was first used, for example inputs/obs_data/2026-10-31_091502/obs.json.
Every copy is in such a folder, so no file under inputs/ looks like the current version when
it is an older run's: each run's entry in the manifest names the copies it ran with, and
inputs/index.json lists every version with the runs that used it. A second run from the same
files copies nothing (copies are matched by content hash), and a changed file goes into a new
dated folder beside the first (_2, _3... when two contents are first used in the same
second). Every path in the manifest is relative to the manifest's folder.
An output written outside the working dir, such as an sa_options output_dir set to an
absolute path elsewhere, is allowed but does not travel with the working dir: a zip of the
working dir does not hold it. The run prints a warning naming the directory, and its entry in
the manifest keeps the absolute path with "outside": true.
cuflynx_study.outside_outputs(read_study('<W>')) lists those entries. Opening the study
elsewhere never writes into that path: nothing re-runs a study from its manifest (read_study
resolves output directories only to read their results, and generation_inputs names none).
To share a working dir, export it:
from libcuflynx.utilities.cuflynx_study import export_working_dir
left_behind = export_working_dir('<W>', 'my_study.zip')
Your working dir is not changed; these changes are only in the zip, so that a yaml run from it reads and writes only in the recipient's working dir, with no edits:
- Each archived user_inputs yaml names its output directories relative to where it is unzipped:
param_id_output_diris the unzipped working dir, and an outsidesa_optionsoutput_dirsuch as/scratch/sa_runsbecomessensitivity/sa_runsin the working dir (output_dir: sa_runsin the yaml). An outsidegenerated_models_dirbecomesgenerated_models, and an outsideemulator_dirthe default underemulators/. - Each archived user_inputs yaml names its inputs by their copies under
inputs/, the versions that yaml's own run used (the manifest'syaml_inputsrecords them), not simply the latest:resources_diris theinputs/system/<date>/folder (module array and parameters file),module_library_dirsandexternal_modules_dirare the folders in it, andparam_id_obs_path,params_for_id_file, the*_funcs_external_pathkeys and, withuse_emulator,emulator_dirname their own copies. The model the run used goes ingenerated_model_path(external_model_pathforexternal_python). - The manifests and
inputs/index.jsondrop the outside entries and every absolute path.
Each outside path gets a warning naming it and its new relative path, and the results there are
not in the zip. Each input rewritten gets a warning naming its copy. left_behind lists the same
paths, the inputs marked 'input': True.
An input with no copy in the working dir, such as an external_modules_dir added by hand or a
yaml whose run the manifest does not record, keeps the path it had, with a warning: the run then
stops at that path on another machine rather than silently using a default in its place.
left_behind lists it with relative None. Paths the yaml derives (model_path,
vessels_csv_abs_path and so on) are left out, since the parser works them out again.
To run an unzipped yaml, point user_inputs_path_override at it in your user_inputs.yaml: that
is what makes its relative paths resolve from its own folder. --user-inputs does not: it takes
relative paths from the current directory. Nothing else is needed, and the originals need not
exist. generated_model_path makes the run use the model the study ran; to run a model generated
again from inputs/system/, delete that key from the yaml first. A calibration workflow's step
yamls (in its step folders) and a packed calibration_workflow.json are not rewritten: rerun a
workflow from its packed copy.
A generated model's inputs/system/ holds everything generating it again needs, so the model
can be regenerated from the working dir alone. Built-in modules are not copied: they come with
libcuflynx, so the manifest records use_builtin_modules and libcuflynx_version instead.
from libcuflynx.scripts.script_generate_with_new_architecture import generate_with_new_architecture
from libcuflynx.utilities.cuflynx_study import generation_inputs, read_study
inp = generation_inputs(read_study('unzipped_study/')) # resources_dir, file_prefix, module sources
generate_with_new_architecture(False, dict(inp, model_type='cellml',
generated_models_dir='regenerated'))
| user_inputs setting | default | what it does |
|---|---|---|
study_name |
file_prefix |
names the manifest; two studies can share one working dir |
write_cuflynx_study |
true |
false writes no manifest and copies nothing; sensitivity output and the dated user_inputs go where cuflynx_study_copy_inputs: false puts them |
cuflynx_study_copy_inputs |
true |
false copies nothing: the manifest names each input outside the working dir by its absolute path and records the working dir as study_dir; sensitivity output defaults to sensitivity_outputs/<file_prefix>_SA_results and the dated user_inputs_<yymmdd>.yaml goes in resources_dir |
The calibrated model
libcuflynx.param_id.calibrated_model writes values into a CellML file. It is the one writer of
a calibrated CellML: CVS0DParamID.write_calibrated_model, a calibration workflow's CellML
steps and CUFLynx all use it, so one best fit gives one file.
from libcuflynx.param_id.calibrated_model import (substitute_parameter_values,
write_calibrated_model, write_cellml_values)
report = write_cellml_values('model.cellml', {'aortic_root/C': 2e-8, 'global/E_lv_A': 4e8},
'model_calibrated.cellml', flatten=None)
# {'updated': ['aortic_root/C', 'global/E_lv_A'], 'unresolved': [],
# 'resolved': {'aortic_root/C': 'parameters/C_aortic_root',
# 'global/E_lv_A': 'parameters_global/E_lv_A'},
# 'path': 'model_calibrated.cellml', 'flattened': True}
new_text, report = substitute_parameter_values(cellml_text, values) # the same, on text
write_calibrated_model(cellml_path, param_id_info, best_param_vals, output_path,
flatten=None, return_report=True) # from a best fit
A value is named vessel/param (resolved by model_qname_candidates, so aortic_root/C is
parameters/C_aortic_root and global/E_lv_A is parameters_global/E_lv_A in a generated
model) or component/variable. Only a variable with a numeric initial value in a component
the file defines is written. The report lists the names written (updated), those with no such
variable (unresolved, which write_calibrated_model also names in a warning) and where each
went (resolved, component/variable; PhLynx reads back only the values in parameters and
parameters_global).
flatten=None (the default) flattens a file that has imports: a generated model imports its
parameters from <prefix>_parameters.cellml, so the calibrated model is one flattened file
that runs by itself. A file with no imports is written as it is, with only the
initial values changed. flatten=False writes the file itself whatever it imports (its
imported constants are then unresolved); flatten=True always flattens.
Calibration workflows
Some parameters can only be calibrated in a larger model, after its parts have been calibrated alone: a neuron soma's leak conductances once every channel has its own values, or a whole circulation once an isolated aorta has been fitted. A calibration workflow records that order in one JSON file and repeats it with one command:
cuflynx-calibration-workflow workflow.json
mpiexec -n 4 cuflynx-calibration-workflow workflow.json # every step on 4 ranks
or from Python:
from libcuflynx.calibration_workflow import run_calibration_workflow
result = run_calibration_workflow('workflow.json', output_dir='wf_out')
result['merged_parameters'] # [{'parameterisation_name': 'aortic_root/C', 'value': ..., 'from_step': ...}]
Each step is an ordinary calibration, named by its three inputs: a model, an obs_data
file and a params_for_id file, the same three that cuflynx-param-id takes. A step can
instead be one of the analyses around a calibration -- a sensitivity analysis, an emulator, an
identifiability analysis, or a reduction that picks which parameters a later calibration fits
(see Step kinds) -- so the file records the whole order of a study. The results
of every calibration are merged into the workflow's target model. To redo a calibration,
edit its obs_data and run the workflow again: every step that used its values is redone too.
Try it
libcuflynx ships small example models for trying workflows. They are algebraic, so a run takes seconds, and every answer is known. Write them anywhere:
python -c "from libcuflynx.external_testing.workflow_library import build_workflow_library as b; b('wf_example')"
WF=wf_example/arrays/chain_array.json
cuflynx-calibration-workflow $WF --dry-run # the plan: where each parameter lands
cuflynx-calibration-workflow $WF --output-dir wf_run # A/p = 2, C/q = 3
cuflynx-methods-latex --workflow $WF --run-dir wf_run -o methods.tex --pdf
chain_module_array.json is a model of two vessels: A (lin_a, y = 2 p^2) feeding C
(lin_c, z = y + k q^2). Step a-alone calibrates p on a model of A alone; step chain
then calibrates q in the whole chain, with p fixed. Read $WF and the files next to it for
a layout to copy. The same chain written with library modules is
wf_example/modules/chain/versions/v1/parameterisations/rest/calibration_workflow.json, and
.../screened/calibration_workflow.json adds a Sobol screen, a reduction and an
identifiability analysis to it (see Step kinds).
Building a workflow in Python
WorkflowBuilder makes the same file with API calls, so a script or a notebook needs no
hand-written JSON. The obs_data and params_for_id can be dicts, as CVS0DParamID takes them
(or an ObsDataCreator). Every method is in the
API reference.
One calibration
With the example models of Try it in wf_example, fit p of the vessel A
(y = 2 p^2) to y = 8:
from libcuflynx.calibration_workflow import WorkflowBuilder
settings = {'param_id_method': 'CMA-ES', 'dt': 0.1,
'optimiser_options': {'num_calls_to_function': 400, 'cost_convergence': 1e-14,
'max_patience': 60, 'seed': 1, 'cost_type': 'gaussian_MLE'}}
wf = WorkflowBuilder('one_fit', target='wf_example/arrays/a_only_module_array.json',
directory='wf_one', module_library_dirs=['wf_example/modules'],
settings=settings)
wf.add_calibration(
'fit',
obs_data={'protocol_info': {'pre_times': [0.0], 'sim_times': [[1.0]],
'params_to_change': {}},
'data_items': [{'data_item_name': 'y_a', 'data_type': 'constant',
'unit': 'dimensionless', 'operands': ['A/y'],
'operation': 'mean', 'value': 8.0, 'std': 0.08}]},
params_for_id=[{'vessel_name': 'A', 'param_name': 'p', 'min': 0.1, 'max': 5}])
wf.run()
wf.result('fit')['values'] # {'A/p': 2.0}
targetis the model the calibrated values are merged into, and the model of every step that names none: a module array path (ormodule_array(path, parameters=...)), orlibrary_module(type, version, parameterisation).directoryis where the workflow file and its data are written; the run goes to<directory>/workflow_output/<name>(wf.output_dir).module_library_dirsis needed whenever a model names modules of a module library, as these arrays do ("parameterisation": "default"oflin_a).settingsareuser_inputs.yamlkeys. A calibration needs itsparam_id_methodand that method'soptimiser_options(genetic_algorithm, the method when none is named, requiresnum_calls_to_function).wf.check()names what is missing, without running anything;wf.update_settings(...)changes settings later.
wf.run() checks the workflow, writes it and runs it. It prints one [workflow] line per
step; everything else a step writes (the optimiser's iterations, compiler output, warnings)
goes to <output_dir>/<step>/log.txt, and what is written outside the steps to
<output_dir>/workflow_log.txt. wf.run(verbose=True) prints all of it as well.
print(wf) lists the steps and whether each has run. wf.show_status() prints a table with
each step's state (done, stale, not run), best cost and finish time, and
wf.show_plan() one with each step's model, the steps it takes from and the parameters it
gives; wf.status() and wf.plan() return the same as dicts.
A chain of steps
The chain of Try it: a-alone calibrates p on a model of A alone, then chain
calibrates q in the whole chain (z = y + q^2) with p fixed.
from libcuflynx.calibration_workflow import WorkflowBuilder, module_array
def obs(item, operand, value, std, operation='mean'):
return {'protocol_info': {'pre_times': [0.0], 'sim_times': [[1.0]], 'params_to_change': {}},
'data_items': [{'data_item_name': item, 'data_type': 'constant',
'unit': 'dimensionless', 'operands': [operand],
'operation': operation, 'value': value, 'std': std}]}
arrays = 'wf_example/arrays'
wf = WorkflowBuilder('chain_from_python', target=module_array(f'{arrays}/chain_module_array.json'),
directory='wf_python', module_library_dirs=['wf_example/modules'],
settings=settings)
wf.add_calibration('a-alone', model=module_array(f'{arrays}/a_only_module_array.json'),
obs_data=obs('y_a', 'A/y', 8.0, 0.08),
params_for_id=[{'vessel_name': 'A', 'param_name': 'p', 'min': 0.1, 'max': 5}])
wf.add_calibration('chain', obs_data=obs('z_c', 'C/z', 17.0, 0.17),
params_for_id=[{'vessel_name': 'C', 'param_name': 'q', 'min': 0.1, 'max': 10}],
fixed_from=['a-alone'])
wf.plan() # the order, and where each parameter lands; runs nothing
wf.run() # A/p = 2, then C/q = 3
wf.result('chain')['values'] # {'C/q': 3.0}
add_calibration, add_sensitivity, add_reduction, add_emulation, add_identifiability,
add_uq, add_set, add_combine and add_sweep make the step kinds. Their keyword arguments are the
step's keys from The file; the options a kind takes in its settings are an
argument of their own (sa_options=, ia_options=, uq_options=, emulator_settings=, and for a reduction
method=, n_params=, ...). add_step(id, kind=..., **keys) takes any step as its raw keys.
In all of them model defaults to the target. library_module(type, version,
parameterisation), module_array(path, parameters=None), external_model(path), cellml_model(path,
parameters=None), selection(*instances),
fixed(step, parameters=), prior(step, kind=, inflate=, parameters=),
set_value(parameter, value, reason=), scale_value(parameter, scale, of=, reason=)
and set_theta(entry, theta, reason=) give a step's model, fixed values, priors and
set entries. A
step is checked against the schema when it is added.
Values set by hand go in a set step (add_set), not in a parameters dict: each carries its
reason into the provenance.
Your own operations
An obs_data item's operation can be a function defined in the script or in a notebook cell:
import numpy as np
from libcuflynx.param_id.operation_funcs import series_to_constant
@series_to_constant
def double_mean(x, series_output=False):
if series_output:
return 2 * x
return 2 * np.mean(x)
wf.add_operation(double_mean)
wf.add_calibration('a-alone', model=module_array(f'{arrays}/a_only_module_array.json'),
obs_data=obs('y_a', 'A/y', 16.0, 0.16, operation='double_mean'),
params_for_id=[{'vessel_name': 'A', 'param_name': 'p', 'min': 0.1, 'max': 5}])
wf.run() # A/p = 2 still (2 * mean(2 p^2) = 16), and chain again after it
add_operation (and add_cost_func, add_modifier_func) copies the function's source into
<name>_operation_funcs.py beside the workflow, with an import for each module it uses and a
marker set on it after its def (f.series_to_constant = True) as its decorator. The
workflow's operation_funcs_external_path names the file, so every rank, the command line and
CUFLynx load it; it has the layout of CUFLynx's "Custom funcs" dialog
(libcuflynx.utilities.user_funcs_file). wf.functions() lists what was added and
wf.remove_operation(name) takes one out.
- The file is imported on its own, so a function must carry what it needs. A lambda, a
function using a variable of the function it is defined in, and one using a value or a
function defined only in the session (in its body, a default value or an annotation) are
refused: pass helper functions to
add_operationtoo (a name starting with_is not registered as an operation), and put values into the function. - The file is generated; edit the function where it is defined and add it again. Its
header records a checksum, so the builder regenerates a file nobody edited, in this session
or a later one. A file that was edited by hand (or that no builder wrote), or that holds
functions this builder does not have (another writer added them), is refused, so they are
not lost without a word:
wf.add_operation(f, overwrite=True)orwf.write(overwrite=True)replaces it.WorkflowBuilder.loadreads a hand-edited file's functions and keeps the file as it is until its functions change; a file holding other top-level statements (a constant, a class) is then refused with their names, since a generated file holds imports and functions only. - A workflow that already names another operation funcs file takes no
add_operation: add the functions to that file.
Running again, and changing a step
Run the script, or the notebook from the top, as often as you like. A file is rewritten only
when its content changes, and wf.run() runs only the steps that have not run or are
stale. Its first line names the steps it runs and those it keeps, and each kept step gets
a line of its own:
[workflow] running 1 of 2 steps: chain; keeping a-alone
[workflow] step a-alone: done and current, not run again
When every step is done and current it says so and runs nothing. To run every step again,
current or not, use wf.run(force=True) (on the command line, leave out --stale-only);
wf.run(from_step='<id>') runs one step and every step after it.
A step is stale when something it ran with has changed: its obs_data, its params_for_id, its
model's parameters file, its settings, or the workflow's functions file (any function in it,
whether or not the step uses it), or when a step it takes values from is stale or ran again.
wf.status() shows which.
- To change a step, change what you pass and add it again with the same id. A dict is
copied when it is added, so editing the dict afterwards changes nothing until
wf.add_calibration('chain', obs_data=edited, ...)is called again. The step keeps its place. wf.run(force=True)runs every step again.wf.run(from_step='chain')runs that step and those after it, andwf.run(only='chain')just that step; both reuse the earlier results, which must be current.wf.run(ranks=4)runsmpiexec -n 4on the written file.wf.remove_step(id)takes a step out.WorkflowBuilder.load(path_or_directory)makes a builder from an existing workflow file.
What the builder writes, in wf.directory, when wf.write() is called (run, plan,
status, model and plot_step call it first):
calibration_workflow.json the workflow; its paths are relative to this directory
data/<step>_obs_data.json an obs_data given as a dict
data/<step>_params_for_id.json a params_for_id given as entries
<name>_operation_funcs.py the functions given to add_operation, with their imports
.workflow_builder_files.json which of these files a builder wrote, for wf.clean()
workflow_output/<name>/ the run (wf.output_dir), see Outputs below
Two steps given the same dict share one file, named after the first. Keep files of your own
out of data/.
Removing or renaming a step leaves its data files behind. wf.clean() lists the files the
builder wrote for this workflow that no workflow in the directory names any more, and
wf.clean(delete=True) moves them to data/removed/; it deletes nothing. A file is only ever
listed when a builder wrote it, its content is still what was written, and no JSON file at the
top of the directory names it. Nothing under workflow_output/ is touched.
After a run, wf.result(id) is what the step recorded (a calibration's values and
best_cost, a reduction's chosen parameters, each kind's files as paths), wf.step_dir(id)
its output directory, wf.plot_step(id) plots a calibration's fit (as png;
formats=('png', 'pdf') for more), and wf.model(id) (or wf.model('target')) generates the
model with the values found so far, under the run's models/<id>/. Every path the builder
returns (wf.directory, wf.path, wf.output_dir, wf.write(), wf.step_dir(id), the files
in wf.result(id)) is a pathlib.Path.
A step's options are dicts under the names the schema gives them: sa_options,
ia_options, emulator_settings, and for a reduction
wf.add_reduction(id, sensitivity_from=..., param_reduction_options={'method': 'pca', ...}).
From the command line
The written file is an ordinary workflow: CUFLynx opens it, pack_workflow carries its data
and functions file, and the command runs it. The command's default output directory is
workflow_output/<name> beside the workflow file, which is the builder's wf.output_dir, so
the command continues the same run from any directory:
cuflynx-calibration-workflow wf_python/calibration_workflow.json --stale-only
--stale-only runs what wf.run() would; without it the command runs every step, and
--only and --from-step are as in Python.
The file
{
"schema_version": 1,
"workflow_name": "aorta_then_circulation",
"module_library_dirs": ["../module_library"],
"settings": {"param_id_method": "CMA-ES", "dt": 0.001,
"optimiser_options": {"num_calls_to_function": 400}},
"target": "resources/circulation_module_array.csv",
"steps": [
{"id": "aorta-compliance",
"model": "resources/aorta_only_module_array.csv",
"obs_data": "data/aorta_obs_data.json",
"params_for_id": "data/aorta_params_for_id.json"},
{"id": "whole-circulation",
"model": "resources/circulation_module_array.csv",
"obs_data": "data/circulation_obs_data.json",
"params_for_id": "data/circulation_params_for_id.json",
"fixed_from": ["aorta-compliance"]}
]
}
Paths are relative to the workflow file. A model is one of:
- a module array of CA, as
"resources/<prefix>_module_array.csv"(or.json). Its parameters file is<prefix>_parameters.jsonbeside it, or name it:{"module_array": "...", "parameters": "..."}. - a module of a module library, as
{"module_type": "i_M", "version": "Argus2026_v01", "parameterisation": "davis2020_wistar"}. The library is found throughmodule_library_dirs(see module parameterisations). - (a step's, with a module-array target) a selection of the target's instances, as
{"select": ["C"]}or{"select": ["heart/lv"]}(see Calibrating a selection). - an external Python model, as
{"external_model_path": "heat1d_model.py"}. It is never generated, so it is the target and every step's model, and its parameters keep theircomponent/variablenames. See Calibration workflows in the external solvers guide. - a CellML model, as
{"cellml_model_path": "model.cellml"}, or{"cellml_model_path": "model.cellml", "parameters": "values.json"}with a parameters file ({"<component>": {"<variable>": {"value": ..., "units": ...}}}) whose values replace the CellML's. Its parameters are its constants, namedcomponent/variable(states and computed variables are not), and every component is a vessel. A params_for_id, set entry or sweep may also name a constant as a calibration of the same file reads it (global/q_lv_initforparameters_global/q_lv_init,aortic_root/Cforparameters/C_aortic_root): the step resolves the name to the constant, and its results, the merged target and the calibrated files name the constant. It is never generated: a step runs a flattened copy,<step_id>/model/generated_models/<step_id>/<step_id>.cellml, with the step's values written in, and<step_id>_parameters.jsonbeside it lists every constant's value. As for an external model, it is the target and every step's model. It runs asmodel_type: cellml(default solverCVODE_myokit), or, withmodel_typepython,casadi_pythonoraadc_pythonin the settings (the workflow's or a step's, withsolverandsolver_infoas for any model), as the Python generated from that copy,<step_id>.pybeside it; the values still go into the CellML.cppandexternal_pythonare refused.write_calibratedwrites<stem>_calibrated_parameters.jsonand<stem>_calibrated.cellmlbeside it, and a pack copies it with the files it imports, at their paths relative to it.
Your own CellML as the target, fitted and then its uncertainty quantified at the fit, from
Python (the files are tests/data/workflow_parity/'s; the paths are relative to the working
directory):
from libcuflynx.calibration_workflow import WorkflowBuilder, cellml_model
wf = WorkflowBuilder('lv', target=cellml_model('lotka_volterra.cellml'), directory='lv_workflow',
settings={'solver': 'CVODE_myokit', 'dt': 0.01,
'param_id_method': 'CMA-ES',
'optimiser_options': {'num_calls_to_function': 300}})
wf.add_calibration('fit', obs_data='lv_obs_data.json', params_for_id='lv_params_for_id.json')
wf.add_uq('posterior', obs_data='lv_obs_data.json', params_for_id='lv_params_for_id.json',
uq_options={'num_steps': 200}, result_from='fit')
wf.run(write_calibrated=True) # also lotka_volterra_calibrated.cellml beside the source
print(wf.result('fit')['best_fit'], wf.result('posterior')['distribution_dir'])
| Key | Meaning |
|---|---|
target |
the model the results are merged into |
module_library_dirs |
module libraries, relative to the file (more with --module-library-dir); needed when a model is a library module |
settings |
user_inputs settings for every step: param_id_method, optimiser_options, solver, solver_info, dt, pre_time, sim_time, UQ_options, DEBUG, ... (the model, obs_data, params_for_id and output paths are the workflow's, and cannot be set) |
step id |
a label for the step, unique in the file: other steps refer to it, and it names the step's output directory. It is not a module or parameter name. |
step model, obs_data, params_for_id |
what the step calibrates, and against what |
step module_map |
a module array whose modules are named differently in the target: {"aorta": "aortic_root"} |
step submodule / module |
where a library module sits in the target: a submodule of a library supermodule target (i_M, or soma/i_M when nested), or a module of a module-array target; inferred when the module occurs once |
step fixed_from |
steps whose calibrated values -- and the values they were themselves given -- are fixed in this step's model, except those it calibrates itself. An entry {"step": "fit_a", "parameters": ["p_A"]} fixes only those of the step's own calibrated or set values (model names in that step), and none it was given |
step priors_from |
steps whose stored posterior becomes this step's prior (below) |
step store_distribution |
sample the posterior by MCMC after the fit and store it |
step start_from |
(calibration) a calibration or set step whose values of this step's own parameters are where its fit starts (below) |
step emulator_dir |
(calibration, sensitivity, identifiability, uq) an emulator trained outside the workflow, which the step runs on (below) |
step settings |
merged over the workflow's (one level deep, so optimiser_options add up) |
A step runs after every step it takes something from (fixed_from, priors_from and the keys
in Step kinds), since it needs their results; steps that pass nothing between
them run in file order. Here whole-circulation runs after aorta-compliance, with the aorta's
calibrated values fixed.
Calibrating a selection
A step can calibrate some instances of a module-array target as they are in it, without a model file of its own:
{"id": "c-alone", "model": {"select": ["C"]},
"obs_data": "data/c_obs.json", "params_for_id": "data/c_params.json"}
A selection runs as one of the other models:
- one instance -- a record, or
heart/lvinside a super instance -- is its library module, the record's version and parameterisation (a submodule's: its version's default), placed at that instance as"module"would place it. A selected supermodule instance is generated with the model's values for it; - several records are the module array they form, cut from the target. A link to a record outside the selection is dropped, which leaves that port open.
The step starts from the target's values for its instances: the entries of the target's
parameters file under them, a nested instance's under its path (heart/lv; see
A model's supermodule instances). Values fixed
from earlier steps go over those. Its obs_data and params_for_id name vessels as
the target does (C/z, heart__lv/E). For one instance, whose model is generated as mod,
renamed copies are written to <step_id>/inputs/ and run from there.
A port the selection leaves open turns its boundary condition into a parameter. Give it a protocol in the step's obs_data, which sets its value while the step runs:
"protocol_info": {"pre_times": [0.0], "sim_times": [[1.0]],
"params_to_change": {"C/x": [[8.0]]}}
Without one, it takes the parameterisation's value or the target's row. A parameter with none
of these stops the step with an UnsetParametersError, whose names list them as the target's
parameters file does (C/x), so a front end can ask for their protocols. The results merge
into the target like any step's: in <prefix>_calibrated_parameters.json (write_calibrated),
the target's parameters file completed with every other value its model uses (its generated
<prefix>_parameters.json), only the values the step calibrated change, a value
inside a super instance under its path (heart/lv/E).
write_calibrated_parameters_to(source, output_dir, path) writes the same file to path, and
nothing else: neither the target's files nor the supermodule version's template change. It builds
on the run's own _target/ generated parameters file, so a library default changed after the run does
not reach the result; only a run without a target model has the target generated again, against
the library as it is then. A run whose target model has a generated parameters CSV (an older
libcuflynx wrote one) is refused: run the workflow again.
Step kinds
A step's kind is calibration unless it says otherwise. sensitivity, emulation and
identifiability run the analyses cuflynx-sensitivity, cuflynx-train-emulator and
cuflynx-identifiability run, on the step's model, obs_data and params_for_id. Only the values
of calibrations, set steps and combine steps are merged into the target.
A step can run on a surrogate in place of the model: on an emulator, named by
the step's emulator_from or emulator_dir (below), or on a reduced-order model, which is the
step's model (an external Python model).
kind |
What it does | Needs | Takes from |
|---|---|---|---|
calibration |
a param_id run; MCMC with store_distribution |
fixed_from, priors_from, start_from, emulator_from, params_for_id_from |
|
sensitivity |
Sobol or local sensitivity analysis | sa_options in its settings |
fixed_from, emulator_from, result_from |
reduction |
keeps the parameters a Sobol step found most influential, or those chosen by hand ("method": "manual") |
sensitivity_from, param_reduction_options in its settings; no model or files (chosen by hand: params_for_id, and no sensitivity_from) |
|
emulation |
trains an emulator of the observables | emulator_settings (optional) |
fixed_from, params_for_id_from |
identifiability |
Identifiability analysis (Laplace or a profile likelihood) at a step's values, or at the model's own | ia_options |
fixed_from, result_from |
uq |
MCMC or a Laplace approximation at a step's values, or at the model's own, with no fit of its own; stores the distribution | UQ_options with method mcmc (default) or laplace |
fixed_from, result_from, emulator_from |
set |
declares values or scales by hand, each with a reason; with "point": true they are only a point for other steps and never reach the target |
set; no model or files |
the calibration or set steps it scales |
combine |
gives one value per parameter from several steps: the values of the calibration with the lowest cost (best_fit), or each parameter's mean (mean). Its values are used in place of theirs, in later steps and in the target (below) |
combine_from, combine; no model or files |
the calibration, set or combine steps it combines |
sweep |
runs a model across chosen parameter values and keeps every run | model (or "on_target": true), sweep, dt, and sim_time or an obs_data; no params_for_id |
fixed_from, result_from |
simulate |
runs a model once through its protocol; a sweep of no parameters | model (or "on_target": true), dt, and sim_time or an obs_data; simulate.outputs or prediction items |
fixed_from, result_from |
figure |
calls a Python function that draws figures from other steps' results | function, inputs; no model or files of data |
the steps its inputs name |
The keys that pass something on, each naming one step of the kind shown:
| Key | Names a | What this step gets |
|---|---|---|
fixed_from |
calibration, set or combine | its values, fixed in this step's model (above) |
priors_from |
calibration with store_distribution, or uq |
its posterior, as a prior (below) |
result_from |
calibration, set or combine | its values, including those of the parameters this step analyses: a local sensitivity, identifiability analysis or uq step is then at that point. Without it, they are at the model's own values |
start_from |
calibration, set or combine | its values of the parameters this calibration fits, as the point the fit starts from |
combine_from |
calibration, set or combine (two or more) | a combine step's inputs: the values it gives one of per parameter |
emulator_from |
emulation | its emulator, which this step (a calibration or sensitivity) runs on instead of the model. The step names the same model, obs_data and params_for_id as the emulation step (an emulator answers only for what it was trained on) and has no fixed_from or result_from: it runs on a copy of that step's model, with the values that step was given. One exception: a calibration may take a reduction's parameters (params_for_id_from) on the emulator of the params_for_id they were reduced from. It calibrates the parameters the reduction kept and holds the emulator's other parameters at their values in the emulation step's model, so the emulator is always evaluated at every parameter it was trained on and no second emulator is trained. Its result lists the held parameters and their values under held, and the run directory has held_entries.json. A held value must be inside its params_for_id bounds. Such a step has no store_distribution or priors_from |
sensitivity_from |
sensitivity (Sobol) | a reduction's indices |
emulator_dir |
(a path, not a step) | an emulator trained outside the workflow, as emulator_from gives one: a directory holding emulator_metadata.json (cuflynx-train-emulator's, or an emulation step's of another run), relative to the workflow file. Not with emulator_from. Its files are hashed into the step's inputs, so a retrained emulator makes the step stale, and a pack copies it to inputs/<step_id>/. It must have been trained on the step's model, obs_data and params_for_id. The step's result_from point is only where the emulator is evaluated: it is not written into the step's model, which stays the one the emulator was trained on |
params_for_id_from |
reduction | the params_for_id the reduction wrote, in place of the step's own (a calibration or emulation of the same model as the sensitivity step, or of a model with the parameters chosen by hand; a step on that emulator names the same reduction) |
A calibration with start_from starts its fit at the values that step calibrated or set
for its own parameters: its model is generated with them, so they are the optimiser's initial
point (CMA-ES and the gradient methods start there; the genetic algorithm draws its first
population at random). They are not fixed, and only the values the step fits reach the target.
step_result.json records them under start_from.
{"id": "sliders", "kind": "set", "set": [
{"parameter": "Lotka_Volterra_module/alpha", "value": 4.2, "reason": "slider position"}]},
{"id": "fit", "model": {"cellml_model_path": "lotka_volterra.cellml"},
"obs_data": "lv_obs_data.json", "params_for_id": "lv_params_for_id.json",
"start_from": "sliders"}
A uq step quantifies the uncertainty of its parameters at one point, without fitting:
result_from a calibration's fit or a set step's values, else the model's own. Its
UQ_options.method is mcmc (the walkers start in a ball about the point, as after a fit) or
laplace (a Gaussian there, its covariance from the Hessian of the cost, with the step's
ia_options choosing the gradient). Either way the distribution is stored in
<step_id>/distribution/, as store_distribution stores a calibration's: an MCMC's chain after
burn-in, or UQ_options.num_samples (default 2000) draws of the Gaussian, those outside the
params_for_id bounds dropped (step_result.json counts them). A later calibration takes it with
priors_from. The run itself is in <step_id>/uq/. run_uq(inp_data_dict, best_param_vals,
method) in libcuflynx.scripts.param_id_run_script runs the same outside a workflow, and
do_uq with UQ_options.method: laplace runs the Laplace approximation after a calibration.
An empty UQ_options ({}, what the builder's add_uq() writes when given no uq_options)
is MCMC with the defaults below, or the workflow's UQ_options when it has some.
UQ_options key |
Default | Used by |
|---|---|---|
method |
mcmc (or laplace) |
every uq step |
library |
emcee (also zeus, pymc) |
mcmc |
num_steps |
5000 | mcmc |
num_walkers |
2 × the number of parameters | mcmc |
burn_in |
0.5 (below 1 a fraction of num_steps, else a number of steps) |
mcmc, and the posterior predictive check's draws from its chain |
num_samples |
2000 draws of the Gaussian, before those outside the bounds are dropped | laplace |
posterior_predictive |
true |
every uq step |
posterior_predictive_samples |
100 | the posterior predictive check |
A uq step then runs the posterior predictive check (libcuflynx.param_id.posterior_predictive):
the model at UQ_options.posterior_predictive_samples (default 100) posterior draws, from the
MCMC chain after burn_in or from the Laplace approximation's stored samples, and how often
the data lies inside the model's intervals. It is written to <step_id>/posterior_predictive/
(posterior_predictive.npz with the draws and predictions, posterior_predictive_coverage.json,
and posterior_predictive_series.npz with the traces of the first draws), and
step_result.json names them (posterior_predictive_dir, posterior_predictive_draws,
posterior_predictive_coverage, posterior_predictive_series) with a summary under
posterior_predictive_summary (num_samples, samples_that_failed_to_simulate,
drawn_from: chain or samples, and each level's predictive_coverage and
sample_interval_coverage). UQ_options.posterior_predictive: false skips it. A check that
fails is a warning, with its message in posterior_predictive_summary.error: the step's
distribution stands.
{"id": "posterior", "kind": "uq", "model": {...}, "obs_data": "...", "params_for_id": "...",
"result_from": "fit", "settings": {"UQ_options": {"method": "laplace", "num_samples": 2000},
"ia_options": {"gradient_source": "FSA"}}}
After its fit, a calibration step writes what cuflynx-plot writes for a calibration: the
observables at the best fit, with the error vectors percent_error_vec.npy and
error_vec_names.npy (CA#341), in its run directory; and, when its model is a CellML,
<step_id>/<step_id>_calibrated.cellml, the step's model with the best fit written in.
step_result.json names them (percent_error_vec, error_vec_names, calibrated_model); a failure to write them is
a warning, and the fit stands. When the obs_data has held-out data (prediction items with a
value), the step also checks the best fit against it, as cuflynx-plot does: it writes
validation_results.json in its run directory (validation_results in the result) and
records each item's statistics under validation (data_item_name, n_points, rmse,
nrmse, mean_abs_z, within_2std, ...; the series are in the file).
A params_for_id modifier entry is calibrated as its theta
(best_fit), and the parameters it modifies take modifier(theta, baseline): those values
are what calibrated, the merged target and the calibrated CellML hold, and modifiers in
the result records each entry's theta, targets, baselines and values. A local sensitivity step records the point it linearised about
under nominal (source: its result_from step or model; the parameters and their values)
and its signed coefficients under local_sensitivity_signed (see
Local sensitivity files), and an
identifiability or uq step its point under at and at_source. An identifiability step runs
the method its ia_options.method names: Laplace, recorded under laplace, or
profile_likelihood (with num_points, range_factor and optimiser_options), which
profiles each parameter about that point. Its files are in profile_likelihood/ in the
step's param_id/ directory (profile_likelihood_dir), and profile_likelihood in the result lists
each parameter's file, the value profiled about (best_val), its cost and its 95% interval
(ci_95).
{"id": "profiles", "kind": "identifiability", "model": {...}, "obs_data": "...",
"params_for_id": "...", "result_from": "fit",
"settings": {"ia_options": {"method": "profile_likelihood", "num_points": 21,
"range_factor": 0.2}}}
Every calibrated CellML (a step's, the target's <stem>_calibrated.cellml, a CellML step's
generated model, and a calibration's <prefix>_calibrated.cellml) is written by one writer,
libcuflynx.param_id.calibrated_model: a model with imports, as a generated one has, is
flattened into one file; a single-file model keeps its form, with only the values changed. See
The calibrated model.
A set step declares values nothing fitted, so they are visible to everything downstream. Each
entry names a parameter as the target does, and gives a reason:
{"id": "sglt1_amount", "kind": "set", "set": [
{"parameter": "SGLT1/Scale_SGLT1", "scale": 14, "of": "sglt1_fit",
"reason": "the amount the whole-cell flux needs"},
{"parameter": "GLUT2_api/Scale_GLUT2", "value": 10, "reason": "kept from the source model"},
{"parameter": "Kir/g_K", "scale": 3.37, "of": "inherited", "reason": "raised at this condition"}
]}
value sets a number. scale multiplies the value named by of: a calibration or set step
(which runs first), or inherited, the value the target itself gives the parameter. A later step
takes the values with fixed_from, and they are merged into the target with the calibrated
values, in run order, so a later step's value wins a parameter both give. They are marked
set_by_hand, with their reason, in the provenance diagram, the target's parameters and the
calibrated parameters file, and are never reported as calibrated.
A set step with "point": true declares a point only: a place to start a fit
(start_from) or to analyse at (result_from, or fixed_from). Its values are not merged into
the target, so it gives the target no value of a parameter it shares with a calibration. The
provenance diagram marks it set by hand, labelled "point only, not in the target".
CUFLynx writes its slider positions, nominal points and best-fit points this way. The key is
explicit, rather than inferred from how other steps use the step, so a workflow's meaning does
not change when a step is added. The builder's add_set(..., point=True).
{"id": "sliders-1", "kind": "set", "point": true, "set": [
{"parameter": "Lotka_Volterra_module/alpha", "value": 4.2, "reason": "slider position"}]}
A params_for_id modifier entry is calibrated as its theta, which acts on the parameters it
modifies (scale: theta times each one's value in the model). Its point is therefore a theta,
not a value of those parameters, and a point set step gives it with an entry and a theta
(the builder's set_theta(entry, theta, reason=)), naming the modifier entry in the
params_for_id of the steps that take it:
{"id": "sliders-2", "kind": "set", "point": true, "set": [
{"entry": "alpha_scale", "theta": 0.9, "reason": "slider position"},
{"parameter": "Lotka_Volterra_module/gamma", "value": 2.8, "reason": "slider position"}]}
A step with start_from or result_from that step starts or is analysed at theta 0.9, and
alpha keeps its value in the step's model, so theta, its min and max and its prior mean
what the params_for_id says. A calibration gives the thetas it fitted the same way: a step
with result_from (or start_from) a calibration that has the same modifier entry is at its
fitted theta, about the model's values, rather than at theta 1 about the fitted parameters.
The step runs with a copy of its params_for_id that has theta on those entries
(<step_id>/<step_id>_params_for_id.json). A theta entry is refused in a set step without
"point": true (a theta is not a value of the target) and in a step whose params_for_id has
no modifier entry of that name. With no theta given, an analysis of a modifier entry is at the
theta that leaves its parameters at the model's values.
A sweep runs its model at each point and keeps every run. It feeds nothing forward: no step
can take from it, and its values do not reach the target. It can start from values with
fixed_from or at a calibration's result with result_from:
{"id": "sglt1_dose", "kind": "sweep", "model": "resources/enterocyte_module_array.json",
"result_from": "whole_cell", "settings": {"sim_time": 100.0},
"sweep": {"design": "grid", "outputs": ["enterocyte/c_Na"],
"parameters": {"SGLT1/Scale_SGLT1": {"min": 1, "max": 20, "points": 7, "scale": "log"},
"Kir/A_Kir": {"values": [0, 1, 2]}}}}
A parameter is named as in a params_for_id and takes [min, max], {"min", "max", "points",
"scale"} (5 points by default; "scale": "log" spaces them by ratio), {"values": [...]}, or
{"factors": [...]}, multiples of the value the step's model gives it, or both: {"values": [1, 10,
100], "factors": [1]} is 1, 10, 100 and the model's value. design is grid, every
combination, or one_at_a_time, each parameter's values with the others at the model's values.
outputs are variables recorded over time. An obs_data gives the protocol in place of
sim_time and pre_time, and its prediction_items with an operation give one feature per point.
Each feature is drawn against the swept parameters as a feature_vs_input plot, for
one_at_a_time or a grid of at most two parameters. A sweep does not read data_items.
A prediction run on the calibrated model takes "on_target": true in place of model and
fixed_from. It runs on the target, given every calibration's and set step's values as the target
merges them (a later step wins), after all of them. In the diagram it sits below the merged box,
with one box under it naming the files it wrote: their folder once, then each file, done only when
every file exists. Parameters that move together go in a zip group: the i-th
point takes each member's i-th value, so their lists have one length, and the design treats the
group as one parameter. With "parameters": {} the sweep is one run of its protocol. A long rest
before a run, or the same run at several levels of an input, is the obs_data protocol: every
point runs all its experiments and sub-experiments.
{"id": "energy_cost", "kind": "sweep", "on_target": true,
"obs_data": "protocols/rest_then_glucose_15_40_obs_data.json", "settings": {"dt": 1.0},
"sweep": {"outputs": ["enterocyte/v_NKA"], "zip": [["GLUT2_api/Scale_GLUT2", "GLUT2_bas/Scale_GLUT2"]],
"parameters": {"GLUT2_api/Scale_GLUT2": {"values": [0, 0.1, 1, 10]},
"GLUT2_bas/Scale_GLUT2": {"values": [1, 1, 10, 100]}}}}
Protocol factors
A step's protocol can give a parameter as factors on the value the step's model gives it, rather
than as values: protocol_info.params_to_change_factors, in the shape of params_to_change. The
workflow resolves them once per step (calibration, analysis or sweep), against the step model's
values after fixed_from / result_from (on the target, the merged values), into
params_to_change in a copy of the obs_data the step reads, <step_id>/inputs/<step_id>_obs_data.json.
So x1 to x10 of the Kir density another step calibrated need no copy of its value:
"protocol_info": {"pre_times": [0, 0, 0], "sim_times": [[60], [60], [60]],
"params_to_change_factors": {"Kir/Scale_Kir": [[1], [2], [10]]}}
The step's step_result.json lists each value the factors multiplied under protocol_factors
(parameter, base, units and, for a value an earlier step gave, from_step), and the
diagram names them in the step's box. A parameter is refused in both params_to_change and
params_to_change_factors, or when the step calibrates or sweeps it. Outside a workflow there is
no step model to take values from, so parse_obs_data_json refuses the key.
The runs are in <step_id>/sweep/: sweep_results.npz has points, failed, parameters,
outputs, features and feature_values, and for each experiment time_<e> and trace_<e>
(points, outputs, times); sweep_manifest.json has the design, each parameter's values and the
errors. Under MPI the points are spread across the ranks. A failed point stays as a NaN row, and
the step fails only when every point fails.
A simulate step is one run of a model through its protocol: the simulation behind a figure,
with the values a calibration found (result_from), values fixed by earlier steps (fixed_from)
or the merged target ("on_target": true). It is a sweep of no parameters and writes the same
files, so whatever reads a sweep reads it. simulate.outputs names the variables recorded over
time; with an obs_data its protocol is run and its prediction_items give features. The
prediction items that carry a value (held-out data) are compared with the model in
<step_id>/sweep/validation_results.json, as cuflynx-run-predictions compares them; a sweep
of more than one point writes no validation.
{"id": "paper_run", "kind": "simulate", "on_target": true,
"obs_data": "protocols/glucose_step_obs_data.json", "settings": {"dt": 1.0},
"simulate": {"outputs": ["enterocyte/c_Na", "enterocyte/v_NKA"]}}
A figure step calls a Python function that draws from the results of other steps; see Figure steps.
A reduction chooses the parameters a calibration fits from a Sobol sensitivity step, and
writes those entries of the sensitivity step's params_for_id -- bounds and all -- as
<step_id>/<step_id>_params_for_id.json, with its report param_reduction.json beside it. Its
options are settings.param_reduction_options, as in user_inputs.yaml (see
Parameter reduction) without the paths:
method: pca (default) keeps one parameter per PCA mode of the outputs that moves the data by
more than its noise; method: sobol keeps the n_params with the highest index.
"param_reduction_options": {} is pca with every default. The options belong to the reduction
step alone: the workflow's own settings (and any other step's) refuse them. min_mode_std is
measured over the Sobol samples, which fill the whole prior box of the sensitivity step's
params_for_id: it is a global, prior-wide measure, not local to the fitted values.
{"id": "screen", "kind": "sensitivity", "model": {...}, "obs_data": "...",
"params_for_id": "candidates_params_for_id.json",
"settings": {"sa_options": {"method": "sobol", "num_samples": 256}}},
{"id": "keep", "kind": "reduction", "sensitivity_from": "screen",
"settings": {"param_reduction_options": {"method": "pca"}}},
{"id": "fit", "model": {...}, "obs_data": "...", "params_for_id_from": "keep"},
{"id": "ia", "kind": "identifiability", "model": {...}, "obs_data": "...",
"params_for_id": "fitted_params_for_id.json", "result_from": "fit",
"settings": {"ia_options": {"method": "Laplace", "gradient_source": "FD"}}}
Rerunning screen reruns keep, and so fit and ia, since each takes from the one before.
A reduction may instead record a choice made by hand: "method": "manual" keeps the
parameters named, for the reason given. It reads no sensitivity step (it has no
sensitivity_from) and names the params_for_id whose entries, with their bounds, it keeps.
A parameter is named as its params_for_id entry is labelled: vessel/variable, a grouped
entry's names joined by +, or a modifier's name.
{"id": "keep", "kind": "reduction", "params_for_id": "candidates_params_for_id.json",
"settings": {"param_reduction_options": {
"method": "manual", "parameters": ["heart/E_lv_A", "aortic_root/C"],
"reason": "the two the pressure data resolve; the rest are from the literature"}}},
{"id": "fit", "model": {...}, "obs_data": "...", "params_for_id_from": "keep"}
The names are checked against the params_for_id, and the step that fits them against its
model, before anything runs. The provenance graph marks the step's box set_by_hand, with the
names and the reason: no value is set by hand, but what is calibrated is. Editing the
params_for_id or the choice reruns keep and what takes from it. The builder's
add_reduction(id, method='manual', parameters=, reason=, params_for_id=).
A reduction is a libcuflynx.sensitivity_analysis.parameter_reduction.ParamReduction, which
can also be used on its own:
from libcuflynx.sensitivity_analysis.parameter_reduction import ParamReduction
ParamReduction.from_options({'method': 'pca'}).reduce(
'sa_results/', 'candidates_params_for_id.json', 'reduction/kept_params_for_id.json')
An emulator can be trained on the kept parameters alone, and MCMC run on it: an emulation
step with "params_for_id_from": "keep", then a calibration with the same
params_for_id_from, "emulator_from" that step and "store_distribution": true.
How values move between models
A value is named by its module and parameter (aortic_root/C, which is C_aortic_root in the
generated model), and moves through the target's names:
- A module array keeps its module names. A value calibrated on
aortic_rootin one model fixesaortic_rootin another, and lands onaortic_rootin the target. When the names differ,module_maprenames the step's modules into the target's. - A library module is generated alone as one module named
mod, so its params_for_id targets aremod/<param>(mod/<submodule>/<param>for a supermodule) and its obs_data operandsmod/<variable>. In the target it is renamed to where it sits: the submodulei_Mof a supermodule target (rho_M_mod__i_Min the model,i_M/rho_Min its parameterisation), or the module of a module-array target that it is.
Each value a step calibrates or sets is recorded in its step_result.json with its module,
param and model_name.
--dry-run checks that every calibrated parameter lands on a module the target has, and prints
where each one lands and what each step is given. After the run, a value with no parameter of
its name in the target is an error. A value passed to a model that lacks its module (an aorta
value into a model without that module) is left out of that model with a warning.
A workflow file whose steps name vessel or vessel_map, or a run whose step_result.json
records name vessel, is refused. Convert it once with
cuflynx-upgrade workflow <workflow file or directory>: given a directory (a study, or a
workflow's output directory), it converts every workflow file and step_result.json below it.
The other checks: a step's files exist; a library module exists in the library, and is in the
target; a target written as a library module names its parameter set with parameterisation
(instance is an error). The schema is libcuflynx/schemas/calibration_workflow.schema.json.
One value per parameter
The target, and every step, is given one value of a parameter. When two steps give the same parameter:
- One takes from the other, directly or through other steps (
fixed_from,start_from,priors_from, ...): the later one's value replaces the earlier one's, with no warning. A step calibrates a parameter itself even whenfixed_fromwould give it a value. Sonka, thenwhole_cellwith"fixed_from": ["nka"], may both fit the same scale:whole_cell's is used. To update an earlier calibration with new data rather than replace it, take the parameter out of the later step's params_for_id and list the earlier step in itspriors_from(below), so the earlier posterior becomes the prior. - One is a
setstep: a value set by hand replaces a calibrated one with no warning, and the provenance marks it set by hand. Between a set step and a step it does not take from, the later in run order is used. Two set steps that do not take from each other (one does not scale the other's value) setting one parameter give a warning, which names the one used. - Neither takes from the other (two calibrations, or combine steps): an error, which
names the parameter, the steps and what they give it to (the target, or a step through its
fixed_fromorresult_from). Add acombinestep, which is its own box in the diagram:
{"id": "best", "kind": "combine", "combine_from": ["from_low", "from_high"],
"combine": {"method": "best_fit"}}
A combine step gives one value for every parameter its inputs give. Later steps take from it
(fixed_from, start_from, result_from, a set step's scale), and the target takes its
values in place of its inputs'. It runs no model. Its step_result.json lists the values
under calibrated, each with combined_from (the inputs that gave it).
best_fittakes every value from the calibration with the lowest cost (chosen_from;costshas each input's). Costs are comparable only between calibrations of the same obs_data with the samecost_type, so anything else is refused; the inputs calibrate the same parameters. Use it for fits of one problem from several starting points.meangives each parameter the mean over the inputs that give it. The inputs may be set steps, and need not give the same parameters.
For the target, the error comes where the target is merged for use: a run of more than one
step, a sweep on_target, and writing the calibrated parameters. Reading the file, --dry-run
(the plan's target_overlap holds the message) and a run of one step (--only) warn instead
and use the later step's value, so a second calibration can be run before the combine step
that settles it is added. A step given two values is always an error.
A step fitting a reduction's choice (params_for_id_from) is checked once the reduction has
run, against what it kept, not against every candidate: the error then comes at the merge,
with every step's result kept, so a run with --stale-only after adding the combine step
runs only that step. A choice made by hand ("method": "manual") is known from the file, so
a step fitting it is checked before anything runs, like any other calibration. The builder's add_combine(id, combine_from, method=).
Outputs
<output_dir>/ --output-dir; default workflow_output/<workflow_name> beside the workflow file
calibration_workflow.json the workflow as run
workflow_result.json order, provenance (input hashes, times, commits, libCellML version), merged parameters
provenance_graph.json how every value was set, for reports and CUFLynx (below)
provenance.svg that graph as a diagram to place in a report
<step_id>/step_result.json its kind; calibrated values, the fixed values and priors it was given, input hashes; an analysis's outputs and the point it analysed (at or nominal; not in fixed)
<step_id>/model/ the generated step model
<step_id>/param_id/ the usual param_id outputs
<step_id>/distribution/ with store_distribution
<step_id>/sensitivity/ a sensitivity step's indices and plots
<step_id>/emulator/ an emulation step's emulator
<step_id>/<step_id>_laplace_*.npy an identifiability step's Laplace mean and covariance (also in step_result.json)
<step_id>/<step_id>_calibrated.cellml a calibration's model with its best fit (a CellML model)
<step_id>/uq/ a uq step's run: its MCMC run directory, or its Laplace mean and covariance
<step_id>/posterior_predictive/ a uq step's posterior predictive check
<step_id>/<step_id>_params_for_id.json a reduction's params_for_id
_target/model/ the target generated with every calibrated value
models/<view>/ a model generated for viewing (WorkflowBuilder.model); no step is named models
<workflow_name>_cuflynx_study.json the study manifest CUFLynx opens (below)
inputs/workflows/<workflow_name>/<yyyy-mm-dd_HHMMSS>/ the workflow packed (--pack layout): every input it was run from
The manifest records the workflow as run, its result, the target and every step (its kind,
model, obs_data, params_for_id, the steps it took something from, its status, run directory and
outputs). It is
updated as each step finishes, so CUFLynx can follow a running workflow. Each step's own
manifest, in <step_id>/param_id/, links back to it. "write_cuflynx_study": false in the
settings turns both off.
The output directory is the workflow's working dir (see
The study working dir): the run packs the workflow into
inputs/workflows/<workflow_name>/<yyyy-mm-dd_HHMMSS>/ (a new dated folder only when the
packed workflow differs from one stored already) and the manifests name the packed copies, by paths relative
to each manifest's folder, so the output directory can be zipped and opened anywhere. A step's
manifest names the same copies (../../inputs/...). The one path left absolute is the
--write-calibrated file, which is written beside the target. "cuflynx_study_copy_inputs":
false in the settings packs nothing and names the inputs where they are.
--pack DIR (or pack_workflow in Python) copies every file the workflow needs to run, and
none of its results, into the new directory DIR: DIR/calibration_workflow.json runs anywhere
and gives the same results. --pack DIR --overwrite (pack_workflow(..., overwrite=True))
replaces an earlier pack in DIR; a directory holding anything a pack does not write is
refused. It holds each step's files under inputs/<step_id>/, the module
versions the workflow uses under modules/ (built-in modules come with libcuflynx), and the
files its settings name under settings/. Paths in settings (external_modules_dir,
*_funcs_external_path) are relative to the workflow file, like its other paths.
--from-step X reruns X and everything after it, reusing the earlier results (and refusing if
their obs_data, params_for_id or parameters changed since); --only X reruns one step.
--write-calibrated writes the merged set beside the target's parameters file, as
<name>_calibrated_parameters.json (<name> is the module array's prefix or the
parameterisation), in the target's nested form: the target's parameters file, completed with
every other value the target's model uses (as its generated <prefix>_parameters.json holds
them, each one's data_reference starting from <parameterisation>:), with each calibrated value set
at its path (<vessel>/<variable> in a module array's file, the module's own path in a
parameterisation's). So the result reproduces the run without the module library. The target's
files are not changed. Each step's generated model, and the target's (_target/), has its own
generated <prefix>_parameters.json: the values that model ran with. workflow_result.json
names the target's as target_model.parameters_path.
Provenance
A run writes provenance_graph.json and provenance.svg when it finishes. The diagram opens a
report: paste the SVG into the page, where it takes the page's text colour. cuflynx-provenance
<output_dir> writes both again, and it needs only the output directory, not the module library.
The graph's schema is libcuflynx/schemas/provenance_graph.schema.json. It is closed, so its
schema_version goes up whenever it gains or changes a node kind, edge style or key, and a
reader (read_provenance_graph, provenance_svg) refuses a version it does not know.
One box stands for each step, in order, with the model source, the measured values, the derived values, the values set by hand, the values calibrated before the run, and the target. Each value the target uses is marked with what set it:
| Mark | What set it | Where it comes from |
|---|---|---|
| calibrated | a step fitted it | the step's results |
| calibrated | an earlier calibration | "origin": "calibrated", which a calibrated parameters file writes; its data_reference names the workflow and step |
| measured | a cited source | "origin": "measured", with the source in data_reference |
| derived | a parameter derivation, from data | "origin": "derived" and "derivation" naming it (tutorial/docs/parameter-derivations.md) |
| inherited | the original model; nothing constrains it | "origin": "inherited" |
| set by hand | us, with a reason | "origin": "set_by_hand" and a required "reason" |
| unclassified | nothing says | no origin |
A "Model source" box stands for the target's model, with an arrow to every step generated from
it; a step whose model is another module array or library module has a source box of its own. A
step's box names, by vessel/param and value, its priors (which step's posterior, and the fitted
kind), the values it calibrated (its parameter count includes those priors_from adds) and the
values earlier steps fixed, each with what set it: calibrated by which step on which obs_data, or
set by hand in which step and why. The target's box names its merged values the same way. A box
shows the first four of each list (six for the target and the model source) and says how many
more the graph file has.
The boxes of values given in the parameters files (measured, derived, set by hand, calibrated before the run) point to the target's model source: those values are in the model of every step generated from it, so each calibration ran with them. When no step comes from that model source, they point to the target.
When a derived value's derivation has fixed_constants, a "Fixed constants of derivations" box
with an arrow to the derived values lists each as <derivation>/<constant> with its value, units
and origin (measured with its source, set by hand with its reason, inherited, or unclassified when
the derivation declares none); it shows the first six and the graph file has them all. The
diagram's footer counts the unclassified constants (1 unclassified constant) after the
unclassified values, whenever there are fixed constants, so none hides behind a zero.
A value is never counted as inherited by default, so an unclassified count above zero says which
values still need describing. workflow_result.json records the libcuflynx commit, the commit of
the repository holding the workflow file, whether tracked files had changed in each, and the
libCellML version. A commit is null outside a repository.
Each step's inputs show as current, stale or missing. A step's result is stale when its
files or settings changed since it ran, or when a step it took something from is stale or ran
again after it, and a later step refuses to reuse it (Run the workflow from ...). A changed
module library is shown and warned about but does not make a step stale, because a library holds
far more than one model uses. A build before the workflow is not tracked.
A figure step is a box like any other step, with a dotted arrow from each step it reads, labelled
with what it reads, and one box under it naming the files it wrote. Its inputs in the graph are
its declaration (settings), its script and each file it lists, each current, stale or
missing.
Figure steps
A figure of a workflow is a step: a Python function in a script file, given the results of the steps it names. libcuflynx loads the results and calls the function, so the figure is drawn by the run, is out of date when anything it reads changes, and is in the provenance diagram and the packed workflow.
{"id": "dose_response", "kind": "figure",
"function": "figures/dose_response.py:draw",
"inputs": {"curves": {"sweep": "sglt1_dose"},
"fit": {"values": "whole_cell"},
"data": {"obs_data": "whole_cell"}},
"files": ["figures/paper_style.py"]}
function is <script>.py:<function>, the script's path relative to the workflow file. Each
entry of inputs is one parameter of the function, by name, and what it is given:
{"<kind>": "<step>"}. The function's parameters are exactly those names and out_dir; this is
checked when the workflow is read, without running the script. files lists other files the
script reads or imports (helpers, a style module beside it).
| Input kind | Read from a | The function gets |
|---|---|---|
sweep |
sweep or simulate step | the arrays of sweep_results.npz as a dict: points, failed, parameters, outputs, features, feature_values, and time_<e>, trace_<e> (points, outputs, times) per experiment; and manifest, sweep_manifest.json as its JSON document |
validation |
simulate step (a sweep of one point) | validation_results.json as its JSON document: items, per prediction item that carries a value its data_item_name, operation, unit, data_type, n_points, rmse, nrmse, mean_abs_z, within_2std, and t, data, std, model at the observation times |
values |
calibration, set or combine step | {"<module>/<parameter>": value}: what it calibrated, set by hand or combined, named as a params_for_id names them (a nested module by its path, heart/lv/E; a global as global/R; a combine step: as the target names them) |
obs_data |
step with an obs_data | the obs_data file as its JSON document |
params_for_id |
step with a params_for_id, or a reduction | the params_for_id it ran with (a reduction: the one it wrote) as its JSON document |
sensitivity |
sensitivity step | Sobol indices, {"S1": {output: {parameter: value}}, "ST": {...}} (empty for a local analysis); and local, {"relative": {output: {parameter: value}}, "absolute": {...}} from a local analysis (sa_options.method: "local"), else None |
progress |
calibration step | the optimiser's history (param_id.run_history.read_run_history): param_labels, cost_history (per generation, best first), param_history_norm (0-1), grad_history, starts (per multi-start: cost, params in actual values), best_cost; and param_mins, param_maxs, the params_for_id bounds |
fit_errors |
calibration step | the best fit's error per data_item, which a calibration writes when it ends: names, percent_error (100 (model - data) / data), std_error ((model - data) / std; a series: averaged over its points) and data_references, in obs_data order |
best_fit |
calibration step | the best fit against its data, from the outputs a calibration saves per experiment it fits (all_outputs_with_best_param_vals_exp_<e>.npz) and its obs_data: items, per data_item its data_item_name, trace_name, data_type, operation, operation_kwargs, plot_type (a constant without one: horizontal), unit, experiment_idx, subexperiment_idx, window (its subexperiment's start and end), value, std, data_reference, t and model (its first operand over its subexperiment; None when the solver did not log it, as Myokit does not log a constant), obs_t (a series: the times of its values) and fit (a constant: the calibrated model's value, from the best fit's std error); and experiment_labels |
mcmc_chain |
calibration with store_distribution |
its MCMC chain: chain, an array (steps, walkers, parameters) cut to the draws every walker reached; param_labels; burn_in_index, the first step after the burn-in its UQ options give |
emulator_validation |
emulation step | the held-out points of emulator_validation.npz in real units: theta (points, parameters), y_true and y_pred (points, features), feature_labels, param_entry_labels; and feature_r2, feature_rmse, feature_nrmse from emulator_metadata.json (None where not recorded) |
distribution |
calibration with store_distribution, or uq step |
{"names": [...], "samples": array (samples, parameters)}, named by the model's names |
laplace |
identifiability step, or uq step with method laplace |
{"parameters": [...], "mean", "covariance", "std"} as arrays |
posterior_predictive |
uq step (with posterior_predictive, the default) |
its posterior predictive check: labels (one per scalar observable), predictions (draws, observables), ground_truth, std and thetas as arrays; coverage, posterior_predictive_coverage.json as its JSON document; and series, when it kept traces, {"meta": {time, observables, segments, experiment_labels}, "traces": {"<segment>|<variable>": array (draws, points)}, "time": {"<segment>": array}}, else None |
profile_likelihood |
identifiability step with method profile_likelihood |
{"nll_threshold_95", "profiles": [{"parameter", "param_values", "costs", "best_val", "best_cost", "ci_95"}]}, the sweeps as arrays |
reduction |
reduction step | its report (param_reduction.json: reduction, selected, ...); for a PCA reduction also modes, [{mode, variance, variance_share, informative, loadings: {feature: value}}], and mode_indices, {"S1": {"mode_<k>": {parameter: value}}, "ST": {...}} (both None for a Sobol reduction) |
The function writes its files into out_dir and returns their paths:
"""Na against the SGLT1 scale, with the fitted value marked."""
import os
import matplotlib.pyplot as plt
def draw(curves, fit, data, out_dir):
scale = curves['points'][:, 0]
sodium = curves['trace_0'][:, 0, -1]
with plt.style.context('seaborn-v0_8-paper'):
figure, axes = plt.subplots()
axes.semilogx(scale, sodium)
axes.axvline(fit['SGLT1/Scale_SGLT1'], linestyle=':')
path = os.path.join(out_dir, 'dose_response.png')
figure.savefig(path, dpi=200)
plt.close(figure)
return [path]
def main(argv=None):
from libcuflynx.calibration_workflow.figures import figure_main
return figure_main(draw, argv)
if __name__ == '__main__':
main()
Rules a figure function follows:
- It runs no simulation. Every simulation is a step with its own protocol (a
sweep, or asimulatestep for one run), so each run is recorded and the figure only reads results. A figure that needs a curve at the calibrated values reads asimulatestep with"on_target": trueorresult_from. - It sets its style inside the function. The function is called with Matplotlib's settings as the rc file gives them, whatever was drawn or imported before, so the figure does not depend on what ran before it. Settings changed at the top of the script do not reach the call.
- It has a
main, as above, so the script also runs on its own on a finished run, through the same loaders and so with the same objects:
python figures/dose_response.py <run directory> [--step dose_response] [--out-dir DIR]
python figures/dose_response.py <run directory> --input curves=sweep:sglt1_dose \
--input fit=values:whole_cell --input data=obs_data:whole_cell
The first form draws the run's figure step that names this script (--step picks one of
several); the second gives the inputs directly. Both give the files the workflow gives: the
same file names, images equal pixel by pixel and other files byte for byte
(libcuflynx.calibration_workflow.figures.output_differences(dir_a, dir_b) lists any
difference, for a test of your own scripts). figure_main takes one function or a list of the
script's figure functions.
The files are in <step_id>/figure/, listed under figures in the step's step_result.json. A
figure step is out of date when its script, a file in files or its declaration changed, or a
step it reads ran again after it. Every run draws the figure steps that are out of date and
whose inputs are current, after its other steps, whatever --from-step or --only say;
--only <figure step> draws that one regardless. A figure whose inputs are out of date waits.
A figure that fails does not stop the other figures or the merge: its error is raised once the
run's results are written. Figure steps pass nothing on, so the calibrated parameters file does
not wait for them, and adding or changing a figure step after a run leaves the other steps
current. pack_workflow copies each script with its files into figures/<step_id>/.
Standard figures
libcuflynx ships a script of standard figures, one function per figure. Copy it beside the workflow and name its functions in figure steps; the copy is the workflow's own script, hashed and packed like any other, so a later libcuflynx does not change a finished run's figures:
from libcuflynx.calibration_workflow.figures import write_standard_figures
write_standard_figures('figures') # figures/standard_figures.py; an existing copy is kept
{"id": "z_traces", "kind": "figure",
"function": "figures/standard_figures.py:sweep_traces",
"inputs": {"sweep": {"sweep": "scan"}}}
The input names are the function's parameters:
| Function | Draws | Inputs |
|---|---|---|
sweep_traces |
per experiment, every output over time, a line per point (traces_exp_<e>.png) |
sweep: sweep |
sweep_features |
each feature against the swept parameters, as the sweep step draws them | sweep: sweep |
prediction_plots |
the obs_data's prediction_plots, from a simulate step run on that obs_data; a time-course plot's output must be among the step's outputs |
simulation: sweep, obs_data: obs_data |
validation |
the held-out prediction items against the model: validation_scores.csv (per item n_points, rmse, nrmse, mean_abs_z, within_2std), the scalar items' data ± std against the model with y = x (validation_parity.png), and per series item the data ± std and the model from the start of its sub-experiment (validation_<item>.png) |
validation: validation |
protocol_inputs |
per experiment each params_to_change entry over the logged time: a number held over its sub-experiment, a trace or shape from the sub-experiment's start (inputs_exp_<e>.png) |
obs_data: obs_data |
sobol_indices |
S1 and ST per output (sobol_<output>.png) and an ST heatmap |
sensitivity: sensitivity |
local_sensitivity |
a heatmap of a local analysis's relative sensitivities, parameters by outputs (local_sensitivity_heatmap.png) |
sensitivity: sensitivity |
pca_modes |
per PCA mode its loading on each feature and the ST of each parameter (pca_mode_<k>.png), and ST per mode (pca_mode_ST_heatmap.png) |
reduction: reduction |
calibration_progress |
the best cost per generation on a log axis, with the band up to the worst recorded best cost (a genetic algorithm's top 10), or a line per start (cost_history.png); each parameter normalised by its bounds per generation (param_history.png) |
progress: progress |
best_fit |
per trace a data_item is measured on and experiment, as the calibration draws it (best_fit_<trace>_exp_<e>.png): the model's trace over the subexperiments its items read; a constant as a dashed line at its data over a ±1 std band and a solid line at the model's value (horizontal; horizontal_from_min from the trace's minimum; vertical a time); a series as its values with ±1 std bars. Units in m3, m3_per_s and J_per_m3 are drawn in cm^3, cm^3/s and kPa |
fit: best_fit |
mcmc_diagnostics |
per parameter each walker's trace (mcmc_chain.png), its running mean from step 0 and from the burn-in (mcmc_cumulative_mean.png), and its autocorrelation against lag with guides at ±0.1, titled "within" or "still correlated" over the last 20% of lags (mcmc_autocorrelation.png); at most 12 walkers and 400 steps drawn |
chain: mcmc_chain |
emulator_validation |
per feature the emulator against the simulator at the held-out points, with y = x, R2 and NRMSE (emulator_parity.png); per feature the normalised residual against each parameter (emulator_residuals_<feature>.png) |
emulator: emulator_validation |
posterior |
per parameter a histogram, its mean and 5-95% band (posterior.png) |
distribution: distribution |
laplace |
per parameter the normal density over ±4 std (laplace.png) |
laplace: laplace |
The calibration fit plot and the error bars per observable are not among them yet: a calibration step does not save its best-fit outputs or error vectors.
A workflow's older external_figures key (commands that libcuflynx recorded but never ran) is
refused: write each as a figure step. A script may call other software itself if it must.
Distributions and priors
With "store_distribution": true (and UQ_options in the settings) a step runs MCMC after its
fit and stores distribution/: the raw chain.npy, the post-burn-in samples.npy, stats.json
(means, standard deviations, quantiles, covariance) and a manifest. In Python:
from libcuflynx.calibration_workflow import StoredDistribution
d = StoredDistribution.load('wf_out/M-type-K-channel')
d.sample(1000, rng=0) # draws, shape (1000, n_params)
d.logpdf(x) # log density at a parameter vector
d.marginal('rho_M_mod') # one parameter's samples
d.mapped_into('i_M').names # named as in the supermodule: ['rho_M_mod_i_M']
A later step lists it in priors_from, either by id or as
{"step": "M-type-K-channel", "kind": "mvnormal", "inflate": 1.0, "parameters": [...]}. parameters
picks some of the stored parameters, by their names in the earlier step's model (rho_M_mod;
its step_result.json lists them as calibrated[].model_name); without it, all of them. Those parameters
are then calibrated again in the later step, with the stored posterior as a prior over all of
them jointly. kind is how the samples are represented, each on a scale on which the parameter's
bounds are unbounded (logit for [min, max], log for a lower bound only), so the density respects
the bounds and can follow a skewed posterior:
kind |
Representation | When |
|---|---|---|
mvnormal (default) |
multivariate normal: means and full covariance | keeps correlations; exact and cheap |
normal |
independent normals | when correlations should be dropped |
kde |
Gaussian kernel density estimate | non-Gaussian posteriors with few (≲5) parameters |
inflate multiplies the variance, to temper an overconfident earlier posterior. A prior only
shapes the log posterior, so a step with priors_from must either sample it
(store_distribution) or optimise it (optimiser_options.objective_function: likelihood, the
genetic algorithm). In the first case its reported values are the posterior medians, since the
optimiser's best fit ignores the prior (step_result.json says which: point_estimate).
Expected outcome
You should have a calibrated model in generated_models/[file_prefix]_[obs_file_name]/ and plots in param_id_output/.
Troubleshooting
- If you see
params_for_id_path ... does not exist, confirmparams_for_id_fileorfile_prefixand yourresources_dir. - If you see
obs_dt is required for series entries, addobs_dtto each series data item inobs_data.json. - If MPI errors occur, ensure OpenMPI/MPICH is installed and
mpi4pyis available in your environment (pip install "libcuflynx[mpi]").