forked from h3abionet/TADA
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.nf
1637 lines (1325 loc) · 53.7 KB
/
main.nf
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 nextflow
/*
========================================================================================
D A D A 2 P I P E L I N E
========================================================================================
DADA2 NEXTFLOW PIPELINE FOR UCT CBIO, HPCBio
----------------------------------------------------------------------------------------
*/
def helpMessage() {
log.info"""
===================================
${workflow.repository}/16S-rDNA-dada2-pipeline ~ version ${params.version}
===================================
Usage:
This pipeline can be run specifying parameters in a config file or with command line flags.
The typical example for running the pipeline with command line flags is as follows:
nextflow run uct-cbio/16S-rDNA-dada2-pipeline --reads '*_R{1,2}.fastq.gz' --trimFor 24 --trimRev 25 --reference 'gg_13_8_train_set_97.fa.gz' -profile uct_hex
The typical command for running the pipeline with your own config (instead of command line flags) is as follows:
nextflow run uct-cbio/16S-rDNA-dada2-pipeline -c dada2_user_input.config -profile uct_hex
where:
dada2_user_input.config is the configuration file (see example 'dada2_user_input.config')
NB: -profile uct_hex still needs to be specified from the command line
To override existing values from the command line, please type these parameters:
Mandatory arguments:
--reads Path to input data (must be surrounded with quotes)
-profile Hardware config to use. Currently profile available for UCT's HPC 'uct_hex' - create your own if necessary
NB -profile should always be specified on the command line, not in the config file
--trimFor integer. headcrop of read1 (set 0 if no trimming is needed)
--trimRev integer. headcrop of read2 (set 0 if no trimming is needed)
--reference Path to taxonomic database to be used for annotation (e.g. gg_13_8_train_set_97.fa.gz)
All available read preparation parameters:
--trimFor integer. headcrop of read1
--trimRev integer. headcrop of read2
--truncFor integer. truncate read1 here (i.e. if you want to trim 10bp off the end of a 250bp R1, truncFor should be set to 240). enforced before trimFor/trimRev
--truncRev integer. truncate read2 here ((i.e. if you want to trim 10bp off the end of a 250bp R2, truncRev should be set to 240). enforced before trimFor/trimRev
--maxEEFor integer. After truncation, R1 reads with higher than maxEE "expected errors" will be discarded. EE = sum(10^(-Q/10)), default=2
--maxEERev integer. After truncation, R1 reads with higher than maxEE "expected errors" will be discarded. EE = sum(10^(-Q/10)), default=2
--truncQ integer. Truncate reads at the first instance of a quality score less than or equal to truncQ; default=2
--maxN integer. Discard reads with more than maxN number of Ns in read; default=0
--maxLen integer. maximum length of trimmed sequence; maxLen is enforced before trimming and truncation; default=Inf (no maximum)
--minLen integer. minLen is enforced after trimming and truncation; default=50
--rmPhiX {"T","F"}. remove PhiX from read
--minOverlap integer. minimum length of the overlap required for merging R1 and R2; default=20 (dada2 package default=12)
--maxMismatch integer. The maximum mismatches allowed in the overlap region; default=0
--trimOverhang {"T","F"}. If "T" (true), "overhangs" in the alignment between R1 and R2 are trimmed off.
"Overhangs" are when R2 extends past the start of R1, and vice-versa, as can happen when reads are longer than the amplicon and read into the other-direction primer region. Default="F" (false)
Other arguments:
--dadaOpt.XXX Set as e.g. --dadaOpt.HOMOPOLYMER_GAP_PENALTY=-1 Global defaults for the dada function, see ?setDadaOpt in R for available options and their defaults
--pool Should sample pooling be used to aid identification of low-abundance ASVs? Options are
pseudo pooling: "pseudo", true: "T", false: "F"
--outdir The output directory where the results will be saved
--email Set this parameter to your e-mail address to get a summary e-mail with details of the run
sent to you when the workflow exits
-name Name for the pipeline run. If not specified, Nextflow will automatically generate a random mnemonic.
--idType The ASV IDs are renamed to simplify downstream analysis, in particular with downstream tools. The
default is "ASV", which simply renames the sequences in sequencial order. Alternatively, this can be
set to "md5" which will run MD5 on the sequence and generate a QIIME2-like unique hash.
Help:
--help Will print out summary above when executing nextflow run uct-cbio/16S-rDNA-dada2-pipeline
Merging arguments (optional):
--minOverlap The minimum length of the overlap required for merging R1 and R2; default=20 (dada2 package default=12)
--maxMismatch The maximum mismatches allowed in the overlap region; default=0.
--trimOverhang If "T" (true), "overhangs" in the alignment between R1 and R2 are trimmed off. "Overhangs" are when R2 extends past the start of R1, and vice-versa, as can happen
when reads are longer than the amplicon and read into the other-direction primer region. Default="F" (false)
--minMergedLen Minimum length of fragment *after* merging
--maxMergedLen Maximum length of fragment *after* merging
Taxonomic arguments (optional):
--species Specify path to fasta file. See dada2 addSpecies() for more detail.
""".stripIndent()
}
// TODO: add checks on options
// Show help message
params.help = false
if (params.help){
helpMessage()
exit 0
}
//Validate inputs
if ( params.trimFor == false && params.amplicon == '16S') {
exit 1, "Must set length of R1 (--trimFor) that needs to be trimmed (set 0 if no trimming is needed)"
}
if ( params.trimRev == false && params.amplicon == '16S') {
exit 1, "Must set length of R2 (--trimRev) that needs to be trimmed (set 0 if no trimming is needed)"
}
// if ( params.reference == false ) {
// exit 1, "Must set reference database using --reference"
// }
if (params.fwdprimer == false && params.amplicon == 'ITS'){
exit 1, "Must set forward primer using --fwdprimer"
}
if (params.revprimer == false && params.amplicon == 'ITS'){
exit 1, "Must set reverse primer using --revprimer"
}
if (params.aligner == 'infernal' && params.infernalCM == false){
exit 1, "Must set covariance model using --infernalCM when using Infernal"
}
if (!(['simple','md5'].contains(params.idType))) {
exit 1, "--idType can only be set to 'simple' or 'md5', got ${params.idType}"
}
// Has the run name been specified by the user?
// this has the bonus effect of catching both -name and --name
custom_runName = params.name
if( !(workflow.runName ==~ /[a-z]+_[a-z]+/) ){
custom_runName = workflow.runName
}
Channel
.fromFilePairs( params.reads )
.ifEmpty { error "Cannot find any reads matching: ${params.reads}" }
.into { dada2ReadPairsToQual; dada2ReadPairs }
// Header log info
log.info "==================================="
log.info " ${params.base}/16S-rDNA-dada2-pipeline ~ version ${params.version}"
log.info "==================================="
def summary = [:]
summary['Run Name'] = custom_runName ?: workflow.runName
summary['Reads'] = params.reads
summary['Forward primer'] = params.fwdprimer
summary['Reverse primer'] = params.revprimer
summary['Amplicon type'] = params.amplicon
summary['trimFor'] = params.trimFor
summary['trimRev'] = params.trimRev
summary['truncFor'] = params.truncFor
summary['truncRev'] = params.truncRev
summary['truncQ'] = params.truncQ
summary['maxEEFor'] = params.maxEEFor
summary['maxEERev'] = params.maxEERev
summary['maxN'] = params.maxN
summary['maxLen'] = params.maxLen
summary['minLen'] = params.minLen
summary['rmPhiX'] = params.rmPhiX
summary['minOverlap'] = params.minOverlap
summary['maxMismatch'] = params.maxMismatch
summary['trimOverhang'] = params.trimOverhang
summary['species'] = params.species
summary['dadaOpt'] = params.dadaOpt
summary['pool'] = params.pool
summary['qualityBinning'] = params.qualityBinning
summary['Reference'] = params.reference
summary['Max Memory'] = params.max_memory
summary['Max CPUs'] = params.max_cpus
summary['Max Time'] = params.max_time
summary['Output dir'] = params.outdir
summary['Working dir'] = workflow.workDir
summary['Container'] = workflow.container
if(workflow.revision) summary['Pipeline Release'] = workflow.revision
summary['Current home'] = "$HOME"
summary['Current user'] = "$USER"
summary['Current path'] = "$PWD"
summary['Script dir'] = workflow.projectDir
summary['Config Profile'] = workflow.profile
if(params.email) {
summary['E-mail Address'] = params.email
}
log.info summary.collect { k,v -> "${k.padRight(15)}: $v" }.join("\n")
log.info "========================================="
/*
*
* Step 1: Filter and trim (run per sample?)
*
*/
process runFastQC {
tag { "rFQC.${pairId}" }
publishDir "${params.outdir}/FASTQC-Raw", mode: "copy", overwrite: true
input:
set pairId, file(in_fastq) from dada2ReadPairsToQual
output:
file '*_fastqc.{zip,html}' into fastqc_files,fastqc_files2
"""
fastqc --nogroup -q ${in_fastq.get(0)} ${in_fastq.get(1)}
"""
}
// TODO: combine MultiQC reports and split by directory (no need for two)
process runMultiQC {
tag { "runMultiQC" }
publishDir "${params.outdir}/MultiQC-Raw", mode: 'copy', overwrite: true
input:
file('./raw-seq/*') from fastqc_files.collect()
output:
file "*_report.html" into multiqc_report
file "*_data"
script:
interactivePlots = params.interactiveMultiQC == true ? "-ip" : ""
"""
multiqc ${interactivePlots} .
"""
}
/* ITS amplicon filtering */
// Note: should explore cutadapt options more: https://github.com/benjjneb/dada2/issues/785
// https://cutadapt.readthedocs.io/en/stable/guide.html#more-than-one
if (params.amplicon == 'ITS') {
process itsFilterAndTrimStep1 {
tag { "ITS_Step1_${pairId}" }
input:
set pairId, file(reads) from dada2ReadPairs
output:
set val(pairId), "${pairId}.R[12].noN.fastq.gz" optional true into itsStep2
set val(pairId), "${pairId}.out.RDS" into itsStep3Trimming // needed for join() later
file('forward_rc') into forwardP
file('reverse_rc') into reverseP
when:
params.precheck == false
script:
"""
#!/usr/bin/env Rscript
library(dada2); packageVersion("dada2")
library(ShortRead); packageVersion("ShortRead")
library(Biostrings); packageVersion("Biostrings")
#Filter out reads with N's
out1 <- filterAndTrim(fwd = "${reads[0]}",
filt = paste0("${pairId}", ".R1.noN.fastq.gz"),
rev = "${reads[1]}",
filt.rev = paste0("${pairId}", ".R2.noN.fastq.gz"),
maxN = 0,
multithread = ${task.cpus})
FWD.RC <- dada2:::rc("${params.fwdprimer}")
REV.RC <- dada2:::rc("${params.revprimer}")
# this may switch to 'env' in the process at some point:
# https://www.nextflow.io/docs/latest/process.html?highlight=env#output-env
# untested within R though
forP <- file("forward_rc")
writeLines(FWD.RC, forP)
close(forP)
revP <- file("reverse_rc")
writeLines(REV.RC, revP)
close(revP)
saveRDS(out1, "${pairId}.out.RDS")
"""
}
process itsFilterAndTrimStep2 {
tag { "ITS_Step2_${pairId}" }
publishDir "${params.outdir}/dada2-FilterAndTrim", mode: "copy", overwrite: true
input:
set pairId, reads from itsStep2
file(forP) from forwardP
file(revP) from reverseP
output:
set val(pairId), "${pairId}.R[12].cutadapt.fastq.gz" optional true into itsStep3
file "*.cutadapt.out" into cutadaptToMultiQC
when:
params.precheck == false
script:
"""
FWD_PRIMER=\$(<forward_rc)
REV_PRIMER=\$(<reverse_rc)
cutadapt -g "${params.fwdprimer}" -a \$FWD_PRIMER \\
-G "${params.revprimer}" -A \$REV_PRIMER \\
--cores ${task.cpus} \\
-n 2 \\
-o "${pairId}.R1.cutadapt.fastq.gz" \\
-p "${pairId}.R2.cutadapt.fastq.gz" \\
"${reads[0]}" "${reads[1]}" > "${pairId}.cutadapt.out"
"""
}
process itsFilterAndTrimStep3 {
tag { "ITS_Step3_${pairId}" }
publishDir "${params.outdir}/dada2-FilterAndTrim", mode: "copy", overwrite: true
input:
set pairId, file(reads), file(trimming) from itsStep3.join(itsStep3Trimming)
output:
set val(pairId), "*.R1.filtered.fastq.gz", "*.R2.filtered.fastq.gz" optional true into filteredReadsforQC, filteredReads
file "*.R1.filtered.fastq.gz" optional true into forReads
file "*.R2.filtered.fastq.gz" optional true into revReads
file "*.trimmed.txt" into trimTracking
when:
params.precheck == false
script:
"""
#!/usr/bin/env Rscript
library(dada2); packageVersion("dada2")
library(ShortRead); packageVersion("ShortRead")
library(Biostrings); packageVersion("Biostrings")
out1 <- readRDS("${trimming}")
out2 <- filterAndTrim(fwd = paste0("${pairId}",".R1.cutadapt.fastq.gz"),
filt = paste0("${pairId}", ".R1.filtered.fastq.gz"),
rev = paste0("${pairId}",".R2.cutadapt.fastq.gz"),
filt.rev = paste0("${pairId}", ".R2.filtered.fastq.gz"),
maxEE = c(${params.maxEEFor},${params.maxEERev}),
truncLen = c(${params.truncFor},${params.truncRev}),
truncQ = ${params.truncQ},
maxN = ${params.maxN},
rm.phix = as.logical(${params.rmPhiX}),
maxLen = ${params.maxLen},
minLen = ${params.minLen},
compress = TRUE,
verbose = TRUE,
multithread = ${task.cpus})
#Change input read counts to actual raw read counts
out3 <- cbind(out1, out2)
colnames(out3) <- c('input', 'filterN', 'cutadapt', 'filtered')
write.csv(out3, paste0("${pairId}", ".trimmed.txt"))
"""
}
}
/* 16S amplicon filtering */
else if (params.amplicon == '16S'){
process filterAndTrim {
tag { "16s_${pairId}" }
publishDir "${params.outdir}/dada2-FilterAndTrim", mode: "copy", overwrite: true
input:
set pairId, file(reads) from dada2ReadPairs
output:
set val(pairId), "*.R1.filtered.fastq.gz", "*.R2.filtered.fastq.gz" optional true into filteredReadsforQC, filteredReads
file "*.R1.filtered.fastq.gz" optional true into forReads
file "*.R2.filtered.fastq.gz" optional true into revReads
file "*.trimmed.txt" into trimTracking
when:
params.precheck == false
script:
phix = params.rmPhiX ? '--rmPhiX TRUE' : '--rmPhiX FALSE'
"""
16S_FilterAndTrim.R ${phix} --id ${pairId} \\
--fwd ${reads[0]} \\
--rev ${reads[1]} \\
--cpus ${task.cpus} \\
--trimFor ${params.trimFor} \\
--trimRev ${params.trimRev} \\
--truncFor ${params.truncFor} \\
--truncRev ${params.truncRev} \\
--truncQ ${params.truncQ} \\
--maxEEFor ${params.maxEEFor} \\
--maxEERev ${params.maxEERev} \\
--maxN ${params.maxN} \\
--maxLen ${params.maxLen} \\
--minLen ${params.minLen}
"""
}
cutadaptToMultiQC = Channel.empty()
} else {
// We need to shut this down!
cutadaptToMultiQC = Channel.empty()
filteredReads = Channel.empty()
filteredReadsforQC = Channel.empty()
}
process runFastQC_postfilterandtrim {
tag { "rFQC_post_FT.${pairId}" }
publishDir "${params.outdir}/FastQC-Post-FilterTrim", mode: "copy", overwrite: true
input:
set val(pairId), file(filtFor), file(filtRev) from filteredReadsforQC
output:
file '*_fastqc.{zip,html}' into fastqc_files_post
when:
params.precheck == false
"""
fastqc --nogroup -q ${filtFor} ${filtRev}
"""
}
process runMultiQC_postfilterandtrim {
tag { "runMultiQC_postfilterandtrim" }
publishDir "${params.outdir}/MultiQC-Post-FilterTrim", mode: 'copy', overwrite: true
input:
file('./raw-seq/*') from fastqc_files2.collect()
file('./trimmed-seq/*') from fastqc_files_post.collect()
file('./cutadapt/*') from cutadaptToMultiQC.collect()
output:
file "*_report.html" into multiqc_report_post
file "*_data"
when:
params.precheck == false
script:
interactivePlots = params.interactiveMultiQC == true ? "-ip" : ""
"""
multiqc ${interactivePlots} .
"""
}
process mergeTrimmedTable {
tag { "mergeTrimmedTable" }
publishDir "${params.outdir}/dada2-FilterAndTrim", mode: "copy", overwrite: true
input:
file trimData from trimTracking.collect()
output:
file "all.trimmed.csv" into trimmedReadTracking
when:
params.precheck == false
script:
"""
#!/usr/bin/env Rscript
trimmedFiles <- list.files(path = '.', pattern = '*.trimmed.txt')
sample.names <- sub('.trimmed.txt', '', trimmedFiles)
trimmed <- do.call("rbind", lapply(trimmedFiles, function (x) as.data.frame(read.csv(x))))
colnames(trimmed)[1] <- "Sequence"
trimmed\$SampleID <- sample.names
write.csv(trimmed, "all.trimmed.csv", row.names = FALSE)
"""
}
/*
*
* Step 2: Learn error rates (run on all samples)
*
*/
// TODO: combine For and Rev process to reduce code duplication?
process LearnErrorsFor {
tag { "LearnErrorsFor" }
publishDir "${params.outdir}/dada2-LearnErrors", mode: "copy", overwrite: true
input:
file fReads from forReads.collect()
output:
file "errorsF.RDS" into errorsFor
file "*.pdf"
when:
params.precheck == false
script:
"""
#!/usr/bin/env Rscript
library(dada2);
packageVersion("dada2")
setDadaOpt(${params.dadaOpt.collect{k,v->"$k=$v"}.join(", ")})
# File parsing
filtFs <- list.files('.', pattern="R1.filtered.fastq.gz", full.names = TRUE)
sample.namesF <- sapply(strsplit(basename(filtFs), "_"), `[`, 1) # Assumes filename = samplename_XXX.fastq.gz
set.seed(100)
# Learn forward error rates
errF <- learnErrors(filtFs, multithread=${task.cpus})
if (as.logical('${params.qualityBinning}') == TRUE ) {
print("Running binning correction")
errs <- t(apply(getErrors(errF), 1, function(x) { x[x < x[40]] = x[40]; return(x)} ))
errF\$err_out <- errs
}
pdf("R1.err.pdf")
plotErrors(errF, nominalQ=TRUE)
dev.off()
saveRDS(errF, "errorsF.RDS")
"""
}
process LearnErrorsRev {
tag { "LearnErrorsRev" }
publishDir "${params.outdir}/dada2-LearnErrors", mode: "copy", overwrite: true
input:
file rReads from revReads.collect()
output:
file "errorsR.RDS" into errorsRev
file "*.pdf"
when:
params.precheck == false
script:
"""
#!/usr/bin/env Rscript
library(dada2);
packageVersion("dada2")
setDadaOpt(${params.dadaOpt.collect{k,v->"$k=$v"}.join(", ")})
# load error profiles
# File parsing
filtRs <- list.files('.', pattern="R2.filtered.fastq.gz", full.names = TRUE)
sample.namesR <- sapply(strsplit(basename(filtRs), "_"), `[`, 1) # Assumes filename = samplename_XXX.fastq.gz
set.seed(100)
# Learn forward error rates
errR <- learnErrors(filtRs, multithread=${task.cpus})
# optional NovaSeq binning error correction
if (as.logical('${params.qualityBinning}') == TRUE) {
print("Running binning correction")
errs <- t(apply(getErrors(errR), 1, function(x) { x[x < x[40]] = x[40]; return(x)} ))
errR\$err_out <- errs
}
pdf("R2.err.pdf")
plotErrors(errR, nominalQ=TRUE)
dev.off()
saveRDS(errR, "errorsR.RDS")
"""
}
/*
*
* Step 3: Dereplication, Sample Inference, Merge Pairs
*
*/
/*
*
* Step 4: Construct sequence table
*
*/
if (params.pool == "T" || params.pool == 'pseudo') {
process PoolSamplesInferDerepAndMerge {
tag { "PoolSamplesInferDerepAndMerge" }
publishDir "${params.outdir}/dada2-Derep-Pooled", mode: "copy", overwrite: true
// TODO: filteredReads channel has ID and two files, should fix this
// with a closure, something like { it[1:2] }, or correct the channel
// as the ID can't be used anyway
input:
file filts from filteredReads.collect( )
file errFor from errorsFor
file errRev from errorsRev
output:
file "seqtab.RDS" into seqTable,rawSeqTableToRename
file "all.mergers.RDS" into mergerTracking
file "all.ddF.RDS" into dadaForReadTracking
file "all.ddR.RDS" into dadaRevReadTracking
file "all.derepFs.RDS" into dadaForDerep
file "all.derepRs.RDS" into dadaRevDerep
file "seqtab.*"
when:
params.precheck == false
script:
if (params.rescueUnmerged == true) {
"""
VariableLenMergePairs-Pooled.R --errFor ${errFor} \\
--errRev ${errRev} \\
--pool ${params.pool} \\
--cpus ${task.cpus} \\
--minOverlap ${params.minOverlap} \\
--maxMismatch ${params.maxMismatch} \\
--trimOverhang ${params.trimOverhang} \\
--justConcatenate ${params.justConcatenate} \\
--rescueUnmerged ${params.rescueUnmerged} \\
--minMergedLen ${params.minMergedLen} \\
--maxMergedLen ${params.maxMergedLen}
"""
} else { // This is the normal route
"""
MergePairs-Pooled.R --errFor ${errFor} \\
--errRev ${errRev} \\
--pool ${params.pool} \\
--cpus ${task.cpus} \\
--minOverlap ${params.minOverlap} \\
--maxMismatch ${params.maxMismatch} \\
--trimOverhang ${params.trimOverhang} \\
--minMergedLen ${params.minMergedLen} \\
--maxMergedLen ${params.maxMergedLen} \\
--justConcatenate ${params.justConcatenate}
"""
}
}
} else {
// pool = F, process per sample
process PerSampleInferDerepAndMerge {
tag { "PerSampleInferDerepAndMerge" }
publishDir "${params.outdir}/dada2-Derep", mode: "copy", overwrite: true
input:
set val(pairId), file(filtFor), file(filtRev) from filteredReads
file errFor from errorsFor
file errRev from errorsRev
output:
file "seqtab.RDS" into seqTable
file "all.mergers.RDS" into mergerTracking
file "all.ddF.RDS" into dadaForReadTracking
file "all.ddR.RDS" into dadaRevReadTracking
file "all.derepF.RDS" into dadaForDerep
file "all.derepR.RDS" into dadaRevDerep
file "seqtab.*"
when:
params.precheck == false
script:
"""
#!/usr/bin/env Rscript
library(dada2)
packageVersion("dada2")
setDadaOpt(${params.dadaOpt.collect{k,v->"$k=$v"}.join(", ")})
errF <- readRDS("${errFor}")
errR <- readRDS("${errRev}")
cat("Processing:", "${pairId}", "\\n")
derepF <- derepFastq("${filtFor}")
ddF <- dada(derepF, err=errF, multithread=${task.cpus}, pool=as.logical("${params.pool}"))
derepR <- derepFastq("${filtRev}")
ddR <- dada(derepR, err=errR, multithread=${task.cpus}, pool=as.logical("${params.pool}"))
merger <- mergePairs(ddF, derepF, ddR, derepR,
returnRejects = TRUE,
minOverlap = ${params.minOverlap},
maxMismatch = ${params.maxMismatch},
trimOverhang = as.logical("${params.trimOverhang}"),
justConcatenate=as.logical("${params.justConcatenate}")
)
saveRDS(merger, paste("${pairId}", "merged", "RDS", sep="."))
saveRDS(ddFs, "all.ddF.RDS")
saveRDS(derepFs, "all.derepFs.RDS")
saveRDS(ddRs, "all.ddR.RDS")
saveRDS(derepRs, "all.derepRs.RDS")
"""
}
process mergeDadaRDS {
tag { "mergeDadaRDS" }
publishDir "${params.outdir}/dada2-Inference", mode: "copy", overwrite: true
input:
file ddFs from dadaFor.collect()
file ddRs from dadaRev.collect()
output:
file "all.ddF.RDS" into dadaForReadTracking
file "all.ddR.RDS" into dadaRevReadTracking
when:
params.precheck == false
script:
'''
#!/usr/bin/env Rscript
library(dada2)
packageVersion("dada2")
dadaFs <- lapply(list.files(path = '.', pattern = '.ddF.RDS$'), function (x) readRDS(x))
names(dadaFs) <- sub('.ddF.RDS', '', list.files('.', pattern = '.ddF.RDS'))
dadaRs <- lapply(list.files(path = '.', pattern = '.ddR.RDS$'), function (x) readRDS(x))
names(dadaRs) <- sub('.ddR.RDS', '', list.files('.', pattern = '.ddR.RDS'))
saveRDS(dadaFs, "all.ddF.RDS")
saveRDS(dadaRs, "all.ddR.RDS")
'''
}
process SequenceTable {
tag { "SequenceTable" }
publishDir "${params.outdir}/dada2-SeqTable", mode: "copy", overwrite: true
input:
file mr from mergedReads.collect()
output:
file "seqtab.RDS" into seqTable,rawSeqTableToRename
file "all.mergers.RDS" into mergerTracking
when:
params.precheck == false
script:
'''
#!/usr/bin/env Rscript
library(dada2)
packageVersion("dada2")
mergerFiles <- list.files(path = '.', pattern = '.*.RDS$')
pairIds <- sub('.merged.RDS', '', mergerFiles)
mergers <- lapply(mergerFiles, function (x) readRDS(x))
names(mergers) <- pairIds
seqtab <- makeSequenceTable(mergers)
seqtab <- seqtab[,nchar(colnames(seqtab)) >= ${params.minLen}]
saveRDS(seqtab, "seqtab.RDS")
saveRDS(mergers, "all.mergers.RDS")
'''
}
}
/*
*
* Step 8: Remove chimeras
*
*/
if (!params.skipChimeraDetection) {
process RemoveChimeras {
tag { "RemoveChimeras" }
publishDir "${params.outdir}/dada2-Chimera-Taxonomy", mode: "copy", overwrite: true
input:
file st from seqTable
output:
file "seqtab_final.RDS" into seqTableToTax,seqTableToRename
when:
params.precheck == false
script:
chimOpts = params.removeBimeraDenovoOptions != false ? ", ${params.removeBimeraDenovoOptions}" : ''
"""
#!/usr/bin/env Rscript
library(dada2)
packageVersion("dada2")
st.all <- readRDS("${st}")
# Remove chimeras
seqtab <- removeBimeraDenovo(
st.all,
method="consensus",
multithread=${task.cpus},
verbose=TRUE ${chimOpts}
)
saveRDS(seqtab, "seqtab_final.RDS")
"""
}
} else {
seqTable.into {seqTableToTax;seqTableToRename}
}
/*
*
* Step 9: Taxonomic assignment
*
*/
if (params.reference) {
if (params.taxassignment == 'rdp') {
// TODO: we could combine these into the same script
refFile = file(params.reference)
if (params.species) {
speciesFile = file(params.species)
process AssignTaxSpeciesRDP {
tag { "AssignTaxSpeciesRDP" }
publishDir "${params.outdir}/dada2-Chimera-Taxonomy", mode: "copy", overwrite: true
input:
file st from seqTableToTax
file ref from refFile
file sp from speciesFile
output:
file "tax_final.RDS" into taxFinal,taxTableToTable
file "bootstrap_final.RDS" into bootstrapFinal
when:
params.precheck == false
script:
"""
#!/usr/bin/env Rscript
library(dada2)
packageVersion("dada2")
seqtab <- readRDS("${st}")
# Assign taxonomy
tax <- assignTaxonomy(seqtab, "${ref}",
multithread=${task.cpus},
tryRC = TRUE,
outputBootstraps = TRUE,
minBoot = ${params.minBoot},
verbose = TRUE)
boots <- tax\$boot
tax <- addSpecies(tax\$tax, "${sp}",
tryRC = TRUE,
verbose = TRUE)
rownames(tax) <- colnames(seqtab)
# Write original data
saveRDS(tax, "tax_final.RDS")
saveRDS(boots, "bootstrap_final.RDS")
"""
}
} else {
process AssignTaxonomyRDP {
tag { "TaxonomyRDP" }
publishDir "${params.outdir}/dada2-Chimera-Taxonomy", mode: "copy", overwrite: true
input:
file st from seqTableToTax
file ref from refFile
output:
file "tax_final.RDS" into taxFinal,taxTableToTable
file "bootstrap_final.RDS" into bootstrapFinal
when:
params.precheck == false
script:
taxLevels = params.taxLevels ? "c( ${params.taxLevels} )," : ''
"""
#!/usr/bin/env Rscript
library(dada2)
packageVersion("dada2")
seqtab <- readRDS("${st}")
# Assign taxonomy
tax <- assignTaxonomy(seqtab, "${ref}",
multithread=${task.cpus},
minBoot = ${params.minBoot},
tryRC = TRUE,
outputBootstraps = TRUE, ${taxLevels}
verbose = TRUE
)
# Write to disk
saveRDS(tax\$tax, "tax_final.RDS")
saveRDS(tax\$boot, "bootstrap_final.RDS")
"""
}
}
} else if (params.taxassignment == 'idtaxa') {
// Experimental!!! This assigns full taxonomy to species level, but only for
// some databases; unknown whether this works with concat sequences. ITS
// doesn't seem to be currently supported
process TaxonomyIDTAXA {
tag { "TaxonomyIDTAXA" }
publishDir "${params.outdir}/dada2-Chimera-Taxonomy", mode: "copy", overwrite: true
input:
file st from seqTableToTax
file ref from refFile // this needs to be a database from the IDTAXA site
output:
file "tax_final.RDS" into taxFinal,taxTableToTable
file "bootstrap_final.RDS" into bootstrapFinal
file "raw_idtaxa.RDS"
when:
params.precheck == false
script:
"""
#!/usr/bin/env Rscript
library(dada2)
library(DECIPHER)
packageVersion("DECIPHER")
seqtab <- readRDS("${st}")
# Create a DNAStringSet from the ASVs
dna <- DNAStringSet(getSequences(seqtab))
# load database; this should be a RData file
load("${refFile}")
ids <- IdTaxa(dna, trainingSet,
strand="both",
processors=${task.cpus},
verbose=TRUE)
# ranks of interest
ranks <- c("domain", "phylum", "class", "order", "family", "genus", "species")
saveRDS(ids, 'raw_idtaxa.RDS')
# Convert the output object of class "Taxa" to a matrix analogous to the output from assignTaxonomy
taxid <- t(sapply(ids, function(x) {
m <- match(ranks, x\$rank)
taxa <- x\$taxon[m]
taxa[startsWith(taxa, "unclassified_")] <- NA
taxa
}))
colnames(taxid) <- ranks
rownames(taxid) <- getSequences(seqtab)
boots <- t(sapply(ids, function(x) {
m <- match(ranks, x\$rank)
bs <- x\$confidence[m]
bs
}))
colnames(boots) <- ranks
rownames(boots) <- getSequences(seqtab)
# Write to disk
saveRDS(taxid, "tax_final.RDS")
saveRDS(boots, "bootstrap_final.RDS")
"""
}
} else if (params.taxassignment) {
exit 1, "Unknown taxonomic assignment method set: ${params.taxassignment}"
} else {
exit 1, "No taxonomic assignment method set, but reference passed"
}
} else {
// set tax channels to 'false', do NOT assign taxonomy
taxFinal = Channel.empty()
taxTableToTable = Channel.empty()
bootstrapFinal = Channel.empty()
}
// Note: this is currently a text dump. We've found the primary issue with
// downstream analysis is getting the data in a form that can be useful as
// input, and there isn't much consistency with this as of yet. So for now
// we're using the spaghetti approach (see what sticks). Also, we are running
// into issues with longer sequences (e.g. concatenated ones) used as IDs with
// tools like Fasttree (it doesn't seem to like that).
// Safest way may be to save the simpleID -> seqs as a mapping file, use that in
// any downstream steps (e.g. alignment/tree), then munge the seq names back
// from the mapping table
/*
*
* Step 8.5: Rename ASVs
*
* A number of downstream programs have issues with sequences as IDs, here we
* (optionally) rename these
*
*/
process RenameASVs {
tag { "RenameASVs" }