-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlamprey.py
2322 lines (1770 loc) · 81.2 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
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
#
import sys, os, subprocess, argparse, collections
import shutil
import cProfile
import random
import heapq
from collections import Counter
import time
import multiprocessing
from progressbar import progressbar
import random as rng
# use local swalign?
sys.path.insert(0, './lib')
import swalign
from skbio.alignment import StripedSmithWaterman
import mappy
import bwapy
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
from Bio.Sequencing.Applications import SamtoolsViewCommandline
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
#########################
cigarOpMap = {'M' : 0,
'I' : 1,
'D' : 2,
'N' : 3,
'S' : 4,
'H' : 5,
'P' : 6,
'=' : 7,
'X' : 8,
'B' : 9}
#########################
class Calls:
def __init__(self, calls = dict({'a' : 0, 't' : 0, 'c' : 0, 'g' : 0, '*' : 0, 'ref' : 0})):
self.calls = calls
#########################
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
print(self.fwd_primer_order)
print(self.rev_primer_order)
#########################
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', calls = Calls(), 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 = 'n'
self.plural_base_support = 0
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 __str__(self):
s = ''
s += str(self.idx) + ' '
s += self.read_id + ' '
s += str(self.timestamp) + ' '
s += self.classification + ' '
s += str(self.mut_count) + ' '
s += str(self.wt_count) + ' '
s += self.plural_base + ' '
s += str(self.plural_base_support) + ' '
s += str(self.target_depth) + ' '
return s
#########################
class Results:
'''
Stores classification, pileup info, and other post processing information for a set of reads.
'''
def __init__(self, ref_vcf_record, target_vcf_record):
self.calls = dict({'a' : 0, 't' : 0, 'c' : 0, 'g' : 0, '*' : 0, 'ref' : 0})
self.ref_base = target_vcf_record.REF.lower()
for alt in target_vcf_record.ALT:
self.mut_base = alt.value.lower()
self.results = []
self.conf_interval = None
self.milestone_map = {"0.95" : False,
"0.99" : False,
"0.999" : False,
"0.9999" : False,
"0.95+0.05" : False,
"0.99+0.05" : False,
"0.999+0.05" : False,
"0.9999+0.05" : False}
def append(self, result):
self.results.append(result)
# add the result of the base call to the calls data structure
if result.classification == 'target':
self.calls[result.plural_base] += 1
# compute stats in realtime
mut = self.calls[self.mut_base]
ref = self.calls[self.ref_base]
total = mut + ref
# confidence level/interval significance vs background error
err = 0.015
for conf_level in [0.95, 0.99, 0.999, 0.9999]:
self.conf_interval = proportionConfidenceInterval(mut, ref, conf_level)
vaf = self.conf_interval[1]
observed_low = self.conf_interval[0]
observed_mean = self.conf_interval[1]
observed_high = self.conf_interval[2]
err_bound = proportionConfidenceErrorBound(mut, ref, conf_level)
err_low, err_mean, err_high = proportionConfidenceInterval(err * float(total), (1.0 - err) * float(total), conf_level)
s = ''
# are we statistically significant?
# must have at least 10 reads supporting the mutation
if mut > 10 and observed_low > err_high and not self.milestone_map[str(conf_level)]:
s = "#Target VAF ({:2f}% {}/{}) statistically significant at {} CL at time {}".format(vaf, mut, total, conf_level, datetime.datetime.now())
# print and log to result file
print(s)
result_trace_path = os.getcwd() + "/lamprey_results/results.trace"
with open(result_trace_path, 'a') as handle:
handle.write(s + "\n")
handle.close()
# mark milestone as completed
self.milestone_map[str(conf_level)] = True
# are the confidence intervals tight? (+/- 5%)
CI_bound = 0.05
CI = observed_high - observed_mean/100.0
milestone_key = str(conf_level) + "+" + str(CI_bound)
if mut > 10 and CI < CI_bound and not self.milestone_map[milestone_key]:
s = "#Target VAF ({:2f}% {}/{}) has CI within +/-{} (+/-{}) for {} CL at time {}".format(vaf, mut, total, CI_bound, CI, conf_level, datetime.datetime.now())
# print and log to result file
print(s)
result_trace_path = os.getcwd() + "/lamprey_results/results.trace"
with open(result_trace_path, 'a') as handle:
handle.write(s + "\n")
handle.close()
# mark milestone as completed
self.milestone_map[milestone_key] = True
# number of reads supporting
def __len__(self):
return len(self.results)
def __str__(self):
mut_count = self.calls[self.mut_base]
ref_count = self.calls[self.ref_base]
total_count = mut_count + ref_count
s = "VAF: {:.2f}% (mut/wt {}/{} total reads considered:{}) Time: {}\n".format(getVAF(self.calls, self.ref_base, self.mut_base), mut_count, total_count, len(self.results), datetime.datetime.now())
if self.conf_interval is not None:
err_bound = proportionConfidenceErrorBound(self.calls[self.mut_base], self.calls[self.ref_base], 0.95)
s += " 95% CI: +/- {:.4f}%\n".format(err_bound)
err_bound = proportionConfidenceErrorBound(self.calls[self.mut_base], self.calls[self.ref_base], 0.99)
s += " 99% CI: +/- {:.4f}%\n".format(err_bound)
err_bound = proportionConfidenceErrorBound(self.calls[self.mut_base], self.calls[self.ref_base], 0.999)
s += " 99.9% CI: +/- {:.4f}%\n".format(err_bound)
err_bound = proportionConfidenceErrorBound(self.calls[self.mut_base], self.calls[self.ref_base], 0.9999)
s += " 99.99% CI: +/- {:.4f}%\n".format(err_bound)
else:
s += " 95% CI: +/- NA%\n"
s += " 99% CI: +/- NA%\n"
s += " 99.9% CI: +/- NA%\n"
s += " 99.99% CI: +/- NA%\n"
return s
##########################
class Fast5Watcher:
def __init__(self, args):
self.observer = Observer()
self.args = args
#
self.source_fast5_dir = args.watchdog
def run(self):
source_fast5_dir = args.watchdog
fast5_event_handler = Fast5Handler(source_fast5_dir)
self.observer.schedule(fast5_event_handler, source_fast5_dir, recursive=True)
self.observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
self.observer.stop()
self.observer.join()
##########################
class FastqWatcher:
def __init__(self, args):
self.observer = Observer()
self.args = args
#
self.source_fast5_dir = args.watchdog
# initialize minimap2
print("> Initializing aligners")
self.sw, self.minimap2 = initAligners(args)
# read in LAMP files
# parse primers from config file
print("> Parsing LAMP assay schema file: {}".format(args.primer_set_fn))
self.primers = PrimerSet(args.primer_set_fn)
print("> Parsing target mutation VCF files:")
# parse ref VCF file if there is one
if args.ref_vcf_fn != '':
print(" * {}".format(args.ref_vcf_fn))
self.ref_vcf_record = parseVCF(args.ref_vcf_fn)
# parse VCF file if there is one
if args.target_vcf_fn != '':
print(" * {}".format(args.target_vcf_fn))
self.target_vcf_record = parseVCF(args.target_vcf_fn)
def run(self):
fastq_event_handler = FastqHandler(self.primers, self.ref_vcf_record, self.target_vcf_record, self.sw, self.minimap2, args)
# this is the directory where we monitor for fastqs
if args.watchdog_barcode is not '':
source_fastq_dir = os.getcwd() + "/lamprey_results/fastq/" + args.watchdog_barcode
else:
source_fastq_dir = os.getcwd() + "/lamprey_results/fastq/"
isdir = os.path.isdir(source_fastq_dir)
if not isdir:
print("WARNING: Source FASTQ directory {} does not exist yet.".format(source_fastq_dir))
print(" - Please double check the file path.")
print(" - Creating empty location in antici....pation of reads...")
os.makedirs(source_fastq_dir, exist_ok=True)
#####
self.observer.schedule(fastq_event_handler, source_fastq_dir, recursive=True)
self.observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
self.observer.stop()
self.observer.join()
#######################################
class Fast5Handler(PatternMatchingEventHandler):
def __init__(self, source_fast5_dir):
PatternMatchingEventHandler.__init__(self,patterns=['*.fast5'], ignore_directories=True, case_sensitive=True)
self.source_fast5_dir = source_fast5_dir
def on_created(self, event):
print("Fast5 created!: {}".format(event.src_path))
# copy to local dir
fast5_dir = os.getcwd() + "/lamprey_results/fast5"
fastq_dir = os.getcwd() + "/lamprey_results/fastq"
process_list_path = os.getcwd() + '/lamprey_results/process_list.txt'
filename = event.src_path.split('/')[-1]
shutil.copyfile(event.src_path, fast5_dir + "/" + filename)
# make a processing list
f = open(process_list_path, 'w')
f.write(filename)
f.close()
# basecall
dirname = os.path.dirname(__file__)
if args.watchdog_barcode is not '':
basecall_script_path = os.path.join(dirname, 'scripts/basecall_barcoded_fast5.sh')
else:
basecall_script_path = os.path.join(dirname, 'scripts/basecall_fast5.sh')
subprocess.run([basecall_script_path, fast5_dir, fastq_dir, process_list_path])
####
class FastqHandler(PatternMatchingEventHandler):
def __init__(self, primers, ref_vcf_record, target_vcf_record, sw, minimap2, args, file_count=0, id_counter=0):
PatternMatchingEventHandler.__init__(self, patterns=['*.fastq'], ignore_directories=True, case_sensitive=True)
self.primers = primers
self.ref_vcf_record = ref_vcf_record
self.target_vcf_record = target_vcf_record
self.args = args
self.minimap2 = minimap2
self.sw = sw
self.file_count = file_count
self.id_counter = id_counter
self.results = Results(self.ref_vcf_record, self.target_vcf_record)
# check to see if a file was created as a fastq in this directory
def on_created(self, event):
self.process_file(event.src_path)
# check to see if a file was renamed or moved to target directory as a fastq
def on_moved(self, event):
self.process_file(event.dest_path)
def process_file(self, event_path):
#print("FASTQ created: {}".format(event.src_path))
self.file_count += 1
# if not included, file creation might trigger event handler before the file is finished being written
time.sleep(0.1)
# parse lamplicons
raw_lamplicons = SeqIO.parse(event_path, "fastq")
handle = open(event_path)
lines = handle.readlines()
#print("FILE LENGTH: ", len(lines))
handle.close()
# process each one
# give each lamplicon an id
lamplicons = []
for lamplicon in raw_lamplicons:
lamplicons.append((self.id_counter, lamplicon))
self.id_counter += 1
#print(self.id_counter, lamplicon.seq)
#print(" * found {} reads.".format(len(lamplicons)), self.id_counter)
# process the batch
# get file directory for relative script paths
dirname = os.path.dirname(__file__)
process_candidates_path = os.path.join(dirname, 'scripts/process_candidates.sh')
generate_consensus_path = os.path.join(dirname, 'scripts/generate_consensus.sh')
os.makedirs(args.output_dir, exist_ok=True)
for lamp_idx,lamplicon in lamplicons:
#print_green("Processing Lamplicon {} \r".format(lamp_idx + 1))
timestamp = parseTimestamp(lamplicon.description.split()[5].split('=')[1])
result = processLamplicon(self.sw,
process_candidates_path,
generate_consensus_path,
self.minimap2,
lamp_idx,
lamplicon,
self.primers,
self.ref_vcf_record,
self.target_vcf_record,
self.args);
# add to list of results
result.read_id = lamplicon.name
result.idx = lamp_idx
result.timestamp = timestamp
#self.results.append(result)
#
self.results = processResultsOnline(self.results, result)
def print_file_count(self):
print(self.file_count)
##########################
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 cigarStringToTuples(cigar):
'''
Converts a cigar string to a pysam endocded list of cigar tuples.
'''
tuples = list()
# walk the cigar string
is_numeric = True
count_str = ''
for i in range(len(cigar)):
if cigar[i].isnumeric():
count_str += cigar[i]
else:
op = cigarOpMap[cigar[i]]
count = int(count_str)
tuples.append((op,count))
count_str = ''
return tuples
#######
def getVAF(calls, ref, mut):
VAF = 0.0
if calls[mut] + calls[ref] > 0:
VAF = float(calls[mut])/float(calls[mut] + calls[ref]) * 100.0
return VAF
#######
def alignSequence_swalign(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 alignSequence_skbio(seq, primer, primer_name):
'''
Aligns two sequences using the skbio Smith-Waterman library.
'''
query = StripedSmithWaterman(primer)
alignment = query(str(seq))
# compute matches between aligned query/target
matches = 0
for i in range(0, len(alignment.aligned_query_sequence)):
if alignment.aligned_query_sequence[i] == alignment.aligned_target_sequence[i] :
matches = matches + 1
identity = float(matches)/float(len(primer))
ret_alignment = Alignment(alignment.target_begin,
alignment.target_end_optimal + 1,
identity,
primer_name)
return ret_alignment
#######
def findPrimerAlignments(aligner, seq, primer, primer_name, identity_threshold, args):
'''
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
#print("*")
#
#print(alignment)
if args.swalign:
alignment = alignSequence_swalign(aligner, seq, primer, primer_name)
else:
alignment = alignSequence_skbio(seq, primer, primer_name)
#print(alignment)
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, args)
alignment_list.extend(left_alignments)
# recurse right
if len(right_seq) >= len(primer):
right_alignments = findPrimerAlignments(
aligner, right_seq, primer, primer_name, identity_threshold, args)
# 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 = aligner.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, args))
alignment_list.extend(findPrimerAlignments(aligner, seq, rc(primers.primer_dict["T"]), "Tc", identity_threshold, args))
# bail if we didn't find a target in this read
# this is a lazy shortcut optimization
# high confidence mode raises the bar for the number of targets considered
#if len(alignment_list) < args.confidence_level:
# 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, args))
# rc
alignment_list.extend(findPrimerAlignments(aligner, seq, rc(primer_seq), primer_name + "c", identity_threshold, args))
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 == 'F3':
color = '\u001b[38;5;4;7m'
elif primer_string == 'F3c':
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 == 'B3':
color = '\u001b[38;5;1;7m'
elif primer_string == 'B3c':
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 primer counter goes below zero, break
if primer_counter < 0:
break
if all_matched:
amplicon_start = 0
return amplicon_start, amplicon_end