API reference

Contents

API reference#

gotranx#

class gotranx.Component(name: str, states: frozenset[State], parameters: frozenset[Parameter], assignments: frozenset[Assignment])[source]#

A Component is a collection of states, parameters and assignments that are given the same tag. This is useful if you have a complicated set of equations and need to group them together.

Raises:

StateNotFound – If component contains a state derivative but not the State

remove_singularities(lookup: dict[str, Atom]) Component[source]#

Remove singularities from the component

Parameters:

lookup (dict[str, atoms.Atom]) – A lookup table for atoms

Returns:

A new component with singularities removed

Return type:

Component

class gotranx.ODE(components: Sequence[BaseComponent], t: Symbol | None = None, name: str = 'ODE', comments: Sequence[Comment] | None = None)[source]#

A class representing an ODE

Parameters:
  • components (Sequence[gotranx.ode_component.BaseComponent]) – The components of the ODE

  • t (sp.Symbol | None, optional) – Symbol representing time, by default None

  • name (str, optional) – Name of the ODE, by default “ODE”

  • comments (Sequence[atoms.Comment] | None, optional) – List of comments, by default None

Raises:

exceptions.DuplicateSymbolError – If a symbol is duplicated

dependents() dict[str, set[str]][source]#

Get a dictionary of dependents for each component

get_component(name: str) BaseComponent[source]#

Get a component by name

Parameters:

name (str) – Name of the component

property intermediates: tuple[Intermediate, ...]#

Get all intermediates in the ODE sorted by name

property missing_variables: dict[str, int]#

Get a dictionary of missing variables for each component

This is relevant if you have different sub odes where the states in one sub ode is a parameter in another sub ode

property num_components: int#

Get the number of components in the ODE

property num_parameters: int#

Get the number of parameters in the ODE

property num_states: int#

Get the number of states in the ODE

property parameters: tuple[Parameter, ...]#

Get all parameters in the ODE

save(path: Path) None[source]#

Save the ODE to a file

Parameters:

path (Path) – The path to save the ODE to

simplify() ODE[source]#

Run sympy’s simplify function on all expressions in the ODE

sorted_assignments(assignments_only: bool = True, remove_unused: bool = False) tuple[Assignment, ...][source]#

Get the assignments in the ODE sorted by dependencies

Parameters:
  • assignments_only (bool, optional) – If True only return assignments otherwise you can include states and parameters as well, by default True

  • remove_unused (bool, optional) – Remove unused variables, by default False

Returns:

The sorted assignments

Return type:

tuple[atoms.Assignment, …]

sorted_state_derivatives() tuple[StateDerivative, ...][source]#

Get the state derivatives in the ODE sorted by dependencies

sorted_states() tuple[State, ...][source]#

Get the states in the ODE sorted by dependencies

property state_derivatives: tuple[StateDerivative, ...]#

Get all state derivatives in the ODE sorted by name

property states: tuple[State, ...]#

Get all states in the ODE

property symbols: dict[str, Symbol]#

Get a dictionary of all symbols in the ODE with the symbol name as key and the symbol as value

class gotranx.Parser(*args, **kwargs)[source]#
class gotranx.TreeToODE(visit_tokens: bool = True)[source]#

Transform a lark tree to an ODE

See https://lark-parser.readthedocs.io/en/latest/recipes.html for more information on how to use lark transformers.

comment(s)[source]#

Convert a comment to an atoms.Comment

expressions(s) tuple[Assignment, ...][source]#

Convert a list of expressions to atoms.Assignment

ode(s) LarkODE[source]#

Convert a lark tree to an ODE

Parameters:

s (list[Any]) – List of objects that could by states, parameters or assignments

Returns:

A tuple of components and comments

Return type:

LarkODE

parameters(s: list[None | Tree | Token]) tuple[Parameter, ...][source]#

Convert a list of parameters to atoms.Parameter

states(s: list[None | Tree | Token]) tuple[State, ...][source]#

Convert a list of states to atoms.State

gotranx.get_scheme(scheme: str) scheme_func[source]#

Get the scheme function from a string

gotranx.load_ode(path: str | Path) ODE[source]#

Load an ODE from a file

Parameters:

path (str | Path) – Path to the file

Returns:

The ODE

Return type:

gotranx.ode.ODE

Raises:

exceptions.ODEFileNotFound – Raised if the file is not found

atoms#

class gotranx.atoms.Assignment(*, name: str, components: tuple[str, ...] = ('',), description: str | None = None, symbol: Symbol | None = None, unit_str: str | None = None, unit: Unit | None = None, value: Expression | None, expr: Expr = 0, comment: Comment | None = None)[source]#

Assignments are object of the form name = value.

remove_singularities(lookup: dict[str, Atom]) Assignment[source]#

Remove singularities from the assignment

Parameters:

lookup (dict[str, Atom]) – A lookup table for atoms

Returns:

A new assignment with singularities removed

Return type:

Assignment

resolve_expression(symbols: dict[str, Symbol]) Assignment[source]#

Resolve the expression of the assignment by building the sympy expression from the expression tree

Parameters:

symbols (dict[str, sp.Symbol]) – A dictionary of all symbols in the model

Returns:

A new Assignment object with the resolved expression

Return type:

Assignment

Raises:

exceptions.ResolveExpressionError – If the expression is not set

simplify() Assignment[source]#

Simplify the expression of the assignment using sympy’s simplify function. This function returns a new Assignment object with the simplified expression.

singularities(lookup: dict[str, Atom]) frozenset[Singularity][source]#

Check if the expression has any singularities and return a list of singularities

to_intermediate() Intermediate[source]#

Convert the Assignment to an Intermediate

to_state_derivative(state: State) StateDerivative[source]#

Convert the Assignment to a StateDerivative

Parameters:

state (State) – The associated state

class gotranx.atoms.Atom(*, name: str, value: float | Expression | sp.core.Number | None, components: tuple[str, ...] = ('',), description: str | None = None, symbol: sp.Symbol = None, unit_str: str | None = None, unit: pint.Unit | None = None)[source]#

Base class for atoms

class gotranx.atoms.Comment(text: str)[source]#

A comment is a string that is not parsed by the parser. It is used to add human readable information to the model.

class gotranx.atoms.Expression(*, tree: Tree)[source]#

An Expression is a group of variables (i.e states, parameters or other expressions) combined with binary operations (i.e +, -, * etc) An Expression is typically a right hand side of an assignment.

class gotranx.atoms.Intermediate(*, name: str, components: tuple[str, ...] = ('',), description: str | None = None, symbol: Symbol | None = None, unit_str: str | None = None, unit: Unit | None = None, value: Expression | None, expr: Expr = 0, comment: Comment | None = None)[source]#

Intermediate is a type of Assignment that is not a StateDerivative

class gotranx.atoms.Parameter(*, name: str, components: tuple[str, ...] = ('',), description: str | None = None, symbol: Symbol | None = None, unit_str: str | None = None, unit: Unit | None = None, value: float | Number)[source]#

A Parameter is a constant scalar value

class gotranx.atoms.State(*, name: str, components: tuple[str, ...] = ('',), description: str | None = None, symbol: Symbol | None = None, unit_str: str | None = None, unit: Unit | None = None, value: float | Number)[source]#

A State is a variable that also has a corresponding state derivative.

class gotranx.atoms.StateDerivative(*, name: str, components: tuple[str, ...] = ('',), description: str | None = None, symbol: Symbol | None = None, unit_str: str | None = None, unit: Unit | None = None, value: Expression | None, expr: Expr = 0, comment: Comment | None = None, state: State)[source]#

A StateDerivative is an Assignment of the form dX_dt = value where X is a state. A StatedDerivative also holds a pointer to the State

resolve_expression(symbols: dict[str, Symbol]) Assignment[source]#

Resolve the expression of the assignment by building the sympy expression from the expression tree

Parameters:

symbols (dict[str, sp.Symbol]) – A dictionary of all symbols in the model

Returns:

A new Assignment object with the resolved expression

Return type:

Assignment

Raises:

exceptions.ResolveExpressionError – If the expression is not set

class gotranx.atoms.TimeDependentState(*, name: str, components: tuple[str, ...] = ('',), description: str | None = None, unit_str: str | None = None, unit: Unit | None = None, value: float | Number, symbol: Function)[source]#

A TimeDependentState is a State, where the symbol is a sympy Function instead of a pure Symbol.

gotranx.atoms.remove_singularities(expr: Expr, singularities: frozenset[Singularity]) Expr[source]#

Remove singularities from an expression recursively using Conditionals

Parameters:
  • expr (sp.Expr) – The expression

  • singularities (frozenset[Singularity]) – The singularities

Returns:

The expression with singularities removed

Return type:

sp.Expr

gotranx.atoms.unit_from_string(unit_str: str | None) Unit | None[source]#

Create a pint unit from a string

Parameters:

unit_str (str | None) – The string representation of the unit

Returns:

It the unit is valid, return the pint unit, else None

Return type:

pint.Unit | None

exceptions#

exception gotranx.exceptions.AssignmentNotFoundInComponent(assignment_name: 'str', component_name: 'str')[source]#
exception gotranx.exceptions.ComponentNotCompleteError(component_name: 'str', missing_state_derivatives: 'list[str]')[source]#
exception gotranx.exceptions.DuplicateSymbolError(duplicates: 'set[str]')[source]#
exception gotranx.exceptions.GotranxError[source]#
exception gotranx.exceptions.InvalidODEException(text: 'str', atoms: 'tuple[Atom, ...]')[source]#
exception gotranx.exceptions.InvalidTreeError(tree: 'lark.Tree')[source]#
exception gotranx.exceptions.MissingSymbolError(symbol: 'str', line_no: 'int')[source]#
exception gotranx.exceptions.ODEFileNotFound(fname: 'Path')[source]#
exception gotranx.exceptions.ParameterNotFoundInComponent(parameter_name: 'str', component_name: 'str')[source]#
exception gotranx.exceptions.ResolveExpressionError(name: 'str')[source]#
exception gotranx.exceptions.StateNotFoundInComponent(state_name: 'str', component_name: 'str')[source]#
exception gotranx.exceptions.UnknownTreeTypeError(datatype: 'str', atom: 'str')[source]#

expressions#

gotranx.expressions.binary_op(op: str, fst, snd)[source]#

Binary operation

Parameters:
  • op (str) – Operation to perform

  • fst (sp.Expr) – First argument

  • snd (sp.Expr) – Second argument

Returns:

The result of the operation

Return type:

sp.Expr

gotranx.expressions.build_expression(root: Tree, symbols: dict[str, Symbol] | None = None) Expr[source]#

Build a sympy expression from a lark tree

Parameters:
  • root (lark.Tree) – The root of the tree

  • symbols (dict[str, sp.Symbol], optional) – A dictionary with symbols, by default None

Returns:

The sympy expression

Return type:

sp.Expr

gotranx.expressions.relational_to_piecewise(expr: Expr) Piecewise[source]#

Convert a relational expression to a piecewise expression

Parameters:

expr (sp.Expr) – The expression to convert

Returns:

The piecewise expression

Return type:

sp.Piecewise

gotranx.expressions.unary_op(op: str, arg)[source]#

Unary operation

Parameters:
  • op (str) – Operation to perform

  • arg (sp.Expr) – The argument

Returns:

The result of the operation

Return type:

sp.Expr

load#

gotranx.load.load_ode(path: str | Path) ODE[source]#

Load an ODE from a file

Parameters:

path (str | Path) – Path to the file

Returns:

The ODE

Return type:

gotranx.ode.ODE

Raises:

exceptions.ODEFileNotFound – Raised if the file is not found

gotranx.load.ode_from_string(text: str, name='ode') ODE[source]#

Create an ODE from a string

Parameters:
  • text (str) – The string to parse

  • name (str, optional) – Name of the ODE, by default “ode”

Returns:

The ODE

Return type:

gotranx.ode.ODE

myokit#

gotranx.myokit.cellml_to_gotran(filename: str | Path) ODE[source]#

Convert a cellml file to gotran ODE by via myokit

Parameters:

filename (str | Path) – The filename of the cellml file

Returns:

The gotran ODE

Return type:

gotranx.ode.ODE

gotranx.myokit.extract_nested_variables(model: Model) tuple[dict[Symbol, Symbol], dict[str, dict[Symbol, Symbol]]][source]#

Extract nested variables from myokit model

Parameters:

model (myokit.Model) – The myokit model

Returns:

A tuple containing all substitutions and component substitutions

Return type:

tuple[dict[sp.Symbol, sp.Symbol], dict[str, dict[sp.Symbol, sp.Symbol]]]

gotranx.myokit.extract_unit(unit: str) str[source]#
gotranx.myokit.extract_unit(unit: None) None

Extract unit from myokit unit

Parameters:

unit (str | None) – The myokit unit

Returns:

Return the unit as a string

Return type:

str | None

gotranx.myokit.gotran_to_cellml(ode: ODE, filename: str | Path) None[source]#

Convert a gotran ODE to cellml file via myokit

Parameters:
  • ode (gotranx.ode.ODE) – The gotran ODE

  • filename (str | Path) – The filename of the cellml file

gotranx.myokit.gotran_to_myokit(ode: ODE, time_component='engine', time_unit='s') Model[source]#

Convert a gotran ODE to myokit model

Parameters:

ode (gotranx.ode.ODE) – The gotran ODE

Returns:

The myokit model

Return type:

myokit.Model

gotranx.myokit.mmt_to_gotran(filename: str | Path) ODE[source]#

Convert a myokit model to gotran ODE

Parameters:

filename (str | Path) – The filename of the myokit model

Returns:

The gotran ODE

Return type:

gotranx.ode.ODE

gotranx.myokit.myokit_to_gotran(model: Model, protocol=None) ODE[source]#

Convert a myokit model to gotran ODE

Parameters:
  • model (myokit.Model) – The myokit model

  • protocol (_type_, optional) – The stimulus protocol used in myokit, by default None

Returns:

The gotran ODE

Return type:

gotranx.ode.ODE

ode#

class gotranx.ode.AllAtoms(symbol_names, symbol_values, symbols, lookup)[source]#
lookup: dict[str, Atom]#

Alias for field number 3

symbol_names: list[str]#

Alias for field number 0

symbol_values: dict[str, set[Any]]#

Alias for field number 1

symbols: dict[str, Symbol]#

Alias for field number 2

class gotranx.ode.ODE(components: Sequence[BaseComponent], t: Symbol | None = None, name: str = 'ODE', comments: Sequence[Comment] | None = None)[source]#

A class representing an ODE

Parameters:
  • components (Sequence[gotranx.ode_component.BaseComponent]) – The components of the ODE

  • t (sp.Symbol | None, optional) – Symbol representing time, by default None

  • name (str, optional) – Name of the ODE, by default “ODE”

  • comments (Sequence[atoms.Comment] | None, optional) – List of comments, by default None

Raises:

exceptions.DuplicateSymbolError – If a symbol is duplicated

dependents() dict[str, set[str]][source]#

Get a dictionary of dependents for each component

get_component(name: str) BaseComponent[source]#

Get a component by name

Parameters:

name (str) – Name of the component

property intermediates: tuple[Intermediate, ...]#

Get all intermediates in the ODE sorted by name

property missing_variables: dict[str, int]#

Get a dictionary of missing variables for each component

This is relevant if you have different sub odes where the states in one sub ode is a parameter in another sub ode

property num_components: int#

Get the number of components in the ODE

property num_parameters: int#

Get the number of parameters in the ODE

property num_states: int#

Get the number of states in the ODE

property parameters: tuple[Parameter, ...]#

Get all parameters in the ODE

save(path: Path) None[source]#

Save the ODE to a file

Parameters:

path (Path) – The path to save the ODE to

simplify() ODE[source]#

Run sympy’s simplify function on all expressions in the ODE

sorted_assignments(assignments_only: bool = True, remove_unused: bool = False) tuple[Assignment, ...][source]#

Get the assignments in the ODE sorted by dependencies

Parameters:
  • assignments_only (bool, optional) – If True only return assignments otherwise you can include states and parameters as well, by default True

  • remove_unused (bool, optional) – Remove unused variables, by default False

Returns:

The sorted assignments

Return type:

tuple[atoms.Assignment, …]

sorted_state_derivatives() tuple[StateDerivative, ...][source]#

Get the state derivatives in the ODE sorted by dependencies

sorted_states() tuple[State, ...][source]#

Get the states in the ODE sorted by dependencies

property state_derivatives: tuple[StateDerivative, ...]#

Get all state derivatives in the ODE sorted by name

property states: tuple[State, ...]#

Get all states in the ODE

property symbols: dict[str, Symbol]#

Get a dictionary of all symbols in the ODE with the symbol name as key and the symbol as value

gotranx.ode.add_temporal_state(components: Sequence[BaseComponent], t: Symbol) tuple[Component, ...][source]#

Add a temporal state to all components

Parameters:
Returns:

The new components with the temporal state

Return type:

tuple[gotranx.ode_component.Component, …]

gotranx.ode.check_components(components: Sequence[BaseComponent])[source]#

Check if all components are complete

Parameters:

components (Sequence[gotranx.ode_component.BaseComponent]) – The components to check

Raises:

exceptions.ComponentNotCompleteError – If a component is not complete

gotranx.ode.find_duplicates(x: Iterable[T]) set[T][source]#

Find duplicates in an iterable. Assumes type is hashable

Parameters:

x (Iterable[T]) – The iterable with potential duplicates

Returns:

List of duplicate values

Return type:

set[T]

gotranx.ode.gather_atoms(components: Sequence[BaseComponent]) AllAtoms[source]#

Gather all atoms from a list of components

Parameters:

components (Sequence[gotranx.ode_component.BaseComponent]) – The components to gather atoms from

Returns:

A named tuple containing all atoms

Return type:

AllAtoms

gotranx.ode.make_ode(components: Sequence[Component], comments: Sequence[Comment] | None = None, name: str = 'ODE') ODE[source]#

Create an ODE from a list of components

Parameters:
  • components (Sequence[gotranx.ode_component.Component]) – The components to create the ODE from

  • comments (Sequence[atoms.Comment] | None, optional) – The a list of comments, by default None

  • name (str, optional) – Name of the ODE, by default “ODE”

Returns:

The ODE

Return type:

ODE

Raises:

exceptions.DuplicateSymbolError – If a symbol is duplicated

gotranx.ode.resolve_expressions(components: Sequence[Component], symbols: dict[str, Symbol]) tuple[Component, ...][source]#

Resolve all expressions in a list of components

Parameters:
  • components (Sequence[gotranx.ode_component.Component]) – The components to resolve expressions in

  • symbols (dict[str, sp.Symbol]) – The symbols to resolve the expressions with

Returns:

The new components with resolved expressions

Return type:

tuple[gotranx.ode_component.Component, …]

gotranx.ode.sort_assignments(assignments: Iterable[Assignment], assignments_only: bool = True) tuple[str, ...][source]#

Sort assignments by dependencies using a topological sorter

Parameters:
  • assignments (Iterable[atoms.Assignment]) – The assignments to sort

  • assignments_only (bool, optional) – If True only include assignments. If False you also include states and parameters, by default True.

Returns:

The sorted assignments

Return type:

tuple[str, …]

Raises:

exceptions.GotranxError – If an assignment has a None value

ode_component#

class gotranx.ode_component.BaseComponent(name: str, states: frozenset[State], parameters: frozenset[Parameter])[source]#

A Component is a collection of states, parameters and assignments that are given the same tag. This is useful if you have a complicated set of equations and need to group them together.

Raises:

StateNotFound – If component contains a state derivative but not the State

property atoms: frozenset[Atom]#

Returns all atoms in the component

Returns:

All atoms in the component

Return type:

frozenset[atoms.Atom]

find_assignment(assignment_name: str) Assignment[source]#

Find a assignment by name

Parameters:

assignment_name (str) – The name of the assignment

Returns:

The assignment

Return type:

atoms.Assignment

Raises:

exceptions.AssignmentNotFoundInComponent – If assignment is not found in component

find_parameter(parameter_name: str) Parameter[source]#

Find a parameter by name

Parameters:

parameter_name (str) – The name of the parameter

Returns:

The parameter

Return type:

atoms.Parameter

Raises:

exceptions.ParameterNotFoundInComponent – If parameter is not found in component

find_state(state_name: str) State[source]#

Find a state by name

Parameters:

state_name (str) – The name of the state

Returns:

The state

Return type:

atoms.State

Raises:

exceptions.StateNotFoundInComponent – If state is not found in component

is_complete() bool[source]#

Returns true if all states have a corresponding state derivative

simplify() Component[source]#

Run sympy’s simplify function on all expressions in the ODE

property states_with_derivatives: frozenset[State]#

Returns the states that have a corresponding state derivative

Returns:

The states that have a corresponding state derivative

Return type:

frozenset[atoms.State]

property states_without_derivatives: frozenset[State]#

Returns the states that do not have a corresponding state derivative

Returns:

The states that do not have a corresponding state derivative

Return type:

frozenset[atoms.State]

class gotranx.ode_component.Component(name: str, states: frozenset[State], parameters: frozenset[Parameter], assignments: frozenset[Assignment])[source]#

A Component is a collection of states, parameters and assignments that are given the same tag. This is useful if you have a complicated set of equations and need to group them together.

Raises:

StateNotFound – If component contains a state derivative but not the State

remove_singularities(lookup: dict[str, Atom]) Component[source]#

Remove singularities from the component

Parameters:

lookup (dict[str, atoms.Atom]) – A lookup table for atoms

Returns:

A new component with singularities removed

Return type:

Component

class gotranx.ode_component.MyokitComponent(name: str, states: frozenset[State], parameters: frozenset[Parameter], state_derivatives: frozenset[StateDerivative], intermediates: frozenset[Intermediate])[source]#

A Component is a collection of states, parameters and assignments that are given the same tag. This is useful if you have a complicated set of equations and need to group them together.

Raises:

StateNotFound – If component contains a state derivative but not the State

parser#

class gotranx.parser.Parser(*args, **kwargs)[source]#
gotranx.parser.load_grammar() str[source]#

Load the grammar

Returns:

The grammar

Return type:

str

save#

gotranx.save.write_ODE_to_ode_file(ode: ODE, path: Path) None[source]#

Write an ODE to a file

Parameters:
  • ode (gotranx.ode.ODE) – The ODE

  • path (Path) – The path to write the ODE to

schemes#

class gotranx.schemes.Scheme(value)[source]#

An enumeration.

gotranx.schemes.explicit_euler(ode: ~gotranx.ode.ODE, dt: ~sympy.core.symbol.Symbol, name: str = 'values', printer: ~gotranx.schemes.printer_func = <function default_printer>, remove_unused: bool = False) list[str][source]#

Generate forward Euler equations for the ODE

The forward Euler scheme is given by

\[x_{n+1} = x_n + dt f(x_n, t_n)\]
Parameters:
  • ode (gotranx.ode.ODE) – The ODE

  • dt (sympy.Symbol) – The time step

  • name (str, optional) – Name of array to be returned by the scheme, by default “values”

  • printer (printer_func, optional) – A code printer, by default default_printer

  • remove_unused (bool, optional) – Remove unused variables, by default False

Returns:

A list of equations as strings

Return type:

list[str]

gotranx.schemes.fraction_numerator_is_nonzero(expr)[source]#

Perform a very cheap check to detect if a fraction is definitely non-zero.

gotranx.schemes.generalized_rush_larsen(ode: ~gotranx.ode.ODE, dt: ~sympy.core.symbol.Symbol, name: str = 'values', printer: ~gotranx.schemes.printer_func = <function default_printer>, remove_unused: bool = False, delta: float = 1e-08) list[str][source]#

Generate the forward generalized Rush-Larsen scheme for the ODE

The forward generalized Rush-Larsen scheme is given by

\[x_{n+1} = x_n + \frac{f(x_n, t_n)}{g(x_n, t_n)} \left( e^{g(x_n, t_n) dt} - 1 \right)\]

where \(g(x_n, t_n)\) is the linearization of \(f(x_n, t_n)\) around \(x_n\)

We fall back to forward Euler if the derivative is zero.

Parameters:
  • ode (gotranx.ode.ODE) – The ODE

  • dt (sympy.Symbol) – The time step

  • name (str, optional) – Name of array to be returned by the scheme, by default “values”

  • printer (printer_func, optional) – A code printer, by default default_printer

  • remove_unused (bool, optional) – Remove unused variables, by default False

  • delta (float, optional) – Tolerance for zero division check, by default 1e-8

Returns:

A list of equations as strings

Return type:

list[str]

gotranx.schemes.get_scheme(scheme: str) scheme_func[source]#

Get the scheme function from a string

gotranx.schemes.hybrid_rush_larsen(ode: ~gotranx.ode.ODE, dt: ~sympy.core.symbol.Symbol, name: str = 'values', printer: ~gotranx.schemes.printer_func = <function default_printer>, remove_unused: bool = False, delta: float = 1e-08, stiff_states: list[str] | None = None) list[str][source]#

Generate the hybrid Rush-Larsen scheme for the ODE

The hybrid Rush-Larsen scheme follows the standard Rush_Larsen scheme is given by

\[x_{n+1} = x_n + \frac{f(x_n, t_n)}{g(x_n, t_n)} \left( e^{g(x_n, t_n) dt} - 1 \right)\]

where \(g(x_n, t_n)\) is the linearization of \(f(x_n, t_n)\) around \(x_n\). The difference between the hybrid and the standard is that the user can specify which states are stiff, and the RL scheme will only be used for these states. If the derivative of a state is zero, the scheme falls back to forward Euler.

We fall back to forward Euler if the derivative is zero.

Parameters:
  • ode (gotranx.ODE) – The ODE

  • dt (sympy.Symbol) – The time step

  • name (str, optional) – Name of array to be returned by the scheme, by default “values”

  • printer (printer_func, optional) – A code printer, by default default_printer

  • remove_unused (bool, optional) – Remove unused variables, by default False

  • delta (float, optional) – Tolerance for zero division check, by default 1e-8

  • stiff_states (list[str] | None, optional) – Stiff states, by default None. If no stiff states are provided, the hybrid rush larsen scheme will be the same as the explicit Euler scheme

Returns:

A list of equations as strings

Return type:

list[str]

gotranx.schemes.list_schemes() list[str][source]#

List available schemes

class gotranx.schemes.printer_func(*args, **kwargs)[source]#
class gotranx.schemes.scheme_func(*args, **kwargs)[source]#

sympytools#

gotranx.sympytools.Conditional(cond, true_value, false_value)[source]#

Declares a conditional

Parameters:
  • cond (A conditional) – The conditional which should be evaluated

  • true_value (Any model expression) – Model expression for a true evaluation of the conditional

  • false_value (Any model expression) – Model expression for a false evaluation of the conditional

gotranx.sympytools.ContinuousConditional(cond, true_value, false_value, sigma=1.0)[source]#

Declares a continuous conditional. Instead of a either or result the true and false values are weighted with a sigmoidal function which either evaluates to 0 or 1 instead of the true or false.

Parameters:
  • cond (An InEquality conditional) – An InEquality conditional which should be evaluated

  • true_value (Any model expression) – Model expression for a true evaluation of the conditional

  • false_value (Any model expression) – Model expression for a false evaluation of the conditional

  • sigma (float (optional)) – Determines the sharpness of the sigmoidal function

gotranx.sympytools.jacobi_matrix(ode) MutableDenseMatrix[source]#

Return the Jacobian matrix of the ODE

Parameters:

ode (gotranx.ode.ODE) – The ODE

Returns:

The Jacobian matrix of the ODE

Return type:

sympy.Matrix

gotranx.sympytools.rhs_matrix(ode, max_tries: int = 20) MutableDenseMatrix[source]#

Return a sympy matrix of the right hand side of the ODE

Parameters:
  • ode (gotranx.ode.ODE) – The ODE

  • max_tries (int, optional) – Maximum number of tries to try to replace the symbols, by default 20

Returns:

A sympy matrix of the right hand side of the ODE

Return type:

sympy.Matrix

Raises:

RuntimeError – If the maximum number of tries is reached

gotranx.sympytools.states_matrix(ode) MutableDenseMatrix[source]#

Return a sympy matrix of the states in the ODE

Parameters:

ode (gotranx.ode.ODE) – The ODE

Returns:

A sympy matrix of the states in the ODE

Return type:

sympy.Matrix

transformer#

class gotranx.transformer.LarkODE(components, comments)[source]#
comments: tuple[Comment, ...]#

Alias for field number 1

components: tuple[Component, ...]#

Alias for field number 0

class gotranx.transformer.TreeToODE(visit_tokens: bool = True)[source]#

Transform a lark tree to an ODE

See https://lark-parser.readthedocs.io/en/latest/recipes.html for more information on how to use lark transformers.

comment(s)[source]#

Convert a comment to an atoms.Comment

expressions(s) tuple[Assignment, ...][source]#

Convert a list of expressions to atoms.Assignment

ode(s) LarkODE[source]#

Convert a lark tree to an ODE

Parameters:

s (list[Any]) – List of objects that could by states, parameters or assignments

Returns:

A tuple of components and comments

Return type:

LarkODE

parameters(s: list[None | Tree | Token]) tuple[Parameter, ...][source]#

Convert a list of parameters to atoms.Parameter

states(s: list[None | Tree | Token]) tuple[State, ...][source]#

Convert a list of states to atoms.State

gotranx.transformer.find_assignments(s: Tree | Token | None, components: tuple[str, ...]) list[Assignment][source]#

Find assignments in a tree

Parameters:
  • s (lark.Tree | lark.lexer.Token | None) – The tree

  • components (tuple[str, ...]) – List of components

Returns:

List of assignments

Return type:

list[atoms.Assignment]

gotranx.transformer.find_components(s: list[None | Tree | Token]) tuple[int, tuple[str, ...]][source]#

Find components in a list

Parameters:

s (list[None | lark.tree.Tree | lark.lexer.Token]) – The list

Returns:

The index and the components

Return type:

tuple[int, tuple[str, …]]

gotranx.transformer.get_unit_and_comment_from_assignment(s: Tree) tuple[str | None, Comment | None][source]#

Get the unit and comment from an assignment

Parameters:

s (lark.Tree) – The tree

Returns:

The unit and comment

Return type:

tuple[str | None, atoms.Comment | None]

gotranx.transformer.lark_list_to_parameters(s: list[None | Tree | Token], cls: Type[T]) tuple[T, ...][source]#

Convert a list of lark trees to parameters

Parameters:
  • s (list[None | lark.tree.Tree | lark.lexer.Token]) – The list

  • cls (Type[T]) – The class of the parameters

Returns:

The parameters

Return type:

tuple[T, …]

gotranx.transformer.remove_quotes(s: str) str[source]#

Remove quotes from a string

Parameters:

s (str) – The string

Returns:

The string without quotes

Return type:

str

gotranx.transformer.tree2parameter(s: Tree, components: tuple[str, ...], cls: Type[T]) T[source]#

Convert a lark tree to a parameter

Parameters:
  • s (lark.Tree) – The tree

  • components (tuple[str, ...]) – The components

  • cls (Type[T]) – The class of the parameter

Returns:

The parameter

Return type:

T

Raises:

exceptions.UnknownTreeTypeError – If the tree type is unknown

units#

cli#

gotranx.cli.license_callback(show_license: bool)[source]#

Prints license information.

gotranx.cli.version_callback(show_version: bool)[source]#

Prints version information.

cellml2ode#

gotran2c#

gotranx.cli.gotran2c.get_code(ode: ODE, scheme: list[Scheme] | None = None, format: Format = Format.clang_format, remove_unused: bool = False, missing_values: dict[str, int] | None = None, delta: float = 1e-08, stiff_states: list[str] | None = None) str[source]#

Generate the Python code for the ODE

Parameters:
  • ode (gotranx.ode.ODE) – The ODE

  • scheme (list[Scheme] | None, optional) – Optional numerical scheme, by default None

  • format (gotranx.codegen.python.Format, optional) – The formatter, by default gotranx.codegen.python.Format.black

  • remove_unused (bool, optional) – Remove unused variables, by default False

  • missing_values (dict[str, int] | None, optional) – Missing values, by default None

  • delta (float, optional) – Delta value for the rush larsen schemes, by default 1e-8

  • stiff_states (list[str] | None, optional) – Stiff states, by default None. Only applicable for the hybrid rush larsen scheme

Returns:

The C code

Return type:

str

gotran2py#

class gotranx.cli.gotran2py.Backend(value)[source]#

An enumeration.

gotranx.cli.gotran2py.get_code(ode: ODE, scheme: list[Scheme] | None = None, format: Format = Format.black, remove_unused: bool = False, missing_values: dict[str, int] | None = None, delta: float = 1e-08, stiff_states: list[str] | None = None, backend: Backend = Backend.numpy, shape: Shape = Shape.dynamic) str[source]#

Generate the Python code for the ODE

Parameters:
  • ode (gotranx.ode.ODE) – The ODE

  • scheme (list[Scheme] | None, optional) – Optional numerical scheme, by default None

  • format (gotranx.codegen.python.Format, optional) – The formatter, by default gotranx.codegen.python.Format.black

  • remove_unused (bool, optional) – Remove unused variables, by default False

  • missing_values (dict[str, int] | None, optional) – Missing values, by default None

  • delta (float, optional) – Delta value for the rush larsen schemes, by default 1e-8

  • stiff_states (list[str] | None, optional) – Stiff states, by default None. Only applicable for the hybrid rush larsen scheme

  • backend (Backend, optional) – The backend, by default Backend.numpy

  • shape (Shape, optional) – The shape of the output arrays, by default Shape.dynamic

Returns:

The Python code

Return type:

str

codegen#

class gotranx.codegen.BaseGotranODECodePrinter(settings=None)[source]#
class gotranx.codegen.CCodeGenerator(ode: ODE, format: Format = Format.clang_format, remove_unused: bool = False)[source]#
gotranx.codegen.CFormat#

alias of Format

class gotranx.codegen.CodeGenerator(ode: ODE, remove_unused: bool = False, shape: Shape = Shape.dynamic)[source]#
initial_parameter_values(name='parameters') str[source]#

Generate code for initializing parameter values

Parameters:

name (str, optional) – The name of the variable, by default “parameters”

Returns:

The generated code

Return type:

str

initial_state_values(name='states') str[source]#

Generate code for initializing state values

Parameters:

name (str, optional) – The name of the variable, by default “states”

Returns:

The generated code

Return type:

str

monitor_values(order: RHSArgument | str = RHSArgument.tsp, use_cse=False) str[source]#

Generate code for the right hand side of the ODE

Parameters:
  • order (RHSArgument | str, optional) – The order of the arguments, by default RHSArgument.tsp

  • use_cse (bool, optional) – Use common subexpression elimination, by default False

Returns:

The generated code

Return type:

str

rhs(order: RHSArgument | str = RHSArgument.tsp, use_cse=False) str[source]#

Generate code for the right hand side of the ODE

Parameters:
  • order (RHSArgument | str, optional) – The order of the arguments, by default RHSArgument.tsp

  • use_cse (bool, optional) – Use common subexpression elimination, by default False

Returns:

The generated code

Return type:

str

scheme(f: scheme_func, order=SchemeArgument.stdp, **kwargs) str[source]#

Generate code for the scheme

Parameters:
  • f (schemes.scheme_func) – Function for generating the scheme

  • order (SchemeArgument | str, optional) – The order of the arguments, by default SchemeArgument.stdp

  • kwargs (dict) – Additional keyword arguments to be passed to the scheme function

Returns:

The generated code

Return type:

str

class gotranx.codegen.Func(arguments, states, parameters, values, values_type, return_name, num_return_values)[source]#
arguments: list[str]#

Alias for field number 0

num_return_values: int#

Alias for field number 6

parameters: IndexedBase#

Alias for field number 2

return_name: str#

Alias for field number 5

states: IndexedBase#

Alias for field number 1

values: IndexedBase#

Alias for field number 3

values_type: str#

Alias for field number 4

class gotranx.codegen.GotranCCodePrinter(*args, **kwargs)[source]#
class gotranx.codegen.GotranODECodePrinter(ode: ODE, *args, **kwargs)[source]#
class gotranx.codegen.GotranPythonCodePrinter(settings=None)[source]#
class gotranx.codegen.JaxCodeGenerator(*args, **kwargs)[source]#
class gotranx.codegen.PythonCodeGenerator(ode: ODE, format: Format = Format.black, *args, **kwargs)[source]#
gotranx.codegen.PythonFormat#

alias of Format

class gotranx.codegen.RHSArgument(value)[source]#

An enumeration.

class gotranx.codegen.SchemeArgument(value)[source]#

An enumeration.

base#

class gotranx.codegen.base.CodeGenerator(ode: ODE, remove_unused: bool = False, shape: Shape = Shape.dynamic)[source]#
initial_parameter_values(name='parameters') str[source]#

Generate code for initializing parameter values

Parameters:

name (str, optional) – The name of the variable, by default “parameters”

Returns:

The generated code

Return type:

str

initial_state_values(name='states') str[source]#

Generate code for initializing state values

Parameters:

name (str, optional) – The name of the variable, by default “states”

Returns:

The generated code

Return type:

str

monitor_values(order: RHSArgument | str = RHSArgument.tsp, use_cse=False) str[source]#

Generate code for the right hand side of the ODE

Parameters:
  • order (RHSArgument | str, optional) – The order of the arguments, by default RHSArgument.tsp

  • use_cse (bool, optional) – Use common subexpression elimination, by default False

Returns:

The generated code

Return type:

str

rhs(order: RHSArgument | str = RHSArgument.tsp, use_cse=False) str[source]#

Generate code for the right hand side of the ODE

Parameters:
  • order (RHSArgument | str, optional) – The order of the arguments, by default RHSArgument.tsp

  • use_cse (bool, optional) – Use common subexpression elimination, by default False

Returns:

The generated code

Return type:

str

scheme(f: scheme_func, order=SchemeArgument.stdp, **kwargs) str[source]#

Generate code for the scheme

Parameters:
  • f (schemes.scheme_func) – Function for generating the scheme

  • order (SchemeArgument | str, optional) – The order of the arguments, by default SchemeArgument.stdp

  • kwargs (dict) – Additional keyword arguments to be passed to the scheme function

Returns:

The generated code

Return type:

str

class gotranx.codegen.base.Func(arguments, states, parameters, values, values_type, return_name, num_return_values)[source]#
arguments: list[str]#

Alias for field number 0

num_return_values: int#

Alias for field number 6

parameters: IndexedBase#

Alias for field number 2

return_name: str#

Alias for field number 5

states: IndexedBase#

Alias for field number 1

values: IndexedBase#

Alias for field number 3

values_type: str#

Alias for field number 4

class gotranx.codegen.base.RHSArgument(value)[source]#

An enumeration.

class gotranx.codegen.base.SchemeArgument(value)[source]#

An enumeration.

class gotranx.codegen.base.Shape(value)[source]#

An enumeration.

c#

class gotranx.codegen.c.CCodeGenerator(ode: ODE, format: Format = Format.clang_format, remove_unused: bool = False)[source]#
class gotranx.codegen.c.Format(value)[source]#

An enumeration.

class gotranx.codegen.c.GotranCCodePrinter(*args, **kwargs)[source]#

ode#

class gotranx.codegen.ode.BaseGotranODECodePrinter(settings=None)[source]#
class gotranx.codegen.ode.GotranODECodePrinter(ode: ODE, *args, **kwargs)[source]#

python#

class gotranx.codegen.python.Format(value)[source]#

An enumeration.

class gotranx.codegen.python.GotranPythonCodePrinter(settings=None)[source]#
class gotranx.codegen.python.PythonCodeGenerator(ode: ODE, format: Format = Format.black, *args, **kwargs)[source]#

templates#

class gotranx.templates.Template(*args, **kwargs)[source]#
static init_parameter_values(name: str, parameter_values: list[float], parameter_names: list[str], code: str) str[source]#

The init_parameter_values function is a function that initializes the parameter values of the model.

The function typically return an array of the parameter values, or in the case of C code, it takes a pointer to the array of parameter values and initializes the values in place.

Parameters:
  • name (str) – Name of the return variable

  • parameter_values (list[float]) – Default values for the parameters

  • parameter_names (list[str]) – The names of the parameters

  • code (str) – Additional code to be inserted into the function

Returns:

The code for the init_parameter_values function

Return type:

str

static init_state_values(name: str, state_values: list[float], state_names: list[str], code: str) str[source]#

The init_state_values function is a function that initializes the state values of the model.

The function typically return an array of the state values, or in the case of C code, it takes a pointer to the array of state values and initializes the values in place.

Parameters:
  • name (str) – Name of the return variable

  • state_values (list[float]) – Default values for the states

  • state_names (list[str]) – The names of the states

  • code (str) – Additional code to be inserted into the function

Returns:

The code for the init_state_values function

Return type:

str

static method(name: str, args: str, states: str, parameters: str, values: str, return_name: str | None, num_return_values: int, shape_info: str, values_type: str, missing_variables: str) str[source]#

The method function is a function that generates a method for the model.

One example of a method is the right-hand side of the ODE, which calculates the derivatives of the states. Another example is the monitor values, which calculates the values of the monitors. All the different numerical schemes are also examples of methods.

Parameters:
  • name (str) – The name of the method

  • args (str) – The arguments of the method

  • states (str) – The code for assigning the states

  • parameters (str) – The code for assigning the parameters

  • values (str) – The code for assigning the values

  • return_name (str | None) – The name of the return variable

  • num_return_values (int) – The number of return values

  • shape_info (str) – The shape information of the return values

  • values_type (str) – The type of the values

  • missing_variables (str) – The code for handling missing variables

Returns:

The code for the method

Return type:

str

static missing_index(data: dict[str, int]) str[source]#

The missing_index function is a function that returns the index of the missing value with the given name.

A missing value is a variable that is not part of the state or parameter but is used in the right-hand side of the ODE. This typically happens when the model is not fully defined, and some variables are missing, for example when you split an ODE into two sub-models and variables needs to be passed between them.

Parameters:

data (dict[str, int]) – The data containing the missing value names and their indexes

Returns:

The code for the missing_index function

Return type:

str

static monitor_index(data: dict[str, int]) str[source]#

The monitor_index function is a function that returns the index of the monitor with the given name.

A monitor is a variable that is not part of the state or parameter but is used to monitor the simulation. For example, in a cardiac cell models, different currents across the membrane are examples of monitors.

Parameters:

data (dict[str, int]) – The data containing the monitor names and their indexes

Returns:

The code for the monitor_index function

Return type:

str

static parameter_index(data: dict[str, int]) str[source]#

The parameter_index function is a function that returns the index of the parameter with the given name.

Parameters:

data (dict[str, int]) – The data containing the parameter names and their indexes

Returns:

The code for the parameter_index function

Return type:

str

static state_index(data: dict[str, int]) str[source]#

The state_index function is a function that returns the index of the state with the given name.

Parameters:

data (dict[str, int]) – The data containing the state names and their indexes

Returns:

The code for the state_index function

Return type:

str

c#

python#

Python template for code generation

gotranx.templates.python.acc(all_values: str, next_value: str = '# ') str[source]#

Accumulate values in a string

Parameters:
  • all_values (str) – The accumulated values

  • next_value (str) – The next value to add

Returns:

The accumulated values

Return type:

str

gotranx.templates.python.init_parameter_values(name, parameter_names, parameter_values, code)[source]#

The init_parameter_values function is a function that initializes the parameter values of the model.

The function typically return an array of the parameter values, or in the case of C code, it takes a pointer to the array of parameter values and initializes the values in place.

Parameters:
  • name (str) – Name of the return variable

  • parameter_values (list[float]) – Default values for the parameters

  • parameter_names (list[str]) – The names of the parameters

  • code (str) – Additional code to be inserted into the function (not used in this template)

Returns:

The code for the init_parameter_values function

Return type:

str

gotranx.templates.python.init_state_values(name, state_names, state_values, code)[source]#

The init_state_values function is a function that initializes the state values of the model.

The function typically return an array of the state values, or in the case of C code, it takes a pointer to the array of state values and initializes the values in place.

Parameters:
  • name (str) – Name of the return variable

  • state_values (list[float]) – Default values for the states

  • state_names (list[str]) – The names of the states

  • code (str) – Additional code to be inserted into the function (not used in this template)

Returns:

The code for the init_state_values function

Return type:

str

gotranx.templates.python.method(name, args, states, parameters, values, return_name: str, num_return_values: int, nan_to_num: bool = False, values_type: str = 'numpy.zeros_like(states, dtype=numpy.float64)', shape_info: str = '', missing_variables: str = '', **kwargs)[source]#

The method function is a function that generates a method for the model.

One example of a method is the right-hand side of the ODE, which calculates the derivatives of the states. Another example is the monitor values, which calculates the values of the monitors. All the different numerical schemes are also examples of methods.

Parameters:
  • name (str) – The name of the method

  • args (str) – The arguments of the method

  • states (str) – The code for assigning the states

  • parameters (str) – The code for assigning the parameters

  • values (str) – The code for assigning the values

  • return_name (str | None) – The name of the return variable

  • num_return_values (int) – The number of return values

  • shape_info (str) – The shape information of the return values

  • values_type (str) – The type of the values

  • missing_variables (str) – The code for handling missing variables

  • nan_to_num (bool) – If True, the return values are passed through numpy.nan_to_num with nan=0.0

Returns:

The code for the method

Return type:

str

gotranx.templates.python.missing_index(data: dict[str, int]) str[source]#

The missing_index function is a function that returns the index of the missing value with the given name.

A missing value is a variable that is not part of the state or parameter but is used in the right-hand side of the ODE. This typically happens when the model is not fully defined, and some variables are missing, for example when you split an ODE into two sub-models and variables needs to be passed between them.

Parameters:

data (dict[str, int]) – The data containing the missing value names and their indexes

Returns:

The code for the missing_index function

Return type:

str

gotranx.templates.python.monitor_index(data: dict[str, int]) str[source]#

The monitor_index function is a function that returns the index of the monitor with the given name.

A monitor is a variable that is not part of the state or parameter but is used to monitor the simulation. For example, in a cardiac cell models, different currents across the membrane are examples of monitors.

Parameters:

data (dict[str, int]) – The data containing the monitor names and their indexes

Returns:

The code for the monitor_index function

Return type:

str

gotranx.templates.python.parameter_index(data: dict[str, int]) str[source]#

The parameter_index function is a function that returns the index of the parameter with the given name.

Parameters:

data (dict[str, int]) – The data containing the parameter names and their indexes

Returns:

The code for the parameter_index function

Return type:

str

gotranx.templates.python.state_index(data: dict[str, int]) str[source]#

The state_index function is a function that returns the index of the state with the given name.

Parameters:

data (dict[str, int]) – The data containing the state names and their indexes

Returns:

The code for the state_index function

Return type:

str