diff --git "a/app.py" "b/app.py" deleted file mode 100644 --- "a/app.py" +++ /dev/null @@ -1,2225 +0,0 @@ -""" -GenomeScope Pro 2.1: publication grade genome visualization and genome composition analytics. - -This version shows the complete genome structure for every replicon (chromosome and -plasmids), reports GC content as both tables and figures, reports codon usage bias as both -tables and figures, and adds a set of further genome analyses and figures. - -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 for each record, with curated colour palettes for feature classes -2. Genome composition: GC content (per record table, window table, profile, histogram), - AT content, GC skew, AT skew, cumulative skews, nucleotide and dinucleotide composition, - dinucleotide relative abundance, tetranucleotide frequency, CpG observed/expected, - Shannon entropy, predicted origin and terminus of replication, and assembly statistics -3. Codon usage bias: codon usage table with optimal codon flags, RSCU table and figures, - RSCU heatmap, effective number of codons (ENC), codon adaptation index (CAI), amino acid - usage, GC at codon positions, GC3s, neutrality plot, ENC plot, and PR2 bias plot -4. Per CDS metrics table, per record summary table, a one page overview figure, annotation - tables, genome summary tables, and a downloadable figure and data package for a manuscript - -References for the methods are listed in the sidebar so the output can be cited. -""" - -import io -import os -import re -import gzip -import math -import zipfile -import tempfile -from collections import Counter -from dataclasses import dataclass, field -from typing import Dict, List, Optional, Tuple - -import matplotlib -matplotlib.use("Agg") -import matplotlib.pyplot as plt -from matplotlib.lines import Line2D -from matplotlib.colors import LinearSegmentedColormap -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 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 2.1", - page_icon="🧬", - layout="wide", - initial_sidebar_state="expanded", -) - -plt.rcParams.update({ - "font.family": "sans-serif", - "font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans"], - "font.size": 10, - "axes.titlesize": 13, - "axes.labelsize": 10, - "xtick.labelsize": 8, - "ytick.labelsize": 8, - "legend.fontsize": 8, - "axes.edgecolor": "#333333", - "axes.linewidth": 0.8, - "figure.dpi": 160, - "savefig.dpi": 600, - "pdf.fonttype": 42, - "ps.fonttype": 42, -}) - -st.markdown( - """ - -""", - unsafe_allow_html=True, -) - -# Two curated feature palettes. The default is a tuned set. The colourblind safe set -# uses the Okabe and Ito colours, which print well and read clearly for most readers. -FEATURE_PALETTES = { - "Default": { - "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", - }, - "Colourblind safe": { - "CDS": "#0072B2", - "gene": "#009E73", - "tRNA": "#E69F00", - "rRNA": "#D55E00", - "ncRNA": "#CC79A7", - "misc_RNA": "#56B4E9", - "repeat_region": "#5b5b5b", - "mobile_element": "#8c6d31", - "source": "#bdbdbd", - "exon": "#34a853", - "mRNA": "#56B4E9", - "promoter": "#CC79A7", - "terminator": "#999999", - "ORF": "#117733", - "bed_feature": "#4d4d4d", - "misc_feature": "#8c510a", - "default": "#0072B2", - "highlight": "#F0E442", - }, -} - -# Line and accent themes for the composition and codon figures. -LINE_THEMES = { - "Ocean": {"primary": "#1f6f8b", "secondary": "#e8915b", "cmap": "viridis"}, - "Ember": {"primary": "#b5341f", "secondary": "#2b6f6f", "cmap": "magma"}, - "Forest": {"primary": "#2f7d4f", "secondary": "#8a5a2b", "cmap": "cividis"}, - "Royal": {"primary": "#3a3a8c", "secondary": "#c97b1e", "cmap": "plasma"}, -} - -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"} -DEFAULT_FEATURES = ["CDS", "gene", "tRNA", "rRNA", "ncRNA", "repeat_region", "mobile_element", "misc_feature", "ORF"] -DNA_COMPLEMENT = str.maketrans("ACGTNacgtn", "TGCANtgcan") - -# Kyte and Doolittle hydropathy values for GRAVY. -KD_HYDRO = { - "A": 1.8, "R": -4.5, "N": -3.5, "D": -3.5, "C": 2.5, "Q": -3.5, "E": -3.5, - "G": -0.4, "H": -3.2, "I": 4.5, "L": 3.8, "K": -3.9, "M": 1.9, "F": 2.8, - "P": -1.6, "S": -0.8, "T": -0.7, "W": -0.9, "Y": -1.3, "V": 4.2, -} -AROMATIC_AA = set("FWY") - -# Common NCBI genetic code tables. The user can pick the right one for the organism. -GENETIC_CODE_OPTIONS = { - "11 Bacterial, Archaeal and Plant Plastid": 11, - "1 Standard": 1, - "2 Vertebrate Mitochondrial": 2, - "4 Mold, Protozoan and Coelenterate Mitochondrial": 4, - "5 Invertebrate Mitochondrial": 5, - "9 Echinoderm and Flatworm Mitochondrial": 9, - "23 Thraustochytrium Mitochondrial": 23, -} - - -@dataclass -class CodonContext: - table_id: int - forward_table: Dict[str, str] - stop_codons: set - sense_codons: List[str] - sense_set: set - aa_to_codons: Dict[str, List[str]] - fourfold_boxes: List[Tuple[str, str]] - - -def build_codon_context(table_id: int) -> CodonContext: - table = CodonTable.unambiguous_dna_by_id[table_id] - forward = dict(table.forward_table) - stop = set(table.stop_codons) - sense = sorted(forward.keys()) - aa_to_codons: Dict[str, List[str]] = {} - for codon, aa in forward.items(): - aa_to_codons.setdefault(aa, []).append(codon) - boxes = [] - for first in "ACGT": - for second in "ACGT": - quad = [first + second + t for t in "ACGT"] - aas = {forward.get(c) for c in quad} - if len(aas) == 1 and None not in aas: - boxes.append((first, second)) - return CodonContext(table_id, forward, stop, sense, set(sense), aa_to_codons, boxes) - - -@dataclass -class ParsedGenome: - records: List - feature_tables: Dict[str, pd.DataFrame] - source_mode: str - notes: List[str] = field(default_factory=list) - - -# ----------------------------- -# General helpers -# ----------------------------- -def clean_text(value: object) -> str: - return re.sub(r"\s+", " ", str(value or "")).strip() - - -def file_suffix(name: str) -> str: - 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]: - if str(name).lower().endswith(".gz"): - return os.path.splitext(name)[0], gzip.decompress(data) - return name, data - - -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" - return "unknown" - - -def parse_text_records(data: bytes, fmt: str): - handle = io.StringIO(data.decode("utf-8", errors="replace")) - return list(SeqIO.parse(handle, fmt)) - - -def reverse_complement(seq: str) -> str: - return seq.translate(DNA_COMPLEMENT)[::-1] - - -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 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")) - - -FEATURE_COLUMNS = ["record_id", "feature_type", "label", "start", "end", "length", "strand", - "gene", "locus_tag", "product", "protein_id", "translation", "note", "source"] - - -# ----------------------------- -# Parsing and annotation handling -# ----------------------------- -def record_to_feature_table(record) -> pd.DataFrame: - rows = [] - for feature in getattr(record, "features", []): - try: - start, end, strand = safe_feature_bounds(feature) - q = getattr(feature, "qualifiers", {}) or {} - rows.append({ - "record_id": record.id, - "feature_type": clean_text(getattr(feature, "type", "feature")), - "label": get_feature_label(feature), - "start": max(0, int(start)), - "end": min(len(record.seq), int(end)), - "length": max(0, int(end) - int(start)), - "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 - return pd.DataFrame(rows, columns=FEATURE_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 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 handle: - handle.write(gff_text) - db_path = os.path.join(workdir, "input.db") - return gffutils.create_db( - gff_path, - dbfn=db_path, - force=True, - keep_order=True, - merge_strategy="merge", - sort_attribute_values=True, - disable_infer_transcripts=True, - disable_infer_genes=True, - ) - - -def gff_and_fasta_to_tables(gff_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 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(): - 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 - rows_by_record[record.id].append({ - "record_id": record.id, - "feature_type": clean_text(feature.featuretype), - "label": clean_text(label), - "start": max(0, int(feature.start) - 1), - "end": min(len(record.seq), int(feature.end)), - "length": max(0, int(feature.end) - int(feature.start) + 1), - "strand": strand, - "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/GTF annotation", - }) - return records, {r.id: pd.DataFrame(rows_by_record[r.id], columns=FEATURE_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 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]] - tables = {} - for record in records: - sdf = bed[bed["seqid"].astype(str).isin([record.id, record.id.split()[0]])].copy() - if sdf.empty: - tables[record.id] = pd.DataFrame(columns=FEATURE_COLUMNS) - continue - out = pd.DataFrame({ - "record_id": record.id, - "feature_type": "bed_feature", - "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": "", - "product": "", - "protein_id": "", - "translation": "", - "note": "Imported BED coordinate", - "source": "BED annotation", - }) - out["length"] = (out["end"] - out["start"]).clip(lower=0) - tables[record.id] = out[FEATURE_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") - 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=FEATURE_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[record.id] = out[FEATURE_COLUMNS].sort_values(["start", "end"], kind="stable").reset_index(drop=True) - return records, tables - - -def predict_orfs(sequence: str, ctx: CodonContext, min_aa: int = 90, max_orfs: int = 5000) -> pd.DataFrame: - seq = str(sequence).upper() - seq_len = len(seq) - starts = {"ATG", "GTG", "TTG"} - stop_codons = ctx.stop_codons - rows = [] - - def scan(s: str, strand: int): - 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) - return pd.DataFrame(rows, columns=FEATURE_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: - 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, ctx: CodonContext) -> ParsedGenome: - 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 annotated {fmt.upper()} file: {rich}") - return ParsedGenome(records, tables, fmt, notes) - 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 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 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: - records = parse_text_records(files[fasta], "fasta") - tables = fasta_tables_with_optional_orfs(records, infer_orfs, min_orf_aa, ctx, 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.") - - 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() - - 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 {"Universal auto detect", "EMBL"} and kind == "embl": - records = parse_text_records(primary_data, "embl") - if not records: - 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 {"Universal auto detect", "FASTA"} and kind == "fasta": - records = parse_text_records(primary_data, "fasta") - if not records: - 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, ctx, notes), "fasta", notes) - - 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 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 {"Universal auto detect", "BED plus FASTA"} and kind == "bed": - if secondary_upload is None: - 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 {"Universal auto detect", "Annotation table plus FASTA"} and kind == "table": - if secondary_upload is None: - 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.") - - -def fasta_tables_with_optional_orfs(records, infer_orfs: bool, min_orf_aa: int, ctx: CodonContext, notes: List[str]) -> Dict[str, pd.DataFrame]: - 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), ctx, 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=FEATURE_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 -# ----------------------------- -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 shannon_entropy(sequence: str) -> float: - seq = str(sequence).upper() - counts = [seq.count(b) for b in "ACGT"] - total = sum(counts) - if total == 0: - return 0.0 - return -sum((c / total) * math.log2(c / total) for c in counts if c > 0) - - -def estimate_tm(sequence: str) -> float: - """Rough whole sequence melting temperature using the basic GC fraction rule.""" - seq = str(sequence).upper() - valid = sum(seq.count(x) for x in "ATGC") - if valid == 0: - return 0.0 - g = seq.count("G") - c = seq.count("C") - return round(64.9 + 41.0 * (g + c - 16.4) / valid, 2) if valid else 0.0 - - -def dinucleotide_relative_abundance(sequence: str) -> pd.DataFrame: - seq = re.sub("[^ACGT]", "", str(sequence).upper()) - n = len(seq) - rows = [] - if n < 2: - return pd.DataFrame(columns=["dinucleotide", "observed_freq", "expected_freq", "rho"]) - mono = {b: seq.count(b) / n for b in "ACGT"} - pairs = Counter(seq[i:i + 2] for i in range(n - 1)) - total_pairs = sum(pairs.values()) - for x in "ACGT": - for y in "ACGT": - obs = pairs.get(x + y, 0) / total_pairs if total_pairs else 0.0 - exp = mono[x] * mono[y] - rho = obs / exp if exp > 0 else 0.0 - rows.append({"dinucleotide": x + y, "observed_freq": round(obs, 6), - "expected_freq": round(exp, 6), "rho": round(rho, 4)}) - return pd.DataFrame(rows) - - -def tetranucleotide_frequency(sequence: str, top: int = 25) -> pd.DataFrame: - seq = re.sub("[^ACGT]", "", str(sequence).upper()) - if len(seq) < 4: - return pd.DataFrame(columns=["tetranucleotide", "count", "frequency_per_1000"]) - counts = Counter(seq[i:i + 4] for i in range(len(seq) - 3)) - total = sum(counts.values()) - rows = [{"tetranucleotide": k, "count": v, - "frequency_per_1000": round(1000.0 * v / total, 4)} for k, v in counts.most_common(top)] - return pd.DataFrame(rows) - - -def window_dataframe(sequence: str, window_size: int = 1000) -> pd.DataFrame: - seq = str(sequence).upper() - rows = [] - cum_gc = 0.0 - cum_at = 0.0 - for start in range(0, len(seq), window_size): - end = min(len(seq), start + window_size) - w = seq[start:end] - gc_skew = gc_skew_value(w) - at_skew = at_skew_value(w) - cum_gc += gc_skew - cum_at += at_skew - rows.append({ - "start": start, - "end": end, - "midpoint": (start + end) // 2, - "GC_percent": compute_gc_percent(w), - "AT_percent": compute_at_percent(w), - "GC_skew": gc_skew, - "AT_skew": at_skew, - "cumulative_GC_skew": cum_gc, - "cumulative_AT_skew": cum_at, - "Shannon_entropy_bits": round(shannon_entropy(w), 4), - "N_count": w.count("N"), - }) - return pd.DataFrame(rows) - - -def predict_origin_terminus(window_df: pd.DataFrame) -> Dict[str, object]: - """Predict origin and terminus of replication from the cumulative GC skew. - For many bacterial genomes the global minimum of the cumulative GC skew marks the - origin and the global maximum marks the terminus. This is a prediction and should be - confirmed with dedicated tools for a final assembly.""" - if window_df.empty: - return {"origin_bp": None, "terminus_bp": None} - cum = window_df["cumulative_GC_skew"].values - mids = window_df["midpoint"].values - return { - "origin_bp": int(mids[int(np.argmin(cum))]), - "terminus_bp": int(mids[int(np.argmax(cum))]), - } - - -def assembly_statistics(records) -> Dict[str, object]: - lengths = sorted([len(r.seq) for r in records], reverse=True) - total = sum(lengths) - if total == 0: - return {} - - def n_x(fraction): - threshold = total * fraction - acc = 0 - for i, length in enumerate(lengths, 1): - acc += length - if acc >= threshold: - return length, i - return lengths[-1], len(lengths) - - n50, l50 = n_x(0.5) - n90, l90 = n_x(0.9) - return { - "num_records": len(records), - "total_length_bp": total, - "longest_record_bp": lengths[0], - "shortest_record_bp": lengths[-1], - "mean_record_length_bp": round(total / len(lengths), 1), - "N50_bp": n50, - "L50": l50, - "N90_bp": n90, - "L90": l90, - } - - -def genome_composition(records) -> Dict[str, object]: - """Aggregate nucleotide composition across all records.""" - combined = {"A": 0, "T": 0, "G": 0, "C": 0, "N": 0} - total = 0 - for r in records: - c = nucleotide_counts(str(r.seq)) - for k in combined: - combined[k] += c[k] - total += len(r.seq) - valid = combined["A"] + combined["T"] + combined["G"] + combined["C"] - gc = 100.0 * (combined["G"] + combined["C"]) / valid if valid else 0.0 - at = 100.0 * (combined["A"] + combined["T"]) / valid if valid else 0.0 - g, c = combined["G"], combined["C"] - a, t = combined["A"], combined["T"] - return { - "total_length_bp": total, - "A": combined["A"], "T": combined["T"], "G": combined["G"], "C": combined["C"], "N": combined["N"], - "GC_percent": round(gc, 3), - "AT_percent": round(at, 3), - "GC_skew": round((g - c) / (g + c), 5) if (g + c) else 0.0, - "AT_skew": round((a - t) / (a + t), 5) if (a + t) else 0.0, - } - - -def per_record_summary(records, tables) -> pd.DataFrame: - """One row per record (replicon) with sequence and feature level statistics.""" - rows = [] - for r in records: - seq = str(r.seq) - fdf = tables.get(r.id, pd.DataFrame()) - fc = fdf["feature_type"].value_counts().to_dict() if not fdf.empty else {} - coding = int(fdf.loc[fdf["feature_type"].str.lower().eq("cds"), "length"].sum()) if not fdf.empty else 0 - rows.append({ - "record_id": r.id, - "description": clean_text(getattr(r, "description", ""))[:70], - "length_bp": len(seq), - "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_obs_exp": round(cpg_observed_expected(seq), 4), - "num_features": int(len(fdf)), - "CDS_count": int(fc.get("CDS", 0)), - "tRNA_count": int(fc.get("tRNA", 0)), - "rRNA_count": int(fc.get("rRNA", 0)), - "coding_density_percent": round(100.0 * coding / len(seq), 3) if len(seq) else 0.0, - }) - return pd.DataFrame(rows).sort_values("length_bp", ascending=False).reset_index(drop=True) - - -# ----------------------------- -# Codon and protein analysis -# ----------------------------- -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] - - -CODING_TYPE_PRIORITY = ["cds", "orf", "gene", "mrna"] - - -def collect_coding_sequences(record, feature_df: pd.DataFrame, coding_types: List[str], min_len_bp: int = 90) -> List[str]: - """Collect coding nucleotide sequences for codon analysis. - - For GenBank and EMBL records the original feature objects are used through - feature.extract, which joins exons and applies the strand correctly. For FASTA based - inputs (ORF prediction, GFF, BED, annotation table) the coordinate table is used.""" - types_lower = {t.lower() for t in coding_types} - seqs: List[str] = [] - - used_record_features = False - for feat in getattr(record, "features", []): - if str(getattr(feat, "type", "")).lower() in types_lower: - try: - s = valid_cds_sequence(str(feat.extract(record.seq))) - except Exception: - continue - if len(s) >= min_len_bp: - seqs.append(s) - used_record_features = True - if used_record_features: - return seqs - - if feature_df is not None and not feature_df.empty: - sub = feature_df[feature_df["feature_type"].str.lower().isin(types_lower)] - for _, row in sub.iterrows(): - s = valid_cds_sequence(extract_feature_sequence(record, row)) - if len(s) >= min_len_bp: - seqs.append(s) - return seqs - - -def collect_all_coding(records, tables, coding_choice: str, min_len_bp: int = 90) -> Tuple[List[str], str]: - """Return all coding sequences and the feature type that produced them. - - With auto detect the function tries CDS, then ORF, then gene, then mRNA, and stops at - the first type that yields sequences. This avoids an empty codon table when the file - labels coding features as ORF or gene rather than CDS.""" - candidates = CODING_TYPE_PRIORITY if coding_choice == "Auto detect" else [coding_choice.lower()] - for cand in candidates: - seqs: List[str] = [] - for r in records: - seqs.extend(collect_coding_sequences(r, tables.get(r.id, pd.DataFrame()), [cand], min_len_bp)) - if seqs: - return seqs, cand.upper() - return [], (candidates[0].upper() if candidates else "CDS") - - -def iterate_codons(seq: str): - for i in range(0, len(seq) - 2, 3): - yield seq[i:i + 3] - - -def codon_counts_single(seq: str, ctx: CodonContext) -> Dict[str, int]: - seq = valid_cds_sequence(seq) - counts: Dict[str, int] = {} - for codon in iterate_codons(seq): - if codon in ctx.sense_set: - counts[codon] = counts.get(codon, 0) + 1 - return counts - - -def aggregate_codon_counts(cds_sequences: List[str], ctx: CodonContext) -> Dict[str, int]: - total: Dict[str, int] = {c: 0 for c in ctx.sense_codons} - for seq in cds_sequences: - for codon, n in codon_counts_single(seq, ctx).items(): - total[codon] += n - return total - - -def enc_from_counts(counts: Dict[str, int], ctx: CodonContext) -> float: - """Wright effective number of codons from synonymous family homozygosity.""" - if not counts or sum(counts.values()) == 0: - return float("nan") - f_by_k: Dict[int, List[float]] = {} - for aa, codons in ctx.aa_to_codons.items(): - k = len(codons) - if k == 1: - continue - cvals = np.array([counts.get(c, 0) for c in codons], dtype=float) - n = cvals.sum() - if n <= 1: - continue - p = cvals / n - f = (n * np.sum(p ** 2) - 1) / (n - 1) - if f <= 0: - continue - f_by_k.setdefault(k, []).append(f) - means = {k: float(np.mean(v)) for k, v in f_by_k.items() if v} - f2, f3, f4, f6 = means.get(2), means.get(3), means.get(4), means.get(6) - if f3 is None and f2 and f4: - f3 = (f2 + f4) / 2.0 - enc = 2.0 - if f2: - enc += 9.0 / f2 - if f3: - enc += 1.0 / f3 - if f4: - enc += 5.0 / f4 - if f6: - enc += 3.0 / f6 - if enc <= 2.0: - return float("nan") - return round(float(min(max(enc, 20.0), 61.0)), 3) - - -def codon_usage_table(counts: Dict[str, int], ctx: CodonContext, stop_counts: Optional[Dict[str, int]] = None, reference_weights: Optional[Dict[str, float]] = None) -> pd.DataFrame: - stop_counts = stop_counts or {c: 0 for c in ctx.stop_codons} - total_sense = sum(counts.values()) - rows = [] - for aa, codons in sorted(ctx.aa_to_codons.items()): - aa_total = sum(counts.get(c, 0) for c in codons) - n_syn = len(codons) - max_count = max([counts.get(c, 0) for c in codons]) if codons else 0 - for codon in sorted(codons): - count = counts.get(codon, 0) - freq_per_thousand = (count / total_sense * 1000.0) if total_sense else 0.0 - expected = aa_total / n_syn if n_syn else 0 - rscu = count / expected if expected else 0.0 - rel_adapt = (count / max_count) if max_count else 0.0 - rows.append({ - "amino_acid": aa, - "codon": codon, - "count": count, - "frequency_per_1000": round(freq_per_thousand, 4), - "RSCU": round(rscu, 4), - "relative_adaptiveness_w": round(rel_adapt, 4), - "optimal_codon": bool(count > 0 and count == max_count and n_syn > 1), - "reference_weight": reference_weights.get(codon, np.nan) if reference_weights else np.nan, - }) - for codon in sorted(ctx.stop_codons): - rows.append({ - "amino_acid": "Stop", - "codon": codon, - "count": stop_counts.get(codon, 0), - "frequency_per_1000": 0.0, - "RSCU": 0.0, - "relative_adaptiveness_w": 0.0, - "optimal_codon": False, - "reference_weight": np.nan, - }) - return pd.DataFrame(rows) - - -def optimal_codon_table(codon_df: pd.DataFrame) -> pd.DataFrame: - if codon_df.empty: - return pd.DataFrame(columns=["amino_acid", "codon", "count", "RSCU", "frequency_per_1000"]) - opt = codon_df[codon_df["optimal_codon"]].copy() - return opt[["amino_acid", "codon", "count", "RSCU", "frequency_per_1000"]].sort_values("amino_acid").reset_index(drop=True) - - -def derive_weights_from_counts(counts: Dict[str, int], ctx: CodonContext) -> Dict[str, float]: - weights: Dict[str, float] = {} - for aa, codons in ctx.aa_to_codons.items(): - max_count = max([counts.get(c, 0) for c in codons]) if codons else 0 - for codon in codons: - weights[codon] = (counts.get(codon, 0) / max_count) if max_count else 0.0 - return weights - - -def cai_single(seq: str, ctx: CodonContext, weights: Optional[Dict[str, float]]) -> float: - if not weights: - return float("nan") - logs = [] - for codon in iterate_codons(valid_cds_sequence(seq)): - if codon in ctx.sense_set: - 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 float("nan") - - -def codon_position_gc(seq: str) -> Tuple[float, float, float]: - seq = valid_cds_sequence(seq) - gc = [0, 0, 0] - tot = [0, 0, 0] - for codon in iterate_codons(seq): - for j in range(3): - base = codon[j] - if base in "ACGT": - tot[j] += 1 - if base in "GC": - gc[j] += 1 - return tuple(100.0 * gc[j] / tot[j] if tot[j] else 0.0 for j in range(3)) - - -def gc3s_value(seq: str, ctx: CodonContext) -> float: - seq = valid_cds_sequence(seq) - gc = 0 - tot = 0 - for codon in iterate_codons(seq): - aa = ctx.forward_table.get(codon) - if aa is None: - continue - if len(ctx.aa_to_codons.get(aa, [])) <= 1: - continue - third = codon[2] - if third in "ACGT": - tot += 1 - if third in "GC": - gc += 1 - return 100.0 * gc / tot if tot else 0.0 - - -def pr2_components(seq: str, ctx: CodonContext) -> Tuple[float, float, int]: - """Return G3/(G3+C3) and A3/(A3+T3) over four-fold degenerate codon boxes.""" - seq = valid_cds_sequence(seq) - box_set = set(ctx.fourfold_boxes) - a3 = t3 = g3 = c3 = 0 - for codon in iterate_codons(seq): - if (codon[0], codon[1]) in box_set: - third = codon[2] - if third == "A": - a3 += 1 - elif third == "T": - t3 += 1 - elif third == "G": - g3 += 1 - elif third == "C": - c3 += 1 - gc = g3 + c3 - at = a3 + t3 - x = g3 / gc if gc else np.nan - y = a3 / at if at else np.nan - return x, y, at + gc - - -def translate_cds(seq: str, ctx: CodonContext) -> str: - seq = valid_cds_sequence(seq) - if not seq: - return "" - try: - protein = str(Seq(seq).translate(table=ctx.table_id)) - except Exception: - return "" - return protein.split("*")[0] - - -def protein_metrics(protein: str) -> Tuple[float, float]: - protein = re.sub("[^ACDEFGHIKLMNPQRSTVWY]", "", str(protein).upper()) - if not protein: - return float("nan"), float("nan") - gravy = sum(KD_HYDRO.get(a, 0.0) for a in protein) / len(protein) - aromaticity = sum(1 for a in protein if a in AROMATIC_AA) / len(protein) - return round(gravy, 4), round(aromaticity, 4) - - -def per_cds_metrics(cds_sequences: List[str], ctx: CodonContext, weights: Optional[Dict[str, float]], min_len_bp: int = 90) -> pd.DataFrame: - rows = [] - for idx, seq in enumerate(cds_sequences, 1): - seq = valid_cds_sequence(seq) - if len(seq) < min_len_bp: - continue - counts = codon_counts_single(seq, ctx) - enc = enc_from_counts(counts, ctx) - gc1, gc2, gc3 = codon_position_gc(seq) - x_pr2, y_pr2, pr2_n = pr2_components(seq, ctx) - protein = translate_cds(seq, ctx) - gravy, aromaticity = protein_metrics(protein) - rows.append({ - "cds_index": idx, - "length_bp": len(seq), - "length_aa": len(protein), - "GC_percent": round(compute_gc_percent(seq), 3), - "GC1": round(gc1, 3), - "GC2": round(gc2, 3), - "GC3": round(gc3, 3), - "GC12": round((gc1 + gc2) / 2.0, 3), - "GC3s": round(gc3s_value(seq, ctx), 3), - "ENC": enc, - "CAI": cai_single(seq, ctx, weights), - "GRAVY": gravy, - "aromaticity": aromaticity, - "PR2_G3_over_GC3": round(x_pr2, 4) if not np.isnan(x_pr2) else np.nan, - "PR2_A3_over_AT3": round(y_pr2, 4) if not np.isnan(y_pr2) else np.nan, - }) - return pd.DataFrame(rows) - - -def amino_acid_usage(cds_sequences: List[str], ctx: CodonContext) -> pd.DataFrame: - counter: Counter = Counter() - for seq in cds_sequences: - counter.update(translate_cds(seq, ctx)) - total = sum(counter.values()) - order = "ACDEFGHIKLMNPQRSTVWY" - rows = [{"amino_acid": aa, "count": counter.get(aa, 0), - "frequency_percent": round(100.0 * counter.get(aa, 0) / total, 4) if total else 0.0} - for aa in order] - return pd.DataFrame(rows) - - -def parse_reference_codon_weights(uploaded_ref, ctx: CodonContext) -> 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 ctx.sense_set: - try: - weights[codon] = float(row[weight_col]) - except Exception: - pass - return weights or None - - -def neutrality_regression(per_cds: pd.DataFrame) -> Dict[str, float]: - if per_cds.empty or len(per_cds) < 3: - return {"slope": np.nan, "intercept": np.nan, "r": np.nan, "n": int(len(per_cds))} - x = per_cds["GC3"].astype(float).values - y = per_cds["GC12"].astype(float).values - mask = np.isfinite(x) & np.isfinite(y) - x, y = x[mask], y[mask] - if len(x) < 3: - return {"slope": np.nan, "intercept": np.nan, "r": np.nan, "n": int(len(x))} - slope, intercept = np.polyfit(x, y, 1) - r = float(np.corrcoef(x, y)[0, 1]) - return {"slope": round(float(slope), 4), "intercept": round(float(intercept), 4), - "r": round(r, 4), "n": int(len(x))} - - -def enc_expected_curve(gc3s_fraction: np.ndarray) -> np.ndarray: - s = np.clip(gc3s_fraction, 1e-6, 1 - 1e-6) - return 2 + s + 29.0 / (s ** 2 + (1 - s) ** 2) - - -# ----------------------------- -# Summary statistics -# ----------------------------- -def build_summary_statistics(records, main_record, composition, assembly, origin_terminus, - full_df_main, filtered_df, all_cds, codon_df, codon_counts, - ctx, cai_mean, per_cds, neutrality) -> Dict[str, object]: - main_seq = str(main_record.seq).upper() - feature_counts = full_df_main["feature_type"].value_counts().to_dict() if not full_df_main.empty else {} - coding_bp = int(full_df_main.loc[full_df_main["feature_type"].str.lower().eq("cds"), "length"].sum()) if not full_df_main.empty else 0 - total_codons = int(sum(codon_counts.values())) - enc_genome = enc_from_counts(codon_counts, ctx) - mean_enc = round(float(per_cds["ENC"].dropna().mean()), 3) if not per_cds.empty else np.nan - mean_gravy = round(float(per_cds["GRAVY"].dropna().mean()), 4) if not per_cds.empty else np.nan - return { - "main_record_id": main_record.id, - "main_record_description": clean_text(getattr(main_record, "description", "")), - "num_records": len(records), - "total_genome_length_bp": composition["total_length_bp"], - "main_record_length_bp": len(main_seq), - "A": composition["A"], "T": composition["T"], "G": composition["G"], - "C": composition["C"], "N": composition["N"], - "GC_percent": composition["GC_percent"], - "AT_percent": composition["AT_percent"], - "GC_skew": composition["GC_skew"], - "AT_skew": composition["AT_skew"], - "CpG_observed_expected": round(cpg_observed_expected(main_seq), 5), - "Shannon_entropy_bits": round(shannon_entropy(main_seq), 4), - "estimated_Tm_C": estimate_tm(main_seq), - "N50_bp": assembly.get("N50_bp"), - "L50": assembly.get("L50"), - "N90_bp": assembly.get("N90_bp"), - "predicted_origin_bp": origin_terminus.get("origin_bp"), - "predicted_terminus_bp": origin_terminus.get("terminus_bp"), - "total_features_main_record": int(len(full_df_main)), - "displayed_features": int(len(filtered_df)), - "CDS_count_main_record": int(feature_counts.get("CDS", 0)), - "gene_count_main_record": int(feature_counts.get("gene", 0)), - "tRNA_count_main_record": int(feature_counts.get("tRNA", 0)), - "rRNA_count_main_record": int(feature_counts.get("rRNA", 0)), - "ORF_count_main_record": int(feature_counts.get("ORF", 0)), - "coding_bp_main_record": coding_bp, - "coding_density_percent_main_record": round(100.0 * coding_bp / len(main_seq), 3) if len(main_seq) else 0.0, - "CDS_used_for_codon_analysis": len(all_cds), - "total_sense_codons": total_codons, - "effective_number_of_codons_ENC_genome": enc_genome, - "mean_ENC_per_CDS": mean_enc, - "mean_GRAVY_per_CDS": mean_gravy, - "codon_adaptation_index_CAI_mean": cai_mean, - "neutrality_slope_GC12_vs_GC3": neutrality.get("slope"), - "neutrality_correlation_r": neutrality.get("r"), - } - - -# ----------------------------- -# Filtering -# ----------------------------- -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: - 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_name in fields: - if field_name in out.columns: - mask = mask | out[field_name].fillna("").str.lower().str.contains(re.escape(q), na=False) - out["highlight"] = mask - else: - 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) - - -# ----------------------------- -# Legends -# ----------------------------- -def feature_legend_html(feature_types: List[str], highlight: bool, palette: Dict[str, str]) -> str: - parts = [] - for ft in feature_types: - color = palette.get(ft, palette["default"]) - parts.append(f'{ft}') - if highlight: - parts.append(f'highlighted match') - return "".join(parts) - - -def add_matplotlib_legend(ax, feature_types: List[str], highlight: bool, palette: Dict[str, str]): - handles = [] - for ft in feature_types: - handles.append(Line2D([0], [0], color=palette.get(ft, palette["default"]), lw=5, label=ft)) - if highlight: - handles.append(Line2D([0], [0], color=palette["highlight"], lw=5, label="highlighted match")) - if handles: - ax.legend(handles=handles, frameon=False, ncol=2, loc="upper right") - - -# ----------------------------- -# Figures -# ----------------------------- -def draw_linear_map(record, filtered_df, feature_types, publication, palette, panel="A"): - if GraphicFeature is None or GraphicRecord is None: - raise RuntimeError("dna_features_viewer is required. Install it with: pip install dna_features_viewer") - features = [] - label_limit = 160 if publication else 80 - for _, row in filtered_df.iterrows(): - color = palette["highlight"] if bool(row.get("highlight", False)) else palette.get(row["feature_type"], palette["default"]) - 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(f"{panel}. 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, palette) - plt.tight_layout() - return fig - - -def draw_circular_map(record, filtered_df, window_df, feature_types, palette, theme, panel="B"): - 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] - axis = sector.add_track((92, 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((74, 90)) - reverse = sector.add_track((58, 73)) - forward.axis(fc="#ffffff", ec="#555555", lw=0.25) - reverse.axis(fc="#ffffff", ec="#555555", lw=0.25) - for _, row in filtered_df.iterrows(): - color = palette["highlight"] if bool(row.get("highlight", False)) else palette.get(row["feature_type"], palette["default"]) - 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) - - if not window_df.empty: - gc_track = sector.add_track((42, 56)) - 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, color=theme["primary"]) - gc_track.fill_between(window_df["midpoint"].tolist(), window_df["GC_percent"].tolist(), y2=[float(window_df["GC_percent"].mean())] * len(window_df), vmin=0, vmax=100, alpha=0.25, color=theme["primary"]) - - max_gc_skew = max(0.05, float(np.nanmax(np.abs(window_df["GC_skew"])))) - gc_skew_track = sector.add_track((28, 41)) - gc_skew_track.axis(fc="#fbfbfb", ec="#555555", lw=0.2) - gc_skew_track.line(window_df["midpoint"].tolist(), window_df["GC_skew"].tolist(), vmin=-max_gc_skew, vmax=max_gc_skew, lw=0.8, color=theme["secondary"]) - gc_skew_track.fill_between(window_df["midpoint"].tolist(), window_df["GC_skew"].tolist(), y2=0, vmin=-max_gc_skew, vmax=max_gc_skew, alpha=0.30, color=theme["secondary"]) - - max_at_skew = max(0.05, float(np.nanmax(np.abs(window_df["AT_skew"])))) - at_skew_track = sector.add_track((14, 27)) - at_skew_track.axis(fc="#fbfbfb", ec="#555555", lw=0.2) - at_skew_track.line(window_df["midpoint"].tolist(), window_df["AT_skew"].tolist(), vmin=-max_at_skew, vmax=max_at_skew, lw=0.8, color="#7d7d7d") - - fig = circos.plotfig() - fig.set_size_inches(9.4, 9.4) - fig.suptitle(f"{panel}. Circular genome map with GC content, GC skew and AT skew tracks", x=0.06, y=0.99, ha="left", fontweight="bold") - return fig - - -def draw_feature_distribution(feature_df, palette): - 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 = dist.head(15) - colors = [palette.get(x, palette["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) - plt.tight_layout() - return fig, dist - - -def draw_gc_profile(window_df, seq_len, theme): - fig, ax = plt.subplots(figsize=(10, 4.8)) - ax.set_title("D. GC content with GC skew and AT skew", 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: - ax.plot(window_df["midpoint"], window_df["GC_percent"], label="GC percent", lw=1.8, color=theme["primary"]) - ax.set_xlabel("Genome position (bp)") - ax.set_ylabel("GC percent") - ax.set_xlim(0, seq_len) - ax.grid(alpha=0.25) - ax2 = ax.twinx() - ax2.plot(window_df["midpoint"], window_df["GC_skew"], label="GC skew", lw=1.1, linestyle="--", color=theme["secondary"]) - ax2.plot(window_df["midpoint"], window_df["AT_skew"], label="AT skew", lw=1.0, linestyle=":", color="#7d7d7d") - ax2.set_ylabel("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 draw_gc_histogram(window_df, theme): - fig, ax = plt.subplots(figsize=(8.5, 4.6)) - ax.set_title("N. GC content distribution across windows", 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: - ax.hist(window_df["GC_percent"], bins=40, color=theme["primary"], edgecolor="#222222", linewidth=0.3) - mean_gc = float(window_df["GC_percent"].mean()) - ax.axvline(mean_gc, color=theme["secondary"], lw=1.6, linestyle="--", label=f"mean GC = {mean_gc:.2f}%") - ax.set_xlabel("GC percent per window") - ax.set_ylabel("Number of windows") - ax.legend(frameon=False, loc="upper right") - ax.grid(axis="y", alpha=0.25) - plt.tight_layout() - return fig - - -def draw_cumulative_skew(window_df, origin_terminus, seq_len, theme): - fig, ax = plt.subplots(figsize=(10, 4.8)) - ax.set_title("E. Cumulative GC skew with predicted origin and terminus", 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: - ax.plot(window_df["midpoint"], window_df["cumulative_GC_skew"], lw=1.8, color=theme["primary"], label="Cumulative GC skew") - ax.plot(window_df["midpoint"], window_df["cumulative_AT_skew"], lw=1.2, linestyle="--", color=theme["secondary"], label="Cumulative AT skew") - ori = origin_terminus.get("origin_bp") - ter = origin_terminus.get("terminus_bp") - if ori is not None: - ax.axvline(ori, color="#1a9850", lw=1.2, linestyle="-.", label=f"Predicted origin ~{ori:,} bp") - if ter is not None: - ax.axvline(ter, color="#d73027", lw=1.2, linestyle="-.", label=f"Predicted terminus ~{ter:,} bp") - ax.set_xlabel("Genome position (bp)") - ax.set_ylabel("Cumulative skew") - ax.set_xlim(0, seq_len) - ax.grid(alpha=0.25) - ax.legend(frameon=False, loc="best") - plt.tight_layout() - return fig - - -def draw_composition(nuc_counts, dinuc_df, theme): - fig, axes = plt.subplots(1, 2, figsize=(13, 4.8)) - axes[0].set_title("F1. Nucleotide composition", loc="left", fontweight="bold") - bases = ["A", "T", "G", "C", "N"] - base_colors = ["#4575b4", "#91bfdb", "#fc8d59", "#d73027", "#999999"] - values = [nuc_counts.get(b, 0) for b in bases] - axes[0].bar(bases, values, color=base_colors, edgecolor="#222222", linewidth=0.35) - axes[0].set_ylabel("Count") - axes[0].grid(axis="y", alpha=0.25) - - axes[1].set_title("F2. Dinucleotide relative abundance", loc="left", fontweight="bold") - if dinuc_df.empty: - axes[1].text(0.5, 0.5, "No data", ha="center", va="center") - axes[1].axis("off") - else: - colors = [theme["secondary"] if (r > 1.23 or r < 0.78) else theme["primary"] for r in dinuc_df["rho"]] - axes[1].bar(dinuc_df["dinucleotide"], dinuc_df["rho"], color=colors, edgecolor="#222222", linewidth=0.3) - axes[1].axhline(1.0, color="#444444", lw=1.0) - axes[1].axhline(1.23, color="#999999", lw=0.8, linestyle="--") - axes[1].axhline(0.78, color="#999999", lw=0.8, linestyle="--") - axes[1].set_ylabel("rho (observed / expected)") - axes[1].tick_params(axis="x", rotation=90) - axes[1].grid(axis="y", alpha=0.25) - plt.tight_layout() - return fig - - -def draw_codon_rscu(codon_df, theme): - fig, ax = plt.subplots(figsize=(13, 5.2)) - ax.set_title("G. 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") - else: - sense["label"] = sense["codon"] + "\n" + sense["amino_acid"] - colors = [theme["primary"] if v >= 1 else theme["secondary"] for v in sense["RSCU"]] - ax.bar(sense["label"], sense["RSCU"], color=colors, edgecolor="#222222", linewidth=0.25) - ax.axhline(1.0, lw=1.0, linestyle="--", color="#444444") - 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 draw_rscu_heatmap(codon_df, ctx, cmap_name): - fig, ax = plt.subplots(figsize=(7.5, 9)) - ax.set_title("H. RSCU codon table heatmap", loc="left", fontweight="bold") - if codon_df.empty or codon_df["count"].sum() == 0: - ax.text(0.5, 0.5, "No CDS codon data available", ha="center", va="center") - ax.axis("off") - plt.tight_layout() - return fig - bases = "TCAG" - rscu_map = dict(zip(codon_df["codon"], codon_df["RSCU"])) - aa_map = dict(zip(codon_df["codon"], codon_df["amino_acid"])) - matrix = np.full((16, 4), np.nan) - labels = [["" for _ in range(4)] for _ in range(16)] - for i, first in enumerate(bases): - for j, second in enumerate(bases): - row = i * 4 + j - for k, third in enumerate(bases): - codon = first + second + third - matrix[row, k] = rscu_map.get(codon, np.nan) - aa = aa_map.get(codon, "*") - labels[row][k] = f"{codon}\n{aa}" - im = ax.imshow(matrix, cmap=cmap_name, aspect="auto", vmin=0, vmax=max(2.0, np.nanmax(matrix))) - ax.set_xticks(range(4)) - ax.set_xticklabels(list(bases)) - ax.set_yticks(range(16)) - ax.set_yticklabels([first + second for first in bases for second in bases]) - ax.set_xlabel("Third position") - ax.set_ylabel("First and second position") - for r in range(16): - for c in range(4): - if not np.isnan(matrix[r, c]): - ax.text(c, r, labels[r][c], ha="center", va="center", fontsize=6, color="#111111") - fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04, label="RSCU") - plt.tight_layout() - return fig - - -def draw_amino_acid_usage(aa_df, theme): - fig, ax = plt.subplots(figsize=(11, 4.6)) - ax.set_title("I. Amino acid usage", loc="left", fontweight="bold") - if aa_df.empty or aa_df["count"].sum() == 0: - ax.text(0.5, 0.5, "No protein data available", ha="center", va="center") - ax.axis("off") - else: - ordered = aa_df.sort_values("frequency_percent", ascending=False) - ax.bar(ordered["amino_acid"], ordered["frequency_percent"], color=theme["primary"], edgecolor="#222222", linewidth=0.3) - ax.set_ylabel("Frequency (%)") - ax.set_xlabel("Amino acid") - ax.grid(axis="y", alpha=0.25) - plt.tight_layout() - return fig - - -def draw_neutrality(per_cds, neutrality, theme): - fig, ax = plt.subplots(figsize=(6.6, 6)) - ax.set_title("J. Neutrality plot (GC12 vs GC3)", loc="left", fontweight="bold") - if per_cds.empty: - ax.text(0.5, 0.5, "No CDS data available", ha="center", va="center") - ax.axis("off") - else: - ax.scatter(per_cds["GC3"], per_cds["GC12"], s=12, alpha=0.55, color=theme["primary"], edgecolor="none") - slope = neutrality.get("slope") - intercept = neutrality.get("intercept") - if slope is not None and not (isinstance(slope, float) and np.isnan(slope)): - xs = np.linspace(per_cds["GC3"].min(), per_cds["GC3"].max(), 50) - ax.plot(xs, slope * xs + intercept, color=theme["secondary"], lw=1.8, - label=f"slope = {slope:.3f}, r = {neutrality.get('r')}") - ax.legend(frameon=False, loc="best") - ax.set_xlabel("GC3 (%)") - ax.set_ylabel("GC12 (%)") - ax.grid(alpha=0.25) - plt.tight_layout() - return fig - - -def draw_enc_plot(per_cds, theme): - fig, ax = plt.subplots(figsize=(6.6, 6)) - ax.set_title("K. ENC plot against expected curve", loc="left", fontweight="bold") - if per_cds.empty: - ax.text(0.5, 0.5, "No CDS data available", ha="center", va="center") - ax.axis("off") - else: - ax.scatter(per_cds["GC3s"], per_cds["ENC"], s=12, alpha=0.55, color=theme["primary"], edgecolor="none", label="CDS") - xs = np.linspace(0.0, 1.0, 200) - ax.plot(xs * 100, enc_expected_curve(xs), color=theme["secondary"], lw=1.8, label="Wright expected curve") - ax.set_xlim(0, 100) - ax.set_ylim(20, 62) - ax.set_xlabel("GC3s (%)") - ax.set_ylabel("ENC") - ax.grid(alpha=0.25) - ax.legend(frameon=False, loc="best") - plt.tight_layout() - return fig - - -def draw_pr2_plot(per_cds, theme): - fig, ax = plt.subplots(figsize=(6.4, 6.2)) - ax.set_title("L. PR2 bias plot", loc="left", fontweight="bold") - sub = per_cds.dropna(subset=["PR2_G3_over_GC3", "PR2_A3_over_AT3"]) if not per_cds.empty else pd.DataFrame() - if sub.empty: - ax.text(0.5, 0.5, "No four-fold codon data available", ha="center", va="center") - ax.axis("off") - else: - ax.scatter(sub["PR2_G3_over_GC3"], sub["PR2_A3_over_AT3"], s=12, alpha=0.55, color=theme["primary"], edgecolor="none") - ax.axvline(0.5, color="#444444", lw=1.0, linestyle="--") - ax.axhline(0.5, color="#444444", lw=1.0, linestyle="--") - ax.set_xlim(0, 1) - ax.set_ylim(0, 1) - ax.set_xlabel("G3 / (G3 + C3)") - ax.set_ylabel("A3 / (A3 + T3)") - ax.grid(alpha=0.25) - plt.tight_layout() - return fig - - -def draw_feature_length_distribution(per_cds, theme): - fig, ax = plt.subplots(figsize=(8.5, 4.6)) - ax.set_title("M. CDS length distribution", loc="left", fontweight="bold") - if per_cds.empty: - ax.text(0.5, 0.5, "No CDS data available", ha="center", va="center") - ax.axis("off") - else: - ax.hist(per_cds["length_bp"], bins=40, color=theme["primary"], edgecolor="#222222", linewidth=0.3) - ax.set_xlabel("CDS length (bp)") - ax.set_ylabel("Number of CDS") - ax.grid(axis="y", alpha=0.25) - plt.tight_layout() - return fig - - -def draw_summary_dashboard(window_df, codon_df, per_cds, feature_df, theme): - fig, axes = plt.subplots(2, 2, figsize=(14, 9)) - - ax = axes[0, 0] - ax.set_title("GC content along the genome", loc="left", fontweight="bold") - if not window_df.empty: - ax.plot(window_df["midpoint"], window_df["GC_percent"], lw=1.4, color=theme["primary"]) - ax.set_xlabel("Position (bp)") - ax.set_ylabel("GC percent") - ax.grid(alpha=0.25) - else: - ax.axis("off") - - ax = axes[0, 1] - ax.set_title("Feature classes", loc="left", fontweight="bold") - dist = feature_df["feature_type"].value_counts().head(10) if not feature_df.empty else pd.Series(dtype=int) - if not dist.empty: - ax.bar(dist.index, dist.values, color=theme["primary"], edgecolor="#222222", linewidth=0.3) - ax.tick_params(axis="x", rotation=40) - ax.set_ylabel("Count") - ax.grid(axis="y", alpha=0.25) - else: - ax.axis("off") - - ax = axes[1, 0] - ax.set_title("ENC against GC3s", loc="left", fontweight="bold") - if not per_cds.empty: - ax.scatter(per_cds["GC3s"], per_cds["ENC"], s=10, alpha=0.5, color=theme["primary"], edgecolor="none") - xs = np.linspace(0.0, 1.0, 200) - ax.plot(xs * 100, enc_expected_curve(xs), color=theme["secondary"], lw=1.5) - ax.set_xlim(0, 100) - ax.set_ylim(20, 62) - ax.set_xlabel("GC3s (%)") - ax.set_ylabel("ENC") - ax.grid(alpha=0.25) - else: - ax.axis("off") - - ax = axes[1, 1] - ax.set_title("Relative synonymous codon usage", loc="left", fontweight="bold") - sense = codon_df[codon_df["amino_acid"] != "Stop"] if not codon_df.empty else pd.DataFrame() - if not sense.empty and sense["count"].sum() > 0: - ax.bar(range(len(sense)), sense["RSCU"], color=theme["primary"], linewidth=0) - ax.axhline(1.0, color="#444444", lw=0.8, linestyle="--") - ax.set_ylabel("RSCU") - ax.set_xlabel("Codons") - ax.set_xticks([]) - else: - ax.axis("off") - - fig.suptitle("Genome analysis overview", x=0.02, ha="left", fontweight="bold", fontsize=15) - plt.tight_layout(rect=(0, 0, 1, 0.97)) - return fig - - -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_bundle(figures, tables, summary_text, methods_text) -> 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(os.path.join("figures", name), data) - for name, df in tables.items(): - zf.writestr(os.path.join("tables", name), df.to_csv(index=False)) - zf.writestr("manuscript_summary.txt", summary_text) - zf.writestr("methods.txt", methods_text) - mem.seek(0) - return mem.getvalue() - - -def manuscript_summary(stats: Dict[str, object]) -> str: - def fmt(value, spec=""): - if value is None or (isinstance(value, float) and np.isnan(value)): - return "not available" - return format(value, spec) if spec else str(value) - return ( - f"The dataset {stats['main_record_id']} contained {fmt(stats['num_records'])} sequence record(s) " - f"with a total length of {fmt(stats['total_genome_length_bp'], ',')} bp. The assembly had an N50 of " - f"{fmt(stats['N50_bp'], ',')} bp and an L50 of {fmt(stats['L50'])}. The overall GC content was " - f"{fmt(stats['GC_percent'], '.2f')}%, AT content was {fmt(stats['AT_percent'], '.2f')}%, GC skew was " - f"{fmt(stats['GC_skew'], '.5f')}, AT skew was {fmt(stats['AT_skew'], '.5f')}, and the CpG observed to " - f"expected ratio was {fmt(stats['CpG_observed_expected'], '.5f')}. The predicted origin and terminus of " - f"replication were near {fmt(stats['predicted_origin_bp'], ',')} bp and {fmt(stats['predicted_terminus_bp'], ',')} bp. " - f"In the longest record, {fmt(stats['total_features_main_record'], ',')} features were parsed, including " - f"{fmt(stats['CDS_count_main_record'], ',')} CDS, {fmt(stats['tRNA_count_main_record'], ',')} tRNA and " - f"{fmt(stats['rRNA_count_main_record'], ',')} rRNA features, which is a coding density of " - f"{fmt(stats['coding_density_percent_main_record'], '.2f')}%. Codon usage was analysed using " - f"{fmt(stats['CDS_used_for_codon_analysis'], ',')} CDS that covered {fmt(stats['total_sense_codons'], ',')} sense codons. " - f"The genome wide effective number of codons was {fmt(stats['effective_number_of_codons_ENC_genome'], '.2f')}, " - f"as well as a mean per CDS value of {fmt(stats['mean_ENC_per_CDS'], '.2f')}. The neutrality plot of GC12 against " - f"GC3 gave a regression slope of {fmt(stats['neutrality_slope_GC12_vs_GC3'], '.3f')} and a correlation of " - f"{fmt(stats['neutrality_correlation_r'], '.3f')}, which describes the balance between mutation and selection " - f"pressure on codon usage. The mean codon adaptation index was {fmt(stats['codon_adaptation_index_CAI_mean'], '.4f')}." - ) - - -METHODS_TEXT = ( - "Methods. Sequence composition was computed from nucleotide counts. GC content and AT content were the " - "percentage of G plus C and A plus T over valid bases. GC skew was (G minus C) over (G plus C) and AT skew " - "was (A minus T) over (A plus T), computed in sliding windows and cumulatively. The predicted origin and " - "terminus of replication were taken as the minimum and maximum of the cumulative GC skew (Lobry 1996; " - "Grigoriev 1998). CpG observed over expected followed Gardiner-Garden and Frommer (1987). Dinucleotide " - "relative abundance (genomic signature) followed Karlin and Burge (1995). Codon usage and relative " - "synonymous codon usage followed Sharp and Li (1986). The effective number of codons followed Wright (1990). " - "The codon adaptation index followed Sharp and Li (1987). The neutrality plot followed Sueoka (1988), the " - "ENC plot followed Wright (1990), and the PR2 bias plot followed Sueoka (1995). GRAVY followed Kyte and " - "Doolittle (1982). Users should confirm the genetic code table and confirm predictions with dedicated tools " - "before final reporting." -) - - -# ----------------------------- -# Per record figure rendering -# ----------------------------- -def render_record_figures(records, tables, main_record, main_figs, detailed_ids, selected_types_main, - query, min_feature_length, max_features, window_size, publication, dpi, palette, theme): - """Render linear, circular and GC profile figures for each detailed record. - The main record reuses the already computed figures to avoid repeated work.""" - record_figures = {} - record_figures[main_record.id] = { - "linear": main_figs["linear"], - "circular": main_figs["circular"], - "gc": main_figs["gc"], - "length_bp": len(main_record.seq), - "selected_types": selected_types_main, - } - for r in records: - if r.id == main_record.id or r.id not in detailed_ids: - continue - fdf = tables.get(r.id, pd.DataFrame()).copy() - avail = sorted(fdf["feature_type"].dropna().unique().tolist()) if not fdf.empty else [] - sel = [x for x in DEFAULT_FEATURES if x in avail] or avail - filt = filter_features(fdf, sel, query, int(min_feature_length), int(max_features)) - wdf = window_dataframe(str(r.seq), int(window_size)) - lin = draw_linear_map(r, filt, sel, publication, palette, panel="A") - circ = draw_circular_map(r, filt, wdf, sel, palette, theme, panel="B") - gcp = draw_gc_profile(wdf, len(r.seq), theme) - record_figures[r.id] = { - "linear": fig_bytes(lin, "png", dpi), - "circular": fig_bytes(circ, "png", dpi), - "gc": fig_bytes(gcp, "png", dpi), - "length_bp": len(r.seq), - "selected_types": sel, - } - for f in (lin, circ, gcp): - plt.close(f) - return record_figures - - -# ----------------------------- -# Session state and Streamlit UI -# ----------------------------- -def initialise_state(): - defaults = { - "done": False, - "error": "", - "records": [], - "tables": {}, - "main_record_id": None, - "stats": {}, - "stats_df": pd.DataFrame(), - "feature_df": pd.DataFrame(), - "filtered_df": pd.DataFrame(), - "window_df": pd.DataFrame(), - "codon_df": pd.DataFrame(), - "optimal_df": pd.DataFrame(), - "per_cds_df": pd.DataFrame(), - "per_record_df": pd.DataFrame(), - "aa_df": pd.DataFrame(), - "dinuc_df": pd.DataFrame(), - "tetra_df": pd.DataFrame(), - "dist_df": pd.DataFrame(), - "assembly": {}, - "origin_terminus": {}, - "neutrality": {}, - "summary": "", - "figures": {}, - "record_figures": {}, - "detailed_order": [], - "bundle": None, - "notes": [], - "available_types": [], - "selected_types": [], - "palette_name": "Default", - } - for k, v in defaults.items(): - st.session_state.setdefault(k, v) - - -def reset_state(): - for key in list(st.session_state.keys()): - del st.session_state[key] - initialise_state() - - -initialise_state() - -st.markdown('
GenomeScope Pro 2.1: Whole Genome Structure, GC Content and Codon Usage Analytics
', unsafe_allow_html=True) -st.markdown('
Per replicon genome maps with all features, GC content tables and figures, codon usage bias tables and figures, replication origin prediction, and publication grade figure export.
', unsafe_allow_html=True) - -with st.sidebar: - st.header("Input") - input_mode = st.selectbox( - "Input type", - ["Universal auto detect", "GenBank", "EMBL", "FASTA", "GFF/GTF plus FASTA", "BED plus FASTA", "Annotation table plus FASTA", "ZIP auto detect"], - index=0, - ) - if input_mode in {"GFF/GTF plus FASTA", "BED plus FASTA", "Annotation table plus FASTA"}: - primary_upload = st.file_uploader("Upload annotation file", accept_multiple_files=False) - secondary_upload = st.file_uploader("Upload matching FASTA file", accept_multiple_files=False) - else: - primary_upload = st.file_uploader("Upload genome file or ZIP", accept_multiple_files=False) - secondary_upload = None - - reference_upload = st.file_uploader("Optional reference codon weights for CAI, CSV/TSV with codon and weight columns", accept_multiple_files=False) - - st.header("Analysis settings") - genetic_code_label = st.selectbox("Genetic code table", list(GENETIC_CODE_OPTIONS.keys()), index=0) - palette_name = st.selectbox("Feature colour palette", list(FEATURE_PALETTES.keys()), index=0) - theme_name = st.selectbox("Figure colour theme", list(LINE_THEMES.keys()), index=0) - run_mode = st.radio("Output mode", ["Fast preview", "Publication quality"], index=1) - max_detailed_records = st.number_input("Replicons to render in detail (largest first)", min_value=1, max_value=20, value=4, step=1) - coding_choice = st.selectbox("Coding feature for codon analysis", ["Auto detect", "CDS", "ORF", "gene", "mRNA"], index=0) - min_coding_bp = st.number_input("Minimum coding length for codon analysis, bp", min_value=30, max_value=3000, value=90, step=30) - derive_weights = st.checkbox("Derive codon weights from this genome when no reference is given", value=True) - infer_orfs = st.checkbox("Predict ORFs for FASTA only input", value=False) - min_orf_aa = st.slider("Minimum ORF length, amino acids", 30, 500, 90, 10) - query = st.text_input("Search and highlight feature", value="") - min_feature_length = st.number_input("Minimum feature length to display, bp", min_value=0, max_value=500000, value=0, step=50) - max_features = st.number_input("Maximum displayed features", min_value=100, max_value=100000, value=25000, step=100) - window_size = st.number_input("Window size for GC and skew, bp", min_value=100, max_value=500000, value=1000, step=100) - - run_button = st.button("Run genome analysis", type="primary", use_container_width=True) - clear_button = st.button("Clear results", use_container_width=True) - - st.markdown('
Methods references: Lobry 1996, Grigoriev 1998, Karlin and Burge 1995, ' - 'Gardiner-Garden and Frommer 1987, Sharp and Li 1986 and 1987, Wright 1990, Sueoka 1988 and 1995, ' - 'Kyte and Doolittle 1982.
', unsafe_allow_html=True) - -if clear_button: - reset_state() - st.rerun() - -if run_button: - if primary_upload is None: - st.error("Please upload the required genome file.") - st.stop() - if input_mode in {"GFF/GTF plus FASTA", "BED plus FASTA", "Annotation table plus FASTA"} and secondary_upload is None: - st.error("Please upload both the annotation file and the matching FASTA file.") - st.stop() - with st.spinner("Parsing genome, computing composition and codon metrics, and rendering figures..."): - try: - ctx = build_codon_context(GENETIC_CODE_OPTIONS[genetic_code_label]) - palette = FEATURE_PALETTES[palette_name] - theme = LINE_THEMES[theme_name] - - parsed = parse_input_bundle(primary_upload, secondary_upload, input_mode, infer_orfs, min_orf_aa, ctx) - records = parsed.records - tables = parsed.feature_tables - if not records: - raise ValueError("No sequence records were parsed.") - - main_record = max(records, key=lambda r: len(r.seq)) - feature_df = tables.get(main_record.id, pd.DataFrame()).copy() - available_types = sorted(feature_df["feature_type"].dropna().unique().tolist()) if not feature_df.empty else [] - selected_types = [x for x in DEFAULT_FEATURES if x in available_types] or available_types - filtered_df = filter_features(feature_df, selected_types, query, int(min_feature_length), int(max_features)) - - window_df = window_dataframe(str(main_record.seq), int(window_size)) - origin_terminus = predict_origin_terminus(window_df) - assembly = assembly_statistics(records) - composition = genome_composition(records) - per_record_df = per_record_summary(records, tables) - nuc_counts = nucleotide_counts(str(main_record.seq)) - dinuc_df = dinucleotide_relative_abundance(str(main_record.seq)) - tetra_df = tetranucleotide_frequency(str(main_record.seq)) - - all_cds, coding_type_used = collect_all_coding(records, tables, coding_choice, int(min_coding_bp)) - if all_cds: - parsed.notes.append(f"Codon analysis used {len(all_cds):,} coding sequences taken from feature type {coding_type_used}.") - else: - parsed.notes.append("No coding sequences were collected, so codon usage is zero. Check that the file " - "contains CDS, ORF or gene features, or enable ORF prediction for FASTA only input, " - "or set the coding feature manually in the sidebar.") - - codon_counts = aggregate_codon_counts(all_cds, ctx) - stop_counts = {c: 0 for c in ctx.stop_codons} - for seq in all_cds: - seq = valid_cds_sequence(seq) - for codon in iterate_codons(seq): - if codon in stop_counts: - stop_counts[codon] += 1 - - ref_weights = parse_reference_codon_weights(reference_upload, ctx) - weights = ref_weights if ref_weights else (derive_weights_from_counts(codon_counts, ctx) if derive_weights else None) - codon_df = codon_usage_table(codon_counts, ctx, stop_counts, ref_weights) - optimal_df = optimal_codon_table(codon_df) - per_cds_df = per_cds_metrics(all_cds, ctx, weights, int(min_coding_bp)) - aa_df = amino_acid_usage(all_cds, ctx) - cai_mean = round(float(per_cds_df["CAI"].dropna().mean()), 4) if not per_cds_df.empty and per_cds_df["CAI"].notna().any() else float("nan") - neutrality = neutrality_regression(per_cds_df) - - stats = build_summary_statistics(records, main_record, composition, assembly, origin_terminus, - feature_df, filtered_df, all_cds, codon_df, codon_counts, - ctx, cai_mean, per_cds_df, neutrality) - stats["coding_feature_type_used"] = coding_type_used if all_cds else "none" - stats_df = pd.DataFrame([stats]).T.reset_index() - stats_df.columns = ["parameter", "value"] - - publication = run_mode == "Publication quality" - dpi = 600 if publication else 300 - - linear_fig = draw_linear_map(main_record, filtered_df, selected_types, publication, palette, panel="A") - circular_fig = draw_circular_map(main_record, filtered_df, window_df, selected_types, palette, theme, panel="B") - distribution_fig, dist_df = draw_feature_distribution(feature_df, palette) - gc_fig = draw_gc_profile(window_df, len(main_record.seq), theme) - gc_hist_fig = draw_gc_histogram(window_df, theme) - cumulative_fig = draw_cumulative_skew(window_df, origin_terminus, len(main_record.seq), theme) - composition_fig = draw_composition(nuc_counts, dinuc_df, theme) - rscu_fig = draw_codon_rscu(codon_df, theme) - heatmap_fig = draw_rscu_heatmap(codon_df, ctx, theme["cmap"]) - aa_fig = draw_amino_acid_usage(aa_df, theme) - neutrality_fig = draw_neutrality(per_cds_df, neutrality, theme) - enc_fig = draw_enc_plot(per_cds_df, theme) - pr2_fig = draw_pr2_plot(per_cds_df, theme) - length_fig = draw_feature_length_distribution(per_cds_df, theme) - dashboard_fig = draw_summary_dashboard(window_df, codon_df, per_cds_df, feature_df, theme) - - fig_objects = { - "A_linear_genome_map": linear_fig, - "B_circular_genome_map": circular_fig, - "C_feature_distribution": distribution_fig, - "D_GC_profile": gc_fig, - "E_cumulative_skew": cumulative_fig, - "F_composition": composition_fig, - "G_codon_RSCU": rscu_fig, - "H_RSCU_heatmap": heatmap_fig, - "I_amino_acid_usage": aa_fig, - "J_neutrality_plot": neutrality_fig, - "K_ENC_plot": enc_fig, - "L_PR2_plot": pr2_fig, - "M_CDS_length_distribution": length_fig, - "N_GC_histogram": gc_hist_fig, - "O_overview_dashboard": dashboard_fig, - } - - figures = {} - for name, fig in fig_objects.items(): - figures[f"{name}.png"] = fig_bytes(fig, "png", dpi) - if publication: - figures[f"{name}.svg"] = fig_bytes(fig, "svg") - figures[f"{name}.pdf"] = fig_bytes(fig, "pdf") - for fig in fig_objects.values(): - plt.close(fig) - - # Per record (per replicon) figures for the structure browser - record_order = [r.id for r in sorted(records, key=lambda r: len(r.seq), reverse=True)] - detailed_ids = set(record_order[:int(max_detailed_records)]) - record_figures = render_record_figures( - records, tables, main_record, - {"linear": figures["A_linear_genome_map.png"], - "circular": figures["B_circular_genome_map.png"], - "gc": figures["D_GC_profile.png"]}, - detailed_ids, selected_types, query, min_feature_length, max_features, - window_size, publication, dpi, palette, theme, - ) - detailed_order = [rid for rid in record_order if rid in record_figures] - - summary = manuscript_summary(stats) - tables_for_zip = { - "summary_statistics.csv": stats_df, - "per_record_summary.csv": per_record_df, - "feature_annotations.csv": feature_df, - "displayed_features.csv": filtered_df, - "window_composition.csv": window_df, - "codon_usage_RSCU.csv": codon_df, - "optimal_codons.csv": optimal_df, - "per_cds_metrics.csv": per_cds_df, - "amino_acid_usage.csv": aa_df, - "dinucleotide_relative_abundance.csv": dinuc_df, - "tetranucleotide_frequency.csv": tetra_df, - "feature_distribution.csv": dist_df, - "assembly_statistics.csv": pd.DataFrame([assembly]) if assembly else pd.DataFrame(), - } - bundle = build_bundle(figures, tables_for_zip, summary, METHODS_TEXT) - - st.session_state.update({ - "done": True, - "error": "", - "records": records, - "tables": tables, - "main_record_id": main_record.id, - "stats": stats, - "stats_df": stats_df, - "feature_df": feature_df, - "filtered_df": filtered_df, - "window_df": window_df, - "codon_df": codon_df, - "optimal_df": optimal_df, - "per_cds_df": per_cds_df, - "per_record_df": per_record_df, - "aa_df": aa_df, - "dinuc_df": dinuc_df, - "tetra_df": tetra_df, - "dist_df": dist_df, - "assembly": assembly, - "origin_terminus": origin_terminus, - "neutrality": neutrality, - "summary": summary, - "figures": figures, - "record_figures": record_figures, - "detailed_order": detailed_order, - "bundle": bundle, - "notes": parsed.notes, - "available_types": available_types, - "selected_types": selected_types, - "palette_name": palette_name, - }) - except Exception as exc: - st.session_state["done"] = False - st.session_state["error"] = str(exc) - -if st.session_state.get("error"): - st.error(f"Analysis failed: {st.session_state['error']}") - -if not st.session_state.get("done"): - st.info("Upload a GenBank, EMBL, FASTA, GFF/GTF plus FASTA, BED plus FASTA, annotation table plus FASTA, or ZIP file, then run the analysis.") - st.stop() - -stats = st.session_state["stats"] -figures = st.session_state["figures"] -record_figures = st.session_state["record_figures"] -palette = FEATURE_PALETTES[st.session_state["palette_name"]] - - -def metric_value(key, spec, suffix=""): - value = stats.get(key) - if value is None or (isinstance(value, float) and np.isnan(value)): - return "n/a" - return f"{format(value, spec)}{suffix}" - - -m1, m2, m3, m4, m5, m6 = st.columns(6) -m1.metric("Total length", metric_value("total_genome_length_bp", ",", " bp")) -m2.metric("GC", metric_value("GC_percent", ".2f", "%")) -m3.metric("Records", metric_value("num_records", ",")) -m4.metric("CDS analysed", metric_value("CDS_used_for_codon_analysis", ",")) -m5.metric("ENC genome", metric_value("effective_number_of_codons_ENC_genome", ".2f")) -m6.metric("CAI mean", metric_value("codon_adaptation_index_CAI_mean", ".4f")) - -if st.session_state["notes"]: - st.markdown('
Run notes
' + "
".join(st.session_state["notes"]) + "
", unsafe_allow_html=True) - -st.markdown('
Feature colour legend
' + - feature_legend_html(st.session_state["selected_types"], - bool(st.session_state["filtered_df"].get("highlight", pd.Series(dtype=bool)).any()) if not st.session_state["filtered_df"].empty else False, - palette) + "
", unsafe_allow_html=True) - -tabs = st.tabs(["Overview", "Genome structure", "GC and composition", "Codon usage bias", "Per CDS metrics", "Tables", "Manuscript text", "Downloads"]) - -with tabs[0]: - st.subheader("Genome analysis overview") - st.image(figures["O_overview_dashboard.png"], use_container_width=True) - st.markdown("**Per record summary**") - st.dataframe(st.session_state["per_record_df"], use_container_width=True, height=260) - -with tabs[1]: - st.subheader("Complete genome structure by replicon") - detailed_order = st.session_state["detailed_order"] - if detailed_order: - choice = st.selectbox("Select a record or replicon", detailed_order, index=0) - rf = record_figures.get(choice, {}) - st.caption(f"{choice} | {rf.get('length_bp', 0):,} bp") - struct_tabs = st.tabs(["Linear map", "Circular map", "GC profile", "Feature distribution"]) - with struct_tabs[0]: - st.image(rf["linear"], use_container_width=True) - with struct_tabs[1]: - st.image(rf["circular"], use_container_width=True) - with struct_tabs[2]: - st.image(rf["gc"], use_container_width=True) - with struct_tabs[3]: - st.image(figures["C_feature_distribution.png"], use_container_width=True) - total_records = int(stats.get("num_records", 0)) - if total_records > len(detailed_order): - st.markdown(f'
Showing detailed figures for the {len(detailed_order)} largest of ' - f'{total_records} records. Increase the replicon setting in the sidebar to render more.
', - unsafe_allow_html=True) - else: - st.info("No records available to display.") - -with tabs[2]: - st.subheader("GC content and genome composition") - comp_tabs = st.tabs(["GC profile", "GC histogram", "Cumulative skew", "Composition", "Per record GC", "Window table", "Dinucleotide", "Tetranucleotide"]) - with comp_tabs[0]: - st.image(figures["D_GC_profile.png"], use_container_width=True) - with comp_tabs[1]: - st.image(figures["N_GC_histogram.png"], use_container_width=True) - with comp_tabs[2]: - st.image(figures["E_cumulative_skew.png"], use_container_width=True) - ori = st.session_state["origin_terminus"].get("origin_bp") - ter = st.session_state["origin_terminus"].get("terminus_bp") - st.markdown(f'
Predicted origin near {ori:,} bp and terminus near {ter:,} bp. ' - f'These are predictions from cumulative GC skew and should be confirmed for a final assembly.
' - if ori is not None and ter is not None else '
No origin prediction available.
', - unsafe_allow_html=True) - with comp_tabs[3]: - st.image(figures["F_composition.png"], use_container_width=True) - with comp_tabs[4]: - st.markdown("**GC content and features per record**") - st.dataframe(st.session_state["per_record_df"], use_container_width=True, height=300) - with comp_tabs[5]: - st.dataframe(st.session_state["window_df"], use_container_width=True, height=320) - with comp_tabs[6]: - st.dataframe(st.session_state["dinuc_df"], use_container_width=True, height=320) - with comp_tabs[7]: - st.dataframe(st.session_state["tetra_df"], use_container_width=True, height=320) - -with tabs[3]: - st.subheader("Codon usage and codon usage bias") - codon_tabs = st.tabs(["RSCU bars", "RSCU heatmap", "Amino acid usage", "Neutrality", "ENC plot", "PR2 plot", "Codon table", "Optimal codons"]) - with codon_tabs[0]: - st.image(figures["G_codon_RSCU.png"], use_container_width=True) - with codon_tabs[1]: - st.image(figures["H_RSCU_heatmap.png"], use_container_width=True) - with codon_tabs[2]: - st.image(figures["I_amino_acid_usage.png"], use_container_width=True) - with codon_tabs[3]: - st.image(figures["J_neutrality_plot.png"], use_container_width=True) - n = st.session_state["neutrality"] - st.markdown(f'
Neutrality slope of GC12 on GC3 was {n.get("slope")} with correlation {n.get("r")} ' - f'over {n.get("n")} CDS. A slope near 1 suggests weak selection and a low slope suggests stronger selection on codon usage.
', - unsafe_allow_html=True) - with codon_tabs[4]: - st.image(figures["K_ENC_plot.png"], use_container_width=True) - with codon_tabs[5]: - st.image(figures["L_PR2_plot.png"], use_container_width=True) - with codon_tabs[6]: - st.dataframe(st.session_state["codon_df"], use_container_width=True, height=420) - st.markdown('
ENC ranges from about 20 to 61. Lower values indicate stronger codon usage bias. ' - 'CAI uses the uploaded reference weights, or weights derived from this genome when that option is selected.
', - unsafe_allow_html=True) - with codon_tabs[7]: - st.markdown("**Most used codon in each synonymous family (optimal codons)**") - st.dataframe(st.session_state["optimal_df"], use_container_width=True, height=420) - -with tabs[4]: - st.subheader("Per CDS metrics") - st.image(figures["M_CDS_length_distribution.png"], use_container_width=True) - st.dataframe(st.session_state["per_cds_df"], use_container_width=True, height=380) - -with tabs[5]: - st.subheader("Summary and annotation tables") - st.markdown("**Genome summary parameters**") - st.dataframe(st.session_state["stats_df"], use_container_width=True, height=300) - st.markdown("**Per record summary**") - st.dataframe(st.session_state["per_record_df"], use_container_width=True, height=240) - st.markdown("**Displayed features (longest record)**") - st.dataframe(st.session_state["filtered_df"], use_container_width=True, height=280) - st.markdown("**All parsed features (longest record)**") - st.dataframe(st.session_state["feature_df"], use_container_width=True, height=280) - -with tabs[6]: - st.subheader("Manuscript ready result statement") - st.text_area("Generated result text", value=st.session_state["summary"], height=220) - st.markdown("**Methods paragraph**") - st.text_area("Methods text", value=METHODS_TEXT, height=220) - -with tabs[7]: - st.subheader("Download results") - st.download_button("Download complete results package", data=st.session_state["bundle"], file_name="GenomeScope_Pro_results.zip", mime="application/zip", use_container_width=True) - cols = st.columns(2) - with cols[0]: - st.download_button("Overview figure (PNG)", data=figures["O_overview_dashboard.png"], file_name="O_overview_dashboard.png", mime="image/png") - st.download_button("Linear genome map (PNG)", data=figures["A_linear_genome_map.png"], file_name="A_linear_genome_map.png", mime="image/png") - st.download_button("Circular genome map (PNG)", data=figures["B_circular_genome_map.png"], file_name="B_circular_genome_map.png", mime="image/png") - st.download_button("RSCU heatmap (PNG)", data=figures["H_RSCU_heatmap.png"], file_name="H_RSCU_heatmap.png", mime="image/png") - with cols[1]: - st.download_button("Per record summary (CSV)", data=st.session_state["per_record_df"].to_csv(index=False).encode("utf-8"), file_name="per_record_summary.csv", mime="text/csv") - st.download_button("Codon usage table (CSV)", data=st.session_state["codon_df"].to_csv(index=False).encode("utf-8"), file_name="codon_usage_RSCU.csv", mime="text/csv") - st.download_button("Optimal codons (CSV)", data=st.session_state["optimal_df"].to_csv(index=False).encode("utf-8"), file_name="optimal_codons.csv", mime="text/csv") - st.download_button("Per CDS metrics (CSV)", data=st.session_state["per_cds_df"].to_csv(index=False).encode("utf-8"), file_name="per_cds_metrics.csv", mime="text/csv") - -st.markdown("---") -st.markdown("GenomeScope Pro 2.1 computes sequence composition from the nucleotide sequence and codon statistics from CDS coordinates. " - "The genome structure tab shows linear and circular maps for each replicon, codon usage is pooled across all records, " - "and GC content is reported per record, per window, as a profile, and as a distribution. " - "For FASTA only inputs, feature maps depend on optional ORF prediction and should be read as predicted rather than curated annotation.") \ No newline at end of file