0
# Core Tree Operations
1
2
Fundamental tree structure manipulation and analysis operations that form the foundation of all ETE3 functionality. These operations provide the essential capabilities for creating, modifying, traversing, and analyzing hierarchical tree structures.
3
4
## Capabilities
5
6
### Tree Creation and Initialization
7
8
Create tree structures from various input formats, with support for Newick format parsing and manual tree construction.
9
10
```python { .api }
11
class Tree:
12
def __init__(self, newick=None, format=0, dist=None, support=None, name=None, quoted_node_names=False):
13
"""
14
Initialize a Tree/TreeNode instance.
15
16
Parameters:
17
- newick (str): Newick format string or file path
18
- format (int): Newick subformat (0-9)
19
0: flexible with support values
20
1: flexible with internal node names
21
2: all branches + leaf names + internal supports
22
3: all branches + all names
23
4: leaf branches + leaf names
24
5: internal and leaf branches + leaf names
25
6: internal branches + leaf names
26
7: leaf branches + all names
27
8: all names
28
9: leaf names
29
- dist (float): Initial branch length
30
- support (float): Initial support value
31
- name (str): Initial node name
32
- quoted_node_names (bool): Handle quoted node names
33
"""
34
```
35
36
### Node Structure Manipulation
37
38
Add, remove, and modify tree nodes to build and reshape tree structures.
39
40
```python { .api }
41
def add_child(self, child=None, name=None, dist=None, support=None):
42
"""
43
Add a child node to current node.
44
45
Parameters:
46
- child (TreeNode): Existing node to add as child
47
- name (str): Name for new child node
48
- dist (float): Branch length to child
49
- support (float): Support value for branch
50
51
Returns:
52
TreeNode: The added child node
53
"""
54
55
def add_sister(self, sister=None, name=None, dist=None):
56
"""
57
Add a sister node at the same level.
58
59
Parameters:
60
- sister (TreeNode): Existing node to add as sister
61
- name (str): Name for new sister node
62
- dist (float): Branch length to sister
63
64
Returns:
65
TreeNode: The added sister node
66
"""
67
68
def remove_child(self, child):
69
"""
70
Remove a child node.
71
72
Parameters:
73
- child (TreeNode): Child node to remove
74
"""
75
76
def delete(self, prevent_nondicotomic=True, preserve_branch_length=False):
77
"""
78
Delete current node from tree.
79
80
Parameters:
81
- prevent_nondicotomic (bool): Avoid creating multifurcations
82
- preserve_branch_length (bool): Preserve branch lengths when deleting
83
"""
84
85
def detach(self):
86
"""
87
Detach node from its parent, returning the detached subtree.
88
89
Returns:
90
TreeNode: The detached node/subtree
91
"""
92
```
93
94
### Tree Traversal and Access
95
96
Navigate through tree structures using different traversal strategies and access specific nodes.
97
98
```python { .api }
99
def traverse(self, strategy="levelorder", is_leaf_fn=None):
100
"""
101
Iterate over tree nodes using specified strategy.
102
103
Parameters:
104
- strategy (str): Traversal strategy ("preorder", "postorder", "levelorder")
105
- is_leaf_fn (function): Custom function to determine leaf nodes
106
107
Yields:
108
TreeNode: Each node in traversal order
109
"""
110
111
def get_leaves(self, is_leaf_fn=None):
112
"""
113
Get all leaf nodes.
114
115
Parameters:
116
- is_leaf_fn (function): Custom function to determine leaf status
117
118
Returns:
119
list: List of leaf TreeNode objects
120
"""
121
122
def get_descendants(self, strategy="levelorder"):
123
"""
124
Get all descendant nodes.
125
126
Parameters:
127
- strategy (str): Traversal strategy
128
129
Returns:
130
list: List of descendant TreeNode objects
131
"""
132
133
def get_ancestors(self):
134
"""
135
Get all ancestor nodes from current node to root.
136
137
Returns:
138
list: List of ancestor TreeNode objects
139
"""
140
141
def get_common_ancestor(self, *target_nodes):
142
"""
143
Find most recent common ancestor of target nodes.
144
145
Parameters:
146
- target_nodes: Variable number of TreeNode objects
147
148
Returns:
149
TreeNode: Common ancestor node
150
"""
151
152
def get_sisters(self):
153
"""
154
Get sister nodes (same parent, excluding self).
155
156
Returns:
157
list: List of sister TreeNode objects
158
"""
159
```
160
161
### Node Properties and Attributes
162
163
Access and modify node properties including names, distances, and custom attributes.
164
165
```python { .api }
166
# Core Properties
167
name: str # Node name
168
dist: float # Branch length/distance to parent
169
support: float # Support value for branch
170
up: TreeNode # Parent node
171
children: list # List of child nodes
172
173
def add_feature(self, pr_name, pr_value):
174
"""
175
Add custom attribute to node.
176
177
Parameters:
178
- pr_name (str): Attribute name
179
- pr_value: Attribute value
180
"""
181
182
def del_feature(self, pr_name):
183
"""
184
Delete custom attribute from node.
185
186
Parameters:
187
- pr_name (str): Attribute name to delete
188
"""
189
```
190
191
### Tree Topology Analysis
192
193
Analyze tree structure and relationships between nodes.
194
195
```python { .api }
196
def is_leaf(self):
197
"""
198
Check if node is a leaf (has no children).
199
200
Returns:
201
bool: True if node is leaf
202
"""
203
204
def is_root(self):
205
"""
206
Check if node is root (has no parent).
207
208
Returns:
209
bool: True if node is root
210
"""
211
212
def get_tree_root(self):
213
"""
214
Get root node of the tree.
215
216
Returns:
217
TreeNode: Root node
218
"""
219
220
def get_distance(self, target, topology_only=False):
221
"""
222
Calculate distance to target node.
223
224
Parameters:
225
- target (TreeNode): Target node
226
- topology_only (bool): Count only nodes, ignore branch lengths
227
228
Returns:
229
float: Distance to target
230
"""
231
232
def get_closest_leaf(self, topology_only=False):
233
"""
234
Find closest leaf node.
235
236
Parameters:
237
- topology_only (bool): Ignore branch lengths
238
239
Returns:
240
tuple: (TreeNode, distance) of closest leaf
241
"""
242
243
def get_farthest_leaf(self, topology_only=False):
244
"""
245
Find farthest leaf node.
246
247
Parameters:
248
- topology_only (bool): Ignore branch lengths
249
250
Returns:
251
tuple: (TreeNode, distance) of farthest leaf
252
"""
253
```
254
255
### Tree Modification and Restructuring
256
257
Modify tree topology and structure through rooting, pruning, and other operations.
258
259
```python { .api }
260
def set_outgroup(self, outgroup):
261
"""
262
Root tree using specified outgroup.
263
264
Parameters:
265
- outgroup (TreeNode or list): Outgroup node(s)
266
267
Returns:
268
TreeNode: New root node
269
"""
270
271
def unroot(self):
272
"""
273
Remove root by creating multifurcation at root.
274
"""
275
276
def prune(self, nodes, preserve_branch_length=False):
277
"""
278
Remove specified nodes from tree.
279
280
Parameters:
281
- nodes (list): Nodes to remove
282
- preserve_branch_length (bool): Preserve branch lengths
283
"""
284
285
def ladderize(self, direction=0):
286
"""
287
Sort tree for ladder-like appearance.
288
289
Parameters:
290
- direction (int): 0 for ascending, 1 for descending
291
"""
292
293
def resolve_polytomy(self, default_dist=0.0, default_support=0.0):
294
"""
295
Resolve polytomies by adding internal nodes.
296
297
Parameters:
298
- default_dist (float): Default branch length for new branches
299
- default_support (float): Default support for new branches
300
"""
301
302
def sort_descendants(self, attr="name"):
303
"""
304
Sort descendants by attribute.
305
306
Parameters:
307
- attr (str): Attribute name to sort by
308
"""
309
310
def standardize(self):
311
"""
312
Standardize tree structure (ladderize + sort).
313
"""
314
315
def swap_children(self):
316
"""
317
Swap positions of child nodes.
318
"""
319
```
320
321
### Tree Copying and Serialization
322
323
Create copies of trees and export to various formats.
324
325
```python { .api }
326
def copy(self, method="cpickle"):
327
"""
328
Create copy of tree.
329
330
Parameters:
331
- method (str): Copy method ("cpickle", "deepcopy")
332
333
Returns:
334
TreeNode: Copied tree
335
"""
336
337
def write(self, features=None, outdir=None, format=0, is_leaf_fn=None):
338
"""
339
Export tree to Newick format.
340
341
Parameters:
342
- features (list): Node features to include
343
- outdir (str): Output directory
344
- format (int): Newick format (0-9)
345
- is_leaf_fn (function): Custom leaf detection function
346
347
Returns:
348
str: Newick representation
349
"""
350
```
351
352
### Node Search and Filtering
353
354
Search for nodes based on attributes and conditions.
355
356
```python { .api }
357
def search_nodes(self, **conditions):
358
"""
359
Search for nodes matching conditions.
360
361
Parameters:
362
- conditions: Keyword arguments for attribute matching
363
364
Returns:
365
list: Matching TreeNode objects
366
"""
367
368
def iter_search_nodes(self, **conditions):
369
"""
370
Iterator version of search_nodes.
371
372
Parameters:
373
- conditions: Keyword arguments for attribute matching
374
375
Yields:
376
TreeNode: Each matching node
377
"""
378
379
def get_leaf_names(self):
380
"""
381
Get names of all leaf nodes.
382
383
Returns:
384
list: List of leaf names
385
"""
386
```
387
388
### Tree Validation and Utility
389
390
Utility functions for tree validation and manipulation.
391
392
```python { .api }
393
def populate(self, size, names_library=None, reuse_names=True):
394
"""
395
Populate tree with random topology.
396
397
Parameters:
398
- size (int): Number of leaf nodes
399
- names_library (list): Names to use for nodes
400
- reuse_names (bool): Allow name reuse
401
402
Returns:
403
TreeNode: Populated tree
404
"""
405
406
def get_cached_content(self, store_attr=None):
407
"""
408
Get cached tree content for performance.
409
410
Parameters:
411
- store_attr (str): Attribute to cache
412
413
Returns:
414
dict: Cached content
415
"""
416
```
417
418
## Tree Error Handling
419
420
```python { .api }
421
class TreeError(Exception):
422
"""Exception raised for tree operation errors."""
423
pass
424
```
425
426
## Usage Examples
427
428
### Basic Tree Operations
429
430
```python
431
from ete3 import Tree
432
433
# Create tree from Newick string
434
t = Tree("(A:1,(B:1,(E:1,D:1):0.5):0.5);")
435
436
# Basic properties
437
print(f"Tree size: {len(t)}")
438
print(f"Is leaf: {t.is_leaf()}")
439
print(f"Children: {len(t.children)}")
440
441
# Traverse tree
442
for node in t.traverse("postorder"):
443
print(f"Node {node.name}: {node.dist}")
444
445
# Find specific nodes
446
leaves = t.get_leaves()
447
ancestors = t.get_ancestors()
448
449
# Modify tree
450
child = t.add_child(name="F", dist=0.8)
451
t.remove_child(child)
452
```
453
454
### Tree Manipulation
455
456
```python
457
# Root tree with outgroup
458
t.set_outgroup(t&"A") # & operator for node access
459
460
# Prune nodes
461
t.prune([t&"B", t&"C"])
462
463
# Copy tree
464
t2 = t.copy()
465
466
# Export to Newick
467
newick_str = t.write(format=1)
468
```