forked from GenomicsNX/CAW
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.nf
1657 lines (1373 loc) · 58.1 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
/*
vim: syntax=groovy
-*- mode: groovy;-*-
================================================================================
= 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 <[email protected]> [@Sebastian-D]
Jesper Eisfeldt <[email protected]> [@J35P312]
Maxime Garcia <[email protected]> [@MaxUlysse]
Szilveszter Juhos <[email protected]> [@szilvajuhos]
Max Käller <[email protected]> [@gulfshores]
Malin Larsson <[email protected]> [@malinlarsson]
Marcel Martin <[email protected]> [@marcelm]
Björn Nystedt <[email protected]> [@bjornnystedt]
Pall Olason <[email protected]> [@pallolason]
Pelin Sahlén <[email protected]> [@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
- MergeBams - Merge BAMs if multilane samples
- MarkDuplicates - Mark Duplicates
- RealignerTargetCreator - Create realignment target intervals
- IndelRealigner - Realign BAMs as T/N pair
- CreateRecalibrationTable - Create Recalibration Table
- RecalibrateBam - Recalibrate Bam
- RunSamtoolsStats - Run Samtools stats on recalibrated BAM files
- RunHaplotypecaller - 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)
- RunVardict - Run VarDict for Variant Calling (Parallelized processes)
- ConcatVCF - Merge results from HaplotypeCaller, MuTect1, MuTect2 and VarDict
- RunStrelka - Run Strelka for Variant Calling
- RunManta - Run Manta for Structural Variant Calling
- RunAlleleCount - Run AlleleCount to prepare for ASCAT
- RunConvertAlleleCounts - Run convertAlleleCounts to prepare for ASCAT
- RunAscat - Run ASCAT for CNV
- 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.1'
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>'}
if (params.help) {
help_message(version, grabRevision())
exit 1
}
if (params.version) {
version_message(version, grabRevision())
exit 1
}
step = params.step
tools = params.tools ? params.tools.split(',').collect {it.trim()} : []
directoryMap = defineDirectoryMap()
referenceMap = defineReferenceMap()
stepList = defineStepList()
toolList = defineToolList()
verbose = params.verbose
if (!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 (!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 (!checkParameterList(tools,toolList)) {exit 1, 'Unknown tool(s), see --help for more information'}
tsvPath = ''
if (params.test) {
if (params.genome == "GRCh37") {
referenceMap.intervals = file("$workflow.projectDir/repeats/tiny.list")
}
testTsvPaths = [
'preprocessing': "$workflow.projectDir/data/tsv/tiny.tsv",
'realign': "$workflow.launchDir/$directoryMap.nonRealigned/nonRealigned.tsv",
'recalibrate': "$workflow.launchDir/$directoryMap.nonRecalibrated/nonRecalibrated.tsv",
'skipPreprocessing': "$workflow.launchDir/$directoryMap.recalibrated/recalibrated.tsv"
]
tsvPath = testTsvPaths[params.step]
} else if (params.sample) {
tsvPath = params.sample
}
// Set up the fastqFiles and bamFiles channels. One of them remains empty
fastqFiles = Channel.empty()
bamFiles = Channel.empty()
if (tsvPath) {
tsvFile = file(tsvPath)
switch (step) {
case 'preprocessing': fastqFiles = extractFastq(tsvFile); break
case 'realign': bamFiles = extractBams(tsvFile); break
case 'recalibrate': bamFiles = extractRecal(tsvFile); break
case 'skipPreprocessing': bamFiles = extractBams(tsvFile); break
default: exit 1, "Unknown step $step"
}
} else if (params.sampleDir) {
if (step != 'preprocessing') exit 1, '--sampleDir does not support steps other than "preprocessing"'
fastqFiles = extractFastqFromDir(params.sampleDir)
tsvFile = params.sampleDir // used in the reports
}
verbose ? fastqFiles = fastqFiles.view {"FASTQ files to preprocess: $it"} : ''
verbose ? bamFiles = bamFiles.view {"BAM files to process: $it"} : ''
start_message(version, grabRevision())
/*
================================================================================
= P R O C E S S E S =
================================================================================
*/
(fastqFiles, fastqFilesforFastQC) = fastqFiles.into(2)
verbose ? fastqFilesforFastQC = fastqFilesforFastQC.view {"FASTQ files for FastQC: $it"} : ''
process RunFastQC {
tag {idPatient + "-" + idRun}
publishDir directoryMap.fastQC, mode: 'copy'
input:
set idPatient, gender, status, idSample, idRun, file(fastqFile1), file(fastqFile2) from fastqFilesforFastQC
output:
file "*_fastqc.{zip,html}" into fastQCreport
when: step == 'preprocessing' && 'MultiQC' in tools
script:
"""
fastqc -q $fastqFile1 $fastqFile2
"""
}
verbose ? fastQCreport = fastQCreport.view {"FastQC report: $it"} : ''
process MapReads {
tag {idPatient + "-" + idRun}
input:
set idPatient, gender, status, idSample, idRun, file(fastqFile1), file(fastqFile2) from fastqFiles
set file(genomeFile), file(bwaIndex) from Channel.value([referenceMap.genomeFile, referenceMap.bwaIndex])
output:
set idPatient, gender, status, idSample, idRun, file("${idRun}.bam") into mappedBam
when: step == 'preprocessing'
script:
readGroup = "@RG\\tID:$idRun\\tPU:$idRun\\tSM:$idSample\\tLB:$idSample\\tPL:illumina"
// adjust mismatch penalty for tumor samples
extra = status == 1 ? "-B 3 " : ""
"""
set -euo pipefail
bwa mem -R \"$readGroup\" ${extra}-t $task.cpus -M \
$genomeFile $fastqFile1 $fastqFile2 | \
samtools sort --threads $task.cpus -m 4G - > ${idRun}.bam
"""
}
verbose ? mappedBam = mappedBam.view {"BAM file to sort into group or single: $it"} : ''
// 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,3])
.choice(singleBam, groupedBam) {it[4].size() > 1 ? 1 : 0}
singleBam = singleBam.map {
idPatient, gender, status, idSample, idRun, bam ->
[idPatient, gender, status, idSample, bam]
}
verbose ? groupedBam = groupedBam.view {"Grouped BAMs to merge: $it"} : ''
process MergeBams {
tag {idPatient + "-" + idSample}
input:
set idPatient, gender, status, idSample, idRun, file(bam) from groupedBam
output:
set idPatient, gender, status, idSample, file("${idSample}.bam") into mergedBam
when: step == 'preprocessing'
script:
"""
samtools merge --threads $task.cpus ${idSample}.bam $bam
"""
}
verbose ? singleBam = singleBam.view {"Single BAM: $it"} : ''
verbose ? mergedBam = mergedBam.view {"Merged BAM: $it"} : ''
mergedBam = mergedBam.mix(singleBam)
verbose ? mergedBam = mergedBam.view {"BAM for MarkDuplicates: $it"} : ''
process MarkDuplicates {
tag {idPatient + "-" + idSample}
publishDir '.', saveAs: { it == "${bam}.metrics" ? "$directoryMap.markDuplicatesQC/$it" : "$directoryMap.nonRealigned/$it" }, mode: 'copy'
input:
set idPatient, gender, status, idSample, file(bam) from mergedBam
output:
set idPatient, gender, val("${idSample}_${status}"), file("${idSample}_${status}.md.bam"), file("${idSample}_${status}.md.bai") into duplicates
set idPatient, gender, status, idSample, val("${idSample}_${status}.md.bam"), val("${idSample}_${status}.md.bai") into markDuplicatesTSV
file ("${bam}.metrics") into markDuplicatesReport
when: step == 'preprocessing'
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, gender, status, idSample, bam, bai ->
"$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 = step == 'preprocessing' ? duplicates.groupTuple(by:[0,1]) : Channel.empty()
duplicatesGrouped = step == 'realign' ? bamFiles.map{
idPatient, gender, status, idSample, bam, bai ->
[idPatient, gender, "${idSample}_${status}", bam, bai]
}.groupTuple(by:[0,1]) : duplicatesGrouped
// The duplicatesGrouped channel is duplicated
// one copy goes to the RealignerTargetCreator process
// and the other to the IndelRealigner process
(duplicatesInterval, duplicatesRealign) = duplicatesGrouped.into(2)
verbose ? duplicatesInterval = duplicatesInterval.view {"BAMs for RealignerTargetCreator: $it"} : ''
verbose ? duplicatesRealign = duplicatesRealign.view {"BAMs to phase: $it"} : ''
verbose ? markDuplicatesReport = markDuplicatesReport.view {"MarkDuplicates report: $it"} : ''
// 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, gender, idSample_status, 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, gender, file("${idPatient}.intervals") into intervals
when: step == 'preprocessing' || 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
"""
}
verbose ? intervals = intervals.view {"Intervals to phase: $it"} : ''
bamsAndIntervals = duplicatesRealign
.phase(intervals)
.map{duplicatesRealign, intervals ->
tuple(
duplicatesRealign[0],
duplicatesRealign[1],
duplicatesRealign[2],
duplicatesRealign[3],
duplicatesRealign[4],
intervals[2]
)}
verbose ? bamsAndIntervals = bamsAndIntervals.view {"BAMs and Intervals phased for IndelRealigner: $it"} : ''
// use nWayOut to split into T/N pair again
process IndelRealigner {
tag {idPatient}
input:
set idPatient, gender, idSample_status, 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, gender, file("*.real.bam"), file("*.real.bai") into realignedBam mode flatten
when: step == 'preprocessing' || 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 = retrieveStatus(realignedBam)
verbose ? realignedBam = realignedBam.view {"Realigned BAM to CreateRecalibrationTable: $it"} : ''
process CreateRecalibrationTable {
tag {idPatient + "-" + idSample}
publishDir directoryMap.nonRecalibrated, mode: 'copy'
input:
set idPatient, gender, 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, gender, status, idSample, file(bam), file(bai), file("${idSample}.recal.table") into recalibrationTable
set idPatient, gender, status, idSample, val("${idSample}_${status}.md.real.bam"), val("${idSample}_${status}.md.real.bai"), val("${idSample}.recal.table") into recalibrationTableTSV
when: step == 'preprocessing' || 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 \
--disable_auto_index_creation_and_locking_when_reading_rods \
-knownSites $dbsnp \
$known \
-nct $task.cpus \
-L $intervals \
-l INFO \
-o ${idSample}.recal.table
"""
}
// Creating a TSV file to restart from this step
recalibrationTableTSV.map { idPatient, gender, status, idSample, bam, bai, recalTable ->
"$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
)
recalibrationTable = step == 'recalibrate' ? bamFiles : recalibrationTable
verbose ? recalibrationTable = recalibrationTable.view {"Base recalibrated table for RecalibrateBam: $it"} : ''
process RecalibrateBam {
tag {idPatient + "-" + idSample}
publishDir directoryMap.recalibrated, mode: 'copy'
input:
set idPatient, gender, 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, gender, status, idSample, file("${idSample}.recal.bam"), file("${idSample}.recal.bai") into recalibratedBam
set idPatient, gender, status, idSample, val("${idSample}.recal.bam"), val("${idSample}.recal.bai") into recalibratedBamTSV
when: step != 'skipPreprocessing'
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, gender, status, idSample, bam, bai ->
"$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
)
recalibratedBam = step == 'skipPreprocessing' ? bamFiles : recalibratedBam
verbose ? recalibratedBam = recalibratedBam.view {"Recalibrated BAM for variant Calling: $it"} : ''
(recalibratedBam, recalibratedBamForStats) = recalibratedBam.into(2)
process RunSamtoolsStats {
tag {idPatient + "-" + idSample}
publishDir directoryMap.samtoolsStats, mode: 'copy'
input:
set idPatient, gender, status, idSample, file(bam), file(bai) from recalibratedBamForStats
output:
file ("${bam}.samtools.stats.out") into recalibratedBamReport
when: 'MultiQC' in tools
script:
"""
samtools stats $bam > ${bam}.samtools.stats.out
"""
}
verbose ? recalibratedBamReport = recalibratedBamReport.view {"BAM Stats: $it"} : ''
// 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 spread normal over 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[2] == 0 ? 1 : 0}
// Removing status because not relevant anymore
bamsNormal = bamsNormal.map { idPatient, gender, status, idSample, bam, bai -> [idPatient, gender, idSample, bam, bai] }
verbose ? bamsNormal = bamsNormal.view {"Normal BAM for variant Calling: $it"} : ''
bamsTumor = bamsTumor.map { idPatient, gender, status, idSample, bam, bai -> [idPatient, gender, idSample, bam, bai] }
verbose ? bamsTumor = bamsTumor.view {"Tumor BAM for variant Calling: $it"} : ''
// We know that MuTect2 (and other somatic callers) are notoriously slow. To speed them up we are chopping the reference into
// smaller pieces at centromeres (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.
// in fact we need two channels: one for the actual genomic region, and an other for names
// without ":", as nextflow is not happy with them (will report as a failed process).
// For region 1:1-2000 the output file name will be something like 1_1-2000_Sample_name.mutect2.vcf
// from the "1:1-2000" string make ["1:1-2000","1_1-2000"]
// define intervals file by --intervals
intervals = Channel.from(file(referenceMap.intervals).readLines())
gI = intervals.map{[it,it.replaceFirst(/\:/,'_')]}
(bamsNormalTemp, bamsNormal, gI) = generateIntervalsForVC(bamsNormal, gI)
(bamsTumorTemp, bamsTumor, gI) = generateIntervalsForVC(bamsTumor, gI)
// HaplotypeCaller
bamsFHC = bamsNormalTemp.mix(bamsTumorTemp)
verbose ? bamsFHC = bamsFHC.view {"Bams with Intervals for HaplotypeCaller: $it"} : ''
(bamsNormalTemp, bamsNormal) = bamsNormal.into(2)
(bamsTumorTemp, bamsTumor) = bamsTumor.into(2)
bamsNormalTemp = bamsNormalTemp.map { idPatient, gender, idSample, bam, bai -> [idPatient, gender, 0, idSample, bam, bai] }
bamsTumorTemp = bamsTumorTemp.map { idPatient, gender, idSample, bam, bai -> [idPatient, gender, 1, idSample, bam, bai] }
bamsForAscat = Channel.create()
bamsForAscat = bamsNormalTemp.mix(bamsTumorTemp)
verbose ? bamsForAscat = bamsForAscat.view {"Bams for Ascat: $it"} : ''
bamsAll = bamsNormal.spread(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, genderNormal, idSampleNormal, bamNormal, baiNormal, idPatientTumor, genderTumor, idSampleTumor, bamTumor, baiTumor ->
[idPatientNormal, genderNormal, idSampleNormal, bamNormal, baiNormal, idSampleTumor, bamTumor, baiTumor]
}
verbose ? bamsAll = bamsAll.view {"Mapped Recalibrated BAM for variant Calling: $it"} : ''
// MuTect1
(bamsFMT1, bamsAll, gI) = generateIntervalsForVC(bamsAll, gI)
verbose ? bamsFMT1 = bamsFMT1.view {"Bams with Intervals for MuTect1: $it"} : ''
// MuTect2
(bamsFMT2, bamsAll, gI) = generateIntervalsForVC(bamsAll, gI)
verbose ? bamsFMT2 = bamsFMT2.view {"Bams with Intervals for MuTect2: $it"} : ''
// FreeBayes
(bamsFFB, bamsAll, gI) = generateIntervalsForVC(bamsAll, gI)
verbose ? bamsFFB = bamsFFB.view {"Bams with Intervals for FreeBayes: $it"} : ''
// VarDict
(bamsFVD, bamsAll, gI) = generateIntervalsForVC(bamsAll, gI)
verbose ? bamsFVD = bamsFVD.view {"Bams with Intervals for VarDict: $it"} : ''
(bamsForManta, bamsForStrelka) = bamsAll.into(2)
verbose ? bamsForManta = bamsForManta.view {"Bams for Manta: $it"} : ''
verbose ? bamsForStrelka = bamsForStrelka.view {"Bams for Strelka: $it"} : ''
process RunHaplotypecaller {
tag {idPatient + "-" + idSample + "-" + gen_int}
input:
set idPatient, gender, idSample, file(bam), file(bai), genInt, gen_int from bamsFHC //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("haplotypecaller"), idPatient, gender, idSample, val("${gen_int}_${idSample}"), file("${gen_int}_${idSample}.g.vcf") into hcVCF
when: 'HaplotypeCaller' in tools
script:
"""
java -Xmx${task.memory.toGiga()}g \
-jar \$GATK_HOME/GenomeAnalysisTK.jar \
-T HaplotypeCaller \
--emitRefConfidence GVCF \
-pairHMM LOGLESS_CACHING \
-R $genomeFile \
--dbsnp $dbsnp \
-I $bam \
-L \"$genInt\" \
--disable_auto_index_creation_and_locking_when_reading_rods \
-o ${gen_int}_${idSample}.g.vcf
"""
}
hcVCF = hcVCF.map {
variantCaller, idPatient, gender, idSample, tag, vcfFile ->
[variantCaller, idPatient, gender, idSample, idSample, tag, vcfFile]
}.groupTuple(by:[0,1,2,3,4])
verbose ? hcVCF = hcVCF.view {"HaplotypeCaller output: $it"} : ''
process RunMutect1 {
tag {idPatient + "-" + idSampleTumor + "-" + gen_int}
input:
set idPatient, gender, idSampleNormal, file(bamNormal), file(baiNormal), idSampleTumor, file(bamTumor), file(baiTumor), genInt, gen_int 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, gender, idSampleNormal, idSampleTumor, val("${gen_int}_${idSampleTumor}_vs_${idSampleNormal}"), file("${gen_int}_${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 \"$genInt\" \
--disable_auto_index_creation_and_locking_when_reading_rods \
--out ${gen_int}_${idSampleTumor}_vs_${idSampleNormal}.call_stats.out \
--vcf ${gen_int}_${idSampleTumor}_vs_${idSampleNormal}.vcf
"""
}
mutect1Output = mutect1Output.groupTuple(by:[0,1,2,3,4])
verbose ? mutect1Output = mutect1Output.view {"MuTect1 output: $it"} : ''
process RunMutect2 {
tag {idPatient + "-" + idSampleTumor + "-" + gen_int}
input:
set idPatient, gender, idSampleNormal, file(bamNormal), file(baiNormal), idSampleTumor, file(bamTumor), file(baiTumor), genInt, gen_int 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, gender, idSampleNormal, idSampleTumor, val("${gen_int}_${idSampleTumor}_vs_${idSampleNormal}"), file("${gen_int}_${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 \"$genInt\" \
-o ${gen_int}_${idSampleTumor}_vs_${idSampleNormal}.vcf
"""
}
mutect2Output = mutect2Output.groupTuple(by:[0,1,2,3,4])
verbose ? mutect2Output = mutect2Output.view {"MuTect2 output: $it"} : ''
process RunFreeBayes {
tag {idPatient + "-" + idSampleTumor + "-" + gen_int}
input:
set idPatient, gender, idSampleNormal, file(bamNormal), file(baiNormal), idSampleTumor, file(bamTumor), file(baiTumor), genInt, gen_int from bamsFFB
file(genomeFile) from Channel.value(referenceMap.genomeFile)
output:
set val("freebayes"), idPatient, gender, idSampleNormal, idSampleTumor, val("${gen_int}_${idSampleTumor}_vs_${idSampleNormal}"), file("${gen_int}_${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 \
-r \"$genInt\" \
$bamTumor \
$bamNormal > ${gen_int}_${idSampleTumor}_vs_${idSampleNormal}.vcf
"""
}
freebayesOutput = freebayesOutput.groupTuple(by:[0,1,2,3,4])
verbose ? freebayesOutput = freebayesOutput.view {"FreeBayes output: $it"} : ''
process RunVardict {
tag {idPatient + "-" + idSampleTumor + "-" + gen_int}
input:
set idPatient, gender, idSampleNormal, file(bamNormal), file(baiNormal), idSampleTumor, file(bamTumor), file(baiTumor), genInt, gen_int from bamsFVD
set file(genomeFile), file(genomeIndex), file(genomeDict) from Channel.value([
referenceMap.genomeFile,
referenceMap.genomeIndex,
referenceMap.genomeDict
])
output:
set val("vardict"), idPatient, gender, idSampleNormal, idSampleTumor, val("${gen_int}_${idSampleTumor}_vs_${idSampleNormal}"), file("${gen_int}_${idSampleTumor}_vs_${idSampleNormal}.out") into vardictOutput
when: 'VarDict' in tools
script:
"""
${referenceMap.vardictHome}/vardict.pl \
-G $genomeFile \
-f 0.01 -N $bamTumor \
-b "$bamTumor|$bamNormal" \
-z 1 -F 0x500 \
-c 1 -S 2 -E 3 -g 4 \
-R $genInt > ${gen_int}_${idSampleTumor}_vs_${idSampleNormal}.out
"""
}
vardictOutput = vardictOutput.groupTuple(by:[0,1,2,3,4])
verbose ? vardictOutput = vardictOutput.view {"vardictOutput output: $it"} : ''
// 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 = hcVCF.mix(mutect1Output, mutect2Output, freebayesOutput, vardictOutput)
verbose ? vcfsToMerge = vcfsToMerge.view {"VCFs To be merged: $it"} : ''
process ConcatVCF {
tag {variantCaller == 'haplotypecaller' ? idPatient + "-" + variantCaller + "-" + idSampleNormal : idPatient + "-" + variantCaller + "-" + idSampleNormal + "-" + idSampleTumor}
publishDir "${directoryMap."$variantCaller"}", mode: 'copy'
input:
set variantCaller, idPatient, gender, idSampleNormal, idSampleTumor, tag, file(vcFiles) from vcfsToMerge
set file(genomeFile), file(genomeIndex), file(genomeDict) from Channel.value([
referenceMap.genomeFile,
referenceMap.genomeIndex,
referenceMap.genomeDict
])
output:
set variantCaller, idPatient, gender, idSampleNormal, idSampleTumor, file("*.vcf.gz") into vcfConcatenated
when: 'HaplotypeCaller' in tools || 'MuTect1' in tools || 'MuTect2' in tools || 'FreeBayes' in tools || 'VarDict' in tools
script:
outputFile = variantCaller == 'haplotypecaller' ? "${variantCaller}_${idSampleNormal}.vcf" : "${variantCaller}_${idSampleTumor}_vs_${idSampleNormal}.vcf"
vcfFiles = vcFiles.collect{" $it"}.join(' ')
if (variantCaller == 'vardict')
"""
set -euo pipefail
for i in $vcFiles ;do
cat \$i | ${referenceMap.vardictHome}/VarDict/testsomatic.R >> testsomatic.out
done
${referenceMap.vardictHome}/VarDict/var2vcf_somatic.pl \
-f 0.01 \
-N "${idSampleTumor}_vs_${idSampleNormal}" testsomatic.out > $outputFile
"""
else if (variantCaller == 'mutect2' || variantCaller == 'mutect1' || variantCaller == 'haplotypecaller' || variantCaller == 'freebayes')
"""
set -euo pipefail
# first make a header from one of the VCF intervals
# get rid of interval information only from the GATK command-line, but leave the rest
awk '/^#/{print}' `ls *vcf| head -1` | \
awk '!/GATKCommandLine/{print}/GATKCommandLine/{for(i=1;i<=NF;i++){if(\$i!~/intervals=/ && \$i !~ /out=/){printf("%s ",\$i)}}printf("\\n")}' \
> header
## concatenate calls
rm -rf raw_calls
for f in *vcf; do
awk '!/^#/{print}' \$f >> raw_calls
done
cat header raw_calls > unsorted.vcf
java -jar \${PICARD_HOME}/picard.jar SortVcf I=unsorted.vcf O=$outputFile SEQUENCE_DICTIONARY=$genomeDict
rm unsorted.vcf
gzip -v $outputFile
"""
}
verbose ? vcfConcatenated = vcfConcatenated.view {"VCF concatenated: $it"} : ''
process RunStrelka {
tag {idPatient + "-" + idSampleTumor}
publishDir directoryMap.strelka, mode: 'copy'
input:
set idPatient, gender, idSampleNormal, file(bamNormal), file(baiNormal), idSampleTumor, file(bamTumor), file(baiTumor) from bamsForStrelka
set file(genomeFile), file(genomeIndex), file(genomeDict) from Channel.value([
referenceMap.genomeFile,
referenceMap.genomeIndex,
referenceMap.genomeDict
])
output:
set val("strelka"), idPatient, gender, idSampleNormal, idSampleTumor, file("*.vcf") into strelkaOutput
when: 'Strelka' in tools
script:
"""
set -euo pipefail
tumorPath=`readlink $bamTumor`
normalPath=`readlink $bamNormal`
genomeFile=`readlink $genomeFile`
\$STRELKA_INSTALL_DIR/bin/configureStrelkaWorkflow.pl \
--tumor \$tumorPath \
--normal \$normalPath \
--ref \$genomeFile \
--config \$STRELKA_INSTALL_DIR/etc/strelka_config_bwa_default.ini \
--output-dir strelka
cd strelka
make -j $task.cpus
cd ..
mv strelka/results/all.somatic.indels.vcf Strelka_${idSampleTumor}_vs_${idSampleNormal}_all_somatic_indels.vcf
mv strelka/results/all.somatic.snvs.vcf Strelka_${idSampleTumor}_vs_${idSampleNormal}_all_somatic_snvs.vcf
mv strelka/results/passed.somatic.indels.vcf Strelka_${idSampleTumor}_vs_${idSampleNormal}_passed_somatic_indels.vcf
mv strelka/results/passed.somatic.snvs.vcf Strelka_${idSampleTumor}_vs_${idSampleNormal}_passed_somatic_snvs.vcf
"""
}
verbose ? strelkaOutput = strelkaOutput.view {"Strelka output: $it"} : ''
process RunManta {
tag {idPatient + "-" + idSampleTumor}
publishDir directoryMap.manta, mode: 'copy'
input:
set idPatient, gender, idSampleNormal, file(bamNormal), file(baiNormal), idSampleTumor, file(bamTumor), file(baiTumor) from bamsForManta
set file(genomeFile), file(genomeIndex) from Channel.value([
referenceMap.genomeFile,
referenceMap.genomeIndex
])
output:
set val("manta"), idPatient, gender, idSampleNormal, idSampleTumor, file("Manta_${idSampleTumor}_vs_${idSampleNormal}.somaticSV.vcf"),file("Manta_${idSampleTumor}_vs_${idSampleNormal}.candidateSV.vcf"),file("Manta_${idSampleTumor}_vs_${idSampleNormal}.diploidSV.vcf"),file("Manta_${idSampleTumor}_vs_${idSampleNormal}.candidateSmallIndels.vcf") into mantaOutput
when: 'Manta' in tools
script:
"""
set -eo pipefail
ln -s $bamNormal Normal.bam
ln -s $bamTumor Tumor.bam
ln -s $baiNormal Normal.bam.bai
ln -s $baiTumor Tumor.bam.bai
\$MANTA_INSTALL_PATH/bin/configManta.py --normalBam Normal.bam --tumorBam Tumor.bam --reference $genomeFile --runDir MantaDir
python MantaDir/runWorkflow.py -m local -j $task.cpus
gunzip -c MantaDir/results/variants/somaticSV.vcf.gz > Manta_${idSampleTumor}_vs_${idSampleNormal}.somaticSV.vcf
gunzip -c MantaDir/results/variants/candidateSV.vcf.gz > Manta_${idSampleTumor}_vs_${idSampleNormal}.candidateSV.vcf
gunzip -c MantaDir/results/variants/diploidSV.vcf.gz > Manta_${idSampleTumor}_vs_${idSampleNormal}.diploidSV.vcf
gunzip -c MantaDir/results/variants/candidateSmallIndels.vcf.gz > Manta_${idSampleTumor}_vs_${idSampleNormal}.candidateSmallIndels.vcf
"""
}
verbose ? mantaOutput = mantaOutput.view {"Manta output: $it"} : ''
// Run commands and code from Malin Larsson
// Based on Jesper Eisfeldt's code
process RunAlleleCount {
tag {idPatient + "-" + idSample}
input:
set idPatient, gender, status, idSample, file(bam), file(bai) from bamsForAscat
set file(acLoci), file(genomeFile), file(genomeIndex), file(genomeDict) from Channel.value([
referenceMap.acLoci,
referenceMap.genomeFile,
referenceMap.genomeIndex,
referenceMap.genomeDict
])
output:
set idPatient, gender, status, idSample, file("${idSample}.alleleCount") into alleleCountOutput
when: 'Ascat' in tools
script:
"""
alleleCounter -l $acLoci -r $genomeFile -b $bam -o ${idSample}.alleleCount;
"""
}
verbose ? alleleCountOutput = alleleCountOutput.view {"alleleCount output: $it"} : ''
alleleCountNormal = Channel.create()
alleleCountTumor = Channel.create()
alleleCountOutput
.choice(alleleCountTumor, alleleCountNormal) {it[2] == 0 ? 1 : 0}
alleleCountOutput = alleleCountNormal.spread(alleleCountTumor)
alleleCountOutput = alleleCountOutput.map {
idPatientNormal, genderNormal, statusNormal, idSampleNormal, alleleCountNormal, idPatientTumor, genderTumor, statusTumor, idSampleTumor, alleleCountTumor ->
[idPatientNormal, genderNormal, idSampleNormal, idSampleTumor, alleleCountNormal, alleleCountTumor]
}
verbose ? alleleCountOutput = alleleCountOutput.view {"alleleCount output: $it"} : ''
// R script from Malin Larssons bitbucket repo:
// https://bitbucket.org/malinlarsson/somatic_wgs_pipeline
process RunConvertAlleleCounts {
tag {idPatient + "-" + idSampleTumor}
publishDir directoryMap.ascat, mode: 'copy'
input:
set idPatient, gender, idSampleNormal, idSampleTumor, file(alleleCountNormal), file(alleleCountTumor) from alleleCountOutput
output:
set idPatient, gender, idSampleNormal, idSampleTumor, file("${idSampleNormal}.BAF"), file("${idSampleNormal}.LogR"), file("${idSampleTumor}.BAF"), file("${idSampleTumor}.LogR") into convertAlleleCountsOutput
when: 'Ascat' in tools
script:
"""
convertAlleleCounts.r $idSampleTumor $alleleCountTumor $idSampleNormal $alleleCountNormal $gender
"""
}
// R scripts from Malin Larssons bitbucket repo:
// https://bitbucket.org/malinlarsson/somatic_wgs_pipeline
process RunAscat {
tag {idPatient + "-" + idSampleTumor}
publishDir directoryMap.ascat, mode: 'copy'
input:
set idPatient, gender, idSampleNormal, idSampleTumor, file(bafNormal), file(logrNormal), file(bafTumor), file(logrTumor) from convertAlleleCountsOutput
output:
set val("ascat"), idPatient, gender, idSampleNormal, idSampleTumor, file("${idSampleTumor}.tumour.png"), file("${idSampleTumor}.germline.png"), file("${idSampleTumor}.LogR.PCFed.txt"), file("${idSampleTumor}.BAF.PCFed.txt"), file("${idSampleTumor}.ASPCF.png"), file("${idSampleTumor}.ASCATprofile.png"), file("${idSampleTumor}.aberrationreliability.png"), file("${idSampleTumor}.rawprofile.png"), file("${idSampleTumor}.sunrise.png") into ascatOutput
when: 'Ascat' in tools
script:
"""
#!/bin/env Rscript
##############################################################################
# Description: #
# R-script for converting output from AlleleCount to BAF and LogR values. #
# #
# Input: #
# AlleleCounter output file for tumor and normal samples #
# The first line should contain a header describing the data #
# The following columns and headers should be present: #
# CHR POS Count_A Count_C Count_G Count_T Good_depth #
# #
# Output: #
# BAF and LogR tables (tab delimited text files) #
##############################################################################
source("$baseDir/scripts/ascat.R")
.libPaths( c( "$baseDir/scripts", .libPaths() ) )
if(!require(RColorBrewer)){
source("http://bioconductor.org/biocLite.R")
biocLite("RColorBrewer", suppressUpdates=TRUE, lib="$baseDir/scripts")
library(RColorBrewer)
}
options(bitmapType='cairo')
tumorbaf = "$bafTumor"