Ling-MD/md-agent-skills / pymol-interface-hbond-figures
pymol-interface-hbond-figures
VerifiedUse when creating reusable PyMOL figures for protein-protein or chain-chain interfaces from PDB/MD snapshot files, especially when the user wants only protein kept, water/ions/ligands removed, inter-chain hydrogen-bonding residues shown as sticks, green dashed hydrogen bonds, chain-colored cartoons and labels, MM/PBSA-style blue/orange chain coloring, or a reproducible PML plus rendered PNG for other systems.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 3.9 KB |
| agents/openai.yaml | config | 328 B |
| references/interface-hbond-style.md | markdown | 2.4 KB |
| scripts/render_interface_hbonds.py | script | 14.2 KB |
scripts/render_interface_hbonds.py
View on GitHub#!/usr/bin/env python3
"""Render inter-chain hydrogen-bond interface figures from a PDB snapshot.
Run this with PyMOL's Python interpreter, for example:
C:\...\PyMOL\python.exe render_interface_hbonds.py --pdb snapshot.pdb
"""
from __future__ import annotations
import argparse
import csv
import math
import os
import sys
from pathlib import Path
def parse_hex_color(value: str) -> tuple[float, float, float]:
value = value.strip()
if value.startswith("#"):
value = value[1:]
if len(value) != 6:
raise argparse.ArgumentTypeError("colors must be #RRGGBB or RRGGBB")
return tuple(int(value[i : i + 2], 16) / 255.0 for i in (0, 2, 4))
def quote_path(path: Path) -> str:
return str(path).replace("\\", "/")
def atom_label(atom: dict) -> str:
return f"{atom['chain']}:{atom['resn']}{atom['resi']}:{atom['name']}"
def residue_key(atom: dict) -> tuple[str, str, str]:
return (atom["chain"], atom["resi"], atom["resn"])
def residue_label(key: tuple[str, str, str]) -> str:
chain, resi, resn = key
return f"{chain}:{resn}{resi}"
def selection_for_residue(obj: str, key: tuple[str, str, str]) -> str:
chain, resi, _resn = key
return f"({obj} and polymer.protein and chain {chain} and resi {resi})"
def distance(a: tuple[float, float, float], b: tuple[float, float, float]) -> float:
return math.sqrt(sum((a[i] - b[i]) ** 2 for i in range(3)))
def is_donor(atom: dict) -> bool:
elem = atom["elem"].upper()
name = atom["name"].upper()
resn = atom["resn"].upper()
if elem == "N":
return not (resn == "PRO" and name == "N")
if elem == "O" and name in {"OG", "OG1", "OH"}:
return resn in {"SER", "THR", "TYR"}
if elem == "S" and name == "SG":
return resn == "CYS"
return False
def is_acceptor(atom: dict) -> bool:
elem = atom["elem"].upper()
name = atom["name"].upper()
resn = atom["resn"].upper()
if elem == "O":
return True
if resn in {"HIS", "HID", "HIE", "HIP", "HSD", "HSE", "HSP"} and name in {"ND1", "NE2"}:
return True
if elem == "S" and name in {"SG", "SD"}:
return resn in {"CYS", "MET"}
return False
def is_hbond_candidate(a: dict, b: dict) -> bool:
return (is_donor(a) and is_acceptor(b)) or (is_acceptor(a) and is_donor(b))
def start_pymol():
try:
import pymol # type: ignore
from pymol import cmd # type: ignore
except Exception as exc: # pragma: no cover - only useful outside PyMOL
raise SystemExit(
"This script must be run with PyMOL's Python interpreter. "
"Use the PyMOL portable python.exe or pymol -cq."
) from exc
pymol.finish_launching(["pymol", "-qc"])
return cmd
def collect_atoms(cmd, obj: str) -> dict[int, dict]:
atoms: dict[int, dict] = {}
cmd.iterate_state(
1,
f"{obj} and polymer.protein",
"atoms[index] = {'model': model, 'index': index, 'name': name, 'resn': resn, "
"'resi': resi, 'chain': chain, 'elem': elem, 'coord': (x, y, z)}",
space={"atoms": atoms},
)
return atoms
def find_hbonds(cmd, obj: str, chain_a: str, chain_b: str, cutoff: float, angle: float):
sel_a = f"({obj} and polymer.protein and chain {chain_a} and elem N+O+S)"
sel_b = f"({obj} and polymer.protein and chain {chain_b} and elem N+O+S)"
raw_pairs = cmd.find_pairs(sel_a, sel_b, mode=1, cutoff=cutoff, angle=angle)
raw_pairs += [(b, a) for (a, b) in cmd.find_pairs(sel_b, sel_a, mode=1, cutoff=cutoff, angle=angle)]
atoms = collect_atoms(cmd, obj)
pairs = []
seen = set()
for left, right in raw_pairs:
i = int(left[1])
j = int(right[1])
if i not in atoms or j not in atoms:
continue
ai = atoms[i]
aj = atoms[j]
if ai["chain"] == aj["chain"]:
continue
if ai["elem"].upper() not in {"N", "O", "S"} or aj["elem"].upper() not in {"N", "O", "S"}:
continue
if not is_hbond_candidate(ai, aj):
continue
pair_key = tuple(sorted((i, j)))
if pair_key in seen:
continue
seen.add(pair_key)
pairs.append((ai, aj, distance(ai["coord"], aj["coord"])))
if pairs:
return pairs
# Conservative fallback for snapshots with missing hydrogens or PyMOL donor typing gaps.
heavy = [
a
for a in atoms.values()
if a["chain"] in {chain_a, chain_b} and a["elem"].upper() in {"N", "O", "S"}
]
for i, ai in enumerate(heavy):
for aj in heavy[i + 1 :]:
if ai["chain"] == aj["chain"]:
continue
if not is_hbond_candidate(ai, aj):
continue
d = distance(ai["coord"], aj["coord"])
if d <= cutoff:
pairs.append((ai, aj, d))
return pairs
def configure_scene(cmd, obj: str, args):
cmd.bg_color("white")
cmd.set("ray_opaque_background", "off")
cmd.set("antialias", 2)
cmd.set("ray_trace_mode", 1)
cmd.set("ray_shadows", "off")
cmd.set("ambient", 0.35)
cmd.set("direct", 0.65)
cmd.set("spec_reflect", 0.15)
cmd.set("cartoon_fancy_helices", "on")
cmd.set("cartoon_smooth_loops", "on")
cmd.set("depth_cue", "off")
cmd.set("orthoscopic", "on")
cmd.set("dash_width", 4)
cmd.set("dash_gap", 0.25)
cmd.set("dash_length", 0.20)
cmd.set("label_font_id", 7)
cmd.set("label_size", args.label_size)
cmd.set("label_outline_color", "white")
cmd.set("label_shadow_mode", 0)
cmd.set_color("chain_a_blue", list(args.chain_a_color))
cmd.set_color("chain_b_orange", list(args.chain_b_color))
cmd.set_color("hbond_green", list(args.hbond_color))
cmd.color("chain_a_blue", f"{obj} and chain {args.chain_a}")
cmd.color("chain_b_orange", f"{obj} and chain {args.chain_b}")
cmd.hide("everything", obj)
cmd.show("cartoon", f"{obj} and polymer.protein")
cmd.set("cartoon_transparency", args.cartoon_transparency, f"{obj} and polymer.protein")
cmd.remove(f"{obj} and not polymer.protein")
def write_tsvs(pairs, residues, pair_path: Path, residue_path: Path):
with pair_path.open("w", newline="", encoding="utf-8") as handle:
writer = csv.writer(handle, delimiter="\t")
writer.writerow(["atom_1", "atom_2", "distance_angstrom"])
for a, b, d in pairs:
writer.writerow([atom_label(a), atom_label(b), f"{d:.2f}"])
with residue_path.open("w", newline="", encoding="utf-8") as handle:
writer = csv.writer(handle, delimiter="\t")
writer.writerow(["chain", "residue", "resname", "label"])
for chain, resi, resn in residues:
writer.writerow([chain, resi, resn, residue_label((chain, resi, resn))])
def label_residues(cmd, obj: str, residues, args):
ordered = sorted(residues, key=lambda item: (item[0], int("".join(filter(str.isdigit, item[1])) or 0), item[1]))
offsets_a = [(-1.0, 0.6, 0.0), (-0.8, -0.6, 0.0), (-1.2, 1.0, 0.0), (-1.0, -1.0, 0.0)]
offsets_b = [(1.0, 0.6, 0.0), (0.8, -0.6, 0.0), (1.2, 1.0, 0.0), (1.0, -1.0, 0.0)]
chain_counts = {args.chain_a: 0, args.chain_b: 0}
for key in ordered:
chain, resi, resn = key
res_sel = selection_for_residue(obj, key)
cmd.show("sticks", res_sel)
cmd.set("stick_radius", args.stick_radius, res_sel)
cmd.color("chain_a_blue" if chain == args.chain_a else "chain_b_orange", f"{res_sel} and elem C")
cmd.color("atomic", f"{res_sel} and not elem C")
label_sel_name = f"lbl_{chain}_{resn}{resi}".replace("-", "_")
label_anchor = f"{res_sel} and name CA"
if cmd.count_atoms(label_anchor) == 0:
label_anchor = f"{res_sel} and name C+N+O"
cmd.select(label_sel_name, label_anchor)
cmd.label(label_sel_name, f"'{resn}{resi}'")
cmd.set("label_color", "chain_a_blue" if chain == args.chain_a else "chain_b_orange", label_sel_name)
offsets = offsets_a if chain == args.chain_a else offsets_b
offset = offsets[chain_counts.get(chain, 0) % len(offsets)]
chain_counts[chain] = chain_counts.get(chain, 0) + 1
cmd.set("label_position", list(offset), label_sel_name)
def write_pml(path: Path, args, residues, pairs):
obj = "snapshot"
lines = [
f"load {quote_path(args.pdb)}, {obj}",
f"remove {obj} and not polymer.protein",
"bg_color white",
"set ray_opaque_background, off",
"set antialias, 2",
"set ray_trace_mode, 1",
"set ray_shadows, off",
"set ambient, 0.35",
"set direct, 0.65",
"set spec_reflect, 0.15",
"set cartoon_fancy_helices, on",
"set cartoon_smooth_loops, on",
"set depth_cue, off",
"set orthoscopic, on",
f"set_color chain_a_blue, [{args.chain_a_color[0]:.3f}, {args.chain_a_color[1]:.3f}, {args.chain_a_color[2]:.3f}]",
f"set_color chain_b_orange, [{args.chain_b_color[0]:.3f}, {args.chain_b_color[1]:.3f}, {args.chain_b_color[2]:.3f}]",
f"set_color hbond_green, [{args.hbond_color[0]:.3f}, {args.hbond_color[1]:.3f}, {args.hbond_color[2]:.3f}]",
f"color chain_a_blue, {obj} and chain {args.chain_a}",
f"color chain_b_orange, {obj} and chain {args.chain_b}",
f"hide everything, {obj}",
f"show cartoon, {obj} and polymer.protein",
f"set cartoon_transparency, {args.cartoon_transparency}, {obj} and polymer.protein",
"set dash_width, 4",
"set dash_gap, 0.25",
"set dash_length, 0.20",
"set label_font_id, 7",
f"set label_size, {args.label_size}",
"set label_outline_color, white",
"set label_shadow_mode, 0",
]
for key in residues:
chain, resi, _resn = key
res_sel = selection_for_residue(obj, key)
lines += [
f"show sticks, {res_sel}",
f"set stick_radius, {args.stick_radius}, {res_sel}",
f"color {'chain_a_blue' if chain == args.chain_a else 'chain_b_orange'}, {res_sel} and elem C",
f"color atomic, {res_sel} and not elem C",
]
for idx, (a, b, _d) in enumerate(pairs, 1):
lines += [
f"distance hb_{idx:02d}, index {a['index']}, index {b['index']}",
f"color hbond_green, hb_{idx:02d}",
]
lines += [
f"zoom ({obj} and polymer.protein), {args.zoom_buffer}",
"orient",
f"png {quote_path(args.output_png)}, width={args.width}, height={args.height}, dpi={args.dpi}, ray={1 if args.ray else 0}",
"quit",
]
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
def render(args):
cmd = start_pymol()
obj = "snapshot"
cmd.reinitialize()
cmd.load(str(args.pdb), obj)
configure_scene(cmd, obj, args)
pairs = find_hbonds(cmd, obj, args.chain_a, args.chain_b, args.cutoff, args.angle)
residues = sorted({residue_key(a) for a, _b, _d in pairs} | {residue_key(b) for _a, b, _d in pairs})
if not pairs:
raise SystemExit("No inter-chain hydrogen bonds found with the current chain/cutoff settings.")
label_residues(cmd, obj, residues, args)
for idx, (a, b, _d) in enumerate(pairs, 1):
cmd.distance(f"hb_{idx:02d}", f"index {a['index']}", f"index {b['index']}")
cmd.color("hbond_green", f"hb_{idx:02d}")
cmd.zoom(f"({obj} and polymer.protein)", args.zoom_buffer)
cmd.orient(obj)
write_tsvs(pairs, residues, args.pair_tsv, args.residue_tsv)
write_pml(args.output_pml, args, residues, pairs)
cmd.png(str(args.output_png), width=args.width, height=args.height, dpi=args.dpi, ray=1 if args.ray else 0)
def build_arg_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Render a PyMOL interface hydrogen-bond figure.")
parser.add_argument("--pdb", required=True, type=Path, help="Input PDB snapshot.")
parser.add_argument("--chain-a", default="A", help="First protein chain ID.")
parser.add_argument("--chain-b", default="B", help="Second protein chain ID.")
parser.add_argument("--out-dir", type=Path, default=None, help="Output directory. Defaults to the PDB directory.")
parser.add_argument("--prefix", default=None, help="Output filename prefix. Defaults to the PDB stem.")
parser.add_argument("--chain-a-color", type=parse_hex_color, default=parse_hex_color("#0B7DB3"))
parser.add_argument("--chain-b-color", type=parse_hex_color, default=parse_hex_color("#E69F00"))
parser.add_argument("--hbond-color", type=parse_hex_color, default=parse_hex_color("#00C71F"))
parser.add_argument("--cutoff", type=float, default=3.6, help="Hydrogen-bond heavy atom cutoff in Angstrom.")
parser.add_argument("--angle", type=float, default=55.0, help="PyMOL find_pairs angle parameter.")
parser.add_argument("--width", type=int, default=2400)
parser.add_argument("--height", type=int, default=1800)
parser.add_argument("--dpi", type=int, default=300)
parser.add_argument("--no-ray", dest="ray", action="store_false", help="Render a fast OpenGL preview instead of ray tracing.")
parser.set_defaults(ray=True)
parser.add_argument("--cartoon-transparency", type=float, default=0.35)
parser.add_argument("--stick-radius", type=float, default=0.22)
parser.add_argument("--label-size", type=int, default=28)
parser.add_argument("--zoom-buffer", type=float, default=8.0)
return parser
def main(argv: list[str] | None = None) -> int:
parser = build_arg_parser()
args = parser.parse_args(argv)
args.pdb = args.pdb.resolve()
if not args.pdb.exists():
parser.error(f"PDB does not exist: {args.pdb}")
out_dir = args.out_dir.resolve() if args.out_dir else args.pdb.parent
out_dir.mkdir(parents=True, exist_ok=True)
prefix = args.prefix or args.pdb.stem
args.output_png = out_dir / f"{prefix}_interface_hbonds.png"
args.output_pml = out_dir / f"{prefix}_interface_hbonds.pml"
args.pair_tsv = out_dir / f"{prefix}_interface_hbond_pairs.tsv"
args.residue_tsv = out_dir / f"{prefix}_interface_hbond_residues.tsv"
render(args)
print(f"PNG: {args.output_png}")
print(f"PML: {args.output_pml}")
print(f"Pairs: {args.pair_tsv}")
print(f"Residues: {args.residue_tsv}")
sys.stdout.flush()
# PyMOL can leave GUI/backend threads alive after headless rendering on Windows.
os._exit(0)
return 0
if __name__ == "__main__":
raise SystemExit(main())
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack." | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |