gmx distance Tutorial: Ligand-to-Pocket Distance in GROMACS

gmx distance measures the distance between pairs of positions in every frame of a GROMACS trajectory. Give it a selection such as com of resname LIG plus com of group "Pocket" and it writes the ligand-to-pocket centre-of-mass distance over time with -oall, plus averages, x/y/z components, a histogram and per-pair statistics through four more output flags.
If your thesis is a protein-ligand MD study, a reviewer will ask one question before any other: did the ligand stay in the pocket? RMSD answers part of it, but the plot that answers it directly is the distance between the ligand and the binding site over time. This guide from the StemSkills Lab team (10+ years in structural bioinformatics, drug design and molecular modeling) shows how to build that plot with gmx distance, how to add a key donor-acceptor pair and a domain-domain distance in the same run, and what to do when the tool refuses your selection. It sits in our GROMACS molecular dynamics learning path, after production MD and basic analysis.
All option names and defaults below are taken from the official gmx distance reference page of the GROMACS 2026.4 manual. The tool has used the same selection-based interface since GROMACS 5.0, so the commands work on any recent version.
What does gmx distance actually calculate?
The manual describes it in one line: gmx distance “calculates distances between pairs of positions as a function of time.” The key word is pairs. Each selection you pass with -select must produce an even number of positions, and the tool pairs them in order: position 1 with 2, 3 with 4, and so on. A position can be a single atom, a centre of mass (com of), a centre of geometry (cog of) or a residue centre (res_com of).
That design is what makes it the right tool for three thesis plots:
- Ligand to pocket: the centre of mass of the ligand paired with the centre of mass of the binding-site residues. One number per frame that tells you whether the ligand stayed, drifted or left.
- A key atom pair: for example a ligand carbonyl oxygen and a histidine NE2 nitrogen, to show that one hydrogen bond or salt bridge seen in docking survives in MD.
- Domain to domain: the centres of mass of two protein domains, to show opening or closing of a cleft.
Distances are in nanometres. 0.35 nm is 3.5 Å, a number you will see again below.
What do I need before running gmx distance?
You need three files from a finished run: the run input file (md.tpr), a trajectory (md.xtc), and usually an index file with your pocket group. Before measuring anything, make the trajectory whole and centred so the ligand is not split across the box edge:
gmx trjconv -s md.tpr -f md.xtc -o md_center.xtc -pbc mol -centerChoose the protein for centring and the whole system for output. Our gmx trjconv tutorial covers the choices in detail. Then build a pocket group. The simplest reliable method is to list the residues within about 5 Å of the ligand in your starting (docked) pose, which you can read from PyMOL or from a LigPlot+ or PLIP interaction diagram, and write them into an index group:
gmx make_ndx -f md.tpr -o index.ndx
> r 41 49 140 141 142 145 163 166
> name 20 Pocket
> qThe residue numbers are an example; use your own. The new group number (20 here) depends on your system, so read it from the screen before naming it. If you have not used make_ndx before, our make_ndx index groups tutorial walks through it. A fixed residue list is better than a distance-based dynamic selection, because the pocket definition should not change while you measure the ligand against it.
How do I measure the ligand-to-pocket distance with gmx distance?
Replace LIG with your ligand’s residue name from the topology (check your .gro file; parameterisation tools name it differently):
gmx distance -s md.tpr -f md_center.xtc -n index.ndx \
-select 'com of resname LIG plus com of group "Pocket"' \
-oall lig_pocket.xvg -oav lig_pocket_avg.xvg -tu nsThree details matter here:
plusjoins two position expressions into one selection, so the tool sees exactly two positions and measures one distance. The selection page of the manual givescom of group 1 plus com of group 2as its own example of this use.- Quoting: wrap the whole selection in single quotes and the group name in double quotes. The shell then passes it unchanged.
-tu nswrites the time axis in nanoseconds instead of the default picoseconds, which is what you want on a thesis figure.
How to read the result: a ligand that stays bound gives a flat line with small fluctuations, close to the value in frame 0. A steady upward drift means the ligand is sliding within or out of the site. A sudden jump to several nanometres and no return means it left the pocket. Report the mean and standard deviation over the equilibrated part of the run, and show the plot for every replicate (our guide to replicate MD simulations explains why one run is not enough).
Want the guided, hands-on version?
Our live Molecular Modeling & MD Simulations cohort bootcamp takes you from zero to running real docking and MD workflows, with a portfolio project for your grad-school applications.
How do I track a single atom pair, like a hydrogen bond or salt bridge?
Select the two atoms by residue and atom name and join them with plus. Use parentheses so each side is evaluated as one expression:
gmx distance -s md.tpr -f md_center.xtc \
-select '(resname LIG and name O1) plus (resnr 145 and name NE2)' \
-oall hbond_pair.xvg -tu nsTake atom names from your own .gro or .itp file, not from the PDB entry, because ligand parameterisation tools often rename atoms. If your system has more than one protein chain, add chain A or restrict with group "Protein", since resnr 145 otherwise matches residue 145 in every chain and gives you more than two positions.
How to judge the plot: 0.35 nm is the default donor-acceptor distance cutoff in gmx hbond (together with a 30° angle cutoff), so time spent below that line is time the hydrogen bond can exist. For ion pairs, the classic survey of protein salt bridges by Barlow and Thornton (Journal of Molecular Biology, 1983) used a 4.0 Å (0.4 nm) cutoff between charged groups, which is still the usual threshold. A distance plot shows how often and when a contact breaks, which a single occupancy percentage hides. For the full occupancy analysis, see our posts on protein-ligand hydrogen bonds with gmx hbond and salt bridge analysis in GROMACS.
How do I measure a domain-to-domain distance?
Use residue ranges inside com of. For a two-domain protein where residues 1 to 120 form domain 1 and 121 to 250 form domain 2:
gmx distance -s md.tpr -f md_center.xtc \
-select 'com of (group "Protein" and resnr 1 to 120) plus com of (group "Protein" and resnr 121 to 250)' \
-oall domains.xvg -tu nsTake domain boundaries from the literature on your protein or from its UniProt or CATH annotation, and state them in your methods. An increase in this distance relative to the apo run, or relative to a wild-type control, is direct evidence of a cleft opening.
Can I calculate several distances in one gmx distance run?
Yes, in two ways. First, -select accepts several selections, and each becomes its own data set:
gmx distance -s md.tpr -f md_center.xtc -n index.ndx \
-select 'com of resname LIG plus com of group "Pocket"' \
'(resname LIG and name O1) plus (resnr 145 and name NE2)' \
-oall combined.xvg -oallstat combined_stats.xvg -tu nsSecond, one selection can hold many pairs. The manual’s example name "C[1-8]" merge name "C[2-9]" interleaves two atom lists to give the pairs C1-C2, C2-C3 and so on up to C8-C9. Use merge when you want consecutive pairs and plus when you want to stitch two different expressions together. If you need a long list of fixed pairs, write the selections into a text file and pass it with -sf.
What are the five gmx distance output files, and which one should I plot?
Every output is an .xvg file and every one is optional.
| Flag | Default file | What it contains | When to use it |
|---|---|---|---|
-oall | dist.xvg | Every individual distance against time | The main thesis figure: one line per pair |
-oav | distave.xvg | Average distance in each selection, against time | Many pairs in one selection that you want summarised as one curve |
-oxyz | distxyz.xvg | x, y and z components instead of the length | Membrane systems, where movement along z (the bilayer normal) is the real question |
-oh | disthist.xvg | Histogram of distances, shaped by -len, -tol and -binw | Showing that a distance has two states (bound and partly unbound) |
-oallstat | diststat.xvg | Mean and standard deviation of each distance over frames | The numbers you quote in a results table |
For the histogram, -len (default 0.1 nm) sets the mean distance the histogram is built around, -tol (default 1) sets the width of the full distribution as a fraction of -len, and -binw (default 0.001 nm) sets the bin width. The defaults suit bond-length distances, not a ligand-to-pocket distance of half a nanometre or more, so set -len close to your observed mean and use a wider bin such as -binw 0.01. To restrict any output to the equilibrated part of the run, add -b and -e (in the unit set by -tu).
To plot in Python, NumPy can skip the xvg header lines directly:
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt("lig_pocket.xvg", comments=("#", "@"))
plt.plot(data[:, 0], data[:, 1])
plt.xlabel("Time (ns)"); plt.ylabel("Ligand-pocket COM distance (nm)")
plt.savefig("lig_pocket.png", dpi=300)Our guide on plotting GROMACS xvg files in Python adds running averages and multi-replicate panels.
How does gmx distance handle periodic boundary conditions?
Two default settings do most of the work. -rmpbc (on by default) makes molecules whole in each frame, using the topology in the .tpr. -pbc (also on by default) computes each distance with the minimum-image convention, so a ligand on the far side of the box edge from the pocket is still measured the short way.
Two cases still need care. A centre of mass of atoms that sit across the box boundary can land in empty space between them; the selection syntax lets you add pbc after the expression (com of resname LIG pbc) so the centre is computed iteratively with periodic wrapping. And a minimum-image distance cannot exceed half the box length, so a fully dissociated ligand in a small box will plateau instead of rising. Centring the trajectory first with trjconv -pbc mol -center, as above, removes most of these problems, and it also makes the trajectory easier to check by eye in VMD. If you suspect the protein is seeing its own periodic image, that is a different test: see our gmx mindist -pi guide.
When should I use gmx pairdist or gmx mindist instead?
gmx distance measures fixed pairs. The manual itself points you to gmx pairdist when you want the minimum or maximum distance between two selections. The three tools answer different questions:
| Tool | Question it answers | Key options | Typical thesis use |
|---|---|---|---|
gmx distance | How far apart are these specific pairs of positions? | -select, -oall, -oallstat | Ligand COM to pocket COM, one H-bond pair, domain COMs |
gmx pairdist | What is the closest (or farthest) approach between two selections? | -ref, -sel, -type min|max, -refgrouping, -selgrouping, -cutoff | Closest ligand atom to the protein; minimum distance to each residue |
gmx mindist | What is the minimum distance between groups, and how many contacts fall within a cutoff? | -od, -on, -d (default 0.6 nm), -group, -pi | Contact counts over time; periodic-image check |
A short gmx pairdist example, for the closest approach of any ligand atom to the protein:
gmx pairdist -s md.tpr -f md_center.xtc \
-ref 'resname LIG' -sel 'group "Protein"' -type min -o lig_prot_min.xvg -tu nsAdd -selgrouping res to get one minimum-distance column per residue instead of a single global value. A good results section uses both views: the COM distance from gmx distance shows the ligand stayed in the site, and the minimum distance from gmx pairdist shows it kept touching the protein.
Why does gmx distance reject my selection, and how do I fix it?
- Odd number of positions. The tool stops because it cannot pair an odd count. Usual cause:
resname LIG plus com of group "Pocket"withoutcom ofon the ligand side gives one position per ligand atom plus one. Fix: putcom of(orcog of) on every multi-atom side. - Residue matches in several chains.
resnr 145 and name NE2returns two atoms in a dimer, giving three positions with the ligand atom. Fix: addand chain A, or select from an index group of one chain. - Group not found.
group "Pocket"fails when you forget-n index.ndxor misspell the group name. Fix: add-nand copy the name exactly frommake_ndx. - Shell eats the quotes. Double quotes around the whole selection conflict with the double quotes around a group name. Fix: single quotes outside, double quotes inside.
- Atom name matches nothing. The PDB says
O1but your parameterised ligand says something else. Fix: grep your.grofile for the ligand residue name and copy the atom names. - Regex surprise. A quoted name with characters other than letters, digits,
*or?, such as"C[1-8]", is read as a regular expression. That is useful on purpose and confusing by accident. - Jumps of several nanometres in one frame. Usually a centre of mass computed across a box boundary. Fix: centre the trajectory with
trjconv -pbc mol -center, or addpbcto thecom ofexpression.
For errors outside the analysis tools, keep our list of common GROMACS errors and fixes open. For your methods section, the standard citation for GROMACS is the reference paper by Abraham et al., SoftwareX 1-2:19-25 (2015).
Frequently asked questions
What units does gmx distance use?
Distances are in nanometres and time is in picoseconds by default. Add -tu ns to write time in nanoseconds. Multiply distances by 10 to report them in ångströms.
Is the ligand-to-pocket COM distance the same as ligand RMSD?
No. Ligand RMSD measures how far the ligand’s atoms moved from a reference pose after fitting, so it also captures flipping and rotation. The COM distance only measures position relative to the site. Report both; our ligand RMSD guide covers the fitting choices.
Do I need an index file for gmx distance?
Not always. Selections such as resname LIG and resnr 1 to 120 work directly from the .tpr. You need -n index.ndx only when the selection refers to a custom group such as group "Pocket".
What is a normal ligand-to-pocket distance?
There is no universal value, because it depends on where the ligand sits relative to the centre of the residues you chose. Judge stability by change over time against the frame-0 value and against replicates, not against a fixed number.
Can gmx distance measure distances to a fixed point in space?
Yes. A constant position is written as [x, y, z] in nanometres, so com of resname LIG plus [3.0, 3.0, 3.0] tracks the ligand against a fixed point. On a centred trajectory this is rarely more useful than the pocket COM.
Once these three distance plots are in your results, the next skills in the sequence are interaction energies and binding free energy. See where they sit on the computational biology skills roadmap, or go back to the GROMACS learning path for the full analysis set.
Want the guided, hands-on version?
Our live Molecular Modeling & MD Simulations cohort bootcamp takes you from zero to running real docking and MD workflows, with a portfolio project for your grad-school applications.
