Skip to content

Biological Foundations and Genomics

Every living cell carries a molecular instruction manual written in a four-letter chemical alphabet, yet reading that code requires decoding long-range regulatory switches, splicing rules, and epigenetic states that turn one genome into hundreds of distinct tissues. This section introduces the Central Dogma as an information-processing pipeline and explores how long-context genomic foundation models, variant effect predictors, and AI-guided CRISPR tools are learning to read and edit the language of DNA.

The Central Dogma as a Living Information System

  • Imagine a master architectural archive locked safely inside a library vault. Builders never take the original blueprints onto a muddy construction site. Instead, they photocopy just the rooms needed for today's work, edit out the marginal notes, hand those working sheets to skilled craftspeople, and assemble physical tools from the instructions. Living cells run this exact workflow every second through the Central Dogma of molecular biology, flowing from DNA to RNA to protein.

The Central Dogma as a living information pipeline showing DNA transcription, mRNA splicing, translation into 3D proteins, epigenetic feedback, and BioAI modelling targets

  • DNA (deoxyribonucleic acid) is the long-term archival drive. The human genome spans roughly \(3 \times 10^9\) base pairs written over a four-symbol alphabet \(\Sigma_{\text{DNA}} = \{\text{A}, \text{C}, \text{G}, \text{T}\}\) paired across two complementary strands (\(\text{A}\) pairs with \(\text{T}\), and \(\text{C}\) pairs with \(\text{G}\)). Each base carries at most \(\log_2 4 = 2\) bits of raw information, meaning the entire blueprint of a human being compresses to roughly \(750\,\text{MB}\), small enough to fit comfortably on a vintage compact disc!

  • Here is the surprise that makes computational genomics far richer than reading plain computer code. Only about \(1.5\%\) to \(2\%\) of the human genome consists of protein-coding exons that directly spell out molecular machines. The remaining \(98\%\) is non-coding DNA, once prematurely dismissed as junk. We now know that vast stretches of this non-coding expanse act as a sophisticated regulatory operating system packed with promoters, enhancers, insulators, and splicing signals that dictate when, where, and how strongly every gene fires.

  • Converting archival DNA into working cellular machinery unfolds in three carefully orchestrated steps.

    1. Transcription. An enzyme called RNA polymerase copies a target gene from DNA into a transient working transcript called pre-mRNA, swapping thymine (\(\text{T}\)) for uracil (\(\text{U}\)).
    2. Splicing. Human genes are fragmented into alternating coding islands (exons) and non-coding spacers (introns). A molecular editor called the spliceosome excises the introns and stitches the exons together into mature mRNA. Through alternative splicing, one gene can mix and match different subsets of exons to produce distinct protein variants (isoforms) tailored to brain, heart, or muscle tissue.
    3. Translation. A molecular factory called the ribosome reads the mature mRNA three letters at a time. Each three-letter triplet is a codon, giving \(4^3 = 64\) possible codewords mapped onto \(20\) standard amino acids plus \(3\) stop signals. Because \(64 > 20\), the genetic code is deliberately redundant (for instance, six different codons all specify leucine), offering natural error tolerance against minor copying typos.
  • Viewed through a computer-science lens, biology is not a static lookup table. The proteins built at the end of the pipeline include transcription factors that loop straight back onto the DNA archive to switch other genes on or off, creating a dense, self-regulating dynamical system.

Epigenomics and Chromatin Accessibility

  • A puzzle immediately confronts anyone approaching genomics for the first time. A firing cortical neuron in your brain and a metabolic liver cell in your abdomen contain virtually identical \(3\)-billion-letter DNA sequences, yet they look, behave, and divide in completely different ways. How can the same source code compile into two radically different organs?

  • Think of a \(3,000\)-page cookbook shared by both a pastry chef and a sushi chef. Neither chef erases the pages they do not use. Instead, they clip heavy brass padlocks onto closed chapters and place bright sticky tabs on the recipes they cook daily. Cells accomplish this through epigenomics, a layer of chemical annotations and physical packaging draped on top of the underlying DNA sequence without altering the letters themselves.

  • Two physical mechanisms dominate this cell-type control system.

    • Chromatin packing and nucleosomes. Stretched end to end, the DNA inside a single microscopic cell measures about two metres long. To fit inside a nucleus ten micrometres wide, DNA spools tightly around protein cylinders called histones, forming bead-like bundles called chromatin. Tightly wound regions (heterochromatin) are physically locked away so transcription machinery cannot touch them, whereas unwound regions (euchromatin) lie open and active. Assays such as ATAC-seq map this open chromatin landscape across the genome.
    • Chemical bookmarks. Enzymes attach small methyl groups directly to DNA bases (especially cytosine in \(\text{CpG}\) pairs) or modify histone tails with acetyl and methyl tags. These marks recruit activator or repressor complexes, locking a cell stably into a neuron, hepatocyte, or immune-cell identity across divisions.
  • For machine learning, epigenomics explains why predicting gene expression solely from raw sequence is a multi-task problem. A genomic AI model takes a stretch of DNA sequence \(x\) and simultaneously predicts thousands of cell-type-specific tracks (chromatin accessibility, histone marks, transcription factor binding, and RNA expression) across hundreds of tissues.

Why Genomic Sequence Modelling Is Uniquely Hard

  • At first glance, DNA looks like an easy special case of natural language processing (chapter 07) with a tiny vocabulary of four letters. In reality, genomic sequence modelling breaks almost every shortcut that makes text Transformers effortless.

Long-range gene regulation via 3D chromatin looping and comparison of quadratic Transformers, Enformer, and sub-quadratic HyenaDNA and Evo architectures

  • Extreme long-range dependencies. In English prose, most grammatical dependencies resolve within a single paragraph of a few hundred tokens. Inside a human chromosome, a regulatory switch called an enhancer can sit \(100{,}000\) to \(1{,}000{,}000\) base pairs away along the linear DNA string from the gene promoter it activates! Because chromatin folds into 3D loops inside the nucleus, that distant enhancer physically bends over to kiss the promoter. Any model whose receptive field stops at \(4{,}096\) nucleotides is completely blind to how real human genes are switched on.

  • Single-nucleotide precision. Unlike English text, where subword tokenisers (chapter 07) cleanly merge common phrases into single tokens, shifting a DNA sequence by one letter can destroy a reading frame, abolish a splice site, or cause a fatal genetic disorder. Coarse \(k\)-mer tokenisation blurs single-base edits and breaks alignment when insertions or deletions shift every downstream token boundary.

  • Reverse-complement symmetry and low local signal. Double-stranded DNA has no privileged reading direction for many regulatory motifs, so a sequence \(x\) and its reverse complement \(x^{\text{rc}}\) often carry equivalent biological meaning. Meanwhile, informative six-letter binding motifs hide like tiny needles inside megabases of repetitive background sequence, making overfitting notoriously easy if train and test splits leak homologous chromosomes.

Genomic Foundation Models

  • Bridging the gap between megabase reach and single-base fidelity has sparked a wave of specialised sequence architectures that directly extend the sequence-modelling machinery from chapter 07 and convolutional networks from chapter 08.

  • Enformer (hierarchical convolutions plus attention over 200 kb). Vanilla self-attention scales as \(O(L^2)\) in sequence length \(L\), so attending directly over \(200{,}000\) nucleotides would require a \(4 \times 10^{10}\)-entry attention matrix per head! Enformer sidesteps this memory wall with a clean two-stage bridge. First, a tower of convolutional layers scans local \(6\) to \(15\) bp transcription-factor motifs and progressively downsamples the sequence into \(128\) bp bins, shrinking \(L = 196{,}608\) raw bases down to \(1{,}536\) compact tokens. Next, a stack of Transformer blocks with relative positional encodings mixes information freely across those bins, letting a gene promoter attend straight to an enhancer \(100\,\text{kb}\) upstream. Finally, multi-task heads predict over \(5{,}000\) human and mouse epigenomic and expression tracks at once.

  • HyenaDNA and Evo (sub-quadratic megabase operators). Pooling into \(128\) bp bins works well for epigenomic track prediction, yet generative DNA modelling and base-level variant analysis crave single-nucleotide resolution across entire chromosomes. Models such as HyenaDNA and Evo replace dense quadratic attention with implicit long convolutions and structured state-space models (SSMs) introduced in chapter 07. Rather than comparing every base pair explicitly with every other base pair, a long convolution slides a learned filter \(h\) of length \(L\) over the input sequence \(u\) using the Fast Fourier Transform (FFT, chapter 09).

\[(u * h)[n] = \mathcal{F}^{-1}\!\Bigl(\mathcal{F}(u) \odot \mathcal{F}(h)\Bigr)[n]\]
  • Because the FFT runs in \(O(L \log L)\) time and state-space recurrences run in \(O(L)\) time during autoregressive generation, HyenaDNA stretches single-nucleotide context up to \(1\,\text{million}\) base pairs (\(1\,\text{Mb}\)), while Evo (built on the StripedHyena hybrid of long convolutions and periodic attention layers) scaled across prokaryotic genomes and generated functional multi-gene CRISPR systems from scratch.

  • Evo 2 (cross-domain 40B genomic foundation model). Scaling that sub-quadratic lineage dramatically, Evo 2 (Arc Institute and NVIDIA, 2025) reaches \(40\) billion parameters with a \(1\,\text{million}\) base-pair single-nucleotide context window, built on the hybrid StripedHyena 2 architecture combining convolutions, state-space operators, and multi-head attention. Trained autoregressively on OpenGenome2 (over \(8.8\) trillion nucleotides spanning bacteria, archaea, eukaryotes, phages, and human genomes), Evo 2 supports both zero-shot pathogenicity scoring of human variants (such as BRCA1 mutations) and long-range generative biological sequence design.

  • AlphaGenome (megabase regulatory genomics at single-base resolution). Pushing the supervised sequence-to-function lineage of Enformer to full megabase scale, AlphaGenome (Google DeepMind, 2025) ingests up to \(1\,\text{million}\) base pairs of DNA and predicts thousands of multimodal regulatory tracks at single-base-pair resolution simultaneously, spanning gene expression, RNA splicing, chromatin accessibility, histone modifications, transcription-factor binding, and 3D chromatin contact maps. Comparing reference and mutated predictions lets researchers score how subtle non-coding variants disrupt gene regulation across long-range enhancer-promoter loops.

Variant Effect Prediction and Clinical Genomics

  • Every human carries roughly four to five million genetic differences (variants) relative to the reference genome. The vast majority are harmless personal quirks, yet a tiny handful trigger devastating hereditary diseases or cancer. Clinicians routinely discover a Variant of Uncertain Significance (VUS) in a patient's DNA that has never been catalogued before.

  • Think of a proofreader checking a one-letter typo in a legal contract. Changing among to amongst leaves the meaning untouched, whereas changing now to not flips the entire contract upside down. AI variant effect predictors quantify exactly which single-letter edits change biological meaning.

  • In silico mutagenesis (ISM) is the most direct test for supervised genomic models like Enformer or SpliceAI (a deep residual dilated CNN trained to predict exon-intron splice junctions across \(10\,\text{kb}\) windows). You feed the reference sequence \(x_{\text{ref}}\) and the mutated sequence \(x_{\text{alt}}\) through the model \(f_{\theta}\) and measure the predicted shift in expression or splicing probability.

\[\Delta_{\text{ISM}}(x_{\text{ref}} \to x_{\text{alt}}) = f_{\theta}(x_{\text{alt}}) - f_{\theta}(x_{\text{ref}})\]
  • Zero-shot evolutionary scoring takes an even broader view using self-supervised language models trained across millions of species. If evolution has preserved a particular letter across half a billion years of life, mutating it is almost certainly damaging. A language model naturally assigns a high log-probability to evolutionarily favoured nucleotides or amino acids and a sharply lower log-probability to disruptive substitutions, yielding the log-likelihood ratio (LLR).
\[\text{LLR}(i, a_{\text{ref}} \to a_{\text{alt}}) = \log p_{\theta}(a_{\text{alt}} \mid x_{-i}) - \log p_{\theta}(a_{\text{ref}} \mid x_{-i})\]
  • AlphaMissense fuses this evolutionary grammar with 3D structural awareness borrowed from AlphaFold (covered in section 02). Specifically targeting missense variants (single DNA mutations inside coding exons that swap one amino acid for another), AlphaMissense predicts whether the swap destabilises the folded protein core or disrupts a functional interface, calibrating its scores against human population allele frequencies to classify roughly \(71\) million possible human missense mutations into benign, ambiguous, or likely pathogenic categories.

CRISPR Gene Editing and AI-Guided Design

  • Reading the genome is transformative on its own, yet modern biology also lets us rewrite it. CRISPR-Cas9, adapted from an ancient bacterial immune defence against viruses, works like a programmable pair of molecular scissors. A biologist designs a short \(20\)-nucleotide guide RNA (gRNA) matching a target DNA address next to a short required landing tag called a PAM (such as NGG for standard SpCas9). The Cas9 enzyme patrols the cell's DNA, locks onto the complementary match, and slices both strands so cellular repair pathways can disable a broken gene or patch in a corrected sequence.

  • Choosing the right \(20\)-letter guide out of dozens of candidate addresses inside a gene is a classic machine-learning optimisation problem governed by two competing objectives.

    • On-target cleavage efficiency. Not every valid guide cuts reliably. Local DNA flexibility, GC-content balance, secondary hairpins inside the guide RNA itself, and whether the target chromatin is physically open strongly affect cutting rates. Neural models trained on tens of thousands of experimental guides predict cutting efficiency \(E(g) \in [0, 1]\) directly from sequence and epigenomic context.
    • Off-target safety. The human genome is enormous, so a \(20\)-letter guide often resembles unintended look-alike sites elsewhere on other chromosomes that differ by only \(1\) to \(4\) mismatches. Cutting a tumour-suppressor gene by accident would be catastrophic! Crucially, mismatches right next to the PAM (the seed region, positions \(1\) to \(8\) from the PAM) strongly suppress Cas9 cutting, whereas mismatches near the far distal tip are tolerated much more easily. AI off-target scorers sum weighted mismatch risk across every near-match site \(s \in \mathcal{O}(g)\) in the genome to compute a specificity score.
\[\text{Specificity}(g) = \frac{1}{1 + \sum_{s \in \mathcal{O}(g)} w_{\text{off}}(g, s)}\]
  • Beyond selecting guides, newer generative BioAI models are beginning to design entirely new CRISPR editors (including base editors and prime editors that rewrite single letters without making risky double-strand breaks) tailored for smaller delivery size and higher precision.

Take-Home

  • The Central Dogma turns a \(3\)-billion-base DNA archive into working 3D proteins through transcription, alternative splicing, and triplet codon translation, with roughly \(98\%\) of the human genome dedicated to non-coding regulation.
  • Identical DNA produces wildly different tissues because epigenomic packaging (chromatin accessibility, histone marks, and DNA methylation) opens or locks specific genes in each cell type.
  • Genomic sequence modelling must bridge \(100\,\text{kb}\) to megabase enhancer-promoter loops while preserving single-nucleotide sensitivity, motivating hybrid CNN-Transformers like Enformer, megabase single-base regulatory models like AlphaGenome, and sub-quadratic FFT-convolution or state-space foundation models like HyenaDNA and the 40B-parameter Evo 2.
  • Variant effect predictors combine in silico mutagenesis, evolutionary log-likelihood ratios, splicing networks, and structural models like AlphaMissense to separate harmless variation from disease-causing mutations.
  • AI-guided CRISPR design balances high on-target editing efficiency against strict genome-wide off-target specificity, weighting mismatches heavily in the PAM-proximal seed region.

Coding Tasks (use CoLab or notebook)

  1. Compare quadratic attention memory scaling against sub-quadratic \(O(L \log L)\) FFT long convolutions across genomic context lengths up to \(1\,\text{Mb}\), then run a JAX 1D FFT long-convolution detector that couples a distant enhancer motif and promoter separated by hundreds of base pairs.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # Part 1: Memory scaling comparison (in megabytes for float32 activations)
    lengths = jnp.array([512, 2048, 8192, 32768, 131072, 524288, 1048576], dtype=jnp.float32)
    attn_mb = (lengths ** 2) * 4.0 / (1024.0 ** 2)
    fft_mb = (lengths * jnp.log2(lengths) * 8.0) * 4.0 / (1024.0 ** 2)
    
    # Part 2: FFT long convolution detecting a distant enhancer -> promoter pairing
    key = jax.random.PRNGKey(42)
    L = 512
    enhancer_pos = 64
    promoter_pos = 420
    dist = promoter_pos - enhancer_pos
    
    # One-hot encode random background DNA (A=0, C=1, G=2, T=3)
    seq_idx = jax.random.randint(key, (L,), 0, 4)
    # Inject an 8 bp enhancer motif (A C G T A C G T) and promoter motif (T A T A A A T A)
    enh_motif = jnp.array([0, 1, 2, 3, 0, 1, 2, 3])
    prom_motif = jnp.array([3, 0, 3, 0, 0, 0, 3, 0])
    
    pos = jnp.arange(L)
    in_enh = (pos >= enhancer_pos) & (pos < enhancer_pos + 8)
    in_prom = (pos >= promoter_pos) & (pos < promoter_pos + 8)
    seq_idx = jnp.where(in_enh, enh_motif[jnp.clip(pos - enhancer_pos, 0, 7)], seq_idx)
    seq_idx = jnp.where(in_prom, prom_motif[jnp.clip(pos - promoter_pos, 0, 7)], seq_idx)
    
    def one_hot(idx, depth):
        return jnp.eye(depth, dtype=jnp.float32)[idx]
    
    one_hot_seq = one_hot(seq_idx, 4)
    enh_kernel = one_hot(enh_motif, 4)
    prom_kernel = one_hot(prom_motif, 4)
    
    def motif_scan(seq_oh, motif_oh):
        k = motif_oh.shape[0]
        scores = [jnp.sum(seq_oh[i:i + k] * motif_oh) / k for i in range(L - k + 1)]
        return jnp.concatenate([jnp.array(scores), jnp.zeros(k - 1)])
    
    enh_act = jax.nn.relu(motif_scan(one_hot_seq, enh_kernel) - 0.75)
    prom_act = jax.nn.relu(motif_scan(one_hot_seq, prom_kernel) - 0.75)
    
    # Long-range implicit kernel peaked around the enhancer-to-promoter distance
    lags = jnp.arange(L, dtype=jnp.float32)
    long_filter = jnp.exp(-0.5 * ((lags - float(dist)) / 18.0) ** 2)
    
    # O(L log L) causal convolution via FFT
    pad_len = 2 * L
    enh_fft = jnp.fft.rfft(enh_act, n=pad_len)
    filt_fft = jnp.fft.rfft(long_filter, n=pad_len)
    long_range_signal = jnp.fft.irfft(enh_fft * filt_fft, n=pad_len)[:L]
    gene_activation = prom_act * long_range_signal
    
    print(f"Peak promoter activation at base {int(jnp.argmax(gene_activation))} (true promoter {promoter_pos})")
    print(f"At 1 Mb context, dense attention needs {float(attn_mb[-1]) / 1e6:.2f} TB vs {float(fft_mb[-1]) / 1e3:.2f} GB for FFT conv")
    
    fig, axes = plt.subplots(1, 2, figsize=(11, 4))
    axes[0].loglog(lengths / 1e3, attn_mb, "o-", color="#e74c3c", lw=2, label="Dense Attention O(L^2)")
    axes[0].loglog(lengths / 1e3, fft_mb, "s-", color="#9b59b6", lw=2, label="FFT Long Conv O(L log L)")
    axes[0].axhline(80000, color="#333", ls="--", lw=1.2, label="80 GB GPU VRAM")
    axes[0].set_title("Memory Scaling Across Genomic Context")
    axes[0].set_xlabel("Sequence Length (kb)")
    axes[0].set_ylabel("Activation Footprint (MB)")
    axes[0].legend(fontsize=8)
    
    axes[1].plot(pos, enh_act, color="#e74c3c", lw=1.8, label="Enhancer motif score")
    axes[1].plot(pos, long_range_signal, "--", color="#3498db", lw=1.8, label="Long-range FFT signal")
    axes[1].plot(pos, gene_activation * 4.0, color="#27ae60", lw=2.2, label="Coupled gene activation")
    axes[1].set_title("Long-Range Enhancer to Promoter Coupling")
    axes[1].set_xlabel("Genomic Position (bp)")
    axes[1].set_ylabel("Activation")
    axes[1].legend(fontsize=8)
    plt.tight_layout()
    plt.show()
    

  2. Perform in silico mutagenesis (ISM) across a \(40\) bp DNA regulatory sequence containing a transcription-factor binding site and a canonical GT splice donor, computing the predicted effect \(\Delta = f(x_{\text{alt}}) - f(x_{\text{ref}})\) of every possible single-nucleotide mutation and plotting the variant-effect heatmap.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    bases = ["A", "C", "G", "T"]
    seq_str = "CGTAGCTCACGTGATCGAATCGGTAAGTCCATGCTAGCTA"
    seq_idx = jnp.array([bases.index(b) for b in seq_str])
    L = len(seq_str)
    
    def one_hot(idx, depth):
        return jnp.eye(depth, dtype=jnp.float32)[idx]
    
    def logsumexp(x):
        m = jnp.max(x)
        return m + jnp.log(jnp.sum(jnp.exp(x - m)))
    
    # Position-weight matrices for an E-box motif (CACGTG at pos 8..13) and splice donor (GTAAGT at pos 22..27)
    ebox_pwm = one_hot(jnp.array([1, 0, 1, 2, 3, 2]), 4) * 1.4 - 0.35
    donor_pwm = one_hot(jnp.array([2, 3, 0, 0, 2, 3]), 4) * 1.6 - 0.40
    
    def score_sequence(oh):
        """Differentiable sequence-to-function model scoring E-box binding + splice donor strength."""
        k = 6
        ebox_scores = jnp.array([jnp.sum(oh[i:i + k] * ebox_pwm) for i in range(L - k + 1)])
        donor_scores = jnp.array([jnp.sum(oh[i:i + k] * donor_pwm) for i in range(L - k + 1)])
        # Smooth max pooling across sequence positions
        ebox_act = jax.nn.sigmoid(logsumexp(ebox_scores * 2.5) / 2.5 - 4.0)
        donor_act = jax.nn.sigmoid(logsumexp(donor_scores * 2.5) / 2.5 - 4.5)
        return 0.5 * ebox_act + 0.5 * donor_act
    
    ref_oh = one_hot(seq_idx, 4)
    ref_score = float(score_sequence(ref_oh))
    
    # Evaluate all L x 4 single-nucleotide variants without in-place mutation
    delta_rows = []
    for b in range(4):
        row = []
        for p in range(L):
            mask = (jnp.arange(L) == p)
            alt_idx = jnp.where(mask, b, seq_idx)
            alt_score = float(score_sequence(one_hot(alt_idx, 4)))
            row.append(alt_score - ref_score)
        delta_rows.append(row)
    
    ism_map = jnp.array(delta_rows)
    worst_drop = float(jnp.min(ism_map))
    print(f"Reference functional score {ref_score:.3f}, strongest pathogenic drop {worst_drop:.3f}")
    
    fig, ax = plt.subplots(figsize=(11, 3.4))
    im = ax.imshow(ism_map, cmap="RdBu", vmin=-0.5, vmax=0.5, aspect="auto")
    ax.set_yticks(range(4))
    ax.set_yticklabels(bases)
    ax.set_xticks(range(L))
    ax.set_xticklabels(list(seq_str), fontsize=7.5)
    ax.set_title("In Silico Mutagenesis Variant Effect Map (Blue Neutral, Red Loss of Function)")
    ax.set_xlabel("Reference Genomic Position")
    ax.set_ylabel("Mutated Base")
    plt.colorbar(im, ax=ax, label="Delta Function Score")
    plt.tight_layout()
    plt.show()
    

  3. Build an AI-inspired CRISPR guide-RNA designer that evaluates candidate \(20\)-nucleotide guides for both on-target cutting efficiency (optimal GC content and favoured PAM-proximal nucleotides) and genome-wide off-target safety (heavily penalising seed-region matches), then plot the efficiency-versus-specificity trade-off.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    key = jax.random.PRNGKey(7)
    n_guides = 60
    n_offtargets = 250
    L_guide = 20
    
    # Generate candidate 20-nt guides and a background panel of genomic near-match sites
    k1, k2, k3 = jax.random.split(key, 3)
    guides = jax.random.randint(k1, (n_guides, L_guide), 0, 4)
    
    # Build semi-homologous background sites by mutating random templates
    templates = jax.random.randint(k2, (n_offtargets, L_guide), 0, 4)
    # Inject some close near-matches to specific guides to make off-target risk realistic
    close_sites = []
    for i in range(40):
        rng = jax.random.PRNGKey(100 + i)
        r1, r2 = jax.random.split(rng)
        base_g = guides[i % n_guides]
        mut_mask = jax.random.uniform(r1, (L_guide,)) < 0.12
        rand_bases = jax.random.randint(r2, (L_guide,), 0, 4)
        close_sites.append(jnp.where(mut_mask, rand_bases, base_g))
    genome_sites = jnp.concatenate([templates, jnp.stack(close_sites, axis=0)], axis=0)
    
    # On-target efficiency favours 45% to 65% GC content and G at position 19 (adjacent to PAM)
    is_gc = (guides == 1) | (guides == 2)
    gc_frac = jnp.mean(is_gc.astype(jnp.float32), axis=1)
    gc_score = jnp.exp(-0.5 * ((gc_frac - 0.55) / 0.14) ** 2)
    pam_bonus = jnp.where(guides[:, -1] == 2, 0.18, jnp.where(guides[:, -1] == 3, -0.15, 0.0))
    on_target = jnp.clip(0.82 * gc_score + pam_bonus, 0.05, 0.99)
    
    # Position-dependent mismatch tolerance (distal pos 0..11 more tolerant, PAM-proximal seed 12..19 strict)
    pos_weights = jnp.linspace(0.15, 0.95, L_guide)
    
    # Compare every guide against every off-target site
    mismatches = (guides[:, None, :] != genome_sites[None, :, :]).astype(jnp.float32)
    weighted_mm = jnp.sum(mismatches * pos_weights[None, None, :], axis=-1)
    # High risk only when few weighted mismatches occur (exclude exact 0-mismatch target itself)
    n_mm = jnp.sum(mismatches, axis=-1)
    off_risk = jnp.where((n_mm >= 1) & (n_mm <= 4), jnp.exp(-1.4 * weighted_mm), 0.0)
    specificity = 1.0 / (1.0 + jnp.sum(off_risk, axis=1))
    
    composite = 0.55 * on_target + 0.45 * specificity
    best_idx = int(jnp.argmax(composite))
    print(f"Top CRISPR guide #{best_idx} achieves on-target {float(on_target[best_idx]):.2f} and specificity {float(specificity[best_idx]):.2f}")
    
    plt.figure(figsize=(7.5, 4.5))
    sc = plt.scatter(specificity, on_target, c=composite, cmap="viridis", s=55, alpha=0.85, edgecolors="#333", lw=0.6)
    plt.scatter([specificity[best_idx]], [on_target[best_idx]], color="#e74c3c", s=140, marker="*", zorder=5, label="Selected Top Guide")
    plt.colorbar(sc, label="Combined Design Score")
    plt.title("CRISPR Guide-RNA Efficiency vs Off-Target Specificity")
    plt.xlabel("Genome-Wide Off-Target Specificity (Higher Is Safer)")
    plt.ylabel("Predicted On-Target Cutting Efficiency")
    plt.legend()
    plt.grid(alpha=0.25)
    plt.tight_layout()
    plt.show()