Same fold, different sequence

Lab 5 of Biology Primer for Computer Scientists. Download the code as a notebook.

Sperm whale myoglobin and the human hemoglobin α chain are paralogs from a gene duplication hundreds of millions of years ago. How much sequence do they still share, and how much structure? You'll measure both, find what the whole globin family conserves, and then predict ubiquitin's contacts from its family alignment and check them against the crystal structure.

Structures: 1A6M (sperm whale myoglobin with O₂ bound, 1.0 Å), 4HHB (human deoxyhemoglobin; chain A is an α chain), and 1UBQ (ubiquitin). Alignments come from Pfam: PF00042 (globins) and PF00240 (ubiquitin). Run the cells in order in the downloaded notebook, or write your own versions first and open the solutions to compare.

Task 1: align the two sequences

Extract the one-letter sequences of 1A6M chain A and 4HHB chain A, align them globally with BLOSUM62 and gap penalties of −11 to open and −1 to extend, print the alignment, and compute the percent identity over aligned (non-gap) pairs.

from Bio.Align import PairwiseAligner, substitution_matrices
from primer import structure, sequence

aligner = PairwiseAligner(mode="global", open_gap_score=-11, extend_gap_score=-1)
aligner.substitution_matrix = substitution_matrices.load("BLOSUM62")
# your code: get the two sequences, align, print, and count identities
Solution
from Bio.Align import PairwiseAligner, substitution_matrices
from primer import structure, sequence

aligner = PairwiseAligner(mode="global", open_gap_score=-11, extend_gap_score=-1)
aligner.substitution_matrix = substitution_matrices.load("BLOSUM62")

mb_chain, hb_chain = structure("1A6M")[0]["A"], structure("4HHB")[0]["A"]
mb_seq, hb_seq = sequence(mb_chain), sequence(hb_chain)
aln = aligner.align(mb_seq, hb_seq)[0]
print(aln)

# aln.aligned holds matching blocks as (start, end) ranges in each sequence
pairs = [(i, j) for (s, e), (t, f) in zip(*aln.aligned) for i, j in zip(range(s, e), range(t, f))]
same = sum(mb_seq[i] == hb_seq[j] for i, j in pairs)
print(f"{len(mb_seq)} and {len(hb_seq)} residues; {same} identical of {len(pairs)} aligned pairs ({same / len(pairs):.0%})")
target            0 VLSEGEWQLVLHVWAKVEADVAGHGQDILIRLFKSHPETLEKFDRFKHLKTEAEMKASED
                  0 |||......|...|.||.|.....|...|.|.|.|.|.|...|..|......|..|.---
query             0 VLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKG---

target           60 LKKHGVTVLTALGAILKKKGHHEAELKPLAQSHATKHKIPIKYLEFISEAIIHVLHSRHP
                 60 ---||..|..||.............|..|...||.|...........|......|....|
query            57 ---HGKKVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLP

target          120 GDFGADAQGAMNKALELFRKDIAAKYKELGY 151
                120 ..|.........|.|.........||.---- 151
query           114 AEFTPAVHASLDKFLASVSTVLTSKYR---- 141

151 and 141 residues; 37 identical of 141 aligned pairs (26%)

About one residue in four matches, the twilight zone. Note where the gaps fall: one block of six myoglobin residues has no partner in the α chain, near myoglobin's short D helix, which the α chain lacks, and the myoglobin chain is longer at its C-terminus. A sequence alignment places gaps only approximately; a structural superposition can move them by a few residues.

Task 2: superimpose the aligned Cα atoms

Use the aligned pairs as the correspondence and find the rigid rotation and translation that best overlays the hemoglobin α Cα atoms on myoglobin's, with Bio.PDB.Superimposer. Report the RMSD over all aligned pairs. Then compute each pair's distance after superposition, keep the pairs closer than 3 Å, refit on those alone, and repeat until the set stops changing. That last set is the conserved core.

Solution
import numpy as np
from Bio.PDB import Superimposer

mb = [r for r in mb_chain if r.id[0] == " "]
hb = [r for r in hb_chain if r.id[0] == " "]

def fit(subset):
    sup = Superimposer()
    sup.set_atoms([mb[i]["CA"] for i, _ in subset], [hb[j]["CA"] for _, j in subset])
    return sup

sup = fit(pairs)
print(f"all {len(pairs)} aligned pairs: RMSD {sup.rms:.2f} Å")
core = pairs
while True:
    rot, tran = sup.rotran
    dev = np.array([np.linalg.norm(mb[i]["CA"].coord - (hb[j]["CA"].coord @ rot + tran)) for i, j in pairs])
    new_core = [p for p, d in zip(pairs, dev) if d < 3.0]
    if new_core == core:
        break
    core, sup = new_core, fit(new_core)
print(f"core of {len(core)} pairs within 3 Å: RMSD {sup.rms:.2f} Å")

import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6.4, 2.8))
ax.plot([mb[i].id[1] for i, _ in pairs], dev, lw=1.5)
ax.axhline(3.0, color="#888", ls="--", lw=1)
ax.set_xlabel("myoglobin residue")
ax.set_ylabel("Cα deviation (Å)")
plt.show()
all 141 aligned pairs: RMSD 2.70 Å
core of 127 pairs within 3 Å: RMSD 1.36 Å
0 20 40 60 80 100 120 140 myoglobin residue 0 2 4 6 8 10 12 Cα deviation (Å)

The deviations stay low along the helices and spike at the ends of the chain and near the gaps, where the alignment strains to pair up residues that the two proteins don't share. Chothia and Lesk's fit from lesson 5.1 predicts 0.40e1.87×0.74≈1.6 Å for 26% identity. Compare it with your core RMSD.

Code
from primer import display_widget

rot, tran = sup.rotran
def trace(residues, transform=None, marks=()):
    coords = [r["CA"].coord if transform is None else r["CA"].coord @ transform[0] + transform[1] for r in residues]
    numbers = [r.id[1] for r in residues]
    return {"coords": [[round(float(x), 2) for x in c] for c in coords],
            "marks": [[numbers.index(n), f"His{n}"] for n in marks]}

display_widget(
    "ca-overlay",
    "Myoglobin and hemoglobin α superimposed on their conserved core. Drag to rotate.",
    traces=[{"label": "myoglobin (1A6M)", **trace(mb, marks=(64, 93))},
            {"label": "hemoglobin α (4HHB A)", **trace(hb, (rot, tran), marks=(58, 87))}],
)

Loading the interactive figure…

Myoglobin and hemoglobin α superimposed on their conserved core. Drag to rotate.

Task 3: look at the heme pocket

Open 1A6M below or in Mol*. The heme's iron is held from below by the proximal histidine, His93, whose side-chain nitrogen bonds directly to the iron. Above the heme, where O₂ binds, sits the distal histidine, His64, which hydrogen-bonds to the bound oxygen. In hemoglobin α the same two roles are played by His87 and His58.

Sperm whale myoglobin's heme pocket: the heme and bound O₂ in element colors, the proximal His93 and distal His64 in blue, with their distances to the iron, and Phe43 in amber.

Open 1A6M in Mol*

To superimpose the two proteins yourself in Mol*, load both entries (Download Structure, then 1A6M and 4HHB), and use Structure Tools, then Superposition, choosing chain A of each. In ChimeraX the command is open 1a6m 4hhb; matchmaker #2/A to #1/A, which aligns the sequences and superimposes in one step.

Task 4: what does the globin family conserve?

Download the Pfam seed alignment of the globin family (PF00042), keep the columns where fewer than half the sequences have a gap, and compute each column's information content with gaps ignored. To map columns onto sperm whale myoglobin, align myoglobin to the seed's alligator myoglobin row (MYG_ALLMI/27-143), which is close enough to align without trouble. List the ten most conserved positions with their myoglobin residue numbers and their distance from the heme iron.

def pfam(accession, kind="seed"):
    ...  # download https://www.ebi.ac.uk/interpro/api/entry/pfam/<accession>/?annotation=alignment:<kind>
         # (gzipped Stockholm) and return {name: aligned sequence}
Solution
import gzip
import urllib.request
from primer import CACHE

def pfam(accession, kind="seed"):
    path = CACHE / f"{accession.lower()}-{kind}.sto.gz"
    if not path.exists():
        url = f"https://www.ebi.ac.uk/interpro/api/entry/pfam/{accession}/?annotation=alignment:{kind}"
        request = urllib.request.Request(url, headers={"User-Agent": "study-bioprimer"})
        path.write_bytes(urllib.request.urlopen(request, timeout=300).read())
    rows = {}
    for line in gzip.open(path, "rt"):
        if line.strip() and not line.startswith(("#", "//")):
            name, seq = line.split()
            rows[name] = rows.get(name, "") + seq
    return rows

AA = "ACDEFGHIKLMNPQRSTVWY"
# The seed is a hand-made alignment: every column counts, and "." and "-" are both gaps.
globins = {name: seq.upper().replace(".", "-") for name, seq in pfam("PF00042").items()}
msa = np.array([list(s) for s in globins.values()])
keep = [j for j in range(msa.shape[1]) if (msa[:, j] == "-").mean() < 0.5]

def information(column, pseudo=0.5):
    residues = [c for c in column if c in AA]
    p = (np.array([residues.count(a) for a in AA]) + pseudo) / (len(residues) + 20 * pseudo)
    return np.log2(20) + (p * np.log2(p)).sum()

# Map columns to sperm whale myoglobin through the alligator myoglobin row.
ref = globins["MYG_ALLMI/27-143"]
ref_index, k = {}, 0
for j, c in enumerate(ref):
    if c != "-":
        ref_index[j] = k
        k += 1
ref_to_mb = {}
aln = aligner.align(ref.replace("-", ""), mb_seq)[0]
for (s, e), (t, f) in zip(*aln.aligned):
    ref_to_mb.update(zip(range(s, e), range(t, f)))

iron = next(a for a in mb_chain.get_atoms() if a.element == "FE")
print(f"{len(globins)} globins, {len(keep)} columns")
scored = sorted(((information(msa[:, j]), j) for j in keep if j in ref_index and ref_index[j] in ref_to_mb), reverse=True)
for bits, j in scored[:10]:
    r = mb[ref_to_mb[ref_index[j]]]
    near = min(a - iron for a in r)
    print(f"{r.get_resname()} {r.id[1]:3d}: {bits:.2f} bits, {near:4.1f} Å from the iron, column {''.join(msa[:, j])[:30]}…")
73 globins, 118 columns
HIS  93: 3.32 bits,  2.1 Å from the iron, column HHHHHHHHHHHHHHHHHHHHHHHHHHHHHH…
PHE  43: 3.32 bits,  5.2 Å from the iron, column FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF…
PHE  33: 2.53 bits,  9.2 Å from the iron, column FFFFFFFFFLFFFFFFFLLLLLLLLFFFFL…
PRO  37: 2.49 bits, 14.2 Å from the iron, column PNPPPGPPPPPKPGPPPPPPPPPPPPPAPP…
ALA 130: 2.44 bits, 20.2 Å from the iron, column AAAAAAAAAAASAAAIAAAYAAZAAAAAAA…
HIS  64: 2.34 bits,  4.6 Å from the iron, column HHHHHHHHHHQHHHHHHHHHHHHHHHHHHQ…
LEU  89: 2.25 bits,  5.2 Å from the iron, column LLLLLLLYLLLLYLLLLLLLLLLLLLLLLL…
LEU 104: 2.20 bits,  6.4 Å from the iron, column FFYYFFFFFLFFMFFFFFFFFFFFFFFFFF…
VAL  68: 2.10 bits,  4.7 Å from the iron, column VVVVVVVVVVVVIVVVVVVVVVVVVVVVVV…
MET 131: 1.99 bits, 16.4 Å from the iron, column WWWWWWWWLMFFWWWWWWFFFWFLYAVLLW…

The two most conserved positions are Phe43, which packs against the heme, and the proximal His93, which binds its iron. Both are identical in every sequence of the seed alignment, which spans globins from mammals, fish, worms, insects, plants, and bacteria. The distal His64 is nearly as conserved; a few globins replace it with glutamine, which can also hydrogen-bond to bound oxygen. Most of the rest are buried hydrophobics in the core. Sequence alone, from a family whose members share as little as 15% identity, points at the heme pocket.

Task 5: predict ubiquitin's contacts from its family

Download the full Pfam alignment of the ubiquitin family (PF00240, kind full, about 9 MB). Keep only match columns, which are the upper-case letters and -; insert positions are lower case and .. The 72 match columns are ubiquitin residues 3–74. Drop sequences that are more than 20% gaps, take a random sample of 5,000, weight each sequence by one over the number of sampled sequences at least 80% identical to it, and compute mutual information with the average product correction for every pair of columns. Count how many of the top 36 pairs with |i−j|≥6 are real contacts, meaning Cβ atoms (Cα for glycine) within 8 Å in 1UBQ, and compare with the fraction of all such pairs that are contacts.

Solution
full = pfam("PF00240", kind="full")
cols = ["".join(c for c in seq if c.isupper() or c == "-") for seq in full.values()]
ALPH = AA + "-"
X = np.array([[ALPH.index(c) if c in ALPH else 20 for c in s] for s in cols], dtype=np.int8)
X = X[(X == 20).mean(axis=1) < 0.2]
rng = np.random.default_rng(0)
X = X[rng.choice(len(X), 5000, replace=False)]
L = X.shape[1]

onehot = np.eye(21)[X].reshape(len(X), -1)
w = 1 / (onehot @ onehot.T / L >= 0.8).sum(1)
W = w / w.sum()
fi = (W @ onehot).reshape(L, 21)
fij = ((onehot.T * W) @ onehot).reshape(L, 21, L, 21)

mi = np.zeros((L, L))
for i in range(L):
    for j in range(i + 1, L):
        p, e = fij[i, :, j, :], np.outer(fi[i], fi[j])
        nz = p > 0
        mi[i, j] = mi[j, i] = (p[nz] * np.log(p[nz] / e[nz])).sum()
mean_col = mi.sum(1) / (L - 1)
mi_apc = mi - np.outer(mean_col, mean_col) / (mi.sum() / (L * (L - 1)))

ubq_chain = structure("1UBQ")[0]["A"]
beta = np.array([(ubq_chain[r]["CB"] if "CB" in ubq_chain[r] else ubq_chain[r]["CA"]).coord for r in range(3, 75)])
dist = np.linalg.norm(beta[:, None] - beta[None], axis=-1)
far = [(i, j) for i in range(L) for j in range(i + 6, L)]
base = np.mean([dist[i, j] < 8 for i, j in far])
ubq = sequence(ubq_chain)
for name, score in [("MI", mi), ("MI + APC", mi_apc)]:
    top = sorted(far, key=lambda p: -score[p])[:36]
    print(f"{name}: {np.mean([dist[p] < 8 for p in top]):.0%} of the top 36 are contacts (random {base:.0%})")
print("top MI + APC pairs:")
for i, j in sorted(far, key=lambda p: -mi_apc[p])[:10]:
    print(f"  {ubq[i + 2]}{i + 3}-{ubq[j + 2]}{j + 3}: Cβ distance {dist[i, j]:.1f} Å")
MI: 22% of the top 36 are contacts (random 6%)
MI + APC: 47% of the top 36 are contacts (random 6%)
top MI + APC pairs:
  K27-D52: Cβ distance 7.1 Å
  D21-K29: Cβ distance 8.3 Å
  E34-L71: Cβ distance 10.7 Å
  I13-E34: Cβ distance 6.0 Å
  I44-H68: Cβ distance 4.1 Å
  I23-L50: Cβ distance 4.8 Å
  I44-V70: Cβ distance 6.5 Å
  Q41-L69: Cβ distance 6.1 Å
  I23-T55: Cβ distance 7.5 Å
  R42-H68: Cβ distance 8.6 Å

Look at the top pairs that aren't contacts. Some are a residue or two from a real contact. Pairs that link the first and last few columns are gap artifacts: many family members are fragments missing both ends, so their gaps co-occur.

Self-check

Myoglobin and hemoglobin α are 26% identical. Shuffled hemoglobin sequences reach 24% on average against myoglobin. Why does nobody doubt that the two are homologs?

Reasoning

The identity is weak evidence, but everything else agrees. Their alignment score is far above the shuffled distribution (lesson 5.2). Their structures superimpose with a core RMSD of about 1.4 Å over most of the chain in the same helix order, which is homology-level structural similarity. They bind the same cofactor through the same conserved residues (proximal and distal histidines, Phe43) at equivalent positions. And they are connected through intermediate sequences, the α and β chains and globins of other species, that align with both at higher identity. The globin gene tree shows the duplications.

A mutation in a human hemoglobin chain replaces the proximal histidine with tyrosine. Predict the effect on the heme and on oxygen transport, using what the family alignment told you.

Reasoning

The proximal histidine is invariant across the whole globin family: no surviving globin has lost it. It holds the iron through a direct bond from its side-chain nitrogen. Tyrosine's phenolate oxygen can bind the iron instead but changes its chemistry, stabilizing the oxidized Fe³⁺ form that can't carry O₂. The prediction is a dysfunctional chain that doesn't transport oxygen properly. Such mutants exist in people (the hemoglobin M variants) and cause methemoglobinemia, a bluish skin color from poorly oxygenated blood.

In Task 2, why refit on the pairs within 3 Å instead of reporting the RMSD over all aligned pairs?

Reasoning

RMSD is dominated by its largest deviations, because they are squared. A handful of misaligned residues at the ends of the chains or around a gap, where the two proteins really differ, inflate the all-pairs RMSD (2.7 Å) and also pull the superposition away from the best fit of the parts that do match. Refitting on the core gives the transform that best overlays the shared structure and an RMSD that measures how similar that structure is (about 1.4 Å). Always report the number of pairs alongside an RMSD: "1.4 Å over 127 Cα" and "2.7 Å over 141 Cα" describe the same superposition.

Your Task 5 result for MI + APC is about 50%. If you halve the number of sequences to 2,500, or keep 5,000 but remove the sequence weights, which change would you expect to hurt more, and why?

Reasoning

Removing the weights probably hurts more. The family is dominated by clusters of near-identical ubiquitins (ubiquitin is almost invariant across eukaryotes, the organisms whose cells have a nucleus, from yeast to humans), so unweighted, the counts mostly reflect a few clades and phylogenetic correlations swamp the contact signal. Halving the sample keeps the diversity and roughly halves the effective number of sequences, which adds noise but leaves the statistic unbiased. Try both: rerun the cell with w = np.ones(len(X)), and separately with 2,500 sequences.

Your top MI + APC list in Task 5 might include a pair such as residue 4 with residue 73, nearly 25 Å apart. Without looking at the structure, how could you have flagged it as suspect from the alignment alone?

Reasoning

Check the gap pattern. Both positions sit at the ends of the domain, and many sequences in a Pfam full alignment are fragments or domains trimmed at slightly different boundaries, so gaps appear at both ends of the same sequences. Gap-versus-residue is then a strong shared signal that has nothing to do with contact. Counting how often each column is a gap, removing sequences or columns with many gaps, or treating the gap state separately would expose it. A real contact usually shows co-variation among residues, not between gaps.