-
Notifications
You must be signed in to change notification settings - Fork 1
/
lamprey.py
1690 lines (1275 loc) · 58.4 KB
/
lamprey.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
863
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/python
import sys, os, subprocess, argparse, collections
import random
import heapq
import time
import multiprocessing
from progressbar import progressbar
import random as rng
# use local swalign?
#sys.path.insert(0, '/home/dna/software/cswalign')
import swalign
import mappy
import pysam
import vcfpy
import numpy as np
import statsmodels.api as sm
import datetime
from Bio import SeqIO
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
#########################
class bcolors:
HEADER = '\033[95m'
BLUE = '\033[94m'
CYAN = '\033[96m'
GREEN = '\033[32;1m'
BGREEN = '\033[32;7m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def print_blue(text):
sys.stdout.write(bcolors.BLUE text bcolors.ENDC)
def print_cyan(text):
sys.stdout.write(bcolors.CYAN text bcolors.ENDC)
def print_red(text):
sys.stdout.write(bcolors.FAIL text bcolors.ENDC)
def print_green(text):
sys.stdout.write(bcolors.GREEN text bcolors.ENDC "\n")
#########################
class PrimerSet:
'''
Stores bases in a primer set.
'''
def __init__(self, primer_set_filename):
self.primer_dict = dict()
self.fwd_primer_order = ['F3', 'F2', 'F1', 'T', 'B1c', 'B2c', 'B3c']
self.rev_primer_order = ['B3', 'B2', 'B1', 'Tc', 'F1c', 'F2c', 'F3c']
# initialize primer set given file
with open(primer_set_filename) as fp:
for line in fp:
# read lines in format <primer_name> <primer_seq>
line = line.strip()
if not line: continue
if line.startswith("#"): continue
fields = line.split(' ')
primer_name = fields[0]
# parse fwd_primer_order line
if primer_name == 'fwd_primer_order':
# clear default
self.fwd_primer_order.clear()
for field in fields[1:]:
self.fwd_primer_order.append(field)
continue
# parse rev_primer_order line
if primer_name == 'rev_primer_order':
# clear default
self.rev_primer_order.clear()
for field in fields[1:]:
self.rev_primer_order.append(field)
continue
# parse normal primer
primer_string = fields[1]
# also store revcomp version
if primer_name.endswith('c'):
self.primer_dict[primer_name[:-1]] = rc(primer_string)
else:
self.primer_dict[primer_name] = primer_string
#########################
class Alignment:
'''
Stores alignment info.
'''
def __init__(self, start=0, end=0, identity=0.0, primer_name=''):
self.start = start
self.end = end
self.identity = identity
self.primer_name = primer_name
def __repr__(self):
return "{} at ({}, {}) identity: {}".format(
self.primer_name, self.start, self.end, self.identity)
def __str__(self):
return "{} at ({}, {}) identity: {}".format(
self.primer_name, self.start, self.end, self.identity)
def __lt__(self, other):
return self.start < other.start
def __eq__(self, other):
self.start == other.start
#########################
class Result:
'''
Stores lamplicon classification, pileup info, and other post processing information.
'''
def __init__(self, classification='unknown', mut_count=0, wt_count=0, pileup_str='', target_depth=0, alignments=[], seq=None, idx=0, read_id = '', timestamp=None):
self.classification = classification
self.mut_count = mut_count
self.wt_count = wt_count
self.plural_base = ''
self.pileup_str = pileup_str
self.target_depth = target_depth
self.target_seq_accuracy = (0,0)
self.bad_calls = None
self.polished_bad_calls = None
self.alignments = alignments
self.seq = seq
self.polished_seq = None
self.idx = idx
self.read_id = read_id
self.timestamp = timestamp
def __lt__(self, other):
return self.timestamp < other.timestamp
##########################
def printHeader():
s = ''
s = ' __ ___ __ _______\n'
s = ' / / / | / |/ / __ \________ __ __\n'
s = ' / / / /| | / /|_/ / /_/ / ___/ _ \/ / / /\n'
s = ' / /___/ ___ |/ / / / ____/ / / __/ /_/ /\n'
s = '/_____/_/ |_/_/ /_/_/ /_/ \___/\__, /\n'
s = ' /____/ \n'
s = ' by Jack Wadden\n'
s = ' Version 0.1\n'
print(s)
#######
def alignPrimer(aligner, seq, primer, primer_name):
'''
Aligns a primer to a DNA sequence.
'''
alignment_tmp = aligner.align(str(seq), primer)
alignment = Alignment(alignment_tmp.r_pos,
alignment_tmp.r_end,
alignment_tmp.identity,
primer_name)
return alignment
#######
def findPrimerAlignments(aligner, seq, primer, primer_name, identity_threshold):
'''
Greedy approach which finds the best primer alignment for a long sequence,
then uses left/right recursion to find all other possible (non-overlapping)
alignments.
'''
# find optimal alignment
alignment = alignPrimer(aligner, seq, primer, primer_name)
alignment_len = alignment.end - alignment.start
# TODO: improve heuristic (50% threshold -> 25% match passes worst case)
alignment_list = list()
if alignment.identity >= identity_threshold and \
alignment_len >= len(primer) * identity_threshold:
# add the optimal alignment to list of valid alignments
alignment_list.append(alignment)
# split the sequence into left/right sections based on the alignment
left_seq = seq[:alignment.start]
right_seq = seq[alignment.end:]
# recurse left
if len(left_seq) >= len(primer):
left_alignments = findPrimerAlignments(
aligner, left_seq, primer, primer_name, identity_threshold)
alignment_list.extend(left_alignments)
# recurse right
if len(right_seq) >= len(primer):
right_alignments = findPrimerAlignments(
aligner, right_seq, primer, primer_name, identity_threshold)
# adjust right alignment positioning (since we cropped out seq start)
for right_alignment in right_alignments:
right_alignment.start = alignment.end
right_alignment.end = alignment.end
# add all right alignments
alignment_list.extend(right_alignments)
return alignment_list
#########################
# from stack overflow: https://stackoverflow.com/questions/25188968/reverse-complement-of-dna-strand-using-python
def rc(seq):
'''
Reverse-complement DNA sequence.
'''
# replace bases with complement, defaulting to same identifier if not found
bases = list(seq)
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}
bases = reversed([complement.get(base,base) for base in bases])
bases = ''.join(bases)
return bases
############################
def pruneRapidAdapters(aligner, seq):
'''
Fancy printing of suspected rapid adapters still in sequence.
'''
# TODO: make adapter seq and thresholds variable
adapter_ytop='GGCGTCTGCTTGGGTGTTTAACCTTTTTTTTTTAATGTACTTCGTTCAGTTACGTATTGCT'
adapter_ybot='GCAATACGTAACTGAACGAAGT'
# check ytop
alignment = aligner.align(adapter_ytop, read_string)
print(alignment.identity)
print(alignment.q_pos)
print(alignment.q_end)
if alignment.q_end < 100 and alignment.identity > 0.55:
print("Found possible adapter top of fwd:")
alignment.dump()
# check rc ytop
alignment = aligner.align(adapter_ytop, rc(read_string))
if alignment.q_end < 100 and alignment.identity > 0.55:
print("Found possible adapter top on rc:")
alignment.dump()
# check ybot
alignment = aligner.align(adapter_ybot, read_string)
if alignment.q_pos > len(read_string) - (len(adapter_ybot) * 2) and alignment.identity > 0.55:
print("Found possible adapter bot on fwd:")
alignment.dump()
# check rc ybot
alignment = sw.align(adapter_ybot, rc(read_string))
if alignment.q_pos > len(read_string) - (len(adapter_ybot) * 2) and alignment.identity > 0.55:
print("Found possible adapter bot on rc:")
alignment.dump()
##################
def findAllPrimerAlignments(aligner, seq, primers, identity_threshold, args):
alignment_list = list()
alignment_list.extend(findPrimerAlignments(aligner, seq, primers.primer_dict["T"], "T", identity_threshold))
alignment_list.extend(findPrimerAlignments(aligner, seq, rc(primers.primer_dict["T"]), "Tc", identity_threshold))
# bail if we didn't find a target in this read
# this is a lazy shortcut optimization
if len(alignment_list) == 0:
return(sorted(alignment_list), 0.0)
if args.high_confidence and len(alignment_list) < 2:
return(sorted(alignment_list), 0.0)
for primer_name, primer_seq in primers.primer_dict.items():
if primer_name == 'T':
continue
else:
# fwd
alignment_list.extend(findPrimerAlignments(aligner, seq, primer_seq, primer_name, identity_threshold))
# rc
alignment_list.extend(findPrimerAlignments(aligner, seq, rc(primer_seq), primer_name "c", identity_threshold))
alignment_list = sorted(alignment_list)
# get alignment coverage
seq_length = len(seq)
primer_coverage = 0
for alignment in alignment_list:
primer_coverage = primer_coverage (alignment.end - alignment.start)
#print("Primer coverage: " str(primer_coverage))
alignment_coverage = float(primer_coverage)/float(seq_length)
return(alignment_list, alignment_coverage)
###################
def clearColor():
sys.stdout.write(bcolors.ENDC)
def setPrimerColor(primer_string):
color = ''
if primer_string == 'T':
color = bcolors.BGREEN
elif primer_string == 'Tc':
color = bcolors.GREEN
elif primer_string == 'F2':
color = '\u001b[38;5;4;7m'
elif primer_string == 'F2c':
color = '\u001b[38;5;4m'
elif primer_string == 'F1':
color = '\u001b[38;5;75;7m'
elif primer_string == 'F1c':
color = '\u001b[38;5;75m'
elif primer_string == 'B2':
color = '\u001b[38;5;1;7m'
elif primer_string == 'B2c':
color = '\u001b[38;5;1m'
elif primer_string == 'B1':
color = '\u001b[38;5;204;7m'
elif primer_string == 'B1c':
color = '\u001b[38;5;204m'
sys.stdout.write(color)
def printPrimerAlignments(seq, alignments):
'''
Fancy printing of all primers aligned to sequence.
'''
print("", flush=True)
print(seq)
print(alignments)
wrap = 100
wrap_counter = 0
found_primer = False
primer_string = ''
primer_string_counter = 0
primer_queue = []
for pos in range(0, len(seq)):
sys.stdout.write(seq[pos])
# print the alignment if we're at the wrap factor OR end of the string
if (pos > 0 and (pos 1) % wrap == 0) or pos == len(seq)-1:
sys.stdout.write('\n')
# print corresponding alignment
for aln_pos in range(wrap_counter * wrap, pos 1):
found_start = False
found_end = False
# do we need to emit a spec char?
for alignment in alignments:
if alignment.start == aln_pos:
found_start = True
primer_string = alignment.primer_name
primer_string_counter = 0
primer_queue.append(alignment)
elif alignment.end == aln_pos:
found_end = True
primer_queue.pop()
# reset color
if found_primer:
setPrimerColor(primer_string)
else:
sys.stdout.write(bcolors.ENDC)
# emit special char
if found_start and found_end:
sys.stdout.write('X')
found_primer = True
elif found_start:
# turn on color
setPrimerColor(primer_string)
sys.stdout.write('$')
found_primer = True
elif found_end:
sys.stdout.write('^')
if len(primer_queue) == 0:
found_primer = False
else:
# if no special char, print either a primer string, -,
# or space if not currently in a primer
if found_primer:
if primer_string_counter < len(primer_string):
sys.stdout.write(primer_string[primer_string_counter])
primer_string_counter = primer_string_counter 1
else:
sys.stdout.write('-')
else:
sys.stdout.write(' ')
# end alignment line
sys.stdout.write(bcolors.ENDC)
sys.stdout.write('\n\n')
# increment wrap counter
wrap_counter = wrap_counter 1
sys.stdout.write('\n')
################################################
def removeOverlappingPrimerAlignments(debug_print, alignments, allowed_overlap):
if debug_print:
print("* Removing overlapping primer alignments...")
new_alignments = list()
overlapping_alignments = list()
overlapping_alignments = 0
last_start_pos = 0
last_end_pos = 0
last_alignment = alignments[0]
for idx,alignment in enumerate(alignments):
# skip first alignment
if idx == 0:
continue
# if this alignment overlaps with the last alignment, pick a winner
if alignment.start < last_alignment.end - allowed_overlap:
if debug_print:
print(" - Found overlapping primer alignment: {}".format(str(alignment.start) " : " str(alignment.end)), flush=True)
if alignment.identity > last_alignment.identity:
# erase last alignment without adding it
last_alignment = alignment
else:
# skip this alignment altogether
last_alignment = last_alignment
else:
# add last alignment... it's cleared
new_alignments.append(last_alignment)
last_alignment = alignment
# append last alignment
new_alignments.append(last_alignment)
return new_alignments
###################
def extractAmpliconAroundTarget(primer_set, alignments, target):
'''
Target sequence was found in lamplicon. Extend this sequence as far as
possible both left and right (including primers) to increase mappability.
This is done using expected next primer, allowing one mismatch.
'''
amplicon_start = 0
amplicon_end = 0
# is target forward or reverse?
fwd_strand = target.primer_name == "T"
# find target alignment index
target_index = alignments.index(target)
#####
# look to the right
#####
allowed_mismatches = 0
primer_counter = primer_set.fwd_primer_order.index('T') if fwd_strand else primer_set.rev_primer_order.index('Tc')
primer_counter = primer_counter 1
all_matched = True
for i in range(target_index 1, len(alignments)):
# primer name
primer_name = alignments[i].primer_name
# expected primer name
if fwd_strand:
expected_primer_name = primer_set.fwd_primer_order[primer_counter]
else:
expected_primer_name = primer_set.rev_primer_order[primer_counter]
# on a mismatch, end the search
if primer_name != expected_primer_name:
if allowed_mismatches > 0:
allowed_mismatches = allowed_mismatches - 1
else:
# we've found our end, point, so make our end the last match end
amplicon_end = alignments[i-1].end
all_matched = False
break
else:
primer_counter = primer_counter 1
# if we matched all primers, we have to quit no matter what
if primer_counter == len(primer_set.fwd_primer_order):
break
# if we matched all in the primer sequence, extend to the end of the entire read
if all_matched:
amplicon_end = -1
#####
# look to the left
#####
allowed_mismatches = 0
primer_counter = primer_set.fwd_primer_order.index('T') if fwd_strand else primer_set.rev_primer_order.index('Tc')
primer_counter = primer_counter - 1
all_matched = True
for i in range(target_index - 1, 0, -1):
# primer name
primer_name = alignments[i].primer_name
# expected primer name
if fwd_strand:
expected_primer_name = primer_set.fwd_primer_order[primer_counter]
else:
expected_primer_name = primer_set.rev_primer_order[primer_counter]
# on a mismatch, end the search
if primer_name != expected_primer_name:
if allowed_mismatches > 0:
allowed_mismatches = allowed_mismatches - 1
else:
# we've found our end, point, so make our end the last match end
amplicon_start = alignments[i 1].start
all_matched = False
break
else:
primer_counter = primer_counter - 1
if all_matched:
amplicon_start = 0
return amplicon_start, amplicon_end
################################################
def getI(read):
return read.get_cigar_stats()[0][1]
def getD(read):
return read.get_cigar_stats()[0][2]
def getEq(read):
return read.get_cigar_stats()[0][7]
def getX(read):
return read.get_cigar_stats()[0][8]
def getAccuracy(read, alt_pos=None, alt_base=None):
'''
Calculate accuracy for a single read, ignoring suspected alternate bases.
'''
# get CIGAR stats
Eq = getEq(read)
X = getX(read)
I = getI(read)
D = getD(read)
# return easy answer if we don't care about alternate reads
if alt_pos is None or alt_base is None:
return (float(Eq) / float(Eq I X D))
# adjust Eq and X if this is a suspected alt read
# find the alignment pair for the ref position
# query the query pos that corresponds, and check if the base is the alt base
for pair in read.get_aligned_pairs():
if pair[0] == None or pair[1] == None:
continue
if pair[1] == (alt_pos - 1):
if read.query_alignment_sequence[pair[0]-read.query_alignment_start] == alt_base:
Eq = Eq 1
X = X - 1
return (float(Eq) / float(Eq I X D))
#### parses CIGAR string and calc total errors.
# ignores leading/trailing errors
# can accept one alt base possibility/position pair to account for tumor reads
# if an alt base is provided, a consensus vote for the alt at that position will
# not be counted as an error
def calcErrorRate(ref_fn, sam_fn, alt_pos=None, alt_base=None):
'''
Calculate overall error rate in SAM file.
'''
# init
samfile = pysam.AlignmentFile(sam_fn, 'r')
cumulative_err_rate = 0.0
mapped_read_count = 0
# accumulate errors
for read in samfile:
if not read.is_unmapped:
mapped_read_count = 1
cumulative_err_rate = getAccuracy(read, alt_pos, alt_base)
# if no mapped reads, cumulative accuracy is 0
if mapped_read_count == 0: return 0
# return average error
avg_err_rate = cumulative_err_rate / mapped_read_count
return avg_err_rate
################################################
def parsePileupCodeString(code_string, variant):
variant_count = 0
ref_count = 0
total_count = 0
skip_counter = 0
set_skip = False
for c in code_string:
#print(c)
if(skip_counter > 0):
skip_counter = skip_counter - 1
continue
if(set_skip):
skip_counter = int(c)
set_skip = False
continue
total_count = total_count 1
if c == ',' or c == '.':
ref_count = ref_count 1
elif c == variant or c == variant.lower():
variant_count = variant_count 1
elif c == '-' or c == ' ':
set_skip = True
elif c == '^':
skip_counter = 1
return ref_count, variant_count
################################################
def countCallsFromPileup(ref_char, pileup_str):
pileup_calls = dict()
pileup_calls['a'] = 0
pileup_calls['t'] = 0
pileup_calls['g'] = 0
pileup_calls['c'] = 0
pileup_calls['*'] = 0 # deletion
#
total_count = 0
skip_counter = 0
set_skip = False
for c in pileup_str:
if(skip_counter > 0):
skip_counter = skip_counter - 1
continue
if(set_skip):
skip_counter = int(c)
set_skip = False
continue
total_count = total_count 1
if c == ',' or c == '.':
pileup_calls[ref_char.lower()] = pileup_calls[ref_char.lower()] 1
elif c.lower() in pileup_calls.keys():
pileup_calls[c.lower()] = pileup_calls[c.lower()] 1
elif c == '-' or c == ' ':
set_skip = True
elif c == '^':
skip_counter = 1
return pileup_calls
################################################
def getPluralityVoter(calls):
total_calls = sum(calls.values())
# is there a plurality voter?
plural_bases = set()
majority_base = ''
majority_vote = False
max_count = 0
for base, count in calls.items():
if count > max_count:
max_count = count
majority_base = base
majority_vote = True
if count == max_count:
plurality_vote = False
for base, count in calls.items():
if count == max_count:
plural_bases.add(base)
# if there was a plurality vote, pick that
# else choose, random call among the tied plurality
if majority_vote == False and plurality_vote == False:
majority_base = random.choice(plural_bases)
return majority_base, max_count
################################################
def extractPileupInfo(pileup_fn, contig, target_locus, limit):
# parse lines in the pileup, extract the depth at the locus
ref = ''
depth = 0
code_string = ''
covers_roi = False
within_roi = False
vote_count = 0
ref_match_count = 0
bad_calls = dict({'a' : 0, 't' : 0, 'c' : 0, 'g' : 0, '*' : 0, 'ref' : 0})
polished_bad_calls = dict({'a' : 0, 't' : 0, 'c' : 0, 'g' : 0, '*' : 0, 'ref' : 0})
with open(pileup_fn) as fp:
for line in fp:
fields = line.split('\t')
if fields[0] == contig:
pileup_locus = int(fields[1])
# retrieve target specific information
if pileup_locus == target_locus:
ref = fields[2]
depth = int(fields[3])
code_string = fields[4]
covers_roi = True
elif pileup_locus < (target_locus limit) and pileup_locus > (target_locus - limit):
within_roi = True
# consider entire read accuracy if the number of votes is 2
locus_depth = int(fields[3])
if locus_depth > 0 and pileup_locus != target_locus:
locus_code_string = fields[4]
locus_ref = fields[2].lower()
calls = countCallsFromPileup(locus_ref, locus_code_string)
majority_base, count = getPluralityVoter(calls)
# is majority/random base right or wrong?
if majority_base == locus_ref.lower():
ref_match_count = ref_match_count 1
polished_bad_calls['ref'] = polished_bad_calls['ref'] 1
else:
polished_bad_calls[majority_base] = polished_bad_calls[majority_base] 1
vote_count = vote_count 1
# collect all incorrect calls
for key in bad_calls:
if key in calls:
if key == locus_ref.lower():
bad_calls['ref'] = bad_calls['ref'] calls[key]
else:
bad_calls[key] = bad_calls[key] calls[key]
return ref, depth, code_string, covers_roi, within_roi, ref_match_count, vote_count, bad_calls, polished_bad_calls
################################################
def proportionConfidenceInterval(mut, wt, conf):
conf_int = sm.stats.proportion_confint(count=mut,
nobs=mut wt,
alpha=(1 - conf))
if (mut wt) > 0:
samp_mean = float(mut)/float(mut wt) * 100.0
else:
samp_mean = 0.0
if conf_int[0] == 0.0:
low = 0.0
else:
low = samp_mean - conf_int[0] * 100.0
high = conf_int[1] * 100.0 - samp_mean
#print("conf:", conf, "%.2f" % low, " -- ", "%.2f" % samp_mean, " -- ", "%.2f" % high, ")")
#print("conf:", conf, "%.4f" % (conf_int[0]*100.0), " -- ", "%.2f" % samp_mean, " -- ", "%.4f" % (conf_int[1]*100.0), ")")
return conf_int[0], samp_mean, conf_int[1]
def isStatisticallySignificant(mut, wt, conf, err):
total = mut wt
err_low, err_mean, err_high = proportionConfidenceInterval(err * float(total), (1.0 - err) * float(total), conf)
obs_low, obs_mean, obs_high = proportionConfidenceInterval(mut, wt, conf)
if (obs_low > err_high):
return True
else:
return False
################################################
def parseVCF(vcf_fn):
reader = vcfpy.Reader.from_path(vcf_fn)
# extract variant roi
for record in reader:
return record
return
################################################
def is_hit_near_target(alignment, vcf_record, limit):
contig = alignment.ctg
ref_start = alignment.r_st
ref_end = alignment.r_en
target_contig = vcf_record.CHROM
target_locus = vcf_record.POS
if target_contig == contig:
# fully contained to be considered a fragment
if target_locus limit > ref_end and target_locus - limit < ref_start:
return True
return False
######################################
def parseTimestamp(timestamp):
# format: 2019-07-10T20:53:45Z
parsed_time = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ")
return parsed_time
def timestampDelta(start, end):
delta = end - start
return delta.total_seconds()
##############################################
def polishLamplicon(lamplicon, subread_alignment_file, alignment_interval_dict):
# generate new read from lamplicon.seq substring
polished_lamplicon = SeqRecord(lamplicon.seq,
id = lamplicon.id,
name = lamplicon.name,
description = lamplicon.description
)
# parse the samfile into pysam
pileup_alignments = pysam.AlignmentFile(subread_alignment_file, "r")
# generate pileup over target region
pileup_iter = pileup_alignments.pileup(truncate=True,
stepper="samtools",
min_base_quality=0,
ignore_overlaps=False,
ignore_orphans=False)
deletion_removal_list = list()
# iterate over the pileup
deletion_streak_counters = dict()
# for each pileup position
for column in pileup_iter:
calls = dict({'a' : 0, 't' : 0, 'c' : 0, 'g' : 0, '*' : 0, 'ref' : 0})
call_count = 0
# get the position in the sub-read for this column
# NOTE: deletions return the location "before" the deletion position in the alignment
query_positions = column.get_query_positions()
# gather all votes and positions in mother read
for read in column.pileups:
# deletion
if read.is_del:
calls['*'] = calls['*'] 1
call_count = call_count 1
# insertion (skip)
elif read.is_refskip:
continue
# mismatch
else:
#print(read.query_position)
#print(read.alignment.query_sequence)
base = read.alignment.query_sequence[read.query_position].lower()
#print("BASE: {}".format(base))
#print(read.alignment.query_sequence)
calls[base] = calls[base] 1
call_count = call_count 1
# compute plurality vote
vote_base, plurality_count = getPluralityVoter(calls)
#print(vote_base, plurality_count)
# if we end up with zero votes, skip this location
if plurality_count < 1:
continue
# polish bases in mother read
read_idx = 0
for read in column.pileups:
# get sub-read direction info
read_start, read_end, direction = alignment_interval_dict[read.alignment.query_name]
# where does this base lie?
offset = query_positions[read_idx]
# if the sub-read aligns to the mother in the forard direction
if direction == 'fwd':
base = vote_base.upper()
# if the sub-read aligns to the reference in the forward
if not read.alignment.is_reverse:
mother_pos = read_start offset
else:
mother_pos = read_end - 1 - offset
# if the sub-read aligns to the mother in the reverse direction
else:
base = rc(vote_base.upper())
# if the sub-read aligns to the reference in the forward
if not read.alignment.is_reverse:
mother_pos = read_start offset
# if the sub-read aligns to the reference in the reverse direction
else:
mother_pos = read_end - 1 - offset
# if we need to polish a deletion, save it and we'll handle it later
# if we are a deletion, and the polished base is a deletion, skip/ignore
if read.is_del and base != '*':
if len(deletion_removal_list) > 0 and deletion_removal_list[-1][0] == mother_pos:
deletion_removal_list[-1][1].append(base)
else:
deletion_removal_list.append((mother_pos, [base], direction))
# polish the base in the mother read
else:
# adjust mother read