forked from HRGV/phyloFlash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PhyloFlash.pm
1849 lines (1612 loc) · 53.7 KB
/
PhyloFlash.pm
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
use strict;
# see bottom of file for copyright & license
package PhyloFlash;
use Exporter qw(import);
use Time::Piece;
use Text::Wrap;
use Config;
use Storable;
$Text::Wrap::huge = "overflow";
=head1 NAME
PhyloFlash Perl module - functions for phyloFlash
=head1 SYNOPSIS
use PhyloFlash;
=head1 DESCRIPTION
This module contains helper functions shared by the phyloFlash scripts.
=head2 FUNCTIONS
=over
=cut
our $VERSION = "3.4.2";
our @ISA = qw(Exporter);
our @EXPORT = qw(
$VERSION
get_cpus
msg
@msg_log
write_logfile
err
version_sort
file_is_newer
get_subdirs
open_or_die
slurpfile
csv_escape
require_tools
check_environment
check_vsearch_version
run_prog
run_prog_nodie
file_download
fasta_copy_except
fasta_copy_iupac_randomize
cluster
hash2taxstring_counts
hashtreeconsensus
taxstring2hash
consensus_taxon_counter
revcomp_DNA
fix_hash_sortmerna_sam
split_sam_line_to_hash
initialize_outfiles_hash
);
use IPC::Cmd qw(can_run);
=item get_cpus ()
Returns the number of CPUs as listed in F</proc/cpuinfo> (Linux)
or reported by F<sysctl> (Darwin/OSX)
=cut
sub get_cpus {
if ($Config{"osname"} eq "linux") {
open(my $fh, "<", "/proc/cpuinfo") or return 1;
return scalar (map /^processor/, <$fh>)
}
elsif ($Config{"osname"} eq "darwin") {
can_run("sysctl") or return 1;
my $ncpu = `sysctl -n hw.ncpu`;
chomp($ncpu);
return $ncpu;
}
else {
return 1;
}
}
=item msg ($msg)
Logs a message to STDERR with time stamp prefix.
=cut
our @msg_log; # Global var to store log
sub msg {
my $t = localtime;
my $line = wrap ("[".$t->hms."] ", " ",
join "\n", @_);
push @msg_log, $line;
print STDERR $line."\n";
}
=item write_logfile ($file)
Saves message log to file
=cut
sub write_logfile {
my $file = shift;
msg ("Saving log to file $file");
my $fh;
open_or_die(\$fh, ">>", $file);
print $fh join "\n", @PhyloFlash::msg_log;
close($fh);
}
=item err($msg)
Logs an error message to STDERR and dies
=cut
sub err {
my @msg = (@_,"Aborting.");
$msg[0] = "FATAL: ".$msg[0];
msg(@msg);
write_logfile("phyloFlash_log_on_error");
exit(3);
}
=item version_sort(@paths)
sorts paths by descending alphanumeric order ignoring directories and
the part of the filename preceding the first digit. E.g.:
/home/xx/silva_125
/var/lib/dbs/silva_ssu_123.1
/software/phyloFlash_2.0/ssu_123
./121
=cut
sub version_sort {
# this will fail with Perl <5.13.2. Versions before that lack the
# non-destructive subsitition flag /r used in the map line below.
return map { $_->[0] }
sort { - ($a->[1] cmp $b->[1]) }
map { [ $_, ($_ =~ s/.*\/[^\d]*//r) =~ s[(\d+)][pack "N", $1]ger ] }
@_;
# works like this:
# last map creates a key->value map with the path the key and the value
# 1. having leading directories and filename up to first digit removed
# 2. all numbers converted to 4-byte strings (most significant first)
# sort does descending sort by string comparison
# first map picks just the key to return sorted array
}
=item file_is_newer ($file1, $file2)
Compares the time stamps of two files. Returns true if file1
is newer than file2.
=cut
sub file_is_newer {
my $file1 = shift;
my $file2 = shift;
return (stat($file1))[9] > (stat($file2))[9];
}
=item get_subdirs ($parent)
Returns array of paths to subdirs of $parent (hidden excluded).
=cut
sub get_subdirs {
my $parent = shift;
opendir(my $dh, $parent) or return ();
my @dirs = map { "$parent/" . $_} grep { !/^\./ && -d "$parent/$_" } readdir($dh);
closedir($dh);
return @dirs;
}
=item open_or_die (\$fh, $mode, $filename)
Opens a file handle and terminates with an error if the
open failed. $fh must be passed as reference!
=cut
sub open_or_die {
my ($fh, $mode, $fname) = @_;
my $msg;
if ($mode eq ">") {
$msg = "write to file";
} elsif ($mode eq ">>") {
$msg = "append to file";
} elsif ($mode eq "<") {
$msg = "read from file";
} elsif ($mode eq "-|") {
$msg = "run command";
}
open($$fh, $mode, $fname)
or err("Failed to $msg '$fname': $!");
}
=item slurpfile ($filename)
Opens a file, slurps contents into string, and returns string.
=cut
sub slurpfile {
my ($file) = @_;
my $return;
{
my $fh_slurp;
open_or_die(\$fh_slurp, "<", $file);
local $/ = undef;
$return = <$fh_slurp>;
close($fh_slurp);
}
return ($return);
}
=item csv_escape ($var)
Escapes data for CSV output according to RFC4180.
=cut
sub csv_escape {
return unless defined wantarray;
my @parms = @_;
for (@parms) {
if (m/[",\r\n]/) {
s/"/""/g;
$_='"'.$_.'"';
}
}
return wantarray ? @parms : $parms[0];
}
# we store a hash of tool_name=>tool_binary here
my %progs = (
vsearch => "vsearch"
);
=item require_tools (%hash)
Adds tools to the list of required tools. Argument must be
a hash. Use like so:
require_tools(("tool" => "mytool.pl"))
=cut
sub require_tools {
my %arg = @_;
%progs = (%progs, %arg);
}
=item check_environment ()
Verifies availability of all tools requested using require_tools().
The required tools are located using can_run and the paths determined
printed using msg(). If any of the tools are missing, this function
will abort, asking the user to fix the prerequisites.
=cut
sub check_environment {
my @missing;
msg("Checking for required tools.");
foreach my $prog (keys %progs) {
my $progname = $progs{$prog};
if ($progs{$prog} = can_run($progname)) {
msg("Using $prog found at \"".$progs{$prog}."\".");
} else {
push @missing, " $prog ($progname)";
}
}
if (@missing) {
msg("Unable to find all required tools. These are missing:");
foreach my $prog (@missing) {
msg($prog);
}
err("Please make sure these are installed and in your PATH.\n\n");
} else {
msg("All required tools found.");
}
}
=item check_vsearch_version ()
Check that Vsearch version is at least 2.5.0. Return "1" if yes, otherwise undef
UDB file is only implemented from 2.5.0 onwards
=cut
sub check_vsearch_version {
my $version_msg = `vsearch -v 2>&1`;
my $return_value;
if ($version_msg =~ m/vsearch v(\d+)\.(\d+)\.\d+/) {
my ($maj,$min) = ($1, $2); # Major and minor version
# Check if at least v2.5.0
if ($maj >= 2 && $min >= 5) {
$return_value = 1;
msg ("Vsearch v2.5.0+ found, will index database to UDB file");
}
} else {
msg ("Could not determine Vsearch version. Assuming to be < v2.5.0");
}
return $return_value;
}
=item run_prog ($progname, $args, $redir_stdout, $redir_sterr)
Runs a tool by the name given in require_tools.
Aborts the script if the tool returned with an error code.
=over 15
=item $progname
the name of the tool
=item $args
command line arguments to be passed
=item $redir_stdout
file or file descriptor to redirect stdout to
=item $redir_stdin
same for stderr
=back
=cut
sub run_prog {
my ($prog, $args, $redir_stdout, $redir_stderr) = @_;
if (not exists $progs{$prog}) {
msg("trying to launch unknown tool \"$prog\". pls add to %progs");
$progs{$prog} = can_run($prog) or err("Failed to find $prog");
}
my $cmd = $progs{$prog}." ".$args;
$cmd .= " >".$redir_stdout if ($redir_stdout);
$cmd .= " 2>".$redir_stderr if ($redir_stderr);
msg("running subcommand:","$cmd");
my $return = system($cmd);
if ($return != 0) {
my @errmsg = ("Tool execution failed!.",
"Error was '$!' and return code '$?'");
if ($redir_stdout) {
push @errmsg, "Check log file $redir_stdout";
}
if ($redir_stderr) {
push @errmsg, "Check error log file $redir_stderr";
}
err(@errmsg);
}
# FIXME: print tail of stderr if redirected
}
=item run_prog_nodie ($progname, $args, $redir_stdout, $redir_sterr)
Runs a tool by the name given in require_tools.
Does not abort the script if returned with error code
=over 15
=item $progname
the name of the tool
=item $args
command line arguments to be passed
=item $redir_stdout
file or file descriptor to redirect stdout to
=item $redir_stdin
same for stderr
=back
=cut
sub run_prog_nodie {
my ($prog, $args, $redir_stdout, $redir_stderr) = @_;
if (not exists $progs{$prog}) {
msg("trying to launch unknown tool \"$prog\". pls add to %progs");
$progs{$prog} = can_run($prog) or err("Failed to find $prog");
}
my $cmd = $progs{$prog}." ".$args;
$cmd .= " >".$redir_stdout if ($redir_stdout);
$cmd .= " 2>".$redir_stderr if ($redir_stderr);
msg("running subcommand:","$cmd");
my $return = system($cmd);
if ($return != 0) {
my @errmsg = ("Tool execution failed!.",
"Error was '$!' and return code '$?'");
if ($redir_stdout) {
push @errmsg, "Check log file $redir_stdout";
}
if ($redir_stderr) {
push @errmsg, "Check error log file $redir_stderr";
}
msg(@errmsg);
}
return ($return);
# FIXME: print tail of stderr if redirected
}
=item file_md5 ($filename)
Computes the (hex coded) MD5 sum for the contents of a local file ($filename).
=cut
sub file_md5 {
my $file = shift;
my $fh;
open($fh, "<", $file)
or err("Unable to open $file.");
my $ctx = Digest::MD5->new;
$ctx->addfile($fh);
close($fh);
return $ctx->hexdigest;
}
=item ftp_read_var ($ftp, $pattern)
Fetches the contents of a file from FTP. $ftp must be a connected
Net::FTP object and $pattern a file pattern relative to the
current path of $ftp. If the file exists, the contents are returned.
Otherwise returns an empty string
=cut
sub ftp_read_var {
my $ftp = shift;
my $file = shift;
my $out = "";
open(my $fh, '>', \$out);
$ftp->get($file, $fh);
close($fh);
return $out;
}
=item file_download ($path)
Downloads a file from a FTP server.
$path should be of the form "ftp.somedomain.tld/some/dirs/pa.*ttern".
Returns the name of the downloaded file.
=over 3
=item -
Compares byte sizes before and after download.
=item -
Compares MD5 sum if <file>.md5 exists on server.
=item -
File download is skipped if both size and MD5 (if exists) are correct
=item -
Asks user to confirm license if the directory containing the target
file also contains a file named LICENSE.txt.
=back
=cut
sub file_download {
my ($server,$path,$pat) = ($_[0] =~ /([^\/]*)(\/.*\/)([^\/]*)/);
msg(" Connecting to $server");
my $ftp = new Net::FTP($server,(
Passive => 1,
Debug => 0,
Timeout => 600
))
or err("Could not connect to $server");
$ftp->login("anonymous", "-phyloFlash")
or err("Could not login to $server:", $ftp->message);
$ftp->binary();
$ftp->pasv();
msg(" Finding $path$pat");
$ftp->cwd($path)
or err("Could not enter path '\$path\': ", $ftp->message);
my $files = $ftp->ls($pat)
or err("Could not list files matching \'$pat'\ in \'$path\': ",
$ftp->message);
err("No files found?!")
if (@$files == 0);
msg(" Multiple files found?! Using first of ".join(@$files))
if (@$files > 1);
my $file = shift(@$files);
my $file_size = $ftp->size($file)
or err("Could not get file size:", $ftp->message);
msg(" Found $file ($file_size bytes)");
# try downloading md5
my $file_md5 = ftp_read_var($ftp, $file.".md5");
$file_md5 =~ s/ .*//;
chomp($file_md5);
# compare with potentially existing file
if (-e $file) { # file exists
msg(" Found existing $file");
if (-s $file == $file_size) { # and has same size
if ($file_md5 eq "") {
msg("Sizes match. Skipping download");
return $file;
}
msg(" Verifying MD5...");
my $local_md5 = file_md5($file);
if ($file_md5 eq $local_md5) { # and has same md5
msg(" Verified. Skipping download");
return $file;
} else { # md5 mismatch
msg(" MD5 sum mismatch: '$file_md5' != '$local_md5'");
}
} else {
msg(" Size mismatch: ".$file_size." != ". -s $file);
}
msg(" -> re-downloading");
}
# verify license
my $license = ftp_read_var($ftp, "LICENSE.txt");
if (!$license eq "") {
msg("The file you are about to download comes with a license:\n\n\n"
.$license."\n\n");
msg("Do you wish to continue downloading under the conditions");
msg("specified above? [yes/no]: ");
my $accept;
while (<>) {
chomp;
if ($_ eq "yes") {
$accept = 1;
last;
} elsif ($_ eq "no") {
$accept = 0;
last;
} else {
msg("[yes/no]: ");
}
}
if ($accept == 0) {
msg("Ok. Goodbye...");
exit(0);
}
}
# download file
print STDERR "|" . "-" x 75 . "|\n";
$ftp->hash(\*STDERR, $ftp->size($file)/76);
$ftp->get($file)
or err("Failed to download $file:", $ftp->message);
print STDERR "\n";
err("File size mismatch?!")
if (-s $file != $file_size);
if ($file_md5 eq "") { # had no md5
return $file;
}
msg(" Verifying MD5...");
my $local_md5 = file_md5($file);
if ($local_md5 eq $file_md5) {
msg("File ok");
return $file;
}
err(" MD5 sum mismatch: '$file_md5' != '$local_md5'");
}
=item fasta_copy_except ($source, $dest, @accs)
Extracts all but the sequences listed in @accs from FASTA file
$source into FASTA file $dest.
=cut
sub fasta_copy_except {
my ($source, $dest, @accs, $overwrite) = @_;
my $sfh;
my $dfh;
if (! -e $dest || $overwrite == 1) { # Check whether file exists or overwrite allowed
open_or_die(\$sfh, "<", $source);
open_or_die(\$dfh, ">", $dest);
my %acc_hash = map { $_ => 1 } @accs;
my $skip = 0;
my $num_acc = scalar (keys %acc_hash);
msg ("Number of sequences to skip: $num_acc");
while(my $row = <$sfh>) {
if (substr($row, 0, 1) eq '>') {
my ($acc) = ($row =~ m/>([^ ]*) /);
$skip = exists $acc_hash{$acc};
}
print $dfh $row if (!$skip);
}
} else {
msg ("WARNING: File $dest already exists, will not overwrite");
}
}
=item cluster ($source, $dest, $id)
Runs vsearch's cluster_fast algorithm to extract centroids
from $source into $dest at a cluster size of $id.
=cut
sub cluster {
my ($src, $dst, $id, $cpus, $overwrite) = @_;
msg("clustering database");
if (! -e $dst || $overwrite == 1) {
run_prog("vsearch",
" --cluster_fast $src "
. "--id $id "
. "--centroids $dst "
. "--notrunclabels "
. "--threads $cpus ");
} else {
msg ("WARNING: File $dst already exists, not overwriting");
}
}
# hash of IUPAC characters coding for multiple possible bases
my %IUPAC_DECODE = (
"X" => "ACGT",
"R" => "AG",
"Y" => "CT",
"M" => "CA",
"K" => "TG",
"W" => "TA",
"S" => "CG",
"B" => "CTG",
"D" => "ATG",
"H" => "ATC",
"V" => "ACG",
"N" => "ACTG");
=item fasta_copy_iupac_randomize ($source, $dest)
Creates a normalized FASTA file $dest from FASTA file $source.
=over 3
=item -
removes alignment characters ("." and "-")
=item -
uppercases all bases
=item -
turns RNA into DNA (U->T)
=item -
replaces echo IUPAC coded ambiguous base with a base randomly chosen
from the set of options (i.e. replaces B with C, T or G).
=back
=cut
sub fasta_copy_iupac_randomize {
my ($infile, $outfile, $overwrite) = @_;
my ($ifh, $ofh);
if (! -e $outfile || $overwrite == 1) {
open_or_die(\$ifh, "<", $infile);
open_or_die(\$ofh, ">", $outfile);
# iterate over lines of FASTA file
while(my $row = <$ifh>) {
# pass through FASTA header
if (substr($row, 0, 1) eq ">") {
print $ofh $row;
next;
}
# remove alignment, uppercase, turn U into T
$row =~ tr/a-zA-Z.-/A-TTV-ZA-TTV-Z/d;
# split into ok / not-ok letter segments
for my $part ( split(/([^AGCT\n])/, $row) ) {
if (not $part =~ m/[AGCT\n]/) {
# segment in need of fix, iterate chars
for my $i ( 0 .. (length($part)-1) ) {
# get replacement character list
my $rpl = $IUPAC_DECODE{substr($part, $i, 1)};
substr($part, $i, 1) =
substr($rpl, rand(length($rpl)), 1)
if defined $rpl;
}
}
print $ofh $part;
}
}
} else {
msg ("WARNING: File $outfile already exists, not overwriting");
}
}
{
package Timer;
use strict;
use Time::Piece;
use Time::Seconds;
=item Timer->new ()
starts a new timer
=cut
sub new {
my ($class) = @_;
my $self = bless {}, $class;
$self->{time} = localtime;
return $self;
}
=item Timer->minutes ()
returns the runtime of the timer in minuts
=cut
sub minutes {
my ($self) = @_;
my $endtime = localtime;
my $diff = $endtime - $self->{time};
return sprintf "%.2f minutes", $diff->minutes;
}
}
=item hash2taxstring_counts
Collapse taxonomy tree into taxstrings and report counts. Taxa are encoded as
hash refs; counts as hash values.
=cut
sub hash2taxstring_counts {
my ($href, $taxstring, $href2) = @_;
foreach my $key (keys %$href) {
if (ref ($href->{$key}) eq 'HASH') { # Recursion
hash2taxstring_counts (\%{$href->{$key}}, "$taxstring;$key", $href2);
} else { # End condition - have reached a count
$href2->{"$taxstring;$key"} = $href->{$key};
}
}
}
=item hashtreeconsensus
Walk hash of taxonomy tree and report where it diverges from single branch.
As a side effect, report taxstring of the congruent portion of the tree
=cut
sub hashtreeconsensus {
my ($href, # Reference to hash of tax tree
$aref # Reference to array to store the congruent portion of tree
) = @_;
my @keys = keys %$href;
if (scalar @keys == 1) {
push @$aref, $keys[0];
if (ref($href->{$keys[0]}) eq 'HASH') { # Recursion
hashtreeconsensus(\%{$href->{$keys[0]}}, $aref);
} else {
return '1'; # The tree is identical to the tips
}
} else {
my @diverge = keys %$href;
return \@diverge; # Return the level at which the tree diverges
}
}
=item taxstring2hash
Convert taxonomy string to a nested hash structure recursively
=cut
sub taxstring2hash {
my ($href, # Reference to hash
$aref # Reference to taxonomy string as array
) = @_;
my $taxon = shift @$aref;
if (@$aref) { # Recursion
taxstring2hash (\%{$href->{$taxon}}, $aref);
} else { # End condition - count number of occurrences of this taxon
$href->{$taxon} ++;
}
}
=item consensus_taxon_counter
Take consensus portion of an array of taxon strings and hash into a taxonomy tree
=cut
sub consensus_taxon_counter {
my ($href_in, # Hash ref for taxonomy trees keyed by read
$aref, # Array ref of list of reads to summarize
$taxlevel, # Taxonomic level for summarizing
) = @_;
my %hashout;
my %taxhash;
foreach my $read (@$aref) {
next if (!defined $href_in->{$read}); # Skip if this read has no taxonomic assignment
# Get consensus taxstring for a given read
my @outarr;
my $return = hashtreeconsensus(\%{$href_in->{$read}}, \@outarr);
if (defined $return && @outarr) {
if (scalar @outarr > $taxlevel) {
# Trim to max taxonomic rank requested
@outarr = @outarr[0..$taxlevel-1];
} elsif (scalar @outarr < $taxlevel) {
# If taxonomic rank of consensus doesn't reach to requested rank,
# repeat the lowest taxonomic rank in brackets until requested
# rank, e.g. Bacteria;Proteobacteria;(Proteobacteria);(Proteobacteria); etc...
my $diff = $taxlevel - scalar (@outarr);
push @outarr, ("($outarr[$#outarr])") x $diff; # Parens before x operator make array
}
# Hash the consensus taxonomy into a taxonomic tree, with counts
# as end values for all reads
taxstring2hash(\%{$taxhash{'ROOT'}}, \@outarr);
}
}
my %taxcounts;
hash2taxstring_counts (\%taxhash, '', \%taxcounts);
foreach my $key (keys %taxcounts) { # Replace ugly ;ROOT; from taxstring to be displayed
my $display_taxstring = $key;
$display_taxstring =~ s/^;ROOT;//;
$hashout{$display_taxstring} = $taxcounts{$key};
}
return \%hashout;
}
=item revcomp_DNA ($seq)
Return reverse complement of a DNA sequence
=cut
sub revcomp_DNA {
my ($seq) = @_;
my $rev = reverse $seq;
$rev =~ tr/ATCGatcgYRWSKMDVHByrwskmdvhb/TAGCtagcRYWSMKHBDVrywsmkhbdv/; # Include ambiguity codes
return $rev;
}
=item fix_hash_sortmerna_sam
Fix SAM file produced by Sortmerna. Returns ref to array of fixed SAM file lines
=cut
sub fix_hash_sortmerna_sam {
# Fix SAM file produced by Sortmerna v2.1b
my ($fastq,
$sam_original,
$acc2tax,
$semode) = @_;
my $pe;
if ($semode == 0) {
$pe = 1;
} else {
$pe = 0;
}
# Read in Fastq file and hash read orientations and sequences
my $fastq_href = read_interleaved_fastq ($fastq);
#print Dumper $fastq_href;
# Read in SAM file and fix bit flags 0x1, 0x40, 0x80, 0x100
my ($sambyread_href, $sambyline_aref) = read_sortmerna_sam($sam_original, $fastq_href, $pe);
# Fix flags related to read pairs: 0x2, 0x4, 0x8, 0x20
fix_pairing_flags($sambyread_href, $fastq_href) if $pe == 1;
#print Dumper $sambyread_href;
# Add back the tax strings to RNAME field
if (defined $acc2tax) {
my $acc2tax_href = retrieve ($acc2tax);
fix_rname_taxstr($sambyread_href, $acc2tax_href);
}
# Flatten hash back to array and print to output
my $aref = samaref_to_lines($sambyline_aref, $fastq_href);
#foreach my $line (@$aref) {
# print "$line\n";
#}
# Return ref to array containing the fixed SAM file including spliced
# dummy sequences for unmapped segments
# Return also sambyread_href and sambyline_aref
return ($sambyread_href,
$sambyline_aref,
$aref,
);
}
sub fix_rname_taxstr {
# Function used by fix_hash_sortmerna_sam
# Replace the accession number of RNAME with the original version
# retrieved from hash of acc vs taxstring
my ($sam_href,
$acc_href
) = @_;
foreach my $id (keys %$sam_href) {
foreach my $segment (keys %{$sam_href->{$id}}) {
foreach my $rname (keys %{$sam_href->{$id}{$segment}}) {
foreach my $href (@{$sam_href->{$id}{$segment}{$rname}}) {
my $new_rname = join " ", ($href->{'RNAME'}, $acc_href->{$href->{'RNAME'}});
$href->{'RNAME'} = $new_rname;
}
}
}
}
}
sub samaref_to_lines {
# Function used by fix_hash_sortmerna_sam
# Reconstruct SAM lines, and also insert dummy entries for unmapped read fwd segments
# Input is an array of hash references and hash of Fastq sequences produced
# by read_interleaved_fastq()
my ($aref,
$fastq_href) = @_;
my @lines;
foreach my $href (@$aref) {
# Split read ID
my $id_fwd = $href->{'QNAME'};
#my $id_rev = $href->{'QNAME'};
my $sep;
if ($id_fwd =~ m/^(.+)([:\/_])[12]$/) {
$id_fwd = $1.$2.'1';
#$id_rev = $1.$2.'2';
}
# Splice in first segment dummy entry if this is rev with fwd read unmapped
if ($href->{'FLAG'} & 0x80 && $href->{'FLAG'} & 0x8) {
my @splice = ($id_fwd, # QNAME
0x1 + 0x4 + 0x40, # Paired read, segment unmapped, first segment
'*', # RNAME
'0', # POS
'255', # MAPQ
'*', # CIGAR
'*', # RNEXT
'0', # PNEXT
'0', # TLEN
$fastq_href->{$href->{'QNAME'}}{'fwd'}{'seq'}, # SEQ
$fastq_href->{$href->{'QNAME'}}{'fwd'}{'qual'} # QUAL
);
push @lines, join "\t", @splice unless $href->{'FLAG'} & 0x100;
}
# Otherwise continue
my @outarr;
my @fields = qw(QNAME FLAG RNAME POS MAPQ CIGAR RNEXT PNEXT TLEN SEQ QUAL);
foreach my $field (@fields) {