This module provides classes, functions and I/O support for working with phylogenetic trees.

This module provides classes, functions and I/O support for working with phylogenetic trees.

−

This code is not yet included with Biopython, and therefore the documentation has not been integrated into the Biopython Tutorial yet either.

+

For more complete documentation, see the Phylogenetics chapter of the [http://biopython.org/DIST/docs/tutorial/Tutorial.html Biopython Tutorial] and the Bio.Phylo [http://biopython.org/DIST/docs/api/Bio.Phylo-module.html API pages] generated from the source code. The [[Phylo cookbook]] page has more examples of how to use this module, and the [[PhyloXML]] page describes how to attach graphical cues and additional information to a tree.

==Availability==

==Availability==

−

The source code for this module is being developed on GitHub, but has not yet been included with a stable Biopython release. If you're interested in testing this code before the official release, see [[SourceCode]] for instructions on getting a copy of the development branch.

+

This module is included in Biopython 1.54 and later. If you're interested in testing newer additions to this code before the next official release, see [[SourceCode]] for instructions on getting a copy of the development branch.

−

+

−

Requirements:

+

−

* Python 2.4 or newer

+

−

* ElementTree module

+

To draw trees (optional), you'll also need these packages:

To draw trees (optional), you'll also need these packages:

−

* [http://networkx.lanl.gov/index.html NetworkX] 1.0rc1 (or 0.36 for snapshot at the end of GSoC 2009)

* [http://networkx.lanl.gov/index.html NetworkX] -- for the functions 'draw_graphviz' and 'to_networkx'

+

* [http://networkx.lanl.gov/pygraphviz/ PyGraphviz] or [http://dkbza.org/pydot.html pydot] -- for the functions 'draw_graphviz' and 'to_networkx'

−

The I/O and tree-manipulation functionality will work without them; they're imported on demand when the functions to_networkx() and draw_graphviz() are called.

+

The I/O and tree-manipulation functionality will work without them; they're imported on demand when the functions draw(), draw_graphviz() and to_networkx() are called.

−

The XML parser used in the PhyloXMLIO sub-module is ElementTree, added to the Python standard library in Python 2.5. To use this module in Python 2.4, you'll need to install a separate package that provides the ElementTree interface. Two exist:

+

To use this module in older versions of Biopython with Python 2.4, you'll also need to install a separate package that provides the ElementTree interface for XML parsing. Either of these will work:

PhyloXMLIO attempts to import each of these compatible ElementTree implementations until it succeeds. The given XML file handle is then parsed incrementally to instantiate an object hierarchy containing the relevant phylogenetic information.

+

The Phylo module has also been successfully tested on Jython 2.5.1, minus the Graphviz- and NetworkX-based functions. However, parsing phyloXML files is noticeably slower because Jython uses a different version of the underlying XML parsing library.

==I/O functions==

==I/O functions==

Line 33:

Line 29:

The second argument to each function is the target format. Currently, the following formats are supported:

The second argument to each function is the target format. Currently, the following formats are supported:

−

* phyloxml

* newick

* newick

* nexus

* nexus

+

* nexml

+

* phyloxml

+

* cdao

See the [[PhyloXML]] page for more examples of using tree objects.

See the [[PhyloXML]] page for more examples of using tree objects.

Line 74:

Line 72:

<python>

<python>

−

tree = Phylo.read('example.xml', 'phyloxml')

+

tree = Phylo.read('example.dnd', 'newick')

print tree

print tree

</python>

</python>

+

+

If you have your tree data already loaded as a Python string, you can parse it with the help of StringIO (in Python's standard library):

+

+

<python>

+

from cStringIO import StringIO

+

+

treedata = "(A, (B, C), (D, E))"

+

handle = StringIO(treedata)

+

tree = Phylo.read(handle, "newick")

+

</python>

+

+

In one line:

+

+

<python>

+

tree = Phylo.read(StringIO("(A, (B, C), (D, E))"), "newick")

+

</python>

+

+

The other I/O functions also can be used with StringIO.

+

+

(General tip: if you write to the StringIO object and want to re-read the contents, you'll need to call the <code>seek(0)</code> method to move the handle back to the start of the StringIO data -- the same as an open file handle. See examples of this in the unit tests for Phylo, <code>Tests/test_Phylo.py</code>, in the Biopython source code.)

===write()===

===write()===

Line 102:

Line 120:

'''PhyloXMLIO:'''

'''PhyloXMLIO:'''

Support for the [http://www.phyloxml.org/ phyloXML] format. See the [[PhyloXML]] page for details.

Support for the [http://www.phyloxml.org/ phyloXML] format. See the [[PhyloXML]] page for details.

+

+

'''NeXMLIO:'''

+

Support for the [http://www.nexml.org/ NeXML] format.

'''NewickIO:'''

'''NewickIO:'''

Line 109:

Line 130:

Wrappers around Bio.Nexus to support the Nexus tree format.

Wrappers around Bio.Nexus to support the Nexus tree format.

−

The Nexus format actually contains several sub-formats for different kinds of data; to represent trees, Nexus provides a block containing some metadata and one or more Newick trees. (Another kind of Nexus block can represent alignments; this is handled in [[AlignIO]].) So to parse a complete Nexus file with all block types handled, use Bio.Nexus directly, and to extract just the trees, use Bio.Phylo. Integration between Bio.Nexus and Bio.Phylo will be improved in the future.

The Nexus format actually contains several sub-formats for different kinds of data; to represent trees, Nexus provides a block containing some metadata and one or more Newick trees. (Another kind of Nexus block can represent alignments; this is handled in [[AlignIO]].) So to parse a complete Nexus file with all block types handled, use Bio.Nexus directly, and to extract just the trees, use Bio.Phylo.

==Tree and Subtree classes==

==Tree and Subtree classes==

Line 133:

Line 157:

Where a third-party package is required, that package is imported when the function itself is called, so these dependencies are not necessary to install or use the rest of the Tree module.

Where a third-party package is required, that package is imported when the function itself is called, so these dependencies are not necessary to install or use the rest of the Tree module.

−

===Exporting to other object representations===

+

===Displaying trees===

−

+

−

Although any phylogenetic tree can reasonably be represented by a directed acyclic graph, the Phylo module does not attempt to provide a generally usable graph library -- only the minimum functionality to represent phylogenetic trees. Instead, it provides functions for exporting tree objects to the standard graph representations, adjacency list (dict) and adjacency matrix, using third-party libraries.

+

−

+

−

'''to_networkx''' returns the given tree as a [http://networkx.lanl.gov/ NetworkX] LabeledDiGraph or LabeledGraph object (depending on whether the tree is rooted). You'll probably need to import networkx directly for subsequent operations on the graph object. From this point you can also try using one of networkx's drawing functions to display the tree, and for simple, fully labeled trees it may even work -- but you'll have better results with Phylo's own draw_graphviz function, discussed below.

+

−

+

−

<python>

+

−

import networkx, pylab

+

−

tree = Phylo.read('example.xml', 'phyloxml')

+

−

net = Phylo.to_networkx(tree)

+

−

networkx.draw(net)

+

−

pylab.show()

+

−

</python>

+

−

'''to_adjacency_matrix''' produces an adjacency matrix as an instance of a NumPy 2-dimensional array, where cell values are branch lengths and rows and columns are vertices in the graph (i.e. nodes in the tree, the root of each clade). The returned tuple includes a list of all clade objects in the original tree, used for determining the indexes of cells in the matrix corresponding to clades or branches in the tree.

Phylogeny(description='phyloXML allows to use either a "branch_length"

Phylogeny(description='phyloXML allows to use either a "branch_length"

attribute or element to indicate branch lengths.', name='example from

attribute or element to indicate branch lengths.', name='example from

Line 179:

Line 178:

</pre>

</pre>

−

'''draw_graphviz''' mimics the networkx function of the same name, with some tweaks to improve the display of the graph. If a file name is given, the graph is drawn directly to that file, and options such as image format (default PDF) may be used. Prerequisites: In addition to networkx, you'll need a local installation of Graphviz,

[http://matplotlib.sourceforge.net/ matplotlib] and either [http://networkx.lanl.gov/pygraphviz/ PyGraphviz] or [http://dkbza.org/pydot.html pydot].

+

'''draw''' displays a rooted phylogram using matplotlib or pylab. ''New in Biopython 1.58.''

+

Try this:

<python>

<python>

−

tree = Phylo.read('example.xml', 'phyloxml')

+

tree = Phylo.read('apaf.xml', 'phyloxml')

−

# Draw it a few different ways

+

tree.ladderize() # Flip branches so deeper clades are displayed at top

−

Phylo.draw_graphviz(tree, 'example.pdf')

+

Phylo.draw(tree)

−

Phylo.draw_graphviz(tree, 'example.png', format='png')

+

</python>

+

+

+

'''draw_graphviz''' mimics the networkx function of the same name, with some tweaks to improve the display of the graph. If a file name is given, the graph is drawn directly to that file, and options such as image format (default PDF) may be used.

Prerequisites: In addition to networkx, you'll need a local installation of Graphviz, [http://matplotlib.sourceforge.net/ matplotlib] and either [http://networkx.lanl.gov/pygraphviz/ PyGraphviz] or [http://dkbza.org/pydot.html pydot].

+

+

Drawing a basic dendrogram is simple:

+

<python>

+

import pylab

+

tree = Phylo.read('apaf.xml', 'phyloxml')

Phylo.draw_graphviz(tree)

Phylo.draw_graphviz(tree)

+

pylab.show()

</python>

</python>

−

'''draw_ascii''' prints an ascii-art rooted phylogram to standard output, or another file handle if specified. Only terminal node labels are shown; these are clade names, but can be something else generated by the 'labeller' argument (which works the same as in draw_graphviz). The width of the text field used for drawing is 80 characters by default, adjustable by keyword argument, and the height in character rows is twice the number of terminals in the tree.

See the [[Phylo cookbook]] page for more drawing features and options.

+

+

'''draw_ascii''' prints an ascii-art rooted phylogram to standard output, or another file handle if specified. Only terminal node labels are shown; these are the result of ''str(clade)'' (usually clade names). The width of the text field used for drawing is 80 characters by default, adjustable with the ''column_width'' keyword argument, and the height in character rows is twice the number of terminals in the tree.

A simple tree with defined branch lengths looks like this:

A simple tree with defined branch lengths looks like this:

Line 279:

Line 300:

</pre>

</pre>

+

+

===Exporting to other object representations===

+

+

Although any phylogenetic tree can reasonably be represented by a directed acyclic graph, the Phylo module does not attempt to provide a generally usable graph library -- only the minimum functionality to represent phylogenetic trees. Instead, it provides functions for exporting tree objects to the standard graph representations, adjacency list (dict) and adjacency matrix, using third-party libraries.

+

+

'''to_networkx''' returns the given tree as a [http://networkx.lanl.gov/ NetworkX] LabeledDiGraph or LabeledGraph object (depending on whether the tree is rooted). You'll probably need to import networkx directly for subsequent operations on the graph object. From this point you can also try using one of networkx's drawing functions to display the tree, and for simple, fully labeled trees it may even work -- but you'll have better results with Phylo's own '''draw_graphviz''' function, discussed above.

+

+

<python>

+

import networkx, pylab

+

tree = Phylo.read('example.xml', 'phyloxml')

+

net = Phylo.to_networkx(tree)

+

networkx.draw(net)

+

pylab.show()

+

</python>

+

+

Recipes for exporting to other libraries, including '''ape''' (via Rpy2) and '''PyCogent''', are available on the [[Phylo_cookbook|Phylo cookbook]] page.

+

+

== Tree Construction ==

+

+

In addition to wrappers of tree construction programs(PHYLIP programs through EMBOSS wrappers in Bio.Emboss.Applications), now Biopython also provides several tree construction algorithm implementations in pure python in the <code>Bio.Phylo.TreeConstruction</code> module.

+

+

All algorithms are designed as worker subclasses of a base class <code>TreeConstructor</code>. All constructors have the same method <code>build_tree</code> that accept a <code>MultipleSeqAlignment</code> object to construct the tree. Currently there are two types of tree constructors: <code>DistanceTreeConstructor</code> and <code>ParsimonyTreeConstructor</code>.

+

+

=== DistanceTreeConstructor ===

+

+

The <code>DistanceTreeConstructor</code> has two algorithms: UPGMA(Unweighted Pair Group Method with Arithmetic Mean) and NJ(Neighbor Joining).

+

+

Both algorithms construct trees based on a distance matrix. So before using these algorithms, let me introduce the <code>DistanceCalculator</code> to generate the distance matrix from a <code>MultipleSeqAlignment</code> object. The following code shows a common way to do this:

As you see, we create a <code>DistanceCalculator</code> object with a string 'identity', which is the name of the model(scoring matrix) to calculate the distance. The 'identity' model is the default one and can be used both for DNA and Protein sequence. To check available models for DNA, protein or all, use the attribute of the calculator <code>dna_models</code>, <code>protein_models</code>, <code>models</code> respectively.

+

+

After the calculator is created with the model, simply use the <code>get_distance()</code> method to get the distance matrix of a given alignment object. Then you will get a <code>DistanceMatrix</code> object, a subclass of <code>Matrix</code>(we will talk about this later).

+

+

Now, let's get back to the <code>DistanceTreeConstructor</code>. We can pass the <code>DistanceCalculator</code> object and a string parameter('nj' or 'upgma') to initialize it, and then call its <code>build_tree()</code> as mentioned before.

Unlike <code>DistanceTreeConstructor</code>, the concrete algorithm of <code>ParsimonyTreeConstructor</code> is delegated to two different worker classes: the <code>ParsimonyScorer</code> to calculate the parsimony score of a target tree by the given alignment, and the <code>TreeSearcher</code> to search the best tree that minimize the parsimony score. A typical usage example can be as follows:

The <code>ParsimonyScorer</code> is a combination of the Fitch algorithm and Sankoff algorithm. It will work as Fitch algorithm by default if no parameter is provide, and work as Sankoff algorithm if a parsimony scoring matrix(a <code>Matrix</code> object) is given, .

+

+

Then the scorer is passed to a <code>TreeSearcher</code> to tell it how to evaluate different trees during searching. Currently, only one searcher <code>NNITreeSearcher</code>, the Nearest Neighbor Interchange(NNI) algorithm, is implemented.

+

+

By passing the searcher and a starting tree to the <code>ParsimonyTreeConstructor</code>, we finally get the instance of it. If no starting tree is provided, a simple upgma tree will be created instead, with the 'identity' model. To use this parsimony constructor, just simply call the <code>build_tree</code> method with an alignment.

+

+

== Consensus Tree ==

+

+

=== Strict, Majority Rule and Adam Consensus ===

+

+

Same as tree construction algorithms, three consensus tree algorithms(Strict, Majority Rule and Adam Consensus) in pure python are also implemented in the <code>Bio.Phylo.Consensus</code> module. You can directly call <code>strict_consensus</code>, <code>majority_consensus</code> and <code>adam_consensus</code> to use these algorithms with a list of trees as the input.

Instead of using 50% as the cutoff, the <code>majority_consensus</code> method allows you to set your own one by providing an extra <code>cutoff</code> parameter(0~1, 0 by default). That means it can also work as strict consensus algorithm when the <code>cutoff</code> equals 1. One more thing different to strict and adam consensus tree, the result majority rule consensus tree has branch support value that are automatically assigned during calculation.

+

+

=== Bootstrap Methods ===

+

+

To get the consensus tree, we must construct a list of bootstrap replicate trees. So in the <code>Bio.Phylo.Consensus</code> module, we also provide several useful bootstrap methods to achieve this.

As you see, the <code>bootstrap</code> method accepts a <code>MultipleSeqAlignment</code> object and generates its bootstrap replicate 100 times. The you can use them to build replicate trees. While, we also provide a convenient method to do this.

+

+

<pre>&gt;&gt;&gt; calculator = DistanceCalculator('blosum62')

+

&gt;&gt;&gt; constructor = DistanceTreeConstructor(calculator)

+

&gt;&gt;&gt; trees = bootstrap_trees(msa, 100, constructor)</pre>

+

This time we pass an extra <code>DistanceTreeConstructor</code> object to a <code>bootstrap_trees</code> method and finally got the replicate trees. Note that both <code>bootstrap</code> and <code>bootstrap_trees</code> are generator functions. You need to use <code>list()</code> function to turn the result into a list of alignment or trees.

+

+

Another useful function is <code>bootstrap_consensus</code>. By passing the consensus method as another extra parameter, we can directly get the consensus tree.

In the above code, we use the first tree as the target tree that we want to calculate its branch support. The <code>get_support</code> method accepts the target tree and a list of trees, and returns a tree, with all internal clades assigned with branch support values.

+

+

== Other Useful Classes ==

+

+

There are some other classes in both <code>TreeConstruction</code> and <code>Consensus</code> module that are used in those algorithms. They may not be used commonly, but might be useful to you in some cases.

+

+

=== Matrix. ===

+

+

The <code>Matrix</code> class in the <code>TreeConstruction</code> module is the super class of <code>DistanceMatrix</code>. They are both actually constructed by a list of names and a nested list of numbers in lower triangular matrix format. The only difference between them is that the diagonal elements in <code>DistanceMatrix</code> will all be 0 no matter what values are assigned.

<code>BitString</code> is an assistant class used frequently in the algorithms in the <code>Consensus</code> module. It's a sub-class of <code>str</code> object that only accepts two characters('0' and '1'), with additional functions for binary-like manipulation(&amp;|^~). Common usage is as follows:

+

+

<pre>&gt;&gt;&gt; from Bio.Phylo.Consensus import BitString

+

&gt;&gt;&gt; bitstr1 = BitString('11111')

+

&gt;&gt;&gt; bitstr2 = BitString('11100')

+

&gt;&gt;&gt; bitstr3 = BitString('01101')

+

&gt;&gt;&gt; bitstr1

+

BitString('11111')

+

&gt;&gt;&gt; bitstr2 &amp; bitstr3

+

BitString('01100')

+

&gt;&gt;&gt; bitstr2 | bitstr3

+

BitString('11101')

+

&gt;&gt;&gt; bitstr2 ^ bitstr3

+

BitString('10001')

+

&gt;&gt;&gt; bitstr2.index_one()

+

[0, 1, 2]

+

&gt;&gt;&gt; bitstr3.index_one()

+

[1, 2, 4]

+

&gt;&gt;&gt; bitstr3.index_zero()

+

[0, 3]

+

&gt;&gt;&gt; bitstr1.contains(bitstr2)

+

True

+

&gt;&gt;&gt; bitstr2.contains(bitstr3)

+

False

+

&gt;&gt;&gt; bitstr2.independent(bitstr3)

+

False

+

&gt;&gt;&gt; bitstr2.independent(bitstr4)

+

True

+

&gt;&gt;&gt; bitstr1.iscompatible(bitstr2)

+

True

+

&gt;&gt;&gt; bitstr2.iscompatible(bitstr3)

+

False

+

&gt;&gt;&gt; bitstr2.iscompatible(bitstr4)

+

True</pre>

+

In consensus and branch support algorithms, it is used to count and store the clades in multiple trees. During counting, the clades will be considered the same if their terminals(in terms of <code>name</code> attribute) are the same.

+

+

For example, let's say two trees are provided as below to search their strict consensus tree:

+

+

<pre>tree1: (((A, B), C),(D, E))

+

tree2: ((A, (B, C)),(D, E))</pre>

+

For both trees, a <code>BitString</code> object '11111' will represent their root clade. Each '1' stands for the terminal clade in the list [A, B, C, D, E] (the order might not be the same, it's determined by the <code>get_terminal</code> method of the first tree provided). For the clade ((A, B), C) in tree1 and (A, (B, C)) in tree2, they both can be represented by '11100'. Similarly, '11000' represents clade (A, B) in tree1, '01100' represents clade (B, C) in tree2, and '00011' represents clade (D, E) in both trees.

+

+

So, with the <code>_count_clades</code> function in this module, finally we can get the clade counts and their BitString representation as follows(the root and terminals are omitted):

+

+

<pre>clade BitString count

+

ABC '11100' 2

+

DE '00011' 2

+

AB '11000' 1

+

BC '01100' 1</pre>

+

To get the BitString representation of a clade, we can use the following code snippet:

+

+

<pre># suppose we are provided with a tree list, the first thing to do is

+

# to get all the terminal names in the first tree

+

term_names = [term.name for term in trees[0].get_terminals()]

+

# for a specific clade in any of the tree, also get its terminal names

+

clade_term_names = [term.name for term in clade.get_terminals()]

+

# then create a boolean list

+

boolvals = [name in clade_term_names for name in term_names]

+

# create the string version and pass it to BitString

+

bitstr = BitString(''.join(map(str, map(int, boolvals))))</pre>

+

To convert back:

+

+

<pre># get all the terminal clades of the first tree

+

terms = [term for term in trees[0].get_terminals()]

+

# get the index of terminal clades in bitstr

+

index_list = bitstr.index_one()

+

# get all terminal clades by index

+

clade_terms = [terms[i] for i in index_list]

+

# create a new calde and append all the terminal clades

+

new_clade = BaseTree.Clade()

+

new_clade.clades.extend(clade_terms)</pre>

+

This is how the <code>BitString</code> is used in the consensus and branch support algorithms. And I think it can be used in many other conditions.

+

+

For example, we can even use it to check whether the structures of two trees are the same.

blast_record = NCBIXML.read(result_handle) # This takes some time to run

+

</python>

+

+

2. Extract the best hits from the BLAST result.

+

<python>

+

from Bio import SeqIO

+

from Bio.Seq import Seq

+

from Bio.SeqRecord import SeqRecord

+

+

def get_seqrecs(alignments, threshold):

+

for aln in alignments:

+

for hsp in aln.hsps:

+

if hsp.expect < threshold:

+

yield SeqRecord(Seq(hsp.sbjct), id=aln.accession)

+

break

+

+

best_seqs = get_seqrecs(blast_record.alignments, 1e-90)

+

SeqIO.write(best_seqs, 'egfr-family.fasta', 'fasta')

+

</python>

+

+

To help with annotating to your tree later, pick a lookup key here (e.g. accession number) and build a dictionary mapping that key to any additional data you can glean from the BLAST output, such as taxonomy and GI numbers. In this example, we're only keeping the original sequence and accession number.

+

+

3. Re-align the sequences using Muscle. The program creates an alignment file in Clustal format, "egfr-family.aln".

Revision as of 04:57, 22 September 2013

This module provides classes, functions and I/O support for working with phylogenetic trees.

For more complete documentation, see the Phylogenetics chapter of the Biopython Tutorial and the Bio.Phylo API pages generated from the source code. The Phylo cookbook page has more examples of how to use this module, and the PhyloXML page describes how to attach graphical cues and additional information to a tree.

Availability

This module is included in Biopython 1.54 and later. If you're interested in testing newer additions to this code before the next official release, see SourceCode for instructions on getting a copy of the development branch.

The Phylo module has also been successfully tested on Jython 2.5.1, minus the Graphviz- and NetworkX-based functions. However, parsing phyloXML files is noticeably slower because Jython uses a different version of the underlying XML parsing library.

I/O functions

Wrappers for supported file formats are available from the top level of the module:

from Bio import Phylo

Like SeqIO and AlignIO, this module provides four I/O functions: parse(), read(), write() and convert(). Each function accepts either a file name or an open file handle, so data can be also loaded from compressed files, StringIO objects, and so on. If the file name is passed as a string, the file is automatically closed when the function finishes; otherwise, you're responsible for closing the handle yourself.

The second argument to each function is the target format. Currently, the following formats are supported:

example from Prof. Joe Felsenstein's book "Inferring Phylogenies"
example from Prof. Joe Felsenstein's book "Inferring Phylogenies"
same example, with support of type "bootstrap"
same example, with species and sequence
same example, with gene duplication information and sequence relationships
similar example, with more detailed sequence data
network, node B is connected to TWO nodes: AB and C
...

If there's only one tree, then the next() method on the resulting generator will return it.

Note that this doesn't immediately reveal whether there are any remaining trees -- if you want to verify that, use read() instead.

read()

Parse and return exactly one tree from the given file or handle. If the file contains zero or multiple trees, a ValueError is raised. This is useful if you know a file contains just one tree, to load that tree object directly rather than through parse() and next(), and as a safety check to ensure the input file does in fact contain exactly one phylogenetic tree at the top level.

tree = Phylo.read('example.dnd', 'newick')print tree

If you have your tree data already loaded as a Python string, you can parse it with the help of StringIO (in Python's standard library):

(General tip: if you write to the StringIO object and want to re-read the contents, you'll need to call the seek(0) method to move the handle back to the start of the StringIO data -- the same as an open file handle. See examples of this in the unit tests for Phylo, Tests/test_Phylo.py, in the Biopython source code.)

write()

Write a sequence of Tree objects to the given file or handle. Passing a single Tree object instead of a list or iterable will also work. (See, Phylo is friendly.)

The Nexus format actually contains several sub-formats for different kinds of data; to represent trees, Nexus provides a block containing some metadata and one or more Newick trees. (Another kind of Nexus block can represent alignments; this is handled in AlignIO.) So to parse a complete Nexus file with all block types handled, use Bio.Nexus directly, and to extract just the trees, use Bio.Phylo.

Tree and Subtree classes

The basic objects are defined in Bio.Phylo.BaseTree.

Format-specific extensions

To support additional information stored in specific file formats, sub-modules within Tree offer additional classes that inherit from BaseTree classes.

Each sub-class of BaseTree.Tree or Node has a class method to promote an object from the basic type to the format-specific one. These sub-class objects can generally be treated as instances of the basic type without any explicit conversion.

PhyloXML:
Support for the phyloXML format. See the PhyloXML page for details.

Newick:
The Newick module provides minor enhancements to the BaseTree classes, plus several shims for compatibility with the existing Bio.Nexus module. The API for this module is under development and should not be relied on, other than the functionality already provided by BaseTree.

Utilities

Some additional tools are located in the Utils module under Bio.Phylo. These functions are also loaded to the top level of the Phylo module on import for easy access.

Where a third-party package is required, that package is imported when the function itself is called, so these dependencies are not necessary to install or use the rest of the Tree module.

draw_graphviz mimics the networkx function of the same name, with some tweaks to improve the display of the graph. If a file name is given, the graph is drawn directly to that file, and options such as image format (default PDF) may be used.

Unrooted tree with colored nodes

Prerequisites: In addition to networkx, you'll need a local installation of Graphviz, matplotlib and either PyGraphviz or pydot.

draw_ascii prints an ascii-art rooted phylogram to standard output, or another file handle if specified. Only terminal node labels are shown; these are the result of str(clade) (usually clade names). The width of the text field used for drawing is 80 characters by default, adjustable with the column_width keyword argument, and the height in character rows is twice the number of terminals in the tree.

Exporting to other object representations

Although any phylogenetic tree can reasonably be represented by a directed acyclic graph, the Phylo module does not attempt to provide a generally usable graph library -- only the minimum functionality to represent phylogenetic trees. Instead, it provides functions for exporting tree objects to the standard graph representations, adjacency list (dict) and adjacency matrix, using third-party libraries.

to_networkx returns the given tree as a NetworkX LabeledDiGraph or LabeledGraph object (depending on whether the tree is rooted). You'll probably need to import networkx directly for subsequent operations on the graph object. From this point you can also try using one of networkx's drawing functions to display the tree, and for simple, fully labeled trees it may even work -- but you'll have better results with Phylo's own draw_graphviz function, discussed above.

Recipes for exporting to other libraries, including ape (via Rpy2) and PyCogent, are available on the Phylo cookbook page.

Tree Construction

In addition to wrappers of tree construction programs(PHYLIP programs through EMBOSS wrappers in Bio.Emboss.Applications), now Biopython also provides several tree construction algorithm implementations in pure python in the Bio.Phylo.TreeConstruction module.

All algorithms are designed as worker subclasses of a base class TreeConstructor. All constructors have the same method build_tree that accept a MultipleSeqAlignment object to construct the tree. Currently there are two types of tree constructors: DistanceTreeConstructor and ParsimonyTreeConstructor.

DistanceTreeConstructor

The DistanceTreeConstructor has two algorithms: UPGMA(Unweighted Pair Group Method with Arithmetic Mean) and NJ(Neighbor Joining).

Both algorithms construct trees based on a distance matrix. So before using these algorithms, let me introduce the DistanceCalculator to generate the distance matrix from a MultipleSeqAlignment object. The following code shows a common way to do this:

As you see, we create a DistanceCalculator object with a string 'identity', which is the name of the model(scoring matrix) to calculate the distance. The 'identity' model is the default one and can be used both for DNA and Protein sequence. To check available models for DNA, protein or all, use the attribute of the calculator dna_models, protein_models, models respectively.

After the calculator is created with the model, simply use the get_distance() method to get the distance matrix of a given alignment object. Then you will get a DistanceMatrix object, a subclass of Matrix(we will talk about this later).

Now, let's get back to the DistanceTreeConstructor. We can pass the DistanceCalculator object and a string parameter('nj' or 'upgma') to initialize it, and then call its build_tree() as mentioned before.

ParsimonyTreeConstructor

Unlike DistanceTreeConstructor, the concrete algorithm of ParsimonyTreeConstructor is delegated to two different worker classes: the ParsimonyScorer to calculate the parsimony score of a target tree by the given alignment, and the TreeSearcher to search the best tree that minimize the parsimony score. A typical usage example can be as follows:

The ParsimonyScorer is a combination of the Fitch algorithm and Sankoff algorithm. It will work as Fitch algorithm by default if no parameter is provide, and work as Sankoff algorithm if a parsimony scoring matrix(a Matrix object) is given, .

Then the scorer is passed to a TreeSearcher to tell it how to evaluate different trees during searching. Currently, only one searcher NNITreeSearcher, the Nearest Neighbor Interchange(NNI) algorithm, is implemented.

By passing the searcher and a starting tree to the ParsimonyTreeConstructor, we finally get the instance of it. If no starting tree is provided, a simple upgma tree will be created instead, with the 'identity' model. To use this parsimony constructor, just simply call the build_tree method with an alignment.

Consensus Tree

Strict, Majority Rule and Adam Consensus

Same as tree construction algorithms, three consensus tree algorithms(Strict, Majority Rule and Adam Consensus) in pure python are also implemented in the Bio.Phylo.Consensus module. You can directly call strict_consensus, majority_consensus and adam_consensus to use these algorithms with a list of trees as the input.

Instead of using 50% as the cutoff, the majority_consensus method allows you to set your own one by providing an extra cutoff parameter(0~1, 0 by default). That means it can also work as strict consensus algorithm when the cutoff equals 1. One more thing different to strict and adam consensus tree, the result majority rule consensus tree has branch support value that are automatically assigned during calculation.

Bootstrap Methods

To get the consensus tree, we must construct a list of bootstrap replicate trees. So in the Bio.Phylo.Consensus module, we also provide several useful bootstrap methods to achieve this.

As you see, the bootstrap method accepts a MultipleSeqAlignment object and generates its bootstrap replicate 100 times. The you can use them to build replicate trees. While, we also provide a convenient method to do this.

This time we pass an extra DistanceTreeConstructor object to a bootstrap_trees method and finally got the replicate trees. Note that both bootstrap and bootstrap_trees are generator functions. You need to use list() function to turn the result into a list of alignment or trees.

Another useful function is bootstrap_consensus. By passing the consensus method as another extra parameter, we can directly get the consensus tree.

In the above code, we use the first tree as the target tree that we want to calculate its branch support. The get_support method accepts the target tree and a list of trees, and returns a tree, with all internal clades assigned with branch support values.

Other Useful Classes

There are some other classes in both TreeConstruction and Consensus module that are used in those algorithms. They may not be used commonly, but might be useful to you in some cases.

Matrix.

The Matrix class in the TreeConstruction module is the super class of DistanceMatrix. They are both actually constructed by a list of names and a nested list of numbers in lower triangular matrix format. The only difference between them is that the diagonal elements in DistanceMatrix will all be 0 no matter what values are assigned.

BitString

BitString is an assistant class used frequently in the algorithms in the Consensus module. It's a sub-class of str object that only accepts two characters('0' and '1'), with additional functions for binary-like manipulation(&|^~). Common usage is as follows:

In consensus and branch support algorithms, it is used to count and store the clades in multiple trees. During counting, the clades will be considered the same if their terminals(in terms of name attribute) are the same.

For example, let's say two trees are provided as below to search their strict consensus tree:

tree1: (((A, B), C),(D, E))
tree2: ((A, (B, C)),(D, E))

For both trees, a BitString object '11111' will represent their root clade. Each '1' stands for the terminal clade in the list [A, B, C, D, E] (the order might not be the same, it's determined by the get_terminal method of the first tree provided). For the clade ((A, B), C) in tree1 and (A, (B, C)) in tree2, they both can be represented by '11100'. Similarly, '11000' represents clade (A, B) in tree1, '01100' represents clade (B, C) in tree2, and '00011' represents clade (D, E) in both trees.

So, with the _count_clades function in this module, finally we can get the clade counts and their BitString representation as follows(the root and terminals are omitted):

To get the BitString representation of a clade, we can use the following code snippet:

# suppose we are provided with a tree list, the first thing to do is
# to get all the terminal names in the first tree
term_names = [term.name for term in trees[0].get_terminals()]
# for a specific clade in any of the tree, also get its terminal names
clade_term_names = [term.name for term in clade.get_terminals()]
# then create a boolean list
boolvals = [name in clade_term_names for name in term_names]
# create the string version and pass it to BitString
bitstr = BitString(''.join(map(str, map(int, boolvals))))

To convert back:

# get all the terminal clades of the first tree
terms = [term for term in trees[0].get_terminals()]
# get the index of terminal clades in bitstr
index_list = bitstr.index_one()
# get all terminal clades by index
clade_terms = [terms[i] for i in index_list]
# create a new calde and append all the terminal clades
new_clade = BaseTree.Clade()
new_clade.clades.extend(clade_terms)

This is how the BitString is used in the consensus and branch support algorithms. And I think it can be used in many other conditions.

For example, we can even use it to check whether the structures of two trees are the same.

# store and return all BitStrings
def _bitstrs(tree):
bitstrs = set()
term_names = [term.name for term in tree.get_terminals()]
term_names.sort()
for clade in tree.get_nonterminals():
clade_term_names = [term.name for term in clade.get_terminals()]
boolvals = [name in clade_term_names for name in term_names]
bitstr = BitString(''.join(map(str, map(int, boolvals))))
bitstrs.add(bitstr)
return bitstrs
def compare(tree1, tree2):
term_names1 = [term.name for term in tree1.get_terminals()]
term_names2 = [term.name for term in tree2.get_terminals()]
# false if terminals are not the same
if set(term_names1) != set(term_names2):
return False
# true if BitStrings are the same
if _bitstrs(tree1) == _bitstrs(tree2):
return True
else:
return False

To help with annotating to your tree later, pick a lookup key here (e.g. accession number) and build a dictionary mapping that key to any additional data you can glean from the BLAST output, such as taxonomy and GI numbers. In this example, we're only keeping the original sequence and accession number.

3. Re-align the sequences using Muscle. The program creates an alignment file in Clustal format, "egfr-family.aln".