Trees¶
|
Tree (e.g. a phylogeny). |
|
Plot a tree with matplotlib. |
|
Calculate 2D coordinates of all nodes, as used by |
- class picea.Tree(name=None, length=None, children=<factory>, ID=None, depth=None, parent=None, cumulative_length=None)[source]¶
Tree (e.g. a phylogeny). Trees are recursive: every node is a
Treewith a list of child nodes, so every node is also the root of its own subtree.Trees are usually created with
from_newick()orfrom_sklearn(). These also set the derived node attributesparent,depth,cumulative_length(distance to the root) andID(seeiloc).Examples
>>> tree = Tree.from_newick('((a,b)ab,c);') >>> [leaf.name for leaf in tree.leaves] ['c', 'a', 'b'] >>> tree.loc['a'].parent.name 'ab'
- Parameters:
- property loc: TreeIndex¶
tree.loc[name]returns the first node with that name (in post-order depth first traversal)Example
>>> from picea import Tree >>> newick = '(((a,b),(c,d)),e);' >>> tree = Tree.from_newick(newick) >>> tree.loc['a'] Tree(name='a', length=None, children=[])
- Raises:
IndexError – If no node has this name
- Type:
Name based index
- property iloc: TreeIndex¶
tree.iloc[ID]returns the node with that ID.from_newick()numbers nodes in pre-order, starting with 0 for the root.Example
>>> from picea import Tree >>> newick = '(((a,b),(c,d)),e);' >>> tree = Tree.from_newick(newick) >>> [leaf.name for leaf in tree.iloc[2].leaves] ['a', 'b']
- Raises:
IndexError – If no node has this ID
- Type:
ID based index
- property nodes: List[Tree]¶
A list of all tree nodes in breadth-first order
- Returns:
A list of all tree nodes
- Return type:
- property leaves: List[Tree]¶
A list of leaf nodes only
- Returns:
A list of leaf nodes only
- Return type:
- property links: List[Tuple[Tree, Tree]]¶
A list of all (parent, child) combinations
- Returns:
All (parent,child) combinations
- Return type:
- classmethod from_newick(string=None, filename=None)[source]¶
Parse a Newick formatted file or string. Exactly one of
stringorfilenamemust be given.Node names (including internal node names such as support values) and branch lengths are read when present. If some nodes have a branch length, other nodes (except the root) without one get length 0.0 with a warning.
Examples
>>> tree = Tree.from_newick('((a:1,b:2)ab:1,c:3)root:0;') >>> tree.loc['b'].cumulative_length 3.0
- to_newick(branch_lengths=False)[source]¶
Newick formatted string of the (sub)tree. The node this is called on is the root of the Newick tree, so its branch length is not written.
Examples
>>> tree = Tree.from_newick('((a:1,b:2)ab:1,c:3)root:0;') >>> tree.to_newick(branch_lengths=True) '((a:1.0,b:2.0)ab:1.0,c:3.0)root;'
- classmethod from_sklearn(clustering)[source]¶
Create a tree from a fitted scikit-learn
AgglomerativeClusteringmodel. Leaves are named by sample index, and the tree has no branch lengths.- Parameters:
clustering (sklearn.cluster.AgglomerativeClustering) – Fitted clustering model
- Returns:
Root node
- Return type:
- to_json(indent=None)[source]¶
json formatted string of
to_dict()- Parameters:
indent (Optional[int]) – Indentation, passed to
json.dumps()- Returns:
json formatted string
- Return type:
- to_dict()[source]¶
Nested dictionary with the
name,lengthandchildrenof every node- Returns:
Tree dictionary
- Return type:
TreeDict
- depth_first(post_order=True)[source]¶
Generator implementing depth first search in either post- or pre-order traversel
- Keyword Arguments:
post_order (bool, optional) – Depth first search in post-order
True (traversal or not. Defaults to)
- picea.treeplot(tree, style=TreeStyle.square, branchlengths=True, ltr=True, node_labels=True, leaf_labels=True, leaf_marker='o', leaf_marker_fill='white', leaf_marker_edge='black', branch_linestyle=None, ax=None, return_layout=False)[source]¶
Plot a tree with matplotlib. See the Trees example for usage.
- Parameters:
tree (Tree) – Tree to plot
style (Union[str, TreeStyle], optional) – Branch style:
"square"(right angles),"triangular"(straight lines from parent to child), or"radial"(root in the center). Defaults toTreeStyle.square.branchlengths (bool, optional) – Scale branches by their length. Use False to plot a cladogram. Trees without branch lengths are always plotted as a cladogram. Defaults to True.
ltr (bool, optional) – Plot left to right (root on the left). Ignored for the radial style. Defaults to True.
node_labels (bool, optional) – Show the names of internal nodes, e.g. support values. Defaults to True.
leaf_labels (bool, optional) – Show leaf names. Defaults to True.
leaf_marker (Union[str, Callable, None], optional) – Matplotlib marker for leaves, a function that takes a leaf and returns a marker, or None for no markers. Defaults to
"o".leaf_marker_fill (Union[str, Callable[[Tree], str], None], optional) – Marker fill color, or a function that takes a leaf and returns a color. Defaults to
"white".leaf_marker_edge (Union[str, Callable[[Tree], str], None], optional) – Marker edge color, or a function that takes a leaf and returns a color. Defaults to
"black".branch_linestyle (Union[dict, Callable[[Tuple[Tree, Tree]], dict], None], optional) – Keyword arguments for
matplotlib.axes.Axes.plot()used to draw branches, or a function that takes a(parent, child)tuple and returns them. Defaults to None (thin black lines).ax (Optional[Ax], optional) – Axes to plot on. A new figure is created when not given.
return_layout (bool, optional) – Also return the node coordinates (see
calculate_tree_layout()). Defaults to False.
- Returns:
The axes, or an
(axes, layout)tuple ifreturn_layoutis True- Return type:
Union[Ax, Tuple[Ax, LayoutDict]]
- Raises:
ValueError – If
styleis not a valid styleTypeError – If a styling option has an invalid type
- picea.calculate_tree_layout(tree, style=TreeStyle.square, ltr=True, branchlengths=True)[source]¶
Calculate 2D coordinates of all nodes, as used by
treeplot()Leaves get consecutive y coordinates (0, 1, 2, …) in depth first order, and internal nodes are centered on their children. With branch lengths, x is the distance to the root. Without branch lengths, or for trees that have none, x is the number of levels below the root, with all leaves aligned (a cladogram). In the radial layout the root is in the center, the radius is the distance to the root, and leaves are spread evenly over the circle.
Examples
>>> tree = Tree.from_newick('((a:1,b:2)ab:1,c:3)root;') >>> layout = calculate_tree_layout(tree) >>> [(node.name, layout[node.ID].x, layout[node.ID].y) for node in tree.leaves] [('c', 3.0, 2.0), ('a', 2.0, 0.0), ('b', 3.0, 1.0)]
- Parameters:
tree (Tree) – Tree
style (Union[str, TreeStyle], optional) –
"square","triangular"or"radial". Only"radial"changes the node coordinates. Defaults toTreeStyle.square.ltr (bool, optional) – Left to right layout (root on the left). If False, x coordinates are negative. Ignored for the radial layout. Defaults to True.
branchlengths (bool, optional) – Use branch lengths. Defaults to True.
- Returns:
Coordinates of every node, by node ID
- Return type:
LayoutDict
- Raises:
ValueError – If
styleis not a valid style