Genome_Visualization_Tool / genomics_external.py
GENOMICS-CDDBRG's picture
Upload 7 files
846b701 verified
Raw History Blame Contribute Delete
7.84 kB
"""
genomics_external.py
Thin wrappers around external command-line bioinformatics tools that this
suite cannot reasonably reimplement in Python: Prokka (annotation) and
pyrodigal + CD-HIT (pan-genome protein clustering). The subprocess-calling
code here is adapted from the original tools' own wrappers, which were
already reasonable; what changes is that neither wrapper computes its own
statistics anymore. Every downstream number (GC%, codon usage, ENC, CAI,
assembly stats, pan-genome accumulation curves) comes from genomics_core, so
the annotation workbench and the pan-genome tool report numbers computed the
same way, with the same tested code, as the single-genome tool.
"""
from __future__ import annotations
import shutil
import subprocess
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Tuple
import pandas as pd
try:
import pyrodigal
_HAVE_PYRODIGAL = True
except Exception:
_HAVE_PYRODIGAL = False
import genomics_parsing as gp
# ------------------------------------------------------------------
# Prokka annotation wrapper (kept close to the original app's robust
# full-then---noanno-fallback logic, since that logic was sound)
# ------------------------------------------------------------------
def prokka_available() -> bool:
return shutil.which("prokka") is not None
def _prokka_outputs_present(outdir: Path, prefix: str) -> bool:
for ext in ("gff", "ffn", "faa", "fna"):
if (outdir / f"{prefix}.{ext}").exists() or list(outdir.glob(f"*.{ext}")):
continue
return False
return True
def _run_prokka_once(fasta_path, outdir: Path, prefix: str, genus: str, species: str,
cpus: int, noanno: bool) -> Tuple[bool, str]:
cmd = ["prokka", "--outdir", str(outdir), "--prefix", str(prefix), "--force", "--cpus", str(cpus)]
if genus:
cmd += ["--genus", str(genus)]
if species:
cmd += ["--species", str(species)]
if noanno:
cmd += ["--noanno"]
cmd += [str(fasta_path)]
proc = subprocess.run(cmd, capture_output=True, text=True, check=False)
log = f"COMMAND:\n{' '.join(cmd)}\n\nSTDOUT:\n{proc.stdout}\n\nSTDERR:\n{proc.stderr}"
ok = proc.returncode == 0 and _prokka_outputs_present(outdir, prefix)
return ok, log
def run_prokka(fasta_path, outdir, prefix: str, genus: str = "", species: str = "", cpus: int = 2) -> Dict[str, object]:
"""Run Prokka with one automatic --noanno retry if full annotation fails
(the common cause is a missing/mismatched BLAST toolchain for the product
search step; gene prediction itself is unaffected)."""
outdir = Path(outdir)
outdir.mkdir(parents=True, exist_ok=True)
if not prokka_available():
return {"success": False, "mode": "unavailable", "outdir": str(outdir),
"log": "Prokka is not installed or not on PATH. Install Prokka "
"(e.g. via bioconda: conda install -c bioconda -c conda-forge prokka) "
"or use the Pan-Genome tool's built-in pyrodigal gene caller, "
"which has no external dependency."}
ok, log_full = _run_prokka_once(fasta_path, outdir, prefix, genus, species, cpus, noanno=False)
if ok:
return {"success": True, "mode": "full", "outdir": str(outdir), "log": log_full}
shutil.rmtree(outdir, ignore_errors=True)
outdir.mkdir(parents=True, exist_ok=True)
ok2, log_noanno = _run_prokka_once(fasta_path, outdir, prefix, genus, species, cpus=1, noanno=True)
combined = (
"FIRST ATTEMPT (full annotation) FAILED - retrying with --noanno so gene "
"prediction still completes even if the product-search step cannot run.\n"
+ "=" * 70 + "\n" + log_full + "\n" + "=" * 70 + "\nSECOND ATTEMPT (--noanno):\n" + log_noanno
)
return {"success": ok2, "mode": "noanno" if ok2 else "failed", "outdir": str(outdir), "log": combined}
# ------------------------------------------------------------------
# Pan-genome: pyrodigal gene calling + CD-HIT clustering
# ------------------------------------------------------------------
def predict_proteins(genome_fasta: str, out_faa: str, genome_name: str) -> int:
if not _HAVE_PYRODIGAL:
raise RuntimeError(
"pyrodigal is required for gene calling in the Pan-Genome tool. "
"Install it with: pip install pyrodigal"
)
records = gp.parse_fasta(open(genome_fasta, "rb").read())
if not records:
raise ValueError(f"No sequences found in {genome_fasta}")
finder = pyrodigal.GeneFinder(meta=True)
lines = []
n = 0
for contig in records:
genes = finder.find_genes(contig.seq.encode())
for gene in genes:
protein_seq = gene.translate()
if not protein_seq:
continue
n += 1
header = f"{genome_name}|gene_{n} contig={contig.id};start={gene.begin};end={gene.end};strand={gene.strand}"
lines.append(f">{header}\n{protein_seq}\n")
if n == 0:
raise ValueError(f"No proteins predicted for genome: {genome_name}")
Path(out_faa).write_text("".join(lines))
return n
def cd_hit_available() -> bool:
return shutil.which("cd-hit") is not None
def run_cd_hit(input_fasta: str, output_prefix: str, identity: float = 0.9, coverage: float = 0.8) -> str:
if not cd_hit_available():
raise RuntimeError(
"cd-hit is required for pan-genome protein clustering. Install it with: "
"conda install -c bioconda cd-hit, or apt-get install cd-hit."
)
cmd = ["cd-hit", "-i", str(input_fasta), "-o", str(output_prefix),
"-c", str(identity), "-aS", str(coverage), "-d", "0", "-M", "2000", "-T", "2"]
res = subprocess.run(cmd, capture_output=True, text=True, check=False)
if res.returncode != 0:
raise RuntimeError(f"CD-HIT failed:\nSTDOUT:\n{res.stdout}\nSTDERR:\n{res.stderr}")
clstr = f"{output_prefix}.clstr"
if not Path(clstr).exists():
raise FileNotFoundError("CD-HIT did not produce a .clstr cluster file.")
return clstr
def parse_cd_hit_clusters(clstr_path: str) -> Dict[str, List[str]]:
clusters: Dict[str, List[str]] = defaultdict(list)
current = None
for line in Path(clstr_path).read_text().splitlines():
line = line.strip()
if line.startswith(">Cluster"):
current = line.replace(">", "").strip()
elif current is not None and ">" in line:
seq_id = line.split(">")[1].split("...")[0]
clusters[current].append(seq_id)
return dict(clusters)
def presence_absence_matrix(clusters: Dict[str, List[str]], genome_names: List[str]):
"""Return (presence ndarray [n_clusters x n_genomes], cluster_ids list)."""
import numpy as np
cluster_ids = list(clusters.keys())
presence = np.zeros((len(cluster_ids), len(genome_names)), dtype=int)
genome_index = {g: i for i, g in enumerate(genome_names)}
for ci, cid in enumerate(cluster_ids):
genomes_present = {seq_id.split("|")[0] for seq_id in clusters[cid]}
for g in genomes_present:
if g in genome_index:
presence[ci, genome_index[g]] = 1
return presence, cluster_ids
def classify_clusters(presence, cluster_ids: List[str], n_genomes: int, core_fraction: float = 1.0) -> pd.DataFrame:
min_core = max(1, int(round(core_fraction * n_genomes)))
n_present = presence.sum(axis=1)
categories = []
for n in n_present:
if n >= min_core:
categories.append("core")
elif n == 1:
categories.append("unique")
else:
categories.append("accessory")
return pd.DataFrame({"cluster_id": cluster_ids, "n_genomes_present": n_present, "category": categories})