API examples

Compare two protein structures with USAlign

Superpose myoglobin onto hemoglobin α from Python, then keep both TM-scores, the superposed model and the native report.

Download Python example · Example code license

Sperm whale myoglobin and the α chain of human hemoglobin share only 27% of their residues. That puts them inside the twilight zone of sequence similarity, where an alignment alone cannot tell distant relatives from chance. Their structures settle it. Superpose myoglobin (1MBN) onto hemoglobin α (1A3N, chain A) with USAlign, and all 141 residues of the shorter chain line up within 1.56 Å, for a TM-score of 0.90.

This example runs that comparison from Python with the ProteinIQ SDK. The script quotes the job before anything is charged, submits it once with a credit limit you choose, and saves the metric table and every alignment file with a checksum. If the connection drops halfway, you rerun one command and pick up the same job instead of paying for a second one.

The result

The public example job ran this same monomer alignment on 11 October 2026 and finished in 4 seconds of compute. Running the script on the same two files should give you these values:

MetricValue
TM-score, normalized by myoglobin (153 residues)0.836
TM-score, normalized by hemoglobin α (141 residues)0.900
Aligned residues141
RMSD over aligned residues1.56 Å
Sequence identity over aligned residues27%

There are two TM-scores because the score is divided by the length of one structure, and these chains differ by 12 residues. By the shorter hemoglobin chain, almost every residue has a close partner: 0.90. By myoglobin, its extra residues count against it: 0.84. Both are far above 0.5, the level above which two proteins usually share a fold. The TM-score and RMSD comparison explains why the length normalization matters more than it looks.

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, then fetch the two structures from RCSB into the same folder:

Bash
curl -O https://files.rcsb.org/download/1MBN.pdb
curl -O https://files.rcsb.org/download/1A3N.pdb

Building the request

USAlign takes two structures in named slots. The first, structure1, is the mobile structure that gets superimposed; the second, structure2, is the reference it lands on. Each input carries the file contents inline, so nothing has to be uploaded before the quote.

Python
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"}}

The settings are written out in full rather than left to defaults, so the request records exactly what was run. Monomer mode aligns one chain against one chain. ter_mode: "2" reads only the first chain of each file, which picks chain A out of the 1A3N tetramer, and het_mode: "0" ignores the heme groups so that only protein residues are aligned. Fast mode stays off; the full search takes seconds for chains this size.

Python
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 the quote and refuses to go further if it has blocking errors, is billed by runtime rather than at a fixed price, or exceeds the limit you set. A quote for a metered job only bounds admission, not the final bill, so this example leaves those jobs alone.

Python
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.

Bash
python structure_analysis.py --tool usalign --structure 1MBN.pdb --reference 1A3N.pdb --output globin-comparison

Submitting exactly once

The hard part of submitting a job over a network is the moment after the request leaves and before the response arrives. If the connection fails there, you cannot tell whether a job started. The script handles this by writing 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 another.

Python
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 your quote and the submission cannot charge you more.

Bash
python structure_analysis.py --tool usalign --structure 1MBN.pdb --reference 1A3N.pdb --output globin-comparison --submit --max-credits YOUR_LIMIT

Saving the results

Once the job completes, collect writes the structured result to results.json and downloads each returned file. File names from the server are sanitized and numbered, so a strange name cannot write outside the output folder, and every file's SHA-256 goes into files.json as it lands. On a rerun, a file whose checksum still matches is kept; one that changed stops the script so you can look at it.

Python
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 this pair, the folder ends up holding the superposed model aligned.pdb, PyMOL scripts that show the superposition, the native US-align report and a provenance record. The report is the clearest view of the alignment:

Text
Length of Structure_1: 153 residues
Length of Structure_2: 141 residues

Aligned length= 141, RMSD=   1.56, Seq_ID=n_identical/n_aligned= 0.270
TM-score= 0.83558 (normalized by length of Structure_1: L=153, d0=4.61)
TM-score= 0.89998 (normalized by length of Structure_2: L=141, d0=4.42)

Below those lines, the report prints the residue-by-residue alignment. Nearly every position is marked as within 5 Å of its partner. The 12 unmatched myoglobin residues fall in two places: six where hemoglobin α lacks the D helix that myoglobin has, and six at myoglobin's longer C-terminal end.

Resuming an interrupted run

Keep the output folder. If the script times out, loses its connection or is stopped, run it again with --resume:

Bash
python structure_analysis.py --output globin-comparison --resume

If 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 whenever you change the inputs or settings.

Going further

RMSD here describes the 141 aligned residues, not the whole of myoglobin, so always read it next to the aligned length. Two structures can have a small RMSD over a short, well-fitting core and still differ everywhere else.

Monomer mode is the right choice for single chains. For complexes, the GCN4 leucine zipper example uses oligomer mode to match a predicted dimer against its crystal structure chain by chain. For proteins that move between states, the adenylate kinase example uses flexible mode to align the open and closed forms across their hinge. The structure alignment use case compares these approaches, and the US-align paper defines the scores.

The same script also runs MolProbity validation; only the request differs.

Complete script

Python
"""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 USAlign example job, which ran the same alignment on the same files; the script itself has not yet been run against the live API.