-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.nf
3208 lines (2461 loc) · 96.7 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
/*
============================================================================
NextITS: Pipeline to process fungal ITS amplicons
============================================================================
License: Apache-2.0
Github : https://github.com/vmikk/NextITS
Website: https://next-its.github.io/
----------------------------------------------------------------------------
*/
// NB!!:
// - provide absolute paths to the input data (e.g. --input and --barcodes)
// - File names should not contain period (.) characters (except for extensions)
// Databases:
// - UDB for chimera identification
// Enable DSL2 syntax
nextflow.enable.dsl = 2
// Pipeline help message
def helpMsg() {
log.info"""
=====================================================================
NextITS v.${workflow.manifest.version}
=====================================================================
Pipeline Usage:
To run the pipeline, enter the following in the command line:
nextflow run vmikk/nextits -r ${workflow.manifest.version} --input ... --outdir ...
Options:
REQUIRED:
--input File with single-end input sequences, PacBio (FASTQ) or a directory with pre-demultiplexed files
--input_R1 Files with paired-end input sequences, Illumina (FASTQ)
--input_R2
--barcodes Barcodes for demultiplexing (FASTA)
--outdir The output directory where the results will be saved
OPTIONAL:
--demultiplexed Boolean, input is multiplexed (true, single FASTQ file) or pre-demultiplexed (multiple FASTQ files)
--seqplatform Sequencing platform type - "PacBio" (default) or "Illumina"
--its_region ITS part selector - "full" (defalut), "ITS1", "ITS2", "none" (trims primers only), or "ITS1_5.8S_ITS2"
--primer_forward Forward primer sequence (default, ITS9mun)
--primer_reverse Reverse primer sequence (default, ITS4ngsUni)
--primer_mismatches
--primer_foverlap Min primer overlap (default, F primer length - 2)
--primer_roverlap Min primer overlap (default, R primer length - 2)
--qc_maxn Discard sequences with more than the specified number of N’s
--trim_minlen Min sequence length after primer trimming (default, 10)
--ITSx_tax ITSx taxonomy profile (default, "all")
--ITSx_evalue ITSx E-value cutoff threshold (default, 1e-1)
--ITSx_partial Keep partial ITS sequences (defalt, off), otherwise specify min length cutoff
--hp Homopolymer compression (default, true)
--hp_similarity Allowed sequence similarity for homopolymer compression (default, 0.999)
--hp_iddef Sequence similarity definition for homopolymer compression (default, 2)
# Chimera identification
--chimera_db Database for reference-based chimera removal
--chimera_rescueoccurrence Min occurrence of chimeric sequences required to rescue them (default, 2)
--chimeranov_abskew De novo chimera identification `abskew` parameter (default, 2.0)
--chimeranov_dn De novo chimera identification `dn` parameter (default, 1.4)
--chimeranov_mindiffs De novo chimera identification `mindiffs` parameter (default, 3)
--chimeranov_mindiv De novo chimera identification `mindiv` parameter (default, 0.8)
--chimeranov_minh De novo chimera identification `minh` parameter (default, 0.28)
--chimeranov_xn De novo chimera identification `xn` parameter (default, 8.0)
# Tag-jump removal
--tj_f Tag-jump filtering, UNCROSS parameter `f` (default, 0.01)
--tj_p Tag-jump filtering parameter `p` (default, 1)
--otu_id Sequence similarity for OTU clustering (default, 0.98)
--otu_iddef Sequence similarity definition for tag-jump removal step (default, 2)
# PacBio-specific parameters
--lima_barcodetype Tag type ("single", "dual", "dual_symmetric", "dual_asymmetric")
--lima_minscore Minimum barcode score for demultiplexing (default, 93)
--lima_minendscore Minimum second barcode score (only for asymmetric and dual barcoding scheme; default, 50)
--lima_minrefspan Minimum read span relative to the barcode length (0-1; default, 0.75)
--lima_minscoringregions Number of barcodes scored required for demultiplexing using dual barcodes (default, 2 = requires both barcodes)
--lima_windowsize Window size for barcode lookup (default, 70 bp)
--lima_minlen Minimum sequence length after clipping barcodes (default, 40)
--qc_maxee Maximum number of expected errors (default, false)
--qc_maxeerate Maximum number of expected errors per base (default, 0.01)
--qc_maxhomopolymerlen Threshold for a homopolymer region length in a sequence (default, 25)
# Illumina-specific parameters
--qc_avgphred Average Phred score for QC (default, false)
--qc_twocolor Enable two-color chemistry mode, e.g. for Illumina NovaSeq (default, false)
--qc_phredmin Two-color mode: min Phred score of qualified bases (default, 24)
--qc_phredperc Two-color mode: Percentage of bases allowed to be unqualified (default, 30)
--qc_polyglen Two-color mode: minimum length of polyG tail (default, 8)
--barcode_window Window size for barcode lookup (default, 30 bp)
--barcode_errors Maximum allowed number of errors in barcodes (default, 1)
--barcode_overlap Min overlap between read and barcode (default, 11)
--pe_minoverlap Min length to detect overlapped region of PE reads (default, 20)
--pe_difflimit Max number of mismatched bases in PE overlap (default, 5)
--pe_diffperclimit Max percentage of mismatched bases in PE overlap (default, 20)
--pe_minlen Min length of merged sequences (default, 30)
--illumina_keep_notmerged Keep not merged Illumina reads (default, true)
--illumina_joinpadgap Join not merged reads into one sequence using padding sequence string (default, NNNNNNNNNN)
--illumina_joinpadqual Join not merged reads into one sequence using padding quality string (default, IIIIIIIIII)
# Miscellaneous parameters
--gzip_compression Compression level for GZIP (default, 7; 1 = fastest (worst compression), 9 = slowest (best))
NEXTFLOW-SPECIFIC:
-profile Configuration profile
-resume Execute the pipeline using the cached results (e.g., in case of )
-work-dir Path to the directory where intermediate result files are stored
-qs Queue size (max number of processes that can be executed in parallel); e.g., 8
-r Pipeline version to run (GitHub branch, tag, or SHA number)
""".stripIndent()
}
// Show help msg
if (params.helpMsg){
helpMsg()
exit(0)
}
// Check if input path was provided
if (params.input == false && params.seqplatform == "PacBio") {
println( "Please provide the input file with sequences in FASTQ.gz format with `--input` parameter.")
exit(1)
}
if (params.input_R1 == false && params.input_R2 == false && params.seqplatform == "Illumina") {
println( "Please provide input files with sequences in FASTQ.gz format with `--input_R1` and `--input_R2` parameters.")
exit(1)
}
if (params.barcodes == false && params.demultiplexed == false) {
println( "Please provide the file with sample barcodes in FASTA format with `--barcodes` parameter.")
exit(1)
}
if (params.chimera_db == false) {
println( "Please provide the UDB file with reference sequences for chimera removal with `--chimera_db` parameter.")
exit(1)
}
if (params.hp == true && params.seqplatform == "Illumina" && params.illumina_keep_notmerged == true) {
println( "Homopolymer compression is not implemented for Illumina non-merged reads.")
exit(1)
}
if (params.seqplatform == "Illumina" && params.demultiplexed == true) {
println( "Handling demultiplexed data for Illumina is not implemented yet.")
exit(1)
}
if (params.seqplatform == "Illumina" && params.illumina_keep_notmerged == true && params.its_region != "none") {
println( "WARNING: Unmerged Illumina reads are not compatible with ITSx. Amplicons will be primer-trimmed.")
}
// Print the parameters to the console and to the log
log.info """
=======================================================================
NextITS v.${workflow.manifest.version}
=======================================================================
Input data path: ${params.input}
Barcodes: ${params.barcodes}
Output path: ${params.outdir}
ITS region: ${params.its_region}
"""
.stripIndent()
log.info """
Pipeline info:
Pipeline profile: ${workflow.profile}
Config file used: ${workflow.configFiles}
Container engine: ${workflow.containerEngine}
"""
.stripIndent()
log.info """
Core Nextflow options:
launchDir: ${workflow.launchDir}
workDir: ${workflow.workDir}
projectDir: ${workflow.projectDir}
"""
.stripIndent()
log.info "======================================================================="
log.info "\n"
// Define output paths for different steps
out_1_demux = params.outdir + "/01_Demux"
out_1_joinPE = params.outdir + "/01_JoinedPE"
out_2_primer = params.outdir + "/02_PrimerCheck"
out_3_itsx = params.outdir + "/03_ITSx"
out_3_trim = params.outdir + "/03_PrimerTrim"
out_3_trimPE = params.outdir + "/03_PrimerTrim_NotMerged"
out_4_homop = params.outdir + "/04_Homopolymer"
out_5_chim = params.outdir + "/05_Chimera"
out_6_tj = params.outdir + "/06_TagJumpFiltration"
out_7_seq = params.outdir + "/07_SeqTable"
out_8_smr = params.outdir + "/08_RunSummary"
// Sub-workflow-specific outputs
out_3_quickstats = params.outdir + "/03_Stats"
// Quality filtering for single-end reads
process qc_se {
label "main_container"
// cpus 10
// Add file ID to the log file
tag "${input.getSimpleName()}"
input:
path input
output:
path "${input.getSimpleName()}.fq.gz", emit: filtered, optional: true
script:
filter_maxee = params.qc_maxee ? "--fastq_maxee ${params.qc_maxee}" : ""
filter_maxeerate = params.qc_maxeerate ? "--fastq_maxee_rate ${params.qc_maxeerate}" : ""
"""
echo -e "QC"
echo -e "Input file: " ${input}
## We do not need to change the file name (output name should be the same as input)
## Therefore, temporary rename input
mv ${input} inp.fq.gz
vsearch \
--fastq_filter inp.fq.gz \
--fastq_qmax 93 \
${filter_maxee} \
${filter_maxeerate} \
--fastq_maxns ${params.qc_maxn} \
--threads ${task.cpus} \
--fastqout - \
| seqkit grep \
--by-seq --ignore-case --invert-match --only-positive-strand --use-regexp -w 0 \
--pattern '"(A{${params.qc_maxhomopolymerlen},}|C{${params.qc_maxhomopolymerlen},}|T{${params.qc_maxhomopolymerlen},}|G{${params.qc_maxhomopolymerlen},})"' \
| gzip -${params.gzip_compression} \
> "${input.getSimpleName()}.fq.gz"
## qc_maxhomopolymerlen
# e.g. "(A{26,}|C{26,}|T{26,}|G{26,})"
echo -e "\nQC finished"
"""
}
// Quality filtering for pair-end reads
process qc_pe {
label "main_container"
// cpus 10
input:
path input_R1
path input_R2
output:
path "QC_R1.fq.gz", emit: filtered_R1
path "QC_R2.fq.gz", emit: filtered_R2
script:
filter_avgphred = params.qc_avgphred ? "--average_qual ${params.qc_avgphred}" : "--average_qual 0"
filter_phredmin = params.qc_phredmin ? "--qualified_quality_phred ${params.qc_phredmin}" : ""
filter_phredperc = params.qc_phredperc ? "--unqualified_percent_limit ${params.qc_phredperc}" : ""
filter_polyglen = params.qc_polyglen ? "--trim_poly_g --poly_g_min_len ${params.qc_polyglen}" : ""
"""
echo -e "QC"
echo -e "Input R1: " ${input_R1}
echo -e "Input R2: " ${input_R2}
## If `filter_phredmin` && `filter_phredperc` are specified,
# Filtering based on percentage of unqualified bases
# how many percents of bases are allowed to be unqualified (Q < 24)
fastp \
--in1 ${input_R1} \
--in2 ${input_R2} \
--disable_adapter_trimming \
--n_base_limit ${params.qc_maxn} \
${filter_avgphred} \
${filter_phredmin} \
${filter_phredperc} \
${filter_polyglen} \
--length_required 100 \
--thread ${task.cpus} \
--html qc.html \
--json qc.json \
--out1 QC_R1.fq.gz \
--out2 QC_R2.fq.gz
echo -e "\nQC finished"
"""
}
// Validate tags for demultiplexing
process tag_validation {
label "main_container"
// cpus 1
input:
path barcodes
output:
path "barcodes_validated.fasta", emit: fasta
path "biosamples_asym.csv", emit: biosamples_asym, optional: true
path "biosamples_sym.csv", emit: biosamples_sym, optional: true
path "file_renaming.tsv", emit: file_renaming, optional: true
script:
"""
echo -e "Valdidating demultiplexing tags\n"
echo -e "Input file: " ${barcodes}
## Convert Windows-style line endings (CRLF) to Unix-style (LF)
LC_ALL=C sed -i 's/\r\$//g' ${barcodes}
## Perform tag validation
validate_tags.R \
--tags ${barcodes} \
--output barcodes_validated.fasta
echo -e "Tag validation finished"
"""
}
// Demultiplexing with LIMA - for PacBio reads
process demux {
label "main_container"
publishDir "${out_1_demux}", mode: "${params.storagemode}" // , saveAs: { filename -> "foo_$filename" }
// cpus 10
input:
path input_fastq
path barcodes
path biosamples_sym // for dual or asymmetric barcodes
path biosamples_asym // for dual or asymmetric barcodes
path file_renaming // for dual or asymmetric barcodes
output:
path "LIMA/*.fq.gz", emit: samples_demux
path "LIMA/lima.lima.report.gz", emit: lima_report
path "LIMA/lima.lima.counts", emit: lima_counts
path "LIMA/lima.lima.summary", emit: lima_summary
script:
"""
echo -e "Input file: " ${input_fastq}
echo -e "Barcodes: " ${barcodes}
## Directory for the results
mkdir -p LIMA
echo -e "Validating data\n"
## Check if symmetric barcodes were provided in the `...` format
## (if `biosamples_sym` does not exists, it means that it is a dummy file)
## (if exists, it means that tags were split into sym and asym at the tag validation step)
if [[ ${params.lima_barcodetype} = "dual_symmetric" ]] && [ -e ${biosamples_sym} ] ; then
echo -e "\nERROR: Symmetric tags are provided in '...' format.\n"
echo -e "In the FASTA file, please include only one tag per sample, since these tags are identical.\n"
exit 1
fi
## Count the number of samples in Biosample files - only for `dual` and `dual_asymmetric` barcodes
if [[ ${params.lima_barcodetype} == "dual_asymmetric" ]] || [[ ${params.lima_barcodetype} == "dual" ]]; then
if [ ! -e ${biosamples_asym} ]; then
echo -e "\nERROR: Tags are specified in wrong format"
echo -e "Use the '...' format in FASTA file.\n"
exit 1
else
line_count_sym=\$(wc -l < ${biosamples_sym})
line_count_asym=\$(wc -l < ${biosamples_asym})
echo -e "..Number of lines in symmetric file: " \$line_count_sym
echo -e "..Number of lines in asymmetric file: " \$line_count_asym
## Check the presence of dual barcode combinations
## If line count is less than 2, it means there are no samples specified
if [[ ${params.lima_barcodetype} == "dual_asymmetric" ]] && [[ \$line_count_asym -lt 2 ]]; then
echo -e "\nERROR: No asymmetric barcodes detected for demultiplexing.\n"
return 1
fi
if [[ ${params.lima_barcodetype} == "dual" ]] && [[ \$line_count_asym -lt 2 ]]; then
echo -e "\nWARNING: No asymmetric barcodes detected, consider using '--lima_barcodetype dual_symmetric'.\n"
fi
fi # end of missing asym biosamples
fi # end of dual/asym validation
## Combine shared arguments into a single variable
## Note the array syntax - that's because of LIMA parser error messages
## (note also that it works in bash, but not in zsh)
common_args=("--ccs \
--window-size ${params.lima_windowsize} \
--min-length ${params.lima_minlen} \
--min-score ${params.lima_minscore} \
--min-ref-span ${params.lima_minrefspan} \
--split-named \
--num-threads ${task.cpus} \
--log-level INFO \
${input_fastq} \
${barcodes}")
## Demultiplex, depending on the barcode type selected
case ${params.lima_barcodetype} in
"single")
echo -e "\nDemultiplexing with LIMA (single barcode)"
lima --same --single-side \
--log-file LIMA/_log.txt \
\$common_args \
"LIMA/lima.fq.gz"
;;
"dual_symmetric")
echo -e "\nDemultiplexing with LIMA (dual symmetric barcodes)"
lima --same \
--min-end-score ${params.lima_minendscore} \
--min-scoring-regions ${params.lima_minscoringregions} \
--log-file LIMA/_log.txt \
\$common_args \
"LIMA/lima.fq.gz"
;;
"dual_asymmetric")
echo -e "\nDemultiplexing with LIMA (dual asymmetric barcodes)"
lima --different \
--min-end-score ${params.lima_minendscore} \
--min-scoring-regions ${params.lima_minscoringregions} \
--biosample-csv ${biosamples_asym} \
--log-file LIMA/_log.txt \
\$common_args \
"LIMA/lima.fq.gz"
;;
"dual")
mkdir -p LIMAs LIMAd
if [[ \$line_count_sym -ge 2 ]]; then
echo -e "\nDemultiplexing with LIMA (dual symmetric barcodes)"
lima --same \
--min-end-score ${params.lima_minendscore} \
--min-scoring-regions ${params.lima_minscoringregions} \
--biosample-csv ${biosamples_sym} \
--log-file LIMAs/_log.txt \
\$common_args \
"LIMAs/lima.fq.gz"
fi
if [[ \$line_count_asym -ge 2 ]]; then
echo -e "\nDemultiplexing with LIMA (dual asymmetric barcodes)"
lima --different \
--min-end-score ${params.lima_minendscore} \
--min-scoring-regions ${params.lima_minscoringregions} \
--biosample-csv ${biosamples_asym} \
--log-file LIMAd/_log.txt \
\$common_args \
"LIMAd/lima.fq.gz"
fi
;;
esac
## Combining symmetric and asymmetric files
if [ ${params.lima_barcodetype} = "dual" ]; then
echo -e "\nPooling of symmetric and asymmetric barcodes"
cd LIMA
find ../LIMAd -name "*.fq.gz" | parallel -j1 "ln -s {} ."
find ../LIMAs -name "*.fq.gz" | parallel -j1 "ln -s {} ."
cd ..
fi
## Rename barcode combinations into sample names
## Only user-provided combinations whould be kept (based on `lima --biosample-csv`)
if [[ ${params.lima_barcodetype} == "dual_asymmetric" ]] || [[ ${params.lima_barcodetype} == "dual" ]]; then
echo -e "\n..Renaming files from tag IDs to sample names"
brename -p "(.+)" -r "{kv}" -k ${file_renaming} LIMA/
fi
if [[ ${params.lima_barcodetype} == "dual_symmetric" ]] || [[ ${params.lima_barcodetype} == "single" ]]; then
echo -e "\n..Renaming demultiplexed files"
rename --filename \
's/^lima.//g; s/--.*\$/.fq.gz/' \
\$(find LIMA -name "*.fq.gz")
fi
## Combine summary stats for dual barcodes (two LIMA runs)
if [[ ${params.lima_barcodetype} == "dual" ]]; then
echo -e "\n..Combining dual-barcode log files"
if [ -f "LIMAd/lima.lima.summary" ]; then
echo -e "Asymmetric barcodes summary\n\n" >> LIMA/lima.lima.summary
cat LIMAd/lima.lima.summary >> LIMA/lima.lima.summary
echo -e "Asymmetric barcodes counts\n\n" >> LIMA/lima.lima.counts
cat LIMAd/lima.lima.counts >> LIMA/lima.lima.counts
echo -e "Asymmetric barcodes report\n\n" >> LIMA/lima.lima.report
cat LIMAd/lima.lima.report >> LIMA/lima.lima.report
fi
if [ -f "LIMAs/lima.lima.summary" ]; then
echo -e "\n\nSymmetric barcodes summary\n\n" >> LIMA/lima.lima.summary
cat LIMAs/lima.lima.summary >> LIMA/lima.lima.summary
echo -e "\n\nSymmetric barcodes counts\n\n" >> LIMA/lima.lima.counts
cat LIMAs/lima.lima.counts >> LIMA/lima.lima.counts
echo -e "\n\nSymmetric barcodes report\n\n" >> LIMA/lima.lima.report
cat LIMAs/lima.lima.report >> LIMA/lima.lima.report
fi
fi # end of dual logs pooling
## Compress logs
echo -e "..Compressing log file"
gzip -${params.gzip_compression} LIMA/lima.lima.report
## LIMA defaults:
# SYMMETRIC : --ccs --min-score 0 --min-end-score 80 --min-ref-span 0.75 --same --single-end
# ASYMMETRIC : --ccs --min-score 80 --min-end-score 50 --min-ref-span 0.75 --different --min-scoring-regions 2
echo -e "\nDemultiplexing finished"
"""
}
// Merge Illumina PE reads
process merge_pe {
label "main_container"
// publishDir "${out_1_demux}", mode: "${params.storagemode}"
// cpus 10
input:
path input_R1
path input_R2
output:
path "Merged.fq.gz", emit: r12
tuple path("NotMerged_R1.fq.gz"), path("NotMerged_R2.fq.gz"), emit: nm, optional: true
script:
"""
echo -e "Merging Illumina pair-end reads"
## By default, fastp modifies sequences header
## e.g., `merged_150_15` means that 150bp are from read1, and 15bp are from read2
## But we'll preserve only sequence ID
fastp \
--in1 ${input_R1} \
--in2 ${input_R2} \
--merge --correction \
--overlap_len_require ${params.pe_minoverlap} \
--overlap_diff_limit ${params.pe_difflimit} \
--overlap_diff_percent_limit ${params.pe_diffperclimit} \
--length_required ${params.pe_minlen} \
--disable_quality_filtering \
--disable_adapter_trimming \
--dont_eval_duplication \
--compression 6 \
--thread ${task.cpus} \
--out1 NotMerged_R1.fq.gz \
--out2 NotMerged_R2.fq.gz \
--json log.json \
--html log.html \
--stdout \
| seqkit seq --only-id \
| gzip -${params.gzip_compression} \
> Merged.fq.gz
## --merged_out Merged.fq.gz \
## --n_base_limit ${params.pe_nlimit} \
# --overlap_len_require the minimum length to detect overlapped region of PE reads
# --overlap_diff_limit the maximum number of mismatched bases to detect overlapped region of PE reads
# --overlap_diff_percent_limit the maximum percentage of mismatched bases to detect overlapped region of PE reads
## NB: reads should meet these three conditions simultaneously!
echo -e "..done"
"""
}
// Modify barcodes for cutadapt (restrict the search window)
process prep_barcodes {
label "main_container"
// publishDir "${out_1_demux}", mode: "${params.storagemode}"
// cpus 1
input:
path barcodes
output:
path "barcodes_modified.fa", emit: barcodesm
script:
"""
echo -e "Restricting the search window for barcode lookup"
echo -e "Provided barcodes: " ${barcodes}
## Add `XN{30}` to the barcodes
sed -e '/^>/! s/^/XN{${params.barcode_window}}/' \
${barcodes} \
> barcodes_modified.fa
echo -e "..Done"
"""
}
// Demultiplexing with cutadapt - for Illumina SE reads
process demux_illumina {
label "main_container"
publishDir "${out_1_demux}", mode: "${params.storagemode}"
// cpus 10
input:
path input_fastq
path barcodes
output:
path "*.fq.gz", emit: samples_demux
script:
"""
echo -e "Input file: " ${input_fastq}
echo -e "Barcodes: " ${barcodes}
echo -e "\nDemultiplexing with cutadapt:"
## Demultiplex with cutadapt
cutadapt \
-g file:${barcodes} \
--revcomp --rename "{header}" \
--errors ${params.barcode_errors} \
--overlap ${params.barcode_overlap} \
--no-indels \
--cores ${task.cpus} \
--discard-untrimmed \
--action none \
-o "{name}.fq.gz" \
${input_fastq} \
> cutadapt.log
echo -e "\n..done"
## Remove empty files (no sequences)
echo -e "\nRemoving empty files"
find . -type f -name "*.fq.gz" -size -29c -print -delete
echo -e "..Done"
echo -e "\nDemultiplexing finished"
"""
}
// Primer disambiguation
process disambiguate {
label "main_container"
// publishDir "${out_2_primer}", mode: "${params.storagemode}"
// cpus 1
output:
path "primer_F.fasta", emit: F
path "primer_R.fasta", emit: R
path "primer_Fr.fasta", emit: Fr
path "primer_Rr.fasta", emit: Rr
script:
"""
## Disambiguate forward primer
echo -e "Disambiguating forward primer"
disambiguate_primers.R \
${params.primer_forward} \
primer_F.fasta
## Disambiguate reverse primer
echo -e "\nDisambiguating reverse primer"
disambiguate_primers.R \
${params.primer_reverse} \
primer_R.fasta
## Reverse-complement primers
echo -e "\nReverse-complementing primers"
seqkit seq -r -p --seq-type dna primer_F.fasta > primer_Fr.fasta
seqkit seq -r -p --seq-type dna primer_R.fasta > primer_Rr.fasta
"""
}
// Check primers + QC + Reorient sequences
// Count number of primer occurrences withnin a read,
// discard reads with > 1 primer occurrence
// NB. read names should not contain spaces! (because of bedtools)
process primer_check {
label "main_container"
publishDir "${out_2_primer}", mode: "${params.storagemode}"
// cpus 1
// Add sample ID to the log file
tag "${input.getSimpleName()}"
input:
path input
path primer_F
path primer_R
path primer_Fr
path primer_Rr
output:
path "${input.getSimpleName()}_PrimerChecked.fq.gz", emit: fq_primer_checked, optional: true
path "${input.getSimpleName()}_PrimerArtefacts.fq.gz", emit: primerartefacts, optional: true
script:
"""
echo -e "Input file: " ${input}
echo -e "Forward primer: " ${params.primer_forward}
echo -e "Reverse primer: " ${params.primer_reverse}
### Count number of pattern occurrences for each sequence
count_primers (){
# \$1 = file with primers
seqkit replace -p "\\s.+" ${input} \
| seqkit locate \
--max-mismatch ${params.primer_mismatches} \
--only-positive-strand \
--pattern-file "\$1" \
--threads ${task.cpus} \
| awk -vOFS='\\t' 'NR > 1 { print \$1 , \$5 , \$6 }' \
| runiq - \
| mlr --tsv \
--implicit-tsv-header \
--headerless-tsv-output \
sort -f 1 -n 2 \
| bedtools merge -i stdin
}
echo -e "\nCounting primers"
echo -e "..forward primer"
count_primers ${primer_F} > PF.txt
echo -e "..rc-forward primer"
count_primers ${primer_Fr} >> PF.txt
echo -e "..reverse primer"
count_primers ${primer_R} > PR.txt
echo -e "..rc-reverse primer"
count_primers ${primer_Rr} >> PR.txt
## Sort by seqID and start position, remove overlapping regions,
## Find duplicated records
echo -e "\nLooking for multiple primer occurrences"
echo -e "..Processing forward primers"
if [ -s PF.txt ]; then
csvtk sort \
-t -T -H -k 1:N -k 2:n \
--num-cpus ${task.cpus} \
PF.txt \
| bedtools merge -i stdin \
| awk '{ print \$1 }' \
| runiq -i - \
> multiprimer.txt
else
echo -e "...No forward primer matches found (in both orientations)"
fi
echo -e "..Processing reverse primers"
if [ -s PR.txt ]; then
csvtk sort \
-t -T -H -k 1:N -k 2:n \
--num-cpus ${task.cpus} \
PR.txt \
| bedtools merge -i stdin \
| awk '{ print \$1 }' \
| runiq -i - \
>> multiprimer.txt
else
echo -e "...No reverse primer matches found (in both orientations)"
fi
## If some artefacts are found
if [ -s multiprimer.txt ]; then
## Keep only uinque seqIDs
runiq multiprimer.txt > multiprimers.txt
rm multiprimer.txt
echo -e "\nNumber of artefacts found: " \$(wc -l < multiprimers.txt)
echo -e "..Removing artefacts"
## Remove primer artefacts
seqkit grep --invert-match \
--threads ${task.cpus} \
--pattern-file multiprimers.txt \
--out-file no_multiprimers.fq.gz \
${input}
## Extract primer artefacts
echo -e "..Extracting artefacts"
seqkit grep \
--threads ${task.cpus} \
--pattern-file multiprimers.txt \
--out-file "${input.getSimpleName()}_PrimerArtefacts.fq.gz" \
${input}
echo -e "..done"
else
echo -e "\nNo primer artefacts found"
ln -s ${input} no_multiprimers.fq.gz
fi
echo -e "..Done"
echo -e "\nReorienting sequences"
## Reverse-complement rev primer
RR=\$(rc.sh ${params.primer_reverse})
## Reorient sequences, discard sequences without both primers
cutadapt \
-a ${params.primer_forward}";required;min_overlap=${params.primer_foverlap}"..."\$RR"";required;min_overlap=${params.primer_roverlap}" \
--errors ${params.primer_mismatches} \
--revcomp --rename "{header}" \
--discard-untrimmed \
--cores ${task.cpus} \
--action none \
--output ${input.getSimpleName()}_PrimerChecked.fq.gz \
no_multiprimers.fq.gz
echo -e "\nAll done"
## Clean up
if [ -f no_multiprimers.fq.gz ]; then rm no_multiprimers.fq.gz; fi
## Remove empty file (no valid sequences)
echo -e "\nRemoving empty files"
find . -type f -name ${input.getSimpleName()}_PrimerChecked.fq.gz -size -29c -print -delete
echo -e "..Done"
"""
}
// Extract ITS region with ITSx
// NB. sequence header should not contain spaces!
process itsx {
label "main_container"
publishDir "${out_3_itsx}", mode: "${params.storagemode}"
// cpus 2
// Add sample ID to the log file
tag "${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}"
input:
path input
output:
path "${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}_hash_table.txt.gz", emit: hashes, optional: true
path "${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}_uc.uc.gz", emit: uc, optional: true
path "${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}.full.fasta.gz", emit: itsx_full, optional: true
path "${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}.SSU.fasta.gz", emit: itsx_ssu, optional: true
path "${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}.ITS1.fasta.gz", emit: itsx_its1, optional: true
path "${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}.5_8S.fasta.gz", emit: itsx_58s, optional: true
path "${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}.ITS2.fasta.gz", emit: itsx_its2, optional: true
path "${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}.LSU.fasta.gz", emit: itsx_lsu, optional: true
path "${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}.positions.txt", optional: true
path "${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}.problematic.txt", optional: true
path "${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}_no_detections.fasta.gz", emit: itsx_nondetects, optional: true
path "${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}.summary.txt", emit: itsx_summary, optional: true
path "${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}.extraction.results", emit: itsx_details, optional: true
path "${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}.SSU.full_and_partial.fasta.gz", emit: itsx_ssu_part, optional: true
path "${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}.ITS1.full_and_partial.fasta.gz", emit: itsx_its1_part, optional: true
path "${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}.5_8S.full_and_partial.fasta.gz", emit: itsx_58s_part, optional: true
path "${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}.ITS2.full_and_partial.fasta.gz", emit: itsx_its2_part, optional: true
path "${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}.LSU.full_and_partial.fasta.gz", emit: itsx_lsu_part, optional: true
script:
sampID="${input.getSimpleName().replaceAll(/_PrimerChecked/, '')}"
// Allow inclusion of sequences that only find a single domain, given that they meet the given E-value and score thresholds, on with parameters 1e-9,0 by default
// singledomain = params.ITSx_singledomain ? "--allow_single_domain 1e-9,0" : ""
"""
echo "Extraction of rRNA regions using ITSx\n"
## Trim primers
echo -e "Trimming primers\n"
## Reverse-complement rev primer
RR=\$(rc.sh ${params.primer_reverse})
cutadapt \
-a ${params.primer_forward}";required;min_overlap=${params.primer_foverlap}"..."\$RR"";required;min_overlap=${params.primer_roverlap}" \
--errors ${params.primer_mismatches} \
--revcomp --rename "{id}" \
--discard-untrimmed \
--minimum-length ${params.trim_minlen} \
--cores ${task.cpus} \
--action trim \
--output ${sampID}_primertrimmed.fq.gz \
${input}
echo -e "..Done\n"
## Check if there are sequences in the output
NUMSEQS=\$( seqkit stat --tabular --quiet ${sampID}_primertrimmed.fq.gz | awk -F'\t' 'NR==2 {print \$4}' )
echo -e "Number of sequences after primer trimming: " \$NUMSEQS
if [ \$NUMSEQS -lt 1 ]; then
echo -e "\nIt looks like no reads remained after trimming the primers\n"
exit 0
fi
## Create a table with seq quality
## Sequence ID - Hash - Length - Average Phred score
echo -e "\nCreating sequence hash table with average sequence quality"
seqkit replace -p "\\s.+" ${sampID}_primertrimmed.fq.gz \
| seqkit fx2tab --length --avg-qual \
| hash_sequences.sh \
| awk '{print \$1 "\t" \$6 "\t" \$4 "\t" \$5}' \
> tmp_hash_table.txt
echo -e "..Done"
## Estimating MaxEE
echo -e "\nEstimating maximum number of expected errors per sequence"
seqkit replace -p "\\s.+" ${sampID}_primertrimmed.fq.gz \
| vsearch \
--fastx_filter - \
--fastq_qmax 93 \
--eeout \
--fastaout - \