source: orange-bioinformatics/orangecontrib/bio/widgets/OWDicty.py @ 1873:0810c5708cc5

Revision 1873:0810c5708cc5, 7.0 KB checked in by Ales Erjavec <ales.erjavec@…>, 7 months ago (diff)

Moved '_bioinformatics' into orangecontrib namespace.

RevLine 
[432]1"""
[1462]2<name>dictyExpress</name>
[1051]3<description>Access to data in dictyExpress database.</description>
[1726]4<icon>icons/DictyExpress.svg</icon>
[1051]5<priority>40</priority>
[432]6"""
7
[1632]8from __future__ import absolute_import
9
10from collections import defaultdict
[432]11import sys
[435]12
[1632]13from Orange.orng import orngEnviron
14from Orange.OrangeWidgets import OWGUI
15from Orange.OrangeWidgets.OWWidget import *
[705]16
[1632]17from .. import obiDicty
[443]18
[435]19class MyTreeWidgetItem(QTreeWidgetItem):
20    def __contains__(self, text):
21        return any(text.upper() in str(self.text(i)).upper() for i in range(self.columnCount()))   
[795]22
23#set buffer file
24bufferpath = os.path.join(orngEnviron.directoryNames["bufferDir"], "dicty")
25try:
26    os.makedirs(bufferpath)
27except:
28    pass
29bufferfile = os.path.join(bufferpath, "database.sq3")
30
[432]31class OWDicty(OWWidget):
[838]32    settingsList = ["serverToken", "platform", "selectedExperiments", "server", "buffertime", "excludeconstant" ]
[1462]33    def __init__(self, parent=None, signalManager=None, name="dictyExpress"):
[432]34        OWWidget.__init__(self, parent, signalManager, name)
[795]35        self.outputs = [("Example table", ExampleTable)]
[432]36        self.serverToken = ""
[1179]37        self.server = obiDicty.defaddress
[432]38
39        self.platform = None
[434]40
[432]41        self.selectedExperiments = []
[795]42        self.buffer = obiDicty.BufferSQLite(bufferfile)
[432]43
44        self.searchString = ""
[838]45        self.excludeconstant = False
[432]46       
[795]47        box = OWGUI.widgetBox(self.controlArea, "Cache")
[796]48        OWGUI.button(box, self, "Clear cache", callback=self.clear_buffer)
[795]49
[838]50        OWGUI.checkBox(self.controlArea, self, "excludeconstant", "Exclude labels with constant values" )
51
[434]52        OWGUI.button(self.controlArea, self, "&Commit", callback=self.Commit)
[443]53        box  = OWGUI.widgetBox(self.controlArea, "Server")
54        OWGUI.lineEdit(box, self, "serverToken","Token", callback=self.Connect)
[434]55        OWGUI.rubber(self.controlArea)
56
[432]57        OWGUI.lineEdit(self.mainArea, self, "searchString", "Search", callbackOnType=True, callback=self.SearchUpdate)
58        self.experimentsWidget = QTreeWidget()
[795]59        self.experimentsWidget.setHeaderLabels(["Strain", "Treatment", "Growth condition", "Platform", "N", "Chips"]) 
[432]60        self.experimentsWidget.setSelectionMode(QTreeWidget.ExtendedSelection)
61        self.experimentsWidget.setRootIsDecorated(False)
62        self.experimentsWidget.setSortingEnabled(True)
63##        self.experimentsWidget.setAlternatingRowColors(True)
[795]64
[432]65        self.mainArea.layout().addWidget(self.experimentsWidget)
66
[434]67        self.loadSettings()
[432]68        self.dbc = None       
69
[831]70        QTimer.singleShot(0, self.UpdateExperiments)       
[432]71
[902]72        self.resize(800, 600)
[432]73
74    def __updateSelectionList(self, oldList, oldSelection, newList):
75        oldList = [oldList[i] for i in oldSelection]
76        return [ i for i, new in enumerate(newList) if new in oldList]
77   
78    def Connect(self):
[831]79
[443]80        address = self.server + "?"
[432]81        if self.serverToken:
82            address += "token="+self.serverToken+"&"
83        try:
[795]84            #obiDicty.verbose = 1
85            self.dbc = obiDicty.DatabaseConnection(address, buffer=self.buffer)
[432]86        except Exception, ex:
87            from traceback import print_exception
88            print_exception(*sys.exc_info())
89            self.error(0, "Error connecting to server" + str(ex))
90            return
91        self.error(0)
92
[795]93    def clear_buffer(self):
[796]94        self.buffer.clear()
[795]95        self.UpdateExperiments()
[435]96
[432]97    def UpdateExperiments(self):
[795]98        self.chipsl = []
[432]99        self.experimentsWidget.clear()
100        self.items = []
[795]101
102        if not self.dbc:
103            self.Connect()
[1179]104
105        """
106        self.progressBarInit()
107
[527]108        strains = self.dbc.annotationOptions("sample")["sample"]
[705]109
[432]110        for i, strain in enumerate(strains):
[705]111            chips = self.dbc.search("norms", sample=strain)
112            annotations = self.dbc.annotations("norms", chips)
113
114            elements = []
115
[795]116            for chip,annot in zip(chips,annotations):
[705]117                d = dict(annot)
[795]118                elements.append(((d.get("treatment", ""), d.get("growthCond", ""), d.get("platform", "")),chip))
[705]119
[795]120            def different_chips(li):
[1179]121                # Returns a map, where keys are different elements in li and values their chip ids
[795]122                dc = defaultdict(list)
123                for a,chip in li:
124                    dc[a].append(chip)
[705]125                return dc
126
[795]127            typeswchips = different_chips(elements) #types with counts
[705]128
[1179]129            for (treatment, cond, platforma),cchips in typeswchips.items():
[795]130                self.chipsl.append(cchips)
131                num = len(cchips)
132                experiment = [strain, treatment, cond, platform, str(num), ','.join(cchips)]
133                self.items.append(MyTreeWidgetItem(self.experimentsWidget, experiment))
[705]134
[432]135            self.progressBarSet((100.0 * i) / len(strains))
[1179]136        """
137
138        annotations = self.dbc.annotations("norms", None)
139
140        elements = []
141
142        for chip,annot in annotations:
143            d = dict(annot)
144            elements.append(((d.get("treatment", ""), d.get("growthCond", ""), d.get("platform", ""), d.get("sample", "")),chip))
145
146        def different_chips(li):
147            # Returns a map, where keys are different elements in li and values their chip ids
148            dc = defaultdict(list)
149            for a,chip in li:
150                dc[a].append(chip)
151            return dc
152
153        typeswchips = different_chips(elements) #types with counts
154
155        for (treatment, cond, platform, strain),cchips in typeswchips.items():
156            self.chipsl.append(cchips)
157            num = len(cchips)
158            experiment = [strain, treatment, cond, platform, str(num), ','.join(cchips)] 
159            self.items.append(MyTreeWidgetItem(self.experimentsWidget, experiment))
160
[902]161        for i in range(5):
162            self.experimentsWidget.resizeColumnToContents(i)
[705]163
[432]164        self.progressBarFinished()
165
166    def SearchUpdate(self, string=""):
167        for item in self.items:
[435]168            item.setHidden(not all(s in item for s in self.searchString.split()))
[443]169
[432]170    def Commit(self):
171        if not self.dbc:
172            self.Connect()
173        allTables = []
[557]174
[434]175        import time
176        start = time.time()
[557]177
178        pb = OWGUI.ProgressBar(self, iterations=1000)
179
[795]180        table = None
181
182        ids = []
[432]183        for item in self.experimentsWidget.selectedItems():
[795]184            ids += str(item.text(5)).split(",")
185
[838]186        table = self.dbc.get_single_data(ids=ids, callback=pb.advance, exclude_constant_labels=self.excludeconstant)
[795]187
[434]188        end = int(time.time()-start)
189       
[557]190        pb.finish()
191
[795]192        #self.send("Example table", None)
[1118]193#        table.taxid = "352472"
194#        table.genesinrows = False
195       
[1632]196        from Orange.orng.orngDataCaching import data_hints
[1118]197        data_hints.set_hint(table, "taxid", "352472", 10.0)
198        data_hints.set_hint(table, "genesinrows", False, 10.0)
[1104]199       
[795]200        self.send("Example table", table)
[432]201
202if __name__ == "__main__":
203    app  = QApplication(sys.argv)
[434]204##    from pywin.debugger import set_trace
205##    set_trace()
[432]206    w = OWDicty()
207    w.show()
208    app.exec_()
209    w.saveSettings()
210           
[503]211       
Note: See TracBrowser for help on using the repository browser.