Communitygithub.com

系统发育学

构建和分析系统发育树,使用 MAFFT(多重比对)、IQ-TREE 2(最大似然法)和 FastTree(快速邻接/最大似然法)。通过 ETE3 或 FigTree 进行可视化。适用于进化分析、微生物基因组学、病毒系统动力学、蛋白质家族分析和分子钟研究。

系统发育学 是什么?

该技能为开发者提供了一套完整的系统发育分析工作流程,涵盖从序列比对到树构建和可视化的全链路。核心工具包括 MAFFT(多重序列比对)、IQ-TREE 2(最大似然法树推断与模型选择)、FastTree(适用于大数据集的快速近似最大似然法)以及 ETE3(用于树操作和可视化的Python库)。该技能支持多种使用场景,如进化关系推断、病毒系统动力学、蛋白质家族分析、水平基因转移检测、祖先序列重构、分子钟分析以及微生物物种系统发育(如基于16S rRNA)。它还提供了详细的模型选择指南,包括DNA模型(如GTR+G、HKY+G)和蛋白质模型(如LG+G、WAG+G),并推荐使用IQ-TREE的自动模型选择功能(-m TEST)。建议遵循最佳实践:确保比对质量、对小数据集使用 linsi 对大数据集使用 fftns、可使用TrimAl进行比对修剪、使用至少1000次超快bootstrap支持分支,以及正确生根树(如中点生根或外群生根)。整个过程可通过一系列Python函数实现自动化,并生成包含对齐、树文件和可视化的结果。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/phylogenetics

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

系统发育学 是做什么的?

概述

系统发育分析通过推断生物序列(基因、蛋白质、基因组)的分支模式,重建其进化历史。该技能涵盖标准工作流程:

  1. MAFFT — 多重序列比对
  2. IQ-TREE 2 — 含模型选择的最大似然法树推断
  3. FastTree — 快速近似最大似然法(适用于大数据集)
  4. ETE3 — Python 树操作与可视化库

安装:

# Conda(推荐用于命令行工具)
conda install -c bioconda mafft iqtree fasttree
uv pip install ete3

# ete3 的 TreeStyle/NodeStyle 渲染依赖于 Qt 后端,图像输出需要 PyQt5;
# 树解析和统计可在没有 PyQt5 的情况下运行。
uv pip install PyQt5

何时使用该技能

在以下情况下使用系统发育学:

  • 进化关系:哪个生物/基因与我的序列最接近?
  • 病毒系统动力学:追踪疫情传播并估计传播日期
  • 蛋白质家族分析:推断基因家族内的进化关系
  • 水平基因转移检测:识别物种树与基因树不一致的基因
  • 祖先序列重构:推断祖先蛋白质序列
  • 分子钟分析:利用时间采样估计分化日期
  • GWAS 辅助:将变异置于进化背景下(例如 SARS-CoV-2 变异)
  • 微生物学:基于 16S rRNA 或核心基因组系统发育的物种系统发育

标准工作流程

1. 使用 MAFFT 进行多重序列比对

import subprocess
import os

def run_mafft(input_fasta: str, output_fasta: str, method: str = "auto",
               n_threads: int = 4) -> str:
    """
    使用 MAFFT 对齐序列。

    参数:
        input_fasta: 未对齐的 FASTA 文件路径
        output_fasta: 对齐输出路径
        method: 'auto'(自动选择)、'einsi'(准确)、'linsi'(准确但慢)、
                'fftnsi'(中等)、'fftns'(快速)、'retree2'(快速)
        n_threads: CPU 线程数

    返回:
        对齐后的 FASTA 文件路径
    """
    methods = {
        "auto": ["mafft", "--auto"],
        "einsi": ["mafft", "--genafpair", "--maxiterate", "1000"],
        "linsi": ["mafft", "--localpair", "--maxiterate", "1000"],
        "fftnsi": ["mafft", "--fftnsi"],
        "fftns": ["mafft", "--fftns"],
        "retree2": ["mafft", "--retree", "2"],
    }

    cmd = methods.get(method, methods["auto"])
    cmd += ["--thread", str(n_threads), "--inputorder", input_fasta]

    with open(output_fasta, 'w') as out:
        result = subprocess.run(cmd, stdout=out, stderr=subprocess.PIPE, text=True)

    if result.returncode != 0:
        raise RuntimeError(f"MAFFT 失败:\n{result.stderr}")

    # 统计对齐的序列数
    with open(output_fasta) as f:
        n_seqs = sum(1 for line in f if line.startswith('>'))
    print(f"MAFFT:已对齐 {n_seqs} 条序列 → {output_fasta}")

    return output_fasta

# MAFFT 方法选择指南:
# 少量序列(<200),追求准确:linsi 或 einsi
# 较多序列(<1000),中等精度:fftnsi
# 大数据集(>1000):fftns 或 auto
# 超大数据集(>10000):mafft --retree 1

2. 比对修剪(可选但推荐)

def trim_alignment_trimal(aligned_fasta: str, output_fasta: str,
                            method: str = "automated1") -> str:
    """
    使用 TrimAl 修剪对齐不良的列。

    方法:
    - 'automated1':自动启发式(推荐)
    - 'gappyout':删除缺口多的列
    - 'strict':严格缺口阈值
    """
    cmd = ["trimal", f"-{method}", "-in", aligned_fasta, "-out", output_fasta, "-fasta"]
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        print(f"TrimAl 警告:{result.stderr}")
        # 回退到未修剪的比对
        import shutil
        shutil.copy(aligned_fasta, output_fasta)
    return output_fasta

3. IQ-TREE 2 — 最大似然树

def run_iqtree(aligned_fasta: str, output_prefix: str,
                model: str = "TEST", bootstrap: int = 1000,
                n_threads: int = 4, extra_args: list = None) -> dict:
    """
    使用 IQ-TREE 2 构建最大似然树。

    参数:
        aligned_fasta: 对齐的 FASTA 文件
        output_prefix: 输出文件前缀
        model: 'TEST' 为自动模型选择,或指定具体模型(例如 DNA 用 'GTR+G',
               蛋白质用 'LG+G4','JTT+G')
        bootstrap: 超快自助法重复次数(推荐 1000)
        n_threads: 线程数('AUTO' 为自动检测)
        extra_args: 其他 IQ-TREE 参数

    返回:
        包含输出文件路径的字典
    """
    cmd = [
        "iqtree2",
        "-s", aligned_fasta,
        "--prefix", output_prefix,
        "-m", model,
        "-B", str(bootstrap),   # 超快自助法
        "-T", str(n_threads),
        "--redo"                # 覆盖已有结果
    ]

    if extra_args:
        cmd.extend(extra_args)

    result = subprocess.run(cmd, capture_output=True, text=True)

    if result.returncode != 0:
        raise RuntimeError(f"IQ-TREE 失败:\n{result.stderr}")

    # 输出模型选择结果
    log_file = f"{output_prefix}.log"
    if os.path.exists(log_file):
        with open(log_file) as f:
            for line in f:
                if "Best-fit model" in line:
                    print(f"IQ-TREE:{line.strip()}")

    output_files = {
        "tree": f"{output_prefix}.treefile",
        "log": f"{output_prefix}.log",
        "iqtree": f"{output_prefix}.iqtree",  # 完整报告
        "model": f"{output_prefix}.model.gz",
    }

    print(f"IQ-TREE:树已保存至 {output_files['tree']}")
    return output_files

# IQ-TREE 模型选择指南:
# DNA:     TEST → GTR+G, HKY+G, TrN+G
# 蛋白质: TEST → LG+G4, WAG+G, JTT+G, Q.pfam+G
# 密码子: TEST → MG+F3X4

# 对于时间(分子钟)分析,添加:
# extra_args = ["--date", "dates.txt", "--clock-test", "--date-CI", "95"]

4. FastTree — 快速近似最大似然法

适用于大数据集(>1000 条序列),当 IQ-TREE 速度过慢时:

def run_fasttree(aligned_fasta: str, output_tree: str,
                  sequence_type: str = "nt", model: str = "gtr",
                  n_threads: int = 4) -> str:
    """
    使用 FastTree 构建快速近似最大似然树。

    参数:
        sequence_type: 'nt' 为核苷酸,'aa' 为氨基酸
        model: 对于 nt:'gtr'(推荐)或 'jc';对于 aa:'lg'、'wag'、'jtt'
    """
    if sequence_type == "nt":
        cmd = ["FastTree", "-nt", "-gtr"]
    else:
        cmd = ["FastTree", f"-{model}"]

    cmd += [aligned_fasta]

    with open(output_tree, 'w') as out:
        result = subprocess.run(cmd, stdout=out, stderr=subprocess.PIPE, text=True)

    if result.returncode != 0:
        raise RuntimeError(f"FastTree 失败:\n{result.stderr}")

    print(f"FastTree:树已保存至 {output_tree}")
    return output_tree

5. 使用 ETE3 进行树分析与可视化

from ete3 import Tree, TreeStyle, NodeStyle, TextFace, PhyloTree
import matplotlib.pyplot as plt

def load_tree(tree_file: str) -> Tree:
    """加载 Newick 格式的树文件。"""
    t = Tree(tree_file)
    print(f"树:{len(t)} 个叶节点,{len(list(t.traverse()))} 个节点")
    return t

def basic_tree_stats(t: Tree) -> dict:
    """计算基本树统计量。"""
    leaves = t.get_leaves()
    distances = [t.get_distance(l1, l2) for l1 in leaves[:min(50, len(leaves))]
                 for l2 in leaves[:min(50, len(leaves))] if l1 != l2]

    stats = {
        "n_leaves": len(leaves),
        "n_internal_nodes": len(t) - len(leaves),
        "total_branch_length": sum(n.dist for n in t.traverse()),
        "max_leaf_distance": max(distances) if distances else 0,
        "mean_leaf_distance": sum(distances)/len(distances) if distances else 0,
    }
    return stats

def find_mrca(t: Tree, leaf_names: list) -> Tree:
    """找到一组叶节点的最近共同祖先。"""
    return t.get_common_ancestor(*leaf_names)

def visualize_tree(t: Tree, output_file: str = "tree.png",
                    show_branch_support: bool = True,
                    color_groups: dict = None,
                    width: int = 800) -> None:
    """
    将系统发育树渲染为图像。

    参数:
        t: ETE3 Tree 对象
        color_groups: 映射叶节点名称 → 颜色的字典(用于着色分类群)
        show_branch_support: 显示自助法值
    """
    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.show_branch_support = show_branch_support
    ts.mode = "r"  # 'r' = 矩形,'c' = 圆形

    if color_groups:
        for node in t.traverse():
            if node.is_leaf() and node.name in color_groups:
                nstyle = NodeStyle()
                nstyle["fgcolor"] = color_groups[node.name]
                nstyle["size"] = 8
                node.set_style(nstyle)

    t.render(output_file, tree_style=ts, w=width, units="px")
    print(f"树已保存至:{output_file}")

def midpoint_root(t: Tree) -> Tree:
    """以中点对树进行生根(当外群未知时使用)。"""
    t.set_outgroup(t.get_midpoint_outgroup())
    return t

def prune_tree(t: Tree, keep_leaves: list) -> Tree:
    """修剪树,仅保留指定的叶节点。"""
    t.prune(keep_leaves, preserve_branch_length=True)
    return t

6. 完整分析脚本

import subprocess, os
from ete3 import Tree

def full_phylogenetic_analysis(
    input_fasta: str,
    output_dir: str = "phylo_results",
    sequence_type: str = "nt",
    n_threads: int = 4,
    bootstrap: int = 1000,
    use_fasttree: bool = False
) -> dict:
    """
    完整的系统发育流程:对齐 → 修剪 → 树构建 → 可视化。

    参数:
        input_fasta: 未对齐的 FASTA 文件
        sequence_type: 'nt'(核苷酸)或 'aa'(氨基酸/蛋白质)
        use_fasttree: 使用 FastTree 代替 IQ-TREE(对大数据集更快)
    """
    os.makedirs(output_dir, exist_ok=True)
    prefix = os.path.join(output_dir, "phylo")

    print("=" * 50)
    print("步骤 1:多重序列比对(MAFFT)")
    aligned = run_mafft(input_fasta, f"{prefix}_aligned.fasta",
                         method="auto", n_threads=n_threads)

    print("\n步骤 2:树推断")
    if use_fasttree:
        tree_file = run_fasttree(
            aligned, f"{prefix}.tree",
            sequence_type=sequence_type,
            model="gtr" if sequence_type == "nt" else "lg"
        )
    else:
        model = "TEST" if sequence_type == "nt" else "TEST"
        iqtree_files = run_iqtree(
            aligned, prefix,
            model=model,
            bootstrap=bootstrap,
            n_threads=n_threads
        )
        tree_file = iqtree_files["tree"]

    print("\n步骤 3:树分析")
    t = Tree(tree_file)
    t = midpoint_root(t)

    stats = basic_tree_stats(t)
    print(f"树统计量:{stats}")

    print("\n步骤 4:可视化")
    visualize_tree(t, f"{prefix}_tree.png", show_branch_support=True)

    # 保存生根后的树
    rooted_tree_file = f"{prefix}_rooted.nwk"
    t.write(format=1, outfile=rooted_tree_file)

    results = {
        "aligned_fasta": aligned,
        "tree_file": tree_file,
        "rooted_tree": rooted_tree_file,
        "visualization": f"{prefix}_tree.png",
        "stats": stats
    }

    print("\n" + "=" * 50)
    print("系统发育分析完成!")
    print(f"结果位于:{output_dir}/")
    return results

IQ-TREE 模型指南

DNA 模型

模型描述使用场景
GTR+G4一般时间可逆 + Gamma最灵活的 DNA 模型
HKY+G4Hasegawa-Kishino-Yano + Gamma双速率模型(常见)
TrN+G4Tamura-Nei不等转换率
JCJukes-Cantor最简单;所有速率相等

蛋白质模型

模型描述使用场景
LG+G4Le-Gascuel + Gamma最佳平均蛋白质模型
WAG+G4Whelan-Goldman广泛使用
JTT+G4Jones-Taylor-Thornton经典模型
Q.pfam+G4基于 pfam 训练用于像 Pfam 的蛋白质家族
Q.bird+G4鸟类特异性脊椎动物蛋白质

提示: 使用 -m TEST 让 IQ-TREE 自动选择最佳模型。

最佳实践

  • 比对质量优先:不良比对导致不可靠的树;请手动检查比对
  • 小数据集(<200 条序列)使用 linsi,大数据集使用 fftns 或 auto
  • 模型选择:除非有特定理由,否则始终对 IQ-TREE 使用 -m TEST
  • 自助法:使用 ≥1000 次超快自助法(-B 1000)获得分支支持度
  • 对树进行生根:无根树可能产生误导;使用外群或中点生根
  • 超过 5000 条序列时使用 FastTree:IQ-TREE 会变慢;FastTree 快 10–100 倍
  • 修剪长比对:TrimAl 可去除不可靠的列;提高树准确性
  • 构建树前检查重组:对病毒/细菌序列使用(RDP4、GARD)

附加资源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

biopython

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

相关技能