API examples
Validate a protein structure with MolProbity
Run MolProbity on ubiquitin from Python, then save the outlier list and full reports with checksums.
Download Python example · Recorded result · Example code license
Ubiquitin's 1987 crystal structure, 1UBQ, is a standard test case for structural biology software. Run it through MolProbity and the backbone comes back flawless: every residue sits in a favored region of the Ramachandran plot. The side chains tell a different story. Six are rotamer outliers, and three of those are Leu71, Arg72 and Leu73, in the flexible tail ubiquitin uses to attach to other proteins.
That split between a clean backbone and a strained tail is what a validation report is for, and you only see it if you keep the per-residue files, not just the headline score. This example runs MolProbity from Python with the ProteinIQ SDK, quotes the job before anything is charged, and saves the summary, the outlier list and the full reports with checksums.
The result
The public example job validated 1UBQ on 18 November 2026 in 10 seconds of compute. These are its headline values:
| Metric | Value |
|---|---|
| MolProbity score | 2.26 |
| Clashscore | 10.56 per 1,000 atoms |
| Ramachandran favored | 100% |
| Ramachandran outliers | 0% |
| Rotamer outliers | 8.8% |
| Cβ deviations | 1 |
| Bond length RMSD | 0.0203 Å |
| Bond angle RMSD | 2.98° |
The MolProbity score is scaled to read like a resolution, so 2.26 says this 1.8 Å structure has the geometry of a typical structure at about 2.3 Å. The score combines clashscore, rotamer outliers and Ramachandran outliers. With a perfect backbone, the clashes and the strained side chains account for all of it, which is common in models refined before all-atom contact analysis and modern rotamer libraries existed.
Set up
You need Python 3.10 or later and version 0.2.0 or later of the ProteinIQ SDK; the SDK page covers installation. Create an API key with the jobs:write and jobs:read scopes for a workspace with API access, and set it as PROTEINIQ_API_KEY in your environment rather than in the script.
Download structure_analysis.py from the link at the top of this page and fetch the structure into the same folder:
curl -O https://files.rcsb.org/download/1UBQ.pdbValidate the file as deposited. Running it through PDBFixer first would add hydrogens and rebuild missing atoms, and the report would then describe your repairs rather than the original model.
Building the request
MolProbity takes a single structure in its protein slot and needs no settings. The file contents go inline in the request, so nothing is uploaded before the quote. The script rejects anything that is not a PDB or mmCIF file before it reaches the API.
def structure_input(file: Path, slot: str) -> dict:
format_name = file.suffix.lower().lstrip(".")
if format_name not in {"pdb", "ent", "cif", "mmcif"}:
raise ValueError("Use a PDB or mmCIF structure file.")
return {"id": slot, "slotId": slot, "kind": "protein", "format": format_name,
"content": file.read_text(encoding="utf-8"), "label": file.name,
"source": {"type": "text"}}def make_request(tool: str, structure: Path, reference: Path | None) -> dict:
if tool == "molprobity":
if reference is not None:
raise ValueError("MolProbity takes one structure.")
inputs = [structure_input(structure, "protein")]
settings = {}
else:
if reference is None:
raise ValueError("USAlign needs --reference as well as --structure.")
inputs = [structure_input(structure, "structure1"), structure_input(reference, "structure2")]
if any(item["format"] == "mmcif" for item in inputs):
raise ValueError("For USAlign, give mmCIF files the .cif extension.")
settings = {"alignment_mode": "monomer", "ter_mode": "2", "mol_type": "auto",
"het_mode": "0", "fast_mode": False}
return {"tool": tool, "input": {"inputs": inputs}, "settings": settings}Quoting before you spend
The quote endpoint prices a request without starting compute. The script prints it and stops if the quote has blocking errors, is billed by runtime rather than at a fixed price, or exceeds the credit limit you pass. A quote for a metered job only bounds admission, not the final bill, so this example leaves those jobs alone.
def check_quote(quote, ceiling: int | None) -> None:
if quote.blocking_errors:
raise ValueError(f"Quote rejected: {quote.blocking_errors}")
if quote.billing.get("mode") != "fixed":
raise ValueError("This example only submits fixed-price jobs; inspect metered billing separately.")
if ceiling is not None and quote.estimated_credits > ceiling:
raise ValueError(f"Quote {quote.estimated_credits} exceeds your {ceiling}-credit limit.")Run the script without --submit to see the quote. No job starts.
python structure_analysis.py --tool molprobity --structure 1UBQ.pdb --output ubiquitin-validationSubmitting exactly once
If the connection fails after the request leaves but before the response arrives, you cannot tell whether a job started. The script writes the request and a fresh idempotency key to request.json before it calls the API. A retry sends the same key, and the server returns the job it already created instead of starting a second one.
def run(args: argparse.Namespace, client: ProteinIQ) -> None:
output = args.output
state_path = output / "request.json"
workspace_id = client.account.get().workspace.get("id")
if not workspace_id:
raise ValueError("Account response did not identify the workspace.")
if state_path.exists():
if not args.resume:
raise ValueError("This output directory already contains a request. Use --resume or a new directory.")
state = json.loads(state_path.read_text(encoding="utf-8"))
if state["base_url"] != client.base_url or state["workspace_id"] != workspace_id:
raise ValueError("Resume with the same ProteinIQ server and workspace as the original request.")
if state.get("job_id"):
collect(client, state, output, args.timeout)
return
if not args.submit:
raise ValueError("Retrying an unconfirmed submission also requires --submit.")
request, ceiling = state["request"], state["max_credits"]
else:
if args.resume:
raise ValueError("No saved request to resume.")
if args.tool is None or args.structure is None:
raise ValueError("Supply --tool and --structure for a new analysis.")
request = make_request(args.tool, args.structure, args.reference)
ceiling = args.max_credits
state = {"request": request, "max_credits": ceiling, "idempotency_key": str(uuid.uuid4()),
"base_url": client.base_url, "workspace_id": workspace_id}
quote = client.jobs.quote(**request)
print(json.dumps(quote.raw, indent=2))
check_quote(quote, ceiling)
if not args.submit:
print("Quote only. No scientific job submitted.")
return
if ceiling is None or ceiling < 1:
raise ValueError("Submission requires a positive integer --max-credits.")
# Persist the exact request and key BEFORE a network call can start a job.
output.mkdir(parents=True, exist_ok=True)
save_json(state_path, state)
job = client.jobs.submit(**request, name=f"Cookbook: {request['tool']}",
idempotency_key=state["idempotency_key"], max_quoted_credits=ceiling)
state["job_id"] = job.id
save_json(state_path, state)
print(f"Job: {job.id}. Resume with --output {output} --resume")
collect(client, state, output, args.timeout)When the quote looks right, pass --submit and replace YOUR_LIMIT with the number of credits you approve, usually the quoted amount. The server enforces the same ceiling through max_quoted_credits, so a price change between quote and submission cannot charge you more.
python structure_analysis.py --tool molprobity --structure 1UBQ.pdb --output ubiquitin-validation --submit --max-credits YOUR_LIMITSaving the reports
When the job completes, collect writes the structured result to results.json and downloads every returned file. Names from the server are sanitized and numbered so they cannot write outside the output folder, and each file's SHA-256 goes into files.json as it lands. On a rerun, files whose checksums still match are kept; a file that changed stops the script so you can look at it.
def collect(client: ProteinIQ, state: dict, output: Path, timeout: float) -> None:
job = client.jobs.wait(state["job_id"], timeout=timeout)
if job.status != "COMPLETED":
raise RuntimeError(f"Job {job.id}: {job.status}: {job.error}")
result = client.results.wait(job.id, timeout=120)
save_json(output / "results.json", result.results)
manifest_path = output / "files.json"
manifest = json.loads(manifest_path.read_text()) if manifest_path.exists() else {}
for index, file in enumerate(result.files, 1):
if not file.url:
raise RuntimeError(f"No download URL for output {file.name}; rerun to refresh links.")
name = re.sub(r"[^a-zA-Z0-9._-]", "_", file.name or "result-file")[:160]
destination = output / f"{index:02d}-{name}"
if destination.exists():
digest = hashlib.sha256(destination.read_bytes()).hexdigest()
if manifest.get(destination.name, {}).get("sha256") != digest:
raise RuntimeError(f"Existing file has no matching checksum: {destination}")
else:
client.download_url(file.url, destination)
digest = hashlib.sha256(destination.read_bytes()).hexdigest()
manifest[destination.name] = {"source_name": file.name, "sha256": digest}
save_json(manifest_path, manifest)
print(destination)
print(f"Completed job: {job.id}. Structured result: {output / 'results.json'}")For 1UBQ, MolProbity returns five files: a summary CSV, an outliers CSV, the full text report, the raw Probe contact list, which at 2.6 MB is the largest, and a run log. The outliers file is the one to open first:
category,chain,residue_number,residue_name,atom,target,detail,score,unit
Rotamer,A,13,ILE,,,OUTLIER,0.0,
Rotamer,A,15,LEU,,,OUTLIER,0.017,
Rotamer,A,39,ASP,,,OUTLIER,0.0,
Rotamer,A,71,LEU,,,OUTLIER,0.038,
Rotamer,A,72,ARG,,,OUTLIER,0.0,
Rotamer,A,73,LEU,,,OUTLIER,0.145,
Clash,A,72,ARG,HG2,A 72 ARG O,,1.038,A overlap
Clash,A,10,GLY,HA2,A 107 HOH O,,0.719,A overlap
Clash,A,42,ARG,HE,A 49 GLN NE2,,0.601,A overlap
Clash,A,42,ARG,HE,A 49 GLN HE21,,0.521,A overlap
Clash,A,51,GLU,CG,A 125 HOH O,,0.501,A overlap
Clash,A,51,GLU,HG3,A 125 HOH O,,0.497,A overlap
Clash,A,48,LYS,HE3,A 100 HOH O,,0.494,A overlap
Clash,A,23,ILE,HB,A 52 ASP HA,,0.469,A overlap
Clash,A,72,ARG,CG,A 72 ARG O,,0.465,A overlap
Clash,A,71,LEU,HA,A 71 LEU HD12,,0.446,A overlap
Clash,A,37,PRO,HA,A 38 PRO HD3,,0.421,A overlap
Clash,A,39,ASP,HB3,A 80 HOH O,,0.411,A overlap
Clash,A,48,LYS,CE,A 100 HOH O,,0.409,A overlap
C-beta,A,33,LYS,,,,0.322,AArg72 appears three times: its side chain is a rotamer outlier, and both its CG atom and the hydrogen HG2 overlap its own backbone oxygen, the hydrogen by 1.04 Å, the worst contact in the structure. Six of the 13 clashes are with crystallographic waters rather than other protein atoms. Neither pattern is visible in the summary numbers.
Resuming an interrupted run
Keep the output folder. If the script times out, loses its connection or is stopped, run it again with --resume:
python structure_analysis.py --output ubiquitin-validation --resumeIf the job ID was saved, the script waits for that job and downloads anything still missing. If the submission response never arrived, add --submit to retry with the saved request and key. A timeout only stops the local wait; the hosted job keeps running until it finishes or you cancel it through the Jobs API. Use a new output folder for a different structure.
Going further
MolProbity measures geometry: steric overlaps, backbone and side-chain conformations, and deviations from ideal bonds. A good score does not show that a model agrees with its experimental data or that it is biologically right, and a poor one does not by itself make a structure unusable. Read the outliers in context first. A strained residue in a flexible tail matters less than one in an active site.
The other public examples show different cases: an inhibitor-bound HIV-1 protease with 45 outliers, and a cryo-EM spike trimer where CaBLAM's backbone checks, built for lower-resolution models, complement the Ramachandran plot. The MolProbity paper defines every metric.
The same script also compares two structures with USAlign; only the request differs.
Complete script
"""ProteinIQ cookbook, Python SDK 0.2.0+. MIT licensed example code.
Quote by default. --submit and --max-credits explicitly authorize one fixed-price
job. Keep the output directory to resume; use a new directory for changed work.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import tempfile
import uuid
from proteiniq import ProteinIQ
from proteiniq.errors import ProteinIQError
def save_json(path: Path, value: object) -> None:
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent, delete=False) as handle:
temporary = Path(handle.name)
json.dump(value, handle, indent=2)
handle.write("\n")
try:
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
def structure_input(file: Path, slot: str) -> dict:
format_name = file.suffix.lower().lstrip(".")
if format_name not in {"pdb", "ent", "cif", "mmcif"}:
raise ValueError("Use a PDB or mmCIF structure file.")
return {"id": slot, "slotId": slot, "kind": "protein", "format": format_name,
"content": file.read_text(encoding="utf-8"), "label": file.name,
"source": {"type": "text"}}
def make_request(tool: str, structure: Path, reference: Path | None) -> dict:
if tool == "molprobity":
if reference is not None:
raise ValueError("MolProbity takes one structure.")
inputs = [structure_input(structure, "protein")]
settings = {}
else:
if reference is None:
raise ValueError("USAlign needs --reference as well as --structure.")
inputs = [structure_input(structure, "structure1"), structure_input(reference, "structure2")]
if any(item["format"] == "mmcif" for item in inputs):
raise ValueError("For USAlign, give mmCIF files the .cif extension.")
settings = {"alignment_mode": "monomer", "ter_mode": "2", "mol_type": "auto",
"het_mode": "0", "fast_mode": False}
return {"tool": tool, "input": {"inputs": inputs}, "settings": settings}
def check_quote(quote, ceiling: int | None) -> None:
if quote.blocking_errors:
raise ValueError(f"Quote rejected: {quote.blocking_errors}")
if quote.billing.get("mode") != "fixed":
raise ValueError("This example only submits fixed-price jobs; inspect metered billing separately.")
if ceiling is not None and quote.estimated_credits > ceiling:
raise ValueError(f"Quote {quote.estimated_credits} exceeds your {ceiling}-credit limit.")
def collect(client: ProteinIQ, state: dict, output: Path, timeout: float) -> None:
job = client.jobs.wait(state["job_id"], timeout=timeout)
if job.status != "COMPLETED":
raise RuntimeError(f"Job {job.id}: {job.status}: {job.error}")
result = client.results.wait(job.id, timeout=120)
save_json(output / "results.json", result.results)
manifest_path = output / "files.json"
manifest = json.loads(manifest_path.read_text()) if manifest_path.exists() else {}
for index, file in enumerate(result.files, 1):
if not file.url:
raise RuntimeError(f"No download URL for output {file.name}; rerun to refresh links.")
name = re.sub(r"[^a-zA-Z0-9._-]", "_", file.name or "result-file")[:160]
destination = output / f"{index:02d}-{name}"
if destination.exists():
digest = hashlib.sha256(destination.read_bytes()).hexdigest()
if manifest.get(destination.name, {}).get("sha256") != digest:
raise RuntimeError(f"Existing file has no matching checksum: {destination}")
else:
client.download_url(file.url, destination)
digest = hashlib.sha256(destination.read_bytes()).hexdigest()
manifest[destination.name] = {"source_name": file.name, "sha256": digest}
save_json(manifest_path, manifest)
print(destination)
print(f"Completed job: {job.id}. Structured result: {output / 'results.json'}")
def run(args: argparse.Namespace, client: ProteinIQ) -> None:
output = args.output
state_path = output / "request.json"
workspace_id = client.account.get().workspace.get("id")
if not workspace_id:
raise ValueError("Account response did not identify the workspace.")
if state_path.exists():
if not args.resume:
raise ValueError("This output directory already contains a request. Use --resume or a new directory.")
state = json.loads(state_path.read_text(encoding="utf-8"))
if state["base_url"] != client.base_url or state["workspace_id"] != workspace_id:
raise ValueError("Resume with the same ProteinIQ server and workspace as the original request.")
if state.get("job_id"):
collect(client, state, output, args.timeout)
return
if not args.submit:
raise ValueError("Retrying an unconfirmed submission also requires --submit.")
request, ceiling = state["request"], state["max_credits"]
else:
if args.resume:
raise ValueError("No saved request to resume.")
if args.tool is None or args.structure is None:
raise ValueError("Supply --tool and --structure for a new analysis.")
request = make_request(args.tool, args.structure, args.reference)
ceiling = args.max_credits
state = {"request": request, "max_credits": ceiling, "idempotency_key": str(uuid.uuid4()),
"base_url": client.base_url, "workspace_id": workspace_id}
quote = client.jobs.quote(**request)
print(json.dumps(quote.raw, indent=2))
check_quote(quote, ceiling)
if not args.submit:
print("Quote only. No scientific job submitted.")
return
if ceiling is None or ceiling < 1:
raise ValueError("Submission requires a positive integer --max-credits.")
# Persist the exact request and key BEFORE a network call can start a job.
output.mkdir(parents=True, exist_ok=True)
save_json(state_path, state)
job = client.jobs.submit(**request, name=f"Cookbook: {request['tool']}",
idempotency_key=state["idempotency_key"], max_quoted_credits=ceiling)
state["job_id"] = job.id
save_json(state_path, state)
print(f"Job: {job.id}. Resume with --output {output} --resume")
collect(client, state, output, args.timeout)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--tool", choices=["molprobity", "usalign"])
parser.add_argument("--structure", type=Path)
parser.add_argument("--reference", type=Path)
parser.add_argument("--output", type=Path, default=Path("outputs"))
parser.add_argument("--submit", action="store_true")
parser.add_argument("--max-credits", type=int)
parser.add_argument("--resume", action="store_true")
parser.add_argument("--timeout", type=float, default=3600)
args = parser.parse_args()
# An exclusive lock also prevents two local processes overwriting recovery state.
args.output.mkdir(parents=True, exist_ok=True)
lock = args.output / ".cookbook.lock"
descriptor = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
try:
with ProteinIQ() as client:
run(args, client)
except (ProteinIQError, ValueError, RuntimeError, TimeoutError) as error:
parser.exit(1, f"{error}\nKeep this directory and resume the same request. A timeout does not cancel compute.\n")
finally:
os.close(descriptor)
lock.unlink(missing_ok=True)
if __name__ == "__main__":
main()How this example was checked
The script is tested offline against simulated API responses. The results shown come from the public MolProbity example job of 18 November 2026, not from a run of this script.