API examples

Dock a ligand with AutoDock Vina

Redock imatinib into c-Abl kinase (1IEP) from Python, then rank the returned poses by affinity and by symmetry-corrected RMSD to the crystal ligand.

Download Python example · Shared job runner · Example code license

Imatinib is a long, flexible drug: 37 heavy atoms joined by seven bonds that Vina treats as rotatable, which gives a docking program a lot of ways to get it wrong. The crystal structure of imatinib bound to the c-Abl kinase domain, 1IEP, solved at 2.1 Å, gives the exact answer a docking program should find. That makes it a fair test: remove the drug, dock it back from its SMILES string, and see whether the program puts it where the crystal says it belongs.

AutoDock Vina does that here in 22 seconds. This example runs the job from Python with the ProteinIQ SDK and then checks each returned pose against the crystal ligand with a symmetry-corrected RMSD, the one number Vina's own output does not give you.

The result

The public example job docked imatinib into 1IEP on 19 July 2026 in 22 seconds of compute. Run on that job's output with the 1IEP entry as reference, the script prints:

Text
5 poses of STI against chain A of 1IEP
rank  affinity (kcal/mol)  RMSD to crystal (A)
   1               -12.51                 0.94
   2               -11.29                 1.43
   3               -10.49                12.24
   4               -10.29                13.39
   5                -9.78                12.54
Top pose reproduces the crystal pose; poses within 2 A: 1, 2

The top pose lands 0.94 Å from the crystal ligand, well inside the 2 Å convention for a correct redocking, and it also has the best Vina score, at -12.51 kcal/mol. The second pose is correct too.

Poses 3 to 5 are 12 to 13 Å away, yet they sit in the same groove: when we superposed them onto the crystal ligand with RDKit they came within 1.8 to 2.4 Å. They have the right shape but run the wrong way, with each end of the drug where the other should be. Vina scored all three at least 2 kcal/mol worse than the top pose.

Vina found nine modes in total. The energy_range of 3 kcal/mol dropped the four weakest, which scored between -9.50 and -9.02 kcal/mol, so the job returned five.

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

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

The script needs only this one file. It builds the receptor from it, centers the search box on the bound imatinib and later uses the same imatinib as the reference for RMSD.

Building the request

1IEP holds two copies of the kinase, chains A and B, each with an imatinib (residue name STI), plus chloride ions and 172 waters. The public job docked into the protein alone, so the script drops every HETATM record and the CONECT records that bond them. What remains is the receptor the job used, line for line.

Python
def receptor_from_complex(pdb_text: str) -> str:
    """Drop ligands, ions and waters (HETATM) and their CONECT records, keeping the protein."""
    kept = [line for line in pdb_text.splitlines(keepends=True) if not line.startswith(("HETATM", "CONECT"))]
    if not any(line.startswith("ATOM") for line in kept):
        raise ValueError("No protein ATOM records in the complex.")
    return "".join(kept)

The search box comes from the crystal ligand of chain A: its bounding box, padded by 5 Å on every side. For 1IEP that gives a box of 18.7 by 26.7 by 23.5 Å, the same box as the public job to within 0.001 Å. Building the box from the ligand you are about to remove is fine for redocking, where the question is whether Vina can find the pose, not the pocket.

Python
def crystal_ligand(pdb_text: str, residue: str, chain: str) -> list[tuple[str, tuple[float, float, float]]]:
    """Heavy atoms of one bound ligand, as (element, coordinates)."""
    atoms = []
    for line in pdb_text.splitlines():
        if line.startswith("HETATM") and line[17:20].strip() == residue and line[21] == chain:
            element = (line[76:78].strip() or line[12:16].strip()[0]).upper()
            if element != "H":
                atoms.append((element, (float(line[30:38]), float(line[38:46]), float(line[46:54]))))
    if not atoms:
        raise ValueError(f"No {residue} ligand in chain {chain}.")
    return atoms
Python
def search_box(atoms, padding: float = 5.0) -> dict:
    """The crystal ligand's bounding box, padded on every side, as Vina center and size settings."""
    box = {}
    for axis, index in zip("xyz", range(3)):
        low, high = min(xyz[index] for _, xyz in atoms), max(xyz[index] for _, xyz in atoms)
        box[f"center_{axis}"] = round((low + high) / 2, 3)
        box[f"size_{axis}"] = round(high - low + 2 * padding, 3)
    return box

The ligand goes in as SMILES, not as the crystal coordinates. Starting from the crystal conformation would hand Vina part of the answer, so ProteinIQ builds a fresh 3D conformer with RDKit before Meeko prepares it. The script accepts one SMILES string and refuses anything with spaces or a . separating several molecules.

Python
def make_request(complex_pdb: Path, smiles: str, residue: str, chain: str) -> dict:
    text = complex_pdb.read_text(encoding="utf-8")
    if not SMILES.match(smiles) or "." in smiles:
        raise ValueError("Give one ligand as a single SMILES string.")
    receptor = proteiniq_job.text_input("protein", "protein", "pdb", receptor_from_complex(text),
                                        f"{complex_pdb.stem} receptor")
    ligand = proteiniq_job.text_input("ligand", "ligand", "smiles", smiles, residue)
    settings = {
        "multi_ligand_mode": "single", "docking_mode": "dock", "scoring_function": "vina",
        "exhaustiveness": 8, "num_modes": 9, "energy_range": 3, "min_rmsd": 1, "seed": 42,
        "search_mode": "manual", **search_box(crystal_ligand(text, residue, chain)),
        "receptor_use_pdb2pqr": "pdb2pqr", "receptor_pdb2pqr_ph": 7,
        "receptor_remove_covalent_ligand_chains": True,
    }
    return {"tool": "autodock-vina", "input": {"inputs": [receptor, ligand]}, "settings": settings}

The settings match the public job, and every setting not listed is at its default. exhaustiveness 8 is Vina's default search effort, num_modes 9 caps the poses, and energy_range 3 discards any pose more than 3 kcal/mol worse than the best. A fixed seed of 42 makes the run repeatable; with 0, Vina picks its own. receptor_use_pdb2pqr set to pdb2pqr runs PDB2PQR at pH 7 on the receptor before Meeko assigns charges and atom types, whether or not atoms are missing.

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 dock_ligand.py --complex 1IEP.pdb --output imatinib-redock \
  --smiles 'CC1=C(C=C(C=C1)NC(=O)C2=CC=C(C=C2)CN3CCN(CC3)C)NC4=NC=CC(=N4)C5=CN=CC=C5'

When the price looks right, add --submit and --max-credits YOUR_LIMIT, replacing 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. If the script is interrupted, run it again with --complex 1IEP.pdb --output imatinib-redock --resume and it picks up the same job.

Reading the poses

The public job returned twelve files: the input protein.pdb, the prepared prepared_receptor.pdbqt and prepared_ligand_01.pdbqt, a receptor preparation report and log, one pose_modeNN.pdbqt per pose and vina_run_summary.txt. Jobs run since then also include a pose_modeNN.sdf beside each pose.

The script reads Imatinib_output.pdbqt, Vina's native output, which holds every pose as a MODEL block with its affinity in a REMARK VINA RESULT line. ProteinIQ names that file after the ligand's label, so the script finds it by its _output.pdbqt ending.

Python
def read_poses(pdbqt: Path) -> list[tuple[float, list[tuple[str, tuple[float, float, float]]]]]:
    """Each MODEL of Vina's native output: its affinity and its heavy atoms."""
    poses = []
    for line in pdbqt.read_text(encoding="utf-8").splitlines():
        if line.startswith("MODEL"):
            affinity, atoms = None, []
        elif line.startswith("REMARK VINA RESULT:"):
            affinity = float(line.split()[3])
        elif line.startswith(("ATOM", "HETATM")):
            element = AD_ELEMENTS.get(line[77:79].strip(), line[77:79].strip()).upper()
            if element != "H":
                atoms.append((element, (float(line[30:38]), float(line[38:46]), float(line[46:54]))))
        elif line.startswith("ENDMDL"):
            poses.append((affinity, atoms))
    if not poses:
        raise ValueError(f"No poses in {pdbqt.name}")
    return poses

PDBQT files store AutoDock atom types rather than elements in their last column: A is an aromatic carbon, NA and OA are nitrogen and oxygen acceptors, HD a polar hydrogen. The parser maps them back to elements and keeps only heavy atoms. Meeko writes just the two polar hydrogens of imatinib, so comparing hydrogens with the crystal ligand, which has none, would make no sense.

Measuring RMSD against the crystal

Vina's own output already lists two RMSD columns, but both compare each pose with the top pose of the same run, never with an experimental structure. They can also mislead. Pose 4 has a lower bound of 1.79 Å from pose 1, which looks close, while it sits 13.39 Å from the crystal ligand. The lower bound matches each atom to the nearest atom of the same element in the other pose, so a reversed ligand filling the same space scores low.

The comparison that answers the redocking question uses the crystal ligand, in the receptor's frame and without fitting. The receptor was never moved, so the pose and the crystal share coordinates, and fitting one ligand onto the other would hide exactly the errors you want to see. Atom names are no help either: Vina renames every atom C, N or O, and the order of atoms in the pose file follows its torsion tree, not the PDB entry. So the script rebuilds both bond graphs from interatomic distances.

Python
def bond_graph(atoms) -> list[set[int]]:
    """Neighbours of each atom, from interatomic distances."""
    neighbours = [set() for _ in atoms]
    for i, (element_i, xyz_i) in enumerate(atoms):
        for j in range(i + 1, len(atoms)):
            element_j, xyz_j = atoms[j]
            if math.dist(xyz_i, xyz_j) < RADII.get(element_i, 0.8) + RADII.get(element_j, 0.8) + 0.45:
                neighbours[i].add(j)
                neighbours[j].add(i)
    return neighbours

It then searches for the atom mapping that keeps every bond and gives the lowest RMSD. Imatinib has two rings that can flip without changing the molecule, the para-substituted benzamide ring and the piperazine, so several mappings are valid and the RMSD should use the best one. The search places atoms in breadth-first order, so each new atom must bond to one already placed, and it abandons any branch whose running sum already exceeds the best complete mapping. For imatinib's 37 heavy atoms the whole report takes a fraction of a second.

Python
def symmetric_rmsd(pose, reference) -> float:
    """In-place heavy-atom RMSD, minimised over every atom mapping that preserves the bond graph.

    Vina renames and reorders atoms, and a flipped phenyl ring is the same pose, so
    atoms are matched by element and bonding rather than by name.
    """
    if sorted(e for e, _ in pose) != sorted(e for e, _ in reference):
        raise ValueError("Pose and reference ligand have different heavy atoms.")
    pose_bonds, ref_bonds = bond_graph(pose), bond_graph(reference)
    # Visit pose atoms in breadth-first order so each new atom has a placed neighbour.
    order, seen = [], set()
    for start in range(len(pose)):
        queue = [start] if start not in seen else []
        seen.update(queue)
        while queue:
            atom = queue.pop(0)
            order.append(atom)
            for neighbour in sorted(pose_bonds[atom] - seen):
                seen.add(neighbour)
                queue.append(neighbour)
    best = [math.inf]

    def extend(depth: int, mapping: dict[int, int], used: set[int], total: float) -> None:
        if total >= best[0]:
            return
        if depth == len(order):
            best[0] = total
            return
        atom = order[depth]
        for candidate in range(len(reference)):
            if (candidate in used or reference[candidate][0] != pose[atom][0]
                    or len(ref_bonds[candidate]) != len(pose_bonds[atom])):
                continue
            if all((mapping[n] in ref_bonds[candidate]) for n in pose_bonds[atom] if n in mapping):
                mapping[atom] = candidate
                used.add(candidate)
                extend(depth + 1, mapping, used,
                       total + math.dist(pose[atom][1], reference[candidate][1]) ** 2)
                del mapping[atom]
                used.discard(candidate)

    extend(0, {}, set(), 0.0)
    if best[0] == math.inf:
        raise ValueError("Pose and reference ligand have different bonding.")
    return math.sqrt(best[0] / len(pose))

The values match RDKit's symmetry-aware CalcRMS to two decimals: 0.94, 1.43, 12.24, 13.39 and 12.54 Å. report prints them beside the affinities and writes them to poses.csv:

Text
rank,affinity_kcal_mol,rmsd_to_crystal_angstrom
1,-12.512,0.94
2,-11.290,1.43
3,-10.489,12.24
Python
def report(result: dict, output: Path, complex_pdb: Path, residue: str, chain: str) -> None:
    (native,) = proteiniq_job.output_files(output, r"_output\.pdbqt$")
    reference = crystal_ligand(complex_pdb.read_text(encoding="utf-8"), residue, chain)
    rows = [(rank, affinity, symmetric_rmsd(atoms, reference))
            for rank, (affinity, atoms) in enumerate(read_poses(native), 1)]
    with open(output / "poses.csv", "w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle)
        writer.writerow(["rank", "affinity_kcal_mol", "rmsd_to_crystal_angstrom"])
        writer.writerows((rank, f"{affinity:.3f}", f"{rmsd:.2f}") for rank, affinity, rmsd in rows)
    print(f"{len(rows)} poses of {residue} against chain {chain} of {complex_pdb.stem}")
    print("rank  affinity (kcal/mol)  RMSD to crystal (A)")
    for rank, affinity, rmsd in rows:
        print(f"{rank:>4}  {affinity:>19.2f}  {rmsd:>19.2f}")
    # A heavy-atom RMSD under 2 Å is the usual threshold for a correctly reproduced pose.
    within = [rank for rank, _, rmsd in rows if rmsd < 2.0]
    print(f"Top pose {'reproduces' if rows[0][2] < 2.0 else 'misses'} the crystal pose; "
          f"poses within 2 A: {', '.join(map(str, within)) or 'none'}")
    print(f"Pose table: {output / 'poses.csv'}")

Going further

A correct redocking says the setup works for this ligand in this receptor conformation. It says less about other ligands, or about the same ligand in a different conformation of the kinase; the redocking guide shows imatinib failing in a structure solved with another inhibitor. Before you trust a pose for a new ligand, check its chemistry and contacts with PoseBusters, and profile its hydrogen bonds and hydrophobic contacts with PLIP as in the interaction profiling example.

To dock a different ligand into the same pocket, pass its SMILES with --smiles and keep --complex 1IEP.pdb: the box still comes from the crystal imatinib, and the RMSD column then measures how far each pose strays from it, which is no longer an accuracy measure. Rescoring the same poses with GNINA gives a second opinion from a different scoring function.

Complete script

Python
"""Redock a ligand into its crystal structure with AutoDock Vina and score each pose by RMSD.

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 math
from pathlib import Path
import re

import proteiniq_job

SMILES = re.compile(r"^[A-Za-z0-9@+\-\[\]()=#$/\\%.:*]+$")
# AutoDock atom types that are not plain element symbols.
AD_ELEMENTS = {"A": "C", "NA": "N", "NS": "N", "OA": "O", "OS": "O", "SA": "S", "HD": "H", "HS": "H"}
# Covalent radii in Å, for perceiving bonds from coordinates.
RADII = {"C": 0.76, "N": 0.71, "O": 0.66, "S": 1.05, "P": 1.07, "F": 0.57, "CL": 1.02, "BR": 1.20, "I": 1.39}


def receptor_from_complex(pdb_text: str) -> str:
    """Drop ligands, ions and waters (HETATM) and their CONECT records, keeping the protein."""
    kept = [line for line in pdb_text.splitlines(keepends=True) if not line.startswith(("HETATM", "CONECT"))]
    if not any(line.startswith("ATOM") for line in kept):
        raise ValueError("No protein ATOM records in the complex.")
    return "".join(kept)


def crystal_ligand(pdb_text: str, residue: str, chain: str) -> list[tuple[str, tuple[float, float, float]]]:
    """Heavy atoms of one bound ligand, as (element, coordinates)."""
    atoms = []
    for line in pdb_text.splitlines():
        if line.startswith("HETATM") and line[17:20].strip() == residue and line[21] == chain:
            element = (line[76:78].strip() or line[12:16].strip()[0]).upper()
            if element != "H":
                atoms.append((element, (float(line[30:38]), float(line[38:46]), float(line[46:54]))))
    if not atoms:
        raise ValueError(f"No {residue} ligand in chain {chain}.")
    return atoms


def search_box(atoms, padding: float = 5.0) -> dict:
    """The crystal ligand's bounding box, padded on every side, as Vina center and size settings."""
    box = {}
    for axis, index in zip("xyz", range(3)):
        low, high = min(xyz[index] for _, xyz in atoms), max(xyz[index] for _, xyz in atoms)
        box[f"center_{axis}"] = round((low + high) / 2, 3)
        box[f"size_{axis}"] = round(high - low + 2 * padding, 3)
    return box


def make_request(complex_pdb: Path, smiles: str, residue: str, chain: str) -> dict:
    text = complex_pdb.read_text(encoding="utf-8")
    if not SMILES.match(smiles) or "." in smiles:
        raise ValueError("Give one ligand as a single SMILES string.")
    receptor = proteiniq_job.text_input("protein", "protein", "pdb", receptor_from_complex(text),
                                        f"{complex_pdb.stem} receptor")
    ligand = proteiniq_job.text_input("ligand", "ligand", "smiles", smiles, residue)
    settings = {
        "multi_ligand_mode": "single", "docking_mode": "dock", "scoring_function": "vina",
        "exhaustiveness": 8, "num_modes": 9, "energy_range": 3, "min_rmsd": 1, "seed": 42,
        "search_mode": "manual", **search_box(crystal_ligand(text, residue, chain)),
        "receptor_use_pdb2pqr": "pdb2pqr", "receptor_pdb2pqr_ph": 7,
        "receptor_remove_covalent_ligand_chains": True,
    }
    return {"tool": "autodock-vina", "input": {"inputs": [receptor, ligand]}, "settings": settings}


def read_poses(pdbqt: Path) -> list[tuple[float, list[tuple[str, tuple[float, float, float]]]]]:
    """Each MODEL of Vina's native output: its affinity and its heavy atoms."""
    poses = []
    for line in pdbqt.read_text(encoding="utf-8").splitlines():
        if line.startswith("MODEL"):
            affinity, atoms = None, []
        elif line.startswith("REMARK VINA RESULT:"):
            affinity = float(line.split()[3])
        elif line.startswith(("ATOM", "HETATM")):
            element = AD_ELEMENTS.get(line[77:79].strip(), line[77:79].strip()).upper()
            if element != "H":
                atoms.append((element, (float(line[30:38]), float(line[38:46]), float(line[46:54]))))
        elif line.startswith("ENDMDL"):
            poses.append((affinity, atoms))
    if not poses:
        raise ValueError(f"No poses in {pdbqt.name}")
    return poses


def bond_graph(atoms) -> list[set[int]]:
    """Neighbours of each atom, from interatomic distances."""
    neighbours = [set() for _ in atoms]
    for i, (element_i, xyz_i) in enumerate(atoms):
        for j in range(i + 1, len(atoms)):
            element_j, xyz_j = atoms[j]
            if math.dist(xyz_i, xyz_j) < RADII.get(element_i, 0.8) + RADII.get(element_j, 0.8) + 0.45:
                neighbours[i].add(j)
                neighbours[j].add(i)
    return neighbours


def symmetric_rmsd(pose, reference) -> float:
    """In-place heavy-atom RMSD, minimised over every atom mapping that preserves the bond graph.

    Vina renames and reorders atoms, and a flipped phenyl ring is the same pose, so
    atoms are matched by element and bonding rather than by name.
    """
    if sorted(e for e, _ in pose) != sorted(e for e, _ in reference):
        raise ValueError("Pose and reference ligand have different heavy atoms.")
    pose_bonds, ref_bonds = bond_graph(pose), bond_graph(reference)
    # Visit pose atoms in breadth-first order so each new atom has a placed neighbour.
    order, seen = [], set()
    for start in range(len(pose)):
        queue = [start] if start not in seen else []
        seen.update(queue)
        while queue:
            atom = queue.pop(0)
            order.append(atom)
            for neighbour in sorted(pose_bonds[atom] - seen):
                seen.add(neighbour)
                queue.append(neighbour)
    best = [math.inf]

    def extend(depth: int, mapping: dict[int, int], used: set[int], total: float) -> None:
        if total >= best[0]:
            return
        if depth == len(order):
            best[0] = total
            return
        atom = order[depth]
        for candidate in range(len(reference)):
            if (candidate in used or reference[candidate][0] != pose[atom][0]
                    or len(ref_bonds[candidate]) != len(pose_bonds[atom])):
                continue
            if all((mapping[n] in ref_bonds[candidate]) for n in pose_bonds[atom] if n in mapping):
                mapping[atom] = candidate
                used.add(candidate)
                extend(depth + 1, mapping, used,
                       total + math.dist(pose[atom][1], reference[candidate][1]) ** 2)
                del mapping[atom]
                used.discard(candidate)

    extend(0, {}, set(), 0.0)
    if best[0] == math.inf:
        raise ValueError("Pose and reference ligand have different bonding.")
    return math.sqrt(best[0] / len(pose))


def report(result: dict, output: Path, complex_pdb: Path, residue: str, chain: str) -> None:
    (native,) = proteiniq_job.output_files(output, r"_output\.pdbqt$")
    reference = crystal_ligand(complex_pdb.read_text(encoding="utf-8"), residue, chain)
    rows = [(rank, affinity, symmetric_rmsd(atoms, reference))
            for rank, (affinity, atoms) in enumerate(read_poses(native), 1)]
    with open(output / "poses.csv", "w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle)
        writer.writerow(["rank", "affinity_kcal_mol", "rmsd_to_crystal_angstrom"])
        writer.writerows((rank, f"{affinity:.3f}", f"{rmsd:.2f}") for rank, affinity, rmsd in rows)
    print(f"{len(rows)} poses of {residue} against chain {chain} of {complex_pdb.stem}")
    print("rank  affinity (kcal/mol)  RMSD to crystal (A)")
    for rank, affinity, rmsd in rows:
        print(f"{rank:>4}  {affinity:>19.2f}  {rmsd:>19.2f}")
    # A heavy-atom RMSD under 2 Å is the usual threshold for a correctly reproduced pose.
    within = [rank for rank, _, rmsd in rows if rmsd < 2.0]
    print(f"Top pose {'reproduces' if rows[0][2] < 2.0 else 'misses'} the crystal pose; "
          f"poses within 2 A: {', '.join(map(str, within)) or 'none'}")
    print(f"Pose table: {output / 'poses.csv'}")


if __name__ == "__main__":
    arguments = proteiniq_job.parser(__doc__, "vina-output")
    arguments.add_argument("--complex", type=Path, required=True,
                           help="PDB file of the crystal complex; the receptor and reference come from it.")
    arguments.add_argument("--smiles", help="SMILES of the ligand to dock.")
    arguments.add_argument("--ligand-residue", default="STI", help="Residue name of the bound ligand.")
    arguments.add_argument("--ligand-chain", default="A", help="Chain of the bound ligand copy.")
    args = arguments.parse_args()
    if not args.resume and args.smiles is None:
        arguments.error("--smiles is required for a new run.")
    proteiniq_job.main(
        args,
        lambda: make_request(args.complex, args.smiles, args.ligand_residue, args.ligand_chain),
        lambda result, output: report(result, output, args.complex, args.ligand_residue, args.ligand_chain),
    )

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 request builder, pose parser and RMSD calculation are tested offline, and the RMSD values are checked against RDKit on the poses returned by the public AutoDock Vina example job of 19 July 2026. The results shown come from that job, which docked the same ligand into the same receptor and box with the same settings; the script itself has not yet been run against the live API.