forked from nf-core/eager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.nf
More file actions
2523 lines (2075 loc) · 104 KB
/
main.nf
File metadata and controls
2523 lines (2075 loc) · 104 KB
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/eager
============================================================================================================
EAGER Analysis Pipeline. Started 2018-06-05
#### Homepage / Documentation
https://github.com/nf-core/eager
#### Authors
For a list of authors and contributors, see: https://github.com/nf-core/eager/tree/dev#authors-alphabetical
============================================================================================================
*/
def helpMessage() {
log.info nfcoreHeader()
log.info"""
=========================================
eager v${workflow.manifest.version}
=========================================
Usage:
The typical command for running the pipeline is as follows:
nextflow run nf-core/eager -profile <docker/singularity/conda> --reads'*_R{1,2}.fastq.gz' --fasta '<your_reference>.fasta'
Mandatory arguments:
--reads Path to input data (must be surrounded with quotes). For paired end data, the path must use '{1,2}' notation to specify read pairs.
-profile Institution or personal hardware config to use (e.g. standard, docker, singularity, conda, aws). Ask your system admin if unsure, or check documentation.
--single_end Specifies that the input is single end reads (required if not paired_end).
--paired_end Specifies that the input is paired end reads (required if not single_end).
--bam Specifies that the input is in BAM format.
--fasta Path and name of FASTA reference file (required if not iGenome reference). File suffixes can be: '.fa', '.fn', '.fna', '.fasta'
--genome Name of iGenomes reference (required if not fasta reference).
Output options:
--outdir The output directory where the results will be saved. Default: ${params.outdir}
-w The directory where intermediate files will be stored. Recommended: '<outdir>/work/'
BAM Input:
--run_convertbam Turns on to convert an input BAM file into FASTQ format before processing.
Input Data Additional Options:
--snpcapture Runs in SNPCapture mode (specify a BED file if you do this!).
References Optional additional pre-made indices, or you wish to overwrite any of the references.
--bwa_index Path and name of a bwa indexed FASTA reference file with index suffixes (i.e. everything before the endings '.amb' '.ann' '.bwt'. Most likely the same value as --fasta)
--bedfile Path to BED file for SNPCapture methods.
--seq_dict Path to picard sequence dictionary file (typically ending in '.dict').
--fasta_index Path to samtools FASTA index (typically ending in '.fai').
--save_reference Turns on saving reference genome indices for later re-usage.
Skipping Skip any of the mentioned steps.
--skip_fastqc Skips both pre- and post-Adapter Removal FastQC steps.
--skip_adapterremoval
--skip_mapping Note: this maybe useful when input is a BAM file.
--skip_preseq
--skip_damage_calculation
--skip_qualimap
--skip_deduplication
Complexity Filtering
--complexity_filter_poly_g Turn on running poly-G removal on FASTQ files.
--complexity_filter_poly_g_min Specify length of poly-g min for clipping to be performed. Default: ${params.complexity_filter_poly_g_min}
Clipping / Merging
--clip_forward_adaptor Specify adapter sequence to be clipped off (forward). Default: '${params.clip_forward_adaptor}'
--clip_reverse_adaptor Specify adapter sequence to be clipped off (reverse). Default: '${params.clip_reverse_adaptor}'
--clip_readlength Specify read minimum length to be kept for downstream analysis. Default: ${params.clip_readlength}
--clip_min_read_quality Specify minimum base quality for trimming off bases. Default: ${params.clip_min_read_quality}
--min_adap_overlap Specify minimum adapter overlap: Default: ${params.min_adap_overlap}
--skip_collapse Turn on skipping of merging forward and reverse reads together. Only applicable for PE libraries.
--skip_trim Turn on skipping of adapter and quality trimming
--preserve5p Turn on skipping 5p quality base trimming (n, score, window) at 5p end.
--mergedonly Turn on sending downstream only merged reads (un-merged reads and singletons are discarded).
Mapping
--mapper Specify which mapper to use. Options: 'bwaaln', 'bwamem', 'circularmapper'. Default: '${params.mapper}'
--bwaalnn Specify the -n parameter for BWA aln. Default: ${params.bwaalnn}
--bwaalnk Specify the -k parameter for BWA aln. Default: ${params.bwaalnk}
--bwaalnl Specify the -l parameter for BWA aln. Default: ${params.bwaalnl}
--circularextension Specify the number of bases to extend reference by (circularmapper only). Default: ${params.circularextension}
--circulartarget Specify the target chromosome for CM (circularmapper only). Default: '${params.circulartarget}'
--circularfilter Turn on to filter off-target reads (circularmapper only).
Stripping
--strip_input_fastq Turn on creating pre-Adapter Removal FASTQ files without reads that mapped to reference (e.g. for public upload of privacy sensitive non-host data)
--strip_mode Stripping mode. Remove mapped reads completely from FASTQ (strip) or just mask mapped reads sequence by N (replace). Default: '${params.strip_mode}'
BAM Filtering
--run_bam_filtering Turn on samtools filter for mapping quality or unmapped reads of BAM files.
--bam_mapping_quality_threshold Minimum mapping quality for reads filter. Default: ${params.bam_mapping_quality_threshold}
--bam_discard_unmapped Turns on discarding of unmapped reads in either FASTQ or BAM format, depending on choice (see --bam_unmapped_type).
--bam_unmapped_type Defines whether to discard all unmapped reads, keep only bam and/or keep only fastq format Options: 'discard', 'bam', 'fastq', 'both'. Default: ${params.bam_unmapped_type}
DeDuplication
--dedupper Deduplication method to use. Options: 'dedup', 'markduplicates'. Default: '${params.dedupper}'
--dedup_all_merged Turn on treating all reads as merged reads.
Library Complexity Estimation
--preseq_step_size Specify the step size of Preseq. Default: ${params.preseq_step_size}
(aDNA) Damage Analysis
--damageprofiler_length Specify length filter for DamageProfiler. Default: ${params.damageprofiler_length}
--damageprofiler_threshold Specify number of bases to consider for damageProfiler (e.g. on damage plot). Default: ${params.damageprofiler_threshold}
--damageprofiler_yaxis Specify the maximum misincorporation frequency that should be displayed on damage plot. Set to 0 to 'autoscale'. Default: ${params.damageprofiler_yaxis}
--run_pmdtools Turn on PMDtools
--udg_type Specify here if you have UDG half treated libraries, Set to 'half' in that case, or 'full' for UDG+. If not set, libraries are assumed to have no UDG treatment.
--pmdtools_range Specify range of bases for PMDTools. Default: ${params.pmdtools_range}
--pmdtools_threshold Specify PMDScore threshold for PMDTools. Default: ${params.pmdtools_threshold}
--pmdtools_reference_mask Specify a path to reference mask for PMDTools.
--pmdtools_max_reads Specify the maximum number of reads to consider for metrics generation. Default: ${params.pmdtools_max_reads}
Annotation Statistics
--run_bedtools_coverage Turn on ability to calculate no. reads, depth and breadth coverage of features in reference.
--anno_file Path to GFF or BED file containing positions of features in reference file (--fasta). Path should be enclosed in quotes.
BAM Trimming
--run_trim_bam Turn on BAM trimming, for example for for full-UDG or half-UDG protocols.
--bamutils_clip_left Specify the number of bases to clip off reads from 'left' end of read. Default: ${params.bamutils_clip_left}
--bamutils_clip_right Specify the number of bases to clip off reads from 'right' end of read. Default: ${params.bamutils_clip_right}
--bamutils_softclip Turn on using softclip instead of hard masking.
Genotyping
--run_genotyping Turn on genotyping of BAM files.
--genotyping_tool Specify which genotyper to use either GATK UnifiedGenotyper, GATK HaplotypeCaller or Freebayes. Note: UnifiedGenotyper requires user-supplied defined GATK 3.5 jar file. Options: 'ug', 'hc', 'freebayes'.
--genotyping_source Specify which input BAM to use for genotyping. Options: 'raw', 'trimmed' or 'pmd'. Default: '${params.genotyping_source}'
--gatk_ug_jar When specifying to use GATK UnifiedGenotyper, path to GATK 3.5 .jar.
--gatk_call_conf Specify GATK phred-scaled confidence threshold. Default: ${params.gatk_call_conf}
--gatk_ploidy Specify GATK organism ploidy. Default: ${params.gatk_ploidy}
--gatk_dbsnp Specify VCF file for output VCF SNP annotation. Optional. Gzip not accepted.
--gatk_ug_out_mode Specify GATK output mode. Options: 'EMIT_VARIANTS_ONLY', 'EMIT_ALL_CONFIDENT_SITES', 'EMIT_ALL_SITES'. Default: '${params.gatk_ug_out_mode}'
--gatk_hc_out_mode Specify GATK output mode. Options: 'EMIT_VARIANTS_ONLY', 'EMIT_ALL_CONFIDENT_SITES', 'EMIT_ALL_ACTIVE_SITES'. Default: '${params.gatk_hc_out_mode}'
--gatk_ug_genotype_model Specify UnifiedGenotyper likelihood model. Options: 'SNP', 'INDEL', 'BOTH', 'GENERALPLOIDYSNP', 'GENERALPLOIDYINDEL'. Default: '${params.gatk_ug_genotype_model}'
--gatk_hc_emitrefconf Specify HaplotypeCaller mode for emitting reference confidence calls . Options: 'NONE', 'BP_RESOLUTION', 'GVCF'. Default: '${params.gatk_hc_emitrefconf}'
--gatk_downsample Maximum depth coverage allowed for genotyping before down-sampling is turned on. Default: ${params.gatk_downsample}
--gatk_ug_defaultbasequalities Supply a default base quality if a read is missing a base quality score. Setting to -1 turns this off.
--freebayes_C Specify minimum required supporting observations to consider a variant. Default: ${params.freebayes_C}
--freebayes_g Specify to skip over regions of high depth by discarding alignments overlapping positions where total read depth is greater than specified in --freebayes_C. Default: ${params.freebayes_g}
--freebayes_p Specify ploidy of sample in FreeBayes. Default: ${params.freebayes_p}
consensus Sequence Generation
--run_vcf2genome Turns on ability to create a consensus sequence FASTA file based on a UnifiedGenotyper VCF file and the original reference (only considers SNPs).
--vcf2genome_outfile Specify name of the output FASTA file containing the consensus sequence. Do not include `.vcf` in the file name. Default: '<input_vcf>'
--vcf2genome_header Specify the header name of the consensus sequence entry within the FASTA file. Default: '<input_vcf>'
--vcf2genome_minc Minimum depth coverage required for a call to be included (else N will be called). Default: ${params.vcf2genome_minc}
--vcf2genome_minq Minimum genotyping quality of a call to be called. Else N will be called. Default: ${params.vcf2genome_minq}
--vcf2genome_minfreq Minimum fraction of reads supporting a call to be included. Else N will be called. Default: ${params.vcf2genome_minfreq}
SNP Table Generation
--run_multivcfanalyzer Turn on MultiVCFAnalyzer. Note: This currently only supports diploid GATK UnifiedGenotyper input.
--write_allele_frequencies Turn on writing write allele frequencies in the SNP table.
--min_genotype_quality Specify the minimum genotyping quality threshold for a SNP to be called. Default: ${params.min_genotype_quality}
--min_base_coverage Specify the minimum number of reads a position needs to be covered to be considered for base calling. Default: ${params.min_base_coverage}
--min_allele_freq_hom Specify the minimum allele frequency that a base requires to be considered a 'homozygous' call. Default: ${params.min_allele_freq_hom}
--min_allele_freq_het Specify the minimum allele frequency that a base requires to be considered a 'heterozygous' call. Default: ${params.min_allele_freq_het}
--additional_vcf_files Specify paths to additional pre-made VCF files to be included in the SNP table generation. Use wildcard(s) for multiple files. Optional.
--reference_gff_annotations Specify path to the reference genome annotations in '.gff' format. Optional.
--reference_gff_exclude Specify path to the positions to be excluded in '.gff' format. Optional.
--snp_eff_results Specify path to the output file from SNP effect analysis in '.txt' format. Optional.
Mitochondrial to Nuclear Ratio
--run_mtnucratio Turn on mitochondrial to nuclear ratio calculation.
--mtnucratio_header Specify the name of the reference FASTA entry corresponding to the mitochondrial genome (up to the first space). Default: '${params.mtnucratio_header}'
Sex Determination
--run_sexdeterrmine Turn on sex determination for human reference genomes.
--sexdeterrmine_bedfile Specify path to SNP panel in bed format for error bar calculation. Optional (see documentation).
Nuclear Contamination for Human DNA
--run_nuclear_contamination Turn on nuclear contamination estimation for human reference genomes.
--contamination_chrom_name The name of the chromosome in your bam. 'X' for hs37d5, 'chrX' for HG19. Default: '${params.contamination_chrom_name}'
Metagenomic Screening
--run_metagenomic_screening Turn on metagenomic screening module for reference-unmapped reads
--metagenomic_tool Specify which classifier to use. Options: 'malt', 'kraken'. Default: '${params.contamination_chrom_name}'
--database Specify path to classifer database directory. For Kraken2 this can also be a `.tar.gz` of the directory.
--metagenomic_min_support_reads Specify a minimum number of reads a taxon of sample total is required to have to be retained. Not compatible with . Default: ${params.metagenomic_min_support_reads}
--percent_identity Percent identity value threshold for MALT. Default: ${params.percent_identity}
--malt_mode Specify which alignment method to use for MALT. Options: 'Unknown', 'BlastN', 'BlastP', 'BlastX', 'Classifier'. Default: '${params.malt_mode}'
--malt_alignment_mode Specify alignment method for MALT. Options: 'Local', 'SemiGlobal'. Default: '${params.malt_alignment_mode}'
--malt_top_percent Specify the percent for LCA algorithm for MALT (see MEGAN6 CE manual). Default: ${params.malt_top_percent}
--malt_min_support_mode Specify whether to use percent or raw number of reads for minimum support required for taxon to be retained for MALT. Options: 'percent', 'reads'. Default: '${params.malt_min_support_mode}'
--malt_min_support_percent Specify the minimum percentage of reads a taxon of sample total is required to have to be retained for MALT. Default: Default: ${params.malt_min_support_percent}
--malt_max_queries Specify the maximium number of queries a read can have for MALT. Default: ${params.malt_max_queries}
--malt_memory_mode Specify the memory load method. Do not use 'map' with GTFS file system for MALT. Options: 'load', 'page', 'map'. Default: '${params.malt_memory_mode}'
Metagenomic Authentication
--run_maltextract Turn on MaltExtract for MALT aDNA characteristics authentication
--maltextract_taxon_list Path to a txt file with taxa of interest (one taxon per row, NCBI taxonomy name format)
--maltextract_ncbifiles Path to directory containing containing NCBI resource files (ncbi.tre and ncbi.map; avaliable: https://github.com/rhuebler/HOPS/)
--maltextract_filter Specify which MaltExtract filter to use. Options: 'def_anc', 'ancient', 'default', 'crawl', 'scan', 'srna', 'assignment'. Default: '${params.maltextract_filter}'
--maltextract_toppercent Specify percent of top alignments to use. Default: ${params.maltextract_toppercent}
--maltextract_destackingoff Turn off destacking.
--maltextract_downsamplingoff Turn off downsampling.
--maltextract_duplicateremovaloff Turn off duplicate removal.
--maltextract_matches Turn on exporting alignments of hits in BLAST format.
--maltextract_megansummary Turn on export of MEGAN summary files.
--maltextract_percentidentity Minimum percent identity alignments are required to have to be reported. Recommended to set same as MALT parameter. Default: ${params.maltextract_percentidentity}
--maltextract_topalignment Turn on using top alignments per read after filtering.
--maltextract_singlestranded Turn on calculating damage patterns in single-stranded mode.
Other options:
-name Name for the pipeline run. If not specified, Nextflow will automatically generate a random mnemonic.
--max_memory Memory limit for each step of pipeline. Should be in form e.g. --max_memory '8.GB'. Default: '${params.max_memory}'
--max_time Time limit for each step of the pipeline. Should be in form e.g. --max_memory '2.h'. Default: '${params.max_time}'
--max_cpus Maximum number of CPUs to use for each step of the pipeline. Should be in form e.g. Default: '${params.max_cpus}'
--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
--plaintext_email Receive plain text emails rather than HTML
--maxMultiqcEmailFileSize 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)
For a full list and more information of available parameters, consider the documentation (https://github.com/nf-core/eager/).
""".stripIndent()
}
/*
* SET UP CONFIGURATION VARIABLES
*/
// Show help message
params.help = false
if (params.help){
helpMessage()
exit 0
}
/*
* SANITY CHECKING
*/
// Validate inputs
if ( params.fasta.isEmpty () ){
exit 1, "Please specify --fasta with the path to your reference"
} else if("${params.fasta}".endsWith(".gz")){
//Put the zip into a channel, then unzip it and forward to downstream processes. DONT unzip in all steps, this is inefficient as NXF links the files anyways from work to work dir
zipped_fasta = file("${params.fasta}")
rm_gz = params.fasta - '.gz'
lastPath = rm_gz.lastIndexOf(File.separator)
bwa_base = rm_gz.substring(lastPath+1)
process unzip_reference{
tag "${zipped_fasta}"
input:
file zipped_fasta
output:
file "*.{fa,fn,fna,fasta}" into ch_fasta_for_bwaindex,ch_fasta_for_faidx,ch_fasta_for_seqdict,ch_fasta_for_circulargenerator,ch_fasta_for_circularmapper,ch_fasta_for_damageprofiler,ch_fasta_for_qualimap,ch_fasta_for_pmdtools,ch_fasta_for_genotyping_ug,ch_fasta_for_genotyping_hc,ch_fasta_for_genotyping_freebayes,ch_fasta_for_vcf2genome,ch_fasta_for_multivcfanalyzer
script:
rm_zip = zipped_fasta - '.gz'
"""
pigz -f -d -p ${task.cpus} $zipped_fasta
"""
}
} else {
fasta_for_indexing = Channel
.fromPath("${params.fasta}", checkIfExists: true)
.into{ ch_fasta_for_bwaindex; ch_fasta_for_faidx; ch_fasta_for_seqdict; ch_fasta_for_circulargenerator; ch_fasta_for_circularmapper; ch_fasta_for_damageprofiler; ch_fasta_for_qualimap; ch_fasta_for_pmdtools; ch_fasta_for_genotyping_ug; ch_fasta__for_genotyping_hc; ch_fasta_for_genotyping_hc; ch_fasta_for_genotyping_freebayes; ch_fasta_for_vcf2genome; ch_fasta_for_multivcfanalyzer }
lastPath = params.fasta.lastIndexOf(File.separator)
bwa_base = params.fasta.substring(lastPath+1)
}
// Check if genome exists in the config file. params.genomes is from igenomes.conf, params.genome specified by user
if (params.genomes && params.genome && !params.genomes.containsKey(params.genome)) {
exit 1, "The provided genome '${params.genome}' is not available in the iGenomes file. Currently the available genomes are ${params.genomes.keySet().join(", ")}"
}
// Index files provided? Then check whether they are correct and complete
if (params.mapper != 'bwaaln' && !params.mapper == 'circularmapper' && !params.mapper == 'bwamem'){
exit 1, "Invalid mapper option. Options are: 'bwaaln', 'bwamem', 'circularmapper'. Default: 'bwaaln'. You gave ${params.mapper}!"
}
if( params.bwa_index && (params.mapper == 'bwaaln' | params.mapper == 'bwamem')){
lastPath = params.bwa_index.lastIndexOf(File.separator)
bwa_dir = params.bwa_index.substring(0,lastPath+1)
bwa_base = params.bwa_index.substring(lastPath+1)
Channel
.fromPath(bwa_dir, checkIfExists: true)
.ifEmpty { exit 1, "BWA index directory not found: ${bwa_dir}" }
.into {bwa_index; bwa_index_bwamem}
}
// Validate not trying to run adapterremoval on a BAM file
if (params.bam && !params.run_convertbam && !params.skip_adapterremoval ) {
exit 1, "AdapterRemoval cannot be run on BAMs. Please validate your parameters."
}
// Validate BAM is single end only
if (params.bam && !params.single_end){
exit 1, "BAM input must be used with --single_end "
}
// Validate that you're not trying to pass FASTQs to BAM only processes
if (params.run_convertbam && params.skip_mapping) {
exit 1, "You can't convert a BAM to FASTQ and skip mapping! Post-mapping steps require BAM input. Please validate your parameters!"
}
// Validate that you're not trying to pass FASTQs to BAM only processes
if (params.bam && !params.run_convertbam && !params.skip_mapping) {
exit 1, "You can't directly map a BAM file! Please supply the --run_convertbam parameter!"
}
// Validate that either paired_end or single_end has been specified by the user!
if( params.single_end || params.paired_end || params.bam){
} else {
exit 1, "Please specify either --single_end, --paired_end to execute the pipeline on FastQ files and --bam for previously processed BAM files!"
}
// Validate that skip_collapse is only set to True for paired_end reads!
if (params.skip_collapse && params.single_end){
exit 1, "--skip_collapse can only be set for paired_end samples!"
}
// Strip mode sanity checking
if (params.strip_input_fastq){
if (!(['strip','replace'].contains(params.strip_mode))) {
exit 1, "--strip_mode can only be set to strip or replace!"
}
if (params.bam && !params.run_convertbam) {
exit 1, "--strip_input_fastq can only be used on FASTQ, but you gave BAM input and didn't specify --run_convertbam!"
}
}
// Mapper sanity checking
if(params.mapper != "bwaaln" && params.mapper != "bwamem" && params.mapper != "circularmapper") {
exit 1, "Please specify a valid mapper. Options: 'bwaaln', 'bwamem', 'circularmapper'. You gave: ${params.mapper}!"
}
if (params.bam_discard_unmapped && params.bam_unmapped_type == '') {
exit 1, "Please specify valid unmapped read output format. Options: 'discard', 'bam', 'fastq', 'both'!"
}
// Bedtools sanity checking
if(params.run_bedtools_coverage && params.anno_file == ''){
exit 1, "You have turned on bedtools coverage, but not specified a BED or GFF file with --anno_file. Please validate your parameters!"
}
// BAM filtering sanity checking - FIRST ONE CURRENTLY DOES NOT WORK!
if (params.bam_discard_unmapped && !params.run_bam_filtering) {
"Please turn on BAM filtering before trying to indicate how to deal with unmapped reads! Give --run_bam_filtering"
}
if (params.run_bam_filtering && params.bam_discard_unmapped && params.bam_unmapped_type == '') {
"Please specify how to deal with unmapped reads. Options: 'discard', 'bam', 'fastq', 'both'"
}
// Genotyping sanity checking
if (params.run_genotyping){
if (params.genotyping_tool != 'ug' && params.genotyping_tool != 'hc' && params.genotyping_tool != 'freebayes') {
exit 1, "Please specify a genotyper. Options: 'ug', 'hc', 'freebayes'. You gave: ${params.genotyping_tool}!"
}
if (params.genotyping_tool == 'ug' && params.gatk_ug_jar == '') {
exit 1, "Please specify path to a GATK 3.5 .jar file with --gatk_ug_jar."
}
if (params.gatk_ug_out_mode != 'EMIT_VARIANTS_ONLY' && params.gatk_ug_out_mode != 'EMIT_ALL_CONFIDENT_SITES' && params.gatk_ug_out_mode != 'EMIT_ALL_SITES') {
exit 1, "Please check your GATK output mode. Options are: 'EMIT_VARIANTS_ONLY', 'EMIT_ALL_CONFIDENT_SITES', 'EMIT_ALL_SITES'. You gave: ${params.gatk_out_mode}!"
}
if (params.gatk_hc_out_mode != 'EMIT_VARIANTS_ONLY' && params.gatk_hc_out_mode != 'EMIT_ALL_CONFIDENT_SITES' && params.gatk_hc_out_mode != 'EMIT_ALL_ACTIVE_SITES') {
exit 1, "Please check your GATK output mode. Options are: 'EMIT_VARIANTS_ONLY', 'EMIT_ALL_CONFIDENT_SITES', 'EMIT_ALL_SITES'. You gave: ${params.gatk_out_mode}!"
}
if (params.genotyping_tool == 'ug' && (params.gatk_ug_genotype_model != 'SNP' && params.gatk_ug_genotype_model != 'INDEL' && params.gatk_ug_genotype_model != 'BOTH' && params.gatk_ug_genotype_model != 'GENERALPLOIDYSNP' && params.gatk_ug_genotype_model != 'GENERALPLOIDYINDEL')) {
exit 1, "Please check your UnifiedGenotyper genotype model. Options: 'SNP', 'INDEL', 'BOTH', 'GENERALPLOIDYSNP', 'GENERALPLOIDYINDEL'. You gave: ${params.gatk_ug_genotype_model}!"
}
if (params.genotyping_tool == 'hc' && (params.gatk_hc_emitrefconf != 'NONE' && params.gatk_hc_emitrefconf != 'GVCF' && params.gatk_hc_emitrefconf != 'BP_RESOLUTION')) {
exit 1, "Please check your HaplotyperCaller reference confidence parameter. Options: 'NONE', 'GVCF', 'BP_RESOLUTION'. You gave: ${params.gatk_hc_emitrefconf}!"
}
}
// Consensus sequence generation sanity checking
if (params.run_vcf2genome) {
if (!params.run_genotyping) {
exit 1, "Consensus sequence generation requires genotyping via UnifiedGenotyper on be turned on with the parameter --run_genotyping and --genotyping_tool 'ug'. Please check your genotyping parameters"
}
if (params.genotyping_tool != 'ug') {
exit 1, "Consensus sequence generation requires genotyping via UnifiedGenotyper on be turned on with the parameter --run_genotyping and --genotyping_tool 'ug'. Please check your genotyping parameters"
}
}
// MultiVCFAnalyzer sanity checking
if (params.run_multivcfanalyzer) {
if (!params.run_genotyping) {
exit 1, "MultiVCFAnalyzer requires genotyping on be turned on with the parameter --run_genotyping. Please check your genotyping parameters"
}
if (params.genotyping_tool != "ug") {
exit 1, "MultiVCFAnalyzer only accepts VCF files from GATK UnifiedGenotyper. Please check your genotyping parameters"
}
if (params.gatk_ploidy != '2') {
exit 1, "MultiVCFAnalyzer only accepts VCF files generated with a GATK ploidy set to 2. Please check your genotyping parameters"
}
}
// Metagenomic sanity checking
if (params.run_metagenomic_screening) {
if ( !params.bam_discard_unmapped ) {
exit 1, "Metagenomic classification can only run on unmapped reads. Please supply --bam_discard_unmapped and --bam_unmapped_type 'fastq'"
}
if (params.bam_discard_unmapped && params.bam_unmapped_type != 'fastq' ) {
exit 1, "Metagenomic classification can only run on unmapped reads in FASTSQ format. Please supply --bam_unmapped_type 'fastq'. You gave '${params.bam_unmapped_type}'!"
}
if (params.metagenomic_tool != 'malt' && params.metagenomic_tool != 'kraken') {
exit 1, "Metagenomic classification can currently only be run with 'malt' or 'kraken' (kraken2). Please check your classifer. You gave '${params.metagenomic_tool}'!"
}
if (params.database == '' ) {
exit 1, "Metagenomic classification requires a path to a database directory. Please specify one with --database '/path/to/database/'."
}
if (params.metagenomic_tool == 'malt' && params.malt_mode != 'BlastN' && params.malt_mode != 'BlastP' && params.malt_mode != 'BlastX') {
exit 1, "Unknown MALT mode specified. Options: 'BlastN', 'BlastP', 'BlastX'. You gave '${params.malt_mode}'!"
}
if (params.metagenomic_tool == 'malt' && params.malt_alignment_mode != 'Local' && params.malt_alignment_mode != 'SemiGlobal') {
exit 1, "Unknown MALT alignment mode specified. Options: 'Local', 'SemiGlobal'. You gave '${params.malt_alignment_mode}'!"
}
if (params.metagenomic_tool == 'malt' && params.malt_min_support_mode == 'percent' && params.metagenomic_min_support_reads != 1) {
exit 1, "Incompatible MALT min support configuration. Percent can only be used with --malt_min_support_percent. You modified --metagenomic_min_support_reads!"
}
if (params.metagenomic_tool == 'malt' && params.malt_min_support_mode == 'reads' && params.malt_min_support_percent != 0.01) {
exit 1, "Incompatible MALT min support configuration. Reads can only be used with --malt_min_supportreads. You modified --malt_min_support_percent!"
}
if (params.metagenomic_tool == 'malt' && params.malt_memory_mode != 'load' && params.malt_memory_mode != 'page' && params.malt_memory_mode != 'map') {
exit 1, "Unknown MALT memory mode specified. Options: 'load', 'page', 'map'. You gave '${params.malt_memory_mode}'!"
}
}
// MaltExtract Sanity checking
if (params.run_maltextract) {
if (params.run_metagenomic_screening && params.metagenomic_tool != 'malt') {
exit 1, "MaltExtract can only accept MALT output. Please supply --metagenomic_tool 'malt'!"
}
if (params.run_metagenomic_screening && params.metagenomic_tool != 'malt') {
exit 1, "MaltExtract can only accept MALT output. Please supply --metagenomic_tool 'malt'!"
}
if (params.maltextract_taxon_list == '') {
exit 1, "MaltExtract requires a taxon list specify target taxa of interest. Specify the file with --params.maltextract_taxon_list!"
}
if (params.maltextract_filter != 'def_anc' && params.maltextract_filter != 'default' && params.maltextract_filter != 'ancient' && params.maltextract_filter != 'scan' && params.maltextract_filter != 'crawl' && params.maltextract_filter != 'srna') {
exit 1, "Unknown MaltExtract filter specified. Options are: 'def_anc', 'default', 'ancient', 'scan', 'crawl', 'srna'. You gave: ${params.maltextract_filter}!"
}
}
// 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
}
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("$baseDir/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("$baseDir/docs/output.md", checkIfExists: true)
where_are_my_files = file("$baseDir/assets/where_are_my_files.txt")
/*
* Create a channel for input read files
* Dump can be used for debugging purposes, e.g. using the -dump-channels operator on run
*/
// If read paths
// Is single FASTQ
// Is paired-end FASTQ
// Is single BAM
// If NOT read paths && FASTQ
// is NOT read paths && BAM
if( params.readPaths ){
if( params.single_end && !params.bam) {
Channel
.from( params.readPaths )
.filter { it =~/.*.fastq.gz|.*.fq.gz|.*.fastq|.*.fq/ }
.ifEmpty { exit 1, "Your specified FASTQ read files did not end in: '.fastq.gz', '.fq.gz', '.fastq', or '.fq' " }
.map { row -> [ row[0], [ file( row[1][0] ) ] ] }
.ifEmpty { exit 1, "params.readPaths was empty - no input files supplied!" }
.into { ch_input_for_skipconvertbam; ch_input_for_convertbam; ch_input_for_indexbam }
} else if (!params.bam){
Channel
.from( params.readPaths )
.filter { it =~/.*.fastq.gz|.*.fq.gz|.*.fastq|.*.fq/ }
.ifEmpty { exit 1, "Your specified FASTQ read files did not end in: '.fastq.gz', '.fq.gz', '.fastq', or '.fq' " }
.map { row -> [ row[0], [ file( row[1][0] ), file( row[1][1] ) ] ] }
.ifEmpty { exit 1, "params.readPaths was empty - no input files supplied!" }
.into { ch_input_for_skipconvertbam; ch_input_for_convertbam; ch_input_for_indexbam }
} else {
Channel
.from( params.readPaths )
.filter { it =~/.*.bam/ }
.ifEmpty { exit 1, "Your specified BAM read files did not end in: '.bam' " }
.map { row -> [ file( row ) ] }
.ifEmpty { exit 1, "params.readPaths was empty - no input files supplied!" }
.dump()
.into { ch_input_for_skipconvertbam; ch_input_for_convertbam; ch_input_for_indexbam }
}
} else if (!params.bam){
Channel
.fromFilePairs( params.reads, size: params.single_end ? 1 : 2 )
.filter { it =~/.*.fastq.gz|.*.fq.gz|.*.fastq|.*.fq/ }
.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!\nValid input file types: .fastq.gz', '.fq.gz', '.fastq', or '.fq'\nIf this is single-end data, please specify --single_end on the command line." }
.into { ch_input_for_skipconvertbam; ch_input_for_convertbam; ch_input_for_indexbam }
} else {
Channel
.fromPath( params.reads )
.filter { it =~/.*.bam/ }
.map { row -> [ file( row ) ] }
.ifEmpty { exit 1, "Cannot find any bam file matching: ${params.reads}\nValid input file types: '.bam'" +
"to be enclosed in quotes!\n" }
.dump() //For debugging purposes
.into { ch_input_for_skipconvertbam; ch_input_for_convertbam; ch_input_for_indexbam }
}
// Header log info
log.info nfcoreHeader()
def summary = [:]
summary['Pipeline Name'] = 'nf-core/eager'
summary['Pipeline Version'] = workflow.manifest.version
summary['Run Name'] = custom_runName ?: workflow.runName
summary['Reads'] = params.reads
summary['Fasta Ref'] = params.fasta
summary['BAM Index Type'] = (params.large_ref == "") ? 'BAI' : 'CSI'
if(params.bwa_index) summary['BWA Index'] = params.bwa_index
summary['Data Type'] = params.single_end ? 'Single-End' : 'Paired-End'
summary['Skipping FASTQC?'] = params.skip_fastqc ? 'Yes' : 'No'
summary['Skipping AdapterRemoval?'] = params.skip_adapterremoval ? 'Yes' : 'No'
if (!params.skip_adapterremoval) {
summary['Skip Read Merging'] = params.skip_collapse ? 'Yes' : 'No'
summary['Skip Adapter Trimming'] = params.skip_trim ? 'Yes' : 'No'
}
summary['Running BAM filtering'] = params.run_bam_filtering ? 'Yes' : 'No'
if (params.run_bam_filtering) {
summary['Skip Read Merging'] = params.bam_discard_unmapped ? 'Yes' : 'No'
summary['Skip Read Merging'] = params.bam_unmapped_type
}
summary['Run Fastq Stripping'] = params.strip_input_fastq ? 'Yes' : 'No'
if (params.strip_input_fastq){
summary['Strip mode'] = params.strip_mode
}
summary['Skipping Mapping?'] = params.skip_mapping ? 'Yes' : 'No'
summary['Skipping Preseq?'] = params.skip_preseq ? 'Yes' : 'No'
summary['Skipping Deduplication?'] = params.skip_deduplication ? 'Yes' : 'No'
summary['Skipping DamageProfiler?'] = params.skip_damage_calculation ? 'Yes' : 'No'
summary['Skipping Qualimap?'] = params.skip_qualimap ? 'Yes' : 'No'
summary['Run BAM Trimming?'] = params.run_trim_bam ? 'Yes' : 'No'
summary['Run PMDtools?'] = params.run_pmdtools ? 'Yes' : 'No'
summary['Run Genotyping?'] = params.run_genotyping ? 'Yes' : 'No'
if (params.run_genotyping){
summary['Genotyping Tool?'] = params.genotyping_tool
summary['Genotyping BAM Input?'] = params.genotyping_source
}
summary['Run MultiVCFAnalyzer'] = params.run_multivcfanalyzer ? 'Yes' : 'No'
summary['Run VCF2Genome'] = params.run_vcf2genome ? 'Yes' : 'No'
summary['Run SexDetErrMine'] = params.run_sexdeterrmine ? 'Yes' : 'No'
summary['Run Nuclear Contamination Estimation'] = params.run_nuclear_contamination ? 'Yes' : 'No'
summary['Run Bedtools Coverage'] = params.run_bedtools_coverage ? 'Yes' : 'No'
summary['Run Metagenomic Binning'] = params.run_metagenomic_screening ? 'Yes' : 'No'
if (params.run_metagenomic_screening) {
summary['Metagenomic Tool'] = params.metagenomic_tool
summary['Run MaltExtract'] = params.run_maltextract ? 'Yes' : 'No'
}
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 Engine'] = workflow.containerEngine
if(workflow.containerEngine) summary['Container'] = workflow.container
summary['Current Home'] = "$HOME"
summary['Current User'] = "$USER"
summary['Current Path'] = "$PWD"
summary['Working Dir'] = workflow.workDir
summary['Output Dir'] = params.outdir
summary['Script Dir'] = workflow.projectDir
summary['Config Profile'] = workflow.profile
if(workflow.profile == 'awsbatch'){
summary['AWS Region'] = params.awsregion
summary['AWS Queue'] = params.awsqueue
}
if(params.email) summary['E-mail Address'] = params.email
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 || 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-"
// 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-eager-summary'
description: " - this information is collected when the pipeline is started."
section_name: 'nf-core/eager Workflow Summary'
section_href: 'https://github.com/nf-core/eager'
plot_type: 'html'
data: |
<dl class=\"dl-horizontal\">
$x
</dl>
""".stripIndent() }
.set { ch_workflow_summary }
/*
* PREPROCESSING - Create BWA indices if they are not present
*/
if(!params.bwa_index && !params.fasta.isEmpty() && (params.mapper == 'bwaaln' || params.mapper == 'bwamem' || params.mapper == 'circularmapper')){
process makeBWAIndex {
label 'sc_medium'
tag {fasta}
publishDir path: "${params.outdir}/reference_genome/bwa_index", mode: 'copy', saveAs: { filename ->
if (params.save_reference) filename
else if(!params.save_reference && filename == "where_are_my_files.txt") filename
else null
}
input:
file fasta from ch_fasta_for_bwaindex
file where_are_my_files
output:
file "BWAIndex" into (bwa_index, bwa_index_bwamem)
file "where_are_my_files.txt"
script:
"""
bwa index $fasta
mkdir BWAIndex && mv ${fasta}* BWAIndex
"""
}
}
/*
* PREPROCESSING - Index Fasta file if not specified on CLI
*/
if (params.fasta_index != '') {
Channel
.fromPath( params.fasta_index )
.set { ch_fai_for_skipfastaindexing }
} else {
Channel
.empty()
.set { ch_fai_for_skipfastaindexing }
}
process makeFastaIndex {
label 'sc_small'
tag {fasta}
publishDir path: "${params.outdir}/reference_genome/fasta_index", mode: 'copy', saveAs: { filename ->
if (params.save_reference) filename
else if(!params.save_reference && filename == "where_are_my_files.txt") filename
else null
}
when: params.fasta_index == '' && !params.fasta.isEmpty() && ( params.mapper == 'bwaaln' || params.mapper == 'bwamem' || params.mapper == 'circularmapper')
input:
file fasta from ch_fasta_for_faidx
file where_are_my_files
output:
file "*.fai" into ch_fasta_faidx_index
file "where_are_my_files.txt"
script:
"""
samtools faidx $fasta
"""
}
ch_fai_for_skipfastaindexing.mix(ch_fasta_faidx_index)
.into { ch_fai_for_ug; ch_fai_for_hc; ch_fai_for_freebayes }
/*
* PREPROCESSING - Create Sequence Dictionary for FastA if not specified on CLI
*/
// Stage dict index file if supplied, else load it into the channel
if (params.seq_dict != '') {
Channel
.fromPath( params.seq_dict )
.set { ch_dict_for_skipdict }
} else {
Channel
.empty()
.set { ch_dict_for_skipdict }
}
process makeSeqDict {
label 'sc_medium'
tag {fasta}
publishDir path: "${params.outdir}/reference_genome/seq_dict", mode: 'copy', saveAs: { filename ->
if (params.save_reference) filename
else if(!params.save_reference && filename == "where_are_my_files.txt") filename
else null
}
when: params.seq_dict == '' && !params.fasta.isEmpty()
input:
file fasta from ch_fasta_for_seqdict
file where_are_my_files
output:
file "*.dict" into ch_seq_dict
file "where_are_my_files.txt"
script:
"""
picard -Xmx${task.memory.toMega()}M -Xms${task.memory.toMega()}M CreateSequenceDictionary R=$fasta O="${fasta.baseName}.dict"
"""
}
ch_dict_for_skipdict.mix(ch_seq_dict)
.into { ch_dict_for_ug; ch_dict_for_hc; ch_dict_for_freebayes }
/*
* PREPROCESSING - Convert BAM to FastQ if BAM input is specified instead of FastQ file(s)
*/
process convertBam {
label 'mc_small'
tag "$bam"
when:
params.bam && params.run_convertbam
input:
file bam from ch_input_for_convertbam
output:
set val("${base}"), file("*.fastq.gz") into ch_output_from_convertbam
script:
base = "${bam.baseName}"
"""
samtools fastq -tn ${bam} | pigz -p ${task.cpus} > ${base}.converted.fastq.gz
"""
}
/*
* PREPROCESSING - Index a input BAM if not being converted to FASTQ
*/
process indexinputbam {
label 'sc_small'
tag "$prefix"
when:
params.bam && !params.run_convertbam
input:
file bam from ch_input_for_indexbam
output:
file "*.{bai,csi}" into ch_mappingindex_for_skipmapping,ch_filteringindex_for_skiprmdup
script:
size = "${params.large_ref}" ? '-c' : ''
prefix = "${bam.baseName}"
"""
samtools index "${size}" ${bam}
"""
}
// convertbam bypass
if (params.run_convertbam) {
ch_input_for_skipconvertbam.mix(ch_output_from_convertbam)
.filter{ it =~/.*converted.fastq.gz/}
.into { ch_convertbam_for_fastp; ch_convertbam_for_skipfastp; ch_convertbam_for_fastqc; ch_convertbam_for_stripfastq }
} else {
ch_input_for_skipconvertbam
.into { ch_convertbam_for_fastp; ch_convertbam_for_skipfastp; ch_convertbam_for_fastqc; ch_convertbam_for_stripfastq }
}
/*
* STEP 1a - FastQC
*/
process fastqc {
label 'sc_tiny'
tag "$name"
publishDir "${params.outdir}/FastQC/input_fastq", mode: 'copy',
saveAs: {filename -> filename.indexOf(".zip") > 0 ? "zips/$filename" : "$filename"}
when:
!params.bam && !params.skip_fastqc || params.bam && params.run_convertbam
input:
set val(name), file(reads) from ch_convertbam_for_fastqc
output:
file "*_fastqc.{zip,html}" into ch_prefastqc_for_multiqc
script:
"""
fastqc -q $reads
rename 's/_fastqc\\.zip\$/_raw_fastqc.zip/' *_fastqc.zip
rename 's/_fastqc\\.html\$/_raw_fastqc.html/' *_fastqc.html
"""
}
/* STEP 1b - FastP
* Optional poly-G complexity filtering step before read merging/adapter clipping etc
* Note: Clipping, Merging, Quality Trimning are turned off here - we leave this to adapter removal itself!
*/
process fastp {
label 'mc_small'
tag "$name"
publishDir "${params.outdir}/FastP", mode: 'copy'
when:
!params.bam && params.complexity_filter_poly_g || params.bam && params.run_convertbam && params.complexity_filter_poly_g
input:
set val(name), file(reads) from ch_convertbam_for_fastp
output:
set val(name), file("*pG.fq.gz") into ch_output_from_fastp
file("*.json") into ch_fastp_for_multiqc
script:
if(params.single_end){
"""
fastp --in1 ${reads[0]} --out1 "${reads[0].baseName}.pG.fq.gz" -A -g --poly_g_min_len "${params.complexity_filter_poly_g_min}" -Q -L -w ${task.cpus} --json "${reads[0].baseName}"_fastp.json
"""
} else {
"""
fastp --in1 ${reads[0]} --in2 ${reads[1]} --out1 "${reads[0].baseName}.pG.fq.gz" --out2 "${reads[1].baseName}.pG.fq.gz" -A -g --poly_g_min_len "${params.complexity_filter_poly_g_min}" -Q -L -w ${task.cpus} --json "${reads[0].baseName}"_fastp.json
"""
}
}
// fastp bypass
if (params.complexity_filter_poly_g) {
ch_convertbam_for_skipfastp.mix(ch_output_from_fastp)
.filter { it =~/.*pG.fq.gz/ }
.into { ch_fastp_for_adapterremoval; ch_fastp_for_skipadapterremoval }
} else {
ch_convertbam_for_skipfastp
.into { ch_fastp_for_adapterremoval; ch_fastp_for_skipadapterremoval }
}
/*
* STEP 2 - Adapter Clipping / Read Merging
*/
process adapter_removal {
label 'mc_small'
tag "$name"
publishDir "${params.outdir}/read_merging", mode: 'copy'
when:
!params.bam && !params.skip_adapterremoval || params.bam && params.run_convertbam && !params.skip_adapterremoval
input:
set val(name), file(reads) from ch_fastp_for_adapterremoval
output:
set val(base), file("output/*.gz") into ch_output_from_adapterremoval, ch_adapterremoval_for_postfastqc
file("output/*.settings") into ch_adapterremoval_logs
script:
base = reads[0].baseName
//This checks whether we skip trimming and defines a variable respectively
trim_me = params.skip_trim ? '' : "--trimns --trimqualities --adapter1 ${params.clip_forward_adaptor} --adapter2 ${params.clip_reverse_adaptor} --minlength ${params.clip_readlength} --minquality ${params.clip_min_read_quality} --minadapteroverlap ${params.min_adap_overlap}"
collapse_me = params.skip_collapse ? '' : '--collapse'
preserve5p = params.preserve5p ? '--preserve5p' : ''
mergedonly = params.mergedonly ? "Y" : "N"
//PE mode, dependent on trim_me and collapse_me the respective procedure is run or not :-)
if (!params.single_end && !params.skip_collapse && !params.skip_trim){
"""
mkdir -p output
AdapterRemoval --file1 ${reads[0]} --file2 ${reads[1]} --basename ${base} ${trim_me} --gzip --threads ${task.cpus} ${collapse_me} ${preserve5p}
#Combine files
if [ ${preserve5p} = "--preserve5p" ] && [ ${mergedonly} = "N" ]; then
cat *.collapsed.gz *.singleton.truncated.gz *.pair1.truncated.gz *.pair2.truncated.gz > output/${base}.combined.fq.gz
elif [ ${preserve5p} = "--preserve5p" ] && [ ${mergedonly} = "Y" ] ; then
cat *.collapsed.gz > output/${base}.combined.fq.gz
elif [ ${mergedonly} = "Y" ] ; then
cat *.collapsed.gz *.collapsed.truncated.gz > output/${base}.combined.fq.gz
else
cat *.collapsed.gz *.collapsed.truncated.gz *.singleton.truncated.gz *.pair1.truncated.gz *.pair2.truncated.gz > output/${base}.combined.fq.gz
fi
mv *.settings output/
"""
//PE, don't collapse, but trim reads
} else if (!params.single_end && params.skip_collapse && !params.skip_trim) {
"""
mkdir -p output
AdapterRemoval --file1 ${reads[0]} --file2 ${reads[1]} --basename ${base} --gzip --threads ${task.cpus} ${trim_me} ${collapse_me} ${preserve5p}
mv *.settings ${base}.pair*.truncated.gz output/
"""
//PE, collapse, but don't trim reads
} else if (!params.single_end && !params.skip_collapse && params.skip_trim) {
"""
mkdir -p output
AdapterRemoval --file1 ${reads[0]} --file2 ${reads[1]} --basename ${base} --gzip --threads ${task.cpus} --basename ${base} ${collapse_me} ${trim_me}
if [ ${mergedonly} = "Y" ]; then
cat *.collapsed.gz *.collapsed.truncated.gz > output/${base}.combined.fq.gz
else
cat *.collapsed.gz *.collapsed.truncated.gz *.singleton.truncated.gz *.pair1.truncated.gz *.pair2.truncated.gz > output/${base}.combined.fq.gz
fi
mv *.settings output/
"""
} else {
//SE, collapse not possible, trim reads
"""
mkdir -p output
AdapterRemoval --file1 ${reads[0]} --basename ${base} --gzip --threads ${task.cpus} ${trim_me} ${preserve5p}
mv *.settings *.truncated.gz output/
"""
}
}
// Adapterremoval bypass
if (!params.skip_adapterremoval) {
ch_output_from_adapterremoval.mix(ch_fastp_for_skipadapterremoval)
.filter { it =~/.*combined.fq.gz|.*truncated.gz/ }
.into { ch_adapterremoval_for_fastqc_after_clipping; ch_adapterremoval_for_skipmap; ch_adapteremoval_for_bwa; ch_adapteremoval_for_cm; ch_adapteremoval_for_bwamem }
} else {
ch_fastp_for_skipadapterremoval
.into { ch_adapterremoval_for_fastqc_after_clipping; ch_adapterremoval_for_skipmap; ch_adapteremoval_for_bwa; ch_adapteremoval_for_cm; ch_adapteremoval_for_bwamem; }
}
/*
* STEP 2b - FastQC after clipping/merging (if applied!)
*/
process fastqc_after_clipping {
label 'sc_tiny'
tag "${name}"
publishDir "${params.outdir}/FastQC/after_clipping", mode: 'copy',
saveAs: {filename -> filename.indexOf(".zip") > 0 ? "zips/$filename" : "$filename"}
when: !params.bam && !params.skip_adapterremoval && !params.skip_fastqc || params.bam && params.run_convertbam && !params.skip_adapterremoval && !params.skip_fastqc
input:
set val(name), file(reads) from ch_adapterremoval_for_fastqc_after_clipping
output: