API reference¶
The export of a model as its system of ordinary differential equations in python, julia, R, typst, LaTeX and markdown. The guide to it is the Guide, the typed data of an application is described in Typed target.
Export of an SBML model as its system of ordinary differential equations.
OdeSystem.from_sbml analyses a model into its ODE system, which is rendered in the
formats of FORMATS:
from sbmlode import OdeSystem
system = OdeSystem.from_sbml("model.xml")
code = system.render("python", simulator=True)
system.write("model.py")
The methods render, write and render_template of OdeSystem are the functions of
the same names of this package, which take the system as their first argument.
The math of the model is written by the printers of sbmlode.printers,
one per dialect, the text of the model through the helpers of
sbmlode.text, the formats by sbmlode.formats:
python, julia and R code, and typst, LaTeX and markdown documents
(sbmlode.documents), e.g. system.write("model.typ").
FORMATS
module-attribute
¶
FORMATS = {
"python": Format(
name="python",
kind="code",
template="python.py.jinja",
suffixes=(".py",),
printer="python",
options={"simulator": True},
),
"julia": Format(
name="julia",
kind="code",
template="julia.jl.jinja",
suffixes=(".jl",),
printer="julia",
options={"simulator": True},
first_index=1,
),
"r": Format(
name="r",
kind="code",
template="r.R.jinja",
suffixes=(".R", ".r"),
printer="r",
options={"simulator": True},
first_index=1,
),
"typst": Format(
name="typst",
kind="document",
template="typst.typ.jinja",
suffixes=(".typ",),
printer="typst",
options={"standalone": True, "symbols": "id"},
),
"latex": Format(
name="latex",
kind="document",
template="latex.tex.jinja",
suffixes=(".tex",),
printer="latex",
options={"standalone": True, "symbols": "id"},
),
"markdown": Format(
name="markdown",
kind="document",
template="markdown.md.jinja",
suffixes=(".md",),
printer="latex",
options={"standalone": True, "symbols": "id"},
),
}
The formats by their name.
Format
dataclass
¶
An output format of the ODE export.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
the name, e.g. |
kind |
Literal['code', 'document']
|
|
template |
str
|
the file name of the template in |
suffixes |
tuple[str, ...]
|
the file suffixes |
printer |
str
|
the key of the math printer in |
options |
Mapping[str, object]
|
the options the format accepts with their defaults |
first_index |
int
|
the index of the first element of a vector, 0 in python, 1 in julia and R |
OdeSystem
dataclass
¶
OdeSystem(
info,
compartments,
species,
amounts,
parameters,
species_references,
functions,
assignments,
initial,
reactions,
odes,
events,
unsupported,
)
The ODE system of an SBML model, see the module for the semantics.
quantities
property
¶
The compartments, species, parameters and species references.
A species held as amount is followed by its amount.
from_sbml
classmethod
¶
Analyse an SBML model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Path | str | SBMLDocument
|
path, SBML string or document, which is not changed |
required |
Returns:
| Type | Description |
|---|---|
OdeSystem
|
the ODE system |
Raises:
| Type | Description |
|---|---|
ValueError
|
if the source cannot be read or the model is not well defined, e.g. its assignments depend on each other in a cycle |
render
¶
Render the system in a format, see formats.render.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fmt
|
str
|
the name of the format, a key of |
required |
**options
|
object
|
the options of the format |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
the code or the document |
typeset
¶
The system typeset for an application, as typed data instead of a document.
The sections are those of the documents (latex, typst, markdown), which
are rendered from the same data: the ODEs, the reaction rates, the
assignments, the function definitions, the initial values, the events and
the unsupported constructs, every text escaped and every math typeset in
the dialect.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dialect
|
Literal['latex', 'typst']
|
the dialect of the math and the text, |
'latex'
|
symbols
|
Literal['id', 'name']
|
|
'id'
|
wrap
|
Callable[[Symbol, str], str] | None
|
the function every math symbol is transformed with, from its
|
None
|
Returns:
| Type | Description |
|---|---|
TypesetSystem
|
the typeset system |
Raises:
| Type | Description |
|---|---|
ValueError
|
for a dialect which is neither |
write
¶
Write the system to a file in the format of its suffix, see formats.write.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str
|
the path of the file |
required |
fmt
|
str | None
|
the name of the format, by default the format of the suffix |
None
|
**options
|
object
|
the options of the format |
{}
|
Returns:
| Type | Description |
|---|---|
Path
|
the path |
render_template
¶
Render the system with a template of its own, see formats.render_template.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
Path | str
|
the path of the jinja2 template |
required |
fmt
|
str
|
the name of the format whose context the template gets |
'python'
|
**options
|
object
|
the options of the format |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
the rendered template |
render
¶
Render an ODE system in a format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
system
|
OdeSystem
|
the ODE system |
required |
fmt
|
str
|
the name of the format, a key of |
required |
**options
|
object
|
the options of the format, see |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
the code or the document |
Raises:
| Type | Description |
|---|---|
ValueError
|
for an unknown format, an unknown option or a value of an option of the wrong type |
NotImplementedError
|
for code of a model with a construct it does not support |
render_template
¶
Render an ODE system with a template of its own and the context of a format.
The template is a jinja2 template which can include the templates of
TEMPLATE_DIR; it gets the context of context and the filters and functions
of the templates of the formats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
system
|
OdeSystem
|
the ODE system |
required |
template
|
Path | str
|
the path of the template |
required |
fmt
|
str
|
the name of the format whose context and printer the template uses |
'python'
|
**options
|
object
|
the options of the format |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
the rendered template |
Raises:
| Type | Description |
|---|---|
ValueError
|
for an unknown format, an unknown option or a value of an option of the wrong type |
NotImplementedError
|
for a code format and a model with a construct it does not support |
write
¶
Write an ODE system to a file, in the format of its suffix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
system
|
OdeSystem
|
the ODE system |
required |
path
|
Path | str
|
the path of the file |
required |
fmt
|
str | None
|
the name of the format, by default the format of the suffix of the path |
None
|
**options
|
object
|
the options of the format |
{}
|
Returns:
| Type | Description |
|---|---|
Path
|
the path |
Raises:
| Type | Description |
|---|---|
ValueError
|
if no format writes the suffix and no format is given, see also
|
The ODE system¶
The parts of an OdeSystem, the result of the analysis.
Analysis of an SBML model into its system of ordinary differential equations.
OdeSystem.from_sbml resolves the semantics of SBML core once, as roadrunner
implements them, so that a format only prints what the system holds:
- States are the species which are neither constant nor boundary nor assigned
and take part in a reaction, and every compartment, species, parameter and species
reference with a rate rule. Every other quantity is constant or assigned; a
quantity an event changes is constant between the events (
Quantity.constantis the flag of SBML,Quantity.rolethe role in the system). - Species are held as roadrunner holds them, in amount if
hasOnlySubstanceUnits, else in concentration; the reaction terms of a species in concentration are divided by its compartment. A rate rule applies to the species as written. - A species in concentration in a variable compartment (a rate rule, an
assignment rule or an event changes the size) without a rule of its own is held as
its amount
n_<id>(OdeSystem.amounts, made unique against the ids of the model), the quantity SBML conserves when the size changes, and its concentration is the assignmentS = n_S / Vof originconcentration. The amount is a state if the species is a state, else a constant (roadrunner keeps the amount of a boundary or constant species when the size changes). An event which assigns the concentration assigns the amountn_S = S_new * Vwith the size at the execution before the event; an event which changes the size of the compartment of a species in concentration with a rate rule rescales it,S = S * V / V_new(EventAssignmentkeeps the value of SBML and this conversion apart, they are evaluated at different times). The state of an amount takes the place of its species in the order of the states. - Conversion factors: the conversion factor of a species, else of the model, multiplies the reaction terms of the species.
- Stoichiometry is a number, or the id of the species reference if a rule, an initial assignment or an event sets it; a species reference with an id is a quantity of the system.
- Local parameters are renamed to
<reaction id>_<id>, made unique, and are constant parameters of the system. rateOf(x)is replaced by the right hand side ofxfor a state, by0for a constant, byd(n/V)/dtfor a concentration held as amount; the rate of another assigned variable is unsupported.- Assignments (assignment rules, concentrations and reaction rates) are ordered by their dependencies, ties in the order of the document; a cycle is an error.
- Initial values at t=0 (
OdeSystem.initial) are every state, every constant set by an initial assignment or converted between amount and concentration, every assigned variable and the reaction rates these depend on, in one order of their dependencies, so that an initial assignment of a rule and a rule of an initial assignment are both right. - Events keep their trigger as written and get its continuous root function
(
events.trigger_root, of the trigger with its function definitions expanded); an event without an id isevent<index>, one without a trigger never fires. - Defaults as roadrunner holds them: a compartment without a size has the size
1 (its
Quantity.value), a stoichiometry which is not set is 1, a reaction without a kinetic law has the rate 0; a rule, initial assignment, event assignment or function definition without math is ignored (L3V2). - Constants in
OdeSystem.initialare only those set by an initial assignment and those whose value is a conversion with another quantity (a species in concentration with an initial amount, divided by its compartment, and the reverse); every other constant has its value inQuantity.value, so that a value passed for it is kept. - Unsupported constructs are collected as
(construct, element id): algebraic rules,delay, fast reactions, distrib functions, an event assignment to a constant, a trigger without a continuous root function, the rate of an assigned variable. A comp model is flattened first, an L1 or L2 model read as L3V2.
Every math of the system is a deep copy owned by the system, so the document can be
freed; a sum is written with the signs of its terms (astutil.signed_sum). The
analysis itself is sbmlode.analysis. The dataclasses which hold
math compare by identity (eq=False), a libsbml math has no value equality.
Symbol
dataclass
¶
An element with an id: its name, unit, SBO term and kind.
Attributes:
| Name | Type | Description |
|---|---|---|
sid |
str
|
the id in the system, which the analysis makes up or changes for a
renamed local parameter ( |
name |
str | None
|
the name |
unit |
str | None
|
the unit |
sbo |
str | None
|
the SBO term |
kind |
Kind
|
the kind of the element |
element |
tuple[str, ...]
|
the element of the model the symbol stands for, if it is not the
element of |
source
property
¶
The element of the model the symbol stands for.
(sid,) for an element of the model, (reaction, id) for a local parameter
of a reaction, (species,) for the amount of a species; an application which
links a symbol to its element resolves this, e.g. SBML4Humans.
Quantity
dataclass
¶
Quantity(
symbol,
value,
constant,
role,
compartment=None,
amount=None,
boundary=None,
conversion_factor=None,
amount_of=None,
)
A compartment, species, parameter, species reference or amount of a species.
Attributes:
| Name | Type | Description |
|---|---|---|
symbol |
Symbol
|
the symbol |
value |
float | None
|
the value of the document in the representation of the quantity, the
default 1 of a compartment without a size; |
constant |
bool
|
the constant flag of SBML |
role |
Role
|
the role in the system |
compartment |
str | None
|
the compartment of a species or an amount, |
amount |
bool | None
|
a species in amount ( |
boundary |
bool | None
|
the boundary condition of a species |
conversion_factor |
str | None
|
the conversion factor of a species, else of the model |
amount_of |
str | None
|
the species of an amount, see |
FunctionDefinition
dataclass
¶
A function definition, called by the math.
Assignment
dataclass
¶
The value of a variable from its math: a rule, a rate, an initial value.
Participant
dataclass
¶
A reactant or product with its stoichiometry, a number or a species reference.
Reaction
dataclass
¶
A reaction; the rate refers to the renamed local parameters.
Ode
dataclass
¶
The ordinary differential equation of a state.
Attributes:
| Name | Type | Description |
|---|---|---|
variable |
str
|
the state |
rhs |
ASTNode
|
the complete right hand side |
origin |
Literal['reactions', 'rate_rule']
|
the reactions or the rate rule of the state |
reaction_terms |
ASTNode | None
|
the sum of stoichiometry, conversion factor and rate of each reaction of a species, before the division by the volume |
volume |
str | None
|
the compartment the reaction terms are divided by |
amount_of |
str | None
|
the species whose amount the state is |
EventAssignment
dataclass
¶
The new value of a variable when an event is executed.
The new value is value * scale / new(divisor), each part optional:
valueismath, evaluated as SBML says: at the trigger time if the event uses the values from the trigger time, else at the execution;1ifmathisNone;scaleis evaluated at the execution of the event, with the values before any assignment of the event is applied, i.e. after the events executed before it;new(divisor)is the new value of the assignment of the same event to the iddivisor, a compartment which is assigned without scale.
Attributes:
| Name | Type | Description |
|---|---|---|
variable |
str
|
the variable, the amount of a species held as amount |
math |
ASTNode | None
|
the value SBML assigns, |
scale |
ASTNode | None
|
|
divisor |
str | None
|
the compartment whose new size divides a rescaled concentration,
|
Event
dataclass
¶
Event(
symbol,
trigger,
root,
initial_value,
persistent,
delay,
priority,
use_values_from_trigger_time,
assignments,
)
An event; root is the root function of the trigger, None if it has none.
ModelInfo
dataclass
¶
The model: id, name, SBML level and version, notes as plain text, units.
The typeset system¶
The typed data OdeSystem.typeset returns.
The context of the document formats of the ODE export: typst, LaTeX and markdown.
A document describes the model to a reader in the sections of the specification:
title and metadata, units, compartments, species, parameters, function definitions,
initial assignments and assignment rules, reactions, the ODE system, events and the
unsupported constructs. DocumentContext.build gives a template every text and every
math of these as markup of its format, so that a template only lays them out:
- text (names, notes, units, flags) is escaped for the markup of the format with
text.typst_text,text.tex_textortext.markdown_text, a unit additionally with its exponents as superscripts and its products as·,mol·m³, and without ligatures,flis two letters; - an id is code,
`k1`in typst and markdown,\texttt{k1}in LaTeX, and is checked to be an SId (ValueErrorotherwise, libsbml reads a document with any id, which could end the code and write markup; an unsupported element without an id is labelled by its metaid, an XML ID); an id of more thanLONG_IDcharacters may break after an underscore in typst and LaTeX (#sym.zws,\allowbreak), which writes no character, so that a table with long ids fits the page; - math is printed with the printer of the format,
LatexPrinterfor LaTeX and markdown (in$$ ... $$),TypstPrinterfor typst, the ids written as the math symbols ofsymbols.typeset_names(symbols="id"or"name"): the rate of a reaction isvwith the id as subscript,v_{\mathrm{J0}}, the amount of a species held as amount isnwith the symbol of the species as subscript,n_{S}; - a long sum is a list of lines (
DocumentPrinter.print_lines), which a template joins into the lines of an alignment; a line after the first begins with its sign.
The context holds:
model:title(the name, else the id),plain_title(the title without the opportunities of line breaks and without math,text.tex_pdf_text, for the bookmarks of a PDF),id,level,version,source,sbmlode(the version which writes the document) andnotes, the paragraphs of the notes;units: the units of the model, each withkindandunit;compartments,parameters: rows withsymbol,id,long_id(whether the id is longer thanLONG_ID, a template lets its column wrap),name,value(math, empty for a value given by a rule or a conversion),unitandconstant; the parameters include the local parameters and the species references with an id;speciesadditionallycompartment(math,Nonefor a species in amount without a compartment) andproperties(amount or concentration, boundary and constant as text);functions:lhs(f(x, y)) andrhs;initial: the initial assignments and the initial values which are a conversion between amount and concentration,assignments: the assignment rules and the concentrations of the species held as amount, each withlhs,linesandorigin;amounts: the species held as amount, withamount,speciesandcompartmentas math;reactions:symbol(v_{J0}),id,long_id,name,equation(math,2 A + B ⟶ C,⇌if reversible,∅for no species),modifiersandlocal_parameters(math, comma separated),linesof the rate;odes:lhs(dS/dt),linesandorigin, the right hand side written with the rates of the reactions and divided by the volume of a species in concentration ((v_1 - v_2)/V, in lines1/V (v_1 - v_2 ...)), or the rate rule;events:id,name,trigger,delay,priority(math,Nonewithout),initial_value,persistent,use_trigger_valuesandassignmentswithlhsandrhs, the effective value with the conversion of a size,conversion(None,amountfor the amount of aspeciesin concentration,resizedfor a concentration whosecompartmentthe event resizes tonew,V^{new});unsupported:constructandid;options: the options of the rendering.
The headings, labels and sentences of a document are written by its template.
TypesetSystem
dataclass
¶
TypesetSystem(
model,
units,
compartments,
species,
parameters,
functions,
initial,
assignments,
amounts,
reactions,
odes,
events,
unsupported,
)
The system typeset for a dialect, the sections of a document.
Every text is escaped and every math typeset for the dialect; the math symbols
are those wrap of OdeSystem.typeset returns.
TypesetEquation
dataclass
¶
An equation of the system: an ODE, an assignment or an initial value.
Attributes:
| Name | Type | Description |
|---|---|---|
variable |
Symbol | None
|
the symbol of the left hand side, |
lhs |
str
|
the left hand side as math, |
lines |
tuple[str, ...]
|
the right hand side as math, in lines of at most four terms; a line after the first begins with its sign |
origin |
str
|
where the equation comes from, |
TypesetReaction
dataclass
¶
TypesetReaction(
variable,
symbol,
id,
long_id,
name,
equation,
modifiers,
local_parameters,
lines,
)
A reaction: its equation and its rate.
Attributes:
| Name | Type | Description |
|---|---|---|
variable |
Symbol
|
the symbol of the reaction |
symbol |
str
|
the math symbol of its rate, |
id |
str
|
the id as code |
long_id |
bool
|
whether the id is longer than |
name |
str | None
|
the name as text |
equation |
str
|
the reaction equation as math, |
modifiers |
str | None
|
the modifiers as math, comma separated |
local_parameters |
str | None
|
the local parameters as math, comma separated |
lines |
tuple[str, ...]
|
the rate as math in lines |
TypesetFunction
dataclass
¶
A function definition, f(x, y) = ....
TypesetEvent
dataclass
¶
TypesetEvent(
symbol,
id,
name,
trigger,
delay,
priority,
initial_value,
persistent,
use_trigger_values,
assignments,
)
An event: its trigger, delay, priority, flags and assignments.
TypesetEventAssignment
dataclass
¶
An event assignment with its effective value, see DocumentContext.
Attributes:
| Name | Type | Description |
|---|---|---|
variable |
Symbol
|
the symbol of the variable |
lhs |
str
|
the variable as math |
rhs |
str
|
the effective value as math |
conversion |
str | None
|
|
species |
str | None
|
the species of an amount as math |
compartment |
str | None
|
the compartment of the conversion as math |
new |
str | None
|
the new size of the compartment as math, |
TypesetUnsupported
dataclass
¶
A construct the system does not support, with its element.
Attributes:
| Name | Type | Description |
|---|---|---|
construct |
str
|
the construct as text, e.g. |
id |
str
|
the label of the element as code |
element |
str
|
the id of the element, or its metaid for an element without an id |
TypesetModel
dataclass
¶
The model of a document: title, metadata and notes.
TypesetRow
dataclass
¶
A compartment or a parameter in its table.
Attributes:
| Name | Type | Description |
|---|---|---|
symbol |
str
|
the math symbol |
id |
str
|
the id as code |
long_id |
bool
|
whether the id is longer than |
name |
str | None
|
the name as text |
value |
str | None
|
the value as math, |
unit |
str | None
|
the unit as text |
constant |
bool
|
the constant flag of SBML |
TypesetSpeciesRow
dataclass
¶
TypesetAmount
dataclass
¶
A species held as amount: its amount, the species and its compartment.
Reading and units¶
Reading and flattening of SBML documents.
read_document reads a document from a path or an SBML string and raises for a
source which could not be read, flatten resolves the submodels of comp into one
model. Both are what the analysis needs of sbmlutils' read_sbml and
flatten_sbml_doc, on libsbml alone.
read_document
¶
Read a document from a path or an SBML string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Path | str
|
the path of an SBML file or an SBML string |
required |
Returns:
| Type | Description |
|---|---|
SBMLDocument
|
the document; the errors of its content are in its error log, they are for |
SBMLDocument
|
a validation to report |
Raises:
| Type | Description |
|---|---|
ValueError
|
if the source cannot be read, a file which cannot be opened or content which is not well-formed XML, with the errors libsbml reported |
flatten
¶
Flatten the submodels of comp into the model of a document, in place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
doc
|
SBMLDocument
|
the document, with a model |
required |
Returns:
| Type | Description |
|---|---|
SBMLDocument
|
the document |
Raises:
| Type | Description |
|---|---|
ValueError
|
if the document has no model or cannot be flattened |
The string of a unit definition, mmol/min.
The string is the one sbmlutils writes for a unit (sbmlutils.report.units), without
pint: a unit is (multiplier * 10^scale * kind)^exponent, a term multiplier *
10^scale * kind is written with the closest SI prefix, ms, and a magnitude which
is not 1 in front of it, 160 s; a factor which names a unit of its own is written
by that name, min, hr, day, cm. A term of a dimensionless kind (dimensionless,
item, avogadro) gets no prefix. A product is *, a quotient /, a term with a
magnitude is grouped in parentheses when it is a factor of more, mmol/(160 s).
unit_term
¶
The term factor * kind of a unit without its exponent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor
|
float
|
the multiplier times ten to the power of the scale of the unit |
required |
kind
|
str
|
the SBML unit kind, as |
required |
Returns:
| Type | Description |
|---|---|
str
|
the term, e.g. |
str
|
magnitude, the empty string if that is 1 |
udef_to_string
¶
The string of a unit definition.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
udef
|
UnitDefinition | str | None
|
the unit definition, or its id, or the name of a unit kind |
required |
model
|
Model | None
|
the model which resolves an id |
None
|
Returns:
| Type | Description |
|---|---|
str | None
|
the string, |
Raises:
| Type | Description |
|---|---|
ValueError
|
for an id without a model |