Showing posts with label Molecular Dynamics. Show all posts
Showing posts with label Molecular Dynamics. Show all posts

Monday, November 30, 2026

Molecular Dynamics for Beginners: What It Is and a First GROMACS Run

 

In the last two posts, we learned what docking is and ran it with AutoDock Vina. Docking gives you a snapshot: one frozen picture of how a molecule might sit in a protein.

But real proteins are never frozen. They wiggle, bend, breathe and interact with water all the time. To see that motion, scientists use molecular dynamics (MD).

In this guide, you'll learn what MD is in simple words, and then run your first simulation with GROMACS, one of the most widely used MD programs. 

No prior MD experience is needed, but basic Linux commands will help.

By the end, you'll know:

  • what molecular dynamics is and why it's useful
  • the key ideas behind it (force fields, time steps, trajectories)
  • how to install GROMACS
  • how to run a full simulation of a protein in water, step by step
  • how to check that your simulation is healthy
  • how to analyze the results (RMSD, radius of gyration)
  • the limits of MD and the mistakes to avoid
  • how to keep learning

Part 1: The Basics

What is molecular dynamics?

Molecular dynamics is a computer method that simulates how atoms and molecules move over time.

You give the computer:

  1. the starting positions of all the atoms (for example, a protein in water)
  2. rules for how atoms push and pull on each other (called a force field)

The computer then calculates the forces on every atom, moves the atoms a tiny step forward in time, and repeats this millions of times. The result is a trajectory: a movie of your molecules in motion.

Photo vs movie

MethodLike a...What you get
DockingPhotoA single predicted pose, mostly static
Molecular dynamicsMovieHow the system moves and changes over time

Docking asks, "Where might this molecule bind?" MD asks, "Does it stay there, and how does everything move around it?"

Why does MD matter?

A static structure from the PDB hides a lot:

  • Proteins are flexible and change shape
  • Water molecules and ions play important roles
  • A docked ligand might be unstable and drift out of the pocket
  • Some binding sites only appear when the protein moves

MD helps you see these things.

Where is MD used?

  • Checking docked poses: does the ligand stay in the pocket, or leave?
  • Protein stability and folding studies
  • Effect of mutations: how does a change in one amino acid alter motion?
  • Understanding how proteins work: enzymes, channels, receptors
  • Drug discovery: studying binding and unbinding
  • Membrane protein research: simulating proteins inside lipid membranes
  • Protein-protein and protein-DNA interactions

Part 2: How MD Works (Simple Version)

You don't need to be a physicist. Here are the core ideas.

1. Newton's laws, for atoms

If you know the force on an atom, you can work out how it will accelerate and move. MD does this for every atom, again and again.

2. The force field

A force field is a set of rules and numbers that describes the forces between atoms. It covers:

  • Bonds: atoms connected by springs
  • Angles: how bonds bend
  • Dihedrals: how groups twist
  • Non-bonded forces: electrostatics (charges) and van der Waals (atoms attracting and repelling)

Popular force fields for proteins include AMBER, CHARMM, OPLS-AA and GROMOS. Each has its own strengths, and which you use should match your system and published practice.

3. The time step

Each step moves the atoms forward by a very small time, usually 2 femtoseconds (fs), which is 0.000000000000002 seconds. To simulate even 1 nanosecond, you need about 500,000 steps.

4. The trajectory

At regular intervals, the program saves the positions of all atoms. Together, these snapshots form the trajectory, which you can watch in a viewer and analyze with numbers.

5. Water and the box

Proteins live in water, so we put the protein in a box of water molecules (this is called explicit solvent). To avoid edge effects, MD uses periodic boundary conditions (PBC): the box is treated as if it repeats infinitely in all directions, so a molecule leaving one side re-enters from the opposite side.

6. Temperature and pressure control

Real cells have a constant temperature and pressure, so MD uses algorithms called thermostats and barostats to keep these steady. The standard process is:

  • NVT (constant Number of particles, Volume, Temperature): the system warms up to the target temperature
  • NPT (constant Number of particles, Pressure, Temperature): the system adjusts its density to the target pressure

Key terms (mini dictionary)

TermSimple meaning
Force fieldThe rulebook for forces between atoms
TopologyA file describing atoms, bonds and parameters of your system
Time stepHow far in time each simulation step moves (about 2 fs)
TrajectoryThe saved "movie" of atom positions over time
Energy minimizationRelaxing the structure to remove bad contacts before the run
EquilibrationLetting temperature and pressure settle before the real run
Production runThe main simulation you analyze
PBCPeriodic boundary conditions (the box repeats in space)
RMSDHow much the structure has changed from a reference
RMSFHow much each residue moves (flexibility)
RgRadius of gyration (how compact the protein is)

Part 3: The Typical MD Workflow

Every MD project follows a similar path:

1. Get structure (PDB)
        ↓
2. Clean the structure
        ↓
3. Choose force field → generate topology
        ↓
4. Put protein in a box
        ↓
5. Add water (solvate)
        ↓
6. Add ions (neutralize the system)
        ↓
7. Energy minimization
        ↓
8. Equilibration (NVT, then NPT)
        ↓
9. Production run
        ↓
10. Analysis

We'll do each of these in the hands-on part.


Part 4: Before You Start

What you need

  • Linux, macOS or Windows with WSL
  • A computer with a few CPU cores and at least 8 GB of RAM (more is better). A GPU speeds things up but isn't required for this tutorial.
  • GROMACS
  • A molecule viewer (VMD, PyMOL or ChimeraX)
  • A plotting tool (Python with matplotlib, or Grace/xmgrace)

What to know first

  • Basic Linux commands
  • What a protein structure and a PDB file are
  • A little biochemistry (amino acids, charge, water)

Install GROMACS

Create an environment and install from conda-forge:

bash
mamba create -n md -c conda-forge gromacs python=3.11 matplotlib numpy
conda activate md
gmx --version

If you prefer, you can install GROMACS through your system's package manager (for example, sudo apt install gromacs on Ubuntu) or compile it from source. The official GROMACS installation guide has instructions for each option, and versions change over time, so check it if something differs from what you see here.

All GROMACS tools run through one command called gmx, followed by a tool name. To see help for any tool, use gmx help <tool>, for example gmx help editconf.


Part 5: Your First Simulation (Hands-On)

We'll simulate hen egg-white lysozyme (PDB ID 1AKI), a small, stable, well-studied protein. This follows the classic "Lysozyme in Water" tutorial by Justin Lemkul, which is the standard starting point for GROMACS beginners and is the basis for several other tutorials, including a BioExcel Building Blocks workflow. Once you've finished this post, the original tutorial is the best place to go deeper. irbbarcelona

Step 1: Make a project folder and get the structure

bash
mkdir lysozyme_md
cd lysozyme_md
wget https://files.rcsb.org/download/1AKI.pdb

If wget isn't available, download 1AKI.pdb from the RCSB PDB website and place it in this folder.

Take a quick look at the file in a viewer to see what the protein looks like.

Step 2: Clean the structure

Crystal structures include crystal water (HOH). For this simple run, we remove it, because the simulation will add its own water:

bash
grep -v HOH 1AKI.pdb > 1AKI_clean.pdb

Always check your own structures for other things to handle: missing residues, alternate locations, ligands, ions and non-standard residues. 1AKI is simple, which is why it's a good first example.

Step 3: Create the topology (choose a force field)

bash
gmx pdb2gmx -f 1AKI_clean.pdb -o 1AKI_processed.gro -water spce -ff oplsaa

What this does:

  • pdb2gmx reads your protein and builds the topology (topol.top), which describes all atoms, bonds and parameters
  • -ff oplsaa selects the OPLS-AA force field, as used in the tutorial
  • -water spce chooses the SPC/E water model
  • -o writes the processed structure in GROMACS format (.gro)

It also adds hydrogen atoms and writes a position-restraint file (posre.itp), which we'll use in equilibration.

Without the -ff option, GROMACS shows an interactive menu of force fields. Pick the one by name, since menu numbers can differ between versions.

Step 4: Define the simulation box

bash
gmx editconf -f 1AKI_processed.gro -o 1AKI_newbox.gro -c -d 1.0 -bt cubic
  • -bt cubic makes a cubic box
  • -c centers the protein in the box
  • -d 1.0 keeps the protein at least 1.0 nm from every box edge

Why the distance matters: because of PBC, the protein would otherwise "see" its own copy in the neighboring box. A gap of 1.0 nm or more prevents that.

Step 4b: Fill the box with water

bash
gmx solvate -cp 1AKI_newbox.gro -cs spc216.gro -o 1AKI_solv.gro -p topol.top
  • -cp is the protein in the box
  • -cs spc216.gro is a pre-made water box that GROMACS uses as a template (it works for SPC, SPC/E and similar 3-point water models)
  • -p topol.top updates your topology with the number of water molecules added

You'll see that thousands of water molecules were added, so your system now has tens of thousands of atoms.

Step 5: Add ions to neutralize the system

A system with a net electric charge behaves badly under the electrostatic methods MD uses. Lysozyme carries a net charge at neutral pH, so we add counter-ions.

First, you need a small parameter file called ions.mdp. Create it:

bash
cat > ions.mdp << 'EOF'
integrator  = steep
emtol       = 1000.0
emstep      = 0.01
nsteps      = 50000
nstlist     = 1
cutoff-scheme = Verlet
ns_type     = grid
coulombtype = cutoff
rcoulomb    = 1.0
rvdw        = 1.0
pbc         = xyz
EOF

Then run:

bash
gmx grompp -f ions.mdp -c 1AKI_solv.gro -p topol.top -o ions.tpr
gmx genion -s ions.tpr -o 1AKI_solv_ions.gro -p topol.top -pname NA -nname CL -neutral
  • grompp is the pre-processor: it combines the parameters (.mdp), structure (.gro) and topology (.top) into one run-input file (.tpr)
  • genion replaces some water molecules with ions. -neutral adds just enough to make the total charge zero.

When genion asks which group to replace, choose SOL (the solvent). Type SOL and press Enter.

Step 6: Energy minimization

Even a good crystal structure has small steric clashes after adding hydrogens and water. Energy minimization relaxes the system to a stable starting point.

Create minim.mdp:

bash
cat > minim.mdp << 'EOF'
integrator  = steep
emtol       = 1000.0
emstep      = 0.01
nsteps      = 50000
nstlist     = 1
cutoff-scheme = Verlet
ns_type     = grid
coulombtype = PME
rcoulomb    = 1.0
rvdw        = 1.0
pbc         = xyz
EOF

Run it:

bash
gmx grompp -f minim.mdp -c 1AKI_solv_ions.gro -p topol.top -o em.tpr
gmx mdrun -v -deffnm em
  • -deffnm em names all output files em.*
  • -v prints progress

When it finishes, you should see that it converged (the maximum force dropped below the tolerance, 1000 kJ/mol/nm). Now check the energy:

bash
gmx energy -f em.edr -o potential.xvg

When prompted, select Potential (type its number or name, then press Enter, then 0 to finish).

Plot it. The potential energy should drop steeply and then level off at a large negative value. If it's not decreasing or ends up positive, something is wrong with your setup.

Step 7: Equilibration, part 1 (NVT: temperature)

Now we warm the system to 300 K while holding the protein in place with position restraints, so the water can settle around it.

Create nvt.mdp:

bash
cat > nvt.mdp << 'EOF'
title       = Lysozyme NVT equilibration
define      = -DPOSRES
integrator  = md
nsteps      = 50000
dt          = 0.002
nstxout     = 500
nstvout     = 500
nstenergy   = 500
nstlog      = 500
continuation = no
constraint_algorithm = lincs
constraints = h-bonds
lincs_iter  = 1
lincs_order = 4
cutoff-scheme = Verlet
ns_type     = grid
nstlist     = 10
rcoulomb    = 1.0
rvdw        = 1.0
coulombtype = PME
pme_order   = 4
fourierspacing = 0.16
tcoupl      = V-rescale
tc-grps     = Protein Non-Protein
tau_t       = 0.1 0.1
ref_t       = 300 300
pcoupl      = no
pbc         = xyz
DispCorr    = EnerPres
gen_vel     = yes
gen_temp    = 300
gen_seed    = -1
EOF

Key settings:

  • define = -DPOSRES turns on the position restraints
  • dt = 0.002 is a 2 fs time step, and nsteps = 50000 makes this a 100 ps run
  • constraints = h-bonds fixes bonds to hydrogens, which allows the 2 fs time step
  • tcoupl = V-rescale is the thermostat, and ref_t = 300 300 sets the target temperature
  • gen_vel = yes assigns starting velocities for 300 K
  • coulombtype = PME handles long-range electrostatics

Run:

bash
gmx grompp -f nvt.mdp -c em.gro -r em.gro -p topol.top -o nvt.tpr
gmx mdrun -deffnm nvt

This takes from several minutes to a couple of hours, depending on your hardware. Then check the temperature:

bash
gmx energy -f nvt.edr -o temperature.xvg

Select Temperature, then 0. The temperature should rise quickly to about 300 K and stay there, fluctuating around it.

Step 8: Equilibration, part 2 (NPT: pressure and density)

Next we let the box adjust to 1 bar of pressure. Create npt.mdp by copying nvt.mdp and changing these lines:

bash
cp nvt.mdp npt.mdp

Edit npt.mdp:

  • Change the title to Lysozyme NPT equilibration
  • Set continuation = yes (we're continuing from NVT)
  • Set gen_vel = no (we keep the velocities from NVT)
  • Remove the three lines gen_vel, gen_temp and gen_seed if present, and add the pressure-coupling block:
pcoupl           = Parrinello-Rahman
pcoupltype       = isotropic
tau_p            = 2.0
ref_p            = 1.0
compressibility  = 4.5e-5
refcoord_scaling = com

(refcoord_scaling = com is needed because the box size is now allowed to change while position restraints are active.)

Run:

bash
gmx grompp -f npt.mdp -c nvt.gro -t nvt.cpt -r nvt.gro -p topol.top -o npt.tpr
gmx mdrun -deffnm npt

The -t nvt.cpt option passes along the checkpoint, so velocities carry over exactly. Check pressure and density:

bash
gmx energy -f npt.edr -o pressure.xvg
gmx energy -f npt.edr -o density.xvg

For pressure, select Pressure; for density, select Density (then 0 each time).

What to expect:

  • Pressure: fluctuates a lot, often by hundreds of bar, around the target of 1 bar. That's normal for a small system, so look at the average and don't worry about the noise.
  • Density: should settle near the density of water, around 1000 kg/m³.

Step 9: Production run

Now we release the restraints and let the protein move freely. Create md.mdp from npt.mdp:

bash
cp npt.mdp md.mdp

Edit md.mdp:

  • Remove the line define = -DPOSRES
  • Change the title to Lysozyme production MD
  • Set nsteps (we'll use 50000 for a quick 100 ps first run; 500000 would be 1 ns)
  • Set how often to save the trajectory by adding:
nstxout-compressed = 5000
compressed-x-grps  = System

Note: nstxout-compressed = 5000 saves a frame every 10 ps with a 2 fs step.

Run:

bash
gmx grompp -f md.mdp -c npt.gro -t npt.cpt -p topol.top -o md_0_1.tpr
gmx mdrun -deffnm md_0_1

For a first run, 100 ps is perfect for learning the workflow. Real scientific conclusions need much longer simulations (typically hundreds of nanoseconds or more) and repeats, but you don't need that to learn the process.

If you have a GPU and your GROMACS build supports it, mdrun will usually detect and use it automatically.


Part 6: Analyzing Your Trajectory

Step 10: Fix the periodic boundary effects

Because of PBC, the protein may appear to jump across the box or be split in the saved trajectory. Fix it first:

bash
gmx trjconv -s md_0_1.tpr -f md_0_1.xtc -o md_0_1_center.xtc -center -pbc mol -ur compact

When asked:

  • For the group to center, choose Protein
  • For the group to output, choose System

Step 11: Watch the movie

Open the trajectory in VMD, PyMOL or ChimeraX. For example, in VMD:

bash
vmd md_0_1.gro md_0_1_center.xtc

(If you only have md_0_1.tpr, you can write a .gro structure file with gmx trjconv -s md_0_1.tpr -f md_0_1_center.xtc -o first_frame.gro -dump 0.) Watching the trajectory teaches you a lot. Does the protein stay folded? Does it look reasonable?

Step 12: RMSD (is the structure stable?)

RMSD measures how far the protein has moved from its starting structure.

bash
gmx rms -s md_0_1.tpr -f md_0_1_center.xtc -o rmsd.xvg -tu ns

Select Backbone for both the fit and the calculation.

How to read it:

  • RMSD rises at first, then levels off (plateaus): the structure has settled and looks stable
  • RMSD keeps rising steadily: the protein is still changing, or possibly unfolding, or your run is too short
  • For a stable folded protein, RMSD typically plateaus at roughly 0.1 to 0.3 nm, but the right value depends on the system

Step 13: Radius of gyration (is it compact?)

bash
gmx gyrate -s md_0_1.tpr -f md_0_1_center.xtc -o gyrate.xvg

Select Protein. A fairly flat Rg means the protein stays compact. A steady increase suggests unfolding.

Step 14: RMSF (which parts move most?)

bash
gmx rmsf -s md_0_1.tpr -f md_0_1_center.xtc -o rmsf.xvg -res

Select C-alpha. High peaks mark flexible regions (often loops and termini). Low values mark rigid regions.

Plot the results with Python

GROMACS writes .xvg files. This short script plots any of them:

python
import numpy as np
import matplotlib.pyplot as plt

def read_xvg(path):
    x, y = [], []
    with open(path) as f:
        for line in f:
            if line.startswith(("#", "@")):
                continue
            parts = line.split()
            x.append(float(parts[0]))
            y.append(float(parts[1]))
    return np.array(x), np.array(y)

x, y = read_xvg("rmsd.xvg")
plt.plot(x, y)
plt.xlabel("Time (ns)")
plt.ylabel("RMSD (nm)")
plt.title("Lysozyme backbone RMSD")
plt.savefig("rmsd.png", dpi=300, bbox_inches="tight")
plt.show()

Change the file name and labels for the other plots.


Part 7: Is My Simulation Healthy? (A Quick Checklist)

CheckWhat good looks like
Energy minimizationConverged, potential energy large and negative
TemperatureStable around 300 K
PressureFluctuates around 1 bar (large noise is normal)
DensityClose to that of water (about 1000 kg/m³)
RMSDLevels off, no steady drift
RgFairly stable
Visual checkProtein intact, no strange stretching or breaking
grompp warningsRead every warning and understand it before moving on

If something is off, go back to the step before it. Problems in equilibration usually start earlier in preparation.


Part 8: What MD Can and Can't Do

What MD is good at

  • Showing how a system moves, not just how it looks
  • Checking whether a structure or docked pose is stable
  • Revealing flexible regions and conformational changes
  • Providing detailed, atom-level views of interactions over time
  • Generating hypotheses about mechanism

What MD is NOT good at (yet)

  • Long timescales. Most routine simulations cover nanoseconds to microseconds, while many biological events (folding, large conformational changes) are slower.
  • Perfect accuracy. Force fields are approximations, and results depend on which one you use.
  • Sampling everything. One trajectory shows only a small part of what's possible, so serious studies use multiple replicates.
  • Chemical reactions. Standard MD doesn't break or form bonds.
  • Being a replacement for experiments. Results are predictions that need support from experimental data.

A healthy way to think about it

MD shows you what is possible and plausible under a given model. It doesn't automatically show what is true in a cell.

When you report MD results, state the force field, water model, simulation length, number of replicates and software version, and be honest about limits.


Part 9: Common Beginner Mistakes

  1. Skipping equilibration. Jumping straight to production can give unstable or meaningless results.
  2. Not neutralizing the system. A net charge causes problems with long-range electrostatics.
  3. A box that's too small. The protein interacts with its own periodic image.
  4. Ignoring grompp warnings. They often point to real problems.
  5. Trusting one short run. A 100 ps simulation is for learning, not for conclusions.
  6. Analyzing without fixing PBC. RMSD and visualization can look wrong if the molecule is split across the box.
  7. Choosing the wrong force field for the system. Match the force field to your molecule type (protein, lipid, DNA, ligand).
  8. Using unprepared structures. Missing atoms, wrong protonation or unusual residues cause errors.
  9. Misreading pressure. Large fluctuations are normal. Focus on the average.
  10. Not recording settings. Always save your .mdp files, versions and commands.

Part 10: Reproducibility Tips

Keep your project organized so anyone (including future you) can repeat it:

lysozyme_md/
├── README.md          # what you did, versions, results, limitations
├── data/
│   └── 1AKI.pdb
├── mdp/
│   ├── ions.mdp
│   ├── minim.mdp
│   ├── nvt.mdp
│   ├── npt.mdp
│   └── md.mdp
├── run_all.sh         # all commands, in order
├── results/
│   ├── rmsd.png
│   ├── gyrate.png
│   └── rmsf.png
└── analysis/
    └── plot_xvg.py

In your README, record the GROMACS version, force field, water model, box type and size, temperature and pressure, run lengths and the analysis results. This also sets you up for the Docker post, where we'll package this whole setup so it runs the same on any machine.


Part 11: How MD Connects to Docking

You can now see how the two topics fit together:

  1. Dock a ligand into a protein to get a predicted pose
  2. Run MD on the protein-ligand complex to test whether the pose stays stable
  3. Analyze interactions and ligand movement over time

One extra challenge: ligands need their own force-field parameters, which standard protein setups don't provide. Tools like CHARMM-GUI, ACPYPE (for GAFF parameters) or the CGenFF server help with this. It's a good next topic once you're comfortable with a protein-only simulation.


Part 12: Your Learning Roadmap

Week 1: Understand the concepts. Force fields, time steps, trajectories, PBC, NVT and NPT.

Week 2: Run the lysozyme tutorial from this post, start to finish. Don't skip the equilibration checks.

Week 3: Analyze properly. Practice RMSD, RMSF, Rg, hydrogen bonds. Write a short interpretation of what you see.

Week 4: Repeat with a different protein. Pick a small, well-studied protein from the PDB and change as little as possible.

Week 5 and beyond:

  • Run longer simulations on a cluster or GPU
  • Run multiple replicates
  • Learn to set up protein-ligand systems
  • Automate the workflow with a script or a workflow manager (Snakemake or Nextflow)
  • Read the official GROMACS documentation and the Lemkul tutorials for more advanced topics

A good first portfolio project

  1. Simulate a small protein in water with GROMACS
  2. Run NVT and NPT equilibration with proper checks
  3. Run a production simulation (as long as you can manage)
  4. Analyze RMSD, RMSF and Rg, and make clear plots
  5. Write a README explaining the method, results and limitations
  6. Upload everything to GitHub

Quick Recap

  • MD simulates how atoms move over time, giving you a movie instead of a photo.
  • It uses a force field to calculate forces, and tiny time steps (about 2 fs) to move atoms forward.
  • The workflow: clean structure → topology → box → solvate → add ions → minimize → equilibrate (NVT, NPT) → production → analysis.
  • Always check energy, temperature, pressure and density before trusting the run.
  • Analyze with RMSD, RMSF and Rg, and look at the trajectory visually.
  • MD results are model-based predictions. Use longer runs and replicates for real conclusions.

Final Thoughts

Your first MD simulation can feel like a lot: new file types, many commands and a pile of new vocabulary. But the workflow is the same every time, and once you've seen one run from start to finish, the rest is practice.

Don't aim for perfect on the first attempt. Run the tutorial, break something on purpose, fix it, and look at your protein moving. That's when MD stops feeling abstract.

If you get stuck on any step, drop your error message in the comments and I'll help. And tell me: would you like to see how to simulate a protein-ligand complex from a docking result next?

In the next post, we'll look at DNA and protein language models (DNABERT, ESM, Enformer): what they actually do.

Editor’s Picks and Reader Favorites

The 2026 Bioinformatics Roadmap: How to Build the Right Skills From Day One

  If the universe flipped a switch and I woke up at level-zero in bioinformatics — no skills, no projects, no confidence — I wouldn’t touch ...