-
Notifications
You must be signed in to change notification settings - Fork 5
/
pipeline.nf
executable file
·4005 lines (3352 loc) · 155 KB
/
pipeline.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;-*-
*/
/*
================================================================================
--------------------------------------------------------------------------------
Processes overview:
Alignment
----------------
- AlignReads
--- Map paired-end FASTQs with bwa mem
--- Sort BAM with samtools sort
--- FASTQ QC with FastP
- MergeBam --- Merge BAM for the same samples from different fileID, samtools merge
- MarkDuplicates --- Mark Duplicates with GATK4 MarkDuplicates
- CreateRecalibrationTable --- Create Recalibration Table with GATK4 BaseRecalibrator
- RecalibrateBam --- Recalibrate Bam with GATK4 ApplyBQSR
Somatic Analysis
----------------
- CreateScatteredIntervals --- GATK4 SplitIntervals
- RunMutect2 --- somatic SNV calling, MuTect2
- SomaticCombineMutect2Vcf --- combine Mutect2 calls, bcftools
- SomaticDellyCall --- somatic SV calling, Delly
- SomaticRunManta --- somatic SV calling, Manta
- SomaticMergeDellyAndManta --- combine Manta and Delly VCFs
- SomaticRunStrelka2 --- somatic SNV calling, Strelka2, using Manta for small indel calling by default
- SomaticCombineChannel --- combine and filter VCFs, bcftools
- SomaticAnnotateMaf --- annotate MAF, vcf2maf
- RunMutationSignatures --- mutational signatures
- DoFacets --- facets-suite: mafAnno.R, geneLevel.R, armLevel.R
- RunPolysolver --- Polysolver
- RunLOHHLA --- LOH in HLA
- SomaticFacetsAnnotation --- annotate FACETS
- RunNeoantigen --- NetMHCpan 4.0
- RunMsiSensor --- MSIsensor
- MetaDataParser --- python script to parse metadata into single *tsv
Germline Analysis
-----------------
- CreateScatteredIntervals --- (run once) GATK4 SplitIntervals
- GermlineDellyCall --- germline SV calling and filtering, Delly
- GermlineRunManta --- germline SV calling, Manta
- GermlineMergeDellyAndManta --- merge SV calls from Delly and Manta
- GermlineRunHaplotypecaller --- germline SNV calling, GATK4
- GermlineCombineHaplotypecallerVcf --- concatenate VCFs of GATK4 HaplotypeCaller
- GermlineRunStrelka2 --- germline SNV calling, Strelka2 (with InDels from Manta)
- GermlineCombineChannel --- combined and filter germline calls, bcftools
- GermlineAnnotateMaf--- annotate MAF, vcf2maf
Quality Control
-----------------
- QcAlfred - BAM QC metrics
- QcCollectHsMetrics --- *For WES only* Calculate hybrid-selection metrics, GATK4 CollectHsMetrics
- QcBamAggregate --- aggregates information from QcAlfred and QcCollectHsMetrics across all samples
- QcConpair --- Tumor-Normal quality/contamination
- QcConpairAll --- Tumor-Normal All Combination quality/contamination
Cohort Aggregation
-----------------
- SomaticAggregateMaf --- collect outputs, MAF
- SomaticAggregateNetMHC --- collect outputs, neoantigen prediction
- SomaticAggregateFacets --- collect outputs, FACETS
- SomaticAggregateSv --- collect outputs, SVs
- SomaticAggregateLOHHLA --- collect outputs, LOHHLA
- SomaticAggregateMetaData --- collect outputs, sample data
- GermlineAggregateMaf --- collect outputs, MAF
- GermlineAggregateSv --- collect outputs, SVs
- QcConpairAggregate --- aggregates information from QcConpair or QcConpairAll across all sample
*/
/*
================================================================================
= C O N F I G U R A T I O N =
================================================================================
*/
if (!(workflow.profile in ['juno', 'awsbatch', 'docker', 'singularity', 'test_singularity', 'test'])) {
println "ERROR: You need to set -profile (values: juno, awsbatch, docker, singularity)"
exit 1
}
// User-set runtime parameters
publishAll = params.publishAll
outDir = file(params.outDir).toAbsolutePath()
outname = params.outname
runGermline = params.germline
runSomatic = params.somatic
runQC = params.QC
runAggregate = params.aggregate
runConpairAll = false
wallTimeExitCode = params.wallTimeExitCode ? params.wallTimeExitCode.split(',').collect{it.trim().toLowerCase()} : []
multiqcWesConfig = workflow.projectDir + "/lib/multiqc_config/exome_multiqc_config.yaml"
multiqcWgsConfig = workflow.projectDir + "/lib/multiqc_config/wgs_multiqc_config.yaml"
multiqcTempoLogo = workflow.projectDir + "/docs/tempoLogo.png"
epochMap = [:]
startEpoch = new Date().getTime()
limitInputLines = 0
chunkSizeLimit = params.chunkSizeLimit
if (params.watch == true){
touchInputs()
}
referenceMap = defineReferenceMap()
targetsMap = loadTargetReferences()
println ""
pairingQc = params.pairing
if (params.mapping || params.bamMapping) {
TempoUtils.checkAssayType(params.assayType)
if (params.watch == false) {
mappingFile = params.mapping ? file(params.mapping, checkIfExists: true) : file(params.bamMapping, checkIfExists: true)
(checkMapping1, checkMapping2, inputMapping) = params.mapping ? TempoUtils.extractFastq(mappingFile, params.assayType, targetsMap.keySet()).into(3) : TempoUtils.extractBAM(mappingFile, params.assayType, targetsMap.keySet()).into(3)
}
else if (params.watch == true) {
mappingFile = params.mapping ? file(params.mapping, checkIfExists: false) : file(params.bamMapping, checkIfExists: false)
(checkMapping1, checkMapping2, inputMapping) = params.mapping ? watchMapping(mappingFile, params.assayType).into(3) : watchBamMapping(mappingFile, params.assayType).into(3)
epochMap[params.mapping ? params.mapping : params.bamMapping ] = 0
}
else{}
if(params.pairing){
if(runQC){
pairingQc = true
}
if (params.watch == false) {
pairingFile = file(params.pairing, checkIfExists: true)
(checkPairing1, checkPairing2, inputPairing) = TempoUtils.extractPairing(pairingFile).into(3)
TempoUtils.crossValidateTargets(checkMapping1, checkPairing1)
if(!TempoUtils.crossValidateSamples(checkMapping2, checkPairing2)){exit 1}
}
else if (params.watch == true) {
pairingFile = file(params.pairing, checkIfExists: false)
(checkPairing1, checkPairing2, inputPairing) = watchPairing(pairingFile).into(3)
epochMap[params.pairing] = 0
}
else{}
if (!runSomatic && !runGermline && !runQC){
println "ERROR: --pairing [tsv] is not used because none of --somatic/--germline/--QC was enabled. If you only need to do BAM QC and/or BAM generation, remove --pairing [tsv]."
exit 1
}
}
else{
if (runSomatic || runGermline){
println "ERROR: --pairing [tsv] needed when using --mapping/--bamMapping [tsv] with --somatic/--germline"
exit 1
}
}
}
else{
if(params.pairing){
println "ERROR: When --pairing [tsv], --mapping/--bamMapping [tsv] must be provided."
exit 1
}
}
if (!runSomatic && runGermline){
println "WARNING: You can't run GERMLINE section without running SOMATIC section. Activating SOMATIC section automatically"
runSomatic = true
}
if (runAggregate == false){
if (!params.mapping && !params.bamMapping){
println "ERROR: (--mapping/-bamMapping [tsv]) or (--mapping/--bamMapping [tsv] & --pairing [tsv] ) or (--aggregate [tsv]) need to be provided, otherwise nothing to be run."
exit 1
}
}
else if (runAggregate == true){
if ((params.mapping || params.bamMapping) && params.pairing){
if (!(runSomatic || runGermline || runQC)){
println "ERROR: Nothing to be aggregated. One or more of the option --somatic/--germline/--QC need to be enabled when using --aggregate"
}
}
else if ((params.mapping || params.bamMapping) && !params.pairing){
if (!runQC){
println "ERROR: Nothing to be aggregated. --QC need to be enabled when using --mapping/--bamMapping [tsv], --pairing false and --aggregate true."
exit 1
}
}
else{
println "ERROR: (--mapping/--bamMapping [tsv]) or (--mapping/--bamMapping [tsv] & --pairing [tsv]) or (--aggregate [tsv]) need to be provided when using --aggregate true"
println " If you want to run aggregate only, you need to use --aggregate [tsv]. See manual"
exit 1
}
}
else {
if ((runSomatic || runGermline || runQC) && !params.mapping && !params.bamMapping){
println "ERROR: Conflict input! When running --aggregate [tsv] with --mapping/--bamMapping/--pairing [tsv] disabled, --QC/--somatic/--germline all need to be disabled!"
println " If you want to run aggregate somatic/germline/qc, just include an additianl colum PATH in the [tsv] and no need to use --QC/--somatic/--germline flag, since it's auto detected. See manual"
exit 1
}
}
if (!(params.cosmic in ['v2', 'v3'])) {
println "ERROR: Possible values of mutational signature reference --cosmic is 'v2', 'v3'"
exit 1
}
/*
================================================================================
= P R O C E S S E S =
================================================================================
*/
// Skip these processes if starting from aligned BAM files
if (params.mapping) {
// Parse input FASTQ mapping
if(params.watch != true){
inputMapping.groupTuple(by: [0])
.map { idSample, targets, files_pe1, files_pe2
-> tuple(groupKey(idSample, targets.size()), targets, files_pe1, files_pe2)
}
.transpose()
.set{ inputMapping }
}
inputMapping.map{ idSample, target, file_pe1, file_pe2 ->
[idSample, target, file_pe1, file_pe2, idSample + "@" + file_pe1.getSimpleName(), file_pe1.getSimpleName()]
}
.set{ inputFastqs }
if (params.splitLanes) {
inputFastqs
.into{ fastqsNeedSplit; fastqsNoNeedSplit }
fastqsNeedSplit
.filter{ item -> !(item[2].getName() =~ /_L(\d){3}_/) }
.multiMap{ idSample, target, file_pe1, file_pe2, fileID, lane ->
inputFastqR1: [idSample, target, file_pe1, file_pe1.toString()]
inputFastqR2: [idSample, target, file_pe2, file_pe2.toString()]
}
.set{ fastqsNeedSplit }
fastqsNoNeedSplit
.filter{ item -> item[2].getName() =~ /_L(\d){3}_/ }
.map { idSample, target, file_pe1, file_pe2, fileID, lane
-> tuple(idSample, target, file_pe1, file_pe1.size(), file_pe2, file_pe2.size(), groupKey(fileID, 1), lane)
}
.set{ fastqsNoNeedSplit }
process SplitLanesR1 {
tag {idSample + "@" + fileID} // The tag directive allows you to associate each process executions with a custom label
input:
set idSample, target, file(fastqFile1), fileID from fastqsNeedSplit.inputFastqR1
output:
file("file-size.txt") into R1Size
set idSample, target, file("*R1*.splitLanes.fastq.gz"), file("*.fcid"), file("*.laneCount") into perLaneFastqsR1
when: params.splitLanes
script:
inputSize = fastqFile1.size()
if (workflow.profile == "juno") {
if (inputSize > 10.GB) {
task.time = { params.maxWallTime }
}
else if (inputSize < 5.GB) {
task.time = task.exitStatus.toString() in wallTimeExitCode ? { params.medWallTime } : { params.minWallTime }
}
else {
task.time = task.exitStatus.toString() in wallTimeExitCode ? { params.maxWallTime } : { params.medWallTime }
}
// if it's the last time to try, use 500h as time limit no matter for what reason it failed before
task.time = task.attempt < 3 ? task.time : { params.maxWallTime }
}
filePartNo = fastqFile1.getSimpleName().split("_R1")[-1]
filePrefix = fastqFile1.getSimpleName().split("_R1")[0..-2].join("_R1")
"""
fcid=`zcat $fastqFile1 | head -1 | tr ':/' '@' | cut -d '@' -f2-4`
touch \${fcid}.fcid
echo -e "${idSample}@${fileID}\t${inputSize}" > file-size.txt
zcat $fastqFile1 | awk -v var="\${fcid}" 'BEGIN {FS = ":"} {lane=\$4 ; print | "gzip > ${filePrefix}@"var"_L00"lane"_R1${filePartNo}.splitLanes.fastq.gz" ; for (i = 1; i <= 3; i++) {getline ; print | "gzip > ${filePrefix}@"var"_L00"lane"_R1${filePartNo}.splitLanes.fastq.gz"}}'
touch `ls *R1*.splitLanes.fastq.gz | wc -l`.laneCount
"""
}
process SplitLanesR2 {
tag {idSample + "@" + fileID} // The tag directive allows you to associate each process executions with a custom label
input:
set idSample, target, file(fastqFile2), fileID from fastqsNeedSplit.inputFastqR2
output:
file("file-size.txt") into R2Size
set idSample, target, file("*_R2*.splitLanes.fastq.gz"), file("*.fcid"), file("*.laneCount") into perLaneFastqsR2
when: params.splitLanes
script:
inputSize = fastqFile2.size()
if (workflow.profile == "juno") {
if (inputSize > 10.GB) {
task.time = { params.maxWallTime }
}
else if (inputSize < 5.GB) {
task.time = task.exitStatus.toString() in wallTimeExitCode ? { params.medWallTime } : { params.minWallTime }
}
else {
task.time = task.exitStatus.toString() in wallTimeExitCode ? { params.maxWallTime } : { params.medWallTime }
}
task.time = task.attempt < 3 ? task.time : { params.maxWallTime }
}
filePartNo = fastqFile2.getSimpleName().split("_R2")[-1]
filePrefix = fastqFile2.getSimpleName().split("_R2")[0..-2].join("_R2")
"""
fcid=`zcat $fastqFile2 | head -1 | tr ':/' '@' | cut -d '@' -f2-4`
touch \${fcid}.fcid
echo -e "${idSample}@${fileID}\t${inputSize}" > file-size.txt
zcat $fastqFile2 | awk -v var="\${fcid}" 'BEGIN {FS = ":"} {lane=\$4 ; print | "gzip > ${filePrefix}@"var"_L00"lane"_R2${filePartNo}.splitLanes.fastq.gz" ; for (i = 1; i <= 3; i++) {getline ; print | "gzip > ${filePrefix}@"var"_L00"lane"_R2${filePartNo}.splitLanes.fastq.gz"}}'
touch `ls *_R2*.splitLanes.fastq.gz | wc -l`.laneCount
"""
}
def fastqR1fileIDs = [:]
perLaneFastqsR1 = perLaneFastqsR1.transpose()
.map{ item ->
def idSample = item[0]
def target = item[1]
def fastq = item[2]
def fileID = idSample + "@" + item[3].getSimpleName()
def lane = fastq.getSimpleName().split("_L00")[1].split("_")[0]
def laneCount = item[4].getSimpleName().toInteger()
// This only checks if same read groups appears in two or more fastq files which belongs to the same sample. Cross sample check will be performed after AlignReads since the read group info is not available for fastqs which does not need to be split.
if ( !params.watch ){
if(!TempoUtils.checkDuplicates(fastqR1fileIDs, fileID + "@" + lane, fileID + "\t" + fastq, "the follwoing fastq files since they contain the same RGID")){exit 1}
}
[idSample, target, fastq, fileID, lane, laneCount]
}
def fastqR2fileIDs = [:]
perLaneFastqsR2 = perLaneFastqsR2.transpose()
.map{ item ->
def idSample = item[0]
def target = item[1]
def fastq = item[2]
def fileID = idSample + "@" + item[3].getSimpleName()
def lane = fastq.getSimpleName().split("_L00")[1].split("_")[0]
def laneCount = item[4].getSimpleName().toInteger()
if ( !params.watch ){
if(!TempoUtils.checkDuplicates(fastqR2fileIDs, fileID + "@" + lane, fileID + "\t" + fastq, "the follwoing fastq files since they contain the same RGID")){exit 1}
}
[idSample, target, fastq, fileID, lane, laneCount]
}
fastqFiles = perLaneFastqsR1
.mix(perLaneFastqsR2)
.groupTuple(by: [0,1,3,4,5], size: 2, sort: true)
.map { idSample, target, fastqPairs, fileID, lanes, laneCount ->
tuple(idSample, target, fastqPairs, groupKey(fileID, laneCount), lanes)
}
.map{ idSample, target, fastqPairs, fileID, lane ->
[idSample, target, fastqPairs[0], fastqPairs[1], fileID, lane]
}
.map{ item ->
def idSample = item[0]
def target = item[1]
def fastqPair1 = item[2]
def fastqPair2 = item[3]
if (item[2].toString().split("_R1").size() < item[3].toString().split("_R1").size()) {
fastqPair1 = item[3]
fastqPair2 = item[2]
}
def fileID = item[4]
def lane = item[5]
[idSample, target, fastqPair1, fastqPair1.size(), fastqPair2, fastqPair2.size(), fileID, lane]
}
.mix(fastqsNoNeedSplit)
}
else{
fastqFiles = inputFastqs.map { idSample, target, file_pe1, file_pe2, fileID, lane
-> tuple(idSample, target, file_pe1, file_pe1.size(), file_pe2, file_pe2.size(), groupKey(fileID, 1), lane)
}
}
// AlignReads - Map reads with BWA mem output SAM
process AlignReads {
tag {fileID + "@" + lane} // The tag directive allows you to associate each process executions with a custom label
publishDir "${outDir}/bams/${idSample}/fastp", mode: params.publishDirMode, pattern: "*.{html,json}"
input:
set idSample, target, file(fastqFile1), sizeFastqFile1, file(fastqFile2), sizeFastqFile2, fileID, lane from fastqFiles
set file(genomeFile), file(bwaIndex) from Channel.value([referenceMap.genomeFile, referenceMap.bwaIndex])
output:
set idSample, file("*.html") into fastPHtml
set idSample, file("*.json"), fileID into fastPJson4MultiQC
file("file-size.txt") into laneSize
set idSample, target, file("*.sorted.bam"), fileID, lane, file("*.readId") into sortedBam
script:
// LSF resource allocation for juno
// if running on juno, check the total size of the FASTQ pairs in order to allocate the runtime limit for the job, via LSF `bsub -W`
// if total size of the FASTQ pairs is over 20 GB, use params.maxWallTimeours
// if total size of the FASTQ pairs is under 12 GB, use 3h. If there is a 140 error, try again with 6h. If 6h doesn't work, try 500h.
inputSize = sizeFastqFile1 + sizeFastqFile2
if (workflow.profile == "juno") {
if (inputSize > 18.GB) {
task.time = { params.maxWallTime }
}
else if (inputSize < 9.GB) {
task.time = task.exitStatus.toString() in wallTimeExitCode ? { params.medWallTime } : { params.minWallTime }
}
else {
task.time = task.exitStatus.toString() in wallTimeExitCode ? { params.maxWallTime } : { params.medWallTime }
}
task.time = task.attempt < 3 ? task.time : { params.maxWallTime }
}
// mem --- total size of the FASTQ pairs in MB (max memory `samtools sort` can take advantage of)
// memDivider --- If mem_per_core is true, use 1. Else, use task.cpus
// memMultiplier --- If mem_per_core is false, use 1. Else, use task.cpus
// originalMem -- If this is the first attempt, use task.memory. Else, use `originalMem`
mem = (inputSize/1024**2).round()
memDivider = params.mem_per_core ? 1 : task.cpus
memMultiplier = params.mem_per_core ? task.cpus : 1
originalMem = task.attempt ==1 ? task.memory : originalMem
if ( mem < 6 * 1024 / task.cpus ) {
// minimum total task memory requirment is 6GB because `bwa mem` need this much to run, and increase by 10% everytime retry
task.memory = { (6 / memMultiplier * (0.9 + 0.1 * task.attempt) + 0.5).round() + " GB" }
mem = (5.4 * 1024 / task.cpus).round()
}
else if ( mem / memDivider * (1 + 0.1 * task.attempt) > originalMem.toMega() ) {
// if file size is too big, use task.memory as the max mem for this task, and decrease -M for `samtools sort` by 10% everytime retry
mem = (originalMem.toMega() / memDivider * (1 - 0.1 * task.attempt) + 0.5).round()
}
else {
// normal situation, `samtools sort` -M = inputSize * 2, task.memory is 110% of `samtools sort` and increase by 10% everytime retry
task.memory = { (mem * memDivider * (1 + 0.1 * task.attempt) / 1024 + 0.5).round() + " GB" }
mem = mem
}
task.memory = task.memory.toGiga() < 1 ? { 1.GB } : task.memory
filePartNo = fastqFile1.getSimpleName().split("_R1")[-1]
"""
rgID=`zcat $fastqFile1 | head -1 | tr ':/' '@' | cut -d '@' -f2-5`
readGroup="@RG\\tID:\${rgID}\\tSM:${idSample}\\tLB:${idSample}\\tPL:Illumina"
touch `zcat $fastqFile1 | head -1 | tr ':/\t ' '@' | cut -d '@' -f2-`.readId
set -e
set -o pipefail
fastq1=${fastqFile1}
fastq2=${fastqFile2}
if ${params.anonymizeFQ}; then
ln -s ${fastqFile1} ${idSample}@\${rgID}@R1${filePartNo}.fastq.gz
ln -s ${fastqFile2} ${idSample}@\${rgID}@R2${filePartNo}.fastq.gz
fastq1=`echo ${idSample}@\${rgID}@R1${filePartNo}.fastq.gz`
fastq2=`echo ${idSample}@\${rgID}@R2${filePartNo}.fastq.gz`
fi
fastp --html ${idSample}@\${rgID}${filePartNo}.fastp.html --json ${idSample}@\${rgID}${filePartNo}.fastp.json --in1 \${fastq1} --in2 \${fastq2}
bwa mem -R \"\${readGroup}\" -t ${task.cpus} -M ${genomeFile} \${fastq1} \${fastq2} | samtools view -Sb - > ${idSample}@\${rgID}${filePartNo}.bam
samtools sort -m ${mem}M -@ ${task.cpus} -o ${idSample}@\${rgID}${filePartNo}.sorted.bam ${idSample}@\${rgID}${filePartNo}.bam
echo -e "${fileID}@${lane}\t${inputSize}" > file-size.txt
"""
}
fastPJson4MultiQC
.groupTuple(by:[2])
.map{idSample, jsonFile, fileID ->
def idSampleout = idSample[0] instanceof Collection ? idSample[0].first() : idSample[0]
[idSampleout, jsonFile]
}.groupTuple(by: [0])
.map{ idSample, jsonFile ->
[idSample, jsonFile.flatten()]
}.into{fastPJson4cohortMultiQC; fastPJson4sampleMultiQC}
// Check for FASTQ files which might have different path but contains the same reads, based only on the name of the first read.
def allReadIds = [:]
sortedBam.map { idSample, target, bam, fileID, lane, readIdFile -> def readId = "@" + readIdFile.getSimpleName().replaceAll("@", ":")
// Use the first line of the fastq file (the name of the first read) as unique identifier to check across all the samples if there is any two fastq files contains the same read name, if so, we consider there are some human error of mixing up the same reads into different fastq files
if ( !params.watch ){
if(!TempoUtils.checkDuplicates(allReadIds, readId, idSample + "\t" + bam, "the follwoing samples, since they contain the same read: \n${readId}")){exit 1}
}
[idSample, target, bam, fileID, lane]
}
.groupTuple(by: [3])
.map{ item ->
def idSample = item[0] instanceof Collection ? item[0].first() : item[0]
def target = item[1] instanceof Collection ? item[1].first() : item[1]
def bams = item[2]
[idSample, target, bams]
}
.groupTuple(by: [0])
.map{ item ->
def idSample = item[0]
def target = item[1] instanceof Collection ? item[1].first() : item[1]
def bams = item[2].flatten()
[idSample, bams, target]
}
.set{ groupedBam }
// MergeBams and MarkDuplicates
process MergeBamsAndMarkDuplicates {
tag {idSample}
input:
set idSample, file(bam), target from groupedBam
output:
set idSample, file("${idSample}.md.bam"), file("${idSample}.md.bai"), target into mdBams, mdBams4BQSR
file("size.txt") into sizeOutput
script:
if (workflow.profile == "juno") {
if(bam.size() > 100.GB) {
task.time = { params.maxWallTime }
}
else if (bam.size() < 80.GB) {
task.time = task.exitStatus.toString() in wallTimeExitCode ? { params.medWallTime } : { params.minWallTime }
}
else {
task.time = task.exitStatus.toString() in wallTimeExitCode ? { params.maxWallTime } : { params.medWallTime }
}
task.time = task.attempt < 3 ? task.time : { params.maxWallTime }
}
memMultiplier = params.mem_per_core ? task.cpus : 1
// when increase memory requested from system every time it retries, keep java Xmx steady, in order to give more memory for java garbadge collection
originalMem = task.attempt ==1 ? task.memory : originalMem
maxMem = (memMultiplier * originalMem.toString().split(" ")[0].toInteger() - 3)
maxMem = maxMem < 4 ? 5 : maxMem
javaOptions = "--java-options '-Xms4000m -Xmx" + maxMem + "g'"
"""
samtools merge --threads ${task.cpus} ${idSample}.merged.bam ${bam.join(" ")}
gatk MarkDuplicates \
${javaOptions} \
--TMP_DIR ./ \
--MAX_RECORDS_IN_RAM 50000 \
--INPUT ${idSample}.merged.bam \
--METRICS_FILE ${idSample}.bam.metrics \
--ASSUME_SORT_ORDER coordinate \
--CREATE_INDEX true \
--OUTPUT ${idSample}.md.bam
echo -e "${idSample}\t`du -hs ${idSample}.md.bam`" > size.txt
"""
}
// GATK BaseRecalibrator , ApplyBQSR
process RunBQSR {
tag {idSample}
publishDir "${outDir}/bams/${idSample}", mode: params.publishDirMode, pattern: "*.bam*"
input:
set idSample, file(bam), file(bai), target from mdBams
set file(genomeFile), file(genomeIndex), file(genomeDict), file(dbsnp), file(dbsnpIndex), file(knownIndels), file(knownIndelsIndex) from Channel.value([
referenceMap.genomeFile,
referenceMap.genomeIndex,
referenceMap.genomeDict,
referenceMap.dbsnp,
referenceMap.dbsnpIndex,
referenceMap.knownIndels,
referenceMap.knownIndelsIndex
])
output:
set idSample, target, file("${idSample}.bam"), file("${idSample}.bam.bai") into bamsBQSR4Alfred, bamsBQSR4CollectHsMetrics, bamsBQSR4Tumor, bamsBQSR4Normal, bamsBQSR4QcPileup, bamsBQSR4Qualimap
set idSample, target, val("${file(outDir).toString()}/bams/${idSample}/${idSample}.bam"), val("${file(outDir).toString()}/bams/${idSample}/${idSample}.bam.bai") into bamResults
file("file-size.txt") into bamSize
script:
if (workflow.profile == "juno") {
if(bam.size() > 200.GB) {
task.time = { params.maxWallTime }
}
else if (bam.size() < 100.GB) {
task.time = task.exitStatus.toString() in wallTimeExitCode ? { params.medWallTime } : { params.minWallTime }
}
else {
task.time = task.exitStatus.toString() in wallTimeExitCode ? { params.maxWallTime } : { params.medWallTime }
}
task.time = task.attempt < 3 ? task.time : { params.maxWallTime }
}
if (task.attempt < 3 ) {
sparkConf = "Spark --conf 'spark.executor.cores = " + task.cpus + "'"
}
else {
sparkConf=""
task.cpus = 4
task.memory = { 6.GB }
if (workflow.profile == "juno"){ task.time = { params.maxWallTime } }
}
memMultiplier = params.mem_per_core ? task.cpus : 1
// when increase memory requested from system every time it retries, keep java Xmx steady, in order to give more memory for java garbadge collection
originalMem = task.attempt ==1 ? task.memory : originalMem
maxMem = (memMultiplier * originalMem.toString().split(" ")[0].toInteger() - 3)
maxMem = maxMem < 4 ? 5 : maxMem
javaOptions = "--java-options '-Xmx" + originalMem.toString().split(" ")[0].toInteger() * memMultiplier + "g'"
knownSites = knownIndels.collect{ "--known-sites ${it}" }.join(' ')
if ( task.attempt < 3 )
"""
gatk \
BQSRPipeline${sparkConf} \
-R ${genomeFile} \
-I ${bam} \
--known-sites ${dbsnp} \
${knownSites} \
--verbosity INFO \
--create-output-bam-index true \
-O ${idSample}.bam
echo -e "${idSample}\t\$(du -b ${idSample}.bam)" > file-size.txt
if [[ -f ${idSample}.bai ]]; then
mv ${idSample}.bai ${idSample}.bam.bai
fi
"""
else
"""
gatk \
BaseRecalibrator${sparkConf} \
${javaOptions} \
--reference ${genomeFile} \
--known-sites ${dbsnp} \
${knownSites} \
--verbosity INFO \
--input ${bam} \
--output ${idSample}.recal.table
gatk \
ApplyBQSR${sparkConf} \
${javaOptions} \
--reference ${genomeFile} \
--create-output-bam-index true \
--bqsr-recal-file ${idSample}.recal.table \
--input ${bam} \
--output ${idSample}.bam
echo -e "${idSample}\t\$(du -b ${idSample}.bam)" > file-size.txt
if [[ -f ${idSample}.bai ]]; then
mv ${idSample}.bai ${idSample}.bam.bai
fi
"""
}
File file = new File(outname)
file.newWriter().withWriter { w ->
w << "SAMPLE\tTARGET\tBAM\tBAI\n"
}
bamResults.subscribe { Object obj ->
file.withWriterAppend { out ->
out.println "${obj[0]}\t${obj[1]}\t${obj[2]}\t${obj[3]}"
}
}
} // End of "if (params.mapping) {}"
/*
================================================================================
= PAIRING TUMOR and NORMAL =
================================================================================
*/
// If starting with BAM files, parse BAM pairing input
if (params.bamMapping) {
inputMapping.into{bamsBQSR4Alfred; bamsBQSR4Qualimap; bamsBQSR4CollectHsMetrics; bamsBQSR4Tumor; bamsBQSR4Normal; bamsBQSR4QcPileup; bamPaths4MultiQC}
if (runQC){
bamPaths4MultiQC.map{idSample, target, bam, bai ->
[ idSample,target, bam.getParent() ]
}.set{ locateFastP4MultiQC}
locateFastP4MultiQC.map{ idSample,target, bamFolder ->
[idSample, file(bamFolder + "/fastp/*json")]
}.into{fastPJson4sampleMultiQC;fastPJson4cohortMultiQC}
}
}
if (params.pairing) {
// Parse input FASTQ mapping
inputPairing.into{pairing4T; pairing4N; pairingTN; pairing4QC; inputPairing; pairing4Qualimap}
bamsBQSR4Tumor.combine(pairing4T)
.filter { item ->
def idSample = item[0]
def target = item[1]
def sampleBam = item[2]
def sampleBai = item[3]
def idTumor = item[4]
def idNormal = item[5]
idSample == idTumor
}.map { item ->
def idTumor = item[4]
def idNormal = item[5]
def tumorBam = item[2]
def tumorBai = item[3]
def target = item[1]
return [ idTumor, idNormal, target, tumorBam, tumorBai ]
}
.unique()
.into{bamsTumor4Combine; bamsTumor4VcfCombine}
bamsBQSR4Normal.combine(pairing4N)
.filter { item ->
def idSample = item[0]
def target = item[1]
def sampleBam = item[2]
def sampleBai = item[3]
def idTumor = item[4]
def idNormal = item[5]
idSample == idNormal
}.map { item ->
def idTumor = item[4]
def idNormal = item[5]
def normalBam = item[2]
def normalBai = item[3]
def target = item[1]
return [ idTumor, idNormal, target, normalBam, normalBai ]
}.unique()
.into{ bamsNormal4Combine; bamsNormalOnly }
bamsNormalOnly.map { item ->
def idNormal = item[1]
def target = item[2]
def normalBam = item[3]
def normalBai = item[4]
return [ idNormal, target, normalBam, normalBai ] }
.unique()
.into{ bams4Haplotypecaller; bamsNormal4Polysolver; bamsForStrelkaGermline; bamsForMantaGermline; bamsForDellyGermline }
bamsTumor4Combine.combine(bamsNormal4Combine, by: [0,1,2])
.map { item -> // re-order the elements
def idTumor = item[0]
def idNormal = item[1]
def target = item[2]
def bamTumor = item[3]
def baiTumor = item[4]
def bamNormal = item[5]
def baiNormal = item[6]
return [ idTumor, idNormal, target, bamTumor, baiTumor, bamNormal, baiNormal ]
}
.set{bamFiles}
} // End of "if (pairingQc) {}"
/*
================================================================================
= SOMATIC PIPELINE =
================================================================================
*/
if (runSomatic || runGermline || runQC) {
// parse --tools parameter for downstream 'when' conditionals, e.g. when: 'delly ' in tools
tools = params.tools ? params.tools.split(',').collect{it.trim().toLowerCase()} : []
// Allow shorter names
if ("mutect" in tools) {
tools.add("mutect2")
}
if ("strelka" in tools) {
tools.add("strelka2")
}
// If using Strelka2, run Manta as well to generate candidate indels
if ("strelka2" in tools) {
tools.add("manta")
}
// If using running either conpair or conpairAll, run pileup as well to generate pileups
if ("conpair" in tools) {
tools.add("pileup")
}
if ("conpairall" in tools) {
runConpairAll = true
tools.add("pileup")
}
}
if (runSomatic || runGermline) {
// GATK SplitIntervals, CreateScatteredIntervals
targets4Intervals = Channel.from(targetsMap.keySet())
.map{ targetId ->
[ targetId, targetsMap."${targetId}"."targetsBedGz", targetsMap."${targetId}"."targetsBedGzTbi" ]
}
process CreateScatteredIntervals {
tag {targetId}
input:
set file(genomeFile), file(genomeIndex), file(genomeDict) from Channel.value([
referenceMap.genomeFile, referenceMap.genomeIndex, referenceMap.genomeDict
])
set val(targetId), file(targets), file(targetsIndex) from targets4Intervals
output:
set file("*.interval_list"), val(targetId), val(targetId) into mergedIList4T, mergedIList4N
when: runSomatic || runGermline
script:
scatterCount = params.scatterCount
subdivision_mode = targetId == "wgs" ? "INTERVAL_SUBDIVISION" : "BALANCING_WITHOUT_INTERVAL_SUBDIVISION_WITH_OVERFLOW"
"""
gatk SplitIntervals \
--reference ${genomeFile} \
--intervals ${targets} \
--scatter-count ${scatterCount} \
--subdivision-mode ${subdivision_mode} \
--output $targetId
for i in $targetId/*.interval_list;
do
BASENAME=`basename \$i`
mv \$i ${targetId}-\$BASENAME
done
"""
}
//Associating interval_list files with BAM files, putting them into one channel
bamFiles.into{bamsTN4Intervals; bamsForDelly; bamsForManta; bams4Strelka; bamns4CombineChannel; bamsForMsiSensor; bamFiles4DoFacets; bamsForLOHHLA }
bamsTN4Intervals.combine(mergedIList4T, by: 2).map{
item ->
def idTumor = item[1]
def idNormal = item[2]
def target = item[0]
def tumorBam = item[3]
def normalBam = item[4]
def tumorBai = item[5]
def normalBai = item[6]
def intervalBed = item[7]
def key = idTumor+"__"+idNormal+"@"+target // adding one unique key
return [ key, idTumor, idNormal, target, tumorBam, normalBam, tumorBai, normalBai, intervalBed ]
}.map{
key, idTumor, idNormal, target, tumorBam, normalBam, tumorBai, normalBai, intervalBed ->
tuple (
groupKey(key, intervalBed.size()), // adding numbers so that each sample only wait for it's own children processes
idTumor, idNormal, target, tumorBam, normalBam, tumorBai, normalBai, intervalBed
)
}
.transpose()
.set{ mergedChannelSomatic }
bams4Haplotypecaller.combine(mergedIList4N, by: 1)
.map{
item ->
def idNormal = item[1]
def target = item[0]
def normalBam = item[2]
def normalBai = item[3]
def intervalBed = item[4]
def key = idNormal+"@"+target // adding one unique key
return [ key, idNormal, target, normalBam, normalBai, intervalBed ]
}.map{
key, idNormal, target, normalBam, normalBai, intervalBed ->
tuple (
groupKey(key, intervalBed.size()), // adding numbers so that each sample only wait for it's own children processes
idNormal, target, normalBam, normalBai, intervalBed
)
}
.transpose()
.set{ mergedChannelGermline }
}
if (runSomatic){
// --- Run Mutect2
process RunMutect2 {
tag {idTumor + "__" + idNormal + "@" + intervalBed.baseName}
input:
set id, idTumor, idNormal, target, file(bamTumor), file(baiTumor), file(bamNormal), file(baiNormal), file(intervalBed) from mergedChannelSomatic
set file(genomeFile), file(genomeIndex), file(genomeDict) from Channel.value([
referenceMap.genomeFile, referenceMap.genomeIndex, referenceMap.genomeDict
])
output:
set id, idTumor, idNormal, target, file("*filtered.vcf.gz"), file("*filtered.vcf.gz.tbi"), file("*Mutect2FilteringStats.tsv") into forMutect2Combine
when: "mutect2" in tools && runSomatic
script:
mutect2Vcf = "${idTumor}__${idNormal}_${intervalBed.baseName}.vcf.gz"
prefix = "${mutect2Vcf}".replaceFirst(".vcf.gz", "")
"""
gatk --java-options -Xmx8g \
Mutect2 \
--reference ${genomeFile} \
--intervals ${intervalBed} \
--input ${bamTumor} \
--tumor-sample ${idTumor} \
--input ${bamNormal} \
--normal-sample ${idNormal} \
--output ${mutect2Vcf}
gatk --java-options -Xmx8g \
FilterMutectCalls \
--variant ${mutect2Vcf} \
--stats ${prefix}.Mutect2FilteringStats.tsv \
--output ${prefix}.filtered.vcf.gz
"""
}
//Formatting the channel to be keyed by idTumor, idNormal, and target
// group by groupKey(key, intervalBed.size())
forMutect2Combine.groupTuple().set{ forMutect2Combine }
// Combine Mutect2 VCFs, bcftools
process SomaticCombineMutect2Vcf {
tag {idTumor + "__" + idNormal}
publishDir "${outDir}/somatic/${idTumor}__${idNormal}/mutect2", mode: params.publishDirMode
input:
set id, idTumor, idNormal, target, file(mutect2Vcf), file(mutect2VcfIndex), file(mutect2Stats) from forMutect2Combine
set file(genomeFile), file(genomeIndex), file(genomeDict) from Channel.value([
referenceMap.genomeFile, referenceMap.genomeIndex, referenceMap.genomeDict
])
output:
set idTumor, idNormal, target, file("${outfile}"), file("${outfile}.tbi") into mutect2CombinedVcf4Combine, mutect2CombinedVcfOutput
when: "mutect2" in tools && runSomatic
script:
idTumor = id.toString().split("__")[0]
idNormal = id.toString().split("@")[0].split("__")[1]
target = id.toString().split("@")[1]
outfile = "${idTumor}__${idNormal}.mutect2.vcf.gz"
"""
bcftools concat \
--allow-overlaps \
${mutect2Vcf} | \
bcftools sort | \
bcftools norm \
--fasta-ref ${genomeFile} \
--check-ref s \
--multiallelics -both | \
bcftools norm --rm-dup all | \
bcftools view \
--samples ${idNormal},${idTumor} \
--output-type z \
--output-file ${outfile}
tabix --preset vcf ${outfile}
"""
}
// --- Run Delly
Channel.from("DUP", "BND", "DEL", "INS", "INV").set{ svTypes }
process SomaticDellyCall {
tag {idTumor + "__" + idNormal + '@' + svType}
publishDir "${outDir}/somatic/${idTumor}__${idNormal}/delly", mode: params.publishDirMode, pattern: "*.delly.vcf.{gz,gz.tbi}"
input:
each svType from svTypes
set idTumor, idNormal, target, file(bamTumor), file(baiTumor), file(bamNormal), file(baiNormal) from bamsForDelly
set file(genomeFile), file(genomeIndex), file(svCallingExcludeRegions) from Channel.value([
referenceMap.genomeFile, referenceMap.genomeIndex, referenceMap.svCallingExcludeRegions
])
output:
set idTumor, idNormal, target, file("${idTumor}__${idNormal}_${svType}.delly.vcf.gz"), file("${idTumor}__${idNormal}_${svType}.delly.vcf.gz.tbi") into dellyFilter4Combine
set file("${idTumor}__${idNormal}_${svType}.delly.vcf.gz"), file("${idTumor}__${idNormal}_${svType}.delly.vcf.gz.tbi") into dellyOutput
when: "delly" in tools && runSomatic
script:
"""
delly call \