名称: etetoolkit 描述: “系统发育树工具包(ETE)。树操作(Newick/NHX),进化事件检测,直系同源/旁系同源分析,NCBI分类学,可视化(PDF/SVG),用于系统发育基因组学。”
ETE工具包技能
概述
ETE(环境用于树探索)是一个用于系统发育和层次树分析的工具包。操作树、分析进化事件、可视化结果,并集成生物数据库,用于系统发育基因组学研究和聚类分析。
核心功能
1. 树操作和分析
加载、操作和分析层次树结构,支持:
- 树输入/输出:读取和写入Newick、NHX、PhyloXML和NeXML格式
- 树遍历:使用前序、后序或层次顺序策略导航树
- 拓扑修改:修剪、根定、折叠节点,解析多分支
- 距离计算:计算分支长度和节点间的拓扑距离
- 树比较:计算Robinson-Foulds距离并识别拓扑差异
常见模式:
from ete3 import Tree
# 从文件加载树
tree = Tree("tree.nw", format=1)
# 基本统计
print(f"叶子数: {len(tree)}")
print(f"总节点数: {len(list(tree.traverse()))}")
# 修剪到感兴趣的分类单元
taxa_to_keep = ["物种1", "物种2", "物种3"]
tree.prune(taxa_to_keep, preserve_branch_length=True)
# 中点根定
midpoint = tree.get_midpoint_outgroup()
tree.set_outgroup(midpoint)
# 保存修改后的树
tree.write(outfile="rooted_tree.nw")
使用scripts/tree_operations.py进行命令行树操作:
# 显示树统计
python scripts/tree_operations.py stats tree.nw
# 转换格式
python scripts/tree_operations.py convert tree.nw output.nw --in-format 0 --out-format 1
# 重新根定树
python scripts/tree_operations.py reroot tree.nw rooted.nw --midpoint
# 修剪到特定分类单元
python scripts/tree_operations.py prune tree.nw pruned.nw --keep-taxa "sp1,sp2,sp3"
# 显示ASCII可视化
python scripts/tree_operations.py ascii tree.nw
2. 系统发育分析
分析基因树,进行进化事件检测:
- 序列对齐集成:链接树到多序列对齐(FASTA、Phylip)
- 物种命名:从基因名称自动或自定义物种提取
- 进化事件:使用物种重叠或树调和检测重复和物种形成事件
- 直系同源检测:基于进化事件识别直系同源和旁系同源
- 基因家族分析:通过重复分裂树,折叠谱系特异性扩展
基因树分析工作流:
from ete3 import PhyloTree
# 加载基因树和对齐
tree = PhyloTree("gene_tree.nw", alignment="alignment.fasta")
# 设置物种命名函数
def get_species(gene_name):
return gene_name.split("_")[0]
tree.set_species_naming_function(get_species)
# 检测进化事件
events = tree.get_descendant_evol_events()
# 分析事件
for node in tree.traverse():
if hasattr(node, "evoltype"):
if node.evoltype == "D":
print(f"重复在 {node.name}")
elif node.evoltype == "S":
print(f"物种形成在 {node.name}")
# 提取直系同源组
ortho_groups = tree.get_speciation_trees()
for i, ortho_tree in enumerate(ortho_groups):
ortho_tree.write(outfile=f"ortholog_group_{i}.nw")
查找直系同源和旁系同源:
# 查找查询基因的直系同源
query = tree & "物种1_基因1"
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()
# 从物种名称构建树
species = ["Homo sapiens", "Pan troglodytes", "Mus musculus"]
name2taxid = ncbi.get_name_translator(species)
taxids = [name2taxid[sp][0] for sp in species]
# 获取连接分类单元的最小树
tree = ncbi.get_topology(taxids)
# 用分类信息注释节点
for node in tree.traverse():
if hasattr(node, "sci_name"):
print(f"{node.sci_name} - 等级: {node.rank} - TaxID: {node.taxid}")
注释现有树:
# 获取树叶子的分类信息
for leaf in tree:
species = extract_species_from_name(leaf.name)
taxid = ncbi.get_name_translator([species])[species][0]
# 获取谱系
lineage = ncbi.get_lineage(taxid)
ranks = ncbi.get_rank(lineage)
names = ncbi.get_taxid_translator(lineage)
# 添加到节点
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")
# 配置树样式
ts = TreeStyle()
ts.show_leaf_name = True
ts.show_branch_support = True
ts.scale = 50 # 像素每分支长度单位
# 样式节点
for node in tree.traverse():
nstyle = NodeStyle()
if node.is_leaf():
nstyle["fgcolor"] = "blue"
nstyle["size"] = 8
else:
# 按支持度着色
if node.support > 0.9:
nstyle["fgcolor"] = "darkgreen"
else:
nstyle["fgcolor"] = "red"
nstyle["size"] = 5
node.set_style(nstyle)
# 渲染到文件
tree.render("tree.pdf", tree_style=ts)
tree.render("tree.png", w=800, h=600, units="px", dpi=300)
使用scripts/quick_visualize.py进行快速可视化:
# 基本可视化
python scripts/quick_visualize.py tree.nw output.pdf
# 圆形布局和自定义样式
python scripts/quick_visualize.py tree.nw output.pdf --mode c --color-by-support
# 高分辨率PNG
python scripts/quick_visualize.py tree.nw output.png --width 1200 --height 800 --units px --dpi 300
# 自定义标题和样式
python scripts/quick_visualize.py tree.nw output.pdf --title "物种系统发育" --show-support
高级可视化与面:
from ete3 import Tree, TreeStyle, TextFace, CircleFace
tree = Tree("tree.nw")
# 添加特征到节点
for leaf in tree:
leaf.add_feature("habitat", "marine" if "fish" in leaf.name else "land")
# 布局函数
def layout(node):
if node.is_leaf():
# 添加彩色圆圈
color = "blue" if node.habitat == "marine" else "green"
circle = CircleFace(radius=5, color=color)
node.add_face(circle, column=0, position="aligned")
# 添加标签
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
# 加载带数据矩阵的树
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)
# 评估聚类质量
for node in tree.traverse():
if not node.is_leaf():
silhouette = node.get_silhouette()
dunn = node.get_dunn()
print(f"聚类: {node.name}")
print(f" 轮廓: {silhouette:.3f}")
print(f" Dunn指数: {dunn:.3f}")
# 用热图可视化
tree.show("heatmap")
6. 树比较
量化树之间的拓扑差异:
- Robinson-Foulds距离:树比较的标准度量
- 归一化RF:尺度不变距离(0.0到1.0)
- 分区分析:识别唯一和共享的二分区
- 共识树:分析多个树的支持度
- 批量比较:成对比较多个树
比较两棵树:
from ete3 import Tree
tree1 = Tree("tree1.nw")
tree2 = Tree("tree2.nw")
# 计算RF距离
rf, max_rf, common_leaves, parts_t1, parts_t2 = tree1.robinson_foulds(tree2)
print(f"RF距离: {rf}/{max_rf}")
print(f"归一化RF: {rf/max_rf:.3f}")
print(f"共同叶子: {len(common_leaves)}")
# 查找唯一分区
unique_t1 = parts_t1 - parts_t2
unique_t2 = parts_t2 - parts_t1
print(f"树1唯一: {len(unique_t1)}")
print(f"树2唯一: {len(unique_t2)}")
比较多棵树:
import numpy as np
trees = [Tree(f"tree{i}.nw") for i in range(4)]
# 创建距离矩阵
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工具包:
# 基本安装
pip install ete3
# 带外部依赖项用于渲染(可选但推荐)
# 在macOS上:
brew install qt@5
# 在Ubuntu/Debian上:
sudo apt-get install python3-pyqt5 python3-pyqt5.qtsvg
# 用于完整功能包括GUI
pip install ete3[gui]
首次NCBITaxa设置:
第一次实例化NCBITaxa时,它会自动下载NCBI分类学数据库(约300MB)到~/.etetoolkit/taxa.sqlite。这只会发生一次:
from ete3 import NCBITaxa
ncbi = NCBITaxa() # 在第一次运行时下载数据库
更新分类学数据库:
ncbi.update_taxonomy_database() # 下载最新的NCBI数据
常见用例
用例1:系统发育基因组学管道
从基因树到直系同源识别的完整工作流:
from ete3 import PhyloTree, NCBITaxa
# 1. 加载带对齐的基因树
tree = PhyloTree("gene_tree.nw", alignment="alignment.fasta")
# 2. 配置物种命名
tree.set_species_naming_function(lambda x: x.split("_")[0])
# 3. 检测进化事件
tree.get_descendant_evol_events()
# 4. 用分类学注释
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. 提取直系同源组
ortho_groups = tree.get_speciation_trees()
# 6. 保存和可视化
for i, ortho in enumerate(ortho_groups):
ortho.write(outfile=f"ortho_{i}.nw")
用例2:树预处理和格式化
批量处理树用于分析:
# 转换格式
python scripts/tree_operations.py convert input.nw output.nw --in-format 0 --out-format 1
# 中点根定
python scripts/tree_operations.py reroot input.nw rooted.nw --midpoint
# 修剪到重点分类单元
python scripts/tree_operations.py prune rooted.nw pruned.nw --keep-taxa taxa_list.txt
# 获取统计
python scripts/tree_operations.py stats pruned.nw
用例3:出版质量图形
创建样式化可视化:
from ete3 import Tree, TreeStyle, NodeStyle, TextFace
tree = Tree("tree.nw")
# 定义分支颜色
clade_colors = {
"哺乳动物": "red",
"鸟类": "blue",
"鱼类": "green"
}
def layout(node):
# 高亮分支
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:
# 添加支持值
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
# 为出版物渲染
tree.render("figure.pdf", w=200, units="mm", tree_style=ts)
tree.render("figure.svg", tree_style=ts) # 可编辑矢量
用例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))
# 标准化:中点根定,解析多分支
midpoint = tree.get_midpoint_outgroup()
tree.set_outgroup(midpoint)
tree.resolve_polytomy(recursive=True)
# 过滤低支持分支
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()
# 保存处理后的树
output_file = os.path.join(output_dir, f"processed_{filename}")
tree.write(outfile=output_file)
参考文档
有关全面API文档、代码示例和详细指南,请参考references/目录中的以下资源:
api_reference.md:所有ETE类和方法的完整API文档(Tree、PhyloTree、ClusterTree、NCBITaxa),包括参数、返回类型和代码示例workflows.md:按任务组织的常见工作流模式(树操作、系统发育分析、树比较、分类学集成、聚类分析)visualization.md:全面可视化指南,覆盖TreeStyle、NodeStyle、面、布局函数和高级可视化技术
需要详细信息时加载这些参考:
# 使用API参考
# 阅读references/api_reference.md获取完整方法签名和参数
# 实施工作流
# 阅读references/workflows.md获取逐步工作流示例
# 创建可视化
# 阅读references/visualization.md获取样式和渲染选项
故障排除
导入错误:
# 如果"ModuleNotFoundError: No module named 'ete3'"
pip install ete3
# 对于GUI和渲染问题
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分类学数据库:
如果数据库下载失败或损坏:
from ete3 import NCBITaxa
ncbi = NCBITaxa()
ncbi.update_taxonomy_database() # 重新下载数据库
大型树的内存问题:
对于非常大的树(>10,000叶子),使用迭代器而不是列表推导:
# 内存高效迭代
for leaf in tree.iter_leaves():
process(leaf)
# 而不是
for leaf in tree.get_leaves(): # 加载所有到内存
process(leaf)
Newick格式参考
ETE支持多种Newick格式规范(0-100):
- 格式0:灵活带分支长度(默认)
- 格式1:带内部节点名称
- 格式2:带引导/支持值
- 格式5:内部节点名称+分支长度
- 格式8:所有特征(名称、距离、支持)
- 格式9:仅叶子名称
- 格式100:仅拓扑
读取/写入时指定格式:
tree = Tree("tree.nw", format=1)
tree.write(outfile="output.nw", format=5)
NHX(New Hampshire扩展)格式保留自定义特征:
tree.write(outfile="tree.nhx", features=["habitat", "temperature", "depth"])
最佳实践
- 保留分支长度:在修剪用于系统发育分析时使用
preserve_branch_length=True - 缓存内容:使用
get_cached_content()重复访问大型树上的节点内容 - 使用迭代器:使用
iter_*方法内存高效处理大型树 - 选择适当的遍历:后序用于自底向上分析,前序用于自顶向下
- 验证单系性:始终检查返回的分支类型(单系/并系/多系)
- 出版物矢量格式:使用PDF或SVG用于出版物图形(可缩放、可编辑)
- 交互式测试:使用
tree.show()在渲染到文件前测试可视化 - PhyloTree用于系统发育学:使用PhyloTree类进行基因树和进化分析
- 复制方法选择:"newick"用于速度,"cpickle"用于完全保真,"deepcopy"用于复杂对象
- NCBI查询缓存:存储NCBI分类学查询结果以避免重复数据库访问