Communitygithub.com

Phylogenetik

Erstellen und Analysieren phylogenetischer Bäume mit MAFFT (Multiples Alignment), IQ-TREE 2 (Maximum Likelihood) und FastTree (schnelles NJ/ML). Visualisierung mit ETE3 oder FigTree. Für Evolutionsanalyse, mikrobielle Genomik, virale Phylodynamik, Proteinfamilienanalyse und molekulare Uhrenstudien.

Was ist Phylogenetik?

Diese Skill bietet eine vollständige Pipeline zur Rekonstruktion der Evolutionsgeschichte biologischer Sequenzen (Gene, Proteine, Genome). Sie umfasst die Erstellung multipler Sequenzalignments mit MAFFT, die Maximum-Likelihood-Bauminferenz mit IQ-TREE 2 (inklusive automatischer Modellauswahl) und die schnelle approximative ML mit FastTree für große Datensätze. Die Visualisierung und Analyse der resultierenden Bäume erfolgt mit der Python-Bibliothek ETE3. Die Pipeline ist ideal für Evolutionsbiologen, Virologen, Mikrobiologen und Bioinformatiker, die verwandtschaftliche Beziehungen untersuchen, virale Ausbreitungswege verfolgen oder molekulare Uhren schätzen möchten. Der Skill unterstützt sowohl Nukleotid- als auch Proteinsequenzen und bietet erweiterte Funktionen wie Trimmen des Alignments, Bootstrap-Unterstützung und Wurzelbildung des Baums.

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

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Was macht Phylogenetik?

Übersicht

Die phylogenetische Analyse rekonstruiert die Evolutionsgeschichte biologischer Sequenzen (Gene, Proteine, Genome), indem sie das Verzweigungsmuster der Abstammung ableitet. Diese Skill deckt die Standard-Pipeline ab:

  1. MAFFT — Multiples Sequenzalignment
  2. IQ-TREE 2 — Maximum-Likelihood-Bauminferenz mit Modellauswahl
  3. FastTree — Schnelle approximative Maximum Likelihood (für große Datensätze)
  4. ETE3 — Python-Bibliothek zur Baummanipulation und -visualisierung

Installation:

# Conda (empfohlen für CLI-Werkzeuge)
conda install -c bioconda mafft iqtree fasttree
uv pip install ete3

# ete3's TreeStyle/NodeStyle-Rendering benötigt das Qt-Backend; Bildausgabe
# benötigt daher PyQt5; Baumparsing und -statistiken funktionieren auch ohne.
uv pip install PyQt5

Wann diese Skill verwenden

Verwende Phylogenetik, wenn:

  • Evolutionsbeziehungen: Welcher Organismus / welches Gen ist am nächsten mit meiner Sequenz verwandt?
  • Virale Phylodynamik: Verfolge die Ausbreitung von Ausbrüchen und schätze Übertragungsdaten
  • Proteinfamilienanalyse: Leite evolutive Beziehungen innerhalb einer Genfamilie ab
  • Erkennung horizontalen Gentransfers: Identifiziere Gene mit nicht übereinstimmenden Arten-/Genbäumen
  • Rekonstruktion von Ahnen-Sequenzen: Leite ancestrale Proteinsequenzen ab
  • Molekulare Uhrenanalyse: Schätze Divergenzdaten mittels zeitlicher Stichproben
  • Begleitanalyse zu GWAS: Platziere Varianten im evolutionären Kontext (z.B. SARS-CoV-2-Varianten)
  • Mikrobiologie: Speziesphylogenie anhand von 16S rRNA oder Kerngenom-Phylogenie

Standardarbeitsablauf

1. Multiples Sequenzalignment mit MAFFT

import subprocess
import os

def run_mafft(input_fasta: str, output_fasta: str, method: str = "auto",
               n_threads: int = 4) -> str:
    """
    Aligniere Sequenzen mit MAFFT.

    Args:
        input_fasta: Pfad zur nicht-alignierten FASTA-Datei
        output_fasta: Pfad für die Ausgabe des Alignments
        method: 'auto' (automatische Auswahl), 'einsi' (genau), 'linsi' (genau, langsam),
                'fftnsi' (mittel), 'fftns' (schnell), 'retree2' (schnell)
        n_threads: Anzahl der CPU-Threads

    Returns:
        Pfad zur alignierten FASTA-Datei
    """
    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 fehlgeschlagen:\n{result.stderr}")

    # Zähle alignierte Sequenzen
    with open(output_fasta) as f:
        n_seqs = sum(1 for line in f if line.startswith('>'))
    print(f"MAFFT: {n_seqs} Sequenzen aligniert → {output_fasta}")

    return output_fasta

# Leitfaden zur MAFFT-Methodenauswahl:
# Wenige Sequenzen (<200), genau: linsi oder einsi
# Viele Sequenzen (<1000), moderat: fftnsi
# Große Datensätze (>1000): fftns oder auto
# Ultra-schnell (>10000): mafft --retree 1

2. Alignment trimmen (optional, aber empfohlen)

def trim_alignment_trimal(aligned_fasta: str, output_fasta: str,
                            method: str = "automated1") -> str:
    """
    Trimme schlecht alignierte Spalten mit TrimAl.

    Methoden:
    - 'automated1': Automatische Heuristik (empfohlen)
    - 'gappyout': Entferne Lücken-Spalten
    - 'strict': Strenger Lücken-Schwellenwert
    """
    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-Warnung: {result.stderr}")
        # Fallback: Verwende das ungetrimmte Alignment
        import shutil
        shutil.copy(aligned_fasta, output_fasta)
    return output_fasta

3. IQ-TREE 2 — Maximum-Likelihood-Baum

def run_iqtree(aligned_fasta: str, output_prefix: str,
                model: str = "TEST", bootstrap: int = 1000,
                n_threads: int = 4, extra_args: list = None) -> dict:
    """
    Erstelle einen Maximum-Likelihood-Baum mit IQ-TREE 2.

    Args:
        aligned_fasta: Alignierte FASTA-Datei
        output_prefix: Präfix für Ausgabedateien
        model: 'TEST' für automatische Modellauswahl, oder spezifisch (z.B. 'GTR+G' für DNA,
               'LG+G4' für Proteine, 'JTT+G' für Proteine)
        bootstrap: Anzahl der Ultra-Schnell-Bootstrap-Replikate (1000 empfohlen)
        n_threads: Anzahl der Threads ('AUTO' zur automatischen Erkennung)
        extra_args: Zusätzliche IQ-TREE-Argumente

    Returns:
        Dict mit Pfaden zu Ausgabedateien
    """
    cmd = [
        "iqtree2",
        "-s", aligned_fasta,
        "--prefix", output_prefix,
        "-m", model,
        "-B", str(bootstrap),   # Ultra-Fast Bootstrap
        "-T", str(n_threads),
        "--redo"                # Überschreibe vorhandene Ergebnisse
    ]

    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 fehlgeschlagen:\n{result.stderr}")

    # Gib Ergebnis der Modellauswahl aus
    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",  # Vollständiger Bericht
        "model": f"{output_prefix}.model.gz",
    }

    print(f"IQ-TREE: Baum gespeichert unter {output_files['tree']}")
    return output_files

# Leitfaden zur IQ-TREE-Modellauswahl:
# DNA:     TEST → GTR+G, HKY+G, TrN+G
# Protein: TEST → LG+G4, WAG+G, JTT+G, Q.pfam+G
# Codon:   TEST → MG+F3X4

# Für zeitliche (molekulare Uhren) Analyse, füge hinzu:
# extra_args = ["--date", "dates.txt", "--clock-test", "--date-CI", "95"]

4. FastTree — Schnelle approximative ML

Für große Datensätze (>1000 Sequenzen), bei denen IQ-TREE zu langsam ist:

def run_fasttree(aligned_fasta: str, output_tree: str,
                  sequence_type: str = "nt", model: str = "gtr",
                  n_threads: int = 4) -> str:
    """
    Erstelle einen schnellen approximativen ML-Baum mit FastTree.

    Args:
        sequence_type: 'nt' für Nukleotide oder 'aa' für Aminosäuren
        model: Für nt: 'gtr' (empfohlen) oder 'jc'; für 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 fehlgeschlagen:\n{result.stderr}")

    print(f"FastTree: Baum gespeichert unter {output_tree}")
    return output_tree

5. Baumanalyse und -visualisierung mit ETE3

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

def load_tree(tree_file: str) -> Tree:
    """Lade eine Newick-Baumdatei."""
    t = Tree(tree_file)
    print(f"Baum: {len(t)} Blätter, {len(list(t.traverse()))} Knoten")
    return t

def basic_tree_stats(t: Tree) -> dict:
    """Berechne grundlegende Baumstatistiken."""
    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:
    """Finde den letzten gemeinsamen Vorfahren einer Menge von Blättern."""
    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:
    """
    Rendere den phylogenetischen Baum als Bild.

    Args:
        t: ETE3 Tree-Objekt
        color_groups: Dict, das Blattname → Farbe abbildet (zum Einfärben von Taxa)
        show_branch_support: Zeige Bootstrap-Werte
    """
    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.show_branch_support = show_branch_support
    ts.mode = "r"  # 'r' = rechteckig, 'c' = kreisförmig

    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"Baum gespeichert unter: {output_file}")

def midpoint_root(t: Tree) -> Tree:
    """Wurzel den Baum am Mittelpunkt (verwenden, wenn keine Außengruppe bekannt ist)."""
    t.set_outgroup(t.get_midpoint_outgroup())
    return t

def prune_tree(t: Tree, keep_leaves: list) -> Tree:
    """Beschneide den Baum, sodass nur die angegebenen Blätter erhalten bleiben."""
    t.prune(keep_leaves, preserve_branch_length=True)
    return t

6. Vollständiges Analysescript

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:
    """
    Vollständige phylogenetische Pipeline: alignieren → trimmen → Baum → visualisieren.

    Args:
        input_fasta: Nicht-alignierte FASTA-Datei
        sequence_type: 'nt' (Nukleotid) oder 'aa' (Aminosäure/Protein)
        use_fasttree: Verwende FastTree anstelle von IQ-TREE (schneller für große Datensätze)
    """
    os.makedirs(output_dir, exist_ok=True)
    prefix = os.path.join(output_dir, "phylo")

    print("=" * 50)
    print("Schritt 1: Multiples Sequenzalignment (MAFFT)")
    aligned = run_mafft(input_fasta, f"{prefix}_aligned.fasta",
                         method="auto", n_threads=n_threads)

    print("\nSchritt 2: Bauminferenz")
    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("\nSchritt 3: Baumanalyse")
    t = Tree(tree_file)
    t = midpoint_root(t)

    stats = basic_tree_stats(t)
    print(f"Baumstatistiken: {stats}")

    print("\nSchritt 4: Visualisierung")
    visualize_tree(t, f"{prefix}_tree.png", show_branch_support=True)

    # Speichere gewurzelten Baum
    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("Phylogenetische Analyse abgeschlossen!")
    print(f"Ergebnisse in: {output_dir}/")
    return results

IQ-TREE-Modellguide

DNA-Modelle

ModellBeschreibungAnwendungsfall
GTR+G4General Time Reversible + GammaFlexibelstes DNA-Modell
HKY+G4Hasegawa-Kishino-Yano + GammaZwei-Raten-Modell (häufig)
TrN+G4Tamura-NeiUngleiche Transitionen
JCJukes-CantorEinfachstes; alle Raten gleich

Protein-Modelle

ModellBeschreibungAnwendungsfall
LG+G4Le-Gascuel + GammaBestes durchschnittliches Proteinmodell
WAG+G4Whelan-GoldmanWeit verbreitet
JTT+G4Jones-Taylor-ThorntonKlassisches Modell
Q.pfam+G4Pfam-trainiertFür Pfam-ähnliche Proteinfamilien
Q.bird+G4VogelspezifischWirbeltierproteine

Tipp: Verwende -m TEST, damit IQ-TREE automatisch das beste Modell auswählt.

Best Practices

  • Alignment-Qualität zuerst: Schlechtes Alignment → unzuverlässige Bäume; überprüfe das Alignment manuell
  • Verwende linsi für kleine (<200 Seq.), fftns oder auto für große Alignments
  • Modellauswahl: Verwende immer -m TEST für IQ-TREE, es sei denn, du hast einen spezifischen Grund
  • Bootstrap: Verwende ≥1000 Ultra-Fast-Bootstraps (-B 1000) für Astunterstützung
  • Wurzel den Baum: Ungewurzelte Bäume können irreführend sein; verwende Außengruppe oder Midpoint-Wurzelung
  • FastTree für >5000 Sequenzen: IQ-TREE wird langsam; FastTree ist 10–100× schneller
  • Lange Alignments trimmen: TrimAl entfernt unzuverlässige Spalten; verbessert die Baumgenauigkeit
  • Prüfe auf Rekombination in viralen/bakteriellen Sequenzen, bevor du Bäume erstellst (RDP4, GARD)

Zusätzliche Ressourcen

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.

Verwandte Skills