Answers.Body: <p>Apologies, try the following,</p>
  
  <pre><code>allclades = list(pars_tree.find_clades(order='level'))
  for i, blength in enumerate(allclades):
          printf(blength=%.2f, blength)
  </code></pre>
  
  <p>"allclades" is a dictionary rather than a simple array.</p>
  
  <p>If this fails I would examine the allclades data structure either using <code>pprint</code> (directly) or using <code>printStruct</code> via the following code, </p>
  
  <pre><code>&gt;&gt;&gt; d = [{'a1':1, 'a2':2, 'a3':3}, [1,2,3], [{'b1':1, 'b2':2}, {'c1':1}], 'd1', 'd2', 'd3']
  &gt;&gt;&gt; printStruct(d)
  
  def printStruct(struc, indent=0):
    if isinstance(struc, dict):
      print '  '*indent+'{'
      for key,val in struc.iteritems():
        if isinstance(val, (dict, list, tuple)):
          print '  '*(indent+1) + str(key) + '=&gt; '
          printStruct(val, indent+2)
        else:
          print '  '*(indent+1) + str(key) + '=&gt; ' + str(val)
      print '  '*indent+'}'
    elif isinstance(struc, list):
      print '  '*indent + '['
      for item in struc:
        printStruct(item, indent+1)
      print '  '*indent + ']'
    elif isinstance(struc, tuple):
      print '  '*indent + '('
      for item in struc:
        printStruct(item, indent+1)
      print '  '*indent + ')'
    else: print '  '*indent + str(struc)
  </code></pre>
  
  <p>Once you know the structure you unravel it accordingly to get to the branch lengths and then issue a printf command to round them to 2 dp.</p>
  
  <p>Goodluck</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-12-28T14:17:11.050Z
Answers.Text: This still has not helped me. May be an elaborative answer will help.
Answers.UserDisplayName: Sidra Younas
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-12-28T20:40:11.967Z
Answers.Text: If I get a moment I will reproduce the analysis, but I'm not your superviser (a very low priority indeed). "list" is the key to the answer in conjunction with printf. Unlocking the object from "list" to get to the branch lengths is the key here.
Answers.UserDisplayName: M__
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-12-24T15:26:32.447Z
Answers.LastActivityDate: 2018-12-24T15:31:35.387Z
Answers.LastEditDate: 2018-12-24T15:31:35.387Z
Answers.UserDisplayName: M__
Answers.Body: <p>The universal coding way to do this is the <code>printf</code> command regardless of language (sprintf is used language depending), for Python this is,</p>
  
  <pre><code>blength = 0.22342
  printf("Taxa A, blength=%.2f", blength)
  </code></pre>
  
  <hr>
  
  <p><strong>Output</strong> </p>
  
  <p>Taxa A, 0.22</p>
  
  <hr>
  
  <p>The following may be useful to your context:</p>
  
  <pre><code>import numpy
  allclades = list(pars_tree.find_clades(order='level'))
  for blength in enumerate(allclades):
          printf(blength=%.2f, blength)
  </code></pre>
  
  <p>Goodluck</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-12-24T07:34:38.920Z
Answers.Text: It did'nt work for me. First there was a syntax error and when I use it this way: `allclades = list(pars_tree.find_clades(order='level'))
  for blength in enumerate(allclades):
      print(blength = "%8.2f" % blength)` . It says, `"TypeError: not all arguments converted during string formatting"` Any suggestions?
Answers.UserDisplayName: Sidra Younas
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-12-23T12:07:59.537Z
Answers.LastActivityDate: 2018-12-23T12:07:59.537Z
Answers.UserDisplayName: M__
Body: <p>I have been using biopython 1.72 to display my phylogenetic tree files.</p>
  
  <ol>
  <li><p>Using the function <code>'Phylo.draw(pars_tree, branch_labels=lambda c: c.branch_length)'</code> to display branch lengths as well on tree, the tree displays the branch lengths as including all numbers after decimal. While I want the numbers to be truncated to two decimal places.
  Following is a python method that truncates upto <code>"the number required"</code> decimal places.</p>
  
  <p>def truncate(n, decimals=0):
      multiplier = 10 ** decimals
      return int(n * multiplier) / multiplier
  truncate (12.567, 2)  #Using function
  12.56                 #Output
  Can I use such method with biopython for branch lengths?</p></li>
  <li><p><code>'Phylo.draw'</code> function opens the window which is very narrow and if the tree file is larger, all the branches are overlapped and it gets difficult to read what is written. Does anyone know any better display method?</p></li>
  </ol>
  
  <p>Following is the example code, I have been using:</p>
  
  <pre><code>from Bio import Phylo
  from Bio.Phylo.TreeConstruction import *
  from Bio import AlignIO
  
  aln = AlignIO.read(open('example.phy'), 'phylip')
  
  calculator = DistanceCalculator()
  dm = calculator.get_distance(aln)
  
  constructor = DistanceTreeConstructor()
  njtree = constructor.nj(dm)
  starting_tree = njtree
  scorer = ParsimonyScorer()
  searcher = NNITreeSearcher(scorer)
  constructor = ParsimonyTreeConstructor(searcher, starting_tree)
  pars_tree = constructor.build_tree(aln)
  Phylo.draw(pars_tree, branch_labels=lambda c: c.branch_length)
  </code></pre>
  
  <p>I have an msa file as input and it gives a tree, which looks like:                                                 </p>
  
  <pre><code>                                                         _______ Human
                                                   _______|
                                                  |       |_______ Chimpanzee
                                           _______|
                                          |       |        _______ Dog
                                   _______|       |_______|
                                  |       |               |_______ Cow
                           _______|       |
                          |       |       |_______________________ Elephant
                   _______|       |
                  |       |       |_______________________________ Mouse
                  |       |
           _______|       |_______________________________________ Platypus
          |       |
          |       |        _______________________________________ Anole_lizard
          |       |_______|
    ______|               |        _______________________________ Chicken
   |      |               |_______|
   |      |                       |_______________________________ Zebra_finch
   |      |
   |      |_______________________________________________________ Xenopus
  _|
   |       _______________________________________________________ Zebrafish
   |______|
   |      |_______________________________________________________ Fugu
   |
   |______________________________________________________________ Amphioxus
  </code></pre>
  
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2018-12-19T11:54:56.793Z
Comments.Text: If you're not wedded to using python to visualise your trees, [FigTree](http://tree.bio.ed.ac.uk/software/figtree/) provides a great alternative.
Comments.UserDisplayName: NatWH
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2018-12-20T05:23:09.047Z
Comments.Text: Well, this is what hinders me. I am working with python.
Comments.UserDisplayName: Sidra Younas
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2018-12-22T10:41:35.827Z
Comments.Text: Can you provide an example of your input tree? I’d approach this my parsing the treefile itself, truncating the values, writing a new tree, and then plotting that, rather than trying to do it whilst plotting. BioPython’s tree handling is not its strong suit IMO, so for something like this I would probably use ETE3 or Dendropy - those tools may include options for truncating your node/branch values.
Comments.UserDisplayName: Joe Healey
Comments.ContentLicense: CC BY-SA 4.0
Comments.CreationDate: 2018-12-22T20:27:05.157Z
Comments.Text: I have edited my question for this.
Comments.UserDisplayName: Sidra Younas
Tags: <phylogenetics><python><phylogeny>
Title: Truncating branch length values of Phylogenetic tree with biopython
ThreadText: # Truncating branch length values of Phylogenetic tree with biopython
  
  (Asked by: username_0 on 2018-12-17)
  
  I have been using biopython 1.72 to display my phylogenetic tree files.
  
  1. Using the function `'Phylo.draw(pars_tree, branch_labels=lambda c: c.branch_length)'` to display branch lengths as well on tree, the tree displays the branch lengths as including all numbers after decimal. While I want the numbers to be truncated to two decimal places.
     Following is a python method that truncates upto `"the number required"` decimal places.
  
     def truncate(n, decimals=0):
     multiplier = 10 \*\* decimals
     return int(n \* multiplier) / multiplier
     truncate (12.567, 2) #Using function
     12.56 #Output
     Can I use such method with biopython for branch lengths?
  2. `'Phylo.draw'` function opens the window which is very narrow and if the tree file is larger, all the branches are overlapped and it gets difficult to read what is written. Does anyone know any better display method?
  
  Following is the example code, I have been using:
  
  ```
  from Bio import Phylo
  from Bio.Phylo.TreeConstruction import *
  from Bio import AlignIO
  
  aln = AlignIO.read(open('example.phy'), 'phylip')
  
  calculator = DistanceCalculator()
  dm = calculator.get_distance(aln)
  
  constructor = DistanceTreeConstructor()
  njtree = constructor.nj(dm)
  starting_tree = njtree
  scorer = ParsimonyScorer()
  searcher = NNITreeSearcher(scorer)
  constructor = ParsimonyTreeConstructor(searcher, starting_tree)
  pars_tree = constructor.build_tree(aln)
  Phylo.draw(pars_tree, branch_labels=lambda c: c.branch_length)
  
  ```
  
  I have an msa file as input and it gives a tree, which looks like:
  
  ```
                                                           _______ Human
                                                   _______|
                                                  |       |_______ Chimpanzee
                                           _______|
                                          |       |        _______ Dog
                                   _______|       |_______|
                                  |       |               |_______ Cow
                           _______|       |
                          |       |       |_______________________ Elephant
                   _______|       |
                  |       |       |_______________________________ Mouse
                  |       |
           _______|       |_______________________________________ Platypus
          |       |
          |       |        _______________________________________ Anole_lizard
          |       |_______|
    ______|               |        _______________________________ Chicken
   |      |               |_______|
   |      |                       |_______________________________ Zebra_finch
   |      |
   |      |_______________________________________________________ Xenopus
  _|
   |       _______________________________________________________ Zebrafish
   |______|
   |      |_______________________________________________________ Fugu
   |
   |______________________________________________________________ Amphioxus
  
  ```
  
  **Tags:** phylogenetics, python, phylogeny
  
  > **Comments:**
  > **username_1**: If you're not wedded to using python to visualise your trees, [FigTree](http://tree.bio.ed.ac.uk/software/figtree/) provides a great alternative.  
  > **username_0**: Well, this is what hinders me. I am working with python.  
  > **username_2**: Can you provide an example of your input tree? I’d approach this my parsing the treefile itself, truncating the values, writing a new tree, and then plotting that, rather than trying to do it whilst plotting. BioPython’s tree handling is not its strong suit IMO, so for something like this I would probably use ETE3 or Dendropy - those tools may include options for truncating your node/branch values.  
  > **username_0**: I have edited my question for this.  
  
  ---
  
  ## 2 answers
  
  ### Answer by username_3 on 2018-12-24. Score: 1
  
  Apologies, try the following,
  
  ```
  allclades = list(pars_tree.find_clades(order='level'))
  for i, blength in enumerate(allclades):
          printf(blength=%.2f, blength)
  
  ```
  
  "allclades" is a dictionary rather than a simple array.
  
  If this fails I would examine the allclades data structure either using `pprint` (directly) or using `printStruct` via the following code,
  
  ```
  >>> d = [{'a1':1, 'a2':2, 'a3':3}, [1,2,3], [{'b1':1, 'b2':2}, {'c1':1}], 'd1', 'd2', 'd3']
  >>> printStruct(d)
  
  def printStruct(struc, indent=0):
    if isinstance(struc, dict):
      print '  '*indent+'{'
      for key,val in struc.iteritems():
        if isinstance(val, (dict, list, tuple)):
          print '  '*(indent+1) + str(key) + '=> '
          printStruct(val, indent+2)
        else:
          print '  '*(indent+1) + str(key) + '=> ' + str(val)
      print '  '*indent+'}'
    elif isinstance(struc, list):
      print '  '*indent + '['
      for item in struc:
        printStruct(item, indent+1)
      print '  '*indent + ']'
    elif isinstance(struc, tuple):
      print '  '*indent + '('
      for item in struc:
        printStruct(item, indent+1)
      print '  '*indent + ')'
    else: print '  '*indent + str(struc)
  
  ```
  
  Once you know the structure you unravel it accordingly to get to the branch lengths and then issue a printf command to round them to 2 dp.
  
  Goodluck
  
  > **Comments:**
  > **username_0**: This still has not helped me. May be an elaborative answer will help.  
  > **username_3**: If I get a moment I will reproduce the analysis, but I'm not your superviser (a very low priority indeed). "list" is the key to the answer in conjunction with printf. Unlocking the object from "list" to get to the branch lengths is the key here.  
  
  ---
  
  ### Answer by username_3 on 2018-12-23. Score: 0
  
  The universal coding way to do this is the `printf` command regardless of language (sprintf is used language depending), for Python this is,
  
  ```
  blength = 0.22342
  printf("Taxa A, blength=%.2f", blength)
  
  ```
  
  ---
  
  **Output**
  
  Taxa A, 0.22
  
  ---
  
  The following may be useful to your context:
  
  ```
  import numpy
  allclades = list(pars_tree.find_clades(order='level'))
  for blength in enumerate(allclades):
          printf(blength=%.2f, blength)
  
  ```
  
  Goodluck
  
  > **Comments:**
  > **username_0**: It did'nt work for me. First there was a syntax error and when I use it this way: `allclades = list(pars_tree.find_clades(order='level')) for blength in enumerate(allclades):     print(blength = "%8.2f" % blength)` . It says, `"TypeError: not all arguments converted during string formatting"` Any suggestions?  
  
  ---
  
  