[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M71JKF2MQTRJB6CJFGACJAEH":3,"skill-same:01M71JKF2MQTRJB6CJFGACJAEH":79},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":46,"commitSha":47,"skillDirectory":48,"forksCount":49,"repositoryHtmlUrl":50,"repositoryHomepageUrl":6,"ownerHtmlUrl":51,"ownerBlogUrl":52,"ownerDescription":53,"updatedAt":54,"install":55,"resources":68},"01M71JKF2MQTRJB6CJFGACJAEH","molecular-dynamics",null,"Run and analyze molecular dynamics simulations with OpenMM and MDAnalysis. Set up protein\u002Fsmall 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.","iDorgham\u002FWorkspace-Factory","iDorgham","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F136521493?v=4","01M6CNGBDAHE4ARW3YJEF4X2FD","Dorgham","01M71E8H3CXZ7DJX59MTM9JEB2",1,"MIT","https:\u002F\u002Fgithub.com\u002FiDorgham\u002FWorkspace-Factory\u002Fblob\u002Fmaster\u002Ffactory\u002Flibrary\u002Fskills\u002Fgithub_imports\u002Fmolecular-dynamics\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"molecular","dynamics","molecular dynamics","for","biophysics","Protein","Simulations","openmm","surfaces","run","energy","analyze","maps","free","biology","up","force fields","structural","structural biology","SET","2026-11-10 10:12:30",false,"---\nname: molecular-dynamics\ndescription: Run and analyze molecular dynamics simulations with OpenMM and MDAnalysis. Set up protein\u002Fsmall 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.\nlicense: MIT\nmetadata:\n    skill-author: Kuan-lin Huang\n---\n\n# Molecular Dynamics\n\n## Overview\n\nMolecular dynamics (MD) simulation computationally models the time evolution of molecular systems by integrating Newton's equations of motion. This skill covers two complementary tools:\n\n- **OpenMM** (https:\u002F\u002Fopenmm.org\u002F): High-performance MD simulation engine with GPU support, Python API, and flexible force field support\n- **MDAnalysis** (https:\u002F\u002Fmdanalysis.org\u002F): Python library for reading, writing, and analyzing MD trajectories from all major simulation packages\n\n**Installation:**\n```bash\nconda install -c conda-forge openmm mdanalysis nglview\n# or\npip install openmm mdanalysis\n```\n\n## When to Use This Skill\n\nUse molecular dynamics when:\n\n- **Protein stability analysis**: How does a mutation affect protein dynamics?\n- **Drug binding simulations**: Characterize binding mode and residence time of a ligand\n- **Conformational sampling**: Explore protein flexibility and conformational changes\n- **Protein-protein interaction**: Model interface dynamics and binding energetics\n- **RMSD\u002FRMSF analysis**: Quantify structural fluctuations from a reference structure\n- **Free energy estimation**: Compute binding free energy or conformational free energy\n- **Membrane simulations**: Model proteins in lipid bilayers\n- **Intrinsically disordered proteins**: Study IDR conformational ensembles\n\n## Core Workflow: OpenMM Simulation\n\n### 1. System Preparation\n\n```python\nfrom openmm.app import *\nfrom openmm import *\nfrom openmm.unit import *\nimport sys\n\ndef prepare_system_from_pdb(pdb_file, forcefield_name=\"amber14-all.xml\",\n                              water_model=\"amber14\u002Ftip3pfb.xml\"):\n    \"\"\"\n    Prepare an OpenMM system from a PDB file.\n\n    Args:\n        pdb_file: Path to cleaned PDB file (use PDBFixer for raw PDB files)\n        forcefield_name: Force field XML file\n        water_model: Water model XML file\n\n    Returns:\n        pdb, forcefield, system, topology\n    \"\"\"\n    # Load PDB\n    pdb = PDBFile(pdb_file)\n\n    # Load force field\n    forcefield = ForceField(forcefield_name, water_model)\n\n    # Add hydrogens and solvate\n    modeller = Modeller(pdb.topology, pdb.positions)\n    modeller.addHydrogens(forcefield)\n\n    # Add solvent box (10 Å padding, 150 mM NaCl)\n    modeller.addSolvent(\n        forcefield,\n        model='tip3p',\n        padding=10*angstroms,\n        ionicStrength=0.15*molar\n    )\n\n    print(f\"System: {modeller.topology.getNumAtoms()} atoms, \"\n          f\"{modeller.topology.getNumResidues()} residues\")\n\n    # Create system\n    system = forcefield.createSystem(\n        modeller.topology,\n        nonbondedMethod=PME,         # Particle Mesh Ewald for long-range electrostatics\n        nonbondedCutoff=1.0*nanometer,\n        constraints=HBonds,           # Constrain hydrogen bonds (allows 2 fs timestep)\n        rigidWater=True,\n        ewaldErrorTolerance=0.0005\n    )\n\n    return modeller, system\n```\n\n### 2. Energy Minimization\n\n```python\nfrom openmm.app import *\nfrom openmm import *\nfrom openmm.unit import *\n\ndef minimize_energy(modeller, system, output_pdb=\"minimized.pdb\",\n                     max_iterations=1000, tolerance=10.0):\n    \"\"\"\n    Energy minimize the system to remove steric clashes.\n\n    Args:\n        modeller: Modeller object with topology and positions\n        system: OpenMM System\n        output_pdb: Path to save minimized structure\n        max_iterations: Maximum minimization steps\n        tolerance: Convergence criterion in kJ\u002Fmol\u002Fnm\n\n    Returns:\n        simulation object with minimized positions\n    \"\"\"\n    # Set up integrator (doesn't matter for minimization)\n    integrator = LangevinMiddleIntegrator(300*kelvin, 1\u002Fpicosecond, 0.004*picoseconds)\n\n    # Create simulation\n    # Use GPU if available (CUDA or OpenCL), fall back to CPU\n    try:\n        platform = Platform.getPlatformByName('CUDA')\n        properties = {'DeviceIndex': '0', 'Precision': 'mixed'}\n    except Exception:\n        try:\n            platform = Platform.getPlatformByName('OpenCL')\n            properties = {}\n        except Exception:\n            platform = Platform.getPlatformByName('CPU')\n            properties = {}\n\n    simulation = Simulation(\n        modeller.topology, system, integrator,\n        platform, properties\n    )\n    simulation.context.setPositions(modeller.positions)\n\n    # Check initial energy\n    state = simulation.context.getState(getEnergy=True)\n    print(f\"Initial energy: {state.getPotentialEnergy()}\")\n\n    # Minimize\n    simulation.minimizeEnergy(\n        tolerance=tolerance*kilojoules_per_mole\u002Fnanometer,\n        maxIterations=max_iterations\n    )\n\n    state = simulation.context.getState(getEnergy=True, getPositions=True)\n    print(f\"Minimized energy: {state.getPotentialEnergy()}\")\n\n    # Save minimized structure\n    with open(output_pdb, 'w') as f:\n        PDBFile.writeFile(simulation.topology, state.getPositions(), f)\n\n    return simulation\n```\n\n### 3. NVT Equilibration\n\n```python\nfrom openmm.app import *\nfrom openmm import *\nfrom openmm.unit import *\n\ndef run_nvt_equilibration(simulation, n_steps=50000, temperature=300,\n                            report_interval=1000, output_prefix=\"nvt\"):\n    \"\"\"\n    NVT equilibration: constant N, V, T.\n    Equilibrate velocities to target temperature.\n\n    Args:\n        simulation: OpenMM Simulation (after minimization)\n        n_steps: Number of MD steps (50000 × 2fs = 100 ps)\n        temperature: Temperature in Kelvin\n        report_interval: Steps between data reports\n        output_prefix: File prefix for trajectory and log\n    \"\"\"\n    # Add position restraints for backbone during NVT\n    # (Optional: restraint heavy atoms)\n\n    # Set temperature\n    simulation.context.setVelocitiesToTemperature(temperature*kelvin)\n\n    # Add reporters\n    simulation.reporters = []\n\n    # Log file\n    simulation.reporters.append(\n        StateDataReporter(\n            f\"{output_prefix}_log.txt\",\n            report_interval,\n            step=True,\n            potentialEnergy=True,\n            kineticEnergy=True,\n            temperature=True,\n            volume=True,\n            speed=True\n        )\n    )\n\n    # DCD trajectory (compact binary format)\n    simulation.reporters.append(\n        DCDReporter(f\"{output_prefix}_traj.dcd\", report_interval)\n    )\n\n    print(f\"Running NVT equilibration: {n_steps} steps ({n_steps*2\u002F1000:.1f} ps)\")\n    simulation.step(n_steps)\n    print(\"NVT equilibration complete\")\n\n    return simulation\n```\n\n### 4. NPT Equilibration and Production\n\n```python\ndef run_npt_production(simulation, n_steps=500000, temperature=300, pressure=1.0,\n                        report_interval=5000, output_prefix=\"npt\"):\n    \"\"\"\n    NPT production run: constant N, P, T.\n\n    Args:\n        n_steps: Production steps (500000 × 2fs = 1 ns)\n        temperature: Temperature in Kelvin\n        pressure: Pressure in bar\n        report_interval: Steps between reports\n    \"\"\"\n    # Add Monte Carlo barostat for pressure control\n    system = simulation.context.getSystem()\n    system.addForce(MonteCarloBarostat(pressure*bar, temperature*kelvin, 25))\n    simulation.context.reinitialize(preserveState=True)\n\n    # Update reporters\n    simulation.reporters = []\n    simulation.reporters.append(\n        StateDataReporter(\n            f\"{output_prefix}_log.txt\",\n            report_interval,\n            step=True,\n            potentialEnergy=True,\n            temperature=True,\n            density=True,\n            speed=True\n        )\n    )\n    simulation.reporters.append(\n        DCDReporter(f\"{output_prefix}_traj.dcd\", report_interval)\n    )\n\n    # Save checkpoints\n    simulation.reporters.append(\n        CheckpointReporter(f\"{output_prefix}_checkpoint.chk\", 50000)\n    )\n\n    print(f\"Running NPT production: {n_steps} steps ({n_steps*2\u002F1000000:.2f} ns)\")\n    simulation.step(n_steps)\n    print(\"Production MD complete\")\n    return simulation\n```\n\n## Trajectory Analysis with MDAnalysis\n\n### 1. Load Trajectory\n\n```python\nimport MDAnalysis as mda\nfrom MDAnalysis.analysis import rms, align, contacts\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef load_trajectory(topology_file, trajectory_file):\n    \"\"\"\n    Load an MD trajectory with MDAnalysis.\n\n    Args:\n        topology_file: PDB, PSF, or other topology file\n        trajectory_file: DCD, XTC, TRR, or other trajectory\n    \"\"\"\n    u = mda.Universe(topology_file, trajectory_file)\n    print(f\"Universe: {u.atoms.n_atoms} atoms, {u.trajectory.n_frames} frames\")\n    print(f\"Time range: 0 to {u.trajectory.totaltime:.0f} ps\")\n    return u\n```\n\n### 2. RMSD Analysis\n\n```python\ndef compute_rmsd(u, selection=\"backbone\", reference_frame=0):\n    \"\"\"\n    Compute RMSD of selected atoms relative to reference frame.\n\n    Args:\n        u: MDAnalysis Universe\n        selection: Atom selection string (MDAnalysis syntax)\n        reference_frame: Frame index for reference structure\n\n    Returns:\n        numpy array of (time, rmsd) values\n    \"\"\"\n    # Align trajectory to minimize RMSD\n    aligner = align.AlignTraj(u, u, select=selection, in_memory=True)\n    aligner.run()\n\n    # Compute RMSD\n    R = rms.RMSD(u, select=selection, ref_frame=reference_frame)\n    R.run()\n\n    rmsd_data = R.results.rmsd  # columns: frame, time, RMSD\n    return rmsd_data\n\ndef plot_rmsd(rmsd_data, title=\"RMSD over time\", output_file=\"rmsd.png\"):\n    \"\"\"Plot RMSD over simulation time.\"\"\"\n    fig, ax = plt.subplots(figsize=(10, 4))\n    ax.plot(rmsd_data[:, 1] \u002F 1000, rmsd_data[:, 2], 'b-', linewidth=0.5)\n    ax.set_xlabel(\"Time (ns)\")\n    ax.set_ylabel(\"RMSD (Å)\")\n    ax.set_title(title)\n    ax.axhline(rmsd_data[:, 2].mean(), color='r', linestyle='--',\n               label=f'Mean: {rmsd_data[:, 2].mean():.2f} Å')\n    ax.legend()\n    plt.tight_layout()\n    plt.savefig(output_file, dpi=150)\n    return fig\n```\n\n### 3. RMSF Analysis (Per-Residue Flexibility)\n\n```python\ndef compute_rmsf(u, selection=\"backbone\", start_frame=0):\n    \"\"\"\n    Compute per-residue RMSF (flexibility).\n\n    Returns:\n        resids, rmsf_values arrays\n    \"\"\"\n    # Select atoms\n    atoms = u.select_atoms(selection)\n\n    # Compute RMSF\n    R = rms.RMSF(atoms)\n    R.run(start=start_frame)\n\n    # Average by residue\n    resids = []\n    rmsf_per_res = []\n    for res in u.select_atoms(selection).residues:\n        res_atoms = res.atoms.intersection(atoms)\n        if len(res_atoms) > 0:\n            resids.append(res.resid)\n            rmsf_per_res.append(R.results.rmsf[res_atoms.indices].mean())\n\n    return np.array(resids), np.array(rmsf_per_res)\n```\n\n### 4. Protein-Ligand Contacts\n\n```python\ndef analyze_contacts(u, protein_sel=\"protein\", ligand_sel=\"resname LIG\",\n                      radius=4.5, start_frame=0):\n    \"\"\"\n    Track protein-ligand contacts over trajectory.\n\n    Args:\n        radius: Contact distance cutoff in Angstroms\n    \"\"\"\n    protein = u.select_atoms(protein_sel)\n    ligand = u.select_atoms(ligand_sel)\n\n    contact_frames = []\n    for ts in u.trajectory[start_frame:]:\n        # Find protein atoms within radius of ligand\n        distances = contacts.contact_matrix(\n            protein.positions, ligand.positions, radius\n        )\n        contact_residues = set()\n        for i in range(distances.shape[0]):\n            if distances[i].any():\n                contact_residues.add(protein.atoms[i].resid)\n        contact_frames.append(contact_residues)\n\n    return contact_frames\n```\n\n## Force Field Selection Guide\n\n| System | Recommended Force Field | Water Model |\n|--------|------------------------|-------------|\n| Standard proteins | AMBER14 (`amber14-all.xml`) | TIP3P-FB |\n| Proteins + small molecules | AMBER14 + GAFF2 | TIP3P-FB |\n| Membrane proteins | CHARMM36m | TIP3P |\n| Nucleic acids | AMBER99-bsc1 or AMBER14 | TIP3P |\n| Disordered proteins | ff19SB or CHARMM36m | TIP3P |\n\n## System Preparation Tools\n\n### PDBFixer (for raw PDB files)\n\n```python\nfrom pdbfixer import PDBFixer\nfrom openmm.app import PDBFile\n\ndef fix_pdb(input_pdb, output_pdb, ph=7.0):\n    \"\"\"Fix common PDB issues: missing residues, atoms, add H, standardize.\"\"\"\n    fixer = PDBFixer(filename=input_pdb)\n    fixer.findMissingResidues()\n    fixer.findNonstandardResidues()\n    fixer.replaceNonstandardResidues()\n    fixer.removeHeterogens(True)    # Remove water\u002Fligands\n    fixer.findMissingAtoms()\n    fixer.addMissingAtoms()\n    fixer.addMissingHydrogens(ph)\n\n    with open(output_pdb, 'w') as f:\n        PDBFile.writeFile(fixer.topology, fixer.positions, f)\n\n    return output_pdb\n```\n\n### GAFF2 for Small Molecules (via OpenFF Toolkit)\n\n```python\n# For ligand parameterization, use OpenFF toolkit or ACPYPE\n# pip install openff-toolkit\nfrom openff.toolkit import Molecule, ForceField as OFFForceField\nfrom openff.interchange import Interchange\n\ndef parameterize_ligand(smiles, ff_name=\"openff-2.0.0.offxml\"):\n    \"\"\"Generate GAFF2\u002FOpenFF parameters for a small molecule.\"\"\"\n    mol = Molecule.from_smiles(smiles)\n    mol.generate_conformers(n_conformers=1)\n\n    off_ff = OFFForceField(ff_name)\n    interchange = off_ff.create_interchange(mol.to_topology())\n    return interchange\n```\n\n## Best Practices\n\n- **Always minimize before MD**: Raw PDB structures have steric clashes\n- **Equilibrate before production**: NVT (50–100 ps) → NPT (100–500 ps) → Production\n- **Use GPU**: Simulations are 10–100× faster on GPU (CUDA\u002FOpenCL)\n- **2 fs timestep with HBonds constraints**: Standard; use 4 fs with HMR (hydrogen mass repartitioning)\n- **Analyze only equilibrated trajectory**: Discard first 20–50% as equilibration\n- **Save checkpoints**: MD runs can fail; checkpoints allow restart\n- **Periodic boundary conditions**: Required for solvated systems\n- **PME for electrostatics**: More accurate than cutoff methods for charged systems\n\n## Additional Resources\n\n- **OpenMM documentation**: https:\u002F\u002Fopenmm.org\u002Fdocumentation.html\n- **MDAnalysis user guide**: https:\u002F\u002Fdocs.mdanalysis.org\u002F\n- **GROMACS** (alternative MD engine): https:\u002F\u002Fmanual.gromacs.org\u002F\n- **NAMD** (alternative): https:\u002F\u002Fwww.ks.uiuc.edu\u002FResearch\u002Fnamd\u002F\n- **CHARMM-GUI** (web-based system builder): https:\u002F\u002Fcharmm-gui.org\u002F\n- **AmberTools** (free Amber tools): https:\u002F\u002Fambermd.org\u002FAmberTools.php\n- **OpenMM paper**: Eastman P et al. (2017) PLOS Computational Biology. PMID: 28278240\n- **MDAnalysis paper**: Michaud-Agrawal N et al. (2011) J Computational Chemistry. PMID: 21500218\n","# Molecular Dynamics\n\n## Overview\n\nMolecular dynamics (MD) simulation computationally models the time evolution of molecular systems by integrating Newton's equations of motion. This skill covers two complementary tools:\n\n- **OpenMM** (https:\u002F\u002Fopenmm.org\u002F): High-performance MD simulation engine with GPU support, Python API, and flexible force field support\n- **MDAnalysis** (https:\u002F\u002Fmdanalysis.org\u002F): Python library for reading, writing, and analyzing MD trajectories from all major simulation packages\n\n**Installation:**\n```bash\nconda install -c conda-forge openmm mdanalysis nglview\n# or\npip install openmm mdanalysis\n```\n\n## When to Use This Skill\n\nUse molecular dynamics when:\n\n- **Protein stability analysis**: How does a mutation affect protein dynamics?\n- **Drug binding simulations**: Characterize binding mode and residence time of a ligand\n- **Conformational sampling**: Explore protein flexibility and conformational changes\n- **Protein-protein interaction**: Model interface dynamics and binding energetics\n- **RMSD\u002FRMSF analysis**: Quantify structural fluctuations from a reference structure\n- **Free energy estimation**: Compute binding free energy or conformational free energy\n- **Membrane simulations**: Model proteins in lipid bilayers\n- **Intrinsically disordered proteins**: Study IDR conformational ensembles\n\n## Core Workflow: OpenMM Simulation\n\n### 1. System Preparation\n\n```python\nfrom openmm.app import *\nfrom openmm import *\nfrom openmm.unit import *\nimport sys\n\ndef prepare_system_from_pdb(pdb_file, forcefield_name=\"amber14-all.xml\",\n                              water_model=\"amber14\u002Ftip3pfb.xml\"):\n    \"\"\"\n    Prepare an OpenMM system from a PDB file.\n\n    Args:\n        pdb_file: Path to cleaned PDB file (use PDBFixer for raw PDB files)\n        forcefield_name: Force field XML file\n        water_model: Water model XML file\n\n    Returns:\n        pdb, forcefield, system, topology\n    \"\"\"\n    # Load PDB\n    pdb = PDBFile(pdb_file)\n\n    # Load force field\n    forcefield = ForceField(forcefield_name, water_model)\n\n    # Add hydrogens and solvate\n    modeller = Modeller(pdb.topology, pdb.positions)\n    modeller.addHydrogens(forcefield)\n\n    # Add solvent box (10 Å padding, 150 mM NaCl)\n    modeller.addSolvent(\n        forcefield,\n        model='tip3p',\n        padding=10*angstroms,\n        ionicStrength=0.15*molar\n    )\n\n    print(f\"System: {modeller.topology.getNumAtoms()} atoms, \"\n          f\"{modeller.topology.getNumResidues()} residues\")\n\n    # Create system\n    system = forcefield.createSystem(\n        modeller.topology,\n        nonbondedMethod=PME,         # Particle Mesh Ewald for long-range electrostatics\n        nonbondedCutoff=1.0*nanometer,\n        constraints=HBonds,           # Constrain hydrogen bonds (allows 2 fs timestep)\n        rigidWater=True,\n        ewaldErrorTolerance=0.0005\n    )\n\n    return modeller, system\n```\n\n### 2. Energy Minimization\n\n```python\nfrom openmm.app import *\nfrom openmm import *\nfrom openmm.unit import *\n\ndef minimize_energy(modeller, system, output_pdb=\"minimized.pdb\",\n                     max_iterations=1000, tolerance=10.0):\n    \"\"\"\n    Energy minimize the system to remove steric clashes.\n\n    Args:\n        modeller: Modeller object with topology and positions\n        system: OpenMM System\n        output_pdb: Path to save minimized structure\n        max_iterations: Maximum minimization steps\n        tolerance: Convergence criterion in kJ\u002Fmol\u002Fnm\n\n    Returns:\n        simulation object with minimized positions\n    \"\"\"\n    # Set up integrator (doesn't matter for minimization)\n    integrator = LangevinMiddleIntegrator(300*kelvin, 1\u002Fpicosecond, 0.004*picoseconds)\n\n    # Create simulation\n    # Use GPU if available (CUDA or OpenCL), fall back to CPU\n    try:\n        platform = Platform.getPlatformByName('CUDA')\n        properties = {'DeviceIndex': '0', 'Precision': 'mixed'}\n    except Exception:\n        try:\n            platform = Platform.getPlatformByName('OpenCL')\n            properties = {}\n        except Exception:\n            platform = Platform.getPlatformByName('CPU')\n            properties = {}\n\n    simulation = Simulation(\n        modeller.topology, system, integrator,\n        platform, properties\n    )\n    simulation.context.setPositions(modeller.positions)\n\n    # Check initial energy\n    state = simulation.context.getState(getEnergy=True)\n    print(f\"Initial energy: {state.getPotentialEnergy()}\")\n\n    # Minimize\n    simulation.minimizeEnergy(\n        tolerance=tolerance*kilojoules_per_mole\u002Fnanometer,\n        maxIterations=max_iterations\n    )\n\n    state = simulation.context.getState(getEnergy=True, getPositions=True)\n    print(f\"Minimized energy: {state.getPotentialEnergy()}\")\n\n    # Save minimized structure\n    with open(output_pdb, 'w') as f:\n        PDBFile.writeFile(simulation.topology, state.getPositions(), f)\n\n    return simulation\n```\n\n### 3. NVT Equilibration\n\n```python\nfrom openmm.app import *\nfrom openmm import *\nfrom openmm.unit import *\n\ndef run_nvt_equilibration(simulation, n_steps=50000, temperature=300,\n                            report_interval=1000, output_prefix=\"nvt\"):\n    \"\"\"\n    NVT equilibration: constant N, V, T.\n    Equilibrate velocities to target temperature.\n\n    Args:\n        simulation: OpenMM Simulation (after minimization)\n        n_steps: Number of MD steps (50000 × 2fs = 100 ps)\n        temperature: Temperature in Kelvin\n        report_interval: Steps between data reports\n        output_prefix: File prefix for trajectory and log\n    \"\"\"\n    # Add position restraints for backbone during NVT\n    # (Optional: restraint heavy atoms)\n\n    # Set temperature\n    simulation.context.setVelocitiesToTemperature(temperature*kelvin)\n\n    # Add reporters\n    simulation.reporters = []\n\n    # Log file\n    simulation.reporters.append(\n        StateDataReporter(\n            f\"{output_prefix}_log.txt\",\n            report_interval,\n            step=True,\n            potentialEnergy=True,\n            kineticEnergy=True,\n            temperature=True,\n            volume=True,\n            speed=True\n        )\n    )\n\n    # DCD trajectory (compact binary format)\n    simulation.reporters.append(\n        DCDReporter(f\"{output_prefix}_traj.dcd\", report_interval)\n    )\n\n    print(f\"Running NVT equilibration: {n_steps} steps ({n_steps*2\u002F1000:.1f} ps)\")\n    simulation.step(n_steps)\n    print(\"NVT equilibration complete\")\n\n    return simulation\n```\n\n### 4. NPT Equilibration and Production\n\n```python\ndef run_npt_production(simulation, n_steps=500000, temperature=300, pressure=1.0,\n                        report_interval=5000, output_prefix=\"npt\"):\n    \"\"\"\n    NPT production run: constant N, P, T.\n\n    Args:\n        n_steps: Production steps (500000 × 2fs = 1 ns)\n        temperature: Temperature in Kelvin\n        pressure: Pressure in bar\n        report_interval: Steps between reports\n    \"\"\"\n    # Add Monte Carlo barostat for pressure control\n    system = simulation.context.getSystem()\n    system.addForce(MonteCarloBarostat(pressure*bar, temperature*kelvin, 25))\n    simulation.context.reinitialize(preserveState=True)\n\n    # Update reporters\n    simulation.reporters = []\n    simulation.reporters.append(\n        StateDataReporter(\n            f\"{output_prefix}_log.txt\",\n            report_interval,\n            step=True,\n            potentialEnergy=True,\n            temperature=True,\n            density=True,\n            speed=True\n        )\n    )\n    simulation.reporters.append(\n        DCDReporter(f\"{output_prefix}_traj.dcd\", report_interval)\n    )\n\n    # Save checkpoints\n    simulation.reporters.append(\n        CheckpointReporter(f\"{output_prefix}_checkpoint.chk\", 50000)\n    )\n\n    print(f\"Running NPT production: {n_steps} steps ({n_steps*2\u002F1000000:.2f} ns)\")\n    simulation.step(n_steps)\n    print(\"Production MD complete\")\n    return simulation\n```\n\n## Trajectory Analysis with MDAnalysis\n\n### 1. Load Trajectory\n\n```python\nimport MDAnalysis as mda\nfrom MDAnalysis.analysis import rms, align, contacts\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef load_trajectory(topology_file, trajectory_file):\n    \"\"\"\n    Load an MD trajectory with MDAnalysis.\n\n    Args:\n        topology_file: PDB, PSF, or other topology file\n        trajectory_file: DCD, XTC, TRR, or other trajectory\n    \"\"\"\n    u = mda.Universe(topology_file, trajectory_file)\n    print(f\"Universe: {u.atoms.n_atoms} atoms, {u.trajectory.n_frames} frames\")\n    print(f\"Time range: 0 to {u.trajectory.totaltime:.0f} ps\")\n    return u\n```\n\n### 2. RMSD Analysis\n\n```python\ndef compute_rmsd(u, selection=\"backbone\", reference_frame=0):\n    \"\"\"\n    Compute RMSD of selected atoms relative to reference frame.\n\n    Args:\n        u: MDAnalysis Universe\n        selection: Atom selection string (MDAnalysis syntax)\n        reference_frame: Frame index for reference structure\n\n    Returns:\n        numpy array of (time, rmsd) values\n    \"\"\"\n    # Align trajectory to minimize RMSD\n    aligner = align.AlignTraj(u, u, select=selection, in_memory=True)\n    aligner.run()\n\n    # Compute RMSD\n    R = rms.RMSD(u, select=selection, ref_frame=reference_frame)\n    R.run()\n\n    rmsd_data = R.results.rmsd  # columns: frame, time, RMSD\n    return rmsd_data\n\ndef plot_rmsd(rmsd_data, title=\"RMSD over time\", output_file=\"rmsd.png\"):\n    \"\"\"Plot RMSD over simulation time.\"\"\"\n    fig, ax = plt.subplots(figsize=(10, 4))\n    ax.plot(rmsd_data[:, 1] \u002F 1000, rmsd_data[:, 2], 'b-', linewidth=0.5)\n    ax.set_xlabel(\"Time (ns)\")\n    ax.set_ylabel(\"RMSD (Å)\")\n    ax.set_title(title)\n    ax.axhline(rmsd_data[:, 2].mean(), color='r', linestyle='--',\n               label=f'Mean: {rmsd_data[:, 2].mean():.2f} Å')\n    ax.legend()\n    plt.tight_layout()\n    plt.savefig(output_file, dpi=150)\n    return fig\n```\n\n### 3. RMSF Analysis (Per-Residue Flexibility)\n\n```python\ndef compute_rmsf(u, selection=\"backbone\", start_frame=0):\n    \"\"\"\n    Compute per-residue RMSF (flexibility).\n\n    Returns:\n        resids, rmsf_values arrays\n    \"\"\"\n    # Select atoms\n    atoms = u.select_atoms(selection)\n\n    # Compute RMSF\n    R = rms.RMSF(atoms)\n    R.run(start=start_frame)\n\n    # Average by residue\n    resids = []\n    rmsf_per_res = []\n    for res in u.select_atoms(selection).residues:\n        res_atoms = res.atoms.intersection(atoms)\n        if len(res_atoms) > 0:\n            resids.append(res.resid)\n            rmsf_per_res.append(R.results.rmsf[res_atoms.indices].mean())\n\n    return np.array(resids), np.array(rmsf_per_res)\n```\n\n### 4. Protein-Ligand Contacts\n\n```python\ndef analyze_contacts(u, protein_sel=\"protein\", ligand_sel=\"resname LIG\",\n                      radius=4.5, start_frame=0):\n    \"\"\"\n    Track protein-ligand contacts over trajectory.\n\n    Args:\n        radius: Contact distance cutoff in Angstroms\n    \"\"\"\n    protein = u.select_atoms(protein_sel)\n    ligand = u.select_atoms(ligand_sel)\n\n    contact_frames = []\n    for ts in u.trajectory[start_frame:]:\n        # Find protein atoms within radius of ligand\n        distances = contacts.contact_matrix(\n            protein.positions, ligand.positions, radius\n        )\n        contact_residues = set()\n        for i in range(distances.shape[0]):\n            if distances[i].any():\n                contact_residues.add(protein.atoms[i].resid)\n        contact_frames.append(contact_residues)\n\n    return contact_frames\n```\n\n## Force Field Selection Guide\n\n| System | Recommended Force Field | Water Model |\n|--------|------------------------|-------------|\n| Standard proteins | AMBER14 (`amber14-all.xml`) | TIP3P-FB |\n| Proteins + small molecules | AMBER14 + GAFF2 | TIP3P-FB |\n| Membrane proteins | CHARMM36m | TIP3P |\n| Nucleic acids | AMBER99-bsc1 or AMBER14 | TIP3P |\n| Disordered proteins | ff19SB or CHARMM36m | TIP3P |\n\n## System Preparation Tools\n\n### PDBFixer (for raw PDB files)\n\n```python\nfrom pdbfixer import PDBFixer\nfrom openmm.app import PDBFile\n\ndef fix_pdb(input_pdb, output_pdb, ph=7.0):\n    \"\"\"Fix common PDB issues: missing residues, atoms, add H, standardize.\"\"\"\n    fixer = PDBFixer(filename=input_pdb)\n    fixer.findMissingResidues()\n    fixer.findNonstandardResidues()\n    fixer.replaceNonstandardResidues()\n    fixer.removeHeterogens(True)    # Remove water\u002Fligands\n    fixer.findMissingAtoms()\n    fixer.addMissingAtoms()\n    fixer.addMissingHydrogens(ph)\n\n    with open(output_pdb, 'w') as f:\n        PDBFile.writeFile(fixer.topology, fixer.positions, f)\n\n    return output_pdb\n```\n\n### GAFF2 for Small Molecules (via OpenFF Toolkit)\n\n```python\n# For ligand parameterization, use OpenFF toolkit or ACPYPE\n# pip install openff-toolkit\nfrom openff.toolkit import Molecule, ForceField as OFFForceField\nfrom openff.interchange import Interchange\n\ndef parameterize_ligand(smiles, ff_name=\"openff-2.0.0.offxml\"):\n    \"\"\"Generate GAFF2\u002FOpenFF parameters for a small molecule.\"\"\"\n    mol = Molecule.from_smiles(smiles)\n    mol.generate_conformers(n_conformers=1)\n\n    off_ff = OFFForceField(ff_name)\n    interchange = off_ff.create_interchange(mol.to_topology())\n    return interchange\n```\n\n## Best Practices\n\n- **Always minimize before MD**: Raw PDB structures have steric clashes\n- **Equilibrate before production**: NVT (50–100 ps) → NPT (100–500 ps) → Production\n- **Use GPU**: Simulations are 10–100× faster on GPU (CUDA\u002FOpenCL)\n- **2 fs timestep with HBonds constraints**: Standard; use 4 fs with HMR (hydrogen mass repartitioning)\n- **Analyze only equilibrated trajectory**: Discard first 20–50% as equilibration\n- **Save checkpoints**: MD runs can fail; checkpoints allow restart\n- **Periodic boundary conditions**: Required for solvated systems\n- **PME for electrostatics**: More accurate than cutoff methods for charged systems\n\n## Additional Resources\n\n- **OpenMM documentation**: https:\u002F\u002Fopenmm.org\u002Fdocumentation.html\n- **MDAnalysis user guide**: https:\u002F\u002Fdocs.mdanalysis.org\u002F\n- **GROMACS** (alternative MD engine): https:\u002F\u002Fmanual.gromacs.org\u002F\n- **NAMD** (alternative): https:\u002F\u002Fwww.ks.uiuc.edu\u002FResearch\u002Fnamd\u002F\n- **CHARMM-GUI** (web-based system builder): https:\u002F\u002Fcharmm-gui.org\u002F\n- **AmberTools** (free Amber tools): https:\u002F\u002Fambermd.org\u002FAmberTools.php\n- **OpenMM paper**: Eastman P et al. (2017) PLOS Computational Biology. PMID: 28278240\n- **MDAnalysis paper**: Michaud-Agrawal N et al. (2011) J Computational Chemistry. PMID: 21500218\n",{"name":5,"license":15,"metadata":44,"description":7},{"skill-author":45},"Kuan-lin Huang","master","c2e410e11df4d80d885e0ecf0583ef3c926df736","factory\u002Flibrary\u002Fskills\u002Fgithub_imports\u002Fmolecular-dynamics",0,"https:\u002F\u002Fgithub.com\u002FiDorgham\u002FWorkspace-Factory","https:\u002F\u002Fgithub.com\u002FiDorgham","Dorgham.me","hey I'm Dorgham \r\nI code, I create, and AI codes back. \r\nMaybe we can give AI the chance!! now we begin. 🚀🤖\r\n... . . . git commit -m \"Hello, Future\" ","2026-05-04 18:39:09",{"source":8,"skillName":5,"commands":56,"prompt":66,"zipAvailable":67},[57,60,63],{"tool":58,"command":59},"npx","npx skills add iDorgham\u002FWorkspace-Factory --skill molecular-dynamics",{"tool":61,"command":62},"bunx","bunx skills add iDorgham\u002FWorkspace-Factory --skill molecular-dynamics",{"tool":64,"command":65},"pnpm","pnpm dlx skills add iDorgham\u002FWorkspace-Factory --skill molecular-dynamics","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FiDorgham\u002FWorkspace-Factory\u002Fblob\u002Fmaster\u002Ffactory\u002Flibrary\u002Fskills\u002Fgithub_imports\u002Fmolecular-dynamics\u002FSKILL.md",true,[69,75],{"path":70,"resourceType":71,"resourceTypeDesc":72,"sizeBytes":73,"sourceHtmlUrl":74},"_AIWF_IMPORT.json","REFERENCE","参考文档",374,"https:\u002F\u002Fgithub.com\u002FiDorgham\u002FWorkspace-Factory\u002Fblob\u002Fmaster\u002Ffactory\u002Flibrary\u002Fskills\u002Fgithub_imports\u002Fmolecular-dynamics\u002F_AIWF_IMPORT.json",{"path":76,"resourceType":71,"resourceTypeDesc":72,"sizeBytes":77,"sourceHtmlUrl":78},"references\u002Fmdanalysis_analysis.md",5643,"https:\u002F\u002Fgithub.com\u002FiDorgham\u002FWorkspace-Factory\u002Fblob\u002Fmaster\u002Ffactory\u002Flibrary\u002Fskills\u002Fgithub_imports\u002Fmolecular-dynamics\u002Freferences\u002Fmdanalysis_analysis.md",[80,113,135,157,177,200],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":91,"publishedAt":112},"01M71P8WVBMB2X3D24R0YT0B0E","vercel-react-view-transitions","Guide for implementing smooth, native-feeling animations using React's View Transition API (`\u003CViewTransition>` component, `addTransitionType`, and CSS view transition pseudo-elements). Use this skill whenever the user wants to add page transitions, animate route changes, create shared element animations, animate enter\u002Fexit of components, animate list reorder, implement directional (forward\u002Fback) navigation animations, or integrate view transitions in Next.js. Also use when the user mentions view transitions, `startViewTransition`, `ViewTransition`, transition types, or asks about animating between UI states in React without third-party animation libraries.","https:\u002F\u002Fgithub.com\u002FiDorgham\u002FWorkspace-Factory\u002Fblob\u002Fmaster\u002Ffactory\u002Flibrary\u002Fskills\u002Fofficial_vercel_labs_react_view_transitions\u002Fskill.md",[86],{"categoryNo":87,"categoryName":88,"taxonomyType":89,"taxonomyTypeDesc":90},"01JBSEEDCAT000000000000009","前端开发","SCENARIO","使用场景",[92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111],"react","vercel react view transitions","view","react view transitions","vercel","transitions","shared","back","Animation","css","types","states","element","implementing","when","components","api","route","create","libraries","2026-11-10 13:02:02",{"skillNo":114,"name":115,"nameZh":6,"description":116,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":117,"categories":118,"keywords":120,"publishedAt":112},"01M71P8TDGHZ289TSAC5VTG2EW","vercel-react-native-skills","React Native and Expo best practices for building performant mobile apps. Use when building React Native components, optimizing list performance, implementing animations, or working with native modules. Triggers on tasks involving React Native, Expo, mobile performance, or native platform APIs.","https:\u002F\u002Fgithub.com\u002FiDorgham\u002FWorkspace-Factory\u002Fblob\u002Fmaster\u002Ffactory\u002Flibrary\u002Fskills\u002Fofficial_vercel_labs_react_native_skills\u002Fskill.md",[119],{"categoryNo":87,"categoryName":88,"taxonomyType":89,"taxonomyTypeDesc":90},[92,121,122,96,123,124,125,126,105,127,106,128,107,129,130,131,132,133,134,22],"react native","native","vercel react native skills","react native skills","modules","performance","apps","tasks","mobile","expo","list","mobile performance","platform","animations",{"skillNo":136,"name":137,"nameZh":6,"description":138,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":139,"categories":140,"keywords":142,"publishedAt":112},"01M71P8QK4JF5BYRGYDDGPZQG9","vercel-react-best-practices","React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React\u002FNext.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.","https:\u002F\u002Fgithub.com\u002FiDorgham\u002FWorkspace-Factory\u002Fblob\u002Fmaster\u002Ffactory\u002Flibrary\u002Fskills\u002Fofficial_vercel_labs_react_best_practices\u002Fskill.md",[141],{"categoryNo":87,"categoryName":88,"taxonomyType":89,"taxonomyTypeDesc":90},[92,143,144,96,145,126,146,106,147,128,107,148,149,150,151,152,153,154,155,156],"react best practices","vercel react best practices","best practices","writing","code","data fetching","react components","next","refactoring","data","patterns","Optimization","guidelines","triggers",{"skillNo":158,"name":159,"nameZh":6,"description":160,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":161,"categories":162,"keywords":164,"publishedAt":112},"01M71P8HVEA70K5N6ZVJCG2ED3","vercel-composition-patterns","React composition patterns that scale. Use when refactoring components with boolean prop proliferation, building flexible component libraries, or designing reusable APIs. Triggers on tasks involving compound components, render props, context providers, or component architecture. Includes React 19 API changes.","https:\u002F\u002Fgithub.com\u002FiDorgham\u002FWorkspace-Factory\u002Fblob\u002Fmaster\u002Ffactory\u002Flibrary\u002Fskills\u002Fofficial_vercel_labs_composition_patterns\u002Fskill.md",[163],{"categoryNo":87,"categoryName":88,"taxonomyType":89,"taxonomyTypeDesc":90},[165,96,166,153,167,168,169,170,156,171,172,173,106,174,128,107,175,176,108,92],"Composition","composition patterns","vercel composition patterns","react composition patterns","react 19","render","boolean","component architecture","use","reusable","architecture","react composition",{"skillNo":178,"name":179,"nameZh":6,"description":180,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":181,"categories":182,"keywords":186,"publishedAt":112},"01M71P60XXKKP222ZFJRG7R373","supabase-postgres-best-practices","Postgres performance optimization and best practices from Supabase. Use this skill when writing, reviewing, or optimizing Postgres queries, schema designs, or database configurations.","https:\u002F\u002Fgithub.com\u002FiDorgham\u002FWorkspace-Factory\u002Fblob\u002Fmaster\u002Ffactory\u002Flibrary\u002Fskills\u002Fofficial_supabase_supabase_postgres_best_practices\u002Fskill.md",[183],{"categoryNo":184,"categoryName":185,"taxonomyType":89,"taxonomyTypeDesc":90},"01JBSEEDCAT000000000000010","后端与接口",[187,188,189,190,145,191,192,193,22,154,126,194,195,146,196,173,197,198,199,106],"postgres best practices","supabase","postgres","supabase postgres best practices","categories","postgres performance","advanced","correct","schema","impact","Rules","critical","database",{"skillNo":201,"name":202,"nameZh":6,"description":203,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":204,"categories":205,"keywords":207,"publishedAt":223},"01M71P2ZCEJD0PKC458YTP1FJW","portable-text-serialization","Render and serialize Portable Text to React, Svelte, Vue, Astro, HTML, Markdown, and plain text. Use when implementing Portable Text rendering in any frontend framework, building custom serializers for non-standard block types, converting Portable Text to HTML strings server-side, converting Portable Text to Markdown, extracting plain text from Portable Text, or troubleshooting rendering issues with marks, blocks, lists, or custom types.","https:\u002F\u002Fgithub.com\u002FiDorgham\u002FWorkspace-Factory\u002Fblob\u002Fmaster\u002Ffactory\u002Flibrary\u002Fskills\u002Fofficial_sanity_io_portable_text_serialization\u002Fskill.md",[206],{"categoryNo":87,"categoryName":88,"taxonomyType":89,"taxonomyTypeDesc":90},[208,209,210,211,212,102,213,170,214,105,215,216,106,92,217,218,219,220,221,222],"text","portable text serialization","portable","serialization","extracting","strings","issues","frontend","svelte","sanity","astro","server","markdown","rendering","vue","2026-11-10 10:56:23"]