amici.de_export

C++ Export

This module provides all necessary functionality specify an DE model and generate executable C++ simulation code. The user generally won’t have to directly call any function from this module as this will be done by amici.pysb_import.pysb2amici(), amici.sbml_import.SbmlImporter.sbml2amici() and amici.petab_import.import_model().

Functions

apply_template(source_file, target_file, ...)

Load source file, apply template substitution as provided in templateData and save as targetFile.

get_function_extern_declaration(fun, name, ode)

Constructs the extern function declaration for a given function

get_model_override_implementation(fun, name, ode)

Constructs amici::Model::* override implementation for a given function

get_sunindex_extern_declaration(fun, name, ...)

Constructs the function declaration for an index function of a given function

get_sunindex_override_implementation(fun, ...)

Constructs the amici::Model function implementation for an index function of a given function

is_valid_identifier(x)

Check whether x is a valid identifier for conditions, parameters, observables.

remove_argument_types(signature)

Strips argument types from a function signature

smart_is_zero_matrix(x)

A faster implementation of sympy's is_zero_matrix

smart_jacobian(eq, sym_var)

Wrapper around symbolic jacobian with some additional checks that reduce computation time for large matrices

smart_multiply(x, y)

Wrapper around symbolic multiplication with some additional checks that reduce computation time for large matrices

var_in_function_signature(name, varname, ode)

Checks if the values for a symbolic variable is passed in the signature of a function

Classes

DEExporter(de_model[, outdir, verbose, ...])

The DEExporter class generates AMICI C++ files for a model as defined in symbolic expressions.

DEModel([verbose, simplify, cache_simplify])

Defines a Differential Equation as set of ModelQuantities.

TemplateAmici(template)

Template format used in AMICI (see string.Template for more details).

class amici.de_export.DEExporter(de_model, outdir=None, verbose=False, assume_pow_positivity=False, compiler=None, allow_reinit_fixpar_initcond=True, generate_sensitivity_code=True, model_name='model')[source]

The DEExporter class generates AMICI C++ files for a model as defined in symbolic expressions.

Variables
  • model – DE definition

  • verbose – more verbose output if True

  • assume_pow_positivity – if set to true, a special pow function is used to avoid problems with state variables that may become negative due to numerical errors

  • compiler – distutils/setuptools compiler selection to build the Python extension

  • functions – carries C++ function signatures and other specifications

  • model_name – name of the model that will be used for compilation

  • model_path – path to the generated model specific files

  • model_swig_path – path to the generated swig files

  • allow_reinit_fixpar_initcond – indicates whether reinitialization of initial states depending on fixedParameters is allowed for this model

  • _build_hints – If the given model uses special functions, this set contains hints for model building.

  • generate_sensitivity_code – Specifies whether code for sensitivity computation is to be generated

Note

When importing large models (several hundreds of species or parameters), import time can potentially be reduced by using multiple CPU cores. This is controlled by setting the AMICI_IMPORT_NPROCS environment variable to the number of parallel processes that are to be used (default: 1). Note that for small models this may (slightly) increase import times.

__init__(de_model, outdir=None, verbose=False, assume_pow_positivity=False, compiler=None, allow_reinit_fixpar_initcond=True, generate_sensitivity_code=True, model_name='model')[source]

Generate AMICI C++ files for the DE provided to the constructor.

Parameters
  • de_model (amici.de_export.DEModel) – DE model definition

  • outdir (typing.Union[pathlib.Path, str, None]) – see amici.ode_export.DEExporter.set_paths()

  • verbose (typing.Union[bool, int, None]) – verbosity level for logging, True/False default to logging.Error/logging.DEBUG

  • assume_pow_positivity (typing.Optional[bool]) – if set to true, a special pow function is used to avoid problems with state variables that may become negative due to numerical errors

  • compiler (typing.Optional[str]) – distutils/setuptools compiler selection to build the python extension

  • allow_reinit_fixpar_initcond (typing.Optional[bool]) – see amici.ode_export.DEExporter

  • generate_sensitivity_code (typing.Optional[bool]) – specifies whether code required for sensitivity computation will be generated

  • model_name (typing.Optional[str]) – name of the model to be used during code generation

compile_model()[source]

Compiles the generated code it into a simulatable module

Return type

None

generate_model_code()[source]

Generates the native C++ code for the loaded model and a Matlab script that can be run to compile a mex file from the C++ code

Return type

None

set_name(model_name)[source]

Sets the model name

Parameters

model_name (str) – name of the model (may only contain upper and lower case letters, digits and underscores, and must not start with a digit)

Return type

None

set_paths(output_dir=None)[source]

Set output paths for the model and create if necessary

Parameters

output_dir (typing.Union[pathlib.Path, str, None]) – relative or absolute path where the generated model code is to be placed. If None, this will default to amici-{self.model_name} in the current working directory. will be created if it does not exist.

Return type

None

class amici.de_export.DEModel(verbose=False, simplify=<function _default_simplify>, cache_simplify=False)[source]

Defines a Differential Equation as set of ModelQuantities. This class provides general purpose interfaces to compute arbitrary symbolic derivatives that are necessary for model simulation or sensitivity computation.

Variables
  • _differential_states – list of differential state variables

  • _algebraic_states – list of algebraic state variables

  • _observables – list of observables

  • _event_observables – list of event observables

  • _sigma_ys – list of sigmas for observables

  • _sigma_zs – list of sigmas for event observables

  • _parameters – list of parameters

  • _log_likelihood_ys – list of loglikelihoods for observables

  • _log_likelihood_zs – list of loglikelihoods for event observables

  • _log_likelihood_rzs – list of loglikelihoods for event observable regularizations

  • _expressions – list of expressions instances

  • _conservation_laws – list of conservation laws

  • _symboldim_funs – define functions that compute model dimensions, these are functions as the underlying symbolic expressions have not been populated at compile time

  • _eqs – carries symbolic formulas of the symbolic variables of the model

  • _sparseeqs – carries linear list of all symbolic formulas for sparsified variables

  • _vals – carries numeric values of symbolic identifiers of the symbolic variables of the model

  • _names – carries the names of symbolic identifiers of the symbolic variables of the model

  • _syms – carries symbolic identifiers of the symbolic variables of the model

  • _sparsesyms – carries linear list of all symbolic identifiers for sparsified variables

  • _colptrs – carries column pointers for sparsified variables. See SUNMatrixContent_Sparse definition in sunmatrix/sunmatrix_sparse.h

  • _rowvals – carries row values for sparsified variables. See SUNMatrixContent_Sparse definition in sunmatrix/sunmatrix_sparse.h

  • _equation_prototype – defines the attribute from which an equation should be generated via list comprehension (see OEModel._generate_equation())

  • _variable_prototype – defines the attribute from which a variable should be generated via list comprehension (see DEModel._generate_symbol())

  • _value_prototype – defines the attribute from which a value should be generated via list comprehension (see DEModel._generate_value())

  • _total_derivative_prototypes – defines how a total derivative equation is computed for an equation, key defines the name and values should be arguments for DEModel.totalDerivative()

  • _lock_total_derivative – add chainvariables to this set when computing total derivative from a partial derivative call to enforce a partial derivative in the next recursion. prevents infinite recursion

  • _simplify – If not None, this function will be used to simplify symbolic derivative expressions. Receives sympy expressions as only argument. To apply multiple simplifications, wrap them in a lambda expression.

  • _x0_fixedParameters_idx – Index list of subset of states for which x0_fixedParameters was computed

  • _w_recursion_depth – recursion depth in w, quantified as nilpotency of dwdw

  • _has_quadratic_nllh – whether all observables have a gaussian noise model, i.e. whether res and FIM make sense.

  • _code_printer – Code printer to generate C++ code

  • _z2event – list of event indices for each event observable

__init__(verbose=False, simplify=<function _default_simplify>, cache_simplify=False)[source]

Create a new DEModel instance.

Parameters
  • verbose (typing.Union[bool, int, None]) – verbosity level for logging, True/False default to logging.DEBUG/logging.ERROR

  • simplify (typing.Optional[typing.Callable]) – see DEModel._simplify()

  • cache_simplify (bool) – Whether to cache calls to the simplify method. Can e.g. decrease import times for models with events.

add_component(component, insert_first=False)[source]

Adds a new ModelQuantity to the model.

Parameters
Return type

None

add_conservation_law(state, total_abundance, coefficients)[source]

Adds a new conservation law to the model. A conservation law is defined by the conserved quantity \(T = \sum_i(a_i * x_i)\), where \(a_i\) are coefficients and \(x_i\) are different state variables.

Parameters
Return type

None

algebraic_states()[source]

Get all algebraic states.

Return type

typing.List[amici.de_model.AlgebraicState]

colptrs(name)[source]

Returns (and constructs if necessary) the column pointers for a sparsified symbolic variable.

Parameters

name (str) – name of the symbolic variable

Return type

typing.Union[typing.List[sympy.core.numbers.Number], typing.List[typing.List[sympy.core.numbers.Number]]]

Returns

list containing the column pointers

conservation_law_has_multispecies(tcl)[source]

Checks whether a conservation law has multiple species or it just defines one constant species

Parameters

tcl (amici.de_model.ConservationLaw) – conservation law

Return type

bool

Returns

boolean indicating if conservation_law is not None

conservation_laws()[source]

Get all conservation laws.

Return type

typing.List[amici.de_model.ConservationLaw]

constants()[source]

Get all constants.

Return type

typing.List[amici.de_model.Constant]

differential_states()[source]

Get all differential states.

Return type

typing.List[amici.de_model.DifferentialState]

eq(name)[source]

Returns (and constructs if necessary) the formulas for a symbolic entity.

Parameters

name (str) – name of the symbolic variable

Return type

sympy.matrices.dense.MutableDenseMatrix

Returns

matrix of symbolic formulas

event_observables()[source]

Get all event observables.

Return type

typing.List[amici.de_model.EventObservable]

events()[source]

Get all events.

Return type

typing.List[amici.de_model.Event]

expressions()[source]

Get all expressions.

Return type

typing.List[amici.de_model.Expression]

free_symbols()[source]

Returns list of free symbols that appear in RHS and initial conditions.

Return type

typing.Set[sympy.core.basic.Basic]

generate_basic_variables()[source]

Generates the symbolic identifiers for all variables in DEModel._variable_prototype

Return type

None

get_appearance_counts(idxs)[source]

Counts how often a state appears in the time derivative of another state and expressions for a subset of states

Parameters

idxs (typing.List[int]) – list of state indices for which counts are to be computed

Return type

typing.List[int]

Returns

list of counts for the states ordered according to the provided indices

get_conservation_laws()[source]

Returns a list of states with conservation law set

Return type

typing.List[typing.Tuple[sympy.core.symbol.Symbol, sympy.core.expr.Expr]]

Returns

list of state identifiers

get_observable_transformations()[source]

List of observable transformations

Return type

typing.List[amici.import_utils.ObservableTransformation]

Returns

list of transformations

get_solver_indices()[source]

Returns a mapping that maps rdata species indices to solver indices

Return type

typing.Dict[int, int]

Returns

dictionary mapping rdata species indices to solver indices

import_from_sbml_importer(si, compute_cls=True)[source]

Imports a model specification from a amici.sbml_import.SbmlImporter instance.

Parameters
Return type

None

is_ode()[source]

Check if model is ODE model.

Return type

bool

log_likelihood_rzs()[source]

Get all event observable regularization log likelihoods.

Return type

typing.List[amici.de_model.LogLikelihoodRZ]

log_likelihood_ys()[source]

Get all observable log likelihoodss.

Return type

typing.List[amici.de_model.LogLikelihoodY]

log_likelihood_zs()[source]

Get all event observable log likelihoods.

Return type

typing.List[amici.de_model.LogLikelihoodZ]

name(name)[source]

Returns (and constructs if necessary) the names of a symbolic variable

Parameters

name (str) – name of the symbolic variable

Return type

typing.List[str]

Returns

list of names

num_cons_law()[source]

Number of conservation laws.

Return type

int

Returns

number of conservation laws

num_const()[source]

Number of Constants.

Return type

int

Returns

number of constant symbols

num_eventobs()[source]

Number of Event Observables.

Return type

int

Returns

number of event observable symbols

num_events()[source]

Number of Events.

Return type

int

Returns

number of event symbols (length of the root vector in AMICI)

num_expr()[source]

Number of Expressions.

Return type

int

Returns

number of expression symbols

num_obs()[source]

Number of Observables.

Return type

int

Returns

number of observable symbols

num_par()[source]

Number of Parameters.

Return type

int

Returns

number of parameter symbols

num_state_reinits()[source]

Number of solver states which would be reinitialized after preequilibration

Return type

int

Returns

number of state variable symbols with reinitialization

num_states_rdata()[source]

Number of states.

Return type

int

Returns

number of state variable symbols

num_states_solver()[source]

Number of states after applying conservation laws.

Return type

int

Returns

number of state variable symbols

observables()[source]

Get all observables.

Return type

typing.List[amici.de_model.Observable]

parameters()[source]

Get all parameters.

Return type

typing.List[amici.de_model.Parameter]

parse_events()[source]

This function checks the right-hand side for roots of Heaviside functions or events, collects the roots, removes redundant roots, and replaces the formulae of the found roots by identifiers of AMICI’s Heaviside function implementation in the right-hand side

Return type

None

rowvals(name)[source]

Returns (and constructs if necessary) the row values for a sparsified symbolic variable.

Parameters

name (str) – name of the symbolic variable

Return type

typing.Union[typing.List[sympy.core.numbers.Number], typing.List[typing.List[sympy.core.numbers.Number]]]

Returns

list containing the row values

sigma_ys()[source]

Get all observable sigmas.

Return type

typing.List[amici.de_model.SigmaY]

sigma_zs()[source]

Get all event observable sigmas.

Return type

typing.List[amici.de_model.SigmaZ]

sparseeq(name)[source]

Returns (and constructs if necessary) the sparsified formulas for a sparsified symbolic variable.

Parameters

name – name of the symbolic variable

Return type

sympy.matrices.dense.MutableDenseMatrix

Returns

linearized matrix containing the symbolic formulas

sparsesym(name, force_generate=True)[source]

Returns (and constructs if necessary) the sparsified identifiers for a sparsified symbolic variable.

Parameters
  • name (str) – name of the symbolic variable

  • force_generate (bool) – whether the symbols should be generated if not available

Return type

typing.List[str]

Returns

linearized Matrix containing the symbolic identifiers

state_has_conservation_law(ix)[source]

Checks whether the state at specified index has a conservation law set

Parameters

ix (int) – state index

Return type

bool

Returns

boolean indicating if conservation_law is not None

state_has_fixed_parameter_initial_condition(ix)[source]

Checks whether the state at specified index has a fixed parameter initial condition

Parameters

ix (int) – state index

Return type

bool

Returns

boolean indicating if any of the initial condition free variables is contained in the model constants

state_is_constant(ix)[source]

Checks whether the temporal derivative of the state is zero

Parameters

ix (int) – state index

Return type

bool

Returns

boolean indicating if constant over time

states()[source]

Get all states.

Return type

typing.List[amici.de_model.State]

sym(name)[source]

Returns (and constructs if necessary) the identifiers for a symbolic entity.

Parameters

name (str) – name of the symbolic variable

Return type

sympy.matrices.dense.MutableDenseMatrix

Returns

matrix of symbolic identifiers

sym_names()[source]

Returns a list of names of generated symbolic variables

Return type

typing.List[str]

Returns

list of names

sym_or_eq(name, varname)[source]

Returns symbols or equations depending on whether a given variable appears in the function signature or not.

Parameters
  • name (str) – name of function for which the signature should be checked

  • varname (str) – name of the variable which should be contained in the function signature

Return type

sympy.matrices.dense.MutableDenseMatrix

Returns

the variable symbols if the variable is part of the signature and the variable equations otherwise.

val(name)[source]

Returns (and constructs if necessary) the numeric values of a symbolic entity

Parameters

name (str) – name of the symbolic variable

Return type

typing.List[sympy.core.numbers.Number]

Returns

list containing the numeric values

class amici.de_export.TemplateAmici(template)[source]

Template format used in AMICI (see string.Template for more details).

Variables

delimiter – delimiter that identifies template variables

__init__(template)
braceidpattern = None
delimiter = 'TPL_'
flags = 2
idpattern = '(?a:[_a-z][_a-z0-9]*)'
pattern = re.compile('\n            TPL_(?:\n              (?P<escaped>TPL_)  |   # Escape sequence of two delimiters\n              (?P<named>(?a:[_a-z][_a-z0-9]*))       |   # delimiter and a Python identifier\n        , re.IGNORECASE|re.VERBOSE)
safe_substitute(mapping={}, /, **kws)
substitute(mapping={}, /, **kws)
amici.de_export.apply_template(source_file, target_file, template_data)[source]

Load source file, apply template substitution as provided in templateData and save as targetFile.

Parameters
Return type

None

amici.de_export.get_function_extern_declaration(fun, name, ode)[source]

Constructs the extern function declaration for a given function

Parameters
  • fun (str) – function name

  • name (str) – model name

  • ode (bool) – whether to generate declaration for DAE or ODE

Return type

str

Returns

C++ function definition string

amici.de_export.get_model_override_implementation(fun, name, ode, nobody=False)[source]

Constructs amici::Model::* override implementation for a given function

Parameters
  • fun (str) – function name

  • name (str) – model name

  • nobody (bool) – whether the function has a nontrivial implementation

Return type

str

Returns

C++ function implementation string

amici.de_export.get_sunindex_extern_declaration(fun, name, indextype)[source]

Constructs the function declaration for an index function of a given function

Parameters
  • fun (str) – function name

  • name (str) – model name

  • indextype (str) – index function {‘colptrs’, ‘rowvals’}

Return type

str

Returns

C++ function declaration string

amici.de_export.get_sunindex_override_implementation(fun, name, indextype, nobody=False)[source]

Constructs the amici::Model function implementation for an index function of a given function

Parameters
  • fun (str) – function name

  • name (str) – model name

  • indextype (str) – index function {‘colptrs’, ‘rowvals’}

  • nobody (bool) – whether the corresponding function has a nontrivial implementation

Return type

str

Returns

C++ function implementation string

amici.de_export.is_valid_identifier(x)[source]

Check whether x is a valid identifier for conditions, parameters, observables… . Identifiers may only contain upper and lower case letters, digits and underscores, and must not start with a digit.

Parameters

x (str) – string to check

Return type

bool

Returns

True if valid, False otherwise

amici.de_export.remove_argument_types(signature)[source]

Strips argument types from a function signature

Parameters

signature (str) – function signature

Return type

str

Returns

string that can be used to construct function calls with the same variable names and ordering as in the function signature

amici.de_export.smart_is_zero_matrix(x)[source]

A faster implementation of sympy’s is_zero_matrix

Avoids repeated indexer type checks and double iteration to distinguish False/None. Found to be about 100x faster for large matrices.

Parameters

x (typing.Union[sympy.matrices.dense.MutableDenseMatrix, sympy.matrices.sparse.MutableSparseMatrix]) – Matrix to check

Return type

bool

amici.de_export.smart_jacobian(eq, sym_var)[source]

Wrapper around symbolic jacobian with some additional checks that reduce computation time for large matrices

Parameters
Return type

sympy.matrices.sparse.MutableSparseMatrix

Returns

jacobian of eq wrt sym_var

amici.de_export.smart_multiply(x, y)[source]

Wrapper around symbolic multiplication with some additional checks that reduce computation time for large matrices

Parameters
Return type

typing.Union[sympy.matrices.dense.MutableDenseMatrix, sympy.matrices.sparse.MutableSparseMatrix]

Returns

product

amici.de_export.var_in_function_signature(name, varname, ode)[source]

Checks if the values for a symbolic variable is passed in the signature of a function

Parameters
  • name (str) – name of the function

  • varname (str) – name of the symbolic variable

  • ode (bool) – whether to check the ODE or DAE signature

Return type

bool

Returns

boolean indicating whether the variable occurs in the function signature