File size: 7,836 Bytes
846b701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
"""
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})