mcpField
E
etetoolkit

etetoolkit

github.com/jackspace数据与数据库1636 次安装12 周前更新
代码仓库

关于 etetoolkit

etetoolkit 是用于系统发育和层级树分析的工具包,面向生物信息学研究者。它结合树操作、进化事件分析、NCBI 分类信息和可视化,也支持聚类分析及树比较。

主要功能

  1. 01读取、编辑和转换多种树格式
  2. 02检测复制与物种形成事件
  3. 03识别直系同源与旁系同源基因
  4. 04整合 NCBI 分类信息
  5. 05生成树图并比较树拓扑
  6. 06分析聚类并绘制热图

适用场景

  1. 01整理和修剪系统发育树
  2. 02从基因树识别直系同源基因
  3. 03为树添加分类谱系信息
  4. 04比较多棵树或展示聚类结果

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/jackspace/claudeskillz --skill etetoolkit

安装后在 Claude Code 中输入/etetoolkit确认已加载。

附带文件SKILL.json

详细介绍

ETE Toolkit 技能

概述

ETE(Environment for Tree Exploration,树探索环境)是一款用于系统发育和层次树分析的工具包。它支持操作树、分析进化事件、可视化结果,并与生物数据库集成,适用于系统基因组学研究和聚类分析。

核心功能

1. 树操作与分析

加载、操作和分析层次树结构,支持:

  • 树的输入/输出:读取和写入 Newick、NHX、PhyloXML 和 NeXML 格式
  • 树遍历:使用前序、后序或层序策略遍历树
  • 拓扑修改:剪枝、设定根节点、折叠节点、解析多分叉
  • 距离计算:计算节点之间的分支长度和拓扑距离
  • 树比较:计算 Robinson-Foulds 距离并识别拓扑差异

常见模式:

from ete3 import Tree

# Load tree from file
tree = Tree("tree.nw", format=1)

# Basic statistics
print(f"Leaves: {len(tree)}")
print(f"Total nodes: {len(list(tree.traverse()))}")

# Prune to taxa of interest
taxa_to_keep = ["species1", "species2", "species3"]
tree.prune(taxa_to_keep, preserve_branch_length=True)

# Midpoint root
midpoint = tree.get_midpoint_outgroup()
tree.set_outgroup(midpoint)

# Save modified tree
tree.write(outfile="rooted_tree.nw")

使用 scripts/tree_operations.py 从命令行操作树:

# Display tree statistics
python scripts/tree_operations.py stats tree.nw

# Convert format
python scripts/tree_operations.py convert tree.nw output.nw --in-format 0 --out-format 1

# Reroot tree
python scripts/tree_operations.py reroot tree.nw rooted.nw --midpoint

# Prune to specific taxa
python scripts/tree_operations.py prune tree.nw pruned.nw --keep-taxa "sp1,sp2,sp3"

# Show ASCII visualization
python scripts/tree_operations.py ascii tree.nw
2. 系统发育分析

通过检测进化事件分析基因树:

  • 序列比对集成:将树与多序列比对(FASTA、Phylip)关联
  • 物种命名:自动从基因名称提取物种,或自定义提取方式
  • 进化事件:使用物种重叠或树重建检测复制和物种形成事件
  • 直系同源关系检测:根据进化事件识别直系同源基因和旁系同源基因
  • 基因家族分析:按复制事件拆分树,折叠谱系特异性扩增

基因树分析工作流:

from ete3 import PhyloTree

# Load gene tree with alignment
tree = PhyloTree("gene_tree.nw", alignment="alignment.fasta")

# Set species naming function
def get_species(gene_name):
    return gene_name.split("_")[0]

tree.set_species_naming_function(get_species)

# Detect evolutionary events
events = tree.get_descendant_evol_events()

# Analyze events
for node in tree.traverse():
    if hasattr(node, "evoltype"):
        if node.evoltype == "D":
            print(f"Duplication at {node.name}")
        elif node.evoltype == "S":
            print(f"Speciation at {node.name}")

# Extract ortholog groups
ortho_groups = tree.get_speciation_trees()
for i, ortho_tree in enumerate(ortho_groups):
    ortho_tree.write(outfile=f"ortholog_group_{i}.nw")

查找直系同源基因和旁系同源基因:

# Find orthologs to query gene
query = tree & "species1_gene1"

orthologs = []
paralogs = []

for event in events:
    if query in event.in_seqs:
        if event.etype == "S":
            orthologs.extend([s for s in event.out_seqs if s != query])
        elif event.etype == "D":
            paralogs.extend([s for s in event.out_seqs if s != query])
3. NCBI 分类数据库集成

集成 NCBI 分类数据库中的分类信息:

  • 数据库访问:自动下载 NCBI 分类数据库并缓存到本地(约 300MB)
  • Taxid/名称转换:在分类 ID 和学名之间进行转换
  • 谱系检索:获取完整的进化谱系
  • 分类树:构建连接指定分类单元的物种树
  • 树注释:自动为树添加分类信息注释

构建基于分类信息的树:

from ete3 import NCBITaxa

ncbi = NCBITaxa()

# Build tree from species names
species = ["Homo sapiens", "Pan troglodytes", "Mus musculus"]
name2taxid = ncbi.get_name_translator(species)
taxids = [name2taxid[sp][0] for sp in species]

# Get minimal tree connecting taxa
tree = ncbi.get_topology(taxids)

# Annotate nodes with taxonomy info
for node in tree.traverse():
    if hasattr(node, "sci_name"):
        print(f"{node.sci_name} - Rank: {node.rank} - TaxID: {node.taxid}")

为现有树添加注释:

# Get taxonomy info for tree leaves
for leaf in tree:
    species = extract_species_from_name(leaf.name)
    taxid = ncbi.get_name_translator([species])[species][0]

    # Get lineage
    lineage = ncbi.get_lineage(taxid)
    ranks = ncbi.get_rank(lineage)
    names = ncbi.get_taxid_translator(lineage)

    # Add to node
    leaf.add_feature("taxid", taxid)
    leaf.add_feature("lineage", [names[t] for t in lineage])
4. 树可视化

创建适用于出版物的高质量树可视化图:

  • 输出格式:用于出版物的 PNG(栅格)、PDF 和 SVG(矢量)格式
  • 布局模式:矩形和圆形树布局
  • 交互式 GUI:通过缩放、平移和搜索交互式探索树
  • 自定义样式:使用 NodeStyle 设置节点外观(颜色、形状、大小)
  • 图形元素:向节点添加图形元素(文本、图像、图表、热图)
  • 布局函数:根据节点属性动态设置样式

基本可视化工作流:

from ete3 import Tree, TreeStyle, NodeStyle

tree = Tree("tree.nw")

# Configure tree style
ts = TreeStyle()
ts.show_leaf_name = True
ts.show_branch_support = True
ts.scale = 50  # pixels per branch length unit

# Style nodes
for node in tree.traverse():
    nstyle = NodeStyle()

    if node.is_leaf():
        nstyle["fgcolor"] = "blue"
        nstyle["size"] = 8
    else:
        # Color by support
        if node.support > 0.9:
            nstyle["fgcolor"] = "darkgreen"
        else:
            nstyle["fgcolor"] = "red"
        nstyle["size"] = 5

    node.set_style(nstyle)

# Render to file
tree.render("tree.pdf", tree_style=ts)
tree.render("tree.png", w=800, h=600, units="px", dpi=300)

使用 scripts/quick_visualize.py 快速生成可视化图:

# Basic visualization
python scripts/quick_visualize.py tree.nw output.pdf

# Circular layout with custom styling
python scripts/quick_visualize.py tree.nw output.pdf --mode c --color-by-support

# High-resolution PNG
python scripts/quick_visualize.py tree.nw output.png --width 1200 --height 800 --units px --dpi 300

# Custom title and styling
python scripts/quick_visualize.py tree.nw output.pdf --title "Species Phylogeny" --show-support

使用图形元素进行高级可视化:

from ete3 import Tree, TreeStyle, TextFace, CircleFace

tree = Tree("tree.nw")

# Add features to nodes
for leaf in tree:
    leaf.add_feature("habitat", "marine" if "fish" in leaf.name else "land")

# Layout function
def layout(node):
    if node.is_leaf():
        # Add colored circle
        color = "blue" if node.habitat == "marine" else "green"
        circle = CircleFace(radius=5, color=color)
        node.add_face(circle, column=0, position="aligned")

        # Add label
        label = TextFace(node.name, fsize=10)
        node.add_face(label, column=1, position="aligned")

ts = TreeStyle()
ts.layout_fn = layout
ts.show_leaf_name = False

tree.render("annotated_tree.pdf", tree_style=ts)
5. 聚类分析

结合数据分析层次聚类结果:

  • ClusterTree:专用于聚类树状图的类
  • 数据矩阵关联:将树叶与数值特征关联
  • 聚类指标:轮廓系数、Dunn 指数、簇间/簇内距离
  • 验证:使用不同距离指标测试聚类质量
  • 热图可视化:在树旁显示数据矩阵

聚类工作流:

from ete3 import ClusterTree

# Load tree with data matrix
matrix = """#Names\tSample1\tSample2\tSample3
Gene1\t1.5\t2.3\t0.8
Gene2\t0.9\t1.1\t1.8
Gene3\t2.1\t2.5\t0.5"""

tree = ClusterTree("((Gene1,Gene2),Gene3);", text_array=matrix)

# Evaluate cluster quality
for node in tree.traverse():
    if not node.is_leaf():
        silhouette = node.get_silhouette()
        dunn = node.get_dunn()

        print(f"Cluster: {node.name}")
        print(f"  Silhouette: {silhouette:.3f}")
        print(f"  Dunn index: {dunn:.3f}")

# Visualize with heatmap
tree.show("heatmap")
6. 树比较

量化树之间的拓扑差异:

  • Robinson-Foulds 距离:树比较的标准指标
  • 标准化 RF:与尺度无关的距离(0.0 至 1.0)
  • 划分分析:识别独有和共有的二分划分
  • 共识树:分析多棵树的支持情况
  • 批量比较:两两比较多棵树

比较两棵树:

from ete3 import Tree

tree1 = Tree("tree1.nw")
tree2 = Tree("tree2.nw")

# Calculate RF distance
rf, max_rf, common_leaves, parts_t1, parts_t2 = tree1.robinson_foulds(tree2)

print(f"RF distance: {rf}/{max_rf}")
print(f"Normalized RF: {rf/max_rf:.3f}")
print(f"Common leaves: {len(common_leaves)}")

# Find unique partitions
unique_t1 = parts_t1 - parts_t2
unique_t2 = parts_t2 - parts_t1

print(f"Unique to tree1: {len(unique_t1)}")
print(f"Unique to tree2: {len(unique_t2)}")

比较多棵树:

import numpy as np

trees = [Tree(f"tree{i}.nw") for i in range(4)]

# Create distance matrix
n = len(trees)
dist_matrix = np.zeros((n, n))

for i in range(n):
    for j in range(i+1, n):
        rf, max_rf, _, _, _ = trees[i].robinson_foulds(trees[j])
        norm_rf = rf / max_rf if max_rf > 0 else 0
        dist_matrix[i, j] = norm_rf
        dist_matrix[j, i] = norm_rf

安装和设置

安装 ETE 工具包:

# Basic installation
pip install ete3

# With external dependencies for rendering (optional but recommended)
# On macOS:
brew install qt@5

# On Ubuntu/Debian:
sudo apt-get install python3-pyqt5 python3-pyqt5.qtsvg

# For full features including GUI
pip install ete3[gui]

首次设置 NCBI Taxonomy:

首次实例化 NCBITaxa 时,它会自动将 NCBI taxonomy 数据库(约 300MB)下载到 ~/.etetoolkit/taxa.sqlite。此操作只会执行一次:

from ete3 import NCBITaxa
ncbi = NCBITaxa()  # Downloads database on first run

更新 taxonomy 数据库:

ncbi.update_taxonomy_database()  # Download latest NCBI data

常见用例

用例 1:系统基因组学工作流

从基因树到直系同源基因识别的完整工作流:

from ete3 import PhyloTree, NCBITaxa

# 1. Load gene tree with alignment
tree = PhyloTree("gene_tree.nw", alignment="alignment.fasta")

# 2. Configure species naming
tree.set_species_naming_function(lambda x: x.split("_")[0])

# 3. Detect evolutionary events
tree.get_descendant_evol_events()

# 4. Annotate with taxonomy
ncbi = NCBITaxa()
for leaf in tree:
    if leaf.species in species_to_taxid:
        taxid = species_to_taxid[leaf.species]
        lineage = ncbi.get_lineage(taxid)
        leaf.add_feature("lineage", lineage)

# 5. Extract ortholog groups
ortho_groups = tree.get_speciation_trees()

# 6. Save and visualize
for i, ortho in enumerate(ortho_groups):
    ortho.write(outfile=f"ortho_{i}.nw")
用例 2:树预处理和格式化

批量处理树以供分析:

# Convert format
python scripts/tree_operations.py convert input.nw output.nw --in-format 0 --out-format 1

# Root at midpoint
python scripts/tree_operations.py reroot input.nw rooted.nw --midpoint

# Prune to focal taxa
python scripts/tree_operations.py prune rooted.nw pruned.nw --keep-taxa taxa_list.txt

# Get statistics
python scripts/tree_operations.py stats pruned.nw
用例 3:出版级图表

创建经过样式设计的可视化图表:

from ete3 import Tree, TreeStyle, NodeStyle, TextFace

tree = Tree("tree.nw")

# Define clade colors
clade_colors = {
    "Mammals": "red",
    "Birds": "blue",
    "Fish": "green"
}

def layout(node):
    # Highlight clades
    if node.is_leaf():
        for clade, color in clade_colors.items():
            if clade in node.name:
                nstyle = NodeStyle()
                nstyle["fgcolor"] = color
                nstyle["size"] = 8
                node.set_style(nstyle)
    else:
        # Add support values
        if node.support > 0.95:
            support = TextFace(f"{node.support:.2f}", fsize=8)
            node.add_face(support, column=0, position="branch-top")

ts = TreeStyle()
ts.layout_fn = layout
ts.show_scale = True

# Render for publication
tree.render("figure.pdf", w=200, units="mm", tree_style=ts)
tree.render("figure.svg", tree_style=ts)  # Editable vector
用例 4:自动化树分析

系统地处理多棵树:

from ete3 import Tree
import os

input_dir = "trees"
output_dir = "processed"

for filename in os.listdir(input_dir):
    if filename.endswith(".nw"):
        tree = Tree(os.path.join(input_dir, filename))

        # Standardize: midpoint root, resolve polytomies
        midpoint = tree.get_midpoint_outgroup()
        tree.set_outgroup(midpoint)
        tree.resolve_polytomy(recursive=True)

        # Filter low support branches
        for node in tree.traverse():
            if hasattr(node, 'support') and node.support < 0.5:
                if not node.is_leaf() and not node.is_root():
                    node.delete()

        # Save processed tree
        output_file = os.path.join(output_dir, f"processed_{filename}")
        tree.write(outfile=output_file)

参考文档

如需完整的 API 文档、代码示例和详细指南,请参阅 references/ 目录中的以下资源:

  • api_reference.md:所有 ETE 类和方法(Tree、PhyloTree、ClusterTree、NCBITaxa)的完整 API 文档,包括参数、返回类型和代码示例
  • workflows.md:按任务分类的常见工作流模式(树操作、系统发育分析、树比较、taxonomy 集成、聚类分析)
  • visualization.md:全面的可视化指南,涵盖 TreeStyle、NodeStyle、Faces、布局函数和高级可视化技术

需要详细信息时,请加载这些参考资料:

# To use API reference
# Read references/api_reference.md for complete method signatures and parameters

# To implement workflows
# Read references/workflows.md for step-by-step workflow examples

# To create visualizations
# Read references/visualization.md for styling and rendering options

故障排除

导入错误:

# If "ModuleNotFoundError: No module named 'ete3'"
pip install ete3

# For GUI and rendering issues
pip install ete3[gui]

渲染问题:

如果 tree.render() 或 tree.show() 因 Qt 相关错误而失败,请安装系统依赖项:

# macOS
brew install qt@5

# Ubuntu/Debian
sudo apt-get install python3-pyqt5 python3-pyqt5.qtsvg

NCBI Taxonomy 数据库:

如果数据库下载失败或损坏:

from ete3 import NCBITaxa
ncbi = NCBITaxa()
ncbi.update_taxonomy_database()  # Redownload database

大树的内存问题:

对于非常大的树(>10,000 个叶节点),请使用迭代器,而不要使用列表推导式:

# Memory-efficient iteration
for leaf in tree.iter_leaves():
    process(leaf)

# Instead of
for leaf in tree.get_leaves():  # Loads all into memory
    process(leaf)

Newick 格式参考

ETE 支持多种 Newick 格式规范(0-100):

  • 格式 0:灵活,包含分支长度(默认)
  • 格式 1:包含内部节点名称
  • 格式 2:包含 bootstrap/支持值
  • 格式 5:内部节点名称 + 分支长度
  • 格式 8:包含所有特性(名称、距离、支持值)
  • 格式 9:仅叶节点名称
  • 格式 100:仅拓扑结构

读写时指定格式:

tree = Tree("tree.nw", format=1)
tree.write(outfile="output.nw", format=5)

NHX(New Hampshire eXtended)格式可保留自定义特性:

tree.write(outfile="tree.nhx", features=["habitat", "temperature", "depth"])

最佳实践

  1. 保留分支长度:在系统发育分析中进行剪枝时,使用 preserve_branch_length=True
  2. 缓存内容:对于大型树上节点内容的重复访问,使用 get_cached_content()
  3. 使用迭代器:使用 iter_* 方法,以节省内存地处理大型树
  4. 选择合适的遍历方式:自底向上分析使用后序遍历,自顶向下分析使用前序遍历
  5. 验证单系性:始终检查返回的分支类型(单系、并系或多系)
  6. 用于出版的矢量格式:出版图表使用 PDF 或 SVG(可缩放、可编辑)
  7. 交互式测试:先使用 tree.show() 测试可视化效果,再渲染到文件
  8. 系统发育分析使用 PhyloTree:对基因树和进化分析使用 PhyloTree 类
  9. 选择复制方法:追求速度时使用 "newick",追求完整保真时使用 "cpickle",处理复杂对象时使用 "deepcopy"
  10. 缓存 NCBI 查询:存储 NCBI taxonomy 查询结果,以避免重复访问数据库

评论

支持 Markdown