""" genomics_core.py ================ Single source of truth for every metric used by the Genomics Workbench suite. Design rules (these are the reason this module exists): 1. ONE definition per metric. The four tools that were merged into this suite each carried their own copy of GC content, ENC, RSCU, dinucleotide O/E and assembly statistics. Some of those copies disagreed with each other (see `gc_percent` docstring). A suite that reports two different GC values for the same genome is not publishable, so every tool now calls this module. 2. NO hard dependency on Biopython, Streamlit or Gradio. This module needs only numpy / pandas / matplotlib. That keeps the science unit-testable in isolation, and it means a bug here can be reproduced without spinning up a web app. 3. Nothing is invented. Every formula is either computed directly from the input sequence or is a named, citable published method, cited at the point of definition. Where a method is a heuristic rather than a measurement, the docstring says so in those words, and the value is labelled as predicted in the output tables. 4. Fail soft, never fake. Empty or unusable input returns an empty table or a placeholder figure. It never returns a plausible-looking number. """ from __future__ import annotations import math import re from collections import Counter from dataclasses import dataclass, field from typing import Dict, List, Optional, Sequence, Tuple import numpy as np import pandas as pd import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap __all__ = [ "set_publication_style", "PALETTES", "THEMES", "CodonContext", "build_codon_context", "gc_percent", "at_percent", "gc_skew", "at_skew", "nucleotide_counts", "shannon_entropy", "cpg_obs_exp", "dinucleotide_oe", "kmer_frequency", "window_table", "predict_ori_ter", "assembly_statistics", "valid_cds", "reverse_complement", "iter_codons", "codon_counts", "aggregate_codon_counts", "enc_from_counts", "codon_usage_table", "relative_adaptiveness", "cai", "gc_by_codon_position", "gc3s", "pr2_coordinates", "neutrality_regression", "wright_expected_enc", "amino_acid_usage", "translate", "kmer_sketch", "mash_distance", "jaccard_containment", "ani_from_mash", "distance_matrix_from_sketches", "neighbor_joining_newick", "heaps_law_fit", "pangenome_accumulation", ] # ====================================================================== # Figure style. One style for the whole suite so figures from different # tabs can sit next to each other in the same manuscript. # ====================================================================== PALETTES = { "Colourblind safe (Okabe-Ito)": { "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", }, "Classic": { "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", }, } 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"}, } RSCU_CMAP = LinearSegmentedColormap.from_list("rscu", ["#f7fbff", "#6baed6", "#08306b"]) def set_publication_style(base_font: float = 10.0) -> None: """Journal-ready defaults: embedded TrueType fonts, 600 dpi raster export.""" plt.rcParams.update({ "font.family": "sans-serif", "font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans"], "font.size": base_font, "axes.titlesize": base_font + 2.5, "axes.titleweight": "bold", "axes.labelsize": base_font, "axes.edgecolor": "#333333", "axes.linewidth": 0.8, "axes.spines.top": False, "axes.spines.right": False, "axes.grid": True, "grid.color": "#e8e8e8", "grid.linewidth": 0.7, "xtick.labelsize": base_font - 1.5, "ytick.labelsize": base_font - 1.5, "legend.fontsize": base_font - 1.5, "legend.frameon": False, "figure.facecolor": "white", "axes.facecolor": "white", "figure.dpi": 140, "savefig.dpi": 600, # Type 42 keeps text as editable text in PDF/EPS, which most journals # require. Type 3 (the matplotlib default) is frequently rejected. "pdf.fonttype": 42, "ps.fonttype": 42, }) def blank_panel(ax, message: str): ax.text(0.5, 0.5, message, ha="center", va="center", fontsize=10, color="#666666") ax.axis("off") return ax # ====================================================================== # Genetic code # ====================================================================== # NCBI translation table 1 (standard). Table 11 (bacterial) has an identical # forward table and differs only in permitted start codons, which are handled # separately in ORF prediction, so both share this mapping. _TABLE1 = { "TTT": "F", "TTC": "F", "TTA": "L", "TTG": "L", "CTT": "L", "CTC": "L", "CTA": "L", "CTG": "L", "ATT": "I", "ATC": "I", "ATA": "I", "ATG": "M", "GTT": "V", "GTC": "V", "GTA": "V", "GTG": "V", "TCT": "S", "TCC": "S", "TCA": "S", "TCG": "S", "CCT": "P", "CCC": "P", "CCA": "P", "CCG": "P", "ACT": "T", "ACC": "T", "ACA": "T", "ACG": "T", "GCT": "A", "GCC": "A", "GCA": "A", "GCG": "A", "TAT": "Y", "TAC": "Y", "CAT": "H", "CAC": "H", "CAA": "Q", "CAG": "Q", "AAT": "N", "AAC": "N", "AAA": "K", "AAG": "K", "GAT": "D", "GAC": "D", "GAA": "E", "GAG": "E", "TGT": "C", "TGC": "C", "TGG": "W", "CGT": "R", "CGC": "R", "CGA": "R", "CGG": "R", "AGT": "S", "AGC": "S", "AGA": "R", "AGG": "R", "GGT": "G", "GGC": "G", "GGA": "G", "GGG": "G", } _TABLE1_STOPS = {"TAA", "TAG", "TGA"} AA_THREE_LETTER = { "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", } # Kyte & Doolittle (1982) J Mol Biol 157:105-132 KD_HYDROPATHY = { "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 = frozenset("FWY") DNA_COMPLEMENT = str.maketrans("ACGTNacgtn", "TGCANtgcan") GENETIC_CODES = { "11 Bacterial, Archaeal and Plant Plastid": 11, "1 Standard": 1, "2 Vertebrate Mitochondrial": 2, "4 Mold / Protozoan / Coelenterate Mitochondrial": 4, "5 Invertebrate Mitochondrial": 5, "9 Echinoderm and Flatworm Mitochondrial": 9, "23 Thraustochytrium Mitochondrial": 23, } @dataclass(frozen=True) class CodonContext: """Everything downstream codon maths needs, resolved once per run.""" table_id: int forward: Dict[str, str] stops: frozenset sense: Tuple[str, ...] sense_set: frozenset aa_to_codons: Dict[str, Tuple[str, ...]] fourfold_boxes: frozenset start_codons: frozenset source: str = "builtin" def build_codon_context(table_id: int = 11) -> CodonContext: """Build a CodonContext for an NCBI translation table. Biopython is used when it is importable, because it carries every NCBI table. Without Biopython only tables 1 and 11 are available; asking for any other table then raises rather than silently substituting the standard code, which would corrupt every downstream codon statistic without warning. """ forward, stops, starts, source = None, None, None, "builtin" try: from Bio.Data import CodonTable # type: ignore t = CodonTable.unambiguous_dna_by_id[int(table_id)] forward = dict(t.forward_table) stops = frozenset(t.stop_codons) starts = frozenset(t.start_codons) source = "biopython" except ImportError: if int(table_id) not in (1, 11): raise RuntimeError( f"Genetic code table {table_id} requires Biopython. Install " f"biopython, or choose table 1 or 11. Refusing to silently fall " f"back to the standard code, which would corrupt codon results." ) forward = dict(_TABLE1) stops = frozenset(_TABLE1_STOPS) starts = frozenset({"ATG", "GTG", "TTG"} if int(table_id) == 11 else {"ATG"}) except KeyError: raise ValueError(f"Unknown NCBI genetic code table id: {table_id}") aa_to_codons: Dict[str, List[str]] = {} for codon, aa in forward.items(): aa_to_codons.setdefault(aa, []).append(codon) boxes = set() 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.add((first, second)) return CodonContext( table_id=int(table_id), forward=forward, stops=stops, sense=tuple(sorted(forward)), sense_set=frozenset(forward), aa_to_codons={a: tuple(sorted(c)) for a, c in aa_to_codons.items()}, fourfold_boxes=frozenset(boxes), start_codons=frozenset(starts), source=source, ) # ====================================================================== # Sequence composition # ====================================================================== def _upper(seq) -> str: return str(seq).upper() def reverse_complement(seq: str) -> str: return _upper(seq).translate(DNA_COMPLEMENT)[::-1] def nucleotide_counts(seq: str) -> Dict[str, int]: s = _upper(seq) counts = {b: s.count(b) for b in "ATGCN"} counts["other"] = len(s) - sum(counts.values()) return counts def gc_percent(seq: str, include_ambiguous: bool = False) -> float: """GC content as a percentage. IMPORTANT - this resolves a real disagreement between the merged tools. GenomeScope Pro divided G+C by the count of unambiguous ACGT bases, while the Prokka workbench divided G+C by the full sequence length including N. For a gapped draft assembly those two give visibly different answers for the same genome, and both numbers were being written into the same results bundle. This suite standardises on the unambiguous-base denominator (include_ambiguous=False), because Ns are absent information rather than observed AT-rich sequence, and counting them in the denominator drags GC down in proportion to assembly gappiness. N content is reported separately so nothing is hidden. Set include_ambiguous=True only to reproduce a legacy number, and say so in the methods if you do. """ s = _upper(seq) g, c = s.count("G"), s.count("C") denom = len(s) if include_ambiguous else (g + c + s.count("A") + s.count("T")) return 100.0 * (g + c) / denom if denom else 0.0 def at_percent(seq: str, include_ambiguous: bool = False) -> float: s = _upper(seq) a, t = s.count("A"), s.count("T") denom = len(s) if include_ambiguous else (a + t + s.count("G") + s.count("C")) return 100.0 * (a + t) / denom if denom else 0.0 def n_percent(seq: str) -> float: s = _upper(seq) return 100.0 * s.count("N") / len(s) if s else 0.0 def gc_skew(seq: str) -> float: """(G - C) / (G + C). Lobry (1996) Mol Biol Evol 13:660-665.""" s = _upper(seq) g, c = s.count("G"), s.count("C") return (g - c) / (g + c) if (g + c) else 0.0 def at_skew(seq: str) -> float: s = _upper(seq) a, t = s.count("A"), s.count("T") return (a - t) / (a + t) if (a + t) else 0.0 def shannon_entropy(seq: str) -> float: """Shannon entropy over ACGT in bits. Maximum 2.0 for equal base usage.""" s = _upper(seq) counts = [s.count(b) for b in "ACGT"] total = sum(counts) if not total: return 0.0 return -sum((c / total) * math.log2(c / total) for c in counts if c > 0) def cpg_obs_exp(seq: str) -> float: """CpG observed/expected. Gardiner-Garden & Frommer (1987) J Mol Biol 196:261-282.""" s = re.sub("[^ACGT]", "", _upper(seq)) if len(s) < 2: return 0.0 c, g = s.count("C"), s.count("G") if not c or not g: return 0.0 cg = s.count("CG") return (cg * len(s)) / (c * g) def dinucleotide_oe(seq: str) -> pd.DataFrame: """Dinucleotide relative abundance (genomic signature). Karlin & Burge (1995) Trends Genet 11:283-290. rho = f(XY) / (f(X)*f(Y)). Karlin's convention: |rho - 1| > 0.23 is treated as a marked deviation. """ s = re.sub("[^ACGT]", "", _upper(seq)) n = len(s) cols = ["dinucleotide", "observed", "observed_freq", "expected_freq", "rho", "marked_deviation"] if n < 2: return pd.DataFrame(columns=cols) mono = {b: s.count(b) / n for b in "ACGT"} pairs = Counter(s[i:i + 2] for i in range(n - 1)) total = sum(pairs.values()) rows = [] for x in "ACGT": for y in "ACGT": obs = pairs.get(x + y, 0) of = obs / total if total else 0.0 ef = mono[x] * mono[y] rho = of / ef if ef > 0 else 0.0 rows.append({ "dinucleotide": x + y, "observed": obs, "observed_freq": round(of, 6), "expected_freq": round(ef, 6), "rho": round(rho, 4), "marked_deviation": bool(abs(rho - 1.0) > 0.23), }) return pd.DataFrame(rows, columns=cols) def kmer_frequency(seq: str, k: int = 4, top: Optional[int] = None) -> pd.DataFrame: s = re.sub("[^ACGT]", "", _upper(seq)) cols = ["kmer", "count", "frequency_per_1000"] if len(s) < k: return pd.DataFrame(columns=cols) counts = Counter(s[i:i + k] for i in range(len(s) - k + 1)) total = sum(counts.values()) items = counts.most_common(top) if top else sorted(counts.items()) return pd.DataFrame( [{"kmer": km, "count": v, "frequency_per_1000": round(1000.0 * v / total, 4)} for km, v in items], columns=cols) def window_table(seq: str, window: int = 1000, step: Optional[int] = None) -> pd.DataFrame: """Sliding-window composition and cumulative skews. step defaults to `window` (non-overlapping tiles), which is what the cumulative skew needs: overlapping windows would count the same bases repeatedly and inflate the cumulative curve, shifting the predicted origin. """ s = _upper(seq) step = int(step or window) rows, cum_gc, cum_at = [], 0.0, 0.0 for start in range(0, max(1, len(s)), step): end = min(len(s), start + window) if start >= end: break w = s[start:end] gs, as_ = gc_skew(w), at_skew(w) cum_gc += gs cum_at += as_ rows.append({ "start": start, "end": end, "midpoint": (start + end) // 2, "GC_percent": gc_percent(w), "AT_percent": at_percent(w), "GC_skew": gs, "AT_skew": as_, "cumulative_GC_skew": cum_gc, "cumulative_AT_skew": cum_at, "Shannon_entropy_bits": round(shannon_entropy(w), 4), "N_count": w.count("N"), }) if end >= len(s): break return pd.DataFrame(rows) def predict_ori_ter(window_df: pd.DataFrame) -> Dict[str, Optional[int]]: """PREDICT (not measure) replication origin and terminus from cumulative GC skew. In many bacterial genomes the leading strand is G-enriched, so cumulative GC skew falls to a global minimum at the origin and rises to a global maximum at the terminus (Lobry 1996; Grigoriev 1998 Nucleic Acids Res 26:2286-2290). This is a heuristic and it fails predictably: on draft assemblies whose contigs are not ordered, on genomes with recent large inversions, on plasmids, and on any organism without a strong strand asymmetry. The keys are named `predicted_*` for that reason. Confirm with a dedicated tool (e.g. Ori-Finder) before reporting a coordinate in a paper. """ out = {"predicted_origin_bp": None, "predicted_terminus_bp": None, "ori_ter_confidence": "not computed"} if window_df is None or window_df.empty or "cumulative_GC_skew" not in window_df: return out cum = window_df["cumulative_GC_skew"].to_numpy(dtype=float) mids = window_df["midpoint"].to_numpy() if len(cum) < 8: out["ori_ter_confidence"] = "too few windows for a meaningful prediction" return out out["predicted_origin_bp"] = int(mids[int(np.argmin(cum))]) out["predicted_terminus_bp"] = int(mids[int(np.argmax(cum))]) # Amplitude of the cumulative curve relative to its own noise is a crude but # honest indicator of whether a switch point really exists. amp = float(np.max(cum) - np.min(cum)) noise = float(np.std(np.diff(cum))) * math.sqrt(len(cum)) ratio = amp / noise if noise > 0 else 0.0 out["ori_ter_amplitude"] = round(amp, 3) out["ori_ter_signal_to_noise"] = round(ratio, 3) out["ori_ter_confidence"] = ( "clear single switch (typical of a closed bacterial chromosome)" if ratio >= 3.0 else "weak or ambiguous - do not report without independent confirmation" ) return out def assembly_statistics(lengths: Sequence[int], gc_values: Optional[Sequence[float]] = None) -> Dict[str, object]: lengths = sorted([int(x) for x in lengths], reverse=True) if not lengths: return {} total = sum(lengths) def nx_lx(fraction: float) -> Tuple[int, int]: target, acc = total * fraction, 0 for i, L in enumerate(lengths, 1): acc += L if acc >= target: return L, i return lengths[-1], len(lengths) n50, l50 = nx_lx(0.50) n75, l75 = nx_lx(0.75) n90, l90 = nx_lx(0.90) out = { "num_records": len(lengths), "total_length_bp": total, "longest_record_bp": lengths[0], "shortest_record_bp": lengths[-1], "mean_record_length_bp": round(total / len(lengths), 1), "median_record_length_bp": float(np.median(lengths)), "N50_bp": n50, "L50": l50, "N75_bp": n75, "L75": l75, "N90_bp": n90, "L90": l90, "auN": round(float(sum(L * L for L in lengths) / total), 1) if total else 0.0, } if gc_values is not None and len(gc_values): gv = np.asarray(list(gc_values), dtype=float) out.update({ "gc_min_percent": round(float(gv.min()), 3), "gc_max_percent": round(float(gv.max()), 3), "gc_std_percent": round(float(gv.std()), 3), }) return out # ====================================================================== # Codon analysis # ====================================================================== def valid_cds(seq: str) -> str: """Strip ambiguity and truncate to a whole number of codons.""" s = re.sub("[^ATGC]", "", _upper(seq)) return s[:len(s) - (len(s) % 3)] def iter_codons(seq: str): for i in range(0, len(seq) - 2, 3): yield seq[i:i + 3] def codon_counts(seq: str, ctx: CodonContext) -> Dict[str, int]: counts: Dict[str, int] = {} for c in iter_codons(valid_cds(seq)): if c in ctx.sense_set: counts[c] = counts.get(c, 0) + 1 return counts def aggregate_codon_counts(seqs: Sequence[str], ctx: CodonContext) -> Dict[str, int]: total = {c: 0 for c in ctx.sense} for s in seqs: for c, n in codon_counts(s, ctx).items(): total[c] += n return total def stop_codon_counts(seqs: Sequence[str], ctx: CodonContext) -> Dict[str, int]: total = {c: 0 for c in ctx.stops} for s in seqs: for c in iter_codons(valid_cds(s)): if c in total: total[c] += 1 return total def enc_from_counts(counts: Dict[str, int], ctx: CodonContext) -> float: """Effective number of codons. Wright (1990) Gene 87:23-29. Nc = 2 + 9/F2 + 1/F3 + 5/F4 + 3/F6, where Fk is the mean homozygosity of k-fold degenerate synonymous families. Note on the merged code: the two source implementations wrote the family homozygosity differently, as (n*sum(p^2) - 1)/(n - 1) and (sum(c^2) - n)/(n*(n - 1)). Those are algebraically identical (substituting p = c/n reduces one to the other) and were verified numerically to agree to floating point, so consolidating them changes no result. What did differ is the handling of absent families, which is unified here on Wright's own recommendation: if no 3-fold family is observed, F3 is interpolated as the mean of F2 and F4 rather than dropped. Dropping the 1/F3 term (as one source copy did) biases Nc downward by roughly 1-3 units and so overstates codon bias. """ if not counts or sum(counts.values()) == 0: return float("nan") f_by_k: Dict[int, List[float]] = {} for aa, codons in ctx.aa_to_codons.items(): k = len(codons) if k == 1: continue c = np.array([counts.get(x, 0) for x in codons], dtype=float) n = c.sum() if n <= 1: continue p = c / n f = (n * float(np.sum(p ** 2)) - 1.0) / (n - 1.0) if f <= 0: continue f_by_k.setdefault(k, []).append(f) means = {k: float(np.mean(v)) for k, v in f_by_k.items() if v} f2, f3, f4, f6 = means.get(2), means.get(3), means.get(4), means.get(6) if f3 is None and f2 and f4: f3 = (f2 + f4) / 2.0 enc = 2.0 if f2: enc += 9.0 / f2 if f3: enc += 1.0 / f3 if f4: enc += 5.0 / f4 if f6: enc += 3.0 / f6 if enc <= 2.0: return float("nan") return round(float(min(max(enc, 20.0), 61.0)), 3) def wright_expected_enc(gc3s_fraction) -> np.ndarray: """Nc expected under mutation drift alone. Wright (1990), eq. 3. Input is a FRACTION in [0, 1], not a percentage.""" s = np.clip(np.asarray(gc3s_fraction, dtype=float), 1e-6, 1 - 1e-6) return 2 + s + 29.0 / (s ** 2 + (1 - s) ** 2) def relative_adaptiveness(counts: Dict[str, int], ctx: CodonContext) -> Dict[str, float]: """w_i = count_i / max(count in that synonymous family). Sharp & Li (1987).""" w: Dict[str, float] = {} for aa, codons in ctx.aa_to_codons.items(): mx = max((counts.get(c, 0) for c in codons), default=0) for c in codons: w[c] = (counts.get(c, 0) / mx) if mx else 0.0 return w def cai(seq: str, ctx: CodonContext, weights: Optional[Dict[str, float]]) -> float: """Codon Adaptation Index. Sharp & Li (1987) Nucleic Acids Res 15:1281-1295. CAI is the geometric mean of the relative adaptiveness w of each codon. Single-codon families (Met, Trp in the standard code) are excluded because w is 1 by construction and including them dilutes the index. THE REFERENCE SET IS THE WHOLE METHOD. CAI only means "adaptation toward highly expressed genes" if `weights` came from a reference set of highly expressed genes. See `build_cai_weights` for what this suite will and will not let you do. """ if not weights: return float("nan") logs = [] for c in iter_codons(valid_cds(seq)): if c not in ctx.sense_set: continue aa = ctx.forward.get(c) if aa is None or len(ctx.aa_to_codons.get(aa, ())) <= 1: continue logs.append(math.log(max(float(weights.get(c, 0.0)), 1e-8))) return round(float(math.exp(float(np.mean(logs)))), 4) if logs else float("nan") def build_cai_weights( ctx: CodonContext, reference_seqs: Optional[Sequence[str]] = None, all_seqs: Optional[Sequence[str]] = None, uploaded_weights: Optional[Dict[str, float]] = None, ) -> Tuple[Optional[Dict[str, float]], str, str]: """Resolve CAI weights and return (weights, provenance_label, warning). Priority, strictest first: 1. Weights uploaded by the user (a published reference table). 2. Weights from an identified reference set of highly expressed genes (this suite uses ribosomal proteins detected from product names). 3. Weights derived from all genes in the same genome. Option 3 is what the original GenomeScope did by default, and it is circular: the index then measures each gene's similarity to the genome's own average usage, not adaptation toward the translational apparatus. It is still useful as a relative ranking within one genome, but it is NOT comparable across studies and should not be called CAI without qualification in a paper. The returned warning says exactly that, and the provenance label is written into the results table so a reader can always tell which was used. """ if uploaded_weights: return uploaded_weights, "user_supplied_reference_table", "" if reference_seqs: w = relative_adaptiveness(aggregate_codon_counts(reference_seqs, ctx), ctx) return (w, f"ribosomal_protein_reference_set_n={len(reference_seqs)}", "") if all_seqs: w = relative_adaptiveness(aggregate_codon_counts(all_seqs, ctx), ctx) return (w, "self_derived_from_all_genes_CIRCULAR", ( "CAI weights were derived from every gene in this genome because no " "reference set was available. This is self-referential: it ranks genes " "against the genome's own mean codon usage rather than against highly " "expressed genes, and it is not comparable with CAI values from other " "studies. Upload a published reference weight table, or rely on the " "ribosomal-protein reference set, before reporting CAI in a manuscript.")) return None, "unavailable", "No CAI weights could be resolved; CAI is reported as NA." RIBOSOMAL_PRODUCT_RE = re.compile( r"(?:^|\b)(?:30S|50S|40S|60S)\s+ribosomal\s+protein\b|(?:^|\b)ribosomal\s+protein\s+[SL]\d+", re.IGNORECASE, ) def looks_ribosomal(product: str, gene: str = "") -> bool: """Identify ribosomal protein genes for use as a CAI reference set. Ribosomal proteins are the conventional proxy for 'highly expressed' when no expression data exists (they are among the most highly expressed genes in fast-growing bacteria, and are the classic reference set in the CAI literature). Matching is on the annotated product string, plus the rpsX / rplX / rpmX gene-name convention. """ if product and RIBOSOMAL_PRODUCT_RE.search(str(product)): return True g = str(gene or "").strip().lower() return bool(re.fullmatch(r"(?:rps|rpl|rpm)[a-z]\d*", g)) def gc_by_codon_position(seq: str) -> Tuple[float, float, float]: """GC percent at codon positions 1, 2 and 3.""" s = valid_cds(seq) gc = [0, 0, 0] tot = [0, 0, 0] for c in iter_codons(s): for j in range(3): if c[j] in "ACGT": tot[j] += 1 if c[j] in "GC": gc[j] += 1 return tuple(100.0 * gc[j] / tot[j] if tot[j] else 0.0 for j in range(3)) # type: ignore def gc3s(seq: str, ctx: CodonContext) -> float: """GC at synonymous third positions. Distinct from plain GC3: single-codon families (Met, Trp) and any codon whose third position is not free to vary synonymously carry no synonymous information, so they are excluded. Wright's ENC plot expects GC3s, not GC3. """ gc = tot = 0 for c in iter_codons(valid_cds(seq)): aa = ctx.forward.get(c) if aa is None or len(ctx.aa_to_codons.get(aa, ())) <= 1: continue if c[2] in "ACGT": tot += 1 if c[2] in "GC": gc += 1 return 100.0 * gc / tot if tot else 0.0 def pr2_coordinates(seq: str, ctx: CodonContext) -> Tuple[float, float, int]: """PR2 plot coordinates over four-fold degenerate families. Sueoka (1995) J Mol Evol 40:318-325. Returns (G3/(G3+C3), A3/(A3+T3), n).""" a3 = t3 = g3 = c3 = 0 for c in iter_codons(valid_cds(seq)): if (c[0], c[1]) in ctx.fourfold_boxes: if c[2] == "A": a3 += 1 elif c[2] == "T": t3 += 1 elif c[2] == "G": g3 += 1 elif c[2] == "C": c3 += 1 gc, at = g3 + c3, a3 + t3 return (g3 / gc if gc else float("nan"), a3 / at if at else float("nan"), at + gc) def translate(seq: str, ctx: CodonContext, to_first_stop: bool = True) -> str: out = [] for c in iter_codons(valid_cds(seq)): if c in ctx.stops: if to_first_stop: break out.append("*") continue aa = ctx.forward.get(c) if aa: out.append(aa) return "".join(out) def protein_metrics(protein: str) -> Tuple[float, float]: """GRAVY (Kyte & Doolittle 1982) and aromaticity (Lobry & Gautier 1994).""" p = re.sub("[^ACDEFGHIKLMNPQRSTVWY]", "", _upper(protein)) if not p: return float("nan"), float("nan") gravy = sum(KD_HYDROPATHY.get(a, 0.0) for a in p) / len(p) arom = sum(1 for a in p if a in AROMATIC_AA) / len(p) return round(gravy, 4), round(arom, 4) def codon_usage_table( counts: Dict[str, int], ctx: CodonContext, stops: Optional[Dict[str, int]] = None, reference_weights: Optional[Dict[str, float]] = None, ) -> pd.DataFrame: """Genome-wide codon usage with RSCU. Sharp & Li (1986) Nucleic Acids Res 14:7737-7749. RSCU = observed / expected-under-uniform-synonymous-use.""" stops = stops or {c: 0 for c in ctx.stops} total_sense = sum(counts.values()) total_all = total_sense + sum(stops.values()) rows = [] for aa, codons in sorted(ctx.aa_to_codons.items()): aa_total = sum(counts.get(c, 0) for c in codons) k = len(codons) mx = max((counts.get(c, 0) for c in codons), default=0) for c in sorted(codons): n = counts.get(c, 0) exp = aa_total / k if k else 0 rows.append({ "amino_acid_1": aa, "amino_acid_3": AA_THREE_LETTER.get(aa, aa), "codon": c, "count": n, "frequency_per_1000": round(1000.0 * n / total_all, 4) if total_all else 0.0, "fraction_within_aa": round(n / aa_total, 4) if aa_total else 0.0, "RSCU": round(n / exp, 4) if exp else 0.0, "relative_adaptiveness_w": round(n / mx, 4) if mx else 0.0, "synonymous_family_size": k, "is_most_used_in_family": bool(n > 0 and n == mx and k > 1), "reference_weight": (reference_weights or {}).get(c, np.nan), }) for c in sorted(ctx.stops): n = stops.get(c, 0) rows.append({ "amino_acid_1": "*", "amino_acid_3": "Stop", "codon": c, "count": n, "frequency_per_1000": round(1000.0 * n / total_all, 4) if total_all else 0.0, "fraction_within_aa": round(n / sum(stops.values()), 4) if sum(stops.values()) else 0.0, "RSCU": np.nan, "relative_adaptiveness_w": np.nan, "synonymous_family_size": len(ctx.stops), "is_most_used_in_family": False, "reference_weight": np.nan, }) return pd.DataFrame(rows) def amino_acid_usage(seqs: Sequence[str], ctx: CodonContext) -> pd.DataFrame: counter: Counter = Counter() for s in seqs: counter.update(translate(s, ctx)) total = sum(counter.values()) rows = [{"amino_acid_1": aa, "amino_acid_3": AA_THREE_LETTER.get(aa, 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 sorted(AA_THREE_LETTER)] return pd.DataFrame(rows) def neutrality_regression(gc3: Sequence[float], gc12: Sequence[float]) -> Dict[str, float]: """GC12 on GC3 regression. Sueoka (1988) PNAS 85:2653-2657. Slope near 1 implies GC3 variation is mirrored at GC12, i.e. mutation pressure dominates. Slope near 0 implies GC12 is constrained while GC3 is free, i.e. selection dominates codon usage. """ x = np.asarray(gc3, dtype=float) y = np.asarray(gc12, dtype=float) m = np.isfinite(x) & np.isfinite(y) x, y = x[m], y[m] out = {"slope": np.nan, "intercept": np.nan, "pearson_r": np.nan, "r_squared": np.nan, "n_genes": int(x.size)} if x.size < 3 or np.allclose(x, x[0]): return out slope, intercept = np.polyfit(x, y, 1) r = float(np.corrcoef(x, y)[0, 1]) out.update({"slope": round(float(slope), 4), "intercept": round(float(intercept), 4), "pearson_r": round(r, 4), "r_squared": round(r * r, 4)}) return out def per_gene_codon_table( seqs: Sequence[str], ctx: CodonContext, weights: Optional[Dict[str, float]] = None, labels: Optional[Sequence[str]] = None, min_codons: int = 30, ) -> pd.DataFrame: cols = ["gene", "length_bp", "n_codons", "GC_percent", "GC1", "GC2", "GC3", "GC12", "GC3s", "ENC", "CAI", "GRAVY", "aromaticity", "PR2_G3_over_GC3", "PR2_A3_over_AT3", "PR2_n_fourfold_codons"] rows = [] for i, s in enumerate(seqs): cds = valid_cds(s) if len(cds) // 3 < min_codons: continue g1, g2, g3 = gc_by_codon_position(cds) x, y, npr2 = pr2_coordinates(cds, ctx) prot = translate(cds, ctx) gravy, arom = protein_metrics(prot) rows.append({ "gene": (labels[i] if labels and i < len(labels) else f"seq_{i+1}"), "length_bp": len(cds), "n_codons": len(cds) // 3, "GC_percent": round(gc_percent(cds), 3), "GC1": round(g1, 3), "GC2": round(g2, 3), "GC3": round(g3, 3), "GC12": round((g1 + g2) / 2.0, 3), "GC3s": round(gc3s(cds, ctx), 3), "ENC": enc_from_counts(codon_counts(cds, ctx), ctx), "CAI": cai(cds, ctx, weights), "GRAVY": gravy, "aromaticity": arom, "PR2_G3_over_GC3": round(x, 4) if np.isfinite(x) else np.nan, "PR2_A3_over_AT3": round(y, 4) if np.isfinite(y) else np.nan, "PR2_n_fourfold_codons": npr2, }) return pd.DataFrame(rows, columns=cols) # ====================================================================== # EXPANSION 1: alignment-free genome distance (k-mer / MinHash) # ---------------------------------------------------------------------- # The comparative tool in the original suite ran a full Needleman-Wunsch # global alignment for every genome pair. That is O(n*m) in both time and # memory: two 5 Mb chromosomes need a ~25 Tcell matrix and will exhaust RAM # long before finishing. Alignment-free sketching is the standard answer and # makes whole-genome comparison tractable in seconds. # ====================================================================== def _hash64(s: str) -> int: # FNV-1a, 64-bit. Deterministic across runs and platforms, unlike Python's # salted built-in hash(), so sketches are reproducible and cacheable. h = 0xcbf29ce484222325 for ch in s.encode("ascii", "ignore"): h ^= ch h = (h * 0x100000001b3) & 0xFFFFFFFFFFFFFFFF return h def _canonical(kmer: str) -> str: rc = kmer.translate(DNA_COMPLEMENT)[::-1] return kmer if kmer <= rc else rc def kmer_sketch(seq: str, k: int = 21, sketch_size: int = 2000) -> Tuple[frozenset, int]: """Bottom-s MinHash sketch of canonical k-mers (Mash; Ondov et al. 2016, Genome Biol 17:132). Canonical k-mers make the sketch strand-independent. k=21 is Mash's default for bacterial genomes: long enough that random matches are negligible at ~5 Mb, short enough to stay sensitive at ~95% identity. Returns (sketch, n_distinct_kmers_seen). """ s = re.sub("[^ACGT]", "", _upper(seq)) if len(s) < k: return frozenset(), 0 seen = set() for i in range(len(s) - k + 1): seen.add(_hash64(_canonical(s[i:i + k]))) return frozenset(sorted(seen)[:sketch_size]), len(seen) def jaccard_containment(a: frozenset, b: frozenset) -> float: if not a or not b: return 0.0 union = a | b # Bottom-s estimator: restrict to the s smallest hashes of the union. s = min(len(a), len(b)) bottom = set(sorted(union)[:s]) if not bottom: return 0.0 return len(bottom & a & b) / len(bottom) def mash_distance(j: float, k: int = 21) -> float: """Mash distance from a Jaccard estimate. D = -(1/k) * ln(2j / (1 + j)). Ondov et al. (2016). This approximates the per-base mutation rate.""" if j <= 0: return 1.0 if j >= 1: return 0.0 return max(0.0, -(1.0 / k) * math.log(2 * j / (1 + j))) def ani_from_mash(d: float) -> float: """Approximate ANI (%) from Mash distance. ANI ~ (1 - D) * 100. APPROXIMATE, and the approximation degrades below roughly 90% ANI where the Poisson model underlying Mash breaks down. For a published ANI value use FastANI or a BLAST-based ANI; use this to triage which pairs are worth the expensive computation. """ return round(100.0 * (1.0 - d), 3) def distance_matrix_from_sketches( sketches: Dict[str, frozenset], k: int = 21 ) -> Tuple[pd.DataFrame, pd.DataFrame]: """Return (mash_distance_df, approx_ani_df) for all pairs.""" names = list(sketches) n = len(names) dm = np.zeros((n, n), dtype=float) am = np.full((n, n), 100.0, dtype=float) for i in range(n): for j in range(i + 1, n): jac = jaccard_containment(sketches[names[i]], sketches[names[j]]) d = mash_distance(jac, k) dm[i, j] = dm[j, i] = d am[i, j] = am[j, i] = ani_from_mash(d) return (pd.DataFrame(dm, index=names, columns=names), pd.DataFrame(am, index=names, columns=names)) # ====================================================================== # EXPANSION 2: neighbour-joining tree from any distance matrix # ====================================================================== def neighbor_joining_newick(dist_df: pd.DataFrame) -> str: """Neighbour-joining tree. Saitou & Nei (1987) Mol Biol Evol 4:406-425. Returns a Newick string. Included so a distance matrix can be turned into a figure-ready tree without adding a phylogenetics dependency. For a publication-grade phylogeny with support values, export the distance matrix or the core-gene alignment and use RAxML-NG / IQ-TREE instead: NJ gives a single point estimate with no branch support. """ names = list(dist_df.index) if len(names) < 2: return "();" if len(names) == 2: d = float(dist_df.iloc[0, 1]) / 2.0 return f"({names[0]}:{d:.6f},{names[1]}:{d:.6f});" nodes = list(names) D = dist_df.to_numpy(dtype=float).copy() labels = {i: names[i] for i in range(len(names))} active = list(range(len(names))) while len(active) > 2: m = len(active) sub = D[np.ix_(active, active)] r = sub.sum(axis=1) Q = np.full((m, m), np.inf) for a in range(m): for b in range(a + 1, m): Q[a, b] = Q[b, a] = (m - 2) * sub[a, b] - r[a] - r[b] a, b = np.unravel_index(np.argmin(Q), Q.shape) if a > b: a, b = b, a i, j = active[a], active[b] dij = sub[a, b] li = 0.5 * dij + (r[a] - r[b]) / (2 * (m - 2)) if m > 2 else dij / 2 lj = dij - li li, lj = max(li, 0.0), max(lj, 0.0) new_label = f"({labels[i]}:{li:.6f},{labels[j]}:{lj:.6f})" # Grow the matrix by one row/col for the merged node. size = D.shape[0] newD = np.zeros((size + 1, size + 1)) newD[:size, :size] = D for x in active: if x in (i, j): continue newD[size, x] = newD[x, size] = 0.5 * (D[i, x] + D[j, x] - dij) D = newD labels[size] = new_label active = [x for x in active if x not in (i, j)] + [size] i, j = active d = max(D[i, j], 0.0) return f"({labels[i]}:{d/2:.6f},{labels[j]}:{d/2:.6f});" # ====================================================================== # EXPANSION 3: pan-genome openness (Heaps' law) and accumulation curves # ====================================================================== def pangenome_accumulation(presence: np.ndarray, permutations: int = 100, seed: int = 0) -> pd.DataFrame: """Pan- and core-genome accumulation curves by random genome sampling. `presence` is a clusters x genomes 0/1 matrix. For each subsample size the curve is averaged over `permutations` random genome orders, which is the standard way to remove input-order dependence (Tettelin et al. 2005 PNAS 102:13950-13955). """ rng = np.random.default_rng(seed) n_clusters, n_genomes = presence.shape rows = [] for size in range(1, n_genomes + 1): pan, core = [], [] for _ in range(permutations): idx = rng.choice(n_genomes, size=size, replace=False) sub = presence[:, idx] pan.append(int((sub.sum(axis=1) > 0).sum())) core.append(int((sub.sum(axis=1) == size).sum())) rows.append({ "n_genomes": size, "pan_mean": float(np.mean(pan)), "pan_sd": float(np.std(pan)), "core_mean": float(np.mean(core)), "core_sd": float(np.std(core)), }) return pd.DataFrame(rows) def heaps_law_fit(accumulation: pd.DataFrame) -> Dict[str, float]: """Fit the pan-genome size to Heaps' law, n = kappa * N^gamma. Tettelin et al. (2008) Curr Opin Microbiol 11:472-477. gamma < 1 means each new genome still adds new genes: the pan-genome is OPEN. gamma > 1 (rare) or a fitted alpha = 1 - gamma > 1 means it is CLOSED and sampling is saturating. Needs at least 3 genomes to fit at all, and the estimate is unstable below roughly 5-10; the returned dict says so rather than quietly reporting a meaningless exponent from 3 points. """ out = {"kappa": np.nan, "gamma": np.nan, "alpha": np.nan, "n_points": int(len(accumulation)), "interpretation": "not fitted"} if accumulation is None or len(accumulation) < 3: out["interpretation"] = "at least 3 genomes are required to fit Heaps' law" return out x = np.log(accumulation["n_genomes"].to_numpy(dtype=float)) y = np.log(accumulation["pan_mean"].to_numpy(dtype=float)) m = np.isfinite(x) & np.isfinite(y) if m.sum() < 3: return out gamma, log_kappa = np.polyfit(x[m], y[m], 1) out["gamma"] = round(float(gamma), 4) out["kappa"] = round(float(np.exp(log_kappa)), 3) out["alpha"] = round(float(1.0 - gamma), 4) if len(accumulation) < 5: out["interpretation"] = (f"gamma = {out['gamma']}, but fitted from only " f"{len(accumulation)} genomes - treat as indicative only") elif gamma > 0: out["interpretation"] = ("open pan-genome: new genes are still being added " "with each genome sampled" if gamma >= 0.05 else "closed pan-genome: gene discovery has saturated") return out