The geometry of a fold
In this lab you compute torsion angles, Ramachandran plots, a contact map, and a secondary-structure assignment from raw coordinates, and check each against an independent answer. The structures are ubiquitin (1UBQ, 76 residues) and the catalytic subunit of protein kinase A (1ATP, chain E, 336 residues). Everything runs in plain NumPy plus Biopython's parser. Try each task before opening its solution.
Task 1: φ and ψ for a whole chain
Write a vectorized dihedral function that takes four (n × 3) arrays and returns n signed angles, then use it to
compute φ, ψ, and ω for every residue of both proteins. Check the result against Biopython's PPBuilder, which
computes φ and ψ its own way. Handle chain breaks. Many structures have residues missing from their coordinates
(neither of these two does), and φ or ψ across a gap is meaningless. Detect a break by a C(i)–N(i+1) distance much
longer than the 1.33 Å peptide bond. Also keep modified residues: 1ATP's phosphothreonine 197 is stored as a HETATM
record but is part of the chain.
Solution
import numpy as np
from Bio.PDB import PPBuilder
from primer import structure, fetch
def dihedrals(p1, p2, p3, p4):
"""Signed dihedral angles (degrees) for rows of four (n, 3) arrays."""
b1, b2, b3 = p2 - p1, p3 - p2, p4 - p3
n1, n2 = np.cross(b1, b2), np.cross(b2, b3)
b2u = b2 / np.linalg.norm(b2, axis=1, keepdims=True)
y = np.einsum("ij,ij->i", np.cross(n1, n2), b2u)
return np.degrees(np.arctan2(y, np.einsum("ij,ij->i", n1, n2)))
def backbone(pdb_id, chain_id):
# Every residue with a full backbone, including modified ones (1ATP's phosphothreonine is a HETATM record).
res = [r for r in structure(pdb_id)[0][chain_id] if all(a in r for a in ("N", "CA", "C", "O"))]
N, CA, C, O = (np.array([r[a].coord for r in res]) for a in ("N", "CA", "C", "O"))
return res, N, CA, C, O
def torsions(N, CA, C):
n = len(N)
phi, psi, omega = (np.full(n, np.nan) for _ in range(3))
linked = np.linalg.norm(N[1:] - C[:-1], axis=1) < 2.0 # True where residue i+1 is bonded to i
phi[1:] = np.where(linked, dihedrals(C[:-1], N[1:], CA[1:], C[1:]), np.nan)
psi[:-1] = np.where(linked, dihedrals(N[:-1], CA[:-1], C[:-1], N[1:]), np.nan)
omega[:-1] = np.where(linked, dihedrals(CA[:-1], C[:-1], N[1:], CA[1:]), np.nan)
return phi, psi, omega, linked
data = {}
for pdb_id, chain_id in [("1UBQ", "A"), ("1ATP", "E")]:
res, N, CA, C, O = backbone(pdb_id, chain_id)
phi, psi, omega, linked = torsions(N, CA, C)
data[pdb_id] = dict(res=res, N=N, CA=CA, C=C, O=O, phi=phi, psi=psi, omega=omega)
# Biopython's answer, keyed by residue number.
ref = {}
for pp in PPBuilder().build_peptides(structure(pdb_id)[0][chain_id]):
for r, (f, s) in zip(pp, pp.get_phi_psi_list()):
ref[r.id[1]] = (np.degrees(f) if f is not None else np.nan, np.degrees(s) if s is not None else np.nan)
mine = np.array([[phi[k], psi[k]] for k, r in enumerate(res) if r.id[1] in ref])
theirs = np.array([ref[r.id[1]] for r in res if r.id[1] in ref])
both = ~np.isnan(mine) & ~np.isnan(theirs)
print(f"{pdb_id}: {len(res)} residues, {(~linked).sum()} chain breaks, "
f"largest difference from Biopython {np.abs(mine - theirs)[both].max():.4f}°, "
f"cis peptides: {np.sum(np.abs(omega) < 30)}")
1UBQ: 76 residues, 0 chain breaks, largest difference from Biopython 0.0000°, cis peptides: 0 1ATP: 336 residues, 0 chain breaks, largest difference from Biopython 0.0000°, cis peptides: 0
The two methods agree to rounding error, and neither protein has a cis peptide bond. On a structure with gaps, the
linked test is what stops residues on either side of a gap from getting φ or ψ from atoms that aren't bonded.
Biopython's PPBuilder does the same by splitting the chain into peptides at breaks.
Task 2: Ramachandran plots
Plot ψ against φ for both proteins, with glycine and proline in their own colors. Then list every non-glycine residue with φ > 0, and say for each whether it falls in the αL region (around +60°, +45°).
Solution
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2, figsize=(9, 4.2), sharey=True)
for ax, pdb_id in zip(axes, data):
d = data[pdb_id]
names = np.array([r.get_resname() for r in d["res"]])
for label, mask, color in [("other", (names != "GLY") & (names != "PRO"), "#333333"),
("Gly", names == "GLY", "#6250d6"), ("Pro", names == "PRO", "#eb6834")]:
ax.scatter(d["phi"][mask], d["psi"][mask], s=9, color=color, label=label, alpha=0.75)
ax.set(xlim=(-180, 180), ylim=(-180, 180), xticks=range(-180, 181, 90), yticks=range(-180, 181, 90),
title=pdb_id, xlabel="φ (degrees)")
axes[0].set_ylabel("ψ (degrees)")
axes[1].legend(loc="lower right")
plt.tight_layout()
plt.show()
for pdb_id, d in data.items():
for k, r in enumerate(d["res"]):
if r.get_resname() != "GLY" and d["phi"][k] > 0:
where = "αL" if 20 < d["phi"][k] < 100 and 0 < d["psi"][k] < 90 else "elsewhere"
print(f"{pdb_id} {r.get_resname()} {r.id[1]:3}: φ {d['phi'][k]:6.1f}°, ψ {d['psi'][k]:6.1f}° ({where})")
1UBQ ALA 46: φ 48.2°, ψ 46.0° (αL) 1UBQ ASN 60: φ 57.9°, ψ 45.4° (αL) 1UBQ GLU 64: φ 66.9°, ψ 19.1° (αL) 1ATP ASN 36: φ 29.5°, ψ 75.1° (αL) 1ATP LYS 83: φ 57.8°, ψ 49.2° (αL) 1ATP ASP 161: φ 56.6°, ψ 22.9° (αL) 1ATP ARG 165: φ 51.8°, ψ 19.2° (αL) 1ATP ASP 184: φ 48.7°, ψ 87.1° (αL) 1ATP SER 212: φ 50.5°, ψ 42.0° (αL) 1ATP ARG 308: φ 63.9°, ψ 32.9° (αL)
Ten of the 412 residues are non-glycines with φ > 0, and all ten sit in or near the αL region. Asn and Asp are overrepresented there, because their side chains can hydrogen-bond back to the backbone and pay for the strain. One of them is Asp 184 of the kinase's DFG motif (the conserved Asp-Phe-Gly at the start of a loop in the C-lobe), an active-site residue held in a strained conformation where it binds the metal ions. A non-glycine far outside the αL region would be worth a look in a viewer: check its density, or whether its neighbors explain it.
Task 3: a contact map
Compute ubiquitin's Cβ–Cβ distance matrix (Cα for glycine), threshold it at 8 Å, and plot it. Draw the helices and strands from the file's HELIX and SHEET records along the axes. Then answer from the picture: which pairs of strands are parallel, and which antiparallel? Confirm with the senses in the SHEET records.
Solution
from matplotlib.patches import Rectangle
res = data["1UBQ"]["res"]
num = [r.id[1] for r in res]
cb = np.array([(r["CB"] if "CB" in r else r["CA"]).coord for r in res])
dist = np.linalg.norm(cb[:, None] - cb[None], axis=2)
contact = dist < 8.0
ss = []
for line in fetch("1UBQ").read_text().splitlines():
if line.startswith("HELIX"):
ss.append(("helix", int(line[21:25]), int(line[33:37]), ""))
elif line.startswith("SHEET"):
ss.append(("strand", int(line[22:26]), int(line[33:37]), line[38:40].strip()))
fig, ax = plt.subplots(figsize=(5.2, 5.2))
ax.imshow(contact, cmap="Blues", origin="upper", extent=(0.5, len(res) + 0.5, len(res) + 0.5, 0.5))
for kind, a, b, _ in ss:
color = "#eb6834" if kind == "helix" else "#2a78d6"
ax.add_patch(Rectangle((a - 0.5, -2.5), b - a + 1, 2, color=color, clip_on=False))
ax.add_patch(Rectangle((-2.5, a - 0.5), 2, b - a + 1, color=color, clip_on=False))
ax.set(xlabel="residue", ylabel="residue", title="1UBQ Cβ contacts < 8 Å")
plt.show()
for kind, a, b, sense in ss:
if kind == "strand":
print(f"strand {a:2}–{b:2}: sense to previous strand {sense or '(first)'}")
strand 10–17: sense to previous strand 0 strand 1– 7: sense to previous strand -1 strand 64–72: sense to previous strand 1 strand 40–45: sense to previous strand -1 strand 48–50: sense to previous strand -1
The hairpin (1–7, 10–17) is a band perpendicular to the diagonal, so it is antiparallel. Strands 1–7 and 64–72 give a band parallel to the diagonal, in the corner: parallel. The SHEET records list the strands in sheet order (10–17, 1–7, 64–72, 40–45, 48–50) with senses 0, −1, 1, −1, −1: each sense is relative to the strand before it in that list, and the parallel pair is the 1 between 1–7 and 64–72.
Task 4: assign secondary structure from hydrogen bonds
Implement a simplified DSSP:
- Place each amide H 1.0 Å from N, opposite the previous residue's C=O bond.
- Compute the electrostatic H-bond energy for every C=O(i) ← N–H(j) pair, kcal/mol, and call it a bond when E < −0.5. This is Coulomb's law (lesson 1.4) summed over the four atom pairs, with DSSP's partial charges of ±0.42 on C and O and ±0.20 on N and H (their product is the 0.084) and 332, the constant that turns charge²/Å into kcal/mol.
- Helix: if residues i−1 and i both have an i → i+4 bond (C=O of i−1 to N–H of i+3, and C=O of i to N–H of i+4), label residues i through i+3 as H.
- Strand: residues i and j form an antiparallel bridge if bonds i→j and j→i both exist, or i−1→j+1 and j−1→i+1 both exist. They form a parallel bridge if i−1→j and j→i+1 exist, or j−1→i and i→j+1 exist. (Here a→b means the C=O of a bonds to the N–H of b.) Label bridge residues E.
Compare your labels with the HELIX and SHEET records for both proteins: what fraction of residues agree, and where are the disagreements?
Solution
def hbonds(N, CA, C, O):
"""Boolean matrix hb[i, j]: the C=O of residue i accepts a hydrogen bond from the N–H of residue j."""
H = N.copy()
dirn = C[:-1] - O[:-1]
H[1:] = N[1:] + dirn / np.linalg.norm(dirn, axis=1, keepdims=True)
r = lambda P, Q: np.linalg.norm(P[:, None] - Q[None], axis=2)
E = 0.084 * 332 * (1 / r(O, N) + 1 / r(C, H) - 1 / r(O, H) - 1 / r(C, N))
hb = E < -0.5
n = len(N)
near = np.abs(np.arange(n)[:, None] - np.arange(n)[None]) < 2
hb[near] = False
hb[:, 0] = False # the first residue has no H placed from a previous residue
return hb
def assign(hb):
n = len(hb)
label = np.array(["C"] * n)
turn4 = np.array([i + 4 < n and hb[i, i + 4] for i in range(n)])
for i in range(1, n - 3):
if turn4[i - 1] and turn4[i]:
label[i:i + 4] = "H"
b = lambda i, j: 0 <= i < n and 0 <= j < n and hb[i, j]
for i in range(1, n - 1):
for j in range(1, n - 1):
if abs(i - j) < 3 or label[i] == "H":
continue
anti = (b(i, j) and b(j, i)) or (b(i - 1, j + 1) and b(j - 1, i + 1))
para = (b(i - 1, j) and b(j, i + 1)) or (b(j - 1, i) and b(i, j + 1))
if anti or para:
label[i] = "E"
return "".join(label)
def from_records(pdb_id, chain_id, res):
index = {r.id[1]: k for k, r in enumerate(res)}
label = ["C"] * len(res)
for line in fetch(pdb_id).read_text().splitlines():
if line.startswith("HELIX") and line[19] == chain_id:
rng, tag = range(int(line[21:25]), int(line[33:37]) + 1), "H"
elif line.startswith("SHEET") and line[21] == chain_id:
rng, tag = range(int(line[22:26]), int(line[33:37]) + 1), "E"
else:
continue
for k in rng:
if k in index:
label[index[k]] = tag
return "".join(label)
for pdb_id, chain_id in [("1UBQ", "A"), ("1ATP", "E")]:
d = data[pdb_id]
mine = assign(hbonds(d["N"], d["CA"], d["C"], d["O"]))
theirs = from_records(pdb_id, chain_id, d["res"])
agree = np.mean([a == b for a, b in zip(mine, theirs)])
print(f"{pdb_id}: {agree:.0%} of residues agree with the file's HELIX/SHEET records")
if pdb_id == "1UBQ":
print(" computed ", mine)
print(" records ", theirs)
1UBQ: 80% of residues agree with the file's HELIX/SHEET records computed CEEEEEECCCCEEEEECCCCCEHHHHHHHHHHHHCCCCCCEEEEECCEECCCCCECCCCCCCCCCEEEEEECCCCC records EEEEEEECCEEEEEEEECCCCCHHHHHHHHHHHHCCCCCEEEEEECCEEECCCCCHHHHCCCCEEEEEEEEECCCC 1ATP: 94% of residues agree with the file's HELIX/SHEET records
Agreement is 80% for ubiquitin and 94% for the kinase. In ubiquitin, most disagreements are at strand ends, where the records extend each strand a residue or two beyond its last hydrogen-bonded pair. The rest come from the short helix at 56–59, which this simplified version doesn't assign (see the self-check), and two isolated "E" residues from single bridges. The HELIX and SHEET records are themselves an assignment, often made by DSSP or by the depositors, so this measures agreement between methods; neither string is ground truth.
Task 5: the kinase's two lobes and its ATP
Open 1ATP in Mol* (or the view below) and find the two lobes, the glycine-rich loop over ATP, and the hinge that joins the lobes (around residue 120). Then compute which residues have any atom within 4 Å of ATP, and which lobe each belongs to (N-lobe up to 120, C-lobe from 128).
Protein kinase A (1ATP, chain E). First view: N-terminus blue, C-terminus red, so the N-lobe is mostly blue and green and the C-lobe orange and red. Second view: the residues around ATP as sticks; compare them with your list.
Open 1ATP in Mol*Solution
from Bio.PDB import NeighborSearch
model = structure("1ATP")[0]
atp = next(r for r in model["E"] if r.get_resname() == "ATP")
search = NeighborSearch([a for a in model["E"].get_atoms() if a.get_parent().id[0] == " "])
close = sorted({a.get_parent().id[1] for atom in atp for a in search.search(atom.coord, 4.0)})
names = {r.id[1]: r.get_resname().capitalize() for r in model["E"]}
lobe = lambda k: "N-lobe" if k <= 120 else ("hinge" if k < 128 else "C-lobe")
for part in ("N-lobe", "hinge", "C-lobe"):
print(f"{part:7}", ", ".join(f"{names[k]} {k}" for k in close if lobe(k) == part))
N-lobe Leu 49, Gly 50, Thr 51, Gly 52, Ser 53, Phe 54, Gly 55, Val 57, Ala 70, Lys 72, Val 104, Met 120 hinge Glu 121, Tyr 122, Val 123, Glu 127 C-lobe Asp 166, Lys 168, Glu 170, Asn 171, Leu 173, Thr 183, Asp 184, Phe 327
ATP touches both lobes: the glycine-rich loop and Lys 72 from above, the hinge (Glu 121 to Glu 127), where its adenine ring (the flat, two-ring base at the far end from the phosphates) hydrogen-bonds to the backbone, and from below the catalytic loop (Asp 166 to Asn 171) and Asp 184 of the DFG motif, which hold the phosphates and the metal ions. Phe 327 comes from the C-terminal tail, which wraps back over the N-lobe. Most kinase inhibitors bind in this same cleft and copy the adenine's hydrogen bonds to the hinge.
Self-check
Your φ/ψ code gives every residue of a protein φ values near +60° and ψ near +45°, and the Ramachandran plot is a mirror image of normal. What are the two likely explanations, and how would you tell them apart?
Reasoning
Either a bug that flips the sign, such as atoms in the wrong order (for example N, C(i−1), Cα, C instead of C(i−1), N, Cα, C) or a cross-product order swapped; or the molecule really is a mirror image, made of D-amino acids, or with its coordinates reflected (one axis negated) somewhere in processing. Test your code on a structure you trust, such as 1UBQ, where helix residues must come out near (−60°, −45°). If it passes, check the chirality of the suspect structure directly: the C–N–Cα–Cβ dihedral is about −122° for L residues and +122° for D.
In your contact map, a residue pair with |i − j| = 40 is in contact in the crystal structure, but a predicted model places them 20 Å apart. The model's φ/ψ angles are all in allowed regions. What does each test tell you?
Reasoning
The Ramachandran test checks each residue's local geometry, and the model passes it. The contact is a long-range, global feature, so the model has the wrong tertiary arrangement: perhaps a strand paired with the wrong partner, or a domain rotated. Contact maps catch errors the Ramachandran plot cannot, which is why structure-prediction assessments score long-range contacts and distances (for example lDDT or the fraction of correct contacts) as well as local stereochemistry.
Your simplified DSSP labels residues 56–59 of ubiquitin as coil, while the HELIX record calls them a helix. Look at which hydrogen bonds the segment makes. What kind of helix is it, and why did your code miss it?
Reasoning
The bonds in that stretch are i → i+3 rather than i → i+4 (the HELIX record's class field for 56–59 is 5, the PDB's code for a 3₁₀ helix). Step 3 only looks for pairs of consecutive i → i+4 bonds, so a 3₁₀ turn is invisible to it. Full DSSP checks i → i+3 and i → i+5 patterns as well and would label these residues G. In the three-state reduction G becomes H, which is why the records and a full DSSP run agree.
A mutation changes Gly 10 of ubiquitin, at φ ≈ +77°, to valine. Using what you computed, predict the local structural effect and how you would test the prediction computationally.
Reasoning
Valine is β-branched and can't comfortably sit at φ > 0. Its Cβ would collide with the backbone, so the hairpin's turn (residues 7–10) would have to rearrange or strain, and the β1–β2 hairpin could loosen. Computationally: build the mutant, then run energy minimization or a short molecular dynamics run (a simulation that moves the atoms under a force field; unit 4), or predict both sequences with a structure predictor. Then compare the turn's φ/ψ and the hairpin's hydrogen-bond ladder (task 4's code) between the wild type and the mutant.