Merge release-5-0 into master
[alexxy/gromacs.git] / src / gromacs / gmxpreprocess / calc_verletbuf.c
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 #include "gmxpre.h"
36
37 #include "calc_verletbuf.h"
38
39 #include <assert.h>
40 #include <math.h>
41 #include <stdlib.h>
42
43 #include <sys/types.h>
44
45 #include "gromacs/ewald/ewald-util.h"
46 #include "gromacs/legacyheaders/macros.h"
47 #include "gromacs/legacyheaders/typedefs.h"
48 #include "gromacs/math/units.h"
49 #include "gromacs/math/vec.h"
50 #include "gromacs/mdlib/nbnxn_consts.h"
51 #include "gromacs/utility/fatalerror.h"
52 #include "gromacs/utility/smalloc.h"
53
54 #ifdef GMX_NBNXN_SIMD
55 /* The include below sets the SIMD instruction type (precision+width)
56  * for all nbnxn SIMD search and non-bonded kernel code.
57  */
58 #ifdef GMX_NBNXN_HALF_WIDTH_SIMD
59 #define GMX_USE_HALF_WIDTH_SIMD_HERE
60 #endif
61 #include "gromacs/simd/simd.h"
62 #endif
63
64
65 /* The code in this file estimates a pairlist buffer length
66  * given a target energy drift per atom per picosecond.
67  * This is done by estimating the drift given a buffer length.
68  * Ideally we would like to have a tight overestimate of the drift,
69  * but that can be difficult to achieve.
70  *
71  * Significant approximations used:
72  *
73  * Uniform particle density. UNDERESTIMATES the drift by rho_global/rho_local.
74  *
75  * Interactions don't affect particle motion. OVERESTIMATES the drift on longer
76  * time scales. This approximation probably introduces the largest errors.
77  *
78  * Only take one constraint per particle into account: OVERESTIMATES the drift.
79  *
80  * For rotating constraints assume the same functional shape for time scales
81  * where the constraints rotate significantly as the exact expression for
82  * short time scales. OVERESTIMATES the drift on long time scales.
83  *
84  * For non-linear virtual sites use the mass of the lightest constructing atom
85  * to determine the displacement. OVER/UNDERESTIMATES the drift, depending on
86  * the geometry and masses of constructing atoms.
87  *
88  * Note that the formulas for normal atoms and linear virtual sites are exact,
89  * apart from the first two approximations.
90  *
91  * Note that apart from the effect of the above approximations, the actual
92  * drift of the total energy of a system can be order of magnitude smaller
93  * due to cancellation of positive and negative drift for different pairs.
94  */
95
96
97 /* Struct for unique atom type for calculating the energy drift.
98  * The atom displacement depends on mass and constraints.
99  * The energy jump for given distance depend on LJ type and q.
100  */
101 typedef struct
102 {
103     real     mass;     /* mass */
104     int      type;     /* type (used for LJ parameters) */
105     real     q;        /* charge */
106     gmx_bool bConstr;  /* constrained, if TRUE, use #DOF=2 iso 3 */
107     real     con_mass; /* mass of heaviest atom connected by constraints */
108     real     con_len;  /* constraint length to the heaviest atom */
109 } atom_nonbonded_kinetic_prop_t;
110
111 /* Struct for unique atom type for calculating the energy drift.
112  * The atom displacement depends on mass and constraints.
113  * The energy jump for given distance depend on LJ type and q.
114  */
115 typedef struct
116 {
117     atom_nonbonded_kinetic_prop_t prop; /* non-bonded and kinetic atom prop. */
118     int                           n;    /* #atoms of this type in the system */
119 } verletbuf_atomtype_t;
120
121 void verletbuf_get_list_setup(gmx_bool                bGPU,
122                               verletbuf_list_setup_t *list_setup)
123 {
124     list_setup->cluster_size_i     = NBNXN_CPU_CLUSTER_I_SIZE;
125
126     if (bGPU)
127     {
128         list_setup->cluster_size_j = NBNXN_GPU_CLUSTER_SIZE;
129     }
130     else
131     {
132 #ifndef GMX_NBNXN_SIMD
133         list_setup->cluster_size_j = NBNXN_CPU_CLUSTER_I_SIZE;
134 #else
135         list_setup->cluster_size_j = GMX_SIMD_REAL_WIDTH;
136 #ifdef GMX_NBNXN_SIMD_2XNN
137         /* We assume the smallest cluster size to be on the safe side */
138         list_setup->cluster_size_j /= 2;
139 #endif
140 #endif
141     }
142 }
143
144 static gmx_bool
145 atom_nonbonded_kinetic_prop_equal(const atom_nonbonded_kinetic_prop_t *prop1,
146                                   const atom_nonbonded_kinetic_prop_t *prop2)
147 {
148     return (prop1->mass     == prop2->mass &&
149             prop1->type     == prop2->type &&
150             prop1->q        == prop2->q &&
151             prop1->bConstr  == prop2->bConstr &&
152             prop1->con_mass == prop2->con_mass &&
153             prop1->con_len  == prop2->con_len);
154 }
155
156 static void add_at(verletbuf_atomtype_t **att_p, int *natt_p,
157                    const atom_nonbonded_kinetic_prop_t *prop,
158                    int nmol)
159 {
160     verletbuf_atomtype_t   *att;
161     int                     natt, i;
162
163     if (prop->mass == 0)
164     {
165         /* Ignore massless particles */
166         return;
167     }
168
169     att  = *att_p;
170     natt = *natt_p;
171
172     i = 0;
173     while (i < natt && !atom_nonbonded_kinetic_prop_equal(prop, &att[i].prop))
174     {
175         i++;
176     }
177
178     if (i < natt)
179     {
180         att[i].n += nmol;
181     }
182     else
183     {
184         (*natt_p)++;
185         srenew(*att_p, *natt_p);
186         (*att_p)[i].prop = *prop;
187         (*att_p)[i].n    = nmol;
188     }
189 }
190
191 static void get_vsite_masses(const gmx_moltype_t  *moltype,
192                              const gmx_ffparams_t *ffparams,
193                              real                 *vsite_m,
194                              int                  *n_nonlin_vsite)
195 {
196     int            ft, i;
197     const t_ilist *il;
198
199     *n_nonlin_vsite = 0;
200
201     /* Check for virtual sites, determine mass from constructing atoms */
202     for (ft = 0; ft < F_NRE; ft++)
203     {
204         if (IS_VSITE(ft))
205         {
206             il = &moltype->ilist[ft];
207
208             for (i = 0; i < il->nr; i += 1+NRAL(ft))
209             {
210                 const t_iparams *ip;
211                 real             cam[5] = {0}, inv_mass, coeff, m_aj;
212                 int              a1, j, aj;
213
214                 ip = &ffparams->iparams[il->iatoms[i]];
215
216                 a1 = il->iatoms[i+1];
217
218                 if (ft != F_VSITEN)
219                 {
220                     for (j = 1; j < NRAL(ft); j++)
221                     {
222                         cam[j] = moltype->atoms.atom[il->iatoms[i+1+j]].m;
223                         if (cam[j] == 0)
224                         {
225                             cam[j] = vsite_m[il->iatoms[i+1+j]];
226                         }
227                         if (cam[j] == 0)
228                         {
229                             gmx_fatal(FARGS, "In molecule type '%s' %s construction involves atom %d, which is a virtual site of equal or high complexity. This is not supported.",
230                                       *moltype->name,
231                                       interaction_function[ft].longname,
232                                       il->iatoms[i+1+j]+1);
233                         }
234                     }
235                 }
236
237                 switch (ft)
238                 {
239                     case F_VSITE2:
240                         /* Exact */
241                         vsite_m[a1] = (cam[1]*cam[2])/(cam[2]*sqr(1-ip->vsite.a) + cam[1]*sqr(ip->vsite.a));
242                         break;
243                     case F_VSITE3:
244                         /* Exact */
245                         vsite_m[a1] = (cam[1]*cam[2]*cam[3])/(cam[2]*cam[3]*sqr(1-ip->vsite.a-ip->vsite.b) + cam[1]*cam[3]*sqr(ip->vsite.a) + cam[1]*cam[2]*sqr(ip->vsite.b));
246                         break;
247                     case F_VSITEN:
248                         /* Exact */
249                         inv_mass = 0;
250                         for (j = 0; j < 3*ffparams->iparams[il->iatoms[i]].vsiten.n; j += 3)
251                         {
252                             aj    = il->iatoms[i+j+2];
253                             coeff = ffparams->iparams[il->iatoms[i+j]].vsiten.a;
254                             if (moltype->atoms.atom[aj].ptype == eptVSite)
255                             {
256                                 m_aj = vsite_m[aj];
257                             }
258                             else
259                             {
260                                 m_aj = moltype->atoms.atom[aj].m;
261                             }
262                             if (m_aj <= 0)
263                             {
264                                 gmx_incons("The mass of a vsiten constructing atom is <= 0");
265                             }
266                             inv_mass += coeff*coeff/m_aj;
267                         }
268                         vsite_m[a1] = 1/inv_mass;
269                         /* Correct for loop increment of i */
270                         i += j - 1 - NRAL(ft);
271                         break;
272                     default:
273                         /* Use the mass of the lightest constructing atom.
274                          * This is an approximation.
275                          * If the distance of the virtual site to the
276                          * constructing atom is less than all distances
277                          * between constructing atoms, this is a safe
278                          * over-estimate of the displacement of the vsite.
279                          * This condition holds for all H mass replacement
280                          * vsite constructions, except for SP2/3 groups.
281                          * In SP3 groups one H will have a F_VSITE3
282                          * construction, so even there the total drift
283                          * estimate shouldn't be far off.
284                          */
285                         assert(j >= 1);
286                         vsite_m[a1] = cam[1];
287                         for (j = 2; j < NRAL(ft); j++)
288                         {
289                             vsite_m[a1] = min(vsite_m[a1], cam[j]);
290                         }
291                         (*n_nonlin_vsite)++;
292                         break;
293                 }
294                 if (gmx_debug_at)
295                 {
296                     fprintf(debug, "atom %4d %-20s mass %6.3f\n",
297                             a1, interaction_function[ft].longname, vsite_m[a1]);
298                 }
299             }
300         }
301     }
302 }
303
304 static void get_verlet_buffer_atomtypes(const gmx_mtop_t      *mtop,
305                                         verletbuf_atomtype_t **att_p,
306                                         int                   *natt_p,
307                                         int                   *n_nonlin_vsite)
308 {
309     verletbuf_atomtype_t          *att;
310     int                            natt;
311     int                            mb, nmol, ft, i, a1, a2, a3, a;
312     const t_atoms                 *atoms;
313     const t_ilist                 *il;
314     const t_iparams               *ip;
315     atom_nonbonded_kinetic_prop_t *prop;
316     real                          *vsite_m;
317     int                            n_nonlin_vsite_mol;
318
319     att  = NULL;
320     natt = 0;
321
322     if (n_nonlin_vsite != NULL)
323     {
324         *n_nonlin_vsite = 0;
325     }
326
327     for (mb = 0; mb < mtop->nmolblock; mb++)
328     {
329         nmol = mtop->molblock[mb].nmol;
330
331         atoms = &mtop->moltype[mtop->molblock[mb].type].atoms;
332
333         /* Check for constraints, as they affect the kinetic energy.
334          * For virtual sites we need the masses and geometry of
335          * the constructing atoms to determine their velocity distribution.
336          */
337         snew(prop, atoms->nr);
338         snew(vsite_m, atoms->nr);
339
340         for (ft = F_CONSTR; ft <= F_CONSTRNC; ft++)
341         {
342             il = &mtop->moltype[mtop->molblock[mb].type].ilist[ft];
343
344             for (i = 0; i < il->nr; i += 1+NRAL(ft))
345             {
346                 ip         = &mtop->ffparams.iparams[il->iatoms[i]];
347                 a1         = il->iatoms[i+1];
348                 a2         = il->iatoms[i+2];
349                 if (atoms->atom[a2].m > prop[a1].con_mass)
350                 {
351                     prop[a1].con_mass = atoms->atom[a2].m;
352                     prop[a1].con_len  = ip->constr.dA;
353                 }
354                 if (atoms->atom[a1].m > prop[a2].con_mass)
355                 {
356                     prop[a2].con_mass = atoms->atom[a1].m;
357                     prop[a2].con_len  = ip->constr.dA;
358                 }
359             }
360         }
361
362         il = &mtop->moltype[mtop->molblock[mb].type].ilist[F_SETTLE];
363
364         for (i = 0; i < il->nr; i += 1+NRAL(F_SETTLE))
365         {
366             ip         = &mtop->ffparams.iparams[il->iatoms[i]];
367             a1         = il->iatoms[i+1];
368             a2         = il->iatoms[i+2];
369             a3         = il->iatoms[i+3];
370             /* Usually the mass of a1 (usually oxygen) is larger than a2/a3.
371              * If this is not the case, we overestimate the displacement,
372              * which leads to a larger buffer (ok since this is an exotic case).
373              */
374             prop[a1].con_mass = atoms->atom[a2].m;
375             prop[a1].con_len  = ip->settle.doh;
376
377             prop[a2].con_mass = atoms->atom[a1].m;
378             prop[a2].con_len  = ip->settle.doh;
379
380             prop[a3].con_mass = atoms->atom[a1].m;
381             prop[a3].con_len  = ip->settle.doh;
382         }
383
384         get_vsite_masses(&mtop->moltype[mtop->molblock[mb].type],
385                          &mtop->ffparams,
386                          vsite_m,
387                          &n_nonlin_vsite_mol);
388         if (n_nonlin_vsite != NULL)
389         {
390             *n_nonlin_vsite += nmol*n_nonlin_vsite_mol;
391         }
392
393         for (a = 0; a < atoms->nr; a++)
394         {
395             if (atoms->atom[a].ptype == eptVSite)
396             {
397                 prop[a].mass = vsite_m[a];
398             }
399             else
400             {
401                 prop[a].mass = atoms->atom[a].m;
402             }
403             prop[a].type     = atoms->atom[a].type;
404             prop[a].q        = atoms->atom[a].q;
405             /* We consider an atom constrained, #DOF=2, when it is
406              * connected with constraints to (at least one) atom with
407              * a mass of more than 0.4x its own mass. This is not a critical
408              * parameter, since with roughly equal masses the unconstrained
409              * and constrained displacement will not differ much (and both
410              * overestimate the displacement).
411              */
412             prop[a].bConstr = (prop[a].con_mass > 0.4*prop[a].mass);
413
414             add_at(&att, &natt, &prop[a], nmol);
415         }
416
417         /* cppcheck-suppress uninitvar Fixed in cppcheck 1.65 */
418         sfree(vsite_m);
419         sfree(prop);
420     }
421
422     if (gmx_debug_at)
423     {
424         for (a = 0; a < natt; a++)
425         {
426             fprintf(debug, "type %d: m %5.2f t %d q %6.3f con %d con_m %5.3f con_l %5.3f n %d\n",
427                     a, att[a].prop.mass, att[a].prop.type, att[a].prop.q,
428                     att[a].prop.bConstr, att[a].prop.con_mass, att[a].prop.con_len,
429                     att[a].n);
430         }
431     }
432
433     *att_p  = att;
434     *natt_p = natt;
435 }
436
437 /* This function computes two components of the estimate of the variance
438  * in the displacement of one atom in a system of two constrained atoms.
439  * Returns in sigma2_2d the variance due to rotation of the constrained
440  * atom around the atom to which it constrained.
441  * Returns in sigma2_3d the variance due to displacement of the COM
442  * of the whole system of the two constrained atoms.
443  *
444  * Note that we only take a single constraint (the one to the heaviest atom)
445  * into account. If an atom has multiple constraints, this will result in
446  * an overestimate of the displacement, which gives a larger drift and buffer.
447  */
448 static void constrained_atom_sigma2(real                                 kT_fac,
449                                     const atom_nonbonded_kinetic_prop_t *prop,
450                                     real                                *sigma2_2d,
451                                     real                                *sigma2_3d)
452 {
453     real sigma2_rot;
454     real com_dist;
455     real sigma2_rel;
456     real scale;
457
458     /* Here we decompose the motion of a constrained atom into two
459      * components: rotation around the COM and translation of the COM.
460      */
461
462     /* Determine the variance for the displacement of the rotational mode */
463     sigma2_rot = kT_fac/(prop->mass*(prop->mass + prop->con_mass)/prop->con_mass);
464
465     /* The distance from the atom to the COM, i.e. the rotational arm */
466     com_dist = prop->con_len*prop->con_mass/(prop->mass + prop->con_mass);
467
468     /* The variance relative to the arm */
469     sigma2_rel = sigma2_rot/(com_dist*com_dist);
470     /* At 6 the scaling formula has slope 0,
471      * so we keep sigma2_2d constant after that.
472      */
473     if (sigma2_rel < 6)
474     {
475         /* A constrained atom rotates around the atom it is constrained to.
476          * This results in a smaller linear displacement than for a free atom.
477          * For a perfectly circular displacement, this lowers the displacement
478          * by: 1/arcsin(arc_length)
479          * and arcsin(x) = 1 + x^2/6 + ...
480          * For sigma2_rel<<1 the displacement distribution is erfc
481          * (exact formula is provided below). For larger sigma, it is clear
482          * that the displacement can't be larger than 2*com_dist.
483          * It turns out that the distribution becomes nearly uniform.
484          * For intermediate sigma2_rel, scaling down sigma with the third
485          * order expansion of arcsin with argument sigma_rel turns out
486          * to give a very good approximation of the distribution and variance.
487          * Even for larger values, the variance is only slightly overestimated.
488          * Note that the most relevant displacements are in the long tail.
489          * This rotation approximation always overestimates the tail (which
490          * runs to infinity, whereas it should be <= 2*com_dist).
491          * Thus we always overestimate the drift and the buffer size.
492          */
493         scale      = 1/(1 + sigma2_rel/6);
494         *sigma2_2d = sigma2_rot*scale*scale;
495     }
496     else
497     {
498         /* sigma_2d is set to the maximum given by the scaling above.
499          * For large sigma2 the real displacement distribution is close
500          * to uniform over -2*con_len to 2*com_dist.
501          * Our erfc with sigma_2d=sqrt(1.5)*com_dist (which means the sigma
502          * of the erfc output distribution is con_dist) overestimates
503          * the variance and additionally has a long tail. This means
504          * we have a (safe) overestimation of the drift.
505          */
506         *sigma2_2d = 1.5*com_dist*com_dist;
507     }
508
509     /* The constrained atom also moves (in 3D) with the COM of both atoms */
510     *sigma2_3d = kT_fac/(prop->mass + prop->con_mass);
511 }
512
513 static void get_atom_sigma2(real                                 kT_fac,
514                             const atom_nonbonded_kinetic_prop_t *prop,
515                             real                                *sigma2_2d,
516                             real                                *sigma2_3d)
517 {
518     if (prop->bConstr)
519     {
520         /* Complicated constraint calculation in a separate function */
521         constrained_atom_sigma2(kT_fac, prop, sigma2_2d, sigma2_3d);
522     }
523     else
524     {
525         /* Unconstrained atom: trivial */
526         *sigma2_2d = 0;
527         *sigma2_3d = kT_fac/prop->mass;
528     }
529 }
530
531 static void approx_2dof(real s2, real x, real *shift, real *scale)
532 {
533     /* A particle with 1 DOF constrained has 2 DOFs instead of 3.
534      * This code is also used for particles with multiple constraints,
535      * in which case we overestimate the displacement.
536      * The 2DOF distribution is sqrt(pi/2)*erfc(r/(sqrt(2)*s))/(2*s).
537      * We approximate this with scale*Gaussian(s,r+shift),
538      * by matching the distribution value and derivative at x.
539      * This is a tight overestimate for all r>=0 at any s and x.
540      */
541     real ex, er;
542
543     ex = exp(-x*x/(2*s2));
544     er = gmx_erfc(x/sqrt(2*s2));
545
546     *shift = -x + sqrt(2*s2/M_PI)*ex/er;
547     *scale = 0.5*M_PI*exp(ex*ex/(M_PI*er*er))*er;
548 }
549
550 static real ener_drift(const verletbuf_atomtype_t *att, int natt,
551                        const gmx_ffparams_t *ffp,
552                        real kT_fac,
553                        real md1_ljd, real d2_ljd, real md3_ljd,
554                        real md1_ljr, real d2_ljr, real md3_ljr,
555                        real md1_el,  real d2_el,
556                        real r_buffer,
557                        real rlist, real boxvol)
558 {
559     /* Erfc(8)=1e-29, use this limit so we have some space for arithmetic
560      * on the result when using float precision.
561      */
562     const real erfc_arg_max = 8.0;
563
564     double     drift_tot, pot1, pot2, pot3, pot;
565     int        i, j;
566     real       s2i_2d, s2i_3d, s2j_2d, s2j_3d, s2, s;
567     int        ti, tj;
568     real       md1, d2, md3;
569     real       sc_fac, rsh, rsh2;
570     double     c_exp, c_erfc;
571
572     drift_tot = 0;
573
574     /* Loop over the different atom type pairs */
575     for (i = 0; i < natt; i++)
576     {
577         get_atom_sigma2(kT_fac, &att[i].prop, &s2i_2d, &s2i_3d);
578         ti = att[i].prop.type;
579
580         for (j = i; j < natt; j++)
581         {
582             get_atom_sigma2(kT_fac, &att[j].prop, &s2j_2d, &s2j_3d);
583             tj = att[j].prop.type;
584
585             /* Add up the up to four independent variances */
586             s2 = s2i_2d + s2i_3d + s2j_2d + s2j_3d;
587
588             /* Note that attractive and repulsive potentials for individual
589              * pairs will partially cancel.
590              */
591             /* -dV/dr at the cut-off for LJ + Coulomb */
592             md1 =
593                 md1_ljd*ffp->iparams[ti*ffp->atnr+tj].lj.c6 +
594                 md1_ljr*ffp->iparams[ti*ffp->atnr+tj].lj.c12 +
595                 md1_el*att[i].prop.q*att[j].prop.q;
596
597             /* d2V/dr2 at the cut-off for LJ + Coulomb */
598             d2 =
599                 d2_ljd*ffp->iparams[ti*ffp->atnr+tj].lj.c6 +
600                 d2_ljr*ffp->iparams[ti*ffp->atnr+tj].lj.c12 +
601                 d2_el*att[i].prop.q*att[j].prop.q;
602
603             /* -d3V/dr3 at the cut-off for LJ, we neglect Coulomb */
604             md3 =
605                 md3_ljd*ffp->iparams[ti*ffp->atnr+tj].lj.c6 +
606                 md3_ljr*ffp->iparams[ti*ffp->atnr+tj].lj.c12;
607
608             rsh    = r_buffer;
609             sc_fac = 1.0;
610
611             if (rsh*rsh > 2*s2*erfc_arg_max*erfc_arg_max)
612             {
613                 /* Erfc might run out of float and become 0, somewhat before
614                  * c_exp becomes 0. To avoid this and to avoid NaN in
615                  * approx_2dof, we set both c_expc and c_erfc to zero.
616                  * In any relevant case this has no effect on the results,
617                  * since c_exp < 6e-29, so the displacement is completely
618                  * negligible for such atom pairs (and an overestimate).
619                  * In nearly all use cases, there will be other atom
620                  * pairs that contribute much more to the total, so zeroing
621                  * this particular contribution has no effect at all.
622                  */
623                 c_exp  = 0;
624                 c_erfc = 0;
625             }
626             else
627             {
628                 /* For constraints: adapt r and scaling for the Gaussian */
629                 if (att[i].prop.bConstr)
630                 {
631                     real sh, sc;
632
633                     approx_2dof(s2i_2d, r_buffer*s2i_2d/s2, &sh, &sc);
634                     rsh    += sh;
635                     sc_fac *= sc;
636                 }
637                 if (att[j].prop.bConstr)
638                 {
639                     real sh, sc;
640
641                     approx_2dof(s2j_2d, r_buffer*s2j_2d/s2, &sh, &sc);
642                     rsh    += sh;
643                     sc_fac *= sc;
644                 }
645
646                 /* Exact contribution of an atom pair with Gaussian displacement
647                  * with sigma s to the energy drift for a potential with
648                  * derivative -md and second derivative dd at the cut-off.
649                  * The only catch is that for potentials that change sign
650                  * near the cut-off there could be an unlucky compensation
651                  * of positive and negative energy drift.
652                  * Such potentials are extremely rare though.
653                  *
654                  * Note that pot has unit energy*length, as the linear
655                  * atom density still needs to be put in.
656                  */
657                 c_exp  = exp(-rsh*rsh/(2*s2))/sqrt(2*M_PI);
658                 c_erfc = 0.5*gmx_erfc(rsh/(sqrt(2*s2)));
659             }
660             s      = sqrt(s2);
661             rsh2   = rsh*rsh;
662
663             pot1 = sc_fac*
664                 md1/2*((rsh2 + s2)*c_erfc - rsh*s*c_exp);
665             pot2 = sc_fac*
666                 d2/6*(s*(rsh2 + 2*s2)*c_exp - rsh*(rsh2 + 3*s2)*c_erfc);
667             pot3 = sc_fac*
668                 md3/24*((rsh2*rsh2 + 6*rsh2*s2 + 3*s2*s2)*c_erfc - rsh*s*(rsh2 + 5*s2)*c_exp);
669             pot = pot1 + pot2 + pot3;
670
671             if (gmx_debug_at)
672             {
673                 fprintf(debug, "n %d %d d s %.3f %.3f %.3f %.3f con %d -d1 %8.1e d2 %8.1e -d3 %8.1e pot1 %8.1e pot2 %8.1e pot3 %8.1e pot %8.1e\n",
674                         att[i].n, att[j].n,
675                         sqrt(s2i_2d), sqrt(s2i_3d),
676                         sqrt(s2j_2d), sqrt(s2j_3d),
677                         att[i].prop.bConstr+att[j].prop.bConstr,
678                         md1, d2, md3,
679                         pot1, pot2, pot3, pot);
680             }
681
682             /* Multiply by the number of atom pairs */
683             if (j == i)
684             {
685                 pot *= (double)att[i].n*(att[i].n - 1)/2;
686             }
687             else
688             {
689                 pot *= (double)att[i].n*att[j].n;
690             }
691             /* We need the line density to get the energy drift of the system.
692              * The effective average r^2 is close to (rlist+sigma)^2.
693              */
694             pot *= 4*M_PI*sqr(rlist + s)/boxvol;
695
696             /* Add the unsigned drift to avoid cancellation of errors */
697             drift_tot += fabs(pot);
698         }
699     }
700
701     return drift_tot;
702 }
703
704 static real surface_frac(int cluster_size, real particle_distance, real rlist)
705 {
706     real d, area_rel;
707
708     if (rlist < 0.5*particle_distance)
709     {
710         /* We have non overlapping spheres */
711         return 1.0;
712     }
713
714     /* Half the inter-particle distance relative to rlist */
715     d = 0.5*particle_distance/rlist;
716
717     /* Determine the area of the surface at distance rlist to the closest
718      * particle, relative to surface of a sphere of radius rlist.
719      * The formulas below assume close to cubic cells for the pair search grid,
720      * which the pair search code tries to achieve.
721      * Note that in practice particle distances will not be delta distributed,
722      * but have some spread, often involving shorter distances,
723      * as e.g. O-H bonds in a water molecule. Thus the estimates below will
724      * usually be slightly too high and thus conservative.
725      */
726     switch (cluster_size)
727     {
728         case 1:
729             /* One particle: trivial */
730             area_rel = 1.0;
731             break;
732         case 2:
733             /* Two particles: two spheres at fractional distance 2*a */
734             area_rel = 1.0 + d;
735             break;
736         case 4:
737             /* We assume a perfect, symmetric tetrahedron geometry.
738              * The surface around a tetrahedron is too complex for a full
739              * analytical solution, so we use a Taylor expansion.
740              */
741             area_rel = (1.0 + 1/M_PI*(6*acos(1/sqrt(3))*d +
742                                       sqrt(3)*d*d*(1.0 +
743                                                    5.0/18.0*d*d +
744                                                    7.0/45.0*d*d*d*d +
745                                                    83.0/756.0*d*d*d*d*d*d)));
746             break;
747         default:
748             gmx_incons("surface_frac called with unsupported cluster_size");
749             area_rel = 1.0;
750     }
751
752     return area_rel/cluster_size;
753 }
754
755 /* Returns the negative of the third derivative of a potential r^-p
756  * with a force-switch function, evaluated at the cut-off rc.
757  */
758 static real md3_force_switch(real p, real rswitch, real rc)
759 {
760     /* The switched force function is:
761      * p*r^-(p+1) + a*(r - rswitch)^2 + b*(r - rswitch)^3
762      */
763     real a, b;
764     real md3_pot, md3_sw;
765
766     a = -((p + 4)*rc - (p + 1)*rswitch)/(pow(rc, p+2)*pow(rc-rswitch, 2));
767     b =  ((p + 3)*rc - (p + 1)*rswitch)/(pow(rc, p+2)*pow(rc-rswitch, 3));
768
769     md3_pot = (p + 2)*(p + 1)*p*pow(rc, p+3);
770     md3_sw  = 2*a + 6*b*(rc - rswitch);
771
772     return md3_pot + md3_sw;
773 }
774
775 void calc_verlet_buffer_size(const gmx_mtop_t *mtop, real boxvol,
776                              const t_inputrec *ir,
777                              real reference_temperature,
778                              const verletbuf_list_setup_t *list_setup,
779                              int *n_nonlin_vsite,
780                              real *rlist)
781 {
782     double                resolution;
783     char                 *env;
784
785     real                  particle_distance;
786     real                  nb_clust_frac_pairs_not_in_list_at_cutoff;
787
788     verletbuf_atomtype_t *att  = NULL;
789     int                   natt = -1, i;
790     double                reppow;
791     real                  md1_ljd, d2_ljd, md3_ljd;
792     real                  md1_ljr, d2_ljr, md3_ljr;
793     real                  md1_el,  d2_el;
794     real                  elfac;
795     real                  kT_fac, mass_min;
796     int                   ib0, ib1, ib;
797     real                  rb, rl;
798     real                  drift;
799
800     if (reference_temperature < 0)
801     {
802         if (EI_MD(ir->eI) && ir->etc == etcNO)
803         {
804             /* This case should be handled outside calc_verlet_buffer_size */
805             gmx_incons("calc_verlet_buffer_size called with an NVE ensemble and reference_temperature < 0");
806         }
807
808         /* We use the maximum temperature with multiple T-coupl groups.
809          * We could use a per particle temperature, but since particles
810          * interact, this might underestimate the buffer size.
811          */
812         reference_temperature = 0;
813         for (i = 0; i < ir->opts.ngtc; i++)
814         {
815             if (ir->opts.tau_t[i] >= 0)
816             {
817                 reference_temperature = max(reference_temperature,
818                                             ir->opts.ref_t[i]);
819             }
820         }
821     }
822
823     /* Resolution of the buffer size */
824     resolution = 0.001;
825
826     env = getenv("GMX_VERLET_BUFFER_RES");
827     if (env != NULL)
828     {
829         sscanf(env, "%lf", &resolution);
830     }
831
832     /* In an atom wise pair-list there would be no pairs in the list
833      * beyond the pair-list cut-off.
834      * However, we use a pair-list of groups vs groups of atoms.
835      * For groups of 4 atoms, the parallelism of SSE instructions, only
836      * 10% of the atoms pairs are not in the list just beyond the cut-off.
837      * As this percentage increases slowly compared to the decrease of the
838      * Gaussian displacement distribution over this range, we can simply
839      * reduce the drift by this fraction.
840      * For larger groups, e.g. of 8 atoms, this fraction will be lower,
841      * so then buffer size will be on the conservative (large) side.
842      *
843      * Note that the formulas used here do not take into account
844      * cancellation of errors which could occur by missing both
845      * attractive and repulsive interactions.
846      *
847      * The only major assumption is homogeneous particle distribution.
848      * For an inhomogeneous system, such as a liquid-vapor system,
849      * the buffer will be underestimated. The actual energy drift
850      * will be higher by the factor: local/homogeneous particle density.
851      *
852      * The results of this estimate have been checked againt simulations.
853      * In most cases the real drift differs by less than a factor 2.
854      */
855
856     /* Worst case assumption: HCP packing of particles gives largest distance */
857     particle_distance = pow(boxvol*sqrt(2)/mtop->natoms, 1.0/3.0);
858
859     get_verlet_buffer_atomtypes(mtop, &att, &natt, n_nonlin_vsite);
860     assert(att != NULL && natt >= 0);
861
862     if (debug)
863     {
864         fprintf(debug, "particle distance assuming HCP packing: %f nm\n",
865                 particle_distance);
866         fprintf(debug, "energy drift atom types: %d\n", natt);
867     }
868
869     reppow   = mtop->ffparams.reppow;
870     md1_ljd  = 0;
871     d2_ljd   = 0;
872     md3_ljd  = 0;
873     md1_ljr  = 0;
874     d2_ljr   = 0;
875     md3_ljr  = 0;
876     if (ir->vdwtype == evdwCUT)
877     {
878         real sw_range, md3_pswf;
879
880         switch (ir->vdw_modifier)
881         {
882             case eintmodNONE:
883             case eintmodPOTSHIFT:
884                 /* -dV/dr of -r^-6 and r^-reppow */
885                 md1_ljd =     -6*pow(ir->rvdw, -7.0);
886                 md1_ljr = reppow*pow(ir->rvdw, -(reppow+1));
887                 /* The contribution of the higher derivatives is negligible */
888                 break;
889             case eintmodFORCESWITCH:
890                 /* At the cut-off: V=V'=V''=0, so we use only V''' */
891                 md3_ljd  = -md3_force_switch(6.0,    ir->rvdw_switch, ir->rvdw);
892                 md3_ljr  =  md3_force_switch(reppow, ir->rvdw_switch, ir->rvdw);
893                 break;
894             case eintmodPOTSWITCH:
895                 /* At the cut-off: V=V'=V''=0.
896                  * V''' is given by the original potential times
897                  * the third derivative of the switch function.
898                  */
899                 sw_range  = ir->rvdw - ir->rvdw_switch;
900                 md3_pswf  = 60.0*pow(sw_range, -3.0);
901
902                 md3_ljd   = -pow(ir->rvdw, -6.0   )*md3_pswf;
903                 md3_ljr   =  pow(ir->rvdw, -reppow)*md3_pswf;
904                 break;
905             default:
906                 gmx_incons("Unimplemented VdW modifier");
907         }
908     }
909     else if (EVDW_PME(ir->vdwtype))
910     {
911         real b, r, br, br2, br4, br6;
912         b        = calc_ewaldcoeff_lj(ir->rvdw, ir->ewald_rtol_lj);
913         r        = ir->rvdw;
914         br       = b*r;
915         br2      = br*br;
916         br4      = br2*br2;
917         br6      = br4*br2;
918         /* -dV/dr of g(br)*r^-6 [where g(x) = exp(-x^2)(1+x^2+x^4/2), see LJ-PME equations in manual] and r^-reppow */
919         md1_ljd  = -exp(-br2)*(br6 + 3.0*br4 + 6.0*br2 + 6.0)*pow(r, -7.0);
920         md1_ljr  = reppow*pow(r, -(reppow+1));
921         /* The contribution of the higher derivatives is negligible */
922     }
923     else
924     {
925         gmx_fatal(FARGS, "Energy drift calculation is only implemented for plain cut-off Lennard-Jones interactions");
926     }
927
928     elfac = ONE_4PI_EPS0/ir->epsilon_r;
929
930     /* Determine md=-dV/dr and dd=d^2V/dr^2 */
931     md1_el = 0;
932     d2_el  = 0;
933     if (ir->coulombtype == eelCUT || EEL_RF(ir->coulombtype))
934     {
935         real eps_rf, k_rf;
936
937         if (ir->coulombtype == eelCUT)
938         {
939             eps_rf = 1;
940             k_rf   = 0;
941         }
942         else
943         {
944             eps_rf = ir->epsilon_rf/ir->epsilon_r;
945             if (eps_rf != 0)
946             {
947                 k_rf = pow(ir->rcoulomb, -3.0)*(eps_rf - ir->epsilon_r)/(2*eps_rf + ir->epsilon_r);
948             }
949             else
950             {
951                 /* epsilon_rf = infinity */
952                 k_rf = 0.5*pow(ir->rcoulomb, -3.0);
953             }
954         }
955
956         if (eps_rf > 0)
957         {
958             md1_el = elfac*(pow(ir->rcoulomb, -2.0) - 2*k_rf*ir->rcoulomb);
959         }
960         d2_el      = elfac*(2*pow(ir->rcoulomb, -3.0) + 2*k_rf);
961     }
962     else if (EEL_PME(ir->coulombtype) || ir->coulombtype == eelEWALD)
963     {
964         real b, rc, br;
965
966         b      = calc_ewaldcoeff_q(ir->rcoulomb, ir->ewald_rtol);
967         rc     = ir->rcoulomb;
968         br     = b*rc;
969         md1_el = elfac*(b*exp(-br*br)*M_2_SQRTPI/rc + gmx_erfc(br)/(rc*rc));
970         d2_el  = elfac/(rc*rc)*(2*b*(1 + br*br)*exp(-br*br)*M_2_SQRTPI + 2*gmx_erfc(br)/rc);
971     }
972     else
973     {
974         gmx_fatal(FARGS, "Energy drift calculation is only implemented for Reaction-Field and Ewald electrostatics");
975     }
976
977     /* Determine the variance of the atomic displacement
978      * over nstlist-1 steps: kT_fac
979      * For inertial dynamics (not Brownian dynamics) the mass factor
980      * is not included in kT_fac, it is added later.
981      */
982     if (ir->eI == eiBD)
983     {
984         /* Get the displacement distribution from the random component only.
985          * With accurate integration the systematic (force) displacement
986          * should be negligible (unless nstlist is extremely large, which
987          * you wouldn't do anyhow).
988          */
989         kT_fac = 2*BOLTZ*reference_temperature*(ir->nstlist-1)*ir->delta_t;
990         if (ir->bd_fric > 0)
991         {
992             /* This is directly sigma^2 of the displacement */
993             kT_fac /= ir->bd_fric;
994
995             /* Set the masses to 1 as kT_fac is the full sigma^2,
996              * but we divide by m in ener_drift().
997              */
998             for (i = 0; i < natt; i++)
999             {
1000                 att[i].prop.mass = 1;
1001             }
1002         }
1003         else
1004         {
1005             real tau_t;
1006
1007             /* Per group tau_t is not implemented yet, use the maximum */
1008             tau_t = ir->opts.tau_t[0];
1009             for (i = 1; i < ir->opts.ngtc; i++)
1010             {
1011                 tau_t = max(tau_t, ir->opts.tau_t[i]);
1012             }
1013
1014             kT_fac *= tau_t;
1015             /* This kT_fac needs to be divided by the mass to get sigma^2 */
1016         }
1017     }
1018     else
1019     {
1020         kT_fac = BOLTZ*reference_temperature*sqr((ir->nstlist-1)*ir->delta_t);
1021     }
1022
1023     mass_min = att[0].prop.mass;
1024     for (i = 1; i < natt; i++)
1025     {
1026         mass_min = min(mass_min, att[i].prop.mass);
1027     }
1028
1029     if (debug)
1030     {
1031         fprintf(debug, "md1_ljd %9.2e d2_ljd %9.2e md3_ljd %9.2e\n", md1_ljd, d2_ljd, md3_ljd);
1032         fprintf(debug, "md1_ljr %9.2e d2_ljr %9.2e md3_ljr %9.2e\n", md1_ljr, d2_ljr, md3_ljr);
1033         fprintf(debug, "md1_el  %9.2e d2_el  %9.2e\n", md1_el, d2_el);
1034         fprintf(debug, "sqrt(kT_fac) %f\n", sqrt(kT_fac));
1035         fprintf(debug, "mass_min %f\n", mass_min);
1036     }
1037
1038     /* Search using bisection */
1039     ib0 = -1;
1040     /* The drift will be neglible at 5 times the max sigma */
1041     ib1 = (int)(5*2*sqrt(kT_fac/mass_min)/resolution) + 1;
1042     while (ib1 - ib0 > 1)
1043     {
1044         ib = (ib0 + ib1)/2;
1045         rb = ib*resolution;
1046         rl = max(ir->rvdw, ir->rcoulomb) + rb;
1047
1048         /* Calculate the average energy drift at the last step
1049          * of the nstlist steps at which the pair-list is used.
1050          */
1051         drift = ener_drift(att, natt, &mtop->ffparams,
1052                            kT_fac,
1053                            md1_ljd, d2_ljd, md3_ljd,
1054                            md1_ljr, d2_ljr, md3_ljr,
1055                            md1_el,  d2_el,
1056                            rb,
1057                            rl, boxvol);
1058
1059         /* Correct for the fact that we are using a Ni x Nj particle pair list
1060          * and not a 1 x 1 particle pair list. This reduces the drift.
1061          */
1062         /* We don't have a formula for 8 (yet), use 4 which is conservative */
1063         nb_clust_frac_pairs_not_in_list_at_cutoff =
1064             surface_frac(min(list_setup->cluster_size_i, 4),
1065                          particle_distance, rl)*
1066             surface_frac(min(list_setup->cluster_size_j, 4),
1067                          particle_distance, rl);
1068         drift *= nb_clust_frac_pairs_not_in_list_at_cutoff;
1069
1070         /* Convert the drift to drift per unit time per atom */
1071         drift /= ir->nstlist*ir->delta_t*mtop->natoms;
1072
1073         if (debug)
1074         {
1075             fprintf(debug, "ib %3d %3d %3d rb %.3f %dx%d fac %.3f drift %.1e\n",
1076                     ib0, ib, ib1, rb,
1077                     list_setup->cluster_size_i, list_setup->cluster_size_j,
1078                     nb_clust_frac_pairs_not_in_list_at_cutoff,
1079                     drift);
1080         }
1081
1082         if (fabs(drift) > ir->verletbuf_tol)
1083         {
1084             ib0 = ib;
1085         }
1086         else
1087         {
1088             ib1 = ib;
1089         }
1090     }
1091
1092     sfree(att);
1093
1094     *rlist = max(ir->rvdw, ir->rcoulomb) + ib1*resolution;
1095 }