forked from bactopia/bactopia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.nf
executable file
·2252 lines (1801 loc) · 92.8 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
import groovy.json.JsonSlurper
import groovy.text.SimpleTemplateEngine
import groovy.util.FileNameByRegexFinder
import java.io.RandomAccessFile;
import java.util.zip.GZIPInputStream;
import java.nio.file.Path
import java.nio.file.Paths
import nextflow.util.SysHelper
PROGRAM_NAME = workflow.manifest.name
VERSION = workflow.manifest.version
// Adjust memory/cpu requests for standard profile only
MAX_MEMORY = ['standard', 'docker', 'singularity'].contains(workflow.profile) ? get_max_memory(params.max_memory).GB : (params.max_memory).GB
MAX_MEMORY_INT = MAX_MEMORY.toString().split(" ")[0]
MAX_CPUS = ['standard', 'docker', 'singularity'].contains(workflow.profile) ? get_max_cpus(params.cpus.toInteger()) : params.cpus.toInteger()
MAX_CPUS_75 = Math.round(MAX_CPUS * 0.75)
MAX_CPUS_50 = Math.round(MAX_CPUS * 0.50)
USING_MERGE = false
// Validate parameters
if (params.help || params.help_all || params.conda_help) print_usage();
if (params.nfdir) print_basedir();
if (params.nfdir) print_basedir();
if (params.available_datasets && params.datasets) print_available_datasets(params.datasets);
if (workflow.commandLine.trim().endsWith(workflow.scriptName)) print_usage();
if (params.example_fastqs) print_example_fastqs();
if (params.version) print_version();
run_type = check_input_params()
check_input_fastqs(run_type)
if (params.check_fastqs) print_check_fastqs(run_type);
// Setup output directories
outdir = params.outdir ? params.outdir : './'
// Setup some defaults
log.info "${PROGRAM_NAME} - ${VERSION}"
AMR_DATABASES = []
ARIBA_DATABASES = []
MINMER_DATABASES = []
MLST_DATABASES = []
REFERENCES = []
PRIMERS = []
BLAST_GENE_FASTAS = []
BLAST_PRIMER_FASTAS = []
BLAST_PROTEIN_FASTAS = []
MAPPING_FASTAS = []
PROKKA_PROTEINS = file(params.empty_proteins)
PRODIGAL_TF = file(params.empty_tf)
REFSEQ_SKETCH = []
REFSEQ_SKETCH_FOUND = false
SPECIES = format_species(params.species)
SPECIES_GENOME_SIZE = null
print_efficiency()
setup_datasets()
process gather_fastqs {
/* Gather up input FASTQs for analysis. */
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "bactopia.versions"
publishDir "${outdir}/${sample}", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: '*.txt'
tag "${sample}"
input:
set val(sample), val(sample_type), val(single_end), file(r1: '*???-r1'), file(r2: '*???-r2'), file(extra) from create_input_channel(run_type)
output:
file "*-error.txt" optional true
set val(sample), val(final_sample_type), val(single_end),
file("fastqs/${sample}*.fastq.gz"), file("extra/*.gz") optional true into FASTQ_PE_STATUS
file "${task.process}/*" optional true
file "bactopia.versions" optional true
file "multiple-read-sets-merged.txt" optional true
shell:
bactopia_version = VERSION
nextflow_version = nextflow.version
is_assembly = sample_type.startsWith('assembly') ? true : false
is_compressed = false
no_cache = params.no_cache ? '-N' : ''
use_ena = params.use_ena
if (task.attempt >= 4) {
if (use_ena) {
// Try SRA
use_ena = false
} else {
// Try ENA
use_ena = true
}
}
if (extra) {
is_compressed = extra.getName().endsWith('gz') ? true : false
}
section = null
if (sample_type == 'assembly_accession') {
section = sample.startsWith('GCF') ? 'refseq' : 'genbank'
}
fcov = params.coverage.toInteger() == 0 ? 150 : Math.round(params.coverage.toInteger() * 1.5)
final_sample_type = sample_type
if (sample_type == 'hybrid-merge-pe') {
final_sample_type = 'hybrid'
} else if (sample_type == 'merge-pe') {
final_sample_type = 'paired-end'
} else if (sample_type == 'merge-se') {
final_sample_type = 'single-end'
}
template(task.ext.template)
}
process fastq_status {
/* Determine if FASTQs are PE or SE, and if they meet minimum basepair/read counts. */
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: '*.txt'
input:
set val(sample), val(sample_type), val(single_end), file(fq), file(extra) from FASTQ_PE_STATUS
output:
file "*-error.txt" optional true
set val(sample), val(sample_type), val(single_end),
file("fastqs/${sample}*.fastq.gz"), file(extra) optional true into ESTIMATE_GENOME_SIZE
file "${task.process}/*" optional true
shell:
single_end = fq[1] == null ? true : false
qin = sample_type.startsWith('assembly') ? 'qin=33' : 'qin=auto'
template(task.ext.template)
}
process estimate_genome_size {
/* Estimate the input genome size if not given. */
tag "${sample}"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: '*.txt'
input:
set val(sample), val(sample_type), val(single_end), file(fq), file(extra) from ESTIMATE_GENOME_SIZE
output:
file "${sample}-genome-size-error.txt" optional true
file("${sample}-genome-size.txt") optional true
set val(sample), val(sample_type), val(single_end),
file("fastqs/${sample}*.fastq.gz"), file(extra), file("${sample}-genome-size.txt") optional true into QC_READS, QC_ORIGINAL_SUMMARY
file "${task.process}/*" optional true
shell:
genome_size = SPECIES_GENOME_SIZE
template(task.ext.template)
}
process qc_reads {
/* Cleanup the reads using Illumina-Cleanup */
tag "${sample}"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "quality-control/*"
publishDir "${outdir}/${sample}", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "*error.txt"
input:
set val(sample), val(sample_type), val(single_end), file(fq), file(extra), file(genome_size) from QC_READS
output:
file "*-error.txt" optional true
file "quality-control/*"
set val(sample), val(single_end),
file("quality-control/${sample}*.fastq.gz") optional true into COUNT_31MERS, ARIBA_ANALYSIS,
MINMER_SKETCH, CALL_VARIANTS,
MAPPING_QUERY
set val(sample), val(sample_type), val(single_end),
file("quality-control/${sample}*.fastq.gz"), file(extra),
file(genome_size) optional true into ASSEMBLY
set val(sample), val(single_end),
file("quality-control/${sample}*.{fastq,error-fq}.gz"),
file(genome_size) optional true into QC_FINAL_SUMMARY
file "${task.process}/*" optional true
shell:
qc_ram = task.memory.toString().split(' ')[0]
is_assembly = sample_type.startsWith('assembly') ? true : false
qin = sample_type.startsWith('assembly') ? 'qin=33' : 'qin=auto'
adapters = params.adapters ? file(params.adapters) : 'adapters'
phix = params.phix ? file(params.phix) : 'phix'
template(task.ext.template)
}
process qc_original_summary {
/* Run FASTQC on the input FASTQ files. */
tag "${sample}"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "quality-control/*"
input:
set val(sample), val(sample_type), val(single_end), file(fq), file(extra), file(genome_size) from QC_ORIGINAL_SUMMARY
output:
file "quality-control/*"
file "${task.process}/*" optional true
shell:
template(task.ext.template)
}
process qc_final_summary {
/* Run FASTQC on the cleaned up FASTQ files. */
tag "${sample}"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "quality-control/*"
input:
set val(sample), val(single_end), file(fq), file(genome_size) from QC_FINAL_SUMMARY
output:
file "quality-control/*"
file "${task.process}/*" optional true
shell:
template(task.ext.template)
}
process assemble_genome {
/* Assemble the genome using Shovill, SKESA is used by default */
tag "${sample}"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "assembly/*"
publishDir "${outdir}/${sample}", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${sample}-assembly-error.txt"
input:
set val(sample), val(sample_type), val(single_end), file(fq), file(extra), file(genome_size) from ASSEMBLY
output:
file "assembly/*"
file "${sample}-assembly-error.txt" optional true
set val(sample), val(single_end), file("fastqs/${sample}*.fastq.gz"), file("assembly/${sample}.{fna,fna.gz}") optional true into SEQUENCE_TYPE
set val(sample), val(single_end), file("assembly/${sample}.{fna,fna.gz}") optional true into MAKE_BLASTDB
set val(sample), val(single_end), file("fastqs/${sample}*.fastq.gz"), file("assembly/${sample}.{fna,fna.gz}"), file("total_contigs_*") optional true into ANNOTATION
set val(sample), file("assembly/${sample}.{fna,fna.gz}"), file(genome_size) optional true into ASSEMBLY_QC
file "${task.process}/*" optional true
shell:
contig_namefmt = params.contig_namefmt ? params.contig_namefmt : "${sample}_%05d"
shovill_ram = task.memory.toString().split(' ')[0]
opts = params.shovill_opts ? "--opts '${params.shovill_opts}'" : ""
kmers = params.shovill_kmers ? "--kmers '${params.shovill_kmers}'" : ""
nostitch = params.nostitch ? "--nostitch" : ""
nocorr = params.nocorr ? "--nocorr" : ""
no_miniasm = params.no_miniasm ? "--no_miniasm" : ""
no_rotate = params.no_rotate ? "--no_rotate" : ""
no_pilon = params.no_pilon ? "--no_pilon" : ""
keep = params.keep_all_files ? "--keep 3" : "--keep 1"
use_original_assembly = null
if (sample_type.startsWith('assembly')) {
use_original_assembly = params.reassemble ? false : true
}
template(task.ext.template)
}
process assembly_qc {
/* Assess the quality of the assembly using QUAST and CheckM */
tag "${sample} - ${method}"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}/assembly", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${method}/*"
input:
set val(sample), file(fasta), file(genome_size) from ASSEMBLY_QC
each method from Channel.fromList(['checkm', 'quast'])
output:
file "${method}/*"
file "${task.process}/*" optional true
shell:
//CheckM Related
full_tree = params.full_tree ? '' : '--reduced_tree'
checkm_ali = params.checkm_ali ? '--ali' : ''
checkm_nt = params.checkm_nt ? '--nt' : ''
force_domain = params.force_domain ? '--force_domain' : ''
no_refinement = params.no_refinement ? '--no_refinement' : ''
individual_markers = params.individual_markers ? '--individual_markers' : ''
skip_adj_correction = params.skip_adj_correction ? '--skip_adj_correction' : ''
skip_pseudogene_correction = params.skip_pseudogene_correction ? '--skip_pseudogene_correction' : ''
ignore_thresholds = params.ignore_thresholds ? '--ignore_thresholds' : ''
template(task.ext.template)
}
process make_blastdb {
/* Create a BLAST database of the assembly using BLAST */
tag "${sample}"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}/blast", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "blastdb/*"
input:
set val(sample), val(single_end), file(fasta) from MAKE_BLASTDB
output:
file("blastdb/*")
set val(sample), file("blastdb/*") into BLAST_GENES, BLAST_PRIMERS, BLAST_PROTEINS
file "${task.process}/*" optional true
shell:
template(task.ext.template)
}
process annotate_genome {
/* Annotate the assembly using Prokka, use a proteins FASTA if available */
tag "${sample}"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "annotation/${sample}*"
input:
set val(sample), val(single_end), file(fq), file(fasta), file(total_contigs) from ANNOTATION
file prokka_proteins from PROKKA_PROTEINS
file prodigal_tf from PRODIGAL_TF
output:
file "annotation/${sample}*"
set val(sample),
file("annotation/${sample}.{ffn,ffn.gz}"),
file("annotation/${sample}.{faa,faa.gz}") optional true into ANTIMICROBIAL_RESISTANCE
file "${task.process}/*" optional true
shell:
gunzip_fasta = fasta.getName().replace('.gz', '')
contig_count = total_contigs.getName().replace('total_contigs_', '')
genus = "Genus"
species = "species"
proteins = ""
if (prokka_proteins.getName() != 'EMPTY_PROTEINS') {
proteins = "--proteins ${prokka_proteins}"
if (SPECIES.contains("-")) {
genus = SPECIES.split('-')[0].capitalize()
species = SPECIES.split('-')[1]
} else {
genus = SPECIES.capitalize()
species = "spp."
}
}
prodigal = ""
if (prodigal_tf.getName() != 'EMPTY_TF' && !params.skip_prodigal_tf) {
prodigal = "--prodigaltf ${prodigal_tf}"
}
compliant = params.compliant ? "--compliant" : ""
locustag = "--locustag ${sample}"
renamed = false
// Contig ID must <= 37 characters
if ("gnl|${params.centre}|${sample}_${contig_count}".length() > 37) {
locustag = ""
compliant = "--compliant"
renamed = true
}
addgenes = params.nogenes ? "" : "--addgenes"
addmrna = params.addmrna ? "--addmrna" : ""
rawproduct = params.rawproduct ? "--rawproduct" : ""
cdsrnaolap = params.cdsrnaolap ? "--cdsrnaolap" : ""
norrna = params.norrna ? "--norrna" : ""
notrna = params.notrna ? "--notrna" : ""
rnammer = params.rnammer ? "--rnammer" : ""
rfam = params.rnammer ? "--rfam" : ""
template(task.ext.template)
}
process count_31mers {
/* Count 31mers in the reads using McCortex */
tag "${sample}"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}/kmers", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "*.ctx"
input:
set val(sample), val(single_end), file(fq) from COUNT_31MERS
output:
file "${sample}.ctx"
file "${task.process}/*" optional true
shell:
m = task.memory.toString().split(' ')[0].toInteger() * 1000 - 500
template(task.ext.template)
}
process sequence_type {
/* Determine MLST types using ARIBA and BLAST */
tag "${sample} - ${schema} - ${method}"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}/mlst/${schema}", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${method}/*"
input:
set val(sample), val(single_end), file(fq), file(assembly) from SEQUENCE_TYPE
each file(dataset) from MLST_DATABASES
output:
file "${method}/*"
file "${task.process}/*" optional true
when:
MLST_DATABASES.isEmpty() == false
shell:
method = dataset =~ /.*blastdb.*/ ? 'blast' : 'ariba'
dataset_tarball = file(dataset).getName()
dataset_name = dataset_tarball.replace('.tar.gz', '').split('-')[1]
schema = dataset_tarball.split('-')[0]
noclean = params.ariba_no_clean ? "--noclean" : ""
spades_options = params.spades_options ? "--spades_options '${params.spades_options}'" : ""
template(task.ext.template)
}
process ariba_analysis {
/* Run reads against all available (if any) ARIBA datasets */
tag "${sample} - ${dataset_name}"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}/ariba", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${dataset_name}/*"
input:
set val(sample), val(single_end), file(fq) from ARIBA_ANALYSIS
each file(dataset) from ARIBA_DATABASES
output:
file "${dataset_name}/*"
file "${task.process}/*" optional true
when:
single_end == false && ARIBA_DATABASES.isEmpty() == false
shell:
dataset_tarball = file(dataset).getName()
dataset_name = dataset_tarball.replace('.tar.gz', '')
spades_options = params.spades_options ? "--spades_options '${params.spades_options}'" : ""
noclean = params.ariba_no_clean ? "--noclean" : ""
template(task.ext.template)
}
process minmer_sketch {
/*
Create minmer sketches of the input FASTQs using Mash (k=21,31) and
Sourmash (k=21,31,51)
*/
tag "${sample}"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}/minmers", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "*.{msh,sig}"
input:
set val(sample), val(single_end), file(fq) from MINMER_SKETCH
output:
file("${sample}*.{msh,sig}")
set val(sample), val(single_end), file("fastqs/${sample}*.fastq.gz"), file("${sample}.sig") into MINMER_QUERY
set val(sample), val(single_end), file("fastqs/${sample}*.fastq.gz"), file("${sample}-k31.msh") into DOWNLOAD_REFERENCES
file "${task.process}/*" optional true
shell:
fastq = single_end ? fq[0] : "${fq[0]} ${fq[1]}"
template(task.ext.template)
}
process minmer_query {
/*
Query minmer sketches against pre-computed RefSeq (Mash, k=21) and
GenBank (Sourmash, k=21,31,51)
*/
tag "${sample} - ${dataset_name}"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}/minmers", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "*.txt"
input:
set val(sample), val(single_end), file(fq), file(sourmash) from MINMER_QUERY
each file(dataset) from MINMER_DATABASES
output:
file "*.txt"
file "${task.process}/*" optional true
when:
MINMER_DATABASES.isEmpty() == false
shell:
dataset_name = dataset.getName()
mash_w = params.screen_w ? "-w" : ""
fastq = single_end ? fq[0] : "${fq[0]} ${fq[1]}"
template(task.ext.template)
}
process call_variants {
/*
Identify variants (SNPs/InDels) against a set of reference genomes
using Snippy.
*/
tag "${sample} - ${reference_name}"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}/variants/user", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${reference_name}/*"
input:
set val(sample), val(single_end), file(fq) from CALL_VARIANTS
each file(reference) from REFERENCES
output:
file "${reference_name}/*"
file "${task.process}/*" optional true
when:
REFERENCES.isEmpty() == false
shell:
snippy_ram = task.memory.toString().split(' ')[0]
reference_name = reference.getSimpleName()
fastq = single_end ? "--se ${fq[0]}" : "--R1 ${fq[0]} --R2 ${fq[1]}"
bwaopt = params.bwaopt ? "--bwaopt 'params.bwaopt'" : ""
fbopt = params.fbopt ? "--fbopt 'params.fbopt'" : ""
template(task.ext.template)
}
process download_references {
/*
Download the nearest RefSeq genomes (based on Mash) to have variants called against.
Exitcode 75 is due to being unable to download from NCBI (e.g. FTP down at the time)
Downloads will be attempted 300 times total before giving up. On failure to download
variants will not be called against the nearest completed genome.
*/
tag "${sample} - ${params.max_references} reference(s)"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}/variants/auto", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: 'mash-dist.txt'
input:
set val(sample), val(single_end), file(fq), file(sample_sketch) from DOWNLOAD_REFERENCES
file(refseq_sketch) from REFSEQ_SKETCH
output:
set val(sample), val(single_end), file("fastqs/${sample}*.fastq.gz"), file("genbank/*.gbk") optional true into CALL_VARIANTS_AUTO
file("mash-dist.txt")
file "${task.process}/*" optional true
when:
REFSEQ_SKETCH_FOUND == true
shell:
no_cache = params.no_cache ? '-N' : ''
tie_break = params.random_tie_break ? "--random_tie_break" : ""
total = params.max_references
template(task.ext.template)
}
process call_variants_auto {
/*
Identify variants (SNPs/InDels) against one or more reference genomes selected based
on their Mash distance from the input.
*/
tag "${sample} - ${reference_name}"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}/variants/auto", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${reference_name}/*"
input:
set val(sample), val(single_end), file(fq), file(reference) from create_reference_channel(CALL_VARIANTS_AUTO)
output:
file "${reference_name}/*"
file "${task.process}/*" optional true
shell:
snippy_ram = task.memory.toString().split(' ')[0]
reference_name = reference.getBaseName().split("${sample}-")[1].split(/\./)[0]
fastq = single_end ? "--se ${fq[0]}" : "--R1 ${fq[0]} --R2 ${fq[1]}"
bwaopt = params.bwaopt ? "--bwaopt 'params.bwaopt'" : ""
fbopt = params.fbopt ? "--fbopt 'params.fbopt'" : ""
template(task.ext.template)
}
process antimicrobial_resistance {
/*
Query nucleotides and proteins (SNPs/InDels) against one or more reference genomes selected based
on their Mash distance from the input.
*/
tag "${sample}"
publishDir "${outdir}/${sample}", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "logs/*"
publishDir "${outdir}/${sample}", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${amrdir}/*"
input:
set val(sample), file(genes), file(proteins) from ANTIMICROBIAL_RESISTANCE
each file(amrdb) from AMR_DATABASES
output:
file "${amrdir}/*"
file "logs/*" optional true
shell:
amrdir = "antimicrobial-resistance"
plus = params.amr_plus ? "--plus" : ""
report_common = params.amr_report_common ? "--report_common" : ""
organism_gene = ""
organism_protein = ""
if (params.amr_organism) {
organism_gene = "-O ${params.amr_organism} --point_mut_all ${amrdir}/${sample}-gene-point-mutations.txt"
organism_protein = "-O ${params.amr_organism} --point_mut_all ${amrdir}/${sample}-protein-point-mutations.txt"
}
template(task.ext.template)
}
process blast_genes {
/*
Query gene FASTA files against annotated assembly using BLAST
*/
tag "${sample}"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}/blast", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "genes/*.{json,json.gz}"
input:
set val(sample), file(blastdb) from BLAST_GENES
file(query) from Channel.from(BLAST_GENE_FASTAS).collect()
output:
file("genes/*.{json,json.gz}")
file "${task.process}/*" optional true
when:
BLAST_GENE_FASTAS.isEmpty() == false
shell:
template(task.ext.template)
}
process blast_primers {
/*
Query primer FASTA files against annotated assembly using BLAST
*/
tag "${sample}"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}/blast", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "primers/*.{json,json.gz}"
input:
set val(sample), file(blastdb) from BLAST_PRIMERS
file(query) from Channel.from(BLAST_PRIMER_FASTAS).collect()
output:
file("primers/*.{json,json.gz}")
file "${task.process}/*" optional true
when:
BLAST_PRIMER_FASTAS.isEmpty() == false
shell:
template(task.ext.template)
}
process blast_proteins {
/*
Query protein FASTA files against annotated assembly using BLAST
*/
tag "${sample}"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}/blast", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "proteins/*.{json,json.gz}"
input:
set val(sample), file(blastdb) from BLAST_PROTEINS
file(query) from Channel.from(BLAST_PROTEIN_FASTAS).collect()
output:
file("proteins/*.{json,json.gz}")
file "${task.process}/*" optional true
when:
BLAST_PROTEIN_FASTAS.isEmpty() == false
shell:
template(task.ext.template)
}
process mapping_query {
/*
Map FASTQ reads against a given set of FASTA files using BWA.
*/
tag "${sample}}"
publishDir "${outdir}/${sample}/logs", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "${task.process}/*"
publishDir "${outdir}/${sample}", mode: "${params.publish_mode}", overwrite: params.overwrite, pattern: "mapping/*"
input:
set val(sample), val(single_end), file(fq) from MAPPING_QUERY
file(query) from Channel.from(MAPPING_FASTAS).collect()
output:
file "mapping/*"
file "${task.process}/*" optional true
when:
MAPPING_FASTAS.isEmpty() == false
shell:
bwa_mem_opts = params.bwa_mem_opts ? params.bwa_mem_opts : ""
bwa_aln_opts = params.bwa_aln_opts ? params.bwa_aln_opts : ""
bwa_samse_opts = params.bwa_samse_opts ? params.bwa_samse_opts : ""
bwa_sampe_opts = params.bwa_sampe_opts ? params.bwa_sampe_opts : ""
template(task.ext.template)
}
workflow.onComplete {
workDir = new File("${workflow.workDir}")
workDirSize = toHumanString(workDir.directorySize())
println """
Bactopia Execution Summary
---------------------------
Command Line : ${workflow.commandLine}
Resumed : ${workflow.resume}
Completed At : ${workflow.complete}
Duration : ${workflow.duration}
Success : ${workflow.success}
Exit Code : ${workflow.exitStatus}
Error Report : ${workflow.errorReport ?: '-'}
Launch Dir : ${workflow.launchDir}
Working Dir : ${workflow.workDir} (Total Size: ${workDirSize})
Working Dir Size: ${workDirSize}
"""
}
// Utility functions
def toHumanString(bytes) {
// Thanks Niklaus
// https://gist.github.com/nikbucher/9687112
base = 1024L
decimals = 3
prefix = ['', 'K', 'M', 'G', 'T']
int i = Math.log(bytes)/Math.log(base) as Integer
i = (i >= prefix.size() ? prefix.size()-1 : i)
return Math.round((bytes / base**i) * 10**decimals) / 10**decimals + prefix[i]
}
def print_version() {
println(PROGRAM_NAME + ' ' + VERSION)
exit 0
}
def print_basedir() {
println("BACTOPIA_DIR = ${baseDir}")
exit 0
}
def print_example_fastqs() {
log.info """
Printing example input for "--fastqs"
sample runtype r1 r2 extra
SA103113 assembly /example/SA103113.fna.gz
SA110685 hybrid /example/SA110685_R1.fastq.gz /example/SA110685_R2.fastq.gz /example/SA110685.fastq.gz
SA123186 paired-end /example/SA123186_R1.fastq.gz /example/SA123186_R2.fastq.gz
SA123456 single-end /example/SA12345.fastq.gz
""".stripIndent()
exit 0
}
def print_check_fastqs(run_type) {
if (run_type == "fastqs") {
log.info 'Printing what would have been processed. Each line consists of an array of'
log.info 'five elements: [SAMPLE_NAME, RUNTYPE, IS_SINGLE_END, [FASTQ_1], [FASTQ_2], EXTRA]'
log.info ''
log.info 'Found:'
create_input_channel(run_type).view()
log.info ''
exit 0
} else {
log.error '"--check_fastqs" requires "--fastqs" to be set.'
exit 1
}
}
def print_available_datasets(dataset) {
exit_code = 0
if (dataset) {
if (file("${dataset}/summary.json").exists()) {
available_datasets = read_json("${dataset}/summary.json")
log.info 'Printing the available pre-configured dataset.'
log.info "Database Location (--datasets): ${dataset}"
log.info ''
if (available_datasets.size() > 0) {
IGNORE = ['species-specific']
GENERAL = ['ariba', 'minmer']
available_datasets.each { key, value ->
if (GENERAL.contains(key) == 'ariba') {
log.info "${key.capitalize()}"
value.each {
log.info "\tFound ${it}"
}
} else if (key == 'species-specific') {
value.each { species, sets ->
log.info "${species.capitalize().replace('-', ' ')} (use --species \"${species}\")"
sets.each { set_name, set_path ->
if (set_name == 'optional') {
log.info "\tOptional:"
set_path.each {
log.info "\t\tFound ${it}"
}
} else {
log.info "\tFound ${set_name}=${set_path}"
}
}
log.info ''
}
} else {
log.info "${key.capitalize()}"
value.each {
log.info "\tFound ${it}"
}
}
log.info ''
}
}
} else {
log.error "Please verify the PATH is correct and ${dataset}/summary.json" +
" exists, if not try rerunning 'bactopia datasets'."
exit_code = 1
}
} else {
log.error "Please use '--datasets' to specify the path to pre-built datasets."
exit_code = 1
}
exit exit_code
}
def read_json(json_file) {
slurp = new JsonSlurper()
return slurp.parseText(file(json_file).text)
}
def format_species(species) {
/* Format species name to accepted format. */
name = false
if (species) {
name = species.toLowerCase()
if (species.contains(" ")) {
name = name.replace(" ", "-")
}
}
return name
}
def get_max_memory(requested) {
available = Math.floor(Double.parseDouble(SysHelper.getAvailMemory().toString().split(" ")[0])).toInteger()
if (available < requested) {
log.warn "Maximum memory (${requested}) was adjusted to fit your system (${available})"
return available
}
return requested
}
def get_max_cpus(requested) {
available = SysHelper.getAvailCpus()
if (available < requested) {
log.warn "Maximum CPUs (${requested}) was adjusted to fit your system (${available})"
return available
}
return requested
}
def dataset_exists(dataset_path) {
if (file(dataset_path).exists()) {
return true
} else {
log.warn "Warning: ${dataset_path} does not exist and will not be used for analysis."
}
}
def setup_datasets() {
genome_size = ['min': 0, 'median': 0, 'mean': 0, 'max': 0]
if (params.datasets) {
dataset_path = params.datasets
available_datasets = read_json("${dataset_path}/summary.json")
// Antimicrobial Resistance Datasets
if (params.skip_amr) {
log.info "Found '--skip_amr', datasets for AMRFinder+ will not be used for analysis."
} else {
if (available_datasets.containsKey('antimicrobial-resistance')) {
available_datasets['antimicrobial-resistance'].each {
if (dataset_exists("${dataset_path}/antimicrobial-resistance/${it.name}")) {
AMR_DATABASES << file("${dataset_path}/antimicrobial-resistance/${it.name}")
}
}
print_dataset_info(AMR_DATABASES, "Antimicrobial resistance datasets")
}
}
// Ariba Datasets
if (available_datasets.containsKey('ariba')) {
available_datasets['ariba'].each {
if (dataset_exists("${dataset_path}/ariba/${it.name}")) {
ARIBA_DATABASES << file("${dataset_path}/ariba/${it.name}")
}
}
print_dataset_info(ARIBA_DATABASES, "ARIBA datasets")
}
// RefSeq/GenBank Check
if (available_datasets.containsKey('minmer')) {
if (available_datasets['minmer'].containsKey('sketches')) {
available_datasets['minmer']['sketches'].each {
if (dataset_exists("${dataset_path}/minmer/${it}")) {
MINMER_DATABASES << file("${dataset_path}/minmer/${it}")
}
}
}
}
print_dataset_info(MINMER_DATABASES, "minmer sketches/signatures")
if (SPECIES) {
if (available_datasets.containsKey('species-specific')) {
if (available_datasets['species-specific'].containsKey(SPECIES)) {
species_db = available_datasets['species-specific'][SPECIES]
if (species_db.containsKey('genome_size')) {
genome_size = species_db['genome_size']
}
if (params.genome_size) {
if (['min', 'median', 'mean', 'max'].contains(params.genome_size)) {
SPECIES_GENOME_SIZE = genome_size[params.genome_size]
} else {
SPECIES_GENOME_SIZE = params.genome_size
}
if (SPECIES_GENOME_SIZE > 0) {
log.info "Will use ${SPECIES_GENOME_SIZE} bp for genome size"
} else if (SPECIES_GENOME_SIZE == 0) {
log.info "Found ${SPECIES_GENOME_SIZE} bp for genome size, it will be estimated."
}
} else {
SPECIES_GENOME_SIZE = null
log.info "Genome size will be estimated."
}
if (species_db.containsKey('annotation')) {
if (species_db['annotation'].containsKey('proteins')) {
prokka = "${dataset_path}/${species_db['annotation']['proteins']}"
if (dataset_exists(prokka)) {
PROKKA_PROTEINS = file(prokka)
log.info "Found Prokka proteins file"
log.info "\t${PROKKA_PROTEINS}"
}
}
if (species_db['annotation'].containsKey('training_set')) {
prodigal_tf = "${dataset_path}/${species_db['annotation']['training_set']}"
if (dataset_exists(prodigal_tf)) {
PRODIGAL_TF = file(prodigal_tf)
log.info "Found Prodigal training file"
log.info "\t${PRODIGAL_TF}"
}
}
}
if (species_db.containsKey('minmer')) {