ae662ec467d8eb5e97ba585f84d3fa04ec830cc2
[alexxy/gromacs.git] / src / gromacs / mdlib / forcerec.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014,2015,2016, by the GROMACS development team, led by
7  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8  * and including many others, as listed in the AUTHORS file in the
9  * top-level source directory and at http://www.gromacs.org.
10  *
11  * GROMACS is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the License, or (at your option) any later version.
15  *
16  * GROMACS is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with GROMACS; if not, see
23  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
25  *
26  * If you want to redistribute modifications to GROMACS, please
27  * consider that scientific software is very special. Version
28  * control is crucial - bugs must be traceable. We will be happy to
29  * consider code for inclusion in the official distribution, but
30  * derived work must not be called official GROMACS. Details are found
31  * in the README & COPYING files - if they are missing, get the
32  * official version at http://www.gromacs.org.
33  *
34  * To help us fund GROMACS development, we humbly ask that you cite
35  * the research papers on the package. Check out http://www.gromacs.org.
36  */
37 #include "gmxpre.h"
38
39 #include "forcerec.h"
40
41 #include "config.h"
42
43 #include <assert.h>
44 #include <stdlib.h>
45 #include <string.h>
46
47 #include <cmath>
48
49 #include <algorithm>
50
51 #include "gromacs/commandline/filenm.h"
52 #include "gromacs/domdec/domdec.h"
53 #include "gromacs/domdec/domdec_struct.h"
54 #include "gromacs/ewald/ewald.h"
55 #include "gromacs/fileio/filetypes.h"
56 #include "gromacs/gmxlib/network.h"
57 #include "gromacs/gmxlib/nonbonded/nonbonded.h"
58 #include "gromacs/gpu_utils/gpu_utils.h"
59 #include "gromacs/hardware/detecthardware.h"
60 #include "gromacs/listed-forces/manage-threading.h"
61 #include "gromacs/listed-forces/pairs.h"
62 #include "gromacs/math/calculate-ewald-splitting-coefficient.h"
63 #include "gromacs/math/functions.h"
64 #include "gromacs/math/units.h"
65 #include "gromacs/math/utilities.h"
66 #include "gromacs/math/vec.h"
67 #include "gromacs/mdlib/force.h"
68 #include "gromacs/mdlib/forcerec-threading.h"
69 #include "gromacs/mdlib/gmx_omp_nthreads.h"
70 #include "gromacs/mdlib/md_support.h"
71 #include "gromacs/mdlib/nb_verlet.h"
72 #include "gromacs/mdlib/nbnxn_atomdata.h"
73 #include "gromacs/mdlib/nbnxn_gpu_data_mgmt.h"
74 #include "gromacs/mdlib/nbnxn_search.h"
75 #include "gromacs/mdlib/nbnxn_simd.h"
76 #include "gromacs/mdlib/nbnxn_util.h"
77 #include "gromacs/mdlib/ns.h"
78 #include "gromacs/mdlib/qmmm.h"
79 #include "gromacs/mdlib/sim_util.h"
80 #include "gromacs/mdtypes/commrec.h"
81 #include "gromacs/mdtypes/fcdata.h"
82 #include "gromacs/mdtypes/group.h"
83 #include "gromacs/mdtypes/inputrec.h"
84 #include "gromacs/mdtypes/md_enums.h"
85 #include "gromacs/pbcutil/ishift.h"
86 #include "gromacs/pbcutil/pbc.h"
87 #include "gromacs/simd/simd.h"
88 #include "gromacs/tables/forcetable.h"
89 #include "gromacs/topology/mtop_util.h"
90 #include "gromacs/trajectory/trajectoryframe.h"
91 #include "gromacs/utility/cstringutil.h"
92 #include "gromacs/utility/exceptions.h"
93 #include "gromacs/utility/fatalerror.h"
94 #include "gromacs/utility/gmxassert.h"
95 #include "gromacs/utility/logger.h"
96 #include "gromacs/utility/pleasecite.h"
97 #include "gromacs/utility/smalloc.h"
98 #include "gromacs/utility/stringutil.h"
99
100 #include "nbnxn_gpu_jit_support.h"
101
102 const char *egrp_nm[egNR+1] = {
103     "Coul-SR", "LJ-SR", "Buck-SR",
104     "Coul-14", "LJ-14", NULL
105 };
106
107 t_forcerec *mk_forcerec(void)
108 {
109     t_forcerec *fr;
110
111     snew(fr, 1);
112
113     return fr;
114 }
115
116 #ifdef DEBUG
117 static void pr_nbfp(FILE *fp, real *nbfp, gmx_bool bBHAM, int atnr)
118 {
119     int i, j;
120
121     for (i = 0; (i < atnr); i++)
122     {
123         for (j = 0; (j < atnr); j++)
124         {
125             fprintf(fp, "%2d - %2d", i, j);
126             if (bBHAM)
127             {
128                 fprintf(fp, "  a=%10g, b=%10g, c=%10g\n", BHAMA(nbfp, atnr, i, j),
129                         BHAMB(nbfp, atnr, i, j), BHAMC(nbfp, atnr, i, j)/6.0);
130             }
131             else
132             {
133                 fprintf(fp, "  c6=%10g, c12=%10g\n", C6(nbfp, atnr, i, j)/6.0,
134                         C12(nbfp, atnr, i, j)/12.0);
135             }
136         }
137     }
138 }
139 #endif
140
141 static real *mk_nbfp(const gmx_ffparams_t *idef, gmx_bool bBHAM)
142 {
143     real *nbfp;
144     int   i, j, k, atnr;
145
146     atnr = idef->atnr;
147     if (bBHAM)
148     {
149         snew(nbfp, 3*atnr*atnr);
150         for (i = k = 0; (i < atnr); i++)
151         {
152             for (j = 0; (j < atnr); j++, k++)
153             {
154                 BHAMA(nbfp, atnr, i, j) = idef->iparams[k].bham.a;
155                 BHAMB(nbfp, atnr, i, j) = idef->iparams[k].bham.b;
156                 /* nbfp now includes the 6.0 derivative prefactor */
157                 BHAMC(nbfp, atnr, i, j) = idef->iparams[k].bham.c*6.0;
158             }
159         }
160     }
161     else
162     {
163         snew(nbfp, 2*atnr*atnr);
164         for (i = k = 0; (i < atnr); i++)
165         {
166             for (j = 0; (j < atnr); j++, k++)
167             {
168                 /* nbfp now includes the 6.0/12.0 derivative prefactors */
169                 C6(nbfp, atnr, i, j)   = idef->iparams[k].lj.c6*6.0;
170                 C12(nbfp, atnr, i, j)  = idef->iparams[k].lj.c12*12.0;
171             }
172         }
173     }
174
175     return nbfp;
176 }
177
178 static real *make_ljpme_c6grid(const gmx_ffparams_t *idef, t_forcerec *fr)
179 {
180     int        i, j, k, atnr;
181     real       c6, c6i, c6j, c12i, c12j, epsi, epsj, sigmai, sigmaj;
182     real      *grid;
183
184     /* For LJ-PME simulations, we correct the energies with the reciprocal space
185      * inside of the cut-off. To do this the non-bonded kernels needs to have
186      * access to the C6-values used on the reciprocal grid in pme.c
187      */
188
189     atnr = idef->atnr;
190     snew(grid, 2*atnr*atnr);
191     for (i = k = 0; (i < atnr); i++)
192     {
193         for (j = 0; (j < atnr); j++, k++)
194         {
195             c6i  = idef->iparams[i*(atnr+1)].lj.c6;
196             c12i = idef->iparams[i*(atnr+1)].lj.c12;
197             c6j  = idef->iparams[j*(atnr+1)].lj.c6;
198             c12j = idef->iparams[j*(atnr+1)].lj.c12;
199             c6   = std::sqrt(c6i * c6j);
200             if (fr->ljpme_combination_rule == eljpmeLB
201                 && !gmx_numzero(c6) && !gmx_numzero(c12i) && !gmx_numzero(c12j))
202             {
203                 sigmai = gmx::sixthroot(c12i / c6i);
204                 sigmaj = gmx::sixthroot(c12j / c6j);
205                 epsi   = c6i * c6i / c12i;
206                 epsj   = c6j * c6j / c12j;
207                 c6     = std::sqrt(epsi * epsj) * gmx::power6(0.5*(sigmai+sigmaj));
208             }
209             /* Store the elements at the same relative positions as C6 in nbfp in order
210              * to simplify access in the kernels
211              */
212             grid[2*(atnr*i+j)] = c6*6.0;
213         }
214     }
215     return grid;
216 }
217
218 static real *mk_nbfp_combination_rule(const gmx_ffparams_t *idef, int comb_rule)
219 {
220     real      *nbfp;
221     int        i, j, atnr;
222     real       c6i, c6j, c12i, c12j, epsi, epsj, sigmai, sigmaj;
223     real       c6, c12;
224
225     atnr = idef->atnr;
226     snew(nbfp, 2*atnr*atnr);
227     for (i = 0; i < atnr; ++i)
228     {
229         for (j = 0; j < atnr; ++j)
230         {
231             c6i  = idef->iparams[i*(atnr+1)].lj.c6;
232             c12i = idef->iparams[i*(atnr+1)].lj.c12;
233             c6j  = idef->iparams[j*(atnr+1)].lj.c6;
234             c12j = idef->iparams[j*(atnr+1)].lj.c12;
235             c6   = std::sqrt(c6i  * c6j);
236             c12  = std::sqrt(c12i * c12j);
237             if (comb_rule == eCOMB_ARITHMETIC
238                 && !gmx_numzero(c6) && !gmx_numzero(c12))
239             {
240                 sigmai = gmx::sixthroot(c12i / c6i);
241                 sigmaj = gmx::sixthroot(c12j / c6j);
242                 epsi   = c6i * c6i / c12i;
243                 epsj   = c6j * c6j / c12j;
244                 c6     = std::sqrt(epsi * epsj) * gmx::power6(0.5*(sigmai+sigmaj));
245                 c12    = std::sqrt(epsi * epsj) * gmx::power12(0.5*(sigmai+sigmaj));
246             }
247             C6(nbfp, atnr, i, j)   = c6*6.0;
248             C12(nbfp, atnr, i, j)  = c12*12.0;
249         }
250     }
251     return nbfp;
252 }
253
254 /* This routine sets fr->solvent_opt to the most common solvent in the
255  * system, e.g. esolSPC or esolTIP4P. It will also mark each charge group in
256  * the fr->solvent_type array with the correct type (or esolNO).
257  *
258  * Charge groups that fulfill the conditions but are not identical to the
259  * most common one will be marked as esolNO in the solvent_type array.
260  *
261  * TIP3p is identical to SPC for these purposes, so we call it
262  * SPC in the arrays (Apologies to Bill Jorgensen ;-)
263  *
264  * NOTE: QM particle should not
265  * become an optimized solvent. Not even if there is only one charge
266  * group in the Qm
267  */
268
269 typedef struct
270 {
271     int    model;
272     int    count;
273     int    vdwtype[4];
274     real   charge[4];
275 } solvent_parameters_t;
276
277 static void
278 check_solvent_cg(const gmx_moltype_t    *molt,
279                  int                     cg0,
280                  int                     nmol,
281                  const unsigned char    *qm_grpnr,
282                  const t_grps           *qm_grps,
283                  t_forcerec   *          fr,
284                  int                    *n_solvent_parameters,
285                  solvent_parameters_t  **solvent_parameters_p,
286                  int                     cginfo,
287                  int                    *cg_sp)
288 {
289     t_atom               *atom;
290     int                   j, k;
291     int                   j0, j1, nj;
292     gmx_bool              perturbed;
293     gmx_bool              has_vdw[4];
294     gmx_bool              match;
295     real                  tmp_charge[4]  = { 0.0 }; /* init to zero to make gcc4.8 happy */
296     int                   tmp_vdwtype[4] = { 0 };   /* init to zero to make gcc4.8 happy */
297     int                   tjA;
298     gmx_bool              qm;
299     solvent_parameters_t *solvent_parameters;
300
301     /* We use a list with parameters for each solvent type.
302      * Every time we discover a new molecule that fulfills the basic
303      * conditions for a solvent we compare with the previous entries
304      * in these lists. If the parameters are the same we just increment
305      * the counter for that type, and otherwise we create a new type
306      * based on the current molecule.
307      *
308      * Once we've finished going through all molecules we check which
309      * solvent is most common, and mark all those molecules while we
310      * clear the flag on all others.
311      */
312
313     solvent_parameters = *solvent_parameters_p;
314
315     /* Mark the cg first as non optimized */
316     *cg_sp = -1;
317
318     /* Check if this cg has no exclusions with atoms in other charge groups
319      * and all atoms inside the charge group excluded.
320      * We only have 3 or 4 atom solvent loops.
321      */
322     if (GET_CGINFO_EXCL_INTER(cginfo) ||
323         !GET_CGINFO_EXCL_INTRA(cginfo))
324     {
325         return;
326     }
327
328     /* Get the indices of the first atom in this charge group */
329     j0     = molt->cgs.index[cg0];
330     j1     = molt->cgs.index[cg0+1];
331
332     /* Number of atoms in our molecule */
333     nj     = j1 - j0;
334
335     if (debug)
336     {
337         fprintf(debug,
338                 "Moltype '%s': there are %d atoms in this charge group\n",
339                 *molt->name, nj);
340     }
341
342     /* Check if it could be an SPC (3 atoms) or TIP4p (4) water,
343      * otherwise skip it.
344      */
345     if (nj < 3 || nj > 4)
346     {
347         return;
348     }
349
350     /* Check if we are doing QM on this group */
351     qm = FALSE;
352     if (qm_grpnr != NULL)
353     {
354         for (j = j0; j < j1 && !qm; j++)
355         {
356             qm = (qm_grpnr[j] < qm_grps->nr - 1);
357         }
358     }
359     /* Cannot use solvent optimization with QM */
360     if (qm)
361     {
362         return;
363     }
364
365     atom = molt->atoms.atom;
366
367     /* Still looks like a solvent, time to check parameters */
368
369     /* If it is perturbed (free energy) we can't use the solvent loops,
370      * so then we just skip to the next molecule.
371      */
372     perturbed = FALSE;
373
374     for (j = j0; j < j1 && !perturbed; j++)
375     {
376         perturbed = PERTURBED(atom[j]);
377     }
378
379     if (perturbed)
380     {
381         return;
382     }
383
384     /* Now it's only a question if the VdW and charge parameters
385      * are OK. Before doing the check we compare and see if they are
386      * identical to a possible previous solvent type.
387      * First we assign the current types and charges.
388      */
389     for (j = 0; j < nj; j++)
390     {
391         tmp_vdwtype[j] = atom[j0+j].type;
392         tmp_charge[j]  = atom[j0+j].q;
393     }
394
395     /* Does it match any previous solvent type? */
396     for (k = 0; k < *n_solvent_parameters; k++)
397     {
398         match = TRUE;
399
400
401         /* We can only match SPC with 3 atoms and TIP4p with 4 atoms */
402         if ( (solvent_parameters[k].model == esolSPC   && nj != 3)  ||
403              (solvent_parameters[k].model == esolTIP4P && nj != 4) )
404         {
405             match = FALSE;
406         }
407
408         /* Check that types & charges match for all atoms in molecule */
409         for (j = 0; j < nj && match == TRUE; j++)
410         {
411             if (tmp_vdwtype[j] != solvent_parameters[k].vdwtype[j])
412             {
413                 match = FALSE;
414             }
415             if (tmp_charge[j] != solvent_parameters[k].charge[j])
416             {
417                 match = FALSE;
418             }
419         }
420         if (match == TRUE)
421         {
422             /* Congratulations! We have a matched solvent.
423              * Flag it with this type for later processing.
424              */
425             *cg_sp = k;
426             solvent_parameters[k].count += nmol;
427
428             /* We are done with this charge group */
429             return;
430         }
431     }
432
433     /* If we get here, we have a tentative new solvent type.
434      * Before we add it we must check that it fulfills the requirements
435      * of the solvent optimized loops. First determine which atoms have
436      * VdW interactions.
437      */
438     for (j = 0; j < nj; j++)
439     {
440         has_vdw[j] = FALSE;
441         tjA        = tmp_vdwtype[j];
442
443         /* Go through all other tpes and see if any have non-zero
444          * VdW parameters when combined with this one.
445          */
446         for (k = 0; k < fr->ntype && (has_vdw[j] == FALSE); k++)
447         {
448             /* We already checked that the atoms weren't perturbed,
449              * so we only need to check state A now.
450              */
451             if (fr->bBHAM)
452             {
453                 has_vdw[j] = (has_vdw[j] ||
454                               (BHAMA(fr->nbfp, fr->ntype, tjA, k) != 0.0) ||
455                               (BHAMB(fr->nbfp, fr->ntype, tjA, k) != 0.0) ||
456                               (BHAMC(fr->nbfp, fr->ntype, tjA, k) != 0.0));
457             }
458             else
459             {
460                 /* Standard LJ */
461                 has_vdw[j] = (has_vdw[j] ||
462                               (C6(fr->nbfp, fr->ntype, tjA, k)  != 0.0) ||
463                               (C12(fr->nbfp, fr->ntype, tjA, k) != 0.0));
464             }
465         }
466     }
467
468     /* Now we know all we need to make the final check and assignment. */
469     if (nj == 3)
470     {
471         /* So, is it an SPC?
472          * For this we require thatn all atoms have charge,
473          * the charges on atom 2 & 3 should be the same, and only
474          * atom 1 might have VdW.
475          */
476         if (has_vdw[1] == FALSE &&
477             has_vdw[2] == FALSE &&
478             tmp_charge[0]  != 0 &&
479             tmp_charge[1]  != 0 &&
480             tmp_charge[2]  == tmp_charge[1])
481         {
482             srenew(solvent_parameters, *n_solvent_parameters+1);
483             solvent_parameters[*n_solvent_parameters].model = esolSPC;
484             solvent_parameters[*n_solvent_parameters].count = nmol;
485             for (k = 0; k < 3; k++)
486             {
487                 solvent_parameters[*n_solvent_parameters].vdwtype[k] = tmp_vdwtype[k];
488                 solvent_parameters[*n_solvent_parameters].charge[k]  = tmp_charge[k];
489             }
490
491             *cg_sp = *n_solvent_parameters;
492             (*n_solvent_parameters)++;
493         }
494     }
495     else if (nj == 4)
496     {
497         /* Or could it be a TIP4P?
498          * For this we require thatn atoms 2,3,4 have charge, but not atom 1.
499          * Only atom 1 mght have VdW.
500          */
501         if (has_vdw[1] == FALSE &&
502             has_vdw[2] == FALSE &&
503             has_vdw[3] == FALSE &&
504             tmp_charge[0]  == 0 &&
505             tmp_charge[1]  != 0 &&
506             tmp_charge[2]  == tmp_charge[1] &&
507             tmp_charge[3]  != 0)
508         {
509             srenew(solvent_parameters, *n_solvent_parameters+1);
510             solvent_parameters[*n_solvent_parameters].model = esolTIP4P;
511             solvent_parameters[*n_solvent_parameters].count = nmol;
512             for (k = 0; k < 4; k++)
513             {
514                 solvent_parameters[*n_solvent_parameters].vdwtype[k] = tmp_vdwtype[k];
515                 solvent_parameters[*n_solvent_parameters].charge[k]  = tmp_charge[k];
516             }
517
518             *cg_sp = *n_solvent_parameters;
519             (*n_solvent_parameters)++;
520         }
521     }
522
523     *solvent_parameters_p = solvent_parameters;
524 }
525
526 static void
527 check_solvent(FILE  *                fp,
528               const gmx_mtop_t  *    mtop,
529               t_forcerec  *          fr,
530               cginfo_mb_t           *cginfo_mb)
531 {
532     const t_block     *   cgs;
533     const gmx_moltype_t  *molt;
534     int                   mb, mol, cg_mol, at_offset, am, cgm, i, nmol_ch, nmol;
535     int                   n_solvent_parameters;
536     solvent_parameters_t *solvent_parameters;
537     int                 **cg_sp;
538     int                   bestsp, bestsol;
539
540     if (debug)
541     {
542         fprintf(debug, "Going to determine what solvent types we have.\n");
543     }
544
545     n_solvent_parameters = 0;
546     solvent_parameters   = NULL;
547     /* Allocate temporary array for solvent type */
548     snew(cg_sp, mtop->nmolblock);
549
550     at_offset = 0;
551     for (mb = 0; mb < mtop->nmolblock; mb++)
552     {
553         molt = &mtop->moltype[mtop->molblock[mb].type];
554         cgs  = &molt->cgs;
555         /* Here we have to loop over all individual molecules
556          * because we need to check for QMMM particles.
557          */
558         snew(cg_sp[mb], cginfo_mb[mb].cg_mod);
559         nmol_ch = cginfo_mb[mb].cg_mod/cgs->nr;
560         nmol    = mtop->molblock[mb].nmol/nmol_ch;
561         for (mol = 0; mol < nmol_ch; mol++)
562         {
563             cgm = mol*cgs->nr;
564             am  = mol*cgs->index[cgs->nr];
565             for (cg_mol = 0; cg_mol < cgs->nr; cg_mol++)
566             {
567                 check_solvent_cg(molt, cg_mol, nmol,
568                                  mtop->groups.grpnr[egcQMMM] ?
569                                  mtop->groups.grpnr[egcQMMM]+at_offset+am : 0,
570                                  &mtop->groups.grps[egcQMMM],
571                                  fr,
572                                  &n_solvent_parameters, &solvent_parameters,
573                                  cginfo_mb[mb].cginfo[cgm+cg_mol],
574                                  &cg_sp[mb][cgm+cg_mol]);
575             }
576         }
577         at_offset += cgs->index[cgs->nr];
578     }
579
580     /* Puh! We finished going through all charge groups.
581      * Now find the most common solvent model.
582      */
583
584     /* Most common solvent this far */
585     bestsp = -2;
586     for (i = 0; i < n_solvent_parameters; i++)
587     {
588         if (bestsp == -2 ||
589             solvent_parameters[i].count > solvent_parameters[bestsp].count)
590         {
591             bestsp = i;
592         }
593     }
594
595     if (bestsp >= 0)
596     {
597         bestsol = solvent_parameters[bestsp].model;
598     }
599     else
600     {
601         bestsol = esolNO;
602     }
603
604     fr->nWatMol = 0;
605     for (mb = 0; mb < mtop->nmolblock; mb++)
606     {
607         cgs  = &mtop->moltype[mtop->molblock[mb].type].cgs;
608         nmol = (mtop->molblock[mb].nmol*cgs->nr)/cginfo_mb[mb].cg_mod;
609         for (i = 0; i < cginfo_mb[mb].cg_mod; i++)
610         {
611             if (cg_sp[mb][i] == bestsp)
612             {
613                 SET_CGINFO_SOLOPT(cginfo_mb[mb].cginfo[i], bestsol);
614                 fr->nWatMol += nmol;
615             }
616             else
617             {
618                 SET_CGINFO_SOLOPT(cginfo_mb[mb].cginfo[i], esolNO);
619             }
620         }
621         sfree(cg_sp[mb]);
622     }
623     sfree(cg_sp);
624
625     if (bestsol != esolNO && fp != NULL)
626     {
627         fprintf(fp, "\nEnabling %s-like water optimization for %d molecules.\n\n",
628                 esol_names[bestsol],
629                 solvent_parameters[bestsp].count);
630     }
631
632     sfree(solvent_parameters);
633     fr->solvent_opt = bestsol;
634 }
635
636 enum {
637     acNONE = 0, acCONSTRAINT, acSETTLE
638 };
639
640 static cginfo_mb_t *init_cginfo_mb(FILE *fplog, const gmx_mtop_t *mtop,
641                                    t_forcerec *fr, gmx_bool bNoSolvOpt,
642                                    gmx_bool *bFEP_NonBonded,
643                                    gmx_bool *bExcl_IntraCGAll_InterCGNone)
644 {
645     const t_block        *cgs;
646     const t_blocka       *excl;
647     const gmx_moltype_t  *molt;
648     const gmx_molblock_t *molb;
649     cginfo_mb_t          *cginfo_mb;
650     gmx_bool             *type_VDW;
651     int                  *cginfo;
652     int                   cg_offset, a_offset;
653     int                   mb, m, cg, a0, a1, gid, ai, j, aj, excl_nalloc;
654     int                  *a_con;
655     int                   ftype;
656     int                   ia;
657     gmx_bool              bId, *bExcl, bExclIntraAll, bExclInter, bHaveVDW, bHaveQ, bHavePerturbedAtoms;
658
659     snew(cginfo_mb, mtop->nmolblock);
660
661     snew(type_VDW, fr->ntype);
662     for (ai = 0; ai < fr->ntype; ai++)
663     {
664         type_VDW[ai] = FALSE;
665         for (j = 0; j < fr->ntype; j++)
666         {
667             type_VDW[ai] = type_VDW[ai] ||
668                 fr->bBHAM ||
669                 C6(fr->nbfp, fr->ntype, ai, j) != 0 ||
670                 C12(fr->nbfp, fr->ntype, ai, j) != 0;
671         }
672     }
673
674     *bFEP_NonBonded               = FALSE;
675     *bExcl_IntraCGAll_InterCGNone = TRUE;
676
677     excl_nalloc = 10;
678     snew(bExcl, excl_nalloc);
679     cg_offset = 0;
680     a_offset  = 0;
681     for (mb = 0; mb < mtop->nmolblock; mb++)
682     {
683         molb = &mtop->molblock[mb];
684         molt = &mtop->moltype[molb->type];
685         cgs  = &molt->cgs;
686         excl = &molt->excls;
687
688         /* Check if the cginfo is identical for all molecules in this block.
689          * If so, we only need an array of the size of one molecule.
690          * Otherwise we make an array of #mol times #cgs per molecule.
691          */
692         bId = TRUE;
693         for (m = 0; m < molb->nmol; m++)
694         {
695             int am = m*cgs->index[cgs->nr];
696             for (cg = 0; cg < cgs->nr; cg++)
697             {
698                 a0 = cgs->index[cg];
699                 a1 = cgs->index[cg+1];
700                 if (ggrpnr(&mtop->groups, egcENER, a_offset+am+a0) !=
701                     ggrpnr(&mtop->groups, egcENER, a_offset   +a0))
702                 {
703                     bId = FALSE;
704                 }
705                 if (mtop->groups.grpnr[egcQMMM] != NULL)
706                 {
707                     for (ai = a0; ai < a1; ai++)
708                     {
709                         if (mtop->groups.grpnr[egcQMMM][a_offset+am+ai] !=
710                             mtop->groups.grpnr[egcQMMM][a_offset   +ai])
711                         {
712                             bId = FALSE;
713                         }
714                     }
715                 }
716             }
717         }
718
719         cginfo_mb[mb].cg_start = cg_offset;
720         cginfo_mb[mb].cg_end   = cg_offset + molb->nmol*cgs->nr;
721         cginfo_mb[mb].cg_mod   = (bId ? 1 : molb->nmol)*cgs->nr;
722         snew(cginfo_mb[mb].cginfo, cginfo_mb[mb].cg_mod);
723         cginfo = cginfo_mb[mb].cginfo;
724
725         /* Set constraints flags for constrained atoms */
726         snew(a_con, molt->atoms.nr);
727         for (ftype = 0; ftype < F_NRE; ftype++)
728         {
729             if (interaction_function[ftype].flags & IF_CONSTRAINT)
730             {
731                 int nral;
732
733                 nral = NRAL(ftype);
734                 for (ia = 0; ia < molt->ilist[ftype].nr; ia += 1+nral)
735                 {
736                     int a;
737
738                     for (a = 0; a < nral; a++)
739                     {
740                         a_con[molt->ilist[ftype].iatoms[ia+1+a]] =
741                             (ftype == F_SETTLE ? acSETTLE : acCONSTRAINT);
742                     }
743                 }
744             }
745         }
746
747         for (m = 0; m < (bId ? 1 : molb->nmol); m++)
748         {
749             int cgm = m*cgs->nr;
750             int am  = m*cgs->index[cgs->nr];
751             for (cg = 0; cg < cgs->nr; cg++)
752             {
753                 a0 = cgs->index[cg];
754                 a1 = cgs->index[cg+1];
755
756                 /* Store the energy group in cginfo */
757                 gid = ggrpnr(&mtop->groups, egcENER, a_offset+am+a0);
758                 SET_CGINFO_GID(cginfo[cgm+cg], gid);
759
760                 /* Check the intra/inter charge group exclusions */
761                 if (a1-a0 > excl_nalloc)
762                 {
763                     excl_nalloc = a1 - a0;
764                     srenew(bExcl, excl_nalloc);
765                 }
766                 /* bExclIntraAll: all intra cg interactions excluded
767                  * bExclInter:    any inter cg interactions excluded
768                  */
769                 bExclIntraAll       = TRUE;
770                 bExclInter          = FALSE;
771                 bHaveVDW            = FALSE;
772                 bHaveQ              = FALSE;
773                 bHavePerturbedAtoms = FALSE;
774                 for (ai = a0; ai < a1; ai++)
775                 {
776                     /* Check VDW and electrostatic interactions */
777                     bHaveVDW = bHaveVDW || (type_VDW[molt->atoms.atom[ai].type] ||
778                                             type_VDW[molt->atoms.atom[ai].typeB]);
779                     bHaveQ  = bHaveQ    || (molt->atoms.atom[ai].q != 0 ||
780                                             molt->atoms.atom[ai].qB != 0);
781
782                     bHavePerturbedAtoms = bHavePerturbedAtoms || (PERTURBED(molt->atoms.atom[ai]) != 0);
783
784                     /* Clear the exclusion list for atom ai */
785                     for (aj = a0; aj < a1; aj++)
786                     {
787                         bExcl[aj-a0] = FALSE;
788                     }
789                     /* Loop over all the exclusions of atom ai */
790                     for (j = excl->index[ai]; j < excl->index[ai+1]; j++)
791                     {
792                         aj = excl->a[j];
793                         if (aj < a0 || aj >= a1)
794                         {
795                             bExclInter = TRUE;
796                         }
797                         else
798                         {
799                             bExcl[aj-a0] = TRUE;
800                         }
801                     }
802                     /* Check if ai excludes a0 to a1 */
803                     for (aj = a0; aj < a1; aj++)
804                     {
805                         if (!bExcl[aj-a0])
806                         {
807                             bExclIntraAll = FALSE;
808                         }
809                     }
810
811                     switch (a_con[ai])
812                     {
813                         case acCONSTRAINT:
814                             SET_CGINFO_CONSTR(cginfo[cgm+cg]);
815                             break;
816                         case acSETTLE:
817                             SET_CGINFO_SETTLE(cginfo[cgm+cg]);
818                             break;
819                         default:
820                             break;
821                     }
822                 }
823                 if (bExclIntraAll)
824                 {
825                     SET_CGINFO_EXCL_INTRA(cginfo[cgm+cg]);
826                 }
827                 if (bExclInter)
828                 {
829                     SET_CGINFO_EXCL_INTER(cginfo[cgm+cg]);
830                 }
831                 if (a1 - a0 > MAX_CHARGEGROUP_SIZE)
832                 {
833                     /* The size in cginfo is currently only read with DD */
834                     gmx_fatal(FARGS, "A charge group has size %d which is larger than the limit of %d atoms", a1-a0, MAX_CHARGEGROUP_SIZE);
835                 }
836                 if (bHaveVDW)
837                 {
838                     SET_CGINFO_HAS_VDW(cginfo[cgm+cg]);
839                 }
840                 if (bHaveQ)
841                 {
842                     SET_CGINFO_HAS_Q(cginfo[cgm+cg]);
843                 }
844                 if (bHavePerturbedAtoms && fr->efep != efepNO)
845                 {
846                     SET_CGINFO_FEP(cginfo[cgm+cg]);
847                     *bFEP_NonBonded = TRUE;
848                 }
849                 /* Store the charge group size */
850                 SET_CGINFO_NATOMS(cginfo[cgm+cg], a1-a0);
851
852                 if (!bExclIntraAll || bExclInter)
853                 {
854                     *bExcl_IntraCGAll_InterCGNone = FALSE;
855                 }
856             }
857         }
858
859         sfree(a_con);
860
861         cg_offset += molb->nmol*cgs->nr;
862         a_offset  += molb->nmol*cgs->index[cgs->nr];
863     }
864     sfree(bExcl);
865
866     /* the solvent optimizer is called after the QM is initialized,
867      * because we don't want to have the QM subsystemto become an
868      * optimized solvent
869      */
870
871     check_solvent(fplog, mtop, fr, cginfo_mb);
872
873     if (getenv("GMX_NO_SOLV_OPT"))
874     {
875         if (fplog)
876         {
877             fprintf(fplog, "Found environment variable GMX_NO_SOLV_OPT.\n"
878                     "Disabling all solvent optimization\n");
879         }
880         fr->solvent_opt = esolNO;
881     }
882     if (bNoSolvOpt)
883     {
884         fr->solvent_opt = esolNO;
885     }
886     if (!fr->solvent_opt)
887     {
888         for (mb = 0; mb < mtop->nmolblock; mb++)
889         {
890             for (cg = 0; cg < cginfo_mb[mb].cg_mod; cg++)
891             {
892                 SET_CGINFO_SOLOPT(cginfo_mb[mb].cginfo[cg], esolNO);
893             }
894         }
895     }
896
897     return cginfo_mb;
898 }
899
900 static int *cginfo_expand(int nmb, cginfo_mb_t *cgi_mb)
901 {
902     int  ncg, mb, cg;
903     int *cginfo;
904
905     ncg = cgi_mb[nmb-1].cg_end;
906     snew(cginfo, ncg);
907     mb = 0;
908     for (cg = 0; cg < ncg; cg++)
909     {
910         while (cg >= cgi_mb[mb].cg_end)
911         {
912             mb++;
913         }
914         cginfo[cg] =
915             cgi_mb[mb].cginfo[(cg - cgi_mb[mb].cg_start) % cgi_mb[mb].cg_mod];
916     }
917
918     return cginfo;
919 }
920
921 static void set_chargesum(FILE *log, t_forcerec *fr, const gmx_mtop_t *mtop)
922 {
923     /*This now calculates sum for q and c6*/
924     double         qsum, q2sum, q, c6sum, c6;
925     int            mb, nmol, i;
926     const t_atoms *atoms;
927
928     qsum   = 0;
929     q2sum  = 0;
930     c6sum  = 0;
931     for (mb = 0; mb < mtop->nmolblock; mb++)
932     {
933         nmol  = mtop->molblock[mb].nmol;
934         atoms = &mtop->moltype[mtop->molblock[mb].type].atoms;
935         for (i = 0; i < atoms->nr; i++)
936         {
937             q       = atoms->atom[i].q;
938             qsum   += nmol*q;
939             q2sum  += nmol*q*q;
940             c6      = mtop->ffparams.iparams[atoms->atom[i].type*(mtop->ffparams.atnr+1)].lj.c6;
941             c6sum  += nmol*c6;
942         }
943     }
944     fr->qsum[0]   = qsum;
945     fr->q2sum[0]  = q2sum;
946     fr->c6sum[0]  = c6sum;
947
948     if (fr->efep != efepNO)
949     {
950         qsum   = 0;
951         q2sum  = 0;
952         c6sum  = 0;
953         for (mb = 0; mb < mtop->nmolblock; mb++)
954         {
955             nmol  = mtop->molblock[mb].nmol;
956             atoms = &mtop->moltype[mtop->molblock[mb].type].atoms;
957             for (i = 0; i < atoms->nr; i++)
958             {
959                 q       = atoms->atom[i].qB;
960                 qsum   += nmol*q;
961                 q2sum  += nmol*q*q;
962                 c6      = mtop->ffparams.iparams[atoms->atom[i].typeB*(mtop->ffparams.atnr+1)].lj.c6;
963                 c6sum  += nmol*c6;
964             }
965             fr->qsum[1]   = qsum;
966             fr->q2sum[1]  = q2sum;
967             fr->c6sum[1]  = c6sum;
968         }
969     }
970     else
971     {
972         fr->qsum[1]   = fr->qsum[0];
973         fr->q2sum[1]  = fr->q2sum[0];
974         fr->c6sum[1]  = fr->c6sum[0];
975     }
976     if (log)
977     {
978         if (fr->efep == efepNO)
979         {
980             fprintf(log, "System total charge: %.3f\n", fr->qsum[0]);
981         }
982         else
983         {
984             fprintf(log, "System total charge, top. A: %.3f top. B: %.3f\n",
985                     fr->qsum[0], fr->qsum[1]);
986         }
987     }
988 }
989
990 void update_forcerec(t_forcerec *fr, matrix box)
991 {
992     if (fr->eeltype == eelGRF)
993     {
994         calc_rffac(NULL, fr->eeltype, fr->epsilon_r, fr->epsilon_rf,
995                    fr->rcoulomb, fr->temp, fr->zsquare, box,
996                    &fr->kappa, &fr->k_rf, &fr->c_rf);
997     }
998 }
999
1000 void set_avcsixtwelve(FILE *fplog, t_forcerec *fr, const gmx_mtop_t *mtop)
1001 {
1002     const t_atoms  *atoms, *atoms_tpi;
1003     const t_blocka *excl;
1004     int             mb, nmol, nmolc, i, j, tpi, tpj, j1, j2, k, nexcl, q;
1005     gmx_int64_t     npair, npair_ij, tmpi, tmpj;
1006     double          csix, ctwelve;
1007     int             ntp, *typecount;
1008     gmx_bool        bBHAM;
1009     real           *nbfp;
1010     real           *nbfp_comb = NULL;
1011
1012     ntp   = fr->ntype;
1013     bBHAM = fr->bBHAM;
1014     nbfp  = fr->nbfp;
1015
1016     /* For LJ-PME, we want to correct for the difference between the
1017      * actual C6 values and the C6 values used by the LJ-PME based on
1018      * combination rules. */
1019
1020     if (EVDW_PME(fr->vdwtype))
1021     {
1022         nbfp_comb = mk_nbfp_combination_rule(&mtop->ffparams,
1023                                              (fr->ljpme_combination_rule == eljpmeLB) ? eCOMB_ARITHMETIC : eCOMB_GEOMETRIC);
1024         for (tpi = 0; tpi < ntp; ++tpi)
1025         {
1026             for (tpj = 0; tpj < ntp; ++tpj)
1027             {
1028                 C6(nbfp_comb, ntp, tpi, tpj) =
1029                     C6(nbfp, ntp, tpi, tpj) - C6(nbfp_comb, ntp, tpi, tpj);
1030                 C12(nbfp_comb, ntp, tpi, tpj) = C12(nbfp, ntp, tpi, tpj);
1031             }
1032         }
1033         nbfp = nbfp_comb;
1034     }
1035     for (q = 0; q < (fr->efep == efepNO ? 1 : 2); q++)
1036     {
1037         csix    = 0;
1038         ctwelve = 0;
1039         npair   = 0;
1040         nexcl   = 0;
1041         if (!fr->n_tpi)
1042         {
1043             /* Count the types so we avoid natoms^2 operations */
1044             snew(typecount, ntp);
1045             gmx_mtop_count_atomtypes(mtop, q, typecount);
1046
1047             for (tpi = 0; tpi < ntp; tpi++)
1048             {
1049                 for (tpj = tpi; tpj < ntp; tpj++)
1050                 {
1051                     tmpi = typecount[tpi];
1052                     tmpj = typecount[tpj];
1053                     if (tpi != tpj)
1054                     {
1055                         npair_ij = tmpi*tmpj;
1056                     }
1057                     else
1058                     {
1059                         npair_ij = tmpi*(tmpi - 1)/2;
1060                     }
1061                     if (bBHAM)
1062                     {
1063                         /* nbfp now includes the 6.0 derivative prefactor */
1064                         csix    += npair_ij*BHAMC(nbfp, ntp, tpi, tpj)/6.0;
1065                     }
1066                     else
1067                     {
1068                         /* nbfp now includes the 6.0/12.0 derivative prefactors */
1069                         csix    += npair_ij*   C6(nbfp, ntp, tpi, tpj)/6.0;
1070                         ctwelve += npair_ij*  C12(nbfp, ntp, tpi, tpj)/12.0;
1071                     }
1072                     npair += npair_ij;
1073                 }
1074             }
1075             sfree(typecount);
1076             /* Subtract the excluded pairs.
1077              * The main reason for substracting exclusions is that in some cases
1078              * some combinations might never occur and the parameters could have
1079              * any value. These unused values should not influence the dispersion
1080              * correction.
1081              */
1082             for (mb = 0; mb < mtop->nmolblock; mb++)
1083             {
1084                 nmol  = mtop->molblock[mb].nmol;
1085                 atoms = &mtop->moltype[mtop->molblock[mb].type].atoms;
1086                 excl  = &mtop->moltype[mtop->molblock[mb].type].excls;
1087                 for (i = 0; (i < atoms->nr); i++)
1088                 {
1089                     if (q == 0)
1090                     {
1091                         tpi = atoms->atom[i].type;
1092                     }
1093                     else
1094                     {
1095                         tpi = atoms->atom[i].typeB;
1096                     }
1097                     j1  = excl->index[i];
1098                     j2  = excl->index[i+1];
1099                     for (j = j1; j < j2; j++)
1100                     {
1101                         k = excl->a[j];
1102                         if (k > i)
1103                         {
1104                             if (q == 0)
1105                             {
1106                                 tpj = atoms->atom[k].type;
1107                             }
1108                             else
1109                             {
1110                                 tpj = atoms->atom[k].typeB;
1111                             }
1112                             if (bBHAM)
1113                             {
1114                                 /* nbfp now includes the 6.0 derivative prefactor */
1115                                 csix -= nmol*BHAMC(nbfp, ntp, tpi, tpj)/6.0;
1116                             }
1117                             else
1118                             {
1119                                 /* nbfp now includes the 6.0/12.0 derivative prefactors */
1120                                 csix    -= nmol*C6 (nbfp, ntp, tpi, tpj)/6.0;
1121                                 ctwelve -= nmol*C12(nbfp, ntp, tpi, tpj)/12.0;
1122                             }
1123                             nexcl += nmol;
1124                         }
1125                     }
1126                 }
1127             }
1128         }
1129         else
1130         {
1131             /* Only correct for the interaction of the test particle
1132              * with the rest of the system.
1133              */
1134             atoms_tpi =
1135                 &mtop->moltype[mtop->molblock[mtop->nmolblock-1].type].atoms;
1136
1137             npair = 0;
1138             for (mb = 0; mb < mtop->nmolblock; mb++)
1139             {
1140                 nmol  = mtop->molblock[mb].nmol;
1141                 atoms = &mtop->moltype[mtop->molblock[mb].type].atoms;
1142                 for (j = 0; j < atoms->nr; j++)
1143                 {
1144                     nmolc = nmol;
1145                     /* Remove the interaction of the test charge group
1146                      * with itself.
1147                      */
1148                     if (mb == mtop->nmolblock-1)
1149                     {
1150                         nmolc--;
1151
1152                         if (mb == 0 && nmol == 1)
1153                         {
1154                             gmx_fatal(FARGS, "Old format tpr with TPI, please generate a new tpr file");
1155                         }
1156                     }
1157                     if (q == 0)
1158                     {
1159                         tpj = atoms->atom[j].type;
1160                     }
1161                     else
1162                     {
1163                         tpj = atoms->atom[j].typeB;
1164                     }
1165                     for (i = 0; i < fr->n_tpi; i++)
1166                     {
1167                         if (q == 0)
1168                         {
1169                             tpi = atoms_tpi->atom[i].type;
1170                         }
1171                         else
1172                         {
1173                             tpi = atoms_tpi->atom[i].typeB;
1174                         }
1175                         if (bBHAM)
1176                         {
1177                             /* nbfp now includes the 6.0 derivative prefactor */
1178                             csix    += nmolc*BHAMC(nbfp, ntp, tpi, tpj)/6.0;
1179                         }
1180                         else
1181                         {
1182                             /* nbfp now includes the 6.0/12.0 derivative prefactors */
1183                             csix    += nmolc*C6 (nbfp, ntp, tpi, tpj)/6.0;
1184                             ctwelve += nmolc*C12(nbfp, ntp, tpi, tpj)/12.0;
1185                         }
1186                         npair += nmolc;
1187                     }
1188                 }
1189             }
1190         }
1191         if (npair - nexcl <= 0 && fplog)
1192         {
1193             fprintf(fplog, "\nWARNING: There are no atom pairs for dispersion correction\n\n");
1194             csix     = 0;
1195             ctwelve  = 0;
1196         }
1197         else
1198         {
1199             csix    /= npair - nexcl;
1200             ctwelve /= npair - nexcl;
1201         }
1202         if (debug)
1203         {
1204             fprintf(debug, "Counted %d exclusions\n", nexcl);
1205             fprintf(debug, "Average C6 parameter is: %10g\n", (double)csix);
1206             fprintf(debug, "Average C12 parameter is: %10g\n", (double)ctwelve);
1207         }
1208         fr->avcsix[q]    = csix;
1209         fr->avctwelve[q] = ctwelve;
1210     }
1211
1212     if (EVDW_PME(fr->vdwtype))
1213     {
1214         sfree(nbfp_comb);
1215     }
1216
1217     if (fplog != NULL)
1218     {
1219         if (fr->eDispCorr == edispcAllEner ||
1220             fr->eDispCorr == edispcAllEnerPres)
1221         {
1222             fprintf(fplog, "Long Range LJ corr.: <C6> %10.4e, <C12> %10.4e\n",
1223                     fr->avcsix[0], fr->avctwelve[0]);
1224         }
1225         else
1226         {
1227             fprintf(fplog, "Long Range LJ corr.: <C6> %10.4e\n", fr->avcsix[0]);
1228         }
1229     }
1230 }
1231
1232
1233 static void set_bham_b_max(FILE *fplog, t_forcerec *fr,
1234                            const gmx_mtop_t *mtop)
1235 {
1236     const t_atoms *at1, *at2;
1237     int            mt1, mt2, i, j, tpi, tpj, ntypes;
1238     real           b, bmin;
1239     real          *nbfp;
1240
1241     if (fplog)
1242     {
1243         fprintf(fplog, "Determining largest Buckingham b parameter for table\n");
1244     }
1245     nbfp   = fr->nbfp;
1246     ntypes = fr->ntype;
1247
1248     bmin           = -1;
1249     fr->bham_b_max = 0;
1250     for (mt1 = 0; mt1 < mtop->nmoltype; mt1++)
1251     {
1252         at1 = &mtop->moltype[mt1].atoms;
1253         for (i = 0; (i < at1->nr); i++)
1254         {
1255             tpi = at1->atom[i].type;
1256             if (tpi >= ntypes)
1257             {
1258                 gmx_fatal(FARGS, "Atomtype[%d] = %d, maximum = %d", i, tpi, ntypes);
1259             }
1260
1261             for (mt2 = mt1; mt2 < mtop->nmoltype; mt2++)
1262             {
1263                 at2 = &mtop->moltype[mt2].atoms;
1264                 for (j = 0; (j < at2->nr); j++)
1265                 {
1266                     tpj = at2->atom[j].type;
1267                     if (tpj >= ntypes)
1268                     {
1269                         gmx_fatal(FARGS, "Atomtype[%d] = %d, maximum = %d", j, tpj, ntypes);
1270                     }
1271                     b = BHAMB(nbfp, ntypes, tpi, tpj);
1272                     if (b > fr->bham_b_max)
1273                     {
1274                         fr->bham_b_max = b;
1275                     }
1276                     if ((b < bmin) || (bmin == -1))
1277                     {
1278                         bmin = b;
1279                     }
1280                 }
1281             }
1282         }
1283     }
1284     if (fplog)
1285     {
1286         fprintf(fplog, "Buckingham b parameters, min: %g, max: %g\n",
1287                 bmin, fr->bham_b_max);
1288     }
1289 }
1290
1291 static void make_nbf_tables(FILE *fp,
1292                             t_forcerec *fr, real rtab,
1293                             const char *tabfn, char *eg1, char *eg2,
1294                             t_nblists *nbl)
1295 {
1296     char buf[STRLEN];
1297     int  i, j;
1298
1299     if (tabfn == NULL)
1300     {
1301         if (debug)
1302         {
1303             fprintf(debug, "No table file name passed, can not read table, can not do non-bonded interactions\n");
1304         }
1305         return;
1306     }
1307
1308     sprintf(buf, "%s", tabfn);
1309     if (eg1 && eg2)
1310     {
1311         /* Append the two energy group names */
1312         sprintf(buf + strlen(tabfn) - strlen(ftp2ext(efXVG)) - 1, "_%s_%s.%s",
1313                 eg1, eg2, ftp2ext(efXVG));
1314     }
1315     nbl->table_elec_vdw = make_tables(fp, fr, buf, rtab, 0);
1316     /* Copy the contents of the table to separate coulomb and LJ tables too,
1317      * to improve cache performance.
1318      */
1319     /* For performance reasons we want
1320      * the table data to be aligned to 16-byte. The pointers could be freed
1321      * but currently aren't.
1322      */
1323     snew(nbl->table_elec, 1);
1324     nbl->table_elec->interaction   = GMX_TABLE_INTERACTION_ELEC;
1325     nbl->table_elec->format        = nbl->table_elec_vdw->format;
1326     nbl->table_elec->r             = nbl->table_elec_vdw->r;
1327     nbl->table_elec->n             = nbl->table_elec_vdw->n;
1328     nbl->table_elec->scale         = nbl->table_elec_vdw->scale;
1329     nbl->table_elec->formatsize    = nbl->table_elec_vdw->formatsize;
1330     nbl->table_elec->ninteractions = 1;
1331     nbl->table_elec->stride        = nbl->table_elec->formatsize * nbl->table_elec->ninteractions;
1332     snew_aligned(nbl->table_elec->data, nbl->table_elec->stride*(nbl->table_elec->n+1), 32);
1333
1334     snew(nbl->table_vdw, 1);
1335     nbl->table_vdw->interaction   = GMX_TABLE_INTERACTION_VDWREP_VDWDISP;
1336     nbl->table_vdw->format        = nbl->table_elec_vdw->format;
1337     nbl->table_vdw->r             = nbl->table_elec_vdw->r;
1338     nbl->table_vdw->n             = nbl->table_elec_vdw->n;
1339     nbl->table_vdw->scale         = nbl->table_elec_vdw->scale;
1340     nbl->table_vdw->formatsize    = nbl->table_elec_vdw->formatsize;
1341     nbl->table_vdw->ninteractions = 2;
1342     nbl->table_vdw->stride        = nbl->table_vdw->formatsize * nbl->table_vdw->ninteractions;
1343     snew_aligned(nbl->table_vdw->data, nbl->table_vdw->stride*(nbl->table_vdw->n+1), 32);
1344
1345     for (i = 0; i <= nbl->table_elec_vdw->n; i++)
1346     {
1347         for (j = 0; j < 4; j++)
1348         {
1349             nbl->table_elec->data[4*i+j] = nbl->table_elec_vdw->data[12*i+j];
1350         }
1351         for (j = 0; j < 8; j++)
1352         {
1353             nbl->table_vdw->data[8*i+j] = nbl->table_elec_vdw->data[12*i+4+j];
1354         }
1355     }
1356 }
1357
1358 /*!\brief If there's bonded interactions of type \c ftype1 or \c
1359  * ftype2 present in the topology, build an array of the number of
1360  * interactions present for each bonded interaction index found in the
1361  * topology.
1362  *
1363  * \c ftype1 or \c ftype2 may be set to -1 to disable seeking for a
1364  * valid type with that parameter.
1365  *
1366  * \c count will be reallocated as necessary to fit the largest bonded
1367  * interaction index found, and its current size will be returned in
1368  * \c ncount. It will contain zero for every bonded interaction index
1369  * for which no interactions are present in the topology.
1370  */
1371 static void count_tables(int ftype1, int ftype2, const gmx_mtop_t *mtop,
1372                          int *ncount, int **count)
1373 {
1374     const gmx_moltype_t *molt;
1375     const t_ilist       *il;
1376     int                  mt, ftype, stride, i, j, tabnr;
1377
1378     // Loop over all moleculetypes
1379     for (mt = 0; mt < mtop->nmoltype; mt++)
1380     {
1381         molt = &mtop->moltype[mt];
1382         // Loop over all interaction types
1383         for (ftype = 0; ftype < F_NRE; ftype++)
1384         {
1385             // If the current interaction type is one of the types whose tables we're trying to count...
1386             if (ftype == ftype1 || ftype == ftype2)
1387             {
1388                 il     = &molt->ilist[ftype];
1389                 stride = 1 + NRAL(ftype);
1390                 // ... and there are actually some interactions for this type
1391                 for (i = 0; i < il->nr; i += stride)
1392                 {
1393                     // Find out which table index the user wanted
1394                     tabnr = mtop->ffparams.iparams[il->iatoms[i]].tab.table;
1395                     if (tabnr < 0)
1396                     {
1397                         gmx_fatal(FARGS, "A bonded table number is smaller than 0: %d\n", tabnr);
1398                     }
1399                     // Make room for this index in the data structure
1400                     if (tabnr >= *ncount)
1401                     {
1402                         srenew(*count, tabnr+1);
1403                         for (j = *ncount; j < tabnr+1; j++)
1404                         {
1405                             (*count)[j] = 0;
1406                         }
1407                         *ncount = tabnr+1;
1408                     }
1409                     // Record that this table index is used and must have a valid file
1410                     (*count)[tabnr]++;
1411                 }
1412             }
1413         }
1414     }
1415 }
1416
1417 /*!\brief If there's bonded interactions of flavour \c tabext and type
1418  * \c ftype1 or \c ftype2 present in the topology, seek them in the
1419  * list of filenames passed to mdrun, and make bonded tables from
1420  * those files.
1421  *
1422  * \c ftype1 or \c ftype2 may be set to -1 to disable seeking for a
1423  * valid type with that parameter.
1424  *
1425  * A fatal error occurs if no matching filename is found.
1426  */
1427 static bondedtable_t *make_bonded_tables(FILE *fplog,
1428                                          int ftype1, int ftype2,
1429                                          const gmx_mtop_t *mtop,
1430                                          const t_filenm *tabbfnm,
1431                                          const char *tabext)
1432 {
1433     int            ncount, *count;
1434     bondedtable_t *tab;
1435
1436     tab = NULL;
1437
1438     ncount = 0;
1439     count  = NULL;
1440     count_tables(ftype1, ftype2, mtop, &ncount, &count);
1441
1442     // Are there any relevant tabulated bond interactions?
1443     if (ncount > 0)
1444     {
1445         snew(tab, ncount);
1446         for (int i = 0; i < ncount; i++)
1447         {
1448             // Do any interactions exist that requires this table?
1449             if (count[i] > 0)
1450             {
1451                 // This pattern enforces the current requirement that
1452                 // table filenames end in a characteristic sequence
1453                 // before the file type extension, and avoids table 13
1454                 // being recognized and used for table 1.
1455                 std::string patternToFind = gmx::formatString("_%s%d.%s", tabext, i, ftp2ext(efXVG));
1456                 bool        madeTable     = false;
1457                 for (int j = 0; j < tabbfnm->nfiles && !madeTable; ++j)
1458                 {
1459                     std::string filename(tabbfnm->fns[j]);
1460                     if (gmx::endsWith(filename, patternToFind))
1461                     {
1462                         // Finally read the table from the file found
1463                         tab[i]    = make_bonded_table(fplog, tabbfnm->fns[j], NRAL(ftype1)-2);
1464                         madeTable = true;
1465                     }
1466                 }
1467                 if (!madeTable)
1468                 {
1469                     bool isPlural = (ftype2 != -1);
1470                     gmx_fatal(FARGS, "Tabulated interaction of type '%s%s%s' with index %d cannot be used because no table file whose name matched '%s' was passed via the gmx mdrun -tableb command-line option.",
1471                               interaction_function[ftype1].longname,
1472                               isPlural ? "' or '" : "",
1473                               isPlural ? interaction_function[ftype2].longname : "",
1474                               i,
1475                               patternToFind.c_str());
1476                 }
1477             }
1478         }
1479         sfree(count);
1480     }
1481
1482     return tab;
1483 }
1484
1485 void forcerec_set_ranges(t_forcerec *fr,
1486                          int ncg_home, int ncg_force,
1487                          int natoms_force,
1488                          int natoms_force_constr, int natoms_f_novirsum)
1489 {
1490     fr->cg0 = 0;
1491     fr->hcg = ncg_home;
1492
1493     /* fr->ncg_force is unused in the standard code,
1494      * but it can be useful for modified code dealing with charge groups.
1495      */
1496     fr->ncg_force           = ncg_force;
1497     fr->natoms_force        = natoms_force;
1498     fr->natoms_force_constr = natoms_force_constr;
1499
1500     if (fr->natoms_force_constr > fr->nalloc_force)
1501     {
1502         fr->nalloc_force = over_alloc_dd(fr->natoms_force_constr);
1503     }
1504
1505     if (fr->bF_NoVirSum)
1506     {
1507         /* TODO: remove this + 1 when padding is properly implemented */
1508         fr->forceBufferNoVirialSummation->resize(natoms_f_novirsum + 1);
1509     }
1510 }
1511
1512 static real cutoff_inf(real cutoff)
1513 {
1514     if (cutoff == 0)
1515     {
1516         cutoff = GMX_CUTOFF_INF;
1517     }
1518
1519     return cutoff;
1520 }
1521
1522 gmx_bool can_use_allvsall(const t_inputrec *ir, gmx_bool bPrintNote, t_commrec *cr, FILE *fp)
1523 {
1524     gmx_bool bAllvsAll;
1525
1526     bAllvsAll =
1527         (
1528             ir->rlist == 0            &&
1529             ir->rcoulomb == 0         &&
1530             ir->rvdw == 0             &&
1531             ir->ePBC == epbcNONE      &&
1532             ir->vdwtype == evdwCUT    &&
1533             ir->coulombtype == eelCUT &&
1534             ir->efep == efepNO        &&
1535             (ir->implicit_solvent == eisNO ||
1536              (ir->implicit_solvent == eisGBSA && (ir->gb_algorithm == egbSTILL ||
1537                                                   ir->gb_algorithm == egbHCT   ||
1538                                                   ir->gb_algorithm == egbOBC))) &&
1539             getenv("GMX_NO_ALLVSALL") == NULL
1540         );
1541
1542     if (bAllvsAll && ir->opts.ngener > 1)
1543     {
1544         const char *note = "NOTE: Can not use all-vs-all force loops, because there are multiple energy monitor groups; you might get significantly higher performance when using only a single energy monitor group.\n";
1545
1546         if (bPrintNote)
1547         {
1548             if (fp != NULL)
1549             {
1550                 fprintf(fp, "\n%s\n", note);
1551             }
1552         }
1553         bAllvsAll = FALSE;
1554     }
1555
1556     if (bAllvsAll && fp && MASTER(cr))
1557     {
1558         fprintf(fp, "\nUsing SIMD all-vs-all kernels.\n\n");
1559     }
1560
1561     return bAllvsAll;
1562 }
1563
1564
1565 gmx_bool nbnxn_gpu_acceleration_supported(const gmx::MDLogger &mdlog,
1566                                           const t_inputrec    *ir,
1567                                           gmx_bool             bRerunMD)
1568 {
1569     if (bRerunMD && ir->opts.ngener > 1)
1570     {
1571         /* Rerun execution time is dominated by I/O and pair search,
1572          * so GPUs are not very useful, plus they do not support more
1573          * than one energy group. If the user requested GPUs
1574          * explicitly, a fatal error is given later.  With non-reruns,
1575          * we fall back to a single whole-of system energy group
1576          * (which runs much faster than a multiple-energy-groups
1577          * implementation would), and issue a note in the .log
1578          * file. Users can re-run if they want the information. */
1579         GMX_LOG(mdlog.warning).asParagraph().appendText("Rerun with energy groups is not implemented for GPUs, falling back to the CPU");
1580         return FALSE;
1581     }
1582
1583     return TRUE;
1584 }
1585
1586 gmx_bool nbnxn_simd_supported(const gmx::MDLogger &mdlog,
1587                               const t_inputrec    *ir)
1588 {
1589     if (ir->vdwtype == evdwPME && ir->ljpme_combination_rule == eljpmeLB)
1590     {
1591         /* LJ PME with LB combination rule does 7 mesh operations.
1592          * This so slow that we don't compile SIMD non-bonded kernels
1593          * for that. */
1594         GMX_LOG(mdlog.warning).asParagraph().appendText("LJ-PME with Lorentz-Berthelot is not supported with SIMD kernels, falling back to plain C kernels");
1595         return FALSE;
1596     }
1597
1598     return TRUE;
1599 }
1600
1601
1602 static void pick_nbnxn_kernel_cpu(const t_inputrec gmx_unused *ir,
1603                                   int                         *kernel_type,
1604                                   int                         *ewald_excl)
1605 {
1606     *kernel_type = nbnxnk4x4_PlainC;
1607     *ewald_excl  = ewaldexclTable;
1608
1609 #if GMX_SIMD
1610     {
1611 #ifdef GMX_NBNXN_SIMD_4XN
1612         *kernel_type = nbnxnk4xN_SIMD_4xN;
1613 #endif
1614 #ifdef GMX_NBNXN_SIMD_2XNN
1615         *kernel_type = nbnxnk4xN_SIMD_2xNN;
1616 #endif
1617
1618 #if defined GMX_NBNXN_SIMD_2XNN && defined GMX_NBNXN_SIMD_4XN
1619         /* We need to choose if we want 2x(N+N) or 4xN kernels.
1620          * Currently this is based on the SIMD acceleration choice,
1621          * but it might be better to decide this at runtime based on CPU.
1622          *
1623          * 4xN calculates more (zero) interactions, but has less pair-search
1624          * work and much better kernel instruction scheduling.
1625          *
1626          * Up till now we have only seen that on Intel Sandy/Ivy Bridge,
1627          * which doesn't have FMA, both the analytical and tabulated Ewald
1628          * kernels have similar pair rates for 4x8 and 2x(4+4), so we choose
1629          * 2x(4+4) because it results in significantly fewer pairs.
1630          * For RF, the raw pair rate of the 4x8 kernel is higher than 2x(4+4),
1631          * 10% with HT, 50% without HT. As we currently don't detect the actual
1632          * use of HT, use 4x8 to avoid a potential performance hit.
1633          * On Intel Haswell 4x8 is always faster.
1634          */
1635         *kernel_type = nbnxnk4xN_SIMD_4xN;
1636
1637 #if !GMX_SIMD_HAVE_FMA
1638         if (EEL_PME_EWALD(ir->coulombtype) ||
1639             EVDW_PME(ir->vdwtype))
1640         {
1641             /* We have Ewald kernels without FMA (Intel Sandy/Ivy Bridge).
1642              * There are enough instructions to make 2x(4+4) efficient.
1643              */
1644             *kernel_type = nbnxnk4xN_SIMD_2xNN;
1645         }
1646 #endif
1647 #endif  /* GMX_NBNXN_SIMD_2XNN && GMX_NBNXN_SIMD_4XN */
1648
1649
1650         if (getenv("GMX_NBNXN_SIMD_4XN") != NULL)
1651         {
1652 #ifdef GMX_NBNXN_SIMD_4XN
1653             *kernel_type = nbnxnk4xN_SIMD_4xN;
1654 #else
1655             gmx_fatal(FARGS, "SIMD 4xN kernels requested, but GROMACS has been compiled without support for these kernels");
1656 #endif
1657         }
1658         if (getenv("GMX_NBNXN_SIMD_2XNN") != NULL)
1659         {
1660 #ifdef GMX_NBNXN_SIMD_2XNN
1661             *kernel_type = nbnxnk4xN_SIMD_2xNN;
1662 #else
1663             gmx_fatal(FARGS, "SIMD 2x(N+N) kernels requested, but GROMACS has been compiled without support for these kernels");
1664 #endif
1665         }
1666
1667         /* Analytical Ewald exclusion correction is only an option in
1668          * the SIMD kernel.
1669          * Since table lookup's don't parallelize with SIMD, analytical
1670          * will probably always be faster for a SIMD width of 8 or more.
1671          * With FMA analytical is sometimes faster for a width if 4 as well.
1672          * On BlueGene/Q, this is faster regardless of precision.
1673          * In single precision, this is faster on Bulldozer.
1674          */
1675 #if GMX_SIMD_REAL_WIDTH >= 8 || \
1676         (GMX_SIMD_REAL_WIDTH >= 4 && GMX_SIMD_HAVE_FMA && !GMX_DOUBLE) || GMX_SIMD_IBM_QPX
1677         *ewald_excl = ewaldexclAnalytical;
1678 #endif
1679         if (getenv("GMX_NBNXN_EWALD_TABLE") != NULL)
1680         {
1681             *ewald_excl = ewaldexclTable;
1682         }
1683         if (getenv("GMX_NBNXN_EWALD_ANALYTICAL") != NULL)
1684         {
1685             *ewald_excl = ewaldexclAnalytical;
1686         }
1687
1688     }
1689 #endif // GMX_SIMD
1690 }
1691
1692
1693 const char *lookup_nbnxn_kernel_name(int kernel_type)
1694 {
1695     const char *returnvalue = NULL;
1696     switch (kernel_type)
1697     {
1698         case nbnxnkNotSet:
1699             returnvalue = "not set";
1700             break;
1701         case nbnxnk4x4_PlainC:
1702             returnvalue = "plain C";
1703             break;
1704         case nbnxnk4xN_SIMD_4xN:
1705         case nbnxnk4xN_SIMD_2xNN:
1706 #if GMX_SIMD
1707             returnvalue = "SIMD";
1708 #else  // GMX_SIMD
1709             returnvalue = "not available";
1710 #endif // GMX_SIMD
1711             break;
1712         case nbnxnk8x8x8_GPU: returnvalue    = "GPU"; break;
1713         case nbnxnk8x8x8_PlainC: returnvalue = "plain C"; break;
1714
1715         case nbnxnkNR:
1716         default:
1717             gmx_fatal(FARGS, "Illegal kernel type selected");
1718             returnvalue = NULL;
1719             break;
1720     }
1721     return returnvalue;
1722 };
1723
1724 static void pick_nbnxn_kernel(FILE                *fp,
1725                               const gmx::MDLogger &mdlog,
1726                               gmx_bool             use_simd_kernels,
1727                               gmx_bool             bUseGPU,
1728                               gmx_bool             bEmulateGPU,
1729                               const t_inputrec    *ir,
1730                               int                 *kernel_type,
1731                               int                 *ewald_excl,
1732                               gmx_bool             bDoNonbonded)
1733 {
1734     assert(kernel_type);
1735
1736     *kernel_type = nbnxnkNotSet;
1737     *ewald_excl  = ewaldexclTable;
1738
1739     if (bEmulateGPU)
1740     {
1741         *kernel_type = nbnxnk8x8x8_PlainC;
1742
1743         if (bDoNonbonded)
1744         {
1745             GMX_LOG(mdlog.warning).asParagraph().appendText("Emulating a GPU run on the CPU (slow)");
1746         }
1747     }
1748     else if (bUseGPU)
1749     {
1750         *kernel_type = nbnxnk8x8x8_GPU;
1751     }
1752
1753     if (*kernel_type == nbnxnkNotSet)
1754     {
1755         if (use_simd_kernels &&
1756             nbnxn_simd_supported(mdlog, ir))
1757         {
1758             pick_nbnxn_kernel_cpu(ir, kernel_type, ewald_excl);
1759         }
1760         else
1761         {
1762             *kernel_type = nbnxnk4x4_PlainC;
1763         }
1764     }
1765
1766     if (bDoNonbonded && fp != NULL)
1767     {
1768         fprintf(fp, "\nUsing %s %dx%d non-bonded kernels\n\n",
1769                 lookup_nbnxn_kernel_name(*kernel_type),
1770                 nbnxn_kernel_to_cluster_i_size(*kernel_type),
1771                 nbnxn_kernel_to_cluster_j_size(*kernel_type));
1772
1773         if (nbnxnk4x4_PlainC == *kernel_type ||
1774             nbnxnk8x8x8_PlainC == *kernel_type)
1775         {
1776             GMX_LOG(mdlog.warning).asParagraph().appendTextFormatted(
1777                     "WARNING: Using the slow %s kernels. This should\n"
1778                     "not happen during routine usage on supported platforms.",
1779                     lookup_nbnxn_kernel_name(*kernel_type));
1780         }
1781     }
1782 }
1783
1784 static void pick_nbnxn_resources(const gmx::MDLogger &mdlog,
1785                                  const t_commrec     *cr,
1786                                  const gmx_hw_info_t *hwinfo,
1787                                  gmx_bool             bDoNonbonded,
1788                                  gmx_bool            *bUseGPU,
1789                                  gmx_bool            *bEmulateGPU,
1790                                  const gmx_gpu_opt_t *gpu_opt)
1791 {
1792     gmx_bool bEmulateGPUEnvVarSet;
1793     char     gpu_err_str[STRLEN];
1794
1795     *bUseGPU = FALSE;
1796
1797     bEmulateGPUEnvVarSet = (getenv("GMX_EMULATE_GPU") != NULL);
1798
1799     /* Run GPU emulation mode if GMX_EMULATE_GPU is defined. Because
1800      * GPUs (currently) only handle non-bonded calculations, we will
1801      * automatically switch to emulation if non-bonded calculations are
1802      * turned off via GMX_NO_NONBONDED - this is the simple and elegant
1803      * way to turn off GPU initialization, data movement, and cleanup.
1804      *
1805      * GPU emulation can be useful to assess the performance one can expect by
1806      * adding GPU(s) to the machine. The conditional below allows this even
1807      * if mdrun is compiled without GPU acceleration support.
1808      * Note that you should freezing the system as otherwise it will explode.
1809      */
1810     *bEmulateGPU = (bEmulateGPUEnvVarSet ||
1811                     (!bDoNonbonded && gpu_opt->n_dev_use > 0));
1812
1813     /* Enable GPU mode when GPUs are available or no GPU emulation is requested.
1814      */
1815     if (gpu_opt->n_dev_use > 0 && !(*bEmulateGPU))
1816     {
1817         /* Each PP node will use the intra-node id-th device from the
1818          * list of detected/selected GPUs. */
1819         if (!init_gpu(mdlog, cr->rank_pp_intranode, gpu_err_str,
1820                       &hwinfo->gpu_info, gpu_opt))
1821         {
1822             /* At this point the init should never fail as we made sure that
1823              * we have all the GPUs we need. If it still does, we'll bail. */
1824             /* TODO the decorating of gpu_err_str is nicer if it
1825                happens inside init_gpu. Out here, the decorating with
1826                the MPI rank makes sense. */
1827             gmx_fatal(FARGS, "On rank %d failed to initialize GPU #%d: %s",
1828                       cr->nodeid,
1829                       get_gpu_device_id(&hwinfo->gpu_info, gpu_opt,
1830                                         cr->rank_pp_intranode),
1831                       gpu_err_str);
1832         }
1833
1834         /* Here we actually turn on hardware GPU acceleration */
1835         *bUseGPU = TRUE;
1836     }
1837 }
1838
1839 gmx_bool uses_simple_tables(int                 cutoff_scheme,
1840                             nonbonded_verlet_t *nbv,
1841                             int                 group)
1842 {
1843     gmx_bool bUsesSimpleTables = TRUE;
1844     int      grp_index;
1845
1846     switch (cutoff_scheme)
1847     {
1848         case ecutsGROUP:
1849             bUsesSimpleTables = TRUE;
1850             break;
1851         case ecutsVERLET:
1852             assert(NULL != nbv && NULL != nbv->grp);
1853             grp_index         = (group < 0) ? 0 : (nbv->ngrp - 1);
1854             bUsesSimpleTables = nbnxn_kernel_pairlist_simple(nbv->grp[grp_index].kernel_type);
1855             break;
1856         default:
1857             gmx_incons("unimplemented");
1858     }
1859     return bUsesSimpleTables;
1860 }
1861
1862 static void init_ewald_f_table(interaction_const_t *ic,
1863                                real                 rtab)
1864 {
1865     real maxr;
1866
1867     /* Get the Ewald table spacing based on Coulomb and/or LJ
1868      * Ewald coefficients and rtol.
1869      */
1870     ic->tabq_scale = ewald_spline3_table_scale(ic);
1871
1872     if (ic->cutoff_scheme == ecutsVERLET)
1873     {
1874         maxr = ic->rcoulomb;
1875     }
1876     else
1877     {
1878         maxr = std::max(ic->rcoulomb, rtab);
1879     }
1880     ic->tabq_size  = static_cast<int>(maxr*ic->tabq_scale) + 2;
1881
1882     sfree_aligned(ic->tabq_coul_FDV0);
1883     sfree_aligned(ic->tabq_coul_F);
1884     sfree_aligned(ic->tabq_coul_V);
1885
1886     sfree_aligned(ic->tabq_vdw_FDV0);
1887     sfree_aligned(ic->tabq_vdw_F);
1888     sfree_aligned(ic->tabq_vdw_V);
1889
1890     if (EEL_PME_EWALD(ic->eeltype))
1891     {
1892         /* Create the original table data in FDV0 */
1893         snew_aligned(ic->tabq_coul_FDV0, ic->tabq_size*4, 32);
1894         snew_aligned(ic->tabq_coul_F, ic->tabq_size, 32);
1895         snew_aligned(ic->tabq_coul_V, ic->tabq_size, 32);
1896         table_spline3_fill_ewald_lr(ic->tabq_coul_F, ic->tabq_coul_V, ic->tabq_coul_FDV0,
1897                                     ic->tabq_size, 1/ic->tabq_scale, ic->ewaldcoeff_q, v_q_ewald_lr);
1898     }
1899
1900     if (EVDW_PME(ic->vdwtype))
1901     {
1902         snew_aligned(ic->tabq_vdw_FDV0, ic->tabq_size*4, 32);
1903         snew_aligned(ic->tabq_vdw_F, ic->tabq_size, 32);
1904         snew_aligned(ic->tabq_vdw_V, ic->tabq_size, 32);
1905         table_spline3_fill_ewald_lr(ic->tabq_vdw_F, ic->tabq_vdw_V, ic->tabq_vdw_FDV0,
1906                                     ic->tabq_size, 1/ic->tabq_scale, ic->ewaldcoeff_lj, v_lj_ewald_lr);
1907     }
1908 }
1909
1910 void init_interaction_const_tables(FILE                *fp,
1911                                    interaction_const_t *ic,
1912                                    real                 rtab)
1913 {
1914     if (EEL_PME_EWALD(ic->eeltype) || EVDW_PME(ic->vdwtype))
1915     {
1916         init_ewald_f_table(ic, rtab);
1917
1918         if (fp != NULL)
1919         {
1920             fprintf(fp, "Initialized non-bonded Ewald correction tables, spacing: %.2e size: %d\n\n",
1921                     1/ic->tabq_scale, ic->tabq_size);
1922         }
1923     }
1924 }
1925
1926 static void clear_force_switch_constants(shift_consts_t *sc)
1927 {
1928     sc->c2   = 0;
1929     sc->c3   = 0;
1930     sc->cpot = 0;
1931 }
1932
1933 static void force_switch_constants(real p,
1934                                    real rsw, real rc,
1935                                    shift_consts_t *sc)
1936 {
1937     /* Here we determine the coefficient for shifting the force to zero
1938      * between distance rsw and the cut-off rc.
1939      * For a potential of r^-p, we have force p*r^-(p+1).
1940      * But to save flops we absorb p in the coefficient.
1941      * Thus we get:
1942      * force/p   = r^-(p+1) + c2*r^2 + c3*r^3
1943      * potential = r^-p + c2/3*r^3 + c3/4*r^4 + cpot
1944      */
1945     sc->c2   =  ((p + 1)*rsw - (p + 4)*rc)/(pow(rc, p + 2)*gmx::square(rc - rsw));
1946     sc->c3   = -((p + 1)*rsw - (p + 3)*rc)/(pow(rc, p + 2)*gmx::power3(rc - rsw));
1947     sc->cpot = -pow(rc, -p) + p*sc->c2/3*gmx::power3(rc - rsw) + p*sc->c3/4*gmx::power4(rc - rsw);
1948 }
1949
1950 static void potential_switch_constants(real rsw, real rc,
1951                                        switch_consts_t *sc)
1952 {
1953     /* The switch function is 1 at rsw and 0 at rc.
1954      * The derivative and second derivate are zero at both ends.
1955      * rsw        = max(r - r_switch, 0)
1956      * sw         = 1 + c3*rsw^3 + c4*rsw^4 + c5*rsw^5
1957      * dsw        = 3*c3*rsw^2 + 4*c4*rsw^3 + 5*c5*rsw^4
1958      * force      = force*dsw - potential*sw
1959      * potential *= sw
1960      */
1961     sc->c3 = -10/gmx::power3(rc - rsw);
1962     sc->c4 =  15/gmx::power4(rc - rsw);
1963     sc->c5 =  -6/gmx::power5(rc - rsw);
1964 }
1965
1966 /*! \brief Construct interaction constants
1967  *
1968  * This data is used (particularly) by search and force code for
1969  * short-range interactions. Many of these are constant for the whole
1970  * simulation; some are constant only after PME tuning completes.
1971  */
1972 static void
1973 init_interaction_const(FILE                       *fp,
1974                        interaction_const_t       **interaction_const,
1975                        const t_forcerec           *fr)
1976 {
1977     interaction_const_t *ic;
1978
1979     snew(ic, 1);
1980
1981     ic->cutoff_scheme   = fr->cutoff_scheme;
1982
1983     /* Just allocate something so we can free it */
1984     snew_aligned(ic->tabq_coul_FDV0, 16, 32);
1985     snew_aligned(ic->tabq_coul_F, 16, 32);
1986     snew_aligned(ic->tabq_coul_V, 16, 32);
1987
1988     ic->rlist           = fr->rlist;
1989
1990     /* Lennard-Jones */
1991     ic->vdwtype         = fr->vdwtype;
1992     ic->vdw_modifier    = fr->vdw_modifier;
1993     ic->rvdw            = fr->rvdw;
1994     ic->rvdw_switch     = fr->rvdw_switch;
1995     ic->ewaldcoeff_lj   = fr->ewaldcoeff_lj;
1996     ic->ljpme_comb_rule = fr->ljpme_combination_rule;
1997     ic->sh_lj_ewald     = 0;
1998     clear_force_switch_constants(&ic->dispersion_shift);
1999     clear_force_switch_constants(&ic->repulsion_shift);
2000
2001     switch (ic->vdw_modifier)
2002     {
2003         case eintmodPOTSHIFT:
2004             /* Only shift the potential, don't touch the force */
2005             ic->dispersion_shift.cpot = -1.0/gmx::power6(ic->rvdw);
2006             ic->repulsion_shift.cpot  = -1.0/gmx::power12(ic->rvdw);
2007             if (EVDW_PME(ic->vdwtype))
2008             {
2009                 real crc2;
2010
2011                 crc2            = gmx::square(ic->ewaldcoeff_lj*ic->rvdw);
2012                 ic->sh_lj_ewald = (std::exp(-crc2)*(1 + crc2 + 0.5*crc2*crc2) - 1)/gmx::power6(ic->rvdw);
2013             }
2014             break;
2015         case eintmodFORCESWITCH:
2016             /* Switch the force, switch and shift the potential */
2017             force_switch_constants(6.0, ic->rvdw_switch, ic->rvdw,
2018                                    &ic->dispersion_shift);
2019             force_switch_constants(12.0, ic->rvdw_switch, ic->rvdw,
2020                                    &ic->repulsion_shift);
2021             break;
2022         case eintmodPOTSWITCH:
2023             /* Switch the potential and force */
2024             potential_switch_constants(ic->rvdw_switch, ic->rvdw,
2025                                        &ic->vdw_switch);
2026             break;
2027         case eintmodNONE:
2028         case eintmodEXACTCUTOFF:
2029             /* Nothing to do here */
2030             break;
2031         default:
2032             gmx_incons("unimplemented potential modifier");
2033     }
2034
2035     ic->sh_invrc6 = -ic->dispersion_shift.cpot;
2036
2037     /* Electrostatics */
2038     ic->eeltype          = fr->eeltype;
2039     ic->coulomb_modifier = fr->coulomb_modifier;
2040     ic->rcoulomb         = fr->rcoulomb;
2041     ic->epsilon_r        = fr->epsilon_r;
2042     ic->epsfac           = fr->epsfac;
2043     ic->ewaldcoeff_q     = fr->ewaldcoeff_q;
2044
2045     if (fr->coulomb_modifier == eintmodPOTSHIFT)
2046     {
2047         ic->sh_ewald = std::erfc(ic->ewaldcoeff_q*ic->rcoulomb);
2048     }
2049     else
2050     {
2051         ic->sh_ewald = 0;
2052     }
2053
2054     /* Reaction-field */
2055     if (EEL_RF(ic->eeltype))
2056     {
2057         ic->epsilon_rf = fr->epsilon_rf;
2058         ic->k_rf       = fr->k_rf;
2059         ic->c_rf       = fr->c_rf;
2060     }
2061     else
2062     {
2063         /* For plain cut-off we might use the reaction-field kernels */
2064         ic->epsilon_rf = ic->epsilon_r;
2065         ic->k_rf       = 0;
2066         if (fr->coulomb_modifier == eintmodPOTSHIFT)
2067         {
2068             ic->c_rf   = 1/ic->rcoulomb;
2069         }
2070         else
2071         {
2072             ic->c_rf   = 0;
2073         }
2074     }
2075
2076     if (fp != NULL)
2077     {
2078         real dispersion_shift;
2079
2080         dispersion_shift = ic->dispersion_shift.cpot;
2081         if (EVDW_PME(ic->vdwtype))
2082         {
2083             dispersion_shift -= ic->sh_lj_ewald;
2084         }
2085         fprintf(fp, "Potential shift: LJ r^-12: %.3e r^-6: %.3e",
2086                 ic->repulsion_shift.cpot, dispersion_shift);
2087
2088         if (ic->eeltype == eelCUT)
2089         {
2090             fprintf(fp, ", Coulomb %.e", -ic->c_rf);
2091         }
2092         else if (EEL_PME(ic->eeltype))
2093         {
2094             fprintf(fp, ", Ewald %.3e", -ic->sh_ewald);
2095         }
2096         fprintf(fp, "\n");
2097     }
2098
2099     *interaction_const = ic;
2100 }
2101
2102 static void init_nb_verlet(FILE                *fp,
2103                            const gmx::MDLogger &mdlog,
2104                            nonbonded_verlet_t **nb_verlet,
2105                            gmx_bool             bFEP_NonBonded,
2106                            const t_inputrec    *ir,
2107                            const t_forcerec    *fr,
2108                            const t_commrec     *cr,
2109                            const char          *nbpu_opt)
2110 {
2111     nonbonded_verlet_t *nbv;
2112     int                 i;
2113     char               *env;
2114     gmx_bool            bEmulateGPU, bHybridGPURun = FALSE;
2115
2116     nbnxn_alloc_t      *nb_alloc;
2117     nbnxn_free_t       *nb_free;
2118
2119     snew(nbv, 1);
2120
2121     pick_nbnxn_resources(mdlog, cr, fr->hwinfo,
2122                          fr->bNonbonded,
2123                          &nbv->bUseGPU,
2124                          &bEmulateGPU,
2125                          fr->gpu_opt);
2126
2127     nbv->nbs             = NULL;
2128     nbv->min_ci_balanced = 0;
2129
2130     nbv->ngrp = (DOMAINDECOMP(cr) ? 2 : 1);
2131     for (i = 0; i < nbv->ngrp; i++)
2132     {
2133         nbv->grp[i].nbl_lists.nnbl = 0;
2134         nbv->grp[i].nbat           = NULL;
2135         nbv->grp[i].kernel_type    = nbnxnkNotSet;
2136
2137         if (i == 0) /* local */
2138         {
2139             pick_nbnxn_kernel(fp, mdlog, fr->use_simd_kernels,
2140                               nbv->bUseGPU, bEmulateGPU, ir,
2141                               &nbv->grp[i].kernel_type,
2142                               &nbv->grp[i].ewald_excl,
2143                               fr->bNonbonded);
2144         }
2145         else /* non-local */
2146         {
2147             if (nbpu_opt != NULL && strcmp(nbpu_opt, "gpu_cpu") == 0)
2148             {
2149                 /* Use GPU for local, select a CPU kernel for non-local */
2150                 pick_nbnxn_kernel(fp, mdlog, fr->use_simd_kernels,
2151                                   FALSE, FALSE, ir,
2152                                   &nbv->grp[i].kernel_type,
2153                                   &nbv->grp[i].ewald_excl,
2154                                   fr->bNonbonded);
2155
2156                 bHybridGPURun = TRUE;
2157             }
2158             else
2159             {
2160                 /* Use the same kernel for local and non-local interactions */
2161                 nbv->grp[i].kernel_type = nbv->grp[0].kernel_type;
2162                 nbv->grp[i].ewald_excl  = nbv->grp[0].ewald_excl;
2163             }
2164         }
2165     }
2166
2167     nbnxn_init_search(&nbv->nbs,
2168                       DOMAINDECOMP(cr) ? &cr->dd->nc : NULL,
2169                       DOMAINDECOMP(cr) ? domdec_zones(cr->dd) : NULL,
2170                       bFEP_NonBonded,
2171                       gmx_omp_nthreads_get(emntPairsearch));
2172
2173     for (i = 0; i < nbv->ngrp; i++)
2174     {
2175         gpu_set_host_malloc_and_free(nbv->grp[0].kernel_type == nbnxnk8x8x8_GPU,
2176                                      &nb_alloc, &nb_free);
2177
2178         nbnxn_init_pairlist_set(&nbv->grp[i].nbl_lists,
2179                                 nbnxn_kernel_pairlist_simple(nbv->grp[i].kernel_type),
2180                                 /* 8x8x8 "non-simple" lists are ATM always combined */
2181                                 !nbnxn_kernel_pairlist_simple(nbv->grp[i].kernel_type),
2182                                 nb_alloc, nb_free);
2183
2184         if (i == 0 ||
2185             nbv->grp[0].kernel_type != nbv->grp[i].kernel_type)
2186         {
2187             gmx_bool bSimpleList;
2188             int      enbnxninitcombrule;
2189
2190             bSimpleList = nbnxn_kernel_pairlist_simple(nbv->grp[i].kernel_type);
2191
2192             if (fr->vdwtype == evdwCUT &&
2193                 (fr->vdw_modifier == eintmodNONE ||
2194                  fr->vdw_modifier == eintmodPOTSHIFT) &&
2195                 getenv("GMX_NO_LJ_COMB_RULE") == NULL)
2196             {
2197                 /* Plain LJ cut-off: we can optimize with combination rules */
2198                 enbnxninitcombrule = enbnxninitcombruleDETECT;
2199             }
2200             else if (fr->vdwtype == evdwPME)
2201             {
2202                 /* LJ-PME: we need to use a combination rule for the grid */
2203                 if (fr->ljpme_combination_rule == eljpmeGEOM)
2204                 {
2205                     enbnxninitcombrule = enbnxninitcombruleGEOM;
2206                 }
2207                 else
2208                 {
2209                     enbnxninitcombrule = enbnxninitcombruleLB;
2210                 }
2211             }
2212             else
2213             {
2214                 /* We use a full combination matrix: no rule required */
2215                 enbnxninitcombrule = enbnxninitcombruleNONE;
2216             }
2217
2218
2219             snew(nbv->grp[i].nbat, 1);
2220             nbnxn_atomdata_init(fp,
2221                                 nbv->grp[i].nbat,
2222                                 nbv->grp[i].kernel_type,
2223                                 enbnxninitcombrule,
2224                                 fr->ntype, fr->nbfp,
2225                                 ir->opts.ngener,
2226                                 bSimpleList ? gmx_omp_nthreads_get(emntNonbonded) : 1,
2227                                 nb_alloc, nb_free);
2228         }
2229         else
2230         {
2231             nbv->grp[i].nbat = nbv->grp[0].nbat;
2232         }
2233     }
2234
2235     if (nbv->bUseGPU)
2236     {
2237         /* init the NxN GPU data; the last argument tells whether we'll have
2238          * both local and non-local NB calculation on GPU */
2239         nbnxn_gpu_init(&nbv->gpu_nbv,
2240                        &fr->hwinfo->gpu_info,
2241                        fr->gpu_opt,
2242                        fr->ic,
2243                        nbv->grp,
2244                        cr->rank_pp_intranode,
2245                        cr->nodeid,
2246                        (nbv->ngrp > 1) && !bHybridGPURun);
2247
2248         /* With tMPI + GPUs some ranks may be sharing GPU(s) and therefore
2249          * also sharing texture references. To keep the code simple, we don't
2250          * treat texture references as shared resources, but this means that
2251          * the coulomb_tab and nbfp texture refs will get updated by multiple threads.
2252          * Hence, to ensure that the non-bonded kernels don't start before all
2253          * texture binding operations are finished, we need to wait for all ranks
2254          * to arrive here before continuing.
2255          *
2256          * Note that we could omit this barrier if GPUs are not shared (or
2257          * texture objects are used), but as this is initialization code, there
2258          * is no point in complicating things.
2259          */
2260 #if GMX_THREAD_MPI
2261         if (PAR(cr))
2262         {
2263             gmx_barrier(cr);
2264         }
2265 #endif  /* GMX_THREAD_MPI */
2266
2267         if ((env = getenv("GMX_NB_MIN_CI")) != NULL)
2268         {
2269             char *end;
2270
2271             nbv->min_ci_balanced = strtol(env, &end, 10);
2272             if (!end || (*end != 0) || nbv->min_ci_balanced < 0)
2273             {
2274                 gmx_fatal(FARGS, "Invalid value passed in GMX_NB_MIN_CI=%s, non-negative integer required", env);
2275             }
2276
2277             if (debug)
2278             {
2279                 fprintf(debug, "Neighbor-list balancing parameter: %d (passed as env. var.)\n",
2280                         nbv->min_ci_balanced);
2281             }
2282         }
2283         else
2284         {
2285             nbv->min_ci_balanced = nbnxn_gpu_min_ci_balanced(nbv->gpu_nbv);
2286             if (debug)
2287             {
2288                 fprintf(debug, "Neighbor-list balancing parameter: %d (auto-adjusted to the number of GPU multi-processors)\n",
2289                         nbv->min_ci_balanced);
2290             }
2291         }
2292
2293     }
2294
2295     *nb_verlet = nbv;
2296 }
2297
2298 gmx_bool usingGpu(nonbonded_verlet_t *nbv)
2299 {
2300     return nbv != NULL && nbv->bUseGPU;
2301 }
2302
2303 void init_forcerec(FILE                *fp,
2304                    const gmx::MDLogger &mdlog,
2305                    t_forcerec          *fr,
2306                    t_fcdata            *fcd,
2307                    const t_inputrec    *ir,
2308                    const gmx_mtop_t    *mtop,
2309                    const t_commrec     *cr,
2310                    matrix               box,
2311                    const char          *tabfn,
2312                    const char          *tabpfn,
2313                    const t_filenm      *tabbfnm,
2314                    const char          *nbpu_opt,
2315                    gmx_bool             bNoSolvOpt,
2316                    real                 print_force)
2317 {
2318     int            i, m, negp_pp, negptable, egi, egj;
2319     real           rtab;
2320     char          *env;
2321     double         dbl;
2322     const t_block *cgs;
2323     gmx_bool       bGenericKernelOnly;
2324     gmx_bool       needGroupSchemeTables, bSomeNormalNbListsAreInUse;
2325     gmx_bool       bFEP_NonBonded;
2326     int           *nm_ind, egp_flags;
2327
2328     if (fr->hwinfo == NULL)
2329     {
2330         /* Detect hardware, gather information.
2331          * In mdrun, hwinfo has already been set before calling init_forcerec.
2332          * Here we ignore GPUs, as tools will not use them anyhow.
2333          */
2334         fr->hwinfo = gmx_detect_hardware(mdlog, cr, FALSE);
2335     }
2336
2337     /* By default we turn SIMD kernels on, but it might be turned off further down... */
2338     fr->use_simd_kernels = TRUE;
2339
2340     fr->bDomDec = DOMAINDECOMP(cr);
2341
2342     if (check_box(ir->ePBC, box))
2343     {
2344         gmx_fatal(FARGS, check_box(ir->ePBC, box));
2345     }
2346
2347     /* Test particle insertion ? */
2348     if (EI_TPI(ir->eI))
2349     {
2350         /* Set to the size of the molecule to be inserted (the last one) */
2351         /* Because of old style topologies, we have to use the last cg
2352          * instead of the last molecule type.
2353          */
2354         cgs       = &mtop->moltype[mtop->molblock[mtop->nmolblock-1].type].cgs;
2355         fr->n_tpi = cgs->index[cgs->nr] - cgs->index[cgs->nr-1];
2356         if (fr->n_tpi != mtop->mols.index[mtop->mols.nr] - mtop->mols.index[mtop->mols.nr-1])
2357         {
2358             gmx_fatal(FARGS, "The molecule to insert can not consist of multiple charge groups.\nMake it a single charge group.");
2359         }
2360     }
2361     else
2362     {
2363         fr->n_tpi = 0;
2364     }
2365
2366     if (ir->coulombtype == eelRF_NEC_UNSUPPORTED)
2367     {
2368         gmx_fatal(FARGS, "%s electrostatics is no longer supported",
2369                   eel_names[ir->coulombtype]);
2370     }
2371
2372     if (ir->bAdress)
2373     {
2374         gmx_fatal(FARGS, "AdResS simulations are no longer supported");
2375     }
2376     if (ir->useTwinRange)
2377     {
2378         gmx_fatal(FARGS, "Twin-range simulations are no longer supported");
2379     }
2380     /* Copy the user determined parameters */
2381     fr->userint1  = ir->userint1;
2382     fr->userint2  = ir->userint2;
2383     fr->userint3  = ir->userint3;
2384     fr->userint4  = ir->userint4;
2385     fr->userreal1 = ir->userreal1;
2386     fr->userreal2 = ir->userreal2;
2387     fr->userreal3 = ir->userreal3;
2388     fr->userreal4 = ir->userreal4;
2389
2390     /* Shell stuff */
2391     fr->fc_stepsize = ir->fc_stepsize;
2392
2393     /* Free energy */
2394     fr->efep        = ir->efep;
2395     fr->sc_alphavdw = ir->fepvals->sc_alpha;
2396     if (ir->fepvals->bScCoul)
2397     {
2398         fr->sc_alphacoul  = ir->fepvals->sc_alpha;
2399         fr->sc_sigma6_min = gmx::power6(ir->fepvals->sc_sigma_min);
2400     }
2401     else
2402     {
2403         fr->sc_alphacoul  = 0;
2404         fr->sc_sigma6_min = 0; /* only needed when bScCoul is on */
2405     }
2406     fr->sc_power      = ir->fepvals->sc_power;
2407     fr->sc_r_power    = ir->fepvals->sc_r_power;
2408     fr->sc_sigma6_def = gmx::power6(ir->fepvals->sc_sigma);
2409
2410     env = getenv("GMX_SCSIGMA_MIN");
2411     if (env != NULL)
2412     {
2413         dbl = 0;
2414         sscanf(env, "%20lf", &dbl);
2415         fr->sc_sigma6_min = gmx::power6(dbl);
2416         if (fp)
2417         {
2418             fprintf(fp, "Setting the minimum soft core sigma to %g nm\n", dbl);
2419         }
2420     }
2421
2422     fr->bNonbonded = TRUE;
2423     if (getenv("GMX_NO_NONBONDED") != NULL)
2424     {
2425         /* turn off non-bonded calculations */
2426         fr->bNonbonded = FALSE;
2427         GMX_LOG(mdlog.warning).asParagraph().appendText(
2428                 "Found environment variable GMX_NO_NONBONDED.\n"
2429                 "Disabling nonbonded calculations.");
2430     }
2431
2432     bGenericKernelOnly = FALSE;
2433
2434     /* We now check in the NS code whether a particular combination of interactions
2435      * can be used with water optimization, and disable it if that is not the case.
2436      */
2437
2438     if (getenv("GMX_NB_GENERIC") != NULL)
2439     {
2440         if (fp != NULL)
2441         {
2442             fprintf(fp,
2443                     "Found environment variable GMX_NB_GENERIC.\n"
2444                     "Disabling all interaction-specific nonbonded kernels, will only\n"
2445                     "use the slow generic ones in src/gmxlib/nonbonded/nb_generic.c\n\n");
2446         }
2447         bGenericKernelOnly = TRUE;
2448     }
2449
2450     if (bGenericKernelOnly == TRUE)
2451     {
2452         bNoSolvOpt         = TRUE;
2453     }
2454
2455     if ( (getenv("GMX_DISABLE_SIMD_KERNELS") != NULL) || (getenv("GMX_NOOPTIMIZEDKERNELS") != NULL) )
2456     {
2457         fr->use_simd_kernels = FALSE;
2458         if (fp != NULL)
2459         {
2460             fprintf(fp,
2461                     "\nFound environment variable GMX_DISABLE_SIMD_KERNELS.\n"
2462                     "Disabling the usage of any SIMD-specific non-bonded & bonded kernel routines\n"
2463                     "(e.g. SSE2/SSE4.1/AVX).\n\n");
2464         }
2465     }
2466
2467     fr->bBHAM = (mtop->ffparams.functype[0] == F_BHAM);
2468
2469     /* Check if we can/should do all-vs-all kernels */
2470     fr->bAllvsAll       = can_use_allvsall(ir, FALSE, NULL, NULL);
2471     fr->AllvsAll_work   = NULL;
2472     fr->AllvsAll_workgb = NULL;
2473
2474     /* All-vs-all kernels have not been implemented in 4.6 and later.
2475      * See Redmine #1249. */
2476     if (fr->bAllvsAll)
2477     {
2478         fr->bAllvsAll            = FALSE;
2479         if (fp != NULL)
2480         {
2481             fprintf(fp,
2482                     "\nYour simulation settings would have triggered the efficient all-vs-all\n"
2483                     "kernels in GROMACS 4.5, but these have not been implemented in GROMACS\n"
2484                     "4.6 and 5.x. If performance is important, please use GROMACS 4.5.7\n"
2485                     "or try cutoff-scheme = Verlet.\n\n");
2486         }
2487     }
2488
2489     /* Neighbour searching stuff */
2490     fr->cutoff_scheme = ir->cutoff_scheme;
2491     fr->bGrid         = (ir->ns_type == ensGRID);
2492     fr->ePBC          = ir->ePBC;
2493
2494     if (fr->cutoff_scheme == ecutsGROUP)
2495     {
2496         const char *note = "NOTE: This file uses the deprecated 'group' cutoff_scheme. This will be\n"
2497             "removed in a future release when 'verlet' supports all interaction forms.\n";
2498
2499         if (MASTER(cr))
2500         {
2501             fprintf(stderr, "\n%s\n", note);
2502         }
2503         if (fp != NULL)
2504         {
2505             fprintf(fp, "\n%s\n", note);
2506         }
2507     }
2508
2509     /* Determine if we will do PBC for distances in bonded interactions */
2510     if (fr->ePBC == epbcNONE)
2511     {
2512         fr->bMolPBC = FALSE;
2513     }
2514     else
2515     {
2516         if (!DOMAINDECOMP(cr))
2517         {
2518             gmx_bool bSHAKE;
2519
2520             bSHAKE = (ir->eConstrAlg == econtSHAKE &&
2521                       (gmx_mtop_ftype_count(mtop, F_CONSTR) > 0 ||
2522                        gmx_mtop_ftype_count(mtop, F_CONSTRNC) > 0));
2523
2524             /* The group cut-off scheme and SHAKE assume charge groups
2525              * are whole, but not using molpbc is faster in most cases.
2526              * With intermolecular interactions we need PBC for calculating
2527              * distances between atoms in different molecules.
2528              */
2529             if ((fr->cutoff_scheme == ecutsGROUP || bSHAKE) &&
2530                 !mtop->bIntermolecularInteractions)
2531             {
2532                 fr->bMolPBC = ir->bPeriodicMols;
2533
2534                 if (bSHAKE && fr->bMolPBC)
2535                 {
2536                     gmx_fatal(FARGS, "SHAKE is not supported with periodic molecules");
2537                 }
2538             }
2539             else
2540             {
2541                 fr->bMolPBC = TRUE;
2542
2543                 if (getenv("GMX_USE_GRAPH") != NULL)
2544                 {
2545                     fr->bMolPBC = FALSE;
2546                     if (fp)
2547                     {
2548                         GMX_LOG(mdlog.warning).asParagraph().appendText("GMX_USE_GRAPH is set, using the graph for bonded interactions");
2549                     }
2550
2551                     if (mtop->bIntermolecularInteractions)
2552                     {
2553                         GMX_LOG(mdlog.warning).asParagraph().appendText("WARNING: Molecules linked by intermolecular interactions have to reside in the same periodic image, otherwise artifacts will occur!");
2554                     }
2555                 }
2556
2557                 if (bSHAKE && fr->bMolPBC)
2558                 {
2559                     gmx_fatal(FARGS, "SHAKE is not properly supported with intermolecular interactions. For short simulations where linked molecules remain in the same periodic image, the environment variable GMX_USE_GRAPH can be used to override this check.\n");
2560                 }
2561             }
2562         }
2563         else
2564         {
2565             fr->bMolPBC = dd_bonded_molpbc(cr->dd, fr->ePBC);
2566         }
2567     }
2568     fr->bGB = (ir->implicit_solvent == eisGBSA);
2569
2570     fr->rc_scaling = ir->refcoord_scaling;
2571     copy_rvec(ir->posres_com, fr->posres_com);
2572     copy_rvec(ir->posres_comB, fr->posres_comB);
2573     fr->rlist                    = cutoff_inf(ir->rlist);
2574     fr->eeltype                  = ir->coulombtype;
2575     fr->vdwtype                  = ir->vdwtype;
2576     fr->ljpme_combination_rule   = ir->ljpme_combination_rule;
2577
2578     fr->coulomb_modifier = ir->coulomb_modifier;
2579     fr->vdw_modifier     = ir->vdw_modifier;
2580
2581     /* Electrostatics: Translate from interaction-setting-in-mdp-file to kernel interaction format */
2582     switch (fr->eeltype)
2583     {
2584         case eelCUT:
2585             fr->nbkernel_elec_interaction = (fr->bGB) ? GMX_NBKERNEL_ELEC_GENERALIZEDBORN : GMX_NBKERNEL_ELEC_COULOMB;
2586             break;
2587
2588         case eelRF:
2589         case eelGRF:
2590             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_REACTIONFIELD;
2591             break;
2592
2593         case eelRF_ZERO:
2594             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_REACTIONFIELD;
2595             fr->coulomb_modifier          = eintmodEXACTCUTOFF;
2596             break;
2597
2598         case eelSWITCH:
2599         case eelSHIFT:
2600         case eelUSER:
2601         case eelENCADSHIFT:
2602         case eelPMESWITCH:
2603         case eelPMEUSER:
2604         case eelPMEUSERSWITCH:
2605             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_CUBICSPLINETABLE;
2606             break;
2607
2608         case eelPME:
2609         case eelP3M_AD:
2610         case eelEWALD:
2611             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_EWALD;
2612             break;
2613
2614         default:
2615             gmx_fatal(FARGS, "Unsupported electrostatic interaction: %s", eel_names[fr->eeltype]);
2616             break;
2617     }
2618
2619     /* Vdw: Translate from mdp settings to kernel format */
2620     switch (fr->vdwtype)
2621     {
2622         case evdwCUT:
2623             if (fr->bBHAM)
2624             {
2625                 fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_BUCKINGHAM;
2626             }
2627             else
2628             {
2629                 fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_LENNARDJONES;
2630             }
2631             break;
2632         case evdwPME:
2633             fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_LJEWALD;
2634             break;
2635
2636         case evdwSWITCH:
2637         case evdwSHIFT:
2638         case evdwUSER:
2639         case evdwENCADSHIFT:
2640             fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_CUBICSPLINETABLE;
2641             break;
2642
2643         default:
2644             gmx_fatal(FARGS, "Unsupported vdw interaction: %s", evdw_names[fr->vdwtype]);
2645             break;
2646     }
2647
2648     /* These start out identical to ir, but might be altered if we e.g. tabulate the interaction in the kernel */
2649     fr->nbkernel_elec_modifier    = fr->coulomb_modifier;
2650     fr->nbkernel_vdw_modifier     = fr->vdw_modifier;
2651
2652     fr->rvdw             = cutoff_inf(ir->rvdw);
2653     fr->rvdw_switch      = ir->rvdw_switch;
2654     fr->rcoulomb         = cutoff_inf(ir->rcoulomb);
2655     fr->rcoulomb_switch  = ir->rcoulomb_switch;
2656
2657     fr->bEwald     = EEL_PME_EWALD(fr->eeltype);
2658
2659     fr->reppow     = mtop->ffparams.reppow;
2660
2661     if (ir->cutoff_scheme == ecutsGROUP)
2662     {
2663         fr->bvdwtab    = ((fr->vdwtype != evdwCUT || !gmx_within_tol(fr->reppow, 12.0, 10*GMX_DOUBLE_EPS))
2664                           && !EVDW_PME(fr->vdwtype));
2665         /* We have special kernels for standard Ewald and PME, but the pme-switch ones are tabulated above */
2666         fr->bcoultab   = !(fr->eeltype == eelCUT ||
2667                            fr->eeltype == eelEWALD ||
2668                            fr->eeltype == eelPME ||
2669                            fr->eeltype == eelRF ||
2670                            fr->eeltype == eelRF_ZERO);
2671
2672         /* If the user absolutely wants different switch/shift settings for coul/vdw, it is likely
2673          * going to be faster to tabulate the interaction than calling the generic kernel.
2674          * However, if generic kernels have been requested we keep things analytically.
2675          */
2676         if (fr->nbkernel_elec_modifier == eintmodPOTSWITCH &&
2677             fr->nbkernel_vdw_modifier == eintmodPOTSWITCH &&
2678             bGenericKernelOnly == FALSE)
2679         {
2680             if ((fr->rcoulomb_switch != fr->rvdw_switch) || (fr->rcoulomb != fr->rvdw))
2681             {
2682                 fr->bcoultab = TRUE;
2683                 /* Once we tabulate electrostatics, we can use the switch function for LJ,
2684                  * which would otherwise need two tables.
2685                  */
2686             }
2687         }
2688         else if ((fr->nbkernel_elec_modifier == eintmodPOTSHIFT && fr->nbkernel_vdw_modifier == eintmodPOTSHIFT) ||
2689                  ((fr->nbkernel_elec_interaction == GMX_NBKERNEL_ELEC_REACTIONFIELD &&
2690                    fr->nbkernel_elec_modifier == eintmodEXACTCUTOFF &&
2691                    (fr->nbkernel_vdw_modifier == eintmodPOTSWITCH || fr->nbkernel_vdw_modifier == eintmodPOTSHIFT))))
2692         {
2693             if ((fr->rcoulomb != fr->rvdw) && (bGenericKernelOnly == FALSE))
2694             {
2695                 fr->bcoultab = TRUE;
2696             }
2697         }
2698
2699         if (fr->nbkernel_elec_modifier == eintmodFORCESWITCH)
2700         {
2701             fr->bcoultab = TRUE;
2702         }
2703         if (fr->nbkernel_vdw_modifier == eintmodFORCESWITCH)
2704         {
2705             fr->bvdwtab = TRUE;
2706         }
2707
2708         if (getenv("GMX_REQUIRE_TABLES"))
2709         {
2710             fr->bvdwtab  = TRUE;
2711             fr->bcoultab = TRUE;
2712         }
2713
2714         if (fp)
2715         {
2716             fprintf(fp, "Table routines are used for coulomb: %s\n",
2717                     gmx::boolToString(fr->bcoultab));
2718             fprintf(fp, "Table routines are used for vdw:     %s\n",
2719                     gmx::boolToString(fr->bvdwtab));
2720         }
2721
2722         if (fr->bvdwtab == TRUE)
2723         {
2724             fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_CUBICSPLINETABLE;
2725             fr->nbkernel_vdw_modifier    = eintmodNONE;
2726         }
2727         if (fr->bcoultab == TRUE)
2728         {
2729             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_CUBICSPLINETABLE;
2730             fr->nbkernel_elec_modifier    = eintmodNONE;
2731         }
2732     }
2733
2734     if (ir->cutoff_scheme == ecutsVERLET)
2735     {
2736         if (!gmx_within_tol(fr->reppow, 12.0, 10*GMX_DOUBLE_EPS))
2737         {
2738             gmx_fatal(FARGS, "Cut-off scheme %S only supports LJ repulsion power 12", ecutscheme_names[ir->cutoff_scheme]);
2739         }
2740         fr->bvdwtab  = FALSE;
2741         fr->bcoultab = FALSE;
2742     }
2743
2744     /* This now calculates sum for q and C6 */
2745     set_chargesum(fp, fr, mtop);
2746
2747     /* Tables are used for direct ewald sum */
2748     if (fr->bEwald)
2749     {
2750         if (EEL_PME(ir->coulombtype))
2751         {
2752             if (fp)
2753             {
2754                 fprintf(fp, "Will do PME sum in reciprocal space for electrostatic interactions.\n");
2755             }
2756             if (ir->coulombtype == eelP3M_AD)
2757             {
2758                 please_cite(fp, "Hockney1988");
2759                 please_cite(fp, "Ballenegger2012");
2760             }
2761             else
2762             {
2763                 please_cite(fp, "Essmann95a");
2764             }
2765
2766             if (ir->ewald_geometry == eewg3DC)
2767             {
2768                 bool haveNetCharge = (fabs(fr->qsum[0]) > 1e-4 ||
2769                                       fabs(fr->qsum[1]) > 1e-4);
2770                 if (fp)
2771                 {
2772                     fprintf(fp, "Using the Ewald3DC correction for systems with a slab geometry%s.\n",
2773                             haveNetCharge ? " and net charge" : "");
2774                 }
2775                 please_cite(fp, "In-Chul99a");
2776                 if (haveNetCharge)
2777                 {
2778                     please_cite(fp, "Ballenegger2009");
2779                 }
2780             }
2781         }
2782         fr->ewaldcoeff_q = calc_ewaldcoeff_q(ir->rcoulomb, ir->ewald_rtol);
2783         init_ewald_tab(&(fr->ewald_table), ir, fp);
2784         if (fp)
2785         {
2786             fprintf(fp, "Using a Gaussian width (1/beta) of %g nm for Ewald\n",
2787                     1/fr->ewaldcoeff_q);
2788         }
2789     }
2790
2791     if (EVDW_PME(ir->vdwtype))
2792     {
2793         if (fp)
2794         {
2795             fprintf(fp, "Will do PME sum in reciprocal space for LJ dispersion interactions.\n");
2796         }
2797         please_cite(fp, "Essmann95a");
2798         fr->ewaldcoeff_lj = calc_ewaldcoeff_lj(ir->rvdw, ir->ewald_rtol_lj);
2799         if (fp)
2800         {
2801             fprintf(fp, "Using a Gaussian width (1/beta) of %g nm for LJ Ewald\n",
2802                     1/fr->ewaldcoeff_lj);
2803         }
2804     }
2805
2806     /* Electrostatics */
2807     fr->epsilon_r       = ir->epsilon_r;
2808     fr->epsilon_rf      = ir->epsilon_rf;
2809     fr->fudgeQQ         = mtop->ffparams.fudgeQQ;
2810
2811     /* Parameters for generalized RF */
2812     fr->zsquare = 0.0;
2813     fr->temp    = 0.0;
2814
2815     if (fr->eeltype == eelGRF)
2816     {
2817         init_generalized_rf(fp, mtop, ir, fr);
2818     }
2819
2820     fr->bF_NoVirSum = (EEL_FULL(fr->eeltype) || EVDW_PME(fr->vdwtype) ||
2821                        gmx_mtop_ftype_count(mtop, F_POSRES) > 0 ||
2822                        gmx_mtop_ftype_count(mtop, F_FBPOSRES) > 0);
2823
2824     /* Initialization call after setting bF_NoVirSum,
2825      * since it efield->initForcerec also sets this to true.
2826      */
2827     ir->efield->initForcerec(fr);
2828
2829     if (fr->bF_NoVirSum)
2830     {
2831         fr->forceBufferNoVirialSummation = new PaddedRVecVector;
2832     }
2833
2834     if (fr->cutoff_scheme == ecutsGROUP &&
2835         ncg_mtop(mtop) > fr->cg_nalloc && !DOMAINDECOMP(cr))
2836     {
2837         /* Count the total number of charge groups */
2838         fr->cg_nalloc = ncg_mtop(mtop);
2839         srenew(fr->cg_cm, fr->cg_nalloc);
2840     }
2841     if (fr->shift_vec == NULL)
2842     {
2843         snew(fr->shift_vec, SHIFTS);
2844     }
2845
2846     if (fr->fshift == NULL)
2847     {
2848         snew(fr->fshift, SHIFTS);
2849     }
2850
2851     if (fr->nbfp == NULL)
2852     {
2853         fr->ntype = mtop->ffparams.atnr;
2854         fr->nbfp  = mk_nbfp(&mtop->ffparams, fr->bBHAM);
2855         if (EVDW_PME(fr->vdwtype))
2856         {
2857             fr->ljpme_c6grid  = make_ljpme_c6grid(&mtop->ffparams, fr);
2858         }
2859     }
2860
2861     /* Copy the energy group exclusions */
2862     fr->egp_flags = ir->opts.egp_flags;
2863
2864     /* Van der Waals stuff */
2865     if ((fr->vdwtype != evdwCUT) && (fr->vdwtype != evdwUSER) && !fr->bBHAM)
2866     {
2867         if (fr->rvdw_switch >= fr->rvdw)
2868         {
2869             gmx_fatal(FARGS, "rvdw_switch (%f) must be < rvdw (%f)",
2870                       fr->rvdw_switch, fr->rvdw);
2871         }
2872         if (fp)
2873         {
2874             fprintf(fp, "Using %s Lennard-Jones, switch between %g and %g nm\n",
2875                     (fr->eeltype == eelSWITCH) ? "switched" : "shifted",
2876                     fr->rvdw_switch, fr->rvdw);
2877         }
2878     }
2879
2880     if (fr->bBHAM && EVDW_PME(fr->vdwtype))
2881     {
2882         gmx_fatal(FARGS, "LJ PME not supported with Buckingham");
2883     }
2884
2885     if (fr->bBHAM && (fr->vdwtype == evdwSHIFT || fr->vdwtype == evdwSWITCH))
2886     {
2887         gmx_fatal(FARGS, "Switch/shift interaction not supported with Buckingham");
2888     }
2889
2890     if (fr->bBHAM && fr->cutoff_scheme == ecutsVERLET)
2891     {
2892         gmx_fatal(FARGS, "Verlet cutoff-scheme is not supported with Buckingham");
2893     }
2894
2895     if (fp)
2896     {
2897         fprintf(fp, "Cut-off's:   NS: %g   Coulomb: %g   %s: %g\n",
2898                 fr->rlist, fr->rcoulomb, fr->bBHAM ? "BHAM" : "LJ", fr->rvdw);
2899     }
2900
2901     fr->eDispCorr = ir->eDispCorr;
2902     fr->numAtomsForDispersionCorrection = mtop->natoms;
2903     if (ir->eDispCorr != edispcNO)
2904     {
2905         set_avcsixtwelve(fp, fr, mtop);
2906     }
2907
2908     if (fr->bBHAM)
2909     {
2910         set_bham_b_max(fp, fr, mtop);
2911     }
2912
2913     fr->gb_epsilon_solvent = ir->gb_epsilon_solvent;
2914
2915     /* Copy the GBSA data (radius, volume and surftens for each
2916      * atomtype) from the topology atomtype section to forcerec.
2917      */
2918     snew(fr->atype_radius, fr->ntype);
2919     snew(fr->atype_vol, fr->ntype);
2920     snew(fr->atype_surftens, fr->ntype);
2921     snew(fr->atype_gb_radius, fr->ntype);
2922     snew(fr->atype_S_hct, fr->ntype);
2923
2924     if (mtop->atomtypes.nr > 0)
2925     {
2926         for (i = 0; i < fr->ntype; i++)
2927         {
2928             fr->atype_radius[i] = mtop->atomtypes.radius[i];
2929         }
2930         for (i = 0; i < fr->ntype; i++)
2931         {
2932             fr->atype_vol[i] = mtop->atomtypes.vol[i];
2933         }
2934         for (i = 0; i < fr->ntype; i++)
2935         {
2936             fr->atype_surftens[i] = mtop->atomtypes.surftens[i];
2937         }
2938         for (i = 0; i < fr->ntype; i++)
2939         {
2940             fr->atype_gb_radius[i] = mtop->atomtypes.gb_radius[i];
2941         }
2942         for (i = 0; i < fr->ntype; i++)
2943         {
2944             fr->atype_S_hct[i] = mtop->atomtypes.S_hct[i];
2945         }
2946     }
2947
2948     /* Generate the GB table if needed */
2949     if (fr->bGB)
2950     {
2951 #if GMX_DOUBLE
2952         fr->gbtabscale = 2000;
2953 #else
2954         fr->gbtabscale = 500;
2955 #endif
2956
2957         fr->gbtabr = 100;
2958         fr->gbtab  = make_gb_table(fr);
2959
2960         init_gb(&fr->born, fr, ir, mtop, ir->gb_algorithm);
2961
2962         /* Copy local gb data (for dd, this is done in dd_partition_system) */
2963         if (!DOMAINDECOMP(cr))
2964         {
2965             make_local_gb(cr, fr->born, ir->gb_algorithm);
2966         }
2967     }
2968
2969     /* Set the charge scaling */
2970     if (fr->epsilon_r != 0)
2971     {
2972         fr->epsfac = ONE_4PI_EPS0/fr->epsilon_r;
2973     }
2974     else
2975     {
2976         /* eps = 0 is infinite dieletric: no coulomb interactions */
2977         fr->epsfac = 0;
2978     }
2979
2980     /* Reaction field constants */
2981     if (EEL_RF(fr->eeltype))
2982     {
2983         calc_rffac(fp, fr->eeltype, fr->epsilon_r, fr->epsilon_rf,
2984                    fr->rcoulomb, fr->temp, fr->zsquare, box,
2985                    &fr->kappa, &fr->k_rf, &fr->c_rf);
2986     }
2987
2988     /* Construct tables for the group scheme. A little unnecessary to
2989      * make both vdw and coul tables sometimes, but what the
2990      * heck. Note that both cutoff schemes construct Ewald tables in
2991      * init_interaction_const_tables. */
2992     needGroupSchemeTables = (ir->cutoff_scheme == ecutsGROUP &&
2993                              (fr->bcoultab || fr->bvdwtab));
2994
2995     negp_pp   = ir->opts.ngener - ir->nwall;
2996     negptable = 0;
2997     if (!needGroupSchemeTables)
2998     {
2999         bSomeNormalNbListsAreInUse = TRUE;
3000         fr->nnblists               = 1;
3001     }
3002     else
3003     {
3004         bSomeNormalNbListsAreInUse = FALSE;
3005         for (egi = 0; egi < negp_pp; egi++)
3006         {
3007             for (egj = egi; egj < negp_pp; egj++)
3008             {
3009                 egp_flags = ir->opts.egp_flags[GID(egi, egj, ir->opts.ngener)];
3010                 if (!(egp_flags & EGP_EXCL))
3011                 {
3012                     if (egp_flags & EGP_TABLE)
3013                     {
3014                         negptable++;
3015                     }
3016                     else
3017                     {
3018                         bSomeNormalNbListsAreInUse = TRUE;
3019                     }
3020                 }
3021             }
3022         }
3023         if (bSomeNormalNbListsAreInUse)
3024         {
3025             fr->nnblists = negptable + 1;
3026         }
3027         else
3028         {
3029             fr->nnblists = negptable;
3030         }
3031         if (fr->nnblists > 1)
3032         {
3033             snew(fr->gid2nblists, ir->opts.ngener*ir->opts.ngener);
3034         }
3035     }
3036
3037     snew(fr->nblists, fr->nnblists);
3038
3039     /* This code automatically gives table length tabext without cut-off's,
3040      * in that case grompp should already have checked that we do not need
3041      * normal tables and we only generate tables for 1-4 interactions.
3042      */
3043     rtab = ir->rlist + ir->tabext;
3044
3045     if (needGroupSchemeTables)
3046     {
3047         /* make tables for ordinary interactions */
3048         if (bSomeNormalNbListsAreInUse)
3049         {
3050             make_nbf_tables(fp, fr, rtab, tabfn, NULL, NULL, &fr->nblists[0]);
3051             m = 1;
3052         }
3053         else
3054         {
3055             m = 0;
3056         }
3057         if (negptable > 0)
3058         {
3059             /* Read the special tables for certain energy group pairs */
3060             nm_ind = mtop->groups.grps[egcENER].nm_ind;
3061             for (egi = 0; egi < negp_pp; egi++)
3062             {
3063                 for (egj = egi; egj < negp_pp; egj++)
3064                 {
3065                     egp_flags = ir->opts.egp_flags[GID(egi, egj, ir->opts.ngener)];
3066                     if ((egp_flags & EGP_TABLE) && !(egp_flags & EGP_EXCL))
3067                     {
3068                         if (fr->nnblists > 1)
3069                         {
3070                             fr->gid2nblists[GID(egi, egj, ir->opts.ngener)] = m;
3071                         }
3072                         /* Read the table file with the two energy groups names appended */
3073                         make_nbf_tables(fp, fr, rtab, tabfn,
3074                                         *mtop->groups.grpname[nm_ind[egi]],
3075                                         *mtop->groups.grpname[nm_ind[egj]],
3076                                         &fr->nblists[m]);
3077                         m++;
3078                     }
3079                     else if (fr->nnblists > 1)
3080                     {
3081                         fr->gid2nblists[GID(egi, egj, ir->opts.ngener)] = 0;
3082                     }
3083                 }
3084             }
3085         }
3086     }
3087
3088     /* Tables might not be used for the potential modifier
3089      * interactions per se, but we still need them to evaluate
3090      * switch/shift dispersion corrections in this case. */
3091     if (fr->eDispCorr != edispcNO)
3092     {
3093         fr->dispersionCorrectionTable = makeDispersionCorrectionTable(fp, fr, rtab, tabfn);
3094     }
3095
3096     /* We want to use unmodified tables for 1-4 coulombic
3097      * interactions, so we must in general have an extra set of
3098      * tables. */
3099     if (gmx_mtop_ftype_count(mtop, F_LJ14) > 0 ||
3100         gmx_mtop_ftype_count(mtop, F_LJC14_Q) > 0 ||
3101         gmx_mtop_ftype_count(mtop, F_LJC_PAIRS_NB) > 0)
3102     {
3103         fr->pairsTable = make_tables(fp, fr, tabpfn, rtab,
3104                                      GMX_MAKETABLES_14ONLY);
3105     }
3106
3107     /* Wall stuff */
3108     fr->nwall = ir->nwall;
3109     if (ir->nwall && ir->wall_type == ewtTABLE)
3110     {
3111         make_wall_tables(fp, ir, tabfn, &mtop->groups, fr);
3112     }
3113
3114     if (fcd && tabbfnm)
3115     {
3116         // Need to catch std::bad_alloc
3117         // TODO Don't need to catch this here, when merging with master branch
3118         try
3119         {
3120             fcd->bondtab  = make_bonded_tables(fp,
3121                                                F_TABBONDS, F_TABBONDSNC,
3122                                                mtop, tabbfnm, "b");
3123             fcd->angletab = make_bonded_tables(fp,
3124                                                F_TABANGLES, -1,
3125                                                mtop, tabbfnm, "a");
3126             fcd->dihtab   = make_bonded_tables(fp,
3127                                                F_TABDIHS, -1,
3128                                                mtop, tabbfnm, "d");
3129         }
3130         GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
3131     }
3132     else
3133     {
3134         if (debug)
3135         {
3136             fprintf(debug, "No fcdata or table file name passed, can not read table, can not do bonded interactions\n");
3137         }
3138     }
3139
3140     /* QM/MM initialization if requested
3141      */
3142     if (ir->bQMMM)
3143     {
3144         fprintf(stderr, "QM/MM calculation requested.\n");
3145     }
3146
3147     fr->bQMMM      = ir->bQMMM;
3148     fr->qr         = mk_QMMMrec();
3149
3150     /* Set all the static charge group info */
3151     fr->cginfo_mb = init_cginfo_mb(fp, mtop, fr, bNoSolvOpt,
3152                                    &bFEP_NonBonded,
3153                                    &fr->bExcl_IntraCGAll_InterCGNone);
3154     if (DOMAINDECOMP(cr))
3155     {
3156         fr->cginfo = NULL;
3157     }
3158     else
3159     {
3160         fr->cginfo = cginfo_expand(mtop->nmolblock, fr->cginfo_mb);
3161     }
3162
3163     if (!DOMAINDECOMP(cr))
3164     {
3165         forcerec_set_ranges(fr, ncg_mtop(mtop), ncg_mtop(mtop),
3166                             mtop->natoms, mtop->natoms, mtop->natoms);
3167     }
3168
3169     fr->print_force = print_force;
3170
3171
3172     /* coarse load balancing vars */
3173     fr->t_fnbf    = 0.;
3174     fr->t_wait    = 0.;
3175     fr->timesteps = 0;
3176
3177     /* Initialize neighbor search */
3178     snew(fr->ns, 1);
3179     init_ns(fp, cr, fr->ns, fr, mtop);
3180
3181     if (cr->duty & DUTY_PP)
3182     {
3183         gmx_nonbonded_setup(fr, bGenericKernelOnly);
3184     }
3185
3186     /* Initialize the thread working data for bonded interactions */
3187     init_bonded_threading(fp, mtop->groups.grps[egcENER].nr,
3188                           &fr->bonded_threading);
3189
3190     fr->nthread_ewc = gmx_omp_nthreads_get(emntBonded);
3191     snew(fr->ewc_t, fr->nthread_ewc);
3192
3193     /* fr->ic is used both by verlet and group kernels (to some extent) now */
3194     init_interaction_const(fp, &fr->ic, fr);
3195     init_interaction_const_tables(fp, fr->ic, rtab);
3196
3197     if (fr->cutoff_scheme == ecutsVERLET)
3198     {
3199         // We checked the cut-offs in grompp, but double-check here.
3200         // We have PME+LJcutoff kernels for rcoulomb>rvdw.
3201         if (EEL_PME_EWALD(ir->coulombtype) && ir->vdwtype == eelCUT)
3202         {
3203             GMX_RELEASE_ASSERT(ir->rcoulomb >= ir->rvdw, "With Verlet lists and PME we should have rcoulomb>=rvdw");
3204         }
3205         else
3206         {
3207             GMX_RELEASE_ASSERT(ir->rcoulomb == ir->rvdw, "With Verlet lists and no PME rcoulomb and rvdw should be identical");
3208         }
3209
3210         init_nb_verlet(fp, mdlog, &fr->nbv, bFEP_NonBonded, ir, fr, cr, nbpu_opt);
3211     }
3212
3213     if (ir->eDispCorr != edispcNO)
3214     {
3215         calc_enervirdiff(fp, ir->eDispCorr, fr);
3216     }
3217 }
3218
3219 #define pr_real(fp, r) fprintf(fp, "%s: %e\n",#r, r)
3220 #define pr_int(fp, i)  fprintf((fp), "%s: %d\n",#i, i)
3221 #define pr_bool(fp, b) fprintf((fp), "%s: %s\n",#b, gmx::boolToString(b))
3222
3223 void pr_forcerec(FILE *fp, t_forcerec *fr)
3224 {
3225     int i;
3226
3227     pr_real(fp, fr->rlist);
3228     pr_real(fp, fr->rcoulomb);
3229     pr_real(fp, fr->fudgeQQ);
3230     pr_bool(fp, fr->bGrid);
3231     /*pr_int(fp,fr->cg0);
3232        pr_int(fp,fr->hcg);*/
3233     for (i = 0; i < fr->nnblists; i++)
3234     {
3235         pr_int(fp, fr->nblists[i].table_elec_vdw->n);
3236     }
3237     pr_real(fp, fr->rcoulomb_switch);
3238     pr_real(fp, fr->rcoulomb);
3239
3240     fflush(fp);
3241 }
3242
3243 /* Frees GPU memory and destroys the GPU context.
3244  *
3245  * Note that this function needs to be called even if GPUs are not used
3246  * in this run because the PME ranks have no knowledge of whether GPUs
3247  * are used or not, but all ranks need to enter the barrier below.
3248  */
3249 void free_gpu_resources(const t_forcerec     *fr,
3250                         const t_commrec      *cr,
3251                         const gmx_gpu_info_t *gpu_info,
3252                         const gmx_gpu_opt_t  *gpu_opt)
3253 {
3254     gmx_bool bIsPPrankUsingGPU;
3255     char     gpu_err_str[STRLEN];
3256
3257     bIsPPrankUsingGPU = (cr->duty & DUTY_PP) && fr && fr->nbv && fr->nbv->bUseGPU;
3258
3259     if (bIsPPrankUsingGPU)
3260     {
3261         /* free nbnxn data in GPU memory */
3262         nbnxn_gpu_free(fr->nbv->gpu_nbv);
3263         /* stop the GPU profiler (only CUDA) */
3264         stopGpuProfiler();
3265
3266         /* With tMPI we need to wait for all ranks to finish deallocation before
3267          * destroying the CUDA context in free_gpu() as some tMPI ranks may be sharing
3268          * GPU and context.
3269          *
3270          * This is not a concern in OpenCL where we use one context per rank which
3271          * is freed in nbnxn_gpu_free().
3272          *
3273          * Note: as only PP ranks need to free GPU resources, so it is safe to
3274          * not call the barrier on PME ranks.
3275          */
3276 #if GMX_THREAD_MPI
3277         if (PAR(cr))
3278         {
3279             gmx_barrier(cr);
3280         }
3281 #endif  /* GMX_THREAD_MPI */
3282
3283         /* uninitialize GPU (by destroying the context) */
3284         if (!free_cuda_gpu(cr->rank_pp_intranode, gpu_err_str, gpu_info, gpu_opt))
3285         {
3286             gmx_warning("On rank %d failed to free GPU #%d: %s",
3287                         cr->nodeid, get_current_cuda_gpu_device_id(), gpu_err_str);
3288         }
3289     }
3290 }