Use full path for legacyheaders
[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 "config.h"
36
37 #include <assert.h>
38 #include <math.h>
39 #include <stdlib.h>
40
41 #include <sys/types.h>
42
43 #include "gromacs/legacyheaders/typedefs.h"
44 #include "gromacs/math/units.h"
45 #include "gromacs/legacyheaders/macros.h"
46 #include "gromacs/math/vec.h"
47 #include "gromacs/legacyheaders/coulomb.h"
48 #include "calc_verletbuf.h"
49 #include "../mdlib/nbnxn_consts.h"
50
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, m_aj;
212                 int              a1, j, aj, coeff;
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*ip->vsiten.n; j += 3)
251                         {
252                             aj    = il->iatoms[i+j+2];
253                             coeff = ip[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                         break;
270                     default:
271                         /* Use the mass of the lightest constructing atom.
272                          * This is an approximation.
273                          * If the distance of the virtual site to the
274                          * constructing atom is less than all distances
275                          * between constructing atoms, this is a safe
276                          * over-estimate of the displacement of the vsite.
277                          * This condition holds for all H mass replacement
278                          * vsite constructions, except for SP2/3 groups.
279                          * In SP3 groups one H will have a F_VSITE3
280                          * construction, so even there the total drift
281                          * estimate shouldn't be far off.
282                          */
283                         assert(j >= 1);
284                         vsite_m[a1] = cam[1];
285                         for (j = 2; j < NRAL(ft); j++)
286                         {
287                             vsite_m[a1] = min(vsite_m[a1], cam[j]);
288                         }
289                         (*n_nonlin_vsite)++;
290                         break;
291                 }
292                 if (gmx_debug_at)
293                 {
294                     fprintf(debug, "atom %4d %-20s mass %6.3f\n",
295                             a1, interaction_function[ft].longname, vsite_m[a1]);
296                 }
297             }
298         }
299     }
300 }
301
302 static void get_verlet_buffer_atomtypes(const gmx_mtop_t      *mtop,
303                                         verletbuf_atomtype_t **att_p,
304                                         int                   *natt_p,
305                                         int                   *n_nonlin_vsite)
306 {
307     verletbuf_atomtype_t          *att;
308     int                            natt;
309     int                            mb, nmol, ft, i, a1, a2, a3, a;
310     const t_atoms                 *atoms;
311     const t_ilist                 *il;
312     const t_iparams               *ip;
313     atom_nonbonded_kinetic_prop_t *prop;
314     real                          *vsite_m;
315     int                            n_nonlin_vsite_mol;
316
317     att  = NULL;
318     natt = 0;
319
320     if (n_nonlin_vsite != NULL)
321     {
322         *n_nonlin_vsite = 0;
323     }
324
325     for (mb = 0; mb < mtop->nmolblock; mb++)
326     {
327         nmol = mtop->molblock[mb].nmol;
328
329         atoms = &mtop->moltype[mtop->molblock[mb].type].atoms;
330
331         /* Check for constraints, as they affect the kinetic energy.
332          * For virtual sites we need the masses and geometry of
333          * the constructing atoms to determine their velocity distribution.
334          */
335         snew(prop, atoms->nr);
336         snew(vsite_m, atoms->nr);
337
338         for (ft = F_CONSTR; ft <= F_CONSTRNC; ft++)
339         {
340             il = &mtop->moltype[mtop->molblock[mb].type].ilist[ft];
341
342             for (i = 0; i < il->nr; i += 1+NRAL(ft))
343             {
344                 ip         = &mtop->ffparams.iparams[il->iatoms[i]];
345                 a1         = il->iatoms[i+1];
346                 a2         = il->iatoms[i+2];
347                 if (atoms->atom[a2].m > prop[a1].con_mass)
348                 {
349                     prop[a1].con_mass = atoms->atom[a2].m;
350                     prop[a1].con_len  = ip->constr.dA;
351                 }
352                 if (atoms->atom[a1].m > prop[a2].con_mass)
353                 {
354                     prop[a2].con_mass = atoms->atom[a1].m;
355                     prop[a2].con_len  = ip->constr.dA;
356                 }
357             }
358         }
359
360         il = &mtop->moltype[mtop->molblock[mb].type].ilist[F_SETTLE];
361
362         for (i = 0; i < il->nr; i += 1+NRAL(F_SETTLE))
363         {
364             ip         = &mtop->ffparams.iparams[il->iatoms[i]];
365             a1         = il->iatoms[i+1];
366             a2         = il->iatoms[i+2];
367             a3         = il->iatoms[i+3];
368             /* Usually the mass of a1 (usually oxygen) is larger than a2/a3.
369              * If this is not the case, we overestimate the displacement,
370              * which leads to a larger buffer (ok since this is an exotic case).
371              */
372             prop[a1].con_mass = atoms->atom[a2].m;
373             prop[a1].con_len  = ip->settle.doh;
374
375             prop[a2].con_mass = atoms->atom[a1].m;
376             prop[a2].con_len  = ip->settle.doh;
377
378             prop[a3].con_mass = atoms->atom[a1].m;
379             prop[a3].con_len  = ip->settle.doh;
380         }
381
382         get_vsite_masses(&mtop->moltype[mtop->molblock[mb].type],
383                          &mtop->ffparams,
384                          vsite_m,
385                          &n_nonlin_vsite_mol);
386         if (n_nonlin_vsite != NULL)
387         {
388             *n_nonlin_vsite += nmol*n_nonlin_vsite_mol;
389         }
390
391         for (a = 0; a < atoms->nr; a++)
392         {
393             if (atoms->atom[a].ptype == eptVSite)
394             {
395                 prop[a].mass = vsite_m[a];
396             }
397             else
398             {
399                 prop[a].mass = atoms->atom[a].m;
400             }
401             prop[a].type     = atoms->atom[a].type;
402             prop[a].q        = atoms->atom[a].q;
403             /* We consider an atom constrained, #DOF=2, when it is
404              * connected with constraints to (at least one) atom with
405              * a mass of more than 0.4x its own mass. This is not a critical
406              * parameter, since with roughly equal masses the unconstrained
407              * and constrained displacement will not differ much (and both
408              * overestimate the displacement).
409              */
410             prop[a].bConstr = (prop[a].con_mass > 0.4*prop[a].mass);
411
412             add_at(&att, &natt, &prop[a], nmol);
413         }
414
415         /* cppcheck-suppress uninitvar Fixed in cppcheck 1.65 */
416         sfree(vsite_m);
417         sfree(prop);
418     }
419
420     if (gmx_debug_at)
421     {
422         for (a = 0; a < natt; a++)
423         {
424             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",
425                     a, att[a].prop.mass, att[a].prop.type, att[a].prop.q,
426                     att[a].prop.bConstr, att[a].prop.con_mass, att[a].prop.con_len,
427                     att[a].n);
428         }
429     }
430
431     *att_p  = att;
432     *natt_p = natt;
433 }
434
435 /* This function computes two components of the estimate of the variance
436  * in the displacement of one atom in a system of two constrained atoms.
437  * Returns in sigma2_2d the variance due to rotation of the constrained
438  * atom around the atom to which it constrained.
439  * Returns in sigma2_3d the variance due to displacement of the COM
440  * of the whole system of the two constrained atoms.
441  *
442  * Note that we only take a single constraint (the one to the heaviest atom)
443  * into account. If an atom has multiple constraints, this will result in
444  * an overestimate of the displacement, which gives a larger drift and buffer.
445  */
446 static void constrained_atom_sigma2(real                                 kT_fac,
447                                     const atom_nonbonded_kinetic_prop_t *prop,
448                                     real                                *sigma2_2d,
449                                     real                                *sigma2_3d)
450 {
451     real sigma2_rot;
452     real com_dist;
453     real sigma2_rel;
454     real scale;
455
456     /* Here we decompose the motion of a constrained atom into two
457      * components: rotation around the COM and translation of the COM.
458      */
459
460     /* Determine the variance for the displacement of the rotational mode */
461     sigma2_rot = kT_fac/(prop->mass*(prop->mass + prop->con_mass)/prop->con_mass);
462
463     /* The distance from the atom to the COM, i.e. the rotational arm */
464     com_dist = prop->con_len*prop->con_mass/(prop->mass + prop->con_mass);
465
466     /* The variance relative to the arm */
467     sigma2_rel = sigma2_rot/(com_dist*com_dist);
468     /* At 6 the scaling formula has slope 0,
469      * so we keep sigma2_2d constant after that.
470      */
471     if (sigma2_rel < 6)
472     {
473         /* A constrained atom rotates around the atom it is constrained to.
474          * This results in a smaller linear displacement than for a free atom.
475          * For a perfectly circular displacement, this lowers the displacement
476          * by: 1/arcsin(arc_length)
477          * and arcsin(x) = 1 + x^2/6 + ...
478          * For sigma2_rel<<1 the displacement distribution is erfc
479          * (exact formula is provided below). For larger sigma, it is clear
480          * that the displacement can't be larger than 2*com_dist.
481          * It turns out that the distribution becomes nearly uniform.
482          * For intermediate sigma2_rel, scaling down sigma with the third
483          * order expansion of arcsin with argument sigma_rel turns out
484          * to give a very good approximation of the distribution and variance.
485          * Even for larger values, the variance is only slightly overestimated.
486          * Note that the most relevant displacements are in the long tail.
487          * This rotation approximation always overestimates the tail (which
488          * runs to infinity, whereas it should be <= 2*com_dist).
489          * Thus we always overestimate the drift and the buffer size.
490          */
491         scale      = 1/(1 + sigma2_rel/6);
492         *sigma2_2d = sigma2_rot*scale*scale;
493     }
494     else
495     {
496         /* sigma_2d is set to the maximum given by the scaling above.
497          * For large sigma2 the real displacement distribution is close
498          * to uniform over -2*con_len to 2*com_dist.
499          * Our erfc with sigma_2d=sqrt(1.5)*com_dist (which means the sigma
500          * of the erfc output distribution is con_dist) overestimates
501          * the variance and additionally has a long tail. This means
502          * we have a (safe) overestimation of the drift.
503          */
504         *sigma2_2d = 1.5*com_dist*com_dist;
505     }
506
507     /* The constrained atom also moves (in 3D) with the COM of both atoms */
508     *sigma2_3d = kT_fac/(prop->mass + prop->con_mass);
509 }
510
511 static void get_atom_sigma2(real                                 kT_fac,
512                             const atom_nonbonded_kinetic_prop_t *prop,
513                             real                                *sigma2_2d,
514                             real                                *sigma2_3d)
515 {
516     if (prop->bConstr)
517     {
518         /* Complicated constraint calculation in a separate function */
519         constrained_atom_sigma2(kT_fac, prop, sigma2_2d, sigma2_3d);
520     }
521     else
522     {
523         /* Unconstrained atom: trivial */
524         *sigma2_2d = 0;
525         *sigma2_3d = kT_fac/prop->mass;
526     }
527 }
528
529 static void approx_2dof(real s2, real x, real *shift, real *scale)
530 {
531     /* A particle with 1 DOF constrained has 2 DOFs instead of 3.
532      * This code is also used for particles with multiple constraints,
533      * in which case we overestimate the displacement.
534      * The 2DOF distribution is sqrt(pi/2)*erfc(r/(sqrt(2)*s))/(2*s).
535      * We approximate this with scale*Gaussian(s,r+shift),
536      * by matching the distribution value and derivative at x.
537      * This is a tight overestimate for all r>=0 at any s and x.
538      */
539     real ex, er;
540
541     ex = exp(-x*x/(2*s2));
542     er = gmx_erfc(x/sqrt(2*s2));
543
544     *shift = -x + sqrt(2*s2/M_PI)*ex/er;
545     *scale = 0.5*M_PI*exp(ex*ex/(M_PI*er*er))*er;
546 }
547
548 static real ener_drift(const verletbuf_atomtype_t *att, int natt,
549                        const gmx_ffparams_t *ffp,
550                        real kT_fac,
551                        real md1_ljd, real d2_ljd, real md3_ljd,
552                        real md1_ljr, real d2_ljr, real md3_ljr,
553                        real md1_el,  real d2_el,
554                        real r_buffer,
555                        real rlist, real boxvol)
556 {
557     double drift_tot, pot1, pot2, pot3, pot;
558     int    i, j;
559     real   s2i_2d, s2i_3d, s2j_2d, s2j_3d, s2, s;
560     int    ti, tj;
561     real   md1, d2, md3;
562     real   sc_fac, rsh, rsh2;
563     double c_exp, c_erfc;
564
565     drift_tot = 0;
566
567     /* Loop over the different atom type pairs */
568     for (i = 0; i < natt; i++)
569     {
570         get_atom_sigma2(kT_fac, &att[i].prop, &s2i_2d, &s2i_3d);
571         ti = att[i].prop.type;
572
573         for (j = i; j < natt; j++)
574         {
575             get_atom_sigma2(kT_fac, &att[j].prop, &s2j_2d, &s2j_3d);
576             tj = att[j].prop.type;
577
578             /* Add up the up to four independent variances */
579             s2 = s2i_2d + s2i_3d + s2j_2d + s2j_3d;
580
581             /* Note that attractive and repulsive potentials for individual
582              * pairs will partially cancel.
583              */
584             /* -dV/dr at the cut-off for LJ + Coulomb */
585             md1 =
586                 md1_ljd*ffp->iparams[ti*ffp->atnr+tj].lj.c6 +
587                 md1_ljr*ffp->iparams[ti*ffp->atnr+tj].lj.c12 +
588                 md1_el*att[i].prop.q*att[j].prop.q;
589
590             /* d2V/dr2 at the cut-off for LJ + Coulomb */
591             d2 =
592                 d2_ljd*ffp->iparams[ti*ffp->atnr+tj].lj.c6 +
593                 d2_ljr*ffp->iparams[ti*ffp->atnr+tj].lj.c12 +
594                 d2_el*att[i].prop.q*att[j].prop.q;
595
596             /* -d3V/dr3 at the cut-off for LJ, we neglect Coulomb */
597             md3 =
598                 md3_ljd*ffp->iparams[ti*ffp->atnr+tj].lj.c6 +
599                 md3_ljr*ffp->iparams[ti*ffp->atnr+tj].lj.c12;
600
601             rsh    = r_buffer;
602             sc_fac = 1.0;
603             /* For constraints: adapt r and scaling for the Gaussian */
604             if (att[i].prop.bConstr)
605             {
606                 real sh, sc;
607
608                 approx_2dof(s2i_2d, r_buffer*s2i_2d/s2, &sh, &sc);
609                 rsh    += sh;
610                 sc_fac *= sc;
611             }
612             if (att[j].prop.bConstr)
613             {
614                 real sh, sc;
615
616                 approx_2dof(s2j_2d, r_buffer*s2j_2d/s2, &sh, &sc);
617                 rsh    += sh;
618                 sc_fac *= sc;
619             }
620
621             /* Exact contribution of an atom pair with Gaussian displacement
622              * with sigma s to the energy drift for a potential with
623              * derivative -md and second derivative dd at the cut-off.
624              * The only catch is that for potentials that change sign
625              * near the cut-off there could be an unlucky compensation
626              * of positive and negative energy drift.
627              * Such potentials are extremely rare though.
628              *
629              * Note that pot has unit energy*length, as the linear
630              * atom density still needs to be put in.
631              */
632             c_exp  = exp(-rsh*rsh/(2*s2))/sqrt(2*M_PI);
633             c_erfc = 0.5*gmx_erfc(rsh/(sqrt(2*s2)));
634             s      = sqrt(s2);
635             rsh2   = rsh*rsh;
636
637             pot1 = sc_fac*
638                 md1/2*((rsh2 + s2)*c_erfc - rsh*s*c_exp);
639             pot2 = sc_fac*
640                 d2/6*(s*(rsh2 + 2*s2)*c_exp - rsh*(rsh2 + 3*s2)*c_erfc);
641             pot3 =
642                 md3/24*((rsh2*rsh2 + 6*rsh2*s2 + 3*s2*s2)*c_erfc - rsh*s*(rsh2 + 5*s2)*c_exp);
643             pot = pot1 + pot2 + pot3;
644
645             if (gmx_debug_at)
646             {
647                 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",
648                         att[i].n, att[j].n,
649                         sqrt(s2i_2d), sqrt(s2i_3d),
650                         sqrt(s2j_2d), sqrt(s2j_3d),
651                         att[i].prop.bConstr+att[j].prop.bConstr,
652                         md1, d2, md3,
653                         pot1, pot2, pot3, pot);
654             }
655
656             /* Multiply by the number of atom pairs */
657             if (j == i)
658             {
659                 pot *= (double)att[i].n*(att[i].n - 1)/2;
660             }
661             else
662             {
663                 pot *= (double)att[i].n*att[j].n;
664             }
665             /* We need the line density to get the energy drift of the system.
666              * The effective average r^2 is close to (rlist+sigma)^2.
667              */
668             pot *= 4*M_PI*sqr(rlist + s)/boxvol;
669
670             /* Add the unsigned drift to avoid cancellation of errors */
671             drift_tot += fabs(pot);
672         }
673     }
674
675     return drift_tot;
676 }
677
678 static real surface_frac(int cluster_size, real particle_distance, real rlist)
679 {
680     real d, area_rel;
681
682     if (rlist < 0.5*particle_distance)
683     {
684         /* We have non overlapping spheres */
685         return 1.0;
686     }
687
688     /* Half the inter-particle distance relative to rlist */
689     d = 0.5*particle_distance/rlist;
690
691     /* Determine the area of the surface at distance rlist to the closest
692      * particle, relative to surface of a sphere of radius rlist.
693      * The formulas below assume close to cubic cells for the pair search grid,
694      * which the pair search code tries to achieve.
695      * Note that in practice particle distances will not be delta distributed,
696      * but have some spread, often involving shorter distances,
697      * as e.g. O-H bonds in a water molecule. Thus the estimates below will
698      * usually be slightly too high and thus conservative.
699      */
700     switch (cluster_size)
701     {
702         case 1:
703             /* One particle: trivial */
704             area_rel = 1.0;
705             break;
706         case 2:
707             /* Two particles: two spheres at fractional distance 2*a */
708             area_rel = 1.0 + d;
709             break;
710         case 4:
711             /* We assume a perfect, symmetric tetrahedron geometry.
712              * The surface around a tetrahedron is too complex for a full
713              * analytical solution, so we use a Taylor expansion.
714              */
715             area_rel = (1.0 + 1/M_PI*(6*acos(1/sqrt(3))*d +
716                                       sqrt(3)*d*d*(1.0 +
717                                                    5.0/18.0*d*d +
718                                                    7.0/45.0*d*d*d*d +
719                                                    83.0/756.0*d*d*d*d*d*d)));
720             break;
721         default:
722             gmx_incons("surface_frac called with unsupported cluster_size");
723             area_rel = 1.0;
724     }
725
726     return area_rel/cluster_size;
727 }
728
729 /* Returns the negative of the third derivative of a potential r^-p
730  * with a force-switch function, evaluated at the cut-off rc.
731  */
732 static real md3_force_switch(real p, real rswitch, real rc)
733 {
734     /* The switched force function is:
735      * p*r^-(p+1) + a*(r - rswitch)^2 + b*(r - rswitch)^3
736      */
737     real a, b;
738     real md3_pot, md3_sw;
739
740     a = -((p + 4)*rc - (p + 1)*rswitch)/(pow(rc, p+2)*pow(rc-rswitch, 2));
741     b =  ((p + 3)*rc - (p + 1)*rswitch)/(pow(rc, p+2)*pow(rc-rswitch, 3));
742
743     md3_pot = (p + 2)*(p + 1)*p*pow(rc, p+3);
744     md3_sw  = 2*a + 6*b*(rc - rswitch);
745
746     return md3_pot + md3_sw;
747 }
748
749 void calc_verlet_buffer_size(const gmx_mtop_t *mtop, real boxvol,
750                              const t_inputrec *ir,
751                              real reference_temperature,
752                              const verletbuf_list_setup_t *list_setup,
753                              int *n_nonlin_vsite,
754                              real *rlist)
755 {
756     double                resolution;
757     char                 *env;
758
759     real                  particle_distance;
760     real                  nb_clust_frac_pairs_not_in_list_at_cutoff;
761
762     verletbuf_atomtype_t *att  = NULL;
763     int                   natt = -1, i;
764     double                reppow;
765     real                  md1_ljd, d2_ljd, md3_ljd;
766     real                  md1_ljr, d2_ljr, md3_ljr;
767     real                  md1_el,  d2_el;
768     real                  elfac;
769     real                  kT_fac, mass_min;
770     int                   ib0, ib1, ib;
771     real                  rb, rl;
772     real                  drift;
773
774     if (reference_temperature < 0)
775     {
776         if (EI_MD(ir->eI) && ir->etc == etcNO)
777         {
778             /* This case should be handled outside calc_verlet_buffer_size */
779             gmx_incons("calc_verlet_buffer_size called with an NVE ensemble and reference_temperature < 0");
780         }
781
782         /* We use the maximum temperature with multiple T-coupl groups.
783          * We could use a per particle temperature, but since particles
784          * interact, this might underestimate the buffer size.
785          */
786         reference_temperature = 0;
787         for (i = 0; i < ir->opts.ngtc; i++)
788         {
789             if (ir->opts.tau_t[i] >= 0)
790             {
791                 reference_temperature = max(reference_temperature,
792                                             ir->opts.ref_t[i]);
793             }
794         }
795     }
796
797     /* Resolution of the buffer size */
798     resolution = 0.001;
799
800     env = getenv("GMX_VERLET_BUFFER_RES");
801     if (env != NULL)
802     {
803         sscanf(env, "%lf", &resolution);
804     }
805
806     /* In an atom wise pair-list there would be no pairs in the list
807      * beyond the pair-list cut-off.
808      * However, we use a pair-list of groups vs groups of atoms.
809      * For groups of 4 atoms, the parallelism of SSE instructions, only
810      * 10% of the atoms pairs are not in the list just beyond the cut-off.
811      * As this percentage increases slowly compared to the decrease of the
812      * Gaussian displacement distribution over this range, we can simply
813      * reduce the drift by this fraction.
814      * For larger groups, e.g. of 8 atoms, this fraction will be lower,
815      * so then buffer size will be on the conservative (large) side.
816      *
817      * Note that the formulas used here do not take into account
818      * cancellation of errors which could occur by missing both
819      * attractive and repulsive interactions.
820      *
821      * The only major assumption is homogeneous particle distribution.
822      * For an inhomogeneous system, such as a liquid-vapor system,
823      * the buffer will be underestimated. The actual energy drift
824      * will be higher by the factor: local/homogeneous particle density.
825      *
826      * The results of this estimate have been checked againt simulations.
827      * In most cases the real drift differs by less than a factor 2.
828      */
829
830     /* Worst case assumption: HCP packing of particles gives largest distance */
831     particle_distance = pow(boxvol*sqrt(2)/mtop->natoms, 1.0/3.0);
832
833     get_verlet_buffer_atomtypes(mtop, &att, &natt, n_nonlin_vsite);
834     assert(att != NULL && natt >= 0);
835
836     if (debug)
837     {
838         fprintf(debug, "particle distance assuming HCP packing: %f nm\n",
839                 particle_distance);
840         fprintf(debug, "energy drift atom types: %d\n", natt);
841     }
842
843     reppow   = mtop->ffparams.reppow;
844     md1_ljd  = 0;
845     d2_ljd   = 0;
846     md3_ljd  = 0;
847     md1_ljr  = 0;
848     d2_ljr   = 0;
849     md3_ljr  = 0;
850     if (ir->vdwtype == evdwCUT)
851     {
852         real sw_range, md3_pswf;
853
854         switch (ir->vdw_modifier)
855         {
856             case eintmodNONE:
857             case eintmodPOTSHIFT:
858                 /* -dV/dr of -r^-6 and r^-reppow */
859                 md1_ljd =     -6*pow(ir->rvdw, -7.0);
860                 md1_ljr = reppow*pow(ir->rvdw, -(reppow+1));
861                 /* The contribution of the higher derivatives is negligible */
862                 break;
863             case eintmodFORCESWITCH:
864                 /* At the cut-off: V=V'=V''=0, so we use only V''' */
865                 md3_ljd  = -md3_force_switch(6.0,    ir->rvdw_switch, ir->rvdw);
866                 md3_ljr  =  md3_force_switch(reppow, ir->rvdw_switch, ir->rvdw);
867                 break;
868             case eintmodPOTSWITCH:
869                 /* At the cut-off: V=V'=V''=0.
870                  * V''' is given by the original potential times
871                  * the third derivative of the switch function.
872                  */
873                 sw_range  = ir->rvdw - ir->rvdw_switch;
874                 md3_pswf  = 60.0*pow(sw_range, -3.0);
875
876                 md3_ljd   = -pow(ir->rvdw, -6.0   )*md3_pswf;
877                 md3_ljr   =  pow(ir->rvdw, -reppow)*md3_pswf;
878                 break;
879             default:
880                 gmx_incons("Unimplemented VdW modifier");
881         }
882     }
883     else if (EVDW_PME(ir->vdwtype))
884     {
885         real b, r, br, br2, br4, br6;
886         b        = calc_ewaldcoeff_lj(ir->rvdw, ir->ewald_rtol_lj);
887         r        = ir->rvdw;
888         br       = b*r;
889         br2      = br*br;
890         br4      = br2*br2;
891         br6      = br4*br2;
892         /* -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 */
893         md1_ljd  = -exp(-br2)*(br6 + 3.0*br4 + 6.0*br2 + 6.0)*pow(r, -7.0);
894         md1_ljr  = reppow*pow(r, -(reppow+1));
895         /* The contribution of the higher derivatives is negligible */
896     }
897     else
898     {
899         gmx_fatal(FARGS, "Energy drift calculation is only implemented for plain cut-off Lennard-Jones interactions");
900     }
901
902     elfac = ONE_4PI_EPS0/ir->epsilon_r;
903
904     /* Determine md=-dV/dr and dd=d^2V/dr^2 */
905     md1_el = 0;
906     d2_el  = 0;
907     if (ir->coulombtype == eelCUT || EEL_RF(ir->coulombtype))
908     {
909         real eps_rf, k_rf;
910
911         if (ir->coulombtype == eelCUT)
912         {
913             eps_rf = 1;
914             k_rf   = 0;
915         }
916         else
917         {
918             eps_rf = ir->epsilon_rf/ir->epsilon_r;
919             if (eps_rf != 0)
920             {
921                 k_rf = pow(ir->rcoulomb, -3.0)*(eps_rf - ir->epsilon_r)/(2*eps_rf + ir->epsilon_r);
922             }
923             else
924             {
925                 /* epsilon_rf = infinity */
926                 k_rf = 0.5*pow(ir->rcoulomb, -3.0);
927             }
928         }
929
930         if (eps_rf > 0)
931         {
932             md1_el = elfac*(pow(ir->rcoulomb, -2.0) - 2*k_rf*ir->rcoulomb);
933         }
934         d2_el      = elfac*(2*pow(ir->rcoulomb, -3.0) + 2*k_rf);
935     }
936     else if (EEL_PME(ir->coulombtype) || ir->coulombtype == eelEWALD)
937     {
938         real b, rc, br;
939
940         b      = calc_ewaldcoeff_q(ir->rcoulomb, ir->ewald_rtol);
941         rc     = ir->rcoulomb;
942         br     = b*rc;
943         md1_el = elfac*(b*exp(-br*br)*M_2_SQRTPI/rc + gmx_erfc(br)/(rc*rc));
944         d2_el  = elfac/(rc*rc)*(2*b*(1 + br*br)*exp(-br*br)*M_2_SQRTPI + 2*gmx_erfc(br)/rc);
945     }
946     else
947     {
948         gmx_fatal(FARGS, "Energy drift calculation is only implemented for Reaction-Field and Ewald electrostatics");
949     }
950
951     /* Determine the variance of the atomic displacement
952      * over nstlist-1 steps: kT_fac
953      * For inertial dynamics (not Brownian dynamics) the mass factor
954      * is not included in kT_fac, it is added later.
955      */
956     if (ir->eI == eiBD)
957     {
958         /* Get the displacement distribution from the random component only.
959          * With accurate integration the systematic (force) displacement
960          * should be negligible (unless nstlist is extremely large, which
961          * you wouldn't do anyhow).
962          */
963         kT_fac = 2*BOLTZ*reference_temperature*(ir->nstlist-1)*ir->delta_t;
964         if (ir->bd_fric > 0)
965         {
966             /* This is directly sigma^2 of the displacement */
967             kT_fac /= ir->bd_fric;
968
969             /* Set the masses to 1 as kT_fac is the full sigma^2,
970              * but we divide by m in ener_drift().
971              */
972             for (i = 0; i < natt; i++)
973             {
974                 att[i].prop.mass = 1;
975             }
976         }
977         else
978         {
979             real tau_t;
980
981             /* Per group tau_t is not implemented yet, use the maximum */
982             tau_t = ir->opts.tau_t[0];
983             for (i = 1; i < ir->opts.ngtc; i++)
984             {
985                 tau_t = max(tau_t, ir->opts.tau_t[i]);
986             }
987
988             kT_fac *= tau_t;
989             /* This kT_fac needs to be divided by the mass to get sigma^2 */
990         }
991     }
992     else
993     {
994         kT_fac = BOLTZ*reference_temperature*sqr((ir->nstlist-1)*ir->delta_t);
995     }
996
997     mass_min = att[0].prop.mass;
998     for (i = 1; i < natt; i++)
999     {
1000         mass_min = min(mass_min, att[i].prop.mass);
1001     }
1002
1003     if (debug)
1004     {
1005         fprintf(debug, "md1_ljd %9.2e d2_ljd %9.2e md3_ljd %9.2e\n", md1_ljd, d2_ljd, md3_ljd);
1006         fprintf(debug, "md1_ljr %9.2e d2_ljr %9.2e md3_ljr %9.2e\n", md1_ljr, d2_ljr, md3_ljr);
1007         fprintf(debug, "md1_el  %9.2e d2_el  %9.2e\n", md1_el, d2_el);
1008         fprintf(debug, "sqrt(kT_fac) %f\n", sqrt(kT_fac));
1009         fprintf(debug, "mass_min %f\n", mass_min);
1010     }
1011
1012     /* Search using bisection */
1013     ib0 = -1;
1014     /* The drift will be neglible at 5 times the max sigma */
1015     ib1 = (int)(5*2*sqrt(kT_fac/mass_min)/resolution) + 1;
1016     while (ib1 - ib0 > 1)
1017     {
1018         ib = (ib0 + ib1)/2;
1019         rb = ib*resolution;
1020         rl = max(ir->rvdw, ir->rcoulomb) + rb;
1021
1022         /* Calculate the average energy drift at the last step
1023          * of the nstlist steps at which the pair-list is used.
1024          */
1025         drift = ener_drift(att, natt, &mtop->ffparams,
1026                            kT_fac,
1027                            md1_ljd, d2_ljd, md3_ljd,
1028                            md1_ljr, d2_ljr, md3_ljr,
1029                            md1_el,  d2_el,
1030                            rb,
1031                            rl, boxvol);
1032
1033         /* Correct for the fact that we are using a Ni x Nj particle pair list
1034          * and not a 1 x 1 particle pair list. This reduces the drift.
1035          */
1036         /* We don't have a formula for 8 (yet), use 4 which is conservative */
1037         nb_clust_frac_pairs_not_in_list_at_cutoff =
1038             surface_frac(min(list_setup->cluster_size_i, 4),
1039                          particle_distance, rl)*
1040             surface_frac(min(list_setup->cluster_size_j, 4),
1041                          particle_distance, rl);
1042         drift *= nb_clust_frac_pairs_not_in_list_at_cutoff;
1043
1044         /* Convert the drift to drift per unit time per atom */
1045         drift /= ir->nstlist*ir->delta_t*mtop->natoms;
1046
1047         if (debug)
1048         {
1049             fprintf(debug, "ib %3d %3d %3d rb %.3f %dx%d fac %.3f drift %f\n",
1050                     ib0, ib, ib1, rb,
1051                     list_setup->cluster_size_i, list_setup->cluster_size_j,
1052                     nb_clust_frac_pairs_not_in_list_at_cutoff,
1053                     drift);
1054         }
1055
1056         if (fabs(drift) > ir->verletbuf_tol)
1057         {
1058             ib0 = ib;
1059         }
1060         else
1061         {
1062             ib1 = ib;
1063         }
1064     }
1065
1066     sfree(att);
1067
1068     *rlist = max(ir->rvdw, ir->rcoulomb) + ib1*resolution;
1069 }