or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.mdnode-operations.mdtree-analysis.mdtree-io.mdtree-manipulation.mdtree-traversal.mdvisualization.md
tile.json

tessl/pypi-treeswift

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.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/treeswift@1.1.x

To install, run

npx @tessl/cli install tessl/pypi-treeswift@1.1.0

index.mddocs/

TreeSwift

TreeSwift 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.

Package Information

  • Package Name: treeswift
  • Language: Python
  • Installation: pip install treeswift
  • Documentation: https://niema.net/TreeSwift
  • GitHub: https://github.com/niemasd/TreeSwift

Core Imports

import treeswift

Import specific components:

from treeswift import Tree, Node, read_tree_newick

Import all main components:

from treeswift import Tree, Node, read_tree, read_tree_newick, read_tree_nexus, read_tree_nexml, read_tree_dendropy

Basic Usage

import 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())

Architecture

TreeSwift uses a simple but powerful node-based tree representation:

  • Tree: The main container class that holds references to the root node and provides tree-level operations
  • Node: Individual nodes that form the tree structure, containing parent-child relationships, labels, and edge lengths
  • File Format Support: Built-in parsers for Newick, Nexus, NeXML formats and integration with DendroPy
  • Traversal Algorithms: Multiple traversal methods (preorder, postorder, level-order, etc.) implemented as efficient generators
  • Performance Focus: Optimized implementations for common phylogenetic operations

Capabilities

Tree I/O and Parsing

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]

Tree I/O and Parsing

Tree Traversal

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]

Tree Traversal

Tree Manipulation

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) -> None

Tree Manipulation

Tree Analysis and Metrics

Comprehensive 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]

Tree Analysis and Metrics

Node Operations

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) -> bool

Node Operations

Visualization and Output

Tree 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) -> None

Visualization and Output

Types

class 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: ...