forked from nf-core/ampliseq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.nf
2232 lines (1869 loc) · 79.8 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/ampliseq
========================================================================================
nf-core/ampliseq Analysis Pipeline.
#### Homepage / Documentation
https://github.com/nf-core/ampliseq
----------------------------------------------------------------------------------------
*/
def helpMessage() {
log.info nfcoreHeader()
log.info"""
Usage:
The minimal command for running the pipeline is as follows:
nextflow run nf-core/ampliseq -profile singularity --input "data" --FW_primer GTGYCAGCMGCCGCGGTAA --RV_primer GGACTACNVGGGTWTCTAAT
In case of a timezone error, please specify "--qiime_timezone", e.g. --qiime_timezone 'Europe/Berlin'!
Main arguments:
-profile [strings] Use this parameter to choose a configuration profile. If not specified, runs locally and expects all software
to be installed and available on the `PATH`. Otherwise specify a container engine, "docker" or "singularity"
and a specialized profile such as "binac".
--input [path/to/folder] Folder containing paired-end demultiplexed fastq files
Note: All samples have to be sequenced in one run, otherwise also specifiy "--multipleSequencingRuns"
--FW_primer [str] Forward primer sequence
--RV_primer [str] Reverse primer sequence
--metadata [path/to/file] Path to metadata sheet, when missing most downstream analysis are skipped (barplots, PCoA plots, ...).
File extension is not relevant. Must have a comma separated list of metadata column headers.
--manifest [path/to/file] Path to manifest.tsv table with the following labels in this exact order: sampleID, forwardReads, reverseReads. In case of single end reads, the labels should be: sampleID, Reads.
Tab ('\t') must be the table separator. Multiple sequencing runs not supported by manifest at this stage.
Default is FALSE.
--qiime_timezone [str] Needs to be specified to resolve a timezone error (default: 'Europe/Berlin')
Other input options:
--extension [str] Naming of sequencing files (default: "/*_R{1,2}_001.fastq.gz").
The prepended "/" is required, also one "*" is required for sample names and "{1,2}" indicates read orientation
--multipleSequencingRuns If samples were sequenced in multiple sequencing runs. Expects one subfolder per sequencing run
in the folder specified by "--input" containing sequencing data of the specific run. These folders
may not contain underscores.
--split [str] A string that will be used between the prepended run/folder name and the sample name. (default: "-")
May not be present in run/folder names and no underscore(s) allowed. Only used with "--multipleSequencingRuns"
--pacbio If PacBio data. Use this option together with --manifest.
--phred64 If the sequencing data has PHRED 64 encoded quality scores (default: PHRED 33)
Filters:
--exclude_taxa [str] Comma separated list of unwanted taxa (default: "mitochondria,chloroplast")
To skip taxa filtering use "none"
--min_frequency [int] Remove entries from the feature table below an absolute abundance threshold (default: 1)
--min_samples [int] Filtering low prevalent features from the feature table (default: 1)
Cutoffs:
--double_primer Cutdapt will be run twice, first to remove reads without primers (default), then a second time to remove reads that erroneously contain a second set of primers, not to be used with "--retain_untrimmed"
--retain_untrimmed Cutadapt will retain untrimmed reads
--maxEE [number] DADA2 read filtering option. After truncation, reads with higher than ‘maxEE’ "expected errors" will be discarded. We recommend (to start with) a value corresponding to approximately 1 expected error per 100-200 bp (default: 2)
--maxLen [int] DADA2 read filtering option [PacBio only], remove reads with length greater than maxLen after trimming and truncation (default: 2999)
--minLen [int] DADA2 read filtering option [PacBio only], remove reads with length less than minLen after trimming and truncation (default: 50)
--trunclenf [int] DADA2 read truncation value for forward strand and single end reads, set this to 0 for no truncation
--trunclenr [int] DADA2 read truncation value for reverse strand, set this to 0 for no truncation
--trunc_qmin [int] If --trunclenf and --trunclenr are not set, these values will be automatically determined using this mean quality score (not preferred) (default: 25)
--trunc_rmin [float] Assures that values chosen with --trunc_qmin will retain a fraction of reads (default: 0.75)
References: If you have trained a compatible classifier before, or want to use a custom database
--classifier [path/to/file] Path to QIIME2 classifier file (typically *-classifier.qza)
--classifier_removeHash Remove all hash signs from taxonomy strings, resolves a rare ValueError during classification (process classifier)
--reference_database Path to file with reference database with taxonomies, currently either a qiime compatible file Silva_132_release.zip, or a UNITE fasta file (default: "https://www.arb-silva.de/fileadmin/silva_databases/qiime/Silva_132_release.zip")
--taxon_reference Specify which database to use for taxonomic assignment. Either 'silva' or 'unite' (default: 'silva')
Statistics:
--metadata_category [str] Comma separated list of metadata column headers for statistics (default: false)
If not specified, all suitable columns in the metadata sheet will be used.
Suitable are columns which are categorical (not numerical) and have multiple
different values that are not all unique.
Other options:
--untilQ2import Skip all steps after importing into QIIME2, used for visually choosing DADA2 parameter
--Q2imported [path/to/file] Path to imported reads (e.g. "demux.qza"), used after visually choosing DADA2 parameter
--onlyDenoising Skip all steps after denoising, produce only sequences and abundance tables on ASV level
--keepIntermediates Keep additional intermediate files, such as trimmed reads or various QIIME2 archives
--outdir [file] The output directory where the results will be saved
--publish_dir_mode [str] Mode for publishing results in the output directory. Available: symlink, rellink, link, copy, copyNoFollow, move (Default: copy)
--email [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
--email_on_fail [email] Same as --email, except only send mail if the workflow is not successful
--max_multiqc_email_size [str] Threshold 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 [str] Name for the pipeline run. If not specified, Nextflow will automatically generate a random mnemonic
Skipping steps:
--skip_fastqc Skip FastQC
--skip_alpha_rarefaction Skip alpha rarefaction
--skip_taxonomy Skip taxonomic classification
--skip_barplot Skip producing barplot
--skip_abundance_tables Skip producing any relative abundance tables
--skip_diversity_indices Skip alpha and beta diversity analysis
--skip_ancom Skip differential abundance testing
AWSBatch options:
--awsqueue [str] The AWSBatch JobQueue that needs to be set when running on AWSBatch
--awsregion [str] The AWS Region for your AWS Batch job to run on
--awscli [str] Path to the AWS CLI tool
""".stripIndent()
}
/*
* SET UP CONFIGURATION VARIABLES
*/
// Show help message
if (params.help){
helpMessage()
exit 0
}
// Configurable variables
params.name = false
params.email = false
params.plaintext_email = false
ch_output_docs = Channel.fromPath("$projectDir/docs/output.md")
Channel.fromPath("$projectDir/assets/matplotlibrc")
.into { ch_mpl_for_classifier_extract_seq; ch_mpl_for_classifier_train; ch_mpl_for_qiime_import; ch_mpl_for_ancom_asv; ch_mpl_for_ancom_tax; ch_mpl_for_ancom; ch_mpl_for_beta_diversity_ord; ch_mpl_for_beta_diversity; ch_mpl_for_alpha_diversity; ch_mpl_for_metadata_pair; ch_mpl_for_metadata_cat; ch_mpl_for_diversity_core; ch_mpl_for_alpha_rare; ch_mpl_for_tree; ch_mpl_for_barcode; ch_mpl_for_relreducetaxa; ch_mpl_for_relasv; ch_mpl_for_export_dada_output; ch_mpl_filter_taxa; ch_mpl_classifier; ch_mpl_dada; ch_mpl_dada_merge; ch_mpl_for_demux_visualize; ch_mpl_for_classifier }
/*
* Define pipeline steps
*/
params.untilQ2import = false
params.Q2imported = false
if (params.Q2imported) {
params.skip_fastqc = true
params.skip_multiqc = true
} else {
params.skip_multiqc = false
}
params.onlyDenoising = false
if (params.onlyDenoising || params.untilQ2import) {
params.skip_abundance_tables = true
params.skip_barplot = true
params.skip_taxonomy = true
params.skip_alpha_rarefaction = true
params.skip_diversity_indices = true
params.skip_ancom = true
} else {
params.skip_abundance_tables = false
params.skip_barplot = false
params.skip_taxonomy = false
params.skip_alpha_rarefaction = false
params.skip_diversity_indices = false
params.skip_ancom = false
}
params.manifest = false
/*
* Import input files
*/
if (params.metadata) {
Channel.fromPath("${params.metadata}", checkIfExists: true)
.into { ch_metadata_for_barplot; ch_metadata_for_alphararefaction; ch_metadata_for_diversity_core; ch_metadata_for_alpha_diversity; ch_metadata_for_metadata_category_all; ch_metadata_for_metadata_category_pairwise; ch_metadata_for_beta_diversity; ch_metadata_for_beta_diversity_ordination; ch_metadata_for_ancom; ch_metadata_for_ancom_tax; ch_metadata_for_ancom_asv }
} else {
Channel.from()
.into { ch_metadata_for_barplot; ch_metadata_for_alphararefaction; ch_metadata_for_diversity_core; ch_metadata_for_alpha_diversity; ch_metadata_for_metadata_category_all; ch_metadata_for_metadata_category_pairwise; ch_metadata_for_beta_diversity; ch_metadata_for_beta_diversity_ordination; ch_metadata_for_ancom; ch_metadata_for_ancom_tax; ch_metadata_for_ancom_asv }
}
if (params.Q2imported) {
Channel.fromPath("${params.Q2imported}", checkIfExists: true)
.into { ch_qiime_demux_import; ch_qiime_demux_vis; ch_qiime_demux_dada }
}
if (params.classifier) {
Channel.fromPath("${params.classifier}", checkIfExists: true)
.set { ch_qiime_classifier }
}
/*
* Sanity check input values
*/
if (!params.Q2imported) {
if (!params.FW_primer) { exit 1, "Option --FW_primer missing" }
if (!params.RV_primer) { exit 1, "Option --RV_primer missing" }
if (!params.input) { exit 1, "Option --input missing" }
}
if (params.Q2imported && params.untilQ2import) {
exit 1, "Choose either to import data into a QIIME2 artefact and quit with --untilQ2import or use an already existing QIIME2 data artefact with --Q2imported."
}
if ("${params.split}".indexOf("_") > -1 ) {
exit 1, "Underscore is not allowed in --split, please review your input."
}
if (params.multipleSequencingRuns && params.manifest) {
exit 1, "The manifest file does not support multiple sequencing runs at this point."
}
single_end = false
if (params.pacbio) {
single_end = true
}
if (single_end && !params.manifest) {
exit 1, "A manifest file is needed for single end reads such as PacBio data."
}
if (params.double_primer && params.retain_untrimmed) {
exit 1, "Incompatible parameters --double_primer and --retain_untrimmed cannot be set at the same time."
}
if (!params.classifier){
if (!(params.taxon_reference == 'silva' || params.taxon_reference == 'unite')) exit 1, "--taxon_reference need to be set to either 'silva' or 'unite'"
}
// 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!"
}
// 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
}
// Check AWS batch settings
if (workflow.profile.contains('awsbatch')) {
// AWSBatch sanity checking
if (!params.awsqueue || !params.awsregion) exit 1, "Specify correct --awsqueue and --awsregion parameters on AWSBatch!"
// Check outdir paths to be S3 buckets if running on AWSBatch
// related: https://github.com/nextflow-io/nextflow/issues/813
if (!params.outdir.startsWith('s3:')) exit 1, "Outdir not on S3 - specify S3 Bucket to run on AWSBatch!"
// Prevent trace files to be stored on S3 since S3 does not support rolling files.
if (params.tracedir.startsWith('s3:')) exit 1, "Specify a local tracedir or run without trace! S3 cannot be used for tracefiles."
}
// Stage config files
ch_multiqc_config = file("$projectDir/assets/multiqc_config.yaml", checkIfExists: true)
ch_multiqc_custom_config = params.multiqc_config ? Channel.fromPath(params.multiqc_config, checkIfExists: true) : Channel.empty()
ch_output_docs = file("$projectDir/docs/output.md", checkIfExists: true)
ch_output_docs_images = file("$projectDir/docs/images/", checkIfExists: true)
// Header log info
log.info nfcoreHeader()
def summary = [:]
summary['Pipeline Name'] = 'nf-core/ampliseq'
if(workflow.revision) summary['Pipeline Release'] = workflow.revision
summary['Run Name'] = custom_runName ?: workflow.runName
summary['Input'] = params.manifest ?: params.input
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.contains('awsbatch')) {
summary['AWS Region'] = params.awsregion
summary['AWS Queue'] = params.awsqueue
summary['AWS CLI'] = params.awscli
}
summary['Config Profile'] = workflow.profile
if (params.config_profile_description) summary['Config Profile Description'] = params.config_profile_description
if (params.config_profile_contact) summary['Config Profile Contact'] = params.config_profile_contact
if (params.config_profile_url) summary['Config Profile URL'] = params.config_profile_url
summary['Config Files'] = workflow.configFiles.join(', ')
if (params.email || params.email_on_fail) {
summary['E-mail Address'] = params.email
summary['E-mail on failure'] = params.email_on_fail
summary['MultiQC maxsize'] = params.max_multiqc_email_size
}
log.info summary.collect { k,v -> "${k.padRight(18)}: $v" }.join("\n")
log.info "-\033[2m--------------------------------------------------\033[0m-"
if( params.trunclenf == false || params.trunclenr == false ){
if ( !params.untilQ2import ) log.info "\n######## WARNING: No DADA2 cutoffs were specified, therefore reads will be truncated where median quality drops below ${params.trunc_qmin} but at least a fraction of ${params.trunc_rmin} of the reads will be retained.\nThe chosen cutoffs do not account for required overlap for merging, therefore DADA2 might have poor merging efficiency or even fail.\n"
}
// Check the hostnames against configured profiles
checkHostname()
Channel.from(summary.collect{ [it.key, it.value] })
.map { k,v -> "<dt>$k</dt><dd><samp>${v ?: '<span style=\"color:#999999;\">N/A</a>'}</samp></dd>" }
.reduce { a, b -> return [a, b].join("\n ") }
.map { x -> """
id: 'nf-core-ampliseq-summary'
description: " - this information is collected when the pipeline is started."
section_name: 'nf-core/ampliseq Workflow Summary'
section_href: 'https://github.com/nf-core/ampliseq'
plot_type: 'html'
data: |
<dl class=\"dl-horizontal\">
$x
</dl>
""".stripIndent() }
.set { ch_workflow_summary }
/*
* Parse software version numbers
*/
process get_software_versions {
publishDir "${params.outdir}/pipeline_info", mode: params.publish_dir_mode,
saveAs: { filename ->
if (filename.indexOf(".csv") > 0) filename
else null
}
output:
file 'software_versions_mqc.yaml' into ch_software_versions_yaml
file "software_versions.csv"
script:
"""
echo $workflow.manifest.version > v_pipeline.txt
echo $workflow.nextflow.version > v_nextflow.txt
fastqc --version > v_fastqc.txt
multiqc --version > v_multiqc.txt
cutadapt --version > v_cutadapt.txt
qiime --version > v_qiime.txt
scrape_software_versions.py &> software_versions_mqc.yaml
"""
}
if (!params.Q2imported){
/*
* Create a channel for optional input manifest file
*/
if (params.manifest && !single_end) {
tsvFile = file(params.manifest).getName()
// extracts read files from TSV and distribute into channels
Channel
.fromPath(params.manifest)
.ifEmpty {exit 1, log.info "Cannot find path file ${tsvFile}"}
.splitCsv(header:true, sep:'\t')
.map { row -> [ row.sampleID, [ file(row.forwardReads, checkIfExists: true), file(row.reverseReads, checkIfExists: true) ] ] }
.into { ch_read_pairs; ch_read_pairs_fastqc; ch_read_pairs_name_check }
} else if ( single_end ) {
// Manifest file is currently the only available input option for single_end
tsvFile = file(params.manifest).getName()
// extracts read files from TSV and distribute into channels
Channel
.fromPath(params.manifest)
.ifEmpty {exit 1, log.info "Cannot find path file ${tsvFile}"}
.splitCsv(header:true, sep:'\t')
.map { row -> [ row.sampleID, file(row.Reads, checkIfExists: true) ] }
.into { ch_read_pairs; ch_read_pairs_fastqc; ch_read_pairs_name_check }
/*
* Create a channel for input read files
*/
} else if (params.readPaths && params.input == "data${params.extension}" && !params.multipleSequencingRuns){
//Test input for single sequencing runs, profile = test
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" }
.map { name, reads -> [ name.toString().indexOf("_") != -1 ? name.toString().take(name.toString().indexOf("_")) : name, reads ] }
.into { ch_read_pairs; ch_read_pairs_fastqc; ch_read_pairs_name_check }
} else if ( !params.readPaths && params.multipleSequencingRuns ) {
//Standard input for multiple sequencing runs
//Get files
Channel
.fromFilePairs( params.input + "/*" + params.extension, size: 2 )
.ifEmpty { exit 1, "Cannot find any reads matching: ${params.input}/*${params.extension}\nNB: Path needs to be enclosed in quotes!" }
.into { ch_extract_folders; ch_rename_key }
//Get folder information
ch_extract_folders
.flatMap { key, files -> [files[0]] }
.map { it.take(it.findLastIndexOf{"/"})[-1] }
.unique()
.into { ch_count_folders; ch_check_folders; ch_report_folders }
//Report folders with sequencing files
ch_report_folders
.collect()
.subscribe {
String folders = it.toString().replace("[", "").replace("]","")
log.info "\nFound the folder(s) \"$folders\" containing sequencing read files matching \"${params.extension}\" in \"${params.input}\".\n" }
//Stop if folder count is 1
ch_count_folders
.count()
.subscribe { if ( it == 1 ) exit 1, "Found only one folder with read data but \"--multipleSequencingRuns\" was specified. Please review data input." }
//Stop if folder names contain "_" or "${params.split}"
ch_check_folders
.subscribe {
if ( it.toString().indexOf("${params.split}") > -1 ) exit 1, "Folder name \"$it\" contains \"${params.split}\", but may not. Please review data input or choose another string using \"--split [str]\" (no underscore allowed!)."
if ( it.toString().indexOf("_") > -1 ) exit 1, "Folder name \"$it\" contains \"_\", but may not. Please review data input."
}
//Add folder information to sequence files
ch_rename_key
.map { key, files -> [ key, files, (files[0].take(files[0].findLastIndexOf{"/"})[-1]) ] }
.into { ch_read_pairs; ch_read_pairs_fastqc }
} else if ( params.readPaths && params.multipleSequencingRuns ) {
//Test input for multiple sequencing runs, profile = test_multi
Channel
.from(params.readPaths)
.map { row -> [ row[0], [file(row[1][0]), file(row[1][1])], row[2] ] }
.ifEmpty { exit 1, "params.readPaths was empty - no input files supplied" }
.into { ch_read_pairs; ch_read_pairs_fastqc }
} else {
//Standard input
Channel
.fromFilePairs( params.input + params.extension, size: 2 )
.ifEmpty { exit 1, "Cannot find any reads matching: ${params.input}${params.extension}\nNB: Path needs to be enclosed in quotes!" }
.map { name, reads -> [ name.toString().indexOf("_") != -1 ? name.toString().take(name.toString().indexOf("_")) : name, reads ] }
.into { ch_read_pairs; ch_read_pairs_fastqc }
}
/*
* fastQC
*/
if (!params.multipleSequencingRuns){
process fastqc {
tag "${pair_id}"
publishDir "${params.outdir}/fastQC", mode: params.publish_dir_mode,
saveAs: {filename -> filename.indexOf(".zip") > 0 ? "zips/$filename" : "$filename"}
input:
set val(pair_id), file(reads) from ch_read_pairs_fastqc
output:
file "*_fastqc.{zip,html}" into ch_fastqc_results
when:
!params.skip_fastqc
script:
"""
fastqc -q ${reads}
"""
}
} else {
process fastqc_multi {
tag "${folder}${params.split}${pair_id}"
publishDir "${params.outdir}/fastQC", mode: params.publish_dir_mode,
saveAs: {filename -> filename.indexOf(".zip") > 0 ? "zips/$filename" : "$filename"}
input:
set val(pair_id), file(reads), val(folder) from ch_read_pairs_fastqc
output:
file "*_fastqc.{zip,html}" into ch_fastqc_results
when:
!params.skip_fastqc
script:
"""
#Rename files so that there is no possible overlap
ln -s "${reads[0]}" "$folder${params.split}${reads[0]}"
ln -s "${reads[1]}" "$folder${params.split}${reads[1]}"
fastqc -q "$folder${params.split}${reads[0]}" "$folder${params.split}${reads[1]}"
"""
}
}
/*
* Trim each read or read-pair with cutadapt
*/
if (!params.multipleSequencingRuns){
process trimming {
tag "${pair_id}"
publishDir "${params.outdir}/trimmed", mode: params.publish_dir_mode,
saveAs: {filename ->
if (filename.indexOf(".gz") == -1) "logs/$filename"
else if(params.keepIntermediates) filename
else null}
input:
set val(pair_id), file(reads) from ch_read_pairs
output:
set val(pair_id), file ("trimmed/*.*") into ch_fastq_trimmed_manifest
file "trimmed/*.*" into (ch_fastq_trimmed, ch_fastq_trimmed_qiime)
file "cutadapt_log_*.txt" into ch_fastq_cutadapt_log
script:
discard_untrimmed = params.retain_untrimmed ? '' : '--discard-untrimmed'
primers = single_end ? "--rc -g ${params.FW_primer}...${params.RV_primer}" : "-g ${params.FW_primer} -G ${params.RV_primer}"
in_2_files = single_end ? "second-trimming_${reads}" : "second-trimming_${reads[0]} second-trimming_${reads[1]}"
out_1_files = single_end ? "-o second-trimming_${reads}" : "-o second-trimming_${reads[0]} -p second-trimming_${reads[1]}"
in_1_files = single_end ? "first-trimming_${reads}" : "first-trimming_${reads[0]} first-trimming_${reads[1]}" //these have to be symlinked below
out_files = single_end ? "-o trimmed/${reads}" : "-o trimmed/${reads[0]} -p trimmed/${reads[1]}"
in_files = single_end ? "${reads}" : "${reads[0]} ${reads[1]}"
"""
mkdir -p trimmed
if [[ \"${params.double_primer}\" = \"true\" && \"${params.retain_untrimmed}\" = \"false\" ]]; then
#rename files to list results correctly in MultiQC
if [ \"${single_end}\" = \"true\" ]; then
ln -s "${reads}" "first-trimming_${reads}"
else
ln -s "${reads[0]}" "first-trimming_${reads[0]}"
ln -s "${reads[1]}" "first-trimming_${reads[1]}"
fi
cutadapt ${primers} ${discard_untrimmed} \
${out_1_files} \
${in_1_files} >> cutadapt_log_${pair_id}.txt
cutadapt ${primers} --discard-trimmed \
${out_files} \
${in_2_files} >> cutadapt_log_${pair_id}.txt
else
cutadapt ${primers} ${discard_untrimmed} \
${out_files} ${in_files} \
>> cutadapt_log_${pair_id}.txt
fi
"""
}
} else {
process trimming_multi {
tag "$folder${params.split}$pair_id"
publishDir "${params.outdir}/trimmed", mode: params.publish_dir_mode,
saveAs: {filename ->
if (filename.indexOf(".gz") == -1) "logs/$filename"
else if(params.keepIntermediates) filename
else null}
input:
set val(pair_id), file(reads), val(folder) from ch_read_pairs
output:
file "trimmed/*.*" into (ch_fastq_trimmed, ch_fastq_trimmed_manifest, ch_fastq_trimmed_qiime)
file "cutadapt_log_$folder${params.split}${pair_id}.txt" into ch_fastq_cutadapt_log
script:
discard_untrimmed = params.retain_untrimmed ? '' : '--discard-untrimmed'
"""
mkdir -p trimmed
if [[ \"${params.double_primer}\" = \"true\" && \"${params.retain_untrimmed}\" = \"false\" ]]; then
mkdir -p firstcutadapt
#Rename files so that MultiQC will pick them up correctely as first trimming
ln -s "${reads[0]}" "first-trimming_$folder${params.split}${reads[0]}"
ln -s "${reads[1]}" "first-trimming_$folder${params.split}${reads[1]}"
cutadapt -g ${params.FW_primer} -G ${params.RV_primer} ${discard_untrimmed} \
-o firstcutadapt/$folder${params.split}${reads[0]} -p firstcutadapt/$folder${params.split}${reads[1]} \
"first-trimming_$folder${params.split}${reads[0]}" "first-trimming_$folder${params.split}${reads[1]}" >> cutadapt_log_$folder${params.split}${pair_id}.txt
#Rename files so that MultiQC will pick them up correctely as second trimming
ln -s "firstcutadapt/$folder${params.split}${reads[0]}" "second-trimming_$folder${params.split}${reads[0]}"
ln -s "firstcutadapt/$folder${params.split}${reads[1]}" "second-trimming_$folder${params.split}${reads[1]}"
cutadapt -g ${params.FW_primer} -G ${params.RV_primer} --discard-trimmed \
-o trimmed/$folder${params.split}${reads[0]} -p trimmed/$folder${params.split}${reads[1]} \
second-trimming_$folder${params.split}${reads[0]} second-trimming_$folder${params.split}${reads[1]} >> cutadapt_log_$folder${params.split}${pair_id}.txt
else
#first, rename files so that MultiQC will pick them up correctely
ln -s "${reads[0]}" "$folder${params.split}${reads[0]}"
ln -s "${reads[1]}" "$folder${params.split}${reads[1]}"
cutadapt -g ${params.FW_primer} -G ${params.RV_primer} ${discard_untrimmed} \
-o trimmed/$folder${params.split}${reads[0]} -p trimmed/$folder${params.split}${reads[1]} \
$folder${params.split}${reads[0]} $folder${params.split}${reads[1]} > cutadapt_log_$folder${params.split}${pair_id}.txt
fi
"""
}
}
/*
* multiQC
*/
process multiqc {
publishDir "${params.outdir}/MultiQC", mode: params.publish_dir_mode
input:
file (multiqc_config) from ch_multiqc_config
file (mqc_custom_config) from ch_multiqc_custom_config.collect().ifEmpty([])
file ('cutadapt/logs/*') from ch_fastq_cutadapt_log.collect().ifEmpty([])
file ('fastqc/*') from ch_fastqc_results.collect().ifEmpty([])
file ('software_versions/*') from ch_software_versions_yaml.collect().ifEmpty([])
file workflow_summary from ch_workflow_summary.collectFile(name: "workflow_summary_mqc.yaml")
output:
file "*multiqc_report.html" into ch_multiqc_report
file "*_data"
when:
!params.skip_multiqc
script:
rtitle = custom_runName ? "--title \"$custom_runName\"" : ''
rfilename = custom_runName ? "--filename " + custom_runName.replaceAll('\\W','_').replaceAll('_+','_') + "_multiqc_report" : ''
custom_config_file = params.multiqc_config ? "--config $mqc_custom_config" : ''
"""
multiqc --interactive -f $rtitle $rfilename $custom_config_file .
"""
}
/*
* Produce manifest file for QIIME2
*/
if (!params.multipleSequencingRuns && single_end){
ch_fastq_trimmed_manifest
.map { name, reads ->
def sampleID = name
def Reads = reads
[ "${sampleID}" +","+ "${Reads}" + ",forward" ]
}
.flatten()
.collectFile(name: 'manifest.txt', newLine: true, storeDir: "${params.outdir}/demux", seed: "sample-id,absolute-filepath,direction")
.set { ch_manifest }
} else if (!params.multipleSequencingRuns){
ch_fastq_trimmed_manifest
.map { name, reads ->
def sampleID = name
def fwdReads = reads [0]
def revReads = reads [1]
[ "${sampleID}" +","+ "${fwdReads}" + ",forward\n" + "${sampleID}" +","+ "${revReads}" +",reverse" ]
}
.flatten()
.collectFile(name: 'manifest.txt', newLine: true, storeDir: "${params.outdir}/demux", seed: "sample-id,absolute-filepath,direction")
.set { ch_manifest }
} else {
ch_fastq_trimmed_manifest
.map { forward, reverse -> [ forward.drop(forward.findLastIndexOf{"/"})[0], forward, reverse ] } //extract file name
.map { name, forward, reverse -> [ name.toString().indexOf("_") != -1 ? name.toString().take(name.toString().indexOf("_")) : name, forward, reverse ] } //extract sample name
.map { name, forward, reverse -> [ name +","+ forward + ",forward\n" + name +","+ reverse +",reverse" ] } //prepare basic synthax
.flatten()
.collectFile(storeDir: "${params.outdir}", seed: "sample-id,absolute-filepath,direction\n") { item ->
def folder = item.take(item.indexOf("${params.split}")) //re-extract folder
[ "${folder}${params.split}manifest.txt", item + '\n' ]
}
.set { ch_manifest_file }
ch_manifest_file
.combine( ch_mpl_for_qiime_import )
.set { ch_manifest }
}
/*
* Import trimmed files into QIIME2 artefact
*/
if (!params.multipleSequencingRuns && !params.pacbio) {
process qiime_import {
publishDir "${params.outdir}/demux", mode: params.publish_dir_mode,
saveAs: { filename ->
params.keepIntermediates ? filename : null
params.untilQ2import ? filename : null }
input:
file(manifest) from ch_manifest
env MATPLOTLIBRC from ch_mpl_for_qiime_import
file('*') from ch_fastq_trimmed_qiime.collect()
output:
file "demux.qza" into (ch_qiime_demux_import, ch_qiime_demux_vis, ch_qiime_demux_dada)
when:
!params.Q2imported
script:
input_format = params.phred64 ? "PairedEndFastqManifestPhred64" : "PairedEndFastqManifestPhred33"
"""
head -n 1 ${manifest} > header.txt
tail -n+2 ${manifest} | cut -d, -f1 > col1.txt
tail -n+2 ${manifest} | cut -d, -f2 | sed 's:.*/::' > col2.txt
while read f; do
realpath \$f >> full_path.txt
done <col2.txt
tail -n+2 ${manifest} | cut -d, -f3 > col3.txt
paste -d, col1.txt full_path.txt col3.txt > cols.txt
cat cols.txt >> header.txt && mv header.txt ${manifest}
qiime tools import \
--type 'SampleData[PairedEndSequencesWithQuality]' \
--input-path ${manifest} \
--output-path demux.qza \
--input-format $input_format
"""
}
} else if (params.pacbio) {
process qiime_import_pacbio{
publishDir "${params.outdir}/demux", mode: 'copy',
saveAs: { filename ->
params.keepIntermediates ? filename : null
params.untilQ2import ? filename : null }
input:
file(manifest) from ch_manifest
env MATPLOTLIBRC from ch_mpl_for_qiime_import
output:
file manifest into ch_dada_import
file "demux.qza" into (ch_qiime_demux_import, ch_qiime_demux_vis)
when:
!params.Q2imported
script:
input_format = params.phred64 ? "SingleEndFastqManifestPhred64" : "SingleEndFastqManifestPhred33"
"""
qiime tools import \
--type 'SampleData[SequencesWithQuality]' \
--input-path ${manifest} \
--output-path demux.qza \
--input-format $input_format
"""
}
} else {
process qiime_import_multi {
tag "${manifest}"
publishDir "${params.outdir}", mode: params.publish_dir_mode,
saveAs: { filename ->
params.keepIntermediates ? filename : null}
input:
set file(manifest), env(MATPLOTLIBRC) from ch_manifest
file('*') from ch_fastq_trimmed_qiime.collect()
output:
file "*demux.qza" into (ch_qiime_demux_import, ch_qiime_demux_vis, ch_qiime_demux_dada) mode flatten
when:
!params.Q2imported
script:
input_format = params.phred64 ? "PairedEndFastqManifestPhred64" : "PairedEndFastqManifestPhred33"
def folder = "${manifest}".take("${manifest}".indexOf("${params.split}"))
"""
head -n 1 ${manifest} > header.txt
tail -n+2 ${manifest} | cut -d, -f1 > col1.txt
tail -n+2 ${manifest} | cut -d, -f2 | sed 's:.*/::' > col2.txt
while read f; do
realpath \$f >> full_path.txt
done <col2.txt
tail -n+2 ${manifest} | cut -d, -f3 > col3.txt
paste -d, col1.txt full_path.txt col3.txt > cols.txt
cat cols.txt >> header.txt && mv header.txt ${manifest}
qiime tools import \
--type 'SampleData[PairedEndSequencesWithQuality]' \
--input-path ${manifest} \
--output-path ${folder}-demux.qza \
--input-format $input_format
"""
}
}
ch_qiime_demux_vis
.combine( ch_mpl_for_demux_visualize )
.set{ ch_qiime_demux_visualisation }
}
/*
* Download, unpack, extract and train classifier
* Download, unpack, and extract classifier in one process, train classifier in following process
* Use "--dereplication 90" for testing and "--dereplication 99" for real datasets
* Requirements with "--dereplication 99": 1 core (seems not to scale with more?), ~35 Gb mem, ~2:15:00 walltime
*/
if( !params.classifier ){
if( !params.onlyDenoising && !params.skip_taxonomy ){
Channel.fromPath("${params.reference_database}")
.set { ch_ref_database }
} else {
Channel.empty()
.set { ch_ref_database }
}
process classifier_extract_seq {
input:
file database from ch_ref_database
env MATPLOTLIBRC from ch_mpl_for_classifier_extract_seq
output:
file("*.qza") into ch_qiime_pretrain
stdout ch_message_classifier_removeHash
when:
!params.onlyDenoising || !params.untilQ2import
script:
"""
export HOME="\${PWD}/HOME"
if [ ${params.taxon_reference} = \"unite\" ]; then
create_unite_taxfile.py $database db.fa db.tax
fasta=\"db.fa\"
taxonomy=\"db.tax\"
else
unzip -qq $database
fasta=\"SILVA_132_QIIME_release/rep_set/rep_set_16S_only/${params.dereplication}/silva_132_${params.dereplication}_16S.fna\"
taxonomy=\"SILVA_132_QIIME_release/taxonomy/16S_only/${params.dereplication}/consensus_taxonomy_7_levels.txt\"
fi
if [ \"${params.classifier_removeHash}\" = \"true\" ]; then
sed \'s/#//g\' \$taxonomy >taxonomy-${params.dereplication}_removeHash.txt
taxonomy=\"taxonomy-${params.dereplication}_removeHash.txt\"
echo \"\n######## WARNING! The taxonomy file was altered by removing all hash signs!\"
fi
### Import
qiime tools import --type \'FeatureData[Sequence]\' \
--input-path \$fasta \
--output-path ref-seq-${params.dereplication}.qza
qiime tools import --type \'FeatureData[Taxonomy]\' \
--input-format HeaderlessTSVTaxonomyFormat \
--input-path \$taxonomy \
--output-path ref-taxonomy-${params.dereplication}.qza
#Extract sequences based on primers
qiime feature-classifier extract-reads \
--i-sequences ref-seq-${params.dereplication}.qza \
--p-f-primer ${params.FW_primer} \
--p-r-primer ${params.RV_primer} \
--o-reads ${params.FW_primer}-${params.RV_primer}-${params.dereplication}-ref-seq.qza \
--quiet
"""
}
ch_message_classifier_removeHash
.subscribe { log.info it }
process classifier_train {
publishDir "${params.outdir}/DB/", mode: params.publish_dir_mode,
saveAs: {filename ->
if (filename.indexOf("${params.FW_primer}-${params.RV_primer}-${params.dereplication}-classifier.qza") == 0) filename
else if(params.keepIntermediates) filename
else null}
input:
file '*' from ch_qiime_pretrain
env MATPLOTLIBRC from ch_mpl_for_classifier_train
output:
file("${params.FW_primer}-${params.RV_primer}-${params.dereplication}-classifier.qza") into ch_qiime_classifier
when:
!params.onlyDenoising || !params.untilQ2import
script:
"""
export HOME="\${PWD}/HOME"
#Train classifier
qiime feature-classifier fit-classifier-naive-bayes \
--i-reference-reads ${params.FW_primer}-${params.RV_primer}-${params.dereplication}-ref-seq.qza \
--i-reference-taxonomy ref-taxonomy-${params.dereplication}.qza \
--o-classifier ${params.FW_primer}-${params.RV_primer}-${params.dereplication}-classifier.qza \
--quiet
"""
}
}
/*
* Import trimmed files into QIIME2 artefact
*/
if( !params.Q2imported ){
process qiime_demux_visualize {
tag "${demux.baseName}"
publishDir "${params.outdir}", mode: params.publish_dir_mode
input:
set file(demux), env(MATPLOTLIBRC) from ch_qiime_demux_visualisation
output:
file("${demux.baseName}/*-seven-number-summaries.csv") into ch_csv_demux
file("${demux.baseName}/*")
"""
export HOME="\${PWD}/HOME"
qiime demux summarize \
--i-data ${demux} \
--o-visualization ${demux.baseName}.qzv
qiime tools export --input-path ${demux.baseName}.qzv --output-path ${demux.baseName}
"""
}
} else {
process qiime_importdemux_visualize {
publishDir "${params.outdir}", mode: params.publish_dir_mode
input:
env MATPLOTLIBRC from ch_mpl_for_demux_visualize
output:
file("demux/*-seven-number-summaries.csv") into ch_csv_demux
file("demux/*")
"""
export HOME="\${PWD}/HOME"
qiime demux summarize \
--i-data ${params.Q2imported} \
--o-visualization demux.qzv
qiime tools export --input-path demux.qzv --output-path demux
"""
}
}
/*
* Determine params.trunclenf and params.trunclenr where the median quality value drops below params.trunc_qmin
* But at least the fraction of params.trunc_rmin reads is retained
* "Warning massage" is printed
*/
if ( ! single_end ) {
process dada_trunc_parameter {
input:
file summary_demux from ch_csv_demux
output:
stdout ch_dada_trunc
when:
!params.untilQ2import
script:
if( params.trunclenf == false || params.trunclenr == false ){
"""
dada_trunc_parameter.py ${summary_demux[0]} ${summary_demux[1]} ${params.trunc_qmin} ${params.trunc_rmin}
"""
}
else
"""
printf "${params.trunclenf},${params.trunclenr}"
"""
}
} else {
process dada_trunc_se {
output:
stdout ch_dada_trunc
when:
!params.untilQ2import
script:
if ( params.trunclenf == false ) {
"""
printf "0"
"""
} else {
"""
printf "${params.trunclenf}"
"""
}
}
}
if (params.multipleSequencingRuns){
//find minimum dada truncation values
ch_dada_trunc
.into { dada_trunc_forward; dada_trunc_reverse }
dada_trunc_forward
.map { trunc -> (trunc.split(',')[0]) }
.min()
.set { dada_forward }
dada_trunc_reverse
.map { trunc -> (trunc.split(',')[1]) }
.min()
.set { dada_reverse }
dada_forward
.combine( dada_reverse )
.set { dada_trunc_multi }
//combine channels for dada_multi
ch_qiime_demux_dada
.combine( dada_trunc_multi )
.combine( ch_mpl_dada )
.set { ch_dada_multi }
}
/*
* Find ASVs with DADA2
* (i) for single sequencing run
* (ii) for PacBio reads
* (iii) for multiple sequencing runs
*/
if (!params.multipleSequencingRuns && !params.pacbio){
process dada_single {
tag "$trunc"
publishDir "${params.outdir}", mode: params.publish_dir_mode,
saveAs: {filename ->
if (filename.indexOf("dada_stats/stats.tsv") == 0) "abundance_table/unfiltered/dada_stats.tsv"
else if (filename.indexOf("dada_report.txt") == 0) "abundance_table/unfiltered/dada_report.txt"