forked from RVDavuluri/ExTraMapper
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathExTraMapper.py
More file actions
1426 lines (1269 loc) · 59.4 KB
/
Copy pathExTraMapper.py
File metadata and controls
1426 lines (1269 loc) · 59.4 KB
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
#!/usr/bin/env python
## ExtraMapper python 3 and later version
## Original version written by Ferhat Ay
## Converted by Abhijit Chakraborty
import argparse
import sys
import os
import string
import operator
import _pickle as pickle
complement = str.maketrans('atcgn', 'tagcn')
# Reads from exported environment variable
ExTraMapperPath=os.environ['EXTRAMAPPER_DIR']
sys.path.append(ExTraMapperPath+"/scripts")
from ensemblUtils import *
############## Functions ##############
def write_out_bedFiles_for_UCSCbrowser(genePairId,exonClasses1,exonClasses2,oneToOneTrs,trevDic1,trevDic2):
outfilename=outdir+"/org1-ucsc-"+str(MAPPED_EXON_THRES)+".bed"
outfile1=open(outfilename,'w')
gEntry=geneDic1[g1]
outfile1.write("browser position chr%s:%d-%d\n" % (gEntry.basicInfoDic["chromosome"],gEntry.basicInfoDic["start_coord"],gEntry.basicInfoDic["end_coord"]))
outfile1.write("browser hide all\n")
outfile1.write("track name=\"%s\" description=\"%s-%s gene pair\" visibility=2 color=0,128,0 useScore=1\n" % (gEntry.basicInfoDic["gene_name"],g1,g2))
print ("\nWriting UCSC browser bed output for org1 into file:\n %s" % outfilename)
outfilename=outdir+"/org2-ucsc-"+str(MAPPED_EXON_THRES)+".bed"
outfile2=open(outfilename,'w')
gEntry=geneDic2[g2]
outfile2.write("browser position chr%s:%d-%d\n" % (gEntry.basicInfoDic["chromosome"],gEntry.basicInfoDic["start_coord"],gEntry.basicInfoDic["end_coord"]))
outfile2.write("browser hide all\n")
outfile2.write("track name=\"%s\" description=\"%s-%s gene pair\" visibility=2 color=0,128,0 useScore=1\n" % (gEntry.basicInfoDic["gene_name"],g2,g1))
print ("Writing UCSC browser bed output for org2 into file:\n %s" % outfilename)
for l in oneToOneTrs:
ti,tj,condition,codingScore,allScore,codingExonDiff,allExonDiff=l
t1Entry=transcriptDic1[trevDic1[ti]]
t2Entry=transcriptDic2[trevDic2[tj]]
#print ("OneToOneTrMatches:\t%s\t%s\t%d\t%.3f\t%.3f\t%d\t%d\n" % \
# (t1Entry.get_summary_string(),t2Entry.get_summary_string(),condition,codingScore,allScore,codingExonDiff,allExonDiff)),
############ do this for t1Entry ########################
ch,st,en="chr"+t1Entry.basicInfoDic["chromosome"],t1Entry.basicInfoDic["start_coord"],t1Entry.basicInfoDic["end_coord"]
name=t1Entry.basicInfoDic["transcript_name"]
color=900
strand=t1Entry.basicInfoDic["strand"]
thickSt,thickEn=ch,st # for now just make everything coding
rgbset=0 # (r,g,b) triplet if wanted to use
noOfExons=len(t1Entry.exons)
blockSizes=""
blockStarts=""
if strand=="+":
for exEntry in t1Entry.exons:
eSt,eEn=exEntry[0],exEntry[1]
blockSizes=blockSizes+","+str(abs(eEn-eSt))
blockStarts=blockStarts+","+str(eSt-st) # exon offsets
#
blockSizes="0"+blockSizes+",1"
blockStarts="0"+blockStarts+","+str(abs(en-st)-1)
else:
for exEntry in t1Entry.exons:
eSt,eEn=exEntry[0],exEntry[1]
blockSizes=str(abs(eEn-eSt))+","+blockSizes
blockStarts=str(eSt-st)+","+blockStarts # exon offsets
#
blockSizes="0,"+blockSizes+"1"
blockStarts="0,"+blockStarts+str(abs(en-st)-1)
#
minSt,maxEn=en,st # initialize so that min, max works fine
for exEntry in t1Entry.codingExons:
eSt,eEn=exEntry[0],exEntry[1]
if eSt<minSt and eSt>-1:
minSt=eSt
if eEn>maxEn and eEn>-1:
maxEn=eEn
#
thickSt,thickEn=minSt,maxEn
# write the original transcript for org1
outfile1.write("%s\t%d\t%d\t%s\t%d\t%s\t%d\t%d\t%d\t%d\t%s\t%s\n" % \
(ch,st,en,name,color,strand,thickSt,thickEn,rgbset,noOfExons+2,blockSizes,blockStarts))
############ do this for t1Entry - DONE ########################
########### now find the liftover partners of each exon to print into outfile1 #########################
liftedOverExons={}
for ex1Entry in t1Entry.exons:
exId1=ex1Entry[2]
if exId1 in exonClasses1 and exonClasses1[exId1][0]=="Mapped":
liftedOverExons[exId1]=1 # has a liftedover version - conserved
#
#
name=t2Entry.basicInfoDic["transcript_name"] # get the name from the other org
color=300
noOfExons=0
blockSizes=""
blockStarts=""
if strand=="+":
for exEntry in t1Entry.exons:
eSt,eEn,eId=exEntry
if eId in liftedOverExons:
blockSizes=blockSizes+","+str(abs(eEn-eSt))
blockStarts=blockStarts+","+str(eSt-st) # exon offsets
noOfExons+=1
#
blockSizes="0"+blockSizes+",1"
blockStarts="0"+blockStarts+","+str(abs(en-st)-1)
else:
for exEntry in t1Entry.exons:
eSt,eEn,eId=exEntry
if eId in liftedOverExons:
blockSizes=str(abs(eEn-eSt))+","+blockSizes
blockStarts=str(eSt-st)+","+blockStarts # exon offsets
noOfExons+=1
#
blockSizes="0,"+blockSizes+"1"
blockStarts="0,"+blockStarts+str(abs(en-st)-1)
#
# write the original transcript for org1's correspondence in org2
outfile1.write("%s\t%d\t%d\t%s\t%d\t%s\t%d\t%d\t%d\t%d\t%s\t%s\n" % \
(ch,st,en,name,color,strand,thickSt,thickEn,rgbset,noOfExons+2,blockSizes,blockStarts))
######################################################################################################
############ do this for t2Entry ########################
ch,st,en="chr"+t2Entry.basicInfoDic["chromosome"],t2Entry.basicInfoDic["start_coord"],t2Entry.basicInfoDic["end_coord"]
name=t2Entry.basicInfoDic["transcript_name"]
color=900
strand=t2Entry.basicInfoDic["strand"]
thickSt,thickEn=ch,st # for now just make everything coding
rgbset=0 # (r,g,b) triplet if wanted to use
noOfExons=len(t2Entry.exons)
blockSizes=""
blockStarts=""
if strand=="+":
for exEntry in t2Entry.exons:
eSt,eEn=exEntry[0],exEntry[1]
blockSizes=blockSizes+","+str(abs(eEn-eSt))
blockStarts=blockStarts+","+str(eSt-st) # exon offsets
#
blockSizes="0"+blockSizes+",1"
blockStarts="0"+blockStarts+","+str(abs(en-st)-1)
else:
for exEntry in t2Entry.exons:
eSt,eEn=exEntry[0],exEntry[1]
blockSizes=str(abs(eEn-eSt))+","+blockSizes
blockStarts=str(eSt-st)+","+blockStarts # exon offsets
#
blockSizes="0,"+blockSizes+"1"
blockStarts="0,"+blockStarts+str(abs(en-st)-1)
#
minSt,maxEn=en,st # initialize so that min, max works fine
for exEntry in t2Entry.codingExons:
eSt,eEn=exEntry[0],exEntry[1]
if eSt<minSt and eSt>-1:
minSt=eSt
if eEn>maxEn and eEn>-1:
maxEn=eEn
#
thickSt,thickEn=minSt,maxEn
# write the original transcript for org2
outfile2.write("%s\t%d\t%d\t%s\t%d\t%s\t%d\t%d\t%d\t%d\t%s\t%s\n" % \
(ch,st,en,name,color,strand,thickSt,thickEn,rgbset,noOfExons+2,blockSizes,blockStarts))
############ do this for t2Entry - DONE ########################
########### now find the liftover partners of each exon to print into outfile2 #########################
liftedOverExons={}
for ex2Entry in t2Entry.exons:
exId2=ex2Entry[2]
if exId2 in exonClasses2 and exonClasses2[exId2][0]=="Mapped":
liftedOverExons[exId2]=1 # has a liftedover version - conserved
#
#
name=t1Entry.basicInfoDic["transcript_name"] # get the name from the other org
color=300
noOfExons=0
blockSizes=""
blockStarts=""
if strand=="+":
for exEntry in t2Entry.exons:
eSt,eEn,eId=exEntry
if eId in liftedOverExons:
blockSizes=blockSizes+","+str(abs(eEn-eSt))
blockStarts=blockStarts+","+str(eSt-st) # exon offsets
noOfExons+=1
#
blockSizes="0"+blockSizes+",1"
blockStarts="0"+blockStarts+","+str(abs(en-st)-1)
else:
for exEntry in t2Entry.exons:
eSt,eEn,eId=exEntry
if eId in liftedOverExons:
blockSizes=str(abs(eEn-eSt))+","+blockSizes
blockStarts=str(eSt-st)+","+blockStarts # exon offsets
noOfExons+=1
#
blockSizes="0,"+blockSizes+"1"
blockStarts="0,"+blockStarts+str(abs(en-st)-1)
#
# write the original transcript for org2's correspondence in org1
outfile2.write("%s\t%d\t%d\t%s\t%d\t%s\t%d\t%d\t%d\t%d\t%s\t%s\n" % \
(ch,st,en,name,color,strand,thickSt,thickEn,rgbset,noOfExons+2,blockSizes,blockStarts))
######################################################################################################
#chr22 2000 7000 itemB 200 - 2200 6950 0 4 433,100,550,1500 0,500,2000,3500
####
outfile1.close()
outfile2.close()
return
def greedily_map_transcripts_with_tie_breaks(tdic1,tdic2,tsimMatrixAll,tsimMatrixCoding,trevDic1,trevDic2):
"""
At each step/condition add the mapping to the overall list and set the corresponding column and row to zeros
1. Pick the highest scoring match in the coding matrix
2. If there is a tie then look at the all matrix
3. If there is a tie then look at the difference between the number of coding exons
4. If there is a tie then look at the difference between the number of exons
5. If there is a tie then look at the difference between the total coding length
6. If still tied then pick all of them and report the situation
"""
oneToOneTrs=[]
newTsimMatrixAll=tsimMatrixAll.copy()
newTsimMatrixCoding=tsimMatrixCoding.copy()
noTr1s=len(tdic1)
noTr2s=len(tdic2)
newMax=0.001
conditionCounter=[0,0,0,0,0,0,0] #1=Unique winner, 2=tie in one score, not in the other,
#3= tie in both scores but coding exon length diff breaks the tie,
#4= tie in both scores and coding exon length diff but overall exon length breaks the tie
#5= tie in all the above but coding length (bp) diff breaks the tie
#6= tie in all the above, just give up and report all
## I dropped the extra condition that ensured not too many mappings so that now ties are allowed to be reported
#while sum(sum(newTsimMatrixCoding))>0 and newMax>0 and len(oneToOneTrs)<min(noTr1s,noTr2s):
while sum(sum(newTsimMatrixAll))+sum(sum(newTsimMatrixCoding))>0 and newMax>0:
# select the max among the two score matrices
newMaxAll=newTsimMatrixAll.max()
newMaxCoding=newTsimMatrixCoding.max()
newMax=max(newMaxCoding,newMaxAll)
# This is a threshold choice but it makes sense to break when transcript similarity scores are too low
if newMaxAll<0.2:
break
codingIsMax=True
# choose where the max of the two came from. For precision purposes use a small difference instead of equality check.
if newMaxAll>newMaxCoding:
xs,ys=np.where(abs(newTsimMatrixAll-newMax)<=0.00000000001)
codingIsMax=False
else:
xs,ys=np.where(abs(newTsimMatrixCoding-newMax)<=0.00000000001)
codingIsMax=True
#
# Condition 0: something wrong, shouldn't have entered the while loop
if len(xs)==0 or len(ys)==0:
conditionCounter[0]+=1
# Condition 1: one unique maximum scoring transcript pair
if len(xs)==1:
#print "Condition1"
x=xs[0]; y=ys[0]
oneToOneTrs.append([x,y,1,newTsimMatrixCoding[x,y],newTsimMatrixAll[x,y],-1,-1])
newTsimMatrixCoding[x,:]=0; newTsimMatrixCoding[:,y]=0
newTsimMatrixAll[x,:]=0; newTsimMatrixAll[:,y]=0
conditionCounter[1]+=1
# This automatically makes anything below unreachable and just reports the first out of ties #######################
# elif len(xs)>1:
# x=xs[0]; y=ys[0]
# oneToOneTrs.append([x,y,1,newTsimMatrixCoding[x,y],newTsimMatrixAll[x,y],-1,-1])
# newTsimMatrixCoding[x,y]=0; newTsimMatrixCoding[x,y]=0
# newTsimMatrixAll[x,y]=0; newTsimMatrixAll[x,y]=0
# conditionCounter[1]+=1
####################################################################################################################
# Condition 1 fails -> multiple equal maximum similarity (either coding or all)
else:
#print "Condition1+"
allMax=0
axs,ays=[],[]
# loop and find the max among the xs,ys pairs
for i in range(len(xs)):
x=xs[i]; y=ys[i]
if codingIsMax==True:
if newTsimMatrixAll[x,y]>allMax:
allMax=newTsimMatrixAll[x,y]
else:
if newTsimMatrixCoding[x,y]>allMax:
allMax=newTsimMatrixCoding[x,y]
#
#
# loop once more and find the pairs among xs,ys that still tie
for i in range(len(xs)):
x=xs[i]; y=ys[i]
if codingIsMax==True:
if abs(newTsimMatrixAll[x,y]-allMax)<=0.00000000001:
axs.append(x); ays.append(y)
else:
if abs(newTsimMatrixCoding[x,y]-allMax)<=0.00000000001:
axs.append(x); ays.append(y)
#
# Condition 2: one unique maximum in one matrix after tie in the other
if len(axs)==1:
#print ("Condition2")
x=axs[0]; y=ays[0]
oneToOneTrs.append([x,y,2,newTsimMatrixCoding[x,y],newTsimMatrixAll[x,y],-1,-1])
newTsimMatrixCoding[x,:]=0; newTsimMatrixCoding[:,y]=0
newTsimMatrixAll[x,:]=0; newTsimMatrixAll[:,y]=0
conditionCounter[2]+=1
# Condition 2 fails -> multiple equal coding and overall sim. check the number of coding exons for tie break
else:
#print ("Condition2+")
minCodingExonDiffList=[]
for i in range(len(axs)):
x=axs[i]; y=ays[i]
t1=trevDic1[x]; t2=trevDic2[y];
tempCodingDiff=abs(len(transcriptDic1[t1].codingExons)-len(transcriptDic2[t2].codingExons))
minCodingExonDiffList.append(tempCodingDiff)
#
minCodingExonDiffList=np.array(minCodingExonDiffList)
minCodingExonDiff=np.min(minCodingExonDiffList)
ncis=np.where(minCodingExonDiffList==minCodingExonDiff)[0] # one-sided index
# Condition 3: one unique minimum difference in the number of coding exons
if len(ncis)==1:
#print ("Condition3")
x=axs[ncis[0]]; y=ays[ncis[0]]
oneToOneTrs.append([x,y,3,newTsimMatrixCoding[x,y],newTsimMatrixAll[x,y],minCodingExonDiff,-1])
newTsimMatrixCoding[x,:]=0; newTsimMatrixCoding[:,y]=0
newTsimMatrixAll[x,:]=0; newTsimMatrixAll[:,y]=0
conditionCounter[3]+=1
# Condition 3 fails -> multiple equal coding/ and overall sim and coding exon count difference
else:
#print ("Condition3+")
minAllExonDiffList=[]
for i in ncis:
x=axs[i]; y=ays[i]
t1=trevDic1[x]; t2=trevDic2[y]
tempAllDiff=abs(len(transcriptDic1[t1].exons)-len(transcriptDic2[t2].exons))
minAllExonDiffList.append(tempAllDiff)
#
minAllExonDiffList=np.array(minAllExonDiffList)
minAllExonDiff=np.min(minAllExonDiffList)
nais=np.where(minAllExonDiffList==minAllExonDiff)[0] # one-sided index
# Condition 4: one unique minimum difference in the number of all exons
if len(nais)==1:
#print ("Condition4")
x=axs[ncis[nais[0]]]; y=ays[ncis[nais[0]]]
oneToOneTrs.append([x,y,4,newTsimMatrixCoding[x,y],newTsimMatrixAll[x,y],minCodingExonDiff,minAllExonDiff])
newTsimMatrixCoding[x,:]=0; newTsimMatrixCoding[:,y]=0
newTsimMatrixAll[x,:]=0; newTsimMatrixAll[:,y]=0
conditionCounter[4]+=1
# Condition 4 fails -> multiple equal coding/ and overall sim andcoding/ and overall exon count difference
else:
#print ("Condition4+")
# check the coding lengths of transcripts
minCodingLenDiffList=[]
for i in nais:
x=axs[ncis[i]]; y=ays[ncis[i]]
t1=trevDic1[x]; t2=trevDic2[y];
tlen1=0; tlen2=0
for stC,enC in transcriptDic1[t1].codingExons:
tlen1+=abs(int(stC)-int(enC))
for stC,enC in transcriptDic2[t2].codingExons:
tlen2+=abs(int(stC)-int(enC))
tempLenDiff=abs(tlen1-tlen2)
minCodingLenDiffList.append(tempLenDiff)
#
minCodingLenDiffList=np.array(minCodingLenDiffList)
minCodingLenDiff=np.min(minCodingLenDiffList)
lcis=np.where(minCodingLenDiffList==minCodingLenDiff)[0] # one-sided index
# Condition 5: one unique minimum difference in the coding length differences
if len(lcis)==1:
#print ("Condition5")
x=axs[ncis[nais[lcis[0]]]]; y=ays[ncis[nais[lcis[0]]]]
oneToOneTrs.append([x,y,5,newTsimMatrixCoding[x,y],newTsimMatrixAll[x,y],minCodingExonDiff,minAllExonDiff])
newTsimMatrixCoding[x,:]=0; newTsimMatrixCoding[:,y]=0
newTsimMatrixAll[x,:]=0; newTsimMatrixAll[:,y]=0
conditionCounter[5]+=1
# Condition 5 fails -> all the above could not break the tie. Just report all of them.
else:
#print (["Condition5+ = 6", lcis, len(lcis),len(oneToOneTrs)])
for i in lcis:
x=axs[ncis[nais[i]]]; y=ays[ncis[nais[i]]]
oneToOneTrs.append([x,y,6,newTsimMatrixCoding[x,y],\
newTsimMatrixAll[x,y],minCodingExonDiff,minAllExonDiff])
for i in lcis:
x=axs[ncis[nais[i]]]; y=ays[ncis[nais[i]]]
newTsimMatrixCoding[x,:]=0; newTsimMatrixCoding[:,y]=0
newTsimMatrixAll[x,:]=0; newTsimMatrixAll[:,y]=0
#
conditionCounter[6]+=1
#
#
#
#
print ("\nCondition counter from the greedy transcript mapping stage:")
print ("\t%d pairs with Condition1: Unique winner pair" % conditionCounter[1])
print ("\t%d pairs with Condition2: Tie in one score, not in the other" % conditionCounter[2])
print ("\t%d pairs with Condition3: Tie in both scores but coding exon length diff breaks the tie" % conditionCounter[3])
print ("\t%d pairs with Condition4: Tie in both scores and coding exon length diff but overall exon length breaks the tie" % conditionCounter[4])
print ("\t%d pairs with Condition5: Tie in all the above but coding length (bp) diff breaks the tie" % conditionCounter[5])
print ("\t%d pairs with Condition6: Tie in all the above, just give up and report all" % conditionCounter[6])
return oneToOneTrs
def greedy_exonPairs_per_transcriptPair(t1,t2):
"""
For a given transcript pair find a matching of exons greedily by picking the
highest similarity exon pairs first and so on to compute one-to-one exon mappings
and an overall pairwise transcript similarity score.
"""
# list the exons and coding exons
elist1=transcriptDic1[t1].exons
elist2=transcriptDic2[t2].exons
#ecodinglist1=transcriptDic1[t1].codingExons # FERHAT fixed 4/5/2018
ecodinglist1=[]
for ex1 in [x[2] for x in elist1]:
if exonDic1[ex1].exon_type!="nonCoding": ecodinglist1.append(ex1)
#ecodinglist2=transcriptDic2[t2].codingExons # FERHAT fixed 4/5/2018
ecodinglist2=[]
for ex2 in [x[2] for x in elist2]:
if exonDic2[ex2].exon_type!="nonCoding": ecodinglist2.append(ex2)
noRows=len(elist1)
noCols=len(elist2)
# create the coding and all similarity matrices for exons
esimMatrixAll=np.zeros((noRows,noCols))
esimMatrixCoding=np.zeros((noRows,noCols))
ei=0
for ex1 in [x[2] for x in elist1]:
origExonEntry1=exonDic1[ex1]
ej=0
e1type=origExonEntry1.exon_type
for ex2 in [x[2] for x in elist2]:
origExonEntry2=exonDic2[ex2]
e2type=origExonEntry2.exon_type
allOverlapScore,codingOverlapScore=0,0
if ex1 in liftoverExonMappings and ex2 in liftoverExonMappings[ex1]:
allOverlapScore,codingOverlapScore,minMatchStrAll,minMatchStrCoding=liftoverExonMappings[ex1][ex2]
if e1type=="fullCoding" and e2type=="fullCoding":
codingOverlapScore=allOverlapScore
esimMatrixAll[ei,ej]=allOverlapScore
esimMatrixCoding[ei,ej]=codingOverlapScore
ej+=1
#
ei+=1
#
# reverse dictionaries for lookup from index to exon id
oneToOneExs=[]
erevDic1={}
erevDic2={}
c=0
for ex1 in [x[2] for x in elist1]:
erevDic1[c]=ex1
c+=1
c=0
for ex2 in [x[2] for x in elist2]:
erevDic2[c]=ex2
c+=1
# greedy selection of best exon pairs using the two exon similarty matrices (coding and all)
newEsimMatrixAll=esimMatrixAll.copy()
newEsimMatrixCoding=esimMatrixCoding.copy()
newMax=0.001
conditionCounter=[0,0,0,0] #1=Unique winner, 2=breakable ties, 3=unbreakable ties
while sum(sum(newEsimMatrixAll))+sum(sum(newEsimMatrixCoding))>0 and newMax>0 and len(oneToOneExs)<min(len(elist1),len(elist2)):
# select the max among the two score matrices
newMaxAll=newEsimMatrixAll.max()
newMaxCoding=newEsimMatrixCoding.max()
newMax=max(newMaxAll,newMaxCoding)
codingIsMax=True
# choose where the max of the two came from. For precision purposes use a small difference instead of equality check.
if newMaxAll>newMaxCoding:
xs,ys=np.where(abs(newEsimMatrixAll-newMax)<=0.00000000001)
codingIsMax=False
else:
xs,ys=np.where(abs(newEsimMatrixCoding-newMax)<=0.00000000001)
codingIsMax=True
# Condition 0: something wrong, shouldn't have entered the while loop
if len(xs)==0 or len(ys)==0:
conditionCounter[0]+=1
# Condition 1: one unique maximum for the maximum similarity (either coding or all)
if len(xs)==1:
x=xs[0]; y=ys[0]
oneToOneExs.append([x,y,1,newEsimMatrixCoding[x,y],newEsimMatrixAll[x,y]])
newEsimMatrixCoding[x,:]=0; newEsimMatrixCoding[:,y]=0
newEsimMatrixAll[x,:]=0; newEsimMatrixAll[:,y]=0
conditionCounter[1]+=1
# Condition 1 fails -> multiple equal maximum similarity (either coding or all)
else:
allMax=0
axs,ays=[],[]
# loop and find the max among the xs,ys pairs
for i in range(len(xs)):
x=xs[i]; y=ys[i]
if codingIsMax==True:
if newEsimMatrixAll[x,y]>allMax:
allMax=newEsimMatrixAll[x,y]
else:
if newEsimMatrixCoding[x,y]>allMax:
allMax=newEsimMatrixCoding[x,y]
#
#
# loop once more and find the pairs among xs,ys that still tie
for i in range(len(xs)):
x=xs[i]; y=ys[i]
if codingIsMax==True:
if abs(newEsimMatrixAll[x,y]-allMax)<=0.00000000001:
axs.append(x); ays.append(y)
else:
if abs(newEsimMatrixCoding[x,y]-allMax)<=0.00000000001:
axs.append(x); ays.append(y)
#
# Condition 2: one unique maximum in 'the other' matrix after tie in max (either coding or all)
if len(axs)==1:
x=axs[0]; y=ays[0]
oneToOneExs.append([x,y,2,newEsimMatrixCoding[x,y],newEsimMatrixAll[x,y]])
newEsimMatrixCoding[x,:]=0; newEsimMatrixCoding[:,y]=0
newEsimMatrixAll[x,:]=0; newEsimMatrixAll[:,y]=0
conditionCounter[2]+=1
# Condition 2 fails -> multiple equal coding and overall sim - THEN JUST pick the first one and report it
else:
# Condition 3: JUST pick the first one and report it
x=axs[0]; y=ays[0]
oneToOneExs.append([x,y,3,newEsimMatrixCoding[x,y],newEsimMatrixAll[x,y]])
newEsimMatrixCoding[x,:]=0; newEsimMatrixCoding[:,y]=0
newEsimMatrixAll[x,:]=0; newEsimMatrixAll[:,y]=0
conditionCounter[3]+=1
#
#
exscoreAll=0
exscoreCoding=0
expathAll=[]
expathCoding=[]
for l in oneToOneExs:
ei,ej,condition,codingScore,allScore=l
ex1=erevDic1[ei]
ex2=erevDic2[ej]
exscoreAll+=allScore
exscoreCoding+=codingScore
expathAll.append([ei,ej,allScore,codingScore])
#
origExonEntry1=exonDic1[ex1]
origExonEntry2=exonDic2[ex2]
e1type=origExonEntry1.exon_type
e2type=origExonEntry2.exon_type
if e1type!="nonCoding" and e2type!="nonCoding":
expathCoding.append([ei,ej,allScore,codingScore])
#
## taking max of exon lengths
#exscoreAll=(exscoreAll)/max(len(elist1),len(elist2))
#exscoreCoding=(exscoreCoding)/max(1,max(len(ecodinglist1),len(ecodinglist2)))
## taking sum of exon lengths
exscoreAll=(2*exscoreAll)/max(1,len(elist1)+len(elist2))
exscoreCoding=(2*exscoreCoding)/max(1,len(ecodinglist1)+len(ecodinglist2))
return (exscoreAll,expathAll,exscoreCoding,expathCoding)
def output_transcript_level_matches(genePairId,exonClasses1,exonClasses2):
"""
Find exon level pairings/mappings using previously calculated exon similarities
and a method of choice (greedy/DP/allToAll) to compute transcript similarities.
Then, extract transcript level mappings using a greedy algorithm that also
does tie breaking in a rule-based system.
"""
print ("*****************************************************************")
outfilename=outdir+"/exonLevelMappings-"+str(MAPPED_EXON_THRES)+".txt"
print ("Writing exon-level mappings into file:\n %s" % outfilename)
outfileExonMappings=open(outfilename,'w')
outfileExonMappings.write("chrName1\tstartCoord1\tendCoord1\tstrand1\texonID1\texonType1\tchrName2\tstartCoord2\tendCoord2\tstrand2\texonID2\texonType2\toverlapScoreFromFullLength\toverlapScoreFromPartialCodingPart\n")
outfilename=outdir+"/transcriptLevelSimilarities-"+str(MAPPED_EXON_THRES)+".txt"
print ("Writing trascript-level similarity scores into file:\n %s" % outfilename)
outfileTranscriptSims=open(outfilename,'w')
outfileTranscriptSims.write("chrName1\tstartCoord1\tendCoord1\tstrand1\ttranscriptID1\ttranscriptType1\tchrName2\tstartCoord2\tendCoord2\tstrand2\ttranscriptID2\ttranscriptType2\tnoOfAllExons1\tnoOfAllExons2\tmappedAllExonPairs\tnoOfCodingExons1\tnoOfCodingExons2\tmappedCodingExonPairs\toverallSimScore\tcodingSimScore\n")
# list of all transcripts per each gene
tdic1=geneDic1[g1].transcripts
tdic2=geneDic2[g2].transcripts
# pairwise transcript similarity matrices
noRows=len(tdic1)
noCols=len(tdic2)
tsimMatrixAll=np.zeros((noRows,noCols))
tsimMatrixCoding=np.zeros((noRows,noCols))
allExonPairs={}
ti=0
for t1 in tdic1:
elist1=transcriptDic1[t1].exons
#ecodinglist1=transcriptDic1[t1].codingExons # FERHAT fixed 4/5/2018
ecodinglist1=[]
for ex1 in [x[2] for x in elist1]:
if exonDic1[ex1].exon_type!="nonCoding": ecodinglist1.append(ex1)
t1Entry=transcriptDic1[t1]
ch1,s1="chr"+t1Entry.basicInfoDic["chromosome"],t1Entry.basicInfoDic["start_coord"]
e1,strand1=t1Entry.basicInfoDic["end_coord"],t1Entry.basicInfoDic["strand"]
t1type=t1Entry.basicInfoDic["transcript_biotype"]
tj=0
for t2 in tdic2:
elist2=transcriptDic2[t2].exons
#ecodinglist2=transcriptDic2[t2].codingExons # FERHAT fixed 4/5/2018
ecodinglist2=[]
for ex2 in [x[2] for x in elist2]:
if exonDic2[ex2].exon_type!="nonCoding": ecodinglist2.append(ex2)
t2Entry=transcriptDic2[t2]
ch2,s2="chr"+t2Entry.basicInfoDic["chromosome"],t2Entry.basicInfoDic["start_coord"]
e2,strand2=t2Entry.basicInfoDic["end_coord"],t2Entry.basicInfoDic["strand"]
t2type=t2Entry.basicInfoDic["transcript_biotype"]
### extract exon mappings/pairings using one of the below methods to compute transcript level similarities
allScore,pathAll,codingScore,pathCoding=greedy_exonPairs_per_transcriptPair(t1,t2)
#allScore,pathAll,codingScore,pathCoding=dynamic_programming_per_transcriptPair(t1,t2)
#allScore,pathAll,codingScore,pathCoding=all_exonPairs_per_transcriptPair(t1,t2)
outfileTranscriptSims.write("%s\t%d\t%d\t%s\t%s\t%s\t%s\t%d\t%d\t%s\t%s\t%s\t%d\t%d\t%d\t%d\t%d\t%d\t\t%.3f\t%.3f\n" % \
(ch1,s1,e1,strand1,t1,t1type,ch2,s2,e2,strand2,t2,t2type, \
len(elist1),len(elist2),len(pathAll), len(ecodinglist1),len(ecodinglist2), len(pathCoding), \
allScore,codingScore))
tsimMatrixAll[ti,tj]=allScore
tsimMatrixCoding[ti,tj]=codingScore
for l in pathAll:
ei,ej,allOverlapScore,codingOverlapScore=l[0],l[1],l[2],l[3]
ex1=elist1[ei][2]
ex2=elist2[ej][2]
if ex1 not in allExonPairs:
allExonPairs[ex1]={}
if ex2 not in allExonPairs[ex1]:
allExonPairs[ex1][ex2]=[0,0]
allExonPairs[ex1][ex2]=[allOverlapScore,codingOverlapScore]
#
tj+=1
#
ti+=1
#
for ex1 in allExonPairs:
origExonEntry1=exonDic1[ex1]
ch1,s1="chr"+origExonEntry1.basicInfoDic["chromosome"],origExonEntry1.basicInfoDic["start_coord"]
e1,strand1=origExonEntry1.basicInfoDic["end_coord"],origExonEntry1.basicInfoDic["strand"]
e1type=origExonEntry1.exon_type
for ex2 in allExonPairs[ex1]:
origExonEntry2=exonDic2[ex2]
ch2,s2="chr"+origExonEntry2.basicInfoDic["chromosome"],origExonEntry2.basicInfoDic["start_coord"]
e2,strand2=origExonEntry2.basicInfoDic["end_coord"],origExonEntry2.basicInfoDic["strand"]
e2type=origExonEntry2.exon_type
allOverlapScore,codingOverlapScore=allExonPairs[ex1][ex2]
# Only output exon mappings that pass the threshold even though other pairs are also used for
# computing the transcript level similarities
if allOverlapScore>=MAPPED_EXON_THRES or codingOverlapScore>=MAPPED_EXON_THRES:
outfileExonMappings.write("%s\t%d\t%d\t%s\t%s\t%s\t%s\t%d\t%d\t%s\t%s\t%s\t%.3f\t%.3f\n" \
% (ch1,s1,e1,strand1,ex1,e1type,ch2,s2,e2,strand2,ex2,e2type,allOverlapScore,codingOverlapScore))
#
#
outfileExonMappings.close()
outfileTranscriptSims.close()
outfilename=outdir+"/transcriptLevelMappings-"+str(MAPPED_EXON_THRES)+".txt"
print ("Writing transcript-level mappings into file:\n %s" % outfilename)
outfileTranscriptMappings=open(outfilename,'w')
outfileTranscriptMappings.write("chrName1\tstartCoord1\tendCoord1\tstrand1\ttranscriptID1\ttranscriptType1\tchrName2\tstartCoord2\tendCoord2\tstrand2\ttranscriptID2\ttranscriptType2\tnoOfAllExons1\tnoOfAllExons2\tmappedAllExonPairs\tnoOfCodingExons1\tnoOfCodingExons2\tmappedCodingExonPairs\toverallSimScore\tcodingSimScore\n")
trevDic1={}
c=0
for t in tdic1:
trevDic1[c]=t
c+=1
c=0
trevDic2={}
for t in tdic2:
trevDic2[c]=t
c+=1
# find and write the one-to-one mapped transcript pairs
oneToOneTrs=greedily_map_transcripts_with_tie_breaks(tdic1,tdic2,tsimMatrixAll,tsimMatrixCoding,trevDic1,trevDic2)
for l in oneToOneTrs:
ti,tj,condition,codingScore,allScore,codingExonDiff,allExonDiff=l
t1=trevDic1[ti]
t2=trevDic2[tj]
elist1=transcriptDic1[t1].exons
#ecodinglist1=transcriptDic1[t1].codingExons # FERHAT fixed 4/5/2018
ecodinglist1=[]
for ex1 in [x[2] for x in elist1]:
if exonDic1[ex1].exon_type!="nonCoding": ecodinglist1.append(ex1)
t1Entry=transcriptDic1[t1]
ch1,s1="chr"+t1Entry.basicInfoDic["chromosome"],t1Entry.basicInfoDic["start_coord"]
e1,strand1=t1Entry.basicInfoDic["end_coord"],t1Entry.basicInfoDic["strand"]
t1type=t1Entry.basicInfoDic["transcript_biotype"]
elist2=transcriptDic2[t2].exons
#ecodinglist2=transcriptDic2[t2].codingExons # FERHAT fixed 4/5/2018
ecodinglist2=[]
for ex2 in [x[2] for x in elist2]:
if exonDic2[ex2].exon_type!="nonCoding": ecodinglist2.append(ex2)
t2Entry=transcriptDic2[t2]
ch2,s2="chr"+t2Entry.basicInfoDic["chromosome"],t2Entry.basicInfoDic["start_coord"]
e2,strand2=t2Entry.basicInfoDic["end_coord"],t2Entry.basicInfoDic["strand"]
t2type=t2Entry.basicInfoDic["transcript_biotype"]
outfileTranscriptMappings.write("%s\t%d\t%d\t%s\t%s\t%s\t%s\t%d\t%d\t%s\t%s\t%s\t%d\t%d\t%d\t%d\t%d\t%d\t\t%.3f\t%.3f\n" % \
(ch1,s1,e1,strand1,t1,t1type,ch2,s2,e2,strand2,t2,t2type, \
len(elist1),len(elist2),len(pathAll), len(ecodinglist1),len(ecodinglist2), len(pathCoding), \
allScore,codingScore))
#
outfileTranscriptMappings.close()
#Write bed files per pair to be able to visualize in genome browser
write_out_bedFiles_for_UCSCbrowser(genePairId,exonClasses1,exonClasses2,oneToOneTrs,trevDic1,trevDic2)
return
def classify_exons(genePairId,mappedExonThreshold):
"""
Given a threshold on the similarity between two exons to be
deemed "mapped" (mappedExonThreshold), this function determines
the exon classes using all the info from parsed liftover files.
"""
# print ("*****************************************************************")
# open the output files to which the results of the mapping will be written
outfilename=outdir+"/exonLevelSimilarities-"+str(MAPPED_EXON_THRES)+".txt"
outfileExonSims=open(outfilename,'w')
print ("Writing exon-level similarity scores into file:\n %s" % outfilename)
outfileExonSims.write("chrName1\tstartCoord1\tendCoord1\tstrand1\texonID1\texonType1\tchrName2\tstartCoord2\tendCoord2\tstrand2\texonID2\texonType2\toverlapScoreFromFullLength\toverlapScoreFromPartialCodingPart\n")
exonClasses1={}; exonClasses2={}
## NOW print all that you learned from parsing these three files per exon
for ex1 in liftoverExonMappings:
origExonEntry1=exonDic1[ex1]
ch1,s1="chr"+origExonEntry1.basicInfoDic["chromosome"],origExonEntry1.basicInfoDic["start_coord"]
e1,strand1=origExonEntry1.basicInfoDic["end_coord"],origExonEntry1.basicInfoDic["strand"]
e1type=origExonEntry1.exon_type
for ex2 in liftoverExonMappings[ex1]:
origExonEntry2=exonDic2[ex2]
ch2,s2="chr"+origExonEntry2.basicInfoDic["chromosome"],origExonEntry2.basicInfoDic["start_coord"]
e2,strand2=origExonEntry2.basicInfoDic["end_coord"],origExonEntry2.basicInfoDic["strand"]
e2type=origExonEntry2.exon_type
allOverlapScore,codingOverlapScore,minMatchStrAll,minMatchStrCoding=liftoverExonMappings[ex1][ex2]
if allOverlapScore>=mappedExonThreshold or codingOverlapScore>=mappedExonThreshold:
if ex1 not in exonClasses1:
exonClasses1[ex1]=["Type",0,0]
if ex2 not in exonClasses2:
exonClasses2[ex2]=["Type",0,0]
if allOverlapScore>exonClasses1[ex1][1]:
exonClasses1[ex1][0]="Mapped"; exonClasses1[ex1][1]=allOverlapScore
if codingOverlapScore>exonClasses1[ex1][2]:
exonClasses1[ex1][0]="Mapped"; exonClasses1[ex1][2]=codingOverlapScore
if allOverlapScore>exonClasses2[ex2][1]:
exonClasses2[ex2][0]="Mapped"; exonClasses2[ex2][1]=allOverlapScore
if codingOverlapScore>exonClasses2[ex2][2]:
exonClasses2[ex2][0]="Mapped"; exonClasses2[ex2][2]=codingOverlapScore
#
outfileExonSims.write("%s\t%d\t%d\t%s\t%s\t%s\t%s\t%d\t%d\t%s\t%s\t%s\t%.3f\t%.3f\n" \
% (ch1,s1,e1,strand1,ex1,e1type,ch2,s2,e2,strand2,ex2,e2type,allOverlapScore,codingOverlapScore)),
#
#outfileExonSims.write("%s\t%s\t%s\t%s\t%.3f\t%.3f\t%s\t%s\n" % \
# (ex1,ex2,origExonEntry1.get_summary_string(),origExonEntry2.get_summary_string(),allOverlapScore,\
# codingOverlapScore,minMatchStrAll,minMatchStrCoding))
#
#
for ex in nonintersectingExons:
for chse in nonintersectingExons[ex]:
minMatchStr,junctionProblem,ch,s,e,strand,sqAcc,sqDon,liftedOverLenForEx=nonintersectingExons[ex][chse]
if ex in exonDic1:
origExonEntry=exonDic1[ex]
# if a mapping not found for this exon with at least mappedExonThreshold and there were no Unmapped entries
if ex not in exonClasses1:
exonClasses1[ex]=["Nonintersecing", junctionProblem, minMatchStr]
else:
origExonEntry=exonDic2[ex]
# if a mapping not found for this exon with at least mappedExonThreshold and there were no Unmapped entries
if ex not in exonClasses2:
exonClasses2[ex]=["Nonintersecing", junctionProblem, minMatchStr]
#
# this doesn't mean that Nonintersecing is the class of this exon
#outfileExonSims.write("PotentialSpliceLoss\t%r\t%s\t%s\t%s\t%d\t%d\t%s\t%s\t%s\t%d\n" % \
# (junctionProblem,minMatchStr,origExonEntry.get_summary_string(),ch,int(s),int(e),strand,sqAcc,sqDon,liftedOverLenForEx))
#
#
for ex in unmappedExons:
for whyUnmapped in unmappedExons[ex]:
minMatchStr=unmappedExons[ex][whyUnmapped]
if ex in exonDic1:
origExonEntry=exonDic1[ex]
# if a mapping not found for this exon with at least mappedExonThreshold
if ex not in exonClasses1:
exonClasses1[ex]=["Unmapped",whyUnmapped,minMatchStr]
else:
origExonEntry=exonDic2[ex]
# if a mapping not found for this exon with at least mappedExonThreshold
if ex not in exonClasses2:
exonClasses2[ex]=["Unmapped",whyUnmapped,minMatchStr]
#
# this doesn't mean that UnmappedExon is the class of this exon
#outfileExonSims.write("UnmappedExon\t%s\t%s\t%s\n" % (minMatchStr,origExonEntry.get_summary_string(),whyUnmapped))
#
#
outfileExonSims.close()
outfilename=outdir+"/exonClasses-"+str(MAPPED_EXON_THRES)+".txt"
outfileExonClasses=open(outfilename,'w')
print ("\nWriting exon classes into file:\n %s" % outfilename)
outfileExonClasses.write("exonID\texonClass\tmaxOverlapScore\tmaxCodingOverlapScore\twhyUnmapped\tjunctionProblem\tchrName\tstartCoord\tendCoord\tstrand\texonID\texonType\tcodingStart\tcodingEnd\ttranscriptIDs\texonNumbers\tgeneID\texonLength\tacceptor2bp\tdonor2bp\tavgCodingConsScore\tavgConsScore\tfirstMidLastCounts\telementType\n")
liftOverExpDic={'#Partially': "PartiallyDeletedInNew", "#Split": "SplitInNew", "#Deleted" : "DeletedInNew", \
"#Duplicated": "DuplicatedInNew", "#Boundary" : "BoundaryProblem"}
#print("***************** Exon classes for the first organism **************************\n"),
counts=[0,0,0,0]
for ex in exonDic1:
origExonEntry=exonDic1[ex]
etype=origExonEntry.exon_type
allOverlapScore=0.0; codingOverlapScore=0.0; whyUnmapped='NA'; junctionProblem='NA'
cl="OTHER"
if ex in exonClasses1:
cl,field1,field2=exonClasses1[ex][0],exonClasses1[ex][1],exonClasses1[ex][2]
if cl=='Mapped':
counts[0]+=1
allOverlapScore=float(field1); codingOverlapScore=float(field2)
if etype=='fullCoding':
codingOverlapScore=max(allOverlapScore,codingOverlapScore)
allOverlapScore=codingOverlapScore
elif cl=='Unmapped':
counts[1]+=1
whyUnmapped=liftOverExpDic[field1]
elif cl=='Nonintersecing':
counts[2]+=1
junctionProblem=field1
#
if cl=='OTHER':
counts[3]+=1
outfileExonClasses.write("%s\t%s\t%.3f\t%.3f\t%s\t%s\t%s\n" % \
(ex,cl,allOverlapScore,codingOverlapScore,whyUnmapped,junctionProblem,origExonEntry.get_summary_string()))
#
print ("\tFor org1: Mapped exons= %d, Unmapped exons= %d, Nonintersecting exons= %d, OTHER= %d" % (counts[0],counts[1],counts[2],counts[3]))
#print("***************** Exon classes for the second organism **************************\n"),
counts=[0,0,0,0]
for ex in exonDic2:
origExonEntry=exonDic2[ex]
etype=origExonEntry.exon_type
allOverlapScore=0.0; codingOverlapScore=0.0; whyUnmapped='NA'; junctionProblem='NA'
cl="OTHER"
if ex in exonClasses2:
cl,field1,field2=exonClasses2[ex][0],exonClasses2[ex][1],exonClasses2[ex][2]
if cl=='Mapped':
counts[0]+=1
allOverlapScore=float(field1); codingOverlapScore=float(field2)
if etype=='fullCoding':
codingOverlapScore=max(allOverlapScore,codingOverlapScore)
allOverlapScore=codingOverlapScore
elif cl=='Unmapped':
counts[1]+=1
whyUnmapped=liftOverExpDic[field1]
elif cl=='Nonintersecing':
counts[2]+=1
junctionProblem=field1
#
if cl=='OTHER':
counts[3]+=1
outfileExonClasses.write("%s\t%s\t%.3f\t%.3f\t%s\t%s\t%s\n" % \
(ex,cl,allOverlapScore,codingOverlapScore,whyUnmapped,junctionProblem,origExonEntry.get_summary_string()))
#
print ("\tFor org2: Mapped exons= %d, Unmapped exons= %d, Nonintersecting exons= %d, OTHER= %d" % (counts[0],counts[1],counts[2],counts[3]))
print ("*****************************************************************\n")
#
outfileExonClasses.close()
return exonClasses1,exonClasses2
def parse_liftOver_nonintersecting_file_perExon(infilename,oneToTwo):
"""
Parse the .nonintersecting files and determine splice junction losses.
An example line:
chr18 9495767 9495820 + ENSE00000327880 2 flank0-minMatch0.9-multiples
chr6 119893048 119893101 + ENSE00000327880 3 flank0-minMatch0.9-multiples
"""
infile=open(infilename,'r')
if oneToTwo==True:
org="org2"
exonDicToUse=exonDic1
geneEntry=geneDic2[g2]
else:
org="org1"
exonDicToUse=exonDic2
geneEntry=geneDic1[g1]
#
with Genome(genomedataDir+"/"+org) as genome:
# move to above
for line in infile:
words=line.rstrip().split()
# if exon names are coming from org1, lifted over coords a from org2
ch,s,e,strand,ex,multiplicity,suffixStr=words
minMatchStr=suffixStr.split("-")[1][8:] # parse the suffixStr assuming a specific format
# don't use the entries coming from partCoding regions as they will not have the splice sites
if suffixStr.endswith("partCoding"):
continue
gCh,gS,gE="chr"+str(geneEntry.basicInfoDic["chromosome"]),geneEntry.basicInfoDic["start_coord"],geneEntry.basicInfoDic["end_coord"]
# discard liftover entries that have nothing to do with the corresponding ortholog gene
if gCh!=ch:
continue
elif max(0, min(int(e),int(gE))-max(int(s),int(gS)))<1:
continue
# information about the original exon before lifted over
origExonEntry=exonDicToUse[ex]
acceptor1=origExonEntry.acceptor2bp
donor1=origExonEntry.donor2bp
avgConsScore=origExonEntry.avgConsScore
fml1=origExonEntry.firstMidLast #[f,m,l] counts
orCh,orS=origExonEntry.basicInfoDic["chromosome"],origExonEntry.basicInfoDic["start_coord"]
orE,orStrand=origExonEntry.basicInfoDic["end_coord"],origExonEntry.basicInfoDic["strand"]
origExonLen=abs(orS-orE)
liftedOverLenForEx=abs(int(s)-int(e))
## below check not needed anymore due to above ch==gCh check
#if ch not in genome:
# continue
sq=genome[ch].seq[int(s)-3:int(e)+2].tostring().lower().upper().decode("utf-8")
print (sq)
if strand=="-":
sqAcc=sq[-2:].lower().translate(complement)[::-1].upper() # reverse complement
sqDon=sq[:2].lower().translate(complement)[::-1].upper() # reverse complement
else:
sqAcc=sq[:2]
sqDon=sq[-2:]
#
# Below if else structure is used for determining junction problems
# depending on whether an exon is first, mid, last or a combination
f,m,l=fml1
junctionProblem=False
if m>0 or (f>0 and l>0):
if sqAcc!=acceptor1 or sqDon!=donor1:
junctionProblem=True
elif f>0:
if sqDon!=donor1:
junctionProblem=True
elif l>0:
if sqAcc!=acceptor1:
junctionProblem=True
#