forked from nf-core/sarek
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.nf
More file actions
2148 lines (1823 loc) · 71.2 KB
/
main.nf
File metadata and controls
2148 lines (1823 loc) · 71.2 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
/*
vim: syntax=groovy
-*- mode: groovy;-*-
kate: syntax groovy; space-indent on; indent-width 2;
================================================================================
= C A N C E R A N A L Y S I S W O R K F L O W =
================================================================================
New Cancer Analysis Workflow. Started March 2016.
--------------------------------------------------------------------------------
@Authors
Sebastian DiLorenzo <sebastian.dilorenzo@bils.se> [@Sebastian-D]
Jesper Eisfeldt <jesper.eisfeldt@scilifelab.se> [@J35P312]
Maxime Garcia <maxime.garcia@scilifelab.se> [@MaxUlysse]
Szilveszter Juhos <szilveszter.juhos@scilifelab.se> [@szilvajuhos]
Max Käller <max.kaller@scilifelab.se> [@gulfshores]
Malin Larsson <malin.larsson@scilifelab.se> [@malinlarsson]
Marcel Martin <marcel.martin@scilifelab.se> [@marcelm]
Björn Nystedt <bjorn.nystedt@scilifelab.se> [@bjornnystedt]
Pall Olason <pall.olason@scilifelab.se> [@pallolason]
Pelin Sahlén <pelin.akan@scilifelab.se> [@pelinakan]
--------------------------------------------------------------------------------
@Homepage
http://opensource.scilifelab.se/projects/caw/
--------------------------------------------------------------------------------
@Documentation
https://github.com/SciLifeLab/CAW/README.md
--------------------------------------------------------------------------------
Processes overview
- RunFastQC - Run FastQC for QC on fastq files
- MapReads - Map reads with BWA
- MergeBams - Merge BAMs if multilane samples
- MarkDuplicates - Mark Duplicates with Picard
- RealignerTargetCreator - Create realignment target intervals
- IndelRealigner - Realign BAMs as T/N pair
- CreateRecalibrationTable - Create Recalibration Table with BaseRecalibrator
- RecalibrateBam - Recalibrate Bam with PrintReads
- RunSamtoolsStats - Run Samtools stats on recalibrated BAM files
- RunBamQC - Run qualimap BamQC on recalibrated BAM files
- CreateIntervalBeds - Create and sort intervals into bed files
- RunHaplotypecaller - Run HaplotypeCaller for Germline Variant Calling (Parallelized processes)
- RunGenotypeGVCFs - Run HaplotypeCaller for Germline Variant Calling (Parallelized processes)
- RunMutect1 - Run MuTect1 for Variant Calling (Parallelized processes)
- RunMutect2 - Run MuTect2 for Variant Calling (Parallelized processes)
- RunFreeBayes - Run FreeBayes for Variant Calling (Parallelized processes)
- ConcatVCF - Merge results from HaplotypeCaller, MuTect1 and MuTect2
- RunStrelka - Run Strelka for Variant Calling
- RunSingleStrelka - Run Strelka for Germline Variant Calling
- RunManta - Run Manta for Structural Variant Calling
- RunSingleManta - Run Manta for Single Structural Variant Calling
- RunAlleleCount - Run AlleleCount to prepare for ASCAT
- RunConvertAlleleCounts - Run convertAlleleCounts to prepare for ASCAT
- RunAscat - Run ASCAT for CNV
- RunBcftoolsStats - Run BCFTools stats on vcf before annotation
- RunSnpeff - Run snpEff for annotation of vcf files
- RunVEP - Run VEP for annotation of vcf files
- GenerateMultiQCconfig - Generate a config file for MultiQC
- RunMultiQC - Run MultiQC for report and QC
================================================================================
= C O N F I G U R A T I O N =
================================================================================
*/
version = '1.2.4'
// Check that Nextflow version is up to date enough
// try / throw / catch works for NF versions < 0.25 when this was implemented
nf_required_version = '0.25.0'
try {
if( ! nextflow.version.matches(">= $nf_required_version") ){
throw GroovyException('Nextflow version too old')
}
} catch (all) {
log.error "============================================================\n" +
" Nextflow version $nf_required_version required! You are running v$workflow.nextflow.version.\n" +
" Pipeline execution will continue, but things may break.\n" +
" Please update Nextflow.\n" +
"============================================================"
}
// Default params:
// Such params are overridden by command line or configuration definitions
// No tools to annotate
params.annotateTools = ''
// No vcf to annotare
params.annotateVCF = ''
// For MultiQC reports
params.callName = ''
// For MultiQC reports
params.contactMail = ''
// GVCF are generated
params.noGVCF = false
// Reports are generated
params.noReports = false
// No sample is defined
params.sample = ''
// No sampleDir is defined
params.sampleDir = ''
// Step is mapping
params.step = 'mapping'
// Not testing
params.test = ''
// No tools to be used
params.tools = ''
if (params.help) exit 0, helpMessage()
if (params.version) exit 0, versionMessage()
if (!isAllowedParams(params)) exit 1, "params is unknown, see --help for more information"
if (!checkUppmaxProject()) exit 1, "No UPPMAX project ID found! Use --project <UPPMAX Project ID>"
step = params.step.toLowerCase()
if (step == 'preprocessing') step = 'mapping'
if (step == 'skippreprocessing') step = 'variantcalling'
tools = params.tools ? params.tools.split(',').collect{it.trim().toLowerCase()} : []
annotateTools = params.annotateTools ? params.annotateTools.split(',').collect{it.trim().toLowerCase()} : []
annotateVCF = params.annotateVCF ? params.annotateVCF.split(',').collect{it.trim()} : []
directoryMap = defineDirectoryMap()
referenceMap = defineReferenceMap()
stepList = defineStepList()
toolList = defineToolList()
nucleotidesPerSecond = 1000.0 // used to estimate variant calling runtime
gvcf = !params.noGVCF
reports = !params.noReports
verbose = params.verbose
if (!checkParameterExistence(step, stepList)) exit 1, 'Unknown step, see --help for more information'
if (step.contains(',')) exit 1, 'You can choose only one step, see --help for more information'
if (step == 'mapping' && !checkExactlyOne([params.test, params.sample, params.sampleDir]))
exit 1, 'Please define which samples to work on by providing exactly one of the --test, --sample or --sampleDir options'
if (!checkReferenceMap(referenceMap)) exit 1, 'Missing Reference file(s), see --help for more information'
if (!checkParameterList(tools,toolList)) exit 1, 'Unknown tool(s), see --help for more information'
if (params.test && params.genome in ['GRCh37', 'GRCh38']) {
referenceMap.intervals = file("$workflow.projectDir/repeats/tiny_${params.genome}.list")
}
// TODO
// MuTect and Mutect2 could be run without a recalibrated BAM (they support
// the --BQSR option), but this is not implemented, yet.
// TODO
// FreeBayes does not need recalibrated BAMs, but we need to test whether
// the channels are set up correctly when we disable it
if (step == "recalibrate" && tools != ['haplotypecaller']) explicitBqsrNeeded = true
else explicitBqsrNeeded = tools.intersect(['manta', 'mutect1', 'mutect2', 'vardict', 'freebayes', 'strelka']).asBoolean()
tsvPath = ''
if (params.sample) tsvPath = params.sample
// No need for tsv file for step annotate
if (!params.sample && !params.sampleDir) {
tsvPaths = [
'mapping': "$workflow.projectDir/data/tsv/tiny.tsv",
'realign': "$workflow.launchDir/$directoryMap.nonRealigned/nonRealigned.tsv",
'recalibrate': "$workflow.launchDir/$directoryMap.nonRecalibrated/nonRecalibrated.tsv",
'variantcalling': "$workflow.launchDir/$directoryMap.recalibrated/recalibrated.tsv"
]
if (params.test || step != 'mapping') tsvPath = tsvPaths[step]
}
// Set up the fastqFiles and bamFiles channels. One of them remains empty
// Except for step annotate, in which both stay empty
fastqFiles = Channel.empty()
bamFiles = Channel.empty()
if (tsvPath) {
tsvFile = file(tsvPath)
switch (step) {
case 'mapping': fastqFiles = extractFastq(tsvFile); break
case 'realign': bamFiles = extractBams(tsvFile); break
case 'recalibrate': bamFiles = extractRecal(tsvFile); break
case 'variantcalling': bamFiles = extractBams(tsvFile); break
default: exit 1, "Unknown step $step"
}
} else if (params.sampleDir) {
if (step != 'mapping') exit 1, '--sampleDir does not support steps other than "mapping"'
fastqFiles = extractFastqFromDir(params.sampleDir)
tsvFile = params.sampleDir // used in the reports
} else if (step != 'annotate') exit 1, 'No sample were defined, see --help'
if (step == 'mapping') {
(patientGenders, fastqFiles) = extractGenders(fastqFiles)
} else {
(patientGenders, bamFiles) = extractGenders(bamFiles)
}
/*
================================================================================
= P R O C E S S E S =
================================================================================
*/
startMessage()
(fastqFiles, fastqFilesforFastQC) = fastqFiles.into(2)
if (verbose) fastqFiles = fastqFiles.view {
"FASTQs to preprocess:\n\
ID : ${it[0]}\tStatus: ${it[1]}\tSample: ${it[2]}\tRun : ${it[3]}\n\
Files : [${it[4].fileName}, ${it[5].fileName}]"
}
if (verbose) bamFiles = bamFiles.view {
"BAMs to process:\n\
ID : ${it[0]}\tStatus: ${it[1]}\tSample: ${it[2]}\n\
Files : [${it[3].fileName}, ${it[4].fileName}]"
}
process RunFastQC {
tag {idPatient + "-" + idRun}
publishDir "$directoryMap.fastQC/$idRun", mode: 'copy'
input:
set idPatient, status, idSample, idRun, file(fastqFile1), file(fastqFile2) from fastqFilesforFastQC
output:
file "*_fastqc.{zip,html}" into fastQCreport
when: step == 'mapping' && reports
script:
"""
fastqc -q $fastqFile1 $fastqFile2
"""
}
if (verbose) fastQCreport = fastQCreport.view {
"FastQC report:\n\
Files : [${it[0].fileName}, ${it[1].fileName}]"
}
process MapReads {
tag {idPatient + "-" + idRun}
input:
set idPatient, status, idSample, idRun, file(fastqFile1), file(fastqFile2) from fastqFiles
set file(genomeFile), file(bwaIndex) from Channel.value([referenceMap.genomeFile, referenceMap.bwaIndex])
output:
set idPatient, status, idSample, idRun, file("${idRun}.bam") into mappedBam
when: step == 'mapping'
script:
readGroup = "@RG\\tID:$idRun\\tPU:$idRun\\tSM:$idSample\\tLB:$idSample\\tPL:illumina"
// adjust mismatch penalty for tumor samples
extra = status == 1 ? "-B 3 " : ""
"""
bwa mem -R \"$readGroup\" ${extra}-t $task.cpus -M \
$genomeFile $fastqFile1 $fastqFile2 | \
samtools sort --threads $task.cpus -m 4G - > ${idRun}.bam
"""
}
if (verbose) mappedBam = mappedBam.view {
"Mapped BAM (single or to be merged):\n\
ID : ${it[0]}\tStatus: ${it[1]}\tSample: ${it[2]}\tRun : ${it[3]}\n\
File : [${it[4].fileName}]"
}
// Sort bam whether they are standalone or should be merged
// Borrowed code from https://github.com/guigolab/chip-nf
singleBam = Channel.create()
groupedBam = Channel.create()
mappedBam.groupTuple(by:[0,1,2])
.choice(singleBam, groupedBam) {it[3].size() > 1 ? 1 : 0}
singleBam = singleBam.map {
idPatient, status, idSample, idRun, bam ->
[idPatient, status, idSample, bam]
}
process MergeBams {
tag {idPatient + "-" + idSample}
input:
set idPatient, status, idSample, idRun, file(bam) from groupedBam
output:
set idPatient, status, idSample, file("${idSample}.bam") into mergedBam
when: step == 'mapping'
script:
"""
samtools merge --threads $task.cpus ${idSample}.bam $bam
"""
}
if (verbose) singleBam = singleBam.view {
"Single BAM:\n\
ID : ${it[0]}\tStatus: ${it[1]}\tSample: ${it[2]}\n\
File : [${it[3].fileName}]"
}
if (verbose) mergedBam = mergedBam.view {
"Merged BAM:\n\
ID : ${it[0]}\tStatus: ${it[1]}\tSample: ${it[2]}\n\
File : [${it[3].fileName}]"
}
mergedBam = mergedBam.mix(singleBam)
if (verbose) mergedBam = mergedBam.view {
"BAM for MarkDuplicates:\n\
ID : ${it[0]}\tStatus: ${it[1]}\tSample: ${it[2]}\n\
File : [${it[3].fileName}]"
}
process MarkDuplicates {
tag {idPatient + "-" + idSample}
publishDir '.', saveAs: { it == "${bam}.metrics" ? "$directoryMap.markDuplicatesQC/$it" : "$directoryMap.nonRealigned/$it" }, mode: 'copy'
input:
set idPatient, status, idSample, file(bam) from mergedBam
output:
set idPatient, file("${idSample}_${status}.md.bam"), file("${idSample}_${status}.md.bai") into duplicates
set idPatient, status, idSample, val("${idSample}_${status}.md.bam"), val("${idSample}_${status}.md.bai") into markDuplicatesTSV
file ("${bam}.metrics") into markDuplicatesReport
when: step == 'mapping'
script:
"""
java -Xmx${task.memory.toGiga()}g \
-jar \$PICARD_HOME/picard.jar MarkDuplicates \
INPUT=${bam} \
METRICS_FILE=${bam}.metrics \
TMP_DIR=. \
ASSUME_SORTED=true \
VALIDATION_STRINGENCY=LENIENT \
CREATE_INDEX=TRUE \
OUTPUT=${idSample}_${status}.md.bam
"""
}
// Creating a TSV file to restart from this step
markDuplicatesTSV.map { idPatient, status, idSample, bam, bai ->
gender = patientGenders[idPatient]
"$idPatient\t$gender\t$status\t$idSample\t$directoryMap.nonRealigned/$bam\t$directoryMap.nonRealigned/$bai\n"
}.collectFile(
name: 'nonRealigned.tsv', sort: true, storeDir: directoryMap.nonRealigned
)
// Create intervals for realignement using both tumor+normal as input
// Group the marked duplicates BAMs for intervals and realign by idPatient
// Grouping also by gender, to make a nicer channel
duplicatesGrouped = Channel.empty()
if (step == 'mapping') {
duplicatesGrouped = duplicates.groupTuple()
} else if (step == 'realign') {
duplicatesGrouped = bamFiles.map{
idPatient, status, idSample, bam, bai ->
[idPatient, bam, bai]
}.groupTuple()
}
// The duplicatesGrouped channel is duplicated
// one copy goes to the RealignerTargetCreator process
// and the other to the IndelRealigner process
(duplicatesInterval, duplicatesRealign) = duplicatesGrouped.into(2)
if (verbose) duplicatesInterval = duplicatesInterval.view {
"BAMs for RealignerTargetCreator:\n\
ID : ${it[0]}\n\
Files : ${it[1].fileName}\n\
Files : ${it[2].fileName}"
}
if (verbose) duplicatesRealign = duplicatesRealign.view {
"BAMs to phase:\n\
ID : ${it[0]}\n\
Files : ${it[1].fileName}\n\
Files : ${it[2].fileName}"
}
if (verbose) markDuplicatesReport = markDuplicatesReport.view {
"MarkDuplicates report:\n\
File : [$it.fileName]"
}
// VCF indexes are added so they will be linked, and not re-created on the fly
// -L "1:131941-141339" \
process RealignerTargetCreator {
tag {idPatient}
input:
set idPatient, file(bam), file(bai) from duplicatesInterval
set file(genomeFile), file(genomeIndex), file(genomeDict), file(knownIndels), file(knownIndelsIndex), file(intervals) from Channel.value([
referenceMap.genomeFile,
referenceMap.genomeIndex,
referenceMap.genomeDict,
referenceMap.knownIndels,
referenceMap.knownIndelsIndex,
referenceMap.intervals
])
output:
set idPatient, file("${idPatient}.intervals") into intervals
when: step == 'mapping' || step == 'realign'
script:
bams = bam.collect{"-I $it"}.join(' ')
known = knownIndels.collect{"-known $it"}.join(' ')
"""
java -Xmx${task.memory.toGiga()}g \
-jar \$GATK_HOME/GenomeAnalysisTK.jar \
-T RealignerTargetCreator \
$bams \
-R $genomeFile \
$known \
-nt $task.cpus \
-L $intervals \
-o ${idPatient}.intervals
"""
}
if (verbose) intervals = intervals.view {
"Intervals to phase:\n\
ID : ${it[0]}\n\
File : [${it[1].fileName}]"
}
bamsAndIntervals = duplicatesRealign
.phase(intervals)
.map{duplicatesRealign, intervals ->
tuple(
duplicatesRealign[0],
duplicatesRealign[1],
duplicatesRealign[2],
intervals[1]
)}
if (verbose) bamsAndIntervals = bamsAndIntervals.view {
"BAMs and Intervals phased for IndelRealigner:\n\
ID : ${it[0]}\n\
Files : ${it[1].fileName}\n\
Files : ${it[2].fileName}\n\
File : [${it[3].fileName}]"
}
// use nWayOut to split into T/N pair again
process IndelRealigner {
tag {idPatient}
input:
set idPatient, file(bam), file(bai), file(intervals) from bamsAndIntervals
set file(genomeFile), file(genomeIndex), file(genomeDict), file(knownIndels), file(knownIndelsIndex) from Channel.value([
referenceMap.genomeFile,
referenceMap.genomeIndex,
referenceMap.genomeDict,
referenceMap.knownIndels,
referenceMap.knownIndelsIndex])
output:
set idPatient, file("*.real.bam"), file("*.real.bai") into realignedBam mode flatten
when: step == 'mapping' || step == 'realign'
script:
bams = bam.collect{"-I $it"}.join(' ')
known = knownIndels.collect{"-known $it"}.join(' ')
"""
java -Xmx${task.memory.toGiga()}g \
-jar \$GATK_HOME/GenomeAnalysisTK.jar \
-T IndelRealigner \
$bams \
-R $genomeFile \
-targetIntervals $intervals \
$known \
-nWayOut '.real.bam'
"""
}
realignedBam = realignedBam.map {
idPatient, bam, bai ->
tag = bam.baseName.tokenize('.')[0]
status = tag[-1..-1].toInteger()
idSample = tag.take(tag.length()-2)
[idPatient, status, idSample, bam, bai]
}
if (verbose) realignedBam = realignedBam.view {
"Realigned BAM to CreateRecalibrationTable:\n\
ID : ${it[0]}\tStatus: ${it[1]}\tSample: ${it[2]}\n\
Files : [${it[3].fileName}, ${it[4].fileName}]"
}
process CreateRecalibrationTable {
tag {idPatient + "-" + idSample}
publishDir directoryMap.nonRecalibrated, mode: 'copy'
input:
set idPatient, status, idSample, file(bam), file(bai) from realignedBam
set file(genomeFile), file(genomeIndex), file(genomeDict), file(dbsnp), file(dbsnpIndex), file(knownIndels), file(knownIndelsIndex), file(intervals) from Channel.value([
referenceMap.genomeFile,
referenceMap.genomeIndex,
referenceMap.genomeDict,
referenceMap.dbsnp,
referenceMap.dbsnpIndex,
referenceMap.knownIndels,
referenceMap.knownIndelsIndex,
referenceMap.intervals,
])
output:
set idPatient, status, idSample, file(bam), file(bai), file("${idSample}.recal.table") into recalibrationTable
set idPatient, status, idSample, val("${idSample}_${status}.md.real.bam"), val("${idSample}_${status}.md.real.bai"), val("${idSample}.recal.table") into recalibrationTableTSV
when: step == 'mapping' || step == 'realign'
script:
known = knownIndels.collect{ "-knownSites $it" }.join(' ')
"""
java -Xmx${task.memory.toGiga()}g \
-Djava.io.tmpdir="/tmp" \
-jar \$GATK_HOME/GenomeAnalysisTK.jar \
-T BaseRecalibrator \
-R $genomeFile \
-I $bam \
-L $intervals \
--disable_auto_index_creation_and_locking_when_reading_rods \
-knownSites $dbsnp \
$known \
-nct $task.cpus \
-l INFO \
-o ${idSample}.recal.table
"""
}
// Create a TSV file to restart from this step
recalibrationTableTSV.map { idPatient, status, idSample, bam, bai, recalTable ->
gender = patientGenders[idPatient]
"$idPatient\t$gender\t$status\t$idSample\t$directoryMap.nonRecalibrated/$bam\t$directoryMap.nonRecalibrated/$bai\t\t$directoryMap.nonRecalibrated/$recalTable\n"
}.collectFile(
name: 'nonRecalibrated.tsv', sort: true, storeDir: directoryMap.nonRecalibrated
)
if (step == 'recalibrate') recalibrationTable = bamFiles
if (verbose) recalibrationTable = recalibrationTable.view {
"Base recalibrated table for RecalibrateBam:\n\
ID : ${it[0]}\tStatus: ${it[1]}\tSample: ${it[2]}\n\
Files : [${it[3].fileName}, ${it[4].fileName}, ${it[5].fileName}]"
}
(bamForBamQC, bamForSamToolsStats, recalTables, recalibrationTableForHC, recalibrationTable) = recalibrationTable.into(5)
// Remove recalTable from Channels to match inputs for Process to avoid:
// WARN: Input tuple does not match input set cardinality declared by process...
bamForBamQC = bamForBamQC.map { it[0..4] }
bamForSamToolsStats = bamForSamToolsStats.map{ it[0..4] }
recalTables = recalTables.map { [it[0]] + it[2..-1] } // remove status
process RecalibrateBam {
tag {idPatient + "-" + idSample}
publishDir directoryMap.recalibrated, mode: 'copy'
input:
set idPatient, status, idSample, file(bam), file(bai), recalibrationReport from recalibrationTable
set file(genomeFile), file(genomeIndex), file(genomeDict), file(intervals) from Channel.value([
referenceMap.genomeFile,
referenceMap.genomeIndex,
referenceMap.genomeDict,
referenceMap.intervals,
])
output:
set idPatient, status, idSample, file("${idSample}.recal.bam"), file("${idSample}.recal.bai") into recalibratedBam, recalibratedBamForStats
set idPatient, status, idSample, val("${idSample}.recal.bam"), val("${idSample}.recal.bai") into recalibratedBamTSV
// HaplotypeCaller can do BQSR on the fly, so do not create a
// recalibrated BAM explicitly.
when: step != 'variantcalling' && explicitBqsrNeeded
script:
"""
java -Xmx${task.memory.toGiga()}g \
-jar \$GATK_HOME/GenomeAnalysisTK.jar \
-T PrintReads \
-R $genomeFile \
-I $bam \
-L $intervals \
--BQSR $recalibrationReport \
-o ${idSample}.recal.bam
"""
}
// Creating a TSV file to restart from this step
recalibratedBamTSV.map { idPatient, status, idSample, bam, bai ->
gender = patientGenders[idPatient]
"$idPatient\t$gender\t$status\t$idSample\t$directoryMap.recalibrated/$bam\t$directoryMap.recalibrated/$bai\n"
}.collectFile(
name: 'recalibrated.tsv', sort: true, storeDir: directoryMap.recalibrated
)
if (step == 'variantcalling') {
// assume input is recalibrated, ignore explicitBqsrNeeded
(recalibratedBam, recalTables) = bamFiles.into(2)
recalTables = recalTables.map{ it + [null] } // null recalibration table means: do not use --BQSR
(recalTables, recalibrationTableForHC) = recalTables.into(2)
recalTables = recalTables.map { [it[0]] + it[2..-1] } // remove status
} else if (!explicitBqsrNeeded) {
(bamForBamQC, bamForSamToolsStats, recalibratedBam) = recalibrationTableForHC.map { it[0..-2] }.into(3)
}
if (verbose) recalibratedBam = recalibratedBam.view {
"Recalibrated BAM for variant Calling:\n\
ID : ${it[0]}\tStatus: ${it[1]}\tSample: ${it[2]}\n\
Files : [${it[3].fileName}, ${it[4].fileName}]"
}
process RunSamtoolsStats {
tag {idPatient + "-" + idSample}
publishDir directoryMap.samtoolsStats, mode: 'copy'
input:
set idPatient, status, idSample, file(bam), file(bai) from bamForSamToolsStats
output:
file ("${bam}.samtools.stats.out") into samtoolsStatsReport
when: reports
script:
"""
samtools stats $bam > ${bam}.samtools.stats.out
"""
}
if (verbose) samtoolsStatsReport = samtoolsStatsReport.view {
"SAMTools stats report:\n\
File : [${it.fileName}]"
}
process RunBamQC {
tag {idPatient + "-" + idSample}
publishDir directoryMap.bamQC, mode: 'copy'
input:
set idPatient, status, idSample, file(bam), file(bai) from bamForBamQC
output:
file("$idSample") into bamQCreport
when: reports
script:
"""
qualimap --java-mem-size=${task.memory.toGiga()}G \
bamqc \
-bam $bam \
-outdir $idSample \
-outformat HTML
"""
}
if (verbose) bamQCreport = bamQCreport.view {
"BamQC report:\n\
Dir : [${it.fileName}]"
}
// Here we have a recalibrated bam set, but we need to separate the bam files based on patient status.
// The sample tsv config file which is formatted like: "subject status sample lane fastq1 fastq2"
// cf fastqFiles channel, I decided just to add _status to the sample name to have less changes to do.
// And so I'm sorting the channel if the sample match _0, then it's a normal sample, otherwise tumor.
// Then combine normal and tumor to get each possibilities
// ie. normal vs tumor1, normal vs tumor2, normal vs tumor3
// then copy this channel into channels for each variant calling
// I guess it will still work even if we have multiple normal samples
// separate recalibrateBams by status
bamsNormal = Channel.create()
bamsTumor = Channel.create()
recalibratedBam
.choice(bamsTumor, bamsNormal) {it[1] == 0 ? 1 : 0}
// Ascat, Strelka Germline & Manta Germline SV
bamsForAscat = Channel.create()
bamsForSingleManta = Channel.create()
bamsForSingleStrelka = Channel.create()
(bamsTumorTemp, bamsTumor) = bamsTumor.into(2)
(bamsNormalTemp, bamsNormal) = bamsNormal.into(2)
(bamsForAscat, bamsForSingleManta, bamsForSingleStrelka) = bamsNormalTemp.mix(bamsTumorTemp).into(3)
// Removing status because not relevant anymore
bamsNormal = bamsNormal.map { idPatient, status, idSample, bam, bai -> [idPatient, idSample, bam, bai] }
bamsTumor = bamsTumor.map { idPatient, status, idSample, bam, bai -> [idPatient, idSample, bam, bai] }
// We know that MuTect2 (and other somatic callers) are notoriously slow.
// To speed them up we are chopping the reference into smaller pieces.
// (see repeats/centromeres.list).
// Do variant calling by this intervals, and re-merge the VCFs.
// Since we are on a cluster, this can parallelize the variant call processes.
// And push down the variant call wall clock time significanlty.
process CreateIntervalBeds {
tag {intervals.fileName}
input:
file(intervals) from Channel.value(referenceMap.intervals)
output:
file '*.bed' into bedIntervals mode flatten
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 (intervals.getName().endsWith('.bed'))
"""
awk -vFS="\t" '{
t = \$5 # runtime estimate
if (t == "") {
# no runtime estimate in this row, assume default value
t = (\$3 - \$2) / ${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
"""
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 ->
final 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) / nucleotidesPerSecond
}
}
[duration, intervalFile]
}.toSortedList({ a, b -> b[0] <=> a[0] })
.flatten().collate(2)
.map{duration, intervalFile -> intervalFile}
if (verbose) bedIntervals = bedIntervals.view {
" Interv: ${it.baseName}"
}
(bamsNormalTemp, bamsNormal, bedIntervals) = generateIntervalsForVC(bamsNormal, bedIntervals)
(bamsTumorTemp, bamsTumor, bedIntervals) = generateIntervalsForVC(bamsTumor, bedIntervals)
// HaplotypeCaller
bamsForHC = bamsNormalTemp.mix(bamsTumorTemp)
bedIntervals = bedIntervals.tap { intervalsTemp }
recalTables = recalTables
.spread(intervalsTemp)
.map { patient, sample, bam, bai, recalTable, intervalBed ->
[patient, sample, bam, bai, intervalBed, recalTable] }
// re-associate the BAMs and samples with the recalibration table
bamsForHC = bamsForHC
.phase(recalTables) { it[0..4] }
.map { it1, it2 -> it1 + [it2[6]] }
bamsAll = bamsNormal.combine(bamsTumor)
// Since idPatientNormal and idPatientTumor are the same
// It's removed from bamsAll Channel (same for genderNormal)
// /!\ It is assumed that every sample are from the same patient
bamsAll = bamsAll.map {
idPatientNormal, idSampleNormal, bamNormal, baiNormal, idPatientTumor, idSampleTumor, bamTumor, baiTumor ->
[idPatientNormal, idSampleNormal, bamNormal, baiNormal, idSampleTumor, bamTumor, baiTumor]
}
// Manta and Strelka
(bamsForManta, bamsForStrelka, bamsAll) = bamsAll.into(3)
bamsTumorNormalIntervals = bamsAll.spread(bedIntervals)
// MuTect1, MuTect2, FreeBayes
(bamsFMT1, bamsFMT2, bamsFFB) = bamsTumorNormalIntervals.into(3)
process RunHaplotypecaller {
tag {idSample + "-" + intervalBed.baseName}
input:
set idPatient, idSample, file(bam), file(bai), file(intervalBed), recalTable from bamsForHC //Are these values `ped to bamNormal already?
set file(genomeFile), file(genomeIndex), file(genomeDict), file(dbsnp), file(dbsnpIndex) from Channel.value([
referenceMap.genomeFile,
referenceMap.genomeIndex,
referenceMap.genomeDict,
referenceMap.dbsnp,
referenceMap.dbsnpIndex
])
output:
set val("gvcf-hc"), idPatient, idSample, idSample, file("${intervalBed.baseName}_${idSample}.g.vcf") into hcGenomicVCF
set idPatient, idSample, file(intervalBed), file("${intervalBed.baseName}_${idSample}.g.vcf") into vcfsToGenotype
when: 'haplotypecaller' in tools
script:
BQSR = (recalTable != null) ? "--BQSR $recalTable" : ''
"""
java -Xmx${task.memory.toGiga()}g \
-jar \$GATK_HOME/GenomeAnalysisTK.jar \
-T HaplotypeCaller \
--emitRefConfidence GVCF \
-pairHMM LOGLESS_CACHING \
-R $genomeFile \
--dbsnp $dbsnp \
$BQSR \
-I $bam \
-L $intervalBed \
--disable_auto_index_creation_and_locking_when_reading_rods \
-o ${intervalBed.baseName}_${idSample}.g.vcf
"""
}
hcGenomicVCF = hcGenomicVCF.groupTuple(by:[0,1,2,3])
if (!gvcf) {hcGenomicVCF.close()}
process RunGenotypeGVCFs {
tag {idSample + "-" + intervalBed.baseName}
input:
set idPatient, idSample, file(intervalBed), file(gvcf) from vcfsToGenotype
set file(genomeFile), file(genomeIndex), file(genomeDict), file(dbsnp), file(dbsnpIndex) from Channel.value([
referenceMap.genomeFile,
referenceMap.genomeIndex,
referenceMap.genomeDict,
referenceMap.dbsnp,
referenceMap.dbsnpIndex
])
output:
set val("haplotypecaller"), idPatient, idSample, idSample, file("${intervalBed.baseName}_${idSample}.vcf") into hcGenotypedVCF
when: 'haplotypecaller' in tools
script:
// Using -L is important for speed
"""
java -Xmx${task.memory.toGiga()}g \
-jar \$GATK_HOME/GenomeAnalysisTK.jar \
-T GenotypeGVCFs \
-R $genomeFile \
-L $intervalBed \
--dbsnp $dbsnp \
--variant $gvcf \
--disable_auto_index_creation_and_locking_when_reading_rods \
-o ${intervalBed.baseName}_${idSample}.vcf
"""
}
hcGenotypedVCF = hcGenotypedVCF.groupTuple(by:[0,1,2,3])
process RunMutect1 {
tag {idSampleTumor + "_vs_" + idSampleNormal + "-" + intervalBed.baseName}
input:
set idPatient, idSampleNormal, file(bamNormal), file(baiNormal), idSampleTumor, file(bamTumor), file(baiTumor), file(intervalBed) from bamsFMT1
set file(genomeFile), file(genomeIndex), file(genomeDict), file(dbsnp), file(dbsnpIndex), file(cosmic), file(cosmicIndex) from Channel.value([
referenceMap.genomeFile,
referenceMap.genomeIndex,
referenceMap.genomeDict,
referenceMap.dbsnp,
referenceMap.dbsnpIndex,
referenceMap.cosmic,
referenceMap.cosmicIndex
])
output:
set val("mutect1"), idPatient, idSampleNormal, idSampleTumor, file("${intervalBed.baseName}_${idSampleTumor}_vs_${idSampleNormal}.vcf") into mutect1Output
when: 'mutect1' in tools
script:
"""
java -Xmx${task.memory.toGiga()}g \
-jar \$MUTECT_HOME/muTect.jar \
-T MuTect \
-R $genomeFile \
--cosmic $cosmic \
--dbsnp $dbsnp \
-I:normal $bamNormal \
-I:tumor $bamTumor \
-L $intervalBed \
--disable_auto_index_creation_and_locking_when_reading_rods \
--out ${intervalBed.baseName}_${idSampleTumor}_vs_${idSampleNormal}.call_stats.out \
--vcf ${intervalBed.baseName}_${idSampleTumor}_vs_${idSampleNormal}.vcf
"""
}
mutect1Output = mutect1Output.groupTuple(by:[0,1,2,3])
process RunMutect2 {
tag {idSampleTumor + "_vs_" + idSampleNormal + "-" + intervalBed.baseName}
input:
set idPatient, idSampleNormal, file(bamNormal), file(baiNormal), idSampleTumor, file(bamTumor), file(baiTumor), file(intervalBed) from bamsFMT2
set file(genomeFile), file(genomeIndex), file(genomeDict), file(dbsnp), file(dbsnpIndex), file(cosmic), file(cosmicIndex) from Channel.value([
referenceMap.genomeFile,
referenceMap.genomeIndex,
referenceMap.genomeDict,
referenceMap.dbsnp,
referenceMap.dbsnpIndex,
referenceMap.cosmic,
referenceMap.cosmicIndex
])
output:
set val("mutect2"), idPatient, idSampleNormal, idSampleTumor, file("${intervalBed.baseName}_${idSampleTumor}_vs_${idSampleNormal}.vcf") into mutect2Output
when: 'mutect2' in tools
script:
"""
java -Xmx${task.memory.toGiga()}g \
-jar \$GATK_HOME/GenomeAnalysisTK.jar \
-T MuTect2 \
-R $genomeFile \
--cosmic $cosmic \
--dbsnp $dbsnp \
-I:normal $bamNormal \
-I:tumor $bamTumor \
--disable_auto_index_creation_and_locking_when_reading_rods \
-L $intervalBed \
-o ${intervalBed.baseName}_${idSampleTumor}_vs_${idSampleNormal}.vcf
"""
}
mutect2Output = mutect2Output.groupTuple(by:[0,1,2,3])
process RunFreeBayes {
tag {idSampleTumor + "_vs_" + idSampleNormal + "-" + intervalBed.baseName}
input:
set idPatient, idSampleNormal, file(bamNormal), file(baiNormal), idSampleTumor, file(bamTumor), file(baiTumor), file(intervalBed) from bamsFFB
file(genomeFile) from Channel.value(referenceMap.genomeFile)
output:
set val("freebayes"), idPatient, idSampleNormal, idSampleTumor, file("${intervalBed.baseName}_${idSampleTumor}_vs_${idSampleNormal}.vcf") into freebayesOutput
when: 'freebayes' in tools
script:
"""
freebayes \
-f $genomeFile \
--pooled-continuous \
--pooled-discrete \
--genotype-qualities \
--report-genotype-likelihood-max \
--allele-balance-priors-off \
--min-alternate-fraction 0.03 \
--min-repeat-entropy 1 \
--min-alternate-count 2 \
-t $intervalBed \
$bamTumor \
$bamNormal > ${intervalBed.baseName}_${idSampleTumor}_vs_${idSampleNormal}.vcf
"""
}
freebayesOutput = freebayesOutput.groupTuple(by:[0,1,2,3])
// we are merging the VCFs that are called separatelly for different intervals
// so we can have a single sorted VCF containing all the calls for a given caller
vcfsToMerge = hcGenomicVCF.mix(hcGenotypedVCF, mutect1Output, mutect2Output, freebayesOutput)
if (verbose) vcfsToMerge = vcfsToMerge.view {
"VCFs To be merged:\n\
Tool : ${it[0]}\tID : ${it[1]}\tSample: [${it[3]}, ${it[2]}]\n\
Files : ${it[4].fileName}"
}