-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.nf
2053 lines (1820 loc) · 82.1 KB
/
main.nf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env nextflow
/*
========================================================================================
MeRIPseqPipe
========================================================================================
MeRIPseqPipe Analysis Pipeline.
#### Homepage / Documentation
https://github.com/canceromics/MeRIPseqPipe
----------------------------------------------------------------------------------------
*/
/*
* to be added
*
* Authors:
* Qi Zhao <[email protected]>: design and implement the pipeline.
* Zhu Kaiyu <[email protected]>:
*/
// requirement:
// - fastp/fastqc
// - STAR/tophat2/bowtie2/hisat2
// - samtools/rseqc
// - MeTPeak/Macs2/MATK/meyer
// - RobustRankAggreg/bedtools
// - Cufflinks/DESeq2/EdgeR
// - QNB/MATK
// - Homer
// - SRAMP/MATK
// - igvtools
def helpMessage() {
// TODO nf-core: Add to this help message with new command line parameters
// log.info nfcoreHeader()
log.info"""
Usage:
The typical command for running the pipeline is as follows:
nextflow path/to/m6APipe/main.nf --readPaths './data/' --designfile -profile standard,docker
Mandatory arguments:
--readPaths Path to input data (must be surrounded with quotes)
--genome Name of iGenomes reference
--designfile format:filename,control_or_treated,ip_or_input,tag_id
--comparefile
-profile Configuration profile to use. Can use multiple (comma separated)
Available: standard, conda, docker, singularity, awsbatch, test
References If not specified in the configuration file or you wish to overwrite any of the references.
--fasta Path to Fasta reference
--gtf Path to GTF reference
Options:
--inputformat fastq.gz;fastq default = fastq
--single_end Specifies that the input is single end reads
--tophat2_index Path to tophat2 index, eg. "path/to/Tophat2Index/*"
--hisat2_index Path to hisat2 index, eg. "path/to/Hisat2Index/*"
--bwa_index Path to bwa index, eg. "path/to/BwaIndex/*"
--star_index Path to star index, eg. "path/to/StarIndex/"
--skip_qc Skip all QC steps
--skip_peakCalling Skip all Peak Calling steps
--skip_diffpeakCalling Skip all Differential methylation analysis
Other options:
--outdir The output directory where the results will be saved, defalut = $baseDir/results
--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
-name Name for the pipeline run. If not specified, Nextflow will automatically generate a random mnemonic.
--skip_fastqc Skip FastQC
--skip_rseqc Skip RSeQC
--skip_genebody_coverage Skip calculating genebody coverage
--skip_cufflinks Skip the cufflinks process of differential expression analysis steps
--skip_edger Skip the EdgeR process of differential expression analysis steps
--skip_deseq2 Skip the deseq2 process of differential expression analysis steps
--skip_metpeak Skip the metpeak process of Peak Calling steps
--skip_macs2 Skip the macs2 process of Peak Calling steps
--skip_matk Skip the matk process of Peak Calling steps
--skip_metdiff Skip the metdiff process of Differential methylation analysis
--skip_QNB Skip the QNB process of Differential methylation analysis
--skip_diffmatk Skip the matk process of Differential methylation analysis
AWSBatch options:
--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()
}
// Show help message
if (params.help) {
helpMessage()
exit 0
}
// Stage config files
ch_multiqc_config = file(params.multiqc_config, checkIfExists: true)
ch_output_docs = file("$baseDir/docs/output.md", checkIfExists: true)
/*
* SET UP CONFIGURATION VARIABLES
*/
// Configurable variables
params.name = false
params.project = false
params.genome = false
params.call = false
params.email = false
params.plaintext_email = false
params.seqCenter = false
params.help = false
// Validate inputs
// 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(", ")}"
}
// TODO nf-core: Add any reference files that are needed
// Configurable reference genomes
//
// NOTE - THIS IS NOT USED IN THIS PIPELINE, EXAMPLE ONLY
// If you want to use the channel below in a process, define the following:
// input:
// file fasta from ch_fasta
//
// Reference index path configuration
// Define these here - after the profiles are loaded with the iGenomes paths
params.star_index = params.genome ? params.genomes[ params.genome ].star ?: false : false
params.fasta = params.genome ? params.genomes[ params.genome ].fasta ?: false : false
params.gtf = params.genome ? params.genomes[ params.genome ].gtf ?: false : false
params.bed12 = params.genome ? params.genomes[ params.genome ].bed12 ?: false : false
params.hisat2_index = params.genome ? params.genomes[ params.genome ].hisat2 ?: 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
}
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."
}
if ( params.fasta ){
fasta = file(params.fasta, checkIfExists: true)
if( !fasta.exists() ) exit 1, LikeletUtils.print_red("Fasta file not found: ${params.fasta}")
}else {
exit 1, LikeletUtils.print_red("No reference genome specified!")
}
if( params.gtf ){
gtf = file ( params.gtf, checkIfExists: true)
if( !gtf.exists() ) exit 1, LikeletUtils.print_red("gtf not found: ${params.gtf}")
} else {
exit 1, LikeletUtils.print_red("No GTF annotation specified!")
}
if ( params.rRNA_fasta ){
rRNA_fasta = file(params.rRNA_fasta, checkIfExists: true)
if( !rRNA_fasta.exists() ) exit 1, LikeletUtils.print_red("Fasta file not found: ${params.rRNA_fasta}")
}else{
rRNA_fasta = Channel.from("")
}
if( params.comparefile == "two_group" ){
comparefile = false
compareLines = Channel.from("two_group")
}else if( params.comparefile){
comparefile = file(params.comparefile)
if( !comparefile.exists() ) exit 1, print_red("Compare file not found: ${params.comparefile}")
compareLines = Channel.from(comparefile.readLines())
}else {
comparefile = false
compareLines = Channel.from("")
}
compareLines.into{
compareLines_for_DESeq2; compareLines_for_edgeR; compareLines_for_plot;
compareLines_for_diffm6A; compareLines_for_arranged_result
}
// Validate the params of skipping Aligners Tools Setting
if( params.aligners == "none" || params.aligners == "star" || params.aligners == "hisat2" || params.aligners == "tophat2" || params.aligners == "bwa" ){
aligner = params.aligners
}else{
exit 1, LikeletUtils.print_red("Invalid aligner option: ${params.aligner}. Valid options: 'star', 'hisat2', 'tophat2', 'bwa', 'none'")
}
if( params.expression_analysis_mode == "edgeR" ){
params.skip_edger = false
params.skip_deseq2 = true
params.skip_cufflinks = true
params.skip_expression = false
}else if( params.expression_analysis_mode == "DESeq2" ){
params.skip_edger = true
params.skip_deseq2 = false
params.skip_cufflinks = true
params.skip_expression = false
}else if( params.expression_analysis_mode == "Cufflinks" ){
params.skip_edger = true
params.skip_deseq2 = true
params.skip_cufflinks = false
params.skip_expression = false
}else if( params.expression_analysis_mode == "none" ){
params.skip_edger = true
params.skip_deseq2 = true
params.skip_cufflinks = true
params.skip_expression = true
}else{
exit 1, LikeletUtils.print_red("Invalid expression_analysis_mode option: ${params.expression_analysis_mode}. Valid options: 'edgeR', 'DESeq2', 'none'")
}
/*
* Create a channel for input read files
*/
if ( params.readPaths ){
if (aligner == 'none') {
Channel
.fromPath( params.readPaths )
.ifEmpty { exit 1, "params.readPaths was empty - no input files supplied" }
.into{ raw_fastq; raw_bam }
} else if ( params.single_end ) {
Channel
.from( params.readPaths )
.map{ row -> [ row[0], [ file(row[1][0], checkIfExists: true) ] ] }
.ifEmpty { exit 1, "params.readPaths was empty - no input files supplied" }
.into{ raw_fastq; raw_bam }
} else {
Channel
.from( params.readPaths )
.map{ row -> [ row[0], [ file(row[1][0], checkIfExists: true), file(row[1][1], checkIfExists: true) ] ] }
.ifEmpty { exit 1, "params.readPaths was empty - no input files supplied" }
.into{ raw_fastq; raw_bam }
}
}else if( params.designfile ) {
designfile = file(params.designfile, checkIfExists: true)
if( !designfile.exists() ) exit 1, LikeletUtils.print_red("Design file not found: ${params.designfile}")
LikeletUtils.extractData(designfile).into{ input_data_fastq; input_data_bam; designinfo}
input_data_fastq.filter{ it[6] == "fastq" }.map{ it.subList(0,6) }.set{ raw_fastq } //filter filetype & delete filetype
input_data_bam.filter{ it[6] == "bam" }.map{ it.subList(0,6) }.set{ raw_bam }
designinfo.map{ it.getAt([0,5]) }.set{ format_design }
}else{
exit 1, LikeletUtils.print_red("No Design file specified!")
}
/* else if( params.input && aligner != "none" ){
Channel
.fromFilePairs( "${params.input}", size: params.single_end ? 1 : 2 )
.ifEmpty { exit 1, LikeletUtils.print_red("reads was empty - no fastq files supplied: ${params.input}. You may check whether it is quoted")}
.into{ raw_fastq; raw_bam }
}else if( params.input && aligner == "none" ){
Channel
.fromPath( params.input )
.ifEmpty { exit 1, LikeletUtils.print_red("reads was empty - no bam files supplied: ${params.input}")}
.into{ raw_fastq; raw_bam }
}
else{
println LikeletUtils.print_red("reads was empty: ${params.input}")
} */
/*
showing the process and files
========================================================================================
*/
// Header log info
println LikeletUtils.sysucc_ascii()
println LikeletUtils.print_purple("============You are running m6APipe with the following parameters===============")
println LikeletUtils.print_purple("Checking parameters ...")
println LikeletUtils.print_yellow("===================================Pipeline summary=============================")
println (LikeletUtils.print_yellow("Max Resources : ") + LikeletUtils.print_green("$params.max_memory memory, $params.max_cpus cpus, $params.max_time time per job"))
if (workflow.containerEngine){
println (LikeletUtils.print_yellow("Container : ") + LikeletUtils.print_green("$workflow.containerEngine - $workflow.container"))
}
println (LikeletUtils.print_yellow("Output dir : ") + LikeletUtils.print_green(params.outdir))
println (LikeletUtils.print_yellow("Launch dir : ") + LikeletUtils.print_green(workflow.launchDir))
println (LikeletUtils.print_yellow("Working dir : ") + LikeletUtils.print_green(workflow.workDir))
println (LikeletUtils.print_yellow("Script dir : ") + LikeletUtils.print_green(workflow.projectDir))
println (LikeletUtils.print_yellow("User : ") + LikeletUtils.print_green(workflow.userName))
if (workflow.profile == 'awsbatch') {
println (LikeletUtils.print_yellow("AWS Region : ") + LikeletUtils.print_green(params.awsregion))
println (LikeletUtils.print_yellow("AWS Queue : ") + LikeletUtils.print_green(params.awsqueue))
}
println (LikeletUtils.print_yellow("Config Profile : ") + LikeletUtils.print_green(workflow.profile))
if (params.config_profile_description){
println (LikeletUtils.print_yellow("Config Description : ") + LikeletUtils.print_green(params.config_profile_description))
}
if (params.config_profile_contact){
println (LikeletUtils.print_yellow("Config Contact : ") + LikeletUtils.print_green(params.config_profile_contact))
}
if (params.config_profile_url){
println (LikeletUtils.print_yellow("Config URL : ") + LikeletUtils.print_green(params.config_profile_url))
}
if (params.email || params.email_on_fail) {
println (LikeletUtils.print_yellow("E-mail Address : ") + LikeletUtils.print_green(params.email))
println (LikeletUtils.print_yellow("E-mail on failure : ") + LikeletUtils.print_green(params.email_on_fail))
println (LikeletUtils.print_yellow("MultiQC maxsize : ") + LikeletUtils.print_green(params.maxMultiqcEmailFileSize))
}
println LikeletUtils.print_yellow("=====================================Reads types================================")
println (LikeletUtils.print_yellow("SingleEnd : ") + LikeletUtils.print_green(params.single_end ? 'Single-End' : 'Paired-End'))
println (LikeletUtils.print_yellow("Stranded : ") + LikeletUtils.print_green(params.stranded))
println (LikeletUtils.print_yellow("gzip : ") + LikeletUtils.print_green(params.gzip))
println LikeletUtils.print_yellow("====================================Mode selected==============================")
println (LikeletUtils.print_yellow("aligners : ") + LikeletUtils.print_green(params.aligners))
println (LikeletUtils.print_yellow("peakCalling_mode : ") + LikeletUtils.print_green(params.peakCalling_mode))
println (LikeletUtils.print_yellow("peakMerged_mode : ") + LikeletUtils.print_green(params.peakMerged_mode))
println (LikeletUtils.print_yellow("expression_analysis_mode : ") + LikeletUtils.print_green(params.expression_analysis_mode))
println (LikeletUtils.print_yellow("methylation_analysis_mode : ") + LikeletUtils.print_green(params.methylation_analysis_mode))
println LikeletUtils.print_yellow("==================================Input files selected==========================")
println (LikeletUtils.print_yellow("Reads Path : ") + LikeletUtils.print_green(params.readPaths ? "github" : params.input))
println (LikeletUtils.print_yellow("fasta file : ") + LikeletUtils.print_green(params.fasta))
println (LikeletUtils.print_yellow("Gtf file : ") + LikeletUtils.print_green(params.gtf))
println (LikeletUtils.print_yellow("Design file : ") + LikeletUtils.print_green(params.designfile))
println (LikeletUtils.print_yellow("Compare file : ") + LikeletUtils.print_green(params.comparefile))
println LikeletUtils.print_yellow("==================================Skip model selected==========================")
println (LikeletUtils.print_yellow("Skip samtools sort : ") + LikeletUtils.print_green(params.skip_sort))
println (LikeletUtils.print_yellow("Skip expression analysis : ") + LikeletUtils.print_green(params.skip_expression))
println (LikeletUtils.print_yellow("Skip peakCalling : ") + LikeletUtils.print_green(params.skip_peakCalling))
println (LikeletUtils.print_yellow("Skip diffpeakCalling : ") + LikeletUtils.print_green(params.skip_diffpeakCalling))
println (LikeletUtils.print_yellow("Skip annotation : ") + LikeletUtils.print_green(params.skip_annotation))
println (LikeletUtils.print_yellow("Skip qc : ") + LikeletUtils.print_green(params.skip_qc))
// log.info summary.collect { k,v -> "${k.padRight(18)}: $v" }.join("\n")
// // Check the hostnames against configured profiles
// checkHostname()
/*
========================================================================================
check or build the index
========================================================================================
*/
/*
* PREPROCESSING - Build BED12 file
* NEED gtf.file
*/
process CheckDesignCompare{
input:
val design_info from format_design.collect()
file comparefile
output:
file (formatted_design) into formatted_designfile
script:
formatted_design = "formatted_designfile.txt"
formatted_design_info = ""
for(int i = 0; i < design_info.size(); i+=2 ) {
sample = design_info[i] + ".input," + design_info[i] + ".ip"
formatted_design_info += design_info[i] + "," + sample + "," + design_info[i+1] + "\n"
}
"""
echo "Sample_ID,input_FileName,ip_FileName,Group" > $formatted_design
echo "$formatted_design_info" |awk NF |sort | uniq >> $formatted_design
# Check the consistency of designfile and comparefile
if [ "$comparefile" != "input.1" ]; then
## get groups' name in comparefile
cat $comparefile | dos2unix | awk -F "_vs_" '{print \$1"\\n"\$2}' | sort | uniq > tmp.compare.group
## get groups' name in designfile
awk -F, 'NR>1{print \$4}' $formatted_design | sort | uniq > tmp.design.group
intersection_num=\$(join tmp.compare.group tmp.design.group | wc -l)
if [[ \$intersection_num != \$(cat tmp.compare.group| wc -l) ]] ;then
echo "The groups' name of comparefile and designfile are inconsistent."
echo "Please check your comparefile: "$comparefile
echo "The groups' name of comparefile in designfile: "\$(join tmp.compare.group tmp.design.group)
exit 1
fi
rm tmp.compare.group tmp.design.group
fi
"""
}
process makeBED12 {
label 'build_index'
tag "gtf2bed12"
publishDir path: { params.saveReference ? "${params.outdir}/Genome/reference_genome" : params.outdir },
saveAs: { params.saveReference ? it : null }, mode: 'copy'
when:
!params.skip_qc && !params.skip_rseqc || !params.skip_motif
input:
file gtf
output:
file "${gtf.baseName}.bed" into bed12file
shell:
'''
gtf_file=!{gtf}
gtfToGenePred -genePredExt -geneNameAsName2 $gtf_file ${gtf_file/.gtf/.tmp}
genePredToBed ${gtf_file/.gtf/.tmp} ${gtf_file/.gtf/.bed}
'''
}
process makechromesize {
label 'build_index'
tag "gtf2bed12"
publishDir path: { params.saveReference ? "${params.outdir}/Genome/reference_genome" : params.outdir },
saveAs: { params.saveReference ? it : null }, mode: 'copy'
when:
true
input:
file fasta
output:
file "chromsizes.file" into chromsizesfile
shell:
"""
samtools faidx ${fasta}
cut -f1,2 ${fasta}.fai > chromsizes.file
"""
}
/*
* PREPROCESSING - Build TOPHAT2 index
* NEED genome.fa
*/
if( params.tophat2_index && aligner == "tophat2" ){
tophat2_index = Channel
.fromPath( params.tophat2_index )
.ifEmpty { exit 1, "Tophat2 index not found: ${params.tophat2_index}" }
}else if( params.fasta ){
process MakeTophat2Index {
label 'build_index'
tag "tophat2_index"
publishDir path: { params.saveReference ? "${params.outdir}/Genome/": params.outdir },
saveAs: { params.saveReference ? it : null }, mode: 'copy'
input:
file fasta
output:
file "Tophat2Index/*" into tophat2_index
when:
aligner == "tophat2"
script:
tophat2_index = "Tophat2Index/" + fasta.baseName.toString()
"""
mkdir Tophat2Index
ln $fasta Tophat2Index
bowtie2-build -f $fasta $tophat2_index
"""
}
}else {
exit 1, println LikeletUtils.print_red("There is no Tophat2 Index")
}
/*
* PREPROCESSING - Build HISAT2 index
* NEED genome.fa genes.gtf snp.txt/vcf
*/
if( params.hisat2_index && aligner == "hisat2" ){
hisat2_index = Channel
.fromPath(params.hisat2_index)
.ifEmpty { exit 1, "hisat2 index not found: ${params.hisat2_index}" }
}else if( params.fasta){
process MakeHisat2Index {
label 'build_index'
tag "hisat2_index"
publishDir path: { params.saveReference ? "${params.outdir}/Genome/ " : params.outdir },
saveAs: { params.saveReference ? it : null }, mode: 'copy'
input:
file fasta
file gtf
output:
file "Hisat2Index/*" into hisat2_index
when:
aligner == "hisat2"
script:
"""
mkdir Hisat2Index
hisat2_extract_exons.py $gtf > Hisat2Index/${fasta.baseName}.exon
hisat2_extract_splice_sites.py $gtf > Hisat2Index/${fasta.baseName}.ss
hisat2-build -p ${task.cpus} -f $fasta --exon Hisat2Index/${fasta.baseName}.exon --ss Hisat2Index/${fasta.baseName}.ss Hisat2Index/${fasta.baseName}
"""
}
}else {
exit 1, println LikeletUtils.print_red("There is no Hisat2 Index")
}
/*
* PREPROCESSING - Build BWA index
* NEED genome.fa
*/
if( params.bwa_index && aligner == "bwa" ){
bwa_index = Channel
.fromPath( params.bwa_index )
.ifEmpty { exit 1, "bwa index not found: ${params.bwa_index}" }
}else if(params.fasta ){
process MakeBWAIndex {
label 'build_index'
tag "bwa_index"
publishDir path: { params.saveReference ? "${params.outdir}/Genome/" : params.outdir },
saveAs: { params.saveReference ? it : null }, mode: 'copy'
input:
file fasta
output:
file "BWAIndex/*" into bwa_index
when:
aligner == "bwa"
script:
"""
mkdir BWAIndex
cd BWAIndex/
bwa index -p ${fasta.baseName} -a bwtsw ../$fasta
cd ../
"""
}
}else {
exit 1, println LikeletUtils.print_red("There is no BWA Index")
}
/*
* PREPROCESSING - Build STAR index
* NEED genome.fa genes.gtf
*/
if( params.star_index && aligner == "star"){
star_index = Channel
.fromPath(params.star_index)
.ifEmpty { exit 1, "STAR index not found: ${params.star_index}" }
}else if( params.fasta ){
process MakeStarIndex {
label 'build_index'
tag "star_index"
publishDir path: { params.saveReference ? "${params.outdir}/Genome/" : params.outdir },
saveAs: { params.saveReference ? it : null }, mode: 'copy'
input:
file fasta
file gtf
output:
file "StarIndex" into star_index
when:
aligner == "star"
script:
readLength = 50
overhang = readLength - 1
"""
mkdir StarIndex
STAR --runThreadN ${task.cpus} \
--runMode genomeGenerate \
--genomeDir StarIndex \
--genomeFastaFiles $fasta \
--sjdbGTFfile $gtf \
--sjdbOverhang $overhang \
--limitGenomeGenerateRAM 36000000000
"""
}
}else {
exit 1, println LikeletUtils.print_red("There is no STAR Index")
}
/*
* PREPROCESSING - Build rRNA index
* NEED rRNA.fa
*/
process MakerRNAindex {
label 'build_index'
tag "rRNA_index"
publishDir path: { params.saveReference ? "${params.outdir}/Genome/" : params.outdir },
saveAs: { params.saveReference ? it : null }, mode: 'copy'
input:
file rRNA_fasta from rRNA_fasta
output:
file "rRNAindex/*" into rRNA_index
when:
params.rRNA_fasta && !params.skip_filterrRNA
script:
"""
mkdir rRNAindex
hisat2-build -p ${task.cpus} -f $rRNA_fasta rRNAindex/${rRNA_fasta.baseName}
"""
}
/*
========================================================================================
Step 1. QC------Fastp & FastQC
========================================================================================
*/
process Fastp{
label 'fastp'
tag "$sample_name"
//errorStrategy 'ignore'
publishDir path: { params.skip_fastp ? params.outdir : "${params.outdir}/QC/fastp" },
saveAs: { params.skip_fastp ? null : it }, mode: 'link'
input:
set val(sample_id), file(reads), val(reads_single_end), val(gzip), val(input), val(group) from raw_fastq
output:
set val(sample_name), file("*_aligners.fastq*"), val(reads_single_end), val(sample_id), val(gzip), val(input), val(group) into fastqc_reads, fastp_reads
file "*" into fastp_results
when:
aligner != "none"
shell:
skip_fastp = params.skip_fastp
if ( reads_single_end ){
filename = reads.toString() - ~/(\.fq)?(\.fastq)?(\.gz)?$/
sample_name = filename
add_aligners = sample_name + "_aligners.fastq" + (gzip ? ".gz" : "")
"""
if [ $skip_fastp == "false" ]; then
fastp -i ${reads} -o ${add_aligners} -j ${sample_name}_fastp.json -h ${sample_name}_fastp.html -w ${task.cpus}
else
mv ${reads} ${add_aligners}
fi
"""
} else {
filename = reads[0].toString() - ~/(_R[0-9])?(_[0-9])?(\.fq)?(\.fastq)?(\.gz)?$/
sample_name = filename
add_aligners_1 = sample_name + "_1_aligners.fastq" + (gzip ? ".gz" : "")
add_aligners_2 = sample_name + "_2_aligners.fastq" + (gzip ? ".gz" : "")
"""
if [ $skip_fastp == "false" ]; then
fastp -i ${reads[0]} -o ${add_aligners_1} -I ${reads[1]} -O ${add_aligners_2} -j ${sample_name}_fastp.json -h ${sample_name}_fastp.html -w ${task.cpus}
else
mv ${reads[0]} ${add_aligners_1}
mv ${reads[1]} ${add_aligners_2}
fi
"""
}
}
process Fastqc{
tag "$sample_name"
publishDir path: { params.skip_fastqc ? params.outdir : "${params.outdir}/QC" },
saveAs: { params.skip_fastqc ? null : it }, mode: 'link'
input:
set val(sample_name), file(reads), val(reads_single_end), val(sample_id), val(gzip), val(input), val(group) from fastqc_reads
output:
file "fastqc/*" into fastqc_results
when:
aligner != "none" && !params.skip_fastqc
shell:
skip_fastqc = params.skip_fastqc
if ( reads_single_end){
"""
mkdir fastqc
fastqc -o fastqc --noextract ${reads}
"""
} else {
"""
mkdir fastqc
fastqc -o fastqc --noextract ${reads[0]}
fastqc -o fastqc --noextract ${reads[1]}
"""
}
}
/*
========================================================================================
Step 2. Reads Mapping
========================================================================================
*/
if(params.rRNA_fasta && !params.skip_filterrRNA){
fastp_reads.set{rRNA_reads}
process FilterrRNA {
label 'aligners'
tag "$sample_name"
publishDir "${params.outdir}/alignment/rRNA_dup", mode: 'link', overwrite: true
input:
set val(sample_name), file(reads), val(reads_single_end), val(sample_id), val(gzip), val(input), val(group) from rRNA_reads
file index from rRNA_index.collect()
output:
set val(sample_name), file("*.fastq.gz"), val(reads_single_end), val(sample_id), val(gzip), val(input), val(group) into tophat2_reads, hisat2_reads, bwa_reads, star_reads
file "*_summary.txt" into rRNA_log
when:
params.rRNA_fasta && !params.skip_filterrRNA
script:
gzip = true
index_base = index[0].toString() - ~/(\.exon)?(\.\d)?(\.fa)?(\.gtf)?(\.ht2)?$/
if (reads_single_end) {
"""
hisat2 --summary-file ${sample_name}_rRNA_summary.txt \
--no-spliced-alignment --no-softclip --norc --no-unal \
-p ${task.cpus} --dta --un-gz ${sample_id}.fastq.gz \
-x $index_base \
-U $reads | \
samtools view -@ ${task.cpus} -Shub - | \
samtools sort -@ ${task.cpus} -o ${sample_name}_rRNA_sort.bam -
"""
} else {
"""
hisat2 --summary-file ${sample_name}_rRNA_summary.txt \
--no-spliced-alignment --no-softclip --norc --no-unal \
-p ${task.cpus} --dta --un-conc-gz ${sample_name}_fastq.gz \
-x $index_base \
-1 ${reads[0]} -2 ${reads[1]} | \
samtools view -@ ${task.cpus} -Shub - | \
samtools sort -@ ${task.cpus} -o ${sample_name}_rRNA_sort.bam -
mv ${sample_name}_fastq.1.gz ${sample_name}_1.fastq.gz
mv ${sample_name}_fastq.2.gz ${sample_name}_2.fastq.gz
"""
}
}
}else{
fastp_reads.into{tophat2_reads; hisat2_reads; bwa_reads; star_reads}
}
process Tophat2Align {
label 'aligners'
tag "$sample_name"
publishDir "${params.outdir}/alignment/tophat2", mode: 'link', overwrite: true
input:
set val(sample_name), file(reads), val(reads_single_end), val(sample_id), val(gzip), val(input), val(group) from tophat2_reads
file index from tophat2_index.collect()
file gtf
output:
set val(sample_id), file("*_tophat2.bam"), val(reads_single_end), val(gzip), val(input), val(group) into tophat2_bam
file "*_log.txt" into tophat2_log
when:
aligner == "tophat2"
script:
index_base = index[0].toString() - ~/(\.rev)?(\.\d)?(\.fa)?(\.bt2)?$/
strand_info = params.stranded == "no" ? "fr-unstranded" : params.stranded == "reverse" ? "fr-secondstrand" : "fr-firststrand"
if (reads_single_end) {
"""
tophat -p ${task.cpus} \
-G $gtf \
-o $sample_name \
--no-novel-juncs \
--library-type $strand_info \
$index_base \
$reads > ${sample_name}_log.txt
mv $sample_name/accepted_hits.bam ${sample_name}_tophat2.bam
"""
} else {
"""
tophat -p ${task.cpus} \
-G $gtf \
-o $sample_name \
--no-novel-juncs \
--library-type $strand_info \
$index_base \
${reads[0]} ${reads[1]} > ${sample_name}_log.txt
mv $sample_name/accepted_hits.bam ${sample_name}_tophat2.bam
"""
}
}
process Hisat2Align {
label 'aligners'
tag "$sample_name"
publishDir "${params.outdir}/alignment/hisat2", mode: 'link', overwrite: true
input:
set val(sample_name), file(reads), val(reads_single_end), val(sample_id), val(gzip), val(input), val(group) from hisat2_reads
file index from hisat2_index.collect()
output:
set val(sample_id), file("*_hisat2.bam"), val(reads_single_end), val(gzip), val(input), val(group) into hisat2_bam
file "*_summary.txt" into hisat2_log
when:
aligner == "hisat2"
script:
index_base = index[0].toString() - ~/(\.exon)?(\.\d)?(\.fa)?(\.gtf)?(\.ht2)?$/
if (reads_single_end) {
"""
hisat2 --summary-file ${sample_name}_hisat2_summary.txt\
-p ${task.cpus} --dta \
-x $index_base \
-U $reads | \
samtools view -@ ${task.cpus} -hbS - > ${sample_name}_hisat2.bam
"""
} else {
"""
hisat2 --summary-file ${sample_name}_hisat2_summary.txt \
-p ${task.cpus} --dta \
-x $index_base \
-1 ${reads[0]} -2 ${reads[1]} | \
samtools view -@ ${task.cpus} -hbS - > ${sample_name}_hisat2.bam
"""
}
}
process BWAAlign{
label 'aligners'
tag "$sample_name"
publishDir "${params.outdir}/alignment/bwa", mode: 'link', overwrite: true
input:
set val(sample_name), file(reads), val(reads_single_end), val(sample_id), val(gzip), val(input), val(group) from bwa_reads
file index from bwa_index.collect()
output:
set val(sample_id), file("*_bwa.bam"), val(reads_single_end), val(gzip), val(input), val(group) into bwa_bam
file "*" into bwa_result
when:
aligner == "bwa"
script:
index_base = index[0].toString() - ~/(\.pac)?(\.bwt)?(\.ann)?(\.amb)?(\.sa)?(\.fa)?$/
if (reads_single_end) {
"""
bwa aln -t ${task.cpus} \
-f ${reads.baseName}.sai \
$index_base \
$reads
bwa samse \
$index_base \
${reads.baseName}.sai \
$reads | \
samtools view -@ ${task.cpus} -h -bS - > ${sample_name}_bwa.bam
"""
} else {
"""
bwa aln -t ${task.cpus} \
-f ${reads[0].baseName}.sai \
$index_base \
${reads[0]}
bwa aln -t ${task.cpus} \
-f ${reads[1].baseName}.sai \
$index_base \
${reads[1]}
bwa sampe \
$index_base \
${reads[0].baseName}.sai ${reads[1].baseName}.sai \
${reads[0]} ${reads[1]} | \
samtools view -@ ${task.cpus} -h -bS - > ${sample_name}_bwa.bam
"""
}
}
process StarAlign {
label 'aligners'
tag "$sample_name"
publishDir "${params.outdir}/alignment/star", mode: 'link', overwrite: true
input:
set val(sample_name), file(reads), val(reads_single_end), val(sample_id), val(gzip), val(input), val(group) from star_reads
file star_index from star_index.collect()
output:
set val(sample_id), file("*_star.bam"), val(reads_single_end), val(gzip), val(input), val(group) into star_bam
file "*.final.out" into star_log
when:
aligner == "star"
script:
gzip_cmd = gzip ? "--readFilesCommand zcat" : ""
if (reads_single_end) {
"""
STAR --runThreadN ${task.cpus} $gzip_cmd \
--twopassMode Basic \
--genomeDir $star_index \
--readFilesIn $reads \
--outSAMtype BAM Unsorted \
--alignSJoverhangMin 8 --alignSJDBoverhangMin 1 \
--outFilterIntronMotifs RemoveNoncanonical \
--outFilterMultimapNmax 20 \
--alignIntronMin 20 \
--alignIntronMax 100000 \
--alignMatesGapMax 1000000 \
--outFileNamePrefix ${sample_name} > ${sample_name}_log.txt
mv ${sample_name}Aligned.out.bam ${sample_name}_star.bam
"""
} else {
"""
STAR --runThreadN ${task.cpus} $gzip_cmd \
--twopassMode Basic \
--genomeDir $star_index \
--readFilesIn ${reads[0]} ${reads[1]} \
--outSAMtype BAM Unsorted \
--alignSJoverhangMin 8 --alignSJDBoverhangMin 1 \
--outFilterIntronMotifs RemoveNoncanonical \
--outFilterMultimapNmax 20 \
--alignIntronMin 20 \
--alignIntronMax 1000000 \
--alignMatesGapMax 1000000 \
--outFileNamePrefix ${sample_name} > ${sample_name}_log.txt
mv ${sample_name}Aligned.out.bam ${sample_name}_star.bam
"""
}
}
/*
========================================================================================
Step 3 Sort BAM file AND QC
========================================================================================
*/
Channel
.from()
.concat(tophat2_bam, hisat2_bam, bwa_bam, star_bam, raw_bam)
.set{ merge_bam_file }
/*
* STEP 3-1 - Sort BAM file
*/
process SortRename {
label 'sort'
tag "$sample_name"
publishDir "${params.outdir}/alignment/samtoolsSort/", mode: 'link', overwrite: true
input:
set val(sample_id), file(bam_file), val(reads_single_end), val(gzip), val(input), val(group) from merge_bam_file
output:
set val(group), val(sample_id), file("*.bam"), file("*.bai") into sorted_bam
file "*.{bam,bai}" into rseqc_bam, bedgraph_bam, feacount_bam, cuffbam, peakquan_bam, diffpeak_bam, sng_bam
file "*.bam" into bam_results
script:
sample_name = sample_id + (input ? ".input_" : ".ip_") + group
output = sample_name + ".bam"
mapq_cutoff = (params.mapq_cutoff).toInteger()
if (!params.skip_sort){
"""
if [ "$mapq_cutoff" -gt "0" ]; then
samtools view -hbq $mapq_cutoff $bam_file | samtools sort -@ ${task.cpus} -O BAM -o $output -
else
samtools sort -@ ${task.cpus} -O BAM -o $output $bam_file
fi
samtools index -@ ${task.cpus} $output
"""
} else {
"""
if [ "$mapq_cutoff" -gt "0" ]; then
samtools view -hbq $mapq_cutoff $bam_file > $output
else
mv $bam_file $output
fi
samtools index -@ ${task.cpus} $output
"""
}
}
/*
* STEP 3-2 - RSeQC analysis
*/
process RSeQC {
tag "$output"
publishDir "${params.outdir}/QC/rseqc" , mode: 'link', overwrite: true,
saveAs: {filename ->
if (filename.indexOf("bam_stat.txt") > 0) "bam_stat/$filename"
else if (filename.indexOf("infer_experiment.txt") > 0) "infer_experiment/$filename"
else if (filename.indexOf("read_distribution.txt") > 0) "read_distribution/$filename"
else if (filename.indexOf("read_duplication.DupRate_plot.pdf") > 0) "read_duplication/$filename"
else if (filename.indexOf("read_duplication.DupRate_plot.r") > 0) "read_duplication/rscripts/$filename"
else if (filename.indexOf("read_duplication.pos.DupRate.xls") > 0) "read_duplication/dup_pos/$filename"
else if (filename.indexOf("read_duplication.seq.DupRate.xls") > 0) "read_duplication/dup_seq/$filename"
else if (filename.indexOf("inner_distance.txt") > 0) "inner_distance/$filename"
else if (filename.indexOf("inner_distance_freq.txt") > 0) "inner_distance/data/$filename"
else if (filename.indexOf("inner_distance_plot.r") > 0) "inner_distance/rscripts/$filename"
else if (filename.indexOf("inner_distance_plot.pdf") > 0) "inner_distance/plots/$filename"
else if (filename.indexOf("junction_plot.r") > 0) "junction_annotation/rscripts/$filename"
else if (filename.indexOf("junction.xls") > 0) "junction_annotation/data/$filename"
else if (filename.indexOf("splice_events.pdf") > 0) "junction_annotation/events/$filename"
else if (filename.indexOf("splice_junction.pdf") > 0) "junction_annotation/junctions/$filename"
else if (filename.indexOf("junctionSaturation_plot.pdf") > 0) "junction_saturation/$filename"
else if (filename.indexOf("junctionSaturation_plot.r") > 0) "junction_saturation/rscripts/$filename"
else filename
}
when:
!params.skip_qc && !params.skip_rseqc
input:
file bam_file from rseqc_bam
file bed12 from bed12file.collect()
output:
file "*" into rseqc_results
file "*.bam_stat.txt" into bam_stat_for_normlization
script:
output = bam_file[0].toString() - ~/(\.bam)?$/