17.1.4. cobra.io

Provide functions for loading and saving metabolic models.

Subpackages

Submodules

Package Contents

Classes

AbstractModelRepository

Define an abstract base class that describes a remote model repository.

BiGGModels

Define a concrete implementation of the BiGG Models repository.

BioModels

Define a concrete implementation of the BioModels repository.

Functions

model_from_dict(→ cobra.core.Model)

Build a cobra Model from a dictionary.

model_to_dict(→ collections.OrderedDict)

Convert a cobra Model to a dictionary.

from_json(→ cobra.Model)

Load a cobra model from a JSON string.

load_json_model(→ cobra.Model)

Load a cobra model from a file in JSON format.

save_json_model(→ None)

Write the cobra model to a file in JSON format.

to_json(→ str)

Return the model as a JSON string.

load_matlab_model(→ cobra.core.Model)

Load a cobra model stored as a .mat file.

save_matlab_model(→ None)

Save the cobra model as a .mat file.

read_sbml_model(→ cobra.core.Model)

Read SBML model from given filename.

write_sbml_model(→ None)

Write cobra model to filename.

validate_sbml_model(...)

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

from_yaml(→ cobra.Model)

Load a cobra model from a YAML string.

load_yaml_model(→ cobra.Model)

Load a cobra model from a file in YAML format.

save_yaml_model(→ None)

Write the cobra model to a file in YAML format.

to_yaml(→ str)

Return the model as a YAML string.

load_model(→ cobra.core.Model)

Download an SBML model from a remote repository.

cobra.io.model_from_dict(obj: Dict) cobra.core.Model[source]

Build a cobra Model from a dictionary.

Models stored in JSON are first formulated as a dictionary that can be read to a cobra Model using this function.

Parameters

obj (dict) – A dictionary with keys: ‘genes’, ‘compartments’, ‘id’, ‘metabolites’, ‘notes’ and ‘reactions’; where ‘metabolites’, ‘genes’ and ‘metabolites’ are in turn lists of dictionaries holding all attributes to form the corresponding object.

Returns

The generated model.

Return type

cobra.Model

Raises

ValueError – If obj has no ‘reactions’ attribute.

See also

model_to_dict

Convert a cobra Model to a dictionary.

cobra.io.model_to_dict(model: cobra.core.Model, sort: bool = False) collections.OrderedDict[source]

Convert a cobra Model to a dictionary.

Parameters
  • model (cobra.Model) – The model to reformulate as a dict.

  • sort (bool, optional) – Whether to sort the metabolites, reactions, and genes or maintain the order defined in the model (default False).

Returns

A dictionary with keys: ‘genes’, ‘compartments’, ‘id’, ‘metabolites’, ‘notes’ and ‘reactions’; where ‘metabolites’, ‘genes’ and ‘metabolites’ are in turn lists of dictionaries holding all attributes to form the corresponding object.

Return type

OrderedDict

See also

model_from_dict

Convert a dictionary to a cobra Model.

cobra.io.from_json(document: str) cobra.Model[source]

Load a cobra model from a JSON string.

Parameters

document (str) – The JSON string representation of a cobra model.

Returns

The cobra model as interpreted from the JSON string.

Return type

cobra.Model

See also

load_json_model

Load directly from a file.

cobra.io.load_json_model(filename: Union[str, pathlib.Path, IO]) cobra.Model[source]

Load a cobra model from a file in JSON format.

Parameters

filename (str or file-like) – File path or descriptor that contains the JSON document describing the cobra model.

Returns

The cobra model as represented in the JSON document.

Return type

cobra.Model

See also

from_json

Load from a JSON string.

cobra.io.save_json_model(model: cobra.Model, filename: Union[str, pathlib.Path, IO], sort: bool = False, pretty: bool = False, **kwargs: Any) None[source]

Write the cobra model to a file in JSON format.

Parameters
  • model (cobra.Model) – The cobra model to represent.

  • filename (str or file-like) – File path or descriptor that the JSON representation should be written to.

  • sort (bool, optional) – Whether to sort the metabolites, reactions, and genes or maintain the order defined in the model (default False).

  • pretty (bool, optional) – Whether to format the JSON more compactly (default) or in a more verbose but easier to read fashion. Can be partially overwritten by the **kwargs (default False).

  • **kwargs (Any) – Keyword arguments passed to json.dump.

See also

to_json

Return a string representation.

json.dump

Base function.

cobra.io.to_json(model: cobra.Model, sort: bool = False, **kwargs: Any) str[source]

Return the model as a JSON string.

Parameters
  • model (cobra.Model) – The cobra model to represent.

  • sort (bool, optional) – Whether to sort the metabolites, reactions, and genes or maintain the order defined in the model (default False).

  • **kwargs (Any) – Keyword arguments passed on to json.dumps.

Returns

JSON string representation of the cobra model.

Return type

str

See also

save_json_model

Write directly to a file.

json.dumps

Base function.

cobra.io.load_matlab_model(infile_path: Union[str, pathlib.Path, IO], variable_name: Optional[str] = None, inf: float = np.inf) cobra.core.Model[source]

Load a cobra model stored as a .mat file.

Parameters
  • infile_path (str or Path or filehandle) – File path or descriptor of the .mat file describing the cobra model.

  • variable_name (str, optional) – The variable name of the model in the .mat file. If None, then the first MATLAB variable which looks like a COBRA model will be used (default None).

  • inf (float, optional) – The value to use for infinite bounds. Some solvers do not handle infinite values so for using those, set this to a high numeric value (default numpy.inf).

Returns

The cobra model as represented in the .mat file.

Return type

cobra.Model

Raises
  • ImportError – If scipy is not found in the Python environment.

  • IOError – If no COBRA model is found in the .mat file.

cobra.io.save_matlab_model(model: cobra.core.Model, file_name: Union[str, pathlib.Path, IO], varname: Optional[str] = None) None[source]

Save the cobra model as a .mat file.

This .mat file can be used directly in cobratoolbox.

Parameters
  • model (cobra.Model) – The cobra model to represent.

  • file_name (str or file-like or Path) – File path or descriptor that the MATLAB representation should be written to.

  • varname (str, optional) – The name of the variable within the MATLAB workspace. Model ID is used if available, else ‘exported_model’ is used (default None).

cobra.io.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

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

cobra.io.from_yaml(document: str) cobra.Model[source]

Load a cobra model from a YAML string.

Parameters

document (str) – The YAML string representation of a cobra model.

Returns

The cobra model as interpreted from the YAML document.

Return type

cobra.Model

See also

load_yaml_model

Load directly from a file.

cobra.io.load_yaml_model(filename: Union[str, pathlib.Path]) cobra.Model[source]

Load a cobra model from a file in YAML format.

Parameters

filename (str or file-like) – File path or descriptor that contains the YAML document describing the cobra model.

Returns

The cobra model as represented in the YAML document.

Return type

cobra.Model

See also

from_yaml

Load from a string.

cobra.io.save_yaml_model(model: cobra.Model, filename: str, sort: bool = False, **kwargs: Any) None[source]

Write the cobra model to a file in YAML format.

Parameters
  • model (cobra.Model) – The cobra model to represent.

  • filename (str or file-like) – File path or descriptor that the YAML representation should be written to.

  • sort (bool, optional) – Whether to sort the metabolites, reactions, and genes or maintain the order defined in the model (default False).

  • **kwargs (Any) – Keyword arguments passed to CobraYAML.dump.

See also

to_yaml

Return a string representation.

ruamel.yaml.dump

Base function.

cobra.io.to_yaml(model: cobra.Model, sort: bool = False, **kwargs: Any) str[source]

Return the model as a YAML string.

Parameters
  • model (cobra.Model) – The cobra model to represent.

  • sort (bool, optional) – Whether to sort the metabolites, reactions, and genes or maintain the order defined in the model (default False).

  • **kwargs (Any) – Keyword arguments passed on to CobraYAML.dump.

Returns

YAML string representation of the cobra model.

Return type

str

See also

save_yaml_model

Write directly to a file.

ruamel.yaml.dump

Base function.

class cobra.io.AbstractModelRepository(*, url: Union[httpx.URL, str], **kwargs)

Bases: abc.ABC

Define an abstract base class that describes a remote model repository.

name

The name of the remote repository.

Type

str

property url: httpx.URL

Return the repository’s URL.

_progress
name :str = Abstract
abstract get_sbml(model_id: str) bytes

Attempt to download an SBML document from the repository.

Parameters

model_id (str) – The identifier of the desired metabolic model. This is typically repository specific.

Returns

A gzip-compressed, UTF-8 encoded SBML document.

Return type

bytes

class cobra.io.BiGGModels(**kwargs)

Bases: cobra.io.web.abstract_model_repository.AbstractModelRepository

Define a concrete implementation of the BiGG Models repository.

name

The name of the BiGG Models repository.

Type

str

name :str = BiGG Models
get_sbml(model_id: str) bytes

Attempt to download an SBML document from the repository.

Parameters

model_id (str) – The identifier of the desired metabolic model. This is typically repository specific.

Returns

A gzip-compressed, UTF-8 encoded SBML document.

Return type

bytes

Raises

httpx.HTTPError – In case there are any connection problems.

class cobra.io.BioModels(**kwargs)

Bases: cobra.io.web.abstract_model_repository.AbstractModelRepository

Define a concrete implementation of the BioModels repository.

name

The name of the BioModels repository.

Type

str

name :str = BioModels
get_sbml(model_id: str) bytes

Attempt to download an SBML document from the repository.

Parameters

model_id (str) – The identifier of the desired metabolic model. This is typically repository specific.

Returns

A gzip-compressed, UTF-8 encoded SBML document.

Return type

bytes

Raises

httpx.HTTPError – In case there are any connection problems.

cobra.io.load_model(model_id: str, repositories: Iterable[cobra.io.web.abstract_model_repository.AbstractModelRepository] = DEFAULT_REPOSITORIES, cache: bool = True) cobra.core.Model

Download an SBML model from a remote repository.

Downloaded SBML documents are by default stored in a cache on disk such that future access is much faster. By default, models can be loaded from the following repositories:

  • BiGG Models

  • BioModels

You can use the AbstractModelRepository class as a parent to implement your own repository accessor which you pass to the load_model function. In case you implement a new interface, please consider submitting a pull request to COBRApy.

Parameters
  • model_id (str) – The identifier of the desired metabolic model. This is typically repository specific.

  • repositories (iterable, optional) – An iterable of repository accessor instances. The model_id is searched in order.

  • cache (bool, optional) – Whether or not to use the local caching mechanism (default yes).

Returns

A model instance generated from the SBML document.

Return type

Model

Raises

RuntimeError – As with any internet connection, there are multiple errors that can occur.

Examples

# Most of the time calling load_model with an identifier should be enough. >>> print(load_model(“e_coli_core”)) e_coli_core >>> print(load_model(“MODEL1510010000”)) MODEL1510010000

See also

BiGGModels, BioModels