forked from nf-core/sarek
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.nf
3523 lines (2798 loc) · 128 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/sarek
================================================================================
Started March 2016.
Ported to nf-core May 2019.
--------------------------------------------------------------------------------
nf-core/sarek:
An open-source analysis pipeline to detect germline or somatic variants
from whole genome or targeted sequencing
--------------------------------------------------------------------------------
@Homepage
https://sarek.scilifelab.se/
--------------------------------------------------------------------------------
@Documentation
https://github.com/nf-core/sarek/README.md
--------------------------------------------------------------------------------
*/
def helpMessage() {
log.info nfcoreHeader()
log.info"""
Usage:
The typical command for running the pipeline is as follows:
nextflow run nf-core/sarek --input sample.tsv -profile docker
Mandatory arguments:
--input Path to input TSV file on mapping, recalibrate and variantcalling steps
Multiple TSV files can be specified with quotes
Works also with the path to a directory on mapping step with a single germline sample only
Alternatively, path to VCF input file on annotate step
Multiple VCF files can be specified with quotes
-profile Configuration profile to use
Can use multiple (comma separated)
Available: conda, docker, singularity, test and more
Options:
--genome Name of iGenomes reference
--noGVCF No g.vcf output from HaplotypeCaller
--noStrelkaBP Will not use Manta candidateSmallIndels for Strelka as Best Practice
--no_intervals Disable usage of intervals
--nucleotidesPerSecond To estimate interval size
Default: 1000.0
--targetBED Target BED file for targeted or whole exome sequencing
--step Specify starting step
Available: Mapping, Recalibrate, VariantCalling, Annotate
Default: Mapping
--tools Specify tools to use for variant calling:
Available: ASCAT, ControlFREEC, FreeBayes, HaplotypeCaller, GenomeChronicler
Manta, mpileup, Mutect2, Strelka, TIDDIT
and/or for annotation:
snpEff, VEP, merge
Default: None
--skipQC Specify which QC tools to skip when running Sarek
Available: all, bamQC, BCFtools, FastQC, MultiQC, samtools, vcftools, versions
Default: None
--annotateTools Specify from which tools Sarek will look for VCF files to annotate, only for step annotate
Available: HaplotypeCaller, Manta, Mutect2, Strelka, TIDDIT
Default: None
--sentieon If sentieon is available, will enable it for preprocessing, and variant calling
Adds the following tools for --tools: DNAseq, DNAscope and TNscope
--annotation_cache Enable the use of cache for annotation, to be used with --snpEff_cache and/or --vep_cache
--snpEff_cache Specity the path to snpEff cache, to be used with --annotation_cache
--vep_cache Specity the path to VEP cache, to be used with --annotation_cache
--pon panel-of-normals VCF (bgzipped, indexed). See: https://software.broadinstitute.org/gatk/documentation/tooldocs/current/org_broadinstitute_hellbender_tools_walkers_mutect_CreateSomaticPanelOfNormals.php
--pon_index index of pon panel-of-normals VCF
References If not specified in the configuration file or you wish to overwrite any of the references.
--acLoci acLoci file
--acLociGC acLoci GC file
--bwaIndex bwa indexes
If none provided, will be generated automatically from the fasta reference
--dbsnp dbsnp file
--dbsnpIndex dbsnp index
If none provided, will be generated automatically if a dbsnp file is provided
--dict dict from the fasta reference
If none provided, will be generated automatically from the fasta reference
--fasta fasta reference
--fastafai reference index
If none provided, will be generated automatically from the fasta reference
--germlineResource Germline Resource File
--germlineResourceIndex Germline Resource Index
If none provided, will be generated automatically if a germlineResource file is provided
--intervals intervals
If none provided, will be generated automatically from the fasta reference
Use --no_intervals to disable automatic generation
--knownIndels knownIndels file
--knownIndelsIndex knownIndels index
If none provided, will be generated automatically if a knownIndels file is provided
--species species for VEP
--snpeffDb snpeffDb version
--vepCacheVersion VEP Cache version
Other options:
--outdir The output directory where the results will be saved
--sequencing_center Name of sequencing center to be displayed in BAM file
--multiqc_config Specify a custom config file for MultiQC
--monochrome_logs Logs will be without colors
--email Set this parameter to your e-mail address to get a summary e-mail with details of the run sent to you when the workflow exits
--maxMultiqcEmailFileSize Theshold size for MultiQC report to be attached in notification email. If file generated by pipeline exceeds the threshold, it will not be attached (Default: 25MB)
-name Name for the pipeline run. If not specified, Nextflow will automatically generate a random mnemonic
AWSBatch options:
--awsqueue The AWSBatch JobQueue that needs to be set when running on AWSBatch
--awsregion The AWS Region for your AWS Batch job to run on
""".stripIndent()
}
/*
* SET UP CONFIGURATION VARIABLES
*/
// Show help message
if (params.help) exit 0, helpMessage()
// Print warning message
if (params.noReports) log.warn "The params `--noReports` is deprecated -- it will be removed in a future release.\n\tPlease check: https://github.com/nf-core/sarek/blob/master/docs/usage.md#--skipQC"
if (params.annotateVCF) log.warn "The params `--annotateVCF` is deprecated -- it will be removed in a future release.\n\tPlease check: https://github.com/nf-core/sarek/blob/master/docs/usage.md#--input"
if (params.genomeDict) log.warn "The params `--genomeDict` is deprecated -- it will be removed in a future release.\n\tPlease check: https://github.com/nf-core/sarek/blob/master/docs/usage.md#--dict"
if (params.genomeFile) log.warn "The params `--genomeFile` is deprecated -- it will be removed in a future release.\n\tPlease check: https://github.com/nf-core/sarek/blob/master/docs/usage.md#--fasta"
if (params.genomeIndex) log.warn "The params `--genomeIndex` is deprecated -- it will be removed in a future release.\n\tPlease check: https://github.com/nf-core/sarek/blob/master/docs/usage.md#--fastaFai"
if (params.sample) log.warn "The params `--sample` is deprecated -- it will be removed in a future release.\n\tPlease check: https://github.com/nf-core/sarek/blob/master/docs/usage.md#--input"
if (params.sampleDir) log.warn "The params `--sampleDir` is deprecated -- it will be removed in a future release.\n\tPlease check: https://github.com/nf-core/sarek/blob/master/docs/usage.md#--input"
// 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(", ")}"
}
stepList = defineStepList()
step = params.step ? params.step.toLowerCase() : ''
// Handle deprecation
if (step == 'preprocessing') step = 'mapping'
if (step.contains(',')) exit 1, 'You can choose only one step, see --help for more information'
if (!checkParameterExistence(step, stepList)) exit 1, "Unknown step ${step}, see --help for more information"
toolList = defineToolList()
tools = params.tools ? params.tools.split(',').collect{it.trim().toLowerCase()} : []
if (!checkParameterList(tools, toolList)) exit 1, 'Unknown tool(s), see --help for more information'
skipQClist = defineSkipQClist()
skipQC = params.skipQC ? params.skipQC == 'all' ? skipQClist : params.skipQC.split(',').collect{it.trim().toLowerCase()} : []
if (!checkParameterList(skipQC, skipQClist)) exit 1, 'Unknown QC tool(s), see --help for more information'
annoList = defineAnnoList()
annotateTools = params.annotateTools ? params.annotateTools.split(',').collect{it.trim().toLowerCase()} : []
if (!checkParameterList(annotateTools,annoList)) exit 1, 'Unknown tool(s) to annotate, see --help for more information'
// Handle deprecation
if (params.noReports) skipQC = skipQClist
// 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 == '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 (workflow.tracedir.startsWith('s3:')) exit 1, "Specify a local tracedir or run without trace! S3 cannot be used for tracefiles."
}
// Stage config files
ch_output_docs = Channel.fromPath("${baseDir}/docs/output.md")
tsvPath = null
if (params.input && (hasExtension(params.input, "tsv") || hasExtension(params.input, "vcf") || hasExtension(params.input, "vcf.gz"))) tsvPath = params.input
if (params.input && (hasExtension(params.input, "vcf") || hasExtension(params.input, "vcf.gz"))) step = "annotate"
// Handle deprecation
if (params.annotateVCF) tsvPath = params.annotateVCF
if (params.sample) tsvPath = params.sample
if (params.sampleDir) tsvPath = params.sampleDir
// If no input file specified, trying to get TSV files corresponding to step in the TSV directory
// only for steps recalibrate and variantCalling
if (!params.input && step != 'mapping' && step != 'annotate') {
if (params.sentieon) {
if (step == 'variantcalling') tsvPath = "${params.outdir}/Preprocessing/TSV/recalibrated_sentieon.tsv"
else exit 1, "Not possible to restart from that step"
}
else {
tsvPath = step == 'recalibrate' ? "${params.outdir}/Preprocessing/TSV/duplicateMarked.tsv" : "${params.outdir}/Preprocessing/TSV/recalibrated.tsv"
}
}
inputSample = Channel.empty()
if (tsvPath) {
tsvFile = file(tsvPath)
switch (step) {
case 'mapping': inputSample = extractFastq(tsvFile); break
case 'recalibrate': inputSample = extractRecal(tsvFile); break
case 'variantcalling': inputSample = extractBam(tsvFile); break
case 'annotate': break
default: exit 1, "Unknown step ${step}"
}
} else if (params.input && !hasExtension(params.input, "tsv")) {
log.info "No TSV file"
if (step != 'mapping') exit 1, 'No other step than "mapping" support a dir as an input'
log.info "Reading ${params.input} directory"
inputSample = extractFastqFromDir(params.input)
(inputSample, fastqTMP) = inputSample.into(2)
fastqTMP.toList().subscribe onNext: {
if (it.size() == 0) exit 1, "No FASTQ files found in --input directory '${params.input}'"
}
tsvFile = params.input // used in the reports
} else if (tsvPath && step == 'annotate') {
log.info "Annotating ${tsvPath}"
} else if (step == 'annotate') {
log.info "Trying automatic annotation on file in the VariantCalling directory"
} else exit 1, 'No sample were defined, see --help'
(genderMap, statusMap, inputSample) = extractInfos(inputSample)
/*
================================================================================
CHECKING REFERENCES
================================================================================
*/
// Initialize each params in params.genomes, catch the command line first if it was defined
// params.fasta has to be the first one
params.fasta = params.genome && !('annotate' in step) ? params.genomes[params.genome].fasta ?: null : null
// The rest can be sorted
params.acLoci = params.genome && 'ascat' in tools ? params.genomes[params.genome].acLoci ?: null : null
params.acLociGC = params.genome && 'ascat' in tools ? params.genomes[params.genome].acLociGC ?: null : null
params.bwaIndex = params.genome && params.fasta && 'mapping' in step ? params.genomes[params.genome].bwaIndex ?: null : null
params.chrDir = params.genome && 'controlfreec' in tools ? params.genomes[params.genome].chrDir ?: null : null
params.chrLength = params.genome && 'controlfreec' in tools ? params.genomes[params.genome].chrLength ?: null : null
params.dbsnp = params.genome && ('mapping' in step || 'controlfreec' in tools || 'haplotypecaller' in tools || 'mutect2' in tools) ? params.genomes[params.genome].dbsnp ?: null : null
params.dbsnpIndex = params.genome && params.dbsnp ? params.genomes[params.genome].dbsnpIndex ?: null : null
params.dict = params.genome && params.fasta ? params.genomes[params.genome].dict ?: null : null
params.fastaFai = params.genome && params.fasta ? params.genomes[params.genome].fastaFai ?: null : null
params.germlineResource = params.genome && 'mutect2' in tools ? params.genomes[params.genome].germlineResource ?: null : null
params.germlineResourceIndex = params.genome && params.germlineResource ? params.genomes[params.genome].germlineResourceIndex ?: null : null
params.intervals = params.genome && !('annotate' in step) ? params.genomes[params.genome].intervals ?: null : null
params.knownIndels = params.genome && 'mapping' in step ? params.genomes[params.genome].knownIndels ?: null : null
params.knownIndelsIndex = params.genome && params.knownIndels ? params.genomes[params.genome].knownIndelsIndex ?: null : null
params.snpeffDb = params.genome && 'snpeff' in tools ? params.genomes[params.genome].snpeffDb ?: null : null
params.species = params.genome && 'vep' in tools ? params.genomes[params.genome].species ?: null : null
params.vepCacheVersion = params.genome && 'vep' in tools ? params.genomes[params.genome].vepCacheVersion ?: null : null
// Initialize channels based on params
ch_acLoci = params.acLoci && 'ascat' in tools ? Channel.value(file(params.acLoci)) : "null"
ch_acLociGC = params.acLociGC && 'ascat' in tools ? Channel.value(file(params.acLociGC)) : "null"
ch_chrDir = params.chrDir && 'controlfreec' in tools ? Channel.value(file(params.chrDir)) : "null"
ch_chrLength = params.chrLength && 'controlfreec' in tools ? Channel.value(file(params.chrLength)) : "null"
ch_dbsnp = params.dbsnp && ('mapping' in step || 'controlfreec' in tools || 'haplotypecaller' in tools || 'mutect2' in tools) ? Channel.value(file(params.dbsnp)) : "null"
ch_fasta = params.fasta && !('annotate' in step) ? Channel.value(file(params.fasta)) : "null"
ch_fastaFai = params.fastaFai && !('annotate' in step) ? Channel.value(file(params.fastaFai)) : "null"
ch_germlineResource = params.germlineResource && 'mutect2' in tools ? Channel.value(file(params.germlineResource)) : "null"
ch_intervals = params.intervals && !params.no_intervals && !('annotate' in step) ? Channel.value(file(params.intervals)) : "null"
// knownIndels is currently a list of file for smallGRCh37, so transform it in a channel
li_knownIndels = []
if (params.knownIndels && ('mapping' in step)) params.knownIndels.each { li_knownIndels.add(file(it)) }
ch_knownIndels = params.knownIndels && params.genome == 'smallGRCh37' ? Channel.value(li_knownIndels.collect()) : params.knownIndels ? Channel.value(file(params.knownIndels)) : "null"
ch_snpEff_cache = params.snpEff_cache ? Channel.value(file(params.snpEff_cache)) : "null"
ch_snpeffDb = params.snpeffDb ? Channel.value(params.snpeffDb) : "null"
ch_vepCacheVersion = params.vepCacheVersion ? Channel.value(params.vepCacheVersion) : "null"
ch_vep_cache = params.vep_cache ? Channel.value(file(params.vep_cache)) : "null"
// Optional files, not defined within the params.genomes[params.genome] scope
ch_cadd_InDels = params.cadd_InDels ? Channel.value(file(params.cadd_InDels)) : "null"
ch_cadd_InDels_tbi = params.cadd_InDels_tbi ? Channel.value(file(params.cadd_InDels_tbi)) : "null"
ch_cadd_WG_SNVs = params.cadd_WG_SNVs ? Channel.value(file(params.cadd_WG_SNVs)) : "null"
ch_cadd_WG_SNVs_tbi = params.cadd_WG_SNVs_tbi ? Channel.value(file(params.cadd_WG_SNVs_tbi)) : "null"
ch_pon = params.pon ? Channel.value(file(params.pon)) : "null"
ch_targetBED = params.targetBED ? Channel.value(file(params.targetBED)) : "null"
/*
================================================================================
PRINTING SUMMARY
================================================================================
*/
// Header log info
log.info nfcoreHeader()
def summary = [:]
if (workflow.revision) summary['Pipeline Release'] = workflow.revision
summary['Run Name'] = custom_runName ?: workflow.runName
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}"
if (params.input) summary['Input'] = params.input
if (params.targetBED) summary['Target BED'] = params.targetBED
if (step) summary['Step'] = step
if (params.tools) summary['Tools'] = tools.join(', ')
if (params.skipQC) summary['QC tools skip'] = skipQC.join(', ')
if (params.no_intervals && step != 'annotate') summary['Intervals'] = 'Do not use'
if ('haplotypecaller' in tools) summary['GVCF'] = params.noGVCF ? 'No' : 'Yes'
if ('strelka' in tools && 'manta' in tools ) summary['Strelka BP'] = params.noStrelkaBP ? 'No' : 'Yes'
if (params.sequencing_center) summary['Sequenced by'] = params.sequencing_center
if (params.pon && 'mutect2' in tools) summary['Panel of normals'] = params.pon
summary['Save Genome Index'] = params.saveGenomeIndex ? 'Yes' : 'No'
summary['Nucleotides/s'] = params.nucleotidesPerSecond
summary['Output dir'] = params.outdir
summary['Launch dir'] = workflow.launchDir
summary['Working dir'] = workflow.workDir
summary['Script dir'] = workflow.projectDir
summary['User'] = workflow.userName
summary['genome'] = params.genome
if (params.fasta) summary['fasta'] = params.fasta
if (params.fastaFai) summary['fastaFai'] = params.fastaFai
if (params.dict) summary['dict'] = params.dict
if (params.bwaIndex) summary['bwaIndex'] = params.bwaIndex
if (params.germlineResource) summary['germlineResource'] = params.germlineResource
if (params.germlineResourceIndex) summary['germlineResourceIndex'] = params.germlineResourceIndex
if (params.intervals) summary['intervals'] = params.intervals
if (params.acLoci) summary['acLoci'] = params.acLoci
if (params.acLociGC) summary['acLociGC'] = params.acLociGC
if (params.chrDir) summary['chrDir'] = params.chrDir
if (params.chrLength) summary['chrLength'] = params.chrLength
if (params.dbsnp) summary['dbsnp'] = params.dbsnp
if (params.dbsnpIndex) summary['dbsnpIndex'] = params.dbsnpIndex
if (params.knownIndels) summary['knownIndels'] = params.knownIndels
if (params.knownIndelsIndex) summary['knownIndelsIndex'] = params.knownIndelsIndex
if (params.snpeffDb) summary['snpeffDb'] = params.snpeffDb
if (params.species) summary['species'] = params.species
if (params.vepCacheVersion) summary['vepCacheVersion'] = params.vepCacheVersion
if (params.species) summary['species'] = params.species
if (params.snpEff_cache) summary['snpEff_cache'] = params.snpEff_cache
if (params.vep_cache) summary['vep_cache'] = params.vep_cache
if (workflow.profile == 'awsbatch') {
summary['AWS Region'] = params.awsregion
summary['AWS Queue'] = params.awsqueue
}
summary['Config Profile'] = workflow.profile
if (params.config_profile_description) summary['Config Description'] = params.config_profile_description
if (params.config_profile_contact) summary['Config Contact'] = params.config_profile_contact
if (params.config_profile_url) summary['Config URL'] = params.config_profile_url
if (params.email) {
summary['E-mail Address'] = params.email
summary['MultiQC maxsize'] = params.maxMultiqcEmailFileSize
}
log.info summary.collect { k, v -> "${k.padRight(18)}: $v" }.join("\n")
if (params.monochrome_logs) log.info "----------------------------------------------------"
else log.info "\033[2m----------------------------------------------------\033[0m"
// Check the hostnames against configured profiles
checkHostname()
/*
* Parse software version numbers
*/
process GetSoftwareVersions {
publishDir path:"${params.outdir}/pipeline_info", mode: params.publishDirMode
output:
file 'software_versions_mqc.yaml' into yamlSoftwareVersion
when: !('versions' in skipQC)
script:
"""
alleleCounter --version &> v_allelecount.txt || true
bcftools version > v_bcftools.txt 2>&1 || true
bwa &> v_bwa.txt 2>&1 || true
configManta.py --version > v_manta.txt 2>&1 || true
configureStrelkaGermlineWorkflow.py --version > v_strelka.txt 2>&1 || true
echo "${workflow.manifest.version}" &> v_pipeline.txt 2>&1 || true
echo "${workflow.nextflow.version}" &> v_nextflow.txt 2>&1 || true
echo "SNPEFF version"\$(snpEff -h 2>&1) > v_snpeff.txt
fastqc --version > v_fastqc.txt 2>&1 || true
freebayes --version > v_freebayes.txt 2>&1 || true
gatk ApplyBQSR --help 2>&1 | grep Version: > v_gatk.txt 2>&1 || true
multiqc --version &> v_multiqc.txt 2>&1 || true
qualimap --version &> v_qualimap.txt 2>&1 || true
R --version &> v_r.txt || true
R -e "library(ASCAT); help(package='ASCAT')" &> v_ascat.txt
samtools --version &> v_samtools.txt 2>&1 || true
tiddit &> v_tiddit.txt 2>&1 || true
vcftools --version &> v_vcftools.txt 2>&1 || true
vep --help &> v_vep.txt 2>&1 || true
scrape_software_versions.py &> software_versions_mqc.yaml
"""
}
yamlSoftwareVersion = yamlSoftwareVersion.dump(tag:'SOFTWARE VERSIONS')
/*
================================================================================
BUILDING INDEXES
================================================================================
*/
// And then initialize channels based on params or indexes that were just built
process BuildBWAindexes {
tag {fasta}
publishDir params.outdir, mode: params.publishDirMode,
saveAs: {params.saveGenomeIndex ? "reference_genome/BWAIndex/${it}" : null }
input:
file(fasta) from ch_fasta
output:
file("${fasta}.*") into bwaIndexes
when: !(params.bwaIndex) && params.fasta && 'mapping' in step
script:
"""
bwa index ${fasta}
"""
}
ch_bwaIndex = params.bwaIndex ? Channel.value(file(params.bwaIndex)) : bwaIndexes
process BuildDict {
tag {fasta}
publishDir params.outdir, mode: params.publishDirMode,
saveAs: {params.saveGenomeIndex ? "reference_genome/${it}" : null }
input:
file(fasta) from ch_fasta
output:
file("${fasta.baseName}.dict") into dictBuilt
when: !(params.dict) && params.fasta && !('annotate' in step)
script:
"""
gatk --java-options "-Xmx${task.memory.toGiga()}g" \
CreateSequenceDictionary \
--REFERENCE ${fasta} \
--OUTPUT ${fasta.baseName}.dict
"""
}
ch_dict = params.dict ? Channel.value(file(params.dict)) : dictBuilt
process BuildFastaFai {
tag {fasta}
publishDir params.outdir, mode: params.publishDirMode,
saveAs: {params.saveGenomeIndex ? "reference_genome/${it}" : null }
input:
file(fasta) from ch_fasta
output:
file("${fasta}.fai") into fastaFaiBuilt
when: !(params.fastaFai) && params.fasta && !('annotate' in step)
script:
"""
samtools faidx ${fasta}
"""
}
ch_fastaFai = params.fastaFai ? Channel.value(file(params.fastaFai)) : fastaFaiBuilt
process BuildDbsnpIndex {
tag {dbsnp}
publishDir params.outdir, mode: params.publishDirMode,
saveAs: {params.saveGenomeIndex ? "reference_genome/${it}" : null }
input:
file(dbsnp) from ch_dbsnp
output:
file("${dbsnp}.tbi") into dbsnpIndexBuilt
when: !(params.dbsnpIndex) && params.dbsnp && ('mapping' in step || 'controlfreec' in tools || 'haplotypecaller' in tools || 'mutect2' in tools)
script:
"""
tabix -p vcf ${dbsnp}
"""
}
ch_dbsnpIndex = params.dbsnp ? params.dbsnpIndex ? Channel.value(file(params.dbsnpIndex)) : dbsnpIndexBuilt : "null"
process BuildGermlineResourceIndex {
tag {germlineResource}
publishDir params.outdir, mode: params.publishDirMode,
saveAs: {params.saveGenomeIndex ? "reference_genome/${it}" : null }
input:
file(germlineResource) from ch_germlineResource
output:
file("${germlineResource}.tbi") into germlineResourceIndexBuilt
when: !(params.germlineResourceIndex) && params.germlineResource && 'mutect2' in tools
script:
"""
tabix -p vcf ${germlineResource}
"""
}
ch_germlineResourceIndex = params.germlineResource ? params.germlineResourceIndex ? Channel.value(file(params.germlineResourceIndex)) : germlineResourceIndexBuilt : "null"
process BuildKnownIndelsIndex {
tag {knownIndels}
publishDir params.outdir, mode: params.publishDirMode,
saveAs: {params.saveGenomeIndex ? "reference_genome/${it}" : null }
input:
each file(knownIndels) from ch_knownIndels
output:
file("${knownIndels}.tbi") into knownIndelsIndexBuilt
when: !(params.knownIndelsIndex) && params.knownIndels && 'mapping' in step
script:
"""
tabix -p vcf ${knownIndels}
"""
}
ch_knownIndelsIndex = params.knownIndels ? params.knownIndelsIndex ? Channel.value(file(params.knownIndelsIndex)) : knownIndelsIndexBuilt.collect() : "null"
process BuildPonIndex {
tag {pon}
publishDir params.outdir, mode: params.publishDirMode,
saveAs: {params.saveGenomeIndex ? "reference_genome/${it}" : null }
input:
file(pon) from ch_pon
output:
file("${pon}.tbi") into ponIndexBuilt
when: !(params.pon_index) && params.pon && ('tnscope' in tools || 'mutect2' in tools)
script:
"""
tabix -p vcf ${pon}
"""
}
ch_ponIndex = params.pon_index ? Channel.value(file(params.pon_index)) : ponIndexBuilt
process BuildIntervals {
tag {fastaFai}
publishDir params.outdir, mode: params.publishDirMode,
saveAs: {params.saveGenomeIndex ? "reference_genome/${it}" : null }
input:
file(fastaFai) from ch_fastaFai
output:
file("${fastaFai.baseName}.bed") into intervalBuilt
when: !(params.intervals) && !('annotate' in step) && !(params.no_intervals)
script:
"""
awk -v FS='\t' -v OFS='\t' '{ print \$1, \"0\", \$2 }' ${fastaFai} > ${fastaFai.baseName}.bed
"""
}
ch_intervals = params.no_intervals ? "null" : params.intervals && !('annotate' in step) ? Channel.value(file(params.intervals)) : intervalBuilt
/*
================================================================================
PREPROCESSING
================================================================================
*/
// STEP 0: CREATING INTERVALS FOR PARALLELIZATION (PREPROCESSING AND VARIANT CALLING)
process CreateIntervalBeds {
tag {intervals.fileName}
input:
file(intervals) from ch_intervals
output:
file '*.bed' into bedIntervals mode flatten
when: (!params.no_intervals) && step != 'annotate'
script:
// If the interval file is BED format, the fifth column is interpreted to
// contain runtime estimates, which is then used to combine short-running jobs
if (hasExtension(intervals, "bed"))
"""
awk -vFS="\t" '{
t = \$5 # runtime estimate
if (t == "") {
# no runtime estimate in this row, assume default value
t = (\$3 - \$2) / ${params.nucleotidesPerSecond}
}
if (name == "" || (chunk > 600 && (chunk + t) > longest * 1.05)) {
# start a new chunk
name = sprintf("%s_%d-%d.bed", \$1, \$2+1, \$3)
chunk = 0
longest = 0
}
if (t > longest)
longest = t
chunk += t
print \$0 > name
}' ${intervals}
"""
else if (hasExtension(intervals, "interval_list"))
"""
grep -v '^@' ${intervals} | awk -vFS="\t" '{
name = sprintf("%s_%d-%d", \$1, \$2, \$3);
printf("%s\\t%d\\t%d\\n", \$1, \$2-1, \$3) > name ".bed"
}'
"""
else
"""
awk -vFS="[:-]" '{
name = sprintf("%s_%d-%d", \$1, \$2, \$3);
printf("%s\\t%d\\t%d\\n", \$1, \$2-1, \$3) > name ".bed"
}' ${intervals}
"""
}
bedIntervals = bedIntervals
.map { intervalFile ->
def duration = 0.0
for (line in intervalFile.readLines()) {
final fields = line.split('\t')
if (fields.size() >= 5) duration += fields[4].toFloat()
else {
start = fields[1].toInteger()
end = fields[2].toInteger()
duration += (end - start) / params.nucleotidesPerSecond
}
}
[duration, intervalFile]
}.toSortedList({ a, b -> b[0] <=> a[0] })
.flatten().collate(2)
.map{duration, intervalFile -> intervalFile}
bedIntervals = bedIntervals.dump(tag:'bedintervals')
if (params.no_intervals && step != 'annotate') bedIntervals = Channel.from(file("no_intervals.bed"))
(intBaseRecalibrator, intApplyBQSR, intHaplotypeCaller, intMpileup, bedIntervals) = bedIntervals.into(5)
// PREPARING CHANNELS FOR PREPROCESSING AND QC
inputBam = Channel.create()
inputPairReads = Channel.create()
if (step in ['recalibrate', 'variantcalling', 'annotate']) {
inputBam.close()
inputPairReads.close()
} else inputSample.choice(inputPairReads, inputBam) {hasExtension(it[3], "bam") ? 1 : 0}
(inputBam, inputBamFastQC) = inputBam.into(2)
// Removing inputFile2 wich is null in case of uBAM
inputBamFastQC = inputBamFastQC.map {
idPatient, idSample, idRun, inputFile1, inputFile2 ->
[idPatient, idSample, idRun, inputFile1]
}
if (params.split_fastq){
inputPairReads = inputPairReads
// newly splitfastq are named based on split, so the name is easier to catch
.splitFastq(by: params.split_fastq, compress:true, file:"split", pe:true)
.map {idPatient, idSample, idRun, reads1, reads2 ->
// The split fastq read1 is the 4th element (indexed 3) its name is split_3
// The split fastq read2's name is split_4
// It's followed by which split it's acutally based on the mother fastq file
// Index start at 1
// Extracting the index to get a new IdRun
splitIndex = reads1.fileName.toString().minus("split_3.").minus(".gz")
newIdRun = idRun + "_" + splitIndex
// Giving the files a new nice name
newReads1 = file("${idSample}_${newIdRun}_R1.fastq.gz")
newReads2 = file("${idSample}_${newIdRun}_R2.fastq.gz")
[idPatient, idSample, newIdRun, reads1, reads2]}
}
inputPairReads = inputPairReads.dump(tag:'INPUT')
(inputPairReads, inputPairReadsFastQC) = inputPairReads.into(2)
// STEP 0.5: QC ON READS
// TODO: Use only one process for FastQC for FASTQ files and uBAM files
// FASTQ and uBAM files are renamed based on the sample name
process FastQCFQ {
label 'FastQC'
label 'cpus_2'
tag {idPatient + "-" + idRun}
publishDir "${params.outdir}/Reports/${idSample}/FastQC/${idSample}_${idRun}", mode: params.publishDirMode
input:
set idPatient, idSample, idRun, file("${idSample}_${idRun}_R1.fastq.gz"), file("${idSample}_${idRun}_R2.fastq.gz") from inputPairReadsFastQC
output:
file("*.{html,zip}") into fastQCFQReport
when: !('fastqc' in skipQC)
script:
"""
fastqc -t 2 -q ${idSample}_${idRun}_R1.fastq.gz ${idSample}_${idRun}_R2.fastq.gz
"""
}
process FastQCBAM {
label 'FastQC'
label 'cpus_2'
tag {idPatient + "-" + idRun}
publishDir "${params.outdir}/Reports/${idSample}/FastQC/${idSample}_${idRun}", mode: params.publishDirMode
input:
set idPatient, idSample, idRun, file("${idSample}_${idRun}.bam") from inputBamFastQC
output:
file("*.{html,zip}") into fastQCBAMReport
when: !('fastqc' in skipQC)
script:
"""
fastqc -t 2 -q ${idSample}_${idRun}.bam
"""
}
fastQCReport = fastQCFQReport.mix(fastQCBAMReport)
fastQCReport = fastQCReport.dump(tag:'FastQC')
// STEP 1: MAPPING READS TO REFERENCE GENOME WITH BWA MEM
inputPairReads = inputPairReads.dump(tag:'INPUT')
inputPairReads = inputPairReads.mix(inputBam)
(inputPairReads, inputPairReadsSentieon) = inputPairReads.into(2)
if (params.sentieon) inputPairReads.close()
else inputPairReadsSentieon.close()
process MapReads {
label 'cpus_max'
label 'memory_max'
echo true
tag {idPatient + "-" + idRun}
input:
set idPatient, idSample, idRun, file(inputFile1), file(inputFile2) from inputPairReads
file(bwaIndex) from ch_bwaIndex
file(fasta) from ch_fasta
file(fastaFai) from ch_fastaFai
output:
set idPatient, idSample, idRun, file("${idSample}_${idRun}.bam") into bamMapped
set idPatient, val("${idSample}_${idRun}"), file("${idSample}_${idRun}.bam") into bamMappedBamQC
script:
// -K is an hidden option, used to fix the number of reads processed by bwa mem
// Chunk size can affect bwa results, if not specified,
// the number of threads can change which can give not deterministic result.
// cf https://github.com/CCDG/Pipeline-Standardization/blob/master/PipelineStandard.md
// and https://github.com/gatk-workflows/gatk4-data-processing/blob/8ffa26ff4580df4ac3a5aa9e272a4ff6bab44ba2/processing-for-variant-discovery-gatk4.b37.wgs.inputs.json#L29
CN = params.sequencing_center ? "CN:${params.sequencing_center}\\t" : ""
readGroup = "@RG\\tID:${idRun}\\t${CN}PU:${idRun}\\tSM:${idSample}\\tLB:${idSample}\\tPL:illumina"
// adjust mismatch penalty for tumor samples
status = statusMap[idPatient, idSample]
extra = status == 1 ? "-B 3" : ""
convertToFastq = hasExtension(inputFile1, "bam") ? "gatk --java-options -Xmx${task.memory.toGiga()}g SamToFastq --INPUT=${inputFile1} --FASTQ=/dev/stdout --INTERLEAVE=true --NON_PF=true | \\" : ""
input = hasExtension(inputFile1, "bam") ? "-p /dev/stdin - 2> >(tee ${inputFile1}.bwa.stderr.log >&2)" : "${inputFile1} ${inputFile2}"
// Pseudo-code: Add soft-coded memory allocation to the two tools, bwa mem | smatools sort
// Request only one from the user, the other is implicit: 1 - defined
bwa_cpus = params.bwa_cpus ? params.bwa_cpus : Math.floor ( params.bwa_cpus_fraction * task.cpus) as Integer
sort_cpus = params.sort_cpus ? params.sort_cpus : task.cpus - bwa_cpus
"""
${convertToFastq}
bwa mem -k 23 -K 100000000 -R \"${readGroup}\" ${extra} -t ${bwa_cpus} -M ${fasta} \
${input} | \
samtools sort --threads ${sort_cpus} - > ${idSample}_${idRun}.bam
"""
}
bamMapped = bamMapped.dump(tag:'Mapped BAM')
// Sort BAM whether they are standalone or should be merged
singleBam = Channel.create()
multipleBam = Channel.create()
bamMapped.groupTuple(by:[0, 1])
.choice(singleBam, multipleBam) {it[2].size() > 1 ? 1 : 0}
singleBam = singleBam.map {
idPatient, idSample, idRun, bam ->
[idPatient, idSample, bam]
}
singleBam = singleBam.dump(tag:'Single BAM')
// STEP 1': MAPPING READS TO REFERENCE GENOME WITH SENTIEON BWA MEM
process SentieonMapReads {
label 'cpus_max'
label 'memory_max'
label 'sentieon'
tag {idPatient + "-" + idRun}
input:
set idPatient, idSample, idRun, file(inputFile1), file(inputFile2) from inputPairReadsSentieon
file(bwaIndex) from ch_bwaIndex
file(fasta) from ch_fasta
file(fastaFai) from ch_fastaFai
output:
set idPatient, idSample, idRun, file("${idSample}_${idRun}.bam") into bamMappedSentieon
set idPatient, idSample, file("${idSample}_${idRun}.bam") into bamMappedSentieonBamQC
when: params.sentieon
script:
// -K is an hidden option, used to fix the number of reads processed by bwa mem
// Chunk size can affect bwa results, if not specified,
// the number of threads can change which can give not deterministic result.
// cf https://github.com/CCDG/Pipeline-Standardization/blob/master/PipelineStandard.md
// and https://github.com/gatk-workflows/gatk4-data-processing/blob/8ffa26ff4580df4ac3a5aa9e272a4ff6bab44ba2/processing-for-variant-discovery-gatk4.b37.wgs.inputs.json#L29
CN = params.sequencing_center ? "CN:${params.sequencing_center}\\t" : ""
readGroup = "@RG\\tID:${idRun}\\t${CN}PU:${idRun}\\tSM:${idSample}\\tLB:${idSample}\\tPL:illumina"
// adjust mismatch penalty for tumor samples
status = statusMap[idPatient, idSample]
extra = status == 1 ? "-B 3" : ""
"""
sentieon bwa mem -K 100000000 -R \"${readGroup}\" ${extra} -t ${task.cpus} -M ${fasta} \
${inputFile1} ${inputFile2} | \
sentieon util sort -r ${fasta} -o ${idSample}_${idRun}.bam -t ${task.cpus} --sam2bam -i -
"""
}
bamMappedSentieon = bamMappedSentieon.dump(tag:'Sentieon Mapped BAM')
// Sort BAM whether they are standalone or should be merged
singleBamSentieon = Channel.create()
multipleBamSentieon = Channel.create()
bamMappedSentieon.groupTuple(by:[0, 1])
.choice(singleBamSentieon, multipleBamSentieon) {it[2].size() > 1 ? 1 : 0}
singleBamSentieon = singleBamSentieon.map {
idPatient, idSample, idRun, bam ->
[idPatient, idSample, bam]
}
singleBamSentieon = singleBamSentieon.dump(tag:'Single BAM')
// STEP 1.5: MERGING BAM FROM MULTIPLE LANES
multipleBam = multipleBam.mix(multipleBamSentieon)
process MergeBamMapped {
label 'med_resources'
tag {idPatient + "-" + idSample}
input:
set idPatient, idSample, idRun, file(bam) from multipleBam
output:
set idPatient, idSample, file("${idSample}.bam") into mergedBam
script:
"""
samtools merge --threads ${task.cpus} ${idSample}.bam ${bam}
"""
}
mergedBam = mergedBam.dump(tag:'Merged BAM')
mergedBam = mergedBam.mix(singleBam,singleBamSentieon)
(mergedBam, mergedBamForSentieon) = mergedBam.into(2)
if (!params.sentieon) mergedBamForSentieon.close()
else mergedBam.close()
mergedBam = mergedBam.dump(tag:'BAMs for MD')
mergedBamForSentieon = mergedBamForSentieon.dump(tag:'Sentieon BAMs to Index')
process IndexBamMergedForSentieon {
label 'med_resources'
tag {idPatient + "-" + idSample}
input:
set idPatient, idSample, file(bam) from mergedBamForSentieon
output:
set idPatient, idSample, file(bam), file("${idSample}.bam.bai") into bamForSentieonDedup
script:
"""
samtools index ${bam}
"""
}
(mergedBam, mergedBamToIndex) = mergedBam.into(2)
process IndexBamFile {
label 'med_resources'
tag {idPatient + "-" + idSample}
input:
set idPatient, idSample, file(bam) from mergedBamToIndex
output:
set idPatient, idSample, file(bam), file("*.bai") into indexedBam
when: !params.knownIndels
script:
"""
samtools index ${bam}
mv ${bam}.bai ${bam.baseName}.bai
"""
}
// STEP 2: MARKING DUPLICATES
process MarkDuplicates {
label 'cpus_max'
label 'memory_max'
tag {idPatient + "-" + idSample}
publishDir params.outdir, mode: params.publishDirMode,
saveAs: {
if (it == "${idSample}.bam.metrics" && 'markduplicates' in skipQC) null
else if (it == "${idSample}.bam.metrics") "Reports/${idSample}/MarkDuplicates/${it}"
else "Preprocessing/${idSample}/DuplicateMarked/${it}"
}
input:
set idPatient, idSample, file("${idSample}.bam") from mergedBam
output:
set idPatient, idSample, file("${idSample}.md.bam"), file("${idSample}.md.bai") into duplicateMarkedBams
file ("${idSample}.bam.metrics") into markDuplicatesReport
when: params.knownIndels
script:
markdup_java_options = task.memory.toGiga() > 8 ? params.markdup_java_options : "\"-Xms" + (task.memory.toGiga() / 2).trunc() + "g -Xmx" + (task.memory.toGiga() - 1) + "g\""
"""
gatk --java-options ${markdup_java_options} \
MarkDuplicates \
--MAX_RECORDS_IN_RAM 50000 \
--INPUT ${idSample}.bam \
--METRICS_FILE ${idSample}.bam.metrics \
--TMP_DIR . \
--ASSUME_SORT_ORDER coordinate \
--CREATE_INDEX true \
--OUTPUT ${idSample}.md.bam
"""
}
if ('markduplicates' in skipQC) markDuplicatesReport.close()
duplicateMarkedBams = duplicateMarkedBams.dump(tag:'MD BAM')
markDuplicatesReport = markDuplicatesReport.dump(tag:'MD Report')
(bamMD, bamMDToJoin) = duplicateMarkedBams.into(2)
bamBaseRecalibrator = bamMD.combine(intBaseRecalibrator)
bamBaseRecalibrator = bamBaseRecalibrator.dump(tag:'BAM FOR BASERECALIBRATOR')
// STEP 2': SENTIEON DEDUP
process SentieonDedup {