Skip to content

Parsers & generators (internal)

Note

These classes are internal building blocks used by the public entry points. They are documented for completeness and for advanced workflows, but their interfaces may change between releases. Prefer the entry points on the Overview page where possible.

Parsers

libcuflynx.parsers.ModelParsers.CSV0DModelParser

CSV0DModelParser(inp_data_dict, parameter_id_dir=None)

Bases: object

Creates a 0D model representation from a vessel and a parameter CSV files.

split_0d_1d_module_array

split_0d_1d_module_array(
    supermodule_registry=None, component_registry=None
)

Writes the 0D and 1D parts of the module array (JSON or CSV, either layout, with its supermodule instances expanded) to vessel_filename_0d and vessel_filename_1d, as CSV. Returns the default parameter rows of the supermodules and parameterisations (see config_schemas.load_module_array).

libcuflynx.parsers.PrimitiveParsers.YamlFileParser

YamlFileParser()

Bases: object

Parses Yaml files

Constructor

Generators

libcuflynx.generators.CVSCellMLGenerator.CVS0DCellMLGenerator

CVS0DCellMLGenerator(model, inp_data_dict)

Bases: object

Generates CellML files for the 0D model represented in @

Constructor

create_unit_converter_component

create_unit_converter_component(
    name,
    input_var,
    output_var,
    scale_factor,
    units_in,
    units_out,
)

Returns a CellML component string that converts input_var (units_in) to output_var (units_out) using the given scale_factor.

add_converter_component

add_converter_component(converter_component_str)

Stores the converter component string for later writing to the CellML file.

get_variable_unit_from_component

get_variable_unit_from_component(
    component_name, variable_name
)

Given a component (module) name and variable name, return the unit name as a string.

libcuflynx.generators.PythonGenerator.PythonGenerator

PythonGenerator(
    cellml_path,
    output_dir=None,
    module_name=None,
    human_readable=True,
    casadi_compat=False,
    aadc_compat=False,
)

Generate a Python module from a CellML file.

Usage

gen = PythonGenerator('model.cellml', output_dir='out') py_path = gen.generate()

generate

generate()

Generate Python code and return the output file path.

Protocol execution

libcuflynx.protocol_runners.protocol_executor.ProtocolExecutor

ProtocolExecutor(sim_helper)

Core multi-experiment / multi-subexperiment protocol simulation loop.

Parameters

sim_helper : SimulationHelper Any solver-wrapper instance (myokit, libopencor, python, casadi). The caller retains ownership; ProtocolExecutor does not close it.

run_protocol

run_protocol(
    protocol_info,
    id_param_names=None,
    id_param_vals=None,
    result_variables=None,
    extra_result_variables=None,
    exp_indices=None,
    continue_on_failure=False,
    reset_after_experiment=True,
)

Run the multi-experiment / multi-subexperiment protocol loop.

Parameters

protocol_info : dict Must contain: - 'sim_times' list[list[float]] — sim duration per (exp, sub) - 'pre_times' list[float] — pre-simulation time per exp - 'params_to_change' dict — {param_name: [[val_exp0_sub0, ...], ...]} May also contain pre-computed keys added by process_protocol_and_weights: - 'num_experiments' int - 'num_sub_per_exp' list[int] Both are derived from sim_times when absent. id_param_names : list, optional Parameter names set once before each experiment (e.g. ID candidates). id_param_vals : list, optional Values matching id_param_names. result_variables : list, optional Variables to retrieve per sub-experiment via get_results(). None → collect all variables via get_all_results(flatten=True). extra_result_variables : list, optional A second variable set collected in the same pass (e.g. pred_names). exp_indices : iterable, optional Only run these experiment indices. Other slots in the output will be absent from results_by_sub / extra_by_sub, and None in t_by_exp. continue_on_failure : bool, default False If True, record None for failed sub-experiments and continue rather than returning early. If False (default), return immediately on the first simulation failure. reset_after_experiment : bool, default True If True (default), call sim_helper.reset_and_clear() after the final sub-experiment of each experiment. Pass False for AD (automatic differentiation) mode where the solver state must be preserved across experiments.

Returns

success : bool False only when a simulation failed AND continue_on_failure is False. results_by_sub : dict Mapping (exp_idx, sub_idx) → result of get_results() or get_all_results(flatten=True). None for failed sub-experiments when continue_on_failure is True. extra_by_sub : dict Same structure for extra_result_variables. Empty dict when extra_result_variables is None. t_by_exp : list[np.ndarray | None] Concatenated, pre_time-shifted time vector per experiment index. None for skipped or failed experiments.

Inner param-id engine

libcuflynx.param_id.paramID.ParamID

ParamID(
    model_path,
    param_id_method,
    obs_info,
    param_id_info,
    protocol_info,
    prediction_info,
    solver_info,
    dt=0.01,
    optimiser_options=None,
    do_ad=False,
    DEBUG=False,
    model_type=None,
    operation_funcs_external_path=None,
    cost_funcs_external_path=None,
    use_emulator=False,
    emulator_dir=None,
    emulator_settings=None,
)

Class for doing parameter identification on simulated models

set_calibrated_entries

set_calibrated_entries(labels)

Calibrate only the params_for_id entries labels (as param_entry_labels names them); run holds every other entry at its value in the model. None calibrates every entry.

The cost is still this param_id's, at the full vector (HeldEntries), so the backend sees the parameter set it was built for: an emulator trained on every entry is calibrated over some of them. best_param_vals and best_param_vals.npy are the full vector, with the held entries at their held values; held_entries records them. A held value must be inside the entry's bounds.

save_all_outputs_per_experiment

save_all_outputs_per_experiment(param_vals, suffix='')

Simulate each experiment with param_vals and save all model variables to NPZ.

Parameters

param_vals : array-like Parameter values to apply before each per-experiment simulation. suffix : str Inserted before .npz (e.g. "_plot" for plot-time dumps).

make_optimiser

make_optimiser(
    cost_obj,
    param_id_info,
    param_norm_obj,
    output_dir,
    optimiser_options=None,
)

The param_id_method optimiser over cost_obj, configured as this run's.

Parameters:

Name Type Description Default
cost_obj

What the optimiser calibrates: this ParamID, or an object with the same get_cost, get_cost_from_params, get_gradient, get_lnlikelihood_lnprior_from_params, param_init and set_best_param_vals over its own parameter vector (as profile likelihood's held-entry cost does).

required
param_id_info

param_names, param_mins and param_maxs of that vector.

required
param_norm_obj

Its Normalise_class.

required
output_dir

Where the optimiser writes its history (None on ranks other than 0). None on every rank writes no files (profile-likelihood points).

required
optimiser_options

Defaults to this run's optimiser_options.

None

set_joint_priors

set_joint_priors(joint_priors)

Add log densities over several parameters to the log prior.

joint_priors is a list of (names, logpdf): names are generated-model parameter names (param_names_for_gen, e.g. g_leak_mod_i_leak_Na), one per calibrated parameter the density is over, and logpdf(values) takes those parameters' values, in that order, and returns a log density (-inf outside its support). It is added to the per-parameter priors, whose bounds checks still apply -- so a parameter with a joint prior is usually given a uniform row in params_for_id.

Used by calibration workflows to make an earlier step's stored posterior the prior of a later one (libcuflynx.calibration_workflow). Like every prior, it only affects the log posterior: MCMC, and optimisers run with objective_function 'likelihood'.

get_lnlikelihood_lnprior_from_ensemble

get_lnlikelihood_lnprior_from_ensemble(ensemble)

Log-posterior for a whole ensemble, predicting the surrogate once for all of it.

The saving is entirely in the emulator call. Evaluating a fitted regressor at sixty-four points costs barely more than at one -- 84.8 ms against 355 ms on the study this was written for, 15x less per point -- because the per-call overhead dominates the arithmetic. An ensemble sampler asks for its whole population at every step, so it is exactly the caller that can pay that overhead once.

Everything after the prediction is unchanged and still per-walker: the protocol loop, the cost reduction, the priors. Only the surrogate is batched, which is the part that was expensive.

Walkers whose prior is not finite are dropped before the prediction rather than after. They contribute nothing but would still cost a row in the batch, and an out-of-bounds row is exactly what out_of_bounds='error' refuses -- so predicting them would turn a walker that is merely being rejected into a failed run.

cross_segment_reference_items

cross_segment_reference_items()

data_items whose operation_kwargs reference an item in another (exp, sub).

Returns a list of (referencing_name, referenced_name). Empty for the ordinary case where every reference stays inside its own sub-experiment.

accumulating_temp_results

accumulating_temp_results()

One temp_results table across every segment of a single cost evaluation (#466).

Only the cost loop wants that. Every other caller evaluates one segment on its own -- CUFLynx's obs_cost, plot_outputs, the gradient backends, a test double -- and must not resolve a reference against values left behind by whatever ran before it. evaluating_segment gives those callers a fresh table, and this is how it knows not to.

obs_output_dicts_per_segment

obs_output_dicts_per_segment(
    operands_outputs_list, get_all_series=False
)

get_obs_output_dict for every segment, in order, with one temp_results table.

operands_outputs_list is indexed like get_cost_and_obs_from_params's operands (flat over experiments, then sub-experiments). Each item's value is right in its own segment's dict, including an item that references an item in an earlier segment, as in the cost. Returns a list of dicts (with get_all_series, a list of (dict, all_series)); a segment with no operands gives None ((None, None)).

evaluating_segment

evaluating_segment(exp_idx, sub_idx)

Mark which (experiment, sub-experiment)'s operands the next evaluations receive.

Carried as state rather than passed to get_obs_output_dict, so that method keeps the signature every other caller already uses -- the gradient backends, plot_outputs, CUFLynx, and any test double that stands in for it. Adding parameters to it broke all of those for no gain.

Inside the block an item is only evaluated and recorded when the segment is its own, and temp_results is left alone so the caller can accumulate one table across the whole protocol. Outside it -- the default -- every item is evaluated against whatever operands are handed over and the table is cleared per call, which is the pre-#466 behaviour.

get_obs_output_dict

get_obs_output_dict(
    operands_outputs,
    get_all_series=False,
    is_symbolic=False,
)

Evaluate every data_item's operation against one sub-experiment's operands.

    ``temp_results`` is the table an ``operation_kwargs`` reference to another item resolves
    against. It used to be cleared on every call, i.e. once per (experiment, sub-experiment),
    which is why a reference could only ever see the segment being evaluated (#466, #127).
    Two arguments change that:

A caller that steps through the segments in order does so inside evaluating_segment, which says which segment these operands belong to and leaves the table alone so it accumulates across all of them.

    Knowing the segment matters because every data_item is evaluated against every one of
    them -- which item *counts* is decided afterwards by the zeroed weight vectors. Without
    it an item would be recorded under its name from some other experiment's trace, and a
    cross-segment reference would silently read that.

build_casadi_functions

build_casadi_functions(
    param_names, param_vals=None, get_all_series=False
)

Build (and cache) the CasADi cost/gradient/observable Functions. See param_id.casadi_backend.build_functions.

get_jac_cost_ca

get_jac_cost_ca(param_vals)

Gradient dJ/dp from the CasADi symbolic graph. See param_id.casadi_backend.get_jac_cost.

get_cost_ca

get_cost_ca(param_vals)

Cost J(p) from the CasADi symbolic graph. See param_id.casadi_backend.get_cost.

fsa_gradient_available

fsa_gradient_available()

True when this run can produce an analytic gradient via Myokit CVODES FSA. See param_id.fsa_backend.gradient_available.

get_jac_cost_fsa

get_jac_cost_fsa(param_vals, return_cost=False)

Gradient dJ/dp via Myokit CVODES forward sensitivity, optionally with the cost from the same solve. See param_id.fsa_backend.get_jac_cost.

get_cost_and_jac_fsa

get_cost_and_jac_fsa(param_vals)

(cost, gradient) from a single Myokit CVODES FSA solve. See param_id.fsa_backend.get_cost_and_jac.

get_cost

get_cost(param_vals)

Compute cost J(p), dispatching to the emulator, CasADi, AADC or numpy.

get_gradient

get_gradient(param_vals)

Compute gradient ∇J(p), dispatching to the emulator, CasADi, AADC, or Myokit FSA.

get_observable_sensitivities

get_observable_sensitivities(
    param_vals, gradient_method=None, fd_rel_step=None
)

d(observable feature)/d(param) for the scalar observables -- the backend-agnostic local-sensitivity accessor, parallel to get_gradient.

Returns {observable_label: {param_name: d(feature)/d(param)}}, dispatching by model_type to the same analytic machinery the cost gradient uses: the CasADi jacobian of the observable vector, or the Myokit CVODES sensitivities with a directional derivative of the feature. Every arm reports the identical quantity, so a local sensitivity analysis is comparable across backends whichever computed it.

gradient_method selects how, in the same FD/AD/FSA vocabulary as gradient_sources() and the Laplace gradient_source -- the arm's own name, so a front-end can offer it, disable it, and report back which one ran:

  • None / 'auto' (default) -- the analytic arm for this backend, raising when there is none. Deliberately still not a silent fall back to FD: a result quietly computed a different way, at a different cost and accuracy, is not the same result.
  • 'AD' -- the exact CasADi jacobian; requires model_type='casadi_python' (aadc_python names its arm AD too, but its local SA is not implemented yet and says so). Any other backend raises naming the mismatch rather than silently reinterpreting.
  • 'FSA' -- Myokit CVODES forward sensitivities; requires cellml + CVODE_myokit + do_ad. Raises naming exactly what is missing otherwise.
  • 'FD' -- central finite differences (param_id.fd_backend). Works on any backend that runs a forward simulation, which is how AADC and the plain scipy backend get a local SA at all (issue #338). Costs 2M simulations for M parameters.

fd_rel_step is the FD step, relative to each parameter, and is ignored by the analytic arms. It matters more than it looks: on Lotka-Volterra, moving it from 1e-3 to 1e-2 changes a sensitivity coefficient by up to 48%, because max of an oscillating trace is a rough functional. So it is the caller's to choose, not a constant buried in the backend -- the same reason the prior hyper-parameters stopped being hardcoded.

get_cost_and_gradient

get_cost_and_gradient(param_vals)

Return (cost, gradient) in one evaluation.

L-BFGS-B needs both J(p) and ∇J(p) at every point it visits. For the Myokit CVODES FSA path a single augmented solve yields both, so this avoids the separate cost solve the optimiser would otherwise do. Other backends fall back to separate calls (CasADi's reverse pass and the AADC tape are cheap, so there is little to merge there).

get_cost_aadc

get_cost_aadc(param_vals)

J(p) evaluated on the AADC tape.

This must be the cost an AADC-gradient optimiser minimises. The forward solver and the tape do not integrate the same way -- the tape has to replay a fixed sequence of operations, so it uses a fixed-step scheme, while sim_helper.run() may use an adaptive one -- and the tape's cost is a separate implementation of the cost function. Taking J(p) from get_cost_from_params and dJ/dp from the tape therefore hands L-BFGS-B the gradient of a different function than the one it is minimising, which breaks the line search. Measured on Lotka-Volterra, that mismatch gave AD/FD ratios of [1.79, 1.96, 1.32, -0.067] -- the last one has the wrong sign.

get_obs_ca

get_obs_ca(param_vals, get_all_series=False)

Observables evaluated through the CasADi graph, in the same shape the numpy path returns. See param_id.casadi_backend.get_obs.

simulate_once

simulate_once(
    param_vals=None,
    reset=True,
    only_one_exp=-1,
    return_series=False,
)

Setting reset to False and only_one_exp to the experiment number you want to use allows you to use the simulation helper object to investigate all parameters.

This can be used with reset=False and only_one_exp set to the experiment number to have the simulation helper object open and ready to investigate the parameters.

if param_vals is not set, then the best_param_vals will be used.

Parameters:

Name Type Description Default
only_one_exp int

If the user wants to only simulate one experiment change this to the experiment number. Defaults to -1.

-1
reset bool

if you want to reset the simulation after running. Gets changed to True for num_experiments > 1. Defaults to True.

True

libcuflynx.param_id.paramID.MCMC

MCMC(
    model_path,
    obs_info,
    param_id_info,
    protocol_info,
    prediction_info,
    solver_info,
    dt=0.01,
    UQ_options=None,
    DEBUG=False,
    model_type=None,
    use_emulator=False,
    emulator_dir=None,
    emulator_settings=None,
)

Bases: ParamID

Class for doing mcmc on simulated models

TODO check the parallelisation for this mcmc

from_param_id classmethod

from_param_id(engine, UQ_options=None)

Adopt an already-built ParamID instead of constructing a second one.

Building an engine compiles the model. Because mcmc_instead selects the inner class at construction time, a UQ run following a calibration had to build a second CVS0DParamID and pay that compile again (CUFLynx #217) -- for the same model, the same obs_info and the same parameters.

MCMC only adds to ParamID, so the built engine's state is exactly what it needs: adopt its __dict__ (simulation helper, parsed infos, output_dir, and the best_param_vals of the calibration that just ran, which is what seeds the walkers) and then run only the MCMC-specific tail.

The result shares the engine's simulation helper rather than copying it -- that is the point -- which is safe because UQ follows a calibration rather than running beside it. Do not use the engine concurrently afterwards.

calibration_weighting

calibration_weighting()

Evaluate costs inside this block with the obs_data weights, not the flat ones.

The flattening exists for the likelihood being sampled: a weighted likelihood is not a posterior (#193). It must not follow the cost out into the artifacts, because best_cost is a calibration artifact -- plot_param_id and simulate_once re-derive it and compare against the saved value, and the calibration itself optimised the weighted cost. A best_cost written on the flat scale is simply a different quantity under the same name, and the two disagree by whatever the weights were (measured on 3compartment: 0.0377 saved against 0.1058 recomputed, which tripped simulate_once's consistency check).

can_vectorise_the_ensemble

can_vectorise_the_ensemble()

Whether the whole walker population can be evaluated in one call.

Two conditions, and both are about what the likelihood is:

  • The forward model has to be a surrogate. Batching wins because a fitted regressor costs almost the same at sixty-four points as at one; a solver integrates sixty-four times either way and gains nothing, while losing the worker pool that was genuinely parallelising it.
  • The sampler has to advance a whole ensemble at once and accept a vectorised log-probability. emcee and zeus both do; pyMC has no such hook and parallelises in the opposite direction, by giving each rank chains of its own.

sampler_needs_a_worker_pool

sampler_needs_a_worker_pool()

Whether this backend parallelises across ranks by farming out the likelihood.

The two backends parallelise in opposite directions, and running one arrangement under the other hangs:

  • emcee and zeus advance one ensemble in one process. The parallelism is the likelihood: the sampler is handed a schwimmbad.MPIPool, and every other rank sits in pool.wait() serving evaluations until the master closes the pool.
  • pyMC has no such hook. PyMCSampler instead gives each rank chains_for_rank(...) chains of its own and gathers them along the walker axis at the end -- which means every rank must reach run_mcmc, and its comm.Barrier() and comm.gather are collectives over COMM_WORLD.

Opening a pool for pyMC therefore deadlocked every mpiexec -n >1 UQ run with library: pymc: the workers were parked inside pool.wait(), blocked in a receive that only the master's pool.close() ends, so they could never join the master's barrier -- and the master waits on that barrier forever, holding the pool open. Neither side can move, and the run hangs after sampling with no error and no chain written. It was never seen because nothing exercised it: the pyMC tests run on one rank, where this branch is not taken at all.

mcmc_chain_path

mcmc_chain_path()

Where the chain is written -- the same path during the run as at the end of it.

Deliberately one file rather than a partial one that is renamed at the end: everything that reads a chain (load_mcmc_chain, the plotters, a front-end) then needs no notion of "the run has finished", and a run that is cancelled or killed leaves its chain exactly where the tooling already looks for it.

burn_in_index

burn_in_index(num_steps)

The first step to keep, from UQ_options['burn_in'].

A value below 1 is a fraction of the chain; 1 or above is a number of steps. Defaults to half the chain, which is what this used to hardcode. Always leaves at least one step, so a burn_in longer than the run degrades to "keep the last sample" rather than producing an empty array and a stack of nan statistics.

flat_param_names

flat_param_names()

One name per calibrated parameter, for labelling the statistics.

A grouped row calibrates one value shared across several model variables, so it is one parameter with several names; the first stands for the group, as it does elsewhere.

posterior_statistics

posterior_statistics(flat_samples)

Per-parameter summary of the posterior, plus the cost at its point summaries.

A posterior is a distribution, and the honest summary of one is a spread rather than a single number -- so mean and median and the quartiles and the 95% interval, not a winner. The costs are reported for comparison with the calibration's best, deliberately without acting on that comparison: see save_mcmc_statistics.

calibration_best_cost

calibration_best_cost()

The calibration's best cost as a finite float, or None if there isn't one.

Prefers the value on disk: a UQ run is often handed the calibration's parameters (set_best_param_vals) without its cost, leaving the in-memory best_cost at inf. Reporting inf would put a JSON Infinity in the file -- which strict JSON parsers reject -- and make every posterior median look like it had beaten the calibration.

save_mcmc_statistics

save_mcmc_statistics(flat_samples)

Write mcmc_statistics.json, and leave the calibration's best fit alone.

This used to overwrite best_param_vals.npy and best_cost.npy with the posterior median whenever that median scored a lower cost. Two different estimators were being conflated: a posterior median summarises a distribution, a calibration best is an argmin, and they answer different questions. Silently replacing one with the other meant a UQ run mutated the calibration's answer -- and the file gave no clue which estimator it held.

The comparison is still reported, because it is genuinely informative (a median that beats the optimum usually means the calibration stopped early, or that the posterior is skewed), but nothing is decided on it. Choosing between the two is the user's call, and both are now on disk to choose from.

The one exception is a UQ run with no calibration behind it at all: nothing else has written a best fit, so the median is the only estimate there is, and the rest of the pipeline (plotting, predictions) needs one. That is recorded in the file's source.

save_posterior_point_estimates

save_posterior_point_estimates(medians, means)

Write the posterior median and mean as loadable parameter sets.

mcmc_statistics.json already records both, but keyed by display name (g_{Na}) and buried in a per-parameter summary alongside quartiles. That is a report, not a parameter set: nothing can feed it back into a model, because the display names are not the model's and the file's shape is not one any parameter loader reads.

The consequence is that save_mcmc_statistics promises "both are now on disk to choose from" while only one of the two -- best_param_vals.npy -- is actually in a form anything can load. Choosing the median meant reading the JSON and retyping fourteen numbers, and that matters, because a calibration best is an argmin found by whatever surrogate drove it and can sit somewhere the model behaves quite differently. One SN_full cpvt run put its "best fit" at a resting potential of -19 mV against data at -75; the posterior median from the same chain sat at -80.

So, beside the JSON:

  • posterior_median_params.csv -- vessel_name,param_name,value, the format CUFLynx's parameter loader reads. Self-describing, so it does not depend on column order matching the model that loads it.
  • posterior_median_param_vals.npy -- the bare array in optimiser order, the same shape as best_param_vals.npy, for anything that reads that.

And the same pair for the mean, because the two costs are reported side by side and a reader invited to compare them should be able to load either.

A modifier slot names several model parameters and holds one value, so every member is written with that value -- matching how best_param_vals.npy is read back.