etetoolkit について
etetoolkit は、系統樹や階層ツリーの解析に使うツールキットで、生物情報学の研究者を対象としています。ツリー操作、進化イベント解析、NCBI 分類情報との連携、可視化に加え、クラスタリングとツリー比較にも対応します。
主な機能
- 01複数のツリー形式の読み込み、編集、変換
- 02重複と種分化イベントの検出
- 03オーソログとパラログの特定
- 04NCBI 分類データとの連携
- 05ツリーの可視化とトポロジー比較
- 06クラスタリング解析とヒートマップ表示
活用シーン
- 01系統樹の前処理と枝の刈り込み
- 02遺伝子ツリーからオーソログを特定
- 03分類系統情報をツリーに付与
- 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 形式の読み書き
- ツリーの走査: preorder、postorder、levelorder の各戦略によるツリーのナビゲーション
- トポロジーの変更: 枝の刈り込み、ルートの設定、ノードの折りたたみ、多分岐の解消
- 距離の計算: ノード間の枝長および位相的距離の算出
- ツリーの比較: 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)と関連付け
- 種名の抽出: 遺伝子名からの自動または任意の種名抽出
- 進化イベント: Species Overlap または系統樹の再構築(reconciliation)を用いた重複および種分化イベントの検出
- オーソログの検出: 進化イベントに基づくオーソログおよびパラログの特定
- 遺伝子ファミリー解析: 重複イベントによるツリーの分割、系統特異的な拡大の折りたたみ
遺伝子ツリー解析のワークフロー:
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 Taxonomy との統合
NCBI Taxonomy データベースの分類情報を統合します。
- データベースへのアクセス: NCBI の分類データ(約 300MB)の自動ダウンロードとローカルキャッシュ
- Taxid と名称の変換: 分類 ID と学名の相互変換
- 系統の取得: 完全な進化的系統(lineage)の取得
- 分類ツリー: 指定した分類群を結ぶ種ツリーの構築
- ツリーへの注釈付け: ツリーへの分類情報の自動注釈付け
分類情報に基づくツリーの構築:
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
- Faces: ノードへのテキスト、画像、グラフ、ヒートマップなどの図形要素の追加
- レイアウト関数: ノードの属性に基づく動的なスタイル設定
基本的な可視化のワークフロー:
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
Faces を用いた高度な可視化:
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)
- 分割解析: 固有の分割と共有される分割(bipartition)の特定
- コンセンサスツリー: 複数のツリーにわたるサポート値の解析
- 一括比較: 複数のツリーをペアごとに比較
2 つのツリーの比較:
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 タクソノミーデータベース(約 300MB)が ~/.etetoolkit/taxa.sqlite に自動的にダウンロードされます。これは一度だけ行われます:
from ete3 import NCBITaxa
ncbi = NCBITaxa() # Downloads database on first run
タクソノミーデータベースを更新します:
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: タスク別に整理された一般的なワークフローパターン(ツリー操作、系統解析、ツリー比較、タクソノミー統合、クラスタリング解析)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)をサポートしています:
- Format 0: 枝長を含む柔軟な形式(デフォルト)
- Format 1: 内部ノード名を含む
- Format 2: ブートストラップ/サポート値を含む
- Format 5: 内部ノード名 + 枝長
- Format 8: すべての要素(名前、距離、サポート値)
- Format 9: リーフ名のみ
- Format 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"])
ベストプラクティス
- 枝長を保持する: 系統解析のために刈り込みを行う場合は
preserve_branch_length=Trueを使用します - コンテンツをキャッシュする: 大規模ツリーでノードのコンテンツに繰り返しアクセスする場合は
get_cached_content()を使用します - イテレーターを使用する: 大規模ツリーのメモリ効率の良い処理には
iter_*メソッドを利用します - 適切な走査方法を選ぶ: ボトムアップ解析には後順、トップダウン解析には前順を使用します
- 単系統性を検証する: 返されるクレードの種類(単系統/側系統/多系統)を必ず確認します
- 出版用にはベクター形式を使用する: 出版図にはPDF または SVG を使用します(拡大縮小が可能で編集もしやすい)
- 対話的にテストする: ファイルに描画する前に
tree.show()で可視化を確認します - 系統解析には PhyloTree を使用する: 遺伝子ツリーや進化解析には PhyloTree クラスを使用します
- コピー方法の選択: 速度重視なら "newick"、完全な忠実性が必要なら "cpickle"、複雑なオブジェクトには "deepcopy" を使用します
- NCBI クエリのキャッシュ: 繰り返しのデータベースアクセスを避けるため、NCBI タクソノミーのクエリ結果を保存します