-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathrmatspipeline.pyx
4038 lines (3500 loc) · 157 KB
/
rmatspipeline.pyx
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
# -*- coding: utf-8 -*-
##
# @file lite2.py
# @brief
# @author Zhijie Xie
# @date 2015-11-27
# cython: language_level=2
# cython: c_string_type=str, c_string_encoding=ascii
import shutil
import sys
import time
from nogilbam cimport *
from os import mkdir, walk
from os.path import basename, splitext, join, exists
from datetime import datetime
from cython.parallel import prange
from cython import boundscheck, wraparound
from cython.operator cimport dereference as deref, preincrement as inc
from rmatspipeline_declarations cimport *
USAGE = '''usage: %(prog)s [options] arg1 arg2'''
cdef:
size_t refer_len = 1000
int sg_mode = 0, read_mode = 1, both_mode = 2
char ccolon = ':', cdot = '.'
char plus_mark = '+'
char minus_mark = '-'
char equal_mark = '='
char empty_mark = ' '
string plus_mark_str = "+"
string minus_mark_str = "-"
string equal_mark_str = "="
string empty_mark_str = " "
string NH = 'NH'
string CHR = "chr"
string dot_str = '.'
string ntxID = '_novel_'
cbool GTF_TX = False
cbool BAM_TX = True
int FRUNSTRANDED = 0
int FRFIRSTSTRAND = 1
int FRSECONDSTRAND = 2
# enum for counting the outcome of each read from the BAMs
int READ_USED = 0
int READ_NOT_PAIRED = 1
int READ_NOT_NH_1 = 2
int READ_NOT_EXPECTED_CIGAR = 3
int READ_NOT_EXPECTED_READ_LENGTH = 4
int READ_NOT_EXPECTED_STRAND = 5
int READ_EXON_NOT_MATCHED_TO_ANNOTATION = 6
int READ_JUNCTION_NOT_MATCHED_TO_ANNOTATION = 7
int READ_CLIPPED = 8
int READ_ENUM_VALUE_COUNT = 9
vector[string] READ_ENUM_NAMES = [
"USED",
"NOT_PAIRED",
"NOT_NH_1",
"NOT_EXPECTED_CIGAR",
"NOT_EXPECTED_READ_LENGTH",
"NOT_EXPECTED_STRAND",
"EXON_NOT_MATCHED_TO_ANNOTATION",
"JUNCTION_NOT_MATCHED_TO_ANNOTATION",
"CLIPPED"
]
char* se_template = '%ld\t%s\t%s\t%s\t%c\t%ld\t%ld\t%ld\t%ld\t%ld\t%ld\n'
char* mxe_template = '%ld\t%s\t%s\t%s\t%c\t%ld\t%ld\t%ld\t%ld\t%ld\t%ld\t%ld\t%ld\n'
char* alt35_template = '%ld\t%s\t%s\t%s\t%c\t%ld\t%ld\t%ld\t%ld\t%ld\t%ld\n'
char* ri_template = '%ld\t%s\t%s\t%s\t%c\t%ld\t%ld\t%ld\t%ld\t%ld\t%ld\n'
char* ceHeader = "ID\tGeneID\tgeneSymbol\tchr\tstrand\texonStart_0base\texonEnd\tupstreamES\tupstreamEE\tdownstreamES\tdownstreamEE\n"
char* mxeHeader = "ID\tGeneID\tgeneSymbol\tchr\tstrand\t1stExonStart_0base\t1stExonEnd\t2ndExonStart_0base\t2ndExonEnd\tupstreamES\tupstreamEE\tdownstreamES\tdownstreamEE\n"
char* altSSHeader = "ID\tGeneID\tgeneSymbol\tchr\tstrand\tlongExonStart_0base\tlongExonEnd\tshortES\tshortEE\tflankingES\tflankingEE\n"
char* riHeader = "ID\tGeneID\tgeneSymbol\tchr\tstrand\triExonStart_0base\triExonEnd\tupstreamES\tupstreamEE\tdownstreamES\tdownstreamEE\n"
char* count_header = 'ID\tIJC_SAMPLE_1\tSJC_SAMPLE_1\tIJC_SAMPLE_2\tSJC_SAMPLE_2\tIncFormLen\tSkipFormLen\n'
char* count_tmp = '%d\t%s\t%s\t%s\t%s\t%d\t%d\n'
char* se_count_header = 'ID\tupstream_to_target_count\ttarget_to_downstream_count\ttarget_count\tupstream_to_downstream_count\n'
char* se_count_template = '%d\t%s\t%s\t%s\t%s\n'
char* mxe_count_header = 'ID\tupstream_to_first_count\tfirst_to_downstream_count\tfirst_count\tupstream_to_second_count\tsecond_to_downstream_count\tsecond_count\n'
char* mxe_count_template = '%d\t%s\t%s\t%s\t%s\t%s\t%s\n'
char* alt35_count_header = 'ID\tacross_short_boundary_count\tlong_to_flanking_count\texclusive_to_long_count\tshort_to_flanking_count\n'
char* alt35_count_template = '%d\t%s\t%s\t%s\t%s\n'
char* ri_count_header = 'ID\tupstream_to_intron_count\tintron_to_downstream_count\tintron_count\tupstream_to_downstream_count\n'
char* ri_count_template = '%d\t%s\t%s\t%s\t%s\n'
inline int c_max(long a, long b) nogil: return a if a >= b else b
inline int c_min(long a, long b) nogil: return a if a <= b else b
string tmptmp = "chr1"
string tmpgene = '\"ENSG00000124508\"'
@boundscheck(False)
@wraparound(False)
cdef void parse_gtf(str gtff, unordered_map[int,cset[string]]& geneGroup,
unordered_map[string,Gene]& genes,
unordered_map[string,SupInfo]& supple) except *:
"""TODO: Docstring for parse_gtf.
:returns: TODO
"""
cdef:
size_t i, idx
str striped, chrom, rtype, strand, eled
str gID, tID, txID, gName, dName, dVal
list ele, desc, group
tuple exon, brange
Transcript tx
unordered_map[string,Transcript] vts
cmap[pair[long,long],size_t].iterator imap
gtf = open(gtff, 'r')
for striped in (line.strip() for line in gtf): ## for each line
if striped[0] == '#': ## comments, skip this line
continue
ele = striped.split('\t')
desc = ele[8].split(';')
gID, txID, gName = '', '', 'NA' ## init..
for eled in desc: ## for each element of description
eleds = eled.strip().split(' ')
if len(eled.strip()) < 2 or len(eleds) < 2:
continue ## probably the last description
dName = eleds[0].upper()
dVal = eleds[1]
if dName == 'GENE_ID': ## it is a description for gene_id
gID = dVal
elif dName == 'TRANSCRIPT_ID': ## it is a description for transcript_id
txID = dVal
elif dName == 'GENE_NAME': ## it is a description for gene_name
gName = dVal
if gID == '' or txID == '': ## wrong one..
continue ## process next line
chrom = ele[0]
# TODO what if chrom[0:3] != 'chr' ?
if chrom[0:3] != 'chr':
chrom = 'chr' + chrom
rtype = ele[2] ## exon, intron, CDS, start_codon, stop_codon..
brange = (int(ele[3]), int(ele[4])) # start coord, end coord, 1-base
# group = range(brange[0]/refer_len-1, brange[1]/refer_len+1) ## groups this line could belong to
strand = ele[6]
# for i in group: ## for each possible group
# geneGroup[i].insert(gID)
if rtype == 'exon': ## process exon
if genes.find(gID) != genes.end():
## this transcript is added already
if genes[gID].trans.find(txID) != genes[gID].trans.end():
## add exon to the existing Tx
genes[gID].trans[txID].exons.push_back(brange)
else: ## first time processing this Tx
tx.exons = [brange,]
genes[gID].trans[txID] = tx ## add first exon
else:
tx.exons = [brange,]
genes[gID].trans[txID] = tx
supple[gID].set_info(gName, chrom, strand)
cdef:
unordered_map[string,Gene].iterator igs
unordered_map[string,Transcript].iterator itx
igs = genes.begin()
while igs != genes.end():
# TODO should we skip this?
# TODO No. However, I don't know why it is necessary.
# TODO If we skip it, SE will lose some count. It can't be...
# if deref(igs).second.trans.size() == 1:
# inc(igs)
# continue
itx = deref(igs).second.trans.begin()
while itx != deref(igs).second.trans.end():
# TODO should we skip this tx?
# TODO No. RI need it.
# if deref(itx).second.exons.size() == 1:
# inc(itx)
# continue
sort(deref(itx).second.exons.begin(), deref(itx).second.exons.end())
for idx in range(deref(itx).second.exons.size()):
deref(igs).second.exon_idx[deref(itx).second.exons[idx]] = 0
# len(first) < len(exons) and len(second) < len(exons)
# first: long one preserved. second: short one preserved.
deref(itx).second.first[deref(itx).second.exons[idx].first] = idx
deref(itx).second.second[deref(itx).second.exons[idx].second] = idx
inc(itx)
i = 0
deref(igs).second.idx_exon.resize(deref(igs).second.exon_idx.size())
imap = deref(igs).second.exon_idx.begin()
while imap != deref(igs).second.exon_idx.end():
deref(imap).second = i
deref(igs).second.idx_exon[i] = deref(imap).first
i += 1
inc(imap)
## for each possible group this line could belong to
for i in range(deref(igs).second.idx_exon.front().first/refer_len,
deref(igs).second.idx_exon.back().second/refer_len+1):
geneGroup[i].insert(deref(igs).first)
inc(igs)
return
@boundscheck(False)
@wraparound(False)
cdef cbool read_has_nh_tag_1(const BamAlignment& bread) nogil:
cdef:
char ttype = '0'
int8_t int8 = 0
int16_t int16 = 0
int32_t int32 = 0
uint8_t uint8 = 0
uint16_t uint16 = 0
uint32_t uint32 = 0
float ff = 0
if bread.GetTagType(NH, ttype):
if ttype == BAM_TAG_TYPE_INT8:
if bread.GetTag(NH, int8) == False:
return False
elif int8 != 1:
return False
elif ttype == BAM_TAG_TYPE_UINT8:
if bread.GetTag(NH, uint8) == False:
return False
elif uint8 != 1:
return False
elif ttype == BAM_TAG_TYPE_INT16:
if bread.GetTag(NH, int16) == False:
return False
elif int16 != 1:
return False
elif ttype == BAM_TAG_TYPE_UINT16:
if bread.GetTag(NH, uint16) == False:
return False
elif uint16 != 1:
return False
elif ttype == BAM_TAG_TYPE_INT32:
if bread.GetTag(NH, int32) == False:
return False
elif int32 != 1:
return False
elif ttype == BAM_TAG_TYPE_UINT32:
if bread.GetTag(NH, uint32) == False:
return False
elif uint32 != 1:
return False
elif ttype == BAM_TAG_TYPE_FLOAT:
if bread.GetTag(NH, ff) == False:
return False
elif ff != 1:
return False
else:
if bread.GetTag(NH, uint8) == False:
return False
elif uint8 != 1:
return False
return True
@boundscheck(False)
@wraparound(False)
cdef int filter_read(const BamAlignment& bread, const cbool& ispaired) nogil:
if ispaired and not bread.IsProperPair():
return READ_NOT_PAIRED
if not read_has_nh_tag_1(bread):
return READ_NOT_NH_1
return READ_USED
@boundscheck(False)
@wraparound(False)
cdef int is_bam_exonread(const vector[CigarOp]& cigar_data,
const int amount_clipped,
const int& readLength,
const cbool variable_read_length) nogil:
cdef:
int length
if cigar_data.size() != 1 or cigar_data[0].Type != 'M':
return READ_NOT_EXPECTED_CIGAR
length = amount_clipped + cigar_data[0].Length
if (not variable_read_length) and length != readLength:
return READ_NOT_EXPECTED_READ_LENGTH
return READ_USED
@boundscheck(False)
@wraparound(False)
cdef int is_bam_multijunc(const vector[CigarOp]& cigar_data,
const int amount_clipped,
const int readLength,
const cbool variable_read_length) nogil:
"""TODO: Docstring for is_bam_multijunc.
:returns: TODO
"""
cdef:
size_t i
size_t num = cigar_data.size()
int length = amount_clipped
if num < 3 or num % 2 == 0:
return READ_NOT_EXPECTED_CIGAR
for i in range(num):
if i % 2 == 1:
if cigar_data[i].Type != 'N':
return READ_NOT_EXPECTED_CIGAR
else:
if cigar_data[i].Type != 'M':
return READ_NOT_EXPECTED_CIGAR
length += cigar_data[i].Length
if (not variable_read_length) and length != readLength:
return READ_NOT_EXPECTED_READ_LENGTH
return READ_USED
# jS 1-based
# jE 0-based
@boundscheck(False)
@wraparound(False)
cdef cbool locate_novel(long& jS, long& jE, cset[Triad]& ntx,
Triad& triad, Gene& gene, cbool& novelSS, long& mil) nogil:
cdef:
cbool connected = False
int leftanchored = -1, rightanchored = -1
size_t nexon = 0, i = 0
size_t ui, di # if ui/di == nexon, ui/di == -1.
cset[Triad].iterator intx
unordered_map[long,size_t].iterator uInd, dInd
unordered_map[string,Transcript].iterator ctx
ntx.clear()
ctx = gene.trans.begin()
while ctx != gene.trans.end():
## for each transcript in the candidate gene
uInd = deref(ctx).second.second.find(jS)
if uInd == deref(ctx).second.second.end():
inc(ctx)
continue
ui = deref(uInd).second
dInd = deref(ctx).second.first.find(jE+1)
if dInd == deref(ctx).second.first.end():
inc(ctx)
continue
di = deref(dInd).second
if di - ui == 1:
ntx.clear()
connected = True
break
elif di - ui > 1:
# TODO 0-1-2-3-4-5 1-2-4-5 1,4 0-1-4-5 1-4-5
# TODO rbegin()
connected = True
triad.left = gene.exon_idx[deref(ctx).second.exons[ui]]
triad.mid = triad.left
triad.right = gene.exon_idx[deref(ctx).second.exons[di]]
ntx.insert(triad)
if ui > 0:
triad.left = gene.exon_idx[deref(ctx).second.exons[ui-1]]
ntx.insert(triad)
if di < deref(ctx).second.exons.size() - 1:
## not the last exon
triad.left = triad.mid
triad.mid = triad.right
triad.right = gene.exon_idx[deref(ctx).second.exons[di+1]]
ntx.insert(triad)
else: ### should not be here..
pass
inc(ctx)
if not connected:
for i in range(gene.idx_exon.size()):
if gene.idx_exon[i].second == jS:
leftanchored = i
elif gene.idx_exon[i].first == jE+1:
rightanchored = i
if leftanchored != -1 and rightanchored != -1:
connected = True
triad.left = leftanchored
triad.mid = triad.left
triad.right = rightanchored
ntx.insert(triad)
elif novelSS and leftanchored != -1 and jE - jS >= mil:
connected = True
triad.left = leftanchored
triad.mid = triad.left
triad.right = -(jE+1)
ntx.insert(triad)
elif novelSS and rightanchored != -1 and jE - jS >= mil:
connected = True
triad.left = -(jS)
triad.mid = triad.left
triad.right = rightanchored
ntx.insert(triad)
return connected
@boundscheck(False)
@wraparound(False)
cdef cbool locate_exon(long mc, long mec, int& rl_jl,
Tetrad& tetrad, Gene& gene) nogil:
cdef:
int ilen
long idxi, idxj
cbool enclosed
enclosed = False
tetrad.set(-1,-1,-1,-1)
ilen = gene.idx_exon.size()
# TODO Truly epic optimization task.
for i in range(ilen):
# 0-based
idxi = gene.idx_exon[i].first - 1
if mec > idxi:
# 1-based
idxj = gene.idx_exon[i].second
if mc > idxi:
if mec <= idxj:
enclosed = True
if mc > idxj:
if tetrad.first < idxj + 1:
tetrad.first = idxj + 1
elif mc < idxj:
if tetrad.first < idxi + 1:
tetrad.first = idxi + 1
if tetrad.second > idxj - 1 or tetrad.second == -1:
tetrad.second = idxj - 1
if tetrad.second > idxj - rl_jl:
if mc == idxj - rl_jl + 1:
tetrad.first = idxj - rl_jl + 1
tetrad.second = tetrad.first
elif mc < idxj - rl_jl + 1:
tetrad.second = idxj - rl_jl
else:
tetrad.first = idxj
tetrad.second = idxj
elif mc < idxi:
if tetrad.second > idxi - 1 or tetrad.second == -1:
tetrad.second = idxi - 1
if tetrad.second > idxi - rl_jl:
if mc == idxi - rl_jl + 1:
tetrad.first = idxi - rl_jl + 1
tetrad.second = tetrad.first
elif mc < idxi - rl_jl + 1:
tetrad.second = idxi - rl_jl
else:
if mec <= idxj:
enclosed = True
tetrad.first = idxi
tetrad.second = idxi
if mec < idxj:
if tetrad.fourth > idxj - 1 or tetrad.fourth == -1:
tetrad.fourth = idxj - 1
if tetrad.third < idxi + 1:
tetrad.third = idxi + 1
if tetrad.third < idxi + rl_jl:
if mec == idxi + rl_jl:
tetrad.third = idxi + rl_jl
tetrad.fourth = tetrad.third
elif mec > idxi + rl_jl:
tetrad.third = idxi + rl_jl + 1
elif mec > idxj:
if tetrad.third < idxj + 1:
tetrad.third = idxj + 1
if tetrad.third < idxj + rl_jl:
if mec == idxj + rl_jl:
tetrad.third = idxj + rl_jl
tetrad.fourth = tetrad.third
elif mec > idxj + rl_jl:
tetrad.third = idxj + rl_jl + 1
else:
tetrad.third = idxj
tetrad.fourth = idxj
elif mec < idxi:
if tetrad.fourth > idxi - 1 or tetrad.fourth == -1:
tetrad.fourth = idxi - 1
if tetrad.second > idxi - 1 or tetrad.second == -1:
tetrad.second = idxi - 1
if tetrad.second > idxi - rl_jl:
if mc == idxi - rl_jl + 1:
tetrad.first = idxi - rl_jl + 1
tetrad.second = tetrad.first
elif mc < idxi - rl_jl + 1:
tetrad.second = idxi - rl_jl # + 1
break
else:
tetrad.third = idxi
tetrad.fourth = idxi
return enclosed
# mc 0-based.
@boundscheck(False)
@wraparound(False)
cdef void locate_multi(long& mc, vector[CigarOp]& cigars, int& rl_jl,
cset[Triad]& ntx, string& multiread,
Gene& gene, char* numstr, cbool& valid, cbool& novelSS,
long& mil, long& mel) nogil:
cdef:
size_t i = 0
cbool enclosed = False
Triad triad
Triad exon_junc
Tetrad tetrad
cbool flag = True, connected = False
long jstart = -1, jend = -1
cset[Triad] local_ntx
ntx.clear()
multiread.clear()
exon_junc.set(mc, -1, -1) # 0-based
for i in range(0, cigars.size()):
if i%2 == 0:
exon_junc.mid = exon_junc.left + cigars[i].Length # 1-based
elif i%2 == 1:
exon_junc.left = exon_junc.right # 0-based
# exon_junc.left = exon_junc.mid + cigars[i].Length # 0-based
continue
if i < cigars.size()-1:
exon_junc.right = exon_junc.mid + cigars[i+1].Length # 0-based
connected = locate_novel(exon_junc.mid, exon_junc.right, local_ntx, triad, gene, novelSS, mil)
insert_set[Triad](ntx, local_ntx.begin(), local_ntx.end())
if valid:
if connected:
jstart = exon_junc.mid # 1-based
jend = exon_junc.right # 0-based
flag = False
else:
jstart = -1
jend = -1
if multiread.length() == 0:
# TODO +1 or not.
enclosed = locate_exon(exon_junc.left, exon_junc.mid, rl_jl, tetrad, gene)
if not novelSS: # or exon_junc.left - tetrad.first < mel:
multiread.append(join_pair(numstr, tetrad.first, tetrad.first, ccolon))
else:
multiread.append(join_pair(numstr, exon_junc.left, exon_junc.left, ccolon))
multiread.append(equal_mark_str+join_pair(numstr, jstart, jend, ccolon))
elif i == cigars.size() - 1:
# TODO +1 or not.
enclosed = locate_exon(exon_junc.left, exon_junc.mid, rl_jl, tetrad, gene)
if not novelSS: # or tetrad.fourth - exon_junc.mid < mel:
multiread.append(equal_mark_str+join_pair(numstr, tetrad.fourth, tetrad.fourth, ccolon))
else:
multiread.append(equal_mark_str+join_pair(numstr, exon_junc.mid, exon_junc.mid, ccolon))
if flag:
multiread.clear()
# In an fr-firststrand paired library, the second read in the pair is
# aligned to the original strand and the first read is aligned to the
# opposite strand.
# In an fr-secondstrand paired library, the first read in the pair is
# aligned to the original strand and the second read is aligned to the
# opposite strand.
@boundscheck(False)
@wraparound(False)
cdef char check_strand_paired_fr_first_strand(const BamAlignment& bread) nogil:
cdef:
cbool is_rev = bread.IsReverseStrand()
cbool is_mate_rev = bread.IsMateReverseStrand()
cbool is_first = bread.IsFirstMate()
cbool is_second = bread.IsSecondMate()
cbool one_mate_rev = is_rev ^ is_mate_rev
cbool either_first_or_second = is_first ^ is_second
if not (one_mate_rev and either_first_or_second):
# strand check failed
return cdot
if is_first:
if is_rev:
return plus_mark
else:
return minus_mark
else:
if is_rev:
return minus_mark
else:
return plus_mark
@boundscheck(False)
@wraparound(False)
cdef char check_strand_paired_fr_second_strand(const BamAlignment& bread) nogil:
cdef:
cbool is_rev = bread.IsReverseStrand()
cbool is_mate_rev = bread.IsMateReverseStrand()
cbool is_first = bread.IsFirstMate()
cbool is_second = bread.IsSecondMate()
cbool one_mate_rev = is_rev ^ is_mate_rev
cbool either_first_or_second = is_first ^ is_second
if not (one_mate_rev and either_first_or_second):
# strand check failed
return cdot
if is_first:
if is_rev:
return minus_mark
else:
return plus_mark
else:
if is_rev:
return plus_mark
else:
return minus_mark
# The single end checks are simplified since there is just one read.
@boundscheck(False)
@wraparound(False)
cdef char check_strand_single_end_fr_first_strand(const BamAlignment& bread) nogil:
cdef:
cbool is_rev = bread.IsReverseStrand()
if is_rev:
return plus_mark
else:
return minus_mark
@boundscheck(False)
@wraparound(False)
cdef char check_strand_single_end_fr_second_strand(const BamAlignment& bread) nogil:
cdef:
cbool is_rev = bread.IsReverseStrand()
if is_rev:
return minus_mark
else:
return plus_mark
@boundscheck(False)
@wraparound(False)
cdef char check_strand(const BamAlignment& bread, const cbool& ispaired, const int& dt) nogil:
if dt == FRFIRSTSTRAND:
if ispaired:
return check_strand_paired_fr_first_strand(bread)
return check_strand_single_end_fr_first_strand(bread)
if dt == FRSECONDSTRAND:
if ispaired:
return check_strand_paired_fr_second_strand(bread)
return check_strand_single_end_fr_second_strand(bread)
# FRUNSTRANDED is the last expected case.
# If the library type is anything else (should never happen) the read will
# be marked as READ_NOT_EXPECTED_STRAND.
return cdot
@boundscheck(False)
@wraparound(False)
cdef void drop_clipping_info(const BamAlignment& bread,
vector[CigarOp]* no_clip_cigar_data,
int* amount_clipped,
cbool* was_clipped,
cbool* invalid_cigar) nogil:
cdef:
int i = 0
int first_non_clip_i = 0
int first_trailing_clip_i = 0
amount_clipped[0] = 0
invalid_cigar[0] = False
no_clip_cigar_data[0].clear()
for i in range(bread.CigarData.size()):
if bread.CigarData[i].Type == 'S' or bread.CigarData[i].Type == 'H':
amount_clipped[0] += bread.CigarData[i].Length
first_non_clip_i += 1
continue
else:
break
first_trailing_clip_i = first_non_clip_i
for i in range(first_non_clip_i, bread.CigarData.size()):
if bread.CigarData[i].Type == 'S' or bread.CigarData[i].Type == 'H':
break
else:
no_clip_cigar_data[0].push_back(bread.CigarData[i])
first_trailing_clip_i += 1
for i in range(first_trailing_clip_i, bread.CigarData.size()):
if bread.CigarData[i].Type == 'S' or bread.CigarData[i].Type == 'H':
amount_clipped[0] += bread.CigarData[i].Length
continue
else:
invalid_cigar[0] = True
break
was_clipped[0] = no_clip_cigar_data[0].size() != bread.CigarData.size()
@boundscheck(False)
@wraparound(False)
cdef void parse_bam(long fidx, string bam,
unordered_map[int,cset[string]]& geneGroup,
unordered_map[string,Gene]& genes,
unordered_map[string,SupInfo]& supple,
unordered_map[string,vector[Triad]]& novel_juncs,
unordered_map[string,cmap[Tetrad,int]]& exons,
unordered_map[string,cmap[string,int]]& multis,
cbool issingle, int jld2, int readLength,
cbool variable_read_length, int dt, cbool& novelSS,
long& mil, long& mel, cbool allow_clipping,
vector[int64_t]& read_outcome_counts) nogil:
"""TODO: Docstring for parse_bam.
:returns: TODO
"""
cdef:
cset[string].iterator cg
cset[string] visited
cbool ispaired = not issingle
long mc, mec
size_t i, j
int rl_jl = readLength-jld2
int estart = 0, eend = 0, jend = 0
cbool enclosed
Triad triad
cset[Triad] ntx
Transcript tx, trans
Tetrad tetrad
string bref_name
unordered_map[int,string] refid2str
int minAnchor, ilen = 0
string multiread
char[1000] numstr
char strand
cbool valid
cdef:
BamReader br
BamAlignment bread
RefVector refv
vector[CigarOp] cigar_data_after_clipping
cbool bread_was_clipped
cbool drop_clipping_info_invalid_cigar
int amount_clipped
if not br.Open(bam):
with gil:
print('Fail to open {}: {}'.format(bam, br.GetErrorString()))
return
refv = br.GetReferenceData()
for i in range(refv.size()):
# TODO what if chr[0:3] != 'chr' ?
if refv[i].RefName.substr(0,3).compare(CHR) != 0:
refid2str[br.GetReferenceID(refv[i].RefName)] = CHR + refv[i].RefName
else:
refid2str[br.GetReferenceID(refv[i].RefName)] = refv[i].RefName
while br.GetNextAlignment(bread):
drop_clipping_info(bread, &cigar_data_after_clipping, &amount_clipped,
&bread_was_clipped, &drop_clipping_info_invalid_cigar)
if drop_clipping_info_invalid_cigar:
read_outcome_counts[READ_NOT_EXPECTED_CIGAR] += 1
continue
if bread_was_clipped and not allow_clipping:
read_outcome_counts[READ_CLIPPED] += 1
continue
filter_outcome = filter_read(bread, ispaired)
if filter_outcome != READ_USED:
read_outcome_counts[filter_outcome] += 1
continue
strand = check_strand(bread, ispaired, dt)
if dt != FRUNSTRANDED and strand == cdot:
read_outcome_counts[READ_NOT_EXPECTED_STRAND] += 1
continue
any_exon_match = False
any_multijunc_match = False
exon_outcome = is_bam_exonread(
cigar_data_after_clipping, amount_clipped, readLength,
variable_read_length)
multijunc_outcome = is_bam_multijunc(
cigar_data_after_clipping, amount_clipped, readLength,
variable_read_length)
if exon_outcome == READ_USED:
mc = bread.Position + 1 # position (1-based) where alignment starts
mec = mc + cigar_data_after_clipping[0].Length - 1
bref_name = refid2str[bread.RefID]
visited.clear()
for i in range(mc/refer_len, mec/refer_len+1):
if geneGroup.find(i) == geneGroup.end():
continue
cg = geneGroup[i].begin()
while cg != geneGroup[i].end():
## for each candidate gene
if ((supple[deref(cg)].chrom != bref_name
or (supple[deref(cg)].strand != strand
and dt != FRUNSTRANDED)
or visited.find(deref(cg)) != visited.end())):
inc(cg)
continue
visited.insert(deref(cg))
enclosed = locate_exon(mc, mec, rl_jl, tetrad, genes[deref(cg)])
if (tetrad.first != -1 and tetrad.second != -1) or\
(tetrad.third != -1 and tetrad.fourth != -1):
any_exon_match = True
exons[deref(cg)][tetrad] += 1
inc(cg)
elif multijunc_outcome == READ_USED:
mc = bread.Position # position (0-based) where alignment starts
minAnchor = c_min(cigar_data_after_clipping[0].Length,
cigar_data_after_clipping.back().Length)
valid = (minAnchor >= rl_jl)
bref_name = refid2str[bread.RefID]
visited.clear()
estart = mc
for i in range(0, cigar_data_after_clipping.size()):
if i%2 == 0:
eend = estart + cigar_data_after_clipping[i].Length # 1-based, end of exonic part
elif i%2 == 1:
estart = eend + cigar_data_after_clipping[i].Length# 0-based, start of exonic part
continue
for j in range(estart/refer_len, eend/refer_len+1):
if geneGroup.find(j) == geneGroup.end():
continue
cg = geneGroup[j].begin()
while cg != geneGroup[j].end():
## for each candidate gene
if ((supple[deref(cg)].chrom != bref_name
or (supple[deref(cg)].strand != strand
and dt != FRUNSTRANDED)
or visited.find(deref(cg)) != visited.end())):
inc(cg)
continue
visited.insert(deref(cg))
locate_multi(mc, cigar_data_after_clipping, rl_jl, ntx, multiread,
genes[deref(cg)], numstr, valid, novelSS,
mil, mel)
if multiread.length() > 0:
any_multijunc_match = True
multis[deref(cg)][multiread] += 1
if ntx.size() != 0:
any_multijunc_match = True
novel_juncs[deref(cg)].insert(novel_juncs[deref(cg)].begin(),
ntx.begin(), ntx.end())
inc(cg)
if any_exon_match or any_multijunc_match:
read_outcome_counts[READ_USED] += 1
elif exon_outcome == READ_USED:
read_outcome_counts[READ_EXON_NOT_MATCHED_TO_ANNOTATION] += 1
elif multijunc_outcome == READ_USED:
read_outcome_counts[READ_JUNCTION_NOT_MATCHED_TO_ANNOTATION] += 1
elif (exon_outcome == READ_NOT_EXPECTED_READ_LENGTH
or multijunc_outcome == READ_NOT_EXPECTED_READ_LENGTH):
read_outcome_counts[READ_NOT_EXPECTED_READ_LENGTH] += 1
else:
read_outcome_counts[READ_NOT_EXPECTED_CIGAR] += 1
br.Close()
return
@boundscheck(False)
@wraparound(False)
cdef void output_read_outcomes(const vector[vector[int64_t]]& read_outcome_counts,
const vector[string]& vbams, str tmp_dir,
str prep_prefix):
cdef:
vector[int64_t] aggregated_read_outcome_counts
int64_t total_for_bam
int64_t total
# initialize counts to zero
aggregated_read_outcome_counts.resize(READ_ENUM_VALUE_COUNT)
f_name = join(tmp_dir, '{}_read_outcomes_by_bam.txt'.format(prep_prefix))
with open(f_name, 'wt') as f_handle:
for i in range(vbams.size()):
f_handle.write('{}\n'.format(vbams[i]))
total_for_bam = 0
for j in range(READ_ENUM_VALUE_COUNT):
f_handle.write('{}: {}\n'.format(READ_ENUM_NAMES[j],
read_outcome_counts[i][j]))
aggregated_read_outcome_counts[j] += read_outcome_counts[i][j]
total_for_bam += read_outcome_counts[i][j]
f_handle.write('TOTAL_FOR_BAM: {}\n'.format(total_for_bam))
print('')
print('read outcome totals across all BAMs')
total = 0
for i in range(READ_ENUM_VALUE_COUNT):
print('{}: {}'.format(READ_ENUM_NAMES[i],
aggregated_read_outcome_counts[i]))
total += aggregated_read_outcome_counts[i]
print('total: {}'.format(total))
print('outcomes by BAM written to: {}'.format(f_name))
print('')
@boundscheck(False)
@wraparound(False)
cdef void detect_novel(str bams, unordered_map[int,cset[string]]& geneGroup,
unordered_map[string,Gene]& genes,
unordered_map[string,SupInfo]& supple,
vector[unordered_map[string,vector[Triad]]]& novel_juncs,
vector[unordered_map[string,cmap[Tetrad,int]]]& exons,
vector[unordered_map[string,cmap[string,int]]]& multis, args):
"""TODO: Docstring for detect_novel.
:returns: TODO
"""
cdef:
int fidx, dt
cbool issingle = False, novelSS = args.novelSS
cbool variable_read_length = args.variable_read_length
long vlen, count = 0, nthread = args.nthread
int readLength = args.readLength, jld2 = args.junctionLength/2
vector[string] vbams = bams.split(',')
long mil = args.mil
long mel = args.mel
cbool allow_clipping = args.allow_clipping
vector[vector[int64_t]] read_outcome_counts
dt = args.dt
vlen = vbams.size()
novel_juncs.resize(vlen)
exons.resize(vlen)
multis.resize(vlen)
read_outcome_counts.resize(vlen)
# initialize outcome counts to zero
for i in range(vlen):
read_outcome_counts[i].resize(READ_ENUM_VALUE_COUNT)
if args.readtype == 'single':
issingle = True