forked from nf-core/rnaseq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.nf
1333 lines (1167 loc) · 50.2 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
/*
===============================================================
nf-core/rnaseq
===============================================================
RNA-Seq Analysis Pipeline. Started March 2016.
#### Homepage / Documentation
https://github.com/nf-core/rnaseq
#### Authors
Phil Ewels @ewels <[email protected]>
Rickard Hammarén @Hammarn <[email protected]>
---------------------------------------------------------------
*/
def helpMessage() {
log.info """
=======================================================
,--./,-.
___ __ __ __ ___ /,-._.--~\'
|\\ | |__ __ / ` / \\ |__) |__ } {
| \\| | \\__, \\__/ | \\ |___ \\`-._,-`-,
`._,._,\'
nf-core/rnaseq : RNA-Seq Best Practice
=======================================================
Usage:
The typical command for running the pipeline is as follows:
nextflow run nf-core/rnaseq --reads '*_R{1,2}.fastq.gz' --genome GRCh37 -profile uppmax
Mandatory arguments:
--reads Path to input data (must be surrounded with quotes)
--genome Name of iGenomes reference
-profile Configuration profile to use. uppmax / uppmax_modules / hebbe / docker / aws
Options:
--singleEnd Specifies that the input is single end reads
--aligner Specifies the aligner (STAR or hisat2) [STAR]
Strandedness:
--forward_stranded The library is forward stranded
--reverse_stranded The library is reverse stranded
--unstranded The default behaviour
References If not specified in the configuration file or you wish to overwrite any of the references.
--star_index Path to STAR index
--hisat2_index Path to HiSAT2 index
--fasta Path to Fasta reference
--gtf Path to GTF file
--gff Path to GFF3 file
--bed12 Path to bed12 file
--downloadFasta If no STAR / Fasta reference is supplied, a URL can be supplied to download a Fasta file at the start of the pipeline.
--downloadGTF If no GTF reference is supplied, a URL can be supplied to download a Fasta file at the start of the pipeline.
--saveReference Save the generated reference files the the Results directory.
--saveTrimmed Save trimmed FastQ file intermediates
--saveAlignedIntermediates Save the BAM files from the Aligment step - not done by default
Trimming options
--clip_r1 [int] Instructs Trim Galore to remove bp from the 5' end of read 1 (or single-end reads)
--clip_r2 [int] Instructs Trim Galore to remove bp from the 5' end of read 2 (paired-end reads only)
--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
--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
Presets:
--pico Sets trimming and standedness settings for the SMARTer Stranded Total RNA-Seq Kit - Pico Input kit. Equivalent to: --forward_stranded --clip_r1 3 --three_prime_clip_r2 3
Other options:
--outdir The output directory where the results will be saved
-w/--work-dir The temporary directory where intermediate data 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
--sampleLevel Used to turn of the edgeR MDS and heatmap. Set automatically when running on fewer than 3 samples
--clusterOptions Extra SLURM options, used in conjunction with Uppmax.config
--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.
--seqCenter Add sequencing center in @RG line of output BAM header
QC options:
--skip_qc Skip all QC steps apart from MultiQC
--skip_fastqc Skip FastQC
--skip_rseqc Skip RSeQC
--skip_kallisto Skip kallisto
--skip_featurecounts Skip featureCounts
--skip_stringtie Skip stringtie
--skip_genebody_coverage Skip calculating genebody coverage [TRUE]
--skip_preseq Skip Preseq
--skip_dupradar Skip dupRadar (and Picard MarkDups)
--skip_edger Skip edgeR MDS plot and heatmap
--skip_multiqc Skip MultiQC
""".stripIndent()
}
/*
* SET UP CONFIGURATION VARIABLES
*/
// Show help emssage
params.help = false
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(", ")}"
}
// Configurable variables
params.name = false
params.project = false
params.genome = false
params.star_index = params.genome ? params.genomes[ params.genome ].star ?: false : false
params.fasta = params.genome ? params.genomes[ params.genome ].fasta ?: false : false
params.kallisto_index = params.genome ? params.genomes[ params.genome ].kallisto ?: false : false
params.gtf = params.genome ? params.genomes[ params.genome ].gtf ?: false : false
params.gff = params.genome ? params.genomes[ params.genome ].gff ?: 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
params.email = false
params.plaintext_email = false
params.seqCenter = false
params.skip_qc = false
params.skip_fastqc = false
params.skip_kallisto = false
params.skip_featurecounts = false
params.skip_stringtie = false
params.skip_rseqc = false
params.skip_genebody_coverage = true
params.skip_preseq = false
params.skip_dupradar = false
params.skip_edger = false
params.skip_multiqc = false
mdsplot_header = file("$baseDir/assets/mdsplot_header.txt")
heatmap_header = file("$baseDir/assets/heatmap_header.txt")
biotypes_header = file("$baseDir/assets/biotypes_header.txt")
multiqc_config = file(params.multiqc_config)
output_docs = file("$baseDir/docs/output.md")
wherearemyfiles = file("$baseDir/assets/where_are_my_files.txt")
// Define regular variables so that they can be overwritten
clip_r1 = params.clip_r1
clip_r2 = params.clip_r2
three_prime_clip_r1 = params.three_prime_clip_r1
three_prime_clip_r2 = params.three_prime_clip_r2
forward_stranded = params.forward_stranded
reverse_stranded = params.reverse_stranded
unstranded = params.unstranded
// Preset trimming options
params.pico = false
if (params.pico){
clip_r1 = 3
clip_r2 = 0
three_prime_clip_r1 = 0
three_prime_clip_r2 = 3
forward_stranded = true
reverse_stranded = false
unstranded = false
}
// Validate inputs
if (params.aligner != 'star' && params.aligner != 'hisat2'){
exit 1, "Invalid aligner option: ${params.aligner}. Valid options: 'star', 'hisat2'"
}
if( params.kallisto_index ){
kallisto_index = Channel
.fromPath(params.kallisto_index)
.ifEmpty { exit 1, "Kallisto index not found: ${params.kallisto_index}" }
}
if( params.star_index && params.aligner == 'star' ){
star_index = Channel
.fromPath(params.star_index)
.ifEmpty { exit 1, "STAR index not found: ${params.star_index}" }
}
else if ( params.hisat2_index && params.aligner == 'hisat2' ){
hs2_indices = Channel
.fromPath("${params.hisat2_index}*")
.ifEmpty { exit 1, "HISAT2 index not found: ${params.hisat2_index}" }
}
else if ( params.fasta ){
fasta = file(params.fasta)
if( !fasta.exists() ) exit 1, "Fasta file not found: ${params.fasta}"
}
else {
exit 1, "No reference genome specified!"
}
if( params.gtf ){
Channel
.fromPath(params.gtf)
.ifEmpty { exit 1, "GTF annotation file not found: ${params.gtf}" }
.into { gtf_makeSTARindex; gtf_makeHisatSplicesites; gtf_makeHISATindex; gtf_makeBED12;
gtf_star; gtf_dupradar; gtf_featureCounts; gtf_stringtieFPKM }
} else if( params.gff ){
gffFile = Channel.fromPath(params.gff)
.ifEmpty { exit 1, "GFF annotation file not found: ${params.gff}" }
} else {
exit 1, "No GTF or GFF3 annotation specified!"
}
if( params.bed12 ){
bed12 = Channel
.fromPath(params.bed12)
.ifEmpty { exit 1, "BED12 annotation file not found: ${params.bed12}" }
.into {bed_rseqc; bed_genebody_coverage}
}
if( params.aligner == 'hisat2' && params.splicesites ){
Channel
.fromPath(params.bed12)
.ifEmpty { exit 1, "HISAT2 splice sites file not found: $alignment_splicesites" }
.into { indexing_splicesites; alignment_splicesites }
}
if( workflow.profile == 'uppmax' || workflow.profile == 'uppmax-devel' ){
if ( !params.project ) exit 1, "No UPPMAX project ID found! Use --project"
}
//AWSBatch sanity checking
if(workflow.profile == 'awsbatch'){
if (!params.awsqueue || !params.awsregion) exit 1, "Specify correct --awsqueue and --awsregion parameters on AWSBatch!"
if (!workflow.workDir.startsWith('s3') || !params.outdir.startsWith('s3')) exit 1, "Specify S3 URLs for workDir and outdir parameters on AWSBatch!"
}
// 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
}
/*
* Create a channel for input read files
*/
if(params.readPaths){
if(params.singleEnd){
Channel
.from(params.readPaths)
.map { row -> [ row[0], [file(row[1][0])]] }
.ifEmpty { exit 1, "params.readPaths was empty - no input files supplied" }
.into { raw_reads_fastqc; raw_reads_trimgalore; }
} else {
Channel
.from(params.readPaths)
.map { row -> [ row[0], [file(row[1][0]), file(row[1][1])]] }
.ifEmpty { exit 1, "params.readPaths was empty - no input files supplied" }
.into { raw_reads_fastqc; raw_reads_trimgalore; }
}
} else {
Channel
.fromFilePairs( params.reads, size: params.singleEnd ? 1 : 2 )
.ifEmpty { exit 1, "Cannot find any reads matching: ${params.reads}\nNB: Path needs to be enclosed in quotes!\nNB: Path requires at least one * wildcard!\nIf this is single-end data, please specify --singleEnd on the command line." }
.into { raw_reads_fastqc; raw_reads_trimgalore; }
}
log.info """=======================================================
,--./,-.
___ __ __ __ ___ /,-._.--~\'
|\\ | |__ __ / ` / \\ |__) |__ } {
| \\| | \\__, \\__/ | \\ |___ \\`-._,-`-,
`._,._,\'
nf-core/rnaseq : RNA-Seq Best Practice
======================================================="""
def summary = [:]
summary['Run Name'] = custom_runName ?: workflow.runName
summary['Reads'] = params.reads
summary['Data Type'] = params.singleEnd ? 'Single-End' : 'Paired-End'
summary['Genome'] = params.genome
if( params.pico ) summary['Library Prep'] = "SMARTer Stranded Total RNA-Seq Kit - Pico Input"
summary['Strandedness'] = ( unstranded ? 'None' : forward_stranded ? 'Forward' : reverse_stranded ? 'Reverse' : 'None' )
summary['Trim R1'] = clip_r1
summary['Trim R2'] = clip_r2
summary["Trim 3' R1"] = three_prime_clip_r1
summary["Trim 3' R2"] = three_prime_clip_r2
if(params.aligner == 'star'){
summary['Aligner'] = "STAR"
if(params.star_index) summary['STAR Index'] = params.star_index
else if(params.fasta) summary['Fasta Ref'] = params.fasta
} else if(params.aligner == 'hisat2') {
summary['Aligner'] = "HISAT2"
if(params.hisat2_index) summary['HISAT2 Index'] = params.hisat2_index
else if(params.fasta) summary['Fasta Ref'] = params.fasta
if(params.splicesites) summary['Splice Sites'] = params.splicesites
}
if(params.kallisto_index) summary['Kallisto Index'] = params.kallisto_index
if(params.gtf) summary['GTF Annotation'] = params.gtf
if(params.gff) summary['GFF3 Annotation'] = params.gff
if(params.bed12) summary['BED Annotation'] = params.bed12
summary['Save Reference'] = params.saveReference ? 'Yes' : 'No'
summary['Save Trimmed'] = params.saveTrimmed ? 'Yes' : 'No'
summary['Save Intermeds'] = params.saveAlignedIntermediates ? 'Yes' : 'No'
summary['Max Memory'] = params.max_memory
summary['Max CPUs'] = params.max_cpus
summary['Max Time'] = params.max_time
summary['Output dir'] = params.outdir
summary['Working dir'] = workflow.workDir
summary['Container'] = workflow.container
if(workflow.revision) summary['Pipeline Release'] = workflow.revision
summary['Current home'] = "$HOME"
summary['Current user'] = "$USER"
summary['Current path'] = "$PWD"
summary['Script dir'] = workflow.projectDir
summary['Config Profile'] = workflow.profile
if(params.project) summary['UPPMAX Project'] = params.project
if(params.email) {
summary['E-mail Address'] = params.email
summary['MultiQC maxsize'] = params.maxMultiqcEmailFileSize
}
log.info summary.collect { k,v -> "${k.padRight(15)}: $v" }.join("\n")
log.info "========================================="
// Show a big error message if we're running on the base config and an uppmax cluster
if( workflow.profile == 'standard'){
if ( "hostname".execute().text.contains('.uppmax.uu.se') ) {
log.error "====================================================\n" +
" WARNING! You are running with the default 'standard'\n" +
" pipeline config profile, which runs on the head node\n" +
" and assumes all software is on the PATH.\n" +
" ALL JOBS ARE RUNNING LOCALLY and stuff will probably break.\n" +
" Please use `-profile uppmax` to run on UPPMAX clusters.\n" +
"============================================================"
}
}
/*
* PREPROCESSING - Build STAR index
*/
if(params.aligner == 'star' && !params.star_index && fasta){
process makeSTARindex {
tag fasta
publishDir path: { params.saveReference ? "${params.outdir}/reference_genome" : params.outdir },
saveAs: { params.saveReference ? it : null }, mode: 'copy'
input:
file fasta from fasta
file gtf from gtf_makeSTARindex
output:
file "star" into star_index
script:
def avail_mem = task.memory ? "--limitGenomeGenerateRAM ${task.memory.toBytes() - 100000000}" : ''
"""
mkdir star
STAR \\
--runMode genomeGenerate \\
--runThreadN ${task.cpus} \\
--sjdbGTFfile $gtf \\
--genomeDir star/ \\
--genomeFastaFiles $fasta \\
$avail_mem
"""
}
}
/*
* PREPROCESSING - Build HISAT2 splice sites file
*/
if(params.aligner == 'hisat2' && !params.splicesites){
process makeHisatSplicesites {
tag "$gtf"
publishDir path: { params.saveReference ? "${params.outdir}/reference_genome" : params.outdir },
saveAs: { params.saveReference ? it : null }, mode: 'copy'
input:
file gtf from gtf_makeHisatSplicesites
output:
file "${gtf.baseName}.hisat2_splice_sites.txt" into indexing_splicesites, alignment_splicesites
script:
"""
hisat2_extract_splice_sites.py $gtf > ${gtf.baseName}.hisat2_splice_sites.txt
"""
}
}
/*
* PREPROCESSING - Build HISAT2 index
*/
if(params.aligner == 'hisat2' && !params.hisat2_index && fasta){
process makeHISATindex {
tag "$fasta"
publishDir path: { params.saveReference ? "${params.outdir}/reference_genome" : params.outdir },
saveAs: { params.saveReference ? it : null }, mode: 'copy'
input:
file fasta from fasta
file indexing_splicesites from indexing_splicesites
file gtf from gtf_makeHISATindex
output:
file "${fasta.baseName}.*.ht2" into hs2_indices
script:
if( !task.memory ){
log.info "[HISAT2 index build] Available memory not known - defaulting to 0. Specify process memory requirements to change this."
avail_mem = 0
} else {
log.info "[HISAT2 index build] Available memory: ${task.memory}"
avail_mem = task.memory.toGiga()
}
if( avail_mem > params.hisatBuildMemory ){
log.info "[HISAT2 index build] Over ${params.hisatBuildMemory} GB available, so using splice sites and exons in HISAT2 index"
extract_exons = "hisat2_extract_exons.py $gtf > ${gtf.baseName}.hisat2_exons.txt"
ss = "--ss $indexing_splicesites"
exon = "--exon ${gtf.baseName}.hisat2_exons.txt"
} else {
log.info "[HISAT2 index build] Less than ${params.hisatBuildMemory} GB available, so NOT using splice sites and exons in HISAT2 index."
log.info "[HISAT2 index build] Use --hisatBuildMemory [small number] to skip this check."
extract_exons = ''
ss = ''
exon = ''
}
"""
$extract_exons
hisat2-build -p ${task.cpus} $ss $exon $fasta ${fasta.baseName}.hisat2_index
"""
}
}
/*
* PREPROCESSING - Convert GFF3 to GTF
*/
if(params.gff){
process convertGFFtoGTF {
tag "$gff"
input:
file gff from gffFile
output:
file "${gff.baseName}.gtf" into gtf_makeSTARindex, gtf_makeHisatSplicesites, gtf_makeHISATindex, gtf_makeBED12,
gtf_star, gtf_dupradar, gtf_featureCounts, gtf_stringtieFPKM
script:
"""
gffread $gff -T -o > ${gff.baseName}.gtf
"""
}
}
/*
* PREPROCESSING - Build BED12 file
*/
if(!params.bed12){
process makeBED12 {
tag "$gtf"
publishDir path: { params.saveReference ? "${params.outdir}/reference_genome" : params.outdir },
saveAs: { params.saveReference ? it : null }, mode: 'copy'
input:
file gtf from gtf_makeBED12
output:
file "${gtf.baseName}.bed" into bed_rseqc, bed_genebody_coverage
script: // This script is bundled with the pipeline, in nfcore/rnaseq/bin/
"""
gtf2bed $gtf > ${gtf.baseName}.bed
"""
}
}
/*
* STEP 1 - FastQC
*/
process fastqc {
tag "$name"
publishDir "${params.outdir}/fastqc", mode: 'copy',
saveAs: {filename -> filename.indexOf(".zip") > 0 ? "zips/$filename" : "$filename"}
when:
!params.skip_qc && !params.skip_fastqc
input:
set val(name), file(reads) from raw_reads_fastqc
output:
file "*_fastqc.{zip,html}" into fastqc_results
script:
"""
fastqc -q $reads
"""
}
/*
* STEP 2 - Trim Galore!
*/
process trim_galore {
tag "$name"
publishDir "${params.outdir}/trim_galore", mode: 'copy',
saveAs: {filename ->
if (filename.indexOf("_fastqc") > 0) "FastQC/$filename"
else if (filename.indexOf("trimming_report.txt") > 0) "logs/$filename"
else if (!params.saveTrimmed && filename == "where_are_my_files.txt") filename
else if (params.saveTrimmed && filename != "where_are_my_files.txt") filename
else null
}
input:
set val(name), file(reads) from raw_reads_trimgalore
file wherearemyfiles
output:
file "*fq.gz" into trimmed_reads, trimmed_reads_kallisto
file "*trimming_report.txt" into trimgalore_results
file "*_fastqc.{zip,html}" into trimgalore_fastqc_reports
file "where_are_my_files.txt"
script:
c_r1 = clip_r1 > 0 ? "--clip_r1 ${clip_r1}" : ''
c_r2 = clip_r2 > 0 ? "--clip_r2 ${clip_r2}" : ''
tpc_r1 = three_prime_clip_r1 > 0 ? "--three_prime_clip_r1 ${three_prime_clip_r1}" : ''
tpc_r2 = three_prime_clip_r2 > 0 ? "--three_prime_clip_r2 ${three_prime_clip_r2}" : ''
if (params.singleEnd) {
"""
trim_galore --fastqc --gzip $c_r1 $tpc_r1 $reads
"""
} else {
"""
trim_galore --paired --fastqc --gzip $c_r1 $c_r2 $tpc_r1 $tpc_r2 $reads
"""
}
}
/*
* STEP 2.5 - align with kallisto
*/
process kallisto {
tag "$prefix"
publishDir "${params.outdir}/kallisto", mode: 'copy'
when:
!params.skip_kallisto
input:
file reads from trimmed_reads_kallisto
file kallisto_index from kallisto_index.collect()
file wherearemyfiles
output:
file '*' into kallisto_results
file "where_are_my_files.txt"
script:
prefix = reads[0].toString() - ~/(_R1)?(_001)?(_trimmed)?(_val_1)?(\.fq)?(\.fastq)?(\.gz)?$/
if (params.singleEnd) {
"""
kallisto quant -i $kallisto_index -o $prefix --single -l 200 -s 20 $reads
"""
} else {
"""
kallisto quant -i $kallisto_index -o $prefix ${reads[0]} ${reads[1]}
"""
}
}
/*
* STEP 3 - align with STAR
*/
// Function that checks the alignment rate of the STAR output
// and returns true if the alignment passed and otherwise false
skipped_poor_alignment = []
def check_log(logs) {
def percent_aligned = 0;
logs.eachLine { line ->
if ((matcher = line =~ /Uniquely mapped reads %\s*\|\s*([\d\.]+)%/)) {
percent_aligned = matcher[0][1]
}
}
logname = logs.getBaseName() - 'Log.final'
if(percent_aligned.toFloat() <= '5'.toFloat() ){
log.info "#################### VERY POOR ALIGNMENT RATE! IGNORING FOR FURTHER DOWNSTREAM ANALYSIS! ($logname) >> ${percent_aligned}% <<"
skipped_poor_alignment << logname
return false
} else {
log.info " Passed alignment > star ($logname) >> ${percent_aligned}% <<"
return true
}
}
if(params.aligner == 'star'){
hisat_stdout = Channel.from(false)
process star {
tag "$prefix"
publishDir "${params.outdir}/STAR", mode: 'copy',
saveAs: {filename ->
if (filename.indexOf(".bam") == -1) "logs/$filename"
else if (!params.saveAlignedIntermediates && filename == "where_are_my_files.txt") filename
else if (params.saveAlignedIntermediates && filename != "where_are_my_files.txt") filename
else null
}
input:
file reads from trimmed_reads
file index from star_index.collect()
file gtf from gtf_star.collect()
file wherearemyfiles
output:
set file("*Log.final.out"), file ('*.bam') into star_aligned
file "*.out" into alignment_logs
file "*SJ.out.tab"
file "*Log.out" into star_log
file "where_are_my_files.txt"
script:
prefix = reads[0].toString() - ~/(_R1)?(_001)?(_trimmed)?(_val_1)?(\.fq)?(\.fastq)?(\.gz)?$/
def avail_mem = task.memory ? "--limitBAMsortRAM ${task.memory.toBytes() - 100000000}" : ''
seqCenter = params.seqCenter ? "--outSAMattrRGline ID:$prefix 'CN:$params.seqCenter'" : ''
"""
STAR --genomeDir $index \\
--sjdbGTFfile $gtf \\
--readFilesIn $reads \\
--runThreadN ${task.cpus} \\
--twopassMode Basic \\
--outWigType bedGraph \\
--outSAMtype BAM SortedByCoordinate $avail_mem \\
--readFilesCommand zcat \\
--runDirPerm All_RWX \\
--outFileNamePrefix $prefix $seqCenter \\
"""
}
// Filter removes all 'aligned' channels that fail the check
star_aligned
.filter { logs, bams -> check_log(logs) }
.flatMap { logs, bams -> bams }
.into { bam_count; bam_rseqc; bam_preseq; bam_markduplicates; bam_featurecounts; bam_stringtieFPKM; bam_for_genebody }
}
/*
* STEP 3 - align with HISAT2
*/
if(params.aligner == 'hisat2'){
star_log = Channel.from(false)
process hisat2Align {
tag "$prefix"
publishDir "${params.outdir}/HISAT2", mode: 'copy',
saveAs: {filename ->
if (filename.indexOf(".hisat2_summary.txt") > 0) "logs/$filename"
else if (!params.saveAlignedIntermediates && filename == "where_are_my_files.txt") filename
else if (params.saveAlignedIntermediates && filename != "where_are_my_files.txt") filename
else null
}
input:
file reads from trimmed_reads
file hs2_indices from hs2_indices.collect()
file alignment_splicesites from alignment_splicesites.collect()
file wherearemyfiles
output:
file "${prefix}.bam" into hisat2_bam
file "${prefix}.hisat2_summary.txt" into alignment_logs
file "where_are_my_files.txt"
script:
index_base = hs2_indices[0].toString() - ~/.\d.ht2/
prefix = reads[0].toString() - ~/(_R1)?(_001)?(_trimmed)?(_val_1)?(\.fq)?(\.fastq)?(\.gz)?$/
seqCenter = params.seqCenter ? "--rg-id ${prefix} --rg CN:${params.seqCenter.replaceAll('\\s','_')}" : ''
def rnastrandness = ''
if (forward_stranded && !unstranded){
rnastrandness = params.singleEnd ? '--rna-strandness F' : '--rna-strandness FR'
} else if (reverse_stranded && !unstranded){
rnastrandness = params.singleEnd ? '--rna-strandness R' : '--rna-strandness RF'
}
if (params.singleEnd) {
"""
hisat2 -x $index_base \\
-U $reads \\
$rnastrandness \\
--known-splicesite-infile $alignment_splicesites \\
-p ${task.cpus} \\
--met-stderr \\
--new-summary \\
--summary-file ${prefix}.hisat2_summary.txt $seqCenter \\
| samtools view -bS -F 4 -F 256 - > ${prefix}.bam
"""
} else {
"""
hisat2 -x $index_base \\
-1 ${reads[0]} \\
-2 ${reads[1]} \\
$rnastrandness \\
--known-splicesite-infile $alignment_splicesites \\
--no-mixed \\
--no-discordant \\
-p ${task.cpus} \\
--met-stderr \\
--new-summary \\
--summary-file ${prefix}.hisat2_summary.txt $seqCenter \\
| samtools view -bS -F 4 -F 8 -F 256 - > ${prefix}.bam
"""
}
}
process hisat2_sortOutput {
tag "${hisat2_bam.baseName}"
publishDir "${params.outdir}/HISAT2", mode: 'copy',
saveAs: { filename ->
if (!params.saveAlignedIntermediates && filename == "where_are_my_files.txt") filename
else if (params.saveAlignedIntermediates && filename != "where_are_my_files.txt") "aligned_sorted/$filename"
else null
}
input:
file hisat2_bam
file wherearemyfiles
output:
file "${hisat2_bam.baseName}.sorted.bam" into bam_count, bam_rseqc, bam_preseq, bam_markduplicates, bam_featurecounts, bam_stringtieFPKM, bam_for_genebody
file "where_are_my_files.txt"
script:
def avail_mem = task.memory ? "-m ${task.memory.toBytes() / task.cpus}" : ''
"""
samtools sort \\
$hisat2_bam \\
-@ ${task.cpus} $avail_mem \\
-o ${hisat2_bam.baseName}.sorted.bam
"""
}
}
/*
* STEP 4 - RSeQC analysis
*/
process rseqc {
tag "${bam_rseqc.baseName - '.sorted'}"
publishDir "${params.outdir}/rseqc" , mode: 'copy',
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("RPKM_saturation.eRPKM.xls") > 0) "RPKM_saturation/rpkm/$filename"
else if (filename.indexOf("RPKM_saturation.rawCount.xls") > 0) "RPKM_saturation/counts/$filename"
else if (filename.indexOf("RPKM_saturation.saturation.pdf") > 0) "RPKM_saturation/$filename"
else if (filename.indexOf("RPKM_saturation.saturation.r") > 0) "RPKM_saturation/rscripts/$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_rseqc
file bed12 from bed_rseqc.collect()
output:
file "*.{txt,pdf,r,xls}" into rseqc_results
script:
def strandRule = ''
if (forward_stranded && !unstranded){
strandRule = params.singleEnd ? '-d ++,--' : '-d 1++,1--,2+-,2-+'
} else if (reverse_stranded && !unstranded){
strandRule = params.singleEnd ? '-d +-,-+' : '-d 1+-,1-+,2++,2--'
}
"""
samtools index $bam_rseqc
infer_experiment.py -i $bam_rseqc -r $bed12 > ${bam_rseqc.baseName}.infer_experiment.txt
junction_annotation.py -i $bam_rseqc -o ${bam_rseqc.baseName}.rseqc -r $bed12
bam_stat.py -i $bam_rseqc 2> ${bam_rseqc.baseName}.bam_stat.txt
junction_saturation.py -i $bam_rseqc -o ${bam_rseqc.baseName}.rseqc -r $bed12 2> ${bam_rseqc.baseName}.junction_annotation_log.txt
inner_distance.py -i $bam_rseqc -o ${bam_rseqc.baseName}.rseqc -r $bed12
read_distribution.py -i $bam_rseqc -r $bed12 > ${bam_rseqc.baseName}.read_distribution.txt
read_duplication.py -i $bam_rseqc -o ${bam_rseqc.baseName}.read_duplication
"""
}
/*
* Step 4.1 Rseqc create BigWig coverage
*/
process createBigWig {
tag "${bam.baseName - 'sortedByCoord.out'}"
publishDir "${params.outdir}/bigwig", mode: 'copy'
when:
!params.skip_qc && !params.skip_genebody_coverage
input:
file bam from bam_for_genebody
output:
file "*.bigwig" into bigwig_for_genebody
script:
"""
samtools index $bam
bamCoverage -b $bam -p ${task.cpus} -o ${bam.baseName}.bigwig
"""
}
/*
* Step 4.2 Rseqc genebody_coverage
*/
process genebody_coverage {
tag "${bigwig.baseName}"
publishDir "${params.outdir}/rseqc" , mode: 'copy',
saveAs: {filename ->
if (filename.indexOf("geneBodyCoverage.curves.pdf") > 0) "geneBodyCoverage/$filename"
else if (filename.indexOf("geneBodyCoverage.r") > 0) "geneBodyCoverage/rscripts/$filename"
else if (filename.indexOf("geneBodyCoverage.txt") > 0) "geneBodyCoverage/data/$filename"
else if (filename.indexOf("log.txt") > -1) false
else filename
}
when:
!params.skip_qc && !params.skip_genebody_coverage
input:
file bigwig from bigwig_for_genebody
file bed12 from bed_genebody_coverage.collect()
output:
file "*.{txt,pdf,r}" into genebody_coverage_results
script:
"""
geneBody_coverage2.py \\
-i $bigwig \\
-o ${bigwig.baseName}.rseqc.txt \\
-r $bed12
"""
}
/*
* STEP 5 - preseq analysis
*/
process preseq {
tag "${bam_preseq.baseName - '.sorted'}"
publishDir "${params.outdir}/preseq", mode: 'copy'
when:
!params.skip_qc && !params.skip_preseq
input:
file bam_preseq
output:
file "${bam_preseq.baseName}.ccurve.txt" into preseq_results
script:
"""
preseq lc_extrap -v -B $bam_preseq -o ${bam_preseq.baseName}.ccurve.txt
"""
}
/*
* STEP 6 Mark duplicates
*/
process markDuplicates {
tag "${bam.baseName - '.sorted'}"
publishDir "${params.outdir}/markDuplicates", mode: 'copy',
saveAs: {filename -> filename.indexOf("_metrics.txt") > 0 ? "metrics/$filename" : "$filename"}
when:
!params.skip_qc && !params.skip_dupradar
input:
file bam from bam_markduplicates
output:
file "${bam.baseName}.markDups.bam" into bam_md
file "${bam.baseName}.markDups_metrics.txt" into picard_results
file "${bam.baseName}.markDups.bam.bai"
script:
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()
}
"""
picard MarkDuplicates \\
TMP_DIR=tmp \\
INPUT=$bam \\
OUTPUT=${bam.baseName}.markDups.bam \\
METRICS_FILE=${bam.baseName}.markDups_metrics.txt \\
REMOVE_DUPLICATES=false \\
ASSUME_SORTED=true \\
PROGRAM_RECORD_ID='null' \\
VALIDATION_STRINGENCY=LENIENT
samtools index ${bam.baseName}.markDups.bam
"""
}
/*
* STEP 7 - dupRadar
*/
process dupradar {
tag "${bam_md.baseName - '.sorted.markDups'}"
publishDir "${params.outdir}/dupradar", mode: 'copy',
saveAs: {filename ->
if (filename.indexOf("_duprateExpDens.pdf") > 0) "scatter_plots/$filename"
else if (filename.indexOf("_duprateExpBoxplot.pdf") > 0) "box_plots/$filename"
else if (filename.indexOf("_expressionHist.pdf") > 0) "histograms/$filename"
else if (filename.indexOf("_dupMatrix.txt") > 0) "gene_data/$filename"
else if (filename.indexOf("_duprateExpDensCurve.txt") > 0) "scatter_curve_data/$filename"
else if (filename.indexOf("_intercept_slope.txt") > 0) "intercepts_slopes/$filename"
else "$filename"
}
when:
!params.skip_qc && !params.skip_dupradar
input:
file bam_md
file gtf from gtf_dupradar.collect()
output:
file "*.{pdf,txt}" into dupradar_results
script: // This script is bundled with the pipeline, in nfcore/rnaseq/bin/
def dupradar_direction = 0
if (forward_stranded && !unstranded) {
dupradar_direction = 1
} else if (reverse_stranded && !unstranded){
dupradar_direction = 2
}
def paired = params.singleEnd ? 'single' : 'paired'
"""
dupRadar.r $bam_md $gtf $dupradar_direction $paired ${task.cpus}
"""
}
/*
* STEP 8 Feature counts
*/
process featureCounts {
tag "${bam_featurecounts.baseName - '.sorted'}"
publishDir "${params.outdir}/featureCounts", mode: 'copy',
saveAs: {filename ->
if (filename.indexOf("biotype_counts") > 0) "biotype_counts/$filename"
else if (filename.indexOf("_gene.featureCounts.txt.summary") > 0) "gene_count_summaries/$filename"
else if (filename.indexOf("_gene.featureCounts.txt") > 0) "gene_counts/$filename"
else "$filename"
}
when:
!params.skip_featurecounts
input:
file bam_featurecounts
file gtf from gtf_featureCounts.collect()
file biotypes_header
output:
file "${bam_featurecounts.baseName}_gene.featureCounts.txt" into geneCounts, featureCounts_to_merge
file "${bam_featurecounts.baseName}_gene.featureCounts.txt.summary" into featureCounts_logs
file "${bam_featurecounts.baseName}_biotype_counts*mqc.{txt,tsv}" into featureCounts_biotype
script:
def featureCounts_direction = 0
if (forward_stranded && !unstranded) {
featureCounts_direction = 1
} else if (reverse_stranded && !unstranded){
featureCounts_direction = 2
}
// Try to get real sample name
sample_name = bam_featurecounts.baseName - 'Aligned.sortedByCoord.out'
"""
featureCounts -a $gtf -g gene_id -o ${bam_featurecounts.baseName}_gene.featureCounts.txt -p -s $featureCounts_direction $bam_featurecounts
featureCounts -a $gtf -g gene_biotype -o ${bam_featurecounts.baseName}_biotype.featureCounts.txt -p -s $featureCounts_direction $bam_featurecounts
cut -f 1,7 ${bam_featurecounts.baseName}_biotype.featureCounts.txt | tail -n +3 | cat $biotypes_header - >> ${bam_featurecounts.baseName}_biotype_counts_mqc.txt
mqc_features_stat.py ${bam_featurecounts.baseName}_biotype_counts_mqc.txt -s $sample_name -f rRNA -o ${bam_featurecounts.baseName}_biotype_counts_gs_mqc.tsv
"""
}
/*
* STEP 9 - Merge featurecounts
*/
process merge_featureCounts {
tag "${input_files[0].baseName - '.sorted'}"
publishDir "${params.outdir}/featureCounts", mode: 'copy'
input: