This repository has been archived by the owner on Nov 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUI.py
2795 lines (2558 loc) · 165 KB
/
UI.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
###UI
#Copyright 2005-2008 J. David Gladstone Institutes, San Francisco California
#Author Nathan Salomonis - [email protected]
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is furnished
#to do so, subject to the following conditions:
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
#INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
#PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
#HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
#OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
#SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""This module contains fairly generic routines for reading in user interface (UI) instructions from
an existing configuration options file (options.txt), buiding those interfaces, downloading and/or
processing files."""
import math
import statistics
import sys, string
import os.path, platform
import time
import webbrowser
import shutil
import update; reload(update)
import BuildAffymetrixAssociations; reload(BuildAffymetrixAssociations)
import gene_associations; reload(gene_associations)
import export
import unique
import OBO_import
import datetime
import traceback
try:
import WikiPathways_webservice
except Exception:
print 'WikiPathways visualization not supported (requires installation of suds)'
try:
from PIL import Image as PIL_Image
import ImageTk
except Exception:
print 'Python Imaging Library not installed... using default PNG viewer'
from sys import argv
try:
import Tkinter
from Tkinter import *
import PmwFreeze
from Tkconstants import LEFT
import tkMessageBox
import tkFileDialog
except ImportError: print "\nPmw or Tkinter not found... proceeding with manual input"
mac_print_mode = 'no'
if os.name == 'posix': mac_print_mode = 'yes' #os.name is 'posix', 'nt', 'os2', 'mac', 'ce' or 'riscos'
debug_mode = 'no'
def filepath(filename):
fn = unique.filepath(filename)
return fn
def osfilepath(filename):
fn = filepath(filename)
fn = string.replace(fn,'\\','/')
return fn
def read_directory(sub_dir):
dir_list = unique.read_directory(sub_dir); dir_list2 = []
###Code to prevent folder names from being included
for entry in dir_list:
if entry[-4:] == ".txt" or entry[-4:] == ".csv" or ".zip" in entry or '.obo' in entry or '.ontology' in entry: dir_list2.append(entry)
return dir_list2
def readDirText(sub_dir):
dir_list = unique.read_directory(sub_dir); dir_list2 = []
###Code to prevent folder names from being included
for entry in dir_list:
if entry[-4:] == ".txt": dir_list2.append(entry)
return dir_list2
def getFolders(sub_dir):
dir_list = unique.read_directory(sub_dir); dir_list2 = []
###Only get folder names
for entry in dir_list:
if entry[-4:] != ".txt" and entry[-4:] != ".csv" and ".zip" not in entry: dir_list2.append(entry)
return dir_list2
def returnDirectoriesNoReplace(dir):
dir_list = unique.returnDirectoriesNoReplace(dir); dir_list2 = []
for entry in dir_list:
if '.' not in entry: dir_list2.append(entry)
return dir_list2
def returnFilesNoReplace(dir):
dir_list = unique.returnDirectoriesNoReplace(dir); dir_list2 = []
for entry in dir_list:
if '.' in entry: dir_list2.append(entry)
return dir_list2
def cleanUpLine(line):
line = string.replace(line,'\n','')
line = string.replace(line,'\c','')
data = string.replace(line,'\r','')
data = string.replace(data,'"','')
return data
################# GUI #################
def wait(seconds):
### stalls the analysis for the designated number of seconds (allows time to print something to the GUI)
start_time = time.time()
diff = 0
while diff<seconds:
diff = time.time()-start_time
class GUI:
def ViewWikiPathways(self):
""" Canvas is already drawn at this point from __init__ """
global pathway_db
pathway_db={}
button_text = 'Help'
### Create a species drop-down option that can be updated
current_species_names = getSpeciesList()
self.title = 'Select species to search for WikiPathways '
self.option = 'species_wp'
self.options = ['---']+current_species_names #species_list
self.default_option = 0
self.dropDown()
### Create a label that can be updated below the dropdown menu
self.label_name = StringVar()
self.label_name.set('Pathway species list may take several seconds to load')
self.invokeLabel() ### Invoke a new label indicating that the database is loading
### Create a MOD selection drop-down list
null,system_list,mod_list = importSystemInfo()
self.title = 'Select the ID system to translate to (MOD)'
self.option = 'mod_wp'
self.options = mod_list
try: self.default_option = mod_list.index('Ensembl') ### Get the Ensembl index number
except Exception: self.default_option = 0
self.dropDown()
### Create a file selection option
self.title = 'Select GO-Elite input ID text file'
self.notes = 'note: ID file must have a header row and at least three columns:\n'
self.notes += '(1) Identifier, (2) System Code, (3) Value to map (- OR +)\n'
self.file_option = 'goelite_input_file'
self.directory_type = 'file'
self.FileSelectionMenu()
dispaly_pathway = Button(text = 'Display Pathway', command = self.displayPathway)
dispaly_pathway.pack(side = 'right', padx = 10, pady = 10)
back_button = Button(self._parent, text="Back", command=self.goBack)
back_button.pack(side = 'right', padx =10, pady = 5)
quit_win = Button(self._parent, text="Quit", command=self.quit)
quit_win.pack(side = 'right', padx =10, pady = 5)
try: help_button = Button(self._parent, text=button_text, command=self.GetHelpTopLevel); help_button.pack(side = 'left', padx = 5, pady = 5)
except Exception: help_button = Button(self._parent, text=button_text, command=self.linkout); help_button.pack(side = 'left', padx = 5, pady = 5)
self._parent.protocol("WM_DELETE_WINDOW", self.deleteWindow)
self._parent.mainloop()
def FileSelectionMenu(self):
option = self.file_option
group = PmwFreeze.Group(self.parent_type,tag_text = self.title)
group.pack(fill = 'both', expand = 1, padx = 10, pady = 2)
def filecallback(callback=self.callback,option=option): self.getPath(option)
default_option=''
entrytxt = StringVar(); #self.entrytxt.set(self.default_dir)
entrytxt.set(default_option)
self.pathdb[option] = entrytxt
self._user_variables[option] = default_option
entry = Entry(group.interior(),textvariable=self.pathdb[option]);
entry.pack(side='left',fill = 'both', expand = 0.7, padx = 10, pady = 2)
button = Button(group.interior(), text="select "+self.directory_type, width = 10, fg="red", command=filecallback)
button.pack(side=LEFT, padx = 2,pady = 2)
if len(self.notes)>0: ln = Label(self.parent_type, text=self.notes,fg="blue"); ln.pack(padx = 10)
def dropDown(self):
def comp_callback(tag,callback=self.callbackWP,option=self.option):
callback(tag,option)
self.comp = PmwFreeze.OptionMenu(self.parent_type,
labelpos = 'w', label_text = self.title, items = self.options, command = comp_callback)
if self.option == 'wp_id_selection':
self.wp_dropdown = self.comp ### update this variable later (optional)
self.comp.pack(anchor = 'w', padx = 10, pady = 0)
self.comp.invoke(self.default_option) ###Just pick the first option
def comboBox(self):
""" Alternative, more sophisticated UI than dropDown (OptionMenu).
Although it behaves similiar it requires different parameters, can not be
as easily updated with new lists (different method) and requires explict
invokation of callback when a default is set rather than selected. """
def comp_callback(tag,callback=self.callbackWP,option=self.option):
callback(tag,option)
self.comp = PmwFreeze.ComboBox(self.parent_type,
labelpos = 'w', dropdown=1, label_text = self.title,
unique = 0, history = 0,
scrolledlist_items = self.options, selectioncommand = comp_callback)
try: self.comp.component('entryfield_entry').bind('<Button-1>', lambda event, self=self: self.comp.invoke())
except Exception: None ### Above is a slick way to force the entry field to be disabled and invoke the scrolledlist
if self.option == 'wp_id_selection':
self.wp_dropdown = self.comp ### update this variable later (optional)
self.comp.pack(anchor = 'w', padx = 10, pady = 0)
self.comp.selectitem(self.default_option) ###Just pick the first option
self.callbackWP(self.options[0],self.option) ### Explicitly, invoke first option (not automatic)
def invokeLabel(self):
self.label_object = Label(self.parent_type, textvariable=self.label_name,fg="blue"); self.label_object.pack(padx = 10)
def invokeStatusLabel(self):
self.label_object = Label(self.parent_type, textvariable=self.label_status_name,fg="blue"); self.label_object.pack(padx = 10)
def enterMenu(self):
if len(self.notes)>0:
lb = Label(self.parent_type, text=self.notes,fg="black"); lb.pack(pady = 5)
### Create and pack a horizontal RadioSelect widget
def custom_validate(tag,custom_validate=self.custom_validate,option=self.option):
validate = custom_validate(tag,self.option)
self.entry_field = PmwFreeze.EntryField(self.parent_type,
labelpos = 'w', label_text = self.title, validate = custom_validate,
value = self.default_option, hull_borderwidth = 2)
self.entry_field.pack(fill = 'x', expand = 0.7, padx = 10, pady = 5)
def displayPathway(self):
filename = self._user_variables['goelite_input_file']
mod_type = self._user_variables['mod_wp']
species = self._user_variables['species_wp']
pathway_name = self._user_variables['wp_id_selection']
wpid_selected = self._user_variables['wp_id_enter']
species_code = species_codes[species].SpeciesCode()
wpid = None
if len(wpid_selected)>0:
wpid = wpid_selected
elif len(self.pathway_db)>0:
for wpid in self.pathway_db:
if pathway_name == self.pathway_db[wpid].WPName():
break
if len(filename)==0:
print_out = 'Select an input ID file with values first'
WarningWindow(print_out,'Error Encountered!')
else:
try:
self.graphic_link = WikiPathways_webservice.visualizePathwayAssociations(filename,species_code,mod_type,wpid)
self.wp_status = 'Pathway images colored and saved to disk by webservice\n(see image title for location)'
self.label_status_name.set(self.wp_status)
try: self.viewPNGFile() ### ImageTK PNG viewer
except Exception:
try: self.openPNGImage() ### OS default PNG viewer
except Exception:
self.wp_status = 'Unable to open PNG file using operating system'
self.label_status_name.set(self.wp_status)
except Exception,e:
try:
wp_logfile = filepath('webservice.log')
wp_report = open(wp_logfile,'a')
wp_report.write(traceback.format_exc())
except Exception:
None
try:
print traceback.format_exc()
except Exception:
null=None ### Occurs when transitioning back from the Official Database download window (not sure why) -- should be fixed in 1.2.5 (sys.stdout not re-routed)
if 'force_no_matching_error' in traceback.format_exc():
print_out = 'None of the input IDs mapped to this pathway'
elif 'force_invalid_pathway' in traceback.format_exc():
print_out = 'Invalid pathway selected'
elif 'IndexError' in traceback.format_exc():
print_out = 'Input ID file does not have at least 3 columns, with the second column being system code'
elif 'ValueError' in traceback.format_exc():
print_out = 'Input ID file error. Please check that you do not have extra rows with no data'
elif 'source_data' in traceback.format_exc():
print_out = 'Input ID file does not contain a valid system code'
else:
print_out = 'Error generating the pathway "%s"' % pathway_name
WarningWindow(print_out,'Error Encountered!')
def getSpeciesPathways(self,species_full):
pathway_list=[]
self.pathway_db = WikiPathways_webservice.getAllSpeciesPathways(species_full)
for wpid in self.pathway_db:
pathway_list.append(self.pathway_db[wpid].WPName())
pathway_list = unique.unique(pathway_list)
pathway_list.sort()
return pathway_list
def callbackWP(self, tag, option):
#print 'Button',[option], tag,'was pressed.'
self._user_variables[option] = tag
if option == 'species_wp':
### Add additional menu options based on user selection
if tag != '---':
### If this already exists from an earlier iteration
hault = False
self.label_name.set('Loading available WikiPathways')
try:
self.pathway_list=self.getSpeciesPathways(tag)
traceback_printout = ''
except Exception,e:
if 'not supported' in traceback.format_exc():
print_out = 'Species not available at WikiPathways'
WarningWindow(print_out,'Species Not Found!')
traceback_printout=''
hault = True
elif 'URLError' in traceback.format_exc():
print_out = 'Internet connection could not be established'
WarningWindow(print_out,'Internet Error')
traceback_printout=''
hault = True
else:
traceback_printout = traceback.format_exc()
try:
if len(self.pathway_list)>0: ### When true, a valid species was selected in a prior interation invoking the WP fields (need to repopulate)
hault = False
except Exception: None
self.pathway_list = ['None']; self.pathway_db={}
self.label_name.set('')
if hault == False:
try:
### If the species specific wikipathways drop down exists, just update it
self.wp_dropdown._list.setlist(self.pathway_list)
self.wp_dropdown.selectitem(self.pathway_list[0])
self.callbackWP(self.pathway_list[0],'wp_id_selection')
except Exception:
### Create a species specific wikipathways drop down
self.option = 'wp_id_selection'
self.title = 'Select WikiPathways to visualize your data'
if len(traceback_printout)>0:
self.title += traceback_printout ### Display the actual problem in the GUI (sloppy but efficient way for users to indicate the missing driver)
self.options = self.pathway_list
self.default_option = 0
self.comboBox() ### Better UI for longer lists of items (dropDown can't scroll on Linux)
### Create a species specific wikipathways ID enter option
self.notes = 'OR'
self.option = 'wp_id_enter'
self.title = 'Enter the WPID (example: WP254) '
self.default_option = ''
self.enterMenu()
try:
### Create a label that can be updated below the dropdown menu
self.wp_status = 'Pathway image may take several seconds to a minute to load...\n'
self.wp_status += '(images saved to "WikiPathways" folder in input directory)'
try: self.label_status_name.set(self.wp_status)
except Exception:
self.label_status_name = StringVar()
self.label_status_name.set(self.wp_status)
self.invokeStatusLabel() ### Invoke a new label indicating that the database is loading
except Exception:
None
if option == 'wp_id_selection':
### Reset any manually input WPID if a new pathway is selected from dropdown
try: self.entry_field.setentry('')
except Exception: null=[]
def viewPNGFile(self):
""" View PNG file within a PMW Tkinter frame """
import ImageTk ### HAVE TO CALL HERE TO TRIGGER AN ERROR - DON'T WANT THE TopLevel to open otherwise
png_file_dir = self.graphic_link['WP']
img = ImageTk.PhotoImage(file=png_file_dir)
tl = Toplevel()
sf = PmwFreeze.ScrolledFrame(tl, labelpos = 'n', label_text = '',
usehullsize = 1, hull_width = 800, hull_height = 550)
sf.pack(padx = 0, pady = 0, fill = 'both', expand = 1)
frame = sf.interior()
tl.title(png_file_dir)
can = Canvas(frame)
can.pack(fill=BOTH, padx = 0, pady = 0)
w = img.width()
h = height=img.height()
can.config(width=w, height=h)
can.create_image(2, 2, image=img, anchor=NW)
tl.mainloop()
def openPNGImage(self):
png_file_dir = self.graphic_link['WP']
if os.name == 'nt':
try: os.startfile('"'+png_file_dir+'"')
except Exception: os.system('open "'+png_file_dir+'"')
elif 'darwin' in sys.platform: os.system('open "'+png_file_dir+'"')
elif 'linux' in sys.platform: os.system('xdg-open "'+png_file_dir+'"')
def __init__(self, parent, option_db, option_list):
self._parent = parent; self._option_list = option_list
self._user_variables = user_variables
self.default_dir = PathDir; self.default_file = PathFile
self.option_db = option_db
filename = 'Config/icon.gif'
fn=filepath(filename); img = PhotoImage(file=fn)
can = Canvas(parent); can.pack(side='top'); can.config(width=img.width(), height=img.height())
can.create_image(2, 2, image=img, anchor=NW)
self.pathdb={}; use_scroll = 'no'
label_text_str = "\nGO-Elite Program Options"
if os.name == 'nt': height = 400; width = 420
else: height = 350; width = 480
if option_db == 'ViewWikiPathways': width = 520
use_scroll = 'yes'
if 'run_from_scratch' in option_list or 'modifyDBs1' in option_list:
if 'modifyDBs1' in option_list and os.name != 'nt': width = 460; height = 350
else: width = 400; height = 325
if 'selected_species3' in option_list:
height -= 30
if os.name != 'nt':height+=50; width+=50
self.sf = PmwFreeze.ScrolledFrame(self._parent,
labelpos = 'n', label_text = label_text_str,
usehullsize = 1, hull_width = width, hull_height = height)
self.sf.pack(padx = 5, pady = 1, fill = 'both', expand = 1)
self.frame = self.sf.interior()
parent_type = self.frame
self.parent_type = parent_type
i = 0; object_directions = ['top','bottom','up','down']
if option_db == 'ViewWikiPathways':
self.ViewWikiPathways()
for option in option_list:
if option in self.option_db:
od = self.option_db[option]; self.title = od.Display(); description = od.Description()
self.display_options = od.AnalysisOptions()
if 'radio' in od.DisplayObject() and self.display_options != ['NA']:
### Create and pack a RadioSelect widget, with radiobuttons.
self._option = option
def radiocallback(tag,callback=self.callback,option=option): callback(tag,option)
radiobuttons = PmwFreeze.RadioSelect(parent_type,
buttontype = 'radiobutton', orient = 'vertical',
labelpos = 'w', command = radiocallback, label_text = self.title,
hull_borderwidth = 2, hull_relief = 'ridge',
);
if description in object_directions: direction = description ### can be used to store directions
else: direction = 'top'
radiobuttons.pack(side = direction, expand = 1, padx = 10, pady = 5)
### print self.display_options
### Add some buttons to the radiobutton RadioSelect.
for text in self.display_options:
if text != ['NA']: radiobuttons.add(text)
self.default_option = od.DefaultOption()
radiobuttons.invoke(self.default_option)
if 'button' in od.DisplayObject() and self.display_options != ['NA']:
self._option = option
### Create and pack a horizontal RadioSelect widget.
self.default_option = od.DefaultOption()
if mac_print_mode == 'yes':
button_type = 'radiobutton'
if self._option == 'run_from_scratch':
self.title = self.title[:int(len(self.title)/1.8)] ### On a mac, the spaced text is too far out
if self._option == 'modifyDBs1':
self.title = self.title[:int(len(self.title)/1.3)] ### On a mac, the spaced text is too far out
else: button_type = 'button'
def buttoncallback(tag,callback=self.callback,option=option):
callback(tag,option)
horiz = PmwFreeze.RadioSelect(parent_type, buttontype = button_type, orient = 'vertical',
labelpos = 'w', command = buttoncallback,
label_text = self.title, frame_borderwidth = 2,
frame_relief = 'ridge'
); horiz.pack(fill = 'x', padx = 10, pady = 10)
### Add some buttons to the horizontal RadioSelect
for text in self.display_options:
if text != ['NA']: horiz.add(text)
horiz.invoke(self.default_option)
if ('folder' in od.DisplayObject() or 'file' in od.DisplayObject()) and self.display_options != ['NA']:
proceed = 'yes'
if option == 'mappfinder_dir' and run_mappfinder == 'yes': proceed = 'no'
if proceed == 'yes':
self._option = option
if option == 'output_dir':
if run_mappfinder == 'no':
notes = ""#"note: if not selected, 'input/MAPPFinder' will\nbe used and results written to 'output/' "
self.title = string.replace(self.title,'output','pre-computed ORA')
else: notes = od.Description()
else: notes = od.Description()
group = PmwFreeze.Group(parent_type,tag_text = self.title)
group.pack(fill = 'both', expand = 1, padx = 10, pady = 2)
def filecallback(callback=self.callback,option=option): self.getPath(option)
entrytxt = StringVar(); #self.entrytxt.set(self.default_dir)
default_option = string.replace(od.DefaultOption(),'---','')
entrytxt.set(default_option)
self.pathdb[option] = entrytxt
self._user_variables[option] = default_option
#l = Label(group.interior(), text=self.title); l.pack(side=LEFT)
entry = Entry(group.interior(),textvariable=self.pathdb[option]);
entry.pack(side='left',fill = 'both', expand = 1, padx = 10, pady = 2)
button = Button(group.interior(), text="select "+od.DisplayObject(), width = 10, fg="red", command=filecallback)
button.pack(side=LEFT, padx = 2,pady = 2)
#print option,run_mappfinder, self.title, self.default_option
if len(notes)>0: ln = Label(parent_type, text=notes,fg="blue"); ln.pack(padx = 10)
if 'drop-down' in od.DisplayObject() and self.display_options != ['NA']:
self._option = option
self.default_option = self.display_options
def comp_callback1(tag,callback=self.callback,option=option):
callback(tag,option)
self.comp = PmwFreeze.OptionMenu(parent_type,
labelpos = 'w', label_text = self.title,
items = self.default_option, command = comp_callback1)
if 'species' in option:
if 'selected_species2' in option:
self.speciescomp2 = self.comp; self.speciescomp2.pack(anchor = 'w', padx = 10, pady = 0)
elif 'selected_species3' in option:
self.speciescomp3 = self.comp; self.speciescomp3.pack(anchor = 'w', padx = 10, pady = 0)
else: self.speciescomp = self.comp; self.speciescomp.pack(anchor = 'w', padx = 10, pady = 0)
try: self.speciescomp.invoke(od.DefaultOption()) ###Just pick the first option
except Exception: self.speciescomp.invoke(self.default_option[0])
else:
self.comp.pack(anchor = 'w', padx = 10, pady = 0)
try: self.comp.invoke(od.DefaultOption()) ###Just pick the first option
except Exception: self.comp.invoke(self.default_option[0])
if len(od.Description())>0 and od.Description() != 'top':
ln = Label(parent_type, text=od.Description(),fg="blue"); ln.pack(padx = 10)
if option == 'selected_version':
notes = 'Note: Available species may vary based on database selection and\n'
notes+= '"Plus" versions have additional Affymetrix & EntrezGene relationships\n'
ln = Label(parent_type, text=notes,fg="blue"); ln.pack(padx = 10)
if 'comboBox' in od.DisplayObject() and self.display_options != ['NA']:
self._option = option
self.default_option = self.display_options
def comp_callback1(tag,callback=self.callbackComboBox,option=option):
callback(tag,option)
self.comp = PmwFreeze.ComboBox(parent_type,
labelpos = 'w', dropdown=1, label_text = self.title,
unique = 0, history = 0,
scrolledlist_items = self.default_option,
selectioncommand = comp_callback1)
if 'species' in option:
if 'selected_species2' in option:
self.speciescomp2 = self.comp; self.speciescomp2.pack(anchor = 'w', padx = 10, pady = 0)
try: self.speciescomp2.component('entryfield_entry').bind('<Button-1>', lambda event, self=self: self.speciescomp2.invoke())
except Exception: None ### Above is a slick way to force the entry field to be disabled and invoke the scrolledlist
try:
self.speciescomp2.selectitem(od.DefaultOption())
self.callbackComboBox(od.DefaultOption(),option)
except Exception:
self.speciescomp2.selectitem(self.default_option[0]) ###Just pick the first option
self.callbackComboBox(self.default_option[0],option)
elif 'selected_species3' in option:
self.speciescomp3 = self.comp; self.speciescomp3.pack(anchor = 'w', padx = 10, pady = 0)
try: self.speciescomp3.component('entryfield_entry').bind('<Button-1>', lambda event, self=self: self.speciescomp3.invoke())
except Exception: None ### Above is a slick way to force the entry field to be disabled and invoke the scrolledlist
try:
self.speciescomp3.selectitem(od.DefaultOption()) ###Just pick the first option
self.callbackComboBox(od.DefaultOption(),option)
except Exception:
self.speciescomp3.selectitem(self.default_option[0])
self.callbackComboBox(self.default_option[0],option)
else:
self.speciescomp = self.comp; self.speciescomp.pack(anchor = 'w', padx = 10, pady = 0)
try: self.speciescomp.component('entryfield_entry').bind('<Button-1>', lambda event, self=self: self.speciescomp.invoke())
except Exception: None ### Above is a slick way to force the entry field to be disabled and invoke the scrolledlist
try:
self.speciescomp.selectitem(od.DefaultOption())
self.callbackComboBox(od.DefaultOption(),option)
except Exception:
self.speciescomp.selectitem(self.default_option[0])
self.callbackComboBox(self.default_option[0],option)
else:
self.combo = self.comp ### has to be a unique combo box to refer to itself in the component call below
self.combo.pack(anchor = 'w', padx = 10, pady = 1)
try: self.combo.component('entryfield_entry').bind('<Button-1>', lambda event, self=self: self.combo.invoke())
except Exception: None ### Above is a slick way to force the entry field to be disabled and invoke the scrolledlist
try:
self.combo.selectitem(od.DefaultOption())
self.callbackComboBox(od.DefaultOption(),option)
except Exception:
self.combo.selectitem(self.default_option[0])
self.callbackComboBox(self.default_option[0],option)
if len(od.Description())>0 and od.Description() != 'top':
ln = Label(parent_type, text=od.Description(),fg="blue"); ln.pack(padx = 10)
if option == 'selected_version':
notes = 'Note: Available species may vary based on database selection and\n'
notes+= '"Plus" versions have additional Affymetrix & EntrezGene relationships\n'
ln = Label(parent_type, text=notes,fg="blue"); ln.pack(padx = 10)
if 'label' in od.DisplayObject() and self.display_options != ['NA']:
ln = Label(parent_type, text=self.title,fg="blue"); ln.pack(padx = 10)
if 'enter' in od.DisplayObject() and self.display_options != ['NA']:
self._option = option
### Create and pack a horizontal RadioSelect widget.
self.default_option = od.DefaultOption()
#print self.default_option, self.title; kill
def custom_validate(tag,custom_validate=self.custom_validate,option=option):
validate = custom_validate(tag,option)
def custom_validate_p(tag,custom_validate_p=self.custom_validate_p,option=option):
validate = custom_validate_p(tag,option)
#print [validate], tag, option
try:
if float(self.default_option) <= 1: use_method = 'p'
else: use_method = 'i'
except ValueError:
use_method = 'i'
if use_method == 'p':
self.entry_field = PmwFreeze.EntryField(parent_type,
labelpos = 'w',
label_text = self.title,
validate = custom_validate,
value = self.default_option, hull_borderwidth = 2, hull_relief = 'ridge'
); self.entry_field.pack(fill = 'x', expand = 1, padx = 10, pady = 10)
if use_method == 'i':
self.entry_field = PmwFreeze.EntryField(parent_type,
labelpos = 'w',
label_text = self.title,
validate = custom_validate,
value = self.default_option, hull_borderwidth = 2, hull_relief = 'ridge'
); self.entry_field.pack(fill = 'x', expand = 1, padx = 10, pady = 10)
if len(od.Description())>0:
ln = Label(parent_type, text=od.Description(),fg="red"); ln.pack(padx = 10)
if 'multiple-checkbox' in od.DisplayObject() and self.display_options != ['NA']:
self._option = option
self.default_option = od.DefaultOption()
### Create and pack a vertical RadioSelect widget, with checkbuttons.
self.checkbuttons = PmwFreeze.RadioSelect(parent_type,
buttontype = 'checkbutton', orient = 'vertical',
labelpos = 'w', command = self.checkbuttoncallback,
label_text = self.title, hull_borderwidth = 2, hull_relief = 'ridge',
); self.checkbuttons.pack(side = 'top', expand = 1, padx = 10, pady = 10)
### Add some buttons to the checkbutton RadioSelect.
for text in self.display_options:
if text != ['NA']: self.checkbuttons.add(text)
self.checkbuttons.invoke(self.default_option)
self.checkbuttons.invoke(self.default_option2)
if 'single-checkbox' in od.DisplayObject() and self.display_options != ['NA']:
self._option = option
proceed = 'yes'
"""if option == 'export_splice_index_values':
if analysis_method != 'splicing-index': proceed = 'no' ### only export corrected constitutive ratios if splicing index method chosen"""
if proceed == 'yes':
self.default_option = od.DefaultOption()
if self.default_option != 'NA':
def checkbuttoncallback(tag,state,checkbuttoncallback=self.checkbuttoncallback,option=option):
checkbuttoncallback(tag,state,option)
### Create and pack a vertical RadioSelect widget, with checkbuttons. hull_relief
self.checkbuttons = PmwFreeze.RadioSelect(parent_type,
buttontype = 'checkbutton', command = checkbuttoncallback,
hull_borderwidth = 2,
); self.checkbuttons.pack(side = 'top', expand = 1, padx = 10, pady = 10)
### Add some buttons to the checkbutton RadioSelect.
self.checkbuttons.add(self.title)
if self.default_option == 'yes': self.checkbuttons.invoke(self.title)
else: self._user_variables[option] = 'no'
i+=1 ####Keep track of index
if len(option_list)>0:
if 'process_go' in option_list: ### For the CEL file selection window, provide a link to get Annotation files
button_text = 'Download Annotation CSVs'; d_url = 'http://www.affymetrix.com/support/technical/byproduct.affx?cat=arrays'
self.d_url = d_url; text_button = Button(self._parent, text=button_text, command=self.Dlinkout); text_button.pack(side = 'left', padx = 5, pady = 5)
if 'permutation' in option_list:
#ScrolledCanvas().mainloop()
systemCodes_win = Button(parent_type, text="GO-Elite Supported System Codes", command=self.systemCodes)
systemCodes_win.pack(side = 'bottom', padx = 5, pady = 5)
if 'new_species_name' in option_list:
button_text = 'Lookup Species TaxID'; d_url = 'http://www.ncbi.nlm.nih.gov/sites/entrez?db=taxonomy'
self.d_url = d_url; text_button = Button(self._parent, text=button_text, command=self.Dlinkout); text_button.pack(side = 'left', padx = 5, pady = 5)
continue_to_next_win = Button(text = 'Continue', command = self._parent.destroy)
continue_to_next_win.pack(side = 'right', padx = 10, pady = 10)
back_button = Button(self._parent, text="Back", command=self.goBack)
back_button.pack(side = 'right', padx =10, pady = 5)
quit_win = Button(self._parent, text="Quit", command=self.quit)
quit_win.pack(side = 'right', padx =10, pady = 5)
button_text = 'Help'
url = 'http://www.genmapp.org/go_elite/help_main.htm'; self.url = url
pdf_help_file = 'Documentation/GO-Elite_Manual.pdf'; pdf_help_file = filepath(pdf_help_file); self.pdf_help_file = pdf_help_file
try: help_button = Button(self._parent, text=button_text, command=self.GetHelpTopLevel); help_button.pack(side = 'left', padx = 5, pady = 5)
except Exception: help_button = Button(self._parent, text=button_text, command=self.linkout); help_button.pack(side = 'left', padx = 5, pady = 5)
self._parent.protocol("WM_DELETE_WINDOW", self.deleteWindow)
self._parent.mainloop()
def goBack(self):
self._parent.destroy()
if 'filter_method' in self._option_list: run_parameter = 'ORA',self._user_variables
else: run_parameter = 'skip'
reload(GO_Elite); GO_Elite.importGOEliteParameters(run_parameter); sys.exit()
def GetHelpTopLevel(self):
message = ''
self.message = message; self.online_help = 'Online Documentation'; self.pdf_help = 'Local PDF File'
tl = Toplevel(); self._tl = tl; nulls = '\t\t\t\t'; tl.title('Please select one of the options')
self.sf = PmwFreeze.ScrolledFrame(self._tl,
labelpos = 'n', label_text = '',
usehullsize = 1, hull_width = 220, hull_height = 150)
self.sf.pack(padx = 10, pady = 10, fill = 'both', expand = 1)
self.frame = self.sf.interior()
group = PmwFreeze.Group(self.sf.interior(),tag_text = 'Options')
group.pack(fill = 'both', expand = 1, padx = 20, pady = 10)
l1 = Label(group.interior(), text=nulls); l1.pack(side = 'bottom')
text_button2 = Button(group.interior(), text=self.online_help, command=self.openOnlineHelp); text_button2.pack(side = 'top', padx = 5, pady = 5)
try: text_button = Button(group.interior(), text=self.pdf_help, command=self.openPDFHelp); text_button.pack(side = 'top', padx = 5, pady = 5)
except Exception: text_button = Button(group.interior(), text=self.pdf_help, command=self.openPDFHelp); text_button.pack(side = 'top', padx = 5, pady = 5)
tl.mainloop()
def openPDFHelp(self):
if os.name == 'nt':
try: os.startfile('"'+self.pdf_help_file+'"')
except Exception: os.system('open "'+self.pdf_help_file+'"')
elif 'darwin' in sys.platform: os.system('open "'+self.pdf_help_file+'"')
elif 'linux' in sys.platform: os.system('xdg-open "'+self.pdf_help_file+'"')
self._tl.destroy()
def openOnlineHelp(self):
try: webbrowser.open(self.url)
except Exception: null=[]
self._tl.destroy()
def linkout(self):
try: webbrowser.open(self.url)
except Exception: null=[]
def Dlinkout(self):
try: webbrowser.open(self.d_url)
except Exception: null=[]
def setvscrollmode(self, tag):
self.sf.configure(vscrollmode = tag)
def systemCodes(self):
selected_species = self._user_variables['species']
species_systems = getSpeciesSystems(selected_species)
GO_Elite.sourceData()
about = "System Name"+'\t\t'+"System Code"+'\t\t'+"MOD"+'\n'
system_list=[]
for system_name in system_codes:
sc = system_codes[system_name]
if system_name in species_systems: ### Restrict by species
system_list.append([system_name,sc.SystemCode(),sc.MOD()])
system_list.sort()
for (system_name,system_code,mod) in system_list:
filler = ' '; filler2=''
if os.name == 'nt':
if platform.win32_ver()[0] != 'Vista': val = 9; val2 = 14; val3 = 19
else: val = 12; val2 = 17; val3 = 20
else: val = 12; val2 = 17; val3 = 20
if os.name == 'nt':
if len(system_name)<val: filler = val2-len(system_name); filler = filler*' '+' '
if len(mod)<val: filler2 = val3-len(mod); filler2 = filler2*' '
about+= system_name+filler+'\t\t'+system_code+filler2+'\t\t'+mod+'\n'
#tkMessageBox.showinfo("Available GO-Elite System Codes",about,parent=self._parent)
dialog = PmwFreeze.TextDialog(self._parent, scrolledtext_labelpos = 'n',
title = 'GO-Elite System Codes', defaultbutton = 0,
label_text = 'Available System Information for '+selected_species)
dialog.insert('end', about)
def info(self):
tkMessageBox.showinfo("title","message",parent=self._parent)
def deleteWindow(self):
#tkMessageBox.showwarning("Quit","Use 'Quit' button to end program!",parent=self._parent)
self._parent.destroy(); sys.exit() ### just quit instead
def quit(self):
#print "quit starts"
#print "cleaning up things..."
self._parent.quit()
self._parent.destroy()
sys.exit()
#print "quit ends"
def chooseDirectory(self,option):
tag = tkFileDialog.askdirectory(parent=self._parent)
#print option,tag
self._user_variables[option] = tag
#tkFileDialog.askopenfile(parent=self._parent)
def getPath(self,option):
if 'dir' in option or 'folder' in option:
try: dirPath = tkFileDialog.askdirectory(parent=self._parent,initialdir=self.default_dir)
except Exception:
self.default_dir = ''
try: dirPath = tkFileDialog.askdirectory(parent=self._parent,initialdir=self.default_dir)
except Exception:
try: dirPath = tkFileDialog.askdirectory(parent=self._parent)
except Exception: dirPath=''
self.default_dir = dirPath
entrytxt = self.pathdb[option]
entrytxt.set(dirPath)
self._user_variables[option] = dirPath
try: file_location_defaults['PathDir'].SetLocation(dirPath)
except Exception: null = None
exportDefaultFileLocations(file_location_defaults)
### Allows the option_db to be updated for the next round (if an error is encountered)
if 'file' in option:
try: tag = tkFileDialog.askopenfile(parent=self._parent,initialdir=self.default_file)
except Exception:
self.default_file = ''
try: tag = tkFileDialog.askopenfile(parent=self._parent,initialdir=self.default_file)
except Exception:
try: tag = tkFileDialog.askopenfile(parent=self._parent)
except Exception: tag=''
try: filePath = tag.name #initialdir=self.default_dir
except AttributeError: filePath = ''
filePath_dir = string.join(string.split(filePath,'/')[:-1],'/')
self.default_file = filePath_dir
entrytxt = self.pathdb[option]
entrytxt.set(filePath)
self._user_variables[option] = filePath
try: file_location_defaults['PathFile'].SetLocation(filePath_dir)
except Exception: null = None
exportDefaultFileLocations(file_location_defaults)
def Report(self,tag,option):
output = tag
return output
def __repr__(self,tag,option): return self.Report(tag,option)
def Results(self): return self._user_variables
def custom_validate(self, text, option):
#print [option],'text:', text
self._user_variables[option] = text
try:
text = float(text);return 1
except ValueError: return -1
def custom_validate_p(self, text, option):
#print [option],'text:', text
self._user_variables[option] = text
try:
text = float(text)
if text <1:return 1
else:return -1
except ValueError:return -1
def callback(self, tag, option):
#print 'Button',[option], tag,'was pressed.'
self._user_variables[option] = tag
if option == 'ORA_algorithm':
if tag == 'Permute p-value':
try: self.entry_field.setentry('2000')
except Exception: null=[]
self._user_variables['permutation'] = '2000'
elif tag == 'Fisher Exact Test':
try: self.entry_field.setentry('NA')
except Exception: null=[]
self._user_variables['permutation'] = '0'
if option == 'dbase_version':
###Export new species info
exportDBversion(tag)
current_species_names = getSpeciesList()
### THIS TOOK FOR EVER TO FIND!!!!!! setitems of the PMW object resets the value list
if 'permutation' in self._option_list:
try: self.speciescomp.setitems(current_species_names)
except Exception: null = [] ### Occurs before speciescomp is declared when dbase_version pulldown is first intiated
else:
try: self.speciescomp.setitems(['all-supported','New Species','---']+current_species_names)
except Exception: null = [] ### Occurs before speciescomp is declared when dbase_version pulldown is first intiated
for i in self._option_list:
var = 'proceed'
if 'species' in i: ### Necessary if the user changes dbase_version and selects continue to accept the displayed species name (since it's note directly invoked)
if 'species' in self._user_variables:
if self._user_variables[i] in current_species_names: var = None
if var == 'proceed':
try: self._user_variables[i] = current_species_names[0]
except Exception: null = []
elif option == 'selected_version':
current_species_names = db_versions[tag]
current_species_names.sort()
try: self.speciescomp.setitems(['---']+current_species_names)
except Exception: null = [] ### Occurs before speciescomp is declared when dbase_version pulldown is first intiated
try: self.speciescomp2.setitems(['---']+current_species_names)
except Exception: null = [] ### Occurs before speciescomp is declared when dbase_version pulldown is first intiated
try: self.speciescomp3.setitems(['---']+current_species_names)
except Exception: null = [] ### Occurs before speciescomp is declared when dbase_version pulldown is first intiated
def callbackComboBox(self, tag, option):
""" Similiar to the above, callback, but ComboBox uses unique methods """
#print 'Button',[option], tag,'was pressed.'
self._user_variables[option] = tag
if option == 'selected_version':
current_species_names = db_versions[tag]
current_species_names.sort()
current_species_names = ['---']+current_species_names
species_option = current_species_names[0]
try:
self.speciescomp._list.setlist(current_species_names) ### This is the way we set a new list for ComboBox
### Select the best default option to display (keep existing or re-set)
if 'selected_species1' in self._user_variables: ### If this is the species downloader
species_option = 'selected_species1'
else:
for i in self._user_variables:
if 'species' in i: species_option = i
default = self.getBestDefaultSelection(species_option,current_species_names)
self.speciescomp.selectitem(default)
except Exception: None ### Occurs before speciescomp is declared when dbase_version pulldown is first intiated
try:
self.speciescomp2._list.setlist(current_species_names)
default = self.getBestDefaultSelection('selected_species2',current_species_names)
self.speciescomp2.selectitem(default)
except Exception: None ### Occurs before speciescomp is declared when dbase_version pulldown is first intiated
try:
self.speciescomp3._list.setlist(current_species_names)
default = self.getBestDefaultSelection('selected_species3',current_species_names)
self.speciescomp3.selectitem(default)
except Exception: None ### Occurs before speciescomp is declared when dbase_version pulldown is first intiated
def getBestDefaultSelection(self,option,option_list):
default = option_list[0] ### set the default to the first option listed
if option in self._user_variables:
selected = self._user_variables[option]
if selected in option_list: ### If selected species exists in the new selected version of EnsMart
default = selected
else:
self._user_variables[option] = default ### Hence, the default has changed, so re-set it
return default
def multcallback(self, tag, state):
if state: action = 'pressed.'
else: action = 'released.'
"""print 'Button', tag, 'was', action, \
'Selection:', self.multiple.getcurselection()"""
self._user_variables[option] = tag
def checkbuttoncallback(self, tag, state, option):
if state: action = 'pressed.'
else: action = 'released.'
"""print 'Button',[option], tag, 'was', action, \
'Selection:', self.checkbuttons.getcurselection()"""
if state==0: tag2 = 'no'
else: tag2 = 'yes'
#print '---blahh', [option], [tag], [state], [action], [self.checkbuttons.getcurselection()]
self._user_variables[option] = tag2
def getSpeciesList():
try: current_species_dirs = unique.read_directory('/Databases')
except Exception: ### Occurs when the version file gets over-written with a bad directory name
try:
### Remove the version file and wipe the species file
os.remove(filepath('Config/version.txt'))
raw = export.ExportFile('Config/species.txt'); raw.close()
os.mkdir(filepath('Databases'))
except Exception: null = []
elite_db_versions = returnDirectoriesNoReplace('/Databases')
try: exportDBversion(elite_db_versions[0])
except Exception: exportDBversion('')
current_species_dirs = unique.read_directory('/Databases')
current_species_names=[]
for species in species_codes:
if species_codes[species].SpeciesCode() in current_species_dirs: current_species_names.append(species)
current_species_names.sort()
return current_species_names
def exportDBversion(db_version):
today = str(datetime.date.today()); today = string.split(today,'-'); today = today[1]+'/'+today[2]+'/'+today[0]
OBO_import.exportVersionData(db_version,today,'Config/')
def getSpeciesSystems(species):
species_code = species_codes[species].SpeciesCode()
import_dir1 = '/Databases/'+species_code+'/uid-gene'
import_dir2 = '/Databases/'+species_code+'/gene-mapp'
import_dir3 = '/Databases/'+species_code+'/gene-go'
try: uid_gene_list = read_directory(import_dir1)
except Exception: uid_gene_list=[]
try: gene_mapp_list = read_directory(import_dir2)
except Exception: gene_mapp_list=[]
try: gene_go_list = read_directory(import_dir3)
except Exception: gene_go_list=[]
uid_gene_list+=gene_mapp_list+gene_go_list
systems=[]