-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.nf
1943 lines (1575 loc) · 57.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
def helpMessage() {
log.info"""
-----------------------------------------------------------------------
SOMATIC_N-OF-1 PIPELINE
-----------------------------------------------------------------------
Usage:
nextflow run brucemoran/somatic_n-of-1
Mandatory arguments:
-profile [str] Configuration profile
(required: standard,singularity)
--sampleCsv [file] CSV format, headers: type (either "germline" or
"somatic"), sampleID, meta, read1 (e.g.
/path/to/read1.fastq.gz), read2
(e.g. /path/to/read2.fastq.gz); use meta for
naming in PCGR, CPSR reports
--runID [str] Name for run, used to tag outputs
--refDir [file] Path of dir in which reference data are held;
this should be created by download-references.nf
and contain dir <assembly>
--assembly [str] Either GRCh37 or GRCh38 (default), as per
download-references.nf
--email [str] Email address to send reports
General Optional Arguments:
--germline [bool] Run HaplotypeCaller on germline sample and
annotate with CPSR (default: true)
--germCNV [bool] Run CNVkit germine CNV caller (default: false)
--scatGath [int] Number of pieces to divide intervalList into for
scattering to variant calling processes
(default: 20 for exome, 100 for WGS)
--incOrder [str] In final plots, use this ordering of samples
(if multiple somatic samples); comma-separated,
no spaces (default: alphanumeric sort)
--sampleCat [str] File used when fastq data is in multiple files
which are cat'ed; replaces --sampleCsv; headers:
type (either germline or somatic), sampleID,
meta, dir (contains fastq to be cat'ed), ext
(extension scheme for parsing read1, read2 e.g.
_1.fq.gz;_2.fq.gz).
--bamCsv [file] CSV format, headers as sampleCsv except read1,
read2 are swapped for bam which is sent to
duplicate marking
--multiqcConfig [str] Config file for multiqc
(default: bin/somatic_n-of-1.multiQC_config.yaml)
--seqLevel [str] WGS or exome (default: WGS)
--exomeTag [str] Tag used for exome kit when running download-references.nf
--cosmic [bool] set this to specify output of COSMIC CGC genes
only (somatic only; based on download and supply
of CGC file in download_references.nf)
--phylogeny [bool] conduct subclonal phylogeny reconstruction with
pairtree
""".stripIndent()
}
if (params.help) exit 0, helpMessage()
//Test Mandatory Arguments
if(params.sampleCsv && params.sampleCat){
exit 1, "Please include only one of --sampleCsv or --sampleCat, see --help for format"
}
if(params.sampleCsv == null && params.sampleCat == null && params.bamCsv == null){
exit 1, "Please include one of --sampleCsv, --bamCsv or --sampleCat, see --help for format"
}
if(!Channel.from(params.runID, checkIfExists: true)){
exit 1, "Please include --runID <your_runID>"
}
if(!Channel.from(params.refDir, checkIfExists: true)){
exit 1, "Please include --refDir <path> see github.com/brucemoran/somatic_n-of-1/ for how to run download-references.nf"
}
if(!Channel.from(params.assembly, checkIfExists: true)){
exit 1, "Please include --assembly <GRCh3x>"
}
if(!params.email){
exit 1, "Please include --email [email protected]"
}
if(params.seqLevel == "exome" && params.exomeTag == null){
exit 1, "Please define --exomeTag when using --seqLevel exome"
}
//Global Variables based on input
params.outDir = "${params.seqLevel}_output"
params.seqlevel = "${params.seqLevel}".toLowerCase()
//Java task memory allocation via task.memory
javaTaskmem = { it.replace(" GB", "g") }
//Reference data as value channels and reusable therefore
reference = [
grchvers: false,
fa: false,
fai: false,
dict: false,
bwa: false,
hc_dbs: false,
dbsnp: false,
gridss: false,
pcgrbase: false,
intlist: false,
seqlevel: false,
bbres: false
]
reference.grchvers = Channel.fromPath("${params.refDir}/${params.assembly}/pcgr/data/*", type: 'dir').getVal()
reference.fa = Channel.value(file(params.genomes[params.assembly].fa))
reference.fai = Channel.value(file(params.genomes[params.assembly].fai))
reference.dict = Channel.value(file(params.genomes[params.assembly].dict))
reference.bwa = Channel.value(file(params.genomes[params.assembly].bwa))
reference.hc_dbs = Channel.value(file(params.genomes[params.assembly].hc_dbs))
reference.dbsnp = Channel.value(file(params.genomes[params.assembly].dbsnp))
reference.gridss = Channel.value(file(params.genomes[params.assembly].gridss))
reference.pcgrbase = Channel.value(file(params.genomes[params.assembly].pcgr))
reference.refflat = Channel.value(file(params.genomes[params.assembly].refflat))
if(params.microbiome){
reference.pathseq = Channel.value(file(params.genomes[params.assembly].pathseq))
}
//if seqlevel is exome, there is a dir per exome already parsed according to exomeTag
reference.seqlevel = params.seqlevel == "wgs" ? Channel.value(file(params.genomes[params.assembly].wgs)) : Channel.value(file(params.genomes[params.assembly].exome))
//set cosmic
reference.cosmic = params.cosmic == true ? Channel.value(file(params.genomes[params.assembly].cosmic)) : null
//setting of intlist, bed based on seqlevel and exomeTag
reference.intlist = params.seqlevel == "wgs" ? Channel.fromPath("${params.refDir}/${params.assembly}/${params.seqlevel}/wgs.bed.interval_list").getVal() : Channel.fromPath("${params.refDir}/${params.assembly}/${params.seqlevel}/${params.exomeTag}/${params.exomeTag}.bed.interval_list").getVal()
reference.bed = params.seqlevel == "wgs" ? Channel.fromPath("${params.refDir}/${params.assembly}/${params.seqlevel}/wgs.bed").getVal() : Channel.fromPath("${params.refDir}/${params.assembly}/${params.seqlevel}/${params.exomeTag}/${params.exomeTag}.bed").getVal()
/*
================================================================================
-0. PREPROCESS INPUT SAMPLE FILE
================================================================================
*/
/* 0.00: Input using sample.csv, bam.csv, sample_cat
*/
if(params.sampleCsv){
Channel.fromPath("${params.sampleCsv}")
.splitCsv( header: true )
.map { row -> [row.type, row.sampleID, row.meta, file(row.read1), file(row.read2)] }
.into { bbduking; ubaming }
}
if(params.bamCsv){
Channel.fromPath("${params.bamCsv}")
.splitCsv( header: true )
.map { row -> [row.type, row.sampleID, row.meta, file(row.bam)] }
.set { which_bam }
process bam_input {
label 'low_mem'
input:
tuple val(type), val(sampleID), val(meta), file(bam) from which_bam
output:
tuple val(type), val(sampleID), val(meta), file(bam), file("*.bai") into dup_marking
script:
"""
#! bash
samtools index ${bam}
"""
}
}
if(params.sampleCat){
Channel.fromPath("${params.sampleCat}")
.splitCsv( header: true )
.map { row -> [row.type, row.sampleID, row.meta, row.dir, row.ext] }
.set { samplecating }
process samplecat {
label 'low_mem'
publishDir "${params.outDir}/samples/${sampleID}/cat", mode: "copy"
input:
tuple val(type), val(sampleID), val(meta), val(dir), val(ext) from samplecating
output:
tuple val(type), val(sampleID), val(meta), file(read1), file(read2) into ( bbduking, ubaming )
script:
rd1ext = "${ext}".split(';')[0]
rd2ext = "${ext}".split(';')[1]
read1 = "${sampleID}.R1.fastq.gz"
read2 = "${sampleID}.R2.fastq.gz"
"""
#! bash
cat \$(find ${dir} | grep ${rd1ext} | sort) > ${read1}
cat \$(find ${dir} | grep ${rd2ext} | sort) > ${read2}
"""
}
}
// 0.01: Create a uBAM for Pathseq
if(!params.bamCsv){
process ubam {
label 'med_mem'
errorStrategy 'retry'
maxRetries 3
input:
tuple val(type), val(sampleID), val(meta), file(read1), file(read2) from ubaming
output:
tuple val(type), val(sampleID), val(meta), file('*.bam'), file('*.bai') into pathseqing
when:
params.microbiome == true
script:
def taskmem = task.memory == null ? "" : "-Xmx" + javaTaskmem("${task.memory}")
"""
DATE=\$(date +"%Y-%m-%dT%T")
mkdir tmp
{
picard ${taskmem} FastqToSam \
FASTQ=${read1} \
FASTQ2=${read2} \
OUTPUT=${sampleID}.unaligned.bam \
READ_GROUP_NAME=${sampleID} \
SAMPLE_NAME=${sampleID} \
LIBRARY_NAME=LANE_X \
PLATFORM_UNIT=IL_X \
PLATFORM=ILLUMINA \
SEQUENCING_CENTER=UCD \
RUN_DATE=\$DATE \
TMP_DIR="tmp"
} 2>&1 | tee > ${sampleID}.FastqToSam.log.txt
samtools index ${sampleID}.unaligned.bam
rm -r tmp
"""
}
/*
================================================================================
0. PREPROCESS INPUT FASTQ
================================================================================
*/
// 0.1: Input trimming
process bbduk {
label 'med_mem'
publishDir path: "${params.outDir}/samples/${sampleID}/bbduk", mode: "copy", pattern: "*.txt"
input:
tuple val(type), val(sampleID), val(meta), file(read1), file(read2) from bbduking
output:
file('*.txt') into log_bbduk
tuple val(type), val(sampleID), val(meta), file('*.bbduk.R1.fastq.gz'), file('*.bbduk.R2.fastq.gz') into bwa_memming
tuple val(type), val(sampleID), val(meta), file('*.bbduk.R1.fastq.gz'), file('*.bbduk.R2.fastq.gz'), file(read1), file(read2) into fastping
tuple val(type), val(sampleID), val(meta), file(read1), file(read2) into fastqcing
script:
def taskmem = task.memory == null ? "" : "-Xmx" + javaTaskmem("${task.memory}")
"""
{
sh bbduk.sh ${taskmem} \
in1=${read1} \
in2=${read2} \
out1=${sampleID}".bbduk.R1.fastq.gz" \
out2=${sampleID}".bbduk.R2.fastq.gz" \
k=31 \
mink=5 \
hdist=1 \
ktrim=r \
trimq=20 \
qtrim=rl \
maq=20 \
ref=/opt/miniconda/envs/somatic_n-of-1/opt/bbmap-adapters.fa \
tpe \
tbo \
stats=${sampleID}".bbduk.adapterstats.txt" \
overwrite=T
} 2>&1 | tee > ${sampleID}.bbduk.runstats.txt
"""
}
// 0.2: fastp QC of pre-, post-bbduk
process fastp {
label 'low_mem'
publishDir "${params.outDir}/samples/${sampleID}/fastp", mode: "copy", pattern: "*.html"
input:
tuple val(type), val(sampleID), val(meta), file(preread1), file(preread2), file(postread1), file(postread2) from fastping
output:
file('*.html') into fastp_html
file('*.json') into fastp_multiqc
script:
"""
fastp -w ${task.cpus} -h ${sampleID}"_pre.fastp.html" -j ${sampleID}"_pre.fastp.json" --in1 ${preread1} --in2 ${preread2}
fastp -w ${task.cpus} -h ${sampleID}"_post.fastp.html" -j ${sampleID}"_post.fastp.json" --in1 ${postread1} --in2 ${postread2}
"""
}
// 0.3: fastQC of per, post-bbduk
process fastqc {
label 'low_mem'
publishDir "${params.outDir}/samples/${sampleID}/fastqc", mode: "copy", pattern: "*.html"
input:
tuple val(type), val(sampleID), val(meta), file(read1), file(read2) from fastqcing
output:
file('*.html') into fastqc_multiqc
script:
"""
#!/bin/bash
fastqc -t ${task.cpus} --noextract -o ./ ${read1} ${read2}
"""
}
/*
================================================================================
1. ALIGNMENT AND BAM PROCESSING
================================================================================
*/
// 1.0: Input alignment
process bwamem {
label 'high_mem'
errorStrategy 'retry'
maxRetries 3
input:
tuple val(type), val(sampleID), val(meta), file(read1), file(read2) from bwa_memming
file(bwa) from reference.bwa
output:
tuple val(type), val(sampleID), val(meta), file('*.bam'), file('*.bai') into (cramming, dup_marking)
script:
def fa = "${bwa}/*fasta"
"""
DATE=\$(date +"%Y-%m-%dT%T")
RGLINE="@RG\\tID:${sampleID}\\tPL:ILLUMINA\\tSM:${sampleID}\\tDS:${type}\\tCN:UCD\\tLB:LANE_X\\tDT:\$DATE"
bwa mem \
-t${task.cpus} \
-M \
-R \$RGLINE \
${fa} \
${read1} ${read2} | \
samtools sort -T "tmp."${sampleID} -o ${sampleID}".sort.bam"
samtools index ${sampleID}".sort.bam"
"""
}
// 1.1: CRAM alignment and output
// TODO: output upload schema for ENA/EGA
process cram {
label 'low_mem'
publishDir path: "${params.outDir}/samples/${sampleID}/bwa", mode: "copy", pattern: "*.cra*"
input:
tuple val(type), val(sampleID), val(meta), file(bam), file(bai) from cramming
file(bwa) from reference.bwa
output:
tuple file('*.cram'), file('*.crai') into completedcram
script:
"""
samtools view -hC -T ${bwa}/*fasta ${sampleID}".sort.bam" > ${sampleID}".sort.cram"
samtools index ${sampleID}".sort.cram"
"""
}
}
// 1.2: MarkDuplicates
process mrkdup {
label 'high_mem'
publishDir path: "${params.outDir}/samples/${sampleID}/picard", mode: "copy", pattern: "*.txt"
input:
tuple val(type), val(sampleID), val(meta), file(bam), file(bai) from dup_marking
output:
file('*.txt') into mrkdup_multiqc
tuple val(type), val(sampleID), val(meta), file('*.md.bam'), file('*.md.bam.bai') into ( gatk4recaling, gridssing )
script:
def taskmem = task.memory == null ? "" : "-Xmx" + javaTaskmem("${task.memory}")
"""
OUTBAM=\$(echo ${bam} | sed 's/bam/md.bam/')
OUTMET=\$(echo ${bam} | sed 's/bam/md.metrics.txt/')
{
picard ${taskmem} \
MarkDuplicates \
TMP_DIR=./ \
INPUT=${bam} \
OUTPUT=/dev/stdout \
COMPRESSION_LEVEL=0 \
QUIET=TRUE \
METRICS_FILE=\$OUTMET \
REMOVE_DUPLICATES=FALSE \
ASSUME_SORTED=TRUE \
VALIDATION_STRINGENCY=LENIENT \
VERBOSITY=ERROR | samtools view -Shb - > \$OUTBAM
samtools index \$OUTBAM
} 2>&1 | tee > ${sampleID}.picard_markDuplicates.log.txt
"""
}
// 1.3: GATK4 BestPractices
process gtkrcl {
label 'high_mem'
publishDir path: "${params.outDir}/samples/${sampleID}/gatk4/bestpractice", mode: "copy", pattern: "*.GATK4_BQSR.log.txt "
input:
tuple val(type), val(sampleID), val(meta), file(bam), file(bai) from gatk4recaling
file(fasta) from reference.fa
file(fai) from reference.fai
file(dict) from reference.dict
file(dbsnp_files) from reference.dbsnp
file(intlist) from reference.intlist
output:
file('*.table') into gtkrcl_multiqc
tuple val(type), val(sampleID), file('*.bqsr.bam'), file('*.bqsr.bam.bai') into ( germfiltering, gmultimetricing, mosdepthing)
tuple val(type), val(sampleID), val(meta), file('*.bqsr.bam'), file('*.bqsr.bam.bai') into ( hc_germ, cnvgerm )
tuple val(sampleID), val(meta) into metas_pcgr
file("${sampleID}.GATK4_BQSR.log.txt") into bqsr_log
script:
def dbsnp = "${dbsnp_files}/*gz"
"""
{
##ensure seq dict from BAM has same regions as bed interval list
head -n1 ${intlist} > use.interval_list
samtools view -H ${bam} | grep "@SQ" | cut -f 2 > bam_sq.txt
cat bam_sq.txt | while read SEQ; do
export seq=\${SEQ};
perl -ane 'if(\$F[1] eq \$ENV{'seq'}){print \$_;}' ${intlist};
done >> use.interval_list
sed 's/SN://g' bam_sq.txt | while read CHR; do
export chr=\${CHR};
perl -ane 'if(\$F[0] eq \$ENV{'chr'}){print \$_;}' ${intlist};
done >> use.interval_list
gatk BaseRecalibrator \
-R ${fasta} \
-I ${bam} \
--known-sites \$(echo ${dbsnp}) \
--use-original-qualities \
-O ${sampleID}.recal_data.table \
--disable-sequence-dictionary-validation true \
-L use.interval_list
#ApplyBQSR
OUTBAM=\$(echo ${bam} | sed 's/bam/bqsr.bam/')
gatk ApplyBQSR \
-R ${fasta} \
-I ${bam} \
--bqsr-recal-file ${sampleID}.recal_data.table \
--add-output-sam-program-record \
--use-original-qualities \
-O \$OUTBAM \
-L use.interval_list
samtools index \$OUTBAM \$OUTBAM".bai"
} 2>&1 | tee > ${sampleID}.GATK4_BQSR.log.txt
"""
}
// 1.4: scatter-gather implementation for mutect2, lancet
process scat_gath {
label 'low_mem'
input:
file(intlist) from reference.intlist
output:
file('lancet.scatgath.*.bed') into lancet_bedding
file('mutect2.scatgath.*.bed.interval_list') into mutect2_bedding
file('hc.scatgath.*.bed.interval_list') into hc_bedding
script:
def sgcount = params.scatGath
if (params.scatGath == null){
if (params.seqlevel == "exome"){
sgcount = 20
}
else {
sgcount = 100
}
}
"""
##strip out all but chromosomes in the interval_list (no decoys etc)
CHRS=\$(grep -v "@" ${intlist} | cut -f 1 | uniq)
for CHR in \$CHRS; do
grep "SN:\$CHR\\s" ${intlist} >> used.interval_list
done
grep -v "@" ${intlist} >> used.interval_list
##generate scatters
picard IntervalListTools \
I=used.interval_list \
SCATTER_COUNT=${sgcount} \
O=./
##rename scatters and parse into appropriate format for tools
ls temp*/* | while read FILE; do
COUNTN=\$(dirname \$FILE | perl -ane '@s=split(/\\_/); print \$s[1];');
mv \$FILE mutect2.scatgath.\${COUNTN}.bed.interval_list;
cp mutect2.scatgath.\${COUNTN}.bed.interval_list hc.scatgath.\${COUNTN}.bed.interval_list
grep -v @ mutect2.scatgath.\${COUNTN}.bed.interval_list | \
cut -f 1,2,3,5 > lancet.scatgath.\${COUNTN}.bed
done
"""
}
process Mosdepth {
input:
tuple val(type), val(sampleID), file(bam), file(bai) from mosdepthing
file(bed) from reference.bed
output:
file('*') into mosdepth_multiqc
script:
"""
mosdepth \
--no-per-base \
--by ${bed} \
${sampleID} \
${bam}
"""
}
/*
================================================================================
2. MUTATION CALLING
================================================================================
*/
// 2.0: GATK4 Germline Haplotypecaller
// Groovy to combine scatter-gather BEDs with bam file for germline
hcbedding = hc_bedding.flatten()
hc_germ
.map { it -> [it[0],it[1],it[2],it[3],it[4]] }
.combine(hcbedding)
.set { hcgermbedding }
process haplotypecaller {
label 'med_mem'
errorStrategy 'retry'
maxRetries 3
input:
tuple val(type), val(sampleID), val(meta), file(bam), file(bai), file(intlist) from hcgermbedding
file(fasta) from reference.fa
file(fai) from reference.fai
file(dict) from reference.dict
file(dbsnp_files) from reference.dbsnp
file(hc_dbs_files) from reference.hc_dbs
output:
tuple val(sampleID), val(meta), file('*sort.hc.vcf') into hc_gt
tuple val(type), val(sampleID) into ver_germID
when:
type == "germline" & params.germline != false \
| type == "germsoma" & params.germline != false
script:
def taskmem = task.memory == null ? "" : "--java-options \"-Xmx" + javaTaskmem("${task.memory}") + "\""
def dbsnp = "${dbsnp_files}/*gz"
def omni = "${hc_dbs_files}/KG_omni*.gz"
def kgp1 = "${hc_dbs_files}/KG_phase1*.gz"
def hpmp = "${hc_dbs_files}/hapmap*.gz"
"""
SCATGATHN=\$(echo ${intlist} | perl -ane '@s=split(/\\./);print \$s[2];')
gatk ${taskmem} HaplotypeCaller \
-R ${fasta} \
-I ${bam} \
--dont-use-soft-clipped-bases \
--standard-min-confidence-threshold-for-calling 20 \
--dbsnp \$(echo ${dbsnp}) \
--native-pair-hmm-threads ${task.cpus} \
-O ${sampleID}".\${SCATGATHN}.hc.vcf" \
--disable-sequence-dictionary-validation true \
-L ${intlist}
picard SortVcf \
I=${sampleID}".\${SCATGATHN}.hc.vcf" \
O=${sampleID}".\${SCATGATHN}.sort.hc.vcf" \
SD=${dict}
"""
}
//in case of germsoma, verify the true germID
//only one with germline as type
ver_germID
.filter( { it[0] == "germline" } )
.map( { it -> it[1] } )
.into { gridssgermID; vcfGRaID }
//group those outputs
hc_gt
.groupTuple()
.map { it -> tuple(it[0], it[1].unique(), it[2..-1].flatten()) }
.set { hc_fm }
/* 2.0.5: GATK germline CNV
*/
process germCnvkit {
publishDir path: "${params.outDir}/samples/${sampleID}/cnvkit", mode: "copy"
label 'med_mem'
errorStrategy 'retry'
maxRetries 3
input:
tuple val(type), val(sampleID), val(meta), file(bam), file(bai) from cnvgerm
file(fasta) from reference.fa
file(fai) from reference.fai
file(refflat) from reference.refflat
file(bed) from reference.bed
output:
file('*') into germCnvkit_comp
tuple file("${sampleID}.call.cns"), file("${sampleID}.scatter.pdf"), file("${sampleID}.diagram.pdf") into sendmail_cnvkit
when:
type == "germline" & params.germline != false & params.germCNV != false \
| type == "germsoma" & params.germline != false & params.germCNV != false
script:
seqlev = params.seqlevel == "wgs" ? "wgs" : "hybrid"
"""
cnvkit.py access ${fasta} -o access.bed
cnvkit.py autobin -f ${fasta} \
-m ${seqlev} \
-t access.bed \
--annotate ${refflat} \
--short-names \
--target-output-bed target.bed \
--antitarget-output-bed antitarget.bed \
${bam}
# For each sample...
cnvkit.py coverage -o ${sampleID}.targetcoverage.cnn \
${bam} target.bed
cnvkit.py coverage -o ${sampleID}.antitargetcoverage.cnn \
${bam} antitarget.bed
# reference
cnvkit.py reference -f ${fasta} \
-o reference.cnn \
${sampleID}.antitargetcoverage.cnn \
${sampleID}.targetcoverage.cnn
# cnr
cnvkit.py fix -o ${sampleID}.cnr ${sampleID}.targetcoverage.cnn ${sampleID}.antitargetcoverage.cnn reference.cnn
# cns
cnvkit.py segment -o ${sampleID}.cns ${sampleID}.cnr
#call
cnvkit.py call -o ${sampleID}.call.cns ${sampleID}.cns
# Optionally, with --scatter and --diagram
cnvkit.py scatter -s ${sampleID}.cns -o ${sampleID}.scatter.pdf ${sampleID}.cnr
cnvkit.py diagram -s ${sampleID}.cns -o ${sampleID}.diagram.pdf ${sampleID}.cnr
"""
}
/* 2.1.1: GRIDSS SV calling in WGS
* because we do not know order or number of samples, create tuple with
* dummy as first and all others as list of elements
* then count them inside process
*/
gridssing
.collect()
.map { it -> tuple(it.flatten()) }
.set { gridssin }
process gridss {
label 'max_mem'
publishDir path: "${params.outDir}/combined/gridss", mode: "copy", pattern: "*.[!bam, vcf.gz]"
input:
file(listbams) from gridssin
val(germlineID) from gridssgermID.collect().flatten().unique()
file(bwa) from reference.bwa
file(gridss_files) from reference.gridss
output:
file('*') into completegridss
tuple val(germlineID), file("tumords.txt"), file("${params.runID}.output.vcf.gz") into gridssfilter
when:
params.seqlevel == "wgs"
script:
def jvmheap_taskmem = task.memory == null ? "" : "--jvmheap " + javaTaskmem("${task.memory}")
def fasta = "${bwa}/*fasta"
def gridss_blacklist = "${gridss_files}/gridss_blacklist.noChr.bed"
def gridss_props = "${gridss_files}/dbs/gridss/gridss.properties"
"""
GERMLINEBAM=\$(ls | grep ${germlineID} | grep bam\$ | grep -v bai)
BAMFILES=\$(echo -n \$GERMLINEBAM" "\$(ls *.bam | grep -v \$GERMLINEBAM))
LABELS=\$(echo -n ${germlineID}" "\$(ls *bam | grep -v ${germlineID} | grep -v assembly | cut -d "." -f1) | sed 's/\\s */,/g')
TUMORDS=\$(echo \$LABELS | perl -ane '@s=split(/\\,/);for(\$i=2;\$i<=@s;\$i++){push(@o,\$i);} print join(",",@o[0..\$#o]) . "\\n";')
TASKCPUS=\$(( ${task.cpus} / 4 )) ##"preprocessing will use up to 200-300% CPU per thread"
echo \$TUMORDS > tumords.txt
gridss.sh \
--reference \$(echo ${fasta}) \
--output ${params.runID}".output.vcf.gz" \
--assembly ${params.runID}".assembly.bam" \
--threads \$TASKCPUS \
--jar /opt/gridss/gridss-2.9.4-gridss-jar-with-dependencies.jar \
--workingdir ./ ${jvmheap_taskmem} \
--blacklist ${gridss_blacklist} \
--steps All \
--configuration ${gridss_props} \
--maxcoverage 50000 \
--labels \$LABELS \
\$BAMFILES
"""
}
/* 2.1.2: GRIDSS SV filtering
*/
process gridss_filter {
label 'max_mem'
publishDir path: "${params.outDir}/combined/gridss", mode: "copy"
input:
tuple val(germlineID), file(tumords), file("${params.runID}.output.vcf.gz") from gridssfilter
output:
file('*') into gridssfilterd
tuple val(germlineID), file("${params.runID}.somatic_filter.vcf.bgz") into gridsspp
when:
params.seqlevel == "wgs"
script:
"""
Rscript --vanilla /opt/gridss/gridss_somatic_filter.R \
--input ${params.runID}".output.vcf.gz" \
--output ${params.runID}".somatic_filter.vcf" \
--plotdir ./ \
--scriptdir /opt/gridss \
--normalordinal 1 \
--tumourordinal \$(cat $tumords)
"""
}
//2.1.3 GRIDSS parse and plot
process gridss_vcf_pp {
label 'low_mem'
errorStrategy 'retry'
maxRetries 3
publishDir path: "${params.outDir}/combined/gridss", mode: "copy", pattern: "*.[pdf, tsv, png, vcf.gz]"
input:
tuple val(germlineID), file(vcf) from gridsspp
file(bwa) from reference.bwa
output:
file('*') into completegridsspp
file("*.pdf") into sendmail_gridss_pdf
file("*.tsv") into sendmail_gridss_tsv
when:
params.seqlevel == "wgs"
script:
def dict = "${bwa}/*dict"
def which_genome = params.assembly == "GRCh37" ? "hg19" : "hg38"
"""
tabix ${vcf}
Rscript -e "somenone::gridss_parse_plot(vcf = \\"${params.runID}.somatic_filter.vcf.bgz\\", germline_id = \\"${germlineID}\\", dict_file = \$(echo \\"${dict}\\"), which_genome = \\"${which_genome}\\", output_path = NULL)"
"""
}
// 2.2: HaplotypeCaller merge
process hc_merge {
label 'high_mem'
publishDir path: "${params.outDir}/samples/${sampleID}/haplotypecaller", mode: "copy", pattern: '*.vcf.*'
input:
tuple val(sampleID), val(meta), file(rawvcfs) from hc_fm
output:
tuple val(sampleID), val(meta), file("${sampleID}.hc.merge.vcf.gz"), file("${sampleID}.hc.merge.vcf.gz.tbi") into ( cpsr_vcf, vep_hc_vcf )
script:
"""
ls *.sort.hc.vcf > vcf.list
picard MergeVcfs I=vcf.list O=${sampleID}".hc.merge.vcf"
bgzip ${sampleID}".hc.merge.vcf"
tabix ${sampleID}".hc.merge.vcf.gz"
"""
}
// 2.3: CPSR annotation of GATK4 Germline
process cpsrreport {
label 'med_mem'
publishDir "${params.outDir}/reports/cpsr", mode: "copy", pattern: "*.html"
publishDir "${params.outDir}/samples/${sampleID}/cpsr", mode: "copy", pattern: "*[!.html]"
input:
tuple val(sampleID), val(meta), file(vcf), file(tbi) from cpsr_vcf
file(grchver) from reference.grchvers
file(pcgrbase) from reference.pcgrbase
output:
file('*') into cpsr_vcfs
file("${metaid}.cpsr.${grchv}.html") into sendmail_cpsr
script:
grchv = "${grchver}".split("\\/")[-1]
metaid = "${meta}".replaceAll("\\s *", "_").replaceAll("[\\[\\(\\)\\]]","").replaceAll("\"","")
"""
{
##CPSR v0.6.1
cpsr.py \
--no-docker \
--no_vcf_validate \
--panel_id 0 \
--query_vcf ${vcf} \
--pcgr_dir ${pcgrbase} \
--output_dir ./ \
--genome_assembly ${grchv} \
--conf ${pcgrbase}/data/${grchv}/cpsr_configuration_default.toml \
--sample_id ${metaid}
} 2>&1 | tee > ${sampleID}.cpsr.log.txt
"""
}
// 2.4: PicardTools metrics suite for MultiQC HTML report
process mltmet {
label 'med_mem'
publishDir "${params.outDir}/samples/${sampleID}/metrics", mode: "copy"
input:
tuple val(type), val(sampleID), file(bam), file(bai) from gmultimetricing
file(fasta) from reference.fa
file(fai) from reference.fai
file(dict) from reference.dict
file(intlist) from reference.intlist
output:
file('*.txt') into multimetrics_multiqc
script:
def taskmem = task.memory == null ? "" : "-Xmx" + javaTaskmem("${task.memory}")
"""
{
if [[ ${params.seqlevel} == "exome" ]]; then
picard ${taskmem} CollectHsMetrics \
I=${bam} \
O=${sampleID}".hs_metrics.txt" \
TMP_DIR=./ \
R=${fasta} \
VALIDATION_STRINGENCY=LENIENT \
BAIT_INTERVALS=${intlist} \
TARGET_INTERVALS=${intlist}
fi
picard ${taskmem} CollectAlignmentSummaryMetrics \
I=${bam} \
O=${sampleID}".AlignmentSummaryMetrics.txt" \
TMP_DIR=./ \
VALIDATION_STRINGENCY=LENIENT \
R=${fasta}
picard ${taskmem} CollectMultipleMetrics \
I=${bam} \
O=${sampleID}".CollectMultipleMetrics.txt" \
TMP_DIR=./ \
VALIDATION_STRINGENCY=LENIENT \
R=${fasta}
picard ${taskmem} CollectSequencingArtifactMetrics \
I=${bam} \
O=${sampleID}".artifact_metrics.txt" \
TMP_DIR=./ \
VALIDATION_STRINGENCY=LENIENT \
R=${fasta}
picard ${taskmem} CollectInsertSizeMetrics \
I=${bam} \
O=${sampleID}".insert_size_metrics.txt" \
H=${bam}".histogram.pdf" \
VALIDATION_STRINGENCY=LENIENT \
TMP_DIR=./
} 2>&1 | tee > ${sampleID}.picard.metrics.log
"""
}
// 2.5: filter germline channel, tap into somatic channels for all processes subsequent
if(!params.germOnly){
def germfilter = branchCriteria {
germfiltered: it[0] == "germline"
return it
somafiltered: true
return it
}
germfiltering
.branch(germfilter)
.set { somagerm }
somagerm.somafiltered
.map { [it[1], it[2..-1]] }
.tap { somatap }
somagerm.germfiltered
.map { [it[1], it[2..-1]] }
.tap { germtap }
somatap.combine(germtap).tap{ somagermtap }
somagermtap
.map { it -> tuple(it[0],
it[1][0..1],
it[2],
it[3][0..1]).flatten() }
.into { mutect2somaticing; mutect2_contam; facetsomaing; mantastrelka2ing; lanceting; gpling }
//2.6.1: SCNA with facets CSV snp-pileup
process fctcsv {
label 'med_mem'
publishDir "${params.outDir}/samples/${sampleID}/facets", mode: "copy"
input:
tuple val(sampleID), file(tumourbam), file(tumourbai), val(germlineID), file(germlinebam), file(germlinebai) from facetsomaing
file(dbsnp_files) from reference.dbsnp
output:
tuple file("${sampleID}.fit_cncf_jointsegs.tsv"), file("${sampleID}.fit_ploidy_purity.tsv") into ( facets_consensusing, facets_pyclone )
tuple val(sampleID), file("${sampleID}.cncf_jointsegs.pcgr.tsv"), file("${sampleID}.fit_ploidy_purity.pcgr.tsv") into facets_pcgr
file("${sampleID}.facets.log.txt") into facets_log
script:
def dbsnp = "${dbsnp_files}/*gz"
"""
{ snp-pileup \
\$(echo ${dbsnp}) \
-r 10 \
-p \