forked from nf-core/methylseq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.nf
1165 lines (1030 loc) · 48 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/methylseq
========================================================================================
nf-core/methylseq Analysis Pipeline.
#### Homepage / Documentation
https://github.com/nf-core/methylseq
----------------------------------------------------------------------------------------
*/
def helpMessage() {
log.info nfcoreHeader()
log.info"""
Usage:
The typical command for running the pipeline is as follows:
nextflow run nf-core/methylseq --reads '*_R{1,2}.fastq.gz' -profile docker
Mandatory arguments:
--aligner [str] Alignment tool to use (default: bismark)
Available: bismark, bismark_hisat, bwameth
--reads [path] Path to input data (must be surrounded with quotes)
-profile [str] Configuration profile to use. Can use multiple (comma separated)
Available: conda, docker, singularity, awsbatch, test and more.
Options:
--genome [str] Name of iGenomes reference
--single_end [bool] Specifies that the input is single end reads
--comprehensive [bool] Output information for all cytosine contexts
--ignore_flags [bool] Run MethylDackel with the flag to ignore SAM flags.
--meth_cutoff [int] Specify a minimum read coverage to report a methylation call during Bismark's bismark_methylation_extractor step.
--min_depth [int] Specify a minimum read coverage for MethylDackel to report a methylation call.
--methyl_kit [bool] Run MethylDackel with the --methyl_kit flag to produce files suitable for use with the methylKit R package.
--skip_deduplication [bool] Skip deduplication step after alignment. This is turned on automatically if --rrbs is specified
--non_directional [bool] Run alignment against all four possible strands
--save_align_intermeds [bool] Save aligned intermediates to results directory
--save_trimmed [bool] Save trimmed reads to results directory
--unmapped [bool] Save unmapped reads to fastq files
--relax_mismatches [bool] Turn on to relax stringency for alignment (set allowed penalty with --num_mismatches)
--num_mismatches [float] 0.6 will allow a penalty of bp * -0.6 - for 100bp reads (bismark default is 0.2)
--known_splices [file] Supply a .gtf file containing known splice sites (bismark_hisat only)
--slamseq [bool] Run bismark in SLAM-seq mode
--local_alignment [bool] Allow soft-clipping of reads (potentially useful for single-cell experiments)
References If not specified in the configuration file or you wish to overwrite any of the references.
--fasta [file] Path to Fasta reference
--fasta_index [path] Path to Fasta Index
--bismark_index [path] Path to Bismark index
--bwa_meth_index [path] Path to bwameth index
--save_reference [bool] Save reference(s) to results directory
Trimming options:
--skip_trimming [bool] Skip read trimming
--clip_r1 [int] Trim the specified number of bases from the 5' end of read 1 (or single-end reads).
--clip_r2 [int] Trim the specified number of bases from the 5' end of read 2 (paired-end only).
--three_prime_clip_r1 [int] Trim the specified number of bases from the 3' end of read 1 AFTER adapter/quality trimming
--three_prime_clip_r2 [int] Trim the specified number of bases from the 3' end of read 2 AFTER adapter/quality trimming
--rrbs [bool] Turn on if dealing with MspI digested material.
Trimming presets:
--pbat [bool]
--single_cell [bool]
--epignome [bool]
--accell [bool]
--zymo [bool]
--cegx [bool]
Other options:
--outdir [path] The output directory where the results will be saved
--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.
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
""".stripIndent()
}
// Show help message
if (params.help) {
helpMessage()
exit 0
}
// Validate inputs
assert params.aligner == 'bwameth' || params.aligner == 'bismark' || params.aligner == 'bismark_hisat' : "Invalid aligner option: ${params.aligner}. Valid options: 'bismark', 'bwameth', 'bismark_hisat'"
/*
* SET UP CONFIGURATION VARIABLES
*/
// Check if genome exists in the config file
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(", ")}"
}
Channel
.fromPath("$baseDir/assets/where_are_my_files.txt", checkIfExists: true)
.into { ch_wherearemyfiles_for_trimgalore; ch_wherearemyfiles_for_alignment }
ch_splicesites_for_bismark_hisat_align = params.known_splices ? Channel.fromPath("${params.known_splices}", checkIfExists: true).collect() : file('null')
if( params.aligner =~ /bismark/ ){
assert params.bismark_index || params.fasta : "No reference genome index or fasta file specified"
ch_wherearemyfiles_for_alignment.set { ch_wherearemyfiles_for_bismark_align }
if( params.bismark_index ){
Channel
.fromPath(params.bismark_index, checkIfExists: true)
.ifEmpty { exit 1, "Bismark index file not found: ${params.bismark_index}" }
.set { ch_bismark_index_for_bismark_align }
}
else if( params.fasta ){
Channel
.fromPath(params.fasta, checkIfExists: true)
.ifEmpty { exit 1, "fasta file not found : ${params.fasta}" }
.set { ch_fasta_for_makeBismarkIndex }
}
}
else if( params.aligner == 'bwameth' ){
assert params.fasta : "No Fasta reference specified! This is required by MethylDackel."
ch_wherearemyfiles_for_alignment.into { ch_wherearemyfiles_for_bwamem_align; ch_wherearemyfiles_for_samtools_sort_index_flagstat }
Channel
.fromPath(params.fasta, checkIfExists: true)
.ifEmpty { exit 1, "fasta file not found : ${params.fasta}" }
.into { ch_fasta_for_makeBwaMemIndex; ch_fasta_for_makeFastaIndex; ch_fasta_for_methyldackel }
if( params.bwa_meth_index ){
Channel
.fromPath("${params.bwa_meth_index}*", checkIfExists: true)
.ifEmpty { exit 1, "bwa-meth index file(s) not found: ${params.bwa_meth_index}" }
.set { ch_bwa_meth_indices_for_bwamem_align }
ch_fasta_for_makeBwaMemIndex.close()
}
if( params.fasta_index ){
Channel
.fromPath(params.fasta_index, checkIfExists: true)
.ifEmpty { exit 1, "fasta index file not found: ${params.fasta_index}" }
.set { ch_fasta_index_for_methyldackel }
ch_fasta_for_makeFastaIndex.close()
}
}
if( workflow.profile == 'uppmax' || workflow.profile == 'uppmax_devel' ){
if( !params.project ) exit 1, "No UPPMAX project ID found! Use --project"
}
// 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
}
// Library prep presets
params.rrbs = false
params.pbat = false
params.single_cell = false
params.epignome = false
params.accel = false
params.zymo = false
params.cegx = false
if(params.pbat){
params.clip_r1 = 9
params.clip_r2 = 9
params.three_prime_clip_r1 = 9
params.three_prime_clip_r2 = 9
}
else if( params.single_cell ){
params.clip_r1 = 6
params.clip_r2 = 6
params.three_prime_clip_r1 = 6
params.three_prime_clip_r2 = 6
}
else if( params.epignome ){
params.clip_r1 = 8
params.clip_r2 = 8
params.three_prime_clip_r1 = 8
params.three_prime_clip_r2 = 8
}
else if( params.accel || params.zymo ){
params.clip_r1 = 10
params.clip_r2 = 15
params.three_prime_clip_r1 = 10
params.three_prime_clip_r2 = 10
}
else if( params.cegx ){
params.clip_r1 = 6
params.clip_r2 = 6
params.three_prime_clip_r1 = 2
params.three_prime_clip_r2 = 2
} else {
params.clip_r1 = 0
params.clip_r2 = 0
params.three_prime_clip_r1 = 0
params.three_prime_clip_r2 = 0
}
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(params.multiqc_config, checkIfExists: true)
ch_output_docs = file("$baseDir/docs/output.md", checkIfExists: true)
/*
* Create a channel for input read files
*/
if (params.readPaths) {
if (params.single_end) {
Channel
.from(params.readPaths)
.map { row -> [ row[0], [ file(row[1][0], checkIfExists: true) ] ] }
.ifEmpty { exit 1, "params.readPaths was empty - no input files supplied" }
.into { ch_read_files_for_fastqc; ch_read_files_for_trim_galore }
} else {
Channel
.from(params.readPaths)
.map { row -> [ row[0], [ file(row[1][0], checkIfExists: true), file(row[1][1], checkIfExists: true) ] ] }
.ifEmpty { exit 1, "params.readPaths was empty - no input files supplied" }
.into { ch_read_files_for_fastqc; ch_read_files_for_trim_galore }
}
} else {
Channel
.fromFilePairs( params.reads, size: params.single_end ? 1 : 2 )
.ifEmpty { exit 1, "Cannot find any reads matching: ${params.reads}\nNB: Path needs to be enclosed in quotes!\nIf this is single-end data, please specify --single_end on the command line." }
.into { ch_read_files_for_fastqc; ch_read_files_for_trim_galore }
}
// Header log info
log.info nfcoreHeader()
def summary = [:]
if (workflow.revision) summary['Pipeline Release'] = workflow.revision
summary['Pipeline Name'] = 'nf-core/methylseq'
summary['Run Name'] = custom_runName ?: workflow.runName
summary['Reads'] = params.reads
summary['Aligner'] = params.aligner
summary['Spliced alignment'] = params.known_splices ? 'Yes' : 'No'
summary['SLAM-seq'] = params.slamseq ? 'Yes' : 'No'
summary['Local alignment'] = params.local_alignment ? 'Yes' : 'No'
summary['Data Type'] = params.single_end ? 'Single-End' : 'Paired-End'
summary['Genome'] = params.genome
if( params.bismark_index ) summary['Bismark Index'] = params.bismark_index
if( params.bwa_meth_index ) summary['BWA-Meth Index'] = "${params.bwa_meth_index}*"
if( params.fasta ) summary['Fasta Ref'] = params.fasta
if( params.fasta_index ) summary['Fasta Index'] = params.fasta_index
if( params.rrbs ) summary['RRBS Mode'] = 'On'
if( params.relax_mismatches ) summary['Mismatch Func'] = "L,0,-${params.num_mismatches} (Bismark default = L,0,-0.2)"
if( params.skip_trimming ) summary['Trimming Step'] = 'Skipped'
if( params.pbat ) summary['Trim Profile'] = 'PBAT'
if( params.single_cell ) summary['Trim Profile'] = 'Single Cell'
if( params.epignome ) summary['Trim Profile'] = 'TruSeq (EpiGnome)'
if( params.accel ) summary['Trim Profile'] = 'Accel-NGS (Swift)'
if( params.zymo ) summary['Trim Profile'] = 'Zymo Pico-Methyl'
if( params.cegx ) summary['Trim Profile'] = 'CEGX'
summary['Trim R1'] = params.clip_r1
summary['Trim R2'] = params.clip_r2
summary["Trim 3' R1"] = params.three_prime_clip_r1
summary["Trim 3' R2"] = params.three_prime_clip_r2
summary['Deduplication'] = params.skip_deduplication || params.rrbs ? 'No' : 'Yes'
summary['Directional Mode'] = params.single_cell || params.zymo || params.non_directional ? 'No' : 'Yes'
summary['All C Contexts'] = params.comprehensive ? 'Yes' : 'No'
if( params.min_depth ) summary['Minimum Depth'] = params.min_depth
if( params.ignore_flags ) summary['MethylDackel'] = 'Ignoring SAM Flags'
if( params.methyl_kit ) summary['MethylDackel'] = 'Producing methyl_kit output'
summary['Save Reference'] = params.save_reference ? 'Yes' : 'No'
summary['Save Trimmed'] = params.save_trimmed ? 'Yes' : 'No'
summary['Save Unmapped'] = params.unmapped ? 'Yes' : 'No'
summary['Save Intermediates'] = params.save_align_intermeds ? 'Yes' : 'No'
summary['Current home'] = "$HOME"
summary['Current path'] = "$PWD"
if( params.project ) summary['UPPMAX Project'] = params.project
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['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()
def create_workflow_summary(summary) {
def yaml_file = workDir.resolve('workflow_summary_mqc.yaml')
yaml_file.text = """
id: 'nf-core-methylseq-summary'
description: " - this information is collected when the pipeline is started."
section_name: 'nf-core/methylseq Workflow Summary'
section_href: 'https://github.com/nf-core/methylseq'
plot_type: 'html'
data: |
<dl class=\"dl-horizontal\">
${summary.collect { k,v -> " <dt>$k</dt><dd><samp>${v ?: '<span style=\"color:#999999;\">N/A</a>'}</samp></dd>" }.join("\n")}
</dl>
""".stripIndent()
return yaml_file
}
/*
* Parse software version numbers
*/
process get_software_versions {
publishDir "${params.outdir}/pipeline_info", mode: 'copy',
saveAs: { filename ->
if (filename.indexOf(".csv") > 0) filename
else null
}
output:
file 'software_versions_mqc.yaml' into ch_software_versions_yaml_for_multiqc
file "software_versions.csv"
script:
"""
echo "$workflow.manifest.version" &> v_ngi_methylseq.txt
echo "$workflow.nextflow.version" &> v_nextflow.txt
bismark_genome_preparation --version &> v_bismark_genome_preparation.txt
fastqc --version &> v_fastqc.txt
cutadapt --version &> v_cutadapt.txt
trim_galore --version &> v_trim_galore.txt
bismark --version &> v_bismark.txt
deduplicate_bismark --version &> v_deduplicate_bismark.txt
bismark_methylation_extractor --version &> v_bismark_methylation_extractor.txt
bismark2report --version &> v_bismark2report.txt
bismark2summary --version &> v_bismark2summary.txt
samtools --version &> v_samtools.txt
hisat2 --version &> v_hisat2.txt
bwa &> v_bwa.txt 2>&1 || true
bwameth.py --version &> v_bwameth.txt
picard MarkDuplicates --version &> v_picard_markdups.txt 2>&1 || true
MethylDackel --version &> v_methyldackel.txt
qualimap --version &> v_qualimap.txt || true
preseq &> v_preseq.txt
multiqc --version &> v_multiqc.txt
scrape_software_versions.py &> software_versions_mqc.yaml
"""
}
/*
* PREPROCESSING - Build Bismark index
*/
if( !params.bismark_index && params.aligner =~ /bismark/ ){
process makeBismarkIndex {
publishDir path: { params.save_reference ? "${params.outdir}/reference_genome" : params.outdir },
saveAs: { params.save_reference ? it : null }, mode: 'copy'
input:
file fasta from ch_fasta_for_makeBismarkIndex
output:
file "BismarkIndex" into ch_bismark_index_for_bismark_align
script:
aligner = params.aligner == 'bismark_hisat' ? '--hisat2' : '--bowtie2'
slam = params.slamseq ? '--slam' : ''
"""
mkdir BismarkIndex
cp $fasta BismarkIndex/
bismark_genome_preparation $aligner $slam BismarkIndex
"""
}
}
/*
* PREPROCESSING - Build bwa-mem index
*/
if( !params.bwa_meth_index && params.aligner == 'bwameth' ){
process makeBwaMemIndex {
tag "$fasta"
publishDir path: "${params.outdir}/reference_genome", saveAs: { params.save_reference ? it : null }, mode: 'copy'
input:
file fasta from ch_fasta_for_makeBwaMemIndex
output:
file "${fasta}*" into ch_bwa_meth_indices_for_bwamem_align
script:
"""
bwameth.py index $fasta
"""
}
}
/*
* PREPROCESSING - Index Fasta file
*/
if( !params.fasta_index && params.aligner == 'bwameth' ){
process makeFastaIndex {
tag "$fasta"
publishDir path: "${params.outdir}/reference_genome", saveAs: { params.save_reference ? it : null }, mode: 'copy'
input:
file fasta from ch_fasta_for_makeFastaIndex
output:
file "${fasta}.fai" into ch_fasta_index_for_methyldackel
script:
"""
samtools faidx $fasta
"""
}
}
/*
* STEP 1 - FastQC
*/
process fastqc {
tag "$name"
label 'process_medium'
publishDir "${params.outdir}/fastqc", mode: 'copy',
saveAs: { filename ->
filename.indexOf(".zip") > 0 ? "zips/$filename" : "$filename"
}
input:
set val(name), file(reads) from ch_read_files_for_fastqc
output:
file '*_fastqc.{zip,html}' into ch_fastqc_results_for_multiqc
script:
"""
fastqc --quiet --threads $task.cpus $reads
"""
}
/*
* STEP 2 - Trim Galore!
*/
if( params.skip_trimming ){
ch_trimmed_reads_for_alignment = ch_read_files_for_trim_galore
ch_trim_galore_results_for_multiqc = Channel.from(false)
} else {
process trim_galore {
tag "$name"
publishDir "${params.outdir}/trim_galore", mode: 'copy',
saveAs: {filename ->
if( filename.indexOf("_fastqc") > 0 ) "FastQC/$filename"
else if( filename.indexOf("trimming_report.txt" ) > 0) "logs/$filename"
else if( !params.save_trimmed && filename == "where_are_my_files.txt" ) filename
else if( params.save_trimmed && filename != "where_are_my_files.txt" ) filename
else null
}
input:
set val(name), file(reads) from ch_read_files_for_trim_galore
file wherearemyfiles from ch_wherearemyfiles_for_trimgalore.collect()
output:
set val(name), file('*fq.gz') into ch_trimmed_reads_for_alignment
file "*trimming_report.txt" into ch_trim_galore_results_for_multiqc
file "*_fastqc.{zip,html}"
file "where_are_my_files.txt"
script:
c_r1 = params.clip_r1 > 0 ? "--clip_r1 ${params.clip_r1}" : ''
c_r2 = params.clip_r2 > 0 ? "--clip_r2 ${params.clip_r2}" : ''
tpc_r1 = params.three_prime_clip_r1 > 0 ? "--three_prime_clip_r1 ${params.three_prime_clip_r1}" : ''
tpc_r2 = params.three_prime_clip_r2 > 0 ? "--three_prime_clip_r2 ${params.three_prime_clip_r2}" : ''
rrbs = params.rrbs ? "--rrbs" : ''
if( params.single_end ) {
"""
trim_galore --fastqc --gzip $rrbs $c_r1 $tpc_r1 $reads
"""
} else {
"""
trim_galore --paired --fastqc --gzip $rrbs $c_r1 $c_r2 $tpc_r1 $tpc_r2 $reads
"""
}
}
}
/*
* STEP 3.1 - align with Bismark
*/
if( params.aligner =~ /bismark/ ){
process bismark_align {
tag "$name"
publishDir "${params.outdir}/bismark_alignments", mode: 'copy',
saveAs: {filename ->
if( filename.indexOf(".fq.gz") > 0 ) "unmapped/$filename"
else if( filename.indexOf("report.txt") > 0 ) "logs/$filename"
else if( (!params.save_align_intermeds && !params.skip_deduplication && !params.rrbs).every() && filename == "where_are_my_files.txt" ) filename
else if( (params.save_align_intermeds || params.skip_deduplication || params.rrbs).any() && filename != "where_are_my_files.txt" ) filename
else null
}
input:
set val(name), file(reads) from ch_trimmed_reads_for_alignment
file index from ch_bismark_index_for_bismark_align.collect()
file wherearemyfiles from ch_wherearemyfiles_for_bismark_align.collect()
file knownsplices from ch_splicesites_for_bismark_hisat_align
output:
set val(name), file("*.bam") into ch_bam_for_bismark_deduplicate, ch_bam_for_bismark_summary, ch_bam_for_preseq
set val(name), file("*report.txt") into ch_bismark_align_log_for_bismark_report, ch_bismark_align_log_for_bismark_summary, ch_bismark_align_log_for_multiqc
file "*.fq.gz" optional true
file "where_are_my_files.txt"
script:
// Paired-end or single end input files
input = params.single_end ? reads : "-1 ${reads[0]} -2 ${reads[1]}"
// Choice of read aligner
aligner = params.aligner == "bismark_hisat" ? "--hisat2" : "--bowtie2"
// Optional extra bismark parameters
splicesites = params.aligner == "bismark_hisat" && knownsplices.name != 'null' ? "--known-splicesite-infile <(hisat2_extract_splice_sites.py ${knownsplices})" : ''
pbat = params.pbat ? "--pbat" : ''
non_directional = params.single_cell || params.zymo || params.non_directional ? "--non_directional" : ''
unmapped = params.unmapped ? "--unmapped" : ''
mismatches = params.relax_mismatches ? "--score_min L,0,-${params.num_mismatches}" : ''
soft_clipping = params.local_alignment ? "--local" : ''
// Try to assign sensible bismark memory units according to what the task was given
multicore = ''
if( task.cpus ){
// Numbers based on recommendation by Felix for a typical mouse genome
if( params.single_cell || params.zymo || params.non_directional ){
cpu_per_multicore = 5
mem_per_multicore = (18.GB).toBytes()
} else {
cpu_per_multicore = 3
mem_per_multicore = (13.GB).toBytes()
}
// How many multicore splits can we afford with the cpus we have?
ccore = ((task.cpus as int) / cpu_per_multicore) as int
// Check that we have enough memory, assuming 13GB memory per instance (typical for mouse alignment)
try {
tmem = (task.memory as nextflow.util.MemoryUnit).toBytes()
mcore = (tmem / mem_per_multicore) as int
ccore = Math.min(ccore, mcore)
} catch (all) {
log.debug "Warning: Not able to define bismark align multicore based on available memory"
}
if( ccore > 1 ){
multicore = "--multicore $ccore"
}
}
// Main command
"""
bismark $input \\
$aligner \\
--bam $pbat $non_directional $unmapped $mismatches $multicore \\
--genome $index \\
$reads \\
$soft_clipping \\
$splicesites
"""
}
/*
* STEP 4 - Bismark deduplicate
*/
if( params.skip_deduplication || params.rrbs ) {
ch_bam_for_bismark_deduplicate.into { ch_bam_dedup_for_bismark_methXtract; ch_bam_dedup_for_qualimap }
ch_bismark_dedup_log_for_bismark_report = Channel.from(false)
ch_bismark_dedup_log_for_bismark_summary = Channel.from(false)
ch_bismark_dedup_log_for_multiqc = Channel.from(false)
} else {
process bismark_deduplicate {
tag "$name"
publishDir "${params.outdir}/bismark_deduplicated", mode: 'copy',
saveAs: {filename -> filename.indexOf(".bam") == -1 ? "logs/$filename" : "$filename"}
input:
set val(name), file(bam) from ch_bam_for_bismark_deduplicate
output:
set val(name), file("*.deduplicated.bam") into ch_bam_dedup_for_bismark_methXtract, ch_bam_dedup_for_qualimap
set val(name), file("*.deduplication_report.txt") into ch_bismark_dedup_log_for_bismark_report, ch_bismark_dedup_log_for_bismark_summary, ch_bismark_dedup_log_for_multiqc
script:
fq_type = params.single_end ? '-s' : '-p'
"""
deduplicate_bismark $fq_type --bam $bam
"""
}
}
/*
* STEP 5 - Bismark methylation extraction
*/
process bismark_methXtract {
tag "$name"
publishDir "${params.outdir}/bismark_methylation_calls", mode: 'copy',
saveAs: {filename ->
if( filename.indexOf("splitting_report.txt" ) > 0 ) "logs/$filename"
else if( filename.indexOf("M-bias" ) > 0) "m-bias/$filename"
else if( filename.indexOf(".cov" ) > 0 ) "methylation_coverage/$filename"
else if( filename.indexOf("bedGraph" ) > 0 ) "bedGraph/$filename"
else "methylation_calls/$filename"
}
input:
set val(name), file(bam) from ch_bam_dedup_for_bismark_methXtract
output:
set val(name), file("*splitting_report.txt") into ch_bismark_splitting_report_for_bismark_report, ch_bismark_splitting_report_for_bismark_summary, ch_bismark_splitting_report_for_multiqc
set val(name), file("*.M-bias.txt") into ch_bismark_mbias_for_bismark_report, ch_bismark_mbias_for_bismark_summary, ch_bismark_mbias_for_multiqc
file '*.{png,gz}'
script:
comprehensive = params.comprehensive ? '--comprehensive --merge_non_CpG' : ''
meth_cutoff = params.meth_cutoff ? "--cutoff ${params.meth_cutoff}" : ''
multicore = ''
if( task.cpus ){
// Numbers based on Bismark docs
ccore = ((task.cpus as int) / 10) as int
if( ccore > 1 ){
multicore = "--multicore $ccore"
}
}
buffer = ''
if( task.memory ){
mbuffer = (task.memory as nextflow.util.MemoryUnit) - 2.GB
// only set if we have more than 6GB available
if( mbuffer.compareTo(4.GB) == 1 ){
buffer = "--buffer_size ${mbuffer.toGiga()}G"
}
}
if(params.single_end) {
"""
bismark_methylation_extractor $comprehensive $meth_cutoff \\
$multicore $buffer \\
--bedGraph \\
--counts \\
--gzip \\
-s \\
--report \\
$bam
"""
} else {
"""
bismark_methylation_extractor $comprehensive $meth_cutoff \\
$multicore $buffer \\
--ignore_r2 2 \\
--ignore_3prime_r2 2 \\
--bedGraph \\
--counts \\
--gzip \\
-p \\
--no_overlap \\
--report \\
$bam
"""
}
}
ch_bismark_align_log_for_bismark_report
.join(ch_bismark_dedup_log_for_bismark_report)
.join(ch_bismark_splitting_report_for_bismark_report)
.join(ch_bismark_mbias_for_bismark_report)
.set{ ch_bismark_logs_for_bismark_report }
/*
* STEP 6 - Bismark Sample Report
*/
process bismark_report {
tag "$name"
publishDir "${params.outdir}/bismark_reports", mode: 'copy'
input:
set val(name), file(align_log), file(dedup_log), file(splitting_report), file(mbias) from ch_bismark_logs_for_bismark_report
output:
file '*{html,txt}' into ch_bismark_reports_results_for_multiqc
script:
"""
bismark2report \\
--alignment_report $align_log \\
--dedup_report $dedup_log \\
--splitting_report $splitting_report \\
--mbias_report $mbias
"""
}
/*
* STEP 7 - Bismark Summary Report
*/
process bismark_summary {
publishDir "${params.outdir}/bismark_summary", mode: 'copy'
input:
file ('*') from ch_bam_for_bismark_summary.collect()
file ('*') from ch_bismark_align_log_for_bismark_summary.collect()
file ('*') from ch_bismark_dedup_log_for_bismark_summary.collect()
file ('*') from ch_bismark_splitting_report_for_bismark_summary.collect()
file ('*') from ch_bismark_mbias_for_bismark_summary.collect()
output:
file '*{html,txt}' into ch_bismark_summary_results_for_multiqc
script:
"""
bismark2summary
"""
}
} // End of bismark processing block
else {
ch_bismark_align_log_for_multiqc = Channel.from(false)
ch_bismark_dedup_log_for_multiqc = Channel.from(false)
ch_bismark_splitting_report_for_multiqc = Channel.from(false)
ch_bismark_mbias_for_multiqc = Channel.from(false)
ch_bismark_reports_results_for_multiqc = Channel.from(false)
ch_bismark_summary_results_for_multiqc = Channel.from(false)
}
/*
* Process with bwa-mem and assorted tools
*/
if( params.aligner == 'bwameth' ){
process bwamem_align {
tag "$name"
publishDir "${params.outdir}/bwa-mem_alignments", mode: 'copy',
saveAs: {filename ->
if( !params.save_align_intermeds && filename == "where_are_my_files.txt" ) filename
else if( params.save_align_intermeds && filename != "where_are_my_files.txt" ) filename
else null
}
input:
set val(name), file(reads) from ch_trimmed_reads_for_alignment
file bwa_meth_indices from ch_bwa_meth_indices_for_bwamem_align.collect()
file wherearemyfiles from ch_wherearemyfiles_for_bwamem_align.collect()
output:
set val(name), file('*.bam') into ch_bam_for_samtools_sort_index_flagstat, ch_bam_for_preseq
file "where_are_my_files.txt"
script:
fasta = bwa_meth_indices[0].toString() - '.bwameth' - '.c2t' - '.amb' - '.ann' - '.bwt' - '.pac' - '.sa'
prefix = reads[0].toString() - ~/(_R1)?(_trimmed)?(_val_1)?(\.fq)?(\.fastq)?(\.gz)?$/
"""
bwameth.py \\
--threads ${task.cpus} \\
--reference $fasta \\
$reads | samtools view -bS - > ${prefix}.bam
"""
}
/*
* STEP 4.- samtools flagstat on samples
*/
process samtools_sort_index_flagstat {
tag "$name"
publishDir "${params.outdir}/bwa-mem_alignments", mode: 'copy',
saveAs: {filename ->
if(filename.indexOf("report.txt") > 0) "logs/$filename"
else if( (!params.save_align_intermeds && !params.skip_deduplication && !params.rrbs).every() && filename == "where_are_my_files.txt") filename
else if( (params.save_align_intermeds || params.skip_deduplication || params.rrbs).any() && filename != "where_are_my_files.txt") filename
else null
}
input:
set val(name), file(bam) from ch_bam_for_samtools_sort_index_flagstat
file wherearemyfiles from ch_wherearemyfiles_for_samtools_sort_index_flagstat.collect()
output:
set val(name), file("${bam.baseName}.sorted.bam") into ch_bam_sorted_for_markDuplicates
file "${bam.baseName}.sorted.bam.bai" into ch_bam_index
file "${bam.baseName}_flagstat_report.txt" into ch_flagstat_results_for_multiqc
file "${bam.baseName}_stats_report.txt" into ch_samtools_stats_results_for_multiqc
file "where_are_my_files.txt"
script:
def avail_mem = task.memory ? ((task.memory.toGiga() - 6) / task.cpus).trunc() : false
def sort_mem = avail_mem && avail_mem > 2 ? "-m ${avail_mem}G" : ''
"""
samtools sort $bam \\
-@ ${task.cpus} $sort_mem \\
-o ${bam.baseName}.sorted.bam
samtools index ${bam.baseName}.sorted.bam
samtools flagstat ${bam.baseName}.sorted.bam > ${bam.baseName}_flagstat_report.txt
samtools stats ${bam.baseName}.sorted.bam > ${bam.baseName}_stats_report.txt
"""
}
/*
* STEP 5 - Mark duplicates
*/
if( params.skip_deduplication || params.rrbs ) {
ch_bam_sorted_for_markDuplicates.into { ch_bam_dedup_for_methyldackel; ch_bam_dedup_for_qualimap }
ch_bam_index.set { ch_bam_index_for_methyldackel }
ch_markDups_results_for_multiqc = Channel.from(false)
} else {
process markDuplicates {
tag "$name"
publishDir "${params.outdir}/bwa-mem_markDuplicates", mode: 'copy',
saveAs: {filename -> filename.indexOf(".bam") == -1 ? "logs/$filename" : "$filename"}
input:
set val(name), file(bam) from ch_bam_sorted_for_markDuplicates
output:
set val(name), file("${bam.baseName}.markDups.bam") into ch_bam_dedup_for_methyldackel, ch_bam_dedup_for_qualimap
file "${bam.baseName}.markDups.bam.bai" into ch_bam_index_for_methyldackel //ToDo check if this correctly overrides the original channel
file "${bam.baseName}.markDups_metrics.txt" into ch_markDups_results_for_multiqc
script:
if( !task.memory ){
log.info "[Picard MarkDuplicates] Available memory not known - defaulting to 3GB. Specify process memory requirements to change this."
avail_mem = 3
} else {
avail_mem = task.memory.toGiga()
}
"""
picard -Xmx${avail_mem}g MarkDuplicates \\
INPUT=$bam \\
OUTPUT=${bam.baseName}.markDups.bam \\
METRICS_FILE=${bam.baseName}.markDups_metrics.txt \\
REMOVE_DUPLICATES=false \\
ASSUME_SORTED=true \\
PROGRAM_RECORD_ID='null' \\
VALIDATION_STRINGENCY=LENIENT
samtools index ${bam.baseName}.markDups.bam
"""
}
}
/*
* STEP 6 - extract methylation with MethylDackel
*/
process methyldackel {
tag "$name"
publishDir "${params.outdir}/MethylDackel", mode: 'copy'
input:
set val(name), file(bam) from ch_bam_dedup_for_methyldackel
file bam_index from ch_bam_index_for_methyldackel
file fasta from ch_fasta_for_methyldackel
file fasta_index from ch_fasta_index_for_methyldackel
output:
file "${bam.baseName}*" into ch_methyldackel_results_for_multiqc
script:
all_contexts = params.comprehensive ? '--CHG --CHH' : ''
min_depth = params.min_depth > 0 ? "--minDepth ${params.min_depth}" : ''
ignore_flags = params.ignore_flags ? "--ignoreFlags" : ''
methyl_kit = params.methyl_kit ? "--methylKit" : ''
"""
MethylDackel extract $all_contexts $ignore_flags $methyl_kit $min_depth $fasta $bam
MethylDackel mbias $all_contexts $ignore_flags $fasta $bam ${bam.baseName} --txt > ${bam.baseName}_methyldackel.txt
"""
}
} // end of bwa-meth if block
else {
ch_flagstat_results_for_multiqc = Channel.from(false)
ch_samtools_stats_results_for_multiqc = Channel.from(false)
ch_markDups_results_for_multiqc = Channel.from(false)
ch_methyldackel_results_for_multiqc = Channel.from(false)
}
/*
* STEP 8 - Qualimap
*/
process qualimap {
tag "$name"
publishDir "${params.outdir}/qualimap", mode: 'copy'
input:
set val(name), file(bam) from ch_bam_dedup_for_qualimap
output:
file "${bam.baseName}_qualimap" into ch_qualimap_results_for_multiqc
script:
gcref = params.genome.toString().startsWith('GRCh') ? '-gd HUMAN' : ''
gcref = params.genome.toString().startsWith('GRCm') ? '-gd MOUSE' : ''
def avail_mem = task.memory ? ((task.memory.toGiga() - 6) / task.cpus).trunc() : false
def sort_mem = avail_mem && avail_mem > 2 ? "-m ${avail_mem}G" : ''
"""
samtools sort $bam \\
-@ ${task.cpus} $sort_mem \\
-o ${bam.baseName}.sorted.bam
qualimap bamqc $gcref \\
-bam ${bam.baseName}.sorted.bam \\
-outdir ${bam.baseName}_qualimap \\
--collect-overlap-pairs \\
--java-mem-size=${task.memory.toGiga()}G \\
-nt ${task.cpus}
"""
}
/*
* STEP 9 - preseq
*/
process preseq {
tag "$name"
publishDir "${params.outdir}/preseq", mode: 'copy'
input:
set val(name), file(bam) from ch_bam_for_preseq
output:
file "${bam.baseName}.ccurve.txt" into preseq_results
script:
def avail_mem = task.memory ? ((task.memory.toGiga() - 6) / task.cpus).trunc() : false
def sort_mem = avail_mem && avail_mem > 2 ? "-m ${avail_mem}G" : ''
"""
samtools sort $bam \\
-@ ${task.cpus} $sort_mem \\
-o ${bam.baseName}.sorted.bam
preseq lc_extrap -v -B ${bam.baseName}.sorted.bam -o ${bam.baseName}.ccurve.txt
"""
}
/*
* STEP 10 - MultiQC
*/
process multiqc {
publishDir "${params.outdir}/MultiQC", mode: 'copy'
input:
file multiqc_config from ch_multiqc_config
file ('fastqc/*') from ch_fastqc_results_for_multiqc.collect().ifEmpty([])
file ('trimgalore/*') from ch_trim_galore_results_for_multiqc.collect().ifEmpty([])
file ('bismark/*') from ch_bismark_align_log_for_multiqc.collect().ifEmpty([])
file ('bismark/*') from ch_bismark_dedup_log_for_multiqc.collect().ifEmpty([])
file ('bismark/*') from ch_bismark_splitting_report_for_multiqc.collect().ifEmpty([])
file ('bismark/*') from ch_bismark_mbias_for_multiqc.collect().ifEmpty([])
file ('bismark/*') from ch_bismark_reports_results_for_multiqc.collect().ifEmpty([])
file ('bismark/*') from ch_bismark_summary_results_for_multiqc.collect().ifEmpty([])
file ('samtools/*') from ch_flagstat_results_for_multiqc.flatten().collect().ifEmpty([])
file ('samtools/*') from ch_samtools_stats_results_for_multiqc.flatten().collect().ifEmpty([])
file ('picard/*') from ch_markDups_results_for_multiqc.flatten().collect().ifEmpty([])
file ('methyldackel/*') from ch_methyldackel_results_for_multiqc.flatten().collect().ifEmpty([])
file ('qualimap/*') from ch_qualimap_results_for_multiqc.collect().ifEmpty([])
file ('preseq/*') from preseq_results.collect().ifEmpty([])
file ('software_versions/*') from ch_software_versions_yaml_for_multiqc.collect()
file workflow_summary from create_workflow_summary(summary)
output:
file "*multiqc_report.html" into ch_multiqc_report
file "*_data"
file "multiqc_plots"
script:
rtitle = custom_runName ? "--title \"$custom_runName\"" : ''
rfilename = custom_runName ? "--filename " + custom_runName.replaceAll('\\W','_').replaceAll('_+','_') + "_multiqc_report" : ''
"""
multiqc -f $rtitle $rfilename --config $multiqc_config . \\
-m custom_content -m picard -m qualimap -m bismark -m samtools -m preseq -m cutadapt -m fastqc
"""
}
/*
* STEP 11 - Output Description HTML
*/
process output_documentation {
publishDir "${params.outdir}/pipeline_info", mode: 'copy'
input:
file output_docs from ch_output_docs
output: