forked from GuilleGorines/PikaVirus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.nf
2053 lines (1617 loc) · 68.5 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/pikavirus
========================================================================================
nf-core/pikavirus Analysis Pipeline.
#### Homepage / Documentation
https://github.com/nf-core/pikavirus
----------------------------------------------------------------------------------------
*/
log.info Headers.nf_core(workflow, params.monochrome_logs)
////////////////////////////////////////////////////
/* -- PRINT HELP -- */
////////////////////////////////////////////////////+
def json_schema = "$projectDir/nextflow_schema.json"
if (params.help) {
def command = "nextflow run nf-core/pikavirus --input samplesheet.csv -profile docker"
log.info NfcoreSchema.params_help(workflow, params, json_schema, command)
exit 0
}
////////////////////////////////////////////////////
/* -- VALIDATE PARAMETERS -- */
////////////////////////////////////////////////////+
if (params.validate_params) {
NfcoreSchema.validateParameters(params, json_schema, log)
}
////////////////////////////////////////////////////
/* -- Collect configuration parameters -- */
////////////////////////////////////////////////////
// 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.'
}
// Stage config files
ch_multiqc_config = file("$projectDir/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("$projectDir/docs/output.md", checkIfExists: true)
ch_output_docs_images = file("$projectDir/docs/images/", checkIfExists: true)
/*
* Create a channel for input read files
*/
if (params.input) { ch_input = file(params.input, checkIfExists: true) } else { exit 1, "Samplesheet file (-input) not specified!" }
////////////////////////////////////////////////////
/* -- PRINT PARAMETER SUMMARY -- */
////////////////////////////////////////////////////
log.info NfcoreSchema.params_summary_log(workflow, params, json_schema)
// Header log info
def summary = [:]
if (workflow.revision) summary['Pipeline Release'] = workflow.revision
summary['Run Name'] = workflow.runName
summary['Input'] = params.input
summary['Trimming'] = params.trimming
if (params.remove_control) summary['Sequencing control'] = params.control_sequence
summary['Kraken scouting'] = params.kraken_scouting
if (params.kraken_scouting) summary['Kraken database'] = params.kraken2_db
summary['Kaiju discovery'] = params.translated_analysis
if (params.translated_analysis) summary ['Kaiju database'] = params.kaiju_db
summary['Virus Search'] = params.virus
if (params.virus) summary['Virus Ref'] = params.vir_ref_dir
if (params.virus) summary['Virus Index File'] = params.vir_dir_repo
summary['Bacteria Search'] = params.bacteria
if (params.bacteria) summary['Bacteria Ref'] = params.bact_ref_dir
if (params.bacteria) summary['Bacteria Index File'] = params.bact_dir_repo
summary['Fungi Search'] = params.fungi
if (params.fungi) summary['Fungi Ref'] = params.fungi_ref_dir
if (params.fungi) summary['Fungi Index File'] = params.fungi_dir_repo
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(18)}: $v" }.join("\n")
log.info "-\033[2m--------------------------------------------------\033[0m-"
// Check the hostnames against configured profiles
checkHostname()
Channel.from(summary.collect{ [it.key, it.value] })
.map { k,v -> "<dt>$k</dt><dd><samp>${v ?: '<span style=\"color:#999999;\">N/A</a>'}</samp></dd>" }
.reduce { a, b -> return [a, b].join("\n ") }
.map { x -> """
id: 'nf-core-pikavirus-summary'
description: " - this information is collected when the pipeline is started."
section_name: 'nf-core/pikavirus Workflow Summary'
section_href: 'https://github.com/nf-core/pikavirus'
plot_type: 'html'
data: |
<dl class=\"dl-horizontal\">
$x
</dl>
""".stripIndent() }
.set { ch_workflow_summary }
/*
* Parse software version numbers
*/
process get_software_versions {
publishDir "${params.outdir}/pipeline_info", mode: params.publish_dir_mode,
saveAs: { filename ->
if (filename.indexOf(".csv") > 0) filename
else null
}
output:
file 'software_versions_mqc.yaml' into ch_software_versions_yaml
file "software_versions.csv"
script:
"""
echo $workflow.manifest.version > v_pipeline.txt
echo $workflow.nextflow.version > v_nextflow.txt
fastqc --version &> v_fastqc.txt &
fastp --version 2> v_fastp.txt
bowtie2 --version > v_bowtie2.txt
mash -v | grep version &> v_mash.txt &
spades.py -v &> v_spades.txt &
quast -v &> v_quast.txt &
samtools --version | grep samtools > v_samtools.txt
bedtools --version > v_bedtools.txt
multiqc --version > v_multiqc.txt
kraken2 --version > v_kraken2.txt
kaiju -help &> tmp &
head -n 1 tmp > v_kaiju.txt
ivar -v > v_ivar.txt
muscle -version > v_muscle.txt
scrape_software_versions.py &> software_versions_mqc.yaml
"""
}
process CHECK_SAMPLESHEET {
tag "$samplesheet"
publishDir "${params.outdir}/", mode: params.publish_dir_mode,
saveAs: { filename ->
if (filename.endsWith(".tsv")) "preprocess/sra/$filename"
else "pipeline_info/$filename"
}
input:
path(samplesheet) from ch_input
output:
path "samplesheet.valid.csv" into ch_samplesheet_reformat
path "sra_run_info.tsv" optional true
script: // These scripts are bundled with the pipeline, in nf-core/viralrecon/bin/
run_sra = !params.skip_sra && !isOffline()
"""
awk -F, '{if(\$1 != "" && \$2 != "") {print \$0}}' $samplesheet > nonsra_id.csv
check_samplesheet.py nonsra_id.csv nonsra.samplesheet.csv
awk -F, '{if(\$1 != "" && \$2 == "" && \$3 == "") {print \$1}}' $samplesheet > sra_id.list
if $run_sra && [ -s sra_id.list ]
then
fetch_sra_runinfo.py sra_id.list sra_run_info.tsv --platform ILLUMINA --library_layout SINGLE,PAIRED
sra_runinfo_to_samplesheet.py sra_run_info.tsv sra.samplesheet.csv
fi
if [ -f nonsra.samplesheet.csv ]
then
head -n 1 nonsra.samplesheet.csv > samplesheet.valid.csv
else
head -n 1 sra.samplesheet.csv > samplesheet.valid.csv
fi
tail -n +2 -q *sra.samplesheet.csv >> samplesheet.valid.csv
"""
}
// Function to get list of [ sample, single_end?, is_sra?, is_ftp?, [ fastq_1, fastq_2 ], [ md5_1, md5_2] ]
def validate_input(LinkedHashMap sample) {
def sample_id = sample.sample_id
def single_end = sample.single_end.toBoolean()
def is_sra = sample.is_sra.toBoolean()
def is_ftp = sample.is_ftp.toBoolean()
def fastq_1 = sample.fastq_1
def fastq_2 = sample.fastq_2
def md5_1 = sample.md5_1
def md5_2 = sample.md5_2
def array = []
if (!is_sra) {
if (single_end) {
array = [ sample_id, single_end, is_sra, is_ftp, [ file(fastq_1, checkIfExists: true) ] ]
} else {
array = [ sample_id, single_end, is_sra, is_ftp, [ file(fastq_1, checkIfExists: true), file(fastq_2, checkIfExists: true) ] ]
}
} else {
array = [ sample_id, single_end, is_sra, is_ftp, [ fastq_1, fastq_2 ], [ md5_1, md5_2 ] ]
}
return array
}
/*
* Create channels for input fastq files
*/
ch_samplesheet_reformat
.splitCsv(header:true, sep:',')
.map { validate_input(it) }
.into { ch_reads_all
ch_reads_sra }
/*
* Download and check SRA data
*/
if (!params.skip_sra || !isOffline()) {
ch_reads_sra
.filter { it[2] }
.into { ch_reads_sra_ftp
ch_reads_sra_dump }
process SRA_FASTQ_FTP {
tag "$sample"
label 'process_medium'
label 'error_retry'
publishDir "${params.outdir}/preprocess/sra", mode: params.publish_dir_mode,
saveAs: { filename ->
if (filename.endsWith(".md5")) "md5/$filename"
else params.save_sra_fastq ? filename : null
}
when:
is_ftp
input:
tuple val(sample), val(single_end), val(is_sra), val(is_ftp), val(fastq), val(md5) from ch_reads_sra_ftp
output:
tuple val(sample), val(single_end), val(is_sra), val(is_ftp), path("*.fastq.gz") into ch_sra_fastq_ftp
script:
if (single_end) {
"""
curl -L ${fastq[0]} -o ${sample}.fastq.gz
echo "${md5[0]} ${sample}.fastq.gz" > ${sample}.fastq.gz.md5
md5sum -c ${sample}.fastq.gz.md5
"""
} else {
"""
curl -L ${fastq[0]} -o ${sample}_1.fastq.gz
echo "${md5[0]} ${sample}_1.fastq.gz" > ${sample}_1.fastq.gz.md5
md5sum -c ${sample}_1.fastq.gz.md5
curl -L ${fastq[1]} -o ${sample}_2.fastq.gz
echo "${md5[1]} ${sample}_2.fastq.gz" > ${sample}_2.fastq.gz.md5
md5sum -c ${sample}_2.fastq.gz.md5
"""
}
}
process SRA_FASTQ_DUMP {
tag "$sample"
label 'process_medium'
label 'error_retry'
publishDir "${params.outdir}/preprocess/sra", mode: params.publish_dir_mode,
saveAs: { filename ->
if (filename.endsWith(".log")) "log/$filename"
else params.save_sra_fastq ? filename : null
}
when:
!is_ftp
input:
tuple val(sample), val(single_end), val(is_sra), val(is_ftp) from ch_reads_sra_dump.map { it[0..3] }
output:
tuple val(sample), val(single_end), val(is_sra), val(is_ftp), path("*.fastq.gz") into ch_sra_fastq_dump
path "*.log"
script:
prefix = "${sample.split('_')[0..-2].join('_')}"
pe = single_end ? "" : "--readids --split-e"
rm_orphan = single_end ? "" : "[ -f ${prefix}.fastq.gz ] && rm ${prefix}.fastq.gz"
"""
parallel-fastq-dump \\
--sra-id $prefix \\
--threads $task.cpus \\
--outdir ./ \\
--tmpdir ./ \\
--gzip \\
$pe \\
> ${prefix}.fastq_dump.log
$rm_orphan
"""
}
ch_reads_all
.filter { !it[2] }
.concat(ch_sra_fastq_ftp, ch_sra_fastq_dump)
.set { ch_reads_all }
}
ch_reads_all
.map { [ it[0].split('_')[0..-2].join('_'), it[1], it[4] ] }
.groupTuple(by: [0, 1])
.map { [ it[0], it[1], it[2].flatten() ] }
.set { ch_reads_all }
/*
* Merge FastQ files with the same sample identifier (resequenced samples)
*/
process CAT_FASTQ {
tag "$sample"
input:
tuple val(sample), val(single_end), path(reads) from ch_reads_all
output:
tuple val(sample), val(single_end), path("*.merged.fastq.gz") into ch_cat_fastqc,
ch_cat_fortrim
val(sample) into samplechannel_translated,
samplechannel_trim_fastqc,
samplechannel_trimmed_fastqc,
samplechannel_krona,
control_results_template,
virus_results_template,
bacteria_results_template,
fungi_results_template
tuple val(sample), val(single_end) into sample_pe_template
script:
readList = reads.collect{it.toString()}
if (!single_end) {
if (readList.size > 2) {
def read1 = []
def read2 = []
readList.eachWithIndex{ v, ix -> ( ix & 1 ? read2 : read1 ) << v }
"""
cat ${read1.sort().join(' ')} > ${sample}_1.merged.fastq.gz
cat ${read2.sort().join(' ')} > ${sample}_2.merged.fastq.gz
"""
} else {
"""
ln -s ${reads[0]} ${sample}_1.merged.fastq.gz
ln -s ${reads[1]} ${sample}_2.merged.fastq.gz
"""
}
} else {
if (readList.size > 1) {
"""
cat ${readList.sort().join(' ')} > ${sample}.merged.fastq.gz
"""
} else {
"""
ln -s $reads ${sample}.merged.fastq.gz
"""
}
}
}
/*
* PREPROCESSING: KAIJU DATABASE
*/
if (params.kaiju && params.translated_analysis) {
if (params.kaiju_db.endsWith('.gz') || params.kaiju_db.endsWith('.tar') || params.kaiju_db.endsWith('.tgz')){
process UNCOMPRESS_KAIJUDB {
label 'error_retry'
input:
path(database) from params.kaiju_db
output:
path("kaijudb") into kaiju_db
script:
"""
mkdir "kaijudb"
tar -zxf $database -C "kaijudb"
"""
}
} else {
kaiju_db = Channel.fromPath(params.kaiju_db)
}
}
/*
* STEP 1.1 - FastQC
*/
process RAW_SAMPLES_FASTQC {
tag "$samplename"
label "process_medium"
publishDir "${params.outdir}/${samplename}/raw_fastqc", mode: params.publish_dir_mode,
saveAs: { filename ->
filename.indexOf(".zip") > 0 ? "zips/$filename" : "$filename"
}
input:
set val(samplename), val(single_end), path(reads) from ch_cat_fastqc
output:
tuple val(samplename), path("*_fastqc.{zip,html}") into raw_fastqc_results
tuple val(samplename), path("*_fastqc.zip") into raw_fastqc_multiqc
path("*_fastqc.zip") into raw_fastqc_multiqc_global
script:
"""
fastqc --quiet --threads $task.cpus $reads
"""
}
/*
* STEP 1.2 - TRIMMING
*/
if (params.trimming) {
process FASTP_TRIM {
tag "$samplename"
label "process_medium"
publishDir "${params.outdir}/${samplename}", mode: params.publish_dir_mode,
saveAs: { filename ->
if (filename.endsWith(".fastq") && params.rescue_trimmed) "trimmed_sequences/$filename"
else if (filename.endsWith(".html")) filename
}
input:
tuple val(samplename), val(single_end), path(reads) from ch_cat_fortrim
output:
tuple val(samplename), val(single_end), path("*trim.fastq.gz") into trimmed_paired_fastqc, trimmed_remove_control
tuple val(samplename), val(single_end), path("*fail.fastq.gz") into trimmed_unpaired
tuple val(samplename), path("*.json") into fastp_multiqc
tuple val(samplename), path("*.html") into fastp_report
path("*.json") into fastp_multiqc_global
script:
detect_adapter = single_end ? "" : "--detect_adapter_for_pe"
reads1 = single_end ? "--in1 ${reads} --out1 ${samplename}_trim.fastq.gz --failed_out ${samplename}_fail.fastq.gz" : "--in1 ${reads[0]} --out1 ${samplename}_1_trim.fastq.gz --unpaired1 ${samplename}_1_fail.fastq.gz"
reads2 = single_end ? "" : "--in2 ${reads[1]} --out2 ${samplename}_2_trim.fastq.gz --unpaired2 ${samplename}_2_fail.fastq.gz"
"""
fastp \\
$detect_adapter \\
--cut_front \\
--cut_tail \\
--length_required 35 \\
--thread $task.cpus \\
--json ${samplename}_trim_fastp.json \\
$reads1 \\
$reads2
"""
}
/*
* STEP 1.3 - FastQC on trimmed reads
*/
process TRIMMED_SAMPLES_FASTQC {
tag "$samplename"
label "process_medium"
publishDir "${params.outdir}/${samplename}/trimmed_fastqc", mode: params.publish_dir_mode
input:
tuple val(samplename), val(single_end), path(reads) from trimmed_paired_fastqc
output:
tuple val(samplename), path("*_fastqc.{zip,html}") into trim_fastqc_results
tuple val(samplename), path("*_fastqc.zip") into trimmed_fastqc_multiqc
path("*_fastqc.zip") into trimmed_fastqc_multiqc_global
script:
"""
fastqc --quiet --threads $task.cpus $reads
"""
}
if (params.remove_control) {
Channel.fromPath(params.control_sequence).set { control_genome }
process BOWTIE2_REMOVE_SEQUENCING_CONTROL {
tag "$samplename"
label "process_high"
input:
tuple val(samplename), val(single_end), path(reads), path(control_sequence) from trimmed_remove_control.combine(control_genome)
output:
tuple val(samplename), val(single_end), path("*_mapped_sorted.bam") into control_alignment
tuple val(samplename), val(single_end), path("*.fastq.gz") into trimmed_virus, trimmed_bact, trimmed_fungi,
reads_for_assembly, trimmed_skip_hostremoval,
trimmed_map_virus, trimmed_map_bact, trimmed_map_fungi,
trimmed_kraken2
script:
samplereads = single_end ? "-U ${reads}" : "-1 ${reads[0]} -2 ${reads[1]}"
unmapped = single_end ? "--un-gz ${samplename}_unmapped.fastq.gz" : "--un-conc-gz ${samplename}_unmapped_R%.fastq.gz"
"""
bowtie2-build \\
--seed 1 \\
--threads $task.cpus \\
$control_sequence \\
"control_sequence"
bowtie2 \\
--threads $task.cpus \\
-x "control_sequence" \\
$unmapped \\
$samplereads | samtools view \\
-@ $task.cpus \\
-b \\
-h \\
-O BAM \\
-o "${control_sequence}_mapped.bam"
samtools sort \\
-@ $task.cpus \\
-o "${control_sequence}_mapped_sorted.bam" \\
"${control_sequence}_mapped.bam"
"""
}
process SAMTOOLS_SEQUENCING_CONTROL {
tag "$samplename"
label "process_medium"
input:
tuple val(samplename), val(single_end), path(sortedbam) from control_alignment
output:
tuple val(samplename), val(single_end), path(sortedbam), path("*idxstats"), path("*flagstat") into control_alignment_bams
script:
prefix = sortedbam.join().minus("_mapped_sorted.bam")
"""
samtools index $sortedbam
samtools idxstats $sortedbam > "${prefix}.sorted.bam.idxstats"
samtools flagstat -O tsv $sortedbam > "${prefix}.sorted.bam.flagstat"
"""
}
process BEDTOOLS_SEQUENCING_CONTROL {
tag "$samplename"
label "process_medium"
input:
tuple val(samplename), val(single_end), path(mapped), path(idxstat), path(flagstat) from control_alignment_bams
output:
tuple val(samplename), path("*_coverage.txt"), path(idxstat), path(flagstat) into coverage_stats_control
script:
prefix = mapped.join().minus("_mapped_sorted.bam")
"""
bedtools genomecov -ibam $mapped > "${prefix}_coverage.txt"
"""
}
process COVERAGE_STATS_SEQUENCING_CONTROL {
tag "$samplename"
label "process_medium"
input:
tuple val(samplename), path(coveragefile), path(idxstat), path(flagstat) from coverage_stats_control
output:
tuple val(samplename), path("*.tsv") into control_coverage_results
script:
"""
coverage_analysis_control.py $samplename $coveragefile $idxstat $flagstat
"""
}
} else {
trimmed_remove_control.into { trimmed_virus
trimmed_bact
trimmed_fungi
reads_for_assembly
trimmed_skip_hostremoval
trimmed_map_virus
trimmed_map_bact
trimmed_map_fungi
trimmed_kraken2 }
nofile_path_control_coverage = Channel.fromPath("NONE_control_coverage")
control_results_template.combine(nofile_path_control_coverage).set { control_coverage_results }
}
} else {
ch_cat_fortrim.into { trimmed_virus
trimmed_bact
trimmed_fungi
reads_for_assembly
trimmed_skip_hostremoval
trimmed_map_virus
trimmed_map_bact
trimmed_map_fungi }
trimmed_fastqc_multiqc_global = Channel.fromPath("NONE_trimmedfastqc_global")
fastp_multiqc_global = Channel.fromPath("NONE_fastp_global")
nofile_path_trimmed_fastqc = Channel.fromPath("NONE_trimmedfastqc")
nofile_path_fastp = Channel.fromPath("NONE_fastp")
nofile_path_control_coverage = Channel.fromPath("NONE_control_coverage")
control_results_template.combine(nofile_path_control_coverage).set { control_coverage_results }
samplechannel_trim_fastqc.combine(nofile_path_fastp).set { fastp_multiqc }
samplechannel_trimmed_fastqc.combine(nofile_path_trimmed_fastqc).set { trimmed_fastqc_multiqc }
}
if (params.kraken_scouting || params.translated_analysis) {
if (params.kraken2_db.endsWith('.gz') || params.kraken2_db.endsWith('.tar') || params.kraken2_db.endsWith('.tgz')) {
Channel.fromPath(params.kraken2_db).set { kraken2_compressed }
process UNCOMPRESS_KRAKEN2DB {
label 'error_retry'
input:
path(database) from kraken2_compressed
output:
path("kraken2db") into kraken2_db_files
script:
"""
tar -zxf $database
if [ -f "hash.k2d" ];
then
mkdir kraken2db
mv *.k2d kraken2db
mv *.kmer_distrib kraken2db
mv seqid2taxid.map kraken2db
mv inspect.txt kraken2db
mv README_assembly_summary.txt kraken2db
else
mv */ kraken2db
fi
"""
}
} else {
Channel.fromPath(params.kraken2_db).set { kraken2_db_files }
}
process SCOUT_KRAKEN2 {
tag "$samplename"
label "process_high"
input:
tuple val(samplename), val(single_end), path(reads), path(kraken2db) from trimmed_kraken2.combine(kraken2_db_files)
output:
tuple val(samplename), path("*.report") into kraken2_report_virus_references, kraken2_report_bacteria_references, kraken2_report_fungi_references
tuple val(samplename), path("*.krona") into kraken2_krona
tuple val(samplename), path("*.report"), path("*.kraken") into kraken2_host
tuple val(samplename), val(single_end), file("*_unclassified.fastq") into unclassified_reads
script:
paired_end = single_end ? "" : "--paired"
unclass_name = single_end ? "${samplename}_unclassified.fastq" : "${samplename}_#_unclassified.fastq"
"""
kraken2 --db $kraken2db \\
${paired_end} \\
--threads $task.cpus \\
--report ${samplename}.report \\
--output ${samplename}.kraken \\
--unclassified-out ${unclass_name} \\
${reads}
cat ${samplename}.kraken | cut -f 2,3 > results.krona
"""
}
if (params.kraken_scouting) {
process KRONA_DB {
output:
path("taxonomy/") into krona_taxonomy_db_kraken
script:
"""
ktUpdateTaxonomy.sh taxonomy
"""
}
process KRONA_KRAKEN_RESULTS {
tag "$samplename"
label "process_medium"
publishDir "${params.outdir}/${samplename}/kraken2_krona_results", mode: params.publish_dir_mode
input:
tuple val(samplename), path(kronafile), path(taxonomy) from kraken2_krona.combine(krona_taxonomy_db_kraken)
output:
tuple val(samplename), path("*.krona.html") into krona_scouting_results
script:
outfile = "${samplename}_kraken.krona.html"
"""
ktImportTaxonomy $kronafile -tax $taxonomy -o $outfile
"""
}
}
if (params.host_removal) {
process REMOVE_HOST_KRAKEN2 {
tag "$samplename"
label "process_medium"
input:
tuple val(samplename), val(single_end), path(reads), path(report), path(output) from trimmed_paired_extract_host.join(kraken2_host_extraction)
output:
tuple val(samplename), val(single_end), path("*_host_extracted.fastq") into reads_for_assembly
script:
read = single_end ? "-s ${reads}" : "-s1 ${reads[0]} -s2 ${reads[1]}"
outputfile = single_end ? "--output $mergedfile" : "-o ${samplename}_1_host_extracted.fastq -o2 ${samplename}_2_host_extracted.fastq"
mergedfile = single_end ? "${samplename}_host_extracted.fastq": "${samplename}_merged.fastq"
merge_outputfile = single_end ? "" : "cat *_host_extracted.fastq > $mergedfile"
"""
extract_kraken_reads.py \\
-k $output \\
-r $report \\
--exclude \\
--taxid ${params.host_taxid} \\
--fastq-output \\
$read \\
$outputfile
$merge_outputfile
"""
}
} else {
trimmed_skip_hostremoval.set { reads_for_assembly }
}
} else {
Channel.fromPath("NONE_krona").set { nofile_path_krona }
samplechannel_krona.combine(nofile_path_krona).set { krona_scouting_results }
}
if (params.virus) {
Channel.fromPath(params.vir_dir_repo).into { virus_datasheet_coverage
virus_datasheet_len
virus_datasheet_selection
virus_datasheet_group_by_species }
if (params.vir_ref_dir.endsWith('.gz') || params.vir_ref_dir.endsWith('.tar') || params.vir_ref_dir.endsWith('.tgz')) {
process UNCOMPRESS_VIRUS_REF {
label 'error_retry'
input:
path(ref_vir) from params.vir_ref_dir
output:
path("viralrefs") into virus_ref_directory, virus_references
script:
"""
mkdir "viralrefs"
tar -xvf $ref_vir --strip-components=1 -C "viralrefs"
"""
}
} else {
Channel.fromPath(params.vir_ref_dir).into { virus_ref_directory
virus_references }
}
process MASH_GENERATE_REFERENCE_SKETCH_VIRUS {
label "process_high"
input:
path(ref) from virus_ref_directory
output:
path("*.msh") into reference_sketch_virus
script:
"""
find ${ref}/ -name "*" -type f > reference_list.txt
mash sketch -k 32 -s 5000 -o reference -l reference_list.txt
"""
}
process MASH_DETECT_VIRUS_REFERENCES {
tag "$samplename"
label "process_high"
input:
tuple val(samplename), val(single_end), path(reads), path(refsketch) from trimmed_virus.combine(reference_sketch_virus)
output:
tuple val(samplename), path(mashout) into mash_result_virus_references
script:
mashout = "mash_screen_results_virus_${samplename}.txt"
"""
echo -e "#Identity\tShared_hashes\tMedian_multiplicity\tP-value\tQuery_id\tQuery_comment" > $mashout
mash -w screen $refsketch $reads >> $mashout
"""
}
process SELECT_FINAL_VIRUS_REFERENCES {
tag "$samplename"
label "process_low"
publishDir "${params.outdir}/${samplename}/virus_coverage", mode: params.publish_dir_mode,
saveAs: { filename ->
if (filename.endsWith(".tsv")) filename
}
input:
tuple val(samplename), path(mashresult), path(refdir), path(datasheet_virus) from mash_result_virus_references.combine(virus_references).combine(virus_datasheet_selection)
output:
tuple val(samplename), path("Final_fnas/*") optional true into bowtie_virus_references
tuple val(samplename), path("not_found.tsv") optional true into failed_virus_samples
script:
"""
extract_significative_references.py $mashresult $refdir $datasheet_virus
"""
}
trimmed_map_virus.join(bowtie_virus_references).set { bowtie_virus_channel }
def rawlist_virus = bowtie_virus_channel.toList().get()
def bowtielist_virus = []
for (line in rawlist_virus) {
if (line[3] instanceof java.util.ArrayList){
last_list = line[3]
}
else {
last_list = [line[3]]
}
for (reference in last_list) {
def ref_slice = [line[0],line[1],line[2],reference]
bowtielist_virus.add(ref_slice)
}
}
def reads_virus_mapping = Channel.fromList(bowtielist_virus)
process BOWTIE2_MAPPING_VIRUS {
tag "${samplename} : ${reference_sequence}"
label "process_high"
input:
tuple val(samplename), val(single_end), path(reads), path(reference_sequence) from reads_virus_mapping
output:
tuple val(samplename), val(single_end), path("*sorted.bam") into bowtie_alingment_sam_virus, bowtie_alingment_bam_virus
tuple val(samplename), val(single_end), path("*sorted.bam"), path(reference_sequence) into ivar_virus
script:
samplereads = single_end ? "-U ${reads}" : "-1 ${reads[0]} -2 ${reads[1]}"
prefix = "${reference_sequence}_vs_${samplename}_virus"
"""
bowtie2-build \\
--seed 1 \\
--threads $task.cpus \\
$reference_sequence \\
"index"
bowtie2 \\
--threads $task.cpus \\
-x "index" \\
$samplereads | samtools view \\
-@ $task.cpus \\
-b \\
-h \\
-O BAM \\
-o "${prefix}.bam"
samtools sort \\
-@ $task.cpus \\
-o "${prefix}.sorted.bam" \\
"${prefix}.bam"
"""
}
process SAMTOOLS_BAM_FROM_SAM_VIRUS {
tag "${samplename} : ${reference_sequence}"
label "process_medium"
input:
tuple val(samplename), val(single_end), path(sortedbam) from bowtie_alingment_sam_virus
output:
tuple val(samplename), val(single_end), path("*.flagstat"), path("*.idxstats"), path("*.stats") into bam_stats_virus
script:
prefix = sortedbam.join()
"""
samtools index $sortedbam
samtools flagstat -O tsv $sortedbam > "${prefix}.flagstat"
samtools idxstats $sortedbam > "${prefix}.idxstats"
samtools stats $sortedbam > "${prefix}.stats"
"""
}
process IVAR_CONSENSUS_SEQUENCE {
tag "${samplename} : ${prefix}"
label "process_medium"
input:
tuple val(samplename), val(single_end), path(sortedbam), path(reference_sequence) from ivar_virus
output:
tuple val(samplename), path("*.fa") into ch_ivar_consensus
script:
prefix = sortedbam.join().minus("_virus.sorted.bam")
"""
if [[ $reference_sequence == **.gz ]]
then
gunzip -c $reference_sequence > fastaref
else
mv $reference_sequence fastaref
fi
samtools mpileup \\
--count-orphans \\
--no-BAQ \\