-
Notifications
You must be signed in to change notification settings - Fork 111
/
main.nf
1354 lines (1123 loc) · 46.5 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
/*
========================================================================================
nf-core/mag
========================================================================================
nf-core/mag Analysis Pipeline. Started 2018-05-22.
#### Homepage / Documentation
https://github.com/nf-core/mag
#### Authors
Hadrien Gourlé HadrienG <hadrien.gourle@slu.se> - hadriengourle.com>
Daniel Straub <d4straub@gmail.com>
----------------------------------------------------------------------------------------
*/
def helpMessage() {
log.info nfcoreHeader()
log.info"""
Usage:
The typical command for running the pipeline is as follows:
nextflow run nf-core/mag --reads '*_R{1,2}.fastq.gz' -profile docker
nextflow run nf-core/mag --manifest 'manifest.tsv' -profile docker
Mandatory arguments:
--reads Path to input data (must be surrounded with quotes)
-profile Configuration profile to use. Can use multiple (comma separated)
Available: conda, docker, singularity, awsbatch, test and more.
Hybrid assembly:
--manifest Path to manifest file (must be surrounded with quotes), required for hybrid assembly with metaSPAdes
Has 4 headerless columns (tab separated): Sample_Id, Long_Reads, Short_Reads_1, Short_Reads_2
Only one file path per entry allowed
Options:
--genome Name of iGenomes reference
--singleEnd Specifies that the input is single end reads
--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
--maxMultiqcEmailFileSize Theshold size for MultiQC report to be attached in notification email. If file generated by pipeline exceeds the threshold, it will not be attached (Default: 25MB)
-name Name for the pipeline run. If not specified, Nextflow will automatically generate a random mnemonic.
Short read preprocessing:
--adapter_forward Sequence of 3' adapter to remove in the forward reads
--adapter_reverse Sequence of 3' adapter to remove in the reverse reads
--mean_quality Mean qualified quality value for keeping read (default: 15)
--trimming_quality Trimming quality value for the sliding window (default: 15)
--keep_phix Keep reads similar to the Illumina internal standard PhiX genome (default: false)
Long read preprocessing:
--skip_adapter_trimming Skip removing adapter sequences from long reads
--longreads_min_length Discard any read which is shorter than this value (default: 1000)
--longreads_keep_percent Keep this percent of bases (default: 90)
--longreads_length_weight The higher the more important is read length when choosing the best reads (default: 10)
--keep_lambda Keep reads similar to the ONT internal standard Escherichia virus Lambda genome (default: false)
Assembly:
--skip_spades Skip Illumina-only SPAdes assembly
--skip_spadeshybrid Skip SPAdes hybrid assembly (only available when using manifest input)
--skip_megahit Skip MEGAHIT assembly
--skip_quast Skip metaQUAST
Taxonomy:
--centrifuge_db [path] Database for taxonomic binning with centrifuge (default: none). E.g. "ftp://ftp.ccb.jhu.edu/pub/infphilo/centrifuge/data/p_compressed+h+v.tar.gz"
--kraken2_db [path] Database for taxonomic binning with kraken2 (default: none). E.g. "ftp://ftp.ccb.jhu.edu/pub/data/kraken2_dbs/minikraken2_v2_8GB_201904_UPDATE.tgz"
--skip_krona Skip creating a krona plot for taxonomic binning
--cat_db [path] Database for taxonomic classification of metagenome assembled genomes (default: none). E.g. "tbb.bio.uu.nl/bastiaan/CAT_prepare/CAT_prepare_20190108.tar.gz"
The zipped file needs to contain a folder named "*taxonomy*" and "*CAT_database*" that hold the respective files.
Binning options:
--skip_binning Skip metagenome binning
--min_contig_size Minimum contig size to be considered for binning (default: 1500)
Bin quality check:
--skip_busco Disable bin QC with BUSCO (default: false)
--busco_reference Download path for BUSCO database, available databases are listed here: https://busco.ezlab.org/
(default: https://busco-archive.ezlab.org/v3/datasets/bacteria_odb9.tar.gz)
AWSBatch options:
--awsqueue The AWSBatch JobQueue that needs to be set when running on AWSBatch
--awsregion The AWS Region for your AWS Batch job to run on
""".stripIndent()
}
/*
* SET UP CONFIGURATION VARIABLES
*/
// Show help message
if (params.help){
helpMessage()
exit 0
}
// Configurable variables
params.name = false
params.multiqc_config = "$baseDir/conf/multiqc_config.yaml"
params.email = false
params.plaintext_email = false
params.manifest = false
params.busco_reference = "https://busco-archive.ezlab.org/v3/datasets/bacteria_odb9.tar.gz"
ch_multiqc_config = Channel.fromPath(params.multiqc_config)
ch_output_docs = Channel.fromPath("$baseDir/docs/output.md")
// AWSBatch sanity checking
if(workflow.profile == 'awsbatch'){
if (!params.awsqueue || !params.awsregion) exit 1, "Specify correct --awsqueue and --awsregion parameters on AWSBatch!"
if (!workflow.workDir.startsWith('s3') || !params.outdir.startsWith('s3')) exit 1, "Specify S3 URLs for workDir and outdir parameters on AWSBatch!"
}
// Check workDir/outdir paths to be S3 buckets if running on AWSBatch
// related: https://github.com/nextflow-io/nextflow/issues/813
if( workflow.profile == 'awsbatch') {
if(!workflow.workDir.startsWith('s3:') || !params.outdir.startsWith('s3:')) exit 1, "Workdir or Outdir not on S3 - specify S3 Buckets for each to run on AWSBatch!"
}
// 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
}
/*
* short read preprocessing options
*/
params.adapter_forward = "AGATCGGAAGAGCACACGTCTGAACTCCAGTCA"
params.adapter_reverse = "AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGT"
params.mean_quality = 15
params.trimming_quality = 15
params.keep_phix = false
// params.phix_reference = "ftp://ftp.ncbi.nlm.nih.gov/genomes/genbank/viral/Enterobacteria_phage_phiX174_sensu_lato/all_assembly_versions/GCA_002596845.1_ASM259684v1/GCA_002596845.1_ASM259684v1_genomic.fna.gz"
params.phix_reference = "$baseDir/assets/data/GCA_002596845.1_ASM259684v1_genomic.fna.gz"
/*
* binning options
*/
params.skip_binning = false
params.skip_busco = false
params.min_contig_size = 1500
/*
* assembly options
*/
params.skip_spades = false
params.skip_spadeshybrid = false
params.skip_megahit = false
params.skip_quast = false
/*
* taxonomy options
*/
params.centrifuge_db = false
params.kraken2_db = false
params.skip_krona = false
params.cat_db = false
/*
* long read preprocessing options
*/
params.skip_adapter_trimming = false
params.keep_lambda = false
params.longreads_min_length = 1000
params.longreads_keep_percent = 90
params.longreads_length_weight = 10
// params.lambda_reference = "ftp://ftp.ncbi.nlm.nih.gov/genomes/genbank/viral/Escherichia_virus_Lambda/all_assembly_versions/GCA_000840245.1_ViralProj14204/GCA_000840245.1_ViralProj14204_genomic.fna.gz"
params.lambda_reference = "$baseDir/assets/data/GCA_000840245.1_ViralProj14204_genomic.fna.gz"
// Stage config files
ch_multiqc_config = Channel.fromPath(params.multiqc_config)
ch_output_docs = Channel.fromPath("$baseDir/docs/output.md")
/*
* Create a channel for input read files
*/
if(!params.skip_busco){
Channel
.fromPath( "${params.busco_reference}", checkIfExists: true )
.set { file_busco_db }
} else {
file_busco_db = Channel.from()
}
if(params.centrifuge_db){
Channel
.fromPath( "${params.centrifuge_db}", checkIfExists: true )
.set { file_centrifuge_db }
} else {
file_centrifuge_db = Channel.from()
}
if(params.kraken2_db){
Channel
.fromPath( "${params.kraken2_db}", checkIfExists: true )
.set { file_kraken2_db }
} else {
file_kraken2_db = Channel.from()
}
if(params.cat_db){
Channel
.fromPath( "${params.cat_db}", checkIfExists: true )
.set { file_cat_db }
} else {
file_cat_db = Channel.from()
}
if(!params.keep_phix) {
Channel
.fromPath( "${params.phix_reference}", checkIfExists: true )
.set { file_phix_db }
}
def returnFile(it) {
// Return file if it exists
inputFile = file(it)
if (!file(inputFile).exists()) exit 1, "Missing file in TSV file: ${inputFile}, see --help for more information"
return inputFile
}
if(params.manifest){
manifestFile = file(params.manifest)
// extracts read files from TSV and distribute into channels
Channel
.from(manifestFile)
.ifEmpty {exit 1, log.info "Cannot find path file ${tsvFile}"}
.splitCsv(sep:'\t')
.map { row ->
def id = row[0]
def lr = returnFile( row[1] )
def sr1 = returnFile( row[2] )
def sr2 = returnFile( row[3] )
[ id, lr, sr1, sr2 ]
}
.into { files_sr; files_all_raw }
// prepare input for fastqc
files_sr
.map { id, lr, sr1, sr2 -> [ id, [ sr1, sr2 ] ] }
.into { read_files_fastqc; read_files_fastp }
} else if(params.readPaths){
if(params.singleEnd){
Channel
.from(params.readPaths)
.map { row -> [ row[0], [file(row[1][0])]] }
.ifEmpty { exit 1, "params.readPaths was empty - no input files supplied" }
.into { read_files_fastqc; read_files_fastp }
files_all_raw = Channel.from()
} else {
Channel
.from(params.readPaths)
.map { row -> [ row[0], [file(row[1][0]), file(row[1][1])]] }
.ifEmpty { exit 1, "params.readPaths was empty - no input files supplied" }
.into { read_files_fastqc; read_files_fastp }
files_all_raw = Channel.from()
}
} else {
Channel
.fromFilePairs( params.reads, size: params.singleEnd ? 1 : 2 )
.ifEmpty { exit 1, "Cannot find any reads matching: ${params.reads}\nNB: Path needs to be enclosed in quotes!\nNB: Path requires at least one * wildcard!\nIf this is single-end data, please specify --singleEnd on the command line." }
.into { read_files_fastqc; read_files_fastp }
files_all_raw = Channel.from()
}
// Header log info
log.info nfcoreHeader()
def summary = [:]
if(workflow.revision) summary['Pipeline Release'] = workflow.revision
summary['Run Name'] = custom_runName ?: workflow.runName
summary['Reads'] = params.reads
summary['Fasta Ref'] = params.fasta
summary['Data Type'] = params.singleEnd ? 'Single-End' : 'Paired-End'
if(params.centrifuge_db) summary['Centrifuge Db'] = params.centrifuge_db
if(params.kraken2_db) summary['Kraken2 Db'] = params.kraken2_db
if(!params.skip_busco) summary['Busco Reference'] = params.busco_reference
summary['Max Resources'] = "$params.max_memory memory, $params.max_cpus cpus, $params.max_time time per job"
if(workflow.containerEngine) summary['Container'] = "$workflow.containerEngine - $workflow.container"
summary['Output dir'] = params.outdir
summary['Launch dir'] = workflow.launchDir
summary['Working dir'] = workflow.workDir
summary['Script dir'] = workflow.projectDir
summary['User'] = workflow.userName
if(workflow.profile == 'awsbatch'){
summary['AWS Region'] = params.awsregion
summary['AWS Queue'] = params.awsqueue
}
summary['Config Profile'] = workflow.profile
if(params.config_profile_description) summary['Config Description'] = params.config_profile_description
if(params.config_profile_contact) summary['Config Contact'] = params.config_profile_contact
if(params.config_profile_url) summary['Config URL'] = params.config_profile_url
if(params.email) {
summary['E-mail Address'] = params.email
summary['MultiQC maxsize'] = params.maxMultiqcEmailFileSize
}
log.info summary.collect { k,v -> "${k.padRight(18)}: $v" }.join("\n")
log.info "\033[2m----------------------------------------------------\033[0m"
// Check the hostnames against configured profiles
checkHostname()
def create_workflow_summary(summary) {
def yaml_file = workDir.resolve('workflow_summary_mqc.yaml')
yaml_file.text = """
id: 'nf-core-mag-summary'
description: " - this information is collected when the pipeline is started."
section_name: 'nf-core/mag Workflow Summary'
section_href: 'https://github.com/nf-core/mag'
plot_type: 'html'
data: |
<dl class=\"dl-horizontal\">
${summary.collect { k,v -> " <dt>$k</dt><dd><samp>${v ?: '<span style=\"color:#999999;\">N/A</a>'}</samp></dd>" }.join("\n")}
</dl>
""".stripIndent()
return yaml_file
}
/*
* Parse software version numbers
*/
process get_software_versions {
publishDir "${params.outdir}/pipeline_info", mode: 'copy',
saveAs: {filename ->
if (filename.indexOf(".csv") > 0) filename
else null
}
output:
file 'software_versions_mqc.yaml' into software_versions_yaml
file "software_versions.csv"
script:
"""
echo $workflow.manifest.version > v_pipeline.txt
echo $workflow.manifest.nextflowVersion > v_nextflow.txt
multiqc --version > v_multiqc.txt
fastqc --version > v_fastqc.txt
fastp -v 2> v_fastp.txt
megahit --version > v_megahit.txt
metabat2 -h 2> v_metabat.txt || true
NanoPlot --version > v_nanoplot.txt
filtlong --version > v_filtlong.txt
porechop --version > v_porechop.txt
NanoLyse --version > v_nanolyse.txt
spades.py --version > v_spades.txt
run_BUSCO.py --version > v_busco.txt
centrifuge --version > v_centrifuge.txt
kraken2 -v > v_kraken2.txt
CAT -v > v_cat.txt
quast -v > v_quast.txt
scrape_software_versions.py > software_versions_mqc.yaml
"""
}
/*
* Trim adapter sequences on long read nanopore files
*/
if (!params.skip_adapter_trimming) {
process porechop {
tag "$id"
input:
set id, file(lr), sr1, sr2 from files_all_raw
output:
set id, file("${id}_porechop.fastq"), sr1, sr2 into files_porechop
set id, file(lr), val("raw") into files_nanoplot_raw
script:
"""
porechop -i ${lr} -t "${task.cpus}" -o ${id}_porechop.fastq
"""
}
} else {
files_all_raw
.into{ files_porechop; pre_files_nanoplot_raw }
pre_files_nanoplot_raw
.map { id, lr, sr1, sr2 -> [ id, lr, "raw" ] }
.set { files_nanoplot_raw }
}
/*
* Remove reads mapping to the lambda genome.
* TODO: add lambda phage to igenomes.config?
*/
if (!params.keep_lambda) {
Channel
.fromPath( "${params.lambda_reference}", checkIfExists: true )
.set { file_nanolyse_db }
process nanolyse {
tag "$id"
publishDir "${params.outdir}", mode: 'copy',
saveAs: {filename -> filename.indexOf(".fastq.gz") == -1 ? "QC_longreads/NanoLyse/$filename" : null}
input:
set id, file(lr), file(sr1), file(sr2), file(nanolyse_db) from files_porechop.combine(file_nanolyse_db)
output:
set id, file("${id}_nanolyse.fastq.gz"), file(sr1), file(sr2) into files_nanolyse
file("${id}_nanolyse_log.txt")
script:
"""
cat ${lr} | NanoLyse --reference $nanolyse_db | gzip > ${id}_nanolyse.fastq.gz
echo "NanoLyse reference: $params.lambda_reference" >${id}_nanolyse_log.txt
cat ${lr} | echo "total reads before NanoLyse: \$((`wc -l`/4))" >>${id}_nanolyse_log.txt
zcat ${id}_nanolyse.fastq.gz | echo "total reads after NanoLyse: \$((`wc -l`/4))" >>${id}_nanolyse_log.txt
"""
}
} else {
files_porechop
.set{ files_nanolyse }
}
/*
* Quality filter long reads focus on length instead of quality to improve assembly size
*/
process filtlong {
tag "$id"
input:
set id, file(lr), file(sr1), file(sr2) from files_nanolyse
output:
set id, file("${id}_lr_filtlong.fastq.gz") into files_lr_filtered
set id, file("${id}_lr_filtlong.fastq.gz"), val('filtered') into files_nanoplot_filtered
script:
"""
filtlong \
-1 ${sr1} \
-2 ${sr2} \
--min_length ${params.longreads_min_length} \
--keep_percent ${params.longreads_keep_percent} \
--trim \
--length_weight ${params.longreads_length_weight} \
${lr} | gzip > ${id}_lr_filtlong.fastq.gz
"""
}
/*
* Quality check for nanopore reads and Quality/Length Plots
*/
process nanoplot {
tag "$id"
publishDir "${params.outdir}/QC_longreads/NanoPlot_${id}", mode: 'copy'
input:
set id, file(lr), type from files_nanoplot_raw.mix(files_nanoplot_filtered)
output:
file '*.png'
file '*.html'
file '*.txt'
script:
"""
NanoPlot -t "${task.cpus}" -p ${type}_ --title ${id}_${type} -c darkblue --fastq ${lr}
"""
}
/*
* STEP 1 - Read trimming and pre/post qc
*/
process fastqc_raw {
tag "$name"
publishDir "${params.outdir}/", mode: 'copy',
saveAs: {filename -> filename.indexOf(".zip") == -1 ? "QC_shortreads/fastqc/$filename" : null}
input:
set val(name), file(reads) from read_files_fastqc
output:
file "*_fastqc.{zip,html}" into fastqc_results
script:
"""
fastqc -t "${task.cpus}" -q $reads
"""
}
process fastp {
tag "$name"
publishDir "${params.outdir}/", mode: 'copy',
saveAs: {filename -> filename.indexOf(".fastq.gz") == -1 ? "QC_shortreads/fastp/$name/$filename" : null}
input:
set val(name), file(reads) from read_files_fastp
val adapter from params.adapter_forward
val adapter_reverse from params.adapter_reverse
val qual from params.mean_quality
val trim_qual from params.trimming_quality
output:
set val(name), file("${name}_trimmed*.fastq.gz") into trimmed_reads
file("fastp.*")
script:
def pe_input = params.singleEnd ? '' : "-I \"${reads[1]}\""
def pe_output1 = params.singleEnd ? "-o \"${name}_trimmed.fastq.gz\"" : "-o \"${name}_trimmed_R1.fastq.gz\""
def pe_output2 = params.singleEnd ? '' : "-O \"${name}_trimmed_R2.fastq.gz\""
"""
fastp -w "${task.cpus}" -q "${qual}" --cut_by_quality5 \
--cut_by_quality3 --cut_mean_quality "${trim_qual}"\
--adapter_sequence=${adapter} --adapter_sequence_r2=${adapter_reverse} \
-i "${reads[0]}" $pe_input $pe_output1 $pe_output2
"""
}
/*
* Remove PhiX contamination from Illumina reads
* TODO: PhiX into/from iGenomes.conf?
*/
if(!params.keep_phix) {
process phix_download_db {
tag "${genome}"
input:
file(genome) from file_phix_db
output:
set file(genome), file("ref*") into phix_db
script:
"""
bowtie2-build --threads "${task.cpus}" "${genome}" ref
"""
}
process remove_phix {
tag "$name"
publishDir "${params.outdir}", mode: 'copy',
saveAs: {filename -> filename.indexOf(".fastq.gz") == -1 ? "QC_shortreads/remove_phix/$filename" : null}
input:
set val(name), file(reads), file(genome), file(db) from trimmed_reads.combine(phix_db)
output:
set val(name), file("*.fastq.gz") into (trimmed_reads_megahit, trimmed_reads_metabat, trimmed_reads_fastqc, trimmed_sr_spadeshybrid, trimmed_reads_spades, trimmed_reads_centrifuge, trimmed_reads_kraken2, trimmed_reads_bowtie2)
file("${name}_remove_phix_log.txt")
script:
if ( !params.singleEnd ) {
"""
bowtie2 -p "${task.cpus}" -x ref -1 "${reads[0]}" -2 "${reads[1]}" --un-conc-gz ${name}_unmapped_%.fastq.gz
echo "Bowtie2 reference: ${genome}" >${name}_remove_phix_log.txt
zcat ${reads[0]} | echo "Read pairs before removal: \$((`wc -l`/4))" >>${name}_remove_phix_log.txt
zcat ${name}_unmapped_1.fastq.gz | echo "Read pairs after removal: \$((`wc -l`/4))" >>${name}_remove_phix_log.txt
"""
} else {
"""
bowtie2 -p "${task.cpus}" -x ref -U ${reads} --un-gz ${name}_unmapped.fastq.gz
echo "Bowtie2 reference: ${genome}" >${name}_remove_phix_log.txt
zcat ${reads[0]} | echo "Reads before removal: \$((`wc -l`/4))" >>${name}_remove_phix_log.txt
zcat ${name}_unmapped.fastq.gz | echo "Reads after removal: \$((`wc -l`/4))" >>${name}_remove_phix_log.txt
"""
}
}
} else {
trimmed_reads.into {trimmed_reads_megahit; trimmed_reads_metabat; trimmed_reads_fastqc; trimmed_sr_spadeshybrid; trimmed_reads_spades; trimmed_reads_centrifuge}
}
process fastqc_trimmed {
tag "$name"
publishDir "${params.outdir}/", mode: 'copy',
saveAs: {filename -> filename.indexOf(".zip") == -1 ? "QC_shortreads/fastqc/$filename" : null}
input:
set val(name), file(reads) from trimmed_reads_fastqc
output:
file "*_fastqc.{zip,html}" into fastqc_results_trimmed
script:
"""
fastqc -t "${task.cpus}" -q ${reads}
"""
}
/*
* STEP - Taxonomic information
*/
process centrifuge_db_preparation {
input:
file(db) from file_centrifuge_db
output:
set val("${db.toString().replace(".tar.gz", "")}"), file("*.cf") into centrifuge_database
script:
"""
tar -xf "${db}"
"""
}
trimmed_reads_centrifuge
.combine(centrifuge_database)
.set { centrifuge_input }
process centrifuge {
tag "${name}-${db_name}"
publishDir "${params.outdir}/Taxonomy/centrifuge/${name}", mode: 'copy',
saveAs: {filename -> filename.indexOf(".krona") == -1 ? filename : null}
input:
set val(name), file(reads), val(db_name), file(db) from centrifuge_input
output:
set val("centrifuge"), val(name), file("results.krona") into centrifuge_to_krona
file("report.txt")
file("kreport.txt")
script:
def input = params.singleEnd ? "-U \"${reads}\"" : "-1 \"${reads[0]}\" -2 \"${reads[1]}\""
"""
centrifuge -x "${db_name}" \
-p "${task.cpus}" \
--report-file report.txt \
-S results.txt \
$input
centrifuge-kreport -x "${db_name}" results.txt > kreport.txt
cat results.txt | cut -f 1,3 > results.krona
"""
}
process kraken2_db_preparation {
input:
file(db) from file_kraken2_db
output:
set val("${db.baseName}"), file("${db.baseName}/*.k2d") into kraken2_database
script:
"""
tar -xf "${db}"
"""
}
trimmed_reads_kraken2
.combine(kraken2_database)
.set { kraken2_input }
process kraken2 {
tag "${name}-${db_name}"
publishDir "${params.outdir}/Taxonomy/kraken2/${name}", mode: 'copy',
saveAs: {filename -> filename.indexOf(".krona") == -1 ? filename : null}
input:
set val(name), file(reads), val(db_name), file("database/*") from kraken2_input
output:
set val("kraken2"), val(name), file("results.krona") into kraken2_to_krona
file("kraken2_report.txt")
script:
def input = params.singleEnd ? "\"${reads}\"" : "--paired \"${reads[0]}\" \"${reads[1]}\""
"""
kraken2 \
--report-zero-counts \
--threads "${task.cpus}" \
--db database \
--fastq-input \
--report kraken2_report.txt \
$input \
> kraken2.kraken
cat kraken2.kraken | cut -f 2,3 > results.krona
"""
}
process krona_db {
output:
file("taxonomy/taxonomy.tab") into file_krona_db
when:
( params.centrifuge_db || params.kraken2_db ) && !params.skip_krona
script:
"""
ktUpdateTaxonomy.sh taxonomy
"""
}
centrifuge_to_krona
.mix(kraken2_to_krona)
.combine(file_krona_db)
.set { krona_input }
process krona {
tag "${classifier}-${name}"
publishDir "${params.outdir}/Taxonomy/${classifier}/${name}", mode: 'copy'
input:
set val(classifier), val(name), file(report), file("taxonomy/taxonomy.tab") from krona_input
output:
file("*.html")
script:
"""
ktImportTaxonomy "$report" -tax taxonomy
"""
}
/*
* STEP 2 - Assembly
*/
process megahit {
tag "$name"
publishDir "${params.outdir}/", mode: 'copy',
saveAs: {filename -> filename.indexOf(".fastq.gz") == -1 ? "Assembly/$filename" : null}
input:
set val(name), file(reads) from trimmed_reads_megahit
output:
set val("MEGAHIT"), val("$name"), file("MEGAHIT/${name}.contigs.fa") into assembly_megahit_to_quast
set val("MEGAHIT"), val("$name"), file("MEGAHIT/${name}.contigs.fa") into assembly_megahit_to_metabat
file("MEGAHIT/*.log")
when:
!params.skip_megahit
script:
def input = params.singleEnd ? "-r \"${reads}\"" : "-1 \"${reads[0]}\" -2 \"${reads[1]}\""
"""
megahit -t "${task.cpus}" $input -o MEGAHIT --out-prefix "${name}"
"""
}
/*
* metaSpades hybrid Assembly
*/
files_lr_filtered
.combine(trimmed_sr_spadeshybrid, by: 0)
.set { files_pre_spadeshybrid }
process spadeshybrid {
tag "$id"
publishDir "${params.outdir}/", mode: 'copy', pattern: "${id}*",
saveAs: {filename -> filename.indexOf(".fastq.gz") == -1 ? "Assembly/SPAdesHybrid/$filename" : null}
input:
set id, file(lr), file(sr) from files_pre_spadeshybrid
output:
set id, val("SPAdesHybrid"), file("${id}_graph.gfa") into assembly_graph_spadeshybrid
set val("SPAdesHybrid"), val("$id"), file("${id}_scaffolds.fasta") into assembly_spadeshybrid_to_quast
set val("SPAdesHybrid"), val("$id"), file("${id}_scaffolds.fasta") into assembly_spadeshybrid_to_metabat
file("${id}_contigs.fasta")
file("${id}_log.txt")
when:
params.manifest && !params.singleEnd && !params.skip_spadeshybrid
script:
def maxmem = "${task.memory.toString().replaceAll(/[\sGB]/,'')}"
"""
metaspades.py \
--threads "${task.cpus}" \
--memory "$maxmem" \
--pe1-1 ${sr[0]} \
--pe1-2 ${sr[1]} \
--nanopore ${lr} \
-o spades
mv spades/assembly_graph_with_scaffolds.gfa ${id}_graph.gfa
mv spades/scaffolds.fasta ${id}_scaffolds.fasta
mv spades/contigs.fasta ${id}_contigs.fasta
mv spades/spades.log ${id}_log.txt
"""
}
process spades {
tag "$id"
publishDir "${params.outdir}/", mode: 'copy', pattern: "${id}*",
saveAs: {filename -> filename.indexOf(".fastq.gz") == -1 ? "Assembly/SPAdes/$filename" : null}
input:
set id, file(sr) from trimmed_reads_spades
output:
set id, val("SPAdes"), file("${id}_graph.gfa") into assembly_graph_spades
set val("SPAdes"), val("$id"), file("${id}_scaffolds.fasta") into assembly_spades_to_quast
set val("SPAdes"), val("$id"), file("${id}_scaffolds.fasta") into assembly_spades_to_metabat
file("${id}_contigs.fasta")
file("${id}_log.txt")
when:
!params.singleEnd && !params.skip_spades
script:
def maxmem = "${task.memory.toString().replaceAll(/[\sGB]/,'')}"
"""
metaspades.py \
--threads "${task.cpus}" \
--memory "$maxmem" \
--pe1-1 ${sr[0]} \
--pe1-2 ${sr[1]} \
-o spades
mv spades/assembly_graph_with_scaffolds.gfa ${id}_graph.gfa
mv spades/scaffolds.fasta ${id}_scaffolds.fasta
mv spades/contigs.fasta ${id}_contigs.fasta
mv spades/spades.log ${id}_log.txt
"""
}
process quast {
tag "$assembler-$sample"
publishDir "${params.outdir}/Assembly/$assembler", mode: 'copy'
input:
set val(assembler), val(sample), file(assembly) from assembly_spades_to_quast.mix(assembly_megahit_to_quast).mix(assembly_spadeshybrid_to_quast)
output:
file("${sample}_QC/*") into quast_results
when:
!params.skip_quast
script:
"""
metaquast.py --threads "${task.cpus}" --rna-finding --max-ref-number 0 -l "${assembler}-${sample}" "${assembly}" -o "${sample}_QC"
"""
}
bowtie2_input = Channel.empty()
assembly_all_to_metabat = assembly_spades_to_metabat.mix(assembly_megahit_to_metabat,assembly_spadeshybrid_to_metabat)
(assembly_all_to_metabat, assembly_all_to_metabat_copy) = assembly_all_to_metabat.into(2)
bowtie2_input = assembly_all_to_metabat
.combine(trimmed_reads_bowtie2)
(bowtie2_input, bowtie2_input_copy) = bowtie2_input.into(2)
/*
* STEP 3 - Binning
*/
process bowtie2 {
tag "$assembler-$sample"
input:
set val(assembler), val(sample), file(assembly), val(sampleToMap), file(reads) from bowtie2_input
output:
set val(assembler), val(sample), file("${assembler}-${sample}-${sampleToMap}.bam"), file("${assembler}-${sample}-${sampleToMap}.bam.bai") into assembly_mapping_for_metabat
when:
!params.skip_binning
script:
def name = "${assembler}-${sample}-${sampleToMap}"
def input = params.singleEnd ? "-U \"${reads}\"" : "-1 \"${reads[0]}\" -2 \"${reads[1]}\""
"""
bowtie2-build --threads "${task.cpus}" "${assembly}" ref
bowtie2 -p "${task.cpus}" -x ref $input | \
samtools view -@ "${task.cpus}" -bS | \
samtools sort -@ "${task.cpus}" -o "${name}.bam"
samtools index "${name}.bam"
"""
}
assembly_mapping_for_metabat = assembly_mapping_for_metabat.groupTuple(by:[0,1]).join(assembly_all_to_metabat_copy)
assembly_mapping_for_metabat = assembly_mapping_for_metabat.dump(tag:'assembly_mapping_for_metabat')
process metabat {
tag "$assembler-$sample"
publishDir "${params.outdir}/", mode: 'copy',
saveAs: {filename -> (filename.indexOf(".bam") == -1 && filename.indexOf(".fastq.gz") == -1) ? "GenomeBinning/$filename" : null}
input:
set val(assembler), val(sample), file(bam), file(index), val(sampleCopy), file(assembly) from assembly_mapping_for_metabat
val(min_size) from params.min_contig_size
output:
set val(assembler), val(sample), file("MetaBAT2/*") into metabat_bins mode flatten
set val(assembler), val(sample), file("MetaBAT2/*") into metabat_bins_for_cat
set val(assembler), val(sample), file("MetaBAT2/*") into metabat_bins_quast_bins
when:
!params.skip_binning
script:
def name = "${assembler}-${sample}"
"""
jgi_summarize_bam_contig_depths --outputDepth depth.txt ${bam}
metabat2 -t "${task.cpus}" -i "${assembly}" -a depth.txt -o "MetaBAT2/${name}" -m ${min_size}
#if bin folder is empty
if [ -z \"\$(ls -A MetaBAT2)\" ]; then
cp ${assembly} MetaBAT2/${assembler}-${assembly}
fi
"""
}
process busco_download_db {
tag "${database.baseName}"
input:
file(database) from file_busco_db
output:
set val("${database.toString().replace(".tar.gz", "")}"), file("buscodb/*") into busco_db
script:
"""
mkdir buscodb
tar -xf ${database} -C buscodb
"""
}
metabat_bins
.combine(busco_db)
.set { metabat_db_busco }
/*
* BUSCO: Quantitative measures for the assessment of genome assembly
*/
process busco {
tag "${assembly}"
publishDir "${params.outdir}/GenomeBinning/QC/BUSCO/", mode: 'copy'
input:
set val(assembler), val(sample), file(assembly), val(db_name), file(db) from metabat_db_busco
output:
file("short_summary_${assembly}.txt") into (busco_summary_to_multiqc, busco_summary_to_plot)
val("$assembler-$sample") into busco_assembler_sample_to_plot
file("${assembly}_busco_log.txt")
file("${assembly}_buscos.faa")
file("${assembly}_buscos.fna")
script:
if( workflow.profile.toString().indexOf("conda") == -1) {
"""
cp -r /opt/conda/pkgs/augustus*/config augustus_config/
export AUGUSTUS_CONFIG_PATH=augustus_config
run_BUSCO.py \
--in ${assembly} \
--lineage_path $db_name \
--cpu "${task.cpus}" \
--blast_single_core \
--mode genome \
--out ${assembly} \
>${assembly}_busco_log.txt
cp run_${assembly}/short_summary_${assembly}.txt short_summary_${assembly}.txt
for f in run_${assembly}/single_copy_busco_sequences/*faa; do
[ -e "\$f" ] && cat run_${assembly}/single_copy_busco_sequences/*faa >${assembly}_buscos.faa || touch ${assembly}_buscos.faa
break
done
for f in run_${assembly}/single_copy_busco_sequences/*fna; do
[ -e "\$f" ] && cat run_${assembly}/single_copy_busco_sequences/*fna >${assembly}_buscos.fna || touch ${assembly}_buscos.fna
break
done
"""
} else {
"""
run_BUSCO.py \
--in ${assembly} \
--lineage_path $db_name \
--cpu "${task.cpus}" \
--blast_single_core \
--mode genome \
--out ${assembly} \
>${assembly}_busco_log.txt
cp run_${assembly}/short_summary_${assembly}.txt short_summary_${assembly}.txt
for f in run_${assembly}/single_copy_busco_sequences/*faa; do
[ -e "\$f" ] && cat run_${assembly}/single_copy_busco_sequences/*faa >${assembly}_buscos.faa || touch ${assembly}_buscos.faa
break
done
for f in run_${assembly}/single_copy_busco_sequences/*fna; do
[ -e "\$f" ] && cat run_${assembly}/single_copy_busco_sequences/*fna >${assembly}_buscos.fna || touch ${assembly}_buscos.fna
break
done