benchmark — Structure Prediction Benchmarking
The synth_pdb.benchmark and synth_pdb.benchmark_metrics modules provide
a complete suite for evaluating AI structure prediction models (AlphaFold,
ESMFold, RoseTTAFold, etc.) against ground-truth synthetic structures.
The key insight
Because synth-pdb controls the ground truth, the benchmark is perfectly objective: there is no ambiguity about which experimental structure is "correct" or whether the reference contains modelling errors. This makes it ideal for blind comparison of structure prediction models.
Quick Start
from synth_pdb.benchmark import run_benchmark
# Score 20 structures predicted by ESMFold
results = run_benchmark(n_structures=20, predictor="esmfold")
# Print formatted summary
print(results.summary())
# Export to CSV for further analysis
results.to_csv("benchmark_results.csv")
Or from the command line:
# Install dependencies
pip install synth-pdb[gnn] transformers accelerate
# Run benchmark (downloads ESMFold ~700 MB on first use)
python scripts/run_benchmark.py --n-structures 20 --output results.csv
run_benchmark()
def run_benchmark(
n_structures: int = 20,
lengths: list[int] | None = None,
conformations: list[str] | None = None,
predictor: str | Callable[[str], str] = "esmfold",
*,
compute_shifts: bool = True,
compute_gnn: bool = True,
random_state: int = 42,
) -> BenchmarkResults
Generate synthetic ground-truth structures, fold them from sequence using a structure predictor, then evaluate the predictions against the ground truth using a comprehensive set of structural metrics.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
n_structures |
int |
20 |
Number of test structures to generate and evaluate. |
lengths |
list[int] |
[20, 30, 50] |
Pool of chain lengths to sample from uniformly. |
conformations |
list[str] |
["alpha", "beta"] |
Pool of secondary structure types. Options: "alpha", "beta", "random". |
predictor |
str or Callable |
"esmfold" |
"esmfold" for the built-in ESMFold backend, or any predictor_fn(sequence: str) → pdb_str callable. |
compute_shifts |
bool |
True |
Compute NMR chemical shift RMSD (requires synth_pdb.chemical_shifts). |
compute_gnn |
bool |
True |
Score both structures with the GNN pLDDT classifier. |
random_state |
int |
42 |
RNG seed for reproducibility. |
Returns
A BenchmarkResults object.
Using a Custom Predictor
def my_predictor(sequence: str) -> str:
"""Return a PDB string for the given amino acid sequence."""
# ... call your model here ...
return pdb_string
results = run_benchmark(n_structures=10, predictor=my_predictor)
This accepts any callable — ColabFold, OmegaFold, a structure database lookup, even a simple homology modelling pipeline.
BenchmarkResults
@dataclass
class BenchmarkResults:
results: list[StructureResult]
predictor: str
n_structures: int
n_success: int
Methods
summary() → str
Returns a formatted multi-line summary report:
━━ Benchmark: ESMFold (18/20 structures) ━━
TM-score mean=0.723 std=0.142 min=0.421 max=0.891
GDT-TS mean=0.681 std=0.159
lDDT mean=0.714 std=0.128
Cα-RMSD mean=2.84 Å std=1.21 Å
Shift RMSD mean=0.412 ppm std=0.193 ppm
GNN pLDDT mean=0.834 (predicted structures)
Structures with TM-score > 0.5 (same fold): 16/18 (89%)
to_csv(path: str) → None
Write full per-structure results (all 12 fields) to a CSV file.
to_dataframe() → pd.DataFrame
Return results as a pandas DataFrame (requires pandas).
StructureResult
Per-structure result returned in BenchmarkResults.results.
| Field | Type | Description |
|---|---|---|
sequence |
str |
Amino acid sequence (single-letter code). |
length |
int |
Number of residues. |
conformation |
str |
Ground-truth secondary structure type. |
tm_score |
float |
TM-score ∈ [0, 1]. Values > 0.5 indicate the same fold. |
gdt_ts |
float |
GDT-TS ∈ [0, 1]. CASP standard metric. |
lddt_mean |
float |
Mean per-residue lDDT ∈ [0, 1]. |
rmsd |
float |
Cα-RMSD in Å after Kabsch superposition. |
shift_rmsd |
float |
Weighted chemical shift RMSD in ppm. NaN if unavailable. |
gnn_score_ref |
float |
GNN global quality score for the ground-truth structure. |
gnn_score_pred |
float |
GNN global quality score for the predicted structure. |
predictor_time_s |
float |
Wall-clock inference time in seconds. |
error |
str |
Non-empty string if prediction failed; other fields are NaN. |
Benchmark Metrics Reference
All metric functions live in synth_pdb.benchmark_metrics and operate on
numpy arrays with no additional dependencies.
tm_score(ca_pred, ca_ref)
def tm_score(
ca_pred: np.ndarray, # [N, 3] predicted Cα coordinates
ca_ref: np.ndarray, # [N, 3] reference Cα coordinates
*,
normalise_by: int | None = None,
) -> float
Compute TM-score. Returns a value in (0, 1]. Two unrelated structures score ≈ 0.17; two structures with the same fold score > 0.5.
For the mathematical definition and interpretation, see the scientific background page.
lddt(ca_pred, ca_ref)
def lddt(
ca_pred: np.ndarray, # [N, 3]
ca_ref: np.ndarray, # [N, 3]
*,
inclusion_radius: float = 15.0, # Å
thresholds: tuple = (0.5, 1, 2, 4), # Å
) -> np.ndarray # [N] per-residue lDDT ∈ [0, 1]
Per-residue lDDT. Does not require superposition. The global lDDT is
float(np.mean(lddt(...))).
gdt_ts(ca_pred, ca_ref)
def gdt_ts(
ca_pred: np.ndarray, # [N, 3]
ca_ref: np.ndarray, # [N, 3]
*,
cutoffs: tuple = (1.0, 2.0, 4.0, 8.0), # Å
) -> float
GDT-TS — average fraction of Cα atoms within {1, 2, 4, 8} Å after superposition.
superpose_kabsch(mobile, reference)
def superpose_kabsch(
mobile: np.ndarray, # [N, 3]
reference: np.ndarray, # [N, 3]
) -> tuple[np.ndarray, float] # (rotated_coords, rmsd)
Optimally superpose mobile onto reference using the Kabsch algorithm (SVD-based).
Returns the rotated coordinate array and the Cα-RMSD in Å.
shift_rmsd(pred_shifts, ref_shifts)
def shift_rmsd(
pred_shifts: dict[str, np.ndarray], # nucleus → per-residue shifts
ref_shifts: dict[str, np.ndarray],
*,
nucleus_weights: dict[str, float] | None = None,
) -> float # weighted shift RMSD in ppm
Weighted chemical shift RMSD following SPARTA+ nucleus weights (H=1.0, C=0.25, N=0.1). NaN residues (missing assignments) are automatically excluded.
from synth_pdb.benchmark_metrics import shift_rmsd
import numpy as np
# Compare predicted and reference ¹H shifts for 10 residues
rmsd = shift_rmsd(
{"H": np.array([8.1, 8.2, 8.3, 8.0, 7.9, 8.4, 8.1, 8.2, 8.0, 7.8])},
{"H": np.array([8.0, 8.1, 8.4, 8.0, 7.8, 8.3, 8.2, 8.1, 8.0, 7.9])},
)
print(f"¹H shift RMSD: {rmsd:.4f} ppm")
extract_ca_coords(pdb_content)
Lightweight, pure-Python PDB parser that extracts Cα coordinates in residue order. Handles duplicate residue numbers (keeps first occurrence per chain/residue pair).
from synth_pdb.benchmark_metrics import extract_ca_coords, tm_score
ca_ref = extract_ca_coords(open("reference.pdb").read())
ca_pred = extract_ca_coords(open("predicted.pdb").read())
n = min(len(ca_ref), len(ca_pred))
score = tm_score(ca_pred[:n], ca_ref[:n])
print(f"TM-score: {score:.3f}")
CLI Reference
python scripts/run_benchmark.py [OPTIONS]
Options:
--predictor {esmfold} Structure prediction backend (default: esmfold)
--n-structures INT Number of test structures (default: 20)
--lengths L [L ...] Chain lengths to sample (default: 20 30 50)
--conformations {alpha,beta,random} [...]
Secondary structure types (default: alpha beta)
--output PATH Save CSV results to this path
--no-shifts Skip chemical shift RMSD
--no-gnn Skip GNN quality scoring
--random-state INT RNG seed (default: 42)
-v, --verbose Enable DEBUG logging
Example Runs
# Full benchmark with all metrics
python scripts/run_benchmark.py \
--n-structures 50 \
--lengths 20 30 50 \
--output results/esmfold_benchmark.csv
# Fast geometry-only benchmark
python scripts/run_benchmark.py \
--n-structures 100 \
--no-shifts --no-gnn \
--output results/fast_benchmark.csv
# Alpha-helix only
python scripts/run_benchmark.py \
--conformations alpha \
--n-structures 30 \
--output results/helix_benchmark.csv
Full API Reference
benchmark
synth_pdb.benchmark. ~~~~~~~~~~~~~~~~~~~~~~ AlphaFold / ESMFold Benchmarking Suite for synth-pdb.
The benchmark asks a simple but powerful question
"Can AI structure prediction models predict synth-pdb synthetic structures?"
Because synth-pdb controls the ground-truth structure and its NMR chemical shifts, the benchmark is perfectly objective - no ambiguity about which experimental structure is "correct".
SCIENTIFIC RATIONALE - Why benchmark against synthetic structures?
Standard benchmarks for protein structure prediction (like CASP or CAMEO) rely on experimental structures from the PDB. While essential, these have noise: * Resolution limits and refinement errors. * Conformational ensemble averaging in crystals/cryo-EM. * Missing loops or disordered regions.
The synth-pdb benchmark provides a Perfect Control Group:
1. Objective Truth: We control every atomic coordinate exactly.
2. Zero Ambiguity: NMR chemical shifts are predicted directly from
the ground truth, eliminating experimental measurement error.
3. Targeted Stress: We can generate structures that specifically
challenge AI models (e.g., extremely long helices or unusual linkers).
METRICS EXPLAINED - The Structural Biology Toolkit
We use the same standards used to judge AlphaFold in CASP competitions:
- TM-score (Template Modeling score): Measures global topology overlap. Ranges [0, 1]. >0.5 typically means the "same fold."
- GDT-TS (Global Distance Test Total Score): Percentage of residues whose Calpha positions are within 1, 2, 4, or 8 A of the target.
- lDDT (Local Distance Difference Test): Measures how well the local inter-atomic distances are preserved. Unlike RMSD, it doesn't require superposition, making it robust to hinge motions.
Quick start::
from synth_pdb.benchmark import run_benchmark
results = run_benchmark(n_structures=10, lengths=[20, 30])
print(results.summary())
results.to_csv("benchmark_results.csv")
Or with the CLI::
python scripts/run_benchmark.py --predictor esmfold --n-structures 20
Supported predictors
- ESMFold (default): Meta's sequence-to-structure model via HuggingFace
transformerslibrary. No API key required. ~700 MB model download on first use.pip install transformers accelerate - Custom callable: Pass any
predictor_fn(sequence: str) -> pdb_strfor full flexibility with any model (ColabFold, OmegaFold, RoseTTAFold, etc.)
Metrics computed
For each generated structure:
tm_scoreTM-score between ground-truth and predicted Calpha tracegdt_tsGDT-TS scorelddtMean lDDT across all residuesrmsdCalpha-RMSD after Kabsch superposition (A)shift_rmsdChemical shift RMSD (ppm) - compares shifts predicted from ground-truth structure vs. from the AI-predicted structuregnn_score_refGNN pLDDT of the ground-truth structuregnn_score_predGNN pLDDT of the AI-predicted structure
Classes
BenchmarkResults
dataclass
Aggregated results for a complete benchmarking run.
Attributes
results : list[StructureResult] Per-structure results. predictor : str Name of the predictor used. n_structures : int Number of structures attempted. n_success : int Structures successfully predicted.
Source code in synth_pdb/benchmark.py
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | |
Functions
summary()
Return a formatted summary of the benchmark results.
Source code in synth_pdb/benchmark.py
to_csv(path)
Write full per-structure results to a CSV file.
Source code in synth_pdb/benchmark.py
to_dataframe()
Return results as a pandas DataFrame (requires pandas).
Source code in synth_pdb/benchmark.py
StructureResult
dataclass
Quality metrics for a single (ground-truth, predicted) structure pair.
This container tracks the "Delta" between what synth-pdb generated and what an AI model (like ESMFold) predicted. It captures both global geometry (TM-score) and local physics (NMR Chemical Shift RMSD).
Attributes
sequence : str Amino acid sequence (single-letter). length : int Number of residues. conformation : str Ground-truth conformation type (e.g. "alpha"). tm_score : float TM-score in [0, 1]. High values indicate correct fold. gdt_ts : float GDT-TS in [0, 1]. Captures global Calpha trace fidelity. lddt_mean : float Mean lDDT in [0, 1]. Captures local geometric accuracy. rmsd : float Calpha-RMSD in A after superposition. shift_rmsd : float NMR Chemical shift RMSD in ppm. A "Physical Audit": measures if the AI-predicted structure "sounds" like the ground truth structure under a virtual spectrometer. gnn_score_ref : float GNN quality score for the ground-truth structure. gnn_score_pred : float GNN quality score for the predicted structure. predictor_time_s: float Wall-clock inference time for this structure (s). error : str Non-empty if prediction failed (e.g. CUDA OOM).
Source code in synth_pdb/benchmark.py
Functions
run_benchmark(n_structures=20, lengths=None, conformations=None, predictor='esmfold', *, compute_shifts=True, compute_gnn=True, random_state=42)
Run the synth-pdb vs. AI structure prediction benchmark.
Generates n_structures synthetic protein structures of varying length
and secondary structure content, then asks the specified predictor to
reconstruct each structure from sequence alone. The prediction is
evaluated against the ground-truth on TM-score, GDT-TS, lDDT, Calpha-RMSD,
and (optionally) NMR chemical shift RMSD.
BENCHMARK LIFECYCLE
For each structure in the trial: 1. Generate: Create a ground-truth PDB with specific geometry. 2. Extract: Convert the 3D structure to its 1D amino acid sequence. 3. Predict: Blindly ask the AI model to predict the 3D structure. 4. Evaluate: Compute TM-score, GDT-TS, and lDDT between (1) and (3). 5. Audit: (Optional) Compare predicted NMR chemical shifts.
This "Circular Validation" ensures the AI model is learning the true underlying physics of protein folding, not just memorizing the PDB.
Parameters
n_structures : int
Total number of test structures to generate.
lengths : list[int], optional
Pool of chain lengths to sample from (default: [20, 30, 50]).
Lengths are sampled uniformly.
conformations : list[str], optional
Pool of conformations to sample from (default: ["alpha", "beta"]).
predictor : str or callable
"esmfold" to use the bundled ESMFold backend, or any callable
predictor_fn(sequence: str) -> pdb_str.
compute_shifts : bool
Whether to compute NMR chemical shift RMSD (requires synth_pdb
chemical_shifts module). Default True.
compute_gnn : bool
Whether to score both structures with the GNN quality scorer.
Default True.
random_state : int
RNG seed for reproducible structure generation.
Returns
BenchmarkResults
Call .summary() for a formatted text report or .to_csv() to
export full results.
Examples
from synth_pdb.benchmark import run_benchmark results = run_benchmark(n_structures=10) print(results.summary())
Source code in synth_pdb/benchmark.py
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 | |
benchmark_metrics
synth_pdb.benchmark_metrics. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pure-numpy structural biology evaluation metrics for the AlphaFold benchmarking suite.
All functions operate on numpy arrays and have no optional dependencies, making them trivially unit-testable and usable in headless environments.
Metrics implemented
TM-score Template Modelling score in [0, 1]. A TM-score > 0.5 indicates that two proteins share the same global topology regardless of RMSD. It is the primary metric in CASP (Critical Assessment of Structure Prediction). Reference: Zhang & Skolnick (2004) Proteins 57, 702-710.
lDDT Local Distance Difference Test in [0, 1]. Evaluates per-residue local geometry without superposition. Used by AlphaFold to report per-residue confidence (pLDDT) during training. Reference: Mariani et al. (2013) Bioinformatics 29, 2722-2728.
GDT-TS Global Distance Test - Total Score. CASP standard metric computed as the average fraction of Calpha atoms within 1, 2, 4, 8 A of the reference. Reference: Zemla (2003) Nucleic Acids Research 31, 3370-3374.
shift_rmsd NMR Chemical Shift Root-Mean-Square Deviation. Measures the agreement between predicted and reference 1H/13C/15N chemical shifts.
Functions
tm_score(ca_pred, ca_ref, *, normalise_by=None)
Compute TM-score between a predicted and reference Calpha trace.
TM-score is defined as::
TM = (1/L_ref) Sum_i 1 / (1 + (d_i / d0)^2)
where d_i is the distance between the i-th pair of aligned Calpha atoms
after optimal superposition, L_ref is the reference chain length, and
d0 is a length-normalising constant::
d0 = 1.24 x (L_ref - 15)^(1/3) - 1.8 (for L_ref >= 22)
d0 = 0.5 (for L_ref < 22)
Parameters
ca_pred : np.ndarray [N, 3] Predicted Calpha coordinates. ca_ref : np.ndarray [N, 3] Reference Calpha coordinates. normalise_by : int, optional If provided, normalise by this length rather than len(ca_ref). Useful when comparing structures of different lengths.
Returns
float TM-score in (0, 1]. Two random structures ~ 0.17; same fold >= 0.5.
Source code in synth_pdb/benchmark_metrics.py
lddt(ca_pred, ca_ref, *, inclusion_radius=15.0, thresholds=(0.5, 1.0, 2.0, 4.0))
Compute per-residue lDDT scores.
lDDT measures how well the local distance geometry of a predicted structure agrees with the reference, without requiring superposition.
For each residue i, we look at all pairs (i, j) where j is within
inclusion_radius A of i in the reference structure. We then count
what fraction of those reference distances are preserved in the predicted
structure within each threshold.
Per-residue lDDT::
lDDT_i = (1 / |T|) Sum_t (fraction of distances within threshold t)
where |T| = len(thresholds) = 4.
Parameters
ca_pred : np.ndarray [N, 3] Predicted Calpha coordinates. ca_ref : np.ndarray [N, 3] Reference Calpha coordinates. inclusion_radius : float Only pairs within this radius in the reference contribute (default 15 A). thresholds : tuple of float Distance preservation thresholds (A).
Returns
np.ndarray [N] Per-residue lDDT in [0, 1]. Global lDDT = mean().
Source code in synth_pdb/benchmark_metrics.py
gdt_ts(ca_pred, ca_ref, *, cutoffs=(1.0, 2.0, 4.0, 8.0))
Compute GDT-TS (Global Distance Test - Total Score).
GDT-TS is the average fraction of Calpha atoms placed within {1, 2, 4, 8} A of the reference after optimal superposition. It is the primary ranking metric used in CASP competitions.
Parameters
ca_pred : np.ndarray [N, 3] Predicted Calpha coordinates. ca_ref : np.ndarray [N, 3] Reference Calpha coordinates. cutoffs : tuple of float Distance cutoffs in A (default CASP standard).
Returns
float GDT-TS in [0, 1]. Perfect prediction = 1.0.
Source code in synth_pdb/benchmark_metrics.py
superpose_kabsch(mobile, reference)
Optimally superpose mobile onto reference using the Kabsch algorithm.
The Kabsch algorithm finds the rotation matrix R that minimises RMSD between two sets of paired points by SVD-decomposing their cross-covariance matrix.
-- Algorithm ------------------------------------------------------------ 1. Translate both sets to their centroids. 2. Compute cross-covariance H = mobile_centred.T @ ref_centred 3. SVD: H = U Sum V^T 4. R = V diag(1, 1, det(V U^T)) U^T <- det term fixes reflections 5. Apply R to mobile.
Parameters
mobile : np.ndarray [N, 3] Coordinates to rotate. reference : np.ndarray [N, 3] Target coordinates.
Returns
rotated : np.ndarray [N, 3] Mobile after optimal superposition. rmsd : float Calpha-RMSD after superposition (A).
Source code in synth_pdb/benchmark_metrics.py
shift_rmsd(pred_shifts, ref_shifts, *, nucleus_weights=None)
Compute weighted chemical shift RMSD between predicted and reference shifts.
Parameters
pred_shifts, ref_shifts : dict mapping nucleus -> np.ndarray [N] Nucleus keys are typically "H", "C", "N" (matching BMRB convention). Arrays must be the same length (one entry per residue). nucleus_weights : dict, optional Per-nucleus weighting (default: H=1.0, C=0.25, N=0.1, matching the CamSol / SPARTA+ convention for weighted shift RMSD).
Returns
float Weighted shift RMSD in ppm. Lower is better.
Examples
rmsd = shift_rmsd( ... {"H": np.array([8.1, 8.2, 8.3])}, ... {"H": np.array([8.0, 8.1, 8.4])}, ... ) print(f"{rmsd:.4f} ppm") 0.1155 ppm
Source code in synth_pdb/benchmark_metrics.py
extract_ca_coords(pdb_content)
Extract Calpha coordinates from a PDB string in residue order.
A lightweight parser - uses only the standard library, no biotite.
Parameters
pdb_content : str Raw PDB-format string.
Returns
np.ndarray [N, 3] Calpha coordinates in A.
Raises
ValueError If fewer than 2 Calpha atoms are found.