-
Notifications
You must be signed in to change notification settings - Fork 30
/
ExpressionBuilder.py
4236 lines (3933 loc) · 222 KB
/
ExpressionBuilder.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
###ExpressionBuilder
#Copyright 2005-2008 J. David Gladstone Institutes, San Francisco California
#Author Nathan Salomonis - nsalomonis@gmail.com
#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 sys, string
import os.path
import bisect
import unique
from stats_scripts import statistics
import math
import reorder_arrays
try: from build_scripts import ExonArray
except: pass
import export
import copy
import time
import traceback
import UI
from import_scripts import BuildAffymetrixAssociations; reload(BuildAffymetrixAssociations)
try:
from scipy import average as Average
except Exception:
try: from statistics import avg as Average
except: pass
use_Tkinter = 'no'
try:
from Tkinter import *
use_Tkinter = 'yes'
except ImportError: use_Tkinter = 'yes'; print "\nPmw or Tkinter not found... Tkinter print out not available";
debug_mode = 'no'
### Method specific global variables most easily initialized here
cluster_id=0
cluster_name='clu_0'
def filepath(filename):
fn = unique.filepath(filename)
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": dir_list2.append(entry)
return dir_list2
def returnLargeGlobalVars():
### Prints all large global variables retained in memory (taking up space)
all = [var for var in globals() if (var[:2], var[-2:]) != ("__", "__")]
for var in all:
try:
if len(globals()[var])>1:
print var, len(globals()[var])
except Exception: null=[]
def clearObjectsFromMemory(db_to_clear):
db_keys={}
for key in db_to_clear: db_keys[key]=[]
for key in db_keys: del db_to_clear[key]
################# Begin Analysis from parsing files
def checkArrayHeaders(expr_input_dir,expr_group_dir):
array_names, array_linker_db = getArrayHeaders(expr_input_dir)
expr_group_list,expr_group_db = importArrayGroups(expr_group_dir,array_linker_db)
def getArrayHeaders(expr_input_dir):
### This method is used to check to see if the array headers in the groups and expression files match
fn=filepath(expr_input_dir); x = 0
for line in open(fn,'rU').xreadlines():
data = cleanUpLine(line)
headers = string.split(data,'\t')
if data[0] != '#':
### differentiate data from column headers
if x == 1: break ### Exit out of loop, since we only want the array names
if x == 0: ### only grab headers if it's the first row
array_names = []; array_linker_db = {}; d = 0
for entry in headers[1:]: entry = string.replace(entry,'"',''); array_names.append(entry)
for array in array_names: array = string.replace(array,'\r',''); array_linker_db[array] = d; d +=1
x = 1
return array_names, array_linker_db
def checkExpressionFileFormat(expFile,reportNegatives=False,filterIDs=False):
""" Determine if the data is log, non-log and increment value for log calculation """
firstLine=True; convert=False
inputMax=0; inputMin=10000; increment=0
expressed_values={}
startIndex = 1
for line in open(expFile,'rU').xreadlines():
line = cleanUpLine(line)
key = string.split(line,'\t')[0]
t = string.split(line,'\t')
if firstLine:
headers = line
if 'row_clusters-flat' == t[1]:
startIndex = 2
firstLine = False
else:
if 'column_clusters-flat' in t:
continue ### skip this row if analyzing a clustered heatmap file
try: uid, coordinates = string.split(key,'=')
except Exception: uid = key
if filterIDs!=False:
if uid not in filterIDs:
continue
if '' in t[1:]:
values = [0 if x=='' else x for x in t[startIndex:]]
elif 'NA' in t[1:]:
values = [0 if x=='NA' else x for x in t[startIndex:]]
else:
values = t[1:]
try: values = map(lambda x: float(x), values)
except Exception:
values2 = []
for x in values:
try: values2.append(float(x))
except: values2.append(0)
values = values2
#print values
#print traceback.format_exc()
if max(values)>inputMax: inputMax = max(values)
if min(values)<inputMin: inputMin = min(values)
if inputMax>100: ### Thus, not log values
expressionDataFormat = 'non-log'
if inputMin<=1: #if inputMin<=1:
increment = inputMin+1
convert = True
else:
expressionDataFormat = "log"
#print expressionDataFormat,increment,convert
if reportNegatives == False:
return expressionDataFormat,increment,convert
else:
### Report if negative values are present
increment = inputMin
if convert: ### Should rarely be the case, as this would indicate that a non-log folds are present in the file
increment = increment+1
return expressionDataFormat,increment,convert
def calculate_expression_measures(expr_input_dir,expr_group_dir,experiment_name,comp_group_dir,probeset_db,annotate_db):
print "Processing the expression file:",expr_input_dir
try: expressionDataFormat,increment,convertNonLogToLog = checkExpressionFileFormat(expr_input_dir)
except Exception:
print traceback.format_exc()
expressionDataFormat = expression_data_format; increment = 0
if expressionDataFormat == 'non-log': convertNonLogToLog=True
else: convertNonLogToLog = False
#print convertNonLogToLog, expressionDataFormat, increment
global array_fold_headers; global summary_filtering_stats; global raw_data_comp_headers; global array_folds
fn1=filepath(expr_input_dir)
x = 0; y = 0; d = 0
blanksPresent=False
array_folds={}
for line in open(fn1,'rU').xreadlines():
data = cleanUpLine(line)
if data[0] != '#' and data[0] != '!':
fold_data = string.split(data,'\t')
try: arrayid = fold_data[0]
except Exception: arrayid = 'UID'
if len(arrayid)>0:
if arrayid[0]== ' ':
try: arrayid = arrayid[1:] ### Cufflinks issue
except Exception: arrayid = ' ' ### can be the first row UID column as blank
if 'ENSG' in arrayid and '.' in arrayid and '-' not in arrayid:
arrayid = string.split(arrayid,'.')[0]
else:
arrayid = 'UID'
#if 'counts.' in expr_input_dir: arrayid,coordinates = string.split(arrayid,'=') ### needed for exon-level analyses only
### differentiate data from column headers
if x == 1:
fold_data = fold_data[1:]; fold_data2=[]
"""
if len(array_names) != len(fold_data):
diff = len(fold_data)-len(fold_data)
fold_data+=diff*['']
if arrayid == 'FOXN4|1/2|10F06_ENSP00000299162':
print fold_data;sys.exit()
"""
for fold in fold_data:
fold = string.replace(fold,'"','')
try:
fold = float(fold); fold_data2.append(fold)
except Exception:
fold_data2.append('')
blanksPresent = True
"""
print_out = 'WARNING!!! The ID'+arrayid+ 'has an invalid expression value:'+[fold]+'\n. Correct and re-run'
try: UI.WarningWindow(print_out,'Critical Error - Exiting Program!!!'); sys.exit()
except NameError: print print_out; sys.exit()
"""
if expressionDataFormat == 'non-log' and (convertNonLogToLog or array_type == 'RNASeq'):
fold_data3=[] ###Convert numeric expression to log fold (previous to version 2.05 added 1)
for fold in fold_data2:
try:
log_fold = math.log((float(fold)+increment),2) ### changed from - log_fold = math.log((float(fold)+1),2) - version 2.05
fold_data3.append(log_fold)
except ValueError: ###Not an ideal situation: Value is negative - Convert to zero
try:
if float(fold)<=0:
log_fold = math.log(1.01,2); fold_data3.append(log_fold)
else:
fold_data3.append('')
blanksPresent = True
"""
print_out = 'WARNING!!! The ID'+arrayid+ 'has an invalid expression value:'+fold+'\n. Correct and re-run'
try: UI.WarningWindow(print_out,'Critical Error - Exiting Program!!!'); sys.exit()
except NameError: print print_out; sys.exit()
"""
except:
fold_data3.append('')
blanksPresent = True
fold_data2 = fold_data3
if (array_type == "AltMouse"):
if arrayid in probeset_db: array_folds[arrayid] = fold_data2; y = y+1
else: array_folds[arrayid] = fold_data2; y = y+1
else: #only grab headers if it's the first row
array_names = []; array_linker_db = {}
for entry in fold_data[1:]:
entry = string.replace(entry,'"','')
if len(entry)>0: array_names.append(entry)
for array in array_names: #use this to have an orignal index order of arrays
array = string.replace(array,'\r','') ###This occured once... not sure why
array_linker_db[array] = d; d +=1
#add this aftwards since these will also be used as index values
x = 1
print len(array_folds),"IDs imported...beginning to calculate statistics for all group comparisons"
expr_group_list,expr_group_db,dataType = importArrayGroups(expr_group_dir,array_linker_db,checkInputType=True)
comp_group_list, comp_group_list2 = importComparisonGroups(comp_group_dir)
if dataType=='Kallisto':
return None, None
if 'RPKM' in norm and 'counts.' in expr_input_dir: normalization_method = 'RPKM-counts' ### process as counts if analyzing the counts file
else: normalization_method = norm
if expressionDataFormat == 'non-log': logvalues=False
else: logvalues=True
if convertNonLogToLog: logvalues = True
try:
array_folds, array_fold_headers, summary_filtering_stats,raw_data_comp_headers = reorder_arrays.reorder(array_folds,array_names,expr_group_list,
comp_group_list,probeset_db,include_raw_data,array_type,normalization_method,fl,logvalues=logvalues,blanksPresent=blanksPresent)
except Exception:
print traceback.format_exc(),'\n'
print_out = 'AltAnalyze encountered an error with the format of the expression file.\nIf the data was designated as log intensities and it is not, then re-run as non-log.'
try: UI.WarningWindow(print_out,'Critical Error - Exiting Program!!!'); root.destroy(); force_exit ### Forces the error log to pop-up
except NameError: print print_out; sys.exit()
### Integrate maximum counts for each gene for the purpose of filtering (RNASeq data only)
if array_type == 'RNASeq' and 'counts.' not in expr_input_dir: addMaxReadCounts(expr_input_dir)
### Export these results to a DATASET statistics and annotation results file
if 'counts.' not in expr_input_dir:
if array_type == 'RNASeq' and norm == 'RPKM':
filterRNASeq(count_statistics_db)
### Export count summary in GenMAPP format
if include_raw_data == 'yes': headers = removeRawCountData(array_fold_headers)
else: headers = array_fold_headers
exportDataForGenMAPP(headers,'counts')
exportAnalyzedData(comp_group_list2,expr_group_db)
### Export formatted results for input as an expression dataset into GenMAPP or PathVisio
if data_type == 'expression':
if include_raw_data == 'yes': headers = removeRawData(array_fold_headers)
else: headers = array_fold_headers
exportDataForGenMAPP(headers,'expression')
try: clearObjectsFromMemory(summary_filtering_stats); clearObjectsFromMemory(array_folds)
except Exception: null=[]
try: clearObjectsFromMemory(summary_filtering_stats); summary_filtering_stats=[]
except Exception: null=[]
else:
### When performing an RNASeq analysis on RPKM data, we first perform these analyses on the raw counts to remove fold changes for low expressing genes
"""count_statistics_db={}; count_statistics_headers=[]
for key in array_folds:
count_statistics_db[key] = array_folds[key]
for name in array_fold_headers: count_statistics_headers.append(name)"""
try: clearObjectsFromMemory(summary_filtering_stats)
except Exception: null=[]
try: clearObjectsFromMemory(summary_filtering_stats); summary_filtering_stats=[]
except Exception: null=[]
return array_folds, array_fold_headers
def filterRNASeq(counts_db):
### Parse through the raw count data summary statistics and annotate any comparisons considered NOT EXPRESSED by read count filtering as not expressed (on top of RPKM filtering)
reassigned = 0; re = 0
for gene in counts_db:
i=0 ### keep track of the index (same as RPKM index)
for val in counts_db[gene]:
if val =='Insufficient Expression':
#print val, i, array_folds[gene][i];kill
if array_folds[gene][i] != 'Insufficient Expression': reassigned = gene, array_folds[gene][i]
array_folds[gene][i] = 'Insufficient Expression' ### Re-assign the fold changes to this non-numeric value
re+=1
i+=1
#print reassigned, re
def addMaxReadCounts(filename):
import RNASeq
max_count_db,array_names = RNASeq.importGeneCounts(filename,'max')
for gene in summary_filtering_stats:
gs = summary_filtering_stats[gene]
gs.setMaxCount(max_count_db[gene]) ### Shouldn't cause an error, but we want to get an exception if it does (something is wrong with the analysis)
def simplerGroupImport(group_dir):
if 'exp.' in group_dir or 'filteredExp.' in group_dir:
group_dir = string.replace(group_dir,'exp.','groups.')
group_dir = string.replace(group_dir,'filteredExp.','groups.')
import collections
try: sample_group_db = collections.OrderedDict()
except Exception:
try:
import ordereddict
sample_group_db = ordereddict.OrderedDict()
except Exception:
sample_group_db={}
fn = filepath(group_dir)
for line in open(fn,'rU').xreadlines():
data = cleanUpLine(line)
try:
group_data = string.split(data,'\t')
sample_filename = group_data[0]
group_name = group_data[-1]
if len(group_data)>3:
forceError
except Exception:
#print 'Non-Standard Groups file or missing relationships'
print string.split(data,'\t')[:10], 'more than 3 columns present in groups file'
kill
sample_group_db[sample_filename] = group_name
return sample_group_db
def simpleGroupImport(group_dir,splitHeaders=False, ignoreComps=False, reverseOrder=False):
""" Used for calculating fold changes prior to clustering for individual samples (genomtric folds) """
import collections
try:
### OrderedDict used to return the keys in the orders added for markerFinder
group_sample_db=collections.OrderedDict()
group_name_db=collections.OrderedDict()
group_name_sample_db=collections.OrderedDict()
group_db=collections.OrderedDict()
except Exception:
try:
import ordereddict
group_sample_db = ordereddict.OrderedDict()
group_name_db=ordereddict.OrderedDict()
group_name_sample_db=ordereddict.OrderedDict()
group_db=ordereddict.OrderedDict()
except Exception:
group_sample_db={}
group_name_db={}
group_name_sample_db={}
group_db={}
sample_list=[]
group_dir = verifyExpressionFile(group_dir)
fn = filepath(group_dir)
for line in open(fn,'rU').xreadlines():
data = cleanUpLine(line)
try: sample_filename,group_number,group_name = string.split(data,'\t')
except Exception:
print traceback.format_exc()
print "\nWARNING!!! Impropper groups file format detected. Terminating AltAnalyze. The groups file must have only three columns (sampleName, groupNumber, groupName).\n"
forceGroupsError
if splitHeaders:
if '~' in sample_filename: sample_filename = string.split(sample_filename,'~')[-1]
group_sample_db[sample_filename] = group_name+':'+sample_filename
if reverseOrder==False:
try: group_name_sample_db[group_name].append(group_name+':'+sample_filename)
except Exception: group_name_sample_db[group_name] = [group_name+':'+sample_filename]
else:
try: group_name_sample_db[group_name].append(sample_filename)
except Exception: group_name_sample_db[group_name] = [sample_filename]
sample_list.append(sample_filename)
group_db[sample_filename] = group_name
group_name_db[group_number]=group_name ### used by simpleCompsImport
### Get the comparisons indicated by the user
if ignoreComps==False: ### Not required for some analyses
comps_name_db,comp_groups = simpleCompsImport(group_dir,group_name_db,reverseOrder=reverseOrder)
else:
comps_name_db={}; comp_groups=[]
return sample_list,group_sample_db,group_db,group_name_sample_db,comp_groups,comps_name_db
def simpleCompsImport(group_dir,group_name_db,reverseOrder=False):
""" Used for calculating fold changes prior to clustering for individual samples (genomtric folds) """
comps_dir = string.replace(group_dir,'groups.','comps.')
import collections
comps_name_db=collections.OrderedDict()
comp_groups=[]
comps_dir = verifyExpressionFile(comps_dir)
fn = filepath(comps_dir)
for line in open(fn,'rU').xreadlines():
data = cleanUpLine(line)
try:
exp_group_num,con_group_num = string.split(data,'\t')
if reverseOrder:
con_group_num, exp_group_num = exp_group_num,con_group_num
exp_group_name = group_name_db[exp_group_num]
con_group_name = group_name_db[con_group_num]
try: comps_name_db[con_group_name].append(exp_group_name)
except Exception:
#comps_name_db[con_group_name] = [exp_group_name] ### If we don't want to include the control samples
comps_name_db[con_group_name] = [con_group_name] ### Add the control group versus itself the first time
comps_name_db[con_group_name].append(exp_group_name)
### Keep track of the order of the groups for ordering the cluster inputs
if con_group_name not in comp_groups:
comp_groups.append(con_group_name)
if exp_group_name not in comp_groups:
comp_groups.append(exp_group_name)
except Exception: pass ### Occurs if there are dummy lines in the file (returns with no values)
return comps_name_db,comp_groups
def importArrayGroups(expr_group_dir,array_linker_db,checkInputType=False):
new_index_order = 0
import collections
updated_groups = collections.OrderedDict()
expr_group_list=[]
expr_group_db = {} ### use when writing out data
fn=filepath(expr_group_dir)
data_type='null'
try:
try:
for line in open(fn,'rU').xreadlines():
data = cleanUpLine(line)
t = string.split(data,'\t')
length = string.join(t,'') ### Some lines can be blank
if len(length)>2:
array_header,group,group_name = t
group = int(group)
### compare new to original index order of arrays
try:
original_index_order = array_linker_db[array_header]
except:
if array_header+'.bed' in array_linker_db:
new_header = array_header+'.bed'
original_index_order = array_linker_db[new_header]
updated_groups[new_header]=group,group_name
elif array_header[:-4] in array_linker_db:
new_header = array_header[:-4]
original_index_order = array_linker_db[new_header]
updated_groups[new_header]=group,group_name
else:
print_out = 'WARNING!!! At least one sample-ID listed in the "groups." file (e.g.,'+array_header+')'+'\n is not in the sample "exp." file. See the new file "arrays." with all "exp." header names\nand correct "groups."'
try: UI.WarningWindow(print_out,'Critical Error - Exiting Program!!!')
except Exception: print print_out
exportArrayHeaders(expr_group_dir,array_linker_db)
try: root.destroy(); sys.exit()
except Exception: sys.exit()
entry = new_index_order, original_index_order, group, group_name
expr_group_list.append(entry)
new_index_order += 1 ### add this aftwards since these will also be used as index values
expr_group_db[str(group)] = group_name
expr_group_list.sort() ### sorting put's this in the original array order
except ValueError:
print_out = 'The group number "'+group+'" is not a valid integer. Correct before proceeding.'
try: UI.WarningWindow(print_out,'Critical Error - Exiting Program!!!'); root.destroy(); sys.exit()
except Exception: print print_out; sys.exit()
except Exception,e:
print traceback.format_exc(),'\n'
exportArrayHeaders(expr_group_dir,array_linker_db)
print_out = 'No groups or comps files found for'+expr_group_dir+'... exiting program.'
try: UI.WarningWindow(print_out,'Critical Error - Exiting Program!!!'); root.destroy(); sys.exit()
except Exception: print print_out; sys.exit()
if len(updated_groups)>0 and checkInputType:
import shutil
try: ### When a Kallisto TPM and a gene-RPKM file co-exist (prioritize differential analysis of Kallisto)
shutil.copy(expr_group_dir,string.replace(expr_group_dir,'.txt','-Kallisto.txt'))
scr_exp_dir = string.replace(expr_group_dir,'groups.','Kallisto_Results/exp.')
dst_exp_dir = string.replace(expr_group_dir,'groups.','exp.')
shutil.copy(scr_exp_dir,string.replace(dst_exp_dir,'.txt','-Kallisto.txt'))
src_comps_dir = string.replace(expr_group_dir,'groups.','comps.')
shutil.copy(src_comps_dir,string.replace(src_comps_dir,'.txt','-Kallisto.txt'))
except:
pass
data_type='Kallisto'
exportUpdatedGroups(expr_group_dir,updated_groups)
if checkInputType:
return expr_group_list,expr_group_db,data_type
else:
return expr_group_list,expr_group_db
def exportUpdatedGroups(expr_group_dir,updated_groups):
eo = export.ExportFile(expr_group_dir)
for sample in updated_groups:
eo.write(sample+'\t'+str(updated_groups[sample][0])+'\t'+updated_groups[sample][1]+'\n')
eo.close()
print 'The groups file has been updated with bed file sample names'
def exportArrayHeaders(expr_group_dir,array_linker_db):
new_file = string.replace(expr_group_dir,'groups.','arrays.')
new_file = string.replace(new_file,'exp.','arrays.')
new_file = string.replace(new_file,'counts.','arrays.')
if 'arrays.' not in new_file: new_file = 'arrays.' + new_file ### Can occur if the file does not have 'exp.' in it
fn=filepath(new_file); data = open(fn,'w')
for array in array_linker_db: data.write(array+'\n')
data.close()
def importComparisonGroups(comp_group_dir):
comp_group_list=[]; comp_group_list2=[]
try:
fn=filepath(comp_group_dir)
for line in open(fn,'rU').xreadlines():
data = cleanUpLine(line)
groups = string.split(data,'\t')
groups2 = groups[0],groups[1] #as a list these would be unhashable
comp_group_list.append(groups)
comp_group_list2.append(groups2)
except Exception: null=[] ### Occcurs when no file present
return comp_group_list, comp_group_list2
def importMicrornaAssociations(species,report):
filename = 'AltDatabase/Ensembl/'+species+'/'+species+'_microRNA-Ensembl.txt'
fn=filepath(filename); ensembl_microRNA_db={}
for line in open(fn,'rU').xreadlines():
data = cleanUpLine(line)
miR,ens_geneid,sources = string.split(data,'\t')
miR_annot = miR+'('+sources+')'
try: ensembl_microRNA_db[ens_geneid].append(miR_annot)
except KeyError: ensembl_microRNA_db[ens_geneid] = [miR_annot]
###Optionally filter out miRs with evidence from just one algorithm (options are 'any' and 'muliple'
for gene in ensembl_microRNA_db:
miRs = ensembl_microRNA_db[gene]; miRs.sort()
if report == 'multiple':
miRs2=[]
for mir in miRs:
if '|' in mir: miRs2.append(mir)
miRs=miRs2
miRs = string.join(miRs,', ')
ensembl_microRNA_db[gene] = miRs
return ensembl_microRNA_db
def importSystemCodes():
filename = 'Config/source_data.txt'
fn=filepath(filename); x=0; systems={}
for line in open(fn,'rU').readlines():
data = cleanUpLine(line)
t = string.split(data,'\t')
system_name=t[0];system_code=t[1]
if x==0: x=1
else: systems[system_name] = system_code
return systems
def exportDataForGenMAPP(headers,input_type):
###Export summary columns for GenMAPP analysis
systems = importSystemCodes()
GenMAPP_file = expression_dataset_output_dir + 'GenMAPP-'+experiment_name+'.txt'
if 'counts' in input_type:
GenMAPP_file = string.replace(GenMAPP_file,'GenMAPP-','COUNTS-')
try: genmapp = export.createExportFile(GenMAPP_file,expression_dataset_output_dir[:-1])
except RuntimeError:
export.isFileOpen(GenMAPP_file,expression_dataset_output_dir[:-1])
genmapp = export.createExportFile(GenMAPP_file,expression_dataset_output_dir[:-1])
if array_type == "3'array" and 'Ensembl' not in vendor:
if vendor == 'Affymetrix': system_code = 'X'
elif vendor == 'Illumina': system_code = 'Il'
elif vendor == 'Agilent': system_code = 'Ag'
elif vendor == 'Codelink': system_code = 'Co'
else:
### This is another system selected by the user
system = string.replace(vendor,'other:','')
try: system_code = systems[system]
except Exception: system_code = 'Sy'
elif array_type != 'AltMouse': system_code = 'En'
else:
try: system_code = systems[vendor]
except Exception: system_code = 'X'
genmapp_title = ['GeneID','SystemCode'] + headers
genmapp_title = string.join(genmapp_title,'\t')+'\t'+'ANOVA-rawp'+'\t'+'ANOVA-adjp'+'\t'+'largest fold'+'\n'
genmapp.write(genmapp_title)
for probeset in array_folds:
if 'ENS' in probeset and (' ' in probeset or '_' in probeset or ':' in probeset or '-' in probeset) and len(probeset)>9:
system_code = 'En'
ensembl_gene = 'ENS'+string.split(probeset,'ENS')[1]
if ' ' in ensembl_gene:
ensembl_gene = string.split(ensembl_gene,' ')[0]
if '_' in ensembl_gene:
ensembl_gene = string.split(ensembl_gene,'_')[0]
if ':' in ensembl_gene:
ensembl_gene = string.split(ensembl_gene,':')[0]
if '-' in ensembl_gene:
ensembl_gene = string.split(ensembl_gene,'-')[0]
data_val = ensembl_gene+'\t'+system_code
elif ('ENS' in probeset or 'ENF' in probeset) and system_code == 'Sy' and len(probeset)>9:
system_code = 'En'
data_val = probeset+'\t'+system_code
else:
data_val = probeset+'\t'+system_code
for value in array_folds[probeset]: data_val += '\t'+ str(value)
gs = summary_filtering_stats[probeset]
data_val += '\t'+ str(gs.Pval()) +'\t'+ str(gs.AdjP()) +'\t'+ str(gs.LogFold()) +'\n'
genmapp.write(data_val)
genmapp.close()
exportGOEliteInput(headers,system_code)
print 'Exported GO-Elite input files...'
def buildCriterion(ge_fold_cutoffs, ge_pvalue_cutoffs, ge_ptype, main_output_folder, operation, UseDownRegulatedLabel=False, genesToExclude={}, ExpName = None):
global array_folds; global m_cutoff; global p_cutoff; global expression_dataset_output_dir
global ptype_to_use; global use_downregulated_label; use_downregulated_label = UseDownRegulatedLabel
m_cutoff = math.log(float(ge_fold_cutoffs),2); p_cutoff = ge_pvalue_cutoffs; ptype_to_use = ge_ptype
expression_dataset_output_dir = string.replace(main_output_folder,'GO-Elite','ExpressionOutput/')
dir_list = read_directory(expression_dataset_output_dir[:-1])
if operation == 'summary': filetype = 'DATASET-'
else: filetype = 'GenMAPP-'
for filename in dir_list:
if ExpName != None:
expectedDatasetName = filetype + ExpName + '.txt' ### There can be multiple in ExpressionOutput (Kallisto/stead-state)
if filename != expectedDatasetName:
continue
if filetype in filename:
print 'Examining:',filename
fn=filepath(expression_dataset_output_dir+filename)
array_folds = {}; x=0
for line in open(fn,'rU').xreadlines():
data = cleanUpLine(line); t = string.split(data,'\t')
if x==0: x=1; headers = t[1:-2]
else:
values = t[1:-2]; probeset = t[0]; system_code = t[1]
if probeset not in genesToExclude: ### E.g., sex-associated or pseudogenes
array_folds[probeset] = values
if operation == 'summary':
exportGeneRegulationSummary(filename,headers,system_code)
else:
input_files_exported = exportGOEliteInput(headers,system_code)
array_folds=[]
def excludeGenesImport(filename):
fn=filepath(filename)
exclude_genes = {}
for line in open(fn,'rU').xreadlines():
data = cleanUpLine(line)
uid = string.split(data,'\t')[0]
exclude_genes[uid] = None
return exclude_genes
def importCountSummary(DATASETfile):
### Copied code from buildCriterion
count_summary_db={}
indexed_headers={}
filetype = 'COUNTS-'
filename = string.replace(DATASETfile,'DATASET-','COUNTS-')
fn=filepath(expression_dataset_output_dir+filename)
print 'Examining:',filename
count_summary_db = {}; x=0
for line in open(fn,'rU').xreadlines():
data = cleanUpLine(line); t = string.split(data,'\t')
if x==0:
x=1; i=0
for header in t:
indexed_headers[header]=i
i+=1
else:
values = t[1:-2]; probeset = t[0]; system_code = t[1]
count_summary_db[probeset] = values
return count_summary_db, indexed_headers
def exportGOEliteInput(headers,system_code):
### Filter statistics based on user-defined thresholds as input for GO-Elite analysis
criterion_db={}; denominator_geneids={}; index = 0; ttest=[]
for column in headers:
if 'ANOVA' in ptype_to_use and ptype_to_use in column: ttest.append(index) ### Not currently implemented
elif ptype_to_use in column and 'ANOVA' not in column: ttest.append(index)
lfi = 2 ### relative logfold index position
if ptype_to_use == 'adjp': lfi = 3
index+=1
### Had to introduce the below code to see if any p-values for a criterion are < 1 (otherwise, include them for GO-Elite)
exclude_p1={}
for probeset in array_folds:
index = 0; af = array_folds[probeset]
for value in array_folds[probeset]:
if index in ttest:
criterion_name = headers[index][5:]
if criterion_name not in exclude_p1:
try: p_value = float(value)
except Exception: p_value = 1 ### Occurs when a p-value is annotated as 'Insufficient Expression'
if p_value < 1:
exclude_p1[criterion_name] = True # Hence, at least one gene has a p<1
index+=1
for probeset in array_folds:
index = 0; af = array_folds[probeset]
for value in array_folds[probeset]:
denominator_geneids[probeset]=[]
if index in ttest:
criterion_name = headers[index][5:]
if use_downregulated_label==False:
rcn = string.split(criterion_name,'_vs_'); rcn.reverse() ### re-label all downregulated as up (reverse the numerator/denominator)
reverse_criterion_names = string.join(rcn,'_vs_')
regulation_call = '-upregulated'
else:
reverse_criterion_names = criterion_name
regulation_call = '-downregulated'
try: log_fold = float(af[index-lfi])
except Exception: log_fold = 0 ### Occurs when a fold change is annotated as 'Insufficient Expression'
try: p_value = float(value)
except Exception: p_value = 1 ### Occurs when a p-value is annotated as 'Insufficient Expression'
try: excl_p1 = exclude_p1[criterion_name] ### You can have adjusted p-values that are equal to 1
except Exception: excl_p1 = False #Make True to exclude ALL non-adjp < sig value entries
#print [log_fold, m_cutoff, p_value, p_cutoff];sys.exit()
if abs(log_fold)>m_cutoff and (p_value<p_cutoff or (p_value==1 and excl_p1==False)):
#if p_value == 1: print log_fold, probeset,[value]; sys.exit()
try: criterion_db[criterion_name].append((probeset,log_fold,p_value))
except KeyError: criterion_db[criterion_name] = [(probeset,log_fold,p_value)]
if log_fold>0:
try: criterion_db[criterion_name+'-upregulated'].append((probeset,log_fold,p_value))
except KeyError: criterion_db[criterion_name+'-upregulated'] = [(probeset,log_fold,p_value)]
else:
if use_downregulated_label==False:
log_fold = abs(log_fold)
try: criterion_db[reverse_criterion_names+regulation_call].append((probeset,log_fold,p_value))
except KeyError: criterion_db[reverse_criterion_names+regulation_call] = [(probeset,log_fold,p_value)]
index += 1
### Format these statistical filtering parameters as a string to include in the file as a record
if m_cutoff<0: fold_cutoff = -1/math.pow(2,m_cutoff)
else: fold_cutoff = math.pow(2,m_cutoff)
stat_filters = ' (Regulation criterion: fold > '+str(fold_cutoff)+' and '+ptype_to_use+ ' p-value < '+str(p_cutoff)+')'
stat_filters_filename = '-fold'+str(fold_cutoff)+'_'+ptype_to_use+str(p_cutoff)
### Format these lists to export as tab-delimited text files
if len(criterion_db)>0:
### Export denominator gene IDs
input_files_exported = 'yes'
expression_dir = string.replace(expression_dataset_output_dir,'ExpressionOutput/','')
goelite_file = expression_dir +'GO-Elite/denominator/GE.denominator.txt'
goelite = export.createExportFile(goelite_file,expression_dir+'GO-Elite/denominator')
goelite_title = ['GeneID','SystemCode']
goelite_title = string.join(goelite_title,'\t')+'\n'; goelite.write(goelite_title)
for probeset in denominator_geneids:
try:
if 'ENS' in probeset and (' ' in probeset or '_' in probeset or ':' in probeset or '-' in probeset) and len(probeset)>9:
system_code = 'En'
ensembl_gene = 'ENS'+string.split(probeset,'ENS')[1]
if ' ' in ensembl_gene:
ensembl_gene = string.split(ensembl_gene,' ')[0]
if '_' in ensembl_gene:
ensembl_gene = string.split(ensembl_gene,'_')[0]
if ':' in ensembl_gene:
ensembl_gene = string.split(ensembl_gene,':')[0]
if '-' in ensembl_gene:
ensembl_gene = string.split(ensembl_gene,'-')[0]
probeset = ensembl_gene
elif ':' in probeset:
probeset = string.split(probeset,':')[0]
system_code = 'Sy'
except Exception:
pass
if ('ENS' in probeset or 'ENF' in probeset) and system_code == 'Sy' and len(probeset)>9:
system_code = 'En'
values = string.join([probeset,system_code],'\t')+'\n'; goelite.write(values)
goelite.close()
### Export criterion gene IDs and minimal data
for criterion_name in criterion_db:
if criterion_name[-1] == ' ': criterion_file_name = criterion_name[:-1]
else: criterion_file_name = criterion_name
if 'upregulated' in criterion_name: elitedir = 'upregulated'
elif 'downregulated' in criterion_name: elitedir = 'downregulated'
else: elitedir = 'regulated'
goelite_file = expression_dir + 'GO-Elite/'+elitedir+'/GE.'+criterion_file_name+stat_filters_filename+'.txt'
goelite = export.ExportFile(goelite_file)
goelite_title = ['GeneID'+stat_filters,'SystemCode',criterion_name+'-log_fold',criterion_name+'-p_value']
goelite_title = string.join(goelite_title,'\t')+'\n'; goelite.write(goelite_title)
for (probeset,log_fold,p_value) in criterion_db[criterion_name]:
try:
if 'ENS' in probeset and (' ' in probeset or '_' in probeset or ':' in probeset or '-' in probeset):
system_code = 'En'
ensembl_gene = 'ENS'+string.split(probeset,'ENS')[1]
if ' ' in ensembl_gene:
ensembl_gene = string.split(ensembl_gene,' ')[0]
if '_' in ensembl_gene:
ensembl_gene = string.split(ensembl_gene,'_')[0]
if ':' in ensembl_gene:
ensembl_gene = string.split(ensembl_gene,':')[0]
if '-' in ensembl_gene:
ensembl_gene = string.split(ensembl_gene,'-')[0]
probeset = ensembl_gene
elif ':' in probeset:
probeset = string.split(probeset,':')[0]
system_code = 'Sy'
except Exception:
pass
values = string.join([probeset,system_code,str(log_fold),str(p_value)],'\t')+'\n'
goelite.write(values)
goelite.close()
else: input_files_exported = 'no'
return input_files_exported
def exportGeneRegulationSummary(filename,headers,system_code):
"""
1) Exports summary results description - Performs a series of targetted queries to report the number
of coding and non-coding genes expressed along with various regulation and annotation parameters.
2) Exports a global regulated expression table - Values are log2 geometric folds relative to baseline
of the entire row (all samples) for any criterion met (see ptype_to_use, m_cutoff, p_cutoff). Optionally
cluster these results downstream and perform QC analyses."""
criterion_db={}; detected_exp_db={}; denominator_geneids={}; index = 0; ttest=[]; avg_columns=[]; all_criterion=[]; all_groups=[]
search_miR = 'miR-1('
coding_types = ['protein_coding','ncRNA']
for column in headers:
if 'ANOVA' in ptype_to_use and ptype_to_use in column: ttest.append(index) ### Not currently implemented
elif ptype_to_use in column and 'ANOVA' not in column: ttest.append(index)
lfi = 2 ### relative logfold index position
if ptype_to_use == 'adjp': lfi = 3
index+=1
if 'Protein Classes' in column: pc = index-1
if 'microRNA' in column: mi = index-1
if 'avg-' in column: avg_columns.append(index-1)
if 'Symbol' in column: sy = index-1
try: count_summary_db,indexed_headers = importCountSummary(filename)
except Exception: count_summary_db={}
### Had to introduce the below code to see if any p-values for a criterion are < 1 (otherwise, include them for GO-Elite)
exclude_p1={}
for probeset in array_folds:
index = 0; af = array_folds[probeset]
for value in array_folds[probeset]:
if index in ttest:
criterion_name = headers[index][5:]
if criterion_name not in exclude_p1:
try: p_value = float(value)
except Exception: p_value = 1 ### Occurs when a p-value is annotated as 'Insufficient Expression'
if p_value < 1:
exclude_p1[criterion_name] = True # Hence, at least one gene has a p<1
index+=1
genes_to_import={}; probeset_symbol={}
for probeset in array_folds:
index = 0; af = array_folds[probeset]
probeset_symbol[probeset] = af[sy]
for value in array_folds[probeset]:
denominator_geneids[probeset]=[]
if index in avg_columns:
column_name = headers[index]
group_name = column_name[4:]
try: protein_class = af[pc]
except Exception: protein_class = 'NULL'
proceed = False
if array_type == 'RNASeq':
if norm == 'RPKM':
try: ### Counts file should be present but if not, still proceed
i2 = indexed_headers[column_name]
if float(af[index])>gene_rpkm_threshold and count_summary_db[probeset][i2]>gene_exp_threshold:
#if float(af[index])>5 and count_summary_db[probeset][i2]>50:
proceed = True
except Exception:
proceed = True
exp_info = probeset, af[index],count_summary_db[probeset][i2] ### keep track of the expression info
else:
if float(af[index])>expr_threshold:
proceed = True
exp_info = probeset, expr_threshold,expr_threshold
if proceed==True:
if group_name not in all_groups: all_groups.append(group_name)
if 'protein_coding' in protein_class:
try: detected_exp_db[group_name,'protein_coding'].append(exp_info)
except KeyError: detected_exp_db[group_name,'protein_coding']=[exp_info]
else:
try: detected_exp_db[group_name,'ncRNA'].append(exp_info)
except KeyError: detected_exp_db[group_name,'ncRNA']=[exp_info]
if index in ttest:
criterion_name = headers[index][5:]
try: log_fold = float(af[index-lfi])
except Exception: log_fold = 0 ### Occurs when a fold change is annotated as 'Insufficient Expression'
try: p_value = float(value)
except Exception: p_value = 1 ### Occurs when a p-value is annotated as 'Insufficient Expression'
try: excl_p1 = exclude_p1[criterion_name] ### You can have adjusted p-values that are equal to 1
except Exception: excl_p1 = False #Make True to exclude ALL non-adjp < sig value entries
try: protein_class = af[pc]
except Exception: protein_class = 'NULL'
if abs(log_fold)>m_cutoff and (p_value<p_cutoff or (p_value==1 and excl_p1==False)):
if criterion_name not in all_criterion: all_criterion.append(criterion_name)
try: criterion_db[criterion_name]+=1
except KeyError: criterion_db[criterion_name] = 1
genes_to_import[probeset]=[] ### All, regulated genes (any criterion)
if 'protein_coding' in protein_class:
if log_fold>0:
try: criterion_db[criterion_name,'upregulated','protein_coding']+=1
except KeyError: criterion_db[criterion_name,'upregulated','protein_coding'] = 1
else:
try: criterion_db[criterion_name,'downregulated','protein_coding']+=1
except KeyError: criterion_db[criterion_name,'downregulated','protein_coding'] = 1
else:
if protein_class == 'NULL':
class_name = 'unclassified'
else:
class_name = 'ncRNA'
if log_fold>0:
try: criterion_db[criterion_name,'upregulated',class_name]+=1
except KeyError: criterion_db[criterion_name,'upregulated',class_name] = 1
else:
try: criterion_db[criterion_name,'downregulated',class_name]+=1
except KeyError: criterion_db[criterion_name,'downregulated',class_name] = 1
index += 1
if len(criterion_db)>0:
try: exportGeometricFolds(expression_dataset_output_dir+filename,array_type,genes_to_import,probeset_symbol)
except Exception,e:
print 'Failed to export geometric folds due to:'
print e ### Don't exit the analysis just report the problem
print traceback.format_exc()
None
### Export lists of expressed genes
all_expressed={}
for (group_name,coding_type) in detected_exp_db:
eo = export.ExportFile(expression_dataset_output_dir+'/ExpressedGenes/'+group_name+'-'+coding_type+'.txt')
eo.write('GeneID\tRPKM\tCounts\n')
for (gene,rpkm,counts) in detected_exp_db[(group_name,coding_type)]:
eo.write(gene+'\t'+str(rpkm)+'\t'+str(counts)+'\n')
all_expressed[gene]=[]
try: eo.close()
except Exception: pass
filename = string.replace(filename,'DATASET-','SUMMARY-')
filename = string.replace(filename,'GenMAPP-','SUMMARY-')
summary_path = expression_dataset_output_dir +filename
export_data = export.ExportFile(summary_path)
print 'Export summary gene expression results to:',filename
### Output Number of Expressed Genes
title = ['Biological group']
for group_name in all_groups: title.append(group_name)
title = string.join(title,'\t')+'\n'; export_data.write(title)
if array_type == 'RNASeq':
### Only really informative for RNA-Seq data right now, since DABG gene-level stats are not calculated (too time-intensive for this one statistic)
for coding_type in coding_types:
if coding_type == 'protein_coding': values = ['Expressed protein-coding genes']
else: values = ['Expressed ncRNAs']
for group in all_groups:
for group_name in detected_exp_db:
if group in group_name and coding_type in group_name:
values.append(str(len(detected_exp_db[group_name])))
values = string.join(values,'\t')+'\n'; export_data.write(values)
export_data.write('\n')
if m_cutoff<0: fold_cutoff = -1/math.pow(2,m_cutoff)
else: fold_cutoff = math.pow(2,m_cutoff)
### Export criterion gene IDs and minimal data
export_data.write('Regulation criterion: fold > '+str(fold_cutoff)+' and '+ptype_to_use+ ' p-value < '+str(p_cutoff)+'\n\n')
for criterion in all_criterion:
title = [criterion,'up','down','up-'+search_miR[:-1],'down-'+search_miR[:-1]]
title = string.join(title,'\t')+'\n'; export_data.write(title)
for coding_type in coding_types:
values = ['Regulated '+coding_type+' genes']
for criterion_name in criterion_db:
if len(criterion_name)==3:
if criterion in criterion_name and ('upregulated',coding_type) == criterion_name[1:]:
values.append(str(criterion_db[criterion_name]))
if len(values)==1: values.append('0')
for criterion_name in criterion_db:
if len(criterion_name)==3:
if criterion in criterion_name and ('downregulated',coding_type) == criterion_name[1:]:
values.append(str(criterion_db[criterion_name]))
if len(values)==2: values.append('0')
for criterion_name in criterion_db:
if len(criterion_name)==4:
if criterion in criterion_name and ('upregulated',coding_type) == criterion_name[1:-1]:
values.append(str(criterion_db[criterion_name]))
if len(values)==3: values.append('0')
for criterion_name in criterion_db:
if len(criterion_name)==4:
if criterion in criterion_name and ('downregulated',coding_type) == criterion_name[1:-1]: