API examples
Profile protein-ligand interactions with PLIP
Run PLIP on indinavir bound to HIV protease (1HSG) from Python, then tabulate its hydrogen bonds, salt bridges, water bridges and hydrophobic contacts by residue.
Download Python example · Shared job runner · Example code license
HIV protease is a dimer of two identical chains, and its active site sits between them: each chain brings one essential Asp25, and two flaps close over the top when an inhibitor binds. When Chen and colleagues solved the complex with indinavir, 1HSG, they described the drug's hydroxyl reaching the carboxyl groups of both Asp25 residues, and two of its amide oxygens bonding to Ile50 of both chains through a single water molecule (Chen et al., 1994).
PLIP reads the same structure and lists every contact that passes its distance and angle rules. This example runs it from Python with the ProteinIQ SDK and turns PLIP's XML report into a table by residue. The table finds both of those features, each on one side of the dimer only, and it shows where a rule-based profile reports less than the crystallographers saw.
The result
The public example job profiled 1HSG, as deposited, on 3 November 2026 in 4 seconds of compute. Run on that job's report, the script prints:
MK1:B:902: 27 interactions with 21 residues
hydrophobic: 15
hydrogen bond: 6
water bridge: 4
salt bridge: 2
LEU23A hydrophobic 3.85
ASP25A salt bridge 5.26
GLY27A water bridge 3.44
ALA28A hydrophobic 3.81
VAL32A hydrophobic 3.77
ILE47A hydrophobic 3.73
GLY48A water bridge 2.93
ILE50A water bridge 2.68, water bridge 2.80
PRO81A hydrophobic 3.92
VAL82A hydrophobic 3.63
ILE84A hydrophobic 3.93
ARG8B hydrogen bond 4.07, hydrogen bond 3.46
ASP25B hydrogen bond 3.04, salt bridge 4.50
GLY27B hydrogen bond 3.03, hydrogen bond 3.16
ALA28B hydrophobic 3.66
ASP29B hydrogen bond 3.23
ASP30B hydrophobic 3.94
VAL32B hydrophobic 3.32
ILE47B hydrophobic 3.81, hydrophobic 3.85
ILE50B hydrophobic 3.78
PRO81B hydrophobic 3.87, hydrophobic 3.71MK1 is indinavir's ligand code, and the drug is modeled in chain B at position 902. It touches 21 residues across both chains, and more than half of its 27 contacts are hydrophobic, spread over 13 residues. That fits the paper, which credits hydrophobic contacts in the pseudo-symmetric pockets on either side of the catalytic center with a share of the affinity as large as that of the hydrogen bonds.
We matched the ligand coordinates in the report to the atoms of 1HSG to see which part of the drug makes each polar contact. The hydrogen bond to Asp25 of chain B, at 3.04 Å donor to acceptor, comes from the central hydroxyl. Ile50 of chain A holds the two amide oxygens through crystal water 308 of chain B, the bridging water the paper describes. Gly27 and Asp29 of chain B bond to the amide and hydroxyl at the indanol end of the drug, and Arg8 of chain B reaches the pyridine nitrogen.
Where the profile falls short of the crystal
The paper says the hydroxyl reaches both aspartates, but PLIP lists a hydrogen bond to Asp25 of chain B only. Asp25 of chain A appears just once, in a salt bridge to the piperazine amine at 5.26 Å, close to PLIP's 5.5 Å limit. Yet the hydroxyl oxygen is 2.77 Å from a carboxyl oxygen of Asp25 in chain A, well within hydrogen bond distance.
PLIP adds a single hydrogen to the hydroxyl and lets each donor make at most one hydrogen bond, the one with the better angle. That is the likely reason the second aspartate is missing; we did not measure the angles.
The bridging water shows the same kind of rule. It sits 2.93 Å from the backbone nitrogen of Ile50 in chain B, closer than to Ile50 of chain A, yet the table has no water bridge to chain B. PLIP lets each water take part in at most two bridges, and water 308 already has two, both to Ile50 of chain A.
Neither gap is a bug in PLIP. The salt bridges need a caveat of their own: PLIP treats every aspartate as negatively charged and assigns ligand charges by functional group, so a salt bridge row says nothing about the real protonation state. Read the polar rows as geometry that passed a rule, then check any contact you plan to argue about in the structure itself.
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 profile_interactions.py and proteiniq_job.py from the links at the top of this page into one folder. The first holds everything specific to PLIP; the second is the job runner that every Python example on these pages shares. Then fetch the structure:
curl -O https://files.rcsb.org/download/1HSG.pdbKeep the crystal waters. All four water bridges, the Ile50 water among them, exist only because the deposited file includes its waters, and a structure cleaned for docking would lose them.
Building the request
PLIP takes one PDB file in its structure slot and finds the ligands itself: in small-molecule mode, every residue that is neither water nor a standard amino acid becomes a binding site. PLIP needs something to profile, so the script checks for ligand HETATM records before it asks for a quote. Its list of ignored residue names covers water, common ions and a few buffer molecules; PLIP itself would still profile those as sites if they are present.
def ligand_residues(pdb_text: str) -> set[str]:
"""HETATM residue names other than water, common ions and buffer molecules."""
return {line[17:20].strip() for line in pdb_text.splitlines()
if line.startswith("HETATM") and line[17:20].strip() not in IGNORED_HETEROGENS}def make_request(structure: Path) -> dict:
complex_input = proteiniq_job.file_input(structure, "structure", "protein", FORMATS)
if not ligand_residues(complex_input["content"]):
raise ValueError(f"{structure.name} has no ligand HETATM records for PLIP to profile.")
settings = {
"analysis_mode": "small_molecule", "model": 1, "nohydro": False,
"hydroph_dist_max": 4.0, "hbond_dist_max": 4.1, "hbond_don_angle_min": 100,
"saltbridge_dist_max": 5.5, "pistack_dist_max": 5.5, "pication_dist_max": 6.0,
"halogen_dist_max": 4.0, "water_bridge_mindist": 2.5, "water_bridge_maxdist": 4.1,
}
return {"tool": "plip", "input": {"inputs": [complex_input]}, "settings": settings}The settings are PLIP's defaults, written out so that request.json records the rules the profile used. nohydro stays off, so PLIP adds polar hydrogens before it looks for hydrogen bonds; crystal structures rarely include hydrogens, and PLIP finds a donor only through an explicit one.
The limits are PLIP's defaults: 4.0 Å between carbons for a hydrophobic contact, 4.1 Å from donor to acceptor and an angle above 100° for a hydrogen bond, 5.5 Å between charge centers for a salt bridge, and 2.5 to 4.1 Å from each partner to the water for a water bridge. Change them only if you accept that the profile will no longer compare with published PLIP results.
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.
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:
python profile_interactions.py --structure 1HSG.pdb --output indinavir-contactsWhen 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.
python profile_interactions.py --structure 1HSG.pdb --output indinavir-contacts --submit --max-credits YOUR_LIMITIf the script is interrupted, run it again with --output indinavir-contacts --resume and it picks up the same job.
Reading the XML report
PLIP returns four files: plip_report.xml, plip_report.txt, the structure it analysed with hydrogens added (Complex_structure_protonated.pdb) and its log, plip_stderr.log. The text report draws one table per interaction type, which is easy to read and awkward to parse. The XML report holds the same interactions as tagged fields, along with every residue of the binding site and properties of the ligand, so the script reads that one.
Each interaction type stores its geometry under different names, and the script keeps one characteristic distance per row: the carbon to carbon distance for a hydrophobic contact, donor to acceptor for a hydrogen bond, acceptor to water for a water bridge, and the distance between charge centers for a salt bridge. The same mapping covers the types this complex lacks, π-stacking, π-cation interactions, halogen bonds and metal complexes.
def read_interactions(xml_report: Path) -> list[dict]:
"""One row per interaction in PLIP's XML report, across every binding site."""
rows = []
for site in ElementTree.parse(xml_report).getroot().iter("bindingsite"):
ids = site.find("identifiers")
ligand = ":".join(ids.findtext(tag, "").strip() for tag in ("hetid", "chain", "position"))
for kind, distance_field in DISTANCES.items():
for element in site.iter(kind):
rows.append({
"ligand": ligand, "type": kind.replace("_interaction", "").replace("_", " "),
"chain": element.findtext("reschain"), "residue": int(element.findtext("resnr")),
"name": element.findtext("restype"),
"distance": float(element.findtext(distance_field)),
})
return rowsThe rows are then grouped by residue. Sorting by chain and residue number puts the two halves of the dimer side by side, which makes the symmetry of the site, and where indinavir breaks it, easy to see.
def by_residue(rows: list[dict]) -> dict[tuple[str, int, str], list[dict]]:
"""Interactions grouped by protein residue, in chain and sequence order."""
groups = defaultdict(list)
for row in rows:
groups[(row["chain"], row["residue"], row["name"])].append(row)
return dict(sorted(groups.items()))report prints the counts and the residue table and writes every row to interactions.csv, which you can filter, sort or compare with the profile of another ligand:
ligand,type,chain,residue,name,distance
MK1:B:902,hydrophobic,A,23,LEU,3.85
MK1:B:902,hydrophobic,A,28,ALA,3.81
MK1:B:902,hydrophobic,B,28,ALA,3.66def report(result: dict, output: Path) -> None:
(xml_report,) = proteiniq_job.output_files(output, r"\.xml$")
rows = read_interactions(xml_report)
if not rows:
print("PLIP found no interactions.")
return
with open(output / "interactions.csv", "w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
residues = by_residue(rows)
ligands = ", ".join(sorted({row["ligand"] for row in rows}))
print(f"{ligands}: {len(rows)} interactions with {len(residues)} residues")
for kind, count in Counter(row["type"] for row in rows).most_common():
print(f" {kind:>17}: {count}")
for (chain, number, name), contacts in residues.items():
detail = ", ".join(f"{row['type']} {row['distance']:.2f}" for row in contacts)
label = f"{name}{number}{chain}"
print(f" {label:<8} {detail}")
print(f"Interaction table: {output / 'interactions.csv'}")The XML report has more than the script prints. Its bs_residue list gives every residue within 7.5 Å of the ligand and its shortest distance to it, which is where the 2.8 Å contact with Asp25 of chain A shows up even though no interaction row names it. lig_properties gives counts such as num_heavy_atoms, 45 for indinavir, which helps when you compare contact counts between ligands of different sizes.
Going further
PLIP describes contacts, not energies: a hydrogen bond at 2.7 Å and one at 4.0 Å are one row each. To profile a docked pose instead of a crystal ligand, merge the receptor and the pose into one PDB file with the ligand as HETATM records, as the PLIP tool page explains; the AutoDock Vina example produces such poses. Docked poses carry no crystal waters, so their profiles have no water bridges, and that difference alone changes how they compare with the crystal.
Other programs apply other rules to the same complex. For indinavir in 1HSG, PLIP, PoseView and the PDB viewer by ProteinIQ return three different hydrogen bond lists; the protein-ligand interactions guide explains what each interaction type measures.
Complete script
"""Profile the noncovalent contacts between a protein and its bound ligand with PLIP.
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
from collections import Counter, defaultdict
from pathlib import Path
import xml.etree.ElementTree as ElementTree
import proteiniq_job
FORMATS = {".pdb": "pdb", ".ent": "ent"}
# Each PLIP interaction type and the XML field that holds its characteristic distance.
DISTANCES = {
"hydrophobic_interaction": "dist", "hydrogen_bond": "dist_d-a", "water_bridge": "dist_a-w",
"salt_bridge": "dist", "pi_stack": "centdist", "pi_cation_interaction": "dist",
"halogen_bond": "dist", "metal_complex": "dist",
}
IGNORED_HETEROGENS = {"HOH", "WAT", "DOD", "NA", "CL", "K", "MG", "CA", "ZN", "SO4", "PO4", "GOL", "EDO"}
def ligand_residues(pdb_text: str) -> set[str]:
"""HETATM residue names other than water, common ions and buffer molecules."""
return {line[17:20].strip() for line in pdb_text.splitlines()
if line.startswith("HETATM") and line[17:20].strip() not in IGNORED_HETEROGENS}
def make_request(structure: Path) -> dict:
complex_input = proteiniq_job.file_input(structure, "structure", "protein", FORMATS)
if not ligand_residues(complex_input["content"]):
raise ValueError(f"{structure.name} has no ligand HETATM records for PLIP to profile.")
settings = {
"analysis_mode": "small_molecule", "model": 1, "nohydro": False,
"hydroph_dist_max": 4.0, "hbond_dist_max": 4.1, "hbond_don_angle_min": 100,
"saltbridge_dist_max": 5.5, "pistack_dist_max": 5.5, "pication_dist_max": 6.0,
"halogen_dist_max": 4.0, "water_bridge_mindist": 2.5, "water_bridge_maxdist": 4.1,
}
return {"tool": "plip", "input": {"inputs": [complex_input]}, "settings": settings}
def read_interactions(xml_report: Path) -> list[dict]:
"""One row per interaction in PLIP's XML report, across every binding site."""
rows = []
for site in ElementTree.parse(xml_report).getroot().iter("bindingsite"):
ids = site.find("identifiers")
ligand = ":".join(ids.findtext(tag, "").strip() for tag in ("hetid", "chain", "position"))
for kind, distance_field in DISTANCES.items():
for element in site.iter(kind):
rows.append({
"ligand": ligand, "type": kind.replace("_interaction", "").replace("_", " "),
"chain": element.findtext("reschain"), "residue": int(element.findtext("resnr")),
"name": element.findtext("restype"),
"distance": float(element.findtext(distance_field)),
})
return rows
def by_residue(rows: list[dict]) -> dict[tuple[str, int, str], list[dict]]:
"""Interactions grouped by protein residue, in chain and sequence order."""
groups = defaultdict(list)
for row in rows:
groups[(row["chain"], row["residue"], row["name"])].append(row)
return dict(sorted(groups.items()))
def report(result: dict, output: Path) -> None:
(xml_report,) = proteiniq_job.output_files(output, r"\.xml$")
rows = read_interactions(xml_report)
if not rows:
print("PLIP found no interactions.")
return
with open(output / "interactions.csv", "w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
residues = by_residue(rows)
ligands = ", ".join(sorted({row["ligand"] for row in rows}))
print(f"{ligands}: {len(rows)} interactions with {len(residues)} residues")
for kind, count in Counter(row["type"] for row in rows).most_common():
print(f" {kind:>17}: {count}")
for (chain, number, name), contacts in residues.items():
detail = ", ".join(f"{row['type']} {row['distance']:.2f}" for row in contacts)
label = f"{name}{number}{chain}"
print(f" {label:<8} {detail}")
print(f"Interaction table: {output / 'interactions.csv'}")
if __name__ == "__main__":
arguments = proteiniq_job.parser(__doc__, "plip-output")
arguments.add_argument("--structure", type=Path, help="PDB file of the protein-ligand complex.")
args = arguments.parse_args()
if not args.resume and args.structure is None:
arguments.error("--structure is required for a new run.")
proteiniq_job.main(args, lambda: make_request(args.structure), report)The shared job runner, proteiniq_job.py:
"""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 is tested offline, and its XML parser is tested on the report returned by the public PLIP example job of 3 November 2026. The results shown come from that job, which profiled the same structure with the same settings; the script itself has not yet been run against the live API.