Skip to content

Generative Chemistry and Retrosynthesis

Virtual screening can only discover medicines that already sit inside a finite catalogue, whereas drug-like chemical space holds roughly \(10^{60}\) valid small molecules waiting to be invented. This file explores how generative models design bespoke drugs across strings, graphs, and 3D protein pockets, how reinforcement learning balances competing medicinal properties, why synthetic accessibility separates real drug candidates from unbuildable daydreams, and how computer-aided retrosynthesis and robotic labs close the discovery loop.

  • Imagine looking for a custom-tailored winter coat by rifling through a thrift shop rack of a million second-hand jackets. Even with a giant warehouse, the odds are slim that any single garment matches your exact arm length, shoulder width, fabric warmth, and waterproof rating all at once. Virtual screening from Section 4 is that giant thrift shop. Even modern make-on-demand libraries of tens of billions of molecules cover less than a single dust speck of the estimated \(10^{60}\) drug-like small molecules allowed by organic chemistry.

  • De novo generative chemistry flips the problem on its head. Instead of sorting through pre-existing catalogues, we train generative models to invent brand-new molecules from scratch that satisfy our binding geometry and safety goals simultaneously. Yet inventing a molecule on a screen is only half the victory. Before a single patient can benefit, a chemist (or robot) must figure out how to synthesise it in a few reliable steps from cheap, commercially available ingredients, which is the art of retrosynthesis.

Families of Molecular Generative Models

  • Think about three different ways an architect could invent a new bridge. They could write a step-by-step text blueprint sentence by sentence, snap pre-engineered steel trusses together like Lego blocks, or sculpt a 3D mesh directly inside a laser scan of the river canyon. Molecular generative AI has evolved along those exact three representations.

Autoregressive String Models (SMILES and SELFIES)

  • Because SMILES encodes any 2D molecular graph as a short ASCII string (for example, CC(=O)Oc1ccccc1C(=O)O for aspirin), researchers quickly realised they could train recurrent networks or GPT-style autoregressive Transformers (Chapter 07) to predict the next chemical token \(p_\theta(x_t \mid x_{<t})\) across millions of real drug-like compounds from databases such as ChEMBL.

  • String language models are remarkably expressive and easy to train at massive scale, yet raw SMILES carries a brittle syntax trap. Opening a ring digit 1 without closing it later, or accidentally attaching five bonds to a carbon atom, produces a grammatically broken string that corresponds to no real molecule. SELFIES (Self-Referencing Embedded Strings, Krenn et al., 2020) resolves this fragility through a formal derivation grammar where every token tracks remaining atomic valences and branch lengths, guaranteeing that 100% of arbitrary SELFIES token sequences decode into a syntactically valid molecule.

Substructure Graph Models and Junction-Tree VAEs

  • Placing one individual atom at a time is awkward when real organic chemistry is built largely out of recurring ring systems and functional motifs. Jin et al. (2018) tackled this with the Junction-Tree Variational Autoencoder (JT-VAE), which decomposes any molecule into a coarse tree whose nodes are chemically valid substructure clusters (such as benzene rings, amides, or piperidine scaffolds) rather than bare atoms.

  • During generation, a latent vector \(\mathbf{z} \in \mathbb{R}^d\) first decodes the coarse junction-tree scaffold step by step and then chooses the exact stereochemically valid attachment points gluing neighbouring motifs together. Because every intermediate motif already obeys chemical valence rules, the model preserves high chemical validity while enabling smooth Bayesian optimisation inside a structured continuous latent space.

Pocket-Conditioned 3D \(SE(3)\)-Equivariant Diffusion

  • Both 1D strings and 2D molecular graphs share a blind spot. They have no direct awareness of the three-dimensional protein pocket where the drug must actually fit. Structure-based 3D generative models such as TargetDiff and DiffSBDD erase that gap by sculpting ligands directly inside the target binding site.

Pipeline of pocket-conditioned SE(3)-equivariant molecular diffusion transforming a noisy Gaussian cloud of coordinates and atom types inside a binding site into a sculpted 3D ligand filtered by multi-parameter optimisation, alongside a comparison of 1D string, 2D graph, and 3D diffusion families

  • At diffusion time \(t = T\), we scatter \(N\) ligand atoms inside the protein cavity with continuous 3D coordinates drawn from a Gaussian cloud \(\mathbf{x}_T \sim \mathcal{N}(\mathbf{0}, I)\) and discrete element types \(\mathbf{h}_T\) drawn from a uniform categorical prior. Over \(T\) reverse denoising steps, an \(SE(3)\)-equivariant graph neural network (Chapter 15) exchanges messages between protein pocket atoms and noisy ligand atoms to predict the clean coordinates and atom types.
  • Because the denoiser is strictly equivariant to 3D rotations \(R \in SO(3)\) and translations \(\mathbf{t} \in \mathbb{R}^3\), spinning the protein pocket in space spins the predicted denoising drift by the exact same matrix \(R\).
  • This inductive bias keeps the generated ligand locked cleanly to the pocket's contours, placing hydrogen-bond donors across from pocket acceptors and tucking aromatic rings into hydrophobic alcoves without wasting data learning every possible 3D orientation from scratch.

Multi-Parameter Optimisation, Fragments, and Linker Design

  • Designing a real medicine is never a single-objective game. Picture designing a commercial airliner. If you reward an optimiser purely for engine thrust, it will bolt giant rockets onto a paper fuselage that melts on takeoff. Similarly, optimising a molecule solely for predicted binding potency routinely produces greasy, insoluble bricks that clog liver enzymes, trigger heart arrhythmias (via the hERG potassium channel), or vanish in the bloodstream within minutes.

RL-Guided Multi-Parameter Optimisation (MPO)

  • Medicinal chemists therefore frame lead design as Multi-Parameter Optimisation (MPO), combining binding affinity, aqueous solubility (\(\log S\)), lipophilicity (\(\log P\)), membrane permeability, metabolic stability, and low toxicity into a composite desirability reward \(R(x) \in [0, 1]\).

  • Frameworks such as REINVENT couple a pretrained generative prior \(\pi_{\text{prior}}(x)\) (which already knows what realistic drug-like chemistry looks like) with an agent policy \(\pi_\theta(x)\) steered by reinforcement learning (Chapter 06). To prevent reward hacking (where the agent exploits bugs in an imperfect ML oracle by inventing grotesque, high-scoring chemical artefacts), REINVENT anchors the agent's log-likelihood close to the prior using an augmented likelihood loss closely tied to KL-regularised RLHF (Chapter 07).

\[\mathcal{L}_{\text{RL}}(\theta) = \mathbb{E}_{x \sim \pi_\theta}\!\left[\left(\log \pi_{\text{prior}}(x) + \sigma R(x) - \log \pi_\theta(x)\right)^2\right]\]
  • Look at how cleanly the hyperparameter \(\sigma > 0\) behaves. Minimising this squared error drives \(\log \pi_\theta(x) \approx \log \pi_{\text{prior}}(x) + \sigma R(x)\), meaning the optimal policy tilts the realistic prior exponentially towards high-reward regions (\(\pi^*(x) \propto \pi_{\text{prior}}(x)\exp(\sigma R(x))\)) without drifting into bizarre, unstable corners of chemical space.

Fragment-Based Drug Design and Linker Generation

  • Rather than inventing a complete 40-atom drug in a single shot, experimental biophysicists often succeed with Fragment-Based Drug Design (FBDD). First, they screen a tiny library of ultra-small fragments (often under 20 heavy atoms) using sensitive X-ray crystallography or NMR to spot two weak-binding pieces tucked neatly into neighbouring sub-pockets.

  • The thermodynamic magic comes straight from Section 4. If Fragment 1 binds weakly with \(\Delta G_1 \approx -5.5\,\text{kcal/mol}\) (\(K_d \approx 100\,\mu\text{M}\)) and Fragment 2 binds nearby with \(\Delta G_2 \approx -5.5\,\text{kcal/mol}\), joining them with a strain-free molecular bridge yields roughly additive binding free energies

\[\Delta G_{\text{linked}} \approx \Delta G_1 + \Delta G_2 + \Delta G_{\text{linker}}\]
  • Because free energies add while dissociation constants multiply, linking two weak \(100\,\mu\text{M}\) fragments can vault straight into a potent nanomolar lead (even after paying a small strain penalty \(\Delta G_{\text{linker}}\)). Modern 3D generative tools such as DiffLinker hold the two crystallised fragment anchors rigidly fixed inside the protein pocket and use \(SE(3)\)-equivariant diffusion to grow a chemically valid, strain-free bridge connecting them seamlessly.

The Reality Check of Synthetic Accessibility

  • Imagine an architect rendering a floating crystal staircase on a computer monitor. It wins every aesthetic award, yet when handed to a structural engineer, nobody on Earth can build it out of real steel and glass. Generative chemistry hits this exact wall whenever models optimise properties without respecting synthetic accessibility.

  • Unconstrained 3D diffusion and RL models notoriously invent strained fused rings, fragile peroxide chains, or dense clusters of chiral stereocentres that would require fifteen delicate synthetic steps at tiny yields, costing months of lab time for a single milligram of material. Two complementary lines of defence keep generated molecules grounded in wet-lab reality.

  • Heuristic scores such as the Synthetic Accessibility (SA) Score (Ertl and Schuffenhauer, 2009) score molecules from \(1\) (trivial to make) to \(10\) (nearly impossible) by summing fragment-frequency rarity penalties alongside penalties for large rings, bridged polycycles, and excessive stereocentres. SA Score is fast enough to sit inside an RL reward function, though it still overlooks specific multi-step synthesis bottlenecks.
  • Synthesis-aware generative models (such as SynNet, ChemProjector, and RxnFlow) eliminate unmakable molecules by construction. Instead of emitting raw atoms, the policy outputs an executable synthesis tree whose leaves are cheap in-stock catalogue chemicals and whose internal actions are reliable, well-established organic reactions. Every molecule the model proposes arrives automatically with a concrete recipe to make it.

Computer-Aided Retrosynthesis Planning

  • Suppose a generative model (or a human medicinal chemist) proposes a promising target molecule without an accompanying recipe. How do we discover a practical step-by-step route to manufacture it? Think of solving a tricky paper maze by placing your pencil on the finish flag and tracing backwards to the entrance, or reverse-engineering a layered birthday cake back to flour, eggs, and sugar from the grocery aisle.

  • Formalised by Nobel laureate E. J. Corey, retrosynthesis works backwards from the target molecule, disconnecting strategic bonds one reaction step at a time until every remaining precursor sits inside a catalogue of inexpensive, commercially available building blocks. Computer-aided synthesis planning (CASP) splits this backward reasoning into a single-step reaction model and a multi-step tree search planner.

Single-Step Retrosynthesis Models

  • Given a product molecule \(M\), a single-step model proposes ranked sets of candidate reactants \(\{R_1, R_2\}\) that can react cleanly to form \(M\). Two complementary model families dominate the field.
  • Template-based models extract thousands of reaction rules (SMARTS templates) from historical reaction corpora such as the US Patent and Trademark Office (USPTO) dataset or Reaxys, then train a neural classifier (often a graph neural network or fingerprint MLP) to rank which template applies best to the target molecule. Templates guarantee chemically valid atom-mapped transformations, though they cannot propose completely novel reaction classes absent from their template library.
  • Template-free models treat retrosynthesis as machine translation or graph editing. Sequence-to-sequence Transformers translate a product SMILES string directly into reactant SMILES strings, while graph-edit networks first identify the exact reaction centre (which bonds to cleave) and then predict which leaving groups (such as a bromine atom or hydroxyl group) restore valid synthons.
  • Disconnecting a complex drug molecule once rarely lands straight on supermarket chemicals. You must chain 3 to 10 consecutive reaction steps, where each intermediate branches into dozens of candidate disconnections and many dead ends. That branching explosion mirrors board games like Go (Chapter 06), which is why landmark planners such as Segler et al. (2018) and open-source AiZynthFinder combine neural single-step policies with Monte Carlo Tree Search (MCTS) (and related AND/OR search algorithms like Retro*).

Backwards retrosynthesis search tree expanding from a target drug molecule through an amide coupling step and an intermediate core down to green commercially available building blocks while pruning dead-end branches, paired with the four-step MCTS and robotic synthesis loop

  • Each node \(s\) in the search tree represents the set of unsolved molecules still awaiting synthesis (starting with the single target drug at the root). Every action \(a\) applies a single-step disconnection to one unsolved molecule, replacing it with its required reactants. During each MCTS iteration, the planner repeats four crisp phases.
  • Selection walks down the explored tree choosing the action \(a^*\) that maximises the PUCT (Predictor plus Upper Confidence Bound for Trees) score, balancing high-value known routes \(Q(s, a)\) against promising under-explored disconnections prioritised by the neural policy probability \(P(s, a)\).
\[a^* = \arg\max_a \left( Q(s, a) + c_{\text{puct}} \, P(s, a) \, \frac{\sqrt{N(s)}}{1 + N(s, a)} \right)\]
  • Expansion queries the neural single-step retrosynthesis model on the selected leaf state to attach the top-\(k\) candidate chemical disconnections and their prior probabilities \(P(s, a)\).
  • Evaluation (Rollout) estimates whether the remaining non-stock intermediates can be solved within a small step budget, awarding a full reward (\(1.0\)) when every leaf molecule appears in the commercial stock catalogue and partial or zero reward for dead ends.
  • Backpropagation sends that outcome back up the ancestor edges, incrementing visit counts \(N(s, a)\) and updating mean route values \(Q(s, a)\) so future search effort concentrates rapidly on the cleanest, shortest synthesis pathways.

Closed-Loop Self-Driving Laboratories

  • Step back and admire how every piece of Chapter 23 now snaps into a single living engine. For decades, medicinal chemistry ran on slow monthly relays called the Design-Make-Test-Analyse (DMTA) cycle. Computational scientists proposed ideas, synthetic chemists spent weeks making a handful in glass flasks, biologists ran plate assays, and weeks later a spreadsheet trickled back to the modellers.

  • Self-driving laboratories collapse that sluggish relay into a tight, automated closed loop that resembles a jazz quartet improvising in real time.

  • Design uses generative chemistry, 3D co-folding, and Bayesian active learning (Chapter 05) to propose batches of novel candidates that jointly balance high predicted potency, multi-parameter drug-likeness, and high epistemic uncertainty so every experiment teaches the surrogate model something genuinely new.
  • Make passes top candidates through MCTS retrosynthesis to compile executable recipes, handing them to automated liquid-handling platforms, microwave synthesisers, and continuous-flow microreactors that run reactions, monitor purity by liquid chromatography-mass spectrometry (LC-MS), and isolate target compounds with minimal human intervention.
  • Test and Analyse pipe freshly synthesised compounds directly into miniaturised biochemical and cellular assays, feeding gold-standard experimental \(IC_{50}\), solubility, and permeability measurements straight back to retrain the ML models for the very next round.

  • Keeping a sober perspective is just as important as celebrating the progress. Automated chemistry excels at reliable, modular coupling reactions (such as amide formations and Suzuki cross-couplings), yet tricky multi-step natural-product syntheses still demand seasoned human chemists. Even more fundamentally, hitting a purified protein pocket in a robot assay is only the opening mile of a marathon. Turning a potent lab molecule into a safe, effective human medicine still hinges on whole-organism biology, unexpected off-target effects, and rigorous clinical trials where real patient physiology remains far richer than any simulator we possess today.

Take-Home

  • Generative chemistry moves beyond finite catalogues by exploring the \(10^{60}\) drug-like chemical universe through 1D SELFIES language models, 2D substructure JT-VAEs, and 3D \(SE(3)\)-equivariant pocket-conditioned diffusion.
  • Real drug design is multi-parameter optimisation, where KL-anchored reinforcement learning (such as REINVENT) steers a realistic prior towards high potency, solubility, and low toxicity without falling into reward hacking.
  • Fragment linking multiplies binding affinities, because joining two weak fragments with additive binding free energies (\(\Delta G_1 + \Delta G_2\)) turns micromolar hits into potent nanomolar leads.
  • Synthetic accessibility is a hard physical filter, solved either by synthesis-constrained generators or by pairing single-step neural reaction models with PUCT-guided MCTS retrosynthesis planners down to buyable stock chemicals.
  • Self-driving laboratories close the DMTA loop, uniting generative design, retrosynthesis, robotic synthesis, and active learning so each experimental measurement sharpens the next generation of molecules.

Coding Tasks (use CoLab or notebook)

  1. Implement REINVENT-style prior-anchored RL for multi-parameter molecular optimisation (MPO) over a discrete vocabulary of 6 chemical building-block tokens assembled into 3-motif molecules. Compare unregularised policy optimisation (which collapses onto an unrealistic high-potency outlier) against KL-anchored augmented likelihood training that improves the composite MPO score (potency, solubility, and synthetic ease) while keeping molecules realistic.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # 6 motifs: Motif 5 (ExoticTrap) has high potency but awful solubility & synthesis
    motifs = ["Benzene", "Pyridine", "Amide", "Morpholine", "Fluorophenyl", "ExoticTrap"]
    potency = jnp.array([0.55, 0.65, 0.72, 0.60, 0.85, 1.00])
    solubility = jnp.array([0.45, 0.85, 0.90, 0.92, 0.55, 0.05])
    synth_ease = jnp.array([0.95, 0.90, 0.92, 0.88, 0.82, 0.05])
    prior_logits = jnp.array([1.2, 1.1, 1.3, 1.0, 0.9, -2.5])
    prior_logp = jax.nn.log_softmax(prior_logits)
    
    mpo_scores = 0.45 * potency + 0.30 * solubility + 0.25 * synth_ease
    
    def train_policy(rewards, use_prior_anchor, sigma=4.5, steps=150, lr=0.12):
        logits = prior_logits.copy()
        mpo_hist = []
    
        def loss_fn(lgt):
            logp = jax.nn.log_softmax(lgt)
            probs = jnp.exp(logp)
            if use_prior_anchor:
                # REINVENT augmented likelihood loss: E[(log pi_prior + sigma*R - log pi)^2]
                return jnp.sum(probs * (prior_logp + sigma * rewards - logp) ** 2)
            return -jnp.sum(probs * rewards)
    
        grad_fn = jax.grad(loss_fn)
        for _ in range(steps):
            probs = jax.nn.softmax(logits)
            mpo_hist.append(float(jnp.sum(probs * mpo_scores)))
            logits = logits - lr * grad_fn(logits)
        return jax.nn.softmax(logits), mpo_hist
    
    p_hack, mpo_hack = train_policy(potency, use_prior_anchor=False)
    p_safe, mpo_safe = train_policy(mpo_scores, use_prior_anchor=True, sigma=4.5)
    print(f"Greedy potency RL -> ExoticTrap prob: {float(p_hack[5]):.3f} | True MPO: {mpo_hack[-1]:.3f}")
    print(f"Prior-anchored RL -> ExoticTrap prob: {float(p_safe[5]):.3f} | True MPO: {mpo_safe[-1]:.3f}")
    
    fig, axes = plt.subplots(1, 2, figsize=(10.5, 4))
    axes[0].plot(mpo_hack, color="#e74c3c", lw=2.2, linestyle="--", label="Greedy potency RL (reward hack)")
    axes[0].plot(mpo_safe, color="#27ae60", lw=2.4, label="Prior-anchored MPO RL (REINVENT)")
    axes[0].set_xlabel("Training Step"); axes[0].set_ylabel("True Composite MPO Score")
    axes[0].set_title("Multi-Parameter Optimisation vs Reward Hacking"); axes[0].legend(); axes[0].grid(alpha=0.3)
    
    x, w = jnp.arange(6), 0.27
    axes[1].bar(x - w, jax.nn.softmax(prior_logits), width=w, color="#3498db", alpha=0.8, label="Prior")
    axes[1].bar(x, p_hack, width=w, color="#e74c3c", alpha=0.85, label="Greedy RL")
    axes[1].bar(x + w, p_safe, width=w, color="#27ae60", alpha=0.85, label="Anchored MPO")
    axes[1].set_xticks(x); axes[1].set_xticklabels(motifs, rotation=22, fontsize=8)
    axes[1].set_ylabel("Sampling Probability"); axes[1].set_title("Final Motif Distributions")
    axes[1].legend(fontsize=8); axes[1].grid(axis="y", alpha=0.3)
    plt.tight_layout(); plt.show()
    

  2. Build a 2D \(SE(2)\)-equivariant pocket-conditioned denoising layer in JAX. Verify mathematically and numerically that rotating and translating both the protein pocket and noisy ligand rotates the predicted denoising drift identically (to machine precision), then run a 40-step reverse denoising trajectory sculpting a clean 4-atom ring inside the pocket.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # Fixed protein pocket atoms surrounding a binding cavity centred at (0, 0)
    pocket_ang = jnp.linspace(0.0, 2.0 * jnp.pi, 9)[:-1]
    pocket_pos = 2.6 * jnp.stack([jnp.cos(pocket_ang), jnp.sin(pocket_ang)], axis=1)
    
    def equivariant_denoise_step(lig_pos, pocket, step_size=0.14):
        """SE(2)-equivariant vector update depending ONLY on invariant pairwise distances."""
        # 1. Pocket-to-ligand messages: pull atoms toward ideal clearance ~2.2 from pocket shell
        diff_p = pocket[None, :, :] - lig_pos[:, None, :]              # (N_l, N_p, 2)
        dist_p = jnp.sqrt(jnp.sum(diff_p ** 2, axis=-1) + 1e-6)        # (N_l, N_p)
        w_p = jnp.tanh(dist_p - 2.15) / (dist_p + 0.5)                 # Invariant scalar weight
        drift_p = jnp.mean(w_p[:, :, None] * diff_p, axis=1)
    
        # 2. Ligand-to-ligand messages: form regular ring spacing (~1.35) without overlap
        diff_l = lig_pos[None, :, :] - lig_pos[:, None, :]             # (N_l, N_l, 2)
        dist_l = jnp.sqrt(jnp.sum(diff_l ** 2, axis=-1) + 1e-6)
        mask = 1.0 - jnp.eye(lig_pos.shape[0])
        w_l = mask * (dist_l - 1.35) / (dist_l + 0.4)
        drift_l = 0.65 * jnp.mean(w_l[:, :, None] * diff_l, axis=1)
    
        return lig_pos + step_size * (drift_p + drift_l)
    
    # Verify strict SE(2) equivariance: f(R x + t, R P + t) == R f(x, P) + t
    key = jax.random.PRNGKey(12)
    x_init = jax.random.normal(key, (4, 2)) * 1.4
    theta = 1.17
    R = jnp.array([[jnp.cos(theta), -jnp.sin(theta)], [jnp.sin(theta), jnp.cos(theta)]])
    t = jnp.array([3.5, -2.1])
    
    out_orig = equivariant_denoise_step(x_init, pocket_pos)
    out_transformed_after = out_orig @ R.T + t
    out_transformed_before = equivariant_denoise_step(x_init @ R.T + t, pocket_pos @ R.T + t)
    equiv_err = float(jnp.max(jnp.abs(out_transformed_after - out_transformed_before)))
    print(f"Max SE(2) equivariance error under rotation + translation: {equiv_err:.2e}")
    
    # Run 40 reverse diffusion denoising steps (with decaying Langevin noise)
    x = x_init
    traj = [x]
    for step in range(40):
        key, k_noise = jax.random.split(key)
        sigma = 0.15 * (1.0 - step / 40.0)
        x = equivariant_denoise_step(x, pocket_pos, step_size=0.18) + sigma * jax.random.normal(k_noise, x.shape)
        traj.append(x)
    
    fig, axes = plt.subplots(1, 2, figsize=(10.5, 4.2))
    for ax, coords, title, col in [
        (axes[0], traj[0], "t = T (Noisy Prior Cloud)", "#e74c3c"),
        (axes[1], traj[-1], "t = 0 (Denoised 3D Ligand in Pocket)", "#27ae60"),
    ]:
        ax.scatter(pocket_pos[:, 0], pocket_pos[:, 1], s=140, color="#3498db", alpha=0.45, label="Pocket atoms")
        ax.scatter(coords[:, 0], coords[:, 1], s=95, color=col, zorder=5, label="Ligand atoms")
        if title.startswith("t = 0"):
            for i in range(4):
                for j in range(i + 1, 4):
                    if float(jnp.linalg.norm(coords[i] - coords[j])) < 1.65:
                        ax.plot([coords[i, 0], coords[j, 0]], [coords[i, 1], coords[j, 1]], color="#333", lw=2)
        ax.set_xlim(-3.5, 3.5); ax.set_ylim(-3.5, 3.5); ax.set_aspect("equal")
        ax.set_title(title); ax.legend(fontsize=8); ax.grid(alpha=0.3)
    plt.tight_layout(); plt.show()
    

  3. Implement a Monte Carlo Tree Search (MCTS) retrosynthesis planner using the PUCT selection rule over a toy multi-step chemical synthesis network with buyable stock chemicals, competing disconnection templates, and chemical dead ends. Watch MCTS focus visits onto the shortest solvable synthesis recipe and plot route visit shares over search iterations.

    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    STOCK = {"Block_A1", "Block_A2", "Block_C", "Block_D1", "Block_D2"}
    RETRO_MODEL = {
        "Target_Drug": [
            ("R1_AmideCoupling", 0.42, ("Interm_A", "Block_C")),  # 2-step solved
            ("R2_RiskyRingClose", 0.36, ("DeadEnd_Core",)),       # High prior dead end
            ("R3_LongSuzuki", 0.22, ("Interm_B", "Block_D1")),    # 3-step solved
        ],
        "Interm_A": [("R4_ReductiveAmin", 0.70, ("Block_A1", "Block_A2")), ("R5_PoorYieldPath", 0.30, ("DeadEnd_Side",))],
        "Interm_B": [("R6_CrossCoupling", 0.65, ("Interm_A", "Block_D2")), ("R7_SideDeadEnd", 0.35, ("DeadEnd_Side",))],
        "DeadEnd_Core": [], "DeadEnd_Side": [],
    }
    
    def get_actions(state):
        mol, rest = state[0], state[1:]
        return [(r, p, tuple(sorted([x for x in rcts if x not in STOCK] + list(rest))))
                for r, p, rcts in RETRO_MODEL.get(mol, [])]
    
    N_state, N_edge, W_edge = {}, {}, {}
    root, c_puct, root_hist = ("Target_Drug",), 1.4, []
    
    for _ in range(120):
        path, state, depth = [], root, 0
        while len(state) > 0 and depth < 5:
            actions = get_actions(state)
            if not actions:
                break
            n_s = N_state.get(state, 0)
            best = max(actions, key=lambda a: (W_edge.get((state, a[0]), 0.0) / max(N_edge.get((state, a[0]), 0), 1))
                       + c_puct * a[1] * float(jnp.sqrt(n_s + 1.0)) / (1.0 + N_edge.get((state, a[0]), 0)))
            rule, _, next_state = best
            path.append((state, rule))
            state, depth = next_state, depth + 1
            if N_edge.get((path[-1][0], rule), 0) == 0:
                break
    
        if len(state) == 0:
            reward = 1.0 - 0.12 * (depth - 1)
        elif len(get_actions(state)) == 0:
            reward = 0.0
        else:
            reward = 0.35 * sum(1 for m in state if RETRO_MODEL.get(m)) / len(state)
    
        for s_node, r_name in path:
            N_state[s_node] = N_state.get(s_node, 0) + 1
            N_edge[(s_node, r_name)] = N_edge.get((s_node, r_name), 0) + 1
            W_edge[(s_node, r_name)] = W_edge.get((s_node, r_name), 0.0) + reward
    
        root_hist.append([N_edge.get((root, r), 0) for r, _, _ in RETRO_MODEL["Target_Drug"]])
    
    hist = jnp.array(root_hist)
    for rule, prior, _ in RETRO_MODEL["Target_Drug"]:
        n = N_edge.get((root, rule), 0)
        print(f"{rule:20s} | prior={prior:.2f} | visits={n:3d} | mean Q={W_edge.get((root, rule), 0.0) / max(n, 1):.3f}")
    
    plt.figure(figsize=(8.5, 4))
    plt.plot(hist[:, 0], color="#27ae60", lw=2.5, label="R1 AmideCoupling (2-step solved)")
    plt.plot(hist[:, 1], color="#e74c3c", lw=2.0, linestyle="--", label="R2 RiskyRingClose (dead end)")
    plt.plot(hist[:, 2], color="#3498db", lw=2.0, linestyle=":", label="R3 LongSuzuki (3-step solved)")
    plt.xlabel("MCTS Search Iteration"); plt.ylabel("Cumulative Root Edge Visits")
    plt.title("PUCT-Guided Retrosynthesis MCTS Concentrates on the Shortest Solvable Route")
    plt.legend(); plt.grid(alpha=0.3); plt.tight_layout(); plt.show()