Skip to content

factory

Factory for creating SBML objects.

This module provides definitions of helper functions for the creation of SBML objects. These are the low level helpers to create models from scratch and are used in the higher level SBML factories.

The general workflow to create new SBML models isto create a lists/iterables of SBMLObjects by using the respective classes in this module, e.g. Compartment, Parameter, Species.

The actual SBase objects are than created in the SBMLDocument/Model by calling create_objects(model, objects) These functions DO NOT take care of the order of the creation, but the order must be correct in the model definition files. To create complete models one should use the modelcreator functionality, which takes care of the order of object creation.

ReactionEquation

ReactionEquation(
    reactants=None,
    products=None,
    modifiers=None,
    reversible=True,
)

Representation of stoichiometric equations with modifiers.

Initialize equation.

A modifier may be given as a bare species id, which is the documented string syntax, or as a full EquationPart carrying its own SBase fields. Both are stored as EquationPart.

EquationException

Bases: Exception

Exception in Equation.

from_str staticmethod

from_str(equation_str)

Parse components of equation string.

to_string

to_string(modifiers=False)

Get string representation of equation.

info

info()

Print overview of parsed equation.

help staticmethod

help()

Get help information string.

ValidationOptions dataclass

ValidationOptions(
    log_errors=True,
    internal_consistency=True,
    general_consistency=True,
    identifier_consistency=True,
    mathml_consistency=True,
    units_consistency=True,
    sbo_consistency=True,
    overdetermined_model=True,
    modeling_practice=True,
)

Options for SBML validator.

Controls the consistency checks that are performed when SBMLDocument.checkConsistency() is called.

  • general_consistency: Correctness and consistency of specific SBML language constructs. Performing this set of checks is highly recommended. With respect to the SBML specification, these concern failures in applying the validation rules numbered 2xxxx in the Level 2 Versions 2-4 and Level 3 Versions 1-2 specifications.

  • ìdentifier_consistency: Correctness and consistency of identifiers used for model entities. An example of inconsistency would be using a species identifier in a reaction rate formula without first having declared the species. With respect to the SBML specification, these concern failures in applying the validation rules numbered 103xx in the Level 2 Versions 2-4 and Level 3 Versions 1-2 specifications.

  • units_consistency: Consistency of measurement units associated with quantities in a model. With respect to the SBML specification, these concern failures in applying the validation rules numbered 105xx in the Level 2 Versions 2-4 and Level 3 Versions 1-2 specifications.

  • mathml_consistency: Syntax of MathML constructs. With respect to the SBML specification, these concern failures in applying the validation rules numbered 102xx in the Level 2 Versions 2-4 and Level 3 Versions 1-2 specifications.

  • sbo_consistency: Consistency and validity of SBO identifiers (if any) used in the model. With respect to the SBML specification, these concern failures in applying the validation rules numbered 107xx in the Level 2 Versions 2-4 and Level 3 Versions 1-2 specifications.

  • overdetermined_model: Static analysis of whether the system of equations implied by a model is mathematically overdetermined. With respect to the SBML specification, this is validation rule #10601 in the Level 2 Versions 2-4 and Level 3 Versions 1-2 specifications.

  • modeling_practise: Additional checks for recommended good modeling practice. (These are tests performed by libSBML and do not have equivalent SBML validation rules.) By default, all validation checks are applied to the model in an SBMLDocument object unless SBMLDocument.setConsistencyChecks() is called to indicate that only a subset should be applied. Further, this default (i.e., performing all checks) applies separately to each new SBMLDocument object created. In other words, each time a model is read using SBMLReader.readSBML(), SBMLReader.readSBMLFromString(), or the global functions readSBML() and readSBMLFromString(), a new SBMLDocument is created and for that document, a call to SBMLDocument.checkConsistency() will default to applying all possible checks. Calling programs must invoke SBMLDocument.setConsistencyChecks() for each such new model if they wish to change the consistency checks applied.

  • internal_consistency: Additional checks that model is consistent XML.

  • log_errors Boolean flag to log errors.

ModelUnits

ModelUnits(
    time=None,
    extent=None,
    substance=None,
    length=None,
    area=None,
    volume=None,
)

Class for storing model units information.

The ModelUnits define globally the units for time, extent, substance, length, area and volume.

The following SBML Level 3 base units can be used.

ampere farad joule lux radian volt avogadro gram katal metre second watt becquerel gray kelvin mole siemens weber candela henry kilogram newton sievert coulomb hertz litre ohm steradian dimensionless item lumen pascal tesla

Construct ModelUnits.

set_model_units staticmethod

set_model_units(model, model_units)

Set the main units in model from dictionary.

Setting the model units is important for understanding the model dynamics. Allowed keys are: time extent substance length area volume

:param model: SBMLModel :param model_units: dict of units :return:

Sbase

Sbase(
    sid=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
    replacedBy=None,
)

Base class of all SBML objects.

no_authoring_hints staticmethod

no_authoring_hints()

Suppress the hints about a hand written element inside the context.

The name and sboTerm hints of _set_fields help somebody writing a model definition. They are noise when a model is written back out after it was parsed from a file, which is what sbmlutils.parser does, and when the element is built by this module rather than by hand, see _UncertChild._check_states_a_value.

Yields:

Type Description
None

None

create_port

create_port(model)

Create the port of the element, if it has one.

A port which references nothing of its own is made to reference this element, by the reference _port_reference_for names for the document being written: its id, its unit id or its metaid. A port which cannot be written is reported here, once, and Model._has_comp_content asks the same predicate so that it does not declare comp for it, see _port_loss.

Parameters:

Name Type Description Default
model Model | None

the model the port is created in; None for an element which is written without one

required

Returns:

Type Description
Port | None

the port, None if the element has no port or if the port cannot

Port | None

be written

Raises:

Type Description
ValueError

if the document does not declare the comp package

create_uncertainties

create_uncertainties(obj, model)

Create distrib:Uncertainty objects.

create_replaced_by

create_replaced_by(sbase, model)

Create the <comp:replacedBy> of the element, if it has one.

comp allows a <comp:replacedBy> on every SBML element, but libsbml only carries one on an element it attaches a CompSBasePlugin to. Measured with libsbml 5.21.2, it attaches none to a <priority>, to a <distrib:uncertainty> or to any element of fbc (<fbc:geneProduct>, <fbc:objective>, <fbc:fluxObjective>, <fbc:userDefinedConstraint>, <fbc:userDefinedConstraintComponent>, <fbc:keyValuePair>), so it can neither write nor read a replacement there. Those classes do not offer replacedBy, and neither does LocalParameter, on which every form of the replacement is invalid; see their class docstrings.

Parameters:

Name Type Description Default
sbase SBase

the libsbml object the replacement is created on

required
model Model

the libsbml.Model the element belongs to

required

Returns:

Type Description
ReplacedBy | None

the created replacement, None if the element has none

create_key_value_pairs

create_key_value_pairs(sbase, model=None)

Create the fbc:keyValuePair elements of the element.

Parameters:

Name Type Description Default
sbase SBase

the libsbml object the pairs are created on

required
model Model | None

the libsbml.Model the element belongs to, which the port of a pair is created in, see Model._fill_sbml; None writes the pairs without a model, which reports the port of a pair which has one

None

Returns:

Type Description
list[KeyValuePair] | None

the created pairs, None if the element has none or if the

list[KeyValuePair] | None

document cannot carry them, see KeyValuePair.create_pairs

KeyValuePair

KeyValuePair(
    key,
    value,
    uri,
    sid=None,
    name=None,
    sboTerm=None,
    metaId=None,
    notes=None,
    annotations=None,
    port=None,
)

Bases: Sbase

A key-value pair of fbc version 3, which every element can carry.

An fbc version 3 <fbc:keyValuePair> carries its key, value and uri and, like every other SBase, an id, a name, a metaid, an sboTerm, notes and annotations; all of them are written and the document validates. The id and the name are read back from an SBML L3V2 document and not from an L3V1 one, although libsbml writes them into both (measured with libsbml 5.21.2). That is a property of libsbml's reader, not of the document: what is written is in the file either way.

A document of fbc version 2, or one which declares no fbc at all, gets no key-value pair: libsbml answers every attribute of a pair with LIBSBML_UNEXPECTED_ATTRIBUTE in fbc version 2 and attaches no fbc plugin without the package. Both are reported once for the element which carries the pairs, see KeyValuePair.create_pairs and _fbc_version_allows, which answers the same question for an <fbc:userDefinedConstraint>.

Neither uncertainties nor a nested list of keyValuePairs is offered: libsbml creates both on the plugins of a <fbc:keyValuePair> without an error and writes neither into the XML. A replacedBy is not offered either, since libsbml attaches no CompSBasePlugin to the element, see sbmlutils.parser._drop_replaced_by.

A pair which is nested in an UncertParameter, an UncertSpan or in the sBaseRef of a comp reference gets no port. Those three are written without the libsbml.Model a <comp:listOfPorts> lives in, so there is nowhere to create it; the port is reported and the document does not declare comp for it, see Sbase._port_loss. Measured with libsbml 5.21.2, a pair nested in an uncert parameter cannot be the target of a port at all (Model.getElementBySId does not answer with it and the document fails with 1090105), while one nested in a <comp:sBaseRef> is resolvable; this package writes a port for neither.

Create a KeyValuePair.

Parameters:

Name Type Description Default
key str

the key of the pair, which is required

required
value str | None

the value of the pair

required
uri str | None

the URI which defines the meaning of the key

required
sid str | None

optional SId, written as fbc:id

None
name str | None

optional SBML name, written as fbc:name

None
sboTerm str | None

optional SBO term

None
metaId str | None

optional SBML metaid

None
notes str | Notes | None

optional notes, as markdown, XHTML or a Notes object

None
annotations OptionalAnnotationsType

optional RDF annotations

None
port Any

optional comp port, which names the pair by its fbc:id in an SBML L3V2 document and by its metaid below one, see Sbase._port_reference_for; a pair nested in an uncert parameter, an uncert span or a <comp:sBaseRef> gets none, see the class docstring

None

create_pairs staticmethod

create_pairs(pairs, sbase, model, element)

Create the key-value pairs of an element, if the document has fbc v3.

The one place which decides whether a <fbc:keyValuePair> can be written at all, asked by Sbase.create_key_value_pairs and by Reaction.create_sbml for the pairs of a species reference, which is an EquationPart rather than an Sbase.

A key-value pair is fbc version 3. In an fbc version 2 document libsbml creates the element and answers setKey, setValue, setUri, setId and setName with LIBSBML_UNEXPECTED_ATTRIBUTE (measured with libsbml 5.21.2), which wrote an <fbc:listOfKeyValuePairs> of empty <fbc:keyValuePair/> elements; and a document which declares no fbc at all has no fbc plugin to create one on. Both are reported once for the element, with the number of pairs which are lost, and nothing is written.

The fbc version is read from the plugin of the created libsbml object, which is the version of the document being written, rather than from the packages of the Model, the way Species._set_charge reads it.

Parameters:

Name Type Description Default
pairs list[KeyValuePair] | None

the key-value pairs of the element, possibly none

required
sbase SBase

the libsbml object the pairs are created on

required
model Model | None

the libsbml.Model the element belongs to, which the port of a pair is created in; None for an element written without one

required
element Any

the model element the pairs belong to, named in the report

required

Returns:

Type Description
list[KeyValuePair] | None

the created pairs, None if the element has none or if the

list[KeyValuePair] | None

document cannot carry them

create_sbml

create_sbml(sbase, model=None)

Create the libsbml.KeyValuePair on the given element.

Written through KeyValuePair.create_pairs, which decides whether the document can carry a pair at all; on its own this writes an empty <fbc:keyValuePair/> into an fbc version 2 document and raises on a document which declares no fbc.

Parameters:

Name Type Description Default
sbase SBase

the libsbml object the pair is created on

required
model Model | None

the libsbml.Model the element belongs to, which the port of the pair is created in. It has to be handed down rather than looked up, and None writes the pair without a model, which reports a port of it; both are stated in Model._fill_sbml

None

Returns:

Type Description
KeyValuePair

the created libsbml.KeyValuePair

Value

Value(
    sid,
    value,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
    replacedBy=None,
)

Bases: Sbase

Helper class.

The value field is a helper storage field which is used differently by different subclasses.

Unit

Unit(kind, exponent=1.0, scale=0, multiplier=1.0)

A single unit of a UnitDefinition.

Corresponds to the information in a libsbml.Unit, i.e. one factor of a unit definition. An SBML unit is multiplier * 10^scale * kind^exponent.

Construct a Unit.

Parameters:

Name Type Description Default
kind str

the SBML unit kind, e.g. "litre"

required
exponent float

the exponent of the unit

1.0
scale int

the decimal scale of the unit

0
multiplier float

the multiplier of the unit

1.0

create_sbml

create_sbml(udef)

Create the libsbml.Unit in the given libsbml.UnitDefinition.

Parameters:

Name Type Description Default
udef UnitDefinition

the libsbml.UnitDefinition the unit is created in

required

Returns:

Type Description
Unit

the created libsbml.Unit

UnitDefinition

UnitDefinition(
    sid,
    definition=None,
    units=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    replacedBy=None,
)

Bases: Sbase

Unit.

Corresponds to the information in the libsbml.UnitDefinition.

Construct UnitDefinition.

A unit definition is either written as a pint expression in definition, which is the authoring style, or as the explicit list of units it consists of, which is what the parser reads from a file.

Parameters:

Name Type Description Default
sid str

the id of the unit definition

required
definition str | None

the pint expression, e.g. "mmole/liter"; defaults to sid

None
units list[Unit] | None

the explicit units of the definition; they take precedence over definition

None
name str | None

the name of the unit definition

None
sboTerm str | None

the SBO term of the unit definition

None
metaId str | None

the meta id of the unit definition

None
annotations OptionalAnnotationsType

the annotations of the unit definition

None
notes str | Notes | None

the notes of the unit definition

None
keyValuePairs list[KeyValuePair] | None

the key value pairs of the unit definition

None
port Any

the port of the unit definition

None
replacedBy Any | None

the comp ReplacedBy of the unit definition

None

create_sbml

create_sbml(model)

Create libsbml.UnitDefinition.

Parameters:

Name Type Description Default
model Model

the libsbml.Model the unit definition is created in

required

Returns:

Type Description
UnitDefinition | None

the created libsbml.UnitDefinition, None for a base unit kind

get_uid_for_unit staticmethod

get_uid_for_unit(unit)

Get unit id for the given unit.

Parameters:

Name Type Description Default
unit UnitDefinition | str | None

a UnitDefinition or the id of one

required

Returns:

Type Description
str | None

the unit id, None if no unit was given

Raises:

Type Description
ValueError

if the unit is neither a UnitDefinition nor a unit id; the value would otherwise reach a libsbml setter and surface as a SWIG TypeError which names neither the value nor the element it was set on

Units

Base class for unit definitions.

attributes classmethod

attributes()

Get the attributes list.

create_unit_definitions classmethod

create_unit_definitions(model)

Create the libsbml.UnitDefinitions in the model.

Deprecated, Model normalizes its units to a list of UnitDefinition and creates them directly.

Parameters:

Name Type Description Default
model Model

the libsbml.Model the unit definitions are created in

required

ValueWithUnit

ValueWithUnit(
    sid,
    value,
    unit=dimensionless,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
    replacedBy=None,
)

Bases: Value

Helper class.

The value field is a helper storage field which is used differently by different subclasses.

Function

Function(
    sid,
    value,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
    replacedBy=None,
)

Bases: Sbase

SBML FunctionDefinitions.

FunctionDefinitions consist of a lambda expression in the value field, e.g., lambda(x,y, piecewise(x,gt(x,y),y) ) # definition of minimum function lambda(x, sin(x) )

A value of None is a function definition without math, which SBML allows from L3V2 on.

Construct Function.

create_sbml

create_sbml(model)

Create FunctionDefinition SBML in model.

Parameter

Parameter(
    sid,
    value=None,
    unit=None,
    constant=True,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
    replacedBy=None,
)

Bases: ValueWithUnit

Parameter.

Construct Parameter.

create_sbml

create_sbml(model)

Create Parameter SBML in model.

LocalParameter

LocalParameter(
    sid,
    value=None,
    unit=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
)

Bases: ValueWithUnit

LocalParameter of a KineticLaw.

A local parameter is scoped to the kinetic law it is defined in, unlike a Parameter, which is global to the model. Its id is scoped with it: libsbml.Model.getElementBySId, which comp resolves a comp:idRef with, does not answer with a local parameter, so a <comp:port> names one by its metaid, see Sbase._port_reference.

A <comp:replacedBy> is not offered. libsbml writes one on a <localParameter> and reads it back, but no such replacement is valid, whichever way it names the element it is replaced by (measured with libsbml 5.21.2): naming the local parameter of the submodel, by comp:metaIdRef or through a <comp:port> of the submodel, makes the flattened model invalid (libsbml 10216, "Cannot use a KineticLaw local parameter outside of its local scope"), comp:idRef cannot name a local parameter at all (1020702), and naming anything else is a class mismatch (1021201, 1021203).

Construct LocalParameter.

Parameters:

Name Type Description Default
sid str

the SId of the local parameter, which is required

required
value str | float | None

the value of the local parameter

None
unit UnitType

the unit of the value

None
name str | None

optional SBML name

None
sboTerm str | None

optional SBO term

None
metaId str | None

optional SBML metaid, which a <comp:port> of the local parameter references it by

None
annotations OptionalAnnotationsType

optional RDF annotations

None
notes str | Notes | None

optional notes, as markdown, XHTML or a Notes object

None
keyValuePairs list[KeyValuePair] | None

optional key-value pairs

None
port Any

optional comp port, which names the local parameter by its metaid

None
uncertainties list[Uncertainty] | None

optional distrib uncertainties

None

create_sbml

create_sbml(klaw, model=None)

Create the libsbml.LocalParameter in the given kinetic law.

Parameters:

Name Type Description Default
klaw KineticLaw

the libsbml.KineticLaw the local parameter is created in

required
model Model | None

the libsbml.Model the kinetic law is created in, which the port and the uncertainties of the local parameter are created in. It has to be handed down rather than looked up, and None falls back to klaw.getModel(), which is the same model outside a <comp:modelDefinition> and the wrong one inside one; both are stated in Model._fill_sbml

None

Returns:

Type Description
LocalParameter

the created libsbml.LocalParameter

Compartment

Compartment(
    sid,
    value,
    unit=None,
    constant=True,
    spatialDimensions=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
    replacedBy=None,
)

Bases: ValueWithUnit

Compartment.

Construct Compartment.

create_sbml

create_sbml(model)

Create Compartment SBML in model.

Species

Species(
    sid,
    compartment,
    initialAmount=None,
    initialConcentration=None,
    substanceUnit=None,
    hasOnlySubstanceUnits=False,
    constant=False,
    boundaryCondition=False,
    charge=None,
    chemicalFormula=None,
    conversionFactor=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
    replacedBy=None,
)

Bases: Sbase

Species.

Construct Species.

create_sbml

create_sbml(model)

Create Species SBML in model.

InitialAssignment

InitialAssignment(
    symbol,
    value,
    unit=dimensionless,
    sid=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
    replacedBy=None,
)

Bases: Value

InitialAssignments.

The unit attribute is only for the case where a parameter must be created (which has the unit). In case of an initialAssignment of a value the units have to be defined in the math. A value of None is an initial assignment without math, which SBML allows from L3V2 on.

A <comp:port> names an initial assignment by its metaid, see Sbase._port_reference.

Construct InitialAssignment.

create_sbml

create_sbml(model)

Create InitialAssignment.

Creates a required parameter if the symbol for the initial assignment does not exist in the model.

RuleWithVariable

Rule.

check_model_for_rule

check_model_for_rule(model)

Check model for rule requirements.

Creates a required parameter if the symbol for the initial assignment does not exist in the model.

AssignmentRule

AssignmentRule(
    variable,
    value,
    unit=dimensionless,
    sid=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
    replacedBy=None,
)

Bases: ValueWithUnit, RuleWithVariable

AssignmentRule.

The unit attribute is only for the case where a parameter must be created (which has the unit). In case of an initialAssignment of a value the units have to be defined in the math. A value of None is a rule without math, which SBML allows from L3V2 on.

A <comp:port> names a rule by its metaid, see Sbase._port_reference.

Construct AssignmentRule.

create_sbml

create_sbml(model)

Create AssignmentRule.

RateRule

RateRule(
    variable,
    value,
    unit=dimensionless,
    sid=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
    replacedBy=None,
)

Bases: ValueWithUnit, RuleWithVariable

RateRule.

A value of None is a rule without math, which SBML allows from L3V2 on.

A <comp:port> names a rule by its metaid, see Sbase._port_reference.

Construct RateRule.

create_sbml

create_sbml(model)

Create RateRule.

AlgebraicRule

AlgebraicRule(
    sid,
    value,
    unit=dimensionless,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
    replacedBy=None,
)

Bases: ValueWithUnit, RuleWithVariable

AlgebraicRule.

A value of None is a rule without math, which SBML allows from L3V2 on.

A <comp:port> names a rule by its metaid, see Sbase._port_reference.

Construct AlgebraicRule.

create_sbml

create_sbml(model)

Create AlgebraicRule.

KineticLaw

KineticLaw(
    math,
    unit=None,
    local_parameters=None,
    sid=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
    replacedBy=None,
)

Bases: Sbase

KineticLaw of a Reaction.

Corresponds to the information in a libsbml.KineticLaw: the rate math, and the local parameters which are scoped to it.

Construct a KineticLaw.

Parameters:

Name Type Description Default
math str | None

the rate expression, as an SBML L3 formula string; None for a kinetic law without math, which SBML allows from L3V2 on

required
unit UnitType

the unit of the rate; never written to XML in any level/version this package currently emits (it existed on libsbml.KineticLaw only in L1V1, L1V2 and L2V1, and this package never wrote it even then). Kept as python state for a KineticLaw parsed from such an old document, since a future write-back needs somewhere to hold it

None
local_parameters list[LocalParameter] | None

the parameters scoped to this kinetic law

None
sid str | None

optional SId, kinetic laws only carry one since SBML L3V2; not written when the target document is older, see Sbase._set_fields

None
name str | None

optional SBML name

None
sboTerm str | None

optional SBO term

None
metaId str | None

optional SBML metaid

None
annotations OptionalAnnotationsType

optional RDF annotations

None
notes str | Notes | None

optional notes, as markdown, XHTML or a Notes object

None
keyValuePairs list[KeyValuePair] | None

optional key-value pairs

None
port Any

optional comp port

None
uncertainties list[Uncertainty] | None

optional distrib uncertainties

None
replacedBy Any | None

optional comp replacement

None

create_sbml

create_sbml(reaction, model=None)

Create the libsbml.KineticLaw on the given reaction.

Parameters:

Name Type Description Default
reaction Reaction

the libsbml.Reaction the kinetic law belongs to

required
model Model | None

the libsbml.Model the reaction is created in, which the math is parsed against and which the port, the uncertainties and the replacedBy of the kinetic law and of its local parameters are created in. It has to be handed down rather than looked up, and None falls back to reaction.getModel(), which is the same model outside a <comp:modelDefinition> and the wrong one inside one; both are stated in Model._fill_sbml

None

Returns:

Type Description
KineticLaw

the created libsbml.KineticLaw

Reaction

Reaction(
    sid,
    equation,
    formula=None,
    pars=None,
    rules=None,
    compartment=None,
    fast=False,
    reversible=None,
    lowerFluxBound=None,
    upperFluxBound=None,
    geneProductAssociation=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
    replacedBy=None,
)

Bases: Sbase

Reaction.

Class for creating libsbml.Reaction.

Equations are of the form '1.0 S1 + 2 S2 => 2.0 P1 + 2 P2 [M1, M2]'

The equation consists of - substrates concatenated via '+' on the left side (with optional stoichiometric coefficients) - separation characters separating the left and right equation sides: '<=>' or '<->' for reversible reactions, '=>' or '->' for irreversible reactions (irreversible reactions are written from left to right) - products concatenated via '+' on the right side (with optional stoichiometric coefficients) - optional list of modifiers within brackets [] separated by ','

Examples of valid equations are

'1.0 S1 + 2 S2 => 2.0 P1 + 2 P2 [M1, M2]', 'c__gal1p => c__gal + c__phos', 'e__h2oM <-> c__h2oM', '3 atp + 2.0 phos + ki <-> 16.98 tet', 'c__gal1p => c__gal + c__phos [c__udp, c__utp]', 'A_ext => A []', '=> cit', 'acoa =>',

Construct Reaction.

create_sbml

create_sbml(model)

Create Reaction SBML in model.

EventAssignment

EventAssignment(
    variable,
    value,
    sid=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
    replacedBy=None,
)

Bases: Value

EventAssignment of an Event.

Assigns the value of the expression to the variable when the event fires.

Construct an EventAssignment.

Parameters:

Name Type Description Default
variable str

the id of the element the assignment applies to

required
value str | float | None

the assigned expression, as an SBML L3 formula string; None for an event assignment without math, which SBML allows from L3V2 on

required
sid str | None

optional SId; libsbml.EventAssignment only gained a real, separate id attribute in SBML L3V2, and only from L3V2 onward is it distinct from variable (see _set_fields docstring for the L3V1 behaviour)

None
name str | None

optional SBML name

None
sboTerm str | None

optional SBO term

None
metaId str | None

optional SBML metaid

None
annotations OptionalAnnotationsType

optional RDF annotations

None
notes str | Notes | None

optional notes, as markdown, XHTML or a Notes object

None
keyValuePairs list[KeyValuePair] | None

optional key-value pairs

None
port Any

optional comp port

None
uncertainties list[Uncertainty] | None

optional distrib uncertainties

None
replacedBy Any | None

optional comp replacement

None

create_sbml

create_sbml(event, model)

Create the libsbml.EventAssignment on the given event.

Parameters:

Name Type Description Default
event Event

the libsbml.Event the assignment belongs to

required
model Model

the libsbml.Model, used to resolve ids in the expression

required

Returns:

Type Description
EventAssignment

the created libsbml.EventAssignment

Trigger

Trigger(
    math,
    initialValue=False,
    persistent=True,
    sid=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
    replacedBy=None,
)

Bases: Sbase

Trigger of an Event.

Corresponds to a libsbml.Trigger: the condition whose change from false to true fires the event, and the two flags which qualify it.

Construct a Trigger.

Parameters:

Name Type Description Default
math str | None

the condition, as an SBML L3 formula string, e.g. "time >= 10"; None for a trigger without math, which SBML allows from L3V2 on

required
initialValue bool

the value of the trigger before the simulation starts; with False a condition which is true at the start fires the event at the start

False
persistent bool

whether a fired event is executed even if the condition turns false again before its delay has passed

True
sid str | None

optional SId, a trigger only carries one since SBML L3V2; not written when the target document is older, see Sbase._set_fields

None
name str | None

optional SBML name, a trigger only carries one since SBML L3V2; not written when the target document is older

None
sboTerm str | None

optional SBO term

None
metaId str | None

optional SBML metaid

None
annotations OptionalAnnotationsType

optional RDF annotations

None
notes str | Notes | None

optional notes, as markdown, XHTML or a Notes object

None
keyValuePairs list[KeyValuePair] | None

optional key-value pairs

None
port Any

optional comp port

None
uncertainties list[Uncertainty] | None

optional distrib uncertainties

None
replacedBy Any | None

optional comp replacement

None

create_sbml

create_sbml(event, model)

Create the libsbml.Trigger on the given event.

Parameters:

Name Type Description Default
event Event

the libsbml.Event the trigger belongs to

required
model Model

the libsbml.Model, used to resolve ids in the math

required

Returns:

Type Description
Trigger

the created libsbml.Trigger

Priority

Priority(
    math,
    sid=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
)

Bases: Sbase

Priority of an Event.

Corresponds to a libsbml.Priority: the math which orders the events that are executed at the same time, the event with the higher priority first.

libsbml attaches no CompSBasePlugin to a <priority>, alone among the four children of an event, so a replacedBy is not offered, see Sbase.create_replaced_by.

Construct a Priority.

Parameters:

Name Type Description Default
math str | None

the priority, as an SBML L3 formula string; None for a priority without math, which SBML allows from L3V2 on

required
sid str | None

optional SId, a priority only carries one since SBML L3V2; not written when the target document is older, see Sbase._set_fields

None
name str | None

optional SBML name, a priority only carries one since SBML L3V2; not written when the target document is older

None
sboTerm str | None

optional SBO term

None
metaId str | None

optional SBML metaid

None
annotations OptionalAnnotationsType

optional RDF annotations

None
notes str | Notes | None

optional notes, as markdown, XHTML or a Notes object

None
keyValuePairs list[KeyValuePair] | None

optional key-value pairs

None
port Any

optional comp port

None
uncertainties list[Uncertainty] | None

optional distrib uncertainties

None

create_sbml

create_sbml(event, model)

Create the libsbml.Priority on the given event.

Parameters:

Name Type Description Default
event Event

the libsbml.Event the priority belongs to

required
model Model

the libsbml.Model, used to resolve ids in the math

required

Returns:

Type Description
Priority | None

the created libsbml.Priority, None below SBML L3, which has no

Priority | None

priority; that is logged as an error

Delay

Delay(
    math,
    sid=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
    replacedBy=None,
)

Bases: Sbase

Delay of an Event.

Corresponds to a libsbml.Delay: the math of the time between the firing of the event and the execution of its assignments.

Construct a Delay.

Parameters:

Name Type Description Default
math str | None

the delay, as an SBML L3 formula string; None for a delay without math, which SBML allows from L3V2 on

required
sid str | None

optional SId, a delay only carries one since SBML L3V2; not written when the target document is older, see Sbase._set_fields

None
name str | None

optional SBML name, a delay only carries one since SBML L3V2; not written when the target document is older

None
sboTerm str | None

optional SBO term

None
metaId str | None

optional SBML metaid

None
annotations OptionalAnnotationsType

optional RDF annotations

None
notes str | Notes | None

optional notes, as markdown, XHTML or a Notes object

None
keyValuePairs list[KeyValuePair] | None

optional key-value pairs

None
port Any

optional comp port

None
uncertainties list[Uncertainty] | None

optional distrib uncertainties

None
replacedBy Any | None

optional comp replacement

None

create_sbml

create_sbml(event, model)

Create the libsbml.Delay on the given event.

Parameters:

Name Type Description Default
event Event

the libsbml.Event the delay belongs to

required
model Model

the libsbml.Model, used to resolve ids in the math

required

Returns:

Type Description
Delay

the created libsbml.Delay

Event

Event(
    sid,
    trigger,
    assignments=None,
    trigger_persistent=None,
    trigger_initialValue=None,
    useValuesFromTriggerTime=True,
    priority=None,
    delay=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
    replacedBy=None,
)

Bases: Sbase

Event.

An event fires when its trigger, e.g. time >= 10, changes from false to true, and then executes its assignments, e.g. {"S1": 5.0}, after its optional delay. The priority orders events which are executed at the same time.

The trigger, the priority and the delay are a Trigger, a Priority and a Delay, which carry their own metadata. Each of them is also accepted as a formula string or a number, which is normalized into the object; this is the documented authoring style, e.g. Event("e1", trigger="time >= 10", priority="1", delay="2"). None writes no element at all: an event without a priority or a delay, or, from SBML L3V2 on, without a trigger. An element without math, which SBML allows from L3V2 on, is an object whose math is None, e.g. Trigger(None).

trigger, priority and delay normalize what is assigned to them after construction in the same way. trigger_persistent and trigger_initialValue read and set the flags of the trigger.

Construct an Event.

Parameters:

Name Type Description Default
sid str | None

optional SId

required
trigger Trigger | str | float | None

the trigger, a Trigger, or its math as a formula string or a number; None for an event without a trigger, which SBML allows from L3V2 on

required
assignments dict[str, str | float] | list[EventAssignment] | None

the event assignments, a list of EventAssignment or a {variable: expression} dict

None
trigger_persistent bool | None

the persistent of the Trigger created from math, True if not given. A Trigger keeps its own persistent, a different value given here is logged as a warning and not applied, as is one given without a trigger

None
trigger_initialValue bool | None

the initialValue of the Trigger created from math, False if not given. A Trigger keeps its own initialValue, a different value given here is logged as a warning and not applied, as is one given without a trigger

None
useValuesFromTriggerTime bool

whether the assignments are evaluated when the event fires rather than when it is executed

True
priority Priority | str | float | None

the priority, a Priority, or its math as a formula string or a number; None for an event without a priority

None
delay Delay | str | float | None

the delay, a Delay, or its math as a formula string or a number; None for an event without a delay

None
name str | None

optional SBML name

None
sboTerm str | None

optional SBO term

None
metaId str | None

optional SBML metaid

None
annotations OptionalAnnotationsType

optional RDF annotations

None
notes str | Notes | None

optional notes, as markdown, XHTML or a Notes object

None
keyValuePairs list[KeyValuePair] | None

optional key-value pairs

None
port Any

optional comp port

None
uncertainties list[Uncertainty] | None

optional distrib uncertainties

None
replacedBy Any | None

optional comp replacement

None

Raises:

Type Description
TypeError

if the trigger, the priority or the delay is neither the object, nor a formula string, nor a number

trigger property writable

trigger

Get the trigger, None for an event without a trigger.

trigger_persistent property writable

trigger_persistent

Get the persistent of the trigger, None without a trigger.

trigger_initialValue property writable

trigger_initialValue

Get the initialValue of the trigger, None without a trigger.

priority property writable

priority

Get the priority, None for an event without a priority.

delay property writable

delay

Get the delay, None for an event without a delay.

create_sbml

create_sbml(model)

Create Event SBML in model.

Constraint

Constraint(
    sid,
    math=None,
    message=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
    replacedBy=None,
)

Bases: Sbase

Constraint.

The Constraint object is a mechanism for stating the assumptions under which a model is designed to operate. The constraints are statements about permissible values of different quantities in a model.

The message must be well formated XHTML, e.g., message='ATP must be non-negative'

Constraint constructor.

create_sbml

create_sbml(model)

Create Constraint SBML in model.

UncertParameter

UncertParameter(
    type,
    value=None,
    var=None,
    unit=None,
    definitionURL=None,
    math=None,
    uncertParameters=None,
    sid=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
)

Bases: _UncertChild

A single value of an Uncertainty, e.g. a mean or a standard deviation.

The value is either a number (value), a reference to a parameter of the model (var), or, for an uncert parameter of the type distribution, the distribution the value is drawn from, as math or as a definitionURL with the uncertParameters of the distribution. The type states which of them it is, e.g. libsbml.DISTRIB_UNCERTTYPE_MEAN.

The fields it shares with an UncertSpan, and the fields neither of them offers, are documented in _UncertChild.

Construct UncertParameter.

Parameters:

Name Type Description Default
type int | None

the kind of the value, a libsbml.DISTRIB_UNCERTTYPE_*, None for an element without one, see _UncertChild

required
value float | None

the numerical value

None
var str | None

the id of the element which holds the value, an alternative to value

None
unit UnitType

the unit of the value

None
definitionURL str | None

see _UncertChild

None
math str | None

see _UncertChild

None
uncertParameters list[UncertParameter | UncertSpan] | None

see _UncertChild

None
sid str | None

the id of the uncert parameter, which is optional in SBML

None
name str | None

the name of the uncert parameter

None
sboTerm str | None

the SBO term of the uncert parameter

None
metaId str | None

the meta id of the uncert parameter, which its annotations are referenced by

None
annotations OptionalAnnotationsType

the annotations of the uncert parameter

None
notes str | Notes | None

the notes of the uncert parameter

None
keyValuePairs list[KeyValuePair] | None

the fbc key value pairs of the uncert parameter

None

create_sbml

create_sbml(parent, model=None)

Create the libsbml.UncertParameter in the given parent.

Parameters:

Name Type Description Default
parent Uncertainty | UncertParameter

the libsbml.Uncertainty or libsbml.UncertParameter the parameter is created in

required
model Model | None

the libsbml.Model the uncertainty is created in, which the math is parsed against, see _UncertChild._set_fields

None

Returns:

Type Description
UncertParameter | None

the created libsbml.UncertParameter, None for a parameter whose

UncertParameter | None

type SBML does not allow on one, see _supports_type

UncertSpan

UncertSpan(
    type,
    valueLower=None,
    varLower=None,
    valueUpper=None,
    varUpper=None,
    unit=None,
    definitionURL=None,
    math=None,
    uncertParameters=None,
    sid=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
)

Bases: _UncertChild

An interval of an Uncertainty, e.g. a range or a confidence interval.

Both bounds are either a number (valueLower, valueUpper) or a reference to a parameter of the model (varLower, varUpper), and the type states what the interval is, e.g. libsbml.DISTRIB_UNCERTTYPE_RANGE.

An uncert span carries the same fields as an UncertParameter, which it is a subclass of in libsbml: it is written with createUncertSpan and read back from the listOfUncertParameters. The shared fields, and the fields neither class offers, are documented in _UncertChild.

Construct UncertSpan.

Parameters:

Name Type Description Default
type int | None

the kind of the interval, a libsbml.DISTRIB_UNCERTTYPE_*, None for an element without one, see _UncertChild

required
valueLower float | None

the numerical value of the lower bound

None
varLower str | None

the id of the element which holds the lower bound, an alternative to valueLower

None
valueUpper float | None

the numerical value of the upper bound

None
varUpper str | None

the id of the element which holds the upper bound, an alternative to valueUpper

None
unit UnitType

the unit of the bounds

None
definitionURL str | None

see _UncertChild

None
math str | None

see _UncertChild

None
uncertParameters list[UncertParameter | UncertSpan] | None

see _UncertChild

None
sid str | None

the id of the uncert span, which is optional in SBML

None
name str | None

the name of the uncert span

None
sboTerm str | None

the SBO term of the uncert span

None
metaId str | None

the meta id of the uncert span, which its annotations are referenced by

None
annotations OptionalAnnotationsType

the annotations of the uncert span

None
notes str | Notes | None

the notes of the uncert span

None
keyValuePairs list[KeyValuePair] | None

the fbc key value pairs of the uncert span

None

create_sbml

create_sbml(parent, model=None)

Create the libsbml.UncertSpan in the given parent.

Parameters:

Name Type Description Default
parent Uncertainty | UncertParameter

the libsbml.Uncertainty or libsbml.UncertParameter the span is created in

required
model Model | None

the libsbml.Model the uncertainty is created in, which the math is parsed against, see _UncertChild._set_fields

None

Returns:

Type Description
UncertSpan | None

the created libsbml.UncertSpan, None for a span whose type SBML

UncertSpan | None

does not allow on one, see _supports_type

Uncertainty

Uncertainty(
    sid=None,
    formula=None,
    uncertParameters=None,
    uncertSpans=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
)

Bases: Sbase

The uncertainty of the value of an element, a distrib:uncertainty.

An uncertainty states what is known about a value beyond the value itself: a mean with a standard deviation, a range, a confidence interval, or the distribution the value is drawn from. Every Sbase can carry a list of them.

SBML holds the values of an uncertainty in one list, the distrib:listOfUncertParameters, whose elements are distrib:uncertParameter and distrib:uncertSpan, and uncertParameters is that list: it takes UncertParameter and UncertSpan objects and is written in its own order, which is how the order of a parsed document is preserved.

uncertSpans is the authoring style of two lists, one per kind, and is kept. It has no place for an order between the two, so its spans are put in front of uncertParameters, which is the order such an uncertainty has always been written in.

formula is the shortcut for a distribution: it is normalized into one UncertParameter of the type distribution when the uncertainty is constructed, see _distribution_parameter, and appended after the children given explicitly. An uncertainty is written from uncertParameters and from nothing else, so a parsed uncertainty, which carries the distribution as an ordinary child, is written exactly once.

libsbml attaches no CompSBasePlugin to a <distrib:uncertainty>, so a replacedBy is not offered, see Sbase.create_replaced_by.

Construct Uncertainty.

Parameters:

Name Type Description Default
sid str | None

the id of the uncertainty, which is optional in SBML

None
formula str | None

the distribution of the value as an SBML L3 formula, e.g. normal(2.0, 2.0); the shortcut for the uncert parameter of the type distribution it is normalized into

None
uncertParameters list[UncertParameter | UncertSpan] | None

the uncert parameters and spans of the uncertainty, in the order they are written in

None
uncertSpans list[UncertSpan] | None

the spans of the uncertainty, which are written before uncertParameters

None
name str | None

the name of the uncertainty

None
sboTerm str | None

the SBO term of the uncertainty

None
metaId str | None

the meta id of the uncertainty, which its annotations are referenced by

None
annotations OptionalAnnotationsType

the annotations of the uncertainty

None
notes str | Notes | None

the notes of the uncertainty

None
keyValuePairs list[KeyValuePair] | None

the fbc key value pairs of the uncertainty

None
port Any

the comp port of the uncertainty

None

formula property writable

formula

Get the distribution of the value as an SBML L3 formula.

Returns:

Type Description
str | None

the formula, None for an uncertainty which states none

create_sbml

create_sbml(sbase, model)

Create the libsbml.Uncertainty on the given element.

Parameters:

Name Type Description Default
sbase SBase

the libsbml object the uncertainty is created on

required
model Model

the libsbml.Model the element belongs to

required

Returns:

Type Description
Uncertainty

the created libsbml.Uncertainty

ExchangeReaction

ExchangeReaction(
    species_id,
    compartment=None,
    fast=False,
    reversible=True,
    lowerFluxBound=None,
    upperFluxBound=None,
    geneProductAssociation=None,
    name=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
    replacedBy=None,
)

Bases: Reaction

Exchange reactions define substances which can be exchanged.

This is important for FBC models.

EXCHANGE_IMPORT (-INF, 0): is defined as negative flux through the exchange reaction, i.e. the upper bound must be 0, the lower bound some negative value, e.g. -INF

EXCHANGE_EXPORT (0, INF): is defined as positive flux through the exchange reaction, i.e. the lower bound must be 0, the upper bound some positive value, e.g. INF

Construct ExchangeReaction.

GeneProduct

GeneProduct(
    sid,
    label,
    associatedSpecies=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
)

Bases: Sbase

GeneProduct.

GeneProduct is a new FBC class derived from SBML SBase that inherits metaid and sboTerm, as well as the subcomponents for Annotation and Notes. The purpose of this class is to define a single gene product. It implements two required attributes id and label as well as two optional attributes name and associatedSpecies.

libsbml attaches no CompSBasePlugin to an <fbc:geneProduct>, so a replacedBy is not offered, see Sbase.create_replaced_by.

Create a GeneProduct.

create_sbml

create_sbml(model)

Create the libsbml.GeneProduct in the model.

Parameters:

Name Type Description Default
model Model

the libsbml.Model the gene product is created in

required

Returns:

Type Description
GeneProduct

the created libsbml.GeneProduct

Raises:

Type Description
ValueError

if the model has no fbc plugin, see _fbc_plugin

UserDefinedConstraintComponent

UserDefinedConstraintComponent(
    coefficient,
    variable,
    variableType=None,
    sid=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
)

Bases: Sbase

UserDefinedConstraintComponent.

libsbml attaches no CompSBasePlugin to an <fbc:userDefinedConstraintComponent>, so a replacedBy is not offered, see Sbase.create_replaced_by.

Create a UserDefinedConstraintComponent.

create_sbml

create_sbml(constraint, model=None)

Create the libsbml.UserDefinedConstraintComponent in the constraint.

Parameters:

Name Type Description Default
constraint UserDefinedConstraint

the libsbml.UserDefinedConstraint the component belongs to

required
model Model | None

the libsbml.Model the constraint is created in, which the fields of the component are written with. It has to be handed down rather than looked up, and None falls back to constraint.getModel(), which is the same model outside a <comp:modelDefinition> and the wrong one inside one; both are stated in Model._fill_sbml

None

Returns:

Type Description
UserDefinedConstraintComponent

the created libsbml.UserDefinedConstraintComponent

UserDefinedConstraint

UserDefinedConstraint(
    lowerBound,
    upperBound,
    components=None,
    variableType=FBC_VARIABLE_TYPE_LINEAR,
    sid=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
)

Bases: Sbase

UserDefinedConstraint.

The FBC UserDefinedConstraint class is derived from SBML SBase and inherits metaid and sboTerm, as well as the subcomponents for Annotation and Notes. It’s purpose is to define non-stoichiometric constraints, that is constraints that are not necessarily defined by the stoichiometrically coupled reaction network. In order to achieve, we defined a new type of linear constraint, the UserDefinedConstraint

libsbml attaches no CompSBasePlugin to an <fbc:userDefinedConstraint>, so a replacedBy is not offered, see Sbase.create_replaced_by.

Create an UserDefinedConstraint.

create_sbml

create_sbml(model)

Create the libsbml.UserDefinedConstraint in the model.

An <fbc:userDefinedConstraint> is fbc version 3. In an fbc version 2 document libsbml creates the element and answers every one of setUpperBound, setLowerBound, setVariable, setCoefficient and setVariableType with LIBSBML_UNEXPECTED_ATTRIBUTE, so all that would be written is an empty <fbc:userDefinedConstraint/>, which is invalid. Such a document is reported once for the constraint and gets no element, the way a key-value pair is refused, see _fbc_version_allows.

Parameters:

Name Type Description Default
model Model

the libsbml.Model the constraint is created in

required

Returns:

Type Description
UserDefinedConstraint | None

the created constraint, None if the fbc version of the document

UserDefinedConstraint | None

cannot carry one

FluxObjective

FluxObjective(
    reaction,
    coefficient,
    variableType=None,
    sid=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
)

Bases: Sbase

FluxObjective.

libsbml attaches no CompSBasePlugin to an <fbc:fluxObjective>, so a replacedBy is not offered, see Sbase.create_replaced_by.

Create a FluxObjective.

normalize_variable_type classmethod

normalize_variable_type(variable_type)

Normalize variable type.

create_sbml

create_sbml(objective, model=None)

Create the libsbml.FluxObjective in the objective.

Parameters:

Name Type Description Default
objective Objective

the libsbml.Objective the flux objective belongs to

required
model Model | None

the libsbml.Model the objective is created in, which the fields of the flux objective are written with. It has to be handed down rather than looked up, and None falls back to objective.getModel(), which is the same model outside a <comp:modelDefinition> and the wrong one inside one; both are stated in Model._fill_sbml

None

Returns:

Type Description
FluxObjective

the created libsbml.FluxObjective

Objective

Objective(
    sid,
    objectiveType=OBJECTIVE_TYPE_MAXIMIZE,
    active=True,
    fluxObjectives=None,
    variableType=FBC_VARIABLE_TYPE_LINEAR,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    port=None,
    uncertainties=None,
)

Bases: Sbase

Objective.

libsbml attaches no CompSBasePlugin to an <fbc:objective>, so a replacedBy is not offered, see Sbase.create_replaced_by.

Create an Objective.

FluxObjectives can either be provided as a list of FluxObjectives or as a dictionary with the reaction ids as keys and the coefficients as values.

normalize_objective_type classmethod

normalize_objective_type(objective_type)

Normalize objective type.

create_sbml

create_sbml(model)

Create Objective.

An objective whose active is set becomes the activeObjective of the model. The objectives of a model are written in the order they are defined in, so of several active ones the last one written wins, and a model whose objectives are all inactive gets no active objective at all.

Parameters:

Name Type Description Default
model Model

the libsbml.Model the objective is created in

required

Returns:

Type Description
Objective

the created libsbml.Objective

Raises:

Type Description
ValueError

if the model has no fbc plugin, see _fbc_plugin

ExternalModelDefinition

ExternalModelDefinition(
    sid,
    source,
    modelRef,
    md5=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
)

Bases: Sbase

ExternalModelDefinition.

comp:modelRef is optional: a definition without one refers to the main model of its source document, which is what resources/models/sbml-test-suite-3.4.0/semantic/01168 does, and such a document validates. The empty string sbmlutils.parser hands over for a definition which states none is therefore not written rather than reported.

Create an ExternalModelDefinition.

create_sbml

create_sbml(model)

Create ExternalModelDefinition.

Submodel

Submodel(
    sid,
    modelRef=None,
    timeConversionFactor=None,
    extentConversionFactor=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
)

Bases: Sbase

Submodel.

Create a Submodel.

create_sbml

create_sbml(model)

Create SBML Submodel.

SbaseRef

SbaseRef(
    sid=None,
    portRef=None,
    idRef=None,
    unitRef=None,
    metaIdRef=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    sBaseRef=None,
)

Bases: Sbase

SBaseRef.

The base of Port, ReplacedElement, ReplacedBy and Deletion: each references an element by one of portRef, idRef, unitRef, metaIdRef. The SBML spec allows a <comp:sBaseRef> to hold a nested <comp:sBaseRef> child of its own, which continues the reference into a submodel of the referenced submodel, to arbitrary depth; sBaseRef holds that nested reference, an SbaseRef in its own right so the chain can continue.

A ReplacedElement, a ReplacedBy and a nested <comp:sBaseRef> carry no sid and no name into any document, which is why both are optional on them. The two are the generic id and name SBML core gave every SBase in L3V2, and libsbml's comp writer serializes neither: measured with libsbml 5.21.2, setIdAttribute and setName answer LIBSBML_UNEXPECTED_ATTRIBUTE below L3V2 and success at L3V2, and the document written carries neither attribute at either version. Writing L3V2 is therefore no remedy, and an sid or a name given on one of the three is reported once per document and per kind of element, without advice, see _UNWRITTEN_ID_TYPECODES. metaId, sboTerm, notes and annotations are unaffected (they predate L3V2 and are written normally), and so are the sid and name of a Port and of a Deletion, since comp gives both elements an id and a name of their own, written as the package attributes comp:id and comp:name.

A Port, a ReplacedElement or a ReplacedBy is a convenient, already available SbaseRef which a caller may reuse for a nested level, and whichever class builds it, a nested level is written as a plain <comp:sBaseRef>, see _set_fields. So a Port reused as one drops its portType, its sid and its name, and a ReplacedElement or a ReplacedBy reused as one drops its submodelRef, and a ReplacedElement also its deletion and its conversionFactor: none of those attributes exists on a <comp:sBaseRef>. sbmlutils.parser builds every nested level as a plain SbaseRef.

Create an SBaseRef.

ReplacedElement

ReplacedElement(
    sid=None,
    elementRef="",
    submodelRef="",
    deletion=None,
    conversionFactor=None,
    portRef=None,
    idRef=None,
    unitRef=None,
    metaIdRef=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    sBaseRef=None,
)

Bases: SbaseRef

ReplacedElement.

comp writes a <comp:replacedElement> inside the element it replaces, and Model.replaced_elements holds it next to that element instead, with elementRef naming it. elementRef is therefore a pointer inside sbmlutils, it is not written into the document: create_sbml resolves it against the model the replacement is written in, as the id of an element, of a unit definition, which lives in a namespace of its own and which getElementBySId does not answer with, or, for an element which has no id at all, as its metaid. An SBML rule, an initial assignment, an event assignment and a kinetic law have an id only from SBML L3V2 on, and the SBML test suite replaces a rate rule which carries a metaid and no id.

The resolution order is the id of an element, then the id of a unit definition, then a metaid, and it is not disambiguated: an element id and a unit definition id live in different namespaces, and a metaid in a third, so one string can name three different elements of one model, and the first of the three wins. A caller which names an element by its metaid is responsible for that metaid being the id of nothing else in the same model; sbmlutils.parser uses a metaid only for an element which has no id and reports the replacement as a loss instead of writing it when the metaid is the id of an element or of a unit definition of the same model, see _replaced_element_ref.

Create a ReplacedElement.

Parameters:

Name Type Description Default
sid str | None

the id of the replacement, which libsbml writes into no document, see the class docstring of SbaseRef

None
elementRef str

the element of this model which is replaced, see the class docstring. comp requires it, and it carries an empty default only because the optional sid keeps its position in front of it; a replacement whose elementRef names no element of the model is refused when it is written

''
submodelRef str

the id of the submodel the replacing element lives in, comp:submodelRef. comp requires it, and it carries an empty default for the same reason; the empty string is what the parser hands over for a document which states none, and libsbml leaves the attribute unset for it

''
deletion str | None

the id of the deletion of the submodel this replacement refers to

None
conversionFactor str | None

the id of the parameter the values of the replaced element are converted with

None
portRef str | None

the port of the submodel which names the replacing element

None
idRef str | None

the id of the replacing element in the submodel

None
unitRef str | None

the id of the replacing unit definition in the submodel

None
metaIdRef str | None

the metaid of the replacing element in the submodel

None
name str | None

the name of the replacement, which libsbml writes into no document either

None
sboTerm str | None

the SBO term of the replacement

None
metaId str | None

the meta id of the replacement

None
annotations OptionalAnnotationsType

the annotations of the replacement

None
notes str | Notes | None

the notes of the replacement

None
keyValuePairs list[KeyValuePair] | None

the fbc key value pairs of the replacement

None
sBaseRef SbaseRef | None

the nested <comp:sBaseRef> which continues the reference into a submodel of the submodel

None

create_sbml

create_sbml(model)

Create the libsbml.ReplacedElement inside the element it replaces.

Parameters:

Name Type Description Default
model Model

the libsbml.Model, or libsbml.ModelDefinition, the replacement is written in, which elementRef is resolved against

required

Returns:

Type Description
ReplacedElement

the created libsbml.ReplacedElement

Raises:

Type Description
ValueError

if elementRef names no element of the model

ReplacedBy

ReplacedBy(
    sid=None,
    elementRef="",
    submodelRef="",
    portRef=None,
    idRef=None,
    unitRef=None,
    metaIdRef=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    sBaseRef=None,
)

Bases: SbaseRef

ReplacedBy: an element of this model is replaced by one of a submodel.

Create a ReplacedBy.

Parameters:

Name Type Description Default
sid str | None

the id of the replacement, which libsbml writes into no document, see the class docstring of SbaseRef

None
elementRef str

the element of this model which is replaced. A <comp:replacedBy> is written inside that element, which create_sbml is handed, so this is a pointer inside sbmlutils and is not written; it carries an empty default only because the optional sid keeps its position in front of it

''
submodelRef str

the id of the submodel the replacing element lives in, comp:submodelRef. comp requires it, and it carries an empty default for the same reason; the empty string is what the parser hands over for a document which states none, and libsbml leaves the attribute unset for it

''
portRef str | None

the port of the submodel which names the replacing element

None
idRef str | None

the id of the replacing element in the submodel

None
unitRef str | None

the id of the replacing unit definition in the submodel

None
metaIdRef str | None

the metaid of the replacing element in the submodel

None
name str | None

the name of the replacement, which libsbml writes into no document either

None
sboTerm str | None

the SBO term of the replacement

None
metaId str | None

the meta id of the replacement

None
annotations OptionalAnnotationsType

the annotations of the replacement

None
notes str | Notes | None

the notes of the replacement

None
keyValuePairs list[KeyValuePair] | None

the fbc key value pairs of the replacement

None
sBaseRef SbaseRef | None

the nested <comp:sBaseRef> which continues the reference into a submodel of the submodel

None

create_sbml

create_sbml(sbase, model)

Create SBML ReplacedBy.

Deletion

Deletion(
    sid,
    submodelRef,
    portRef=None,
    idRef=None,
    unitRef=None,
    metaIdRef=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    sBaseRef=None,
)

Bases: SbaseRef

Deletion.

Initialize Deletion.

create_sbml

create_sbml(model)

Create the libsbml.Deletion inside the submodel it deletes from.

Parameters:

Name Type Description Default
model Model

the libsbml.Model, or libsbml.ModelDefinition, the submodel of the deletion lives in

required

Returns:

Type Description
Deletion

the created libsbml.Deletion

Raises:

Type Description
ValueError

if the document does not declare the comp package, or if submodelRef names no submodel of the model

PortType

Bases: StrEnum

Supported port types.

Port

Port(
    sid,
    portRef=None,
    idRef=None,
    unitRef=None,
    metaIdRef=None,
    portType=PORT,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    sBaseRef=None,
)

Bases: SbaseRef

Port.

Ports are stored in an optional child ListOfPorts object, which, if present, must contain one or more Port objects. All of the Ports present in the ListOfPorts collectively define the 'port interface' of the Model.

portType is an authoring convenience: a port which states no sboTerm is given the SBO term of its port type, SBO:0000599 for the plain PortType.PORT of the default. portType=None asks for neither, which is what a port read from a document states: SBML has no port type, the document either carries an sboTerm or it does not, and inventing one would make a round trip of a port without an sboTerm write one.

Create a Port.

create_sbml

create_sbml(model)

Create the libsbml.Port in the given model.

Parameters:

Name Type Description Default
model Model

the libsbml.Model, or libsbml.ModelDefinition, the port is created in

required

Returns:

Type Description
Port

the created libsbml.Port

Raises:

Type Description
ValueError

if the document does not declare the comp package

Package

Bases: StrEnum

Supported/tested packages.

The definition order is the order the packages are declared on the <sbml> element in, see packages_in_canonical_order.

ModelDict

Bases: TypedDict

ModelDict.

The ModelDict allows to define the Model as dictionary and then use:

md: ModelDict Model(**md)

For model construction. If possible use the Model object directly.

Model

Model(
    sid,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    packages=None,
    creators=None,
    model_units=None,
    conversionFactor=None,
    units=None,
    objects=None,
    external_model_definitions=None,
    model_definitions=None,
    submodels=None,
    functions=None,
    compartments=None,
    species=None,
    parameters=None,
    assignments=None,
    rules=None,
    rate_rules=None,
    algebraic_rules=None,
    reactions=None,
    events=None,
    constraints=None,
    ports=None,
    replaced_elements=None,
    deletions=None,
    strict=None,
    user_defined_constraints=None,
    objectives=None,
    gene_products=None,
    layouts=None,
)

Bases: Sbase, FrozenClass

Model.

The field annotations below document the model structure. Model used to declare pydantic.BaseModel as a base, but Model.__init__ never reached BaseModel.__init__ and FrozenClass.__setattr__ shadowed pydantic's, so no validation ever ran and deepcopy, == and model_dump raised. FrozenClass rejects unknown attributes, which is what the freeze was for.

Model constructor.

create_sbml

create_sbml(doc)

Create Model.

To create the complete SBMLDocument with the model use:

doc = Document(model=model).create_sbml()

Parameters:

Name Type Description Default
doc SBMLDocument

the libsbml.SBMLDocument the model is created on. A ModelDefinition is created on the comp plugin of the document as well, which is what it inherits this from

required

Returns:

Type Description
Model

the created and filled libsbml.Model

Raises:

Type Description
ValueError

if doc is not a libsbml.SBMLDocument. A model definition used to be created in the libsbml.Model it belonged to, and a caller which still passes one would otherwise reach the comp plugin of that model and fail with an AttributeError about createModelDefinition

get_sbml

get_sbml()

Create SBML model.

check_packages

check_packages(packages)

Check that all provided packages are supported.

Parameters:

Name Type Description Default
packages list[Package] | None

the packages of the model definition, in any order

required

Returns:

Type Description
list[Package]

the packages, normalized to their version and in the canonical

list[Package]

order of packages_in_canonical_order

Raises:

Type Description
ValueError

if a package is not a Package, given twice, or not supported

merge_models staticmethod

merge_models(models)

Merge information from multiple models into a single model.

The lists of the models are concatenated, the creators and the unit definitions are collected and deduplicated, and every other attribute is taken from the last model which sets it.

Parameters:

Name Type Description Default
models Iterable[Model]

the models to merge; a single Model is returned unchanged

required

Returns:

Type Description
Model

the merged model

Raises:

Type Description
ValueError

if no models are provided

ModelDefinition

ModelDefinition(
    sid,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    keyValuePairs=None,
    packages=None,
    creators=None,
    model_units=None,
    conversionFactor=None,
    units=None,
    objects=None,
    external_model_definitions=None,
    model_definitions=None,
    submodels=None,
    functions=None,
    compartments=None,
    species=None,
    parameters=None,
    assignments=None,
    rules=None,
    rate_rules=None,
    algebraic_rules=None,
    reactions=None,
    events=None,
    constraints=None,
    ports=None,
    replaced_elements=None,
    deletions=None,
    strict=None,
    user_defined_constraints=None,
    objectives=None,
    gene_products=None,
    layouts=None,
)

Bases: Model

A comp model definition: a complete model of its own inside a document.

A <comp:modelDefinition> lives in the document next to its main model and is instantiated by the Submodels which name it in their modelRef. In libsbml ModelDefinition subclasses Model, and so does this class: the same code writes every element of it, its unit definitions, its model units and its model history included. It is created on the comp plugin of the document rather than with createModel, which is the only thing that differs, see _create_sbml.

What a model definition does not take, decided by what libsbml 5.21.2 accepts on a <comp:modelDefinition> and writes for it:

  • packages: a package is declared on the <sbml> element, which is the document, and comp gives a model definition no place to declare one. Rejected. The document declares what the content of its model definitions needs, see Model._required_packages.
  • model_definitions and external_model_definitions: both are children of the <sbml> element as well, and the CompModelPlugin of a model definition has neither createModelDefinition nor createExternalModelDefinition, so comp does not nest them at all. Rejected.
  • strict: the fbc model plugin does attach to a model definition and setStrict succeeds on it, but libsbml then writes fbc:strict twice on the <comp:modelDefinition> element and the document it writes cannot be read back, by libsbml or any other XML parser ("Duplicate XML attribute"). The attribute is therefore not written and a model definition which sets it is reported. A model definition with fbc content consequently carries the libsbml error 2020209 ("Strict attribute required on "): a document which validates with one error is usable, an unreadable one is not.

Everything else a Model holds is written into it: the comp constructs of a model definition (submodels, ports, replaced_elements, deletions), the fbc ones (gene_products, objectives, user_defined_constraints, the charge and the chemical formula of a species, the flux bounds and the gene product association of a reaction, key-value pairs), the distrib uncertainties of any of its elements and a layouts list, all through the plugins libsbml attaches to a model definition as it does to the model of a document.

A model definition is a model in a document, not the model of it: it is written by putting it in the model_definitions of a Model and writing that model. Handing one to create_model, to Document or to get_sbml is refused, since the document it would write has a <comp:modelDefinition> and no <model> at all.

Document

Document(
    model,
    sid=None,
    name=None,
    sboTerm=None,
    metaId=None,
    annotations=None,
    notes=None,
    sbml_level=SBML_LEVEL,
    sbml_version=SBML_VERSION,
)

Bases: Sbase

The SBML document a model is written into.

keyValuePairs are not offered. fbc version 3 gives a <fbc:keyValuePair> to every SBase, but libsbml 5.21.2 attaches an FbcSBMLDocumentPlugin to the <sbml> element, which has no key-value-pair accessor at all: writing the pairs of a document failed with an AttributeError on the plugin, and a <listOfKeyValuePairs> written into the XML of an <sbml> element by hand is read without an error and is invisible afterwards.

Document constructor.

Parameters:

Name Type Description Default
model Model

the model of the document

required
sid str | None

the id of the document

None
name str | None

the name of the document

None
sboTerm str | None

the SBO term of the document

None
metaId str | None

the meta id of the document

None
annotations OptionalAnnotationsType

the annotations of the document

None
notes str | Notes | None

the notes of the document

None
sbml_level int

the SBML level to write

SBML_LEVEL
sbml_version int

the SBML version to write

SBML_VERSION

Raises:

Type Description
ValueError

if the model is a ModelDefinition, which is a model of the document but not the model of the document

create_sbml

create_sbml()

Create the libsbml.SBMLDocument of the model.

This writes a whole document, so a loss which one decision fixes for every element at once is reported once rather than once per element: an annotation resource which cannot be canonicalized, see annotator.collect_resource_losses, an attribute the document has no place for, see collect_attribute_losses, and content its fbc version cannot carry, see collect_content_losses.

Returns:

Type Description
SBMLDocument

the created libsbml.SBMLDocument

get_sbml

get_sbml()

Return SBML string of the model.

:return: SBML string

get_json

get_json()

Get JSON representation.

FactoryResult dataclass

FactoryResult(
    model, sbml_path, antimony_path=None, markdown_path=None
)

Data structure for model creation.

create_objects

create_objects(model, obj_iter, key=None)

Create the objects in the model.

This function calls the respective create_sbml function of all objects in the order of the objects.

:param model: SBMLModel instance :param obj_iter: iterator of given model object classes like Parameter, ... :param key: object key :return: dictionary of SBML objects

ast_node_from_formula

ast_node_from_formula(model, formula)

Parse the ASTNode from given formula string with model.

:param model: SBMLModel instance :param formula: formula str :return: astnode

collect_attribute_losses

collect_attribute_losses()

Report the attributes a document does not carry once per kind.

An attribute is lost for the same reason on every element which carries it, and a report per element buries that one reason under thousands of lines. Inside this context every such loss is collected and logged at debug, and one warning per element kind and attribute is emitted when the context ends. Outside it, every loss is warned about on its own. Two kinds are collected:

  • an attribute which the SBML level and version of the document, or the version of the package, does not have at all, which the caller fixes for every element at once by writing SBML Level 3 Version 2 or by declaring a later version of the package, see _record_attribute_loss;
  • an attribute which libsbml writes into no document whatever the level, the core id and name of a comp reference, which the caller can do nothing about and which is therefore reported without advice, see _record_unwritten_attribute.

The context is entered by the code which writes a whole document, Document.create_sbml and create_model; a context inside an active one collects into it and reports nothing of its own.

Yields:

Type Description
None

None

collect_content_losses

collect_content_losses()

Report the content a document cannot carry once per kind.

Content which the version of a package does not have at all is lost on every element which carries it, and declaring the version which has it is one decision which keeps all of them, exactly as writing a later SBML level and version is for an attribute, see collect_attribute_losses. Inside this context every such loss is collected and one report per kind of content is emitted when the context ends. Outside it, the content of every element is reported on its own.

The context is entered by the code which writes a whole document, Document.create_sbml and create_model; a context inside an active one collects into it and reports nothing of its own.

Returns:

Type Description
AbstractContextManager[None]

the context manager

set_notes

set_notes(sbase, notes, format=MARKDOWN)

Set notes information on SBase.

:param sbase: SBase :param notes: notes information (xml string) :return:

set_model_history

set_model_history(sbase, creators, set_timestamps=True)

Set the model history from given creators.

:param sbase: SBML model :param creators: list of creators :param set_timestamps: boolean flag to set timestamps on history. :return:

date_now

date_now()

Get current time stamp for history.

:return: current libsbml Date

packages_in_canonical_order

packages_in_canonical_order(packages)

Order the packages of a model canonically, without repetition.

The packages of a model were collected in a set, which the namespace declarations and the required attributes of the <sbml> element were written from in iteration order: the order of a set of Package members depends on the hash seed, so the same model definition wrote a different <sbml> element in every process. The declaration order of a namespace carries no meaning in XML, but a file which changes between two runs cannot be compared byte by byte at all. The definition order of Package is the order used instead, which is the alphabetical one, comp, distrib, fbc.

Parameters:

Name Type Description Default
packages Iterable[Package]

the packages of a model, in any order and with repetition

required

Returns:

Type Description
list[Package]

the packages in the definition order of Package, each one once

create_model

create_model(
    model,
    filepath,
    sbml_level=SBML_LEVEL,
    sbml_version=SBML_VERSION,
    validate=True,
    validation_options=None,
    show_sbml=False,
    annotations=None,
    create_antimony=False,
    create_markdown=False,
)

Create SBML model from models.

This is the entry point for creating models. If multiple models are provided these are merged in the process of model creation. See merge_models for more details.

Additional model annotations can be provided via a file.

The created SBML can be serialized to additional formats for inspection, which are written next to the SBML file: the antimony serialization of the model (create_antimony, *.ant) and the markdown overview of the ODE system (create_markdown, *.md, see sbmlutils.converters.odefac).

:param model: Model or iterable of Model instances which are merged in single model :param filepath: Path to write the SBML model to :param sbml_level: set SBML level for model generation :param sbml_version: set SBML version for model generation :param validate: boolean flag to validate the SBML file :param validation_options: options for model validation :param show_sbml: boolean flag to show SBML :param annotations: Path to annotations file :param create_antimony: write the antimony serialization to *.ant :param create_markdown: write the markdown overview of the ODE system to *.md

:return: FactoryResult

:raises ValueError: if model is neither a Model nor an iterable of them :raises OSError: if the SBML could not be written to filepath, see write_sbml. The parent directory is created if it does not exist. Validation does not raise: a document which does not validate is written and returned all the same.