-
Notifications
You must be signed in to change notification settings - Fork 26
/
phyloFlash.pl
executable file
·3141 lines (2752 loc) · 119 KB
/
phyloFlash.pl
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 perl
use strict;
use warnings;
=head1 NAME
phyloFlash - A script to rapidly estimate the phylogenetic composition of
an Illumina (meta)genomic dataset and reconstruct SSU rRNA genes
=head1 SYNOPSIS
B<phyloFlash.pl> [OPTIONS] -lib I<name> -read1 F<<file>> -read2 F<<file>>
B<phyloFlash.pl> -help
B<phyloFlash.pl> -man
B<phyloFlash.pl> -check_env
=head1 DESCRIPTION
This tool rapidly approximates the phylogenetic composition of a (meta)genomic
library by mapping reads to a reference SSU rRNA database, and reconstructing
full-length SSU rRNA sequences. The pipeline is intended for Illumina paired-end
HiSeq and MiSeq reads.
For more information, see the manual at L<http://hrgv.github.io/phyloFlash/>
=head1 ARGUMENTS
=head2 INPUT
=over 8
=item -lib I<NAME>
Library I<NAME> to use for output file. The name must be one word comprising
only letters, numbers and "_" or "-" (no whitespace or other punctuation).
=item -read1 F<FILE>
Forward reads in FASTA or FASTQ formats. May be compressed with Gzip (.gz
extension). If interleaved reads are provided, please use I<--interleaved> flag
in addition for paired-end processing.
=item -read2 F<FILE>
File containing reverse reads. If this option is omitted, B<phyloFlash>
will run in B<experimental> single-end mode.
=item -check_env
Invokes checking of working environment and dependencies without data input.
Use to test setup.
=item -help
Print brief help.
=item -man
Show manual.
=item -outfiles
Show detailed list of output and temporary files and exit.
=item -version
Report version
=back
=head2 LOCAL SETTINGS
=over 8
=item -CPUs I<N>
Set the number of threads to use. Defaults to all available CPU cores.
=item -crlf
Use CRLF as line terminator in CSV output (to become RFC4180 compliant).
=item -decimalcomma
Use decimal comma instead of decimal point to fix locale problems.
Default: Off
=item -dbhome F<DIR>
Directory containing phyloFlash reference databases.
Use F<phyloFlash_makedb.pl> to create an appropriate directory.
If not specified, phyloFlash will check for an environment variable
I<$PHYLOFLASH_DBHOME>, then look in the current dir, the home dir, and
the dir where the phyloFlash.pl script is located, for a suitable database dir.
=back
=head2 ANALYSIS TOOLS
=over 8
=item -emirge
Turn on EMIRGE reconstruction of SSU sequences
Default: Off ("-noemirge")
=item -skip_spades
Turn off SPAdes assembly of SSU sequences
Default: No (use SPAdes by default)
=item -sortmerna
Use Sortmerna instead of BBmap to extract SSU rRNA reads. Insert size and
%id to reference statistics will not be available.
Default: No
=back
=head2 INPUT AND ANALYSIS OPTIONS
=over 8
=item -interleaved
Interleaved readfile with R1 and R2 in a single file at read1
=item -readlength I<N>
Sets the expected readlength. If no value is supplied, auto-detect read length.
Must be within 50..500.
Default: -1 (auto-detect)
=item -readlimit I<N>
Limits processing to the first I<N> reads in each input file. Use this
for transcriptomes with a lot of rRNA reads (use values <1000000).
Default: unlimited
=item -amplimit I<N>
Sets the limit of SSU read pairs to switch from emirge.py to
emirge_amplicon.py. This feature is not reliable as emirge_amplicon.py
has been problematic to run (use values >100000).
Default: 500000
=item -id I<N>
Minimum allowed identity for BBmap read mapping process in %. Must be within
50..98. Set this to a lower value for very divergent taxa
Default: 70
=item -evalue_sortmerna I<N>
E-value cutoff to use for SortMeRNA (only if I<-sortmerna> option chosen). In
scientific exponent notation (see below)
Default: 1e-09
=item -clusterid I<N>
Identity threshold for clustering with vsearch in %.
Must be within 50..100.
Default: 97
=item -taxlevel I<N>
Level in the taxonomy string to summarize read counts per taxon.
Numeric and 1-based (i.e. "1" corresponds to "Domain").
Default: 4 ("Order")
=item -tophit
Report taxonomic summary based on the best hit per read only. Otherwise, the
consensus of all ambiguous mappings of a given read will be used to assign its
taxonomy. (This was the default behavior before v3.2)
Default: No (use consensus)
=item -maxinsert I<N>
Maximum insert size allowed for paired end read mapping. Must be within
0..1200.
Default: 1200
=item -sc
Turn on single cell MDA data mode for SPAdes assembly of SSU sequences
=item -trusted F<FILE>
User-supplied Fasta file of trusted contigs containing SSU rRNA sequences. The
SSU sequences will be extracted with Barrnap, and the input read files will be
screened against these extracted "trusted" SSU sequences
=item -poscov
Use Nhmmer to find positional coverage of reads across Barrnap's HMM model of
the 16S and 18S rRNA genes from a subsample of reads, as an estimate of
coverage evenness.
Default: Off ("-noposcov")
=item -everything
Turn on all the optional analyses and output options. Options without defaults
and any local settings must still be specified. Equivalent to "-emirge -poscov
-treemap -zip -log"
=item -almosteverything
Like I<-everything> except without running EMIRGE.
=back
=head2 OUTPUT OPTIONS
=over 8
=item -html
Generate output in HTML format.
Default: On. (Turn off with "-nohtml")
=item -treemap
Draw interactive treemap of taxonomic classification in html-formatted report.
This uses Google Visualization API, which requires an internet connection,
requires that you agree to their terms of service (see
L<https://developers.google.com/chart/terms>), and is not open source, although
it is free to use.
Default: Off ("-notreemap")
=item -zip
Compress output into a tar.gz archive file. Overridden by I<-almosteverything>
or I<-everything>.
Default: Off ("-nozip")
=item -keeptmp
Keep temporary/intermediate files
Default: No ("-nokeeptmp")
=item -log
Write status messages printed to STDERR also to a log file
Default: Off ("-nolog")
=back
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2014-2018 by Harald Gruber-Vodicka <[email protected]>
Elmar A. Pruesse <[email protected]>
and Brandon Seah <[email protected]>
LICENSE
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
=cut
use FindBin;
use lib $FindBin::RealBin;
use PhyloFlash;
use Pod::Usage;
use Getopt::Long;
use File::Basename;
use File::Temp;
use File::Path 'remove_tree';
use Storable;
use IPC::Cmd qw(can_run);
use Cwd;
#use Data::Dumper;
# change these to match your installation
my @dbhome_dirs = (".", $ENV{"HOME"}, $FindBin::RealBin);
# constants
my $version = "phyloFlash v$VERSION"; # Current phyloFlash version
my $progname = $FindBin::Script; # Current script name
my $cwd = getcwd; # Current working folder
my $progcmd = join " ", ($progname, @ARGV) ; # How the script was called
# configuration variables / defaults
my $DBHOME = undef;
my $readsf_full = undef; # path to forward read file
my $readsr_full = undef; # path to reverse read file
my $readsf = undef; # forward read filename, stripped of directory names
my $readsr = undef; # reverse read filename, stripped of directory names
my $SEmode = 0; # single ended mode
my $libraryNAME = undef; # output basename
my $interleaved = 0; # Flag - interleaved read data in read1 input (default = 0, no)
my $id = 70; # minimum %id for mapping with BBmap
my $evalue_sortmerna = 1e-09; # E-value cutoff for sortmerna, ignored if -sortmerna not chosen
my $readlength = -1 ; # length of input reads, -1 for automatic read length detection
my $readlimit = -1; # max # of reads to use
my $amplimit = 500000; # number of SSU pairs at which to switch to emirge_amplicon
my $maxinsert = 1200; # max insert size for paired end read mapping
my $cpus = get_cpus # num cpus to use
my $clusterid = 97; # threshold for vsearch clustering
my $trusted_contigs; # Filename for trusted contigs, if available
my $html_flag = 1; # generate HTML output? (default = 1, on)
my $treemap_flag = 0; # generate interactive treemap (default = 0, off)
my $crlf = 0; # csv line terminator
my $decimalcomma= 0; # Decimal separator (default = .)
my $use_sortmerna = 0; # Flag - Use Sortmerna instead of BBmap? (Default = 0, no)
my $skip_emirge = 1; # Flag - skip Emirge step? (default = 1, yes)
my $skip_spades = 0; # Flag - skip SPAdes assembly? (default = 0, no)
my $poscov_flag = 0; # Flag - use Nhmmer to estimate positional coverage? (Default = 0, no)
my $sc = 0; # Flag - single cell data? (default = 0, no)
my $zip = 0; # Flag - Compress output into archive? (default = 0, no)
my $save_log = 0; # Save STDERR messages to log (Default = 0, no)
my $keeptmp = 0; # Do not delete temporary files (Default = 0, do delete temporary files)
my $tophit_flag; # Use "old" way of taxonomic summary, by taking top bbmap hit (no ambiguities) (Default: undef, no)
my @tools_list; # Array to store list of tools required
# (0 will be turned into "\n" in parsecmdline)
# default database names for EMIRGE and Vsearch
my $emirge_db = "SILVA_SSU.noLSU.masked.trimmed.NR96.fixed";
my $vsearch_db = "SILVA_SSU.noLSU.masked.trimmed.udb";
my $sortmerna_db = $emirge_db;
my $ins_used = "SE mode!"; # Report insert size used by EMIRGE
my %outfiles; # Hash to keep track of output files
# variables for report generation
my $sam_fixed_href; # Ref to hash storing initial mapping data (stored as array of refs to hashes keyed by SAM column name), keyed by RNAME, read orientation, QNAME
my $sam_fixed_aref; # Ref to array storing initial mapping data (pointing to same refs as above) in original order of SAM input file
my %ssu_sam_mapstats; # Statistics of mapping vs SSU database, parsed from from SAM file
# Fields for %ssu_sam_mapstats
# total_reads Total read (pairs) input
# total_read_segments Total read segments input
# ssu_fwd_seg_map Total fwd read segments mapped
# ssu_rev_seg_map Total rev read segments mapped
# ssu_tot_map Total read segments mapped
# ssu_tot_pair_map Total read pairs mapped (one or both segments)
# ssu_tot_pair_ratio Ratio of read (pairs) mapping to SSU (one or both segments
# ssu_tot_pair_ratio_pc Above as percentage
# assem_tot_map Total segments mapping to full length assembled
# ssu_unassem Total segments not mapping to full length
# assem_ratio Ratio assembled/unassmebled
# assem_ratio_pc Above as percentage
# spades_fwd_map Fwd read segments mapping to SPAdes
# spades_rev_map
# spades_tot_map
# emirge_fwd_map
# emirge_rev_map
# emirge_tot_map
# trusted_fwd_map
# trusted_rev_map
# trusted_tot_map
# Hashes to keep count of NTUs
my %taxa_ambig_byread_hash; # Hash of all taxonomy assignments per read
my $taxa_full_href; # Summary of read counts for full-length taxonomy strings (for treemap) - hash ref
my $taxa_summary_href; # Summary of read counts at specific taxonomic level (hash ref)
my $taxa_unassem_summary_href; # Summary of read counts of UNASSEMBLED reads at specific taxonomic level (hash ref)
my $taxon_report_lvl = 4; # Taxonomic level to report counts
my @ssuassem_results_sorted; # Sorted list of SSU sequences for reporting
my @ssurecon_results_sorted;
my %ssufull_hash;
# mapping statistics parsed from BBmap output
my $readnr = 0;
my $readnr_pairs;
my $SSU_total_pairs;
my $SSU_ratio;
my $SSU_ratio_pc;
# Insert size stats from BBmap output
my $ins_me = 0;
my $ins_std = 0;
# Alpha-diversity statistics calculated from taxon counts
my $chao1 = 0;
my @xtons = (0,0,0); # singleton, doubleton and tripleton count
my $runtime;
# display welcome message incl. version
sub welcome {
print STDERR "\nThis is $version\n\n";
}
# checks whether a given directory is a valid dbhome
# (contains the necessary files for bbmap, emirge and vsearch)
sub check_dbhome {
my $dbhome = shift;
my @required_list = ('ref/genome/1/summary.txt',
$emirge_db.".fasta",
$vsearch_db);
push @required_list, ("$sortmerna_db.bursttrie_0.dat","$sortmerna_db.acc2taxstring.hashimage") if ($use_sortmerna == 1);
foreach (@required_list) {
return "${dbhome}/$_" unless -r "${dbhome}/$_"
}
return "";
}
# searches @dbhome_dirs for the dbdir with the highest version
# returns "" if none found
sub find_dbhome {
my @dirs;
my @dbdirs;
foreach (@dbhome_dirs) {
push(@dirs, get_subdirs($_));
}
foreach (@dirs) {
if (check_dbhome($_) eq "") {
push(@dbdirs, $_);
}
}
if (scalar @dbdirs > 0) {
@dbdirs = version_sort(@dbdirs);
return $dbdirs[0];
}
return "";
}
# Specify list of required tools. Run this subroutine AFTER parse_cmdline()
sub process_required_tools {
# binaries needed by phyloFlash
require_tools(
bbmap => "bbmap.sh",
reformat => "reformat.sh",
barrnap => "$FindBin::RealBin/barrnap-HGV/bin/barrnap_HGV",
vsearch => "vsearch",
mafft => "mafft",
fastaFromBed => "fastaFromBed",
sed => "sed",
grep => "grep",
awk => "awk",
cat => "cat",
plotscript_SVG => "$FindBin::RealBin/phyloFlash_plotscript_svg.pl",
);
if ($skip_spades == 0) {
require_tools(spades => "spades.py");
}
if ($skip_emirge == 0) {
require_tools(emirge => "emirge.py",
emirge_amp => "emirge_amplicon.py",
emirge_rename_fasta => "emirge_rename_fasta.py");
}
if ($use_sortmerna == 1) {
require_tools (sortmerna => "sortmerna",
indexdb_rna => "indexdb_rna");
}
# Check operating system to decide which nhmmer to use
my $opsys = $^O;
msg ("Current operating system $opsys");
if ($opsys eq "darwin") {
require_tools (nhmmer => "$FindBin::RealBin/barrnap-HGV/binaries/darwin/nhmmer");
} elsif ($opsys eq "linux") {
require_tools (nhmmer => "$FindBin::RealBin/barrnap-HGV/binaries/linux/nhmmer");
} else {
msg ("Could not determine operating system, assuming linux");
require_tools (nhmmer => "$FindBin::RealBin/barrnap-HGV/binaries/linux/nhmmer");
}
}
sub verify_dbhome {
# verify database present
if (defined($DBHOME)) {
if (my $file = check_dbhome($DBHOME)) {
pod2usage("\nBroken dbhome directory: missing file \"$file\"");
}
} elsif (defined $ENV{"PHYLOFLASH_DBHOME"}) {
# dbhome defined as environment variable
if (my $file = check_dbhome($ENV{"PHYLOFLASH_DBHOME"})) {
pod2usage("\nBroken dbhome directory $ENV{'PHYLOFLASH_DBHOME'}: missing file \"$file\"");
} else {
$DBHOME = $ENV{"PHYLOFLASH_DBHOME"};
}
} else {
$DBHOME = find_dbhome();
pod2usage("Failed to find suitable DBHOME. (Searched \""
.join("\", \"",@dbhome_dirs)."\".)\nPlease provide a path using -dbhome. "
."You can build a reference database using phyloFlash_makedb.pl\n")
if ($DBHOME eq "");
}
msg("Using dbhome '$DBHOME'");
}
sub auto_detect_readlength {
# Get read lengths from input files instead of asking user for input
my ($fwd, # Fwd read file
$rev, # Rev read file, undef if not available
$limit # Stop after this many reads
) = @_;
require_tools("readlength" => "readlength.sh");
my @readlength_cmd = ("readlength",
"reads=$limit",
"bin=1",
"in=$fwd");
if (defined $rev) {
push @readlength_cmd, "in2=$rev";
}
# Use readlength.sh from bbmap suite to count read lengths from Fasta or Fastq
run_prog("readlength",
join(" ", @readlength_cmd),
$outfiles{"readlength_out"}{"filename"},
$outfiles{"readlength_err"}{"filename"});
$outfiles{"readlength_out"}{"made"} = 1;
# Hash counts of reads per read length
my @lens;
my $fh;
open_or_die(\$fh, "<", $outfiles{"readlength_out"}{"filename"});
while (my $line = <$fh>) {
next if $line =~ m/^#/; # Skip headers
my @split = split /\t/, $line;
push @lens, $split[0];
}
# Sort by highest counts
if (scalar @lens > 1) {
msg("Reads are not all the same length, using longest read length found...");
}
my @sort_lens = sort { $b <=> $a } @lens;
# Return the longest read length
msg("Auto-detected read length: $sort_lens[0]");
return ($sort_lens[0]);
}
# parse arguments passed on commandline and do some
# sanity checks
sub parse_cmdline {
pod2usage(-verbose=>0) if !@ARGV;
my $emirge = 0;
my $everything = 0 ;
my $almosteverything = 0;
GetOptions('read1=s' => \$readsf_full,
'read2=s' => \$readsr_full,
'lib=s' => \$libraryNAME,
'dbhome=s' => \$DBHOME,
'interleaved' => \$interleaved,
'readlength=i' => \$readlength,
'readlimit=i' => \$readlimit,
'amplimit=i' => \$amplimit,
'maxinsert=i' => \$maxinsert,
'id=i' => \$id,
'clusterid=i' => \$clusterid,
'taxlevel=i' => \$taxon_report_lvl,
'CPUs=i' => \$cpus,
'html!' => \$html_flag,
'treemap!' => \$treemap_flag,
'crlf' => \$crlf,
'decimalcomma' => \$decimalcomma,
'sortmerna!' => \$use_sortmerna,
'evalue_sortmerna=s' => \$evalue_sortmerna,
'emirge!' => \$emirge,
'skip_emirge' => \$skip_emirge,
'skip_spades' => \$skip_spades,
'trusted=s' => \$trusted_contigs,
'poscov!' => \$poscov_flag,
'sc' => \$sc,
'zip!' => \$zip,
'log!' => \$save_log,
'keeptmp!' => \$keeptmp,
'everything' => \$everything,
'almosteverything' => \$almosteverything,
'tophit!' => \$tophit_flag,
'check_env' => \&check_env_wrapper,
'outfiles' => \&output_description,
'help|h' => sub { pod2usage(-verbose=>0); },
'man' => sub { pod2usage(-exitval=>0, -verbose=>2); },
'version' => sub { welcome(); exit; },
) or pod2usage(2);
$skip_emirge = 0 if $emirge == 1; # ain't gonna not be less careful with no double negatives
# Say hello
welcome();
# Verify DBHOME is a valid phyloFlash DB folder
verify_dbhome();
# verify valid lib name
pod2usage("Please specify output file basename with -lib\n")
if !defined($libraryNAME);
pod2usage("\nERROR: Argument to -lib may not be empty\n")
if length($libraryNAME) == 0;
pod2usage("\nERROR: Argument to -lib may contain only alphanumeric characters,"
."'_' and '-'.\n")
if $libraryNAME =~ m/[^a-zA-Z0-9_-]/ ;
msg("working on library $libraryNAME");
# verify read files
pod2usage("\nPlease specify input forward read file with -read1")
if !defined($readsf_full);
pod2usage("\nUnable to open forward read file '$readsf_full'. ".
"Make sure the file exists and is readable by you.")
if ! -e $readsf_full;
# strip directory paths from forward read filename
if ($readsf_full =~ m/.*\/(.+)/) {
$readsf = $1;
} else {
$readsf = $readsf_full;
}
if (defined($readsr_full)) {
pod2usage("\nUnable to open reverse read file '$readsr_full'.".
"Make sure the file exists and is readable by you.")
if ! -e $readsr_full;
pod2usage("\nForward and reverse input read file need to be different")
if ($readsr_full eq $readsf_full);
if ($readsr_full =~ m/.*\/(.+)/) { # strip directory paths from reverse read filename
$readsr = $1;
} else { $readsr = $readsr_full; }
} elsif ( $interleaved == 1 ){
msg("Using interleaved read data");
} else {
$SEmode = 1; # no reverse reads, we operate in single ended mode
$readsr = "";
$readsr_full = "";
}
msg("Forward reads $readsf_full");
if ($SEmode == 0) {
if (defined($readsr_full)) {
msg("Reverse reads $readsr_full");
} else{
msg("Reverse reads from interleaved read file $readsf_full");
}
} else {
msg("Running in single ended mode");
}
# populate hash to keep track of output files
my $outfiles_href = initialize_outfiles_hash($libraryNAME,$readsf);
%outfiles = %$outfiles_href;
# use hash to keep track of output file description, filename,
# whether it should be deleted at cleanup, and if file was actually created
if ($readlength < 0) {
msg("Automatic read length detection");
$readlength = auto_detect_readlength($readsf_full, $readsr_full, 10000);
}
# check lengths
pod2usage("\nReadlength must be within 50...500")
if ($readlength < 50 or $readlength > 500);
pod2usage("\nMaxinsert must be within 0..1200")
if ($maxinsert < 0 or $maxinsert > 1200);
pod2usage("\nReadmapping identity (-id) must be within 50..98")
if ($id < 50 or $id > 98);
pod2usage("\nClustering identity (-clusterid) must be within 50..100")
if ($clusterid < 50 or $clusterid > 100);
$crlf = $crlf ? "\r\n":"\n";
# check CPUS
if ($cpus eq "all" or $cpus < 0) {
$cpus = get_cpus();
}
# Warn user about Sortmerna requirements
if ($use_sortmerna == 1) {
msg ("Sortmerna will be used instead of BBmap for the initial SSU rRNA read extraction");
msg ("Sortmerna requires uncompressed input files - Ensure that you have enough disk space");
msg ("The following input parameters specific to BBMap will be ignored: --id, --maxinsert");
}
# check surplus arguments
err("Command line contains extra words:", @ARGV)
if ($ARGV[0]);
# If trusted contigs supplied, check that file is at least a valid ASCII/UTF-8 text file
if (defined $trusted_contigs) {
msg ("Trusted contigs file $trusted_contigs supplied");
if (! -T $trusted_contigs) {
msg ("WARNING: Trusted contigs file $trusted_contigs does not appear to be plain text file. Ignoring...");
$trusted_contigs = undef;
}
}
# Activate all optional outputs if "everything" is asked for
if ($everything + $almosteverything > 0) {
($poscov_flag,
$html_flag,
$treemap_flag,
$zip,
$save_log
) = (1,1,1,1,1);
$skip_spades = 0; # Override any skip spades
if ($everything == 1) {
msg ("Running \"everything\" - overrides other command line options");
$skip_emirge = 0;
} else {
# "almost everything" does not turn on EMIRGE
msg ("Running \"everything\" except EMIRGE- overrides other command line options");
}
}
}
sub check_env_wrapper {
# verify tools present
welcome();
process_required_tools();
check_environment(); # will die on failure
verify_dbhome();
exit();
}
sub output_description {
my $example_outfiles = initialize_outfiles_hash("LIBNAME","READS");
print STDERR "Description of output files \n\n";
print STDERR "FILENAME\tDESCRIPTION\n";
foreach my $outfile (sort {$a cmp $b} keys %$example_outfiles) {
my @out = ($example_outfiles->{$outfile}{"filename"},
$example_outfiles->{$outfile}{"description"},);
print STDERR join ("\t", @out)."\n";
}
exit;
}
sub print_report {
## Write plaintext report file
msg("writing final files...");
my $fh;
open_or_die(\$fh, '>', $outfiles{"report"}{"filename"});
$outfiles{"report"}{"made"} = 1;
print {$fh} qq ~
$version - high throughput phylogenetic screening using SSU rRNA gene(s) abundance(s)
Command:\t$progcmd
Library name:\t$libraryNAME
---
Forward read file\t$readsf_full~;
if ($SEmode == 0) {
if ($interleaved == 1) { # reads are provided interleaved
print {$fh} qq~
Reverse reads provided interleaved in file\t$readsf_full~;}
else { # reads are provided in two separate files
print {$fh} qq ~
Reverse read file\t$readsr_full~;
}
}
print {$fh} qq~
---
Current working directory\t$cwd
---
Minimum mapping identity:\t$id%
~;
if (defined($readsr_full) || $interleaved == 1) { # If in PE mode
print {$fh} qq~
---
Input PE-reads:\t$readnr_pairs
Mapped SSU reads:\t$SSU_total_pairs
Mapping ratio:\t$SSU_ratio_pc%
Detected median insert size:\t$ins_me
Used insert size:\t$ins_used
Insert size standard deviation:\t$ins_std
~;
} else { # Else if in SE mode
print {$fh} qq~
---
Input SE-reads:\t$readnr_pairs
Mapped SSU reads:\t$SSU_total_pairs
Mapping ratio:\t$SSU_ratio_pc%
~;
}
if (defined $ssu_sam_mapstats{"assem_ratio"}) {
print {$fh} "Ratio of assembled SSU reads:\t".$ssu_sam_mapstats{"assem_ratio"}."\n";
}
my $chao1_3dp = $chao1 eq "n.d." ? $chao1 : sprintf ("%.3f", $chao1);
print {$fh} qq~
---
Runtime:\t$runtime
CPUs used:\t$cpus
---
Read mapping based higher taxa (NTUs) detection
NTUs observed once:\t$xtons[0]
NTUs observed twice:\t$xtons[1]
NTUs observed three or more times:\t$xtons[2]
NTU Chao1 richness estimate:\t$chao1_3dp
List of NTUs in order of abundance (min. 3 reads mapped):
NTU\treads
~;
# sort keys numerically descending in hash of
# mapping-based detected higher taxa
my @keys = sort {${$taxa_summary_href}{$b} <=> ${$taxa_summary_href}{$a}} keys %$taxa_summary_href;
foreach my $key (@keys) {
if (${$taxa_summary_href}{$key} >= 3) {
my @out = ($key, ${$taxa_summary_href}{$key});
print {$fh} join("\t", @out)."\n";
}
}
if (defined $outfiles{"spades_fasta"}{"made"}) {
## Print the table of SSU assembly-based taxa to report file
print {$fh} "---\n";
print {$fh} "SSU assembly based taxa:\n";
print {$fh} "OTU\tread_cov\tcoverage\tdbHit\ttaxonomy\t%id\talnlen\tevalue\n";
foreach my $seqid ( sort { $ssufull_hash{$b} <=> $ssufull_hash{$a} } keys %ssufull_hash) {
next unless (defined $ssufull_hash{$seqid}{"source"} && $ssufull_hash{$seqid}{"source"} eq "SPAdes");
my @out;
push @out, $seqid;
my @fields = qw(counts cov dbHit taxon pcid alnlen evalue);
foreach my $field (@fields) {
push @out, $ssufull_hash{$seqid}{$field};
}
print {$fh} join("\t", @out)."\n";
}
}
if (defined $outfiles{"emirge_fasta"}{"made"}) {
## Print the table of SSU reconstruction-based taxa to report file
print {$fh} "---\n";
print {$fh} "SSU reconstruction based taxa:\n";
print {$fh} "OTU\tread_cov\tratio\tdbHit\ttaxonomy\t%id\talnlen\tevalue\n";
foreach my $seqid (sort { $ssufull_hash{$b} <=> $ssufull_hash{$a} } keys %ssufull_hash) {
next unless (defined $ssufull_hash{$seqid}{"source"} && $ssufull_hash{$seqid}{"source"} eq "EMIRGE");
my @out;
push @out, $seqid;
my @fields = qw(counts cov dbHit taxon pcid alnlen evalue);
foreach my $field (@fields) {
push @out, $ssufull_hash{$seqid}{$field};
}
print {$fh} join("\t", @out)."\n";
}
}
if (defined $outfiles{"trusted_fasta"}{"made"}) {
## Print the table of SSU extracted from trusted contigs to report file
print {$fh} "---\n";
print {$fh} "SSU from trusted contigs:\n";
print {$fh} "OTU\tread_cov\tratio\tdbHit\ttaxonomy\t%id\talnlen\tevalue\n";
foreach my $seqid (sort { $ssufull_hash{$b} <=> $ssufull_hash{$a} } keys %ssufull_hash) {
next unless (defined $ssufull_hash{$seqid}{"source"} && $ssufull_hash{$seqid}{"source"} eq "trusted");
my @out;
push @out, $seqid;
my @fields = qw(counts cov dbHit taxon pcid alnlen evalue);
foreach my $field (@fields) {
push @out, $ssufull_hash{$seqid}{$field};
}
print {$fh} join("\t", @out)."\n";
}
}
if (defined $outfiles{"emirge_fasta"}{"made"} || defined $outfiles{"spades_fasta"}{"made"} || defined $outfiles{"trusted_fasta"}{"made"}) {
## Print the table of taxonomic affiliations for unassembled SSU reads
print {$fh} "---\n";
print {$fh} "Taxonomic affiliation of unassembled reads (min. 3 reads mapped):\n";
my @taxsort = sort {${$taxa_unassem_summary_href}{$b} <=> ${$taxa_unassem_summary_href}{$a}} keys %$taxa_unassem_summary_href;
foreach my $uatax (@taxsort) {
if (${$taxa_unassem_summary_href}{$uatax} >= 3) {
my @out = ($uatax, ${$taxa_unassem_summary_href}{$uatax});
print {$fh} join ("\t", @out)."\n";
}
}
}
close($fh);
}
sub write_csv {
msg("exporting results to csv");
# CSV file of phyloFlash run metadata
my @report = csv_escape((
"version",$version,
"library name",$libraryNAME,
"forward read file",$readsf_full,
"reverse read file",$readsr_full,
"cwd",$cwd,
"minimum mapping identity",$id,
"single ended mode",$SEmode,
"input reads",$ssu_sam_mapstats{'total_reads'},
"input read segments",$ssu_sam_mapstats{'total_read_segments'},
"mapped SSU reads",$SSU_total_pairs,
"mapped SSU read segments",$ssu_sam_mapstats{'ssu_tot_map'},
"mapping ratio",$SSU_ratio_pc,
"detected median insert size",$ins_me,
"used insert size",$ins_used,
"insert size stddev",$ins_std,
"runtime",$runtime,
"CPUs",$cpus,
"NTUs observed once",$xtons[0],
"NTUs observed twice",$xtons[1],
"NTUs observed three or more times",$xtons[2],
"NTU Chao1 richness estimate", $chao1 eq "n.d." ? $chao1 : sprintf ("%.3f", $chao1), # Round to 3 d.p.
"program command",$progcmd,
"database path",$DBHOME,
));
my $fh;
open_or_die(\$fh, ">", $outfiles{"report_csv"}{"filename"});
$outfiles{"report_csv"}{"made"} = 1;
while ($#report > 0) {
print {$fh} shift(@report).",".shift(@report).$crlf;
}
close($fh);
# CSV file of taxonomic units (NTUs) from mapping vs SILVA database
# truncated to requested taxonomic level
open_or_die(\$fh, ">", $outfiles{"ntu_csv"}{"filename"});
$outfiles{"ntu_csv"}{"made"} = 1;
# Sort results descending
my @keys = sort {${$taxa_summary_href}{$b} <=> ${$taxa_summary_href}{$a}} keys %$taxa_summary_href;
foreach my $key (@keys) {
my @out = ($key, ${$taxa_summary_href}{$key});
print {$fh} join(",",csv_escape(@out)).$crlf;
}
close($fh);
if (!defined $tophit_flag) {
#CSV file of taxonomic units (NTUs) from mapping vs SILVA database,
# not truncated to requested taxonomic level
open_or_die(\$fh, ">", $outfiles{"ntu_full_csv"}{"filename"});
$outfiles{"ntu_full_csv"}{"made"} = 1;
# Sort results descending
my @keys_full = sort {${$taxa_full_href}{$b} <=> ${$taxa_full_href}{$a}} keys %$taxa_full_href;
foreach my $key (@keys_full) {
my @out = ($key, ${$taxa_full_href}{$key});
print {$fh} join(",",csv_escape(@out)).$crlf;
}
close($fh);
}
# If full-length seqeunces were assembled or reconstructed
if (defined $outfiles{"spades_fasta"}{"made"} || defined $outfiles{"emirge_fasta"}{"made"} || defined $outfiles{"trusted_fasta"}{"made"}) {
# CSV file of assembled/reconstructed sequnces
open_or_die(\$fh, ">", $outfiles{"full_len_class"}{"filename"});
$outfiles{"full_len_class"}{"made"}++;
print $fh "OTU,read_cov,coverage,dbHit,taxonomy,%id,alnlen,evalue\n"; # Header
# Sort descending by read counts
foreach my $seqid (sort {$ssufull_hash{$b}{"counts"} <=> $ssufull_hash{$a}{"counts"}} keys %ssufull_hash) {
my @out;
push @out, $seqid;
foreach my $field (qw(counts cov dbHit taxon pcid alnlen evalue)) {
if (defined $ssufull_hash{$seqid}{$field}) {
push @out, $ssufull_hash{$seqid}{$field};
} else {
push @out, 'NA';
}
}
print {$fh} join (",", csv_escape(@out)).$crlf;
}
close($fh);
# CSV file of taxonomic affiliations for unassembled/unreconstructed reads
my $fh2;
open_or_die (\$fh2, ">", $outfiles{"unassem_csv"}{"filename"});
my @taxsort = sort {${$taxa_unassem_summary_href}{$b} <=> ${$taxa_unassem_summary_href}{$a}} keys %$taxa_unassem_summary_href;
foreach my $uatax (@taxsort) {
my @out = ($uatax, ${$taxa_unassem_summary_href}{$uatax});
print {$fh2} join (",", csv_escape(@out)).$crlf;
}
$outfiles{"unassem_csv"}{"made"}++;
close ($fh2);
}
}
sub bbmap_fast_filter_sam_run {
# input: $readsf, $readsr