Merge branch release-2016
[alexxy/gromacs.git] / docs / manual / algorithms.tex
1 %
2 % This file is part of the GROMACS molecular simulation package.
3 %
4 % Copyright (c) 2013,2014,2015,2016,2017, by the GROMACS development team, led by
5 % Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 % and including many others, as listed in the AUTHORS file in the
7 % top-level source directory and at http://www.gromacs.org.
8 %
9 % GROMACS is free software; you can redistribute it and/or
10 % modify it under the terms of the GNU Lesser General Public License
11 % as published by the Free Software Foundation; either version 2.1
12 % of the License, or (at your option) any later version.
13 %
14 % GROMACS is distributed in the hope that it will be useful,
15 % but WITHOUT ANY WARRANTY; without even the implied warranty of
16 % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 % Lesser General Public License for more details.
18 %
19 % You should have received a copy of the GNU Lesser General Public
20 % License along with GROMACS; if not, see
21 % http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 % Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23 %
24 % If you want to redistribute modifications to GROMACS, please
25 % consider that scientific software is very special. Version
26 % control is crucial - bugs must be traceable. We will be happy to
27 % consider code for inclusion in the official distribution, but
28 % derived work must not be called official GROMACS. Details are found
29 % in the README & COPYING files - if they are missing, get the
30 % official version at http://www.gromacs.org.
31 %
32 % To help us fund GROMACS development, we humbly ask that you cite
33 % the research papers on the package. Check out http://www.gromacs.org.
34
35 \newcommand{\nproc}{\mbox{$M$}}
36 \newcommand{\natom}{\mbox{$N$}}
37 \newcommand{\nx}{\mbox{$n_x$}}
38 \newcommand{\ny}{\mbox{$n_y$}}
39 \newcommand{\nz}{\mbox{$n_z$}}
40 \newcommand{\nsgrid}{NS grid}
41 \newcommand{\fftgrid}{FFT grid}
42 \newcommand{\dgrid}{\mbox{$\delta_{grid}$}}
43 \newcommand{\bfv}[1]{{\mbox{\boldmath{$#1$}}}}
44 % non-italicized boldface for math (e.g. matrices)                              
45 \newcommand{\bfm}[1]{{\bf #1}}
46 \newcommand{\dt}{\Delta t}
47 \newcommand{\rv}{\bfv{r}}
48 \newcommand{\vv}{\bfv{v}}
49 \newcommand{\F}{\bfv{F}}
50 \newcommand{\pb}{\bfv{p}}
51 \newcommand{\veps}{v_{\epsilon}}
52 \newcommand{\peps}{p_{\epsilon}}
53 \newcommand{\sinhx}[1]{\frac{\sinh{\left( #1\right)}}{#1}}
54 \chapter{Algorithms}
55 \label{ch:algorithms}
56 \section{Introduction}
57 In this chapter we first give describe some general concepts used in
58 {\gromacs}:  {\em periodic boundary conditions} (\secref{pbc})
59 and the {\em group concept} (\secref{groupconcept}). The MD algorithm is
60 described in \secref{MD}: first a global form of the algorithm is
61 given, which is refined in subsequent subsections. The (simple) EM
62 (Energy Minimization) algorithm is described in \secref{EM}. Some
63 other algorithms for special purpose dynamics are described after
64 this.  
65
66 A few issues are of general interest. In all cases the {\em system}
67 must be defined, consisting of molecules. Molecules again consist of
68 particles  with defined interaction functions. The detailed
69 description of the {\em topology} of the molecules and of the {\em force
70 field} and the calculation of forces is given in
71 \chref{ff}. In the present chapter we describe
72 other aspects of the algorithm, such as pair list generation, update of
73 velocities  and positions, coupling to external temperature and
74 pressure,  conservation of constraints. 
75 The {\em analysis} of the data generated by an MD simulation is treated in \chref{analysis}.
76
77 \section{Periodic boundary conditions\index{periodic boundary conditions}}
78 \label{sec:pbc}
79 \begin{figure}
80 \centerline{\includegraphics[width=9cm]{plots/pbctric}}
81 \caption {Periodic boundary conditions in two dimensions.}
82 \label{fig:pbc}
83 \end{figure}
84 The classical way to minimize edge effects in a finite system is to
85 apply {\em periodic boundary conditions}. The atoms of the system to
86 be simulated are put into a space-filling box, which is surrounded by
87 translated copies of itself (\figref{pbc}).  Thus there are no
88 boundaries of the system; the artifact caused by unwanted boundaries
89 in an isolated cluster is now replaced by the artifact of periodic
90 conditions. If the system is crystalline, such boundary conditions are
91 desired (although motions are naturally restricted to periodic motions
92 with wavelengths fitting into the box). If one wishes to simulate
93 non-periodic systems, such as liquids or solutions, the periodicity by
94 itself causes errors. The errors can be evaluated by comparing various
95 system sizes; they are expected to be less severe than the errors
96 resulting from an unnatural boundary with vacuum.
97
98 There are several possible shapes for space-filling unit cells. Some,
99 like the {\em \normindex{rhombic dodecahedron}} and the
100 {\em \normindex{truncated octahedron}}~\cite{Adams79} are closer to being a sphere
101 than a cube is, and are therefore better suited to the 
102 study of an approximately spherical macromolecule in solution, since
103 fewer solvent molecules are required to fill the box given a minimum
104 distance between macromolecular images. At the same time, rhombic 
105 dodecahedra and truncated octahedra are special cases of {\em triclinic} 
106 unit cells\index{triclinic unit cell}; the most general space-filling unit cells
107 that comprise all possible space-filling shapes~\cite{Bekker95}.
108 For this reason, {\gromacs} is based on the triclinic unit cell.
109   
110 {\gromacs} uses periodic boundary conditions, combined with the {\em
111 \normindex{minimum image convention}}: only one -- the nearest -- image of each
112 particle is considered for short-range non-bonded interaction terms.
113 For long-range electrostatic interactions this is not always accurate
114 enough, and {\gromacs} therefore also incorporates lattice sum methods
115 such as Ewald Sum, PME and PPPM.
116
117 {\gromacs} supports triclinic boxes of any shape.
118 The simulation box (unit cell) is defined by the 3 box vectors 
119 ${\bf a}$,${\bf b}$ and ${\bf c}$.
120 The box vectors must satisfy the following conditions:
121 \beq
122 \label{eqn:box_rot}
123 a_y = a_z = b_z = 0
124 \eeq
125 \beq
126 \label{eqn:box_shift1}
127 a_x>0,~~~~b_y>0,~~~~c_z>0
128 \eeq
129 \beq
130 \label{eqn:box_shift2}
131 |b_x| \leq \frac{1}{2} \, a_x,~~~~
132 |c_x| \leq \frac{1}{2} \, a_x,~~~~
133 |c_y| \leq \frac{1}{2} \, b_y
134 \eeq
135 Equations \ref{eqn:box_rot} can always be satisfied by rotating the box.
136 Inequalities (\ref{eqn:box_shift1}) and (\ref{eqn:box_shift2}) can always be
137 satisfied by adding and subtracting box vectors.
138
139 Even when simulating using a triclinic box, {\gromacs} always keeps the
140 particles in a brick-shaped volume for efficiency,
141 as illustrated in \figref{pbc} for a 2-dimensional system.
142 Therefore, from the output trajectory it might seem that the simulation was
143 done in a rectangular box. The program {\tt trjconv} can be used to convert 
144 the trajectory to a different unit-cell representation.
145
146 It is also possible to simulate without periodic boundary conditions,
147 but it is usually more efficient to simulate an isolated cluster of molecules
148 in a large periodic box, since fast grid searching can only be used 
149 in a periodic system.
150
151 \begin{figure}
152 \centerline{
153 \includegraphics[width=5cm]{plots/rhododec}
154 ~~~~\includegraphics[width=5cm]{plots/truncoct}
155 }
156 \caption {A rhombic dodecahedron and truncated octahedron
157 (arbitrary orientations).}
158 \label{fig:boxshapes}
159 \end{figure}
160
161 \subsection{Some useful box types}
162 \begin{table}
163 \centerline{
164 \begin{tabular}{|c|c|c|ccc|ccc|}
165 \dline
166 box type & image & box & \multicolumn{3}{c|}{box vectors} & \multicolumn{3}{c|}{box vector angles} \\
167  & distance & volume & ~{\bf a}~ & {\bf b} & {\bf c} &
168    $\angle{\bf bc}$ & $\angle{\bf ac}$ & $\angle{\bf ab}$ \\
169 \dline
170              &     &       & $d$ & 0              & 0              & & & \\
171 cubic        & $d$ & $d^3$ & 0   & $d$            & 0              & $90^\circ$ & $90^\circ$ & $90^\circ$ \\
172              &     &       & 0   & 0              & $d$            & & & \\
173 \hline
174 rhombic      &     &       & $d$ & 0              & $\frac{1}{2}\,d$ & & & \\
175 dodecahedron & $d$ & $\frac{1}{2}\sqrt{2}\,d^3$ & 0   & $d$            & $\frac{1}{2}\,d$ & $60^\circ$ & $60^\circ$ & $90^\circ$ \\
176 (xy-square)  &     & $0.707\,d^3$ & 0   & 0              & $\frac{1}{2}\sqrt{2}\,d$ & & & \\
177 \hline
178 rhombic      &     &       & $d$ & $\frac{1}{2}\,d$ & $\frac{1}{2}\,d$ & & & \\
179 dodecahedron & $d$ & $\frac{1}{2}\sqrt{2}\,d^3$ & 0 & $\frac{1}{2}\sqrt{3}\,d$ & $\frac{1}{6}\sqrt{3}\,d$ & $60^\circ$ & $60^\circ$ & $60^\circ$ \\
180 (xy-hexagon) &     & $0.707\,d^3$ & 0   & 0              & $\frac{1}{3}\sqrt{6}\,d$ & & & \\
181 \hline
182 truncated    &     &       & $d$ & $\frac{1}{3}\,d$ & $-\frac{1}{3}\,d$ & & &\\
183 octahedron   & $d$ & $\frac{4}{9}\sqrt{3}\,d^3$ & 0   & $\frac{2}{3}\sqrt{2}\,d$ & $\frac{1}{3}\sqrt{2}\,d$ & $71.53^\circ$ & $109.47^\circ$ & $71.53^\circ$ \\
184              &     & $0.770\,d^3$ & 0   & 0              & $\frac{1}{3}\sqrt{6}\,d$ & & & \\
185 \dline
186 \end{tabular}
187 }
188 \caption{The cubic box, the rhombic \normindex{dodecahedron} and the truncated
189 \normindex{octahedron}.}
190 \label{tab:boxtypes}
191 \end{table}
192 The three most useful box types for simulations of solvated systems
193 are described in \tabref{boxtypes}.  The rhombic dodecahedron
194 (\figref{boxshapes}) is the smallest and most regular space-filling
195 unit cell. Each of the 12 image cells is at the same distance.  The
196 volume is 71\% of the volume of a cube having the same image
197 distance. This saves about 29\% of CPU-time when simulating a
198 spherical or flexible molecule in solvent. There are two different
199 orientations of a rhombic dodecahedron that satisfy equations
200 \ref{eqn:box_rot}, \ref{eqn:box_shift1} and \ref{eqn:box_shift2}.
201 The program {\tt editconf} produces the orientation
202 which has a square intersection with the xy-plane.  This orientation
203 was chosen because the first two box vectors coincide with the x and
204 y-axis, which is easier to comprehend. The other orientation can be
205 useful for simulations of membrane proteins. In this case the
206 cross-section with the xy-plane is a hexagon, which has an area which
207 is 14\% smaller than the area of a square with the same image
208 distance.  The height of the box ($c_z$) should be changed to obtain
209 an optimal spacing.  This box shape not only saves CPU time, it
210 also results in a more uniform arrangement of the proteins.
211
212 \subsection{Cut-off restrictions}
213 The \normindex{minimum image convention} implies that the cut-off radius used to
214 truncate non-bonded interactions may not exceed half the shortest box
215 vector:
216 \beq
217 \label{eqn:physicalrc}
218   R_c < \half \min(\|{\bf a}\|,\|{\bf b}\|,\|{\bf c}\|),
219 \eeq
220 because otherwise more than one image would be within the cut-off distance 
221 of the force. When a macromolecule, such as a protein, is studied in
222 solution, this restriction alone is not sufficient: in principle, a single
223 solvent molecule should not be able
224 to `see' both sides of the macromolecule. This means that the length of
225 each box vector must exceed the length of the macromolecule in the
226 direction of that edge {\em plus} two times the cut-off radius $R_c$.
227 It is, however, common to compromise in this respect, and make the solvent 
228 layer somewhat smaller in order to reduce the computational cost.
229 For efficiency reasons the cut-off with triclinic boxes is more restricted.
230 For grid search the extra restriction is weak:
231 \beq
232 \label{eqn:gridrc}
233 R_c < \min(a_x,b_y,c_z)
234 \eeq
235 For simple search the extra restriction is stronger:
236 \beq
237 \label{eqn:simplerc}
238 R_c < \half \min(a_x,b_y,c_z)
239 \eeq
240
241 Each unit cell (cubic, rectangular or triclinic)
242 is surrounded by 26 translated images. A
243 particular image can therefore always be identified by an index pointing to one
244 of 27 {\em translation vectors} and constructed by applying a
245 translation with the indexed vector (see \ssecref{forces}).
246 Restriction (\ref{eqn:gridrc}) ensures that only 26 images need to be
247 considered.
248
249 \section{The group concept}
250 \label{sec:groupconcept}\index{group}
251 The {\gromacs} MD and analysis programs use user-defined {\em groups} of
252 atoms to perform certain actions on. The maximum number of groups is
253 256, but each atom can only belong to six different groups, one 
254 each of the following:
255 \begin{description}
256 \item[\swapindex{temperature-coupling}{group}]
257 The \normindex{temperature coupling} parameters (reference
258 temperature, time constant, number of degrees of freedom, see
259 \ssecref{update}) can be defined for each T-coupling group
260 separately. For example, in a solvated macromolecule the solvent (that
261 tends to generate more heating by force and integration errors) can be
262 coupled with a shorter time constant to a bath than is a macromolecule,
263 or a surface can be kept cooler than an adsorbing molecule. Many
264 different T-coupling groups may be defined. See also center of mass
265 groups below.
266
267 \item[\swapindex{freeze}{group}\index{frozen atoms}]
268 Atoms that belong to a freeze group are kept stationary in the
269 dynamics. This is useful during equilibration, {\eg} to avoid badly
270 placed solvent molecules giving unreasonable kicks to protein atoms,
271 although the same effect can also be obtained by putting a restraining
272 potential on the atoms that must be protected. The freeze option can
273 be used, if desired, on just one or two coordinates of an atom,
274 thereby freezing the atoms in a plane or on a line.  When an atom is
275 partially frozen, constraints will still be able to move it, even in a
276 frozen direction. A fully frozen atom can not be moved by constraints.
277 Many freeze groups can be defined.  Frozen coordinates are unaffected
278 by pressure scaling; in some cases this can produce unwanted results,
279 particularly when constraints are also used (in this case you will
280 get very large pressures). Accordingly, it is recommended to avoid
281 combining freeze groups with constraints and pressure coupling. For the
282 sake of equilibration it could suffice to start with freezing in a
283 constant volume simulation, and afterward use position restraints in
284 conjunction with constant pressure.
285
286 \item[\swapindex{accelerate}{group}]
287 On each atom in an ``accelerate group'' an acceleration
288 $\ve{a}^g$ is imposed. This is equivalent to an external
289 force. This feature makes it possible to drive the system into a
290 non-equilibrium state and enables the performance of 
291 \swapindex{non-equilibrium}{MD} and hence to obtain transport properties.
292
293 \item[\swapindex{energy-monitor}{group}]
294 Mutual interactions between all energy-monitor groups are compiled
295 during the simulation. This is done separately for Lennard-Jones and
296 Coulomb terms.  In principle up to 256 groups could be defined, but
297 that would lead to 256$\times$256 items! Better use this concept
298 sparingly.
299
300 All non-bonded interactions between pairs of energy-monitor groups can
301 be excluded\index{exclusions} (see details in the User Guide).
302 Pairs of particles from excluded pairs of energy-monitor groups
303 are not put into the pair list.
304 This can result in a significant speedup
305 for simulations where interactions within or between parts of the system
306 are not required.
307
308 \item[\swapindex{center of mass}{group}\index{removing COM motion}]
309 In \gromacs\ the center of mass (COM) motion can be removed, for
310 either the complete system or for groups of atoms. The latter is
311 useful, {\eg} for systems where there is limited friction ({\eg} gas
312 systems) to prevent center of mass motion to occur. It makes sense to
313 use the same groups for temperature coupling and center of mass motion
314 removal.
315
316 \item[\swapindex{Compressed position output}{group}]
317
318 In order to further reduce the size of the compressed trajectory file
319 ({\tt .xtc{\index{XTC}}} or {\tt .tng{\index{TNG}}}), it is possible
320 to store only a subset of all particles. All x-compression groups that
321 are specified are saved, the rest are not. If no such groups are
322 specified, than all atoms are saved to the compressed trajectory file.
323
324 \end{description}
325 The use of groups in {\gromacs} tools is described in
326 \secref{usinggroups}.
327
328 \section{Molecular Dynamics}
329 \label{sec:MD}
330 \begin{figure}
331 \begin{center}
332 \addtolength{\fboxsep}{0.5cm}
333 \begin{shadowenv}[12cm]
334 {\large \bf THE GLOBAL MD ALGORITHM}
335 \rule{\textwidth}{2pt} \\
336 {\bf 1. Input initial conditions}\\[2ex]
337 Potential interaction $V$ as a function of atom positions\\
338 Positions $\ve{r}$ of all atoms in the system\\
339 Velocities $\ve{v}$ of all atoms in the system \\
340 $\Downarrow$\\
341 \rule{\textwidth}{1pt}\\
342 {\bf repeat 2,3,4} for the required number of steps:\\
343 \rule{\textwidth}{1pt}\\
344 {\bf 2. Compute forces} \\[1ex]
345 The force on any atom  \\[1ex]
346 $\ve{F}_i = - \displaystyle\frac{\partial V}{\partial \ve{r}_i}$ \\[1ex]
347 is computed by calculating the force between non-bonded atom pairs: \\
348 $\ve{F}_i = \sum_j \ve{F}_{ij}$ \\
349 plus the forces due to bonded interactions (which may depend on 1, 2,
350 3, or 4 atoms), plus restraining and/or external forces. \\
351 The potential and kinetic energies and the pressure tensor may be computed. \\
352 $\Downarrow$\\
353 {\bf 3. Update configuration} \\[1ex]
354 The movement of the atoms is simulated by numerically solving Newton's
355 equations of motion \\[1ex]
356 $\displaystyle
357 \frac {\de^2\ve{r}_i}{\de t^2} = \frac{\ve{F}_i}{m_i} $ \\
358 or \\
359 $\displaystyle
360 \frac{\de\ve{r}_i}{\de t} = \ve{v}_i ; \;\;
361 \frac{\de\ve{v}_i}{\de t} = \frac{\ve{F}_i}{m_i} $ \\[1ex]
362 $\Downarrow$ \\
363 {\bf 4.} if required: {\bf Output step} \\
364 write positions, velocities, energies, temperature, pressure, etc. \\
365 \end{shadowenv}
366 \caption{The global MD algorithm}
367 \label{fig:global}
368 \end{center}
369 \end{figure}
370 A global flow scheme for MD is given in \figref{global}. Each
371 MD or  EM run requires as input a set of initial coordinates and --
372 optionally -- initial velocities of all particles involved. This
373 chapter does not describe how these are obtained; for the setup of an
374 actual MD run check the online manual at {\wwwpage}.
375
376 \subsection{Initial conditions}
377 \subsubsection{Topology and force field}
378 The system topology, including a description of the force field, must
379 be read in.
380 Force fields and topologies are described in \chref{ff}
381 and \ref{ch:top}, respectively.
382 All this information is static; it is never modified during the run.
383
384 \subsubsection{Coordinates and velocities}
385 \begin{figure}
386 \centerline{\includegraphics[width=8cm]{plots/maxwell}}
387 \caption{A Maxwell-Boltzmann velocity distribution, generated from 
388     random numbers.}
389 \label{fig:maxwell}
390 \end{figure}
391
392 Then, before a run starts, the box size and the coordinates and
393 velocities of  all particles are required. The box size and shape is 
394 determined by three vectors (nine numbers) $\ve{b}_1, \ve{b}_2, \ve{b}_3$, 
395 which represent the three basis vectors of the periodic box.
396
397 If the run starts at $t=t_0$, the coordinates at $t=t_0$ must be
398 known. The {\em leap-frog algorithm}, the default algorithm used to 
399 update the time step with $\Dt$ (see \ssecref{update}), also requires 
400 that the velocities at $t=t_0 - \hDt$ are known. If velocities are not 
401 available, the program can generate initial atomic velocities 
402 $v_i, i=1\ldots 3N$ with a \index{Maxwell-Boltzmann distribution} 
403 (\figref{maxwell}) at a given absolute temperature $T$:
404 \beq 
405 p(v_i) = \sqrt{\frac{m_i}{2 \pi kT}}\exp\left(-\frac{m_i v_i^2}{2kT}\right)
406 \eeq
407 where $k$ is Boltzmann's constant (see \chref{defunits}).
408 To accomplish this, normally distributed random numbers are generated
409 by adding twelve random numbers $R_k$ in the range $0 \le R_k < 1$ and
410 subtracting 6.0 from their sum. The result is then multiplied by the
411 standard deviation of the velocity distribution $\sqrt{kT/m_i}$. Since
412 the resulting total energy will not correspond exactly to the required
413 temperature $T$, a correction is made: first the center-of-mass motion
414 is removed and then all velocities are scaled so that the total
415 energy corresponds exactly to $T$ (see \eqnref{E-T}). 
416 % Why so complicated? What's wrong with Box-Mueller transforms?
417
418 \subsubsection{Center-of-mass motion\index{removing COM motion}}
419 The \swapindex{center-of-mass}{velocity} is normally set to zero at
420 every step; there is (usually) no net external force acting on the
421 system and the center-of-mass velocity should remain constant. In
422 practice, however, the update algorithm introduces a very slow change in
423 the center-of-mass velocity, and therefore in the total kinetic energy of
424 the system -- especially when temperature coupling is used. If such
425 changes are not quenched, an appreciable center-of-mass motion
426 can develop in long runs, and the temperature will be
427 significantly misinterpreted. Something similar may happen due to overall
428 rotational motion, but only when an isolated cluster is simulated. In
429 periodic systems with filled boxes, the overall rotational motion is
430 coupled to other degrees of freedom and does not cause such problems.
431
432
433 \subsection{Neighbor searching\swapindexquiet{neighbor}{searching}}
434 \label{subsec:ns}
435 As mentioned in \chref{ff}, internal forces are
436 either generated from fixed (static) lists, or from dynamic lists.
437 The latter consist of non-bonded interactions between any pair of particles.
438 When calculating the non-bonded forces, it is convenient to have all
439 particles in a rectangular box.
440 As shown in \figref{pbc}, it is possible to transform a
441 triclinic box into a rectangular box.
442 The output coordinates are always in a rectangular box, even when a
443 dodecahedron or triclinic box was used for the simulation.
444 Equation \ref{eqn:box_rot} ensures that we can reset particles
445 in a rectangular box by first shifting them with
446 box vector ${\bf c}$, then with ${\bf b}$ and finally with ${\bf a}$.
447 Equations \ref{eqn:box_shift2}, \ref{eqn:physicalrc} and \ref{eqn:gridrc}
448 ensure that we can find the 14 nearest triclinic images within
449 a linear combination that does not involve multiples of box vectors.
450
451 \subsubsection{Pair lists generation}
452 The non-bonded pair forces need to be calculated only for those pairs
453 $i,j$  for which the distance $r_{ij}$ between $i$ and the 
454 \swapindex{nearest}{image} 
455 of $j$ is less than a given cut-off radius $R_c$. Some of the particle
456 pairs that fulfill this criterion are excluded, when their interaction
457 is already fully accounted for by bonded interactions.  {\gromacs}
458 employs a {\em pair list} that contains those particle pairs for which
459 non-bonded forces must be calculated.  The pair list contains particles
460 $i$, a displacement vector for particle $i$, and all particles $j$ that
461 are within \verb'rlist' of this particular image of particle $i$.  The
462 list is updated every \verb'nstlist' steps.
463
464 To make the \normindex{neighbor list}, all particles that are close
465 ({\ie} within the neighbor list cut-off) to a given particle must be found.
466 This searching, usually called neighbor search (NS) or pair search,
467 involves periodic boundary conditions and determining the {\em image}
468 (see \secref{pbc}). The search algorithm is $O(N)$, although a simpler
469 $O(N^2)$ algorithm is still available under some conditions.
470
471 \subsubsection{\normindex{Cut-off schemes}: group versus Verlet}
472 From version 4.6, {\gromacs} supports two different cut-off scheme
473 setups: the original one based on particle groups and one using a Verlet
474 buffer. There are some important differences that affect results,
475 performance and feature support. The group scheme can be made to work
476 (almost) like the Verlet scheme, but this will lead to a decrease in
477 performance. The group scheme is especially fast for water molecules,
478 which are abundant in many simulations, but on the most recent x86
479 processors, this advantage is negated by the better instruction-level
480 parallelism available in the Verlet-scheme implementation. The group
481 scheme is deprecated in version 5.0, and will be removed in a future
482 version. For practical details of choosing and setting up
483 cut-off schemes, please see the User Guide.
484
485 In the group scheme, a neighbor list is generated consisting of pairs
486 of groups of at least one particle. These groups were originally
487 \swapindex{charge}{group}s (see
488   \secref{chargegroup}), but with a proper treatment of long-range
489 electrostatics, performance in unbuffered simulations is their only advantage. A pair of groups
490 is put into the neighbor list when their center of geometry is within
491 the cut-off distance. Interactions between all particle pairs (one from
492 each charge group) are calculated for a certain number of MD steps,
493 until the neighbor list is updated. This setup is efficient, as the
494 neighbor search only checks distance between charge-group pair, not
495 particle pairs (saves a factor of $3 \times 3 = 9$ with a three-particle water
496 model) and the non-bonded force kernels can be optimized for, say, a
497 water molecule ``group''. Without explicit buffering, this setup leads
498 to energy drift as some particle pairs which are within the cut-off don't
499 interact and some outside the cut-off do interact. This can be caused
500 by
501 \begin{itemize}
502 \item particles moving across the cut-off between neighbor search steps, and/or
503 \item for charge groups consisting of more than one particle, particle pairs
504   moving in/out of the cut-off when their charge group center of
505   geometry distance is outside/inside of the cut-off.
506 \end{itemize}
507 Explicitly adding a buffer to the neighbor list will remove such
508 artifacts, but this comes at a high computational cost. How severe the
509 artifacts are depends on the system, the properties in which you are
510 interested, and the cut-off setup.
511
512 The Verlet cut-off scheme uses a buffered pair list by default. It
513 also uses clusters of particles, but these are not static as in the group
514 scheme. Rather, the clusters are defined spatially and consist of 4 or
515 8 particles, which is convenient for stream computing, using e.g. SSE, AVX
516 or CUDA on GPUs. At neighbor search steps, a pair list is created
517 with a Verlet buffer, ie. the pair-list cut-off is larger than the
518 interaction cut-off. In the non-bonded kernels, interactions are only
519 computed when a particle pair is within the cut-off distance at that
520 particular time step. This ensures that as particles move between pair
521 search steps, forces between nearly all particles within the cut-off
522 distance are calculated. We say {\em nearly} all particles, because
523 {\gromacs} uses a fixed pair list update frequency for
524 efficiency. A particle-pair, whose distance was outside the cut-off,
525 could possibly move enough during this fixed number of
526 steps that its distance is now within the cut-off. This
527 small chance results in a small energy drift, and the size of the
528 chance depends on the temperature. When temperature
529 coupling is used, the buffer size can be determined automatically,
530 given a certain tolerance on the energy drift.
531
532 The Verlet cut-off scheme is implemented in a very efficient fashion
533 based on clusters of particles. The simplest example is a cluster size
534 of 4 particles. The pair list is then constructed based on cluster
535 pairs. The cluster-pair search is much faster searching based on
536 particle pairs, because $4 \times 4 = 16$ particle pairs are put in
537 the list at once. The non-bonded force calculation kernel can then
538 calculate many particle-pair interactions at once, which maps nicely
539 to SIMD or SIMT units on modern hardware, which can perform multiple
540 floating operations at once. These non-bonded kernels
541 are much faster than the kernels used in the group scheme for most
542 types of systems, particularly on newer hardware.
543
544 Additionally, when the list buffer is determined automatically as
545 described below, we also apply dynamic pair list pruning. The pair list
546 can be constructed infrequently, but that can lead to a lot of pairs
547 in the list that are outside the cut-off range for all or most of
548 the life time of this pair list. Such pairs can be pruned out by
549 applying a cluster-pair kernel that only determines which clusters
550 are in range. Because of the way the non-bonded data is regularized
551 in {\gromacs}, this kernel is an order of magnitude faster than
552 the search and the interaction kernel. On the GPU this pruning is
553 overlapped with the integration on the CPU, so it is free in most
554 cases. Therefore we can prune every 4-10 integration steps with
555 little overhead and significantly reduce the number of cluster pairs
556 in the interaction kernel. This procedure is applied automatically,
557 unless the user set the pair-list buffer size manually.
558
559 \subsubsection{Energy drift and pair-list buffering}
560 For a canonical (NVT) ensemble, the average energy error caused by
561 diffusion of $j$ particles from outside the pair-list cut-off
562 $r_\ell$ to inside the interaction cut-off $r_c$ over the lifetime
563 of the list can be determined from the atomic
564 displacements and the shape of the potential at the cut-off.
565 %Since we are interested in the small drift regime, we will assume
566 %#that atoms will only move within the cut-off distance in the last step,
567 %$n_\mathrm{ps}-1$, of the pair list update interval $n_\mathrm{ps}$.
568 %Over this number of steps the displacment of an atom with mass $m$
569 The displacement distribution along one dimension for a freely moving
570 particle with mass $m$ over time $t$ at temperature $T$ is
571 a Gaussian $G(x)$
572 of zero mean and variance $\sigma^2 = t^2 k_B T/m$. For the distance
573 between two particles, the variance changes to $\sigma^2 = \sigma_{12}^2 =
574 t^2 k_B T(1/m_1+1/m_2)$. Note that in practice particles usually
575 interact with (bump into) other particles over time $t$ and therefore the real
576 displacement distribution is much narrower.  Given a non-bonded
577 interaction cut-off distance of $r_c$ and a pair-list cut-off
578 $r_\ell=r_c+r_b$ for $r_b$ the Verlet buffer size, we can then
579 write the average energy error after time $t$ for all missing pair
580 interactions between a single $i$ particle of type 1 surrounded
581 by all $j$ particles that are of type 2 with number density $\rho_2$,
582 when the inter-particle distance changes from $r_0$ to $r_t$, as:
583 \beq
584 \langle \Delta V \rangle =
585 \int_{0}^{r_c} \int_{r_\ell}^\infty 4 \pi r_0^2 \rho_2 V(r_t) G\!\left(\frac{r_t-r_0}{\sigma}\right) d r_0\, d r_t
586 \eeq
587 To evaluate this analytically, we need to make some approximations. First we replace $V(r_t)$ by a Taylor expansion around $r_c$, then we can move the lower bound of the integral over $r_0$ to $-\infty$ which will simplify the result:
588 \begin{eqnarray}
589 \langle \Delta V \rangle &\approx&
590 \int_{-\infty}^{r_c} \int_{r_\ell}^\infty 4 \pi r_0^2 \rho_2 \Big[ V'(r_c) (r_t - r_c) +
591 \nonumber\\
592 & &
593 \phantom{\int_{-\infty}^{r_c} \int_{r_\ell}^\infty 4 \pi r_0^2 \rho_2 \Big[}
594 V''(r_c)\frac{1}{2}(r_t - r_c)^2 +
595 \nonumber\\
596 & &
597 \phantom{\int_{-\infty}^{r_c} \int_{r_\ell}^\infty 4 \pi r_0^2 \rho_2 \Big[}
598   V'''(r_c)\frac{1}{6}(r_t - r_c)^3 +
599   \nonumber\\
600 & &
601 \phantom{\int_{-\infty}^{r_c} \int_{r_\ell}^\infty 4 \pi r_0^2 \rho_2 \Big[}
602   O \! \left((r_t - r_c)^4 \right)\Big] G\!\left(\frac{r_t-r_0}{\sigma}\right) d r_0 \, d r_t
603 \end{eqnarray}
604 Replacing the factor $r_0^2$ by $(r_\ell + \sigma)^2$, which results in a slight overestimate, allows us to calculate the integrals analytically:
605 \begin{eqnarray}
606 \langle \Delta V \rangle \!
607 &\approx&
608 4 \pi (r_\ell+\sigma)^2 \rho_2
609 \int_{-\infty}^{r_c} \int_{r_\ell}^\infty \Big[ V'(r_c) (r_t - r_c) +
610 \nonumber\\
611 & &
612 \phantom{4 \pi (r_\ell+\sigma)^2 \rho_2 \int_{-\infty}^{r_c} \int_{r_\ell}^\infty \Big[}
613 V''(r_c)\frac{1}{2}(r_t - r_c)^2 +
614 \nonumber\\
615 & &
616 \phantom{4 \pi (r_\ell+\sigma)^2 \rho_2 \int_{-\infty}^{r_c} \int_{r_\ell}^\infty \Big[}
617 V'''(r_c)\frac{1}{6}(r_t - r_c)^3 \Big] G\!\left(\frac{r_t-r_0}{\sigma}\right)
618 d r_0 \, d r_t\\
619 &=&
620 4 \pi (r_\ell+\sigma)^2 \rho_2 \bigg\{
621 \frac{1}{2}V'(r_c)\left[r_b \sigma G\!\left(\frac{r_b}{\sigma}\right) - (r_b^2+\sigma^2)E\!\left(\frac{r_b}{\sigma}\right) \right] +
622 \nonumber\\
623 & &
624 \phantom{4 \pi (r_\ell+\sigma)^2 \rho_2 \bigg\{ }
625 \frac{1}{6}V''(r_c)\left[ \sigma(r_b^2+2\sigma^2) G\!\left(\frac{r_b}{\sigma}\right) - r_b(r_b^2+3\sigma^2 ) E\!\left(\frac{r_b}{\sigma}\right) \right] +
626 \nonumber\\
627 & &
628 \phantom{4 \pi (r_\ell+\sigma)^2 \rho_2 \bigg\{ }
629 \frac{1}{24}V'''(r_c)\bigg[ r_b\sigma(r_b^2+5\sigma^2) G\!\left(\frac{r_b}{\sigma}\right)
630 \nonumber\\
631 & &
632 \phantom{4 \pi (r_\ell+\sigma)^2 \rho_2 \bigg\{ \frac{1}{24}V'''(r_c)\bigg[ }
633  - (r_b^4+6r_b^2\sigma^2+3\sigma^4 ) E\!\left(\frac{r_b}{\sigma}\right) \bigg]
634 \bigg\}
635 \end{eqnarray}
636
637 where $G(x)$ is a Gaussian distribution with 0 mean and unit variance and
638 $E(x)=\frac{1}{2}\mathrm{erfc}(x/\sqrt{2})$. We always want to achieve
639 small energy error, so $\sigma$ will be small compared to both $r_c$
640 and $r_\ell$, thus the approximations in the equations above are good,
641 since the Gaussian distribution decays rapidly. The energy error needs
642 to be averaged over all particle pair types and weighted with the
643 particle counts. In {\gromacs} we don't allow cancellation of error
644 between pair types, so we average the absolute values. To obtain the
645 average energy error per unit time, it needs to be divided by the
646 neighbor-list life time $t = ({\tt nstlist} - 1)\times{\tt dt}$. The
647 function can not be inverted analytically, so we use bisection to
648 obtain the buffer size $r_b$ for a target drift.  Again we note that
649 in practice the error we usually be much smaller than this estimate,
650 as in the condensed phase particle displacements will be much smaller
651 than for freely moving particles, which is the assumption used here.
652
653 When (bond) constraints are present, some particles will have fewer
654 degrees of freedom. This will reduce the energy errors. For simplicity,
655 we only consider one constraint per particle, the heaviest particle
656 in case a particle is involved in multiple constraints.
657 This simplification overestimates the displacement. The motion of
658 a constrained particle is a superposition of the 3D motion of the
659 center of mass of both particles and a 2D rotation around the center of mass.
660 The displacement in an arbitrary direction of a particle with 2 degrees
661 of freedom is not Gaussian, but rather follows the complementary error
662 function:
663 \beq
664 \frac{\sqrt{\pi}}{2\sqrt{2}\sigma}\,\mathrm{erfc}\left(\frac{|r|}{\sqrt{2}\,\sigma}\right)
665 \label{eqn:2D_disp}
666 \eeq
667 where $\sigma^2$ is again $t^2 k_B T/m$.  This distribution can no
668 longer be integrated analytically to obtain the energy error. But we
669 can generate a tight upper bound using a scaled and shifted Gaussian
670 distribution (not shown). This Gaussian distribution can then be used
671 to calculate the energy error as described above. The rotation displacement
672 around the center of mass can not be more than the length of the arm.
673 To take this into account, we scale $\sigma$ in \eqnref{2D_disp} (details
674 not presented here) to obtain an overestimate of the real displacement.
675 This latter effect significantly reduces the buffer size for longer
676 neighborlist lifetimes in e.g. water, as constrained hydrogens are by far
677 the fastest particles, but they can not move further than 0.1 nm
678 from the heavy atom they are connected to.
679
680
681 There is one important implementation detail that reduces the energy
682 errors caused by the finite Verlet buffer list size. The derivation
683 above assumes a particle pair-list. However, the {\gromacs}
684 implementation uses a cluster pair-list for efficiency. The pair list
685 consists of pairs of clusters of 4 particles in most cases, also
686 called a $4 \times 4$ list, but the list can also be $4 \times 8$ (GPU
687 CUDA kernels and AVX 256-bit single precision kernels) or $4 \times 2$
688 (SSE double-precision kernels). This means that the pair-list is
689 effectively much larger than the corresponding $1 \times 1$ list. Thus
690 slightly beyond the pair-list cut-off there will still be a large
691 fraction of particle pairs present in the list. This fraction can be
692 determined in a simulation and accurately estimated under some
693 reasonable assumptions. The fraction decreases with increasing
694 pair-list range, meaning that a smaller buffer can be used. For
695 typical all-atom simulations with a cut-off of 0.9 nm this fraction is
696 around 0.9, which gives a reduction in the energy errors of a factor of
697 10. This reduction is taken into account during the automatic Verlet
698 buffer calculation and results in a smaller buffer size.
699
700 \begin{figure}
701 \centerline{\includegraphics[width=9cm]{plots/verlet-drift}}
702 \caption {Energy drift per atom for an SPC/E water system at 300K with
703   a time step of 2 fs and a pair-list update period of 10 steps
704   (pair-list life time: 18 fs). PME was used with {\tt ewald-rtol} set
705   to 10$^{-5}$; this parameter affects the shape of the potential at
706   the cut-off. Error estimates due to finite Verlet buffer size are
707   shown for a $1 \times 1$ atom pair list and $4 \times 4$ atom pair
708   list without and with (dashed line) cancellation of positive and
709   negative errors. Real energy drift is shown for simulations using
710   double- and mixed-precision settings. Rounding errors in the SETTLE
711   constraint algorithm from the use of single precision causes
712   the drift to become negative
713   at large buffer size. Note that at zero buffer size, the real drift
714   is small because positive (H-H) and negative (O-H) energy errors
715   cancel.}
716 \label{fig:verletdrift}
717 \end{figure}
718
719 In \figref{verletdrift} one can see that for small buffer sizes the drift
720 of the total energy is much smaller than the pair energy error tolerance,
721 due to cancellation of errors. For larger buffer size, the error estimate
722 is a factor of 6 higher than drift of the total energy, or alternatively
723 the buffer estimate is 0.024 nm too large. This is because the protons
724 don't move freely over 18 fs, but rather vibrate.
725 %At a buffer size of zero there is cancellation of
726 %drift due to repulsive (H-H) and attractive (O-H) interactions.
727
728 \subsubsection{Cut-off artifacts and switched interactions}
729 With the Verlet scheme, the pair potentials are shifted to be zero at
730 the cut-off, which makes the potential the integral of the force.
731 This is only possible in the group scheme if the shape of the potential
732 is such that its value is zero at the cut-off distance.
733 However, there can still be energy drift when the
734 forces are non-zero at the cut-off. This effect is extremely small and
735 often not noticeable, as other integration errors (e.g. from constraints)
736 may dominate. To
737 completely avoid cut-off artifacts, the non-bonded forces can be
738 switched exactly to zero at some distance smaller than the neighbor
739 list cut-off (there are several ways to do this in {\gromacs}, see
740 \secref{mod_nb_int}). One then has a buffer with the size equal to the
741 neighbor list cut-off less the longest interaction cut-off.
742
743
744 \subsubsection{Simple search\swapindexquiet{simple}{search}}
745 Due to \eqnsref{box_rot}{simplerc}, the vector $\rvij$
746 connecting images within the cut-off $R_c$ can be found by constructing:
747 \bea
748 \ve{r}'''   & = & \ve{r}_j-\ve{r}_i \\
749 \ve{r}''    & = & \ve{r}''' - {\bf c}*\verb'round'(r'''_z/c_z) \\
750 \ve{r}'     & = & \ve{r}'' - {\bf b}*\verb'round'(r''_y/b_y) \\
751 \ve{r}_{ij} & = & \ve{r}' - {\bf a}*\verb'round'(r'_x/a_x)
752 \eea
753 When distances between two particles in a triclinic box are needed
754 that do not obey \eqnref{box_rot},
755 many shifts of combinations of box vectors need to be considered to find
756 the nearest image.
757
758
759 \begin{figure}
760 \centerline{\includegraphics[width=8cm]{plots/nstric}}
761 \caption {Grid search in two dimensions. The arrows are the box vectors.}
762 \label{fig:grid}
763 \end{figure}
764
765 \subsubsection{Grid search\swapindexquiet{grid}{search}}
766 \label{sec:nsgrid}
767 The grid search is schematically depicted in \figref{grid}.  All
768 particles are put on the {\nsgrid}, with the smallest spacing $\ge$
769 $R_c/2$ in each of the directions.  In the direction of each box
770 vector, a particle $i$ has three images. For each direction the image
771 may be -1,0 or 1, corresponding to a translation over -1, 0 or +1 box
772 vector. We do not search the surrounding {\nsgrid} cells for neighbors
773 of $i$ and then calculate the image, but rather construct the images
774 first and then search neighbors corresponding to that image of $i$.
775 As \figref{grid} shows, some grid cells may be searched more than once
776 for different images of $i$. This is not a problem, since, due to the
777 minimum image convention, at most one image will ``see'' the
778 $j$-particle.  For every particle, fewer than 125 (5$^3$) neighboring
779 cells are searched.  Therefore, the algorithm scales linearly with the
780 number of particles.  Although the prefactor is large, the scaling
781 behavior makes the algorithm far superior over the standard $O(N^2)$
782 algorithm when there are more than a few hundred particles.  The
783 grid search is equally fast for rectangular and triclinic boxes.  Thus
784 for most protein and peptide simulations the rhombic dodecahedron will
785 be the preferred box shape.
786
787 \subsubsection{Charge groups}
788 \label{sec:chargegroup}\swapindexquiet{charge}{group}%
789 Charge groups were originally introduced to reduce cut-off artifacts
790 of Coulomb interactions. When a plain cut-off is used, significant
791 jumps in the potential and forces arise when atoms with (partial) charges
792 move in and out of the cut-off radius. When all chemical moieties have
793 a net charge of zero, these jumps can be reduced by moving groups
794 of atoms with net charge zero, called charge groups, in and
795 out of the neighbor list. This reduces the cut-off effects from
796 the charge-charge level to the dipole-dipole level, which decay
797 much faster. With the advent of full range electrostatics methods,
798 such as particle-mesh Ewald (\secref{pme}), the use of charge groups is
799 no longer required for accuracy. It might even have a slight negative effect
800 on the accuracy or efficiency, depending on how the neighbor list is made
801 and the interactions are calculated.
802
803 But there is still an important reason for using ``charge groups'': efficiency with the group cut-off scheme.
804 Where applicable, neighbor searching is carried out on the basis of
805 charge groups which are defined in the molecular topology.
806 If the nearest image distance between the {\em
807 geometrical centers} of the atoms of two charge groups is less than
808 the cut-off radius, all atom pairs between the charge groups are
809 included in the pair list.
810 The neighbor searching for a water system, for instance,
811 is $3^2=9$ times faster when each molecule is treated as a charge group.
812 Also the highly optimized water force loops (see \secref{waterloops})
813 only work when all atoms in a water molecule form a single charge group.
814 Currently the name {\em neighbor-search group} would be more appropriate,
815 but the name charge group is retained for historical reasons.
816 When developing a new force field, the advice is to use charge groups
817 of 3 to 4 atoms for optimal performance. For all-atom force fields
818 this is relatively easy, as one can simply put hydrogen atoms, and in some
819 case oxygen atoms, in the same charge group as the heavy atom they
820 are connected to; for example: CH$_3$, CH$_2$, CH, NH$_2$, NH, OH, CO$_2$, CO.
821
822 With the Verlet cut-off scheme, charge groups are ignored.
823
824
825 \subsection{Compute forces}
826 \label{subsec:forces}
827
828 \subsubsection{Potential energy}
829 When forces are computed, the \swapindex{potential}{energy} of each
830 interaction term is computed as well. The total potential energy is
831 summed for various contributions, such as Lennard-Jones, Coulomb, and
832 bonded terms. It is also possible to compute these contributions for
833 {\em energy-monitor groups} of atoms that are separately defined (see
834 \secref{groupconcept}).
835
836 \subsubsection{Kinetic energy and temperature}
837 The \normindex{temperature} is given by the total
838 \swapindex{kinetic}{energy} of the $N$-particle system:
839 \beq
840 E_{kin} = \half \sum_{i=1}^N m_i v_i^2
841 \eeq
842 From this the absolute temperature $T$ can be computed using:
843 \beq
844 \half N_{\mathrm{df}} kT = E_{\mathrm{kin}}
845 \label{eqn:E-T}
846 \eeq
847 where $k$ is Boltzmann's constant and $N_{df}$ is the number of
848 degrees of freedom which can be computed from:
849 \beq
850 N_{\mathrm{df}}  ~=~     3 N - N_c - N_{\mathrm{com}}
851 \eeq
852 Here $N_c$ is the number of {\em \normindex{constraints}} imposed on the system.
853 When performing molecular dynamics $N_{\mathrm{com}}=3$ additional degrees of
854 freedom must be removed, because the three
855 center-of-mass velocities are constants of the motion, which are usually
856 set to zero. When simulating in vacuo, the rotation around the center of mass
857 can also be removed, in this case $N_{\mathrm{com}}=6$.
858 When more than one temperature-coupling group\index{temperature-coupling group} is used, the number of degrees
859 of freedom for group $i$ is:
860 \beq
861 N^i_{\mathrm{df}}  ~=~  (3 N^i - N^i_c) \frac{3 N - N_c - N_{\mathrm{com}}}{3 N - N_c}
862 \eeq
863
864 The kinetic energy can also be written as a tensor, which is necessary
865 for pressure calculation in a triclinic system, or systems where shear
866 forces  are imposed:
867 \beq
868 {\bf E}_{\mathrm{kin}} = \half \sum_i^N m_i \vvi \otimes \vvi
869 \eeq
870
871 \subsubsection{Pressure and virial}
872 The \normindex{pressure} 
873 tensor {\bf P} is calculated from the difference between 
874 kinetic energy $E_{\mathrm{kin}}$ and the \normindex{virial} ${\bf \Xi}$:
875 \beq
876 {\bf P} = \frac{2}{V} ({\bf E}_{\mathrm{kin}}-{\bf \Xi})
877 \label{eqn:P}
878 \eeq
879 where $V$ is the volume of the computational box. 
880 The scalar pressure $P$, which can be used for pressure coupling in the case
881 of isotropic systems, is computed as:
882 \beq
883 P       = {\rm trace}({\bf P})/3
884 \eeq
885
886 The virial ${\bf \Xi}$ tensor is defined as:
887 \beq
888 {\bf \Xi} = -\half \sum_{i<j} \rvij \otimes \Fvij 
889 \label{eqn:Xi}
890 \eeq
891
892 The {\gromacs} implementation of the virial computation is described
893 in \secref{virial}.
894
895 \subsection{The \swapindex{leap-frog}{integrator}}
896 \label{subsec:update}
897 \begin{figure}
898 \centerline{\includegraphics[width=8cm]{plots/leapfrog}}
899 \caption[The Leap-Frog integration method.]{The Leap-Frog integration method. The algorithm is called Leap-Frog because $\ve{r}$ and $\ve{v}$ are leaping
900 like  frogs over each other's backs.}
901 \label{fig:leapfrog}
902 \end{figure}
903
904 The default MD integrator in {\gromacs} is the so-called {\em leap-frog} 
905 algorithm~\cite{Hockney74} for the integration of the equations of
906 motion.  When extremely accurate integration with temperature
907 and/or pressure coupling is required, the velocity Verlet integrators
908 are also present and may be preferable (see \ssecref{vverlet}). The leap-frog
909 algorithm uses positions $\ve{r}$ at time $t$ and
910 velocities $\ve{v}$ at time $t-\hDt$; it updates positions and
911 velocities using the forces
912 $\ve{F}(t)$ determined by the positions at time $t$ using these relations:
913 \bea
914 \label{eqn:leapfrogv}
915 \ve{v}(t+\hDt)  &~=~&   \ve{v}(t-\hDt)+\frac{\Dt}{m}\ve{F}(t)   \\
916 \ve{r}(t+\Dt)   &~=~&   \ve{r}(t)+\Dt\ve{v}(t+\hDt)
917 \eea
918 The algorithm is visualized in \figref{leapfrog}.
919 It produces trajectories that are identical to the Verlet~\cite{Verlet67} algorithm,
920 whose position-update relation is
921 \beq
922 \ve{r}(t+\Dt)~=~2\ve{r}(t) - \ve{r}(t-\Dt) + \frac{1}{m}\ve{F}(t)\Dt^2+O(\Dt^4)
923 \eeq
924 The algorithm is of third order in $\ve{r}$ and is time-reversible.
925 See ref.~\cite{Berendsen86b} for the merits of this algorithm and comparison
926 with other time integration algorithms.
927
928 The \swapindex{equations of}{motion} are modified for temperature
929 coupling and pressure coupling, and extended to include the
930 conservation of constraints, all of which are described below.  
931
932 \subsection{The \swapindex{velocity Verlet}{integrator}}
933 \label{subsec:vverlet}
934 The velocity Verlet algorithm~\cite{Swope82} is also implemented in
935 {\gromacs}, though it is not yet fully integrated with all sets of
936 options.  In velocity Verlet, positions $\ve{r}$ and velocities
937 $\ve{v}$ at time $t$ are used to integrate the equations of motion;
938 velocities at the previous half step are not required.  \bea
939 \label{eqn:velocityverlet1}
940 \ve{v}(t+\hDt)  &~=~&   \ve{v}(t)+\frac{\Dt}{2m}\ve{F}(t)   \\
941 \ve{r}(t+\Dt)   &~=~&   \ve{r}(t)+\Dt\,\ve{v}(t+\hDt) \\
942 \ve{v}(t+\Dt)   &~=~&   \ve{v}(t+\hDt)+\frac{\Dt}{2m}\ve{F}(t+\Dt)
943 \eea
944 or, equivalently,
945 \bea
946 \label{eqn:velocityverlet2}
947 \ve{r}(t+\Dt)   &~=~&   \ve{r}(t)+ \Dt\,\ve{v} + \frac{\Dt^2}{2m}\ve{F}(t) \\
948 \ve{v}(t+\Dt)   &~=~&   \ve{v}(t)+ \frac{\Dt}{2m}\left[\ve{F}(t) + \ve{F}(t+\Dt)\right]
949 \eea
950 With no temperature or pressure coupling, and with {\em corresponding}
951 starting points, leap-frog and velocity Verlet will generate identical
952 trajectories, as can easily be verified by hand from the equations
953 above.  Given a single starting file with the {\em same} starting
954 point $\ve{x}(0)$ and $\ve{v}(0)$, leap-frog and velocity Verlet will
955 {\em not} give identical trajectories, as leap-frog will interpret the
956 velocities as corresponding to $t=-\hDt$, while velocity Verlet will
957 interpret them as corresponding to the timepoint $t=0$.
958
959 \subsection{Understanding reversible integrators: The Trotter decomposition}
960 To further understand the relationship between velocity Verlet and
961 leap-frog integration, we introduce the reversible Trotter formulation
962 of dynamics, which is also useful to understanding implementations of
963 thermostats and barostats in {\gromacs}.
964
965 A system of coupled, first-order differential equations can be evolved
966 from time $t = 0$ to time $t$ by applying the evolution operator
967 \bea
968 \Gamma(t) &=& \exp(iLt) \Gamma(0) \nonumber \\
969 iL &=& \dot{\Gamma}\cdot \nabla_{\Gamma},
970 \eea
971 where $L$ is the Liouville operator, and $\Gamma$ is the
972 multidimensional vector of independent variables (positions and
973 velocities).
974 A short-time approximation to the true operator, accurate at time $\Dt
975 = t/P$, is applied $P$ times in succession to evolve the system as
976 \beq
977 \Gamma(t) = \prod_{i=1}^P \exp(iL\Dt) \Gamma(0)
978 \eeq
979 For NVE dynamics, the Liouville operator is
980 \bea
981 iL = \sum_{i=1}^{N} \vv_i \cdot \nabla_{\rv_i} + \sum_{i=1}^N \frac{1}{m_i}\F(r_i) \cdot \nabla_{\vv_i}.
982 \eea
983 This can be split into two additive operators
984 \bea
985 iL_1 &=& \sum_{i=1}^N \frac{1}{m_i}\F(r_i) \cdot \nabla_{\vv_i} \nonumber \\
986 iL_2 &=& \sum_{i=1}^{N} \vv_i \cdot \nabla_{\rv_i} 
987 \eea
988 Then a short-time, symmetric, and thus reversible approximation of the true dynamics will be
989 \bea
990 \exp(iL\Dt) = \exp(iL_2\hDt) \exp(iL_1\Dt) \exp(iL_2\hDt) + \mathcal{O}(\Dt^3).
991 \label{eq:NVE_Trotter}
992 \eea
993 This corresponds to velocity Verlet integration.  The first
994 exponential term over $\hDt$ corresponds to a velocity half-step, the
995 second exponential term over $\Dt$ corresponds to a full velocity
996 step, and the last exponential term over $\hDt$ is the final velocity
997 half step.  For future times $t = n\Dt$, this becomes
998 \bea
999 \exp(iLn\Dt) &\approx&  \left(\exp(iL_2\hDt) \exp(iL_1\Dt) \exp(iL_2\hDt)\right)^n \nonumber \\
1000              &\approx&  \exp(iL_2\hDt) \bigg(\exp(iL_1\Dt) \exp(iL_2\Dt)\bigg)^{n-1} \nonumber \\
1001              &       &  \;\;\;\; \exp(iL_1\Dt) \exp(iL_2\hDt) 
1002 \eea
1003 This formalism allows us to easily see the difference between the
1004 different flavors of Verlet integrators.  The leap-frog integrator can
1005 be seen as starting with Eq.~\ref{eq:NVE_Trotter} with the
1006 $\exp\left(iL_1 \dt\right)$ term, instead of the half-step velocity
1007 term, yielding
1008 \bea 
1009 \exp(iLn\dt) &=& \exp\left(iL_1 \dt\right) \exp\left(iL_2 \Dt \right) + \mathcal{O}(\Dt^3).
1010 \eea 
1011 Here, the full step in velocity is between $t-\hDt$ and $t+\hDt$,
1012 since it is a combination of the velocity half steps in velocity
1013 Verlet. For future times $t = n\Dt$, this becomes
1014 \bea 
1015 \exp(iLn\dt) &\approx& \bigg(\exp\left(iL_1 \dt\right) \exp\left(iL_2 \Dt \right)  \bigg)^{n}.
1016 \eea 
1017 Although at first this does not appear symmetric, as long as the full velocity
1018 step is between $t-\hDt$ and $t+\hDt$, then this is simply a way of
1019 starting velocity Verlet at a different place in the cycle.
1020
1021 Even though the trajectory and thus potential energies are identical
1022 between leap-frog and velocity Verlet, the kinetic energy and
1023 temperature will not necessarily be the same.  Standard velocity
1024 Verlet uses the velocities at the $t$ to calculate the kinetic energy
1025 and thus the temperature only at time $t$; the kinetic energy is then a sum over all particles
1026 \bea
1027 KE_{\mathrm{full}}(t) &=& \sum_i \left(\frac{1}{2m_i}\ve{v}_i(t)\right)^2 \nonumber\\ 
1028       &=& \sum_i \frac{1}{2m_i}\left(\frac{1}{2}\ve{v}_i(t-\hDt)+\frac{1}{2}\ve{v}_i(t+\hDt)\right)^2,
1029 \eea
1030 with the square on the {\em outside} of the average.  Standard
1031 leap-frog calculates the kinetic energy at time $t$ based on the
1032 average kinetic energies at the timesteps $t+\hDt$ and $t-\hDt$, or
1033 the sum over all particles
1034 \bea
1035 KE_{\mathrm{average}}(t) &=& \sum_i \frac{1}{2m_i}\left(\frac{1}{2}\ve{v}_i(t-\hDt)^2+\frac{1}{2}\ve{v}_i(t+\hDt)^2\right),
1036 \eea
1037 where the square is {\em inside} the average.
1038
1039 A non-standard variant of velocity Verlet which averages the kinetic
1040 energies $KE(t+\hDt)$ and $KE(t-\hDt)$, exactly like leap-frog, is also
1041 now implemented in {\gromacs} (as {\tt .mdp} file option {\tt md-vv-avek}).  Without
1042 temperature and pressure coupling, velocity Verlet with
1043 half-step-averaged kinetic energies and leap-frog will be identical up
1044 to numerical precision.  For temperature- and pressure-control schemes,
1045 however, velocity Verlet with half-step-averaged kinetic energies and
1046 leap-frog will be different, as will be discussed in the section in
1047 thermostats and barostats.
1048
1049 The half-step-averaged kinetic energy and temperature are slightly more
1050 accurate for a given step size; the difference in average kinetic
1051 energies using the half-step-averaged kinetic energies ({\em md} and
1052 {\em md-vv-avek}) will be closer to the kinetic energy obtained in the
1053 limit of small step size than will the full-step kinetic energy (using
1054 {\em md-vv}).  For NVE simulations, this difference is usually not
1055 significant, since the positions and velocities of the particles are
1056 still identical; it makes a difference in the way the the temperature
1057 of the simulations are {\em interpreted}, but {\em not} in the
1058 trajectories that are produced.  Although the kinetic energy is more
1059 accurate with the half-step-averaged method, meaning that it changes
1060 less as the timestep gets large, it is also more noisy.  The RMS deviation
1061 of the total energy of the system (sum of kinetic plus
1062 potential) in the half-step-averaged kinetic energy case will be
1063 higher (about twice as high in most cases) than the full-step kinetic
1064 energy.  The drift will still be the same, however, as again, the
1065 trajectories are identical.
1066
1067 For NVT simulations, however, there {\em will} be a difference, as
1068 discussed in the section on temperature control, since the velocities
1069 of the particles are adjusted such that kinetic energies of the
1070 simulations, which can be calculated either way, reach the
1071 distribution corresponding to the set temperature.  In this case, the
1072 three methods will not give identical results.
1073
1074 Because the velocity and position are both defined at the same time
1075 $t$ the velocity Verlet integrator can be used for some methods,
1076 especially rigorously correct pressure control methods, that are not
1077 actually possible with leap-frog.  The integration itself takes
1078 negligibly more time than leap-frog, but twice as many communication
1079 calls are currently required.  In most cases, and especially for large
1080 systems where communication speed is important for parallelization and
1081 differences between thermodynamic ensembles vanish in the $1/N$ limit,
1082 and when only NVT ensembles are required, leap-frog will likely be the
1083 preferred integrator.  For pressure control simulations where the fine
1084 details of the thermodynamics are important, only velocity Verlet
1085 allows the true ensemble to be calculated.  In either case, simulation
1086 with double precision may be required to get fine details of
1087 thermodynamics correct.
1088
1089 \subsection{Multiple time stepping}
1090 Several other simulation packages uses multiple time stepping for
1091 bonds and/or the PME mesh forces. In {\gromacs} we have not implemented
1092 this (yet), since we use a different philosophy. Bonds can be constrained
1093 (which is also a more sound approximation of a physical quantum
1094 oscillator), which allows the smallest time step to be increased
1095 to the larger one. This not only halves the number of force calculations,
1096 but also the update calculations. For even larger time steps, angle vibrations
1097 involving hydrogen atoms can be removed using virtual interaction
1098 sites (see \secref{rmfast}),
1099 which brings the shortest time step up to
1100 PME mesh update frequency of a multiple time stepping scheme.
1101
1102 \subsection{Temperature coupling\index{temperature coupling}}
1103 While direct use of molecular dynamics gives rise to the NVE (constant
1104 number, constant volume, constant energy ensemble), most quantities
1105 that we wish to calculate are actually from a constant temperature
1106 (NVT) ensemble, also called the canonical ensemble. {\gromacs} can use
1107 the {\em weak-coupling} scheme of Berendsen~\cite{Berendsen84},
1108 stochastic randomization through the Andersen
1109 thermostat~\cite{Andersen80}, the extended ensemble Nos{\'e}-Hoover
1110 scheme~\cite{Nose84,Hoover85}, or a velocity-rescaling
1111 scheme~\cite{Bussi2007a} to simulate constant temperature, with
1112 advantages of each of the schemes laid out below.
1113
1114 There are several other reasons why it might be necessary to control
1115 the temperature of the system (drift during equilibration, drift as a
1116 result of force truncation and integration errors, heating due to
1117 external or frictional forces), but this is not entirely correct to do
1118 from a thermodynamic standpoint, and in some cases only masks the
1119 symptoms (increase in temperature of the system) rather than the
1120 underlying problem (deviations from correct physics in the dynamics).
1121 For larger systems, errors in ensemble averages and structural
1122 properties incurred by using temperature control to remove slow drifts
1123 in temperature appear to be negligible, but no completely
1124 comprehensive comparisons have been carried out, and some caution must
1125 be taking in interpreting the results.
1126
1127 When using temperature and/or pressure coupling the total energy is
1128 no longer conserved. Instead there is a \normindex{conserved energy quantity}
1129 the formula of which will depend on the combination or temperature and
1130 pressure coupling algorithm used. For all coupling algorithms, except
1131 for Andersen temperature coupling and Parrinello-Rahman pressure coupling
1132 combined with shear stress, the conserved energy quantity is computed
1133 and stored in the energy and log file. Note that this quantity will not
1134 be conserved when external forces are applied to the system, such as
1135 pulling on group with a changing distance or an electric field.
1136 Furthermore, how well the energy is conserved depends on the accuracy
1137 of all algorithms involved in the simulation. Usually the algorithms that
1138 cause most drift are constraints and the pair-list buffer, depending
1139 on the parameters used.
1140
1141 \subsubsection{Berendsen temperature coupling\pawsindexquiet{Berendsen}{temperature coupling}\index{weak coupling}}
1142 The Berendsen algorithm mimics weak coupling with first-order 
1143 kinetics to an external heat bath with given temperature $T_0$. 
1144 See ref.~\cite{Berendsen91} for a comparison with the
1145 Nos{\'e}-Hoover scheme. The effect of this algorithm is
1146 that a deviation of the system temperature from $T_0$ is slowly
1147 corrected according to:
1148 \beq
1149 \frac{\de T}{\de t} = \frac{T_0-T}{\tau}
1150 \label{eqn:Tcoupling}
1151 \eeq
1152 which means that a temperature deviation decays exponentially with a
1153 time constant $\tau$.
1154 This method of coupling has the advantage that the strength of the
1155 coupling can be varied and adapted to the user requirement: for
1156 equilibration purposes the coupling time can be taken quite short
1157 ({\eg} 0.01 ps), but for reliable equilibrium runs it can be taken much
1158 longer ({\eg} 0.5 ps) in which case it hardly influences the
1159 conservative dynamics. 
1160
1161 The Berendsen thermostat suppresses the fluctuations of the kinetic
1162 energy.  This means that one does not generate a proper canonical
1163 ensemble, so rigorously, the sampling will be incorrect.  This
1164 error scales with $1/N$, so for very large systems most ensemble
1165 averages will not be affected significantly, except for the
1166 distribution of the kinetic energy itself.  However, fluctuation
1167 properties, such as the heat capacity, will be affected.  A similar
1168 thermostat which does produce a correct ensemble is the velocity
1169 rescaling thermostat~\cite{Bussi2007a} described below.
1170
1171 The heat flow into or out of the system is affected by scaling the
1172 velocities of each particle every step, or every $n_\mathrm{TC}$ steps,
1173 with a time-dependent factor $\lambda$, given by:
1174 \beq 
1175 \lambda = \left[ 1 + \frac{n_\mathrm{TC} \Delta t}{\tau_T}
1176 \left\{\frac{T_0}{T(t -  \hDt)} - 1 \right\} \right]^{1/2}
1177 \label{eqn:lambda}
1178 \eeq
1179 The parameter $\tau_T$ is close, but not exactly equal, to the time constant
1180 $\tau$ of the temperature coupling (\eqnref{Tcoupling}):
1181 \beq
1182 \tau = 2 C_V \tau_T / N_{df} k
1183 \eeq
1184 where $C_V$ is the total heat capacity of the system, $k$ is Boltzmann's
1185 constant, and $N_{df}$ is the total number of degrees of freedom. The
1186 reason that $\tau \neq \tau_T$ is that the kinetic energy change
1187 caused by scaling the velocities is partly redistributed between
1188 kinetic and potential energy and hence the change in temperature is
1189 less than the scaling energy.  In practice, the ratio $\tau / \tau_T$
1190 ranges from 1 (gas) to 2 (harmonic solid) to 3 (water). When we use
1191 the term ``temperature coupling time constant,'' we mean the parameter
1192 \normindex{$\tau_T$}.  
1193 {\bf Note} that in practice the scaling factor $\lambda$ is limited to 
1194 the range of 0.8 $<= \lambda <=$ 1.25, to avoid scaling by very large
1195 numbers which may crash the simulation. In normal use, 
1196 $\lambda$ will always be much closer to 1.0.
1197
1198 The thermostat modifies the kinetic energy at each scaling step by:
1199 \beq
1200 \Delta E_k = (\lambda - 1)^2 E_k
1201 \eeq
1202 The sum of these changes over the run needs to subtracted from the total energy
1203 to obtain the conserved energy quantity.
1204
1205 \subsubsection{Velocity-rescaling temperature coupling\pawsindexquiet{velocity-rescaling}{temperature coupling}}
1206 The velocity-rescaling thermostat~\cite{Bussi2007a} is essentially a Berendsen
1207 thermostat (see above) with an additional stochastic term that ensures
1208 a correct kinetic energy distribution by modifying it according to
1209 \beq
1210 \de K = (K_0 - K) \frac{\de t}{\tau_T} + 2 \sqrt{\frac{K K_0}{N_f}} \frac{\de W}{\sqrt{\tau_T}},
1211 \label{eqn:vrescale}
1212 \eeq
1213 where $K$ is the kinetic energy, $N_f$ the number of degrees of freedom and $\de W$ a Wiener process.
1214 There are no additional parameters, except for a random seed.
1215 This thermostat produces a correct canonical ensemble and still has
1216 the advantage of the Berendsen thermostat: first order decay of
1217 temperature deviations and no oscillations.
1218
1219 \subsubsection{\normindex{Andersen thermostat}}
1220 One simple way to maintain a thermostatted ensemble is to take an
1221 $NVE$ integrator and periodically re-select the velocities of the
1222 particles from a Maxwell-Boltzmann distribution.~\cite{Andersen80}
1223 This can either be done by randomizing all the velocities
1224 simultaneously (massive collision) every $\tau_T/\Dt$ steps ({\tt andersen-massive}), or by
1225 randomizing every particle with some small probability every timestep ({\tt andersen}),
1226 equal to $\Dt/\tau$, where in both cases $\Dt$ is the timestep and
1227 $\tau_T$ is a characteristic coupling time scale.
1228 Because of the way constraints operate, all particles in the same
1229 constraint group must be randomized simultaneously.  Because of
1230 parallelization issues, the {\tt andersen} version cannot currently (5.0) be
1231 used in systems with constraints. {\tt andersen-massive} can be used regardless of constraints.
1232 This thermostat is also currently only possible with velocity Verlet algorithms,
1233 because it operates directly on the velocities at each timestep.
1234
1235 This algorithm completely avoids some of the ergodicity issues of other thermostatting
1236 algorithms, as energy cannot flow back and forth between energetically
1237 decoupled components of the system as in velocity scaling motions.
1238 However, it can slow down the kinetics of system by randomizing
1239 correlated motions of the system, including slowing sampling when
1240 $\tau_T$ is at moderate levels (less than 10 ps). This algorithm
1241 should therefore generally not be used when examining kinetics or
1242 transport properties of the system.~\cite{Basconi2013}
1243
1244 \subsubsection{Nos{\'e}-Hoover temperature coupling\index{Nose-Hoover temperature coupling@Nos{\'e}-Hoover temperature coupling|see{temperature coupling, Nos{\'e}-Hoover}}{\index{temperature coupling Nose-Hoover@temperature coupling Nos{\'e}-Hoover}}\index{extended ensemble}}
1245
1246 The Berendsen weak-coupling algorithm is
1247 extremely efficient for relaxing a system to the target temperature,
1248 but once the system has reached equilibrium it might be more
1249 important to probe a correct canonical ensemble. This is unfortunately
1250 not the case for the weak-coupling scheme.
1251
1252 To enable canonical ensemble simulations, {\gromacs} also supports the
1253 extended-ensemble approach first proposed by Nos{\'e}~\cite{Nose84}
1254 and later modified by Hoover~\cite{Hoover85}. The system Hamiltonian is
1255 extended by introducing a thermal reservoir and a friction term in the
1256 equations of motion.  The friction force is proportional to the
1257 product of each particle's velocity and a friction parameter, $\xi$.
1258 This friction parameter (or ``heat bath'' variable) is a fully
1259 dynamic quantity with its own momentum ($p_{\xi}$) and equation of
1260 motion; the time derivative is calculated from the difference between
1261 the current kinetic energy and the reference temperature.  
1262
1263 In this formulation, the particles' equations of motion in
1264 \figref{global} are replaced by:
1265 \beq
1266 \frac {\de^2\ve{r}_i}{\de t^2} = \frac{\ve{F}_i}{m_i} - 
1267 \frac{p_{\xi}}{Q}\frac{\de \ve{r}_i}{\de t} ,
1268 \label{eqn:NH-eqn-of-motion}
1269 \eeq where the equation of motion for the heat bath parameter $\xi$ is:
1270 \beq \frac {\de p_{\xi}}{\de t} = \left( T - T_0 \right).  \eeq The
1271 reference temperature is denoted $T_0$, while $T$ is the current
1272 instantaneous temperature of the system. The strength of the coupling
1273 is determined by the constant $Q$ (usually called the ``mass parameter''
1274 of the reservoir) in combination with the reference
1275 temperature.~\footnote{Note that some derivations, an alternative
1276   notation $\xi_{\mathrm{alt}} = v_{\xi} = p_{\xi}/Q$ is used.}
1277
1278 The conserved quantity for the Nos{\'e}-Hoover equations of motion is not 
1279 the total energy, but rather
1280 \bea
1281 H = \sum_{i=1}^{N} \frac{\pb_i}{2m_i} + U\left(\rv_1,\rv_2,\ldots,\rv_N\right) +\frac{p_{\xi}^2}{2Q} + N_fkT\xi,
1282 \eea
1283 where $N_f$ is the total number of degrees of freedom.
1284
1285 In our opinion, the mass parameter is a somewhat awkward way of
1286 describing coupling strength, especially due to its dependence on
1287 reference temperature (and some implementations even include the
1288 number of degrees of freedom in your system when defining $Q$).  To
1289 maintain the coupling strength, one would have to change $Q$ in
1290 proportion to the change in reference temperature. For this reason, we
1291 prefer to let the {\gromacs} user work instead with the period
1292 $\tau_T$ of the oscillations of kinetic energy between the system and
1293 the reservoir instead. It is directly related to $Q$ and $T_0$ via:
1294 \beq
1295 Q = \frac {\tau_T^2 T_0}{4 \pi^2}.
1296 \eeq
1297 This provides a much more intuitive way of selecting the
1298 Nos{\'e}-Hoover coupling strength (similar to the weak-coupling
1299 relaxation), and in addition $\tau_T$ is independent of system size
1300 and reference temperature.
1301
1302 It is however important to keep the difference between the 
1303 weak-coupling scheme and the Nos{\'e}-Hoover algorithm in mind: 
1304 Using weak coupling you get a
1305 strongly damped {\em exponential relaxation}, 
1306 while the Nos{\'e}-Hoover approach
1307 produces an {\em oscillatory relaxation}. 
1308 The actual time it takes to relax with Nos{\'e}-Hoover coupling is 
1309 several times larger than the period of the
1310 oscillations that you select. These oscillations (in contrast
1311 to exponential relaxation) also means that
1312 the time constant normally should be 4--5 times larger
1313 than the relaxation time used with weak coupling, but your 
1314 mileage may vary.
1315
1316 Nos{\'e}-Hoover dynamics in simple systems such as collections of
1317 harmonic oscillators, can be {\em nonergodic}, meaning that only a
1318 subsection of phase space is ever sampled, even if the simulations
1319 were to run for infinitely long.  For this reason, the Nos{\'e}-Hoover
1320 chain approach was developed, where each of the Nos{\'e}-Hoover
1321 thermostats has its own Nos{\'e}-Hoover thermostat controlling its
1322 temperature.  In the limit of an infinite chain of thermostats, the
1323 dynamics are guaranteed to be ergodic. Using just a few chains can
1324 greatly improve the ergodicity, but recent research has shown that the
1325 system will still be nonergodic, and it is still not entirely clear
1326 what the practical effect of this~\cite{Cooke2008}. Currently, the
1327 default number of chains is 10, but this can be controlled by the
1328 user.  In the case of chains, the equations are modified in the
1329 following way to include a chain of thermostatting
1330 particles~\cite{Martyna1992}:
1331
1332 \bea
1333 \frac {\de^2\ve{r}_i}{\de t^2} &~=~& \frac{\ve{F}_i}{m_i} - \frac{p_{{\xi}_1}}{Q_1} \frac{\de \ve{r}_i}{\de t} \nonumber \\
1334 \frac {\de p_{{\xi}_1}}{\de t} &~=~& \left( T - T_0 \right) - p_{{\xi}_1} \frac{p_{{\xi}_2}}{Q_2} \nonumber \\
1335 \frac {\de p_{{\xi}_{i=2\ldots N}}}{\de t} &~=~& \left(\frac{p_{\xi_{i-1}}^2}{Q_{i-1}} -kT\right) - p_{\xi_i} \frac{p_{\xi_{i+1}}}{Q_{i+1}} \nonumber \\
1336 \frac {\de p_{\xi_N}}{\de t} &~=~& \left(\frac{p_{\xi_{N-1}}^2}{Q_{N-1}}-kT\right)
1337 \label{eqn:NH-chain-eqn-of-motion}
1338 \eea
1339 The conserved quantity for Nos{\'e}-Hoover chains is
1340 \bea
1341 H = \sum_{i=1}^{N} \frac{\pb_i}{2m_i} + U\left(\rv_1,\rv_2,\ldots,\rv_N\right) +\sum_{k=1}^M\frac{p^2_{\xi_k}}{2Q^{\prime}_k} + N_fkT\xi_1 + kT\sum_{k=2}^M \xi_k 
1342 \eea
1343 The values and velocities of the Nos{\'e}-Hoover thermostat variables
1344 are generally not included in the output, as they take up a fair
1345 amount of space and are generally not important for analysis of
1346 simulations, but this can be overridden by defining the environment
1347 variable {\tt GMX_NOSEHOOVER_CHAINS}, which will print the values of all
1348 the positions and velocities of all Nos{\'e}-Hoover particles in the
1349 chain to the {\tt .edr} file.  Leap-frog simulations currently can only have 
1350 Nos{\'e}-Hoover chain lengths of 1, but this will likely be updated in 
1351 later version.
1352
1353 As described in the integrator section, for temperature coupling, the
1354 temperature that the algorithm attempts to match to the reference
1355 temperature is calculated differently in velocity Verlet and leap-frog
1356 dynamics.  Velocity Verlet ({\em md-vv}) uses the full-step kinetic
1357 energy, while leap-frog and {\em md-vv-avek} use the half-step-averaged
1358 kinetic energy.
1359
1360 We can examine the Trotter decomposition again to better understand
1361 the differences between these constant-temperature integrators.  In
1362 the case of Nos{\'e}-Hoover dynamics (for simplicity, using a chain
1363 with $N=1$, with more details in Ref.~\cite{Martyna1996}), we split
1364 the Liouville operator as
1365 \beq
1366 iL = iL_1 + iL_2 + iL_{\mathrm{NHC}},
1367 \eeq
1368 where
1369 \bea
1370 iL_1 &=& \sum_{i=1}^N \left[\frac{\pb_i}{m_i}\right]\cdot \frac{\partial}{\partial \rv_i} \nonumber \\
1371 iL_2 &=& \sum_{i=1}^N \F_i\cdot \frac{\partial}{\partial \pb_i} \nonumber \\
1372 iL_{\mathrm{NHC}} &=& \sum_{i=1}^N-\frac{p_{\xi}}{Q}\vv_i\cdot \nabla_{\vv_i} +\frac{p_{\xi}}{Q}\frac{\partial }{\partial \xi} + \left( T - T_0 \right)\frac{\partial }{\partial p_{\xi}}
1373 \eea
1374 For standard velocity Verlet with Nos{\'e}-Hoover temperature control, this becomes
1375 \bea  
1376 \exp(iL\dt) &=& \exp\left(iL_{\mathrm{NHC}}\dt/2\right) \exp\left(iL_2 \dt/2\right) \nonumber \\
1377 &&\exp\left(iL_1 \dt\right) \exp\left(iL_2 \dt/2\right) \exp\left(iL_{\mathrm{NHC}}\dt/2\right) + \mathcal{O}(\Dt^3).
1378 \eea
1379 For half-step-averaged temperature control using {\em md-vv-avek},
1380 this decomposition will not work, since we do not have the full step
1381 temperature until after the second velocity step.  However, we can
1382 construct an alternate decomposition that is still reversible, by
1383 switching the place of the NHC and velocity portions of the
1384 decomposition:
1385 \bea  
1386 \exp(iL\dt) &=& \exp\left(iL_2 \dt/2\right) \exp\left(iL_{\mathrm{NHC}}\dt/2\right)\exp\left(iL_1 \dt\right)\nonumber \\
1387 &&\exp\left(iL_{\mathrm{NHC}}\dt/2\right) \exp\left(iL_2 \dt/2\right)+ \mathcal{O}(\Dt^3)
1388 \label{eq:half_step_NHC_integrator}
1389 \eea
1390 This formalism allows us to easily see the difference between the
1391 different flavors of velocity Verlet integrator.  The leap-frog
1392 integrator can be seen as starting with
1393 Eq.~\ref{eq:half_step_NHC_integrator} just before the $\exp\left(iL_1
1394 \dt\right)$ term, yielding:
1395 \bea  
1396 \exp(iL\dt) &=&  \exp\left(iL_1 \dt\right) \exp\left(iL_{\mathrm{NHC}}\dt/2\right) \nonumber \\
1397 &&\exp\left(iL_2 \dt\right) \exp\left(iL_{\mathrm{NHC}}\dt/2\right) + \mathcal{O}(\Dt^3)
1398 \eea
1399 and then using some algebra tricks to solve for some quantities are
1400 required before they are actually calculated~\cite{Holian95}.
1401
1402
1403 \subsubsection{Group temperature coupling}\index{temperature-coupling group}%
1404 In {\gromacs} temperature coupling can be performed on groups of
1405 atoms, typically a protein and solvent. The reason such algorithms
1406 were introduced is that energy exchange between different components
1407 is not perfect, due to different effects including cut-offs etc. If
1408 now the whole system is coupled to one heat bath, water (which
1409 experiences the largest cut-off noise) will tend to heat up and the
1410 protein will cool down. Typically 100 K differences can be obtained.
1411 With the use of proper electrostatic methods (PME) these difference
1412 are much smaller but still not negligible.  The parameters for
1413 temperature coupling in groups are given in the {\tt mdp} file.
1414 Recent investigation has shown that small temperature differences
1415 between protein and water may actually be an artifact of the way
1416 temperature is calculated when there are finite timesteps, and very
1417 large differences in temperature are likely a sign of something else
1418 seriously going wrong with the system, and should be investigated
1419 carefully~\cite{Eastwood2010}.
1420
1421 One special case should be mentioned: it is possible to temperature-couple only
1422 part of the system, leaving other parts without temperature
1423 coupling. This is done by specifying ${-1}$ for the time constant
1424 $\tau_T$ for the group that should not be thermostatted.  If only
1425 part of the system is thermostatted, the system will still eventually
1426 converge to an NVT system.  In fact, one suggestion for minimizing
1427 errors in the temperature caused by discretized timesteps is that if
1428 constraints on the water are used, then only the water degrees of
1429 freedom should be thermostatted, not protein degrees of freedom, as
1430 the higher frequency modes in the protein can cause larger deviations
1431 from the ``true'' temperature, the temperature obtained with small
1432 timesteps~\cite{Eastwood2010}.
1433
1434 \subsection{Pressure coupling\index{pressure coupling}}
1435 In the same spirit as the temperature coupling, the system can also be
1436 coupled to a ``pressure bath.'' {\gromacs} supports both the Berendsen
1437 algorithm~\cite{Berendsen84} that scales coordinates and box vectors
1438 every step, the extended-ensemble Parrinello-Rahman approach~\cite{Parrinello81,Nose83}, and for
1439 the velocity Verlet variants, the Martyna-Tuckerman-Tobias-Klein
1440 (MTTK) implementation of pressure
1441 control~\cite{Martyna1996}. Parrinello-Rahman and Berendsen can be
1442 combined with any of the temperature coupling methods above. MTTK can
1443 only be used with Nos{\'e}-Hoover temperature control. From 5.1 afterwards,
1444 it can only used when the system does not have constraints.
1445
1446 \subsubsection{Berendsen pressure coupling\pawsindexquiet{Berendsen}{pressure coupling}\index{weak coupling}}
1447 \label{sec:berendsen_pressure_coupling}
1448 The Berendsen algorithm rescales the 
1449 coordinates and box vectors every step, or every $n_\mathrm{PC}$ steps,
1450  with a matrix {\boldmath $\mu$},
1451 which has the effect of a first-order kinetic relaxation of the pressure
1452 towards a given reference pressure ${\bf P}_0$ according to
1453 \beq
1454 \frac{\de {\bf P}}{\de t} = \frac{{\bf P}_0-{\bf P}}{\tau_p}.
1455 \eeq
1456 The scaling matrix {\boldmath $\mu$} is given by
1457 \beq
1458 \mu_{ij}
1459 = \delta_{ij} - \frac{n_\mathrm{PC}\Delta t}{3\, \tau_p} \beta_{ij} \{P_{0ij} - P_{ij}(t) \}.
1460 \label{eqn:mu}
1461 \eeq
1462 \index{isothermal compressibility}
1463 \index{compressibility}
1464 Here, {\boldmath $\beta$} is the isothermal compressibility of the system.
1465 In most cases this will be a diagonal matrix, with equal elements on the
1466 diagonal, the value of which is generally not known.
1467 It suffices to take a rough estimate because the value of {\boldmath $\beta$}
1468 only influences the non-critical time constant of the
1469 pressure relaxation without affecting the average pressure itself.
1470 For water at 1 atm and 300 K 
1471 $\beta = 4.6 \times 10^{-10}$ Pa$^{-1} = 4.6 \times 10^{-5}$ bar$^{-1}$,
1472 which is $7.6 \times 10^{-4}$ MD units (see \chref{defunits}).
1473 Most other liquids have similar values.
1474 When scaling completely anisotropically, the system has to be rotated in
1475 order to obey \eqnref{box_rot}.
1476 This rotation is approximated in first order in the scaling, which is usually
1477 less than $10^{-4}$. The actual scaling matrix {\boldmath $\mu'$} is
1478 \beq
1479 \mbox{\boldmath $\mu'$} = 
1480 \left(\begin{array}{ccc}
1481 \mu_{xx} & \mu_{xy} + \mu_{yx} & \mu_{xz} + \mu_{zx} \\
1482 0        & \mu_{yy}            & \mu_{yz} + \mu_{zy} \\
1483 0        & 0                   & \mu_{zz}
1484 \end{array}\right).
1485 \eeq
1486 The velocities are neither scaled nor rotated.
1487 Since the equations of motion are modified by pressure coupling, the conserved
1488 energy quantity also needs to be modified. For first order pressure coupling,
1489 the work the barostat applies to the system every step needs to
1490 be subtracted from the total energy to obtain the conserved energy quantity:
1491 \beq
1492 - \sum_{i,j} (\mu_{ij} -\delta_{ij}) P_{ij} V =
1493 \sum_{i,j} 2(\mu_{ij} -\delta_{ij}) \Xi_{ij}
1494 \eeq
1495 where $\delta_{ij}$ is the Kronecker delta and  ${\bf \Xi}$ is the virial.
1496 Note that the factor 2 originates from the factor $\frac{1}{2}$
1497 in the virial definition (\eqnref{Xi}).
1498
1499
1500 In {\gromacs}, the Berendsen scaling can also be done isotropically, 
1501 which means that instead of $\ve{P}$ a diagonal matrix with elements of size
1502 trace$(\ve{P})/3$ is used. For systems with interfaces, semi-isotropic 
1503 scaling can be useful.
1504 In this case, the $x/y$-directions are scaled isotropically and the $z$
1505 direction is scaled independently. The compressibility in the $x/y$ or
1506 $z$-direction can be set to zero, to scale only in the other direction(s).
1507
1508 If you allow full anisotropic deformations and use constraints you
1509 might have to scale more slowly or decrease your timestep to avoid
1510 errors from the constraint algorithms.  It is important to note that
1511 although the Berendsen pressure control algorithm yields a simulation
1512 with the correct average pressure, it does not yield the exact NPT
1513 ensemble, and it is not yet clear exactly what errors this approximation
1514 may yield.
1515
1516 \subsubsection{Parrinello-Rahman pressure coupling\pawsindexquiet{Parrinello-Rahman}{pressure coupling}}
1517
1518 In cases where the fluctuations in pressure or volume are important
1519 {\em per se} ({\eg} to calculate thermodynamic properties), especially
1520 for small systems, it may be a problem that the exact ensemble is not
1521 well defined for the weak-coupling scheme, and that it does not
1522 simulate the true NPT ensemble.
1523
1524 {\gromacs} also supports constant-pressure simulations using the
1525 Parrinello-Rahman approach~\cite{Parrinello81,Nose83}, which is similar
1526 to the Nos{\'e}-Hoover temperature coupling, and in theory gives the
1527 true NPT ensemble.  With the Parrinello-Rahman barostat, the box
1528 vectors as represented by the matrix \ve{b} obey the matrix equation
1529 of motion\footnote{The box matrix representation \ve{b} in {\gromacs}
1530 corresponds to the transpose of the box matrix representation \ve{h}
1531 in the paper by Nos{\'e} and Klein. Because of this, some of our
1532 equations will look slightly different.}
1533 \beq
1534 \frac{\de \ve{b}^2}{\de t^2}= V \ve{W}^{-1} \ve{b}'^{-1} \left( \ve{P} - \ve{P}_{ref}\right).
1535 \eeq
1536
1537 The volume of the box is denoted $V$, and $\ve{W}$ is a matrix parameter that determines
1538 the strength of the coupling. The matrices \ve{P} and \ve{P}$_{ref}$ are the 
1539 current and reference pressures, respectively.
1540
1541 The equations of motion for the particles are also changed, just as
1542 for the Nos{\'e}-Hoover coupling. In most cases you would combine the 
1543 Parrinello-Rahman barostat with the Nos{\'e}-Hoover
1544 thermostat, but to keep it simple we only show the Parrinello-Rahman 
1545 modification here. The modified Hamiltonian, which will be conserved, is:
1546 \beq
1547 E_\mathrm{pot} + E_\mathrm{kin} +  \sum_i P_{ii} V +
1548 \sum_{i,j} \frac{1}{2} W_{ij}  \left( \frac{\de b_{ij}}{\de t} \right)^2
1549 \eeq
1550 The equations of motion for the atoms, obtained from the Hamiltonian are:
1551 \bea \frac {\de^2\ve{r}_i}{\de t^2} & = & \frac{\ve{F}_i}{m_i} -
1552 \ve{M} \frac{\de \ve{r}_i}{\de t} , \\ \ve{M} & = & \ve{b}^{-1} \left[
1553   \ve{b} \frac{\de \ve{b}'}{\de t} + \frac{\de \ve{b}}{\de t} \ve{b}'
1554   \right] \ve{b}'^{-1}.  \eea The (inverse) mass parameter matrix
1555 $\ve{W}^{-1}$ determines the strength of the coupling, and how the box
1556 can be deformed.  The box restriction (\ref{eqn:box_rot}) will be
1557 fulfilled automatically if the corresponding elements of $\ve{W}^{-1}$
1558 are zero. Since the coupling strength also depends on the size of your
1559 box, we prefer to calculate it automatically in {\gromacs}.  You only
1560 have to provide the approximate isothermal compressibilities
1561 {\boldmath $\beta$} and the pressure time constant $\tau_p$ in the
1562 input file ($L$ is the largest box matrix element): \beq \left(
1563 \ve{W}^{-1} \right)_{ij} = \frac{4 \pi^2 \beta_{ij}}{3 \tau_p^2 L}.
1564 \eeq Just as for the Nos{\'e}-Hoover thermostat, you should realize
1565 that the Parrinello-Rahman time constant is {\em not} equivalent to
1566 the relaxation time used in the Berendsen pressure coupling algorithm.
1567 In most cases you will need to use a 4--5 times larger time constant
1568 with Parrinello-Rahman coupling. If your pressure is very far from
1569 equilibrium, the Parrinello-Rahman coupling may result in very large
1570 box oscillations that could even crash your run.  In that case you
1571 would have to increase the time constant, or (better) use the weak-coupling
1572 scheme to reach the target pressure, and then switch to
1573 Parrinello-Rahman coupling once the system is in equilibrium.
1574 Additionally, using the leap-frog algorithm, the pressure at time $t$
1575 is not available until after the time step has completed, and so the
1576 pressure from the previous step must be used, which makes the algorithm
1577 not directly reversible, and may not be appropriate for high precision
1578 thermodynamic calculations.
1579
1580 \subsubsection{Surface-tension coupling\pawsindexquiet{surface-tension}{pressure coupling}}
1581 When a periodic system consists of more than one phase, separated by
1582 surfaces which are parallel to the $xy$-plane,
1583 the surface tension and the $z$-component of the pressure can be coupled
1584 to a pressure bath. Presently, this only works with the Berendsen
1585 pressure coupling algorithm in {\gromacs}.
1586 The average surface tension $\gamma(t)$ can be calculated from
1587 the difference between the normal and the lateral pressure
1588 \bea
1589 \gamma(t) & = & 
1590 \frac{1}{n} \int_0^{L_z}
1591 \left\{ P_{zz}(z,t) - \frac{P_{xx}(z,t) + P_{yy}(z,t)}{2} \right\} \mbox{d}z \\
1592 & = &
1593 \frac{L_z}{n} \left\{ P_{zz}(t) - \frac{P_{xx}(t) + P_{yy}(t)}{2} \right\},
1594 \eea
1595 where $L_z$ is the height of the box and $n$ is the number of surfaces.
1596 The pressure in the z-direction is corrected by scaling the height of
1597 the box with $\mu_{zz}$
1598 \beq
1599 \Delta P_{zz} = \frac{\Delta t}{\tau_p} \{ P_{0zz} - P_{zz}(t) \}
1600 \eeq
1601 \beq
1602 \mu_{zz} = 1 + \beta_{zz} \Delta P_{zz}
1603 \eeq
1604 This is similar to normal pressure coupling, except that the factor
1605 of $1/3$ is missing. 
1606 The pressure correction in the $z$-direction is then used to get the
1607 correct convergence for the surface tension to the reference value $\gamma_0$.
1608 The correction factor for the box length in the $x$/$y$-direction is
1609 \beq
1610 \mu_{x/y} = 1 + \frac{\Delta t}{2\,\tau_p} \beta_{x/y}
1611         \left( \frac{n \gamma_0}{\mu_{zz} L_z}
1612         - \left\{ P_{zz}(t)+\Delta P_{zz} - \frac{P_{xx}(t) + P_{yy}(t)}{2} \right\} 
1613         \right)
1614 \eeq
1615 The value of $\beta_{zz}$ is more critical than with normal pressure
1616 coupling. Normally an incorrect compressibility will just scale $\tau_p$,
1617 but with surface tension coupling it affects the convergence of the surface
1618 tension. 
1619 When $\beta_{zz}$ is set to zero (constant box height), $\Delta P_{zz}$ is also set
1620 to zero, which is necessary for obtaining the correct surface tension. 
1621
1622 \subsubsection{MTTK pressure control algorithms}
1623
1624 As mentioned in the previous section, one weakness of leap-frog
1625 integration is in constant pressure simulations, since the pressure
1626 requires a calculation of both the virial and the kinetic energy at
1627 the full time step; for leap-frog, this information is not available
1628 until {\em after} the full timestep.  Velocity Verlet does allow the
1629 calculation, at the cost of an extra round of global communication,
1630 and can compute, mod any integration errors, the true NPT ensemble.
1631
1632 The full equations, combining both pressure coupling and temperature
1633 coupling, are taken from Martyna {\em et al.}~\cite{Martyna1996} and
1634 Tuckerman~\cite{Tuckerman2006} and are referred to here as MTTK
1635 equations (Martyna-Tuckerman-Tobias-Klein).  We introduce for
1636 convenience $\epsilon = (1/3)\ln (V/V_0)$, where $V_0$ is a reference
1637 volume.  The momentum of $\epsilon$ is $\veps = p_{\epsilon}/W =
1638 \dot{\epsilon} = \dot{V}/3V$, and define $\alpha = 1 + 3/N_{dof}$ (see
1639 Ref~\cite{Tuckerman2006})
1640
1641 The isobaric equations are
1642 \bea
1643 \dot{\rv}_i &=& \frac{\pb_i}{m_i} + \frac{\peps}{W} \rv_i \nonumber \\
1644 \frac{\dot{\pb}_i}{m_i} &=& \frac{1}{m_i}\F_i - \alpha\frac{\peps}{W} \frac{\pb_i}{m_i} \nonumber \\
1645 \dot{\epsilon} &=& \frac{\peps}{W} \nonumber \\
1646 \frac{\dot{\peps}}{W} &=& \frac{3V}{W}(P_{\mathrm{int}} - P) + (\alpha-1)\left(\sum_{n=1}^N\frac{\pb_i^2}{m_i}\right),\\
1647 \eea
1648 where
1649 \bea
1650 P_{\mathrm{int}} &=& P_{\mathrm{kin}} -P_{\mathrm{vir}} = \frac{1}{3V}\left[\sum_{i=1}^N \left(\frac{\pb_i^2}{2m_i} - \rv_i \cdot \F_i\
1651 \right)\right].
1652 \eea
1653 The terms including $\alpha$ are required to make phase space
1654 incompressible~\cite{Tuckerman2006}. The $\epsilon$ acceleration term
1655 can be rewritten as
1656 \bea
1657 \frac{\dot{\peps}}{W} &=& \frac{3V}{W}\left(\alpha P_{\mathrm{kin}} - P_{\mathrm{vir}} - P\right)
1658 \eea
1659 In terms of velocities, these equations become
1660 \bea
1661 \dot{\rv}_i &=& \vv_i + \veps \rv_i \nonumber \\
1662 \dot{\vv}_i &=& \frac{1}{m_i}\F_i - \alpha\veps \vv_i \nonumber \\
1663 \dot{\epsilon} &=& \veps \nonumber \\
1664 \dot{\veps} &=& \frac{3V}{W}(P_{\mathrm{int}} - P) + (\alpha-1)\left( \sum_{n=1}^N \frac{1}{2} m_i \vv_i^2\right)\nonumber \\
1665 P_{\mathrm{int}} &=& P_{\mathrm{kin}} - P_{\mathrm{vir}} = \frac{1}{3V}\left[\sum_{i=1}^N \left(\frac{1}{2} m_i\vv_i^2 - \rv_i \cdot \F_i\right)\right]
1666 \eea
1667 For these equations, the conserved quantity is
1668 \bea
1669 H = \sum_{i=1}^{N} \frac{\pb_i^2}{2m_i} + U\left(\rv_1,\rv_2,\ldots,\rv_N\right) + \frac{p_\epsilon}{2W} + PV
1670 \eea
1671 The next step is to add temperature control.  Adding Nos{\'e}-Hoover
1672 chains, including to the barostat degree of freedom, where we use
1673 $\eta$ for the barostat Nos{\'e}-Hoover variables, and $Q^{\prime}$
1674 for the coupling constants of the thermostats of the barostats, we get
1675 \bea
1676 \dot{\rv}_i &=& \frac{\pb_i}{m_i} + \frac{\peps}{W} \rv_i \nonumber \\
1677 \frac{\dot{\pb}_i}{m_i} &=& \frac{1}{m_i}\F_i - \alpha\frac{\peps}{W} \frac{\pb_i}{m_i} - \frac{p_{\xi_1}}{Q_1}\frac{\pb_i}{m_i}\nonumber \\
1678 \dot{\epsilon} &=& \frac{\peps}{W} \nonumber \\
1679 \frac{\dot{\peps}}{W} &=& \frac{3V}{W}(\alpha P_{\mathrm{kin}} - P_{\mathrm{vir}} - P) -\frac{p_{\eta_1}}{Q^{\prime}_1}\peps \nonumber \\
1680 \dot{\xi}_k &=& \frac{p_{\xi_k}}{Q_k} \nonumber \\ 
1681 \dot{\eta}_k &=& \frac{p_{\eta_k}}{Q^{\prime}_k} \nonumber \\
1682 \dot{p}_{\xi_k} &=& G_k - \frac{p_{\xi_{k+1}}}{Q_{k+1}} \;\;\;\; k=1,\ldots, M-1 \nonumber \\ 
1683 \dot{p}_{\eta_k} &=& G^\prime_k - \frac{p_{\eta_{k+1}}}{Q^\prime_{k+1}} \;\;\;\; k=1,\ldots, M-1 \nonumber \\
1684 \dot{p}_{\xi_M} &=& G_M \nonumber \\
1685 \dot{p}_{\eta_M} &=& G^\prime_M, \nonumber \\
1686 \eea
1687 where
1688 \bea
1689 P_{\mathrm{int}} &=& P_{\mathrm{kin}} - P_{\mathrm{vir}} = \frac{1}{3V}\left[\sum_{i=1}^N \left(\frac{\pb_i^2}{2m_i} - \rv_i \cdot \F_i\right)\right] \nonumber \\
1690 G_1  &=& \sum_{i=1}^N \frac{\pb^2_i}{m_i} - N_f kT \nonumber \\
1691 G_k  &=&  \frac{p^2_{\xi_{k-1}}}{2Q_{k-1}} - kT \;\; k = 2,\ldots,M \nonumber \\
1692 G^\prime_1 &=& \frac{\peps^2}{2W} - kT \nonumber \\
1693 G^\prime_k &=& \frac{p^2_{\eta_{k-1}}}{2Q^\prime_{k-1}} - kT \;\; k = 2,\ldots,M
1694 \eea
1695 The conserved quantity is now
1696 \bea
1697 H = \sum_{i=1}^{N} \frac{\pb_i}{2m_i} + U\left(\rv_1,\rv_2,\ldots,\rv_N\right) + \frac{p^2_\epsilon}{2W} + PV + \nonumber \\
1698 \sum_{k=1}^M\frac{p^2_{\xi_k}}{2Q_k} +\sum_{k=1}^M\frac{p^2_{\eta_k}}{2Q^{\prime}_k} + N_fkT\xi_1 +  kT\sum_{i=2}^M \xi_k + kT\sum_{k=1}^M \eta_k
1699 \eea
1700 Returning to the Trotter decomposition formalism, for pressure control and temperature control~\cite{Martyna1996} we get:
1701 \bea
1702 iL = iL_1 + iL_2 + iL_{\epsilon,1} + iL_{\epsilon,2} + iL_{\mathrm{NHC-baro}} + iL_{\mathrm{NHC}}
1703 \eea
1704 where ``NHC-baro'' corresponds to the Nos{\`e}-Hoover chain of the barostat,
1705 and NHC corresponds to the NHC of the particles,
1706 \bea
1707 iL_1 &=& \sum_{i=1}^N \left[\frac{\pb_i}{m_i} + \frac{\peps}{W}\rv_i\right]\cdot \frac{\partial}{\partial \rv_i} \\
1708 iL_2 &=& \sum_{i=1}^N \F_i - \alpha \frac{\peps}{W}\pb_i \cdot \frac{\partial}{\partial \pb_i} \\
1709 iL_{\epsilon,1} &=& \frac{p_\epsilon}{W} \frac{\partial}{\partial \epsilon}\\
1710 iL_{\epsilon,2} &=& G_{\epsilon} \frac{\partial}{\partial p_\epsilon}
1711 \eea
1712 and where
1713 \bea
1714 G_{\epsilon} = 3V\left(\alpha P_{\mathrm{kin}} - P_{\mathrm{vir}} - P\right)
1715 \eea 
1716 Using the Trotter decomposition, we get
1717 \bea  
1718 \exp(iL\dt) &=& \exp\left(iL_{\mathrm{NHC-baro}}\dt/2\right)\exp\left(iL_{\mathrm{NHC}}\dt/2\right) \nonumber \nonumber \\
1719 &&\exp\left(iL_{\epsilon,2}\dt/2\right) \exp\left(iL_2 \dt/2\right) \nonumber \nonumber \\
1720 &&\exp\left(iL_{\epsilon,1}\dt\right) \exp\left(iL_1 \dt\right) \nonumber \nonumber \\
1721 &&\exp\left(iL_2 \dt/2\right) \exp\left(iL_{\epsilon,2}\dt/2\right) \nonumber \nonumber \\
1722 &&\exp\left(iL_{\mathrm{NHC}}\dt/2\right)\exp\left(iL_{\mathrm{NHC-baro}}\dt/2\right) + \mathcal{O}(\dt^3)
1723 \eea
1724 The action of $\exp\left(iL_1 \dt\right)$ comes from the solution of
1725 the the differential equation 
1726 $\dot{\rv}_i = \vv_i + \veps \rv_i$
1727 with $\vv_i = \pb_i/m_i$ and $\veps$ constant with initial condition
1728 $\rv_i(0)$, evaluate at $t=\Delta t$.  This yields the evolution
1729 \beq
1730 \rv_i(\dt) = \rv_i(0)e^{\veps \dt} + \Delta t \vv_i(0) e^{\veps \dt/2} \sinhx{\veps \dt/2}.
1731 \eeq
1732 The action of $\exp\left(iL_2 \dt/2\right)$ comes from the solution
1733 of the differential equation $\dot{\vv}_i = \frac{\F_i}{m_i} -
1734 \alpha\veps\vv_i$, yielding
1735 \beq
1736 \vv_i(\dt/2) = \vv_i(0)e^{-\alpha\veps \dt/2} + \frac{\Delta t}{2m_i}\F_i(0) e^{-\alpha\veps \dt/4}\sinhx{\alpha\veps \dt/4}.
1737 \eeq
1738 {\em md-vv-avek} uses the full step kinetic energies for determining the pressure with the pressure control,
1739 but the half-step-averaged kinetic energy for the temperatures, which can be written as a Trotter decomposition as
1740 \bea  
1741 \exp(iL\dt) &=& \exp\left(iL_{\mathrm{NHC-baro}}\dt/2\right)\nonumber \exp\left(iL_{\epsilon,2}\dt/2\right) \exp\left(iL_2 \dt/2\right) \nonumber \\
1742 &&\exp\left(iL_{\mathrm{NHC}}\dt/2\right) \exp\left(iL_{\epsilon,1}\dt\right) \exp\left(iL_1 \dt\right) \exp\left(iL_{\mathrm{NHC}}\dt/2\right) \nonumber \\
1743 &&\exp\left(iL_2 \dt/2\right) \exp\left(iL_{\epsilon,2}\dt/2\right) \exp\left(iL_{\mathrm{NHC-baro}}\dt/2\right) + \mathcal{O}(\dt^3)
1744 \eea
1745
1746 With constraints, the equations become significantly more complicated,
1747 in that each of these equations need to be solved iteratively for the
1748 constraint forces. Before {\gromacs} 5.1, these iterative
1749 constraints were solved as described in~\cite{Yu2010}. From {\gromacs}
1750 5.1 onward, MTTK with constraints has been removed because of
1751 numerical stability issues with the iterations.
1752
1753 \subsubsection{Infrequent evaluation of temperature and pressure coupling}
1754
1755 Temperature and pressure control require global communication to
1756 compute the kinetic energy and virial, which can become costly if
1757 performed every step for large systems.  We can rearrange the Trotter
1758 decomposition to give alternate symplectic, reversible integrator with
1759 the coupling steps every $n$ steps instead of every steps.  These new
1760 integrators will diverge if the coupling time step is too large, as
1761 the auxiliary variable integrations will not converge.  However, in
1762 most cases, long coupling times are more appropriate, as they disturb
1763 the dynamics less~\cite{Martyna1996}.
1764
1765 Standard velocity Verlet with Nos{\'e}-Hoover temperature control has a Trotter expansion
1766 \bea  
1767 \exp(iL\dt) &\approx& \exp\left(iL_{\mathrm{NHC}}\dt/2\right) \exp\left(iL_2 \dt/2\right) \nonumber \\
1768 &&\exp\left(iL_1 \dt\right) \exp\left(iL_2 \dt/2\right) \exp\left(iL_{\mathrm{NHC}}\dt/2\right).
1769 \eea
1770 If the Nos{\'e}-Hoover chain is sufficiently slow with respect to the motions of the system, we can
1771 write an alternate integrator over $n$ steps for velocity Verlet as
1772 \bea  
1773 \exp(iL\dt) &\approx& (\exp\left(iL_{\mathrm{NHC}}(n\dt/2)\right)\left[\exp\left(iL_2 \dt/2\right)\right. \nonumber \\
1774 &&\left.\exp\left(iL_1 \dt\right) \exp\left(iL_2 \dt/2\right)\right]^n \exp\left(iL_{\mathrm{NHC}}(n\dt/2)\right).
1775 \eea
1776 For pressure control, this becomes
1777 \bea  
1778 \exp(iL\dt) &\approx& \exp\left(iL_{\mathrm{NHC-baro}}(n\dt/2)\right)\exp\left(iL_{\mathrm{NHC}}(n\dt/2)\right) \nonumber \nonumber \\
1779 &&\exp\left(iL_{\epsilon,2}(n\dt/2)\right) \left[\exp\left(iL_2 \dt/2\right)\right. \nonumber \nonumber \\
1780 &&\exp\left(iL_{\epsilon,1}\dt\right) \exp\left(iL_1 \dt\right) \nonumber \nonumber \\
1781 &&\left.\exp\left(iL_2 \dt/2\right)\right]^n \exp\left(iL_{\epsilon,2}(n\dt/2)\right) \nonumber \nonumber \\
1782 &&\exp\left(iL_{\mathrm{NHC}}(n\dt/2)\right)\exp\left(iL_{\mathrm{NHC-baro}}(n\dt/2)\right),
1783 \eea
1784 where the box volume integration occurs every step, but the auxiliary variable
1785 integrations happen every $n$ steps.
1786
1787
1788
1789 \subsection{The complete update algorithm}
1790 \begin{figure}
1791 \begin{center}
1792 \addtolength{\fboxsep}{0.5cm}
1793 \begin{shadowenv}[12cm]
1794 {\large \bf THE UPDATE ALGORITHM}
1795 \rule{\textwidth}{2pt} \\
1796 Given:\\
1797 Positions $\ve{r}$ of all atoms at time $t$ \\
1798 Velocities $\ve{v}$ of all atoms at time $t-\hDt$ \\
1799 Accelerations $\ve{F}/m$ on all atoms at time $t$.\\
1800 (Forces are computed disregarding any constraints)\\
1801 Total kinetic energy and virial at $t-\Dt$\\
1802 $\Downarrow$ \\
1803 {\bf 1.} Compute the scaling factors $\lambda$ and $\mu$\\
1804 according to \eqnsref{lambda}{mu}\\   
1805 $\Downarrow$ \\
1806 {\bf 2.} Update and scale velocities: $\ve{v}' =  \lambda (\ve{v} +
1807 \ve{a} \Delta t)$ \\
1808 $\Downarrow$ \\
1809 {\bf 3.} Compute new unconstrained coordinates: $\ve{r}' = \ve{r} + \ve{v}'
1810 \Delta t$ \\
1811 $\Downarrow$ \\
1812 {\bf 4.} Apply constraint algorithm to coordinates: constrain($\ve{r}^{'} \rightarrow  \ve{r}'';
1813 \,  \ve{r}$) \\
1814 $\Downarrow$ \\
1815 {\bf 5.} Correct velocities for constraints: $\ve{v} = (\ve{r}'' -
1816 \ve{r}) / \Delta t$ \\
1817 $\Downarrow$ \\
1818 {\bf 6.} Scale coordinates and box: $\ve{r} = \mu \ve{r}''; \ve{b} =
1819 \mu  \ve{b}$ \\
1820 \end{shadowenv}
1821 \caption{The MD update algorithm with the leap-frog integrator}
1822 \label{fig:complete-update}
1823 \end{center}
1824 \end{figure}
1825 The complete algorithm for the update of velocities and coordinates is
1826 given using leap-frog in \figref{complete-update}. The SHAKE algorithm of step
1827 4 is explained below. 
1828
1829 {\gromacs} has a provision to ``freeze''  (prevent motion of) selected
1830 particles\index{frozen atoms}, which must be defined as a ``\swapindex{freeze}{group}.'' This is implemented
1831 using a {\em freeze factor $\ve{f}_g$}, which is a vector, and differs for each
1832 freeze group (see \secref{groupconcept}). This vector contains only
1833 zero (freeze) or one (don't freeze).
1834 When we take this freeze factor and the external acceleration $\ve{a}_h$ into 
1835 account the update algorithm for the velocities becomes
1836 \beq
1837 \ve{v}(t+\hdt)~=~\ve{f}_g * \lambda * \left[ \ve{v}(t-\hdt) +\frac{\ve{F}(t)}{m}\Delta t + \ve{a}_h \Delta t \right],
1838 \eeq
1839 where $g$ and $h$ are group indices which differ per atom.
1840
1841 \subsection{Output step}
1842 The most important output of the MD run is the {\em
1843 \swapindex{trajectory}{file}}, which contains particle coordinates
1844 and (optionally) velocities at regular intervals.
1845 The trajectory file contains frames that could include positions,
1846 velocities and/or forces, as well as information about the dimensions
1847 of the simulation volume, integration step, integration time, etc. The
1848 interpretation of the time varies with the integrator chosen, as
1849 described above. For Velocity Verlet integrators, velocities labeled
1850 at time $t$ are for that time. For other integrators (e.g. leap-frog,
1851 stochastic dynamics), the velocities labeled at time $t$ are for time
1852 $t - \hDt$.
1853
1854 Since the trajectory
1855 files are lengthy, one should not save every step! To retain all
1856 information it suffices to write a frame every 15 steps, since at
1857 least 30 steps are made per period of the highest frequency in the
1858 system, and Shannon's \normindex{sampling} theorem states that two samples per
1859 period of the highest frequency in a band-limited signal contain all
1860 available information. But that still gives very long files! So, if
1861 the highest frequencies are not of interest, 10 or 20 samples per ps
1862 may suffice. Be aware of the distortion of high-frequency motions by
1863 the {\em stroboscopic effect}, called {\em aliasing}: higher frequencies
1864 are  mirrored with respect to the sampling frequency and appear as
1865 lower frequencies.
1866
1867 {\gromacs} can also write reduced-precision coordinates for a subset of
1868 the simulation system to a special compressed trajectory file
1869 format. All the other tools can read and write this format. See
1870 the User Guide for details on how to set up your {\tt .mdp} file
1871 to have {\tt mdrun} use this feature.
1872
1873 \section{Shell molecular dynamics}
1874 {\gromacs} can simulate \normindex{polarizability} using the 
1875 \normindex{shell model} of Dick and Overhauser~\cite{Dick58}. In such models
1876 a shell particle representing the electronic degrees of freedom is
1877 attached to a nucleus by a spring. The potential energy is minimized with
1878 respect to the shell position  at every step of the simulation (see below).
1879 Successful applications of shell models in {\gromacs} have been published
1880 for $N_2$~\cite{Jordan95} and water~\cite{Maaren2001a}.
1881
1882 \subsection{Optimization of the shell positions}
1883 The force \ve{F}$_S$ on a shell particle $S$ can be decomposed into two
1884 components
1885 \begin{equation}
1886 \ve{F}_S ~=~ \ve{F}_{bond} + \ve{F}_{nb}
1887 \end{equation}
1888 where \ve{F}$_{bond}$ denotes the component representing the
1889 polarization energy, usually represented by a harmonic potential and
1890 \ve{F}$_{nb}$ is the sum of Coulomb and van der Waals interactions. If we
1891 assume that \ve{F}$_{nb}$ is almost constant we can analytically derive the
1892 optimal position of the shell, i.e. where \ve{F}$_S$ = 0. If we have the
1893 shell S connected to atom A we have
1894 \begin{equation}
1895 \ve{F}_{bond} ~=~ k_b \left( \ve{x}_S - \ve{x}_A\right).
1896 \end{equation}
1897 In an iterative solver, we have positions \ve{x}$_S(n)$ where $n$ is
1898 the iteration count. We now have at iteration $n$
1899 \begin{equation}
1900 \ve{F}_{nb} ~=~ \ve{F}_S - k_b \left( \ve{x}_S(n) - \ve{x}_A\right)
1901 \end{equation}
1902 and the optimal position for the shells $x_S(n+1)$ thus follows from
1903 \begin{equation}
1904 \ve{F}_S - k_b \left( \ve{x}_S(n) - \ve{x}_A\right) + k_b \left( \ve{x}_S(n+1) - \ve{x}_A\right) = 0
1905 \end{equation}
1906 if we write
1907 \begin{equation}
1908 \Delta \ve{x}_S = \ve{x}_S(n+1) - \ve{x}_S(n)
1909 \end{equation}
1910 we finally obtain
1911 \begin{equation}
1912 \Delta \ve{x}_S = \ve{F}_S/k_b
1913 \end{equation}
1914 which then yields the algorithm to compute the next trial in the optimization
1915 of shell positions
1916 \begin{equation}
1917 \ve{x}_S(n+1) ~=~ \ve{x}_S(n) + \ve{F}_S/k_b.
1918 \end{equation}
1919
1920 \section{Constraint algorithms\index{constraint algorithms}}
1921 Constraints can be imposed in {\gromacs} using LINCS (default) or
1922 the traditional SHAKE method.
1923
1924 \subsection{\normindex{SHAKE}}
1925 \label{subsec:SHAKE}
1926 The SHAKE~\cite{Ryckaert77} algorithm changes a set of unconstrained
1927 coordinates $\ve{r}^{'}$ to a set of coordinates $\ve{r}''$ that
1928 fulfill a  list of distance constraints, using a set $\ve{r}$
1929 reference, as
1930 \beq
1931 {\rm SHAKE}(\ve{r}^{'} \rightarrow \ve{r}'';\, \ve{r})
1932 \eeq
1933 This action is consistent with solving a set of Lagrange multipliers
1934 in the constrained equations of motion. SHAKE needs a {\em relative tolerance};
1935 it will continue until all constraints are satisfied within
1936 that relative tolerance. An error message is
1937 given if SHAKE cannot reset the coordinates because the deviation is
1938 too large, or if a given number of iterations is surpassed. 
1939
1940 Assume the equations of motion must fulfill $K$ holonomic constraints,
1941 expressed as
1942 \beq
1943 \sigma_k(\ve{r}_1 \ldots \ve{r}_N) = 0; \;\; k=1 \ldots K.
1944 \eeq
1945 For example, $(\ve{r}_1 - \ve{r}_2)^2 - b^2 = 0$.
1946 Then the forces are defined as
1947 \beq
1948 - \frac{\partial}{\partial \ve{r}_i} \left( V + \sum_{k=1}^K \lambda_k
1949 \sigma_k \right),
1950 \eeq
1951 where $\lambda_k$ are Lagrange multipliers which must be solved to
1952 fulfill the constraint equations. The second part of this sum
1953 determines the {\em constraint forces} $\ve{G}_i$, defined by
1954 \beq
1955 \ve{G}_i = -\sum_{k=1}^K \lambda_k \frac{\partial \sigma_k}{\partial
1956 \ve{r}_i}
1957 \eeq
1958 The displacement due to the constraint forces in the leap-frog or
1959 Verlet algorithm is equal to $(\ve{G}_i/m_i)(\Dt)^2$. Solving the
1960 Lagrange multipliers (and hence the displacements) requires the
1961 solution of a set of coupled equations of the second degree. These are
1962 solved iteratively by SHAKE.
1963 \label{subsec:SETTLE}
1964 For the special case of rigid water molecules, that often make up more
1965 than 80\% of the simulation system we have implemented the 
1966 \normindex{SETTLE}
1967 algorithm~\cite{Miyamoto92} (\secref{constraints}).
1968
1969 For velocity Verlet, an additional round of constraining must be
1970 done, to constrain the velocities of the second velocity half step,
1971 removing any component of the velocity parallel to the bond vector.
1972 This step is called RATTLE, and is covered in more detail in the
1973 original Andersen paper~\cite{Andersen1983a}.
1974
1975
1976
1977
1978
1979 \newcommand{\fs}[1]{\begin{equation} \label{eqn:#1}}
1980 \newcommand{\fe}{\end{equation}}
1981 \newcommand{\p}{\partial}
1982 \newcommand{\Bm}{\ve{B}}
1983 \newcommand{\M}{\ve{M}}
1984 \newcommand{\iM}{\M^{-1}}
1985 \newcommand{\Tm}{\ve{T}}
1986 \newcommand{\Sm}{\ve{S}}
1987 \newcommand{\fo}{\ve{f}}
1988 \newcommand{\con}{\ve{g}}
1989 \newcommand{\lenc}{\ve{d}}
1990
1991 \subsection{\normindex{LINCS}}
1992 \label{subsec:lincs}
1993
1994 \subsubsection{The LINCS algorithm}
1995 LINCS is an algorithm that resets bonds to their correct lengths
1996 after an unconstrained update~\cite{Hess97}. 
1997 The method is non-iterative, as it always uses two steps.
1998 Although LINCS is based on matrices, no matrix-matrix multiplications are 
1999 needed. The method is more stable and faster than SHAKE, 
2000 but it can only be used with bond constraints and 
2001 isolated angle constraints, such as the proton angle in OH. 
2002 Because of its stability, LINCS is especially useful for Brownian dynamics. 
2003 LINCS has two parameters, which are explained in the subsection parameters.
2004 The parallel version of LINCS, P-LINCS, is described
2005 in subsection \ssecref{plincs}.
2006  
2007 \subsubsection{The LINCS formulas}
2008 We consider a system of $N$ particles, with positions given by a
2009 $3N$ vector $\ve{r}(t)$.
2010 For molecular dynamics the equations of motion are given by Newton's Law
2011 \fs{c1}
2012 {\de^2 \ve{r} \over \de t^2} = \iM \ve{F},
2013 \fe
2014 where $\ve{F}$ is the $3N$ force vector 
2015 and $\M$ is a $3N \times 3N$ diagonal matrix,
2016 containing the masses of the particles.
2017 The system is constrained by $K$ time-independent constraint equations
2018 \fs{c2}
2019 g_i(\ve{r}) = | \ve{r}_{i_1}-\ve{r}_{i_2} | - d_i = 0 ~~~~~~i=1,\ldots,K.
2020 \fe
2021
2022 In a numerical integration scheme, LINCS is applied after an
2023 unconstrained update, just like SHAKE. The algorithm works in two
2024 steps (see figure \figref{lincs}). In the first step, the projections
2025 of the new bonds on the old bonds are set to zero. In the second step,
2026 a correction is applied for the lengthening of the bonds due to
2027 rotation. The numerics for the first step and the second step are very
2028 similar. A complete derivation of the algorithm can be found in
2029 \cite{Hess97}. Only a short description of the first step is given
2030 here.
2031
2032 \begin{figure}
2033 \centerline{\includegraphics[height=50mm]{plots/lincs}}
2034 \caption[The three position updates needed for one time step.]{The
2035 three position updates needed for one time step. The dashed line is
2036 the old bond of length $d$, the solid lines are the new bonds. $l=d
2037 \cos \theta$ and $p=(2 d^2 - l^2)^{1 \over 2}$.}
2038 \label{fig:lincs}
2039 \end{figure}
2040
2041 A new notation is introduced for the gradient matrix of the constraint 
2042 equations which appears on the right hand side of this equation:
2043 \fs{c3}
2044 B_{hi} = {\p g_h \over \p r_i}
2045 \fe
2046 Notice that $\Bm$ is a $K \times 3N$ matrix, it contains the directions
2047 of the constraints.
2048 The following equation shows how the new constrained coordinates 
2049 $\ve{r}_{n+1}$ are related to the unconstrained coordinates
2050 $\ve{r}_{n+1}^{unc}$ by
2051 \fs{m0}
2052 \begin{array}{c}
2053   \ve{r}_{n+1}=(\ve{I}-\Tm_n \ve{B}_n) \ve{r}_{n+1}^{unc} + \Tm_n \lenc=  
2054   \\[2mm]
2055   \ve{r}_{n+1}^{unc} - 
2056 \iM \Bm_n (\Bm_n \iM \Bm_n^T)^{-1} (\Bm_n \ve{r}_{n+1}^{unc} - \lenc) 
2057 \end{array}
2058 \fe
2059 where $\Tm = \iM \Bm^T (\Bm \iM \Bm^T)^{-1}$.
2060 The derivation of this equation from \eqnsref{c1}{c2} can be found
2061 in \cite{Hess97}.
2062
2063 This first step does not set the real bond lengths to the prescribed lengths,
2064 but the projection of the new bonds onto the old directions of the bonds.
2065 To correct for the rotation of bond $i$, the projection of the
2066 bond, $p_i$, on the old direction is set to
2067 \fs{m1a}
2068 p_i=\sqrt{2 d_i^2 - l_i^2},
2069 \fe
2070 where $l_i$ is the bond length after the first projection.
2071 The corrected positions are
2072 \fs{m1b}
2073 \ve{r}_{n+1}^*=(\ve{I}-\Tm_n \Bm_n)\ve{r}_{n+1} + \Tm_n \ve{p}.
2074 \fe
2075 This correction for rotational effects is actually an iterative process,
2076 but during MD only one iteration is applied.
2077 The relative constraint deviation after this procedure will be less than
2078 0.0001 for every constraint.
2079 In energy minimization, this might not be accurate enough, so the number
2080 of iterations is equal to the order of the expansion (see below).
2081
2082 Half of the CPU time goes to inverting the constraint coupling 
2083 matrix $\Bm_n \iM \Bm_n^T$, which has to be done every time step.
2084 This $K \times K$ matrix
2085 has $1/m_{i_1} + 1/m_{i_2}$ on the diagonal.
2086 The off-diagonal elements are only non-zero when two bonds are connected,
2087 then the element is 
2088 $\cos \phi /m_c$,  where $m_c$ is 
2089 the mass of the atom connecting the
2090 two bonds and $\phi$ is the angle between the bonds.
2091
2092 The matrix $\Tm$ is inverted through a power expansion.
2093 A $K \times K$ matrix $\ve{S}$ is 
2094 introduced which is the inverse square root of 
2095 the diagonal of $\Bm_n \iM \Bm_n^T$.
2096 This matrix is used to convert the diagonal elements 
2097 of the coupling matrix to one:
2098 \fs{m2}
2099 \begin{array}{c}
2100 (\Bm_n \iM \Bm_n^T)^{-1}
2101 = \Sm \Sm^{-1} (\Bm_n \iM \Bm_n^T)^{-1} \Sm^{-1} \Sm  \\[2mm]
2102 = \Sm (\Sm \Bm_n \iM \Bm_n^T \Sm)^{-1} \Sm =
2103   \Sm (\ve{I} - \ve{A}_n)^{-1} \Sm
2104 \end{array}
2105 \fe
2106 The matrix $\ve{A}_n$ is symmetric and sparse and has zeros on the diagonal.
2107 Thus a simple trick can be used to calculate the inverse:
2108 \fs{m3}
2109 (\ve{I}-\ve{A}_n)^{-1}= 
2110         \ve{I} + \ve{A}_n + \ve{A}_n^2 + \ve{A}_n^3 + \ldots
2111 \fe
2112
2113 This inversion method is only valid if the absolute values of all the
2114 eigenvalues of $\ve{A}_n$ are smaller than one.
2115 In molecules with only bond constraints, the connectivity is so low
2116 that this will always be true, even if ring structures are present.
2117 Problems can arise in angle-constrained molecules.
2118 By constraining angles with additional distance constraints,
2119 multiple small ring structures are introduced.
2120 This gives a high connectivity, leading to large eigenvalues.
2121 Therefore LINCS should NOT be used with coupled angle-constraints.
2122
2123 For molecules with all bonds constrained the eigenvalues of $A$
2124 are around 0.4. This means that with each additional order
2125 in the expansion \eqnref{m3} the deviations decrease by a factor 0.4.
2126 But for relatively isolated triangles of constraints the largest
2127 eigenvalue is around 0.7.
2128 Such triangles can occur when removing hydrogen angle vibrations
2129 with an additional angle constraint in alcohol groups
2130 or when constraining water molecules with LINCS, for instance
2131 with flexible constraints.
2132 The constraints in such triangles converge twice as slow as
2133 the other constraints. Therefore, starting with {\gromacs} 4,
2134 additional terms are added to the expansion for such triangles
2135 \fs{m3_ang}
2136 (\ve{I}-\ve{A}_n)^{-1} \approx
2137         \ve{I} + \ve{A}_n + \ldots + \ve{A}_n^{N_i} +
2138         \left(\ve{A}^*_n + \ldots + {\ve{A}_n^*}^{N_i} \right) \ve{A}_n^{N_i}
2139 \fe
2140 where $N_i$ is the normal order of the expansion and
2141 $\ve{A}^*$ only contains the elements of $\ve{A}$ that couple
2142 constraints within rigid triangles, all other elements are zero.
2143 In this manner, the accuracy of angle constraints comes close
2144 to that of the other constraints, while the series of matrix vector
2145 multiplications required for determining the expansion
2146 only needs to be extended for a few constraint couplings.
2147 This procedure is described in the P-LINCS paper\cite{Hess2008a}.
2148
2149 \subsubsection{The LINCS Parameters}
2150 The accuracy of LINCS depends on the number of matrices used
2151 in the expansion \eqnref{m3}. For MD calculations a fourth order
2152 expansion is enough. For Brownian dynamics with
2153 large time steps an eighth order expansion may be necessary.
2154 The order is a parameter in the {\tt *.mdp} file.
2155 The implementation of LINCS is done in such a way that the 
2156 algorithm will never crash. Even when it is impossible to
2157 to reset the constraints LINCS will generate a conformation
2158 which fulfills the constraints as well as possible.
2159 However, LINCS will generate a warning when in one step a bond 
2160 rotates over more than a predefined angle.
2161 This angle is set by the user in the {\tt *.mdp} file.
2162
2163
2164
2165 \section{Simulated Annealing}
2166 \label{sec:SA}
2167 The well known \swapindex{simulated}{annealing}
2168 (SA) protocol is supported in {\gromacs}, and you can even couple multiple
2169 groups of atoms separately with an arbitrary number of reference temperatures
2170 that change during the simulation. The annealing is implemented by simply 
2171 changing the current reference temperature for each group in the temperature
2172 coupling, so the actual relaxation and coupling properties depends on the
2173 type of thermostat you use and how hard you are coupling it. Since we are
2174 changing the reference temperature it is important to remember that the system
2175 will NOT instantaneously reach this value - you need to allow for the inherent
2176 relaxation time in the coupling algorithm too. If you are changing the 
2177 annealing reference temperature faster than the temperature relaxation you
2178 will probably end up with a crash when the difference becomes too large.
2179
2180 The annealing protocol is specified as a series of corresponding times and 
2181 reference temperatures for each group, and you can also choose whether you only
2182 want a single sequence (after which the temperature will be coupled to the 
2183 last reference value), or if the annealing should be periodic and restart at 
2184 the first reference point once the sequence is completed. You can mix and
2185 match both types of annealing and non-annealed groups in your simulation.
2186
2187 \newcommand{\vrond}{\stackrel{\circ}{\ve{r}}}
2188 \newcommand{\rond}{\stackrel{\circ}{r}}
2189 \newcommand{\ruis}{\ve{r}^G}
2190
2191 \section{Stochastic Dynamics\swapindexquiet{stochastic}{dynamics}}
2192 \label{sec:SD}
2193 Stochastic or velocity \swapindex{Langevin}{dynamics} adds a friction
2194 and a noise term to Newton's equations of motion, as
2195 \beq
2196 \label{SDeq}
2197 m_i {\de^2 \ve{r}_i \over \de t^2} =
2198 - m_i \gamma_i {\de \ve{r}_i \over \de t} + \ve{F}_i(\ve{r}) + \vrond_i,
2199 \eeq 
2200 where $\gamma_i$ is the friction constant $[1/\mbox{ps}]$ and
2201 $\vrond_i\!\!(t)$  is a noise process with 
2202 $\langle \rond_i\!\!(t) \rond_j\!\!(t+s) \rangle = 
2203     2 m_i \gamma_i k_B T \delta(s) \delta_{ij}$.
2204 When $1/\gamma_i$ is large compared to the time scales present in the system,
2205 one could see stochastic dynamics as molecular dynamics with stochastic
2206 temperature-coupling. The advantage compared to MD with Berendsen
2207 temperature-coupling is that in case of SD the generated ensemble is known.
2208 For simulating a system in vacuum there is the additional advantage that there is no
2209 accumulation of errors for the overall translational and rotational
2210 degrees of freedom.
2211 When $1/\gamma_i$ is small compared to the time scales present in the system,
2212 the dynamics will be completely different from MD, but the sampling is
2213 still correct.
2214
2215 In {\gromacs} there is one simple and efficient implementation. Its
2216 accuracy is equivalent to the normal MD leap-frog and
2217 Velocity Verlet integrator. It is nearly identical to the common way of discretizing the Langevin equation, but the friction and velocity term are applied in an impulse fashion~\cite{Goga2012}.
2218 It can be described as:
2219 \bea
2220 \label{eqn:sd_int1}
2221 \ve{v}'  &~=~&   \ve{v}(t-\hDt) + \frac{1}{m}\ve{F}(t)\Dt \\
2222 \Delta\ve{v}     &~=~&   -\alpha \, \ve{v}'(t+\hDt) + \sqrt{\frac{k_B T}{m}(1 - \alpha^2)} \, \ruis_i \\
2223 \ve{r}(t+\Dt)   &~=~&   \ve{r}(t)+\left(\ve{v}' +\frac{1}{2}\Delta \ve{v}\right)\Dt \label{eqn:sd1_x_upd}\\
2224 \ve{v}(t+\hDt)  &~=~&   \ve{v}' + \Delta \ve{v} \\
2225 \alpha &~=~& 1 - e^{-\gamma \Dt}
2226 \eea
2227 where $\ruis_i$ is Gaussian distributed noise with $\mu = 0$, $\sigma = 1$.
2228 The velocity is first updated a full time step without friction and noise to get $\ve{v}'$, identical to the normal update in leap-frog. The friction and noise are then applied as an impulse at step $t+\Dt$. The advantage of this scheme is that the velocity-dependent terms act at the full time step, which makes the correct integration of forces that depend on both coordinates and velocities, such as constraints and dissipative particle dynamics (DPD, not implented yet), straightforward. With constraints, the coordinate update \eqnref{sd1_x_upd} is split into a normal leap-frog update and a $\Delta \ve{v}$. After both of these updates the constraints are applied to coordinates and velocities.
2229
2230 When using SD as a thermostat, an appropriate value for $\gamma$ is e.g. 0.5 ps$^{-1}$,
2231 since this results in a friction that is lower than the internal friction
2232 of water, while it still provides efficient thermostatting.
2233
2234
2235 \section{Brownian Dynamics\swapindexquiet{Brownian}{dynamics}}
2236 \label{sec:BD}
2237 In the limit of high friction, stochastic dynamics reduces to 
2238 Brownian dynamics, also called position Langevin dynamics.
2239 This applies to over-damped systems, 
2240 {\ie} systems in which the inertia effects are negligible.
2241 The equation is
2242 \beq
2243 {\de \ve{r}_i \over \de t} = \frac{1}{\gamma_i} \ve{F}_i(\ve{r}) + \vrond_i
2244 \eeq 
2245 where $\gamma_i$ is the friction coefficient $[\mbox{amu/ps}]$ and
2246 $\vrond_i\!\!(t)$  is a noise process with 
2247 $\langle \rond_i\!\!(t) \rond_j\!\!(t+s) \rangle = 
2248     2 \delta(s) \delta_{ij} k_B T / \gamma_i$.
2249 In {\gromacs} the equations are integrated with a simple, explicit scheme
2250 \beq
2251 \ve{r}_i(t+\Delta t) = \ve{r}_i(t) +
2252         {\Delta t \over \gamma_i} \ve{F}_i(\ve{r}(t)) 
2253         + \sqrt{2 k_B T {\Delta t \over \gamma_i}}\, \ruis_i,
2254 \eeq
2255 where $\ruis_i$ is Gaussian distributed noise with $\mu = 0$, $\sigma = 1$.
2256 The friction coefficients $\gamma_i$ can be chosen the same for all
2257 particles or as $\gamma_i = m_i\,\gamma_i$, where the friction constants
2258 $\gamma_i$ can be different for different groups of atoms. 
2259 Because the system is assumed to be over-damped, large timesteps
2260 can be used. LINCS should be used for the constraints since SHAKE
2261 will not converge for large atomic displacements.
2262 BD is an option of the {\tt mdrun} program.
2263
2264 \section{Energy Minimization}
2265 \label{sec:EM}\index{energy minimization}%
2266 Energy minimization in {\gromacs} can be done using steepest descent,
2267 conjugate gradients, or l-bfgs (limited-memory
2268 Broyden-Fletcher-Goldfarb-Shanno quasi-Newtonian minimizer...we
2269 prefer the abbreviation). EM is just an option of the {\tt mdrun}
2270 program.
2271
2272 \subsection{Steepest Descent\index{steepest descent}}
2273 Although steepest descent is certainly not the most efficient
2274 algorithm for searching, it is robust and easy to implement.
2275
2276 We define the vector $\ve{r}$ as the vector of all $3N$ coordinates.
2277 Initially a maximum displacement $h_0$ ({\eg} 0.01 nm) must be given. 
2278
2279 First the forces $\ve{F}$ and potential energy are calculated.
2280 New positions are calculated by
2281 \beq
2282 \ve{r}_{n+1} =  \ve{r}_n + \frac{\ve{F}_n}{\max (|\ve{F}_n|)} h_n,
2283 \eeq
2284 where $h_n$ is the maximum displacement and $\ve{F}_n$ is the force,
2285 or the negative gradient of the  potential $V$. The notation $\max
2286 (|\ve{F}_n|)$ means the largest scalar force on any atom.
2287 The forces and energy are again computed for the new positions \\
2288 If ($V_{n+1} < V_n$) the new positions are accepted and $h_{n+1} = 1.2
2289 h_n$. \\
2290 If ($V_{n+1} \geq V_n$) the new positions are rejected and $h_n = 0.2 h_n$.
2291
2292 The algorithm stops when either a user-specified number of force 
2293 evaluations has been performed ({\eg} 100), or when the maximum of the absolute
2294 values of the force (gradient) components is smaller than a specified
2295 value $\epsilon$.
2296 Since force truncation produces some noise in the
2297 energy evaluation, the stopping criterion should not be made too tight
2298 to avoid endless iterations. A reasonable value for $\epsilon$ can be
2299 estimated from the root mean square force $f$ a harmonic oscillator would exhibit at a
2300 temperature $T$. This value is
2301 \beq
2302   f = 2 \pi \nu \sqrt{ 2mkT},
2303 \eeq
2304 where $\nu$ is the oscillator frequency, $m$ the (reduced) mass, and
2305 $k$ Boltzmann's constant. For a weak oscillator with a wave number of
2306 100 cm$^{-1}$ and a mass of 10 atomic units, at a temperature of 1 K,
2307 $f=7.7$ kJ~mol$^{-1}$~nm$^{-1}$. A value for $\epsilon$ between 1 and
2308 10 is acceptable.   
2309
2310 \subsection{Conjugate Gradient\index{conjugate gradient}}
2311 Conjugate gradient is slower than steepest descent in the early stages
2312 of the minimization, but becomes more efficient closer to the energy
2313 minimum.  The parameters and stop criterion are the same as for
2314 steepest descent.  In {\gromacs} conjugate gradient can not be used
2315 with constraints, including the SETTLE algorithm for
2316 water~\cite{Miyamoto92}, as this has not been implemented. If water is
2317 present it must be of a flexible model, which can be specified in the
2318 {\tt *.mdp} file by {\tt define = -DFLEXIBLE}.
2319
2320 This is not really a restriction, since the accuracy of conjugate
2321 gradient is only required for minimization prior to a normal-mode
2322 analysis, which cannot be performed with constraints.  For most other
2323 purposes steepest descent is efficient enough.
2324
2325 \subsection{\normindex{L-BFGS}}
2326 The original BFGS algorithm works by successively creating better
2327 approximations of the inverse Hessian matrix, and moving the system to
2328 the currently estimated minimum. The memory requirements for this are
2329 proportional to the square of the number of particles, so it is not
2330 practical for large systems like biomolecules. Instead, we use the
2331 L-BFGS algorithm of Nocedal~\cite{Byrd95a,Zhu97a}, which approximates
2332 the inverse Hessian by a fixed number of corrections from previous
2333 steps. This sliding-window technique is almost as efficient as the
2334 original method, but the memory requirements are much lower -
2335 proportional to the number of particles multiplied with the correction
2336 steps. In practice we have found it to converge faster than conjugate
2337 gradients, but due to the correction steps it is not yet parallelized.
2338 It is also noteworthy that switched or shifted interactions usually
2339 improve the convergence, since sharp cut-offs mean the potential
2340 function at the current coordinates is slightly different from the
2341 previous steps used to build the inverse Hessian approximation.
2342
2343 \section{Normal-Mode Analysis\index{normal-mode analysis}\index{NMA}}
2344 Normal-mode analysis~\cite{Levitt83,Go83,BBrooks83b} 
2345 can be performed using {\gromacs}, by diagonalization of the mass-weighted
2346 \normindex{Hessian} $H$:
2347 \bea
2348 R^T M^{-1/2} H M^{-1/2} R   &=& \mbox{diag}(\lambda_1,\ldots,\lambda_{3N})
2349 \\
2350 \lambda_i &=& (2 \pi \omega_i)^2
2351 \eea
2352 where $M$ contains the atomic masses, $R$ is a matrix that contains
2353 the eigenvectors as columns, $\lambda_i$ are the eigenvalues
2354 and $\omega_i$ are the corresponding frequencies.
2355
2356 First the Hessian matrix, which is a $3N \times 3N$ matrix where $N$
2357 is the number of atoms, needs to be calculated:
2358 \bea
2359 H_{ij}  &=&     \frac{\partial^2 V}{\partial x_i \partial x_j}
2360 \eea
2361 where $x_i$ and $x_j$ denote the atomic x, y or z coordinates.
2362 In practice, this equation is not used, but the Hessian is
2363 calculated numerically from the force as:
2364 \bea
2365 H_{ij} &=& -
2366   \frac{f_i({\bf x}+h{\bf e}_j) - f_i({\bf x}-h{\bf e}_j)}{2h}
2367 \\
2368 f_i     &=& - \frac{\partial V}{\partial x_i}
2369 \eea
2370 where ${\bf e}_j$ is the unit vector in direction $j$.
2371 It should be noted that
2372 for a usual normal-mode calculation, it is necessary to completely minimize 
2373 the energy prior to computation of the Hessian.
2374 The tolerance required depends on the type of system,
2375 but a rough indication is 0.001 kJ mol$^{-1}$.
2376 Minimization should be done with conjugate gradients or L-BFGS in double precision.
2377
2378 A number of {\gromacs} programs are involved in these
2379 calculations. First, the energy should be minimized using {\tt mdrun}.
2380 Then, {\tt mdrun} computes the Hessian.  {\bf Note} that for generating
2381 the run input file, one should use the minimized conformation from
2382 the full precision trajectory file, as the structure file is not
2383 accurate enough.
2384 {\tt \normindex{gmx nmeig}} does the diagonalization and
2385 the sorting of the normal modes according to their frequencies.
2386 Both {\tt mdrun} and {\tt gmx nmeig} should be run in double precision.
2387 The normal modes can be analyzed with the program {\tt gmx anaeig}.
2388 Ensembles of structures at any temperature and for any subset of
2389 normal modes can be generated with {\tt \normindex{gmx nmens}}.
2390 An overview of normal-mode analysis and the related principal component
2391 analysis (see \secref{covanal}) can be found in~\cite{Hayward95b}.
2392
2393
2394 \section{Free energy calculations\index{free energy calculations}}
2395 \label{sec:fecalc}
2396 \subsection{Slow-growth methods\index{slow-growth methods}}
2397 Free energy calculations can be performed
2398 in {\gromacs} using  a number of methods, including ``slow-growth.'' An example problem 
2399 might be calculating the difference in free energy of binding of an inhibitor {\bf I}
2400 to an enzyme {\bf E} and to a mutated enzyme {\bf E$^{\prime}$}. It 
2401 is not feasible with computer simulations to perform a docking
2402 calculation for such a large complex, or even releasing the inhibitor from
2403 the enzyme in a reasonable amount of computer time with reasonable accuracy.
2404 However, if we consider the free energy cycle in~\figref{free}A
2405 we can write:
2406 \beq
2407 \Delta G_1 - \Delta G_2 =       \Delta G_3 - \Delta G_4
2408 \label{eqn:ddg}
2409 \eeq
2410 If we are interested in the left-hand term we can equally well compute
2411 the right-hand term.
2412 \begin{figure}
2413 \centerline{\includegraphics[width=6cm,angle=270]{plots/free1}\hspace{2cm}\includegraphics[width=6cm,angle=270]{plots/free2}}
2414 \caption[Free energy cycles.]{Free energy cycles. {\bf A:} to
2415 calculate $\Delta G_{12}$, the free energy difference between the
2416 binding of inhibitor {\bf I} to enzymes {\bf E} respectively {\bf
2417 E$^{\prime}$}. {\bf B:} to calculate $\Delta G_{12}$, the free energy
2418 difference for binding of inhibitors {\bf I} respectively {\bf I$^{\prime}$} to
2419 enzyme {\bf E}.}
2420 \label{fig:free}
2421 \end{figure}
2422
2423 If we want to compute the difference in free energy of binding of two
2424 inhibitors {\bf I} and {\bf I$^{\prime}$} to an enzyme {\bf E} (\figref{free}B)
2425 we can again use \eqnref{ddg} to compute the desired property.
2426
2427 \newcommand{\sA}{^{\mathrm{A}}}
2428 \newcommand{\sB}{^{\mathrm{B}}}
2429 Free energy differences between two molecular species can
2430 be calculated in {\gromacs} using the ``slow-growth'' method.
2431 Such free energy differences between different molecular species are
2432 physically meaningless, but they can be used to obtain meaningful
2433 quantities employing a thermodynamic cycle.
2434 The method requires a simulation during which the Hamiltonian of the
2435 system changes slowly from that describing one system (A) to that
2436 describing the other system (B). The change must be so slow that the
2437 system remains in equilibrium during the process; if that requirement
2438 is fulfilled, the change is reversible and a slow-growth simulation from B to A
2439 will yield the same results (but with a different sign) as a slow-growth
2440 simulation from A to B. This is a useful check, but the user should be
2441 aware of the danger that equality of forward and backward growth results does
2442 not guarantee correctness of the results.
2443
2444 The required modification of the Hamiltonian $H$ is realized by making
2445 $H$ a function of a \textit{coupling parameter} $\lambda:
2446 H=H(p,q;\lambda)$ in such a way that $\lambda=0$ describes system A
2447 and $\lambda=1$ describes system B: 
2448 \beq
2449   H(p,q;0)=H\sA (p,q);~~~~ H(p,q;1)=H\sB (p,q).
2450 \eeq
2451 In {\gromacs}, the functional form of the $\lambda$-dependence is
2452 different for the various force-field contributions and is described
2453 in section \secref{feia}.
2454
2455 The Helmholtz free energy $A$ is related to the
2456 partition function $Q$ of an $N,V,T$ ensemble, which is assumed to be
2457 the equilibrium ensemble generated by a MD simulation at constant
2458 volume and temperature. The generally more useful Gibbs free energy
2459 $G$ is related to the partition function $\Delta$ of an $N,p,T$
2460 ensemble, which is assumed to be the equilibrium ensemble generated by
2461 a MD simulation at constant pressure and temperature:
2462 \bea
2463  A(\lambda) &=&  -k_BT \ln Q \\
2464  Q &=& c \int\!\!\int \exp[-\beta H(p,q;\lambda)]\,dp\,dq \\
2465  G(\lambda) &=&  -k_BT \ln \Delta \\
2466  \Delta &=& c \int\!\!\int\!\!\int \exp[-\beta H(p,q;\lambda) -\beta
2467 pV]\,dp\,dq\,dV \\
2468 G &=& A + pV, 
2469 \eea
2470 where $\beta = 1/(k_BT)$ and $c = (N! h^{3N})^{-1}$.
2471 These integrals over phase space cannot be evaluated from a
2472 simulation, but it is possible to evaluate the derivative with 
2473 respect to $\lambda$ as an ensemble average:
2474 \beq
2475  \frac{dA}{d\lambda} =  \frac{\int\!\!\int (\partial H/ \partial
2476 \lambda) \exp[-\beta H(p,q;\lambda)]\,dp\,dq}{\int\!\!\int \exp[-\beta
2477 H(p,q;\lambda)]\,dp\,dq} = 
2478 \left\langle \frac{\partial H}{\partial \lambda} \right\rangle_{NVT;\lambda},
2479 \eeq
2480 with a similar relation for $dG/d\lambda$ in the $N,p,T$
2481 ensemble.  The difference in free energy between A and B can be found
2482 by integrating the derivative over $\lambda$:
2483 \bea
2484   A\sB(V,T)-A\sA(V,T) &=& \int_0^1 \left\langle \frac{\partial
2485 H}{\partial \lambda} \right\rangle_{NVT;\lambda} \,d\lambda 
2486 \label{eq:delA} \\
2487  G\sB(p,T)-G\sA(p,T) &=& \int_0^1 \left\langle \frac{\partial
2488 H}{\partial \lambda} \right\rangle_{NpT;\lambda} \,d\lambda.
2489 \label{eq:delG}
2490 \eea
2491 If one wishes to evaluate $G\sB(p,T)-G\sA(p,T)$,
2492 the natural choice is a constant-pressure simulation. However, this
2493 quantity can also be obtained from a slow-growth simulation at
2494 constant volume, starting with system A at pressure $p$ and volume $V$
2495 and ending with system B at pressure $p_B$, by applying the following
2496 small (but, in principle, exact) correction: 
2497 \beq
2498   G\sB(p)-G\sA(p) =
2499 A\sB(V)-A\sA(V) - \int_p^{p\sB}[V\sB(p')-V]\,dp'
2500 \eeq
2501 Here we omitted the constant $T$ from the notation. This correction is
2502 roughly equal to $-\frac{1}{2} (p\sB-p)\Delta V=(\Delta V)^2/(2
2503 \kappa V)$, where $\Delta V$ is the volume change at $p$ and $\kappa$
2504 is the isothermal compressibility. This is usually
2505 small; for example, the growth of a water molecule from nothing
2506 in a bath of 1000 water molecules at constant volume would produce an
2507 additional pressure of as much as 22 bar, but a correction to the 
2508 Helmholtz free energy of just -1 kJ mol$^{-1}$. %-20 J/mol.
2509
2510 In Cartesian coordinates, the kinetic energy term in the Hamiltonian
2511 depends only on the momenta, and can be separately integrated and, in
2512 fact, removed from the equations. When masses do not change, there is
2513 no contribution from the kinetic energy at all; otherwise the
2514 integrated contribution to the free energy is $-\frac{3}{2} k_BT \ln
2515 (m\sB/m\sA)$. {\bf Note} that this is only true in the absence of constraints.
2516
2517 \subsection{Thermodynamic integration\index{thermodynamic integration}\index{BAR}\index{Bennett's acceptance ratio}}  
2518 {\gromacs} offers the possibility to integrate eq.~\ref{eq:delA} or
2519 eq. \ref{eq:delG} in one simulation over the full range from A to
2520 B. However, if the change is large and insufficient sampling can be
2521 expected, the user may prefer to determine the value of $\langle
2522 dG/d\lambda \rangle$ accurately at a number of well-chosen
2523 intermediate values of $\lambda$. This can easily be done by setting
2524 the stepsize {\tt delta_lambda} to zero. Each simulation can be
2525 equilibrated first, and a proper error estimate can be made for each
2526 value of $dG/d\lambda$ from the fluctuation of $\partial H/\partial
2527 \lambda$. The total free energy change is then determined afterward
2528 by an appropriate numerical integration procedure.
2529
2530 {\gromacs} now also supports the use of Bennett's Acceptance Ratio~\cite{Bennett1976}
2531 for calculating values of $\Delta$G for transformations from state A to state B using
2532 the program {\tt \normindex{gmx bar}}. The same data can also be used to calculate free
2533 energies using MBAR~\cite{Shirts2008}, though the analysis currently requires external tools from
2534 the external {\tt pymbar} package, at https://SimTK.org/home/pymbar.
2535
2536 The $\lambda$-dependence for the force-field contributions is
2537 described in detail in section \secref{feia}.
2538
2539 \section{Replica exchange\index{replica exchange}}
2540 Replica exchange molecular dynamics (\normindex{REMD})
2541 is a method that can be used to speed up
2542 the sampling of any type of simulation, especially if
2543 conformations are separated by relatively high energy barriers.
2544 It involves simulating multiple replicas of the same system
2545 at different temperatures and randomly exchanging the complete state
2546 of two replicas at regular intervals with the probability:
2547 \beq
2548 P(1 \leftrightarrow 2)=\min\left(1,\exp\left[
2549 \left(\frac{1}{k_B T_1} - \frac{1}{k_B T_2}\right)(U_1 - U_2)
2550  \right] \right)
2551 \eeq
2552 where $T_1$ and $T_2$ are the reference temperatures and $U_1$ and $U_2$
2553 are the instantaneous potential energies of replicas 1 and 2 respectively.
2554 After exchange the velocities are scaled by $(T_1/T_2)^{\pm0.5}$
2555 and a neighbor search is performed the next step.
2556 This combines the fast sampling and frequent barrier-crossing
2557 of the highest temperature with correct Boltzmann sampling at
2558 all the different temperatures~\cite{Hukushima96a,Sugita99}.
2559 We only attempt exchanges for neighboring temperatures as the probability
2560 decreases very rapidly with the temperature difference.
2561 One should not attempt exchanges for all possible pairs in one step.
2562 If, for instance, replicas 1 and 2 would exchange, the chance of
2563 exchange for replicas 2 and 3 not only depends on the energies of
2564 replicas 2 and 3, but also on the energy of replica 1.
2565 In {\gromacs} this is solved by attempting exchange for all ``odd''
2566 pairs on ``odd'' attempts and for all ``even'' pairs on ``even'' attempts.
2567 If we have four replicas: 0, 1, 2 and 3, ordered in temperature
2568 and we attempt exchange every 1000 steps, pairs 0-1 and 2-3
2569 will be tried at steps 1000, 3000 etc. and pair 1-2 at steps 2000, 4000 etc.
2570
2571 How should one choose the temperatures?
2572 The energy difference can be written as:
2573 \beq
2574 U_1 - U_2 =  N_{df} \frac{c}{2} k_B (T_1 - T_2)
2575 \eeq
2576 where $N_{df}$ is the total number of degrees of freedom of one replica
2577 and $c$ is 1 for harmonic potentials and around 2 for protein/water systems.
2578 If $T_2 = (1+\epsilon) T_1$ the probability becomes:
2579 \beq
2580 P(1 \leftrightarrow 2)
2581   = \exp\left( -\frac{\epsilon^2 c\,N_{df}}{2 (1+\epsilon)} \right)
2582 \approx \exp\left(-\epsilon^2 \frac{c}{2} N_{df} \right)
2583 \eeq
2584 Thus for a probability of $e^{-2}\approx 0.135$
2585 one obtains $\epsilon \approx 2/\sqrt{c\,N_{df}}$.
2586 With all bonds constrained one has $N_{df} \approx 2\, N_{atoms}$
2587 and thus for $c$ = 2 one should choose $\epsilon$ as $1/\sqrt{N_{atoms}}$.
2588 However there is one problem when using pressure coupling. The density at
2589 higher temperatures will decrease, leading to higher energy~\cite{Seibert2005a},
2590 which should be taken into account. The {\gromacs} website features a
2591 so-called ``REMD calculator,'' that lets you type in the temperature range and
2592 the number of atoms, and based on that proposes a set of temperatures.
2593
2594 An extension to the REMD for the isobaric-isothermal ensemble was
2595 proposed by Okabe {\em et al.}~\cite{Okabe2001a}. In this work the
2596 exchange probability is modified to:
2597 \beq
2598 P(1 \leftrightarrow 2)=\min\left(1,\exp\left[
2599 \left(\frac{1}{k_B T_1} - \frac{1}{k_B T_2}\right)(U_1 - U_2) +
2600 \left(\frac{P_1}{k_B T_1} - \frac{P_2}{k_B T_2}\right)\left(V_1-V_2\right)
2601  \right] \right)
2602 \eeq
2603 where $P_1$ and $P_2$ are the respective reference pressures and $V_1$ and
2604 $V_2$ are the respective instantaneous volumes in the simulations.
2605 In most cases the differences in volume are so small that the second
2606 term is negligible. It only plays a role when the difference between
2607 $P_1$ and $P_2$ is large or in phase transitions.
2608
2609 Hamiltonian replica exchange is also supported in {\gromacs}.  In
2610 Hamiltonian replica exchange, each replica has a different
2611 Hamiltonian, defined by the free energy pathway specified for the simulation.  The
2612 exchange probability to maintain the correct ensemble probabilities is:
2613 \beq P(1 \leftrightarrow 2)=\min\left(1,\exp\left[
2614     \left(\frac{1}{k_B T} - \frac{1}{k_B T}\right)((U_1(x_2) - U_1(x_1)) + (U_2(x_1) - U_2(x_2)))
2615 \right]
2616 \right)
2617 \eeq
2618 The separate Hamiltonians are defined by the free energy functionality
2619 of {\gromacs}, with swaps made between the different values of
2620 $\lambda$ defined in the mdp file.
2621
2622 Hamiltonian and temperature replica exchange can also be performed
2623 simultaneously, using the acceptance criteria:
2624 \beq
2625 P(1 \leftrightarrow 2)=\min\left(1,\exp\left[
2626 \left(\frac{1}{k_B T} - \right)(\frac{U_1(x_2) - U_1(x_1)}{k_B T_1} + \frac{U_2(x_1) - U_2(x_2)}{k_B T_2})
2627  \right] \right)
2628 \eeq
2629
2630 Gibbs sampling replica exchange has also been implemented in
2631 {\gromacs}~\cite{Chodera2011}.  In Gibbs sampling replica exchange, all
2632 possible pairs are tested for exchange, allowing swaps between
2633 replicas that are not neighbors.
2634
2635 Gibbs sampling replica exchange requires no additional potential
2636 energy calculations.  However there is an additional communication
2637 cost in Gibbs sampling replica exchange, as for some permutations,
2638 more than one round of swaps must take place.  In some cases, this
2639 extra communication cost might affect the efficiency.
2640
2641 All replica exchange variants are options of the {\tt mdrun}
2642 program. It will only work when MPI is installed, due to the inherent
2643 parallelism in the algorithm. For efficiency each replica can run on a
2644 separate rank.  See the manual page of {\tt mdrun} on how to use these
2645 multinode features.
2646
2647
2648 \section{Essential Dynamics sampling\index{essential dynamics}\index{principal component analysis}\seeindexquiet{PCA}{covariance analysis}}
2649 The results from Essential Dynamics (see \secref{covanal})
2650 of a protein can be used to guide MD simulations. The idea is that
2651 from an initial MD simulation (or from other sources) a definition of
2652 the collective fluctuations with largest amplitude is obtained. The
2653 position along one or more of these collective modes can be
2654 constrained in a (second) MD simulation in a number of ways for
2655 several purposes. For example, the position along a certain mode may
2656 be kept fixed to monitor the average force (free-energy gradient) on
2657 that coordinate in that position. Another application is to enhance
2658 sampling efficiency with respect to usual MD
2659 \cite{Degroot96a,Degroot96b}. In this case, the system is encouraged
2660 to sample its available configuration space more systematically than
2661 in a diffusion-like path that proteins usually take.
2662
2663 Another possibility to enhance sampling is \normindex{flooding}.
2664 Here a flooding potential is added to certain
2665 (collective) degrees of freedom to expel the system out
2666 of a region of phase space \cite{Lange2006a}.
2667
2668 The procedure for essential dynamics sampling or flooding is as follows.
2669 First, the eigenvectors and eigenvalues need to be determined
2670 using covariance analysis ({\tt gmx covar})
2671 or normal-mode analysis ({\tt gmx nmeig}).
2672 Then, this information is fed into {\tt make_edi},
2673 which has many options for selecting vectors and setting parameters,
2674 see {\tt gmx make_edi -h}.
2675 The generated {\tt edi} input file is then passed to {\tt mdrun}.
2676
2677
2678 \section{\normindex{Expanded Ensemble}}
2679
2680 In an expanded ensemble simulation~\cite{Lyubartsev1992}, both the coordinates and the
2681 thermodynamic ensemble are treated as configuration variables that can
2682 be sampled over.  The probability of any given state can be written as:
2683 \beq
2684 P(\vec{x},k) \propto \exp\left(-\beta_k U_k + g_k\right),
2685 \eeq
2686 where $\beta_k = \frac{1}{k_B T_k}$ is the $\beta$ corresponding to the $k$th
2687 thermodynamic state, and $g_k$ is a user-specified weight factor corresponding
2688 to the $k$th state.  This space is therefore a {\em mixed}, {\em generalized}, or {\em
2689   expanded} ensemble which samples from multiple thermodynamic
2690 ensembles simultaneously. $g_k$ is chosen to give a specific weighting
2691 of each subensemble in the expanded ensemble, and can either be fixed,
2692 or determined by an iterative procedure. The set of $g_k$ is
2693 frequently chosen to give each thermodynamic ensemble equal
2694 probability, in which case $g_k$ is equal to the free energy in
2695 non-dimensional units, but they can be set to arbitrary values as
2696 desired.  Several different algorithms can be used to equilibrate
2697 these weights, described in the mdp option listings.
2698
2699 In {\gromacs}, this space is sampled by alternating sampling in the $k$
2700 and $\vec{x}$ directions.  Sampling in the $\vec{x}$ direction is done
2701 by standard molecular dynamics sampling; sampling between the
2702 different thermodynamics states is done by Monte Carlo, with several
2703 different Monte Carlo moves supported. The $k$ states can be defined
2704 by different temperatures, or choices of the free energy $\lambda$
2705 variable, or both.  Expanded ensemble simulations thus represent a
2706 serialization of the replica exchange formalism, allowing a single
2707 simulation to explore many thermodynamic states.
2708
2709
2710
2711 \section{Parallelization\index{parallelization}}
2712 The CPU time required for a simulation can be reduced by running the simulation
2713 in parallel over more than one core.
2714 Ideally, one would want to have linear scaling: running on $N$ cores
2715 makes the simulation $N$ times faster. In practice this can only be
2716 achieved for a small number of cores. The scaling will depend
2717 a lot on the algorithms used. Also, different algorithms can have different
2718 restrictions on the interaction ranges between atoms.
2719
2720 \section{Domain decomposition\index{domain decomposition}}
2721 Since most interactions in molecular simulations are local,
2722 domain decomposition is a natural way to decompose the system.
2723 In domain decomposition, a spatial domain is assigned to each rank,
2724 which will then integrate the equations of motion for the particles
2725 that currently reside in its local domain. With domain decomposition,
2726 there are two choices that have to be made: the division of the unit cell
2727 into domains and the assignment of the forces to domains.
2728 Most molecular simulation packages use the half-shell method for assigning
2729 the forces. But there are two methods that always require less communication:
2730 the eighth shell~\cite{Liem1991} and the midpoint~\cite{Shaw2006} method.
2731 {\gromacs} currently uses the eighth shell method, but for certain systems
2732 or hardware architectures it might be advantageous to use the midpoint
2733 method. Therefore, we might implement the midpoint method in the future.
2734 Most of the details of the domain decomposition can be found
2735 in the {\gromacs} 4 paper~\cite{Hess2008b}.
2736
2737 \subsection{Coordinate and force communication}
2738 In the most general case of a triclinic unit cell,
2739 the space in divided with a 1-, 2-, or 3-D grid in parallelepipeds
2740 that we call domain decomposition cells.
2741 Each cell is assigned to a particle-particle rank.
2742 The system is partitioned over the ranks at the beginning
2743 of each MD step in which neighbor searching is performed.
2744 Since the neighbor searching is based on charge groups, charge groups
2745 are also the units for the domain decomposition.
2746 Charge groups are assigned to the cell where their center of geometry resides.
2747 Before the forces can be calculated, the coordinates from some
2748 neighboring cells need to be communicated,
2749 and after the forces are calculated, the forces need to be communicated
2750 in the other direction.
2751 The communication and force assignment is based on zones that 
2752 can cover one or multiple cells.
2753 An example of a zone setup is shown in \figref{ddcells}.
2754
2755 \begin{figure}
2756 \centerline{\includegraphics[width=6cm]{plots/dd-cells}}
2757 \caption{
2758 A non-staggered domain decomposition grid of 3$\times$2$\times$2 cells.
2759 Coordinates in zones 1 to 7 are communicated to the corner cell
2760 that has its home particles in zone 0.
2761 $r_c$ is the cut-off radius. 
2762 \label{fig:ddcells}
2763 }
2764 \end{figure}
2765
2766 The coordinates are communicated by moving data along the ``negative''
2767 direction in $x$, $y$ or $z$ to the next neighbor. This can be done in one
2768 or multiple pulses. In \figref{ddcells} two pulses in $x$ are required,
2769 then one in $y$ and then one in $z$. The forces are communicated by
2770 reversing this procedure. See the {\gromacs} 4 paper~\cite{Hess2008b}
2771 for details on determining which non-bonded and bonded forces
2772 should be calculated on which rank.
2773
2774 \subsection{Dynamic load balancing\swapindexquiet{dynamic}{load balancing}}
2775 When different ranks have a different computational load
2776 (load imbalance), all ranks will have to wait for the one
2777 that takes the most time. One would like to avoid such a situation.
2778 Load imbalance can occur due to four reasons:
2779 \begin{itemize}
2780 \item inhomogeneous particle distribution
2781 \item inhomogeneous interaction cost distribution (charged/uncharged,
2782   water/non-water due to {\gromacs} water innerloops)
2783 \item statistical fluctuation (only with small particle numbers)
2784 \item differences in communication time, due to network topology and/or other jobs on the machine interfering with our communication
2785 \end{itemize}
2786 So we need a dynamic load balancing algorithm
2787 where the volume of each domain decomposition cell
2788 can be adjusted {\em independently}.
2789 To achieve this, the 2- or 3-D domain decomposition grids need to be
2790 staggered. \figref{ddtric} shows the most general case in 2-D.
2791 Due to the staggering, one might require two distance checks
2792 for deciding if a charge group needs to be communicated:
2793 a non-bonded distance and a bonded distance check.
2794
2795 \begin{figure}
2796 \centerline{\includegraphics[width=7cm]{plots/dd-tric}}
2797 \caption{
2798 The zones to communicate to the rank of zone 0,
2799 see the text for details. $r_c$ and $r_b$ are the non-bonded
2800 and bonded cut-off radii respectively, $d$ is an example
2801 of a distance between following, staggered boundaries of cells.
2802 \label{fig:ddtric}
2803 }
2804 \end{figure}
2805
2806 By default, {\tt mdrun} automatically turns on the dynamic load
2807 balancing during a simulation when the total performance loss
2808 due to the force calculation imbalance is 2\% or more.
2809 {\bf Note} that the reported force load imbalance numbers might be higher,
2810 since the force calculation is only part of work that needs to be done
2811 during an integration step.
2812 The load imbalance is reported in the log file at log output steps
2813 and when the {\tt -v} option is used also on screen.
2814 The average load imbalance and the total performance loss
2815 due to load imbalance are reported at the end of the log file.
2816
2817 There is one important parameter for the dynamic load balancing,
2818 which is the minimum allowed scaling. By default, each dimension
2819 of the domain decomposition cell can scale down by at least
2820 a factor of 0.8. For 3-D domain decomposition this allows cells
2821 to change their volume by about a factor of 0.5, which should allow
2822 for compensation of a load imbalance of 100\%.
2823 The minimum allowed scaling can be changed with the {\tt -dds}
2824 option of {\tt mdrun}.
2825
2826 The load imbalance is measured by timing a single region of the MD step
2827 on each MPI rank. This region can not include MPI communication, as
2828 timing of MPI calls does not allow separating wait due to imbalance
2829 from actual communication.
2830 The domain volumes are then scaled, with under-relaxation, inversely
2831 proportional with the measured time. This procedure will decrease the
2832 load imbalance when the change in load in the measured region correlates
2833 with the change in domain volume and the load outside
2834 the measured region does not depend strongly on the domain volume.
2835 In CPU-only simulations, the load is measured between the coordinate
2836 and the force communication. In simulations with non-bonded
2837 work on GPUs, we overlap communication and
2838 work on the CPU with calculation on the GPU. Therefore we
2839 measure from the last communication before the force calculation to
2840 when the CPU or GPU is finished, whichever is last.
2841 When not using PME ranks, we subtract the time in PME from the CPU time,
2842 as this includes MPI calls and the PME load is independent of domain size.
2843 This generally works well, unless the non-bonded load is low and there is
2844 imbalance in the bonded interactions. Then two issues can arise.
2845 Dynamic load balancing can increase the imbalance in update and constraints
2846 and with PME the coordinate and force redistribution time can go up
2847 significantly. Although dynamic load balancing
2848 can significantly improve performance in cases where there is imbalance in
2849 the bonded interactions on the CPU, there are many situations in which
2850 some domains continue decreasing in size and the load imbalance increases
2851 and/or PME coordinate and force redistribution cost increases significantly.
2852 As of version 2016.1, {\tt mdrun} disables the dynamic load balancing when
2853 measurement indicates that it deteriorates performance. This means that in most
2854 cases the user will get good performance with the default, automated
2855 dynamic load balancing setting.
2856
2857 \subsection{Constraints in parallel\index{constraints}}
2858 \label{subsec:plincs}
2859 Since with domain decomposition parts of molecules can reside
2860 on different ranks, bond constraints can cross cell boundaries.
2861 Therefore a parallel constraint algorithm is required.
2862 {\gromacs} uses the \normindex{P-LINCS} algorithm~\cite{Hess2008a},
2863 which is the parallel version of the \normindex{LINCS} algorithm~\cite{Hess97}
2864 (see \ssecref{lincs}).
2865 The P-LINCS procedure is illustrated in \figref{plincs}.
2866 When molecules cross the cell boundaries, atoms in such molecules
2867 up to ({\tt lincs_order + 1}) bonds away are communicated over the cell boundaries.
2868 Then, the normal LINCS algorithm can be applied to the local bonds
2869 plus the communicated ones. After this procedure, the local bonds
2870 are correctly constrained, even though the extra communicated ones are not.
2871 One coordinate communication step is required for the initial LINCS step
2872 and one for each iteration. Forces do not need to be communicated.
2873
2874 \begin{figure}
2875 \centerline{\includegraphics[width=6cm]{plots/par-lincs2}}
2876 \caption{
2877 Example of the parallel setup of P-LINCS with one molecule
2878 split over three domain decomposition cells, using a matrix
2879 expansion order of 3.
2880 The top part shows which atom coordinates need to be communicated
2881 to which cells. The bottom parts show the local constraints (solid)
2882 and the non-local constraints (dashed) for each of the three cells.
2883 \label{fig:plincs}
2884 }
2885 \end{figure}
2886
2887 \subsection{Interaction ranges}
2888 Domain decomposition takes advantage of the locality of interactions.
2889 This means that there will be limitations on the range of interactions.
2890 By default, {\tt mdrun} tries to find the optimal balance between
2891 interaction range and efficiency. But it can happen that a simulation
2892 stops with an error message about missing interactions,
2893 or that a simulation might run slightly faster with shorter
2894 interaction ranges. A list of interaction ranges
2895 and their default values is given in \tabref{dd_ranges}.
2896
2897 \begin{table}
2898 \centerline{
2899 \begin{tabular}{|c|c|ll|}
2900 \dline
2901 interaction & range & option & default \\
2902 \dline
2903 non-bonded        & $r_c$ = max($r_{\mathrm{list}}$,$r_{\mathrm{VdW}}$,$r_{\mathrm{Coul}}$) & {\tt mdp} file & \\
2904 two-body bonded   & max($r_{\mathrm{mb}}$,$r_c$) & {\tt mdrun -rdd} & starting conf. + 10\% \\
2905 multi-body bonded & $r_{\mathrm{mb}}$ & {\tt mdrun -rdd} & starting conf. + 10\% \\
2906 constraints       & $r_{\mathrm{con}}$ & {\tt mdrun -rcon} & est. from bond lengths \\
2907 virtual sites     & $r_{\mathrm{con}}$ & {\tt mdrun -rcon} & 0 \\
2908 \dline
2909 \end{tabular}
2910 }
2911 \caption{The interaction ranges with domain decomposition.}
2912 \label{tab:dd_ranges}
2913 \end{table}
2914
2915 In most cases the defaults of {\tt mdrun} should not cause the simulation
2916 to stop with an error message of missing interactions.
2917 The range for the bonded interactions is determined from the distance
2918 between bonded charge-groups in the starting configuration, with 10\% added
2919 for headroom. For the constraints, the value of $r_{\mathrm{con}}$ is determined by
2920 taking the maximum distance that ({\tt lincs_order + 1}) bonds can cover
2921 when they all connect at angles of 120 degrees.
2922 The actual constraint communication is not limited by $r_{\mathrm{con}}$,
2923 but by the minimum cell size $L_C$, which has the following lower limit:
2924 \beq
2925 L_C \geq \max(r_{\mathrm{mb}},r_{\mathrm{con}})
2926 \eeq
2927 Without dynamic load balancing the system is actually allowed to scale
2928 beyond this limit when pressure scaling is used.
2929 {\bf Note} that for triclinic boxes, $L_C$ is not simply the box diagonal
2930 component divided by the number of cells in that direction,
2931 rather it is the shortest distance between the triclinic cells borders.
2932 For rhombic dodecahedra this is a factor of $\sqrt{3/2}$ shorter
2933 along $x$ and $y$.
2934
2935 When $r_{\mathrm{mb}} > r_c$, {\tt mdrun} employs a smart algorithm to reduce
2936 the communication. Simply communicating all charge groups within
2937 $r_{\mathrm{mb}}$ would increase the amount of communication enormously.
2938 Therefore only charge-groups that are connected by bonded interactions
2939 to charge groups which are not locally present are communicated.
2940 This leads to little extra communication, but also to a slightly
2941 increased cost for the domain decomposition setup.
2942 In some cases, {\eg} coarse-grained simulations with a very short cut-off,
2943 one might want to set $r_{\mathrm{mb}}$ by hand to reduce this cost.
2944
2945 \subsection{Multiple-Program, Multiple-Data PME parallelization\index{PME}}
2946 \label{subsec:mpmd_pme}
2947 Electrostatics interactions are long-range, therefore special
2948 algorithms are used to avoid summation over many atom pairs.
2949 In {\gromacs} this is usually
2950 PME (\secref{pme}).
2951 Since with PME all particles interact with each other, global communication
2952 is required. This will usually be the limiting factor for 
2953 scaling with domain decomposition.
2954 To reduce the effect of this problem, we have come up with
2955 a Multiple-Program, Multiple-Data approach~\cite{Hess2008b}.
2956 Here, some ranks are selected to do only the PME mesh calculation,
2957 while the other ranks, called particle-particle (PP) ranks,
2958 do all the rest of the work.
2959 For rectangular boxes the optimal PP to PME rank ratio is usually 3:1,
2960 for rhombic dodecahedra usually 2:1.
2961 When the number of PME ranks is reduced by a factor of 4, the number
2962 of communication calls is reduced by about a factor of 16.
2963 Or put differently, we can now scale to 4 times more ranks.
2964 In addition, for modern 4 or 8 core machines in a network,
2965 the effective network bandwidth for PME is quadrupled,
2966 since only a quarter of the cores will be using the network connection
2967 on each machine during the PME calculations.
2968
2969 \begin{figure}
2970 \centerline{\includegraphics[width=12cm]{plots/mpmd-pme}}
2971 \caption{
2972 Example of 8 ranks without (left) and with (right) MPMD.
2973 The PME communication (red arrows) is much higher on the left
2974 than on the right. For MPMD additional PP - PME coordinate
2975 and force communication (blue arrows) is required,
2976 but the total communication complexity is lower.
2977 \label{fig:mpmd_pme}
2978 }
2979 \end{figure}
2980
2981 {\tt mdrun} will by default interleave the PP and PME ranks.
2982 If the ranks are not number consecutively inside the machines,
2983 one might want to use {\tt mdrun -ddorder pp_pme}.
2984 For machines with a real 3-D torus and proper communication software
2985 that assigns the ranks accordingly one should use
2986 {\tt mdrun -ddorder cartesian}.
2987
2988 To optimize the performance one should usually set up the cut-offs
2989 and the PME grid such that the PME load is 25 to 33\% of the total
2990 calculation load. {\tt grompp} will print an estimate for this load
2991 at the end and also {\tt mdrun} calculates the same estimate
2992 to determine the optimal number of PME ranks to use.
2993 For high parallelization it might be worthwhile to optimize
2994 the PME load with the {\tt mdp} settings and/or the number
2995 of PME ranks with the {\tt -npme} option of {\tt mdrun}.
2996 For changing the electrostatics settings it is useful to know
2997 the accuracy of the electrostatics remains nearly constant
2998 when the Coulomb cut-off and the PME grid spacing are scaled
2999 by the same factor.
3000 {\bf Note} that it is usually better to overestimate than to underestimate
3001 the number of PME ranks, since the number of PME ranks is smaller
3002 than the number of PP ranks, which leads to less total waiting time.
3003
3004 The PME domain decomposition can be 1-D or 2-D along the $x$ and/or
3005 $y$ axis. 2-D decomposition is also known as \normindex{pencil decomposition} because of
3006 the shape of the domains at high parallelization.
3007 1-D decomposition along the $y$ axis can only be used when
3008 the PP decomposition has only 1 domain along $x$. 2-D PME decomposition
3009 has to have the number of domains along $x$ equal to the number of
3010 the PP decomposition. {\tt mdrun} automatically chooses 1-D or 2-D
3011 PME decomposition (when possible with the total given number of ranks),
3012 based on the minimum amount of communication for the coordinate redistribution
3013 in PME plus the communication for the grid overlap and transposes.
3014 To avoid superfluous communication of coordinates and forces
3015 between the PP and PME ranks, the number of DD cells in the $x$
3016 direction should ideally be the same or a multiple of the number
3017 of PME ranks. By default, {\tt mdrun} takes care of this issue.
3018
3019 \subsection{Domain decomposition flow chart}
3020 In \figref{dd_flow} a flow chart is shown for domain decomposition
3021 with all possible communication for different algorithms.
3022 For simpler simulations, the same flow chart applies,
3023 without the algorithms and communication for
3024 the algorithms that are not used.
3025
3026 \begin{figure}
3027 \centerline{\includegraphics[width=12cm]{plots/flowchart}}
3028 \caption{
3029 Flow chart showing the algorithms and communication (arrows)
3030 for a standard MD simulation with virtual sites, constraints
3031 and separate PME-mesh ranks.
3032 \label{fig:dd_flow}
3033 }
3034 \end{figure}
3035
3036
3037 \section{Implicit solvation\index{implicit solvation}\index{Generalized Born methods}}
3038 \label{sec:gbsa}
3039 Implicit solvent models provide an efficient way of representing 
3040 the electrostatic effects of solvent molecules, while saving a 
3041 large piece of the computations involved in an accurate, aqueous 
3042 description of the surrounding water in molecular dynamics simulations. 
3043 Implicit solvation models offer several advantages compared with 
3044 explicit solvation, including eliminating the need for the equilibration of water 
3045 around the solute, and the absence of viscosity, which allows the protein 
3046 to more quickly explore conformational space.
3047
3048 Implicit solvent calculations in {\gromacs} can be done using the 
3049 generalized Born-formalism, and the Still~\cite{Still97}, HCT~\cite{Truhlar96}, 
3050 and OBC~\cite{Case04} models are available for calculating the Born radii.
3051
3052 Here, the free energy $G_{\mathrm{solv}}$ of solvation is the sum of three terms,
3053 a solvent-solvent cavity term ($G_{\mathrm{cav}}$), a solute-solvent van der
3054 Waals term ($G_{\mathrm{vdw}}$), and finally a solvent-solute electrostatics
3055 polarization term ($G_{\mathrm{pol}}$).
3056
3057 The sum of $G_{\mathrm{cav}}$ and $G_{\mathrm{vdw}}$ corresponds to the (non-polar)
3058 free energy of solvation for a molecule from which all charges
3059 have been removed, and is commonly called $G_{\mathrm{np}}$,
3060 calculated from the total solvent accessible surface area 
3061 multiplied with a surface tension. 
3062 The total expression for the solvation free energy then becomes:
3063
3064 \beq
3065 G_{\mathrm{solv}} = G_{\mathrm{np}}  + G_{\mathrm{pol}}
3066 \label{eqn:gb_solv}
3067 \eeq
3068
3069 Under the generalized Born model, $G_{\mathrm{pol}}$ is calculated from the generalized Born equation~\cite{Still97}:
3070
3071 \beq
3072 G_{\mathrm{pol}} = \left(1-\frac{1}{\epsilon}\right) \sum_{i=1}^n \sum_{j>i}^n \frac {q_i q_j}{\sqrt{r^2_{ij} + b_i b_j \exp\left(\frac{-r^2_{ij}}{4 b_i b_j}\right)}}
3073 \label{eqn:gb_still}
3074 \eeq
3075
3076 In {\gromacs}, we have introduced the substitution~\cite{Larsson10}:
3077
3078 \beq
3079 c_i=\frac{1}{\sqrt{b_i}}
3080 \label{eqn:gb_subst}
3081 \eeq
3082
3083 which makes it possible to introduce a cheap transformation to a new 
3084 variable $x$ when evaluating each interaction, such that:
3085
3086 \beq
3087 x=\frac{r_{ij}}{\sqrt{b_i b_j }} = r_{ij} c_i c_j
3088 \label{eqn:gb_subst2}
3089 \eeq
3090
3091 In the end, the full re-formulation of~\ref{eqn:gb_still} becomes:
3092  
3093 \beq
3094 G_{\mathrm{pol}} = \left(1-\frac{1}{\epsilon}\right) \sum_{i=1}^n \sum_{j>i}^n \frac{q_i q_j}{\sqrt{b_i  b_j}} ~\xi (x) = \left(1-\frac{1}{\epsilon}\right) \sum_{i=1}^n q_i c_i \sum_{j>i}^n q_j c_j~\xi (x)
3095 \label{eqn:gb_final}
3096 \eeq 
3097
3098 The non-polar part ($G_{\mathrm{np}}$) of Equation~\ref{eqn:gb_solv} is calculated 
3099 directly from the Born radius of each atom using a simple ACE type 
3100 approximation by Schaefer {\em et al.}~\cite{Karplus98}, including a 
3101 simple loop over all atoms. 
3102 This requires only one extra solvation parameter, independent of atom type, 
3103 but differing slightly between the three Born radii models.
3104
3105 % LocalWords:  GROningen MAchine BIOSON Groningen GROMACS Berendsen der Spoel
3106 % LocalWords:  Drunen Comp Phys Comm ROck NS FFT pbc EM ifthenelse gmxlite ff
3107 % LocalWords:  octahedra triclinic Ewald PME PPPM trjconv xy solvated
3108 % LocalWords:  boxtypes boxshapes editconf Lennard COM XTC TNG kT defunits
3109 % LocalWords:  Boltzmann's Mueller nb int mdrun chargegroup simplerc prefactor
3110 % LocalWords:  pme waterloops CH NH CO df com virial integrator Verlet vverlet
3111 % LocalWords:  integrators ref timepoint timestep timesteps mdp md vv avek NVE
3112 % LocalWords:  NVT off's leapfrogv lll LR rmfast SPC fs Nos physicality ps GMX
3113 % LocalWords:  Tcoupling nonergodic thermostatting NOSEHOOVER algorithmes ij yx
3114 % LocalWords:  Parrinello Rahman rescales atm anisotropically ccc xz zx yy yz
3115 % LocalWords:  zy zz se barostat compressibilities MTTK NPT Martyna al isobaric
3116 % LocalWords:  Tuckerman vir PV fkT iLt iL Liouville NHC Eq baro mu trj mol bc
3117 % LocalWords:  freezegroup Shannon's polarizability Overhauser barostats iLn KE
3118 % LocalWords:  negligibly thermostatted Tobias  rhombic maxwell et xtc tng TC rlist
3119 % LocalWords:  waals LINCS holonomic plincs lincs unc ang SA Langevin SD amu BD
3120 % LocalWords:  bfgs Broyden Goldfarb Shanno mkT kJ DFLEXIBLE Nocedal diag nmeig
3121 % LocalWords:  diagonalization anaeig nmens covanal ddg feia BT dp dq pV dV dA
3122 % LocalWords:  NpT eq stepsize REMD constrainted website Okabe MPI covar edi dd
3123 % LocalWords:  progman NMR ddcells innerloops ddtric tric dds rdd conf rcon est
3124 % LocalWords:  mb PP MPMD ddorder pp cartesian grompp npme parallelizable edr
3125 % LocalWords:  macromolecule nstlist vacuo parallelization dof indices MBAR AVX
3126 % LocalWords:  TOL numerics parallelized eigenvectors dG parallelepipeds VdW np
3127 % LocalWords:  Coul multi solvation HCT OBC solv cav vdw Schaefer symplectic dt
3128 % LocalWords:  pymbar multinode subensemble Monte solute subst groupconcept GPU
3129 % LocalWords:  dodecahedron octahedron dodecahedra equilibration usinggroups nm
3130 % LocalWords:  topologies rlistlong CUDA GPUs rcoulomb SIMD BlueGene FPUs erfc
3131 % LocalWords:  cutoffschemesupport unbuffered bondeds OpenMP ewald rtol
3132 % LocalWords:  verletdrift peptide RMS rescaling ergodicity ergodic discretized
3133 % LocalWords:  isothermal compressibility isotropically anisotropic iteratively
3134 % LocalWords:  incompressible integrations translational biomolecules NMA PCA
3135 % LocalWords:  Bennett's equilibrated Hamiltonians covariance equilibrate
3136 % LocalWords:  inhomogeneous conformational online other's th