Skip to content

Molecular Docking and Binding Affinity

Knowing what a molecule looks like in three dimensions is only half the story, because a medicine only works if it settles snugly into the right biological target and stays there long enough to shift a disease pathway. This file unpacks how small molecules recognise flexible protein pockets, how binding thermodynamics links free energy to experimental potency, how classical physics docking evolved into neural diffusion and all-atom co-folding, and how Free Energy Perturbation and physical checks like PoseBusters separate true binders from geometric illusions.

  • Imagine trying to silence a noisy alarm clock inside a dark room by wedging a tiny pebble between two spinning brass gears. To succeed, the pebble must fit the gap cleanly without bumping the casing, cling tightly enough to resist vibration, and ignore every other clock on the shelf. That, in miniature, is what a small-molecule drug does inside the human body.

  • Most modern medicines work by binding non-covalently to a specific three-dimensional groove, called a binding pocket or active site, on a target protein such as an enzyme, ion channel, or cell-surface receptor. Predicting where a candidate ligand sits inside that pocket is molecular docking, and predicting how tightly it clings once seated is binding affinity prediction.

How Drugs Work, Lock and Key versus Induced Fit

  • Picture slipping a rigid brass key into a steel padlock. In 1894, chemist Emil Fischer proposed this famous lock-and-key model to explain why enzymes recognise one substrate while ignoring thousands of lookalikes. Complementary shape and matching electrical charges let the right ligand click neatly into a pre-formed protein cavity.

  • Now picture sliding your bare hand into a soft leather driving glove instead. Neither your hand nor the glove is rigid. As your fingers push in, the leather stretches and moulds around your knuckles while your fingers curl slightly to match the seams. In 1958, Daniel Koshland captured this biological reality in the induced-fit model, recognising that both the ligand and the protein side chains (and sometimes whole protein loops) flex dynamically as they meet. A closely related view, conformational selection, notes that a protein continuously breathes through an ensemble of shapes in solution and the ligand selectively traps the shape that fits it best.

  • What actually holds a drug inside its pocket once it arrives? Instead of permanent covalent welds (except in specialised covalent inhibitors), most drugs rely on a choir of gentle non-covalent interactions working in concert.

  • Hydrogen bonds act like directional microscopic magnets between an electronegative donor (such as an \(-\text{NH}\) or \(-\text{OH}\) group) and a lone-pair acceptor (such as a carbonyl oxygen \(= \text{O}\) or ring nitrogen).
  • Hydrophobic packing tucks oily, non-polar carbon rings away from surrounding water into grease-lined crevices of the pocket.
  • Electrostatic salt bridges and \(\pi\)-stacking pair opposite formal charges or align flat aromatic rings against tyrosine, phenylalanine, and tryptophan side chains.
  • Steric clashes act as hard bouncers, because trying to push two electron clouds into the same volume raises repulsive energy astronomically (scaling like \(r^{-12}\) in a Lennard-Jones potential).

Binding Thermodynamics and Affinity Metrics

  • Think of a bustling dance floor where protein molecules \(P\) and ligand molecules \(L\) constantly pair up into bound complexes \(PL\) and drift apart again. Binding is never a one-way trap. It is a dynamic reversible equilibrium \(P + L \rightleftharpoons PL\) characterised by the equilibrium dissociation constant \(K_d\).
\[K_d = \frac{[P][L]}{[PL]}\]
  • Notice the units and direction of \(K_d\). It is measured in molar concentration (\(\text{M}\)), and it equals the exact ligand concentration at which half of all protein pockets are occupied. A smaller \(K_d\) therefore signals a tighter binder. Early screening hits often sit around \(10\,\mu\text{M}\) (\(10^{-5}\,\text{M}\)), promising leads tighten to \(100\,\text{nM}\) (\(10^{-7}\,\text{M}\)), and potent clinical drugs frequently reach low nanomolar (\(1\text{–}10\,\text{nM}\)) or even picomolar (\(10^{-12}\,\text{M}\)) affinity.

  • Statistical mechanics ties this experimental concentration ratio directly to the Gibbs free energy of binding \(\Delta G\) (measured in \(\text{kcal/mol}\) or \(\text{kJ/mol}\)), which splits into an enthalpic term \(\Delta H\) and an entropic term \(-T\Delta S\).

\[\Delta G = \Delta H - T\Delta S = RT \ln\!\left(\frac{K_d}{c^\circ}\right)\]
  • Here \(R \approx 1.987 \times 10^{-3}\,\text{kcal/(mol}\cdot\text{K)}\) is the ideal gas constant, \(T\) is absolute temperature, and \(c^\circ = 1\,\text{M}\) is the standard reference concentration (often left implicit when writing \(\Delta G = RT \ln K_d\)). A more negative \(\Delta G\) means stronger spontaneous binding.
  • Enthalpy (\(\Delta H\)) reflects the net heat released when new hydrogen bonds, salt bridges, and van der Waals contacts form inside the pocket minus the energetic cost of stripping water molecules away from the polar surfaces of both ligand and protein (desolvation).
  • Entropy (\(-T\Delta S\)) captures a subtle tug of war. Pinning a floppy ligand with many rotatable bonds inside a tight pocket freezes its motion and costs unfavourable conformational entropy (\(\Delta S < 0\)). Conversely, freeing ordered cages of water molecules trapped inside an oily hydrophobic pocket releases massive solvent entropy (\(\Delta S > 0\)), driving the celebrated hydrophobic effect.
  • Because tightening bonds often restricts molecular motion at the same time, medicinal chemists frequently wrestle with enthalpy-entropy compensation, where gaining a favourable hydrogen bond barely improves \(\Delta G\) because the complex becomes stiffer.

  • Plugging in room temperature (\(T = 298.15\,\text{K}\)) reveals one of the most useful rules of thumb in all of drug discovery. Since \(RT \approx 0.592\,\text{kcal/mol}\) and \(\ln(10) \approx 2.303\), every ten-fold improvement in binding affinity corresponds to a free energy change of

\[\Delta \Delta G_{10\times} = -RT \ln(10) \approx -1.36\,\text{kcal/mol}\]
  • Pause and appreciate how unforgiving that number is. Improving a drug's binding free energy by roughly \(1.4\,\text{kcal/mol}\) (barely the margin of a single well-aligned hydrogen bond, and smaller than the typical error of many computational predictors) makes the molecule 10 times more potent. Pushing from a weak \(10\,\mu\text{M}\) hit (\(\Delta G \approx -6.8\,\text{kcal/mol}\)) to a potent \(10\,\text{nM}\) drug (\(\Delta G \approx -10.9\,\text{kcal/mol}\)) requires winning just three of those \(1.36\,\text{kcal/mol}\) steps.

  • In wet-lab biochemistry and machine learning benchmarks, you will encounter two closely related potency metrics alongside \(K_d\).

  • \(IC_{50}\) is the inhibitor concentration required to cut a target enzyme's biological activity by 50% in a functional assay. Unlike \(K_d\), \(IC_{50}\) depends on how much natural substrate \([S]\) competes with the drug in the test tube (linked via the Cheng-Prusoff equation \(K_i = IC_{50} / (1 + [S]/K_m)\) for competitive inhibitors).
  • \(pK_d = -\log_{10}(K_d)\) (and similarly \(pIC_{50}\) or \(pK_i\), with concentrations in molar units) converts tiny exponential numbers into a clean linear scale. A \(1\,\mu\text{M}\) binder has \(pK_d = 6\), a \(100\,\text{nM}\) binder has \(pK_d = 7\), and a \(10\,\text{nM}\) binder has \(pK_d = 8\). Because \(pK_d\) is strictly proportional to \(-\Delta G\), machine learning models almost always train on \(pK_d\) or \(\Delta G\) rather than raw \(K_d\).

Structure-Based Virtual Screening and Classical Docking

  • Imagine a master locksmith testing ten thousand blank keys inside an intricate lock, rotating the wrist, sliding the blade deeper or shallower, and jiggling the hinges until every tumbler clicks cleanly. Structure-based virtual screening (SBVS) runs this exact search computationally, taking an experimental 3D structure (from X-ray crystallography or cryo-EM) or an AlphaFold prediction of a protein pocket and docking millions or even billions of catalogue compounds to shortlist the most promising candidates for lab testing.

  • Classical physics-based docking tools such as AutoDock Vina split the problem into two cleanly separated ingredients, a search algorithm and a scoring function.

  • The search space describes every physically valid pose of a flexible ligand inside a rigid (or slightly side-chain-flexible) protein box. A rigid body has 3 translational coordinates \(\mathbf{t} \in \mathbb{R}^3\) and 3 orientational degrees of freedom \(R \in SO(3)\). Adding \(m\) rotatable single bonds inside the ligand introduces \(m\) internal torsion angles \(\boldsymbol{\tau} \in [0, 2\pi)^m\), giving a \((6 + m)\)-dimensional non-convex energy landscape. Vina explores this space using iterated global Monte Carlo perturbations interleaved with fast local gradient-based Broyden-Fletcher-Goldfarb-Shanno (BFGS) refinements.
  • The empirical scoring function estimates binding free energy \(\hat{E}\) from pairwise interatomic distances \(d_{ij}\) between protein atom \(i\) and ligand atom \(j\) (adjusted for their van der Waals radii \(r_i + r_j\)). Vina combines attractive Gaussian steric wells, a quadratic repulsive wall for clashes, a hydrophobic burial bonus, and a directional hydrogen-bond bonus, finally dividing the raw contact score by a conformational entropy penalty \(1 + w_{\text{rot}} N_{\text{rot}}\) that penalises overly floppy ligands with many rotatable bonds \(N_{\text{rot}}\).

Diagram comparing ligand pose degrees of freedom in translation, rotation, and rotatable torsions inside a flexible binding pocket alongside the evolution from classical AutoDock Vina search to DiffDock manifold diffusion and AlphaFold 3 co-folding

  • Classical docking shines because it is blazingly fast (a few seconds per molecule on a CPU), grounded in physical geometry, and requires no target-specific training labels. Yet it carries clear blind spots. Treating the protein pocket as mostly frozen misses induced-fit rearrangements, implicit solvent terms struggle with tightly bound structural water molecules that bridge hydrogen bonds, and empirical scores correlate only weakly with true experimental \(\Delta G\). Virtual screening is therefore great at enriching true binders over random decoys, yet poor at ranking two close analogues within \(1\,\text{kcal/mol}\).

Neural Docking and All-Atom Co-Folding

  • Instead of rattling a rigid key through thousands of random trials inside a dark lock, imagine watching a blurry cloud of dust gently swirl and settle straight into the exact resting shape of a ligand inside the pocket. That generative perspective sparked a dramatic shift from search-and-score docking to learned geometric inference.

  • DiffDock (Corso et al., 2023) reframed blind docking (where even the pocket location on the protein surface is unknown) as a score-based diffusion model (Chapter 06). Rather than diffusing every ligand atom freely in unconstrained 3D space (which can scramble bond lengths and tear aromatic rings apart), DiffDock defines forward noising and reverse denoising strictly on the physically valid product manifold

\[\mathcal{M} = \mathbb{R}^3 \times SO(3) \times \mathbb{T}^m\]
  • At each denoising step, an \(SE(3)\)-equivariant graph neural network looks at the protein pocket and noisy ligand pose, then predicts three coupled score vectors, a translation drift in \(\mathbb{R}^3\), a rotational angular update on the Lie group \(SO(3)\), and angular torsion twists on the \(m\)-dimensional torus \(\mathbb{T}^m\). Crucially, because a protein may have multiple plausible binding pockets, DiffDock draws dozens of independent candidate poses from the learned distribution and passes them to a separate confidence model trained to predict which sample lies within \(2\,\text{\AA}\) RMSD of the true crystal pose.

  • Even manifold docking still treats the receptor as a fixed statue. All-atom co-folding models such as AlphaFold 3 (Abramson et al., 2024), Boltz-1 (MIT and Recursion, 2024, released under a permissive MIT open-source licence), Boltz-2 (2025), and Chai-1 dismantle that boundary entirely. Given a protein amino-acid sequence alongside the molecular graph of a small-molecule ligand (plus ions, DNA, or RNA), these models run a shared Pairformer trunk to reason over residue-residue and residue-atom couplings, then feed the resulting representations into an all-atom diffusion module that denoises every heavy atom of both protein and ligand simultaneously in 3D space. Because the protein side chains and loops fold around the drug during generation, co-folding models naturally represent induced fit from first principles, and Boltz-2 further adds steerable method conditioning, template guidance, and pocket constraints.

Predicting Binding Affinity, FEP, ML Surrogates, and Physical Plausibility

  • Suppose you want to measure the tiny weight difference between two nearly identical hummingbird feathers. Stepping onto a bathroom scale while holding each feather gives noisy garbage, whereas placing both feathers on opposing pans of a balanced beam reveals the exact difference effortlessly. That exact insight underpins the gold standard of physics-based affinity prediction.

  • Simulating a drug physically entering and leaving a protein pocket through brute-force molecular dynamics (MD) takes milliseconds to seconds of simulated biological time, orders of magnitude beyond what standard atomistic simulations can afford. Free Energy Perturbation (FEP) sidesteps this barrier using a beautiful thermodynamic trick. Because Gibbs free energy is a state function (independent of the path taken between start and end), we can construct an alchemical thermodynamic cycle comparing two closely related analogues \(A\) and \(B\) that differ by a small chemical edit (such as swapping a hydrogen atom for a chlorine atom).

Side-by-side comparison of the room-temperature binding affinity ladder showing 1.36 kcal per mol per 10x change in Kd alongside the relative Free Energy Perturbation alchemical thermodynamic cycle connecting unbound and bound states of ligands A and B

  • Instead of dragging the molecules out of the pocket, FEP smoothly morphs ligand \(A\) into ligand \(B\) through non-physical intermediate potential energy functions \(U_\lambda(\mathbf{x})\) as a coupling parameter \(\lambda\) steps from \(0\) to \(1\). Doing this small alchemical morph once in bulk water (\(\Delta G_{\text{solv}}\)) and once inside the protein pocket (\(\Delta G_{\text{complex}}\)) yields the exact relative binding free energy difference
\[\Delta \Delta G_{\text{bind}}(A \to B) = \Delta G_{\text{bind}}(B) - \Delta G_{\text{bind}}(A) = \Delta G_{\text{complex}}(A \to B) - \Delta G_{\text{solv}}(A \to B)\]
  • Each leg is computed from equilibrium molecular dynamics snapshots using the Zwanzig equation (and in modern practice across multiple overlapping \(\lambda\) windows using the statistically optimal Bennett Acceptance Ratio or MBAR estimator).
\[\Delta G_{A \to B} = -k_B T \ln \left\langle \exp\!\left(-\frac{U_B(\mathbf{x}) - U_A(\mathbf{x})}{k_B T}\right) \right\rangle_A\]
  • Here \(\langle \cdot \rangle_A\) denotes an average over conformations sampled from the Boltzmann distribution of state \(A\), and \(k_B T\) plays the per-molecule role of \(RT\). When the starting binding pose is trustworthy and force-field parameters are well calibrated, commercial and open-source FEP pipelines routinely achieve errors around \(0.8\text{–}1.2\,\text{kcal/mol}\), sharp enough to guide real medicinal chemistry teams toward 10x potency gains before anyone steps up to a fume hood.

  • The catch with FEP is compute cost and scope. Running dozens of GPU hours per compound pair is unbeatable during final lead optimisation, yet far too slow to score ten million virtual hits. Machine learning affinity surrogates (3D convolutional grids, \(SE(3)\)-equivariant GNNs, and joint co-folding affinity modules) bridge this speed gap. Notably, Boltz-2 attaches a dedicated binding-affinity head directly to its biomolecular co-folding trunk, approaching FEP accuracy on major lead-optimisation benchmarks while running up to \(1{,}000\times\) faster. Even so, practitioners must stay sceptical of benchmark leaderboards. Standard datasets like PDBbind contain strong hidden sequence and scaffold leaks, so models that look brilliant on random splits often memorise ligand-only properties or nearest-neighbour training pockets and stumble badly when tested on truly novel protein families. Increasingly, winning drug discovery pipelines pair fast ML triage (or active-learning FEP) with rigorous physics recalculation at the top of the funnel.

  • Finally, high geometric accuracy on a single metric can hide shocking physical nonsense. In a landmark audit called PoseBusters (Buttenschoen et al., 2024), researchers inspected top poses from early deep learning docking models that looked great by standard root-mean-square deviation (\(\text{RMSD} < 2\,\text{\AA}\)). Beneath the hood, many neural poses pushed ligand atoms straight through protein side chains, warped flat aromatic rings into bent potato chips, stretched covalent bonds to impossible lengths, or accidentally inverted chiral stereocentres into mirror-image molecules. Running automated physical plausibility suites (checking bond lengths, bond angles, ring planarity, chirality, and interatomic steric clashes) and applying brief molecular-mechanics energy minimisation after neural prediction has quickly become a mandatory safety rail across computational drug design.

Take-Home

  • Drug recognition is dynamic induced fit rather than a static lock and key, held together by a delicate balance of directional hydrogen bonds, hydrophobic burial, electrostatics, and hard steric repulsion.
  • Small energy shifts drive massive potency leaps, because \(\Delta G = \Delta H - T\Delta S = RT \ln K_d\) implies that strengthening binding by just \(1.36\,\text{kcal/mol}\) at room temperature yields a ten-fold tighter \(K_d\) (one unit of \(pK_d\)).
  • Docking has evolved from rigid search to joint all-atom diffusion, progressing from empirical physics engines like AutoDock Vina to manifold diffusion over \(\mathbb{R}^3 \times SO(3) \times \mathbb{T}^m\) (DiffDock) and flexible protein-ligand co-folding (AlphaFold 3 and Boltz).
  • Relative FEP exploits thermodynamic cycles for high precision, mutating ligand \(A\) into analogue \(B\) in water and in the pocket to reach roughly \(1\,\text{kcal/mol}\) accuracy, complementing fast ML surrogates that triage massive chemical libraries.
  • Physical plausibility checks like PoseBusters are non-negotiable, because RMSD alone misses steric clashes, distorted bond geometries, and flipped chirality in unconstrained neural structure predictions.

Coding Tasks (use CoLab or notebook)

  1. Explore binding thermodynamics and enthalpy-entropy compensation across drug-discovery potency regimes from \(100\,\mu\text{M}\) to \(100\,\text{pM}\). Verify numerically that every \(10\times\) tighter \(K_d\) corresponds to \(-1.36\,\text{kcal/mol}\) at \(298.15\,\text{K}\) and plot the non-linear \(K_d\) curve against the linear \(pK_d\) and \(\Delta G\) scales.

    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # Thermodynamic constants at room temperature (298.15 K)
    R_kcal = 1.9872e-3  # kcal / (mol * K)
    T = 298.15
    RT = R_kcal * T
    
    # Potency sweep from 100 uM (1e-4 M) down to 100 pM (1e-10 M)
    pKd_vals = jnp.linspace(4.0, 10.0, 121)
    Kd_vals = 10.0 ** (-pKd_vals)
    dG_vals = RT * jnp.log(Kd_vals)
    
    # Verify exact 10x step change in Delta G (pKd increasing by 1.0)
    step_10x = float(RT * jnp.log(0.1))
    print(f"RT at 298.15 K = {RT:.4f} kcal/mol")
    print(f"10x tighter Kd (delta pKd = +1) changes Delta G by {step_10x:.3f} kcal/mol")
    for label, pkd in [("Early hit (10 uM)", 5.0), ("Lead (1 uM)", 6.0), ("Strong lead (100 nM)", 7.0), ("Drug (10 nM)", 8.0)]:
        dg = float(RT * jnp.log(10.0 ** (-pkd)))
        print(f"  {label:22s} -> pKd = {pkd:.1f}, Delta G = {dg:.2f} kcal/mol")
    
    # Compare three lead-optimisation strategies yielding the same 10 nM affinity
    strategies = ["Enthalpy-driven\n(H-bonds)", "Balanced\n(Ideal lead)", "Entropy-driven\n(Hydrophobic)"]
    dH = jnp.array([-14.5, -8.4, -3.2])
    minus_TdS = jnp.array([3.6, -2.5, -7.7])
    dG_total = dH + minus_TdS
    
    fig, axes = plt.subplots(1, 2, figsize=(10.5, 4))
    axes[0].plot(pKd_vals, dG_vals, color="#3498db", lw=2.5)
    for pkd, col in [(5.0, "#f39c12"), (6.0, "#3498db"), (7.0, "#9b59b6"), (8.0, "#27ae60")]:
        dg = float(RT * jnp.log(10.0 ** (-pkd)))
        axes[0].scatter([pkd], [dg], color=col, s=65, zorder=5)
    axes[0].set_xlabel("pKd = -log10(Kd)"); axes[0].set_ylabel("Delta G (kcal/mol)")
    axes[0].set_title("Linear Binding Free Energy vs pKd (298 K)"); axes[0].grid(alpha=0.3)
    
    x = jnp.arange(len(strategies))
    w = 0.25
    axes[1].bar(x - w, dH, width=w, color="#3498db", label="Enthalpy (Delta H)")
    axes[1].bar(x, minus_TdS, width=w, color="#f39c12", label="Entropy (-T Delta S)")
    axes[1].bar(x + w, dG_total, width=w, color="#27ae60", label="Total Delta G")
    axes[1].axhline(0.0, color="#333", lw=1)
    axes[1].set_xticks(x); axes[1].set_xticklabels(strategies, fontsize=8.5)
    axes[1].set_ylabel("Energy (kcal/mol)"); axes[1].set_title("Enthalpy-Entropy Profiles for Identical 10 nM Affinity")
    axes[1].legend(fontsize=8); axes[1].grid(axis="y", alpha=0.3)
    plt.tight_layout(); plt.show()
    

  2. Build a differentiable 2D flexible molecular docking engine in JAX. Place a 3-atom hinged ligand (with translation \(t_x, t_y\), global rotation \(\theta\), and internal bond torsion \(\phi\)) inside a U-shaped protein pocket featuring steric wall atoms, a hydrophobic patch, and a hydrogen-bond donor. Optimise poses from multiple random restarts using jax.grad and visualise the lowest-energy docked pose.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # Define a 2D U-shaped protein pocket: wall atoms, H-bond donor, hydrophobic centre
    angles = jnp.linspace(jnp.pi * 0.15, jnp.pi * 0.85, 11)
    pocket_wall = jnp.stack([2.6 * jnp.cos(angles), -2.4 * jnp.sin(angles) + 1.0], axis=1)
    hbond_site = jnp.array([-1.55, -0.35])     # Pocket H-bond donor
    hydro_site = jnp.array([1.25, -0.55])      # Pocket hydrophobic anchor
    
    def ligand_coords(pose):
        """Build 3-atom flexible ligand from pose = [tx, ty, theta, phi]."""
        tx, ty, theta, phi = pose[0], pose[1], pose[2], pose[3]
        L1, L2 = 1.35, 1.30
        a0 = jnp.array([tx, ty])                                        # Central hinge atom
        a1 = a0 + jnp.array([L1 * jnp.cos(theta), L1 * jnp.sin(theta)]) # Polar H-bond acceptor
        a2 = a0 + jnp.array([L2 * jnp.cos(theta + phi), L2 * jnp.sin(theta + phi)])  # Hydrophobic tail
        return jnp.stack([a0, a1, a2], axis=0)
    
    def docking_energy(pose):
        """Vina-inspired differentiable scoring function (steric + H-bond + hydrophobic + torsion)."""
        atoms = ligand_coords(pose)  # (3, 2)
        # Pairwise distances between 3 ligand atoms and pocket wall atoms
        diff = atoms[:, None, :] - pocket_wall[None, :, :]
        dist = jnp.sqrt(jnp.sum(diff ** 2, axis=-1) + 1e-6)
        # Soft Lennard-Jones-like steric interaction (optimal wall clearance ~ 1.15)
        steric_rep = jnp.sum(jnp.where(dist < 1.05, 8.0 * (1.05 - dist) ** 2, 0.0))
        vdw_attr = -0.35 * jnp.sum(jnp.exp(-((dist - 1.35) / 0.55) ** 2))
        # Specific H-bond attraction on atom 1 and hydrophobic packing on atom 2
        d_hb = jnp.sqrt(jnp.sum((atoms[1] - hbond_site) ** 2) + 1e-6)
        d_hy = jnp.sqrt(jnp.sum((atoms[2] - hydro_site) ** 2) + 1e-6)
        e_hbond = -3.8 * jnp.exp(-((d_hb - 0.55) / 0.65) ** 2)
        e_hydro = -2.6 * jnp.exp(-(d_hy / 0.90) ** 2)
        # Keep ligand inside binding box + gentle preferred internal bond angle around 2.1 rad
        e_torsion = 0.6 * (jnp.cos(pose[3]) - jnp.cos(2.1)) ** 2
        e_box = 0.08 * jnp.sum(atoms[0] ** 2)
        return steric_rep + vdw_attr + e_hbond + e_hydro + e_torsion + e_box
    
    grad_energy = jax.grad(docking_energy)
    
    # Multi-start gradient-based docking search (10 random initial poses)
    key = jax.random.PRNGKey(7)
    best_energy, best_pose, best_hist = 1e9, None, None
    all_finals = []
    
    for r in range(10):
        key, k1, k2 = jax.random.split(key, 3)
        xy = jax.random.uniform(k1, (2,), minval=-1.2, maxval=1.2)
        ang = jax.random.uniform(k2, (2,), minval=-jnp.pi, maxval=jnp.pi)
        pose = jnp.concatenate([xy, ang])
        hist = []
        for step in range(160):
            e = float(docking_energy(pose))
            hist.append(e)
            g = grad_energy(pose)
            g_norm = jnp.sqrt(jnp.sum(g ** 2) + 1e-8)
            pose = pose - 0.04 * g / jnp.maximum(g_norm, 1.0)
        final_e = float(docking_energy(pose))
        all_finals.append(final_e)
        if final_e < best_energy:
            best_energy, best_pose, best_hist = final_e, pose, hist
    
    print(f"Best docked energy across 10 restarts: {best_energy:.3f} kcal/mol (median={float(jnp.median(jnp.array(all_finals))):.3f})")
    best_atoms = ligand_coords(best_pose)
    
    fig, axes = plt.subplots(1, 2, figsize=(10.5, 4))
    axes[0].plot(best_hist, color="#9b59b6", lw=2.2)
    axes[0].set_xlabel("Optimisation Step"); axes[0].set_ylabel("Docking Score (kcal/mol)")
    axes[0].set_title("Pose Energy Minimisation Trajectory"); axes[0].grid(alpha=0.3)
    
    axes[1].plot(pocket_wall[:, 0], pocket_wall[:, 1], "-o", color="#3498db", lw=3, ms=8, alpha=0.75, label="Protein pocket")
    axes[1].scatter([hbond_site[0]], [hbond_site[1]], color="#27ae60", s=120, marker="*", zorder=6, label="H-bond site")
    axes[1].scatter([hydro_site[0]], [hydro_site[1]], color="#f39c12", s=110, marker="s", alpha=0.8, zorder=5, label="Hydrophobic site")
    axes[1].plot([best_atoms[1, 0], best_atoms[0, 0], best_atoms[2, 0]],
                 [best_atoms[1, 1], best_atoms[0, 1], best_atoms[2, 1]], color="#333", lw=3, zorder=6)
    axes[1].scatter([best_atoms[0, 0]], [best_atoms[0, 1]], color="#333", s=70, zorder=7)
    axes[1].scatter([best_atoms[1, 0]], [best_atoms[1, 1]], color="#e74c3c", s=95, zorder=7, label="Ligand acceptor (O)")
    axes[1].scatter([best_atoms[2, 0]], [best_atoms[2, 1]], color="#9b59b6", s=95, zorder=7, label="Ligand greasy tail")
    axes[1].set_aspect("equal"); axes[1].set_title(f"Best Docked Pose (E = {best_energy:.2f} kcal/mol)")
    axes[1].legend(fontsize=7.5, loc="upper right"); axes[1].grid(alpha=0.3)
    plt.tight_layout(); plt.show()
    

  3. Simulate a relative Free Energy Perturbation (FEP) thermodynamic cycle using the Zwanzig exponential averaging equation. Compare naive one-step FEP (which suffers high variance when states \(A\) and \(B\) barely overlap) against multi-window stratified FEP across intermediate \(\lambda\) stages, and verify convergence against the exact analytical \(\Delta \Delta G_{\text{bind}}\).

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # 1D harmonic-well binding model where exact free energy is known analytically:
    # U(x) = u0 + 0.5 * k * (x - mu)^2  =>  G = u0 + 0.5 * kT * ln(k / (2 pi kT))
    kT = 0.592  # kcal/mol at 298 K
    
    # Ligand A -> Ligand B in bulk water (solv) and inside the protein pocket (comp)
    # Ligand B shifts equilibrium position and stiffens inside the pocket, gaining deeper well depth
    solv_A = (0.0, 1.0, 0.0)     # (u0, k, mu)
    solv_B = (-0.4, 1.4, 0.9)
    comp_A = (-7.0, 1.6, 0.0)
    comp_B = (-9.3, 3.2, 1.1)
    
    def exact_dG(stateA, stateB):
        uA, kA, _ = stateA
        uB, kB, _ = stateB
        return (uB - uA) + 0.5 * kT * jnp.log(kB / kA)
    
    exact_solv = float(exact_dG(solv_A, solv_B))
    exact_comp = float(exact_dG(comp_A, comp_B))
    exact_ddG = exact_comp - exact_solv
    
    def interp_state(stateA, stateB, lam):
        """Linearly interpolate harmonic potential parameters along alchemical coordinate lambda."""
        uA, kA, mA = stateA
        uB, kB, mB = stateB
        return ((1.0 - lam) * uA + lam * uB,
                (1.0 - lam) * kA + lam * kB,
                (1.0 - lam) * mA + lam * mB)
    
    def potential(x, state):
        u0, k, mu = state
        return u0 + 0.5 * k * (x - mu) ** 2
    
    def fep_windows(key, stateA, stateB, n_windows, n_samples):
        """Compute Delta G(A -> B) by summing Zwanzig estimators over n_windows lambda intervals."""
        lams = jnp.linspace(0.0, 1.0, n_windows + 1)
        total_dG = 0.0
        for w in range(n_windows):
            key, subkey = jax.random.split(key)
            s0 = interp_state(stateA, stateB, float(lams[w]))
            s1 = interp_state(stateA, stateB, float(lams[w + 1]))
            # Exact Boltzmann samples from Gaussian p0(x) ~ N(mu0, kT / k0)
            sigma0 = jnp.sqrt(kT / s0[1])
            x = s0[2] + sigma0 * jax.random.normal(subkey, (n_samples,))
            dU = potential(x, s1) - potential(x, s0)
            # Numerically stable log-mean-exp for Zwanzig equation: -kT * ln <exp(-dU / kT)>
            scaled = -dU / kT
            m = jnp.max(scaled)
            dG_w = -kT * (m + jnp.log(jnp.mean(jnp.exp(scaled - m))))
            total_dG = total_dG + float(dG_w)
        return total_dG
    
    # Run repeated trials for 1, 2, 4, 8, and 16 alchemical windows (fixed total sample budget = 4000)
    window_counts = [1, 2, 4, 8, 16]
    key = jax.random.PRNGKey(101)
    means, stds = [], []
    
    for nw in window_counts:
        n_per_w = 4000 // nw
        trials = []
        for _ in range(25):
            key, k_s, k_c = jax.random.split(key, 3)
            dg_s = fep_windows(k_s, solv_A, solv_B, nw, n_per_w)
            dg_c = fep_windows(k_c, comp_A, comp_B, nw, n_per_w)
            trials.append(dg_c - dg_s)
        arr = jnp.array(trials)
        means.append(float(jnp.mean(arr)))
        stds.append(float(jnp.std(arr)))
        print(f"Windows={nw:2d} (n={n_per_w:4d}/win) -> Est ddG = {means[-1]:+.3f} +/- {stds[-1]:.3f} kcal/mol (Exact = {exact_ddG:+.3f})")
    
    plt.figure(figsize=(8, 4))
    plt.errorbar(window_counts, means, yerr=stds, fmt="-o", color="#9b59b6", lw=2.2, capsize=5, label="Stratified Zwanzig FEP (mean +/- std)")
    plt.axhline(exact_ddG, color="#27ae60", lw=2, linestyle="--", label=f"Exact analytical ddG ({exact_ddG:.3f} kcal/mol)")
    plt.xscale("log", base=2); plt.xticks(window_counts, [str(w) for w in window_counts])
    plt.xlabel("Number of Alchemical Lambda Windows (Fixed Total Sample Budget)")
    plt.ylabel("Relative Binding Free Energy ddG (kcal/mol)")
    plt.title("Why Multi-Window Alchemical FEP Beats Direct One-Step Perturbation")
    plt.legend(); plt.grid(alpha=0.3); plt.tight_layout(); plt.show()