forked from nf-core/sarek
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.nf
4296 lines (3424 loc) · 157 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
/*
================================================================================
nf-core/sarek
================================================================================
Started March 2016.
Ported to nf-core May 2019.
--------------------------------------------------------------------------------
nf-core/sarek:
An open-source analysis pipeline to detect germline or somatic variants
from whole genome or targeted sequencing
--------------------------------------------------------------------------------
@Homepage
https://nf-co.re/sarek
--------------------------------------------------------------------------------
@Documentation
https://nf-co.re/sarek/docs
--------------------------------------------------------------------------------
*/
log.info Headers.nf_core(workflow, params.monochrome_logs)
////////////////////////////////////////////////////
/* -- PRINT HELP -- */
////////////////////////////////////////////////////
def json_schema = "$projectDir/nextflow_schema.json"
if (params.help) {
def command = "nextflow run nf-core/sarek --input sample.tsv -profile docker"
log.info NfcoreSchema.params_help(workflow, params, json_schema, command)
exit 0
}
////////////////////////////////////////////////////
/* -- VALIDATE PARAMETERS -- */
////////////////////////////////////////////////////
if (params.validate_params) {
NfcoreSchema.validateParameters(params, json_schema, log)
}
////////////////////////////////////////////////////
/* -- Collect configuration parameters -- */
////////////////////////////////////////////////////
// Check if genome exists in the config file
if (params.genomes && !params.genomes.containsKey(params.genome) && !params.igenomes_ignore) {
exit 1, "The provided genome '${params.genome}' is not available in the iGenomes file. Currently the available genomes are ${params.genomes.keySet().join(", ")}"
} else if (params.genomes && !params.genomes.containsKey(params.genome) && params.igenomes_ignore) {
exit 1, "The provided genome '${params.genome}' is not available in the genomes file. Currently the available genomes are ${params.genomes.keySet().join(", ")}"
}
/*
================================================================================
SET UP CONFIGURATION VARIABLES
================================================================================
*/
stepList = defineStepList()
step = params.step ? params.step.toLowerCase().replaceAll('-', '').replaceAll('_', '') : ''
// Handle deprecation
if (step == 'preprocessing') step = 'mapping'
if (step.contains(',')) exit 1, 'You can choose only one step, see --help for more information'
if (!checkParameterExistence(step, stepList)) exit 1, "Unknown step ${step}, see --help for more information"
toolList = defineToolList()
tools = params.tools ? params.tools.split(',').collect{it.trim().toLowerCase().replaceAll('-', '').replaceAll('_', '')} : []
if (step == 'controlfreec') tools = ['controlfreec']
if (!checkParameterList(tools, toolList)) exit 1, 'Unknown tool(s), see --help for more information'
skipQClist = defineSkipQClist()
skipQC = params.skip_qc ? params.skip_qc == 'all' ? skipQClist : params.skip_qc.split(',').collect{it.trim().toLowerCase().replaceAll('-', '').replaceAll('_', '')} : []
if (!checkParameterList(skipQC, skipQClist)) exit 1, 'Unknown QC tool(s), see --help for more information'
annoList = defineAnnoList()
annotate_tools = params.annotate_tools ? params.annotate_tools.split(',').collect{it.trim().toLowerCase().replaceAll('-', '')} : []
if (!checkParameterList(annotate_tools,annoList)) exit 1, 'Unknown tool(s) to annotate, see --help for more information'
// Check parameters
if ((params.ascat_ploidy && !params.ascat_purity) || (!params.ascat_ploidy && params.ascat_purity)) exit 1, 'Please specify both --ascat_purity and --ascat_ploidy, or none of them'
if (params.umi && !(params.read_structure1 && params.read_structure2)) exit 1, 'Please specify both --read_structure1 and --read_structure2, when using --umi'
// Check AWS batch settings
if (workflow.profile.contains('awsbatch')) {
// AWSBatch sanity checking
if (!params.awsqueue || !params.awsregion) exit 1, 'Specify correct --awsqueue and --awsregion parameters on AWSBatch!'
// Check outdir paths to be S3 buckets if running on AWSBatch
// related: https://github.com/nextflow-io/nextflow/issues/813
if (!params.outdir.startsWith('s3:')) exit 1, 'Outdir not on S3 - specify S3 Bucket to run on AWSBatch!'
// Prevent trace files to be stored on S3 since S3 does not support rolling files.
if (params.tracedir.startsWith('s3:')) exit 1, 'Specify a local tracedir or run without trace! S3 cannot be used for tracefiles.'
}
// MultiQC
// Stage config files
ch_multiqc_config = file("$projectDir/assets/multiqc_config.yaml", checkIfExists: true)
ch_multiqc_custom_config = params.multiqc_config ? Channel.fromPath(params.multiqc_config, checkIfExists: true) : Channel.empty()
ch_output_docs = file("$projectDir/docs/output.md", checkIfExists: true)
ch_output_docs_images = file("$projectDir/docs/images/", checkIfExists: true)
// Handle input
tsvPath = null
if (params.input && (hasExtension(params.input, "tsv") || hasExtension(params.input, "vcf") || hasExtension(params.input, "vcf.gz"))) tsvPath = params.input
if (params.input && (hasExtension(params.input, "vcf") || hasExtension(params.input, "vcf.gz"))) step = "annotate"
save_bam_mapped = params.skip_markduplicates ? true : params.save_bam_mapped ? true : false
// If no input file specified, trying to get TSV files corresponding to step in the TSV directory
// only for steps preparerecalibration, recalibrate, variantcalling and controlfreec
if (!params.input && params.sentieon) {
switch (step) {
case 'mapping': break
case 'recalibrate': tsvPath = "${params.outdir}/Preprocessing/TSV/sentieon_deduped.tsv"; break
case 'variantcalling': tsvPath = "${params.outdir}/Preprocessing/TSV/sentieon_recalibrated.tsv"; break
case 'annotate': break
default: exit 1, "Unknown step ${step}"
}
} else if (!params.input && !params.sentieon && !params.skip_markduplicates) {
switch (step) {
case 'mapping': break
case 'preparerecalibration': tsvPath = "${params.outdir}/Preprocessing/TSV/duplicates_marked_no_table.tsv"; break
case 'recalibrate': tsvPath = "${params.outdir}/Preprocessing/TSV/duplicates_marked.tsv"; break
case 'variantcalling': tsvPath = "${params.outdir}/Preprocessing/TSV/recalibrated.tsv"; break
case 'controlfreec': tsvPath = "${params.outdir}/VariantCalling/TSV/control-freec_mpileup.tsv"; break
case 'annotate': break
default: exit 1, "Unknown step ${step}"
}
} else if (!params.input && !params.sentieon && params.skip_markduplicates) {
switch (step) {
case 'mapping': break
case 'preparerecalibration': tsvPath = "${params.outdir}/Preprocessing/TSV/mapped.tsv"; break
case 'recalibrate': tsvPath = "${params.outdir}/Preprocessing/TSV/mapped_no_duplicates_marked.tsv"; break
case 'variantcalling': tsvPath = "${params.outdir}/Preprocessing/TSV/recalibrated.tsv"; break
case 'controlfreec': tsvPath = "${params.outdir}/VariantCalling/TSV/control-freec_mpileup.tsv"; break
case 'annotate': break
default: exit 1, "Unknown step ${step}"
}
}
inputSample = Channel.empty()
if (tsvPath) {
tsvFile = file(tsvPath)
switch (step) {
case 'mapping': inputSample = extractFastq(tsvFile); break
case 'preparerecalibration': inputSample = extractBam(tsvFile); break
case 'recalibrate': inputSample = extractRecal(tsvFile); break
case 'variantcalling': inputSample = extractBam(tsvFile); break
case 'controlfreec': inputSample = extractPileup(tsvFile); break
case 'annotate': break
default: exit 1, "Unknown step ${step}"
}
} else if (params.input && !hasExtension(params.input, "tsv")) {
log.info "No TSV file"
if (step != 'mapping') exit 1, 'No step other than "mapping" supports a directory as an input'
log.info "Reading ${params.input} directory"
log.warn "[nf-core/sarek] in ${params.input} directory, all fastqs are assuming to be from the same sample, which is assumed to be a germline one"
inputSample = extractFastqFromDir(params.input)
(inputSample, fastqTMP) = inputSample.into(2)
fastqTMP.toList().subscribe onNext: {
if (it.size() == 0) exit 1, "No FASTQ files found in --input directory '${params.input}'"
}
tsvFile = params.input // used in the reports
} else if (tsvPath && step == 'annotate') {
log.info "Annotating ${tsvPath}"
} else if (step == 'annotate') {
log.info "Trying automatic annotation on files in the VariantCalling/ directory"
} else exit 1, 'No sample were defined, see --help'
(genderMap, statusMap, inputSample) = extractInfos(inputSample)
/*
================================================================================
CHECKING REFERENCES
================================================================================
*/
// Initialize each params in params.genomes, catch the command line first if it was defined
// params.fasta has to be the first one
params.fasta = params.genome && !('annotate' in step) ? params.genomes[params.genome].fasta ?: null : null
// The rest can be sorted
params.ac_loci = params.genome && 'ascat' in tools ? params.genomes[params.genome].ac_loci ?: null : null
params.ac_loci_gc = params.genome && 'ascat' in tools ? params.genomes[params.genome].ac_loci_gc ?: null : null
params.bwa = params.genome && params.fasta && 'mapping' in step ? params.genomes[params.genome].bwa ?: null : null
params.chr_dir = params.genome && 'controlfreec' in tools ? params.genomes[params.genome].chr_dir ?: null : null
params.chr_length = params.genome && 'controlfreec' in tools ? params.genomes[params.genome].chr_length ?: null : null
params.dbsnp = params.genome && ('mapping' in step || 'preparerecalibration' in step || 'controlfreec' in tools || 'haplotypecaller' in tools || 'mutect2' in tools || params.sentieon) ? params.genomes[params.genome].dbsnp ?: null : null
params.dbsnp_index = params.genome && params.dbsnp ? params.genomes[params.genome].dbsnp_index ?: null : null
params.dict = params.genome && params.fasta ? params.genomes[params.genome].dict ?: null : null
params.fasta_fai = params.genome && params.fasta ? params.genomes[params.genome].fasta_fai ?: null : null
params.germline_resource = params.genome && 'mutect2' in tools ? params.genomes[params.genome].germline_resource ?: null : null
params.germline_resource_index = params.genome && params.germline_resource ? params.genomes[params.genome].germline_resource_index ?: null : null
params.intervals = params.genome && !('annotate' in step) ? params.genomes[params.genome].intervals ?: null : null
params.known_indels = params.genome && ('mapping' in step || 'preparerecalibration' in step) ? params.genomes[params.genome].known_indels ?: null : null
params.known_indels_index = params.genome && params.known_indels ? params.genomes[params.genome].known_indels_index ?: null : null
params.mappability = params.genome && 'controlfreec' in tools ? params.genomes[params.genome].mappability ?: null : null
params.snpeff_db = params.genome && ('snpeff' in tools || 'merge' in tools) ? params.genomes[params.genome].snpeff_db ?: null : null
params.species = params.genome && ('vep' in tools || 'merge' in tools) ? params.genomes[params.genome].species ?: null : null
params.vep_cache_version = params.genome && ('vep' in tools || 'merge' in tools) ? params.genomes[params.genome].vep_cache_version ?: null : null
// Initialize channels with files based on params
ch_ac_loci = params.ac_loci && 'ascat' in tools ? Channel.value(file(params.ac_loci)) : "null"
ch_ac_loci_gc = params.ac_loci_gc && 'ascat' in tools ? Channel.value(file(params.ac_loci_gc)) : "null"
ch_chr_dir = params.chr_dir && 'controlfreec' in tools ? Channel.value(file(params.chr_dir)) : "null"
ch_chr_length = params.chr_length && 'controlfreec' in tools ? Channel.value(file(params.chr_length)) : "null"
ch_dbsnp = params.dbsnp && ('mapping' in step || 'preparerecalibration' in step || 'controlfreec' in tools || 'haplotypecaller' in tools || 'mutect2' in tools || params.sentieon) ? Channel.value(file(params.dbsnp)) : "null"
ch_fasta = params.fasta && !('annotate' in step) ? Channel.value(file(params.fasta)) : "null"
ch_fai = params.fasta_fai && !('annotate' in step) ? Channel.value(file(params.fasta_fai)) : "null"
ch_germline_resource = params.germline_resource && 'mutect2' in tools ? Channel.value(file(params.germline_resource)) : "null"
ch_intervals = params.intervals && !params.no_intervals && !('annotate' in step) ? Channel.value(file(params.intervals)) : "null"
ch_known_indels = params.known_indels && ('mapping' in step || 'preparerecalibration' in step) ? Channel.value(file(params.known_indels)) : "null"
ch_mappability = params.mappability && 'controlfreec' in tools ? Channel.value(file(params.mappability)) : "null"
// Initialize channels with values based on params
ch_snpeff_cache = params.snpeff_cache ? Channel.value(file(params.snpeff_cache)) : "null"
ch_snpeff_db = params.snpeff_db ? Channel.value(params.snpeff_db) : "null"
ch_vep_cache_version = params.vep_cache_version ? Channel.value(params.vep_cache_version) : "null"
ch_vep_cache = params.vep_cache ? Channel.value(file(params.vep_cache)) : "null"
// Optional files, not defined within the params.genomes[params.genome] scope
ch_cadd_indels = params.cadd_indels ? Channel.value(file(params.cadd_indels)) : "null"
ch_cadd_indels_tbi = params.cadd_indels_tbi ? Channel.value(file(params.cadd_indels_tbi)) : "null"
ch_cadd_wg_snvs = params.cadd_wg_snvs ? Channel.value(file(params.cadd_wg_snvs)) : "null"
ch_cadd_wg_snvs_tbi = params.cadd_wg_snvs_tbi ? Channel.value(file(params.cadd_wg_snvs_tbi)) : "null"
ch_pon = params.pon ? Channel.value(file(params.pon)) : "null"
ch_target_bed = params.target_bed ? Channel.value(file(params.target_bed)) : "null"
// Optional values, not defined within the params.genomes[params.genome] scope
ch_read_structure1 = params.read_structure1 ? Channel.value(params.read_structure1) : "null"
ch_read_structure2 = params.read_structure2 ? Channel.value(params.read_structure2) : "null"
////////////////////////////////////////////////////
/* -- PRINT PARAMETER SUMMARY -- */
////////////////////////////////////////////////////
log.info NfcoreSchema.params_summary_log(workflow, params, json_schema)
// Header log info
def summary = [:]
if (workflow.revision) summary['Pipeline Release'] = workflow.revision
summary['Run Name'] = workflow.runName
summary['Max Resources'] = "$params.max_memory memory, $params.max_cpus cpus, $params.max_time time per job"
if (workflow.containerEngine) summary['Container'] = "$workflow.containerEngine - $workflow.container"
summary['Output dir'] = params.outdir
summary['Launch dir'] = workflow.launchDir
summary['Working dir'] = workflow.workDir
summary['Script dir'] = workflow.projectDir
summary['User'] = workflow.userName
if (workflow.profile.contains('awsbatch')) {
summary['AWS Region'] = params.awsregion
summary['AWS Queue'] = params.awsqueue
summary['AWS CLI'] = params.awscli
}
summary['Input'] = params.input
summary['Step'] = step
summary['Genome'] = params.genome
if (params.no_intervals && step != 'annotate') summary['Intervals'] = 'Do not use'
summary['Nucleotides/s'] = params.nucleotides_per_second
if (params.sentieon) summary['Sention'] = "Using Sentieon for Preprocessing and/or Variant Calling"
if (params.skip_qc) summary['QC tools skipped'] = skipQC.join(', ')
if (params.target_bed) summary['Target BED'] = params.target_bed
if (params.tools) summary['Tools'] = tools.join(', ')
if (params.trim_fastq || params.split_fastq) summary['Modify fastqs (trim/split)'] = ""
if (params.trim_fastq) {
summary['Fastq trim'] = "Fastq trim selected"
summary['Trim R1'] = "${params.clip_r1} bp"
summary['Trim R2'] = "${params.clip_r2} bp"
summary["Trim 3' R1"] = "${params.three_prime_clip_r1} bp"
summary["Trim 3' R2"] = "${params.three_prime_clip_r2} bp"
summary['NextSeq Trim'] = "${params.trim_nextseq} bp"
summary['Saved Trimmed Fastq'] = params.save_trimmed ? 'Yes' : 'No'
}
if (params.split_fastq) summary['Reads in fastq'] = params.split_fastq
summary['MarkDuplicates'] = "Options"
summary['Java options'] = params.markdup_java_options
summary['GATK Spark'] = params.use_gatk_spark ? 'Yes' : 'No'
summary['Save BAMs mapped'] = params.save_bam_mapped ? 'Yes' : 'No'
summary['Skip MarkDuplicates'] = params.skip_markduplicates ? 'Yes' : 'No'
if ('ascat' in tools) {
summary['ASCAT'] = "Options"
if (params.ascat_purity) summary['purity'] = params.ascat_purity
if (params.ascat_ploidy) summary['ploidy'] = params.ascat_ploidy
}
if ('controlfreec' in tools) {
summary['Control-FREEC'] = "Options"
if (params.cf_coeff) summary['coefficientOfVariation'] = params.cf_coeff
if (params.cf_contamination) summary['contamination'] = params.cf_contamination
if (params.cf_contamination_adjustment) summary['contaminationAdjustment'] = params.cf_contamination_adjustment
if (params.cf_ploidy) summary['ploidy'] = params.cf_ploidy
if (params.cf_window) summary['window'] = params.cf_window
}
if ('haplotypecaller' in tools) summary['GVCF'] = params.generate_gvcf ? 'Yes' : 'No'
if ('strelka' in tools && 'manta' in tools) summary['Strelka BP'] = params.no_strelka_bp ? 'No' : 'Yes'
if (params.pon && ('mutect2' in tools || (params.sentieon && 'tnscope' in tools))) summary['Panel of normals'] = params.pon
if (params.annotate_tools) summary['Tools to annotate'] = annotate_tools.join(', ')
if (params.annotation_cache) {
summary['Annotation cache'] = "Enabled"
if (params.snpeff_cache) summary['snpEff cache'] = params.snpeff_cache
if (params.vep_cache) summary['VEP cache'] = params.vep_cache
}
if (params.cadd_cache) {
summary['CADD cache'] = "Enabled"
if (params.cadd_indels) summary['CADD indels'] = params.cadd_indels
if (params.cadd_wg_snvs) summary['CADD wg snvs'] = params.cadd_wg_snvs
}
if (params.genesplicer) summary['genesplicer'] = "Enabled"
if (params.igenomes_base && !params.igenomes_ignore) summary['AWS iGenomes base'] = params.igenomes_base
if (params.igenomes_ignore) summary['AWS iGenomes'] = "Do not use"
if (params.genomes_base && !params.igenomes_ignore) summary['Genomes base'] = params.genomes_base
summary['Save Reference'] = params.save_reference ? 'Yes' : 'No'
if (params.ac_loci) summary['Loci'] = params.ac_loci
if (params.ac_loci_gc) summary['Loci GC'] = params.ac_loci_gc
if (params.bwa) summary['BWA indexes'] = params.bwa
if (params.chr_dir) summary['Chromosomes'] = params.chr_dir
if (params.chr_length) summary['Chromosomes length'] = params.chr_length
if (params.dbsnp) summary['dbsnp'] = params.dbsnp
if (params.dbsnp_index) summary['dbsnpIndex'] = params.dbsnp_index
if (params.dict) summary['dict'] = params.dict
if (params.fasta) summary['fasta reference'] = params.fasta
if (params.fasta_fai) summary['fasta index'] = params.fasta_fai
if (params.germline_resource) summary['germline resource'] = params.germline_resource
if (params.germline_resource_index) summary['germline resource index'] = params.germline_resource_index
if (params.intervals) summary['intervals'] = params.intervals
if (params.known_indels) summary['known indels'] = params.known_indels
if (params.known_indels_index) summary['known indels index'] = params.known_indels_index
if (params.mappability) summary['Mappability'] = params.mappability
if (params.snpeff_cache) summary['snpEff cache'] = params.snpeff_cache
if (params.snpeff_db) summary['snpEff DB'] = params.snpeff_db
if (params.species) summary['species'] = params.species
if (params.vep_cache) summary['VEP cache'] = params.vep_cache
if (params.vep_cache_version) summary['VEP cache version'] = params.vep_cache_version
summary['Output dir'] = params.outdir
summary['Publish dir mode'] = params.publish_dir_mode
if (params.sequencing_center) summary['Sequenced by'] = params.sequencing_center
summary['Launch dir'] = workflow.launchDir
summary['Working dir'] = workflow.workDir
summary['Script dir'] = workflow.projectDir
summary['User'] = workflow.userName
if (params.multiqc_config) summary['MultiQC config'] = params.multiqc_config
summary['Config Profile'] = workflow.profile
if (params.config_profile_description) summary['Config Description'] = params.config_profile_description
if (params.config_profile_contact) summary['Config Contact'] = params.config_profile_contact
if (params.config_profile_url) summary['Config URL'] = params.config_profile_url
summary['Config Files'] = workflow.configFiles.join(', ')
if (workflow.profile.contains('awsbatch')) {
summary['AWS Region'] = params.awsregion
summary['AWS Queue'] = params.awsqueue
summary['AWS CLI'] = params.awscli
}
if (params.email || params.email_on_fail) {
summary['E-mail Address'] = params.email
summary['E-mail on failure'] = params.email_on_fail
summary['MultiQC maxsize'] = params.max_multiqc_email_size
}
log.info summary.collect { k,v -> "${k.padRight(18)}: $v" }.join("\n")
log.info "-\033[2m--------------------------------------------------\033[0m-"
if ('mutect2' in tools && !(params.pon)) log.warn "[nf-core/sarek] Mutect2 was requested, but as no panel of normals were given, results will not be optimal"
if (params.sentieon) log.warn "[nf-core/sarek] Sentieon will be used, only works if Sentieon is available where nf-core/sarek is run"
// Check the hostnames against configured profiles
checkHostname()
Channel.from(summary.collect{ [it.key, it.value] })
.map { k,v -> "<dt>$k</dt><dd><samp>${v ?: '<span style=\"color:#999999;\">N/A</a>'}</samp></dd>" }
.reduce { a, b -> return [a, b].join("\n ") }
.map { x -> """
id: 'sarek-summary'
description: " - this information is collected when the pipeline is started."
section_name: 'nf-core/sarek Workflow Summary'
section_href: 'https://github.com/nf-core/sarek'
plot_type: 'html'
data: |
<dl class=\"dl-horizontal\">
$x
</dl>
""".stripIndent() }
.set { ch_workflow_summary }
// Parse software version numbers
process get_software_versions {
publishDir "${params.outdir}/pipeline_info", mode: params.publish_dir_mode,
saveAs: { filename ->
if (filename.indexOf('.csv') > 0) filename
else null
}
output:
file 'software_versions_mqc.yaml' into ch_software_versions_yaml
file 'software_versions.csv'
when: !('versions' in skipQC)
script:
aligner = params.aligner == "bwa-mem2" ? "bwa-mem2" : "bwa"
"""
alleleCounter --version &> v_allelecount.txt 2>&1 || true
bcftools --version &> v_bcftools.txt 2>&1 || true
${aligner} version &> v_bwa.txt 2>&1 || true
cnvkit.py version &> v_cnvkit.txt 2>&1 || true
configManta.py --version &> v_manta.txt 2>&1 || true
configureStrelkaGermlineWorkflow.py --version &> v_strelka.txt 2>&1 || true
echo "${workflow.manifest.version}" &> v_pipeline.txt 2>&1 || true
echo "${workflow.nextflow.version}" &> v_nextflow.txt 2>&1 || true
snpEff -version &> v_snpeff.txt 2>&1 || true
fastqc --version &> v_fastqc.txt 2>&1 || true
freebayes --version &> v_freebayes.txt 2>&1 || true
freec &> v_controlfreec.txt 2>&1 || true
gatk ApplyBQSR --help &> v_gatk.txt 2>&1 || true
msisensor &> v_msisensor.txt 2>&1 || true
multiqc --version &> v_multiqc.txt 2>&1 || true
qualimap --version &> v_qualimap.txt 2>&1 || true
R --version &> v_r.txt 2>&1 || true
R -e "library(ASCAT); help(package='ASCAT')" &> v_ascat.txt 2>&1 || true
samtools --version &> v_samtools.txt 2>&1 || true
tiddit &> v_tiddit.txt 2>&1 || true
trim_galore -v &> v_trim_galore.txt 2>&1 || true
vcftools --version &> v_vcftools.txt 2>&1 || true
vep --help &> v_vep.txt 2>&1 || true
scrape_software_versions.py &> software_versions_mqc.yaml
"""
}
ch_software_versions_yaml = ch_software_versions_yaml.dump(tag:'SOFTWARE VERSIONS')
/*
================================================================================
BUILDING INDEXES
================================================================================
*/
// And then initialize channels based on params or indexes that were just built
process BuildBWAindexes {
tag "${fasta}"
publishDir params.outdir, mode: params.publish_dir_mode,
saveAs: {params.save_reference ? "reference_genome/BWAIndex/${it}" : null }
input:
file(fasta) from ch_fasta
output:
file("${fasta}.*") into bwa_built
when: !(params.bwa) && params.fasta && 'mapping' in step
script:
aligner = params.aligner == "bwa-mem2" ? "bwa-mem2" : "bwa"
"""
${aligner} index ${fasta}
"""
}
ch_bwa = params.bwa ? Channel.value(file(params.bwa)) : bwa_built
process BuildDict {
tag "${fasta}"
publishDir params.outdir, mode: params.publish_dir_mode,
saveAs: {params.save_reference ? "reference_genome/${it}" : null }
input:
file(fasta) from ch_fasta
output:
file("${fasta.baseName}.dict") into dictBuilt
when: !(params.dict) && params.fasta && !('annotate' in step) && !('controlfreec' in step)
script:
"""
gatk --java-options "-Xmx${task.memory.toGiga()}g" \
CreateSequenceDictionary \
--REFERENCE ${fasta} \
--OUTPUT ${fasta.baseName}.dict
"""
}
ch_dict = params.dict ? Channel.value(file(params.dict)) : dictBuilt
process BuildFastaFai {
tag "${fasta}"
publishDir params.outdir, mode: params.publish_dir_mode,
saveAs: {params.save_reference ? "reference_genome/${it}" : null }
input:
file(fasta) from ch_fasta
output:
file("${fasta}.fai") into fai_built
when: !(params.fasta_fai) && params.fasta && !('annotate' in step)
script:
"""
samtools faidx ${fasta}
"""
}
ch_fai = params.fasta_fai ? Channel.value(file(params.fasta_fai)) : fai_built
process BuildDbsnpIndex {
tag "${dbsnp}"
publishDir params.outdir, mode: params.publish_dir_mode,
saveAs: {params.save_reference ? "reference_genome/${it}" : null }
input:
file(dbsnp) from ch_dbsnp
output:
file("${dbsnp}.tbi") into dbsnp_tbi
when: !(params.dbsnp_index) && params.dbsnp && ('mapping' in step || 'preparerecalibration' in step || 'controlfreec' in tools || 'haplotypecaller' in tools || 'mutect2' in tools || 'tnscope' in tools)
script:
"""
tabix -p vcf ${dbsnp}
"""
}
ch_dbsnp_tbi = params.dbsnp ? params.dbsnp_index ? Channel.value(file(params.dbsnp_index)) : dbsnp_tbi : "null"
process BuildGermlineResourceIndex {
tag "${germlineResource}"
publishDir params.outdir, mode: params.publish_dir_mode,
saveAs: {params.save_reference ? "reference_genome/${it}" : null }
input:
file(germlineResource) from ch_germline_resource
output:
file("${germlineResource}.tbi") into germline_resource_tbi
when: !(params.germline_resource_index) && params.germline_resource && 'mutect2' in tools
script:
"""
tabix -p vcf ${germlineResource}
"""
}
ch_germline_resource_tbi = params.germline_resource ? params.germline_resource_index ? Channel.value(file(params.germline_resource_index)) : germline_resource_tbi : "null"
process BuildKnownIndelsIndex {
tag "${knownIndels}"
publishDir params.outdir, mode: params.publish_dir_mode,
saveAs: {params.save_reference ? "reference_genome/${it}" : null }
input:
each file(knownIndels) from ch_known_indels
output:
file("${knownIndels}.tbi") into known_indels_tbi
when: !(params.known_indels_index) && params.known_indels && ('mapping' in step || 'preparerecalibration' in step)
script:
"""
tabix -p vcf ${knownIndels}
"""
}
ch_known_indels_tbi = params.known_indels ? params.known_indels_index ? Channel.value(file(params.known_indels_index)) : known_indels_tbi.collect() : "null"
process BuildPonIndex {
tag "${pon}"
publishDir params.outdir, mode: params.publish_dir_mode,
saveAs: {params.save_reference ? "reference_genome/${it}" : null }
input:
file(pon) from ch_pon
output:
file("${pon}.tbi") into pon_tbi
when: !(params.pon_index) && params.pon && ('tnscope' in tools || 'mutect2' in tools)
script:
"""
tabix -p vcf ${pon}
"""
}
ch_pon_tbi = params.pon ? params.pon_index ? Channel.value(file(params.pon_index)) : pon_tbi : "null"
process BuildIntervals {
tag "${fastaFai}"
publishDir params.outdir, mode: params.publish_dir_mode,
saveAs: {params.save_reference ? "reference_genome/${it}" : null }
input:
file(fastaFai) from ch_fai
output:
file("${fastaFai.baseName}.bed") into intervalBuilt
when: !(params.intervals) && !('annotate' in step) && !('controlfreec' in step)
script:
"""
awk -v FS='\t' -v OFS='\t' '{ print \$1, \"0\", \$2 }' ${fastaFai} > ${fastaFai.baseName}.bed
"""
}
ch_intervals = params.no_intervals ? "null" : params.intervals && !('annotate' in step) ? Channel.value(file(params.intervals)) : intervalBuilt
/*
================================================================================
PREPROCESSING
================================================================================
*/
// STEP 0: CREATING INTERVALS FOR PARALLELIZATION (PREPROCESSING AND VARIANT CALLING)
process CreateIntervalBeds {
tag "${intervals}"
input:
file(intervals) from ch_intervals
output:
file '*.bed' into bedIntervals mode flatten
when: (!params.no_intervals) && step != 'annotate'
script:
// If the interval file is BED format, the fifth column is interpreted to
// contain runtime estimates, which is then used to combine short-running jobs
if (hasExtension(intervals, "bed"))
"""
awk -vFS="\t" '{
t = \$5 # runtime estimate
if (t == "") {
# no runtime estimate in this row, assume default value
t = (\$3 - \$2) / ${params.nucleotides_per_second}
}
if (name == "" || (chunk > 600 && (chunk + t) > longest * 1.05)) {
# start a new chunk
name = sprintf("%s_%d-%d.bed", \$1, \$2+1, \$3)
chunk = 0
longest = 0
}
if (t > longest)
longest = t
chunk += t
print \$0 > name
}' ${intervals}
"""
else if (hasExtension(intervals, "interval_list"))
"""
grep -v '^@' ${intervals} | awk -vFS="\t" '{
name = sprintf("%s_%d-%d", \$1, \$2, \$3);
printf("%s\\t%d\\t%d\\n", \$1, \$2-1, \$3) > name ".bed"
}'
"""
else
"""
awk -vFS="[:-]" '{
name = sprintf("%s_%d-%d", \$1, \$2, \$3);
printf("%s\\t%d\\t%d\\n", \$1, \$2-1, \$3) > name ".bed"
}' ${intervals}
"""
}
bedIntervals = bedIntervals
.map { intervalFile ->
def duration = 0.0
for (line in intervalFile.readLines()) {
final fields = line.split('\t')
if (fields.size() >= 5) duration += fields[4].toFloat()
else {
start = fields[1].toInteger()
end = fields[2].toInteger()
duration += (end - start) / params.nucleotides_per_second
}
}
[duration, intervalFile]
}.toSortedList({ a, b -> b[0] <=> a[0] })
.flatten().collate(2)
.map{duration, intervalFile -> intervalFile}
bedIntervals = bedIntervals.dump(tag:'bedintervals')
if (params.no_intervals && step != 'annotate') {
file("${params.outdir}/no_intervals.bed").text = "no_intervals\n"
bedIntervals = Channel.from(file("${params.outdir}/no_intervals.bed"))
}
(intBaseRecalibrator, intApplyBQSR, intHaplotypeCaller, intFreebayesSingle, intMpileup, bedIntervalsSingle, bedIntervalsPair) = bedIntervals.into(7)
// PREPARING CHANNELS FOR PREPROCESSING AND QC
inputBam = Channel.create()
inputPairReads = Channel.create()
if (step in ['preparerecalibration', 'recalibrate', 'variantcalling', 'controlfreec', 'annotate']) {
inputBam.close()
inputPairReads.close()
} else inputSample.choice(inputPairReads, inputBam) {hasExtension(it[3], "bam") ? 1 : 0}
(inputBam, inputBamFastQC) = inputBam.into(2)
// Removing inputFile2 which is null in case of uBAM
inputBamFastQC = inputBamFastQC.map {
idPatient, idSample, idRun, inputFile1, inputFile2 ->
[idPatient, idSample, idRun, inputFile1]
}
if (params.split_fastq){
inputPairReads = inputPairReads
// newly splitfastq are named based on split, so the name is easier to catch
.splitFastq(by: params.split_fastq, compress:true, file:"split", pe:true)
.map {idPatient, idSample, idRun, reads1, reads2 ->
// The split fastq read1 is the 4th element (indexed 3) its name is split_3
// The split fastq read2's name is split_4
// It's followed by which split it's acutally based on the mother fastq file
// Index start at 1
// Extracting the index to get a new IdRun
splitIndex = reads1.fileName.toString().minus("split_3.").minus(".gz")
newIdRun = idRun + "_" + splitIndex
// Giving the files a new nice name
newReads1 = file("${idSample}_${newIdRun}_R1.fastq.gz")
newReads2 = file("${idSample}_${newIdRun}_R2.fastq.gz")
[idPatient, idSample, newIdRun, reads1, reads2]}
}
inputPairReads = inputPairReads.dump(tag:'INPUT')
(inputPairReads, inputPairReadsTrimGalore, inputPairReadsFastQC, inputPairReadsUMI) = inputPairReads.into(4)
if (params.umi) inputPairReads.close()
else inputPairReadsUMI.close()
if (params.trim_fastq) inputPairReads.close()
else inputPairReadsTrimGalore.close()
// STEP 0.5: QC ON READS
// TODO: Use only one process for FastQC for FASTQ files and uBAM files
// FASTQ and uBAM files are renamed based on the sample name
process FastQCFQ {
label 'FastQC'
label 'cpus_2'
tag "${idPatient}-${idRun}"
publishDir "${params.outdir}/Reports/${idSample}/FastQC/${idSample}_${idRun}", mode: params.publish_dir_mode
input:
set idPatient, idSample, idRun, file("${idSample}_${idRun}_R1.fastq.gz"), file("${idSample}_${idRun}_R2.fastq.gz") from inputPairReadsFastQC
output:
file("*.{html,zip}") into fastQCFQReport
when: !('fastqc' in skipQC)
script:
"""
fastqc -t 2 -q ${idSample}_${idRun}_R1.fastq.gz ${idSample}_${idRun}_R2.fastq.gz
"""
}
process FastQCBAM {
label 'FastQC'
label 'cpus_2'
tag "${idPatient}-${idRun}"
publishDir "${params.outdir}/Reports/${idSample}/FastQC/${idSample}_${idRun}", mode: params.publish_dir_mode
input:
set idPatient, idSample, idRun, file("${idSample}_${idRun}.bam") from inputBamFastQC
output:
file("*.{html,zip}") into fastQCBAMReport
when: !('fastqc' in skipQC)
script:
"""
fastqc -t 2 -q ${idSample}_${idRun}.bam
"""
}
fastQCReport = fastQCFQReport.mix(fastQCBAMReport)
fastQCReport = fastQCReport.dump(tag:'FastQC')
process TrimGalore {
label 'TrimGalore'
tag "${idPatient}-${idRun}"
publishDir "${params.outdir}/Reports/${idSample}/TrimGalore/${idSample}_${idRun}", mode: params.publish_dir_mode,
saveAs: {filename ->
if (filename.indexOf("_fastqc") > 0) "FastQC/$filename"
else if (filename.indexOf("trimming_report.txt") > 0) "logs/$filename"
else if (params.save_trimmed) filename
else null
}
input:
set idPatient, idSample, idRun, file("${idSample}_${idRun}_R1.fastq.gz"), file("${idSample}_${idRun}_R2.fastq.gz") from inputPairReadsTrimGalore
output:
file("*.{html,zip,txt}") into trimGaloreReport
set idPatient, idSample, idRun, file("${idSample}_${idRun}_R1_val_1.fq.gz"), file("${idSample}_${idRun}_R2_val_2.fq.gz") into outputPairReadsTrimGalore
when: params.trim_fastq
script:
// Calculate number of --cores for TrimGalore based on value of task.cpus
// See: https://github.com/FelixKrueger/TrimGalore/blob/master/Changelog.md#version-060-release-on-1-mar-2019
// See: https://github.com/nf-core/atacseq/pull/65
def cores = 1
if (task.cpus) {
cores = (task.cpus as int) - 4
if (cores < 1) cores = 1
if (cores > 4) cores = 4
}
c_r1 = params.clip_r1 > 0 ? "--clip_r1 ${params.clip_r1}" : ''
c_r2 = params.clip_r2 > 0 ? "--clip_r2 ${params.clip_r2}" : ''
tpc_r1 = params.three_prime_clip_r1 > 0 ? "--three_prime_clip_r1 ${params.three_prime_clip_r1}" : ''
tpc_r2 = params.three_prime_clip_r2 > 0 ? "--three_prime_clip_r2 ${params.three_prime_clip_r2}" : ''
nextseq = params.trim_nextseq > 0 ? "--nextseq ${params.trim_nextseq}" : ''
"""
trim_galore \
--cores ${cores} \
--paired \
--fastqc \
--gzip \
${c_r1} ${c_r2} \
${tpc_r1} ${tpc_r2} \
${nextseq} \
${idSample}_${idRun}_R1.fastq.gz ${idSample}_${idRun}_R2.fastq.gz
mv *val_1_fastqc.html "${idSample}_${idRun}_R1.trimmed_fastqc.html"
mv *val_2_fastqc.html "${idSample}_${idRun}_R2.trimmed_fastqc.html"
mv *val_1_fastqc.zip "${idSample}_${idRun}_R1.trimmed_fastqc.zip"
mv *val_2_fastqc.zip "${idSample}_${idRun}_R2.trimmed_fastqc.zip"
"""
}
/*
================================================================================
UMIs PROCESSING
================================================================================
*/
// UMI - STEP 1 - ANNOTATE
// the process needs to convert fastq to unmapped bam
// and while doing the conversion, tag the bam field RX with the UMI sequence
process UMIFastqToBAM {
publishDir "${params.outdir}/Reports/${idSample}/UMI/${idSample}_${idRun}", mode: params.publish_dir_mode
input:
set idPatient, idSample, idRun, file("${idSample}_${idRun}_R1.fastq.gz"), file("${idSample}_${idRun}_R2.fastq.gz") from inputPairReadsUMI
val read_structure1 from ch_read_structure1
val read_structure2 from ch_read_structure2
output:
tuple val(idPatient), val(idSample), val(idRun), file("${idSample}_umi_converted.bam") into umi_converted_bams_ch
when: params.umi
// tmp folder for fgbio might be solved more elengantly?
script:
"""
mkdir tmp
fgbio --tmp-dir=${PWD}/tmp \
FastqToBam \
-i "${idSample}_${idRun}_R1.fastq.gz" "${idSample}_${idRun}_R2.fastq.gz" \
-o "${idSample}_umi_converted.bam" \
--read-structures ${read_structure1} ${read_structure2} \
--sample ${idSample} \
--library ${idSample}
"""
}
// UMI - STEP 2 - MAP THE BAM FILE
// this is necessary because the UMI groups are created based on
// mapping position + same UMI tag
process UMIMapBamFile {
input:
set idPatient, idSample, idRun, file(convertedBam) from umi_converted_bams_ch
file(bwaIndex) from ch_bwa
file(fasta) from ch_fasta
file(fastaFai) from ch_fai
output:
tuple val(idPatient), val(idSample), val(idRun), file("${idSample}_umi_unsorted.bam") into umi_aligned_bams_ch
when: params.umi
script:
aligner = params.aligner == "bwa-mem2" ? "bwa-mem2" : "bwa"
"""
samtools bam2fq -T RX ${convertedBam} | \
${aligner} mem -p -t ${task.cpus} -C -M -R \"@RG\\tID:${idSample}\\tSM:${idSample}\\tPL:Illumina\" \
${fasta} - | \
samtools view -bS - > ${idSample}_umi_unsorted.bam
"""
}
// UMI - STEP 3 - GROUP READS BY UMIs
// We have chose the Adjacency method, following the nice paper and blog explanation integrated in both
// UMItools and FGBIO
// https://cgatoxford.wordpress.com/2015/08/14/unique-molecular-identifiers-the-problem-the-solution-and-the-proof/
// alternatively we can define this as input for the user to choose from
process GroupReadsByUmi {
publishDir "${params.outdir}/Reports/${idSample}/UMI/${idSample}_${idRun}", mode: params.publish_dir_mode
input:
set idPatient, idSample, idRun, file(alignedBam) from umi_aligned_bams_ch
output:
file("${idSample}_umi_histogram.txt") into umi_histogram_ch
tuple val(idPatient), val(idSample), val(idRun), file("${idSample}_umi-grouped.bam") into umi_grouped_bams_ch
when: params.umi
script:
"""
mkdir tmp
samtools view -h ${alignedBam} | \
samblaster -M --addMateTags | \
samtools view -Sb - >${idSample}_unsorted_tagged.bam
fgbio --tmp-dir=${PWD}/tmp \
GroupReadsByUmi \
-s Adjacency \
-i ${idSample}_unsorted_tagged.bam \
-o ${idSample}_umi-grouped.bam \
-f ${idSample}_umi_histogram.txt
"""
}
// UMI - STEP 4 - CALL MOLECULAR CONSENSUS
// Now that the reads are organised by UMI groups a molecular consensus will be created
// the resulting bam file will be again unmapped and therefore can be fed into the
// existing workflow from the step mapping
process CallMolecularConsensusReads {
publishDir "${params.outdir}/Reports/${idSample}/UMI/${idSample}_${idRun}", mode: params.publish_dir_mode
input:
set idPatient, idSample, idRun, file(groupedBamFile) from umi_grouped_bams_ch
output:
tuple val(idPatient), val(idSample), val(idRun), file("${idSample}_umi-consensus.bam"), val("null") into consensus_bam_ch
when: params.umi
script:
"""
mkdir tmp
fgbio --tmp-dir=${PWD}/tmp \
CallMolecularConsensusReads \
-i $groupedBamFile \