GENOMICS-CDDBRG's picture
Update app.py
4e6c3d7 verified
Raw History Blame Contribute Delete
139 kB
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 subprocess 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 import streamlit as st import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt 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. # ============================================================ 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 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")) 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", "TAT":"Y","TAC":"Y","TAA":"*","TAG":"*","TGT":"C","TGC":"C","TGA":"*","TGG":"W", "CTT":"L","CTC":"L","CTA":"L","CTG":"L","CCT":"P","CCC":"P","CCA":"P","CCG":"P", "CAT":"H","CAC":"H","CAA":"Q","CAG":"Q","CGT":"R","CGC":"R","CGA":"R","CGG":"R", "ATT":"I","ATC":"I","ATA":"I","ATG":"M","ACT":"T","ACC":"T","ACA":"T","ACG":"T", "AAT":"N","AAC":"N","AAA":"K","AAG":"K","AGT":"S","AGC":"S","AGA":"R","AGG":"R", "GTT":"V","GTC":"V","GTA":"V","GTG":"V","GCT":"A","GCC":"A","GCA":"A","GCG":"A", "GAT":"D","GAC":"D","GAA":"E","GAG":"E","GGT":"G","GGC":"G","GGA":"G","GGG":"G", } STOP_CODONS = {"TAA", "TAG", "TGA"} START_CODONS = {"ATG", "GTG", "TTG"} AA_TO_CODONS = defaultdict(list) 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") # 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. AMRFINDER_ORGANISMS = { "escherichia": "Escherichia", "shigella": "Escherichia", "salmonella": "Salmonella", "klebsiella pneumoniae": "Klebsiella_pneumoniae", "klebsiella oxytoca": "Klebsiella_oxytoca", "acinetobacter baumannii": "Acinetobacter_baumannii", "pseudomonas aeruginosa": "Pseudomonas_aeruginosa", "staphylococcus aureus": "Staphylococcus_aureus", "enterococcus faecalis": "Enterococcus_faecalis", "enterococcus faecium": "Enterococcus_faecium", "campylobacter": "Campylobacter", "streptococcus pneumoniae": "Streptococcus_pneumoniae", "streptococcus pyogenes": "Streptococcus_pyogenes", "streptococcus agalactiae": "Streptococcus_agalactiae", "neisseria gonorrhoeae": "Neisseria_gonorrhoeae", "neisseria meningitidis": "Neisseria_meningitidis", "vibrio cholerae": "Vibrio_cholerae", "clostridioides difficile": "Clostridioides_difficile", "enterobacter cloacae": "Enterobacter_cloacae", "serratia marcescens": "Serratia_marcescens", } _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): genus_text = str(genus).strip() species_text = str(species).strip() g = genus_text.lower() s = species_text.lower() full = f"{g} {s}".strip() 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 "" # ============================================================ # Session state # ============================================================ def init_state(): defaults = { "run_complete": False, "zip_bytes": None, "log_text": "", "tables": {}, "figures_png": {}, "reports": {}, "manifest": {}, } for key, val in defaults.items(): if key not in st.session_state: st.session_state[key] = val init_state() def clear_results(): for key in ["run_complete", "zip_bytes", "log_text", "tables", "figures_png", "reports", "manifest"]: if key in st.session_state: del st.session_state[key] init_state() st.rerun() # ============================================================ # General helpers # ============================================================ def command_available(name: str) -> bool: return shutil.which(name) is not 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( 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: 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"): text = str(text).strip() text = re.sub(r"[^A-Za-z0-9._-]+", "_", text) text = text.strip("._-") return text or fallback def validate_extension(filename: str) -> bool: suffixes = [s.lower() for s in Path(filename).suffixes] return any(s in SUPPORTED_EXTENSIONS for s in suffixes) def read_uploaded_to_path(uploaded_file, outdir: Path) -> Path: outdir.mkdir(parents=True, exist_ok=True) out = outdir / sanitize_text(uploaded_file.name, "uploaded.fasta") with open(out, "wb") as f: f.write(uploaded_file.getbuffer()) return out def decompress_if_needed(path: Path, outdir: Path) -> Path: if not path.name.lower().endswith(".gz"): return path 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" records: List[Tuple[str, str]] = [] current_header: Optional[str] = None seq_parts: List[str] = [] 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(">"): 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 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) -> List[Dict[str, str]]: records: List[Dict[str, str]] = [] current_id: Optional[str] = None current_desc = "" parts: List[str] = [] 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: 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: parts.append(line.upper()) if current_id is not None: 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] def dataframe_to_csv_bytes(df: pd.DataFrame) -> bytes: return df.to_csv(index=False).encode("utf-8") def st_show_image(data, caption: Optional[str] = None) -> None: """Display an image full width across Streamlit versions. st.image only accepted use_container_width from a fairly recent Streamlit release; older builds (still common in pinned conda environments) raise a TypeError for it and expect use_column_width instead. Try the current argument first, then fall back, so the app runs the same way regardless of which Streamlit build is deployed. """ try: st.image(data, caption=caption, use_container_width=True) except TypeError: st.image(data, caption=caption, use_column_width=True) def human_bp(n): n = int(n) if n >= 1_000_000: return f"{n / 1_000_000:.2f} Mb" if n >= 1_000: return f"{n / 1_000:.2f} kb" return f"{n} bp" # ============================================================ # Genome statistics # ============================================================ def nxx(lengths, fraction): ordered = sorted([int(x) for x in lengths if int(x) > 0], reverse=True) if not ordered: return 0, 0 cutoff = sum(ordered) * fraction cumulative = 0 for i, length in enumerate(ordered, start=1): cumulative += length if cumulative >= cutoff: return length, i return 0, 0 def genome_composition(records): seq = "".join(r["sequence"] for r in records).upper() total = len(seq) counts = Counter(seq) a = counts.get("A", 0) t = counts.get("T", 0) g = counts.get("G", 0) c = counts.get("C", 0) n = counts.get("N", 0) ambiguous = sum(counts.get(x, 0) for x in "RYKMSWBDHV") valid = a + t + g + c + n + ambiguous gc = g + c at = a + t cpg = seq.count("CG") cpg_expected = (c * g / total) if total else 0 lengths = [len(r["sequence"]) for r in records] n50, l50 = nxx(lengths, 0.50) n75, l75 = nxx(lengths, 0.75) n90, l90 = nxx(lengths, 0.90) return { "contigs": len(records), "total_bases": total, "A": a, "T": t, "G": g, "C": c, "N": n, "ambiguous_bases": ambiguous, "invalid_or_removed_bases": max(0, total - valid), "GC_percent": round((gc / total * 100) if total else 0, 4), "AT_percent": round((at / total * 100) if total else 0, 4), "N_percent": round((n / total * 100) if total else 0, 4), "GC_skew": round(((g - c) / gc) if gc else 0, 6), "AT_skew": round(((a - t) / at) if at else 0, 6), "CpG_observed": cpg, "CpG_OE": round((cpg / cpg_expected) if cpg_expected else 0, 6), "largest_contig": max(lengths) if lengths else 0, "smallest_contig": min(lengths) if lengths else 0, "mean_contig_length": round(float(np.mean(lengths)), 2) if lengths else 0, "median_contig_length": round(float(np.median(lengths)), 2) if lengths else 0, "N50": n50, "L50": l50, "N75": n75, "L75": l75, "N90": n90, "L90": l90, } def contig_statistics(records, input_file): rows = [] for rec in records: seq = rec["sequence"].upper() length = len(seq) g = seq.count("G") c = seq.count("C") n = seq.count("N") rows.append({ "input_file": input_file, "contig_id": rec["id"], "contig_length": length, "GC_percent": round(((g + c) / length * 100) if length else 0, 4), "N_percent": round((n / length * 100) if length else 0, 4), }) return pd.DataFrame(rows) def window_statistics(records, input_file, window): rows = [] for rec in records: seq = rec["sequence"].upper() for start in range(0, len(seq), window): w = seq[start:start + window] if not w: continue g = w.count("G") c = w.count("C") a = w.count("A") t = w.count("T") gc = g + c at = a + t rows.append({ "input_file": input_file, "contig_id": rec["id"], "start": start + 1, "end": start + len(w), "midpoint": start + len(w) // 2, "window_size": len(w), "GC_percent": round((gc / len(w) * 100) if w else 0, 4), "GC_skew": round(((g - c) / gc) if gc else 0, 6), "AT_skew": round(((a - t) / at) if at else 0, 6), }) 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) # ============================================================ def prokka_version(): if not command_available("prokka"): return "Prokka not available." code, out, err = run_command(["prokka", "--version"]) return (out or err or "Prokka version could not be determined.").strip() def _prokka_files_present(outdir, prefix): outdir = Path(outdir) for ext in ["gff", "ffn", "faa"]: if (outdir / f"{prefix}.{ext}").exists(): continue if list(outdir.glob(f"*.{ext}")): continue return False return True def _prokka_command(fasta_path, outdir, prefix, genus, species, kingdom, threads, locus_tag, compliant, addgenes, noanno): cmd = [ "prokka", "--outdir", str(outdir), "--prefix", prefix, "--kingdom", kingdom, "--genus", genus, "--species", species, "--cpus", str(threads), "--force", ] if locus_tag.strip(): cmd.extend(["--locustag", sanitize_text(locus_tag).upper()[:12]]) if compliant: cmd.append("--compliant") if addgenes: cmd.append("--addgenes") if noanno: cmd.append("--noanno") cmd.append(str(fasta_path)) return cmd def run_prokka(fasta_path, outdir, prefix, genus, species, kingdom, threads, locus_tag, compliant, addgenes): """Run Prokka. Try full annotation, then retry once with --noanno so gene prediction still completes if the product search step fails on the host.""" if not command_available("prokka"): return {"success": False, "skipped": True, "mode": "unavailable", "log": "Prokka is not available in this environment.", "outdir": outdir} outdir = Path(outdir) outdir.mkdir(parents=True, exist_ok=True) cmd = _prokka_command(fasta_path, outdir, prefix, genus, species, kingdom, threads, locus_tag, compliant, addgenes, noanno=False) code, out, err = run_command(cmd) log_full = "COMMAND:\n" + " ".join(cmd) + "\n\nSTDOUT:\n" + out + "\n\nSTDERR:\n" + err if code == 0 and _prokka_files_present(outdir, prefix): return {"success": True, "skipped": False, "mode": "full", "log": log_full, "outdir": outdir} # Fallback: clean and retry with --noanno at one cpu if outdir.exists(): shutil.rmtree(outdir) outdir.mkdir(parents=True, exist_ok=True) cmd2 = _prokka_command(fasta_path, outdir, prefix, genus, species, kingdom, 1, locus_tag, compliant, addgenes, noanno=True) code2, out2, err2 = run_command(cmd2) log_noanno = "COMMAND:\n" + " ".join(cmd2) + "\n\nSTDOUT:\n" + out2 + "\n\nSTDERR:\n" + err2 combined = ( "FIRST ATTEMPT (full annotation) did not complete. Retried with --noanno.\n" + "=" * 70 + "\n" + log_full + "\n" + "=" * 70 + "\nSECOND ATTEMPT (--noanno):\n" + log_noanno ) if code2 == 0 and _prokka_files_present(outdir, prefix): return {"success": True, "skipped": False, "mode": "noanno", "log": combined, "outdir": outdir} return {"success": False, "skipped": False, "mode": "failed", "log": combined, "outdir": outdir} def parse_gff_attributes(attr): 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): if not Path(gff_path).exists(): return pd.DataFrame() rows = [] with open(gff_path, "r", encoding="utf-8", errors="ignore") as f: for line in f: if line.startswith("#"): if line.startswith("##FASTA"): break continue parts = line.rstrip("\n").split("\t") if len(parts) != 9: continue seqid, source, feature_type, start, end, score, strand, phase, attrs = parts attr = parse_gff_attributes(attrs) try: start_i = int(start) end_i = int(end) length = abs(end_i - start_i) + 1 except Exception: start_i, end_i, length = np.nan, np.nan, np.nan rows.append({ "input_file": input_file, "contig_id": seqid, "source": source, "feature_type": feature_type, "start": start_i, "end": end_i, "length_bp": length, "strand": strand, "gene": attr.get("gene", ""), "locus_tag": attr.get("locus_tag", attr.get("ID", "")), "product": attr.get("product", ""), "inference": attr.get("inference", ""), }) return pd.DataFrame(rows) def annotation_summary(feature_df, input_file, genome_length): if feature_df.empty: return pd.DataFrame([{ "input_file": input_file, "total_features": 0, "CDS": 0, "genes": 0, "rRNA": 0, "tRNA": 0, "tmRNA": 0, "repeat_region": 0, "hypothetical_proteins": 0, "functional_CDS": 0, "hypothetical_percent": 0, "coding_density_percent": 0, "CDS_per_Mb": 0, }]) counts = feature_df["feature_type"].value_counts().to_dict() cds = feature_df[feature_df["feature_type"] == "CDS"].copy() total_cds_length = cds["length_bp"].dropna().sum() if not cds.empty else 0 product_lower = cds["product"].fillna("").str.lower() if not cds.empty else pd.Series(dtype=str) hypothetical = int(product_lower.str.contains("hypothetical protein", regex=False).sum()) if not cds.empty else 0 functional = int(len(cds) - hypothetical) if not cds.empty else 0 return pd.DataFrame([{ "input_file": input_file, "total_features": int(len(feature_df)), "CDS": int(counts.get("CDS", 0)), "genes": int(counts.get("gene", 0)), "rRNA": int(counts.get("rRNA", 0)), "tRNA": int(counts.get("tRNA", 0)), "tmRNA": int(counts.get("tmRNA", 0)), "repeat_region": int(counts.get("repeat_region", 0)), "hypothetical_proteins": hypothetical, "functional_CDS": functional, "hypothetical_percent": round((hypothetical / len(cds) * 100) if len(cds) else 0, 4), "coding_density_percent": round((total_cds_length / genome_length * 100) if genome_length else 0, 4), "CDS_per_Mb": round((len(cds) / (genome_length / 1_000_000)) if genome_length else 0, 4), "mean_CDS_length": round(float(cds["length_bp"].mean()), 2) if len(cds) else 0, "median_CDS_length": round(float(cds["length_bp"].median()), 2) if len(cds) else 0, }]) # ============================================================ # Secondary metabolite gene clusters (antiSMASH) # ============================================================ def antismash_available() -> bool: return command_available("antismash") def antismash_version() -> str: if not antismash_available(): return "antiSMASH not available." code, out, err = run_command(["antismash", "--version"]) return (out or err or "antiSMASH version could not be determined.").strip() def run_antismash(fasta_path, outdir, prefix, taxon="bacteria", threads=1): """Run antiSMASH on a nucleotide FASTA using prodigal gene finding.""" if not antismash_available(): return {"success": False, "skipped": True, "log": "antiSMASH not available.", "outdir": outdir} outdir = Path(outdir) outdir.mkdir(parents=True, exist_ok=True) cmd = [ "antismash", "--taxon", taxon, "--genefinding-tool", "prodigal", "--cpus", str(max(1, int(threads))), "--output-dir", str(outdir), "--output-basename", prefix, str(fasta_path), ] code, out, err = run_command(cmd) log = "COMMAND:\n" + " ".join(cmd) + "\n\nSTDOUT:\n" + out + "\n\nSTDERR:\n" + err return {"success": code == 0, "skipped": False, "log": log, "outdir": outdir} def parse_antismash_results(outdir, prefix, input_file): """Read antiSMASH JSON regions. Falls back to counting region GenBank files.""" outdir = Path(outdir) rows = [] json_path = outdir / f"{prefix}.json" if not json_path.exists(): matches = list(outdir.glob("*.json")) json_path = matches[0] if matches else None if json_path and json_path.exists(): try: with open(json_path, "r", encoding="utf-8", errors="ignore") as fh: data = json.load(fh) for rec in data.get("records", []): rec_id = rec.get("id") or rec.get("name") or "unknown" for i, area in enumerate(rec.get("areas", []) or [], start=1): products = area.get("products") or area.get("product") or [] if isinstance(products, str): products = [products] rows.append({ "input_file": input_file, "contig_id": rec_id, "region": f"region_{i}", "start": area.get("start", ""), "end": area.get("end", ""), "bgc_types": ", ".join(products) if products else "unspecified", "n_products": len(products), }) 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")): rows.append({ "input_file": input_file, "contig_id": gbk.stem, "region": gbk.stem.split(".")[-1], "start": "", "end": "", "bgc_types": "see region file", "n_products": 1, }) return pd.DataFrame(rows) # ============================================================ # BLAST database and screening # ============================================================ def db_exists(prefix: Path) -> bool: """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): if reference_upload is None: return None if not command_available("makeblastdb"): raise RuntimeError("makeblastdb is not available. Install ncbi-blast+ in the Docker image.") raw = read_uploaded_to_path(reference_upload, outdir) dec = decompress_if_needed(raw, outdir) norm = normalize_fasta(dec, outdir) prefix = outdir / db_name code, out, err = run_command(["makeblastdb", "-in", str(norm), "-dbtype", "nucl", "-out", str(prefix), "-parse_seqids"]) if code != 0: code, out, err = run_command(["makeblastdb", "-in", str(norm), "-dbtype", "nucl", "-out", str(prefix)]) if code != 0: raise RuntimeError(f"makeblastdb failed for {db_name}.\n{err}\n{out}") return prefix def resolve_database(default_prefix: Path, uploaded_reference, workdir: Path, db_name: str): if uploaded_reference is not None: return build_temp_blast_db(uploaded_reference, workdir, db_name) if db_exists(default_prefix): return default_prefix return None def run_blastn(query_fasta, db_prefix, output_tsv, evalue, max_targets, threads, task): if not command_available("blastn"): raise RuntimeError("blastn is not available. Install ncbi-blast+ in the Docker image.") cmd = [ "blastn", "-task", task, "-query", str(query_fasta), "-db", str(db_prefix), "-evalue", str(evalue), "-max_target_seqs", str(max_targets), "-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.\n{log}") return log def parse_reference_header(stitle, db_type): title = re.sub(r"\s+", " ", str(stitle).strip()) organism = "Unknown" accession = "Unknown" m = re.search(r"\[([^\]]+)\]\s*$", title) if m: organism = m.group(1).strip() title2 = re.sub(r"\[[^\]]+\]\s*$", "", title).strip() else: title2 = title tokens = title2.split() if tokens: accession = tokens[0] pipe_parts = [p.strip() for p in title2.split("|") if p.strip()] candidate = pipe_parts[-1].split()[0] if pipe_parts else accession if db_type == "AMR": gene_symbol = re.sub(r"[^A-Za-z0-9_()./-]", "", candidate) or accession product = title2 else: 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 def infer_functional_group(product, db_type): text = str(product).lower() if db_type == "AMR": groups = { "Beta-lactam resistance": ["beta-lactam", "betalactam", "bla", "carbapenem", "cephalosporin", "penicillin", "oxa", "ctx-m", "tem", "shv", "ndm", "kpc", "vim", "imp"], "Aminoglycoside resistance": ["aminoglycoside", "aac", "aad", "aph", "ant("], "Fluoroquinolone resistance": ["quinolone", "fluoroquinolone", "qnr", "gyr", "parc", "pare"], "Tetracycline resistance": ["tetracycline", "tet("], "Macrolide resistance": ["macrolide", "erm", "mph", "mef", "msr"], "Sulfonamide resistance": ["sulfonamide", "sulphonamide", "sul1", "sul2", "sul3"], "Trimethoprim resistance": ["trimethoprim", "dfr"], "Colistin resistance": ["colistin", "mcr"], "Vancomycin resistance": ["vancomycin", "vana", "vanb", "vanc"], "Efflux-mediated resistance": ["efflux", "acr", "mex", "emr", "mdf", "ade", "oqx"], "Chloramphenicol resistance": ["chloramphenicol", "cat", "flo"], "Rifampicin resistance": ["rifampicin", "rifampin", "rpo"], } for group, words in groups.items(): if any(w in text for w in words): return group return "AMR other or unclassified" groups = { "Adhesion": ["adhesin", "fimbr", "pil", "pili", "curli", "intimin", "attachment", "adherence"], "Toxin": ["toxin", "enterotoxin", "cytotoxin", "hemolysin", "haemolysin", "leukotoxin", "shiga", "exotoxin"], "Secretion system": ["type iii", "type iv", "type vi", "secret", "injectisome", "effector"], "Capsule": ["capsule", "capsular", "polysaccharide", "k antigen"], "Iron acquisition": ["siderophore", "iron", "heme", "haem", "ferric", "ferrous"], "Motility": ["flagell", "motility", "chemotaxis"], "Invasion": ["invasion", "internalin", "invasin"], "Immune evasion": ["serum resistance", "complement", "immune evasion", "antiphagocytic"], "Biofilm": ["biofilm", "pellicle", "matrix"], "Enzyme": ["protease", "lipase", "hyaluronidase", "neuraminidase", "collagenase"], } for group, words in groups.items(): if any(w in text for w in words): return group return "Other or unclassified" 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" ] if not Path(blast_tsv).exists() or Path(blast_tsv).stat().st_size == 0: return pd.DataFrame(columns=cols) df = pd.read_csv(blast_tsv, sep="\t", header=None, names=cols) 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) # 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"] >= 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 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 {db_type}" 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 def apply_species_filter(df, species_text, mode): if df.empty or not str(species_text).strip(): return df q = str(species_text).strip().lower() organisms = df["source_organism"].astype(str).str.lower() if mode == "Exact species": return df[organisms.str.strip() == q].copy() if mode == "Genus-level": genus = q.split()[0] return df[organisms.str.contains(genus, regex=False)].copy() return df[organisms.str.contains(q, regex=False)].copy() # ============================================================ # NCBI AMRFinderPlus # ============================================================ def amrfinder_available() -> bool: return command_available("amrfinder") def amrfinder_version() -> str: if not amrfinder_available(): return "AMRFinderPlus not available." code, out, err = run_command(["amrfinder", "-V"]) text = (out or err or "").strip() return text if text else "AMRFinderPlus version could not be determined." def run_amrfinderplus(fasta_path, output_tsv, threads=1, organism=""): """Run NCBI AMRFinderPlus on assembled nucleotide sequence. The --plus option adds selected virulence, stress, biocide, heat, acid, and metal resistance genes to the core AMR calls. The function retries without the organism flag, then without the threads flag, so that an unsupported flag does not stop the run. A missing AMRFinderPlus database is reported as a clear error. """ if not amrfinder_available(): raise RuntimeError("AMRFinderPlus is not available. Install ncbi-amrfinderplus in the Docker image.") def build_cmd(use_threads, use_organism): cmd = ["amrfinder", "-n", str(fasta_path), "--plus", "-o", str(output_tsv)] if use_threads: cmd.extend(["--threads", str(max(1, int(threads)))]) if use_organism and str(organism).strip(): cmd.extend(["--organism", str(organism).strip()]) return cmd attempts = [ build_cmd(True, True), build_cmd(True, False), # drop organism if it is rejected build_cmd(False, False), # drop threads if it is rejected ] last_log = "" for cmd in attempts: code, out, err = run_command(cmd) last_log = "COMMAND:\n" + " ".join(cmd) + "\n\nSTDOUT:\n" + out + "\n\nSTDERR:\n" + err low = (err or "").lower() if ("no amrfinder database" in low) or ("amrfinder -u" in low) or ("please run" in low and "database" in low): raise RuntimeError( "AMRFinderPlus database is not installed. Run 'amrfinder -u' during the Docker build " "so the database is present before deployment.\n" + last_log ) if code == 0: return last_log raise RuntimeError("AMRFinderPlus failed after retries.\n" + last_log) def _first_existing_col(df, candidates): lower_map = {c.lower().strip(): c for c in df.columns} for cand in candidates: if cand.lower().strip() in lower_map: return lower_map[cand.lower().strip()] for c in df.columns: cl = c.lower().strip() if any(cand.lower().strip() in cl for cand in candidates): return c return None 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.""" output_tsv = Path(output_tsv) if not output_tsv.exists() or output_tsv.stat().st_size == 0: return pd.DataFrame() df = pd.read_csv(output_tsv, sep="\t") if df.empty: return pd.DataFrame() gene_col = _first_existing_col(df, ["Gene symbol", "Gene", "Element symbol"]) seq_col = _first_existing_col(df, ["Sequence name", "Name of closest sequence", "Protein name", "Element name"]) contig_col = _first_existing_col(df, ["Contig id", "Contig", "Sequence identifier"]) start_col = _first_existing_col(df, ["Start"]) stop_col = _first_existing_col(df, ["Stop", "End"]) strand_col = _first_existing_col(df, ["Strand"]) type_col = _first_existing_col(df, ["Element type", "Type"]) subtype_col = _first_existing_col(df, ["Element subtype", "Subtype"]) class_col = _first_existing_col(df, ["Class"]) subclass_col = _first_existing_col(df, ["Subclass"]) method_col = _first_existing_col(df, ["Method"]) coverage_col = _first_existing_col(df, ["% Coverage of reference sequence", "Coverage of reference sequence", "Coverage"]) identity_col = _first_existing_col(df, ["% Identity to reference sequence", "Identity to reference sequence", "Identity"]) accession_col = _first_existing_col(df, ["Accession of closest sequence", "Accession"]) rows = [] for _, row in df.iterrows(): element_type = str(row.get(type_col, "") if type_col else "") element_subtype = str(row.get(subtype_col, "") if subtype_col else "") cls = str(row.get(class_col, "") if class_col else "") subclass = str(row.get(subclass_col, "") if subclass_col else "") method = str(row.get(method_col, "") if method_col else "") text = " ".join([element_type, element_subtype, cls, subclass, method]).lower() if "virulence" in text or element_type.lower().strip() == "virulence": database = "Virulence" elif any(x in text for x in ["stress", "biocide", "metal", "heat", "acid"]): database = "Stress_Biocide" else: database = "AMR" gene = str(row.get(gene_col, "Unknown") if gene_col else "Unknown") product = str(row.get(seq_col, "") if seq_col else "") functional_group = subclass or cls or element_subtype or element_type or infer_functional_group(product + " " + gene, "AMR" if database == "AMR" else "VFDB") try: identity = float(row.get(identity_col, 0)) if identity_col else 0.0 except Exception: identity = 0.0 try: coverage = float(row.get(coverage_col, 0)) if coverage_col else 0.0 except Exception: coverage = 0.0 try: start = int(row.get(start_col, 0)) if start_col else 0 except Exception: start = 0 try: stop = int(row.get(stop_col, 0)) if stop_col else 0 except Exception: stop = 0 rows.append({ "qseqid": str(row.get(contig_col, "Unknown") if contig_col else "Unknown"), "sseqid": gene, "stitle": product, "pident": identity, "length": abs(stop - start) + 1 if start and stop else 0, "mismatch": np.nan, "gapopen": np.nan, "qstart": start, "qend": stop, "sstart": np.nan, "send": np.nan, "evalue": np.nan, "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, "product_name": product, "source_organism": "NCBI AMRFinderPlus reference", "reference_accession": str(row.get(accession_col, "") if accession_col else ""), "functional_group": functional_group, "database": database, "input_file": input_file, "detection_source": "NCBI AMRFinderPlus --plus", "element_type": element_type, "element_subtype": element_subtype, "class": cls, "subclass": subclass, "method": method, }) return pd.DataFrame(rows) # ============================================================ # Codon usage and ORF analysis # ============================================================ 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: forward = rec["sequence"].upper() seq_len = len(forward) def scan(sequence, strand): found = 0 for frame in range(3): 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 current_start = None scan(forward, 1) scan(reverse_complement(forward), -1) return pd.DataFrame(rows) def codon_counts_from_sequences(sequences): counts = Counter() for seq in sequences: s = re.sub(r"[^ACGT]", "", str(seq).upper()) usable = len(s) - (len(s) % 3) for i in range(0, usable, 3): codon = s[i:i + 3] if codon in GENETIC_CODE and codon not in STOP_CODONS: counts[codon] += 1 return counts def compute_rscu(codon_counts, input_file): rows = [] total = max(1, sum(codon_counts.values())) for aa, codons in sorted(AA_TO_CODONS.items()): aa_total = sum(codon_counts.get(c, 0) for c in codons) expected = aa_total / len(codons) if codons else 0 for codon in sorted(codons): obs = codon_counts.get(codon, 0) rows.append({ "input_file": input_file, "amino_acid": aa, "codon": codon, "count": int(obs), "frequency_per_1000": round(obs / total * 1000, 5), "RSCU": round((obs / expected) if expected else 0, 5), "GC3": 1 if codon[2] in {"G", "C"} else 0, }) return pd.DataFrame(rows) def compute_enc(codon_counts): 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) 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 0 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 round(float(min(max(enc, 20), 61)), 4) def load_cai_weights(uploaded): if uploaded is None: return {} text = uploaded.getvalue().decode("utf-8", errors="replace") df = pd.read_csv(io.StringIO(text)) df.columns = [c.strip().lower() for c in df.columns] codon_col = "codon" if "codon" in df.columns else df.columns[0] weight_col = "weight" if "weight" in df.columns else "cai_weight" if "cai_weight" in df.columns else df.columns[1] weights = {} for _, row in df.iterrows(): codon = str(row[codon_col]).upper().replace("U", "T").strip() try: val = float(row[weight_col]) except Exception: continue if codon in GENETIC_CODE: weights[codon] = max(0.0, min(1.0, val)) return weights def compute_cai(codon_counts, weights): weighted_log_sum = 0.0 included_codons = 0 for codon, count in codon_counts.items(): 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 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": "annotator_cds"} for gid, s in cds_pairs ]) else: orf_table = find_orfs(records, input_file, min_aa=min_orf_aa) if not orf_table.empty: seqs = orf_table["sequence"].tolist() cds_pairs = list(zip(orf_table["orf_id"].tolist(), seqs)) orf_df = orf_table.drop(columns=["sequence"], errors="ignore") else: seqs = [r["sequence"] for r in records] cds_pairs = [(r["id"], r["sequence"]) for r in records] orf_df = pd.DataFrame() counts = codon_counts_from_sequences(seqs) rscu = compute_rscu(counts, input_file) total_codons = int(sum(counts.values())) gc3 = sum(v for codon, v in counts.items() if codon[2] in {"G", "C"}) stats = pd.DataFrame([{ "input_file": input_file, "predicted_ORFs_used": int(len(cds_pairs)), "total_sense_codons": total_codons, "GC3_percent": round((gc3 / total_codons * 100) if total_codons else 0, 4), "effective_number_of_codons_ENc": compute_enc(counts), "CAI": compute_cai(counts, cai_weights) if cai_weights else 0, }]) per_gene = cbe.per_gene_codon_indices(cds_pairs, input_file, min_codons=100) aa_comp = cbe.amino_acid_composition_from_cds(cds_pairs, input_file) return orf_df, rscu, stats, per_gene, aa_comp 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 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_reference_coverage_pct", ] if hit_df.empty: return pd.DataFrame(columns=columns) 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) 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_reference_coverage_pct=(coverage_col, "mean"), ).reset_index() out.insert(0, "database", db_type) for column in ["mean_identity_pct", "mean_reference_coverage_pct"]: out[column] = out[column].round(3) return out.sort_values( ["number_of_hits", "unique_genes"], ascending=[False, False], ) def format_hit_table(hit_df): 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.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() 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): base = genome_df.copy() if not annotation_df.empty: base = base.merge(annotation_df, on="input_file", how="left") 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), functional_groups=("functional_group", pd.Series.nunique), mean_identity_pct=("pident", "mean"), ).reset_index() grouped = grouped.rename(columns={ "hits": f"{db_type}_hits", "unique_genes": f"{db_type}_unique_genes", "functional_groups": f"{db_type}_functional_groups", "mean_identity_pct": f"{db_type}_mean_identity_pct", }) 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) for col in base.columns: if col.endswith("_mean_identity_pct"): base[col] = base[col].fillna(0).round(3) return base.fillna(0) def generate_report_paragraph(row): return ( 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"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"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." ) # ============================================================ # Figures # ============================================================ def style_axes(ax): ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) def fig_to_png_bytes(fig): buf = io.BytesIO() fig.savefig(buf, format="png", dpi=300, bbox_inches="tight") buf.seek(0) return buf.read() def fig_to_pdf_bytes(fig): buf = io.BytesIO() fig.savefig(buf, format="pdf", bbox_inches="tight") buf.seek(0) return buf.read() 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=PALETTE["primary"], edgecolor="white") ax.set_title("Contig length distribution") ax.set_xlabel("Contig length bp") ax.set_ylabel("Frequency") style_axes(ax) return fig def fig_top_contigs(contig_df): if contig_df.empty: return None 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=PALETTE["primary"], edgecolor="white") ax.set_title("Top contig lengths") ax.set_xlabel("Contig rank") ax.set_ylabel("Length bp") style_axes(ax) return fig def fig_gc_by_contig(contig_df): if contig_df.empty: 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=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) return fig def fig_feature_counts(feature_df): if feature_df.empty: return None 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=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) style_axes(ax) return fig def fig_cds_length(feature_df): if feature_df.empty: return None cds = feature_df[feature_df["feature_type"] == "CDS"] if cds.empty: return None fig, ax = plt.subplots(figsize=(8, 5), dpi=300) 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) return fig def fig_hypothetical_status(feature_df): if feature_df.empty: return None cds = feature_df[feature_df["feature_type"] == "CDS"] if cds.empty: return None product_lower = cds["product"].fillna("").str.lower() hypothetical = int(product_lower.str.contains("hypothetical protein", regex=False).sum()) functional = int(len(cds) - hypothetical) fig, ax = plt.subplots(figsize=(6.5, 5), dpi=300) ax.bar(["Functional CDS", "Hypothetical CDS"], [functional, hypothetical], 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.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=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) style_axes(ax) return fig 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 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(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): 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=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) return fig 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.""" 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: class_label = sub["class"].fillna("").astype(str).str.strip() else: class_label = pd.Series([""] * len(sub), index=sub.index) fallback = sub["functional_group"].fillna("Unclassified").astype(str).str.strip() class_label = class_label.where(class_label != "", fallback).replace("", "Unclassified") counts = class_label.value_counts().head(20) if counts.empty: return None fig, ax = plt.subplots(figsize=(9, 6), dpi=300) 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) return fig def fig_top_virulence_genes(hit_df): 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): 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): 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" 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(f"{db_type} 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_virulence_heatmap(hit_df, basis): """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): if smc_df is None or smc_df.empty: return None types = [] for v in smc_df["bgc_types"].fillna(""): for t in str(v).split(","): t = t.strip() if t and t not in ("unspecified", "see region file"): types.append(t) if not types: 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=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) style_axes(ax) return fig def fig_rscu(rscu_df, isolate): if rscu_df.empty: return None sub = rscu_df[rscu_df["input_file"] == isolate] if sub.empty: 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=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) style_axes(ax) return fig def fig_window_gc(window_df, isolate): if window_df.empty: return None 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] fig, ax = plt.subplots(figsize=(10, 4.8), dpi=300) 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="--") style_axes(ax) return fig def fig_gc_skew(window_df, isolate): if window_df.empty: return None 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].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=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="--") style_axes(ax) return fig def collect_figures(tables, heatmap_basis): figures = {} genome_df = tables.get("genome_statistics", pd.DataFrame()) contig_df = tables.get("contig_statistics", pd.DataFrame()) feature_df = tables.get("annotation_feature_table", pd.DataFrame()) 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()) 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()) aa_df = tables.get("amino_acid_composition", pd.DataFrame()) smc_df = tables.get("secondary_metabolite_clusters", pd.DataFrame()) fig_builders = { "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), "figure_05_feature_type_counts": lambda: fig_feature_counts(feature_df), "figure_06_cds_length_distribution": lambda: fig_cds_length(feature_df), "figure_07_functional_annotation_status": lambda: fig_hypothetical_status(feature_df), "figure_08_virulence_functional_groups": lambda: fig_detection_groups(vf_summary, "Virulence hits by functional group"), "figure_09_amr_resistance_groups": lambda: fig_detection_groups(amr_summary, "AMR hits by resistance class"), "figure_10_virulence_identity_coverage": lambda: fig_virulence_identity_coverage(hit_df), "figure_11_amr_identity_coverage": lambda: fig_identity_coverage(hit_df, "AMR"), "figure_12_top_virulence_genes": lambda: fig_top_virulence_genes(hit_df), "figure_13_top_amr_genes": lambda: fig_top_genes(hit_df, "AMR"), "figure_14_virulence_heatmap": lambda: fig_virulence_heatmap(hit_df, heatmap_basis), "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), } for name, builder in fig_builders.items(): try: fig = builder() if fig is not None: figures[name] = fig except Exception as 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]: 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]: 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]: 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]: 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 # ============================================================ # Output ZIP # ============================================================ 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(): if df is not None: zf.writestr(f"tables/{sanitize_text(name)}.csv", df.to_csv(index=False)) for name, text in reports.items(): zf.writestr(f"reports/{sanitize_text(name)}.txt", text + "\n") 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", ( 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, a circular genome map, manuscript ready result paragraphs, logs, and publication quality " "figures in PNG and PDF formats.\n" )) mem.seek(0) return mem.read() # ============================================================ # UI # ============================================================ 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. 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 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) run_codon = st.checkbox("Run codon usage analysis", value=True) 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) locus_tag = st.text_input("Locus tag", value="BGA") prokka_compliant = st.checkbox("Use Prokka compliant mode", value=False) prokka_addgenes = st.checkbox("Add gene features", value=True) st.header("BLAST thresholds") 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) st.header("Species filtering") st.caption("Applies to BLAST results only. AMRFinderPlus results are not filtered by organism.") species_filter_text = st.text_input("Reference organism filter", value="") species_filter_mode = st.selectbox("Filter mode", ["Contains text", "Genus-level", "Exact species"], index=0) st.header("Database options") st.caption("Upload database FASTA files if prebuilt databases are not installed in the Docker image.") vfdb_upload = st.file_uploader("Optional VFDB nucleotide FASTA", type=["fa", "fasta", "fna", "fas", "txt", "gz"], key="vfdb_ref") amr_upload = st.file_uploader("Optional AMR nucleotide FASTA", type=["fa", "fasta", "fna", "fas", "txt", "gz"], key="amr_ref") st.header("Codon and window settings") min_orf_aa = st.slider("Minimum ORF length aa", 30, 300, 90, 10) cai_upload = st.file_uploader("Optional CAI weight CSV", type=["csv"]) 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) 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')}") st.write(f"makeblastdb available: {command_available('makeblastdb')}") st.write(f"AMRFinderPlus available: {amrfinder_available()}") st.write(f"AMRFinderPlus version: {amrfinder_version()}") st.write(f"antiSMASH available: {antismash_available()}") st.write(f"antiSMASH version: {antismash_version()}") st.write(f"Streamlit XSRF protection enabled: {st.get_option('server.enableXsrfProtection')}") st.write(f"Streamlit CORS enabled: {st.get_option('server.enableCORS')}") st.write(f"Streamlit max upload size MB: {st.get_option('server.maxUploadSize')}") st.write(f"Installed VFDB database detected: {db_exists(DEFAULT_VFDB_DB_PREFIX)} at {DEFAULT_VFDB_DB_PREFIX}") st.write(f"Installed AMR database detected: {db_exists(DEFAULT_AMR_DB_PREFIX)} at {DEFAULT_AMR_DB_PREFIX}") uploaded_files = st.file_uploader( "Upload one or more bacterial genome FASTA files", type=["fa", "fasta", "fna", "fas", "ffn", "txt", "gz"], accept_multiple_files=True, ) c1, c2 = st.columns(2) run_clicked = c1.button("Run complete genome analysis", type="primary", use_container_width=True) clear_clicked = c2.button("Clear results", use_container_width=True) if clear_clicked: clear_results() if run_clicked: if not uploaded_files: st.error("Please upload at least one bacterial genome FASTA file.") else: invalid = [f.name for f in uploaded_files if not validate_extension(f.name)] total_size_mb = sum(f.size for f in uploaded_files) / (1024 * 1024) if invalid: st.error("Unsupported file type detected: " + ", ".join(invalid)) elif total_size_mb > MAX_UPLOAD_MB: st.error(f"Uploaded files exceed the configured limit of {MAX_UPLOAD_MB} MB.") else: progress = st.progress(0) status = st.empty() annotation_modes = {} try: all_genome_stats = [] all_fasta_quality = [] input_provenance = [] all_contigs = [] all_windows = [] all_features = [] all_annotation_summaries = [] all_hits = [] all_orfs = [] all_rscu = [] all_codon_stats = [] all_per_gene = [] all_aa = [] all_smc = [] logs = {} with tempfile.TemporaryDirectory() as tmp: tmpdir = Path(tmp) raw_dir = tmpdir / "raw" prepared_dir = tmpdir / "prepared" db_dir = tmpdir / "databases" blast_dir = tmpdir / "blast" annotation_root = tmpdir / "annotation" antismash_root = tmpdir / "antismash" 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.") vfdb_prefix = resolve_database(DEFAULT_VFDB_DB_PREFIX, vfdb_upload, db_dir, "vfdb_uploaded") if run_vfdb else None amr_prefix = resolve_database(DEFAULT_AMR_DB_PREFIX, amr_upload, db_dir, "amr_uploaded") if run_amr else None use_amrfinderplus = (run_vfdb or run_amr) and amrfinder_available() if run_vfdb and vfdb_prefix is None and use_amrfinderplus: st.info("No VFDB BLAST database was found, so virulence screening will use the built-in NCBI AMRFinderPlus --plus detector. Upload VFDB FASTA or install a VFDB BLAST database only if you specifically want VFDB based screening.") if run_amr and amr_prefix is None and use_amrfinderplus: st.info("No AMR BLAST database was found, so AMR screening will use the built-in NCBI AMRFinderPlus detector.") # Report missing detectors per module, rather than one combined # message, so the guidance only names the module(s) that were # actually requested and are genuinely unavailable. missing_amr = run_amr and amr_prefix is None and not use_amrfinderplus missing_vfdb = run_vfdb and vfdb_prefix is None and not use_amrfinderplus if missing_amr or missing_vfdb: missing_labels = [] if missing_amr: missing_labels.append("AMR") if missing_vfdb: missing_labels.append("virulence") joined = " or ".join(missing_labels) st.error( f"No {joined} detector is available. The Docker image must install " "ncbi-amrfinderplus, or you must upload VFDB and AMR FASTA databases. " f"{'AMR' if missing_amr else 'Virulence'} screening will be skipped for this run " "until one of the options below is in place." ) with st.expander("How to fix this", expanded=False): st.markdown( "**Option 1: install NCBI AMRFinderPlus in the Docker image (covers both AMR and virulence).**\n" "```\nmicromamba install -n genomics -c bioconda -c conda-forge ncbi-amrfinderplus\namrfinder -u\n```\n" "The `amrfinder -u` step downloads the reference database and must run during " "the image build, before deployment, since this app does not have outbound " "internet access to fetch it at request time.\n\n" "**Option 2: install ncbi-blast+ and mount preinstalled BLAST databases.**\n" "Build nucleotide BLAST databases with `makeblastdb -dbtype nucl` and place them " f"at the paths configured by the `VFDB_DB_PREFIX` (currently `{DEFAULT_VFDB_DB_PREFIX}`) " f"and `AMR_DB_PREFIX` (currently `{DEFAULT_AMR_DB_PREFIX}`) environment variables.\n\n" "**Option 3: upload a reference FASTA directly in this session.**\n" "Use the 'Database options' section in the sidebar to upload a VFDB and/or AMR " "nucleotide FASTA file. The app will build a temporary BLAST database from it " "for this run only.\n\n" "If you do not need this module, you can also simply turn off " f"'{'Detect AMR genes' if missing_amr else 'Detect virulence genes'}' " "in the sidebar to stop seeing this message." ) 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}") comp = genome_composition(records) comp["input_file"] = uploaded.name all_genome_stats.append(comp) contigs = contig_statistics(records, uploaded.name) all_contigs.append(contigs) if run_windows: all_windows.append(window_statistics(records, uploaded.name, int(window_size))) annotation_cds = None if run_annotation: 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}: 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"], ) ) 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=annotation_cds ) all_orfs.append(orfs) all_rscu.append(rscu) all_codon_stats.append(codon_stats) all_per_gene.append(per_gene) all_aa.append(aa_comp) # Secondary metabolite gene clusters (antiSMASH) if run_smc and antismash_available(): smc_out = antismash_root / sample_prefix res_smc = run_antismash(fasta_path, smc_out, sample_prefix, taxon="bacteria", threads=int(threads)) 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)) else: st.warning(f"{uploaded.name}: antiSMASH did not complete. See the logs.") elif run_smc and not antismash_available(): st.info("antiSMASH is not installed, so secondary metabolite detection was skipped. Install antismash in the Docker image to enable it.") # 1) Built-in NCBI AMRFinderPlus: AMR + virulence + stress/biocide/metal if use_amrfinderplus: amr_tsv = blast_dir / f"{sample_prefix}_amrfinderplus.tsv" organism = supported_amrfinder_organism(genus, species) try: logs[f"amrfinderplus_{sample_prefix}"] = run_amrfinderplus( fasta_path, amr_tsv, threads=int(threads), organism=organism ) amr_hits = parse_amrfinderplus_output(amr_tsv, uploaded.name) if not amr_hits.empty: keep_dbs = [] if run_amr: keep_dbs += ["AMR", "Stress_Biocide"] if run_vfdb: keep_dbs += ["Virulence"] amr_hits = amr_hits[amr_hits["database"].isin(keep_dbs)] # No species filter here. AMRFinderPlus rows do not carry a # source organism, so the filter would remove them all. if not amr_hits.empty: all_hits.append(amr_hits) except Exception as exc: logs[f"amrfinderplus_{sample_prefix}"] = f"AMRFinderPlus failed: {exc}" st.warning(f"{uploaded.name}: AMRFinderPlus detection failed. See the logs for details.") # 2) Optional BLAST homology search against installed or uploaded databases for db_type, db_prefix in [("VFDB", vfdb_prefix), ("AMR", amr_prefix)]: if db_prefix is None: continue out_tsv = blast_dir / f"{sample_prefix}_{db_type}.tsv" try: 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) except Exception as exc: logs[f"blast_{db_type}_{sample_prefix}"] = f"BLAST failed: {exc}" progress.progress(100) status.success("Analysis completed.") 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() annotation_df = pd.concat(all_annotation_summaries, ignore_index=True) if all_annotation_summaries else pd.DataFrame() hit_df = pd.concat(all_hits, ignore_index=True) if all_hits else pd.DataFrame() detailed_hits = format_hit_table(hit_df) vf_summary = build_detection_summary(hit_df, "VFDB") amr_summary = build_detection_summary(hit_df, "AMR") 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() per_gene_df = pd.concat(all_per_gene, ignore_index=True) if all_per_gene else pd.DataFrame() aa_df = pd.concat(all_aa, ignore_index=True) if all_aa else pd.DataFrame() smc_df = pd.concat(all_smc, ignore_index=True) if all_smc else pd.DataFrame() isolate_summary = build_isolate_summary(genome_df, annotation_df, hit_df, codon_df) reports = {} for _, row in isolate_summary.iterrows(): reports[f"{sanitize_text(row['input_file'])}_manuscript_result_paragraph"] = generate_report_paragraph(row) 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, "annotation_feature_table": feature_df, "raw_hit_table": hit_df, "detailed_gene_hits": detailed_hits, "virulence_summary": vf_summary, "amr_summary": amr_summary, "secondary_metabolite_clusters": smc_df, "predicted_orfs": orf_df, "rscu_table": rscu_df, "codon_usage_statistics": codon_df, "per_gene_codon_indices": per_gene_df, "amino_acid_composition": aa_df, } figures = collect_figures(tables, heatmap_basis) manifest = { "tool": APP_TITLE, "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": { "genome_annotation": run_annotation, "requested_annotation_engine": annotation_engine, "virulence_screening": run_vfdb, "amr_screening": run_amr, "secondary_metabolites": run_smc, "codon_usage": run_codon, "window_gc_skew": run_windows, }, "thresholds": { "min_identity_percent": min_identity, "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, }, "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"), "makeblastdb_available": command_available("makeblastdb"), "amrfinderplus_available": amrfinder_available(), "amrfinderplus_version": amrfinder_version(), "antismash_available": antismash_available(), "antismash_version": antismash_version(), }, "database_status": { "preinstalled_vfdb_detected": db_exists(DEFAULT_VFDB_DB_PREFIX), "preinstalled_amr_detected": db_exists(DEFAULT_AMR_DB_PREFIX), "uploaded_vfdb_used": vfdb_upload is not None, "uploaded_amr_used": amr_upload is not None, }, } 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 = 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()]) except Exception as exc: st.exception(exc) if st.session_state.run_complete: tables = st.session_state.tables reports = st.session_state.reports isolate_summary = tables.get("isolate_summary", pd.DataFrame()) 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()) 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()) contig_df = tables.get("contig_statistics", pd.DataFrame()) window_df = tables.get("window_gc_skew", pd.DataFrame()) feature_df = tables.get("annotation_feature_table", pd.DataFrame()) per_gene_df = tables.get("per_gene_codon_indices", pd.DataFrame()) aa_df = tables.get("amino_acid_composition", pd.DataFrame()) smc_df = tables.get("secondary_metabolite_clusters", pd.DataFrame()) st.markdown("---") st.subheader("Overall summary") m1, m2, m3, m4, m5 = st.columns(5) m1.metric("Genome files", isolate_summary.shape[0]) m2.metric("Total bases", f"{int(isolate_summary['total_bases'].sum()):,}" if "total_bases" in isolate_summary else "0") m3.metric("Mean GC percent", f"{float(isolate_summary['GC_percent'].mean()):.2f}" if "GC_percent" in isolate_summary else "0") m4.metric("Virulence hits", f"{int(isolate_summary['VFDB_hits'].sum()):,}" if "VFDB_hits" in isolate_summary else "0") m5.metric("AMR hits", f"{int(isolate_summary['AMR_hits'].sum()):,}" if "AMR_hits" in isolate_summary else "0") tab1, tab2, tab3, tab_smc, tab4, tab5, tab6 = st.tabs([ "Summary", "Annotation", "Virulence and AMR", "Secondary metabolites", "Codon and composition", "Figures", "Downloads", ]) with tab1: st.dataframe(isolate_summary, use_container_width=True, height=360) if reports: selected = st.selectbox("Select result paragraph", list(reports.keys())) st.info(reports[selected]) with tab2: st.markdown("### Annotation summary") st.dataframe(tables.get("annotation_summary", pd.DataFrame()), use_container_width=True, height=260) st.markdown("### Annotation feature table") st.dataframe(feature_df, use_container_width=True, height=460) with tab3: st.markdown("### Detailed virulence and AMR gene hits") if detailed_hits.empty: st.warning("No virulence or AMR hits passed the selected thresholds, or no detector was available.") else: st.dataframe(detailed_hits, use_container_width=True, height=460) c1, c2 = st.columns(2) with c1: st.markdown("### Virulence summary") st.dataframe(vf_summary, use_container_width=True, height=300) with c2: st.markdown("### AMR summary") st.dataframe(amr_summary, use_container_width=True, height=300) with tab_smc: st.markdown("### Predicted secondary metabolite biosynthetic gene clusters") if smc_df is None or smc_df.empty: st.warning("No secondary metabolite clusters were detected, or antiSMASH was not enabled or installed.") else: st.dataframe(smc_df, use_container_width=True, height=420) with tab4: st.markdown("### Genome statistics") st.dataframe(genome_df, use_container_width=True, height=280) st.markdown("### Contig statistics") st.dataframe(contig_df, use_container_width=True, height=280) st.markdown("### Window GC and skew") st.dataframe(window_df, use_container_width=True, height=280) st.markdown("### Codon usage statistics") st.dataframe(codon_df, use_container_width=True, height=220) st.markdown("### Per-gene codon indices (ENc, GC3, GC12, PR2)") st.dataframe(per_gene_df, use_container_width=True, height=300) st.markdown("### Amino acid composition") st.dataframe(aa_df, use_container_width=True, height=300) st.markdown("### RSCU table") st.dataframe(rscu_df, use_container_width=True, height=360) with tab5: if not st.session_state.figures_png: st.info("No figures were generated.") else: for name, png in st.session_state.figures_png.items(): st_show_image(png, caption=name) with tab6: st.markdown("### Download complete report") st.download_button( "Download complete ZIP report", data=st.session_state.zip_bytes, file_name="bulamarwa_genomics_suite_report.zip", mime="application/zip", use_container_width=True, ) st.markdown("### Download individual tables") cols = st.columns(3) table_items = list(tables.items()) for i, (name, df) in enumerate(table_items): with cols[i % 3]: st.download_button( f"{name}.csv", dataframe_to_csv_bytes(df), file_name=f"{sanitize_text(name)}.csv", mime="text/csv", use_container_width=True, ) with st.expander("Run manifest"): st.json(st.session_state.manifest) if st.session_state.log_text: with st.expander("Tool logs"): st.text(st.session_state.log_text) 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 Bakta or Prokka, ncbi-blast+, ncbi-amrfinderplus, and antiSMASH can be installed." ) st.caption( 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." )
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 subprocess
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
import streamlit as st
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
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.
# ============================================================
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 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"))
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",
"TAT":"Y","TAC":"Y","TAA":"*","TAG":"*","TGT":"C","TGC":"C","TGA":"*","TGG":"W",
"CTT":"L","CTC":"L","CTA":"L","CTG":"L","CCT":"P","CCC":"P","CCA":"P","CCG":"P",
"CAT":"H","CAC":"H","CAA":"Q","CAG":"Q","CGT":"R","CGC":"R","CGA":"R","CGG":"R",
"ATT":"I","ATC":"I","ATA":"I","ATG":"M","ACT":"T","ACC":"T","ACA":"T","ACG":"T",
"AAT":"N","AAC":"N","AAA":"K","AAG":"K","AGT":"S","AGC":"S","AGA":"R","AGG":"R",
"GTT":"V","GTC":"V","GTA":"V","GTG":"V","GCT":"A","GCC":"A","GCA":"A","GCG":"A",
"GAT":"D","GAC":"D","GAA":"E","GAG":"E","GGT":"G","GGC":"G","GGA":"G","GGG":"G",
}
STOP_CODONS = {"TAA", "TAG", "TGA"}
START_CODONS = {"ATG", "GTG", "TTG"}
AA_TO_CODONS = defaultdict(list)
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",
}