-
Notifications
You must be signed in to change notification settings - Fork 30
/
GO_Elite.py
2872 lines (2615 loc) · 160 KB
/
GO_Elite.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
###GO-Elite
#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 instructions importing existing over-representation analysis (ORA)
results, pruning redundant Gene Ontology paths, reading in command-line options and coordinating
all GO-Elite analysis and update functions found in other modules."""
try:
try: import traceback
except Exception: None
import sys, string
import os.path, platform
import unique; reload(unique)
import math
import copy
import time
import shutil
import webbrowser
import gene_associations; reload(gene_associations)
try: from import_scripts import OBO_import
except Exception: pass
import export
import UI
import mappfinder; reload(mappfinder)
import datetime
from visualization_scripts import WikiPathways_webservice
except Exception:
print_out = "\nWarning!!! Critical Python incompatiblity encoutered.\nThis can occur if the users calls the GO-Elite "
print_out += "python source code WITHIN A COMPILED version directory which results in critical conflicts between "
print_out += "the compiled distributed binaries and the operating systems installed version of python. "
print_out += "If this applies, either:\n(A) double-click on the executable GO-Elite file (GO-Elite or GO-Elite.exe) "
print_out += "or\n(B) download the Source-Code version of GO-Elite and run this version (after installing any needed "
print_out += "dependencies (see our Wiki or Documentation). Otherwise, contact us at: [email protected]\n\n"
print_out += "Installation Wiki: http://code.google.com/p/go-elite/wiki/Installation\n"
print print_out
try:
### Create a log report of this
import unique
try: log_file = unique.filepath('GO-Elite_error-report.log')
except Exception: log_file = unique.filepath('/GO-Elite_error-report.log')
log_report = open(log_file,'a')
log_report.write(print_out)
try: log_report.write(traceback.format_exc())
except Exception: None
log_report.close()
print 'See log file for additional technical details:',log_file
### Open this file
if os.name == 'nt':
try: os.startfile('"'+log_file+'"')
except Exception: os.system('open "'+log_file+'"')
elif 'darwin' in sys.platform: os.system('open "'+log_file+'"')
elif 'linux' in sys.platform: os.system('xdg-open "'+log_file+'/"')
except Exception: None
sys.exit()
debug_mode = 'no'
Tkinter_failure = False
start_time = time.time()
try: command_args = string.join(sys.argv,' ')
except Exception: command_args = ''
if len(sys.argv[1:])>1 and '-' in command_args:
use_Tkinter = 'no'
else:
try:
import Tkinter
from Tkinter import *
from visualization_scripts import PmwFreeze
use_Tkinter = 'yes'
except ImportError:
use_Tkinter = 'yes'
Tkinter_failure = True
###### File Import Functions ######
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 read_directory_extended(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 entry[-4:] == ".tab": dir_list2.append(entry)
return dir_list2
def refDir():
reference_dir=unique.refDir()
return reference_dir
def eliminate_redundant_dict_values(database):
db1={}
for key in database: list = unique.unique(database[key]); list.sort(); db1[key] = list
return db1
###### Classes ######
class GrabFiles:
def setdirectory(self,value):
self.data = value
def display(self):
print self.data
def searchdirectory(self,search_term):
#self is an instance while self.data is the value of the instance
files,file_dir,file = gene_associations.getDirectoryFiles(self.data,str(search_term))
if len(file)<1: print search_term,'not found'
return file_dir
def searchdirectory_start(self,search_term):
#self is an instance while self.data is the value of the instance
files,file_dir,file = gene_associations.getDirectoryFiles(self.data,str(search_term))
match = ''
for file in files:
split_strs = string.split(file,'.')
split_strs = string.split(split_strs[0],'/')
if search_term == split_strs[-1]: match = file
return match
def getDirectoryFiles(import_dir, search_term):
exact_file = ''; exact_file_dir=''
dir_list = read_directory_extended(import_dir) #send a sub_directory to a function to identify all files in a directory
for data in dir_list: #loop through each file in the directory to output results
if (':' in import_dir) or ('/Users/' == import_dir[:7]) or ('Linux' in platform.system()): affy_data_dir = import_dir+'/'+data
else: affy_data_dir = import_dir[1:]+'/'+data
if search_term in affy_data_dir: exact_file = affy_data_dir
return exact_file
def getAllDirectoryFiles(import_dir, search_term):
exact_files = []
dir_list = read_directory(import_dir) #send a sub_directory to a function to identify all files in a directory
for data in dir_list: #loop through each file in the directory to output results
if ':' in import_dir or ('/Users/' == import_dir[:7]) or ('Linux' in platform.system()): affy_data_dir = import_dir+'/'+data
else: affy_data_dir = import_dir[1:]+'/'+data
if search_term in affy_data_dir: exact_files.append(affy_data_dir)
return exact_files
###### GO-Elite Functions ######
def import_path_index():
global path_id_to_goid; global full_path_db; global all_nested_paths
try: built_go_paths, path_goid_db, path_dictionary = OBO_import.remoteImportOntologyTree(ontology_type)
except IOError:
### This exception was added in version 1.2 and replaces the code in OBO_import.buildNestedOntologyTree which resets the OBO version to 0/0/00 and re-runs (see unlisted_variable = kill)
print_out = "Unknown error encountered during Gene Ontology Tree import.\nPlease report to [email protected] if this error re-occurs."
try: UI.WarningWindow(print_out,'Error Encountered!'); root.destroy(); sys.exit()
except Exception: print print_out; sys.exit()
print 'Imported',ontology_type,'tree-structure for pruning'
full_path_db = built_go_paths
path_id_to_goid = path_goid_db
#all_nested_paths = path_dictionary
#print len(full_path_db), 'GO paths imported'
class MAPPFinderResults:
def __init__(self,goid,go_name,zscore,num_changed,onto_type,permute_p,result_line):
self._goid = goid; self._zscore = zscore; self._num_changed = num_changed
self._onto_type = onto_type; self._permute_p = permute_p; self._go_name= go_name
self._result_line = result_line
def GOID(self): return self._goid
def GOName(self): return self._go_name
def ZScore(self): return self._zscore
def NumChanged(self): return self._num_changed
def OntoType(self): return self._onto_type
def PermuteP(self): return self._permute_p
def ResultLine(self): return self._result_line
def Report(self):
output = self.GOID()+'|'+self.GOName()
return output
def __repr__(self): return self.Report()
def cleanUpLine(line):
line = string.replace(line,'\n','')
line = string.replace(line,'\c','')
data = string.replace(line,'\r','')
data = string.replace(data,'"','')
return data
def moveMAPPFinderFiles(input_dir):
###Create new archive directory
import datetime
dir_list = read_directory_extended(input_dir)
input_dir2 = input_dir
if len(dir_list)>0: ###if there are recently run files in the directory
today = str(datetime.date.today()); today = string.split(today,'-'); today = today[0]+''+today[1]+''+today[2]
time_stamp = string.replace(time.ctime(),':','')
time_stamp = string.replace(time_stamp,' ',' ')
time_stamp = string.split(time_stamp,' ') ###Use a time-stamp as the output dir (minus the day)
time_stamp = today+'-'+time_stamp[3]
if 'archived-' not in input_dir2: ### We don't want users to select an archived directory and have the results moved to a child archive directory.
archive_dir = input_dir2 +'/archived-'+time_stamp
fn = filepath(archive_dir)
try: os.mkdir(fn) ###create new directory
except Exception:
try: archive_dir = archive_dir[1:]; fn = filepath(archive_dir); os.mkdir(fn)
except Exception: null = [] ### directory already exists
###Read all files in old directory and copy to new directory
m = GrabFiles(); m.setdirectory(input_dir)
#print 'Moving MAPPFinder results to the archived directory',archive_dir
for mappfinder_input in dir_list:
mappfinder_input_dir = m.searchdirectory(mappfinder_input)
fn = filepath(mappfinder_input_dir)
fn2 = string.split(fn,'/')
destination_dir = string.join(fn2[:-1]+['/archived-'+time_stamp+'/']+[fn2[-1]],'/')
#destination_dir = string.replace(fn,'/'+mappfinder_dir+'/','/'+mappfinder_dir+'/archived-'+time_stamp+'/');
try: shutil.copyfile(fn, destination_dir)
except Exception:
print_out = "WARNING!!! Unable to move ORA results to an archived directory."
#print traceback.format_exc()
#print print_out
#try: UI.WarningWindow(print_out,' Exit ')
#except Exception: print print_out
proceed = 'no'
#while proceed == 'no':
try: os.remove(fn); proceed = 'yes'
except Exception:
pass
#print 'Tried to move the file',mappfinder_input,'to an archived folder, but it is currently open.'
#print 'Please close this file and hit return or quit GO-Elite'
#inp = sys.stdin.readline()
def checkPathwayType(filename):
type='GeneSet'
ontology_type = string.split(filename,'-')[-1][:-4]
if ontology_type == 'local': ontology_type = 'WikiPathways'
if ontology_type == 'GO': ontology_type = 'GeneOntology'
fn=filepath(filename); x=20; y=0
for line in open(fn,'rU').readlines():
y+=1
if y<x:
if 'Ontology-ID' in line: type = 'Ontology'
return ontology_type,type
def importMAPPFinderResults(filename):
zscore_changed_path_db = {}; go_full = {}; zscore_goid = {}
global dummy_db; dummy_db = {}; global file_headers; file_headers = []
global full_go_name_db; full_go_name_db = {}; filtered_mapps=[]; filtered_mapp_list = []
run_mod = ''; run_source=''; gene_identifier_file = ''
fn=filepath(filename); x=0; y=0
#print "Importing MAPPFinder data for:",filename
for line in open(fn,'rU').readlines():
data = cleanUpLine(line)
if x == 0 and y == 0:
if 'Ontology-ID' in data:
x = 1; go_titles = data + '\n'; input_file_type = 'Ontology'
elif 'Gene-Set Name' in data:
y = 1; mapp_titles = data + '\n'; input_file_type = 'GeneSet'
elif data in species_list: ###Check species from results file
if data in species_list: species = data; species_code = species_codes[species]
elif 'source identifiers supplied' in data:
space_delimited = string.split(data,' ')
gene_input_file_data = string.split(data,'supplied in the input file:')
putative_source_type = space_delimited[1] ###Extract out uid from GO/MAPP results file
if putative_source_type in source_types: run_source = putative_source_type
elif putative_source_type in mod_types: run_source = putative_source_type
if len(gene_input_file_data)>1: gene_identifier_file = gene_input_file_data[-1]
elif 'source identifiers linked to' in data:
space_delimited = string.split(data,' ')
putative_mod_type = space_delimited[-2] ###Extract out MOD from GO/MAPP results file
if putative_mod_type in mod_types: run_mod = putative_mod_type
elif 'Probes linked to a ' in data:
space_delimited = string.split(data,' ')
putative_mod_type = space_delimited[-2] ###Extract out MOD from GO/MAPP results file (derived from GenMAPP MAPPFinder results)
if putative_mod_type in mod_types: run_mod = putative_mod_type
else:
print_out = "WARNING!!! The MOD "+putative_mod_type+"\nused by GenMAPP MAPPFinder, is not\navailable in GO-Elite. Errors may\nresult in deriving propper gene\nassociations since a different MOD has to be\nused."
try: UI.WarningWindow(print_out,' Exit ')
except Exception: print print_out
elif x == 1:
try: goid, go_name, go_type, number_changed, number_measured, number_go, percent_changed, percent_present, z_score, permutep, adjustedp = string.split(data,'\t')
except ValueError:
t = string.split(data,'\t')
print_out = "WARNING...GeneOntology results file has too few or too many columns.\nExpected 16 columns, but read"+ str(len(t))
try: UI.WarningWindow(print_out,' Exit ')
except Exception:
print print_out; print t; print 'Please correct and re-run'
sys.exit()
if goid != 'GO': ###Exclude the top level of the GO tree (not an ID number MAPPFinder output)
#go_id_full = 'GO:'+goid
###Check to make sure that the GOID is the right length (usually proceeded by zeros which can be removed)
if len(goid)<7:
extended_goid=goid
while len(extended_goid)< 7: extended_goid = '0'+extended_goid
if extended_goid in full_path_db: goid = extended_goid
if goid in full_path_db:
for path in full_path_db[goid]:
#goid = int(goid); path = path_data.PathTuple() ###Path is a tuple of integers
z_score = float(z_score); permutep = float(permutep); number_changed = int(number_changed)
#path_list = string.split(path,'.')#; path_list=[]; full_tree_index[path] = path_list ###used to created nested gene associations to GO-elite terms
full_go_name_db[goid] = go_name
#enrichment_type
if number_changed > change_threshold and permutep < p_val_threshold and int(number_go) <= max_member_count:
if (z_score > z_threshold and enrichment_type=='ORA') or (z_score < (z_threshold*-1) and enrichment_type=='URA'):
#tree_index[path] = path_list; zscore_changed_path_db[path] = z_score, number_changed; zscore_goid[goid] = z_score, go_type; go_terms[path] = goid
z = MAPPFinderResults(goid,go_name,z_score,number_changed,input_file_type,permutep,data)
zscore_changed_path_db[path] = z; zscore_goid[goid] = z
go_full[goid]= data + '\n'
### for all entries, save a dummy entry. This is needed if we want to re-examine in MAPPFinder but don't want to visualize non-GO-elite selected terms
dummy_data = str(goid) +"\t"+ go_name +"\t"+ go_type
dummy_data = dummy_data+ "\t"+"0"+"\t"+"0"+"\t"+"0"+"\t"+"0"+"\t"+"0"+"\t"+"0"+"\t"+"0"+"\t"+"0"+"\t"+"0"+"\t"+"0"+"\t"+"0"+"\t"+"1"+"\t"+"1" +"\n"
dummy_db[goid] = dummy_data
elif y == 1:
###CODE USED TO PROCESS LOCAL RESULT FILES FOR MAPPS
try:
try:
t = string.split(data,'\t')
mapp_name = t[0]; num_changed = t[1]; zscore = t[6]; permutep = t[7]; num_on_mapp = t[3]
num_changed = int(num_changed); zscore = float(zscore); permutep = float(permutep)
#print [mapp_name, num_changed, zscore,permutep]
if num_changed > change_threshold and permutep < p_val_threshold and int(num_on_mapp) <= max_member_count:
if (zscore > z_threshold and enrichment_type=='ORA') or (zscore < (z_threshold*-1) and enrichment_type=='URA'):
filtered_mapps.append((zscore, line, mapp_name))
#zscore_goid[mapp_name] = zscore, 'MAPP'
z = MAPPFinderResults(mapp_name,mapp_name,zscore,num_changed,input_file_type,permutep,data)
zscore_goid[mapp_name] = z
filtered_mapp_list.append(mapp_name) ###Use this for downstream analyses
except ValueError: continue
except IndexError: continue
if x == 1:
try: species_code = species_code ###Test to see if there is a proper species name found
except UnboundLocalError:
#print 'No proper species name found in GO results. Please change and re-run'
#inp = sys.stdin.readline(); sys.exit()
###Pick arbitrary species code
for species in species_codes: species_code = species_codes[species]
return run_mod,run_source,zscore_changed_path_db, go_full, go_titles, zscore_goid, input_file_type, gene_identifier_file, species_code
if y == 1:
filtered_mapps.sort(); filtered_mapps.reverse()
return run_mod,run_source,filtered_mapp_list, filtered_mapps, mapp_titles, zscore_goid, input_file_type, gene_identifier_file, species_code
def buildFullTreePath(go_index_list):
"""Find common parent nodes among children and parents and collapse into a single branch node"""
global path_dictionary; path_dictionary = {}; path_dictionary_filtered={}
for tuple_index in go_index_list: path_dictionary[tuple_index] = [] ###store the original top level path-indeces
for tuple_index in go_index_list:
path_len = len(tuple_index); i=-1
while path_len+i > 0:
parent_path = tuple_index[:i]
if parent_path in path_dictionary:
path_dictionary[parent_path].append(tuple_index) ###if a parent path of a
i-=1
for parent_path in path_dictionary:
if len(path_dictionary[parent_path])>0:
path_dictionary[parent_path].sort()
path_dictionary_filtered[parent_path] = path_dictionary[parent_path]
### All GOIDs NOT in path_dictionary_filtered (no significant parents) are added back later
return path_dictionary_filtered
def buildOrderedTree(go_index_list):
"""Find common parent nodes among children and parents and collapse into a single branch node"""
path_dictionary = {}; path_dictionary_filtered={}; organized_tree_db={}
original_path_dictionary={}
for tuple_index in go_index_list:
path_dictionary[tuple_index] = [] ###store the original top level path-indeces
original_path_dictionary[tuple_index] = []
for tuple_index in go_index_list:
path_len = len(tuple_index); i=-1
while path_len+i > 0:
parent_path = tuple_index[:i]
if parent_path in path_dictionary:
path_dictionary[tuple_index].append(parent_path)
original_path_dictionary[parent_path].append(tuple_index)
i-=1
for parent_path in original_path_dictionary:
if len(original_path_dictionary[parent_path])>0:
original_path_dictionary[parent_path].sort()
path_dictionary_filtered[parent_path] = original_path_dictionary[parent_path]
### All GOIDs NOT in path_dictionary_filtered (no significant parents) are added back later
keys_to_delete={}
for child in path_dictionary:
if len(path_dictionary[child])>0:
path_dictionary[child].sort()
new_path = path_dictionary[child][1:]
for path in new_path:
keys_to_delete[path] = []
for path in keys_to_delete:
try: del path_dictionary[path]
except Exception: null=[]
parent_tree_db={}
for child in path_dictionary:
if len(path_dictionary[child])>0:
path_dictionary[child].sort()
new_path = path_dictionary[child][1:]+[child]
#print new_path, path_dictionary[child][0], path_dictionary[child];kill
try: parent_tree_db[path_dictionary[child][0]].append(new_path)
except Exception: parent_tree_db[path_dictionary[child][0]] = [new_path]
else:
organized_tree_db['node',child]=['null']
for path in keys_to_delete:
try: del parent_tree_db[path]
except Exception: null=[]
for path in parent_tree_db:
del organized_tree_db['node',path]
finished = 'no'
while finished == 'no':
parent_tree_db2={}; count=0
for parent_path in parent_tree_db:
if len(parent_tree_db[parent_path])>1:
for childset in parent_tree_db[parent_path]:
top_child = childset[0]
if len(childset)>1:
if 'node' not in parent_path:
new_parent = 'node',parent_path,top_child
else: new_parent = tuple(list(parent_path)+[top_child])
try: parent_tree_db2[new_parent].append(childset[1:])
except Exception: parent_tree_db2[new_parent] = [childset[1:]]
count+=1
elif len(childset)==1:
if 'node' not in parent_path:
new_parent = 'node',parent_path,top_child
else: new_parent = tuple(list(parent_path)+[top_child])
organized_tree_db[new_parent] = ['null']
else:
childset = parent_tree_db[parent_path][0]
if 'node' not in parent_path:
new_parent = 'node',parent_path
else: new_parent = parent_path
#if len(childset)>1: print new_parent, childset;kill
organized_tree_db[new_parent] = childset
if count == 0: finished = 'yes'
parent_tree_db = parent_tree_db2
possible_sibling_paths={}; siblings_reverse_lookup={}
for path in organized_tree_db:
if len(path)>2 and organized_tree_db[path]== ['null']:
try: possible_sibling_paths[path[-1][:-1]].append(path)
except Exception: possible_sibling_paths[path[-1][:-1]] = [path]
### Since some deepest children will have siblings, along with cousins on different branches, we must exclude these
for node in path[1:-1]:
try: siblings_reverse_lookup[node].append(path)
except KeyError: siblings_reverse_lookup[node] = [path]
for node in siblings_reverse_lookup:
try:
if len(siblings_reverse_lookup[node])!=len(possible_sibling_paths[node]):
try: del possible_sibling_paths[node]
except Exception: null=[]
except Exception: null=[]
for common_path in possible_sibling_paths:
if len(possible_sibling_paths[common_path])>1:
sibling_paths=[]
for key in possible_sibling_paths[common_path]:
new_key = tuple(['sibling1']+list(key[1:]))
organized_tree_db[new_key] = ['siblings_type1']
sibling_paths.append(key[-1])
del organized_tree_db[key]
sibling_paths = unique.unique(sibling_paths)
sibling_paths.sort()
new_key = tuple(['sibling2']+list(key[1:-1]))
organized_tree_db[new_key]=sibling_paths
"""
for i in organized_tree_db:
print i, organized_tree_db[i]
kill"""
return organized_tree_db,path_dictionary_filtered
def link_score_to_all_paths(all_paths,zscore_changed_path_db):
temp_list = []
parent_highest_score = {}
for entry in all_paths:
if entry in zscore_changed_path_db:
if filter_method == 'z-score': new_entry = zscore_changed_path_db[entry].ZScore(), entry
elif filter_method == 'gene number':new_entry = zscore_changed_path_db[entry].NumChanged(), entry
elif filter_method == 'combination':
z_score_val = zscore_changed_path_db[entry].ZScore()
gene_num = math.log(zscore_changed_path_db[entry].NumChanged(),2)
new_entry = gene_num*z_score_val, entry
else:
print 'error, no filter method selected!!'
break
for item in all_paths[entry]:
if filter_method == 'z-score':
new_item = zscore_changed_path_db[item].ZScore(), item
temp_list.append(new_item)
elif filter_method == 'gene number':
new_item = zscore_changed_path_db[item].NumChanged(), item
temp_list.append(new_item)
elif filter_method == 'combination':
z_score_val = zscore_changed_path_db[item].ZScore()
gene_num = math.log(zscore_changed_path_db[item].NumChanged(),2)
new_item = gene_num*z_score_val, item
temp_list.append(new_item)
else:
print 'error, no filter method selected!!'
break
max_child_score = max(temp_list)[0]
max_child_path = max(temp_list)[1]
parent_score = new_entry[0]
parent_path = new_entry[1]
if max_child_score <= parent_score:
parent_highest_score[parent_path] = all_paths[entry] #include the elite parent and it's children
#print "parent_path",parent_path,parent_score,"max_child_path", max_child_path, max_child_score
temp_list=[]
"""for entry in parent_highest_score:
print entry,':',parent_highest_score[entry]"""
#print "Number of parents > child in tree:",len(parent_highest_score)
return parent_highest_score
def calculate_score_for_children(tree, zscore_changed_path_db):
temp_list = []
child_highest_score = {}
for entry in tree: ###The tree is a key with one or more nodes representing a branch, chewed back, with or without children
for item in tree[entry]: #get the children of the tree
if item in zscore_changed_path_db:
if filter_method == 'z-score':
new_item = zscore_changed_path_db[item].ZScore(), item
temp_list.append(new_item)
elif filter_method == 'gene number':
new_item = zscore_changed_path_db[item].NumChanged(), item
temp_list.append(new_item)
elif filter_method == 'combination':
z_score_val = zscore_changed_path_db[item].ZScore()
gene_num = math.log(zscore_changed_path_db[item].NumChanged(),2)
new_item = gene_num*z_score_val, item
temp_list.append(new_item)
#print new_item,z_score_val
else:
print 'error, no filter method selected!!'
break
"""elif item == 'siblings_type1': #this will only occur if an parent had multiple children, none of them with nested children
if filter_method == 'z-score':
parent_item = entry[-1]
new_item = zscore_changed_path_db[parent_item][0], parent_item
temp_list.append(new_item)
elif filter_method == 'gene number':
new_item = zscore_changed_path_db[parent_item][1], parent_item
temp_list.append(new_item)
elif filter_method == 'combination':
z_score_val = zscore_changed_path_db[parent_item][0]
gene_num = math.log(zscore_changed_path_db[parent_item][1],2)
new_item = gene_num*z_score_val, parent_item
temp_list.append(new_item)"""
#print new_item,z_score_val
if len(temp_list)> 0: #if there is at least one nested go_path
max_child_score = max(temp_list)[0]
max_child_path = max(temp_list)[1]
child_highest_score[entry]=max_child_path
temp_list = []
"""for entry in child_highest_score:
print entry,':',child_highest_score[entry]"""
return child_highest_score
def collapse_tree(parent_highest_score,child_highest_score,tree):
collapsed = {}
collapsed_parents = {}
collapsed_children = {}
for entry in tree:
count=0 #see next comment
for item in entry:
if item in parent_highest_score and count==0: #ensures that only the top parent is added
collapsed_parents[entry] = item, parent_highest_score[item] #include the children of the elite parent to exclude later
### aka elite_parents[parent_paths] = elite_parent_path, non_elite_children
count +=1 #see last comment
break
for entry in tree:
if entry not in collapsed_parents: ###if the highest score does not occur for one of the parent terms in the key of the tree-branch
if entry in child_highest_score: ###Entry is the parent path stored and the value is the child path with the max score (greater than parent)
max_child_path = child_highest_score[entry]
collapsed_children[entry] = max_child_path, tree[entry] #include the children to exclude from other entries later (includes the max_child_path though)
"""for entry in collapsed_children:
print entry,':',collapsed_children[entry]"""
temp_list = []
for entry in collapsed_parents:
node = collapsed_parents[entry][0]
children = collapsed_parents[entry][1]
collapsed['parent',node] = children
"""if entry in tree:
for item in entry:
temp_list.append(item)
for item in tree[entry]:
temp_list.append(item)
temp_list.sort()
temp_list2 = unique.unique(temp_list)
collapsed['parent',node] = temp_list2
temp_list=[]"""
for entry in collapsed_children:
#previously we included the blocked out code which also
#would later exclude entries that contain key entry items in the elite entries
node = collapsed_children[entry][0]
siblings = collapsed_children[entry][1]
collapsed['child',node] = siblings
"""if entry in tree:
for item in entry: temp_list.append(item)
for item in tree[entry]: temp_list.append(item)
temp_list.sort()
temp_list2 = unique.unique(temp_list)
collapsed['child',node] = temp_list2
temp_list=[]"""
for entry in tree:
nested_path = tree[entry]
if nested_path == ['null']:
collapsed['unique',entry[-1]] = 'unique',entry[-1]
#print "The length of the collapsed list is:",len(collapsed)
###This code is used to check whether or not a tree with multiple siblings listed as children was added to collapsed because the parent term(s) had a higher score
###if not, we must individually add the child sibling terms
for entry in tree:
if tree[entry] == ['siblings_type1']:
parent_root_node = 'parent',entry[-2]
if parent_root_node not in collapsed:
#use 'child' since we have to over-write the child entry created if the 'parent' was'nt more significant (thus syblings would eroneously be considered children)
collapsed['child',entry[-1]] = 'node',entry[-1]
#for entry in collapsed:
#print entry,collapsed[entry]
return collapsed
def link_goid(tree,zscore_changed_path_db,all_paths):
"""Starting with the collapsed tree, convert to goids"""
temp1=[]; temp2=[]; new_tree = {}; count = 0
for entry in tree:
for top_node in entry:
try: goid = zscore_changed_path_db[top_node].GOID(); temp1.append(goid)
except KeyError: not_valid_goid = ''
for child_node in tree[entry]:
try: goid= zscore_changed_path_db[child_node].GOID(); temp2.append(goid)
except KeyError: not_valid_goid = ''
temp2.sort()
new_top = tuple(temp1) #one elite go-term in goid form
new_child = temp2 #list of children (value items) in dictionary, in goid form
count +=1; temp_list=[]
if new_top in new_tree: #if the new dictionary, new_tree already has this key added
top_node = new_top[0]
for node in new_tree[new_top]:
if node != top_node: temp_list.append(node)
for node in new_child:
if node != top_node: temp_list.append(node)
temp_list.sort(); new_list = unique.unique(temp_list)
new_tree[new_top] = new_list; temp_list=[]
else:
#print new_child[0], new_top[0]
if new_child[0] == new_top[0]: #if the first dictionary (which should be the only) value equals the key
new_tree[new_top] = []
else: ###note: if two parents, both more significant than all children, share a child, both will still be reported. This is fine, since we don't know the parent's relationship
temp_list2 = []
for node in new_child:
if node != new_top[0]: #get rid of values that equal the key!!!
temp_list2.append(node)
temp_list2.sort()
new_child = temp_list2
new_tree[new_top] = new_child #this should be the unique term
#print new_top, new_child
temp1 = []; temp2 = []
###remove entries that are parents or children of the most 'elite' entry, in dictionary
###note: parents of the entry shouldn't be selected, since collapsing chooses
###selects the highest scoring node.
if exclude_related == 'yes':
exclude = {}
for entry in new_tree:
for item in new_tree[entry]:
exclude[item] = ''
#print item, entry, new_tree[entry]
new_tree2={}
for entry in new_tree:
if entry[0] not in exclude:
new_tree2[entry[0]] = ''
new_tree = new_tree2
#for entry in tree: print entry,':',tree[entry]
#for entry in new_tree: print entry,':',new_tree[entry]
#print "Length of input tree/output tree",len(tree),'/',len(new_tree),'count:',count
return new_tree
def exportGOResults(go_full,go_titles,collapsed_go_tree,zscore_goid,go_gene_annotation_db,go_values_db,value_headers,goids_with_redundant_genes):
reference_dir = refDir()
if len(go_elite_output_folder) == 0: output_folder = "output"; ref_dir = reference_dir +'/'+output_folder
else: output_folder = go_elite_output_folder; ref_dir = go_elite_output_folder
output_results = output_folder+'/'+mappfinder_input[0:-4]+ '_' +filter_method +'_elite.txt'
if ontology_type == 'WikiPathways':
output_results = string.replace(output_results, 'WikiPathways','local') ### Makes the output filename compatible with GenMAPP-CS plugin filenames
if ontology_type == 'GO':
output_results = string.replace(output_results, 'GeneOntology','GO') ### Makes the output filename compatible with GenMAPP-CS plugin filenames
entries_added=[] #keep track of added GOIDs - later, add back un-added for MAPPFinder examination
print_out = 'Results file: '+output_results+ '\nis open...can not re-write.\nPlease close file and select "OK".'
try: raw = export.ExportFile(output_results)
except Exception:
try: UI.WarningWindow(print_out,' OK ')
except Exception:
print print_out; print 'Please correct (hit return to continue)'; inp = sys.stdin.readline()
if export_user_summary_values == 'yes' and len(value_headers)>0:
value_headers2=[]; stdev_headers=[]
for i in value_headers: value_headers2.append('AVG-'+i); stdev_headers.append('STDEV-'+i)
value_headers = '\t'+string.join(value_headers2+stdev_headers,'\t')
else: value_headers = ''
if len(go_gene_annotation_db)>0: go_titles = go_titles[:-1]+'\t'+'redundant with terms'+'\t'+'inverse redundant'+'\t'+'gene symbols'+value_headers+'\n' ###If re-outputing results after building gene_associations
raw.write(go_titles)
combined_results[output_results] = [((ontology_type,'Ontology'),mappfinder_input,go_titles)]
#append data to a list, to sort it by go_cateogry and z-score
collapsed_go_list = []; collapsed_go_list2 = []; goids_redundant_with_others={}
for entry in collapsed_go_tree:
goid = entry
entries_added.append(goid)
if goid in zscore_goid:
z_score_val = zscore_goid[goid].ZScore()
go_type = zscore_goid[goid].OntoType()
if sort_only_by_zscore == 'yes': info = z_score_val,z_score_val,goid
else: info = go_type,z_score_val,goid
collapsed_go_list.append(info); collapsed_go_list2.append(goid)
collapsed_go_list.sort()
collapsed_go_list.reverse()
for (go_type,z_score_val,goid) in collapsed_go_list:
if goid in go_full:
data = go_full[goid]
if len(go_gene_annotation_db)>0:
symbol_ls = []; goid_vals = ''
if goid in go_gene_annotation_db:
for s in go_gene_annotation_db[goid]:
if len(s.Symbol())>0: symbol_ls.append(s.Symbol()) #s.GeneID()
else: symbol_ls.append(s.GeneID())
if goid in go_values_db:
goid_vals = string.join(go_values_db[goid][0]+go_values_db[goid][1],'\t') ###mean of values from input file, for each GO term
symbol_ls = unique.unique(symbol_ls); symbol_ls.sort()
symbols = string.join(symbol_ls,'|')
try:
rr = goids_with_redundant_genes[goid]
redundant_with_terms = rr.RedundantNames(); inverse_redundant = rr.InverseNames()
if len(redundant_with_terms)>1: goids_redundant_with_others[goid]=[]
except KeyError: redundant_with_terms = ' '; inverse_redundant =' '
if export_user_summary_values == 'yes' and len(goid_vals)>0: goid_vals = '\t'+goid_vals
else: goid_vals = ''
data = data[:-1]+'\t'+redundant_with_terms+'\t'+inverse_redundant+'\t'+symbols+goid_vals+'\n' ###If re-outputing results after building gene_associations
raw.write(data)
combined_results[output_results].append(((ontology_type,'Ontology'),mappfinder_input,data))
raw.close()
combined_results[output_results].append((('',''),'',''))
summary_data_db['redundant_go_term_count'] = len(goids_redundant_with_others)
#print "New MAPPFinder Elite file", output_results, "written...."
return collapsed_go_list2
def exportLocalResults(filtered_mapps,mapp_titles,mapp_gene_annotation_db,mapp_values_db,mapp_value_headers,mapps_with_redundant_genes):
if len(go_elite_output_folder) == 0: output_folder = "output"
else: output_folder = go_elite_output_folder
output_results = output_folder+'/'+mappfinder_input[0:-4]+ '_' +filter_method + '_elite.txt'
try: raw = export.ExportFile(output_results)
except Exception:
try: UI.WarningWindow(print_out,' OK ')
except Exception:
print print_out; print 'Please correct (hit return to continue)'; inp = sys.stdin.readline()
if export_user_summary_values == 'yes' and len(mapp_value_headers)>0:
mapp_value_headers2=[]; stdev_headers=[]
for i in mapp_value_headers: mapp_value_headers2.append('AVG-'+i); stdev_headers.append('STDEV-'+i)
mapp_value_headers = '\t'+string.join(mapp_value_headers2+stdev_headers,'\t')
else: mapp_value_headers = ''
if len(mapp_gene_annotation_db)>0: mapp_titles = mapp_titles[:-1]+'\t'+'redundant with terms'+'\t'+'inverse redundant'+'\t'+'gene symbols'+mapp_value_headers+'\n'
raw.write(mapp_titles)
combined_results[output_results] = [((ontology_type,'GeneSet'),mappfinder_input,mapp_titles)]
filtered_mapp_list = []; mapps_redundant_with_others={}
for (zscore,line,mapp_name) in filtered_mapps:
if len(mapp_gene_annotation_db)>0:
symbol_ls = []; mapp_vals=''
if mapp_name in mapp_gene_annotation_db:
for s in mapp_gene_annotation_db[mapp_name]:
if len(s.Symbol())>0: symbol_ls.append(s.Symbol()) #s.GeneID()
else: symbol_ls.append(s.GeneID())
symbol_ls = unique.unique(symbol_ls); symbol_ls.sort()
symbols = string.join(symbol_ls,'|')
if mapp_name in mapp_values_db:
mapp_vals = string.join(mapp_values_db[mapp_name][0]+mapp_values_db[mapp_name][1],'\t') ###mean of values from input file, for each MAPP
try:
rr = mapps_with_redundant_genes[mapp_name]
redundant_with_terms = rr.RedundantNames(); inverse_redundant = rr.InverseNames()
if len(redundant_with_terms)>1: mapps_redundant_with_others[mapp_name]=[]
except KeyError: redundant_with_terms = ' '; inverse_redundant = ' '
if export_user_summary_values == 'yes' and len(mapp_vals)>0: mapp_vals = '\t'+mapp_vals
else: mapp_vals = ''
line = line[:-1]+'\t'+redundant_with_terms+'\t'+inverse_redundant+'\t'+symbols+mapp_vals+'\n' ###If re-outputing results after building gene_associations
raw.write(line)
combined_results[output_results].append(((ontology_type,'GeneSet'),mappfinder_input,line))
raw.close()
combined_results[output_results].append((('',''),'',''))
#print "Local Filtered MAPPFinder file", output_results, "written...."
summary_data_db['redundant_mapp_term_count'] = len(mapps_redundant_with_others)
def importORASimple(ora_dir,elite_pathway_db,file_type):
""" This function imports pathway data for any elite pathway from the unfiltered results """
summary_results_db={}
ontology_name = file_type
if file_type == 'GeneOntology': file_type = 'GO.'
if file_type == 'WikiPathways': file_type = 'local'
dir_list = read_directory(ora_dir)
for file in dir_list:
if '.txt' in file and file_type in file:
fn=filepath(ora_dir+'/'+file)
for line in open(fn,'rU').readlines():
data = cleanUpLine(line)
t = string.split(data,'\t')
try:
### Applies to Ontology ORA files
pathway_id = t[0]; pathway_name = t[1]; num_changed = t[3]; num_measured = t[4]; zscore = t[8]; permutep = t[9]; pathway_type = t[2]
except IndexError:
### Applies to Local pathway files
try:
pathway_name = t[0]; num_changed = t[1]; num_measured = t[2]; zscore = t[6]; permutep = t[7]; pathway_id = pathway_name; pathway_type = 'GeneSet'
except Exception: pathway_name='null'
### If the pathway/ontology term was considered a pruned term (elite)
if (pathway_name,ontology_name) in elite_pathway_db:
try:
int(num_changed)
### Encode this data immediately for combination with the other input files and for export
key = (pathway_id,pathway_name,ontology_name,pathway_type)
values = [num_changed,num_measured,zscore,permutep]
try: summary_results_db[pathway_name,key].append([file,values])
except Exception: summary_results_db[pathway_name,key] = [[file,values]]
except Exception: null=[]
return summary_results_db
def outputOverlappingResults(combined_results,ora_dir):
"""For any elite term/pathway from a user analysis, output all associated original ORA data"""
output_folder = go_elite_output_folder
output_results = output_folder+'/'+'overlapping-results_' +filter_method + '_elite.txt'
proceed = 'no'
while proceed == 'no':
try: raw = export.ExportFile(output_results); proceed = 'yes'
except Exception:
print_out = output_results, '\nis open. Please close and select "Continue".'
try: UI.WarningWindow(print_out,' OK ')
except Exception:
print print_out; print 'Please correct (hit return to continue)'; inp = sys.stdin.readline()
filename_list=[]; criterion={}
for filename in combined_results:
filename_list.append(filename)
criterion[string.join(string.split(filename,'-')[:-2],'-')]=None
filename_list.sort() ### rank the results alphebetically so local and GO results are sequential
ontology_to_filename={}; pathway_to_filename={}
### determine which Elite pathways are in which files and store
if len(criterion)>1:
ontology_files={}; local_files={}
for filename in filename_list:
file = export.findFilename(filename)[:-4]
for (pathway_type,mapp_name,line) in combined_results[filename]:
specific_pathway_type,pathway_type = pathway_type
t = string.split(line,'\t')
if pathway_type == 'Ontology':
go_name = t[1]
try: ontology_to_filename[go_name,specific_pathway_type].append(file)
except Exception: ontology_to_filename[go_name,specific_pathway_type]=[file]
if specific_pathway_type not in ontology_files:
ontology_files[specific_pathway_type] = [file]
elif file not in ontology_files[specific_pathway_type]:
ontology_files[specific_pathway_type].append(file)
elif pathway_type == 'GeneSet':
pathway_name = t[0]
try: pathway_to_filename[pathway_name,specific_pathway_type].append(file)
except Exception: pathway_to_filename[pathway_name,specific_pathway_type]=[file]
if specific_pathway_type not in local_files:
local_files[specific_pathway_type] = [file]
elif file not in local_files[specific_pathway_type]:
local_files[specific_pathway_type].append(file)
headers = ['number_changed','number_measured',' z_score','permuteP']
header_ontology = ['Ontology-ID','Ontology-term','Ontology-name','Ontology-type','elite_term_in']
header_local = ['GeneSet-ID','GeneSet-term','GeneSet-name','GeneSet-type','elite_term_in']
for ontology_type in ontologies_analyzed:
input_file_type = ontologies_analyzed[ontology_type]
if input_file_type == 'Ontology':
ontology_elite_db = importORASimple(ora_dir,ontology_to_filename,ontology_type)
writeOverlapLine(raw,ontology_files,headers,header_ontology,ontology_elite_db,ontology_to_filename,ontology_type)
else:
local_elite_db = importORASimple(ora_dir,pathway_to_filename,ontology_type)
writeOverlapLine(raw,local_files,headers,header_local,local_elite_db,pathway_to_filename,ontology_type)
raw.write('\n')
raw.close()
### Move to the root directory
fn = filepath(output_results)
fn2 = string.replace(fn,'CompleteResults/ORA_pruned','')
try:
export.customFileMove(fn,fn2)
from visualization_scripts import clustering
clustering.clusterPathwayZscores(fn2) ### outputs the overlapping results as a heatmap
except Exception,e:
#print e
#print fn; print fn2; print "OverlapResults failed to be copied from CompleteResults (please see CompleteResults instead)"
pass
def writeOverlapLine(raw,ontology_files,headers,header_ontology,ontology_elite_db,ontology_to_filename,ontology_type):
file_headers=[]
filenames = ontology_files[ontology_type]
filenames.sort() ### Sort by filename
for filename in filenames:
file_headers += updateHeaderName(headers,filename)
title = string.join(header_ontology+file_headers,'\t')+'\n'
raw.write(title)
for (pathway_name,key) in ontology_elite_db:
elite_files = string.join(ontology_to_filename[pathway_name,ontology_type],'|')
row = list(key)+[elite_files]
scores_data = ontology_elite_db[(pathway_name,key)]
scores_data.sort() ### Sort by filename to match above
for (file,values) in scores_data:
row += values
raw.write(string.join(row,'\t')+'\n')
def updateHeaderName(headers,filename):
headers_copy = copy.deepcopy(headers)
i=0
for header in headers_copy:
headers_copy[i]=header+'.'+filename
i+=1
return headers_copy
def output_combined_results(combined_results):
if len(go_elite_output_folder) == 0: output_folder = "output"
else: output_folder = go_elite_output_folder
output_results = output_folder+'/'+'pruned-results_' +filter_method + '_elite.txt'
proceed = 'no'
while proceed == 'no':
try: raw = export.ExportFile(output_results); proceed = 'yes'
except Exception:
print_out = output_results, '\nis open. Please close and select "Continue".'
try: UI.WarningWindow(print_out,' OK ')
except Exception:
print print_out; print 'Please correct (hit return to continue)'; inp = sys.stdin.readline()
filename_list=[]
for filename in combined_results: filename_list.append(filename)
filename_list.sort() ### rank the results alphebetically so local and GO results are seqeuntial
for filename in filename_list:
for (pathway_type,mapp_name,line) in combined_results[filename]:
specific_pathway_type,pathway_type = pathway_type
data = cleanUpLine(line)
t = string.split(data,'\t')
if pathway_type == 'Ontology':
goid = t[0]
del t[0]; #del t[2:7]
go_type = t[1]; del t[1]; specific_pathway_type = go_type
t[0] = t[0]+'('+goid+')'
t.reverse(); t.append(specific_pathway_type); t.append(mapp_name); t.reverse()
vals = string.join(t,'\t'); vals = vals + '\n'
raw.write(vals)
#print filename, len(combined_results[filename])
raw.close()
def identifyGeneFiles(import_dir, mappfinder_input):
e = GrabFiles(); e.setdirectory(import_dir)
if len(gene_identifier_file)>0: ###global variable set upon MAPPFinder result import
gene_file_dir = e.searchdirectory(gene_identifier_file)
return gene_file_dir
else:
mappfinder_input = string.replace(mappfinder_input,'-GO.txt','') ###the prefix in most cases will be the same for the MAPPFinder results and gene input filename
mappfinder_input = string.replace(mappfinder_input,'-local.txt','')
split_name = string.split(mappfinder_input,'.')
gene_file_dir = e.searchdirectory(mappfinder_input)
if len(gene_file_dir)>0: return gene_file_dir
else:
try:
index = int(split_name[0])
index_str = str(index)
gene_file_dir = e.searchdirectory_start(index_str)
except ValueError: gene_file_dir =''
return gene_file_dir
def grabAllNestedGOIDs(collapsed_go_tree,all_paths):
###Updated all_paths contains all possible paths listed in GO
nested_collapsed_go_tree={}
for goid_tuple in collapsed_go_tree:
for goid in goid_tuple:
child_goids=[]
path_id_list = full_path_db[goid]
for path_id in path_id_list: ###examine all possible paths for that goid (and different possible children)
#path_id = path_id_data.PathTuple()
if path_id in all_paths:
child_path_id_list = all_paths[path_id]