/
calculate_read_cost.py
executable file
·1902 lines (1622 loc) · 72.1 KB
/
calculate_read_cost.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
#!/usr/bin/env python
import sys, os, subprocess
import multiprocessing
import string, re
import platform
from datetime import datetime, date, time
import copy
from argparse import ArgumentParser, FileType
"""
"""
def reverse_complement(seq):
result = ""
for nt in seq:
base = nt
if nt == 'A':
base = 'T'
elif nt == 'a':
base = 't'
elif nt == 'C':
base = 'G'
elif nt == 'c':
base = 'g'
elif nt == 'G':
base = 'C'
elif nt == 'g':
base = 'c'
elif nt == 'T':
base = 'A'
elif nt == 't':
base = 'a'
result = base + result
return result
"""
"""
def read_genome(genome_filename):
chr_dic = {}
genome_file = open(genome_filename, "r")
chr_name, sequence = "", ""
for line in genome_file:
if line[0] == ">":
if chr_name and sequence:
chr_dic[chr_name] = sequence
chr_name = line[1:-1]
sequence = ""
else:
sequence += line[:-1]
if chr_name and sequence:
chr_dic[chr_name] = sequence
genome_file.close()
print >> sys.stderr, "genome is loaded"
return chr_dic
"""
"""
def extract_splice_sites(gtf_fname):
trans = {}
gtf_file = open(gtf_fname)
# Parse valid exon lines from the GTF file into a dict by transcript_id
for line in gtf_file:
line = line.strip()
if not line or line.startswith('#'):
continue
if '#' in line:
line = line.split('#')[0].strip()
try:
chrom, source, feature, left, right, score, \
strand, frame, values = line.split('\t')
except ValueError:
continue
left, right = int(left), int(right)
if feature != 'exon' or left >= right:
continue
values_dict = {}
for attr in values.split(';')[:-1]:
attr, _, val = attr.strip().partition(' ')
values_dict[attr] = val.strip('"')
if 'gene_id' not in values_dict or \
'transcript_id' not in values_dict:
continue
transcript_id = values_dict['transcript_id']
if transcript_id not in trans:
trans[transcript_id] = [chrom, strand, [[left, right]]]
else:
trans[transcript_id][2].append([left, right])
gtf_file.close()
# Sort exons and merge where separating introns are <=5 bps
for tran, [chrom, strand, exons] in trans.items():
exons.sort()
tmp_exons = [exons[0]]
for i in range(1, len(exons)):
if exons[i][0] - tmp_exons[-1][1] <= 5:
tmp_exons[-1][1] = exons[i][1]
else:
tmp_exons.append(exons[i])
trans[tran] = [chrom, strand, tmp_exons]
# Calculate and print the unique junctions
junctions = set()
for chrom, strand, exons in trans.values():
for i in range(1, len(exons)):
junctions.add(to_junction_str([chrom, exons[i-1][1], exons[i][0]]))
return junctions
cigar_re = re.compile('\d+\w')
def to_junction_str(junction):
return "%s-%d-%d" % (junction[0], junction[1], junction[2])
def to_junction(junction_str):
fields = junction_str.split("-")
if len(fields) > 3:
chr, left, right = "-".join(fields[:-2]), fields[-2], fields[-1]
else:
assert len(fields) == 3
chr, left, right = fields
return [chr, int(left), int(right)]
"""
"""
def junction_cmp(a, b):
if a[0] != b[0]:
if a[0] < b[0]:
return -1
else:
return 1
if a[1] != b[1]:
if a[1] < b[1]:
return -1
else:
return 1
if a[2] != b[2]:
if a[2] < b[2]:
return -1
else:
return 1
return 0
"""
# chr and pos are assumed to be integers
"""
def get_junctions(chr, pos, cigar_str, min_anchor_len = 0, read_len = 100):
junctions = []
right_pos = pos
cigars = cigar_re.findall(cigar_str)
cigars = [[int(cigars[i][:-1]), cigars[i][-1]] for i in range(len(cigars))]
left_anchor_lens = []
cur_left_anchor_len = 0
for i in range(len(cigars)):
length, cigar_op = cigars[i]
if cigar_op in "MI":
cur_left_anchor_len += length
elif cigar_op == "N":
assert cur_left_anchor_len > 0
left_anchor_lens.append(cur_left_anchor_len)
cur_left_anchor_len = 0
for i in range(len(cigars)):
length, cigar_op = cigars[i]
if cigar_op == "N":
left, right = right_pos - 1, right_pos + length
if i > 0 and cigars[i-1][1] in "ID":
if cigars[i-1][1] == "I":
left += cigars[i-1][0]
else:
left -= cigars[i-1][0]
if i + 1 < len(cigars) and cigars[i+1][1] in "ID":
if cigars[i+1][1] == "I":
right -= cigars[i+1][0]
else:
right += cigars[i+1][0]
junction_idx = len(junctions)
assert junction_idx < len(left_anchor_lens)
left_anchor_len = left_anchor_lens[junction_idx]
assert left_anchor_len > 0 and left_anchor_len < read_len
right_anchor_len = read_len - left_anchor_len
if left_anchor_len >= min_anchor_len and right_anchor_len >= min_anchor_len:
junctions.append([chr, left, right])
if cigar_op in "MND":
right_pos += length
return junctions
def get_right(pos, cigars):
right_pos = pos
cigars = cigar_re.findall(cigars)
for cigar in cigars:
length = int(cigar[:-1])
cigar_op = cigar[-1]
if cigar_op in "MDN":
right_pos += length
return right_pos
def get_cigar_chars(cigars):
cigars = cigar_re.findall(cigars)
cigar_chars = ""
for cigar in cigars:
cigar_op = cigar[-1]
cigar_chars += cigar_op
return cigar_chars
"""
"""
def get_cigar_chars_MN(cigars):
cigars = cigar_re.findall(cigars)
cigar_chars = ""
for cigar in cigars:
cigar_op = cigar[-1]
if cigar_op in "MN":
if cigar_chars == "" or cigar_chars[-1] != cigar_op:
cigar_chars += cigar_op
return cigar_chars
"""
"""
def is_small_anchor_junction_read(cigars):
cigar_list = []
for cigar in cigar_re.findall(cigars):
cigar_op = cigar[-1]
cigar_len = int(cigar[:-1])
cigar_list.append([cigar_op, cigar_len])
if len(cigar_list) < 3:
return False
if cigar_list[0][0] != 'M' or cigar_list[-1][0] != 'M':
return False
if cigar_list[0][1] > 10 and cigar_list[-1][1] > 10:
return False
if cigar_list[1][0] != 'N' or cigar_list[-2][0] != 'N':
return False
return True
"""
"""
def is_canonical_junction(chr_dic, junction):
chr, left, right = junction
donor = chr_dic[chr][left:left+2]
acceptor = chr_dic[chr][right-3:right-1]
rev_donor = reverse_complement(acceptor)
rev_acceptor = reverse_complement(donor)
if (donor == "GT" and acceptor == "AG") or \
(rev_donor == "GT" and rev_acceptor == "AG"):
return True
return False
"""
"""
def is_small_exon_junction_read(cigars, min_exon_len = 23):
cigars = cigar_re.findall(cigars)
for i in range(1, len(cigars) - 1):
cigar = cigars[i]
cigar_op = cigar[-1]
cigar_len = int(cigar[:-1])
prev_op = cigars[i-1][-1]
next_op = cigars[i+1][-1]
if prev_op == 'N' and cigar_op == 'M' and next_op == 'N':
if cigar_len <= min_exon_len:
return True
return False
"""
"""
def extract_single(infilename, outfilename, chr_dic, aligner, version, debug_dic):
infile = open(infilename)
outfile = open(outfilename, "w")
prev_read_id = ""
num_reads, num_aligned_reads, num_ualigned_reads = 0, 0, 0
if aligner == "hisat2":
prev_NH, NH_real = 0, 0
for line in infile:
if line[0] == '@':
continue
cols = line[:-1].split()
read_id, flag, chr, pos, mapQ, cigar_str = cols[:6]
read_seq = cols[9]
if len(read_id) >= 3 and read_id[-2] == "/":
read_id = read_id[:-2]
if read_id.find("seq.") == 0:
read_id = read_id[4:]
if aligner == "gsnap":
chr = chr.replace("_", ":")
if read_id != prev_read_id:
num_reads += 1
flag, pos, mapQ = int(flag), int(pos), int(mapQ)
if flag & 0x4 != 0:
prev_read_id = read_id
continue
NH = ""
NM = ""
for i in range(11, len(cols)):
col = cols[i]
# "nM" from STAR
if col.startswith("NM") or col.startswith("nM"):
NM = col
elif col.startswith("NH"):
NH = col
assert NM != ""
NM = int(NM[5:])
if NH != "":
NH = int(NH[5:])
if aligner == "hisat2":
if prev_read_id == read_id:
assert prev_NH == NH
if NH == 1 or mapQ == 60:
assert NH == 1 and mapQ == 60
if read_id != prev_read_id:
num_aligned_reads += 1
if aligner == "hisat2" and \
NH == 1:
num_ualigned_reads += 1
read_pos, right_pos = 0, pos - 1
cigars = cigar_re.findall(cigar_str)
cigars = [[cigar[-1], int(cigar[:-1])] for cigar in cigars]
for i in range(len(cigars)):
cigar_op, length = cigars[i]
if cigar_op == "S":
assert i == 0 or i == len(cigars) - 1
if i == 0:
assert cigars[i+1][0] == "M"
ref_seq = chr_dic[chr][right_pos-length:right_pos]
else:
assert cigars[i-1][0] == "M"
ref_seq = chr_dic[chr][right_pos:right_pos+length]
ref_seq = ref_seq.upper()
if length == len(ref_seq):
for j in range(length):
if ref_seq[j] != "N" and read_seq[read_pos+j] != ref_seq[j]:
NM += 1
else:
NM += length
if cigar_op in "MND":
right_pos += length
if cigar_op in "MIS":
read_pos += length
if cigars[0][0] == "S":
assert cigars[1][0] == "M"
pos -= cigars[0][1]
cigars[1][1] += cigars[0][1]
cigars = cigars[1:]
if cigars[-1][0] == "S":
assert cigars[-2][0] == "M"
cigars[-2][1] += cigars[-1][1]
cigars = cigars[:-1]
cigar_str = ""
for cigar in cigars:
cigar_op, length = cigar
cigar_str += ("%d%s" % (length, cigar_op))
p_str = "%s\t%s\t%d\t%s\tNM:i:%d" % \
(read_id, chr, pos, cigar_str, NM)
print >> outfile, p_str
if aligner == "hisat2":
if prev_read_id != read_id:
if prev_read_id != "":
assert prev_NH == NH_real
NH_real = 1
else:
NH_real += 1
prev_NH = NH
prev_read_id = read_id
if aligner == "hisat2":
if prev_read_id != "":
assert prev_NH == NH_real
outfile.close()
infile.close()
# Sanity check for HISAT2's alignment summary
if aligner == "hisat2" and os.path.exists(infilename + ".summary"):
hisat2_reads, hisat2_0aligned_reads, hisat2_ualigned_reads, hisat2_maligned_reads = 0, 0, 0, 0
for line in open(infilename + ".summary"):
line = line.strip()
if line.startswith("HISAT2 summary") or \
line.startswith("Overall"):
continue
category, num = line.split(':')
num = num.strip()
num = int(num.split(' ')[0])
if category.startswith("Total reads"):
hisat2_reads = num
elif category.startswith("Aligned 0 time"):
hisat2_0aligned_reads = num
elif category.startswith("Aligned 1 time"):
hisat2_ualigned_reads = num
else:
assert category.startswith("Aligned >1 time")
assert hisat2_reads == hisat2_0aligned_reads + hisat2_ualigned_reads + num
hisat2_aligned_reads = hisat2_reads - hisat2_0aligned_reads
assert hisat2_reads == num_reads
assert hisat2_aligned_reads == num_aligned_reads
assert hisat2_ualigned_reads == num_ualigned_reads
"""
"""
def extract_pair(infilename, outfilename, chr_dic, aligner, version, debug_dic):
read_dic = {}
pair_reported = set()
infile = open(infilename)
outfile = open(outfilename, "w")
num_pairs, num_conc_aligned_pairs, num_conc_ualigned_pairs, num_disc_aligned_pairs = 0, 0, 0, 0
num_aligned_reads, num_ualigned_reads = 0, 0
prev_read_id, pair_list = "", set()
if aligner == "hisat2":
prev_NH1, prev_NH2 = 0, 0
NH1_real, NH2_real = 0, 0
for line in infile:
if line[0] == '@':
continue
cols = line[:-1].split()
read_id, flag, chr1, pos1, mapQ, cigar1_str, chr2, pos2 = cols[:8]
read_seq = cols[9]
if len(read_id) >= 3 and read_id[-2] == "/":
read_id = read_id[:-2]
if read_id.find("seq.") == 0:
read_id = read_id[4:]
if aligner == "gsnap":
chr1 = chr1.replace("_", ":")
chr2 = chr2.replace("_", ":")
if read_id != prev_read_id:
num_pairs += 1
pair_list = set()
flag = int(flag)
canonical_pos1, canonical_pos2 = int(pos1), int(pos2)
left_read = (flag & 0x40 != 0)
pos1 = canonical_pos1
mapQ = int(mapQ)
if flag & 0x4 != 0:
prev_read_id, is_prev_read_left = read_id, left_read
continue
concordant = (flag & 0x2 != 0)
NH, NM1, YT = "", "", ""
for i in range(11, len(cols)):
col = cols[i]
# "nM" from STAR
if col.startswith("NM") or col.startswith("nM"):
NM1 = col
elif col.startswith("NH"):
NH = col
elif col.startswith("YT"):
YT = col[5:]
assert NM1 != ""
NM1 = int(NM1[5:])
assert NH != ""
NH = int(NH[5:])
if aligner == "hisat2":
if prev_read_id == read_id:
if left_read:
assert prev_NH1 == 0 or prev_NH1 == NH
else:
assert prev_NH2 == 0 or prev_NH2 == NH
if NH == 1 or mapQ == 60:
assert NH == 1 and mapQ == 60
unpaired = (flag & 0x8 != 0) or (YT in ["UU", "UP"])
if unpaired:
if left_read not in pair_list:
pair_list.add(left_read)
num_aligned_reads += 1
if aligner == "hisat2" and NH == 1:
num_ualigned_reads += 1
assert mapQ == 60
else:
if read_id != prev_read_id:
if concordant:
num_conc_aligned_pairs += 1
if aligner == "hisat2" and NH == 1:
num_conc_ualigned_pairs += 1
else:
if aligner == "hisat2":
assert YT == "DP"
num_disc_aligned_pairs += 1
read_pos, right_pos = 0, pos1 - 1
cigars = cigar_re.findall(cigar1_str)
cigars = [[cigar[-1], int(cigar[:-1])] for cigar in cigars]
for i in range(len(cigars)):
cigar_op, length = cigars[i]
if cigar_op == "S":
assert i == 0 or i == len(cigars) - 1
if i == 0:
assert cigars[i+1][0] == "M"
ref_seq = chr_dic[chr1][right_pos-length:right_pos]
else:
assert cigars[i-1][0] == "M"
ref_seq = chr_dic[chr1][right_pos:right_pos+length]
ref_seq = ref_seq.upper()
if length == len(ref_seq):
for j in range(length):
if ref_seq[j] != "N" and read_seq[read_pos+j] != ref_seq[j]:
NM1 += 1
else:
NM1 += length
if cigar_op in "MND":
right_pos += length
if cigar_op in "MIS":
read_pos += length
if cigars[0][0] == "S":
assert cigars[1][0] == "M"
pos1 -= cigars[0][1]
cigars[1][1] += cigars[0][1]
cigars = cigars[1:]
if cigars[-1][0] == "S":
assert cigars[-2][0] == "M"
cigars[-2][1] += cigars[-1][1]
cigars = cigars[:-1]
cigar1_str = ""
for cigar in cigars:
cigar_op, length = cigar
cigar1_str += ("%d%s" % (length, cigar_op))
if chr2 == '*':
continue
if chr2 == '=':
chr2 = chr1
me = "%s\t%s\t%d" % (read_id, chr1, canonical_pos1)
partner = "%s\t%s\t%d" % (read_id, chr2, canonical_pos2)
if partner in read_dic:
maps = read_dic[partner]
for map in maps:
if map[0] == me:
cigar2_str, NM2, pos2 = map[1:4]
if int(pos2) > int(pos1):
p_str = "%s\t%s\t%d\t%s\t%s\t%d\t%s\tNM:i:%d\tNM:i:%d" % \
(read_id, chr1, pos1, cigar1_str, chr2, pos2, cigar2_str, NM1, NM2)
else:
p_str = "%s\t%s\t%d\t%s\t%s\t%d\t%s\tNM:i:%d\tNM:i:%d" % \
(read_id, chr2, pos2, cigar2_str, chr1, pos1, cigar1_str, NM2, NM1)
if p_str not in pair_reported:
pair_reported.add(p_str)
print >> outfile, p_str
if not me in read_dic:
read_dic[me] = []
read_dic[me].append([partner, cigar1_str, NM1, pos1])
if aligner == "hisat2":
if prev_read_id != read_id:
if prev_read_id != "":
assert prev_NH1 == NH1_real
assert prev_NH2 == NH2_real
prev_NH1, prev_NH2 = 0, 0
if left_read:
NH1_real, NH2_real = 1, 0
else:
NH1_real, NH2_real = 0, 1
else:
if left_read:
NH1_real += 1
else:
NH2_real += 1
if left_read:
prev_NH1 = NH
else:
prev_NH2 = NH
prev_read_id = read_id
if aligner == "hisat2":
if prev_read_id != "":
assert prev_NH1 == NH1_real
assert prev_NH2 == NH2_real
outfile.close()
infile.close()
# Sanity check for HISAT2's alignment summary
if aligner == "hisat2" and os.path.exists(infilename + ".summary"):
hisat2_pairs, hisat2_0aligned_pairs, hisat2_conc_ualigned_pairs, hisat2_conc_maligned_pairs, hisat2_disc_aligned_pairs = 0, 0, 0, 0, 0
hisat2_reads, hisat2_0aligned_reads, hisat2_ualigned_reads, hisat2_maligned_reads = 0, 0, 0, 0
for line in open(infilename + ".summary"):
line = line.strip()
if line.startswith("HISAT2 summary") or \
line.startswith("Overall"):
continue
category, num = line.split(':')
num = num.strip()
num = int(num.split(' ')[0])
if category.startswith("Total pairs"):
hisat2_pairs = num
elif category.startswith("Aligned concordantly or discordantly 0 time"):
hisat2_0aligned_pairs = num
elif category.startswith("Aligned concordantly 1 time"):
hisat2_conc_ualigned_pairs = num
elif category.startswith("Aligned concordantly >1 time"):
hisat2_conc_maligned_pairs = num
elif category.startswith("Aligned discordantly"):
hisat2_disc_aligned_pairs = num
assert hisat2_pairs == hisat2_0aligned_pairs + hisat2_conc_ualigned_pairs + hisat2_conc_maligned_pairs + hisat2_disc_aligned_pairs
elif category.startswith("Total unpaired reads"):
hisat2_reads = num
assert hisat2_reads == hisat2_0aligned_pairs * 2
elif category.startswith("Aligned 0 time"):
hisat2_0aligned_reads = num
elif category.startswith("Aligned 1 time"):
hisat2_ualigned_reads = num
else:
assert category.startswith("Aligned >1 times")
hisat2_maligned_reads = num
assert hisat2_reads == hisat2_0aligned_reads + hisat2_ualigned_reads + hisat2_maligned_reads
assert hisat2_pairs == num_pairs
assert hisat2_conc_ualigned_pairs == num_conc_ualigned_pairs
assert hisat2_conc_maligned_pairs == num_conc_aligned_pairs - num_conc_ualigned_pairs
assert hisat2_disc_aligned_pairs == num_disc_aligned_pairs
assert hisat2_ualigned_reads == num_ualigned_reads
assert hisat2_maligned_reads == num_aligned_reads - num_ualigned_reads
"""
"""
def is_junction_read(junctions_dic, chr, pos, cigar_str):
result_junctions = []
junctions = get_junctions(chr, pos, cigar_str)
for junction in junctions:
junction_str = to_junction_str(junction)
result_junctions.append([junction_str, junction_str in junctions_dic])
return result_junctions
"""
"""
def is_junction_pair(junctions_dic, chr, pos, cigar_str, mate_chr, mate_pos, mate_cigar_str):
junctions = is_junction_read(junctions_dic, chr, pos, cigar_str)
mate_junctions = is_junction_read(junctions_dic, mate_chr, mate_pos, mate_cigar_str)
junctions += mate_junctions
return junctions
"""
"""
def find_in_gtf_junctions(chr_dic, gtf_junctions, junction, relax_dist = 5):
def find_in_gtf_junctions(gtf_junctions, junction):
l, u = 0, len(gtf_junctions)
while l < u:
m = (l + u) / 2
assert m >= 0 and m < len(gtf_junctions)
cmp_result = junction_cmp(junction, gtf_junctions[m])
if cmp_result == 0:
return m
elif cmp_result < 0:
u = m
else:
l = m + 1
return l
chr, left, right = junction
gtf_index = find_in_gtf_junctions(gtf_junctions, [chr, left - relax_dist, right - relax_dist])
if gtf_index >= 0:
i = gtf_index
while i < len(gtf_junctions):
chr2, left2, right2 = gtf_junctions[i]
if chr2 > chr or \
left2 - left > relax_dist or \
right2 - right > relax_dist:
break
if abs(left - left2) <= relax_dist and left - left2 == right - right2:
test_small = ":" in chr
if is_canonical_junction(chr_dic, gtf_junctions[i]):
if left == left2:
return i
else:
return -1
else:
return i
i += 1
return -1
"""
"""
def compare_single_sam(RNA, reference_sam, query_sam, mapped_fname, chr_dic, gtf_junctions, gtf_junctions_set, ex_gtf_junctions):
aligned, multi_aligned = 0, 0
db_dic, db_junction_dic = {}, {}
mapped_file = open(mapped_fname, "w")
file = open(reference_sam, "r")
junction_read_dic = {}
for line in file:
if line[0] == '@':
continue
read_name, chr, pos, cigar, NM = line[:-1].split()
pos = int(pos)
if read_name.find("seq.") == 0:
read_name = read_name[4:]
if len(read_name) > 2 and read_name[-2] == '/':
read_name = read_name[:-2]
multi_aligned += 1
if read_name not in db_dic:
db_dic[read_name] = []
aligned += 1
pos2 = get_right(pos, cigar)
db_dic[read_name].append([chr, pos, pos2, cigar])
read_junctions = is_junction_read(gtf_junctions_set, chr, pos, cigar)
if len(read_junctions) > 0:
if read_name not in db_junction_dic:
db_junction_dic[read_name] = []
for junction_str, is_gtf_junction in read_junctions:
db_junction_dic[read_name].append([junction_str, is_gtf_junction])
if junction_str not in junction_read_dic:
junction_read_dic[junction_str] = []
junction_read_dic[junction_str].append(line[:-1])
file.close()
temp_junctions, temp_gtf_junctions = set(), set()
for read_name, can_junctions in db_junction_dic.items():
if len(can_junctions) <= 0:
continue
# daehwan - for debugging purposes
# 1. select the best candidate among spliced alignments if multiple
def pickup_junction(can_junctions):
junctions = [can_junctions[0]]
for i in range(1, len(can_junctions)):
def get_intron_len(can_junction):
chr, left, right = to_junction(can_junction)
return right - left - 1
intron, intron_cmp = get_intron_len(junctions[0][0]), get_intron_len(can_junctions[i][0])
if intron > intron_cmp:
junctions = [can_junctions[i]]
elif intron == intron_cmp:
junctions.append(can_junctions[i])
return junctions
# can_junctions = pickup_junction(can_junctions)
for can_junction in can_junctions:
found_junction_str = None
junction_str, is_gtf_junction = can_junction
if is_gtf_junction:
found_junction_str = junction_str
if not found_junction_str:
junction = to_junction(junction_str)
gtf_index = find_in_gtf_junctions(chr_dic, gtf_junctions, junction)
if gtf_index >= 0:
is_gtf_junction = True
found_junction_str = to_junction_str(gtf_junctions[gtf_index])
if found_junction_str:
temp_gtf_junctions.add(found_junction_str)
temp_junctions.add(found_junction_str)
else:
if junction_str not in temp_junctions:
None
# assert junction_str in junction_read_dic
# daehwan - for debugging purposes
"""
if len(junction_read_dic[junction_str]) <= 2:
canonical = is_canonical_junction(chr_dic, to_junction(junction_str))
if not canonical:
print >> sys.stdout, read_name, junction_str, len(junction_read_dic[junction_str]), can_junctions
for line in junction_read_dic[junction_str]:
print >> sys.stdout, "\t", line
"""
temp_junctions.add(junction_str)
temp2_junctions = []
for junction in temp_junctions:
temp2_junctions.append(to_junction(junction))
temp_junctions = sorted(list(temp2_junctions), cmp=junction_cmp)
temp2_junctions = []
for can_junction in temp_junctions:
if len(temp2_junctions) <= 0:
temp2_junctions.append(can_junction)
else:
chr, left, right = temp2_junctions[-1]
chr2, left2, right2 = can_junction
if chr == chr2 and \
abs(left - left2) == abs(right - right2) and \
abs(left - left2) <= 10 and \
not to_junction_str(can_junction) in temp_gtf_junctions:
continue
temp2_junctions.append(can_junction)
temp_junctions = set()
for junction in temp2_junctions:
temp_junctions.add(to_junction_str(junction))
file = open(query_sam)
mapped, unmapped, unique_mapped, mapping_point = 0, 0, 0, 0.0
for line in file:
if line[0] == '@':
continue
if RNA:
read_name, chr, pos, cigar, trans_id, NM = line[:-1].split()
else:
read_name, chr, pos, cigar, NM = line[:-1].split()
pos = int(pos)
pos2 = get_right(pos, cigar)
if read_name not in db_dic:
unmapped += 1
continue
maps = db_dic[read_name]
found = False
if [chr, pos, pos2, cigar] in maps:
found = True
if not found:
for map in maps:
if chr == map[0] and \
pos == map[1] and \
pos2 == map[2] and \
get_cigar_chars(cigar) == get_cigar_chars(map[3]):
read_junctions = is_junction_read(gtf_junctions_set, map[0], map[1], map[3])
if True:
found_list = [False for i in range(len(read_junctions))]
for j in range(len(read_junctions)):
junction_str, is_gtf_junction = read_junctions[j]
junction = to_junction(junction_str)
gtf_index = find_in_gtf_junctions(chr_dic, gtf_junctions, junction)
if gtf_index >= 0:
found_list[j] = True
found = not (False in found_list)
else:
found = False
break
if found:
print >> mapped_file, read_name
mapped += 1
if len(maps) == 1:
unique_mapped += 1
mapping_point += (1.0 / len(maps))
else:
unmapped += 1
file.close()
mapped_file.close()
# daehwan - for debugging purposes
false_can_junctions, false_noncan_junctions = 0, 0
for junction_str in temp_junctions:
if junction_str in temp_gtf_junctions:
continue
if junction_str in ex_gtf_junctions:
continue
if is_canonical_junction(chr_dic, to_junction(junction_str)):
false_can_junctions += 1
else:
false_noncan_junctions += 1
print >> sys.stderr, "\t\t\tfalse junctions: %d (canonical), %d (non-canonical)" % (false_can_junctions, false_noncan_junctions)
return mapped, unique_mapped, unmapped, aligned, multi_aligned, len(temp_junctions), len(temp_gtf_junctions), mapping_point
"""
"""
def compare_paired_sam(RNA, reference_sam, query_sam, mapped_fname, chr_dic, gtf_junctions, gtf_junctions_set, ex_gtf_junctions):
aligned, multi_aligned = 0, 0
db_dic, db_junction_dic, junction_pair_dic = {}, {}, {}
mapped_file = open(mapped_fname, "w")
file = open(reference_sam, "r")
for line in file:
if line[0] == '@':
continue
read_name, chr, pos, cigar, chr2, pos2, cigar2, NM, NM2 = line[:-1].split()
pos, pos2 = int(pos), int(pos2)
if read_name.find("seq.") == 0:
read_name = read_name[4:]
if len(read_name) > 2 and read_name[-2] == '/':
read_name = read_name[:-2]
multi_aligned += 1
if read_name not in db_dic:
db_dic[read_name] = []
aligned += 1
pos_right, pos2_right = get_right(pos, cigar), get_right(pos2, cigar2)
db_dic[read_name].append([chr, pos, pos_right, cigar, pos2, pos2_right, cigar2])
pair_junctions = is_junction_pair(gtf_junctions_set, chr, pos, cigar, chr2, pos2, cigar2)
if len(pair_junctions) > 0:
if read_name not in db_junction_dic:
db_junction_dic[read_name] = []
for junction_str, is_gtf_junction in pair_junctions:
db_junction_dic[read_name].append([junction_str, is_gtf_junction])
# daehwan - for debugging purposes
if junction_str not in junction_pair_dic:
junction_pair_dic[junction_str] = []
junction_pair_dic[junction_str].append(line[:-1])
file.close()
temp_junctions, temp_gtf_junctions = set(), set()
for read_name, can_junctions in db_junction_dic.items():
if len(can_junctions) <= 0:
continue
# daehwan - for debugging purposes
# 1. select the best candidate among spliced alignments if multiple
def pickup_junction(can_junctions):
junctions = [can_junctions[0]]
for i in range(1, len(can_junctions)):