Spaces:
Build error
Build error
Update app.py
Browse files12345678910111213141516171819202122232442 unmodified lines67686970717273609 unmodified lines683684685686687688689690126 unmodified lines817818819820821822102 unmodified lines9259269279289299304 unmodified lines935936937938939940941942943944945281 unmodified lines122712281229123012311232123310 unmodified lines1244124512461247124812491250125112521253125412551256125732 unmodified lines129012911292129312941295129639 unmodified lines133613371338133913401341195 unmodified lines15371538153915401541154259 unmodified lines16021603160416051606160710 unmodified lines16181619162016211622162316243 unmodified lines16281629163016311632163312 unmodified lines1646164716481649165016511652165316 unmodified lines16701671167216731674167542 unmodified lines17181719172017211722172313 unmodified lines1737173817391740174117428 unmodified lines17511752175317541755175617571758175917603 unmodified lines1764176517661767176817699 unmodified lines1779178017811782178317845 unmodified lines179017911792179317941795179617971798179918001801180215 unmodified lines18181819182018211822182318243 unmodified lines18281829183018311832183313 unmodified lines1847184818491850185118527 unmodified lines18601861186218631864186518666 unmodified lines1873187418751876187718781879188018811882188318841885188618871888188918901891189218931 unmodified line18951896189718981899190019011902190319041905190619071908190919101911191215 unmodified lines1928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970"""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."""42 unmodified lines# Page and figure configuration# -----------------------------st.set_page_config(page_title="GenomeScope Pro 2.0",page_icon="🧬",layout="wide",initial_sidebar_state="expanded",609 unmodified linesvalid = 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.0126 unmodified lines}# -----------------------------# Codon and protein analysis# -----------------------------102 unmodified lines"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):4 unmodified lines"frequency_per_1000": 0.0,"RSCU": 0.0,"relative_adaptiveness_w": 0.0,"reference_weight": np.nan,})return 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():281 unmodified lines# -----------------------------# 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 = []10 unmodified linesheight = 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)32 unmodified linesfig = 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 fig39 unmodified linesreturn 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")195 unmodified linesreturn figdef fig_bytes(fig, fmt: str = "png", dpi: int = 600) -> bytes:buffer = io.BytesIO()kwargs = {"bbox_inches": "tight"}59 unmodified lines)# -----------------------------# Session state and Streamlit UI# -----------------------------10 unmodified lines"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(),3 unmodified lines"neutrality": {},"summary": "","figures": {},"bundle": None,"notes": [],"available_types": [],12 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")16 unmodified linespalette_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)42 unmodified linesorigin_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))13 unmodified linesref_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")8 unmodified linespublication = 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)3 unmodified linesenc_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,9 unmodified lines"K_ENC_plot": enc_fig,"L_PR2_plot": pr2_fig,"M_CDS_length_distribution": length_fig,}figures = {}5 unmodified linesfor fig in fig_objects.values():plt.close(fig)summary = manuscript_summary(stats)tables_for_zip = {"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,15 unmodified lines"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,3 unmodified lines"neutrality": neutrality,"summary": summary,"figures": figures,"bundle": bundle,"notes": parsed.notes,"available_types": available_types,13 unmodified linesstats = st.session_state["stats"]figures = st.session_state["figures"]palette = FEATURE_PALETTES[st.session_state["palette_name"]]7 unmodified linesm1, 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"))6 unmodified linesbool(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")1 unmodified linef'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]:15 unmodified linesst.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.")1234567891011121314151617181920212223242542 unmodified lines68697071727374609 unmodified lines684685686687688689126 unmodified lines816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847102 unmodified lines9509519529539549559564 unmodified lines961962963964965966967968969970971972973974975976977978979281 unmodified lines126112621263126412651266126710 unmodified lines1278127912801281128212831284128512861287128812891290129132 unmodified lines132413251326132713281329133039 unmodified lines137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393195 unmodified lines158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164959 unmodified lines1709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175210 unmodified lines1763176417651766176717681769177017713 unmodified lines1775177617771778177917801781178212 unmodified lines1795179617971798179918001801180216 unmodified lines181918201821182218231824182542 unmodified lines186818691870187118721873187413 unmodified lines18881889189018911892189318948 unmodified lines190319041905190619071908190919101911191219133 unmodified lines19171918191919201921192219239 unmodified lines193319341935193619371938193919405 unmodified lines194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197315 unmodified lines1989199019911992199319941995199619973 unmodified lines2001200220032004200520062007200813 unmodified lines20222023202420252026202720287 unmodified lines20362037203820392040204120426 unmodified lines20492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320941 unmodified line20962097209820992100210121022103210421052106210721082109211021112112211321142115211615 unmodified lines2132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180"""GenomeScope Pro 2.1: publication grade genome visualization and genome composition analytics.This version shows the complete genome structure for every replicon (chromosome andplasmids), reports GC content as both tables and figures, reports codon usage bias as bothtables and figures, and adds a set of further genome analyses and figures.Supported inputs:1. GenBank, EMBL, FASTA, GFF3 plus FASTA, BED plus FASTA, CSV/TSV annotation plus FASTA2. ZIP archives containing one of the above supported combinationsMain outputs:1. Linear and circular genome maps for each record, with curated colour palettes for feature classes2. Genome composition: GC content (per record table, window table, profile, histogram),AT content, GC skew, AT skew, cumulative skews, nucleotide and dinucleotide composition,dinucleotide relative abundance, tetranucleotide frequency, CpG observed/expected,Shannon entropy, predicted origin and terminus of replication, and assembly statistics3. Codon usage bias: codon usage table with optimal codon flags, RSCU table and figures,RSCU heatmap, effective number of codons (ENC), codon adaptation index (CAI), amino acidusage, GC at codon positions, GC3s, neutrality plot, ENC plot, and PR2 bias plot4. Per CDS metrics table, per record summary table, a one page overview figure, annotationtables, genome summary tables, and a downloadable figure and data package for a manuscriptReferences for the methods are listed in the sidebar so the output can be cited."""42 unmodified lines# Page and figure configuration# -----------------------------st.set_page_config(page_title="GenomeScope Pro 2.1",page_icon="🧬",layout="wide",initial_sidebar_state="expanded",609 unmodified linesvalid = sum(seq.count(x) for x in "ATGC")if valid == 0:return 0.0g = seq.count("G")c = seq.count("C")return round(64.9 + 41.0 * (g + c - 16.4) / valid, 2) if valid else 0.0126 unmodified lines}def per_record_summary(records, tables) -> pd.DataFrame:"""One row per record (replicon) with sequence and feature level statistics."""rows = []for r in records:seq = str(r.seq)fdf = tables.get(r.id, pd.DataFrame())fc = fdf["feature_type"].value_counts().to_dict() if not fdf.empty else {}coding = int(fdf.loc[fdf["feature_type"].str.lower().eq("cds"), "length"].sum()) if not fdf.empty else 0rows.append({"record_id": r.id,"description": clean_text(getattr(r, "description", ""))[:70],"length_bp": len(seq),"GC_percent": round(compute_gc_percent(seq), 3),"AT_percent": round(compute_at_percent(seq), 3),"GC_skew": round(gc_skew_value(seq), 5),"AT_skew": round(at_skew_value(seq), 5),"CpG_obs_exp": round(cpg_observed_expected(seq), 4),"num_features": int(len(fdf)),"CDS_count": int(fc.get("CDS", 0)),"tRNA_count": int(fc.get("tRNA", 0)),"rRNA_count": int(fc.get("rRNA", 0)),"coding_density_percent": round(100.0 * coding / len(seq), 3) if len(seq) else 0.0,})return pd.DataFrame(rows).sort_values("length_bp", ascending=False).reset_index(drop=True)# -----------------------------# Codon and protein analysis# -----------------------------102 unmodified lines"frequency_per_1000": round(freq_per_thousand, 4),"RSCU": round(rscu, 4),"relative_adaptiveness_w": round(rel_adapt, 4),"optimal_codon": bool(count > 0 and count == max_count and n_syn > 1),"reference_weight": reference_weights.get(codon, np.nan) if reference_weights else np.nan,})for codon in sorted(ctx.stop_codons):4 unmodified lines"frequency_per_1000": 0.0,"RSCU": 0.0,"relative_adaptiveness_w": 0.0,"optimal_codon": False,"reference_weight": np.nan,})return pd.DataFrame(rows)def optimal_codon_table(codon_df: pd.DataFrame) -> pd.DataFrame:if codon_df.empty:return pd.DataFrame(columns=["amino_acid", "codon", "count", "RSCU", "frequency_per_1000"])opt = codon_df[codon_df["optimal_codon"]].copy()return opt[["amino_acid", "codon", "count", "RSCU", "frequency_per_1000"]].sort_values("amino_acid").reset_index(drop=True)def derive_weights_from_counts(counts: Dict[str, int], ctx: CodonContext) -> Dict[str, float]:weights: Dict[str, float] = {}for aa, codons in ctx.aa_to_codons.items():281 unmodified lines# -----------------------------# Figures# -----------------------------def draw_linear_map(record, filtered_df, feature_types, publication, palette, panel="A"):if GraphicFeature is None or GraphicRecord is None:raise RuntimeError("dna_features_viewer is required. Install it with: pip install dna_features_viewer")features = []10 unmodified linesheight = 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(f"{panel}. Linear genome map", loc="left", fontweight="bold")ax.set_xlabel(f"{record.id} | {len(record.seq):,} bp")add_matplotlib_legend(ax, feature_types, bool(filtered_df.get("highlight", pd.Series(dtype=bool)).any()) if not filtered_df.empty else False, palette)plt.tight_layout()return figdef draw_circular_map(record, filtered_df, window_df, feature_types, palette, theme, panel="B"):if Circos is None:raise RuntimeError("pycirclize is required for circular maps. Install it with: pip install pycirclize")seq_len = len(record.seq)32 unmodified linesfig = circos.plotfig()fig.set_size_inches(9.4, 9.4)fig.suptitle(f"{panel}. Circular genome map with GC content, GC skew and AT skew tracks", x=0.06, y=0.99, ha="left", fontweight="bold")return fig39 unmodified linesreturn figdef draw_gc_histogram(window_df, theme):fig, ax = plt.subplots(figsize=(8.5, 4.6))ax.set_title("N. GC content distribution across windows", loc="left", fontweight="bold")if window_df.empty:ax.text(0.5, 0.5, "No sequence windows available", ha="center", va="center")ax.axis("off")else:ax.hist(window_df["GC_percent"], bins=40, color=theme["primary"], edgecolor="#222222", linewidth=0.3)mean_gc = float(window_df["GC_percent"].mean())ax.axvline(mean_gc, color=theme["secondary"], lw=1.6, linestyle="--", label=f"mean GC = {mean_gc:.2f}%")ax.set_xlabel("GC percent per window")ax.set_ylabel("Number of windows")ax.legend(frameon=False, loc="upper right")ax.grid(axis="y", alpha=0.25)plt.tight_layout()return 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")195 unmodified linesreturn figdef draw_summary_dashboard(window_df, codon_df, per_cds, feature_df, theme):fig, axes = plt.subplots(2, 2, figsize=(14, 9))ax = axes[0, 0]ax.set_title("GC content along the genome", loc="left", fontweight="bold")if not window_df.empty:ax.plot(window_df["midpoint"], window_df["GC_percent"], lw=1.4, color=theme["primary"])ax.set_xlabel("Position (bp)")ax.set_ylabel("GC percent")ax.grid(alpha=0.25)else:ax.axis("off")ax = axes[0, 1]ax.set_title("Feature classes", loc="left", fontweight="bold")dist = feature_df["feature_type"].value_counts().head(10) if not feature_df.empty else pd.Series(dtype=int)if not dist.empty:ax.bar(dist.index, dist.values, color=theme["primary"], edgecolor="#222222", linewidth=0.3)ax.tick_params(axis="x", rotation=40)ax.set_ylabel("Count")ax.grid(axis="y", alpha=0.25)else:ax.axis("off")ax = axes[1, 0]ax.set_title("ENC against GC3s", loc="left", fontweight="bold")if not per_cds.empty:ax.scatter(per_cds["GC3s"], per_cds["ENC"], s=10, alpha=0.5, color=theme["primary"], edgecolor="none")xs = np.linspace(0.0, 1.0, 200)ax.plot(xs * 100, enc_expected_curve(xs), color=theme["secondary"], lw=1.5)ax.set_xlim(0, 100)ax.set_ylim(20, 62)ax.set_xlabel("GC3s (%)")ax.set_ylabel("ENC")ax.grid(alpha=0.25)else:ax.axis("off")ax = axes[1, 1]ax.set_title("Relative synonymous codon usage", loc="left", fontweight="bold")sense = codon_df[codon_df["amino_acid"] != "Stop"] if not codon_df.empty else pd.DataFrame()if not sense.empty and sense["count"].sum() > 0:ax.bar(range(len(sense)), sense["RSCU"], color=theme["primary"], linewidth=0)ax.axhline(1.0, color="#444444", lw=0.8, linestyle="--")ax.set_ylabel("RSCU")ax.set_xlabel("Codons")ax.set_xticks([])else:ax.axis("off")fig.suptitle("Genome analysis overview", x=0.02, ha="left", fontweight="bold", fontsize=15)plt.tight_layout(rect=(0, 0, 1, 0.97))return figdef fig_bytes(fig, fmt: str = "png", dpi: int = 600) -> bytes:buffer = io.BytesIO()kwargs = {"bbox_inches": "tight"}59 unmodified lines)# -----------------------------# Per record figure rendering# -----------------------------def render_record_figures(records, tables, main_record, main_figs, detailed_ids, selected_types_main,query, min_feature_length, max_features, window_size, publication, dpi, palette, theme):"""Render linear, circular and GC profile figures for each detailed record.The main record reuses the already computed figures to avoid repeated work."""record_figures = {}record_figures[main_record.id] = {"linear": main_figs["linear"],"circular": main_figs["circular"],"gc": main_figs["gc"],"length_bp": len(main_record.seq),"selected_types": selected_types_main,}for r in records:if r.id == main_record.id or r.id not in detailed_ids:continuefdf = tables.get(r.id, pd.DataFrame()).copy()avail = sorted(fdf["feature_type"].dropna().unique().tolist()) if not fdf.empty else []sel = [x for x in DEFAULT_FEATURES if x in avail] or availfilt = filter_features(fdf, sel, query, int(min_feature_length), int(max_features))wdf = window_dataframe(str(r.seq), int(window_size))lin = draw_linear_map(r, filt, sel, publication, palette, panel="A")circ = draw_circular_map(r, filt, wdf, sel, palette, theme, panel="B")gcp = draw_gc_profile(wdf, len(r.seq), theme)record_figures[r.id] = {"linear": fig_bytes(lin, "png", dpi),"circular": fig_bytes(circ, "png", dpi),"gc": fig_bytes(gcp, "png", dpi),"length_bp": len(r.seq),"selected_types": sel,}for f in (lin, circ, gcp):plt.close(f)return record_figures# -----------------------------# Session state and Streamlit UI# -----------------------------10 unmodified lines"filtered_df": pd.DataFrame(),"window_df": pd.DataFrame(),"codon_df": pd.DataFrame(),"optimal_df": pd.DataFrame(),"per_cds_df": pd.DataFrame(),"per_record_df": pd.DataFrame(),"aa_df": pd.DataFrame(),"dinuc_df": pd.DataFrame(),"tetra_df": pd.DataFrame(),3 unmodified lines"neutrality": {},"summary": "","figures": {},"record_figures": {},"detailed_order": [],"bundle": None,"notes": [],"available_types": [],12 unmodified linesinitialise_state()st.markdown('<div class="main-title">GenomeScope Pro 2.1: Whole Genome Structure, GC Content and Codon Usage Analytics</div>', unsafe_allow_html=True)st.markdown('<div class="sub-title">Per replicon genome maps with all features, GC content tables and figures, codon usage bias tables and figures, replication origin prediction, and publication grade figure export.</div>', unsafe_allow_html=True)with st.sidebar:st.header("Input")16 unmodified linespalette_name = st.selectbox("Feature colour palette", list(FEATURE_PALETTES.keys()), index=0)theme_name = st.selectbox("Figure colour theme", list(LINE_THEMES.keys()), index=0)run_mode = st.radio("Output mode", ["Fast preview", "Publication quality"], index=1)max_detailed_records = st.number_input("Replicons to render in detail (largest first)", min_value=1, max_value=20, value=4, step=1)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)42 unmodified linesorigin_terminus = predict_origin_terminus(window_df)assembly = assembly_statistics(records)composition = genome_composition(records)per_record_df = per_record_summary(records, tables)nuc_counts = nucleotide_counts(str(main_record.seq))dinuc_df = dinucleotide_relative_abundance(str(main_record.seq))tetra_df = tetranucleotide_frequency(str(main_record.seq))13 unmodified linesref_weights = parse_reference_codon_weights(reference_upload, ctx)weights = ref_weights if ref_weights else (derive_weights_from_counts(codon_counts, ctx) if derive_weights else None)codon_df = codon_usage_table(codon_counts, ctx, stop_counts, ref_weights)optimal_df = optimal_codon_table(codon_df)per_cds_df = per_cds_metrics(all_cds, ctx, weights)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")8 unmodified linespublication = run_mode == "Publication quality"dpi = 600 if publication else 300linear_fig = draw_linear_map(main_record, filtered_df, selected_types, publication, palette, panel="A")circular_fig = draw_circular_map(main_record, filtered_df, window_df, selected_types, palette, theme, panel="B")distribution_fig, dist_df = draw_feature_distribution(feature_df, palette)gc_fig = draw_gc_profile(window_df, len(main_record.seq), theme)gc_hist_fig = draw_gc_histogram(window_df, theme)cumulative_fig = draw_cumulative_skew(window_df, origin_terminus, len(main_record.seq), theme)composition_fig = draw_composition(nuc_counts, dinuc_df, theme)rscu_fig = draw_codon_rscu(codon_df, theme)3 unmodified linesenc_fig = draw_enc_plot(per_cds_df, theme)pr2_fig = draw_pr2_plot(per_cds_df, theme)length_fig = draw_feature_length_distribution(per_cds_df, theme)dashboard_fig = draw_summary_dashboard(window_df, codon_df, per_cds_df, feature_df, theme)fig_objects = {"A_linear_genome_map": linear_fig,9 unmodified lines"K_ENC_plot": enc_fig,"L_PR2_plot": pr2_fig,"M_CDS_length_distribution": length_fig,"N_GC_histogram": gc_hist_fig,"O_overview_dashboard": dashboard_fig,}figures = {}5 unmodified linesfor fig in fig_objects.values():plt.close(fig)# Per record (per replicon) figures for the structure browserrecord_order = [r.id for r in sorted(records, key=lambda r: len(r.seq), reverse=True)]detailed_ids = set(record_order[:int(max_detailed_records)])record_figures = render_record_figures(records, tables, main_record,{"linear": figures["A_linear_genome_map.png"],"circular": figures["B_circular_genome_map.png"],"gc": figures["D_GC_profile.png"]},detailed_ids, selected_types, query, min_feature_length, max_features,window_size, publication, dpi, palette, theme,)detailed_order = [rid for rid in record_order if rid in record_figures]summary = manuscript_summary(stats)tables_for_zip = {"summary_statistics.csv": stats_df,"per_record_summary.csv": per_record_df,"feature_annotations.csv": feature_df,"displayed_features.csv": filtered_df,"window_composition.csv": window_df,"codon_usage_RSCU.csv": codon_df,"optimal_codons.csv": optimal_df,"per_cds_metrics.csv": per_cds_df,"amino_acid_usage.csv": aa_df,"dinucleotide_relative_abundance.csv": dinuc_df,15 unmodified lines"filtered_df": filtered_df,"window_df": window_df,"codon_df": codon_df,"optimal_df": optimal_df,"per_cds_df": per_cds_df,"per_record_df": per_record_df,"aa_df": aa_df,"dinuc_df": dinuc_df,"tetra_df": tetra_df,3 unmodified lines"neutrality": neutrality,"summary": summary,"figures": figures,"record_figures": record_figures,"detailed_order": detailed_order,"bundle": bundle,"notes": parsed.notes,"available_types": available_types,13 unmodified linesstats = st.session_state["stats"]figures = st.session_state["figures"]record_figures = st.session_state["record_figures"]palette = FEATURE_PALETTES[st.session_state["palette_name"]]7 unmodified linesm1, m2, m3, m4, m5, m6 = st.columns(6)m1.metric("Total length", metric_value("total_genome_length_bp", ",", " bp"))m2.metric("GC", metric_value("GC_percent", ".2f", "%"))m3.metric("Records", metric_value("num_records", ","))m4.metric("CDS analysed", metric_value("CDS_used_for_codon_analysis", ","))m5.metric("ENC genome", metric_value("effective_number_of_codons_ENC_genome", ".2f"))m6.metric("CAI mean", metric_value("codon_adaptation_index_CAI_mean", ".4f"))6 unmodified linesbool(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(["Overview", "Genome structure", "GC and composition", "Codon usage bias", "Per CDS metrics", "Tables", "Manuscript text", "Downloads"])with tabs[0]:st.subheader("Genome analysis overview")st.image(figures["O_overview_dashboard.png"], use_container_width=True)st.markdown("**Per record summary**")st.dataframe(st.session_state["per_record_df"], use_container_width=True, height=260)with tabs[1]:st.subheader("Complete genome structure by replicon")detailed_order = st.session_state["detailed_order"]if detailed_order:choice = st.selectbox("Select a record or replicon", detailed_order, index=0)rf = record_figures.get(choice, {})st.caption(f"{choice} | {rf.get('length_bp', 0):,} bp")struct_tabs = st.tabs(["Linear map", "Circular map", "GC profile", "Feature distribution"])with struct_tabs[0]:st.image(rf["linear"], use_container_width=True)with struct_tabs[1]:st.image(rf["circular"], use_container_width=True)with struct_tabs[2]:st.image(rf["gc"], use_container_width=True)with struct_tabs[3]:st.image(figures["C_feature_distribution.png"], use_container_width=True)total_records = int(stats.get("num_records", 0))if total_records > len(detailed_order):st.markdown(f'<div class="note">Showing detailed figures for the {len(detailed_order)} largest of 'f'{total_records} records. Increase the replicon setting in the sidebar to render more.</div>',unsafe_allow_html=True)else:st.info("No records available to display.")with tabs[2]:st.subheader("GC content and genome composition")comp_tabs = st.tabs(["GC profile", "GC histogram", "Cumulative skew", "Composition", "Per record GC", "Window table", "Dinucleotide", "Tetranucleotide"])with comp_tabs[0]:st.image(figures["D_GC_profile.png"], use_container_width=True)with comp_tabs[1]:st.image(figures["N_GC_histogram.png"], use_container_width=True)with comp_tabs[2]:st.image(figures["E_cumulative_skew.png"], use_container_width=True)ori = st.session_state["origin_terminus"].get("origin_bp")ter = st.session_state["origin_terminus"].get("terminus_bp")1 unmodified linef'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[3]:st.image(figures["F_composition.png"], use_container_width=True)with comp_tabs[4]:st.markdown("**GC content and features per record**")st.dataframe(st.session_state["per_record_df"], use_container_width=True, height=300)with comp_tabs[5]:st.dataframe(st.session_state["window_df"], use_container_width=True, height=320)with comp_tabs[6]:st.dataframe(st.session_state["dinuc_df"], use_container_width=True, height=320)with comp_tabs[7]:st.dataframe(st.session_state["tetra_df"], use_container_width=True, height=320)with tabs[3]:st.subheader("Codon usage and codon usage bias")codon_tabs = st.tabs(["RSCU bars", "RSCU heatmap", "Amino acid usage", "Neutrality", "ENC plot", "PR2 plot", "Codon table", "Optimal codons"])with codon_tabs[0]:st.image(figures["G_codon_RSCU.png"], use_container_width=True)with codon_tabs[1]:15 unmodified linesst.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 codon_tabs[7]:st.markdown("**Most used codon in each synonymous family (optimal codons)**")st.dataframe(st.session_state["optimal_df"], use_container_width=True, height=420)with tabs[4]:st.subheader("Per CDS metrics")st.image(figures["M_CDS_length_distribution.png"], use_container_width=True)st.dataframe(st.session_state["per_cds_df"], use_container_width=True, height=380)with tabs[5]:st.subheader("Summary and annotation tables")st.markdown("**Genome summary parameters**")st.dataframe(st.session_state["stats_df"], use_container_width=True, height=300)st.markdown("**Per record summary**")st.dataframe(st.session_state["per_record_df"], use_container_width=True, height=240)st.markdown("**Displayed features (longest record)**")st.dataframe(st.session_state["filtered_df"], use_container_width=True, height=280)st.markdown("**All parsed features (longest record)**")st.dataframe(st.session_state["feature_df"], use_container_width=True, height=280)with tabs[6]:st.subheader("Manuscript ready result statement")st.text_area("Generated result text", value=st.session_state["summary"], height=220)st.markdown("**Methods paragraph**")st.text_area("Methods text", value=METHODS_TEXT, height=220)with tabs[7]:st.subheader("Download results")st.download_button("Download complete results package", data=st.session_state["bundle"], file_name="GenomeScope_Pro_results.zip", mime="application/zip", use_container_width=True)cols = st.columns(2)with cols[0]:st.download_button("Overview figure (PNG)", data=figures["O_overview_dashboard.png"], file_name="O_overview_dashboard.png", mime="image/png")st.download_button("Linear genome map (PNG)", data=figures["A_linear_genome_map.png"], file_name="A_linear_genome_map.png", mime="image/png")st.download_button("Circular genome map (PNG)", data=figures["B_circular_genome_map.png"], file_name="B_circular_genome_map.png", mime="image/png")st.download_button("RSCU heatmap (PNG)", data=figures["H_RSCU_heatmap.png"], file_name="H_RSCU_heatmap.png", mime="image/png")with cols[1]:st.download_button("Per record summary (CSV)", data=st.session_state["per_record_df"].to_csv(index=False).encode("utf-8"), file_name="per_record_summary.csv", mime="text/csv")st.download_button("Codon usage table (CSV)", data=st.session_state["codon_df"].to_csv(index=False).encode("utf-8"), file_name="codon_usage_RSCU.csv", mime="text/csv")st.download_button("Optimal codons (CSV)", data=st.session_state["optimal_df"].to_csv(index=False).encode("utf-8"), file_name="optimal_codons.csv", mime="text/csv")st.download_button("Per CDS metrics (CSV)", data=st.session_state["per_cds_df"].to_csv(index=False).encode("utf-8"), file_name="per_cds_metrics.csv", mime="text/csv")st.markdown("---")st.markdown("GenomeScope Pro 2.1 computes sequence composition from the nucleotide sequence and codon statistics from CDS coordinates. ""The genome structure tab shows linear and circular maps for each replicon, codon usage is pooled across all records, ""and GC content is reported per record, per window, as a profile, and as a distribution. ""For FASTA only inputs, feature maps depend on optional ORF prediction and should be read as predicted rather than curated annotation.")
app.py+265-55