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