source: orange-bioinformatics/_bioinformatics/widgets/OWDicty.py @ 1726:6778e0225b86

Revision 1726:6778e0225b86, 7.0 KB checked in by Ales Erjavec <ales.erjavec@…>, 17 months ago (diff)

Added new icons by Peter Cuhalev and replaced existing ones with expanded paths.

Line 
1"""
2<name>dictyExpress</name>
3<description>Access to data in dictyExpress database.</description>
4<icon>icons/DictyExpress.svg</icon>
5<priority>40</priority>
6"""
7
8from __future__ import absolute_import
9
10from collections import defaultdict
11import sys
12
13from Orange.orng import orngEnviron
14from Orange.OrangeWidgets import OWGUI
15from Orange.OrangeWidgets.OWWidget import *
16
17from .. import obiDicty
18
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()))   
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
31class OWDicty(OWWidget):
32    settingsList = ["serverToken", "platform", "selectedExperiments", "server", "buffertime", "excludeconstant" ]
33    def __init__(self, parent=None, signalManager=None, name="dictyExpress"):
34        OWWidget.__init__(self, parent, signalManager, name)
35        self.outputs = [("Example table", ExampleTable)]
36        self.serverToken = ""
37        self.server = obiDicty.defaddress
38
39        self.platform = None
40
41        self.selectedExperiments = []
42        self.buffer = obiDicty.BufferSQLite(bufferfile)
43
44        self.searchString = ""
45        self.excludeconstant = False
46       
47        box = OWGUI.widgetBox(self.controlArea, "Cache")
48        OWGUI.button(box, self, "Clear cache", callback=self.clear_buffer)
49
50        OWGUI.checkBox(self.controlArea, self, "excludeconstant", "Exclude labels with constant values" )
51
52        OWGUI.button(self.controlArea, self, "&Commit", callback=self.Commit)
53        box  = OWGUI.widgetBox(self.controlArea, "Server")
54        OWGUI.lineEdit(box, self, "serverToken","Token", callback=self.Connect)
55        OWGUI.rubber(self.controlArea)
56
57        OWGUI.lineEdit(self.mainArea, self, "searchString", "Search", callbackOnType=True, callback=self.SearchUpdate)
58        self.experimentsWidget = QTreeWidget()
59        self.experimentsWidget.setHeaderLabels(["Strain", "Treatment", "Growth condition", "Platform", "N", "Chips"]) 
60        self.experimentsWidget.setSelectionMode(QTreeWidget.ExtendedSelection)
61        self.experimentsWidget.setRootIsDecorated(False)
62        self.experimentsWidget.setSortingEnabled(True)
63##        self.experimentsWidget.setAlternatingRowColors(True)
64
65        self.mainArea.layout().addWidget(self.experimentsWidget)
66
67        self.loadSettings()
68        self.dbc = None       
69
70        QTimer.singleShot(0, self.UpdateExperiments)       
71
72        self.resize(800, 600)
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):
79
80        address = self.server + "?"
81        if self.serverToken:
82            address += "token="+self.serverToken+"&"
83        try:
84            #obiDicty.verbose = 1
85            self.dbc = obiDicty.DatabaseConnection(address, buffer=self.buffer)
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
93    def clear_buffer(self):
94        self.buffer.clear()
95        self.UpdateExperiments()
96
97    def UpdateExperiments(self):
98        self.chipsl = []
99        self.experimentsWidget.clear()
100        self.items = []
101
102        if not self.dbc:
103            self.Connect()
104
105        """
106        self.progressBarInit()
107
108        strains = self.dbc.annotationOptions("sample")["sample"]
109
110        for i, strain in enumerate(strains):
111            chips = self.dbc.search("norms", sample=strain)
112            annotations = self.dbc.annotations("norms", chips)
113
114            elements = []
115
116            for chip,annot in zip(chips,annotations):
117                d = dict(annot)
118                elements.append(((d.get("treatment", ""), d.get("growthCond", ""), d.get("platform", "")),chip))
119
120            def different_chips(li):
121                # Returns a map, where keys are different elements in li and values their chip ids
122                dc = defaultdict(list)
123                for a,chip in li:
124                    dc[a].append(chip)
125                return dc
126
127            typeswchips = different_chips(elements) #types with counts
128
129            for (treatment, cond, platforma),cchips in typeswchips.items():
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))
134
135            self.progressBarSet((100.0 * i) / len(strains))
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
161        for i in range(5):
162            self.experimentsWidget.resizeColumnToContents(i)
163
164        self.progressBarFinished()
165
166    def SearchUpdate(self, string=""):
167        for item in self.items:
168            item.setHidden(not all(s in item for s in self.searchString.split()))
169
170    def Commit(self):
171        if not self.dbc:
172            self.Connect()
173        allTables = []
174
175        import time
176        start = time.time()
177
178        pb = OWGUI.ProgressBar(self, iterations=1000)
179
180        table = None
181
182        ids = []
183        for item in self.experimentsWidget.selectedItems():
184            ids += str(item.text(5)).split(",")
185
186        table = self.dbc.get_single_data(ids=ids, callback=pb.advance, exclude_constant_labels=self.excludeconstant)
187
188        end = int(time.time()-start)
189       
190        pb.finish()
191
192        #self.send("Example table", None)
193#        table.taxid = "352472"
194#        table.genesinrows = False
195       
196        from Orange.orng.orngDataCaching import data_hints
197        data_hints.set_hint(table, "taxid", "352472", 10.0)
198        data_hints.set_hint(table, "genesinrows", False, 10.0)
199       
200        self.send("Example table", table)
201
202if __name__ == "__main__":
203    app  = QApplication(sys.argv)
204##    from pywin.debugger import set_trace
205##    set_trace()
206    w = OWDicty()
207    w.show()
208    app.exec_()
209    w.saveSettings()
210           
211       
Note: See TracBrowser for help on using the repository browser.