Model

The central object in Myokit is the Model. In most scenario’s, models are created by parsing a file in mmt syntax. Once parsed, a model can be validated to ensure its integrity. In models with unsound semantics (for example a cyclical reference between variables) the validate() method will raise an IntegrityError.

For models with a limited number of state variables, validation is fast. In these cases, the validate() method is run after parsing as an additional check. For larger models, validation is costly and avoided until a simulation is run or another analysis method is used.

Once created and validated, a model can be asked to compute the solvable order of its equations which can then be used by an exporter to generate runnable simulation or analysis code.

A ModelComparison class is available that can compare models syntactically, while the step() method can compare model output (either to other models’ output or to stored reference files from external implementations).

myokit.Model

class myokit.Model(name=None)

Represents an electrophysiological cell model, structured in components.

Components can be added to the model using add_component(). Access to a model’s component is provided through the get() method and components().

Minimal dictionary support is provided: A component named “x” can be obtained from a model m using m["x"]. The number of components in m is given by len(m) and the presence of “x” in m can be tested using if "x" in m:.

Variables stored inside components can be accessed using get() or values(). Values defined through their derivative make up the model state and can be accessed using states(). States have initial values accessible through initial_values().

A model’s validity can be checked using is_valid(), which returns the latest validation status and validate(), which (re)validates the model. Warnings can be obtained using warnings()

The optional constructor argument name can be used to set a meta property “name”.

Meta-data properties can be accessed via the property meta, for example model.meta['key']= 'value'.

For consistency with components, variables, and expressions, models cannot be compared with == (which will only return True if both operands are the same object). Checking if models are the same in other senses can be done with is_similar(). Models can be serialized with pickle.

add_component(name)

Adds a component with the given name to this model.

This method resets the model’s validation status.

Returns the newly created myokit.Component object.

add_component_allow_renaming(name)

Attempts to add a component with the given name to this model, but uses a different name if this causes any conflicts.

The new component’s name will be modified by appending _1, _2, etc. until the conflict is resolved.

This method can be used when symbolically manipulating a model in situations where the exact names are unimportant.

Returns the newly created myokit.Component object.

add_function(name, arguments, template)

Adds a user function to this model.

Returns the newly created myokit.UserFunction object.

binding(binding)

Returns the variable with the binding label binding. If no such variable is found, None is returned.

bindings()

Returns an iterator over all (binding label : variable) mappings in this model.

bindingx(binding)

Returns the variable with the binding label binding, raising a myokit.IncompatibleModelError if no such variable is found.

See Model.binding().

check_units(mode=1)

Checks the units used in this model.

Models can specify units in two ways:

  1. By setting variable units. This is done using the in keyword in mmt syntax or through myokit.Variable.set_unit(). This specifies the unit that a variable’s value should be in.

  2. By adding units to literals. This is done using square brackets in mmt syntax (for example 5 [m] / 10 [s]) or by adding a unit when creating a Number object, for example myokit.Number(2, myokit.units.mV).

When checking a model’s units, this method loops over all variables and performs two checks:

  1. The unit resulting from the variable’s RHS is evaluated. This involves checking rules such as “in x + y, x and y must have the same units, or “in exp(x) the units of x must be dimensionless”. A myokit.IncompatibleUnitExpression will be raised if any inompatibilities are found.

  2. The calculated unit is compared with the variable unit. An IncompatibleUnitError will be triggered if the two units don’t match.

Two unit-checking modes are available.

In strict mode (mode=myokit.UNIT_STRICT), all unspecified units in expressions are treated as “dimensionless”. For example, the expression 5 * V where V is in [mV] will be treated as dimensionless times millivolt (or [1] * [mV] in mmt syntax), resulting in the unit [mV]. The expression 5 + V will be interpreted as dimensionless plus millivolt, and will raise an error. In strict mode, functions such as sin and exp will check that their argument is dimensionless (so sin(3 [m]) is never allowed, only e.g. sin(3 [m] / 1 [m])).

In tolerant mode, unspecified units will be treated as whatever makes the expression work. So ? + [mV] wil be interpreted as [mV] + [mV]. In addition, functions that require dimensionless input in strict mode won’t perform this check in tolerant mode.

A note about references:

In both modes, when a reference is encountered, for example when checking the expression 5 * y, the system will look up the variable y’s unit, and will not look at y’s rhs. Consider the following buggy model:

x = 5 [mV] # RHS unit, no variable unit y = 3 [A] + x # RHS unit, no variable unit

When checking the expression y = 3 + x the variable x will be treated as unspecified, because no variable unit is set for x using the in keyword. In strict mode, this will lead to an error when checking x = 5 [mV] because x is dimensionless while 5 [mV] has units [mV]. In tolerant mode, no error will be raised. When tolerantly evaluating y = 3[A] + x it will be assumed that x is also in [A], because no variable unit is given that says otherwise (despite the RHS of x having units mV).

clone()

Returns a (deep) clone of this model.

code(line_numbers=False)

Returns this model in mmt syntax.

Line numbers can be added by setting line_numbers=True.

component_cycles()

Finds cyclical references between components and returns them. For example, if a.p depends on b.q while b.x depends on a.y, a cycle a > b > a will be returned.

For a faster way to check if there are any interdependent components (without returning the exact cycles found), use has_interdependent_components().

components(sort=False)

Returns an iterator over this model’s component objects.

count_components()

Returns the number of components in this model.

count_equations(const=None, inter=None, state=None, bound=None, deep=False)

Returns the number of equations matching the given criteria. See equations() for an explanation of the arguments.

count_states()

Returns the number of state variables in this model.

count_variables(const=None, inter=None, state=None, bound=None, deep=False)

Returns the number of variables matching the given criteria. See variables() for an explanation of the arguments.

create_unique_names()

Create a globally unique name for each Component and Variable.

Ideally, the global name equals the variable or component’s basic name. If a name is disputed the following strategy will be used:

  1. For variables, the parent name will be added as a prefix to all variables claiming the disputed name.

  2. If problems persist, a suffix _i will be added, where i is the first integer which doesn’t result in clashing names.

In addition, the method will avoid names listed using reserve_unique_names() and names starting with a prefix listed using reserve_unique_prefix().

equations(const=None, inter=None, state=None, bound=None, deep=False)

Creates and returns a filtered iterator over the equations of this object’s variables.

The returned values can be filtered using the following arguments:

const=True|False|None

Set to True to return only constants’ equations. False to exclude all constants and any other value to ignore this check.

For a definition of “constant variable” see variables().

inter=True|False|None

Set to True to return only intermediary variables’ equations, False to exclude all intermediary variables and any other value to ignore this check.

For a definition of “intermediary variable” see variables().

state=True|False|None

Set to True to return only state variables’ equations, False to exclude all state variables and any other value to ignore this check.

bound=True|False|None

Set to True to return only bound variables’ equations, False to exclude all bound variables and any other value to ignore this check.

deep=True|False (by default it’s False)

Set to True to include the equations of nested variables meeting all other criteria.

eval_state_derivatives(state=None, inputs=None, precision=64, ignore_errors=False)

Deprecated alias of evaluate_derivatives().

evaluate_derivatives(state=None, inputs=None, precision=64, ignore_errors=False)

Evaluates and returns the values of all state variable derivatives. The values are returned in a list sorted in the same order as the state variables.

Arguments:

state=None

If given, the state values given by state will be used as starting point. Here state can be any object accepted as input by :meth:map_to_state().

inputs=None

To set the values of external inputs, a dictionary mapping binding labels to values can be passed in as inputs.

precision

To assist in finding the origins of numerical errors, the equations can be evaluated using single-precision floating point. To do this, set precision=myokit.SINGLE_PRECISION.

ignore_errors

By default, the evaluation routine raises myokit.NumericalError exceptions for invalid operations. To return NaN instead, set ignore_errors=True.

expressions_for(*variables)

Determines the expressions needed to evaluate one or more variables.

If state variables are included in the list, “evaluating” the variable is interpreted as evaluating its derivative.

Returns a tuple (eqs, args) where eqs is a list of Equation objects in solvable order containing the minimal set of equations needed to evaluate the given variable and args is a list of the state variables and bound variables these expressions require as input.

format_state(state=None, state2=None, precision=64)

Converts a sequence of floating point numbers to a string where each line has the format <full_qualified_name> = <float_value>.

Arguments:

state=None

The state to display. If no state is given this model’s (evaluated) <initial_values()>initial values() are used.

state2=None

An optional second state, to be shown next to state for comparison.

precision=myokit.DOUBLE_PRECISION

An optional precision argument to pass into myokit.float.str() when formatting the state values.

format_state_derivatives(state=None, derivatives=None, precision=64)

Like format_state() but displays the derivatives along with each state’s value.

Arguments:

state=None

The state to show derivatives for. If no state is given this model’s (evaluated) <initial_values()>initial values() are used.

derivatives=None

An optional list or other sequence of evaluated derivatives. If not given, the values will be calculed from state using eval_derivatives().

precision=myokit.DOUBLE_PRECISION

An optional precision argument to use when evaluating the state derivatives, and to pass into myokit.float.str() when formatting the state values and derivatives.

format_warnings()

Formats all warnings generated during the last call to validate() and returns a string containing the result.

get(name, class_filter=None)

Searches for a component or variable with the given qname and returns it.

To return only objects of a certain class, pass it in as class_filter.

get_function(name, nargs)

Returns the user function with name name and nargs arguments.

has_component(name)

Returns True if this model has a component with the given name.

has_equations(const=None, inter=None, state=None, bound=None, deep=False)

Returns True if there are any equations that can be returned by calling :meth:equations with the same arguments.

has_interdependent_components()

Returns True if this model contains mutually dependent components. That is, if there exists any component A whose variables depend on variables from component B, while variables in component B depend on variables in component A.

To see the variables causing the interdependence, use component_cycles().

has_parse_info()

Returns True if this model retains parsing information, so that methods such as item_at_text_position() and show_line_of() can be used.

has_variable(name)

Returns True if the given name corresponds to a variable in this object. Accepts both single names x and qualified names x.y as input.

This function performs the same search as variable, so in most cases it will be more efficient to call variable() in a try-catch block rather than checking for existence explicitly.

has_variables(const=None, inter=None, state=None, bound=None, deep=False)

Returns True if there are any variables that can be returned by calling :meth:variables with the same arguments.

has_warnings()

Returns True if this model has any warnings.

import_component(external_component, new_name=None, var_map=None, allow_name_mapping=False, convert_units=False)

Imports one or multiple components from another model (the “source model”) into this one (the “target model”).

If variables in the external_component refer to variables from other components they will be mapped on to variables from this model by trying the following strategies (in order):

  1. Using the provided dict var_map, which maps variables in the source model to variables in this model.

  2. By assuming variables with the same label/binding map onto each other.

  3. By assuming that variables with the same qualified names map onto each other. This rule is only applied if allow_name_mapping is set to True.

Arguments:

external_component

A myokit.Component or a list of components from another model.

new_name

An optional new name for the imported component or list of names if multiple components are provided.

var_map

An optional dict mapping variables in the source model to variables from this model (with variables specified as objects or as fully qualified names).

allow_name_mapping

Set this to True to allow mapping based on fully qualified names, e.g. a variable x.y in the source model will be mapped to a variable x.y in the target model.

convert_units

Set this to True to convert the units of any mapped variables, if required and possible.

If any variables cannot be mapped, a myokit.VariableMappingError will be raised. A myokit.DuplicateNameError will be raised if the component’s name or new_name clashes with an existing component name. If unit conversion is enabled and variables with incompattible units are mapped onto each other, a class:myokit.IncompatibleUnitsError will be raised.

initial_values(as_floats=False)

Returns a list of the model’s initial values.

By default, expressions are returned, but this can be changed to a list of floats by setting as_floats=True.

inits()

Deprecated method: Returns an iterator over the Equation objects defining this model’s initial values.

is_similar(other, check_unames=False)

Returns True if this model has the same code as the other model.

If check_unames is set to True, the method also checks if the defined unique names and unique name prefixes are the same.

is_valid()

Returns True if this model is valid, False if it is invalid and None if the validation status has not been determined with validate().

Valid models may still have one or more warnings.

item_at_text_position(line, char)

Finds the component, variable, or expression at the position (line, char), and returns a tuple (token, object) with a parser token and the found object, or None if nothing is found.

Both line and char should be given as integers. The first line is line 1, while the first character is char 0.

label(label)

Returns the variable with the given label, or None if no such variable can be found.

labels()

Returns an iterator over all (label : variable) mappings in this model.

labelx(label)

Returns the variable with the label label, raising a myokit.IncompatibleModelError if no such variable is found.

See Model.label().

load_state(filename)

Deprecated method: Sets the model’s initial values using data from a file formatted in any style accepted by myokit.map_to_state().

map_component_dependencies(omit_states=True, omit_constants=False)

Scans all equations and creates a map of inter-component dependencies.

The result is an ordered dictionary with the following structure:

{
    comp1 : [dep1, dep2, dep3, ...],
    comp2 : [dep1, dep2, dep3, ...],
    ...
}

where comp1, comp2, ... are Components and dep1, dep2, ... are the components they depend upon.

Only direct dependencies are listed: If A depends on B and B depends on C then the returned value for A is [B], not [B,C].

By default, dependencies on state variables’ current values are omitted. This behavior can be changed by setting omit_states to False.

To omit all dependencies on constants, set omit_constants to True.

map_component_io(omit_states=False, omit_derivatives=False, omit_constants=False, rl_states=None)

Scans all equations and creates a list of input and output variables for each component.

Input variables are taken to be any foreign variables the component needs to perform its calculations, plus the current values of its own state variables if it needs them.

Output variables are taken to be any values calculated by this component but used outside it. This includes the derivatives of the state variables it calculates. State variables are never given as outputs, as it is assumed these are updated by an ODE solver.

The output can be customized using the following arguments:

omit_states

Set to True to omit state values from the input lists. This can be useful in cases where the state is stored in a vector.

omit_derivatives

Set to True to omit derivatives from the input and output lists. This can be useful if derivatives are stored in a vector.

omit_constants

Set to True to omit constants from the input and output lists. This can be useful if constants are stored globally, e.g. as C macros.

rl_states

A map {state_variable : {inf_variable, tau_variable} can be passed in to enable mapping for Rush-Larsen schemes. In this case, all variables listed as inf or tau_variable will be included in component output lists, and the derivatives of each state_variable in the mapping will only be added to the output list if there are other variables that depend on it.

The result is a tuple containing two OrderedDict objects, each of the following structure:

{
    comp1: [lhs1, lhs2, ...],
    comp2: [lhs1, lhs2, ...],
    ...
}

The first dict contains the inputs to every component, the second dict contains every components output values. The values in the lists are :class:LhsExpression objects referring to either a variable or its derivative.

map_deep_dependencies(collapse=False, omit_states=True, filter_encompassed=False)

Scans the list of equations stored in this model and creates a map relating each equation’s left hand side to a list of other LhsExpressions it depends on, either directly or through an intermediate variable.

The method map_shallow_dependencies() performs a similar check, but only returns direct dependencies. This method expands the full dependency tree.

The result is an OrderedDict with the following structure:

{
  lhs1 : [dep1, dep2, dep3, ...],
  ...
}

where lhs1 is a LhsExpression and dep1, dep2 and dep3 are the LhsExpression objects it depends upon.

If the system is not solvable: that is, if it contains cyclical references, a myokit.IntegrityError is raised.

If the optional parameter collapse is set to True nested variables will not be listed separatly. Instead, their dependencies will be added to the dependency lists of their parents.

By default, dependencies on state variables’ current values are omitted. This behavior can be changed by setting omit_states to False.

In case of a dependency such as:

a = f(b)
b = g(c)

the set returned for a will include b and c. So while a here depends on both b and c, b’s sole dependency on c means a can be calculated if just c is known. To filter out the dependency on b, set filter_encompassed to True. Note that this will also filter out all dependencies on constants, since a constant’s dependencies (an empty set) can be said to be included in all other sets.

map_shallow_dependencies(collapse=False, omit_states=True, omit_constants=False)

Scans the list of equations stored in this model and creates a map relating each equation’s left hand side to a list of other LhsExpressions it depends on directly.

In contrast to the method map_deep_dependencies(), that performs a deep search for all nested dependencies, this method only returns direct dependencies. I.E. LhsExpressions named specifically in the equation’s right hand side.

The result is an OrderedDict with the following structure:

{
  lhs1 : [dep1, dep2, dep3, ...],
  ...
}

where lhs1 is a LhsExpression and dep1, dep2 and dep3 are the LhsExpression objects it depends upon.

In special cases, the obtained result can differ from the mathematical concept of a dependency: if x = 0 * y the function will return a dependency of x on y. Similarly, for x = if(cond, a, b) the function will report a dependency of x on cond, a and b.

If the optional parameter collapse is set to True nested variables will not be listed separatly. Instead, their dependencies will be added to the dependency lists of their parents.

By default, dependencies on state variables’ current values are omitted. This behavior can be changed by setting omit_states to False. Dependencies on constants are included by default, but this can be changed by setting omit_constants to True.

map_to_state(state)

This utility function accepts a number of different input types and returns a list of floats in the same order as the model’s state variables.

The following types of input are meaningfully handled:

  • A dictionary mapping state variable names or objects to floats

  • A dictionary mapping state variable names or objects to lists. The last value in every list will be used. This allows the dictionary returned by myokit.Simulation.run() to be used directly.

  • A formatted string declaring each variable’s value using the syntax component.var_name = 1.234 or simply containing a comma or space delimited list of floats.

  • A list of scalars. In this case, the list length will be checked and all values converted to float. No re-ordering takes place.

name()

Returns the model meta property name, or None if it isn’t set.

remove_component(component)

Removes a component from the model.

This will reset the model’s validation status.

remove_derivative_references()

Scans this model’s RHS for any references to derivatives and removes them by introducing a new variable.

For example, given a (partial) model:

[ernie]
dot(x) = (12 - x) / 5

[bert]
y = 1 + dot(x)

this method will update the model to:

[ernie]
dot_x = (12 - x) / 5
dot(x) = dot_x

[bert]
y = 1 + dot_x
reorder_state(order)

Changes the order of this model’s state variables. The argument order must be a list of state variables or their qnames.

This method does not affect the model’s validation status.

reserve_unique_name_prefix(prefix, prepend)

Indicates a prefix that won’t be used in unique names (unames).

When creating a unique name, any variable starting with prefix will be prepended with the string prepend.

reserve_unique_names(*unames)

Reserves one or more names that won’t be used in unique names (unames).

This function can be used to add keywords to a model before exporting. After reserving one or more keywords, use create_unique_names() to reset the model’s unames.

Adding new names does _not_ clear the previously reserved names.

resolve_interdependent_components()

Checks if the model contains components that each depend on the other. If so, variables from these components will be moved to a new component called “remaining” until the issue is resolved.

save_state(filename)

Deprecated method: Saves the model state to a file (as floats).

set_initial_values(values)

Sets this model’s initial values.

The values must be specified as either a list of floats, expressions, and/or strings; or as a dict or string in a format accepted by map_to_state().

set_name(name=None)

Changes the value of the meta-property “name”.

set_state(state)

Deprecated method: use set_initial_values() instead.

set_value(qname, value)

Changes a variable’s defining expression to the given number or myokit.Expression.

For state variables, this updates the expression for their derivative. For all other variables, the expression for their value is updated.

This will reset the model’s validation status.

show_evaluation_of(var)

Returns a string representing the evaluation of a single variable.

The variable’s equation and value are displayed, along with the value and formula of any nested variables and the values of all dependencies.

show_expressions_for(var)

Returns a string containing the expressions needed to evaluate the given variable from the state variables.

show_line_of(var, raw=False)

Returns a string containing the type of variable var is and the line it was defined on.

If raw is set to True the method returns an integer with the line number, or None if no line number information is known (i.e. if this model wasn’t created by parsing).

solvable_order()

Returns all equations in a solvable order. The resulting output has the following structure:

OrderedDict {
  'comp1' : EquationList([eq1, eq2, eq3, ...]),
  'comp2' : EquationList([eq1, eq2, eq3, ...]),
  ...,
  '*remaining*' : EquationList([eq1, eq2, eq3])
}

The OrderedDict contains each component’s name as a key and maps it to a list of equations that can be solved for this component, stored in an :class:EquationList object which extends the list type with a number of special iterators.

The order of the components is such that the components with the fewest dependencies are listed first, in an effort to ensure as many equations as possible can be solved on a per-component basis.

The final entry in the OrderedDict is a list of all remaining equations that could not be solved on a per-component basis. For models that contain fully separable components (that is, if the model contains only components that depend on each other non-cyclically) this list will be empty.

state()

Deprecated method, use initial_values(as_floats=True) instead.

states()

Returns an iterator over this model’s state variable objects.

suggest_variable(name)

Returns a tuple (found, suggested, msg).

If the requested variable is found, only the found part of the tuple is set. If not, the second and third argument are set. Here suggested will take the form of a suggested variable with a similar name, while msg will be a suggested error message.

time()

Returns this model’s time variable.

The time variable is identified by it’s binding to the external source “time”. For a valid model, this method always returns a unique variable. If no time variable has been declared None is returned.

time_unit(mode=1)

Returns the units used by this model’s time variable.

If no time unit is set and mode is myokit.UNIT_TOLERANT (default), then None is returned. With mode set to myokit.UNIT_STRICT the returned value in this case is myokit.units.dimensionless.

timex()

Returns this model’s time variable, raising a myokit.IncompatibleModelError if no time variable is found.

See Model.time().

user_functions()

Returns a dictionary mapping this model’s user function names to their Expression objects.

validate(remove_unused_variables=False)

Validates this model and raises errors if any issues are found.

Small issues (e.g. unused variables) will generate warnings, which can be retrieved using Model.warnings() or Model.format_warnings(). Any previously set warnings will be erased whenever validate() is run.

If remove_unused_variables is set to True, any unused variables will be removed from this model during validation.

value(qname)

Returns the value of a variable.

var(name)

Searches for the given variable and returns it if found. Accepts both single names x and qualified names x.y as input.

variables(const=None, inter=None, state=None, bound=None, deep=False, sort=False)

Creates and returns a filtered iterator over the contained variables.

The returned values can be filtered using the following arguments:

const=True|False|None

Constants are defined as variables that do not depend on state variables or derivatives. In other words, any variable whose value can be determined before starting an ODE solving routine.

Set to True to return only constants, False to exclude all constants and any other value to ignore this check.

inter=True|False|None

Intermediary variables are those variables that are not constant but are not part of the state. In other words, intermediary variables are the variables that need to be calculated at every step of an ODE solving routine before calculating the ODE derivatives and updating the state.

Set to True to return only intermediary variables, False to exclude all intermediary variables and any other value to ignore this check.

state=True|False|None

Set to True to return only state variables, False to exclude all state variables and any other value to ignore this check.

bound=True|False|None

Set to True to return only variables bound to an external value, False to exclude all bound variables and any other value to forgo this check.

deep=True|False (by default it’s False)

Set to True to return nested variables meeting all other criteria.

sort=True|False (by default it’s False)

Set to True to return the variables in a consistent order. (Note that this does _not_ mean alphabetical sorting of all variables, just that the order is consistent between calls!)

warnings()

Returns a list containing the warnings generated in this model.

Helper classes and functions

myokit.check_name(name)

Tests if the given name is a valid myokit name and raises a myokit.InvalidNameError if it isn’t.

class myokit.ModelPart(parent, name)

Base class for model parts.

code()

Returns this object in mmt syntax.

has_ancestor(obj)

Returns True if the given object obj is an ancestor of this ModelPart.

is_ancestor(obj)

Returns True if this object is an ancestor of the given ModelPart` object.

model()

Returns the myokit.Model this object belongs to (if set).

name()

Returns this object’s name.

parent(kind=None)

Returns this object’s parent.

If the optional variable kind is set, the method will scan until an instance of the requested type is found.

qname(hide=None)

Returns this object’s fully qualified name. That is, an object named y with a parent named x will return the string x.y. If y has a child z its qname will be x.y.z.

If the optional argument hide is set to this object’s parent the parent qualifier will be omitted.

uname()

Returns a globally unique name for this object.

class myokit.ObjectWithMetaData

Base class for objects with meta data.

Meta-data properties are all stored in a dict and should be string:string mappings.

class myokit.MetaDataContainer

Dictionary that stores string meta-data.

Each key must be a valid Myokit name (so start with at least one letter, and contain only letters, numbers, and underscores), or a series of valid Myokit names separated by colons (:). Values can be any string.

A MetaDataContainer can be cloned using clone = MetaDataContainer(original).

class myokit.VarOwner(parent, name)

Represents a holder of Variables

Minimal dictionary support is provided: A variable named “x” can be obtained from an owner m using m["x"]. The number of variables in m is given by len(m) and the presence of “x” in m can be tested using if "x" in m:.

add_variable(name, unit=None, rhs=None, label=None, binding=None, initial_value=None)

Adds a child variable with the given name to this VarOwner.

Returns the newly created myokit.Variable object.

If given, the unit, rhs, and a label or binding will also be set.

If an initial_value is given the variable will be promoted to a state and its initial value will be set.

add_variable_allow_renaming(name)

Attempts to add a child variable with the given name to this VarOwner, but uses a different name if this causes any conflicts.

The new variable’s name will be modified by appending _1, _2, etc. until the conflict is resolved.

This method can be used when symbolically manipulating a model in situations where the exact names are unimportant.

Returns the newly created myokit.Variable object.

can_add_variable(name, variable_whitelist=None)

Returns True if a variable can be added to this VarOwner under the given name.

This method is automatically called by add_variable() and move_variable(), there is no need to call it before using these methods.

To ignore clashes with known variables, a list variable_whitelist can be passed in.

get(name, class_filter=None)

Searches for a variable with the given qname and returns it.

To return only objects of a certain class, pass it in as class_filter.

The qnames are specified relative to the VarOwner. For example, in a model with a component ina and a variable ina.h we expect the following results

>>> import myokit
>>> m = myokit.load_model('example')
>>> c = m.get('ina')        # Retrieves the component <ina>
>>> h = c.get('h')          # Retrieves the variable <ina.h>
>>> x = c.get('ina.h')      # Searches for <ina.ina.h>: KeyError!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'ina'
move_variable(variable, new_parent, new_name=None)

Moves the given variable to another VarOwner new_parent. In addition, this method can be used to rename variables (either with or without moving them).

remove_variable(variable, recursive=False)

Removes the given variable from this VarOwner and from the model.

If recursive is True, any child variables will be deleted as well.

A myokit.IntegrityError will be raised if

class myokit.VarProvider

Abstract class

This class provides an iterator over variables and equations for any object that can provide access to an iterator over its variables.

count_equations(const=None, inter=None, state=None, bound=None, deep=False)

Returns the number of equations matching the given criteria. See equations() for an explanation of the arguments.

count_variables(const=None, inter=None, state=None, bound=None, deep=False)

Returns the number of variables matching the given criteria. See variables() for an explanation of the arguments.

equations(const=None, inter=None, state=None, bound=None, deep=False)

Creates and returns a filtered iterator over the equations of this object’s variables.

The returned values can be filtered using the following arguments:

const=True|False|None

Set to True to return only constants’ equations. False to exclude all constants and any other value to ignore this check.

For a definition of “constant variable” see variables().

inter=True|False|None

Set to True to return only intermediary variables’ equations, False to exclude all intermediary variables and any other value to ignore this check.

For a definition of “intermediary variable” see variables().

state=True|False|None

Set to True to return only state variables’ equations, False to exclude all state variables and any other value to ignore this check.

bound=True|False|None

Set to True to return only bound variables’ equations, False to exclude all bound variables and any other value to ignore this check.

deep=True|False (by default it’s False)

Set to True to include the equations of nested variables meeting all other criteria.

has_equations(const=None, inter=None, state=None, bound=None, deep=False)

Returns True if there are any equations that can be returned by calling :meth:equations with the same arguments.

has_variable(name)

Returns True if the given name corresponds to a variable in this object. Accepts both single names x and qualified names x.y as input.

This function performs the same search as variable, so in most cases it will be more efficient to call variable() in a try-catch block rather than checking for existence explicitly.

has_variables(const=None, inter=None, state=None, bound=None, deep=False)

Returns True if there are any variables that can be returned by calling :meth:variables with the same arguments.

var(name)

Searches for the given variable and returns it if found. Accepts both single names x and qualified names x.y as input.

variables(const=None, inter=None, state=None, bound=None, deep=False, sort=False)

Creates and returns a filtered iterator over the contained variables.

The returned values can be filtered using the following arguments:

const=True|False|None

Constants are defined as variables that do not depend on state variables or derivatives. In other words, any variable whose value can be determined before starting an ODE solving routine.

Set to True to return only constants, False to exclude all constants and any other value to ignore this check.

inter=True|False|None

Intermediary variables are those variables that are not constant but are not part of the state. In other words, intermediary variables are the variables that need to be calculated at every step of an ODE solving routine before calculating the ODE derivatives and updating the state.

Set to True to return only intermediary variables, False to exclude all intermediary variables and any other value to ignore this check.

state=True|False|None

Set to True to return only state variables, False to exclude all state variables and any other value to ignore this check.

bound=True|False|None

Set to True to return only variables bound to an external value, False to exclude all bound variables and any other value to forgo this check.

deep=True|False (by default it’s False)

Set to True to return nested variables meeting all other criteria.

sort=True|False (by default it’s False)

Set to True to return the variables in a consistent order. (Note that this does _not_ mean alphabetical sorting of all variables, just that the order is consistent between calls!)

Model comparison

class myokit.ModelComparison(model1, model2, live=False)

Compares two models.

The resulting diff text can be iterated over:

for line in ModelComparison(m1, m2):
    print(line)

Differences can be printed directly to stdout by setting live=True.

equal()

Returns True if the two models were equal.

text()

Returns the full difference text.

myokit.step(model, initial=None, reference=None, ignore_errors=False)

Evaluates the state derivatives in a model and compares the results with a list of reference values, if given.

The model should be given as a valid myokit.Model. The state values to start from can be given as initial, which should be any item that can be converted to a valid state using model.map_to_state.

The values can be compared to reference output given as a list reference. Alternatively, if reference is a model the two models’ outputs will be compared.

By default, the evaluation routine checks for numerical errors (divide-by-zeros, invalid operations and overflows). To run an evaluation without error checking, set ignore_errors=True.

Returns a string indicating the results.