forked from wan230114/MeRIPseqPipe-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.nf
1941 lines (1698 loc) · 77.4 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:An integrated analysis pipeline for MeRIPseq data based on Nextflow.
#### Homepage / Documentation
https://github.com/canceromics/MeRIPseqPipe
----------------------------------------------------------------------------------------
*/
/*
* Authors:
* Bao Xiaoqiong <baoxq@sysucc.org.cn>
* Zhu Kaiyu <zhuky5@mail2.sysu.edu.cn>:
* Qi Zhao <zhaoqi@sysucc.org.cn>;
*/
/*
requirement:
- FastQC/fastp
- STAR/HISAT2/TopHat2/BWA
- SAMtools/RseQC
- MeTPeak/MACS2/MATK/Meyer
- RobustRankAggreg/MSPC/BEDTools
- featureCounts/DESeq2/EdgeR
- QNB
- HMOER
- igvtools
*/
def helpMessage() {
log.info"""
Usage:
The typical command for running the pipeline is as follows:
nextflow run path/to/MeRIPseqPipe --designfile 'path/to/designfile.tsv' --comparefile 'path/to/compare.txt' -profile <docker/test/conda> -resume
OR,
nextflow path/to/MeRIPseqPipe/main.nf -c path/to/MeRIPseqPipe/nextflow.config --designfile 'path/to/designfile/designfile.tsv' --comparefile 'path/to/comparefile/compare.txt' -profile <docker/test/conda> -resume
Mandatory arguments:
--designfile .tsv format(table splited by tabs): Sample_ID, input_R1, input_R2, ip_R1, ip_R2, Group_ID
--comparefile .txt format: control_vs_treated;
"false" for projects without differential analysis and "two_groups" for only two groups in the designfile
-profile Configuration files can contain the definition of one or more profiles.
Available: conda, docker, 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
Index:
--rRNA_fasta Path to HISAT2 rRNA fasta reference
--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/*'
Main parameters of analysis mode:
--stranded "yes" OR "no" OR "reverse"
--mapq_cutoff [0-255] for filtering reads of different mapping quality
--featurecount_minMQS Integer giving the minimum mapping quality score a read must satisfy in order to be counted.
--motiflength length for HOMER motif searching
--delfc the threshold values of differential gene filtering
--dmlfc the threshold values of differential peak filtering
--cluster_method Hierarchical clustering method
--aligners "star" OR "bwa" OR "tophat2" OR "hisat2" OR "none","none" for bam files
--expression_analysis_mode "DESeq2" OR "edgeR" OR "none"
--peakCalling_mode "group" OR "independence" for MATK and MeTPeak
--peakMerged_mode "rank" OR "macs2" OR "MATK" OR "metpeak" OR "mspc"
--methylation_analysis_mode "MATK" OR "QNB" OR "Wilcox-test" OR "edgeR" OR "DESeq2"
Process skipping options:
--skip_fastp Skip fastp
--skip_fastqc Skip FastQC
--skip_rseqc Skip RSeQC
--skip_filterrRNA Skip the process of rRNA cleaning before mapping
--skip_qc Skip all Quality Control steps
--skip_edger Skip the EdgeR process of differential expression analysis steps
--skip_deseq2 Skip the DESeq2 process of differential expression analysis steps
--skip_sort Skip the process of sorting BAM files
--skip_expression Skip all Differential expression analysis
--skip_peakCalling Skip all Peak Calling steps
--skip_diffpeakCalling Skip all Differential methylation analysis
--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_meyer Skip the Meyer process of Peak Calling steps
--skip_QNB Skip the QNB process of Differential methylation analysis
--skip_diffmatk Skip the MATK process of Differential methylation analysis
--skip_annotation Skip the process of peak annotation
--skip_motif Skip the process of motif searching
--skip_m6Aprediction Skip the process of m6A site prediction
--skip_createbedgraph Skip the process of making bedgraph format files and creatIGVjs
Other options:
--outdir The output directory where the results will be saved, defalut = $baseDir/results
--help To show the help message
-name Name for the pipeline run. If not specified, Nextflow will automatically generate a random mnemonic.
""".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(", ")}"
}
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
}
//check fasta files
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!")
}
//check gtf files
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!")
}
//check rRNA fasta files
if ( params.rRNA_fasta ){
rRNA_fasta = file(params.rRNA_fasta, checkIfExists: true)
if( !rRNA_fasta.exists() ) exit 1, LikeletUtils.print_red("rRNA fasta file not found: ${params.rRNA_fasta}")
}else{
rRNA_fasta = Channel.from("")
}
//check comparefile
if( params.comparefile == "two_groups" ){
comparefile = false
compareLines = Channel.from("two_groups")
}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_expression = false
}else if( params.expression_analysis_mode == "DESeq2" ){
params.skip_edger = true
params.skip_deseq2 = false
params.skip_expression = false
}else if( params.expression_analysis_mode == "none" ){
params.skip_edger = true
params.skip_deseq2 = 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!")
}
/*
showing the process and files
========================================================================================
*/
// Header log info
println LikeletUtils.sysucc_ascii()
println LikeletUtils.print_purple("============You are running MeRIPseqPipe 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)?$/
"""
infer_experiment.py -i ${bam_file[0]} -r ${bed12} > ${output}.infer_experiment.txt
junction_annotation.py -i ${bam_file[0]} -o ${output}.rseqc -r ${bed12}
bam_stat.py -i ${bam_file[0]} > ${output}.bam_stat.txt
junction_saturation.py -i ${bam_file[0]} -o ${output}.rseqc -r ${bed12} 2> ${output}.junction_annotation_log.txt