-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBuildAffymetrixAssociations.py
1325 lines (1222 loc) · 72.5 KB
/
BuildAffymetrixAssociations.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
###BuildAffymetrixAssociations
#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 methods for reading Affymetrix formatted CSV annotations files
from http://www.affymetrix.com, extracting out various direct and inferred gene relationships,
downloading, integrating and inferring WikiPathway gene relationships and downloading and
extracting EntrezGene-Gene Ontology relationships from NCBI."""
import sys, string
import os.path
import unique
import datetime
import export
import update
import gene_associations
import OBO_import
################# Parse directory files
def filepath(filename):
fn = unique.filepath(filename)
return fn
def read_directory(sub_dir):
try:
dir_list = unique.read_directory(sub_dir)
#add in code to prevent folder names from being included
dir_list2 = []
for entry in dir_list:
if entry[-4:] == ".txt" or entry[-4:] == ".csv" or entry[-4:] == ".TXT" or entry[-4:] == ".tab" or '.zip' in entry:
dir_list2.append(entry)
except Exception:
#print sub_dir, "NOT FOUND!!!!"
dir_list2=[]
return dir_list2
def returnDirectories(sub_dir):
dir_list = unique.returnDirectories(sub_dir)
###Below code used to prevent folder names from being included
dir_list2 = []
for i in dir_list:
if "." not in i: dir_list2.append(i)
return dir_list2
def cleanUpLine(line):
data = string.replace(line,'\n','')
data = string.replace(data,'\c','')
data = string.replace(data,'\r','')
data = string.replace(data,'"','')
return data
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
file = getDirectoryFiles(self.data,str(search_term))
if len(file)<1: print search_term,'not found'
return file
def returndirectory(self):
dir_list = read_directory(self.data)
return dir_list
def getDirectoryFiles(import_dir, search_term):
exact_file = ''
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
affy_data_dir = import_dir[1:]+'/'+data
if search_term in affy_data_dir: exact_file = affy_data_dir
return exact_file
################# Import and Annotate Data
class AffymetrixInformation:
def __init__(self,probeset,symbol,ensembl,entrez,unigene,uniprot,description,goids,go_names,pathways):
self._probeset = probeset; self._ensembl = ensembl; self._uniprot = uniprot; self._description = description
self._entrez = entrez; self._symbol = symbol; self._unigene = unigene
self._goids = goids; self._go_names = go_names; self._pathways = pathways
def ArrayID(self): return self._probeset
def Description(self): return self._description
def Symbol(self): return self._symbol
def Ensembl(self): return self._ensembl
def EnsemblString(self):
ens_str = string.join(self._ensembl,'|')
return ens_str
def Entrez(self): return self._entrez
def EntrezString(self):
entrez_str = string.join(self._entrez,'|')
return entrez_str
def Unigene(self): return self._unigene
def UnigeneString(self):
unigene_str = string.join(self._unigene,'|')
return unigene_str
def Uniprot(self): return self._uniprot
def GOIDs(self): return self._goids
def GOProcessIDs(self): return self._goids[0]
def GOComponentIDs(self): return self._goids[1]
def GOFunctionIDs(self): return self._goids[2]
def GONameLists(self): return self._go_names
def GOProcessNames(self):
go_names = string.join(self._go_names[0],' // ')
return go_names
def GOComponentNames(self):
go_names = string.join(self._go_names[1],' // ')
return go_names
def GOFunctionNames(self):
go_names = string.join(self._go_names[2],' // ')
return go_names
def GONames(self):
go_names = self._go_names[0]+self._go_names[1]+self._go_names[2]
return go_names
def Pathways(self): return self._pathways
def PathwayInfo(self):
pathway_str = string.join(self.Pathways(),' // ')
return pathway_str
def GOPathwayInfo(self):
pathway_str = string.join(self.GONames() + self.Pathways(),' // ')
return pathway_str
def resetEnsembl(self,ensembl): self._ensembl = ensembl
def resetEntrez(self,entrez): self._entrez = entrez
def setSequence(self,seq): self.seq = seq
def setSpecies(self,species): self.species = species
def setCoordinates(self,coordinates): self.coordinates = coordinates
def Sequence(self): return self.seq
def Species(self): return self.species
def Coordinates(self): return self.coordinates
def ArrayValues(self):
output = self.Symbol()+'|'+self.ArrayID()
return output
def __repr__(self): return self.ArrayValues()
class InferredEntrezInformation:
def __init__(self,symbol,entrez,description):
self._entrez = entrez; self._symbol = symbol; self._description = description
def Entrez(self): return self._entrez
def Symbol(self): return self._symbol
def Description(self): return self._description
def DataValues(self):
output = self.Symbol()+'|'+self.Entrez()
return output
def __repr__(self): return self.DataValues()
def eliminate_redundant_dict_values(database):
db1={}
for key in database: list = unique.unique(database[key]); list.sort(); db1[key] = list
return db1
def buildMODDbase():
mod_db={}
mod_db['Dr'] = 'FlyBase'
mod_db['Ce'] = 'WormBase'
mod_db['Mm'] = 'MGI Name'
mod_db['Rn'] = 'RGD Name'
mod_db['Sc'] = 'SGD accession number'
mod_db['At'] = 'AGI'
return mod_db
def verifyFile(filename):
fn=filepath(filename); file_found = 'yes'
try:
for line in open(fn,'rU').xreadlines():break
except Exception: file_found = 'no'
return file_found
######### Import New Data ##########
def parse_affymetrix_annotations(filename,species):
###Import an Affymetrix array annotation file (from http://www.affymetrix.com) and parse out annotations
temp_affy_db = {}; x=0; y=0
if process_go == 'yes':
eg_go_found = verifyFile('Databases/'+species+'/gene-go/EntrezGene-GeneOntology.txt')
ens_go_found = verifyFile('Databases/'+species+'/gene-go/Ensembl-GeneOntology.txt')
if eg_go_found == 'no' or ens_go_found == 'no': process_go_var = 'yes'
else: process_go_var = 'yes'
fn=filepath(filename); mod_db = buildMODDbase()
for line in open(fn,'r').readlines():
probeset_data = string.replace(line,'\n','') #remove endline
probeset_data = string.replace(probeset_data,'---','')
affy_data = string.split(probeset_data[1:-1],'","') #remove endline
try: mod_name = mod_db[species]
except KeyError: mod_name = 'YYYYYY' ###Something that should not be found
if x==0 and line[0]!='#':
x=1; affy_headers = affy_data
for header in affy_headers:
y = 0
while y < len(affy_headers):
if 'Probe Set ID' in affy_headers[y] or 'probeset_id' in affy_headers[y]: ps = y
if 'transcript_cluster_id' in affy_headers[y]: tc = y
if 'Gene Symbol' in affy_headers[y]: gs = y
if 'Ensembl' in affy_headers[y]: ens = y
if ('nigene' in affy_headers[y] or 'UniGene' in affy_headers[y]) and 'Cluster' not in affy_headers[y]: ug = y
if 'mrna_assignment' in affy_headers[y]: ma = y
if 'gene_assignment' in affy_headers[y]: ga = y
if 'Entrez' in affy_headers[y] or 'LocusLink' in affy_headers[y]: ll = y
if 'SwissProt' in affy_headers[y] or 'swissprot' in affy_headers[y]: sp = y
if 'Gene Title' in affy_headers[y]: gt = y
if 'rocess' in affy_headers[y]: bp = y
if 'omponent' in affy_headers[y]: cc = y
if 'unction' in affy_headers[y]: mf = y
if 'RefSeq Protein' in affy_headers[y]: rp = y
if 'RefSeq Transcript' in affy_headers[y]: rt = y
if 'athway' in affy_headers[y]: gp = y
### miRNA array specific
if 'Alignments' == affy_headers[y]: al = y
if 'Transcript ID(Array Design)' in affy_headers[y]: ti = y
if 'Sequence Type' in affy_headers[y]: st = y
if 'Sequence' == affy_headers[y]: sq = y
if 'Species Scientific Name' == affy_headers[y]: ss = y
if mod_name in affy_headers[y]: mn = y
y += 1
elif x == 1:
###If using the Affy 2.0 Annotation file structure, both probeset and transcript cluster IDs are present
###If transcript_cluster centric file (gene's only no probesets), then probeset = transcript_cluster
try:
transcript_cluster = affy_data[tc] ###Affy's unique Gene-ID
probeset = affy_data[ps]
if probeset != transcript_cluster: ###Occurs for transcript_cluster ID centered files
probesets = [probeset,transcript_cluster]
else: probesets = [probeset]
ps = tc; version = 2 ### Used to define where the non-UID data exists
except UnboundLocalError:
try: probesets = [affy_data[ps]]; uniprot = affy_data[sp]; version = 1
except Exception: probesets = [affy_data[ps]]; version = 3 ### Specific to miRNA arrays
try: uniprot = affy_data[sp]; unigene = affy_data[ug]; uniprot_list = string.split(uniprot,' /// ')
except Exception: uniprot=''; unigene=''; uniprot_list=[] ### This occurs due to miRNA array or a random python error, typically once twice in the file
symbol = ''; description = ''
try: pathway_data = affy_data[gp]
except Exception: pathway_data='' ### This occurs due to miRNA array or a random python error, typically once twice in the file
for probeset in probesets:
if version == 1: ###Applies to 3' biased arrays only (Conventional Format)
description = affy_data[gt]; symbol = affy_data[gs]; goa=''; entrez = affy_data[ll]
ensembl_list = []; ensembl = affy_data[ens]; ensembl_list = string.split(ensembl,' /// ')
entrez_list = string.split(entrez,' /// '); unigene_list = string.split(unigene,' /// ')
uniprot_list = string.split(uniprot,' /// '); symbol_list = string.split(symbol,' /// ')
try: mod = affy_data[mn]; mod_list = string.split(mod,' /// ')
except UnboundLocalError: mod = ''; mod_list = []
if len(symbol)<1 and len(mod)>0: symbol = mod ### For example, for At, use Tair if no symbol present
if len(mod_list)>3: mod_list=[]
ref_prot = affy_data[rp]; ref_prot_list = string.split(ref_prot,' /// ')
ref_tran = affy_data[rt]; ref_tran_list = string.split(ref_tran,' /// ')
###Process GO information if desired
if process_go_var == 'yes':
process = affy_data[bp]; component = affy_data[cc]; function = affy_data[mf]
process_goids, process_names = extractPathwayData(process,'GO',version)
component_goids, component_names = extractPathwayData(component,'GO',version)
function_goids, function_names = extractPathwayData(function,'GO',version)
goids = [process_goids,component_goids,function_goids]
go_names = [process_names,component_names,function_names]
else: goids=[]; go_names=[]
if extract_pathway_names == 'yes': null, pathways = extractPathwayData(pathway_data,'pathway',version)
else: pathways = []
ai = AffymetrixInformation(probeset, symbol, ensembl_list, entrez_list, unigene_list, uniprot_list, description, goids, go_names, pathways)
if len(entrez_list)<5: affy_annotation_db[probeset] = ai
if parse_wikipathways == 'yes':
if (len(entrez_list)<4 and len(entrez_list)>0) and (len(ensembl_list)<4 and len(ensembl_list)>0):
primary_list = entrez_list+ensembl_list
for primary in primary_list:
if len(primary)>0:
for gene in ensembl_list:
if len(gene)>1: meta[primary,gene]=[]
for gene in ref_prot_list:
gene_data = string.split(gene,'.'); gene = gene_data[0]
if len(gene)>1: meta[primary,gene]=[]
for gene in ref_tran_list:
if len(gene)>1: meta[primary,gene]=[]
for gene in unigene_list:
if len(gene)>1: meta[primary,gene]=[]
for gene in mod_list:
if len(gene)>1: meta[primary,'mod:'+gene]=[]
for gene in symbol_list:
if len(gene)>1: meta[primary,gene]=[]
for gene in uniprot_list:
if len(gene)>1: meta[primary,gene]=[]
for gene in entrez_list:
if len(gene)>1: meta[primary,gene]=[]
#symbol_list = string.split(symbol,' /// '); description_list = string.split(description,' /// ')
if len(entrez_list)<2: ###Only store annotations for EntrezGene if there is only one listed ID, since the symbol, description and Entrez Gene are sorted alphabetically, not organized relative to each other (stupid)
iter = 0
for entrez in entrez_list:
#symbol = symbol_list[iter]; description = description_list[iter] ###grab the symbol that matches the EntrezGene entry
z = InferredEntrezInformation(symbol,entrez,description)
try: gene_annotation_db[entrez] = z
except NameError: null=[]
iter += 1
if len(ensembl_list)<2: ###Only store annotations for EntrezGene if there is only one listed ID, since the symbol, description and Entrez Gene are sorted alphabetically, not organized relative to each other (stupid)
for ensembl in ensembl_list:
z = InferredEntrezInformation(symbol,ensembl,description)
try: gene_annotation_db['ENS:'+ensembl] = z
except NameError: null=[]
elif version == 2: ### Applies to Exon, Transcript, whole geneome Gene arrays.
uniprot_list2 = []
for uniprot_id in uniprot_list:
if len(uniprot_id)>0:
try: a = int(uniprot_id[1]); uniprot_list2.append(uniprot_id)
except ValueError: null = []
uniprot_list = uniprot_list2
ensembl_list=[]; descriptions=[]; refseq_list=[]; symbol_list=[]
try: mrna_associations = affy_data[ma]
except IndexError: mrna_associations='';
ensembl_data = string.split(mrna_associations,' /// ')
for entry in ensembl_data:
annotations = string.split(entry,' // ')
#if probeset == '8148358': print annotations
for i in annotations:
if 'gene:ENS' in i:
ensembl_id_data = string.split(i,'gene:ENS')
ensembl_ids = ensembl_id_data[1:]; description = ensembl_id_data[0] ###There can be multiple IDs
descriptions.append((len(description),description))
for ensembl_id in ensembl_ids:
ensembl_id = string.split(ensembl_id,' ')
ensembl_id = 'ENS'+ensembl_id[0]; ensembl_list.append(ensembl_id)
if 'NM_' in i:
refseq_id = string.replace(i,' ','')
refseq_list.append(refseq_id)
#if probeset == '8148358': print ensembl_list; kill
try: gene_assocs = affy_data[ga]; entrez_list=[]
except IndexError: gene_assocs=''; entrez_list=[]
entrez_data = string.split(gene_assocs,' /// ')
for entry in entrez_data:
try:
if len(entry)>0:
annotations = string.split(entry,' // ')
entrez_gene = int(annotations[-1]); entrez_list.append(str(entrez_gene))
symbol = annotations[1]; description = annotations[2]; descriptions.append((len(description),description))
symbol_list.append(symbol)
#print entrez_gene,symbol, descriptions;kill
z = InferredEntrezInformation(symbol,entrez_gene,description)
try: gene_annotation_db[str(entrez_gene)] = z ###create an inferred Entrez gene database
except NameError: null = []
except ValueError: null = []
if len(symbol_list) == 1 and len(ensembl_list)>0:
symbol = symbol_list[0]
for ensembl in ensembl_list:
z = InferredEntrezInformation(symbol,ensembl,description)
try: gene_annotation_db['ENS:'+ensembl] = z ###create an inferred Entrez gene database
except NameError: null = []
gene_assocs = string.replace(gene_assocs,'---','')
unigene_data = string.split(unigene,' /// '); unigene_list = []
for entry in unigene_data:
if len(entry)>0:
annotations = string.split(entry,' // ')
try: null = int(annotations[-2][3:]); unigene_list.append(annotations[-2])
except Exception: null = []
###Only applies to optional GOID inclusion
if parse_wikipathways == 'yes':
if (len(entrez_list)<4 and len(entrez_list)>0) and (len(ensembl_list)<4 and len(ensembl_list)>0):
primary_list = entrez_list+ensembl_list
for primary in primary_list:
if len(primary)>0:
for gene in ensembl_list:
if len(gene)>1: meta[primary,gene]=[]
for gene in refseq_list:
gene_data = string.split(gene,'.'); gene = gene_data[0]
if len(gene)>1: meta[primary,gene]=[]
for gene in unigene_list:
if len(gene)>1: meta[primary,gene]=[]
for gene in symbol_list:
if len(gene)>1: meta[primary,gene]=[]
for gene in uniprot_list:
if len(gene)>1: meta[primary,gene]=[]
for gene in entrez_list:
if len(gene)>1: meta[primary,gene]=[]
if process_go_var == 'yes':
try: process = affy_data[bp]; component = affy_data[cc]; function = affy_data[mf]
except IndexError: process = ''; component=''; function=''### This occurs due to a random python error, typically once twice in the file
process_goids, process_names = extractPathwayData(process,'GO',version)
component_goids, component_names = extractPathwayData(component,'GO',version)
function_goids, function_names = extractPathwayData(function,'GO',version)
goids = [process_goids,component_goids,function_goids]
go_names = [process_names,component_names,function_names]
else: goids=[]; go_names=[]
if extract_pathway_names == 'yes': null, pathways = extractPathwayData(pathway_data,[],version)
else: pathways = []
entrez_list=unique.unique(entrez_list); unigene_list=unique.unique(unigene_list); uniprot_list=unique.unique(uniprot_list); ensembl_list=unique.unique(ensembl_list)
descriptions2=[]
for i in descriptions:
if 'cdna:known' not in i: descriptions2.append(i)
descriptions = descriptions2
if len(descriptions)>0:
descriptions.sort(); description = descriptions[-1][1]
if description[0] == ' ': description = description[1:] ### some entries begin with a blank
ai = AffymetrixInformation(probeset,symbol,ensembl_list,entrez_list,unigene_list,uniprot_list,description,goids,go_names,pathways)
if len(entrez_list)<5 and len(ensembl_list)<5: affy_annotation_db[probeset] = ai
elif version == 3:
description = affy_data[st]; symbol = affy_data[ti]
ai = AffymetrixInformation(probeset, symbol, [], [], [], [], description, [], [], [])
ai.setSequence(affy_data[sq])
ai.setSpecies(affy_data[ss])
ai.setCoordinates(affy_data[al])
affy_annotation_db[probeset] = ai
return version
def getArrayAnnotationsFromGOElite(conventional_array_db,species_code,vendor,use_go):
import gene_associations; import time
start_time = time.time()
### Get Gene Ontology gene associations
try: gene_to_mapp_ens = gene_associations.importGeneMAPPData(species_code,'Ensembl-MAPP.txt') ### was just 'Ensembl'
except Exception: gene_to_mapp_ens = {}
try: gene_to_mapp_eg = gene_associations.importGeneMAPPData(species_code,'EntrezGene-MAPP.txt')
except Exception: gene_to_mapp_eg = {}
if vendor == 'Affymetrix': ### Remove exon associations which decrease run efficency and are superfulous
try: ens_to_array = gene_associations.getGeneToUidNoExon(species_code,'Ensembl-'+vendor); print 'Ensembl-'+vendor,'relationships imported'
except Exception: ens_to_array={}
try: eg_to_array = gene_associations.getGeneToUidNoExon(species_code,'EntrezGene-'+vendor); print 'EntrezGene-'+vendor,'relationships imported'
except Exception: eg_to_array={}
print '*',
else:
try: ens_to_array = gene_associations.getGeneToUid(species_code,'Ensembl-'+vendor)
except Exception: ens_to_array = {}
try: eg_to_array = gene_associations.getGeneToUid(species_code,'EntrezGene-'+vendor)
except Exception: eg_to_array = {}
print '*',
try: ens_annotations = gene_associations.importGeneData(species_code,'Ensembl')
except Exception: ens_annotations = {}
try: eg_annotations = gene_associations.importGeneData(species_code,'EntrezGene')
except Exception: eg_annotations = {}
if use_go == 'yes':
import OBO_import
go_annotations = OBO_import.importPreviousOntologyAnnotations('GeneOntology')
try: gene_to_go_ens = gene_associations.importGeneToOntologyData(species_code,'Ensembl','null','GeneOntology')
except Exception: gene_to_go_ens = {}
print '*',
try: gene_to_go_eg = gene_associations.importGeneToOntologyData(species_code,'EntrezGene','null','GeneOntology')
except Exception: gene_to_go_eg = {}
print '*',
component_db,process_db,function_db,selected_array_ens = annotateGOElitePathways('GO',go_annotations,gene_to_go_ens,ens_to_array)
print '*',
component_eg_db,process_eg_db,function_eg_db,selected_array_eg = annotateGOElitePathways('GO',go_annotations,gene_to_go_eg,eg_to_array)
print '*',
component_db = combineDBs(component_eg_db,component_db)
print '*',
process_db = combineDBs(process_eg_db,process_db)
print '*',
function_db = combineDBs(function_eg_db,function_db)
else:
selected_array_ens={}
selected_array_eg ={}
print '* * * * * *',
unique_arrayids={} ### Get all unique probesets
for gene in ens_to_array:
for uid in ens_to_array[gene]: unique_arrayids[uid]=[]
for gene in eg_to_array:
for uid in eg_to_array[gene]: unique_arrayids[uid]=[]
array_ens_mapp_db = annotateGOElitePathways('MAPP','',gene_to_mapp_ens,ens_to_array)
array_eg_mapp_db = annotateGOElitePathways('MAPP','',gene_to_mapp_eg,eg_to_array)
array_mapp_db = combineDBs(array_ens_mapp_db,array_eg_mapp_db)
print '*',
array_to_ens = swapKeyValues(ens_to_array)
array_to_eg = swapKeyValues(eg_to_array)
for uid in selected_array_ens:
gene = selected_array_ens[uid] ### Best candidate gene of several
array_to_ens[uid].remove(gene) ### Delete the first instance of this Ensembl
array_to_ens[uid].append(gene); array_to_ens[uid].reverse() ### Make the first ID
for uid in selected_array_eg:
gene = selected_array_eg[uid]
array_to_eg[uid].remove(gene) ### Delete the first instance of this Ensembl
array_to_eg[uid].append(gene); array_to_eg[uid].reverse() ### Make the first ID
global array_symbols; global array_descriptions; array_symbols={}; array_descriptions={}
getArrayIDAnnotations(array_to_ens,ens_annotations,'Ensembl')
getArrayIDAnnotations(array_to_eg,eg_annotations,'Entrez')
print '*',
for arrayid in unique_arrayids:
try: component_names = component_db[arrayid]
except Exception: component_names=[]
try: process_names = process_db[arrayid]
except Exception: process_names=[]
try: function_names = function_db[arrayid]
except Exception: function_names=[]
try: wp_names = array_mapp_db[arrayid]
except Exception: wp_names=[]
try: ensembls = array_to_ens[arrayid]
except Exception: ensembls=[]
try: entrezs = array_to_eg[arrayid]
except Exception: entrezs=[]
try: symbol = array_symbols[arrayid]
except Exception: symbol=''
try: description = array_descriptions[arrayid]
except Exception: description=''
#if len(wp_names)>0:
#print arrayid, component_names, process_names, function_names, wp_names, ensembls, entrezs, symbol, description;kill
try:
ca = conventional_array_db[arrayid]
definition = ca.Description()
symbol = ca.Symbol()
ens = ca.Ensembl()
entrez = ca.Entrez()
pathways = ca.Pathways()
process, component, function = ca.GONameLists()
ensembls+=ens; entrezs+=entrez; wp_names+=pathways
component_names+=component; process_names+=process; function_names+=function
ensembls=unique.unique(ensembls); entrezs=unique.unique(entrezs); wp_names=unique.unique(wp_names)
component_names=unique.unique(component_names); process_names=unique.unique(process_names); function_names=unique.unique(function_names)
except Exception: null=[]
go_names = process_names,component_names,function_names
ai = AffymetrixInformation(arrayid,symbol,ensembls,entrezs,[],[],description,[],go_names,wp_names)
conventional_array_db[arrayid] = ai
#print len(conventional_array_db),'ArrayIDs with annotations.'
end_time = time.time(); time_diff = int(end_time-start_time)
print 'ArrayID annotations imported in',time_diff, 'seconds'
return conventional_array_db
class PathwayInformation:
def __init__(self,component_list,function_list,process_list,pathway_list):
self.component_list = component_list; self.function_list = function_list
self.process_list = process_list; self.pathway_list = pathway_list
def Component(self): return self.Format(self.component_list)
def Process(self): return self.Format(self.process_list)
def Function(self): return self.Format(self.function_list)
def Pathway(self): return self.Format(self.pathway_list)
def Combined(self): return self.Format(self.pathway_list+self.process_list+self.function_list+self.component_list)
def Format(self,terms):
return string.join(terms,' // ')
def getHousekeepingGenes(species_code):
vendor = 'Affymetrix'
exclude = ['ENSG00000256901'] ### Incorrect homology with housekeeping
import gene_associations
try: ens_to_array = gene_associations.getGeneToUidNoExon(species_code,'Ensembl-'+vendor); print 'Ensembl-'+vendor,'relationships imported'
except Exception: ens_to_array={}
housekeeping_genes={}
for gene in ens_to_array:
for uid in ens_to_array[gene]:
if 'AFFX' in uid:
if gene not in exclude: housekeeping_genes[gene]=[]
return housekeeping_genes
def getEnsemblAnnotationsFromGOElite(species_code):
import gene_associations; import time
start_time = time.time()
### Get Gene Ontology gene associations
try: gene_to_mapp_ens = gene_associations.importGeneMAPPData(species_code,'Ensembl-MAPP.txt')
except Exception: gene_to_mapp_ens = {}
import OBO_import
go_annotations = OBO_import.importPreviousOntologyAnnotations('GeneOntology')
try: gene_to_go_ens = gene_associations.importGeneToOntologyData(species_code,'Ensembl','null','GeneOntology')
except Exception: gene_to_go_ens = {}
component_db={}; process_db={}; function_db={}; all_genes={}
for gene in gene_to_go_ens:
all_genes[gene]=[]
for goid in gene_to_go_ens[gene]:
if goid in go_annotations:
s = go_annotations[goid]
go_name = string.replace(s.OntologyTerm(),'\\','')
gotype = s.OntologyType()
if gotype[0] == 'C' or gotype[0] == 'c':
try: component_db[gene].append(go_name)
except KeyError: component_db[gene] = [go_name]
elif gotype[0] == 'P' or gotype[0] == 'p' or gotype[0] == 'b':
try: process_db[gene].append(go_name)
except KeyError: process_db[gene] = [go_name]
elif gotype[0] == 'F' or gotype[0] == 'f' or gotype[0] == 'm':
try: function_db[gene].append(go_name)
except KeyError: function_db[gene] = [go_name]
for gene in gene_to_mapp_ens: all_genes[gene]=[]
for gene in all_genes:
component_go=[]; process_go=[]; function_go=[]; pathways=[]
if gene in component_db: component_go = component_db[gene]
if gene in function_db: function_go = function_db[gene]
if gene in process_db: process_go = process_db[gene]
if gene in gene_to_mapp_ens: pathways = gene_to_mapp_ens[gene]
pi=PathwayInformation(component_go,function_go,process_go,pathways)
all_genes[gene]=pi
end_time = time.time(); time_diff = int(end_time-start_time)
print len(all_genes),'Ensembl GO/pathway annotations imported in',time_diff, 'seconds'
return all_genes
def getArrayIDAnnotations(uid_to_gene,gene_annotations,gene_type):
for uid in uid_to_gene:
gene = uid_to_gene[uid][0]
if gene in gene_annotations:
s = gene_annotations[gene]
if len(s.Symbol()) > 0:
array_symbols[uid] = s.Symbol()
array_descriptions[uid] = s.Description()
def combineDBs(db1,db2):
for i in db1:
try: db1[i]+=db2[i]
except Exception: null=[]
for i in db2:
try: db2[i]+=db1[i]
except Exception: db1[i]=db2[i]
db1 = eliminate_redundant_dict_values(db1)
return db1
def annotateGOElitePathways(pathway_type,go_annotations,gene_to_pathway,gene_to_uid):
array_pathway_db={}; determine_best_geneID={}
for gene in gene_to_uid:
#if gene == 'ENSG00000233911': print gene_to_uid[gene],len(gene_to_pathway[gene]),'b'
try: pathways = gene_to_pathway[gene]
except Exception: pathways=[]
for arrayid in gene_to_uid[gene]:
#if arrayid == '208286_x_at': print 'a',[gene]
for pathway in pathways:
try:
if pathway_type == 'GO':
s = go_annotations[pathway]
go_name = string.replace(s.OntologyTerm(),'\\','')
try: array_pathway_db[arrayid,s.OntologyType()].append(go_name)
except Exception: array_pathway_db[arrayid,s.OntologyType()] = [go_name]
else:
try: array_pathway_db[arrayid].append(pathway + '(WikiPathways)')
except Exception: array_pathway_db[arrayid] = [pathway + '(WikiPathways)']
except Exception: null=[] ### if GOID not found in annotation database
if pathway_type == 'GO':
try: determine_best_geneID[arrayid].append([len(pathways),gene])
except Exception: determine_best_geneID[arrayid]=[[len(pathways),gene]]
array_pathway_db = eliminate_redundant_dict_values(array_pathway_db)
if pathway_type == 'GO':
### First, see which gene has the best GO annotations for an arrayID
selected_array_gene={}
for arrayid in determine_best_geneID:
if len(determine_best_geneID[arrayid])>1:
determine_best_geneID[arrayid].sort()
count,gene = determine_best_geneID[arrayid][-1] ### gene with the most GO annotations associated
### The below is code that appears to be necessary when non-chromosomal Ensembl genes with same name and annotation
### are present. When this happens, the lowest sorted Ensembl tends to be the real chromosomal instance
determine_best_geneID[arrayid].reverse()
#if arrayid == '208286_x_at': print determine_best_geneID[arrayid]
for (count2,gene2) in determine_best_geneID[arrayid]:
#if arrayid == '208286_x_at': print count2,gene2
if count == count2: gene = gene2
else: break
selected_array_gene[arrayid] = gene
component_db={}; process_db={}; function_db={}; determine_best_geneID=[]
for (arrayid,gotype) in array_pathway_db:
if string.lower(gotype[0]) == 'c':
component_db[arrayid] = array_pathway_db[(arrayid,gotype)]
elif string.lower(gotype[0]) == 'b' or string.lower(gotype[0]) == 'p':
process_db[arrayid] = array_pathway_db[(arrayid,gotype)]
if string.lower(gotype[0]) == 'm' or string.lower(gotype[0]) == 'f':
function_db[arrayid] = array_pathway_db[(arrayid,gotype)]
return component_db,process_db,function_db,selected_array_gene
else: return array_pathway_db
def extractPathwayData(terms,type,version):
goids = []; go_names = []
buffer = ' /// '; small_buffer = ' // '
go_entries = string.split(terms,buffer)
for go_entry in go_entries:
go_entry_info = string.split(go_entry,small_buffer)
try:
if len(go_entry_info)>1:
if version == 1:
if type == 'GO': ### 6310 // DNA recombination // inferred from electronic annotation ///
goid, go_name, source = go_entry_info
while len(goid)< 7: goid = '0'+goid
goid = 'GO:'+goid
else: ### Calcium signaling pathway // KEGG ///
go_name, source = go_entry_info; goid = ''
if len(go_name)>1: go_name = source+'-'+go_name
else: go_name = ''
if version == 2:
if type == 'GO': ### NM_153254 // GO:0006464 // protein modification process // inferred from electronic annotation ///
try: accession, goid, go_name, source = go_entry_info
except ValueError: accession = go_entry_info[0]; goid = go_entry_info[1]; go_name = ''; source = ''
else: ### AF057061 // GenMAPP // Matrix_Metalloproteinases
accession, go_name, source = go_entry_info; goid = ''
if len(go_name)>1: go_name = source+'-'+go_name
else: go_name = ''
goids.append(goid); go_names.append(go_name)
except IndexError: goids = goids
if extract_go_names != 'yes': go_names = [] ### Then don't store (save memory)
goids = unique.unique(goids); go_names = unique.unique(go_names)
return goids, go_names
def exportResultsSummary(dir_list,species,type):
program_type,database_dir = unique.whatProgramIsThis()
if program_type == 'AltAnalyze': parent_dir = 'AltDatabase/goelite'
else: parent_dir = 'Databases'
if overwrite_previous == 'over-write previous':
if program_type != 'AltAnalyze': import OBO_import; OBO_import.exportVersionData(0,'0/0/0','/'+species+'/nested/') ### Erase the existing file so that the database is re-remade
else: parent_dir = 'NewDatabases'
new_file = parent_dir+'/'+species+'/'+type+'_files_summarized.txt'
today = str(datetime.date.today()); today = string.split(today,'-'); today = today[1]+'/'+today[2]+'/'+today[0]
fn=filepath(new_file); data = open(fn,'w')
for filename in dir_list: data.write(filename+'\t'+today+'\n')
try:
if parse_wikipathways == 'yes': data.write(wikipathways_file+'\t'+today+'\n')
except Exception: null=[]
data.close()
def exportMetaGeneData(species):
program_type,database_dir = unique.whatProgramIsThis()
if program_type == 'AltAnalyze': parent_dir = 'AltDatabase/goelite'
else: parent_dir = 'Databases'
if overwrite_previous == 'over-write previous':
if program_type != 'AltAnalyze':
null = None
#import OBO_import; OBO_import.exportVersionData(0,'0/0/0','/'+species+'/nested/') ### Erase the existing file so that the database is re-remade
else: parent_dir = 'NewDatabases'
new_file = parent_dir+'/'+species+'/uid-gene/Ensembl_EntrezGene-meta.txt'
data = export.ExportFile(new_file)
for (primary,gene) in meta: data.write(primary+'\t'+gene+'\n')
data.close()
def importMetaGeneData(species):
program_type,database_dir = unique.whatProgramIsThis()
if program_type == 'AltAnalyze': parent_dir = 'AltDatabase/goelite'
else: parent_dir = 'Databases'
filename = parent_dir+'/'+species+'/uid-gene/Ensembl_EntrezGene-meta.txt'
fn=filepath(filename)
for line in open(fn,'rU').readlines():
data = cleanUpLine(line)
primary,gene = string.split(data,'\t')
meta[primary,gene]=[]
def exportRelationshipDBs(species):
program_type,database_dir = unique.whatProgramIsThis()
if program_type == 'AltAnalyze': parent_dir = 'AltDatabase/goelite'
else: parent_dir = 'Databases'
if overwrite_previous == 'over-write previous':
if program_type != 'AltAnalyze': import OBO_import; OBO_import.exportVersionData(0,'0/0/0','/'+species+'/nested/') ### Erase the existing file so that the database is re-remade
else: parent_dir = 'NewDatabases'
x1=0; x2=0; x3=0; x4=0; x5=0; x6=0
today = str(datetime.date.today()); today = string.split(today,'-'); today = today[1]+'/'+today[2]+'/'+today[0]
import UI; header = 'GeneID'+'\t'+'GOID'+'\n'
ens_annotations_found = verifyFile('Databases/'+species+'/gene/Ensembl.txt')
if process_go == 'yes': ens_process_go = 'yes'; eg_process_go = 'yes'
else:
ens_process_go = 'no'; eg_process_go = 'no'
eg_go_found = verifyFile('Databases/'+species+'/gene-go/EntrezGene-GeneOntology.txt')
ens_go_found = verifyFile('Databases/'+species+'/gene-go/Ensembl-GeneOntology.txt')
if eg_go_found == 'no': eg_process_go = 'yes'
if ens_go_found == 'no': ens_process_go = 'yes'
for probeset in affy_annotation_db:
ai = affy_annotation_db[probeset]
ensembls = unique.unique(ai.Ensembl()); entrezs = unique.unique(ai.Entrez())
for ensembl in ensembls:
if len(ensembl)>0:
if x1 == 0: ### prevents the file from being written if no data present
new_file1 = parent_dir+'/'+species+'/uid-gene/Ensembl-Affymetrix.txt'
data1 = export.ExportFile(new_file1); x1=1
data1.write(ensembl+'\t'+probeset+'\n')
if ens_process_go == 'yes':
goids = unique.unique(ai.GOIDs())
for goid_ls in goids:
for goid in goid_ls:
if len(goid)>0:
if x4==0:
new_file4 = parent_dir+'/'+species+'/gene-go/Ensembl-GeneOntology.txt'
data4 = export.ExportFile(new_file4); data4.write(header); x4=1
data4.write(ensembl+'\t'+goid+'\n')
for entrez in entrezs:
if len(entrez)>0:
if x2 == 0:
new_file2 = parent_dir+'/'+species+'/uid-gene/EntrezGene-Affymetrix.txt'
data2 = export.ExportFile(new_file2); x2=1
data2.write(entrez+'\t'+probeset+'\n')
if eg_process_go == 'yes':
goids = unique.unique(ai.GOIDs())
for goid_ls in goids:
for goid in goid_ls:
if len(goid)>0:
if x5==0:
new_file5 = parent_dir+'/'+species+'/gene-go/EntrezGene-GeneOntology.txt'
data5 = export.ExportFile(new_file5); data5.write(header); x5=1
data5.write(entrez+'\t'+goid+'\n')
for geneid in gene_annotation_db:
ea = gene_annotation_db[geneid]
if len(geneid)>0 and 'ENS:' not in geneid:
if x3 == 0:
new_file3 = parent_dir+'/'+species+'/gene/EntrezGene.txt'
data3 = export.ExportFile(new_file3); x3=1
data3.write('ID'+'\t'+'Symbol'+'\t'+'Name'+'\t'+'Species'+'\t'+'Date'+'\t'+'Remarks'+'\n')
data3.write(geneid+'\t'+ea.Symbol()+'\t'+ea.Description()+'\t'+species+'\t'+today+'\t'+''+'\n')
elif ens_annotations_found == 'no' and 'ENS:' in geneid:
geneid = string.replace(geneid,'ENS:','')
if x6 == 0:
new_file6 = parent_dir+'/'+species+'/gene/EntrezGene.txt'
data6 = export.ExportFile(new_file6); x6=1
data6.write('ID'+'\t'+'Symbol'+'\t'+'Name'+'\n')
data6.write(geneid+'\t'+ea.Symbol()+'\t'+ea.Description()+'\n')
if x1==1: data1.close()
if x2==1: data2.close()
if x3==1: data3.close()
if x4==1: data4.close()
if x5==1: data5.close()
if x6==1: data6.close()
def swapKeyValues(db):
swapped={}
for key in db:
values = list(db[key]) ###If the value is not a list, make a list
for value in values:
try: swapped[value].append(key)
except KeyError: swapped[value] = [key]
swapped = eliminate_redundant_dict_values(swapped)
return swapped
def integratePreviousAssociations():
print 'Integrating associations from previous databases...'
#print len(entrez_annotations),len(ens_to_uid), len(entrez_to_uid)
for gene in entrez_annotations:
if gene not in gene_annotation_db:
### Add previous gene information to the new database
y = entrez_annotations[gene]
z = InferredEntrezInformation(y.Symbol(),gene,y.Description())
gene_annotation_db[gene] = z
uid_to_ens = swapKeyValues(ens_to_uid); uid_to_entrez = swapKeyValues(entrez_to_uid)
###Add prior missing gene relationships for all probesets in the new database and that are missing
for uid in uid_to_ens:
if uid in affy_annotation_db:
y = affy_annotation_db[uid]
ensembl_ids = uid_to_ens[uid]
if y.Ensembl() == ['']: y.resetEnsembl(ensembl_ids)
else:
ensembl_ids = unique.unique(y.Ensembl()+ensembl_ids)
y.resetEnsembl(ensembl_ids)
else:
ensembl_ids = uid_to_ens[uid]; entrez_ids = []
if uid in uid_to_entrez: entrez_ids = uid_to_entrez[uid]
ai = AffymetrixInformation(uid, '', ensembl_ids, entrez_ids, [], [], '',[],[],[])
affy_annotation_db[uid] = ai
for uid in uid_to_entrez:
if uid in affy_annotation_db:
y = affy_annotation_db[uid]
entrez_ids = uid_to_entrez[uid]
if y.Entrez() == ['']: y.resetEntrez(entrez_ids)
else:
entrez_ids = uid_to_entrez[uid]; ensembl_ids = []
if uid in uid_to_ens: ensembl_ids = uid_to_ens[uid]
ai = AffymetrixInformation(uid, '', ensembl_ids, entrez_ids, [], [], '',[],[],[])
affy_annotation_db[uid] = ai
def parseGene2GO(tax_id,species,overwrite_prev,rewrite_existing):
global overwrite_previous; overwrite_previous = overwrite_prev; status = 'run'
program_type,database_dir = unique.whatProgramIsThis()
if program_type == 'AltAnalyze': database_dir = '/AltDatabase'
else: database_dir = '/BuildDBs'
import_dir = database_dir+'/Entrez/Gene2GO'
g = GrabFiles(); g.setdirectory(import_dir)
filename = g.searchdirectory('gene2go') ###Identify gene files corresponding to a particular MOD
if len(filename)>1:
fn=filepath(filename); gene_go=[]; x = 0
for line in open(fn,'rU').readlines():
data = cleanUpLine(line)
t = string.split(data,'\t')
if x == 0: x = 1 ###skip the first line
else:
taxid=t[0];entrez=t[1];goid=t[2]
if taxid == tax_id: gene_go.append([entrez,goid])
else: status = 'not run'
if len(gene_go)>0:
program_type,database_dir = unique.whatProgramIsThis()
if program_type == 'AltAnalyze': parent_dir = 'AltDatabase/goelite'
else: parent_dir = 'Databases'
if overwrite_previous == 'over-write previous':
if program_type != 'AltAnalyze': import OBO_import; OBO_import.exportVersionData(0,'0/0/0','/'+species+'/nested/') ### Erase the existing file so that the database is re-remade
else: parent_dir = 'NewDatabases'
new_file = parent_dir+'/'+species+'/gene-go/EntrezGene-GeneOntology.txt'
today = str(datetime.date.today()); today = string.split(today,'-'); today = today[1]+'/'+today[2]+'/'+today[0]
import EnsemblSQL
headers = ['EntrezGene ID','GO ID']
EnsemblSQL.exportListstoFiles(gene_go,headers,new_file,rewrite_existing)
print 'Exported',len(gene_go),'gene-GO relationships for species:',species
exportResultsSummary(['Gene2GO.zip'],species,'EntrezGene_GO')
else: print 'No NCBI Gene Ontology support for this species'
return 'run'
def getMetaboliteIDTranslations(species_code):
mod = 'HMDB'; meta_metabolite_db={}
meta_metabolite_db = importMetaboliteIDs(species_code,mod,'CAS',meta_metabolite_db)
meta_metabolite_db = importMetaboliteIDs(species_code,mod,'ChEBI',meta_metabolite_db)
meta_metabolite_db = importMetaboliteIDs(species_code,mod,'PubChem',meta_metabolite_db)
return meta_metabolite_db
def importMetaboliteIDs(species_code,mod,source,meta_metabolite_db):
mod_source = mod+'-'+source
gene_to_source_id = gene_associations.getGeneToUid(species_code,('hide',mod_source))
source_to_gene = OBO_import.swapKeyValues(gene_to_source_id)
#print mod_source, 'relationships imported'
meta_metabolite_db[source] = source_to_gene
return meta_metabolite_db
def importWikipathways(system_codes,incorporate_previous_associations,process_go,species_full,species,integrate_affy_associations,relationship_type,overwrite_affycsv):
global wikipathways_file; global overwrite_previous
overwrite_previous = overwrite_affycsv
database_dir = '/BuildDBs'
import_dir = database_dir+'/wikipathways'
g = GrabFiles(); g.setdirectory(import_dir); wikipathway_gene_db={}; eg_wikipathway_db={}; ens_wikipathway_db={}
search_term = relationship_type+'_data_'+species_full
#search_term = 'wikipathways'
filename = g.searchdirectory(search_term) ###Identify gene files corresponding to a particular MOD
#print "Parsing",filename; wikipathways_file = string.split(filename,'/')[-1]
#print "Extracting data for species:",species_full,species
if len(filename)>1:
fn=filepath(filename); gene_go={}; x = 0
for line in open(fn,'rU').readlines():
data = cleanUpLine(line)
data = string.replace(data,'MGI:','')
t = string.split(data,'\t')
if x == 0:
x = 1; y = 0
while y < len(t):
if 'Ensembl' in t[y]: ens = y
if 'UniGene' in t[y]: ug = y
if 'Entrez' in t[y]: ll = y
if 'SwissProt' in t[y]: sp = y
if 'Uniprot' in t[y]: sp = y
if 'RefSeq' in t[y]: rt = y
if 'MOD' in t[y]: md= y
if 'Pathway Name' in t[y]: pn = y
if 'Organism' in t[y]: og= y
if 'Url to WikiPathways' in t[y]: ur= y
if 'PubChem' in t[y]: pc = y
if 'CAS' in t[y]: cs = y
if 'ChEBI' in t[y]: cb = y
y += 1
else:
try: ensembl = t[ens]; unigene = t[ug]; uniprot = t[sp]; refseq = t[rt]; mod = t[md]; entrez = t[ll]
except Exception: print '\nWARNING...errors were encountered when processing the line',[line]; print 'Errors in the WP file are present!!!!\n'; print [last_line]; sys.exit(); continue
last_line = line
ensembl = splitEntry(ensembl); unigene = splitEntry(unigene); uniprot = splitEntry(uniprot)
pathway_name = t[pn]; organism = t[og]; wikipathways_url = t[ur]; entrez = splitEntry(entrez);
refseq = splitEntry(refseq); mod = splitOthers(mod); mod2 = []
try: pubchem = t[pc]; cas = t[cs]; chemEBI = t[cb]
except Exception:
pubchem=''; cas=''; chemEBI=''
if x==1: print 'WARNING!!! Metabolite Identifiers missing from WikiPathways file.'
x+=1
pubchem = splitEntry(pubchem); cas = splitEntry(cas); chemEBI = splitEntry(chemEBI)
htp,url,wpid = string.split(wikipathways_url,':')
pathway_name = pathway_name +':'+ wpid
for m in mod: mod2.append('mod:'+m); mod = mod2
#relationship_type
gene_ids = mod+ensembl+unigene+uniprot+refseq+entrez
if organism == species_full:
if relationship_type == 'mapped':
for id in pubchem:
try: wikipathway_gene_db[id].append(('PubChem',pathway_name))
except Exception: wikipathway_gene_db[id] = [('PubChem',pathway_name)]
for id in cas:
try: wikipathway_gene_db[id].append(('CAS',pathway_name))
except Exception: wikipathway_gene_db[id] = [('CAS',pathway_name)]
for id in chemEBI:
try: wikipathway_gene_db[id].append(('ChEBI',pathway_name))
except Exception: wikipathway_gene_db[id] = [('ChEBI',pathway_name)]
else:
for gene_id in gene_ids:
if len(gene_id)>1:
try: wikipathway_gene_db[gene_id].append(pathway_name)
except KeyError: wikipathway_gene_db[gene_id] = [pathway_name]
for gene_id in ensembl:
if len(gene_id)>1:
try: ens_wikipathway_db[pathway_name].append(gene_id)
except KeyError: ens_wikipathway_db[pathway_name] = [gene_id]