# 17.1.1.3. cobra.io¶

## 17.1.1.3.3. Package Contents¶

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

### 17.1.1.3.3.2. Functions¶

 Build a model from a dict. model_to_dict(model, sort=False) Convert model to a dict. from_json(document) Load a cobra model from a JSON document. load_json_model(filename) Load a cobra model from a file in JSON format. save_json_model(model, filename, sort=False, pretty=False, **kwargs) Write the cobra model to a file in JSON format. to_json(model, sort=False, **kwargs) Return the model as a JSON document. load_matlab_model(infile_path, variable_name=None, inf=inf) Load a cobra model stored as a .mat file. save_matlab_model(model, file_name, varname=None) Save the cobra model as a .mat file. read_sbml_model(filename, number=float, f_replace=F_REPLACE, **kwargs) Reads SBML model from given filename. write_sbml_model(cobra_model, filename, f_replace=F_REPLACE, **kwargs) Writes cobra model to filename. validate_sbml_model(filename, check_model=True, internal_consistency=True, check_units_consistency=False, check_modeling_practice=False, **kwargs) Validate SBML model and returns the model along with a list of errors. from_yaml(document) Load a cobra model from a YAML document. load_yaml_model(filename) Load a cobra model from a file in YAML format. save_yaml_model(model, filename, sort=False, **kwargs) Write the cobra model to a file in YAML format. to_yaml(model, sort=False, **kwargs) Return the model as a YAML document. load_model(model_id: str, repositories: Iterable[AbstractModelRepository] = (BiGGModels(), BioModels()), cache: bool = True) → ‘Model’ Download an SBML model from a remote repository.
cobra.io.model_from_dict(obj)[source]

Build a model from a dict.

Models stored in json are first formulated as a dict that can be read to cobra model using this function.

Parameters

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

Returns

The generated model.

Return type

cora.core.Model

cobra.io.model_to_dict(model, sort=False)[source]

Convert model to a dict.

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.

Returns

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

Return type

OrderedDict

cobra.io.from_json(document)[source]

Load a cobra model from a JSON document.

Parameters

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

Returns

The cobra model as represented in the JSON document.

Return type

cobra.Model

load_json_model()

cobra.io.load_json_model(filename)[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

from_json()

cobra.io.save_json_model(model, filename, sort=False, pretty=False, **kwargs)[source]

Write the cobra model to a file in JSON format.

kwargs are passed on to json.dump.

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.

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

to_json()

Return a string representation.

json.dump()

Base function.

cobra.io.to_json(model, sort=False, **kwargs)[source]

Return the model as a JSON document.

kwargs are passed on to json.dumps.

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.

Returns

String representation of the cobra model as a JSON document.

Return type

str

save_json_model()

Write directly to a file.

json.dumps()

Base function.

cobra.io.load_matlab_model(infile_path, variable_name=None, inf=inf)[source]

Load a cobra model stored as a .mat file.

Parameters
• infile_path (str) – path to the file to to read

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

• inf (value) – 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.

Returns

The resulting cobra model

Return type

cobra.core.Model.Model

cobra.io.save_matlab_model(model, file_name, varname=None)[source]

Save the cobra model as a .mat file.

This .mat file can be used directly in the MATLAB version of COBRA.

Parameters
• model (cobra.core.Model.Model object) – The model to save

• file_name (str or file-like object) – The file to save to

• varname (string) – The name of the variable within the workspace

cobra.io.read_sbml_model(filename, number=float, f_replace=F_REPLACE, **kwargs)[source]

Reads 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

Returns

Return type

cobra.core.Model

Notes

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

File handles to compressed files are not supported yet.

cobra.io.write_sbml_model(cobra_model, filename, f_replace=F_REPLACE, **kwargs)[source]

Writes 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) – path to which the model is written

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

cobra.io.validate_sbml_model(filename, check_model=True, internal_consistency=True, check_units_consistency=False, check_modeling_practice=False, **kwargs)[source]

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

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

• internal_consistency (boolean {True, False}) – Check internal consistency.

• check_units_consistency (boolean {True, False}) – Check consistency of units.

• check_modeling_practice (boolean {True, False}) – Check modeling practise.

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

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.

Raises
cobra.io.from_yaml(document)[source]

Load a cobra model from a YAML document.

Parameters

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

Returns

The cobra model as represented in the YAML document.

Return type

cobra.Model

load_yaml_model()

cobra.io.load_yaml_model(filename)[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

from_yaml()

cobra.io.save_yaml_model(model, filename, sort=False, **kwargs)[source]

Write the cobra model to a file in YAML format.

kwargs are passed on to yaml.dump.

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.

to_yaml()

Return a string representation.

ruamel.yaml.dump()

Base function.

cobra.io.to_yaml(model, sort=False, **kwargs)[source]

Return the model as a YAML document.

kwargs are passed on to yaml.dump.

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.

Returns

String representation of the cobra model as a YAML document.

Return type

str

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

_progress
name :str = Abstract
property url(self) → httpx.URL

Return the repository’s URL.

abstract get_sbml(self, model_id: str) → bytes

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)

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(self, model_id: str) → bytes

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)

Define a concrete implementation of the BioModels repository.

name

The name of the BioModels repository.

Type

str

name :str = BioModels
get_sbml(self, model_id: str) → bytes

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[AbstractModelRepository] = (BiGGModels(), BioModels()), cache: bool = True) → 'Model'

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