API examples

Predict residue pKa values with PROPKA

Run PROPKA on ubiquitin from Python, then read the native report to see which groups shift from their model pKa, why, and which change charge near a chosen pH.

Download Python example · Shared job runner · Example code license

Lys27 of ubiquitin is the most buried charged group in the protein. In the 1.8 Å crystal structure, 1UBQ, PROPKA rates it 33% buried, and taking a positive charge away from water should make it easier to lose its proton. PROPKA agrees that burial pushes its pKa down by 1.15 units. Its predicted pKa, though, is 10.53, a shift of just +0.03 from the 10.50 of a free lysine. Asp52 sits next to it, and the salt bridge between them gives back everything the burial took away.

A shift of zero can hide two large effects pulling in opposite directions, which is why PROPKA's native report is worth reading line by line rather than only for its final pKa column. This example runs PROPKA on ubiquitin from Python with the ProteinIQ SDK, parses the determinants in the .pka report, and lists the groups that move furthest from their model values, the terms that move them, and the groups whose charge is uncertain at the pH you work at.

The result

The public example job ran PROPKA 3.5.1 on 1UBQ with default settings on 25 July 2026, in under a second of compute. Run on the same file, the script prints:

Text
1ubq: 26 ionizable groups, folded pI 7.07, net charge +0.03 at pH 7.0
Largest shifts from the model pKa:
  group        pKa  model  shift  buried  desolv  sc H-bond  bb H-bond  Coulomb
  ASP  58 A   2.99   3.80  -0.81      0%   +0.40      -0.23      -0.75    -0.23
  ASP  52 A   3.10   3.80  -0.70     14%   +0.64      -0.81      +0.00    -0.52
  LYS  11 A  11.02  10.50  +0.52      0%   -0.29      +0.43      +0.00    +0.38
  GLU  34 A   3.99   4.50  -0.51      0%   +0.42      -0.43      +0.00    -0.51
  HIS  68 A   6.00   6.50  -0.50      0%   -0.32      +0.00      +0.00    -0.18
Most buried: LYS  27 A, 33% buried: desolvation -1.15, H-bonds +0.81, Coulomb +0.38, net shift +0.03
  ASP  52 A alone contributes +1.28
Groups within 1 pH unit of pH 7.0, where both states are populated:
  HIS  68 A  pKa  6.00    9% in the charged form

Ubiquitin is small and mostly exposed to solvent, and none of its 26 groups moves by as much as one unit. The largest shift, Asp58 at -0.81, comes from hydrogen bonds rather than burial: the carboxylate accepts one from the side chain of Thr55 and one from its backbone amide, and a nearby Arg54 adds to the effect. Each of these stabilizes the charged carboxylate, so the group gives up its proton more easily and its pKa falls.

The salt bridges show up in pairs. Asp52 is lowered by 0.70 and Lys27 is held up by the same interaction; Lys11 is raised by 0.52 and Glu34 lowered by 0.51, mostly through one hydrogen bond and the Coulomb attraction between them. A salt bridge favors the state in which both partners are charged, so it pushes an acid's pKa down and a base's up.

These shifts are small next to PROPKA's own accuracy. The PROPKA 3 benchmark found root-mean-square errors of 0.65 to 1.00 pKa units depending on residue type, so every value here is consistent with a normal surface residue. Proteins with buried active sites look different: in the lysozyme example job, catalytic Glu35 is predicted at 6.52, 2.02 units above its model value.

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

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

Building the request

PROPKA takes one structure in a slot called protein, as PDB or mmCIF. The script reads the file, maps its extension to a format, and refuses a file with no ATOM records before anything is priced.

Python
def make_request(structure: Path) -> dict:
    protein = proteiniq_job.file_input(structure, "protein", "protein", STRUCTURE_FORMATS)
    if "ATOM" not in protein["content"]:
        raise ValueError(f"{structure.name} has no ATOM records for PROPKA to read.")
    settings = {"chain_ids": "", "titrate_only": "", "display_coupled_residues": False,
                "keep_protons": False, "ph": 7.0, "window_min": 0, "window_max": 14,
                "window_step": 1, "grid_min": 0, "grid_max": 14, "grid_step": 0.1}
    return {"tool": "propka", "input": {"inputs": [protein]}, "settings": settings}

The settings are the public job's, written out so that request.json records exactly what ran. Empty chain_ids and titrate_only titrate every recognized group in every chain. keep_protons stays off, so any hydrogens in the input are discarded when PROPKA reads the file. display_coupled_residues stays off too; turn it on for proteins with strongly interacting acid pairs, where PROPKA can report an alternative pair of pKa values.

ph is sent as 7.0, but in PROPKA 3.5.1 it changes neither the pKa values nor the report, so the script applies your pH itself after the job, as described below. The two scan windows, 0 to 14 in steps of 1 for the folding profile and 0.1 for the charge grid, are the defaults and set which rows the end of the report contains.

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 predict_pka.py --structure 1UBQ.pdb --output ubiquitin

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 predict_pka.py --structure 1UBQ.pdb --output ubiquitin --submit --max-credits YOUR_LIMIT

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

Reading the determinants

The job returns two files: propka-results.csv, one row per group with its pKa, model pKa and shift, and 1ubq.pka, PROPKA's native report. The CSV gives the answer; the report gives the reasons. Its determinants table has one block per group: the predicted pKa, a BURIED percentage, the desolvation terms, then one line per neighbor for side-chain hydrogen bonds, backbone hydrogen bonds and Coulomb interactions. This is the block for Lys27:

Text
LYS  27 A  10.53    33 %   -1.15  374   0.00    0    0.81 ASP  52 A    0.00 XXX   0 X    0.02 GLU  24 A
LYS  27 A                                            0.00 XXX   0 X    0.00 XXX   0 X    0.03 ASP  39 A
LYS  27 A                                            0.00 XXX   0 X    0.00 XXX   0 X    0.02 GLU  51 A
LYS  27 A                                            0.00 XXX   0 X    0.00 XXX   0 X   -0.18 ARG  72 A
LYS  27 A                                            0.00 XXX   0 X    0.00 XXX   0 X    0.02 TYR  59 A
LYS  27 A                                            0.00 XXX   0 X    0.00 XXX   0 X    0.47 ASP  52 A

BURIED comes from the 374 heavy atoms within 15 Å of the group, and desolvation is the -1.15 that follows it. XXX 0 X fills a column that has no partner on that line. Every number is in pKa units and is simply added to the model pKa, so the block reads as a sum: 10.50, minus 1.15 for burial, plus 0.81 for the hydrogen bond to Asp52, plus 0.38 from the six Coulomb neighbors, gives 10.54 against the printed 10.53. Across all 26 groups in this report, the terms add up to the printed pKa within 0.02.

determinants reads that table into one record per group. Each group label takes the first nine characters of a line, the first line of a block holds the pKa and burial, and every line holds up to three partner terms, each a value followed by a nine-character label.

Python
def determinants(text: str) -> dict[str, dict]:
    """Per-group terms from the .pka determinants table, keyed by labels like 'ASP  58 A'."""
    body = text.split("INTERACTION", 1)[1].split("SUMMARY OF THIS PREDICTION", 1)[0]
    groups: dict[str, dict] = {}
    for line in body.splitlines():
        label, rest = line[:9], line[9:]
        if not label.strip() or label.startswith("-"):
            continue
        first = FIRST_ROW.match(rest)
        if first:
            pka, buried, regular, reorganization, rest = first.groups()
            groups[label] = {"label": label, "pka": float(pka), "buried": int(buried),
                             "desolvation": float(regular) + float(reorganization),
                             "sidechain_hbond": 0.0, "backbone_hbond": 0.0, "coulombic": 0.0,
                             "partners": []}
        group = groups[label]
        # Each row holds one side-chain H-bond, one backbone H-bond and one Coulomb partner.
        for kind, (value, partner) in zip(("sidechain_hbond", "backbone_hbond", "coulombic"),
                                          TERM.findall(rest)):
            if not partner.startswith("XXX"):
                group[kind] += float(value)
                group["partners"].append((kind, float(value), partner))
    return groups

The model pKa values are in the summary further down, and groups_with_shifts joins them to the determinants to get each shift.

Python
def groups_with_shifts(text: str) -> list[dict]:
    groups = determinants(text)
    for label, model in model_pkas(text).items():
        if label in groups:
            groups[label].update(model_pka=model, shift=round(groups[label]["pka"] - model, 2))
    return [group for group in groups.values() if "model_pka" in group]

To name the neighbor behind a shift, strongest_partner adds up every term each neighbor contributes. For Lys27, Asp52 appears twice, once as a hydrogen bond and once as a Coulomb partner, for +1.28 in total, which is more than the burial costs.

Python
def strongest_partner(group: dict) -> tuple[str, float]:
    """The neighbor whose H-bond and Coulomb terms together move this pKa most."""
    totals: dict[str, float] = {}
    for _, value, partner in group["partners"]:
        totals[partner] = totals.get(partner, 0.0) + value
    partner = max(totals, key=lambda name: abs(totals[name]))
    return partner, round(totals[partner], 2)

Protonation at your pH

A pKa says where a group is half protonated. At any other pH, the Henderson-Hasselbalch equation gives the fraction that carries a proton: one unit away from the pKa leaves about 91% in the dominant state, and two units about 99%. Groups more than a unit from your pH can be given a single state with some confidence. Groups closer than that are populated both ways, and with prediction errors near one unit you should check both.

Python
def protonated_fraction(pka: float, ph: float) -> float:
    return 1 / (1 + 10 ** (ph - pka))

At pH 7.0, His68 is the only such group in ubiquitin: with a predicted pKa of 6.00, about 9% of it carries the positive charge. Because the script applies the pH after the job, you can change it without paying for another run. --resume finds the completed job, keeps the downloaded files whose checksums still match, and reports again:

Bash
python predict_pka.py --output ubiquitin --resume --ph 5.5

At pH 5.5, two glutamates join it:

Text
Groups within 1 pH unit of pH 5.5, where both states are populated:
  GLU  24 A  pKa  4.78   84% in the charged form
  GLU  51 A  pKa  4.56   90% in the charged form
  HIS  68 A  pKa  6.00   76% in the charged form

The net charge in the first line comes from the charge profile at the end of the .pka report, which PROPKA calculates for the folded and unfolded protein on a 0.1 pH grid. Ubiquitin's folded charge is +0.03 at pH 7.0 and its folded pI is 7.07, against 7.26 for the unfolded chain, whose groups all keep their model pKa values.

Python
def charge_profile(text: str) -> tuple[dict[float, float], float | None]:
    """Folded net charge by pH from the end of the report, and the folded pI."""
    section = text.split("Protein charge of folded and unfolded state", 1)[-1]
    charges = {float(m[1]): float(m[3]) for m in map(CHARGE_ROW.match, section.splitlines()) if m}
    pi = PI_LINE.search(text)
    return charges, float(pi[1]) if pi else None

report prints the summary and writes every group to pka_shifts.csv, with the terms and the protonated fraction at your pH:

Text
group,pka,model_pka,shift,buried_percent,desolvation,sidechain_hbond,backbone_hbond,coulombic,protonated_at_ph_7
ASP 21 A,3.36,3.8,-0.44,6,0.65,-0.08,-0.76,-0.26,0.0
ASP 32 A,3.92,3.8,0.12,0,0.15,0.0,0.0,-0.03,0.001
ASP 39 A,3.67,3.8,-0.13,0,0.3,0.0,0.0,-0.43,0.0
ASP 52 A,3.1,3.8,-0.7,14,0.64,-0.81,0.0,-0.52,0.0
Python
def report(result: dict, output: Path, ph: float = 7.0) -> None:
    (pka_file,) = proteiniq_job.output_files(output, r"\.pka$")
    text = pka_file.read_text(encoding="utf-8")
    groups = groups_with_shifts(text)
    charges, pi = charge_profile(text)
    # The charge profile is tabulated on PROPKA's pH grid; take the row nearest the chosen pH.
    charge = charges[min(charges, key=lambda grid: abs(grid - ph))] if charges else float("nan")
    print(f"{pka_file.stem.split('-', 1)[-1]}: {len(groups)} ionizable groups, folded pI {pi}, "
          f"net charge {charge:+.2f} at pH {ph:.1f}")
    print("Largest shifts from the model pKa:")
    print("  group        pKa  model  shift  buried  desolv  sc H-bond  bb H-bond  Coulomb")
    for g in sorted(groups, key=lambda g: -abs(g["shift"]))[:5]:
        print(f"  {g['label']}  {g['pka']:5.2f}  {g['model_pka']:5.2f}  {g['shift']:+5.2f}  {g['buried']:5d}%"
              f"  {g['desolvation']:+6.2f}  {g['sidechain_hbond']:+9.2f}  {g['backbone_hbond']:+9.2f}"
              f"  {g['coulombic']:+7.2f}")
    most = max(groups, key=lambda group: group["buried"])
    print(f"Most buried: {most['label']}, {most['buried']}% buried: desolvation {most['desolvation']:+.2f}, "
          f"H-bonds {most['sidechain_hbond'] + most['backbone_hbond']:+.2f}, Coulomb {most['coulombic']:+.2f}, "
          f"net shift {most['shift']:+.2f}")
    if most["partners"]:
        partner, total = strongest_partner(most)
        print(f"  {partner} alone contributes {total:+.2f}")
    print(f"Groups within 1 pH unit of pH {ph:.1f}, where both states are populated:")
    for g in groups:
        if abs(g["pka"] - ph) <= 1:
            fraction = protonated_fraction(g["pka"], ph)
            charged = 1 - fraction if g["label"][:3].strip() in ACIDS else fraction
            print(f"  {g['label']}  pKa {g['pka']:5.2f}  {charged:4.0%} in the charged form")
    with open(output / "pka_shifts.csv", "w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle)
        writer.writerow(["group", "pka", "model_pka", "shift", "buried_percent", "desolvation",
                         "sidechain_hbond", "backbone_hbond", "coulombic", f"protonated_at_ph_{ph:g}"])
        writer.writerows([" ".join(g["label"].split()), g["pka"], g["model_pka"], g["shift"], g["buried"],
                          round(g["desolvation"], 2), round(g["sidechain_hbond"], 2),
                          round(g["backbone_hbond"], 2), round(g["coulombic"], 2),
                          round(protonated_fraction(g["pka"], ph), 3)] for g in groups)
    print(f"Per-group table: {output / 'pka_shifts.csv'}")

Going further

PROPKA predicts from one conformation. A side chain that adopts a different rotamer in solution, or a loop that moves, can change a prediction, and a crystal structure with missing atoms should be repaired with PDBFixer before it is submitted. The PROPKA documentation covers coupled groups, ligand sites and the folding profile. For a drug molecule rather than a protein residue, the guide to predicting pKa online covers the small-molecule methods.

PROPKA returns pKa values, not a protonated structure. For simulation or electrostatics, PDB2PQR assigns protonation states, charges and radii at a chosen pH and can use PROPKA to do it. For a protein isoelectric point from the sequence alone, without a structure, IPC 2.0 gives a value to compare with the unfolded pI above.

Complete script

Python
"""Predict residue pKa values with PROPKA and explain the largest shifts.

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

import proteiniq_job

STRUCTURE_FORMATS = {".pdb": "pdb", ".ent": "ent", ".cif": "cif"}
# Groups that lose a proton to become charged; the rest gain one.
ACIDS = {"ASP", "GLU", "C-", "TYR", "CYS"}
NUMBER = r"(-?\d+\.\d+)"
FIRST_ROW = re.compile(rf"^\s*{NUMBER}\*?\s+(\d+)\s*%\s+{NUMBER}\s+\d+\s+{NUMBER}\s+\d+(.*)$")
TERM = re.compile(rf"{NUMBER} (\S.{{8}})")
SUMMARY_ROW = re.compile(rf"^   (\S.{{8}})\s+{NUMBER}\*?\s+{NUMBER}")
CHARGE_ROW = re.compile(rf"^\s*{NUMBER}\s+{NUMBER}\s+{NUMBER}\s*$")
PI_LINE = re.compile(rf"The pI is\s+{NUMBER} \(folded\) and\s+{NUMBER} \(unfolded\)")


def make_request(structure: Path) -> dict:
    protein = proteiniq_job.file_input(structure, "protein", "protein", STRUCTURE_FORMATS)
    if "ATOM" not in protein["content"]:
        raise ValueError(f"{structure.name} has no ATOM records for PROPKA to read.")
    settings = {"chain_ids": "", "titrate_only": "", "display_coupled_residues": False,
                "keep_protons": False, "ph": 7.0, "window_min": 0, "window_max": 14,
                "window_step": 1, "grid_min": 0, "grid_max": 14, "grid_step": 0.1}
    return {"tool": "propka", "input": {"inputs": [protein]}, "settings": settings}


def determinants(text: str) -> dict[str, dict]:
    """Per-group terms from the .pka determinants table, keyed by labels like 'ASP  58 A'."""
    body = text.split("INTERACTION", 1)[1].split("SUMMARY OF THIS PREDICTION", 1)[0]
    groups: dict[str, dict] = {}
    for line in body.splitlines():
        label, rest = line[:9], line[9:]
        if not label.strip() or label.startswith("-"):
            continue
        first = FIRST_ROW.match(rest)
        if first:
            pka, buried, regular, reorganization, rest = first.groups()
            groups[label] = {"label": label, "pka": float(pka), "buried": int(buried),
                             "desolvation": float(regular) + float(reorganization),
                             "sidechain_hbond": 0.0, "backbone_hbond": 0.0, "coulombic": 0.0,
                             "partners": []}
        group = groups[label]
        # Each row holds one side-chain H-bond, one backbone H-bond and one Coulomb partner.
        for kind, (value, partner) in zip(("sidechain_hbond", "backbone_hbond", "coulombic"),
                                          TERM.findall(rest)):
            if not partner.startswith("XXX"):
                group[kind] += float(value)
                group["partners"].append((kind, float(value), partner))
    return groups


def model_pkas(text: str) -> dict[str, float]:
    summary = text.split("SUMMARY OF THIS PREDICTION", 1)[1].split("-----", 1)[0]
    return {match[1]: float(match[3]) for match in map(SUMMARY_ROW.match, summary.splitlines()) if match}


def charge_profile(text: str) -> tuple[dict[float, float], float | None]:
    """Folded net charge by pH from the end of the report, and the folded pI."""
    section = text.split("Protein charge of folded and unfolded state", 1)[-1]
    charges = {float(m[1]): float(m[3]) for m in map(CHARGE_ROW.match, section.splitlines()) if m}
    pi = PI_LINE.search(text)
    return charges, float(pi[1]) if pi else None


def strongest_partner(group: dict) -> tuple[str, float]:
    """The neighbor whose H-bond and Coulomb terms together move this pKa most."""
    totals: dict[str, float] = {}
    for _, value, partner in group["partners"]:
        totals[partner] = totals.get(partner, 0.0) + value
    partner = max(totals, key=lambda name: abs(totals[name]))
    return partner, round(totals[partner], 2)


def protonated_fraction(pka: float, ph: float) -> float:
    return 1 / (1 + 10 ** (ph - pka))


def groups_with_shifts(text: str) -> list[dict]:
    groups = determinants(text)
    for label, model in model_pkas(text).items():
        if label in groups:
            groups[label].update(model_pka=model, shift=round(groups[label]["pka"] - model, 2))
    return [group for group in groups.values() if "model_pka" in group]


def report(result: dict, output: Path, ph: float = 7.0) -> None:
    (pka_file,) = proteiniq_job.output_files(output, r"\.pka$")
    text = pka_file.read_text(encoding="utf-8")
    groups = groups_with_shifts(text)
    charges, pi = charge_profile(text)
    # The charge profile is tabulated on PROPKA's pH grid; take the row nearest the chosen pH.
    charge = charges[min(charges, key=lambda grid: abs(grid - ph))] if charges else float("nan")
    print(f"{pka_file.stem.split('-', 1)[-1]}: {len(groups)} ionizable groups, folded pI {pi}, "
          f"net charge {charge:+.2f} at pH {ph:.1f}")
    print("Largest shifts from the model pKa:")
    print("  group        pKa  model  shift  buried  desolv  sc H-bond  bb H-bond  Coulomb")
    for g in sorted(groups, key=lambda g: -abs(g["shift"]))[:5]:
        print(f"  {g['label']}  {g['pka']:5.2f}  {g['model_pka']:5.2f}  {g['shift']:+5.2f}  {g['buried']:5d}%"
              f"  {g['desolvation']:+6.2f}  {g['sidechain_hbond']:+9.2f}  {g['backbone_hbond']:+9.2f}"
              f"  {g['coulombic']:+7.2f}")
    most = max(groups, key=lambda group: group["buried"])
    print(f"Most buried: {most['label']}, {most['buried']}% buried: desolvation {most['desolvation']:+.2f}, "
          f"H-bonds {most['sidechain_hbond'] + most['backbone_hbond']:+.2f}, Coulomb {most['coulombic']:+.2f}, "
          f"net shift {most['shift']:+.2f}")
    if most["partners"]:
        partner, total = strongest_partner(most)
        print(f"  {partner} alone contributes {total:+.2f}")
    print(f"Groups within 1 pH unit of pH {ph:.1f}, where both states are populated:")
    for g in groups:
        if abs(g["pka"] - ph) <= 1:
            fraction = protonated_fraction(g["pka"], ph)
            charged = 1 - fraction if g["label"][:3].strip() in ACIDS else fraction
            print(f"  {g['label']}  pKa {g['pka']:5.2f}  {charged:4.0%} in the charged form")
    with open(output / "pka_shifts.csv", "w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle)
        writer.writerow(["group", "pka", "model_pka", "shift", "buried_percent", "desolvation",
                         "sidechain_hbond", "backbone_hbond", "coulombic", f"protonated_at_ph_{ph:g}"])
        writer.writerows([" ".join(g["label"].split()), g["pka"], g["model_pka"], g["shift"], g["buried"],
                          round(g["desolvation"], 2), round(g["sidechain_hbond"], 2),
                          round(g["backbone_hbond"], 2), round(g["coulombic"], 2),
                          round(protonated_fraction(g["pka"], ph), 3)] for g in groups)
    print(f"Per-group table: {output / 'pka_shifts.csv'}")


if __name__ == "__main__":
    arguments = proteiniq_job.parser(__doc__, "propka-output")
    arguments.add_argument("--structure", type=Path, help="Protein structure (PDB or mmCIF).")
    arguments.add_argument("--ph", type=float, default=7.0, help="pH for the protonation summary.")
    args = arguments.parse_args()
    if not args.resume and args.structure is None:
        arguments.error("--structure is required for a new run.")
    if not 0 <= args.ph <= 14:
        arguments.error("--ph must be between 0 and 14, the range of PROPKA's charge profile.")
    proteiniq_job.main(args, lambda: make_request(args.structure),
                       lambda result, output: report(result, output, args.ph))

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 report parser are tested offline, and the parser is tested on the .pka report returned by the public PROPKA example job of 25 July 2026. The results shown come from that job, which ran the same 1UBQ file with the same settings; the script itself has not yet been run against the live API.