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
for new annotation format; https://github.com/opencobra/cobrapy/issues/684)
- write compartment annotations and notes (depends on updated first-class
compartments; see https://github.com/opencobra/cobrapy/issues/760)
- support compression on file handles (depends on solution for
Module Contents¶
Functions¶
|
Convert non alphanumeric to string representation of ascii number. |
|
Convert an ascii number to a character. |
|
Clip a prefix from the beginning of a string if it exists. |
|
Clip gene prefix from id. |
|
Add gene prefix to id. |
|
Clip specie/metabolite prefix from id. |
|
Add specie/metabolite prefix to id. |
|
Clip reaction prefix from id. |
|
Add reaction prefix to id. |
|
Clip group prefix from id. |
|
Add group prefix to id. |
|
Read SBML model from given filename. |
|
Get SBMLDocument from given filename. |
|
Create cobra model from SBMLDocument. |
|
Write cobra model to filename. |
|
Convert Cobra model to SBMLDocument. |
|
Create bound in model for given reaction. |
|
Create parameter in SBML model. |
|
Get required attribute from SBase. |
|
Check the libsbml return value and logs error messages. |
|
Create dictionary of COBRA notes. |
|
Set SBase notes based on dictionary. |
|
Parse cobra annotations from a given SBase object. |
|
Parse provider and term from given identifiers annotation uri. |
|
Set SBase annotations based on cobra annotations. |
|
Validate SBML model and returns the model along with a list of errors. |
|
Return string representation of SBMLError. |
Attributes¶
- 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
- 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
- cobra.io.sbml._clip(sid: str, prefix: str) str [source]¶
Clip a prefix from the beginning of a string if it exists.
- cobra.io.sbml._f_gene(sid: str, prefix: str = 'G_') str [source]¶
Clip gene prefix from id.
- Parameters
- Returns
Returns modified str with prefix removed, SBML_DOT (see above) replaced with “.”, __(NUMBER)__ replaced with the character value of NUMBER.
- Return type
See also
- cobra.io.sbml._f_gene_rev(sid: str, prefix: str = 'G_') str [source]¶
Add gene prefix to id.
- Parameters
- 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
See also
- cobra.io.sbml._f_specie(sid: str, prefix: str = 'M_') str [source]¶
Clip specie/metabolite prefix from id.
- Parameters
- Returns
Returns modified str with prefix removed, SBML_DOT (see above) replaced with “.”, __(NUMBER)__ replaced with the character value of NUMBER.
- Return type
See also
- cobra.io.sbml._f_specie_rev(sid: str, prefix: str = 'M_') str [source]¶
Add specie/metabolite prefix to id.
- Parameters
- 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
See also
- cobra.io.sbml._f_reaction(sid: str, prefix: str = 'R_') str [source]¶
Clip reaction prefix from id.
- Parameters
- Returns
Returns modified str with prefix removed, SBML_DOT (see above) replaced with “.”, __(NUMBER)__ replaced with the character value of NUMBER.
- Return type
See also
- cobra.io.sbml._f_reaction_rev(sid: str, prefix: str = 'R_') str [source]¶
Add reaction prefix to id.
- Parameters
- 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
See also
- cobra.io.sbml._f_group(sid: str, prefix: str = 'G_') str [source]¶
Clip group prefix from id.
- Parameters
- Returns
Returns modified str with prefix removed, SBML_DOT (see above) replaced with “.”, __(NUMBER)__ replaced with the character value of NUMBER.
- Return type
See also
- cobra.io.sbml._f_group_rev(sid: str, prefix: str = 'G_') str [source]¶
Add group prefix to id.
- Parameters
- 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
See also
- cobra.io.sbml.read_sbml_model(filename: Union[str, IO, pathlib.Path], number: Type = float, f_replace: dict = F_REPLACE, **kwargs) cobra.core.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)
- Return type
- 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, pathlib.Path]) libsbml.SBMLDocument [source]¶
Get SBMLDocument from given filename.
- Parameters
filename (path to SBML, or SBML string, or filehandle) –
- 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) cobra.core.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.
- Return type
- 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: cobra.core.Model, filename: Union[str, IO, pathlib.Path], 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: cobra.core.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.
- Return type
libsbml.SBMLDocument
- cobra.io.sbml._create_bound(model: libsbml.Model, reaction: cobra.core.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
- 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) –
- 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) –
None (If 'value' is) – ‘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.
using (logs an error message constructed) – ‘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) –
- 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._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
- 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)
- 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, pathlib.Path], check_model: bool = True, internal_consistency: bool = True, check_units_consistency: bool = False, check_modeling_practice: bool = False, **kwargs) Tuple[Optional[cobra.core.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.