This module provides functionality for working with trees, including
phylogenetic trees and hierarchies, and prefix trees (i.e., tries).
Functionality is provided for constructing trees, for traversing in multiple
ways, comparisons, fetching subtrees, and more. This module supports trees that
are multifurcating and nodes that have single descendants.

A new tree can be constructed from a Newick string. Newick is a common format
used to represent tree objects within a file. Newick was part of the original
PHYLIP package from Joseph Felsenstein’s group (defined here), and is based around representing nesting with
parentheses. For instance, the following string describes a 3 taxon tree, with
one internal node:

((A, B)C, D)root;

Where A, B, and D are tips of the tree, and C is an internal node that covers
tips A and B.

Now let’s construct a simple tree and dump an ASCII representation:

>>> tree=TreeNode.from_newick("((A, B)C, D)root;")>>> printtree.is_root()# is this the root of the tree?True>>> printtree.is_tip()# is this node a tip?False>>> printtree.ascii_art() /-A /C-------|-root----| \-B | \-D

There are a few common ways to traverse a tree, and depending on your use,
some methods are more appropriate than others. Wikipedia has a well written
page on tree traversal methods, and will go into
further depth than what we’ll cover here. We’re only going to cover two of the
commonly used traversals here, preorder and postorder, but we will show
examples of two other common helper traversal methods to gather tips or
internal nodes.

The first traversal we’ll cover is a preorder traversal in which you evaluate
from root to tips, looking at the left most child first. For instance:

>>> fornodeintree.preorder():... printnode.namerootCABD

The next method we’ll look at is a postorder traveral which will evaluate the
left subtree tips first before walking back up the tree:

>>> fornodeintree.postorder():... printnode.nameABCDroot

TreeNode provides two helper methods as well for iterating over just the tips
or for iterating over just the internal nodes.

Note, by default, non_tips will ignore self (which is the root in this
case). You can pass the include_self flag to non_tips if you wish to
include self.

The TreeNode provides a few ways to compare trees. First, let’s create two
similar trees and compare their topologies using compare_subsets. This
distance is the fraction of common clades present in the two trees, where a
distance of 0 means the trees contain identical clades, and a distance of 1
indicates the trees do not share any common clades:

We can additionally take into account branch length when computing distances
between trees. First, we’re going to construct two new trees with described
branch length, note the difference in the Newick strings: