Merge branch release-5-1 into release-2016
[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,2017, 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/md_logging.h"
57 #include "gromacs/gmxlib/network.h"
58 #include "gromacs/gmxlib/nonbonded/nonbonded.h"
59 #include "gromacs/gpu_utils/gpu_utils.h"
60 #include "gromacs/hardware/detecthardware.h"
61 #include "gromacs/listed-forces/manage-threading.h"
62 #include "gromacs/listed-forces/pairs.h"
63 #include "gromacs/math/calculate-ewald-splitting-coefficient.h"
64 #include "gromacs/math/functions.h"
65 #include "gromacs/math/units.h"
66 #include "gromacs/math/utilities.h"
67 #include "gromacs/math/vec.h"
68 #include "gromacs/mdlib/force.h"
69 #include "gromacs/mdlib/forcerec-threading.h"
70 #include "gromacs/mdlib/gmx_omp_nthreads.h"
71 #include "gromacs/mdlib/md_support.h"
72 #include "gromacs/mdlib/nb_verlet.h"
73 #include "gromacs/mdlib/nbnxn_atomdata.h"
74 #include "gromacs/mdlib/nbnxn_gpu_data_mgmt.h"
75 #include "gromacs/mdlib/nbnxn_search.h"
76 #include "gromacs/mdlib/nbnxn_simd.h"
77 #include "gromacs/mdlib/nbnxn_util.h"
78 #include "gromacs/mdlib/ns.h"
79 #include "gromacs/mdlib/qmmm.h"
80 #include "gromacs/mdlib/sim_util.h"
81 #include "gromacs/mdtypes/commrec.h"
82 #include "gromacs/mdtypes/fcdata.h"
83 #include "gromacs/mdtypes/group.h"
84 #include "gromacs/mdtypes/inputrec.h"
85 #include "gromacs/mdtypes/md_enums.h"
86 #include "gromacs/pbcutil/ishift.h"
87 #include "gromacs/pbcutil/pbc.h"
88 #include "gromacs/simd/simd.h"
89 #include "gromacs/tables/forcetable.h"
90 #include "gromacs/topology/mtop_util.h"
91 #include "gromacs/trajectory/trajectoryframe.h"
92 #include "gromacs/utility/cstringutil.h"
93 #include "gromacs/utility/exceptions.h"
94 #include "gromacs/utility/fatalerror.h"
95 #include "gromacs/utility/gmxassert.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         fr->f_novirsum_n = natoms_f_novirsum;
1508         if (fr->f_novirsum_n > fr->f_novirsum_nalloc)
1509         {
1510             fr->f_novirsum_nalloc = over_alloc_dd(fr->f_novirsum_n);
1511             srenew(fr->f_novirsum_alloc, fr->f_novirsum_nalloc);
1512         }
1513     }
1514     else
1515     {
1516         fr->f_novirsum_n = 0;
1517     }
1518 }
1519
1520 static real cutoff_inf(real cutoff)
1521 {
1522     if (cutoff == 0)
1523     {
1524         cutoff = GMX_CUTOFF_INF;
1525     }
1526
1527     return cutoff;
1528 }
1529
1530 gmx_bool can_use_allvsall(const t_inputrec *ir, gmx_bool bPrintNote, t_commrec *cr, FILE *fp)
1531 {
1532     gmx_bool bAllvsAll;
1533
1534     bAllvsAll =
1535         (
1536             ir->rlist == 0            &&
1537             ir->rcoulomb == 0         &&
1538             ir->rvdw == 0             &&
1539             ir->ePBC == epbcNONE      &&
1540             ir->vdwtype == evdwCUT    &&
1541             ir->coulombtype == eelCUT &&
1542             ir->efep == efepNO        &&
1543             (ir->implicit_solvent == eisNO ||
1544              (ir->implicit_solvent == eisGBSA && (ir->gb_algorithm == egbSTILL ||
1545                                                   ir->gb_algorithm == egbHCT   ||
1546                                                   ir->gb_algorithm == egbOBC))) &&
1547             getenv("GMX_NO_ALLVSALL") == NULL
1548         );
1549
1550     if (bAllvsAll && ir->opts.ngener > 1)
1551     {
1552         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";
1553
1554         if (bPrintNote)
1555         {
1556             if (MASTER(cr))
1557             {
1558                 fprintf(stderr, "\n%s\n", note);
1559             }
1560             if (fp != NULL)
1561             {
1562                 fprintf(fp, "\n%s\n", note);
1563             }
1564         }
1565         bAllvsAll = FALSE;
1566     }
1567
1568     if (bAllvsAll && fp && MASTER(cr))
1569     {
1570         fprintf(fp, "\nUsing SIMD all-vs-all kernels.\n\n");
1571     }
1572
1573     return bAllvsAll;
1574 }
1575
1576
1577 gmx_bool nbnxn_gpu_acceleration_supported(FILE             *fplog,
1578                                           const t_commrec  *cr,
1579                                           const t_inputrec *ir,
1580                                           gmx_bool          bRerunMD)
1581 {
1582     if (bRerunMD && ir->opts.ngener > 1)
1583     {
1584         /* Rerun execution time is dominated by I/O and pair search,
1585          * so GPUs are not very useful, plus they do not support more
1586          * than one energy group. If the user requested GPUs
1587          * explicitly, a fatal error is given later.  With non-reruns,
1588          * we fall back to a single whole-of system energy group
1589          * (which runs much faster than a multiple-energy-groups
1590          * implementation would), and issue a note in the .log
1591          * file. Users can re-run if they want the information. */
1592         md_print_warn(cr, fplog, "Rerun with energy groups is not implemented for GPUs, falling back to the CPU\n");
1593         return FALSE;
1594     }
1595
1596     return TRUE;
1597 }
1598
1599 gmx_bool nbnxn_simd_supported(FILE             *fplog,
1600                               const t_commrec  *cr,
1601                               const t_inputrec *ir)
1602 {
1603     if (ir->vdwtype == evdwPME && ir->ljpme_combination_rule == eljpmeLB)
1604     {
1605         /* LJ PME with LB combination rule does 7 mesh operations.
1606          * This so slow that we don't compile SIMD non-bonded kernels
1607          * for that. */
1608         md_print_warn(cr, fplog, "LJ-PME with Lorentz-Berthelot is not supported with SIMD kernels, falling back to plain C kernels\n");
1609         return FALSE;
1610     }
1611
1612     return TRUE;
1613 }
1614
1615
1616 static void pick_nbnxn_kernel_cpu(const t_inputrec gmx_unused *ir,
1617                                   int                         *kernel_type,
1618                                   int                         *ewald_excl)
1619 {
1620     *kernel_type = nbnxnk4x4_PlainC;
1621     *ewald_excl  = ewaldexclTable;
1622
1623 #if GMX_SIMD
1624     {
1625 #ifdef GMX_NBNXN_SIMD_4XN
1626         *kernel_type = nbnxnk4xN_SIMD_4xN;
1627 #endif
1628 #ifdef GMX_NBNXN_SIMD_2XNN
1629         *kernel_type = nbnxnk4xN_SIMD_2xNN;
1630 #endif
1631
1632 #if defined GMX_NBNXN_SIMD_2XNN && defined GMX_NBNXN_SIMD_4XN
1633         /* We need to choose if we want 2x(N+N) or 4xN kernels.
1634          * Currently this is based on the SIMD acceleration choice,
1635          * but it might be better to decide this at runtime based on CPU.
1636          *
1637          * 4xN calculates more (zero) interactions, but has less pair-search
1638          * work and much better kernel instruction scheduling.
1639          *
1640          * Up till now we have only seen that on Intel Sandy/Ivy Bridge,
1641          * which doesn't have FMA, both the analytical and tabulated Ewald
1642          * kernels have similar pair rates for 4x8 and 2x(4+4), so we choose
1643          * 2x(4+4) because it results in significantly fewer pairs.
1644          * For RF, the raw pair rate of the 4x8 kernel is higher than 2x(4+4),
1645          * 10% with HT, 50% without HT. As we currently don't detect the actual
1646          * use of HT, use 4x8 to avoid a potential performance hit.
1647          * On Intel Haswell 4x8 is always faster.
1648          */
1649         *kernel_type = nbnxnk4xN_SIMD_4xN;
1650
1651 #if !GMX_SIMD_HAVE_FMA
1652         if (EEL_PME_EWALD(ir->coulombtype) ||
1653             EVDW_PME(ir->vdwtype))
1654         {
1655             /* We have Ewald kernels without FMA (Intel Sandy/Ivy Bridge).
1656              * There are enough instructions to make 2x(4+4) efficient.
1657              */
1658             *kernel_type = nbnxnk4xN_SIMD_2xNN;
1659         }
1660 #endif
1661 #endif  /* GMX_NBNXN_SIMD_2XNN && GMX_NBNXN_SIMD_4XN */
1662
1663
1664         if (getenv("GMX_NBNXN_SIMD_4XN") != NULL)
1665         {
1666 #ifdef GMX_NBNXN_SIMD_4XN
1667             *kernel_type = nbnxnk4xN_SIMD_4xN;
1668 #else
1669             gmx_fatal(FARGS, "SIMD 4xN kernels requested, but GROMACS has been compiled without support for these kernels");
1670 #endif
1671         }
1672         if (getenv("GMX_NBNXN_SIMD_2XNN") != NULL)
1673         {
1674 #ifdef GMX_NBNXN_SIMD_2XNN
1675             *kernel_type = nbnxnk4xN_SIMD_2xNN;
1676 #else
1677             gmx_fatal(FARGS, "SIMD 2x(N+N) kernels requested, but GROMACS has been compiled without support for these kernels");
1678 #endif
1679         }
1680
1681         /* Analytical Ewald exclusion correction is only an option in
1682          * the SIMD kernel.
1683          * Since table lookup's don't parallelize with SIMD, analytical
1684          * will probably always be faster for a SIMD width of 8 or more.
1685          * With FMA analytical is sometimes faster for a width if 4 as well.
1686          * On BlueGene/Q, this is faster regardless of precision.
1687          * In single precision, this is faster on Bulldozer.
1688          */
1689 #if GMX_SIMD_REAL_WIDTH >= 8 || \
1690         (GMX_SIMD_REAL_WIDTH >= 4 && GMX_SIMD_HAVE_FMA && !GMX_DOUBLE) || GMX_SIMD_IBM_QPX
1691         *ewald_excl = ewaldexclAnalytical;
1692 #endif
1693         if (getenv("GMX_NBNXN_EWALD_TABLE") != NULL)
1694         {
1695             *ewald_excl = ewaldexclTable;
1696         }
1697         if (getenv("GMX_NBNXN_EWALD_ANALYTICAL") != NULL)
1698         {
1699             *ewald_excl = ewaldexclAnalytical;
1700         }
1701
1702     }
1703 #endif // GMX_SIMD
1704 }
1705
1706
1707 const char *lookup_nbnxn_kernel_name(int kernel_type)
1708 {
1709     const char *returnvalue = NULL;
1710     switch (kernel_type)
1711     {
1712         case nbnxnkNotSet:
1713             returnvalue = "not set";
1714             break;
1715         case nbnxnk4x4_PlainC:
1716             returnvalue = "plain C";
1717             break;
1718         case nbnxnk4xN_SIMD_4xN:
1719         case nbnxnk4xN_SIMD_2xNN:
1720 #if GMX_SIMD
1721             returnvalue = "SIMD";
1722 #else  // GMX_SIMD
1723             returnvalue = "not available";
1724 #endif // GMX_SIMD
1725             break;
1726         case nbnxnk8x8x8_GPU: returnvalue    = "GPU"; break;
1727         case nbnxnk8x8x8_PlainC: returnvalue = "plain C"; break;
1728
1729         case nbnxnkNR:
1730         default:
1731             gmx_fatal(FARGS, "Illegal kernel type selected");
1732             returnvalue = NULL;
1733             break;
1734     }
1735     return returnvalue;
1736 };
1737
1738 static void pick_nbnxn_kernel(FILE                *fp,
1739                               const t_commrec     *cr,
1740                               gmx_bool             use_simd_kernels,
1741                               gmx_bool             bUseGPU,
1742                               gmx_bool             bEmulateGPU,
1743                               const t_inputrec    *ir,
1744                               int                 *kernel_type,
1745                               int                 *ewald_excl,
1746                               gmx_bool             bDoNonbonded)
1747 {
1748     assert(kernel_type);
1749
1750     *kernel_type = nbnxnkNotSet;
1751     *ewald_excl  = ewaldexclTable;
1752
1753     if (bEmulateGPU)
1754     {
1755         *kernel_type = nbnxnk8x8x8_PlainC;
1756
1757         if (bDoNonbonded)
1758         {
1759             md_print_warn(cr, fp, "Emulating a GPU run on the CPU (slow)");
1760         }
1761     }
1762     else if (bUseGPU)
1763     {
1764         *kernel_type = nbnxnk8x8x8_GPU;
1765     }
1766
1767     if (*kernel_type == nbnxnkNotSet)
1768     {
1769         if (use_simd_kernels &&
1770             nbnxn_simd_supported(fp, cr, ir))
1771         {
1772             pick_nbnxn_kernel_cpu(ir, kernel_type, ewald_excl);
1773         }
1774         else
1775         {
1776             *kernel_type = nbnxnk4x4_PlainC;
1777         }
1778     }
1779
1780     if (bDoNonbonded && fp != NULL)
1781     {
1782         fprintf(fp, "\nUsing %s %dx%d non-bonded kernels\n\n",
1783                 lookup_nbnxn_kernel_name(*kernel_type),
1784                 nbnxn_kernel_to_cluster_i_size(*kernel_type),
1785                 nbnxn_kernel_to_cluster_j_size(*kernel_type));
1786
1787         if (nbnxnk4x4_PlainC == *kernel_type ||
1788             nbnxnk8x8x8_PlainC == *kernel_type)
1789         {
1790             md_print_warn(cr, fp,
1791                           "WARNING: Using the slow %s kernels. This should\n"
1792                           "not happen during routine usage on supported platforms.\n\n",
1793                           lookup_nbnxn_kernel_name(*kernel_type));
1794         }
1795     }
1796 }
1797
1798 static void pick_nbnxn_resources(FILE                *fp,
1799                                  const t_commrec     *cr,
1800                                  const gmx_hw_info_t *hwinfo,
1801                                  gmx_bool             bDoNonbonded,
1802                                  gmx_bool            *bUseGPU,
1803                                  gmx_bool            *bEmulateGPU,
1804                                  const gmx_gpu_opt_t *gpu_opt)
1805 {
1806     gmx_bool bEmulateGPUEnvVarSet;
1807     char     gpu_err_str[STRLEN];
1808
1809     *bUseGPU = FALSE;
1810
1811     bEmulateGPUEnvVarSet = (getenv("GMX_EMULATE_GPU") != NULL);
1812
1813     /* Run GPU emulation mode if GMX_EMULATE_GPU is defined. Because
1814      * GPUs (currently) only handle non-bonded calculations, we will
1815      * automatically switch to emulation if non-bonded calculations are
1816      * turned off via GMX_NO_NONBONDED - this is the simple and elegant
1817      * way to turn off GPU initialization, data movement, and cleanup.
1818      *
1819      * GPU emulation can be useful to assess the performance one can expect by
1820      * adding GPU(s) to the machine. The conditional below allows this even
1821      * if mdrun is compiled without GPU acceleration support.
1822      * Note that you should freezing the system as otherwise it will explode.
1823      */
1824     *bEmulateGPU = (bEmulateGPUEnvVarSet ||
1825                     (!bDoNonbonded && gpu_opt->n_dev_use > 0));
1826
1827     /* Enable GPU mode when GPUs are available or no GPU emulation is requested.
1828      */
1829     if (gpu_opt->n_dev_use > 0 && !(*bEmulateGPU))
1830     {
1831         /* Each PP node will use the intra-node id-th device from the
1832          * list of detected/selected GPUs. */
1833         if (!init_gpu(fp, cr->rank_pp_intranode, gpu_err_str,
1834                       &hwinfo->gpu_info, gpu_opt))
1835         {
1836             /* At this point the init should never fail as we made sure that
1837              * we have all the GPUs we need. If it still does, we'll bail. */
1838             /* TODO the decorating of gpu_err_str is nicer if it
1839                happens inside init_gpu. Out here, the decorating with
1840                the MPI rank makes sense. */
1841             gmx_fatal(FARGS, "On rank %d failed to initialize GPU #%d: %s",
1842                       cr->nodeid,
1843                       get_gpu_device_id(&hwinfo->gpu_info, gpu_opt,
1844                                         cr->rank_pp_intranode),
1845                       gpu_err_str);
1846         }
1847
1848         /* Here we actually turn on hardware GPU acceleration */
1849         *bUseGPU = TRUE;
1850     }
1851 }
1852
1853 gmx_bool uses_simple_tables(int                 cutoff_scheme,
1854                             nonbonded_verlet_t *nbv,
1855                             int                 group)
1856 {
1857     gmx_bool bUsesSimpleTables = TRUE;
1858     int      grp_index;
1859
1860     switch (cutoff_scheme)
1861     {
1862         case ecutsGROUP:
1863             bUsesSimpleTables = TRUE;
1864             break;
1865         case ecutsVERLET:
1866             assert(NULL != nbv && NULL != nbv->grp);
1867             grp_index         = (group < 0) ? 0 : (nbv->ngrp - 1);
1868             bUsesSimpleTables = nbnxn_kernel_pairlist_simple(nbv->grp[grp_index].kernel_type);
1869             break;
1870         default:
1871             gmx_incons("unimplemented");
1872     }
1873     return bUsesSimpleTables;
1874 }
1875
1876 static void init_ewald_f_table(interaction_const_t *ic,
1877                                real                 rtab)
1878 {
1879     real maxr;
1880
1881     /* Get the Ewald table spacing based on Coulomb and/or LJ
1882      * Ewald coefficients and rtol.
1883      */
1884     ic->tabq_scale = ewald_spline3_table_scale(ic);
1885
1886     if (ic->cutoff_scheme == ecutsVERLET)
1887     {
1888         maxr = ic->rcoulomb;
1889     }
1890     else
1891     {
1892         maxr = std::max(ic->rcoulomb, rtab);
1893     }
1894     ic->tabq_size  = static_cast<int>(maxr*ic->tabq_scale) + 2;
1895
1896     sfree_aligned(ic->tabq_coul_FDV0);
1897     sfree_aligned(ic->tabq_coul_F);
1898     sfree_aligned(ic->tabq_coul_V);
1899
1900     sfree_aligned(ic->tabq_vdw_FDV0);
1901     sfree_aligned(ic->tabq_vdw_F);
1902     sfree_aligned(ic->tabq_vdw_V);
1903
1904     if (EEL_PME_EWALD(ic->eeltype))
1905     {
1906         /* Create the original table data in FDV0 */
1907         snew_aligned(ic->tabq_coul_FDV0, ic->tabq_size*4, 32);
1908         snew_aligned(ic->tabq_coul_F, ic->tabq_size, 32);
1909         snew_aligned(ic->tabq_coul_V, ic->tabq_size, 32);
1910         table_spline3_fill_ewald_lr(ic->tabq_coul_F, ic->tabq_coul_V, ic->tabq_coul_FDV0,
1911                                     ic->tabq_size, 1/ic->tabq_scale, ic->ewaldcoeff_q, v_q_ewald_lr);
1912     }
1913
1914     if (EVDW_PME(ic->vdwtype))
1915     {
1916         snew_aligned(ic->tabq_vdw_FDV0, ic->tabq_size*4, 32);
1917         snew_aligned(ic->tabq_vdw_F, ic->tabq_size, 32);
1918         snew_aligned(ic->tabq_vdw_V, ic->tabq_size, 32);
1919         table_spline3_fill_ewald_lr(ic->tabq_vdw_F, ic->tabq_vdw_V, ic->tabq_vdw_FDV0,
1920                                     ic->tabq_size, 1/ic->tabq_scale, ic->ewaldcoeff_lj, v_lj_ewald_lr);
1921     }
1922 }
1923
1924 void init_interaction_const_tables(FILE                *fp,
1925                                    interaction_const_t *ic,
1926                                    real                 rtab)
1927 {
1928     if (EEL_PME_EWALD(ic->eeltype) || EVDW_PME(ic->vdwtype))
1929     {
1930         init_ewald_f_table(ic, rtab);
1931
1932         if (fp != NULL)
1933         {
1934             fprintf(fp, "Initialized non-bonded Ewald correction tables, spacing: %.2e size: %d\n\n",
1935                     1/ic->tabq_scale, ic->tabq_size);
1936         }
1937     }
1938 }
1939
1940 static void clear_force_switch_constants(shift_consts_t *sc)
1941 {
1942     sc->c2   = 0;
1943     sc->c3   = 0;
1944     sc->cpot = 0;
1945 }
1946
1947 static void force_switch_constants(real p,
1948                                    real rsw, real rc,
1949                                    shift_consts_t *sc)
1950 {
1951     /* Here we determine the coefficient for shifting the force to zero
1952      * between distance rsw and the cut-off rc.
1953      * For a potential of r^-p, we have force p*r^-(p+1).
1954      * But to save flops we absorb p in the coefficient.
1955      * Thus we get:
1956      * force/p   = r^-(p+1) + c2*r^2 + c3*r^3
1957      * potential = r^-p + c2/3*r^3 + c3/4*r^4 + cpot
1958      */
1959     sc->c2   =  ((p + 1)*rsw - (p + 4)*rc)/(pow(rc, p + 2)*gmx::square(rc - rsw));
1960     sc->c3   = -((p + 1)*rsw - (p + 3)*rc)/(pow(rc, p + 2)*gmx::power3(rc - rsw));
1961     sc->cpot = -pow(rc, -p) + p*sc->c2/3*gmx::power3(rc - rsw) + p*sc->c3/4*gmx::power4(rc - rsw);
1962 }
1963
1964 static void potential_switch_constants(real rsw, real rc,
1965                                        switch_consts_t *sc)
1966 {
1967     /* The switch function is 1 at rsw and 0 at rc.
1968      * The derivative and second derivate are zero at both ends.
1969      * rsw        = max(r - r_switch, 0)
1970      * sw         = 1 + c3*rsw^3 + c4*rsw^4 + c5*rsw^5
1971      * dsw        = 3*c3*rsw^2 + 4*c4*rsw^3 + 5*c5*rsw^4
1972      * force      = force*dsw - potential*sw
1973      * potential *= sw
1974      */
1975     sc->c3 = -10/gmx::power3(rc - rsw);
1976     sc->c4 =  15/gmx::power4(rc - rsw);
1977     sc->c5 =  -6/gmx::power5(rc - rsw);
1978 }
1979
1980 /*! \brief Construct interaction constants
1981  *
1982  * This data is used (particularly) by search and force code for
1983  * short-range interactions. Many of these are constant for the whole
1984  * simulation; some are constant only after PME tuning completes.
1985  */
1986 static void
1987 init_interaction_const(FILE                       *fp,
1988                        interaction_const_t       **interaction_const,
1989                        const t_forcerec           *fr)
1990 {
1991     interaction_const_t *ic;
1992
1993     snew(ic, 1);
1994
1995     ic->cutoff_scheme   = fr->cutoff_scheme;
1996
1997     /* Just allocate something so we can free it */
1998     snew_aligned(ic->tabq_coul_FDV0, 16, 32);
1999     snew_aligned(ic->tabq_coul_F, 16, 32);
2000     snew_aligned(ic->tabq_coul_V, 16, 32);
2001
2002     ic->rlist           = fr->rlist;
2003
2004     /* Lennard-Jones */
2005     ic->vdwtype         = fr->vdwtype;
2006     ic->vdw_modifier    = fr->vdw_modifier;
2007     ic->rvdw            = fr->rvdw;
2008     ic->rvdw_switch     = fr->rvdw_switch;
2009     ic->ewaldcoeff_lj   = fr->ewaldcoeff_lj;
2010     ic->ljpme_comb_rule = fr->ljpme_combination_rule;
2011     ic->sh_lj_ewald     = 0;
2012     clear_force_switch_constants(&ic->dispersion_shift);
2013     clear_force_switch_constants(&ic->repulsion_shift);
2014
2015     switch (ic->vdw_modifier)
2016     {
2017         case eintmodPOTSHIFT:
2018             /* Only shift the potential, don't touch the force */
2019             ic->dispersion_shift.cpot = -1.0/gmx::power6(ic->rvdw);
2020             ic->repulsion_shift.cpot  = -1.0/gmx::power12(ic->rvdw);
2021             if (EVDW_PME(ic->vdwtype))
2022             {
2023                 real crc2;
2024
2025                 crc2            = gmx::square(ic->ewaldcoeff_lj*ic->rvdw);
2026                 ic->sh_lj_ewald = (std::exp(-crc2)*(1 + crc2 + 0.5*crc2*crc2) - 1)/gmx::power6(ic->rvdw);
2027             }
2028             break;
2029         case eintmodFORCESWITCH:
2030             /* Switch the force, switch and shift the potential */
2031             force_switch_constants(6.0, ic->rvdw_switch, ic->rvdw,
2032                                    &ic->dispersion_shift);
2033             force_switch_constants(12.0, ic->rvdw_switch, ic->rvdw,
2034                                    &ic->repulsion_shift);
2035             break;
2036         case eintmodPOTSWITCH:
2037             /* Switch the potential and force */
2038             potential_switch_constants(ic->rvdw_switch, ic->rvdw,
2039                                        &ic->vdw_switch);
2040             break;
2041         case eintmodNONE:
2042         case eintmodEXACTCUTOFF:
2043             /* Nothing to do here */
2044             break;
2045         default:
2046             gmx_incons("unimplemented potential modifier");
2047     }
2048
2049     ic->sh_invrc6 = -ic->dispersion_shift.cpot;
2050
2051     /* Electrostatics */
2052     ic->eeltype          = fr->eeltype;
2053     ic->coulomb_modifier = fr->coulomb_modifier;
2054     ic->rcoulomb         = fr->rcoulomb;
2055     ic->epsilon_r        = fr->epsilon_r;
2056     ic->epsfac           = fr->epsfac;
2057     ic->ewaldcoeff_q     = fr->ewaldcoeff_q;
2058
2059     if (EEL_PME_EWALD(ic->eeltype) && ic->coulomb_modifier == eintmodPOTSHIFT)
2060     {
2061         GMX_RELEASE_ASSERT(ic->rcoulomb != 0, "Cutoff radius cannot be zero");
2062         ic->sh_ewald = std::erfc(ic->ewaldcoeff_q*ic->rcoulomb) / ic->rcoulomb;
2063     }
2064     else
2065     {
2066         ic->sh_ewald = 0;
2067     }
2068
2069     /* Reaction-field */
2070     if (EEL_RF(ic->eeltype))
2071     {
2072         ic->epsilon_rf = fr->epsilon_rf;
2073         ic->k_rf       = fr->k_rf;
2074         ic->c_rf       = fr->c_rf;
2075     }
2076     else
2077     {
2078         /* For plain cut-off we might use the reaction-field kernels */
2079         ic->epsilon_rf = ic->epsilon_r;
2080         ic->k_rf       = 0;
2081         if (fr->coulomb_modifier == eintmodPOTSHIFT)
2082         {
2083             ic->c_rf   = 1/ic->rcoulomb;
2084         }
2085         else
2086         {
2087             ic->c_rf   = 0;
2088         }
2089     }
2090
2091     if (fp != NULL)
2092     {
2093         real dispersion_shift;
2094
2095         dispersion_shift = ic->dispersion_shift.cpot;
2096         if (EVDW_PME(ic->vdwtype))
2097         {
2098             dispersion_shift -= ic->sh_lj_ewald;
2099         }
2100         fprintf(fp, "Potential shift: LJ r^-12: %.3e r^-6: %.3e",
2101                 ic->repulsion_shift.cpot, dispersion_shift);
2102
2103         if (ic->eeltype == eelCUT)
2104         {
2105             fprintf(fp, ", Coulomb %.e", -ic->c_rf);
2106         }
2107         else if (EEL_PME(ic->eeltype))
2108         {
2109             fprintf(fp, ", Ewald %.3e", -ic->sh_ewald);
2110         }
2111         fprintf(fp, "\n");
2112     }
2113
2114     *interaction_const = ic;
2115 }
2116
2117 static void init_nb_verlet(FILE                *fp,
2118                            nonbonded_verlet_t **nb_verlet,
2119                            gmx_bool             bFEP_NonBonded,
2120                            const t_inputrec    *ir,
2121                            const t_forcerec    *fr,
2122                            const t_commrec     *cr,
2123                            const char          *nbpu_opt)
2124 {
2125     nonbonded_verlet_t *nbv;
2126     int                 i;
2127     char               *env;
2128     gmx_bool            bEmulateGPU, bHybridGPURun = FALSE;
2129
2130     nbnxn_alloc_t      *nb_alloc;
2131     nbnxn_free_t       *nb_free;
2132
2133     snew(nbv, 1);
2134
2135     pick_nbnxn_resources(fp, cr, fr->hwinfo,
2136                          fr->bNonbonded,
2137                          &nbv->bUseGPU,
2138                          &bEmulateGPU,
2139                          fr->gpu_opt);
2140
2141     nbv->nbs             = NULL;
2142     nbv->min_ci_balanced = 0;
2143
2144     nbv->ngrp = (DOMAINDECOMP(cr) ? 2 : 1);
2145     for (i = 0; i < nbv->ngrp; i++)
2146     {
2147         nbv->grp[i].nbl_lists.nnbl = 0;
2148         nbv->grp[i].nbat           = NULL;
2149         nbv->grp[i].kernel_type    = nbnxnkNotSet;
2150
2151         if (i == 0) /* local */
2152         {
2153             pick_nbnxn_kernel(fp, cr, fr->use_simd_kernels,
2154                               nbv->bUseGPU, bEmulateGPU, ir,
2155                               &nbv->grp[i].kernel_type,
2156                               &nbv->grp[i].ewald_excl,
2157                               fr->bNonbonded);
2158         }
2159         else /* non-local */
2160         {
2161             if (nbpu_opt != NULL && strcmp(nbpu_opt, "gpu_cpu") == 0)
2162             {
2163                 /* Use GPU for local, select a CPU kernel for non-local */
2164                 pick_nbnxn_kernel(fp, cr, fr->use_simd_kernels,
2165                                   FALSE, FALSE, ir,
2166                                   &nbv->grp[i].kernel_type,
2167                                   &nbv->grp[i].ewald_excl,
2168                                   fr->bNonbonded);
2169
2170                 bHybridGPURun = TRUE;
2171             }
2172             else
2173             {
2174                 /* Use the same kernel for local and non-local interactions */
2175                 nbv->grp[i].kernel_type = nbv->grp[0].kernel_type;
2176                 nbv->grp[i].ewald_excl  = nbv->grp[0].ewald_excl;
2177             }
2178         }
2179     }
2180
2181     nbnxn_init_search(&nbv->nbs,
2182                       DOMAINDECOMP(cr) ? &cr->dd->nc : NULL,
2183                       DOMAINDECOMP(cr) ? domdec_zones(cr->dd) : NULL,
2184                       bFEP_NonBonded,
2185                       gmx_omp_nthreads_get(emntPairsearch));
2186
2187     for (i = 0; i < nbv->ngrp; i++)
2188     {
2189         gpu_set_host_malloc_and_free(nbv->grp[0].kernel_type == nbnxnk8x8x8_GPU,
2190                                      &nb_alloc, &nb_free);
2191
2192         nbnxn_init_pairlist_set(&nbv->grp[i].nbl_lists,
2193                                 nbnxn_kernel_pairlist_simple(nbv->grp[i].kernel_type),
2194                                 /* 8x8x8 "non-simple" lists are ATM always combined */
2195                                 !nbnxn_kernel_pairlist_simple(nbv->grp[i].kernel_type),
2196                                 nb_alloc, nb_free);
2197
2198         if (i == 0 ||
2199             nbv->grp[0].kernel_type != nbv->grp[i].kernel_type)
2200         {
2201             gmx_bool bSimpleList;
2202             int      enbnxninitcombrule;
2203
2204             bSimpleList = nbnxn_kernel_pairlist_simple(nbv->grp[i].kernel_type);
2205
2206             if (fr->vdwtype == evdwCUT &&
2207                 (fr->vdw_modifier == eintmodNONE ||
2208                  fr->vdw_modifier == eintmodPOTSHIFT) &&
2209                 getenv("GMX_NO_LJ_COMB_RULE") == NULL)
2210             {
2211                 /* Plain LJ cut-off: we can optimize with combination rules */
2212                 enbnxninitcombrule = enbnxninitcombruleDETECT;
2213             }
2214             else if (fr->vdwtype == evdwPME)
2215             {
2216                 /* LJ-PME: we need to use a combination rule for the grid */
2217                 if (fr->ljpme_combination_rule == eljpmeGEOM)
2218                 {
2219                     enbnxninitcombrule = enbnxninitcombruleGEOM;
2220                 }
2221                 else
2222                 {
2223                     enbnxninitcombrule = enbnxninitcombruleLB;
2224                 }
2225             }
2226             else
2227             {
2228                 /* We use a full combination matrix: no rule required */
2229                 enbnxninitcombrule = enbnxninitcombruleNONE;
2230             }
2231
2232
2233             snew(nbv->grp[i].nbat, 1);
2234             nbnxn_atomdata_init(fp,
2235                                 nbv->grp[i].nbat,
2236                                 nbv->grp[i].kernel_type,
2237                                 enbnxninitcombrule,
2238                                 fr->ntype, fr->nbfp,
2239                                 ir->opts.ngener,
2240                                 bSimpleList ? gmx_omp_nthreads_get(emntNonbonded) : 1,
2241                                 nb_alloc, nb_free);
2242         }
2243         else
2244         {
2245             nbv->grp[i].nbat = nbv->grp[0].nbat;
2246         }
2247     }
2248
2249     if (nbv->bUseGPU)
2250     {
2251         /* init the NxN GPU data; the last argument tells whether we'll have
2252          * both local and non-local NB calculation on GPU */
2253         nbnxn_gpu_init(&nbv->gpu_nbv,
2254                        &fr->hwinfo->gpu_info,
2255                        fr->gpu_opt,
2256                        fr->ic,
2257                        nbv->grp,
2258                        cr->rank_pp_intranode,
2259                        cr->nodeid,
2260                        (nbv->ngrp > 1) && !bHybridGPURun);
2261
2262         /* With tMPI + GPUs some ranks may be sharing GPU(s) and therefore
2263          * also sharing texture references. To keep the code simple, we don't
2264          * treat texture references as shared resources, but this means that
2265          * the coulomb_tab and nbfp texture refs will get updated by multiple threads.
2266          * Hence, to ensure that the non-bonded kernels don't start before all
2267          * texture binding operations are finished, we need to wait for all ranks
2268          * to arrive here before continuing.
2269          *
2270          * Note that we could omit this barrier if GPUs are not shared (or
2271          * texture objects are used), but as this is initialization code, there
2272          * is no point in complicating things.
2273          */
2274 #if GMX_THREAD_MPI
2275         if (PAR(cr))
2276         {
2277             gmx_barrier(cr);
2278         }
2279 #endif  /* GMX_THREAD_MPI */
2280
2281         if ((env = getenv("GMX_NB_MIN_CI")) != NULL)
2282         {
2283             char *end;
2284
2285             nbv->min_ci_balanced = strtol(env, &end, 10);
2286             if (!end || (*end != 0) || nbv->min_ci_balanced < 0)
2287             {
2288                 gmx_fatal(FARGS, "Invalid value passed in GMX_NB_MIN_CI=%s, non-negative integer required", env);
2289             }
2290
2291             if (debug)
2292             {
2293                 fprintf(debug, "Neighbor-list balancing parameter: %d (passed as env. var.)\n",
2294                         nbv->min_ci_balanced);
2295             }
2296         }
2297         else
2298         {
2299             nbv->min_ci_balanced = nbnxn_gpu_min_ci_balanced(nbv->gpu_nbv);
2300             if (debug)
2301             {
2302                 fprintf(debug, "Neighbor-list balancing parameter: %d (auto-adjusted to the number of GPU multi-processors)\n",
2303                         nbv->min_ci_balanced);
2304             }
2305         }
2306
2307     }
2308
2309     *nb_verlet = nbv;
2310 }
2311
2312 gmx_bool usingGpu(nonbonded_verlet_t *nbv)
2313 {
2314     return nbv != NULL && nbv->bUseGPU;
2315 }
2316
2317 void init_forcerec(FILE              *fp,
2318                    t_forcerec        *fr,
2319                    t_fcdata          *fcd,
2320                    const t_inputrec  *ir,
2321                    const gmx_mtop_t  *mtop,
2322                    const t_commrec   *cr,
2323                    matrix             box,
2324                    const char        *tabfn,
2325                    const char        *tabpfn,
2326                    const t_filenm    *tabbfnm,
2327                    const char        *nbpu_opt,
2328                    gmx_bool           bNoSolvOpt,
2329                    real               print_force)
2330 {
2331     int            i, m, negp_pp, negptable, egi, egj;
2332     real           rtab;
2333     char          *env;
2334     double         dbl;
2335     const t_block *cgs;
2336     gmx_bool       bGenericKernelOnly;
2337     gmx_bool       needGroupSchemeTables, bSomeNormalNbListsAreInUse;
2338     gmx_bool       bFEP_NonBonded;
2339     int           *nm_ind, egp_flags;
2340
2341     if (fr->hwinfo == NULL)
2342     {
2343         /* Detect hardware, gather information.
2344          * In mdrun, hwinfo has already been set before calling init_forcerec.
2345          * Here we ignore GPUs, as tools will not use them anyhow.
2346          */
2347         fr->hwinfo = gmx_detect_hardware(fp, cr, FALSE);
2348     }
2349
2350     /* By default we turn SIMD kernels on, but it might be turned off further down... */
2351     fr->use_simd_kernels = TRUE;
2352
2353     fr->bDomDec = DOMAINDECOMP(cr);
2354
2355     if (check_box(ir->ePBC, box))
2356     {
2357         gmx_fatal(FARGS, check_box(ir->ePBC, box));
2358     }
2359
2360     /* Test particle insertion ? */
2361     if (EI_TPI(ir->eI))
2362     {
2363         /* Set to the size of the molecule to be inserted (the last one) */
2364         /* Because of old style topologies, we have to use the last cg
2365          * instead of the last molecule type.
2366          */
2367         cgs       = &mtop->moltype[mtop->molblock[mtop->nmolblock-1].type].cgs;
2368         fr->n_tpi = cgs->index[cgs->nr] - cgs->index[cgs->nr-1];
2369         if (fr->n_tpi != mtop->mols.index[mtop->mols.nr] - mtop->mols.index[mtop->mols.nr-1])
2370         {
2371             gmx_fatal(FARGS, "The molecule to insert can not consist of multiple charge groups.\nMake it a single charge group.");
2372         }
2373     }
2374     else
2375     {
2376         fr->n_tpi = 0;
2377     }
2378
2379     if (ir->coulombtype == eelRF_NEC_UNSUPPORTED)
2380     {
2381         gmx_fatal(FARGS, "%s electrostatics is no longer supported",
2382                   eel_names[ir->coulombtype]);
2383     }
2384
2385     if (ir->bAdress)
2386     {
2387         gmx_fatal(FARGS, "AdResS simulations are no longer supported");
2388     }
2389     if (ir->useTwinRange)
2390     {
2391         gmx_fatal(FARGS, "Twin-range simulations are no longer supported");
2392     }
2393     /* Copy the user determined parameters */
2394     fr->userint1  = ir->userint1;
2395     fr->userint2  = ir->userint2;
2396     fr->userint3  = ir->userint3;
2397     fr->userint4  = ir->userint4;
2398     fr->userreal1 = ir->userreal1;
2399     fr->userreal2 = ir->userreal2;
2400     fr->userreal3 = ir->userreal3;
2401     fr->userreal4 = ir->userreal4;
2402
2403     /* Shell stuff */
2404     fr->fc_stepsize = ir->fc_stepsize;
2405
2406     /* Free energy */
2407     fr->efep        = ir->efep;
2408     fr->sc_alphavdw = ir->fepvals->sc_alpha;
2409     if (ir->fepvals->bScCoul)
2410     {
2411         fr->sc_alphacoul  = ir->fepvals->sc_alpha;
2412         fr->sc_sigma6_min = gmx::power6(ir->fepvals->sc_sigma_min);
2413     }
2414     else
2415     {
2416         fr->sc_alphacoul  = 0;
2417         fr->sc_sigma6_min = 0; /* only needed when bScCoul is on */
2418     }
2419     fr->sc_power      = ir->fepvals->sc_power;
2420     fr->sc_r_power    = ir->fepvals->sc_r_power;
2421     fr->sc_sigma6_def = gmx::power6(ir->fepvals->sc_sigma);
2422
2423     env = getenv("GMX_SCSIGMA_MIN");
2424     if (env != NULL)
2425     {
2426         dbl = 0;
2427         sscanf(env, "%20lf", &dbl);
2428         fr->sc_sigma6_min = gmx::power6(dbl);
2429         if (fp)
2430         {
2431             fprintf(fp, "Setting the minimum soft core sigma to %g nm\n", dbl);
2432         }
2433     }
2434
2435     fr->bNonbonded = TRUE;
2436     if (getenv("GMX_NO_NONBONDED") != NULL)
2437     {
2438         /* turn off non-bonded calculations */
2439         fr->bNonbonded = FALSE;
2440         md_print_warn(cr, fp,
2441                       "Found environment variable GMX_NO_NONBONDED.\n"
2442                       "Disabling nonbonded calculations.\n");
2443     }
2444
2445     bGenericKernelOnly = FALSE;
2446
2447     /* We now check in the NS code whether a particular combination of interactions
2448      * can be used with water optimization, and disable it if that is not the case.
2449      */
2450
2451     if (getenv("GMX_NB_GENERIC") != NULL)
2452     {
2453         if (fp != NULL)
2454         {
2455             fprintf(fp,
2456                     "Found environment variable GMX_NB_GENERIC.\n"
2457                     "Disabling all interaction-specific nonbonded kernels, will only\n"
2458                     "use the slow generic ones in src/gmxlib/nonbonded/nb_generic.c\n\n");
2459         }
2460         bGenericKernelOnly = TRUE;
2461     }
2462
2463     if (bGenericKernelOnly == TRUE)
2464     {
2465         bNoSolvOpt         = TRUE;
2466     }
2467
2468     if ( (getenv("GMX_DISABLE_SIMD_KERNELS") != NULL) || (getenv("GMX_NOOPTIMIZEDKERNELS") != NULL) )
2469     {
2470         fr->use_simd_kernels = FALSE;
2471         if (fp != NULL)
2472         {
2473             fprintf(fp,
2474                     "\nFound environment variable GMX_DISABLE_SIMD_KERNELS.\n"
2475                     "Disabling the usage of any SIMD-specific non-bonded & bonded kernel routines\n"
2476                     "(e.g. SSE2/SSE4.1/AVX).\n\n");
2477         }
2478     }
2479
2480     fr->bBHAM = (mtop->ffparams.functype[0] == F_BHAM);
2481
2482     /* Check if we can/should do all-vs-all kernels */
2483     fr->bAllvsAll       = can_use_allvsall(ir, FALSE, NULL, NULL);
2484     fr->AllvsAll_work   = NULL;
2485     fr->AllvsAll_workgb = NULL;
2486
2487     /* All-vs-all kernels have not been implemented in 4.6 and later.
2488      * See Redmine #1249. */
2489     if (fr->bAllvsAll)
2490     {
2491         fr->bAllvsAll            = FALSE;
2492         if (fp != NULL)
2493         {
2494             fprintf(fp,
2495                     "\nYour simulation settings would have triggered the efficient all-vs-all\n"
2496                     "kernels in GROMACS 4.5, but these have not been implemented in GROMACS\n"
2497                     "4.6 and 5.x. If performance is important, please use GROMACS 4.5.7\n"
2498                     "or try cutoff-scheme = Verlet.\n\n");
2499         }
2500     }
2501
2502     /* Neighbour searching stuff */
2503     fr->cutoff_scheme = ir->cutoff_scheme;
2504     fr->bGrid         = (ir->ns_type == ensGRID);
2505     fr->ePBC          = ir->ePBC;
2506
2507     if (fr->cutoff_scheme == ecutsGROUP)
2508     {
2509         const char *note = "NOTE: This file uses the deprecated 'group' cutoff_scheme. This will be\n"
2510             "removed in a future release when 'verlet' supports all interaction forms.\n";
2511
2512         if (MASTER(cr))
2513         {
2514             fprintf(stderr, "\n%s\n", note);
2515         }
2516         if (fp != NULL)
2517         {
2518             fprintf(fp, "\n%s\n", note);
2519         }
2520     }
2521
2522     /* Determine if we will do PBC for distances in bonded interactions */
2523     if (fr->ePBC == epbcNONE)
2524     {
2525         fr->bMolPBC = FALSE;
2526     }
2527     else
2528     {
2529         if (!DOMAINDECOMP(cr))
2530         {
2531             gmx_bool bSHAKE;
2532
2533             bSHAKE = (ir->eConstrAlg == econtSHAKE &&
2534                       (gmx_mtop_ftype_count(mtop, F_CONSTR) > 0 ||
2535                        gmx_mtop_ftype_count(mtop, F_CONSTRNC) > 0));
2536
2537             /* The group cut-off scheme and SHAKE assume charge groups
2538              * are whole, but not using molpbc is faster in most cases.
2539              * With intermolecular interactions we need PBC for calculating
2540              * distances between atoms in different molecules.
2541              */
2542             if ((fr->cutoff_scheme == ecutsGROUP || bSHAKE) &&
2543                 !mtop->bIntermolecularInteractions)
2544             {
2545                 fr->bMolPBC = ir->bPeriodicMols;
2546
2547                 if (bSHAKE && fr->bMolPBC)
2548                 {
2549                     gmx_fatal(FARGS, "SHAKE is not supported with periodic molecules");
2550                 }
2551             }
2552             else
2553             {
2554                 fr->bMolPBC = TRUE;
2555
2556                 if (getenv("GMX_USE_GRAPH") != NULL)
2557                 {
2558                     fr->bMolPBC = FALSE;
2559                     if (fp)
2560                     {
2561                         md_print_warn(cr, fp, "GMX_USE_GRAPH is set, using the graph for bonded interactions\n");
2562                     }
2563
2564                     if (mtop->bIntermolecularInteractions)
2565                     {
2566                         md_print_warn(cr, fp, "WARNING: Molecules linked by intermolecular interactions have to reside in the same periodic image, otherwise artifacts will occur!\n");
2567                     }
2568                 }
2569
2570                 if (bSHAKE && fr->bMolPBC)
2571                 {
2572                     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");
2573                 }
2574             }
2575         }
2576         else
2577         {
2578             fr->bMolPBC = dd_bonded_molpbc(cr->dd, fr->ePBC);
2579         }
2580     }
2581     fr->bGB = (ir->implicit_solvent == eisGBSA);
2582
2583     fr->rc_scaling = ir->refcoord_scaling;
2584     copy_rvec(ir->posres_com, fr->posres_com);
2585     copy_rvec(ir->posres_comB, fr->posres_comB);
2586     fr->rlist                    = cutoff_inf(ir->rlist);
2587     fr->eeltype                  = ir->coulombtype;
2588     fr->vdwtype                  = ir->vdwtype;
2589     fr->ljpme_combination_rule   = ir->ljpme_combination_rule;
2590
2591     fr->coulomb_modifier = ir->coulomb_modifier;
2592     fr->vdw_modifier     = ir->vdw_modifier;
2593
2594     /* Electrostatics: Translate from interaction-setting-in-mdp-file to kernel interaction format */
2595     switch (fr->eeltype)
2596     {
2597         case eelCUT:
2598             fr->nbkernel_elec_interaction = (fr->bGB) ? GMX_NBKERNEL_ELEC_GENERALIZEDBORN : GMX_NBKERNEL_ELEC_COULOMB;
2599             break;
2600
2601         case eelRF:
2602         case eelGRF:
2603             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_REACTIONFIELD;
2604             break;
2605
2606         case eelRF_ZERO:
2607             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_REACTIONFIELD;
2608             fr->coulomb_modifier          = eintmodEXACTCUTOFF;
2609             break;
2610
2611         case eelSWITCH:
2612         case eelSHIFT:
2613         case eelUSER:
2614         case eelENCADSHIFT:
2615         case eelPMESWITCH:
2616         case eelPMEUSER:
2617         case eelPMEUSERSWITCH:
2618             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_CUBICSPLINETABLE;
2619             break;
2620
2621         case eelPME:
2622         case eelP3M_AD:
2623         case eelEWALD:
2624             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_EWALD;
2625             break;
2626
2627         default:
2628             gmx_fatal(FARGS, "Unsupported electrostatic interaction: %s", eel_names[fr->eeltype]);
2629             break;
2630     }
2631
2632     /* Vdw: Translate from mdp settings to kernel format */
2633     switch (fr->vdwtype)
2634     {
2635         case evdwCUT:
2636             if (fr->bBHAM)
2637             {
2638                 fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_BUCKINGHAM;
2639             }
2640             else
2641             {
2642                 fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_LENNARDJONES;
2643             }
2644             break;
2645         case evdwPME:
2646             fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_LJEWALD;
2647             break;
2648
2649         case evdwSWITCH:
2650         case evdwSHIFT:
2651         case evdwUSER:
2652         case evdwENCADSHIFT:
2653             fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_CUBICSPLINETABLE;
2654             break;
2655
2656         default:
2657             gmx_fatal(FARGS, "Unsupported vdw interaction: %s", evdw_names[fr->vdwtype]);
2658             break;
2659     }
2660
2661     /* These start out identical to ir, but might be altered if we e.g. tabulate the interaction in the kernel */
2662     fr->nbkernel_elec_modifier    = fr->coulomb_modifier;
2663     fr->nbkernel_vdw_modifier     = fr->vdw_modifier;
2664
2665     fr->rvdw             = cutoff_inf(ir->rvdw);
2666     fr->rvdw_switch      = ir->rvdw_switch;
2667     fr->rcoulomb         = cutoff_inf(ir->rcoulomb);
2668     fr->rcoulomb_switch  = ir->rcoulomb_switch;
2669
2670     fr->bEwald     = EEL_PME_EWALD(fr->eeltype);
2671
2672     fr->reppow     = mtop->ffparams.reppow;
2673
2674     if (ir->cutoff_scheme == ecutsGROUP)
2675     {
2676         fr->bvdwtab    = ((fr->vdwtype != evdwCUT || !gmx_within_tol(fr->reppow, 12.0, 10*GMX_DOUBLE_EPS))
2677                           && !EVDW_PME(fr->vdwtype));
2678         /* We have special kernels for standard Ewald and PME, but the pme-switch ones are tabulated above */
2679         fr->bcoultab   = !(fr->eeltype == eelCUT ||
2680                            fr->eeltype == eelEWALD ||
2681                            fr->eeltype == eelPME ||
2682                            fr->eeltype == eelRF ||
2683                            fr->eeltype == eelRF_ZERO);
2684
2685         /* If the user absolutely wants different switch/shift settings for coul/vdw, it is likely
2686          * going to be faster to tabulate the interaction than calling the generic kernel.
2687          * However, if generic kernels have been requested we keep things analytically.
2688          */
2689         if (fr->nbkernel_elec_modifier == eintmodPOTSWITCH &&
2690             fr->nbkernel_vdw_modifier == eintmodPOTSWITCH &&
2691             bGenericKernelOnly == FALSE)
2692         {
2693             if ((fr->rcoulomb_switch != fr->rvdw_switch) || (fr->rcoulomb != fr->rvdw))
2694             {
2695                 fr->bcoultab = TRUE;
2696                 /* Once we tabulate electrostatics, we can use the switch function for LJ,
2697                  * which would otherwise need two tables.
2698                  */
2699             }
2700         }
2701         else if ((fr->nbkernel_elec_modifier == eintmodPOTSHIFT && fr->nbkernel_vdw_modifier == eintmodPOTSHIFT) ||
2702                  ((fr->nbkernel_elec_interaction == GMX_NBKERNEL_ELEC_REACTIONFIELD &&
2703                    fr->nbkernel_elec_modifier == eintmodEXACTCUTOFF &&
2704                    (fr->nbkernel_vdw_modifier == eintmodPOTSWITCH || fr->nbkernel_vdw_modifier == eintmodPOTSHIFT))))
2705         {
2706             if ((fr->rcoulomb != fr->rvdw) && (bGenericKernelOnly == FALSE))
2707             {
2708                 fr->bcoultab = TRUE;
2709             }
2710         }
2711
2712         if (fr->nbkernel_elec_modifier == eintmodFORCESWITCH)
2713         {
2714             fr->bcoultab = TRUE;
2715         }
2716         if (fr->nbkernel_vdw_modifier == eintmodFORCESWITCH)
2717         {
2718             fr->bvdwtab = TRUE;
2719         }
2720
2721         if (getenv("GMX_REQUIRE_TABLES"))
2722         {
2723             fr->bvdwtab  = TRUE;
2724             fr->bcoultab = TRUE;
2725         }
2726
2727         if (fp)
2728         {
2729             fprintf(fp, "Table routines are used for coulomb: %s\n",
2730                     gmx::boolToString(fr->bcoultab));
2731             fprintf(fp, "Table routines are used for vdw:     %s\n",
2732                     gmx::boolToString(fr->bvdwtab));
2733         }
2734
2735         if (fr->bvdwtab == TRUE)
2736         {
2737             fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_CUBICSPLINETABLE;
2738             fr->nbkernel_vdw_modifier    = eintmodNONE;
2739         }
2740         if (fr->bcoultab == TRUE)
2741         {
2742             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_CUBICSPLINETABLE;
2743             fr->nbkernel_elec_modifier    = eintmodNONE;
2744         }
2745     }
2746
2747     if (ir->cutoff_scheme == ecutsVERLET)
2748     {
2749         if (!gmx_within_tol(fr->reppow, 12.0, 10*GMX_DOUBLE_EPS))
2750         {
2751             gmx_fatal(FARGS, "Cut-off scheme %S only supports LJ repulsion power 12", ecutscheme_names[ir->cutoff_scheme]);
2752         }
2753         fr->bvdwtab  = FALSE;
2754         fr->bcoultab = FALSE;
2755     }
2756
2757     /* Tables are used for direct ewald sum */
2758     if (fr->bEwald)
2759     {
2760         if (EEL_PME(ir->coulombtype))
2761         {
2762             if (fp)
2763             {
2764                 fprintf(fp, "Will do PME sum in reciprocal space for electrostatic interactions.\n");
2765             }
2766             if (ir->coulombtype == eelP3M_AD)
2767             {
2768                 please_cite(fp, "Hockney1988");
2769                 please_cite(fp, "Ballenegger2012");
2770             }
2771             else
2772             {
2773                 please_cite(fp, "Essmann95a");
2774             }
2775
2776             if (ir->ewald_geometry == eewg3DC)
2777             {
2778                 if (fp)
2779                 {
2780                     fprintf(fp, "Using the Ewald3DC correction for systems with a slab geometry.\n");
2781                 }
2782                 please_cite(fp, "In-Chul99a");
2783             }
2784         }
2785         fr->ewaldcoeff_q = calc_ewaldcoeff_q(ir->rcoulomb, ir->ewald_rtol);
2786         init_ewald_tab(&(fr->ewald_table), ir, fp);
2787         if (fp)
2788         {
2789             fprintf(fp, "Using a Gaussian width (1/beta) of %g nm for Ewald\n",
2790                     1/fr->ewaldcoeff_q);
2791         }
2792     }
2793
2794     if (EVDW_PME(ir->vdwtype))
2795     {
2796         if (fp)
2797         {
2798             fprintf(fp, "Will do PME sum in reciprocal space for LJ dispersion interactions.\n");
2799         }
2800         please_cite(fp, "Essmann95a");
2801         fr->ewaldcoeff_lj = calc_ewaldcoeff_lj(ir->rvdw, ir->ewald_rtol_lj);
2802         if (fp)
2803         {
2804             fprintf(fp, "Using a Gaussian width (1/beta) of %g nm for LJ Ewald\n",
2805                     1/fr->ewaldcoeff_lj);
2806         }
2807     }
2808
2809     /* Electrostatics */
2810     fr->epsilon_r       = ir->epsilon_r;
2811     fr->epsilon_rf      = ir->epsilon_rf;
2812     fr->fudgeQQ         = mtop->ffparams.fudgeQQ;
2813
2814     /* Parameters for generalized RF */
2815     fr->zsquare = 0.0;
2816     fr->temp    = 0.0;
2817
2818     if (fr->eeltype == eelGRF)
2819     {
2820         init_generalized_rf(fp, mtop, ir, fr);
2821     }
2822
2823     fr->bF_NoVirSum = (EEL_FULL(fr->eeltype) || EVDW_PME(fr->vdwtype) ||
2824                        gmx_mtop_ftype_count(mtop, F_POSRES) > 0 ||
2825                        gmx_mtop_ftype_count(mtop, F_FBPOSRES) > 0 ||
2826                        inputrecElecField(ir)
2827                        );
2828
2829     if (fr->cutoff_scheme == ecutsGROUP &&
2830         ncg_mtop(mtop) > fr->cg_nalloc && !DOMAINDECOMP(cr))
2831     {
2832         /* Count the total number of charge groups */
2833         fr->cg_nalloc = ncg_mtop(mtop);
2834         srenew(fr->cg_cm, fr->cg_nalloc);
2835     }
2836     if (fr->shift_vec == NULL)
2837     {
2838         snew(fr->shift_vec, SHIFTS);
2839     }
2840
2841     if (fr->fshift == NULL)
2842     {
2843         snew(fr->fshift, SHIFTS);
2844     }
2845
2846     if (fr->nbfp == NULL)
2847     {
2848         fr->ntype = mtop->ffparams.atnr;
2849         fr->nbfp  = mk_nbfp(&mtop->ffparams, fr->bBHAM);
2850         if (EVDW_PME(fr->vdwtype))
2851         {
2852             fr->ljpme_c6grid  = make_ljpme_c6grid(&mtop->ffparams, fr);
2853         }
2854     }
2855
2856     /* Copy the energy group exclusions */
2857     fr->egp_flags = ir->opts.egp_flags;
2858
2859     /* Van der Waals stuff */
2860     if ((fr->vdwtype != evdwCUT) && (fr->vdwtype != evdwUSER) && !fr->bBHAM)
2861     {
2862         if (fr->rvdw_switch >= fr->rvdw)
2863         {
2864             gmx_fatal(FARGS, "rvdw_switch (%f) must be < rvdw (%f)",
2865                       fr->rvdw_switch, fr->rvdw);
2866         }
2867         if (fp)
2868         {
2869             fprintf(fp, "Using %s Lennard-Jones, switch between %g and %g nm\n",
2870                     (fr->eeltype == eelSWITCH) ? "switched" : "shifted",
2871                     fr->rvdw_switch, fr->rvdw);
2872         }
2873     }
2874
2875     if (fr->bBHAM && EVDW_PME(fr->vdwtype))
2876     {
2877         gmx_fatal(FARGS, "LJ PME not supported with Buckingham");
2878     }
2879
2880     if (fr->bBHAM && (fr->vdwtype == evdwSHIFT || fr->vdwtype == evdwSWITCH))
2881     {
2882         gmx_fatal(FARGS, "Switch/shift interaction not supported with Buckingham");
2883     }
2884
2885     if (fr->bBHAM && fr->cutoff_scheme == ecutsVERLET)
2886     {
2887         gmx_fatal(FARGS, "Verlet cutoff-scheme is not supported with Buckingham");
2888     }
2889
2890     if (fp)
2891     {
2892         fprintf(fp, "Cut-off's:   NS: %g   Coulomb: %g   %s: %g\n",
2893                 fr->rlist, fr->rcoulomb, fr->bBHAM ? "BHAM" : "LJ", fr->rvdw);
2894     }
2895
2896     fr->eDispCorr = ir->eDispCorr;
2897     fr->numAtomsForDispersionCorrection = mtop->natoms;
2898     if (ir->eDispCorr != edispcNO)
2899     {
2900         set_avcsixtwelve(fp, fr, mtop);
2901     }
2902
2903     if (fr->bBHAM)
2904     {
2905         set_bham_b_max(fp, fr, mtop);
2906     }
2907
2908     fr->gb_epsilon_solvent = ir->gb_epsilon_solvent;
2909
2910     /* Copy the GBSA data (radius, volume and surftens for each
2911      * atomtype) from the topology atomtype section to forcerec.
2912      */
2913     snew(fr->atype_radius, fr->ntype);
2914     snew(fr->atype_vol, fr->ntype);
2915     snew(fr->atype_surftens, fr->ntype);
2916     snew(fr->atype_gb_radius, fr->ntype);
2917     snew(fr->atype_S_hct, fr->ntype);
2918
2919     if (mtop->atomtypes.nr > 0)
2920     {
2921         for (i = 0; i < fr->ntype; i++)
2922         {
2923             fr->atype_radius[i] = mtop->atomtypes.radius[i];
2924         }
2925         for (i = 0; i < fr->ntype; i++)
2926         {
2927             fr->atype_vol[i] = mtop->atomtypes.vol[i];
2928         }
2929         for (i = 0; i < fr->ntype; i++)
2930         {
2931             fr->atype_surftens[i] = mtop->atomtypes.surftens[i];
2932         }
2933         for (i = 0; i < fr->ntype; i++)
2934         {
2935             fr->atype_gb_radius[i] = mtop->atomtypes.gb_radius[i];
2936         }
2937         for (i = 0; i < fr->ntype; i++)
2938         {
2939             fr->atype_S_hct[i] = mtop->atomtypes.S_hct[i];
2940         }
2941     }
2942
2943     /* Generate the GB table if needed */
2944     if (fr->bGB)
2945     {
2946 #if GMX_DOUBLE
2947         fr->gbtabscale = 2000;
2948 #else
2949         fr->gbtabscale = 500;
2950 #endif
2951
2952         fr->gbtabr = 100;
2953         fr->gbtab  = make_gb_table(fr);
2954
2955         init_gb(&fr->born, fr, ir, mtop, ir->gb_algorithm);
2956
2957         /* Copy local gb data (for dd, this is done in dd_partition_system) */
2958         if (!DOMAINDECOMP(cr))
2959         {
2960             make_local_gb(cr, fr->born, ir->gb_algorithm);
2961         }
2962     }
2963
2964     /* Set the charge scaling */
2965     if (fr->epsilon_r != 0)
2966     {
2967         fr->epsfac = ONE_4PI_EPS0/fr->epsilon_r;
2968     }
2969     else
2970     {
2971         /* eps = 0 is infinite dieletric: no coulomb interactions */
2972         fr->epsfac = 0;
2973     }
2974
2975     /* Reaction field constants */
2976     if (EEL_RF(fr->eeltype))
2977     {
2978         calc_rffac(fp, fr->eeltype, fr->epsilon_r, fr->epsilon_rf,
2979                    fr->rcoulomb, fr->temp, fr->zsquare, box,
2980                    &fr->kappa, &fr->k_rf, &fr->c_rf);
2981     }
2982
2983     /*This now calculates sum for q and c6*/
2984     set_chargesum(fp, fr, mtop);
2985
2986     /* Construct tables for the group scheme. A little unnecessary to
2987      * make both vdw and coul tables sometimes, but what the
2988      * heck. Note that both cutoff schemes construct Ewald tables in
2989      * init_interaction_const_tables. */
2990     needGroupSchemeTables = (ir->cutoff_scheme == ecutsGROUP &&
2991                              (fr->bcoultab || fr->bvdwtab));
2992
2993     negp_pp   = ir->opts.ngener - ir->nwall;
2994     negptable = 0;
2995     if (!needGroupSchemeTables)
2996     {
2997         bSomeNormalNbListsAreInUse = TRUE;
2998         fr->nnblists               = 1;
2999     }
3000     else
3001     {
3002         bSomeNormalNbListsAreInUse = FALSE;
3003         for (egi = 0; egi < negp_pp; egi++)
3004         {
3005             for (egj = egi; egj < negp_pp; egj++)
3006             {
3007                 egp_flags = ir->opts.egp_flags[GID(egi, egj, ir->opts.ngener)];
3008                 if (!(egp_flags & EGP_EXCL))
3009                 {
3010                     if (egp_flags & EGP_TABLE)
3011                     {
3012                         negptable++;
3013                     }
3014                     else
3015                     {
3016                         bSomeNormalNbListsAreInUse = TRUE;
3017                     }
3018                 }
3019             }
3020         }
3021         if (bSomeNormalNbListsAreInUse)
3022         {
3023             fr->nnblists = negptable + 1;
3024         }
3025         else
3026         {
3027             fr->nnblists = negptable;
3028         }
3029         if (fr->nnblists > 1)
3030         {
3031             snew(fr->gid2nblists, ir->opts.ngener*ir->opts.ngener);
3032         }
3033     }
3034
3035     snew(fr->nblists, fr->nnblists);
3036
3037     /* This code automatically gives table length tabext without cut-off's,
3038      * in that case grompp should already have checked that we do not need
3039      * normal tables and we only generate tables for 1-4 interactions.
3040      */
3041     rtab = ir->rlist + ir->tabext;
3042
3043     if (needGroupSchemeTables)
3044     {
3045         /* make tables for ordinary interactions */
3046         if (bSomeNormalNbListsAreInUse)
3047         {
3048             make_nbf_tables(fp, fr, rtab, tabfn, NULL, NULL, &fr->nblists[0]);
3049             m = 1;
3050         }
3051         else
3052         {
3053             m = 0;
3054         }
3055         if (negptable > 0)
3056         {
3057             /* Read the special tables for certain energy group pairs */
3058             nm_ind = mtop->groups.grps[egcENER].nm_ind;
3059             for (egi = 0; egi < negp_pp; egi++)
3060             {
3061                 for (egj = egi; egj < negp_pp; egj++)
3062                 {
3063                     egp_flags = ir->opts.egp_flags[GID(egi, egj, ir->opts.ngener)];
3064                     if ((egp_flags & EGP_TABLE) && !(egp_flags & EGP_EXCL))
3065                     {
3066                         if (fr->nnblists > 1)
3067                         {
3068                             fr->gid2nblists[GID(egi, egj, ir->opts.ngener)] = m;
3069                         }
3070                         /* Read the table file with the two energy groups names appended */
3071                         make_nbf_tables(fp, fr, rtab, tabfn,
3072                                         *mtop->groups.grpname[nm_ind[egi]],
3073                                         *mtop->groups.grpname[nm_ind[egj]],
3074                                         &fr->nblists[m]);
3075                         m++;
3076                     }
3077                     else if (fr->nnblists > 1)
3078                     {
3079                         fr->gid2nblists[GID(egi, egj, ir->opts.ngener)] = 0;
3080                     }
3081                 }
3082             }
3083         }
3084     }
3085
3086     /* Tables might not be used for the potential modifier
3087      * interactions per se, but we still need them to evaluate
3088      * switch/shift dispersion corrections in this case. */
3089     if (fr->eDispCorr != edispcNO)
3090     {
3091         fr->dispersionCorrectionTable = makeDispersionCorrectionTable(fp, fr, rtab, tabfn);
3092     }
3093
3094     /* We want to use unmodified tables for 1-4 coulombic
3095      * interactions, so we must in general have an extra set of
3096      * tables. */
3097     if (gmx_mtop_ftype_count(mtop, F_LJ14) > 0 ||
3098         gmx_mtop_ftype_count(mtop, F_LJC14_Q) > 0 ||
3099         gmx_mtop_ftype_count(mtop, F_LJC_PAIRS_NB) > 0)
3100     {
3101         fr->pairsTable = make_tables(fp, fr, tabpfn, rtab,
3102                                      GMX_MAKETABLES_14ONLY);
3103     }
3104
3105     /* Wall stuff */
3106     fr->nwall = ir->nwall;
3107     if (ir->nwall && ir->wall_type == ewtTABLE)
3108     {
3109         make_wall_tables(fp, ir, tabfn, &mtop->groups, fr);
3110     }
3111
3112     if (fcd && tabbfnm)
3113     {
3114         // Need to catch std::bad_alloc
3115         // TODO Don't need to catch this here, when merging with master branch
3116         try
3117         {
3118             fcd->bondtab  = make_bonded_tables(fp,
3119                                                F_TABBONDS, F_TABBONDSNC,
3120                                                mtop, tabbfnm, "b");
3121             fcd->angletab = make_bonded_tables(fp,
3122                                                F_TABANGLES, -1,
3123                                                mtop, tabbfnm, "a");
3124             fcd->dihtab   = make_bonded_tables(fp,
3125                                                F_TABDIHS, -1,
3126                                                mtop, tabbfnm, "d");
3127         }
3128         GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
3129     }
3130     else
3131     {
3132         if (debug)
3133         {
3134             fprintf(debug, "No fcdata or table file name passed, can not read table, can not do bonded interactions\n");
3135         }
3136     }
3137
3138     /* QM/MM initialization if requested
3139      */
3140     if (ir->bQMMM)
3141     {
3142         fprintf(stderr, "QM/MM calculation requested.\n");
3143     }
3144
3145     fr->bQMMM      = ir->bQMMM;
3146     fr->qr         = mk_QMMMrec();
3147
3148     /* Set all the static charge group info */
3149     fr->cginfo_mb = init_cginfo_mb(fp, mtop, fr, bNoSolvOpt,
3150                                    &bFEP_NonBonded,
3151                                    &fr->bExcl_IntraCGAll_InterCGNone);
3152     if (DOMAINDECOMP(cr))
3153     {
3154         fr->cginfo = NULL;
3155     }
3156     else
3157     {
3158         fr->cginfo = cginfo_expand(mtop->nmolblock, fr->cginfo_mb);
3159     }
3160
3161     if (!DOMAINDECOMP(cr))
3162     {
3163         forcerec_set_ranges(fr, ncg_mtop(mtop), ncg_mtop(mtop),
3164                             mtop->natoms, mtop->natoms, mtop->natoms);
3165     }
3166
3167     fr->print_force = print_force;
3168
3169
3170     /* coarse load balancing vars */
3171     fr->t_fnbf    = 0.;
3172     fr->t_wait    = 0.;
3173     fr->timesteps = 0;
3174
3175     /* Initialize neighbor search */
3176     snew(fr->ns, 1);
3177     init_ns(fp, cr, fr->ns, fr, mtop);
3178
3179     if (cr->duty & DUTY_PP)
3180     {
3181         gmx_nonbonded_setup(fr, bGenericKernelOnly);
3182     }
3183
3184     /* Initialize the thread working data for bonded interactions */
3185     init_bonded_threading(fp, mtop->groups.grps[egcENER].nr,
3186                           &fr->bonded_threading);
3187
3188     fr->nthread_ewc = gmx_omp_nthreads_get(emntBonded);
3189     snew(fr->ewc_t, fr->nthread_ewc);
3190
3191     /* fr->ic is used both by verlet and group kernels (to some extent) now */
3192     init_interaction_const(fp, &fr->ic, fr);
3193     init_interaction_const_tables(fp, fr->ic, rtab);
3194
3195     if (fr->cutoff_scheme == ecutsVERLET)
3196     {
3197         // We checked the cut-offs in grompp, but double-check here.
3198         // We have PME+LJcutoff kernels for rcoulomb>rvdw.
3199         if (EEL_PME_EWALD(ir->coulombtype) && ir->vdwtype == eelCUT)
3200         {
3201             GMX_RELEASE_ASSERT(ir->rcoulomb >= ir->rvdw, "With Verlet lists and PME we should have rcoulomb>=rvdw");
3202         }
3203         else
3204         {
3205             GMX_RELEASE_ASSERT(ir->rcoulomb == ir->rvdw, "With Verlet lists and no PME rcoulomb and rvdw should be identical");
3206         }
3207
3208         init_nb_verlet(fp, &fr->nbv, bFEP_NonBonded, ir, fr, cr, nbpu_opt);
3209     }
3210
3211     if (ir->eDispCorr != edispcNO)
3212     {
3213         calc_enervirdiff(fp, ir->eDispCorr, fr);
3214     }
3215 }
3216
3217 #define pr_real(fp, r) fprintf(fp, "%s: %e\n",#r, r)
3218 #define pr_int(fp, i)  fprintf((fp), "%s: %d\n",#i, i)
3219 #define pr_bool(fp, b) fprintf((fp), "%s: %s\n",#b, gmx::boolToString(b))
3220
3221 void pr_forcerec(FILE *fp, t_forcerec *fr)
3222 {
3223     int i;
3224
3225     pr_real(fp, fr->rlist);
3226     pr_real(fp, fr->rcoulomb);
3227     pr_real(fp, fr->fudgeQQ);
3228     pr_bool(fp, fr->bGrid);
3229     /*pr_int(fp,fr->cg0);
3230        pr_int(fp,fr->hcg);*/
3231     for (i = 0; i < fr->nnblists; i++)
3232     {
3233         pr_int(fp, fr->nblists[i].table_elec_vdw->n);
3234     }
3235     pr_real(fp, fr->rcoulomb_switch);
3236     pr_real(fp, fr->rcoulomb);
3237
3238     fflush(fp);
3239 }
3240
3241 /* Frees GPU memory and destroys the GPU context.
3242  *
3243  * Note that this function needs to be called even if GPUs are not used
3244  * in this run because the PME ranks have no knowledge of whether GPUs
3245  * are used or not, but all ranks need to enter the barrier below.
3246  */
3247 void free_gpu_resources(const t_forcerec     *fr,
3248                         const t_commrec      *cr,
3249                         const gmx_gpu_info_t *gpu_info,
3250                         const gmx_gpu_opt_t  *gpu_opt)
3251 {
3252     gmx_bool bIsPPrankUsingGPU;
3253     char     gpu_err_str[STRLEN];
3254
3255     bIsPPrankUsingGPU = (cr->duty & DUTY_PP) && fr && fr->nbv && fr->nbv->bUseGPU;
3256
3257     if (bIsPPrankUsingGPU)
3258     {
3259         /* free nbnxn data in GPU memory */
3260         nbnxn_gpu_free(fr->nbv->gpu_nbv);
3261         /* stop the GPU profiler (only CUDA) */
3262         stopGpuProfiler();
3263
3264         /* With tMPI we need to wait for all ranks to finish deallocation before
3265          * destroying the CUDA context in free_gpu() as some tMPI ranks may be sharing
3266          * GPU and context.
3267          *
3268          * This is not a concern in OpenCL where we use one context per rank which
3269          * is freed in nbnxn_gpu_free().
3270          *
3271          * Note: as only PP ranks need to free GPU resources, so it is safe to
3272          * not call the barrier on PME ranks.
3273          */
3274 #if GMX_THREAD_MPI
3275         if (PAR(cr))
3276         {
3277             gmx_barrier(cr);
3278         }
3279 #endif  /* GMX_THREAD_MPI */
3280
3281         /* uninitialize GPU (by destroying the context) */
3282         if (!free_cuda_gpu(cr->rank_pp_intranode, gpu_err_str, gpu_info, gpu_opt))
3283         {
3284             gmx_warning("On rank %d failed to free GPU #%d: %s",
3285                         cr->nodeid, get_current_cuda_gpu_device_id(), gpu_err_str);
3286         }
3287     }
3288 }