본문으로 건너뛰기
cccskills
무료GitHub에 공개

biopython-phylo

Use Bio.Phylo to read/write phylogenetic trees and perform visualization and statistics; use when tree parsing/conversion, pruning/rerooting, distance calculation, or plotting is required.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

실행 점수 미검증

설치 방법 보기

포함된 파일(4)

  • SKILL.md6.8 KB
  • biopython-phylo_audit_result_v1.json12.0 KB
  • config/task_config.json2 B
  • references/phylogenetics.md14.1 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Source: https://github.com/aipoch/medical-research-skills

biopython-phylo

When to Use

  • Converting phylogenetic tree files between Newick, NEXUS, and phyloXML formats.
  • Traversing a tree to locate clades, prune taxa, or reroot at a specific node/outgroup.
  • Computing pairwise distances, distance matrices, or basic tree statistics (e.g., branch length summaries).
  • Producing quick tree visualizations as ASCII output for logs/CLI workflows.
  • Generating publication-ready plots of trees using Matplotlib.

Key Features

  • Read and write phylogenetic trees via Bio.Phylo with support for common formats (Newick/NEXUS/phyloXML).
  • Tree manipulation utilities: traversal, clade selection, pruning, and rerooting.
  • Distance computation and simple statistics derived from branch lengths/topology.
  • Visualization options:
    • ASCII rendering for terminal output.
    • Matplotlib-based plotting for figures.

Dependencies

  • biopython>=1.80
  • Optional (for plotting):
    • matplotlib>=3.7

Example Usage

The following example is runnable end-to-end and follows the conventions:

  • Configuration is stored in config/task_config.json.
  • Script is invoked as python scripts/phylo_task.py.
  • All file I/O uses encoding="utf-8".
  • JSON output uses ensure_ascii=False.

config/task_config.json

{
  "input_tree": "data/input_tree.nwk",
  "input_format": "newick",
  "output_tree": "artifacts/output_tree.xml",
  "output_format": "phyloxml",
  "prune_terminals": ["TaxonC"],
  "reroot_outgroup": "TaxonB",
  "ascii_out": "artifacts/tree_ascii.txt",
  "stats_out": "artifacts/tree_stats.json",
  "plot_enabled": true,
  "plot_out": "artifacts/tree_plot.png"
}

scripts/phylo_task.py

import json
import os
from typing import Any, Dict, List, Optional

from Bio import Phylo


def ensure_parent_dir(path: str) -> None:
    parent = os.path.dirname(path)
    if parent:
        os.makedirs(parent, exist_ok=True)


def load_config(path: str) -> Dict[str, Any]:
    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)


def prune_by_names(tree, names: List[str]) -> None:
    # Prune terminals by name if present
    for n in names:
        if tree.find_any(name=n) is not None:
            tree.prune(target=n)


def reroot_by_outgroup_name(tree, outgroup_name: str) -> None:
    outgroup = tree.find_any(name=outgroup_name)
    if outgroup is None:
        raise ValueError(f"Outgroup '{outgroup_name}' not found in tree terminals/clades.")
    tree.root_with_outgroup(outgroup)


def tree_stats(tree) -> Dict[str, Any]:
    terminals = tree.get_terminals()
    nonterminals = tree.get_nonterminals()

    # Collect branch lengths (may include None)
    lengths = []
    for clade in tree.find_clades(order="preorder"):
        if clade.branch_length is not None:
            lengths.append(float(clade.branch_length))

    return {
        "n_terminals": len(terminals),
        "n_nonterminals": len(nonterminals),
        "n_clades_total": len(terminals) + len(nonterminals),
        "branch_length_count": len(lengths),
        "branch_length_sum": sum(lengths) if lengths else 0.0,
        "branch_length_min": min(lengths) if lengths else None,
        "branch_length_max": max(lengths) if lengths else None,
        "branch_length_mean": (sum(lengths) / len(lengths)) if lengths else None,
    }


def write_ascii(tree, out_path: str) -> None:
    ensure_parent_dir(out_path)
    with open(out_path, "w", encoding="utf-8") as f:
        Phylo.draw_ascii(tree, file=f)


def plot_tree(tree, out_path: str) -> None:
    # Optional dependency: matplotlib
    import matplotlib
    matplotlib.use("Agg")  # headless backend
    import matplotlib.pyplot as plt

    ensure_parent_dir(out_path)
    fig = plt.figure(figsize=(10, 6))
    ax = fig.add_subplot(1, 1, 1)
    Phylo.draw(tree, do_show=False, axes=ax)
    fig.tight_layout()
    fig.savefig(out_path, dpi=200)
    plt.close(fig)


def main(config_path: str = "config/task_config.json") -> None:
    cfg = load_config(config_path)

    input_tree = cfg["input_tree"]
    input_format = cfg.get("input_format", "newick")
    output_tree = cfg["output_tree"]
    output_format = cfg.get("output_format", "phyloxml")

    prune_terminals: List[str] = cfg.get("prune_terminals", [])
    reroot_outgroup: Optional[str] = cfg.get("reroot_outgroup")

    ascii_out = cfg.get("ascii_out", "artifacts/tree_ascii.txt")
    stats_out = cfg.get("stats_out", "artifacts/tree_stats.json")

    plot_enabled = bool(cfg.get("plot_enabled", False))
    plot_out = cfg.get("plot_out", "artifacts/tree_plot.png")

    # Read
    tree = Phylo.read(input_tree, input_format)

    # Manipulate
    if prune_terminals:
        prune_by_names(tree, prune_terminals)

    if reroot_outgroup:
        reroot_by_outgroup_name(tree, reroot_outgroup)

    # Write converted tree
    ensure_parent_dir(output_tree)
    Phylo.write(tree, output_tree, output_format)

    # ASCII visualization
    write_ascii(tree, ascii_out)

    # Stats
    ensure_parent_dir(stats_out)
    with open(stats_out, "w", encoding="utf-8") as f:
        json.dump(tree_stats(tree), f, ensure_ascii=False, indent=2)

    # Plot (optional)
    if plot_enabled:
        plot_tree(tree, plot_out)


if __name__ == "__main__":
    main()

Run

python scripts/phylo_task.py

Implementation Details

  • Configuration-first execution: parameters are stored in config/task_config.json as an intermediate artifact; scripts are invoked uniformly via python scripts/<task_name>.py. Avoid stacking many CLI -- arguments; prefer config files.
  • Encoding and JSON output:
    • Always open files with encoding="utf-8".
    • When writing JSON, use ensure_ascii=False to preserve non-ASCII characters.
  • Supported formats:
    • Input/output formats are passed to Phylo.read(...) and Phylo.write(...) (e.g., newick, nexus, phyloxml).
  • Pruning:
    • Pruning is performed by terminal/clade name using tree.prune(target=<name>). Names not found are skipped (or can be treated as errors depending on your policy).
  • Rerooting:
    • Rerooting uses tree.root_with_outgroup(outgroup_clade); the outgroup is located via tree.find_any(name=...).
  • Statistics:
    • Branch lengths may be missing (None); statistics should ignore missing values.
    • Basic counts can be derived from tree.get_terminals() and tree.get_nonterminals().
  • Visualization:
    • ASCII output uses Phylo.draw_ascii(tree, file=...) for deterministic CLI-friendly rendering.
    • Matplotlib plotting uses a non-interactive backend (Agg) for headless environments and saves to an image file.

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Transform lengthy academic papers into concise, structured 250-word abstracts.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

aipoch/medical-research-skills2천2026년 9월 17일 업데이트

Precision editing tool that reduces abstract word count through intelligent compression techniques, maintaining scientific rigor while meeting strict journal and conference requirements.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

aipoch/medical-research-skills2천2026년 9월 17일 업데이트

Refines long medical academic texts into SCI-style unstructured Chinese and English abstracts; use when you need to condense drafts/reports/summaries into bilingual abstracts and generate Summary_Report.md.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

aipoch/medical-research-skills2천2026년 9월 17일 업데이트

Generates submission-ready Elsevier/SCI Highlights from manuscript text or extracted PDF/DOCX/TXT content. Use when a user needs 3-5 concise, evidence-grounded highlight bullets for a research paper, review, meta-analysis, case report, or bioinformatics manuscript.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

aipoch/medical-research-skills2천2026년 9월 17일 업데이트

Generates complete FAERS pharmacovigilance study designs for multi-drug or class-level safety comparison inside one predefined SOC or AE family using active comparators, disproportionality analysis, subgroup characterization, and reviewer-facing evidence control.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

aipoch/medical-research-skills2천2026년 9월 17일 업데이트

Analyze data with `adme-property-predictor` using a reproducible workflow, explicit validation, and structured outputs for review-ready interpretation.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

aipoch/medical-research-skills2천2026년 9월 17일 업데이트

aipoch의 스킬 모두 보기

이 스킬의 문제 신고