booldog.io.sbml

Read-write SBML-qual files

Notes

SBML-qual code is inspired by:

Attributes

_SBML_AVAILABLE

logger

SBML_INT_MAX

Sentinel value libsbml uses for "unset" integer attributes (e.g. a

TOKEN_REGEX

Tokenizes a bnet-format rule string into !, &, |,

Exceptions

BoolDogSBMLException

Custom Exception for SBML parsing

Classes

SBMLQualReader

Read an SBML-qual XML file, converting each transition to a

TransitionParser

Parse SBML transition to bnet format

MathMLParser

Recursively parse a libsbml MathML AST (as used in SBML-qual

SBMLQualWriter

Build and write an SBML-qual representation of a Boolean

Functions

read_sbmlqual(file)

Parse an SBML-qual file into the data needed to construct a

write_sbmlqual(model, outfile, **kwargs)

Write a BoolDogModel object to an SBML-qual file, via

Module Contents

booldog.io.sbml._SBML_AVAILABLE = True
booldog.io.sbml.logger
booldog.io.sbml.SBML_INT_MAX = 2147483647

Sentinel value libsbml uses for “unset” integer attributes (e.g. a qualitative species/transition’s threshold or output level). Compared against to determine whether such an attribute was actually set in the SBML file.

Type:

int

booldog.io.sbml.TOKEN_REGEX

Tokenizes a bnet-format rule string into !, &, |, (, ) and identifier tokens, ignoring surrounding whitespace. Used by SBMLQualWriter._rule_to_formula() to translate bnet rule syntax into the &&/|| syntax accepted by libsbml.parseL3Formula.

Type:

re.Pattern

exception booldog.io.sbml.BoolDogSBMLException

Bases: Exception

Custom Exception for SBML parsing

class booldog.io.sbml.SBMLQualReader(file)

Read an SBML-qual XML file, converting each transition to a bnet-format Boolean rule.

Parameters:

file (str or path-like) – Path to SBML-qual file containing a Boolean network.

Raises:
file

Path to the SBML-qual file, as given at construction.

Type:

str or path-like

document

The parsed SBML document.

Type:

libsbml.SBMLDocument

model

The SBML model contained in document.

Type:

libsbml.Model

model_id

The SBML model’s id attribute.

Type:

str

plugin

The ‘qual’ package plugin of model, providing access to qualitative species and transitions.

Type:

libsbml.QualModelPlugin

all_species

Ids of all qualitative species defined in the model.

Type:

list of str

species_names

Mapping of qualitative species id to its (possibly empty) SBML name attribute.

Type:

dict

transitions

All transitions defined in the model.

Type:

list of libsbml.Transition

rules

Mapping of output species id to its bnet-format Boolean rule string, derived from the model’s transitions (see _get_all_rules()).

Type:

dict

_get_qual_plugin()

Find and return the model’s ‘qual’ package plugin.

Returns:

The ‘qual’ plugin attached to model.

Return type:

libsbml.QualModelPlugin

Raises:

BoolDogSBMLException – If the model has no plugin with package name ‘qual’.

_get_all_species()

List all qualitative species defined via the ‘qual’ plugin.

Returns:

(id, name) pairs for every qualitative species in plugin, in declaration order.

Return type:

list of tuple

_get_all_transitions()

List all transitions defined via the ‘qual’ plugin.

Returns:

Every transition in plugin, in declaration order.

Return type:

list of libsbml.Transition

_get_all_rules()

Derive a bnet-format Boolean rule for each transition’s output species.

For each transition, inputs/outputs are extracted with TransitionParser.parse_io() and its function term is parsed with TransitionParser.parse_function(); the resulting rule string is assigned to every one of that transition’s output species.

Returns:

Mapping of output species id to its bnet-format rule string.

Return type:

dict

to_bnet()

Converts the SBML-qual file to a bnet format.

Returns:

bnet – bnet representation of the Boolean network.

Return type:

str

class booldog.io.sbml.TransitionParser

Parse SBML transition to bnet format

static parse_io(transition, all_species)

Extract transition inputs and outputs.

Parameters:
  • transition (libsbml::Transition) – Transition specifying the logical rule associated with the Transition outputs.

  • all_species (list) – List ids of all species present in model

Returns:

  • inputs (dict) – Dictionary mapping each input’s id to a dict of its species information: "id", "species" (qualitative species id), "sign", "threshold" (int, or None if unset in the SBML file), and "transition_effect".

  • outputs (list) – List of dicts (one per transition output), each with keys "species", "transition_effect" and "output_level" (int, or None if unset).

Notes

Warnings are logged (not raised) for inputs/outputs referencing a species not in all_species, inputs with a transition effect other than “None”, or inputs with a threshold that isn’t 0 or 1 — these are conditions this Boolean-only SBML-qual reader does not support, but does not treat as fatal for inputs.

For outputs, an unrecognised species, an unsupported transition effect (i.e. not “assignmentLevel”), or a set output level are all logged as warnings and skipped (excluded from the returned outputs list), without affecting collection of any other outputs for this transition.

static parse_function(transition, all_species, inputs)

Parse transition function to a logical rule.

Parameters:
  • transition (libsbml::Transition) – Transition specifying the logical rule associated with the Transition outputs.

  • all_species (list) – List ids of all species present in model

  • inputs (dict) – Dictionary of id: species information for this transition’s inputs

Returns:

logic_rule – Logic rule of this transition (in bnet format)

Return type:

str

Raises:

BoolDogSBMLException – If MathMLParser.parse() fails to parse a function term’s MathML.

Notes

Function terms named “defaultTerm” are skipped (the actual default result is read separately from transition.getDefaultTerm()). Every other function term is parsed to a bnet-format expression via MathMLParser.parse(), and sorted by its ResultLevel into an activation list (level 1) or inhibition list (level 0 or anything else).

The final rule is built as:

  • "( a1 | a2 | ... ) & !( i1 | i2 | ... )" if there is at least one activation and one inhibition term;

  • "( a1 | a2 | ... )" if there are only activation terms;

  • "!( i1 | i2 | ... )" if there are only inhibition terms;

  • str(default_term) (i.e. "0" or "1") if there are no non-default function terms at all.

class booldog.io.sbml.MathMLParser

Recursively parse a libsbml MathML AST (as used in SBML-qual FunctionTerms) into a bnet-format Boolean rule string.

static parse(node, all_species, inputs, level=0)

Recursively parse a MathML AST node to bnet syntax.

Parameters:
  • node (libsbml.ASTNode) – The (sub-)expression to parse.

  • all_species (list) – List of ids of all species present in the model; leaf nodes named after one of these are treated as species references.

  • inputs (dict) – Mapping of transition input id to its species information (as returned by TransitionParser.parse_io()); leaf nodes named after one of these keys are resolved to that input’s "threshold" value.

  • level (int, optional) – Current recursion depth, used by _handle_operator() to decide whether to wrap the result in parentheses (top-level expressions, level == 0, are not parenthesised). Default 0.

Returns:

For a leaf node: the species id (str) if it names a species in all_species; the referenced input’s threshold (int or None) if it names a key in inputs; or the node’s integer value (int) if it is an integer literal. For an internal node: the bnet-format string built by _handle_operator() from its (recursively parsed) children.

Return type:

str or int

Raises:

ValueError – If a leaf node’s name matches neither a species nor an input id, and it is not an integer literal.

static _handle_operator(operator, children, level)

Combine already-parsed child expressions with a MathML operator, into a bnet-format expression string.

Parameters:
  • operator (str) – MathML operator name (e.g. “and”, “or”, “times”, “plus”, “xor”, “not”, or a comparison: “eq”, “neq”, “gt”, “lt”, “geq”, “leq”).

  • children (list) – The operator’s operands, already parsed to bnet-format strings (or, for comparisons, possibly ints — see _handle_comparison()).

  • level (int) – Recursion depth of the containing expression (see parse()); if greater than 0 the combined “and”/”or” expression is wrapped in parentheses.

Returns:

The combined bnet-format expression. “times”/”plus” are treated as “and”/”or” respectively (a common encoding when Boolean values are represented as 0/1 numerically).

Return type:

str

Raises:

ValueError – If operator is “not” and does not have exactly one child, or if operator is not one of the recognised MathML operators.

static _handle_xor(children)

Combine already-parsed child expressions with an n-ary xor, via a minimal disjunctive normal form (DNF).

Since bnet syntax has no native xor operator, each of children (bnet-format expression strings) is treated as an opaque Boolean variable, an n-input xor truth table over them is built, and booldog.utils.boolean_normal_forms.functions2mindnf() is used to minimise it to a DNF bnet-format expression string, substituting the original child expression strings back in as “variable names”.

Parameters:

children (list of str) – The xor’s operands, already parsed to bnet-format strings.

Returns:

A minimal-DNF bnet-format expression equivalent to the xor of children.

Return type:

str

static _handle_comparison(operator, children)

Return the bnet form of a MathML comparison operator applied to two already-parsed operands.

Parameters:
  • operator (str) – One of “eq”, “neq”, “gt”, “lt”, “geq”, “leq”.

  • children (list) – Exactly two operands: each either a bnet-format expression string (a Boolean-valued sub-expression) or an int (a threshold/integer-literal leaf value, from parse()).

Returns:

The bnet-format result of applying operator to the two operands:

  • if both operands are int: the Python comparison’s Boolean result, as bnet’s "1"/"0";

  • if exactly one operand is an int (0 or 1): a simplified bnet-format expression referencing only the variable operand (e.g. x >= 1 is just x; x >= 0 is always true, i.e. "1");

  • if neither operand is an int: a full bnet-format Boolean expression combining both operands’ expression strings.

Return type:

str

Raises:

ValueError – If children does not have exactly two elements.

class booldog.io.sbml.SBMLQualWriter(network, level=3, version=1, qual_version=1)

Build and write an SBML-qual representation of a Boolean BoolDogModel.

Each node becomes a qualitative species (id sanitised to alphanumerics only), and each node’s rule becomes a Transition with a single FunctionTerm (result level 1, built from the rule via _rule_to_formula()) and a DefaultTerm of result level 0.

Parameters:
  • network (BoolDogModel) – The Boolean network to export.

  • level (int, optional) – SBML level. Default 3.

  • version (int, optional) – SBML version. Default 1.

  • qual_version (int, optional) – Version of the ‘qual’ package. Default 1.

network

The network being exported, as given at construction.

Type:

BoolDogModel

mplugin

The ‘qual’ plugin of the SBML model being built, used to create qualitative species and transitions.

Type:

libsbml.QualModelPlugin

node_dict

Mapping of BoolDog node identifier to its sanitised SBML-qual species id, populated by _add_species().

Type:

dict

doc

The fully-built SBML document, ready to be written out with write().

Type:

libsbml.SBMLDocument

write(outfile)

Write the built SBML document to file.

Parameters:

outfile (str or Path) – Path to write the SBML-qual XML file to.

Return type:

None

_add_species()

Create a qualitative species for every node in network.

The SBML id is derived from the node identifier by lower-casing it and stripping any non-alphanumeric/underscore characters (so it is recorded in node_dict, since it may no longer match the original node identifier). Each species is placed in the single compartment “c”, marked constant according to network.is_constant(node), and named after node.name.

Return type:

None

_add_transitions()

Create a Transition for every node in network, encoding its Boolean rule.

Each transition has a single output (the node itself, with transition effect “assignmentLevel”), one FunctionTerm (result level 1) whose math is the node’s rule converted via _rule_to_formula(), and a DefaultTerm of result level 0. Transition inputs (regulator thresholds) are not currently created; see the commented-out code and _rule_to_formula()’s Notes for the planned (not yet implemented) threshold support.

Return type:

None

Raises:

BoolDogSBMLException – If building the MathML formula for a node’s rule fails (wraps the underlying exception).

_rule_to_formula(rule, input_node_dict)

Convert a bnet-format rule to a MathML AST, as supported by libsbml.parseL3Formula.

Parameters:
  • rule (str) – A Boolean rule in bnet format (using node identifiers as they appear in network, e.g. "A & !B").

  • input_node_dict (dict) – Currently unused by this method (reserved/accepted for the planned threshold support described below, but not read here).

Returns:

The MathML AST parsed from the reformatted formula (the return value of libsbml.parseL3Formula), suitable for FunctionTerm.setMath.

Return type:

libsbml.ASTNode

Raises:

KeyError – If an identifier token in rule is not a key of node_dict (i.e. not a node of network).

Notes

Tokenizes rule with TOKEN_REGEX and, for each token, replaces:

  • & with &&

  • | with ||

  • identifiers with their sanitised SBML species id (self.node_dict[tok])

  • !, (, ) are kept as-is

then parses the reassembled string with libsbml.parseL3Formula.

To support thresholds, we need to replace the bnet format with a format supported by libsbml’s parseL3Formula:

  • A to (A >= theta_A) f”({node_dict[node]} >= {input_node_dict[node]})”

  • !A to (A < theta_A) f”({node_dict[node]} < {input_node_dict[node]})”

This is currently NOT implemented.

booldog.io.sbml.read_sbmlqual(file)

Parse an SBML-qual file into the data needed to construct a BoolDogModel.

Parameters:

file (str) – Path to SBML-qual file.

Returns:

data – Dictionary with keys "nodes" (list of BoolDogNode, one per qualitative species; nodes with no associated transition get rule=None), "modelinfo" (BoolDogModelInfo, with identifier set to the SBML model id and source_format set to "sbml-qual"), and "primes" (None, since primes are not computed by this reader). Suitable for BoolDogModel(**data).

Return type:

dict

Raises:

ImportError – If libsbml is not installed.

Notes

The SBML-qual file is converted to a Boolean network using libsbml, via the bnet format. To access the bnet format directly, you can construct a SBMLQualReader and call its SBMLQualReader.to_bnet() method.

booldog.io.sbml.write_sbmlqual(model, outfile, **kwargs)

Write a BoolDogModel object to an SBML-qual file, via SBMLQualWriter.

Parameters:
  • model (BoolDogModel) – A BoolDog object representing a Boolean network.

  • outfile (str or Path) – Path to write the SBML-qual XML file to.

  • **kwargs – Forwarded to SBMLQualWriter.write(). SBMLQualWriter is also always constructed with its default level/version/qual_version; those are not currently configurable from this function.

Return type:

None

Raises:
  • ImportError – If libsbml is not installed.

  • TypeErrorKnown bug, not intentional behaviour: SBMLQualWriter.write() only accepts outfile, so passing any keyword arguments in **kwargs here raises TypeError. See KNOWN_BUGS.md.