API examples

Score a complex model with DockQ

Compare an AlphaFold2 model of the GCN4 leucine zipper dimer with its crystal structure in Python, then break the DockQ score into fnat, iRMSD and LRMSD.

Download Python example · Shared job runner · Example code license

The GCN4 leucine zipper is about as simple as a protein complex gets: two identical 33-residue helices from a yeast transcription factor, wound around each other into a parallel coiled coil. Its crystal structure, 2ZTA, was solved at 1.8 Å by O'Shea, Klemm, Kim and Alber in 1991. AlphaFold2 predicts the dimer from the sequence alone, with no alignment, and gives the interface an ipTM of 0.74. That is a middling score, the kind that leaves you unsure whether the two helices pack the right way.

A reference structure settles it. DockQ measures how far a model interface is from the same interface in a trusted structure, and against 2ZTA this model scores 0.935, well inside the High quality class. This example runs that comparison from Python with the ProteinIQ SDK, then takes the score apart into the three measurements it averages, so you can see which one costs the model its last 0.065.

The result

The public example job scored the AlphaFold2 model against 2ZTA with default settings on 11 October 2026, in 3 seconds of compute. Run on the same two files, the script prints:

Text
DockQ 2.1.3, chain mapping AB:AB (model:native), GlobalDockQ 0.935
Interface A:B: DockQ 0.935, High; CAPRI criteria give High
  fnat      0.979    term 0.979  46 of 47 native contacts
  iRMSD      0.62 Å  term 0.854
  LRMSD      1.40 Å  term 0.974  chain A placed with chain B superposed
  fnonnat   0.061               3 of 49 model contacts not in the native
  clashes       1

The model keeps 46 of the 47 residue contacts that hold the crystal dimer together, and the backbone of the interface sits within 0.62 Å of the crystal after superposition. Those numbers describe an interface that is right at nearly atomic detail. The DockQ guide explains the scale; anything from 0.80 up is High, the best of the four classes that the CAPRI docking assessment uses.

The term column shows where the missing 0.065 goes. fnat and LRMSD each contribute almost their full share, while the iRMSD term is 0.854. DockQ scales iRMSD so that 1.5 Å earns half the term, which makes it the strictest of the three: an interface 0.62 Å off is excellent, and it still gives up about 0.15 of a possible 1.

The ipTM of 0.74 and the DockQ of 0.935 are not in conflict. ipTM is the model's own estimate of its interface accuracy, made without seeing the answer; DockQ measures the actual error against an experimental structure. The ipTM and pTM guide covers what the predicted score does and does not promise.

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 score_complex.py and proteiniq_job.py from the links at the top of this page into one folder. The first holds everything specific to DockQ; the second is the job runner that every Python example on these pages shares. Fetch the crystal structure from RCSB into the same folder:

Bash
curl -O https://files.rcsb.org/download/2ZTA.pdb

The model is a prediction, so it has no RCSB entry. It is the prediction_rank01.pdb file returned by the AlphaFold2 example job of 19 July 2026, which folded two copies of the GCN4 sequence RMKQLEDKVEELLSKNYHLENEVARLKKLVGER with the multimer model in single-sequence mode. Download that file from the job's results, or run AlphaFold2 on the same two chains to make your own model; a new run can differ slightly from the one scored here.

Building the request

DockQ takes two structures in named slots: model for the predicted or docked complex, and native for the reference. Each is read from disk and sent inline. An interface needs two chains on each side, so the script counts the chain IDs in each PDB file first and refuses a single chain before anything is priced. mmCIF files skip that check and are left for DockQ to read.

Python
def make_request(model: Path, native: Path, chain_mapping: str = "") -> dict:
    if chain_mapping and (chain_mapping.count(":") != 1 or "," in chain_mapping):
        raise ValueError("Write the chain mapping as MODEL:NATIVE, one character per chain, e.g. AB:AB.")
    inputs = []
    for path, slot in ((model, "model"), (native, "native")):
        structure = proteiniq_job.file_input(path, slot, "protein", STRUCTURE_FORMATS)
        # An interface needs two chains. mmCIF chain IDs are left for DockQ to read.
        if structure["format"] != "cif" and len(pdb_chains(path)) < 2:
            raise ValueError(f"{path.name} has fewer than two chains, so it has no interface to score.")
        inputs.append(structure)
    settings = {"chain_mapping": chain_mapping, "small_molecule": False, "capri_peptide": False,
                "no_align": False, "allowed_mismatches": 0}
    return {"tool": "dockq", "input": {"inputs": inputs}, "settings": settings}

The settings are the public job's, written out so that request.json records exactly what ran. An empty chain_mapping lets DockQ work out which model chain corresponds to which reference chain.

allowed_mismatches stays at 0 because the sequences are identical; DockQ handles missing residues as alignment gaps, which matters here because 2ZTA has no coordinates for the last two residues of each chain. Both chains are scored over the 31 residues the two structures share. Small molecule and CAPRI peptide modes are for other kinds of interfaces and stay off.

Quoting, submitting and resuming

proteiniq_job.py handles the parts of running a job that are the same for every tool. It prices the request before anything is charged and stops if the quote has blocking errors, is billed by runtime, or exceeds your limit. It writes the request and an idempotency key to disk before submitting, so a retry after a dropped connection returns the job that already started instead of paying for a second one. Then it waits, saves the structured result to results.json and downloads each file with its SHA-256.

Python
def run(args: argparse.Namespace, client: ProteinIQ, build_request: Callable[[], dict],
        metered: bool = False) -> dict | None:
    """Quote, then submit at most one job and collect it. Returns the result once complete.

    With metered=True a runtime-billed quote is accepted, and --max-credits is sent
    with the quote and the submission as the spending cap (billing.max_reserved_credits).
    """
    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"):
            return collect(client, state, output, args.timeout)
        if not args.submit:
            raise ValueError("Retrying an unconfirmed submission also requires --submit.")
        if state.get("submission"):
            # Resend exactly what the first attempt sent, so the idempotency key
            # returns that job instead of a new quote changing the request.
            return submit_and_collect(client, state, state_path, output, args.timeout)
        request, ceiling = state["request"], state["max_credits"]
    else:
        if args.resume:
            raise ValueError("No saved request to resume.")
        request = build_request()
        ceiling = args.max_credits
        state = {"request": request, "max_credits": ceiling, "idempotency_key": str(uuid.uuid4()),
                 "base_url": client.base_url, "workspace_id": workspace_id}
    spending_cap = {"billing": {"max_reserved_credits": ceiling}} if metered and ceiling and ceiling > 0 else {}
    quote = client.jobs.quote(**request, **spending_cap)
    print(json.dumps(quote.raw, indent=2))
    check_quote(quote, ceiling, metered)
    if not args.submit:
        print("Quote only. No job submitted.")
        return None
    if ceiling is None or ceiling < 1:
        raise ValueError("Submission requires a positive integer --max-credits.")
    state["submission"] = {**request, **(spending_cap if quote.billing.get("mode") != "fixed" else {}),
                           "name": args.job_name, "max_quoted_credits": ceiling}
    return submit_and_collect(client, state, state_path, output, args.timeout)

The MolProbity example walks through each of those steps in more detail. Run the script without --submit first to see the quote:

Bash
python score_complex.py --model prediction_rank01.pdb --native 2ZTA.pdb --output gcn4-dockq

When the price looks right, add --submit and replace YOUR_LIMIT with the credits you approve. The server enforces the same ceiling through max_quoted_credits, so a price change between quote and submission cannot charge you more.

Bash
python score_complex.py --model prediction_rank01.pdb --native 2ZTA.pdb --output gcn4-dockq --submit --max-credits YOUR_LIMIT

If the script is interrupted, run it again with --output gcn4-dockq --resume and it picks up the same job.

Reading the native report

DockQ returns three files: dockq_results.json, its complete result at full precision; dockq_stdout.log, the text report it prints on the command line; and dockq_stderr.log, its diagnostic stream. The text report is the quickest read:

Text
Total DockQ over 1 native interfaces: 0.935 with AB:AB model:native mapping
Native chains: A, B
	Model chains: A, B
	DockQ: 0.935
	iRMSD: 0.621
	LRMSD: 1.396
	fnat: 0.979
	fnonnat: 0.061
	F1: 0.958
	clashes: 1

The script works from the JSON instead, because it holds every interface of the chosen chain mapping with the contact counts behind fnat. interfaces turns each one into a row and skips small-molecule interfaces, which DockQ scores from LRMSD alone and which have no fnat to classify.

Python
def interfaces(native_report: dict) -> list[dict]:
    """One row per native interface for the chain mapping DockQ chose."""
    rows = []
    for metrics in native_report["best_result"].values():
        if metrics.get("is_het") or metrics.get("fnat") is None:
            continue  # Small-molecule interfaces are scored from LRMSD alone.
        terms = dockq_terms(metrics["fnat"], metrics["iRMSD"], metrics["LRMSD"])
        rows.append({**metrics, "interface": f"{metrics['chain1']}:{metrics['chain2']}",
                     "terms": terms, "band": band(metrics["DockQ"]),
                     "capri": capri_class(metrics["fnat"], metrics["iRMSD"], metrics["LRMSD"])})
    return rows

Taking the score apart

DockQ is the mean of three terms. fnat, the fraction of native contacts the model reproduces, enters as it is; a contact is a pair of residues from the two chains with heavy atoms within 5 Å. The two RMSDs are converted to scores between 0 and 1.

iRMSD is the backbone RMSD of the interface residues, those within 10 Å of the partner, after superposing them, and 1.5 Å scores 0.5. LRMSD is the backbone RMSD of the smaller chain once the larger one is superposed, and 8.5 Å scores 0.5. Recomputing the terms is the quickest way to see which kind of error a model has.

Python
def dockq_terms(fnat: float, irmsd: float, lrmsd: float) -> tuple[float, float, float]:
    """The three averaged terms of DockQ: fnat and the two RMSDs scaled to 0..1."""
    return fnat, 1 / (1 + (irmsd / 1.5) ** 2), 1 / (1 + (lrmsd / 8.5) ** 2)

The formula averages away the difference between, say, a model with the right contacts on a slightly rotated partner and one with a perfect partner placement but a different contact set. Reading the terms side by side shows which of the two you have.

The quality bands came from CAPRI, which classified models from fnat, LRMSD and iRMSD before DockQ existed. Basu and Wallner chose the DockQ cutoffs 0.23, 0.49 and 0.80 to reproduce those classes, and they agree for most models but not all. The script applies the original criteria too, so a model near a boundary shows both readings:

Python
def capri_class(fnat: float, irmsd: float, lrmsd: float) -> str:
    for name, min_fnat, max_lrmsd, max_irmsd in CAPRI:
        if fnat >= min_fnat and (lrmsd <= max_lrmsd or irmsd <= max_irmsd):
            return name
    return "Incorrect"

This model is a useful case. Its LRMSD of 1.40 Å misses the 1 Å limit for High, and the class still holds because CAPRI accepts either RMSD and the iRMSD of 0.62 Å passes. Judged on LRMSD alone, the model would drop to Medium.

The class1 and class2 fields in the JSON say which chain DockQ treated as the ligand for LRMSD. In DockQ 2.1.3 the smaller chain is the ligand, and when the chains are the same length, as here, the first chain of the pair is. That is why the report reads "chain A placed with chain B superposed".

Chain mapping in a homodimer

Both GCN4 chains have the same sequence, so model chain A could match crystal chain A or crystal chain B. DockQ tries every assignment the sequences allow and keeps the one with the highest total DockQ over the reference interfaces. For a homodimer that is two mappings, and the progress bar in dockq_stderr.log counts them:

Text
DONE: 100%|██████████| 2/2 [00:00<00:00, 15.07it/s]

The winning mapping, AB:AB, is written model chains first, then reference chains. For larger assemblies with many identical chains, the number of mappings grows quickly, and passing --chain-mapping with an explicit MODEL:NATIVE string fixes the assignment and skips the search.

report prints the summary above and writes one row per interface to interfaces.csv, which is the format to keep when you score many models against the same reference:

Text
interface,dockq,band,capri_class,fnat,irmsd,lrmsd,fnonnat,f1,clashes
A:B,0.9353411566622518,High,High,0.9787234042553191,0.6213254831009528,1.3956307233688632,0.061224489795918366,0.9583333333333334,1
Python
def report(result: dict, output: Path) -> None:
    (native_file,) = proteiniq_job.output_files(output, r"dockq_results\.json$")
    native_report = json.loads(native_file.read_text(encoding="utf-8"))
    rows = interfaces(native_report)
    print(f"DockQ {result.get('version', '')}, chain mapping {native_report['best_mapping_str']} "
          f"(model:native), GlobalDockQ {native_report['GlobalDockQ']:.3f}")
    for row in rows:
        fnat_term, irmsd_term, lrmsd_term = row["terms"]
        ligand, receptor = ((row["chain1"], row["chain2"]) if row["class1"] == "ligand"
                            else (row["chain2"], row["chain1"]))
        print(f"Interface {row['interface']}: DockQ {row['DockQ']:.3f}, {row['band']}; "
              f"CAPRI criteria give {row['capri']}")
        print(f"  fnat     {row['fnat']:6.3f}    term {fnat_term:.3f}  "
              f"{row['nat_correct']} of {row['nat_total']} native contacts")
        print(f"  iRMSD    {row['iRMSD']:6.2f} Å  term {irmsd_term:.3f}")
        print(f"  LRMSD    {row['LRMSD']:6.2f} Å  term {lrmsd_term:.3f}  "
              f"chain {ligand} placed with chain {receptor} superposed")
        print(f"  fnonnat  {row['fnonnat']:6.3f}               "
              f"{row['nonnat_count']} of {row['model_total']} model contacts not in the native")
        print(f"  clashes  {row['clashes']:6d}")
    with open(output / "interfaces.csv", "w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle)
        writer.writerow(["interface", "dockq", "band", "capri_class", "fnat", "irmsd", "lrmsd",
                         "fnonnat", "f1", "clashes"])
        writer.writerows([row["interface"], row["DockQ"], row["band"], row["capri"], row["fnat"],
                          row["iRMSD"], row["LRMSD"], row["fnonnat"], row["F1"], row["clashes"]]
                         for row in rows)
    print(f"Interface table: {output / 'interfaces.csv'}")

Going further

DockQ grades the interface and nothing else. To compare the two structures as wholes, the structure comparison example runs USAlign, and its oligomer mode aligns this same model against 2ZTA chain by chain in a public USAlign job. MolProbity checks the model's own geometry, including clashes anywhere in the structure, where DockQ only counts those across the interface.

Without a reference structure, DockQ has nothing to measure against. The ipSAE tool estimates interface quality from a prediction's own PAE and pLDDT instead, and the ipSAE guide explains how to read those scores. The same script works for larger complexes: in the transcription factor and DNA example, DockQ scores six interfaces of a four-chain Boltz-2 model against 5GNJ, and report prints one block per interface.

Complete script

Python
"""Score a predicted protein complex against a reference structure with DockQ.

Quotes by default. Add --submit --max-credits N to run one job. Keep the output
folder to resume. Needs proteiniq_job.py from the same page in this folder.
"""
from __future__ import annotations

import csv
import json
from pathlib import Path

import proteiniq_job

STRUCTURE_FORMATS = {".pdb": "pdb", ".ent": "ent", ".cif": "cif"}
# DockQ v2 prints these bands; Basu and Wallner chose them to match the CAPRI classes.
BANDS = [(0.80, "High"), (0.49, "Medium"), (0.23, "Acceptable"), (0.0, "Incorrect")]
# CAPRI criteria: (class, minimum fnat, maximum LRMSD, maximum iRMSD); either RMSD may pass.
CAPRI = [("High", 0.5, 1.0, 1.0), ("Medium", 0.3, 5.0, 2.0), ("Acceptable", 0.1, 10.0, 4.0)]


def pdb_chains(path: Path) -> set[str]:
    return {line[21] for line in path.read_text(encoding="utf-8").splitlines()
            if line.startswith(("ATOM", "HETATM")) and len(line) > 21}


def make_request(model: Path, native: Path, chain_mapping: str = "") -> dict:
    if chain_mapping and (chain_mapping.count(":") != 1 or "," in chain_mapping):
        raise ValueError("Write the chain mapping as MODEL:NATIVE, one character per chain, e.g. AB:AB.")
    inputs = []
    for path, slot in ((model, "model"), (native, "native")):
        structure = proteiniq_job.file_input(path, slot, "protein", STRUCTURE_FORMATS)
        # An interface needs two chains. mmCIF chain IDs are left for DockQ to read.
        if structure["format"] != "cif" and len(pdb_chains(path)) < 2:
            raise ValueError(f"{path.name} has fewer than two chains, so it has no interface to score.")
        inputs.append(structure)
    settings = {"chain_mapping": chain_mapping, "small_molecule": False, "capri_peptide": False,
                "no_align": False, "allowed_mismatches": 0}
    return {"tool": "dockq", "input": {"inputs": inputs}, "settings": settings}


def dockq_terms(fnat: float, irmsd: float, lrmsd: float) -> tuple[float, float, float]:
    """The three averaged terms of DockQ: fnat and the two RMSDs scaled to 0..1."""
    return fnat, 1 / (1 + (irmsd / 1.5) ** 2), 1 / (1 + (lrmsd / 8.5) ** 2)


def band(dockq: float) -> str:
    return next(name for floor, name in BANDS if dockq >= floor)


def capri_class(fnat: float, irmsd: float, lrmsd: float) -> str:
    for name, min_fnat, max_lrmsd, max_irmsd in CAPRI:
        if fnat >= min_fnat and (lrmsd <= max_lrmsd or irmsd <= max_irmsd):
            return name
    return "Incorrect"


def interfaces(native_report: dict) -> list[dict]:
    """One row per native interface for the chain mapping DockQ chose."""
    rows = []
    for metrics in native_report["best_result"].values():
        if metrics.get("is_het") or metrics.get("fnat") is None:
            continue  # Small-molecule interfaces are scored from LRMSD alone.
        terms = dockq_terms(metrics["fnat"], metrics["iRMSD"], metrics["LRMSD"])
        rows.append({**metrics, "interface": f"{metrics['chain1']}:{metrics['chain2']}",
                     "terms": terms, "band": band(metrics["DockQ"]),
                     "capri": capri_class(metrics["fnat"], metrics["iRMSD"], metrics["LRMSD"])})
    return rows


def report(result: dict, output: Path) -> None:
    (native_file,) = proteiniq_job.output_files(output, r"dockq_results\.json$")
    native_report = json.loads(native_file.read_text(encoding="utf-8"))
    rows = interfaces(native_report)
    print(f"DockQ {result.get('version', '')}, chain mapping {native_report['best_mapping_str']} "
          f"(model:native), GlobalDockQ {native_report['GlobalDockQ']:.3f}")
    for row in rows:
        fnat_term, irmsd_term, lrmsd_term = row["terms"]
        ligand, receptor = ((row["chain1"], row["chain2"]) if row["class1"] == "ligand"
                            else (row["chain2"], row["chain1"]))
        print(f"Interface {row['interface']}: DockQ {row['DockQ']:.3f}, {row['band']}; "
              f"CAPRI criteria give {row['capri']}")
        print(f"  fnat     {row['fnat']:6.3f}    term {fnat_term:.3f}  "
              f"{row['nat_correct']} of {row['nat_total']} native contacts")
        print(f"  iRMSD    {row['iRMSD']:6.2f} Å  term {irmsd_term:.3f}")
        print(f"  LRMSD    {row['LRMSD']:6.2f} Å  term {lrmsd_term:.3f}  "
              f"chain {ligand} placed with chain {receptor} superposed")
        print(f"  fnonnat  {row['fnonnat']:6.3f}               "
              f"{row['nonnat_count']} of {row['model_total']} model contacts not in the native")
        print(f"  clashes  {row['clashes']:6d}")
    with open(output / "interfaces.csv", "w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle)
        writer.writerow(["interface", "dockq", "band", "capri_class", "fnat", "irmsd", "lrmsd",
                         "fnonnat", "f1", "clashes"])
        writer.writerows([row["interface"], row["DockQ"], row["band"], row["capri"], row["fnat"],
                          row["iRMSD"], row["LRMSD"], row["fnonnat"], row["F1"], row["clashes"]]
                         for row in rows)
    print(f"Interface table: {output / 'interfaces.csv'}")


if __name__ == "__main__":
    arguments = proteiniq_job.parser(__doc__, "dockq-output")
    arguments.add_argument("--model", type=Path, help="Predicted or docked complex (PDB or mmCIF).")
    arguments.add_argument("--native", type=Path, help="Reference complex, usually an experimental structure.")
    arguments.add_argument("--chain-mapping", default="", help="Optional MODEL:NATIVE mapping, e.g. AB:AB.")
    args = arguments.parse_args()
    if not args.resume and (args.model is None or args.native is None):
        arguments.error("--model and --native are required for a new run.")
    proteiniq_job.main(args, lambda: make_request(args.model, args.native, args.chain_mapping), report)

The shared job runner, proteiniq_job.py:

Python
"""Run one ProteinIQ job safely from a script. Python SDK 0.2.0+. MIT licensed.

Every API example imports this module. It quotes by default, submits only with
--submit and --max-credits, saves the request and idempotency key before the
network call, resumes interrupted runs, and downloads outputs with checksums.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import tempfile
from typing import Callable
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 text_input(slot: str, kind: str, format_name: str, content: str, label: str) -> dict:
    """One entry of a request's inputs[], with the file contents inline."""
    if not content.strip():
        raise ValueError(f"The {slot} input is empty.")
    return {"id": slot, "slotId": slot, "kind": kind, "format": format_name,
            "content": content, "label": label, "source": {"type": "text"}}


def file_input(path: Path, slot: str, kind: str, formats: dict[str, str]) -> dict:
    """Read a local file into an input, mapping its extension to an accepted format."""
    format_name = formats.get(path.suffix.lower())
    if format_name is None:
        raise ValueError(f"{path.name}: use one of {', '.join(sorted(formats))}.")
    return text_input(slot, kind, format_name, path.read_text(encoding="utf-8"), path.name)


def check_quote(quote, ceiling: int | None, metered: bool = False) -> None:
    if quote.blocking_errors:
        raise ValueError(f"Quote rejected: {quote.blocking_errors}")
    if quote.billing.get("mode") != "fixed" and not metered:
        raise ValueError("These examples only submit 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) -> dict:
    """Wait for the job, save its structured result and download every file once."""
    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(f"Completed job {job.id}. Files are in {output}")
    return result.results


def output_files(output: Path, pattern: str) -> list[Path]:
    """Downloaded files whose original server name matches a regular expression."""
    manifest = json.loads((output / "files.json").read_text(encoding="utf-8"))
    return [output / local for local, entry in manifest.items()
            if re.search(pattern, entry.get("source_name") or "")]


def run(args: argparse.Namespace, client: ProteinIQ, build_request: Callable[[], dict],
        metered: bool = False) -> dict | None:
    """Quote, then submit at most one job and collect it. Returns the result once complete.

    With metered=True a runtime-billed quote is accepted, and --max-credits is sent
    with the quote and the submission as the spending cap (billing.max_reserved_credits).
    """
    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"):
            return collect(client, state, output, args.timeout)
        if not args.submit:
            raise ValueError("Retrying an unconfirmed submission also requires --submit.")
        if state.get("submission"):
            # Resend exactly what the first attempt sent, so the idempotency key
            # returns that job instead of a new quote changing the request.
            return submit_and_collect(client, state, state_path, output, args.timeout)
        request, ceiling = state["request"], state["max_credits"]
    else:
        if args.resume:
            raise ValueError("No saved request to resume.")
        request = build_request()
        ceiling = args.max_credits
        state = {"request": request, "max_credits": ceiling, "idempotency_key": str(uuid.uuid4()),
                 "base_url": client.base_url, "workspace_id": workspace_id}
    spending_cap = {"billing": {"max_reserved_credits": ceiling}} if metered and ceiling and ceiling > 0 else {}
    quote = client.jobs.quote(**request, **spending_cap)
    print(json.dumps(quote.raw, indent=2))
    check_quote(quote, ceiling, metered)
    if not args.submit:
        print("Quote only. No job submitted.")
        return None
    if ceiling is None or ceiling < 1:
        raise ValueError("Submission requires a positive integer --max-credits.")
    state["submission"] = {**request, **(spending_cap if quote.billing.get("mode") != "fixed" else {}),
                           "name": args.job_name, "max_quoted_credits": ceiling}
    return submit_and_collect(client, state, state_path, output, args.timeout)


def submit_and_collect(client: ProteinIQ, state: dict, state_path: Path, output: Path, timeout: float) -> dict:
    # Persist the exact submission and key BEFORE a network call can start a job.
    save_json(state_path, state)
    job = client.jobs.submit(**state["submission"], idempotency_key=state["idempotency_key"])
    state["job_id"] = job.id
    save_json(state_path, state)
    print(f"Job {job.id} submitted. Resume with --output {output} --resume")
    return collect(client, state, output, timeout)


def parser(description: str | None, default_output: str) -> argparse.ArgumentParser:
    """The flags every example shares. Add the example's own inputs to the result."""
    arguments = argparse.ArgumentParser(description=description)
    arguments.add_argument("--output", type=Path, default=Path(default_output))
    arguments.add_argument("--submit", action="store_true", help="Start the job after a successful quote.")
    arguments.add_argument("--max-credits", type=int, help="Highest quote you approve.")
    arguments.add_argument("--resume", action="store_true", help="Continue the request saved in --output.")
    arguments.add_argument("--timeout", type=float, default=3600, help="Seconds to wait locally.")
    arguments.add_argument("--job-name", default="API example")
    return arguments


def main(args: argparse.Namespace, build_request: Callable[[], dict],
         report: Callable[[dict, Path], None], metered: bool = False) -> None:
    """Run the job, then hand the structured result and output folder to report()."""
    args.output.mkdir(parents=True, exist_ok=True)
    # An exclusive lock prevents two local processes overwriting recovery state.
    lock = args.output / ".proteiniq.lock"
    try:
        descriptor = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    except FileExistsError:
        raise SystemExit(f"{args.output} is in use by another run. Delete {lock} if none is running.")
    try:
        with ProteinIQ() as client:
            result = run(args, client, build_request, metered)
        if result is not None:
            report(result, args.output)
    except (ProteinIQError, ValueError, RuntimeError, TimeoutError) as error:
        raise SystemExit(f"{error}\nKeep this directory and resume the same request. A timeout does not cancel compute.")
    finally:
        os.close(descriptor)
        lock.unlink(missing_ok=True)

How this example was checked

The script's request builder and scoring functions are tested offline, and its parser is tested on the native DockQ report returned by the public DockQ example job of 11 October 2026. The results shown come from that job, which scored the same model against the same crystal structure with the same settings; the script itself has not yet been run against the live API.