API examples
Align protein sequences with Clustal Omega
Align human, mouse and chicken β-globin in Python, then compute column conservation and pairwise identity and check the heme-binding histidines.
Download Python example · Shared job runner · Example code license
The heme group in hemoglobin's β chain is held by two histidines, one on each face of the iron. Change either and the protein suffers: UniProt lists four human variants at the proximal histidine, all unstable, and Hb M-Saskatoon, with tyrosine in place of the distal one, binds oxygen more tightly. Residues under that kind of constraint should look the same in every vertebrate, while the surface of the protein drifts.
Clustal Omega aligns human, mouse and chicken β-globin in a fraction of a second. This example runs it from Python with the ProteinIQ SDK and then reads the alignment with plain Python: how many columns are identical in all three species, how similar each pair is, and what sits at the positions you ask about.
The result
The public example job aligned the three sequences with Clustal Omega 1.2.4 on 24 July 2026 in under a second of compute. Run on that alignment and asked about positions 7, 64 and 93, the script prints:
3 sequences, 147 columns, 0 with gaps
Identical in every sequence: 91 columns (61.9%)
Pairwise identity:
P68871_HBB_HUMAN vs P02088_HBB1_MOUSE: 80.3%
P68871_HBB_HUMAN vs P02112_HBB_CHICK: 69.4%
P02088_HBB1_MOUSE vs P02112_HBB_CHICK: 65.3%
Conserved blocks of 10+ columns, numbered by P68871_HBB_HUMAN:
89-108 LSELHCDKLHVDPENFRLLG
P68871_HBB_HUMAN E7: E A E (varies)
P68871_HBB_HUMAN H64: H H H (identical)
P68871_HBB_HUMAN H93: H H H (identical)All three chains are 147 residues long and the alignment needs no gaps, so column numbers and residue numbers are the same in every species. 91 of the 147 columns, 61.9%, hold the same residue in all three. Mouse and human share 80.3% of their residues, while chicken shares 69.4% with human and 65.3% with mouse. The two mammals are closer to each other than either is to the bird, as their ancestry predicts.
Both heme histidines are identical in all three species. UniProt annotates His64 as the distal residue and His93 as the proximal one that binds the iron, and His93 falls inside the longest identical stretch in the alignment, the 20 residues from Leu89 to Gly108.
UniProt counts the initiator methionine as residue 1. Hemoglobin researchers number the mature chain without it, so the literature calls the same residues His63 and His92, or E7 and F8 by their helix positions. Keep that offset of one in mind when you compare this output with a paper.
Position 7 is the contrast. It is Glu6 in clinical numbering, the residue that sickle cell hemoglobin replaces with valine, and in mouse it is alanine. UniProt lists the same glutamate to alanine change in humans as Hb G-Makassar. A position can vary between species and still matter in one of them, so conservation is evidence about constraint, not a verdict on any single mutation.
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 align_sequences.py and proteiniq_job.py from the links at the top of this page into one folder. The first holds everything specific to Clustal Omega; the second is the job runner that every Python example on these pages shares. Then save the three sequences, which are the full UniProt entries P68871, P02088 and P02112 with shorter headers:
cat > beta_globins.fasta <<'EOF'
>P68871_HBB_HUMAN
MVHLTPEEKSAVTALWGKVNVDEVGGEALGRLLVVYPWTQRFFESFGDLSTPDAVMGNPKVKAHGKKVLGAFSDGLAHLDNLKGTFATLSELHCDKLHVDPENFRLLGNVLVCVLAHHFGKEFTPPVQAAYQKVVAGVANALAHKYH
>P02088_HBB1_MOUSE
MVHLTDAEKAAVSCLWGKVNSDEVGGEALGRLLVVYPWTQRYFDSFGDLSSASAIMGNAKVKAHGKKVITAFNDGLNHLDSLKGTFASLSELHCDKLHVDPENFRLLGNMIVIVLGHHLGKDFTPAAQAAFQKVVAGVATALAHKYH
>P02112_HBB_CHICK
MVHWTAEEKQLITGLWGKVNVAECGAEALARLLIVYPWTQRFFASFGNLSSPTAILGNPMVRAHGKKVLTSFGDAVKNLDNIKNTFSQLSELHCDKLHVDPENFRLLGDILIIVLAAHFSKDFTPECQAAWQKLVRVVAHALARKYH
EOFTo align your own set, curl https://rest.uniprot.org/uniprotkb/P68871.fasta returns any entry as FASTA. Keep the headers short and unique, because the script keys each row of the alignment by its name.
Building the request
Clustal Omega takes sequences in a slot called sequences. The script reads the FASTA file, joins wrapped lines, and stops before anything is sent if there are fewer than two sequences, a header is missing or repeated, or a sequence contains letters that are not amino acid codes.
def read_fasta(fasta: Path) -> list[tuple[str, str]]:
records, name = [], None
for line in fasta.read_text(encoding="utf-8").splitlines():
line = line.strip()
if line.startswith(">"):
name = line[1:].split()[0] if line[1:].strip() else ""
records.append([name, ""])
elif line:
if name is None:
raise ValueError("Start the file with a >name header line.")
records[-1][1] += line.upper()
names = [name for name, _ in records]
if len(records) < 2:
raise ValueError("Clustal Omega needs at least 2 sequences.")
if "" in names or len(set(names)) != len(names):
raise ValueError("Give every sequence its own unique name after the >.")
for name, sequence in records:
unknown = set(sequence) - AMINO_ACIDS
if not sequence or unknown:
raise ValueError(f"{name}: not a protein sequence; unexpected letters {sorted(unknown)}")
return [(name, sequence) for name, sequence in records]The settings match the public job and are written out so that request.json records exactly what ran. sequence_type is fixed to Protein rather than auto-detected. output_format is clustal because that format carries Clustal Omega's own conservation line, which the tests use as a check on the parser; FASTA is the default and the easier format to pass to other tools.
iterations is 1, so Clustal Omega rebuilds its guide tree from the first alignment and realigns once; the native default of 0 skips that step. output_order keeps the rows in input order, which makes the first sequence the reference for numbering.
def make_request(fasta: Path) -> dict:
records = read_fasta(fasta)
content = "\n".join(f">{name}\n{sequence}" for name, sequence in records)
sequences = proteiniq_job.text_input("sequences", "msa", "fasta", content, fasta.stem)
settings = {"sequence_type": "Protein", "output_format": "clustal", "iterations": 1,
"use_full_matrix": False, "output_order": "input-order", "dealign": False,
"output_distance_matrix": False, "output_guide_tree": False}
return {"tool": "clustal-omega", "input": {"inputs": [sequences]}, "settings": settings}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 align_sequences.py --sequences beta_globins.fasta --output globinsWhen the price looks right, add --submit and replace YOUR_LIMIT with the credits you approve. --positions takes residue numbers in the first sequence and prints what every species has there.
python align_sequences.py --sequences beta_globins.fasta --output globins --positions 7,64,93 --submit --max-credits YOUR_LIMITIf the script is interrupted, run it again with --output globins --resume and it picks up the same job.
Reading the alignment
The public job returned one file, UniProt_vertebrate_beta-globins_aligned.aln, named after its input label. A new run takes the label from your FASTA file name and also returns a run log, which the script leaves alone.
Clustal format splits each row into blocks of 60 columns with the sequence name at the start of every line, and puts the conservation track on lines that begin with spaces. The parser skips those lines, joins the blocks into one row per sequence, and checks that every row came out the same length.
def read_clustal(path: Path) -> dict[str, str]:
"""Join the blocks of a Clustal file into one aligned row per sequence."""
lines = path.read_text(encoding="utf-8").splitlines()
if not lines or not lines[0].startswith("CLUSTAL"):
raise ValueError(f"{path.name} is not a Clustal alignment")
rows: dict[str, str] = {}
for line in lines[1:]:
# Blank lines separate blocks; lines starting with a space hold the * : . track.
if not line.strip() or line[0].isspace():
continue
name, segment, *_ = line.split()
rows[name] = rows.get(name, "") + segment
if len({len(row) for row in rows.values()}) != 1:
raise ValueError(f"Rows in {path.name} have different lengths")
return rowsClustal's track marks a fully identical column with *, a column of strongly similar residues with : and a weakly similar one with .. In this alignment it has 91 stars, 24 colons and 8 dots, and the script's count of identical columns agrees with the stars.
Percent identity has several definitions in use, which is why numbers from different programs do not always match.
This one counts identical residues over the columns where neither sequence has a gap, so a long insertion in one sequence does not drag the value down. With no gaps in this alignment, every definition that divides by aligned positions gives the same answer. If you want Clustal Omega's own figures, turn on output_distance_matrix, or the percent identity matrix under the advanced settings.
def percent_identity(a: str, b: str) -> float:
"""Identical residues over columns where neither sequence has a gap."""
pairs = [(x, y) for x, y in zip(a, b) if x != "-" and y != "-"]
return 100 * sum(x == y for x, y in pairs) / len(pairs)Column numbers mean little to a reader; residue numbers do. columns walks the alignment once and numbers each column by the residue it holds in the reference sequence, leaving gap columns unnumbered, so the positions you pass to --positions are the ones in the reference's UniProt entry or structure.
def columns(rows: dict[str, str], reference: str) -> list[dict]:
"""One record per column, numbered by the reference sequence's own residues."""
number, table = 0, []
for index, residues in enumerate(zip(*rows.values()), 1):
if rows[reference][index - 1] != "-":
number += 1
table.append({
"column": index,
"reference_residue": number if rows[reference][index - 1] != "-" else None,
"residues": "".join(residues),
"identical": "-" not in residues and len(set(residues)) == 1,
})
return tableSingle identical columns happen by chance when sequences are as close as these. Long runs of them are more telling, so the script reports every stretch of at least 10 identical columns.
def conserved_blocks(table: list[dict], minimum: int = 10) -> list[tuple[int, int]]:
"""Runs of at least `minimum` identical columns, as (first, last) column numbers."""
blocks, start = [], None
for record in table + [{"column": len(table) + 1, "identical": False}]:
if record["identical"] and start is None:
start = record["column"]
elif not record["identical"] and start is not None:
if record["column"] - start >= minimum:
blocks.append((start, record["column"] - 1))
start = None
return blocksreport prints the summary and writes every column to conservation.csv, ready to sort, plot, or map onto a structure. These are the rows around the proximal histidine:
column,P68871_HBB_HUMAN_residue,P68871_HBB_HUMAN,P02088_HBB1_MOUSE,P02112_HBB_CHICK,identical
88,88,T,S,Q,False
89,89,L,L,L,True
90,90,S,S,S,True
91,91,E,E,E,True
92,92,L,L,L,True
93,93,H,H,H,True
94,94,C,C,C,Truedef report(result: dict, output: Path, positions: list[int] = ()) -> None:
(alignment,) = proteiniq_job.output_files(output, r"\.aln$")
rows = read_clustal(alignment)
names = list(rows)
reference = names[0]
table = columns(rows, reference)
with open(output / "conservation.csv", "w", newline="", encoding="utf-8") as handle:
writer = csv.writer(handle)
writer.writerow(["column", f"{reference}_residue", *names, "identical"])
for record in table:
writer.writerow([record["column"], record["reference_residue"] or "",
*record["residues"], record["identical"]])
identical = sum(record["identical"] for record in table)
gapped = sum("-" in record["residues"] for record in table)
print(f"{len(names)} sequences, {len(table)} columns, {gapped} with gaps")
print(f"Identical in every sequence: {identical} columns ({100 * identical / len(table):.1f}%)")
print("Pairwise identity:")
for a, b in combinations(names, 2):
print(f" {a} vs {b}: {percent_identity(rows[a], rows[b]):.1f}%")
sequence = rows[reference]
print(f"Conserved blocks of 10+ columns, numbered by {reference}:")
for first, last in conserved_blocks(table):
start, end = table[first - 1]["reference_residue"], table[last - 1]["reference_residue"]
print(f" {start}-{end} {sequence[first - 1:last]}")
by_residue = {record["reference_residue"]: record for record in table}
for position in positions:
record = by_residue.get(position)
if record is None:
print(f" {reference} has no residue {position}")
continue
state = "identical" if record["identical"] else "varies"
print(f"{reference} {sequence[record['column'] - 1]}{position}: "
f"{' '.join(record['residues'])} ({state})")
print(f"Per-column table: {output / 'conservation.csv'}")Going further
Three closely related sequences make a small sample, and some of their 91 identical columns may be shared only because too little time has passed to change them. Add more distant relatives, such as human α-globin (P69905) or myoglobin (P02144), and the columns that stay identical become much stronger evidence that a position matters.
Distant relatives also bring gaps, which is where the choice of aligner starts to show; MAFFT vs MUSCLE vs Clustal Omega compares the three on a standard benchmark, and MAFFT and MUSCLE 5 run the same way from the API.
An alignment is also the input to a tree. The IQ-TREE example builds a maximum likelihood tree from an alignment of nine primate mitochondrial genomes and reads its clades and support values. To see where the conserved residues sit in space, fold the reference sequence as in the ESMFold example and color the model by the identical column.
Complete script
"""Align protein sequences with Clustal Omega and measure how conserved they are.
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 itertools import combinations
from pathlib import Path
import proteiniq_job
AMINO_ACIDS = set("ACDEFGHIKLMNPQRSTVWYBZXUO")
def read_fasta(fasta: Path) -> list[tuple[str, str]]:
records, name = [], None
for line in fasta.read_text(encoding="utf-8").splitlines():
line = line.strip()
if line.startswith(">"):
name = line[1:].split()[0] if line[1:].strip() else ""
records.append([name, ""])
elif line:
if name is None:
raise ValueError("Start the file with a >name header line.")
records[-1][1] += line.upper()
names = [name for name, _ in records]
if len(records) < 2:
raise ValueError("Clustal Omega needs at least 2 sequences.")
if "" in names or len(set(names)) != len(names):
raise ValueError("Give every sequence its own unique name after the >.")
for name, sequence in records:
unknown = set(sequence) - AMINO_ACIDS
if not sequence or unknown:
raise ValueError(f"{name}: not a protein sequence; unexpected letters {sorted(unknown)}")
return [(name, sequence) for name, sequence in records]
def make_request(fasta: Path) -> dict:
records = read_fasta(fasta)
content = "\n".join(f">{name}\n{sequence}" for name, sequence in records)
sequences = proteiniq_job.text_input("sequences", "msa", "fasta", content, fasta.stem)
settings = {"sequence_type": "Protein", "output_format": "clustal", "iterations": 1,
"use_full_matrix": False, "output_order": "input-order", "dealign": False,
"output_distance_matrix": False, "output_guide_tree": False}
return {"tool": "clustal-omega", "input": {"inputs": [sequences]}, "settings": settings}
def read_clustal(path: Path) -> dict[str, str]:
"""Join the blocks of a Clustal file into one aligned row per sequence."""
lines = path.read_text(encoding="utf-8").splitlines()
if not lines or not lines[0].startswith("CLUSTAL"):
raise ValueError(f"{path.name} is not a Clustal alignment")
rows: dict[str, str] = {}
for line in lines[1:]:
# Blank lines separate blocks; lines starting with a space hold the * : . track.
if not line.strip() or line[0].isspace():
continue
name, segment, *_ = line.split()
rows[name] = rows.get(name, "") + segment
if len({len(row) for row in rows.values()}) != 1:
raise ValueError(f"Rows in {path.name} have different lengths")
return rows
def percent_identity(a: str, b: str) -> float:
"""Identical residues over columns where neither sequence has a gap."""
pairs = [(x, y) for x, y in zip(a, b) if x != "-" and y != "-"]
return 100 * sum(x == y for x, y in pairs) / len(pairs)
def columns(rows: dict[str, str], reference: str) -> list[dict]:
"""One record per column, numbered by the reference sequence's own residues."""
number, table = 0, []
for index, residues in enumerate(zip(*rows.values()), 1):
if rows[reference][index - 1] != "-":
number += 1
table.append({
"column": index,
"reference_residue": number if rows[reference][index - 1] != "-" else None,
"residues": "".join(residues),
"identical": "-" not in residues and len(set(residues)) == 1,
})
return table
def conserved_blocks(table: list[dict], minimum: int = 10) -> list[tuple[int, int]]:
"""Runs of at least `minimum` identical columns, as (first, last) column numbers."""
blocks, start = [], None
for record in table + [{"column": len(table) + 1, "identical": False}]:
if record["identical"] and start is None:
start = record["column"]
elif not record["identical"] and start is not None:
if record["column"] - start >= minimum:
blocks.append((start, record["column"] - 1))
start = None
return blocks
def report(result: dict, output: Path, positions: list[int] = ()) -> None:
(alignment,) = proteiniq_job.output_files(output, r"\.aln$")
rows = read_clustal(alignment)
names = list(rows)
reference = names[0]
table = columns(rows, reference)
with open(output / "conservation.csv", "w", newline="", encoding="utf-8") as handle:
writer = csv.writer(handle)
writer.writerow(["column", f"{reference}_residue", *names, "identical"])
for record in table:
writer.writerow([record["column"], record["reference_residue"] or "",
*record["residues"], record["identical"]])
identical = sum(record["identical"] for record in table)
gapped = sum("-" in record["residues"] for record in table)
print(f"{len(names)} sequences, {len(table)} columns, {gapped} with gaps")
print(f"Identical in every sequence: {identical} columns ({100 * identical / len(table):.1f}%)")
print("Pairwise identity:")
for a, b in combinations(names, 2):
print(f" {a} vs {b}: {percent_identity(rows[a], rows[b]):.1f}%")
sequence = rows[reference]
print(f"Conserved blocks of 10+ columns, numbered by {reference}:")
for first, last in conserved_blocks(table):
start, end = table[first - 1]["reference_residue"], table[last - 1]["reference_residue"]
print(f" {start}-{end} {sequence[first - 1:last]}")
by_residue = {record["reference_residue"]: record for record in table}
for position in positions:
record = by_residue.get(position)
if record is None:
print(f" {reference} has no residue {position}")
continue
state = "identical" if record["identical"] else "varies"
print(f"{reference} {sequence[record['column'] - 1]}{position}: "
f"{' '.join(record['residues'])} ({state})")
print(f"Per-column table: {output / 'conservation.csv'}")
if __name__ == "__main__":
arguments = proteiniq_job.parser(__doc__, "clustal-omega-output")
arguments.add_argument("--sequences", type=Path, help="FASTA file with 2 or more protein sequences.")
arguments.add_argument("--positions", type=lambda text: [int(n) for n in text.split(",")], default=[],
help="Comma-separated residue numbers in the first sequence to report.")
args = arguments.parse_args()
if not args.resume and args.sequences is None:
arguments.error("--sequences is required for a new run.")
proteiniq_job.main(args, lambda: make_request(args.sequences),
lambda result, output: report(result, output, args.positions))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's request builder and alignment parser are tested offline, and its conservation analysis is tested on the alignment returned by the public Clustal Omega example job of 24 July 2026. The results shown come from that job, which aligned the same sequences with the same settings; the script itself has not yet been run against the live API.