PDB and mmCIF files
Almost every structural-bioinformatics program starts by reading one of two file formats, and parsing bugs here fail silently: a shifted column, a residue number taken for a sequence position, or a missing loop closed up as if it weren't there will corrupt a whole dataset without raising an error. This lesson reads both formats field by field, then the identifiers that trip people up: residue numbers, chains, models, and the gap between what is in the file and the molecule in the cell.
What an entry records
The PDB archive consists of entries containing three-dimensional Cartesian coordinates, information specific to the method of structure determination, and experimental data. These include structure factors for X-ray experiments and constraints generated by NMR experiments. The table below contains the general information collected for all structures,Proteins for structure work are rarely purified from their native organism. The gene is put into a carrier DNA (the expression vector) and introduced into a fast-growing host, usually the bacterium E. coli, which then makes the protein in bulk. as well as some of the information specific to X-ray experiments.
| Content of all depositions |
|---|
| Source: genus, species, strain, or variant of gene (cloned or synthetic); expression vector and host, or the method of chemical synthesis |
| Sequence: full sequence of all macromolecular components |
| Chemical structure of cofactors and prosthetic groups (cofactors bound so tightly they act as part of the protein, like heme) |
| Names of all components of the structure |
| Literature citations for the structure submitted |
| Three-dimensional coordinates |
| Keywords and experimental method |
| Additional items for X-ray structures |
| Temperature factors and occupancies assigned to each atom |
| Crystallization conditions, including pH, temperature, solvents, salts, and methods |
| Crystal data, including the unit cell dimensions and space group |
| Data collection information: instrument, wavelength, temperature, and processing programs |
| Refinement information, including R factor, resolution limits, number of reflections, and geometry |
| Structure factors, with the flag marking the free-R test set |
Each deposition to the PDB is represented by a PDB ID, a four-character code. The PDB ID is assigned arbitrarily and is an immutable reference to the structure. PDB IDs are never reused and remain the link between the structure and the literature reference that describes that structure.
The legacy PDB format
The Protein Data Bank was established in 1971 at Brookhaven National Laboratory, in response to community requests for a central repository of information on biological macromolecular structures. Seven structures were included in the PDB at its inception. The essential elements of the format used to encode these first entries are still the core of the PDB format used today.
The PDB format consists of a collection of fixed format records that describe the atomic coordinates, chemical and biochemical features, experimental details of the structure determination, and some structural features such as secondary structure assignments, hydrogen bonding, biological assemblies, and active sites. Each item of the data in the PDB format is assigned to a range of character positions in one of many PDB record types (HEADER, SOURCE, REMARK, etc.). The ATOM records encode the atomic coordinate data. ATOM records are among the more than 45 named data records in the PDB format, and these records have strict column formatting rules.

Here are real records from the anchor structures. Every field lives in a fixed range of columns, and the ranges, not the spaces, define the fields:
Code
import numpy as np
from primer import alphafold, display_widget, fetch, structure
def records(pdb_id, keep, limit=None):
path = alphafold(pdb_id[3:]) if pdb_id.startswith("AF-") else fetch(pdb_id)
lines = [l.rstrip("\n") for l in open(path) if l.startswith(("ATOM", "HETATM")) and keep(l)]
return lines[:limit]
lines = (records("1UBQ", lambda l: l.startswith("ATOM"), 1)
+ records("7RSA", lambda l: l[12:16] == " CB " and l[17:26] == "GLN A 11")
+ records("1PPB", lambda l: l[12:16] == " CA " and l[21:27] == "H 60A")
+ records("4HHB", lambda l: l[12:16] == "FE ", 1)
+ records("1UBQ", lambda l: l.startswith("HETATM"), 1)
+ records("1AON", lambda l: l[30:38] == " 68.227" and l[38:46] == "-100.558")
+ records("AF-P04637", lambda l: l[12:16] == " CA ", 1))
display_widget("pdb-columns",
"Point at a column to name its field. The lines come from 1UBQ (an ordinary atom), 7RSA (one atom in two "
"alternate positions, A and B), 1PPB (residue 60A: an insertion code), 4HHB (the iron of a heme, a "
"HETATM), 1UBQ (a water), 1AON (a large complex whose x and y fields touch), and an AlphaFold model "
"(where the B-factor column holds pLDDT).",
lines=lines,
notes=["1UBQ", "7RSA, altloc A", "7RSA, altloc B", "1PPB, insertion code", "4HHB heme iron", "1UBQ water",
"1AON, fields touch", "AlphaFold p53"])
Point at a column to name its field. The lines come from 1UBQ (an ordinary atom), 7RSA (one atom in two alternate positions, A and B), 1PPB (residue 60A: an insertion code), 4HHB (the iron of a heme, a HETATM), 1UBQ (a water), 1AON (a large complex whose x and y fields touch), and an AlphaFold model (where the B-factor column holds pLDDT).
The 1AON line shows why the format must be read by column. Splitting on whitespace works on most lines and then quietly fails:
line = lines[6]
print(line)
print(len(line.split()), "whitespace-separated fields:", line.split()[6:9])
def parse_atom(line):
"""One ATOM/HETATM record, by the fixed column ranges of the PDB format (1-based, inclusive)."""
field = lambda first, last: line[first - 1:last].strip()
return {
"record": field(1, 6), "serial": int(field(7, 11)), "name": field(13, 16), "altloc": field(17, 17),
"resname": field(18, 20), "chain": field(22, 22), "resseq": int(field(23, 26)), "icode": field(27, 27),
"x": float(field(31, 38)), "y": float(field(39, 46)), "z": float(field(47, 54)),
"occupancy": float(field(55, 60) or 1), "b": float(field(61, 66) or 0), "element": field(77, 78),
}
print(parse_atom(line))
ATOM 4593 O GLY B 110 68.227-100.558 -0.570 1.00 22.81 O
11 whitespace-separated fields: ['68.227-100.558', '-0.570', '1.00']
{'record': 'ATOM', 'serial': 4593, 'name': 'O', 'altloc': '', 'resname': 'GLY', 'chain': 'B', 'resseq': 110, 'icode': '', 'x': 68.227, 'y': -100.558, 'z': -0.57, 'occupancy': 1.0, 'b': 22.81, 'element': 'O'}Splitting gives 11 fields instead of 12: 68.227-100.558 came out as one token, and every field after it
shifted by one. Optional fields cause the same trouble. A program that writes a single chain may leave the
chain column blank, and older files may leave out the element. Parse by column ranges.
A line carries several identifiers, and they answer different questions. The serial number (columns 7–11)
only numbers lines in the file. The chain identifier says which polymer the atom belongs to. The residue
number and insertion code name the residue within its chain. And in a file with several models (an NMR
ensemble), MODEL and ENDMDL records bracket each copy, so the same chain, residue, and atom names repeat
once per model. Biopython mirrors this hierarchy as structure[model][chain][residue][atom].
The PDB format uses fixed width fields to represent data, and this places absolute limits on the size of certain items of data. For instance, the maximum number of atom records that can be represented in a single structure model is limited to 99,999, and the field width of the identifier for polymer chains is limited to a single character. Although these restrictions were reasonable when the format was first defined, this is no longer the case. Many large molecular systems, such as the ribosomal subunit structures, cannot be represented in a single PDB-format file.
Since 2014 such structures (ribosomes, viral capsids, most large cryo-EM complexes) have been distributed only in mmCIF, the archive's master format; the HIV capsid 3J3Q, for example, has no legacy-format file.
mmCIF: the same data as tables
In its simplest form, an mmCIF data file looks like a paired collection of data item names and values. The
leading underscore character identifies data item names. The underscore character is followed by a text
string interpreted as containing both a category name and an item name separated by a period, as in
_refine.ls_d_res_high. Short text strings may be enclosed in single or double quotation marks. Text
strings that span multiple lines are enclosed by semicolons placed at the first character position of the
line. There are two special characters used as placeholders for item values that for some reason cannot
be explicitly assigned. The question mark (?) is used to mark an item value as missing. A period (.) may be
used to identify that there is no appropriate value for the item or that a value has been intentionally
omitted.
Vectors and tables of data may be encoded using a loop_ directive. To build a table, the data item names
corresponding to the table columns are preceded by the loop_ directive and followed by the corresponding
rows of data. All of the data items within the loop must belong to the same category, and the number of
data values following the loop must be an exact multiple of the number of data item names.

So an mmCIF file is a small relational database serialized as text: each category is a table, and
_atom_site is the one with the coordinates. Biopython's MMCIF2Dict reads every item into a dictionary
of columns:
from Bio.PDB.MMCIF2Dict import MMCIF2Dict
hb = MMCIF2Dict(str(fetch("4HHB", "cif")))
print(hb["_exptl.method"], hb["_refine.ls_d_res_high"], hb["_refine.ls_R_factor_R_free"])
columns = ["group_PDB", "label_atom_id", "label_comp_id", "label_asym_id", "label_seq_id",
"auth_asym_id", "auth_seq_id", "occupancy", "B_iso_or_equiv"]
for i in (0, 4400):
print({c: hb[f"_atom_site.{c}"][i] for c in columns})
print("chains by label_asym_id:", sorted(set(hb["_atom_site.label_asym_id"])))
print("chains by auth_asym_id: ", sorted(set(hb["_atom_site.auth_asym_id"])))
['X-RAY DIFFRACTION'] ['1.74'] ['?']
{'group_PDB': 'ATOM', 'label_atom_id': 'N', 'label_comp_id': 'VAL', 'label_asym_id': 'A', 'label_seq_id': '1', 'auth_asym_id': 'A', 'auth_seq_id': '1', 'occupancy': '1.00', 'B_iso_or_equiv': '49.05'}
{'group_PDB': 'HETATM', 'label_atom_id': 'C3B', 'label_comp_id': 'HEM', 'label_asym_id': 'E', 'label_seq_id': '.', 'auth_asym_id': 'A', 'auth_seq_id': '142', 'occupancy': '1.00', 'B_iso_or_equiv': '17.41'}
chains by label_asym_id: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N']
chains by auth_asym_id: ['A', 'B', 'C', 'D']Most identifiers come in two versions. The auth_ columns hold the author's labels, the same ones the
legacy format shows (chains A–D, residue numbers as deposited). The label_ columns are assigned by the
archive with strict rules: every distinct molecule instance gets its own label_asym_id, so 4HHB's
four hemes, two phosphate ions, and the waters around each protein chain all become chains of their own
(14 in all), and label_seq_id counts polymer
residues 1, 2, 3, … through the deposited sequence, with "." for ligands and water. When software
reports "chain E" or "residue 40", find out which of the two it means. Note also the "?" for R-free: the
item exists, and the value is missing, because 4HHB predates R-free.
Residue numbers are names, not positions
The PDB format does not specify the precise relationship between the polymer sequence given in the SEQRES records and the observed residue sequence within the ATOM records, so the sequence information that is presented in the entry cannot be used directly. To use these data, additional sequence alignment must be performed to resolve gaps and possible conflicts.

Three numbers can describe one residue, and they are different numbers:
- its position in the deposited sequence (SEQRES, mmCIF
label_seq_id), which is also its position in the entry's FASTA sequence; - its author residue number (the ATOM record,
auth_seq_id), which may start anywhere, skip, or carry an insertion code; - its position in the reference sequence for that protein (UniProt), which matters when you match mutations or literature to a structure.
The mmCIF table _pdbx_poly_seq_scheme lists every residue of the deposited sequence with its author
number and whether it was observed, and _struct_ref_seq aligns the deposited sequence to UniProt. The
EGFR kinase domain in 1M17, a drug target with an inhibitor bound, puts both to work:
from primer import THREE_TO_ONE
egfr = MMCIF2Dict(str(fetch("1M17", "cif")))
scheme = zip(egfr["_pdbx_poly_seq_scheme.seq_id"], egfr["_pdbx_poly_seq_scheme.mon_id"],
egfr["_pdbx_poly_seq_scheme.pdb_seq_num"], egfr["_pdbx_poly_seq_scheme.pdb_ins_code"],
egfr["_pdbx_poly_seq_scheme.auth_seq_num"])
ref_first, ref_last = (int(egfr[f"_struct_ref_seq.seq_align_{k}"][0]) for k in ("beg", "end"))
db_first = int(egfr["_struct_ref_seq.db_align_beg"][0])
occupied = {} # label_seq_id -> does any atom of the residue have nonzero occupancy?
for seq_id, occupancy in zip(egfr["_atom_site.label_seq_id"], egfr["_atom_site.occupancy"]):
occupied[seq_id] = occupied.get(seq_id, False) or float(occupancy) > 0
rows = []
for seq_id, monomer, number, icode, observed in scheme:
n = int(seq_id)
uniprot = n - ref_first + db_first if ref_first <= n <= ref_last else None
state = 0 if observed == "?" else 1 if occupied.get(seq_id) else 2 # missing, present, zero occupancy
rows.append([n, THREE_TO_ONE.get(monomer, "X"), number + ("" if icode in ".?" else icode), uniprot, state])
print(f"{len(rows)} residues; author numbers {rows[0][2]}–{rows[-1][2]}; "
f"UniProt P00533 positions {rows[ref_first - 1][3]}–{rows[ref_last - 1][3]}")
display_widget("residue-numbering",
"The 333 residues of 1M17's deposited sequence. Hover for each residue's three numbers; search for "
"834 or 858 to see the two numbering schemes collide.",
residues=rows, name="EGFR kinase (1M17)", db="UniProt P00533")
333 residues; author numbers 666–998; UniProt P00533 positions 695–1022
The 333 residues of 1M17's deposited sequence. Hover for each residue's three numbers; search for 834 or 858 to see the two numbering schemes collide.
Three traps show up at once. The first five residues (GSHMA) are an expression tag that isn't part of EGFR at all: labs add a short tag to the protein to make it easy to purify, then cut most of it off, and a few residues are left behind. The author numbers run 666–998 and are offset by 24 from UniProt's, because EGFR is often numbered without its 24-residue signal peptide, a short N-terminal stretch that directs a new protein to the cell membrane and is cut off once it has done that job. So the cancer mutation that UniProt numbering calls L858R (leucine 858 replaced by arginine) is Leu 834 in this file; type 834 into the search box and you find both Leu 834 and Val 810, which UniProt calls 834. And residues 965–976 are in the sequence but absent from the model, so the coordinates jump from 964 to 977. A program that numbers the residues it finds in the ATOM records 1, 2, 3, … would misalign everything after the first gap.
Insertion codes break the numbering the other way, adding residues without new numbers. Thrombin keeps the numbering of chymotrypsin, a related protease (an enzyme that cuts other proteins), so that equivalent residues of the two enzymes share numbers; where thrombin has extra residues, they get letters:
from collections import Counter
thrombin = structure("1PPB")[0]["H"]
inserted = Counter(r.id[1] for r in thrombin if r.id[2] != " ")
print("residue numbers carrying insertion codes in 1PPB chain H:", dict(inserted))
print("residue 60 and its insertions:", [f"{r.get_resname()} {r.id[1]}{r.id[2].strip()}" for r in thrombin
if r.id[1] == 60])
residue numbers carrying insertion codes in 1PPB chain H: {36: 1, 60: 9, 77: 1, 97: 1, 129: 3, 149: 5, 184: 1, 186: 4, 204: 2, 221: 1}
residue 60 and its insertions: ['LEU 60', 'TYR 60A', 'PRO 60B', 'PRO 60C', 'TRP 60D', 'ASP 60E', 'LYS 60F', 'ASN 60G', 'PHE 60H', 'THR 60I']In Biopython a residue's id is a triple (hetero flag, number, insertion code), and chain[60] finds only
the residue without a code; chain[(" ", 60, "A")] finds 60A.
FASTA files carry their own identifier schemes. The PDB's FASTA for an entry lists each distinct polymer (entity) with the chains that share it, while UniProt's header names a database accession:
import urllib.request
from primer import fasta, uniprot
with urllib.request.urlopen("https://www.rcsb.org/fasta/entry/4HHB", timeout=60) as r:
for header, seq in fasta(r.read().decode()):
print(f">{header}\n {seq[:40]}… ({len(seq)} residues)")
header, seq = fasta(uniprot("P69905"))[0]
print(f">{header}\n {seq[:40]}… ({len(seq)} residues)")
>4HHB_2|Chains B, D|Hemoglobin subunit beta|Homo sapiens (9606) VHLTPEEKSAVTALWGKVNVDEVGGEALGRLLVVYPWTQR… (146 residues) >4HHB_1|Chains A, C|Hemoglobin subunit alpha|Homo sapiens (9606) VLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTK… (141 residues) >sp|P69905|HBA_HUMAN Hemoglobin subunit alpha OS=Homo sapiens OX=9606 GN=HBA1 PE=1 SV=2 MVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTT… (142 residues)
The UniProt sequence of hemoglobin α has 142 residues and starts with Met; the structure's has 141 and starts with Val, because the cell removes the initial methionine. Residue 1 in 4HHB is residue 2 in UniProt.
Chains, assemblies, and the asymmetric unit
Structure determination does not always provide the functional form of a biological macromolecule. Rather, it provides the tertiary structure as found in the asymmetric unit of the crystal (the smallest piece of the unit cell from which symmetry rebuilds the whole cell), which is not necessarily a biologically functional unit. The Cartesian coordinates found in a PDB entry generally correspond to the asymmetric unit of the molecule as found in the crystal and represent the unique atomic positions that are refined against the experimental data. The necessary crystallographic symmetry operations, as defined by the space group, must be applied to generate the biologically active quaternary structure. This is done through the application of rotation and translation to the individual chemical components listed in the PDB entry.
The process must distinguish between an assembly that is a truly biologically active molecule and an assembly that is a number of discrete components associated through crystal packing, but having no physiological relevance. The PDB now captures the interpretation of the biologically active molecule from the structural biologists depositing the structure data, rather than only determining it automatically.
Hemoglobin shows both cases. In deoxyhemoglobin, 4HHB, the asymmetric unit happens to be the whole α₂β₂ tetramer: chains A–D are all in the file. In oxyhemoglobin, 1HHO, the crystal's symmetry relates the two halves of the tetramer, so the file holds only one α and one β chain. The other two come from a rotation stored in the file:
oxy = MMCIF2Dict(str(fetch("1HHO", "cif")))
print("assembly:", oxy["_pdbx_struct_assembly.oligomeric_details"],
"built with operators", oxy["_pdbx_struct_assembly_gen.oper_expression"])
i = oxy["_pdbx_struct_oper_list.id"].index("2")
R = np.array([[float(oxy[f"_pdbx_struct_oper_list.matrix[{r}][{c}]"][i]) for c in (1, 2, 3)] for r in (1, 2, 3)])
t = np.array([float(oxy[f"_pdbx_struct_oper_list.vector[{r}]"][i]) for r in (1, 2, 3)])
print("operator", oxy["_pdbx_struct_oper_list.name"][i], "rotation:", R.tolist(), "translation:", t.tolist())
half = structure("1HHO")[0]
ca = {chain.id: np.array([res["CA"].coord for res in chain if "CA" in res]) for chain in half}
for a in ca:
for b in ca:
mate = ca[b] @ R.T + t # chain b's copy in the other half of the tetramer
contacts = (np.linalg.norm(ca[a][:, None] - mate[None], axis=2) < 8).sum()
print(f"chain {a} touches the symmetry copy of chain {b} at {contacts} Cα pairs within 8 Å")
assembly: ['tetrameric'] built with operators ['1,2'] operator 7_555 rotation: [[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, -1.0]] translation: [0.0, 0.0, 0.0] chain A touches the symmetry copy of chain A at 18 Cα pairs within 8 Å chain A touches the symmetry copy of chain B at 19 Cα pairs within 8 Å chain B touches the symmetry copy of chain A at 19 Cα pairs within 8 Å chain B touches the symmetry copy of chain B at 10 Cα pairs within 8 Å
Applying a rotation to a set of coordinates is all "generating the assembly" means. The archive also
provides ready-made assembly files (1HHO-assembly1.cif). The trap runs both ways: an analysis of
interfaces, pockets, or buried surface on 1HHO's file alone would miss the α₁β₂ interface entirely, and an
analysis on a file with several copies in the asymmetric unit can mistake crystal contacts for biological
interfaces.
The asymmetric unit of oxyhemoglobin (1HHO): one α chain and one β chain, with their hemes. The other half of the functional tetramer exists only as the symmetry operator in the cell above.
Open 1HHO in Mol*Check yourself
Your parser reads residue numbers from ATOM records and builds the sequence by appending one letter per new number. On 1M17 it produces a sequence of 312 letters, while the PDB's FASTA has 333. Name every reason for the difference.
Reasoning
The FASTA comes from the deposited sequence (SEQRES), which includes residues with no coordinates: the expression tag and first residue (666–671), the internal stretch 965–976, and the C-terminal 996–998, 21 residues in all. Glu 725 is present in the coordinates at zero occupancy, so a parser that drops zero-occupancy atoms would lose it too. Separately, a parser that appends one letter per number would also merge residues sharing a number with different insertion codes (not an issue in 1M17, but it would be in thrombin).
A paper reports that "mutation of Arg 72 abolishes binding" for a protein whose structure you've downloaded. Residue 72 in the file is a glycine. What do you check before concluding the paper is wrong?
Reasoning
Which numbering each source uses. The paper may use UniProt positions (including the initiator Met or a
signal peptide) while the file uses author numbers with an offset, or vice versa. Use the entry's
_struct_ref_seq mapping (or align the two sequences) and look for an arginine near position 72 in the
other scheme. Also check for insertion codes and for a construct that starts partway into the protein.
You compute the solvent-accessible surface of every residue in 1HHO to find residues buried in subunit interfaces. Which residues will your analysis mislabel, and how do you fix it?
Reasoning
Residues at the interface between the two αβ halves (for example α₁ residues that contact β₂) will look
exposed, because their partners aren't in the file. Generate the biological assembly first, either by
applying the symmetry operator from _pdbx_struct_oper_list as in the cell above or by downloading the
assembly file, and compute surfaces on the full tetramer.