Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

23. Molecular simulation: pressure and diffusion in a Lennard-Jones liquid

School of Engineering, Nazarbayev University

Track: advanced example  ·  Uses: Chapters 4 and 17

Reading: Allen & Tildesley, Computer Simulation of Liquids · Frenkel & Smit, Understanding Molecular Simulation · Yeh & Hummer (2004)

A molecular dynamics (MD) simulation is a measurement performed on a model. Its “readings” are a time series, its random error comes from the finite length of the run, and its systematic errors come from the finite system, the finite time step and the details of the model. All the ideas of this repository apply, with one complication that dominates everything else: the readings are strongly correlated in time.

This example analyses a real (if small) MD run and shows how to

  • check a time series before averaging it;

  • obtain correct error bars for the temperature, energy and pressure by block averaging and from the autocorrelation time;

  • test the error bars for internal consistency;

  • estimate a transport coefficient and its uncertainty from independent blocks;

  • list what the statistical error bar does not include.

The simulation

The data were produced by scripts/run_lj_md.py, a self-contained NumPy implementation (about 100 lines) that runs in one to two minutes:

  • 256 particles, truncated-and-shifted Lennard-Jones potential, cutoff 2.5 σ2.5\,\sigma, cubic periodic box, reduced density ρ=0.8\rho = 0.8;

  • velocity-Verlet integration, time step Δt=0.005\Delta t = 0.005;

  • equilibration with velocity rescaling to T=1.0T = 1.0, then 2000 steps discarded, then a production run of 40 000 steps (200 time units) at constant energy (NVE), with the potential energy, temperature and pressure saved at every step.

All quantities are in reduced Lennard-Jones units.

40000 samples, 200 time units, N = 256, box length 6.840

Step 1. Look before averaging

Two checks come before any statistics.

Is the series stationary? The mean of the first and second halves of the run should agree (we return to this quantitatively in Step 4). A drift would mean that the system was still equilibrating.

Is the integration sound? In an NVE simulation the total energy is conserved by the equations of motion, so any change is numerical error. This is a systematic check that costs nothing.

total energy per particle : -3.23495
fluctuation (std)         : 2.7e-04
drift over the whole run  : +3.6e-04   (1.1e-04 of its value)
for comparison, std of the potential energy per particle: 4.6e-02

The fluctuation of the total energy is two orders of magnitude smaller than that of the potential energy, and the total energy drifts by about one part in 104 of its value over the run. For the purposes of this example the integration is sound.

Step 2. The naive error bar, and why it is wrong

Treating the 40 000 saved values as independent gives the following.

quantity     mean        std        naive s/sqrt(N)
T           0.98361    0.03062     0.00015
U/N        -4.70460    0.04583     0.00023
P           1.59700    0.20293     0.00101

A pressure with a relative uncertainty of 0.06 % from a two-minute simulation of 256 particles would be remarkable. It is also wrong. Configurations one time step apart are almost identical, as panel (a) of the figure below shows, and the autocorrelation functions in panel (b) take some tens of steps to decay.

quantity   tau_int (steps)   tau_int (time)   N_eff    sqrt(2 tau_int)
T               6.9          0.034          2918       3.70
U/N             6.8          0.034          2929       3.70
P              11.5          0.057          1742       4.79

The 40 000 samples are worth only about 3000 independent values for the energy and temperature and fewer than 2000 for the pressure. The naive error bars are too small by the factors in the last column, 3.7 and 4.8.

(Temperature and potential energy have the same correlation time. In an NVE simulation their sum, in the form of the total energy, is fixed, so they are two views of the same fluctuation.)

Step 3. Block averaging

<Figure size 1012x792 with 4 Axes>

Panel (c) is the blocking analysis of Section 17.4, with the standard error divided by its naive value. The dotted lines are the independent estimates 2τint\sqrt{2\tau_\text{int}} from the autocorrelation functions.

The energy curve levels off for blocks longer than about half a time unit, at the value given by τint\tau_\text{int}. The pressure curve is less tidy, as real data often are: it flattens near the τint\tau_\text{int} value but continues to creep upwards, within its growing error bars. The cause is visible in panel (b). The pressure autocorrelation function has a small positive tail that persists for several tenths of a time unit, and the summation window of the τint\tau_\text{int} estimate cuts part of it off. The last points of a blocking curve, with few blocks, carry large error bars and should not be over-read, but the trend is a reason to prefer long blocks here.

We take blocks of 500 steps (2.5 time units, 80 blocks), which leaves enough blocks for a reliable standard deviation.

blocks of 500 steps (2.5 time units), 80 blocks

quantity   naive          from tau_int    block average    result
T          0.00015        0.00057         0.00056        0.98361 ± 0.00056
U/N        0.00023        0.00085         0.00084        -4.70460 ± 0.00084
P          0.00101        0.00486         0.00471        1.5970 ± 0.0047

The two corrected estimates agree with each other to within their own precision (with 80 blocks, the block estimate is itself uncertain by about 8 %, Section 4.3). For the pressure, panel (c) suggests that the true standard error may be some 10 % larger than the value in the table. An uncertainty known to 10 or 20 % is a perfectly good uncertainty; this is why two significant figures are the most that an error bar deserves.

Step 4. Are the error bars believable?

In the notebooks with synthetic data we verified error bars by repeating the experiment thousands of times. With a real simulation the equivalent is to run independent replicas, which is the best test and is left as an exercise. A cheaper check uses the run itself: the two halves of the run are (nearly) independent measurements of the same quantity, so their difference should be compatible with zero in units of its uncertainty (Section 1.6).

quantity   first half    second half    difference / its uncertainty
T            0.98398      0.98323       +0.66    (with naive error bars: +2.43)
U/N         -4.70520     -4.70400       -0.72    (with naive error bars: -2.63)
P            1.59539      1.59861       -0.34    (with naive error bars: -1.59)

With the block error bars the two halves agree to within one standard uncertainty for all three quantities: no sign of drift, and no sign that the error bars are too small. With the naive error bars the same differences would have been read as 2.4 and 2.6 standard uncertainties for temperature and energy, and one might have concluded, wrongly, that the system was still equilibrating.

Saving less often loses almost nothing

Since neighbouring samples are nearly redundant, most of them can be discarded without harm. The table shows the block-average standard error of the pressure when only every nnth step is kept.

keep every   samples   naive s/sqrt(N)   correct standard error
      1       40000      0.00101           0.00471
      5        8000      0.00227           0.00471
     20        2000      0.00454           0.00521
     50         800      0.00718           0.00735
    100         400      0.01015           0.01017

Keeping every 5th step loses nothing. Keeping every 20th step, an interval of about 2τint2\tau_\text{int}, reduces the data twentyfold and increases the true uncertainty by only 10 %. Beyond that, information is being lost, the samples are effectively independent, and the naive error bar becomes correct. Saving every step buys nothing except disk usage and a false sense of precision.

Step 5. The self-diffusion coefficient

The diffusion coefficient follows from the long-time slope of the mean-square displacement (Einstein relation),

⟨∣r(t)−r(0)∣2⟩→6Dt+const.\langle |\boldsymbol r(t) - \boldsymbol r(0)|^2\rangle \to 6Dt + \text{const} .

DD is not an average of a time series, so the methods above do not apply directly. The cleanest route to its uncertainty is the one recommended in Section 17.5 for derived quantities: divide the run into blocks long compared with the correlation time, compute the complete quantity in each block, and use the scatter between blocks. The script saved the mean-square displacement separately for 10 consecutive blocks of 20 time units (panel (d)). For each block we fit a straight line between lag times 2 and 8 and take D=slope/6D = \text{slope}/6.

D in each block: [0.0668 0.0665 0.0659 0.0594 0.0564 0.0707 0.066  0.0618 0.0658 0.0555]
D = 0.0635 ± 0.0016   (relative uncertainty 2.5%, from 10 blocks)

With only ten blocks, the standard error is itself uncertain by about a quarter, and a 95 % interval should use Student’s tt (t=2.26t = 2.26 for nine degrees of freedom) and not the factor 2.

The fit window is a choice, and choices are a source of systematic uncertainty. A simple test is to vary it.

fit window     D          u_D
   1 to  5    0.0625     0.0010
   2 to  8    0.0635     0.0016
   4 to 10    0.0643     0.0021
   6 to 10    0.0645     0.0024

The estimate rises by about 3 % from the earliest to the latest window, an amount comparable with the statistical uncertainty. (The four values come from the same trajectories, so they are strongly correlated and their differences are more significant than the individual error bars suggest.) A slow approach of the mean-square displacement to its asymptotic slope would produce such a trend. Windows at long lag times also give noisier estimates, because fewer independent time origins contribute. We keep the window from 2 to 8 and note that the choice of window contributes an uncertainty of 1 to 2 %, to be added to the statistical one.

Step 6. What the error bars do not include

The final statistical results of this run are:

T   = 0.98361 ± 0.00056
U/N = -4.70460 ± 0.00084
P   = 1.5970 ± 0.0047
D   = 0.0635 ± 0.0016

These uncertainties answer one question: how much would the averages change if the same simulation were run again with different initial velocities? They say nothing about the following.

The state point. The run is at constant energy, and the temperature is an output: T=0.984T = 0.984, not the 1.0 that was aimed for during equilibration. Reporting the pressure above as “the pressure at ρ=0.8\rho = 0.8, T=1.0T = 1.0” would be an error far larger than the statistical uncertainty, because (∂P/∂T)ρ(\partial P/\partial T)_\rho is large in a dense liquid (roughly 4 to 5 in reduced units near this state point; it can be measured with a second run at a slightly different energy). A temperature offset of 0.016 then shifts the pressure by about 0.07, more than ten times uPu_P. This is the same lesson as the temperature of the glycerol in Chapter 21: define the measurand before quoting its uncertainty.

The model. The potential is truncated and shifted at 2.5 σ2.5\,\sigma. The results are properties of that model. They differ substantially from those of the full Lennard-Jones potential (the pressure by several tenths of a reduced unit at this density) and must not be compared with them without correction.

Finite size. With 256 particles in a periodic box, thermodynamic averages carry errors of order 1/N1/N. The diffusion coefficient is affected much more strongly, because the hydrodynamic flow field of a moving particle interacts with its periodic images. The correction derived by Yeh and Hummer,

D∞=DPBC+ξ kBT6πηL,ξ≈2.837,D_\infty = D_\text{PBC} + \frac{\xi\,k_\mathrm{B}T}{6\pi\eta L} , \qquad \xi \approx 2.837 ,

with η\eta the shear viscosity and LL the box length, decays only as 1/L1/L and is typically of order ten per cent or more for a few hundred particles, several times the statistical uncertainty found above.

The time step. Velocity-Verlet averages carry a discretisation error of order Δt2\Delta t^2. It is checked by repeating the run with half the time step.

Unsampled slow processes. A simple liquid at this state point relaxes in about a time unit, and 200 time units are ample. For a glass-former, a polymer melt or a system near a phase transition the same run length could be shorter than one correlation time, and every error bar computed from it would be meaningless (Section 17.6).

A complete statement of a simulation result therefore reads like the uncertainty budget of an experiment: the statistical uncertainty from block averaging, plus an estimate or bound for each systematic effect, obtained by varying the system size, the time step and the cutoff.

Summary

  • Successive MD configurations are correlated. Here the naive standard error was too small by factors of 3.7 to 4.8; in slowly relaxing systems the factor can be in the hundreds.

  • Block averaging and the integrated autocorrelation time give consistent, correct error bars; use one and check with the other.

  • Split-run comparisons and independent replicas test the error bars.

  • For derived quantities such as DD, compute the whole quantity in independent blocks.

  • The statistical error bar is the smallest part of the story. State point, model, system size and time step each need their own estimate.

References

  • M. P. Allen and D. J. Tildesley, Computer Simulation of Liquids, 2nd ed. (Oxford University Press, 2017).

  • D. Frenkel and B. Smit, Understanding Molecular Simulation, 2nd ed. (Academic Press, 2002).

  • I.-C. Yeh and G. Hummer, “System-size dependence of diffusion coefficients and viscosities from molecular dynamics simulations with periodic boundary conditions”, J. Phys. Chem. B 108, 15873 (2004).

Exercises

  1. Run scripts/run_lj_md.py five times with different seeds (change SEED). Is the scatter of the five mean pressures consistent with the error bar found here?

  2. Repeat the run with DT = 0.0025 and twice the number of steps. Do U/NU/N and PP change by more than their statistical uncertainty?

  3. Repeat with N_CELLS = 5 (500 particles). By how much does DD change? Estimate the viscosity that the Yeh–Hummer formula would imply.

  4. Estimate the constant-volume heat capacity from the fluctuations of the kinetic energy in the NVE ensemble (Lebowitz–Percus–Verlet formula) and obtain its uncertainty with ep.jackknife over blocks.

  5. Equilibrate badly on purpose (set N_EQUIL = 200, N_RELAX = 0) and repeat the split-half test.