-
Notifications
You must be signed in to change notification settings - Fork 30
/
UI.py
executable file
·7466 lines (6919 loc) · 428 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.
import math
from stats_scripts import statistics
import sys, string
import shutil
import os.path
import unique
import update; reload(update)
import export
import ExpressionBuilder
import time
import webbrowser
import traceback
import AltAnalyze
from sys import argv
"""
import numpy
import scipy
from PIL import Image as PIL_Image
import ImageTk
import matplotlib
import matplotlib.pyplot as pylab
"""
try:
try:
from visualization_scripts import WikiPathways_webservice
except Exception:
#print traceback.format_exc()
if 'URLError' in traceback.format_exc():
print 'No internet connection found'
else:
print 'WikiPathways visualization not supported (requires installation of suds)'
try:
from PIL import Image as PIL_Image
try: import ImageTk
except Exception: from PIL import ImageTk
import PIL._imaging
import PIL._imagingft
except Exception:
print traceback.format_exc()
#print 'Python Imaging Library not installed... using default PNG viewer'
None
try:
### Only used to test if matplotlib is installed
#import matplotlib
#import matplotlib.pyplot as pylab
None
except Exception:
#print traceback.format_exc()
print 'Graphical output mode disabled (requires matplotlib, numpy and scipy)'
None
except Exception:
None
command_args = string.join(sys.argv,' ')
if len(sys.argv[1:])>1 and '-' in command_args and '--GUI' not in command_args:
runningCommandLine = True
else:
runningCommandLine = False
try:
import Tkinter
#import bwidget; from bwidget import *
from Tkinter import *
from visualization_scripts import PmwFreeze
from Tkconstants import LEFT
import tkMessageBox
import tkFileDialog
except Exception: 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)
return dir_list
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 and 'affymetrix' not in entry:
if 'EnsMart' 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 identifyCELfiles(dir,array_type,vendor):
dir_list = read_directory(dir); dir_list2=[]; full_dir_list=[]
datatype = 'arrays'
types={}
for file in dir_list:
original_file = file
file_lower = string.lower(file); proceed = 'no'
### "._" indicates a mac alias
if ('.cel' in file_lower[-4:] and '.cel.' not in file_lower) and file_lower[:2] != '._':
proceed = 'yes'
elif ('.bed' in file_lower[-4:] or '.tab' in file_lower or '.junction_quantification.txt' in file_lower or '.bam' in file_lower) and file_lower[:2] != '._' and '.bai' not in file_lower:
proceed = 'yes'
datatype = 'RNASeq'
elif array_type == "3'array" and '.cel' not in file_lower[-4:] and '.txt' in file_lower[-4:] and vendor != 'Affymetrix':
proceed = 'yes'
if proceed == 'yes':
if '__' in file and '.cel' not in string.lower(file):
#print file,string.split(file,'__'),file[-4:]
file=string.split(file,'__')[0]+file[-4:]
if '.tab' in original_file: file = string.replace(file,'.txt','.tab')
elif '.bed' in original_file: file = string.replace(file,'.txt','.bed')
if '.TAB' in original_file: file = string.replace(file,'.txt','.TAB')
elif '.BED' in original_file: file = string.replace(file,'.txt','.BED')
dir_list2.append(file)
file = dir+'/'+file
full_dir_list.append(file)
dir_list2 = unique.unique(dir_list2)
full_dir_list = unique.unique(full_dir_list)
dir_list2.sort(); full_dir_list.sort()
if datatype == 'RNASeq':
checkBEDFileFormat(dir) ### Make sure the names are wonky
dir_list3=[]
c = string.lower(string.join(dir_list2,''))
if '.bam' in c and '.bed' in c: #If bed present use bed and not bam
for i in dir_list2:
if '.bam' not in i:
dir_list3.append(i)
dir_list2 = dir_list3
elif '.bam' in c:
for i in dir_list2:
if '.bam' in i:
dir_list3.append(string.replace(i,'.bam','.bed'))
elif '.BAM' in i:
dir_list3.append(string.replace(i,'.BAM','.bed'))
dir_list2 = dir_list3
return dir_list2,full_dir_list
def checkBEDFileFormat(bed_dir):
""" This checks to see if some files have two underscores and one has none or if double underscores are missing from all."""
dir_list = read_directory(bed_dir)
condition_db={}
for filename in dir_list:
if '.tab' in string.lower(filename) or '.bed' in string.lower(filename) or '.junction_quantification.txt' in string.lower(filename):
condition_db[filename]=[]
if len(condition_db)==0: ### Occurs if BAMs present but not .bed files
for filename in dir_list:
if '.bam' in string.lower(filename):
condition_db[filename]=[]
### Check to see if exon.bed and junction.bed file names are propper or faulty (which will result in downstream errors)
double_underscores=[]
no_doubles=[]
for condition in condition_db:
if '__' in condition:
double_underscores.append(condition)
else:
no_doubles.append(condition)
exon_beds=[]
junctions_beds=[]
if len(double_underscores)>0 and len(no_doubles)>0:
### Hence, a problem is likely due to inconsistent naming
print_out = 'The input files appear to have inconsistent naming. If both exon and\njunction sample data are present, make sure they are named propperly.\n\n'
print_out += 'For example: cancer1__exon.bed, cancer1__junction.bed\n(double underscore required to match these samples up)!\n\n'
print_out += 'Exiting AltAnalyze'
IndicatorWindowSimple(print_out,'Quit')
sys.exit()
elif len(no_doubles)>0:
for condition in no_doubles:
condition = string.lower(condition)
if 'exon' in condition:
exon_beds.append(condition)
if 'junction' in condition:
junctions_beds.append(condition)
if len(exon_beds)>0 and len(junctions_beds)>0:
print_out = 'The input files appear to have inconsistent naming. If both exon and\njunction sample data are present, make sure they are named propperly.\n\n'
print_out += 'For example: cancer1__exon.bed, cancer1__junction.bed\n(double underscore required to match these samples up)!\n\n'
print_out += 'Exiting AltAnalyze'
IndicatorWindowSimple(print_out,'Quit')
sys.exit()
def identifyArrayType(full_dir_list):
#import re
arrays={}; array_type=None ### Determine the type of unique arrays in each directory
for filename in full_dir_list:
fn=filepath(filename); ln=0
for line in open(fn,'rU').xreadlines():
if '\x00' in line: ### Simple way of determining if it is a version 4 file with encoding
line = string.replace(line,'\x00\x00',' ') ### retains spaces
line = string.replace(line,'\x00','') ### returns human readable line
if ln<150:
data = cleanUpLine(line); ln+=1
if 'sq' in data:
try:
#fileencoding = "iso-8859-1"
#txt = line.decode(fileencoding); print [txt];kill ### This works but so does the above
array_info,null = string.split(data,'sq')
array_info = string.split(array_info,' ')
array_type = array_info[-1]
if '.' in array_type: array_type,null = string.split(array_type,'.')
#array_type = string.join(re.findall(r"\w",array_type),'') ### should force only alphanumeric but doesn't seem to always work
arrays[array_type]=[]
#print array_type+'\t'+filename
break
except Exception: pass
elif 'affymetrix-array-type' in data:
null, array_type = string.split(data,'affymetrix-array-type')
if '.' in array_type: array_type,null = string.split(array_type,'.')
arrays[array_type]=[]
"""else: ### some CEL file versions are encoded
fileencoding = "iso-8859-1"
txt = line.decode(fileencoding)
print txt;kill"""
else: break
array_ls = []
for array in arrays:
if len(array)<50: array_ls.append(array) ### Occurs with version 4 encoding (bad entries added)
return array_ls, array_type
def getAffyFilesRemote(array_name,arraytype,species):
global backSelect; global array_type; global debug_mode
debug_mode = 'yes'
backSelect = 'yes'
array_type = arraytype
library_dir, annotation_dir, bgp_file, clf_file = getAffyFiles(array_name,species)
return library_dir, annotation_dir, bgp_file, clf_file
def getAffyFiles(array_name,species):#('AltDatabase/affymetrix/LibraryFiles/'+library_file,species)
sa = supproted_array_db[array_name]; library_file = sa.LibraryFile(); annot_file = sa.AnnotationFile(); original_library_file = library_file
filename = 'AltDatabase/affymetrix/LibraryFiles/'+library_file
fn=filepath(filename); library_dir=filename; bgp_file = ''; clf_file = ''
local_lib_files_present = False
if backSelect == 'yes': warn = 'no'
else: warn = 'yes'
try:
for line in open(fn,'rU').xreadlines():break
### Hence, the library file was found!!!
local_lib_files_present = True
input_cdf_file = filename
if '.pgf' in input_cdf_file:
###Check to see if the clf and bgp files are present in this directory
icf_list = string.split(input_cdf_file,'/'); parent_dir = string.join(icf_list[:-1],'/'); cdf_short = icf_list[-1]
clf_short = string.replace(cdf_short,'.pgf','.clf')
if array_type == 'exon' or array_type == 'junction':
bgp_short = string.replace(cdf_short,'.pgf','.antigenomic.bgp')
else: bgp_short = string.replace(cdf_short,'.pgf','.bgp')
try: dir_list = read_directory(parent_dir)
except Exception: dir_list = read_directory('/'+parent_dir)
if clf_short in dir_list and bgp_short in dir_list:
pgf_file = input_cdf_file; clf_file = string.replace(pgf_file,'.pgf','.clf')
if array_type == 'exon' or array_type == 'junction': bgp_file = string.replace(pgf_file,'.pgf','.antigenomic.bgp')
else: bgp_file = string.replace(pgf_file,'.pgf','.bgp')
else:
try:
print_out = "The directory;\n"+parent_dir+"\ndoes not contain either a .clf or antigenomic.bgp\nfile, required for probeset summarization."
IndicatorWindow(print_out,'Continue')
except Exception: print print_out; sys.exit()
except Exception:
print_out = "AltAnalyze was not able to find a library file\nfor your arrays. Would you like AltAnalyze to\nautomatically download these files?"
try:
dw = DownloadWindow(print_out,'Download by AltAnalyze','Select Local Files')
warn = 'no' ### If already downloading the library, don't warn to download the csv too
dw_results = dw.Results(); option = dw_results['selected_option']
except Exception: option = 1 ### Occurs when Tkinter is not present - used by CommandLine mode
if option == 1:
library_file = string.replace(library_file,'.cdf','.zip')
filename = 'AltDatabase/affymetrix/LibraryFiles/'+library_file
input_cdf_file = filename
if '.pgf' in input_cdf_file:
pgf_file = input_cdf_file; clf_file = string.replace(pgf_file,'.pgf','.clf')
if array_type == 'exon' or array_type == 'junction': bgp_file = string.replace(pgf_file,'.pgf','.antigenomic.bgp')
else: bgp_file = string.replace(pgf_file,'.pgf','.bgp')
filenames = [pgf_file+'.gz',clf_file+'.gz',bgp_file+'.gz']
if 'Glue' in pgf_file:
kil_file = string.replace(pgf_file,'.pgf','.kil') ### Only applies to the Glue array
filenames.append(kil_file+'.gz')
else: filenames = [input_cdf_file]
for filename in filenames:
var_list = filename,'LibraryFiles'
if debug_mode == 'no': StatusWindow(var_list,'download')
else:
for filename in filenames:
continue_analysis = update.downloadCurrentVersion(filename,'LibraryFiles','')
try: os.remove(filepath(filename)) ### Not sure why this works now and not before
except Exception: pass
else: library_dir = ''
filename = 'AltDatabase/affymetrix/'+species+'/'+annot_file
fn=filepath(filename); annotation_dir = filename
try:
for line in open(fn,'rU').xreadlines():break
except Exception:
if warn == 'yes' and local_lib_files_present == False:
### Indicates that library file wasn't present to prior to this method
print_out = "AltAnalyze was not able to find a CSV annotation file\nfor your arrays. Would you like AltAnalyze to\nautomatically download these files?"
try:
dw = DownloadWindow(print_out,'Download by AltAnalyze','Select Local Files'); warn = 'no'
dw_results = dw.Results(); option = dw_results['selected_option']
except OSError: option = 1 ### Occurs when Tkinter is not present - used by CommandLine mode
else:
try: option = option
except Exception: option = 2
if option == 1 or debug_mode=='yes':
annot_file += '.zip'
filenames = ['AltDatabase/affymetrix/'+species+'/'+annot_file]
for filename in filenames:
var_list = filename,'AnnotationFiles'
if debug_mode == 'no': StatusWindow(var_list,'download')
else:
for filename in filenames:
try: update.downloadCurrentVersionUI(filename,'AnnotationFiles','',Tk())
except Exception:
try: update.downloadCurrentVersion(filename,'AnnotationFiles',None)
except Exception: pass ### Don't actually need Affy's annotations in most cases - GO-Elite used instead
try: os.remove(filepath(filename)) ### Not sure why this works now and not before
except Exception: pass
else: annotation_dir = ''
return library_dir, annotation_dir, bgp_file, clf_file
def cleanUpLine(line):
line = string.replace(line,'\n','')
line = string.replace(line,'\c','')
data = string.replace(line,'\r','')
data = string.replace(data,'"','')
return data
########### Status Window Functions ###########
def copyFiles(file1,file2,root):
print 'Copying files from:\n',file1
data = export.ExportFile(file2) ### Ensures the directory exists
try: shutil.copyfile(file1,file2)
except Exception: print "This file already exists in the destination directory."
root.destroy()
class StatusWindow:
def __init__(self,info_list,analysis_type,windowType='parent'):
try:
if windowType == 'child':
root = Toplevel()
else:
root = Tk()
self._parent = root
root.title('AltAnalyze version 2.1.4.4')
statusVar = StringVar() ### Class method for Tkinter. Description: "Value holder for strings variables."
height = 300; width = 700
if os.name != 'nt': height+=100; width+=50
self.sf = PmwFreeze.ScrolledFrame(self._parent,
labelpos = 'n', label_text = 'Download File Status Window',
usehullsize = 1, hull_width = width, hull_height = height)
self.sf.pack(padx = 5, pady = 1, fill = 'both', expand = 1)
self.frame = self.sf.interior()
group = PmwFreeze.Group(self.sf.interior(),tag_text = 'Output')
group.pack(fill = 'both', expand = 1, padx = 10, pady = 0)
Label(group.interior(),width=180,height=1000,justify=LEFT, bg='black', fg = 'white',anchor=NW,padx = 5,pady = 5, textvariable=statusVar).pack(fill=X,expand=Y)
status = StringVarFile(statusVar,root) ### Captures the stdout (or print) to the GUI instead of to the terminal
self.original_sys_out = sys.stdout ### Save the original stdout mechanism
#ProgressBar('Download',self._parent)
except Exception: None
if analysis_type == 'download':
filename,dir = info_list
try: sys.stdout = status; root.after(100,update.downloadCurrentVersionUI(filename,dir,None,self._parent))
except Exception:
update.downloadCurrentVersion(filename,dir,None)
if analysis_type == 'copy':
file1,file2 = info_list
try: sys.stdout = status; root.after(100,copyFiles(file1,file2,self._parent))
except Exception: copyFiles(file1,file2,None)
if analysis_type == 'getOnlineDBConfig':
file_location_defaults = info_list
try: sys.stdout = status; root.after(100,getOnlineDBConfig(file_location_defaults,self._parent))
except Exception,e: getOnlineDBConfig(file_location_defaults,None)
if analysis_type == 'getOnlineEliteDatabase':
file_location_defaults,db_version,new_species_codes,update_goelite_resources = info_list
try: sys.stdout = status; root.after(100,getOnlineEliteDatabase(file_location_defaults,db_version,new_species_codes,update_goelite_resources,self._parent))
except Exception,e: getOnlineEliteDatabase(file_location_defaults,db_version,new_species_codes,update_goelite_resources,None)
if analysis_type == 'getAdditionalOnlineResources':
species_code,additional_resources = info_list
try: sys.stdout = status; root.after(100,getAdditionalOnlineResources(species_code,additional_resources,self._parent))
except Exception,e: getAdditionalOnlineResources(species_code,additional_resources,None)
if analysis_type == 'createHeatMap':
filename, row_method, row_metric, column_method, column_metric, color_gradient, transpose, contrast = info_list
try: sys.stdout = status; root.after(100,createHeatMap(filename, row_method, row_metric, column_method, column_metric, color_gradient, transpose, contrast, self._parent))
except Exception,e: createHeatMap(filename, row_method, row_metric, column_method, column_metric, color_gradient, transpose,contrast,None)
if analysis_type == 'performPCA':
filename, pca_labels, dimensions, pca_algorithm, transpose, geneSetName, species, zscore, colorByGene, reimportModelScores, maskGroups,coordinateFile = info_list
try: sys.stdout = status; root.after(100,performPCA(filename, pca_labels, pca_algorithm,
transpose, self._parent, plotType = dimensions, geneSetName=geneSetName,
species=species, zscore=zscore, colorByGene=colorByGene, reimportModelScores=reimportModelScores,
maskGroups=maskGroups,coordinateFile=coordinateFile))
except Exception,e: performPCA(filename, pca_labels, pca_algorithm, transpose, None, plotType = dimensions, geneSetName=geneSetName,
species=species, zscore=zscore, colorByGene=colorByGene, reimportModelScores=reimportModelScores,
maskGroups=maskGroups,coordinateFile=coordinateFile)
if analysis_type == 'runLineageProfiler':
fl, filename, vendor, custom_markerFinder, geneModel_file, modelDiscovery = info_list
try: sys.stdout = status; root.after(100,runLineageProfiler(fl, filename, vendor, custom_markerFinder, geneModel_file, self._parent, modelSize=modelDiscovery))
except Exception,e: runLineageProfiler(fl, filename, vendor, custom_markerFinder, geneModel_file, None, modelSize=modelDiscovery)
if analysis_type == 'MergeFiles':
files_to_merge, join_option, ID_option, output_merge_dir = info_list
try: sys.stdout = status; root.after(100,MergeFiles(files_to_merge, join_option, ID_option, output_merge_dir, self._parent))
except Exception,e: MergeFiles(files_to_merge, join_option, ID_option, output_merge_dir, None)
if analysis_type == 'VennDiagram':
files_to_merge, output_venn_dir = info_list
try: sys.stdout = status; root.after(100,vennDiagram(files_to_merge, output_venn_dir, self._parent))
except Exception,e: vennDiagram(files_to_merge, output_venn_dir, None)
if analysis_type == 'AltExonViewer':
species,platform,exp_file,gene,show_introns,analysisType = info_list
try: sys.stdout = status; root.after(100,altExonViewer(species,platform,exp_file,gene,show_introns,analysisType,self._parent))
except Exception,e: altExonViewer(species,platform,exp_file,gene,show_introns,analysisType,None)
if analysis_type == 'network':
inputDir,inputType,outputdir,interactionDirs,degrees,expressionFile,gsp = info_list
try: sys.stdout = status; root.after(100,networkBuilder(inputDir,inputType,outputdir,interactionDirs,degrees,expressionFile,gsp, self._parent))
except Exception,e: networkBuilder(inputDir,inputType,outputdir,interactionDirs,degrees,expressionFile,gsp, None)
if analysis_type == 'IDConverter':
filename, species_code, input_source, output_source = info_list
try: sys.stdout = status; root.after(100,IDconverter(filename, species_code, input_source, output_source, self._parent))
except Exception,e: IDconverter(filename, species_code, input_source, output_source, None)
if analysis_type == 'predictGroups':
try: expFile, mlp_instance, gsp, reportOnly = info_list
except Exception: expFile, mlp_instance, gsp, reportOnly = info_list
try: sys.stdout = status; root.after(100,predictSampleExpGroups(expFile, mlp_instance, gsp, reportOnly, self._parent))
except Exception,e: predictSampleExpGroups(expFile, mlp_instance, gsp, reportOnly, None)
if analysis_type == 'preProcessRNASeq':
species,exp_file_location_db,dataset,mlp_instance = info_list
try: sys.stdout = status; root.after(100,preProcessRNASeq(species,exp_file_location_db,dataset,mlp_instance, self._parent))
except Exception,e: preProcessRNASeq(species,exp_file_location_db,dataset,mlp_instance, None)
try:
self._parent.protocol("WM_DELETE_WINDOW", self.deleteWindow)
self._parent.mainloop()
self._parent.destroy()
except Exception: None ### This is what typically get's called
try:
sys.stdout = self.original_sys_out ### Has to be last to work!!!
except Exception: None
def deleteWindow(self):
#tkMessageBox.showwarning("Quit Selected","Use 'Quit' button to end program!",parent=self._parent)
self._parent.destroy(); sys.exit()
def quit(self):
try: self._parent.destroy(); sys.exit() #self._parent.quit();
except Exception: sys.exit() #self._parent.quit();
def SysOut(self):
return self.original_sys_out
def preProcessRNASeq(species,exp_file_location_db,dataset,mlp_instance,root):
for dataset in exp_file_location_db:
flx = exp_file_location_db[dataset]
if root == None: display=False
else: display=True
runKallisto = False
try:
import RNASeq
from build_scripts import ExonArray
expFile = flx.ExpFile()
count = verifyFileLength(expFile)
try: fastq_folder = flx.RunKallisto()
except Exception: fastq_folder = []
try: customFASTA = flx.CustomFASTA()
except Exception: customFASTA = None
try: matrix_file = flx.ChromiumSparseMatrix()
except Exception: matrix_file = []
try: integrateChromiumFiles = flx.IntegrateChromiumFiles()
except: integrateChromiumFiles = False
processing10xData = False
if integrateChromiumFiles:
processing10xData = True
from import_scripts import mergeFiles
from import_scripts import ChromiumProcessing
files_to_merge = ChromiumProcessing.getMatrices(matrix_file)
if len(files_to_merge)==0:
files_to_merge = ChromiumProcessing.getTextMatrices(matrix_file)
if len(files_to_merge)>1:
combined_flat_file = mergeFiles.joinFiles(files_to_merge, 'Intersection', False, matrix_file)
shutil.move(combined_flat_file, expFile)
try: root.destroy()
except Exception: pass
return None
else:
matrix_file = files_to_merge[0]
integrateChromiumFiles = False ### Trigger below import10XSparseMatrix
if len(matrix_file)>0 and integrateChromiumFiles == False:
print 'Exporting Chromium sparse matrix file to tab-delimited-text'
try:
#print expFile, 'expFile'
#print flx.RootDir(), 'root_dir'
output_dir = export.findParentDir(expFile)
try: os.mkdir(output_dir)
except Exception: pass
matrix_dir = export.findParentDir(matrix_file)
genome = export.findFilename(matrix_dir[:-1])
parent_dir = export.findParentDir(matrix_dir[:-1])
from import_scripts import ChromiumProcessing
ChromiumProcessing.import10XSparseMatrix(matrix_file,genome,dataset,expFile=expFile)
except Exception:
print 'Chromium export failed due to:',traceback.format_exc()
ChromiumProcessingError
try: root.destroy()
except Exception: pass
return None
elif len(fastq_folder)>0 and count<2:
print 'Pre-processing input files'
try:
parent_dir = export.findParentDir(expFile)
flx.setRootDir(parent_dir)
RNASeq.runKallisto(species,dataset,flx.RootDir(),fastq_folder,mlp_instance,returnSampleNames=False,customFASTA=customFASTA)
except Exception:
print 'Kallisto failed due to:',traceback.format_exc()
try: root.destroy()
except Exception: pass
return None
elif len(fastq_folder)>0 and count>1:
try: root.destroy()
except Exception: pass
return None ### Already run
elif count<2 and processing10xData == False:
print 'Pre-processing input BED/BAM files\n'
analyzeBAMs=False
bedFilesPresent=False
dir_list = unique.read_directory(flx.BEDFileDir())
for file in dir_list:
if '.bam' in string.lower(file):
analyzeBAMs=True
if '.bed' in string.lower(file):
bedFilesPresent=True
if analyzeBAMs and bedFilesPresent==False:
print 'No bed files present, deriving from BAM files'
from import_scripts import multiBAMtoBED
bam_dir = flx.BEDFileDir()
refExonCoordinateFile = filepath('AltDatabase/ensembl/'+species+'/'+species+'_Ensembl_exon.txt')
outputExonCoordinateRefBEDfile = bam_dir+'/BedRef/'+species+'_'+string.replace(dataset,'exp.','')
analysisType = ['exon','junction','reference']
#analysisType = ['junction']
try: multiBAMtoBED.parallelBAMProcessing(bam_dir,refExonCoordinateFile,outputExonCoordinateRefBEDfile,analysisType=analysisType,useMultiProcessing=flx.multiThreading(),MLP=mlp_instance,root=root)
except Exception:
print traceback.format_exc()
try: biotypes = RNASeq.alignExonsAndJunctionsToEnsembl(species,exp_file_location_db,dataset,Multi=mlp_instance)
except Exception:
print traceback.format_exc()
biotypes = getBiotypes(expFile)
elif processing10xData == False:
biotypes = getBiotypes(expFile)
array_linker_db,array_names = ExonArray.remoteExonProbesetData(expFile,{},'arraynames',flx.ArrayType())
steady_state_export = expFile[:-4]+'-steady-state.txt'
normalize_feature_exp = flx.FeatureNormalization()
try: excludeLowExpressionExons = flx.excludeLowExpressionExons()
except Exception: excludeLowExpressionExons = True
if flx.useJunctionsForGeneExpression():
if 'junction' in biotypes:
feature = 'junction'
else:
feature = 'exon'
else:
### Use all exons either way at this step since more specific parameters will apply to the next iteration
if 'exon' in biotypes:
feature = 'exon'
else:
feature = 'junction'
probeset_db = getAllKnownFeatures(feature,species,flx.ArrayType(),flx.Vendor(),flx)
print 'Calculating gene-level expression values from',feature+'s'
RNASeq.calculateGeneLevelStatistics(steady_state_export,species,probeset_db,normalize_feature_exp,array_names,flx,excludeLowExp=excludeLowExpressionExons,exportRPKMs=True)
#if display == False: print print_out
#try: InfoWindow(print_out, 'Continue')
#except Exception: None
try: root.destroy()
except Exception: pass
except Exception:
error = traceback.format_exc()
#print error
try:
logfile = filepath(fl.RootDir()+'Error.log')
log_report = open(logfile,'a')
log_report.write(traceback.format_exc())
except Exception:
None
print_out = 'Expression quantification failed..\n',error
if runningCommandLine==False:
try: print print_out
except Exception: pass ### Windows issue with the Tk status window stalling after pylab.show is called
try: WarningWindow(print_out,'Continue')
except Exception: pass
try: root.destroy()
except Exception: pass
if 'ChromiumProcessingError' in error:
ChromiumProcessingError
def getBiotypes(filename):
biotypes={}
firstRow=True
if 'RawSpliceData' in filename: index = 2
else: index = 0
try:
fn=filepath(filename)
for line in open(fn,'rU').xreadlines():
t = string.split(line,'\t')
if firstRow:
firstRow = False
else:
if '-' in t[index]:
biotypes['junction']=[]
else:
biotypes['exon']=[]
except Exception: pass
return biotypes
def getAllKnownFeatures(feature,species,array_type,vendor,fl):
### Simple method to extract gene features of interest
from build_scripts import ExonArrayEnsemblRules
source_biotype = 'mRNA'
if array_type == 'gene': source_biotype = 'gene'
elif array_type == 'junction': source_biotype = 'junction'
if array_type == 'AltMouse':
import ExpressionBuilder
probeset_db,constitutive_gene_db = ExpressionBuilder.importAltMerge('full')
source_biotype = 'AltMouse'
elif vendor == 'Affymetrix' or array_type == 'RNASeq':
if array_type == 'RNASeq':
source_biotype = array_type, fl.RootDir()
dbs = ExonArrayEnsemblRules.getAnnotations('no','Ensembl',source_biotype,species)
probeset_db = dbs[0]; del dbs
probeset_gene_db={}
for probeset in probeset_db:
probe_data = probeset_db[probeset]
gene = probe_data[0]; external_exonid = probe_data[-2]
if len(external_exonid)>2: ### These are known exon only (e.g., 'E' probesets)
proceed = True
if feature == 'exon': ### Restrict the analysis to exon RPKM or count data for constitutive calculation
if '-' in probeset and '_' not in probeset: proceed = False
else:
if '-' not in probeset and '_' not in probeset: proceed = False ### Use this option to override
if proceed:
try: probeset_gene_db[gene].append(probeset)
except Exception: probeset_gene_db[gene] = [probeset]
return probeset_gene_db
def RemotePredictSampleExpGroups(expFile, mlp_instance, gsp, globalVars):
global species
global array_type
species, array_type = globalVars
predictSampleExpGroups(expFile, mlp_instance, gsp, False, None, exportAdditionalResults=False)
return graphic_links
def getICGSNMFOutput(root,filename):
if 'exp.' in filename:
filename = string.replace(filename,'exp.','')
umap_scores_file=''
for file in unique.read_directory(root):
if '-UMAP_coordinates.txt' in file and filename in file:
umap_scores_file = file
return root+'/'+umap_scores_file
def exportAdditionalICGSOutputs(expFile,group_selected,outputTSNE=True):
### Remove OutlierRemoved files (they will otherwise clutter up the directory)
if 'OutliersRemoved' in group_selected and 'OutliersRemoved' not in expFile:
try: os.remove(expFile[:-4]+'-OutliersRemoved.txt')
except Exception: pass
try: os.remove(string.replace(expFile[:-4]+'-OutliersRemoved.txt','exp.','groups.'))
except Exception: pass
try: os.remove(string.replace(expFile[:-4]+'-OutliersRemoved.txt','exp.','comps.'))
except Exception: pass
### Create the new groups file but don't over-write the old
import RNASeq
new_groups_dir = RNASeq.exportGroupsFromClusters(group_selected,expFile,array_type,suffix='ICGS')
from import_scripts import sampleIndexSelection; reload(sampleIndexSelection)
### Look to see if a UMAP file exists in ICGS-NMF
if 'ICGS-NMF' in group_selected or 'NMF-SVM' in group_selected:
root = export.findParentDir(export.findParentDir(expFile)[:-1])+'/ICGS-NMF'
umap_scores_file = getICGSNMFOutput(root,export.findFilename(expFile)[:-4])
tSNE_score_file = umap_scores_file
extension = '-UMAP_scores.txt'
elif outputTSNE:
try:
### Build-tSNE plot from the selected ICGS output (maybe different than Guide-3)
tSNE_graphical_links = performPCA(group_selected, 'no', 'UMAP', False, None, plotType='2D',
display=False, geneSetName=None, species=species, zscore=True, reimportModelScores=False,
separateGenePlots=False,returnImageLoc=True)
if 'SNE' in tSNE_graphical_links[-1][-1]:
tSNE_score_file =tSNE_graphical_links[-1][-1][:-10]+'-t-SNE_scores.txt'
extension = '-t-SNE_scores.txt'
else:
tSNE_score_file =tSNE_graphical_links[-1][-1][:-9]+'-UMAP_scores.txt'
extension = '-UMAP_scores.txt'
except Exception:
print traceback.format_exc()
pass
if '-steady-state' in expFile:
newExpFile = string.replace(expFile,'-steady-state','-ICGS-steady-state')
ICGS_order = sampleIndexSelection.getFilters(new_groups_dir)
sampleIndexSelection.filterFile(expFile,newExpFile,ICGS_order)
### Copy the steady-state files for ICGS downstream-specific analyses
ssCountsFile = string.replace(expFile,'exp.','counts.')
newExpFile = string.replace(expFile,'-steady-state','-ICGS-steady-state')
newssCountsFile = string.replace(newExpFile,'exp.','counts.')
exonExpFile = string.replace(expFile,'-steady-state','')
exonCountFile = string.replace(exonExpFile,'exp.','counts.')
newExonExpFile = string.replace(newExpFile,'-steady-state','')
newExonCountsFile = string.replace(newExonExpFile,'exp.','counts.')
sampleIndexSelection.filterFile(ssCountsFile,newssCountsFile,ICGS_order)
sampleIndexSelection.filterFile(exonExpFile,newExonExpFile,ICGS_order)
sampleIndexSelection.filterFile(exonCountFile,newExonCountsFile,ICGS_order)
exonExpFile = exonExpFile[:-4]+'-ICGS.txt'
else:
newExpFile = expFile[:-4]+'-ICGS.txt'
ICGS_order = sampleIndexSelection.getFilters(new_groups_dir)
sampleIndexSelection.filterFile(expFile,newExpFile,ICGS_order)
exonExpFile = newExpFile
if outputTSNE:
try:
status = verifyFile(tSNE_score_file)
if status=='no':
tSNE_score_file = string.replace(tSNE_score_file,'Clustering-','')
### Copy the t-SNE scores to use it for gene expression analyses
if 'DataPlots' not in tSNE_score_file:
outdir = export.findParentDir(export.findParentDir(tSNE_score_file)[:-1])+'/DataPlots'
else:
outdir = export.findParentDir(tSNE_score_file)
exp_tSNE_score_file = outdir+'/'+export.findFilename(exonExpFile)[:-4]+extension
import shutil
export.customFileCopy(tSNE_score_file,exp_tSNE_score_file)
except Exception:
#print traceback.format_exc()
pass
return exonExpFile,newExpFile,new_groups_dir
def predictSampleExpGroups(expFile, mlp_instance, gsp, reportOnly, root, exportAdditionalResults=True):
global graphic_links; graphic_links=[];
if root == None: display=False
else: display=True
import RNASeq,ExpressionBuilder; reload(RNASeq) ### allows for GUI testing with restarting
try:
if gsp.FeaturestoEvaluate() != 'AltExon':
from stats_scripts import ICGS_NMF
reload(ICGS_NMF)
scaling = True ### Performs pagerank downsampling if over 2,500 cells - currently set as a hard coded default
dynamicCorrelation=True
status = verifyFile(expFile)
if status=='no':
expFile = string.replace(expFile,'-steady-state','') ### Occurs for Kallisto processed
graphic_links=ICGS_NMF.runICGS_NMF(expFile,scaling,array_type,species,gsp,enrichmentInput='',dynamicCorrelation=True)
#graphic_links = RNASeq.singleCellRNASeqWorkflow(species, array_type, expFile, mlp_instance, parameters=gsp, reportOnly=reportOnly)
if gsp.FeaturestoEvaluate() != 'Genes':
### For splice-ICGS (needs to be updated in a future version to ICGS_NMF updated code)
graphic_links2,cluster_input_file=ExpressionBuilder.unbiasedComparisonSpliceProfiles(fl.RootDir(),species,array_type,expFile=fl.CountsFile(),min_events=gsp.MinEvents(),med_events=gsp.MedEvents())
gsp.setCountsCutoff(0);gsp.setExpressionCutoff(0)
graphic_links3 = RNASeq.singleCellRNASeqWorkflow(species, 'exons', cluster_input_file, mlp_instance, parameters=gsp, reportOnly=reportOnly)
graphic_links+=graphic_links2+graphic_links3
print_out = 'Predicted sample groups saved.'
if exportAdditionalResults:
### Optionally automatically generate t-SNE and MarkerFinder Results
guide3_results = graphic_links[-1][-1][:-4]+'.txt'
exportAdditionalICGSOutputs(expFile,guide3_results)
if len(graphic_links)==0:
print_out = 'No predicted sample groups identified. Try different parameters.'
if display == False: print print_out
try: InfoWindow(print_out, 'Continue')
except Exception: None
try: root.destroy()
except Exception: pass
except Exception:
error = traceback.format_exc()
if 'score_ls' in error:
error = 'Unknown error likely due to too few genes resulting from the filtering options.'
if 'options_result_in_no_genes' in error:
error = 'ERROR: No genes differentially expressed with the input criterion'
print_out = 'Predicted sample export failed..\n'+error
try: print print_out
except Exception: pass ### Windows issue with the Tk status window stalling after pylab.show is called
try: WarningWindow(print_out,'Continue')
except Exception: pass
try: root.destroy()
except Exception: pass
try: print error
except Exception: pass
def openDirectory(output_dir):
if runningCommandLine:
pass
elif os.name == 'nt':
try: os.startfile('"'+output_dir+'"')
except Exception: os.system('open "'+output_dir+'"')
elif 'darwin' in sys.platform: os.system('open "'+output_dir+'"')
elif 'linux' in sys.platform: os.system('xdg-open "'+output_dir+'"')
def networkBuilder(inputDir,inputType,outputdir,interactionDirs_short,degrees,expressionFile,gsp,root):
species = gsp.Species()
Genes = gsp.GeneSelection()
PathwaySelect = gsp.PathwaySelect()
OntologyID = gsp.OntologyID()
GeneSet = gsp.GeneSet()
IncludeExpIDs = gsp.IncludeExpIDs()
if 'Ontology' in GeneSet: directory = 'nested'
else: directory = 'gene-mapp'
interactionDirs=[]
obligatorySet=[] ### Always include interactions from these if associated with any input ID period
secondarySet=[]
print 'Species:',species, '| Algorithm:',degrees, ' | InputType:',inputType, ' | IncludeExpIDs:',IncludeExpIDs
print 'Genes:',Genes
print 'OntologyID:',gsp.OntologyID(), gsp.PathwaySelect(), GeneSet
print ''
if interactionDirs_short == None or len(interactionDirs_short)==0:
interactionDirs_short = ['WikiPathways']
for i in interactionDirs_short:
if i == None: None
else:
if 'common-' in i:
i = string.replace(i,'common-','')
secondarySet.append(i)
if 'all-' in i:
i = string.replace(i,'all-','')
obligatorySet.append(i)
fn = filepath('AltDatabase/goelite/'+species+'/gene-interactions/Ensembl-'+i+'.txt')
interactionDirs.append(fn)
print "Interaction Files:",string.join(interactionDirs_short,' ')
import InteractionBuilder
try:
output_filename = InteractionBuilder.buildInteractions(species,degrees,inputType,inputDir,outputdir,interactionDirs,Genes=Genes,
geneSetType=GeneSet,PathwayFilter=PathwaySelect,OntologyID=OntologyID,directory=directory,expressionFile=expressionFile,
obligatorySet=obligatorySet,secondarySet=secondarySet,IncludeExpIDs=IncludeExpIDs)
if output_filename==None:
print_out = 'Network creation/visualization failed..\nNo outputs produced... try different options.\n'
print_out += traceback.format_exc()
if root != None and root != '':
try: InfoWindow(print_out, 'Continue')
except Exception: None
else:
if root != None and root != '':
try: openDirectory(outputdir)
except Exception: None
else:
print 'Results saved to:',output_filename
if root != None and root != '':
GUI(root,'ViewPNG',[],output_filename) ### The last is default attributes (should be stored as defaults in the option_db var)
except Exception:
error = traceback.format_exc()
if 'queryGeneError' in error:
print_out = 'No valid gene IDs present in the input text search\n(valid IDs = FOXP1,SOX2,NANOG,TCF7L1)'
else: print_out = 'Network creation/visualization failed..\n',error
if root != None and root != '':
try: InfoWindow(print_out, 'Continue')
except Exception: None
try: root.destroy()
except Exception: None
def vennDiagram(files_to_merge, output_venn_dir, root, display=True):
from visualization_scripts import VennDiagram
if root == None and display==False: display=False
else: display=True
try:
VennDiagram.compareInputFiles(files_to_merge,output_venn_dir,display=display)
if display == False: print 'VennDiagrams saved to:',output_venn_dir
except Exception:
error = traceback.format_exc()
print_out = 'Venn Diagram export failed..\n',error
if root != None and root != '':
try: InfoWindow(print_out, 'Continue')
except Exception: None
try: root.destroy()
except Exception: None
def altExonViewer(species,platform,exp_file,gene,show_introns,analysisType,root):
from visualization_scripts import QC
transpose=True
if root == None: display = False
else: display = True
if analysisType == 'Sashimi-Plot':
showEvent = False
try:
### Create sashimi plot index
from visualization_scripts import SashimiIndex
print 'Indexing splicing-events'
SashimiIndex.remoteIndexing(species,exp_file)
from visualization_scripts import SashimiPlot
#reload(SashimiPlot)
print 'Running Sashimi-Plot...'
genes=None
if '.txt' in gene:
events_file = gene
events = None
else:
gene = string.replace(gene,',',' ')
genes = string.split(gene,' ')
events_file = None
if len(genes)==1:
showEvent = True
SashimiPlot.remoteSashimiPlot(species,exp_file,exp_file,events_file,events=genes,show=showEvent) ### assuming the bam files are in the root-dir
if root != None and root != '':
print_out = 'Sashimi-Plot results saved to:\n'+exp_file+'/SashimiPlots'
try: InfoWindow(print_out, 'Continue')
except Exception: None
except Exception:
error = traceback.format_exc()
print_out = 'AltExon Viewer failed..\n',error
if root != None and root != '':
try: WarningWindow(print_out, 'Continue')
except Exception: None
try: root.destroy()
except Exception: None
else:
#print [analysisType, species,platform,exp_file,gene,transpose,display,show_introns]
try: QC.displayExpressionGraph(species,platform,exp_file,gene,transpose,display=display,showIntrons=show_introns,analysisType=analysisType)
except Exception:
error = traceback.format_exc()
print_out = 'AltExon Viewer failed..\n',error
if root != None and root != '':
try: WarningWindow(print_out, 'Continue')
except Exception: None
try: root.destroy()
except Exception: None
def MergeFiles(files_to_merge, join_option, ID_option, output_merge_dir, root, includeFilenames=True):
from import_scripts import mergeFiles
try: outputfile = mergeFiles.joinFiles(files_to_merge, join_option, ID_option, output_merge_dir, includeFilenames=includeFilenames)
except Exception:
outputfile = 'failed'
error = traceback.format_exc()
print traceback.format_exc()
if outputfile == 'failed':
print_out = 'File merge failed due to:\n',error
else:
print_out = 'File merge complete. See the new file:\n'+outputfile
if root != None and root!= '':
try: InfoWindow(print_out, 'Continue')
except Exception: None
try: root.destroy()
except Exception: None
if outputfile != 'failed': ### Open the folder
try: openDirectory(output_merge_dir)
except Exception: None
def IDconverter(filename, species_code, input_source, output_source, root):
import gene_associations
try: outputfile = gene_associations.IDconverter(filename, species_code, input_source, output_source)
except Exception:
outputfile = 'failed'