Protein Folding and Structure Prediction¶
A protein begins life as a limp one-dimensional ribbon of amino acids, yet within milliseconds it collapses into an intricate three-dimensional machine capable of catalysing chemistry, transporting oxygen, or fighting off viruses. This section unpacks the half-century grand challenge of protein folding, from evolutionary co-variation and AlphaFold 2's geometric Evoformer to single-sequence language models like ESMFold and AlphaFold 3's all-atom biomolecular diffusion.
Proteins as 3D Origami Machines and Levinthal's Paradox¶
-
If DNA is the cell's hard drive, proteins are the physical robots that carry out almost every task inside living organisms. A protein is a linear chain of building blocks drawn from \(20\) standard amino acids. Each amino acid shares the same repeating backbone atoms (an amine nitrogen \(\text{N}\), a central alpha carbon \(\text{C}_\alpha\), and a carbonyl carbon \(\text{C}\)), decorated with a unique chemical side chain that can be oily (hydrophobic), water-loving (polar), positively charged, negatively charged, tiny, or bulky.
-
Biologists organise protein geometry into four nested levels of structure, much like building a cathedral from bricks, arches, rooms, and connected wings.
- Primary structure. The 1D amino-acid sequence read straight from mRNA, such as
M K E L A V I R ..., typically \(50\) to \(1{,}000\) residues long. - Secondary structure. Local geometric motifs stabilised by regular backbone hydrogen bonds, chiefly spring-like alpha-helices and pleated beta-sheets connected by flexible loops.
- Tertiary structure. The complete 3D fold of a single chain, driven largely by hydrophobic collapse as oily side chains tuck inward away from surrounding water while charged side chains face outward.
- Quaternary structure. Multiple folded chains snapping together into a larger multi-subunit complex, such as the four-chain haemoglobin assembly carrying oxygen in your blood.
- Primary structure. The 1D amino-acid sequence read straight from mRNA, such as
-
Because a protein's 3D shape directly determines its biological function, Christian Anfinsen proved in the 1960s that the amino-acid sequence alone contains all the information needed to specify the native fold. Yet this raised a staggering computational puzzle known as Levinthal's paradox. Each backbone residue can twist around two flexible dihedral angles (\(\phi\) and \(\psi\)). Even if each residue could take only \(3\) discrete shapes, a modest \(100\)-residue protein would have \(3^{100} \approx 5 \times 10^{47}\) conformations (and realistic bond rotations push estimates past \(10^{300}\)). Checking conformations randomly at atomic vibration speeds would take vastly longer than the age of the universe, yet real cells fold proteins cleanly in milliseconds!
-
Nature avoids brute-force search because the physics of folding forms a rough energy funnel. Local contacts form early, narrowing the search space step by step as the chain tumbles downhill toward its lowest-free-energy state. For fifty years, simulating that funnel from raw atomic physics proved too slow and error-prone for general proteins. The breakthrough came from combining evolutionary statistics with geometric deep learning.
Evolutionary Co-Variation and Multiple Sequence Alignments¶
- Suppose you have never seen a suspension bridge, yet you are given photographs of a thousand bridges built across different centuries. You notice that whenever an engineer makes cable \(i\) thicker, anchor bolt \(j\) fifty metres down the blueprint also gets reinforced in lockstep. Even without structural engineering equations, you could deduce immediately that cable \(i\) and bolt \(j\) physically touch and bear load together!
-
Evolution runs that exact experiment across billions of years. If we gather homologous versions of a protein family from humans, mice, fish, flies, and bacteria and stack them row by row, we obtain a Multiple Sequence Alignment (MSA). Suppose residue \(i\) and residue \(j\) sit eighty positions apart along the 1D chain, yet in the folded 3D protein they press tightly against each other in a stabilising salt bridge (a positively charged lysine
K+touching a negatively charged aspartateD-). If a random mutation flips position \(i\) to negative, the protein breaks and the organism struggles to survive unless a compensatory mutation flips position \(j\) to positive. -
Measuring these coupled mutations across an MSA uncovers a hidden 3D contact map. Early statistical methods measured pairwise mutual information (chapter 05) between columns \(i\) and \(j\), yet raw correlation suffers from transitive echoes (if \(i\) touches \(k\) and \(k\) touches \(j\), then \(i\) and \(j\) appear correlated even when far apart). Direct Coupling Analysis (DCA) solved this by fitting a global Potts model over the alignment, estimating direct interaction weights \(J_{ij}(a, b)\) so only genuine physical contacts stand out sharply.
- While Potts models extracted remarkable contact hints for deep families, they still could not turn noisy distance clues directly into sub-angstrom atomic coordinates. That leap required an end-to-end neural architecture designed around 3D Euclidean geometry.
AlphaFold 2 Deep Dive¶
- At the 2020 CASP14 blind structure-prediction competition, AlphaFold 2 solved the single-chain folding challenge to experimental accuracy (often within \(1\,\text{\AA}\), roughly the width of a single carbon atom). Its success rests not on one trick, but on five deeply geometric architectural ideas working in concert.
Evoformer and Triangle Reasoning¶
-
AlphaFold 2 maintains two living representations throughout its \(48\)-block Evoformer trunk. The MSA representation (shape \(N_{\text{seq}} \times L \times c_m\)) tracks evolutionary history across homologous sequences, while the pair representation (shape \(L \times L \times c_z\)) tracks the spatial relationship between every pair of residues \((i, j)\).
-
Inside every Evoformer block, the two tracks talk continuously. Row-wise attention along the MSA is biased by the current pair matrix (so residues believed to be nearby in 3D exchange evolutionary information), while an outer product mean summarizes co-variation across MSA columns and injects it back into the pair matrix.
-
The jewel of the pair track is triangular reasoning. In ordinary 3D Euclidean space, any three residues \((i, j, k)\) must obey the triangle inequality (\(d_{ij} \le d_{ik} + d_{kj}\)). A naive pairwise network could easily hallucinate impossible geometry where \(i\) is \(4\,\text{\AA}\) from \(k\), \(k\) is \(4\,\text{\AA}\) from \(j\), yet \(i\) is \(50\,\text{\AA}\) from \(j\)! AlphaFold 2 updates each pair embedding \(\mathbf{z}_{ij}\) by summing multiplicative messages over every third residue \(k\) (triangular multiplicative update) and running triangle self-attention along edges sharing a vertex.
- By repeating this triangle message passing across \(48\) blocks, the pair representation self-organises into a globally consistent 3D distance geometry before a single atom is placed in space.
Structure Module, Rigid Frames, and Invariant Point Attention¶
-
Converting abstract pair embeddings into 3D coordinates raises a symmetry problem we studied in chapter 15. Rotating a protein \(90^\circ\) in space or shifting it across the room does not change its physics or identity! The Structure Module enforces strict \(SE(3)\) equivariance (invariance under rigid 3D rotations and translations) by representing every residue \(i\) as a tiny rigid triangle called a local frame \(T_i = (R_i, \mathbf{t}_i)\), where \(R_i \in SO(3)\) is a \(3 \times 3\) rotation matrix (chapter 02) and \(\mathbf{t}_i \in \mathbb{R}^3\) is the position of its \(\text{C}_\alpha\) atom.
-
All \(L\) frames start stacked together at the origin in what the authors affectionately called the black-hole initialisation, and \(8\) layers of Invariant Point Attention (IPA) iteratively push and rotate them into the folded protein. In IPA, each residue projects query and key 3D points into its own local frame, maps them into global coordinates using \(T_i\), and scores attention using squared Euclidean distances between query points of residue \(i\) and key points of residue \(j\). Because rigid rotations and translations preserve Euclidean distances, the resulting attention weights are strictly invariant to global pose, while predicted frame updates rotate equivariantly with the molecule!
FAPE Loss, Recycling, and Calibrated Confidence¶
- Training a 3D coordinate network directly with global root-mean-square error fails because a minor hinge tilt between two domains produces massive global coordinate errors even when both domains fold perfectly. AlphaFold 2 instead introduces Frame Aligned Point Error (FAPE). For every residue frame \(i\) and every predicted atom \(j\), FAPE transforms atom \(j\) into residue \(i\)'s local coordinate system (\(T_i^{-1} \circ \mathbf{x}_j\)) and compares it with the true structure viewed from the true frame \(i\).
-
FAPE is simultaneously invariant to global rigid motions, sensitive to mirror-image reflections (preserving biological chirality!), and smooth across both local side-chain packing and global domain placement thanks to clamping at \(d_{\text{clamp}} = 10\,\text{\AA}\).
-
Rather than making one giant pass, AlphaFold 2 uses iterative recycling, feeding its finished 3D coordinates and trunk embeddings right back into the input of the Evoformer three times. This acts like an artist stepping back from a sculpture, spotting a subtle proportion mismatch, and refining it cleanly without multiplying model parameters.
-
Finally, a scientific tool is only trustworthy when it knows what it does not know. AlphaFold 2 outputs two richly calibrated confidence metrics.
- pLDDT (predicted Local Distance Difference Test) gives every single residue a score from \(0\) to \(100\). Scores above \(90\) indicate crisp side-chain accuracy, \(70\) to \(90\) indicate a reliable backbone, and scores below \(50\) strongly flag intrinsically disordered regions that wiggle freely in water rather than adopting one fixed fold.
- PAE (Predicted Aligned Error) is an \(L \times L\) matrix where entry \((i, j)\) estimates the expected position error (in angstroms) of residue \(j\) when aligned on residue \(i\)'s frame. Dark low-error squares along the diagonal with bright high-error off-diagonal blocks immediately tell a biologist that two domains are individually rock-solid yet connected by a floppy linker!
Protein Language Models and Single-Sequence Folding¶
-
AlphaFold 2's main bottleneck is speed. Searching massive genomic databases to build a deep MSA can take tens of minutes per protein, and for orphan proteins or newly engineered synthetic proteins (section 03) no natural evolutionary family exists at all.
-
Protein Language Models (PLMs) such as ESM-2 take an audaciously direct inspiration from chapter 07. Treat hundreds of millions of natural protein sequences as a vast corpus of sentences written by evolution, randomly mask \(15\%\) of the amino acids, and train a deep Transformer (up to \(15\) billion parameters) to predict the missing letters using masked language modelling!
-
Remarkably, to predict a masked amino acid accurately across diverse species, the Transformer must implicitly internalise the hidden laws of protein folding inside its weights. Researchers discovered that ESM-2's self-attention maps spontaneously align with real 3D physical contacts even though the model was never shown a single 3D coordinate during pretraining.
-
ESMFold plugs those rich single-sequence ESM-2 representations straight into a streamlined folding trunk and IPA structure module, bypassing MSA database search entirely. The result runs up to \(60\times\) faster than AlphaFold 2, enabling scientists to fold over \(600\) million metagenomic proteins in weeks. The honest trade-off is accuracy on subtle folds where a deep MSA provides extra co-evolutionary constraints that a single-sequence model has not memorised.
AlphaFold 3 and All-Atom Biomolecular Diffusion¶
-
Real biology rarely involves a lonely protein floating by itself. Proteins bind DNA helices, splice RNA strands, dock small-molecule drugs, carry chemical modifications like phosphorylation, and coordinate metal ions such as zinc and magnesium. Because AlphaFold 2 hardcoded amino-acid backbone frames, it could not naturally place an arbitrary drug molecule or nucleic acid alongside a protein.
-
AlphaFold 3 and open-source successors such as Chai-1, Boltz-1 (MIT-licensed all-atom co-folding), and Boltz-2 (which pairs biomolecular co-folding directly with a fast small-molecule binding-affinity module) unify all of molecular biology inside one joint architecture connecting directly back to the diffusion generative models of chapter 08 and the ligand-binding chemistry explored in chapter 23.
-
Two major architectural shifts power this leap.
- Pairformer replaces heavy MSA processing. Rather than devoting \(48\) heavy blocks to dense MSA rows, AlphaFold 3 compresses MSA information lightly in just \(4\) blocks and spends almost all its capacity inside a \(48\)-block Pairformer operating purely on single and pairwise token representations across proteins, nucleotides, and chemical atoms.
- All-atom diffusion module replaces rigid frames. Instead of outputting residue frames via IPA, AlphaFold 3 uses a conditional denoising diffusion network operating directly on raw 3D atomic coordinates! Starting from a cloud of Gaussian noise centred on every atom of the protein, DNA, ligand, and ion complex, the diffusion module iteratively denoises the cloud into a sharp, physically realistic all-atom assembly.
-
Shifting to generative diffusion brings both extraordinary strengths and honest new failure modes. Because diffusion samples from a conditional distribution rather than averaging ambiguous outcomes, AlphaFold 3 predicts flexible pockets and protein-ligand complexes with far higher fidelity. Yet generative diffusion can occasionally hallucinate tidy-looking alpha-helices inside genuinely disordered loops (a flaw mitigated by cross-distilling training targets from AlphaFold 2) or occasionally violate minor stereochemical chirality rules, reminding us that even the strongest AI predictors still benefit from physical checks and experimental validation.
Take-Home¶
- Proteins fold from 1D chains of \(20\) amino acids into 3D molecular machines down an energy funnel, bypassing Levinthal's astronomical search space in milliseconds.
- Evolutionary co-variation across Multiple Sequence Alignments acts as a 3D ruler because distant residues that mutate together across species almost always touch physically in the folded protein.
- AlphaFold 2 pairs the Evoformer's triangular inequality updates with \(SE(3)\)-equivariant Invariant Point Attention, FAPE loss, recycling, and calibrated pLDDT and PAE confidence metrics to reach atomic accuracy.
- Protein language models like ESM-2 learn evolutionary and structural grammar purely from masked sequence prediction, enabling ESMFold to predict 3D structures rapidly from a single sequence without MSA search.
- AlphaFold 3 combines a streamlined Pairformer with all-atom diffusion to jointly model complexes of proteins, DNA, RNA, small-molecule ligands, and ions, unifying structural biology with molecular chemistry.
Coding Tasks (use CoLab or notebook)¶
-
Simulate a \(400\)-sequence Multiple Sequence Alignment governed by a pairwise co-evolutionary energy landscape with known 3D contacts, compute pairwise mutual information with Average Product Correction (APC) in JAX, and verify that co-variation recovers the hidden contact map.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt key = jax.random.PRNGKey(21) L = 24 n_seq = 400 alphabet = 4 # Simplified 4-state amino acid classes (positive, negative, hydrophobic, polar) # True long-range 3D contact pairs (i, j) true_pairs = [(2, 18), (3, 17), (4, 16), (6, 20), (7, 19), (10, 22)] # Sample independent background columns first k_bg, k_coup = jax.random.split(key) msa = jax.random.randint(k_bg, (n_seq, L), 0, alphabet) # Enforce strong co-variation on true contacts (complementary pairing with 12% noise) cols = [msa[:, c] for c in range(L)] for idx, (i, j) in enumerate(true_pairs): r1, r2 = jax.random.split(jax.random.PRNGKey(500 + idx)) partner = (alphabet - 1) - cols[i] noise_mask = jax.random.uniform(r1, (n_seq,)) < 0.12 rand_col = jax.random.randint(r2, (n_seq,), 0, alphabet) cols[j] = jnp.where(noise_mask, rand_col, partner) msa = jnp.stack(cols, axis=1) # One-hot encode MSA -> (n_seq, L, alphabet) oh = jnp.eye(alphabet, dtype=jnp.float32)[msa] p_single = jnp.mean(oh, axis=0) + 1e-8 # (L, A) p_joint = jnp.einsum("nia,njb->ijab", oh, oh) / n_seq + 1e-8 # (L, L, A, A) p_indep = p_single[:, None, :, None] * p_single[None, :, None, :] # Mutual information matrix MI(i, j) mi = jnp.sum(p_joint * jnp.log(p_joint / p_indep), axis=(-2, -1)) diag_mask = 1.0 - jnp.eye(L) mi = mi * diag_mask # Average Product Correction (APC) removes background phylogenetic noise row_mean = jnp.sum(mi, axis=1) / (L - 1) global_mean = jnp.sum(mi) / (L * (L - 1)) apc = (row_mean[:, None] * row_mean[None, :]) / (global_mean + 1e-8) mi_apc = jnp.maximum(0.0, (mi - apc) * diag_mask) # Build ground-truth contact map true_map = jnp.zeros((L, L)) for i, j in true_pairs: mask = ((jnp.arange(L)[:, None] == i) & (jnp.arange(L)[None, :] == j)) | ( (jnp.arange(L)[:, None] == j) & (jnp.arange(L)[None, :] == i) ) true_map = jnp.where(mask, 1.0, true_map) top_k = len(true_pairs) * 2 flat_idx = jnp.argsort(mi_apc.ravel())[-top_k:] hits = float(jnp.sum(true_map.ravel()[flat_idx])) print(f"Top-{top_k} APC co-variation peaks recovered {int(hits)} / {top_k} true symmetric contact entries") fig, axes = plt.subplots(1, 2, figsize=(9.5, 4)) axes[0].imshow(true_map, cmap="Blues", origin="lower") axes[0].set_title("True 3D Residue Contacts") axes[0].set_xlabel("Residue Index") axes[0].set_ylabel("Residue Index") im = axes[1].imshow(mi_apc, cmap="magma", origin="lower") axes[1].set_title("Recovered Co-Variation Map (MI + APC)") axes[1].set_xlabel("Residue Index") plt.colorbar(im, ax=axes[1], label="Coupling Score") plt.tight_layout() plt.show() -
Implement a differentiable 2D \(SE(2)\) Frame Aligned Point Error (FAPE) loss in JAX, confirm numerically that FAPE is strictly invariant under global rotations and translations, and optimise a scrambled chain of rigid frames directly into the native hairpin fold with
jax.grad.import jax import jax.numpy as jnp import matplotlib.pyplot as plt def rot2d(theta): c, s = jnp.cos(theta), jnp.sin(theta) return jnp.stack([jnp.stack([c, -s], axis=-1), jnp.stack([s, c], axis=-1)], axis=-2) def fape_loss(pred_t, pred_ang, true_t, true_ang, clamp=6.0): """Frame Aligned Point Error invariant to global rigid rotations and translations.""" R_pred = rot2d(pred_ang) R_true = rot2d(true_ang) # Express every residue position j inside every local frame i: R_i^T (t_j - t_i) diff_pred = pred_t[None, :, :] - pred_t[:, None, :] local_pred = jnp.einsum("iba,ijb->ija", R_pred, diff_pred) diff_true = true_t[None, :, :] - true_t[:, None, :] local_true = jnp.einsum("iba,ijb->ija", R_true, diff_true) dists = jnp.sqrt(jnp.sum((local_pred - local_true) ** 2, axis=-1) + 1e-6) return jnp.mean(jnp.minimum(dists, clamp)) # Create a native 14-residue hairpin fold s = jnp.linspace(0.0, jnp.pi, 14) true_t = jnp.stack([3.0 * jnp.sin(s), 4.5 * jnp.cos(s)], axis=-1) tangents = jnp.concatenate([true_t[1:] - true_t[:-1], true_t[-1:] - true_t[-2:-1]], axis=0) true_ang = jnp.arctan2(tangents[:, 1], tangents[:, 0]) # Test SE(2) invariance by rotating and shifting the true fold globally shift = jnp.array([12.5, -7.3]) phi = 1.15 R_glob = rot2d(phi) moved_t = jnp.einsum("ab,nb->na", R_glob, true_t) + shift moved_ang = true_ang + phi inv_err = float(fape_loss(moved_t, moved_ang, true_t, true_ang)) print(f"FAPE error after arbitrary global rotation + shift {inv_err:.6f} (strictly invariant)") # Optimise a black-hole-like noisy chain via FAPE gradients key = jax.random.PRNGKey(10) k1, k2 = jax.random.split(key) pred_t = 0.5 * jax.random.normal(k1, true_t.shape) pred_ang = jax.random.uniform(k2, true_ang.shape, minval=-jnp.pi, maxval=jnp.pi) grad_fn = jax.grad(fape_loss, argnums=(0, 1)) losses = [] for step in range(90): losses.append(float(fape_loss(pred_t, pred_ang, true_t, true_ang))) gt, ga = grad_fn(pred_t, pred_ang, true_t, true_ang) pred_t = pred_t - 0.35 * gt pred_ang = pred_ang - 0.35 * ga # Align predicted fold onto true fold using frame 0 for visual comparison R0_align = jnp.matmul(rot2d(true_ang[0]), rot2d(pred_ang[0]).T) aligned_pred = jnp.einsum("ab,nb->na", R0_align, pred_t - pred_t[0]) + true_t[0] print(f"FAPE dropped from {losses[0]:.3f} to {losses[-1]:.4f} over 90 steps") fig, axes = plt.subplots(1, 2, figsize=(10, 4)) axes[0].plot(losses, color="#9b59b6", lw=2) axes[0].set_title("FAPE Loss Convergence") axes[0].set_xlabel("Optimisation Step") axes[0].set_ylabel("FAPE Loss") axes[1].plot(true_t[:, 0], true_t[:, 1], "o-", color="#3498db", lw=2.5, label="True Fold") axes[1].plot(aligned_pred[:, 0], aligned_pred[:, 1], "x--", color="#27ae60", lw=2, label="FAPE Optimised Fold") axes[1].set_title("Rigid-Frame Alignment Recovery") axes[1].axis("equal") axes[1].legend() plt.tight_layout() plt.show() -
Simulate a two-domain protein linked by a floppy disordered hinge across an ensemble of predicted models to compute per-residue pLDDT and the \(L \times L\) PAE confidence matrix in JAX, visualising how both metrics diagnose local fold quality versus inter-domain uncertainty.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt key = jax.random.PRNGKey(33) n_ens = 25 L1, L_link, L2 = 16, 8, 16 L = L1 + L_link + L2 # Construct ideal coordinates for Domain A, flexible linker, and Domain B t1 = jnp.linspace(0.0, 2.5 * jnp.pi, L1) dom1 = jnp.stack([1.8 * jnp.cos(t1), 1.8 * jnp.sin(t1), jnp.linspace(0.0, 4.0, L1)], axis=-1) t_link = jnp.linspace(0.0, 1.0, L_link + 2)[1:-1] link_base = jnp.stack([1.8 + 4.5 * t_link, 0.5 * jnp.sin(3.0 * t_link), 4.0 + 1.5 * t_link], axis=-1) t2 = jnp.linspace(0.0, 2.5 * jnp.pi, L2) dom2 = jnp.stack([8.0 + 1.8 * jnp.cos(t2), 1.8 * jnp.sin(t2), 5.5 + jnp.linspace(0.0, 4.0, L2)], axis=-1) # Generate ensemble samples: rigid domains with low local noise, floppy linker, random hinge rotation of Domain B samples = [] for m in range(n_ens): rng = jax.random.PRNGKey(100 + m) k1, k2, k3, k4 = jax.random.split(rng, 4) d1_s = dom1 + 0.18 * jax.random.normal(k1, dom1.shape) lk_s = link_base + 1.6 * jax.random.normal(k2, link_base.shape) # Random hinge rotation around the z-axis for Domain B relative to Domain A ang = jax.random.uniform(k3, (1,), minval=-0.7, maxval=0.7)[0] c, s_a = jnp.cos(ang), jnp.sin(ang) Rz = jnp.array([[c, -s_a, 0.0], [s_a, c, 0.0], [0.0, 0.0, 1.0]]) pivot = jnp.array([6.5, 0.0, 5.5]) d2_rot = jnp.einsum("ab,nb->na", Rz, dom2 - pivot) + pivot d2_s = d2_rot + 0.22 * jax.random.normal(k4, dom2.shape) samples.append(jnp.concatenate([d1_s, lk_s, d2_s], axis=0)) ens = jnp.stack(samples, axis=0) # (n_ens, L, 3) # Pairwise distance matrices across the ensemble diffs = ens[:, :, None, :] - ens[:, None, :, :] dists = jnp.sqrt(jnp.sum(diffs ** 2, axis=-1) + 1e-6) # (n_ens, L, L) dist_std = jnp.std(dists, axis=0) # (L, L) proxy for PAE # Local pLDDT from stability of nearby neighbours (within 10 A in mean distance) mean_dist = jnp.mean(dists, axis=0) local_mask = (mean_dist < 10.0) & (mean_dist > 0.1) local_err = jnp.sum(dist_std * local_mask, axis=1) / (jnp.sum(local_mask, axis=1) + 1e-6) plddt = 100.0 * jnp.exp(-0.55 * local_err) print(f"Mean pLDDT Domain A {float(jnp.mean(plddt[:L1])):.1f}, Linker {float(jnp.mean(plddt[L1:L1+L_link])):.1f}, Domain B {float(jnp.mean(plddt[L1+L_link:])):.1f}") fig, axes = plt.subplots(1, 2, figsize=(10.5, 4)) axes[0].plot(jnp.arange(L), plddt, color="#27ae60", lw=2.2) axes[0].axvspan(L1, L1 + L_link - 1, color="#e74c3c", alpha=0.14, label="Disordered Linker") axes[0].axhline(70, color="#666", ls="--", lw=1) axes[0].set_ylim(0, 105) axes[0].set_title("Per-Residue Local Confidence (pLDDT)") axes[0].set_xlabel("Residue Index") axes[0].set_ylabel("pLDDT (0 to 100)") axes[0].legend() im = axes[1].imshow(dist_std, cmap="Greens_r", vmin=0.0, vmax=3.5, origin="upper") axes[1].set_title("Predicted Aligned Error Proxy (PAE Matrix)") axes[1].set_xlabel("Scored Residue j") axes[1].set_ylabel("Aligned Residue i") plt.colorbar(im, ax=axes[1], label="Position Uncertainty (A)") plt.tight_layout() plt.show()