Run and analyze molecular dynamics simulations with OpenMM

Run and analyze molecular dynamics simulations with OpenMM and MDAnalysis. Set up protein/small molecule systems, define force fields, run energy minimization and production MD, analyze trajectories (RMSD, RMSF, contact maps, free…
--- name: molecular-dynamics description: Run and analyze molecular dynamics simulations with OpenMM and MDAnalysis. Set up protein/small molecule systems, define force fields, run energy minimization and production MD, analyze trajectories (RMSD, RMSF, contact maps, free energy surfaces). For structural biology, drug binding, and biophysics. license: MIT metadata: version: "1.1" skill-author: Kuan-lin Huang --- # Molecular Dynamics ## Overview Molecular dynamics (MD) simulation computationally models the time evolution of molecular systems by integrating Newton's equations of motion. This skill covers two complementary tools: - **OpenMM** (https://openmm.org/): High-performance MD simulation engine with GPU support, Python API, and flexible force field support - **MDAnalysis** (https://mdanalysis.org/): Python library for reading, writing, and analyzing MD trajectories from all major simulation packages
Overview
Molecular dynamics (MD) simulation computationally models the time evolution of molecular systems by integrating Newton's equations of motion. This skill covers two complementary tools:
Manual install (npx, ZIP)
npx skills add K-Dense-AI/scientific-agent-skills --skill molecular-dynamics -g -a claude-codemkdir -p ~/.claude/skills && curl -sL https://codeload.github.com/K-Dense-AI/scientific-agent-skills/tar.gz/49c6e97775ea \
| tar -xz -C ~/.claude/skills --strip-components=2 scientific-agent-skills-49c6e97775ea/skills/molecular-dynamicsNew-Item -ItemType Directory -Force "$HOME\.claude\skills" | Out-Null; Invoke-WebRequest "https://m.agentalley.io/zip/97266a99cec9284b0a78/molecular-dynamics.zip" -OutFile "$env:TEMP\molecular-dynamics.zip"; Expand-Archive "$env:TEMP\molecular-dynamics.zip" -DestinationPath "$HOME\.claude\skills" -ForceConnects with Agent Alley MCP · agentalley.io/mcp
Files included
SKILL.md14.4 KBreferences/1 file · 5.5 KB
Read the files here
Show the full text459 lines
Molecular Dynamics
Overview
Molecular dynamics (MD) simulation computationally models the time evolution of molecular systems by integrating Newton's equations of motion. This skill covers two complementary tools:
- OpenMM (https://openmm.org/): High-performance MD simulation engine with GPU support, Python API, and flexible force field support
- MDAnalysis (https://mdanalysis.org/): Python library for reading, writing, and analyzing MD trajectories from all major simulation packages
Installation:
conda install -c conda-forge openmm mdanalysis nglview
# or
uv pip install openmm mdanalysis
When to Use This Skill
Use molecular dynamics when:
- Protein stability analysis: How does a mutation affect protein dynamics?
- Drug binding simulations: Characterize binding mode and residence time of a ligand
- Conformational sampling: Explore protein flexibility and conformational changes
- Protein-protein interaction: Model interface dynamics and binding energetics
- RMSD/RMSF analysis: Quantify structural fluctuations from a reference structure
- Free energy estimation: Compute binding free energy or conformational free energy
- Membrane simulations: Model proteins in lipid bilayers
- Intrinsically disordered proteins: Study IDR conformational ensembles
Core Workflow: OpenMM Simulation
1. System Preparation
from openmm.app import *
from openmm import *
from openmm.unit import *
import sys
def prepare_system_from_pdb(pdb_file, forcefield_name="amber14-all.xml",
water_model="amber14/tip3pfb.xml"):
"""
Prepare an OpenMM system from a PDB file.
Args:
pdb_file: Path to cleaned PDB file (use PDBFixer for raw PDB files)
forcefield_name: Force field XML file
water_model: Water model XML file
Returns:
pdb, forcefield, system, topology
"""
# Load PDB
pdb = PDBFile(pdb_file)
# Load force field
forcefield = ForceField(forcefield_name, water_model)
# Add hydrogens and solvate
modeller = Modeller(pdb.topology, pdb.positions)
modeller.addHydrogens(forcefield)
# Add solvent box (10 Å padding, 150 mM NaCl)
modeller.addSolvent(
forcefield,
model='tip3p',
padding=10*angstroms,
ionicStrength=0.15*molar
)
print(f"System: {modeller.topology.getNumAtoms()} atoms, "
f"{modeller.topology.getNumResidues()} residues")
# Create system
system = forcefield.createSystem(
modeller.topology,
nonbondedMethod=PME, # Particle Mesh Ewald for long-range electrostatics
nonbondedCutoff=1.0*nanometer,
constraints=HBonds, # Constrain hydrogen bonds (allows 2 fs timestep)
rigidWater=True,
ewaldErrorTolerance=0.0005
)
return modeller, system
2. Energy Minimization
from openmm.app import *
from openmm import *
from openmm.unit import *
def minimize_energy(modeller, system, output_pdb="minimized.pdb",
max_iterations=1000, tolerance=10.0):
"""
Energy minimize the system to remove steric clashes.
Args:
modeller: Modeller object with topology and positions
system: OpenMM System
output_pdb: Path to save minimized structure
max_iterations: Maximum minimization steps
tolerance: Convergence criterion in kJ/mol/nm
Returns:
simulation object with minimized positions
"""
# Set up integrator (doesn't matter for minimization)
integrator = LangevinMiddleIntegrator(300*kelvin, 1/picosecond, 0.004*picoseconds)
# Create simulation
# Use GPU if available (CUDA or OpenCL), fall back to CPU
try:
platform = Platform.getPlatformByName('CUDA')
properties = {'DeviceIndex': '0', 'Precision': 'mixed'}
except Exception:
try:
platform = Platform.getPlatformByName('OpenCL')
properties = {}
except Exception:
platform = Platform.getPlatformByName('CPU')
properties = {}
simulation = Simulation(
modeller.topology, system, integrator,
platform, properties
)
simulation.context.setPositions(modeller.positions)
# Check initial energy
state = simulation.context.getState(getEnergy=True)
print(f"Initial energy: {state.getPotentialEnergy()}")
# Minimize
simulation.minimizeEnergy(
tolerance=tolerance*kilojoules_per_mole/nanometer,
maxIterations=max_iterations
)
state = simulation.context.getState(getEnergy=True, getPositions=True)
print(f"Minimized energy: {state.getPotentialEnergy()}")
# Save minimized structure
with open(output_pdb, 'w') as f:
PDBFile.writeFile(simulation.topology, state.getPositions(), f)
return simulation
3. NVT Equilibration
from openmm.app import *
from openmm import *
from openmm.unit import *
def run_nvt_equilibration(simulation, n_steps=50000, temperature=300,
report_interval=1000, output_prefix="nvt"):
"""
NVT equilibration: constant N, V, T.
Equilibrate velocities to target temperature.
Args:
simulation: OpenMM Simulation (after minimization)
n_steps: Number of MD steps (50000 × 2fs = 100 ps)
temperature: Temperature in Kelvin
report_interval: Steps between data reports
output_prefix: File prefix for trajectory and log
"""
# Add position restraints for backbone during NVT
# (Optional: restraint heavy atoms)
# Set temperature
simulation.context.setVelocitiesToTemperature(temperature*kelvin)
# Add reporters
simulation.reporters = []
# Log file
simulation.reporters.append(
StateDataReporter(
f"{output_prefix}_log.txt",
report_interval,
step=True,
potentialEnergy=True,
kineticEnergy=True,
temperature=True,
volume=True,
speed=True
)
)
# DCD trajectory (compact binary format)
simulation.reporters.append(
DCDReporter(f"{output_prefix}_traj.dcd", report_interval)
)
print(f"Running NVT equilibration: {n_steps} steps ({n_steps*2/1000:.1f} ps)")
simulation.step(n_steps)
print("NVT equilibration complete")
return simulation
4. NPT Equilibration and Production
def run_npt_production(simulation, n_steps=500000, temperature=300, pressure=1.0,
report_interval=5000, output_prefix="npt"):
"""
NPT production run: constant N, P, T.
Args:
n_steps: Production steps (500000 × 2fs = 1 ns)
temperature: Temperature in Kelvin
pressure: Pressure in bar
report_interval: Steps between reports
"""
# Add Monte Carlo barostat for pressure control
system = simulation.context.getSystem()
system.addForce(MonteCarloBarostat(pressure*bar, temperature*kelvin, 25))
simulation.context.reinitialize(preserveState=True)
# Update reporters
simulation.reporters = []
simulation.reporters.append(
StateDataReporter(
f"{output_prefix}_log.txt",
report_interval,
step=True,
potentialEnergy=True,
temperature=True,
density=True,
speed=True
)
)
simulation.reporters.append(
DCDReporter(f"{output_prefix}_traj.dcd", report_interval)
)
# Save checkpoints
simulation.reporters.append(
CheckpointReporter(f"{output_prefix}_checkpoint.chk", 50000)
)
print(f"Running NPT production: {n_steps} steps ({n_steps*2/1000000:.2f} ns)")
simulation.step(n_steps)
print("Production MD complete")
return simulation
Trajectory Analysis with MDAnalysis
1. Load Trajectory
import MDAnalysis as mda
from MDAnalysis.analysis import rms, align, contacts
import numpy as np
import matplotlib.pyplot as plt
def load_trajectory(topology_file, trajectory_file):
"""
Load an MD trajectory with MDAnalysis.
Args:
topology_file: PDB, PSF, or other topology file
trajectory_file: DCD, XTC, TRR, or other trajectory
"""
u = mda.Universe(topology_file, trajectory_file)
print(f"Universe: {u.atoms.n_atoms} atoms, {u.trajectory.n_frames} frames")
print(f"Time range: 0 to {u.trajectory.totaltime:.0f} ps")
return u
2. RMSD Analysis
def compute_rmsd(u, selection="backbone", reference_frame=0):
"""
Compute RMSD of selected atoms relative to reference frame.
Args:
u: MDAnalysis Universe
selection: Atom selection string (MDAnalysis syntax)
reference_frame: Frame index for reference structure
Returns:
numpy array of (time, rmsd) values
"""
# Align trajectory to minimize RMSD
aligner = align.AlignTraj(u, u, select=selection, in_memory=True)
aligner.run()
# Compute RMSD
R = rms.RMSD(u, select=selection, ref_frame=reference_frame)
R.run()
rmsd_data = R.results.rmsd # columns: frame, time, RMSD
return rmsd_data
def plot_rmsd(rmsd_data, title="RMSD over time", output_file="rmsd.png"):
"""Plot RMSD over simulation time."""
fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(rmsd_data[:, 1] / 1000, rmsd_data[:, 2], 'b-', linewidth=0.5)
ax.set_xlabel("Time (ns)")
ax.set_ylabel("RMSD (Å)")
ax.set_title(title)
ax.axhline(rmsd_data[:, 2].mean(), color='r', linestyle='--',
label=f'Mean: {rmsd_data[:, 2].mean():.2f} Å')
ax.legend()
plt.tight_layout()
plt.savefig(output_file, dpi=150)
return fig
3. RMSF Analysis (Per-Residue Flexibility)
def compute_rmsf(u, selection="backbone", start_frame=0):
"""
Compute per-residue RMSF (flexibility).
Returns:
resids, rmsf_values arrays
"""
# Select atoms
atoms = u.select_atoms(selection)
# Compute RMSF
R = rms.RMSF(atoms)
R.run(start=start_frame)
# Average by residue
resids = []
rmsf_per_res = []
for res in u.select_atoms(selection).residues:
res_atoms = res.atoms.intersection(atoms)
if len(res_atoms) > 0:
resids.append(res.resid)
rmsf_per_res.append(R.results.rmsf[res_atoms.indices].mean())
return np.array(resids), np.array(rmsf_per_res)
4. Protein-Ligand Contacts
def analyze_contacts(u, protein_sel="protein", ligand_sel="resname LIG",
radius=4.5, start_frame=0):
"""
Track protein-ligand contacts over trajectory.
Args:
radius: Contact distance cutoff in Angstroms
"""
protein = u.select_atoms(protein_sel)
ligand = u.select_atoms(ligand_sel)
contact_frames = []
for ts in u.trajectory[start_frame:]:
# Find protein atoms within radius of ligand
distances = contacts.contact_matrix(
protein.positions, ligand.positions, radius
)
contact_residues = set()
for i in range(distances.shape[0]):
if distances[i].any():
contact_residues.add(protein.atoms[i].resid)
contact_frames.append(contact_residues)
return contact_frames
Force Field Selection Guide
| System | Recommended Force Field | Water Model |
|---|---|---|
| Standard proteins | AMBER14 (amber14-all.xml) |
TIP3P-FB |
| Proteins + small molecules | AMBER14 + GAFF2 | TIP3P-FB |
| Membrane proteins | CHARMM36m | TIP3P |
| Nucleic acids | AMBER99-bsc1 or AMBER14 | TIP3P |
| Disordered proteins | ff19SB or CHARMM36m | TIP3P |
System Preparation Tools
PDBFixer (for raw PDB files)
from pdbfixer import PDBFixer
from openmm.app import PDBFile
def fix_pdb(input_pdb, output_pdb, ph=7.0):
"""Fix common PDB issues: missing residues, atoms, add H, standardize."""
fixer = PDBFixer(filename=input_pdb)
fixer.findMissingResidues()
fixer.findNonstandardResidues()
fixer.replaceNonstandardResidues()
fixer.removeHeterogens(True) # Remove water/ligands
fixer.findMissingAtoms()
fixer.addMissingAtoms()
fixer.addMissingHydrogens(ph)
with open(output_pdb, 'w') as f:
PDBFile.writeFile(fixer.topology, fixer.positions, f)
return output_pdb
GAFF2 for Small Molecules (via OpenFF Toolkit)
# For ligand parameterization, use OpenFF toolkit or ACPYPE
# uv pip install openff-toolkit
from openff.toolkit import Molecule, ForceField as OFFForceField
from openff.interchange import Interchange
def parameterize_ligand(smiles, ff_name="openff-2.0.0.offxml"):
"""Generate GAFF2/OpenFF parameters for a small molecule."""
mol = Molecule.from_smiles(smiles)
mol.generate_conformers(n_conformers=1)
off_ff = OFFForceField(ff_name)
interchange = off_ff.create_interchange(mol.to_topology())
return interchange
Best Practices
- Always minimize before MD: Raw PDB structures have steric clashes
- Equilibrate before production: NVT (50–100 ps) → NPT (100–500 ps) → Production
- Use GPU: Simulations are 10–100× faster on GPU (CUDA/OpenCL)
- 2 fs timestep with HBonds constraints: Standard; use 4 fs with HMR (hydrogen mass repartitioning)
- Analyze only equilibrated trajectory: Discard first 20–50% as equilibration
- Save checkpoints: MD runs can fail; checkpoints allow restart
- Periodic boundary conditions: Required for solvated systems
- PME for electrostatics: More accurate than cutoff methods for charged systems
Additional Resources
- OpenMM documentation: https://openmm.org/documentation.html
- MDAnalysis user guide: https://docs.mdanalysis.org/
- GROMACS (alternative MD engine): https://manual.gromacs.org/
- NAMD (alternative): https://www.ks.uiuc.edu/Research/namd/
- CHARMM-GUI (web-based system builder): https://charmm-gui.org/
- AmberTools (free Amber tools): https://ambermd.org/AmberTools.php
- OpenMM paper: Eastman P et al. (2017) PLOS Computational Biology. PMID: 28278240
- MDAnalysis paper: Michaud-Agrawal N et al. (2011) J Computational Chemistry. PMID: 21500218
| 1 | |
| 2 | name molecular-dynamics |
| 3 | description Run and analyze molecular dynamics simulations with OpenMM and MDAnalysis. Set up protein/small molecule systems, define force fields, run energy minimization and production MD, analyze trajectories (RMSD, RMSF, contact maps, free energy surfaces). For structural biology, drug binding, and biophysics. |
| 4 | license MIT |
| 5 | metadata |
| 6 | version "1.1" |
| 7 | skill-author Kuan-lin Huang |
| 8 | |
| 9 | |
| 10 | # Molecular Dynamics |
| 11 | |
| 12 | ## Overview |
| 13 | |
| 14 | Molecular dynamics (MD) simulation computationally models the time evolution of molecular systems by integrating Newton's equations of motion. This skill covers two complementary tools: |
| 15 | |
| 16 | **OpenMM** (https://openmm.org/): High-performance MD simulation engine with GPU support, Python API, and flexible force field support |
| 17 | **MDAnalysis** (https://mdanalysis.org/): Python library for reading, writing, and analyzing MD trajectories from all major simulation packages |
| 18 | |
| 19 | **Installation:** |
| 20 | |
| 21 | conda install -c conda-forge openmm mdanalysis nglview |
| 22 | # or |
| 23 | uv pip install openmm mdanalysis |
| 24 | |
| 25 | |
| 26 | ## When to Use This Skill |
| 27 | |
| 28 | Use molecular dynamics when: |
| 29 | |
| 30 | **Protein stability analysis**: How does a mutation affect protein dynamics? |
| 31 | **Drug binding simulations**: Characterize binding mode and residence time of a ligand |
| 32 | **Conformational sampling**: Explore protein flexibility and conformational changes |
| 33 | **Protein-protein interaction**: Model interface dynamics and binding energetics |
| 34 | **RMSD/RMSF analysis**: Quantify structural fluctuations from a reference structure |
| 35 | **Free energy estimation**: Compute binding free energy or conformational free energy |
| 36 | **Membrane simulations**: Model proteins in lipid bilayers |
| 37 | **Intrinsically disordered proteins**: Study IDR conformational ensembles |
| 38 | |
| 39 | ## Core Workflow: OpenMM Simulation |
| 40 | |
| 41 | ### 1. System Preparation |
| 42 | |
| 43 | |
| 44 | from openmm.app import * |
| 45 | from openmm import * |
| 46 | from openmm.unit import * |
| 47 | import sys |
| 48 | |
| 49 | def prepare_system_from_pdb(pdb_file, forcefield_name="amber14-all.xml", |
| 50 | water_model="amber14/tip3pfb.xml"): |
| 51 | """ |
| 52 | Prepare an OpenMM system from a PDB file. |
| 53 | |
| 54 | Args: |
| 55 | pdb_file: Path to cleaned PDB file (use PDBFixer for raw PDB files) |
| 56 | forcefield_name: Force field XML file |
| 57 | water_model: Water model XML file |
| 58 | |
| 59 | Returns: |
| 60 | pdb, forcefield, system, topology |
| 61 | """ |
| 62 | # Load PDB |
| 63 | pdb = PDBFile(pdb_file) |
| 64 | |
| 65 | # Load force field |
| 66 | forcefield = ForceField(forcefield_name, water_model) |
| 67 | |
| 68 | # Add hydrogens and solvate |
| 69 | modeller = Modeller(pdb.topology, pdb.positions) |
| 70 | modeller.addHydrogens(forcefield) |
| 71 | |
| 72 | # Add solvent box (10 Å padding, 150 mM NaCl) |
| 73 | modeller.addSolvent( |
| 74 | forcefield, |
| 75 | model='tip3p', |
| 76 | padding=10*angstroms, |
| 77 | ionicStrength=0.15*molar |
| 78 | ) |
| 79 | |
| 80 | print(f"System: {modeller.topology.getNumAtoms()} atoms, " |
| 81 | f"{modeller.topology.getNumResidues()} residues") |
| 82 | |
| 83 | # Create system |
| 84 | system = forcefield.createSystem( |
| 85 | modeller.topology, |
| 86 | nonbondedMethod=PME, # Particle Mesh Ewald for long-range electrostatics |
| 87 | nonbondedCutoff=1.0*nanometer, |
| 88 | constraints=HBonds, # Constrain hydrogen bonds (allows 2 fs timestep) |
| 89 | rigidWater=True, |
| 90 | ewaldErrorTolerance=0.0005 |
| 91 | ) |
| 92 | |
| 93 | return modeller, system |
| 94 | |
| 95 | |
| 96 | ### 2. Energy Minimization |
| 97 | |
| 98 | |
| 99 | from openmm.app import * |
| 100 | from openmm import * |
| 101 | from openmm.unit import * |
| 102 | |
| 103 | def minimize_energy(modeller, system, output_pdb="minimized.pdb", |
| 104 | max_iterations=1000, tolerance=10.0): |
| 105 | """ |
| 106 | Energy minimize the system to remove steric clashes. |
| 107 | |
| 108 | Args: |
| 109 | modeller: Modeller object with topology and positions |
| 110 | system: OpenMM System |
| 111 | output_pdb: Path to save minimized structure |
| 112 | max_iterations: Maximum minimization steps |
| 113 | tolerance: Convergence criterion in kJ/mol/nm |
| 114 | |
| 115 | Returns: |
| 116 | simulation object with minimized positions |
| 117 | """ |
| 118 | # Set up integrator (doesn't matter for minimization) |
| 119 | integrator = LangevinMiddleIntegrator(300*kelvin, 1/picosecond, 0.004*picoseconds) |
| 120 | |
| 121 | # Create simulation |
| 122 | # Use GPU if available (CUDA or OpenCL), fall back to CPU |
| 123 | try: |
| 124 | platform = Platform.getPlatformByName('CUDA') |
| 125 | properties = {'DeviceIndex': '0', 'Precision': 'mixed'} |
| 126 | except Exception: |
| 127 | try: |
| 128 | platform = Platform.getPlatformByName('OpenCL') |
| 129 | properties = {} |
| 130 | except Exception: |
| 131 | platform = Platform.getPlatformByName('CPU') |
| 132 | properties = {} |
| 133 | |
| 134 | simulation = Simulation( |
| 135 | modeller.topology, system, integrator, |
| 136 | platform, properties |
| 137 | ) |
| 138 | simulation.context.setPositions(modeller.positions) |
| 139 | |
| 140 | # Check initial energy |
| 141 | state = simulation.context.getState(getEnergy=True) |
| 142 | print(f"Initial energy: {state.getPotentialEnergy()}") |
| 143 | |
| 144 | # Minimize |
| 145 | simulation.minimizeEnergy( |
| 146 | tolerance=tolerance*kilojoules_per_mole/nanometer, |
| 147 | maxIterations=max_iterations |
| 148 | ) |
| 149 | |
| 150 | state = simulation.context.getState(getEnergy=True, getPositions=True) |
| 151 | print(f"Minimized energy: {state.getPotentialEnergy()}") |
| 152 | |
| 153 | # Save minimized structure |
| 154 | with open(output_pdb, 'w') as f: |
| 155 | PDBFile.writeFile(simulation.topology, state.getPositions(), f) |
| 156 | |
| 157 | return simulation |
| 158 | |
| 159 | |
| 160 | ### 3. NVT Equilibration |
| 161 | |
| 162 | |
| 163 | from openmm.app import * |
| 164 | from openmm import * |
| 165 | from openmm.unit import * |
| 166 | |
| 167 | def run_nvt_equilibration(simulation, n_steps=50000, temperature=300, |
| 168 | report_interval=1000, output_prefix="nvt"): |
| 169 | """ |
| 170 | NVT equilibration: constant N, V, T. |
| 171 | Equilibrate velocities to target temperature. |
| 172 | |
| 173 | Args: |
| 174 | simulation: OpenMM Simulation (after minimization) |
| 175 | n_steps: Number of MD steps (50000 × 2fs = 100 ps) |
| 176 | temperature: Temperature in Kelvin |
| 177 | report_interval: Steps between data reports |
| 178 | output_prefix: File prefix for trajectory and log |
| 179 | """ |
| 180 | # Add position restraints for backbone during NVT |
| 181 | # (Optional: restraint heavy atoms) |
| 182 | |
| 183 | # Set temperature |
| 184 | simulation.context.setVelocitiesToTemperature(temperature*kelvin) |
| 185 | |
| 186 | # Add reporters |
| 187 | simulation.reporters = [] |
| 188 | |
| 189 | # Log file |
| 190 | simulation.reporters.append( |
| 191 | StateDataReporter( |
| 192 | f"{output_prefix}_log.txt", |
| 193 | report_interval, |
| 194 | step=True, |
| 195 | potentialEnergy=True, |
| 196 | kineticEnergy=True, |
| 197 | temperature=True, |
| 198 | volume=True, |
| 199 | speed=True |
| 200 | ) |
| 201 | ) |
| 202 | |
| 203 | # DCD trajectory (compact binary format) |
| 204 | simulation.reporters.append( |
| 205 | DCDReporter(f"{output_prefix}_traj.dcd", report_interval) |
| 206 | ) |
| 207 | |
| 208 | print(f"Running NVT equilibration: {n_steps} steps ({n_steps*2/1000:.1f} ps)") |
| 209 | simulation.step(n_steps) |
| 210 | print("NVT equilibration complete") |
| 211 | |
| 212 | return simulation |
| 213 | |
| 214 | |
| 215 | ### 4. NPT Equilibration and Production |
| 216 | |
| 217 | |
| 218 | def run_npt_production(simulation, n_steps=500000, temperature=300, pressure=1.0, |
| 219 | report_interval=5000, output_prefix="npt"): |
| 220 | """ |
| 221 | NPT production run: constant N, P, T. |
| 222 | |
| 223 | Args: |
| 224 | n_steps: Production steps (500000 × 2fs = 1 ns) |
| 225 | temperature: Temperature in Kelvin |
| 226 | pressure: Pressure in bar |
| 227 | report_interval: Steps between reports |
| 228 | """ |
| 229 | # Add Monte Carlo barostat for pressure control |
| 230 | system = simulation.context.getSystem() |
| 231 | system.addForce(MonteCarloBarostat(pressure*bar, temperature*kelvin, 25)) |
| 232 | simulation.context.reinitialize(preserveState=True) |
| 233 | |
| 234 | # Update reporters |
| 235 | simulation.reporters = [] |
| 236 | simulation.reporters.append( |
| 237 | StateDataReporter( |
| 238 | f"{output_prefix}_log.txt", |
| 239 | report_interval, |
| 240 | step=True, |
| 241 | potentialEnergy=True, |
| 242 | temperature=True, |
| 243 | density=True, |
| 244 | speed=True |
| 245 | ) |
| 246 | ) |
| 247 | simulation.reporters.append( |
| 248 | DCDReporter(f"{output_prefix}_traj.dcd", report_interval) |
| 249 | ) |
| 250 | |
| 251 | # Save checkpoints |
| 252 | simulation.reporters.append( |
| 253 | CheckpointReporter(f"{output_prefix}_checkpoint.chk", 50000) |
| 254 | ) |
| 255 | |
| 256 | print(f"Running NPT production: {n_steps} steps ({n_steps*2/1000000:.2f} ns)") |
| 257 | simulation.step(n_steps) |
| 258 | print("Production MD complete") |
| 259 | return simulation |
| 260 | |
| 261 | |
| 262 | ## Trajectory Analysis with MDAnalysis |
| 263 | |
| 264 | ### 1. Load Trajectory |
| 265 | |
| 266 | |
| 267 | import MDAnalysis as mda |
| 268 | from MDAnalysis.analysis import rms, align, contacts |
| 269 | import numpy as np |
| 270 | import matplotlib.pyplot as plt |
| 271 | |
| 272 | def load_trajectory(topology_file, trajectory_file): |
| 273 | """ |
| 274 | Load an MD trajectory with MDAnalysis. |
| 275 | |
| 276 | Args: |
| 277 | topology_file: PDB, PSF, or other topology file |
| 278 | trajectory_file: DCD, XTC, TRR, or other trajectory |
| 279 | """ |
| 280 | u = mda.Universe(topology_file, trajectory_file) |
| 281 | print(f"Universe: {u.atoms.n_atoms} atoms, {u.trajectory.n_frames} frames") |
| 282 | print(f"Time range: 0 to {u.trajectory.totaltime:.0f} ps") |
| 283 | return u |
| 284 | |
| 285 | |
| 286 | ### 2. RMSD Analysis |
| 287 | |
| 288 | |
| 289 | def compute_rmsd(u, selection="backbone", reference_frame=0): |
| 290 | """ |
| 291 | Compute RMSD of selected atoms relative to reference frame. |
| 292 | |
| 293 | Args: |
| 294 | u: MDAnalysis Universe |
| 295 | selection: Atom selection string (MDAnalysis syntax) |
| 296 | reference_frame: Frame index for reference structure |
| 297 | |
| 298 | Returns: |
| 299 | numpy array of (time, rmsd) values |
| 300 | """ |
| 301 | # Align trajectory to minimize RMSD |
| 302 | aligner = align.AlignTraj(u, u, select=selection, in_memory=True) |
| 303 | aligner.run() |
| 304 | |
| 305 | # Compute RMSD |
| 306 | R = rms.RMSD(u, select=selection, ref_frame=reference_frame) |
| 307 | R.run() |
| 308 | |
| 309 | rmsd_data = R.results.rmsd # columns: frame, time, RMSD |
| 310 | return rmsd_data |
| 311 | |
| 312 | def plot_rmsd(rmsd_data, title="RMSD over time", output_file="rmsd.png"): |
| 313 | """Plot RMSD over simulation time.""" |
| 314 | fig, ax = plt.subplots(figsize=(10, 4)) |
| 315 | ax.plot(rmsd_data[:, 1] / 1000, rmsd_data[:, 2], 'b-', linewidth=0.5) |
| 316 | ax.set_xlabel("Time (ns)") |
| 317 | ax.set_ylabel("RMSD (Å)") |
| 318 | ax.set_title(title) |
| 319 | ax.axhline(rmsd_data[:, 2].mean(), color='r', linestyle='--', |
| 320 | label=f'Mean: {rmsd_data[:, 2].mean():.2f} Å') |
| 321 | ax.legend() |
| 322 | plt.tight_layout() |
| 323 | plt.savefig(output_file, dpi=150) |
| 324 | return fig |
| 325 | |
| 326 | |
| 327 | ### 3. RMSF Analysis (Per-Residue Flexibility) |
| 328 | |
| 329 | |
| 330 | def compute_rmsf(u, selection="backbone", start_frame=0): |
| 331 | """ |
| 332 | Compute per-residue RMSF (flexibility). |
| 333 | |
| 334 | Returns: |
| 335 | resids, rmsf_values arrays |
| 336 | """ |
| 337 | # Select atoms |
| 338 | atoms = u.select_atoms(selection) |
| 339 | |
| 340 | # Compute RMSF |
| 341 | R = rms.RMSF(atoms) |
| 342 | R.run(start=start_frame) |
| 343 | |
| 344 | # Average by residue |
| 345 | resids = [] |
| 346 | rmsf_per_res = [] |
| 347 | for res in u.select_atoms(selection).residues: |
| 348 | res_atoms = res.atoms.intersection(atoms) |
| 349 | if len(res_atoms) > 0: |
| 350 | resids.append(res.resid) |
| 351 | rmsf_per_res.append(R.results.rmsf[res_atoms.indices].mean()) |
| 352 | |
| 353 | return np.array(resids), np.array(rmsf_per_res) |
| 354 | |
| 355 | |
| 356 | ### 4. Protein-Ligand Contacts |
| 357 | |
| 358 | |
| 359 | def analyze_contacts(u, protein_sel="protein", ligand_sel="resname LIG", |
| 360 | radius=4.5, start_frame=0): |
| 361 | """ |
| 362 | Track protein-ligand contacts over trajectory. |
| 363 | |
| 364 | Args: |
| 365 | radius: Contact distance cutoff in Angstroms |
| 366 | """ |
| 367 | protein = u.select_atoms(protein_sel) |
| 368 | ligand = u.select_atoms(ligand_sel) |
| 369 | |
| 370 | contact_frames = [] |
| 371 | for ts in u.trajectory[start_frame:]: |
| 372 | # Find protein atoms within radius of ligand |
| 373 | distances = contacts.contact_matrix( |
| 374 | protein.positions, ligand.positions, radius |
| 375 | ) |
| 376 | contact_residues = set() |
| 377 | for i in range(distances.shape[0]): |
| 378 | if distances[i].any(): |
| 379 | contact_residues.add(protein.atoms[i].resid) |
| 380 | contact_frames.append(contact_residues) |
| 381 | |
| 382 | return contact_frames |
| 383 | |
| 384 | |
| 385 | ## Force Field Selection Guide |
| 386 | |
| 387 | | System | Recommended Force Field | Water Model | |
| 388 | |--------|------------------------|-------------| |
| 389 | | Standard proteins | AMBER14 (`amber14-all.xml`) | TIP3P-FB | |
| 390 | | Proteins + small molecules | AMBER14 + GAFF2 | TIP3P-FB | |
| 391 | | Membrane proteins | CHARMM36m | TIP3P | |
| 392 | | Nucleic acids | AMBER99-bsc1 or AMBER14 | TIP3P | |
| 393 | | Disordered proteins | ff19SB or CHARMM36m | TIP3P | |
| 394 | |
| 395 | ## System Preparation Tools |
| 396 | |
| 397 | ### PDBFixer (for raw PDB files) |
| 398 | |
| 399 | |
| 400 | from pdbfixer import PDBFixer |
| 401 | from openmm.app import PDBFile |
| 402 | |
| 403 | def fix_pdb(input_pdb, output_pdb, ph=7.0): |
| 404 | """Fix common PDB issues: missing residues, atoms, add H, standardize.""" |
| 405 | fixer = PDBFixer(filename=input_pdb) |
| 406 | fixer.findMissingResidues() |
| 407 | fixer.findNonstandardResidues() |
| 408 | fixer.replaceNonstandardResidues() |
| 409 | fixer.removeHeterogens(True) # Remove water/ligands |
| 410 | fixer.findMissingAtoms() |
| 411 | fixer.addMissingAtoms() |
| 412 | fixer.addMissingHydrogens(ph) |
| 413 | |
| 414 | with open(output_pdb, 'w') as f: |
| 415 | PDBFile.writeFile(fixer.topology, fixer.positions, f) |
| 416 | |
| 417 | return output_pdb |
| 418 | |
| 419 | |
| 420 | ### GAFF2 for Small Molecules (via OpenFF Toolkit) |
| 421 | |
| 422 | |
| 423 | # For ligand parameterization, use OpenFF toolkit or ACPYPE |
| 424 | # uv pip install openff-toolkit |
| 425 | from openff.toolkit import Molecule, ForceField as OFFForceField |
| 426 | from openff.interchange import Interchange |
| 427 | |
| 428 | def parameterize_ligand(smiles, ff_name="openff-2.0.0.offxml"): |
| 429 | """Generate GAFF2/OpenFF parameters for a small molecule.""" |
| 430 | mol = Molecule.from_smiles(smiles) |
| 431 | mol.generate_conformers(n_conformers=1) |
| 432 | |
| 433 | off_ff = OFFForceField(ff_name) |
| 434 | interchange = off_ff.create_interchange(mol.to_topology()) |
| 435 | return interchange |
| 436 | |
| 437 | |
| 438 | ## Best Practices |
| 439 | |
| 440 | **Always minimize before MD**: Raw PDB structures have steric clashes |
| 441 | **Equilibrate before production**: NVT (50–100 ps) → NPT (100–500 ps) → Production |
| 442 | **Use GPU**: Simulations are 10–100× faster on GPU (CUDA/OpenCL) |
| 443 | **2 fs timestep with HBonds constraints**: Standard; use 4 fs with HMR (hydrogen mass repartitioning) |
| 444 | **Analyze only equilibrated trajectory**: Discard first 20–50% as equilibration |
| 445 | **Save checkpoints**: MD runs can fail; checkpoints allow restart |
| 446 | **Periodic boundary conditions**: Required for solvated systems |
| 447 | **PME for electrostatics**: More accurate than cutoff methods for charged systems |
| 448 | |
| 449 | ## Additional Resources |
| 450 | |
| 451 | **OpenMM documentation**: https://openmm.org/documentation.html |
| 452 | **MDAnalysis user guide**: https://docs.mdanalysis.org/ |
| 453 | **GROMACS** (alternative MD engine): https://manual.gromacs.org/ |
| 454 | **NAMD** (alternative): https://www.ks.uiuc.edu/Research/namd/ |
| 455 | **CHARMM-GUI** (web-based system builder): https://charmm-gui.org/ |
| 456 | **AmberTools** (free Amber tools): https://ambermd.org/AmberTools.php |
| 457 | **OpenMM paper**: Eastman P et al. (2017) PLOS Computational Biology. PMID: 28278240 |
| 458 | **MDAnalysis paper**: Michaud-Agrawal N et al. (2011) J Computational Chemistry. PMID: 21500218 |
| 459 |
Details
- Updated
- Sep 21, 2026
- License
- MIT
- Stars on the repo
- ★ 45,977
- Checked
- Source
- K-Dense-AI/scientific-agent-skills ↗
- Creator
- K-Dense-AI · 168 listings
Similar skills
See all →
SkillPythonic wrapper around RDKit with simplified interfaceDatamol Cheminformatics Skill
SkillMolecular ML with diverse featurizers and pre-built datasetsDeepchem
SkillDiffDock and DiffDock-L molecular dockingDiffDock: Molecular Docking with Diffusion Models
SkillProcess, clean, compare, and search tandem mass spectraMatchms
SkillMedicinal chemistry filters for compound triageMedchem
SkillMolecular featurization for MLMolfeat - Molecular Featurization HubMore from K-Dense-AI
SkillHow to use the Adaptyv Bio Foundry API and Python SDK
SkillAeon Time Series Machine Learning
SkillPlan, execute, and document validation, verificationAnalytical method validation
SkillData structure for annotated matrices in single-cellAnndata
SkillAutonomously improve a real artifact against an objectiveArbor — Autonomous Optimization via Hypothesis Tree Refinement
SkillInfer gene regulatory networks from gene expression dataArboreto