Spaces:
Build error
Build error
Update app.py
Browse files1234567891011121314153 unmodified lines1920212223242526272829303122 unmodified lines545556575859608 unmodified lines69707172737414 unmodified lines89909192939495969798991001011021031041051061071081091101111121135 unmodified lines1191201211221231241251261271281291301 unmodified line13213313413513613713863 unmodified lines20220320420520620721 unmodified lines22923023123223323423523647 unmodified lines2842852862872882892902913 unmodified lines29529629729829930030130230330430530611 unmodified lines31831932032132232332417 unmodified lines34234334434534634734834935035135235311 unmodified lines3653663673683693703713723733743753763773783793803813821 unmodified line38438538638738838939022 unmodified lines41341441541641741841942010 unmodified lines43143243343443543643724 unmodified lines46246346446546646746818 unmodified lines48748848949049149249319 unmodified lines5135145155165175185195201 unmodified line52252352452552652752852953053153253353453553653753853954040 unmodified lines58158258358458558658758858959059159259359459559659759859960060160260360460560660720 unmodified lines6286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686692 unmodified lines6726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197206 unmodified lines7277287297307317327331 unmodified line7357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777789 unmodified lines7887897907917927937947957962 unmodified lines7998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848852 unmodified lines8888898908918928938943 unmodified lines8988999009019029039049059069079089099109119129139149159169179181 unmodified line9209219229239249259269279289299309319329339349359362 unmodified lines9399409419429439444 unmodified lines9499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809813 unmodified lines985986987988989990991992993994995996997998999100010011002100310047 unmodified lines1012101310141015101610171018101912 unmodified lines103210331034103510361037103810391040104110421043104410451046104710485 unmodified lines10541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051 unmodified line11071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611378 unmodified lines114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205"""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 FASTA2. ZIP archives containing one of the above supported combinationsMain outputs:1. Linear and circular genome maps with distinct colours for feature classes2. GC content, GC skew, cumulative GC skew, nucleotide composition, CpG observed/expected3. CDS based codon usage, RSCU, ENC, codon adaptation index when a reference codon table is supplied4. Annotation tables, genome summary tables, and downloadable figure package"""import io3 unmodified linesimport mathimport zipfileimport tempfilefrom dataclasses import dataclassfrom typing import Dict, List, Optional, Tupleimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltfrom matplotlib.lines import Line2Dimport numpy as npimport pandas as pdimport streamlit as st22 unmodified lines# Page and figure configuration# -----------------------------st.set_page_config(page_title="GenomeScope Pro",page_icon="🧬",layout="wide",initial_sidebar_state="expanded",8 unmodified lines"xtick.labelsize": 8,"ytick.labelsize": 8,"legend.fontsize": 8,"figure.dpi": 160,"savefig.dpi": 600,"pdf.fonttype": 42,14 unmodified linesunsafe_allow_html=True,)FEATURE_COLORS = {"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",}FASTA_EXTS = {".fa", ".fasta", ".fna", ".fas", ".ffn"}5 unmodified linesTABLE_EXTS = {".csv", ".tsv", ".txt"}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)@dataclass1 unmodified linerecords: Listfeature_tables: Dict[str, pd.DataFrame]source_mode: strnotes: List[str]# -----------------------------63 unmodified linesreturn clean_text(getattr(feature, "type", "feature"))# -----------------------------# Parsing and annotation handling# -----------------------------21 unmodified lines})except Exception:continuecolumns = ["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):47 unmodified lines"note": "; ".join(attrs.get("Note", [])),"source": "GFF/GTF annotation",})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]]:3 unmodified linesbed = 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 = {}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=columns)continueout = pd.DataFrame({"record_id": record.id,11 unmodified lines"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, tables17 unmodified linesstrand_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)continueout = pd.DataFrame({"record_id": record.id,11 unmodified lines"source": "Annotation table",})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, tablesdef 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 rowsfor frame in range(3):pos = framewhile pos <= len(s) - 3 and len(rows) < max_orfs:1 unmodified lineif codon in starts:stop = pos + 3while stop <= len(s) - 3:if s[stop:stop + 3] in STOP_CODONS:nt_len = stop + 3 - posif nt_len // 3 >= min_aa:if strand == 1:22 unmodified linespos += 3scan(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]:10 unmodified linesreturn filesdef parse_input_bundle(primary_upload, secondary_upload, input_mode: str, infer_orfs: bool, min_orf_aa: int) -> ParsedGenome:notes: List[str] = []if input_mode == "ZIP auto detect":24 unmodified linesreturn 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, 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.")18 unmodified linesif 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, notes), "fasta", notes)if input_mode in {"Universal auto detect", "GFF/GTF plus FASTA"} and kind == "gff":if secondary_upload is None:19 unmodified linesraise ValueError("Unsupported input type or missing paired FASTA 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.")1 unmodified linetables = {}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.idtables[record.id] = dfelse: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()40 unmodified linesreturn (cg * len(seq)) / (c * g)def window_dataframe(sequence: str, window_size: int = 1000) -> pd.DataFrame:seq = str(sequence).upper()rows = []cumulative = 0.0for 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 += skewrows.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()20 unmodified linesreturn seqsdef 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] += 1elif codon in stop_counts:stop_counts[codon] += 1total_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 0for codon in sorted(codons):freq_per_thousand = (counts[codon] / total_sense * 1000.0) if total_sense else 0.0expected = aa_total / n_syn if n_syn else 0rscu = counts[codon] / expected if expected else 0.0rel_adapt = (counts[codon] / max_count) if max_count else 0.0rows.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,2 unmodified linesreturn 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.0f_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:continuecounts = group["count"].astype(float).valuesn = counts.sum()if n <= 1:continuehomozygosity = ((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.nanf2, f3, f4, f6 = [mean_or_nan(f_by_k[k]) for k in [2, 3, 4, 6]]enc = 2enc += 9 / f2 if not np.isnan(f2) else 0enc += 1 / f3 if not np.isnan(f3) else 0enc += 5 / f4 if not np.isnan(f4) else 0enc += 3 / f6 if not np.isnan(f6) else 0return 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.0logs = []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.0def parse_reference_codon_weights(uploaded_ref) -> Optional[Dict[str, float]]:if uploaded_ref is None:return Nonetext = uploaded_ref.getvalue().decode("utf-8", errors="replace")6 unmodified linesweights = {}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:1 unmodified linereturn weights or Nonedef 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 0total_codons = int(codon_df.loc[codon_df["amino_acid"] != "Stop", "count"].sum()) if not codon_df.empty else 0return {"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:9 unmodified linesif 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"] = maskelse:out["highlight"] = False2 unmodified linesreturn 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'<span class="legend-item"><span class="legend-swatch" style="background:{color}"></span>{ft}</span>')if highlight:parts.append(f'<span class="legend-item"><span class="legend-swatch" style="background:{FEATURE_COLORS["highlight"]}"></span>highlighted match</span>')return "".join(parts)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 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 = []label_limit = 160 if publication else 80for _, 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 = clean_text(row.get("label", row["feature_type"])) if len(filtered_df) <= label_limit else Noneif 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.5fig, 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 figdef 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]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():color = FEATURE_COLORS["highlight"] if bool(row.get("highlight", False)) else FEATURE_COLORS.get(row["feature_type"], FEATURE_COLORS["default"])track = reverse if int(row.get("strand", 0)) == -1 else forwardtrack.rect(int(row["start"]), int(row["end"]), fc=color, ec=color, lw=0.1)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)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 figdef 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")2 unmodified linesax.axis("off")else: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")3 unmodified linesreturn fig, distdef draw_gc_profile(window_df: pd.DataFrame, seq_len: int):fig, ax = plt.subplots(figsize=(10, 4.8))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:ax.plot(window_df["midpoint"], window_df["GC_percent"], label="GC percent", lw=1.8)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.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")1 unmodified linereturn figdef 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")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)2 unmodified linesreturn figdef fig_bytes(fig, fmt: str = "png", dpi: int = 600) -> bytes:buffer = io.BytesIO()kwargs = {"bbox_inches": "tight"}4 unmodified linesreturn buffer.getvalue()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(stats: Dict[str, object]) -> str:return (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.")# -----------------------------# Session state and Streamlit UI# -----------------------------3 unmodified lines"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)7 unmodified linesinitialise_state()st.markdown('<div class="main-title">GenomeScope Pro: Whole Genome Visualization and Composition Analytics</div>', unsafe_allow_html=True)st.markdown('<div class="sub-title">A Streamlit tool for annotated genome maps, GC analysis, codon usage, codon bias indices and publication grade image export.</div>', unsafe_allow_html=True)with st.sidebar:st.header("Input")12 unmodified linesreference_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")run_mode = st.radio("Output mode", ["Fast preview", "Publication quality"], index=1)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("GC window size, 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)if clear_button:reset_state()st.rerun()5 unmodified linesif 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, calculating composition metrics and rendering figures..."):try:parsed = parse_input_bundle(primary_upload, secondary_upload, input_mode, infer_orfs, min_orf_aa)records = parsed.recordstables = parsed.feature_tablesif not records:raise ValueError("No sequence records were parsed.")record = records[0]feature_df = tables.get(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_typesfiltered_df = filter_features(feature_df, selected_types, query, int(min_feature_length), int(max_features))window_df = window_dataframe(str(record.seq), int(window_size))cds_sequences = collect_cds_sequences(record, feature_df)ref_weights = parse_reference_codon_weights(reference_upload)codon_df = codon_usage_table(cds_sequences, ref_weights)cai = codon_adaptation_index(cds_sequences, ref_weights)stats = build_summary_statistics(record, feature_df, filtered_df, cds_sequences, codon_df, cai)stats_df = pd.DataFrame([stats])publication = run_mode == "Publication quality"dpi = 600 if publication else 300linear_fig = draw_linear_map(record, filtered_df, selected_types, publication)circular_fig = draw_circular_map(record, filtered_df, window_df, selected_types)distribution_fig, dist_df = draw_feature_distribution(feature_df)gc_fig = draw_gc_profile(window_df, len(record.seq))codon_fig = draw_codon_rscu(codon_df)figures = {"A_linear_genome_map.png": fig_bytes(linear_fig, "png", dpi),"B_circular_genome_map.png": fig_bytes(circular_fig, "png", dpi),"C_feature_distribution.png": fig_bytes(distribution_fig, "png", dpi),"D_GC_profile.png": fig_bytes(gc_fig, "png", dpi),"E_codon_RSCU.png": fig_bytes(codon_fig, "png", dpi),"A_linear_genome_map.svg": fig_bytes(linear_fig, "svg") if publication else None,"B_circular_genome_map.svg": fig_bytes(circular_fig, "svg") if publication else None,"C_feature_distribution.svg": fig_bytes(distribution_fig, "svg") if publication else None,"D_GC_profile.svg": fig_bytes(gc_fig, "svg") if publication else None,"E_codon_RSCU.svg": fig_bytes(codon_fig, "svg") if publication else None,"A_linear_genome_map.pdf": fig_bytes(linear_fig, "pdf") if publication else None,"B_circular_genome_map.pdf": fig_bytes(circular_fig, "pdf") if publication else None,"C_feature_distribution.pdf": fig_bytes(distribution_fig, "pdf") if publication else None,"D_GC_profile.pdf": fig_bytes(gc_fig, "pdf") if publication else None,"E_codon_RSCU.pdf": fig_bytes(codon_fig, "pdf") if publication else None,}for fig in [linear_fig, circular_fig, distribution_fig, gc_fig, codon_fig]:plt.close(fig)summary = manuscript_summary(stats)1 unmodified line"summary_statistics.csv": stats_df,"feature_annotations.csv": feature_df,"displayed_features.csv": filtered_df,"window_GC_statistics.csv": window_df,"codon_usage_RSCU.csv": codon_df,"feature_distribution.csv": dist_df,}bundle = build_bundle(figures, tables_for_zip, summary)st.session_state.update({"done": True,"error": "","records": records,"tables": tables,"record_id": record.id,"stats": stats,"stats_df": stats_df,"feature_df": feature_df,"filtered_df": filtered_df,"window_df": window_df,"codon_df": codon_df,"dist_df": dist_df,"summary": summary,"figures": figures,"bundle": bundle,"notes": parsed.notes,"available_types": available_types,"selected_types": selected_types,})except Exception as exc:st.session_state["done"] = False8 unmodified linesstats = st.session_state["stats"]figures = st.session_state["figures"]m1, m2, m3, m4, m5, m6 = st.columns(6)m1.metric("Genome length", f"{stats['genome_length_bp']:,} bp")m2.metric("GC", f"{stats['GC_percent']:.2f}%")m3.metric("Coding density", f"{stats['coding_density_percent']:.2f}%")m4.metric("CDS", f"{stats['CDS_count']:,}")m5.metric("ENC", f"{stats['effective_number_of_codons_ENC']:.2f}")m6.metric("CAI", f"{stats['codon_adaptation_index_CAI']:.4f}")if st.session_state["notes"]:st.markdown('<div class="box"><b>Run notes</b><br>' + "<br>".join(st.session_state["notes"]) + "</div>", unsafe_allow_html=True)st.markdown('<div class="box"><b>Feature colour legend</b><br>' + 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) + "</div>", unsafe_allow_html=True)tabs = st.tabs(["Genome images", "Genome statistics", "Codon bias", "Annotation table", "Manuscript text", "Downloads"])with tabs[0]:st.subheader("Publication grade genome images")image_tabs = st.tabs(["Linear map", "Circular map", "Feature distribution", "GC profile", "Codon RSCU"])keys = ["A_linear_genome_map.png", "B_circular_genome_map.png", "C_feature_distribution.png", "D_GC_profile.png", "E_codon_RSCU.png"]for tab, key in zip(image_tabs, keys):with tab:st.image(figures[key], use_container_width=True)with tabs[1]:st.subheader("Genome composition and structure")st.dataframe(st.session_state["stats_df"], use_container_width=True, height=180)st.markdown("**Window based GC statistics**")st.dataframe(st.session_state["window_df"], use_container_width=True, height=300)st.markdown("**Feature distribution**")st.dataframe(st.session_state["dist_df"], use_container_width=True, height=250)with tabs[2]:st.subheader("Codon usage and codon bias")st.dataframe(st.session_state["codon_df"], use_container_width=True, height=420)st.markdown('<div class="note">ENC ranges from about 20 to 61. Lower values indicate stronger codon usage bias. CAI is calculated only when a valid reference codon weight table is uploaded.</div>', unsafe_allow_html=True)with tabs[3]:st.subheader("Parsed and displayed annotation")st.markdown("**Displayed features**")st.dataframe(st.session_state["filtered_df"], use_container_width=True, height=350)st.markdown("**All parsed features**")st.dataframe(st.session_state["feature_df"], use_container_width=True, height=350)with tabs[4]:st.subheader("Manuscript ready result statement")st.text_area("Generated text", value=st.session_state["summary"], height=180)with tabs[5]: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)st.download_button("Download linear genome map", data=figures["A_linear_genome_map.png"], file_name="A_linear_genome_map.png", mime="image/png")st.download_button("Download circular genome map", data=figures["B_circular_genome_map.png"], file_name="B_circular_genome_map.png", mime="image/png")st.download_button("Download codon usage table", data=st.session_state["codon_df"].to_csv(index=False).encode("utf-8"), file_name="codon_usage_RSCU.csv", mime="text/csv")st.markdown("---")st.markdown("GenomeScope Pro calculates sequence composition from the nucleotide sequence and codon statistics from CDS coordinates. For FASTA only inputs, feature maps depend on optional ORF prediction and should be interpreted as predicted rather than curated annotation.")12345678910111213141516171819202122232425263 unmodified lines30313233343536373839404142434422 unmodified lines676869707172738 unmodified lines828384858687888914 unmodified lines1041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591605 unmodified lines1661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182191 unmodified line22122222322422522622763 unmodified lines29129229329429529629729829930021 unmodified lines32232332432532632732847 unmodified lines3763773783793803813823 unmodified lines38638738838939039139239339439539611 unmodified lines40840941041141241341417 unmodified lines43243343443543643743843944044144211 unmodified lines4544554564574584594604614624634644654664674684694704711 unmodified line47347447547647747847922 unmodified lines50250350450550650750810 unmodified lines51952052152252352452524 unmodified lines55055155255355455555618 unmodified lines57557657757857958058119 unmodified lines6016026036046056066071 unmodified line60961061161261361461561661761861962062162262362462562662740 unmodified lines66866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482520 unmodified lines8468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369372 unmodified lines940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410856 unmodified lines10921093109410951096109710981 unmodified line1100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911809 unmodified lines1190119111921193119411951196119711982 unmodified lines12011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913002 unmodified lines13031304130513061307130813093 unmodified lines13131314131513161317131813191320132113221323132413251326132713281329133013311332133313341 unmodified line1336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314042 unmodified lines14071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115424 unmodified lines15471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616073 unmodified lines16111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716387 unmodified lines1646164716481649165016511652165312 unmodified lines16661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916905 unmodified lines169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931 unmodified line179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718388 unmodified lines1847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970"""GenomeScope Pro 2.0: publication grade genome visualization and genome composition analytics.This version extends the original tool to support a methodological paper. It adds manygenome parameters, a wider set of publication quality figures, and several analysis tables.Supported inputs:1. GenBank, EMBL, FASTA, GFF3 plus FASTA, BED plus FASTA, CSV/TSV annotation plus FASTA2. ZIP archives containing one of the above supported combinationsMain outputs:1. Linear and circular genome maps with curated colour palettes for feature classes2. Genome composition: GC content, AT content, GC skew, AT skew, cumulative skews,nucleotide and dinucleotide composition, dinucleotide relative abundance (genomicsignature), tetranucleotide frequency, CpG observed/expected, Shannon entropy,predicted origin and terminus of replication, and assembly statistics (N50, L50, N90)3. Codon analysis: codon usage, RSCU, RSCU heatmap, effective number of codons (ENC),codon adaptation index (CAI), amino acid usage, GC at codon positions, GC3s,neutrality plot, ENC plot against Wright expected curve, and PR2 bias plot4. Per CDS metrics table, annotation tables, genome summary tables, and a downloadablefigure and data package suitable for a manuscriptReferences for the methods are listed in the sidebar so the output can be cited."""import io3 unmodified linesimport mathimport zipfileimport tempfilefrom collections import Counterfrom dataclasses import dataclass, fieldfrom typing import Dict, List, Optional, Tupleimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltfrom matplotlib.lines import Line2Dfrom matplotlib.colors import LinearSegmentedColormapimport numpy as npimport pandas as pdimport streamlit as st22 unmodified lines# Page and figure configuration# -----------------------------st.set_page_config(page_title="GenomeScope Pro 2.0",page_icon="🧬",layout="wide",initial_sidebar_state="expanded",8 unmodified lines"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,14 unmodified linesunsafe_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"}5 unmodified linesTABLE_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,}@dataclassclass CodonContext:table_id: intforward_table: Dict[str, str]stop_codons: setsense_codons: List[str]sense_set: setaa_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)@dataclass1 unmodified linerecords: Listfeature_tables: Dict[str, pd.DataFrame]source_mode: strnotes: List[str] = field(default_factory=list)# -----------------------------63 unmodified linesreturn 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# -----------------------------21 unmodified lines})except Exception:continuereturn 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):47 unmodified lines"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]]:3 unmodified linesbed = 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)continueout = pd.DataFrame({"record_id": record.id,11 unmodified lines"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, tables17 unmodified linesstrand_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)continueout = pd.DataFrame({"record_id": record.id,11 unmodified lines"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, tablesdef 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_codonsrows = []def scan(s: str, strand: int):for frame in range(3):pos = framewhile pos <= len(s) - 3 and len(rows) < max_orfs:1 unmodified lineif codon in starts:stop = pos + 3while stop <= len(s) - 3:if s[stop:stop + 3] in stop_codons:nt_len = stop + 3 - posif nt_len // 3 >= min_aa:if strand == 1:22 unmodified linespos += 3scan(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]:10 unmodified linesreturn filesdef 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":24 unmodified linesreturn 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.")18 unmodified linesif 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:19 unmodified linesraise 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.")1 unmodified linetables = {}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.idtables[record.id] = dfelse: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()40 unmodified linesreturn (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.0return -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.0a = seq.count("A")t = seq.count("T")g = seq.count("G")c = seq.count("C")return round(64.9 + 41.0 * (g + c - 16.4) / valid, 2) if valid else 0.0def 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.0exp = mono[x] * mono[y]rho = obs / exp if exp > 0 else 0.0rows.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.0cum_at = 0.0for 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_skewcum_at += at_skewrows.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 theorigin and the global maximum marks the terminus. This is a prediction and should beconfirmed with dedicated tools for a final assembly."""if window_df.empty:return {"origin_bp": None, "terminus_bp": None}cum = window_df["cumulative_GC_skew"].valuesmids = window_df["midpoint"].valuesreturn {"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 * fractionacc = 0for i, length in enumerate(lengths, 1):acc += lengthif acc >= threshold:return length, ireturn 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 = 0for 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.0at = 100.0 * (combined["A"] + combined["T"]) / valid if valid else 0.0g, 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,}# -----------------------------# 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()20 unmodified linesreturn seqsdef 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) + 1return countsdef 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] += nreturn totaldef 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:continuecvals = np.array([counts.get(c, 0) for c in codons], dtype=float)n = cvals.sum()if n <= 1:continuep = cvals / nf = (n * np.sum(p ** 2) - 1) / (n - 1)if f <= 0:continuef_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.0enc = 2.0if f2:enc += 9.0 / f2if f3:enc += 1.0 / f3if f4:enc += 5.0 / f4if f6:enc += 3.0 / f6if 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 0for codon in sorted(codons):count = counts.get(codon, 0)freq_per_thousand = (count / total_sense * 1000.0) if total_sense else 0.0expected = aa_total / n_syn if n_syn else 0rscu = count / expected if expected else 0.0rel_adapt = (count / max_count) if max_count else 0.0rows.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),"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,2 unmodified linesreturn pd.DataFrame(rows)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 0for codon in codons:weights[codon] = (counts.get(codon, 0) / max_count) if max_count else 0.0return weightsdef 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] += 1if base in "GC":gc[j] += 1return 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 = 0tot = 0for codon in iterate_codons(seq):aa = ctx.forward_table.get(codon)if aa is None:continueif len(ctx.aa_to_codons.get(aa, [])) <= 1:continuethird = codon[2]if third in "ACGT":tot += 1if third in "GC":gc += 1return 100.0 * gc / tot if tot else 0.0def 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 = 0for codon in iterate_codons(seq):if (codon[0], codon[1]) in box_set:third = codon[2]if third == "A":a3 += 1elif third == "T":t3 += 1elif third == "G":g3 += 1elif third == "C":c3 += 1gc = g3 + c3at = a3 + t3x = g3 / gc if gc else np.nany = a3 / at if at else np.nanreturn x, y, at + gcdef 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]]) -> pd.DataFrame:rows = []for idx, seq in enumerate(cds_sequences, 1):seq = valid_cds_sequence(seq)if len(seq) < 90:continuecounts = 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 Nonetext = uploaded_ref.getvalue().decode("utf-8", errors="replace")6 unmodified linesweights = {}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:1 unmodified linereturn weights or Nonedef 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).valuesy = per_cds["GC12"].astype(float).valuesmask = 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 0total_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.nanmean_gravy = round(float(per_cds["GRAVY"].dropna().mean()), 4) if not per_cds.empty else np.nanreturn {"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:9 unmodified linesif 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"] = maskelse:out["highlight"] = False2 unmodified linesreturn 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'<span class="legend-item"><span class="legend-swatch" style="background:{color}"></span>{ft}</span>')if highlight:parts.append(f'<span class="legend-item"><span class="legend-swatch" style="background:{palette["highlight"]}"></span>highlighted match</span>')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):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 80for _, 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 Noneif 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.5fig, 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, palette)plt.tight_layout()return figdef draw_circular_map(record, filtered_df, window_df, feature_types, palette, theme):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 forwardtrack.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("B. Circular genome map with GC content, GC skew and AT skew tracks", x=0.06, y=0.99, ha="left", fontweight="bold")return figdef 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")2 unmodified linesax.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")3 unmodified linesreturn fig, distdef 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")1 unmodified linereturn figdef 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 figdef 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 figdef 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)2 unmodified linesreturn figdef 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 figbases = "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 + jfor k, third in enumerate(bases):codon = first + second + thirdmatrix[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 figdef 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 figdef 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 figdef 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 figdef 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 figdef 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 figdef fig_bytes(fig, fmt: str = "png", dpi: int = 600) -> bytes:buffer = io.BytesIO()kwargs = {"bbox_inches": "tight"}4 unmodified linesreturn 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.")# -----------------------------# Session state and Streamlit UI# -----------------------------3 unmodified lines"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(),"per_cds_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": {},"bundle": None,"notes": [],"available_types": [],"selected_types": [],"palette_name": "Default",}for k, v in defaults.items():st.session_state.setdefault(k, v)7 unmodified linesinitialise_state()st.markdown('<div class="main-title">GenomeScope Pro 2.0: Whole Genome Visualization and Composition Analytics</div>', unsafe_allow_html=True)st.markdown('<div class="sub-title">A Streamlit tool for annotated genome maps, GC and skew analysis, codon usage, codon bias indices, replication origin prediction, and publication grade figure export.</div>', unsafe_allow_html=True)with st.sidebar:st.header("Input")12 unmodified linesreference_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)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('<div class="note">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.</div>', unsafe_allow_html=True)if clear_button:reset_state()st.rerun()5 unmodified linesif 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.recordstables = parsed.feature_tablesif 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_typesfiltered_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)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 = []for r in records:all_cds.extend(collect_cds_sequences(r, tables.get(r.id, pd.DataFrame())))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] += 1ref_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)per_cds_df = per_cds_metrics(all_cds, ctx, weights)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_df = pd.DataFrame([stats]).T.reset_index()stats_df.columns = ["parameter", "value"]publication = run_mode == "Publication quality"dpi = 600 if publication else 300linear_fig = draw_linear_map(main_record, filtered_df, selected_types, publication, palette)circular_fig = draw_circular_map(main_record, filtered_df, window_df, selected_types, palette, theme)distribution_fig, dist_df = draw_feature_distribution(feature_df, palette)gc_fig = draw_gc_profile(window_df, len(main_record.seq), 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)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,}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)summary = manuscript_summary(stats)1 unmodified line"summary_statistics.csv": stats_df,"feature_annotations.csv": feature_df,"displayed_features.csv": filtered_df,"window_composition.csv": window_df,"codon_usage_RSCU.csv": codon_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,"per_cds_df": per_cds_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,"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"] = False8 unmodified linesstats = st.session_state["stats"]figures = st.session_state["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("N50", metric_value("N50_bp", ",", " bp"))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('<div class="box"><b>Run notes</b><br>' + "<br>".join(st.session_state["notes"]) + "</div>", unsafe_allow_html=True)st.markdown('<div class="box"><b>Feature colour legend</b><br>' +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) + "</div>", unsafe_allow_html=True)tabs = st.tabs(["Genome maps", "Composition", "Codon bias", "Per CDS metrics", "Annotation table", "Manuscript text", "Downloads"])with tabs[0]:st.subheader("Publication grade genome maps")image_tabs = st.tabs(["Linear map", "Circular map", "Feature distribution"])for tab, key in zip(image_tabs, ["A_linear_genome_map.png", "B_circular_genome_map.png", "C_feature_distribution.png"]):with tab:st.image(figures[key], use_container_width=True)with tabs[1]:st.subheader("Genome composition and structure")comp_tabs = st.tabs(["GC profile", "Cumulative skew", "Composition", "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["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'<div class="note">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.</div>'if ori is not None and ter is not None else '<div class="note">No origin prediction available.</div>',unsafe_allow_html=True)with comp_tabs[2]:st.image(figures["F_composition.png"], use_container_width=True)with comp_tabs[3]:st.dataframe(st.session_state["window_df"], use_container_width=True, height=320)with comp_tabs[4]:st.dataframe(st.session_state["dinuc_df"], use_container_width=True, height=320)with comp_tabs[5]:st.dataframe(st.session_state["tetra_df"], use_container_width=True, height=320)with tabs[2]:st.subheader("Codon usage and codon bias")codon_tabs = st.tabs(["RSCU bars", "RSCU heatmap", "Amino acid usage", "Neutrality", "ENC plot", "PR2 plot", "Codon table"])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'<div class="note">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.</div>',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('<div class="note">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.</div>',unsafe_allow_html=True)with tabs[3]: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[4]:st.subheader("Parsed and displayed annotation")st.markdown("**Genome summary parameters**")st.dataframe(st.session_state["stats_df"], use_container_width=True, height=300)st.markdown("**Displayed features**")st.dataframe(st.session_state["filtered_df"], use_container_width=True, height=300)st.markdown("**All parsed features in the longest record**")st.dataframe(st.session_state["feature_df"], use_container_width=True, height=300)with tabs[5]: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[6]: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("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("Cumulative skew (PNG)", data=figures["E_cumulative_skew.png"], file_name="E_cumulative_skew.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 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.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("Summary parameters (CSV)", data=st.session_state["stats_df"].to_csv(index=False).encode("utf-8"), file_name="summary_statistics.csv", mime="text/csv")st.download_button("Window composition (CSV)", data=st.session_state["window_df"].to_csv(index=False).encode("utf-8"), file_name="window_composition.csv", mime="text/csv")st.markdown("---")st.markdown("GenomeScope Pro 2.0 computes sequence composition from the nucleotide sequence and codon statistics from CDS coordinates. ""Detailed maps and GC profiles use the longest record, while codon analysis pools CDS across all records. ""For FASTA only inputs, feature maps depend on optional ORF prediction and should be read as predicted rather than curated annotation.")
app.py+1034-269