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