[ PROMPT_NODE_26262 ]
phylogenetics
[ SKILL_DOCUMENTATION ]
# 使用 Bio.Phylo 进行系统发育分析
## 概述
Bio.Phylo 提供了一个统一的工具包,用于读取、写入、分析和可视化系统发育树。它支持多种文件格式,包括 Newick、NEXUS、phyloXML、NeXML 和 CDAO。
## 支持的文件格式
- **Newick** - 简单的树表示法 (最常用)
- **NEXUS** - 带有附加数据的扩展格式
- **phyloXML** - 基于 XML 的丰富注释格式
- **NeXML** - 现代 XML 格式
- **CDAO** - 比较数据分析本体
## 读取与写入树
### 读取树
python
from Bio import Phylo
# 从文件读取树
tree = Phylo.read("tree.nwk", "newick")
# 从文件解析多棵树
trees = list(Phylo.parse("trees.nwk", "newick"))
print(f"找到 {len(trees)} 棵树")
### 写入树
python
# 将树写入文件
Phylo.write(tree, "output.nwk", "newick")
# 写入多棵树
Phylo.write(trees, "output.nex", "nexus")
### 格式转换
python
# 在格式之间转换
count = Phylo.convert("input.nwk", "newick", "output.xml", "phyloxml")
print(f"已转换 {count} 棵树")
## 树结构与导航
### 树的基本组件
树由以下部分组成:
- **Clade (分支)** - 树中的节点(内部或末端)
- **Terminal clades (末端分支)** - 叶子/末梢 (分类单元)
- **Internal clades (内部分支)** - 内部节点
- **Branch length (分支长度)** - 进化距离
### 访问树属性
python
# 树根
root = tree.root
# 末端节点 (叶子)
terminals = tree.get_terminals()
print(f"分类单元数量: {len(terminals)}")
# 非末端节点
nonterminals = tree.get_nonterminals()
print(f"内部节点数量: {len(nonterminals)}")
# 所有分支
all_clades = list(tree.find_clades())
print(f"总分支数: {len(all_clades)}")
### 遍历树
python
# 遍历所有分支
for clade in tree.find_clades():
if clade.name:
print(f"分支: {clade.name}, 分支长度: {clade.branch_length}")
# 仅遍历末端分支
for terminal in tree.get_terminals():
print(f"分类单元: {terminal.name}")
# 先序遍历 (Depth-first)
for clade in tree.find_clades(order="preorder"):
print(clade.name)
# 层序遍历 (Breadth-first)
for clade in tree.find_clades(order="level"):
print(clade.name)
### 查找特定分支
python
# 按名称查找分支
clade = tree.find_any(name="Species_A")
# 查找所有符合条件的分支
def is_long_branch(clade):
return clade.branch_length and clade.branch_length > 0.5
lon