forked from arpcard/rgi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBWT.py
1665 lines (1443 loc) · 60.8 KB
/
BWT.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
from app.settings import *
import csv, glob
from multiprocessing import Pool
import time
import statistics
class BWT(object):
"""
Class to align metagenomic reads to CARD and wildCARD reference using bwa or bowtie2 and
provide reports (gene, allele report and read level reports).
"""
def __init__(self, aligner, include_wildcard, include_baits, read_one, read_two, threads, output_file, debug, clean, local_database, mapq, mapped, coverage):
"""Creates BWT object."""
self.aligner = aligner
self.read_one = read_one
self.read_two = read_two
self.threads = threads
self.output_file = output_file
self.local_database = local_database
self.db = path
self.data = data_path
self.include_wildcard = include_wildcard
self.include_baits = include_baits
self.mapq = mapq
self.mapped = mapped
self.coverage = coverage
if self.local_database:
self.db = LOCAL_DATABASE
self.data = LOCAL_DATABASE
# index dbs
self.indecies_directory = os.path.join(self.db,"bwt")
logger.info("card")
self.reference_genome = os.path.join(self.data, "card_reference.fasta")
self.index_directory_bowtie2 = os.path.join(self.db, self.indecies_directory, "card_reference", "{}".format("bowtie2"))
self.index_directory_kma = os.path.join(self.db, self.indecies_directory, "card_reference", "{}".format("kma"))
self.index_directory_bwa = os.path.join(self.db, self.indecies_directory, "card_reference", "{}".format("bwa"))
if self.include_baits == True:
logger.info("baits")
self.reference_genome_baits = os.path.join(self.data, "baits_reference.fasta")
self.index_directory_bowtie2_baits = os.path.join(self.db, self.indecies_directory, "baits_reference", "{}".format("bowtie2_baits"))
self.index_directory_bwa_baits = os.path.join(self.db, self.indecies_directory, "baits_reference", "{}".format("bwa_baits"))
# card and variants
if self.include_wildcard == True:
logger.info("card variants")
self.reference_genome = os.path.join(self.data, "card_wildcard_reference.fasta")
self.index_directory_bowtie2 = os.path.join(self.db, self.indecies_directory, "card_wildcard_reference", "{}".format("bowtie2"))
self.index_directory_bwa = os.path.join(self.db, self.indecies_directory, "card_wildcard_reference", "{}".format("bwa"))
# outputs
self.working_directory = os.path.join(os.getcwd())
self.output_sam_file = os.path.join(self.working_directory, "{}.temp.sam".format(self.output_file))
self.output_sam_file_baits = os.path.join(self.working_directory, "{}.baits.temp.sam".format(self.output_file))
self.output_bam_file = os.path.join(self.working_directory, "{}.temp.bam".format(self.output_file))
self.output_bam_file_baits = os.path.join(self.working_directory, "{}.baits.temp.bam".format(self.output_file))
self.output_bam_sorted_file = os.path.join(self.working_directory, "{}.sorted.temp.bam".format(self.output_file))
self.sorted_bam_sorted_file_length_100 = os.path.join(self.working_directory, "{}.sorted.length_100.bam".format(self.output_file))
self.unmapped = os.path.join(self.working_directory, "{}.unmapped.temp.bam".format(self.output_file))
self.mapped = os.path.join(self.working_directory, "{}.mapped.temp.bam".format(self.output_file))
self.mapping_overall_stats = os.path.join(self.working_directory, "{}.overall_mapping_stats.txt".format(self.output_file))
self.mapping_artifacts_stats = os.path.join(self.working_directory, "{}.artifacts_mapping_stats.txt".format(self.output_file))
self.mapping_reference_stats = os.path.join(self.working_directory, "{}.reference_mapping_stats.txt".format(self.output_file))
self.mapping_baits_stats = os.path.join(self.working_directory, "{}.baits_mapping_stats.txt".format(self.output_file))
self.baits_reads_count = os.path.join(self.working_directory, "{}.baits_reads_count.temp.txt".format(self.output_file))
self.reads_baits_count = os.path.join(self.working_directory, "{}.reads_baits_count.temp.txt".format(self.output_file))
self.aro_term_reads = os.path.join(self.working_directory, "{}.aro_term_reads.temp.txt".format(self.output_file))
self.output_tab = os.path.join(self.working_directory, "{}.temp.txt".format(self.output_file))
self.output_tab_sequences = os.path.join(self.working_directory, "{}.seqs.temp.txt".format(self.output_file))
self.output_tab_coverage = os.path.join(self.working_directory, "{}.coverage.temp.txt".format(self.output_file))
self.output_tab_coverage_all_positions = os.path.join(self.working_directory, "{}.coverage_all_positions.temp.txt".format(self.output_file))
self.output_tab_coverage_all_positions_summary = os.path.join(self.working_directory, "{}.coverage_all_positions.summary.temp.txt".format(self.output_file))
self.model_species_data_type = os.path.join(self.working_directory, "{}.model_species_data_type.temp.txt".format(self.output_file))
self.allele_mapping_data_json = os.path.join(self.working_directory, "{}.allele_mapping_data.json".format(self.output_file))
self.allele_mapping_data_tab = os.path.join(self.working_directory, "{}.allele_mapping_data.txt".format(self.output_file))
self.gene_mapping_data_tab = os.path.join(self.working_directory, "{}.gene_mapping_data.txt".format(self.output_file))
self.baits_mapping_data_tab = os.path.join(self.working_directory, "{}.baits_mapping_data.temp.txt".format(self.output_file))
self.baits_mapping_data_json = os.path.join(self.working_directory, "{}.baits_mapping_data.temp.json".format(self.output_file))
self.reads_mapping_data_json = os.path.join(self.working_directory, "{}.reads_mapping_data.temp.json".format(self.output_file))
# map baits to complete genes
self.baits_card_sam = os.path.join(self.working_directory, "{}.baits_card.temp.sam".format(self.output_file))
self.baits_card_bam = os.path.join(self.working_directory, "{}.baits_card.temp.bam".format(self.output_file))
self.baits_card_tab = os.path.join(self.working_directory, "{}.baits_card.temp.txt".format(self.output_file))
self.baits_card_json = os.path.join(self.working_directory, "{}.baits_card.temp.json".format(self.output_file))
self.baits_card_data_tab = os.path.join(self.working_directory, "{}.baits_card_data.temp.txt".format(self.output_file))
self.card_baits_reads_count_json = os.path.join(self.working_directory, "{}.card_baits_reads_count.temp.json".format(self.output_file))
self.debug = debug
self.clean = clean
if self.debug:
logger.setLevel(10)
def __repr__(self):
"""Returns BWT class full object."""
return "BWT({}".format(self.__dict__)
def clean_files(self):
"""Cleans temporary files."""
if self.clean == True:
basename_output_file = os.path.splitext(os.path.basename(self.output_file))[0]
logger.info("Cleaning up temporary files...{}".format(basename_output_file))
# clean working_directory
self.clean_directory(self.working_directory, basename_output_file)
d_name, f_name = os.path.split(self.output_file)
# clean destination_directory
self.clean_directory(d_name, basename_output_file)
else:
logger.info("Clean up skipped.")
def clean_directory(self, directory, basename_output_file):
"""Cleans files in directory."""
logger.info(directory)
files = glob.glob(os.path.join(directory, "*"))
for f in files:
if os.path.basename(self.output_file) in f and ".temp" in f and os.path.isfile(f):
self.remove_file(f)
def remove_file(self, f):
"""Removes file."""
if os.path.exists(f):
try:
logger.info("Removed file: {}".format(f))
os.remove(f)
except Exception as e:
raise e
else:
logger.warning("Missing file: {}".format(f))
def create_index(self, index_directory, reference_genome):
"""
Create bwa or bowtie2 index for reference genome
"""
if self.aligner == "bowtie2":
if not os.path.exists(index_directory):
os.makedirs(index_directory)
logger.info("created index at {}".format(index_directory))
os.system("bowtie2-build --quiet {reference_genome} {index_directory} --threads {threads}".format(
index_directory=index_directory,
reference_genome=reference_genome,
threads=self.threads
)
)
elif self.aligner == "kma":
if not os.path.exists(index_directory):
os.makedirs(index_directory)
logger.info("created index at {}".format(index_directory))
os.system("kma index -i {reference_genome} -o {index_directory}".format(
index_directory=index_directory,
reference_genome=reference_genome
)
)
else:
if not os.path.exists(index_directory):
os.makedirs(index_directory)
logger.info("created index at {}".format(index_directory))
os.system("bwa index -p {index_directory} {reference_genome}".format(
index_directory=index_directory,
reference_genome=reference_genome
)
)
def align_kma(self, reference_genome, index_directory, output_sam_file):
"""
Align paired reads to card or wildcard
"""
self.check_index(index_directory=index_directory, reference_genome=reference_genome)
logger.info("align reads -ipe {} {} to {}".format(self.read_one, self.read_two, reference_genome))
cmd = "kma -ex_mode -1t1 -ipe {read_one} {read_two} -t_db {index_directory} -o {output_sam_file}.temp -sam > {output_sam_file}".format(
threads=self.threads,
index_directory=index_directory,
read_one=self.read_one,
read_two=self.read_two,
output_sam_file=output_sam_file
)
os.system(cmd)
def align_kma_interleaved(self, reference_genome, index_directory, output_sam_file):
"""
Align paired reads to card or wildcard
"""
self.check_index(index_directory=index_directory, reference_genome=reference_genome)
logger.info("align reads -ipe {} {} to {}".format(self.read_one, self.read_two, reference_genome))
cmd = "kma -ex_mode -1t1 -int {read_one} -t_db {index_directory} -o {output_sam_file}.temp -sam > {output_sam_file}".format(
threads=self.threads,
index_directory=index_directory,
read_one=self.read_one,
read_two=self.read_two,
output_sam_file=output_sam_file
)
os.system(cmd)
def align_bowtie2_unpaired(self, reference_genome, index_directory, output_sam_file):
"""
Align unpaired reads to card or wildcard
"""
self.check_index(index_directory=index_directory, reference_genome=reference_genome)
cmd = "bowtie2 --very-sensitive-local --threads {threads} -x {index_directory} -U {unpaired_reads} -S {output_sam_file}".format(
threads=self.threads,
index_directory=index_directory,
unpaired_reads=self.read_one,
output_sam_file=output_sam_file
)
os.system(cmd)
def align_bowtie2(self, reference_genome, index_directory, output_sam_file):
"""
Align paired reads to card or wildcard
"""
self.check_index(index_directory=index_directory, reference_genome=reference_genome)
logger.info("align reads -1 {} -2 {} to {}".format(self.read_one, self.read_two, reference_genome))
cmd = "bowtie2 --quiet --very-sensitive-local --threads {threads} -x {index_directory} -1 {read_one} -2 {read_two} -S {output_sam_file}".format(
threads=self.threads,
index_directory=index_directory,
read_one=self.read_one,
read_two=self.read_two,
output_sam_file=output_sam_file
)
os.system(cmd)
def align_bowtie2_baits_to_genes(self, reference_genome, index_directory, output_sam_file):
"""
Align baits to genes
"""
self.check_index(index_directory=index_directory, reference_genome=reference_genome)
logger.info("align baits -f {} to complete genes in {}".format(self.reference_genome_baits, reference_genome))
cmd = "bowtie2 --quiet --very-sensitive-local --threads {threads} -x {index_directory} -f {unpaired_reads} -S {output_sam_file}".format(
threads=self.threads,
index_directory=index_directory,
unpaired_reads=self.reference_genome_baits,
output_sam_file=output_sam_file
)
os.system(cmd)
def align_bwa_single_end_mapping(self, reference_genome, index_directory, output_sam_file):
"""
Align unpaired reads to reference genome using bwa
"""
self.check_index(index_directory=index_directory, reference_genome=reference_genome)
os.system("bwa mem -M -t {threads} {index_directory} {read_one} > {output_sam_file}".format(
threads=self.threads,
index_directory=index_directory,
read_one=self.read_one,
output_sam_file=output_sam_file
)
)
def align_bwa_paired_end_mapping(self, reference_genome, index_directory, output_sam_file):
"""
Align paired reads to reference genome using bwa
"""
self.check_index(index_directory=index_directory, reference_genome=reference_genome)
os.system("bwa mem -t {threads} {index_directory} {read_one} {read_two} > {output_sam_file}".format(
threads=self.threads,
index_directory=index_directory,
read_one=self.read_one,
read_two=self.read_two,
output_sam_file=output_sam_file
)
)
def convert_sam_to_bam(self, input_sam_file, output_bam_file):
"""
Convert sam file to bam file
"""
os.system("samtools view --threads {threads} -b {input_sam_file} > {output_bam_file}".format(
threads=self.threads,
output_bam_file=output_bam_file,
input_sam_file=input_sam_file
)
)
def sort_bam(self):
"""
Sort bam file
"""
os.system("samtools sort --threads {threads} -T {output_file}.sorted -o {sorted_bam_file} {unsorted_bam_file}".format(
threads=self.threads,
output_file=self.output_file,
unsorted_bam_file=self.output_bam_file,
sorted_bam_file=self.output_bam_sorted_file
)
)
def index_bam(self, bam_file):
"""
Index input bam file using 'samtools index' function
"""
os.system("samtools index {input_bam}".format(input_bam=bam_file))
def extract_alignments_with_length(self, length=10, map_quality=2):
"""
Get alignments from bam file using length as a filter (default length=10, map_quality=2)
TODO:: add filters (mapped, length, coverage and map_quality)
"""
cmd="bamtools filter -in {input_bam} -out {output_bam}".format(
input_bam=self.output_bam_sorted_file,
output_bam=self.sorted_bam_sorted_file_length_100,
length=length,
map_quality=map_quality
)
# logger.debug(cmd)
os.system(cmd)
def get_aligned(self):
"""
Get stats for aligned reads using 'samtools idxstats' function
"""
cmd = "samtools idxstats {input_bam} > {output_tab}".format(
input_bam=self.sorted_bam_sorted_file_length_100,
output_tab=self.output_tab
)
os.system(cmd)
def get_qname_rname_sequence(self):
"""
MAPQ (mapping quality - describes the uniqueness of the alignment, 0=non-unique, >10 probably unique) | awk '$5 > 0'
"""
cmd="samtools view --threads {threads} {input_bam} | cut -f 1,2,3,4,5,7 | sort -s -n -k 1,1 > {output_tab}".format(
threads=self.threads,
input_bam=self.sorted_bam_sorted_file_length_100,
output_tab=self.output_tab_sequences
)
os.system(cmd)
def get_coverage(self):
"""
Get coverage using 'samtools depth' function and write outputs to a tab-delimited file
"""
cmd="samtools depth {sorted_bam_file} > {output_tab}".format(
sorted_bam_file=self.sorted_bam_sorted_file_length_100,
output_tab=self.output_tab_coverage
)
os.system(cmd)
def get_coverage_all_positions(self):
"""
Get converage for all positions using 'genomeCoverageBed -ibam' function
BAM file _must_ be sorted by position
By default, bedtools genomecov will compute a histogram of coverage for the genome file provided. The default output format is as follows:
1. chromosome (or entire genome)
2. depth of coverage from features in input file
3. number of bases on chromosome (or genome) with depth equal to column 2.
4. size of chromosome (or entire genome) in base pairs
5. fraction of bases on chromosome (or entire genome) with depth equal to column 2.
"""
cmd = "bedtools genomecov -ibam {sorted_bam_file} > {output_tab}".format(
sorted_bam_file=self.sorted_bam_sorted_file_length_100,
output_tab=self.output_tab_coverage_all_positions
)
os.system(cmd)
os.system("cat {output_tab} | awk '$2 > 0' | cut -f1,3,4,5 > {output_file}".format(
output_tab=self.output_tab_coverage_all_positions,
output_file=self.output_tab_coverage_all_positions_summary
)
)
def get_baits_count(self):
"""
TODO:: Get baits count
"""
pass
def get_reads_count(self):
"""
Parse tab-delimited file for read counts to a dictionary
"""
sequences = {}
with open(self.output_tab, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter='\t', quotechar='|')
for row in reader:
if int(row[2]) > 0:
sequences[row[0]] = {
"mapped": row[2],
"unmapped": row[3],
"all": format(sum(map(int, [row[2], row[3]])))
}
# write file reference_stats
with open(self.mapping_reference_stats, "w") as out:
out.write("**********************************************\n")
out.write("Stats for Reference: \n")
out.write("**********************************************\n")
out.write("\n")
out.write("how many reference terms (or ARO terms): {}\n\n".format(len(sequences.keys())))
return sequences
def get_model_details(self, by_accession=False):
"""
Parse card.json to get each model details
"""
models = {}
try:
with open(os.path.join(self.data, "card.json"), 'r') as jfile:
data = json.load(jfile)
except Exception as e:
logger.error("{}".format(e))
exit()
for i in data:
if i.isdigit():
categories = {}
taxon = []
if "model_sequences" in data[i]:
for item in data[i]["model_sequences"]["sequence"]:
taxa = " ".join(data[i]["model_sequences"]["sequence"][item]["NCBI_taxonomy"]["NCBI_taxonomy_name"].split()[:2])
if taxa not in taxon:
taxon.append(taxa)
for c in data[i]["ARO_category"]:
if data[i]["ARO_category"][c]["category_aro_class_name"] not in categories.keys():
categories[data[i]["ARO_category"][c]["category_aro_class_name"]] = []
if data[i]["ARO_category"][c]["category_aro_name"] not in categories[data[i]["ARO_category"][c]["category_aro_class_name"]]:
categories[data[i]["ARO_category"][c]["category_aro_class_name"]].append(data[i]["ARO_category"][c]["category_aro_name"])
if by_accession == False:
models[data[i]["model_id"]] = {
"model_id": data[i]["model_id"],
"ARO_accession": data[i]["ARO_accession"],
"model_name": data[i]["model_name"],
"model_type": data[i]["model_type"],
"categories": categories,
"taxon": taxon
}
else:
models[data[i]["ARO_accession"]] = {
"model_id": data[i]["model_id"],
"ARO_accession": data[i]["ARO_accession"],
"model_name": data[i]["model_name"],
"model_type": data[i]["model_type"],
"categories": categories,
"taxon": taxon
}
return models
def get_variant_details(self):
"""
Parse tab-delimited to a dictionary for all variants
"""
os.system("cat {index_file} | cut -f1,2,6,7,8,9,10 | sort > {output_file}".format(
index_file=os.path.join(self.data, "index-for-model-sequences.txt"),
output_file=self.model_species_data_type
)
)
variants = {}
# prevalence_sequence_id model_id accession species_name data_type rgi_criteria percent_identity
# 10687 2882 FBHN01 Campylobacter coli ncbi_contig Strict 67.71
# 0 1 2 3 4 5 6
'''
1031: { # model_id
'1280': { # prevalence_sequence_id
0: { # ncbi accession
data_type: "ncbi_contig",
percent_identity: "99.64",
rgi_criteria: "Strict",
species_name: 'Escherichia coli'
}
},
'438': { # prevalence_sequence_id
0: { # ncbi accession
data_type: "ncbi_contig",
percent_identity: "99.64",
rgi_criteria: "Strict",
species_name: 'Klebsiella pneumoniae'
}
},
}
'''
# prevalence_sequence_id model_id species_name accession data_type rgi_criteria percent_identity
# 10687 2882 Campylobacter coli FBHN01 ncbi_contig Strict 67.71
# 0 1 2 3 4 5 6
with open(self.model_species_data_type, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter='\t', quotechar='|')
for row in reader:
# add new model
if row[1] not in variants.keys():
variants.update({
row[1]: { # model_id
row[0]: { # prevalence_sequence_id
row[3]: #accession
{
"data_type":row[4],
"rgi_criteria":row[5],
"percent_identity":row[6],
"species_name": row[2]
}
}
}
})
# update existing model
else:
# check if prev_id is present
if row[0] not in variants[row[1]].keys():
# new prevalence_sequence_id
variants[row[1]].update({
row[0]: { # prevalence_sequence_id
row[3]: #accession
{
"data_type":row[4],
"rgi_criteria":row[5],
"percent_identity":row[6],
"species_name": row[2]
}
}
})
else:
# new accession
variants[row[1]][row[0]].update({
row[3]: #accession
{
"data_type":row[4],
"rgi_criteria":row[5],
"percent_identity":row[6],
"species_name": row[2]
}
})
return variants
def get_baits_details(self):
"""
Parse index file to a dictionary for all baits
"""
baits = {}
# 0 1 2 3 4 5 6 7
# ProbeID, GeneID, TaxaID, ARO, ProbeSeq, Upstream, Downstream,RevComp
with open(os.path.join(self.data, "baits-probes-with-sequence-info.txt"), 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in reader:
if row[0] != "ProbeID":
baits.update({
"{}|{}".format(row[0],row[3]): {
"ProbeID": row[0],
"GeneID":row[1],
"TaxaID":row[2],
"ARO": row[3],
"ProbeSeq":row[4],
"Upstream": row[5],
"Downstream": row[6],
"RevComp": row[7]
}
})
return baits
def get_alignments(self, hit_id, ref_len=0):
"""
Parse tab-delimited file into dictionary for mapped reads
"""
sequences = []
with open(self.output_tab_sequences, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter='\t', quotechar='|')
for row in reader:
if hit_id == row[2]:
sequences.append({
"qname": str(row[0]),
"flag": str(row[1]),
"rname": str(row[2]),
"pos": str(row[3]),
"mapq": str(row[4]),
"mrnm": str(row[5])
})
return sequences
def get_coverage_details(self, hit_id):
"""
Parse tab-delimited file
"""
sequences = {}
sequences.update({
hit_id: {
"covered": 0,
"uncovered": 0,
"length": 0
}
})
with open(self.output_tab_coverage_all_positions_summary, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter='\t', quotechar='|')
for row in reader:
if hit_id == row[0]:
sequences[hit_id]["covered"] = sequences[hit_id]["covered"] + int(row[1])
sequences[hit_id]["length"] = int(row[2])
sequences[hit_id]["uncovered"] = sequences[hit_id]["length"] - sequences[hit_id]["covered"]
return sequences
def filter_count_reads(self, is_mapped="false", length=""):
"""
Filter reads using mapQuality, length and isMapped
TODO:: Review to remove / include
"""
read_one=os.path.join(self.working_directory, "{}.R1.fastq".format(self.output_file))
read_two=os.path.join(self.working_directory, "{}.R2.fastq".format(self.output_file))
options = ""
if length:
options = options + " -length >={}".format(length)
if self.mapq:
options = options + " -mapQuality >={}".format(self.mapq)
filter_cmd = "bamtools filter -in {in_bam} -out {out_bam} -isMapped {is_mapped} {options}".format(
in_bam=self.sorted_bam_sorted_file_length_100,
out_bam=self.mapped,
is_mapped=is_mapped,
options=options
)
os.system(filter_cmd)
# bedtools bamtobed -i trimmedreadstocardvslamq35l40.bam > trimmedreadstocardvslamq35l40.bed
os.system("bedtools bamtobed -i {} > out.bed".format(self.mapped))
extract_cmd = "samtools fastq -1 {read_one} -2 {read_two} {in_bam}".format(
read_one=read_one,
read_two=read_two,
in_bam=self.mapped
)
os.system(extract_cmd)
read_one_count_cmd = "awk '{c}' {read_one}".format(
c="{s++}END{print s/4}",
read_one=read_one
)
read_two_count_cmd = "awk '{c}' {read_two}".format(
c="{s++}END{print s/4}",
read_two=read_two
)
return os.popen(read_one_count_cmd).readlines()[0].strip("\n") , os.popen(read_two_count_cmd).readlines()[0].strip("\n")
def get_stats(self):
"""
Get stats using 'bamtools stats' and 'samtools flagstat' function
"""
'''
stats = {
"mapped": {
"read_one": 0,
"read_two": 0
},
"unmapped": {
"read_one": 0,
"read_two": 0
}
}
# unmapped
unmapped = self.filter_count_reads()
stats["unmapped"]["read_one"] = unmapped[0]
stats["unmapped"]["read_two"] = unmapped[1]
# mapped
# max mapQuality for bowtie2 is 42
# max mapQuality for bwa is 37
# see http://www.acgt.me/blog/2014/12/16/understanding-mapq-scores-in-sam-files-does-37-42
mapped = self.filter_count_reads(is_mapped="true")
stats["mapped"]["read_one"] = mapped[0]
stats["mapped"]["read_two"] = mapped[1]
logger.info("count reads {}".format(json.dumps(stats,indent=2)))
'''
# overall stats for mapping
cmd_overall = "bamtools stats -in {} > {}".format(self.sorted_bam_sorted_file_length_100 , self.mapping_overall_stats)
# logger.info("overall mapping stats using {}".format(cmd_overall))
os.system(cmd_overall)
# stats showing duplicates
# write file reference_stats
with open(self.mapping_artifacts_stats, "w") as out:
out.write("**********************************************\n")
out.write("Stats for Artifacts: \n")
out.write("**********************************************\n")
out.write("\n")
cmd_artifacts = "samtools flagstat {} >> {}".format(self.sorted_bam_sorted_file_length_100 , self.mapping_artifacts_stats)
# logger.info("mapping artifacts stats i.e duplicates using {}".format(cmd_artifacts))
os.system(cmd_artifacts)
def find_between(s, start, end):
return (s.split(start))[1].split(end)[0]
def probes_stats(self, baits_card):
stats = {}
baits = {}
with open(self.baits_mapping_data_tab, "r") as f2:
reader=csv.reader(f2,delimiter='\t')
for row in reader:
if "ARO" in row[2]:
bait = row[2]
read = "{}|{}".format(row[0], row[1])
if bait not in baits.keys():
baits[bait] = [read]
else:
if read not in baits[bait]:
baits[bait].append(read)
aro_to_reads = {}
for m in baits:
aro = (m.split("|ARO:"))[1].split( "|")[0]
if "|ARO:{}|".format(aro) in m:
for r in baits[m]:
if aro in aro_to_reads.keys():
if r not in aro_to_reads[aro]:
aro_to_reads[aro].append(r)
else:
aro_to_reads[aro] = [r]
with open(self.aro_term_reads, "w") as tab_out3:
writer = csv.writer(tab_out3, delimiter='\t', dialect='excel')
writer.writerow([
"ARO",
"Number of Mapped Reads to baits"
])
for aro in aro_to_reads:
writer.writerow([aro, len(aro_to_reads[aro])])
with open(self.baits_mapping_data_json, "w") as outfile:
json.dump(baits, outfile)
reads_to_baits = {}
for i in baits.keys():
for j in baits[i]:
t = i
if j not in reads_to_baits.keys():
reads_to_baits[j] = [t]
else:
if t not in reads_to_baits[j]:
reads_to_baits[j].append(t)
with open(self.reads_mapping_data_json, "w") as outfile2:
json.dump(reads_to_baits, outfile2)
with open(self.baits_reads_count, "w") as tab_out2:
writer = csv.writer(tab_out2, delimiter='\t', dialect='excel')
writer.writerow([
"Bait",
"Number of Mapped Reads"
])
for item in baits:
writer.writerow([item, len(baits[item])])
probe_reads_count = {}
with open(self.baits_reads_count, 'r') as csv_file:
for row in csv.reader(csv_file, delimiter='\t'):
probe_reads_count[row[0]] = row[1]
data_out = {}
for i in baits_card:
data_out[i] = {}
for k in baits_card[i]:
probe_dict = k.split("|")
probe = "|".join(probe_dict[:-1])
if probe in probe_reads_count.keys():
data_out[i].update({k : int(probe_reads_count[probe])})
else:
data_out[i].update({k : 0})
with open(self.card_baits_reads_count_json, "w") as af:
af.write(json.dumps(data_out,sort_keys=True))
with open(self.reads_baits_count, "w") as tab_out2:
writer = csv.writer(tab_out2, delimiter='\t', dialect='excel')
writer.writerow([
"Read",
"Baits"
])
for item in reads_to_baits:
writer.writerow([item,
"; ".join(reads_to_baits[item])
])
with open(self.baits_mapping_data_tab, "r") as f2:
reader=csv.reader(f2,delimiter='\t')
for row in reader:
if "ARO" in row[2]:
term = row[2].split("|")[4]
name = row[2].split("|")[5]
probe = row[2]
probe_ok = False
for k in baits_card.keys():
if term in k:
matching = [s for s in baits_card[k] if probe in s]
if matching:
probe_ok = True
if probe_ok == True:
if term not in stats.keys():
# read reference fasta to count baits used
cmd = "cat {} | grep -c \"|{}|\"".format(self.reference_genome_baits,term)
cmd2 = "cat {} | grep -c \"|{}|\"".format(self.reads_baits_count,term)
stats[term] = {
"aro_name": name,
"total_baits": int(self.count_probes(cmd)),
"read_count": int(self.count_probes(cmd2)),
"mapped_baits": {
probe: len(baits[probe])
}
}
else:
if probe not in stats[term]["mapped_baits"].keys():
stats[term]["mapped_baits"].update({probe: len(baits[probe]) })
# write tab for probes and mapped probes
with open(self.mapping_baits_stats, "w") as tab_out:
writer = csv.writer(tab_out, delimiter='\t', dialect='excel')
writer.writerow([
"ARO Term",
"ARO Accession",
"Number of Baits",
"Number of Mapped Baits with Reads",
"Number of Reads Mapped to Baits",
"Average Number of reads per Bait",
"Number of reads per Bait Coefficient of Variation (%)"
])
'''
Coefficient of variation = (Standard Deviation / Mean ) * 100
- ratio of the standard devitation to the mean
| - | Number of Probes | Mapped Probes |
| -------- | -------- | ------------ |
| Mean | 57 | 22 |
| std_dev | 38 | 31 |
| CV | 66.67% | 140.91% |
# note - probes with >0 mapping were considered
'''
for i in stats:
accession, baits_count, baits_with_reads_count, reads_count, sample = self.get_counts(i, data_out)
standard_devitation = 0
coefficient_of_variation = 0
try:
standard_devitation = statistics.stdev(sample)
except Exception as e:
print(stats[i]["aro_name"], sample, e)
mean = statistics.mean(sample)
if mean > 0:
coefficient_of_variation = (standard_devitation / mean) * 100
writer.writerow([
stats[i]["aro_name"],
i,
baits_count,
baits_with_reads_count,
reads_count,
format(mean,'.2f'),
format(coefficient_of_variation,'.2f')
])
def get_counts(self, accession, data_out):
baits_count = 0
baits_with_reads_count = 0
reads_count = 0
sample = []
for i in data_out:
if accession in i:
baits_count = len(data_out[i])
for c in data_out[i]:
reads_count = reads_count + int(data_out[i][c])
sample.append(int(data_out[i][c]))
if int(data_out[i][c]) > 0:
baits_with_reads_count = baits_with_reads_count + 1
return accession, baits_count, baits_with_reads_count, reads_count, sample
return accession, baits_count, baits_with_reads_count, reads_count, sample
def count_probes(self, cmd):
return os.popen(cmd).readlines()[0].strip("\n")
def baits_reads_counts(self, accession):
"""
Returns
number_of_mapped_baits,
number_of_mapped_baits_with_reads,
average_bait_coverage,
bait_coverage_coefficient_of_variation
"""
if self.include_baits == True:
with open(self.mapping_baits_stats, "r") as f2:
reader=csv.reader(f2,delimiter='\t')
for row in reader:
if "ARO Term" not in row[0]:
if accession in row[1]:
return row[2], row[3], row[4], row[6]
return 0, 0, 0, 0
else:
return 0, 0, 0, 0
def get_model_id(self, models_by_accession, alignment_hit):
model_id = ""
if alignment_hit[0:22] == "Prevalence_Sequence_ID" or alignment_hit[0:4] == "ARO:":
model_id = alignment_hit.split("|")[1].split(":")[1]
else:
accession = alignment_hit.split("|")[4].split(":")[1]
try:
model_id = models_by_accession[accession]["model_id"]
except Exception as e:
logger.warning("missing aro accession: {} for alignment {} -> {}".format(accession,alignment_hit,e))
return model_id
def summary(self, alignment_hit, models, variants, baits, reads, models_by_accession):
start = time.time()
# logger.debug(alignment_hit)
coverage = self.get_coverage_details(alignment_hit)
model_id = self.get_model_id(models_by_accession, alignment_hit)
try:
alignments = self.get_alignments(alignment_hit)
mapq_l = []
mate_pair = []
mapq_average = 0
for a in alignments:
mapq_l.append(int(a["mapq"]))
if a["mrnm"] != "=" and a["mrnm"] not in mate_pair:
if "ARO:{}".format(models[model_id]["ARO_accession"]) not in a["mrnm"]:
mate_pair.append(a["mrnm"])
if len(mapq_l) > 0:
mapq_average = sum(mapq_l)/len(mapq_l)
observed_in_genomes = "no data"
observed_in_plasmids = "no data"
prevalence_sequence_id = ""
observed_data_types = []
# range_of_reference_allele_source = []
percent_identity = 0.0
# Genus and species level only (only get first two words)
observed_in_pathogens = []
database = "CARD"
reference_allele_source = "CARD curation"
# if variants and "Resistomes & Variants" in database and "ARO:" not in alignment_hit:
if "Prevalence_Sequence_ID" in alignment_hit:
database = "Resistomes & Variants"
# logger.debug("model_id: {}, alignment_hit: {}".format(model_id, alignment_hit))
if model_id in variants.keys():
_accession = ""
for s in variants[model_id]:
prevalence_sequence_id = alignment_hit.split("|")[0].split(":")[-1]
observed_in_genomes = "NO"
observed_in_plasmids = "NO"
for accession in variants[model_id][prevalence_sequence_id]:
_accession = accession
if variants[model_id][prevalence_sequence_id][accession]["data_type"] not in observed_data_types:
observed_data_types.append(variants[model_id][prevalence_sequence_id][accession]["data_type"])
if variants[model_id][prevalence_sequence_id][accession]["species_name"] not in observed_in_pathogens:
observed_in_pathogens.append(variants[model_id][prevalence_sequence_id][accession]["species_name"].replace('"', ""))
if "Resistomes & Variants" in database:
if "ncbi_chromosome" in observed_data_types:
observed_in_genomes = "YES"
if "ncbi_plasmid" in observed_data_types: