diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,16 +1,25 @@ -import io -import os -import re +from __future__ import annotations + import gzip +import hashlib +import io import json +import logging import math +import os +import platform +import re import shutil -import zipfile -import tempfile import subprocess -from pathlib import Path -from datetime import datetime +import sys +import tempfile +import time +import zipfile from collections import Counter, defaultdict +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple +from urllib.parse import unquote import numpy as np import pandas as pd @@ -19,55 +28,51 @@ import streamlit as st import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt - -# codon_bias_extras.py ships with this package and must sit in the same folder -# as app.py. The earlier embedded string fallback was removed because it was -# fragile to maintain. If the file is missing, the message below tells the user -# exactly what to restore. -try: - import codon_bias_extras as cbe -except ModuleNotFoundError as exc: - raise ModuleNotFoundError( - "codon_bias_extras.py was not found. It must sit in the same folder as app.py. " - "It is included in this package, so copy it back if it was removed." - ) from exc +from matplotlib.patches import Patch # ============================================================ # App configuration +# +# This file is a single-file build. It merges what used to be three files +# (the Streamlit app, codon_bias_extras.py, and genome_figures_extra.py) +# into one module, so the tool has no external local-file dependency and +# deploys the same way from a single script. # ============================================================ -st.set_page_config( - page_title="Bulamarwa Genome Annotation, AMR and Virulence Workbench", - page_icon="🧬", - layout="wide", -) - -cbe.set_pub_style() - -APP_TITLE = "Bulamarwa Genome Annotation, AMR and Virulence Workbench" +APP_NAME = "Bulamarwa" +APP_SUFFIX = "Genomics Suite" +APP_TITLE = f"{APP_NAME} {APP_SUFFIX}" +APP_TAGLINE = "Genome Annotation, AMR, Virulence and Codon Usage Analysis" +APP_VERSION = "2.1.0" +RUN_SCHEMA_VERSION = "1.1" APP_SUBTITLE = ( - "A bacterial genome analysis platform for Prokka annotation, antimicrobial resistance gene screening, " + "A reproducible bacterial genome analysis platform for standardized annotation, antimicrobial resistance gene screening, " "virulence gene screening, secondary metabolite gene cluster detection, genome composition analysis, " "codon usage bias analysis, and publication quality reporting." ) +st.set_page_config( + page_title=f"{APP_TITLE} | {APP_TAGLINE}", + page_icon="\U0001F9EC", + layout="wide", +) + MAX_UPLOAD_MB = int(os.getenv("MAX_UPLOAD_MB", "500")) +MAX_DECOMPRESSED_MB = int(os.getenv("MAX_DECOMPRESSED_MB", "2000")) +COMMAND_TIMEOUT_SECONDS = int(os.getenv("COMMAND_TIMEOUT_SECONDS", "7200")) +APP_LOG_LEVEL = os.getenv("APP_LOG_LEVEL", "INFO").upper() SUPPORTED_EXTENSIONS = {".fa", ".fasta", ".fna", ".fas", ".ffn", ".txt", ".gz"} DEFAULT_VFDB_DB_PREFIX = Path(os.getenv("VFDB_DB_PREFIX", "/opt/vfdb/vfdb_nt")) DEFAULT_AMR_DB_PREFIX = Path(os.getenv("AMR_DB_PREFIX", "/opt/amr/amr_nt")) +DEFAULT_BAKTA_DB = Path(os.getenv("BAKTA_DB", "/opt/bakta/db")) -# Upper limit on the raw annotation files copied into the download archive. -MAX_ARCHIVE_OUTPUT_MB = int(os.getenv("MAX_ARCHIVE_OUTPUT_MB", "300")) - -# File types kept from the Prokka and antiSMASH working directories so that the -# user receives the actual annotation output, not only the parsed tables. -PROKKA_KEEP_EXTENSIONS = { - ".gff", ".gbk", ".ffn", ".faa", ".fna", ".fsa", ".tbl", ".tsv", ".txt", ".sqn", ".log", ".err" -} -ANTISMASH_KEEP_EXTENSIONS = {".gbk", ".json", ".html", ".txt"} -ANTISMASH_SKIP_DIRS = {"css", "js", "images", "fonts", "svg"} +logging.basicConfig( + level=getattr(logging, APP_LOG_LEVEL, logging.INFO), + format="%(asctime)s | %(levelname)s | %(name)s | %(message)s", +) +LOGGER = logging.getLogger("bulamarwa_genomics_suite") GENETIC_CODE = { "TTT":"F","TTC":"F","TTA":"L","TTG":"L","TCT":"S","TCC":"S","TCA":"S","TCG":"S", @@ -87,18 +92,462 @@ for codon, aa in GENETIC_CODE.items(): if aa != "*": AA_TO_CODONS[aa].append(codon) +AA_NAMES = { + "A": "Ala", "R": "Arg", "N": "Asn", "D": "Asp", "C": "Cys", + "Q": "Gln", "E": "Glu", "G": "Gly", "H": "His", "I": "Ile", + "L": "Leu", "K": "Lys", "M": "Met", "F": "Phe", "P": "Pro", + "S": "Ser", "T": "Thr", "W": "Trp", "Y": "Tyr", "V": "Val", +} + DNA_COMPLEMENT = str.maketrans("ACGTNacgtn", "TGCANtgcan") -# The detection tables mix BLAST hits with AMRFinderPlus calls. AMRFinderPlus -# labels its virulence rows "Virulence", so any virulence view must accept both -# that label and the BLAST "VFDB" label. -DATABASE_ALIASES = { - "VFDB": ["VFDB", "Virulence"], - "AMR": ["AMR"], - "Stress_Biocide": ["Stress_Biocide"], +# Shared color palette for all figures in this file, kept consistent across +# both the general genome plots and the codon-bias plots. +PALETTE = { + "primary": "#2c5f8a", "secondary": "#c45a3b", "accent": "#3b8c6e", + "warm": "#d9a23b", "purple": "#7a5ba6", "neutral": "#6b6b6b", + "light": "#d9e2ec", } +def set_pub_style() -> None: + """Shared matplotlib style for publication quality figures.""" + plt.rcParams.update({ + "figure.dpi": 150, + "savefig.dpi": 300, + "font.family": "sans-serif", + "font.sans-serif": ["DejaVu Sans", "Arial", "Helvetica"], + "font.size": 10, + "axes.titlesize": 13, + "axes.titleweight": "bold", + "axes.labelsize": 11, + "axes.edgecolor": "#444444", + "axes.linewidth": 0.9, + "legend.fontsize": 9, + "legend.frameon": False, + "xtick.labelsize": 9, + "ytick.labelsize": 9, + "axes.spines.top": False, + "axes.spines.right": False, + "figure.facecolor": "white", + "axes.facecolor": "white", + }) + + +set_pub_style() + + +# ============================================================ +# Codon usage bias module +# +# This section replaces the former codon_bias_extras.py. It supplies the +# per-gene codon indices (GC1/GC2/GC3/GC12, ENc, PR2 ratios), the ENc plot, +# the neutrality plot, the PR2 bias plot, amino acid composition, and the +# RSCU heatmap. The functions are grouped under the CodonBias class purely +# for a tidy call site (cbe.method(...)); each method is self-contained. +# ============================================================ + +class CodonBias: + """Codon usage bias calculations and figures used across the workbench.""" + + @staticmethod + def read_fasta_pairs(path: Path) -> List[Tuple[str, str]]: + pairs: List[Tuple[str, str]] = [] + header: Optional[str] = None + chunks: List[str] = [] + with open(path, "r", encoding="utf-8", errors="ignore") as fh: + for raw in fh: + line = raw.rstrip() + if not line: + continue + if line.startswith(">"): + if header is not None: + pairs.append((header, "".join(chunks).upper())) + header = line[1:].split()[0] + chunks = [] + else: + chunks.append(line) + if header is not None: + pairs.append((header, "".join(chunks).upper())) + return pairs + + @staticmethod + def _enc_from_counts(codon_counts: Mapping[str, int]) -> float: + """Wright's effective number of codons (ENc) from a codon count dict.""" + family_F = defaultdict(list) + for aa, codons in AA_TO_CODONS.items(): + if len(codons) <= 1: + continue + total = sum(codon_counts.get(c, 0) for c in codons) + if total <= 1: + continue + p2 = sum((codon_counts.get(c, 0) / total) ** 2 for c in codons) + F = (total * p2 - 1) / (total - 1) + if F > 0: + family_F[len(codons)].append(F) + + def mean_f(k): + vals = family_F.get(k, []) + return float(np.mean(vals)) if vals else np.nan + + F2, F3, F4, F6 = mean_f(2), mean_f(3), mean_f(4), mean_f(6) + available = [x for x in [F2, F3, F4, F6] if not np.isnan(x) and x > 0] + if not available: + return np.nan + fallback = float(np.mean(available)) + F2 = F2 if (not np.isnan(F2) and F2 > 0) else fallback + F3 = F3 if (not np.isnan(F3) and F3 > 0) else fallback + F4 = F4 if (not np.isnan(F4) and F4 > 0) else fallback + F6 = F6 if (not np.isnan(F6) and F6 > 0) else fallback + enc = 2 + 9 / F2 + 1 / F3 + 5 / F4 + 3 / F6 + return float(min(max(enc, 20), 61)) + + @classmethod + def per_gene_codon_indices( + cls, + cds_pairs: Sequence[Tuple[str, str]], + input_file: str, + min_codons: int = 100, + ) -> pd.DataFrame: + """Per-gene GC1/GC2/GC3/GC12, ENc, and PR2 ratios. + + Only genes with at least min_codons sense codons are kept, which is + standard practice for stable per-gene ENc estimates. + """ + rows: List[Dict[str, Any]] = [] + for gene_id, raw_seq in cds_pairs: + s = re.sub(r"[^ACGT]", "", str(raw_seq).upper()) + usable = len(s) - (len(s) % 3) + if usable < min_codons * 3: + continue + + counts: Counter = Counter() + g1 = c1 = g2 = c2 = g3 = c3 = a3 = t3 = 0 + n_codons = 0 + for i in range(0, usable, 3): + codon = s[i:i + 3] + if codon not in GENETIC_CODE: + continue + b1, b2, b3 = codon[0], codon[1], codon[2] + if b1 == "G": + g1 += 1 + elif b1 == "C": + c1 += 1 + if b2 == "G": + g2 += 1 + elif b2 == "C": + c2 += 1 + if b3 == "G": + g3 += 1 + elif b3 == "C": + c3 += 1 + elif b3 == "A": + a3 += 1 + elif b3 == "T": + t3 += 1 + if codon not in STOP_CODONS: + counts[codon] += 1 + n_codons += 1 + + if n_codons < min_codons: + continue + + gc1 = 100.0 * (g1 + c1) / n_codons + gc2 = 100.0 * (g2 + c2) / n_codons + gc3 = 100.0 * (g3 + c3) / n_codons + gc12 = (gc1 + gc2) / 2.0 + gc_total = 100.0 * (g1 + c1 + g2 + c2 + g3 + c3) / (3 * n_codons) + enc = cls._enc_from_counts(counts) + + pr2_x = (g3 / (g3 + c3)) if (g3 + c3) else np.nan # G3 / (G3 + C3) + pr2_y = (a3 / (a3 + t3)) if (a3 + t3) else np.nan # A3 / (A3 + T3) + + rows.append({ + "input_file": input_file, + "gene_id": str(gene_id), + "codon_count": n_codons, + "length_nt": n_codons * 3, + "GC_percent": round(gc_total, 4), + "GC1_percent": round(gc1, 4), + "GC2_percent": round(gc2, 4), + "GC3_percent": round(gc3, 4), + "GC12_percent": round(gc12, 4), + "ENc": round(enc, 4) if not np.isnan(enc) else np.nan, + "PR2_G3_over_G3C3": round(pr2_x, 6) if not np.isnan(pr2_x) else np.nan, + "PR2_A3_over_A3T3": round(pr2_y, 6) if not np.isnan(pr2_y) else np.nan, + }) + return pd.DataFrame(rows) + + @staticmethod + def amino_acid_composition_from_cds( + cds_pairs: Sequence[Tuple[str, str]], + input_file: str, + ) -> pd.DataFrame: + counts: Counter = Counter() + total = 0 + for _, raw_seq in cds_pairs: + s = re.sub(r"[^ACGT]", "", str(raw_seq).upper()) + usable = len(s) - (len(s) % 3) + for i in range(0, usable, 3): + aa = GENETIC_CODE.get(s[i:i + 3], "X") + if aa in AA_NAMES: + counts[aa] += 1 + total += 1 + rows = [] + for aa, name in AA_NAMES.items(): + c = counts.get(aa, 0) + rows.append({ + "input_file": input_file, + "amino_acid": aa, + "amino_acid_name": name, + "count": int(c), + "percent": round(100.0 * c / total, 5) if total else 0.0, + }) + return pd.DataFrame(rows).sort_values("percent", ascending=False).reset_index(drop=True) + + @staticmethod + def fig_rscu_heatmap(rscu_df: pd.DataFrame, isolate: str): + sub = rscu_df[rscu_df["input_file"] == isolate].copy() + if sub.empty: + return None + matrix = sub.pivot(index="amino_acid", columns="codon", values="RSCU").fillna(0) + if matrix.empty: + return None + fig, ax = plt.subplots( + figsize=(max(10, matrix.shape[1] * 0.28), max(4.5, matrix.shape[0] * 0.28)), + dpi=300, + ) + im = ax.imshow(matrix.values, aspect="auto", cmap="RdBu_r", vmin=0, vmax=2) + ax.set_title(f"RSCU heatmap: {isolate}") + ax.set_xlabel("Codon") + ax.set_ylabel("Amino acid") + ax.set_xticks(np.arange(matrix.shape[1])) + ax.set_xticklabels(matrix.columns, rotation=90, fontsize=7) + ax.set_yticks(np.arange(matrix.shape[0])) + ax.set_yticklabels(matrix.index, fontsize=8) + cbar = fig.colorbar(im, ax=ax, fraction=0.025, pad=0.01) + cbar.set_label("RSCU") + fig.tight_layout() + return fig + + @staticmethod + def _enc_expected(gc3_fraction: float) -> float: + """Wright's expected ENc under no selection for a given GC3 fraction.""" + s = gc3_fraction + denom = s ** 2 + (1 - s) ** 2 + if denom == 0: + return 61.0 + return 2 + s + 29.0 / denom + + @classmethod + def fig_enc_plot(cls, per_gene_df: pd.DataFrame, isolate: str): + sub = per_gene_df[per_gene_df["input_file"] == isolate].dropna(subset=["ENc", "GC3_percent"]) + if sub.empty: + return None + fig, ax = plt.subplots(figsize=(7.5, 5.5), dpi=300) + x = sub["GC3_percent"].to_numpy(dtype=float) / 100.0 + ax.scatter(x, sub["ENc"], s=16, alpha=0.6, color=PALETTE["primary"], + edgecolor="none", label="Genes") + grid = np.linspace(0.0, 1.0, 300) + expected = [cls._enc_expected(v) for v in grid] + ax.plot(grid, expected, linestyle="--", linewidth=1.4, color=PALETTE["secondary"], + label="Expected (no selection)") + ax.set_title(f"ENc plot: {isolate}") + ax.set_xlabel("GC3 (fraction)") + ax.set_ylabel("Effective number of codons") + ax.set_xlim(0, 1) + ax.set_ylim(20, 61.5) + ax.legend() + ax.grid(alpha=0.25, linestyle="--") + fig.tight_layout() + return fig + + @staticmethod + def fig_neutrality_plot(per_gene_df: pd.DataFrame, isolate: str): + sub = per_gene_df[per_gene_df["input_file"] == isolate].dropna( + subset=["GC3_percent", "GC12_percent"] + ) + if len(sub) < 3: + return None + x = sub["GC3_percent"].to_numpy(dtype=float) / 100.0 + y = sub["GC12_percent"].to_numpy(dtype=float) / 100.0 + slope, intercept = np.polyfit(x, y, 1) + predicted = slope * x + intercept + ss_res = float(np.sum((y - predicted) ** 2)) + ss_tot = float(np.sum((y - y.mean()) ** 2)) + r2 = 1 - ss_res / ss_tot if ss_tot else np.nan + + fig, ax = plt.subplots(figsize=(7.5, 5.5), dpi=300) + ax.scatter(x, y, s=16, alpha=0.6, color=PALETTE["accent"], edgecolor="none", label="Genes") + order = np.argsort(x) + ax.plot(x[order], predicted[order], linestyle="--", linewidth=1.4, color=PALETTE["secondary"], + label=f"Fit: slope = {slope:.3f}, R\u00b2 = {r2:.3f}") + ax.set_title(f"Neutrality plot: {isolate}") + ax.set_xlabel("GC3 (fraction)") + ax.set_ylabel("GC12 (fraction)") + ax.legend() + ax.grid(alpha=0.25, linestyle="--") + fig.tight_layout() + return fig, {"slope": float(slope), "intercept": float(intercept), "r2": float(r2)} + + @staticmethod + def fig_pr2_plot(per_gene_df: pd.DataFrame, isolate: str): + sub = per_gene_df[per_gene_df["input_file"] == isolate].dropna( + subset=["PR2_G3_over_G3C3", "PR2_A3_over_A3T3"] + ) + if sub.empty: + return None + fig, ax = plt.subplots(figsize=(6.2, 6.0), dpi=300) + ax.scatter( + sub["PR2_G3_over_G3C3"], sub["PR2_A3_over_A3T3"], + s=16, alpha=0.6, color=PALETTE["purple"], edgecolor="none", + ) + ax.axvline(0.5, linestyle="--", linewidth=1, color=PALETTE["neutral"]) + ax.axhline(0.5, linestyle="--", linewidth=1, color=PALETTE["neutral"]) + ax.set_title(f"PR2 bias plot: {isolate}") + ax.set_xlabel("G3 / (G3 + C3)") + ax.set_ylabel("A3 / (A3 + T3)") + ax.set_xlim(0, 1) + ax.set_ylim(0, 1) + fig.tight_layout() + return fig + + @staticmethod + def fig_amino_acid_composition(aa_df: pd.DataFrame, isolate: str): + sub = aa_df[aa_df["input_file"] == isolate].sort_values("percent", ascending=False) + if sub.empty: + return None + label_col = "amino_acid_name" if "amino_acid_name" in sub.columns else "amino_acid" + fig, ax = plt.subplots(figsize=(9, 5.5), dpi=300) + ax.bar(sub[label_col], sub["percent"], color=PALETTE["accent"], edgecolor="white", linewidth=0.6) + ax.set_title(f"Amino acid composition: {isolate}") + ax.set_xlabel("Amino acid") + ax.set_ylabel("Percent of residues") + plt.setp(ax.get_xticklabels(), rotation=45, ha="right") + fig.tight_layout() + return fig + + +cbe = CodonBias() + + +# ============================================================ +# Circular genome map and nucleotide composition donut +# +# This section replaces the former genome_figures_extra.py. It adds a +# CGView-style circular genome overview (GC content and GC skew rings) and a +# refined nucleotide composition donut, both wired into the main figure set. +# ============================================================ + +def fig_nucleotide_donut(genome_df: pd.DataFrame): + """Donut chart of A, T, G, C, N proportions across all analysed genomes.""" + if genome_df.empty: + return None + totals = genome_df[["A", "T", "G", "C", "N"]].sum() + values = totals.to_numpy(dtype=float) + if values.sum() <= 0: + return None + labels = list(totals.index) + colors = [PALETTE["primary"], "#5a8fc4", PALETTE["secondary"], PALETTE["warm"], PALETTE["neutral"]] + + fig, ax = plt.subplots(figsize=(6, 6), dpi=300) + wedges, _ = ax.pie( + values, colors=colors, startangle=90, counterclock=False, + wedgeprops={"width": 0.42, "edgecolor": "white", "linewidth": 2}, + ) + total = values.sum() + legend_labels = [f"{label} {v / total * 100:.1f}%" for label, v in zip(labels, values)] + ax.legend(wedges, legend_labels, loc="center", frameon=False, fontsize=11) + ax.set_title("Genome nucleotide composition") + return fig + + +def _smooth(values: np.ndarray, k: int = 3) -> np.ndarray: + if k <= 1 or len(values) < k: + return values + kernel = np.ones(k) / k + return np.convolve(values, kernel, mode="same") + + +def fig_circular_genome(window_df: pd.DataFrame, isolate: str, genome_gc_mean: Optional[float] = None): + """Circular genome map for the longest contig of one isolate. + + Outer ring: windowed GC content deviation from the genome mean. + Inner ring: windowed GC skew, accent color for positive, purple for negative. + Requires at least six GC windows on the longest contig; otherwise returns + None rather than drawing a misleading sparse map. + """ + sub = window_df[window_df["input_file"] == isolate] + if sub.empty: + return None + longest = sub.groupby("contig_id")["end"].max().sort_values(ascending=False).index[0] + sub = sub[sub["contig_id"] == longest].sort_values("midpoint").copy() + if len(sub) < 6: + return None + + n = len(sub) + theta = np.linspace(0, 2 * np.pi, n, endpoint=False) + width = 2 * np.pi / n + + gc = sub["GC_percent"].to_numpy(dtype=float) + gc_mean = genome_gc_mean if genome_gc_mean is not None else float(np.mean(gc)) + gc_dev = _smooth(gc - gc_mean) + skew = _smooth(sub["GC_skew"].to_numpy(dtype=float)) + + fig = plt.figure(figsize=(7.6, 7.6), dpi=300) + ax = fig.add_subplot(111, projection="polar") + ax.set_theta_zero_location("N") + ax.set_theta_direction(-1) + ax.axis("off") + + gc_inner, gc_outer = 2.4, 3.4 + skew_inner, skew_outer = 1.3, 2.2 + + max_dev = max(1e-6, float(np.max(np.abs(gc_dev)))) + for t, d in zip(theta, gc_dev): + h = (abs(d) / max_dev) * (gc_outer - gc_inner) / 2 + base = (gc_inner + gc_outer) / 2 + if d >= 0: + ax.bar(t, h, width=width, bottom=base, color=PALETTE["primary"], edgecolor="none", alpha=0.9) + else: + ax.bar(t, h, width=width, bottom=base - h, color=PALETTE["warm"], edgecolor="none", alpha=0.9) + + max_skew = max(1e-6, float(np.max(np.abs(skew)))) + for t, s in zip(theta, skew): + h = (abs(s) / max_skew) * (skew_outer - skew_inner) / 2 + base = (skew_inner + skew_outer) / 2 + if s >= 0: + ax.bar(t, h, width=width, bottom=base, color=PALETTE["accent"], edgecolor="none", alpha=0.9) + else: + ax.bar(t, h, width=width, bottom=base - h, color=PALETTE["purple"], edgecolor="none", alpha=0.9) + + for r in [(gc_inner + gc_outer) / 2, (skew_inner + skew_outer) / 2]: + ax.plot(np.linspace(0, 2 * np.pi, 200), [r] * 200, color="#bbbbbb", linewidth=0.6, linestyle="--") + + ax.set_ylim(0, gc_outer + 0.3) + + contig_len = int(sub["end"].max()) + for frac in [0, 0.25, 0.5, 0.75]: + ang = frac * 2 * np.pi + ax.plot([ang, ang], [0.9, gc_outer + 0.1], color="#dddddd", linewidth=0.6) + ax.text(ang, gc_outer + 0.25, f"{int(contig_len * frac / 1000)} kb", + ha="center", va="center", fontsize=8, color="#555555") + + ax.text(0, 0, f"{isolate}\n{contig_len / 1e6:.2f} Mb\nGC {gc_mean:.1f}%", + ha="center", va="center", fontsize=10, weight="bold") + + fig.suptitle(f"Circular genome map: {longest}", fontsize=13, weight="bold", y=0.98) + + handles = [ + Patch(color=PALETTE["primary"], label="GC above mean"), + Patch(color=PALETTE["warm"], label="GC below mean"), + Patch(color=PALETTE["accent"], label="GC skew +"), + Patch(color=PALETTE["purple"], label="GC skew -"), + ] + ax.legend(handles=handles, loc="upper right", bbox_to_anchor=(1.18, 1.12), frameon=False, fontsize=8.5) + return fig + + # AMRFinderPlus organism strings. Passing the correct one enables point mutation # calls as well as acquired gene calls. An unknown genus returns an empty string, # which makes AMRFinderPlus run without the organism specific module. @@ -126,14 +575,53 @@ AMRFINDER_ORGANISMS = { } +_AMRFINDER_ORGANISM_CACHE: Optional[set] = None + + +def amrfinder_supported_organisms() -> set: + """Read organism modules from the installed AMRFinderPlus database.""" + global _AMRFINDER_ORGANISM_CACHE + if _AMRFINDER_ORGANISM_CACHE is not None: + return _AMRFINDER_ORGANISM_CACHE + if not command_available("amrfinder"): + _AMRFINDER_ORGANISM_CACHE = set() + return _AMRFINDER_ORGANISM_CACHE + + code, out, err = run_command(["amrfinder", "--list_organisms"], timeout=120) + text = out or err + organisms = set() + if code == 0: + for raw in text.splitlines(): + line = raw.strip() + if not line or line.startswith("#"): + continue + token = line.split()[0] + if re.fullmatch(r"[A-Za-z][A-Za-z0-9_]+", token): + organisms.add(token) + _AMRFINDER_ORGANISM_CACHE = organisms + return organisms + + def supported_amrfinder_organism(genus, species): - g = str(genus).strip().lower() - s = str(species).strip().lower() + genus_text = str(genus).strip() + species_text = str(species).strip() + g = genus_text.lower() + s = species_text.lower() full = f"{g} {s}".strip() - if full in AMRFINDER_ORGANISMS: - return AMRFINDER_ORGANISMS[full] - if g in AMRFINDER_ORGANISMS: - return AMRFINDER_ORGANISMS[g] + + candidate = AMRFINDER_ORGANISMS.get(full) or AMRFINDER_ORGANISMS.get(g, "") + available = amrfinder_supported_organisms() + if candidate and (not available or candidate in available): + return candidate + + normalized_candidates = [ + f"{genus_text}_{species_text}".strip("_"), + genus_text, + ] + available_lower = {value.lower(): value for value in available} + for value in normalized_candidates: + if value.lower() in available_lower: + return available_lower[value.lower()] return "" @@ -174,12 +662,69 @@ def command_available(name: str) -> bool: return shutil.which(name) is not None -def run_command(cmd, cwd=None): +def run_command( + cmd: Sequence[str], + cwd: Optional[Path] = None, + timeout: Optional[int] = None, + env: Optional[Mapping[str, str]] = None, +) -> Tuple[int, str, str]: + """Execute an external command without a shell and with a hard timeout. + + Returning a tuple preserves compatibility with the existing workflow while + adding duration, timeout, and executable validation information to stderr. + """ + if not isinstance(cmd, (list, tuple)) or not cmd: + return 1, "", "Command must be a non-empty sequence of arguments." + args = [str(x) for x in cmd] + executable = args[0] + if shutil.which(executable) is None: + return 127, "", f"Executable not found on PATH: {executable}" + + started = time.monotonic() try: - result = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, check=False) - return result.returncode, result.stdout, result.stderr + result = subprocess.run( + args, + cwd=str(cwd) if cwd is not None else None, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=False, + timeout=timeout or COMMAND_TIMEOUT_SECONDS, + env=dict(os.environ, **dict(env or {})), + shell=False, + ) + duration = time.monotonic() - started + stderr = result.stderr or "" + stderr += f"\n[bulamarwa] elapsed_seconds={duration:.3f}" + return result.returncode, result.stdout or "", stderr + except subprocess.TimeoutExpired as exc: + duration = time.monotonic() - started + stdout = exc.stdout.decode("utf-8", "replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "") + stderr = exc.stderr.decode("utf-8", "replace") if isinstance(exc.stderr, bytes) else (exc.stderr or "") + stderr += ( + f"\nCommand timed out after {timeout or COMMAND_TIMEOUT_SECONDS} seconds. " + f"elapsed_seconds={duration:.3f}" + ) + return 124, stdout, stderr except Exception as exc: - return 1, "", str(exc) + LOGGER.exception("External command failed before completion") + return 1, "", f"{type(exc).__name__}: {exc}" + + +def sha256_path(path: Path, chunk_size: int = 1024 * 1024) -> str: + digest = hashlib.sha256() + with open(path, "rb") as handle: + while True: + block = handle.read(chunk_size) + if not block: + break + digest.update(block) + return digest.hexdigest() + + +def utc_now_iso() -> str: + return datetime.now(timezone.utc).replace(microsecond=0).isoformat() def sanitize_text(text: str, fallback="sample"): @@ -205,66 +750,143 @@ def read_uploaded_to_path(uploaded_file, outdir: Path) -> Path: def decompress_if_needed(path: Path, outdir: Path) -> Path: if not path.name.lower().endswith(".gz"): return path - out = outdir / path.stem - with gzip.open(path, "rb") as fin, open(out, "wb") as fout: - shutil.copyfileobj(fin, fout) + + out = outdir / sanitize_text(path.stem, "decompressed.fasta") + max_bytes = MAX_DECOMPRESSED_MB * 1024 * 1024 + written = 0 + try: + with gzip.open(path, "rb") as fin, open(out, "wb") as fout: + while True: + block = fin.read(1024 * 1024) + if not block: + break + written += len(block) + if written > max_bytes: + raise ValueError( + f"Decompressed input exceeds the configured limit of " + f"{MAX_DECOMPRESSED_MB} MB." + ) + fout.write(block) + except Exception: + out.unlink(missing_ok=True) + raise return out def normalize_fasta(input_path: Path, outdir: Path) -> Path: + """Validate and normalize nucleotide FASTA without silently inventing data.""" output_path = outdir / f"{sanitize_text(input_path.stem)}_normalized.fasta" - seq_count = 0 - saw_header = False + records: List[Tuple[str, str]] = [] + current_header: Optional[str] = None + seq_parts: List[str] = [] - with open(input_path, "r", encoding="utf-8", errors="ignore") as fin, open(output_path, "w", encoding="utf-8") as fout: - for raw in fin: + with open(input_path, "r", encoding="utf-8", errors="replace") as fin: + for line_number, raw in enumerate(fin, start=1): line = raw.strip() if not line: continue if line.startswith(">"): - header = line[1:].strip() or f"sequence_{seq_count + 1}" - header = re.sub(r"\s+", " ", header) - fout.write(f">{header}\n") - saw_header = True - seq_count += 1 - else: - seq = re.sub(r"[^A-Za-z.-]", "", line).upper() - if seq: - fout.write(seq + "\n") + if current_header is not None: + records.append((current_header, "".join(seq_parts))) + current_header = re.sub(r"\s+", " ", line[1:].strip()) + if not current_header: + current_header = f"sequence_{len(records) + 1}" + seq_parts = [] + continue - if not saw_header or seq_count == 0: - raise ValueError("No valid FASTA header was detected. FASTA records must begin with '>'.") + if current_header is None: + raise ValueError( + f"Sequence data were found before the first FASTA header at line {line_number}." + ) + cleaned = re.sub(r"\s+", "", line).upper().replace(".", "N").replace("-", "N") + invalid = sorted(set(cleaned) - set("ACGTNRYKMSWBDHV")) + if invalid: + raise ValueError( + f"Unsupported nucleotide symbol(s) {', '.join(invalid)} at line {line_number}. " + "Accepted IUPAC DNA symbols are ACGTNRYKMSWBDHV." + ) + seq_parts.append(cleaned) + + if current_header is not None: + records.append((current_header, "".join(seq_parts))) + + if not records: + raise ValueError("No FASTA records were detected. Every record must begin with '>'.") + + seen: Counter = Counter() + with open(output_path, "w", encoding="utf-8", newline="\n") as fout: + for index, (header, sequence) in enumerate(records, start=1): + if not sequence: + raise ValueError(f"FASTA record {index} ({header}) contains no sequence.") + primary_id = header.split()[0] + seen[primary_id] += 1 + if seen[primary_id] > 1: + header = f"{primary_id}_duplicate_{seen[primary_id]} " + " ".join(header.split()[1:]) + header = header.strip() + fout.write(f">{header}\n") + for start in range(0, len(sequence), 80): + fout.write(sequence[start:start + 80] + "\n") return output_path -def read_fasta_records(fasta_path: Path): - records = [] - current_id = None +def read_fasta_records(fasta_path: Path) -> List[Dict[str, str]]: + records: List[Dict[str, str]] = [] + current_id: Optional[str] = None current_desc = "" - parts = [] + parts: List[str] = [] - with open(fasta_path, "r", encoding="utf-8", errors="ignore") as f: - for line in f: - line = line.strip() + with open(fasta_path, "r", encoding="utf-8", errors="replace") as handle: + for raw in handle: + line = raw.strip() if not line: continue if line.startswith(">"): if current_id is not None: - records.append({"id": current_id, "description": current_desc, "sequence": "".join(parts).upper()}) + sequence = "".join(parts).upper() + if not sequence: + raise ValueError(f"FASTA record {current_id} contains no sequence.") + records.append({ + "id": current_id, + "description": current_desc, + "sequence": sequence, + }) current_desc = line[1:].strip() current_id = current_desc.split()[0] parts = [] else: - seq = re.sub(r"[^ACGTNRYKMSWBDHVacgtnrykmswbdhv]", "", line).upper() - parts.append(seq) + parts.append(line.upper()) if current_id is not None: - records.append({"id": current_id, "description": current_desc, "sequence": "".join(parts).upper()}) + sequence = "".join(parts).upper() + if not sequence: + raise ValueError(f"FASTA record {current_id} contains no sequence.") + records.append({ + "id": current_id, + "description": current_desc, + "sequence": sequence, + }) return records +def fasta_quality_summary(records: Sequence[Mapping[str, str]], input_file: str) -> pd.DataFrame: + total = sum(len(str(record["sequence"])) for record in records) + ambiguous = sum( + sum(base not in {"A", "C", "G", "T"} for base in str(record["sequence"]).upper()) + for record in records + ) + return pd.DataFrame([{ + "input_file": input_file, + "records": len(records), + "total_bases": total, + "ambiguous_bases": ambiguous, + "ambiguous_percent": round((ambiguous / total * 100) if total else 0.0, 6), + "empty_records": 0, + "duplicate_primary_ids_after_normalization": 0, + }]) + + def reverse_complement(seq: str) -> str: return seq.translate(DNA_COMPLEMENT)[::-1] @@ -282,83 +904,6 @@ def human_bp(n): return f"{n} bp" -def st_image_compat(data, caption=None): - """Display an image across Streamlit versions. - - st.image only gained use_container_width in Streamlit 1.39 (Sept 2024); the - parameter it replaced, use_column_width, was removed in later versions. A - fixed keyword crashes on whichever version does not have it, so this tries - the current name first and falls back to the older one, then to neither. - """ - try: - st.image(data, caption=caption, use_container_width=True) - except TypeError: - try: - st.image(data, caption=caption, use_column_width=True) - except TypeError: - st.image(data, caption=caption) - - -def select_database(hit_df, db_type): - """Return the hit rows belonging to a detection category. - - BLAST writes 'VFDB' and 'AMR'. AMRFinderPlus writes 'Virulence', 'AMR', and - 'Stress_Biocide'. Filtering on a single literal would silently drop rows, so - every category is resolved through DATABASE_ALIASES. - """ - if hit_df is None or hit_df.empty or "database" not in hit_df.columns: - return pd.DataFrame() - labels = DATABASE_ALIASES.get(db_type, [db_type]) - return hit_df[hit_df["database"].isin(labels)].copy() - - -def coverage_for_plot(sub): - """Coverage series for plotting. - - BLAST rows carry query coverage. AMRFinderPlus reports coverage of the - reference sequence only, which is subject coverage, so query coverage is not - defined for those rows and the subject value is used instead. - """ - cov = sub["query_coverage_pct"] if "query_coverage_pct" in sub.columns else pd.Series(dtype=float) - if "subject_coverage_pct" in sub.columns: - cov = cov.reindex(sub.index) if not cov.empty else pd.Series(np.nan, index=sub.index) - cov = cov.fillna(sub["subject_coverage_pct"]) - return pd.to_numeric(cov, errors="coerce") - - -def harvest_directory(src_dir, archive_prefix, keep_ext, store, budget, skip_dirs=()): - """Copy selected result files into an in-memory store for the download ZIP. - - The Prokka and antiSMASH outputs live inside a TemporaryDirectory that is - removed before the archive is written, so the bytes are read here while the - directory still exists. A byte budget stops a very large antiSMASH run from - exhausting memory. - """ - src_dir = Path(src_dir) - if not src_dir.exists(): - return - for path in sorted(src_dir.rglob("*")): - if not path.is_file(): - continue - rel = path.relative_to(src_dir) - if any(part in skip_dirs for part in rel.parts[:-1]): - continue - if keep_ext and path.suffix.lower() not in keep_ext: - continue - try: - size = path.stat().st_size - except OSError: - continue - if budget["used"] + size > budget["limit"]: - budget["skipped"].append(f"{archive_prefix}/{rel.as_posix()}") - continue - try: - store[f"{archive_prefix}/{rel.as_posix()}"] = path.read_bytes() - except OSError: - continue - budget["used"] += size - - # ============================================================ # Genome statistics # ============================================================ @@ -475,6 +1020,101 @@ def window_statistics(records, input_file, window): return pd.DataFrame(rows) +# ============================================================ +# Standardized genome annotation +# ============================================================ + +def bakta_available() -> bool: + return command_available("bakta") + + +def bakta_version() -> str: + if not bakta_available(): + return "Bakta not available." + code, out, err = run_command(["bakta", "--version"], timeout=120) + return (out or err or "Bakta version could not be determined.").strip() + + +def bakta_database_available() -> bool: + return DEFAULT_BAKTA_DB.exists() and any(DEFAULT_BAKTA_DB.iterdir()) + + +def run_bakta( + fasta_path, + outdir, + prefix, + genus, + species, + threads, + locus_tag, + compliant, +): + """Run Bakta when both the executable and a database are available.""" + if not bakta_available(): + return { + "success": False, + "skipped": True, + "engine": "bakta", + "mode": "unavailable", + "log": "Bakta is not available in this environment.", + "outdir": Path(outdir), + } + if not bakta_database_available(): + return { + "success": False, + "skipped": True, + "engine": "bakta", + "mode": "database_unavailable", + "log": f"Bakta database was not detected at {DEFAULT_BAKTA_DB}.", + "outdir": Path(outdir), + } + + outdir = Path(outdir) + outdir.mkdir(parents=True, exist_ok=True) + cmd = [ + "bakta", + "--db", str(DEFAULT_BAKTA_DB), + "--output", str(outdir), + "--prefix", prefix, + "--threads", str(max(1, int(threads))), + "--force", + ] + if str(genus).strip(): + cmd.extend(["--genus", str(genus).strip()]) + if str(species).strip(): + cmd.extend(["--species", str(species).strip()]) + if str(locus_tag).strip(): + cmd.extend(["--locus-tag", sanitize_text(locus_tag).upper()[:24]]) + if compliant: + cmd.append("--compliant") + cmd.append(str(fasta_path)) + + code, out, err = run_command(cmd) + log = "COMMAND:\n" + " ".join(cmd) + "\n\nSTDOUT:\n" + out + "\n\nSTDERR:\n" + err + gff_candidates = list(outdir.glob("*.gff3")) + list(outdir.glob("*.gff")) + ffn_candidates = list(outdir.glob("*.ffn")) + success = code == 0 and bool(gff_candidates) and bool(ffn_candidates) + return { + "success": success, + "skipped": False, + "engine": "bakta", + "mode": "full" if success else "failed", + "log": log, + "outdir": outdir, + } + + +def choose_annotation_engine(requested: str, kingdom: str) -> str: + requested = str(requested).strip() + if requested == "Bakta": + return "Bakta" + if requested == "Prokka": + return "Prokka" + if str(kingdom).lower() == "bacteria" and bakta_available() and bakta_database_available(): + return "Bakta" + return "Prokka" + + # ============================================================ # Prokka annotation (robust: full, then --noanno fallback) # ============================================================ @@ -561,12 +1201,13 @@ def run_prokka(fasta_path, outdir, prefix, genus, species, kingdom, threads, def parse_gff_attributes(attr): - d = {} - for item in str(attr).split(";"): - if "=" in item: - k, v = item.split("=", 1) - d[k] = v - return d + attributes = {} + for item in str(attr).strip().split(";"): + if not item or "=" not in item: + continue + key, value = item.split("=", 1) + attributes[unquote(key.strip())] = unquote(value.strip()) + return attributes def parse_prokka_gff(gff_path, input_file): @@ -625,8 +1266,6 @@ def annotation_summary(feature_df, input_file, genome_length): "hypothetical_percent": 0, "coding_density_percent": 0, "CDS_per_Mb": 0, - "mean_CDS_length": 0, - "median_CDS_length": 0, }]) counts = feature_df["feature_type"].value_counts().to_dict() @@ -720,8 +1359,8 @@ def parse_antismash_results(outdir, prefix, input_file): "bgc_types": ", ".join(products) if products else "unspecified", "n_products": len(products), }) - except Exception: - pass + except Exception as exc: + LOGGER.warning("Could not parse antiSMASH JSON %s: %s", json_path, exc) if not rows: for gbk in sorted(outdir.glob(f"{prefix}*.region*.gbk")): @@ -743,15 +1382,15 @@ def parse_antismash_results(outdir, prefix, input_file): # ============================================================ def db_exists(prefix: Path) -> bool: - """Check for a BLAST nucleotide database. - - Path.with_suffix replaces an existing suffix rather than appending one, so a - versioned prefix such as amr_nt.2024 was previously probed as amr_nt.nsq and - reported as missing. The suffix is therefore appended as text. - """ - possible_suffixes = [".nsq", ".nin", ".nhr", ".00.nsq", ".00.nin", ".00.nhr"] - base = str(prefix) - return any(Path(base + s).exists() for s in possible_suffixes) + """Detect BLAST nucleotide databases in legacy and BLASTDB v5 layouts.""" + prefix = Path(prefix) + candidates = [ + f"{prefix}.nsq", f"{prefix}.nin", f"{prefix}.nhr", + f"{prefix}.ndb", f"{prefix}.not", f"{prefix}.ntf", f"{prefix}.nto", + f"{prefix}.00.nsq", f"{prefix}.00.nin", f"{prefix}.00.nhr", + f"{prefix}.00.ndb", f"{prefix}.00.not", f"{prefix}.00.ntf", f"{prefix}.00.nto", + ] + return any(Path(candidate).exists() for candidate in candidates) def build_temp_blast_db(reference_upload, outdir: Path, db_name: str): @@ -794,25 +1433,20 @@ def run_blastn(query_fasta, db_prefix, output_tsv, evalue, max_targets, threads, "-db", str(db_prefix), "-evalue", str(evalue), "-max_target_seqs", str(max_targets), - "-num_threads", str(threads), + "-num_threads", str(max(1, int(threads))), + "-dust", "yes", + "-soft_masking", "true", "-outfmt", "6 qseqid sseqid stitle pident length mismatch gapopen qstart qend sstart send evalue bitscore qlen slen", "-out", str(output_tsv), ] code, out, err = run_command(cmd) + log = "COMMAND:\n" + " ".join(cmd) + "\n\nSTDOUT:\n" + out + "\n\nSTDERR:\n" + err if code != 0: - raise RuntimeError(f"BLASTN failed.\nCommand: {' '.join(cmd)}\nSTDERR:\n{err}\nSTDOUT:\n{out}") + raise RuntimeError(f"BLASTN failed.\n{log}") + return log def parse_reference_header(stitle, db_type): - """Extract gene symbol, product, organism and accession from a reference title. - - VFDB nucleotide headers look like: - VFG000676(gb|AAD32411) (plc) phospholipase C [Listeria monocytogenes EGD-e] - The gene symbol is the first parenthesised group after the identifier. The - earlier code took the first whitespace token, which contains a pipe character - and therefore failed the symbol pattern, so every VFDB hit was labelled - Unknown. - """ title = re.sub(r"\s+", " ", str(stitle).strip()) organism = "Unknown" accession = "Unknown" @@ -835,16 +1469,8 @@ def parse_reference_header(stitle, db_type): gene_symbol = re.sub(r"[^A-Za-z0-9_()./-]", "", candidate) or accession product = title2 else: - gene_symbol = "Unknown" - m_gene = re.match(r"^\S+\s+\(([^)]+)\)", title2) - if m_gene: - symbol = m_gene.group(1).strip() - if re.fullmatch(r"[A-Za-z0-9_.()/\\-]{1,50}", symbol): - gene_symbol = symbol - if gene_symbol == "Unknown": - first = tokens[0] if tokens else "Unknown" - if re.fullmatch(r"[A-Za-z0-9_.()/-]{2,50}", first): - gene_symbol = first + first = tokens[0] if tokens else "Unknown" + gene_symbol = first if re.fullmatch(r"[A-Za-z0-9_.()/-]{2,50}", first) else "Unknown" product = title2 return gene_symbol, product, organism, accession @@ -891,7 +1517,20 @@ def infer_functional_group(product, db_type): return "Other or unclassified" -def load_and_filter_blast(blast_tsv, input_file, db_type, min_identity, min_query_cov, min_subject_cov): +def load_and_filter_blast( + blast_tsv, + input_file, + db_type, + min_identity, + min_reference_coverage, + min_alignment_bp=0, +): + """Filter nucleotide database hits using reference-gene coverage. + + The query is an assembled genome contig. Therefore, alignment length divided + by the full contig length is not a valid gene-detection filter. The relevant + completeness measure is coverage of the reference AMR or virulence sequence. + """ cols = [ "qseqid", "sseqid", "stitle", "pident", "length", "mismatch", "gapopen", "qstart", "qend", "sstart", "send", "evalue", "bitscore", "qlen", "slen" @@ -902,34 +1541,53 @@ def load_and_filter_blast(blast_tsv, input_file, db_type, min_identity, min_quer df = pd.read_csv(blast_tsv, sep="\t", header=None, names=cols) - for c in ["pident", "length", "mismatch", "gapopen", "qstart", "qend", "sstart", "send", "evalue", "bitscore", "qlen", "slen"]: - df[c] = pd.to_numeric(df[c], errors="coerce") + numeric_cols = [ + "pident", "length", "mismatch", "gapopen", "qstart", "qend", + "sstart", "send", "evalue", "bitscore", "qlen", "slen", + ] + for column in numeric_cols: + df[column] = pd.to_numeric(df[column], errors="coerce") + + df["contig_coverage_pct"] = ( + df["length"] / df["qlen"].replace(0, np.nan) * 100 + ).round(3) + df["reference_coverage_pct"] = ( + df["length"] / df["slen"].replace(0, np.nan) * 100 + ).round(3) - df["query_coverage_pct"] = (df["length"] / df["qlen"] * 100).round(3) - df["subject_coverage_pct"] = (df["length"] / df["slen"] * 100).round(3) + # Backward-compatible aliases retained for existing output consumers. + df["query_coverage_pct"] = df["contig_coverage_pct"] + df["subject_coverage_pct"] = df["reference_coverage_pct"] df = df[ - (df["pident"] >= min_identity) & - (df["query_coverage_pct"] >= min_query_cov) & - (df["subject_coverage_pct"] >= min_subject_cov) + (df["pident"] >= float(min_identity)) + & (df["reference_coverage_pct"] >= float(min_reference_coverage)) + & (df["length"] >= int(min_alignment_bp)) ].copy() if df.empty: return df - parsed = df["stitle"].apply(lambda x: parse_reference_header(x, db_type)) - df["gene_symbol"] = [x[0] for x in parsed] - df["product_name"] = [x[1] for x in parsed] - df["source_organism"] = [x[2] for x in parsed] - df["reference_accession"] = [x[3] for x in parsed] - df["functional_group"] = df["product_name"].apply(lambda x: infer_functional_group(x, db_type)) + parsed = df["stitle"].apply(lambda value: parse_reference_header(value, db_type)) + df["gene_symbol"] = [value[0] for value in parsed] + df["product_name"] = [value[1] for value in parsed] + df["source_organism"] = [value[2] for value in parsed] + df["reference_accession"] = [value[3] for value in parsed] + df["functional_group"] = df["product_name"].apply( + lambda value: infer_functional_group(value, db_type) + ) df["database"] = db_type df["input_file"] = input_file - df["detection_source"] = f"BLASTN against {db_type} database" - df["coverage_basis"] = "query and subject" + df["detection_source"] = f"BLASTN {db_type}" - df = df.sort_values(["bitscore", "pident", "query_coverage_pct"], ascending=False) - df = df.drop_duplicates(subset=["input_file", "qseqid", "sseqid", "database"], keep="first") + df = df.sort_values( + ["bitscore", "pident", "reference_coverage_pct"], + ascending=[False, False, False], + ) + df = df.drop_duplicates( + subset=["input_file", "qseqid", "sseqid", "database"], + keep="first", + ) return df @@ -1018,13 +1676,7 @@ def _first_existing_col(df, candidates): def parse_amrfinderplus_output(output_tsv, input_file): """Convert AMRFinderPlus TSV output into the same long format used for the - virulence and AMR tables in this app. - - AMRFinderPlus reports percent coverage of the reference sequence, which is - subject coverage. There is no query coverage, because the query is a whole - contig, so query_coverage_pct is left undefined rather than being filled with - the reference value. - """ + virulence and AMR tables in this app.""" output_tsv = Path(output_tsv) if not output_tsv.exists() or output_tsv.stat().st_size == 0: return pd.DataFrame() @@ -1102,6 +1754,8 @@ def parse_amrfinderplus_output(output_tsv, input_file): "bitscore": np.nan, "qlen": np.nan, "slen": np.nan, + "contig_coverage_pct": np.nan, + "reference_coverage_pct": coverage, "query_coverage_pct": np.nan, "subject_coverage_pct": coverage, "gene_symbol": gene, @@ -1112,7 +1766,6 @@ def parse_amrfinderplus_output(output_tsv, input_file): "database": database, "input_file": input_file, "detection_source": "NCBI AMRFinderPlus --plus", - "coverage_basis": "reference sequence", "element_type": element_type, "element_subtype": element_subtype, "class": cls, @@ -1128,58 +1781,62 @@ def parse_amrfinderplus_output(output_tsv, input_file): # ============================================================ def find_orfs(records, input_file, min_aa=90, max_orfs_per_contig=10000): + """Linear-time six-frame fallback ORF prediction. + + Annotator-derived CDS should be preferred. This fallback is intentionally + conservative and reports only the first complete ORF between a start and + in-frame stop codon. + """ rows = [] for rec in records: - seq = rec["sequence"].upper() - seq_len = len(seq) + forward = rec["sequence"].upper() + seq_len = len(forward) - def scan(s, strand): + def scan(sequence, strand): found = 0 for frame in range(3): - i = frame - while i <= len(s) - 3 and found < max_orfs_per_contig: - codon = s[i:i + 3] - if codon in START_CODONS: - j = i + 3 - hit = False - while j <= len(s) - 3: - stop = s[j:j + 3] - if stop in STOP_CODONS: - nt_len = j + 3 - i - aa_len = nt_len // 3 - if aa_len >= min_aa: - if strand == 1: - start, end = i + 1, j + 3 - orf_seq = s[i:j + 3] - else: - start, end = seq_len - (j + 3) + 1, seq_len - i - orf_seq = reverse_complement(s[i:j + 3]) - rows.append({ - "input_file": input_file, - "contig_id": rec["id"], - "orf_id": f"{rec['id']}_ORF_{strand}_{start}_{end}", - "start": start, - "end": end, - "strand": strand, - "length_nt": nt_len, - "length_aa": aa_len, - "sequence": orf_seq, - }) - found += 1 - i = j + 3 - hit = True + current_start = None + for position in range(frame, len(sequence) - 2, 3): + codon = sequence[position:position + 3] + if current_start is None: + if codon in START_CODONS: + current_start = position + continue + + if codon in STOP_CODONS: + nt_len = position + 3 - current_start + aa_len = nt_len // 3 + if aa_len >= int(min_aa): + if strand == 1: + start = current_start + 1 + end = position + 3 + orf_seq = sequence[current_start:position + 3] + else: + start = seq_len - (position + 3) + 1 + end = seq_len - current_start + orf_seq = reverse_complement( + sequence[current_start:position + 3] + ) + rows.append({ + "input_file": input_file, + "contig_id": rec["id"], + "orf_id": f"{rec['id']}_ORF_{strand}_{start}_{end}", + "start": start, + "end": end, + "strand": strand, + "length_nt": nt_len, + "length_aa": aa_len, + "sequence": orf_seq, + "prediction_source": "internal_complete_orf_fallback", + }) + found += 1 + if found >= int(max_orfs_per_contig): break - j += 3 - # Resume at the codon directly after the stop. The earlier - # code fell through to i += 3 as well, which stepped past - # that codon and lost any ORF starting immediately after. - if hit: - continue - i += 3 + current_start = None - scan(seq, 1) - scan(reverse_complement(seq), -1) + scan(forward, 1) + scan(reverse_complement(forward), -1) return pd.DataFrame(rows) @@ -1276,25 +1933,27 @@ def load_cai_weights(uploaded): def compute_cai(codon_counts, weights): - logs = [] + weighted_log_sum = 0.0 + included_codons = 0 for codon, count in codon_counts.items(): - w = float(weights.get(codon, 0)) - if w > 0: - logs.extend([math.log(w)] * int(count)) - if not logs: - return 0 - return round(float(math.exp(sum(logs) / len(logs))), 6) + weight = float(weights.get(codon, 0)) + if weight > 0 and int(count) > 0: + weighted_log_sum += int(count) * math.log(weight) + included_codons += int(count) + if included_codons == 0: + return 0.0 + return round(float(math.exp(weighted_log_sum / included_codons)), 6) def codon_analysis(records, input_file, min_orf_aa, cai_weights, cds_pairs=None): - """Codon analysis. Uses Prokka CDS (cds_pairs) when available, otherwise the - naive ORF finder. Returns orf table, RSCU table, codon stats, per-gene + """Codon analysis. Uses annotator CDS (cds_pairs) when available, otherwise + the naive ORF finder. Returns orf table, RSCU table, codon stats, per-gene indices, and amino acid composition.""" if cds_pairs: seqs = [s for _, s in cds_pairs] orf_df = pd.DataFrame([ {"input_file": input_file, "gene_id": gid, "length_nt": len(s), - "length_aa": len(s) // 3, "source": "prokka_cds"} + "length_aa": len(s) // 3, "source": "annotator_cds"} for gid, s in cds_pairs ]) else: @@ -1329,72 +1988,114 @@ def codon_analysis(records, input_file, min_orf_aa, cai_weights, cds_pairs=None) return orf_df, rscu, stats, per_gene, aa_comp -def read_prokka_cds(prokka_outdir, prefix): - """Return list of (gene_id, sequence) from the Prokka .ffn file if present.""" - outdir = Path(prokka_outdir) - ffn = outdir / f"{prefix}.ffn" - if not ffn.exists(): - matches = list(outdir.glob("*.ffn")) - if not matches: - return None - ffn = matches[0] +def find_annotation_file(outdir, prefix, suffixes): + outdir = Path(outdir) + for suffix in suffixes: + candidate = outdir / f"{prefix}{suffix}" + if candidate.exists(): + return candidate + for suffix in suffixes: + matches = sorted(outdir.glob(f"*{suffix}")) + if matches: + return matches[0] + return None + + +def read_annotation_cds(annotation_outdir, prefix): + """Return coding nucleotide sequences from Bakta or Prokka output.""" + ffn = find_annotation_file(annotation_outdir, prefix, [".ffn"]) + if ffn is None: + return None try: return cbe.read_fasta_pairs(ffn) - except Exception: + except Exception as exc: + LOGGER.warning("Could not parse annotation CDS file %s: %s", ffn, exc) return None +# Backward-compatible function name for downstream users. +read_prokka_cds = read_annotation_cds + + # ============================================================ # Summary tables # ============================================================ def build_detection_summary(hit_df, db_type): - columns = ["database", "functional_group", "number_of_hits", "unique_genes", "mean_identity_pct", "mean_query_coverage_pct", "mean_subject_coverage_pct"] - if hit_df is None or hit_df.empty: + columns = [ + "database", "functional_group", "number_of_hits", "unique_genes", + "mean_identity_pct", "mean_reference_coverage_pct", + ] + if hit_df.empty: return pd.DataFrame(columns=columns) - sub = select_database(hit_df, db_type) + if db_type == "VFDB": + sub = hit_df[hit_df["database"].isin(["VFDB", "Virulence"])].copy() + else: + sub = hit_df[hit_df["database"] == db_type].copy() if sub.empty: return pd.DataFrame(columns=columns) - out = sub.groupby("functional_group").agg( + coverage_col = ( + "reference_coverage_pct" + if "reference_coverage_pct" in sub.columns + else "subject_coverage_pct" + ) + out = sub.groupby("functional_group", dropna=False).agg( number_of_hits=("functional_group", "size"), unique_genes=("gene_symbol", pd.Series.nunique), mean_identity_pct=("pident", "mean"), - mean_query_coverage_pct=("query_coverage_pct", "mean"), - mean_subject_coverage_pct=("subject_coverage_pct", "mean"), + mean_reference_coverage_pct=(coverage_col, "mean"), ).reset_index() out.insert(0, "database", db_type) - for col in ["mean_identity_pct", "mean_query_coverage_pct", "mean_subject_coverage_pct"]: - out[col] = out[col].round(3) + for column in ["mean_identity_pct", "mean_reference_coverage_pct"]: + out[column] = out[column].round(3) - return out.sort_values("number_of_hits", ascending=False) + return out.sort_values( + ["number_of_hits", "unique_genes"], + ascending=[False, False], + ) def format_hit_table(hit_df): - keep = [ - "input_file", "database", "detection_source", "contig_id", "gene_symbol", "product_name", "functional_group", - "identity_pct", "query_coverage_pct", "subject_coverage_pct", "coverage_basis", "bitscore", "evalue", - "reference_organism", "reference_accession", "query_start", "query_end" + columns = [ + "input_file", "database", "detection_source", "contig_id", "gene_symbol", + "product_name", "functional_group", "identity_pct", + "reference_coverage_pct", "contig_coverage_pct", "alignment_length_bp", + "bitscore", "evalue", "reference_organism", "reference_accession", + "query_start", "query_end", "reference_start", "reference_end", ] - - if hit_df is None or hit_df.empty: - return pd.DataFrame(columns=keep) + if hit_df.empty: + return pd.DataFrame(columns=columns) out = hit_df.rename(columns={ "qseqid": "contig_id", "pident": "identity_pct", + "length": "alignment_length_bp", "source_organism": "reference_organism", "qstart": "query_start", "qend": "query_end", + "sstart": "reference_start", + "send": "reference_end", }).copy() - for col in keep: - if col not in out.columns: - out[col] = np.nan - - return out[keep].sort_values(["input_file", "database", "bitscore", "identity_pct"], ascending=[True, True, False, False]) + if "reference_coverage_pct" not in out: + out["reference_coverage_pct"] = out.get("subject_coverage_pct", np.nan) + if "contig_coverage_pct" not in out: + out["contig_coverage_pct"] = out.get("query_coverage_pct", np.nan) + if "detection_source" not in out: + out["detection_source"] = out["database"].astype(str) + + for column in columns: + if column not in out: + out[column] = np.nan + + return out[columns].sort_values( + ["input_file", "database", "bitscore", "identity_pct"], + ascending=[True, True, False, False], + na_position="last", + ) def build_isolate_summary(genome_df, annotation_df, hit_df, codon_df): @@ -1403,14 +2104,17 @@ def build_isolate_summary(genome_df, annotation_df, hit_df, codon_df): if not annotation_df.empty: base = base.merge(annotation_df, on="input_file", how="left") - for db_type in ["VFDB", "AMR", "Stress_Biocide"]: - sub = select_database(hit_df, db_type) - if sub.empty: + for db_type in ["VFDB", "AMR"]: + if hit_df.empty: base[f"{db_type}_hits"] = 0 base[f"{db_type}_unique_genes"] = 0 base[f"{db_type}_functional_groups"] = 0 base[f"{db_type}_mean_identity_pct"] = 0.0 else: + if db_type == "VFDB": + sub = hit_df[hit_df["database"].isin(["VFDB", "Virulence"])] + else: + sub = hit_df[hit_df["database"] == db_type] grouped = sub.groupby("input_file").agg( hits=("gene_symbol", "size"), unique_genes=("gene_symbol", pd.Series.nunique), @@ -1425,6 +2129,9 @@ def build_isolate_summary(genome_df, annotation_df, hit_df, codon_df): }) base = base.merge(grouped, on="input_file", how="left") + if not codon_df.empty: + base = base.merge(codon_df, on="input_file", how="left") + for col in base.columns: if col.endswith("_hits") or col.endswith("_unique_genes") or col.endswith("_functional_groups"): base[col] = base[col].fillna(0).astype(int) @@ -1433,9 +2140,6 @@ def build_isolate_summary(genome_df, annotation_df, hit_df, codon_df): if col.endswith("_mean_identity_pct"): base[col] = base[col].fillna(0).round(3) - if not codon_df.empty: - base = base.merge(codon_df, on="input_file", how="left") - return base.fillna(0) @@ -1444,11 +2148,10 @@ def generate_report_paragraph(row): f"The analysed genome file {row.get('input_file')} contained {int(row.get('contigs', 0))} contig(s) " f"with a total size of {int(row.get('total_bases', 0)):,} bp, GC content of {float(row.get('GC_percent', 0)):.2f}%, " f"N50 of {int(row.get('N50', 0)):,} bp and L50 of {int(row.get('L50', 0))}. " - f"Prokka annotation identified {int(row.get('CDS', 0))} CDS, {int(row.get('rRNA', 0))} rRNA, " + f"Standardized annotation identified {int(row.get('CDS', 0))} CDS, {int(row.get('rRNA', 0))} rRNA, " f"{int(row.get('tRNA', 0))} tRNA, and {int(row.get('hypothetical_proteins', 0))} hypothetical proteins. " f"Virulence screening detected {int(row.get('VFDB_hits', 0))} virulence associated hit(s), " f"while antimicrobial resistance screening detected {int(row.get('AMR_hits', 0))} AMR associated hit(s) after applying the selected identity and coverage thresholds. " - f"A further {int(row.get('Stress_Biocide_hits', 0))} stress, biocide or metal resistance associated hit(s) were recorded. " f"Codon usage analysis detected {int(row.get('predicted_ORFs_used', 0))} predicted ORF(s), " f"with GC3 of {float(row.get('GC3_percent', 0)):.2f}% and ENc of {float(row.get('effective_number_of_codons_ENc', 0)):.2f}. " f"These outputs provide genome composition, annotation, AMR, virulence, and codon bias evidence for downstream comparative genomics and methodological reporting." @@ -1478,40 +2181,12 @@ def fig_to_pdf_bytes(fig): return buf.read() -def render_figures(figures): - """Serialise every figure to PNG and PDF bytes, then close it. - - Matplotlib keeps pyplot figures open until they are closed explicitly and - warns beyond twenty open figures. A five isolate run builds roughly sixty, so - each figure is rendered to bytes here and released immediately rather than - being held in memory for the rest of the session. - """ - rendered = {} - for name, fig in figures.items(): - try: - rendered[name] = {"png": fig_to_png_bytes(fig), "pdf": fig_to_pdf_bytes(fig)} - finally: - plt.close(fig) - return rendered - - -def fig_nucleotide_composition(genome_df): - totals = genome_df[["A", "T", "G", "C", "N"]].sum() - title = "Genome nucleotide composition" - if "input_file" in genome_df.columns and genome_df["input_file"].nunique() > 1: - title = f"Pooled nucleotide composition ({genome_df['input_file'].nunique()} genomes)" - fig, ax = plt.subplots(figsize=(6.5, 5.2), dpi=300) - ax.pie(totals.values, labels=totals.index, autopct="%1.1f%%", startangle=90) - ax.set_title(title, fontsize=13, weight="bold") - return fig - - def fig_contig_distribution(contig_df): if contig_df.empty: return None fig, ax = plt.subplots(figsize=(8, 5), dpi=300) - ax.hist(contig_df["contig_length"], bins=30, color="#2c5f8a", edgecolor="white") - ax.set_title("Contig length distribution", fontsize=13, weight="bold") + ax.hist(contig_df["contig_length"], bins=30, color=PALETTE["primary"], edgecolor="white") + ax.set_title("Contig length distribution") ax.set_xlabel("Contig length bp") ax.set_ylabel("Frequency") style_axes(ax) @@ -1524,8 +2199,8 @@ def fig_top_contigs(contig_df): plot = contig_df.sort_values("contig_length", ascending=False).head(30).copy() plot["rank"] = range(1, len(plot) + 1) fig, ax = plt.subplots(figsize=(8, 5), dpi=300) - ax.bar(plot["rank"], plot["contig_length"], color="#2c5f8a", edgecolor="white") - ax.set_title("Top contig lengths", fontsize=13, weight="bold") + ax.bar(plot["rank"], plot["contig_length"], color=PALETTE["primary"], edgecolor="white") + ax.set_title("Top contig lengths") ax.set_xlabel("Contig rank") ax.set_ylabel("Length bp") style_axes(ax) @@ -1537,8 +2212,8 @@ def fig_gc_by_contig(contig_df): return None plot = contig_df.sort_values("contig_length", ascending=False).head(60).copy() fig, ax = plt.subplots(figsize=(8, 5), dpi=300) - ax.scatter(plot["contig_length"], plot["GC_percent"], alpha=0.8, color="#3b8c6e") - ax.set_title("Contig length and GC content", fontsize=13, weight="bold") + ax.scatter(plot["contig_length"], plot["GC_percent"], alpha=0.8, color=PALETTE["accent"]) + ax.set_title("Contig length and GC content") ax.set_xlabel("Contig length bp") ax.set_ylabel("GC content percent") style_axes(ax) @@ -1551,8 +2226,8 @@ def fig_feature_counts(feature_df): counts = feature_df["feature_type"].value_counts().reset_index() counts.columns = ["feature_type", "count"] fig, ax = plt.subplots(figsize=(8, 5), dpi=300) - ax.bar(counts["feature_type"], counts["count"], color="#2c5f8a", edgecolor="white") - ax.set_title("Annotated genomic feature classes", fontsize=13, weight="bold") + ax.bar(counts["feature_type"], counts["count"], color=PALETTE["primary"], edgecolor="white") + ax.set_title("Annotated genomic feature classes") ax.set_xlabel("Feature type") ax.set_ylabel("Count") ax.tick_params(axis="x", rotation=45) @@ -1567,8 +2242,8 @@ def fig_cds_length(feature_df): if cds.empty: return None fig, ax = plt.subplots(figsize=(8, 5), dpi=300) - ax.hist(cds["length_bp"].dropna(), bins=40, color="#2c5f8a", edgecolor="white") - ax.set_title("CDS length distribution", fontsize=13, weight="bold") + ax.hist(cds["length_bp"].dropna(), bins=40, color=PALETTE["primary"], edgecolor="white") + ax.set_title("CDS length distribution") ax.set_xlabel("CDS length bp") ax.set_ylabel("Frequency") style_axes(ax) @@ -1586,20 +2261,20 @@ def fig_hypothetical_status(feature_df): functional = int(len(cds) - hypothetical) fig, ax = plt.subplots(figsize=(6.5, 5), dpi=300) ax.bar(["Functional CDS", "Hypothetical CDS"], [functional, hypothetical], - color=["#3b8c6e", "#c45a3b"], edgecolor="white") - ax.set_title("Functional annotation status", fontsize=13, weight="bold") + color=[PALETTE["accent"], PALETTE["secondary"]], edgecolor="white") + ax.set_title("Functional annotation status") ax.set_ylabel("Number of CDS") style_axes(ax) return fig def fig_detection_groups(summary_df, title): - if summary_df is None or summary_df.empty: + if summary_df.empty: return None plot = summary_df.head(15).copy() fig, ax = plt.subplots(figsize=(9, 5.5), dpi=300) - ax.bar(plot["functional_group"], plot["number_of_hits"], color="#c45a3b", edgecolor="white") - ax.set_title(title, fontsize=13, weight="bold") + ax.bar(plot["functional_group"], plot["number_of_hits"], color=PALETTE["secondary"], edgecolor="white") + ax.set_title(title) ax.set_xlabel("Functional group") ax.set_ylabel("Number of hits") ax.tick_params(axis="x", rotation=45, labelsize=9) @@ -1607,28 +2282,32 @@ def fig_detection_groups(summary_df, title): return fig -def fig_identity_coverage(hit_df, db_type, title=None): - sub = select_database(hit_df, db_type) +def fig_identity_coverage(hit_df, db_type): + if hit_df.empty: + return None + sub = hit_df[hit_df["database"] == db_type] if sub.empty: return None - cov = coverage_for_plot(sub) fig, ax = plt.subplots(figsize=(7.8, 5.5), dpi=300) - ax.scatter(cov, pd.to_numeric(sub["pident"], errors="coerce"), alpha=0.8, color="#2c5f8a") - ax.set_title(title or f"{db_type} hit quality", fontsize=13, weight="bold") - ax.set_xlabel("Coverage percent (query for BLAST hits, reference for AMRFinderPlus hits)") + coverage_col = "reference_coverage_pct" if "reference_coverage_pct" in sub.columns else "subject_coverage_pct" + ax.scatter(sub[coverage_col], sub["pident"], alpha=0.8, color=PALETTE["primary"]) + ax.set_title(f"{db_type} hit quality") + ax.set_xlabel("Reference sequence coverage percent") ax.set_ylabel("Identity percent") style_axes(ax) return fig -def fig_top_genes(hit_df, db_type, title=None): - sub = select_database(hit_df, db_type) +def fig_top_genes(hit_df, db_type): + if hit_df.empty: + return None + sub = hit_df[hit_df["database"] == db_type] if sub.empty: return None counts = sub["gene_symbol"].fillna("Unknown").replace("", "Unknown").value_counts().head(15) fig, ax = plt.subplots(figsize=(9, 6), dpi=300) - ax.barh(counts.index[::-1], counts.values[::-1], color="#3b8c6e", edgecolor="white") - ax.set_title(title or f"Top detected {db_type} genes", fontsize=13, weight="bold") + ax.barh(counts.index[::-1], counts.values[::-1], color=PALETTE["accent"], edgecolor="white") + ax.set_title(f"Top detected {db_type} genes") ax.set_xlabel("Number of hits") ax.set_ylabel("Gene") style_axes(ax) @@ -1638,7 +2317,9 @@ def fig_top_genes(hit_df, db_type, title=None): def fig_amr_class_counts(hit_df): """AMR hits per resistance class. Uses the AMRFinderPlus class column when present, with a fallback to functional_group for BLAST only rows.""" - sub = select_database(hit_df, "AMR") + if hit_df is None or hit_df.empty: + return None + sub = hit_df[hit_df["database"] == "AMR"].copy() if sub.empty: return None if "class" in sub.columns: @@ -1651,8 +2332,8 @@ def fig_amr_class_counts(hit_df): if counts.empty: return None fig, ax = plt.subplots(figsize=(9, 6), dpi=300) - ax.barh(counts.index[::-1], counts.values[::-1], color="#c45a3b", edgecolor="white") - ax.set_title("AMR gene hits per resistance class", fontsize=13, weight="bold") + ax.barh(counts.index[::-1], counts.values[::-1], color=PALETTE["secondary"], edgecolor="white") + ax.set_title("AMR gene hits per resistance class") ax.set_xlabel("Number of hits") ax.set_ylabel("Resistance class") style_axes(ax) @@ -1660,15 +2341,41 @@ def fig_amr_class_counts(hit_df): def fig_top_virulence_genes(hit_df): - return fig_top_genes(hit_df, "VFDB", title="Top detected virulence genes") + if hit_df.empty: + return None + sub = hit_df[hit_df["database"].isin(["VFDB", "Virulence"])] + if sub.empty: + return None + counts = sub["gene_symbol"].fillna("Unknown").replace("", "Unknown").value_counts().head(15) + fig, ax = plt.subplots(figsize=(9, 6), dpi=300) + ax.barh(counts.index[::-1], counts.values[::-1], color=PALETTE["accent"], edgecolor="white") + ax.set_title("Top detected virulence genes") + ax.set_xlabel("Number of hits") + ax.set_ylabel("Gene") + style_axes(ax) + return fig def fig_virulence_identity_coverage(hit_df): - return fig_identity_coverage(hit_df, "VFDB", title="Virulence hit quality") + if hit_df.empty: + return None + sub = hit_df[hit_df["database"].isin(["VFDB", "Virulence"])] + if sub.empty: + return None + fig, ax = plt.subplots(figsize=(7.8, 5.5), dpi=300) + coverage_col = "reference_coverage_pct" if "reference_coverage_pct" in sub.columns else "subject_coverage_pct" + ax.scatter(sub[coverage_col], sub["pident"], alpha=0.8, color=PALETTE["primary"]) + ax.set_title("Virulence hit quality") + ax.set_xlabel("Reference sequence coverage percent") + ax.set_ylabel("Identity percent") + style_axes(ax) + return fig -def fig_heatmap(hit_df, db_type, basis, title=None): - sub = select_database(hit_df, db_type) +def fig_heatmap(hit_df, db_type, basis): + if hit_df.empty: + return None + sub = hit_df[hit_df["database"] == db_type] if sub.empty or sub["input_file"].nunique() < 2: return None col = "gene_symbol" if basis == "Gene" else "functional_group" @@ -1678,7 +2385,7 @@ def fig_heatmap(hit_df, db_type, basis, title=None): matrix = matrix.loc[:, matrix.sum(axis=0).sort_values(ascending=False).head(30).index] fig, ax = plt.subplots(figsize=(max(8, matrix.shape[1] * 0.45), max(4.5, matrix.shape[0] * 0.55)), dpi=300) im = ax.imshow(matrix.values, aspect="auto", cmap="viridis") - ax.set_title(title or f"{db_type} comparative heatmap", fontsize=13, weight="bold") + ax.set_title(f"{db_type} comparative heatmap") ax.set_xlabel(col) ax.set_ylabel("Genome") ax.set_xticks(np.arange(matrix.shape[1])) @@ -1691,7 +2398,30 @@ def fig_heatmap(hit_df, db_type, basis, title=None): def fig_virulence_heatmap(hit_df, basis): - return fig_heatmap(hit_df, "VFDB", basis, title="Virulence comparative heatmap") + """Comparative virulence heatmap that includes both BLAST VFDB hits and + AMRFinderPlus virulence rows.""" + if hit_df is None or hit_df.empty: + return None + sub = hit_df[hit_df["database"].isin(["VFDB", "Virulence"])].copy() + if sub.empty or sub["input_file"].nunique() < 2: + return None + col = "gene_symbol" if basis == "Gene" else "functional_group" + matrix = pd.crosstab(sub["input_file"], sub[col]) + if matrix.empty: + return None + matrix = matrix.loc[:, matrix.sum(axis=0).sort_values(ascending=False).head(30).index] + fig, ax = plt.subplots(figsize=(max(8, matrix.shape[1] * 0.45), max(4.5, matrix.shape[0] * 0.55)), dpi=300) + im = ax.imshow(matrix.values, aspect="auto", cmap="viridis") + ax.set_title("Virulence comparative heatmap") + ax.set_xlabel(col) + ax.set_ylabel("Genome") + ax.set_xticks(np.arange(matrix.shape[1])) + ax.set_yticks(np.arange(matrix.shape[0])) + ax.set_xticklabels(matrix.columns, rotation=60, ha="right", fontsize=8) + ax.set_yticklabels(matrix.index, fontsize=8) + cbar = fig.colorbar(im, ax=ax) + cbar.set_label("Hit count") + return fig def fig_bgc_types(smc_df): @@ -1707,8 +2437,8 @@ def fig_bgc_types(smc_df): return None counts = pd.Series(Counter(types)).sort_values(ascending=False).head(15) fig, ax = plt.subplots(figsize=(9, 5.5), dpi=300) - ax.bar(counts.index, counts.values, color="#7a5ba6", edgecolor="white") - ax.set_title("Predicted secondary metabolite BGC types", fontsize=13, weight="bold") + ax.bar(counts.index, counts.values, color=PALETTE["purple"], edgecolor="white") + ax.set_title("Predicted secondary metabolite BGC types") ax.set_xlabel("Biosynthetic gene cluster type") ax.set_ylabel("Number of regions") ax.tick_params(axis="x", rotation=45, labelsize=9) @@ -1724,9 +2454,9 @@ def fig_rscu(rscu_df, isolate): return None sub = sub.sort_values(["amino_acid", "codon"]) fig, ax = plt.subplots(figsize=(13, 5.8), dpi=300) - ax.bar(sub["codon"], sub["RSCU"], color="#2c5f8a", edgecolor="white") - ax.axhline(1.0, linestyle="--", linewidth=1, color="#6b6b6b") - ax.set_title(f"Relative synonymous codon usage: {isolate}", fontsize=13, weight="bold") + ax.bar(sub["codon"], sub["RSCU"], color=PALETTE["primary"], edgecolor="white") + ax.axhline(1.0, linestyle="--", linewidth=1, color=PALETTE["neutral"]) + ax.set_title(f"Relative synonymous codon usage: {isolate}") ax.set_xlabel("Codon") ax.set_ylabel("RSCU") ax.tick_params(axis="x", rotation=90, labelsize=8) @@ -1743,8 +2473,8 @@ def fig_window_gc(window_df, isolate): longest = sub.groupby("contig_id")["end"].max().sort_values(ascending=False).index[0] sub = sub[sub["contig_id"] == longest] fig, ax = plt.subplots(figsize=(10, 4.8), dpi=300) - ax.plot(sub["midpoint"], sub["GC_percent"], linewidth=1.8, color="#2c5f8a") - ax.set_title(f"Window GC profile: {isolate} | {longest}", fontsize=13, weight="bold") + ax.plot(sub["midpoint"], sub["GC_percent"], linewidth=1.8, color=PALETTE["primary"]) + ax.set_title(f"Window GC profile: {isolate} | {longest}") ax.set_xlabel("Position bp") ax.set_ylabel("GC percent") ax.grid(alpha=0.25, linestyle="--") @@ -1762,9 +2492,9 @@ def fig_gc_skew(window_df, isolate): sub = sub[sub["contig_id"] == longest].copy() sub["cumulative_GC_skew"] = sub["GC_skew"].cumsum() fig, ax = plt.subplots(figsize=(10, 4.8), dpi=300) - ax.plot(sub["midpoint"], sub["cumulative_GC_skew"], linewidth=1.8, color="#c45a3b") - ax.axhline(0, linewidth=0.8, color="#6b6b6b") - ax.set_title(f"Cumulative GC skew: {isolate} | {longest}", fontsize=13, weight="bold") + ax.plot(sub["midpoint"], sub["cumulative_GC_skew"], linewidth=1.8, color=PALETTE["secondary"]) + ax.axhline(0, linewidth=0.8, color=PALETTE["neutral"]) + ax.set_title(f"Cumulative GC skew: {isolate} | {longest}") ax.set_xlabel("Position bp") ax.set_ylabel("Cumulative GC skew") ax.grid(alpha=0.25, linestyle="--") @@ -1772,12 +2502,8 @@ def fig_gc_skew(window_df, isolate): return fig -def collect_figures(tables, heatmap_basis, errors=None): - """Build every figure. Failures are recorded in `errors` rather than being - discarded silently, so a missing figure can be traced from the ZIP logs.""" +def collect_figures(tables, heatmap_basis): figures = {} - if errors is None: - errors = {} genome_df = tables.get("genome_statistics", pd.DataFrame()) contig_df = tables.get("contig_statistics", pd.DataFrame()) @@ -1785,7 +2511,6 @@ def collect_figures(tables, heatmap_basis, errors=None): hit_df = tables.get("raw_hit_table", pd.DataFrame()) vf_summary = tables.get("virulence_summary", pd.DataFrame()) amr_summary = tables.get("amr_summary", pd.DataFrame()) - stress_summary = tables.get("stress_biocide_summary", pd.DataFrame()) rscu_df = tables.get("rscu_table", pd.DataFrame()) window_df = tables.get("window_gc_skew", pd.DataFrame()) per_gene_df = tables.get("per_gene_codon_indices", pd.DataFrame()) @@ -1793,7 +2518,7 @@ def collect_figures(tables, heatmap_basis, errors=None): smc_df = tables.get("secondary_metabolite_clusters", pd.DataFrame()) fig_builders = { - "figure_01_nucleotide_composition": lambda: fig_nucleotide_composition(genome_df) if not genome_df.empty else None, + "figure_01_nucleotide_composition": lambda: fig_nucleotide_donut(genome_df), "figure_02_contig_length_distribution": lambda: fig_contig_distribution(contig_df), "figure_03_top_contig_lengths": lambda: fig_top_contigs(contig_df), "figure_04_gc_content_by_contig": lambda: fig_gc_by_contig(contig_df), @@ -1810,7 +2535,6 @@ def collect_figures(tables, heatmap_basis, errors=None): "figure_15_amr_heatmap": lambda: fig_heatmap(hit_df, "AMR", heatmap_basis), "figure_16_secondary_metabolite_bgc_types": lambda: fig_bgc_types(smc_df), "figure_17_amr_resistance_class_counts": lambda: fig_amr_class_counts(hit_df), - "figure_18_stress_biocide_groups": lambda: fig_detection_groups(stress_summary, "Stress, biocide and metal hits by group"), } for name, builder in fig_builders.items(): @@ -1819,46 +2543,69 @@ def collect_figures(tables, heatmap_basis, errors=None): if fig is not None: figures[name] = fig except Exception as exc: - errors[name] = f"{type(exc).__name__}: {exc}" - - def guarded(name, fn): - try: - fig = fn() - if fig is not None: - figures[name] = fig - except Exception as exc: - errors[name] = f"{type(exc).__name__}: {exc}" + LOGGER.warning("Figure generation failed for %s: %s", name, exc) if not rscu_df.empty: for isolate in sorted(rscu_df["input_file"].unique())[:5]: - tag = sanitize_text(isolate) - guarded(f"figure_rscu_{tag}", lambda i=isolate: fig_rscu(rscu_df, i)) - guarded(f"figure_rscu_heatmap_{tag}", lambda i=isolate: cbe.fig_rscu_heatmap(rscu_df, i)) + fig = fig_rscu(rscu_df, isolate) + if fig is not None: + figures[f"figure_rscu_{sanitize_text(isolate)}"] = fig + try: + fig = cbe.fig_rscu_heatmap(rscu_df, isolate) + if fig is not None: + figures[f"figure_rscu_heatmap_{sanitize_text(isolate)}"] = fig + except Exception as exc: + LOGGER.warning("RSCU heatmap generation failed for %s: %s", isolate, exc) # Codon bias methodological figures per isolate if not per_gene_df.empty: for isolate in sorted(per_gene_df["input_file"].unique())[:5]: - tag = sanitize_text(isolate) - guarded(f"figure_enc_plot_{tag}", lambda i=isolate: cbe.fig_enc_plot(per_gene_df, i)) - - def _neutrality(i=isolate): - res = cbe.fig_neutrality_plot(per_gene_df, i) - return res[0] if res is not None else None - guarded(f"figure_neutrality_plot_{tag}", _neutrality) - - guarded(f"figure_pr2_plot_{tag}", lambda i=isolate: cbe.fig_pr2_plot(per_gene_df, i)) + try: + f = cbe.fig_enc_plot(per_gene_df, isolate) + if f is not None: + figures[f"figure_enc_plot_{sanitize_text(isolate)}"] = f + except Exception as exc: + LOGGER.warning("ENc plot generation failed for %s: %s", isolate, exc) + try: + res = cbe.fig_neutrality_plot(per_gene_df, isolate) + if res is not None: + figures[f"figure_neutrality_plot_{sanitize_text(isolate)}"] = res[0] + except Exception as exc: + LOGGER.warning("Neutrality plot generation failed for %s: %s", isolate, exc) + try: + f = cbe.fig_pr2_plot(per_gene_df, isolate) + if f is not None: + figures[f"figure_pr2_plot_{sanitize_text(isolate)}"] = f + except Exception as exc: + LOGGER.warning("PR2 plot generation failed for %s: %s", isolate, exc) # Amino acid composition per isolate if not aa_df.empty: for isolate in sorted(aa_df["input_file"].unique())[:5]: - tag = sanitize_text(isolate) - guarded(f"figure_amino_acid_composition_{tag}", lambda i=isolate: cbe.fig_amino_acid_composition(aa_df, i)) + try: + f = cbe.fig_amino_acid_composition(aa_df, isolate) + if f is not None: + figures[f"figure_amino_acid_composition_{sanitize_text(isolate)}"] = f + except Exception as exc: + LOGGER.warning("Amino acid composition figure failed for %s: %s", isolate, exc) if not window_df.empty: + genome_gc_by_isolate = {} + if not genome_df.empty and "input_file" in genome_df.columns: + genome_gc_by_isolate = dict(zip(genome_df["input_file"], genome_df["GC_percent"])) for isolate in sorted(window_df["input_file"].unique())[:5]: - tag = sanitize_text(isolate) - guarded(f"figure_gc_profile_{tag}", lambda i=isolate: fig_window_gc(window_df, i)) - guarded(f"figure_cumulative_gc_skew_{tag}", lambda i=isolate: fig_gc_skew(window_df, i)) + fig = fig_window_gc(window_df, isolate) + if fig is not None: + figures[f"figure_gc_profile_{sanitize_text(isolate)}"] = fig + fig = fig_gc_skew(window_df, isolate) + if fig is not None: + figures[f"figure_cumulative_gc_skew_{sanitize_text(isolate)}"] = fig + try: + fig = fig_circular_genome(window_df, isolate, genome_gc_mean=genome_gc_by_isolate.get(isolate)) + if fig is not None: + figures[f"figure_circular_genome_map_{sanitize_text(isolate)}"] = fig + except Exception as exc: + LOGGER.warning("Circular genome map generation failed for %s: %s", isolate, exc) return figures @@ -1867,7 +2614,7 @@ def collect_figures(tables, heatmap_basis, errors=None): # Output ZIP # ============================================================ -def make_zip(tables, reports, rendered_figures, logs, manifest, annotation_files=None): +def make_zip(tables, reports, figures, logs, manifest): mem = io.BytesIO() with zipfile.ZipFile(mem, "w", compression=zipfile.ZIP_DEFLATED) as zf: for name, df in tables.items(): @@ -1877,30 +2624,20 @@ def make_zip(tables, reports, rendered_figures, logs, manifest, annotation_files for name, text in reports.items(): zf.writestr(f"reports/{sanitize_text(name)}.txt", text + "\n") - for name, payload in rendered_figures.items(): - zf.writestr(f"figures/png/{sanitize_text(name)}.png", payload["png"]) - zf.writestr(f"figures/pdf/{sanitize_text(name)}.pdf", payload["pdf"]) - - for arcname, data in (annotation_files or {}).items(): - zf.writestr(arcname, data) + for name, fig in figures.items(): + zf.writestr(f"figures/png/{sanitize_text(name)}.png", fig_to_png_bytes(fig)) + zf.writestr(f"figures/pdf/{sanitize_text(name)}.pdf", fig_to_pdf_bytes(fig)) for name, text in logs.items(): zf.writestr(f"logs/{sanitize_text(name)}.txt", text) zf.writestr("metadata/run_manifest.json", json.dumps(manifest, indent=2)) zf.writestr("README_OUTPUTS.txt", ( - "This ZIP archive contains genome statistics, Prokka annotation summaries, AMR and virulence gene screening results, " + f"{APP_TITLE} v{APP_VERSION}\n\n" + "This ZIP archive contains FASTA quality control, genome statistics, Bakta or Prokka annotation summaries, AMR and virulence gene screening results, " "secondary metabolite gene cluster predictions, codon usage analysis including per-gene ENc, neutrality, and PR2 analyses, " - "amino acid composition, window based GC and skew analysis, manuscript ready result paragraphs, logs, and publication quality " - "figures in PNG and PDF formats.\n\n" - "Folders:\n" - " tables/ parsed results as CSV\n" - " figures/png, figures/pdf publication quality figures\n" - " reports/ manuscript ready result paragraphs\n" - " annotation/prokka/ raw Prokka output per genome (GFF, FFN, FAA, GBK and related files)\n" - " annotation/antismash/ raw antiSMASH output per genome (region GenBank, JSON and HTML)\n" - " logs/ tool logs, including any figures that failed to build\n" - " metadata/ run manifest with software versions and thresholds\n" + "amino acid composition, window based GC and skew analysis, a circular genome map, manuscript ready result paragraphs, logs, and publication quality " + "figures in PNG and PDF formats.\n" )) mem.seek(0) @@ -1912,20 +2649,22 @@ def make_zip(tables, reports, rendered_figures, logs, manifest, annotation_files # ============================================================ st.markdown(f"## {APP_TITLE}") +st.caption(f"{APP_TAGLINE} | Version {APP_VERSION} | Run schema {RUN_SCHEMA_VERSION}") st.write(APP_SUBTITLE) with st.expander("Methodological scope and interpretation", expanded=False): st.write( - "The tool performs genome level analysis from bacterial FASTA files. Prokka annotation is used when available. " + "The tool performs genome level analysis from bacterial FASTA files. Bakta is preferred for standardized bacterial annotation when its database is available, with Prokka as a compatible fallback. " "Virulence and AMR detection use built-in NCBI AMRFinderPlus --plus where available, as well as optional nucleotide homology searches against user supplied or preinstalled BLAST databases. " "Secondary metabolite gene clusters are predicted with antiSMASH where available. " "Codon usage bias is reported with RSCU, ENc, GC3, and the standard per-gene ENc plot, neutrality plot, and PR2 plot. " + "For BLAST-based gene detection, completeness is measured against the reference gene sequence rather than the full genome contig. " "Results are predictions and should be interpreted with database provenance, selected thresholds, genome quality, species context, and phenotype data where available." ) with st.sidebar: st.header("Analysis modules") - run_annotation = st.checkbox("Run Prokka annotation", value=True) + run_annotation = st.checkbox("Run standardized genome annotation", value=True) run_vfdb = st.checkbox("Detect virulence genes", value=True) run_amr = st.checkbox("Detect AMR genes", value=True) run_smc = st.checkbox("Detect secondary metabolites (antiSMASH)", value=False) @@ -1933,6 +2672,12 @@ with st.sidebar: run_windows = st.checkbox("Run window GC and skew analysis", value=True) st.header("Annotation parameters") + annotation_engine = st.selectbox( + "Annotation engine", + ["Auto (Bakta preferred)", "Bakta", "Prokka"], + index=0, + help="Auto uses Bakta for bacterial genomes when its database is available, otherwise Prokka.", + ) genus = st.text_input("Genus", value="Escherichia") species = st.text_input("Species", value="coli") kingdom = st.selectbox("Kingdom", ["Bacteria", "Archaea", "Viruses"], index=0) @@ -1941,9 +2686,22 @@ with st.sidebar: prokka_addgenes = st.checkbox("Add gene features", value=True) st.header("BLAST thresholds") - min_identity = st.slider("Minimum identity percent", 50.0, 100.0, 90.0, 1.0) - min_query_cov = st.slider("Minimum query coverage percent", 20.0, 100.0, 60.0, 1.0) - min_subject_cov = st.slider("Minimum subject coverage percent", 20.0, 100.0, 60.0, 1.0) + min_identity = st.slider("Minimum nucleotide identity percent", 50.0, 100.0, 90.0, 1.0) + min_reference_cov = st.slider( + "Minimum reference gene coverage percent", + 20.0, + 100.0, + 80.0, + 1.0, + help="Coverage is calculated against the AMR or virulence reference sequence, not the full genome contig.", + ) + min_alignment_bp = st.number_input( + "Minimum aligned length bp", + min_value=0, + max_value=10000, + value=100, + step=10, + ) evalue = st.selectbox("E value", [1e-5, 1e-10, 1e-20, 1e-30, 1e-50], index=2) max_targets = st.slider("Maximum target hits per query", 1, 100, 10, 1) blast_task = st.selectbox("BLASTN task", ["megablast", "blastn"], index=0) @@ -1964,13 +2722,14 @@ with st.sidebar: window_size = st.number_input("Window size bp", min_value=500, max_value=100000, value=5000, step=500) heatmap_basis = st.selectbox("Comparative heatmap basis", ["Gene", "Functional group"], index=0) - st.header("Output options") - include_raw_outputs = st.checkbox("Include raw Prokka and antiSMASH files in the ZIP", value=True) - threads = st.slider("CPU threads", 1, max(1, os.cpu_count() or 2), min(4, max(1, os.cpu_count() or 2)), 1) with st.expander("Deployment status", expanded=False): + st.write(f"Application version: {APP_VERSION}") + st.write(f"Bakta available: {bakta_available()}") + st.write(f"Bakta version: {bakta_version()}") + st.write(f"Bakta database detected: {bakta_database_available()} at {DEFAULT_BAKTA_DB}") st.write(f"Prokka available: {command_available('prokka')}") st.write(f"Prokka version: {prokka_version()}") st.write(f"blastn available: {command_available('blastn')}") @@ -2018,6 +2777,8 @@ if run_clicked: try: all_genome_stats = [] + all_fasta_quality = [] + input_provenance = [] all_contigs = [] all_windows = [] all_features = [] @@ -2030,12 +2791,6 @@ if run_clicked: all_aa = [] all_smc = [] logs = {} - annotation_files = {} - archive_budget = { - "used": 0, - "limit": MAX_ARCHIVE_OUTPUT_MB * 1024 * 1024, - "skipped": [], - } with tempfile.TemporaryDirectory() as tmp: tmpdir = Path(tmp) @@ -2043,10 +2798,10 @@ if run_clicked: prepared_dir = tmpdir / "prepared" db_dir = tmpdir / "databases" blast_dir = tmpdir / "blast" - prokka_root = tmpdir / "prokka" + annotation_root = tmpdir / "annotation" antismash_root = tmpdir / "antismash" - for p in [raw_dir, prepared_dir, db_dir, blast_dir, prokka_root, antismash_root]: + for p in [raw_dir, prepared_dir, db_dir, blast_dir, annotation_root, antismash_root]: p.mkdir(parents=True, exist_ok=True) status.info("Preparing built-in AMRFinderPlus and optional BLAST databases.") @@ -2063,15 +2818,27 @@ if run_clicked: cai_weights = load_cai_weights(cai_upload) if run_codon else {} + used_sample_prefixes = set() for idx, uploaded in enumerate(uploaded_files, start=1): status.info(f"Analysing {uploaded.name}") progress.progress(int((idx - 1) / len(uploaded_files) * 100)) sample_prefix = sanitize_text(Path(uploaded.name).stem) + if sample_prefix in used_sample_prefixes: + sample_prefix = f"{sample_prefix}_{idx}" + used_sample_prefixes.add(sample_prefix) raw_path = read_uploaded_to_path(uploaded, raw_dir) + input_provenance.append({ + "file_name": uploaded.name, + "size_bytes": int(raw_path.stat().st_size), + "sha256": sha256_path(raw_path), + }) dec_path = decompress_if_needed(raw_path, prepared_dir) fasta_path = normalize_fasta(dec_path, prepared_dir) records = read_fasta_records(fasta_path) + all_fasta_quality.append( + fasta_quality_summary(records, uploaded.name) + ) if not records: raise ValueError(f"No FASTA records were found in {uploaded.name}") @@ -2086,46 +2853,96 @@ if run_clicked: if run_windows: all_windows.append(window_statistics(records, uploaded.name, int(window_size))) - prokka_cds = None + annotation_cds = None if run_annotation: - prokka_out = prokka_root / sample_prefix - result = run_prokka( - fasta_path=fasta_path, - outdir=prokka_out, - prefix=sample_prefix, - genus=genus, - species=species, - kingdom=kingdom, - threads=int(threads), - locus_tag=locus_tag, - compliant=prokka_compliant, - addgenes=prokka_addgenes, - ) - logs[f"prokka_{sample_prefix}"] = result["log"] - annotation_modes[uploaded.name] = result.get("mode") + selected_engine = choose_annotation_engine(annotation_engine, kingdom) + annotation_out = annotation_root / sample_prefix + + if selected_engine == "Bakta": + result = run_bakta( + fasta_path=fasta_path, + outdir=annotation_out, + prefix=sample_prefix, + genus=genus, + species=species, + threads=int(threads), + locus_tag=locus_tag, + compliant=prokka_compliant, + ) + if not result.get("success") and annotation_engine.startswith("Auto"): + result = run_prokka( + fasta_path=fasta_path, + outdir=annotation_out, + prefix=sample_prefix, + genus=genus, + species=species, + kingdom=kingdom, + threads=int(threads), + locus_tag=locus_tag, + compliant=prokka_compliant, + addgenes=prokka_addgenes, + ) + result["engine"] = "prokka" + else: + result = run_prokka( + fasta_path=fasta_path, + outdir=annotation_out, + prefix=sample_prefix, + genus=genus, + species=species, + kingdom=kingdom, + threads=int(threads), + locus_tag=locus_tag, + compliant=prokka_compliant, + addgenes=prokka_addgenes, + ) + result["engine"] = "prokka" + + engine_name = result.get("engine", selected_engine.lower()) + logs[f"annotation_{engine_name}_{sample_prefix}"] = result.get("log", "") + annotation_modes[uploaded.name] = { + "engine": engine_name, + "mode": result.get("mode"), + "success": bool(result.get("success")), + } + if result.get("mode") == "noanno": - st.warning(f"{uploaded.name}: full product search did not complete, so Prokka ran in fallback mode (--noanno). Gene prediction and composition are valid, but CDS product names are not available.") - gff_path = Path(result["outdir"]) / f"{sample_prefix}.gff" - feature_df = parse_prokka_gff(gff_path, uploaded.name) + st.warning( + f"{uploaded.name}: Prokka completed in --noanno fallback mode. " + "Gene prediction is available, but CDS product annotation is limited." + ) + if not result.get("success"): + st.warning( + f"{uploaded.name}: annotation did not complete. " + "Genome composition and enabled independent modules will continue." + ) + + gff_path = find_annotation_file( + result["outdir"], + sample_prefix, + [".gff3", ".gff"], + ) + feature_df = ( + parse_prokka_gff(gff_path, uploaded.name) + if gff_path is not None + else pd.DataFrame() + ) all_features.append(feature_df) - all_annotation_summaries.append(annotation_summary(feature_df, uploaded.name, comp["total_bases"])) - prokka_cds = read_prokka_cds(result["outdir"], sample_prefix) - - # Copy the raw Prokka output while the temporary - # directory still exists, otherwise it is lost before - # the ZIP is written. - if include_raw_outputs and result.get("success"): - harvest_directory( - result["outdir"], - f"annotation/prokka/{sample_prefix}", - PROKKA_KEEP_EXTENSIONS, - annotation_files, - archive_budget, + all_annotation_summaries.append( + annotation_summary( + feature_df, + uploaded.name, + comp["total_bases"], ) + ) + annotation_cds = read_annotation_cds( + result["outdir"], + sample_prefix, + ) if run_codon: orfs, rscu, codon_stats, per_gene, aa_comp = codon_analysis( - records, uploaded.name, min_orf_aa, cai_weights, cds_pairs=prokka_cds + records, uploaded.name, min_orf_aa, cai_weights, cds_pairs=annotation_cds ) all_orfs.append(orfs) all_rscu.append(rscu) @@ -2140,15 +2957,6 @@ if run_clicked: logs[f"antismash_{sample_prefix}"] = res_smc["log"] if res_smc["success"]: all_smc.append(parse_antismash_results(res_smc["outdir"], sample_prefix, uploaded.name)) - if include_raw_outputs: - harvest_directory( - res_smc["outdir"], - f"annotation/antismash/{sample_prefix}", - ANTISMASH_KEEP_EXTENSIONS, - annotation_files, - archive_budget, - skip_dirs=ANTISMASH_SKIP_DIRS, - ) else: st.warning(f"{uploaded.name}: antiSMASH did not complete. See the logs.") elif run_smc and not antismash_available(): @@ -2184,8 +2992,23 @@ if run_clicked: continue out_tsv = blast_dir / f"{sample_prefix}_{db_type}.tsv" try: - run_blastn(fasta_path, db_prefix, out_tsv, evalue, max_targets, int(threads), blast_task) - df = load_and_filter_blast(out_tsv, uploaded.name, db_type, min_identity, min_query_cov, min_subject_cov) + logs[f"blast_{db_type}_{sample_prefix}"] = run_blastn( + fasta_path, + db_prefix, + out_tsv, + evalue, + max_targets, + int(threads), + blast_task, + ) + df = load_and_filter_blast( + out_tsv, + uploaded.name, + db_type, + min_identity, + min_reference_cov, + min_alignment_bp, + ) df = apply_species_filter(df, species_filter_text, species_filter_mode) if not df.empty: all_hits.append(df) @@ -2195,18 +3018,8 @@ if run_clicked: progress.progress(100) status.success("Analysis completed.") - if archive_budget["skipped"]: - logs["archive_skipped_files"] = ( - f"The raw output archive budget of {MAX_ARCHIVE_OUTPUT_MB} MB was reached, so the following " - "files were not added to the ZIP. Raise MAX_ARCHIVE_OUTPUT_MB to include them.\n\n" - + "\n".join(archive_budget["skipped"]) - ) - st.info( - f"{len(archive_budget['skipped'])} raw output file(s) exceeded the {MAX_ARCHIVE_OUTPUT_MB} MB " - "archive budget and were left out of the ZIP. The parsed tables and figures are complete." - ) - genome_df = pd.DataFrame(all_genome_stats) + fasta_quality_df = pd.concat(all_fasta_quality, ignore_index=True) if all_fasta_quality else pd.DataFrame() contig_df = pd.concat(all_contigs, ignore_index=True) if all_contigs else pd.DataFrame() window_df = pd.concat(all_windows, ignore_index=True) if all_windows else pd.DataFrame() feature_df = pd.concat(all_features, ignore_index=True) if all_features else pd.DataFrame() @@ -2215,7 +3028,6 @@ if run_clicked: detailed_hits = format_hit_table(hit_df) vf_summary = build_detection_summary(hit_df, "VFDB") amr_summary = build_detection_summary(hit_df, "AMR") - stress_summary = build_detection_summary(hit_df, "Stress_Biocide") orf_df = pd.concat(all_orfs, ignore_index=True) if all_orfs else pd.DataFrame() rscu_df = pd.concat(all_rscu, ignore_index=True) if all_rscu else pd.DataFrame() codon_df = pd.concat(all_codon_stats, ignore_index=True) if all_codon_stats else pd.DataFrame() @@ -2232,6 +3044,7 @@ if run_clicked: tables = { "isolate_summary": isolate_summary, "genome_statistics": genome_df, + "fasta_quality_control": fasta_quality_df, "contig_statistics": contig_df, "window_gc_skew": window_df, "annotation_summary": annotation_df, @@ -2240,7 +3053,6 @@ if run_clicked: "detailed_gene_hits": detailed_hits, "virulence_summary": vf_summary, "amr_summary": amr_summary, - "stress_biocide_summary": stress_summary, "secondary_metabolite_clusters": smc_df, "predicted_orfs": orf_df, "rscu_table": rscu_df, @@ -2249,19 +3061,24 @@ if run_clicked: "amino_acid_composition": aa_df, } - figure_errors = {} - figures = collect_figures(tables, heatmap_basis, errors=figure_errors) - rendered_figures = render_figures(figures) - if figure_errors: - logs["figure_build_errors"] = "\n".join(f"{k}: {v}" for k, v in figure_errors.items()) + figures = collect_figures(tables, heatmap_basis) manifest = { "tool": APP_TITLE, - "analysis_date": datetime.now().isoformat(), - "input_files": [f.name for f in uploaded_files], + "tool_version": APP_VERSION, + "schema_version": RUN_SCHEMA_VERSION, + "analysis_date_utc": utc_now_iso(), + "run_id": hashlib.sha256((utc_now_iso() + "|" + "|".join(f.name for f in uploaded_files)).encode("utf-8")).hexdigest()[:16], + "input_files": input_provenance, + "runtime": { + "python_version": sys.version.split()[0], + "platform": platform.platform(), + "cpu_count": os.cpu_count(), + }, "annotation_modes": annotation_modes, "modules": { - "prokka_annotation": run_annotation, + "genome_annotation": run_annotation, + "requested_annotation_engine": annotation_engine, "virulence_screening": run_vfdb, "amr_screening": run_amr, "secondary_metabolites": run_smc, @@ -2270,22 +3087,17 @@ if run_clicked: }, "thresholds": { "min_identity_percent": min_identity, - "min_query_coverage_percent": min_query_cov, - "min_subject_coverage_percent": min_subject_cov, + "min_reference_coverage_percent": min_reference_cov, + "min_alignment_length_bp": int(min_alignment_bp), "evalue": evalue, "max_targets": max_targets, "blast_task": blast_task, }, - "outputs": { - "raw_annotation_files_included": bool(include_raw_outputs), - "raw_annotation_files_count": len(annotation_files), - "raw_annotation_bytes": archive_budget["used"], - "raw_annotation_files_skipped": len(archive_budget["skipped"]), - "archive_budget_mb": MAX_ARCHIVE_OUTPUT_MB, - "figures_built": len(rendered_figures), - "figures_failed": len(figure_errors), - }, "software_status": { + "bakta_available": bakta_available(), + "bakta_version": bakta_version(), + "bakta_database_available": bakta_database_available(), + "bakta_database_path": str(DEFAULT_BAKTA_DB), "prokka_available": command_available("prokka"), "prokka_version": prokka_version(), "blastn_available": command_available("blastn"), @@ -2303,12 +3115,15 @@ if run_clicked: }, } - zip_bytes = make_zip(tables, reports, rendered_figures, logs, manifest, annotation_files) + zip_bytes = make_zip(tables, reports, figures, logs, manifest) + figures_png = {name: fig_to_png_bytes(fig) for name, fig in figures.items()} + for fig in figures.values(): + plt.close(fig) st.session_state.run_complete = True st.session_state.tables = tables st.session_state.reports = reports - st.session_state.figures_png = {k: v["png"] for k, v in rendered_figures.items()} + st.session_state.figures_png = figures_png st.session_state.zip_bytes = zip_bytes st.session_state.manifest = manifest st.session_state.log_text = "\n\n".join([f"===== {k} =====\n{v}" for k, v in logs.items()]) @@ -2325,7 +3140,6 @@ if st.session_state.run_complete: detailed_hits = tables.get("detailed_gene_hits", pd.DataFrame()) vf_summary = tables.get("virulence_summary", pd.DataFrame()) amr_summary = tables.get("amr_summary", pd.DataFrame()) - stress_summary = tables.get("stress_biocide_summary", pd.DataFrame()) codon_df = tables.get("codon_usage_statistics", pd.DataFrame()) rscu_df = tables.get("rscu_table", pd.DataFrame()) genome_df = tables.get("genome_statistics", pd.DataFrame()) @@ -2373,10 +3187,6 @@ if st.session_state.run_complete: if detailed_hits.empty: st.warning("No virulence or AMR hits passed the selected thresholds, or no detector was available.") else: - st.caption( - "Coverage basis differs by detector. BLAST rows report query and subject coverage. " - "AMRFinderPlus reports coverage of the reference sequence only, so query coverage is left blank for those rows." - ) st.dataframe(detailed_hits, use_container_width=True, height=460) c1, c2 = st.columns(2) @@ -2387,12 +3197,6 @@ if st.session_state.run_complete: st.markdown("### AMR summary") st.dataframe(amr_summary, use_container_width=True, height=300) - st.markdown("### Stress, biocide and metal resistance summary") - if stress_summary is None or stress_summary.empty: - st.info("No stress, biocide or metal resistance elements were reported by AMRFinderPlus --plus.") - else: - st.dataframe(stress_summary, use_container_width=True, height=260) - with tab_smc: st.markdown("### Predicted secondary metabolite biosynthetic gene clusters") if smc_df is None or smc_df.empty: @@ -2421,14 +3225,14 @@ if st.session_state.run_complete: st.info("No figures were generated.") else: for name, png in st.session_state.figures_png.items(): - st_image_compat(png, caption=name) + st.image(png, caption=name, use_container_width=True) with tab6: st.markdown("### Download complete report") st.download_button( "Download complete ZIP report", data=st.session_state.zip_bytes, - file_name="bulamarwa_genome_annotation_amr_virulence_report.zip", + file_name="bulamarwa_genomics_suite_report.zip", mime="application/zip", use_container_width=True, ) @@ -2456,9 +3260,9 @@ if st.session_state.run_complete: else: st.info( "Upload bacterial genome FASTA files, configure the modules, then run the complete genome analysis. " - "For Hugging Face deployment, use a Docker Space so that Prokka, ncbi-blast+, ncbi-amrfinderplus, and antiSMASH can be installed." + "For Hugging Face deployment, use a Docker Space so that Bakta or Prokka, ncbi-blast+, ncbi-amrfinderplus, and antiSMASH can be installed." ) st.caption( - "Interpretation note: AMR, virulence, and secondary metabolite results are prediction based. They do not replace phenotypic antimicrobial susceptibility testing, experimental virulence assays, or chemical confirmation of metabolites." + f"{APP_TITLE} v{APP_VERSION}. Interpretation note: AMR, virulence, and secondary metabolite results are prediction based. They do not replace phenotypic antimicrobial susceptibility testing, experimental virulence assays, or chemical confirmation of metabolites." ) \ No newline at end of file