-
Notifications
You must be signed in to change notification settings - Fork 150
/
main.nf
executable file
·1674 lines (1449 loc) · 70 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/chipseq
========================================================================================
nf-core/chipseq Analysis Pipeline.
#### Homepage / Documentation
https://github.com/nf-core/chipseq
----------------------------------------------------------------------------------------
*/
def helpMessage() {
log.info nfcoreHeader()
log.info"""
Usage:
The typical command for running the pipeline is as follows:
nextflow run nf-core/chipseq --design design.csv --genome GRCh37 -profile docker
Mandatory arguments:
--design Comma-separated file containing information about the samples in the experiment (see docs/usage.md)
--fasta Path to Fasta reference. Not mandatory when using reference in iGenomes config via --genome
--gtf Path to GTF file in Ensembl format. Not mandatory when using reference in iGenomes config via --genome
-profile Configuration profile to use. Can use multiple (comma separated)
Available: conda, docker, singularity, awsbatch, test
Generic
--singleEnd Specifies that the input is single-end reads
--seq_center Sequencing center information to be added to read group of BAM files
--fragment_size [int] Estimated fragment size used to extend single-end reads (Default: 200)
--fingerprint_bins [int] Number of genomic bins to use when calculating fingerprint plot (Default: 500000)
References If not specified in the configuration file or you wish to overwrite any of the references
--genome Name of iGenomes reference
--bwa_index Full path to directory containing BWA index including base name i.e. /path/to/index/genome.fa
--gene_bed Path to BED file containing gene intervals
--tss_bed Path to BED file containing transcription start sites
--macs_gsize Effective genome size parameter required by MACS2. If using iGenomes config, values have only been provided when --genome is set as GRCh37, GRCm38, hg19, mm10, BDGP6 and WBcel235
--blacklist Path to blacklist regions (.BED format), used for filtering alignments
--saveGenomeIndex If generated by the pipeline save the BWA index in the results directory
Trimming
--clip_r1 [int] Instructs Trim Galore to remove bp from the 5' end of read 1 (or single-end reads) (Default: 0)
--clip_r2 [int] Instructs Trim Galore to remove bp from the 5' end of read 2 (paired-end reads only) (Default: 0)
--three_prime_clip_r1 [int] Instructs Trim Galore to remove bp from the 3' end of read 1 AFTER adapter/quality trimming has been performed (Default: 0)
--three_prime_clip_r2 [int] Instructs Trim Galore to re move bp from the 3' end of read 2 AFTER adapter/quality trimming has been performed (Default: 0)
--skipTrimming Skip the adapter trimming step
--saveTrimmed Save the trimmed FastQ files in the the results directory
Alignments
--keepDups Duplicate reads are not filtered from alignments
--keepMultiMap Reads mapping to multiple locations are not filtered from alignments
--saveAlignedIntermediates Save the intermediate BAM files from the alignment step - not done by default
Peaks
--narrowPeak Run MACS2 in narrowPeak mode
--broad_cutoff [float] Specifies broad cutoff value for MACS2. Only used when --narrowPeak isnt specified (Default: 0.1)
--min_reps_consensus Number of biological replicates required from a given condition for a peak to contribute to a consensus peak (Default: 1)
--saveMACSPileup Instruct MACS2 to create bedGraph files normalised to signal per million reads
--skipDiffAnalysis Skip differential binding analysis
QC
--skipFastQC Skip FastQC
--skipPicardMetrics Skip Picard CollectMultipleMetrics
--skipPreseq Skip Preseq
--skipPlotProfile Skip deepTools plotProfile
--skipPlotFingerprint Skip deepTools plotFingerprint
--skipSpp Skip Phantompeakqualtools
--skipIGV Skip IGV
--skipMultiQC Skip MultiQC
--skipMultiQCStats Exclude general statistics table from MultiQC report
Other
--outdir The output directory where the results will be saved
--email Set this parameter to your e-mail address to get a summary e-mail with details of the run sent to you when the workflow exits
--maxMultiqcEmailFileSize Theshold size for MultiQC report to be attached in notification email. If file generated by pipeline exceeds the threshold, it will not be attached (Default: 25MB)
-name Name for the pipeline run. If not specified, Nextflow will automatically generate a random mnemonic
AWSBatch
--awsqueue The AWSBatch JobQueue that needs to be set when running on AWSBatch
--awsregion The AWS Region for your AWS Batch job to run on
""".stripIndent()
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/* -- -- */
/* -- SET UP CONFIGURATION VARIABLES -- */
/* -- -- */
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/*
* SET UP CONFIGURATION VARIABLES
*/
// Show help message
if (params.help){
helpMessage()
exit 0
}
// Check if genome exists in the config file
if (params.genomes && params.genome && !params.genomes.containsKey(params.genome)) {
exit 1, "The provided genome '${params.genome}' is not available in the iGenomes file. Currently the available genomes are ${params.genomes.keySet().join(", ")}"
}
////////////////////////////////////////////////////
/* -- DEFAULT PARAMETER VALUES -- */
////////////////////////////////////////////////////
// Configurable variables
params.fasta = params.genome ? params.genomes[ params.genome ].fasta ?: false : false
params.bwa_index = params.genome ? params.genomes[ params.genome ].bwa ?: false : false
params.gtf = params.genome ? params.genomes[ params.genome ].gtf ?: false : false
params.gene_bed = params.genome ? params.genomes[ params.genome ].gene_bed ?: false : false
params.macs_gsize = params.genome ? params.genomes[ params.genome ].macs_gsize ?: false : false
params.blacklist = params.genome ? params.genomes[ params.genome ].blacklist ?: false : false
// Has the run name been specified by the user?
// this has the bonus effect of catching both -name and --name
custom_runName = params.name
if (!(workflow.runName ==~ /[a-z]+_[a-z]+/)){
custom_runName = workflow.runName
}
////////////////////////////////////////////////////
/* -- CONFIG FILES -- */
////////////////////////////////////////////////////
// Pipeline config
ch_output_docs = file("$baseDir/docs/output.md", checkIfExists: true)
// JSON files required by BAMTools for alignment filtering
if (params.singleEnd) {
ch_bamtools_filter_config = file(params.bamtools_filter_se_config, checkIfExists: true)
} else {
ch_bamtools_filter_config = file(params.bamtools_filter_pe_config, checkIfExists: true)
}
// Header files for MultiQC
ch_multiqc_config = file(params.multiqc_config, checkIfExists: true)
ch_peak_count_header = file("$baseDir/assets/multiqc/peak_count_header.txt", checkIfExists: true)
ch_frip_score_header = file("$baseDir/assets/multiqc/frip_score_header.txt", checkIfExists: true)
ch_peak_annotation_header = file("$baseDir/assets/multiqc/peak_annotation_header.txt", checkIfExists: true)
ch_deseq2_pca_header = file("$baseDir/assets/multiqc/deseq2_pca_header.txt", checkIfExists: true)
ch_deseq2_clustering_header = file("$baseDir/assets/multiqc/deseq2_clustering_header.txt", checkIfExists: true)
ch_spp_correlation_header = file("$baseDir/assets/multiqc/spp_correlation_header.txt", checkIfExists: true)
ch_spp_nsc_header = file("$baseDir/assets/multiqc/spp_nsc_header.txt", checkIfExists: true)
ch_spp_rsc_header = file("$baseDir/assets/multiqc/spp_rsc_header.txt", checkIfExists: true)
////////////////////////////////////////////////////
/* -- VALIDATE INPUTS -- */
////////////////////////////////////////////////////
// Validate inputs
if (params.design) { ch_design = file(params.design, checkIfExists: true) } else { exit 1, "Samples design file not specified!" }
if (params.gtf) { ch_gtf = file(params.gtf, checkIfExists: true) } else { exit 1, "GTF annotation file not specified!" }
if (params.gene_bed) { ch_gene_bed = file(params.gene.bed, checkIfExists: true) }
if (params.tss_bed) { ch_tss_bed = file(params.tss_bed, checkIfExists: true) }
if (params.blacklist) { ch_blacklist = file(params.blacklist, checkIfExists: true) }
if (params.fasta){
lastPath = params.fasta.lastIndexOf(File.separator)
bwa_base = params.fasta.substring(lastPath+1)
ch_fasta = file(params.fasta, checkIfExists: true)
} else {
exit 1, "Fasta file not specified!"
}
if (params.bwa_index){
lastPath = params.bwa_index.lastIndexOf(File.separator)
bwa_dir = params.bwa_index.substring(0,lastPath+1)
bwa_base = params.bwa_index.substring(lastPath+1)
ch_bwa_index = Channel
.fromPath(bwa_dir, checkIfExists: true)
.ifEmpty { exit 1, "BWA index directory not found: ${bwa_dir}" }
}
////////////////////////////////////////////////////
/* -- AWS -- */
////////////////////////////////////////////////////
if( workflow.profile == '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 (workflow.tracedir.startsWith('s3:')) exit 1, "Specify a local tracedir or run without trace! S3 cannot be used for tracefiles."
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/* -- -- */
/* -- HEADER LOG INFO -- */
/* -- -- */
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Header log info
log.info nfcoreHeader()
def summary = [:]
summary['Run Name'] = custom_runName ?: workflow.runName
summary['Data Type'] = params.singleEnd ? 'Single-End' : 'Paired-End'
summary['Design File'] = params.design
summary['Genome'] = params.genome ?: 'Not supplied'
summary['Fasta File'] = params.fasta
summary['GTF File'] = params.gtf
if (params.gene_bed) summary['Gene BED File'] = params.gene_bed
if (params.tss_bed) summary['TSS BED File'] = params.tss_bed
if (params.bwa_index) summary['BWA Index'] = params.bwa_index
if (params.blacklist) summary['Blacklist BED'] = params.blacklist
summary['MACS2 Genome Size'] = params.macs_gsize ?: 'Not supplied'
summary['Min Consensus Reps'] = params.min_reps_consensus
if (params.macs_gsize) summary['MACS2 Narrow Peaks'] = params.narrowPeak ? 'Yes' : 'No'
if (!params.narrowPeak) summary['MACS2 Broad Cutoff'] = params.broad_cutoff
if (params.skipTrimming){
summary['Trimming Step'] = 'Skipped'
} else {
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"
}
if (params.seq_center) summary['Sequencing Center'] = params.seq_center
if (params.singleEnd) summary['Fragment Size'] = "$params.fragment_size bp"
summary['Fingerprint Bins'] = params.fingerprint_bins
if (params.keepDups) summary['Keep Duplicates'] = 'Yes'
if (params.keepMultiMap) summary['Keep Multi-mapped'] = 'Yes'
summary['Save Genome Index'] = params.saveGenomeIndex ? 'Yes' : 'No'
if (params.saveTrimmed) summary['Save Trimmed'] = 'Yes'
if (params.saveAlignedIntermediates) summary['Save Intermeds'] = 'Yes'
if (params.saveMACSPileup) summary['Save MACS2 Pileup'] = 'Yes'
if (params.skipDiffAnalysis) summary['Skip Diff Analysis'] = 'Yes'
if (params.skipFastQC) summary['Skip FastQC'] = 'Yes'
if (params.skipPicardMetrics) summary['Skip Picard Metrics'] = 'Yes'
if (params.skipPreseq) summary['Skip Preseq'] = 'Yes'
if (params.skipPlotProfile) summary['Skip plotProfile'] = 'Yes'
if (params.skipPlotFingerprint) summary['Skip plotFingerprint'] = 'Yes'
if (params.skipSpp) summary['Skip spp'] = 'Yes'
if (params.skipIGV) summary['Skip IGV'] = 'Yes'
if (params.skipMultiQC) summary['Skip MultiQC'] = 'Yes'
if (params.skipMultiQCStats) summary['Skip MultiQC Stats'] = 'Yes'
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 == 'awsbatch'){
summary['AWS Region'] = params.awsregion
summary['AWS Queue'] = params.awsqueue
}
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
if(params.email) {
summary['E-mail Address'] = params.email
summary['MultiQC Max Size'] = params.maxMultiqcEmailFileSize
}
log.info summary.collect { k,v -> "${k.padRight(20)}: $v" }.join("\n")
log.info "\033[2m----------------------------------------------------\033[0m"
// Check the hostnames against configured profiles
checkHostname()
// Show a big warning message if we're not running MACS
if (!params.macs_gsize){
def warnstring = params.genome ? "supported for '${params.genome}'" : 'supplied'
log.warn "=================================================================\n" +
" WARNING! MACS genome size parameter not $warnstring.\n" +
" Peak calling, annotation and differential analysis will be skipped.\n" +
" Please specify value for '--macs_gsize' to run these steps.\n" +
"======================================================================="
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/* -- -- */
/* -- PARSE DESIGN FILE -- */
/* -- -- */
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/*
* PREPROCESSING - REFORMAT DESIGN FILE, CHECK VALIDITY & CREATE IP vs CONTROL MAPPINGS
*/
process checkDesign {
tag "$design"
publishDir "${params.outdir}/pipeline_info", mode: 'copy'
input:
file design from ch_design
output:
file "design_reads.csv" into ch_design_reads_csv
file "design_controls.csv" into ch_design_controls_csv
script: // This script is bundled with the pipeline, in nf-core/chipseq/bin/
"""
check_design.py $design design_reads.csv design_controls.csv
"""
}
/*
* Create channels for input fastq files
*/
if (params.singleEnd) {
ch_design_reads_csv.splitCsv(header:true, sep:',')
.map { row -> [ row.sample_id, [ file(row.fastq_1, checkIfExists: true) ] ] }
.into { ch_raw_reads_fastqc;
ch_raw_reads_trimgalore }
} else {
ch_design_reads_csv.splitCsv(header:true, sep:',')
.map { row -> [ row.sample_id, [ file(row.fastq_1, checkIfExists: true), file(row.fastq_2, checkIfExists: true) ] ] }
.into { ch_raw_reads_fastqc;
ch_raw_reads_trimgalore }
}
/*
* Create a channel with [sample_id, control id, antibody, replicatesExist, multipleGroups]
*/
ch_design_controls_csv.splitCsv(header:true, sep:',')
.map { row -> [ row.sample_id, row.control_id, row.antibody, row.replicatesExist.toBoolean(), row.multipleGroups.toBoolean() ] }
.set { ch_design_controls_csv }
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/* -- -- */
/* -- PREPARE ANNOTATION FILES -- */
/* -- -- */
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/*
* PREPROCESSING - Build BWA index
*/
if (!params.bwa_index){
process makeBWAindex {
tag "$fasta"
label 'process_high'
publishDir path: { params.saveGenomeIndex ? "${params.outdir}/reference_genome" : params.outdir },
saveAs: { params.saveGenomeIndex ? it : null }, mode: 'copy'
input:
file fasta from ch_fasta
output:
file "BWAIndex" into ch_bwa_index
script:
"""
bwa index -a bwtsw $fasta
mkdir BWAIndex && mv ${fasta}* BWAIndex
"""
}
}
/*
* PREPROCESSING - Generate gene BED file
*/
if (!params.gene_bed){
process makeGeneBED {
tag "$gtf"
label 'process_low'
publishDir "${params.outdir}/reference_genome", mode: 'copy'
input:
file gtf from ch_gtf
output:
file "*.bed" into ch_gene_bed
script: // This script is bundled with the pipeline, in nf-core/chipseq/bin/
"""
gtf2bed $gtf > ${gtf.baseName}.bed
"""
}
}
/*
* PREPROCESSING - Generate TSS BED file
*/
if (!params.tss_bed){
process makeTSSBED {
tag "$bed"
publishDir "${params.outdir}/reference_genome", mode: 'copy'
input:
file bed from ch_gene_bed
output:
file "*.bed" into ch_tss_bed
script:
"""
cat $bed | awk -v FS='\t' -v OFS='\t' '{ if(\$6=="+") \$3=\$2+1; else \$2=\$3-1; print \$1, \$2, \$3, \$4, \$5, \$6;}' > ${bed.baseName}.tss.bed
"""
}
}
/*
* PREPROCESSING - Prepare genome intervals for filtering
*/
process makeGenomeFilter {
tag "$fasta"
publishDir "${params.outdir}/reference_genome", mode: 'copy'
input:
file fasta from ch_fasta
output:
file "$fasta" into ch_genome_fasta // FASTA FILE FOR IGV
file "*.fai" into ch_genome_fai // FAI INDEX FOR REFERENCE GENOME
file "*.bed" into ch_genome_filter_regions // BED FILE WITHOUT BLACKLIST REGIONS
file "*.sizes" into ch_genome_sizes_bigwig // CHROMOSOME SIZES FILE FOR BEDTOOLS
script:
blacklist_filter = params.blacklist ? "sortBed -i ${params.blacklist} -g ${fasta}.sizes | complementBed -i stdin -g ${fasta}.sizes" : "awk '{print \$1, '0' , \$2}' OFS='\t' ${fasta}.sizes"
"""
samtools faidx $fasta
cut -f 1,2 ${fasta}.fai > ${fasta}.sizes
$blacklist_filter > ${fasta}.include_regions.bed
"""
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/* -- -- */
/* -- FASTQ QC -- */
/* -- -- */
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/*
* STEP 1 - FastQC
*/
process fastqc {
tag "$name"
label 'process_medium'
publishDir "${params.outdir}/fastqc", mode: 'copy',
saveAs: {filename -> filename.endsWith(".zip") ? "zips/$filename" : "$filename"}
when:
!params.skipFastQC
input:
set val(name), file(reads) from ch_raw_reads_fastqc
output:
file "*.{zip,html}" into ch_fastqc_reports_mqc
script:
// Added soft-links to original fastqs for consistent naming in MultiQC
if (params.singleEnd) {
"""
[ ! -f ${name}.fastq.gz ] && ln -s $reads ${name}.fastq.gz
fastqc -q ${name}.fastq.gz
"""
} else {
"""
[ ! -f ${name}_1.fastq.gz ] && ln -s ${reads[0]} ${name}_1.fastq.gz
[ ! -f ${name}_2.fastq.gz ] && ln -s ${reads[1]} ${name}_2.fastq.gz
fastqc -q ${name}_1.fastq.gz
fastqc -q ${name}_2.fastq.gz
"""
}
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/* -- -- */
/* -- ADAPTER TRIMMING -- */
/* -- -- */
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/*
* STEP 2 - Trim Galore!
*/
if (params.skipTrimming){
ch_trimmed_reads = ch_raw_reads_trimgalore
ch_trimgalore_results_mqc = []
ch_trimgalore_fastqc_reports_mqc = []
} else {
process trimGalore {
tag "$name"
label 'process_long'
publishDir "${params.outdir}/trim_galore", mode: 'copy',
saveAs: {filename ->
if (filename.endsWith(".html")) "fastqc/$filename"
else if (filename.endsWith(".zip")) "fastqc/zip/$filename"
else if (filename.endsWith("trimming_report.txt")) "logs/$filename"
else params.saveTrimmed ? filename : null
}
input:
set val(name), file(reads) from ch_raw_reads_trimgalore
output:
set val(name), file("*.fq.gz") into ch_trimmed_reads
file "*.txt" into ch_trimgalore_results_mqc
file "*.{zip,html}" into ch_trimgalore_fastqc_reports_mqc
script:
// Added soft-links to original fastqs for consistent naming in MultiQC
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}" : ''
if (params.singleEnd) {
"""
[ ! -f ${name}.fastq.gz ] && ln -s $reads ${name}.fastq.gz
trim_galore --fastqc --gzip $c_r1 $tpc_r1 ${name}.fastq.gz
"""
} else {
"""
[ ! -f ${name}_1.fastq.gz ] && ln -s ${reads[0]} ${name}_1.fastq.gz
[ ! -f ${name}_2.fastq.gz ] && ln -s ${reads[1]} ${name}_2.fastq.gz
trim_galore --paired --fastqc --gzip $c_r1 $c_r2 $tpc_r1 $tpc_r2 ${name}_1.fastq.gz ${name}_2.fastq.gz
"""
}
}
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/* -- -- */
/* -- ALIGN -- */
/* -- -- */
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/*
* STEP 3.1 - Align read 1 with bwa
*/
process bwaMEM {
tag "$name"
label 'process_high'
input:
set val(name), file(reads) from ch_trimmed_reads
file index from ch_bwa_index.collect()
output:
set val(name), file("*.bam") into ch_bwa_bam
script:
prefix="${name}.Lb"
if (!params.seq_center) {
rg="\'@RG\\tID:${name}\\tSM:${name.split('_')[0..-2].join('_')}\\tPL:ILLUMINA\\tLB:${name}\\tPU:1\'"
} else {
rg="\'@RG\\tID:${name}\\tSM:${name.split('_')[0..-2].join('_')}\\tPL:ILLUMINA\\tLB:${name}\\tPU:1\\tCN:${params.seq_center}\'"
}
"""
bwa mem \\
-t $task.cpus \\
-M \\
-R $rg \\
${index}/${bwa_base} \\
$reads \\
| samtools view -@ $task.cpus -b -h -F 0x0100 -O BAM -o ${prefix}.bam -
"""
}
/*
* STEP 3.2 - Convert .bam to coordinate sorted .bam
*/
process sortBAM {
tag "$name"
label 'process_medium'
if (params.saveAlignedIntermediates) {
publishDir path: "${params.outdir}/bwa/library", mode: 'copy',
saveAs: { filename ->
if (filename.endsWith(".flagstat")) "samtools_stats/$filename"
else if (filename.endsWith(".idxstats")) "samtools_stats/$filename"
else if (filename.endsWith(".stats")) "samtools_stats/$filename"
else filename }
}
input:
set val(name), file(bam) from ch_bwa_bam
output:
set val(name), file("*.sorted.{bam,bam.bai}") into ch_sort_bam_merge
file "*.{flagstat,idxstats,stats}" into ch_sort_bam_flagstat_mqc
script:
prefix="${name}.Lb"
"""
samtools sort -@ $task.cpus -o ${prefix}.sorted.bam -T $name $bam
samtools index ${prefix}.sorted.bam
samtools flagstat ${prefix}.sorted.bam > ${prefix}.sorted.bam.flagstat
samtools idxstats ${prefix}.sorted.bam > ${prefix}.sorted.bam.idxstats
samtools stats ${prefix}.sorted.bam > ${prefix}.sorted.bam.stats
"""
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/* -- -- */
/* -- MERGE LIBRARY BAM -- */
/* -- -- */
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/*
* STEP 4.1 Merge BAM files for all libraries from same sample
*/
ch_sort_bam_merge.map { it -> [ it[0].split('_')[0..-2].join('_'), it[1] ] }
.groupTuple(by: [0])
.map { it -> [ it[0], it[1].flatten() ] }
.set { ch_sort_bam_merge }
process mergeBAM {
tag "$name"
label 'process_medium'
publishDir "${params.outdir}/bwa/mergedLibrary", mode: 'copy',
saveAs: { filename ->
if (filename.endsWith(".flagstat")) "samtools_stats/$filename"
else if (filename.endsWith(".idxstats")) "samtools_stats/$filename"
else if (filename.endsWith(".stats")) "samtools_stats/$filename"
else if (filename.endsWith(".metrics.txt")) "picard_metrics/$filename"
else params.saveAlignedIntermediates ? filename : null
}
input:
set val(name), file(bams) from ch_sort_bam_merge
output:
set val(name), file("*${prefix}.sorted.{bam,bam.bai}") into ch_merge_bam_filter,
ch_merge_bam_preseq
file "*.{flagstat,idxstats,stats}" into ch_merge_bam_stats_mqc
file "*.txt" into ch_merge_bam_metrics_mqc
script:
prefix="${name}.mLb.mkD"
bam_files = bams.findAll { it.toString().endsWith('.bam') }.sort()
if (!task.memory){
log.info "[Picard MarkDuplicates] Available memory not known - defaulting to 3GB. Specify process memory requirements to change this."
avail_mem = 3
} else {
avail_mem = task.memory.toGiga()
}
if (bam_files.size() > 1) {
"""
picard -Xmx${avail_mem}g MergeSamFiles \\
${'INPUT='+bam_files.join(' INPUT=')} \\
OUTPUT=${name}.sorted.bam \\
SORT_ORDER=coordinate \\
VALIDATION_STRINGENCY=LENIENT \\
TMP_DIR=tmp
samtools index ${name}.sorted.bam
picard -Xmx${avail_mem}g MarkDuplicates \\
INPUT=${name}.sorted.bam \\
OUTPUT=${prefix}.sorted.bam \\
ASSUME_SORTED=true \\
REMOVE_DUPLICATES=false \\
METRICS_FILE=${prefix}.MarkDuplicates.metrics.txt \\
VALIDATION_STRINGENCY=LENIENT \\
TMP_DIR=tmp
samtools index ${prefix}.sorted.bam
samtools idxstats ${prefix}.sorted.bam > ${prefix}.sorted.bam.idxstats
samtools flagstat ${prefix}.sorted.bam > ${prefix}.sorted.bam.flagstat
samtools stats ${prefix}.sorted.bam > ${prefix}.sorted.bam.stats
"""
} else {
"""
picard -Xmx${avail_mem}g MarkDuplicates \\
INPUT=${bam_files[0]} \\
OUTPUT=${prefix}.sorted.bam \\
ASSUME_SORTED=true \\
REMOVE_DUPLICATES=false \\
METRICS_FILE=${prefix}.MarkDuplicates.metrics.txt \\
VALIDATION_STRINGENCY=LENIENT \\
TMP_DIR=tmp
samtools index ${prefix}.sorted.bam
samtools idxstats ${prefix}.sorted.bam > ${prefix}.sorted.bam.idxstats
samtools flagstat ${prefix}.sorted.bam > ${prefix}.sorted.bam.flagstat
samtools stats ${prefix}.sorted.bam > ${prefix}.sorted.bam.stats
"""
}
}
/*
* STEP 4.2 Filter BAM file at merged library-level
*/
process filterBAM {
tag "$name"
label 'process_medium'
publishDir path: "${params.outdir}/bwa/mergedLibrary", mode: 'copy',
saveAs: { filename ->
if (params.singleEnd || params.saveAlignedIntermediates) {
if (filename.endsWith(".flagstat")) "samtools_stats/$filename"
else if (filename.endsWith(".idxstats")) "samtools_stats/$filename"
else if (filename.endsWith(".stats")) "samtools_stats/$filename"
else if (filename.endsWith(".sorted.bam")) filename
else if (filename.endsWith(".sorted.bam.bai")) filename
else null }
}
input:
set val(name), file(bam) from ch_merge_bam_filter
file bed from ch_genome_filter_regions.collect()
file bamtools_filter_config from ch_bamtools_filter_config
output:
set val(name), file("*.{bam,bam.bai}") into ch_filter_bam
set val(name), file("*.flagstat") into ch_filter_bam_flagstat
file "*.{idxstats,stats}" into ch_filter_bam_stats_mqc
script:
prefix = params.singleEnd ? "${name}.mLb.clN" : "${name}.mLb.flT"
filter_params = params.singleEnd ? "-F 0x004" : "-F 0x004 -F 0x0008 -f 0x001"
dup_params = params.keepDups ? "" : "-F 0x0400"
multimap_params = params.keepMultiMap ? "" : "-q 1"
blacklist_params = params.blacklist ? "-L $bed" : ""
name_sort_bam = params.singleEnd ? "" : "samtools sort -n -@ $task.cpus -o ${prefix}.bam -T $prefix ${prefix}.sorted.bam"
"""
samtools view \\
$filter_params \\
$dup_params \\
$multimap_params \\
$blacklist_params \\
-b ${bam[0]} \\
| bamtools filter \\
-out ${prefix}.sorted.bam \\
-script $bamtools_filter_config
samtools index ${prefix}.sorted.bam
samtools flagstat ${prefix}.sorted.bam > ${prefix}.sorted.bam.flagstat
samtools idxstats ${prefix}.sorted.bam > ${prefix}.sorted.bam.idxstats
samtools stats ${prefix}.sorted.bam > ${prefix}.sorted.bam.stats
$name_sort_bam
"""
}
/*
* STEP 4.3 Remove orphan reads from paired-end BAM file
*/
if (params.singleEnd){
ch_filter_bam.into { ch_rm_orphan_bam_metrics;
ch_rm_orphan_bam_bigwig;
ch_rm_orphan_bam_macs_1;
ch_rm_orphan_bam_macs_2;
ch_rm_orphan_bam_phantompeakqualtools;
ch_rm_orphan_name_bam_counts }
ch_filter_bam_flagstat.into { ch_rm_orphan_flagstat_bigwig;
ch_rm_orphan_flagstat_macs;
ch_rm_orphan_flagstat_mqc }
ch_filter_bam_stats_mqc.set { ch_rm_orphan_stats_mqc }
} else {
process rmOrphanReads {
tag "$name"
label 'process_medium'
publishDir path: "${params.outdir}/bwa/mergedLibrary", mode: 'copy',
saveAs: { filename ->
if (filename.endsWith(".flagstat")) "samtools_stats/$filename"
else if (filename.endsWith(".idxstats")) "samtools_stats/$filename"
else if (filename.endsWith(".stats")) "samtools_stats/$filename"
else if (filename.endsWith(".sorted.bam")) filename
else if (filename.endsWith(".sorted.bam.bai")) filename
else null
}
input:
set val(name), file(bam) from ch_filter_bam
output:
set val(name), file("*.sorted.{bam,bam.bai}") into ch_rm_orphan_bam_metrics,
ch_rm_orphan_bam_bigwig,
ch_rm_orphan_bam_macs_1,
ch_rm_orphan_bam_macs_2,
ch_rm_orphan_bam_phantompeakqualtools
set val(name), file("${prefix}.bam") into ch_rm_orphan_name_bam_counts
set val(name), file("*.flagstat") into ch_rm_orphan_flagstat_bigwig,
ch_rm_orphan_flagstat_macs,
ch_rm_orphan_flagstat_mqc
file "*.{idxstats,stats}" into ch_rm_orphan_stats_mqc
script: // This script is bundled with the pipeline, in nf-core/chipseq/bin/
prefix="${name}.mLb.clN"
"""
bampe_rm_orphan.py ${bam[0]} ${prefix}.bam --only_fr_pairs
samtools sort -@ $task.cpus -o ${prefix}.sorted.bam -T $prefix ${prefix}.bam
samtools index ${prefix}.sorted.bam
samtools flagstat ${prefix}.sorted.bam > ${prefix}.sorted.bam.flagstat
samtools idxstats ${prefix}.sorted.bam > ${prefix}.sorted.bam.idxstats
samtools stats ${prefix}.sorted.bam > ${prefix}.sorted.bam.stats
"""
}
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/* -- -- */
/* -- MERGE LIBRARY BAM POST-ANALYSIS -- */
/* -- -- */
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/*
* STEP 5.1 preseq analysis after merging libraries and before filtering
*/
process preseq {
tag "$name"
label 'process_low'
publishDir "${params.outdir}/bwa/mergedLibrary/preseq", mode: 'copy'
when:
!params.skipPreseq
input:
set val(name), file(bam) from ch_merge_bam_preseq
output:
file "*.ccurve.txt" into ch_preseq_results
script:
prefix="${name}.mLb.clN"
"""
preseq lc_extrap -v -output ${prefix}.ccurve.txt -bam ${bam[0]}
"""
}
/*
* STEP 5.2 Picard CollectMultipleMetrics after merging libraries and filtering
*/
process collectMultipleMetrics {
tag "$name"
label 'process_medium'
publishDir path: "${params.outdir}/bwa/mergedLibrary", mode: 'copy',
saveAs: { filename ->
if (filename.endsWith("_metrics")) "picard_metrics/$filename"
else if (filename.endsWith(".pdf")) "picard_metrics/pdf/$filename"
else null
}
when:
!params.skipPicardMetrics
input:
set val(name), file(bam) from ch_rm_orphan_bam_metrics
file fasta from ch_fasta
output:
file "*_metrics" into ch_collectmetrics_mqc
file "*.pdf" into ch_collectmetrics_pdf
script:
prefix="${name}.mLb.clN"
if (!task.memory){
log.info "[Picard CollectMultipleMetrics] Available memory not known - defaulting to 3GB. Specify process memory requirements to change this."
avail_mem = 3
} else {
avail_mem = task.memory.toGiga()
}
"""
picard -Xmx${avail_mem}g CollectMultipleMetrics \\
INPUT=${bam[0]} \\
OUTPUT=${prefix}.CollectMultipleMetrics \\
REFERENCE_SEQUENCE=$fasta \\
VALIDATION_STRINGENCY=LENIENT \\
TMP_DIR=tmp
"""
}
/*
* STEP 5.3 Read depth normalised bigWig
*/
process bigWig {
tag "$name"
label 'process_medium'
publishDir "${params.outdir}/bwa/mergedLibrary/bigwig", mode: 'copy',
saveAs: {filename ->
if (filename.endsWith(".txt")) "scale/$filename"
else if (filename.endsWith(".bigWig")) "$filename"
else null
}
input:
set val(name), file(bam), file(flagstat) from ch_rm_orphan_bam_bigwig.join(ch_rm_orphan_flagstat_bigwig, by: [0])
file sizes from ch_genome_sizes_bigwig.collect()
output:
set val(name), file("*.bigWig") into ch_bigwig_plotprofile
file "*scale_factor.txt" into ch_bigwig_scale
file "*igv.txt" into ch_bigwig_igv
script:
prefix="${name}.mLb.clN"
pe_fragment = params.singleEnd ? "" : "-pc"
extend = (params.singleEnd && params.fragment_size > 0) ? "-fs ${params.fragment_size}" : ''
"""
SCALE_FACTOR=\$(grep 'mapped (' $flagstat | awk '{print 1000000/\$1}')
echo \$SCALE_FACTOR > ${prefix}.scale_factor.txt
genomeCoverageBed -ibam ${bam[0]} -bg -scale \$SCALE_FACTOR $pe_fragment $extend | sort -k1,1 -k2,2n > ${prefix}.bedGraph
bedGraphToBigWig ${prefix}.bedGraph $sizes ${prefix}.bigWig
find * -type f -name "*.bigWig" -exec echo -e "bwa/mergedLibrary/bigwig/"{}"\\t0,0,178" \\; > ${prefix}.bigWig.igv.txt
"""
}
/*
* STEP 5.4 generate gene body coverage plot with deepTools
*/
process plotProfile {
tag "$name"
label 'process_high'
publishDir "${params.outdir}/bwa/mergedLibrary/deepTools/plotProfile", mode: 'copy'
when:
!params.skipPlotProfile
input:
set val(name), file(bigwig) from ch_bigwig_plotprofile
file bed from ch_gene_bed
output:
file '*.{gz,pdf}' into ch_plotprofile_results
file '*.plotProfile.tab' into ch_plotprofile_mqc
script:
"""
computeMatrix scale-regions \\
--regionsFileName $bed \\
--scoreFileName $bigwig \\
--outFileName ${name}.computeMatrix.mat.gz \\
--outFileNameMatrix ${name}.computeMatrix.vals.mat.gz \\
--regionBodyLength 1000 \\
--beforeRegionStartLength 3000 \\
--afterRegionStartLength 3000 \\
--skipZeros \\
--smartLabels \\
-p $task.cpus
plotProfile --matrixFile ${name}.computeMatrix.mat.gz \\
--outFileName ${name}.plotProfile.pdf \\
--outFileNameData ${name}.plotProfile.tab
"""
}
/*
* STEP 5.5 Phantompeakqualtools
*/
process phantomPeakQualTools {
tag "$name"
label 'process_medium'
publishDir "${params.outdir}/bwa/mergedLibrary/phantompeakqualtools", mode: 'copy'
when:
!params.skipSpp
input:
set val(name), file(bam) from ch_rm_orphan_bam_phantompeakqualtools
file spp_correlation_header from ch_spp_correlation_header
file spp_nsc_header from ch_spp_nsc_header
file spp_rsc_header from ch_spp_rsc_header
output:
file '*.pdf' into ch_spp_plot
file '*.spp.out' into ch_spp_out,
ch_spp_out_mqc
file '*_mqc.tsv' into ch_spp_csv_mqc
script:
"""
RUN_SPP=`which run_spp.R`
Rscript -e "library(caTools); source(\\"\$RUN_SPP\\")" -c="${bam[0]}" -savp="${name}.spp.pdf" -savd="${name}.spp.Rdata" -out="${name}.spp.out" -p=$task.cpus
cp $spp_correlation_header ${name}_spp_correlation_mqc.tsv
Rscript -e "load('${name}.spp.Rdata'); write.table(crosscorr\\\$cross.correlation, file=\\"${name}_spp_correlation_mqc.tsv\\", sep=",", quote=FALSE, row.names=FALSE, col.names=FALSE,append=TRUE)"
awk -v OFS='\t' '{print "${name}", \$9}' ${name}.spp.out | cat $spp_nsc_header - > ${name}_spp_nsc_mqc.tsv
awk -v OFS='\t' '{print "${name}", \$10}' ${name}.spp.out | cat $spp_rsc_header - > ${name}_spp_rsc_mqc.tsv
"""
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/* -- -- */
/* -- MERGE LIBRARY PEAK ANALYSIS -- */
/* -- -- */
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Create channel linking IP bams with control bams
ch_rm_orphan_bam_macs_1.combine(ch_rm_orphan_bam_macs_2)
.set { ch_rm_orphan_bam_macs_1 }
ch_design_controls_csv.combine(ch_rm_orphan_bam_macs_1)