πŸ“¦ Core

Core data structures for phylogenetic modeling and simulation.

class phyloom.core.MSA(sequences: Iterable[SequenceRecord])[source]

Multiple sequence alignment.

Parameters:

sequences – Sequence records in alignment order.

Examples

Maintain a multiple sequence alignment of three sequences.

>>> from phyloom.core import MSA, SequenceRecord
>>> sequences = [
...     SequenceRecord("human", "ACGT"),
...     SequenceRecord("mouse", "A-GT"),
...     SequenceRecord("avian", "AC-T"),
... ]
>>> msa = MSA(sequences)
>>> [sequence.name for sequence in msa]
['human', 'mouse', 'avian']
>>> msa.n_sequences, msa.n_sites, msa.shape, msa.n_unique_sequences
(3, 4, (3, 4), 3)
>>> len(msa)
3

Empty and ragged alignments are rejected.

>>> MSA([])
Traceback (most recent call last):
...
ValueError: MSA must contain at least one sequence.
>>> MSA([SequenceRecord("a", "AC"), SequenceRecord("b", "A")])
Traceback (most recent call last):
...
ValueError: All sequences in the alignment must have the same length (got lengths: {1, 2}).
property sequences: tuple[SequenceRecord, ...]

Sequence records in alignment order.

property n_sequences: int

Number of sequences in the alignment.

property n_sites: int

Number of aligned sites in each sequence.

property shape: tuple[int, int]

Alignment shape as (n_sequences, n_sites).

property n_unique_sequences: int

Number of distinct character rows in the alignment.

dump(filepath: PathLike, header_from_sequence: Callable[[SequenceRecord], str] | None)[source]

Write the alignment to a FASTA file.

Parameters:
  • filepath – Path to the output FASTA file.

  • header_from_sequence – Optional function to generate a header from a sequence. If not provided, the sequence name is used as the header.

__len__() → int[source]

Return the number of sequences in the alignment.

__iter__() → Iterator[SequenceRecord][source]

Iterate over sequence records in alignment order.

class phyloom.core.Edge(length: LengthT_co | None = None, **kwargs: Any)[source]

Bases: MetadataMixin, Generic[LengthT_co]

A directed edge in a phylogenetic tree or network.

Parameters:
  • length – Optional edge length.

  • kwargs – Additional metadata associated with the edge.

property length: LengthT_co

Edge length.

class phyloom.core.Net(nodes: Mapping[NodeID, Node], edges: Mapping[tuple[NodeID, NodeID], Edge[LengthT_co]], root: NodeID, stem: Edge[LengthT_co] | None = None)[source]

Bases: Generic[LengthT_co]

Phylogenetic network.

A Net represents a rooted directed acyclic graph (DAG) in which every node is reachable from a distinguished root and edges are directed away from that root. Unlike a tree, a network may contain reticulation nodes with multiple parents while remaining acyclic. An optional stem edge can represent the branch leading into the network above the root.

Parameters:
  • nodes – Mapping from node ids to node records.

  • edges – Mapping from directed (parent, child) node-id pairs to edge records.

  • root – Root node id.

  • stem – Optional stem edge attached above the root.

Examples

Maintain a phylogenetic network with four nodes.

>>> from phyloom.core import Net, Node, Edge
>>> names = ["root", "left", "right", "reticulate"]
>>> nodes = {i: Node(name) for i, name in enumerate(names)}
>>> links = [(0, 1), (0, 2), (1, 3), (2, 3)]
>>> edges = {link: Edge() for link in links}
>>> net = Net(nodes, edges, root=0)
>>> net.root, net.stem
(0, None)
>>> net.n_nodes, net.n_edges
(4, 4)
>>> [nodes[node].name for node in net]
['root', 'right', 'left', 'reticulate']
>>> [nodes[parent].name for parent in net.parents_of(3)]
['left', 'right']
>>> net.children_of(0)
(1, 2)
>>> net.is_leaf(0), net.is_leaf(3)
(False, True)
>>> net.get_leaves(), net.count_leaves()
((3,), 1)
>>> net.is_internal(0), net.is_internal(3)
(True, False)
>>> net.get_internals(), net.count_internals()
((0, 2, 1), 3)
>>> net.get_node_id("reticulate"), net.get_node("reticulate")
(3, Node(name='reticulate', metadata={}))
>>> net.pretty_print()
root
|-- left
|   `-- reticulate
`-- right
    `-- ref reticulate

Cycles are rejected.

>>> cyclic_edges = {**edges, (3, 1): Edge()}
>>> Net(nodes, cyclic_edges, root=0)
Traceback (most recent call last):
...
ValueError: The network is not a DAG or is not fully connected from the root.

Every node must be reachable from the root.

>>> Net({**nodes, 4: Node("unreachable")}, edges, root=0)
Traceback (most recent call last):
...
ValueError: The network is not a DAG or is not fully connected from the root.
property nodes: Mapping[NodeID, Node]

Read-only mapping from node ids to node records.

property n_nodes: int

Number of nodes in the network.

property edges: Mapping[tuple[NodeID, NodeID], Edge[LengthT_co]]

Read-only mapping from directed (parent, child) node-id pairs to edge records.

property n_edges: int

Number of edges in the network.

property root: NodeID

Root node id.

property stem: Edge[LengthT_co] | None

Stem edge attached above the root.

children_of(node: NodeID) → tuple[NodeID, ...][source]

Get the children of a node.

parents_of(node: NodeID) → tuple[NodeID, ...][source]

Get the parents of a node.

is_leaf(node: NodeID) → bool[source]

Check if a node is a leaf (has no children).

get_leaves() → tuple[NodeID, ...][source]

Get all leaf nodes.

count_leaves() → int[source]

Count the number of leaf nodes.

is_internal(node: NodeID) → bool[source]

Check if a node is internal (has at least one child).

get_internals() → tuple[NodeID, ...][source]

Get all internal nodes.

count_internals() → int[source]

Count the number of internal nodes.

get_node_id(name: str) → NodeID[source]

Get a node id by its name.

get_node(name: str) → Node[source]

Get a node record by its name.

to_newick() → str[source]

Serialize the network into a Newick string.

dump(filepath: PathLike)[source]

Write the network to a Newick file.

pretty_print()[source]

Print a human-readable representation of the network.

__iter__() → Iterator[NodeID][source]

Iterate over the nodes in the network in a topological order (parents before children).

class phyloom.core.Node(name: str = '', **kwargs: Any)[source]

Bases: MetadataMixin

A node in a phylogenetic tree or network.

Parameters:
  • name – Node name.

  • kwargs – Additional metadata associated with the node.

property name: str

Node name.

class phyloom.core.SequenceRecord(name: str, chars: str, **kwargs: Any)[source]

Bases: MetadataMixin

A sequence record in a multiple sequence alignment (MSA).

Parameters:
  • name – Sequence name.

  • chars – Sequence characters. Must contain at least one character.

  • **kwargs – Additional metadata associated with the sequence.

property name: str

Sequence name.

property chars: str

Sequence characters.

property n_chars: int

Number of characters in the sequence.

class phyloom.core.Tree(nodes: Mapping[NodeID, Node], edges: Mapping[tuple[NodeID, NodeID], Edge[LengthT_co]], root: NodeID, stem: Edge[LengthT_co] | None = None)[source]

Bases: Net[LengthT_co]

Phylogenetic tree.

A Tree represents a rooted directed tree in which every node is reachable from a distinguished root, and edges are directed away from that root. Unlike a network, a tree contains no reticulation nodes with multiple parents: every node except the root has exactly one parent. An optional stem edge can represent the branch leading into the tree above the root.

Parameters:
  • nodes – Mapping from node ids to node records.

  • edges – Mapping from directed (parent, child) node-id pairs to edge records.

  • root – Root node id.

  • stem – Optional stem edge attached above the root.

Examples

Maintain a phylogenetic tree with five nodes.

>>> from phyloom.core import Edge, Node, Tree
>>> names = ["root", "left", "right", "left-left", "left-right"]
>>> nodes = {i: Node(name) for i, name in enumerate(names)}
>>> links = [(0, 1), (0, 2), (1, 3), (1, 4)]
>>> lengths = [0.2, 0.3, 0.4, 0.5]
>>> edges = {link: Edge(length) for link, length in zip(links, lengths)}
>>> tree = Tree(nodes, edges, root=0, stem=Edge(length=0.1))
>>> tree.root
0
>>> tree.nodes[tree.parent_of(4)].name
'left'
>>> tree.children_of(1)
(3, 4)
>>> tree.get_leaves(), tree.count_leaves()
((2, 4, 3), 3)
>>> tree.get_internals(), tree.count_internals()
((0, 1), 2)
>>> tree.edge_of(0).length, tree.edge_of(4).length
(0.1, 0.5)
>>> tree.is_binary()
True
>>> tree.get_mrca([3, 4])
1
>>> tree.get_path(3, 2)
[3, 1, 0, 2]

Reticulation nodes are rejected.

>>> nodes = {i: Node(str(i)) for i in range(4)}
>>> links = [(0, 1), (0, 2), (1, 3), (2, 3)]
>>> edges = {link: Edge() for link in links}
>>> Tree(nodes, edges, root=0)
Traceback (most recent call last):
...
ValueError: The network is not a tree: some nodes have more than one parent.
parent_of(node: NodeID) → NodeID[source]

Get the unique parent of a node.

edge_of(node: NodeID) → Edge[LengthT_co][source]

Get the edge leading into a node.

is_binary() → bool[source]

Check whether every internal node has exactly two children.

get_mrca(nodes: Iterable[NodeID]) → NodeID[source]

Get the most recent common ancestor of two nodes.

get_path(from_node: NodeID, to_node: NodeID) → list[NodeID][source]

Get the path between two nodes, including both endpoints.

ladderize()[source]

Sort each node’s children by the number of descendant leaves.

The tree is modified in place. Children with fewer descendant leaves are placed first.

Examples

>>> from phyloom.core import Edge, Node, Tree
>>> nodes = {i: Node(str(i)) for i in range(5)}
>>> links = [(0, 2), (0, 1), (2, 3), (2, 4)]
>>> edges = {link: Edge() for link in links}
>>> tree = Tree(nodes, edges, root=0)
>>> tree.pretty_print()
0
|-- 2
|   |-- 3
|   `-- 4
`-- 1
>>> tree.ladderize()
>>> tree.pretty_print()
0
|-- 1
`-- 2
    |-- 3
    `-- 4