Removed unused host-side allocation code
[alexxy/gromacs.git] / src / gromacs / mdlib / forcerec.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014,2015,2016, by the GROMACS development team, led by
7  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8  * and including many others, as listed in the AUTHORS file in the
9  * top-level source directory and at http://www.gromacs.org.
10  *
11  * GROMACS is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the License, or (at your option) any later version.
15  *
16  * GROMACS is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with GROMACS; if not, see
23  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
25  *
26  * If you want to redistribute modifications to GROMACS, please
27  * consider that scientific software is very special. Version
28  * control is crucial - bugs must be traceable. We will be happy to
29  * consider code for inclusion in the official distribution, but
30  * derived work must not be called official GROMACS. Details are found
31  * in the README & COPYING files - if they are missing, get the
32  * official version at http://www.gromacs.org.
33  *
34  * To help us fund GROMACS development, we humbly ask that you cite
35  * the research papers on the package. Check out http://www.gromacs.org.
36  */
37 #include "gmxpre.h"
38
39 #include "forcerec.h"
40
41 #include "config.h"
42
43 #include <assert.h>
44 #include <stdlib.h>
45 #include <string.h>
46
47 #include <cmath>
48
49 #include <algorithm>
50
51 #include "gromacs/commandline/filenm.h"
52 #include "gromacs/domdec/domdec.h"
53 #include "gromacs/domdec/domdec_struct.h"
54 #include "gromacs/ewald/ewald.h"
55 #include "gromacs/fileio/filetypes.h"
56 #include "gromacs/gmxlib/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 (fr->coulomb_modifier == eintmodPOTSHIFT)
2060     {
2061         ic->sh_ewald = std::erfc(ic->ewaldcoeff_q*ic->rcoulomb);
2062     }
2063     else
2064     {
2065         ic->sh_ewald = 0;
2066     }
2067
2068     /* Reaction-field */
2069     if (EEL_RF(ic->eeltype))
2070     {
2071         ic->epsilon_rf = fr->epsilon_rf;
2072         ic->k_rf       = fr->k_rf;
2073         ic->c_rf       = fr->c_rf;
2074     }
2075     else
2076     {
2077         /* For plain cut-off we might use the reaction-field kernels */
2078         ic->epsilon_rf = ic->epsilon_r;
2079         ic->k_rf       = 0;
2080         if (fr->coulomb_modifier == eintmodPOTSHIFT)
2081         {
2082             ic->c_rf   = 1/ic->rcoulomb;
2083         }
2084         else
2085         {
2086             ic->c_rf   = 0;
2087         }
2088     }
2089
2090     if (fp != NULL)
2091     {
2092         real dispersion_shift;
2093
2094         dispersion_shift = ic->dispersion_shift.cpot;
2095         if (EVDW_PME(ic->vdwtype))
2096         {
2097             dispersion_shift -= ic->sh_lj_ewald;
2098         }
2099         fprintf(fp, "Potential shift: LJ r^-12: %.3e r^-6: %.3e",
2100                 ic->repulsion_shift.cpot, dispersion_shift);
2101
2102         if (ic->eeltype == eelCUT)
2103         {
2104             fprintf(fp, ", Coulomb %.e", -ic->c_rf);
2105         }
2106         else if (EEL_PME(ic->eeltype))
2107         {
2108             fprintf(fp, ", Ewald %.3e", -ic->sh_ewald);
2109         }
2110         fprintf(fp, "\n");
2111     }
2112
2113     *interaction_const = ic;
2114 }
2115
2116 static void init_nb_verlet(FILE                *fp,
2117                            nonbonded_verlet_t **nb_verlet,
2118                            gmx_bool             bFEP_NonBonded,
2119                            const t_inputrec    *ir,
2120                            const t_forcerec    *fr,
2121                            const t_commrec     *cr,
2122                            const char          *nbpu_opt)
2123 {
2124     nonbonded_verlet_t *nbv;
2125     int                 i;
2126     char               *env;
2127     gmx_bool            bEmulateGPU, bHybridGPURun = FALSE;
2128
2129     nbnxn_alloc_t      *nb_alloc;
2130     nbnxn_free_t       *nb_free;
2131
2132     snew(nbv, 1);
2133
2134     pick_nbnxn_resources(fp, cr, fr->hwinfo,
2135                          fr->bNonbonded,
2136                          &nbv->bUseGPU,
2137                          &bEmulateGPU,
2138                          fr->gpu_opt);
2139
2140     nbv->nbs             = NULL;
2141     nbv->min_ci_balanced = 0;
2142
2143     nbv->ngrp = (DOMAINDECOMP(cr) ? 2 : 1);
2144     for (i = 0; i < nbv->ngrp; i++)
2145     {
2146         nbv->grp[i].nbl_lists.nnbl = 0;
2147         nbv->grp[i].nbat           = NULL;
2148         nbv->grp[i].kernel_type    = nbnxnkNotSet;
2149
2150         if (i == 0) /* local */
2151         {
2152             pick_nbnxn_kernel(fp, cr, fr->use_simd_kernels,
2153                               nbv->bUseGPU, bEmulateGPU, ir,
2154                               &nbv->grp[i].kernel_type,
2155                               &nbv->grp[i].ewald_excl,
2156                               fr->bNonbonded);
2157         }
2158         else /* non-local */
2159         {
2160             if (nbpu_opt != NULL && strcmp(nbpu_opt, "gpu_cpu") == 0)
2161             {
2162                 /* Use GPU for local, select a CPU kernel for non-local */
2163                 pick_nbnxn_kernel(fp, cr, fr->use_simd_kernels,
2164                                   FALSE, FALSE, ir,
2165                                   &nbv->grp[i].kernel_type,
2166                                   &nbv->grp[i].ewald_excl,
2167                                   fr->bNonbonded);
2168
2169                 bHybridGPURun = TRUE;
2170             }
2171             else
2172             {
2173                 /* Use the same kernel for local and non-local interactions */
2174                 nbv->grp[i].kernel_type = nbv->grp[0].kernel_type;
2175                 nbv->grp[i].ewald_excl  = nbv->grp[0].ewald_excl;
2176             }
2177         }
2178     }
2179
2180     nbnxn_init_search(&nbv->nbs,
2181                       DOMAINDECOMP(cr) ? &cr->dd->nc : NULL,
2182                       DOMAINDECOMP(cr) ? domdec_zones(cr->dd) : NULL,
2183                       bFEP_NonBonded,
2184                       gmx_omp_nthreads_get(emntPairsearch));
2185
2186     for (i = 0; i < nbv->ngrp; i++)
2187     {
2188         gpu_set_host_malloc_and_free(nbv->grp[0].kernel_type == nbnxnk8x8x8_GPU,
2189                                      &nb_alloc, &nb_free);
2190
2191         nbnxn_init_pairlist_set(&nbv->grp[i].nbl_lists,
2192                                 nbnxn_kernel_pairlist_simple(nbv->grp[i].kernel_type),
2193                                 /* 8x8x8 "non-simple" lists are ATM always combined */
2194                                 !nbnxn_kernel_pairlist_simple(nbv->grp[i].kernel_type),
2195                                 nb_alloc, nb_free);
2196
2197         if (i == 0 ||
2198             nbv->grp[0].kernel_type != nbv->grp[i].kernel_type)
2199         {
2200             gmx_bool bSimpleList;
2201             int      enbnxninitcombrule;
2202
2203             bSimpleList = nbnxn_kernel_pairlist_simple(nbv->grp[i].kernel_type);
2204
2205             if (fr->vdwtype == evdwCUT &&
2206                 (fr->vdw_modifier == eintmodNONE ||
2207                  fr->vdw_modifier == eintmodPOTSHIFT) &&
2208                 getenv("GMX_NO_LJ_COMB_RULE") == NULL)
2209             {
2210                 /* Plain LJ cut-off: we can optimize with combination rules */
2211                 enbnxninitcombrule = enbnxninitcombruleDETECT;
2212             }
2213             else if (fr->vdwtype == evdwPME)
2214             {
2215                 /* LJ-PME: we need to use a combination rule for the grid */
2216                 if (fr->ljpme_combination_rule == eljpmeGEOM)
2217                 {
2218                     enbnxninitcombrule = enbnxninitcombruleGEOM;
2219                 }
2220                 else
2221                 {
2222                     enbnxninitcombrule = enbnxninitcombruleLB;
2223                 }
2224             }
2225             else
2226             {
2227                 /* We use a full combination matrix: no rule required */
2228                 enbnxninitcombrule = enbnxninitcombruleNONE;
2229             }
2230
2231
2232             snew(nbv->grp[i].nbat, 1);
2233             nbnxn_atomdata_init(fp,
2234                                 nbv->grp[i].nbat,
2235                                 nbv->grp[i].kernel_type,
2236                                 enbnxninitcombrule,
2237                                 fr->ntype, fr->nbfp,
2238                                 ir->opts.ngener,
2239                                 bSimpleList ? gmx_omp_nthreads_get(emntNonbonded) : 1,
2240                                 nb_alloc, nb_free);
2241         }
2242         else
2243         {
2244             nbv->grp[i].nbat = nbv->grp[0].nbat;
2245         }
2246     }
2247
2248     if (nbv->bUseGPU)
2249     {
2250         /* init the NxN GPU data; the last argument tells whether we'll have
2251          * both local and non-local NB calculation on GPU */
2252         nbnxn_gpu_init(&nbv->gpu_nbv,
2253                        &fr->hwinfo->gpu_info,
2254                        fr->gpu_opt,
2255                        fr->ic,
2256                        nbv->grp,
2257                        cr->rank_pp_intranode,
2258                        cr->nodeid,
2259                        (nbv->ngrp > 1) && !bHybridGPURun);
2260
2261         /* With tMPI + GPUs some ranks may be sharing GPU(s) and therefore
2262          * also sharing texture references. To keep the code simple, we don't
2263          * treat texture references as shared resources, but this means that
2264          * the coulomb_tab and nbfp texture refs will get updated by multiple threads.
2265          * Hence, to ensure that the non-bonded kernels don't start before all
2266          * texture binding operations are finished, we need to wait for all ranks
2267          * to arrive here before continuing.
2268          *
2269          * Note that we could omit this barrier if GPUs are not shared (or
2270          * texture objects are used), but as this is initialization code, there
2271          * is no point in complicating things.
2272          */
2273 #if GMX_THREAD_MPI
2274         if (PAR(cr))
2275         {
2276             gmx_barrier(cr);
2277         }
2278 #endif  /* GMX_THREAD_MPI */
2279
2280         if ((env = getenv("GMX_NB_MIN_CI")) != NULL)
2281         {
2282             char *end;
2283
2284             nbv->min_ci_balanced = strtol(env, &end, 10);
2285             if (!end || (*end != 0) || nbv->min_ci_balanced < 0)
2286             {
2287                 gmx_fatal(FARGS, "Invalid value passed in GMX_NB_MIN_CI=%s, non-negative integer required", env);
2288             }
2289
2290             if (debug)
2291             {
2292                 fprintf(debug, "Neighbor-list balancing parameter: %d (passed as env. var.)\n",
2293                         nbv->min_ci_balanced);
2294             }
2295         }
2296         else
2297         {
2298             nbv->min_ci_balanced = nbnxn_gpu_min_ci_balanced(nbv->gpu_nbv);
2299             if (debug)
2300             {
2301                 fprintf(debug, "Neighbor-list balancing parameter: %d (auto-adjusted to the number of GPU multi-processors)\n",
2302                         nbv->min_ci_balanced);
2303             }
2304         }
2305
2306     }
2307
2308     *nb_verlet = nbv;
2309 }
2310
2311 gmx_bool usingGpu(nonbonded_verlet_t *nbv)
2312 {
2313     return nbv != NULL && nbv->bUseGPU;
2314 }
2315
2316 void init_forcerec(FILE              *fp,
2317                    t_forcerec        *fr,
2318                    t_fcdata          *fcd,
2319                    const t_inputrec  *ir,
2320                    const gmx_mtop_t  *mtop,
2321                    const t_commrec   *cr,
2322                    matrix             box,
2323                    const char        *tabfn,
2324                    const char        *tabpfn,
2325                    const t_filenm    *tabbfnm,
2326                    const char        *nbpu_opt,
2327                    gmx_bool           bNoSolvOpt,
2328                    real               print_force)
2329 {
2330     int            i, m, negp_pp, negptable, egi, egj;
2331     real           rtab;
2332     char          *env;
2333     double         dbl;
2334     const t_block *cgs;
2335     gmx_bool       bGenericKernelOnly;
2336     gmx_bool       needGroupSchemeTables, bSomeNormalNbListsAreInUse;
2337     gmx_bool       bFEP_NonBonded;
2338     int           *nm_ind, egp_flags;
2339
2340     if (fr->hwinfo == NULL)
2341     {
2342         /* Detect hardware, gather information.
2343          * In mdrun, hwinfo has already been set before calling init_forcerec.
2344          * Here we ignore GPUs, as tools will not use them anyhow.
2345          */
2346         fr->hwinfo = gmx_detect_hardware(fp, cr, FALSE);
2347     }
2348
2349     /* By default we turn SIMD kernels on, but it might be turned off further down... */
2350     fr->use_simd_kernels = TRUE;
2351
2352     fr->bDomDec = DOMAINDECOMP(cr);
2353
2354     if (check_box(ir->ePBC, box))
2355     {
2356         gmx_fatal(FARGS, check_box(ir->ePBC, box));
2357     }
2358
2359     /* Test particle insertion ? */
2360     if (EI_TPI(ir->eI))
2361     {
2362         /* Set to the size of the molecule to be inserted (the last one) */
2363         /* Because of old style topologies, we have to use the last cg
2364          * instead of the last molecule type.
2365          */
2366         cgs       = &mtop->moltype[mtop->molblock[mtop->nmolblock-1].type].cgs;
2367         fr->n_tpi = cgs->index[cgs->nr] - cgs->index[cgs->nr-1];
2368         if (fr->n_tpi != mtop->mols.index[mtop->mols.nr] - mtop->mols.index[mtop->mols.nr-1])
2369         {
2370             gmx_fatal(FARGS, "The molecule to insert can not consist of multiple charge groups.\nMake it a single charge group.");
2371         }
2372     }
2373     else
2374     {
2375         fr->n_tpi = 0;
2376     }
2377
2378     if (ir->coulombtype == eelRF_NEC_UNSUPPORTED)
2379     {
2380         gmx_fatal(FARGS, "%s electrostatics is no longer supported",
2381                   eel_names[ir->coulombtype]);
2382     }
2383
2384     if (ir->bAdress)
2385     {
2386         gmx_fatal(FARGS, "AdResS simulations are no longer supported");
2387     }
2388     if (ir->useTwinRange)
2389     {
2390         gmx_fatal(FARGS, "Twin-range simulations are no longer supported");
2391     }
2392     /* Copy the user determined parameters */
2393     fr->userint1  = ir->userint1;
2394     fr->userint2  = ir->userint2;
2395     fr->userint3  = ir->userint3;
2396     fr->userint4  = ir->userint4;
2397     fr->userreal1 = ir->userreal1;
2398     fr->userreal2 = ir->userreal2;
2399     fr->userreal3 = ir->userreal3;
2400     fr->userreal4 = ir->userreal4;
2401
2402     /* Shell stuff */
2403     fr->fc_stepsize = ir->fc_stepsize;
2404
2405     /* Free energy */
2406     fr->efep        = ir->efep;
2407     fr->sc_alphavdw = ir->fepvals->sc_alpha;
2408     if (ir->fepvals->bScCoul)
2409     {
2410         fr->sc_alphacoul  = ir->fepvals->sc_alpha;
2411         fr->sc_sigma6_min = gmx::power6(ir->fepvals->sc_sigma_min);
2412     }
2413     else
2414     {
2415         fr->sc_alphacoul  = 0;
2416         fr->sc_sigma6_min = 0; /* only needed when bScCoul is on */
2417     }
2418     fr->sc_power      = ir->fepvals->sc_power;
2419     fr->sc_r_power    = ir->fepvals->sc_r_power;
2420     fr->sc_sigma6_def = gmx::power6(ir->fepvals->sc_sigma);
2421
2422     env = getenv("GMX_SCSIGMA_MIN");
2423     if (env != NULL)
2424     {
2425         dbl = 0;
2426         sscanf(env, "%20lf", &dbl);
2427         fr->sc_sigma6_min = gmx::power6(dbl);
2428         if (fp)
2429         {
2430             fprintf(fp, "Setting the minimum soft core sigma to %g nm\n", dbl);
2431         }
2432     }
2433
2434     fr->bNonbonded = TRUE;
2435     if (getenv("GMX_NO_NONBONDED") != NULL)
2436     {
2437         /* turn off non-bonded calculations */
2438         fr->bNonbonded = FALSE;
2439         md_print_warn(cr, fp,
2440                       "Found environment variable GMX_NO_NONBONDED.\n"
2441                       "Disabling nonbonded calculations.\n");
2442     }
2443
2444     bGenericKernelOnly = FALSE;
2445
2446     /* We now check in the NS code whether a particular combination of interactions
2447      * can be used with water optimization, and disable it if that is not the case.
2448      */
2449
2450     if (getenv("GMX_NB_GENERIC") != NULL)
2451     {
2452         if (fp != NULL)
2453         {
2454             fprintf(fp,
2455                     "Found environment variable GMX_NB_GENERIC.\n"
2456                     "Disabling all interaction-specific nonbonded kernels, will only\n"
2457                     "use the slow generic ones in src/gmxlib/nonbonded/nb_generic.c\n\n");
2458         }
2459         bGenericKernelOnly = TRUE;
2460     }
2461
2462     if (bGenericKernelOnly == TRUE)
2463     {
2464         bNoSolvOpt         = TRUE;
2465     }
2466
2467     if ( (getenv("GMX_DISABLE_SIMD_KERNELS") != NULL) || (getenv("GMX_NOOPTIMIZEDKERNELS") != NULL) )
2468     {
2469         fr->use_simd_kernels = FALSE;
2470         if (fp != NULL)
2471         {
2472             fprintf(fp,
2473                     "\nFound environment variable GMX_DISABLE_SIMD_KERNELS.\n"
2474                     "Disabling the usage of any SIMD-specific non-bonded & bonded kernel routines\n"
2475                     "(e.g. SSE2/SSE4.1/AVX).\n\n");
2476         }
2477     }
2478
2479     fr->bBHAM = (mtop->ffparams.functype[0] == F_BHAM);
2480
2481     /* Check if we can/should do all-vs-all kernels */
2482     fr->bAllvsAll       = can_use_allvsall(ir, FALSE, NULL, NULL);
2483     fr->AllvsAll_work   = NULL;
2484     fr->AllvsAll_workgb = NULL;
2485
2486     /* All-vs-all kernels have not been implemented in 4.6 and later.
2487      * See Redmine #1249. */
2488     if (fr->bAllvsAll)
2489     {
2490         fr->bAllvsAll            = FALSE;
2491         if (fp != NULL)
2492         {
2493             fprintf(fp,
2494                     "\nYour simulation settings would have triggered the efficient all-vs-all\n"
2495                     "kernels in GROMACS 4.5, but these have not been implemented in GROMACS\n"
2496                     "4.6 and 5.x. If performance is important, please use GROMACS 4.5.7\n"
2497                     "or try cutoff-scheme = Verlet.\n\n");
2498         }
2499     }
2500
2501     /* Neighbour searching stuff */
2502     fr->cutoff_scheme = ir->cutoff_scheme;
2503     fr->bGrid         = (ir->ns_type == ensGRID);
2504     fr->ePBC          = ir->ePBC;
2505
2506     if (fr->cutoff_scheme == ecutsGROUP)
2507     {
2508         const char *note = "NOTE: This file uses the deprecated 'group' cutoff_scheme. This will be\n"
2509             "removed in a future release when 'verlet' supports all interaction forms.\n";
2510
2511         if (MASTER(cr))
2512         {
2513             fprintf(stderr, "\n%s\n", note);
2514         }
2515         if (fp != NULL)
2516         {
2517             fprintf(fp, "\n%s\n", note);
2518         }
2519     }
2520
2521     /* Determine if we will do PBC for distances in bonded interactions */
2522     if (fr->ePBC == epbcNONE)
2523     {
2524         fr->bMolPBC = FALSE;
2525     }
2526     else
2527     {
2528         if (!DOMAINDECOMP(cr))
2529         {
2530             gmx_bool bSHAKE;
2531
2532             bSHAKE = (ir->eConstrAlg == econtSHAKE &&
2533                       (gmx_mtop_ftype_count(mtop, F_CONSTR) > 0 ||
2534                        gmx_mtop_ftype_count(mtop, F_CONSTRNC) > 0));
2535
2536             /* The group cut-off scheme and SHAKE assume charge groups
2537              * are whole, but not using molpbc is faster in most cases.
2538              * With intermolecular interactions we need PBC for calculating
2539              * distances between atoms in different molecules.
2540              */
2541             if ((fr->cutoff_scheme == ecutsGROUP || bSHAKE) &&
2542                 !mtop->bIntermolecularInteractions)
2543             {
2544                 fr->bMolPBC = ir->bPeriodicMols;
2545
2546                 if (bSHAKE && fr->bMolPBC)
2547                 {
2548                     gmx_fatal(FARGS, "SHAKE is not supported with periodic molecules");
2549                 }
2550             }
2551             else
2552             {
2553                 fr->bMolPBC = TRUE;
2554
2555                 if (getenv("GMX_USE_GRAPH") != NULL)
2556                 {
2557                     fr->bMolPBC = FALSE;
2558                     if (fp)
2559                     {
2560                         md_print_warn(cr, fp, "GMX_USE_GRAPH is set, using the graph for bonded interactions\n");
2561                     }
2562
2563                     if (mtop->bIntermolecularInteractions)
2564                     {
2565                         md_print_warn(cr, fp, "WARNING: Molecules linked by intermolecular interactions have to reside in the same periodic image, otherwise artifacts will occur!\n");
2566                     }
2567                 }
2568
2569                 if (bSHAKE && fr->bMolPBC)
2570                 {
2571                     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");
2572                 }
2573             }
2574         }
2575         else
2576         {
2577             fr->bMolPBC = dd_bonded_molpbc(cr->dd, fr->ePBC);
2578         }
2579     }
2580     fr->bGB = (ir->implicit_solvent == eisGBSA);
2581
2582     fr->rc_scaling = ir->refcoord_scaling;
2583     copy_rvec(ir->posres_com, fr->posres_com);
2584     copy_rvec(ir->posres_comB, fr->posres_comB);
2585     fr->rlist                    = cutoff_inf(ir->rlist);
2586     fr->eeltype                  = ir->coulombtype;
2587     fr->vdwtype                  = ir->vdwtype;
2588     fr->ljpme_combination_rule   = ir->ljpme_combination_rule;
2589
2590     fr->coulomb_modifier = ir->coulomb_modifier;
2591     fr->vdw_modifier     = ir->vdw_modifier;
2592
2593     /* Electrostatics: Translate from interaction-setting-in-mdp-file to kernel interaction format */
2594     switch (fr->eeltype)
2595     {
2596         case eelCUT:
2597             fr->nbkernel_elec_interaction = (fr->bGB) ? GMX_NBKERNEL_ELEC_GENERALIZEDBORN : GMX_NBKERNEL_ELEC_COULOMB;
2598             break;
2599
2600         case eelRF:
2601         case eelGRF:
2602             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_REACTIONFIELD;
2603             break;
2604
2605         case eelRF_ZERO:
2606             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_REACTIONFIELD;
2607             fr->coulomb_modifier          = eintmodEXACTCUTOFF;
2608             break;
2609
2610         case eelSWITCH:
2611         case eelSHIFT:
2612         case eelUSER:
2613         case eelENCADSHIFT:
2614         case eelPMESWITCH:
2615         case eelPMEUSER:
2616         case eelPMEUSERSWITCH:
2617             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_CUBICSPLINETABLE;
2618             break;
2619
2620         case eelPME:
2621         case eelP3M_AD:
2622         case eelEWALD:
2623             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_EWALD;
2624             break;
2625
2626         default:
2627             gmx_fatal(FARGS, "Unsupported electrostatic interaction: %s", eel_names[fr->eeltype]);
2628             break;
2629     }
2630
2631     /* Vdw: Translate from mdp settings to kernel format */
2632     switch (fr->vdwtype)
2633     {
2634         case evdwCUT:
2635             if (fr->bBHAM)
2636             {
2637                 fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_BUCKINGHAM;
2638             }
2639             else
2640             {
2641                 fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_LENNARDJONES;
2642             }
2643             break;
2644         case evdwPME:
2645             fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_LJEWALD;
2646             break;
2647
2648         case evdwSWITCH:
2649         case evdwSHIFT:
2650         case evdwUSER:
2651         case evdwENCADSHIFT:
2652             fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_CUBICSPLINETABLE;
2653             break;
2654
2655         default:
2656             gmx_fatal(FARGS, "Unsupported vdw interaction: %s", evdw_names[fr->vdwtype]);
2657             break;
2658     }
2659
2660     /* These start out identical to ir, but might be altered if we e.g. tabulate the interaction in the kernel */
2661     fr->nbkernel_elec_modifier    = fr->coulomb_modifier;
2662     fr->nbkernel_vdw_modifier     = fr->vdw_modifier;
2663
2664     fr->rvdw             = cutoff_inf(ir->rvdw);
2665     fr->rvdw_switch      = ir->rvdw_switch;
2666     fr->rcoulomb         = cutoff_inf(ir->rcoulomb);
2667     fr->rcoulomb_switch  = ir->rcoulomb_switch;
2668
2669     fr->bEwald     = EEL_PME_EWALD(fr->eeltype);
2670
2671     fr->reppow     = mtop->ffparams.reppow;
2672
2673     if (ir->cutoff_scheme == ecutsGROUP)
2674     {
2675         fr->bvdwtab    = ((fr->vdwtype != evdwCUT || !gmx_within_tol(fr->reppow, 12.0, 10*GMX_DOUBLE_EPS))
2676                           && !EVDW_PME(fr->vdwtype));
2677         /* We have special kernels for standard Ewald and PME, but the pme-switch ones are tabulated above */
2678         fr->bcoultab   = !(fr->eeltype == eelCUT ||
2679                            fr->eeltype == eelEWALD ||
2680                            fr->eeltype == eelPME ||
2681                            fr->eeltype == eelRF ||
2682                            fr->eeltype == eelRF_ZERO);
2683
2684         /* If the user absolutely wants different switch/shift settings for coul/vdw, it is likely
2685          * going to be faster to tabulate the interaction than calling the generic kernel.
2686          * However, if generic kernels have been requested we keep things analytically.
2687          */
2688         if (fr->nbkernel_elec_modifier == eintmodPOTSWITCH &&
2689             fr->nbkernel_vdw_modifier == eintmodPOTSWITCH &&
2690             bGenericKernelOnly == FALSE)
2691         {
2692             if ((fr->rcoulomb_switch != fr->rvdw_switch) || (fr->rcoulomb != fr->rvdw))
2693             {
2694                 fr->bcoultab = TRUE;
2695                 /* Once we tabulate electrostatics, we can use the switch function for LJ,
2696                  * which would otherwise need two tables.
2697                  */
2698             }
2699         }
2700         else if ((fr->nbkernel_elec_modifier == eintmodPOTSHIFT && fr->nbkernel_vdw_modifier == eintmodPOTSHIFT) ||
2701                  ((fr->nbkernel_elec_interaction == GMX_NBKERNEL_ELEC_REACTIONFIELD &&
2702                    fr->nbkernel_elec_modifier == eintmodEXACTCUTOFF &&
2703                    (fr->nbkernel_vdw_modifier == eintmodPOTSWITCH || fr->nbkernel_vdw_modifier == eintmodPOTSHIFT))))
2704         {
2705             if ((fr->rcoulomb != fr->rvdw) && (bGenericKernelOnly == FALSE))
2706             {
2707                 fr->bcoultab = TRUE;
2708             }
2709         }
2710
2711         if (fr->nbkernel_elec_modifier == eintmodFORCESWITCH)
2712         {
2713             fr->bcoultab = TRUE;
2714         }
2715         if (fr->nbkernel_vdw_modifier == eintmodFORCESWITCH)
2716         {
2717             fr->bvdwtab = TRUE;
2718         }
2719
2720         if (getenv("GMX_REQUIRE_TABLES"))
2721         {
2722             fr->bvdwtab  = TRUE;
2723             fr->bcoultab = TRUE;
2724         }
2725
2726         if (fp)
2727         {
2728             fprintf(fp, "Table routines are used for coulomb: %s\n",
2729                     gmx::boolToString(fr->bcoultab));
2730             fprintf(fp, "Table routines are used for vdw:     %s\n",
2731                     gmx::boolToString(fr->bvdwtab));
2732         }
2733
2734         if (fr->bvdwtab == TRUE)
2735         {
2736             fr->nbkernel_vdw_interaction = GMX_NBKERNEL_VDW_CUBICSPLINETABLE;
2737             fr->nbkernel_vdw_modifier    = eintmodNONE;
2738         }
2739         if (fr->bcoultab == TRUE)
2740         {
2741             fr->nbkernel_elec_interaction = GMX_NBKERNEL_ELEC_CUBICSPLINETABLE;
2742             fr->nbkernel_elec_modifier    = eintmodNONE;
2743         }
2744     }
2745
2746     if (ir->cutoff_scheme == ecutsVERLET)
2747     {
2748         if (!gmx_within_tol(fr->reppow, 12.0, 10*GMX_DOUBLE_EPS))
2749         {
2750             gmx_fatal(FARGS, "Cut-off scheme %S only supports LJ repulsion power 12", ecutscheme_names[ir->cutoff_scheme]);
2751         }
2752         fr->bvdwtab  = FALSE;
2753         fr->bcoultab = FALSE;
2754     }
2755
2756     /* Tables are used for direct ewald sum */
2757     if (fr->bEwald)
2758     {
2759         if (EEL_PME(ir->coulombtype))
2760         {
2761             if (fp)
2762             {
2763                 fprintf(fp, "Will do PME sum in reciprocal space for electrostatic interactions.\n");
2764             }
2765             if (ir->coulombtype == eelP3M_AD)
2766             {
2767                 please_cite(fp, "Hockney1988");
2768                 please_cite(fp, "Ballenegger2012");
2769             }
2770             else
2771             {
2772                 please_cite(fp, "Essmann95a");
2773             }
2774
2775             if (ir->ewald_geometry == eewg3DC)
2776             {
2777                 if (fp)
2778                 {
2779                     fprintf(fp, "Using the Ewald3DC correction for systems with a slab geometry.\n");
2780                 }
2781                 please_cite(fp, "In-Chul99a");
2782             }
2783         }
2784         fr->ewaldcoeff_q = calc_ewaldcoeff_q(ir->rcoulomb, ir->ewald_rtol);
2785         init_ewald_tab(&(fr->ewald_table), ir, fp);
2786         if (fp)
2787         {
2788             fprintf(fp, "Using a Gaussian width (1/beta) of %g nm for Ewald\n",
2789                     1/fr->ewaldcoeff_q);
2790         }
2791     }
2792
2793     if (EVDW_PME(ir->vdwtype))
2794     {
2795         if (fp)
2796         {
2797             fprintf(fp, "Will do PME sum in reciprocal space for LJ dispersion interactions.\n");
2798         }
2799         please_cite(fp, "Essmann95a");
2800         fr->ewaldcoeff_lj = calc_ewaldcoeff_lj(ir->rvdw, ir->ewald_rtol_lj);
2801         if (fp)
2802         {
2803             fprintf(fp, "Using a Gaussian width (1/beta) of %g nm for LJ Ewald\n",
2804                     1/fr->ewaldcoeff_lj);
2805         }
2806     }
2807
2808     /* Electrostatics */
2809     fr->epsilon_r       = ir->epsilon_r;
2810     fr->epsilon_rf      = ir->epsilon_rf;
2811     fr->fudgeQQ         = mtop->ffparams.fudgeQQ;
2812
2813     /* Parameters for generalized RF */
2814     fr->zsquare = 0.0;
2815     fr->temp    = 0.0;
2816
2817     if (fr->eeltype == eelGRF)
2818     {
2819         init_generalized_rf(fp, mtop, ir, fr);
2820     }
2821
2822     fr->bF_NoVirSum = (EEL_FULL(fr->eeltype) || EVDW_PME(fr->vdwtype) ||
2823                        gmx_mtop_ftype_count(mtop, F_POSRES) > 0 ||
2824                        gmx_mtop_ftype_count(mtop, F_FBPOSRES) > 0 ||
2825                        inputrecElecField(ir)
2826                        );
2827
2828     if (fr->cutoff_scheme == ecutsGROUP &&
2829         ncg_mtop(mtop) > fr->cg_nalloc && !DOMAINDECOMP(cr))
2830     {
2831         /* Count the total number of charge groups */
2832         fr->cg_nalloc = ncg_mtop(mtop);
2833         srenew(fr->cg_cm, fr->cg_nalloc);
2834     }
2835     if (fr->shift_vec == NULL)
2836     {
2837         snew(fr->shift_vec, SHIFTS);
2838     }
2839
2840     if (fr->fshift == NULL)
2841     {
2842         snew(fr->fshift, SHIFTS);
2843     }
2844
2845     if (fr->nbfp == NULL)
2846     {
2847         fr->ntype = mtop->ffparams.atnr;
2848         fr->nbfp  = mk_nbfp(&mtop->ffparams, fr->bBHAM);
2849         if (EVDW_PME(fr->vdwtype))
2850         {
2851             fr->ljpme_c6grid  = make_ljpme_c6grid(&mtop->ffparams, fr);
2852         }
2853     }
2854
2855     /* Copy the energy group exclusions */
2856     fr->egp_flags = ir->opts.egp_flags;
2857
2858     /* Van der Waals stuff */
2859     if ((fr->vdwtype != evdwCUT) && (fr->vdwtype != evdwUSER) && !fr->bBHAM)
2860     {
2861         if (fr->rvdw_switch >= fr->rvdw)
2862         {
2863             gmx_fatal(FARGS, "rvdw_switch (%f) must be < rvdw (%f)",
2864                       fr->rvdw_switch, fr->rvdw);
2865         }
2866         if (fp)
2867         {
2868             fprintf(fp, "Using %s Lennard-Jones, switch between %g and %g nm\n",
2869                     (fr->eeltype == eelSWITCH) ? "switched" : "shifted",
2870                     fr->rvdw_switch, fr->rvdw);
2871         }
2872     }
2873
2874     if (fr->bBHAM && EVDW_PME(fr->vdwtype))
2875     {
2876         gmx_fatal(FARGS, "LJ PME not supported with Buckingham");
2877     }
2878
2879     if (fr->bBHAM && (fr->vdwtype == evdwSHIFT || fr->vdwtype == evdwSWITCH))
2880     {
2881         gmx_fatal(FARGS, "Switch/shift interaction not supported with Buckingham");
2882     }
2883
2884     if (fr->bBHAM && fr->cutoff_scheme == ecutsVERLET)
2885     {
2886         gmx_fatal(FARGS, "Verlet cutoff-scheme is not supported with Buckingham");
2887     }
2888
2889     if (fp)
2890     {
2891         fprintf(fp, "Cut-off's:   NS: %g   Coulomb: %g   %s: %g\n",
2892                 fr->rlist, fr->rcoulomb, fr->bBHAM ? "BHAM" : "LJ", fr->rvdw);
2893     }
2894
2895     fr->eDispCorr = ir->eDispCorr;
2896     fr->numAtomsForDispersionCorrection = mtop->natoms;
2897     if (ir->eDispCorr != edispcNO)
2898     {
2899         set_avcsixtwelve(fp, fr, mtop);
2900     }
2901
2902     if (fr->bBHAM)
2903     {
2904         set_bham_b_max(fp, fr, mtop);
2905     }
2906
2907     fr->gb_epsilon_solvent = ir->gb_epsilon_solvent;
2908
2909     /* Copy the GBSA data (radius, volume and surftens for each
2910      * atomtype) from the topology atomtype section to forcerec.
2911      */
2912     snew(fr->atype_radius, fr->ntype);
2913     snew(fr->atype_vol, fr->ntype);
2914     snew(fr->atype_surftens, fr->ntype);
2915     snew(fr->atype_gb_radius, fr->ntype);
2916     snew(fr->atype_S_hct, fr->ntype);
2917
2918     if (mtop->atomtypes.nr > 0)
2919     {
2920         for (i = 0; i < fr->ntype; i++)
2921         {
2922             fr->atype_radius[i] = mtop->atomtypes.radius[i];
2923         }
2924         for (i = 0; i < fr->ntype; i++)
2925         {
2926             fr->atype_vol[i] = mtop->atomtypes.vol[i];
2927         }
2928         for (i = 0; i < fr->ntype; i++)
2929         {
2930             fr->atype_surftens[i] = mtop->atomtypes.surftens[i];
2931         }
2932         for (i = 0; i < fr->ntype; i++)
2933         {
2934             fr->atype_gb_radius[i] = mtop->atomtypes.gb_radius[i];
2935         }
2936         for (i = 0; i < fr->ntype; i++)
2937         {
2938             fr->atype_S_hct[i] = mtop->atomtypes.S_hct[i];
2939         }
2940     }
2941
2942     /* Generate the GB table if needed */
2943     if (fr->bGB)
2944     {
2945 #if GMX_DOUBLE
2946         fr->gbtabscale = 2000;
2947 #else
2948         fr->gbtabscale = 500;
2949 #endif
2950
2951         fr->gbtabr = 100;
2952         fr->gbtab  = make_gb_table(fr);
2953
2954         init_gb(&fr->born, fr, ir, mtop, ir->gb_algorithm);
2955
2956         /* Copy local gb data (for dd, this is done in dd_partition_system) */
2957         if (!DOMAINDECOMP(cr))
2958         {
2959             make_local_gb(cr, fr->born, ir->gb_algorithm);
2960         }
2961     }
2962
2963     /* Set the charge scaling */
2964     if (fr->epsilon_r != 0)
2965     {
2966         fr->epsfac = ONE_4PI_EPS0/fr->epsilon_r;
2967     }
2968     else
2969     {
2970         /* eps = 0 is infinite dieletric: no coulomb interactions */
2971         fr->epsfac = 0;
2972     }
2973
2974     /* Reaction field constants */
2975     if (EEL_RF(fr->eeltype))
2976     {
2977         calc_rffac(fp, fr->eeltype, fr->epsilon_r, fr->epsilon_rf,
2978                    fr->rcoulomb, fr->temp, fr->zsquare, box,
2979                    &fr->kappa, &fr->k_rf, &fr->c_rf);
2980     }
2981
2982     /*This now calculates sum for q and c6*/
2983     set_chargesum(fp, fr, mtop);
2984
2985     /* Construct tables for the group scheme. A little unnecessary to
2986      * make both vdw and coul tables sometimes, but what the
2987      * heck. Note that both cutoff schemes construct Ewald tables in
2988      * init_interaction_const_tables. */
2989     needGroupSchemeTables = (ir->cutoff_scheme == ecutsGROUP &&
2990                              (fr->bcoultab || fr->bvdwtab));
2991
2992     negp_pp   = ir->opts.ngener - ir->nwall;
2993     negptable = 0;
2994     if (!needGroupSchemeTables)
2995     {
2996         bSomeNormalNbListsAreInUse = TRUE;
2997         fr->nnblists               = 1;
2998     }
2999     else
3000     {
3001         bSomeNormalNbListsAreInUse = FALSE;
3002         for (egi = 0; egi < negp_pp; egi++)
3003         {
3004             for (egj = egi; egj < negp_pp; egj++)
3005             {
3006                 egp_flags = ir->opts.egp_flags[GID(egi, egj, ir->opts.ngener)];
3007                 if (!(egp_flags & EGP_EXCL))
3008                 {
3009                     if (egp_flags & EGP_TABLE)
3010                     {
3011                         negptable++;
3012                     }
3013                     else
3014                     {
3015                         bSomeNormalNbListsAreInUse = TRUE;
3016                     }
3017                 }
3018             }
3019         }
3020         if (bSomeNormalNbListsAreInUse)
3021         {
3022             fr->nnblists = negptable + 1;
3023         }
3024         else
3025         {
3026             fr->nnblists = negptable;
3027         }
3028         if (fr->nnblists > 1)
3029         {
3030             snew(fr->gid2nblists, ir->opts.ngener*ir->opts.ngener);
3031         }
3032     }
3033
3034     snew(fr->nblists, fr->nnblists);
3035
3036     /* This code automatically gives table length tabext without cut-off's,
3037      * in that case grompp should already have checked that we do not need
3038      * normal tables and we only generate tables for 1-4 interactions.
3039      */
3040     rtab = ir->rlist + ir->tabext;
3041
3042     if (needGroupSchemeTables)
3043     {
3044         /* make tables for ordinary interactions */
3045         if (bSomeNormalNbListsAreInUse)
3046         {
3047             make_nbf_tables(fp, fr, rtab, tabfn, NULL, NULL, &fr->nblists[0]);
3048             m = 1;
3049         }
3050         else
3051         {
3052             m = 0;
3053         }
3054         if (negptable > 0)
3055         {
3056             /* Read the special tables for certain energy group pairs */
3057             nm_ind = mtop->groups.grps[egcENER].nm_ind;
3058             for (egi = 0; egi < negp_pp; egi++)
3059             {
3060                 for (egj = egi; egj < negp_pp; egj++)
3061                 {
3062                     egp_flags = ir->opts.egp_flags[GID(egi, egj, ir->opts.ngener)];
3063                     if ((egp_flags & EGP_TABLE) && !(egp_flags & EGP_EXCL))
3064                     {
3065                         if (fr->nnblists > 1)
3066                         {
3067                             fr->gid2nblists[GID(egi, egj, ir->opts.ngener)] = m;
3068                         }
3069                         /* Read the table file with the two energy groups names appended */
3070                         make_nbf_tables(fp, fr, rtab, tabfn,
3071                                         *mtop->groups.grpname[nm_ind[egi]],
3072                                         *mtop->groups.grpname[nm_ind[egj]],
3073                                         &fr->nblists[m]);
3074                         m++;
3075                     }
3076                     else if (fr->nnblists > 1)
3077                     {
3078                         fr->gid2nblists[GID(egi, egj, ir->opts.ngener)] = 0;
3079                     }
3080                 }
3081             }
3082         }
3083     }
3084
3085     /* Tables might not be used for the potential modifier
3086      * interactions per se, but we still need them to evaluate
3087      * switch/shift dispersion corrections in this case. */
3088     if (fr->eDispCorr != edispcNO)
3089     {
3090         fr->dispersionCorrectionTable = makeDispersionCorrectionTable(fp, fr, rtab, tabfn);
3091     }
3092
3093     /* We want to use unmodified tables for 1-4 coulombic
3094      * interactions, so we must in general have an extra set of
3095      * tables. */
3096     if (gmx_mtop_ftype_count(mtop, F_LJ14) > 0 ||
3097         gmx_mtop_ftype_count(mtop, F_LJC14_Q) > 0 ||
3098         gmx_mtop_ftype_count(mtop, F_LJC_PAIRS_NB) > 0)
3099     {
3100         fr->pairsTable = make_tables(fp, fr, tabpfn, rtab,
3101                                      GMX_MAKETABLES_14ONLY);
3102     }
3103
3104     /* Wall stuff */
3105     fr->nwall = ir->nwall;
3106     if (ir->nwall && ir->wall_type == ewtTABLE)
3107     {
3108         make_wall_tables(fp, ir, tabfn, &mtop->groups, fr);
3109     }
3110
3111     if (fcd && tabbfnm)
3112     {
3113         // Need to catch std::bad_alloc
3114         // TODO Don't need to catch this here, when merging with master branch
3115         try
3116         {
3117             fcd->bondtab  = make_bonded_tables(fp,
3118                                                F_TABBONDS, F_TABBONDSNC,
3119                                                mtop, tabbfnm, "b");
3120             fcd->angletab = make_bonded_tables(fp,
3121                                                F_TABANGLES, -1,
3122                                                mtop, tabbfnm, "a");
3123             fcd->dihtab   = make_bonded_tables(fp,
3124                                                F_TABDIHS, -1,
3125                                                mtop, tabbfnm, "d");
3126         }
3127         GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
3128     }
3129     else
3130     {
3131         if (debug)
3132         {
3133             fprintf(debug, "No fcdata or table file name passed, can not read table, can not do bonded interactions\n");
3134         }
3135     }
3136
3137     /* QM/MM initialization if requested
3138      */
3139     if (ir->bQMMM)
3140     {
3141         fprintf(stderr, "QM/MM calculation requested.\n");
3142     }
3143
3144     fr->bQMMM      = ir->bQMMM;
3145     fr->qr         = mk_QMMMrec();
3146
3147     /* Set all the static charge group info */
3148     fr->cginfo_mb = init_cginfo_mb(fp, mtop, fr, bNoSolvOpt,
3149                                    &bFEP_NonBonded,
3150                                    &fr->bExcl_IntraCGAll_InterCGNone);
3151     if (DOMAINDECOMP(cr))
3152     {
3153         fr->cginfo = NULL;
3154     }
3155     else
3156     {
3157         fr->cginfo = cginfo_expand(mtop->nmolblock, fr->cginfo_mb);
3158     }
3159
3160     if (!DOMAINDECOMP(cr))
3161     {
3162         forcerec_set_ranges(fr, ncg_mtop(mtop), ncg_mtop(mtop),
3163                             mtop->natoms, mtop->natoms, mtop->natoms);
3164     }
3165
3166     fr->print_force = print_force;
3167
3168
3169     /* coarse load balancing vars */
3170     fr->t_fnbf    = 0.;
3171     fr->t_wait    = 0.;
3172     fr->timesteps = 0;
3173
3174     /* Initialize neighbor search */
3175     snew(fr->ns, 1);
3176     init_ns(fp, cr, fr->ns, fr, mtop);
3177
3178     if (cr->duty & DUTY_PP)
3179     {
3180         gmx_nonbonded_setup(fr, bGenericKernelOnly);
3181     }
3182
3183     /* Initialize the thread working data for bonded interactions */
3184     init_bonded_threading(fp, mtop->groups.grps[egcENER].nr,
3185                           &fr->bonded_threading);
3186
3187     fr->nthread_ewc = gmx_omp_nthreads_get(emntBonded);
3188     snew(fr->ewc_t, fr->nthread_ewc);
3189
3190     /* fr->ic is used both by verlet and group kernels (to some extent) now */
3191     init_interaction_const(fp, &fr->ic, fr);
3192     init_interaction_const_tables(fp, fr->ic, rtab);
3193
3194     if (fr->cutoff_scheme == ecutsVERLET)
3195     {
3196         // We checked the cut-offs in grompp, but double-check here.
3197         // We have PME+LJcutoff kernels for rcoulomb>rvdw.
3198         if (EEL_PME_EWALD(ir->coulombtype) && ir->vdwtype == eelCUT)
3199         {
3200             GMX_RELEASE_ASSERT(ir->rcoulomb >= ir->rvdw, "With Verlet lists and PME we should have rcoulomb>=rvdw");
3201         }
3202         else
3203         {
3204             GMX_RELEASE_ASSERT(ir->rcoulomb == ir->rvdw, "With Verlet lists and no PME rcoulomb and rvdw should be identical");
3205         }
3206
3207         init_nb_verlet(fp, &fr->nbv, bFEP_NonBonded, ir, fr, cr, nbpu_opt);
3208     }
3209
3210     if (ir->eDispCorr != edispcNO)
3211     {
3212         calc_enervirdiff(fp, ir->eDispCorr, fr);
3213     }
3214 }
3215
3216 #define pr_real(fp, r) fprintf(fp, "%s: %e\n",#r, r)
3217 #define pr_int(fp, i)  fprintf((fp), "%s: %d\n",#i, i)
3218 #define pr_bool(fp, b) fprintf((fp), "%s: %s\n",#b, gmx::boolToString(b))
3219
3220 void pr_forcerec(FILE *fp, t_forcerec *fr)
3221 {
3222     int i;
3223
3224     pr_real(fp, fr->rlist);
3225     pr_real(fp, fr->rcoulomb);
3226     pr_real(fp, fr->fudgeQQ);
3227     pr_bool(fp, fr->bGrid);
3228     /*pr_int(fp,fr->cg0);
3229        pr_int(fp,fr->hcg);*/
3230     for (i = 0; i < fr->nnblists; i++)
3231     {
3232         pr_int(fp, fr->nblists[i].table_elec_vdw->n);
3233     }
3234     pr_real(fp, fr->rcoulomb_switch);
3235     pr_real(fp, fr->rcoulomb);
3236
3237     fflush(fp);
3238 }
3239
3240 /* Frees GPU memory and destroys the GPU context.
3241  *
3242  * Note that this function needs to be called even if GPUs are not used
3243  * in this run because the PME ranks have no knowledge of whether GPUs
3244  * are used or not, but all ranks need to enter the barrier below.
3245  */
3246 void free_gpu_resources(const t_forcerec     *fr,
3247                         const t_commrec      *cr,
3248                         const gmx_gpu_info_t *gpu_info,
3249                         const gmx_gpu_opt_t  *gpu_opt)
3250 {
3251     gmx_bool bIsPPrankUsingGPU;
3252     char     gpu_err_str[STRLEN];
3253
3254     bIsPPrankUsingGPU = (cr->duty & DUTY_PP) && fr && fr->nbv && fr->nbv->bUseGPU;
3255
3256     if (bIsPPrankUsingGPU)
3257     {
3258         /* free nbnxn data in GPU memory */
3259         nbnxn_gpu_free(fr->nbv->gpu_nbv);
3260         /* stop the GPU profiler (only CUDA) */
3261         stopGpuProfiler();
3262
3263         /* With tMPI we need to wait for all ranks to finish deallocation before
3264          * destroying the CUDA context in free_gpu() as some tMPI ranks may be sharing
3265          * GPU and context.
3266          *
3267          * This is not a concern in OpenCL where we use one context per rank which
3268          * is freed in nbnxn_gpu_free().
3269          *
3270          * Note: as only PP ranks need to free GPU resources, so it is safe to
3271          * not call the barrier on PME ranks.
3272          */
3273 #if GMX_THREAD_MPI
3274         if (PAR(cr))
3275         {
3276             gmx_barrier(cr);
3277         }
3278 #endif  /* GMX_THREAD_MPI */
3279
3280         /* uninitialize GPU (by destroying the context) */
3281         if (!free_cuda_gpu(cr->rank_pp_intranode, gpu_err_str, gpu_info, gpu_opt))
3282         {
3283             gmx_warning("On rank %d failed to free GPU #%d: %s",
3284                         cr->nodeid, get_current_cuda_gpu_device_id(), gpu_err_str);
3285         }
3286     }
3287 }