diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,12 +1,26 @@ +""" +GenomeScope Pro: publication grade genome visualization and genome composition analytics. + +Supported inputs: +1. GenBank, EMBL, FASTA, GFF3 plus FASTA, BED plus FASTA, CSV/TSV annotation plus FASTA +2. ZIP archives containing one of the above supported combinations + +Main outputs: +1. Linear and circular genome maps with distinct colours for feature classes +2. GC content, GC skew, cumulative GC skew, nucleotide composition, CpG observed/expected +3. CDS based codon usage, RSCU, ENC, codon adaptation index when a reference codon table is supplied +4. Annotation tables, genome summary tables, and downloadable figure package +""" import io import os import re import gzip +import math import zipfile import tempfile from dataclasses import dataclass -from typing import Dict, List, Tuple +from typing import Dict, List, Optional, Tuple import matplotlib matplotlib.use("Agg") @@ -16,28 +30,44 @@ import numpy as np import pandas as pd import streamlit as st from Bio import SeqIO +from Bio.Seq import Seq from Bio.SeqFeature import CompoundLocation -from dna_features_viewer import GraphicFeature, GraphicRecord -from pycirclize import Circos +from Bio.Data import CodonTable + +try: + from dna_features_viewer import GraphicFeature, GraphicRecord +except Exception: + GraphicFeature = None + GraphicRecord = None + +try: + from pycirclize import Circos +except Exception: + Circos = None try: import gffutils except Exception: gffutils = None +# ----------------------------- +# Page and figure configuration +# ----------------------------- +st.set_page_config( + page_title="GenomeScope Pro", + page_icon="🧬", + layout="wide", + initial_sidebar_state="expanded", +) -# ========================= -# Global style -# ========================= plt.rcParams.update({ "font.family": "sans-serif", "font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans"], "font.size": 10, - "axes.titlesize": 12, + "axes.titlesize": 13, "axes.labelsize": 10, - "axes.linewidth": 0.8, - "xtick.labelsize": 9, - "ytick.labelsize": 9, + "xtick.labelsize": 8, + "ytick.labelsize": 8, "legend.fontsize": 8, "figure.dpi": 160, "savefig.dpi": 600, @@ -45,53 +75,56 @@ plt.rcParams.update({ "ps.fonttype": 42, }) -st.set_page_config( - page_title="Genome Visualization Tool Ultra-Premium", - page_icon="🧬", - layout="wide", - initial_sidebar_state="expanded", -) - st.markdown( """ - - """, + +""", unsafe_allow_html=True, ) FEATURE_COLORS = { - "CDS": "#1f77b4", - "gene": "#2ca02c", - "tRNA": "#ff7f0e", - "rRNA": "#d62728", - "ncRNA": "#9467bd", - "misc_feature": "#8c564b", - "repeat_region": "#7f7f7f", - "mobile_element": "#bcbd22", - "ORF": "#17becf", - "exon": "#4daf4a", - "mRNA": "#984ea3", - "transcript": "#a65628", - "promoter": "#f781bf", - "bed_feature": "#6c757d", - "default": "#4c78a8", - "highlight": "#ffd700", + "CDS": "#2166ac", + "gene": "#1a9850", + "tRNA": "#fdae61", + "rRNA": "#d73027", + "ncRNA": "#762a83", + "misc_RNA": "#9970ab", + "repeat_region": "#636363", + "mobile_element": "#bf812d", + "source": "#bdbdbd", + "exon": "#66bd63", + "mRNA": "#3288bd", + "promoter": "#e78ac3", + "terminator": "#8da0cb", + "ORF": "#00a6a6", + "bed_feature": "#4d4d4d", + "misc_feature": "#8c510a", + "default": "#4575b4", + "highlight": "#ffd92f", } -DEFAULT_FEATURES = ["CDS", "gene", "tRNA", "rRNA", "ncRNA", "misc_feature", "repeat_region", "ORF"] -FASTA_EXTS = {".fa", ".fasta", ".fna", ".fas", ".ffn", ".faa"} + +FASTA_EXTS = {".fa", ".fasta", ".fna", ".fas", ".ffn"} +PROTEIN_EXTS = {".faa", ".pep"} GB_EXTS = {".gb", ".gbk", ".genbank"} EMBL_EXTS = {".embl"} GFF_EXTS = {".gff", ".gff3", ".gtf"} BED_EXTS = {".bed"} TABLE_EXTS = {".csv", ".tsv", ".txt"} -DNA_COMPLEMENT = str.maketrans("ATGCatgcNn", "TACGtacgNn") +DEFAULT_FEATURES = ["CDS", "gene", "tRNA", "rRNA", "ncRNA", "repeat_region", "mobile_element", "misc_feature", "ORF"] +DNA_COMPLEMENT = str.maketrans("ACGTNacgtn", "TGCANtgcan") +STANDARD_TABLE = CodonTable.unambiguous_dna_by_id[11] +STOP_CODONS = set(STANDARD_TABLE.stop_codons) +SENSE_CODONS = sorted([c for c in STANDARD_TABLE.forward_table.keys()]) +AA_TO_CODONS: Dict[str, List[str]] = {} +for codon, aa in STANDARD_TABLE.forward_table.items(): + AA_TO_CODONS.setdefault(aa, []).append(codon) @dataclass @@ -102,51 +135,18 @@ class ParsedGenome: notes: List[str] -def init_session_state(): - defaults = { - "analysis_done": False, - "analysis_error": "", - "parsed": None, - "record_ids": [], - "selected_record_id": None, - "full_df": pd.DataFrame(), - "filtered_df": pd.DataFrame(), - "display_df": pd.DataFrame(), - "stats": {}, - "notes": [], - "available_types": [], - "selected_types_cache": [], - "stats_df": pd.DataFrame(), - "dist_df": pd.DataFrame(), - "density_df": pd.DataFrame(), - "summary_text": "", - "figure_pack": {}, - "table_csv": None, - "summary_zip": None, - "legend_html": "", - "run_mode_cache": "Fast preview", - } - for k, v in defaults.items(): - if k not in st.session_state: - st.session_state[k] = v - - -def clear_results(): - keys = [k for k in st.session_state.keys() if not k.startswith("_")] - for key in keys: - del st.session_state[key] - init_session_state() - - -def normalize_text(value: str) -> str: +# ----------------------------- +# General helpers +# ----------------------------- +def clean_text(value: object) -> str: return re.sub(r"\s+", " ", str(value or "")).strip() def file_suffix(name: str) -> str: - n = str(name).lower() - if n.endswith(".gz"): - n = os.path.splitext(n)[0] - return os.path.splitext(n)[1] + name = str(name).lower() + if name.endswith(".gz"): + name = os.path.splitext(name)[0] + return os.path.splitext(name)[1] def maybe_decompress(name: str, data: bytes) -> Tuple[str, bytes]: @@ -157,220 +157,89 @@ def maybe_decompress(name: str, data: bytes) -> Tuple[str, bytes]: def infer_file_kind(filename: str) -> str: ext = file_suffix(filename) + if str(filename).lower().endswith(".zip"): + return "zip" if ext in GB_EXTS: return "genbank" if ext in EMBL_EXTS: return "embl" if ext in FASTA_EXTS: return "fasta" + if ext in PROTEIN_EXTS: + return "protein" if ext in GFF_EXTS: return "gff" if ext in BED_EXTS: return "bed" if ext in TABLE_EXTS: return "table" - if str(filename).lower().endswith(".zip"): - return "zip" return "unknown" -def get_feature_bounds(feature): - strand = feature.location.strand if feature.location.strand in (-1, 1) else 0 - if isinstance(feature.location, CompoundLocation): - parts = list(feature.location.parts) - start = int(min(part.start for part in parts)) - end = int(max(part.end for part in parts)) - else: - start = int(feature.location.start) - end = int(feature.location.end) - return start, end, strand - - -def get_feature_label(feature): - qualifiers = getattr(feature, "qualifiers", {}) or {} - for key in ["gene", "locus_tag", "product", "note", "ID", "Name"]: - if key in qualifiers and qualifiers[key]: - return str(qualifiers[key][0]) - return getattr(feature, "type", "feature") +def parse_text_records(data: bytes, fmt: str): + handle = io.StringIO(data.decode("utf-8", errors="replace")) + return list(SeqIO.parse(handle, fmt)) -def compute_gc_percent(sequence: str) -> float: - seq = str(sequence).upper() - if not seq: - return 0.0 - gc = seq.count("G") + seq.count("C") - return (gc / len(seq)) * 100.0 +def reverse_complement(seq: str) -> str: + return seq.translate(DNA_COMPLEMENT)[::-1] -def chunk_gc_content(sequence: str, window_size: int = 1000) -> Tuple[List[int], List[float]]: - seq = str(sequence).upper() - positions, values = [], [] - for i in range(0, len(seq), window_size): - window = seq[i:i + window_size] - if window: - positions.append(i + len(window) // 2) - values.append(compute_gc_percent(window)) - return positions, values +def safe_feature_bounds(feature) -> Tuple[int, int, int]: + strand = feature.location.strand if feature.location.strand in (-1, 1) else 0 + if isinstance(feature.location, CompoundLocation): + starts = [int(part.start) for part in feature.location.parts] + ends = [int(part.end) for part in feature.location.parts] + return min(starts), max(ends), int(strand) + return int(feature.location.start), int(feature.location.end), int(strand) -def gc_skew_windows(sequence: str, window_size: int = 1000) -> Tuple[List[int], List[float]]: - seq = str(sequence).upper() - positions, values = [], [] - for i in range(0, len(seq), window_size): - window = seq[i:i + window_size] - g = window.count("G") - c = window.count("C") - denom = g + c - positions.append(i + len(window) // 2) - values.append((g - c) / denom if denom else 0.0) - return positions, values +def get_feature_label(feature) -> str: + q = getattr(feature, "qualifiers", {}) or {} + for key in ["gene", "locus_tag", "product", "standard_name", "note", "ID", "Name"]: + if q.get(key): + return clean_text(q[key][0]) + return clean_text(getattr(feature, "type", "feature")) +# ----------------------------- +# Parsing and annotation handling +# ----------------------------- def record_to_feature_table(record) -> pd.DataFrame: rows = [] for feature in getattr(record, "features", []): try: - start, end, strand = get_feature_bounds(feature) - qualifiers = getattr(feature, "qualifiers", {}) or {} + start, end, strand = safe_feature_bounds(feature) + q = getattr(feature, "qualifiers", {}) or {} rows.append({ "record_id": record.id, - "feature_type": getattr(feature, "type", "feature"), + "feature_type": clean_text(getattr(feature, "type", "feature")), "label": get_feature_label(feature), - "start": int(start), - "end": int(end), + "start": max(0, int(start)), + "end": min(len(record.seq), int(end)), "length": max(0, int(end) - int(start)), - "strand": int(strand), - "locus_tag": "; ".join(qualifiers.get("locus_tag", [])), - "gene": "; ".join(qualifiers.get("gene", [])), - "product": "; ".join(qualifiers.get("product", [])), - "note": "; ".join(qualifiers.get("note", [])), - "source": "annotation", + "strand": strand, + "gene": "; ".join(q.get("gene", [])), + "locus_tag": "; ".join(q.get("locus_tag", [])), + "product": "; ".join(q.get("product", [])), + "protein_id": "; ".join(q.get("protein_id", [])), + "translation": "; ".join(q.get("translation", [])), + "note": "; ".join(q.get("note", [])), + "source": "GenBank/EMBL annotation", }) except Exception: continue - cols = ["record_id", "feature_type", "label", "start", "end", "length", "strand", "locus_tag", "gene", "product", "note", "source"] - return pd.DataFrame(rows, columns=cols).sort_values(["start", "end"], kind="stable").reset_index(drop=True) - - -def reverse_complement(seq: str) -> str: - return seq.translate(DNA_COMPLEMENT)[::-1] - - -def find_orfs_in_sequence(sequence: str, min_aa: int = 90, max_orfs: int = 2500) -> pd.DataFrame: - seq = str(sequence).upper() - seq_len = len(seq) - stops = {"TAA", "TAG", "TGA"} - starts = {"ATG", "GTG", "TTG"} - rows = [] - - def scan_strand(s: str, strand_val: int): - nonlocal rows - for frame in range(3): - i = frame - while i <= len(s) - 3: - if len(rows) >= max_orfs: - return - codon = s[i:i + 3] - if codon in starts: - j = i + 3 - while j <= len(s) - 3: - stop = s[j:j + 3] - if stop in stops: - nt_len = (j + 3) - i - aa_len = nt_len // 3 - if aa_len >= min_aa: - if strand_val == 1: - start, end = i, j + 3 - else: - start = seq_len - (j + 3) - end = seq_len - i - rows.append({ - "feature_type": "ORF", - "label": f"ORF_{strand_val}_{start+1}_{end}", - "start": int(start), - "end": int(end), - "length": int(end - start), - "strand": int(strand_val), - "locus_tag": "", - "gene": "", - "product": f"Predicted ORF ({aa_len} aa)", - "note": "FASTA-only inferred ORF", - "source": "orf_prediction", - }) - i = j + 3 - break - j += 3 - i += 3 - - scan_strand(seq, 1) - scan_strand(reverse_complement(seq), -1) - cols = ["feature_type", "label", "start", "end", "length", "strand", "locus_tag", "gene", "product", "note", "source"] - return pd.DataFrame(rows, columns=cols).sort_values(["start", "end"], kind="stable").reset_index(drop=True) - - -def parse_text_records(data: bytes, fmt: str): - handle = io.StringIO(data.decode("utf-8", errors="replace")) - return list(SeqIO.parse(handle, fmt)) - - -def parse_annotation_table(data: bytes, fasta_bytes: bytes) -> Tuple[List, Dict[str, pd.DataFrame]]: - text = data.decode("utf-8", errors="replace") - first = text.splitlines()[0] if text.splitlines() else "" - sep = "," if "," in first else "\t" - df = pd.read_csv(io.StringIO(text), sep=sep) - df.columns = [c.strip() for c in df.columns] - colmap = {c.lower(): c for c in df.columns} - start_col = colmap.get("start") - end_col = colmap.get("end") - if start_col is None or end_col is None: - raise ValueError("Annotation table requires start and end columns.") - record_col = colmap.get("record_id") or colmap.get("seqid") or colmap.get("chrom") or colmap.get("contig") - type_col = colmap.get("feature_type") or colmap.get("type") - label_col = colmap.get("label") or colmap.get("gene") or colmap.get("name") - strand_col = colmap.get("strand") - product_col = colmap.get("product") - note_col = colmap.get("note") - locus_col = colmap.get("locus_tag") - - records = parse_text_records(fasta_bytes, "fasta") - if not records: - raise ValueError("No FASTA records found for annotation table pairing.") - tables = {} - - for r in records: - sdf = df if record_col is None else df[df[record_col].astype(str) == r.id].copy() - if record_col is not None and sdf.empty: - sdf = df[df[record_col].astype(str) == r.id.split()[0]].copy() - if sdf.empty: - tables[r.id] = pd.DataFrame(columns=["record_id","feature_type","label","start","end","length","strand","locus_tag","gene","product","note","source"]) - continue - - out = pd.DataFrame({ - "record_id": r.id, - "feature_type": sdf[type_col].astype(str) if type_col else "misc_feature", - "label": sdf[label_col].astype(str) if label_col else "feature", - "start": sdf[start_col].astype(int), - "end": sdf[end_col].astype(int), - "strand": sdf[strand_col].replace({"+": 1, "-": -1}).fillna(0).astype(int) if strand_col else 0, - "locus_tag": sdf[locus_col].astype(str) if locus_col else "", - "gene": sdf[label_col].astype(str) if label_col else "", - "product": sdf[product_col].astype(str) if product_col else "", - "note": sdf[note_col].astype(str) if note_col else "", - "source": "table", - }) - out["length"] = (out["end"] - out["start"]).clip(lower=0) - tables[r.id] = out[["record_id","feature_type","label","start","end","length","strand","locus_tag","gene","product","note","source"]].sort_values(["start","end"]).reset_index(drop=True) - - return records, tables + columns = ["record_id", "feature_type", "label", "start", "end", "length", "strand", "gene", "locus_tag", "product", "protein_id", "translation", "note", "source"] + return pd.DataFrame(rows, columns=columns).sort_values(["start", "end"], kind="stable").reset_index(drop=True) def build_gff_db(gff_text: str, workdir: str): if gffutils is None: - raise RuntimeError("gffutils is not installed.") + raise RuntimeError("gffutils is required for GFF/GTF parsing. Install it with: pip install gffutils") gff_path = os.path.join(workdir, "input.gff3") - with open(gff_path, "w", encoding="utf-8") as f: - f.write(gff_text) - db_path = os.path.join(workdir, "temp_gff.db") + with open(gff_path, "w", encoding="utf-8") as handle: + handle.write(gff_text) + db_path = os.path.join(workdir, "input.db") return gffutils.create_db( gff_path, dbfn=db_path, @@ -384,815 +253,953 @@ def build_gff_db(gff_text: str, workdir: str): def gff_and_fasta_to_tables(gff_bytes: bytes, fasta_bytes: bytes) -> Tuple[List, Dict[str, pd.DataFrame]]: - gff_text = gff_bytes.decode("utf-8", errors="replace") records = parse_text_records(fasta_bytes, "fasta") if not records: - raise ValueError("No FASTA records found.") - record_map = {r.id: r for r in records} - alt_map = {r.id.split()[0]: r for r in records} - alt_map.update({r.name: r for r in records}) - tables = {r.id: [] for r in records} - - with tempfile.TemporaryDirectory() as td: - db = build_gff_db(gff_text, td) + raise ValueError("No FASTA records were found for the GFF/GTF pairing.") + record_lookup = {r.id: r for r in records} + record_lookup.update({r.id.split()[0]: r for r in records}) + rows_by_record = {r.id: [] for r in records} + with tempfile.TemporaryDirectory() as temp_dir: + db = build_gff_db(gff_bytes.decode("utf-8", errors="replace"), temp_dir) for feature in db.all_features(): - seqid = str(feature.seqid) - record = record_map.get(seqid) or alt_map.get(seqid) + record = record_lookup.get(str(feature.seqid)) if record is None: continue attrs = feature.attributes or {} label = attrs.get("Name", [""])[0] or attrs.get("gene", [""])[0] or attrs.get("locus_tag", [""])[0] or attrs.get("ID", [""])[0] or feature.featuretype strand = 1 if feature.strand == "+" else -1 if feature.strand == "-" else 0 - tables[record.id].append({ + rows_by_record[record.id].append({ "record_id": record.id, - "feature_type": str(feature.featuretype), - "label": normalize_text(label), + "feature_type": clean_text(feature.featuretype), + "label": clean_text(label), "start": max(0, int(feature.start) - 1), - "end": int(feature.end), - "length": max(0, int(feature.end) - (int(feature.start) - 1)), + "end": min(len(record.seq), int(feature.end)), + "length": max(0, int(feature.end) - int(feature.start) + 1), "strand": strand, - "locus_tag": "; ".join(attrs.get("locus_tag", [])), "gene": "; ".join(attrs.get("gene", [])), + "locus_tag": "; ".join(attrs.get("locus_tag", [])), "product": "; ".join(attrs.get("product", [])), + "protein_id": "; ".join(attrs.get("protein_id", [])), + "translation": "", "note": "; ".join(attrs.get("Note", [])), - "source": "gff", + "source": "GFF/GTF annotation", }) - - out = {} - cols = ["record_id","feature_type","label","start","end","length","strand","locus_tag","gene","product","note","source"] - for rec in records: - out[rec.id] = pd.DataFrame(tables.get(rec.id, []), columns=cols).sort_values(["start","end"], kind="stable").reset_index(drop=True) - return records, out + columns = ["record_id", "feature_type", "label", "start", "end", "length", "strand", "gene", "locus_tag", "product", "protein_id", "translation", "note", "source"] + return records, {r.id: pd.DataFrame(rows_by_record[r.id], columns=columns).sort_values(["start", "end"], kind="stable").reset_index(drop=True) for r in records} def bed_and_fasta_to_tables(bed_bytes: bytes, fasta_bytes: bytes) -> Tuple[List, Dict[str, pd.DataFrame]]: records = parse_text_records(fasta_bytes, "fasta") if not records: - raise ValueError("No FASTA records found.") - df = pd.read_csv(io.StringIO(bed_bytes.decode("utf-8", errors="replace")), sep="\t", comment="#", header=None) - df = df.iloc[:, :min(6, df.shape[1])] - df.columns = ["seqid", "start", "end", "name", "score", "strand"][:df.shape[1]] + raise ValueError("No FASTA records were found for the BED pairing.") + bed = pd.read_csv(io.StringIO(bed_bytes.decode("utf-8", errors="replace")), sep="\t", header=None, comment="#") + bed = bed.iloc[:, :min(6, bed.shape[1])] + bed.columns = ["seqid", "start", "end", "name", "score", "strand"][:bed.shape[1]] + columns = ["record_id", "feature_type", "label", "start", "end", "length", "strand", "gene", "locus_tag", "product", "protein_id", "translation", "note", "source"] tables = {} - cols = ["record_id","feature_type","label","start","end","length","strand","locus_tag","gene","product","note","source"] - - for r in records: - sdf = df[df["seqid"].astype(str) == r.id].copy() if "seqid" in df.columns else pd.DataFrame() + for record in records: + sdf = bed[bed["seqid"].astype(str).isin([record.id, record.id.split()[0]])].copy() if sdf.empty: - tables[r.id] = pd.DataFrame(columns=cols) + tables[record.id] = pd.DataFrame(columns=columns) continue out = pd.DataFrame({ - "record_id": r.id, + "record_id": record.id, "feature_type": "bed_feature", - "label": sdf["name"].astype(str) if "name" in sdf.columns else "BED_feature", - "start": sdf["start"].astype(int), - "end": sdf["end"].astype(int), - "strand": sdf["strand"].replace({"+":1, "-":-1}).fillna(0).astype(int) if "strand" in sdf.columns else 0, + "label": sdf["name"].astype(str) if "name" in sdf else "BED_feature", + "start": sdf["start"].astype(int).clip(lower=0), + "end": sdf["end"].astype(int).clip(upper=len(record.seq)), + "strand": sdf["strand"].replace({"+": 1, "-": -1}).fillna(0).astype(int) if "strand" in sdf else 0, + "gene": sdf["name"].astype(str) if "name" in sdf else "", "locus_tag": "", - "gene": sdf["name"].astype(str) if "name" in sdf.columns else "", "product": "", - "note": "Imported from BED", - "source": "bed", + "protein_id": "", + "translation": "", + "note": "Imported BED coordinate", + "source": "BED annotation", + }) + out["length"] = (out["end"] - out["start"]).clip(lower=0) + tables[record.id] = out[columns].sort_values(["start", "end"], kind="stable").reset_index(drop=True) + return records, tables + + +def annotation_table_and_fasta_to_tables(table_bytes: bytes, fasta_bytes: bytes) -> Tuple[List, Dict[str, pd.DataFrame]]: + records = parse_text_records(fasta_bytes, "fasta") + if not records: + raise ValueError("No FASTA records were found for the annotation table pairing.") + text = table_bytes.decode("utf-8", errors="replace") + first = text.splitlines()[0] if text.splitlines() else "" + sep = "," if first.count(",") >= first.count("\t") else "\t" + df = pd.read_csv(io.StringIO(text), sep=sep) + df.columns = [c.strip() for c in df.columns] + lower = {c.lower(): c for c in df.columns} + start_col = lower.get("start") + end_col = lower.get("end") + if start_col is None or end_col is None: + raise ValueError("Annotation table must contain start and end columns.") + record_col = lower.get("record_id") or lower.get("seqid") or lower.get("contig") or lower.get("chrom") + type_col = lower.get("feature_type") or lower.get("type") + label_col = lower.get("label") or lower.get("name") or lower.get("gene") + strand_col = lower.get("strand") + product_col = lower.get("product") + locus_col = lower.get("locus_tag") + columns = ["record_id", "feature_type", "label", "start", "end", "length", "strand", "gene", "locus_tag", "product", "protein_id", "translation", "note", "source"] + tables = {} + for record in records: + sdf = df if record_col is None else df[df[record_col].astype(str).isin([record.id, record.id.split()[0]])].copy() + if sdf.empty: + tables[record.id] = pd.DataFrame(columns=columns) + continue + out = pd.DataFrame({ + "record_id": record.id, + "feature_type": sdf[type_col].astype(str) if type_col else "misc_feature", + "label": sdf[label_col].astype(str) if label_col else "feature", + "start": sdf[start_col].astype(int).clip(lower=0), + "end": sdf[end_col].astype(int).clip(upper=len(record.seq)), + "strand": sdf[strand_col].replace({"+": 1, "-": -1}).fillna(0).astype(int) if strand_col else 0, + "gene": sdf[label_col].astype(str) if label_col else "", + "locus_tag": sdf[locus_col].astype(str) if locus_col else "", + "product": sdf[product_col].astype(str) if product_col else "", + "protein_id": "", + "translation": "", + "note": "Imported annotation table", + "source": "Annotation table", }) out["length"] = (out["end"] - out["start"]).clip(lower=0) - tables[r.id] = out[cols].sort_values(["start","end"]).reset_index(drop=True) + tables[record.id] = out[columns].sort_values(["start", "end"], kind="stable").reset_index(drop=True) return records, tables -def parse_uploaded_zip(uploaded_zip) -> Dict[str, bytes]: - out = {} - with zipfile.ZipFile(io.BytesIO(uploaded_zip.read())) as zf: - for info in zf.infolist(): +def predict_orfs(sequence: str, min_aa: int = 90, max_orfs: int = 5000) -> pd.DataFrame: + seq = str(sequence).upper() + seq_len = len(seq) + starts = {"ATG", "GTG", "TTG"} + rows = [] + + def scan(s: str, strand: int): + nonlocal rows + for frame in range(3): + pos = frame + while pos <= len(s) - 3 and len(rows) < max_orfs: + codon = s[pos:pos + 3] + if codon in starts: + stop = pos + 3 + while stop <= len(s) - 3: + if s[stop:stop + 3] in STOP_CODONS: + nt_len = stop + 3 - pos + if nt_len // 3 >= min_aa: + if strand == 1: + start, end = pos, stop + 3 + else: + start, end = seq_len - (stop + 3), seq_len - pos + rows.append({ + "record_id": "", + "feature_type": "ORF", + "label": f"ORF_{strand}_{start + 1}_{end}", + "start": int(start), + "end": int(end), + "length": int(end - start), + "strand": strand, + "gene": "", + "locus_tag": "", + "product": f"Predicted ORF, {nt_len // 3} aa", + "protein_id": "", + "translation": "", + "note": "FASTA only predicted ORF", + "source": "ORF prediction", + }) + pos = stop + 3 + break + stop += 3 + pos += 3 + scan(seq, 1) + scan(reverse_complement(seq), -1) + columns = ["record_id", "feature_type", "label", "start", "end", "length", "strand", "gene", "locus_tag", "product", "protein_id", "translation", "note", "source"] + return pd.DataFrame(rows, columns=columns).sort_values(["start", "end"], kind="stable").reset_index(drop=True) + + +def parse_zip(uploaded_file) -> Dict[str, bytes]: + data = uploaded_file.getvalue() + files = {} + with zipfile.ZipFile(io.BytesIO(data)) as archive: + for info in archive.infolist(): if info.is_dir(): continue name = os.path.basename(info.filename) if name: - out[name] = zf.read(info.filename) - return out + n, b = maybe_decompress(name, archive.read(info.filename)) + files[n] = b + return files def parse_input_bundle(primary_upload, secondary_upload, input_mode: str, infer_orfs: bool, min_orf_aa: int) -> ParsedGenome: - notes = [] - - if input_mode == "ZIP (auto-detect)": - files = parse_uploaded_zip(primary_upload) - normalized = {} - for name, data in files.items(): - new_name, new_data = maybe_decompress(name, data) - normalized[new_name] = new_data - - names = list(normalized.keys()) - rich_name = next((n for n in names if infer_file_kind(n) in {"genbank", "embl"}), None) - if rich_name: - fmt = "genbank" if infer_file_kind(rich_name) == "genbank" else "embl" - records = parse_text_records(normalized[rich_name], fmt) + notes: List[str] = [] + + if input_mode == "ZIP auto detect": + files = parse_zip(primary_upload) + names = list(files.keys()) + rich = next((n for n in names if infer_file_kind(n) in {"genbank", "embl"}), None) + if rich: + fmt = "genbank" if infer_file_kind(rich) == "genbank" else "embl" + records = parse_text_records(files[rich], fmt) tables = {r.id: record_to_feature_table(r) for r in records} - notes.append(f"ZIP detected {fmt.upper()} input: {rich_name}") + notes.append(f"ZIP detected annotated {fmt.upper()} file: {rich}") return ParsedGenome(records, tables, fmt, notes) - - fasta_name = next((n for n in names if infer_file_kind(n) == "fasta"), None) - gff_name = next((n for n in names if infer_file_kind(n) == "gff"), None) - bed_name = next((n for n in names if infer_file_kind(n) == "bed"), None) - table_name = next((n for n in names if infer_file_kind(n) == "table"), None) - - if gff_name and fasta_name: - records, tables = gff_and_fasta_to_tables(normalized[gff_name], normalized[fasta_name]) - notes.append(f"ZIP detected GFF/GTF + FASTA input: {gff_name} + {fasta_name}") + fasta = next((n for n in names if infer_file_kind(n) == "fasta"), None) + gff = next((n for n in names if infer_file_kind(n) == "gff"), None) + bed = next((n for n in names if infer_file_kind(n) == "bed"), None) + table = next((n for n in names if infer_file_kind(n) == "table"), None) + if gff and fasta: + records, tables = gff_and_fasta_to_tables(files[gff], files[fasta]) + notes.append(f"ZIP detected GFF/GTF plus FASTA: {gff} and {fasta}") return ParsedGenome(records, tables, "gff_fasta", notes) - if bed_name and fasta_name: - records, tables = bed_and_fasta_to_tables(normalized[bed_name], normalized[fasta_name]) - notes.append(f"ZIP detected BED + FASTA input: {bed_name} + {fasta_name}") + if bed and fasta: + records, tables = bed_and_fasta_to_tables(files[bed], files[fasta]) + notes.append(f"ZIP detected BED plus FASTA: {bed} and {fasta}") return ParsedGenome(records, tables, "bed_fasta", notes) - if table_name and fasta_name: - records, tables = parse_annotation_table(normalized[table_name], normalized[fasta_name]) - notes.append(f"ZIP detected annotation table + FASTA input: {table_name} + {fasta_name}") + if table and fasta: + records, tables = annotation_table_and_fasta_to_tables(files[table], files[fasta]) + notes.append(f"ZIP detected annotation table plus FASTA: {table} and {fasta}") return ParsedGenome(records, tables, "table_fasta", notes) - if fasta_name: - records = parse_text_records(normalized[fasta_name], "fasta") - long_input = sum(len(str(r.seq)) for r in records) > 3_000_000 - do_orf = infer_orfs and not long_input - tables = {} - cols = ["feature_type","label","start","end","length","strand","locus_tag","gene","product","note","source"] - for r in records: - orf_df = find_orfs_in_sequence(str(r.seq), min_aa=min_orf_aa) if do_orf else pd.DataFrame(columns=cols) - if not orf_df.empty: - orf_df.insert(0, "record_id", r.id) - tables[r.id] = orf_df - notes.append(f"ZIP detected FASTA-only input: {fasta_name}") - if infer_orfs and long_input: - notes.append("ORF prediction was disabled automatically because the FASTA input was very large.") + if fasta: + records = parse_text_records(files[fasta], "fasta") + tables = fasta_tables_with_optional_orfs(records, infer_orfs, min_orf_aa, notes) + notes.append(f"ZIP detected FASTA only: {fasta}") return ParsedGenome(records, tables, "fasta", notes) + raise ValueError("The ZIP archive did not contain a supported genome input combination.") - raise ValueError("ZIP file did not contain a supported combination.") + primary_name, primary_data = maybe_decompress(primary_upload.name, primary_upload.getvalue()) + kind = infer_file_kind(primary_name) if input_mode == "Universal auto detect" else input_mode.lower() - pname, pdata = maybe_decompress(primary_upload.name, primary_upload.getvalue()) - kind = infer_file_kind(pname) if input_mode == "Universal / Auto-detect" else None + if input_mode in {"Universal auto detect", "GenBank"} and kind == "genbank": + records = parse_text_records(primary_data, "genbank") + if not records: + raise ValueError("No GenBank records were detected.") + return ParsedGenome(records, {r.id: record_to_feature_table(r) for r in records}, "genbank", ["Parsed annotated GenBank input."]) - if input_mode in {"GenBank", "EMBL", "Universal / Auto-detect"} and (input_mode != "Universal / Auto-detect" or kind in {"genbank", "embl"}): - fmt = "genbank" if (input_mode == "GenBank" or kind == "genbank") else "embl" - records = parse_text_records(pdata, fmt) + if input_mode in {"Universal auto detect", "EMBL"} and kind == "embl": + records = parse_text_records(primary_data, "embl") if not records: - raise ValueError(f"No {fmt} records were found.") - tables = {r.id: record_to_feature_table(r) for r in records} - notes.append(f"Parsed annotated {fmt.upper()} input.") - return ParsedGenome(records, tables, fmt, notes) + raise ValueError("No EMBL records were detected.") + return ParsedGenome(records, {r.id: record_to_feature_table(r) for r in records}, "embl", ["Parsed annotated EMBL input."]) - if input_mode in {"FASTA", "Universal / Auto-detect"} and (input_mode != "Universal / Auto-detect" or kind == "fasta"): - records = parse_text_records(pdata, "fasta") + if input_mode in {"Universal auto detect", "FASTA"} and kind == "fasta": + records = parse_text_records(primary_data, "fasta") if not records: - raise ValueError("No FASTA records were found.") - long_input = sum(len(str(r.seq)) for r in records) > 3_000_000 - do_orf = infer_orfs and not long_input - tables = {} - cols = ["feature_type","label","start","end","length","strand","locus_tag","gene","product","note","source"] - for r in records: - orf_df = find_orfs_in_sequence(str(r.seq), min_aa=min_orf_aa) if do_orf else pd.DataFrame(columns=cols) - if not orf_df.empty: - orf_df.insert(0, "record_id", r.id) - tables[r.id] = orf_df - notes.append("FASTA-only input.") - if do_orf: - notes.append("ORF prediction enabled.") - elif infer_orfs and long_input: - notes.append("ORF prediction was disabled automatically because the FASTA input was very large.") - else: - notes.append("No native annotation available.") - return ParsedGenome(records, tables, "fasta", notes) + raise ValueError("No FASTA records were detected.") + notes.append("Parsed FASTA input. Native feature annotation is not available unless ORF prediction is enabled.") + return ParsedGenome(records, fasta_tables_with_optional_orfs(records, infer_orfs, min_orf_aa, notes), "fasta", notes) - if input_mode in {"GFF/GTF + FASTA", "Universal / Auto-detect"} and (input_mode != "Universal / Auto-detect" or kind == "gff"): + if input_mode in {"Universal auto detect", "GFF/GTF plus FASTA"} and kind == "gff": if secondary_upload is None: - raise ValueError("Please upload the matching FASTA file.") - sname, sdata = maybe_decompress(secondary_upload.name, secondary_upload.getvalue()) - records, tables = gff_and_fasta_to_tables(pdata, sdata) - notes.append("Parsed GFF/GTF annotation with FASTA sequence.") - return ParsedGenome(records, tables, "gff_fasta", notes) + raise ValueError("Please upload the matching FASTA file for GFF/GTF input.") + _, secondary_data = maybe_decompress(secondary_upload.name, secondary_upload.getvalue()) + records, tables = gff_and_fasta_to_tables(primary_data, secondary_data) + return ParsedGenome(records, tables, "gff_fasta", ["Parsed GFF/GTF annotation with matching FASTA sequence."]) - if input_mode in {"BED + FASTA", "Universal / Auto-detect"} and (input_mode != "Universal / Auto-detect" or kind == "bed"): + if input_mode in {"Universal auto detect", "BED plus FASTA"} and kind == "bed": if secondary_upload is None: - raise ValueError("Please upload the matching FASTA file.") - sname, sdata = maybe_decompress(secondary_upload.name, secondary_upload.getvalue()) - records, tables = bed_and_fasta_to_tables(pdata, sdata) - notes.append("Parsed BED coordinates with FASTA sequence.") - return ParsedGenome(records, tables, "bed_fasta", notes) + raise ValueError("Please upload the matching FASTA file for BED input.") + _, secondary_data = maybe_decompress(secondary_upload.name, secondary_upload.getvalue()) + records, tables = bed_and_fasta_to_tables(primary_data, secondary_data) + return ParsedGenome(records, tables, "bed_fasta", ["Parsed BED annotation with matching FASTA sequence."]) - if input_mode in {"Annotation table + FASTA", "Universal / Auto-detect"} and (input_mode != "Universal / Auto-detect" or kind == "table"): + if input_mode in {"Universal auto detect", "Annotation table plus FASTA"} and kind == "table": if secondary_upload is None: - raise ValueError("Please upload the matching FASTA file.") - sname, sdata = maybe_decompress(secondary_upload.name, secondary_upload.getvalue()) - records, tables = parse_annotation_table(pdata, sdata) - notes.append("Parsed annotation table with FASTA sequence.") - return ParsedGenome(records, tables, "table_fasta", notes) + raise ValueError("Please upload the matching FASTA file for annotation table input.") + _, secondary_data = maybe_decompress(secondary_upload.name, secondary_upload.getvalue()) + records, tables = annotation_table_and_fasta_to_tables(primary_data, secondary_data) + return ParsedGenome(records, tables, "table_fasta", ["Parsed annotation table with matching FASTA sequence."]) + + raise ValueError("Unsupported input type or missing paired FASTA file.") - raise ValueError("Unsupported input or missing paired file.") +def fasta_tables_with_optional_orfs(records, infer_orfs: bool, min_orf_aa: int, notes: List[str]) -> Dict[str, pd.DataFrame]: + columns = ["record_id", "feature_type", "label", "start", "end", "length", "strand", "gene", "locus_tag", "product", "protein_id", "translation", "note", "source"] + total_len = sum(len(r.seq) for r in records) + if infer_orfs and total_len > 10_000_000: + notes.append("ORF prediction was disabled because the input is larger than 10 Mb. Use annotated GenBank/GFF for large genomes.") + infer_orfs = False + tables = {} + for record in records: + if infer_orfs: + df = predict_orfs(str(record.seq), min_aa=min_orf_aa) + if not df.empty: + df["record_id"] = record.id + tables[record.id] = df + else: + tables[record.id] = pd.DataFrame(columns=columns) + if infer_orfs: + notes.append("ORF prediction was performed for FASTA only input using bacterial start codons ATG, GTG and TTG.") + return tables + + +# ----------------------------- +# Genome composition and codon bias +# ----------------------------- +def nucleotide_counts(sequence: str) -> Dict[str, int]: + seq = str(sequence).upper() + return {base: seq.count(base) for base in ["A", "T", "G", "C", "N"]} + + +def compute_gc_percent(sequence: str) -> float: + seq = str(sequence).upper() + valid = sum(seq.count(x) for x in "ATGC") + if valid == 0: + return 0.0 + return 100.0 * (seq.count("G") + seq.count("C")) / valid + + +def compute_at_percent(sequence: str) -> float: + seq = str(sequence).upper() + valid = sum(seq.count(x) for x in "ATGC") + if valid == 0: + return 0.0 + return 100.0 * (seq.count("A") + seq.count("T")) / valid + + +def gc_skew_value(sequence: str) -> float: + seq = str(sequence).upper() + g, c = seq.count("G"), seq.count("C") + return (g - c) / (g + c) if (g + c) else 0.0 + + +def at_skew_value(sequence: str) -> float: + seq = str(sequence).upper() + a, t = seq.count("A"), seq.count("T") + return (a - t) / (a + t) if (a + t) else 0.0 + + +def cpg_observed_expected(sequence: str) -> float: + seq = str(sequence).upper().replace("N", "") + if len(seq) < 2: + return 0.0 + c = seq.count("C") + g = seq.count("G") + cg = seq.count("CG") + if c == 0 or g == 0: + return 0.0 + return (cg * len(seq)) / (c * g) -def filter_features(df: pd.DataFrame, selected_types: List[str], query: str, min_len: int = 0, max_features: int = 25000) -> pd.DataFrame: - filtered = df.copy() + +def window_dataframe(sequence: str, window_size: int = 1000) -> pd.DataFrame: + seq = str(sequence).upper() + rows = [] + cumulative = 0.0 + for start in range(0, len(seq), window_size): + end = min(len(seq), start + window_size) + w = seq[start:end] + skew = gc_skew_value(w) + cumulative += skew + rows.append({ + "start": start, + "end": end, + "midpoint": (start + end) // 2, + "GC_percent": compute_gc_percent(w), + "GC_skew": skew, + "cumulative_GC_skew": cumulative, + "N_count": w.count("N"), + }) + return pd.DataFrame(rows) + + +def extract_feature_sequence(record, row: pd.Series) -> str: + start, end = int(row["start"]), int(row["end"]) + seq = str(record.seq[start:end]).upper() + if int(row.get("strand", 0)) == -1: + seq = reverse_complement(seq) + return seq + + +def valid_cds_sequence(seq: str) -> str: + seq = re.sub("[^ATGC]", "", str(seq).upper()) + usable = len(seq) - (len(seq) % 3) + return seq[:usable] + + +def collect_cds_sequences(record, feature_df: pd.DataFrame) -> List[str]: + if feature_df.empty: + return [] + cds = feature_df[feature_df["feature_type"].str.lower().eq("cds")].copy() + seqs = [] + for _, row in cds.iterrows(): + seq = valid_cds_sequence(extract_feature_sequence(record, row)) + if len(seq) >= 90: + seqs.append(seq) + return seqs + + +def codon_usage_table(cds_sequences: List[str], reference_weights: Optional[Dict[str, float]] = None) -> pd.DataFrame: + counts = {codon: 0 for codon in SENSE_CODONS} + stop_counts = {codon: 0 for codon in STOP_CODONS} + for seq in cds_sequences: + seq = valid_cds_sequence(seq) + for i in range(0, len(seq) - 2, 3): + codon = seq[i:i + 3] + if codon in counts: + counts[codon] += 1 + elif codon in stop_counts: + stop_counts[codon] += 1 + total_sense = sum(counts.values()) + rows = [] + for aa, codons in sorted(AA_TO_CODONS.items()): + aa_total = sum(counts[c] for c in codons) + n_syn = len(codons) + max_count = max([counts[c] for c in codons]) if codons else 0 + for codon in sorted(codons): + freq_per_thousand = (counts[codon] / total_sense * 1000.0) if total_sense else 0.0 + expected = aa_total / n_syn if n_syn else 0 + rscu = counts[codon] / expected if expected else 0.0 + rel_adapt = (counts[codon] / max_count) if max_count else 0.0 + rows.append({ + "amino_acid": aa, + "codon": codon, + "count": counts[codon], + "frequency_per_1000": round(freq_per_thousand, 4), + "RSCU": round(rscu, 4), + "relative_adaptiveness_w": round(rel_adapt, 4), + "reference_weight": reference_weights.get(codon, np.nan) if reference_weights else np.nan, + }) + for codon in sorted(STOP_CODONS): + rows.append({ + "amino_acid": "Stop", + "codon": codon, + "count": stop_counts[codon], + "frequency_per_1000": 0.0, + "RSCU": 0.0, + "relative_adaptiveness_w": 0.0, + "reference_weight": np.nan, + }) + return pd.DataFrame(rows) + + +def effective_number_of_codons(codon_df: pd.DataFrame) -> float: + """Approximate Wright ENC from homozygosity of synonymous codon families.""" + if codon_df.empty or codon_df["count"].sum() == 0: + return 0.0 + f_by_k: Dict[int, List[float]] = {2: [], 3: [], 4: [], 6: []} + sense = codon_df[codon_df["amino_acid"] != "Stop"].copy() + for aa, group in sense.groupby("amino_acid"): + k = len(group) + if k == 1: + continue + counts = group["count"].astype(float).values + n = counts.sum() + if n <= 1: + continue + homozygosity = ((counts ** 2).sum() - n) / (n * (n - 1)) + if k in f_by_k: + f_by_k[k].append(max(homozygosity, 1e-9)) + def mean_or_nan(vals): + return float(np.mean(vals)) if vals else np.nan + f2, f3, f4, f6 = [mean_or_nan(f_by_k[k]) for k in [2, 3, 4, 6]] + enc = 2 + enc += 9 / f2 if not np.isnan(f2) else 0 + enc += 1 / f3 if not np.isnan(f3) else 0 + enc += 5 / f4 if not np.isnan(f4) else 0 + enc += 3 / f6 if not np.isnan(f6) else 0 + return round(float(min(max(enc, 20.0), 61.0)), 3) + + +def codon_adaptation_index(cds_sequences: List[str], weights: Optional[Dict[str, float]]) -> float: + if not weights: + return 0.0 + logs = [] + for seq in cds_sequences: + seq = valid_cds_sequence(seq) + for i in range(0, len(seq) - 2, 3): + codon = seq[i:i + 3] + if codon in SENSE_CODONS: + w = max(float(weights.get(codon, 0.0)), 1e-8) + logs.append(math.log(w)) + return round(float(math.exp(np.mean(logs))), 4) if logs else 0.0 + + +def parse_reference_codon_weights(uploaded_ref) -> Optional[Dict[str, float]]: + if uploaded_ref is None: + return None + text = uploaded_ref.getvalue().decode("utf-8", errors="replace") + first = text.splitlines()[0] if text.splitlines() else "" + sep = "," if first.count(",") >= first.count("\t") else "\t" + df = pd.read_csv(io.StringIO(text), sep=sep) + 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 "w" if "w" in df.columns else df.columns[-1] + weights = {} + for _, row in df.iterrows(): + codon = str(row[codon_col]).upper().replace("U", "T") + if codon in SENSE_CODONS: + try: + weights[codon] = float(row[weight_col]) + except Exception: + pass + return weights or None + + +def build_summary_statistics(record, full_df: pd.DataFrame, filtered_df: pd.DataFrame, cds_sequences: List[str], codon_df: pd.DataFrame, cai: float) -> Dict[str, object]: + seq = str(record.seq).upper() + counts = nucleotide_counts(seq) + feature_counts = full_df["feature_type"].value_counts().to_dict() if not full_df.empty else {} + coding_bp = int(full_df.loc[full_df["feature_type"].str.lower().eq("cds"), "length"].sum()) if not full_df.empty else 0 + total_codons = int(codon_df.loc[codon_df["amino_acid"] != "Stop", "count"].sum()) if not codon_df.empty else 0 + return { + "record_id": record.id, + "description": clean_text(getattr(record, "description", "")), + "genome_length_bp": len(seq), + "A": counts["A"], + "T": counts["T"], + "G": counts["G"], + "C": counts["C"], + "N": counts["N"], + "GC_percent": round(compute_gc_percent(seq), 3), + "AT_percent": round(compute_at_percent(seq), 3), + "GC_skew": round(gc_skew_value(seq), 5), + "AT_skew": round(at_skew_value(seq), 5), + "CpG_observed_expected": round(cpg_observed_expected(seq), 5), + "total_features": int(len(full_df)), + "displayed_features": int(len(filtered_df)), + "CDS_count": int(feature_counts.get("CDS", 0)), + "gene_count": int(feature_counts.get("gene", 0)), + "tRNA_count": int(feature_counts.get("tRNA", 0)), + "rRNA_count": int(feature_counts.get("rRNA", 0)), + "ORF_count": int(feature_counts.get("ORF", 0)), + "coding_bp": coding_bp, + "coding_density_percent": round(100.0 * coding_bp / len(seq), 3) if len(seq) else 0.0, + "CDS_used_for_codon_analysis": len(cds_sequences), + "total_sense_codons": total_codons, + "effective_number_of_codons_ENC": effective_number_of_codons(codon_df), + "codon_adaptation_index_CAI": cai, + } + + +# ----------------------------- +# Filtering and visualization +# ----------------------------- +def filter_features(df: pd.DataFrame, selected_types: List[str], query: str, min_len: int, max_features: int) -> pd.DataFrame: + if df.empty: + out = df.copy() + out["highlight"] = False + return out + out = df.copy() if selected_types: - filtered = filtered[filtered["feature_type"].isin(selected_types)].copy() - if min_len > 0 and not filtered.empty: - filtered = filtered[filtered["length"].fillna(0) >= min_len].copy() - - if filtered.empty: - filtered["highlight"] = False - return filtered - - query = normalize_text(query).lower() - if query: - mask = ( - filtered["label"].fillna("").str.lower().str.contains(query, na=False) - | filtered["gene"].fillna("").str.lower().str.contains(query, na=False) - | filtered["locus_tag"].fillna("").str.lower().str.contains(query, na=False) - | filtered["product"].fillna("").str.lower().str.contains(query, na=False) - | filtered["note"].fillna("").str.lower().str.contains(query, na=False) - ) - filtered["highlight"] = mask + out = out[out["feature_type"].isin(selected_types)].copy() + if min_len > 0: + out = out[out["length"].fillna(0).astype(int) >= min_len].copy() + q = clean_text(query).lower() + if q: + fields = ["label", "gene", "locus_tag", "product", "protein_id", "note"] + mask = pd.Series(False, index=out.index) + for field in fields: + if field in out.columns: + mask = mask | out[field].fillna("").str.lower().str.contains(re.escape(q), na=False) + out["highlight"] = mask else: - filtered["highlight"] = False + out["highlight"] = False + if len(out) > max_features: + out = out.nsmallest(max_features, "start").copy() + return out.sort_values(["start", "end"], kind="stable").reset_index(drop=True) + + +def feature_legend_html(feature_types: List[str], highlight: bool) -> str: + parts = [] + for ft in feature_types: + color = FEATURE_COLORS.get(ft, FEATURE_COLORS["default"]) + parts.append(f'{ft}') + if highlight: + parts.append(f'highlighted match') + return "".join(parts) - if len(filtered) > max_features: - filtered = filtered.nsmallest(max_features, "start").copy() - return filtered.sort_values(["start", "end"], kind="stable").reset_index(drop=True) +def add_matplotlib_legend(ax, feature_types: List[str], highlight: bool): + handles = [] + for ft in feature_types: + handles.append(Line2D([0], [0], color=FEATURE_COLORS.get(ft, FEATURE_COLORS["default"]), lw=5, label=ft)) + if highlight: + handles.append(Line2D([0], [0], color=FEATURE_COLORS["highlight"], lw=5, label="highlighted match")) + if handles: + ax.legend(handles=handles, frameon=False, ncol=2, loc="upper right") -def build_linear_graphic_record(record, filtered_df: pd.DataFrame, annotate_limit: int = 120, label_max_len: int = 28) -> GraphicRecord: +def draw_linear_map(record, filtered_df: pd.DataFrame, feature_types: List[str], publication: bool): + if GraphicFeature is None or GraphicRecord is None: + raise RuntimeError("dna_features_viewer is required. Install it with: pip install dna_features_viewer") features = [] - do_labels = len(filtered_df) <= annotate_limit + label_limit = 160 if publication else 80 for _, row in filtered_df.iterrows(): color = FEATURE_COLORS["highlight"] if bool(row.get("highlight", False)) else FEATURE_COLORS.get(row["feature_type"], FEATURE_COLORS["default"]) - label = normalize_text(row.get("label", row["feature_type"])) if do_labels else None - if label and len(label) > label_max_len: - label = label[: label_max_len - 3] + "..." - strand = int(row["strand"]) if row["strand"] in (-1, 1) else 0 - features.append( - GraphicFeature( - start=int(row["start"]), - end=int(row["end"]), - strand=strand, - color=color, - label=label, - ) - ) - return GraphicRecord(sequence_length=len(record.seq), features=features) - - -def add_feature_legend(ax, feature_types: List[str], include_highlight: bool): - items = [] - for ft in feature_types: - color = FEATURE_COLORS.get(ft, FEATURE_COLORS["default"]) - items.append(Line2D([0], [0], color=color, lw=4, label=ft)) - if include_highlight: - items.append(Line2D([0], [0], color=FEATURE_COLORS["highlight"], lw=4, label="highlighted match")) - if items: - ax.legend(handles=items, loc="upper right", frameon=False, ncol=2) - - -def draw_linear_map(record, filtered_df: pd.DataFrame, feature_types: List[str], publication_mode: bool = False): - annotate_limit = 180 if publication_mode else 110 - label_max_len = 34 if publication_mode else 24 - graphic_record = build_linear_graphic_record(record, filtered_df, annotate_limit=annotate_limit, label_max_len=label_max_len) - fig_height = 4.8 if len(filtered_df) <= 80 else 6.0 if len(filtered_df) <= 220 else 7.2 - fig, ax = plt.subplots(figsize=(16, fig_height)) - graphic_record.plot(ax=ax, with_ruler=True, annotate_inline=(len(filtered_df) <= annotate_limit)) - ax.set_title("A. Linear genome map", fontsize=14, fontweight="bold", loc="left") - ax.set_xlabel(f"Record: {record.id} | Length: {len(record.seq):,} bp", fontsize=10) - add_feature_legend(ax, feature_types, include_highlight=bool(filtered_df["highlight"].any()) if "highlight" in filtered_df.columns and not filtered_df.empty else False) + label = clean_text(row.get("label", row["feature_type"])) if len(filtered_df) <= label_limit else None + if label and len(label) > 34: + label = label[:31] + "..." + features.append(GraphicFeature(start=int(row["start"]), end=int(row["end"]), strand=int(row["strand"]) if int(row["strand"]) in [-1, 1] else 0, color=color, label=label)) + graphic = GraphicRecord(sequence_length=len(record.seq), features=features) + height = 4.8 if len(filtered_df) < 100 else 6.2 if len(filtered_df) < 300 else 7.5 + fig, ax = plt.subplots(figsize=(16, height)) + graphic.plot(ax=ax, with_ruler=True, annotate_inline=(len(filtered_df) <= label_limit)) + ax.set_title("A. Linear genome map", loc="left", fontweight="bold") + ax.set_xlabel(f"{record.id} | {len(record.seq):,} bp") + add_matplotlib_legend(ax, feature_types, bool(filtered_df.get("highlight", pd.Series(dtype=bool)).any()) if not filtered_df.empty else False) plt.tight_layout() return fig -def draw_circular_map(record, filtered_df: pd.DataFrame, show_gc_content: bool = True, show_gc_skew: bool = True, window_size: int = 1000): +def draw_circular_map(record, filtered_df: pd.DataFrame, window_df: pd.DataFrame, feature_types: List[str]): + if Circos is None: + raise RuntimeError("pycirclize is required for circular maps. Install it with: pip install pycirclize") seq_len = len(record.seq) circos = Circos({record.id: seq_len}, space=2) sector = circos.sectors[0] - - tick_track = sector.add_track((88, 100)) - tick_track.axis(fc="#f7f7f7", ec="black", lw=0.4) - tick_interval = max(1000, seq_len // 10) if seq_len <= 100000 else max(5000, seq_len // 12) - tick_track.xticks_by_interval( - tick_interval, - label_formatter=lambda v: f"{int(v/1000)} kb" if v >= 1000 else str(v), - show_bottom_line=True, - label_orientation="vertical", - label_size=8, - ) - - pos_track = sector.add_track((64, 84)) - neg_track = sector.add_track((44, 64)) - pos_track.axis(fc="#ffffff", ec="black", lw=0.3) - neg_track.axis(fc="#ffffff", ec="black", lw=0.3) - + axis = sector.add_track((88, 100)) + axis.axis(fc="#f8f9fa", ec="#222222", lw=0.4) + tick_interval = max(1000, seq_len // 12) + axis.xticks_by_interval(tick_interval, label_formatter=lambda v: f"{int(v / 1000)} kb" if v >= 1000 else str(int(v)), label_size=8, label_orientation="vertical") + + forward = sector.add_track((66, 84)) + reverse = sector.add_track((46, 64)) + forward.axis(fc="#ffffff", ec="#555555", lw=0.25) + reverse.axis(fc="#ffffff", ec="#555555", lw=0.25) for _, row in filtered_df.iterrows(): - start = int(row["start"]) - end = int(row["end"]) color = FEATURE_COLORS["highlight"] if bool(row.get("highlight", False)) else FEATURE_COLORS.get(row["feature_type"], FEATURE_COLORS["default"]) - if row["strand"] == -1: - neg_track.rect(start, end, fc=color, ec=color) - else: - pos_track.rect(start, end, fc=color, ec=color) - - inner_bottom = 10 - if show_gc_content: - gc_track = sector.add_track((26, 40)) - gc_track.axis(fc="#f8f8f8", ec="black", lw=0.25) - positions, values = chunk_gc_content(record.seq, window_size) - if values: - gc_track.line(positions, values, vmin=0, vmax=100) - gc_track.fill_between(positions, values, y2=[50.0] * len(values), vmin=0, vmax=100, alpha=0.28) - inner_bottom = 24 - - if show_gc_skew: - skew_track = sector.add_track((inner_bottom, inner_bottom + 12)) - skew_track.axis(fc="#f8f8f8", ec="black", lw=0.25) - positions, skews = gc_skew_windows(record.seq, window_size) - if skews: - vmax = max(abs(min(skews)), abs(max(skews)), 0.1) - skew_track.line(positions, skews, vmin=-vmax, vmax=vmax) - skew_track.fill_between(positions, skews, y2=0, vmin=-vmax, vmax=vmax, alpha=0.35) + track = reverse if int(row.get("strand", 0)) == -1 else forward + track.rect(int(row["start"]), int(row["end"]), fc=color, ec=color, lw=0.1) - fig = circos.plotfig() - fig.set_size_inches(8.8, 8.8) - fig.suptitle("B. Circular genome map", fontsize=14, fontweight="bold", y=0.98, x=0.12, ha="left") - return fig + if not window_df.empty: + gc_track = sector.add_track((28, 42)) + gc_track.axis(fc="#fbfbfb", ec="#555555", lw=0.2) + gc_track.line(window_df["midpoint"].tolist(), window_df["GC_percent"].tolist(), vmin=0, vmax=100, lw=0.8) + gc_track.fill_between(window_df["midpoint"].tolist(), window_df["GC_percent"].tolist(), y2=[50.0] * len(window_df), vmin=0, vmax=100, alpha=0.25) + skew_track = sector.add_track((12, 26)) + skew_track.axis(fc="#fbfbfb", ec="#555555", lw=0.2) + max_skew = max(0.05, float(np.nanmax(np.abs(window_df["GC_skew"])))) + skew_track.line(window_df["midpoint"].tolist(), window_df["GC_skew"].tolist(), vmin=-max_skew, vmax=max_skew, lw=0.8) + skew_track.fill_between(window_df["midpoint"].tolist(), window_df["GC_skew"].tolist(), y2=0, vmin=-max_skew, vmax=max_skew, alpha=0.30) -def feature_distribution_table(df: pd.DataFrame) -> pd.DataFrame: - if df.empty: - return pd.DataFrame(columns=["feature_type", "count"]) - return df["feature_type"].value_counts().rename_axis("feature_type").reset_index(name="count") + fig = circos.plotfig() + fig.set_size_inches(9.2, 9.2) + fig.suptitle("B. Circular genome map with GC tracks", x=0.08, y=0.98, ha="left", fontweight="bold") + return fig -def draw_feature_distribution(dist_df: pd.DataFrame): - fig, ax = plt.subplots(figsize=(9, 5)) - ax.set_title("C. Feature-type distribution", fontsize=14, fontweight="bold", loc="left") - if dist_df.empty: - ax.text(0.5, 0.5, "No features available", ha="center", va="center") +def draw_feature_distribution(feature_df: pd.DataFrame): + dist = feature_df["feature_type"].value_counts().rename_axis("feature_type").reset_index(name="count") if not feature_df.empty else pd.DataFrame(columns=["feature_type", "count"]) + fig, ax = plt.subplots(figsize=(9, 4.8)) + ax.set_title("C. Feature class distribution", loc="left", fontweight="bold") + if dist.empty: + ax.text(0.5, 0.5, "No annotated features", ha="center", va="center") ax.axis("off") else: - show_df = dist_df.head(15).copy() - colors = [FEATURE_COLORS.get(ft, FEATURE_COLORS["default"]) for ft in show_df["feature_type"]] - ax.bar(show_df["feature_type"], show_df["count"], color=colors, edgecolor="black", linewidth=0.4) + show = dist.head(15) + colors = [FEATURE_COLORS.get(x, FEATURE_COLORS["default"]) for x in show["feature_type"]] + ax.bar(show["feature_type"], show["count"], color=colors, edgecolor="#222222", linewidth=0.35) ax.set_xlabel("Feature class") ax.set_ylabel("Count") ax.tick_params(axis="x", rotation=40) - ax.grid(axis="y", alpha=0.25, linestyle="--") + ax.grid(axis="y", alpha=0.25) plt.tight_layout() - return fig + return fig, dist -def build_density_df(record, filtered_df: pd.DataFrame, bins: int = 100) -> pd.DataFrame: - if filtered_df.empty: - return pd.DataFrame(columns=["bin_start", "bin_end", "count"]) - seq_len = len(record.seq) - edges = np.linspace(0, seq_len, bins + 1, dtype=int) - counts = [] - for i in range(bins): - start = edges[i] - end = edges[i + 1] - count = ((filtered_df["start"] < end) & (filtered_df["end"] > start)).sum() - counts.append(count) - return pd.DataFrame({"bin_start": edges[:-1], "bin_end": edges[1:], "count": counts}) - - -def draw_density_plot(density_df: pd.DataFrame, seq_len: int): +def draw_gc_profile(window_df: pd.DataFrame, seq_len: int): fig, ax = plt.subplots(figsize=(10, 4.8)) - ax.set_title("D. Genome-wide feature density", fontsize=14, fontweight="bold", loc="left") - if density_df.empty: - ax.text(0.5, 0.5, "No features available", ha="center", va="center") + ax.set_title("D. GC content and GC skew profile", loc="left", fontweight="bold") + if window_df.empty: + ax.text(0.5, 0.5, "No sequence windows available", ha="center", va="center") ax.axis("off") else: - mids = (density_df["bin_start"] + density_df["bin_end"]) / 2 - ax.plot(mids, density_df["count"], linewidth=1.8) - ax.fill_between(mids, density_df["count"], alpha=0.25) + ax.plot(window_df["midpoint"], window_df["GC_percent"], label="GC percent", lw=1.8) ax.set_xlabel("Genome position (bp)") - ax.set_ylabel("Feature count") + ax.set_ylabel("GC percent") ax.set_xlim(0, seq_len) - ax.grid(alpha=0.25, linestyle="--") + ax.grid(alpha=0.25) + ax2 = ax.twinx() + ax2.plot(window_df["midpoint"], window_df["GC_skew"], label="GC skew", lw=1.2, linestyle="--") + ax2.set_ylabel("GC skew") + lines, labels = ax.get_legend_handles_labels() + lines2, labels2 = ax2.get_legend_handles_labels() + ax.legend(lines + lines2, labels + labels2, frameon=False, loc="upper right") plt.tight_layout() return fig -def fig_to_bytes(fig, fmt="png", dpi=600) -> bytes: - buf = io.BytesIO() - kwargs = {"bbox_inches": "tight"} - if fmt.lower() == "png": - kwargs["dpi"] = dpi - fig.savefig(buf, format=fmt, **kwargs) - buf.seek(0) - return buf.getvalue() - - -def fig_to_rgb_array(fig, dpi=260): - buf = io.BytesIO() - fig.savefig(buf, format="png", dpi=dpi, bbox_inches="tight") - buf.seek(0) - img = plt.imread(buf) - return img - - -def build_publication_composite(linear_fig, circular_fig, dist_fig, density_fig, record_id: str): - linear_img = fig_to_rgb_array(linear_fig, dpi=260) - circular_img = fig_to_rgb_array(circular_fig, dpi=260) - dist_img = fig_to_rgb_array(dist_fig, dpi=260) - density_img = fig_to_rgb_array(density_fig, dpi=260) - - fig, axes = plt.subplots(2, 2, figsize=(16, 13)) - fig.suptitle(f"Genome annotation figure set: {record_id}", fontsize=16, fontweight="bold", y=0.99) - - for ax, img in zip(axes.ravel(), [linear_img, circular_img, dist_img, density_img]): - ax.imshow(img) +def draw_codon_rscu(codon_df: pd.DataFrame): + fig, ax = plt.subplots(figsize=(13, 5.2)) + ax.set_title("E. Relative synonymous codon usage", loc="left", fontweight="bold") + sense = codon_df[codon_df["amino_acid"] != "Stop"].copy() if not codon_df.empty else pd.DataFrame() + if sense.empty or sense["count"].sum() == 0: + ax.text(0.5, 0.5, "No CDS codon data available", ha="center", va="center") ax.axis("off") - - plt.tight_layout(rect=[0, 0, 1, 0.975]) + else: + sense["label"] = sense["codon"] + "\n" + sense["amino_acid"] + ax.bar(sense["label"], sense["RSCU"], edgecolor="#222222", linewidth=0.25) + ax.axhline(1.0, lw=1.0, linestyle="--") + ax.set_ylabel("RSCU") + ax.set_xlabel("Codon and amino acid") + ax.tick_params(axis="x", rotation=90) + ax.grid(axis="y", alpha=0.25) + plt.tight_layout() return fig -def build_summary_stats(record, full_df: pd.DataFrame, filtered_df: pd.DataFrame) -> Dict[str, object]: - counts = full_df["feature_type"].value_counts().to_dict() if not full_df.empty else {} - return { - "Record ID": record.id, - "Description": normalize_text(getattr(record, "description", "")), - "Genome length (bp)": len(record.seq), - "GC (%)": round(compute_gc_percent(record.seq), 2), - "Displayed features": len(filtered_df), - "Total parsed features": len(full_df), - "CDS": int(counts.get("CDS", 0)), - "gene": int(counts.get("gene", 0)), - "tRNA": int(counts.get("tRNA", 0)), - "rRNA": int(counts.get("rRNA", 0)), - "ORF": int(counts.get("ORF", 0)), - } +def fig_bytes(fig, fmt: str = "png", dpi: int = 600) -> bytes: + buffer = io.BytesIO() + kwargs = {"bbox_inches": "tight"} + if fmt == "png": + kwargs["dpi"] = dpi + fig.savefig(buffer, format=fmt, **kwargs) + buffer.seek(0) + return buffer.getvalue() -def build_legend_html(feature_types: List[str], include_highlight: bool = False) -> str: - parts = [] - for ft in feature_types: - color = FEATURE_COLORS.get(ft, FEATURE_COLORS["default"]) - parts.append( - f""" - - - {ft} - - """ - ) - if include_highlight: - parts.append( - f""" - - - highlighted match - - """ - ) - return "".join(parts) +def build_bundle(figures: Dict[str, bytes], tables: Dict[str, pd.DataFrame], summary_text: str) -> bytes: + mem = io.BytesIO() + with zipfile.ZipFile(mem, "w", compression=zipfile.ZIP_DEFLATED) as zf: + for name, data in figures.items(): + if data is not None: + zf.writestr(name, data) + for name, df in tables.items(): + zf.writestr(name, df.to_csv(index=False)) + zf.writestr("manuscript_summary.txt", summary_text) + mem.seek(0) + return mem.getvalue() -def manuscript_summary_text(stats: Dict[str, object], top_features: pd.DataFrame, record_id: str, query: str, run_mode: str) -> str: - feature_phrase = "No annotated feature classes were available." - if not top_features.empty: - top3 = ", ".join([f"{r.feature_type} ({r.count})" for r in top_features.head(3).itertuples()]) - feature_phrase = f"The most abundant annotated classes were {top3}." - highlight_phrase = f' The search query "{query}" was highlighted in gold across the figure set.' if query.strip() else "" - quality_phrase = "Publication mode was used to generate vector-ready figure exports (SVG/PDF) together with high-resolution PNG files." if run_mode == "Publication quality" else "Fast preview mode was used for rapid inspection, while preserving clear labels and feature legends." +def manuscript_summary(stats: Dict[str, object]) -> str: return ( - f"The record {record_id} spans {stats['Genome length (bp)']:,} bp with a GC content of {stats['GC (%)']:.2f}%. " - f"A total of {stats['Total parsed features']} features were parsed, of which {stats['Displayed features']} were displayed after filtering. " - f"{feature_phrase}{highlight_phrase} {quality_phrase}" + f"The genome record {stats['record_id']} had a length of {stats['genome_length_bp']:,} bp, " + f"with GC content of {stats['GC_percent']:.2f}%, AT content of {stats['AT_percent']:.2f}%, " + f"GC skew of {stats['GC_skew']:.5f}, and CpG observed/expected ratio of {stats['CpG_observed_expected']:.5f}. " + f"A total of {stats['total_features']:,} annotated features were parsed, including {stats['CDS_count']:,} CDS, " + f"{stats['tRNA_count']:,} tRNA and {stats['rRNA_count']:,} rRNA features. The estimated coding density was " + f"{stats['coding_density_percent']:.2f}%. Codon usage analysis was performed using {stats['CDS_used_for_codon_analysis']:,} CDS, " + f"covering {stats['total_sense_codons']:,} sense codons. The effective number of codons was " + f"{stats['effective_number_of_codons_ENC']:.2f}, while the codon adaptation index was " + f"{stats['codon_adaptation_index_CAI']:.4f} when a reference weight table was supplied." ) -def make_results_bundle(figure_pack: Dict[str, bytes], summary_df: pd.DataFrame, feature_df: pd.DataFrame, stats_df: pd.DataFrame, density_df: pd.DataFrame, summary_text: str) -> bytes: - mem = io.BytesIO() - with zipfile.ZipFile(mem, mode="w", compression=zipfile.ZIP_DEFLATED) as zf: - for name, content in figure_pack.items(): - if content is not None: - zf.writestr(name, content) - zf.writestr("feature_annotations.csv", feature_df.to_csv(index=False)) - zf.writestr("summary_statistics.csv", stats_df.to_csv(index=False)) - zf.writestr("feature_density.csv", density_df.to_csv(index=False)) - zf.writestr("results_summary.txt", summary_text) - mem.seek(0) - return mem.getvalue() - - -def prepare_figures(record, filtered_df, full_df, available_types, show_gc_content, show_gc_skew, window_size, run_mode): - publication = run_mode == "Publication quality" - - linear_fig = draw_linear_map(record, filtered_df, available_types, publication_mode=publication) - circular_fig = draw_circular_map(record, filtered_df, show_gc_content=show_gc_content, show_gc_skew=show_gc_skew, window_size=int(window_size)) - dist_df = feature_distribution_table(full_df) - density_df = build_density_df(record, filtered_df, bins=120 if publication else 80) - dist_fig = draw_feature_distribution(dist_df) - density_fig = draw_density_plot(density_df, len(record.seq)) - composite_fig = build_publication_composite(linear_fig, circular_fig, dist_fig, density_fig, record.id) - - figure_pack = { - "panel_A_linear_map.png": fig_to_bytes(linear_fig, "png", dpi=600 if publication else 300), - "panel_B_circular_map.png": fig_to_bytes(circular_fig, "png", dpi=600 if publication else 300), - "panel_C_feature_distribution.png": fig_to_bytes(dist_fig, "png", dpi=600 if publication else 300), - "panel_D_feature_density.png": fig_to_bytes(density_fig, "png", dpi=600 if publication else 300), - "figure_composite_ABCD.png": fig_to_bytes(composite_fig, "png", dpi=600 if publication else 300), - "panel_A_linear_map.svg": fig_to_bytes(linear_fig, "svg") if publication else None, - "panel_B_circular_map.svg": fig_to_bytes(circular_fig, "svg") if publication else None, - "panel_C_feature_distribution.svg": fig_to_bytes(dist_fig, "svg") if publication else None, - "panel_D_feature_density.svg": fig_to_bytes(density_fig, "svg") if publication else None, - "panel_A_linear_map.pdf": fig_to_bytes(linear_fig, "pdf") if publication else None, - "panel_B_circular_map.pdf": fig_to_bytes(circular_fig, "pdf") if publication else None, - "panel_C_feature_distribution.pdf": fig_to_bytes(dist_fig, "pdf") if publication else None, - "panel_D_feature_density.pdf": fig_to_bytes(density_fig, "pdf") if publication else None, - "figure_composite_ABCD.pdf": fig_to_bytes(composite_fig, "pdf") if publication else None, +# ----------------------------- +# Session state and Streamlit UI +# ----------------------------- +def initialise_state(): + defaults = { + "done": False, + "error": "", + "records": [], + "tables": {}, + "record_id": None, + "stats": {}, + "stats_df": pd.DataFrame(), + "feature_df": pd.DataFrame(), + "filtered_df": pd.DataFrame(), + "window_df": pd.DataFrame(), + "codon_df": pd.DataFrame(), + "dist_df": pd.DataFrame(), + "summary": "", + "figures": {}, + "bundle": None, + "notes": [], + "available_types": [], + "selected_types": [], } + for k, v in defaults.items(): + st.session_state.setdefault(k, v) - preview = { - "linear_png": figure_pack["panel_A_linear_map.png"], - "circular_png": figure_pack["panel_B_circular_map.png"], - "dist_png": figure_pack["panel_C_feature_distribution.png"], - "density_png": figure_pack["panel_D_feature_density.png"], - "composite_png": figure_pack["figure_composite_ABCD.png"], - } - for fig in [linear_fig, circular_fig, dist_fig, density_fig, composite_fig]: - plt.close(fig) - - return figure_pack, preview, dist_df, density_df - - -def run_analysis( - primary_upload, - secondary_upload, - input_mode, - infer_orfs, - min_orf_aa, - gene_query, - show_gc_content, - show_gc_skew, - window_size, - run_mode, - selected_record_id=None, - min_feature_length=0, -): - parsed = parse_input_bundle( - primary_upload=primary_upload, - secondary_upload=secondary_upload, - input_mode=input_mode, - infer_orfs=infer_orfs, - min_orf_aa=min_orf_aa, - ) +def reset_state(): + for key in list(st.session_state.keys()): + del st.session_state[key] + initialise_state() - record_ids = [r.id for r in parsed.records] - if not record_ids: - raise ValueError("No records were parsed from the input.") - - chosen_record = selected_record_id if selected_record_id in record_ids else record_ids[0] - record = next(r for r in parsed.records if r.id == chosen_record) - full_df = parsed.feature_tables.get(record.id, pd.DataFrame()).copy() - - available_types = sorted(full_df["feature_type"].dropna().unique().tolist()) if not full_df.empty else [] - default_selected = [x for x in DEFAULT_FEATURES if x in available_types] or available_types - filtered_df = filter_features(full_df, default_selected, gene_query, min_len=min_feature_length) - display_df = filtered_df.copy() - if not display_df.empty and "highlight" in display_df.columns: - display_df["highlight"] = display_df["highlight"].map({True: "yes", False: "no"}) - - stats = build_summary_stats(record, full_df, filtered_df) - stats_df = pd.DataFrame([stats]) - - figure_pack, preview, dist_df, density_df = prepare_figures( - record=record, - filtered_df=filtered_df, - full_df=full_df, - available_types=default_selected, - show_gc_content=show_gc_content, - show_gc_skew=show_gc_skew, - window_size=window_size, - run_mode=run_mode, - ) - summary_text = manuscript_summary_text(stats, dist_df, record.id, gene_query, run_mode) - legend_html = build_legend_html(default_selected, include_highlight=(bool(filtered_df["highlight"].any()) if "highlight" in filtered_df.columns and not filtered_df.empty else False)) - table_csv = display_df.to_csv(index=False).encode("utf-8") - results_zip = make_results_bundle(figure_pack, display_df, display_df, stats_df, density_df, summary_text) - - st.session_state["parsed"] = parsed - st.session_state["analysis_done"] = True - st.session_state["analysis_error"] = "" - st.session_state["record_ids"] = record_ids - st.session_state["selected_record_id"] = record.id - st.session_state["full_df"] = full_df - st.session_state["filtered_df"] = filtered_df - st.session_state["display_df"] = display_df - st.session_state["stats"] = stats - st.session_state["notes"] = parsed.notes - st.session_state["available_types"] = available_types - st.session_state["selected_types_cache"] = default_selected - st.session_state["stats_df"] = stats_df - st.session_state["dist_df"] = dist_df - st.session_state["density_df"] = density_df - st.session_state["summary_text"] = summary_text - st.session_state["figure_pack"] = {**figure_pack, **preview} - st.session_state["table_csv"] = table_csv - st.session_state["summary_zip"] = results_zip - st.session_state["legend_html"] = legend_html - st.session_state["run_mode_cache"] = run_mode - - -init_session_state() - -st.markdown('