cobra.io
========

.. py:module:: cobra.io

.. autoapi-nested-parse::

   Provide functions for loading and saving metabolic models.



Submodules
----------

.. toctree::
   :maxdepth: 1

   /autoapi/cobra/io/dict/index
   /autoapi/cobra/io/json/index
   /autoapi/cobra/io/mat/index
   /autoapi/cobra/io/sbml/index
   /autoapi/cobra/io/web/index
   /autoapi/cobra/io/yaml/index


Classes
-------

.. autoapisummary::

   cobra.io.AbstractModelRepository
   cobra.io.BiGGModels
   cobra.io.BioModels


Functions
---------

.. autoapisummary::

   cobra.io.model_from_dict
   cobra.io.model_to_dict
   cobra.io.from_json
   cobra.io.load_json_model
   cobra.io.save_json_model
   cobra.io.to_json
   cobra.io.load_matlab_model
   cobra.io.save_matlab_model
   cobra.io.read_sbml_model
   cobra.io.write_sbml_model
   cobra.io.validate_sbml_model
   cobra.io.from_yaml
   cobra.io.load_yaml_model
   cobra.io.save_yaml_model
   cobra.io.to_yaml
   cobra.io.load_model


Package Contents
----------------

.. py:function:: model_from_dict(obj: Dict) -> cobra.core.Model

   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.

   :param obj: 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.
   :type obj: dict

   :returns: The generated model.
   :rtype: cobra.Model

   :raises ValueError: If `obj` has no 'reactions' attribute.

   .. seealso::

      :py:obj:`model_to_dict`
          Convert a cobra Model to a dictionary.


.. py:function:: model_to_dict(model: cobra.core.Model, sort: bool = False) -> collections.OrderedDict

   Convert a cobra Model to a dictionary.

   :param model: The model to reformulate as a dict.
   :type model: cobra.Model
   :param sort: Whether to sort the metabolites, reactions, and genes or maintain the
                order defined in the model (default False).
   :type sort: bool, optional

   :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.
   :rtype: OrderedDict

   .. seealso::

      :py:obj:`model_from_dict`
          Convert a dictionary to a cobra Model.


.. py:function:: from_json(document: str) -> cobra.Model

   Load a cobra model from a JSON string.

   :param document: The JSON string representation of a cobra model.
   :type document: str

   :returns: The cobra model as interpreted from the JSON string.
   :rtype: cobra.Model

   .. seealso::

      :py:obj:`load_json_model`
          Load directly from a file.


.. py:function:: load_json_model(filename: Union[str, pathlib.Path, IO]) -> cobra.Model

   Load a cobra model from a file in JSON format.

   :param filename: File path or descriptor that contains the JSON document describing the
                    cobra model.
   :type filename: str or file-like

   :returns: The cobra model as represented in the JSON document.
   :rtype: cobra.Model

   .. seealso::

      :py:obj:`from_json`
          Load from a JSON string.


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

   Write the cobra model to a file in JSON format.

   :param model: The cobra model to represent.
   :type model: cobra.Model
   :param filename: File path or descriptor that the JSON representation should be
                    written to.
   :type filename: str or file-like
   :param sort: Whether to sort the metabolites, reactions, and genes or maintain the
                order defined in the model (default False).
   :type sort: bool, optional
   :param pretty: 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).
   :type pretty: bool, optional
   :param \*\*kwargs: Keyword arguments passed to `json.dump`.
   :type \*\*kwargs: Any

   .. seealso::

      :py:obj:`to_json`
          Return a string representation.

      :py:obj:`json.dump`
          Base function.


.. py:function:: to_json(model: cobra.Model, sort: bool = False, **kwargs: Any) -> str

   Return the model as a JSON string.

   :param model: The cobra model to represent.
   :type model: cobra.Model
   :param sort: Whether to sort the metabolites, reactions, and genes or maintain the
                order defined in the model (default False).
   :type sort: bool, optional
   :param \*\*kwargs: Keyword arguments passed on to `json.dumps`.
   :type \*\*kwargs: Any

   :returns: JSON string representation of the cobra model.
   :rtype: str

   .. seealso::

      :py:obj:`save_json_model`
          Write directly to a file.

      :py:obj:`json.dumps`
          Base function.


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

   Load a cobra model stored as a .mat file.

   :param infile_path: File path or descriptor of the .mat file describing the cobra model.
   :type infile_path: str or Path or filehandle
   :param variable_name: 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).
   :type variable_name: str, optional
   :param inf: 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`).
   :type inf: float, optional

   :returns: The cobra model as represented in the .mat file.
   :rtype: cobra.Model

   :raises ImportError: If scipy is not found in the Python environment.
   :raises IOError: If no COBRA model is found in the .mat file.


.. py:function:: save_matlab_model(model: cobra.core.Model, file_name: Union[str, pathlib.Path, IO], varname: Optional[str] = None) -> None

   Save the cobra model as a .mat file.

   This .mat file can be used directly in cobratoolbox.

   :param model: The cobra model to represent.
   :type model: cobra.Model
   :param file_name: File path or descriptor that the MATLAB representation should be
                     written to.
   :type file_name: str or file-like or Path
   :param varname: The name of the variable within the MATLAB workspace. Model ID is
                   used if available, else 'exported_model' is used (default None).
   :type varname: str, optional


.. py:function:: read_sbml_model(filename: Union[str, IO, pathlib.Path], number: Type = float, f_replace: dict = F_REPLACE, **kwargs) -> cobra.core.Model

   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.

   :param filename: SBML which is read into cobra model
   :type filename: path to SBML file, or SBML string, or SBML file handle
   :param number: In which data type should the stoichiometry be parsed.
   :type number: data type of stoichiometry: {float, int}
   :param f_replace: 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
   :type f_replace: dict of replacement functions for id replacement
   :param \*\*kwargs: Further keyword arguments are passed on to the called function (_sbml_to_model)

   :rtype: cobra.core.Model

   :raises IOError if file not read:
   :raises All other errors are wrapped around in a message pointing to SBML validator.:

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


.. py:function:: write_sbml_model(cobra_model: cobra.core.Model, filename: Union[str, IO, pathlib.Path], f_replace: dict = F_REPLACE, **kwargs) -> None

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

   :param cobra_model: Model instance which is written to SBML
   :type cobra_model: cobra.core.Model
   :param filename: path to which the model is written
   :type filename: string or filehandle
   :param f_replace: dictionary of replacement functions for id replacement
   :type f_replace: dict
   :param \*\*kwargs: Further keyword arguments are passed on.


.. py:function:: 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]

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

   :param filename: The filename (or SBML string) of the SBML model to be validated.
   :type filename: str or filehandle
   :param check_model: Whether to also check some basic model properties such as reaction
                       boundaries and compartment formulas.
   :type check_model: boolean {True, False}, default True
   :param internal_consistency: Check internal consistency (default True).
   :type internal_consistency: bool, optional
   :param check_units_consistency: Check consistency of units (default True).
   :type check_units_consistency: bool, optional
   :param check_modeling_practice: Check modeling practise (defualt True).
   :type check_modeling_practice: bool, optional
   :param \*\*kwargs: Further keyword arguments are passed on to the called function (_sbml_to_model).

   :returns: * *(model, errors)*
             * **model** (:class:`~cobra.core.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.

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


.. py:function:: from_yaml(document: str) -> cobra.Model

   Load a cobra model from a YAML string.

   :param document: The YAML string representation of a cobra model.
   :type document: str

   :returns: The cobra model as interpreted from the YAML document.
   :rtype: cobra.Model

   .. seealso::

      :py:obj:`load_yaml_model`
          Load directly from a file.


.. py:function:: load_yaml_model(filename: Union[str, pathlib.Path]) -> cobra.Model

   Load a cobra model from a file in YAML format.

   :param filename: File path or descriptor that contains the YAML document describing the
                    cobra model.
   :type filename: str or file-like

   :returns: The cobra model as represented in the YAML document.
   :rtype: cobra.Model

   .. seealso::

      :py:obj:`from_yaml`
          Load from a string.


.. py:function:: save_yaml_model(model: cobra.Model, filename: str, sort: bool = False, **kwargs: Any) -> None

   Write the cobra model to a file in YAML format.

   :param model: The cobra model to represent.
   :type model: cobra.Model
   :param filename: File path or descriptor that the YAML representation should be
                    written to.
   :type filename: str or file-like
   :param sort: Whether to sort the metabolites, reactions, and genes or maintain the
                order defined in the model (default False).
   :type sort: bool, optional
   :param \*\*kwargs: Keyword arguments passed to `CobraYAML.dump`.
   :type \*\*kwargs: Any

   .. seealso::

      :py:obj:`to_yaml`
          Return a string representation.

      :py:obj:`ruamel.yaml.dump`
          Base function.


.. py:function:: to_yaml(model: cobra.Model, sort: bool = False, **kwargs: Any) -> str

   Return the model as a YAML string.

   :param model: The cobra model to represent.
   :type model: cobra.Model
   :param sort: Whether to sort the metabolites, reactions, and genes or maintain the
                order defined in the model (default False).
   :type sort: bool, optional
   :param \*\*kwargs: Keyword arguments passed on to `CobraYAML.dump`.
   :type \*\*kwargs: Any

   :returns: YAML string representation of the cobra model.
   :rtype: str

   .. seealso::

      :py:obj:`save_yaml_model`
          Write directly to a file.

      :py:obj:`ruamel.yaml.dump`
          Base function.


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

   Bases: :py:obj:`abc.ABC`


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

   .. attribute:: name

      The name of the remote repository.

      :type: str


   .. py:attribute:: _progress


   .. py:attribute:: name
      :type:  str
      :value: 'Abstract'



   .. py:attribute:: _url


   .. py:property:: url
      :type: httpx.URL


      Return the repository's URL.


   .. py:method:: get_sbml(model_id: str) -> bytes
      :abstractmethod:


      Attempt to download an SBML document from the repository.

      :param model_id: The identifier of the desired metabolic model. This is typically repository
                       specific.
      :type model_id: str

      :returns: A gzip-compressed, UTF-8 encoded SBML document.
      :rtype: bytes



.. py:class:: BiGGModels(**kwargs)

   Bases: :py:obj:`cobra.io.web.abstract_model_repository.AbstractModelRepository`


   Define a concrete implementation of the BiGG Models repository.

   .. attribute:: name

      The name of the BiGG Models repository.

      :type: str


   .. py:attribute:: name
      :type:  str
      :value: 'BiGG Models'



   .. py:method:: get_sbml(model_id: str) -> bytes

      Attempt to download an SBML document from the repository.

      :param model_id: The identifier of the desired metabolic model. This is typically repository
                       specific.
      :type model_id: str

      :returns: A gzip-compressed, UTF-8 encoded SBML document.
      :rtype: bytes

      :raises httpx.HTTPError: In case there are any connection problems.



.. py:class:: BioModels(**kwargs)

   Bases: :py:obj:`cobra.io.web.abstract_model_repository.AbstractModelRepository`


   Define a concrete implementation of the BioModels repository.

   .. attribute:: name

      The name of the BioModels repository.

      :type: str


   .. py:attribute:: name
      :type:  str
      :value: 'BioModels'



   .. py:method:: get_sbml(model_id: str) -> bytes

      Attempt to download an SBML document from the repository.

      :param model_id: The identifier of the desired metabolic model. This is typically repository
                       specific.
      :type model_id: str

      :returns: A gzip-compressed, UTF-8 encoded SBML document.
      :rtype: bytes

      :raises httpx.HTTPError: In case there are any connection problems.



.. py:function:: 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.

   :param model_id: The identifier of the desired metabolic model. This is typically repository
                    specific.
   :type model_id: str
   :param repositories: An iterable of repository accessor instances. The model_id is searched in order.
   :type repositories: iterable, optional

   :returns: A model instance generated from the SBML document.
   :rtype: Model

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

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

   .. seealso:: :py:obj:`BiGGModels`, :py:obj:`BioModels`


