Skip to content

Trees

Everything that takes a finished Tree. Build trees with this package or read_newick; the functions assume leaves first and internal nodes ordered by height.

tree

Working with a finished tree: Newick, layouts, clustering and distances.

to_newick

to_newick(
    tree: Tree, labels: Sequence[str] | None = None
) -> str

Serialise a tree to Newick.

Parameters:

Name Type Description Default
tree Tree

The tree.

required
labels Sequence[str] | None

One label per leaf. None labels leaves by index.

None

Returns:

Type Description
str

The Newick string, semicolon terminated.

read_newick

read_newick(text: str) -> tuple[Tree, list[str]]

Parse a Newick string.

Parameters:

Name Type Description Default
text str

The Newick string.

required

Returns:

Type Description
tuple[Tree, list[str]]

The tree and its leaf labels, in leaf order.

layout

layout(
    tree: Tree,
    *,
    kind: Literal[
        "daylight", "angle", "dendrogram"
    ] = "daylight",
    hyperbolic: bool = False,
) -> ndarray

Node coordinates for drawing.

Parameters:

Name Type Description Default
tree Tree

The tree.

required
kind Literal['daylight', 'angle', 'dendrogram']

"daylight" (equal-daylight radial, the default), "angle" (equal-angle radial, faster and cruder) or "dendrogram". Equal daylight falls back to equal angle above a node count where refinement stops paying.

'daylight'
hyperbolic bool

Project onto the Poincare disk afterwards, which gives the crowded outer branches more room.

False

Returns:

Type Description
ndarray

(n_nodes, 2) coordinates. Draw an edge from every node i with

ndarray

tree.parent[i] >= 0 to its parent.

cluster

cluster(tree: Tree, n_clusters: int) -> Clustering

Cut the tree into clusters.

Greedy branch cuts minimising the summed within-cluster leaf distance. The numbering depends on the tree alone.

Parameters:

Name Type Description Default
tree Tree

The tree.

required
n_clusters int

How many clusters, clamped to 1..n_leaves.

required

Returns:

Type Description
Clustering

The clustering.

tree_distances

tree_distances(
    tree: Tree, pairs: ndarray | None = None
) -> ndarray

Path distance along the tree between leaves.

Parameters:

Name Type Description Default
tree Tree

The tree.

required
pairs ndarray | None

(m, 2) leaf index pairs. None for every pair, returned as a square (n_leaves, n_leaves) matrix; that is quadratic in memory, so sample pairs on large trees.

None

Returns:

Type Description
ndarray

One distance per pair, or the full matrix.

robinson_foulds

robinson_foulds(left: Tree, right: Tree) -> int

Robinson-Foulds distance between two trees over the same leaves.

Leaves are matched by index. Branch lengths are ignored.

Parameters:

Name Type Description Default
left Tree

First tree.

required
right Tree

Second tree.

required

Returns:

Type Description
int

Splits in one tree but not the other.