-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathmain.nf
1474 lines (1274 loc) · 55.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
/*
========================================================================================
nf-core/nanoseq
========================================================================================
nf-core/nanoseq Analysis Pipeline.
#### Homepage / Documentation
https://github.com/nf-core/nanoseq
----------------------------------------------------------------------------------------
*/
def helpMessage() {
log.info nfcoreHeader()
log.info"""
Usage:
The typical command for running the pipeline is as follows:
nextflow run nf-core/nanoseq \
--input samplesheet.csv \
--protocol DNA \
--input_path ./fast5/ \
--flowcell FLO-MIN106 \
--kit SQK-LSK109 \
--barcode_kit SQK-PBK004 \
-profile docker
Mandatory arguments
--input [file] Comma-separated file containing information about the samples in the experiment (see docs/usage.md)
--protocol [str] Specifies the type of sequencing i.e. "DNA", "cDNA" or "directRNA"
-profile [str] Configuration profile to use. Can use multiple (comma separated)
Available: docker, singularity, test, awsbatch, <institute> and more.
Basecalling/Demultiplexing
--input_path [file] Path to Nanopore run directory (e.g. fastq_pass/) or a basecalled fastq file that requires demultiplexing
--flowcell [str] Flowcell used to perform the sequencing e.g. FLO-MIN106. Not required if '--guppy_config' is specified
--kit [str] Kit used to perform the sequencing e.g. SQK-LSK109. Not required if '--guppy_config' is specified
--barcode_kit [str] Barcode kit used to perform the sequencing e.g. SQK-PBK004
--barcode_both_ends [bool] Require barcode on both ends for Guppy basecaller (Default: false)
--guppy_config [file/str] Guppy config file used for basecalling. Cannot be used in conjunction with '--flowcell' and '--kit'
--guppy_model [file/str] Custom basecalling model file (JSON) to use for Guppy basecalling, such as the output from Taiyaki (Default: false)
--guppy_gpu [bool] Whether to perform basecalling with Guppy in GPU mode (Default: false)
--guppy_gpu_runners [int] Number of '--gpu_runners_per_device' used for Guppy when using '--guppy_gpu' (Default: 6)
--guppy_cpu_threads [int] Number of '--cpu_threads_per_caller' used for Guppy when using '--guppy_gpu' (Default: 1)
--gpu_device [str] Basecalling device specified to Guppy in GPU mode using '--device' (Default: 'auto')
--gpu_cluster_options [str] Cluster options required to use GPU resources (e.g. '--part=gpu --gres=gpu:1')
--qcat_min_score [int] Minimum scores of '--min-score' used for qcat (Default: 60)
--qcat_detect_middle [bool] Search for adapters in the whole read '--detect-middle' used for qcat (Default: false)
--skip_basecalling [bool] Skip basecalling with Guppy (Default: false)
--skip_demultiplexing [bool] Skip demultiplexing with Guppy (Default: false)
Alignment
--aligner [str] Specifies the aligner to use (available are: minimap2 or graphmap2). Both are capable of performing unspliced/spliced alignment (Default: 'minimap2')
--stranded [bool] Specifies if the data is strand-specific. Automatically activated when using '--protocol directRNA' (Default: false)
--save_align_intermeds [bool] Save the '.sam' files from the alignment step (Default: false)
--skip_alignment [bool] Skip alignment and subsequent process (Default: false)
Coverage tracks
--skip_bigwig [bool] Skip BigWig file generation (Default: false)
--skip_bigbed [bool] Skip BigBed file generation (Default: false)
Quantification and differential analysis
--quantification_method [str] Specifies the transcript quantification method to use (available are: bambu or stringtie2). Only available when protocol is cDNA or directRNA.
--skip_quantification [bool] Skip transcript quantification and differential analysis (Default: false)
--skip_differential_analysis [bool] Skip differential analysis with DESeq2 and DEXSeq (Default: false)
QC
--skip_qc [bool] Skip all QC steps apart from MultiQC (Default: false)
--skip_pycoqc [bool] Skip pycoQC (Default: false)
--skip_nanoplot [bool] Skip NanoPlot (Default: false)
--skip_fastqc [bool] Skip FastQC (Default: false)
--skip_multiqc [bool] Skip MultiQC (Default: false)
Other
--outdir [file] The output directory where the results will be saved (Default: '/results')
--publish_dir_mode [str] Mode for publishing results in the output directory. Available: symlink, rellink, link, copy, copyNoFollow, move (Default: copy)
--email [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
--email_on_fail [email] Same as --email, except only send mail if the workflow is not successful (Default: false)
--max_multiqc_email_size [str] 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 [str] Name for the pipeline run. If not specified, Nextflow will automatically generate a random mnemonic.
AWSBatch
--awsqueue [str] The AWSBatch JobQueue that needs to be set when running on AWSBatch
--awsregion [str] The AWS Region for your AWS Batch job to run on (Default: 'eu-west-1')
--awscli [str] Path to the AWS CLI tool
""".stripIndent()
}
// Show help message
if (params.help) {
helpMessage()
exit 0
}
/*
* SET UP CONFIGURATION VARIABLES
*/
if (params.input) { ch_input = file(params.input, checkIfExists: true) } else { exit 1, "Samplesheet file not specified!" }
// Function to check if running offline
def isOffline() {
try {
return NXF_OFFLINE as Boolean
}
catch( Exception e ) {
return false
}
}
def ch_guppy_model = Channel.empty()
def ch_guppy_config = Channel.empty()
if (!params.skip_basecalling) {
// Pre-download test-dataset to get files for '--input_path' parameter
// Nextflow is unable to recursively download directories via HTTPS
if (workflow.profile.contains('test')) {
if (!isOffline()) {
process GET_TEST_DATA {
output:
path "test-datasets/fast5/$barcoded/" into ch_input_path
script:
barcoded = workflow.profile.contains('test_nonbc') ? "nonbarcoded" : "barcoded"
"""
git clone https://github.com/nf-core/test-datasets.git --branch nanoseq --single-branch
"""
}
} else {
exit 1, "NXF_OFFLINE=true or -offline has been set so cannot download and run any test dataset!"
}
} else {
if (params.input_path) { ch_input_path = Channel.fromPath(params.input_path, checkIfExists: true) } else { exit 1, "Please specify a valid run directory to perform basecalling!" }
}
// Need to stage guppy_config properly depending on whether its a file or string
if (!params.guppy_config) {
if (!params.flowcell) { exit 1, "Please specify a valid flowcell identifier for basecalling!" }
if (!params.kit) { exit 1, "Please specify a valid kit identifier for basecalling!" }
} else if (file(params.guppy_config).exists()) {
ch_guppy_config = Channel.fromPath(params.guppy_config)
}
// Need to stage guppy_model properly depending on whether its a file or string
if (params.guppy_model) {
if (file(params.guppy_model).exists()) {
ch_guppy_model = Channel.fromPath(params.guppy_model)
}
}
} else {
if (!params.skip_demultiplexing) {
if (!params.barcode_kit) {
params.barcode_kit = 'Auto'
}
def qcatBarcodeKitList = ['Auto', 'RBK001', 'RBK004', 'NBD103/NBD104',
'NBD114', 'NBD104/NBD114', 'PBC001', 'PBC096',
'RPB004/RLB001', 'PBK004/LWB001', 'RAB204', 'VMK001', 'DUAL']
if (params.barcode_kit && qcatBarcodeKitList.contains(params.barcode_kit)) {
if (params.input_path) { ch_input_path = Channel.fromPath(params.input_path, checkIfExists: true) } else { exit 1, "Please specify a valid input fastq file to perform demultiplexing!" }
} else {
exit 1, "Please provide a barcode kit to demultiplex with qcat. Valid options: ${qcatBarcodeKitList}"
}
}
}
if (!params.skip_alignment) {
if (params.aligner != 'minimap2' && params.aligner != 'graphmap2') {
exit 1, "Invalid aligner option: ${params.aligner}. Valid options: 'minimap2', 'graphmap2'"
}
if (params.protocol != 'DNA' && params.protocol != 'cDNA' && params.protocol != 'directRNA') {
exit 1, "Invalid protocol option: ${params.protocol}. Valid options: 'DNA', 'cDNA', 'directRNA'"
}
}
if (!params.skip_quantification) {
if (params.quantification_method != 'bambu' && params.quantification_method != 'stringtie2') {
exit 1, "Invalid transcript quantification option: ${params.quantification_method}. Valid options: 'bambu', 'stringtie2'"
}
if (params.protocol != 'cDNA' && params.protocol != 'directRNA') {
exit 1, "Invalid protocol option if performing quantification: ${params.protocol}. Valid options: 'cDNA', 'directRNA'"
}
}
// Stage config files
ch_multiqc_config = file("$baseDir/assets/multiqc_config.yaml", checkIfExists: true)
ch_multiqc_custom_config = params.multiqc_config ? Channel.fromPath(params.multiqc_config, checkIfExists: true) : Channel.empty()
ch_output_docs = file("$baseDir/docs/output.md", checkIfExists: true)
ch_output_docs_images = file("$baseDir/docs/images/", checkIfExists: true)
// 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 AWS batch settings
if (workflow.profile.contains('awsbatch')) {
// AWSBatch sanity checking
if (!params.awsqueue || !params.awsregion) exit 1, "Specify correct --awsqueue and --awsregion parameters on AWSBatch!"
// Check outdir paths to be S3 buckets if running on AWSBatch
// related: https://github.com/nextflow-io/nextflow/issues/813
if (!params.outdir.startsWith('s3:')) exit 1, "Outdir not on S3 - specify S3 Bucket to run on AWSBatch!"
// Prevent trace files to be stored on S3 since S3 does not support rolling files.
if (params.tracedir.startsWith('s3:')) exit 1, "Specify a local tracedir or run without trace! S3 cannot be used for tracefiles."
}
// Header log info
log.info nfcoreHeader()
def summary = [:]
if (workflow.revision) summary['Pipeline Release'] = workflow.revision
summary['Run Name'] = custom_runName ?: workflow.runName
summary['Samplesheet'] = params.input
summary['Protocol'] = params.protocol
summary['Stranded'] = (params.stranded || params.protocol == 'directRNA') ? 'Yes' : 'No'
summary['Skip Basecalling'] = params.skip_basecalling ? 'Yes' : 'No'
summary['Skip Demultiplexing'] = params.skip_demultiplexing ? 'Yes' : 'No'
if (!params.skip_basecalling) {
summary['Run Dir'] = params.input_path
summary['Flowcell ID'] = params.flowcell ?: 'Not required'
summary['Kit ID'] = params.kit ?: 'Not required'
summary['Barcode Kit ID'] = params.barcode_kit ?: 'Unspecified'
summary['Barcode Both Ends'] = params.barcode_both_ends ? 'Yes' : 'No'
summary['Guppy Config File'] = params.guppy_config ?: 'Unspecified'
summary['Guppy Model File'] = params.guppy_model ?:'Unspecified'
summary['Guppy GPU Mode'] = params.guppy_gpu ? 'Yes' : 'No'
summary['Guppy GPU Runners'] = params.guppy_gpu_runners
summary['Guppy CPU Threads'] = params.guppy_cpu_threads
summary['Guppy GPU Device'] = params.gpu_device ?: 'Unspecified'
summary['Guppy GPU Options'] = params.gpu_cluster_options ?: 'Unspecified'
}
if (params.skip_basecalling && !params.skip_demultiplexing) {
summary['Input FastQ File'] = params.input_path
summary['Barcode Kit ID'] = params.barcode_kit ?: 'Unspecified'
summary['Qcat Min Score'] = params.qcat_min_score
summary['Qcat Detect Middle'] = params.qcat_detect_middle ? 'Yes': 'No'
}
if (!params.skip_alignment) {
summary['Aligner'] = params.aligner
summary['Save Intermeds'] = params.save_align_intermeds ? 'Yes' : 'No'
}
if (!params.skip_quantification && params.protocol != 'DNA') {
summary['Quantification Method'] = params.quantification_method
summary['Skip Diff Analysis'] = params.skip_differential_analysis
}
if (params.skip_alignment) summary['Skip Alignment'] = 'Yes'
if (params.skip_bigbed) summary['Skip BigBed'] = 'Yes'
if (params.skip_bigwig) summary['Skip BigWig'] = 'Yes'
if (params.skip_qc) summary['Skip QC'] = 'Yes'
if (params.skip_pycoqc) summary['Skip PycoQC'] = 'Yes'
if (params.skip_nanoplot) summary['Skip NanoPlot'] = 'Yes'
if (params.skip_fastqc) summary['Skip FastQC'] = 'Yes'
if (params.skip_multiqc) summary['Skip MultiQC'] = 'Yes'
summary['Max Resources'] = "$params.max_memory memory, $params.max_cpus cpus, $params.max_time time per job"
if (workflow.containerEngine) summary['Container'] = "$workflow.containerEngine - $workflow.container"
summary['Output dir'] = params.outdir
summary['Launch dir'] = workflow.launchDir
summary['Working dir'] = workflow.workDir
summary['Script dir'] = workflow.projectDir
summary['User'] = workflow.userName
if (workflow.profile.contains('awsbatch')) {
summary['AWS Region'] = params.awsregion
summary['AWS Queue'] = params.awsqueue
summary['AWS CLI'] = params.awscli
}
summary['Config Profile'] = workflow.profile
if (params.config_profile_description) summary['Config Profile Description'] = params.config_profile_description
if (params.config_profile_contact) summary['Config Profile Contact'] = params.config_profile_contact
if (params.config_profile_url) summary['Config Profile URL'] = params.config_profile_url
summary['Config Files'] = workflow.configFiles.join(', ')
if (params.email || params.email_on_fail) {
summary['E-mail Address'] = params.email
summary['E-mail on failure'] = params.email_on_fail
summary['MultiQC maxsize'] = params.max_multiqc_email_size
}
log.info summary.collect { k,v -> "${k.padRight(21)}: $v" }.join("\n")
log.info "-\033[2m--------------------------------------------------\033[0m-"
// Check the hostnames against configured profiles
checkHostname()
/*
* Check input samplesheet
*/
process CHECK_SAMPLESHEET {
tag "$samplesheet"
publishDir "${params.outdir}/pipeline_info", mode: params.publish_dir_mode
input:
path samplesheet from ch_input
output:
path "*reformat.csv" into ch_samplesheet_reformat
script: // This script is bundled with the pipeline, in nf-core/nanoseq/bin/
"""
check_samplesheet.py $samplesheet samplesheet_reformat.csv
"""
}
// Function to resolve fasta and gtf file if using iGenomes
// Returns [ sample, input_file, barcode, fasta, gtf, is_transcripts, annotation_str ]
def get_sample_info(LinkedHashMap sample, LinkedHashMap genomeMap) {
// Resolve fasta and gtf file if using iGenomes
def fasta = false
def gtf = false
if (sample.genome) {
if (genomeMap && genomeMap.containsKey(sample.genome)) {
fasta = file(genomeMap[sample.genome].fasta, checkIfExists: true)
gtf = file(genomeMap[sample.genome].gtf, checkIfExists: true)
} else {
fasta = file(sample.genome, checkIfExists: true)
}
}
// Check if input file and gtf file exists
input_file = sample.input_file ? file(sample.input_file, checkIfExists: true) : null
gtf = sample.gtf ? file(sample.gtf, checkIfExists: true) : gtf
return [ sample.sample, input_file, sample.barcode, fasta, gtf, sample.is_transcripts.toBoolean(), fasta.toString()+';'+gtf.toString() ]
}
// Create channels = [ sample, barcode, fasta, gtf, is_transcripts, annotation_str ]
ch_samplesheet_reformat
.splitCsv(header:true, sep:',')
.map { get_sample_info(it, params.genomes) }
.map { it -> [ it[0], it[2], it[3], it[4], it[5], it[6] ] }
.into {
ch_sample_fasta
ch_sample_gtf
ch_sample_replicates
ch_sample_groups
ch_sample_info
ch_sample_name
ch_sample_annotation
}
// Check that reference genome and annotation are the same for all samples if perfoming quantification
// Check if we have replicates and multiple conditions in the input samplesheet
def REPLICATES_EXIST = false
def MULTIPLE_CONDITIONS = false
if (!params.skip_quantification) {
def fastas = ch_sample_fasta.map { it[2] }.unique().toList().val
def gtfs = ch_sample_gtf.map { it[3] }.unique().toList().val
if (fastas.size() != 1 || gtfs.size() != 1 || fastas[0] == false || gtfs[0] == false) {
exit 1, """Quantification can only be performed if all samples in the samplesheet have the same reference fasta and GTF file."
Please specify the '--skip_quantification' parameter if you wish to skip these steps."""
}
REPLICATES_EXIST = ch_sample_replicates.map { it -> it[0].split('_')[-1].replaceAll('R','').toInteger() }.max().val > 1
MULTIPLE_CONDITIONS = ch_sample_groups.map { it -> it[0].split('_')[0..-2].join('_') }.unique().count().val > 1
}
if (!params.skip_basecalling) {
// Get sample name for single sample when --skip_demultiplexing
ch_sample_name
.first()
.map { it[0] }
.set { ch_sample_name }
/*
* Basecalling and demultipexing using Guppy
*/
process GUPPY {
tag "$input_path"
label 'process_high'
publishDir path: "${params.outdir}/guppy", mode: params.publish_dir_mode,
saveAs: { filename ->
if (!filename.endsWith("guppy.txt")) filename
}
input:
path input_path from ch_input_path
val name from ch_sample_name
path guppy_config from ch_guppy_config.ifEmpty([])
path guppy_model from ch_guppy_model.ifEmpty([])
output:
path "fastq/*.fastq.gz" into ch_fastq
path "basecalling/*.txt" into ch_guppy_pycoqc_summary,
ch_guppy_nanoplot_summary
path "basecalling/*"
path "v_guppy.txt" into ch_guppy_version
script:
barcode_kit = params.barcode_kit ? "--barcode_kits $params.barcode_kit" : ""
barcode_ends = params.barcode_both_ends ? "--require_barcodes_both_ends" : ""
proc_options = params.guppy_gpu ? "--device $params.gpu_device --num_callers $task.cpus --cpu_threads_per_caller $params.guppy_cpu_threads --gpu_runners_per_device $params.guppy_gpu_runners" : "--num_callers 2 --cpu_threads_per_caller ${task.cpus/2}"
def config = "--flowcell $params.flowcell --kit $params.kit"
if (params.guppy_config) config = file(params.guppy_config).exists() ? "--config ./$guppy_config" : "--config $params.guppy_config"
def model = ""
if (params.guppy_model) model = file(params.guppy_model).exists() ? "--model ./$guppy_model" : "--model $params.guppy_model"
"""
guppy_basecaller \\
--input_path $input_path \\
--save_path ./basecalling \\
--records_per_fastq 0 \\
--compress_fastq \\
$barcode_kit \\
$proc_options \\
$barcode_ends \\
$config \\
$model
guppy_basecaller --version &> v_guppy.txt
## Concatenate fastq files
mkdir fastq
cd basecalling
if [ "\$(find . -type d -name "barcode*" )" != "" ]
then
for dir in barcode*/
do
dir=\${dir%*/}
cat \$dir/*.fastq.gz > ../fastq/\$dir.fastq.gz
done
else
cat *.fastq.gz > ../fastq/${name}.fastq.gz
fi
"""
}
// Create channels = [ sample, fastq, fasta, gtf, is_transcripts, annotation_str ]
ch_fastq
.flatten()
.map { it -> [ it, it.baseName.substring(0,it.baseName.lastIndexOf('.')) ] } // [barcode001.fastq, barcode001]
.join(ch_sample_info, by: 1) // join on barcode
.map { it -> [ it[2], it[1], it[3], it[4], it[5], it[6] ] }
.into {
ch_fastq_nanoplot
ch_fastq_fastqc
ch_fastq_sizes
ch_fastq_gtf
ch_fastq_index
ch_fastq_align
}
} else {
if (!params.skip_demultiplexing) {
/*
* Demultipexing using qcat
*/
process QCAT {
tag "$input_path"
label 'process_medium'
publishDir path: "${params.outdir}/qcat", mode: params.publish_dir_mode
input:
path input_path from ch_input_path
output:
path "fastq/*.fastq.gz" into ch_fastq
script:
detect_middle = params.qcat_detect_middle ? "--detect-middle $params.qcat_detect_middle" : ""
"""
## Unzip fastq file
## qcat doesnt support zipped files yet
FILE=$input_path
if [[ \$FILE == *.gz ]]
then
zcat $input_path > unzipped.fastq
FILE=unzipped.fastq
fi
qcat \\
-f \$FILE \\
-b ./fastq \\
--kit $params.barcode_kit \\
--min-score $params.qcat_min_score \\
$detect_middle
## Zip fastq files
pigz -p $task.cpus fastq/*
"""
}
// Create channels = [ sample, fastq, fasta, gtf, is_transcripts, annotation_str ]
ch_fastq
.flatten()
.map { it -> [ it, it.baseName.substring(0,it.baseName.lastIndexOf('.'))] } // [barcode001.fastq, barcode001]
.join(ch_sample_info, by: 1) // join on barcode
.map { it -> [ it[2], it[1], it[3], it[4], it[5], it[6] ] }
.into {
ch_fastq_nanoplot
ch_fastq_fastqc
ch_fastq_sizes
ch_fastq_gtf
ch_fastq_index
ch_fastq_align
}
} else {
if (!params.skip_alignment) {
// Create channels = [ sample, fastq, fasta, gtf, is_transcripts, annotation_str ]
ch_samplesheet_reformat
.splitCsv(header:true, sep:',')
.map { get_sample_info(it, params.genomes) }
.map { it -> if (it[1].toString().endsWith('.gz')) [ it[0], it[1], it[3], it[4], it[5], it[6] ] }
.into {
ch_fastq_nanoplot
ch_fastq_fastqc
ch_fastq_sizes
ch_fastq_gtf
ch_fastq_index
ch_fastq_align
}
} else {
ch_fastq_nanoplot = Channel.empty()
ch_fastq_fastqc = Channel.empty()
}
}
ch_guppy_version = Channel.empty()
ch_guppy_pycoqc_summary = Channel.empty()
ch_guppy_nanoplot_summary = Channel.empty()
}
/*
* QC using PycoQC
*/
process PYCOQC {
tag "$summary_txt"
label 'process_low'
publishDir "${params.outdir}/pycoqc", mode: params.publish_dir_mode
when:
!params.skip_basecalling && !params.skip_qc && !params.skip_pycoqc
input:
path summary_txt from ch_guppy_pycoqc_summary
output:
path "*.html"
path "*.json" into ch_pycoqc_multiqc
path "v_pycoqc.txt" into ch_pycoqc_version
script:
"""
pycoQC -f $summary_txt -o pycoqc.html -j pycoqc.json
pycoQC --version &> v_pycoqc.txt
"""
}
/*
* QC using NanoPlot
*/
process NANOPLOT_SUMMARY {
tag "$summary_txt"
label 'process_low'
publishDir "${params.outdir}/nanoplot/summary", mode: params.publish_dir_mode
when:
!params.skip_basecalling && !params.skip_qc && !params.skip_nanoplot
input:
path summary_txt from ch_guppy_nanoplot_summary
output:
path "*.{png,html,txt,log}"
script:
"""
NanoPlot -t $task.cpus --summary $summary_txt
"""
}
/*
* FastQ QC using NanoPlot
*/
process NANOPLOT_FASTQ {
tag "$sample"
label 'process_low'
publishDir "${params.outdir}/nanoplot/fastq/${sample}", mode: params.publish_dir_mode
when:
!params.skip_qc && !params.skip_nanoplot
input:
tuple val(sample), path(fastq) from ch_fastq_nanoplot.map { ch -> [ ch[0], ch[1] ] }
output:
path "*.{png,html,txt,log}"
script:
"""
NanoPlot -t $task.cpus --fastq $fastq
"""
}
/*
* FastQ QC using FastQC
*/
process FASTQC {
tag "$sample"
label 'process_medium'
publishDir "${params.outdir}/fastqc", mode: params.publish_dir_mode
when:
!params.skip_qc && !params.skip_fastqc
input:
tuple val(sample), path(fastq) from ch_fastq_fastqc.map { ch -> [ ch[0], ch[1] ] }
output:
path "*.{zip,html}" into ch_fastqc_multiqc
script:
"""
[ ! -f ${sample}.fastq.gz ] && ln -s $fastq ${sample}.fastq.gz
fastqc \\
-q \\
-t $task.cpus \\
${sample}.fastq.gz
"""
}
if (!params.skip_alignment) {
// Get unique list of all fasta files
ch_fastq_sizes
.filter { it[2] }
.map { it -> [ it[2], it[-1].toString() ] } // [ fasta, annotation_str ]
.unique()
.set { ch_fastq_sizes }
/*
* Make chromosome sizes file
*/
process GET_CHROM_SIZES {
tag "$fasta"
input:
tuple path(fasta), val(name) from ch_fastq_sizes
output:
tuple path("*.sizes"), val(name) into ch_chrom_sizes
script:
"""
samtools faidx $fasta
cut -f 1,2 ${fasta}.fai > ${fasta}.sizes
"""
}
// Get unique list of all gtf files
ch_fastq_gtf
.filter { it[3] }
.map { it -> [ it[3], it[-1] ] } // [ gtf, annotation_str ]
.unique()
.set { ch_fastq_gtf }
/*
* Convert GTF to BED12
*/
process GTF_TO_BED {
tag "$gtf"
label 'process_low'
input:
tuple path(gtf), val(name) from ch_fastq_gtf
output:
tuple path("*.bed"), val(name) into ch_gtf_bed
script: // This script is bundled with the pipeline, in nf-core/nanoseq/bin/
"""
gtf2bed $gtf > ${gtf.baseName}.bed
"""
}
ch_chrom_sizes
.join(ch_gtf_bed, by: 1, remainder:true)
.map { it -> [ it[1], it[2], it[0] ] }
.cross(ch_fastq_index) { it -> it[-1] }
.flatten()
.collate(9)
.map { it -> [ it[5], it[0], it[6], it[1], it[7], it[8] ]} // [ fasta, sizes, gtf, bed, is_transcripts, annotation_str ]
.unique()
.set { ch_fasta_index }
/*
* Create genome/transcriptome index
*/
if (params.aligner == 'minimap2') {
process MINIMAP2_INDEX {
tag "$fasta"
label 'process_medium'
input:
tuple path(fasta), path(sizes), val(gtf), val(bed), val(is_transcripts), val(annotation_str) from ch_fasta_index
output:
tuple path(fasta), path(sizes), val(gtf), val(bed), val(is_transcripts), path("*.mmi"), val(annotation_str) into ch_index
script:
preset = (params.protocol == 'DNA' || is_transcripts) ? "-ax map-ont" : "-ax splice"
kmer = (params.protocol == 'directRNA') ? "-k14" : ""
stranded = (params.stranded || params.protocol == 'directRNA') ? "-uf" : ""
// TODO pipeline: Should be staging bed file properly as an input
junctions = (params.protocol != 'DNA' && bed) ? "--junc-bed ${file(bed)}" : ""
"""
minimap2 \\
$preset \\
$kmer \\
$stranded \\
$junctions \\
-t $task.cpus \\
-d ${fasta}.mmi \\
$fasta
"""
}
} else {
process GRAPHMAP2_INDEX {
tag "$fasta"
label 'process_high'
input:
tuple path(fasta), path(sizes), val(gtf), val(bed), val(is_transcripts), val(annotation_str) from ch_fasta_index
output:
tuple path(fasta), path(sizes), val(gtf), val(bed), val(is_transcripts), path("*.gmidx"), val(annotation_str) into ch_index
script:
preset = (params.protocol == 'DNA' || is_transcripts) ? "" : "-x rnaseq"
// TODO pipeline: Should be staging gtf file properly as an input
junctions = (params.protocol != 'DNA' && !is_transcripts && gtf) ? "--gtf ${file(gtf)}" : ""
"""
graphmap2 \\
align \\
$preset \\
$junctions \\
-t $task.cpus \\
-I \\
-r $fasta
"""
}
}
ch_index
.cross(ch_fastq_align) { it -> it[-1] }
.flatten()
.collate(13)
.map { it -> [ it[7], it[8], it[0], it[1], it[2], it[3], it[4], it[5] ] } // [ sample, fastq, fasta, sizes, gtf, bed, is_transcripts, index ]
.set { ch_index }
/*
* Align fastq files
*/
if (params.aligner == 'minimap2') {
process MINIMAP2_ALIGN {
tag "$sample"
label 'process_medium'
if (params.save_align_intermeds) {
publishDir path: "${params.outdir}/${params.aligner}", mode: params.publish_dir_mode,
saveAs: { filename ->
if (filename.endsWith(".sam")) filename
}
}
input:
tuple val(sample), path(fastq), path(fasta), path(sizes), val(gtf), val(bed), val(is_transcripts), path(index) from ch_index
output:
tuple val(sample), path(sizes), val(is_transcripts), path("*.sam") into ch_align_sam
script:
preset = (params.protocol == 'DNA' || is_transcripts) ? "-ax map-ont" : "-ax splice"
kmer = (params.protocol == 'directRNA') ? "-k14" : ""
stranded = (params.stranded || params.protocol == 'directRNA') ? "-uf" : ""
// TODO pipeline: Should be staging bed file properly as an input
junctions = (params.protocol != 'DNA' && bed) ? "--junc-bed ${file(bed)}" : ""
"""
minimap2 \\
$preset \\
$kmer \\
$stranded \\
$junctions \\
-t $task.cpus \\
$index \\
$fastq > ${sample}.sam
"""
}
} else {
process GRAPHMAP2_ALIGN {
tag "$sample"
label 'process_medium'
if (params.save_align_intermeds) {
publishDir path: "${params.outdir}/${params.aligner}", mode: params.publish_dir_mode,
saveAs: { filename ->
if (filename.endsWith(".sam")) filename
}
}
input:
tuple val(sample), path(fastq), path(fasta), path(sizes), val(gtf), val(bed), val(is_transcripts), path(index) from ch_index
output:
tuple val(sample), path(sizes), val(is_transcripts), path("*.sam") into ch_align_sam
script:
preset = (params.protocol == 'DNA' || is_transcripts) ? "" : "-x rnaseq"
// TODO pipeline: Should be staging gtf file properly as an input
junctions = (params.protocol != 'DNA' && !is_transcripts && gtf) ? "--gtf ${file(gtf)}" : ""
"""
graphmap2 \\
align \\
$preset \\
$junctions \\
-t $task.cpus \\
-r $fasta \\
-i $index \\
-d $fastq \\
-o ${sample}.sam \\
--extcigar
"""
}
}
/*
* Coordinate sort BAM files
*/
process SAMTOOLS_SORT {
tag "$sample"
label 'process_medium'
publishDir path: "${params.outdir}/${params.aligner}", mode: params.publish_dir_mode,
saveAs: { filename ->
if (filename.endsWith(".flagstat")) "samtools_stats/$filename"
else if (filename.endsWith(".idxstats")) "samtools_stats/$filename"
else if (filename.endsWith(".stats")) "samtools_stats/$filename"
else if (filename.endsWith(".sorted.bam")) filename
else if (filename.endsWith(".sorted.bam.bai")) filename
else null
}
input:
tuple val(sample), path(sizes), val(is_transcripts), path(sam) from ch_align_sam
output:
tuple val(sample), path(sizes), val(is_transcripts), path("*.sorted.bam"), path("*.sorted.bam.bai") into ch_sortbam_bedgraph,
ch_sortbam_bed12,
ch_sortbam_quant
path "*.{flagstat,idxstats,stats}" into ch_sortbam_stats_multiqc
script:
"""
samtools view -b -h -O BAM -@ $task.cpus -o ${sample}.bam $sam
samtools sort -@ $task.cpus -o ${sample}.sorted.bam -T $sample ${sample}.bam
samtools index ${sample}.sorted.bam
samtools flagstat ${sample}.sorted.bam > ${sample}.sorted.bam.flagstat
samtools idxstats ${sample}.sorted.bam > ${sample}.sorted.bam.idxstats
samtools stats ${sample}.sorted.bam > ${sample}.sorted.bam.stats
"""
}
ch_sortbam_quant
.map { it -> [ it[0], it[3] ] }
.set { ch_sortbam_quant }
} else {
ch_sortbam_bedgraph = Channel.empty()
ch_sortbam_bed12 = Channel.empty()
ch_sortbam_stats_multiqc = Channel.empty()
ch_samplesheet_reformat
.splitCsv(header:true, sep:',')
.map { get_sample_info(it, params.genomes) }
.map { it -> if (it[1].toString().endsWith('.bam')) [ it[0] , it[1] ] }
.set { ch_sortbam_rename }
/*
* Rename BAM inputs to <GROUP_REPLICATE>
*/
process BAM_RENAME {
tag "$sample"
input:
tuple val(sample), path(bam) from ch_sortbam_rename
output:
tuple val(sample), path("*.bam") into ch_sortbam_quant
script:
"""
[ ! -f ${sample}.bam ] && ln -s $bam ${sample}.bam
"""
}
}
/*
* Convert BAM to BEDGraph
*/
process BEDTOOLS_GENOMECOV {
tag "$sample"
label 'process_medium'
when:
!params.skip_alignment && !params.skip_bigwig
input:
tuple val(sample), path(sizes), val(is_transcripts), path(bam), path(bai) from ch_sortbam_bedgraph
output:
tuple val(sample), path(sizes), val(is_transcripts), path("*.bedGraph") into ch_bedgraph
script:
split = (params.protocol == 'DNA' || is_transcripts) ? "" : "-split"
"""
bedtools \\
genomecov \\
$split \\
-ibam ${bam[0]} \\
-bg \\
| bedtools sort > ${sample}.bedGraph
"""
}
/*
* Convert BEDGraph to BigWig
*/
process UCSC_BEDGRAPHTOBIGWIG {
tag "$sample"
label 'process_medium'
publishDir path: "${params.outdir}/${params.aligner}/bigwig/", mode: params.publish_dir_mode
when:
!params.skip_alignment && !params.skip_bigwig
input:
tuple val(sample), path(sizes), val(is_transcripts), path(bedgraph) from ch_bedgraph
output:
tuple val(sample), path(sizes), val(is_transcripts), path("*.bigWig") into ch_bigwig
script:
"""
bedGraphToBigWig \\
$bedgraph \\
$sizes \\
${sample}.bigWig
"""
}
/*
* Convert BAM to BED12
*/
process BEDTOOLS_BAMTOBED {
tag "$sample"
label 'process_medium'
when:
!params.skip_alignment && !params.skip_bigbed && (params.protocol == 'directRNA' || params.protocol == 'cDNA')
input:
tuple val(sample), path(sizes), val(is_transcripts), path(bam), path(bai) from ch_sortbam_bed12
output:
tuple val(sample), path(sizes), val(is_transcripts), path("*.bed12") into ch_bed12
script:
"""
bedtools \\
bamtobed \\
-bed12 \\
-cigar \\
-i ${bam[0]} \\
| bedtools sort > ${sample}.bed12
"""
}
/*
* Convert BED12 to BigBED
*/
process UCSC_BED12TOBIGBED {
tag "$sample"
label 'process_medium'
publishDir path: "${params.outdir}/${params.aligner}/bigbed/", mode: params.publish_dir_mode
when:
!params.skip_alignment && !params.skip_bigbed && (params.protocol == 'directRNA' || params.protocol == 'cDNA')
input:
tuple val(sample), path(sizes), val(is_transcripts), path(bed12) from ch_bed12
output:
tuple val(sample), path(sizes), val(is_transcripts), path("*.bigBed") into ch_bigbed
script:
"""
bedToBigBed \\
$bed12 \\
$sizes \\
${sample}.bigBed
"""
}