lib/Mashtree.pm

filter: Statementstmt 91.6% 22 / 24 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 8 / 8 Podpod n/a totaltotal 93.7% 30 / 32 CC 1 SCAR 0.4
CC
1
Cov
92%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/Mashtree/Mash.pm ↑ Summary bin/mashtree »
1 #!/usr/bin/env perl
2 package Mashtree;
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use Exporter qw(import);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use File::Basename qw/fileparse basename dirname/;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use List::Util qw/shuffle/;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Scalar::Util qw/looks_like_number/;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 0 ▶use threads;
Subroutine BEGIN: called CC=1 SCAR=2.6
12 use threads::shared;
13  
14 use lib dirname($INC{"Mashtree.pm"});
15 use Bio::Matrix::IO;
16 use Bio::TreeIO;
17  
18 our @EXPORT_OK = qw(
19 logmsg openFastq _truncateFilename distancesToPhylip createTreeFromPhylip sortNames treeDist mashDist mashHashes raw_mash_distance raw_mash_distance_unequal_sizes
20 @fastqExt @fastaExt @bamExt @vcfExt @richseqExt @mshExt
21 $MASHTREE_VERSION
22 );
23  
24 local $0=basename $0;
25  
26 =pod
27  
28 =head1 NAME Mashtree
29  
30 =head1 SYNOPSIS
31  
32 Helps run a mashtree analysis to make rapid trees for genomes.
33 Please see github.com/lskatz/Mashtree for more information.
34  
35 =over
36  
37 =item mashtree executables
38  
39 This document covers the Mashtree library, but the highlight
40 the mashtree package is the executable `mashtree`.
41 See github.com/lskatz/Mashtree for more information.
42  
43 Fast method:
44  
45 mashtree --numcpus 12 *.fastq.gz [*.fasta] > mashtree.dnd
46  
47 More accurate method:
48  
49 mashtree --mindepth 0 --numcpus 12 *.fastq.gz [*.fasta] > mashtree.dnd
50  
51 Bootstrapping and jackknifing
52  
53 mashtree_bootstrap.pl --reps 100 --numcpus 12 *.fastq.gz -- --min-depth 0 > mashtree.jackknife.dnd
54 mashtree_jackknife.pl --reps 100 --numcpus 12 *.fastq.gz -- --min-depth 0 > mashtree.jackknife.dnd
55  
56 =back
57  
58 =head1 VARIABLES
59  
60 =over
61  
62 =item $VERSION
63  
64 =item $MASHTREE_VERSION (same value as $VERSION)
65  
66 =item @fastqExt = qw(.fastq.gz .fastq .fq .fq.gz)
67  
68 =item @fastaExt = qw(.fasta .fna .faa .mfa .fas .fsa .fa)
69  
70 =item @bamExt = qw(.sorted.bam .bam)
71  
72 =item @vcfExt = qw(.vcf.gz .vcf)
73  
74 =item @mshExt = qw(.msh)
75  
76 =item @richseqExt = qw(.gb .gbank .genbank .gbk .gbs .gbf .embl .ebl .emb .dat .swiss .sp)
77  
78 =item $fhStick :shared
79  
80 Used to mark whether a file is being read, so that Mashtree limits disk I/O
81  
82 =back
83  
84 =cut
85  
86 ######
87 # CONSTANTS
88  
89 our $VERSION = "1.4.6";
90 our $MASHTREE_VERSION=$VERSION;
91 our @fastqExt=qw(.fastq.gz .fastq .fq .fq.gz);
92 our @fastaExt=qw(.fasta .fna .faa .mfa .fas .fsa .fa);
93 our @bamExt=qw(.sorted.bam .bam);
94 our @vcfExt=qw(.vcf.gz .vcf);
95 our @mshExt=qw(.msh);
96 # Richseq extensions were obtained mostly from bioperl under
97 # the genbank, embl, and swissprot entries, under
98 # the source for Bio::SeqIO
99 our @richseqExt=qw(.gb .gbank .genbank .gbk .gbs .gbf .embl .ebl .emb .dat .swiss .sp);
100  
101 # Helpful things
102 my $fhStick :shared; # A thread can only open a fastq file if it has the talking stick.
103  
104 =head1 METHODS
105  
106 =over
107  
108 =item $SIG{'__DIE__'}
109  
110 Remakes how `die` works, so that it references the caller
111  
112 =cut
113  
114 #################################################
115 ### COMMON SUBS/TOOLS (not object subroutines) ##
116 #################################################
117 # Redefine how scripts die
118 $SIG{'__DIE__'} = sub {
119 local $0=basename($0);
120 my $e = $_[0] || "";
121 my $callerSub=(caller(1))[3] || (caller(0))[3] || "UnknownSub";
122  
123 $e =~ s/(at [^\s]+? line \d+\.$)/\nStopped $1/;
124 die("$0: $callerSub: $e");
125 };
126  
127 =pod
128  
129 =item logmsg
130  
131 Prints a message to STDERR with the thread number and the program name, with a trailing newline.
132  
133 =cut
134  
135 # Centralized logmsg
136 #sub logmsg {print STDERR "$0: ".(caller(1))[3].": @_\n";}
137 sub logmsg {
138 local $0=basename $0;
139 my $parentSub=(caller(1))[3] || (caller(0))[3];
140 $parentSub=~s/^main:://;
141  
142 # Find the thread ID and stringify it
143 my $tid=threads->tid;
144 $tid=($tid) ? "(TID$tid)" : "";
145  
146 my $msg="$0: $parentSub$tid: @_\n";
147  
148 print STDERR $msg;
149 }
150  
151 =pod
152  
153 =item openFastq
154  
155 Opens a fastq file in a thread-safe way.
156  
157 =cut
158  
159 sub openFastq{
160 my($fastq,$settings)=@_;
161  
162 my $fh;
163  
164 lock($fhStick);
165  
166 my @fastqExt=qw(.fastq.gz .fastq .fq.gz .fq);
167 my($name,$dir,$ext)=fileparse($fastq,@fastqExt);
168 if($ext =~/\.gz$/){
169 open($fh,"zcat $fastq | ") or die "ERROR: could not open $fastq for reading!: $!";
170 } else {
171 open($fh,"<",$fastq) or die "ERROR: could not open $fastq for reading!: $!";
172 }
173 return $fh;
174 }
175  
176 =pod
177  
178 =item _truncateFilename
179  
180 Removes fastq extension, removes directory name,
181  
182 =cut
183  
184 sub _truncateFilename{
185 my($file,$settings)=@_;
186 # strip off msh and any other known extentions
187 my $name=$file;
188 my $oldName="";
189 # Strip until we get convergence
190 while($name ne $oldName){
191 $oldName = $name;
192 $name = basename($name,@mshExt,@fastqExt,@richseqExt,@fastaExt);
193 }
194 return $name;
195 }
196  
197 =pod
198  
199 =item distancesToPhylip
200  
201 1. Read the mash distances
202 2. Create a phylip file
203  
204 Arguments: hash of distances, output directory, settings hash
205  
206 =cut
207  
208 sub distancesToPhylip{
209 my($distances,$outdir,$settings)=@_;
210  
211 my $phylip = "$outdir/distances.phylip";
212 # NOTE: need to regenerate the combined distances each time
213 # because I need to allow variation in the input samples.
214 #return $phylip if(-e $phylip);
215  
216 # The way phylip is, I need to know the genome names
217 # a priori
218 my %name;
219 open(MASHDIST,"<",$distances) or die "ERROR: could not open $distances for reading: $!";
220 while(<MASHDIST>){
221 next if(/^#/);
222 my($name)=split(/\t/,$_);
223 $name=~s/^\s+|\s+$//g; # whitespace trim before right-padding is added
224 $name{_truncateFilename($name,$settings)}=1;
225 }
226 close MASHDIST;
227 my @name=sortNames([keys(%name)],$settings);
228 # Index the array
229 my $columnIndex=0;
230 for(@name){
231 $name{$_}=$columnIndex++;
232 }
233  
234 # Load up the matrix object
235 logmsg "Reading the distances file at $distances";
236 open(MASHDIST,"<",$distances) or die "ERROR: could not open $distances for reading: $!";
237 my $query="UNKNOWN"; # Default ID in case anything goes wrong
238 my @m;
239 while(<MASHDIST>){
240 chomp;
241 if(/^#query\s+(.+)/){
242 $query=_truncateFilename($1,$settings);
243 } else {
244 my ($reference,$distance)=split(/\t/,$_);
245 $reference=_truncateFilename($reference,$settings);
246 $distance=sprintf("%0.10f",$distance);
247 $m[$name{$query}][$name{$reference}]=$distance;
248 $m[$name{$reference}][$name{$query}]=$distance;
249 }
250 }
251 close MASHDIST;
252 #my $matrixObj=Bio::Matrix::Generic->new(-rownames=>\@name,-colnames=>\@name,-values=>\@m);
253  
254 # taking this method from write_matrix in http://cpansearch.perl.org/src/CJFIELDS/BioPerl-1.6.924/Bio/Matrix/IO/phylip.pm
255 my $str;
256 $str.=(" " x 4) . scalar(@name)."\n";
257 for(my $i=0;$i<@name;$i++){
258 $str.=$name[$i];
259 my $count=0;
260 for(my $j=0;$j<@name;$j++){
261 if($count < $#name){
262 $str.=$m[$i][$j]. " ";
263 } else {
264 $str.=$m[$i][$j];
265 }
266 $count++;
267 }
268 $str.="\n";
269 }
270 open(PHYLIP,">",$phylip) or die "ERROR: could not write to $phylip: $!";
271 print PHYLIP $str;
272 close PHYLIP;
273 return $phylip;
274 }
275  
276 =pod
277  
278 =item sortNames
279  
280 Sorts names.
281  
282 Arguments:
283  
284 1. $name - array of names
285 2. $settings - options
286 * $$settings{'sort-order'} is either "abc", "random", "input-order"
287  
288 =cut
289  
290 sub sortNames{
291 my($name,$settings)=@_;
292 my @sorted;
293 if($$settings{'sort-order'} =~ /^(abc|alphabet)$/){
294 @sorted=sort { $a cmp $b } @$name;
295 } elsif($$settings{'sort-order'}=~/^rand(om)?/){
296 @sorted=shuffle(@$name);
297 } elsif($$settings{'sort-order'} eq 'input-order'){
298 @sorted=@$name;
299 } else {
300 die "ERROR: I don't understand sort-order $$settings{'sort-order'}";
301 }
302 return @sorted;
303 }
304  
305 =pod
306  
307 =item createTreeFromPhylip($phylip, $outdir, $settings)
308  
309 Create tree file with Quicktree but bioperl
310 as a backup.
311  
312 =cut
313  
314 sub createTreeFromPhylip{
315 my($phylip,$outdir,$settings)=@_;
316  
317 my $treeObj;
318  
319 my $quicktreePath=`which quicktree 2>/dev/null`;
320 # bioperl if there was an error with which quicktree
321 if($?){
322 logmsg "DEPRECATION WARNING: CANNOT FIND QUICKTREE IN YOUR PATH. I will use BioPerl to make the tree this time, but it will be removed in the next version.";
323 #logmsg "Creating tree with BioPerl";
324 my $dfactory = Bio::Tree::DistanceFactory->new(-method=>"NJ");
325 my $matrix = Bio::Matrix::IO->new(-format=>"phylip", -file=>$phylip)->next_matrix;
326 $treeObj = $dfactory->make_tree($matrix);
327 open(TREE,">","$outdir/tree.dnd") or die "ERROR: could not open $outdir/tree.dnd: $!";
328 print TREE $treeObj->as_text("newick");
329 print TREE "\n";
330 close TREE;
331 }
332 # quicktree
333 else {
334 #logmsg "Creating tree with QuickTree";
335 system("quicktree -in m $phylip > $outdir/tree.dnd.tmp");
336 die "ERROR with quicktree" if $?;
337 $treeObj=Bio::TreeIO->new(-file=>"$outdir/tree.dnd.tmp")->next_tree;
338 open(my $treeFh, ">", "$outdir/tree.dnd") or die "ERROR: could not write to $outdir/tree.dnd: $!";
339 print $treeFh $treeObj->as_text("newick")."\n";
340 #my $outtree=Bio::TreeIO->new(-file=>">$outdir/tree.dnd", -format=>"newick");
341 #$outtree->write_tree($treeObj);
342  
343 unlink("$outdir/tree.dnd.tmp");
344 }
345  
346 return $treeObj;
347  
348 }
349  
350 =pod
351  
352 =item treeDist($treeObj1, $treeObj2)
353  
354 Lee's implementation of a tree distance. The objective
355 is to return zero if two trees are the same.
356  
357 =cut
358  
359 sub treeDist{
360 my($treeObj1,$treeObj2)=@_;
361  
362 # If the tree objects are really strings, then make Bio::Tree::Tree objects
363 if(!ref($treeObj1)){
364 if(-e $treeObj1){ # if this is a file, get the contents
365 $treeObj1=`cat $treeObj1`;
366 }
367 $treeObj1=Bio::TreeIO->new(-string=>$treeObj1)->next_tree;
368 }
369 if(!ref($treeObj2)){
370 if(-e $treeObj2){ # if this is a file, get the contents
371 $treeObj2=`cat $treeObj2`;
372 }
373 $treeObj2=Bio::TreeIO->new(-string=>$treeObj2)->next_tree;
374 }
375 for($treeObj1,$treeObj2){
376 #$_->force_binary;
377 }
378
379 # Get all leaf nodes so that they can be compared
380 my @nodes1=sort {$a->id cmp $b->id} grep{$_->is_Leaf} $treeObj1->get_nodes;
381 my @nodes2=sort {$a->id cmp $b->id} grep{$_->is_Leaf} $treeObj2->get_nodes;
382 my $numNodes=@nodes1;
383  
384 # Test 1: are these the same nodes?
385 my $nodeString1=join(" ",map{$_->id} @nodes1);
386 my $nodeString2=join(" ",map{$_->id} @nodes2);
387 if($nodeString1 ne $nodeString2){
388 # TODO print out the differing nodes?
389 logmsg "ERROR: nodes are not the same in both trees!\n $nodeString1\n $nodeString2";
390 return ~0; #largest int
391 }
392  
393 # Find the number of branches it takes to get to each node.
394 # Turn it into a Euclidean distance
395 my $euclideanDistance=0;
396 for(my $i=0;$i<$numNodes;$i++){
397 for(my $j=$i+1;$j<$numNodes;$j++){
398 my ($numBranches1,$numBranches2);
399  
400 my $lca1=$treeObj1->get_lca($nodes1[$i],$nodes1[$j]);
401 my $lca2=$treeObj2->get_lca($nodes2[$i],$nodes2[$j]);
402
403 # Distance in tree1
404 my $distance1=0;
405 my @ancestory1=reverse $treeObj1->get_lineage_nodes($nodes1[$i]);
406 my @ancestory2=reverse $treeObj1->get_lineage_nodes($nodes1[$j]);
407 for my $currentNode(@ancestory1){
408 $distance1++;
409 last if($currentNode eq $lca1);
410 }
411 for my $currentNode(@ancestory2){
412 $distance1++;
413 last if($currentNode eq $lca1);
414 }
415
416 # Distance in tree2
417 my $distance2=0;
418 my @ancestory3=reverse $treeObj2->get_lineage_nodes($nodes2[$i]);
419 my @ancestory4=reverse $treeObj2->get_lineage_nodes($nodes2[$j]);
420 for my $currentNode(@ancestory3){
421 $distance2++;
422 last if($currentNode eq $lca2);
423 }
424 for my $currentNode(@ancestory4){
425 $distance2++;
426 last if($currentNode eq $lca2);
427 }
428  
429 if($distance1 != $distance2){
430 logmsg "These two nodes do not have the same distance between trees: ".$nodes1[$i]->id." and ".$nodes1[$j]->id;
431 }
432  
433 # Add up the Euclidean distance
434 $euclideanDistance+=($distance1 - $distance2) ** 2;
435 }
436 }
437 $euclideanDistance=sqrt($euclideanDistance);
438 return $euclideanDistance;
439 }
440  
441 =pod
442  
443 =item mashDist($file1, $file2, $k, $settings)
444  
445 Find the distance between two mash sketch files
446 Alternatively: two hash lists.
447  
448 =cut
449  
450 sub mashDist{
451 my($file1, $file2, $k, $settings)=@_;
452  
453 my($hashes1, $hashes2, $kmer1, $kmer2);
454 if(ref($file1) eq 'ARRAY'){
455 $hashes1 = $file1;
456 $kmer1 = -1;
457 } else {
458 ($hashes1, $kmer1) = mashHashes($file1);
459 }
460 if(ref($file2) eq 'ARRAY'){
461 $hashes2 = $file2;
462 $kmer2 = -1;
463 } else {
464 ($hashes2, $kmer2) = mashHashes($file2);
465 }
466  
467 if($kmer1 ne $kmer2){
468 die "ERROR: kmer lengths do not match($kmer1 vs $kmer2)";
469 }
470  
471 # Set the default kmer length and perform sanity check
472 $k ||= $kmer1;
473 if(!looks_like_number($k)){
474 die "ERROR: k was not set to an integer";
475 }
476 if($k < 1){
477 die "ERROR: k was undefined or set to less than 1";
478 }
479  
480 my($common, $total) = (0,0);
481 if(scalar(@$hashes1) != scalar(@$hashes2)){
482 ($common, $total) = raw_mash_distance_unequal_sizes($hashes1, $hashes2);
483 } else {
484 ($common, $total) = raw_mash_distance($hashes1, $hashes2);
485 }
486 my $jaccard = $common/$total;
487 my $mash_distance = -1/$k * log(2*$jaccard / (1+$jaccard));
488 #logmsg "========== $mash_distance = -1/$k * log(2*$jaccard / (1+$jaccard)) ==============";
489  
490 return $mash_distance;
491 }
492  
493 =pod
494  
495 =item mashHashes($sketch)
496  
497 Return an array of hashes, the kmer length, and the genome estimated length
498  
499 =cut
500  
501 sub mashHashes{
502 my($sketch)=@_;
503 my @hash;
504 my $length = 0;
505 my $kmer = 0;
506  
507 if(!-e $sketch){
508 die "ERROR: file not found: $sketch";
509 }
510  
511 my $fh;
512 if($sketch =~ /\.msh$/){
513 open($fh, "mash info -d $sketch | ") or die "ERROR: could not run mash info -d on $sketch: $!";
514 } elsif($sketch =~ /\.json$/){
515 open($fh, $sketch) or die "ERROR: could not read $sketch: $!";
516 }
517 while(<$fh>){
518 if(/kmer\D+(\d+)/){
519 $kmer = $1;
520 }
521 elsif(/length\D+(\d+)/){
522 $length = $1;
523 }
524 elsif(/hashes/){
525 while(<$fh>){
526 last if(/\]/);
527 next if(!/\d/);
528 s/\D+//g;
529 s/^\s+|\s+$//g;
530 push(@hash, $_);
531 }
532 }
533 }
534 if(!@hash){
535 die "ERROR: no hashes found in $sketch";
536 }
537 return (\@hash, $kmer, $length);
538 }
539  
540 =pod
541  
542 =item raw_mash_distance_unequal_sizes($hashes1, $hashes2)
543  
544 Compare unequal sized hashes. Treat the first
545 set of hashes as the reference (denominator)
546 set.
547  
548 =cut
549  
550 sub raw_mash_distance_unequal_sizes{
551 my($hashes1, $hashes2) = @_;
552  
553 my (%sketch1,%sketch2);
554 @sketch1{@$hashes1} = (1) x scalar(@$hashes1);
555 @sketch2{@$hashes2} = (1) x scalar(@$hashes2);
556  
557 my %union;
558 for my $h(@$hashes1){
559 if($sketch2{$h}){
560 $union{$h}++;
561 }
562 }
563  
564 my $common = scalar(keys(%union));
565 my $total = scalar(@$hashes1);
566  
567 return($common,$total);
568 }
569  
570 =pod
571  
572 =item raw_mash_distance($hashes1, $hashes2)
573  
574 Return the number of kmers in common and the number compared total. inspiration from
575 https://github.com/onecodex/finch-rs/blob/master/src/distance.rs#L34
576  
577 =cut
578  
579 sub raw_mash_distance{
580 my($hashes1, $hashes2) = @_;
581  
582 my @sketch1 = sort {$a <=> $b} @$hashes1;
583 my @sketch2 = sort {$a <=> $b} @$hashes2;
584  
585 my $i = 0;
586 my $j = 0;
587 my $common = 0;
588 my $total = 0;
589  
590 my $sketch_size = @sketch1;
591 while($total < $sketch_size && $i < @sketch1 && $j < @sketch2){
592 my $ltgt = ($sketch1[$i] <=> $sketch2[$j]); # -1 if sketch1 is less than, +1 if sketch1 is greater than
593  
594 if($ltgt == -1){
595 $i += 1;
596 } elsif($ltgt == 1){
597 $j += 1;
598 } elsif($ltgt==0) {
599 $i += 1;
600 $j += 1;
601 $common += 1;
602 } else {
603 die "Internal error";
604 }
605  
606 $total += 1;
607 }
608  
609 if($total < $sketch_size){
610 if($i < @sketch1){
611 $total += @sketch1 - 1;
612 }
613  
614 if($j < @sketch2){
615 $total += @sketch2 - 1;
616 }
617  
618 if($total > $sketch_size){
619 $total = $sketch_size;
620 }
621 }
622  
623 return ($common, $total);
624 }
625  
626 # Calculates the Transfer Bootstrap Expectation (TBE) for internal nodes based on
627 # the methods outlined in Lemoine et al, Nature, 2018.
628 # Currently experimental.
629 # I entered this sub into bioperl > v1.7.5 but it is worth
630 # having locally here to help maintain compatibility.
631 # The only difference is that it isn't an object method
632 # and that it is called without an OO implementation.
633  
634 =item transfer_bootstrap_expectation
635  
636 Title : transfer_bootstrap_expectation
637 Usage : my $tree_with_bs = transfer_bootstrap_expectation(\@bs_trees,$guide_tree);
638 Function: Calculates the Transfer Bootstrap Expectation (TBE) for internal nodes based on
639 the methods outlined in Lemoine et al, Nature, 2018.
640 Currently experimental.
641 Returns : L<Bio::Tree::TreeI>
642 Args : Arrayref of L<Bio::Tree::TreeI>s
643 Guide tree, L<Bio::Tree::TreeI>s
644  
645 =back
646  
647 =cut
648  
649 sub transfer_bootstrap_expectation{
650 my ($bs_trees,$guide_tree) = @_;
651  
652 if(!defined($bs_trees) || ref($bs_trees) ne 'ARRAY'){
653 die "ERROR: second parameter in assess_bootstrap() must be a list";
654 }
655 my $num_bs_trees = scalar(@$bs_trees);
656 if($num_bs_trees < 1){
657 die "ERROR: no bootstrap trees were passed to ".(caller(0))[3];
658 }
659  
660 # internal nodes are defined by their children
661 my %internal = ();
662 my %leafNameId = ();
663 my @idLookup = ();
664 my @internalLookup = ();
665 my @tree = ($guide_tree, @$bs_trees);
666 my $numTrees = scalar(@tree);
667 for(my $i = 0; $i < $numTrees; $i++){ # guide tree's index is $i==0
668 # Do this as a top down approach, can probably be
669 # improved by caching internal node states, but not going
670 # to worry about it right now.
671  
672 my @allnodes = $tree[$i]->get_nodes;
673 my @internalnodes = grep { ! $_->is_Leaf } @allnodes;
674 for my $node ( @internalnodes ) {
675 my @tips = sort map { $_->id }
676 grep { $_->is_Leaf() } $node->get_all_Descendents;
677 my $id = join(",", @tips);
678 # Map the concatenated-leaf ID to the internal ID on the guide tree
679 if( $i == 0 ) {
680 $internal{$id} = $node->internal_id;
681 $leafNameId{$node->internal_id} = $id;
682 }
683  
684 # Record the tips for each tree's internal node
685 # ID lookup (concatenated string of leaf names)
686 $idLookup[$i]{$id} = \@tips;
687 # Internal ID lookup
688 $internalLookup[$i]{$internal{$id}} = \@tips;
689 }
690 }
691  
692 # Find the average distance from branch b to all
693 # bootstrap trees' branches b*
694 my @id = sort keys %internal;
695 my $numIds = @id;
696 # Loop through all internal nodes of the guide tree
697 for(my $j=0; $j<$numIds; $j++){
698 my $refNode = $guide_tree->find_node(-internal_id => $internal{$id[$j]});
699 my $refNodeId = $refNode->internal_id;
700 my $refJoinId = $leafNameId{$refNodeId};
701 my $refLeaves = $idLookup[0]{$refJoinId};
702 my %refLeafIndex = map{$_=>1} @$refLeaves;
703 #next if(!defined($refLeaves));
704  
705 # For each internal node, start calculating for
706 # an average TBE distance.
707 my $nodeTbeTotal = 0;
708
709 # Loop through all bootstrap trees, skipping the 0th
710 # tree which is the guide tree.
711 for(my $i=1;$i<$numTrees;$i++){
712  
713 # Find the right branch to bootstrap with. The right
714 # branch will be the one that has the smallest
715 # TBE distance.
716 my @bsNode = grep {!$_->is_Leaf} $tree[$i]->get_nodes;
717 my $numBsIds = scalar(@bsNode);
718 my $minDistance = ~0; # large int
719 for(my $k=0;$k<$numBsIds;$k++){
720 my @queryLeaves = sort map { $_->id }
721 grep { $_->is_Leaf() } $bsNode[$k]->get_all_Descendents;
722  
723 my %queryLeafIndex = map{$_=>1} @queryLeaves;
724  
725 # How many moves does it take to go from query to ref?
726 my $dist=0;
727 for my $queryLeaf(@queryLeaves){
728 if(!$refLeafIndex{$queryLeaf}){
729 $dist++;
730 }
731 }
732 for my $refLeaf(@$refLeaves){
733 if(!$queryLeafIndex{$refLeaf}){
734 $dist++;
735 }
736 }
737  
738 if($dist < $minDistance){
739 $minDistance = $dist;
740 }
741 }
742 $nodeTbeTotal += $minDistance;
743 }
744 my $avgTbe = $nodeTbeTotal / $numTrees;
745
746 # Calculate the average of all b to b* distances
747 # But it is also 1 - average.
748 my $numRefLeaves = scalar(@$refLeaves);
749 my $nodeTbe = 1 - $avgTbe/$numRefLeaves;
750 # Round to an integer
751 $refNode->bootstrap(sprintf("%0.0f",100 * $nodeTbe));
752 }
753
754 return $guide_tree;
755 }
756  
757 1;
758  
759  
760 __END__
« blib/lib/Mashtree/Mash.pm ↑ Summary bin/mashtree »