Source: https://github.com/aipoch/medical-research-skills
When to Use
- Preprocess phylogenetic trees: convert formats (Newick/NHX/PhyloXML), reroot (midpoint/outgroup), prune taxa, and resolve polytomies before downstream analyses.
- Detect evolutionary events in gene trees: infer duplication vs. speciation events and derive ortholog/paralog relationships for phylogenomics.
- Annotate trees with taxonomy: map species names to NCBI TaxIDs, retrieve lineages/ranks, and build minimal taxonomy topologies connecting a set of taxa.
- Generate publication-quality visualizations: render trees to PDF/SVG/PNG with custom styles, support-based coloring, and node “faces” (labels, shapes, heatmaps).
- Compare alternative topologies: quantify differences between trees using Robinson–Foulds (RF) distance and partition/bipartition analysis.
Key Features
- Tree I/O and manipulation
- Read/write: Newick, NHX, PhyloXML, NeXML
- Traversals: preorder, postorder, levelorder
- Operations: prune, reroot, collapse, resolve polytomies
- Metrics: branch/topological distances, RF distance
- Phylogenetic (gene tree) analysis
- Alignment association (FASTA/Phylip)
- Species name extraction from gene IDs
- Duplication/speciation detection (e.g., species overlap / reconciliation-style workflows)
- Orthology/paralogy extraction and gene-family splitting
- NCBI taxonomy integration
- Auto-download + local cache of taxonomy DB
- TaxID ↔ scientific name translation
- Lineage/rank retrieval and taxonomy-based topology building
- Tree annotation with taxonomic metadata
- Visualization
- Rectangular/circular layouts, GUI exploration
- NodeStyle/TreeStyle customization
- Faces (text, shapes, charts/heatmaps) and layout functions
- Export to PDF/SVG/PNG
- Clustering support
- ClusterTree for dendrograms linked to numeric matrices
- Cluster quality metrics (e.g., silhouette, Dunn index)
- Heatmap + tree combined views
Dependencies
ete3 (recommended: >=3.1.0)
- Optional GUI/rendering dependencies (platform-specific):
PyQt5 (e.g., >=5.15)
- Qt SVG support (often packaged as
python3-pyqt5.qtsvg on Debian/Ubuntu)
Example Usage
The following example is designed to be runnable end-to-end (it uses an in-memory Newick string and does not require external files).
# pip install ete3
from ete3 import Tree, TreeStyle, NodeStyle
# 1) Load a tree (Newick)
nw = "((A:0.1,B:0.2)90:0.3,(C:0.2,D:0.4)70:0.1);"
t = Tree(nw, format=1)
# 2) Basic stats
print("Leaves:", len(t))
print("Total nodes:", sum(1 for _ in t.traverse()))
# 3) Midpoint rooting
mid = t.get_midpoint_outgroup()
t.set_outgroup(mid)
# 4) Prune to taxa of interest (preserve branch lengths)
t.prune(["A", "C", "D"], preserve_branch_length=True)
# 5) Style nodes (color internal nodes by support)
ts = TreeStyle()
ts.show_leaf_name = True
ts.show_branch_support = True
for n in t.traverse():
st = NodeStyle()
if n.is_leaf():
st["fgcolor"] = "blue"
st["size"] = 8
else:
# ETE stores internal support in n.support when present
st["fgcolor"] = "darkgreen" if getattr(n, "support", 0) >= 80 else "red"
st["size"] = 5
n.set_style(st)
# 6) Render (PDF/SVG/PNG supported depending on your environment)
t.render("example_tree.pdf", tree_style=ts)
print("Wrote: example_tree.pdf")
Implementation Details
Tree parsing formats (Newick “format” codes)
ETE uses a format integer to control how node attributes are interpreted when reading/writing Newick. Common patterns:
format=0: flexible default (often includes branch lengths)
format=1: includes internal node names
format=2: includes support/bootstrap values
format=5: internal node names + branch lengths
format=8: name + distance + support (maximal common usage)
format=9: leaf names only
format=100: topology only
Example:
from ete3 import Tree
t = Tree("tree.nw", format=1)
t.write(outfile="out.nw", format=5)
NHX feature preservation
NHX is used to store custom per-node features. When writing, specify which features to serialize:
t.write(outfile="tree.nhx", features=["taxid", "habitat", "lineage"])
Rerooting and pruning behavior
- Midpoint rooting uses
get_midpoint_outgroup() to select an outgroup that balances path lengths.
- Pruning should typically use
preserve_branch_length=True to avoid distorting distances in phylogenetic contexts.
Evolutionary event detection (gene trees)
For gene trees, PhyloTree supports event labeling on internal nodes (commonly:
evoltype == "D" for duplication
evoltype == "S" for speciation)
A typical workflow is:
- Load a gene tree (optionally with an alignment).
- Provide a species naming function to map gene IDs → species.
- Run descendant event detection.
- Extract ortholog groups (speciation subtrees) or query ortholog/paralog sets from events.
Tree comparison (Robinson–Foulds)
Tree.robinson_foulds(other_tree) returns:
rf: RF distance (number of differing bipartitions)
max_rf: maximum possible RF given shared leaves
- plus shared leaves and partition sets for deeper inspection
Normalized RF is typically computed as rf / max_rf (when max_rf > 0).
1---2name: etetoolkit3description: ETE (Environment for Tree Exploration) toolkit for phylogenetic and hierarchical tree analysis; use it when you need to parse/manipulate Newick/NHX trees, detect duplication/speciation events, integrate NCBI taxonomy, and render publication-quality figures.4license: MIT5---6> **Source**: [https://github.com/aipoch/medical-research-skills](https://github.com/aipoch/medical-research-skills)78## When to Use910- **Preprocess phylogenetic trees**: convert formats (Newick/NHX/PhyloXML), reroot (midpoint/outgroup), prune taxa, and resolve polytomies before downstream analyses.11- **Detect evolutionary events in gene trees**: infer **duplication vs. speciation** events and derive **ortholog/paralog** relationships for phylogenomics.12- **Annotate trees with taxonomy**: map species names to **NCBI TaxIDs**, retrieve lineages/ranks, and build minimal taxonomy topologies connecting a set of taxa.13- **Generate publication-quality visualizations**: render trees to **PDF/SVG/PNG** with custom styles, support-based coloring, and node “faces” (labels, shapes, heatmaps).14- **Compare alternative topologies**: quantify differences between trees using **Robinson–Foulds (RF)** distance and partition/bipartition analysis.1516## Key Features1718- **Tree I/O and manipulation**19 - Read/write: Newick, NHX, PhyloXML, NeXML20 - Traversals: preorder, postorder, levelorder21 - Operations: prune, reroot, collapse, resolve polytomies22 - Metrics: branch/topological distances, RF distance23- **Phylogenetic (gene tree) analysis**24 - Alignment association (FASTA/Phylip)25 - Species name extraction from gene IDs26 - Duplication/speciation detection (e.g., species overlap / reconciliation-style workflows)27 - Orthology/paralogy extraction and gene-family splitting28- **NCBI taxonomy integration**29 - Auto-download + local cache of taxonomy DB30 - TaxID ↔ scientific name translation31 - Lineage/rank retrieval and taxonomy-based topology building32 - Tree annotation with taxonomic metadata33- **Visualization**34 - Rectangular/circular layouts, GUI exploration35 - NodeStyle/TreeStyle customization36 - Faces (text, shapes, charts/heatmaps) and layout functions37 - Export to PDF/SVG/PNG38- **Clustering support**39 - ClusterTree for dendrograms linked to numeric matrices40 - Cluster quality metrics (e.g., silhouette, Dunn index)41 - Heatmap + tree combined views4243## Dependencies4445- `ete3` (recommended: `>=3.1.0`)46- Optional GUI/rendering dependencies (platform-specific):47 - `PyQt5` (e.g., `>=5.15`)48 - Qt SVG support (often packaged as `python3-pyqt5.qtsvg` on Debian/Ubuntu)4950## Example Usage5152The following example is designed to be runnable end-to-end (it uses an in-memory Newick string and does not require external files).5354```python55# pip install ete35657from ete3 import Tree, TreeStyle, NodeStyle5859# 1) Load a tree (Newick)60nw = "((A:0.1,B:0.2)90:0.3,(C:0.2,D:0.4)70:0.1);"61t = Tree(nw, format=1)6263# 2) Basic stats64print("Leaves:", len(t))65print("Total nodes:", sum(1 for _ in t.traverse()))6667# 3) Midpoint rooting68mid = t.get_midpoint_outgroup()69t.set_outgroup(mid)7071# 4) Prune to taxa of interest (preserve branch lengths)72t.prune(["A", "C", "D"], preserve_branch_length=True)7374# 5) Style nodes (color internal nodes by support)75ts = TreeStyle()76ts.show_leaf_name = True77ts.show_branch_support = True7879for n in t.traverse():80 st = NodeStyle()81 if n.is_leaf():82 st["fgcolor"] = "blue"83 st["size"] = 884 else:85 # ETE stores internal support in n.support when present86 st["fgcolor"] = "darkgreen" if getattr(n, "support", 0) >= 80 else "red"87 st["size"] = 588 n.set_style(st)8990# 6) Render (PDF/SVG/PNG supported depending on your environment)91t.render("example_tree.pdf", tree_style=ts)92print("Wrote: example_tree.pdf")93```9495## Implementation Details9697### Tree parsing formats (Newick “format” codes)98ETE uses a `format` integer to control how node attributes are interpreted when reading/writing Newick. Common patterns:99100- `format=0`: flexible default (often includes branch lengths)101- `format=1`: includes internal node names102- `format=2`: includes support/bootstrap values103- `format=5`: internal node names + branch lengths104- `format=8`: name + distance + support (maximal common usage)105- `format=9`: leaf names only106- `format=100`: topology only107108Example:109110```python111from ete3 import Tree112113t = Tree("tree.nw", format=1)114t.write(outfile="out.nw", format=5)115```116117### NHX feature preservation118NHX is used to store custom per-node features. When writing, specify which features to serialize:119120```python121t.write(outfile="tree.nhx", features=["taxid", "habitat", "lineage"])122```123124### Rerooting and pruning behavior125- **Midpoint rooting** uses `get_midpoint_outgroup()` to select an outgroup that balances path lengths.126- **Pruning** should typically use `preserve_branch_length=True` to avoid distorting distances in phylogenetic contexts.127128### Evolutionary event detection (gene trees)129For gene trees, `PhyloTree` supports event labeling on internal nodes (commonly:130- `evoltype == "D"` for duplication131- `evoltype == "S"` for speciation)132133A typical workflow is:1341. Load a gene tree (optionally with an alignment).1352. Provide a **species naming function** to map gene IDs → species.1363. Run descendant event detection.1374. Extract ortholog groups (speciation subtrees) or query ortholog/paralog sets from events.138139### Tree comparison (Robinson–Foulds)140`Tree.robinson_foulds(other_tree)` returns:141- `rf`: RF distance (number of differing bipartitions)142- `max_rf`: maximum possible RF given shared leaves143- plus shared leaves and partition sets for deeper inspection144145Normalized RF is typically computed as `rf / max_rf` (when `max_rf > 0`).