Commits

Marko Toplak  committed 418d0e7 Merge

Merge.

  • Participants
  • Parent commits 56ba93b, a3db39d

Comments (0)

Files changed (6)

File _bioinformatics/obiKEGG/__init__.py

-"""\
+"""
 ==============================================
 KEGG - Kyoto Encyclopedia of Genes and Genomes
 ==============================================
 import os
 import sys
 import urllib2
+import threading
 
 from collections import defaultdict
 from itertools import chain
 from datetime import datetime
+from contextlib import contextmanager
 
 from Orange.utils import lru_cache
 from Orange.utils import progress_bar_milestones
 
     @classmethod
     def organism_name_search(cls, name):
-        genome = KEGGGenome()
-        try:
-            name = genome.org_code_to_entry_key(name)
-        except ValueError:
-            pass
-
-        if name not in genome:
-            ids = genome.search(name)
-            if ids:
-                name = ids.pop(0) if ids else name
-            else:
-                raise OrganismNotFoundError(name)
-
-        try:
-            return genome[name].organism_code
-        except KeyError:
-            raise OrganismNotFoundError(name)
+        return organism_name_search(name)
 
     @classmethod
     def organism_version(cls, name):
         name = cls.organism_name_search(name)
-        genome = KEGGGenome()
-        info = genome.api.info(name)
-        return info.release
+        with _global_genome_instance() as genome:
+            info = genome.api.info(name)
+            return info.release
 
     def _set_genematcher(self, genematcher):
         setattr(self, "_genematcher", genematcher)
 
 def organism_name_search(name):
     """
-    Search and organism by `name` and return an KEGG organism code.
+    Search for a organism by `name` and return it's KEGG organism code.
     """
-    return KEGGOrganism.organism_name_search(name)
+    with _global_genome_instance() as genome:
+        try:
+            name = genome.org_code_to_entry_key(name)
+        except ValueError:
+            pass
+
+        if name not in genome:
+            ids = genome.search(name)
+            if ids:
+                name = ids.pop(0) if ids else name
+            else:
+                raise OrganismNotFoundError(name)
+
+        try:
+            return genome[name].organism_code
+        except KeyError:
+            raise OrganismNotFoundError(name)
 
 
 def pathways(org):
     return KEGGPathway.list(org)
 
 
-def organisms():
-    """
-    Return a list of all KEGG organisms.
-    """
-    return KEGGOrganism.organisms()
-
-
 def from_taxid(taxid):
     """
     Return a KEGG organism code for a an NCBI Taxonomy id string `taxid`.
     """
-    genome = KEGGGenome()
-    res = genome.search(taxid)
-    for r in res:
-        e = genome[r]
+    with _global_genome_instance() as genome:
+        res = genome.search(taxid)
+        for r in res:
+            e = genome[r]
 
-        if e.taxid in [taxid, genome.TAXID_MAP.get(taxid, taxid)]:
-            return e.org_code()
+            if e.taxid in [taxid, genome.TAXID_MAP.get(taxid, taxid)]:
+                return e.org_code()
 
-    return None
+        return None
 
 
 def to_taxid(name):
     """
     Return a NCBI Taxonomy id for a given KEGG Organism name
     """
-    genome = KEGGGenome()
-    if name in genome:
-        return genome[name].taxid
+    with _global_genome_instance() as genome:
+        if name in genome:
+            return genome[name].taxid
 
-    keys = genome.search(name)
-    if keys:
-        return genome[keys[0]].taxid
-    else:
-        return None
+        keys = genome.search(name)
+        if keys:
+            return genome[keys[0]].taxid
+        else:
+            return None
+
+
+def _global_genome_instance():
+    genome = getattr(_global_genome_instance, "_genome", None)
+    if genome is None:
+        genome = KEGGGenome()
+        genome._lock = threading.RLock()
+        _global_genome_instance._genome = genome
+
+    @contextmanager
+    def instance_locked(instance, lock):
+        lock.acquire()
+        try:
+            yield instance
+        finally:
+            lock.release()
+
+    return instance_locked(genome, genome._lock)
 
 
 def main():

File _bioinformatics/widgets/OWGOEnrichmentAnalysis.py

                             tooltip="Select organism", debuggingEnabled=0)
         
         # freeze until annotation combo box is updateded with available annotations.
-        self.signalManager.freeze(self).push()
+        if self.signalManager:
+            self.signalManager.freeze(self).push()
         QTimer.singleShot(0, self.UpdateOrganismComboBox)
         
         self.geneAttrIndexCombo = OWGUI.comboBox(self.inputTab, self, "geneAttrIndex",
             self.annotationComboBox.addItems(self.annotationCodes)
             self.annotationComboBox.setCurrentIndex(self.annotationIndex)
         finally:
-            self.signalManager.freeze(self).pop()
-            
+            if self.signalManager:
+                self.signalManager.freeze(self).pop()
+
     def UpdateGeneMatcher(self):
         dialog = GeneMatcherDialog(self, defaults=self.geneMatcherSettings, modal=True)
         if dialog.exec_():
     import sys
     app = QApplication(sys.argv)
     w=OWGOEnrichmentAnalysis()
-    data = orange.ExampleTable("../../../doc/datasets/brown-selected.tab")
+    data = orange.ExampleTable("brown-selected.tab")
     w.show()
     w.SetClusterDataset(data)
     app.exec_()

File _bioinformatics/widgets/OWGsea.py

 
     def UpdateOrganismComboBox(self):
         try:
-            self.progressBarInit()
-            with orngServerFiles.DownloadProgress.setredirect(self.progressBarSet):
-                genome = obiKEGG.KEGGGenome()
-            self.progressBarFinished()
-            
-            self.allOrganismCodes = genome 
-    
+            genome = obiKEGG.KEGGGenome()
+
+            self.allOrganismCodes = genome
+
             essential = genome.essential_organisms()
-            
-            local = [name.split(".")[0].split("_")[-1] for name in orngServerFiles.listfiles("KEGG") if "kegg_genes" in name]
-            self.organismCodes = [(code, organism.definition) for code, organism in self.allOrganismCodes.items() if code in local or code in essential]
-            self.organismCodes.sort()
-            items = [desc for code, desc in self.organismCodes]
-            self.organismCodes = [obiKEGG.to_taxid(code) for code, desc in self.organismCodes]
-            
+
+            local = [name.split(".")[0].split("_")[-1]
+                     for name in orngServerFiles.listfiles("KEGG")
+                     if "kegg_genes" in name]
+
+            entry_keys = map(genome.org_code_to_entry_key,
+                             essential + local)
+
+            entries = genome.batch_get(entry_keys)
+
+            items = [entry.definition for entry in entries]
+
+            self.organismTaxids = [entry.taxid for entry in entries]
+
+            self.organismComboBox.clear()
             self.organismComboBox.addItems(items)
         finally:
-            self.signalManager.freeze(self).pop() #setFreeze(0)
+            if self.signalManager:
+                self.signalManager.freeze(self).pop()
 
 
     def __init__(self, parent=None, signalManager = None, name='GSEA'):
         box = OWGUI.widgetBox(ca, 'Organism')
         #FROM KEGG WIDGET - organism selection
         self.allOrganismCodes = {}
-        self.organismCodes = []
+        self.organismTaxids = []
         self.organismComboBox = cb = OWGUI.comboBox(box, self, "organismIndex", items=[], debuggingEnabled=0) #changed
         cb.setMaximumWidth(200)
-        self.signalManager.freeze(self).push() #setFreeze(1)
+
+        if self.signalManager:
+            self.signalManager.freeze(self).push()
         QTimer.singleShot(100, self.UpdateOrganismComboBox)
  
         #OWGUI.checkBox(box, self, "csgm", "Case sensitive gene matching")
 
         collectionNames = [ self.geneSel[a] for a in self.gridSel ]
 
-        organism = self.organismCodes[self.organismIndex]
+        organism = self.organismTaxids[self.organismIndex]
 
         if self.gsgo:
             collectionNames.append((("GO",),organism))
         if data:
             taxid = data_hints.get_hint(data, "taxid", None)
             try:
-                code = obiKEGG.from_taxid(taxid)
-                self.organismIndex = self.organismCodes.index(code)
+                self.organismIndex = self.organismTaxids.index(taxid)
             except Exception, ex:
                 pass
-            
+
             if obiGsea.already_have_correlations(data):
 
                 #disable correlation type
     #d = orange.ExampleTable('/home/marko/ddd.tab')
     #d = orange.ExampleTable('tmp.tab')
     #d = orange.ExampleTable('../gene_three_lines_log.tab')
-    ow.setData(d)
+
+    QTimer.singleShot(1000, lambda : ow.setData(d))
 
     a.exec_()
     ow.saveSettings()

File _bioinformatics/widgets/OWKEGGPathwayBrowser.py

             debuggingEnabled=0,
             tooltip="Select the organism of the input genes")
 
-        self.signalManager.freeze(self).push()
+        if self.signalManager:
+            self.signalManager.freeze(self).push()
 
         # Selection of genes attribute
         box = OWGUI.widgetBox(self.controlArea, "Gene attribute")
         self.has_new_reference_set = False
 
         self.setEnabled(False)
+        self.infoLabel.setText("Fetching organism definitions\n")
         QTimer.singleShot(100, self.UpdateOrganismComboBox)
 
     def UpdateOrganismComboBox(self):
             # TODO: Add option to specify additional organisms not
             # in the common list.
 
-            self.infoLabel.setText("Fetching organism definitions\n")
-
             keys = map(genome.org_code_to_entry_key, essential + common)
 
             self.progressBarInit()
             items = [desc for code, desc in codes]
 
             self.organismCodes = [code for code, desc in codes]
+            self.organismComboBox.clear()
             self.organismComboBox.addItems(items)
+            self.organismComboBox.setCurrentIndex(self.organismIndex)
         finally:
             self.setEnabled(True)
             self.infoLabel.setText("No data on input\n")
-            self.signalManager.freeze(self).pop()
+            if self.signalManager:
+                self.signalManager.freeze(self).pop()
 
     def Clear(self):
         """
 
 if __name__ == "__main__":
     app = QApplication(sys.argv)
+    w = OWKEGGPathwayBrowser()
+    w.show()
+
     data = Orange.data.Table("brown-selected.tab")
-    w = OWKEGGPathwayBrowser()
-    w.UpdateOrganismComboBox()
-    w.show()
-    w.SetData(Orange.data.Table(data[:]))
-    QTimer.singleShot(10, w.handleNewSignals)
+
+    QTimer.singleShot(1000, lambda: w.SetData(data))
+    QTimer.singleShot(1500, w.handleNewSignals)
 
     app.exec_()
     w.saveSettings()

File _bioinformatics/widgets/OWPIPA.py

             return "-1"
 
     def UpdateExperimentTypes(self):
-        self.signalManager.freeze(self).push() #setFreeze(1)
+        if self.signalManager:
+            self.signalManager.freeze(self).push()
         try:
             self.expressionTypesCB.clear()
             items = [desc for _,desc,_ in self.exTypes]
         except IOError:
             pass
         finally:
-            self.signalManager.freeze(self).pop() #setFreeze(0)
+            if self.signalManager:
+                self.signalManager.freeze(self).pop()
+
         self.ctypei = max(0, min(self.ctypei, len(self.exTypes)-1))
 
     def UpdateExperiments(self, reload=False):

File _bioinformatics/widgets/OWSetEnrichment.py

         
         self.loadSettings()
         
-        self.signalManager.freeze(self).push()
+        if self.signalManager:
+            self.signalManager.freeze(self).push()
         QTimer.singleShot(50, self.updateHierarchy)
         
         box = OWGUI.widgetBox(self.controlArea, "Info")
             self.speciesComboBox.addItems([obiTaxonomy.name(id) for id in self.taxid_list])
             self.genesets = all
         finally:
-            self.signalManager.freeze(self).pop() #setFreeze(self.signalManager.freezing - 1)
+            if self.signalManager:
+                self.signalManager.freeze(self).pop()
         
     def setData(self, data=None):
         self.data = data
     app = QApplication(sys.argv)
     w = OWSetEnrichment()
     w.updateHierarchy()
-    data = orange.ExampleTable("../../../doc/datasets/brown-selected")
+    data = orange.ExampleTable("brown-selected")
 #    data = orange.ExampleTable("../human")
 #    print cProfile.runctx("w.setData(data)", globals(), locals())
     w.setData(data)