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

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.

parsers.PrimitiveParsers.YamlFileParser

YamlFileParser()

Bases: object

Parses Yaml files

Constructor

Generators

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.

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

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, opencor, 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

param_id.paramID.OpencorParamID

OpencorParamID(
    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,
)

Class for doing parameter identification on opencor models

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).

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 CasADi or AADC or numpy.

get_gradient

get_gradient(param_vals)

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

get_observable_sensitivities

get_observable_sensitivities(param_vals)

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. Both arms report the identical quantity so a local sensitivity analysis is backend-consistent. There is no finite-difference fallback -- backends without an analytic sensitivity raise, pointing at global Sobol SA instead.

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

param_id.paramID.OpencorMCMC

OpencorMCMC(
    model_path,
    obs_info,
    param_id_info,
    protocol_info,
    prediction_info,
    solver_info,
    dt=0.01,
    mcmc_options=None,
    DEBUG=False,
    model_type=None,
)

Bases: OpencorParamID

Class for doing mcmc on opencor models

TODO check the parallelisation for this mcmc