source: orange-bioinformatics/widgets/OWDicty.py @ 1462:ee4cee02fb85

Revision 1462:ee4cee02fb85, 6.9 KB checked in by markotoplak, 3 years ago (diff)

Bioinformatics widgets name changes, new icon for GeneMANIA.

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