Spaces:
Build error
Build error
Delete genome_analytics.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428"""genome_analytics.py
Extension module for GenomeScope Pro. It adds publication oriented genomecomposition and codon usage bias analyses, plus matplotlib figures that use noextra dependencies beyond what the main app already imports.
All metrics are derived from the nucleotide sequence and the parsed CDScoordinates. Nothing is invented. Functions are written to fail soft on emptyinput, returning an empty table or a placeholder figure instead of raising.
Wire-in: see the integration notes provided with this file."""
import reimport mathfrom typing import Dict, List, Optional
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom matplotlib.colors import LinearSegmentedColormapfrom Bio.Data import CodonTable
# ------------------------------------------------------------------# Genetic code (bacterial table 11), kept consistent with the main app# ------------------------------------------------------------------_STANDARD = CodonTable.unambiguous_dna_by_id[11]FORWARD = dict(_STANDARD.forward_table)STOP_CODONS = set(_STANDARD.stop_codons)SENSE_CODONS = sorted(FORWARD.keys())AA_TO_CODONS: Dict[str, List[str]] = {}for _c, _a in FORWARD.items(): AA_TO_CODONS.setdefault(_a, []).append(_c)
DNA_COMPLEMENT = str.maketrans("ACGTNacgtn", "TGCANtgcan")
# A calm, colour-blind friendly palette for the new figuresPALETTE = { "A": "#1b9e77", "T": "#d95f02", "G": "#7570b3", "C": "#e7298a", "N": "#999999", "gc": "#2166ac", "skew": "#b2182b", "line": "#1f4e79", "accent": "#b45f06", "point": "#2166ac", "fit": "#b2182b", "grid": "#d9e6f2", "bg": "#f7fbff",}RSCU_CMAP = LinearSegmentedColormap.from_list("rscu", ["#f7fbff", "#6baed6", "#08306b"])
# ------------------------------------------------------------------# Small local helpers (self contained copies, identical in behaviour)# ------------------------------------------------------------------def valid_cds_sequence(seq: str) -> str: seq = re.sub("[^ATGC]", "", str(seq).upper()) usable = len(seq) - (len(seq) % 3) return seq[:usable]
def reverse_complement(seq: str) -> str: return str(seq).translate(DNA_COMPLEMENT)[::-1]
def extract_feature_sequence(record, row: pd.Series) -> str: start, end = int(row["start"]), int(row["end"]) seq = str(record.seq[start:end]).upper() if int(row.get("strand", 0)) == -1: seq = reverse_complement(seq) return seq
# ------------------------------------------------------------------# Codon level metrics# ------------------------------------------------------------------def codon_counts_from_seq(seq: str) -> Dict[str, int]: seq = valid_cds_sequence(seq) counts: Dict[str, int] = {} for i in range(0, len(seq) - 2, 3): c = seq[i:i + 3] if c in FORWARD: counts[c] = counts.get(c, 0) + 1 return counts
def _enc_combine(f2, f3, f4, f6) -> float: enc = 2.0 enc += 9 / f2 if not np.isnan(f2) else 0 enc += 1 / f3 if not np.isnan(f3) else 0 enc += 5 / f4 if not np.isnan(f4) else 0 enc += 3 / f6 if not np.isnan(f6) else 0 return round(float(min(max(enc, 20.0), 61.0)), 3)
def enc_from_counts(counts: Dict[str, int]) -> float: """Wright effective number of codons from a single gene codon count.""" if not counts or sum(counts.values()) == 0: return np.nan f_by_k: Dict[int, List[float]] = {2: [], 3: [], 4: [], 6: []} for aa, codons in AA_TO_CODONS.items(): k = len(codons) if k == 1: continue c = np.array([counts.get(cod, 0) for cod in codons], dtype=float) n = c.sum() if n <= 1: continue homozygosity = ((c ** 2).sum() - n) / (n * (n - 1)) if k in f_by_k: f_by_k[k].append(max(homozygosity, 1e-9)) mean = lambda v: float(np.mean(v)) if v else np.nan return _enc_combine(*[mean(f_by_k[k]) for k in (2, 3, 4, 6)])
def gc_positions(seq: str): """Return GC fraction at codon positions 1, 2, and 3.""" seq = valid_cds_sequence(seq) n = len(seq) // 3 p1 = seq[0::3][:n]; p2 = seq[1::3][:n]; p3 = seq[2::3][:n] gc = lambda s: (s.count("G") + s.count("C")) / len(s) if s else 0.0 return gc(p1), gc(p2), gc(p3)
def third_position_base_fractions(seq: str): seq = valid_cds_sequence(seq) p3 = seq[2::3][:len(seq) // 3] tot = len(p3) if p3 else 1 return {b: p3.count(b) / tot for b in "ATGC"}
def gene_cai(seq: str, weights: Optional[Dict[str, float]]) -> float: if not weights: return np.nan seq = valid_cds_sequence(seq) logs = [] for i in range(0, len(seq) - 2, 3): c = seq[i:i + 3] if c in FORWARD: logs.append(math.log(max(float(weights.get(c, 0.0)), 1e-8))) return round(float(math.exp(np.mean(logs))), 4) if logs else np.nan
def wright_expected_enc(gc3_fraction): s = np.asarray(gc3_fraction, dtype=float) return 2 + s + 29.0 / (s ** 2 + (1 - s) ** 2)
def derive_genome_weights(codon_df: pd.DataFrame) -> Optional[Dict[str, float]]: """Relative adaptiveness w per codon from the genome wide usage table.""" if codon_df is None or codon_df.empty or "relative_adaptiveness_w" not in codon_df.columns: return None sense = codon_df[codon_df["amino_acid"] != "Stop"] weights = {} for _, r in sense.iterrows(): try: weights[str(r["codon"])] = float(r["relative_adaptiveness_w"]) except Exception: continue return weights or None
# ------------------------------------------------------------------# Per gene and genome composition tables# ------------------------------------------------------------------PER_GENE_COLUMNS = [ "gene", "length_nt", "n_codons", "GC", "GC1", "GC2", "GC3", "GC12", "ENC", "CAI", "A3", "T3", "G3", "C3",]
def per_gene_codon_statistics(record, feature_df: pd.DataFrame, weights: Optional[Dict[str, float]] = None, min_codons: int = 30) -> pd.DataFrame: if feature_df is None or feature_df.empty: return pd.DataFrame(columns=PER_GENE_COLUMNS) cds = feature_df[feature_df["feature_type"].str.lower().eq("cds")] rows = [] for _, r in cds.iterrows(): seq = valid_cds_sequence(extract_feature_sequence(record, r)) if len(seq) // 3 < min_codons: continue counts = codon_counts_from_seq(seq) gc1, gc2, gc3 = gc_positions(seq) gc = (seq.count("G") + seq.count("C")) / len(seq) if seq else 0.0 p3 = third_position_base_fractions(seq) label = str(r.get("label") or r.get("gene") or r.get("locus_tag") or r.get("protein_id") or "CDS") rows.append({ "gene": label[:40], "length_nt": len(seq), "n_codons": len(seq) // 3, "GC": round(gc * 100, 3), "GC1": round(gc1 * 100, 3), "GC2": round(gc2 * 100, 3), "GC3": round(gc3 * 100, 3), "GC12": round((gc1 + gc2) / 2 * 100, 3), "ENC": enc_from_counts(counts), "CAI": gene_cai(seq, weights), "A3": round(p3["A"], 4), "T3": round(p3["T"], 4), "G3": round(p3["G"], 4), "C3": round(p3["C"], 4), }) return pd.DataFrame(rows, columns=PER_GENE_COLUMNS)
def dinucleotide_oe(seq: str) -> pd.DataFrame: seq = "".join(ch for ch in str(seq).upper() if ch in "ATGC") L = len(seq) rows = [] mono = {b: (seq.count(b) / L if L else 0.0) for b in "ATGC"} for b1 in "ATGC": for b2 in "ATGC": d = b1 + b2 obs = seq.count(d) obs_f = obs / (L - 1) if L > 1 else 0.0 exp_f = mono[b1] * mono[b2] ratio = obs_f / exp_f if exp_f > 0 else 0.0 rows.append({"dinucleotide": d, "observed": obs, "obs_freq": round(obs_f, 6), "exp_freq": round(exp_f, 6), "obs_exp_ratio": round(ratio, 4)}) return pd.DataFrame(rows)
def amino_acid_usage(cds_sequences: List[str]) -> pd.DataFrame: counts: Dict[str, int] = {} for seq in cds_sequences: seq = valid_cds_sequence(seq) for i in range(0, len(seq) - 2, 3): aa = FORWARD.get(seq[i:i + 3]) if aa: counts[aa] = counts.get(aa, 0) + 1 total = sum(counts.values()) rows = [{"amino_acid": aa, "count": counts.get(aa, 0), "frequency_percent": round(100.0 * counts.get(aa, 0) / total, 3) if total else 0.0} for aa in sorted(AA_TO_CODONS.keys())] return pd.DataFrame(rows)
def per_record_summary(records, tables: Dict[str, pd.DataFrame]) -> pd.DataFrame: rows = [] for rec in records: seq = str(rec.seq).upper() L = len(seq) g, c, a, t = seq.count("G"), seq.count("C"), seq.count("A"), seq.count("T") valid = a + t + g + c fdf = tables.get(rec.id, pd.DataFrame()) n_cds = int(fdf["feature_type"].str.lower().eq("cds").sum()) if not fdf.empty else 0 rows.append({ "record_id": rec.id, "length_bp": L, "GC_percent": round(100.0 * (g + c) / valid, 3) if valid else 0.0, "AT_percent": round(100.0 * (a + t) / valid, 3) if valid else 0.0, "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, "N_count": seq.count("N"), "features": int(len(fdf)), "CDS": n_cds, }) return pd.DataFrame(rows)
def predict_ori_ter(window_df: pd.DataFrame): """Predict origin and terminus from cumulative GC skew (bacterial heuristic).""" if window_df is None or window_df.empty or "cumulative_GC_skew" not in window_df.columns: return None, None cum = window_df["cumulative_GC_skew"].values mids = window_df["midpoint"].values if len(cum) < 3: return None, None return int(mids[int(np.argmin(cum))]), int(mids[int(np.argmax(cum))])
def neutrality_regression(gc3_fraction, gc12_fraction) -> Dict[str, float]: gc3 = np.asarray(gc3_fraction, dtype=float) gc12 = np.asarray(gc12_fraction, dtype=float) if len(gc3) < 3: return {"slope": np.nan, "intercept": np.nan, "pearson_r": np.nan, "n_genes": int(len(gc3))} slope, intercept = np.polyfit(gc3, gc12, 1) r = float(np.corrcoef(gc3, gc12)[0, 1]) return {"slope": round(float(slope), 4), "intercept": round(float(intercept), 4), "pearson_r": round(r, 4), "n_genes": int(len(gc3))}
# ------------------------------------------------------------------# Figures (matplotlib only)# ------------------------------------------------------------------def _blank(ax, msg): ax.text(0.5, 0.5, msg, ha="center", va="center") ax.axis("off")
def draw_cumulative_skew(window_df, seq_len, ori, ter): fig, ax = plt.subplots(figsize=(10, 4.8)) ax.set_title("F. Cumulative GC skew with predicted origin and terminus", loc="left", fontweight="bold") if window_df is None or window_df.empty: _blank(ax, "No sequence windows available") plt.tight_layout(); return fig ax.plot(window_df["midpoint"], window_df["cumulative_GC_skew"], color=PALETTE["line"], lw=1.8) ax.fill_between(window_df["midpoint"], window_df["cumulative_GC_skew"], 0, color=PALETTE["line"], alpha=0.12) if ori is not None: ax.axvline(ori, color=PALETTE["skew"], ls="--", lw=1.4, label=f"predicted origin ~{ori:,} bp") if ter is not None: ax.axvline(ter, color=PALETTE["accent"], ls="--", lw=1.4, label=f"predicted terminus ~{ter:,} bp") ax.set_xlim(0, seq_len); ax.set_xlabel("Genome position (bp)") ax.set_ylabel("Cumulative GC skew"); ax.grid(alpha=0.25, color=PALETTE["grid"]) ax.legend(frameon=False, loc="best") plt.tight_layout(); return fig
def draw_nucleotide_composition(stats): fig, ax = plt.subplots(figsize=(7.5, 4.8)) ax.set_title("G. Nucleotide composition", loc="left", fontweight="bold") bases = ["A", "T", "G", "C", "N"] vals = [stats.get(b, 0) for b in bases] ax.bar(bases, vals, color=[PALETTE[b] for b in bases], edgecolor="#222222", linewidth=0.4) ax.set_ylabel("Count"); ax.set_xlabel("Base") ax.grid(axis="y", alpha=0.25, color=PALETTE["grid"]) sub = f"GC {stats.get('GC_percent', 0):.1f}% AT {stats.get('AT_percent', 0):.1f}%" ax.text(0.99, 0.97, sub, transform=ax.transAxes, ha="right", va="top", fontsize=9, color=PALETTE["line"]) plt.tight_layout(); return fig
def draw_dinucleotide_oe(dinuc_df): fig, ax = plt.subplots(figsize=(11, 4.6)) ax.set_title("H. Dinucleotide observed / expected ratio", loc="left", fontweight="bold") if dinuc_df is None or dinuc_df.empty: _blank(ax, "No sequence available"); plt.tight_layout(); return fig d = dinuc_df.copy() colors = ["#b2182b" if v < 0.78 else "#2166ac" if v > 1.23 else "#9e9e9e" for v in d["obs_exp_ratio"]] ax.bar(d["dinucleotide"], d["obs_exp_ratio"], color=colors, edgecolor="#222222", linewidth=0.3) ax.axhline(1.0, color="#444444", lw=1.0, ls="--") ax.set_ylabel("Observed / expected"); ax.set_xlabel("Dinucleotide") ax.grid(axis="y", alpha=0.25, color=PALETTE["grid"]) plt.tight_layout(); return fig
def draw_enc_plot(per_gene_df): fig, ax = plt.subplots(figsize=(7.6, 6.0)) ax.set_title("I. ENC plot (Wright)", loc="left", fontweight="bold") if per_gene_df is None or per_gene_df.empty: _blank(ax, "No CDS for codon bias analysis"); plt.tight_layout(); return fig gc3 = per_gene_df["GC3"].values / 100.0 enc = per_gene_df["ENC"].values xs = np.linspace(0.0, 1.0, 200) ax.plot(xs, wright_expected_enc(xs), color=PALETTE["fit"], lw=1.8, label="expected under no selection") ax.scatter(gc3, enc, s=18, color=PALETTE["point"], alpha=0.7, edgecolor="white", linewidth=0.3, label="genes") ax.set_xlim(0, 1); ax.set_ylim(20, 62) ax.set_xlabel("GC3 (fraction)"); ax.set_ylabel("ENC") ax.grid(alpha=0.25, color=PALETTE["grid"]); ax.legend(frameon=False, loc="lower center") plt.tight_layout(); return fig
def draw_neutrality_plot(per_gene_df, nr): fig, ax = plt.subplots(figsize=(7.0, 6.0)) ax.set_title("J. Neutrality plot (GC12 vs GC3)", loc="left", fontweight="bold") if per_gene_df is None or per_gene_df.empty: _blank(ax, "No CDS for codon bias analysis"); plt.tight_layout(); return fig x = per_gene_df["GC3"].values; y = per_gene_df["GC12"].values ax.scatter(x, y, s=18, color=PALETTE["point"], alpha=0.7, edgecolor="white", linewidth=0.3) if nr.get("slope") is not None and not np.isnan(nr.get("slope", np.nan)): xs = np.linspace(min(x), max(x), 50) ax.plot(xs, nr["slope"] * xs + nr["intercept"], color=PALETTE["fit"], lw=1.8, label=f"slope {nr['slope']:.3f}, r {nr['pearson_r']:.3f}") ax.legend(frameon=False, loc="best") ax.set_xlabel("GC3 (%)"); ax.set_ylabel("GC12 (%)") ax.grid(alpha=0.25, color=PALETTE["grid"]) plt.tight_layout(); return fig
def draw_pr2_plot(per_gene_df): fig, ax = plt.subplots(figsize=(6.6, 6.4)) ax.set_title("K. PR2 bias plot (4-fold third position)", loc="left", fontweight="bold") if per_gene_df is None or per_gene_df.empty: _blank(ax, "No CDS for codon bias analysis"); plt.tight_layout(); return fig g3 = per_gene_df["G3"].values; c3 = per_gene_df["C3"].values a3 = per_gene_df["A3"].values; t3 = per_gene_df["T3"].values gc = g3 + c3; at = a3 + t3 x = np.divide(g3, gc, out=np.full_like(g3, 0.5), where=gc > 0) y = np.divide(a3, at, out=np.full_like(a3, 0.5), where=at > 0) ax.scatter(x, y, s=18, color=PALETTE["point"], alpha=0.7, edgecolor="white", linewidth=0.3) ax.axhline(0.5, color="#444444", lw=1.0, ls="--") ax.axvline(0.5, color="#444444", lw=1.0, ls="--") 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, color=PALETTE["grid"]) plt.tight_layout(); return fig
def draw_rscu_heatmap(codon_df): fig, ax = plt.subplots(figsize=(8.4, 6.4)) ax.set_title("L. RSCU heatmap by amino acid", loc="left", fontweight="bold") if codon_df is None or codon_df.empty or codon_df["count"].sum() == 0: _blank(ax, "No CDS codon data available"); plt.tight_layout(); return fig sense = codon_df[codon_df["amino_acid"] != "Stop"].copy() aas = sorted(sense["amino_acid"].unique()) max_syn = max(len(AA_TO_CODONS[a]) for a in aas) mat = np.full((len(aas), max_syn), np.nan) labels = [["" for _ in range(max_syn)] for _ in aas] for i, aa in enumerate(aas): sub = sense[sense["amino_acid"] == aa].sort_values("codon") for j, (_, r) in enumerate(sub.iterrows()): mat[i, j] = r["RSCU"]; labels[i][j] = r["codon"] im = ax.imshow(np.nan_to_num(mat, nan=0.0), aspect="auto", cmap=RSCU_CMAP, vmin=0, vmax=max(2.0, np.nanmax(mat))) ax.set_yticks(range(len(aas))); ax.set_yticklabels(aas) ax.set_xticks(range(max_syn)); ax.set_xticklabels([f"syn {k+1}" for k in range(max_syn)]) for i in range(len(aas)): for j in range(max_syn): if labels[i][j]: ax.text(j, i, labels[i][j], ha="center", va="center", fontsize=7, color="#222222" if mat[i, j] < 1.5 else "white") fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04, label="RSCU") ax.set_xlabel("Synonymous codon slot") plt.tight_layout(); return fig
def draw_aa_usage(aa_df): fig, ax = plt.subplots(figsize=(10, 4.6)) ax.set_title("M. Amino acid usage", loc="left", fontweight="bold") if aa_df is None or aa_df.empty or aa_df["count"].sum() == 0: _blank(ax, "No CDS for amino acid usage"); plt.tight_layout(); return fig d = aa_df.sort_values("frequency_percent", ascending=False) ax.bar(d["amino_acid"], d["frequency_percent"], color=PALETTE["gc"], edgecolor="#222222", linewidth=0.3) ax.set_ylabel("Frequency (%)"); ax.set_xlabel("Amino acid") ax.grid(axis="y", alpha=0.25, color=PALETTE["grid"]) plt.tight_layout(); return fig
def draw_multirecord_overview(per_record_df): fig, ax = plt.subplots(figsize=(8.0, 5.0)) ax.set_title("N. Per record GC versus length", loc="left", fontweight="bold") if per_record_df is None or per_record_df.empty: _blank(ax, "Single record input"); plt.tight_layout(); return fig d = per_record_df sizes = 30 + 170 * (d["length_bp"] / d["length_bp"].max()) ax.scatter(d["length_bp"], d["GC_percent"], s=sizes, color=PALETTE["point"], alpha=0.7, edgecolor="white", linewidth=0.4) ax.set_xlabel("Record length (bp)"); ax.set_ylabel("GC (%)") ax.grid(alpha=0.25, color=PALETTE["grid"]) plt.tight_layout(); return figgenome_analytics.pyDeleted-428