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