-
Notifications
You must be signed in to change notification settings - Fork 67
/
assembly.py
executable file
·1685 lines (1479 loc) · 69.8 KB
/
assembly.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
''' This script contains a number of utilities for viral sequence assembly
from NGS reads. Primarily used for Lassa and Ebola virus analysis in
the Sabeti Lab / Broad Institute Viral Genomics.
'''
__author__ = "[email protected], [email protected]"
__commands__ = []
# built-ins
import argparse
import logging
import random
import numpy
import os
import os.path
import shutil
import subprocess
import functools
import operator
import concurrent.futures
import csv
from itertools import zip_longest # pylint: disable=E0611
# intra-module
import util.cmd
import util.file
import util.misc
import util.vcf
import read_utils
import tools
import tools.picard
import tools.samtools
import tools.gatk
import tools.novoalign
import tools.spades
import tools.trimmomatic
import tools.trinity
import tools.mafft
import tools.mummer
import tools.muscle
import tools.gap2seq
# third-party
import Bio.AlignIO
import Bio.SeqIO
import Bio.Data.IUPACData
log = logging.getLogger(__name__)
class DenovoAssemblyError(RuntimeError):
'''Indicates a failure of the de novo assembly step. Can indicate an internal error in the assembler, but also
insufficient input data (for assemblers which cannot report that condition separately).'''
def __init__(self, reason):
super(DenovoAssemblyError, self).__init__(reason)
def trim_rmdup_subsamp_reads(inBam, clipDb, outBam, n_reads=100000, trim_opts=None):
''' Take reads through Trimmomatic, Prinseq, and subsampling.
This should probably move over to read_utils.
'''
downsamplesam = tools.picard.DownsampleSamTool()
samtools = tools.samtools.SamtoolsTool()
if n_reads < 1:
raise Exception()
# BAM -> fastq
infq = list(map(util.file.mkstempfname, ['.in.1.fastq', '.in.2.fastq']))
tools.picard.SamToFastqTool().execute(inBam, infq[0], infq[1])
n_input = util.file.count_fastq_reads(infq[0])
# --- Trimmomatic ---
trimfq = list(map(util.file.mkstempfname, ['.trim.1.fastq', '.trim.2.fastq']))
trimfq_unpaired = list(map(util.file.mkstempfname, ['.trim.unpaired.1.fastq', '.trim.unpaired.2.fastq']))
if n_input == 0:
for i in range(2):
shutil.copyfile(infq[i], trimfq[i])
else:
tools.trimmomatic.TrimmomaticTool().execute(
infq[0],
infq[1],
trimfq[0],
trimfq[1],
clipDb,
unpairedOutFastq1=trimfq_unpaired[0],
unpairedOutFastq2=trimfq_unpaired[1],
**(trim_opts or {})
)
n_trim = max(map(util.file.count_fastq_reads, trimfq)) # count is pairs
n_trim_unpaired = sum(map(util.file.count_fastq_reads, trimfq_unpaired)) # count is individual reads
# --- Prinseq duplicate removal ---
# the paired reads from trim, de-duplicated
rmdupfq = list(map(util.file.mkstempfname, ['.rmdup.1.fastq', '.rmdup.2.fastq']))
# the unpaired reads from rmdup, de-duplicated with the other singleton files later on
rmdupfq_unpaired_from_paired_rmdup = list(
map(util.file.mkstempfname, ['.rmdup.unpaired.1.fastq', '.rmdup.unpaired.2.fastq'])
)
prinseq = tools.prinseq.PrinseqTool()
prinseq.rmdup_fastq_paired(
trimfq[0],
trimfq[1],
rmdupfq[0],
rmdupfq[1],
includeUnmated=False,
unpairedOutFastq1=rmdupfq_unpaired_from_paired_rmdup[0],
unpairedOutFastq2=rmdupfq_unpaired_from_paired_rmdup[1]
)
n_rmdup_paired = max(map(util.file.count_fastq_reads, rmdupfq)) # count is pairs
n_rmdup = n_rmdup_paired # count is pairs
tmp_header = util.file.mkstempfname('.header.sam')
tools.samtools.SamtoolsTool().dumpHeader(inBam, tmp_header)
# convert paired reads to bam
# stub out an empty file if the input fastqs are empty
tmp_bam_paired = util.file.mkstempfname('.paired.bam')
if all(os.path.getsize(x) > 0 for x in rmdupfq):
tools.picard.FastqToSamTool().execute(rmdupfq[0], rmdupfq[1], 'Dummy', tmp_bam_paired)
else:
opts = ['INPUT=' + tmp_header, 'OUTPUT=' + tmp_bam_paired, 'VERBOSITY=ERROR']
tools.picard.PicardTools().execute('SamFormatConverter', opts, JVMmemory='50m')
n_paired_subsamp = 0
n_unpaired_subsamp = 0
n_rmdup_unpaired = 0
# --- subsampling ---
# if we have too few paired reads after trimming and de-duplication, we can incorporate unpaired reads to reach the desired count
if n_rmdup_paired * 2 < n_reads:
# the unpaired reads from the trim operation, and the singletons from Prinseq
unpaired_concat = util.file.mkstempfname('.unpaired.fastq')
# merge unpaired reads from trimmomatic and singletons left over from paired-mode prinseq
util.file.cat(unpaired_concat, trimfq_unpaired + rmdupfq_unpaired_from_paired_rmdup)
# remove the earlier singleton files
for f in trimfq_unpaired + rmdupfq_unpaired_from_paired_rmdup:
os.unlink(f)
# the de-duplicated singletons
unpaired_concat_rmdup = util.file.mkstempfname('.unpaired.rumdup.fastq')
prinseq.rmdup_fastq_single(unpaired_concat, unpaired_concat_rmdup)
os.unlink(unpaired_concat)
n_rmdup_unpaired = util.file.count_fastq_reads(unpaired_concat_rmdup)
did_include_subsampled_unpaired_reads = True
# if there are no unpaired reads, simply output the paired reads
if n_rmdup_unpaired == 0:
shutil.copyfile(tmp_bam_paired, outBam)
n_output = samtools.count(outBam)
else:
# take pooled unpaired reads and convert to bam
tmp_bam_unpaired = util.file.mkstempfname('.unpaired.bam')
tools.picard.FastqToSamTool().execute(unpaired_concat_rmdup, None, 'Dummy', tmp_bam_unpaired)
tmp_bam_unpaired_subsamp = util.file.mkstempfname('.unpaired.subsamp.bam')
reads_to_add = (n_reads - (n_rmdup_paired * 2))
downsamplesam.downsample_to_approx_count(tmp_bam_unpaired, tmp_bam_unpaired_subsamp, reads_to_add)
n_unpaired_subsamp = samtools.count(tmp_bam_unpaired_subsamp)
os.unlink(tmp_bam_unpaired)
# merge the subsampled unpaired reads into the bam to be used as
tmp_bam_merged = util.file.mkstempfname('.merged.bam')
tools.picard.MergeSamFilesTool().execute([tmp_bam_paired, tmp_bam_unpaired_subsamp], tmp_bam_merged)
os.unlink(tmp_bam_unpaired_subsamp)
tools.samtools.SamtoolsTool().reheader(tmp_bam_merged, tmp_header, outBam)
os.unlink(tmp_bam_merged)
n_paired_subsamp = n_rmdup_paired # count is pairs
n_output = n_rmdup_paired * 2 + n_unpaired_subsamp # count is individual reads
else:
did_include_subsampled_unpaired_reads = False
log.info("PRE-SUBSAMPLE COUNT: %s read pairs", n_rmdup_paired)
tmp_bam_paired_subsamp = util.file.mkstempfname('.unpaired.subsamp.bam')
downsamplesam.downsample_to_approx_count(tmp_bam_paired, tmp_bam_paired_subsamp, n_reads)
n_paired_subsamp = samtools.count(tmp_bam_paired_subsamp) // 2 # count is pairs
n_output = n_paired_subsamp * 2 # count is individual reads
tools.samtools.SamtoolsTool().reheader(tmp_bam_paired_subsamp, tmp_header, outBam)
os.unlink(tmp_bam_paired_subsamp)
os.unlink(tmp_bam_paired)
os.unlink(tmp_header)
n_final_individual_reads = samtools.count(outBam)
log.info("Pre-DeNovoAssembly read filters: ")
log.info(" {} read pairs at start ".format(n_input))
log.info(
" {} read pairs after Trimmomatic {}".format(
n_trim, "(and {} unpaired)".format(n_trim_unpaired) if n_trim_unpaired > 0 else ""
)
)
log.info(
" {} read pairs after Prinseq rmdup {} ".format(
n_rmdup, "(and {} unpaired from Trimmomatic+Prinseq)".format(n_rmdup_unpaired)
if n_rmdup_unpaired > 0 else ""
)
)
if did_include_subsampled_unpaired_reads:
log.info(
" Too few individual reads ({}*2={}) from paired reads to reach desired threshold ({}), so including subsampled unpaired reads".format(
n_rmdup_paired, n_rmdup_paired * 2, n_reads
)
)
else:
log.info(" Paired read count sufficient to reach threshold ({})".format(n_reads))
log.info(
" {} individual reads for de novo assembly ({}{})".format(
n_output, "paired subsampled {} -> {}".format(n_rmdup_paired, n_paired_subsamp)
if not did_include_subsampled_unpaired_reads else "{} read pairs".format(n_rmdup_paired),
" + unpaired subsampled {} -> {}".format(n_rmdup_unpaired, n_unpaired_subsamp)
if did_include_subsampled_unpaired_reads else ""
)
)
log.info(" {} individual reads".format(n_final_individual_reads))
if did_include_subsampled_unpaired_reads:
if n_final_individual_reads < n_reads:
log.warning(
"NOTE: Even with unpaired reads included, there are fewer unique trimmed reads than requested for de novo assembly input."
)
# clean up temp files
for i in range(2):
for f in infq, trimfq, rmdupfq:
if os.path.exists(f[i]):
os.unlink(f[i])
# multiply counts so all reflect individual reads
return (n_input * 2, n_trim * 2, n_rmdup * 2, n_output, n_paired_subsamp * 2, n_unpaired_subsamp)
def parser_trim_rmdup_subsamp(parser=argparse.ArgumentParser()):
parser.add_argument('inBam', help='Input reads, unaligned BAM format.')
parser.add_argument('clipDb', help='Trimmomatic clip DB.')
parser.add_argument(
'outBam',
help="""Output reads, unaligned BAM format (currently, read groups and other
header information are destroyed in this process)."""
)
parser.add_argument(
'--n_reads',
default=100000,
type=int,
help='Subsample reads to no more than this many individual reads. Note that paired reads are given priority, and unpaired reads are included to reach the count if there are too few paired reads to reach n_reads. (default %(default)s)'
)
util.cmd.common_args(parser, (('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, trim_rmdup_subsamp_reads, split_args=True)
return parser
__commands__.append(('trim_rmdup_subsamp', parser_trim_rmdup_subsamp))
def assemble_trinity(
inBam, clipDb,
outFasta, n_reads=100000,
outReads=None,
always_succeed=False,
JVMmemory=None,
threads=None
):
''' This step runs the Trinity assembler.
First trim reads with trimmomatic, rmdup with prinseq,
and random subsample to no more than 100k reads.
'''
if outReads:
subsamp_bam = outReads
else:
subsamp_bam = util.file.mkstempfname('.subsamp.bam')
picard_opts = {
'CLIPPING_ATTRIBUTE': tools.picard.SamToFastqTool.illumina_clipping_attribute,
'CLIPPING_ACTION': 'X'
}
read_stats = trim_rmdup_subsamp_reads(inBam, clipDb, subsamp_bam, n_reads=n_reads)
subsampfq = list(map(util.file.mkstempfname, ['.subsamp.1.fastq', '.subsamp.2.fastq']))
tools.picard.SamToFastqTool().execute(subsamp_bam, subsampfq[0], subsampfq[1], picardOptions=tools.picard.PicardTools.dict_to_picard_opts(picard_opts))
try:
tools.trinity.TrinityTool().execute(subsampfq[0], subsampfq[1], outFasta, JVMmemory=JVMmemory, threads=threads)
except subprocess.CalledProcessError as e:
if always_succeed:
log.warning("denovo assembly (Trinity) failed to assemble input, emitting empty output instead.")
util.file.make_empty(outFasta)
else:
raise DenovoAssemblyError('denovo assembly (Trinity) failed. {} reads at start. {} read pairs after Trimmomatic. '
'{} read pairs after Prinseq rmdup. {} reads for trinity ({} pairs + {} unpaired).'.format(*read_stats))
os.unlink(subsampfq[0])
os.unlink(subsampfq[1])
if not outReads:
os.unlink(subsamp_bam)
def parser_assemble_trinity(parser=argparse.ArgumentParser()):
parser.add_argument('inBam', help='Input unaligned reads, BAM format.')
parser.add_argument('clipDb', help='Trimmomatic clip DB.')
parser.add_argument('outFasta', help='Output assembly.')
parser.add_argument(
'--n_reads',
default=100000,
type=int,
help='Subsample reads to no more than this many pairs. (default %(default)s)'
)
parser.add_argument('--outReads', default=None, help='Save the trimmomatic/prinseq/subsamp reads to a BAM file')
parser.add_argument(
"--always_succeed",
help="""If Trinity fails (usually because insufficient reads to assemble),
emit an empty fasta file as output. Default is to throw a DenovoAssemblyError.""",
default=False,
action="store_true",
dest="always_succeed"
)
parser.add_argument(
'--JVMmemory',
default=tools.trinity.TrinityTool.jvm_mem_default,
help='JVM virtual memory size (default: %(default)s)'
)
util.cmd.common_args(parser, (('threads', None), ('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, assemble_trinity, split_args=True)
return parser
__commands__.append(('assemble_trinity', parser_assemble_trinity))
def assemble_spades(
in_bam,
clip_db,
out_fasta,
spades_opts='',
contigs_trusted=None, contigs_untrusted=None,
filter_contigs=False,
min_contig_len=0,
kmer_sizes=(55,65),
n_reads=10000000,
outReads=None,
always_succeed=False,
max_kmer_sizes=1,
mem_limit_gb=8,
threads=None,
):
'''De novo RNA-seq assembly with the SPAdes assembler.
'''
if outReads:
trim_rmdup_bam = outReads
else:
trim_rmdup_bam = util.file.mkstempfname('.subsamp.bam')
trim_rmdup_subsamp_reads(in_bam, clip_db, trim_rmdup_bam, n_reads=n_reads,
trim_opts=dict(maxinfo_target_length=35, maxinfo_strictness=.2))
with tools.picard.SamToFastqTool().execute_tmp(trim_rmdup_bam, includeUnpaired=True, illuminaClipping=True
) as (reads_fwd, reads_bwd, reads_unpaired):
try:
tools.spades.SpadesTool().assemble(reads_fwd=reads_fwd, reads_bwd=reads_bwd, reads_unpaired=reads_unpaired,
contigs_untrusted=contigs_untrusted, contigs_trusted=contigs_trusted,
contigs_out=out_fasta, filter_contigs=filter_contigs,
min_contig_len=min_contig_len,
kmer_sizes=kmer_sizes, always_succeed=always_succeed, max_kmer_sizes=max_kmer_sizes,
spades_opts=spades_opts, mem_limit_gb=mem_limit_gb,
threads=threads)
except subprocess.CalledProcessError as e:
raise DenovoAssemblyError('SPAdes assembler failed: ' + str(e))
if not outReads:
os.unlink(trim_rmdup_bam)
def parser_assemble_spades(parser=argparse.ArgumentParser()):
parser.add_argument('in_bam', help='Input unaligned reads, BAM format. May include both paired and unpaired reads.')
parser.add_argument('clip_db', help='Trimmomatic clip db')
parser.add_argument('out_fasta', help='Output assembled contigs. Note that, since this is RNA-seq assembly, for each assembled genomic region there may be several contigs representing different variants of that region.')
parser.add_argument('--contigsTrusted', dest='contigs_trusted',
help='Optional input contigs of high quality, previously assembled from the same sample')
parser.add_argument('--contigsUntrusted', dest='contigs_untrusted',
help='Optional input contigs of high medium quality, previously assembled from the same sample')
parser.add_argument('--nReads', dest='n_reads', type=int, default=10000000,
help='Before assembly, subsample the reads to at most this many')
parser.add_argument('--outReads', default=None, help='Save the trimmomatic/prinseq/subsamp reads to a BAM file')
parser.add_argument('--filterContigs', dest='filter_contigs', default=False, action='store_true',
help='only output contigs SPAdes is sure of (drop lesser-quality contigs from output)')
parser.add_argument('--alwaysSucceed', dest='always_succeed', default=False, action='store_true',
help='if assembly fails for any reason, output an empty contigs file, rather than failing with '
'an error code')
parser.add_argument('--minContigLen', dest='min_contig_len', type=int, default=0,
help='only output contigs longer than this many bp')
parser.add_argument('--spadesOpts', dest='spades_opts', default='', help='(advanced) Extra flags to pass to the SPAdes assembler')
parser.add_argument('--memLimitGb', dest='mem_limit_gb', default=4, type=int, help='Max memory to use, in GB (default: %(default)s)')
util.cmd.common_args(parser, (('threads', None), ('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, assemble_spades, split_args=True)
return parser
__commands__.append(('assemble_spades', parser_assemble_spades))
def gapfill_gap2seq(in_scaffold, in_bam, out_scaffold, threads=None, mem_limit_gb=4, time_soft_limit_minutes=60.0,
random_seed=0, gap2seq_opts='', always_succeed=False):
''' This step runs the Gap2Seq tool to close gaps between contigs in a scaffold.
'''
try:
tools.gap2seq.Gap2SeqTool().gapfill(in_scaffold, in_bam, out_scaffold, gap2seq_opts=gap2seq_opts, threads=threads,
mem_limit_gb=mem_limit_gb, time_soft_limit_minutes=time_soft_limit_minutes,
random_seed=random_seed)
except Exception as e:
if not always_succeed:
raise
log.warning('Gap-filling failed (%s); ignoring error, emulating successful run where simply no gaps were filled.')
shutil.copyfile(in_scaffold, out_scaffold)
def parser_gapfill_gap2seq(parser=argparse.ArgumentParser(description='Close gaps between contigs in a scaffold')):
parser.add_argument('in_scaffold', help='FASTA file containing the scaffold. Each FASTA record corresponds to one '
'segment (for multi-segment genomes). Contigs within each segment are separated by Ns.')
parser.add_argument('in_bam', help='Input unaligned reads, BAM format.')
parser.add_argument('out_scaffold', help='Output assembly.')
parser.add_argument('--memLimitGb', dest='mem_limit_gb', default=4.0, help='Max memory to use, in gigabytes %(default)s')
parser.add_argument('--timeSoftLimitMinutes', dest='time_soft_limit_minutes', default=60.0,
help='Stop trying to close more gaps after this many minutes (default: %(default)s); this is a soft/advisory limit')
parser.add_argument('--maskErrors', dest='always_succeed', default=False, action='store_true',
help='In case of any error, just copy in_scaffold to out_scaffold, emulating a successful run that simply could not '
'fill any gaps.')
parser.add_argument('--gap2seqOpts', dest='gap2seq_opts', default='', help='(advanced) Extra command-line options to pass to Gap2Seq')
parser.add_argument('--randomSeed', dest='random_seed', default=0, help='Random seed; 0 means use current time')
util.cmd.common_args(parser, (('threads', None), ('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, gapfill_gap2seq, split_args=True)
return parser
__commands__.append(('gapfill_gap2seq', parser_gapfill_gap2seq))
def _order_and_orient_orig(inFasta, inReference, outFasta,
outAlternateContigs=None,
breaklen=None, # aligner='nucmer', circular=False, trimmed_contigs=None,
maxgap=200, minmatch=10, mincluster=None,
min_pct_id=0.6, min_contig_len=200, min_pct_contig_aligned=0.3):
''' This step cleans up the de novo assembly with a known reference genome.
Uses MUMmer (nucmer or promer) to create a reference-based consensus
sequence of aligned contigs (with runs of N's in between the de novo
contigs).
'''
mummer = tools.mummer.MummerTool()
#if trimmed_contigs:
# trimmed = trimmed_contigs
#else:
# trimmed = util.file.mkstempfname('.trimmed.contigs.fasta')
#mummer.trim_contigs(inReference, inFasta, trimmed,
# aligner=aligner, circular=circular, extend=False, breaklen=breaklen,
# min_pct_id=min_pct_id, min_contig_len=min_contig_len,
# min_pct_contig_aligned=min_pct_contig_aligned)
#mummer.scaffold_contigs(inReference, trimmed, outFasta,
# aligner=aligner, circular=circular, extend=True, breaklen=breaklen,
# min_pct_id=min_pct_id, min_contig_len=min_contig_len,
# min_pct_contig_aligned=min_pct_contig_aligned)
mummer.scaffold_contigs_custom(
inReference,
inFasta,
outFasta,
outAlternateContigs=outAlternateContigs,
extend=True,
breaklen=breaklen,
min_pct_id=min_pct_id,
min_contig_len=min_contig_len,
maxgap=maxgap,
minmatch=minmatch,
mincluster=mincluster,
min_pct_contig_aligned=min_pct_contig_aligned
)
#if not trimmed_contigs:
# os.unlink(trimmed)
return 0
def _call_order_and_orient_orig(inReference, outFasta, outAlternateContigs, **kwargs):
return _order_and_orient_orig(inReference=inReference, outFasta=outFasta, outAlternateContigs=outAlternateContigs, **kwargs)
def order_and_orient(inFasta, inReference, outFasta,
outAlternateContigs=None, outReference=None,
breaklen=None, # aligner='nucmer', circular=False, trimmed_contigs=None,
maxgap=200, minmatch=10, mincluster=None,
min_pct_id=0.6, min_contig_len=200, min_pct_contig_aligned=0.3, n_genome_segments=0,
outStats=None, threads=None):
''' This step cleans up the de novo assembly with a known reference genome.
Uses MUMmer (nucmer or promer) to create a reference-based consensus
sequence of aligned contigs (with runs of N's in between the de novo
contigs).
'''
chk = util.cmd.check_input
ref_segments_all = [tuple(Bio.SeqIO.parse(inRef, 'fasta')) for inRef in util.misc.make_seq(inReference)]
chk(ref_segments_all, 'No references given')
chk(len(set(map(len, ref_segments_all))) == 1, 'All references must have the same number of segments')
if n_genome_segments:
if len(ref_segments_all) == 1:
chk((len(ref_segments_all[0]) % n_genome_segments) == 0,
'Number of reference sequences in must be a multiple of the number of genome segments')
else:
chk(len(ref_segments_all[0]) == n_genome_segments,
'Number of reference segments must match the n_genome_segments parameter')
else:
n_genome_segments = len(ref_segments_all[0])
ref_segments_all = functools.reduce(operator.concat, ref_segments_all, ())
n_refs = len(ref_segments_all) // n_genome_segments
log.info('n_genome_segments={} n_refs={}'.format(n_genome_segments, n_refs))
ref_ids = []
with util.file.tempfnames(suffixes=[ '.{}.ref.fasta'.format(ref_num) for ref_num in range(n_refs)]) as refs_fasta, \
util.file.tempfnames(suffixes=[ '.{}.scaffold.fasta'.format(ref_num) for ref_num in range(n_refs)]) as scaffolds_fasta, \
util.file.tempfnames(suffixes=[ '.{}.altcontig.fasta'.format(ref_num) for ref_num in range(n_refs)]) as alt_contigs_fasta:
for ref_num in range(n_refs):
this_ref_segs = ref_segments_all[ref_num*n_genome_segments : (ref_num+1)*n_genome_segments]
ref_ids.append(this_ref_segs[0].id)
Bio.SeqIO.write(this_ref_segs, refs_fasta[ref_num], 'fasta')
with concurrent.futures.ProcessPoolExecutor(max_workers=util.misc.sanitize_thread_count(threads)) as executor:
retvals = executor.map(functools.partial(_call_order_and_orient_orig, inFasta=inFasta,
breaklen=breaklen, maxgap=maxgap, minmatch=minmatch, mincluster=mincluster, min_pct_id=min_pct_id,
min_contig_len=min_contig_len, min_pct_contig_aligned=min_pct_contig_aligned),
refs_fasta, scaffolds_fasta, alt_contigs_fasta)
for r in retvals:
# if an exception is raised by _call_order_and_orient_contig, the
# concurrent.futures.Executor.map function documentations states
# that the same exception will be raised when retrieving that entry
# of the retval iterator. This for loop is intended to reveal any
# CalledProcessErrors from mummer itself.
assert r==0
scaffolds = [tuple(Bio.SeqIO.parse(scaffolds_fasta[ref_num], 'fasta')) for ref_num in range(n_refs)]
base_counts = [sum([len(seg.seq.ungap('N')) for seg in scaffold]) \
if len(scaffold)==n_genome_segments else 0 for scaffold in scaffolds]
best_ref_num = numpy.argmax(base_counts)
if len(scaffolds[best_ref_num]) != n_genome_segments:
raise IncompleteAssemblyError(len(scaffolds[best_ref_num]), n_genome_segments)
log.info('base_counts={} best_ref_num={}'.format(base_counts, best_ref_num))
shutil.copyfile(scaffolds_fasta[best_ref_num], outFasta)
if outAlternateContigs:
shutil.copyfile(alt_contigs_fasta[best_ref_num], outAlternateContigs)
if outReference:
shutil.copyfile(refs_fasta[best_ref_num], outReference)
if outStats:
ref_ranks = (-numpy.array(base_counts)).argsort().argsort()
with open(outStats, 'w') as stats_f:
stats_w = csv.DictWriter(stats_f, fieldnames='ref_num ref_name base_count rank'.split(), delimiter='\t')
stats_w.writeheader()
for ref_num, (ref_id, base_count, rank) in enumerate(zip(ref_ids, base_counts, ref_ranks)):
stats_w.writerow({'ref_num': ref_num, 'ref_name': ref_id, 'base_count': base_count, 'rank': rank})
def parser_order_and_orient(parser=argparse.ArgumentParser()):
parser.add_argument('inFasta', help='Input de novo assembly/contigs, FASTA format.')
parser.add_argument(
'inReference', nargs='+',
help=('Reference genome for ordering, orienting, and merging contigs, FASTA format. Multiple filenames may be listed, each '
'containing one reference genome. Alternatively, multiple references may be given by specifying a single filename, '
'and giving the number of reference segments with the nGenomeSegments parameter. If multiple references are given, '
'they must all contain the same number of segments listed in the same order.')
)
parser.add_argument(
'outFasta',
help="""Output assembly, FASTA format, with the same number of
chromosomes as inReference, and in the same order."""
)
parser.add_argument(
'--outAlternateContigs',
help="""Output sequences (FASTA format) from alternative contigs that mapped,
but were not chosen for the final output.""",
default=None
)
parser.add_argument('--nGenomeSegments', dest='n_genome_segments', type=int, default=0,
help="""Number of genome segments. If 0 (the default), the `inReference` parameter is treated as one genome.
If positive, the `inReference` parameter is treated as a list of genomes of nGenomeSegments each.""")
parser.add_argument('--outReference', help='Output the reference chosen for scaffolding to this file')
parser.add_argument('--outStats', help='Output stats used in reference selection')
#parser.add_argument('--aligner',
# help='nucmer (nucleotide) or promer (six-frame translations) [default: %(default)s]',
# choices=['nucmer', 'promer'],
# default='nucmer')
#parser.add_argument("--circular",
# help="""Allow contigs to wrap around the ends of the chromosome.""",
# default=False,
# action="store_true",
# dest="circular")
parser.add_argument(
"--breaklen",
"-b",
help="""Amount to extend alignment clusters by (if --extend).
nucmer default 200, promer default 60.""",
type=int,
default=None,
dest="breaklen"
)
parser.add_argument(
"--maxgap",
"-g",
help="""Maximum gap between two adjacent matches in a cluster.
Our default is %(default)s.
nucmer default 90, promer default 30. Manual suggests going to 1000.""",
type=int,
default=200,
dest="maxgap"
)
parser.add_argument(
"--minmatch",
"-l",
help="""Minimum length of an maximal exact match.
Our default is %(default)s.
nucmer default 20, promer default 6.""",
type=int,
default=10,
dest="minmatch"
)
parser.add_argument(
"--mincluster",
"-c",
help="""Minimum cluster length.
nucmer default 65, promer default 20.""",
type=int,
default=None,
dest="mincluster"
)
parser.add_argument(
"--min_pct_id",
"-i",
type=float,
default=0.6,
help="show-tiling: minimum percent identity for contig alignment (0.0 - 1.0, default: %(default)s)"
)
parser.add_argument(
"--min_contig_len",
type=int,
default=200,
help="show-tiling: reject contigs smaller than this (default: %(default)s)"
)
parser.add_argument(
"--min_pct_contig_aligned",
"-v",
type=float,
default=0.3,
help="show-tiling: minimum percent of contig length in alignment (0.0 - 1.0, default: %(default)s)"
)
#parser.add_argument("--trimmed_contigs",
# default=None,
# help="optional output file for trimmed contigs")
util.cmd.common_args(parser, (('threads', None), ('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, order_and_orient, split_args=True)
return parser
__commands__.append(('order_and_orient', parser_order_and_orient))
class IncompleteAssemblyError(Exception):
def __init__(self, actual_n, expected_n):
super(IncompleteAssemblyError, self).__init__(
'All computed scaffolds are incomplete. Best assembly has {} contigs, expected {}'.format(
actual_n, expected_n)
)
class PoorAssemblyError(Exception):
def __init__(self, chr_idx, seq_len, non_n_count, min_length, segment_length):
super(PoorAssemblyError, self).__init__(
'Error: poor assembly quality, chr {}: contig length {}, unambiguous bases {}; bases required of reference segment length: {}/{} ({:.0%})'.format(
chr_idx, seq_len, non_n_count, min_length, int(segment_length), float(min_length)/float(segment_length)
)
)
def impute_from_reference(
inFasta,
inReference,
outFasta,
minLengthFraction,
minUnambig,
replaceLength,
newName=None,
aligner='muscle',
index=False
):
'''
This takes a de novo assembly, aligns against a reference genome, and
imputes all missing positions (plus some of the chromosome ends)
with the reference genome. This provides an assembly with the proper
structure (but potentially wrong sequences in areas) from which
we can perform further read-based refinement.
Two steps:
filter_short_seqs: We then toss out all assemblies that come out to
< 15kb or < 95% unambiguous and fail otherwise.
modify_contig: Finally, we trim off anything at the end that exceeds
the length of the known reference assembly. We also replace all
Ns and everything within 55bp of the chromosome ends with the
reference sequence. This is clearly incorrect consensus sequence,
but it allows downstream steps to map reads in parts of the genome
that would otherwise be Ns, and we will correct all of the inferred
positions with two steps of read-based refinement (below), and
revert positions back to Ns where read support is lacking.
FASTA indexing: output assembly is indexed for Picard, Samtools, Novoalign.
'''
tempFastas = []
pmc = parser_modify_contig(argparse.ArgumentParser())
assert aligner in ('muscle', 'mafft', 'mummer')
with open(inFasta, 'r') as asmFastaFile:
with open(inReference, 'r') as refFastaFile:
asmFasta = Bio.SeqIO.parse(asmFastaFile, 'fasta')
refFasta = Bio.SeqIO.parse(refFastaFile, 'fasta')
for idx, (refSeqObj, asmSeqObj) in enumerate(zip_longest(refFasta, asmFasta)):
# our zip fails if one file has more seqs than the other
if not refSeqObj or not asmSeqObj:
raise KeyError("inFasta and inReference do not have the same number of sequences. This could be because the de novo assembly process was unable to create contigs for all segments.")
# error if PoorAssembly
minLength = len(refSeqObj) * minLengthFraction
non_n_count = unambig_count(asmSeqObj.seq)
seq_len = len(asmSeqObj)
log.info(
"Assembly Quality - segment {idx} - name {segname} - contig len {len_actual} / {len_desired} ({min_frac}) - unambiguous bases {unamb_actual} / {unamb_desired} ({min_unamb})".format(
idx=idx + 1,
segname=refSeqObj.id,
len_actual=seq_len,
len_desired=len(refSeqObj),
min_frac=minLengthFraction,
unamb_actual=non_n_count,
unamb_desired=seq_len,
min_unamb=minUnambig
)
)
if seq_len < minLength or non_n_count < seq_len * minUnambig:
raise PoorAssemblyError(idx + 1, seq_len, non_n_count, minLength, len(refSeqObj))
# prepare temp input and output files
tmpOutputFile = util.file.mkstempfname(prefix='seq-out-{idx}-'.format(idx=idx), suffix=".fasta")
concat_file = util.file.mkstempfname('.ref_and_actual.fasta')
ref_file = util.file.mkstempfname('.ref.fasta')
actual_file = util.file.mkstempfname('.actual.fasta')
aligned_file = util.file.mkstempfname('.'+aligner+'.fasta')
refName = refSeqObj.id
with open(concat_file, 'wt') as outf:
Bio.SeqIO.write([refSeqObj, asmSeqObj], outf, "fasta")
with open(ref_file, 'wt') as outf:
Bio.SeqIO.write([refSeqObj], outf, "fasta")
with open(actual_file, 'wt') as outf:
Bio.SeqIO.write([asmSeqObj], outf, "fasta")
# align scaffolded genome to reference (choose one of three aligners)
if aligner == 'mafft':
tools.mafft.MafftTool().execute(
[ref_file, actual_file], aligned_file, False, True, True, False, False, None
)
elif aligner == 'muscle':
if len(refSeqObj) > 40000:
tools.muscle.MuscleTool().execute(
concat_file, aligned_file, quiet=False,
maxiters=2, diags=True
)
else:
tools.muscle.MuscleTool().execute(concat_file, aligned_file, quiet=False)
elif aligner == 'mummer':
tools.mummer.MummerTool().align_one_to_one(ref_file, actual_file, aligned_file)
# run modify_contig
args = [
aligned_file, tmpOutputFile, refName, '--call-reference-ns', '--trim-ends', '--replace-5ends',
'--replace-3ends', '--replace-length', str(replaceLength), '--replace-end-gaps'
]
if newName:
# renames the segment name "sampleName-idx" where idx is the segment number
args.extend(['--name', newName + "-" + str(idx + 1)])
args = pmc.parse_args(args)
args.func_main(args)
# clean up
os.unlink(concat_file)
os.unlink(ref_file)
os.unlink(actual_file)
os.unlink(aligned_file)
tempFastas.append(tmpOutputFile)
# merge outputs
util.file.concat(tempFastas, outFasta)
for tmpFile in tempFastas:
os.unlink(tmpFile)
# Index final output FASTA for Picard/GATK, Samtools, and Novoalign
if index:
tools.samtools.SamtoolsTool().faidx(outFasta, overwrite=True)
tools.picard.CreateSequenceDictionaryTool().execute(outFasta, overwrite=True)
tools.novoalign.NovoalignTool().index_fasta(outFasta)
return 0
def parser_impute_from_reference(parser=argparse.ArgumentParser()):
parser.add_argument(
'inFasta',
help='Input assembly/contigs, FASTA format, already ordered, oriented and merged with inReference.'
)
parser.add_argument('inReference', help='Reference genome to impute with, FASTA format.')
parser.add_argument('outFasta', help='Output assembly, FASTA format.')
parser.add_argument("--newName", default=None, help="rename output chromosome (default: do not rename)")
parser.add_argument(
"--minLengthFraction",
type=float,
default=0.5,
help="minimum length for contig, as fraction of reference (default: %(default)s)"
)
parser.add_argument(
"--minUnambig",
type=float,
default=0.5,
help="minimum percentage unambiguous bases for contig (default: %(default)s)"
)
parser.add_argument(
"--replaceLength",
type=int,
default=0,
help="length of ends to be replaced with reference (default: %(default)s)"
)
parser.add_argument(
'--aligner',
help="""which method to use to align inFasta to
inReference. "muscle" = MUSCLE, "mafft" = MAFFT,
"mummer" = nucmer. [default: %(default)s]""",
choices=['muscle', 'mafft', 'mummer'],
default='muscle'
)
parser.add_argument(
"--index",
help="""Index outFasta for Picard/GATK, Samtools, and Novoalign.""",
default=False,
action="store_true",
dest="index"
)
util.cmd.common_args(parser, (('loglevel', None), ('version', None), ('tmp_dir', None)))
util.cmd.attach_main(parser, impute_from_reference, split_args=True)
return parser
__commands__.append(('impute_from_reference', parser_impute_from_reference))
def refine_assembly(
inFasta,
inBam,
outFasta,
outVcf=None,
outBam=None,
novo_params='',
min_coverage=2,
major_cutoff=0.5,
chr_names=None,
keep_all_reads=False,
already_realigned_bam=None,
JVMmemory=None,
threads=None,
gatk_path=None,
novoalign_license_path=None
):
''' This a refinement step where we take a crude assembly, align
all reads back to it, and modify the assembly to the majority
allele at each position based on read pileups.
This step considers both SNPs as well as indels called by GATK
and will correct the consensus based on GATK calls.
Reads are aligned with Novoalign, then PCR duplicates are removed
with Picard (in order to debias the allele counts in the pileups),
and realigned with GATK's IndelRealigner (in order to call indels).
Output FASTA file is indexed for Picard, Samtools, and Novoalign.
'''
chr_names = chr_names or []
# if the input fasta is empty, create an empty output fasta and return
if (os.path.getsize(inFasta) == 0):
util.file.touch(outFasta)
return 0
# Get tools
picard_index = tools.picard.CreateSequenceDictionaryTool()
picard_mkdup = tools.picard.MarkDuplicatesTool()
samtools = tools.samtools.SamtoolsTool()
novoalign = tools.novoalign.NovoalignTool(license_path=novoalign_license_path)
gatk = tools.gatk.GATKTool(path=gatk_path)
# Create deambiguated genome for GATK
deambigFasta = util.file.mkstempfname('.deambig.fasta')
deambig_fasta(inFasta, deambigFasta)
picard_index.execute(deambigFasta, overwrite=True)
samtools.faidx(deambigFasta, overwrite=True)
if already_realigned_bam:
realignBam = already_realigned_bam
else:
# Novoalign reads to self
novoBam = util.file.mkstempfname('.novoalign.bam')
min_qual = 0 if keep_all_reads else 1
novoalign.execute(inBam, inFasta, novoBam, options=novo_params.split(), min_qual=min_qual, JVMmemory=JVMmemory)
rmdupBam = util.file.mkstempfname('.rmdup.bam')
opts = ['CREATE_INDEX=true']
if not keep_all_reads:
opts.append('REMOVE_DUPLICATES=true')
picard_mkdup.execute([novoBam], rmdupBam, picardOptions=opts, JVMmemory=JVMmemory)
os.unlink(novoBam)
realignBam = util.file.mkstempfname('.realign.bam')
gatk.local_realign(rmdupBam, deambigFasta, realignBam, JVMmemory=JVMmemory, threads=threads)
os.unlink(rmdupBam)
if outBam:
shutil.copyfile(realignBam, outBam)
# Modify original assembly with VCF calls from GATK
tmpVcf = util.file.mkstempfname('.vcf.gz')
tmpFasta = util.file.mkstempfname('.fasta')
gatk.ug(realignBam, deambigFasta, tmpVcf, JVMmemory=JVMmemory, threads=threads)
if already_realigned_bam is None:
os.unlink(realignBam)
os.unlink(deambigFasta)
name_opts = []
if chr_names:
name_opts = ['--name'] + chr_names
main_vcf_to_fasta(
parser_vcf_to_fasta(argparse.ArgumentParser(
)).parse_args([
tmpVcf,
tmpFasta,
'--trim_ends',
'--min_coverage',
str(min_coverage),
'--major_cutoff',
str(major_cutoff)
] + name_opts)
)
if outVcf:
shutil.copyfile(tmpVcf, outVcf)
if outVcf.endswith('.gz'):
shutil.copyfile(tmpVcf + '.tbi', outVcf + '.tbi')
os.unlink(tmpVcf)
shutil.copyfile(tmpFasta, outFasta)
os.unlink(tmpFasta)
# Index final output FASTA for Picard/GATK, Samtools, and Novoalign
picard_index.execute(outFasta, overwrite=True)
# if the input bam is empty, an empty fasta will be created, however
# faidx cannot index an empty fasta file, so only index if the fasta
# has a non-zero size
if (os.path.getsize(outFasta) > 0):
samtools.faidx(outFasta, overwrite=True)
novoalign.index_fasta(outFasta)
return 0
def parser_refine_assembly(parser=argparse.ArgumentParser()):
parser.add_argument(
'inFasta', help='Input assembly, FASTA format, pre-indexed for Picard, Samtools, and Novoalign.'
)
parser.add_argument('inBam', help='Input reads, unaligned BAM format.')
parser.add_argument(
'outFasta',
help='Output refined assembly, FASTA format, indexed for Picard, Samtools, and Novoalign.'
)
parser.add_argument(
'--already_realigned_bam',
default=None,
help="""BAM with reads that are already aligned to inFasta.
This bypasses the alignment process by novoalign and instead uses the given
BAM to make an assembly. When set, outBam is ignored."""
)
parser.add_argument(
'--outBam',
default=None,
help='Reads aligned to inFasta. Unaligned and duplicate reads have been removed. GATK indel realigned.'
)
parser.add_argument('--outVcf', default=None, help='GATK genotype calls for genome in inFasta coordinate space.')
parser.add_argument(
'--min_coverage',
default=3,
type=int,
help='Minimum read coverage required to call a position unambiguous.'