[med-svn] [python-cobra] 01/06: Imported Upstream version 0.4.0b3

Afif Elghraoui afif-guest at moszumanska.debian.org
Sat Aug 29 05:30:50 UTC 2015


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

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

commit 4677731652a4573ea930a36777a7edbafd02a785
Author: Afif Elghraoui <afif at ghraoui.name>
Date:   Fri Aug 28 21:47:52 2015 -0700

    Imported Upstream version 0.4.0b3
---
 .travis.yml                                  | 25 ++++++---
 INSTALL.md                                   | 33 ++++++------
 README.md                                    |  5 ++
 cobra/VERSION                                |  2 +-
 cobra/flux_analysis/deletion_worker.py       |  2 +-
 cobra/flux_analysis/phenotype_phase_plane.py | 26 ++++------
 cobra/io/__init__.py                         | 27 ++++------
 cobra/io/mat.py                              |  3 +-
 cobra/solvers/cglpk.pyx                      | 76 +++++++++++++++-------------
 cobra/test/__init__.py                       |  5 +-
 cobra/test/flux_analysis.py                  |  9 ++++
 setup.py                                     | 12 +++--
 12 files changed, 129 insertions(+), 96 deletions(-)

diff --git a/.travis.yml b/.travis.yml
index fe99e32..3b51629 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -6,19 +6,32 @@ cache:
 python:
   - "2.7"
   - "3.4"
+addons:
+  apt:
+    packages:
+      - gfortran
+      - libatlas-dev
+      - libatlas-base-dev
+      - liblapack-dev
+      - libgmp-dev
+      - libglpk-dev
+      - libmpfr-dev
+
 # command to install dependencies
 env:
   - PIP_CACHE_DIR=$HOME/.cache/pip
 before_install:
   - pip install pip --upgrade
   - export PIP_OPTS="-f https://opencobra.github.io/pypi_cobrapy_travis --no-index"
-  - pip install cython coveralls  # these guys get cached
-  - if [[ $TRAVIS_PYTHON_VERSION == 2* ]]; then pip install lxml; fi # cached
-  - pip install numpy scipy python-libsbml-experimental $PIP_OPTS  # download wheels
+  # These get cached
+  - pip install numpy scipy python-libsbml -v  # verbose for long-running compiles
+  - pip install cython coveralls jsonschema six
+  - if [[ $TRAVIS_PYTHON_VERSION == 2* ]]; then pip install lxml; fi
+  # These use pre-compiled wheels (defined in PIP_OPTS)
   - if [[ $TRAVIS_PYTHON_VERSION == 2* ]]; then pip install glpk cylp $PIP_OPTS; fi
-  - wget https://opencobra.github.io/pypi_cobrapy_travis/travis_test_dependencies.zip  # esolver, and glpk
-  - unzip travis_test_dependencies.zip
-  - export PATH=$PATH:$PWD
+  # Download esolver and add it to the path
+  - wget https://opencobra.github.io/pypi_cobrapy_travis/esolver.gz
+  - gzip -d esolver.gz; chmod +x esolver; export PATH=$PATH:$PWD
 install:
   - python setup.py develop
 # # command to run tests
diff --git a/INSTALL.md b/INSTALL.md
index 5b5ea8e..8839752 100644
--- a/INSTALL.md
+++ b/INSTALL.md
@@ -1,8 +1,9 @@
-For installation help, please use the [Google Group]
-(http://groups.google.com/group/cobra-pie).
+#Installation of cobrapy
 
+For installation help, please use the
+[Google Group](http://groups.google.com/group/cobra-pie).
 For usage instructions, please see the 
-[documentation](https://cobrapy.readthedocs.org/en/latest/)
+[documentation](https://cobrapy.readthedocs.org/en/latest/).
 
 --------------------------------------------------------------------------------
 
@@ -11,18 +12,18 @@ Mac OS X (10.7+) and Ubuntu ship with Python. Windows users without python
 can download and install python from the [python 
 website](https://www.python.org/ftp/python/2.7.9/python-2.7.9.amd64.msi).
 Please note that though Anaconda and other python distributions may work with
-cobrapy, they are not explicitly supported at this time.
-
-
-#Installation of cobrapy
+cobrapy, they are not explicitly supported (yet!).
 
 ## Stable version installation
 
+cobrapy can be installed with any recent installation of pip. Instructions
+for several operating systems are below:
+
 ### Mac OS X
 0. [install pip](http://pip.readthedocs.org/en/latest/installing.html).
 1. In a terminal, run ```sudo pip install cobra```
 
-### GNU/Linux
+### Ubuntu or Debian Linux
 0. [install pip](http://pip.readthedocs.org/en/latest/installing.html).
 1. Install the python and glpk development libraries. On debian-based
    systems (including Ubuntu and Mint), this can be done with
@@ -33,6 +34,7 @@ cobrapy, they are not explicitly supported at this time.
 The preferred installation method on Windows is also to use pip. The latest
 Windows installers for Python 2.7 and 3.4 include pip, so if you use those you
 will already have pip.
+
 1. In a terminal, run ```C:\Python27\Scripts\pip.exe install cobra```
    (you may need to adjust the path accordingly).
 
@@ -61,13 +63,14 @@ On windows, these can downloaded from [this site]
 (http://www.lfd.uci.edu/~gohlke/pythonlibs/). On Mac/Linux, they can be
 installed using pip, or from the OS package manager (e.g brew, apt, yum).
 
-1. [libsbml](http://sbml.org) >= 5.10 to read/write SBML files
-  * [Windows installer](http://www.lfd.uci.edu/~gohlke/pythonlibs/#libsbml)
-  * Use ```sudo pip install python-libsbml-experimental``` on Mac/Linux
-2. [numpy](http://numpy.org) >= 1.6.1 for double deletions
-  * [Windows installer](http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy)
-3. [scipy](http://scipy.org) >= 0.11 for ArrayBasedModel and saving to *.mat files.
-  * [Windows installer](http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy)
+1. [libsbml](http://sbml.org) >= 5.10 to read/write SBML level 2 files
+    * [Windows installer](http://www.lfd.uci.edu/~gohlke/pythonlibs/#libsbml)
+    * Use ```sudo pip install python-libsbml``` on Mac/Linux
+2. [lxml](http://lxml.de/) to speed up read/write of SBML level 3 files.
+3. [numpy](http://numpy.org) >= 1.6.1 for double deletions
+    * [Windows installer](http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy)
+4. [scipy](http://scipy.org) >= 0.11 for ArrayBasedModel and saving to *.mat files.
+    * [Windows installer](http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy)
 
 ## Other solvers
 cobrapy comes with bindings to the GNU Linear Programming Kit ([glpk]
diff --git a/README.md b/README.md
index b3575bd..7810886 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,10 @@
 cobrapy
 =======
+[![Build Status](https://travis-ci.org/opencobra/cobrapy.svg?branch=master)](https://travis-ci.org/opencobra/cobrapy)
+[![Coverage Status](https://coveralls.io/repos/opencobra/cobrapy/badge.svg?branch=master&service=github)](https://coveralls.io/github/opencobra/cobrapy?branch=master)
+[![Build status](https://ci.appveyor.com/api/projects/status/2o549lhjyukke8nd/branch/master?svg=true)](https://ci.appveyor.com/project/aebrahim/cobrapy/branch/master)
+[![PyPI](https://img.shields.io/pypi/v/cobra.svg)](https://pypi.python.org/pypi/cobra)
+
 
 COnstraint-Based Reconstruction and Analysis (COBRA) methods are widely used
 for genome-scale modeling of metabolic networks in both prokaryotes and
diff --git a/cobra/VERSION b/cobra/VERSION
index b49a8bd..de998de 100644
--- a/cobra/VERSION
+++ b/cobra/VERSION
@@ -1 +1 @@
-0.4.0b2
+0.4.0b3
diff --git a/cobra/flux_analysis/deletion_worker.py b/cobra/flux_analysis/deletion_worker.py
index 68e7863..887501a 100644
--- a/cobra/flux_analysis/deletion_worker.py
+++ b/cobra/flux_analysis/deletion_worker.py
@@ -29,7 +29,7 @@ def compute_fba_deletion(lp, solver_object, model, indexes, **kwargs):
         s.solve_problem(lp, **kwargs)
     except Exception as e:
         return RuntimeError("solver failure when deleting %s: %s" %
-                                (str(indexes), repr(e)))
+                            (str(indexes), repr(e)))
     status = s.get_status(lp)
     objective = s.get_objective_value(lp) if status == "optimal" else 0.
 
diff --git a/cobra/flux_analysis/phenotype_phase_plane.py b/cobra/flux_analysis/phenotype_phase_plane.py
index b7deab8..27ca550 100644
--- a/cobra/flux_analysis/phenotype_phase_plane.py
+++ b/cobra/flux_analysis/phenotype_phase_plane.py
@@ -146,11 +146,9 @@ class phenotypePhasePlaneData:
             i, j = unravel_index(self.segments.argmin(), self.segments.shape)
             # update the segment id for any point with a similar shadow price
             # to the current point
-            self.segments[
-                (abs(self.shadow_prices1 - self.shadow_prices1[i, j])
-                    < threshold) *
-                (abs(self.shadow_prices2 - self.shadow_prices2[i, j])
-                    < threshold)] += segment_id
+            d1 = abs(self.shadow_prices1 - self.shadow_prices1[i, j])
+            d2 = abs(self.shadow_prices2 - self.shadow_prices2[i, j])
+            self.segments[(d1 < threshold) * (d2 < threshold)] += segment_id
             # add the current point as one of the phases
             self.phases.append((
                 (self.reaction1_fluxes[i], self.reaction2_fluxes[j]),
@@ -185,8 +183,8 @@ def _calculate_subset(arguments):
         # float instead of numpy.float64
         flux1 = float(-1 * flux1)
         # change bounds on reaction 1
-        solver.change_variable_bounds(problem, index1, flux1 - tolerance, flux1
-                                      + tolerance)
+        solver.change_variable_bounds(problem, index1, flux1 - tolerance,
+                                      flux1 + tolerance)
         for b, flux2 in enumerate(reaction2_fluxes):
             j = j_list[b]
             flux2 = float(-1 * flux2)  # same story as flux1
@@ -235,17 +233,13 @@ def calculate_phenotype_phase_plane(
         reaction1_range_max, reaction2_range_max,
         reaction1_npoints, reaction2_npoints)
     # find the objects for the reactions and metabolites
-    index1 = model.reactions.index(
-        model.reactions.get_by_id(data.reaction1_name))
-    index2 = model.reactions.index(
-        model.reactions.get_by_id(data.reaction2_name))
-    metabolite1_name = \
-        str(model.reactions.get_by_id(reaction1_name)._metabolites.keys()[0])
-    metabolite2_name = \
-        str(model.reactions.get_by_id(reaction2_name)._metabolites.keys()[0])
+    index1 = model.reactions.index(data.reaction1_name)
+    index2 = model.reactions.index(data.reaction2_name)
+    metabolite1_name = list(model.reactions[index1]._metabolites)[0].id
+    metabolite2_name = list(model.reactions[index2]._metabolites)[0].id
     if n_processes > reaction1_npoints:  # limit the number of processes
         n_processes = reaction1_npoints
-    range_add = reaction1_npoints / n_processes
+    range_add = reaction1_npoints // n_processes
     # prepare the list of arguments for each _calculate_subset call
     arguments_list = []
     i = arange(reaction1_npoints)
diff --git a/cobra/io/__init__.py b/cobra/io/__init__.py
index 8f26e92..d82cf88 100644
--- a/cobra/io/__init__.py
+++ b/cobra/io/__init__.py
@@ -1,29 +1,24 @@
 from warnings import warn
 
+from .sbml3 import read_sbml_model, write_sbml_model
+from .json import load_json_model, save_json_model, to_json
+
+# These functions have other dependencies
 try:
     import libsbml
 except ImportError:
+    warn("cobra.io.sbml requires libsbml")
     libsbml = None
+else:
+    from .sbml import read_legacy_sbml
+    from .sbml import write_cobra_model_to_sbml_file as write_legacy_sbml
+
 try:
     import scipy
 except ImportError:
+    warn("cobra.io.mat requires scipy")
     scipy = None
-
-if libsbml:
-    from .sbml import read_legacy_sbml
-    from .sbml import write_cobra_model_to_sbml_file as write_legacy_sbml
-else:
-    warn("cobra.io.sbml requires libsbml")
-
-if scipy:
-    from .mat import load_matlab_model
-    from .mat import save_matlab_model
 else:
-    warn("cobra.io.mat requires scipy")
-
-from .sbml3 import read_sbml_model, write_sbml_model
-
-from .json import load_json_model
-from .json import save_json_model, to_json
+    from .mat import load_matlab_model, save_matlab_model
 
 del libsbml, scipy, warn
diff --git a/cobra/io/mat.py b/cobra/io/mat.py
index 6f665e6..3865e65 100644
--- a/cobra/io/mat.py
+++ b/cobra/io/mat.py
@@ -41,7 +41,8 @@ def _get_id_comparment(id):
 
 def _cell(x):
     """translate an array x into a MATLAB cell array"""
-    return array(x, dtype=np_object)
+    x_no_none = [i if i is not None else "" for i in x]
+    return array(x_no_none, dtype=np_object)
 
 
 def load_matlab_model(infile_path, variable_name=None):
diff --git a/cobra/solvers/cglpk.pyx b/cobra/solvers/cglpk.pyx
index 6d81299..b375914 100644
--- a/cobra/solvers/cglpk.pyx
+++ b/cobra/solvers/cglpk.pyx
@@ -116,16 +116,17 @@ cdef check_error(int result):
                        (ERROR_CODES[result], ERROR_MESSAGES[result]))
 
 
-# Do not want to print out to terminal. Even when not verbose, output
-# will be redirected through the hook.
-glp_term_out(GLP_OFF)
-
 
 cdef int hook(void *info, const char *s):
     """function to redirect sdout to python stdout"""
     print(s)
     return 1
 
+
+cdef int silent_hook(void *info, const char *s):
+    """function to print nothing but trick GLPK into thinking we did"""
+    return 1
+
 cdef double _to_double(value):
     if isinstance(value, Basic) and not isinstance(value, Number):
         return 0.
@@ -142,10 +143,13 @@ cdef class GLP:
     # cython related allocation/dellocation functions
     def __cinit__(self):
         self.glp = glp_create_prob()
+        # initialize parameters
         glp_set_obj_dir(self.glp, GLP_MAX)  # default is maximize
         glp_init_smcp(&self.parameters)
         glp_init_iocp(&self.integer_parameters)
         self.exact = False
+        glp_term_hook(hook, NULL)
+        self.parameters.msg_lev = GLP_MSG_OFF
 
     def __dealloc__(self):
         glp_delete_prob(self.glp)
@@ -157,10 +161,6 @@ cdef class GLP:
         cdef int *c_cols
         cdef double *c_values
         cdef double b
-        
-        # initialize parameters
-        self.parameters.msg_lev = GLP_MSG_OFF
-        glp_term_hook(NULL, NULL)
 
         if cobra_model is None:
             return
@@ -274,16 +274,9 @@ cdef class GLP:
 
     def solve_problem(self, **solver_parameters):
         cdef int result
-        cdef glp_smcp parameters = self.parameters
-        cdef int time_limit = parameters.tm_lim
-        cdef glp_iocp integer_parameters = self.integer_parameters
+        cdef int time_limit
         cdef glp_prob *glp = self.glp
 
-        if "quadratic_component" in solver_parameters:
-            q = solver_parameters.pop("quadratic_component")
-            if q is not None:
-                raise ValueError("quadratic component must be None for glpk")
-
         for key, value in solver_parameters.items():
             self.set_parameter(key, value)
 
@@ -296,22 +289,22 @@ cdef class GLP:
         #with nogil:  # we can use this if glpk ever gets thread-safe malloc
         # Try to solve the problem with the existing basis, but with
         # a time limit in case it gets stuck.
-        if parameters.tm_lim > 500:
-            parameters.tm_lim = 500
-        if glp_simplex(glp, &parameters) != 0:
+        time_limit = self.parameters.tm_lim  # save time limit
+        self.parameters.tm_lim = min(500, time_limit)
+        fast_status = glp_simplex(glp, &self.parameters)
+        self.parameters.tm_lim = time_limit
+        
+        if fast_status != 0:
             glp_adv_basis(glp, 0)
-            parameters.tm_lim = time_limit
-            check_error(glp_simplex(glp, &parameters))
-        parameters.tm_lim = time_limit
+            check_error(glp_simplex(glp, &self.parameters))
+        self.parameters.tm_lim = time_limit
         if self.exact:
-            check_error(glp_exact(glp, &parameters))
+            check_error(glp_exact(glp, &self.parameters))
         if self.is_mip():
             self.integer_parameters.tm_lim = self.parameters.tm_lim
             self.integer_parameters.msg_lev = self.parameters.msg_lev
-            #self.integer_parameters.tol_bnd = self.parameters.tol_bnd
-            #self.integer_parameters.tol_piv = self.parameters.tol_piv
             #with nogil:
-            check_error(glp_intopt(glp, &integer_parameters))
+            check_error(glp_intopt(glp, &self.integer_parameters))
         return self.get_status()
 
     @classmethod
@@ -351,6 +344,11 @@ cdef class GLP:
             self.set_objective_sense(value)
         elif parameter_name in {"time_limit", "tm_lim"}:
             self.parameters.tm_lim = int(1000 * value)
+            # Setting a value less than 0.001 would cause us to not
+            # set a time limit at all. It's better to set a time limit
+            # of 1 ms in this case.
+            #if value > 0 and self.parameters.tm_lim == 0:
+            #    self.parameters.tm_lim = 1
         elif parameter_name == "tolerance_feasibility":
             self.parameters.tol_bnd = float(value)
             self.parameters.tol_dj = float(value)
@@ -367,9 +365,7 @@ cdef class GLP:
         elif parameter_name == "verbose":
             if not value:  # suppress all output
                 self.parameters.msg_lev = GLP_MSG_OFF
-                glp_term_hook(NULL, NULL)
                 return
-            glp_term_hook(hook, NULL)
             if value == "err":
                 self.parameters.msg_lev = GLP_MSG_ERR
             elif value is True or value == "all":
@@ -400,6 +396,9 @@ cdef class GLP:
                     glp_scale_prob(self.glp, SCALINGS[value])
             else:
                 glp_unscale_prob(self.glp)
+        elif parameter_name == "quadratic_component":
+            if value is not None:
+                raise ValueError("quadratic component must be None for glpk")
         else:
             raise ValueError("unknown parameter " + str(parameter_name))
 
@@ -496,14 +495,19 @@ cdef class GLP:
             raise RuntimeError("Unknown python version")
         cdef char *c_name = <bytes> b_name
         cdef int res
-        if b_name.endswith(".lp"):
-            res = glp_write_lp(self.glp, NULL, c_name)
-        elif b_name.endswith(".mps"):
-            res = glp_write_mps(self.glp, GLP_MPS_FILE, NULL, c_name)
-        else:
-            raise ValueError("Unknown file format for %s" % str(filename))
-        if res != 0:
-            raise IOError("failed to write LP to file %s" % str(filename))
+        # no other way to silence this function
+        glp_term_hook(silent_hook, NULL)
+        try:
+            if b_name.endswith(".lp"):
+                res = glp_write_lp(self.glp, NULL, c_name)
+            elif b_name.endswith(".mps"):
+                res = glp_write_mps(self.glp, GLP_MPS_FILE, NULL, c_name)
+            else:
+                raise ValueError("Unknown file format for %s" % str(filename))
+            if res != 0:
+                raise IOError("failed to write LP to file %s" % str(filename))
+        finally:
+            glp_term_hook(hook, NULL)
 
 
 # wrappers for all the functions at the module level
diff --git a/cobra/test/__init__.py b/cobra/test/__init__.py
index 7a20929..564fefc 100644
--- a/cobra/test/__init__.py
+++ b/cobra/test/__init__.py
@@ -63,4 +63,7 @@ suite = create_test_suite()
 
 def test_all():
     """###running unit tests on cobra py###"""
-    _unittest.TextTestRunner(verbosity=2).run(create_test_suite())
+    status = not _unittest.TextTestRunner(verbosity=2).run(
+        create_test_suite()
+    ).wasSuccessful()
+    return status
diff --git a/cobra/test/flux_analysis.py b/cobra/test/flux_analysis.py
index 2fd2edf..14a354f 100644
--- a/cobra/test/flux_analysis.py
+++ b/cobra/test/flux_analysis.py
@@ -381,6 +381,15 @@ class TestCobraFluxAnalysis(TestCase):
         self.assertEqual(rxns.r7.genes, {m.genes.z})
         self.assertEqual(rxns.r8.gene_reaction_rule, "")
 
+    @skipIf(numpy is None, "double deletions require numpy")
+    def test_phenotype_phase_plane(self):
+        model = create_test_model("textbook")
+        data = calculate_phenotype_phase_plane(
+            model, "EX_glc__D_e", "EX_o2_e",
+            reaction1_npoints=20, reaction2_npoints=20)
+        self.assertEqual(data.growth_rates.shape, (20, 20))
+        self.assertAlmostEqual(data.growth_rates.max(), 1.20898, places=4)
+        self.assertAlmostEqual(abs(data.growth_rates[0, :]).max(), 0, places=4)
 
 # make a test suite to run all of the tests
 loader = TestLoader()
diff --git a/setup.py b/setup.py
index 8a9ab80..4282ba0 100644
--- a/setup.py
+++ b/setup.py
@@ -129,7 +129,7 @@ except:
 
 extras = {
     'matlab': ["pymatbridge"],
-    'sbml': ["python-libsbml-experimental", "lxml"],
+    'sbml': ["python-libsbml", "lxml"],
     'array': ["numpy>=1.6", "scipy>=11.0"],
     'display': ["matplotlib", "brewer2mpl", "pandas"]
 }
@@ -149,8 +149,14 @@ extras["all"] = list(all_extras)
 if "bdist_wininst" in argv:
     setup_kwargs["py_modules"] = ["six"]
 
-with open("README.md", "r") as infile:
-    setup_kwargs["long_description"] = infile.read()
+try:
+    import pypandoc
+    readme = pypandoc.convert("README.md", "rst")
+    install = pypandoc.convert("INSTALL.md", "rst")
+    setup_kwargs["long_description"] = readme + "\n\n" + install
+except:
+    with open("README.md", "r") as infile:
+        setup_kwargs["long_description"] = infile.read()
 
 setup(
     name="cobra",

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