Skip to content

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

Format(
    name,
    kind,
    template,
    suffixes,
    printer,
    options=dict(),
    first_index=0,
)

An output format of the ODE export.

Attributes:

Name Type Description
name str

the name, e.g. "python"

kind Literal['code', 'document']

"code", which simulates the model, or "document", which describes it

template str

the file name of the template in TEMPLATE_DIR

suffixes tuple[str, ...]

the file suffixes write takes the format from, case sensitive

printer str

the key of the math printer in printers.PRINTERS, for code also the language of symbols.code_names

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.

states property

states

The ids of the states, in the order of the odes.

constants property

constants

The ids of the constants, in the order of quantities.

assigned property

assigned

The assigned variables and reactions, in the order of assignments.

quantities property

quantities

The compartments, species, parameters and species references.

A species held as amount is followed by its amount.

from_sbml classmethod

from_sbml(source)

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(fmt, **options)

Render the system in a format, see formats.render.

Parameters:

Name Type Description Default
fmt str

the name of the format, a key of formats.FORMATS

required
**options object

the options of the format

{}

Returns:

Type Description
str

the code or the document

typeset

typeset(dialect='latex', symbols='id', wrap=None)

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 (the math of KaTeX and MathJax as well) or typst

'latex'
symbols Literal['id', 'name']

"id" or "name", what the math symbols are made of

'id'
wrap Callable[[Symbol, str], str] | None

the function every math symbol is transformed with, from its Symbol and its typeset symbol, e.g. into a link to the element Symbol.source names; called for the symbols the documents make up as well, the rate v of a reaction and the amount n of a species

None

Returns:

Type Description
TypesetSystem

the typeset system

Raises:

Type Description
ValueError

for a dialect which is neither latex nor typst or symbols which are neither id nor name

write

write(path, fmt=None, **options)

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_template(template, fmt='python', **options)

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

quantity

quantity(sid)

The quantity of an id, KeyError if it is none.

symbol

symbol(sid)

The symbol of an id, KeyError if it is none.

render

render(system, fmt, **options)

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 FORMATS

required
**options object

the options of the format, see Format.options

{}

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_template(system, template, fmt='python', **options)

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(system, path, fmt=None, **options)

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 render

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.constant is the flag of SBML, Quantity.role the 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 assignment S = n_S / V of origin concentration. 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 amount n_S = S_new * V with 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 (EventAssignment keeps 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 of x for a state, by 0 for a constant, by d(n/V)/dt for 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 is event<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.initial are 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 in Quantity.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

Symbol(sid, name, unit, sbo, kind, element=())

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 (<reaction>_<id>) and the amount of a species (n_<species>)

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 sid: (reaction, id) for a local parameter, (species,) for the amount of a species; empty otherwise, see source

source property

source

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; None if it is not set or needs a conversion, which OdeSystem.initial then holds

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, None for a species in amount without a compartment, which L3 requires and libsbml reads

amount bool | None

a species in amount (hasOnlySubstanceUnits)

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 OdeSystem.amounts

FunctionDefinition dataclass

FunctionDefinition(symbol, arguments, body)

A function definition, called by the math.

Assignment dataclass

Assignment(variable, math, origin)

The value of a variable from its math: a rule, a rate, an initial value.

Participant dataclass

Participant(species, stoichiometry)

A reactant or product with its stoichiometry, a number or a species reference.

Reaction dataclass

Reaction(
    symbol,
    reactants,
    products,
    modifiers,
    reversible,
    rate,
    local_parameters,
)

A reaction; the rate refers to the renamed local parameters.

Ode dataclass

Ode(
    variable,
    rhs,
    origin,
    reaction_terms=None,
    volume=None,
    amount_of=None,
)

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

EventAssignment(variable, math, scale=None, divisor=None)

The new value of a variable when an event is executed.

The new value is value * scale / new(divisor), each part optional:

  • value is math, evaluated as SBML says: at the trigger time if the event uses the values from the trigger time, else at the execution; 1 if math is None;
  • scale is 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 id divisor, 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, None for a species whose amount stays

scale ASTNode | None

V for a concentration assigned as amount n = S * V and for a rescaled concentration, S * V for a concentration whose amount stays

divisor str | None

the compartment whose new size divides a rescaled concentration, S = S_value * V / V_new

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

ModelInfo(sid, name, level, version, notes, units, source)

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_text or text.markdown_text, a unit additionally with its exponents as superscripts and its products as ·, mol·m³, and without ligatures, fl is two letters;
  • an id is code, `k1` in typst and markdown, \texttt{k1} in LaTeX, and is checked to be an SId (ValueError otherwise, 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 than LONG_ID characters 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, LatexPrinter for LaTeX and markdown (in $$ ... $$), TypstPrinter for typst, the ids written as the math symbols of symbols.typeset_names (symbols="id" or "name"): the rate of a reaction is v with the id as subscript, v_{\mathrm{J0}}, the amount of a species held as amount is n with 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) and notes, the paragraphs of the notes;
  • units: the units of the model, each with kind and unit;
  • compartments, parameters: rows with symbol, id, long_id (whether the id is longer than LONG_ID, a template lets its column wrap), name, value (math, empty for a value given by a rule or a conversion), unit and constant; the parameters include the local parameters and the species references with an id; species additionally compartment (math, None for a species in amount without a compartment) and properties (amount or concentration, boundary and constant as text);
  • functions: lhs (f(x, y)) and rhs;
  • 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 with lhs, lines and origin;
  • amounts: the species held as amount, with amount, species and compartment as math;
  • reactions: symbol (v_{J0}), id, long_id, name, equation (math, 2 A + B ⟶ C, ⇌ if reversible, ∅ for no species), modifiers and local_parameters (math, comma separated), lines of the rate;
  • odes: lhs (dS/dt), lines and origin, 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 lines 1/V (v_1 - v_2 ...)), or the rate rule;
  • events: id, name, trigger, delay, priority (math, None without), initial_value, persistent, use_trigger_values and assignments with lhs and rhs, the effective value with the conversion of a size, conversion (None, amount for the amount of a species in concentration, resized for a concentration whose compartment the event resizes to new, V^{new});
  • unsupported: construct and id;
  • options: the options of the rendering.

The headings, labels and sentences of a document are written by its template.

Wrap module-attribute

Wrap = Callable[['Symbol', str], str]

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

TypesetEquation(variable, lhs, lines, origin)

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, None if it is no element

lhs str

the left hand side as math, dS/dt of an ODE

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, reactions or rate_rule for an ODE, the Origin of an assignment

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, v with the id as subscript

id str

the id as code

long_id bool

whether the id is longer than LONG_ID

name str | None

the name as text

equation str

the reaction equation as math, 2 A + B -> C

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

TypesetFunction(variable, id, name, lhs, rhs)

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

TypesetEventAssignment(
    variable,
    lhs,
    rhs,
    conversion,
    species,
    compartment,
    new,
)

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

None, amount for the amount of a species in concentration, resized for a concentration whose compartment the event resizes

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, V^{new}

TypesetUnsupported dataclass

TypesetUnsupported(construct, id, element)

A construct the system does not support, with its element.

Attributes:

Name Type Description
construct str

the construct as text, e.g. algebraic rule

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

TypesetModel(
    title,
    plain_title,
    id,
    level,
    version,
    source,
    sbmlode,
    notes,
)

The model of a document: title, metadata and notes.

TypesetUnit dataclass

TypesetUnit(kind, unit)

A unit of the model, e.g. the unit of time.

TypesetRow dataclass

TypesetRow(
    symbol, id, long_id, name, value, unit, constant
)

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 LONG_ID

name str | None

the name as text

value str | None

the value as math, None for a value given by a rule or a conversion

unit str | None

the unit as text

constant bool

the constant flag of SBML

TypesetSpeciesRow dataclass

TypesetSpeciesRow(
    symbol,
    id,
    long_id,
    name,
    value,
    unit,
    constant,
    compartment=None,
    properties="",
)

Bases: TypesetRow

A species in its table: a row with its compartment and its properties.

TypesetAmount dataclass

TypesetAmount(amount, species, compartment)

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_document(source)

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(doc)

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

unit_term(factor, kind)

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 libsbml.UnitKind_toString names it

required

Returns:

Type Description
str

the term, e.g. ms, 160 s or min; a dimensionless term is its

str

magnitude, the empty string if that is 1

udef_to_string

udef_to_string(udef, model=None)

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, - for a unit definition without units, None without a unit

Raises:

Type Description
ValueError

for an id without a model