Variable¶
- class myokit.Variable(parent, name)¶
Represents a model variable.
Variables should not be created directly, but only via
Component.add_variable()orVariable.add_variable().Each variable has a single defining equation. For state variables, this equation has a derivative on the left-hand side (lhs), for all other variables the lhs of the defining equation is simply the variable’s name.
Variables can be made into state variables using
Variable.promote().Variables can be made to represent an externally defined variable using
Variable.set_binding(). In this case, the right hand side set for a variable will be used as an alternative in situations where the external input is not available.Meta-data properties can be accessed via the property
meta, for examplemodel.meta['key']= 'value'.- add_variable(name, unit=None, rhs=None, label=None, binding=None, initial_value=None)¶
Adds a child variable with the given
nameto thisVarOwner.Returns the newly created
myokit.Variableobject.If given, the
unit,rhs, and alabelorbindingwill also be set.If an
initial_valueis 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.Variableobject.
- binding()¶
Returns this variable’s binding label or
Noneif no binding is set.
- can_add_variable(name, variable_whitelist=None)¶
Returns
Trueif a variable can be added to thisVarOwnerunder the givenname.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_whitelistcan be passed in.
- clamp(value=None)¶
Clamps this variable to its current value or the given
value.This will perform the following actions:
The model’s RHS will be set to a literal, using
var.set_rhs(var.eval()).If this is a state variable, it will be demoted.
Any child variables will be removed.
- code()¶
Returns this object in
mmtsyntax.
- convert_unit(new_unit, helpers=None)¶
Converts the units this variable is expressed in to
new_unit, and updates the RHS with an appropriate scaling factor.Unit conversion proceeds in the following steps:
A scaling factor is determined (see below).
The variable’s RHS is multiplied by this factor
For state variables, the current state value is also updated.
All references to the variable in the model equations are divided by the scaling factor.
If the time variable is updated, all derivative equations are updated.
The scaling factor is determined using
myokit.Unit.conversion_factor(old_unit, new_unit, helpers)(), whereold_unitis the current variable unit (as determined byvariable.unit(myokit.UNIT_STRICT)).For state variables, as with ordinary variables, the
new_unitshould be the unit of the variable itself (and not of its time derivative).Arguments:
new_unitThe new unit this variable should be in. Given either as a
myokit.Unitor as a string that can be converted to a unit usingmyokit.parse_unit(new_unit).helpers=NoneAn optional list of conversion factors, which the method will attempt to use if the new and old units are incompatible. Each factor should be specified as a
myokit.Quantityor something that can be converted to a Quantity e.g. a string1 [uF/cm^2]or amyokit.Number().
Note that this method will assume the expression is currently in the unit returned by
Variable.unit(). It will not check whether the current RHS expression evaluates to the correct units.Returns
Trueif a unit conversion was performed,Falseif not.Raises a
myokit.IncompatibleUnitErrorif the units cannot be converted.’
- 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.
- demote()¶
Turns a state variable into an intermediary variable.
This will reset the validation status of the model this variable belongs to.
- eq()¶
Returns this variable’s defining equation.
For state variables this will be an equation for the variable’s derivative. For ordinary variables the equation for the variable’s value is returned.
- 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|NoneSet to
Trueto return only constants’ equations.Falseto exclude all constants and any other value to ignore this check.For a definition of “constant variable” see
variables().inter=True|False|NoneSet to
Trueto return only intermediary variables’ equations,Falseto exclude all intermediary variables and any other value to ignore this check.For a definition of “intermediary variable” see
variables().state=True|False|NoneSet to
Trueto return only state variables’ equations,Falseto exclude all state variables and any other value to ignore this check.bound=True|False|NoneSet to
Trueto return only bound variables’ equations,Falseto exclude all bound variables and any other value to ignore this check.deep=True|False(by default it’sFalse)Set to
Trueto include the equations of nested variables meeting all other criteria.
- eval()¶
Evaluates this variable’s defining equation and returns the result.
- get(name, class_filter=None)¶
Searches for a variable with the given
qnameand 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 componentinaand a variableina.hwe 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'
- 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:
equationswith the same arguments.
- has_variable(name)¶
Returns True if the given name corresponds to a variable in this object. Accepts both single names
xand qualified namesx.yas input.This function performs the same search as
variable, so in most cases it will be more efficient to callvariable()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:
variableswith the same arguments.
- index()¶
For state variables, this will return their index in the state vector.
For all other variables, this will raise an exception.
- initial_value(as_float=False)¶
Returns a state variable’s initial value, or raises an exception when called on a non-state variable.
By default, a
myokit.Expressionis returned. To evaluate and return a float setas_float=True.
- is_ancestor(obj)¶
Returns
Trueif this object is an ancestor of the givenModelPart`object.
- is_bound()¶
Returns
Trueif a binding label has been added to this variable.
- is_constant()¶
Returns
Trueif this variable has a constant value (even if that value is defined in terms of other constants).Myokit doesn’t discern between mathematical and physical constants, parameters etc. Anything that doesn’t change during a simulation is termed a constant. Note that this specifically excludes variables that define a _binding_ to an external input.
- is_intermediary()¶
Returns
Trueif this variable is an intermediary variable, i.e. not a constant, not a state variable, and not bound to an external input such as time.
- is_labelled()¶
Returns
Trueif a label has been added to this variable.
- is_literal()¶
Returns
Trueif this variable does not depend on other variables.
- is_nested()¶
Returns
Trueif this variable’s parent is another variable.
- is_referenced()¶
Returns
Trueif other variables reference this variable’slhs. For states, this means it only returnsTrueif other variables depend on this variable’s derivative.
- is_state()¶
Returns
Trueif this variable is a state variable.
- label()¶
Returns this variable’s label or
Noneif no label is set.
- lhs()¶
Returns the left-hand side of the equation defining this variable.
For state variables this will be a
myokit.Derivative, for all others this should be amyokit.Name.
- model()¶
Returns the
myokit.Modelthis object belongs to (if set).
- move_variable(variable, new_parent, new_name=None)¶
Moves the given variable to another
VarOwnernew_parent. In addition, this method can be used to rename variables (either with or without moving them).
- name()¶
Returns this object’s name.
- parent(kind=None)¶
Returns this object’s parent.
If the optional variable
kindis set, the method will scan until an instance of the requested type is found.
- promote(initial_value=0, state_value=None)¶
Turns this variable into a state variable with an initial value given by
initial_value.The new
initial_valueshould be:A numerical value.
A string which can be parsed to a
myokit.Expression. Any references to variables must be made using their fully qualified names.
Note that expressions can contain references to non-nested and constant-valued variables (i.e. their right-hand side is either a literal expression or refers only to constants).
Calling
promotewill reset the validation status of the model this variable belongs to.(The argument
state_valueis a deprecated alias forinitial_value.)
- pyfunc(use_numpy=True, arguments=False)¶
Returns a python function that evaluates this variable as a function of the state variables it depends on.
The argument names used by the returned function will be the variables’ unames, ordered alphabetically.
If the function runs in “numpy-mode”, which is enabled by default, the vector ready versions of
log,expetc are used and piecewise statements are evaluated using an array ready piecewise function. To disable this functionality, setuse_numpy=False.To obtain more information about the arguments in the created function handle, set the optional argument
argumentstoTrue. With this setting, the function will return a tuple(handle, vars)wherehandleis the function handle andvarsis a list ofmyokit.LhsExpressionobjects in the same order as the function arguments.
- qname(hide=None)¶
Returns this object’s fully qualified name. That is, an object named
ywith a parent namedxwill return the stringx.y. Ifyhas a childzits qname will bex.y.z.If the optional argument
hideis set to this object’s parent the parent qualifier will be omitted.
- refs_by(state_refs=False)¶
Returns an iterator over the set of
Variablesthat refer to this variable.By default (
state_refs=False), the returned variables all refer to this variable’s definingLhsExpression, i.e. the one returned bylhs().For example:
a = 2 b = 1 + a a.refs_by() will include b
But references to state values are not counted:
dot(a) = 2 b = 1 + a c = 1 + dot(a) a.refs_by() will include c, but not b
To see who refers to this variable’s state value, use
state_refs=True:dot(a) = 2 b = 1 + a c = 1 + dot(a) a.refs_by(True) will include b, but not c
Calling
refs_by(True)on a non-state variable will raise anException.
- refs_to(state_refs=False)¶
Returns an iterator over the set of
Variablesthat this variable’s defining equation refers to.By default, this will _not_ include references to a state variable’s value. To obtain a list of state variables whose value is referenced, use
state_refs=True.See also:
refs_by().
- remove_child_variables()¶
Removes all child variables of this variable.
A
myokit.IntegrityErrorwill be raised if the variable depends on any of its child variables.
- remove_variable(variable, recursive=False)¶
Removes the given variable from this
VarOwnerand from the model.If
recursiveisTrue, any child variables will be deleted as well.A
myokit.IntegrityErrorwill be raised if the variable cannot be removed because other variables depend on it. (Although dependencies from child variables will be ignored ifrecursiveis set toTrue).
- rename(new_name)¶
Renames this variable.
- rhs()¶
Returns the right-hand side of the equation defining this variable.
For state variables this will be the expression for their derivative, for all others an expression for their value is returned.
- set_binding(binding)¶
Adds a unique binding label to this variable, indicating it can be used as an entry point for external inputs.
To remove a binding, call
set_binding(None).Adding or removing binding labels resets the model’s validation status.
- set_initial_value(value)¶
Sets the initial value of a state variable, or raises an exception if called on a non-state variable.
The new value can be passed in as an expression, number, or a string (in which case it will be parsed as an expression). Expressions can refer to variables as long as they are not nested and are constant in time. Variable references in strings must be made using fully qualified names (
component.variable).
- set_label(label=None)¶
Adds a unique
labelfor this variable, indicated that its value can be read by external users.To remove a label call
set_label(None).
- set_rhs(rhs)¶
Changes the expression for this variable’s right hand side (rhs).
For state variables, this updates their derivative. For all others this will update the expression for their value.
Expressions can be specified using
myokit.Expressionobjects, but floats or strings that can be parsed into expressions are also allowed:# Ways of setting x = 2 x.set_rhs(myokit.Number(2)) x.set_rhs(2) x.set_rhs(2.0) x.set_rhs('2') # Ways of setting x = 1 + y x.set_rhs(myokit.Plus(myokit.Number(1), myokit.Name(y))) x.set_rhs('1 + y')
Expressions used as a variable’s right-hand side must be numerical:
myokit.Conditionoperators can not be used as RHS.Calling set_rhs will reset the validation status of the model this variable belongs to.
- set_state_value(value)¶
Deprecated method, use
set_initial_value()instead.
- set_unit(unit=None)¶
Changes this variable’s unit. The unit can be set to any valid Unit object, or
Noneto remove the unit.
- state_value()¶
Deprecated method, use
initial_value(as_float=True)instead.
- uname()¶
Returns a globally unique name for this object.
- unit(mode=1)¶
Returns the unit specified for this variable.
If no unit was set and
modeismyokit.UNIT_TOLERANT, then None is returned. Inmyokit.UNIT_STRICTmode the valuemyokit.units.dimensionlessis returned in this case.Variables’ units are set using
Variable.set_unit()or using theinkeyword in.mmtfiles. The unit set for a variable is the unit this variable’s expression _should_ have. This allows expressions to be validated by computing the resulting unit of an expression and comparing it with the value set for the variable.
- validate()¶
Attempts to check this variable’s validity, raises errors if it isn’t.
- value()¶
Will return the value of this variable’s defining right-hand side expression.
- var(name)¶
Searches for the given variable and returns it if found. Accepts both single names
xand qualified namesx.yas 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|NoneConstants 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
Trueto return only constants,Falseto exclude all constants and any other value to ignore this check.inter=True|False|NoneIntermediary 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
Trueto return only intermediary variables,Falseto exclude all intermediary variables and any other value to ignore this check.state=True|False|NoneSet to True to return only state variables, False to exclude all state variables and any other value to ignore this check.
bound=True|False|NoneSet 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’sFalse)Set to True to return nested variables meeting all other criteria.
sort=True|False(by default it’sFalse)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!)