[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M735WDQR7GVAMYGD5RCC0JWV":3,"skill-same:01M735WDQR7GVAMYGD5RCC0JWV":54},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":26,"commitSha":27,"skillDirectory":28,"forksCount":29,"repositoryHtmlUrl":30,"repositoryHomepageUrl":6,"ownerHtmlUrl":31,"ownerBlogUrl":32,"ownerDescription":6,"updatedAt":33,"install":34,"resources":47},"01M735WDQR7GVAMYGD5RCC0JWV","alterlab-phylogenetics",null,"Build and analyze phylogenetic trees using MAFFT (multiple alignment), IQ-TREE 2 (maximum likelihood), and FastTree (fast NJ\u002FML). Visualize with ETE3 or FigTree. For evolutionary analysis, microbial genomics, viral phylodynamics, protein family analysis, and molecular clock studies. Part of the AlterLab Academic Skills suite.","roohe\u002Fagentic-super-skills","roohe","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99054084?v=4","01M734WCDFP6RZVT5CNM00QR26","01M734WCE4BD0T4NZS5PCV9V5F",10,"MIT","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Falterlab-phylogenetics\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: alterlab-phylogenetics\ndescription: Build and analyze phylogenetic trees using MAFFT (multiple alignment), IQ-TREE 2 (maximum likelihood), and FastTree (fast NJ\u002FML). Visualize with ETE3 or FigTree. For evolutionary analysis, microbial genomics, viral phylodynamics, protein family analysis, and molecular clock studies. Part of the AlterLab Academic Skills suite.\nlicense: MIT\nmetadata:\n    skill-author: AlterLab\n    version: \"1.0.0\"\n---\n\n# Phylogenetics\n\n## Overview\n\nPhylogenetic analysis reconstructs the evolutionary history of biological sequences (genes, proteins, genomes) by inferring the branching pattern of descent. This skill covers the standard pipeline:\n\n1. **MAFFT** — Multiple sequence alignment\n2. **IQ-TREE 2** — Maximum likelihood tree inference with model selection\n3. **FastTree** — Fast approximate maximum likelihood (for large datasets)\n4. **ETE3** — Python library for tree manipulation and visualization\n\n**Installation:**\n```bash\n# Conda (recommended for CLI tools)\nconda install -c bioconda mafft iqtree fasttree\npip install ete3\n```\n\n## When to Use This Skill\n\nUse phylogenetics when:\n\n- **Evolutionary relationships**: Which organism\u002Fgene is most closely related to my sequence?\n- **Viral phylodynamics**: Trace outbreak spread and estimate transmission dates\n- **Protein family analysis**: Infer evolutionary relationships within a gene family\n- **Horizontal gene transfer detection**: Identify genes with discordant species\u002Fgene trees\n- **Ancestral sequence reconstruction**: Infer ancestral protein sequences\n- **Molecular clock analysis**: Estimate divergence dates using temporal sampling\n- **GWAS companion**: Place variants in evolutionary context (e.g., SARS-CoV-2 variants)\n- **Microbiology**: Species phylogeny from 16S rRNA or core genome phylogeny\n\n## Standard Workflow\n\n### 1. Multiple Sequence Alignment with MAFFT\n\n```python\nimport subprocess\nimport os\n\ndef run_mafft(input_fasta: str, output_fasta: str, method: str = \"auto\",\n               n_threads: int = 4) -> str:\n    \"\"\"\n    Align sequences with MAFFT.\n\n    Args:\n        input_fasta: Path to unaligned FASTA file\n        output_fasta: Path for aligned output\n        method: 'auto' (auto-select), 'einsi' (accurate), 'linsi' (accurate, slow),\n                'fftnsi' (medium), 'fftns' (fast), 'retree2' (fast)\n        n_threads: Number of CPU threads\n\n    Returns:\n        Path to aligned FASTA file\n    \"\"\"\n    methods = {\n        \"auto\": [\"mafft\", \"--auto\"],\n        \"einsi\": [\"mafft\", \"--genafpair\", \"--maxiterate\", \"1000\"],\n        \"linsi\": [\"mafft\", \"--localpair\", \"--maxiterate\", \"1000\"],\n        \"fftnsi\": [\"mafft\", \"--fftnsi\"],\n        \"fftns\": [\"mafft\", \"--fftns\"],\n        \"retree2\": [\"mafft\", \"--retree\", \"2\"],\n    }\n\n    cmd = methods.get(method, methods[\"auto\"])\n    cmd += [\"--thread\", str(n_threads), \"--inputorder\", input_fasta]\n\n    with open(output_fasta, 'w') as out:\n        result = subprocess.run(cmd, stdout=out, stderr=subprocess.PIPE, text=True)\n\n    if result.returncode != 0:\n        raise RuntimeError(f\"MAFFT failed:\\n{result.stderr}\")\n\n    # Count aligned sequences\n    with open(output_fasta) as f:\n        n_seqs = sum(1 for line in f if line.startswith('>'))\n    print(f\"MAFFT: aligned {n_seqs} sequences → {output_fasta}\")\n\n    return output_fasta\n\n# MAFFT method selection guide:\n# Few sequences (\u003C200), accurate: linsi or einsi\n# Many sequences (\u003C1000), moderate: fftnsi\n# Large datasets (>1000): fftns or auto\n# Ultra-fast (>10000): mafft --retree 1\n```\n\n### 2. Trim Alignment (Optional but Recommended)\n\n```python\ndef trim_alignment_trimal(aligned_fasta: str, output_fasta: str,\n                            method: str = \"automated1\") -> str:\n    \"\"\"\n    Trim poorly aligned columns with TrimAl.\n\n    Methods:\n    - 'automated1': Automatic heuristic (recommended)\n    - 'gappyout': Remove gappy columns\n    - 'strict': Strict gap threshold\n    \"\"\"\n    cmd = [\"trimal\", f\"-{method}\", \"-in\", aligned_fasta, \"-out\", output_fasta, \"-fasta\"]\n    result = subprocess.run(cmd, capture_output=True, text=True)\n    if result.returncode != 0:\n        print(f\"TrimAl warning: {result.stderr}\")\n        # Fall back to using the untrimmed alignment\n        import shutil\n        shutil.copy(aligned_fasta, output_fasta)\n    return output_fasta\n```\n\n### 3. IQ-TREE 2 — Maximum Likelihood Tree\n\n```python\ndef run_iqtree(aligned_fasta: str, output_prefix: str,\n                model: str = \"TEST\", bootstrap: int = 1000,\n                n_threads: int = 4, extra_args: list = None) -> dict:\n    \"\"\"\n    Build a maximum likelihood tree with IQ-TREE 2.\n\n    Args:\n        aligned_fasta: Aligned FASTA file\n        output_prefix: Prefix for output files\n        model: 'TEST' for automatic model selection, or specify (e.g., 'GTR+G' for DNA,\n               'LG+G4' for proteins, 'JTT+G' for proteins)\n        bootstrap: Number of ultrafast bootstrap replicates (1000 recommended)\n        n_threads: Number of threads ('AUTO' to auto-detect)\n        extra_args: Additional IQ-TREE arguments\n\n    Returns:\n        Dict with paths to output files\n    \"\"\"\n    cmd = [\n        \"iqtree2\",\n        \"-s\", aligned_fasta,\n        \"--prefix\", output_prefix,\n        \"-m\", model,\n        \"-B\", str(bootstrap),   # Ultrafast bootstrap\n        \"-T\", str(n_threads),\n        \"--redo\"                # Overwrite existing results\n    ]\n\n    if extra_args:\n        cmd.extend(extra_args)\n\n    result = subprocess.run(cmd, capture_output=True, text=True)\n\n    if result.returncode != 0:\n        raise RuntimeError(f\"IQ-TREE failed:\\n{result.stderr}\")\n\n    # Print model selection result\n    log_file = f\"{output_prefix}.log\"\n    if os.path.exists(log_file):\n        with open(log_file) as f:\n            for line in f:\n                if \"Best-fit model\" in line:\n                    print(f\"IQ-TREE: {line.strip()}\")\n\n    output_files = {\n        \"tree\": f\"{output_prefix}.treefile\",\n        \"log\": f\"{output_prefix}.log\",\n        \"iqtree\": f\"{output_prefix}.iqtree\",  # Full report\n        \"model\": f\"{output_prefix}.model.gz\",\n    }\n\n    print(f\"IQ-TREE: Tree saved to {output_files['tree']}\")\n    return output_files\n\n# IQ-TREE model selection guide:\n# DNA:     TEST → GTR+G, HKY+G, TrN+G\n# Protein: TEST → LG+G4, WAG+G, JTT+G, Q.pfam+G\n# Codon:   TEST → MG+F3X4\n\n# For temporal (molecular clock) analysis, add:\n# extra_args = [\"--date\", \"dates.txt\", \"--clock-test\", \"--date-CI\", \"95\"]\n```\n\n### 4. FastTree — Fast Approximate ML\n\nFor large datasets (>1000 sequences) where IQ-TREE is too slow:\n\n```python\ndef run_fasttree(aligned_fasta: str, output_tree: str,\n                  sequence_type: str = \"nt\", model: str = \"gtr\",\n                  n_threads: int = 4) -> str:\n    \"\"\"\n    Build a fast approximate ML tree with FastTree.\n\n    Args:\n        sequence_type: 'nt' for nucleotide or 'aa' for amino acid\n        model: For nt: 'gtr' (recommended) or 'jc'; for aa: 'lg', 'wag', 'jtt'\n    \"\"\"\n    if sequence_type == \"nt\":\n        cmd = [\"FastTree\", \"-nt\", \"-gtr\"]\n    else:\n        cmd = [\"FastTree\", f\"-{model}\"]\n\n    cmd += [aligned_fasta]\n\n    with open(output_tree, 'w') as out:\n        result = subprocess.run(cmd, stdout=out, stderr=subprocess.PIPE, text=True)\n\n    if result.returncode != 0:\n        raise RuntimeError(f\"FastTree failed:\\n{result.stderr}\")\n\n    print(f\"FastTree: Tree saved to {output_tree}\")\n    return output_tree\n```\n\n### 5. Tree Analysis and Visualization with ETE3\n\n```python\nfrom ete3 import Tree, TreeStyle, NodeStyle, TextFace, PhyloTree\nimport matplotlib.pyplot as plt\n\ndef load_tree(tree_file: str) -> Tree:\n    \"\"\"Load a Newick tree file.\"\"\"\n    t = Tree(tree_file)\n    print(f\"Tree: {len(t)} leaves, {len(list(t.traverse()))} nodes\")\n    return t\n\ndef basic_tree_stats(t: Tree) -> dict:\n    \"\"\"Compute basic tree statistics.\"\"\"\n    leaves = t.get_leaves()\n    distances = [t.get_distance(l1, l2) for l1 in leaves[:min(50, len(leaves))]\n                 for l2 in leaves[:min(50, len(leaves))] if l1 != l2]\n\n    stats = {\n        \"n_leaves\": len(leaves),\n        \"n_internal_nodes\": len(t) - len(leaves),\n        \"total_branch_length\": sum(n.dist for n in t.traverse()),\n        \"max_leaf_distance\": max(distances) if distances else 0,\n        \"mean_leaf_distance\": sum(distances)\u002Flen(distances) if distances else 0,\n    }\n    return stats\n\ndef find_mrca(t: Tree, leaf_names: list) -> Tree:\n    \"\"\"Find the most recent common ancestor of a set of leaves.\"\"\"\n    return t.get_common_ancestor(*leaf_names)\n\ndef visualize_tree(t: Tree, output_file: str = \"tree.png\",\n                    show_branch_support: bool = True,\n                    color_groups: dict = None,\n                    width: int = 800) -> None:\n    \"\"\"\n    Render phylogenetic tree to image.\n\n    Args:\n        t: ETE3 Tree object\n        color_groups: Dict mapping leaf_name → color (for coloring taxa)\n        show_branch_support: Show bootstrap values\n    \"\"\"\n    ts = TreeStyle()\n    ts.show_leaf_name = True\n    ts.show_branch_support = show_branch_support\n    ts.mode = \"r\"  # 'r' = rectangular, 'c' = circular\n\n    if color_groups:\n        for node in t.traverse():\n            if node.is_leaf() and node.name in color_groups:\n                nstyle = NodeStyle()\n                nstyle[\"fgcolor\"] = color_groups[node.name]\n                nstyle[\"size\"] = 8\n                node.set_style(nstyle)\n\n    t.render(output_file, tree_style=ts, w=width, units=\"px\")\n    print(f\"Tree saved to: {output_file}\")\n\ndef midpoint_root(t: Tree) -> Tree:\n    \"\"\"Root tree at midpoint (use when outgroup unknown).\"\"\"\n    t.set_outgroup(t.get_midpoint_outgroup())\n    return t\n\ndef prune_tree(t: Tree, keep_leaves: list) -> Tree:\n    \"\"\"Prune tree to keep only specified leaves.\"\"\"\n    t.prune(keep_leaves, preserve_branch_length=True)\n    return t\n```\n\n### 6. Complete Analysis Script\n\n```python\nimport subprocess, os\nfrom ete3 import Tree\n\ndef full_phylogenetic_analysis(\n    input_fasta: str,\n    output_dir: str = \"phylo_results\",\n    sequence_type: str = \"nt\",\n    n_threads: int = 4,\n    bootstrap: int = 1000,\n    use_fasttree: bool = False\n) -> dict:\n    \"\"\"\n    Complete phylogenetic pipeline: align → trim → tree → visualize.\n\n    Args:\n        input_fasta: Unaligned FASTA\n        sequence_type: 'nt' (nucleotide) or 'aa' (amino acid\u002Fprotein)\n        use_fasttree: Use FastTree instead of IQ-TREE (faster for large datasets)\n    \"\"\"\n    os.makedirs(output_dir, exist_ok=True)\n    prefix = os.path.join(output_dir, \"phylo\")\n\n    print(\"=\" * 50)\n    print(\"Step 1: Multiple Sequence Alignment (MAFFT)\")\n    aligned = run_mafft(input_fasta, f\"{prefix}_aligned.fasta\",\n                         method=\"auto\", n_threads=n_threads)\n\n    print(\"\\nStep 2: Tree Inference\")\n    if use_fasttree:\n        tree_file = run_fasttree(\n            aligned, f\"{prefix}.tree\",\n            sequence_type=sequence_type,\n            model=\"gtr\" if sequence_type == \"nt\" else \"lg\"\n        )\n    else:\n        model = \"TEST\" if sequence_type == \"nt\" else \"TEST\"\n        iqtree_files = run_iqtree(\n            aligned, prefix,\n            model=model,\n            bootstrap=bootstrap,\n            n_threads=n_threads\n        )\n        tree_file = iqtree_files[\"tree\"]\n\n    print(\"\\nStep 3: Tree Analysis\")\n    t = Tree(tree_file)\n    t = midpoint_root(t)\n\n    stats = basic_tree_stats(t)\n    print(f\"Tree statistics: {stats}\")\n\n    print(\"\\nStep 4: Visualization\")\n    visualize_tree(t, f\"{prefix}_tree.png\", show_branch_support=True)\n\n    # Save rooted tree\n    rooted_tree_file = f\"{prefix}_rooted.nwk\"\n    t.write(format=1, outfile=rooted_tree_file)\n\n    results = {\n        \"aligned_fasta\": aligned,\n        \"tree_file\": tree_file,\n        \"rooted_tree\": rooted_tree_file,\n        \"visualization\": f\"{prefix}_tree.png\",\n        \"stats\": stats\n    }\n\n    print(\"\\n\" + \"=\" * 50)\n    print(\"Phylogenetic analysis complete!\")\n    print(f\"Results in: {output_dir}\u002F\")\n    return results\n```\n\n## IQ-TREE Model Guide\n\n### DNA Models\n\n| Model | Description | Use case |\n|-------|-------------|---------|\n| `GTR+G4` | General Time Reversible + Gamma | Most flexible DNA model |\n| `HKY+G4` | Hasegawa-Kishino-Yano + Gamma | Two-rate model (common) |\n| `TrN+G4` | Tamura-Nei | Unequal transitions |\n| `JC` | Jukes-Cantor | Simplest; all rates equal |\n\n### Protein Models\n\n| Model | Description | Use case |\n|-------|-------------|---------|\n| `LG+G4` | Le-Gascuel + Gamma | Best average protein model |\n| `WAG+G4` | Whelan-Goldman | Widely used |\n| `JTT+G4` | Jones-Taylor-Thornton | Classical model |\n| `Q.pfam+G4` | pfam-trained | For Pfam-like protein families |\n| `Q.bird+G4` | Bird-specific | Vertebrate proteins |\n\n**Tip:** Use `-m TEST` to let IQ-TREE automatically select the best model.\n\n## Best Practices\n\n- **Alignment quality first**: Poor alignment → unreliable trees; check alignment manually\n- **Use `linsi` for small (\u003C200 seq), `fftns` or `auto` for large alignments**\n- **Model selection**: Always use `-m TEST` for IQ-TREE unless you have a specific reason\n- **Bootstrap**: Use ≥1000 ultrafast bootstraps (`-B 1000`) for branch support\n- **Root the tree**: Unrooted trees can be misleading; use outgroup or midpoint rooting\n- **FastTree for >5000 sequences**: IQ-TREE becomes slow; FastTree is 10–100× faster\n- **Trim long alignments**: TrimAl removes unreliable columns; improves tree accuracy\n- **Check for recombination** in viral\u002Fbacterial sequences before building trees (`RDP4`, `GARD`)\n\n## Additional Resources\n\n- **MAFFT**: https:\u002F\u002Fmafft.cbrc.jp\u002Falignment\u002Fsoftware\u002F\n- **IQ-TREE 2**: http:\u002F\u002Fwww.iqtree.org\u002F | Tutorial: https:\u002F\u002Fwww.iqtree.org\u002Fworkshop\u002Fmolevol2022\n- **FastTree**: http:\u002F\u002Fwww.microbesonline.org\u002Ffasttree\u002F\n- **ETE3**: http:\u002F\u002Fetetoolkit.org\u002F\n- **FigTree** (GUI visualization): https:\u002F\u002Ftree.bio.ed.ac.uk\u002Fsoftware\u002Ffigtree\u002F\n- **iTOL** (web visualization): https:\u002F\u002Fitol.embl.de\u002F\n- **MUSCLE** (alternative aligner): https:\u002F\u002Fwww.drive5.com\u002Fmuscle\u002F\n- **TrimAl** (alignment trimming): https:\u002F\u002Fvicfero.github.io\u002Ftrimal\u002F\n","# Phylogenetics\n\n## Overview\n\nPhylogenetic analysis reconstructs the evolutionary history of biological sequences (genes, proteins, genomes) by inferring the branching pattern of descent. This skill covers the standard pipeline:\n\n1. **MAFFT** — Multiple sequence alignment\n2. **IQ-TREE 2** — Maximum likelihood tree inference with model selection\n3. **FastTree** — Fast approximate maximum likelihood (for large datasets)\n4. **ETE3** — Python library for tree manipulation and visualization\n\n**Installation:**\n```bash\n# Conda (recommended for CLI tools)\nconda install -c bioconda mafft iqtree fasttree\npip install ete3\n```\n\n## When to Use This Skill\n\nUse phylogenetics when:\n\n- **Evolutionary relationships**: Which organism\u002Fgene is most closely related to my sequence?\n- **Viral phylodynamics**: Trace outbreak spread and estimate transmission dates\n- **Protein family analysis**: Infer evolutionary relationships within a gene family\n- **Horizontal gene transfer detection**: Identify genes with discordant species\u002Fgene trees\n- **Ancestral sequence reconstruction**: Infer ancestral protein sequences\n- **Molecular clock analysis**: Estimate divergence dates using temporal sampling\n- **GWAS companion**: Place variants in evolutionary context (e.g., SARS-CoV-2 variants)\n- **Microbiology**: Species phylogeny from 16S rRNA or core genome phylogeny\n\n## Standard Workflow\n\n### 1. Multiple Sequence Alignment with MAFFT\n\n```python\nimport subprocess\nimport os\n\ndef run_mafft(input_fasta: str, output_fasta: str, method: str = \"auto\",\n               n_threads: int = 4) -> str:\n    \"\"\"\n    Align sequences with MAFFT.\n\n    Args:\n        input_fasta: Path to unaligned FASTA file\n        output_fasta: Path for aligned output\n        method: 'auto' (auto-select), 'einsi' (accurate), 'linsi' (accurate, slow),\n                'fftnsi' (medium), 'fftns' (fast), 'retree2' (fast)\n        n_threads: Number of CPU threads\n\n    Returns:\n        Path to aligned FASTA file\n    \"\"\"\n    methods = {\n        \"auto\": [\"mafft\", \"--auto\"],\n        \"einsi\": [\"mafft\", \"--genafpair\", \"--maxiterate\", \"1000\"],\n        \"linsi\": [\"mafft\", \"--localpair\", \"--maxiterate\", \"1000\"],\n        \"fftnsi\": [\"mafft\", \"--fftnsi\"],\n        \"fftns\": [\"mafft\", \"--fftns\"],\n        \"retree2\": [\"mafft\", \"--retree\", \"2\"],\n    }\n\n    cmd = methods.get(method, methods[\"auto\"])\n    cmd += [\"--thread\", str(n_threads), \"--inputorder\", input_fasta]\n\n    with open(output_fasta, 'w') as out:\n        result = subprocess.run(cmd, stdout=out, stderr=subprocess.PIPE, text=True)\n\n    if result.returncode != 0:\n        raise RuntimeError(f\"MAFFT failed:\\n{result.stderr}\")\n\n    # Count aligned sequences\n    with open(output_fasta) as f:\n        n_seqs = sum(1 for line in f if line.startswith('>'))\n    print(f\"MAFFT: aligned {n_seqs} sequences → {output_fasta}\")\n\n    return output_fasta\n\n# MAFFT method selection guide:\n# Few sequences (\u003C200), accurate: linsi or einsi\n# Many sequences (\u003C1000), moderate: fftnsi\n# Large datasets (>1000): fftns or auto\n# Ultra-fast (>10000): mafft --retree 1\n```\n\n### 2. Trim Alignment (Optional but Recommended)\n\n```python\ndef trim_alignment_trimal(aligned_fasta: str, output_fasta: str,\n                            method: str = \"automated1\") -> str:\n    \"\"\"\n    Trim poorly aligned columns with TrimAl.\n\n    Methods:\n    - 'automated1': Automatic heuristic (recommended)\n    - 'gappyout': Remove gappy columns\n    - 'strict': Strict gap threshold\n    \"\"\"\n    cmd = [\"trimal\", f\"-{method}\", \"-in\", aligned_fasta, \"-out\", output_fasta, \"-fasta\"]\n    result = subprocess.run(cmd, capture_output=True, text=True)\n    if result.returncode != 0:\n        print(f\"TrimAl warning: {result.stderr}\")\n        # Fall back to using the untrimmed alignment\n        import shutil\n        shutil.copy(aligned_fasta, output_fasta)\n    return output_fasta\n```\n\n### 3. IQ-TREE 2 — Maximum Likelihood Tree\n\n```python\ndef run_iqtree(aligned_fasta: str, output_prefix: str,\n                model: str = \"TEST\", bootstrap: int = 1000,\n                n_threads: int = 4, extra_args: list = None) -> dict:\n    \"\"\"\n    Build a maximum likelihood tree with IQ-TREE 2.\n\n    Args:\n        aligned_fasta: Aligned FASTA file\n        output_prefix: Prefix for output files\n        model: 'TEST' for automatic model selection, or specify (e.g., 'GTR+G' for DNA,\n               'LG+G4' for proteins, 'JTT+G' for proteins)\n        bootstrap: Number of ultrafast bootstrap replicates (1000 recommended)\n        n_threads: Number of threads ('AUTO' to auto-detect)\n        extra_args: Additional IQ-TREE arguments\n\n    Returns:\n        Dict with paths to output files\n    \"\"\"\n    cmd = [\n        \"iqtree2\",\n        \"-s\", aligned_fasta,\n        \"--prefix\", output_prefix,\n        \"-m\", model,\n        \"-B\", str(bootstrap),   # Ultrafast bootstrap\n        \"-T\", str(n_threads),\n        \"--redo\"                # Overwrite existing results\n    ]\n\n    if extra_args:\n        cmd.extend(extra_args)\n\n    result = subprocess.run(cmd, capture_output=True, text=True)\n\n    if result.returncode != 0:\n        raise RuntimeError(f\"IQ-TREE failed:\\n{result.stderr}\")\n\n    # Print model selection result\n    log_file = f\"{output_prefix}.log\"\n    if os.path.exists(log_file):\n        with open(log_file) as f:\n            for line in f:\n                if \"Best-fit model\" in line:\n                    print(f\"IQ-TREE: {line.strip()}\")\n\n    output_files = {\n        \"tree\": f\"{output_prefix}.treefile\",\n        \"log\": f\"{output_prefix}.log\",\n        \"iqtree\": f\"{output_prefix}.iqtree\",  # Full report\n        \"model\": f\"{output_prefix}.model.gz\",\n    }\n\n    print(f\"IQ-TREE: Tree saved to {output_files['tree']}\")\n    return output_files\n\n# IQ-TREE model selection guide:\n# DNA:     TEST → GTR+G, HKY+G, TrN+G\n# Protein: TEST → LG+G4, WAG+G, JTT+G, Q.pfam+G\n# Codon:   TEST → MG+F3X4\n\n# For temporal (molecular clock) analysis, add:\n# extra_args = [\"--date\", \"dates.txt\", \"--clock-test\", \"--date-CI\", \"95\"]\n```\n\n### 4. FastTree — Fast Approximate ML\n\nFor large datasets (>1000 sequences) where IQ-TREE is too slow:\n\n```python\ndef run_fasttree(aligned_fasta: str, output_tree: str,\n                  sequence_type: str = \"nt\", model: str = \"gtr\",\n                  n_threads: int = 4) -> str:\n    \"\"\"\n    Build a fast approximate ML tree with FastTree.\n\n    Args:\n        sequence_type: 'nt' for nucleotide or 'aa' for amino acid\n        model: For nt: 'gtr' (recommended) or 'jc'; for aa: 'lg', 'wag', 'jtt'\n    \"\"\"\n    if sequence_type == \"nt\":\n        cmd = [\"FastTree\", \"-nt\", \"-gtr\"]\n    else:\n        cmd = [\"FastTree\", f\"-{model}\"]\n\n    cmd += [aligned_fasta]\n\n    with open(output_tree, 'w') as out:\n        result = subprocess.run(cmd, stdout=out, stderr=subprocess.PIPE, text=True)\n\n    if result.returncode != 0:\n        raise RuntimeError(f\"FastTree failed:\\n{result.stderr}\")\n\n    print(f\"FastTree: Tree saved to {output_tree}\")\n    return output_tree\n```\n\n### 5. Tree Analysis and Visualization with ETE3\n\n```python\nfrom ete3 import Tree, TreeStyle, NodeStyle, TextFace, PhyloTree\nimport matplotlib.pyplot as plt\n\ndef load_tree(tree_file: str) -> Tree:\n    \"\"\"Load a Newick tree file.\"\"\"\n    t = Tree(tree_file)\n    print(f\"Tree: {len(t)} leaves, {len(list(t.traverse()))} nodes\")\n    return t\n\ndef basic_tree_stats(t: Tree) -> dict:\n    \"\"\"Compute basic tree statistics.\"\"\"\n    leaves = t.get_leaves()\n    distances = [t.get_distance(l1, l2) for l1 in leaves[:min(50, len(leaves))]\n                 for l2 in leaves[:min(50, len(leaves))] if l1 != l2]\n\n    stats = {\n        \"n_leaves\": len(leaves),\n        \"n_internal_nodes\": len(t) - len(leaves),\n        \"total_branch_length\": sum(n.dist for n in t.traverse()),\n        \"max_leaf_distance\": max(distances) if distances else 0,\n        \"mean_leaf_distance\": sum(distances)\u002Flen(distances) if distances else 0,\n    }\n    return stats\n\ndef find_mrca(t: Tree, leaf_names: list) -> Tree:\n    \"\"\"Find the most recent common ancestor of a set of leaves.\"\"\"\n    return t.get_common_ancestor(*leaf_names)\n\ndef visualize_tree(t: Tree, output_file: str = \"tree.png\",\n                    show_branch_support: bool = True,\n                    color_groups: dict = None,\n                    width: int = 800) -> None:\n    \"\"\"\n    Render phylogenetic tree to image.\n\n    Args:\n        t: ETE3 Tree object\n        color_groups: Dict mapping leaf_name → color (for coloring taxa)\n        show_branch_support: Show bootstrap values\n    \"\"\"\n    ts = TreeStyle()\n    ts.show_leaf_name = True\n    ts.show_branch_support = show_branch_support\n    ts.mode = \"r\"  # 'r' = rectangular, 'c' = circular\n\n    if color_groups:\n        for node in t.traverse():\n            if node.is_leaf() and node.name in color_groups:\n                nstyle = NodeStyle()\n                nstyle[\"fgcolor\"] = color_groups[node.name]\n                nstyle[\"size\"] = 8\n                node.set_style(nstyle)\n\n    t.render(output_file, tree_style=ts, w=width, units=\"px\")\n    print(f\"Tree saved to: {output_file}\")\n\ndef midpoint_root(t: Tree) -> Tree:\n    \"\"\"Root tree at midpoint (use when outgroup unknown).\"\"\"\n    t.set_outgroup(t.get_midpoint_outgroup())\n    return t\n\ndef prune_tree(t: Tree, keep_leaves: list) -> Tree:\n    \"\"\"Prune tree to keep only specified leaves.\"\"\"\n    t.prune(keep_leaves, preserve_branch_length=True)\n    return t\n```\n\n### 6. Complete Analysis Script\n\n```python\nimport subprocess, os\nfrom ete3 import Tree\n\ndef full_phylogenetic_analysis(\n    input_fasta: str,\n    output_dir: str = \"phylo_results\",\n    sequence_type: str = \"nt\",\n    n_threads: int = 4,\n    bootstrap: int = 1000,\n    use_fasttree: bool = False\n) -> dict:\n    \"\"\"\n    Complete phylogenetic pipeline: align → trim → tree → visualize.\n\n    Args:\n        input_fasta: Unaligned FASTA\n        sequence_type: 'nt' (nucleotide) or 'aa' (amino acid\u002Fprotein)\n        use_fasttree: Use FastTree instead of IQ-TREE (faster for large datasets)\n    \"\"\"\n    os.makedirs(output_dir, exist_ok=True)\n    prefix = os.path.join(output_dir, \"phylo\")\n\n    print(\"=\" * 50)\n    print(\"Step 1: Multiple Sequence Alignment (MAFFT)\")\n    aligned = run_mafft(input_fasta, f\"{prefix}_aligned.fasta\",\n                         method=\"auto\", n_threads=n_threads)\n\n    print(\"\\nStep 2: Tree Inference\")\n    if use_fasttree:\n        tree_file = run_fasttree(\n            aligned, f\"{prefix}.tree\",\n            sequence_type=sequence_type,\n            model=\"gtr\" if sequence_type == \"nt\" else \"lg\"\n        )\n    else:\n        model = \"TEST\" if sequence_type == \"nt\" else \"TEST\"\n        iqtree_files = run_iqtree(\n            aligned, prefix,\n            model=model,\n            bootstrap=bootstrap,\n            n_threads=n_threads\n        )\n        tree_file = iqtree_files[\"tree\"]\n\n    print(\"\\nStep 3: Tree Analysis\")\n    t = Tree(tree_file)\n    t = midpoint_root(t)\n\n    stats = basic_tree_stats(t)\n    print(f\"Tree statistics: {stats}\")\n\n    print(\"\\nStep 4: Visualization\")\n    visualize_tree(t, f\"{prefix}_tree.png\", show_branch_support=True)\n\n    # Save rooted tree\n    rooted_tree_file = f\"{prefix}_rooted.nwk\"\n    t.write(format=1, outfile=rooted_tree_file)\n\n    results = {\n        \"aligned_fasta\": aligned,\n        \"tree_file\": tree_file,\n        \"rooted_tree\": rooted_tree_file,\n        \"visualization\": f\"{prefix}_tree.png\",\n        \"stats\": stats\n    }\n\n    print(\"\\n\" + \"=\" * 50)\n    print(\"Phylogenetic analysis complete!\")\n    print(f\"Results in: {output_dir}\u002F\")\n    return results\n```\n\n## IQ-TREE Model Guide\n\n### DNA Models\n\n| Model | Description | Use case |\n|-------|-------------|---------|\n| `GTR+G4` | General Time Reversible + Gamma | Most flexible DNA model |\n| `HKY+G4` | Hasegawa-Kishino-Yano + Gamma | Two-rate model (common) |\n| `TrN+G4` | Tamura-Nei | Unequal transitions |\n| `JC` | Jukes-Cantor | Simplest; all rates equal |\n\n### Protein Models\n\n| Model | Description | Use case |\n|-------|-------------|---------|\n| `LG+G4` | Le-Gascuel + Gamma | Best average protein model |\n| `WAG+G4` | Whelan-Goldman | Widely used |\n| `JTT+G4` | Jones-Taylor-Thornton | Classical model |\n| `Q.pfam+G4` | pfam-trained | For Pfam-like protein families |\n| `Q.bird+G4` | Bird-specific | Vertebrate proteins |\n\n**Tip:** Use `-m TEST` to let IQ-TREE automatically select the best model.\n\n## Best Practices\n\n- **Alignment quality first**: Poor alignment → unreliable trees; check alignment manually\n- **Use `linsi` for small (\u003C200 seq), `fftns` or `auto` for large alignments**\n- **Model selection**: Always use `-m TEST` for IQ-TREE unless you have a specific reason\n- **Bootstrap**: Use ≥1000 ultrafast bootstraps (`-B 1000`) for branch support\n- **Root the tree**: Unrooted trees can be misleading; use outgroup or midpoint rooting\n- **FastTree for >5000 sequences**: IQ-TREE becomes slow; FastTree is 10–100× faster\n- **Trim long alignments**: TrimAl removes unreliable columns; improves tree accuracy\n- **Check for recombination** in viral\u002Fbacterial sequences before building trees (`RDP4`, `GARD`)\n\n## Additional Resources\n\n- **MAFFT**: https:\u002F\u002Fmafft.cbrc.jp\u002Falignment\u002Fsoftware\u002F\n- **IQ-TREE 2**: http:\u002F\u002Fwww.iqtree.org\u002F | Tutorial: https:\u002F\u002Fwww.iqtree.org\u002Fworkshop\u002Fmolevol2022\n- **FastTree**: http:\u002F\u002Fwww.microbesonline.org\u002Ffasttree\u002F\n- **ETE3**: http:\u002F\u002Fetetoolkit.org\u002F\n- **FigTree** (GUI visualization): https:\u002F\u002Ftree.bio.ed.ac.uk\u002Fsoftware\u002Ffigtree\u002F\n- **iTOL** (web visualization): https:\u002F\u002Fitol.embl.de\u002F\n- **MUSCLE** (alternative aligner): https:\u002F\u002Fwww.drive5.com\u002Fmuscle\u002F\n- **TrimAl** (alignment trimming): https:\u002F\u002Fvicfero.github.io\u002Ftrimal\u002F\n",{"name":5,"license":14,"metadata":23,"description":7},{"version":24,"skill-author":25},"1.0.0","AlterLab","master","f483e54f3ad5f202a77d45f2e57f8d970b71195f","skills_library\u002Falterlab-phylogenetics",2,"https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills","https:\u002F\u002Fgithub.com\u002Froohe","yoou.link","2026-05-19 15:56:07",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add roohe\u002Fagentic-super-skills --skill alterlab-phylogenetics",{"tool":40,"command":41},"bunx","bunx skills add roohe\u002Fagentic-super-skills --skill alterlab-phylogenetics",{"tool":43,"command":44},"pnpm","pnpm dlx skills add roohe\u002Fagentic-super-skills --skill alterlab-phylogenetics","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Falterlab-phylogenetics\u002FSKILL.md",true,[48],{"path":49,"resourceType":50,"resourceTypeDesc":51,"sizeBytes":52,"sourceHtmlUrl":53},"references\u002Fiqtree_inference.md","REFERENCE","参考文档",5391,"https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Falterlab-phylogenetics\u002Freferences\u002Fiqtree_inference.md",[55,62,69,76,83,90],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M73D865CZME2FCMKA4PQM348","zarr-python","Chunked N-D arrays for cloud storage. Compressed arrays, parallel I\u002FO, S3\u002FGCS integration, NumPy\u002FDask\u002FXarray compatible, for large-scale scientific computing pipelines.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fzarr-python\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":18},"01M73D7Z64J4ABWZJD7P44XBBF","youtube-downloader","Download and process YouTube content for research. Use when: downloading competitor videos for analysis; extracting audio for podcasts; getting transcripts for content repurposing; archiving webinars; research content curation","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fyoutube-downloader\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":18},"01M73D7K8778TGZV3GJFR3703D","yc-pitch-deck","Create a compelling startup pitch deck that follows the structure proven to raise billions from top investors. Master the YC and Sequoia formats that get founders funded. Use when: **Fundraising** to create investor pitch decks; **YC application** to structure your narrative; **Demo Day prep** to craft your 2-minute pitch; **Angel investors** to communicate your opportunity; **Partnership pitches** to structure compelling asks","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fyc-pitch-deck\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":18},"01M73D70KJSE0E8Z28YMNNRT04","x-twitter-scraper","Use when the user needs X (Twitter) data or confirmation-gated X actions through Xquik: tweet search, user lookup, follower extraction, media download, monitoring, webhooks, MCP, SDKs, posting, likes, DMs, and profile updates. Requires a Xquik API key. Never ask for X login material.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fx-twitter-scraper\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":18},"01M73D6ED01GV077R7K4NZNFZJ","write-vignette","Create R package vignettes using R Markdown or Quarto. Covers vignette setup, YAML configuration, code chunk options, building and testing, and CRAN requirements for vignettes. Use when adding a Getting Started tutorial, documenting complex workflows spanning multiple functions, creating domain-specific guides, or when CRAN submission requires user-facing documentation beyond function help pages.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fwrite-vignette\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":18},"01M73D69YJR0BK3NFHE0CYG3EF","write-validation-documentation","Write IQ\u002FOQ\u002FPQ validation documentation for computerized systems in regulated environments. Covers protocols, reports, test scripts, deviation handling, and approval workflows. Use when validating R or other software for regulated use, preparing for a regulatory audit, documenting qualification of computing environments, or creating and updating validation protocols and reports for new or re-qualified systems.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fwrite-validation-documentation\u002FSKILL.md",[],[]]