-
Notifications
You must be signed in to change notification settings - Fork 26
/
tama_collapse.py
6407 lines (4677 loc) · 260 KB
/
tama_collapse.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 re
import sys
import time
from Bio import SeqIO
from StringIO import StringIO
from Bio import AlignIO
import os
import argparse
from __init__ import __version__
"""
Transcriptome Annotation by Modular Algorithms (TAMA)
TAMA Collapse
Author: Richard I. Kuo
This script collapses transcripts and groups transcripts into genes for long reads mapped onto a genome assembly.
"""
tc_version = 'tc0.2'
tc_date = 'tc_version_date_2023_03_28'
### Notes on changes
# Fixed issue with coordinates of soft clipped variants in the variant output file.
#####################################################################
#####################################################################
ap = argparse.ArgumentParser(description='This script collapses mapped transcript models')
ap.add_argument('-s', type=str, nargs=1, help='Sorted sam file (required)')
ap.add_argument('-f', type=str, nargs=1, help='Genome fasta file (required)')
ap.add_argument('-p', type=str, nargs=1, help='Output prefix (required)')
ap.add_argument('-x', type=str, nargs=1, help='Capped flag: capped or no_cap')
ap.add_argument('-e', type=str, nargs=1, help='Collapse exon ends flag: common_ends or longest_ends (default common_ends)')
ap.add_argument('-c', type=str, nargs=1, help='Coverage (default 99)')
ap.add_argument('-i', type=str, nargs=1, help='Identity (default 85)')
ap.add_argument('-icm', type=str, nargs=1, help='Identity calculation method (default ident_cov for including coverage) (alternate is ident_map for excluding hard and soft clipping)')
ap.add_argument('-a', type=str, nargs=1, help='5 prime threshold (default 10)')
ap.add_argument('-m', type=str, nargs=1, help='Exon/Splice junction threshold (default 10)')
ap.add_argument('-z', type=str, nargs=1, help='3 prime threshold (default 10)')
ap.add_argument('-d', type=str, nargs=1, help='Flag for merging duplicate transcript groups (default is merge_dup will merge duplicates ,no_merge quits when duplicates are found)')
ap.add_argument('-sj', type=str, nargs=1, help='Use error threshold to prioritize the use of splice junction information from collapsing transcripts(default no_priority, activate with sj_priority)')
ap.add_argument('-sjt', type=str, nargs=1, help='Threshold for detecting errors near splice junctions (default is 10bp)')
ap.add_argument('-lde', type=str, nargs=1, help='Threshold for amount of local density error near splice junctions that is allowed (default is 1000 errors which practically means no threshold is applied)')
ap.add_argument('-ses', type=str, nargs=1, help='Simple error symbol. Use this to pick the symbol used to represent matches in the simple error string for LDE output.')
ap.add_argument('-b', type=str, nargs=1, help='Use BAM instead of SAM')
ap.add_argument('-log', type=str, nargs=1, help='Turns off log output to screen of collapsing process. (default on, use log_off to turn off)')
ap.add_argument('-v', type=str, nargs=1, help='Prints out version date and exits.')
ap.add_argument('-rm', type=str, nargs=1, help='Run mode allows you to use original or low_mem mode, default is original')
ap.add_argument('-vc', type=str, nargs=1, help='Variation covwerage threshold: Default 5 reads')
opts = ap.parse_args()
#check for version request
if not opts.v:
print(tc_date)
else:
print(tc_date)
print("Program did not run")
sys.exit()
#check for missing args
missing_arg_flag = 0
if not opts.s:
print("Sam file is missing")
missing_arg_flag = 1
if not opts.f:
print("Fasta file missing")
missing_arg_flag = 1
if not opts.p:
print("Output prefix name missing")
missing_arg_flag = 1
if not opts.x:
print("Default capped flag will be used: Capped")
fiveprime_cap_flag = "capped"
else:
fiveprime_cap_flag = opts.x[0]
if fiveprime_cap_flag != "no_cap" and fiveprime_cap_flag != "capped":
print("Error with cap flag. Should be capped or no_cap.")
sys.exit()
if not opts.e:
print("Default collapse exon ends flag will be used: common_ends")
collapse_flag = "common_ends"
else:
collapse_flag = opts.e[0]
if not opts.c:
print("Default coverage: 99")
coverage_threshold = 99.0
else:
coverage_threshold = float(opts.c[0])
if not opts.i:
print("Default identity: 85")
identity_threshold = 85.0
else:
identity_threshold = float(opts.i[0])
if not opts.icm:
print("Default identity calculation method: ident_cov")
ident_calc_method = 'ident_cov'
else:
ident_calc_method = str(opts.icm[0])
if ident_calc_method != "ident_cov" and ident_calc_method != "ident_map":
print("Error with -icm input. Should be ident_cov or ident_map. Run terminated.")
print(ident_calc_method)
sys.exit()
if not opts.a:
print("Default 5 prime threshold: 10")
fiveprime_threshold = 10
else:
fiveprime_threshold = int(opts.a[0])
if not opts.m:
print("Default exon/splice junction threshold: 10")
exon_diff_threshold = 10
else:
exon_diff_threshold = int(opts.m[0])
if not opts.z:
print("Default 3 prime threshold: 10")
threeprime_threshold = 10
else:
threeprime_threshold = int(opts.z[0])
if not opts.d:
print("Default duplicate merge flag: merge_dup")
duplicate_flag = "merge_dup"
else:
duplicate_flag = str(opts.d[0])
if not opts.sj:
print("Default splice junction priority: no_priority")
sj_priority_flag = "no_priority"
else:
sj_priority_flag = str(opts.sj[0])
if not opts.sjt:
print("Default splice junction error threshold: 10")
sj_err_threshold = 10
else:
sj_err_threshold = int(opts.sjt[0])
if not opts.lde:
print("Default splice junction local density error threshold: 1000")
lde_threshold = 1000
else:
lde_threshold = int(opts.lde[0])
if not opts.ses:
print("Default simple error symbol for matches is the underscore \"_\" .")
ses_match_char = "_"
else:
ses_match_char = int(opts.ses[0])
if not opts.b:
print("Using SAM format for reading in.")
bam_flag = "SAM"
else:
print("Using BAM format for reading in.")
import pysam
bam_flag = str(opts.b[0])
if not opts.log:
print("Default log output on")
log_flag = "log_on"
else:
log_flag = str(opts.log[0])
if log_flag != "log_off":
print("Please use log_off to turn off log prints to screen")
sys.exit()
if not opts.rm:
print("Default run mode original")
run_mode_flag = "original"
else:
run_mode_flag = str(opts.rm[0])
if run_mode_flag != "original" and run_mode_flag != "low_mem" :
print("Please use original or low_mem for -rm setting")
sys.exit()
if not opts.vc:
print("Default 5 read threshold")
var_support_threshold = 5
else:
var_support_threshold = int(opts.vc[0])
if missing_arg_flag == 1:
print("Please try again with complete arguments")
sam_file = opts.s[0]
fasta_file_name = opts.f[0]
outfile_prefix = opts.p[0]
input_sambam_flag = "na"
if sam_file.endswith("bam"):
input_sambam_flag = "BAM"
if bam_flag == "SAM":
print("You designated SAM input but are supplying BAM. Please use the same format for input as specified.")
sys.exit()
if sam_file.endswith("sam"):
input_sambam_flag = "SAM"
if bam_flag == "BAM":
print("You designated BAM input but are supplying SAM. Please use the same format for input as specified.")
sys.exit()
if input_sambam_flag == "na":
print("Input SAM/BAM file not recoginized from extension format designation.")
#####################################################################
#####################################################################
start_time = time.time()
prev_time = start_time
#print("opening sam file")
#sam_file = sys.argv[1]
#sam_file_contents = open(sam_file).read().rstrip("\n").split("\n")
#print("opening fasta file")
#fasta_file_name = sys.argv[2]
#outfile_prefix = sys.argv[3]
#fiveprime_cap_flag = "capped"
#collapse_flag = "common_ends"
#default threshold, will add option to change via arguments
#coverage_threshold = 99.0
#identity_threshold = 85.0
#default poly A threshold
a_window = 20
a_perc_thresh = 70.0
no_mismatch_flag = "0" # use this for showing no mismatch near splice junction
# see calc_error_rate and sj_error_priority_start and sj_error_priority_end
bed_outfile_name = outfile_prefix + ".bed"
outfile_bed = open(bed_outfile_name,"w")
cluster_outfile_name = outfile_prefix + "_read.txt"
outfile_cluster = open(cluster_outfile_name,"w")
cluster_line = "\t".join(["read_id","mapped_flag","accept_flag","percent_coverage","percent_identity","error_line<h;s;i;d;m>", "length", "cigar"])
outfile_cluster.write(cluster_line)
outfile_cluster.write("\n")
trans_report_outfile_name = outfile_prefix + "_trans_report.txt"
outfile_trans_report = open(trans_report_outfile_name,"w")
trans_report_line = "\t".join(["transcript_id","num_clusters","high_coverage","low_coverage","high_quality_percent","low_quality_percent","start_wobble_list","end_wobble_list","collapse_sj_start_err","collapse_sj_end_err","collapse_error_nuc"])
#trans_report_line = "\t".join(["transcript_id","num_clusters","high_coverage","low_coverage","high_quality_percent","low_quality_percent","start_wobble_list","end_wobble_list","collapse_sj_start_err","collapse_sj_end_err","collapse_error_nuc","sj_error_simple"])
outfile_trans_report.write(trans_report_line)
outfile_trans_report.write("\n")
trans_clust_outfile_name = outfile_prefix + "_trans_read.bed"
outfile_trans_clust_report = open(trans_clust_outfile_name,"w")
#trans_clust_line = "\t".join(["transcript_id","cluster_id","scaffold","strand","start","end","exon_starts","exon_ends"])
#outfile_trans_clust_report.write(trans_clust_line)
#outfile_trans_clust_report.write("\n")
if run_mode_flag == "original":
variant_outfile_name = outfile_prefix + "_variants.txt"
outfile_variant = open(variant_outfile_name,"w")
variant_file_line = "\t".join(["scaffold","position","type","ref_allele","alt_allele","count","cov_count","cluster_list"])
outfile_variant.write(variant_file_line)
outfile_variant.write("\n")
varcov_outfile_name = outfile_prefix + "_varcov.txt"
outfile_varcov = open(varcov_outfile_name,"w")
varcov_file_line = "\t".join(["positions","overlap_clusters"])
outfile_varcov.write(varcov_file_line)
outfile_varcov.write("\n")
polya_outfile_name = outfile_prefix + "_polya.txt"
outfile_polya = open(polya_outfile_name,"w")
polya_file_line = "\t".join(["cluster_id","trans_id","strand","a_percent","a_count","sequence"])
outfile_polya.write(polya_file_line)
outfile_polya.write("\n")
#rtswitch_outfile_name = outfile_prefix + "_rtswitch.txt"
#outfile_rtswitch = open(rtswitch_outfile_name,"w")
#rtswitch_file_line = "\t".join(["trans_id","junct_num","first_seq","second_seq","rev_comp_first_seq"])
#outfile_rtswitch.write(rtswitch_file_line)
#outfile_rtswitch.write("\n")
strand_outfile_name = outfile_prefix + "_strand_check.txt"
outfile_strand = open(strand_outfile_name,"w")
strand_file_line = "\t".join(["read_id","scaff_name","start_pos","cigar","strands"])
outfile_strand.write(strand_file_line)
outfile_strand.write("\n")
lde_outfile_name = outfile_prefix + "_local_density_error.txt"
outfile_lde = open(lde_outfile_name,"w")
lde_file_line = "\t".join(["cluster_id","lde_flag","scaff_name","start_pos","end_pos","strand","num_exons","bad_sj_num_line","bad_sj_error_count_line","sj_error_profile_idmsh","sj_error_nuc","sj_error_simple","cigar"])
outfile_lde.write(lde_file_line)
outfile_lde.write("\n")
report_outfile_name = outfile_prefix + "_report.txt"
outfile_report = open(report_outfile_name,"w")
variation_dict = {} # variation_dict[scaffold][position][variant type][alt allele][cluster id] = 1
var_coverage_dict = {} # var_coverage_dict[scaffold][position][trans_id] = 1
## sj hash 2020/07/27
sj_hash_read_threshold = 20
check_trans_id = '11_c110717/1/696' #########################################################################debugging
def track_time(start_time,prev_time):
end_time = time.time()
time_taken = int(end_time - prev_time)
tt_hours = time_taken / 60
tt_hours = tt_hours /60
leftover_time = time_taken - (tt_hours * 60 * 60)
tt_minutes = leftover_time / 60
leftover_time = time_taken - (tt_minutes * 60)
tt_seconds = leftover_time
print("time taken since last check:\t" + str(tt_hours) + ":" + str(tt_minutes) + ":" + str(tt_seconds) )
time_total = int(end_time - start_time)
tt_hours = time_total / 60
tt_hours = tt_hours /60
leftover_time = time_total - (tt_hours * 60 * 60)
tt_minutes = leftover_time / 60
leftover_time = time_total - (tt_minutes * 60)
tt_seconds = leftover_time
print("time taken since beginning:\t" + str(tt_hours) + ":" + str(tt_minutes) + ":" + str(tt_seconds) )
this_time = end_time
return this_time
#convert cigar into list of digits and list of characters
def cigar_list(cigar):
# fix issue with X and = used in SAM format from mininmap2
cigar = re.sub('=', 'M', cigar)
cigar = re.sub('X', 'M', cigar)
cig_char = re.sub('\d', ' ', cigar)
cig_char_list = cig_char.split()
cig_digit = re.sub("[a-zA-Z]+", ' ', cigar)
cig_dig_list = cig_digit.split()
return(cig_dig_list,cig_char_list)
####################################################################################################
#get mapped sequence length
def mapped_seq_length(cigar):
[cig_dig_list,cig_char_list] = cigar_list(cigar)
map_seq_length = 0
for i in xrange(len(cig_dig_list)):
cig_flag = cig_char_list[i]
if cig_flag == "H":
continue
elif cig_flag == "S":
continue
elif cig_flag == "M":
map_seq_length = map_seq_length + int(cig_dig_list[i])
continue
elif cig_flag == "I":
continue
elif cig_flag == "D":
map_seq_length = map_seq_length + int(cig_dig_list[i])
continue
elif cig_flag == "N":
continue
return map_seq_length
####################################################################################################
#get the coordinate for the end of the transcript
def trans_coordinates(start_pos,cigar):
[cig_dig_list,cig_char_list] = cigar_list(cigar)
end_pos = int(start_pos)
exon_start_list = []
exon_end_list = []
exon_start_list.append(int(start_pos))
for i in xrange(len(cig_dig_list)):
cig_flag = cig_char_list[i]
if cig_flag == "H":
continue
elif cig_flag == "S":
continue
elif cig_flag == "M":
end_pos = end_pos + int(cig_dig_list[i])
continue
elif cig_flag == "I":
continue
elif cig_flag == "D":
end_pos = end_pos + int(cig_dig_list[i])
continue
elif cig_flag == "N":
#add exon end position to list (must be before updating end pos info)
exon_end_list.append(end_pos)
end_pos = end_pos + int(cig_dig_list[i])
#add exon start
exon_start_list.append(end_pos)
continue
#add last exon end position
exon_end_list.append(end_pos)
return end_pos,exon_start_list,exon_end_list
####################################################################################################
#deal with wildcards
nuc_char_dict = {} # nuc_char_dict[nuc char][nuc single] = 1
nuc_char_dict["A"] = {}
nuc_char_dict["A"]["A"] = 1
nuc_char_dict["T"] = {}
nuc_char_dict["T"]["T"] = 1
nuc_char_dict["C"] = {}
nuc_char_dict["C"]["C"] = 1
nuc_char_dict["G"] = {}
nuc_char_dict["G"]["G"] = 1
nuc_char_dict["S"] = {}
nuc_char_dict["S"]["C"] = 1
nuc_char_dict["S"]["G"] = 1
nuc_char_dict["W"] = {}
nuc_char_dict["W"]["A"] = 1
nuc_char_dict["W"]["T"] = 1
nuc_char_dict["K"] = {}
nuc_char_dict["K"]["A"] = 1
nuc_char_dict["K"]["C"] = 1
nuc_char_dict["M"] = {}
nuc_char_dict["M"]["G"] = 1
nuc_char_dict["M"]["T"] = 1
nuc_char_dict["Y"] = {}
nuc_char_dict["Y"]["A"] = 1
nuc_char_dict["Y"]["G"] = 1
nuc_char_dict["R"] = {}
nuc_char_dict["R"]["C"] = 1
nuc_char_dict["R"]["T"] = 1
nuc_char_dict["V"] = {}
nuc_char_dict["V"]["C"] = 1
nuc_char_dict["V"]["G"] = 1
nuc_char_dict["V"]["T"] = 1
nuc_char_dict["H"] = {}
nuc_char_dict["H"]["A"] = 1
nuc_char_dict["H"]["G"] = 1
nuc_char_dict["H"]["T"] = 1
nuc_char_dict["D"] = {}
nuc_char_dict["D"]["A"] = 1
nuc_char_dict["D"]["C"] = 1
nuc_char_dict["D"]["T"] = 1
nuc_char_dict["B"] = {}
nuc_char_dict["B"]["A"] = 1
nuc_char_dict["B"]["C"] = 1
nuc_char_dict["B"]["G"] = 1
nuc_char_dict["N"] = {}
nuc_char_dict["N"]["A"] = 1
nuc_char_dict["N"]["T"] = 1
nuc_char_dict["N"]["C"] = 1
nuc_char_dict["N"]["G"] = 1
#nuc_char_dict["Z"] = {}
report_gene_count = 0
report_trans_count = 0
report_accepted_reads = 0
report_discarded_reads = 0
#use this to find mismatch between two aligned sequences
def mismatch_seq(genome_seq,query_seq,genome_pos,seq_pos):
if len(genome_seq) != len(query_seq):
print("Genome seq is not the same length as query seq")
print(genome_seq)
print(query_seq)
print(genome_pos)
print(seq_pos)
sys.exit()
genome_mismatch_list = []
seq_mismatch_list = []
nuc_mismatch_list = []
for i in xrange(len(genome_seq)):
genome_nuc = genome_seq[i]
read_nuc = query_seq[i]
read_nuc = read_nuc.upper()
nuc_match_flag = 0
for g_nuc_char in nuc_char_dict[genome_nuc]:
for t_nuc_char in nuc_char_dict[read_nuc]:
if g_nuc_char == t_nuc_char:
nuc_match_flag = 1
#if genome_seq[i] != query_seq[i]: #########################################need to fix this for wildcard situations
if nuc_match_flag == 0:
genome_mismatch_coord = genome_pos + i
seq_mismatch_coord = seq_pos + i
genome_mismatch_list.append(genome_mismatch_coord)
seq_mismatch_list.append(seq_mismatch_coord)
nuc_mismatch_str = query_seq[i] + "." + genome_seq[i]
nuc_mismatch_list.append(nuc_mismatch_str)
return genome_mismatch_list,seq_mismatch_list,nuc_mismatch_list
####################################################################################################
def update_variation_dict(scaffold,var_pos,var_type,var_seq,read_id):
if type(var_seq) is list:
var_seq = "".join(var_seq)
if scaffold not in variation_dict:
variation_dict[scaffold] = {}
if var_pos not in variation_dict[scaffold]:
variation_dict[scaffold][var_pos] = {}
if var_type not in variation_dict[scaffold][var_pos]:
variation_dict[scaffold][var_pos][var_type] = {}
if var_seq not in variation_dict[scaffold][var_pos][var_type]:
variation_dict[scaffold][var_pos][var_type][var_seq] = {}
if read_id not in variation_dict[scaffold][var_pos][var_type][var_seq]:
variation_dict[scaffold][var_pos][var_type][var_seq][read_id] = 1
#For variation coverage
if scaffold not in var_coverage_dict:
var_coverage_dict[scaffold] = {}###############for var cov
if var_pos not in var_coverage_dict[scaffold]:
var_coverage_dict[scaffold][var_pos] = {}###############for var cov
var_coverage_dict[scaffold][var_pos][read_id] = 1
#used to calculate error rate of mapping
def calc_error_rate(start_pos,cigar,seq_list,scaffold,read_id):
[cig_dig_list,cig_char_list] = cigar_list(cigar)
h_count = 0
s_count = 0
i_count = 0
d_count = 0
mis_count = 0
all_genome_mismatch_list = []
all_nuc_mismatch_list = [] # this shows the nuc mismatch for the all_genome_mismatch_list
insertion_list = []
insertion_length_list = []
deletion_list = []
deletion_length_list = []
sj_pre_error_list = []
sj_post_error_list = []
nomatch_dict = {} # nomatch_dict[non match id] = list
nomatch_dict['mismatch_list'] = all_genome_mismatch_list
nomatch_dict['insertion_list'] = insertion_list
nomatch_dict['insertion_length_list'] = insertion_length_list
nomatch_dict['deletion_list'] = deletion_list
nomatch_dict['deletion_length_list'] = deletion_length_list
#walk through both the query seq and the mapped seq
genome_pos = start_pos - 1 #adjust for 1 base to 0 base coordinates
seq_pos = 0
for i in xrange(len(cig_dig_list)):
cig_flag = cig_char_list[i]
#print(seq_pos)
if cig_flag == "H":
h_count = h_count + int(cig_dig_list[i])
### for variation detection start
var_pos = genome_pos - h_count
var_seq = "N" * h_count
var_type = cig_flag
update_variation_dict(scaffold,var_pos,var_type,var_seq,read_id)
### for variation detection end
continue
elif cig_flag == "S":
s_count = s_count + int(cig_dig_list[i])
### for variation detection start
seq_start = seq_pos
seq_end = seq_pos + int(cig_dig_list[i])
var_pos = genome_pos - s_count
var_seq = seq_list[seq_start:seq_end]
var_type = cig_flag
###### change made 2019/11/19
#correct for soft clips at end of mapping
num_cig_entities = len(cig_dig_list)
if i == num_cig_entities - 1:
var_pos = genome_pos + 1 - s_count
###### change made 2019/11/19
update_variation_dict(scaffold,var_pos,var_type,var_seq,read_id)
### for variation detection end
#adjust seq position to account for missing soft mask in genome coord
seq_pos = seq_pos + int(cig_dig_list[i])
continue
elif cig_flag == "M":
match_length = int(cig_dig_list[i])
seq_start = seq_pos
seq_end = seq_pos + match_length
genome_start = genome_pos
genome_end = genome_pos + match_length
#seq_slice = seq_list[seq_start:seq_end+1]
#genome_slice = fasta_dict[scaffold][genome_start:genome_end+1]
seq_slice = seq_list[seq_start:seq_end]
genome_slice = fasta_dict[scaffold][genome_start:genome_end]
seq_diff = seq_end - seq_start
gen_diff = genome_end - genome_start
######################################################
#print(str(match_length)+cig_flag)
######################################################
#get number and location of mis matches
genome_mismatch_list,seq_mismatch_list,nuc_mismatch_list = mismatch_seq(genome_slice,seq_slice,genome_start,seq_start)
mis_count = mis_count + len(genome_mismatch_list)
all_genome_mismatch_list.extend(genome_mismatch_list)
all_nuc_mismatch_list.extend(nuc_mismatch_list)
### for variation detection start
for mismatch_index in xrange(len(seq_mismatch_list)):
var_pos = genome_mismatch_list[mismatch_index]
seq_var_pos = seq_mismatch_list[mismatch_index]
var_seq = seq_list[seq_var_pos]
var_type = cig_flag
update_variation_dict(scaffold,var_pos,var_type,var_seq,read_id)
### for variation detection end
seq_pos = seq_pos + match_length
genome_pos = genome_pos + match_length
continue
elif cig_flag == "I":
### for variation detection start
seq_start = seq_pos
seq_end = seq_pos + int(cig_dig_list[i])
var_pos = genome_pos
var_seq = seq_list[seq_start:seq_end]
var_type = cig_flag
update_variation_dict(scaffold,var_pos,var_type,var_seq,read_id)
### for variation detection end
insertion_length = int(cig_dig_list[i])
seq_pos = seq_pos + insertion_length
i_count = i_count + insertion_length
insertion_list.append(genome_pos)
insertion_length_list.append(insertion_length)
continue
elif cig_flag == "D":
deletion_list.append(genome_pos)
deletion_length = int(cig_dig_list[i])
deletion_length_list.append(deletion_length)
### for variation detection start
var_pos = genome_pos
var_seq = str(deletion_length) #var seq for deletion is length of deletion
var_type = cig_flag
update_variation_dict(scaffold,var_pos,var_type,var_seq,read_id)
### for variation detection end
genome_pos = genome_pos + deletion_length
d_count = d_count + deletion_length
continue
elif cig_flag == "N":
sj_pre_error_builder_list = [] # list of cigar string before splice junctions
sj_post_error_builder_list = [] # list of cigar string after splice junctions
# check for errors before splice junction pre
#########################################
prev_cig_flag = cig_char_list[i - 1]
prev_cig_length = int(cig_dig_list[i - 1])
#############################################################################################################################
# Add sj error info
prev_total_mismatch_length = 0
this_mismatch_length = 0 # keep track of where in the error list of cig
all_genome_mismatch_index = len(all_genome_mismatch_list) - 1
prev_total_cig_length = prev_cig_length
prev_cig_index = i - 1
this_cig_genome_pos = genome_pos
prev_sj_flag = 0
while prev_total_mismatch_length <= sj_err_threshold and prev_sj_flag == 0:
this_mismatch_length = this_mismatch_length + prev_cig_length
prev_total_mismatch_length = this_mismatch_length
if prev_cig_flag == "M":
# if no mismatch
if len(all_genome_mismatch_list) < 1: # no mismatch from M cigar regions up to this point
#last_genome_mismatch = -2 * sj_err_threshold
if prev_total_mismatch_length <= sj_err_threshold: # no mis matches for this gene
sj_pre_error_builder_list.append(str(prev_cig_length) + prev_cig_flag)
elif all_genome_mismatch_index >= 0:
last_genome_mismatch = all_genome_mismatch_list[all_genome_mismatch_index]
last_nuc_mismatch = all_nuc_mismatch_list[all_genome_mismatch_index]
dist_prev_mismatch = genome_pos - last_genome_mismatch
m_builder_add_count = 0
#while dist_prev_mismatch <= this_mismatch_length and dist_prev_mismatch <= sj_err_threshold:
while last_genome_mismatch >= this_cig_genome_pos - prev_cig_length and last_genome_mismatch <= this_cig_genome_pos and dist_prev_mismatch <= sj_err_threshold: # dist_prev_mismatch is still in range of sj threshold
sj_pre_error_builder_list.append(str(dist_prev_mismatch) + "." + last_nuc_mismatch)
m_builder_add_count += 1
all_genome_mismatch_index -= 1
last_genome_mismatch = all_genome_mismatch_list[all_genome_mismatch_index]
last_nuc_mismatch = all_nuc_mismatch_list[all_genome_mismatch_index]
dist_prev_mismatch = genome_pos - last_genome_mismatch
if all_genome_mismatch_index < 0:
break
if m_builder_add_count == 0:
if prev_total_mismatch_length <= sj_err_threshold: # still within in sj threshold so output
sj_pre_error_builder_list.append(str(prev_cig_length) + prev_cig_flag)
elif all_genome_mismatch_index < 0: # length of mismatch list is not 0 but index has gone past that
#last_genome_mismatch = -2 * sj_err_threshold
if prev_total_mismatch_length <= sj_err_threshold: # still within in sj threshold so output
sj_pre_error_builder_list.append(str(prev_cig_length) + prev_cig_flag)
else:
print("Error with all_genome_mismatch_index")
print(all_genome_mismatch_list)
print(all_genome_mismatch_index)
sys.exit()
elif prev_cig_flag != "N":
prev_cig_flag = cig_char_list[prev_cig_index]
prev_cig_length = int(cig_dig_list[prev_cig_index])
sj_pre_error_builder_list.append(str(prev_cig_length) + prev_cig_flag)
elif prev_cig_flag == "N":
prev_sj_flag = 1
prev_cig_index -= 1
if prev_cig_index < 0 :
break
this_cig_genome_pos = this_cig_genome_pos - prev_cig_length
prev_cig_flag = cig_char_list[prev_cig_index]
prev_cig_length = int(cig_dig_list[prev_cig_index])
if len(sj_pre_error_builder_list) == 0: # in case no errors are found
sj_pre_error_builder_list.append(no_mismatch_flag)
# end of adding sj error info prev
#############################################################################################################################
#########################################
# not related to sj error should probably move this up or down code of this block
#########################################
intron_length = int(cig_dig_list[i])
genome_pos = genome_pos + intron_length
#########################################
#check for errors after splice junction post
#########################################
next_cig_flag = cig_char_list[i + 1]
next_cig_length = int(cig_dig_list[i + 1])
#############################################################################################################################
next_total_mismatch_length = 0
this_mismatch_length = 0 # keep track of where in the error list of cig
all_genome_mismatch_index = len(all_genome_mismatch_list) - 1
next_total_cig_length = next_cig_length
next_cig_index = i + 1
this_next_seq_pos = seq_pos
this_genome_pos = genome_pos
#genome_mismatch_index = 0
next_sj_flag = 0
while next_total_mismatch_length <= sj_err_threshold and next_sj_flag == 0:
this_mismatch_length = this_mismatch_length + next_cig_length
next_total_mismatch_length = this_mismatch_length
if next_cig_flag == "M":
match_length = next_cig_length
seq_start = this_next_seq_pos
seq_end = this_next_seq_pos + match_length
genome_start = this_genome_pos
genome_end = this_genome_pos + match_length
seq_slice = seq_list[seq_start:seq_end]
genome_slice = fasta_dict[scaffold][genome_start:genome_end]
#######################################################
#print(str(match_length)+next_cig_flag)
#print(seq_start)
#print(seq_end)
######################################################
genome_mismatch_list, seq_mismatch_list, nuc_mismatch_list = mismatch_seq(genome_slice, seq_slice, genome_start, seq_start)
genome_mismatch_index = 0
# if no mismatch
if len(genome_mismatch_list) < 1: # no mismatch in this cig entry
#dist_next_mismatch = 2 * sj_err_threshold
if next_total_mismatch_length <= sj_err_threshold:
sj_post_error_builder_list.append(str(next_cig_length) + next_cig_flag)
elif genome_mismatch_index <= len(genome_mismatch_list):
nuc_next_mismatch = nuc_mismatch_list[0]
#dist_next_mismatch = genome_mismatch_list[0] - this_genome_pos
dist_next_mismatch = genome_mismatch_list[0] - genome_pos
m_builder_add_count = 0
while dist_next_mismatch <= this_mismatch_length and dist_next_mismatch < sj_err_threshold:
next_genome_mismatch = genome_mismatch_list[genome_mismatch_index]
next_nuc_mismatch = nuc_mismatch_list[genome_mismatch_index]
#dist_next_mismatch = next_genome_mismatch - this_genome_pos
dist_next_mismatch = next_genome_mismatch - genome_pos
if dist_next_mismatch <= sj_err_threshold: # this mismatch goes beyond this M length
sj_post_error_builder_list.append(str(dist_next_mismatch) + "." + next_nuc_mismatch)
m_builder_add_count += 1
genome_mismatch_index += 1
if genome_mismatch_index >= len(genome_mismatch_list):
break
if m_builder_add_count == 0:
if next_total_mismatch_length <= sj_err_threshold:
sj_post_error_builder_list.append(str(next_cig_length) + next_cig_flag)
else:
print("Error with genome_mismatch_index")
sys.exit()
elif next_cig_flag != "N":
next_cig_flag = cig_char_list[next_cig_index]
next_cig_length = int(cig_dig_list[next_cig_index])
sj_post_error_builder_list.append(str(next_cig_length) + next_cig_flag)
elif next_cig_flag == "N":
next_sj_flag = 1
if next_cig_flag != "D": # increase this seq pos only if not a deletion
this_next_seq_pos = this_next_seq_pos + next_cig_length
if next_cig_flag != "I":
this_genome_pos = this_genome_pos + next_cig_length
next_cig_index += 1
if next_cig_index >= len(cig_char_list):
break
next_cig_flag = cig_char_list[next_cig_index]
next_cig_length = int(cig_dig_list[next_cig_index])
if len(sj_post_error_builder_list) == 0: # in case no errors are found
sj_post_error_builder_list.append(no_mismatch_flag)
# end of adding sj error info post
#############################################################################################################################
#############################################################################################################################
sj_post_error_builder_line = "_".join(sj_post_error_builder_list)
sj_pre_error_builder_list_reverse = list(reversed(sj_pre_error_builder_list))
sj_pre_error_builder_line = "_".join(sj_pre_error_builder_list_reverse)
sj_pre_error_list.append(sj_pre_error_builder_line)
sj_post_error_list.append(sj_post_error_builder_line)
#########################################
continue
else:
match_length = int(cig_dig_list[i])
print("Error with cigar flag")
print(str(match_length) + cig_flag)
print(cig_dig_list)
print(cig_char_list)
sys.exit()
#print("calc_error_rate")
#print(cigar)
#blah = ",".join([str(h_count),str(s_count),str(i_count),str(d_count),str(mis_count)])
#print(blah)
#print(cig_dig_list)
#print(cig_char_list)
#sys.exit()