0
# TreeSwift
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: treeswift
7
- **Language**: Python
8
- **Installation**: `pip install treeswift`
9
- **Documentation**: https://niema.net/TreeSwift
10
- **GitHub**: https://github.com/niemasd/TreeSwift
11
12
## Core Imports
13
14
```python
15
import treeswift
16
```
17
18
Import specific components:
19
20
```python
21
from treeswift import Tree, Node, read_tree_newick
22
```
23
24
Import all main components:
25
26
```python
27
from treeswift import Tree, Node, read_tree, read_tree_newick, read_tree_nexus, read_tree_nexml, read_tree_dendropy
28
```
29
30
## Basic Usage
31
32
```python
33
import treeswift
34
35
# Load a tree from Newick format
36
tree = treeswift.read_tree_newick("((A:0.1,B:0.2):0.05,(C:0.3,D:0.4):0.15):0.0;")
37
38
# Basic tree information
39
print(f"Number of leaves: {tree.num_nodes(internal=False)}")
40
print(f"Tree height: {tree.height()}")
41
42
# Traverse the tree
43
for node in tree.traverse_postorder():
44
if node.is_leaf():
45
print(f"Leaf: {node.get_label()}")
46
else:
47
print(f"Internal node with {node.num_children()} children")
48
49
# Create a tree programmatically
50
tree = treeswift.Tree()
51
root = tree.root
52
left_child = treeswift.Node(label="A", edge_length=0.1)
53
right_child = treeswift.Node(label="B", edge_length=0.2)
54
root.add_child(left_child)
55
root.add_child(right_child)
56
57
# Output as Newick
58
print(tree.newick())
59
```
60
61
## Architecture
62
63
TreeSwift uses a simple but powerful node-based tree representation:
64
65
- **Tree**: The main container class that holds references to the root node and provides tree-level operations
66
- **Node**: Individual nodes that form the tree structure, containing parent-child relationships, labels, and edge lengths
67
- **File Format Support**: Built-in parsers for Newick, Nexus, NeXML formats and integration with DendroPy
68
- **Traversal Algorithms**: Multiple traversal methods (preorder, postorder, level-order, etc.) implemented as efficient generators
69
- **Performance Focus**: Optimized implementations for common phylogenetic operations
70
71
## Capabilities
72
73
### Tree I/O and Parsing
74
75
Read trees from multiple file formats including Newick, Nexus, NeXML, and DendroPy integration. Support for both string and file inputs with automatic format detection.
76
77
```python { .api }
78
def read_tree(input: str, schema: str) -> Tree | list[Tree] | dict[str, Tree]
79
def read_tree_newick(newick: str) -> Tree | list[Tree]
80
def read_tree_nexus(nexus: str, translate: bool = True) -> dict[str, Tree]
81
def read_tree_nexml(nexml: str) -> dict[str, Tree]
82
def read_tree_dendropy(tree) -> Tree
83
def read_tree_linkage(linkage, return_list: bool = False) -> Tree | list[Tree]
84
```
85
86
[Tree I/O and Parsing](./tree-io.md)
87
88
### Tree Traversal
89
90
Comprehensive tree traversal methods including preorder, postorder, level-order, inorder, and distance-based traversals. All traversal methods are implemented as memory-efficient generators.
91
92
```python { .api }
93
def traverse_preorder(self, leaves: bool = True, internal: bool = True) -> Generator[Node, None, None]
94
def traverse_postorder(self, leaves: bool = True, internal: bool = True) -> Generator[Node, None, None]
95
def traverse_levelorder(self, leaves: bool = True, internal: bool = True) -> Generator[Node, None, None]
96
def traverse_inorder(self, leaves: bool = True, internal: bool = True) -> Generator[Node, None, None]
97
def traverse_rootdistorder(self, ascending: bool = True, leaves: bool = True, internal: bool = True) -> Generator[tuple[float, Node], None, None]
98
```
99
100
[Tree Traversal](./tree-traversal.md)
101
102
### Tree Manipulation
103
104
Extensive tree modification operations including rerooting, subtree extraction, node contraction, polytomy resolution, and branch manipulation. Supports both in-place modifications and copy-based operations.
105
106
```python { .api }
107
def reroot(self, node: Node, length: float = None, branch_support: bool = False) -> None
108
def extract_subtree(self, node: Node) -> Tree
109
def extract_tree_with(self, labels: set, suppress_unifurcations: bool = True) -> Tree
110
def contract_low_support(self, threshold: float, terminal: bool = False, internal: bool = True) -> None
111
def resolve_polytomies(self) -> None
112
def scale_edges(self, multiplier: float) -> None
113
```
114
115
[Tree Manipulation](./tree-manipulation.md)
116
117
### Tree Analysis and Metrics
118
119
Comprehensive tree analysis including distance calculations, balance indices, phylogenetic statistics, and coalescence analysis. Supports both basic metrics and advanced phylogenetic measures.
120
121
```python { .api }
122
def distance_matrix(self, leaf_labels: bool = False) -> dict
123
def diameter(self) -> float
124
def height(self, weighted: bool = True) -> float
125
def colless(self, normalize: str = 'leaves') -> float
126
def sackin(self, normalize: str = 'leaves') -> float
127
def gamma_statistic(self) -> float
128
def coalescence_times(self, backward: bool = True) -> Generator[float, None, None]
129
def find_node(self, label: object, leaves: bool = True, internal: bool = False) -> Node | list[Node] | None
130
def label_to_node(self, selection: str | set = 'leaves') -> dict
131
def labels(self, leaves: bool = True, internal: bool = True) -> Generator[object, None, None]
132
```
133
134
[Tree Analysis and Metrics](./tree-analysis.md)
135
136
### Node Operations
137
138
Individual node manipulation including label and edge length management, parent-child relationships, node properties, and node-level traversals.
139
140
```python { .api }
141
def add_child(self, child: Node) -> None
142
def remove_child(self, child: Node) -> None
143
def get_label(self) -> object
144
def set_label(self, label: object) -> None
145
def get_edge_length(self) -> float
146
def set_edge_length(self, length: float) -> None
147
def is_leaf(self) -> bool
148
def is_root(self) -> bool
149
```
150
151
[Node Operations](./node-operations.md)
152
153
### Visualization and Output
154
155
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.
156
157
```python { .api }
158
def draw(self, show_plot: bool = True, export_filename: str = None, show_labels: bool = False, **kwargs) -> None
159
def newick(self) -> str
160
def write_tree_newick(self, filename: str, hide_rooted_prefix: bool = False) -> None
161
def lineages_through_time(self, present_day: float = None, show_plot: bool = True, **kwargs) -> dict
162
def plot_ltt(lineages: dict, show_plot: bool = True, **kwargs) -> None
163
```
164
165
[Visualization and Output](./visualization.md)
166
167
## Types
168
169
```python { .api }
170
class Tree:
171
"""Main tree container class."""
172
root: Node
173
is_rooted: bool
174
175
def __init__(self, is_rooted: bool = True) -> None: ...
176
177
class Node:
178
"""Individual tree node with parent-child relationships."""
179
children: list[Node]
180
parent: Node | None
181
label: object
182
edge_length: float | None
183
184
def __init__(self, label: object = None, edge_length: float = None) -> None: ...
185
```