source: orange-bioinformatics/orangecontrib/bio/widgets/OWDicty.py @ 1874:b3e32cc5cf6f

Revision 1874:b3e32cc5cf6f, 7.3 KB checked in by Ales Erjavec <ales.erjavec@…>, 6 months ago (diff)

Added new style widget meta descriptions.

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.BufferSQLite(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
93        address = self.server + "?"
94        if self.serverToken:
95            address += "token="+self.serverToken+"&"
96        try:
97            #obiDicty.verbose = 1
98            self.dbc = obiDicty.DatabaseConnection(address, buffer=self.buffer)
99        except Exception, ex:
100            from traceback import print_exception
101            print_exception(*sys.exc_info())
102            self.error(0, "Error connecting to server" + str(ex))
103            return
104        self.error(0)
105
106    def clear_buffer(self):
107        self.buffer.clear()
108        self.UpdateExperiments()
109
110    def UpdateExperiments(self):
111        self.chipsl = []
112        self.experimentsWidget.clear()
113        self.items = []
114
115        if not self.dbc:
116            self.Connect()
117
118        """
119        self.progressBarInit()
120
121        strains = self.dbc.annotationOptions("sample")["sample"]
122
123        for i, strain in enumerate(strains):
124            chips = self.dbc.search("norms", sample=strain)
125            annotations = self.dbc.annotations("norms", chips)
126
127            elements = []
128
129            for chip,annot in zip(chips,annotations):
130                d = dict(annot)
131                elements.append(((d.get("treatment", ""), d.get("growthCond", ""), d.get("platform", "")),chip))
132
133            def different_chips(li):
134                # Returns a map, where keys are different elements in li and values their chip ids
135                dc = defaultdict(list)
136                for a,chip in li:
137                    dc[a].append(chip)
138                return dc
139
140            typeswchips = different_chips(elements) #types with counts
141
142            for (treatment, cond, platforma),cchips in typeswchips.items():
143                self.chipsl.append(cchips)
144                num = len(cchips)
145                experiment = [strain, treatment, cond, platform, str(num), ','.join(cchips)]
146                self.items.append(MyTreeWidgetItem(self.experimentsWidget, experiment))
147
148            self.progressBarSet((100.0 * i) / len(strains))
149        """
150
151        annotations = self.dbc.annotations("norms", None)
152
153        elements = []
154
155        for chip,annot in annotations:
156            d = dict(annot)
157            elements.append(((d.get("treatment", ""), d.get("growthCond", ""), d.get("platform", ""), d.get("sample", "")),chip))
158
159        def different_chips(li):
160            # Returns a map, where keys are different elements in li and values their chip ids
161            dc = defaultdict(list)
162            for a,chip in li:
163                dc[a].append(chip)
164            return dc
165
166        typeswchips = different_chips(elements) #types with counts
167
168        for (treatment, cond, platform, strain),cchips in typeswchips.items():
169            self.chipsl.append(cchips)
170            num = len(cchips)
171            experiment = [strain, treatment, cond, platform, str(num), ','.join(cchips)] 
172            self.items.append(MyTreeWidgetItem(self.experimentsWidget, experiment))
173
174        for i in range(5):
175            self.experimentsWidget.resizeColumnToContents(i)
176
177        self.progressBarFinished()
178
179    def SearchUpdate(self, string=""):
180        for item in self.items:
181            item.setHidden(not all(s in item for s in self.searchString.split()))
182
183    def Commit(self):
184        if not self.dbc:
185            self.Connect()
186        allTables = []
187
188        import time
189        start = time.time()
190
191        pb = OWGUI.ProgressBar(self, iterations=1000)
192
193        table = None
194
195        ids = []
196        for item in self.experimentsWidget.selectedItems():
197            ids += str(item.text(5)).split(",")
198
199        table = self.dbc.get_single_data(ids=ids, callback=pb.advance, exclude_constant_labels=self.excludeconstant)
200
201        end = int(time.time()-start)
202       
203        pb.finish()
204
205        #self.send("Example table", None)
206#        table.taxid = "352472"
207#        table.genesinrows = False
208       
209        from Orange.orng.orngDataCaching import data_hints
210        data_hints.set_hint(table, "taxid", "352472", 10.0)
211        data_hints.set_hint(table, "genesinrows", False, 10.0)
212       
213        self.send("Example table", table)
214
215if __name__ == "__main__":
216    app  = QApplication(sys.argv)
217##    from pywin.debugger import set_trace
218##    set_trace()
219    w = OWDicty()
220    w.show()
221    app.exec_()
222    w.saveSettings()
223           
224       
Note: See TracBrowser for help on using the repository browser.