[med-svn] [python-cobra] 01/04: Imported Upstream version 0.5.9

Afif Elghraoui afif at moszumanska.debian.org
Wed Jan 25 09:26:31 UTC 2017


This is an automated email from the git hooks/post-receive script.

afif pushed a commit to branch master
in repository python-cobra.

commit ca2efe87100c25083c6ac1d70fdc5026f4ec22d9
Author: Afif Elghraoui <afif at debian.org>
Date:   Wed Jan 25 00:24:25 2017 -0800

    Imported Upstream version 0.5.9
---
 .travis.yml                       |   3 +-
 CONTRIBUTING.rst                  |  14 +++----
 INSTALL.rst                       |   4 +-
 appveyor.yml                      |   1 +
 appveyor/build_glpk.py            |   4 +-
 cobra/VERSION                     |   2 +-
 cobra/io/mat.py                   |  84 +++++++++++++++++++++++++++++---------
 cobra/io/sbml.py                  |  25 +++++++-----
 cobra/io/sbml3.py                 |   4 +-
 cobra/manipulation/delete.py      |  50 +++++++++++------------
 cobra/test/data/raven.mat         | Bin 0 -> 2519 bytes
 cobra/test/data/raven.pickle      | Bin 0 -> 11233 bytes
 cobra/test/data/update_pickles.py |   5 ++-
 cobra/test/test_io.py             |  37 ++++++++++-------
 cobra/test/test_manipulation.py   |  11 +++++
 15 files changed, 156 insertions(+), 88 deletions(-)

diff --git a/.travis.yml b/.travis.yml
index b3a5844..1a002b4 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -46,7 +46,6 @@ matrix:
         - MB_PYTHON_VERSION=3.5
 
 before_install:
-  - rvm get head
   - (git clone https://github.com/matthew-brett/multibuild.git && cd multibuild && git checkout ffe5995)
   # matplotlib non-compatible as testing runs in venv (non-framework)
   - TEST_DEPENDS="cython codecov coverage numpy scipy python-libsbml jsonschema six pytest pytest-cov pytest-benchmark pandas tabulate"
@@ -62,7 +61,7 @@ install:
   - build_wheel . $PLAT
 
 script:
-  - if [[ $TRAVIS_OS_NAME == "linux" ]]; then pip install pip --upgrade; pip install pep8; pep8 cobra --exclude=oven,solvers,sbml.py --show-source; fi
+  - if [[ $TRAVIS_OS_NAME == "linux" ]]; then pip install pip --upgrade; pip install 'sphinx>=1.5' rstcheck pep8; pep8 cobra --exclude=oven,solvers,sbml.py --show-source; rstcheck *.rst; fi
   - install_run $PLAT
 
 deploy:
diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst
index 39e544f..fc3e6b7 100644
--- a/CONTRIBUTING.rst
+++ b/CONTRIBUTING.rst
@@ -1,5 +1,3 @@
-.. Highlight:: shell
-
 ============
 Contributing
 ============
@@ -102,20 +100,20 @@ Here's how to set up `cobrapy` for local development to contribute smaller featu
 
    Now you can make your changes locally.
 
-5. When you are done making changes, check that your changes pass pep8
+9. When you are done making changes, check that your changes pass pep8
    and the tests with tox for the supported Python versions::
 
     (cobrapy)$ tox -e py27
     (cobrapy)$ tox -e py34
     (cobrapy)$ tox -e py35
 
-6. Commit your changes and push your branch to GitHub::
+10. Commit your changes and push your branch to GitHub::
 
     (cobrapy)$ git add .
     (cobrapy)$ git commit -m "Your detailed description of your changes."
     (cobrapy)$ git push origin name-of-your-bugfix-or-feature
 
-7. Submit a pull request through the GitHub website.
+11. Submit a pull request through the GitHub website.
 
 For larger features that you want to work on collaboratively with other cobrapy team members, you may consider to first request to join the cobrapy developers team to get write access to the repository so that you can create a branch in the main repository (or simply ask the maintainer to create a branch for you). Once you have a new branch you can push your changes directly to the main repository and when finished, submit a pull request from that branch to ``devel``.
 
@@ -194,12 +192,12 @@ Branching model
 
 Please use concise descriptive commit messages and consider using ``git pull --rebase`` when you update your own fork to avoid merge commits.
 
-5. Tests are in the ``cobra/test`` directory. They are automatically run
+1. Tests are in the ``cobra/test`` directory. They are automatically run
    through continuous integration services on both python 2 and python 3
    when pull requests are made.
-6. Please write tests for new functions. Writing documentation as well
+2. Please write tests for new functions. Writing documentation as well
    would also be very helpful.
-7. Ensure code will work with both python 2 and python 3. For example,
+3. Ensure code will work with both python 2 and python 3. For example,
    instead of ``my_dict.iteritems()`` use ``six.iteritems(my_dict)``
 
 Thank you very much for contributing to cobrapy!
diff --git a/INSTALL.rst b/INSTALL.rst
index fb43ae7..69fd03b 100644
--- a/INSTALL.rst
+++ b/INSTALL.rst
@@ -22,9 +22,9 @@ Instructions for several operating systems are below:
 Mac OS X or Linux
 -----------------
 
-0. `install
+1. `install
    pip <http://pip.readthedocs.org/en/latest/installing.html>`_.
-1. In a terminal, run ``sudo pip install cobra``
+2. In a terminal, run ``sudo pip install cobra``
 
 We highly recommend updating ``pip`` beforehand (``pip install pip --upgrade``).
 
diff --git a/appveyor.yml b/appveyor.yml
index bb0e64e..8fcedcb 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -45,6 +45,7 @@ cache:
 install:
   - "powershell appveyor\\install.ps1"
   - ps: Start-FileDownload 'https://bitbucket.org/gutworth/six/raw/default/six.py'
+  - "%PYTHON%/python -m pip install pip setuptools>=24.0 wheel --upgrade"
   - "%WITH_COMPILER% %PYTHON%/python appveyor/build_glpk.py"
   - "%PYTHON%/python -m pip install pip setuptools wheel --upgrade"
   - "%PYTHON%/python -m pip install --upgrade pytest"
diff --git a/appveyor/build_glpk.py b/appveyor/build_glpk.py
index 1e9dfe1..ab05865 100644
--- a/appveyor/build_glpk.py
+++ b/appveyor/build_glpk.py
@@ -4,7 +4,7 @@ import hashlib
 import tarfile
 import struct
 import shutil
-import setuptools.msvc9_support
+import setuptools.msvc
 try:
     import urllib2
 except ImportError:  # python 3
@@ -35,7 +35,7 @@ def get_vcvarsall_cmd():
         vc_ver = 10
     else:
         vc_ver = 9
-    vc_path = setuptools.msvc9_support.find_vcvarsall(vc_ver)
+    vc_path = setuptools.msvc.msvc9_find_vcvarsall(vc_ver)
     assert vc_path is not None
     return '"%s" %s' % (vc_path, " amd64" if bitness == 64 else "")
 
diff --git a/cobra/VERSION b/cobra/VERSION
index 659914a..416bfb0 100644
--- a/cobra/VERSION
+++ b/cobra/VERSION
@@ -1 +1 @@
-0.5.8
+0.5.9
diff --git a/cobra/io/mat.py b/cobra/io/mat.py
index 801c551..37a7e33 100644
--- a/cobra/io/mat.py
+++ b/cobra/io/mat.py
@@ -2,7 +2,7 @@ import re
 from uuid import uuid4
 from warnings import warn
 
-from numpy import array, object as np_object
+from numpy import isinf, inf, array, object as np_object
 from scipy.io import loadmat, savemat
 from scipy.sparse import coo_matrix, dok_matrix
 
@@ -15,12 +15,13 @@ try:
     # if scipy version is earlier than 0.11, OrderedDict will not work, so use
     # a dict instead
     if scipy_version < 11:
-        dicttype = dict
+        DictClass = dict
     else:
-        from collections import OrderedDict as dicttype
+        from collections import OrderedDict as DictClass
     del short_version, scipy_version
 except ImportError:
-    dicttype = dict
+    DictClass = dict
+    short_version = None
 
 
 # precompiled regular expressions
@@ -28,7 +29,7 @@ _bracket_re = re.compile("r\[[a-z]\]$")
 _underscore_re = re.compile(r"_[a-z]$")
 
 
-def _get_id_comparment(id):
+def _get_id_compartment(id):
     """extract the compartment from the id string"""
     bracket_search = _bracket_re.findall(id)
     if len(bracket_search) == 1:
@@ -45,18 +46,29 @@ def _cell(x):
     return array(x_no_none, dtype=np_object)
 
 
-def load_matlab_model(infile_path, variable_name=None):
+def load_matlab_model(infile_path, variable_name=None, inf=inf):
     """Load a cobra model stored as a .mat file
 
-    infile_path : str
-
-    variable_name : str, optional
+    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
+    -------
+    cobra.core.Model.Model:
+        The resulting cobra model
 
     """
     data = loadmat(infile_path)
+    possible_names = []
     if variable_name is None:
         # skip meta variables
         meta_vars = {"__globals__", "__header__", "__version__"}
@@ -64,14 +76,16 @@ def load_matlab_model(infile_path, variable_name=None):
         if len(possible_names) == 1:
             variable_name = possible_names[0]
     if variable_name is not None:
-        return from_mat_struct(data[variable_name], model_id=variable_name)
+        return from_mat_struct(data[variable_name], model_id=variable_name,
+                               inf=inf)
     for possible_name in possible_names:
         try:
-            return from_mat_struct(data[possible_name], model_id=possible_name)
+            return from_mat_struct(data[possible_name], model_id=possible_name,
+                                   inf=inf)
         except ValueError:
-            None
+            pass
     # If code here is executed, then no model was found.
-    raise Exception("no COBRA model found")
+    raise IOError("no COBRA model found")
 
 
 def save_matlab_model(model, file_name, varname=None):
@@ -93,13 +107,22 @@ def save_matlab_model(model, file_name, varname=None):
             appendmat=True, oned_as="column")
 
 
+def create_mat_metabolite_id(model):
+    for met in model.metabolites:
+        if not _get_id_compartment(met.id) and met.compartment:
+            yield '{}[{}]'.format(met.id,
+                                  model.compartments[met.compartment].lower())
+        else:
+            yield met.id
+
+
 def create_mat_dict(model):
     """create a dict mapping model attributes to arrays"""
-    model = model.to_array_based_model()
+    model = model.to_array_based_model(deepcopy_model=True)
     rxns = model.reactions
     mets = model.metabolites
-    mat = dicttype()
-    mat["mets"] = _cell(mets.list_attr("id"))
+    mat = DictClass()
+    mat["mets"] = _cell([met_id for met_id in create_mat_metabolite_id(model)])
     mat["metNames"] = _cell(mets.list_attr("name"))
     mat["metFormulas"] = _cell([str(m.formula) for m in mets])
     try:
@@ -133,7 +156,7 @@ def create_mat_dict(model):
     return mat
 
 
-def from_mat_struct(mat_struct, model_id=None):
+def from_mat_struct(mat_struct, model_id=None, inf=inf):
     """create a model from the COBRA toolbox struct
 
     The struct will be a dict read in by scipy.io.loadmat
@@ -142,7 +165,7 @@ def from_mat_struct(mat_struct, model_id=None):
     m = mat_struct
     if m.dtype.names is None:
         raise ValueError("not a valid mat struct")
-    if not set(["rxns", "mets", "S", "lb", "ub"]) <= set(m.dtype.names):
+    if not {"rxns", "mets", "S", "lb", "ub"} <= set(m.dtype.names):
         raise ValueError("not a valid mat struct")
     if "c" in m.dtype.names:
         c_vec = m["c"][0, 0]
@@ -151,7 +174,12 @@ def from_mat_struct(mat_struct, model_id=None):
         warn("objective vector 'c' not found")
     model = Model()
     if "description" in m.dtype.names:
-        model.id = m["description"][0, 0][0]
+        description = m["description"][0, 0][0]
+        if len(description) > 1:
+            model.id = description[0]
+            warn("Several IDs detected, only using the first.")
+        else:
+            model.id = description
     elif model_id is not None:
         model.id = model_id
     else:
@@ -159,7 +187,19 @@ def from_mat_struct(mat_struct, model_id=None):
     for i, name in enumerate(m["mets"][0, 0]):
         new_metabolite = Metabolite()
         new_metabolite.id = str(name[0][0])
-        new_metabolite.compartment = _get_id_comparment(new_metabolite.id)
+        if all(var in m.dtype.names for var in
+               ['metComps', 'comps', 'compNames']):
+            comp_index = m["metComps"][0, 0][i][0] - 1
+            new_metabolite.compartment = m['comps'][0, 0][comp_index][0][0]
+            if new_metabolite.compartment not in model.compartments:
+
+                comp_name = m['compNames'][0, 0][comp_index][0][0]
+                model.compartments[new_metabolite.compartment] = comp_name
+        else:
+            new_metabolite.compartment = _get_id_compartment(new_metabolite.id)
+            if new_metabolite.compartment not in model.compartments:
+                model.compartments[
+                    new_metabolite.compartment] = new_metabolite.compartment
         try:
             new_metabolite.name = str(m["metNames"][0, 0][i][0][0])
         except (IndexError, ValueError):
@@ -182,6 +222,10 @@ def from_mat_struct(mat_struct, model_id=None):
         new_reaction.id = str(name[0][0])
         new_reaction.lower_bound = float(m["lb"][0, 0][i][0])
         new_reaction.upper_bound = float(m["ub"][0, 0][i][0])
+        if isinf(new_reaction.lower_bound) and new_reaction.lower_bound < 0:
+            new_reaction.lower_bound = -inf
+        if isinf(new_reaction.upper_bound) and new_reaction.upper_bound > 0:
+            new_reaction.upper_bound = inf
         if c_vec is not None:
             new_reaction.objective_coefficient = float(c_vec[i][0])
         try:
diff --git a/cobra/io/sbml.py b/cobra/io/sbml.py
index 5a9bf30..a3bdf7c 100644
--- a/cobra/io/sbml.py
+++ b/cobra/io/sbml.py
@@ -38,7 +38,7 @@ def parse_legacy_id(the_id, the_compartment=None, the_type='metabolite',
     the_type: String.  Currently only 'metabolite' is supported
 
     use_hyphens:   Boolean.  If True, double underscores (__) in an SBML ID will be converted to hyphens
-    
+
     """
     if use_hyphens:
         the_id = the_id.replace('__','-')
@@ -150,6 +150,9 @@ def create_cobra_model_from_sbml_file(sbml_filename, old_sbml=False, legacy_meta
             else:
                 if tmp_metabolite.charge is None or tmp_metabolite.charge == note_charge:
                     tmp_metabolite.notes.pop("CHARGE")
+                    # set charge to the one from notes if not assigend before
+                    # the same
+                    tmp_metabolite.charge = note_charge
                 else:  # tmp_metabolite.charge != note_charge
                     msg = "different charges specified for %s (%d and %d)"
                     msg = msg % (tmp_metabolite.id, tmp_metabolite.charge, note_charge)
@@ -221,7 +224,7 @@ def create_cobra_model_from_sbml_file(sbml_filename, old_sbml=False, legacy_meta
         #they override the sbml reversible attribute.  If they are not
         #specified then the bounds are determined by getReversible.
         if not sbml_reaction.getKineticLaw():
-            
+
             if sbml_reaction.getReversible():
                 parameter_dict['lower_bound'] = __default_lower_bound
                 parameter_dict['upper_bound'] = __default_upper_bound
@@ -229,7 +232,7 @@ def create_cobra_model_from_sbml_file(sbml_filename, old_sbml=False, legacy_meta
                 #Assume that irreversible reactions only proceed from left to right.
                 parameter_dict['lower_bound'] = 0
                 parameter_dict['upper_bound'] = __default_upper_bound
-                
+
             parameter_dict['objective_coefficient'] = __default_objective_coefficient
         else:
             for sbml_parameter in sbml_reaction.getKineticLaw().getListOfParameters():
@@ -295,7 +298,7 @@ def create_cobra_model_from_sbml_file(sbml_filename, old_sbml=False, legacy_meta
                     tmp_locus_id = tmp_row_dict['LOCUS']
                     if 'TRANSCRIPT' in tmp_row_dict:
                         tmp_locus_id = tmp_locus_id + '.' + tmp_row_dict['TRANSCRIPT']
-                    
+
                     if 'ABBREVIATION' in tmp_row_dict:
                         gene_id_to_object[tmp_locus_id].name = tmp_row_dict['ABBREVIATION']
 
@@ -343,7 +346,7 @@ def parse_legacy_sbml_notes(note_string, note_delimiter = ':'):
 
     if 'CHARGE' in note_dict and note_dict['CHARGE'][0].lower() in ['none', 'na', 'nan']:
         note_dict.pop('CHARGE') #Remove non-numeric charges
-        
+
     return(note_dict)
 
 def write_cobra_model_to_sbml_file(cobra_model, sbml_filename,
@@ -370,7 +373,7 @@ def write_cobra_model_to_sbml_file(cobra_model, sbml_filename,
 
     """
 
-    sbml_doc = get_libsbml_document(cobra_model, 
+    sbml_doc = get_libsbml_document(cobra_model,
                                    sbml_level=sbml_level, sbml_version=sbml_version,
                                    print_time=print_time,
                                    use_fbc_package=use_fbc_package)
@@ -388,8 +391,8 @@ def get_libsbml_document(cobra_model,
     note_start_tag, note_end_tag = '<p>', '</p>'
     if sbml_level > 2 or (sbml_level == 2 and sbml_version == 4):
         note_start_tag, note_end_tag = '<html:p>', '</html:p>'
-        
-    
+
+
     sbml_doc = SBMLDocument(sbml_level, sbml_version)
     sbml_model = sbml_doc.createModel(cobra_model.id.split('.')[0])
     #Note need to set units
@@ -412,7 +415,7 @@ def get_libsbml_document(cobra_model,
     if not cobra_model.compartments:
         cobra_model.compartments = {'c': 'cytosol',
                                     'p': 'periplasm',
-                                    'e': 'extracellular'}    
+                                    'e': 'extracellular'}
     for the_key in cobra_model.compartments.keys():
         sbml_comp = sbml_model.createCompartment()
         sbml_comp.setId(the_key)
@@ -481,7 +484,7 @@ def get_libsbml_document(cobra_model,
             species_reference.setId(metabolite_id + '_' + the_reaction_id)
             species_reference.setSpecies(metabolite_id)
             species_reference.setStoichiometry(abs(sbml_stoichiometry))
-            
+
         #Add in the kineticLaw
         sbml_law = KineticLaw(sbml_level, sbml_version)
         if hasattr(sbml_law, 'setId'):
@@ -508,6 +511,8 @@ def get_libsbml_document(cobra_model,
         #If they are not identical, they are set to be identical
         note_dict = the_reaction.notes.copy()
         if the_reaction.gene_reaction_rule:
+            if 'GENE ASSOCIATION' in note_dict:
+                del note_dict['GENE ASSOCIATION']
             note_dict['GENE_ASSOCIATION'] = [str(the_reaction.gene_reaction_rule)]
         if the_reaction.subsystem:
             note_dict['SUBSYSTEM'] = [str(the_reaction.subsystem)]
diff --git a/cobra/io/sbml3.py b/cobra/io/sbml3.py
index 23ffe22..c08f433 100644
--- a/cobra/io/sbml3.py
+++ b/cobra/io/sbml3.py
@@ -441,10 +441,10 @@ def model_to_xml(cobra_model, units=True):
             return param_id
 
     # add in compartments
-    compartmenst_list = SubElement(xml_model, "listOfCompartments")
+    compartments_list = SubElement(xml_model, "listOfCompartments")
     compartments = cobra_model.compartments
     for compartment, name in iteritems(compartments):
-        SubElement(compartmenst_list, "compartment", id=compartment, name=name,
+        SubElement(compartments_list, "compartment", id=compartment, name=name,
                    constant="true")
 
     # add in metabolites
diff --git a/cobra/manipulation/delete.py b/cobra/manipulation/delete.py
index b2178c3..93aa8e4 100644
--- a/cobra/manipulation/delete.py
+++ b/cobra/manipulation/delete.py
@@ -1,56 +1,54 @@
-import re
-from copy import deepcopy
-from warnings import warn
 from ast import NodeTransformer, And
 
 from six import iteritems, string_types
 
-from ..core.Gene import eval_gpr, parse_gpr, ast2str
+from cobra.core.Gene import eval_gpr, parse_gpr, ast2str
 
 
 def prune_unused_metabolites(cobra_model):
-    """Removes metabolites that aren't involved in any reactions in the model
+    """Remove metabolites that are not involved in any reactions
 
-    cobra_model: A Model object.
+    Parameters
+    ----------
+    cobra_model: cobra.core.Model
+        the model to remove unused metabolites from
 
+    Returns
+    -------
+    list
+        list of metabolites that were removed
     """
     inactive_metabolites = []
     active_metabolites = []
     for the_metabolite in cobra_model.metabolites:
         if len(the_metabolite._reaction) == 0:
-            the_metabolite.remove_from_model(cobra_model)
+            the_metabolite.remove_from_model()
             inactive_metabolites.append(the_metabolite)
         else:
             active_metabolites.append(the_metabolite)
-    if inactive_metabolites:
-        return inactive_metabolites
-    else:
-        warn('All metabolites used in at least 1 reaction')
+    return inactive_metabolites
 
 
 def prune_unused_reactions(cobra_model):
-    """Removes reactions from cobra_model.
-
-    cobra_model: A Model object.
+    """Remove reactions that have no assigned metabolites
 
-    reactions_to_prune: None, a string matching a reaction.id, a
-    cobra.Reaction, or as list of the ids / Reactions to remove from
-    cobra_model.  If None then the function will delete reactions that have no
-    active metabolites in the model.
+    Parameters
+    ----------
+    cobra_model: cobra.core.Model
+        the model to remove unused reactions from
 
+    Returns
+    -------
+    list
+        list of reactions that were removed
     """
     pruned_reactions = []
     reactions_to_prune = [x for x in cobra_model.reactions
                           if len(x._metabolites) == 0]
     for the_reaction in reactions_to_prune:
-        try:
-            the_reaction.remove_from_model(cobra_model)
-            pruned_reactions.append(the_reaction)
-        except:
-            warn('%s not in %s' % (the_reaction.id, cobra_model.id))
-    if not pruned_reactions:
-        warn('All reactions have at least 1 metabolite')
-        return
+        the_reaction.remove_from_model()
+        pruned_reactions.append(the_reaction)
+    return pruned_reactions
 
 
 def undelete_model_genes(cobra_model):
diff --git a/cobra/test/data/raven.mat b/cobra/test/data/raven.mat
new file mode 100644
index 0000000..ff8a741
Binary files /dev/null and b/cobra/test/data/raven.mat differ
diff --git a/cobra/test/data/raven.pickle b/cobra/test/data/raven.pickle
new file mode 100644
index 0000000..8391da9
Binary files /dev/null and b/cobra/test/data/raven.pickle differ
diff --git a/cobra/test/data/update_pickles.py b/cobra/test/data/update_pickles.py
index 6225775..8ea205e 100755
--- a/cobra/test/data/update_pickles.py
+++ b/cobra/test/data/update_pickles.py
@@ -12,7 +12,7 @@ from collections import OrderedDict
 import cobra
 from cobra.version import get_version
 from cobra.io import read_sbml_model, write_sbml_model, save_matlab_model, \
-    save_json_model
+    save_json_model, load_matlab_model
 from cobra.io.sbml3 import write_sbml2
 
 # ecoli
@@ -81,6 +81,9 @@ write_sbml_model(mini, "mini_fbc2.xml.bz2")
 write_sbml_model(mini, "mini_fbc2.xml.gz")
 write_sbml2(mini, "mini_fbc1.xml", use_fbc_package=True)
 write_sbml_model(mini, "mini_cobra.xml", use_fbc_package=False)
+raven = load_matlab_model("raven.mat")
+with open("raven.pickle", "wb") as outfile:
+    dump(raven, outfile, protocol=2)
 
 # fva results
 fva_result = cobra.flux_analysis.flux_variability_analysis(textbook)
diff --git a/cobra/test/test_io.py b/cobra/test/test_io.py
index 4649a52..b2c7ad0 100644
--- a/cobra/test/test_io.py
+++ b/cobra/test/test_io.py
@@ -82,6 +82,9 @@ trials = [IOTrial('fbc2', 'mini.pickle', 'mini_fbc2.xml',
           pytest.mark.skipif("not scipy")(
               IOTrial('mat', 'mini.pickle', 'mini.mat',
                       io.load_matlab_model, io.save_matlab_model, None)),
+          pytest.mark.skipif("not scipy")(
+              IOTrial('raven-mat', 'raven.pickle', 'raven.mat',
+                      io.load_matlab_model, io.save_matlab_model, None)),
           IOTrial('json', 'mini.pickle', 'mini.json',
                   io.load_json_model, io.save_json_model, validate_json),
           IOTrial('pickle', 'mini.pickle', 'mini.pickle',
@@ -118,21 +121,21 @@ class TestCobraIO:
                      "objective_coefficient", "gene_reaction_rule"):
             assert getattr(model1.reactions[0], attr) == getattr(
                 model2.reactions[0], attr)
-            assert getattr(model1.reactions[10], attr) == getattr(
-                model2.reactions[10], attr)
+            assert getattr(model1.reactions[5], attr) == getattr(
+                model2.reactions[5], attr)
             assert getattr(model1.reactions[-1], attr) == getattr(
                 model2.reactions[-1], attr)
         for attr in ("id", "name", "compartment", "formula", "charge"):
             assert getattr(model1.metabolites[0], attr) == getattr(
                 model2.metabolites[0], attr)
-            assert getattr(model1.metabolites[10], attr) == getattr(
-                model2.metabolites[10], attr)
+            assert getattr(model1.metabolites[5], attr) == getattr(
+                model2.metabolites[5], attr)
             assert getattr(model1.metabolites[-1], attr) == getattr(
                 model2.metabolites[-1], attr)
         assert len(model1.reactions[0].metabolites) == len(
             model2.reactions[0].metabolites)
-        assert len(model1.reactions[14].metabolites) == len(
-            model2.reactions[14].metabolites)
+        assert len(model1.reactions[8].metabolites) == len(
+            model2.reactions[8].metabolites)
         assert len(model1.reactions[-1].metabolites) == len(
             model2.reactions[-1].metabolites)
         assert len(model1.genes) == len(model2.genes)
@@ -141,21 +144,17 @@ class TestCobraIO:
         model2.optimize()
         assert abs(model1.solution.f - model2.solution.f) < 0.001
         # ensure the references are correct
-        if name == 'mat':
-            pytest.xfail('curiously, reference check now fail with matlab')
         assert model2.metabolites[0]._model is model2
         assert model2.reactions[0]._model is model2
         assert model2.genes[0]._model is model2
 
     @classmethod
     def extra_comparisons(cls, name, model1, model2):
-        if name in ['fbc1', 'mat', 'cobra']:
-            pytest.skip("not supported")
         assert model1.compartments == model2.compartments
         assert model1.metabolites[4].annotation == model2.metabolites[
             4].annotation
         assert model1.reactions[4].annotation == model2.reactions[4].annotation
-        assert model1.genes[4].annotation == model2.genes[4].annotation
+        assert model1.genes[5].annotation == model2.genes[5].annotation
         for attr in ("id", "name"):
             assert getattr(model1.genes[0], attr) == getattr(model2.genes[0],
                                                              attr)
@@ -164,18 +163,28 @@ class TestCobraIO:
             assert getattr(model1.genes[-1], attr) == getattr(model2.genes[-1],
                                                               attr)
 
-    def test_read(self, io_trial):
+    def test_read_1(self, io_trial):
         name, reference_model, test_model, _ = io_trial
         if name in ['fbc1']:
             pytest.xfail('not supported')
         self.compare_models(name, reference_model, test_model)
+
+    def test_read_2(self, io_trial):
+        name, reference_model, test_model, _ = io_trial
+        if name in ['fbc1', 'mat', 'cobra', 'raven-mat']:
+            pytest.xfail('not supported')
         self.extra_comparisons(name, reference_model, test_model)
 
-    def test_write(self, io_trial):
+    def test_write_1(self, io_trial):
         name, _, test_model, reread_model = io_trial
-        if name in ['fbc1']:
+        if name in ['fbc1', 'raven-mat']:
             pytest.xfail('not supported')
         self.compare_models(name, test_model, reread_model)
+
+    def test_write_2(self, io_trial):
+        name, _, test_model, reread_model = io_trial
+        if name in ['fbc1', 'mat', 'cobra', 'raven-mat']:
+            pytest.xfail('not supported')
         self.extra_comparisons(name, test_model, reread_model)
 
 
diff --git a/cobra/test/test_manipulation.py b/cobra/test/test_manipulation.py
index 6bafd08..b77963a 100644
--- a/cobra/test/test_manipulation.py
+++ b/cobra/test/test_manipulation.py
@@ -242,3 +242,14 @@ class TestManipulation:
         r1.add_metabolites({m1: 1})
         with pytest.raises(ValueError):
             r1.check_mass_balance()
+
+    def test_prune_unused(self, model):
+        metabolite = model.metabolites.ru5p__D_c
+        [model.reactions.get_by_id(x).remove_from_model() for x in
+         ['RPI', 'RPE', 'GND']]
+        unused = delete.prune_unused_metabolites(model)
+        assert unused[0] is metabolite
+        reaction = Reaction('foo')
+        model.add_reaction(reaction)
+        unused = delete.prune_unused_reactions(model)
+        assert unused[0] is reaction

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-med/python-cobra.git



More information about the debian-med-commit mailing list