Constrained sampling and allosteric response with Gibbs
Gibbs samples ensembles of conformations around a structure you already have. It can also hold part of that structure fixed and sample everything else around it. We call the fixed part a constraint.
A constraint lets you ask what if questions about a protein. For example: if this loop is locked in this state, how does the rest of the protein respond? When a change at one site shifts the conformation of a distant site, the response is allosteric.
Objective We'll work through two examples:
- Part 1, a constraint on a small protein: crambin (PDB 1CRN), a 46-residue plant protein. We hold its first helix fixed, sample the rest, and compare the result with a free run. This shows what a constraint does and how to check that it held.
- Part 2, an allosteric response in PTP1B: protein tyrosine phosphatase 1B is a drug target for diabetes and cancer. Its active site sits between two loops, the WPD loop and the P-loop, which close over a substrate. We fix both loops either closed or open and watch loop L16, which sits on the other side of the domain and is never constrained. If L16 follows the state of the active-site loops, the model has learned the coupling between them.
How Gibbs works Gibbs conditions on a PoET-2 embedding of the protein's homologs, so before sampling we build two things:
- An MSA of homologs of the sequence.
- A prompt, a set of sequences sampled from that MSA. The platform embeds the prompt with PoET-2.
Prerequisites
-
An OpenProtein.AI account. The notebook reads your credentials from the environment variables
OPENPROTEIN_USERNAMEandOPENPROTEIN_PASSWORD, and asks for any that are not set. -
Install the necessary Python packages:
openprotein-python, a build that includes Gibbsgemmi, to read and edit structuresnumpy,pandasandmatplotlibmolviewspec, which renders the 3D structures inside the notebook with Mol*
You don't need to download any data by hand. The notebook downloads every structure it uses from the RCSB PDB into data/.
Run time. Building an MSA takes a few minutes per protein. The PTP1B ensembles are the slow step: 200 conformations of a 298-residue protein per state.
Each step stores its job id, so you can paste an id into the matching *_id variable and pick up where you left off without recomputing anything.
# Install any of the extra packages that this kernel is missing.
import importlib.util
import subprocess
import sys
PACKAGES = ["gemmi", "numpy", "pandas", "matplotlib", "molviewspec"]
missing = [pkg for pkg in PACKAGES if importlib.util.find_spec(pkg) is None]
if missing:
print("installing:", ", ".join(missing))
subprocess.check_call([sys.executable, "-m", "pip", "install", "--quiet", *missing])
print("installed. Restart the kernel if an import below still fails.")
else:
print("all extra packages are installed:", ", ".join(PACKAGES))all extra packages are installed: gemmi, numpy, pandas, matplotlib, molviewspec
Imports
The printed version shows which SDK the kernel imported.
import getpass
import os
import urllib.request
from collections.abc import Sequence
from dataclasses import dataclass
from pathlib import Path
import gemmi
import matplotlib.pyplot as plt
import molviewspec as mvs
import numpy as np
import openprotein
import pandas as pd
from openprotein.jobs import StructurePredictionFuture
print("openprotein", openprotein.__version__)
DATA_DIR = Path("data")
DATA_DIR.mkdir(exist_ok=True)
TEMPERATURE_K = 300openprotein 0.17.1.dev190+gcc0a41959
Connect to the OpenProtein.AI API
The credentials come from the environment rather than from the notebook, so the notebook is safe to share.
Set OPENPROTEIN_API_BACKEND to point at a different deployment.
session = openprotein.connect(
username=os.environ.get("OPENPROTEIN_USERNAME") or input("username: "),
password=os.environ.get("OPENPROTEIN_PASSWORD") or getpass.getpass("password: "),
)Next we fetch Gibbs, the all-atom, temperature-conditioned model:
model = session.models.gibbsHelpers
The cell below defines the helpers used in both parts. It is not necessary to read them.
- Structures are held as plain dictionaries,
{residue number: {"name": ..., "atoms": {atom name: xyz}}}. This makes it easy to cut a constraint out of a structure, or to assemble a structure from several PDB entries. - Ensembles come back as a single multi-model mmCIF, with one model per conformation. Gibbs numbers each chain from 1, so we match residues to the reference by their position in the chain.
- Superposition fits each conformation onto a reference on a chosen set of CA atoms. Gibbs writes each conformation in its own frame, so we superpose before we compare.
ENSEMBLE_TIMEOUT = 3 * 60 * 60
def download(pdb_id: str, fmt: str = "cif") -> Path:
"""Download a PDB entry from the RCSB into DATA_DIR, unless it is already there."""
path = DATA_DIR / f"{pdb_id.upper()}.{fmt}"
if not path.is_file():
urllib.request.urlretrieve(
f"https://files.rcsb.org/download/{pdb_id.upper()}.{fmt}", path
)
return path
def read_chain(path: Path, chain_id: str = "A") -> dict:
"""Heavy atoms of one protein chain, keyed by residue number. Keeps the first alternate conformation."""
st = gemmi.read_structure(str(path))
st.setup_entities()
st.remove_hydrogens()
residues = {}
for res in st[0][chain_id].get_polymer():
atoms = {}
for atom in res:
if atom.name != "OXT" and atom.name not in atoms:
atoms[atom.name] = np.array(atom.pos.tolist())
if "CA" in atoms:
residues[res.seqid.num] = {"name": res.name, "atoms": atoms}
return residues
def to_pdb(models, resseqs, chain_id: str = "A") -> str:
"""PDB text for `resseqs` of one structure, or of a list of them as one multi-model file."""
st = gemmi.Structure()
for k, residues in enumerate(
[models] if isinstance(models, dict) else models, start=1
):
model_ = gemmi.Model(str(k))
chain = gemmi.Chain(chain_id)
for r in resseqs:
res = gemmi.Residue()
res.name = residues[r]["name"]
res.seqid = gemmi.SeqId(r, " ")
res.entity_type = gemmi.EntityType.Polymer
for name, xyz in residues[r]["atoms"].items():
atom = gemmi.Atom()
atom.name = name
atom.element = gemmi.Element(name[0])
atom.pos = gemmi.Position(*xyz)
atom.occ = 1.0
res.add_atom(atom)
chain.add_residue(res)
model_.add_chain(chain)
st.add_model(model_)
st.setup_entities()
return st.make_pdb_string()
def sequence(residues: dict, resseqs) -> str:
return gemmi.one_letter_code([residues[r]["name"] for r in resseqs])
def fetch_ensemble(job: StructurePredictionFuture, resseqs) -> list[dict]:
"""The conformations of a finished job, numbered like the reference."""
cif = job.get()[0].to_string()
ens = gemmi.make_structure_from_block(gemmi.cif.read_string(cif).sole_block())
conformations = []
for m in ens:
chain = list(m[0])
if len(chain) != len(resseqs):
raise ValueError(f"{len(chain)} residues, expected {len(resseqs)}")
conformations.append(
{
r: {
"name": res.name,
"atoms": {a.name: np.array(a.pos.tolist()) for a in res},
}
for r, res in zip(resseqs, chain, strict=True)
}
)
return conformations
def ca(residues: dict, resseqs) -> np.ndarray:
return np.array([residues[r]["atoms"]["CA"] for r in resseqs])
def kabsch(P: np.ndarray, Q: np.ndarray):
"""Rotation R and translation t that minimise |P @ R.T + t - Q|."""
p_c, q_c = P.mean(0), Q.mean(0)
U, _, Vt = np.linalg.svd((P - p_c).T @ (Q - q_c))
d = np.sign(np.linalg.det(Vt.T @ U.T))
R = Vt.T @ np.diag([1.0, 1.0, d]) @ U.T
return R, q_c - p_c @ R.T
def moved(residues: dict, R, t) -> dict:
return {
r: {"name": v["name"], "atoms": {a: x @ R.T + t for a, x in v["atoms"].items()}}
for r, v in residues.items()
}
def superposed(conformations: list[dict], reference: dict, on) -> list[dict]:
"""Every conformation superposed onto `reference` on the CA atoms of residues `on`."""
return [moved(c, *kabsch(ca(c, on), ca(reference, on))) for c in conformations]
def rmsf(conformations: list[dict], resseqs) -> np.ndarray:
"""Per-residue CA RMSF (Å) across conformations that are already superposed."""
xyz = np.array([ca(c, resseqs) for c in conformations])
return np.sqrt(((xyz - xyz.mean(0)) ** 2).sum(-1).mean(0))
def ca_rmsd(a: dict, b: dict, resseqs) -> float:
return float(np.sqrt(((ca(a, resseqs) - ca(b, resseqs)) ** 2).sum(-1).mean()))
def held_check(conformations: list[dict], constraint: dict) -> None:
"""How far the held atoms moved from the constraint, after superposing each conformation on them."""
held = [(r, a) for r, v in constraint.items() for a in v["atoms"]]
target = np.array([constraint[r]["atoms"][a] for r, a in held])
worst = 0.0
for c in conformations:
missing = [(r, a) for r, a in held if a not in c[r]["atoms"]]
if missing:
raise ValueError(f"held atoms missing from a conformation: {missing[:5]}")
xyz = np.array([c[r]["atoms"][a] for r, a in held])
R, t = kabsch(xyz, target)
worst = max(
worst, float(np.sqrt(((xyz @ R.T + t - target) ** 2).sum(-1).mean()))
)
print(
f"held: {len(held)} atoms, largest RMSD to the constraint over {len(conformations)} conformations {worst:.3f} Å"
)
BACKBONE = {"N", "CA", "C", "O"}
@dataclass(frozen=True)
class Layer:
"""One structure in a Mol* scene, drawn as a cartoon.
`highlights` recolour regions of the base color, `labels` are drawn on the first model,
and `models` picks which models of a multi-model PDB to draw.
"""
pdb: str
color: str
models: Sequence[int] = (0,)
highlights: Sequence[tuple[mvs.ComponentExpression, str]] = ()
labels: Sequence[tuple[mvs.ComponentExpression, str]] = ()
opacity: float = 1.0
def span(first: int, last: int, chain: str | None = None) -> mvs.ComponentExpression:
"""Residues `first` to `last`, inclusive, by their PDB numbers."""
return mvs.ComponentExpression(
auth_asym_id=chain, beg_auth_seq_id=first, end_auth_seq_id=last
)
def backbone_pdb(pdb: str) -> str:
"""The backbone atoms only: Mol* draws a cartoon from them, and the viewer stays small."""
st = gemmi.read_pdb_string(pdb)
for model in st:
for chain in model:
for res in chain:
for i in reversed(range(len(res))):
if res[i].name not in BACKBONE:
del res[i]
return st.make_pdb_string()
def show_scene(layers: Sequence[Layer], height: int = 450) -> None:
"""Draw the layers together in one Mol* viewer."""
builder = mvs.create_builder()
files: dict[str, bytes] = {}
parsed = {}
for layer in layers:
if layer.pdb not in parsed:
name = f"structure_{len(files)}.pdb"
files[name] = backbone_pdb(layer.pdb).encode()
parsed[layer.pdb] = builder.download(url=name).parse(format="pdb")
for k, model in enumerate(layer.models):
structure = parsed[layer.pdb].model_structure(model_index=model)
cartoon = structure.component(selector="polymer").representation(
type="cartoon"
)
cartoon.color(color=layer.color)
for region, color in layer.highlights:
cartoon.color(color=color, selector=region)
if layer.opacity < 1:
cartoon.opacity(opacity=layer.opacity)
if k == 0:
for region, text in layer.labels:
structure.component(selector=region).label(text=text)
builder.molstar_notebook(data=files, width=800, height=height)Part 1: A constraint on crambin
Prepare the reference and the constraint
Crambin has two helices, residues 7–19 and 23–30, packed against a small β-sheet. We hold the first helix fixed, with its side chains, and let Gibbs sample everything else.
A constraint can be contiguous or non-contiguous set of residues with their coordinates, and those residues must be part of the reference sequence.
crambin = read_chain(download("1CRN", fmt="pdb"))
CRAMBIN_RESIDUES = sorted(crambin)
HELIX_1 = list(range(7, 20))
helix_constraint = {r: crambin[r] for r in HELIX_1}
crambin_pdb = to_pdb(crambin, CRAMBIN_RESIDUES)
helix_constraint_pdb = to_pdb(helix_constraint, HELIX_1)
print(
"sequence :",
sequence(crambin, CRAMBIN_RESIDUES),
f"({len(CRAMBIN_RESIDUES)} residues)",
)
print("constraint:", sequence(crambin, HELIX_1), f"residues {HELIX_1[0]}-{HELIX_1[-1]}")sequence : TTCCPSIVARSNFNVCRLPGTPEAICATYTGCIIIPGATCPGDYAN (46 residues) constraint: IVARSNFNVCRLP residues 7-19
The held helix is shown in orange:
show_scene(
[
Layer(
crambin_pdb,
"lightgrey",
highlights=[(span(HELIX_1[0], HELIX_1[-1]), "#E69F00")],
)
],
height=380,
)Build an MSA and a prompt
# replace with an existing MSA job id to reuse it
crambin_msa_id: str | None = None
if crambin_msa_id is None:
crambin_msa = session.align.create_msa(seed=sequence(crambin, CRAMBIN_RESIDUES))
else:
crambin_msa = session.load_job(crambin_msa_id)
print("MSA :", crambin_msa.id)
_ = crambin_msa.wait_until_done(verbose=True)
crambin_prompt = crambin_msa.sample_prompt(num_ensemble_prompts=10, random_seed=42)
print("prompt:", crambin_prompt.id)
_ = crambin_prompt.wait_until_done(verbose=True)MSA : 772307e4-58c5-4097-8148-26a08bb088fa
stderr (1 line)
Waiting: 100%|███████████████████████████████| 100/100 [00:00<00:00, 264.50it/s, status=SUCCESS]
prompt: c18d3571-f673-8fd3-868f-28975fd92682
stderr (1 line)
Waiting: 100%|████████████████████████████████| 100/100 [00:37<00:00, 2.63it/s, status=SUCCESS]
Sample a free and a constrained ensemble
Each ensemble is one model.Input with the reference structure, the prompt and, optionally, a constraint cut from that structure.
We also sample a free ensemble with no constraint, so we can see what the constraint changed.
NUM_SAMPLES_CRAMBIN = 20
# replace with existing job ids to reuse their results
crambin_free_job_id: str | None = None
crambin_held_job_id: str | None = None
crambin_jobs = {}
for name, job_id, constraint in (
("free", crambin_free_job_id, None),
("constrained", crambin_held_job_id, helix_constraint_pdb),
):
if job_id is None:
crambin_jobs[name] = model.sample(
[
model.Input(
reference_structure=crambin_pdb,
prompt=crambin_prompt,
constraint=constraint,
)
],
num_samples=NUM_SAMPLES_CRAMBIN,
temperature=TEMPERATURE_K,
)
else:
crambin_jobs[name] = session.load_job(job_id)
print(f"{name:11s}:", crambin_jobs[name].id)
for job in crambin_jobs.values():
_ = job.wait_until_done(verbose=True, timeout=ENSEMBLE_TIMEOUT)
crambin_free_job, crambin_held_job = crambin_jobs["free"], crambin_jobs["constrained"]Check that the constraint held
We superpose each conformation on the held atoms and measure how far they moved from the constraint. A constraint that held comes back at about 0 Å.
crambin_free = fetch_ensemble(crambin_free_job, CRAMBIN_RESIDUES)
crambin_held = fetch_ensemble(crambin_held_job, CRAMBIN_RESIDUES)
print(
f"free: {len(crambin_free)} conformations | constrained: {len(crambin_held)} conformations\n"
)
held_check(crambin_held, helix_constraint)Where does the protein still move?
We superpose both ensembles on the CA atoms of the held helix, and compute the per-residue RMSF (root mean square fluctuation). In the constrained ensemble, the helix does not move at all, while the rest of the protein keeps sampling around it.
crambin_free = superposed(crambin_free, crambin, on=HELIX_1)
crambin_held = superposed(crambin_held, crambin, on=HELIX_1)
fig, ax = plt.subplots(figsize=(10, 3))
ax.axvspan(
HELIX_1[0] - 0.5,
HELIX_1[-1] + 0.5,
color="#E69F00",
alpha=0.15,
lw=0,
label="held (helix 7–19)",
)
ax.plot(
CRAMBIN_RESIDUES,
rmsf(crambin_free, CRAMBIN_RESIDUES),
color="#999999",
lw=1.5,
label="free",
)
ax.plot(
CRAMBIN_RESIDUES,
rmsf(crambin_held, CRAMBIN_RESIDUES),
color="#0072B2",
lw=1.5,
label="constrained",
)
ax.set_xlabel("Residue")
ax.set_ylabel("CA RMSF (Å)")
ax.set_title(
f"Crambin at {TEMPERATURE_K} K: flexibility with and without the first helix held"
)
ax.legend(frameon=False)
fig.tight_layout()Render the constrained ensemble
All 20 conformations of the constrained ensemble, overlaid after superposing on the held helix. The held helix (residues 7–19) is orange and lands on itself in every conformation; the sampled rest of the protein is blue.
def show_constrained(conformations: list[dict], resseqs, held, color="#E69F00"):
"""Every conformation overlaid, with the held residues in `color` and the sampled ones in blue."""
lo, hi = min(held), max(held)
show_scene(
[
Layer(
to_pdb(conformations, resseqs),
"#56B4E9",
models=range(len(conformations)),
highlights=[(span(lo, hi), color)],
)
]
)
show_constrained(crambin_held, CRAMBIN_RESIDUES, HELIX_1)Part 2: An allosteric response in PTP1B
The question
PTP1B's active site sits between two loops that open and close together:
| region | residues | role |
|---|---|---|
| WPD loop | 178–188 | closes over the substrate; D181 is the catalytic acid |
| P-loop | 214–221 | binds the phosphate; C215 is the catalytic nucleophile |
| L16 | 237–243 | a loop on the far side of the domain, never constrained here |
Two crystal structures show the two states:
- 5K9W: WPD loop closed (D181–C215 CA distance 8.3 Å)
- 2CM2: WPD loop open (13.0 Å)
L16 also sits differently in the two structures, about 2.6 Å CA RMSD apart. So we ask: if we fix the WPD loop and the P-loop in one state, does L16 move to its position in the crystal structure of that same state?
We run two ensembles:
- closed: WPD loop and P-loop fixed as in 5K9W, sampled from the closed reference
- open: WPD loop and P-loop fixed as in 2CM2, sampled from the open reference
Each run starts from the reference in the same state as its constraint. Everything except the two fixed loops is sampled, L16 included.
Download the structures
pdb_5k9w = read_chain(
download("5K9W")
) # closed, with the inhibitor TCS401 (dropped, it is not polymer)
pdb_2cm2 = read_chain(download("2CM2")) # apo, open
pdb_1sug = read_chain(
download("1SUG")
) # apo, closed; supplies the C-terminal residues 294-299
for name, chain in (("5K9W", pdb_5k9w), ("2CM2", pdb_2cm2), ("1SUG", pdb_1sug)):
print(f"{name}: residues {min(chain)}-{max(chain)} ({len(chain)} with coordinates)")5K9W: residues 0-297 (298 with coordinates) 2CM2: residues 0-282 (283 with coordinates) 1SUG: residues 2-299 (298 with coordinates)
Build the references and the constraints
Each reference covers residues 2–299, and both have the same sequence, so one MSA and one prompt serve both runs. No single entry covers that whole range in both states, so each reference is assembled from several entries:
- closed reference: 5K9W residues 2–293, plus 1SUG for 294–299 (5K9W ends at 297)
- open reference: 2CM2 residues 2–278, 5K9W for 279–293 (2CM2 has no α7 helix), and 1SUG for 294–299
Every entry is first superposed onto 5K9W on the residues that do not move between them, so all the pieces share one frame. The constraints are the WPD loop and the P-loop, with side chains, cut from 5K9W (closed) and from the superposed 2CM2 (open). Both constraints hold exactly the same atoms.
def core_fit(P, Q, cutoff=2.0, min_frac=0.4, max_iter=20):
"""Superpose P onto Q on the positions that do not move, so a moving loop does not drag the fit."""
core = np.ones(len(P), dtype=bool)
for _ in range(max_iter):
R, t = kabsch(P[core], Q[core])
dev = np.linalg.norm(P @ R.T + t - Q, axis=-1)
new = dev < cutoff
if new.sum() < max(3, min_frac * len(P)):
new = dev <= np.quantile(dev, min_frac)
if (new == core).all():
break
core = new
R, t = kabsch(P[core], Q[core])
return R, t, core
def fit_onto_5k9w(chain, lo, hi):
"""`chain` superposed onto 5K9W on its rigid core between residues lo and hi; also returns that core."""
shared = [
r
for r in range(lo, hi + 1)
if r in chain and r in pdb_5k9w and chain[r]["name"] == pdb_5k9w[r]["name"]
]
R, t, core = core_fit(ca(chain, shared), ca(pdb_5k9w, shared))
return moved(chain, R, t), [r for r, c in zip(shared, core) if c]
WPD, P_LOOP, L16 = list(range(178, 189)), list(range(214, 222)), list(range(237, 244))
FIXED = WPD + P_LOOP
PTP1B_RESIDUES = list(range(2, 300))
fit_1sug, _ = fit_onto_5k9w(pdb_1sug, 2, 297)
fit_2cm2, core_2cm2 = fit_onto_5k9w(pdb_2cm2, 2, 282)
closed_ref = {r: (pdb_5k9w if r < 294 else fit_1sug)[r] for r in PTP1B_RESIDUES}
open_ref = {
r: (fit_2cm2 if r < 279 else pdb_5k9w if r < 294 else fit_1sug)[r]
for r in PTP1B_RESIDUES
}
# the same atoms in both states: those present in both 5K9W and 2CM2
shared_atoms = {
r: [a for a in pdb_5k9w[r]["atoms"] if a in pdb_2cm2[r]["atoms"]] for r in FIXED
}
closed_loops = {
r: {
"name": pdb_5k9w[r]["name"],
"atoms": {a: pdb_5k9w[r]["atoms"][a] for a in shared_atoms[r]},
}
for r in FIXED
}
open_loops = {
r: {
"name": fit_2cm2[r]["name"],
"atoms": {a: fit_2cm2[r]["atoms"][a] for a in shared_atoms[r]},
}
for r in FIXED
}
# the rigid core every conformation is superposed on: 2CM2's core, minus the loops, L11 and the C-terminus
flexible = (
set(range(WPD[0] - 2, WPD[-1] + 3))
| set(range(P_LOOP[0] - 2, P_LOOP[-1] + 3))
| set(range(L16[0] - 2, L16[-1] + 3))
| set(range(150, 154))
| set(range(280, 300))
)
CORE = [r for r in core_2cm2 if r not in flexible]
closed_ref_pdb, open_ref_pdb = (
to_pdb(closed_ref, PTP1B_RESIDUES),
to_pdb(open_ref, PTP1B_RESIDUES),
)
closed_loops_pdb, open_loops_pdb = (
to_pdb(closed_loops, FIXED),
to_pdb(open_loops, FIXED),
)
ptp1b_sequence = sequence(closed_ref, PTP1B_RESIDUES)
assert sequence(open_ref, PTP1B_RESIDUES) == ptp1b_sequence, (
"the two references must share a sequence"
)
d_closed = np.linalg.norm(
closed_ref[181]["atoms"]["CA"] - closed_ref[215]["atoms"]["CA"]
)
d_open = np.linalg.norm(open_ref[181]["atoms"]["CA"] - open_ref[215]["atoms"]["CA"])
L16_APART = ca_rmsd(closed_ref, fit_2cm2, L16)
print(f"references : residues 2-299, {len(ptp1b_sequence)} residues, same sequence")
print(f"D181-C215 : closed {d_closed:.1f} Å, open {d_open:.1f} Å")
print(
f"constraints: {len(FIXED)} residues, {sum(len(v) for v in shared_atoms.values())} atoms each"
)
print(f"L16 : 5K9W and 2CM2 are {L16_APART:.2f} Å CA RMSD apart")
print(f"core : {len(CORE)} residues")references : residues 2-299, 298 residues, same sequence D181-C215 : closed 8.3 Å, open 13.0 Å constraints: 19 residues, 137 atoms each L16 : 5K9W and 2CM2 are 2.62 Å CA RMSD apart core : 235 residues
The two references, closed (5K9W) in blue and then open (2CM2) in vermillion. The loops we fix, the WPD loop and the P-loop, and the loop L16 are coloured by state.
COLORS = {
"closed": "#0072B2",
"open": "#D55E00",
} # Okabe-Ito blue and vermillion, safe for colour blindness
TITLES = {"closed": "Closed (5K9W)", "open": "Open (2CM2)"}
LOOPS = {"WPD loop": WPD, "P-loop": P_LOOP, "L16": L16}
def ptp1b_layer(pdb: str, state: str) -> Layer:
"""The protein in grey, with the three loops in the color of the state, and labelled."""
return Layer(
pdb,
"#DADDE2",
highlights=[(span(r[0], r[-1]), COLORS[state]) for r in LOOPS.values()],
labels=[(span(r[0], r[-1]), name) for name, r in LOOPS.items()],
)
for state, pdb in (("closed", closed_ref_pdb), ("open", open_ref_pdb)):
print(TITLES[state])
show_scene([ptp1b_layer(pdb, state)], height=420)Closed (5K9W)
Open (2CM2)
Build an MSA and a prompt
Both references have the same sequence, so one prompt serves both runs.
# replace with an existing MSA job id to reuse it
ptp1b_msa_id: str | None = None
if ptp1b_msa_id is None:
ptp1b_msa = session.align.create_msa(seed=ptp1b_sequence)
else:
ptp1b_msa = session.load_job(ptp1b_msa_id)
print("MSA :", ptp1b_msa.id)
_ = ptp1b_msa.wait_until_done(verbose=True)
ptp1b_prompt = ptp1b_msa.sample_prompt(num_ensemble_prompts=10, random_seed=42)
print("prompt:", ptp1b_prompt.id)
_ = ptp1b_prompt.wait_until_done(verbose=True)MSA : 7f33cf3d-c866-42fa-b9dd-0498404a06df
stderr (1 line)
Waiting: 100%|███████████████████████████████| 100/100 [00:00<00:00, 362.93it/s, status=SUCCESS]
prompt: 618fd4af-4e7a-8804-abe1-955449ab46cc
stderr (1 line)
Waiting: 100%|████████████████████████████████| 100/100 [08:21<00:00, 5.01s/it, status=SUCCESS]
Sample the two states
We submit both runs before waiting on either, so they sample at the same time.
NUM_SAMPLES_PTP1B conformations per state gives a clear picture of where L16 goes. Lower NUM_SAMPLES_PTP1B for a quicker first run.
NUM_SAMPLES_PTP1B = 200
# replace with existing job ids to reuse their results
ptp1b_job_ids: dict[str, str | None] = {"closed": None, "open": None}
ptp1b_runs = {
"closed": (closed_ref_pdb, closed_loops_pdb),
"open": (open_ref_pdb, open_loops_pdb),
}
ptp1b_constraints = {"closed": closed_loops, "open": open_loops}
ptp1b_jobs = {}
for state, (reference_pdb, constraint_pdb) in ptp1b_runs.items():
if ptp1b_job_ids[state] is None:
ptp1b_jobs[state] = model.sample(
[
model.Input(
reference_structure=reference_pdb,
prompt=ptp1b_prompt,
constraint=constraint_pdb,
)
],
num_samples=NUM_SAMPLES_PTP1B,
temperature=TEMPERATURE_K,
)
else:
ptp1b_jobs[state] = session.load_job(ptp1b_job_ids[state])
print(f"{state:6s}:", ptp1b_jobs[state].id)
for job in ptp1b_jobs.values():
_ = job.wait_until_done(verbose=True, timeout=ENSEMBLE_TIMEOUT)Check that the loops held
As in Part 1, the held atoms should come back at about 0 Å from the constraint. The fixed residues have a few atoms that are not in the constraint, because it holds only the atoms present in both 5K9W and 2CM2. Those few are sampled.
ptp1b_ensembles = {}
for state, job in ptp1b_jobs.items():
conformations = fetch_ensemble(job, PTP1B_RESIDUES)
print(f"[{state}] {len(conformations)} conformations")
held_check(conformations, ptp1b_constraints[state])
ptp1b_ensembles[state] = superposed(conformations, closed_ref, on=CORE)Measure L16 in every conformation
After superposing each conformation on the rigid core, we measure:
- the L16 CA RMSD to its position in 5K9W (closed) and in 2CM2 (open). A conformation is closer to open when its RMSD to 2CM2 is the smaller of the two.
- the D181–C215 CA distance, which confirms the active-site loops stayed in their state.
rows = []
for state, conformations in ptp1b_ensembles.items():
for k, c in enumerate(conformations):
rows.append(
{
"state": state,
"sample": k,
"l16_rmsd_closed": ca_rmsd(c, closed_ref, L16),
"l16_rmsd_open": ca_rmsd(c, fit_2cm2, L16),
"d181_c215": float(
np.linalg.norm(c[181]["atoms"]["CA"] - c[215]["atoms"]["CA"])
),
}
)
ptp1b_df = pd.DataFrame(rows)
ptp1b_df["l16_closer_to_open"] = ptp1b_df.l16_rmsd_open < ptp1b_df.l16_rmsd_closed
ptp1b_df.groupby("state", sort=False).agg(
conformations=("sample", "size"),
d181_c215_median=("d181_c215", "median"),
l16_rmsd_to_5k9w_median=("l16_rmsd_closed", "median"),
l16_rmsd_to_2cm2_median=("l16_rmsd_open", "median"),
l16_closer_to_open=("l16_closer_to_open", "mean"),
).round(2)Plot the response of L16
Each point is one conformation, placed by its L16 CA RMSD to the two crystal structures. The stars mark 5K9W and 2CM2 themselves. Points above the diagonal have L16 closer to the closed crystal structure, and points below it closer to the open one.
def plot_l16_scatter(df: pd.DataFrame, l16_apart: float):
fig, ax = plt.subplots(figsize=(5.2, 5.2))
lim = max(df.l16_rmsd_closed.quantile(0.99), df.l16_rmsd_open.quantile(0.99)) * 1.08
for state in ("closed", "open"):
g = df[df.state == state]
ax.scatter(
g.l16_rmsd_closed,
g.l16_rmsd_open,
s=10,
color=COLORS[state],
alpha=0.55,
lw=0,
label=f"{state} constraint",
)
ax.plot([0, lim], [0, lim], color="#5A5A5A", lw=0.8, ls=":")
ax.scatter(
[0, l16_apart],
[l16_apart, 0],
marker="*",
s=320,
color=[COLORS["closed"], COLORS["open"]],
edgecolor="white",
lw=0.8,
zorder=4,
clip_on=False,
)
ax.annotate(
"5K9W",
(0, l16_apart),
xytext=(8, 8),
textcoords="offset points",
fontweight="bold",
color=COLORS["closed"],
)
ax.annotate(
"2CM2",
(l16_apart, 0),
xytext=(6, 8),
textcoords="offset points",
fontweight="bold",
color=COLORS["open"],
)
closer_to_open = df.groupby("state").l16_closer_to_open.mean() * 100
ax.text(
0.03,
0.97,
"closer to closed\n"
+ "\n".join(f"{s} {100 - closer_to_open[s]:.0f}%" for s in ("closed", "open")),
transform=ax.transAxes,
va="top",
fontsize=9,
color="#5A5A5A",
)
ax.text(
0.97,
0.22,
"closer to open\n"
+ "\n".join(f"{s} {closer_to_open[s]:.0f}%" for s in ("closed", "open")),
transform=ax.transAxes,
ha="right",
va="bottom",
fontsize=9,
color="#5A5A5A",
)
ax.set_xlim(0, lim)
ax.set_ylim(0, lim)
ax.set_aspect("equal")
ax.set_xlabel("L16 Cα RMSD to 5K9W, closed (Å)")
ax.set_ylabel("L16 Cα RMSD to 2CM2, open (Å)")
ax.set_title("Gibbs-generated samples", fontweight="bold")
ax.spines[["top", "right"]].set_visible(False)
ax.legend(
loc="lower left",
frameon=True,
framealpha=0.9,
edgecolor="none",
markerscale=1.5,
)
fig.tight_layout()
return fig
_ = plot_l16_scatter(ptp1b_df, L16_APART)With the active-site loops fixed closed, almost every conformation keeps L16 close to its 5K9W position. With the loops fixed open, the cloud shifts toward 2CM2, and a large share of the conformations have L16 closer to its open position. L16 itself was never constrained: it was sampled freely in both runs, and it settled near the crystal position of the state its active-site loops were fixed in.
The D181–C215 distances in the table above confirm that the active-site loops stayed in their state in both runs.
Render the response
For each state we draw the conformation whose L16 is closest to that state's crystal structure, in grey, with its loops coloured by state. On top, L16 from ten random conformations of the same run shows how far it spreads.
rng = np.random.default_rng(0)
best_column = {"closed": "l16_rmsd_closed", "open": "l16_rmsd_open"}
for state in ("closed", "open"):
runs = ptp1b_df[ptp1b_df.state == state]
best = int(runs.sort_values(best_column[state]).iloc[0]["sample"])
bundle = rng.choice(runs["sample"].values, size=min(10, len(runs)), replace=False)
l16_bundle = to_pdb([ptp1b_ensembles[state][int(i)] for i in bundle], L16)
print(
f"{state:6s}: best conformation {best}, L16 {runs.loc[runs['sample'] == best, best_column[state]].item():.2f} Å "
f"from {'5K9W' if state == 'closed' else '2CM2'}"
)
show_scene(
[
ptp1b_layer(to_pdb(ptp1b_ensembles[state][best], PTP1B_RESIDUES), state),
Layer(l16_bundle, COLORS[state], models=range(len(bundle)), opacity=0.6),
],
height=440,
)Save the ensembles
Each ensemble is written as a multi-model PDB file, superposed on the rigid core and numbered like the PDB entries. PyMOL, ChimeraX and VMD all open these files as one trajectory.
OUT_DIR = Path("ensembles")
OUT_DIR.mkdir(exist_ok=True)
outputs = {
"1CRN_free_ensemble.pdb": (crambin_free, CRAMBIN_RESIDUES),
"1CRN_helix1_held_ensemble.pdb": (crambin_held, CRAMBIN_RESIDUES),
"PTP1B_loops_closed_ensemble.pdb": (ptp1b_ensembles["closed"], PTP1B_RESIDUES),
"PTP1B_loops_open_ensemble.pdb": (ptp1b_ensembles["open"], PTP1B_RESIDUES),
}
for name, (conformations, resseqs) in outputs.items():
(OUT_DIR / name).write_text(to_pdb(conformations, resseqs))
print("wrote", OUT_DIR / name)
ptp1b_df.to_csv(OUT_DIR / "PTP1B_L16_per_conformation.csv", index=False)
print("wrote", OUT_DIR / "PTP1B_L16_per_conformation.csv")Conclusion
In this walkthrough, we used Gibbs to sample around a constraint:
- Crambin: a constraint is a piece of the reference, cut out with its residue numbers intact. Gibbs keeps it in place, and the rest of the protein keeps moving around it.
- PTP1B: with the WPD loop and the P-loop fixed in one state, the distant loop L16, which is sampled freely, sits near its crystal position in that same state.