scientific-skills/Data Analysis/biopython-phylo/SKILL.md
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.
npx skillsauth add aipoch/medical-research-skills biopython-phyloInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Bio.Phylo with support for common formats (Newick/NEXUS/phyloXML).biopython>=1.80matplotlib>=3.7The following example is runnable end-to-end and follows the conventions:
config/task_config.json.python scripts/phylo_task.py.encoding="utf-8".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.pyimport 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()
python scripts/phylo_task.py
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="utf-8".ensure_ascii=False to preserve non-ASCII characters.Phylo.read(...) and Phylo.write(...) (e.g., newick, nexus, phyloxml).tree.prune(target=<name>). Names not found are skipped (or can be treated as errors depending on your policy).tree.root_with_outgroup(outgroup_clade); the outgroup is located via tree.find_any(name=...).None); statistics should ignore missing values.tree.get_terminals() and tree.get_nonterminals().Phylo.draw_ascii(tree, file=...) for deterministic CLI-friendly rendering.Agg) for headless environments and saves to an image file.tools
Generates complete conventional oncology bulk-transcriptome biomarker and hub-gene research designs from a user-provided cancer type and study direction. Always use this skill whenever a user wants to design, plan, or build a tumor bioinformatics study centered on differential expression, prognostic filtering or risk modeling, PPI-based hub-gene prioritization, diagnostic/prognostic evaluation, clinical association, immune infiltration context, methylation context, and optional tissue or cell validation. Covers five study patterns (signature-first prognostic workflow, hub-gene-first biomarker workflow, hybrid signature-to-hub workflow, immune-context biomarker workflow, translational validation workflow) and always outputs four workload configs (Lite / Standard / Advanced / Publication+) with recommended primary plan, step-by-step workflow, figure plan, validation strategy, minimal executable version, publication upgrade path...
development
Generates complete conventional non-oncology bioinformatics research designs from a user-provided disease context, process-related gene family or biological theme, and validation direction. Use when a study centers on multi-dataset bulk transcriptome integration, DEG analysis, process-gene intersection, enrichment analysis, GSEA, PPI hub-gene prioritization, TF/miRNA regulatory networks, ROC-based biomarker evaluation, and immune infiltration analysis. Covers five study patterns (process-DEG discovery, enrichment/GSEA interpretation, hub-gene prioritization, regulatory-network and immune interpretation, multi-layer public validation) and always outputs Lite / Standard / Advanced / Publication+ with a recommended primary plan, stepwise workflow, figure plan, validation hierarchy, minimal executable version, publication upgrade path, and strictly verified literature retrieval.
tools
Plans confounder control, variable adjustment logic, and bias mitigation strategies at the protocol stage for clinical, epidemiologic, translational, observational, and biomarker studies. Always use this skill when a user needs to identify major confounders, decide which variables should or should not be adjusted for, compare matching/stratification/weighting approaches, anticipate selection or measurement bias, or pressure-test a study design before execution. Focus on bias sensing, causal structure awareness, variable-role classification, and critical design review rather than generic statistical advice.
testing
Generates complete comparative network-toxicology research designs from a user-provided exposure pair, shared toxic phenotype, and validation direction. Use when a study centers on two related exposures under one outcome and needs target collection, shared-vs-specific target decomposition, enrichment, PPI hub prioritization, docking, optional transcriptomic cross-checks, and conservative mechanistic synthesis. Covers five study patterns and always outputs Lite / Standard / Advanced / Publication+ with a recommended primary plan, stepwise workflow, figure plan, validation hierarchy, minimal executable version, publication upgrade path, and strictly verified literature retrieval.