-
Notifications
You must be signed in to change notification settings - Fork 67
/
read_utils.py
executable file
·1455 lines (1204 loc) · 57.2 KB
/
read_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
Utilities for working with sequence reads, such as converting formats and
fixing mate pairs.
"""
from __future__ import division
__author__ = "[email protected], [email protected]"
__commands__ = []
import argparse
import logging
import math
import os
import tempfile
import shutil
import sys
import concurrent.futures
from contextlib import contextmanager
import functools
from Bio import SeqIO
import pysam
import util.cmd
import util.file
import util.misc
from util.file import mkstempfname
import tools.bwa
import tools.cdhit
import tools.picard
import tools.samtools
import tools.mvicuna
import tools.prinseq
import tools.novoalign
import tools.gatk
log = logging.getLogger(__name__)
# =======================
# *** purge_unmated ***
# =======================
def purge_unmated(inFastq1, inFastq2, outFastq1, outFastq2, regex=r'^@(\S+)/[1|2]$'):
'''Use mergeShuffledFastqSeqs to purge unmated reads, and
put corresponding reads in the same order.
Corresponding sequences must have sequence identifiers
of the form SEQID/1 and SEQID/2.
'''
tempOutput = mkstempfname()
mergeShuffledFastqSeqsPath = os.path.join(util.file.get_scripts_path(), 'mergeShuffledFastqSeqs.pl')
cmdline = [mergeShuffledFastqSeqsPath, '-t', '-r', regex, '-f1', inFastq1, '-f2', inFastq2, '-o', tempOutput]
log.debug(' '.join(cmdline))
util.misc.run_and_print(cmdline, check=True)
shutil.move(tempOutput + '.1.fastq', outFastq1)
shutil.move(tempOutput + '.2.fastq', outFastq2)
return 0
def parser_purge_unmated(parser=argparse.ArgumentParser()):
parser.add_argument('inFastq1', help='Input fastq file; 1st end of paired-end reads.')
parser.add_argument('inFastq2', help='Input fastq file; 2nd end of paired-end reads.')
parser.add_argument('outFastq1', help='Output fastq file; 1st end of paired-end reads.')
parser.add_argument('outFastq2', help='Output fastq file; 2nd end of paired-end reads.')
parser.add_argument(
"--regex",
help="Perl regular expression to parse paired read IDs (default: %(default)s)",
default=r'^@(\S+)/[1|2]$'
)
util.cmd.common_args(parser, (('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, purge_unmated, split_args=True)
return parser
__commands__.append(('purge_unmated', parser_purge_unmated))
# ===============================
# *** index_fasta_samtools ***
# ===============================
def parser_index_fasta_samtools(parser=argparse.ArgumentParser()):
parser.add_argument('inFasta', help='Reference genome, FASTA format.')
util.cmd.common_args(parser, (('loglevel', None), ('version', None)))
util.cmd.attach_main(parser, main_index_fasta_samtools)
return parser
def main_index_fasta_samtools(args):
'''Index a reference genome for Samtools.'''
tools.samtools.SamtoolsTool().faidx(args.inFasta, overwrite=True)
return 0
__commands__.append(('index_fasta_samtools', parser_index_fasta_samtools))
# =============================
# *** index_fasta_picard ***
# =============================
def parser_index_fasta_picard(parser=argparse.ArgumentParser()):
parser.add_argument('inFasta', help='Input reference genome, FASTA format.')
parser.add_argument(
'--JVMmemory',
default=tools.picard.CreateSequenceDictionaryTool.jvmMemDefault,
help='JVM virtual memory size (default: %(default)s)'
)
parser.add_argument(
'--picardOptions',
default=[],
nargs='*',
help='Optional arguments to Picard\'s CreateSequenceDictionary, OPTIONNAME=value ...'
)
util.cmd.common_args(parser, (('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, main_index_fasta_picard)
return parser
def main_index_fasta_picard(args):
'''Create an index file for a reference genome suitable for Picard/GATK.'''
tools.picard.CreateSequenceDictionaryTool().execute(
args.inFasta, overwrite=True,
picardOptions=args.picardOptions,
JVMmemory=args.JVMmemory
)
return 0
__commands__.append(('index_fasta_picard', parser_index_fasta_picard))
# =============================
# *** mkdup_picard ***
# =============================
def parser_mkdup_picard(parser=argparse.ArgumentParser()):
parser.add_argument('inBams', help='Input reads, BAM format.', nargs='+')
parser.add_argument('outBam', help='Output reads, BAM format.')
parser.add_argument('--outMetrics', help='Output metrics file. Default is to dump to a temp file.', default=None)
parser.add_argument(
"--remove",
help="Instead of marking duplicates, remove them entirely (default: %(default)s)",
default=False,
action="store_true",
dest="remove"
)
parser.add_argument(
'--JVMmemory',
default=tools.picard.MarkDuplicatesTool.jvmMemDefault,
help='JVM virtual memory size (default: %(default)s)'
)
parser.add_argument(
'--picardOptions',
default=[],
nargs='*',
help='Optional arguments to Picard\'s MarkDuplicates, OPTIONNAME=value ...'
)
util.cmd.common_args(parser, (('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, main_mkdup_picard)
return parser
def main_mkdup_picard(args):
'''Mark or remove duplicate reads from BAM file.'''
opts = list(args.picardOptions)
if args.remove:
opts = ['REMOVE_DUPLICATES=true'] + opts
tools.picard.MarkDuplicatesTool().execute(
args.inBams, args.outBam,
args.outMetrics, picardOptions=opts,
JVMmemory=args.JVMmemory
)
return 0
__commands__.append(('mkdup_picard', parser_mkdup_picard))
# =============================
# *** revert_bam_picard ***
# =============================
def parser_revert_sam_common(parser=argparse.ArgumentParser()):
parser.add_argument('--clearTags', dest='clear_tags', default=False, action='store_true',
help='When supplying an aligned input file, clear the per-read attribute tags')
parser.add_argument("--tagsToClear", type=str, nargs='+', dest="tags_to_clear", default=["XT", "X0", "X1", "XA",
"AM", "SM", "BQ", "CT", "XN", "OC", "OP"],
help='A space-separated list of tags to remove from all reads in the input bam file (default: %(default)s)')
parser.add_argument(
'--doNotSanitize',
dest="do_not_sanitize",
action='store_true',
help="""When being reverted, picard's SANITIZE=true
is set unless --doNotSanitize is given.
Sanitization is a destructive operation that removes reads so the bam file is consistent.
From the picard documentation:
'Reads discarded include (but are not limited to) paired reads with missing mates, duplicated records,
records with mismatches in length of bases and qualities.'
For more information see:
https://broadinstitute.github.io/picard/command-line-overview.html#RevertSam
"""
)
try:
parser.add_argument(
'--JVMmemory',
default=tools.picard.RevertSamTool.jvmMemDefault,
help='JVM virtual memory size (default: %(default)s)'
)
except argparse.ArgumentError:
# if --JVMmemory is already present in the parser, continue on...
pass
return parser
def parser_revert_bam_picard(parser=argparse.ArgumentParser()):
parser.add_argument('inBam', help='Input reads, BAM format.')
parser.add_argument('outBam', help='Output reads, BAM format.')
parser.add_argument(
'--JVMmemory',
default=tools.picard.RevertSamTool.jvmMemDefault,
help='JVM virtual memory size (default: %(default)s)'
)
parser.add_argument(
'--picardOptions',
default=[],
nargs='*',
help='Optional arguments to Picard\'s RevertSam, OPTIONNAME=value ...'
)
parser = parser_revert_sam_common(parser)
util.cmd.common_args(parser, (('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, main_revert_bam_picard, split_args=True)
return parser
def main_revert_bam_picard(inBam, outBam, clear_tags=False, tags_to_clear=None, picardOptions=None, do_not_sanitize=False, JVMmemory=None):
'''Revert BAM to raw reads'''
picardOptions = picardOptions or []
tags_to_clear = tags_to_clear or []
if clear_tags:
for tag in tags_to_clear:
picardOptions.append("ATTRIBUTE_TO_CLEAR={}".format(tag))
if not do_not_sanitize and not any(opt.startswith("SANITIZE") for opt in picardOptions):
picardOptions.append('SANITIZE=true')
tools.picard.RevertSamTool().execute(inBam, outBam, picardOptions=picardOptions, JVMmemory=JVMmemory)
return 0
__commands__.append(('revert_bam_picard', parser_revert_bam_picard))
@contextmanager
def revert_bam_if_aligned(inBam, revert_bam=None, clear_tags=True, tags_to_clear=None, picardOptions=None, JVMmemory="4g", sanitize=False):
'''
revert the bam file if aligned.
If a revertBam file path is specified, it is used, otherwise a temp file is created.
'''
revertBamOut = revert_bam if revert_bam else util.file.mkstempfname('.bam')
picardOptions = picardOptions or []
tags_to_clear = tags_to_clear or []
outBam = inBam
with pysam.AlignmentFile(inBam, 'rb', check_sq=False) as bam:
# if it looks like the bam is aligned, revert it
if 'SQ' in bam.header and len(bam.header['SQ'])>0:
if clear_tags:
for tag in tags_to_clear:
picardOptions.append("ATTRIBUTE_TO_CLEAR={}".format(tag))
if not any(opt.startswith("SORT_ORDER") for opt in picardOptions):
picardOptions.append('SORT_ORDER=queryname')
if sanitize and not any(opt.startswith("SANITIZE") for opt in picardOptions):
picardOptions.append('SANITIZE=true')
tools.picard.RevertSamTool().execute(
inBam, revertBamOut, picardOptions=picardOptions
)
outBam = revertBamOut
else:
# if we don't need to produce a revertBam file
# but the user has specified one anyway
# simply touch the output
if revert_bam:
log.warning("An output was specified for 'revertBam', but the input is unaligned, so RevertSam was not needed. Touching the output.")
util.file.touch(revertBamOut)
# TODO: error out? run RevertSam anyway?
yield outBam
if revert_bam == None:
os.unlink(revertBamOut)
# =========================
# *** generic picard ***
# =========================
def parser_picard(parser=argparse.ArgumentParser()):
parser.add_argument('command', help='picard command')
parser.add_argument(
'--JVMmemory',
default=tools.picard.PicardTools.jvmMemDefault,
help='JVM virtual memory size (default: %(default)s)'
)
parser.add_argument(
'--picardOptions',
default=[], nargs='*',
help='Optional arguments to Picard, OPTIONNAME=value ...'
)
util.cmd.common_args(parser, (('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, main_picard)
return parser
def main_picard(args):
'''Generic Picard runner.'''
tools.picard.PicardTools().execute(args.command, picardOptions=args.picardOptions, JVMmemory=args.JVMmemory)
return 0
__commands__.append(('picard', parser_picard))
# ===================
# *** sort_bam ***
# ===================
def parser_sort_bam(parser=argparse.ArgumentParser()):
parser.add_argument('inBam', help='Input bam file.')
parser.add_argument('outBam', help='Output bam file, sorted.')
parser.add_argument(
'sortOrder',
help='How to sort the reads. [default: %(default)s]',
choices=tools.picard.SortSamTool.valid_sort_orders,
default=tools.picard.SortSamTool.default_sort_order
)
parser.add_argument(
"--index",
help="Index outBam (default: %(default)s)",
default=False,
action="store_true",
dest="index"
)
parser.add_argument(
"--md5",
help="MD5 checksum outBam (default: %(default)s)",
default=False,
action="store_true",
dest="md5"
)
parser.add_argument(
'--JVMmemory',
default=tools.picard.SortSamTool.jvmMemDefault,
help='JVM virtual memory size (default: %(default)s)'
)
parser.add_argument(
'--picardOptions',
default=[],
nargs='*',
help='Optional arguments to Picard\'s SortSam, OPTIONNAME=value ...'
)
util.cmd.common_args(parser, (('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, main_sort_bam)
return parser
def main_sort_bam(args):
'''Sort BAM file'''
opts = list(args.picardOptions)
if args.index:
opts = ['CREATE_INDEX=true'] + opts
if args.md5:
opts = ['CREATE_MD5_FILE=true'] + opts
tools.picard.SortSamTool().execute(
args.inBam, args.outBam, args.sortOrder,
picardOptions=opts, JVMmemory=args.JVMmemory
)
return 0
__commands__.append(('sort_bam', parser_sort_bam))
# ====================
# *** downsample_bams ***
# ====================
def parser_downsample_bams(parser=argparse.ArgumentParser()):
parser.add_argument('in_bams', help='Input bam files.', nargs='+')
parser.add_argument('--outPath', dest="out_path", type=str, help="""Output path. If not provided,
downsampled bam files will be written to the same paths as each
source bam file""")
parser.add_argument('--readCount', dest="specified_read_count", type=int, help='The number of reads to downsample to.')
group = parser.add_mutually_exclusive_group()
group.add_argument('--deduplicateBefore', action='store_true', dest="deduplicate_before", help='de-duplicate reads before downsampling.')
group.add_argument('--deduplicateAfter', action='store_true', dest="deduplicate_after", help='de-duplicate reads after downsampling.')
parser.add_argument(
'--JVMmemory',
default=tools.picard.DownsampleSamTool.jvmMemDefault,
help='JVM virtual memory size (default: %(default)s)'
)
parser.add_argument(
'--picardOptions',
default=[],
nargs='*',
help='Optional arguments to Picard\'s DownsampleSam, OPTIONNAME=value ...'
)
util.cmd.common_args(parser, (('threads', None), ('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, main_downsample_bams, split_args=True)
return parser
def main_downsample_bams(in_bams, out_path, specified_read_count=None, deduplicate_before=False, deduplicate_after=False, picardOptions=None, threads=None, JVMmemory=None):
'''Downsample multiple bam files to the smallest read count in common, or to the specified count.'''
if picardOptions is None:
picardOptions = []
opts = list(picardOptions) + []
def get_read_counts(bams):
samtools = tools.samtools.SamtoolsTool()
# get read counts for bam files provided
read_counts = {}
with concurrent.futures.ThreadPoolExecutor(max_workers=util.misc.sanitize_thread_count(threads)) as executor:
for x, result in zip(bams, executor.map(samtools.count, bams)):
read_counts[x] = int(result)
return read_counts
def get_downsample_target_count(bams, readcount_requested):
read_counts = get_read_counts(bams)
downsample_target = 0
if readcount_requested is not None:
downsample_target = readcount_requested
if downsample_target > min(read_counts.values()):
raise ValueError("The smallest file has %s reads, which is less than the downsample target specified, %s. Please reduce the target count or omit it to use the read count of the smallest input file." % (min(read_counts.values()), downsample_target))
else:
downsample_target = min(read_counts.values())
return downsample_target
def downsample_bams(data_pairs, downsample_target, threads=None, JVMmemory=None):
downsamplesam = tools.picard.DownsampleSamTool()
workers = util.misc.sanitize_thread_count(threads)
JVMmemory = JVMmemory if JVMmemory else tools.picard.DownsampleSamTool.jvmMemDefault
jvm_worker_memory = str(max(1,int(JVMmemory.rstrip("g"))/workers))+'g'
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
future_to_file = {executor.submit(downsamplesam.downsample_to_approx_count, *(list(fp)+[downsample_target]), JVMmemory=jvm_worker_memory): fp[0] for fp in data_pairs}
for future in concurrent.futures.as_completed(future_to_file):
f = future_to_file[future]
try:
data = future.result()
except Exception as exc:
raise
def dedup_bams(data_pairs, threads=None, JVMmemory=None):
workers = util.misc.sanitize_thread_count(threads)
JVMmemory = JVMmemory if JVMmemory else tools.picard.DownsampleSamTool.jvmMemDefault
jvm_worker_memory = str(max(1,int(JVMmemory.rstrip("g"))/workers))+'g'
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
future_to_file = {executor.submit(rmdup_mvicuna_bam, *fp, JVMmemory=jvm_worker_memory): fp[0] for fp in data_pairs}
for future in concurrent.futures.as_completed(future_to_file):
f = future_to_file[future]
try:
data = future.result()
except Exception as exc:
raise
data_pairs = []
if deduplicate_before:
with util.file.tempfnames(suffixes=[ '{}.dedup.bam'.format(os.path.splitext(os.path.basename(x))[0]) for x in in_bams]) as deduped_bams:
data_pairs = list(zip(in_bams, deduped_bams))
dedup_bams(data_pairs, threads=threads, JVMmemory=JVMmemory)
downsample_target = get_downsample_target_count(deduped_bams, specified_read_count)
if out_path:
util.file.mkdir_p(out_path)
data_pairs = list(zip(deduped_bams, [os.path.join(out_path, os.path.splitext(os.path.basename(x))[0]+".dedup.downsampled-{}.bam".format(downsample_target)) for x in in_bams]))
else:
data_pairs = list(zip(deduped_bams, [os.path.splitext(x)[0]+".dedup.downsampled-{}.bam".format(downsample_target) for x in in_bams]))
downsample_bams(data_pairs, downsample_target, threads=threads, JVMmemory=JVMmemory)
else:
downsample_target = get_downsample_target_count(in_bams, specified_read_count)
if deduplicate_after:
log.warning("--deduplicateAfter has been specified. Read count of output files is not guaranteed.")
with util.file.tempfnames(suffixes=[ '{}.downsampled-{}.bam'.format(os.path.splitext(os.path.basename(x))[0], downsample_target) for x in in_bams]) as downsampled_tmp_bams:
data_pairs = list(zip(in_bams, downsampled_tmp_bams))
downsample_bams(data_pairs, downsample_target, threads=threads, JVMmemory=JVMmemory)
if out_path:
util.file.mkdir_p(out_path)
data_pairs = list(zip(downsampled_tmp_bams, [os.path.join(out_path, os.path.splitext(os.path.basename(x))[0]+".downsampled-{}.dedup.bam").format(downsample_target) for x in in_bams]))
else:
data_pairs = list(zip(downsampled_tmp_bams, [os.path.splitext(x)[0]+".downsampled-{}.dedup.bam".format(downsample_target) for x in in_bams]))
dedup_bams(data_pairs, threads=threads, JVMmemory=JVMmemory)
else:
if out_path:
util.file.mkdir_p(out_path)
data_pairs = list(zip(in_bams, [os.path.join(out_path, os.path.splitext(os.path.basename(x))[0]+".downsampled-{}.bam".format(downsample_target)) for x in in_bams]))
else:
data_pairs = list(zip(in_bams, [os.path.splitext(x)[0]+".downsampled-{}.bam".format(downsample_target) for x in in_bams]))
downsample_bams(data_pairs, downsample_target, threads=threads, JVMmemory=JVMmemory)
return 0
__commands__.append(('downsample_bams', parser_downsample_bams))
# ====================
# *** merge_bams ***
# ====================
def parser_merge_bams(parser=argparse.ArgumentParser()):
parser.add_argument('inBams', help='Input bam files.', nargs='+')
parser.add_argument('outBam', help='Output bam file.')
parser.add_argument(
'--JVMmemory',
default=tools.picard.MergeSamFilesTool.jvmMemDefault,
help='JVM virtual memory size (default: %(default)s)'
)
parser.add_argument(
'--picardOptions',
default=[],
nargs='*',
help='Optional arguments to Picard\'s MergeSamFiles, OPTIONNAME=value ...'
)
util.cmd.common_args(parser, (('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, main_merge_bams)
return parser
def main_merge_bams(args):
'''Merge multiple BAMs into one'''
opts = list(args.picardOptions) + ['USE_THREADING=true']
tools.picard.MergeSamFilesTool().execute(args.inBams, args.outBam, picardOptions=opts, JVMmemory=args.JVMmemory)
return 0
__commands__.append(('merge_bams', parser_merge_bams))
# ====================
# *** filter_bam ***
# ====================
def parser_filter_bam(parser=argparse.ArgumentParser()):
parser.add_argument('inBam', help='Input bam file.')
parser.add_argument('readList', help='Input file of read IDs.')
parser.add_argument('outBam', help='Output bam file.')
parser.add_argument(
"--exclude",
help="""If specified, readList is a list of reads to remove from input.
Default behavior is to treat readList as an inclusion list (all unnamed
reads are removed).""",
default=False,
action="store_true",
dest="exclude"
)
parser.add_argument(
'--JVMmemory',
default=tools.picard.FilterSamReadsTool.jvmMemDefault,
help='JVM virtual memory size (default: %(default)s)'
)
parser.add_argument(
'--picardOptions',
default=[],
nargs='*',
help='Optional arguments to Picard\'s FilterSamReads, OPTIONNAME=value ...'
)
util.cmd.common_args(parser, (('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, main_filter_bam)
return parser
def main_filter_bam(args):
'''Filter BAM file by read name'''
tools.picard.FilterSamReadsTool().execute(
args.inBam,
args.exclude,
args.readList,
args.outBam,
picardOptions=args.picardOptions,
JVMmemory=args.JVMmemory
)
return 0
__commands__.append(('filter_bam', parser_filter_bam))
# =======================
# *** fastq_to_bam ***
# =======================
def fastq_to_bam(
inFastq1,
inFastq2,
outBam,
sampleName=None,
header=None,
JVMmemory=tools.picard.FastqToSamTool.jvmMemDefault,
picardOptions=None
):
''' Convert a pair of fastq paired-end read files and optional text header
to a single bam file.
'''
picardOptions = picardOptions or []
if header:
fastqToSamOut = mkstempfname('.bam')
else:
fastqToSamOut = outBam
if sampleName is None:
sampleName = 'Dummy' # Will get overwritten by rehead command
if header:
# With the header option, rehead will be called after FastqToSam.
# This will invalidate any md5 file, which would be a slow to construct
# on our own, so just disallow and let the caller run md5sum if desired.
if any(opt.lower() == 'CREATE_MD5_FILE=True'.lower() for opt in picardOptions):
raise Exception("""CREATE_MD5_FILE is not allowed with '--header.'""")
tools.picard.FastqToSamTool().execute(
inFastq1, inFastq2,
sampleName, fastqToSamOut,
picardOptions=picardOptions,
JVMmemory=JVMmemory
)
if header:
tools.samtools.SamtoolsTool().reheader(fastqToSamOut, header, outBam)
return 0
def parser_fastq_to_bam(parser=argparse.ArgumentParser()):
parser.add_argument('inFastq1', help='Input fastq file; 1st end of paired-end reads.')
parser.add_argument('inFastq2', help='Input fastq file; 2nd end of paired-end reads.')
parser.add_argument('outBam', help='Output bam file.')
headerGroup = parser.add_mutually_exclusive_group(required=True)
headerGroup.add_argument('--sampleName', help='Sample name to insert into the read group header.')
headerGroup.add_argument('--header', help='Optional text file containing header.')
parser.add_argument(
'--JVMmemory',
default=tools.picard.FastqToSamTool.jvmMemDefault,
help='JVM virtual memory size (default: %(default)s)'
)
parser.add_argument(
'--picardOptions',
default=[],
nargs='*',
help='''Optional arguments to Picard\'s FastqToSam,
OPTIONNAME=value ... Note that header-related options will be
overwritten by HEADER if present.'''
)
util.cmd.common_args(parser, (('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, fastq_to_bam, split_args=True)
return parser
__commands__.append(('fastq_to_bam', parser_fastq_to_bam))
def join_paired_fastq(
inFastqs,
output,
outFormat
):
''' Join paired fastq reads into single reads with Ns
'''
inFastqs = list(inFastqs)
if output == '-':
output = sys.stdout
SeqIO.write(util.file.join_paired_fastq(inFastqs, output_format=outFormat), output, outFormat)
return 0
def parser_join_paired_fastq(parser=argparse.ArgumentParser()):
parser.add_argument('output', help='Output file.')
parser.add_argument('inFastqs', nargs='+', help='Input fastq file (2 if paired, 1 if interleaved)')
parser.add_argument('--outFormat', default='fastq', help='Output file format.')
util.cmd.common_args(parser, (('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, join_paired_fastq, split_args=True)
return parser
__commands__.append(('join_paired_fastq', parser_join_paired_fastq))
# ======================
# *** split_reads ***
# ======================
defaultIndexLen = 2
defaultMaxReads = 1000
defaultFormat = 'fastq'
def split_bam(inBam, outBams):
'''Split BAM file equally into several output BAM files. '''
samtools = tools.samtools.SamtoolsTool()
picard = tools.picard.PicardTools()
# get totalReadCount and maxReads
# maxReads = totalReadCount / num files, but round up to the nearest
# even number in order to keep read pairs together (assuming the input
# is sorted in query order and has no unmated reads, which can be
# accomplished by Picard RevertSam with SANITIZE=true)
totalReadCount = samtools.count(inBam)
maxReads = int(math.ceil(float(totalReadCount) / len(outBams) / 2) * 2)
log.info("splitting %d reads into %d files of %d reads each", totalReadCount, len(outBams), maxReads)
# load BAM header into memory
header = samtools.getHeader(inBam)
if 'SO:queryname' not in header[0]:
raise Exception('Input BAM file must be sorted in queryame order')
# dump to bigsam
bigsam = mkstempfname('.sam')
samtools.view(['-@', '3'], inBam, bigsam)
# split bigsam into little ones
with util.file.open_or_gzopen(bigsam, 'rt') as inf:
for outBam in outBams:
log.info("preparing file " + outBam)
tmp_sam_reads = mkstempfname('.sam')
with open(tmp_sam_reads, 'wt') as outf:
for row in header:
outf.write('\t'.join(row) + '\n')
for _ in range(maxReads):
line = inf.readline()
if not line:
break
outf.write(line)
if outBam == outBams[-1]:
for line in inf:
outf.write(line)
picard.execute(
"SamFormatConverter", [
'INPUT=' + tmp_sam_reads, 'OUTPUT=' + outBam, 'VERBOSITY=WARNING'
],
JVMmemory='512m'
)
os.unlink(tmp_sam_reads)
os.unlink(bigsam)
def parser_split_bam(parser=argparse.ArgumentParser()):
parser.add_argument('inBam', help='Input BAM file.')
parser.add_argument('outBams', nargs='+', help='Output BAM files')
util.cmd.common_args(parser, (('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, split_bam, split_args=True)
return parser
__commands__.append(('split_bam', parser_split_bam))
# =======================
# *** reheader_bam ***
# =======================
def parser_reheader_bam(parser=argparse.ArgumentParser()):
parser.add_argument('inBam', help='Input reads, BAM format.')
parser.add_argument('rgMap', help='Tabular file containing three columns: field, old, new.')
parser.add_argument('outBam', help='Output reads, BAM format.')
util.cmd.common_args(parser, (('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, main_reheader_bam)
return parser
def main_reheader_bam(args):
''' Copy a BAM file (inBam to outBam) while renaming elements of the BAM header.
The mapping file specifies which (key, old value, new value) mappings. For
example:
LB lib1 lib_one
SM sample1 Sample_1
SM sample2 Sample_2
SM sample3 Sample_3
CN broad BI
'''
# read mapping file
mapper = dict((a + ':' + b, a + ':' + c) for a, b, c in util.file.read_tabfile(args.rgMap))
# read and convert bam header
header_file = mkstempfname('.sam')
with open(header_file, 'wt') as outf:
for row in tools.samtools.SamtoolsTool().getHeader(args.inBam):
if row[0] == '@RG':
row = [mapper.get(x, x) for x in row]
outf.write('\t'.join(row) + '\n')
# write new bam with new header
tools.samtools.SamtoolsTool().reheader(args.inBam, header_file, args.outBam)
os.unlink(header_file)
return 0
__commands__.append(('reheader_bam', parser_reheader_bam))
def parser_reheader_bams(parser=argparse.ArgumentParser()):
parser.add_argument('rgMap', help='Tabular file containing three columns: field, old, new.')
util.cmd.common_args(parser, (('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, main_reheader_bams)
return parser
def main_reheader_bams(args):
''' Copy BAM files while renaming elements of the BAM header.
The mapping file specifies which (key, old value, new value) mappings. For
example:
LB lib1 lib_one
SM sample1 Sample_1
SM sample2 Sample_2
SM sample3 Sample_3
CN broad BI
FN in1.bam out1.bam
FN in2.bam out2.bam
'''
# read mapping file
mapper = dict((a + ':' + b, a + ':' + c) for a, b, c in util.file.read_tabfile(args.rgMap) if a != 'FN')
files = list((b, c) for a, b, c in util.file.read_tabfile(args.rgMap) if a == 'FN')
header_file = mkstempfname('.sam')
# read and convert bam headers
for inBam, outBam in files:
if os.path.isfile(inBam):
with open(header_file, 'wt') as outf:
for row in tools.samtools.SamtoolsTool().getHeader(inBam):
if row[0] == '@RG':
row = [mapper.get(x, x) for x in row]
outf.write('\t'.join(row) + '\n')
# write new bam with new header
tools.samtools.SamtoolsTool().reheader(inBam, header_file, outBam)
os.unlink(header_file)
return 0
__commands__.append(('reheader_bams', parser_reheader_bams))
# ============================
# *** dup_remove_mvicuna ***
# ============================
def mvicuna_fastqs_to_readlist(inFastq1, inFastq2, readList):
# Run M-Vicuna on FASTQ files
outFastq1 = mkstempfname('.1.fastq')
outFastq2 = mkstempfname('.2.fastq')
if inFastq2 is None or os.path.getsize(inFastq2) < 10:
tools.mvicuna.MvicunaTool().rmdup_single(inFastq1, outFastq1)
else:
tools.mvicuna.MvicunaTool().rmdup((inFastq1, inFastq2), (outFastq1, outFastq2), None)
# Make a list of reads to keep
with open(readList, 'at') as outf:
for fq in (outFastq1, outFastq2):
with util.file.open_or_gzopen(fq, 'rt') as inf:
line_num = 0
for line in inf:
if (line_num % 4) == 0:
idVal = line.rstrip('\n')[1:]
if idVal.endswith('/1'):
outf.write(idVal[:-2] + '\n')
line_num += 1
os.unlink(outFastq1)
os.unlink(outFastq2)
def rmdup_cdhit_bam(inBam, outBam, max_mismatches=None, jvm_memory=None):
''' Remove duplicate reads from BAM file using cd-hit-dup.
'''
max_mismatches = max_mismatches or 4
tmp_dir = tempfile.mkdtemp()
tools.picard.SplitSamByLibraryTool().execute(inBam, tmp_dir)
s2fq_tool = tools.picard.SamToFastqTool()
cdhit = tools.cdhit.CdHit()
out_bams = []
for f in os.listdir(tmp_dir):
out_bam = mkstempfname('.bam')
out_bams.append(out_bam)
library_sam = os.path.join(tmp_dir, f)
in_fastqs = mkstempfname('.1.fastq'), mkstempfname('.2.fastq')
s2fq_tool.execute(library_sam, in_fastqs[0], in_fastqs[1])
if not os.path.getsize(in_fastqs[0]) > 0 and not os.path.getsize(in_fastqs[1]) > 0:
continue
out_fastqs = mkstempfname('.1.fastq'), mkstempfname('.2.fastq')
options = {
'-e': max_mismatches,
}
if in_fastqs[1] is not None and os.path.getsize(in_fastqs[1]) > 10:
options['-i2'] = in_fastqs[1]
options['-o2'] = out_fastqs[1]
log.info("executing cd-hit-est on library " + library_sam)
# cd-hit-dup cannot operate on piped fastq input because it reads twice
cdhit.execute('cd-hit-dup', in_fastqs[0], out_fastqs[0], options=options, background=True)
tools.picard.FastqToSamTool().execute(out_fastqs[0], out_fastqs[1], f, out_bam, JVMmemory=jvm_memory)
for fn in in_fastqs:
os.unlink(fn)
with util.file.fifo(name='merged.sam') as merged_bam:
merge_opts = ['SORT_ORDER=queryname']
tools.picard.MergeSamFilesTool().execute(out_bams, merged_bam, picardOptions=merge_opts, JVMmemory=jvm_memory, background=True)
tools.picard.ReplaceSamHeaderTool().execute(merged_bam, inBam, outBam, JVMmemory=jvm_memory)
def parser_rmdup_cdhit_bam(parser=argparse.ArgumentParser()):
parser.add_argument('inBam', help='Input reads, BAM format.')
parser.add_argument('outBam', help='Output reads, BAM format.')
parser.add_argument(
'--JVMmemory',
default=tools.picard.FilterSamReadsTool.jvmMemDefault,
help='JVM virtual memory size (default: %(default)s)',
dest='jvm_memory'
)
util.cmd.common_args(parser, (('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, rmdup_cdhit_bam, split_args=True)
return parser
__commands__.append(('rmdup_cdhit_bam', parser_rmdup_cdhit_bam))
def _merge_fastqs_and_mvicuna(lb, files):
readList = mkstempfname('.keep_reads.txt')
log.info("executing M-Vicuna DupRm on library " + lb)
# create merged FASTQs per library
infastqs = (mkstempfname('.1.fastq'), mkstempfname('.2.fastq'))
for d in range(2):
with open(infastqs[d], 'wt') as outf:
for fprefix in files:
fn = '%s_%d.fastq' % (fprefix, d + 1)
if os.path.isfile(fn):
with open(fn, 'rt') as inf:
for line in inf:
outf.write(line)
os.unlink(fn)
else:
log.warning(
"""no reads found in %s,
assuming that's because there's no reads in that read group""", fn
)
# M-Vicuna DupRm to see what we should keep (append IDs to running file)
if os.path.getsize(infastqs[0]) > 0 or os.path.getsize(infastqs[1]) > 0:
mvicuna_fastqs_to_readlist(infastqs[0], infastqs[1], readList)
for fn in infastqs:
os.unlink(fn)
return readList
def rmdup_mvicuna_bam(inBam, outBam, JVMmemory=None):
''' Remove duplicate reads from BAM file using M-Vicuna. The
primary advantage to this approach over Picard's MarkDuplicates tool
is that Picard requires that input reads are aligned to a reference,
and M-Vicuna can operate on unaligned reads.
'''
# Convert BAM -> FASTQ pairs per read group and load all read groups
tempDir = tempfile.mkdtemp()
tools.picard.SamToFastqTool().per_read_group(inBam, tempDir, picardOptions=['VALIDATION_STRINGENCY=LENIENT'], JVMmemory=JVMmemory)
read_groups = [x[1:] for x in tools.samtools.SamtoolsTool().getHeader(inBam) if x[0] == '@RG']
read_groups = [dict(pair.split(':', 1) for pair in rg) for rg in read_groups]
# Collect FASTQ pairs for each library
lb_to_files = {}
for rg in read_groups:
lb_to_files.setdefault(rg.get('LB', 'none'), set())
fname = rg['ID']
lb_to_files[rg.get('LB', 'none')].add(os.path.join(tempDir, fname))
log.info("found %d distinct libraries and %d read groups", len(lb_to_files), len(read_groups))
# For each library, merge FASTQs and run rmdup for entire library
readListAll = mkstempfname('.keep_reads_all.txt')
per_lb_read_lists = []
with concurrent.futures.ProcessPoolExecutor(max_workers=util.misc.available_cpu_count()) as executor:
futures = [executor.submit(_merge_fastqs_and_mvicuna, lb, files) for lb, files in lb_to_files.items()]
for future in concurrent.futures.as_completed(futures):
log.info("mvicuna finished processing library")
try:
readList = future.result()
per_lb_read_lists.append(readList)
except Exception as exc:
log.error('mvicuna process call generated an exception: %s' % (exc))
# merge per-library read lists together
util.file.concat(per_lb_read_lists, readListAll)
# remove per-library read lists
for fl in per_lb_read_lists:
os.unlink(fl)
# Filter original input BAM against keep-list
tools.picard.FilterSamReadsTool().execute(inBam, False, readListAll, outBam, JVMmemory=JVMmemory)
return 0
def parser_rmdup_mvicuna_bam(parser=argparse.ArgumentParser()):