TreeSwift: Fast tree module for Python 2 and 3 - A Python library for parsing, manipulating, and iterating over rooted tree structures with emphasis on performance and speed.
npx @tessl/cli install tessl/pypi-treeswift@1.1.0TreeSwift is a pure Python library for parsing, manipulating, and iterating over rooted tree structures with emphasis on performance and speed. It provides comprehensive tree traversal capabilities, supports multiple tree file formats (Newick, NEXUS, NeXML), and offers efficient tree manipulation operations for phylogenetic analysis and computational biology applications.
pip install treeswiftimport treeswiftImport specific components:
from treeswift import Tree, Node, read_tree_newickImport all main components:
from treeswift import Tree, Node, read_tree, read_tree_newick, read_tree_nexus, read_tree_nexml, read_tree_dendropyimport treeswift
# Load a tree from Newick format
tree = treeswift.read_tree_newick("((A:0.1,B:0.2):0.05,(C:0.3,D:0.4):0.15):0.0;")
# Basic tree information
print(f"Number of leaves: {tree.num_nodes(internal=False)}")
print(f"Tree height: {tree.height()}")
# Traverse the tree
for node in tree.traverse_postorder():
if node.is_leaf():
print(f"Leaf: {node.get_label()}")
else:
print(f"Internal node with {node.num_children()} children")
# Create a tree programmatically
tree = treeswift.Tree()
root = tree.root
left_child = treeswift.Node(label="A", edge_length=0.1)
right_child = treeswift.Node(label="B", edge_length=0.2)
root.add_child(left_child)
root.add_child(right_child)
# Output as Newick
print(tree.newick())TreeSwift uses a simple but powerful node-based tree representation:
Read trees from multiple file formats including Newick, Nexus, NeXML, and DendroPy integration. Support for both string and file inputs with automatic format detection.
def read_tree(input: str, schema: str) -> Tree | list[Tree] | dict[str, Tree]
def read_tree_newick(newick: str) -> Tree | list[Tree]
def read_tree_nexus(nexus: str, translate: bool = True) -> dict[str, Tree]
def read_tree_nexml(nexml: str) -> dict[str, Tree]
def read_tree_dendropy(tree) -> Tree
def read_tree_linkage(linkage, return_list: bool = False) -> Tree | list[Tree]Comprehensive tree traversal methods including preorder, postorder, level-order, inorder, and distance-based traversals. All traversal methods are implemented as memory-efficient generators.
def traverse_preorder(self, leaves: bool = True, internal: bool = True) -> Generator[Node, None, None]
def traverse_postorder(self, leaves: bool = True, internal: bool = True) -> Generator[Node, None, None]
def traverse_levelorder(self, leaves: bool = True, internal: bool = True) -> Generator[Node, None, None]
def traverse_inorder(self, leaves: bool = True, internal: bool = True) -> Generator[Node, None, None]
def traverse_rootdistorder(self, ascending: bool = True, leaves: bool = True, internal: bool = True) -> Generator[tuple[float, Node], None, None]Extensive tree modification operations including rerooting, subtree extraction, node contraction, polytomy resolution, and branch manipulation. Supports both in-place modifications and copy-based operations.
def reroot(self, node: Node, length: float = None, branch_support: bool = False) -> None
def extract_subtree(self, node: Node) -> Tree
def extract_tree_with(self, labels: set, suppress_unifurcations: bool = True) -> Tree
def contract_low_support(self, threshold: float, terminal: bool = False, internal: bool = True) -> None
def resolve_polytomies(self) -> None
def scale_edges(self, multiplier: float) -> NoneComprehensive tree analysis including distance calculations, balance indices, phylogenetic statistics, and coalescence analysis. Supports both basic metrics and advanced phylogenetic measures.
def distance_matrix(self, leaf_labels: bool = False) -> dict
def diameter(self) -> float
def height(self, weighted: bool = True) -> float
def colless(self, normalize: str = 'leaves') -> float
def sackin(self, normalize: str = 'leaves') -> float
def gamma_statistic(self) -> float
def coalescence_times(self, backward: bool = True) -> Generator[float, None, None]
def find_node(self, label: object, leaves: bool = True, internal: bool = False) -> Node | list[Node] | None
def label_to_node(self, selection: str | set = 'leaves') -> dict
def labels(self, leaves: bool = True, internal: bool = True) -> Generator[object, None, None]Individual node manipulation including label and edge length management, parent-child relationships, node properties, and node-level traversals.
def add_child(self, child: Node) -> None
def remove_child(self, child: Node) -> None
def get_label(self) -> object
def set_label(self, label: object) -> None
def get_edge_length(self) -> float
def set_edge_length(self, length: float) -> None
def is_leaf(self) -> bool
def is_root(self) -> boolTree visualization using matplotlib and various output formats including Newick, Nexus, and indented representations. Support for lineages-through-time plots and tree drawing with customizable styling.
def draw(self, show_plot: bool = True, export_filename: str = None, show_labels: bool = False, **kwargs) -> None
def newick(self) -> str
def write_tree_newick(self, filename: str, hide_rooted_prefix: bool = False) -> None
def lineages_through_time(self, present_day: float = None, show_plot: bool = True, **kwargs) -> dict
def plot_ltt(lineages: dict, show_plot: bool = True, **kwargs) -> Noneclass Tree:
"""Main tree container class."""
root: Node
is_rooted: bool
def __init__(self, is_rooted: bool = True) -> None: ...
class Node:
"""Individual tree node with parent-child relationships."""
children: list[Node]
parent: Node | None
label: object
edge_length: float | None
def __init__(self, label: object = None, edge_length: float = None) -> None: ...