New: Earn 20% as an AgentAlley affiliate. Share your link and earn on every sale you refer. Join now New: Earn 20% as an affiliate. Join now

Run and analyze molecular dynamics simulations with OpenMM

by K-Dense-AI · MIT license · ★ 45,977 on GitHub · updated Sep 21

Molecular dynamics cover

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)
Claude Codenpx skills add K-Dense-AI/scientific-agent-skills --skill molecular-dynamics -g -a claude-code
Claude Code (manual)mkdir -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-dynamics
Windows (PowerShell)New-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" -Force
Claude.ai / desktopDownload the ZIP and upload it under Settings → Capabilities → Skills.
Codex, Cursor, other agentsPoint them at SKILL.md. The other files are plain text.

Connects with Agent Alley MCP · agentalley.io/mcp

Files included

  • SKILL.md14.4 KB
  • references/1 file · 5.5 KB
Read the files here
K-Dense-AI/49c6e972 files
SKILL.md
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

1---
2name: molecular-dynamics
3description: 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.
4license: MIT
5metadata:
6 version: "1.1"
7 skill-author: Kuan-lin Huang
8---
9 
10# Molecular Dynamics
11 
12## Overview
13 
14Molecular 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```bash
21conda install -c conda-forge openmm mdanalysis nglview
22# or
23uv pip install openmm mdanalysis
24```
25 
26## When to Use This Skill
27 
28Use 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```python
44from openmm.app import *
45from openmm import *
46from openmm.unit import *
47import sys
48 
49def 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```python
99from openmm.app import *
100from openmm import *
101from openmm.unit import *
102 
103def 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```python
163from openmm.app import *
164from openmm import *
165from openmm.unit import *
166 
167def 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```python
218def 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```python
267import MDAnalysis as mda
268from MDAnalysis.analysis import rms, align, contacts
269import numpy as np
270import matplotlib.pyplot as plt
271 
272def 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```python
289def 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 
312def 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```python
330def 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```python
359def 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```python
400from pdbfixer import PDBFixer
401from openmm.app import PDBFile
402 
403def 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```python
423# For ligand parameterization, use OpenFF toolkit or ACPYPE
424# uv pip install openff-toolkit
425from openff.toolkit import Molecule, ForceField as OFFForceField
426from openff.interchange import Interchange
427 
428def 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 
View all files on GitHub →

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
View creator

Similar skills

See all →
SkillPythonic wrapper around RDKit with simplified interfaceDatamol Cheminformatics SkillK-Dense-AI/scientific-agent-skills · by K-Dense-AIPythonic wrapper around RDKit with simplified interface and sensible defaults. Preferred for standard drug discovery including SMILES parsing, standardization, descriptors, fingerprints, clustering, 3D conformers, parallel processing. Returns native rdkit.Chem.Mol objects. For advanced control or custom parameters, use rdkit directly.★ 46k GitHub starsSkillMolecular ML with diverse featurizers and pre-built datasetsDeepchemK-Dense-AI/scientific-agent-skills · by K-Dense-AIMolecular ML with diverse featurizers and pre-built datasets. Use for property prediction (ADMET, toxicity) with traditional ML or GNNs when you want extensive featurization options and MoleculeNet benchmarks. Best for quick experiments with pre-trained models, diverse molecular representations. For graph-first PyTorch workflows use torchdrug; for benchmark datasets use pytdc.★ 46k GitHub starsSkillDiffDock and DiffDock-L molecular dockingDiffDock: Molecular Docking with Diffusion ModelsK-Dense-AI/scientific-agent-skills · by K-Dense-AIDiffDock and DiffDock-L molecular docking. Use for protein-small-molecule pose prediction from PDB or sequence plus SMILES/SDF/MOL2, batch docking, virtual screening, and pose-confidence interpretation. Not for binding affinity prediction.★ 46k GitHub starsSkillProcess, clean, compare, and search tandem mass spectraMatchmsK-Dense-AI/scientific-agent-skills · by K-Dense-AIProcess, clean, compare, and search tandem mass spectra with matchms. Use for MS/MS file I/O, metadata harmonization, peak filtering, spectral similarity, library matching, score matrices, and molecular-similarity networks. Use pyopenms instead for LC-MS feature detection or proteomics pipelines.★ 46k GitHub starsSkillMedicinal chemistry filters for compound triageMedchemK-Dense-AI/scientific-agent-skills · by K-Dense-AIMedicinal chemistry filters for compound triage. Apply drug-likeness rules (Lipinski, Veber, CNS), structural alert catalogs (PAINS, NIBR, ChEMBL), complexity metrics, and the medchem query language for library filtering.★ 46k GitHub starsSkillMolecular featurization for MLMolfeat - Molecular Featurization HubK-Dense-AI/scientific-agent-skills · by K-Dense-AIMolecular featurization for ML (100+ featurizers). ECFP, MACCS, descriptors, pretrained models (ChemBERTa), convert SMILES to features, for QSAR and molecular ML.★ 46k GitHub stars

More from K-Dense-AI

SkillHow to use the Adaptyv Bio Foundry API and Python SDKK-Dense-AI/scientific-agent-skills · by K-Dense-AIHow to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.★ 46k GitHub starsSkillAeon Time Series Machine LearningK-Dense-AI/scientific-agent-skills · by K-Dense-AIThis skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.★ 46k GitHub starsSkillPlan, execute, and document validation, verificationAnalytical method validationK-Dense-AI/scientific-agent-skills · by K-Dense-AIPlan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include "method validation", "analytical method validation", "AMV", "validation protocol", "acceptance criteria", "linearity", "reportable range", "accuracy and precision", "repeatability", "intermediate precision", "recovery", "LOD", "LOQ", "detection limit", "quantitation limit", "specificity", "robustness", "method transfer", "method comparison", "Deming", "Passing-Bablok", "Bland-Altman", "equivalence testing", "OOS investigation", "ICH Q2", "Q2(R2)", "Q14", "USP 1225", "ICH M10", "incurred sample reanalysis", "ISR", "CLSI EP", and any request to show that an assay works.★ 46k GitHub starsSkillData structure for annotated matrices in single-cellAnndataK-Dense-AI/scientific-agent-skills · by K-Dense-AIData structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.★ 46k GitHub starsSkillAutonomously improve a real artifact against an objectiveArbor — Autonomous Optimization via Hypothesis Tree RefinementK-Dense-AI/scientific-agent-skills · by K-Dense-AIAutonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g. "get my model's eval score up", "improve this agent/harness", "tune this pipeline", "beat the baseline on this benchmark", "run a search over approaches and keep the best", "do an MLE-bench / Kaggle-style optimization", or any long-horizon "make this artifact better and don't just memorize the dev set" task. Trigger it even when the user doesn't say "Arbor" or "hypothesis tree" but describes repeated experiment-and-evaluate loops, branching exploration of competing ideas, or worries about a dev/test gap. Runs Claude itself as the coordinator with subagent executors in isolated git worktrees; for the standalone `arbor` CLI tool see references/arbor-upstream.md.★ 46k GitHub starsSkillInfer gene regulatory networks from gene expression dataArboretoK-Dense-AI/scientific-agent-skills · by K-Dense-AIInfer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.★ 46k GitHub stars