Skip to content

De Novo Protein Design

Predicting the shape of a protein that evolution already invented is a triumph of reading biology, yet medicine and green chemistry often demand brand-new molecular tools that nature never had reason to evolve. This section turns structure prediction upside down, exploring fixed-backbone inverse folding, SE(3) diffusion for sculpting novel backbones, machine-learning-guided directed evolution, and the closed Design-Build-Test-Learn loop that anchors digital designs in wet-lab reality.

Inverting the Folding Problem

  • Think of all naturally occurring proteins on Earth as a handful of tiny oases scattered across an unimaginable desert. A short \(100\)-residue protein has \(20^{100} \approx 1.3 \times 10^{130}\) possible amino-acid sequences, vastly exceeding the number of atoms in the observable universe! Over four billion years, biological evolution has sampled only an infinitesimal speck of that space, shaped strictly by survival pressures rather than human needs like neutralising a new virus, breaking down ocean plastics, or capturing atmospheric carbon.

  • De novo protein design flips the arrow of chapter 24 section 02. Instead of mapping an existing sequence \(s\) to its structure \(x\) (forward folding, \(f: s \mapsto x\)), we specify a desired biological function or 3D geometry \(x^*\) and ask AI to invent a brand-new amino-acid sequence \(s^*\) that folds reliably into \(x^*\) and performs the job in water.

  • Fortunately, physics works in our favour through sequence-to-structure degeneracy. Many distinct amino-acid sequences can fold into almost the exact same 3D backbone shape, provided they pack a snug hydrophobic interior and display a soluble polar exterior. Modern BioAI decomposes this inverse challenge into a remarkably effective two-stage pipeline, first sculpting a physically realistic 3D backbone and then solving for sequences that stabilise it.

De novo protein design workflow combining RFdiffusion SE(3) backbone sculpting, ProteinMPNN inverse folding, and AlphaFold self-consistency filtering

Fixed-Backbone Inverse Folding

  • Imagine handing a master tailor an empty wooden mannequin and asking them to choose the exact fabrics, seams, and buttons so the finished coat holds that silhouette cleanly on its own. That is fixed-backbone inverse folding. Given the 3D backbone coordinates of a target protein (\(\text{N}, \text{C}_\alpha, \text{C}, \text{O}\) atoms along the chain), the model predicts an amino-acid sequence \(s = (s_1, \dots, s_L)\) whose lowest-energy folded state matches that exact backbone.

  • Earlier physics-based methods such as Rosetta spent hours running Monte Carlo side-chain packing simulations and still struggled when designed proteins clumped together in test tubes. Deep geometric models like ProteinMPNN and ESM-IF1 transformed inverse folding into a sub-second neural inference step using the 3D graph neural networks of chapter 15.

  • ProteinMPNN represents the backbone as a sparse \(k\)-nearest-neighbour spatial graph (typically linking each residue to its \(48\) closest 3D neighbours). Edge features encode pairwise inter-atomic distances and relative orientations invariant to global rotation and translation. Three message-passing encoder layers propagate geometric context across the fold, telling buried core nodes that space is tight and oily while telling surface nodes that they face surrounding water.

  • An autoregressive decoder then generates the amino-acid sequence one residue at a time, factorising the joint probability over a randomised decoding order \(\pi\) rather than strictly left-to-right.

\[p_{\theta}(s \mid X) = \prod_{t=1}^{L} p_{\theta}\!\bigl(s_{\pi(t)} \mid s_{\pi(<t)}, X\bigr)\]
  • Sampling in random order lets biologists lock critical catalytic residues or binding hotspots in place first and let ProteinMPNN design the surrounding scaffold around them! It also supports tied positions for symmetric assemblies (forcing identical subunits to receive identical sequences) and temperature scaling (\(T \approx 0.1\) to \(0.3\)) to trade diversity against high-confidence stability. Adding tiny Gaussian jitter (\(\approx 0.2\,\text{\AA}\)) to training backbones turned out to be a crucial insight, stopping the network from memorising brittle crystal coordinates and boosting real wet-lab expression success rates dramatically.

Generative 3D Backbone Design in SE(3)

  • Inverse folding solves the sequence once you already have a backbone, yet where does a brand-new 3D backbone come from when you want to bind a previously undruggable cancer receptor? The answer adapts the denoising diffusion probabilistic models of chapter 08 from flat 2D pixel grids onto the curved 3D manifold of rigid protein frames, pioneered by RFdiffusion and FrameDiff.

  • Just as in AlphaFold 2, each residue \(i\) carries a rigid frame \(T_i = (R_i, \mathbf{t}_i) \in SE(3)\). During the forward noising process, we smoothly corrupt a clean real protein backbone across timesteps \(t = 1, \dots, T\) until nothing remains except an unrecognisable cloud of floating frames.

    • Translations \(\mathbf{t}_i \in \mathbb{R}^3\) follow standard 3D Gaussian diffusion, drifting outward toward an isotropic normal cloud \(\mathcal{N}(\mathbf{0}, I_3)\).
    • Rotations \(R_i \in SO(3)\) cannot simply add flat Gaussian noise without breaking orthogonality! Instead, rotational diffusion evolves via Brownian motion on the rotation group \(SO(3)\), sampled from the isotropic Gaussian distribution on \(SO(3)\), denoted \(\mathcal{IG}_{SO(3)}\), converging smoothly to a uniform random orientation.
  • During reverse generation, an \(SE(3)\)-equivariant neural network (fine-tuned directly from the pretrained RoseTTAFold structure predictor in RFdiffusion) inspects the noisy frame cloud at step \(t\) and predicts the clean denoised frames \(\hat{T}_0\), taking a small step back toward physical order.

  • The true magic of RFdiffusion lies in conditional sculpting, which turns backbone generation into molecular CAD software.

    • Custom protein binders. You fix the 3D coordinates of a disease target (say a viral spike protein), tag a handful of surface hotspot residues, and let RFdiffusion denoise a free chain right alongside that surface until it wraps snugly into a complementary lock-and-key binder.
    • Motif scaffolding. Suppose biochemists know the exact 3D arrangement of three catalytic amino acids that cleave a chemical bond. You freeze those three motif frames in space and ask RFdiffusion to hallucinate a sturdy custom protein body around them holding the active site rigidly in place.
    • Symmetric nanocages. By symmetrising noisy frames at every denoising step under cyclic, dihedral, or icosahedral symmetry groups, RFdiffusion builds hollow geometric protein cages useful for next-generation vaccines and targeted drug delivery.

Sequence-Space Design and ML-Guided Directed Evolution

  • Not every bioengineering problem calls for inventing a fold from zero. Often a natural enzyme already performs a useful reaction, yet it falls apart at industrial temperatures or runs ten times too slowly. In the wet lab, directed evolution (awarded the 2018 Nobel Prize in Chemistry) mimics natural selection in fast forward by randomly mutating the gene, testing thousands of variants, keeping the winners, and repeating for many cycles.

  • Random mutagenesis struggles whenever a protein's fitness landscape is rugged and shaped by epistasis, where two mutations that individually look neutral or slightly harmful combine synergistically to unlock a huge jump in activity. Blind local hill-climbing gets trapped on mediocre peaks and wastes thousands of expensive assays.

  • Machine-learning-guided directed evolution (MLDE) accelerates this search by training a surrogate fitness model \(\hat{f}_{\theta}(s)\) on measured sequence-activity pairs (often powered by embeddings from protein language models like ESM-2 so the surrogate already understands evolutionary constraints even with fewer than \(100\) lab measurements!). Rather than picking only the highest predicted mean \(\mu(s)\), an uncertainty-aware acquisition function such as Upper Confidence Bound balances exploiting known winners with exploring promising untested regions.

\[\alpha_{\text{UCB}}(s) = \mu(s) + \beta \, \sigma(s)\]
  • Evolutionary search, Gibbs sampling, or discrete diffusion explores millions of multi-mutant combinations in silico against \(\alpha_{\text{UCB}}(s)\), selecting a small, diverse batch of high-potential variants for the next round of lab testing. Across real enzyme campaigns, ML-guided evolution routinely achieves in two or three rounds what purely random screening takes ten or more rounds to reach.

Hallucination and Gradient-Based Design

  • Before diffusion models matured, researchers discovered an ingenious way to turn any differentiable folding network into a designer directly, dubbed protein hallucination (echoing Google's DeepDream for image classifiers in chapter 08).

  • Start with a completely random amino-acid sequence represented as a continuous probability matrix \(P \in \mathbb{R}^{L \times 20}\) (relaxed via softmax logits or straight-through Gumbel-Softmax so gradients flow smoothly). Pass \(P\) through a frozen folding network like AlphaFold or RoseTTAFold and define a differentiable design objective, such as maximising confidence (\(\text{pLDDT}\)), sharpening pairwise distance distributions away from a vague background prior via Kullback-Leibler divergence (chapter 05), or matching a desired binding interface.

\[\mathcal{L}_{\text{design}}(P) = \mathcal{L}_{\text{struct}}\!\bigl(f_{\text{fold}}(P)\bigr) - \lambda \, D_{\text{KL}}\!\Bigl(p_{\text{dist}}(P) \,\|\, p_{\text{bg}}\Bigr)\]
  • Backpropagating \(\nabla_P \mathcal{L}_{\text{design}}\) iteratively updates the sequence logits until the folding model hallucinates a crisp, novel sequence predicted to fold tightly!

  • Gradient-based hallucination taught BioAI a sobering lesson about adversarial examples. Just as tiny pixel tweaks can fool an image classifier into seeing a panda where none exists, unconstrained gradient descent through AlphaFold can invent bizarre, overly hydrophobic sequences that earn a \(98\) pLDDT score inside the neural network yet crash out as useless insoluble sludge in a real beaker. Modern pipelines fix this neatly by pairing hallucination or diffusion backbones with ProteinMPNN sequence redesign, which naturally restores water-soluble surface chemistry.

The Wet-Lab Reality Check and Closed DBTL Loop

  • A gorgeous 3D ribbon spinning on a laptop monitor cures nobody until real cells manufacture the protein and it works in salty, crowded biological fluid. Bridging silicon and wet chemistry relies on strict in silico filtering followed by a disciplined Design-Build-Test-Learn (DBTL) cycle.

The closed-loop Design-Build-Test-Learn cycle linking computational protein design, DNA synthesis, biophysical assays, and active-learning surrogate updates

  • Before spending money to synthesise a single strand of DNA, designers filter thousands of generated candidates through self-consistency refolding. Take a backbone \(X_{\text{gen}}\) from RFdiffusion, generate eight candidate sequences with ProteinMPNN, and fold each sequence independently using AlphaFold 2 or ESMFold to obtain \(\hat{X}_{\text{fold}}\). We compute the self-consistency RMSD (\(\text{scRMSD}\)) between the intended backbone and the refolded backbone, keeping only candidates with \(\text{scRMSD} < 2.0\,\text{\AA}\), high \(\text{pLDDT}\), and low interface \(\text{PAE}\) (typically \(\text{iPAE} < 10\,\text{\AA}\) for binders).

  • Candidates surviving in silico filtering enter the physical Build and Test stages, where real biology enforces four tough gatekeepers that computer models still only partially predict.

    • Expression and solubility. Will bacteria or yeast actually produce the protein cleanly, or will sticky patches cause chains to clump into useless aggregates?
    • Folding yield and thermal stability. Does the purified protein adopt a single monomeric shape and hold together at body temperature (measured by melting temperature \(T_m\))?
    • Binding affinity and specificity. For therapeutic binders, biophysical assays like Surface Plasmon Resonance (SPR) measure the equilibrium dissociation constant \(K_D\) (lower \(K_D\), down to nanomolar or picomolar concentrations, means tighter binding) while checking that the binder ignores off-target human proteins.
    • Immunogenicity and dynamics. Even a tight binder can trigger an unwanted immune response in patients or fail to flex smoothly along a catalytic cycle.
  • The final Learn step closes the loop. Historically, biologists published only their rare successes and threw failed experiments in the bin. In modern BioAI labs, negative data (sequences that misfolded, aggregated, or failed to bind) is pure gold! Feeding both hits and failures back into the surrogate models recalibrates uncertainty and steers round \(n + 1\) sharply away from dead ends, turning protein engineering from blind luck into a systematic, compounding engineering discipline.

Take-Home

  • De novo protein design inverts structure prediction, navigating an astronomical \(20^L\) sequence space to invent custom binders, enzymes, and assemblies that evolution never explored.
  • Fixed-backbone inverse folding models such as ProteinMPNN and ESM-IF1 use 3D \(k\)-NN graph message passing and randomised autoregressive decoding to turn any target backbone into stable, water-soluble sequences in under a second.
  • Generative backbone models like RFdiffusion and FrameDiff adapt denoising diffusion directly onto rigid frames in \(SE(3)\), enabling conditional sculpting of target binders, active-site scaffolds, and symmetric nanocages.
  • Machine-learning-guided directed evolution pairs protein embeddings with uncertainty-aware surrogate models to cross epistatic valleys in far fewer experimental rounds, while gradient hallucination reveals the importance of avoiding adversarial sequences.
  • Self-consistency refolding (\(\text{scRMSD} < 2\,\text{\AA}\)) screens designs cheaply in silico, while the closed Design-Build-Test-Learn loop turns both wet-lab hits and failures into fuel for smarter iterations.

Coding Tasks (use CoLab or notebook)

  1. Build a lightweight geometric inverse-folding scorer in JAX over a synthetic 3D four-helix bundle that computes residue burial (3D neighbour count) via graph message passing, samples amino-acid classes at low versus high temperature \(T\), and compares core hydrophobicity against surface solubility.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # Build a synthetic 3D 4-helix bundle backbone (4 helices x 12 residues = 48 residues)
    coords_list = []
    centres = [(-3.0, -3.0), (3.0, -3.0), (3.0, 3.0), (-3.0, 3.0)]
    for h_idx, (cx, cy) in enumerate(centres):
        t = jnp.linspace(0.0, 3.2 * jnp.pi, 12)
        z = jnp.linspace(0.0, 16.5, 12)
        if h_idx % 2 == 1:
            z = z[::-1]
        hx = cx + 2.3 * jnp.cos(t + h_idx * 0.7)
        hy = cy + 2.3 * jnp.sin(t + h_idx * 0.7)
        coords_list.append(jnp.stack([hx, hy, z], axis=-1))
    backbone = jnp.concatenate(coords_list, axis=0)  # (48, 3)
    
    # Pairwise 3D distances and k-NN spatial graph message passing for burial
    diffs = backbone[:, None, :] - backbone[None, :, :]
    dists = jnp.sqrt(jnp.sum(diffs ** 2, axis=-1) + 1e-6)
    # Smooth neighbour contact count within 8.5 A (excluding self)
    adj = jax.nn.sigmoid((8.5 - dists) * 1.4) * (1.0 - jnp.eye(backbone.shape[0]))
    burial = jnp.sum(adj, axis=1)
    burial_norm = (burial - jnp.min(burial)) / (jnp.max(burial) - jnp.min(burial) + 1e-6)
    
    # 3 simplified residue classes: 0=Hydrophobic (core), 1=Polar (surface), 2=Charged (exposed)
    logits = jnp.stack([
        4.2 * burial_norm - 1.8,          # Hydrophobic favoured in buried core
        2.4 * (1.0 - burial_norm) - 0.3,  # Polar favoured on exterior
        3.6 * (1.0 - burial_norm) - 1.5,  # Charged strongly favoured on exposed exterior
    ], axis=-1)
    
    def sample_inverse_fold(key, temp):
        probs = jax.nn.softmax(logits / temp, axis=-1)
        # Gumbel-Max sampling using pure jax.random.uniform (Pyodide compatible)
        u = jax.random.uniform(key, logits.shape, minval=1e-6, maxval=1.0 - 1e-6)
        gumbel = -jnp.log(-jnp.log(u))
        sampled = jnp.argmax(logits / temp + gumbel, axis=-1)
        core_mask = burial_norm > 0.55
        surf_mask = burial_norm <= 0.55
        core_hydro = float(jnp.mean((sampled == 0)[core_mask]))
        surf_polar = float(jnp.mean((sampled >= 1)[surf_mask]))
        entropy = float(-jnp.mean(jnp.sum(probs * jnp.log(probs + 1e-8), axis=-1)))
        return sampled, core_hydro, surf_polar, entropy
    
    key = jax.random.PRNGKey(12)
    k_low, k_high = jax.random.split(key)
    s_low, ch_l, sp_l, ent_l = sample_inverse_fold(k_low, temp=0.25)
    s_high, ch_h, sp_h, ent_h = sample_inverse_fold(k_high, temp=1.50)
    
    print(f"Low temp (T=0.25)  core hydrophobic {ch_l:.1%}, surface soluble {sp_l:.1%}, mean entropy {ent_l:.2f}")
    print(f"High temp (T=1.50) core hydrophobic {ch_h:.1%}, surface soluble {sp_h:.1%}, mean entropy {ent_h:.2f}")
    
    # Visualise top-down projection coloured by sampled residue class at T=0.25
    fig, axes = plt.subplots(1, 2, figsize=(10, 4.2))
    axes[0].scatter(backbone[:, 0], backbone[:, 1], c=burial_norm, cmap="viridis", s=90, edgecolors="#333")
    axes[0].set_title("3D Helix Bundle Burial Score (Top View)")
    axes[0].set_xlabel("X (A)")
    axes[0].set_ylabel("Y (A)")
    axes[0].axis("equal")
    
    for cls_id, (lbl, col) in enumerate([("Hydrophobic Core", "#f39c12"), ("Polar Surface", "#3498db"), ("Charged Exterior", "#27ae60")]):
        m = s_low == cls_id
        axes[1].scatter(backbone[m, 0], backbone[m, 1], color=col, s=90, edgecolors="#333", label=lbl)
    axes[1].set_title("Inverse-Folded Design (T = 0.25)")
    axes[1].set_xlabel("X (A)")
    axes[1].axis("equal")
    axes[1].legend(fontsize=8)
    plt.tight_layout()
    plt.show()
    

  2. Implement a conditional rigid-frame diffusion toy model in JAX over 2D residue frames \((x_i, y_i, \theta_i) \in SE(2)\) that denoises a random cloud of frames into a complementary binder arc nestled against a fixed target receptor pocket, visualising snapshots across reverse diffusion timesteps.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # Fixed target receptor surface (a curved binding groove)
    t_tgt = jnp.linspace(-1.4, 1.4, 12)
    target_xy = jnp.stack([t_tgt * 2.2, -1.6 - 0.55 * (t_tgt ** 2)], axis=-1)
    
    # Ideal conditional binder backbone nestled snugly above the target groove
    n_res = 12
    s = jnp.linspace(-1.2, 1.2, n_res)
    ideal_xy = jnp.stack([s * 2.0, 0.35 - 0.48 * (s ** 2)], axis=-1)
    tang = jnp.concatenate([ideal_xy[1:] - ideal_xy[:-1], ideal_xy[-1:] - ideal_xy[-2:-1]], axis=0)
    ideal_th = jnp.arctan2(tang[:, 1], tang[:, 0])
    clean_feat = jnp.concatenate([ideal_xy, jnp.cos(ideal_th)[:, None], jnp.sin(ideal_th)[:, None]], axis=-1)
    
    # Train a conditional denoiser using random nonlinear features + ridge regression
    key = jax.random.PRNGKey(0)
    n_train, d_in, d_hid = 220, n_res * 4 + 1, 96
    k_w, k_b, k_t, k_n, k_j = jax.random.split(key, 5)
    W_rand = jax.random.normal(k_w, (d_in, d_hid)) * 0.25
    b_rand = jax.random.normal(k_b, (d_hid,)) * 0.2
    
    ts = jax.random.uniform(k_t, (n_train, 1), minval=0.05, maxval=1.0)
    jit_xy = clean_feat[None, :, :2] + 0.12 * jax.random.normal(k_j, (n_train, n_res, 2))
    targets = jnp.concatenate([jit_xy, jnp.broadcast_to(clean_feat[None, :, 2:], (n_train, n_res, 2))], axis=-1)
    noise = jax.random.normal(k_n, targets.shape)
    noisy = jnp.sqrt(1.0 - ts[:, :, None]) * targets + jnp.sqrt(ts[:, :, None]) * noise * 2.2
    
    X_in = jnp.concatenate([noisy.reshape(n_train, -1), ts], axis=-1)
    H = jax.nn.tanh(jnp.dot(X_in, W_rand) + b_rand)
    Y_tr = targets.reshape(n_train, -1)
    W_out = jnp.linalg.solve(jnp.dot(H.T, H) + 1.5 * jnp.eye(d_hid), jnp.dot(H.T, Y_tr))
    
    def predict_clean(x_feat, t_scalar):
        inp = jnp.concatenate([x_feat.ravel(), jnp.array([t_scalar])])
        h = jax.nn.tanh(jnp.dot(inp, W_rand) + b_rand)
        return jnp.dot(h, W_out).reshape(n_res, 4)
    
    # Reverse denoising sampling from pure noise cloud (t=1.0 -> t=0.0)
    rng = jax.random.PRNGKey(999)
    x = jax.random.normal(rng, (n_res, 4)) * 2.2
    snapshots = {}
    steps = 40
    for i in range(steps, 0, -1):
        t = i / steps
        t_prev = (i - 1) / steps
        if i in (40, 22, 8):
            snapshots[i] = x
        pred_x0 = predict_clean(x, t)
        rng, k_step = jax.random.split(rng)
        eps = jax.random.normal(k_step, x.shape) * (0.35 * jnp.sqrt(t_prev))
        alpha = 1.0 - (t_prev / (t + 1e-6))
        x = (1.0 - alpha) * x + alpha * pred_x0 + eps * (0.25 if i > 1 else 0.0)
    snapshots[0] = x
    
    final_rmsd = float(jnp.sqrt(jnp.mean(jnp.sum((snapshots[0][:, :2] - ideal_xy) ** 2, axis=-1))))
    print(f"Denoised binder backbone RMSD to ideal pocket geometry {final_rmsd:.3f} A")
    
    fig, axes = plt.subplots(1, 4, figsize=(12, 3.2))
    for ax, step_id in zip(axes, [40, 22, 8, 0]):
        pts = snapshots[step_id]
        ax.plot(target_xy[:, 0], target_xy[:, 1], "s-", color="#e74c3c", lw=2.5, ms=5, label="Target")
        ax.plot(pts[:, 0], pts[:, 1], "o-", color="#3498db", lw=1.8, ms=4, label="Binder")
        th_n = pts[:, 2:] / (jnp.linalg.norm(pts[:, 2:], axis=-1, keepdims=True) + 1e-6)
        ax.quiver(pts[:, 0], pts[:, 1], th_n[:, 0], th_n[:, 1], color="#9b59b6", scale=12, width=0.012)
        ax.set_title(f"Step t = {step_id / steps:.2f}")
        ax.set_xlim(-5.5, 5.5)
        ax.set_ylim(-4.5, 4.5)
    axes[0].legend(fontsize=7.5, loc="upper left")
    plt.tight_layout()
    plt.show()
    

  3. Simulate ML-guided directed evolution inside a \(6\)-round Design-Build-Test-Learn loop on a synthetic epistatic enzyme fitness landscape, comparing an uncertainty-aware JAX ensemble surrogate (UCB acquisition) against random mutagenesis under an identical wet-lab assay budget.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    key = jax.random.PRNGKey(55)
    L, A, batch_size, n_rounds = 10, 4, 16, 6
    
    def one_hot(seqs, depth):
        return jnp.eye(depth, dtype=jnp.float32)[seqs]
    
    # Construct a rugged epistatic ground-truth fitness landscape (additive + pairwise couplings)
    k1, k2 = jax.random.split(key)
    h_add = jax.random.normal(k1, (L, A)) * 0.45
    J_epi = jax.random.normal(k2, (L, L, A, A)) * 0.30
    J_epi = J_epi * jnp.triu(jnp.ones((L, L)), k=1)[:, :, None, None]
    
    def true_fitness(seqs):
        oh = one_hot(seqs, A)
        return jnp.einsum("nla,la->n", oh, h_add) + jnp.einsum("nia,njb,ijab->n", oh, oh, J_epi)
    
    # Candidate pool of 2,500 variants around a wild-type enzyme
    wt = jnp.zeros((L,), dtype=jnp.int32)
    k_pool1, k_pool2 = jax.random.split(jax.random.PRNGKey(77))
    mut_mask = jax.random.uniform(k_pool1, (2500, L)) < 0.35
    rand_aa = jax.random.randint(k_pool2, (2500, L), 0, A)
    pool = jnp.where(mut_mask, rand_aa, wt[None, :])
    pool_oh = one_hot(pool, A).reshape(2500, -1)
    pool_y = true_fitness(pool)
    oracle_best = float(jnp.max(pool_y))
    
    # 5-member nonlinear random-feature ridge ensemble for fast calibrated uncertainty
    def fit_and_predict(X_tr, y_tr, X_eval, seed):
        preds = []
        n_tr, d_hid = X_tr.shape[0], 48
        for m in range(5):
            kw, kb, kboot = jax.random.split(jax.random.PRNGKey(seed * 20 + m), 3)
            W = jax.random.normal(kw, (L * A, d_hid)) * 0.4
            b = jax.random.normal(kb, (d_hid,)) * 0.2
            boot = jax.random.randint(kboot, (n_tr,), 0, n_tr)
            H_tr = jax.nn.relu(jnp.dot(X_tr[boot], W) + b)
            w_out = jnp.linalg.solve(jnp.dot(H_tr.T, H_tr) + 0.5 * jnp.eye(d_hid), jnp.dot(H_tr.T, y_tr[boot]))
            H_ev = jax.nn.relu(jnp.dot(X_eval, W) + b)
            preds.append(jnp.dot(H_ev, w_out))
        arr = jnp.stack(preds, axis=0)
        return jnp.mean(arr, axis=0), jnp.std(arr, axis=0)
    
    # Run 6 DBTL rounds comparing ML-guided UCB vs random mutagenesis
    ml_tested = list(range(batch_size))
    rand_tested = list(range(batch_size))
    ml_best_hist = [float(jnp.max(pool_y[jnp.array(ml_tested)]))]
    rand_best_hist = [float(jnp.max(pool_y[jnp.array(rand_tested)]))]
    
    for rd in range(1, n_rounds + 1):
        idx_arr = jnp.array(ml_tested)
        mu, sigma = fit_and_predict(pool_oh[idx_arr], pool_y[idx_arr], pool_oh, seed=rd)
        ucb = mu + 0.8 * sigma
        seen_mask = jnp.isin(jnp.arange(2500), idx_arr)
        ucb_masked = jnp.where(seen_mask, -1e9, ucb)
        ml_tested.extend([int(i) for i in jnp.argsort(ucb_masked)[-batch_size:]])
        ml_best_hist.append(float(jnp.max(pool_y[jnp.array(ml_tested)])))
    
        kr = jax.random.PRNGKey(800 + rd)
        rand_tested.extend([int(i) for i in jax.random.randint(kr, (batch_size,), 0, 2500)])
        rand_best_hist.append(float(jnp.max(pool_y[jnp.array(rand_tested)])))
    
    print(f"After {n_rounds} DBTL rounds -> ML-guided peak {ml_best_hist[-1]:.2f} vs Random {rand_best_hist[-1]:.2f} (Oracle {oracle_best:.2f})")
    
    rounds_x = list(range(n_rounds + 1))
    plt.figure(figsize=(7.5, 4.2))
    plt.plot(rounds_x, ml_best_hist, "o-", color="#27ae60", lw=2.4, label="ML-Guided DBTL (Ensemble UCB)")
    plt.plot(rounds_x, rand_best_hist, "s--", color="#e74c3c", lw=2.0, label="Random Mutagenesis Baseline")
    plt.axhline(oracle_best, color="#333", ls=":", lw=1.4, label="Global Landscape Optimum")
    plt.title("Closed-Loop Enzyme Optimisation on an Epistatic Landscape")
    plt.xlabel("DBTL Lab Round (16 Assays per Round)")
    plt.ylabel("Best Discovered Enzyme Fitness")
    plt.legend()
    plt.grid(alpha=0.25)
    plt.tight_layout()
    plt.show()