Molecular Representations and Cheminformatics¶
Chemistry lives in a universe of roughly \(10^{60}\) plausible drug-like molecules, far too vast to explore by trial and error in a wet laboratory. This file introduces how computational chemistry encodes molecules for machine learning, progressing from 1D strings and circular fingerprints to 2D graphs, 3D conformers, and molecular chirality.
The Immensity of Chemical Space¶
-
Imagine standing on a beach and trying to find one specific grain of sand that happens to cure a rare disease. Even that image dramatically understates the scale of chemical space. Medicinal chemists estimate that there are roughly \(10^{60}\) chemically stable, small drug-like molecules with fewer than 30 heavy atoms. To put that number in perspective, the entire planet Earth contains roughly \(10^{50}\) atoms, and humanity has only ever synthesised and catalogued on the order of \(10^{8}\) distinct compounds across all of recorded chemistry.
-
Because we can physically test only an infinitesimal speck of chemical space, modern drug discovery and materials science rely heavily on cheminformatics, the discipline of representing, searching, and predicting molecular properties on a computer.
-
Yet a real molecule is not a spreadsheet row or a neat grid of pixels. It is a dynamic, three-dimensional quantum cloud of positively charged nuclei and negatively charged electrons constantly vibrating and flexing in water. Translating that physical object into numbers that a machine learning model can digest is arguably the single most important design choice in computational chemistry. What your representation throws away, no neural network can easily recover.
- Across cheminformatics, four main families of representations form a natural ladder of increasing geometric richness, moving from fast one-dimensional strings and bit vectors up to topological graphs and full three-dimensional atomic coordinates.
1D String Representations from SMILES to SELFIES¶
-
Suppose you want to describe a sprawling London Underground map to a friend over the telephone without sending a picture. You would pick a starting station, read off stops along a line, pause in parentheses whenever a branch splits off, and drop numbered markers wherever a track loops back to form a circle.
-
That exact trick powers SMILES (Simplified Molecular Input Line Entry System), invented by David Weininger in 1988. SMILES flattens any molecular graph into a compact string of ASCII characters using a depth-first graph traversal.
- Atoms appear as their element symbols (
C,N,O,F,Cl), while hydrogens are left implicit because standard valence rules fill them in automatically (for instance,CCOrepresents ethanol, \(\text{CH}_3\text{CH}_2\text{OH}\)). - Bond orders default to single bonds, while
=denotes a double bond and#denotes a triple bond (for example,CC(=O)Ois acetic acid). - Branches are enclosed in parentheses
(...), and ring closures match pairs of digits such asC1CCCCC1for cyclohexane, or lowercase lettersc1ccccc1for an aromatic benzene ring.
- Atoms appear as their element symbols (
-
Because a depth-first walk can begin at any atom and follow branches in any order, a single molecule corresponds to many valid SMILES strings. Ethanol can be written as
CCO,OCC, orC(O)C. To search a database reliably, cheminformatics toolkits apply canonicalisation (rooted in Morgan's canonical numbering algorithm), which picks one deterministic starting atom and traversal order so every molecule receives a single canonical SMILES. Interestingly, deep learning researchers often flip this around during training, feeding ten or twenty randomised non-canonical SMILES for the same molecule (SMILES enumeration) as a simple, effective form of data augmentation. -
Despite its elegance, SMILES has a glaring Achilles' heel for generative models and evolutionary search. Its grammar is brittle. Dropping a single closing parenthesis, leaving a ring digit unpaired, or putting five bonds on a carbon atom turns a string into invalid chemical gibberish. If you mutate a SMILES string randomly, most outputs fail to parse into any real molecule.
-
SELFIES (Self-Referencing Embedded Strings), introduced by Krenn and colleagues in 2020, solves this fragility by redesigning the alphabet itself. Think of SMILES like raw hand-written HTML where a missing angle bracket breaks the page, whereas SELFIES works like a self-healing state machine. Every SELFIES token such as
[C],[=O],[Branch1], or[Ring1]updates a strict internal derivation counter tracking remaining atomic valences and legal branch lengths. If a token asks for an impossible bond or an out-of-range ring closure, the grammar automatically clamps or skips it. As a result, every arbitrary sequence of SELFIES tokens is mathematically guaranteed to decode into a 100% chemically valid molecule, making latent-space optimisation and genetic algorithms far more reliable.
Circular Fingerprints and Tanimoto Similarity¶
-
Before deep learning arrived in chemistry, how did pharmaceutical companies search ten million compounds in milliseconds to find structural cousins of a promising drug? They borrowed the same philosophy behind music-recognition apps like Shazam. Instead of comparing full songs note by note, you hash short local neighbourhoods into a fixed-size table of binary flags.
-
Circular fingerprints, most famously Morgan fingerprints and ECFP (Extended-Connectivity Fingerprints), turn any molecule into a fixed-length binary vector \(\mathbf{b} \in \{0, 1\}^B\) (commonly \(B = 1024\) or \(2048\) bits).
- Radius 0 assigns every heavy atom an integer hash encoding its immediate chemical invariants (atomic number, degree, formal charge, attached hydrogens, and ring membership).
- Radius \(r = 1, 2, \dots, R\) iteratively updates each atom's integer identifier by hashing its previous identifier together with the sorted identifiers and bond orders of all directly bonded neighbours.
- Bit folding maps every discovered substructure identifier \(h\) into a fixed bit position \(h \bmod B\), setting that entry of \(\mathbf{b}\) to \(1\).
-
A radius-2 fingerprint sees circular neighbourhoods up to diameter 4 bonds and is widely known as ECFP4. Circular fingerprints remain astonishingly competitive baselines when paired with Random Forests or gradient boosted trees on small datasets, though folding millions of possible chemical fragments into 2048 slots inevitably introduces occasional bit collisions, where two unrelated substructures flip the same bit on.
-
Once two molecules \(A\) and \(B\) are encoded as binary bit sets (or vectors \(\mathbf{a}, \mathbf{b} \in \{0, 1\}^B\)), chemists measure their structural similarity using the Tanimoto coefficient (identical to the Jaccard index).
- Notice why Tanimoto beats plain Euclidean distance or accuracy for sparse chemical fingerprints. Out of 2048 bits, a typical small drug turns on only 40 to 80 bits. Two completely unrelated molecules share roughly 1950 zeros in common, yet sharing the absence of an exotic bromine ring does not make them chemically alike. Tanimoto ignores shared zeros completely, measuring strictly the overlap among present substructures on a clean scale from \(0\) (disjoint) to \(1\) (identical fingerprints).
2D Molecular Graphs and Message Passing¶
-
Circular fingerprints have one big limitation. Their hashing rules are frozen in advance, so they cannot adapt which substructures matter most for a particular protein target or toxicity assay. To let a neural network learn chemical features end to end, we represent the molecule directly as its native 2D molecular graph \(G = (V, E)\), connecting directly to the Graph Neural Networks covered in chapter 15.
-
Picture a neighbourhood dinner table where every guest starts by knowing only their own background, then chats with the people sitting immediately beside them, and repeats the conversation for \(L\) rounds. After three rounds of passing notes, every person holds a rich summary of their entire three-hop social circle.
-
In a molecular graph, atoms are nodes \(v \in V\) equipped with initial feature vectors \(\mathbf{x}_v\) (one-hot element identity, orbital hybridisation such as \(sp\), \(sp^2\), or \(sp^3\), formal charge, degree, aromaticity, and implicit hydrogen count), and chemical bonds are edges \((u, v) \in E\) with edge features \(\mathbf{e}_{uv}\) (bond order, conjugation, aromaticity, and ring membership).
- Message Passing Neural Networks (MPNNs) (Gilmer et al., 2017) unify nearly all 2D molecular GNNs into three clean stages. At layer \(t\), each atom \(v\) gathers messages from its bonded neighbours \(\mathcal{N}(v)\), updates its hidden state, and after \(L\) layers pools all atom embeddings into one permutation-invariant molecular vector \(\mathbf{h}_G\).
- Look closely at the parallel between MPNNs and Morgan fingerprints. One round of message passing inspects radius-1 neighbourhoods, two rounds inspect radius-2 environments just like ECFP4, and summing across all nodes in the readout \(R\) ensures the prediction never depends on how the atoms were arbitrarily numbered in a file. An MPNN is essentially a differentiable, task-adaptive circular fingerprint trained by backpropagation.
3D Conformers, Chirality, and Internal Coordinates¶
-
Even a perfect 2D molecular graph leaves out a crucial dimension of biology. Try slipping your left hand into a right-handed leather glove. Your left and right hands have the exact same 2D connectivity graph (thumb attached to palm, four fingers in sequence), yet they refuse to match in three-dimensional space.
-
Molecules live in 3D space too, and two geometric realities make 3D representations indispensable in drug design.
- Conformational ensembles arise because single chemical bonds can rotate freely at body temperature. Rather than sitting frozen like a crystal statue, a flexible drug molecule wiggles continuously through many low-energy 3D shapes called conformers, adopting one specific bound pose when it locks inside a target protein pocket.
- Chirality and enantiomers occur whenever a tetrahedral carbon atom bonds to four different chemical groups, creating a chiral centre. Such a molecule comes in two non-superimposable mirror images called enantiomers (labelled \(R\) and \(S\)). Because human proteins and enzymes are themselves built exclusively from left-handed (L) amino acids, a protein pocket acts like a right-handed glove. One enantiomer of a drug can fit snugly and cure disease while its mirror twin either fails to bind or hits an unintended target.
-
History offers a sobering reminder of chirality in thalidomide, prescribed in the late 1950s for morning sickness. Its \((R)\)-enantiomer acted as a gentle sedative, whereas its \((S)\)-enantiomer caused severe limb malformations in developing embryos (and tragically, even administering the pure \((R)\) form failed because human blood rapidly interconverts the two mirror images). A naive 2D molecular graph without stereochemical tags treats both enantiomers as completely identical.
-
Storing raw 3D Cartesian coordinates \(\{\mathbf{r}_1, \dots, \mathbf{r}_N\} \subset \mathbb{R}^3\) captures both conformers and chirality, yet raw \((x, y, z)\) numbers shift whenever you rotate or translate the molecule. To describe pure internal shape independently of laboratory axes, chemists often convert to internal coordinates (the Z-matrix representation).
- Bond lengths \(r_{ij} = \|\mathbf{r}_j - \mathbf{r}_i\|\) give distances between bonded pairs.
- Bond angles \(\theta_{ijk}\) measure the bend formed by three connected atoms \((i, j, k)\).
- Dihedral (torsion) angles \(\phi_{ijkl} \in (-\pi, \pi]\) measure the signed twist between the plane of \((i, j, k)\) and the plane of \((j, k, l)\) around the central \(j\text{--}k\) bond.
-
Notice a beautiful geometric property of signed dihedral angles. Pairwise distances and bond angles remain unchanged when you reflect a molecule in a mirror, meaning distance-only models remain completely blind to chirality! A signed dihedral angle, computed using the scalar triple product (chapter 01), flips sign under mirror reflection (\(\phi \to -\phi\)), cleanly separating left-handed and right-handed enantiomers.
Take-Home¶
- Drug-like chemical space holds roughly \(10^{60}\) molecules, making computational representation the indispensable bridge between quantum physics and practical discovery.
- 1D SMILES strings compactly encode bonding topology for language models and benefit from canonicalisation and enumeration, while SELFIES trades a tiny grammar overhead for a 100% chemical validity guarantee.
- Morgan (ECFP) fingerprints hash local circular neighbourhoods into sparse bit vectors whose overlap is scored cleanly via Tanimoto similarity without being fooled by shared zeros.
- 2D molecular graphs and Message Passing Neural Networks replace fixed hashing with learnable, permutation-invariant neighbourhood aggregation over atom and bond features.
- 3D conformers, signed dihedral angles, and stereochemistry are essential whenever molecular flexibility or mirror-image chirality determines biological function.
Coding Tasks (use CoLab or notebook)¶
-
Build a mini circular Morgan fingerprint encoder from scratch for five small organic molecules, fold the local neighbourhood hashes into binary bit vectors, compute the pairwise Tanimoto similarity matrix in JAX, and visualise it as a heatmap.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt # Define 5 simple heavy-atom molecular graphs: (atom_types, bond_list) # Atom codes: 6=C, 7=N, 8=O molecules = { "Ethane": ([6, 6], [(0, 1, 1)]), "Ethanol": ([6, 6, 8], [(0, 1, 1), (1, 2, 1)]), "AceticAcid": ([6, 6, 8, 8], [(0, 1, 1), (1, 2, 2), (1, 3, 1)]), "Acetamide": ([6, 6, 8, 7], [(0, 1, 1), (1, 2, 2), (1, 3, 1)]), "Benzene": ([6, 6, 6, 6, 6, 6], [(0, 1, 4), (1, 2, 4), (2, 3, 4), (3, 4, 4), (4, 5, 4), (5, 0, 4)]), } def morgan_fingerprint(atoms, bonds, radius=2, n_bits=64): """Hash circular atom neighbourhoods up to a given radius into a bit vector.""" n = len(atoms) adj = [[] for _ in range(n)] for u, v, order in bonds: adj[u].append((v, order)) adj[v].append((u, order)) # Radius 0 initial atom invariants: (atomic_num, degree) ids = [hash((atoms[i], len(adj[i]))) for i in range(n)] discovered = list(ids) for _ in range(radius): new_ids = [] for i in range(n): nbr_sig = tuple(sorted((order, ids[j]) for j, order in adj[i])) h = hash((ids[i], nbr_sig)) new_ids.append(h) discovered.append(h) ids = new_ids bits = [0.0] * n_bits for h in discovered: bits[abs(h) % n_bits] = 1.0 return jnp.array(bits) names = list(molecules.keys()) fps = jnp.stack([morgan_fingerprint(*molecules[k]) for k in names], axis=0) # Pairwise Tanimoto similarity matrix dot_mat = jnp.dot(fps, fps.T) norms = jnp.sum(fps, axis=1, keepdims=True) tanimoto = dot_mat / (norms + norms.T - dot_mat + 1e-8) for i, name in enumerate(names): row = " ".join(f"{float(tanimoto[i, j]):.2f}" for j in range(len(names))) print(f"{name:11s} -> {row}") fig, ax = plt.subplots(figsize=(6.2, 5.0)) im = ax.imshow(tanimoto, cmap="viridis", vmin=0.0, vmax=1.0) ax.set_xticks(range(len(names))) ax.set_yticks(range(len(names))) ax.set_xticklabels(names, rotation=30, ha="right") ax.set_yticklabels(names) for i in range(len(names)): for j in range(len(names)): ax.text(j, i, f"{float(tanimoto[i, j]):.2f}", ha="center", va="center", color="white" if float(tanimoto[i, j]) < 0.65 else "black", fontsize=9) plt.colorbar(im, ax=ax, label="Tanimoto Similarity") ax.set_title("Circular Fingerprint Tanimoto Similarity Matrix") plt.tight_layout() plt.show() -
Implement a two-layer Message Passing Neural Network (MPNN) in JAX operating on atom features and bond features, then randomly permute the atom numbering of acetamide to verify exact permutation invariance of the pooled molecular embedding.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt def init_mpnn(key, node_dim, edge_dim, hidden_dim): k1, k2, k3 = jax.random.split(key, 3) return { "W_in": jax.random.normal(k1, (node_dim, hidden_dim)) * 0.4, "W_msg": jax.random.normal(k2, (2 * hidden_dim + edge_dim, hidden_dim)) * 0.4, "W_upd": jax.random.normal(k3, (2 * hidden_dim, hidden_dim)) * 0.4, } def mpnn_embed(params, X, E, A, n_layers=2): """Run L rounds of edge-conditioned message passing and sum readout.""" h = jax.nn.relu(jnp.dot(X, params["W_in"])) # (N, H) N, H = h.shape for _ in range(n_layers): # Broadcast all node pairs (i, j) hi = jnp.broadcast_to(h[:, None, :], (N, N, H)) hj = jnp.broadcast_to(h[None, :, :], (N, N, H)) pair_in = jnp.concatenate([hi, hj, E], axis=-1) # (N, N, 2H + E_dim) msgs = jax.nn.tanh(jnp.dot(pair_in, params["W_msg"])) # Mask strictly to bonded neighbours via adjacency matrix A agg = jnp.sum(msgs * A[:, :, None], axis=1) # (N, H) h = jax.nn.relu(jnp.dot(jnp.concatenate([h, agg], axis=-1), params["W_upd"])) return jnp.sum(h, axis=0), h # Acetamide heavy atoms: [C1, C2, O3, N4] # Node features: [is_C, is_N, is_O, is_sp2, degree/4] X_acet = jnp.array([ [1.0, 0.0, 0.0, 0.0, 0.25], # C1 (methyl) [1.0, 0.0, 0.0, 1.0, 0.75], # C2 (carbonyl) [0.0, 0.0, 1.0, 1.0, 0.25], # O3 (oxygen) [0.0, 1.0, 0.0, 1.0, 0.25], # N4 (amine) ]) # Adjacency A and edge features [single_bond, double_bond] A_acet = jnp.array([ [0., 1., 0., 0.], [1., 0., 1., 1.], [0., 1., 0., 0.], [0., 1., 0., 0.], ]) # Build edge tensor [single_bond, double_bond] with pure array stacking single_mask = jnp.array([ [0., 1., 0., 0.], [1., 0., 0., 1.], [0., 0., 0., 0.], [0., 1., 0., 0.], ]) double_mask = jnp.array([ [0., 0., 0., 0.], [0., 0., 1., 0.], [0., 1., 0., 0.], [0., 0., 0., 0.], ]) E_acet = jnp.stack([single_mask, double_mask], axis=-1) params = init_mpnn(jax.random.PRNGKey(12), node_dim=5, edge_dim=2, hidden_dim=8) emb_orig, node_orig = mpnn_embed(params, X_acet, E_acet, A_acet) # Permute atom order: [O3, N4, C1, C2] perm = jnp.array([2, 3, 0, 1]) X_perm = X_acet[perm] A_perm = A_acet[perm][:, perm] E_perm = E_acet[perm][:, perm, :] emb_perm, _ = mpnn_embed(params, X_perm, E_perm, A_perm) diff = float(jnp.max(jnp.abs(emb_orig - emb_perm))) print(f"Max embedding difference after permuting atoms: {diff:.2e}") fig, ax = plt.subplots(figsize=(7.2, 3.6)) idx = jnp.arange(len(emb_orig)) ax.bar(idx - 0.18, emb_orig, width=0.35, color="#3498db", label="Original atom order") ax.bar(idx + 0.18, emb_perm, width=0.35, color="#27ae60", label="Permuted atom order") ax.set_xlabel("Embedding Dimension") ax.set_ylabel("Pooled Feature Value") ax.set_title(f"MPNN Graph Embedding Permutation Invariance (Max Diff = {diff:.1e})") ax.legend() plt.tight_layout() plt.show() -
Build a 3D chiral tetrahedral centre and its mirror-image enantiomer in JAX, compare all pairwise interatomic distances against signed dihedral angles and signed tetrahedral volume, and demonstrate why 2D or distance-only encodings cannot distinguish enantiomers.
import jax.numpy as jnp import matplotlib.pyplot as plt def pairwise_distances(coords): diff = coords[:, None, :] - coords[None, :, :] return jnp.sqrt(jnp.sum(diff ** 2, axis=-1) + 1e-12) def signed_dihedral(r0, r1, r2, r3): """Compute signed torsion angle in degrees for four 3D points.""" b0 = r0 - r1 b1 = r2 - r1 b2 = r3 - r2 b1_hat = b1 / (jnp.linalg.norm(b1) + 1e-12) v = b0 - jnp.dot(b0, b1_hat) * b1_hat w = b2 - jnp.dot(b2, b1_hat) * b1_hat x = jnp.dot(v, w) y = jnp.dot(jnp.cross(b1_hat, v), w) return jnp.arctan2(y, x) * (180.0 / jnp.pi) # Chiral carbon at origin bonded to 4 distinct substituents (different bond lengths) enantiomer_R = jnp.array([ [ 0.00, 0.00, 0.00], # C* (chiral centre) [ 1.09, 0.00, 0.00], # Group 1 (H) [-0.45, 1.28, 0.00], # Group 2 (F) [-0.50, -0.70, 1.24], # Group 3 (Cl) [-0.58, -0.82, -1.45], # Group 4 (Br) ]) # Mirror reflection across the xy-plane (z -> -z) produces the S enantiomer enantiomer_S = enantiomer_R * jnp.array([1.0, 1.0, -1.0]) D_R = pairwise_distances(enantiomer_R) D_S = pairwise_distances(enantiomer_S) dist_diff = float(jnp.max(jnp.abs(D_R - D_S))) # Signed dihedral between substituents 1-0-2-3 and signed tetrahedral volume dih_R = float(signed_dihedral(enantiomer_R[1], enantiomer_R[0], enantiomer_R[2], enantiomer_R[3])) dih_S = float(signed_dihedral(enantiomer_S[1], enantiomer_S[0], enantiomer_S[2], enantiomer_S[3])) vol_R = float(jnp.linalg.det(enantiomer_R[2:5] - enantiomer_R[1])) vol_S = float(jnp.linalg.det(enantiomer_S[2:5] - enantiomer_S[1])) print(f"Max pairwise distance difference (R vs S): {dist_diff:.2e}") print(f"Signed dihedral angle: R = {dih_R:+.1f} deg, S = {dih_S:+.1f} deg") print(f"Signed chiral volume: R = {vol_R:+.3f}, S = {vol_S:+.3f}") fig, axes = plt.subplots(1, 2, figsize=(10.5, 4.0)) tri_idx = jnp.triu_indices(5, k=1) axes[0].plot(D_R[tri_idx], "o-", color="#3498db", lw=2, label="(R)-enantiomer") axes[0].plot(D_S[tri_idx], "x--", color="#e74c3c", lw=2, markersize=8, label="(S)-enantiomer") axes[0].set_xlabel("Atom Pair Index") axes[0].set_ylabel("Distance (Angstroms)") axes[0].set_title("Pairwise Distances Are Identical (Blind to Chirality)") axes[0].legend() metrics = ["Dihedral (deg / 30)", "Signed Volume"] vals_R = [dih_R / 30.0, vol_R] vals_S = [dih_S / 30.0, vol_S] x = jnp.arange(len(metrics)) axes[1].bar(x - 0.18, vals_R, width=0.35, color="#27ae60", label="(R)-enantiomer") axes[1].bar(x + 0.18, vals_S, width=0.35, color="#9b59b6", label="(S)-enantiomer") axes[1].axhline(0.0, color="#333", lw=1) axes[1].set_xticks(x) axes[1].set_xticklabels(metrics) axes[1].set_title("Signed 3D Geometry Flips Sign Across Enantiomers") axes[1].legend() plt.tight_layout() plt.show()