17.1.1.3.2.4. cobra.io.sbml

SBML import and export using python-libsbml.

  • The SBML importer supports all versions of SBML and the fbc package.

  • The SBML exporter writes SBML L3 models.

  • Annotation information is stored on the cobrapy objects

  • Information from the group package is read

Parsing of fbc models was implemented as efficient as possible, whereas (discouraged) fallback solutions are not optimized for efficiency.

Notes are only supported in a minimal way relevant for constraint-based models. I.e., structured information from notes in the form

<p>key: value</p>

is read into the Object.notes dictionary when reading SBML files. On writing the Object.notes dictionary is serialized to the SBML notes information.

Annotations are read in the Object.annotation fields.

Some SBML related issues are still open, please refer to the respective issue: - update annotation format and support qualifiers (depends on decision

17.1.1.3.2.4.1. Module Contents

17.1.1.3.2.4.1.1. Functions

_escape_non_alphanum(nonASCII: Match) → str

Convert non alphanumeric to string representation of ascii number.

_number_to_chr(numberStr: Match) → str

Convert an ascii number to a character.

_clip(sid: str, prefix: str) → str

Clip a prefix from the beginning of a string if it exists.

_f_gene(sid: str, prefix: str = ‘G_’) → str

Clip gene prefix from id.

_f_gene_rev(sid: str, prefix: str = ‘G_’) → str

Add gene prefix to id.

_f_specie(sid: str, prefix: str = ‘M_’) → str

Clip specie/metabolite prefix from id.

_f_specie_rev(sid: str, prefix: str = ‘M_’) → str

Add specie/metabolite prefix to id.

_f_reaction(sid: str, prefix: str = ‘R_’) → str

Clip reaction prefix from id.

_f_reaction_rev(sid: str, prefix: str = ‘R_’) → str

Add reaction prefix to id.

_f_group(sid: str, prefix: str = ‘G_’) → str

Clip group prefix from id.

_f_group_rev(sid: str, prefix: str = ‘G_’) → str

Add group prefix to id.

read_sbml_model(filename: Union[str, IO], number: Type = float, f_replace: dict = F_REPLACE, **kwargs) → Model

Read SBML model from given filename.

_get_doc_from_filename(filename: Union[str, IO]) → ‘libsbml.SBMLDocument’

Get SBMLDocument from given filename.

_sbml_to_model(doc: libsbml.SBMLDocument, number: Type = float, f_replace: dict = F_REPLACE, set_missing_bounds: bool = False, **kwargs) → Model

Create cobra model from SBMLDocument.

write_sbml_model(cobra_model: Model, filename: Union[str, IO], f_replace: dict = F_REPLACE, **kwargs) → None

Write cobra model to filename.

_model_to_sbml(cobra_model: Model, f_replace: Optional[dict] = None, units: bool = True) → libsbml.SBMLDocument

Convert Cobra model to SBMLDocument.

_create_bound(model: libsbml.Model, reaction: Reaction, bound_type: str, f_replace: dict, units: Optional[bool] = None, flux_udef: Optional[libsbml.UnitDefinition] = None) → str

Create bound in model for given reaction.

_create_parameter(model: libsbml.Model, pid: str, value: float, sbo: Optional[str] = None, constant: Optional[bool] = True, units: Optional[bool] = None, flux_udef: Optional[libsbml.UnitDefinition] = None) → None

Create parameter in SBML model.

_check_required(sbase: libsbml.Base, value: str, attribute: str) → str

Get required attribute from SBase.

_check(value: Union[None, int], message: str) → None

Check the libsbml return value and logs error messages.

_parse_notes_dict(sbase) → dict

Create dictionary of COBRA notes.

_sbase_notes_dict(sbase: libsbml.SBase, notes: dict) → None

Set SBase notes based on dictionary.

_parse_annotations(sbase: libsbml.SBase) → dict

Parse cobra annotations from a given SBase object.

_parse_annotation_info(uri: str) → Union[None, Tuple[str, str]]

Parse provider and term from given identifiers annotation uri.

_sbase_annotations(sbase: libsbml.SBase, annotation: dict) → None

Set SBase annotations based on cobra annotations.

validate_sbml_model(filename: Union[str, IO], check_model: bool = True, internal_consistency: bool = True, check_units_consistency: bool = False, check_modeling_practice: bool = False, **kwargs) → Tuple[Optional[Model], dict]

Validate SBML model and returns the model along with a list of errors.

_error_string(error: libsbml.SBMLError, k: Optional[int] = None)

Return string representation of SBMLError.

exception cobra.io.sbml.CobraSBMLError[source]

Bases: Exception

SBML error class.

cobra.io.sbml.LOGGER[source]
cobra.io.sbml.config[source]
cobra.io.sbml.LOWER_BOUND_ID = cobra_default_lb[source]
cobra.io.sbml.UPPER_BOUND_ID = cobra_default_ub[source]
cobra.io.sbml.ZERO_BOUND_ID = cobra_0_bound[source]
cobra.io.sbml.BOUND_MINUS_INF = minus_inf[source]
cobra.io.sbml.BOUND_PLUS_INF = plus_inf[source]
cobra.io.sbml.SBO_FBA_FRAMEWORK = SBO:0000624[source]
cobra.io.sbml.SBO_DEFAULT_FLUX_BOUND = SBO:0000626[source]
cobra.io.sbml.SBO_FLUX_BOUND = SBO:0000625[source]
cobra.io.sbml.SBO_EXCHANGE_REACTION = SBO:0000627[source]
cobra.io.sbml.LONG_SHORT_DIRECTION[source]
cobra.io.sbml.SHORT_LONG_DIRECTION[source]
cobra.io.sbml.Unit[source]
cobra.io.sbml.UNITS_FLUX = ['mmol_per_gDW_per_hr', None][source]
cobra.io.sbml.SBML_DOT = __SBML_DOT__[source]
cobra.io.sbml.pattern_notes :Pattern[source]
cobra.io.sbml.pattern_to_sbml :Pattern[source]
cobra.io.sbml.pattern_from_sbml :Pattern[source]
cobra.io.sbml._escape_non_alphanum(nonASCII: Match) → str[source]

Convert non alphanumeric to string representation of ascii number.

Converts a non alphanumeric character to a string representation of its ascii number using ord.

Parameters

nonASCII (Match) – Match object, identified by pattern_from_sbml

Returns

The ascii code, surronded by __.

Return type

str

cobra.io.sbml._number_to_chr(numberStr: Match) → str[source]

Convert an ascii number to a character.

Parameters

numberStr (Match) – Match object, identified by pattern_from_sbml

Returns

The first match between the underscores, converted to character.

Return type

str

cobra.io.sbml._clip(sid: str, prefix: str) → str[source]

Clip a prefix from the beginning of a string if it exists.

Parameters
  • sid (str) – String to clip.

  • prefix (str) – Prefix to remove.

Returns

The string with prefix clipped if it existed. Otherwise the original string.

Return type

str

cobra.io.sbml._f_gene(sid: str, prefix: str = 'G_') → str[source]

Clip gene prefix from id.

Parameters
  • sid (str) – String to process

  • prefix (str, optional) – Prefix for gene (default “G_”).

Returns

Returns modified str with prefix removed, SBML_DOT (see above) replaced with “.”, __(NUMBER)__ replaced with the character value of NUMBER.

Return type

str

cobra.io.sbml._f_gene_rev(sid: str, prefix: str = 'G_') → str[source]

Add gene prefix to id.

Parameters
  • sid (str) – String to process

  • prefix (str, optional) – Prefix for gene (default “G_”).

Returns

Returns prefix prepended to modified str, with “.” replaced with SBML_DOT, non alphanumeric repalced with a string representation of the unicode number.

Return type

str

cobra.io.sbml._f_specie(sid: str, prefix: str = 'M_') → str[source]

Clip specie/metabolite prefix from id.

Parameters
  • sid (str) – String to process

  • prefix (str, optional) – Prefix for species/metabolite (default “M_”).

Returns

Returns modified str with prefix removed, SBML_DOT (see above) replaced with “.”, __(NUMBER)__ replaced with the character value of NUMBER.

Return type

str

cobra.io.sbml._f_specie_rev(sid: str, prefix: str = 'M_') → str[source]

Add specie/metabolite prefix to id.

Parameters
  • sid (str) – String to process

  • prefix (str, optional) – Prefix for metabolite (default “M_”).

Returns

Returns prefix prepended to modified str, with “.” replaced with SBML_DOT, non alphanumeric repalced with a string representation of the unicode number.

Return type

str

cobra.io.sbml._f_reaction(sid: str, prefix: str = 'R_') → str[source]

Clip reaction prefix from id.

Parameters
  • sid (str) – String to process

  • prefix (str, optional) – Prefix for reaction (default “R_”).

Returns

Returns modified str with prefix removed, SBML_DOT (see above) replaced with “.”, __(NUMBER)__ replaced with the character value of NUMBER.

Return type

str

cobra.io.sbml._f_reaction_rev(sid: str, prefix: str = 'R_') → str[source]

Add reaction prefix to id.

Parameters
  • sid (str) – String to process

  • prefix (str, optional) – Prefix for reaction (default “R_”).

Returns

Returns prefix prepended to modified str, with “.” replaced with SBML_DOT, non alphanumeric repalced with a string representation of the unicode number.

Return type

str

cobra.io.sbml._f_group(sid: str, prefix: str = 'G_') → str[source]

Clip group prefix from id.

Parameters
  • sid (str) – String to process

  • prefix (str, optional) – Prefix for group (default “G_”).

Returns

Returns modified str with prefix removed, SBML_DOT (see above) replaced with “.”, __(NUMBER)__ replaced with the character value of NUMBER.

Return type

str

cobra.io.sbml._f_group_rev(sid: str, prefix: str = 'G_') → str[source]

Add group prefix to id.

Parameters
  • sid (str) – String to process

  • prefix (str, optional) – Prefix for group (default “G_”).

Returns

Returns prefix prepended to modified str, with “.” replaced with SBML_DOT, non alphanumeric repalced with a string representation of the unicode number.

Return type

str

cobra.io.sbml.F_GENE = F_GENE[source]
cobra.io.sbml.F_GENE_REV = F_GENE_REV[source]
cobra.io.sbml.F_SPECIE = F_SPECIE[source]
cobra.io.sbml.F_SPECIE_REV = F_SPECIE_REV[source]
cobra.io.sbml.F_REACTION = F_REACTION[source]
cobra.io.sbml.F_REACTION_REV = F_REACTION_REV[source]
cobra.io.sbml.F_GROUP = F_GROUP[source]
cobra.io.sbml.F_GROUP_REV = F_GROUP_REV[source]
cobra.io.sbml.F_REPLACE :dict[source]
cobra.io.sbml.read_sbml_model(filename: Union[str, IO], number: Type = float, f_replace: dict = F_REPLACE, **kwargs) → Model[source]

Read SBML model from given filename.

If the given filename ends with the suffix ‘’.gz’’ (for example, ‘’myfile.xml.gz’),’ the file is assumed to be compressed in gzip format and will be automatically decompressed upon reading. Similarly, if the given filename ends with ‘’.zip’’ or ‘’.bz2’,’ the file is assumed to be compressed in zip or bzip2 format (respectively). Files whose names lack these suffixes will be read uncompressed. Note that if the file is in zip format but the archive contains more than one file, only the first file in the archive will be read and the rest ignored.

To read a gzip/zip file, libSBML needs to be configured and linked with the zlib library at compile time. It also needs to be linked with the bzip2 library to read files in bzip2 format. (Both of these are the default configurations for libSBML.)

This function supports SBML with FBC-v1 and FBC-v2. FBC-v1 models are converted to FBC-v2 models before reading.

The parser tries to fall back to information in notes dictionaries if information is not available in the FBC packages, e.g., CHARGE, FORMULA on species, or GENE_ASSOCIATION, SUBSYSTEM on reactions.

Parameters
  • filename (path to SBML file, or SBML string, or SBML file handle) – SBML which is read into cobra model

  • number (data type of stoichiometry: {float, int}) – In which data type should the stoichiometry be parsed.

  • f_replace (dict of replacement functions for id replacement) – Dictionary of replacement functions for gene, specie, and reaction. By default the following id changes are performed on import: clip G_ from genes, clip M_ from species, clip R_ from reactions If no replacements should be performed, set f_replace={}, None

  • **kwargs – Further keyword arguments are passed on to the called function (_sbml_to_model)

Returns

Return type

cobra.core.Model

Raises
  • IOError if file not read

  • All other errors are wrapped around in a message pointing to SBML validator.

Notes

Provided file handles cannot be opened in binary mode, i.e., use
with open(path, “r” as f):

read_sbml_model(f)

File handles to compressed files are not supported yet.

cobra.io.sbml._get_doc_from_filename(filename: Union[str, IO]) → 'libsbml.SBMLDocument'[source]

Get SBMLDocument from given filename.

Parameters

filename (path to SBML, or SBML string, or filehandle) –

Returns

Return type

libsbml.SBMLDocument

Raises
  • IOError if file not readable or does not contain SBML.

  • CobraSBMLError if input type is not valid.

cobra.io.sbml._sbml_to_model(doc: libsbml.SBMLDocument, number: Type = float, f_replace: dict = F_REPLACE, set_missing_bounds: bool = False, **kwargs) → Model[source]

Create cobra model from SBMLDocument.

Parameters
  • doc (libsbml.SBMLDocument) –

  • number (data type of stoichiometry: {float, int}) – In which data type should the stoichiometry be parsed.

  • f_replace (dict) – dict of replacement functions for id replacement

  • set_missing_bounds (bool) – flag to set missing bounds. Looks like it will be ignored.

  • **kwargs – Further keyword arguments are passed on.

Returns

Return type

cobra.core.Model

Raises
  • CobraSBMLError if no SBML model detected in file.

  • Exception if fbc coversion from v1 to v2 needed and not successful.

  • CobraSBMLError if upper or lower bound are missing from a reaction.

  • CobraSBMLError if objective reaction declared and not found. Objective reaction not – declared will lead to an ERROR being logged.

cobra.io.sbml.write_sbml_model(cobra_model: Model, filename: Union[str, IO], f_replace: dict = F_REPLACE, **kwargs) → None[source]

Write cobra model to filename.

The created model is SBML level 3 version 1 (L1V3) with fbc package v2 (fbc-v2).

If the given filename ends with the suffix “.gz” (for example, “myfile.xml.gz”), libSBML assumes the caller wants the file to be written compressed in gzip format. Similarly, if the given filename ends with “.zip” or “.bz2”, libSBML assumes the caller wants the file to be compressed in zip or bzip2 format (respectively). Files whose names lack these suffixes will be written uncompressed. Special considerations for the zip format: If the given filename ends with “.zip”, the file placed in the zip archive will have the suffix “.xml” or “.sbml”. For example, the file in the zip archive will be named “test.xml” if the given filename is “test.xml.zip” or “test.zip”. Similarly, the filename in the archive will be “test.sbml” if the given filename is “test.sbml.zip”.

Parameters
  • cobra_model (cobra.core.Model) – Model instance which is written to SBML

  • filename (string or filehandle) – path to which the model is written

  • f_replace (dict) – dictionary of replacement functions for id replacement

  • **kwargs – Further keyword arguments are passed on.

cobra.io.sbml._model_to_sbml(cobra_model: Model, f_replace: Optional[dict] = None, units: bool = True) → libsbml.SBMLDocument[source]

Convert Cobra model to SBMLDocument.

Parameters
  • cobra_model (cobra.core.Model) – Cobra model instance

  • f_replace (dict of replacement functions) – Replacement to apply on identifiers.

  • units (boolean) – Should the FLUX_UNITS be written in the SBMLDocument.

Returns

Return type

libsbml.SBMLDocument

cobra.io.sbml._create_bound(model: libsbml.Model, reaction: Reaction, bound_type: str, f_replace: dict, units: Optional[bool] = None, flux_udef: Optional[libsbml.UnitDefinition] = None) → str[source]

Create bound in model for given reaction.

Adds the parameters for the bounds to the SBML model.

Parameters
  • model (libsbml.Model) – SBML model instance

  • reaction (cobra.core.Reaction) – Cobra reaction instance from which the bounds are read.

  • bound_type ({LOWER_BOUND, UPPER_BOUND}) – Type of bound

  • f_replace (dict) – of id replacement functions

  • units (bool, optional, defualt None) – Whether or not to use flux units in the SBML document.

  • flux_udef (libsbml.UnitDefinition, optional) – Unit definition if units are used.

Returns

pid – Id of bound parameter.

Return type

str

cobra.io.sbml._create_parameter(model: libsbml.Model, pid: str, value: float, sbo: Optional[str] = None, constant: Optional[bool] = True, units: Optional[bool] = None, flux_udef: Optional[libsbml.UnitDefinition] = None) → None[source]

Create parameter in SBML model.

Parameters
  • model (libsbml.Model) – SBML model instance

  • pid (str) – Parameter id to create in the SBML model.

  • value (float) – Value to set parameter

  • sbo (str, optional) – SBO term for parameter. In COBRA, it seems to be SBO_FLUX_BOUND ( “SBO:0000625”) or SBO_DEFAULT_FLUX_BOUND (“SBO:0000626”)

  • constant (bool, optional) – Flag if parameter is constant.

  • units (bool, optional, defualt None) – Whether or not to use flux units in the SBML document.

  • flux_udef (libsbml.UnitDefinition, optional) – Unit definition if units are used.

cobra.io.sbml._check_required(sbase: libsbml.Base, value: str, attribute: str) → str[source]

Get required attribute from SBase.

Parameters
  • sbase (libsbml.SBase) –

  • value (existing value) –

  • attribute (name of attribute) –

Returns

Return type

attribute value (or value if already set)

Raises

CobraSBMLError if attribute not found or not parsed.

cobra.io.sbml._check(value: Union[None, int], message: str) → None[source]

Check the libsbml return value and logs error messages.

Parameters
  • value (None or int) –

  • message (str) –

  • 'value' is None, logs an error message constructed using (If) – ‘message’ and then exits with status code 1. If ‘value’ is an integer, it assumes it is a libSBML return status code. If the code value is LIBSBML_OPERATION_SUCCESS, returns without further action; if it is not, prints an error message constructed using ‘message’ along with text from libSBML explaining the meaning of the code, and exits with status code 1.

cobra.io.sbml._parse_notes_dict(sbase) → dict[source]

Create dictionary of COBRA notes.

Parameters

sbase (libsbml.SBase) –

Returns

Return type

dict of notes

cobra.io.sbml._sbase_notes_dict(sbase: libsbml.SBase, notes: dict) → None[source]

Set SBase notes based on dictionary.

Parameters
  • sbase (libsbml.SBase) – SBML object to set notes on

  • notes (dict) – Notes information from cobra object.

cobra.io.sbml.URL_IDENTIFIERS_PATTERN[source]
cobra.io.sbml.URL_IDENTIFIERS_PREFIX = https://identifiers.org[source]
cobra.io.sbml.QUALIFIER_TYPES[source]
cobra.io.sbml._parse_annotations(sbase: libsbml.SBase) → dict[source]

Parse cobra annotations from a given SBase object.

Annotations are dictionaries with the providers as keys.

Parameters

sbase (libsbml.SBase) – SBase from which the SBML annotations are read

Returns

Return type

dict (annotation dictionary)

cobra.io.sbml._parse_annotation_info(uri: str) → Union[None, Tuple[str, str]][source]

Parse provider and term from given identifiers annotation uri.

Parameters

uri (str) – uri (identifiers.org url)

Returns

Return type

(provider, identifier) if resolvable, None otherwise

cobra.io.sbml._sbase_annotations(sbase: libsbml.SBase, annotation: dict) → None[source]

Set SBase annotations based on cobra annotations.

Parameters
  • sbase (libsbml.SBase) – SBML object to annotate

  • annotation (dict, cobra annotation structure) – cobra object with annotation information

Raises

CobraSBMLError for unsupported qualifier

cobra.io.sbml.validate_sbml_model(filename: Union[str, IO], check_model: bool = True, internal_consistency: bool = True, check_units_consistency: bool = False, check_modeling_practice: bool = False, **kwargs) → Tuple[Optional[Model], dict][source]

Validate SBML model and returns the model along with a list of errors.

Parameters
  • filename (str or filehandle) – The filename (or SBML string) of the SBML model to be validated.

  • check_model (boolean {True, False}, default True) – Whether to also check some basic model properties such as reaction boundaries and compartment formulas.

  • internal_consistency (bool, optional) – Check internal consistency (default True).

  • check_units_consistency (bool, optional) – Check consistency of units (default True).

  • check_modeling_practice (bool, optional) – Check modeling practise (defualt True).

  • **kwargs – Further keyword arguments are passed on to the called function (_sbml_to_model).

Returns

  • (model, errors)

  • model (Model object) – The cobra model if the file could be read successfully or None otherwise.

  • errors (dict) – Warnings and errors grouped by their respective types.

Notes

Errors and warnings are grouped based on their type. SBML_* types are from the libsbml validator. COBRA_* types are from the cobrapy SBML parser.

cobra.io.sbml._error_string(error: libsbml.SBMLError, k: Optional[int] = None)[source]

Return string representation of SBMLError.

Parameters
  • error (libsbml.SBMLError) –

  • k (int, optional) – index of error (default None).

Returns

Return type

string representation of error