PyMOL
When to Use
Use this skill when the user wants to:
- Create publication-quality images of protein or molecular structures.
- Perform structural alignments or superpositions between two or more structures.
- Measure distances, angles, contacts, or RMSD between atoms/residues.
- Highlight binding sites, active site residues, or specific ligand interactions.
- Color structures by B-factor, pLDDT confidence, secondary structure, or chain.
- Render surfaces (electrostatic, transparent, cavity/pocket).
- Perform in silico mutagenesis on a loaded structure.
- Batch-render a directory of structure files.
- Re-open and modify an existing
.pse session file.
Do NOT use when:
- The user wants to run AlphaFold predictions (use an AlphaFold skill instead).
- The user wants docking or molecular dynamics simulations.
- The user only has a sequence and no structure file — fetch the structure first. Check if any other installed skills can retrieve structures from the PDB or AlphaFold Database before proceeding.
Prerequisites
uv: Read the uv skill and follow its Setup instructions to ensure uv is installed and on PATH. All PyMOL scripts are executed via uv run with PEP 0723 inline dependency headers, so uv handles virtual environment and package installation automatically.
- License Notification: If
.licenses/pymol_LICENSE.txt does not already exist in the workspace root directory, then:
- Prominently notify the user to check the PyMOL license at https://www.pymol.org/.
- Create the file
.licenses/pymol_LICENSE.txt recording the notification text and timestamp.
- Structure files must be on the host: Download or place structure files (
.pdb, .cif, .pse, etc.) into a directory within the user's project before running any PyMOL script. This skill does not fetch structures from remote databases.
Procedure
1. Pre-Flight File Check
Before writing or running any PyMOL script, verify that the requested structure file exists on the host:
Test-Path "path/to/structure.cif"
If the file does not exist, stop and ask the user to provide or download it.
2. Write the PyMOL Script
Create a Python script (e.g., render.py) in the user's project directory. Every script must include:
- PEP 0723 inline metadata header declaring
pymol-open-source-whl as a dependency.
- Environment variable
PYOPENGL_PLATFORM=osmesa set before importing pymol.
- Init boilerplate in the exact order shown below —
from pymol import cmd must come after finish_launching(), not before.
- Structure load verification: after every
cmd.load(), check cmd.count_atoms("all"); if 0, print an error and call cmd.quit() immediately.
cmd.png() for image output — never use cmd.draw() or cmd.ray() with hardware acceleration (OSMesa does not support it).
cmd.save() for a .pse session file alongside every PNG output.
cmd.quit() as the final line of every script. Omitting it causes the process to hang.
Minimal example script (render.py)
# /// script
# requires-python = ">=3.10, <3.13"
# dependencies = [
# "pymol-open-source-whl",
# ]
# ///
import os
import sys
# Set environment variable for headless rendering
os.environ["PYOPENGL_PLATFORM"] = "osmesa"
import pymol # pytype: disable=import-error
pymol.pymol_argv = ["pymol", "-cq"]
pymol.finish_launching()
from pymol import cmd # pytype: disable=import-error
cmd.load("AF-P00520-F1-model_v4.cif", "structure")
if cmd.count_atoms("all") == 0:
print("ERROR: Failed to load structure file.", flush=True)
cmd.quit()
sys.exit(1)
cmd.show("cartoon")
cmd.color("green", "ss h")
cmd.color("yellow", "ss s")
cmd.color("gray", "ss l+''")
cmd.orient()
cmd.set("ray_opaque_background", 1)
cmd.png("output/render.png", width=1200, height=900, dpi=150)
cmd.save("output/session.pse")
cmd.quit()
3. Run the Script
From the user's project directory (output paths must be absolute or relative to the project root):
uv run render.py
uv will automatically read the PEP 0723 header, create an ephemeral environment, install pymol-open-source-whl and its dependencies, and execute the script.
4. Load Reference Files
- Before writing non-trivial scripts: load references/PYMOL_REFERENCE.md for selection syntax, common commands, and gotchas. This is essential for correct atom selections and command parameters.
- Before writing recipe-based scripts: load references/RECIPES.md for complete, copy-paste-ready recipes. Available recipes include:
- Cartoon with secondary structure coloring
- B-factor (pLDDT) coloring — continuous spectrum
- AlphaFold pLDDT coloring — canonical threshold-based confidence colors
- Highlight specific residues — active site or key residues as sticks
- Surface rendering — transparent surface over cartoon
- Electrostatic surface rendering — vacuum electrostatics (qualitative)
- Multi-chain complex colors — automatic per-chain coloring
- B-factor putty analysis — tube width proportional to flexibility
- Cavity and pocket visualization — surface cavity detection with ligand focus
- Multi-structure batch rendering — render a directory of structures
- Measure distance between residues — CA–CA distance with labels
- Zoom into binding pocket — simple pocket focus
- Protein-ligand interaction — ligand isolation, styled rendering, polar contacts
- Two-structure superposition with RMSD — align/cealign with auto-fallback
- In silico mutagenesis — mutate residues with the mutagenesis wizard
- Load and modify an existing session — re-open a
.pse file
5. Interpret and Report Output
- The
output/ directory (or user-specified directory) contains PNG images and a .pse session file.
- Any measurements or metrics (distances, RMSD, atom counts) are printed to stdout by the PyMOL script. Report these values to the user.
- Present PNG images to the user and describe the visualization.
- Tell the user they can open the
.pse file in their local PyMOL to further explore, rotate, or modify the visualization.
- If the user wants modifications, load the saved
.pse in a new script and re-run.
- Notification: If this skill is used, ensure this is mentioned in the output.
Pitfalls
- Never use
cmd.draw() or cmd.ray() with hardware acceleration. OSMesa software rendering only. Use cmd.png() for all image output. Set PYOPENGL_PLATFORM=osmesa before importing pymol.
- Never omit
cmd.quit(). Without it the process stops responding and hangs indefinitely.
- Init boilerplate order is mandatory.
from pymol import cmd must come after pymol.finish_launching(), not before. Reordering causes import failures or silent crashes.
- Always verify structure load. After
cmd.load(), check cmd.count_atoms("all"). If 0, the file path may be wrong or the format unsupported — print an error and quit immediately.
- Output paths must be absolute or relative to the user's project root. Always run PyMOL scripts from the project directory. Relative paths from other working directories will silently write files to unexpected locations.
- Always save a
.pse session file alongside any PNG. This lets the user open the session in their local PyMOL for further inspection.
- Large sessions with surfaces can exceed the
--max_output_mb limit (default 500 MB). Increase it with --max_output_mb=1000 if needed.
- Python version constraint: PEP 0723 header pins
requires-python = ">=3.10, <3.13". Do not change this unless the user explicitly requests a different version range.
- Do not fetch structures from remote databases within PyMOL scripts. Download structure files to the host first, then load them with
cmd.load().
Verification
After running a PyMOL script, verify the outputs were created:
# Check that the PNG image exists
Test-Path "output/render.png"
# Check that the session file exists
Test-Path "output/session.pse"
# Check file sizes are non-zero
(Get-Item "output/render.png").Length
(Get-Item "output/session.pse").Length
Expected: both files exist and have non-zero byte sizes. If either is missing or zero-length, check the script stdout for error messages — particularly load failures or OSMesa rendering errors.
Additionally, verify the script did not hang by confirming the uv run process exited cleanly (return code 0):
uv run render.py; echo "Exit code: $LASTEXITCODE"
Expected: Exit code: 0. A non-zero exit code or a hung process indicates a missing cmd.quit(), a failed structure load, or an OSMesa rendering error.
1---
2name: pymol
3description: >
4 Visualize, analyze, and render protein and molecular structures using PyMOL.
5 Use when the user wants to create images of protein structures, perform
6 structural alignments or superposition, measure distances or contacts,
7 highlight binding sites or active site residues, color by B-factor/pLDDT,
8 or analyze protein-ligand interactions. Do not use for docking,
9 molecular dynamics, or sequence-only analysis.
10version: 1.0.1
11metadata:
12 source: https://skillmd.com/skills/kayforkind/pymol
13---
14
15# PyMOL
16
17## When to Use
18
19Use this skill when the user wants to:
20
21- Create publication-quality images of protein or molecular structures.
22- Perform structural alignments or superpositions between two or more structures.
23- Measure distances, angles, contacts, or RMSD between atoms/residues.
24- Highlight binding sites, active site residues, or specific ligand interactions.
25- Color structures by B-factor, pLDDT confidence, secondary structure, or chain.
26- Render surfaces (electrostatic, transparent, cavity/pocket).
27- Perform in silico mutagenesis on a loaded structure.
28- Batch-render a directory of structure files.
29- Re-open and modify an existing `.pse` session file.
30
31**Do NOT use when:**
32
33- The user wants to run AlphaFold predictions (use an AlphaFold skill instead).
34- The user wants docking or molecular dynamics simulations.
35- The user only has a sequence and no structure file — fetch the structure first. Check if any other installed skills can retrieve structures from the PDB or AlphaFold Database before proceeding.
36
37## Prerequisites
38
391. **`uv`**: Read the `uv` skill and follow its Setup instructions to ensure `uv` is installed and on PATH. All PyMOL scripts are executed via `uv run` with PEP 0723 inline dependency headers, so `uv` handles virtual environment and package installation automatically.
402. **License Notification**: If `.licenses/pymol_LICENSE.txt` does not already exist in the workspace root directory, then:
41 1. Prominently notify the user to check the PyMOL license at https://www.pymol.org/.
42 2. Create the file `.licenses/pymol_LICENSE.txt` recording the notification text and timestamp.
433. **Structure files must be on the host**: Download or place structure files (`.pdb`, `.cif`, `.pse`, etc.) into a directory within the user's project before running any PyMOL script. This skill does not fetch structures from remote databases.
44
45## Procedure
46
47### 1. Pre-Flight File Check
48
49Before writing or running any PyMOL script, verify that the requested structure file exists on the host:
50
51```powershell
52Test-Path "path/to/structure.cif"
53```
54
55If the file does not exist, stop and ask the user to provide or download it.
56
57### 2. Write the PyMOL Script
58
59Create a Python script (e.g., `render.py`) in the user's project directory. Every script **must** include:
60
61- **PEP 0723 inline metadata header** declaring `pymol-open-source-whl` as a dependency.
62- **Environment variable** `PYOPENGL_PLATFORM=osmesa` set before importing pymol.
63- **Init boilerplate** in the exact order shown below — `from pymol import cmd` must come **after** `finish_launching()`, not before.
64- **Structure load verification**: after every `cmd.load()`, check `cmd.count_atoms("all")`; if 0, print an error and call `cmd.quit()` immediately.
65- **`cmd.png()` for image output** — never use `cmd.draw()` or `cmd.ray()` with hardware acceleration (OSMesa does not support it).
66- **`cmd.save()` for a `.pse` session file** alongside every PNG output.
67- **`cmd.quit()`** as the final line of every script. Omitting it causes the process to hang.
68
69#### Minimal example script (`render.py`)
70
71```python
72# /// script
73# requires-python = ">=3.10, <3.13"
74# dependencies = [
75# "pymol-open-source-whl",
76# ]
77# ///
78
79import os
80import sys
81
82# Set environment variable for headless rendering
83os.environ["PYOPENGL_PLATFORM"] = "osmesa"
84
85import pymol # pytype: disable=import-error
86pymol.pymol_argv = ["pymol", "-cq"]
87pymol.finish_launching()
88
89from pymol import cmd # pytype: disable=import-error
90
91cmd.load("AF-P00520-F1-model_v4.cif", "structure")
92if cmd.count_atoms("all") == 0:
93 print("ERROR: Failed to load structure file.", flush=True)
94 cmd.quit()
95 sys.exit(1)
96
97cmd.show("cartoon")
98cmd.color("green", "ss h")
99cmd.color("yellow", "ss s")
100cmd.color("gray", "ss l+''")
101cmd.orient()
102cmd.set("ray_opaque_background", 1)
103cmd.png("output/render.png", width=1200, height=900, dpi=150)
104cmd.save("output/session.pse")
105cmd.quit()
106```
107
108### 3. Run the Script
109
110From the user's project directory (output paths must be absolute or relative to the project root):
111
112```powershell
113uv run render.py
114```
115
116`uv` will automatically read the PEP 0723 header, create an ephemeral environment, install `pymol-open-source-whl` and its dependencies, and execute the script.
117
118### 4. Load Reference Files
119
120- **Before writing non-trivial scripts**: load [references/PYMOL_REFERENCE.md](references/PYMOL_REFERENCE.md) for selection syntax, common commands, and gotchas. This is essential for correct atom selections and command parameters.
121- **Before writing recipe-based scripts**: load [references/RECIPES.md](references/RECIPES.md) for complete, copy-paste-ready recipes. Available recipes include:
122 - Cartoon with secondary structure coloring
123 - B-factor (pLDDT) coloring — continuous spectrum
124 - AlphaFold pLDDT coloring — canonical threshold-based confidence colors
125 - Highlight specific residues — active site or key residues as sticks
126 - Surface rendering — transparent surface over cartoon
127 - Electrostatic surface rendering — vacuum electrostatics (qualitative)
128 - Multi-chain complex colors — automatic per-chain coloring
129 - B-factor putty analysis — tube width proportional to flexibility
130 - Cavity and pocket visualization — surface cavity detection with ligand focus
131 - Multi-structure batch rendering — render a directory of structures
132 - Measure distance between residues — CA–CA distance with labels
133 - Zoom into binding pocket — simple pocket focus
134 - Protein-ligand interaction — ligand isolation, styled rendering, polar contacts
135 - Two-structure superposition with RMSD — align/cealign with auto-fallback
136 - In silico mutagenesis — mutate residues with the mutagenesis wizard
137 - Load and modify an existing session — re-open a `.pse` file
138
139### 5. Interpret and Report Output
140
141- The `output/` directory (or user-specified directory) contains PNG images and a `.pse` session file.
142- Any measurements or metrics (distances, RMSD, atom counts) are printed to stdout by the PyMOL script. Report these values to the user.
143- Present PNG images to the user and describe the visualization.
144- Tell the user they can open the `.pse` file in their local PyMOL to further explore, rotate, or modify the visualization.
145- If the user wants modifications, load the saved `.pse` in a new script and re-run.
146- **Notification**: If this skill is used, ensure this is mentioned in the output.
147
148## Pitfalls
149
150- **Never use `cmd.draw()` or `cmd.ray()` with hardware acceleration.** OSMesa software rendering only. Use `cmd.png()` for all image output. Set `PYOPENGL_PLATFORM=osmesa` before importing pymol.
151- **Never omit `cmd.quit()`.** Without it the process stops responding and hangs indefinitely.
152- **Init boilerplate order is mandatory.** `from pymol import cmd` must come after `pymol.finish_launching()`, not before. Reordering causes import failures or silent crashes.
153- **Always verify structure load.** After `cmd.load()`, check `cmd.count_atoms("all")`. If 0, the file path may be wrong or the format unsupported — print an error and quit immediately.
154- **Output paths must be absolute or relative to the user's project root.** Always run PyMOL scripts from the project directory. Relative paths from other working directories will silently write files to unexpected locations.
155- **Always save a `.pse` session file** alongside any PNG. This lets the user open the session in their local PyMOL for further inspection.
156- **Large sessions with surfaces can exceed the `--max_output_mb` limit** (default 500 MB). Increase it with `--max_output_mb=1000` if needed.
157- **Python version constraint**: PEP 0723 header pins `requires-python = ">=3.10, <3.13"`. Do not change this unless the user explicitly requests a different version range.
158- **Do not fetch structures from remote databases within PyMOL scripts.** Download structure files to the host first, then load them with `cmd.load()`.
159
160## Verification
161
162After running a PyMOL script, verify the outputs were created:
163
164```powershell
165# Check that the PNG image exists
166Test-Path "output/render.png"
167
168# Check that the session file exists
169Test-Path "output/session.pse"
170
171# Check file sizes are non-zero
172(Get-Item "output/render.png").Length
173(Get-Item "output/session.pse").Length
174```
175
176Expected: both files exist and have non-zero byte sizes. If either is missing or zero-length, check the script stdout for error messages — particularly load failures or OSMesa rendering errors.
177
178Additionally, verify the script did not hang by confirming the `uv run` process exited cleanly (return code 0):
179
180```powershell
181uv run render.py; echo "Exit code: $LASTEXITCODE"
182```
183
184Expected: `Exit code: 0`. A non-zero exit code or a hung process indicates a missing `cmd.quit()`, a failed structure load, or an OSMesa rendering error.