A first look at a PDB file
A structure viewer makes it easy to forget that its molecule arrived as records in a file. Here we will start with those records and build our own small account of ubiquitin: which atoms were included, which chain they belong to, and how much space the protein occupies. The structure is 1UBQ throughout.
The goal is a parser you can check and a set of measurements you can explain. Try each task before opening its solution. Later cells use variables created earlier, so work down the page in order.
Setup
The displayed outputs let you follow the lab without installing anything. To run it in this repository,
use uv run scripts/notes.py bioprimer 0.9-lab-first-look-at-a-pdb-file. The notebook download at the top
of the page includes the primer helper; outside the repository it needs Python with Biopython, NumPy,
and Matplotlib. The embedded structure viewer provides the visual part of the exercise.
Task 1: inspect the records
primer.fetch returns a local copy of an entry's structure file. Before extracting coordinates, print
the opening lines and count the record types. The first six columns identify the kind of record. What
fraction of the lines actually describe atom positions?
from collections import Counter
from primer import fetch
path = fetch("1UBQ")
lines = path.read_text().splitlines()
print(len(lines), "lines; the longest has", max(map(len, lines)), "characters\n")
for line in lines[:8]:
print(line)
print()
print(Counter(line[:6].strip() for line in lines).most_common())
970 lines; the longest has 80 characters
HEADER CHROMOSOMAL PROTEIN 02-JAN-87 1UBQ
TITLE STRUCTURE OF UBIQUITIN REFINED AT 1.8 ANGSTROMS RESOLUTION
COMPND MOL_ID: 1;
COMPND 2 MOLECULE: UBIQUITIN;
COMPND 3 CHAIN: A;
COMPND 4 ENGINEERED: YES
SOURCE MOL_ID: 1;
SOURCE 2 ORGANISM_SCIENTIFIC: HOMO SAPIENS;
[('ATOM', 602), ('REMARK', 260), ('HETATM', 58), ('REVDAT', 6), ('JRNL', 6), ('SEQRES', 6), ('SHEET', 5), ('COMPND', 4), ('SOURCE', 4), ('HELIX', 2), ('HEADER', 1), ('TITLE', 1), ('KEYWDS', 1), ('EXPDTA', 1), ('AUTHOR', 1), ('DBREF', 1), ('FORMUL', 1), ('CRYST1', 1), ('ORIGX1', 1), ('ORIGX2', 1), ('ORIGX3', 1), ('SCALE1', 1), ('SCALE2', 1), ('SCALE3', 1), ('TER', 1), ('MASTER', 1), ('END', 1)]ATOM records describe atoms in standard protein or nucleic-acid residues; HETATM records include
waters, ligands, and some modified residues. In this entry there are 602 ATOM records and 58 HETATM
records. The latter are water oxygens. Other records contain information such as the reported sequence,
experimental details, and annotations of helices and sheets.
The file is doing two jobs: describing a molecular model and recording information about how to interpret it. Extracting the coordinates should not make us forget the second job.
Task 2: decode one atom exactly
Legacy PDB records use fixed columns. Empty fields still occupy their allotted spaces. Read the following table as one-based, inclusive column numbers:
| Columns | Field | Example |
|---|---|---|
| 1–6 | record name | ATOM |
| 7–11 | atom serial number | 1 |
| 13–16 | atom name | N |
| 17 | alternate location | blank |
| 18–20 | residue name | MET |
| 22 | chain identifier | A |
| 23–26 | residue number | 1 |
| 27 | insertion code | blank |
| 31–38, 39–46, 47–54 | x, y, z in Å | 27.340 |
| 55–60 | occupancy | 1.00 |
| 61–66 | B factor | 9.67 |
| 77–78 | element | N |
Occupancy describes the modeled fraction at a site; alternate-location records can describe multiple positions. The B factor describes displacement or disorder within the crystallographic model. We will interpret these fields more carefully in chapter 6. For this task, extract them without shifting them into a neighboring column.
Write parse_atom(line) to return these fields as a dictionary. Convert number fields to numbers.
Columns 31–38 become the Python slice line[30:38].
def parse_atom(line):
... # your code: slice each field out of the line, strip spaces, convert numbers
Solution
def parse_atom(line):
return {
"record": line[0:6].strip(),
"serial": int(line[6:11]),
"name": line[12:16].strip(),
"altloc": line[16].strip(),
"resname": line[17:20].strip(),
"chain": line[21].strip(),
"resseq": int(line[22:26]),
"icode": line[26].strip(),
"x": float(line[30:38]),
"y": float(line[38:46]),
"z": float(line[46:54]),
"occupancy": float(line[54:60]),
"bfactor": float(line[60:66]),
"element": line[76:78].strip(),
}
atom_lines = [line for line in lines if line.startswith(("ATOM ", "HETATM"))]
atoms = [parse_atom(line) for line in atom_lines]
print(len(atoms), "atoms")
print(atoms[0])
print(atoms[-1])
660 atoms
{'record': 'ATOM', 'serial': 1, 'name': 'N', 'altloc': '', 'resname': 'MET', 'chain': 'A', 'resseq': 1, 'icode': '', 'x': 27.34, 'y': 24.43, 'z': 2.614, 'occupancy': 1.0, 'bfactor': 9.67, 'element': 'N'}
{'record': 'HETATM', 'serial': 661, 'name': 'O', 'altloc': '', 'resname': 'HOH', 'chain': 'A', 'resseq': 134, 'icode': '', 'x': 37.667, 'y': 43.421, 'z': 17.0, 'occupancy': 0.5, 'bfactor': 33.32, 'element': 'O'}Now stress the tempting alternative, line.split(). Insert two negative coordinates that each fill
their eight-character field:
line = atom_lines[0]
fused = line[:30] + f"{-100.123:8.3f}{-200.456:8.3f}" + line[46:]
print(fused)
print(fused.split())
print({k: parse_atom(fused)[k] for k in ("x", "y", "z")})
ATOM 1 N MET A 1 -100.123-200.456 2.614 1.00 9.67 N
['ATOM', '1', 'N', 'MET', 'A', '1', '-100.123-200.456', '2.614', '1.00', '9.67', 'N']
{'x': -100.123, 'y': -200.456, 'z': 2.614}The fields have no separating whitespace, so splitting merges the numbers. This is not an overflow; each number fits its field exactly. The format never promised a delimiter between them. A parser that works only when the values happen to leave spaces is using a property of the sample instead of the format.
Task 3: compare two independent readings
Use Biopython's parser as a second implementation. For this entry, identify an atom by its chain, residue number, and atom name, then compare the key sets and coordinates. Predict the expected agreement before running the code.
Solution
import numpy as np
from primer import structure
s = structure("1UBQ")
bio = {(a.get_parent().get_parent().id, a.get_parent().id[1], a.get_id()): a.coord for a in s.get_atoms()}
mine = {(a["chain"], a["resseq"], a["name"]): np.array([a["x"], a["y"], a["z"]]) for a in atoms}
print("Biopython:", len(bio), "atoms; mine:", len(mine), "atoms; same keys:", bio.keys() == mine.keys())
print(f"largest coordinate difference: {max(np.abs(bio[k] - mine[k]).max() for k in mine):.1e} Å")
Biopython: 660 atoms; mine: 660 atoms; same keys: True largest coordinate difference: 1.9e-06 Å
The keys should agree and the coordinate difference should be tiny, around floating-point rounding. Biopython stores these coordinates as 32-bit floats. Agreement at this scale checks parsing; it does not mean the experiment located atoms to millionths of an ångström.
Our short key is sufficient for 1UBQ. General files may require model identifiers, residue kinds, insertion codes, and alternate-location handling to avoid collisions. A residue numbered 52A must not silently overwrite residue 52 in a dictionary.
Task 4: separate the molecule from what was modeled
Count residues by kind, atoms by element, and hydrogens. Compare the residues with coordinates to the
sequence in SEQRES. Before running the cell, decide whether every water in the crystal and every
hydrogen in the protein must appear in the file.
Solution
from primer import sequence
model = s[0]
for chain in model:
kinds = Counter("amino acid" if r.id[0] == " " else "water" if r.get_resname() == "HOH" else "other"
for r in chain)
print("chain", chain.id, dict(kinds))
print("elements:", Counter(a["element"] for a in atoms))
print("hydrogens:", sum(a["element"] == "H" for a in atoms))
seqres = " ".join(line[19:70] for line in lines if line.startswith("SEQRES")).split() # 13 names per line
print("SEQRES:", len(seqres), "residues; with coordinates:", len(sequence(model["A"])))
chain A {'amino acid': 76, 'water': 58}
elements: Counter({'C': 378, 'O': 176, 'N': 105, 'S': 1})
hydrogens: 0
SEQRES: 76 residues; with coordinates: 76The model has one protein chain with 76 residues, plus 58 water oxygens and no hydrogen atoms. Hydrogen scatters X-rays weakly, and this 1.8 Å structure does not list individual hydrogens. Waters appear only where a position could be modeled from the data. Neither absence implies that the real molecule existed without hydrogen or without surrounding water.
All 76 sequence residues have coordinates here. A less ordered region in another protein might lack coordinates even though its residues were present in the experimental sample. A missing record can reflect the limits of a model rather than a deletion from the molecule.
Task 5: measure compactness
The largest atom-to-atom distance tells us the protein's span, but one extended tail can dominate it. The radius of gyration measures the distribution of all selected points about their centroid:
Compute this equally weighted quantity for the protein heavy atoms and for its Cα atoms. A physical mass-weighted radius uses atom masses as weights; here we want a geometric measure of each point set. Then compare with a uniform sphere of the same approximate mass and density 1.35 g/cm³. A uniform sphere of radius has .
Solution
protein = np.array([a.coord for a in model["A"].get_atoms()
if a.get_parent().id[0] == " "], dtype=float)
ca = np.array([r["CA"].coord for r in model["A"] if r.id[0] == " "], dtype=float)
def radius_of_gyration(xyz):
return np.sqrt(((xyz - xyz.mean(axis=0)) ** 2).sum(axis=1).mean())
n = len(ca)
D = np.linalg.norm(protein[:, None] - protein[None], axis=-1)
volume = n * 110 / (1.35 * 6.022e23) * 1e24 # approximate volume in ų
sphere_radius = (3 * volume / (4 * np.pi)) ** (1 / 3)
print(f"heavy atoms: {len(protein)}, Rg = {radius_of_gyration(protein):.1f} Å")
print(f"Cα atoms: {n}, Rg = {radius_of_gyration(ca):.1f} Å")
print(f"largest atom-atom distance: {D.max():.1f} Å")
print(f"uniform-sphere reference Rg: {np.sqrt(3 / 5) * sphere_radius:.1f} Å")
print(f"Cα path length: {np.linalg.norm(np.diff(ca, axis=0), axis=1).sum():.1f} Å")
heavy atoms: 602, Rg = 11.7 Å Cα atoms: 76, Rg = 11.5 Å largest atom-atom distance: 44.0 Å uniform-sphere reference Rg: 10.4 Å Cα path length: 285.7 Å
The measured is around 12 Å, close to the compact-sphere scale. The chain's Cα path is much longer than its span: the chain repeatedly turns back through the same small volume. The sphere estimate will not reproduce a tail or a cavity, but it helps us recognize the scale of a compact arrangement.
Task 6: explain what each picture omits
In the viewer, follow the chain in the cartoon, then switch to sticks and space-filling spheres. Find the contact between residues 5 and 68 from lesson 0.3. Before changing views, predict what will become easier to see and what will be obscured.
The cartoon exposes the chain's path through the fold. Sticks expose its bond graph. Space-filling spheres expose the occupied volume. The final view measures the Cα separation of Val 5 and His 68; these are the same coordinates in every representation.
Open 1UBQ in Mol*For a larger working view, open 1UBQ in Mol*. Locate the same two residues and compare the atom selections with the embedded view. Record both atom names with any distance you report: “5.7 Å between residues” is ambiguous until we know which points were measured.
Solution
A cartoon is useful for tracing the fold but suppresses most atoms. Sticks show connections but make the molecule look more porous than it is. Spheres show packing but can hide the chain inside the protein. The Val 5–His 68 measurement is between their Cα atoms, not between their closest side-chain atoms.
Self-check
A line reads:
ATOM 52183 CA GLY B1042 -101.274-112.509 34.120 1.00 61.20 C
Identify the residue number and x and y coordinates. Which assumptions would a whitespace parser violate?
Reasoning
The residue number is 1042, x is −101.274 Å, and y is −112.509 Å. Chain B touches the residue number, and x touches y, because each field occupies fixed columns. Whitespace splitting cannot reliably separate them. Depending on the implementation, it will either fail or misassign fields.
A parser agrees with Biopython within Å. Can you report a protein contact distance with six decimal places of experimental precision?
Reasoning
No. That agreement concerns numerical storage and parsing of the same coordinates. Experimental uncertainty and modeling error are much larger and must be assessed from the structure's evidence. Repeating a model's digits precisely does not improve the underlying measurement.
A chain is numbered 50, 51, 52, 52A, 53, 60, 61. What must a parser keep, and what would you inspect before claiming that residues 54–59 are absent from the protein?
Reasoning
Keep the insertion code distinguishing 52A from 52. Inspect the full sequence and annotations: the gap may represent residues without modeled coordinates, an intentional numbering convention, or a changed experimental construct. Residue numbers are labels and cannot safely be used as array positions.
A 300-residue model has Å. Scaling the 76-residue compact-sphere reference by gives roughly 16–17 Å. What can you conclude, and what must you look at next?
Reasoning
The model is much more extended than a compact sphere of similar mass. It could be a rod, multiple separated domains, or a compact core with long extended tails. Inspect the geometry and confidence or experimental support before deciding whether the extension is biological or a modeling problem.
Why should a parser for this small legacy PDB file not automatically be used for a huge molecular assembly? Name a representational limit as well as an atom-identity problem.
Reasoning
The legacy format has only five columns for atom serial numbers and one character for a chain ID. PDBx/mmCIF accommodates much larger assemblies and richer identifiers. Even within smaller files, alternate locations and insertion codes can make a short atom key nonunique. Use a format-aware library and a complete identity scheme for general work.