""" codon_bias_extras.py Adds the standard codon usage bias analyses and publication-quality figures that a methodological paper in this area is expected to report: - Per-gene codon indices: GC, GC1, GC2, GC3, GC12, ENc, and third-position base proportions for PR2 analysis. - ENc plot (ENc against GC3 with Wright's expected curve). - Neutrality plot (GC12 against GC3 with regression slope). - PR2 bias plot (A3/(A3+T3) against G3/(G3+C3)). - Amino acid composition table and figure. - Codon usage (RSCU) heatmap. The module uses only numpy, pandas, and matplotlib, so it adds no new dependency to the Space. """ import io import re from collections import Counter, defaultdict import numpy as np import pandas as pd import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt GENETIC_CODE = { "TTT": "F", "TTC": "F", "TTA": "L", "TTG": "L", "TCT": "S", "TCC": "S", "TCA": "S", "TCG": "S", "TAT": "Y", "TAC": "Y", "TAA": "*", "TAG": "*", "TGT": "C", "TGC": "C", "TGA": "*", "TGG": "W", "CTT": "L", "CTC": "L", "CTA": "L", "CTG": "L", "CCT": "P", "CCC": "P", "CCA": "P", "CCG": "P", "CAT": "H", "CAC": "H", "CAA": "Q", "CAG": "Q", "CGT": "R", "CGC": "R", "CGA": "R", "CGG": "R", "ATT": "I", "ATC": "I", "ATA": "I", "ATG": "M", "ACT": "T", "ACC": "T", "ACA": "T", "ACG": "T", "AAT": "N", "AAC": "N", "AAA": "K", "AAG": "K", "AGT": "S", "AGC": "S", "AGA": "R", "AGG": "R", "GTT": "V", "GTC": "V", "GTA": "V", "GTG": "V", "GCT": "A", "GCC": "A", "GCA": "A", "GCG": "A", "GAT": "D", "GAC": "D", "GAA": "E", "GAG": "E", "GGT": "G", "GGC": "G", "GGA": "G", "GGG": "G", } STOP_CODONS = {"TAA", "TAG", "TGA"} AA_NAMES = { "A": "Ala", "R": "Arg", "N": "Asn", "D": "Asp", "C": "Cys", "Q": "Gln", "E": "Glu", "G": "Gly", "H": "His", "I": "Ile", "L": "Leu", "K": "Lys", "M": "Met", "F": "Phe", "P": "Pro", "S": "Ser", "T": "Thr", "W": "Trp", "Y": "Tyr", "V": "Val", } AA_TO_CODONS = defaultdict(list) for _codon, _aa in GENETIC_CODE.items(): if _aa != "*": AA_TO_CODONS[_aa].append(_codon) PALETTE = { "primary": "#2c5f8a", "secondary": "#c45a3b", "accent": "#3b8c6e", "warm": "#d9a23b", "purple": "#7a5ba6", "neutral": "#6b6b6b", "light": "#d9e2ec", } def set_pub_style(): plt.rcParams.update({ "savefig.dpi": 300, "font.family": "sans-serif", "font.sans-serif": ["DejaVu Sans", "Arial", "Helvetica"], "font.size": 11, "axes.titlesize": 13, "axes.titleweight": "bold", "axes.labelsize": 11, "axes.edgecolor": "#444444", "axes.linewidth": 0.9, "axes.spines.top": False, "axes.spines.right": False, "xtick.labelsize": 9.5, "ytick.labelsize": 9.5, "legend.fontsize": 9.5, "legend.frameon": False, "figure.facecolor": "white", "axes.facecolor": "white", }) # ---------------------------------------------------------------------------- # FASTA helper (reads a Prokka .ffn or any nucleotide FASTA) # ---------------------------------------------------------------------------- def read_fasta_pairs(path): """Return list of (id, sequence) from a FASTA file.""" pairs = [] header = None chunks = [] with open(path, "r", encoding="utf-8", errors="ignore") as fh: for line in fh: line = line.rstrip("\n") if not line: continue if line.startswith(">"): if header is not None: pairs.append((header, "".join(chunks).upper())) header = line[1:].split()[0] chunks = [] else: chunks.append(line) if header is not None: pairs.append((header, "".join(chunks).upper())) return pairs # ---------------------------------------------------------------------------- # Per-gene codon indices # ---------------------------------------------------------------------------- def _enc_from_counts(codon_counts): """Wright's effective number of codons from a codon count dict.""" family_F = defaultdict(list) for aa, codons in AA_TO_CODONS.items(): if len(codons) <= 1: continue total = sum(codon_counts.get(c, 0) for c in codons) if total <= 1: continue p2 = sum((codon_counts.get(c, 0) / total) ** 2 for c in codons) F = (total * p2 - 1) / (total - 1) if F > 0: family_F[len(codons)].append(F) def mean_f(k): vals = family_F.get(k, []) return float(np.mean(vals)) if vals else np.nan F2, F3, F4, F6 = mean_f(2), mean_f(3), mean_f(4), mean_f(6) available = [x for x in [F2, F3, F4, F6] if not np.isnan(x) and x > 0] if not available: return np.nan fallback = float(np.mean(available)) F2 = F2 if (not np.isnan(F2) and F2 > 0) else fallback F3 = F3 if (not np.isnan(F3) and F3 > 0) else fallback F4 = F4 if (not np.isnan(F4) and F4 > 0) else fallback F6 = F6 if (not np.isnan(F6) and F6 > 0) else fallback enc = 2 + 9 / F2 + 1 / F3 + 5 / F4 + 3 / F6 return float(min(max(enc, 20), 61)) def per_gene_codon_indices(cds_pairs, input_file, min_codons=100): """Compute per-gene codon indices for ENc, neutrality, and PR2 plots. cds_pairs: list of (gene_id, nucleotide_sequence) Only genes with at least min_codons sense codons are kept, which is the usual practice for stable ENc estimates. """ rows = [] for gene_id, seq in cds_pairs: s = re.sub(r"[^ACGT]", "", seq.upper()) usable = len(s) - (len(s) % 3) if usable < min_codons * 3: continue counts = Counter() g1 = c1 = g2 = c2 = g3 = c3 = a3 = t3 = 0 n_codons = 0 for i in range(0, usable, 3): codon = s[i:i + 3] if codon not in GENETIC_CODE: continue b1, b2, b3 = codon[0], codon[1], codon[2] # position 1 if b1 == "G": g1 += 1 elif b1 == "C": c1 += 1 # position 2 if b2 == "G": g2 += 1 elif b2 == "C": c2 += 1 # position 3 if b3 == "G": g3 += 1 elif b3 == "C": c3 += 1 elif b3 == "A": a3 += 1 elif b3 == "T": t3 += 1 if codon not in STOP_CODONS: counts[codon] += 1 n_codons += 1 if n_codons < min_codons: continue gc1 = 100.0 * (g1 + c1) / n_codons gc2 = 100.0 * (g2 + c2) / n_codons gc3 = 100.0 * (g3 + c3) / n_codons gc12 = (gc1 + gc2) / 2.0 gc_total = 100.0 * (g1 + c1 + g2 + c2 + g3 + c3) / (3 * n_codons) enc = _enc_from_counts(counts) # PR2 coordinates at the third position of four-fold and all sites pr2_x = (g3 / (g3 + c3)) if (g3 + c3) else np.nan # G3/(G3+C3) pr2_y = (a3 / (a3 + t3)) if (a3 + t3) else np.nan # A3/(A3+T3) rows.append({ "input_file": input_file, "gene_id": gene_id, "n_codons": n_codons, "GC_percent": round(gc_total, 3), "GC1_percent": round(gc1, 3), "GC2_percent": round(gc2, 3), "GC3_percent": round(gc3, 3), "GC12_percent": round(gc12, 3), "ENc": round(enc, 3) if not np.isnan(enc) else np.nan, "PR2_G3_ratio": round(pr2_x, 4) if not np.isnan(pr2_x) else np.nan, "PR2_A3_ratio": round(pr2_y, 4) if not np.isnan(pr2_y) else np.nan, }) return pd.DataFrame(rows) # ---------------------------------------------------------------------------- # Figures # ---------------------------------------------------------------------------- def _enc_expected(gc3_fraction): """Wright's expected ENc under no selection for a given GC3 fraction.""" s = gc3_fraction denom = s ** 2 + (1 - s) ** 2 if denom == 0: return 61.0 return 2 + s + 29.0 / denom def fig_enc_plot(per_gene_df, isolate): sub = per_gene_df[per_gene_df["input_file"] == isolate].dropna(subset=["ENc", "GC3_percent"]) if sub.empty: return None fig, ax = plt.subplots(figsize=(7, 5.5)) ax.scatter(sub["GC3_percent"] / 100.0, sub["ENc"], s=14, alpha=0.55, color=PALETTE["primary"], edgecolor="none", label="Genes") xs = np.linspace(0.0, 1.0, 200) ys = [_enc_expected(x) for x in xs] ax.plot(xs, ys, color=PALETTE["secondary"], linewidth=2, label="Expected (no selection)") ax.set_xlim(0, 1) ax.set_ylim(20, 62) ax.set_xlabel("GC3 (fraction)") ax.set_ylabel("ENc") ax.set_title(f"ENc plot: {isolate}") ax.legend() ax.grid(alpha=0.25, linestyle="--") return fig def fig_neutrality_plot(per_gene_df, isolate): sub = per_gene_df[per_gene_df["input_file"] == isolate].dropna(subset=["GC12_percent", "GC3_percent"]) if len(sub) < 3: return None x = sub["GC3_percent"].values / 100.0 y = sub["GC12_percent"].values / 100.0 slope, intercept = np.polyfit(x, y, 1) yhat = slope * x + intercept ss_res = np.sum((y - yhat) ** 2) ss_tot = np.sum((y - np.mean(y)) ** 2) r2 = 1 - ss_res / ss_tot if ss_tot else 0.0 fig, ax = plt.subplots(figsize=(7, 5.5)) ax.scatter(x, y, s=14, alpha=0.55, color=PALETTE["accent"], edgecolor="none", label="Genes") xs = np.linspace(min(x), max(x), 100) ax.plot(xs, slope * xs + intercept, color=PALETTE["secondary"], linewidth=2, label=f"Fit: slope = {slope:.3f}, R2 = {r2:.3f}") ax.set_xlabel("GC3 (fraction)") ax.set_ylabel("GC12 (fraction)") ax.set_title(f"Neutrality plot: {isolate}") ax.legend() ax.grid(alpha=0.25, linestyle="--") return fig, slope, intercept, r2 def fig_pr2_plot(per_gene_df, isolate): sub = per_gene_df[per_gene_df["input_file"] == isolate].dropna(subset=["PR2_G3_ratio", "PR2_A3_ratio"]) if sub.empty: return None fig, ax = plt.subplots(figsize=(6.2, 6)) ax.scatter(sub["PR2_G3_ratio"], sub["PR2_A3_ratio"], s=14, alpha=0.55, color=PALETTE["purple"], edgecolor="none") ax.axhline(0.5, color=PALETTE["neutral"], linewidth=1, linestyle="--") ax.axvline(0.5, color=PALETTE["neutral"], linewidth=1, linestyle="--") ax.set_xlim(0, 1) ax.set_ylim(0, 1) ax.set_xlabel("G3 / (G3 + C3)") ax.set_ylabel("A3 / (A3 + T3)") ax.set_title(f"PR2 bias plot: {isolate}") return fig def amino_acid_composition_from_cds(cds_pairs, input_file): """Translate CDS and count amino acids.""" counts = Counter() total = 0 for _, seq in cds_pairs: s = re.sub(r"[^ACGT]", "", seq.upper()) usable = len(s) - (len(s) % 3) for i in range(0, usable, 3): aa = GENETIC_CODE.get(s[i:i + 3], "X") if aa in AA_NAMES: counts[aa] += 1 total += 1 rows = [] for aa, name in AA_NAMES.items(): c = counts.get(aa, 0) rows.append({ "input_file": input_file, "amino_acid": name, "code": aa, "count": c, "percent": round(100.0 * c / total, 3) if total else 0.0, }) return pd.DataFrame(rows).sort_values("percent", ascending=False).reset_index(drop=True) def fig_amino_acid_composition(aa_df, isolate): sub = aa_df[aa_df["input_file"] == isolate] if sub.empty: return None fig, ax = plt.subplots(figsize=(8, 4.5)) ax.bar(sub["amino_acid"], sub["percent"], color=PALETTE["accent"], edgecolor="white", linewidth=0.6) ax.set_xlabel("Amino acid") ax.set_ylabel("Percent of residues (%)") ax.set_title(f"Amino acid composition: {isolate}") plt.setp(ax.get_xticklabels(), rotation=45, ha="right") return fig def fig_rscu_heatmap(rscu_df, isolate): """Heatmap of RSCU values grouped by amino acid for one isolate.""" sub = rscu_df[rscu_df["input_file"] == isolate].copy() if sub.empty: return None sub = sub.sort_values(["amino_acid", "codon"]) codons = sub["codon"].tolist() values = sub["RSCU"].values.reshape(1, -1) fig, ax = plt.subplots(figsize=(13, 2.4)) im = ax.imshow(values, aspect="auto", cmap="RdBu_r", vmin=0, vmax=2) ax.set_yticks([]) ax.set_xticks(np.arange(len(codons))) ax.set_xticklabels(codons, rotation=90, fontsize=7) ax.set_title(f"RSCU heatmap: {isolate}") cbar = fig.colorbar(im, ax=ax, fraction=0.025, pad=0.01) cbar.set_label("RSCU") return fig