source: orange-bioinformatics/orangecontrib/bio/widgets/OWDicty.py @ 2053:c25fb8a4dbbb

Revision 2053:c25fb8a4dbbb, 7.3 KB checked in by markotoplak, 6 days ago (diff)

Renamed BufferSQLite -> CacheSQLite. dicty documentation updates.

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