Sample conformational ensembles of protein complexes with Gibbs
Proteins move, and a single structure shows only one conformation. In this tutorial, we'll use the OpenProtein structural ensemble model to sample ensembles of conformations around a structure you already have.
Objective We'll sample and visualize two ensembles:
- A monomer: crambin (PDB 1CRN), a 46-residue plant protein. It is small, so its MSA, prompt and ensemble come back fast. This makes it a good first run.
- A multimer: a single-domain antibody (nanobody) bound to the ricin A-chain (PDB 5SV3). The two chains are sampled together, so the ensemble shows how the complex flexes while it stays docked.
How the model works The model starts from a reference structure and samples conformations around it. It 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. For a complex, the chains are joined by
:and homologs are paired across chains. - 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 release that includes Gibbsnumpyandmatplotlibmolviewspec, which renders the 3D structures inside the notebook with Mol*
You don't need to download any data by hand. The notebook fetches both structures from the RCSB PDB.
Run time. Building an MSA is the slow step. A monomer like crambin takes a few minutes. A complex can take much longer, because homologs are searched and paired for every chain.
Each step prints its job id. To pick up where you left off without recomputing anything, load a finished job with session.load_job(job_id).
%pip install --quiet openprotein-python numpy matplotlib molviewspecImports
The printed version shows which SDK the kernel imported.
import getpass
import os
from pathlib import Path
import matplotlib.pyplot as plt
import molviewspec as mvs
import numpy as np
import openprotein
from matplotlib.colors import to_hex
from openprotein.molecules import Complex, Protein, Structure
print("openprotein", openprotein.__version__)
TEMPERATURE_K = 300Download the structures
Structure.from_pdb_id fetches an entry from the RCSB. We take its first model and keep only the protein chains we want to sample, which leaves out waters and ligands.
We also keep only the residues the experiment resolved, so the sequence the MSA is built from matches the structure that is sampled.
The monomer: crambin (1CRN)
def resolved(protein: Protein) -> Protein:
"""Only the residues with coordinates, so the sequence matches the structure."""
return protein.at(np.flatnonzero(~protein.get_structure_mask()) + 1)
monomer = Complex(
{"A": resolved(Structure.from_pdb_id("1CRN")[0].get_protein(chain_id="A"))}
)
monomer_sequence = monomer.get_protein(chain_id="A").sequence.decode()
print("sequence:", monomer_sequence)
print("length :", len(monomer_sequence))sequence: TTCCPSIVARSNFNVCRLPGTPEAICATYTGCIIIPGATCPGDYAN length : 46
The multimer: nanobody + ricin A-chain (5SV3)
The 5SV3 entry holds two copies of the complex in its asymmetric unit: A/B and C/D. We keep one copy, with the nanobody as chain A and ricin as chain B.
For a complex, the sequence we build the MSA from is the chains joined by :.
entry = Structure.from_pdb_id("5SV3")[0]
complex_ = Complex({c: resolved(entry.get_protein(chain_id=c)) for c in ["A", "B"]})
complex_sequence = ":".join(
p.sequence.decode() for p in complex_.get_proteins().values()
)
for name, p in complex_.get_proteins().items():
print(f"chain {name}: {len(p)} residues")
print("MSA seed:", complex_sequence[:40] + "...")chain A: 126 residues chain B: 167 residues MSA seed: EVQLVESGGGLVQAGDSLRLSCTASGRTLGDYGVAWFRQA...
Look at the inputs
The cell below defines show, which renders structures in the notebook with Mol*, and draws the two inputs.
You can rotate a view with the mouse and zoom with the scroll wheel.
Crambin is first, then the complex with the nanobody (chain A) in blue and ricin (chain B) in orange.
CHAIN_COLORS = {"A": "#4C78A8", "B": "#F58518"}
def show(
*layers: tuple[Complex, str | dict[str, str], float], height: int = 450
) -> None:
"""Draw complexes together in one Mol* viewer, as cartoons.
Each layer is (complex, color, opacity). The color is one color, or a
{chain id: color} dict.
"""
builder = mvs.create_builder()
files = {}
for i, (molecule, color, opacity) in enumerate(layers):
name = f"structure_{i}.pdb"
files[name] = molecule.to_string(format="pdb").encode()
structure = builder.download(url=name).parse(format="pdb").model_structure()
cartoon = structure.component(selector="polymer").representation(type="cartoon")
if isinstance(color, dict):
for chain, c in color.items():
cartoon.color(
color=c, selector=mvs.ComponentExpression(auth_asym_id=chain)
)
else:
cartoon.color(color=color)
if opacity < 1:
cartoon.opacity(opacity=opacity)
builder.molstar_notebook(data=files, width=800, height=height)
show((monomer, CHAIN_COLORS["A"], 1.0), height=380)
show((complex_, CHAIN_COLORS, 1.0), height=380)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 for the results
An ensemble comes back as a Structure with one Complex per conformation. Each chain keeps its id and its residues, in the reference's order.
The sampler writes each conformation in its own frame, so before comparing conformations we superpose each one onto the reference on its CA atoms, with the client's superimpose_onto.
The helpers below cover what the client does not: the closest distance between two chains, the overlay of an ensemble, and its per-residue flexibility.
# The first run can take longer while the model loads.
ENSEMBLE_TIMEOUT = 1800
# Protein.coordinates holds each residue's atoms in the atom37 layout; CA is atom 1.
CA = 1
def closest_ca_distance(model: Complex, chain_a: str, chain_b: str) -> float:
"""The closest CA-CA distance between two chains, in Å."""
a = model.get_protein(chain_id=chain_a).coordinates[:, CA]
b = model.get_protein(chain_id=chain_b).coordinates[:, CA]
return float(np.nanmin(np.linalg.norm(a[:, None] - b[None, :], axis=-1)))
def show_ensemble(
ens: Structure, reference: Complex, colors: dict[str, str] | None = None
) -> None:
"""Every conformation overlaid on the reference, which is drawn in grey.
Conformations are colored first to last, or by chain when `colors` is given.
"""
n = len(ens)
layers = [(reference, "lightgrey", 0.6)]
for i, conformation in enumerate(ens):
color = colors or to_hex(plt.cm.viridis(i / max(n - 1, 1)))
layers.append((conformation, color, 0.6))
show(*layers)
def plot_rmsf(ens: Structure, title: str) -> None:
"""Per-residue CA RMSF (Å) across the conformations, one panel per chain.
Superpose the conformations first.
"""
chain_ids = list(ens[0].get_proteins())
fig, axes = plt.subplots(
1, len(chain_ids), figsize=(12, 3), sharey=True, squeeze=False
)
for ax, chain_id in zip(axes[0], chain_ids, strict=True):
xyz = np.stack(
[m.get_protein(chain_id=chain_id).coordinates[:, CA] for m in ens]
)
rmsf = np.sqrt(((xyz - xyz.mean(axis=0)) ** 2).sum(axis=-1).mean(axis=0))
residues = np.arange(1, len(rmsf) + 1)
color = CHAIN_COLORS.get(chain_id, "grey")
ax.plot(residues, rmsf, color=color)
ax.fill_between(residues, rmsf, alpha=0.2, color=color)
ax.set_xlabel(f"Residue (chain {chain_id})")
axes[0, 0].set_ylabel("CA RMSF (Å)")
fig.suptitle(title)
fig.tight_layout()Part 1: Sample an ensemble of a monomer
Build an MSA and a prompt
First, we build an MSA from the crambin sequence. Then we sample a prompt from it.
num_ensemble_prompts=10 samples ten sets of homologs. The model averages over them, which makes the embedding less sensitive to which homologs any one prompt drew.
monomer_msa = session.align.create_msa(seed=monomer_sequence)
print("MSA :", monomer_msa.id)
_ = monomer_msa.wait_until_done(verbose=True)
monomer_prompt = monomer_msa.sample_prompt(num_ensemble_prompts=10, random_seed=42)
print("prompt:", monomer_prompt.id)
_ = monomer_prompt.wait_until_done(verbose=True)MSA : 81773208-4711-44f8-a623-b774f0f5414f
stderr (1 line)
Waiting: 100%|███████████████████████████████| 100/100 [00:00<00:00, 279.70it/s, status=SUCCESS]
prompt: 3e264199-4f61-4140-aa6b-4497eb26fb3c
stderr (1 line)
Waiting: 100%|████████████████████████████████| 100/100 [02:04<00:00, 1.25s/it, status=SUCCESS]
Sample the ensemble
Each ensemble is one model.Input:
reference_structure: the structure to sample around. It can be PDB or mmCIF text, aProtein,ComplexorStructure, or a finished structure prediction.prompt: the prompt for this protein, or its id. A prompt is sampled from one protein's MSA, so each input carries its own.temperature: optional, in Kelvin. It overrides the call'stemperaturefor this input. Higher temperatures give broader ensembles.
sample takes a list of inputs, so a single call can sample several proteins, or the same protein at several temperatures.
num_samples is the number of conformations in each ensemble.
NUM_SAMPLES_MONOMER = 20
monomer_job = model.sample(
[model.Input(reference_structure=monomer, prompt=monomer_prompt)],
num_samples=NUM_SAMPLES_MONOMER,
temperature=TEMPERATURE_K,
)
print("ensemble:", monomer_job.id)
_ = monomer_job.wait_until_done(verbose=True, timeout=ENSEMBLE_TIMEOUT)ensemble: 7a6a8bfb-c4a8-43ef-a0db-da4599b29fca
stderr (1 line)
Waiting: 100%|████████████████████████████████| 100/100 [04:10<00:00, 2.50s/it, status=SUCCESS]
Inspect the ensemble
We fetch the ensemble and superpose every conformation onto the crystal structure. The CA RMSD to the reference shows how far each conformation moved from it.
monomer_ens = monomer_job.get()[0]
n_residues = len(monomer_ens[0].get_protein(chain_id="A"))
print(f"{len(monomer_ens)} conformations, {n_residues} residues each")
# superimpose_onto moves each conformation onto the reference, in place
monomer_rmsds = [
monomer.rmsd(m.superimpose_onto(monomer, backbone_only="CA"), backbone_only="CA")
for m in monomer_ens
]
print(
f"CA RMSD to the crystal structure: mean {np.mean(monomer_rmsds):.2f} Å, "
f"range {min(monomer_rmsds):.2f}-{max(monomer_rmsds):.2f} Å"
)20 conformations, 46 residues each CA RMSD to the crystal structure: mean 0.83 Å, range 0.39-1.24 Å
Render the conformations
Every conformation is overlaid on the crystal structure (grey), colored from first to last.
show_ensemble(monomer_ens, monomer)Where does the protein move?
The per-residue CA RMSF (root mean square fluctuation) measures how much each residue moves across the ensemble. Peaks mark the flexible regions. In crambin, the termini and the loops between its two helices and its β-sheet are the most likely to move.
plot_rmsf(
monomer_ens,
f"Crambin (1CRN): flexibility across {len(monomer_ens)} conformations "
f"at {TEMPERATURE_K} K",
)Part 2: Sample an ensemble of a multimer
Sampling a complex uses the same API. Only two things change:
- The MSA is built from the chains joined by
:, so homologs are searched for the whole complex and paired across its chains. - The reference structure holds every chain. The ensemble comes back with the same chain ids, and the same residues in the same order, as the reference.
Build an MSA and a prompt for the complex
# a paired MSA for a complex is slow
complex_msa = session.align.create_msa(seed=complex_sequence)
print("MSA :", complex_msa.id)
_ = complex_msa.wait_until_done(verbose=True)
complex_prompt = complex_msa.sample_prompt(num_ensemble_prompts=10, random_seed=42)
print("prompt:", complex_prompt.id)
_ = complex_prompt.wait_until_done(verbose=True)MSA : 4723ee3a-9a78-46ff-9e38-d66f92ec73ca
stderr (1 line)
Waiting: 100%|███████████████████████████████| 100/100 [00:00<00:00, 225.80it/s, status=SUCCESS]
prompt: 4fb0628b-e613-4301-927f-a6ed441fef99
stderr (1 line)
Waiting: 100%|████████████████████████████████| 100/100 [03:41<00:00, 2.21s/it, status=SUCCESS]
Sample the ensemble of the complex
NUM_SAMPLES_COMPLEX = 8
complex_job = model.sample(
[model.Input(reference_structure=complex_, prompt=complex_prompt)],
num_samples=NUM_SAMPLES_COMPLEX,
temperature=TEMPERATURE_K,
)
print("ensemble:", complex_job.id)
_ = complex_job.wait_until_done(verbose=True, timeout=ENSEMBLE_TIMEOUT)ensemble: 28aa941a-93c6-4740-a057-8123795d3427
stderr (1 line)
Waiting: 100%|████████████████████████████████| 100/100 [01:47<00:00, 1.08s/it, status=SUCCESS]
Inspect the ensemble of the complex
For a complex, it is also worth checking that the two chains stay docked. For each conformation, we measure the closest CA-CA distance between the nanobody and ricin, and compare it with the crystal structure.
complex_ens = complex_job.get()[0]
print(f"{len(complex_ens)} conformations")
for name, chain in complex_ens[0].get_proteins().items():
print(f" chain {name}: {len(chain)} residues")
complex_rmsds = [
complex_.rmsd(m.superimpose_onto(complex_, backbone_only="CA"), backbone_only="CA")
for m in complex_ens
]
reference_closest = closest_ca_distance(complex_, "A", "B")
print(f"\nreference: closest nanobody-ricin CA distance {reference_closest:.1f} Å")
for i, (m, rmsd) in enumerate(zip(complex_ens, complex_rmsds, strict=True), start=1):
closest = closest_ca_distance(m, "A", "B")
print(
f"conformation {i}: CA RMSD {rmsd:.2f} Å, "
f"closest nanobody-ricin CA {closest:.1f} Å"
)8 conformations chain A: 126 residues chain B: 167 residues reference: closest nanobody-ricin CA distance 4.2 Å conformation 1: CA RMSD 1.62 Å, closest nanobody-ricin CA 4.4 Å conformation 2: CA RMSD 3.28 Å, closest nanobody-ricin CA 3.8 Å conformation 3: CA RMSD 1.30 Å, closest nanobody-ricin CA 4.3 Å conformation 4: CA RMSD 1.35 Å, closest nanobody-ricin CA 4.1 Å conformation 5: CA RMSD 1.60 Å, closest nanobody-ricin CA 4.3 Å conformation 6: CA RMSD 1.77 Å, closest nanobody-ricin CA 4.4 Å conformation 7: CA RMSD 1.86 Å, closest nanobody-ricin CA 4.1 Å conformation 8: CA RMSD 2.58 Å, closest nanobody-ricin CA 4.0 Å
Render the conformations of the complex
The nanobody (chain A) is blue and ricin (chain B) is orange.
show_ensemble(complex_ens, complex_, colors=CHAIN_COLORS)Where does the complex move?
We plot the RMSF for each chain separately. In the nanobody, the CDR loops that contact the antigen are the usual places to look.
plot_rmsf(
complex_ens, f"Nanobody (A) + ricin A-chain (B): flexibility at {TEMPERATURE_K} K"
)Save the ensembles
Each ensemble is written as a multi-model PDB file. PyMOL, ChimeraX and VMD all open these files as one trajectory.
OUT_DIR = Path("ensembles")
OUT_DIR.mkdir(exist_ok=True)
for name, ens in [
("1CRN_ensemble.pdb", monomer_ens),
("5SV3_AB_ensemble.pdb", complex_ens),
]:
(OUT_DIR / name).write_text(ens.to_string(format="pdb"))
print("wrote", OUT_DIR / name)wrote ensembles/1CRN_ensemble.pdb wrote ensembles/5SV3_AB_ensemble.pdb
Conclusion
In this walkthrough, we sampled conformational ensembles with the structural ensemble model:
- Monomer: from a crystal structure, an MSA and a prompt, to an ensemble of conformations and a per-residue flexibility profile.
- Multimer: the same steps for a two-chain complex. The MSA is built from
:-joined chains, and both chains are sampled together and stayed docked in this run.