-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.nf
5200 lines (4485 loc) · 204 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
// NGS580 Target exome analysis for 580 gene panel
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import groovy.json.JsonSlurper;
def jsonSlurper = new JsonSlurper()
def workflowTimestamp = "${workflow.start.format('yyyy-MM-dd-HH-mm-ss')}"
def username = System.getProperty("user.name")
String localhostname = java.net.InetAddress.getLocalHost().getHostName();
Date now = new Date()
SimpleDateFormat timestamp = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss")
def currentDirPath = new File(System.getProperty("user.dir")).getCanonicalPath()
Process uname_proc = 'uname'.execute()
def uname = "${uname_proc.text.trim()}"
def NXF_PIDFILE = ".nextflow.pid"
if(uname == "Linux"){
// /proc/self only works on Linux
int pid = Integer.parseInt(new File("/proc/self").getCanonicalFile().getName())
File pid_file = new File("${NXF_PIDFILE}")
pid_file.write("${pid}\n")
}
// ~~~~~~~~~~ CONFIGURATION ~~~~~~~~~~ //
// configure pipeline settings
// order of evaluation
// 1. uses CLI passed arg in 'params'
// 2. uses nextflow.config arg in 'params'
// 3. uses values from config.json
// 4. uses default value
// default values; overriden by nextflow.config and CLI
params.configFile = "config.json"
params.reportDir = "report"
params.outputDir = "output"
params.ref_dir = "ref"
params.nxf_completion_log = ".nextflow.completion.log"
params.GIT_CURRENT_BRANCH = "none"
params.GIT_CURRENT_COMMIT = "none"
params.GIT_CURRENT_TAG = "none"
params.GIT_RECENT_TAG = "none"
// default config values
def defaultParams = [:]
defaultParams.runID = "NGS607_run"
defaultParams.workflowLabel = "NGS607"
defaultParams.numTargetSplitLines = 50
defaultParams.targetsBed = "targets/targets.629.bed"
defaultParams.targetsAnnotatedBed = "targets/targets.annotated.629.bed"
defaultParams.baitintervals = "targets/bait.interval_list"
defaultParams.targetintervals = "targets/targets.interval_list"
defaultParams.projectDir = "${workflow.projectDir}"
defaultParams.samplesheet = "samples.analysis.tsv"
defaultParams.demuxSamplesheet = "demux-samplesheet.csv"
defaultParams.sampleTumorNormalCsv = "samples.tumor.normal.csv"
defaultParams.SeraCareSelectedTsv = "data/SeraCare-selected-variants.tsv"
defaultParams.SeraCareErrorRate = 0.02
defaultParams.SeraCareSelectedVariantsdisTsv = "data/SeraCare-selected-variants-dist.tsv"
defaultParams.SeraCareTruthSet = "data/SeraSeq-Truth.txt"
defaultParams.reconv_hg19_genomelength = "data/hg19_genome_length_PACT.txt"
defaultParams.genes_tsv = "data/probe_genes_heatmap_list.tsv"
defaultParams.CNVPool = "ref/CNV-Pool/NGS607-pool.cnn"
defaultParams.HapMapBam = "ref/HapMap-Pool/NGS607/HapMap-pool.bam"
defaultParams.HapMapBai = "ref/HapMap-Pool/NGS607/HapMap-pool.bam.bai"
// load the JSON config, if present
def externalConfig
def externalConfigFile_obj = new File("${params.configFile}")
if ( externalConfigFile_obj.exists() ) {
log.info("Loading configs from ${params.configFile}")
String externalConfigJSON = externalConfigFile_obj.text
externalConfig = jsonSlurper.parseText(externalConfigJSON)
}
// add and overwrite all values in defaultParams with items from config
if( externalConfig ){
log.info("Updating with configs from ${params.configFile}")
// overwrite existing default params with JSON config values
defaultParams.keySet().each { key ->
if( externalConfig.containsKey(key) ){
defaultParams[key] = externalConfig[key]
}
}
// append the missing JSON configs to default params; doesn't overwrite
externalConfig.keySet().each { key ->
if( ! defaultParams.containsKey(key) ){
defaultParams[key] = externalConfig[key]
}
}
}
// add all the entries to params; wont overwrite existing entries from CLI or nextflow.config
params << defaultParams
// set variables to use throughout the pipeline
def numTargetSplitLines = params.numTargetSplitLines
def HapMapBam = params.HapMapBam
def HapMapBai = params.HapMapBai
def targetsBed = params.targetsBed
def targetsAnnotatedBed = params.targetsAnnotatedBed
def baitintervals = params.baitintervals
def targetintervals = params.targetintervals
def runID = params.runID
def samplesheet = params.samplesheet
def demuxSamplesheet = params.demuxSamplesheet
def sampleTumorNormalCsv = params.sampleTumorNormalCsv
def SeraCareSelectedTsv = params.SeraCareSelectedTsv
def SeraCareSelectedTsvFile = new File("${SeraCareSelectedTsv}").getName()
def SeraCareSelectedVariantsdisTsv = params.SeraCareSelectedVariantsdisTsv
def SeraCareTruthSet = params.SeraCareTruthSet
def SeraCareErrorRate = params.SeraCareErrorRate
def CNVPool = params.CNVPool
def reconv_hg19_genomelength = params.reconv_hg19_genomelength
def genes_tsv = params.genes_tsv
def projectDir = params.runID
def pactid = new File("${demuxSamplesheet}").readLines()[3].split(',')[1]
// Enable or disable some pipeline steps here TODO: better config management for this
disable_multiqc = true // for faster testing of the rest of the pipeline
disable_msisensor = true // breaks on very small demo datasets
disable_eval_pair_vcf = true
disable_varscan2 = true
// load a mapping dict to use for keeping track of the names and suffixes for some files throughout the pipeline
String filemapJSON = new File("filemap.json").text
def filemap = jsonSlurper.parseText(filemapJSON)
// names of some important output files to use throughout the pipeline
def all_annotations_file = filemap.files.all_annotations_file
def all_seracare_annotations_file = filemap.files.all_seracare_annotations_file
def all_HapMapPool_annotations_file = filemap.files.all_HapMapPool_annotations_file
def samplesheet_output_file = filemap.files.samplesheet_output_file
def sample_coverage_file = filemap.files.sample_coverage_file
def interval_coverage_file = filemap.files.interval_coverage_file
def signatures_weights_file = filemap.files.signatures_weights_file
def targets_annotations_file = filemap.files.targets_annotations_file
def tmb_file = filemap.files.tmb_file
def git_json = filemap.files.git_json
def callable_loci_file = filemap.files.callable_loci_file
def snp_overlap_file = filemap.files.snp_overlap_file
def outputDirPath = new File(params.outputDir).getCanonicalPath()
def reportDirPath = new File(params.reportDir).getCanonicalPath()
// REFERENCE FILES
params.ref_fa = "${params.ref_dir}/iGenomes/Homo_sapiens/UCSC/hg19/Sequence/WholeGenomeFasta/genome.fa"
params.ref_fa_bwa_dir = "${params.ref_dir}/BWA/hg19"
params.ref_fai = "${params.ref_dir}/iGenomes/Homo_sapiens/UCSC/hg19/Sequence/WholeGenomeFasta/genome.fa.fai"
params.ref_dict = "${params.ref_dir}/iGenomes/Homo_sapiens/UCSC/hg19/Sequence/WholeGenomeFasta/genome.dict"
params.ref_chrom_sizes = "${params.ref_dir}/Illumina/hg19/chrom.sizes"
params.microsatellites = "${params.ref_dir}/msisensor/microsatellites/microsatellites.clean_chr_only_list"
params.trimmomatic_contaminant_fa = "${params.ref_dir}/contaminants/trimmomatic.fa"
params.gatk_bundle_dir = "${params.ref_dir}/gatk-bundle"
params.gatk_1000G_phase1_indels_hg19_vcf = "${params.gatk_bundle_dir}/1000G_phase1.indels.hg19.vcf"
params.gatk_1000G_phase1_indels_hg19_vcf_idx = "${params.gatk_bundle_dir}/1000G_phase1.indels.hg19.vcf.idx"
params.mills_and_1000G_gold_standard_indels_hg19_vcf = "${params.gatk_bundle_dir}/Mills_and_1000G_gold_standard.indels.hg19.vcf"
params.mills_and_1000G_gold_standard_indels_hg19_vcf_idx = "${params.gatk_bundle_dir}/Mills_and_1000G_gold_standard.indels.hg19.vcf.idx"
params.dbsnp_ref_vcf = "${params.gatk_bundle_dir}/dbsnp_138.hg19.vcf"
params.dbsnp_ref_vcf_idx = "${params.gatk_bundle_dir}/dbsnp_138.hg19.vcf.idx"
params.dbsnp_ref_vcf_gz = "${params.gatk_bundle_dir}/dbsnp_138.hg19.vcf.gz"
params.dbsnp_ref_vcf_gz_tbi = "${params.gatk_bundle_dir}/dbsnp_138.hg19.vcf.gz.tbi"
params.cosmic_ref_vcf = "${params.ref_dir}/hg19/CosmicCodingMuts_v73.hg19.vcf"
params.cosmic_ref_vcf_idx = "${params.ref_dir}/hg19/CosmicCodingMuts_v73.hg19.vcf.idx"
params.common_snp_vcf = "${params.ref_dir}/hg19/common_all_20170710.vcf.gz"
params.common_snp_vcf_tbi = "${params.ref_dir}/hg19/common_all_20170710.vcf.gz.tbi"
// ~~~~~~~~~~ VALIDATION ~~~~~~~~~~ //
// make sure reference data directory exists
def ref_dir = new File("${params.ref_dir}")
if( !ref_dir.exists() ){
log.error "Ref dir does not exist: ${params.ref_dir}"
exit 1
}
// make sure annovar reference databases directory exist
def ANNOVAR_DB_DIR = new File("${params.ANNOVAR_DB_DIR}")
if( !ANNOVAR_DB_DIR.exists() ){
log.error "ANNOVAR database dir does not exist: ${params.ANNOVAR_DB_DIR}"
exit 1
}
// ~~~~~ START WORKFLOW ~~~~~ //
log.info "~~~~~~~ NGS580 Pipeline ~~~~~~~"
if(uname == "Linux"){
// /proc/self only works on Linux
int pid = Integer.parseInt(new File("/proc/self").getCanonicalFile().getName())
log.info "* pid: ${pid}"
}
log.info "* hostname: ${localhostname}"
log.info "* uname: ${uname}"
log.info "* Launch time: ${workflowTimestamp}"
log.info "* Run ID: ${runID}"
log.info "* Samplesheet: ${samplesheet}"
log.info "* demuxSamplesheet: ${demuxSamplesheet}"
log.info "* Targets: ${targetsBed}"
log.info "* Project dir: ${workflow.projectDir}"
log.info "* Launch dir: ${workflow.launchDir}"
log.info "* Work dir: ${workflow.workDir.toUriString()}"
log.info "* Output dir: ${outputDirPath}"
log.info "* Profile: ${workflow.profile ?: '-'}"
log.info "* Script name: ${workflow.scriptName ?: '-'}"
log.info "* Script ID: ${workflow.scriptId ?: '-'}"
log.info "* Container engine: ${workflow.containerEngine?:'-'}"
log.info "* Workflow session: ${workflow.sessionId}"
log.info "* Nextflow run name: ${workflow.runName}"
log.info "* Nextflow version: ${workflow.nextflow.version}, build ${workflow.nextflow.build} (${workflow.nextflow.timestamp})"
log.info "* Launch command:\n${workflow.commandLine}\n"
// ~~~~~ DATA INPUT ~~~~~ //
// targets .bed file
Channel.fromPath( file(targetsBed) ).set{ targets_bed } // TODO: why is this here? duplicated..
Channel.fromPath( file(targetsAnnotatedBed) ).set{ targets_annotated_bed }
Channel.fromPath( file(baitintervals) ).set{ bait_intervals }
Channel.fromPath( file(targetintervals) ).set{ target_intervals }
// reference files
Channel.fromPath( file(targetsBed) ).into { targets_bed;
targets_bed2;
targets_bed3;
targets_bed4;
targets_bed5;
targets_bed6;
targets_bed7;
targets_bed8;
targets_bed9;
targets_bed10;
targets_bed11;
targets_bed12;
targets_bed13;
targets_bed14 }
Channel.fromPath( file(params.ref_fa) ).into { ref_fasta;
ref_fasta2;
ref_fasta3;
ref_fasta4;
ref_fasta5;
ref_fasta6;
ref_fasta7;
ref_fasta8;
ref_fasta9;
ref_fasta10;
ref_fasta11;
ref_fasta12;
ref_fasta13;
ref_fasta14;
ref_fasta15;
ref_fasta16;
ref_fasta17;
ref_fasta18;
ref_fasta19;
ref_fasta20;
ref_fasta21 }
Channel.fromPath( file(params.ref_fai) ).into { ref_fai;
ref_fai2;
ref_fai3;
ref_fai4;
ref_fai5;
ref_fai6;
ref_fai7;
ref_fai8;
ref_fai9;
ref_fai10;
ref_fai11;
ref_fai12;
ref_fai13;
ref_fai14;
ref_fai15;
ref_fai16;
ref_fai17;
ref_fai18;
ref_fai19;
ref_fai20;
ref_fai21 }
Channel.fromPath( file(params.ref_dict) ).into { ref_dict;
ref_dict2;
ref_dict3;
ref_dict4;
ref_dict5;
ref_dict6;
ref_dict7;
ref_dict8;
ref_dict9;
ref_dict10;
ref_dict11;
ref_dict12;
ref_dict13;
ref_dict14;
ref_dict15;
ref_dict16;
ref_dict17;
ref_dict18;
ref_dict19;
ref_dict20;
ref_dict21 }
Channel.fromPath( file(params.reconv_hg19_genomelength) ).set{ hg19_reconCNV_genome_PACT }
Channel.fromPath( file(params.ref_chrom_sizes) ).set{ ref_chrom_sizes }
Channel.fromPath( file(params.trimmomatic_contaminant_fa) ).set{ trimmomatic_contaminant_fa }
Channel.fromPath( file(params.ref_fa_bwa_dir) ).set{ ref_fa_bwa_dir }
Channel.fromPath( file(params.gatk_1000G_phase1_indels_hg19_vcf) ).into{ gatk_1000G_phase1_indels_vcf;
gatk_1000G_phase1_indels_vcf2;
gatk_1000G_phase1_indels_vcf3;
gatk_1000G_phase1_indels_vcf4 }
Channel.fromPath( file(params.gatk_1000G_phase1_indels_hg19_vcf_idx) ).into{ gatk_1000G_phase1_indels_vcf_idx;
gatk_1000G_phase1_indels_vcf_idx2;
gatk_1000G_phase1_indels_vcf_idx3;
gatk_1000G_phase1_indels_vcf_idx4 }
Channel.fromPath( file(params.mills_and_1000G_gold_standard_indels_hg19_vcf) ).into{ mills_and_1000G_gold_standard_indels_vcf;
mills_and_1000G_gold_standard_indels_vcf2;
mills_and_1000G_gold_standard_indels_vcf3;
mills_and_1000G_gold_standard_indels_vcf4 }
Channel.fromPath( file(params.mills_and_1000G_gold_standard_indels_hg19_vcf_idx) ).into{ mills_and_1000G_gold_standard_indels_vcf_idx;
mills_and_1000G_gold_standard_indels_vcf_idx2;
mills_and_1000G_gold_standard_indels_vcf_idx3;
mills_and_1000G_gold_standard_indels_vcf_idx4 }
Channel.fromPath( file(params.dbsnp_ref_vcf) ).into{ dbsnp_ref_vcf;
dbsnp_ref_vcf2;
dbsnp_ref_vcf3;
dbsnp_ref_vcf4;
dbsnp_ref_vcf5;
dbsnp_ref_vcf6;
dbsnp_ref_vcf7;
dbsnp_ref_vcf8 }
Channel.fromPath( file(params.dbsnp_ref_vcf_idx) ).into{ dbsnp_ref_vcf_idx;
dbsnp_ref_vcf_idx2;
dbsnp_ref_vcf_idx3;
dbsnp_ref_vcf_idx4;
dbsnp_ref_vcf_idx5;
dbsnp_ref_vcf_idx6;
dbsnp_ref_vcf_idx7;
dbsnp_ref_vcf_idx8 }
Channel.fromPath( file(params.dbsnp_ref_vcf_gz) ).set { dbsnp_ref_vcf_gz }
Channel.fromPath( file(params.dbsnp_ref_vcf_gz_tbi) ).set { dbsnp_ref_vcf_gz_tbi }
Channel.fromPath( file(params.cosmic_ref_vcf) ).into{ cosmic_ref_vcf; cosmic_ref_vcf2 }
Channel.fromPath( file(params.cosmic_ref_vcf_idx) ).into{ cosmic_ref_vcf_idx; cosmic_ref_vcf_idx2 }
Channel.fromPath( file(params.common_snp_vcf) ).set{ common_snp_vcf }
Channel.fromPath( file(params.common_snp_vcf_tbi) ).set{ common_snp_vcf_tbi }
Channel.fromPath( file(params.microsatellites) ).set{ microsatellites }
Channel.fromPath( file(params.ANNOVAR_DB_DIR) ).into { annovar_db_dir;
annovar_db_dir2;
annovar_db_dir3;
annovar_db_dir4 }
// report and output dir
Channel.fromPath("${outputDirPath}").into { analysis_output; analysis_output2 }
// load analysis report files
Channel.fromPath("${reportDirPath}/util").into { report_utils; report_utils2 }
Channel.fromPath("${reportDirPath}/analysis/*")
.set { analysis_report_files_base }
analysis_report_files_base.mix(report_utils).set { analysis_report_files }
// load samples report files
Channel.fromPath("${reportDirPath}/samples/*")
.toList()
.map { items ->
return( [items])
}
.set { samples_report_files }
// read samples from analysis samplesheet
Channel.fromPath( file(samplesheet) )
.splitCsv(header: true, sep: '\t')
.map{row ->
def sampleID = row['Sample']
def reads1 = row['R1'].tokenize( ',' ).collect { file(it) } // comma-sep string into list of files
def reads2 = row['R2'].tokenize( ',' ).collect { file(it) }
return [ sampleID, reads1, reads2 ]
}
.tap { samples_R1_R2; samples_R1_R2_2 } // set of all fastq R1 R2 per sample
.map { sampleID, reads1, reads2 ->
return [ reads1, reads2 ]
}
.flatMap().flatMap()
.set { samples_each_fastq } // emit each fastq file individually, no sampleID
// read sample tumor-normal pairs from analysis sheet
Channel.fromPath( file(samplesheet) )
.splitCsv(header: true, sep: '\t')
.map { row ->
def tumorID = row['Tumor']
def normalID = row['Normal']
return [ tumorID, normalID ]
}
.filter { item ->
item[0] != item[1] // remove Normal samples
}
.tap { samples_pairs_with_NA; samples_pairs_with_NA2 }
.filter { item ->
item[1] != 'NA' // unpaired samples
}
.into { samples_pairs;
samples_pairs2;
samples_pairs3;
samples_pairs4 }
// read sample IDs from analysis sheet
Channel.fromPath( file(samplesheet) )
.splitCsv(header: true, sep: '\t')
.map{row ->
def sampleID = row['Sample']
return(sampleID)
}
.unique()
.into { sampleIDs; sampleIDs2; sampleIDs3 }
// find all the HapMap samples
sampleIDs2.filter {
def is_hapmap = "${it}".toLowerCase().contains("hapmap")
return(is_hapmap)
}.set { hapmap_sample_ids }
// ref HapMap Pool bam and bai
Channel.from([ [file("${HapMapBam}"), file("${HapMapBai}")] ]).filter { items ->
def bam = items[0]
def bai = items[1]
// only run these steps if params were set and files exist
HapMapBam && HapMapBai && bam.exists() && bai.exists()
}.set { hapmap_pool_ch }
// find all the SeraCare samples
sampleIDs3.filter {
def is_seracare = "${it}".toLowerCase().contains("seracare")
return(is_seracare)
}.set { seracare_sample_ids }
Channel.fromPath( "${SeraCareSelectedTsv}").into { seracare_selected_tsv; seracare_selected_tsv2 }
Channel.fromPath( file(SeraCareSelectedVariantsdisTsv)).into {seracare_selected_variants_dist_tsv; seracare_selected_variants_dist_tsv2}
Channel.fromPath( file(SeraCareTruthSet)).into {seracare_truth_set; seracare_truth_set2 }
Channel.fromPath("/gpfs/data/molecpathlab/production/NGS607/",type: 'dir').set { ngs607_dir }
Channel.fromPath("${CNVPool}").set { cnv_pool_ch }
Channel.fromPath( file(samplesheet) ).set { samples_analysis_sheet }
// Channels for probe heatmap
Channel.fromPath(file(genes_tsv)).set{ probe_genes_tsv }
params.metrics_dir = "/gpfs/data/molecpathlab/production/NGS607/${runID}/output/CollectHsMetrics"
metrics_dir_chan = Channel.fromPath("${params.metrics_dir}")
hsmetrics_coverage_files = Channel.fromPath("${params.metrics_dir}/*PerTargetCoverage.txt").toList()
// logging channels
Channel.from("Sample\tProgram\tType\tNote\tFiles").set { failed_samples }
Channel.from("Comparison\tTumor\tNormal\tChunk\tProgram\tProgramType\tNote\tFiles").set { failed_pairs }
// ~~~~~ PIPELINE TASKS ~~~~~ //
// PREPROCESSING
process git {
// get repo information
publishDir "${params.outputDir}", mode: 'copy'
output:
file("${output_file}") into git_json_ch
script:
output_file = "${git_json}"
"""
git.py --dir "${workflow.projectDir}" -o "${output_file}"
"""
}
process copy_samplesheet {
// make a copy of the samplesheet in the output directory
// this ensures the output sheet has the correct name
publishDir "${params.outputDir}", mode: 'copy'
executor "local"
input:
file(input_sheet: "input_samplesheet.tsv") from samples_analysis_sheet
output:
file("${samplesheet_output_file}") into samplesheet_output_file_ch
val("") into done_copy_samplesheet
script:
"""
cp "${input_sheet}" "${samplesheet_output_file}"
"""
}
process print_metadata {
// print the workflow meta data to the output directory
publishDir "${params.outputDir}", mode: 'copy'
executor "local"
input:
val(x) from Channel.from('')
output:
file("${output_file}") into metadata_ch
val("") into done_print_metadata
script:
output_file = "meta.tsv"
"""
printf "Run\tTime\tSession\tWorkflow\tLocation\tSystem\tOutputPath\tUsername\n" > "${output_file}"
printf "${runID}\t${workflowTimestamp}\t${workflow.sessionId}\t${workflow.runName}\t${workflow.projectDir}\t${localhostname}\t${outputDirPath}\t${username}\n" >> "${output_file}"
"""
}
process targets_zip {
input:
file(targets_bed) from targets_bed13
output:
set file("${output_bgz}"), file("${output_index}") into targets_zipped, targets_zipped2
script:
output_bgz = "targets.bed.bgz"
output_index = "targets.bed.bgz.tbi"
"""
sort -V -k1,1 -k2,2 "${targets_bed}" > targets.sorted.bed
bgzip -c targets.sorted.bed > "${output_bgz}"
tabix -p bed "${output_bgz}"
"""
}
process targets_metrics {
// print metrics about the targets
publishDir "${params.outputDir}/metrics/targets", mode: 'copy', pattern: "*.bed"
publishDir "${params.outputDir}", mode: 'copy', pattern: "*${targets_metrics}"
executor "local"
input:
file(targets) from targets_bed9
output:
file("${targets_metrics}") into targets_metrics_ch
script:
targets_sorted = "targets.sorted.bed"
targets_merged = "targets.merged.bed"
targets_metrics = "targets.metrics.tsv"
"""
num_targets="\$(cat "${targets}" | wc -l)"
targets_md5="\$(python -c "import hashlib; print(hashlib.md5(open('${targets}', 'rb').read()).hexdigest())")"
# check if there are strands in the targets
if [ "\$(bed.py "${targets}" hasStrands)" == "True" ]; then
sort -k 1,1 -k2,2n "${targets}" > "${targets_sorted}"
bedtools merge -s -i "${targets_sorted}" > "${targets_merged}"
else
sort -k 1,1 -k2,2n "${targets}" > "${targets_sorted}"
bedtools merge -i "${targets_sorted}" > "${targets_merged}"
fi
num_merged_targets="\$(cat "${targets_merged}" | wc -l)"
targets_coverage_bp="\$(bed.py "${targets}" breadthOfCoverage)"
targets_coverage_Mbp="\$(python -c "print( \${targets_coverage_bp} / float((10**6)) )")"
targets_filename="\$(python -c "import os; print(os.path.basename(os.path.realpath('${targets}')))")"
printf 'Targets File\tNumber of Targets\tNumber of Merged Targets\tBreadth Of Coverage (Mbp)\tBreadth Of Coverage (bp)\tmd5\n' > "${targets_metrics}"
printf "\${targets_filename}\t\${num_targets}\t\${num_merged_targets}\t\${targets_coverage_Mbp}\t\${targets_coverage_bp}\t\${targets_md5}\n" >> "${targets_metrics}"
"""
}
target_ANNOVAR_BUILD_VERSION = "hg19"
target_ANNOVAR_PROTOCOL = "refGene"
target_ANNOVAR_OPERATION = "g"
process annotate_targets {
// annotate the target.bed regions
input:
set file(targets_bed), file(annovar_db_dir) from targets_bed11.combine(annovar_db_dir4)
output:
file("${output_file}") into annotated_targets
script:
prefix = "targets"
interval_tmp = "${prefix}.intervals.tmp"
remainder_tsv = "${prefix}.remainder.tsv"
avinput_file = "${prefix}.avinput"
annovar_output_txt = "${prefix}.${target_ANNOVAR_BUILD_VERSION}_multianno.txt"
output_file = "${targets_annotations_file}"
"""
# convert table to ANNOVAR format for annotation; http://annovar.openbioinformatics.org/en/latest/user-guide/input/
# add '0' cols for ref and alt
cut -f1-3 "${targets_bed}" > "${avinput_file}"
sed -e 's|\$|\t0|' -i "${avinput_file}"
sed -e 's|\$|\t0|' -i "${avinput_file}"
# annotate
table_annovar.pl "${avinput_file}" "${annovar_db_dir}" \
--buildver "${target_ANNOVAR_BUILD_VERSION}" \
--remove \
--protocol "${target_ANNOVAR_PROTOCOL}" \
--operation "${target_ANNOVAR_OPERATION}" \
--nastring . \
--outfile "${prefix}"
mv "${annovar_output_txt}" "${output_file}"
"""
}
process fastq_merge {
// merge multiple R1 and R2 fastq files (e.g. split by lane) into a single fastq each
input:
set val(sampleID), file(fastq_r1: "*"), file(fastq_r2: "*") from samples_R1_R2
output:
set val(sampleID), file("${merged_fastq_R1}"), file("${merged_fastq_R2}") into samples_fastq_merged
file("${num_reads_R1}")
file("${num_reads_R2}")
file("${num_reads}")
val(sampleID) into done_fastq_merge
script:
prefix = "${sampleID}"
merged_fastq_R1 = "${prefix}_R1.fastq.gz"
merged_fastq_R2 = "${prefix}_R2.fastq.gz"
num_reads = "${prefix}.reads.txt"
num_reads_R1 = "${prefix}_R1.reads.txt"
num_reads_R2 = "${prefix}_R2.reads.txt"
"""
cat ${fastq_r1} > "${merged_fastq_R1}"
cat ${fastq_r2} > "${merged_fastq_R2}"
# get the number of reads
zcat "${merged_fastq_R1}" | awk '{s++}END{print s/4}' > "${num_reads}"
cp "${num_reads}" "${num_reads_R1}"
zcat "${merged_fastq_R2}" | awk '{s++}END{print s/4}' > "${num_reads_R2}"
"""
}
process trimmomatic {
// trim low quality bases from reads
publishDir "${params.outputDir}/reads/trimmed", mode: 'copy', pattern: "*${fastq_R1_trimmed}"
publishDir "${params.outputDir}/reads/trimmed", mode: 'copy', pattern: "*${fastq_R2_trimmed}"
publishDir "${params.outputDir}/reads/stats", mode: 'copy', pattern: "*.txt"
input:
set val(sampleID), file(read1), file(read2), file(trimmomatic_contaminant_fa) from samples_fastq_merged.combine(trimmomatic_contaminant_fa)
output:
set val(sampleID), file("${fastq_R1_trimmed}"), file("${fastq_R2_trimmed}") into samples_fastq_trimmed, samples_fastq_trimmed2
file("${num_reads_trim}")
file("${num_reads_trim_R1}")
file("${num_reads_trim_R2}")
file("${num_reads_unpaired_R1}")
file("${num_reads_unpaired_R2}")
val(sampleID) into done_trimmomatic
script:
prefix = "${sampleID}"
fastq_R1_trimmed = "${prefix}_R1.trim.fastq.gz"
fastq_R2_trimmed = "${prefix}_R2.trim.fastq.gz"
fastq_R1_unpaired = "${prefix}_R1.unpaired.fastq.gz"
fastq_R2_unpaired = "${prefix}_R2.unpaired.fastq.gz"
num_reads_trim = "${prefix}.trim.reads.txt"
num_reads_trim_R1 = "${prefix}_R1.trim.reads.txt"
num_reads_trim_R2 = "${prefix}_R2.trim.reads.txt"
num_reads_unpaired_R1 = "${prefix}_R1.unpaired.reads.txt"
num_reads_unpaired_R2 = "${prefix}_R2.unpaired.reads.txt"
"""
trimmomatic.sh PE -threads \${NSLOTS:-\${NTHREADS:-1}} \
"${read1}" "${read2}" \
"${fastq_R1_trimmed}" "${fastq_R1_unpaired}" \
"${fastq_R2_trimmed}" "${fastq_R2_unpaired}" \
ILLUMINACLIP:${trimmomatic_contaminant_fa}:2:30:10:1:true TRAILING:5 SLIDINGWINDOW:4:15 MINLEN:35
# get the number of reads
zcat "${fastq_R1_trimmed}" | awk '{s++}END{print s/4}' > "${num_reads_trim}"
cp "${num_reads_trim}" "${num_reads_trim_R1}"
zcat "${fastq_R2_trimmed}" | awk '{s++}END{print s/4}' > "${num_reads_trim_R2}"
zcat "${fastq_R1_unpaired}" | awk '{s++}END{print s/4}' > "${num_reads_unpaired_R1}"
zcat "${fastq_R2_unpaired}" | awk '{s++}END{print s/4}' > "${num_reads_unpaired_R2}"
"""
}
process fastqc {
// quality control checking with FastQC
publishDir "${params.outputDir}/qc/fastqc", mode: 'copy'
input:
set val(sampleID), file(fastq_R1), file(fastq_R2) from samples_fastq_trimmed2
output:
file(output_R1_html)
file(output_R1_zip)
file(output_R2_html)
file(output_R2_zip)
val(sampleID) into done_fastqc_trim
script:
output_R1_html = "${fastq_R1}".replaceFirst(/.fastq.gz$/, "_fastqc.html")
output_R1_zip = "${fastq_R1}".replaceFirst(/.fastq.gz$/, "_fastqc.zip")
output_R2_html = "${fastq_R2}".replaceFirst(/.fastq.gz$/, "_fastqc.html")
output_R2_zip = "${fastq_R2}".replaceFirst(/.fastq.gz$/, "_fastqc.zip")
"""
fastqc -o . "${fastq_R1}"
fastqc -o . "${fastq_R2}"
"""
}
process alignment {
// first pass alignment with BWA
publishDir "${params.outputDir}/alignments/raw", mode: 'copy'
input:
set val(sampleID), file(fastq_R1_trim), file(fastq_R2_trim), file(ref_fa_bwa_dir) from samples_fastq_trimmed.combine(ref_fa_bwa_dir)
output:
set val(sampleID), file("${bam_file}") into samples_bam, samples_bam2, samples_bam3, samples_bam4
val(sampleID) into done_alignment
script:
prefix = "${sampleID}"
bam_file = "${prefix}.bam"
"""
bwa mem \
-M -v 1 \
-t \${NSLOTS:-\${NTHREADS:-1}} \
-R '@RG\\tID:${sampleID}\\tSM:${sampleID}\\tLB:${sampleID}\\tPL:ILLUMINA' \
"${ref_fa_bwa_dir}/genome.fa" \
"${fastq_R1_trim}" "${fastq_R2_trim}" | \
sambamba view \
--sam-input \
--nthreads=\${NSLOTS:-\${NTHREADS:-1}} \
--filter='mapping_quality>=10' \
--format=bam \
--compression-level=0 \
/dev/stdin | \
sambamba sort \
--nthreads=\${NSLOTS:-\${NTHREADS:-1}} \
--out="${bam_file}" /dev/stdin
"""
}
process samtools_flagstat {
// alignment stats
publishDir "${params.outputDir}/alignments/stats", mode: 'copy'
input:
set val(sampleID), file(sample_bam) from samples_bam
output:
set val(sampleID), file("${flagstat}") into flagstats
val(sampleID) into done_sambamba_flagstat
script:
prefix = "${sampleID}"
flagstat = "${prefix}.flagstat.txt"
"""
samtools flagstat "${sample_bam}" > "${flagstat}"
"""
}
process samtools_flagstat_table {
// convert flagstat output to a flat table
publishDir "${params.outputDir}/alignments/stats", mode: 'copy'
input:
set val(sampleID), file(flagstat) from flagstats
output:
file("${output_file}") into sambamba_flagstat_tables
val(sampleID) into done_sambamba_flagstat_table
script:
prefix = "${sampleID}"
output_file = "${prefix}.flagstat.tsv"
"""
flagstat2table.R "${flagstat}" tmp.tsv
paste-col.py -i tmp.tsv --header "Sample" -v "${sampleID}" > "${output_file}"
"""
}
sambamba_flagstat_tables.collectFile(name: ".flagstat.tsv", keepHeader: true).set { sambamba_flagstat_table_collected }
process update_samtools_flagstat_table {
// add labels to the table to output
publishDir "${params.outputDir}", mode: 'copy'
input:
file(table) from sambamba_flagstat_table_collected
output:
file("${output_file}") into samtools_flagstat_table_ch
val('') into done_samtools_flagstat_table_update
script:
output_file = "flagstat.tsv"
"""
paste-col.py -i "${table}" --header "Run" -v "${runID}" | \
paste-col.py --header "Time" -v "${workflowTimestamp}" | \
paste-col.py --header "Session" -v "${workflow.sessionId}" | \
paste-col.py --header "Workflow" -v "${workflow.runName}" | \
paste-col.py --header "Location" -v "${workflow.projectDir}" | \
paste-col.py --header "System" -v "${localhostname}" | \
paste-col.py --header "GitBranch" -v "${params.GIT_CURRENT_BRANCH}" | \
paste-col.py --header "GitTag" -v "${params.GIT_CURRENT_TAG}" > \
"${output_file}"
"""
}
process sambamba_dedup {
// deduplicate alignments
publishDir "${params.outputDir}/alignments/deduplicated", mode: 'copy'
input:
set val(sampleID), file(sample_bam) from samples_bam2
output:
set val(sampleID), file("${bam_file}") into samples_dd_bam, samples_dd_bam2
set val(sampleID), file("${bam_file}"), file("${bai_file}") into samples_dd_bam3, samples_dd_bam4, samples_dd_bam5
set val(sampleID), file("${log_file}") into sambamba_dedup_logs
val(sampleID) into done_sambamba_dedup
script:
prefix = "${sampleID}"
bam_file = "${prefix}.dd.bam"
bai_file = "${prefix}.dd.bam.bai"
log_file = "${prefix}.dd.log"
"""
sambamba markdup \
--remove-duplicates \
--nthreads \${NSLOTS:-\${NTHREADS:-1}} \
--hash-table-size 525000 \
--overflow-list-size 525000 \
"${sample_bam}" "${bam_file}"
# make a copy of the .command.err Nextflow log file for parsing
cat .command.err > "${log_file}"
samtools index "${bam_file}"
"""
}
process sambamba_dedup_log_table {
// convert the dedup stats the a flat table
publishDir "${params.outputDir}/alignment-stats", mode: 'copy'
input:
set val(sampleID), file(log_file) from sambamba_dedup_logs
output:
file("${output_file}") into sambamba_dedup_log_tables
val(sampleID) into done_sambamba_dedup_log_table
script:
prefix = "${sampleID}"
output_file = "${prefix}.dd.tsv"
"""
dedup-log2table.R "${log_file}" tmp.tsv
paste-col.py -i tmp.tsv --header "Sample" -v "${sampleID}" > "${output_file}"
"""
}
sambamba_dedup_log_tables.collectFile(name: ".reads.dedup.tsv", keepHeader: true).set { sambamba_dedup_log_tables_collected }
process update_sambamba_dedup_log_table{
// add labels to the table to output
publishDir "${params.outputDir}", mode: 'copy'
input:
file(table) from sambamba_dedup_log_tables_collected
output:
file("${output_file}") into sambamba_dedup_log_table_ch
val('') into done_update_sambamba_dedup_log_table
script:
output_file = "reads.dedup.tsv"
"""
paste-col.py -i "${table}" --header "Run" -v "${runID}" | \
paste-col.py --header "Time" -v "${workflowTimestamp}" | \
paste-col.py --header "Session" -v "${workflow.sessionId}" | \
paste-col.py --header "Workflow" -v "${workflow.runName}" | \
paste-col.py --header "Location" -v "${workflow.projectDir}" | \
paste-col.py --header "System" -v "${localhostname}" | \
paste-col.py --header "GitBranch" -v "${params.GIT_CURRENT_BRANCH}" | \
paste-col.py --header "GitTag" -v "${params.GIT_CURRENT_TAG}" > \
"${output_file}"
"""
}
process samtools_dedup_flagstat {
// dedup alignment stats
publishDir "${params.outputDir}/alignment-stats", mode: 'copy'
input:
set val(sampleID), file(sample_bam) from samples_dd_bam2
output:
set val(sampleID), file("${flagstat}") into dedup_flagstats
val(sampleID) into done_sambamba_dedup_flagstat
script:
prefix = "${sampleID}"
flagstat = "${prefix}.dd.flagstat.txt"
"""
samtools flagstat "${sample_bam}" > "${flagstat}"
"""
}
process samtools_dedup_flagstat_table {
// convert dedup stats to a flat table
publishDir "${params.outputDir}/alignment-stats", mode: 'copy'
input:
set val(sampleID), file(flagstat) from dedup_flagstats
output:
file("${output_file}") into sambamba_dedup_flagstat_tables
val(sampleID) into done_sambamba_dedup_flagstat_table
script:
prefix = "${sampleID}"
output_file = "${prefix}.dd.flagstat.tsv"
"""
flagstat2table.R "${flagstat}" tmp.tsv
paste-col.py -i tmp.tsv --header "Sample" -v "${sampleID}" > "${output_file}"
"""
}
sambamba_dedup_flagstat_tables.collectFile(name: ".flagstat.dedup.tsv", keepHeader: true).set { sambamba_dedup_flagstat_tables_collected }
process update_samtools_dedup_flagstat_table {
// add labels to the table to output
publishDir "${params.outputDir}", mode: 'copy'
input:
file(table) from sambamba_dedup_flagstat_tables_collected
output:
file("${output_file}") into samtools_dedup_flagstat_table_ch
val('') into done_update_samtools_dedup_flagstat_table
script:
output_file = "flagstat.dedup.tsv"
"""
paste-col.py -i "${table}" --header "Run" -v "${runID}" | \
paste-col.py --header "Time" -v "${workflowTimestamp}" | \
paste-col.py --header "Session" -v "${workflow.sessionId}" | \
paste-col.py --header "Workflow" -v "${workflow.runName}" | \
paste-col.py --header "Location" -v "${workflow.projectDir}" | \
paste-col.py --header "System" -v "${localhostname}" | \
paste-col.py --header "GitBranch" -v "${params.GIT_CURRENT_BRANCH}" | \
paste-col.py --header "GitTag" -v "${params.GIT_CURRENT_TAG}" > \
"${output_file}"
"""
}
// setup downstream Channels
samples_dd_bam.combine(ref_fasta)
.combine(ref_fai)
.combine(ref_dict)
.combine(targets_bed)
.combine(gatk_1000G_phase1_indels_vcf)
.combine(gatk_1000G_phase1_indels_vcf_idx)
.combine(mills_and_1000G_gold_standard_indels_vcf)
.combine(mills_and_1000G_gold_standard_indels_vcf_idx)
.combine(dbsnp_ref_vcf)
.combine(dbsnp_ref_vcf_idx)
.set { samples_dd_bam_ref_gatk }
// MAIN REALIGNMENT AND RECALIBRATION STEP
process gatk_RealignerTargetCreator {
// re-align and recalibrate alignments for later variant calling
publishDir "${params.outputDir}/alignment-stats", pattern: "${intervals_file}", mode: 'copy'
input:
set val(sampleID), file(sample_bam), file(ref_fasta), file(ref_fai), file(ref_dict), file(targets_bed_file), file(gatk_1000G_phase1_indels_vcf), file(gatk_1000G_phase1_indels_vcf_idx), file(mills_and_1000G_gold_standard_indels_vcf), file(mills_and_1000G_gold_standard_indels_vcf_idx), file(dbsnp_ref_vcf), file(dbsnp_ref_vcf_idx) from samples_dd_bam_ref_gatk
output:
set val(sampleID), file("${intervals_file}"), file(sample_bam) into realigned_intervals_tables
val(sampleID) into done_gatk_RealignerTargetCreator
script:
prefix = "${sampleID}"
intervals_file = "${prefix}.RealignerTargetCreator.intervals"
"""
gatk.sh -T RealignerTargetCreator \
-dt NONE \
--logging_level ERROR \
-nt \${NSLOTS:-\${NTHREADS:-1}} \
--reference_sequence "${ref_fasta}" \
-known "${gatk_1000G_phase1_indels_vcf}" \
-known "${mills_and_1000G_gold_standard_indels_vcf}" \
--intervals "${targets_bed_file}" \
--interval_padding 10 \
--input_file "${sample_bam}" \
--out "${intervals_file}"
"""
}
realigned_intervals_tables.combine(ref_fasta6)
.combine(ref_fai6)
.combine(ref_dict6)
.combine(targets_bed5)