Trees

Tree([name, length, children, ID, depth, ...])

Tree (e.g. a phylogeny).

treeplot(tree[, style, branchlengths, ltr, ...])

Plot a tree with matplotlib.

calculate_tree_layout(tree[, style, ltr, ...])

Calculate 2D coordinates of all nodes, as used by treeplot()

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 Tree with a list of child nodes, so every node is also the root of its own subtree.

Trees are usually created with from_newick() or from_sklearn(). These also set the derived node attributes parent, depth, cumulative_length (distance to the root) and ID (see iloc).

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:
  • name (Optional[str]) – Node name

  • length (Optional[float]) – Length of the branch to the parent node

  • children (Optional[List[Tree]]) – Child nodes

  • ID (Optional[int]) – Node ID

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 root: Tree

Root node of the (sub)tree

Returns:

Root node

Return type:

Tree

property nodes: List[Tree]

A list of all tree nodes in breadth-first order

Returns:

A list of all tree nodes

Return type:

list

property leaves: List[Tree]

A list of leaf nodes only

Returns:

A list of leaf nodes only

Return type:

list

A list of all (parent, child) combinations

Returns:

All (parent,child) combinations

Return type:

list

classmethod from_newick(string=None, filename=None)[source]

Parse a Newick formatted file or string. Exactly one of string or filename must 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
Parameters:
  • string (Optional[str]) – Newick formatted string

  • filename (Optional[str]) – Newick filename

Returns:

Root node

Return type:

Tree

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;'
Parameters:

branch_lengths (bool, optional) – Include branch lengths. Nodes without a branch length are written with length 0, with a warning. Defaults to False.

Returns:

Newick formatted string

Return type:

str

classmethod from_sklearn(clustering)[source]

Create a tree from a fitted scikit-learn AgglomerativeClustering model. 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:

Tree

to_sklearn()[source]

Not implemented yet

classmethod from_json()[source]

Not implemented yet

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:

str

classmethod from_dict(tree_dict)[source]

Not implemented yet

to_dict()[source]

Nested dictionary with the name, length and children of every node

Returns:

Tree dictionary

Return type:

TreeDict

breadth_first()[source]

Generator implementing breadth first search starting at root node

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)

rename_leaves(rename_func, inplace=True)[source]

Rename all leaves by calling rename_func on every leaf name

Parameters:
  • rename_func (Callable[[str], str]) – Function that takes a leaf name and returns a new name

  • inplace (bool) – Rename the leaves of this tree. If False, rename and return a copy.

Returns:

The renamed copy if inplace is False, otherwise None

Return type:

Optional[Tree]

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 to TreeStyle.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 if return_layout is True

Return type:

Union[Ax, Tuple[Ax, LayoutDict]]

Raises:
  • ValueError – If style is not a valid style

  • TypeError – 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 to TreeStyle.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 style is not a valid style