Class: NewickTree

Inherits:
Object
  • Object
show all
Defined in:
lib/Newick.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(treeString) ⇒ NewickTree

Returns a new instance of NewickTree.



351
352
353
354
# File 'lib/Newick.rb', line 351

def initialize(treeString)
  tokenizer = NewickTokenizer.new(treeString)
  @root = buildTree(nil, tokenizer)
end

Instance Attribute Details

#rootObject (readonly)

Returns the value of attribute root.



350
351
352
# File 'lib/Newick.rb', line 350

def root
  @root
end

Class Method Details

.fromFile(fileName) ⇒ Object

create new NewickTree from tree stored in file



357
358
359
360
361
362
363
364
365
366
# File 'lib/Newick.rb', line 357

def NewickTree.fromFile(fileName)
  treeString = ""
  inFile = File.new(fileName)
  inFile.each {|line|
    treeString += line.chomp
  }
  inFile.close
  treeString.gsub!(/\[[^\]]*\]/,"") # remove comments before parsing
  return NewickTree.new(treeString)
end

Instance Method Details

#addBootStrap(bootClades) ⇒ Object

add bootstrap values (given in clade arrays) to a tree



636
637
638
639
640
641
642
643
644
645
646
# File 'lib/Newick.rb', line 636

def addBootStrap(bootClades)
  @root.descendants.each {|clade|
    next if clade.leaf?
    bootClades.each {|bClade|
	boot, rest = bClade.first, bClade[1..bClade.size - 1]
	if (rest == clade.taxa ) # same clade found
 clade.name = boot
	end
    }
  }
end

#addECnums(alignFile) ⇒ Object

add EC numbers from alignment



583
584
585
586
587
588
589
590
591
592
593
594
595
# File 'lib/Newick.rb', line 583

def addECnums(alignFile)
  ec = Hash.new
  File.new(alignFile).each {|line|
    if (line =~ /^>/)
	definition = line.chomp[1..line.length]
	name = definition.split(" ").first
	if (definition =~ /\[EC:([0-9|\.]*)/)
 ec[name] = name + "_" + $1
	end
    end
  }
  unAlias(ec)
end

#alias(aliasFile = nil, longAlias = false) ⇒ Object

renames nodes and creates an alias file, returning aliased tree and hash



432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# File 'lib/Newick.rb', line 432

def alias(aliasFile = nil, longAlias = false)
  ali = Hash.new
  aliF = File.new(aliasFile, "w") if (!aliasFile.nil?)
  if (longAlias)
    taxon = "SEQ" + "0"* taxa.sort {|x,y| x.length <=> y.length}.last.length
  else
    taxon =  "SEQ0000001"
  end
  @root.descendants.each {|node|
    if (node.name != "" && node.name.to_i == 0)
	ali[taxon] = node.name
	aliF.printf("%s\t%s\n", taxon, node.name) if (!aliasFile.nil?)
	node.name = taxon.dup
	taxon.succ!
    end
  }
  aliF.close if (!aliasFile.nil?)
  return self, ali
end

#buildTree(parent, tokenizer) ⇒ Object

internal function used for building tree structure from string



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
# File 'lib/Newick.rb', line 369

def buildTree(parent, tokenizer)
  while (!(token = tokenizer.nextToken).nil?)
    if (token.type == "LABEL")
	name = token.value
	edgeLen = 0
	if (tokenizer.peekToken.type == "WEIGHT")
 edgeLen = tokenizer.nextToken.value.to_f
	end
	node = NewickNode.new(name, edgeLen)
	return node
    elsif (token.value == "(")
	node = NewickNode.new("", 0)
	forever = true
	while (forever)
 child = buildTree(node, tokenizer)
 node.addChild(child)
 break if tokenizer.peekToken.value != ","
 tokenizer.nextToken
	end
	if (tokenizer.nextToken.value != ")")
 raise NewickParseError, "Expected ')' but found: #{token.value}"
	else
 peek = tokenizer.peekToken
 if (peek.value == ")" || peek.value == "," || peek.value == ";")
   return node
 elsif (peek.type == "WEIGHT")
   node.edgeLen = tokenizer.nextToken.value.to_f
   return node
 elsif (peek.type == "LABEL")
   token = tokenizer.nextToken
   node.name = token.value
   if (tokenizer.peekToken.type == "WEIGHT")
     node.edgeLen = tokenizer.nextToken.value.to_f
   end
   return node
 end
	end 
    else
	raise NewickParseError, 
 "Expected '(' or label but found: #{token.value}"
    end
  end
end

#calcPos(yUnit) ⇒ Object

calculates leaf node positions (backwards from leaves, given spacing)



677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
# File 'lib/Newick.rb', line 677

def calcPos(yUnit)
  yPos = 0.25
  @root.reorder
  leaves = @root.leaves.sort {|x, y| x.nodesToNode(y) <=> y.nodesToNode(x)}
  leaves.each {|leaf|
    leaf.y = yPos
    yPos += yUnit
  }
  nodes =  @root.intNodes.sort{|x, y| y.nodesToAncestor(@root) <=> 
                                     x.nodesToAncestor(@root)}
  nodes.each {|node|
    node.calcYPos
  }
  @root.calcYPos
  @root.calcXPos
  nodes =  @root.intNodes.sort{|x, y| x.nodesToAncestor(@root) <=> 
                                     y.nodesToAncestor(@root)}
  nodes.each {|node|
    @root.calcXPos # (forwards from root)
  }
end

#clades(bootstrap = false) ⇒ Object

returns array of arrays representing the tree clades



627
628
629
630
631
632
633
# File 'lib/Newick.rb', line 627

def clades(bootstrap = false)
  clades = []
  @root.descendants.each {|clade|
    clades.push(clade.taxa(bootstrap)) if (!clade.children.empty?)
  }
  return clades
end

#compare(tree) ⇒ Object

returns lists of clades different between two trees



496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
# File 'lib/Newick.rb', line 496

def compare(tree)
  tree1 = self.dup.unroot
  tree2 = tree.dup.unroot
  
  diff1 = []
  diff2 = []
  if (tree1.taxa == tree2.taxa)
    clades1 = tree1.clades
    clades2 = tree2.clades
    clades1.each {|clade|
	if (!clades2.include?(clade))
 diff1.push(clade)
	end
    }
    clades2.each {|clade|
	if (!clades1.include?(clade))
 diff2.push(clade)
	end
    }
  else
    raise NewickParseError, "The trees have different taxa!"
  end
  return diff1, diff2
end

#distanceMatrixObject

returns a 2D hash of pairwise distances on tree



476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
# File 'lib/Newick.rb', line 476

def distanceMatrix
  dMatrix = Hash.new
  @root.taxa.each {|taxon1|
    dMatrix[taxon1] = Hash.new
    taxon1Node = @root.findNode(taxon1)
    @root.taxa.each {|taxon2|
	if (taxon1 == taxon2)
 dMatrix[taxon1][taxon2] = 0.0
	else
 taxon2Node = @root.findNode(taxon2)
 lca = taxon1Node.lca(taxon2Node)
 dMatrix[taxon1][taxon2] = taxon1Node.distToAncestor(lca) + 
   taxon2Node.distToAncestor(lca)
	end
    }
  }
  return dMatrix
end

#draw(pdfFile, boot = "width", linker = :giLink, labelName = false, highlights = Hash.new, brackets = nil, rawNames = false) ⇒ Object

returns PDF representation of branching structure of tree



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
# File 'lib/Newick.rb', line 711

def draw(pdfFile, boot="width", linker = :giLink, labelName = false,
  highlights = Hash.new, brackets = nil, rawNames = false)
  pdf=FPDF.new('P', "cm")
  pdf.SetTitle(pdfFile)
  pdf.SetCreator("newickDraw")
  pdf.SetAuthor(ENV["USER"]) if (!ENV["USER"].nil?)
  pdf.AddPage
  yUnit = nil
  lineWidth = nil
  fontSize = nil
  bootScale = 0.6
  if (taxa.size < 30)
    fontSize = 10
    yUnit = 0.5
    lineWidth = 0.02
  elsif (taxa.size < 60)
    fontSize = 8
    yUnit = 0.25
    lineWidth = 0.01
  elsif (taxa.size < 150)
    fontSize = 8
    yUnit = 0.197
    lineWidth = 0.01
  elsif (taxa.size < 300)
    fontSize = 2
    yUnit = 0.09
    lineWidth = 0.005
  elsif (taxa.size < 400)
    fontSize = 2
    yUnit = 0.055
    lineWidth = 0.002
  elsif (taxa.size < 800)
    fontSize = 1
    yUnit = 0.030
    lineWidth = 0.0015
  else
    fontSize = 0.5
    yUnit = 0.020
    lineWidth = 0.0010
  end
  bootScale = 0.5 * fontSize
  pdf.SetFont('Times','B', fontSize)
  calcPos(yUnit) # calculate node pos before drawing
  max = 0
  @root.leaves.each {|leaf|
    d = leaf.distToAncestor(@root)
    max = d if (max < d)
  }
  xScale = 10.0/max
  xOffSet = 0.25
  pdf.SetLineWidth(lineWidth)
  pdf.SetTextColor(0, 0, 0)
  pdf.Line(0, @root.y, xOffSet, @root.y)
  pdf.Line(xOffSet, @root.yMin, xOffSet, @root.yMax)
  @root.descendants.each {|child|
    if (!child.leaf?)
      if (child.name.to_i > 75 && boot == "width") # good bootstrap
        pdf.SetLineWidth(lineWidth * 5)
      else
        pdf.SetLineWidth(lineWidth)
      end
     bootX = xOffSet + child.x*xScale 
     bootY = ((child.yMin + child.yMax) / 2.0) 
     pdf.SetXY(bootX, bootY) 
     pdf.SetFont('Times','B', bootScale)
     pdf.Write(0, child.name.to_s)
     pdf.SetFont('Times','B', fontSize)
      pdf.Line(xOffSet + child.x*xScale, child.yMin, 
        xOffSet + child.x*xScale, child.yMax)
    else
      if (child.parent.name.to_i > 75 && boot == "width") # good bootstrap
        pdf.SetLineWidth(lineWidth * 5)
      else
        pdf.SetLineWidth(lineWidth)
      end
      pdf.SetXY(xOffSet + child.x*xScale, child.y)
     efields = child.name.split("__")
      entry, species = efields.first, efields.last
     if (entry =~/\{([^\}]*)\}/)
       species = $1
     end
      species = entry if species.nil? && !rawNames
      species = child.name if rawNames
     hl = false
     highlights.keys.each{|highlight|
       hl = highlights[highlight] if (entry.index(highlight))
     } 
      if (pdfFile.index(entry)) # name of query taxon
        pdf.SetTextColor(255,0, 0) # red
        pdf.Write(0, entry) 
        pdf.SetTextColor(0, 0, 0) # black
      elsif (linker && link = send(linker, entry)) 
       pdf.SetTextColor(255,0, 0) if hl # red
       pdf.Write(0, species, link)
       pdf.SetTextColor(0, 0, 0) if hl # black 
      elsif (!species.nil?)
        pdf.SetTextColor(hl[0],hl[1], hl[2]) if hl 
        pdf.Write(0, species) 
        pdf.SetTextColor(0, 0, 0) if hl # black 
      else
        pdf.SetTextColor(hl[0],hl[1], hl[2]) if hl # red
        pdf.Write(0, entry) 
        pdf.SetTextColor(0, 0, 0) if hl # black 
      end
    end
    pdf.Line(xOffSet + child.parent.x*xScale, child.y, 
      xOffSet + child.x*xScale, child.y)
    }
    if (labelName)
      pdf.SetFont('Times','B', 24)
      pdf.SetXY(0, pdf.GetY + 1)
      pdf.Write(0, File.basename(pdfFile,".pdf"))
    end
    if (brackets)
      brackets.each {|bracket|
        x, y1, y2, label, r, p = bracket
        next if label.nil?
        pdf.SetLineWidth(lineWidth * 5)
        pdf.SetFont('Times','B', fontSize*1.5)
        pdf.Line(x, y1, x, y2)
        pdf.Line(x, y1, x - 0.3, y1)
        pdf.Line(x, y2, x - 0.3, y2)
        pdf.SetXY(x, (y1+y2)/2)
        pdf.Write(0, label)
        if (r == "r")
          pdf.SetTextColor(255, 0, 0) 
          pdf.SetXY(x + 1.8, -0.65+(y1+y2)/2)
          pdf.SetFont('Times','B', fontSize*10)
          pdf.Write(0, " .")
          pdf.SetTextColor(0, 0, 0)
        end
        if (p == "p" || r == "p")
          pdf.SetTextColor(255, 0, 255) 
          pdf.SetXY(x + 2.3, -0.65+(y1+y2)/2)
          pdf.SetFont('Times','B', fontSize*10)
          pdf.Write(0, " .")
          pdf.SetTextColor(0, 0, 0)
        end
      }
    end
    pdf.SetLineWidth(lineWidth * 5)
    pdf.Line(1, pdf.GetY + 1, 1 + 0.1*xScale, pdf.GetY + 1) 
    pdf.SetFont('Times','B', fontSize)
    pdf.SetXY(1 + 0.1*xScale, pdf.GetY + 1)
    pdf.Write(0, "0.1")
    if (pdfFile =~/^--/)
      return pdf.Output
    else
      pdf.Output(pdfFile)
  end
end

#findNode(name) ⇒ Object

return node with the given name



522
523
524
# File 'lib/Newick.rb', line 522

def findNode(name)
  return @root.findNode(name)
end

#fixPhylipObject

Fixes PHYLIP’s mistake of using branch lengths and not node values



665
666
667
668
669
670
671
672
673
# File 'lib/Newick.rb', line 665

def fixPhylip
  @root.descendants.each {|child|
    br = child.edgeLen.to_i
    child.edgeLen = 0
    if (br > 0 && !child.leaf?)
      child.name = br.to_s
    end
  }
end

function to generate gi link to ncbi for draw, below



700
701
702
703
704
705
706
707
708
# File 'lib/Newick.rb', line 700

def giLink(entry)
  ncbiLink = "http://www.ncbi.nlm.nih.gov/entrez/"
  protLink = "viewer.fcgi?db=protein&val="
  if (entry =~ /^gi[\_]*([0-9]*)/ || entry =~ /(^[A-Z|0-9]*)\|/)
    return ncbiLink + protLink + $1
  else
    return nil
  end
end

#midpointRootObject

root the tree on midpoint distance



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
# File 'lib/Newick.rb', line 598

def midpointRoot
  unroot
  org1, org2, dist = mostDistantLeaves
  midDist = dist / 2.0
  return self if (midDist == 0)
  if (org1.distToAncestor(@root) > org2.distToAncestor(@root))
    node = org1
  else
    node = org2
  end
  distTraveled = 0
  while(!node.nil?)
    distTraveled += node.edgeLen
    break if (distTraveled >= midDist)
    node = node.parent
  end
  oldDist = node.edgeLen
  left, right = node, node.parent
  right.removeChild(node)
  right.reverseChildParent
  left.edgeLen = distTraveled - midDist
  right.edgeLen = oldDist - left.edgeLen
  @root = NewickNode.new("", 0)
  @root.addChild(left)
  @root.addChild(right)
  return self
end

#mostDistantLeavesObject

returns the two most distant leaves and their distance apart



559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
# File 'lib/Newick.rb', line 559

def mostDistantLeaves
  greatestDist = 0
  dist = Hash.new
  org1, org2 = nil, nil
  @root.leaves.each {|node1|
    @root.leaves.each {|node2|
      dist[node1] = Hash.new if dist[node1].nil?
      dist[node2] = Hash.new if dist[node2].nil?
      next if (!dist[node1][node2].nil?)
      lca = node1.lca(node2)
      dist[node1][node2] = node1.distToAncestor(lca) + 
                              node2.distToAncestor(lca)
      dist[node2][node1] = dist[node1][node2]
      if (dist[node1][node2] > greatestDist)
        org1 = node1
        org2 = node2
        greatestDist = dist[node1][node2]
	end
    }
  }
  return org1, org2, greatestDist
end

#reAlias(aliasNames) ⇒ Object

renames nodes according to inverse alias hash



461
462
463
464
465
466
467
468
# File 'lib/Newick.rb', line 461

def reAlias(aliasNames)
  @root.descendants.each {|node|
    aliasNames.keys.each {|key|
      node.name = key if (aliasNames[key] == node.name)
    }
  }
  return self
end

#relatives(taxon) ⇒ Object

return array of arrays of taxa representing relatives at each level



649
650
651
652
653
654
655
656
657
658
659
660
661
# File 'lib/Newick.rb', line 649

def relatives(taxon)
  node = findNode(taxon)
  if (node.nil?)
    return nil
  else
    relatives = []
    while(!node.parent.nil?)
	relatives.push(node.parent.taxa - node.taxa)
	node = node.parent
    end
    return relatives
  end
end

#reorderObject

reorders leaves alphabetically and size



426
427
428
429
# File 'lib/Newick.rb', line 426

def reorder
  @root.reorder
  return self
end

#reroot(node) ⇒ Object

root the tree on a given node



542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
# File 'lib/Newick.rb', line 542

def reroot(node)
  unroot
  left = node
  right = left.parent
  right.removeChild(node)
  right.reverseChildParent
  if (left.edgeLen != 0)
    right.edgeLen = left.edgeLen / 2.0
    left.edgeLen = right.edgeLen
  end
  @root = NewickNode.new("", 0)
  @root.addChild(left)
  @root.addChild(right)
  return self
end

#taxaObject

return array of all taxa in tree



471
472
473
# File 'lib/Newick.rb', line 471

def taxa
  return @root.taxa
end

#to_s(showLen = true, bootStrap = "node") ⇒ Object

return string representation of tree



414
415
416
# File 'lib/Newick.rb', line 414

def to_s(showLen = true, bootStrap = "node")
  return @root.to_s(showLen, bootStrap) + ";"
end

#unAlias(aliasNames) ⇒ Object

renames nodes according to alias hash



453
454
455
456
457
458
# File 'lib/Newick.rb', line 453

def unAlias(aliasNames)
  @root.descendants.each {|node|
    node.name = aliasNames[node.name] if (!aliasNames[node.name].nil?)
  }
  return self
end

#unrootObject

unroot the tree



527
528
529
530
531
532
533
534
535
536
537
538
539
# File 'lib/Newick.rb', line 527

def unroot
  if (@root.children.size != 2)
    return self # already unrooted
  end
  left, right = @root.children
  left, right = right, left if (right.leaf?) # don't uproot leaf side   
  left.edgeLen += right.edgeLen
  right.children.each {|child|
    @root.addChild(child)
  }
  @root.removeChild(right)
  return self
end

#write(fileName, showLen = true, bootStrap = "node") ⇒ Object

write string representation of tree to file



419
420
421
422
423
# File 'lib/Newick.rb', line 419

def write(fileName, showLen = true, bootStrap = "node")
  file = File.new(fileName, "w")
  file.print @root.to_s(showLen, bootStrap) + ";\n"
  file.close
end