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
|
Load source file, apply template substitution as provided in templateData and save as targetFile. |
|
Constructs the extern function declaration for a given function |
|
Constructs |
|
Constructs the function declaration for an index function of a given function |
|
Constructs the |
Check whether x is a valid identifier for conditions, parameters, observables. |
|
|
Strips argument types from a function signature |
A faster implementation of sympy's is_zero_matrix |
|
|
Wrapper around symbolic jacobian with some additional checks that reduce computation time for large matrices |
|
Wrapper around symbolic multiplication with some additional checks that reduce computation time for large matrices |
|
Checks if the values for a symbolic variable is passed in the signature of a function |
Classes
|
The DEExporter class generates AMICI C++ files for a model as defined in symbolic expressions. |
|
Defines a Differential Equation as set of ModelQuantities. |
|
Template format used in AMICI (see |
- 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 definitionoutdir (
typing.Union
[pathlib.Path
,str
,None
]) – seeamici.ode_export.DEExporter.set_paths()
verbose (
typing.Union
[bool
,int
,None
]) – verbosity level for logging,True
/False
default tologging.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 errorscompiler (
typing.Optional
[str
]) – distutils/setuptools compiler selection to build the python extensionallow_reinit_fixpar_initcond (
typing.Optional
[bool
]) – seeamici.ode_export.DEExporter
generate_sensitivity_code (
typing.Optional
[bool
]) – specifies whether code required for sensitivity computation will be generatedmodel_name (
typing.Optional
[str
]) – name of the model to be used during code generation
- 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
- 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. IfNone
, this will default toamici-{self.model_name}
in the current working directory. will be created if it does not exist.- Return type
- 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 tologging.DEBUG
/logging.ERROR
simplify (
typing.Optional
[typing.Callable
]) – seeDEModel._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
component (
amici.de_model.ModelQuantity
) – model quantity to be addedinsert_first (
typing.Optional
[bool
]) – whether to add quantity first or last, relevant when components may refer to other components of the same type.
- Return type
- 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
state (
sympy.core.symbol.Symbol
) – symbolic identifier of the state that should be replaced by the conservation law (\(x_j\))total_abundance (
sympy.core.symbol.Symbol
) – symbolic identifier of the total abundance (\(T/a_j\))coefficients (
typing.Dict
[sympy.core.symbol.Symbol
,sympy.core.expr.Expr
]) – Dictionary of coefficients {x_i: a_i}
- Return type
- 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
- Returns
boolean indicating if conservation_law is not None
- eq(name)[source]
Returns (and constructs if necessary) the formulas for a symbolic entity.
- Parameters
name (
str
) – name of the symbolic variable- Return type
- Returns
matrix of symbolic formulas
- free_symbols()[source]
Returns list of free symbols that appear in RHS and initial conditions.
- Return type
- generate_basic_variables()[source]
Generates the symbolic identifiers for all variables in
DEModel._variable_prototype
- Return type
- 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
- 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
- Returns
list of transformations
- get_solver_indices()[source]
Returns a mapping that maps rdata species indices to solver indices
- Return type
- 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
si (
amici.sbml_import.SbmlImporter
) – imported SBML modelcompute_cls (
typing.Optional
[bool
]) – whether to compute conservation laws
- Return type
- name(name)[source]
Returns (and constructs if necessary) the names of a symbolic variable
- Parameters
name (
str
) – name of the symbolic variable- Return type
- Returns
list of names
- num_cons_law()[source]
Number of conservation laws.
- Return type
- Returns
number of conservation laws
- num_eventobs()[source]
Number of Event Observables.
- Return type
- Returns
number of event observable symbols
- num_events()[source]
Number of Events.
- Return type
- Returns
number of event symbols (length of the root vector in AMICI)
- num_state_reinits()[source]
Number of solver states which would be reinitialized after preequilibration
- Return type
- Returns
number of state variable symbols with reinitialization
- num_states_solver()[source]
Number of states after applying conservation laws.
- Return type
- Returns
number of state variable symbols
- 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
- 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
- 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
- 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
- Return type
- 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
- state_has_fixed_parameter_initial_condition(ix)[source]
Checks whether the state at specified index has a fixed parameter initial condition
- sym(name)[source]
Returns (and constructs if necessary) the identifiers for a symbolic entity.
- Parameters
name (
str
) – name of the symbolic variable- Return type
- Returns
matrix of symbolic identifiers
- sym_names()[source]
Returns a list of names of generated symbolic variables
- Return type
- 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
- Return type
- Returns
the variable symbols if the variable is part of the signature and the variable equations otherwise.
- 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
source_file (
typing.Union
[str
,pathlib.Path
]) – relative or absolute path to template filetarget_file (
typing.Union
[str
,pathlib.Path
]) – relative or absolute path to output filetemplate_data (
typing.Dict
[str
,str
]) – template keywords to substitute (key is template variable withoutTemplateAmici.delimiter
)
- Return type
- amici.de_export.get_function_extern_declaration(fun, name, ode)[source]
Constructs the extern function declaration for a given function
- amici.de_export.get_model_override_implementation(fun, name, ode, nobody=False)[source]
Constructs
amici::Model::*
override implementation for a given function
- amici.de_export.get_sunindex_extern_declaration(fun, name, indextype)[source]
Constructs the function declaration for an index function of a given function
- 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
- 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.
- amici.de_export.remove_argument_types(signature)[source]
Strips argument types from a 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
- 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
eq (
sympy.matrices.dense.MutableDenseMatrix
) – equationsym_var (
sympy.matrices.dense.MutableDenseMatrix
) – differentiation variable
- Return type
- 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
x (
typing.Union
[sympy.matrices.dense.MutableDenseMatrix
,sympy.matrices.sparse.MutableSparseMatrix
]) – educt 1y (
sympy.matrices.dense.MutableDenseMatrix
) – educt 2
- Return type
typing.Union
[sympy.matrices.dense.MutableDenseMatrix
,sympy.matrices.sparse.MutableSparseMatrix
]- Returns
product