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

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, with every component nested under it

A dot in a component name nests it (see in_subtree()): "ep" holds the atoms of "ep", "ep.calcium" and "ep.gate". The model need not have a component named "ep" itself. A component with nothing nested under it is returned as it is; otherwise a new Component holds the atoms of all of them, each with its own components. On such a union’s to_ode() model the only component is name; its sub-components are not addressable there.

Parameters:

name (str) – Name of the component

Raises:

KeyError – If the model has no component name and none nested under it

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

remove_singularities(order: int = 3) → ODE[source]#

Guard every removable singularity in the model’s assignments.

A gate rate like x/(exp(x) - 1) has a removable pole that float64 cannot evaluate near, and whose derivative – which the Rush-Larsen linearized block forms by differentiating through intermediates – has a double pole there. Each affected assignment is rewritten in the state variable its pole lives in and wrapped in a Piecewise whose other branch is a truncated Taylor series. See gotranx.singularities for how poles are found and classified.

Parameters:

order (int, optional) – Order of the Taylor replacement, by default 3. Must be at least 1: a constant replacement differentiates to zero, which leaves the linearization silently wrong.

Returns:

A new ODE. This one is unchanged.

Return type:

ODE

rename(mapping: Mapping[str, str]) → ODE[source]#

Return a copy with atoms renamed, e.g. {"a": "q"}.

Renaming a state also renames its derivative. Every rename that is refused is reported at once in a gotranx.exceptions.RenameError, a ValueError; see gotranx.operations.rename().

rescale_time(k: float, components: Iterable[str] | None = None) → ODE[source]#

Return a copy with time rescaled by k (t becomes k * t).

State derivatives of the selected components are multiplied by k; components=None selects every component, and a name that is not a component raises ValueError. k = 0.001 brings a model in seconds onto a clock in milliseconds.

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

split(name: str, inputs: Iterable[str], outputs: Iterable[str]) → ODE[source]#

Return a copy with a new component name carved out of this one.

The new component holds the outputs and what they depend on, up to the inputs and the parameters, e.g. ode.split("mechanics", inputs=["cai"], outputs=["Ta", "J_TRPN"]). Then ode - ode.get_component("mechanics") needs only outputs from it, and the component itself needs only the inputs. What moves keeps its place under the new name: land.crossbridges becomes mechanics.crossbridges. See gotranx.operations.split() for the rules; every problem is reported at once in a gotranx.exceptions.SplitError.

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(glue: bool = False)[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.

Parameters:

glue (bool, optional) – Transform a glue file instead, by default False. The result is then a tuple of gotranx.glue.GlueStatement, in the order of the file (see gotranx.glue.parse_glue()). Without it, replace, += and part.name raise exceptions.GlueOnlyConstruct.

comment(s)[source]#

Convert a comment to an atoms.Comment

expressions(s) → tuple[atoms.Assignment | atoms.Comment, ...] | tuple[GlueStatement, ...][source]#

Convert a list of expressions to atoms.Assignment and atoms.Comment (or to glue statements, in glue mode)

ode(s) → LarkODE | tuple[GlueStatement, ...][source]#

Convert a lark tree to an ODE

Parameters:

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

Returns:

A tuple of components and comments (in glue mode, a tuple of the file’s glue statements, in order)

Return type:

LarkODE

parameters(s: list[Any]) → tuple[atoms.Parameter | atoms.Comment, ...] | tuple[GlueStatement, ...][source]#

Convert a list of parameters to atoms.Parameter (or to glue statements, in glue mode)

states(s: list[Any]) → tuple[State | Comment, ...][source]#

Convert a list of states to atoms.State

gotranx.compose(recipe: str | Path | Mapping[str, Any], *, base_dir: str | Path | None = None, remove_singularities: bool = True) → ODE[source]#

Compose an ODE from the parts and the glue file a recipe names

Parameters:
  • recipe (str | Path | Mapping[str, Any]) – A recipe (TOML) file, or a dict with the same keys. time_unit and parts are required, glue and allow_missing (default false) optional. Each part has a name, a file (.ode or .cellml) and a time_unit, and may rename its names ({old = "new"})

  • base_dir (str | Path | None, optional) – For a dict, the directory relative paths resolve against, by default the current directory. A recipe file’s relative paths resolve against its own directory.

  • remove_singularities (bool, optional) – Guard the composed model’s removable singularities, by default True, as gotranx.load.load_ode() does. The parts are loaded without, so this is done once, on the composed model.

Returns:

The composed model. Each part keeps its components, under its name: part ep’s component gate is ep.gate, and its unnamed one ep, which also holds what the glue defines for ep. get_component("ep") takes them all. Its comments hold the recipe and the sha256 of every file read, and no timestamp, so that composing the same files again saves the same text.

Return type:

gotranx.ode.ODE

Raises:

exceptions.CompositionError – With every message, if anything is wrong. A glue message starts with <glue file>:<line>:.

Notes

A part whose time_unit differs from the model’s has every state derivative multiplied by k, one model time unit in the part’s unit, and t replaced by k*t. The glue is in the model’s time unit.

With allow_missing = true, glue may use names that no part defines; they are the model’s missing variables. Such a model can be saved, but gotranx cannot load an .ode file that uses names it does not define.

components = {<name> = {inputs = [...], outputs = [...]}} calls gotranx.ode.ODE.split() on the composed model, one table after another in recipe order. Names may be written part.name, which is checked against the part and then unqualified. A split that fails is raised as a CompositionError with its messages, each starting components.<name>:.

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

Get the scheme function from a string

gotranx.load_ode(path: str | Path, *, remove_singularities: bool = True) → ODE[source]#

Load an ODE from a file

Parameters:
  • path (str | Path) – Path to the file

  • remove_singularities (bool, optional) – Replace a neighborhood of every removable singularity with a truncated Taylor series, by default True. See ode_from_string().

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, 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.

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.

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, verbatim: bool = False)[source]#

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

A verbatim comment is saved as one line, exactly as it is, where others are wrapped at 80 columns. It is how the comment is printed, not part of what it says, so two comments with the same text are equal either way.

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, 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, 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, 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, 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.make_symbol(name: str) → Symbol[source]#

Create the canonical sympy symbol used for an atom with the given name

Every atom (state, parameter, intermediate, …) with a given name must use a symbol built by this function - sympy symbols with different assumptions are not considered equal even if they share a name (e.g. sp.Symbol("x") != sp.Symbol("x", real=True)), so any code that needs to compare or substitute atom symbols (e.g. via xreplace) must use symbols created here rather than a bare sp.Symbol(name).

Parameters:

name (str) – The name of the symbol

Returns:

The canonical symbol for this name

Return type:

sp.Symbol

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

composition#

Compose an ODE from named parts and a glue file.

A composition has two files:

  • a recipe (TOML), which says which models (parts) are combined and how each is adapted to the others: its name, its file, its time unit and any renames;

  • a glue file, which says how they are coupled, in the .ode grammar plus part.name, replace and += (see gotranx.glue).

The result is an ordinary gotranx.ode.ODE, in which each part keeps its components, each named part.component and so nested under the part (see gotranx.ode.in_subtree()). See compose().

gotranx.composition.compose(recipe: str | Path | Mapping[str, Any], *, base_dir: str | Path | None = None, remove_singularities: bool = True) → ODE[source]#

Compose an ODE from the parts and the glue file a recipe names

Parameters:
  • recipe (str | Path | Mapping[str, Any]) – A recipe (TOML) file, or a dict with the same keys. time_unit and parts are required, glue and allow_missing (default false) optional. Each part has a name, a file (.ode or .cellml) and a time_unit, and may rename its names ({old = "new"})

  • base_dir (str | Path | None, optional) – For a dict, the directory relative paths resolve against, by default the current directory. A recipe file’s relative paths resolve against its own directory.

  • remove_singularities (bool, optional) – Guard the composed model’s removable singularities, by default True, as gotranx.load.load_ode() does. The parts are loaded without, so this is done once, on the composed model.

Returns:

The composed model. Each part keeps its components, under its name: part ep’s component gate is ep.gate, and its unnamed one ep, which also holds what the glue defines for ep. get_component("ep") takes them all. Its comments hold the recipe and the sha256 of every file read, and no timestamp, so that composing the same files again saves the same text.

Return type:

gotranx.ode.ODE

Raises:

exceptions.CompositionError – With every message, if anything is wrong. A glue message starts with <glue file>:<line>:.

Notes

A part whose time_unit differs from the model’s has every state derivative multiplied by k, one model time unit in the part’s unit, and t replaced by k*t. The glue is in the model’s time unit.

With allow_missing = true, glue may use names that no part defines; they are the model’s missing variables. Such a model can be saved, but gotranx cannot load an .ode file that uses names it does not define.

components = {<name> = {inputs = [...], outputs = [...]}} calls gotranx.ode.ODE.split() on the composed model, one table after another in recipe order. Names may be written part.name, which is checked against the part and then unqualified. A split that fails is raised as a CompositionError with its messages, each starting components.<name>:.

gotranx.composition.input_files(recipe: str | Path | Mapping[str, Any], *, base_dir: str | Path | None = None) → list[tuple[str, Path]][source]#

The files composing recipe reads, each with what it is ("the recipe", "the glue file" or "the file of part <name>"), as far as the recipe names them. Nothing is checked: a recipe that cannot be read gives the recipe file alone, and compose() says what is wrong with it.

Parameters are as for compose().

glue#

Glue files: how the parts of a composition are coupled.

A glue file is written in the .ode grammar, in blocks that each name exactly one component (the part the block belongs to), plus three constructs that only glue files accept:

  • part.name, which references a name of another part;

  • replace name = ..., which changes an existing name of the part, in a parameters or an expressions block;

  • dX_dt += ..., which adds a term to a state derivative.

A glue file cannot declare states. This module only parses a glue file into GlueStatement objects; what each statement does to the parts is up to the composition that applies it.

class gotranx.glue.GlueStatement(kind: Literal['new', 'replace', 'add'], block: Literal['parameters', 'expressions'], component: str, name: str, atom: Parameter | Assignment, references: frozenset[tuple[str | None, str]], line: int)[source]#

One statement of a glue file

kind#

name = ..., replace name = ... or dX_dt += ...

Type:

“new”, “replace” or “add”

block#

The kind of block the statement is in

Type:

“parameters” or “expressions”

component#

The block’s component, i.e. the part the statement belongs to

Type:

str

name#

The name the statement defines, replaces or (for “add”) adds to, e.g. "dcai_dt"

Type:

str

atom#

The statement as an atom in component. For “add”, an assignment of the added term to name. Its expression tree may hold part.name (qualified_variable) nodes, which unqualify() replaces

Type:

atoms.Parameter | atoms.Assignment

references#

(part, name) for every name the right-hand side uses, with part None for a bare name

Type:

frozenset[tuple[str | None, str]]

line#

The line of the glue file the statement starts on

Type:

int

gotranx.glue.glue_statement(tree: Tree, block: Literal['parameters', 'expressions'], component: str) → GlueStatement[source]#

Convert the tree of one statement of a glue file to a GlueStatement

Parameters:
  • tree (lark.Tree) – The statement, as parsed

  • block ("parameters" or "expressions") – The kind of block the statement is in

  • component (str) – The component the block names

Returns:

The statement

Return type:

GlueStatement

gotranx.glue.load_glue(path: str | Path) → tuple[GlueStatement, ...][source]#

Load a glue file

Parameters:

path (str | Path) – Path to the file

Returns:

Its statements, in the order of the file

Return type:

tuple[GlueStatement, …]

Raises:
  • exceptions.ODEFileNotFound – If the file is not found

  • UnicodeDecodeError – If the file is not UTF-8, which it is read as, whatever the locale

gotranx.glue.parse_glue(text: str) → tuple[GlueStatement, ...][source]#

Parse the text of a glue file

Parameters:

text (str) – The glue file’s text

Returns:

Its statements, in the order of the file

Return type:

tuple[GlueStatement, …]

Raises:
gotranx.glue.references(tree: Tree) → frozenset[tuple[str | None, str]][source]#

(part, name) for every name used in an expression tree, with part None for a bare name

gotranx.glue.unqualify(tree: Tree) → Tree[source]#

Replace each part.name node of an expression tree with a plain variable node name, which keeps the line number

Parameters:

tree (lark.Tree) – An expression tree, e.g. GlueStatement.atom.value.tree

Returns:

A new tree; tree itself is left unchanged

Return type:

lark.Tree

operations#

Operations that build new ODEs from existing ones.

gotranx.operations.all_atoms(ode: ODE) → tuple[Atom, ...][source]#

The states, parameters, intermediates and state derivatives of an ODE.

gotranx.operations.rebuild(atoms_: Iterable[Atom], *, name: str, comments: Sequence[Comment] = ()) → ODE[source]#

Build an ODE from atoms by printing them to .ode text and parsing it.

Printing uses atom.expr and atom.value, so the result is consistent even if the atoms were modified after parsing. An atom in several components is printed in a block naming all of them. The comments are not parsed again: the result has comments as given, so that each is saved as it was (see gotranx.atoms.Comment).

gotranx.operations.rename(ode: ODE, mapping: Mapping[str, str]) → ODE[source]#

Return a copy of ode with atoms renamed according to mapping.

Renaming a state also renames its derivative. Names may be swapped, {"a": "b", "b": "a"}.

Raises:

gotranx.exceptions.RenameError – A ValueError naming every rename that is refused, and why: a name that is not in the model, a state derivative (rename its state), a new name that is not a valid name, is t or time, is still a name of the model after the other renames, or names the derivative of something that is not a state.

gotranx.operations.rescale_time(ode: ODE, k: float, components: Iterable[str] | None = None) → ODE[source]#

Return a copy of ode whose time is rescaled by k.

With t_new = t_old / k, e.g. k = 0.001 brings a model written in seconds onto a clock in milliseconds. Every state derivative in the selected components is multiplied by k and t is replaced by k * t in every expression of those components. components=None selects all components, and a name selects that component and every component nested under it ("ep" selects "ep.gate", see gotranx.ode.in_subtree()). An assignment in several components is rescaled if any of them is selected.

Raises:
  • ValueError – If k is not positive and finite, or a name in components is not a component of ode.

  • TypeError – If components is a string rather than a sequence of names.

gotranx.operations.split(ode: ODE, name: str, inputs: Iterable[str], outputs: Iterable[str]) → ODE[source]#

Return a copy of ode with a new component name carved out of it.

The new component holds the outputs and everything they depend on, following dependencies until an input or a parameter:

  • A state brings its derivative, and a derivative its state.

  • States, derivatives and intermediates are followed only inside the outputs’ home: the top-level components the outputs belong to, with everything nested under them (ep for ep.gate, see gotranx.ode.in_subtree()). Reaching one outside it is an error: add it to inputs.

  • An intermediate that depends, recursively, only on parameters is followed from any component. If the rest of the model uses it too, it is computed on both sides.

  • A parameter used on both sides is written under both. One used only by the new component moves there.

  • A monitor, an intermediate that no state derivative depends on, in the outputs’ home, joins the new component if it reads a state, a derivative or an intermediate (other than a parameter-only one) of the new component, under the same rules. A monitor outside the home stays, and reads outputs as crossings.

What moves keeps its place under the new component: each of its components in the outputs’ home has its top-level name replaced by name, so land.crossbridges becomes mechanics.crossbridges and land becomes mechanics. An atom with no component in the home goes to name itself. What is on both sides keeps its components and gains those. Everything else stays where it was. So the declared inputs are exactly what the new component needs from the rest, and the outputs the only things of the new component the rest may use (an output need not be used).

Raises:
  • TypeError – If inputs or outputs is a string rather than a sequence of names.

  • gotranx.exceptions.SplitError – With every message at once: a name that is not in the model, name already a component or a component with others nested under it, no outputs, a dependency outside the outputs’ home, an input the new component computes or does not need, and the rest using something of the new component that is not an output. An unknown output, or none, stops the checks that follow the outputs’ dependencies, since they would mislead.

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.CompositionError(messages: list[str])[source]#

Everything wrong with a composition: its recipe, its parts or its glue.

The messages are collected before this is raised, and str() lists them one per line. A glue file’s messages start with <glue file>:<line>:.

exception gotranx.exceptions.DuplicateSymbolError(duplicates: 'set[str]')[source]#
exception gotranx.exceptions.GlueOnlyConstruct(line: int | None = None)[source]#

A plain .ode file used one of the constructs only glue files accept.

exception gotranx.exceptions.GotranxError[source]#
exception gotranx.exceptions.GotranxImportError(module: 'str')[source]#
exception gotranx.exceptions.InvalidGlueBlock(message: str, line: int | None = None)[source]#

A glue block that declares states, or does not name exactly one component.

exception gotranx.exceptions.InvalidModelName(name: 'str')[source]#
exception gotranx.exceptions.InvalidNamespace(name: 'str')[source]#
exception gotranx.exceptions.InvalidODEException(text: 'str', atoms: 'tuple[Atom, ...]')[source]#
exception gotranx.exceptions.InvalidSupertype(supertype: 'object')[source]#
exception gotranx.exceptions.InvalidTreeError(tree: 'lark.Tree')[source]#
exception gotranx.exceptions.MissingPotentialState(v_name: 'str', ode_name: 'str', state_names: 'list[str]')[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.RenameError(problems: dict[str, str])[source]#

Everything wrong with a rename (gotranx.ode.ODE.rename()).

problems maps each name whose rename is refused to the reason, in the order of the mapping; the other names could be renamed. str() lists the messages, one per line.

exception gotranx.exceptions.ReservedName(name: 'str', backend: 'str')[source]#
exception gotranx.exceptions.ResolveExpressionError(name: 'str')[source]#
exception gotranx.exceptions.SplitError(messages: list[str])[source]#

Everything wrong with a split (gotranx.ode.ODE.split()).

The messages are collected before this is raised, and str() lists them one per line.

exception gotranx.exceptions.StateNotFoundInComponent(state_name: 'str', component_name: 'str')[source]#
exception gotranx.exceptions.UnknownStatement(word: str, line: int | None = None)[source]#

A two-word statement, <word> name = ..., whose first word is not replace.

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

linearization#

gotranx.linearization.diagonal_jacobian(ode: ODE, remove_unused: bool = False) → dict[str, Expr][source]#

Compute \(\partial f_i / \partial y_i\) for every state.

This is the diagonal of the Jacobian of the full right-hand side, which is the quantity the generalized Rush-Larsen method is defined in terms of. It differentiates through intermediate assignments, so it does not depend on whether the model author named a subexpression.

Implemented as forward-mode automatic differentiation: one tangent sweep per state over the topologically sorted assignments, seeded at that state.

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

  • remove_unused (bool, optional) – Sweep only the assignments the state derivatives depend on, by default False. Should match the value passed to ode.sorted_assignments by the caller.

Returns:

Mapping from state name to its diagonal Jacobian entry. Every state of the ODE is present; an entry may be zero, which means the derivative genuinely does not depend on its own state.

Return type:

dict[str, sympy.Expr]

gotranx.linearization.gating_states(ode: ODE, remove_unused: bool = False) → list[str][source]#

The states whose right-hand side is affine in the state itself.

These are the states the classic Rush-Larsen method integrates exponentially: \(f_i = a_i y_i + b_i\) with \(a_i \ne 0\) and \(a_i\), \(b_i\) independent of \(y_i\) (e.g. a Hodgkin-Huxley gate \((m_\infty - m)/\tau_m\)). A state qualifies when

  • its diagonal Jacobian entry \(a_i\) is not zero,

  • \(\partial a_i / \partial y_i\) is structurally zero, and

  • no conditional that \(f_i\) depends on has a condition that depends on \(y_i\) (differentiation ignores conditions, so a branch switch on \(y_i\) would otherwise go unnoticed).

Anything that cannot be shown to satisfy these is not gating.

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

  • remove_unused (bool, optional) – Passed on to ode.sorted_assignments, by default False

Returns:

The names of the gating states, in ode.states order

Return type:

list[str]

load#

gotranx.load.load_ode(path: str | Path, *, remove_singularities: bool = True) → ODE[source]#

Load an ODE from a file

Parameters:
  • path (str | Path) – Path to the file

  • remove_singularities (bool, optional) – Replace a neighborhood of every removable singularity with a truncated Taylor series, by default True. See ode_from_string().

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', *, remove_singularities: bool = True) → 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”

  • remove_singularities (bool, optional) – Replace a neighborhood of every removable singularity with a truncated Taylor series, by default True. Pass False to get the expressions exactly as written, which will divide by zero wherever the model has a removable pole – numpy warns and returns nan there, numba crashes – and whose derivative, which the Rush-Larsen schemes form, is wrong by an O(1) amount with a possibly wrong sign well before that.

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: myokit.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') → myokit.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: myokit.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, with every component nested under it

A dot in a component name nests it (see in_subtree()): "ep" holds the atoms of "ep", "ep.calcium" and "ep.gate". The model need not have a component named "ep" itself. A component with nothing nested under it is returned as it is; otherwise a new Component holds the atoms of all of them, each with its own components. On such a union’s to_ode() model the only component is name; its sub-components are not addressable there.

Parameters:

name (str) – Name of the component

Raises:

KeyError – If the model has no component name and none nested under it

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

remove_singularities(order: int = 3) → ODE[source]#

Guard every removable singularity in the model’s assignments.

A gate rate like x/(exp(x) - 1) has a removable pole that float64 cannot evaluate near, and whose derivative – which the Rush-Larsen linearized block forms by differentiating through intermediates – has a double pole there. Each affected assignment is rewritten in the state variable its pole lives in and wrapped in a Piecewise whose other branch is a truncated Taylor series. See gotranx.singularities for how poles are found and classified.

Parameters:

order (int, optional) – Order of the Taylor replacement, by default 3. Must be at least 1: a constant replacement differentiates to zero, which leaves the linearization silently wrong.

Returns:

A new ODE. This one is unchanged.

Return type:

ODE

rename(mapping: Mapping[str, str]) → ODE[source]#

Return a copy with atoms renamed, e.g. {"a": "q"}.

Renaming a state also renames its derivative. Every rename that is refused is reported at once in a gotranx.exceptions.RenameError, a ValueError; see gotranx.operations.rename().

rescale_time(k: float, components: Iterable[str] | None = None) → ODE[source]#

Return a copy with time rescaled by k (t becomes k * t).

State derivatives of the selected components are multiplied by k; components=None selects every component, and a name that is not a component raises ValueError. k = 0.001 brings a model in seconds onto a clock in milliseconds.

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

split(name: str, inputs: Iterable[str], outputs: Iterable[str]) → ODE[source]#

Return a copy with a new component name carved out of this one.

The new component holds the outputs and what they depend on, up to the inputs and the parameters, e.g. ode.split("mechanics", inputs=["cai"], outputs=["Ta", "J_TRPN"]). Then ode - ode.get_component("mechanics") needs only outputs from it, and the component itself needs only the inputs. What moves keeps its place under the new name: land.crossbridges becomes mechanics.crossbridges. See gotranx.operations.split() for the rules; every problem is reported at once in a gotranx.exceptions.SplitError.

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.in_subtree(component: str, name: str) → bool[source]#

Whether the component named component is name or nested under it.

A dot in a component name nests it under every prefix that ends before a dot: "ep.gate" is under "ep", and "a.b.c" under "a.b" and "a", but "epa" is not under "ep".

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

gotranx.ode.top_level(component: str) → str[source]#

The first dotted segment of a component name: "ep" for "ep.gate"

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

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, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#
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, cse: bool = True) → 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\)

The linearization \(g = \partial f_i / \partial y_i\) is the diagonal of the Jacobian of the full right-hand side, computed by differentiating through intermediate expressions. It therefore does not depend on whether the model author named a subexpression.

If \(g\) is zero the update reduces to \(x_{n+1} = x_n + dt f\), which is the exact \(g \to 0\) limit of the expression above, not a fallback.

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

  • cse (bool, optional) – Factor shared subexpressions out of the linearized expressions with one sympy.cse pass across every linearized state at once, by default True. This costs far fewer operations than inlining them (1.08x the rhs against 9.43x, on ToRORd_dyn_chloride) at the price of one named local per factored subexpression. Pass False to inline instead, which emits no temporaries at all – worth it only on the vectorized numpy backend, where each of those locals is a live array held until the generated function returns.

Returns:

A list of equations as strings

Return type:

list[str]

gotranx.schemes.generalized_rush_larsen_2(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, cse: bool = True) → list[str][source]#

Generate the second-order generalized Rush-Larsen scheme for the ODE

With \(a_i = \partial f_i / \partial y_i\) and \(\varphi(a, h) = (e^{a h} - 1)/a\), one step is

\[\begin{split}y^*_i &= y_i + f_i(t_n, y)\, \varphi(a_i(t_n, y), \Delta t/2) \\ y^{n+1}_i &= y_i + \left[f_i^* + a_i^* (y_i - y^*_i)\right] \varphi(a_i^*, \Delta t)\end{split}\]

where \(f^*\) and \(a^*\) are evaluated at \((t_n + \Delta t/2, y^*)\). The bracket is the linearization of \(f_i\) around \(y^*\) evaluated at \(y_n\), which makes the step exact for a gate with frozen coefficients (Sundnes et al. 2009, Perego & Veneziani 2009). States with a zero diagonal entry get explicit midpoint.

This differs from goss’s GRL2, which uses \(f(y^*)\) as the numerator and evaluates the second stage at \(t_n\); that variant converges at first order on stiff, non-autonomous problems.

Missing variables (values supplied by the caller) are held constant over the step. The generated code evaluates the model twice, so it is about twice the size of generalized_rush_larsen().

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

  • cse (bool, optional) – Factor shared subexpressions out of the linearized expressions of each stage, by default True (see generalized_rush_larsen())

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, cse: bool = True) → 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.

The linearization \(g = \partial f_i / \partial y_i\) is the diagonal of the Jacobian of the full right-hand side, computed by differentiating through intermediate expressions. It therefore does not depend on whether the model author named a subexpression.

If \(g\) is zero the update reduces to \(x_{n+1} = x_n + dt f\), which is the exact \(g \to 0\) limit of the expression above, not a fallback.

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) – States to integrate with the Rush-Larsen update; all others use forward Euler. By default None, which makes this scheme equivalent to explicit Euler. For a state that can be linearized, this is a cost/accuracy trade-off, not a capability gate: the Rush-Larsen update costs an exponential per state per step. The exception is a state whose derivative does not depend on itself; it gets forward Euler regardless (the exact g -> 0 limit), and a warning is logged.

  • cse (bool, optional) – Factor shared subexpressions out of the linearized expressions with one sympy.cse pass across every linearized state at once, by default True. This costs far fewer operations than inlining them (1.08x the rhs against 9.43x, on ToRORd_dyn_chloride) at the price of one named local per factored subexpression. Pass False to inline instead, which emits no temporaries at all – worth it only on the vectorized numpy backend, where each of those locals is a live array held until the generated function returns.

Returns:

A list of equations as strings

Return type:

list[str]

gotranx.schemes.hybrid_rush_larsen_2(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, cse: bool = True) → list[str][source]#

Generate the second-order hybrid Rush-Larsen scheme for the ODE

The two-stage update of generalized_rush_larsen_2() applied to stiff_states; every other state uses explicit midpoint, so with no stiff states this is the explicit midpoint (RK2) method. A stiff state whose derivative does not depend on itself also gets explicit midpoint, and a warning is logged.

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

  • stiff_states (list[str] | None, optional) – States to integrate with the exponential update, by default None

  • cse (bool, optional) – Factor shared subexpressions out of the linearized expressions of each stage, by default True

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]#
gotranx.schemes.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, cse: bool = True) → list[str][source]#

Generate the (first-order) Rush-Larsen scheme for the ODE

The exponential update of generalized_rush_larsen() is applied to the gating states, i.e. the states whose right-hand side is affine in the state itself (see gotranx.linearization.gating_states()); every other state uses forward Euler. Use hybrid_rush_larsen() to choose the states yourself.

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

  • cse (bool, optional) – Factor shared subexpressions out of the linearized expressions, by default True (see generalized_rush_larsen())

Returns:

A list of equations as strings

Return type:

list[str]

gotranx.schemes.rush_larsen_2(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, cse: bool = True) → list[str][source]#

Generate the second-order Rush-Larsen scheme for the ODE

The two-stage update of generalized_rush_larsen_2() applied to the gating states (see gotranx.linearization.gating_states()); every other state uses explicit midpoint. Use hybrid_rush_larsen_2() to choose the states yourself.

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

  • cse (bool, optional) – Factor shared subexpressions out of the linearized expressions of each stage, by default True

Returns:

A list of equations as strings

Return type:

list[str]

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.cse_hiding_piecewise(exprs, **kwargs)[source]#

sympy.cse, with Piecewise subtrees held opaque.

sympy.cse happily hoists a subexpression out of a Piecewise branch and computes it unconditionally. That is harmless for a branch chosen for convenience and fatal for one chosen to avoid a singularity: the whole point of Piecewise((taylor, Abs(V - v0) < delta), (expr, True)) is that expr is never evaluated near v0, and a hoisted temporary evaluates it everywhere. The same hoist breaks model conditionals that were already written defensively – given two guards sharing (V + 40)/(exp(-(V + 40)/10) - 1), cse emits it as a temporary that is nan at exactly V = -40.

Every Piecewise is replaced by a fresh Dummy before the call, so nothing inside one can be factored out. Afterwards, a Piecewise that ended up used more than once becomes a temporary of its own – cse will not do that for us, because by then it is looking at a bare symbol and sees nothing worth naming – and one used exactly once is restored inline. So a guard shared between two expressions is still computed once, which is most of what CSE was buying here.

hide does not descend into a Piecewise, so a nested guard is always part of its enclosing guard’s subtree and never a temporary of its own. That is what makes it safe to emit every guard temporary ahead of cse’s own: a guard’s expression references only model symbols, never another temporary.

Note that under numpy both branches of the emitted where are still evaluated. That is where semantics, not a hoist; what this function guarantees is that no temporary computed outside a guard divides by zero at the guarded value.

Parameters:
  • exprs (list[sympy.Expr]) – The expressions to factor.

  • **kwargs – Passed straight through to sympy.cse.

Returns:

Exactly what sympy.cse returns: the replacement pairs and the reduced expressions.

Return type:

tuple[list, list]

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(glue: bool = False)[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.

Parameters:

glue (bool, optional) – Transform a glue file instead, by default False. The result is then a tuple of gotranx.glue.GlueStatement, in the order of the file (see gotranx.glue.parse_glue()). Without it, replace, += and part.name raise exceptions.GlueOnlyConstruct.

comment(s)[source]#

Convert a comment to an atoms.Comment

expressions(s) → tuple[atoms.Assignment | atoms.Comment, ...] | tuple[GlueStatement, ...][source]#

Convert a list of expressions to atoms.Assignment and atoms.Comment (or to glue statements, in glue mode)

ode(s) → LarkODE | tuple[GlueStatement, ...][source]#

Convert a lark tree to an ODE

Parameters:

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

Returns:

A tuple of components and comments (in glue mode, a tuple of the file’s glue statements, in order)

Return type:

LarkODE

parameters(s: list[Any]) → tuple[atoms.Parameter | atoms.Comment, ...] | tuple[GlueStatement, ...][source]#

Convert a list of parameters to atoms.Parameter (or to glue statements, in glue mode)

states(s: list[Any]) → tuple[State | Comment, ...][source]#

Convert a list of states to atoms.State

gotranx.transformer.check_statement_word(tree: Tree) → None[source]#

Raise exceptions.UnknownStatement if tree is a two-word statement whose first word is not replace.

The grammar reads any two names before =, so that replace stays an ordinary name everywhere else.

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[Any]) → tuple[int, tuple[str, ...]][source]#

Find components in a list

Parameters:

s (list[Any]) – The list

Returns:

The index and the components

Return type:

tuple[int, tuple[str, …]]

gotranx.transformer.first_line(items: list[Any]) → int | None[source]#

The line of the first token in items (searching trees depth first), if any

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[Any], cls: type[T]) → tuple[T | Comment, ...][source]#

Convert a list of lark trees to parameters

Parameters:
  • s (list[Any]) – The list

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

Returns:

The parameters and any standalone comments

Return type:

tuple[T | atoms.Comment, …]

gotranx.transformer.refuse_glue_constructs(items: list[Any]) → None[source]#

Raise if a block of a plain .ode file holds a glue-only construct

Parameters:

items (list[Any]) – The children of a states, parameters or expressions block

Raises:
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.compose(recipe: ~pathlib.Path = <typer.models.ArgumentInfo object>, outname: ~pathlib.Path | None = <typer.models.OptionInfo object>, version: bool = <typer.models.OptionInfo object>, license: bool = <typer.models.OptionInfo object>) → None[source]#

Compose parts and a glue file into one .ode model, and print what each part or split needs from the others

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, cse: bool = True) → 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

  • cse (bool, optional) – Factor out subexpressions shared by the linearized expressions in the rush larsen schemes, by default True. False inlines them instead, emitting no temporaries

Returns:

The C code

Return type:

str

gotran2py#

class gotranx.cli.gotran2py.Backend(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#
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, cse: bool = True, 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

  • cse (bool, optional) – Factor out subexpressions shared by the linearized expressions in the rush larsen schemes, by default True. False inlines them instead, emitting no temporaries

  • 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]#
float_type = 'double'#

The floating point type of every state, parameter, value and local

missing_variables_argument = 'const double *__restrict missing_variables'#

How a function declares its missing-variables argument (C needs a type).

restrict = '__restrict'#

How a pointer argument is declared free of aliasing

gotranx.codegen.CFormat#

alias of Format

class gotranx.codegen.CUDACodeGenerator(ode: ODE, format: Format = Format.clang_format, remove_unused: bool = False, namespace: str | None = None, float_type: FloatType | str = FloatType.double)[source]#

CUDA kernels: one thread per cell, all cells’ states stored state-major.

State i of cell cell is states[i * n_cells + cell], and likewise for the values a kernel writes and for the missing variables; the parameters are shared by every cell. Each kernel takes the number of cells as its last argument. states and values are not __restrict__, so a scheme may update the states in place.

restrict = '__restrict__'#

How a pointer argument is declared free of aliasing

class gotranx.codegen.CUDACodePrinter(float_type: str = 'double', *args, **kwargs)[source]#

The C++ printer for CUDA device code.

Math functions are printed without std:: (exp(x)), which resolves to CUDA’s device overloads for both float and double. Every integer is printed as a floating point literal: sqrt(5) would resolve to the C++ library’s constexpr integer overload, which is host-only and cannot be called from a kernel.

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

missing_variables_argument = 'missing_variables'#

How a function declares its missing-variables argument (C needs a type).

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.CppCodeGenerator(ode: ODE, format: Format = Format.clang_format, remove_unused: bool = False, namespace: str | None = None, float_type: FloatType | str = FloatType.double)[source]#

C++17 code: the C generator’s functions, inline and in a namespace.

gotran2cpp.get_code puts the pieces in namespace <namespace> { … }; the namespace defaults to the ODE’s name.

class gotranx.codegen.CytoZooCodeGenerator(ode: ODE, model_name: str | None = None, v_name: str | None = 'v', remove_unused: bool = False, type_stable: bool = True, supertype: str = 'AbstractCardiacCellModel')[source]#

Emit a CytoZoo cell-model adapter.

Subclasses the Julia generator so every expression, every TYPE(…)-wrapped literal and every assignment block is shared rather than reimplemented. What differs is the RHS signature (Task 5), the parameter assignments (Task 5) and the adapter block below.

adapter() → str[source]#

The struct, name tuples, index lookups and interface methods.

class gotranx.codegen.FloatType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#
class gotranx.codegen.Func(arguments, states, parameters, values, values_type, return_name, num_return_values, post_function_signature)[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

post_function_signature: str#

Alias for field number 7

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.GotranCppCodePrinter(float_type: str = 'double', *args, **kwargs)[source]#

The C printer with C++17’s std:: math functions.

With float_type=”float” every number is printed as a float literal (2.5f, 2.0f, 1.0f/3.0f), so that no expression is silently promoted to double: in C++, std::pow(x, 2) and std::fmax(0, x) are double for a float x.

class gotranx.codegen.GotranJuliaCodePrinter(type_stable: bool = False, *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.JuliaCodeGenerator(ode: ODE, remove_unused: bool = False, type_stable: bool = False)[source]#
class gotranx.codegen.MTKCodeGenerator(ode: ODE, remove_unused: bool = False)[source]#
generate(remove_unused: bool | None = None) → str[source]#

Generate ModelingToolkit.jl code.

exception gotranx.codegen.MissingPotentialState(v_name: 'str', ode_name: 'str', state_names: 'list[str]')[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, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#
class gotranx.codegen.SchemeArgument(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#

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

missing_variables_argument = 'missing_variables'#

How a function declares its missing-variables argument (C needs a type).

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, post_function_signature)[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

post_function_signature: str#

Alias for field number 7

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, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#
class gotranx.codegen.base.SchemeArgument(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#
class gotranx.codegen.base.Shape(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#

c#

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

The floating point type of every state, parameter, value and local

missing_variables_argument = 'const double *__restrict missing_variables'#

How a function declares its missing-variables argument (C needs a type).

restrict = '__restrict'#

How a pointer argument is declared free of aliasing

class gotranx.codegen.c.Format(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#
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, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#
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, post_function_signature: 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

  • post_function_signature (str) – The code going after the function signature (e.g. ‘where T’ or ‘-> None’)

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