Source: https://github.com/aipoch/medical-research-skills
biopython-structure
When to Use
- You need to parse PDB or mmCIF files and access the structure hierarchy (model → chain → residue → atom).
- You want to compute geometric measurements such as distances, bond angles, and dihedral angles between atoms/residues.
- You need neighbor searches (e.g., find residues/atoms within a cutoff) for contact analysis or local environment inspection.
- You want to perform structural comparison, including alignment/superposition and RMSD-style evaluation.
- You need to extract, modify, and save structures (e.g., subset chains/residues and write back to PDB/mmCIF).
Key Features
- Structure parsing for PDB/mmCIF using
Bio.PDB parsers.
- Hierarchical traversal and selection of models, chains, residues, and atoms.
- Geometry calculations: distance, angle, and dihedral computations using Bio.PDB utilities.
- Neighbor search via spatial indexing (
NeighborSearch) for efficient cutoff queries.
- Structural operations: extraction, saving, and superposition (e.g.,
Superimposer).
- Quality/annotation hooks: optional integration with DSSP (external executable) for secondary structure and accessibility.
Dependencies
biopython (>= 1.79)
numpy (>= 1.21)
- Optional:
DSSP executable (e.g., mkdssp, version depends on your system installation)
Example Usage
Create config/task_config.json:
{
"input_path": "data/1ubq.pdb",
"format": "pdb",
"chain_id": "A",
"atom_name": "CA",
"distance_cutoff": 8.0,
"output_path": "outputs/chainA_ca_neighbors.json"
}
Create scripts/neighbor_search.py:
import json
from pathlib import Path
import numpy as np
from Bio.PDB import PDBParser, MMCIFParser, NeighborSearch
def load_structure(input_path: str, fmt: str):
if fmt.lower() in ("pdb", ".pdb"):
parser = PDBParser(QUIET=True)
elif fmt.lower() in ("cif", "mmcif", ".cif", ".mmcif"):
parser = MMCIFParser(QUIET=True)
else:
raise ValueError(f"Unsupported format: {fmt}")
return parser.get_structure("structure", input_path)
def main():
config_path = Path("config/task_config.json")
with config_path.open("r", encoding="utf-8") as f:
cfg = json.load(f)
structure = load_structure(cfg["input_path"], cfg["format"])
# Use the first model by default
model = next(structure.get_models())
chain = model[cfg["chain_id"]]
# Collect atoms for neighbor search
all_atoms = list(structure.get_atoms())
ns = NeighborSearch(all_atoms)
# Pick a reference atom (first residue in chain that has the requested atom)
ref_atom = None
for residue in chain.get_residues():
if cfg["atom_name"] in residue:
ref_atom = residue[cfg["atom_name"]]
break
if ref_atom is None:
raise RuntimeError(f"No atom '{cfg['atom_name']}' found in chain {cfg['chain_id']}")
cutoff = float(cfg["distance_cutoff"])
neighbors = ns.search(ref_atom.coord, cutoff, level="R") # residues within cutoff
results = []
for res in neighbors:
# Skip hetero/water if desired; here we keep everything and report identifiers
res_id = res.get_id() # (hetflag, resseq, icode)
results.append(
{
"chain_id": res.get_parent().id,
"resname": res.get_resname(),
"resseq": int(res_id[1]),
"icode": (res_id[2] or "").strip(),
}
)
out_path = Path(cfg["output_path"])
out_path.parent.mkdir(parents=True, exist_ok=True)
with out_path.open("w", encoding="utf-8") as f:
json.dump(
{
"input_path": cfg["input_path"],
"reference": {
"chain_id": cfg["chain_id"],
"atom_name": cfg["atom_name"],
"cutoff": cutoff,
},
"neighbor_residues": results,
},
f,
ensure_ascii=False,
indent=2,
)
if __name__ == "__main__":
main()
Run the script:
python scripts/neighbor_search.py
Implementation Details
- Configuration convention: write runtime parameters to
config/task_config.json as an intermediate file and invoke scripts via python scripts/<task_name>.py. Avoid stacking many CLI -- arguments; prefer config files.
- Encoding and JSON output: all file I/O must explicitly use
encoding="utf-8". When writing JSON, use ensure_ascii=False to preserve non-ASCII characters.
- Parsing strategy:
- Use
PDBParser(QUIET=True) for .pdb.
- Use
MMCIFParser(QUIET=True) for .cif/.mmcif.
- Access hierarchy through iterators (
get_models(), get_chains(), get_residues(), get_atoms()).
- Geometry calculations:
- Distances are typically computed from atomic coordinates (NumPy arrays) using Euclidean norm, e.g.
np.linalg.norm(a.coord - b.coord).
- Angles/dihedrals can be computed using Bio.PDB vector utilities (e.g.,
Bio.PDB.vectors.calc_angle, calc_dihedral) when needed.
- Neighbor search:
NeighborSearch(list(structure.get_atoms())) builds a spatial index over atoms.
search(center, radius, level="A"|"R"|"C"...) returns neighbors at the requested hierarchy level (atoms, residues, etc.).
- Scope coverage:
- PDB/mmCIF parsing and hierarchical access
- Distance/angle/dihedral computations
- Neighbor search and structural quality/annotation (optional DSSP)
- Structure extraction/saving and superposition (e.g.,
Superimposer)
When Not to Use
- Do not use this skill when the required source data, identifiers, files, or credentials are missing.
- Do not use this skill when the user asks for fabricated results, unsupported claims, or out-of-scope conclusions.
- Do not use this skill when a simpler direct answer is more appropriate than the documented workflow.
Required Inputs
- A clearly specified task goal aligned with the documented scope.
- All required files, identifiers, parameters, or environment variables before execution.
- Any domain constraints, formatting requirements, and expected output destination if applicable.
Recommended Workflow
- Validate the request against the skill boundary and confirm all required inputs are present.
- Select the documented execution path and prefer the simplest supported command or procedure.
- Produce the expected output using the documented file format, schema, or narrative structure.
- Run a final validation pass for completeness, consistency, and safety before returning the result.
Output Contract
- Return a structured deliverable that is directly usable without reformatting.
- If a file is produced, prefer a deterministic output name such as
biopython_structure_result.md unless the skill documentation defines a better convention.
- Include a short validation summary describing what was checked, what assumptions were made, and any remaining limitations.
Validation and Safety Rules
- Validate required inputs before execution and stop early when mandatory fields or files are missing.
- Do not fabricate measurements, references, findings, or conclusions that are not supported by the provided source material.
- Emit a clear warning when credentials, privacy constraints, safety boundaries, or unsupported requests affect the result.
- Keep the output safe, reproducible, and within the documented scope at all times.
Failure Handling
- If validation fails, explain the exact missing field, file, or parameter and show the minimum fix required.
- If an external dependency or script fails, surface the command path, likely cause, and the next recovery step.
- If partial output is returned, label it clearly and identify which checks could not be completed.
Quick Validation
Run this minimal verification path before full execution when possible:
No local script validation step is required for this skill.
Expected output format:
Result file: biopython_structure_result.md
Validation summary: PASS/FAIL with brief notes
Assumptions: explicit list if any
1---2name: biopython-structure3description: Use Bio.PDB to parse and analyze protein structures (PDB/mmCIF) for structural bioinformatics tasks; use when you need structure parsing, geometry calculations, or structural comparison/superposition.4license: MIT5---6> **Source**: [https://github.com/aipoch/medical-research-skills](https://github.com/aipoch/medical-research-skills)
7
8# biopython-structure
9
10## When to Use
11
12- You need to parse **PDB** or **mmCIF** files and access the structure hierarchy (model → chain → residue → atom).
13- You want to compute **geometric measurements** such as distances, bond angles, and dihedral angles between atoms/residues.
14- You need **neighbor searches** (e.g., find residues/atoms within a cutoff) for contact analysis or local environment inspection.
15- You want to perform **structural comparison**, including alignment/superposition and RMSD-style evaluation.
16- You need to **extract, modify, and save** structures (e.g., subset chains/residues and write back to PDB/mmCIF).
17
18## Key Features
19
20- **Structure parsing** for PDB/mmCIF using `Bio.PDB` parsers.
21- **Hierarchical traversal** and selection of models, chains, residues, and atoms.
22- **Geometry calculations**: distance, angle, and dihedral computations using Bio.PDB utilities.
23- **Neighbor search** via spatial indexing (`NeighborSearch`) for efficient cutoff queries.
24- **Structural operations**: extraction, saving, and **superposition** (e.g., `Superimposer`).
25- **Quality/annotation hooks**: optional integration with **DSSP** (external executable) for secondary structure and accessibility.
26
27## Dependencies
28
29- `biopython` (>= 1.79)
30- `numpy` (>= 1.21)
31- Optional: `DSSP` executable (e.g., `mkdssp`, version depends on your system installation)
32
33## Example Usage
34
35Create `config/task_config.json`:
36
37```json
38{
39 "input_path": "data/1ubq.pdb",
40 "format": "pdb",
41 "chain_id": "A",
42 "atom_name": "CA",
43 "distance_cutoff": 8.0,
44 "output_path": "outputs/chainA_ca_neighbors.json"
45}
46```
47
48Create `scripts/neighbor_search.py`:
49
50```python
51import json
52from pathlib import Path
53
54import numpy as np
55from Bio.PDB import PDBParser, MMCIFParser, NeighborSearch
56
57def load_structure(input_path: str, fmt: str):
58 if fmt.lower() in ("pdb", ".pdb"):
59 parser = PDBParser(QUIET=True)
60 elif fmt.lower() in ("cif", "mmcif", ".cif", ".mmcif"):
61 parser = MMCIFParser(QUIET=True)
62 else:
63 raise ValueError(f"Unsupported format: {fmt}")
64 return parser.get_structure("structure", input_path)
65
66def main():
67 config_path = Path("config/task_config.json")
68 with config_path.open("r", encoding="utf-8") as f:
69 cfg = json.load(f)
70
71 structure = load_structure(cfg["input_path"], cfg["format"])
72
73 # Use the first model by default
74 model = next(structure.get_models())
75 chain = model[cfg["chain_id"]]
76
77 # Collect atoms for neighbor search
78 all_atoms = list(structure.get_atoms())
79 ns = NeighborSearch(all_atoms)
80
81 # Pick a reference atom (first residue in chain that has the requested atom)
82 ref_atom = None
83 for residue in chain.get_residues():
84 if cfg["atom_name"] in residue:
85 ref_atom = residue[cfg["atom_name"]]
86 break
87 if ref_atom is None:
88 raise RuntimeError(f"No atom '{cfg['atom_name']}' found in chain {cfg['chain_id']}")
89
90 cutoff = float(cfg["distance_cutoff"])
91 neighbors = ns.search(ref_atom.coord, cutoff, level="R") # residues within cutoff
92
93 results = []
94 for res in neighbors:
95 # Skip hetero/water if desired; here we keep everything and report identifiers
96 res_id = res.get_id() # (hetflag, resseq, icode)
97 results.append(
98 {
99 "chain_id": res.get_parent().id,
100 "resname": res.get_resname(),
101 "resseq": int(res_id[1]),
102 "icode": (res_id[2] or "").strip(),
103 }
104 )
105
106 out_path = Path(cfg["output_path"])
107 out_path.parent.mkdir(parents=True, exist_ok=True)
108 with out_path.open("w", encoding="utf-8") as f:
109 json.dump(
110 {
111 "input_path": cfg["input_path"],
112 "reference": {
113 "chain_id": cfg["chain_id"],
114 "atom_name": cfg["atom_name"],
115 "cutoff": cutoff,
116 },
117 "neighbor_residues": results,
118 },
119 f,
120 ensure_ascii=False,
121 indent=2,
122 )
123
124if __name__ == "__main__":
125 main()
126```
127
128Run the script:
129
130```bash
131python scripts/neighbor_search.py
132```
133
134## Implementation Details
135
136- **Configuration convention**: write runtime parameters to `config/task_config.json` as an intermediate file and invoke scripts via `python scripts/<task_name>.py`. Avoid stacking many CLI `--` arguments; prefer config files.
137- **Encoding and JSON output**: all file I/O must explicitly use `encoding="utf-8"`. When writing JSON, use `ensure_ascii=False` to preserve non-ASCII characters.
138- **Parsing strategy**:
139 - Use `PDBParser(QUIET=True)` for `.pdb`.
140 - Use `MMCIFParser(QUIET=True)` for `.cif/.mmcif`.
141 - Access hierarchy through iterators (`get_models()`, `get_chains()`, `get_residues()`, `get_atoms()`).
142- **Geometry calculations**:
143 - Distances are typically computed from atomic coordinates (NumPy arrays) using Euclidean norm, e.g. `np.linalg.norm(a.coord - b.coord)`.
144 - Angles/dihedrals can be computed using Bio.PDB vector utilities (e.g., `Bio.PDB.vectors.calc_angle`, `calc_dihedral`) when needed.
145- **Neighbor search**:
146 - `NeighborSearch(list(structure.get_atoms()))` builds a spatial index over atoms.
147 - `search(center, radius, level="A"|"R"|"C"...)` returns neighbors at the requested hierarchy level (atoms, residues, etc.).
148- **Scope coverage**:
149 - PDB/mmCIF parsing and hierarchical access
150 - Distance/angle/dihedral computations
151 - Neighbor search and structural quality/annotation (optional DSSP)
152 - Structure extraction/saving and superposition (e.g., `Superimposer`)
153
154## When Not to Use
155
156- Do not use this skill when the required source data, identifiers, files, or credentials are missing.
157- Do not use this skill when the user asks for fabricated results, unsupported claims, or out-of-scope conclusions.
158- Do not use this skill when a simpler direct answer is more appropriate than the documented workflow.
159
160## Required Inputs
161
162- A clearly specified task goal aligned with the documented scope.
163- All required files, identifiers, parameters, or environment variables before execution.
164- Any domain constraints, formatting requirements, and expected output destination if applicable.
165
166## Recommended Workflow
167
1681. Validate the request against the skill boundary and confirm all required inputs are present.
1692. Select the documented execution path and prefer the simplest supported command or procedure.
1703. Produce the expected output using the documented file format, schema, or narrative structure.
1714. Run a final validation pass for completeness, consistency, and safety before returning the result.
172
173## Output Contract
174
175- Return a structured deliverable that is directly usable without reformatting.
176- If a file is produced, prefer a deterministic output name such as `biopython_structure_result.md` unless the skill documentation defines a better convention.
177- Include a short validation summary describing what was checked, what assumptions were made, and any remaining limitations.
178
179## Validation and Safety Rules
180
181- Validate required inputs before execution and stop early when mandatory fields or files are missing.
182- Do not fabricate measurements, references, findings, or conclusions that are not supported by the provided source material.
183- Emit a clear warning when credentials, privacy constraints, safety boundaries, or unsupported requests affect the result.
184- Keep the output safe, reproducible, and within the documented scope at all times.
185
186## Failure Handling
187
188- If validation fails, explain the exact missing field, file, or parameter and show the minimum fix required.
189- If an external dependency or script fails, surface the command path, likely cause, and the next recovery step.
190- If partial output is returned, label it clearly and identify which checks could not be completed.
191
192## Quick Validation
193
194Run this minimal verification path before full execution when possible:
195
196```text
197No local script validation step is required for this skill.
198```
199
200Expected output format:
201
202```text
203Result file: biopython_structure_result.md
204Validation summary: PASS/FAIL with brief notes
205Assumptions: explicit list if any
206```