Remove typedef struct in some mdtypes files
[alexxy/gromacs.git] / src / gromacs / mdlib / sim_util.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014,2015,2016,2017, by the GROMACS development team, led by
7  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8  * and including many others, as listed in the AUTHORS file in the
9  * top-level source directory and at http://www.gromacs.org.
10  *
11  * GROMACS is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the License, or (at your option) any later version.
15  *
16  * GROMACS is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with GROMACS; if not, see
23  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
25  *
26  * If you want to redistribute modifications to GROMACS, please
27  * consider that scientific software is very special. Version
28  * control is crucial - bugs must be traceable. We will be happy to
29  * consider code for inclusion in the official distribution, but
30  * derived work must not be called official GROMACS. Details are found
31  * in the README & COPYING files - if they are missing, get the
32  * official version at http://www.gromacs.org.
33  *
34  * To help us fund GROMACS development, we humbly ask that you cite
35  * the research papers on the package. Check out http://www.gromacs.org.
36  */
37 #include "gmxpre.h"
38
39 #include "sim_util.h"
40
41 #include "config.h"
42
43 #include <assert.h>
44 #include <math.h>
45 #include <stdio.h>
46 #include <string.h>
47
48 #include <cstdint>
49
50 #include <array>
51
52 #include "gromacs/domdec/domdec.h"
53 #include "gromacs/domdec/domdec_struct.h"
54 #include "gromacs/essentialdynamics/edsam.h"
55 #include "gromacs/ewald/pme.h"
56 #include "gromacs/gmxlib/chargegroup.h"
57 #include "gromacs/gmxlib/network.h"
58 #include "gromacs/gmxlib/nrnb.h"
59 #include "gromacs/gmxlib/nonbonded/nb_free_energy.h"
60 #include "gromacs/gmxlib/nonbonded/nb_kernel.h"
61 #include "gromacs/gmxlib/nonbonded/nonbonded.h"
62 #include "gromacs/imd/imd.h"
63 #include "gromacs/listed-forces/bonded.h"
64 #include "gromacs/listed-forces/disre.h"
65 #include "gromacs/listed-forces/orires.h"
66 #include "gromacs/math/functions.h"
67 #include "gromacs/math/units.h"
68 #include "gromacs/math/vec.h"
69 #include "gromacs/math/vecdump.h"
70 #include "gromacs/mdlib/calcmu.h"
71 #include "gromacs/mdlib/constr.h"
72 #include "gromacs/mdlib/force.h"
73 #include "gromacs/mdlib/forcerec.h"
74 #include "gromacs/mdlib/genborn.h"
75 #include "gromacs/mdlib/gmx_omp_nthreads.h"
76 #include "gromacs/mdlib/mdrun.h"
77 #include "gromacs/mdlib/nb_verlet.h"
78 #include "gromacs/mdlib/nbnxn_atomdata.h"
79 #include "gromacs/mdlib/nbnxn_gpu_data_mgmt.h"
80 #include "gromacs/mdlib/nbnxn_grid.h"
81 #include "gromacs/mdlib/nbnxn_search.h"
82 #include "gromacs/mdlib/qmmm.h"
83 #include "gromacs/mdlib/update.h"
84 #include "gromacs/mdlib/nbnxn_kernels/nbnxn_kernel_gpu_ref.h"
85 #include "gromacs/mdlib/nbnxn_kernels/nbnxn_kernel_ref.h"
86 #include "gromacs/mdlib/nbnxn_kernels/simd_2xnn/nbnxn_kernel_simd_2xnn.h"
87 #include "gromacs/mdlib/nbnxn_kernels/simd_4xn/nbnxn_kernel_simd_4xn.h"
88 #include "gromacs/mdtypes/commrec.h"
89 #include "gromacs/mdtypes/inputrec.h"
90 #include "gromacs/mdtypes/md_enums.h"
91 #include "gromacs/mdtypes/state.h"
92 #include "gromacs/pbcutil/ishift.h"
93 #include "gromacs/pbcutil/mshift.h"
94 #include "gromacs/pbcutil/pbc.h"
95 #include "gromacs/pulling/pull.h"
96 #include "gromacs/pulling/pull_rotation.h"
97 #include "gromacs/timing/cyclecounter.h"
98 #include "gromacs/timing/gpu_timing.h"
99 #include "gromacs/timing/wallcycle.h"
100 #include "gromacs/timing/wallcyclereporting.h"
101 #include "gromacs/timing/walltime_accounting.h"
102 #include "gromacs/utility/arrayref.h"
103 #include "gromacs/utility/basedefinitions.h"
104 #include "gromacs/utility/cstringutil.h"
105 #include "gromacs/utility/exceptions.h"
106 #include "gromacs/utility/fatalerror.h"
107 #include "gromacs/utility/gmxassert.h"
108 #include "gromacs/utility/gmxmpi.h"
109 #include "gromacs/utility/pleasecite.h"
110 #include "gromacs/utility/smalloc.h"
111 #include "gromacs/utility/sysinfo.h"
112
113 #include "nbnxn_gpu.h"
114
115 void print_time(FILE                     *out,
116                 gmx_walltime_accounting_t walltime_accounting,
117                 gmx_int64_t               step,
118                 t_inputrec               *ir,
119                 t_commrec gmx_unused     *cr)
120 {
121     time_t finish;
122     char   timebuf[STRLEN];
123     double dt, elapsed_seconds, time_per_step;
124     char   buf[48];
125
126 #if !GMX_THREAD_MPI
127     if (!PAR(cr))
128 #endif
129     {
130         fprintf(out, "\r");
131     }
132     fprintf(out, "step %s", gmx_step_str(step, buf));
133     fflush(out);
134
135     if ((step >= ir->nstlist))
136     {
137         double seconds_since_epoch = gmx_gettime();
138         elapsed_seconds = seconds_since_epoch - walltime_accounting_get_start_time_stamp(walltime_accounting);
139         time_per_step   = elapsed_seconds/(step - ir->init_step + 1);
140         dt              = (ir->nsteps + ir->init_step - step) * time_per_step;
141
142         if (ir->nsteps >= 0)
143         {
144             if (dt >= 300)
145             {
146                 finish = (time_t) (seconds_since_epoch + dt);
147                 gmx_ctime_r(&finish, timebuf, STRLEN);
148                 sprintf(buf, "%s", timebuf);
149                 buf[strlen(buf)-1] = '\0';
150                 fprintf(out, ", will finish %s", buf);
151             }
152             else
153             {
154                 fprintf(out, ", remaining wall clock time: %5d s          ", (int)dt);
155             }
156         }
157         else
158         {
159             fprintf(out, " performance: %.1f ns/day    ",
160                     ir->delta_t/1000*24*60*60/time_per_step);
161         }
162     }
163 #if !GMX_THREAD_MPI
164     if (PAR(cr))
165     {
166         fprintf(out, "\n");
167     }
168 #endif
169
170     fflush(out);
171 }
172
173 void print_date_and_time(FILE *fplog, int nodeid, const char *title,
174                          double the_time)
175 {
176     char   time_string[STRLEN];
177
178     if (!fplog)
179     {
180         return;
181     }
182
183     {
184         int    i;
185         char   timebuf[STRLEN];
186         time_t temp_time = (time_t) the_time;
187
188         gmx_ctime_r(&temp_time, timebuf, STRLEN);
189         for (i = 0; timebuf[i] >= ' '; i++)
190         {
191             time_string[i] = timebuf[i];
192         }
193         time_string[i] = '\0';
194     }
195
196     fprintf(fplog, "%s on rank %d %s\n", title, nodeid, time_string);
197 }
198
199 void print_start(FILE *fplog, t_commrec *cr,
200                  gmx_walltime_accounting_t walltime_accounting,
201                  const char *name)
202 {
203     char buf[STRLEN];
204
205     sprintf(buf, "Started %s", name);
206     print_date_and_time(fplog, cr->nodeid, buf,
207                         walltime_accounting_get_start_time_stamp(walltime_accounting));
208 }
209
210 static void sum_forces(rvec f[], const PaddedRVecVector *forceToAdd)
211 {
212     /* TODO: remove this - 1 when padding is properly implemented */
213     int         end  = forceToAdd->size() - 1;
214     const rvec *fAdd = as_rvec_array(forceToAdd->data());
215
216     // cppcheck-suppress unreadVariable
217     int gmx_unused nt = gmx_omp_nthreads_get(emntDefault);
218 #pragma omp parallel for num_threads(nt) schedule(static)
219     for (int i = 0; i < end; i++)
220     {
221         rvec_inc(f[i], fAdd[i]);
222     }
223 }
224
225 static void calc_virial(int start, int homenr, rvec x[], rvec f[],
226                         tensor vir_part, t_graph *graph, matrix box,
227                         t_nrnb *nrnb, const t_forcerec *fr, int ePBC)
228 {
229     int    i;
230
231     /* The short-range virial from surrounding boxes */
232     clear_mat(vir_part);
233     calc_vir(SHIFTS, fr->shift_vec, fr->fshift, vir_part, ePBC == epbcSCREW, box);
234     inc_nrnb(nrnb, eNR_VIRIAL, SHIFTS);
235
236     /* Calculate partial virial, for local atoms only, based on short range.
237      * Total virial is computed in global_stat, called from do_md
238      */
239     f_calc_vir(start, start+homenr, x, f, vir_part, graph, box);
240     inc_nrnb(nrnb, eNR_VIRIAL, homenr);
241
242     /* Add position restraint contribution */
243     for (i = 0; i < DIM; i++)
244     {
245         vir_part[i][i] += fr->vir_diag_posres[i];
246     }
247
248     /* Add wall contribution */
249     for (i = 0; i < DIM; i++)
250     {
251         vir_part[i][ZZ] += fr->vir_wall_z[i];
252     }
253
254     if (debug)
255     {
256         pr_rvecs(debug, 0, "vir_part", vir_part, DIM);
257     }
258 }
259
260 static void pull_potential_wrapper(t_commrec *cr,
261                                    t_inputrec *ir,
262                                    matrix box, rvec x[],
263                                    rvec f[],
264                                    tensor vir_force,
265                                    t_mdatoms *mdatoms,
266                                    gmx_enerdata_t *enerd,
267                                    real *lambda,
268                                    double t,
269                                    gmx_wallcycle_t wcycle)
270 {
271     t_pbc  pbc;
272     real   dvdl;
273
274     /* Calculate the center of mass forces, this requires communication,
275      * which is why pull_potential is called close to other communication.
276      * The virial contribution is calculated directly,
277      * which is why we call pull_potential after calc_virial.
278      */
279     wallcycle_start(wcycle, ewcPULLPOT);
280     set_pbc(&pbc, ir->ePBC, box);
281     dvdl                     = 0;
282     enerd->term[F_COM_PULL] +=
283         pull_potential(ir->pull_work, mdatoms, &pbc,
284                        cr, t, lambda[efptRESTRAINT], x, f, vir_force, &dvdl);
285     enerd->dvdl_lin[efptRESTRAINT] += dvdl;
286     wallcycle_stop(wcycle, ewcPULLPOT);
287 }
288
289 static void pme_receive_force_ener(t_commrec      *cr,
290                                    gmx_wallcycle_t wcycle,
291                                    gmx_enerdata_t *enerd,
292                                    t_forcerec     *fr)
293 {
294     real   e_q, e_lj, dvdl_q, dvdl_lj;
295     float  cycles_ppdpme, cycles_seppme;
296
297     cycles_ppdpme = wallcycle_stop(wcycle, ewcPPDURINGPME);
298     dd_cycles_add(cr->dd, cycles_ppdpme, ddCyclPPduringPME);
299
300     /* In case of node-splitting, the PP nodes receive the long-range
301      * forces, virial and energy from the PME nodes here.
302      */
303     wallcycle_start(wcycle, ewcPP_PMEWAITRECVF);
304     dvdl_q  = 0;
305     dvdl_lj = 0;
306     gmx_pme_receive_f(cr, as_rvec_array(fr->f_novirsum->data()), fr->vir_el_recip, &e_q,
307                       fr->vir_lj_recip, &e_lj, &dvdl_q, &dvdl_lj,
308                       &cycles_seppme);
309     enerd->term[F_COUL_RECIP] += e_q;
310     enerd->term[F_LJ_RECIP]   += e_lj;
311     enerd->dvdl_lin[efptCOUL] += dvdl_q;
312     enerd->dvdl_lin[efptVDW]  += dvdl_lj;
313
314     if (wcycle)
315     {
316         dd_cycles_add(cr->dd, cycles_seppme, ddCyclPME);
317     }
318     wallcycle_stop(wcycle, ewcPP_PMEWAITRECVF);
319 }
320
321 static void print_large_forces(FILE *fp, t_mdatoms *md, t_commrec *cr,
322                                gmx_int64_t step, real forceTolerance,
323                                const rvec *x, const rvec *f)
324 {
325     real           force2Tolerance = gmx::square(forceTolerance);
326     std::uintmax_t numNonFinite    = 0;
327     for (int i = 0; i < md->homenr; i++)
328     {
329         real force2    = norm2(f[i]);
330         bool nonFinite = !std::isfinite(force2);
331         if (force2 >= force2Tolerance || nonFinite)
332         {
333             fprintf(fp, "step %" GMX_PRId64 " atom %6d  x %8.3f %8.3f %8.3f  force %12.5e\n",
334                     step,
335                     ddglatnr(cr->dd, i), x[i][XX], x[i][YY], x[i][ZZ], std::sqrt(force2));
336         }
337         if (nonFinite)
338         {
339             numNonFinite++;
340         }
341     }
342     if (numNonFinite > 0)
343     {
344         /* Note that with MPI this fatal call on one rank might interrupt
345          * the printing on other ranks. But we can only avoid that with
346          * an expensive MPI barrier that we would need at each step.
347          */
348         gmx_fatal(FARGS, "At step %" GMX_PRId64 " detected non-finite forces on %ju atoms", step, numNonFinite);
349     }
350 }
351
352 static void post_process_forces(t_commrec *cr,
353                                 gmx_int64_t step,
354                                 t_nrnb *nrnb, gmx_wallcycle_t wcycle,
355                                 gmx_localtop_t *top,
356                                 matrix box, rvec x[],
357                                 rvec f[],
358                                 tensor vir_force,
359                                 t_mdatoms *mdatoms,
360                                 t_graph *graph,
361                                 t_forcerec *fr, gmx_vsite_t *vsite,
362                                 int flags)
363 {
364     if (fr->bF_NoVirSum)
365     {
366         if (vsite)
367         {
368             /* Spread the mesh force on virtual sites to the other particles...
369              * This is parallellized. MPI communication is performed
370              * if the constructing atoms aren't local.
371              */
372             wallcycle_start(wcycle, ewcVSITESPREAD);
373             spread_vsite_f(vsite, x, as_rvec_array(fr->f_novirsum->data()), nullptr,
374                            (flags & GMX_FORCE_VIRIAL), fr->vir_el_recip,
375                            nrnb,
376                            &top->idef, fr->ePBC, fr->bMolPBC, graph, box, cr);
377             wallcycle_stop(wcycle, ewcVSITESPREAD);
378         }
379         if (flags & GMX_FORCE_VIRIAL)
380         {
381             /* Now add the forces, this is local */
382             sum_forces(f, fr->f_novirsum);
383
384             if (EEL_FULL(fr->eeltype))
385             {
386                 /* Add the mesh contribution to the virial */
387                 m_add(vir_force, fr->vir_el_recip, vir_force);
388             }
389             if (EVDW_PME(fr->vdwtype))
390             {
391                 /* Add the mesh contribution to the virial */
392                 m_add(vir_force, fr->vir_lj_recip, vir_force);
393             }
394             if (debug)
395             {
396                 pr_rvecs(debug, 0, "vir_force", vir_force, DIM);
397             }
398         }
399     }
400
401     if (fr->print_force >= 0)
402     {
403         print_large_forces(stderr, mdatoms, cr, step, fr->print_force, x, f);
404     }
405 }
406
407 static void do_nb_verlet(t_forcerec *fr,
408                          interaction_const_t *ic,
409                          gmx_enerdata_t *enerd,
410                          int flags, int ilocality,
411                          int clearF,
412                          t_nrnb *nrnb,
413                          gmx_wallcycle_t wcycle)
414 {
415     int                        enr_nbnxn_kernel_ljc, enr_nbnxn_kernel_lj;
416     nonbonded_verlet_group_t  *nbvg;
417     gmx_bool                   bUsingGpuKernels;
418
419     if (!(flags & GMX_FORCE_NONBONDED))
420     {
421         /* skip non-bonded calculation */
422         return;
423     }
424
425     nbvg = &fr->nbv->grp[ilocality];
426
427     /* GPU kernel launch overhead is already timed separately */
428     if (fr->cutoff_scheme != ecutsVERLET)
429     {
430         gmx_incons("Invalid cut-off scheme passed!");
431     }
432
433     bUsingGpuKernels = (nbvg->kernel_type == nbnxnk8x8x8_GPU);
434
435     if (!bUsingGpuKernels)
436     {
437         wallcycle_sub_start(wcycle, ewcsNONBONDED);
438     }
439     switch (nbvg->kernel_type)
440     {
441         case nbnxnk4x4_PlainC:
442             nbnxn_kernel_ref(&nbvg->nbl_lists,
443                              nbvg->nbat, ic,
444                              fr->shift_vec,
445                              flags,
446                              clearF,
447                              fr->fshift[0],
448                              enerd->grpp.ener[egCOULSR],
449                              fr->bBHAM ?
450                              enerd->grpp.ener[egBHAMSR] :
451                              enerd->grpp.ener[egLJSR]);
452             break;
453
454         case nbnxnk4xN_SIMD_4xN:
455             nbnxn_kernel_simd_4xn(&nbvg->nbl_lists,
456                                   nbvg->nbat, ic,
457                                   nbvg->ewald_excl,
458                                   fr->shift_vec,
459                                   flags,
460                                   clearF,
461                                   fr->fshift[0],
462                                   enerd->grpp.ener[egCOULSR],
463                                   fr->bBHAM ?
464                                   enerd->grpp.ener[egBHAMSR] :
465                                   enerd->grpp.ener[egLJSR]);
466             break;
467         case nbnxnk4xN_SIMD_2xNN:
468             nbnxn_kernel_simd_2xnn(&nbvg->nbl_lists,
469                                    nbvg->nbat, ic,
470                                    nbvg->ewald_excl,
471                                    fr->shift_vec,
472                                    flags,
473                                    clearF,
474                                    fr->fshift[0],
475                                    enerd->grpp.ener[egCOULSR],
476                                    fr->bBHAM ?
477                                    enerd->grpp.ener[egBHAMSR] :
478                                    enerd->grpp.ener[egLJSR]);
479             break;
480
481         case nbnxnk8x8x8_GPU:
482             nbnxn_gpu_launch_kernel(fr->nbv->gpu_nbv, nbvg->nbat, flags, ilocality);
483             break;
484
485         case nbnxnk8x8x8_PlainC:
486             nbnxn_kernel_gpu_ref(nbvg->nbl_lists.nbl[0],
487                                  nbvg->nbat, ic,
488                                  fr->shift_vec,
489                                  flags,
490                                  clearF,
491                                  nbvg->nbat->out[0].f,
492                                  fr->fshift[0],
493                                  enerd->grpp.ener[egCOULSR],
494                                  fr->bBHAM ?
495                                  enerd->grpp.ener[egBHAMSR] :
496                                  enerd->grpp.ener[egLJSR]);
497             break;
498
499         default:
500             gmx_incons("Invalid nonbonded kernel type passed!");
501
502     }
503     if (!bUsingGpuKernels)
504     {
505         wallcycle_sub_stop(wcycle, ewcsNONBONDED);
506     }
507
508     if (EEL_RF(ic->eeltype) || ic->eeltype == eelCUT)
509     {
510         enr_nbnxn_kernel_ljc = eNR_NBNXN_LJ_RF;
511     }
512     else if ((!bUsingGpuKernels && nbvg->ewald_excl == ewaldexclAnalytical) ||
513              (bUsingGpuKernels && nbnxn_gpu_is_kernel_ewald_analytical(fr->nbv->gpu_nbv)))
514     {
515         enr_nbnxn_kernel_ljc = eNR_NBNXN_LJ_EWALD;
516     }
517     else
518     {
519         enr_nbnxn_kernel_ljc = eNR_NBNXN_LJ_TAB;
520     }
521     enr_nbnxn_kernel_lj = eNR_NBNXN_LJ;
522     if (flags & GMX_FORCE_ENERGY)
523     {
524         /* In eNR_??? the nbnxn F+E kernels are always the F kernel + 1 */
525         enr_nbnxn_kernel_ljc += 1;
526         enr_nbnxn_kernel_lj  += 1;
527     }
528
529     inc_nrnb(nrnb, enr_nbnxn_kernel_ljc,
530              nbvg->nbl_lists.natpair_ljq);
531     inc_nrnb(nrnb, enr_nbnxn_kernel_lj,
532              nbvg->nbl_lists.natpair_lj);
533     /* The Coulomb-only kernels are offset -eNR_NBNXN_LJ_RF+eNR_NBNXN_RF */
534     inc_nrnb(nrnb, enr_nbnxn_kernel_ljc-eNR_NBNXN_LJ_RF+eNR_NBNXN_RF,
535              nbvg->nbl_lists.natpair_q);
536
537     if (ic->vdw_modifier == eintmodFORCESWITCH)
538     {
539         /* We add up the switch cost separately */
540         inc_nrnb(nrnb, eNR_NBNXN_ADD_LJ_FSW+((flags & GMX_FORCE_ENERGY) ? 1 : 0),
541                  nbvg->nbl_lists.natpair_ljq + nbvg->nbl_lists.natpair_lj);
542     }
543     if (ic->vdw_modifier == eintmodPOTSWITCH)
544     {
545         /* We add up the switch cost separately */
546         inc_nrnb(nrnb, eNR_NBNXN_ADD_LJ_PSW+((flags & GMX_FORCE_ENERGY) ? 1 : 0),
547                  nbvg->nbl_lists.natpair_ljq + nbvg->nbl_lists.natpair_lj);
548     }
549     if (ic->vdwtype == evdwPME)
550     {
551         /* We add up the LJ Ewald cost separately */
552         inc_nrnb(nrnb, eNR_NBNXN_ADD_LJ_EWALD+((flags & GMX_FORCE_ENERGY) ? 1 : 0),
553                  nbvg->nbl_lists.natpair_ljq + nbvg->nbl_lists.natpair_lj);
554     }
555 }
556
557 static void do_nb_verlet_fep(nbnxn_pairlist_set_t *nbl_lists,
558                              t_forcerec           *fr,
559                              rvec                  x[],
560                              rvec                  f[],
561                              t_mdatoms            *mdatoms,
562                              t_lambda             *fepvals,
563                              real                 *lambda,
564                              gmx_enerdata_t       *enerd,
565                              int                   flags,
566                              t_nrnb               *nrnb,
567                              gmx_wallcycle_t       wcycle)
568 {
569     int              donb_flags;
570     nb_kernel_data_t kernel_data;
571     real             lam_i[efptNR];
572     real             dvdl_nb[efptNR];
573     int              th;
574     int              i, j;
575
576     donb_flags = 0;
577     /* Add short-range interactions */
578     donb_flags |= GMX_NONBONDED_DO_SR;
579
580     /* Currently all group scheme kernels always calculate (shift-)forces */
581     if (flags & GMX_FORCE_FORCES)
582     {
583         donb_flags |= GMX_NONBONDED_DO_FORCE;
584     }
585     if (flags & GMX_FORCE_VIRIAL)
586     {
587         donb_flags |= GMX_NONBONDED_DO_SHIFTFORCE;
588     }
589     if (flags & GMX_FORCE_ENERGY)
590     {
591         donb_flags |= GMX_NONBONDED_DO_POTENTIAL;
592     }
593
594     kernel_data.flags  = donb_flags;
595     kernel_data.lambda = lambda;
596     kernel_data.dvdl   = dvdl_nb;
597
598     kernel_data.energygrp_elec = enerd->grpp.ener[egCOULSR];
599     kernel_data.energygrp_vdw  = enerd->grpp.ener[egLJSR];
600
601     /* reset free energy components */
602     for (i = 0; i < efptNR; i++)
603     {
604         dvdl_nb[i]  = 0;
605     }
606
607     assert(gmx_omp_nthreads_get(emntNonbonded) == nbl_lists->nnbl);
608
609     wallcycle_sub_start(wcycle, ewcsNONBONDED);
610 #pragma omp parallel for schedule(static) num_threads(nbl_lists->nnbl)
611     for (th = 0; th < nbl_lists->nnbl; th++)
612     {
613         try
614         {
615             gmx_nb_free_energy_kernel(nbl_lists->nbl_fep[th],
616                                       x, f, fr, mdatoms, &kernel_data, nrnb);
617         }
618         GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
619     }
620
621     if (fepvals->sc_alpha != 0)
622     {
623         enerd->dvdl_nonlin[efptVDW]  += dvdl_nb[efptVDW];
624         enerd->dvdl_nonlin[efptCOUL] += dvdl_nb[efptCOUL];
625     }
626     else
627     {
628         enerd->dvdl_lin[efptVDW]  += dvdl_nb[efptVDW];
629         enerd->dvdl_lin[efptCOUL] += dvdl_nb[efptCOUL];
630     }
631
632     /* If we do foreign lambda and we have soft-core interactions
633      * we have to recalculate the (non-linear) energies contributions.
634      */
635     if (fepvals->n_lambda > 0 && (flags & GMX_FORCE_DHDL) && fepvals->sc_alpha != 0)
636     {
637         kernel_data.flags          = (donb_flags & ~(GMX_NONBONDED_DO_FORCE | GMX_NONBONDED_DO_SHIFTFORCE)) | GMX_NONBONDED_DO_FOREIGNLAMBDA;
638         kernel_data.lambda         = lam_i;
639         kernel_data.energygrp_elec = enerd->foreign_grpp.ener[egCOULSR];
640         kernel_data.energygrp_vdw  = enerd->foreign_grpp.ener[egLJSR];
641         /* Note that we add to kernel_data.dvdl, but ignore the result */
642
643         for (i = 0; i < enerd->n_lambda; i++)
644         {
645             for (j = 0; j < efptNR; j++)
646             {
647                 lam_i[j] = (i == 0 ? lambda[j] : fepvals->all_lambda[j][i-1]);
648             }
649             reset_foreign_enerdata(enerd);
650 #pragma omp parallel for schedule(static) num_threads(nbl_lists->nnbl)
651             for (th = 0; th < nbl_lists->nnbl; th++)
652             {
653                 try
654                 {
655                     gmx_nb_free_energy_kernel(nbl_lists->nbl_fep[th],
656                                               x, f, fr, mdatoms, &kernel_data, nrnb);
657                 }
658                 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
659             }
660
661             sum_epot(&(enerd->foreign_grpp), enerd->foreign_term);
662             enerd->enerpart_lambda[i] += enerd->foreign_term[F_EPOT];
663         }
664     }
665
666     wallcycle_sub_stop(wcycle, ewcsNONBONDED);
667 }
668
669 gmx_bool use_GPU(const nonbonded_verlet_t *nbv)
670 {
671     return nbv != nullptr && nbv->bUseGPU;
672 }
673
674 static gmx_inline void clear_rvecs_omp(int n, rvec v[])
675 {
676     int nth = gmx_omp_nthreads_get_simple_rvec_task(emntDefault, n);
677
678     /* Note that we would like to avoid this conditional by putting it
679      * into the omp pragma instead, but then we still take the full
680      * omp parallel for overhead (at least with gcc5).
681      */
682     if (nth == 1)
683     {
684         for (int i = 0; i < n; i++)
685         {
686             clear_rvec(v[i]);
687         }
688     }
689     else
690     {
691 #pragma omp parallel for num_threads(nth) schedule(static)
692         for (int i = 0; i < n; i++)
693         {
694             clear_rvec(v[i]);
695         }
696     }
697 }
698
699 /*! \brief  This routine checks if the potential energy is finite.
700  *
701  * Note that passing this check does not guarantee finite forces,
702  * since those use slightly different arithmetics. But in most cases
703  * there is just a narrow coordinate range where forces are not finite
704  * and energies are finite.
705  *
706  * \param[in] enerd  The energy data; the non-bonded group energies need to be added in here before calling this routine
707  */
708 static void checkPotentialEnergyValidity(const gmx_enerdata_t *enerd)
709 {
710     if (!std::isfinite(enerd->term[F_EPOT]))
711     {
712         gmx_fatal(FARGS, "The total potential energy is %g, which is not finite. The LJ and electrostatic contributions to the energy are %g and %g, respectively. A non-finite potential energy can be caused by overlapping interactions in bonded interactions or very large or NaN coordinate values. Usually this is caused by a badly or non-equilibrated initial configuration or incorrect interactions or parameters in the topology.",
713                   enerd->term[F_EPOT],
714                   enerd->term[F_LJ],
715                   enerd->term[F_COUL_SR]);
716     }
717 }
718
719 void do_force_cutsVERLET(FILE *fplog, t_commrec *cr,
720                          t_inputrec *inputrec,
721                          gmx_int64_t step, t_nrnb *nrnb, gmx_wallcycle_t wcycle,
722                          gmx_localtop_t *top,
723                          gmx_groups_t gmx_unused *groups,
724                          matrix box, rvec x[], history_t *hist,
725                          PaddedRVecVector *force,
726                          tensor vir_force,
727                          t_mdatoms *mdatoms,
728                          gmx_enerdata_t *enerd, t_fcdata *fcd,
729                          real *lambda, t_graph *graph,
730                          t_forcerec *fr, interaction_const_t *ic,
731                          gmx_vsite_t *vsite, rvec mu_tot,
732                          double t, gmx_edsam_t ed,
733                          gmx_bool bBornRadii,
734                          int flags)
735 {
736     int                 cg1, i, j;
737     double              mu[2*DIM];
738     gmx_bool            bStateChanged, bNS, bFillGrid, bCalcCGCM;
739     gmx_bool            bDoForces, bUseGPU, bUseOrEmulGPU;
740     gmx_bool            bDiffKernels = FALSE;
741     rvec                vzero, box_diag;
742     float               cycles_pme, cycles_force, cycles_wait_gpu;
743     /* TODO To avoid loss of precision, float can't be used for a
744      * cycle count. Build an object that can do this right and perhaps
745      * also be used by gmx_wallcycle_t */
746     gmx_cycles_t        cycleCountBeforeLocalWorkCompletes = 0;
747     nonbonded_verlet_t *nbv;
748
749     cycles_force    = 0;
750     cycles_wait_gpu = 0;
751     nbv             = fr->nbv;
752
753     const int start  = 0;
754     const int homenr = mdatoms->homenr;
755
756     clear_mat(vir_force);
757
758     if (DOMAINDECOMP(cr))
759     {
760         cg1 = cr->dd->ncg_tot;
761     }
762     else
763     {
764         cg1 = top->cgs.nr;
765     }
766     if (fr->n_tpi > 0)
767     {
768         cg1--;
769     }
770
771     bStateChanged = (flags & GMX_FORCE_STATECHANGED);
772     bNS           = (flags & GMX_FORCE_NS) && (fr->bAllvsAll == FALSE);
773     bFillGrid     = (bNS && bStateChanged);
774     bCalcCGCM     = (bFillGrid && !DOMAINDECOMP(cr));
775     bDoForces     = (flags & GMX_FORCE_FORCES);
776     bUseGPU       = fr->nbv->bUseGPU;
777     bUseOrEmulGPU = bUseGPU || (nbv->grp[0].kernel_type == nbnxnk8x8x8_PlainC);
778
779     if (bStateChanged)
780     {
781         update_forcerec(fr, box);
782
783         if (inputrecNeedMutot(inputrec))
784         {
785             /* Calculate total (local) dipole moment in a temporary common array.
786              * This makes it possible to sum them over nodes faster.
787              */
788             calc_mu(start, homenr,
789                     x, mdatoms->chargeA, mdatoms->chargeB, mdatoms->nChargePerturbed,
790                     mu, mu+DIM);
791         }
792     }
793
794     if (fr->ePBC != epbcNONE)
795     {
796         /* Compute shift vectors every step,
797          * because of pressure coupling or box deformation!
798          */
799         if ((flags & GMX_FORCE_DYNAMICBOX) && bStateChanged)
800         {
801             calc_shifts(box, fr->shift_vec);
802         }
803
804         if (bCalcCGCM)
805         {
806             put_atoms_in_box_omp(fr->ePBC, box, homenr, x);
807             inc_nrnb(nrnb, eNR_SHIFTX, homenr);
808         }
809         else if (EI_ENERGY_MINIMIZATION(inputrec->eI) && graph)
810         {
811             unshift_self(graph, box, x);
812         }
813     }
814
815     nbnxn_atomdata_copy_shiftvec(flags & GMX_FORCE_DYNAMICBOX,
816                                  fr->shift_vec, nbv->grp[0].nbat);
817
818 #if GMX_MPI
819     if (!(cr->duty & DUTY_PME))
820     {
821         gmx_bool bBS;
822         matrix   boxs;
823
824         /* Send particle coordinates to the pme nodes.
825          * Since this is only implemented for domain decomposition
826          * and domain decomposition does not use the graph,
827          * we do not need to worry about shifting.
828          */
829
830         wallcycle_start(wcycle, ewcPP_PMESENDX);
831
832         bBS = (inputrec->nwall == 2);
833         if (bBS)
834         {
835             copy_mat(box, boxs);
836             svmul(inputrec->wall_ewald_zfac, boxs[ZZ], boxs[ZZ]);
837         }
838
839         gmx_pme_send_coordinates(cr, bBS ? boxs : box, x,
840                                  lambda[efptCOUL], lambda[efptVDW],
841                                  (flags & (GMX_FORCE_VIRIAL | GMX_FORCE_ENERGY)),
842                                  step);
843
844         wallcycle_stop(wcycle, ewcPP_PMESENDX);
845     }
846 #endif /* GMX_MPI */
847
848     /* do gridding for pair search */
849     if (bNS)
850     {
851         if (graph && bStateChanged)
852         {
853             /* Calculate intramolecular shift vectors to make molecules whole */
854             mk_mshift(fplog, graph, fr->ePBC, box, x);
855         }
856
857         clear_rvec(vzero);
858         box_diag[XX] = box[XX][XX];
859         box_diag[YY] = box[YY][YY];
860         box_diag[ZZ] = box[ZZ][ZZ];
861
862         wallcycle_start(wcycle, ewcNS);
863         if (!fr->bDomDec)
864         {
865             wallcycle_sub_start(wcycle, ewcsNBS_GRID_LOCAL);
866             nbnxn_put_on_grid(nbv->nbs, fr->ePBC, box,
867                               0, vzero, box_diag,
868                               0, mdatoms->homenr, -1, fr->cginfo, x,
869                               0, nullptr,
870                               nbv->grp[eintLocal].kernel_type,
871                               nbv->grp[eintLocal].nbat);
872             wallcycle_sub_stop(wcycle, ewcsNBS_GRID_LOCAL);
873         }
874         else
875         {
876             wallcycle_sub_start(wcycle, ewcsNBS_GRID_NONLOCAL);
877             nbnxn_put_on_grid_nonlocal(nbv->nbs, domdec_zones(cr->dd),
878                                        fr->cginfo, x,
879                                        nbv->grp[eintNonlocal].kernel_type,
880                                        nbv->grp[eintNonlocal].nbat);
881             wallcycle_sub_stop(wcycle, ewcsNBS_GRID_NONLOCAL);
882         }
883
884         if (nbv->ngrp == 1 ||
885             nbv->grp[eintNonlocal].nbat == nbv->grp[eintLocal].nbat)
886         {
887             nbnxn_atomdata_set(nbv->grp[eintLocal].nbat, eatAll,
888                                nbv->nbs, mdatoms, fr->cginfo);
889         }
890         else
891         {
892             nbnxn_atomdata_set(nbv->grp[eintLocal].nbat, eatLocal,
893                                nbv->nbs, mdatoms, fr->cginfo);
894             nbnxn_atomdata_set(nbv->grp[eintNonlocal].nbat, eatAll,
895                                nbv->nbs, mdatoms, fr->cginfo);
896         }
897         wallcycle_stop(wcycle, ewcNS);
898     }
899
900     /* initialize the GPU atom data and copy shift vector */
901     if (bUseGPU)
902     {
903         if (bNS)
904         {
905             wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU_NB);
906             nbnxn_gpu_init_atomdata(nbv->gpu_nbv, nbv->grp[eintLocal].nbat);
907             wallcycle_stop(wcycle, ewcLAUNCH_GPU_NB);
908         }
909
910         wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU_NB);
911         nbnxn_gpu_upload_shiftvec(nbv->gpu_nbv, nbv->grp[eintLocal].nbat);
912         wallcycle_stop(wcycle, ewcLAUNCH_GPU_NB);
913     }
914
915     /* do local pair search */
916     if (bNS)
917     {
918         wallcycle_start_nocount(wcycle, ewcNS);
919         wallcycle_sub_start(wcycle, ewcsNBS_SEARCH_LOCAL);
920         nbnxn_make_pairlist(nbv->nbs, nbv->grp[eintLocal].nbat,
921                             &top->excls,
922                             ic->rlist,
923                             nbv->min_ci_balanced,
924                             &nbv->grp[eintLocal].nbl_lists,
925                             eintLocal,
926                             nbv->grp[eintLocal].kernel_type,
927                             nrnb);
928         wallcycle_sub_stop(wcycle, ewcsNBS_SEARCH_LOCAL);
929
930         if (bUseGPU)
931         {
932             /* initialize local pair-list on the GPU */
933             nbnxn_gpu_init_pairlist(nbv->gpu_nbv,
934                                     nbv->grp[eintLocal].nbl_lists.nbl[0],
935                                     eintLocal);
936         }
937         wallcycle_stop(wcycle, ewcNS);
938     }
939     else
940     {
941         wallcycle_start(wcycle, ewcNB_XF_BUF_OPS);
942         wallcycle_sub_start(wcycle, ewcsNB_X_BUF_OPS);
943         nbnxn_atomdata_copy_x_to_nbat_x(nbv->nbs, eatLocal, FALSE, x,
944                                         nbv->grp[eintLocal].nbat);
945         wallcycle_sub_stop(wcycle, ewcsNB_X_BUF_OPS);
946         wallcycle_stop(wcycle, ewcNB_XF_BUF_OPS);
947     }
948
949     if (bUseGPU)
950     {
951         wallcycle_start(wcycle, ewcLAUNCH_GPU_NB);
952         /* launch local nonbonded F on GPU */
953         do_nb_verlet(fr, ic, enerd, flags, eintLocal, enbvClearFNo,
954                      nrnb, wcycle);
955         wallcycle_stop(wcycle, ewcLAUNCH_GPU_NB);
956     }
957
958     /* Communicate coordinates and sum dipole if necessary +
959        do non-local pair search */
960     if (DOMAINDECOMP(cr))
961     {
962         bDiffKernels = (nbv->grp[eintNonlocal].kernel_type !=
963                         nbv->grp[eintLocal].kernel_type);
964
965         if (bDiffKernels)
966         {
967             /* With GPU+CPU non-bonded calculations we need to copy
968              * the local coordinates to the non-local nbat struct
969              * (in CPU format) as the non-local kernel call also
970              * calculates the local - non-local interactions.
971              */
972             wallcycle_start(wcycle, ewcNB_XF_BUF_OPS);
973             wallcycle_sub_start(wcycle, ewcsNB_X_BUF_OPS);
974             nbnxn_atomdata_copy_x_to_nbat_x(nbv->nbs, eatLocal, TRUE, x,
975                                             nbv->grp[eintNonlocal].nbat);
976             wallcycle_sub_stop(wcycle, ewcsNB_X_BUF_OPS);
977             wallcycle_stop(wcycle, ewcNB_XF_BUF_OPS);
978         }
979
980         if (bNS)
981         {
982             wallcycle_start_nocount(wcycle, ewcNS);
983             wallcycle_sub_start(wcycle, ewcsNBS_SEARCH_NONLOCAL);
984
985             if (bDiffKernels)
986             {
987                 nbnxn_grid_add_simple(nbv->nbs, nbv->grp[eintNonlocal].nbat);
988             }
989
990             nbnxn_make_pairlist(nbv->nbs, nbv->grp[eintNonlocal].nbat,
991                                 &top->excls,
992                                 ic->rlist,
993                                 nbv->min_ci_balanced,
994                                 &nbv->grp[eintNonlocal].nbl_lists,
995                                 eintNonlocal,
996                                 nbv->grp[eintNonlocal].kernel_type,
997                                 nrnb);
998
999             wallcycle_sub_stop(wcycle, ewcsNBS_SEARCH_NONLOCAL);
1000
1001             if (nbv->grp[eintNonlocal].kernel_type == nbnxnk8x8x8_GPU)
1002             {
1003                 /* initialize non-local pair-list on the GPU */
1004                 nbnxn_gpu_init_pairlist(nbv->gpu_nbv,
1005                                         nbv->grp[eintNonlocal].nbl_lists.nbl[0],
1006                                         eintNonlocal);
1007             }
1008             wallcycle_stop(wcycle, ewcNS);
1009         }
1010         else
1011         {
1012             wallcycle_start(wcycle, ewcMOVEX);
1013             dd_move_x(cr->dd, box, x);
1014             wallcycle_stop(wcycle, ewcMOVEX);
1015
1016             wallcycle_start(wcycle, ewcNB_XF_BUF_OPS);
1017             wallcycle_sub_start(wcycle, ewcsNB_X_BUF_OPS);
1018             nbnxn_atomdata_copy_x_to_nbat_x(nbv->nbs, eatNonlocal, FALSE, x,
1019                                             nbv->grp[eintNonlocal].nbat);
1020             wallcycle_sub_stop(wcycle, ewcsNB_X_BUF_OPS);
1021             cycles_force += wallcycle_stop(wcycle, ewcNB_XF_BUF_OPS);
1022         }
1023
1024         if (bUseGPU && !bDiffKernels)
1025         {
1026             wallcycle_start(wcycle, ewcLAUNCH_GPU_NB);
1027             /* launch non-local nonbonded F on GPU */
1028             do_nb_verlet(fr, ic, enerd, flags, eintNonlocal, enbvClearFNo,
1029                          nrnb, wcycle);
1030             cycles_force += wallcycle_stop(wcycle, ewcLAUNCH_GPU_NB);
1031         }
1032     }
1033
1034     if (bUseGPU)
1035     {
1036         /* launch D2H copy-back F */
1037         wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU_NB);
1038         if (DOMAINDECOMP(cr) && !bDiffKernels)
1039         {
1040             nbnxn_gpu_launch_cpyback(nbv->gpu_nbv, nbv->grp[eintNonlocal].nbat,
1041                                      flags, eatNonlocal);
1042         }
1043         nbnxn_gpu_launch_cpyback(nbv->gpu_nbv, nbv->grp[eintLocal].nbat,
1044                                  flags, eatLocal);
1045         cycles_force += wallcycle_stop(wcycle, ewcLAUNCH_GPU_NB);
1046     }
1047
1048     if (bStateChanged && inputrecNeedMutot(inputrec))
1049     {
1050         if (PAR(cr))
1051         {
1052             gmx_sumd(2*DIM, mu, cr);
1053         }
1054
1055         for (i = 0; i < 2; i++)
1056         {
1057             for (j = 0; j < DIM; j++)
1058             {
1059                 fr->mu_tot[i][j] = mu[i*DIM + j];
1060             }
1061         }
1062     }
1063     if (fr->efep == efepNO)
1064     {
1065         copy_rvec(fr->mu_tot[0], mu_tot);
1066     }
1067     else
1068     {
1069         for (j = 0; j < DIM; j++)
1070         {
1071             mu_tot[j] =
1072                 (1.0 - lambda[efptCOUL])*fr->mu_tot[0][j] +
1073                 lambda[efptCOUL]*fr->mu_tot[1][j];
1074         }
1075     }
1076
1077     /* Reset energies */
1078     reset_enerdata(enerd);
1079     clear_rvecs(SHIFTS, fr->fshift);
1080
1081     if (DOMAINDECOMP(cr) && !(cr->duty & DUTY_PME))
1082     {
1083         wallcycle_start(wcycle, ewcPPDURINGPME);
1084         dd_force_flop_start(cr->dd, nrnb);
1085     }
1086
1087     if (inputrec->bRot)
1088     {
1089         /* Enforced rotation has its own cycle counter that starts after the collective
1090          * coordinates have been communicated. It is added to ddCyclF to allow
1091          * for proper load-balancing */
1092         wallcycle_start(wcycle, ewcROT);
1093         do_rotation(cr, inputrec, box, x, t, step, wcycle, bNS);
1094         wallcycle_stop(wcycle, ewcROT);
1095     }
1096
1097     /* Temporary solution until all routines take PaddedRVecVector */
1098     rvec *f = as_rvec_array(force->data());
1099
1100     /* Start the force cycle counter.
1101      * This counter is stopped after do_force_lowlevel.
1102      * No parallel communication should occur while this counter is running,
1103      * since that will interfere with the dynamic load balancing.
1104      */
1105     wallcycle_start(wcycle, ewcFORCE);
1106     if (bDoForces)
1107     {
1108         /* Reset forces for which the virial is calculated separately:
1109          * PME/Ewald forces if necessary */
1110         if (fr->bF_NoVirSum)
1111         {
1112             if (flags & GMX_FORCE_VIRIAL)
1113             {
1114                 fr->f_novirsum = fr->forceBufferNoVirialSummation;
1115             }
1116             else
1117             {
1118                 /* We are not calculating the pressure so we do not need
1119                  * a separate array for forces that do not contribute
1120                  * to the pressure.
1121                  */
1122                 fr->f_novirsum = force;
1123             }
1124         }
1125
1126         if (fr->bF_NoVirSum)
1127         {
1128             if (flags & GMX_FORCE_VIRIAL)
1129             {
1130                 /* TODO: remove this - 1 when padding is properly implemented */
1131                 clear_rvecs_omp(fr->f_novirsum->size() - 1,
1132                                 as_rvec_array(fr->f_novirsum->data()));
1133             }
1134         }
1135         /* Clear the short- and long-range forces */
1136         clear_rvecs_omp(fr->natoms_force_constr, f);
1137
1138         clear_rvec(fr->vir_diag_posres);
1139     }
1140
1141     if (inputrec->bPull && pull_have_constraint(inputrec->pull_work))
1142     {
1143         clear_pull_forces(inputrec->pull_work);
1144     }
1145
1146     /* We calculate the non-bonded forces, when done on the CPU, here.
1147      * We do this before calling do_force_lowlevel, because in that
1148      * function, the listed forces are calculated before PME, which
1149      * does communication.  With this order, non-bonded and listed
1150      * force calculation imbalance can be balanced out by the domain
1151      * decomposition load balancing.
1152      */
1153
1154     if (!bUseOrEmulGPU)
1155     {
1156         /* Maybe we should move this into do_force_lowlevel */
1157         do_nb_verlet(fr, ic, enerd, flags, eintLocal, enbvClearFYes,
1158                      nrnb, wcycle);
1159     }
1160
1161     if (fr->efep != efepNO)
1162     {
1163         /* Calculate the local and non-local free energy interactions here.
1164          * Happens here on the CPU both with and without GPU.
1165          */
1166         if (fr->nbv->grp[eintLocal].nbl_lists.nbl_fep[0]->nrj > 0)
1167         {
1168             do_nb_verlet_fep(&fr->nbv->grp[eintLocal].nbl_lists,
1169                              fr, x, f, mdatoms,
1170                              inputrec->fepvals, lambda,
1171                              enerd, flags, nrnb, wcycle);
1172         }
1173
1174         if (DOMAINDECOMP(cr) &&
1175             fr->nbv->grp[eintNonlocal].nbl_lists.nbl_fep[0]->nrj > 0)
1176         {
1177             do_nb_verlet_fep(&fr->nbv->grp[eintNonlocal].nbl_lists,
1178                              fr, x, f, mdatoms,
1179                              inputrec->fepvals, lambda,
1180                              enerd, flags, nrnb, wcycle);
1181         }
1182     }
1183
1184     if (!bUseOrEmulGPU || bDiffKernels)
1185     {
1186         int aloc;
1187
1188         if (DOMAINDECOMP(cr))
1189         {
1190             do_nb_verlet(fr, ic, enerd, flags, eintNonlocal,
1191                          bDiffKernels ? enbvClearFYes : enbvClearFNo,
1192                          nrnb, wcycle);
1193         }
1194
1195         if (!bUseOrEmulGPU)
1196         {
1197             aloc = eintLocal;
1198         }
1199         else
1200         {
1201             aloc = eintNonlocal;
1202         }
1203
1204         /* Add all the non-bonded force to the normal force array.
1205          * This can be split into a local and a non-local part when overlapping
1206          * communication with calculation with domain decomposition.
1207          */
1208         cycles_force += wallcycle_stop(wcycle, ewcFORCE);
1209         wallcycle_start(wcycle, ewcNB_XF_BUF_OPS);
1210         wallcycle_sub_start(wcycle, ewcsNB_F_BUF_OPS);
1211         nbnxn_atomdata_add_nbat_f_to_f(nbv->nbs, eatAll, nbv->grp[aloc].nbat, f);
1212         wallcycle_sub_stop(wcycle, ewcsNB_F_BUF_OPS);
1213         cycles_force += wallcycle_stop(wcycle, ewcNB_XF_BUF_OPS);
1214         wallcycle_start_nocount(wcycle, ewcFORCE);
1215
1216         /* if there are multiple fshift output buffers reduce them */
1217         if ((flags & GMX_FORCE_VIRIAL) &&
1218             nbv->grp[aloc].nbl_lists.nnbl > 1)
1219         {
1220             /* This is not in a subcounter because it takes a
1221                negligible and constant-sized amount of time */
1222             nbnxn_atomdata_add_nbat_fshift_to_fshift(nbv->grp[aloc].nbat,
1223                                                      fr->fshift);
1224         }
1225     }
1226
1227     /* update QMMMrec, if necessary */
1228     if (fr->bQMMM)
1229     {
1230         update_QMMMrec(cr, fr, x, mdatoms, box, top);
1231     }
1232
1233     /* Compute the bonded and non-bonded energies and optionally forces */
1234     do_force_lowlevel(fr, inputrec, &(top->idef),
1235                       cr, nrnb, wcycle, mdatoms,
1236                       x, hist, f, enerd, fcd, top, fr->born,
1237                       bBornRadii, box,
1238                       inputrec->fepvals, lambda, graph, &(top->excls), fr->mu_tot,
1239                       flags, &cycles_pme);
1240
1241     cycles_force += wallcycle_stop(wcycle, ewcFORCE);
1242
1243     if (ed)
1244     {
1245         do_flood(cr, inputrec, x, f, ed, box, step, bNS);
1246     }
1247
1248     if (bUseOrEmulGPU && !bDiffKernels)
1249     {
1250         /* wait for non-local forces (or calculate in emulation mode) */
1251         if (DOMAINDECOMP(cr))
1252         {
1253             if (bUseGPU)
1254             {
1255                 float cycles_tmp;
1256
1257                 wallcycle_start(wcycle, ewcWAIT_GPU_NB_NL);
1258                 nbnxn_gpu_wait_for_gpu(nbv->gpu_nbv,
1259                                        flags, eatNonlocal,
1260                                        enerd->grpp.ener[egLJSR], enerd->grpp.ener[egCOULSR],
1261                                        fr->fshift);
1262                 cycles_tmp       = wallcycle_stop(wcycle, ewcWAIT_GPU_NB_NL);
1263                 cycles_wait_gpu += cycles_tmp;
1264                 cycles_force    += cycles_tmp;
1265             }
1266             else
1267             {
1268                 wallcycle_start_nocount(wcycle, ewcFORCE);
1269                 do_nb_verlet(fr, ic, enerd, flags, eintNonlocal, enbvClearFYes,
1270                              nrnb, wcycle);
1271                 cycles_force += wallcycle_stop(wcycle, ewcFORCE);
1272             }
1273             wallcycle_start(wcycle, ewcNB_XF_BUF_OPS);
1274             wallcycle_sub_start(wcycle, ewcsNB_F_BUF_OPS);
1275             /* skip the reduction if there was no non-local work to do */
1276             if (nbv->grp[eintNonlocal].nbl_lists.nbl[0]->nsci > 0)
1277             {
1278                 nbnxn_atomdata_add_nbat_f_to_f(nbv->nbs, eatNonlocal,
1279                                                nbv->grp[eintNonlocal].nbat, f);
1280             }
1281             wallcycle_sub_stop(wcycle, ewcsNB_F_BUF_OPS);
1282             cycles_force += wallcycle_stop(wcycle, ewcNB_XF_BUF_OPS);
1283         }
1284     }
1285
1286     if (bDoForces && DOMAINDECOMP(cr))
1287     {
1288         if (bUseGPU)
1289         {
1290             /* We are done with the CPU compute, but the GPU local non-bonded
1291              * kernel can still be running while we communicate the forces.
1292              * We start a counter here, so we can, hopefully, time the rest
1293              * of the GPU kernel execution and data transfer.
1294              */
1295             cycleCountBeforeLocalWorkCompletes = gmx_cycles_read();
1296         }
1297
1298         /* Communicate the forces */
1299         wallcycle_start(wcycle, ewcMOVEF);
1300         dd_move_f(cr->dd, f, fr->fshift);
1301         wallcycle_stop(wcycle, ewcMOVEF);
1302     }
1303
1304     if (bUseOrEmulGPU)
1305     {
1306         /* wait for local forces (or calculate in emulation mode) */
1307         if (bUseGPU)
1308         {
1309             float       cycles_tmp, cycles_wait_est;
1310             /* Measured overhead on CUDA and OpenCL with(out) GPU sharing
1311              * is between 0.5 and 1.5 Mcycles. So 2 MCycles is an overestimate,
1312              * but even with a step of 0.1 ms the difference is less than 1%
1313              * of the step time.
1314              */
1315             const float gpuWaitApiOverheadMargin = 2e6f; /* cycles */
1316
1317             wallcycle_start(wcycle, ewcWAIT_GPU_NB_L);
1318             nbnxn_gpu_wait_for_gpu(nbv->gpu_nbv,
1319                                    flags, eatLocal,
1320                                    enerd->grpp.ener[egLJSR], enerd->grpp.ener[egCOULSR],
1321                                    fr->fshift);
1322             cycles_tmp      = wallcycle_stop(wcycle, ewcWAIT_GPU_NB_L);
1323
1324             if (bDoForces && DOMAINDECOMP(cr))
1325             {
1326                 cycles_wait_est = gmx_cycles_read() - cycleCountBeforeLocalWorkCompletes;
1327
1328                 if (cycles_tmp < gpuWaitApiOverheadMargin)
1329                 {
1330                     /* We measured few cycles, it could be that the kernel
1331                      * and transfer finished earlier and there was no actual
1332                      * wait time, only API call overhead.
1333                      * Then the actual time could be anywhere between 0 and
1334                      * cycles_wait_est. As a compromise, we use half the time.
1335                      */
1336                     cycles_wait_est *= 0.5f;
1337                 }
1338             }
1339             else
1340             {
1341                 /* No force communication so we actually timed the wait */
1342                 cycles_wait_est = cycles_tmp;
1343             }
1344             /* Even though this is after dd_move_f, the actual task we are
1345              * waiting for runs asynchronously with dd_move_f and we usually
1346              * have nothing to balance it with, so we can and should add
1347              * the time to the force time for load balancing.
1348              */
1349             cycles_force    += cycles_wait_est;
1350             cycles_wait_gpu += cycles_wait_est;
1351
1352             /* now clear the GPU outputs while we finish the step on the CPU */
1353             wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU_NB);
1354             nbnxn_gpu_clear_outputs(nbv->gpu_nbv, flags);
1355             wallcycle_stop(wcycle, ewcLAUNCH_GPU_NB);
1356         }
1357         else
1358         {
1359             wallcycle_start_nocount(wcycle, ewcFORCE);
1360             do_nb_verlet(fr, ic, enerd, flags, eintLocal,
1361                          DOMAINDECOMP(cr) ? enbvClearFNo : enbvClearFYes,
1362                          nrnb, wcycle);
1363             wallcycle_stop(wcycle, ewcFORCE);
1364         }
1365         wallcycle_start(wcycle, ewcNB_XF_BUF_OPS);
1366         wallcycle_sub_start(wcycle, ewcsNB_F_BUF_OPS);
1367         nbnxn_atomdata_add_nbat_f_to_f(nbv->nbs, eatLocal,
1368                                        nbv->grp[eintLocal].nbat, f);
1369         wallcycle_sub_stop(wcycle, ewcsNB_F_BUF_OPS);
1370         wallcycle_stop(wcycle, ewcNB_XF_BUF_OPS);
1371     }
1372
1373     if (DOMAINDECOMP(cr))
1374     {
1375         dd_force_flop_stop(cr->dd, nrnb);
1376         if (wcycle)
1377         {
1378             dd_cycles_add(cr->dd, cycles_force-cycles_pme, ddCyclF);
1379             if (bUseGPU)
1380             {
1381                 dd_cycles_add(cr->dd, cycles_wait_gpu, ddCyclWaitGPU);
1382             }
1383         }
1384     }
1385
1386     if (bDoForces)
1387     {
1388         /* Compute forces due to electric field */
1389         if (fr->efield != nullptr)
1390         {
1391             fr->efield->calculateForces(cr, mdatoms, fr->f_novirsum, t);
1392         }
1393
1394         /* If we have NoVirSum forces, but we do not calculate the virial,
1395          * we sum fr->f_novirsum=f later.
1396          */
1397         if (vsite && !(fr->bF_NoVirSum && !(flags & GMX_FORCE_VIRIAL)))
1398         {
1399             wallcycle_start(wcycle, ewcVSITESPREAD);
1400             spread_vsite_f(vsite, x, f, fr->fshift, FALSE, nullptr, nrnb,
1401                            &top->idef, fr->ePBC, fr->bMolPBC, graph, box, cr);
1402             wallcycle_stop(wcycle, ewcVSITESPREAD);
1403         }
1404
1405         if (flags & GMX_FORCE_VIRIAL)
1406         {
1407             /* Calculation of the virial must be done after vsites! */
1408             calc_virial(0, mdatoms->homenr, x, f,
1409                         vir_force, graph, box, nrnb, fr, inputrec->ePBC);
1410         }
1411     }
1412
1413     if (inputrec->bPull && pull_have_potential(inputrec->pull_work))
1414     {
1415         /* Since the COM pulling is always done mass-weighted, no forces are
1416          * applied to vsites and this call can be done after vsite spreading.
1417          */
1418         pull_potential_wrapper(cr, inputrec, box, x,
1419                                f, vir_force, mdatoms, enerd, lambda, t,
1420                                wcycle);
1421     }
1422
1423     /* Add the forces from enforced rotation potentials (if any) */
1424     if (inputrec->bRot)
1425     {
1426         wallcycle_start(wcycle, ewcROTadd);
1427         enerd->term[F_COM_PULL] += add_rot_forces(inputrec->rot, f, cr, step, t);
1428         wallcycle_stop(wcycle, ewcROTadd);
1429     }
1430
1431     /* Add forces from interactive molecular dynamics (IMD), if bIMD == TRUE. */
1432     IMD_apply_forces(inputrec->bIMD, inputrec->imd, cr, f, wcycle);
1433
1434     if (PAR(cr) && !(cr->duty & DUTY_PME))
1435     {
1436         /* In case of node-splitting, the PP nodes receive the long-range
1437          * forces, virial and energy from the PME nodes here.
1438          */
1439         pme_receive_force_ener(cr, wcycle, enerd, fr);
1440     }
1441
1442     if (bDoForces)
1443     {
1444         post_process_forces(cr, step, nrnb, wcycle,
1445                             top, box, x, f, vir_force, mdatoms, graph, fr, vsite,
1446                             flags);
1447     }
1448
1449     if (flags & GMX_FORCE_ENERGY)
1450     {
1451         /* Sum the potential energy terms from group contributions */
1452         sum_epot(&(enerd->grpp), enerd->term);
1453
1454         if (!EI_TPI(inputrec->eI))
1455         {
1456             checkPotentialEnergyValidity(enerd);
1457         }
1458     }
1459 }
1460
1461 void do_force_cutsGROUP(FILE *fplog, t_commrec *cr,
1462                         t_inputrec *inputrec,
1463                         gmx_int64_t step, t_nrnb *nrnb, gmx_wallcycle_t wcycle,
1464                         gmx_localtop_t *top,
1465                         gmx_groups_t *groups,
1466                         matrix box, rvec x[], history_t *hist,
1467                         PaddedRVecVector *force,
1468                         tensor vir_force,
1469                         t_mdatoms *mdatoms,
1470                         gmx_enerdata_t *enerd, t_fcdata *fcd,
1471                         real *lambda, t_graph *graph,
1472                         t_forcerec *fr, gmx_vsite_t *vsite, rvec mu_tot,
1473                         double t, gmx_edsam_t ed,
1474                         gmx_bool bBornRadii,
1475                         int flags)
1476 {
1477     int        cg0, cg1, i, j;
1478     double     mu[2*DIM];
1479     gmx_bool   bStateChanged, bNS, bFillGrid, bCalcCGCM;
1480     gmx_bool   bDoForces;
1481     float      cycles_pme, cycles_force;
1482
1483     const int  start  = 0;
1484     const int  homenr = mdatoms->homenr;
1485
1486     clear_mat(vir_force);
1487
1488     cg0 = 0;
1489     if (DOMAINDECOMP(cr))
1490     {
1491         cg1 = cr->dd->ncg_tot;
1492     }
1493     else
1494     {
1495         cg1 = top->cgs.nr;
1496     }
1497     if (fr->n_tpi > 0)
1498     {
1499         cg1--;
1500     }
1501
1502     bStateChanged  = (flags & GMX_FORCE_STATECHANGED);
1503     bNS            = (flags & GMX_FORCE_NS) && (fr->bAllvsAll == FALSE);
1504     /* Should we perform the long-range nonbonded evaluation inside the neighborsearching? */
1505     bFillGrid      = (bNS && bStateChanged);
1506     bCalcCGCM      = (bFillGrid && !DOMAINDECOMP(cr));
1507     bDoForces      = (flags & GMX_FORCE_FORCES);
1508
1509     if (bStateChanged)
1510     {
1511         update_forcerec(fr, box);
1512
1513         if (inputrecNeedMutot(inputrec))
1514         {
1515             /* Calculate total (local) dipole moment in a temporary common array.
1516              * This makes it possible to sum them over nodes faster.
1517              */
1518             calc_mu(start, homenr,
1519                     x, mdatoms->chargeA, mdatoms->chargeB, mdatoms->nChargePerturbed,
1520                     mu, mu+DIM);
1521         }
1522     }
1523
1524     if (fr->ePBC != epbcNONE)
1525     {
1526         /* Compute shift vectors every step,
1527          * because of pressure coupling or box deformation!
1528          */
1529         if ((flags & GMX_FORCE_DYNAMICBOX) && bStateChanged)
1530         {
1531             calc_shifts(box, fr->shift_vec);
1532         }
1533
1534         if (bCalcCGCM)
1535         {
1536             put_charge_groups_in_box(fplog, cg0, cg1, fr->ePBC, box,
1537                                      &(top->cgs), x, fr->cg_cm);
1538             inc_nrnb(nrnb, eNR_CGCM, homenr);
1539             inc_nrnb(nrnb, eNR_RESETX, cg1-cg0);
1540         }
1541         else if (EI_ENERGY_MINIMIZATION(inputrec->eI) && graph)
1542         {
1543             unshift_self(graph, box, x);
1544         }
1545     }
1546     else if (bCalcCGCM)
1547     {
1548         calc_cgcm(fplog, cg0, cg1, &(top->cgs), x, fr->cg_cm);
1549         inc_nrnb(nrnb, eNR_CGCM, homenr);
1550     }
1551
1552     if (bCalcCGCM && gmx_debug_at)
1553     {
1554         pr_rvecs(debug, 0, "cgcm", fr->cg_cm, top->cgs.nr);
1555     }
1556
1557 #if GMX_MPI
1558     if (!(cr->duty & DUTY_PME))
1559     {
1560         gmx_bool bBS;
1561         matrix   boxs;
1562
1563         /* Send particle coordinates to the pme nodes.
1564          * Since this is only implemented for domain decomposition
1565          * and domain decomposition does not use the graph,
1566          * we do not need to worry about shifting.
1567          */
1568
1569         wallcycle_start(wcycle, ewcPP_PMESENDX);
1570
1571         bBS = (inputrec->nwall == 2);
1572         if (bBS)
1573         {
1574             copy_mat(box, boxs);
1575             svmul(inputrec->wall_ewald_zfac, boxs[ZZ], boxs[ZZ]);
1576         }
1577
1578         gmx_pme_send_coordinates(cr, bBS ? boxs : box, x,
1579                                  lambda[efptCOUL], lambda[efptVDW],
1580                                  (flags & (GMX_FORCE_VIRIAL | GMX_FORCE_ENERGY)),
1581                                  step);
1582
1583         wallcycle_stop(wcycle, ewcPP_PMESENDX);
1584     }
1585 #endif /* GMX_MPI */
1586
1587     /* Communicate coordinates and sum dipole if necessary */
1588     if (DOMAINDECOMP(cr))
1589     {
1590         wallcycle_start(wcycle, ewcMOVEX);
1591         dd_move_x(cr->dd, box, x);
1592         wallcycle_stop(wcycle, ewcMOVEX);
1593     }
1594
1595     if (inputrecNeedMutot(inputrec))
1596     {
1597         if (bStateChanged)
1598         {
1599             if (PAR(cr))
1600             {
1601                 gmx_sumd(2*DIM, mu, cr);
1602             }
1603             for (i = 0; i < 2; i++)
1604             {
1605                 for (j = 0; j < DIM; j++)
1606                 {
1607                     fr->mu_tot[i][j] = mu[i*DIM + j];
1608                 }
1609             }
1610         }
1611         if (fr->efep == efepNO)
1612         {
1613             copy_rvec(fr->mu_tot[0], mu_tot);
1614         }
1615         else
1616         {
1617             for (j = 0; j < DIM; j++)
1618             {
1619                 mu_tot[j] =
1620                     (1.0 - lambda[efptCOUL])*fr->mu_tot[0][j] + lambda[efptCOUL]*fr->mu_tot[1][j];
1621             }
1622         }
1623     }
1624
1625     /* Reset energies */
1626     reset_enerdata(enerd);
1627     clear_rvecs(SHIFTS, fr->fshift);
1628
1629     if (bNS)
1630     {
1631         wallcycle_start(wcycle, ewcNS);
1632
1633         if (graph && bStateChanged)
1634         {
1635             /* Calculate intramolecular shift vectors to make molecules whole */
1636             mk_mshift(fplog, graph, fr->ePBC, box, x);
1637         }
1638
1639         /* Do the actual neighbour searching */
1640         ns(fplog, fr, box,
1641            groups, top, mdatoms,
1642            cr, nrnb, bFillGrid);
1643
1644         wallcycle_stop(wcycle, ewcNS);
1645     }
1646
1647     if (inputrec->implicit_solvent && bNS)
1648     {
1649         make_gb_nblist(cr, inputrec->gb_algorithm,
1650                        x, box, fr, &top->idef, graph, fr->born);
1651     }
1652
1653     if (DOMAINDECOMP(cr) && !(cr->duty & DUTY_PME))
1654     {
1655         wallcycle_start(wcycle, ewcPPDURINGPME);
1656         dd_force_flop_start(cr->dd, nrnb);
1657     }
1658
1659     if (inputrec->bRot)
1660     {
1661         /* Enforced rotation has its own cycle counter that starts after the collective
1662          * coordinates have been communicated. It is added to ddCyclF to allow
1663          * for proper load-balancing */
1664         wallcycle_start(wcycle, ewcROT);
1665         do_rotation(cr, inputrec, box, x, t, step, wcycle, bNS);
1666         wallcycle_stop(wcycle, ewcROT);
1667     }
1668
1669     /* Temporary solution until all routines take PaddedRVecVector */
1670     rvec *f = as_rvec_array(force->data());
1671
1672     /* Start the force cycle counter.
1673      * This counter is stopped after do_force_lowlevel.
1674      * No parallel communication should occur while this counter is running,
1675      * since that will interfere with the dynamic load balancing.
1676      */
1677     wallcycle_start(wcycle, ewcFORCE);
1678
1679     if (bDoForces)
1680     {
1681         /* Reset forces for which the virial is calculated separately:
1682          * PME/Ewald forces if necessary */
1683         if (fr->bF_NoVirSum)
1684         {
1685             if (flags & GMX_FORCE_VIRIAL)
1686             {
1687                 fr->f_novirsum = fr->forceBufferNoVirialSummation;
1688                 /* TODO: remove this - 1 when padding is properly implemented */
1689                 clear_rvecs(fr->f_novirsum->size() - 1,
1690                             as_rvec_array(fr->f_novirsum->data()));
1691             }
1692             else
1693             {
1694                 /* We are not calculating the pressure so we do not need
1695                  * a separate array for forces that do not contribute
1696                  * to the pressure.
1697                  */
1698                 fr->f_novirsum = force;
1699             }
1700         }
1701
1702         /* Clear the short- and long-range forces */
1703         clear_rvecs(fr->natoms_force_constr, f);
1704
1705         clear_rvec(fr->vir_diag_posres);
1706     }
1707     if (inputrec->bPull && pull_have_constraint(inputrec->pull_work))
1708     {
1709         clear_pull_forces(inputrec->pull_work);
1710     }
1711
1712     /* update QMMMrec, if necessary */
1713     if (fr->bQMMM)
1714     {
1715         update_QMMMrec(cr, fr, x, mdatoms, box, top);
1716     }
1717
1718     /* Compute the bonded and non-bonded energies and optionally forces */
1719     do_force_lowlevel(fr, inputrec, &(top->idef),
1720                       cr, nrnb, wcycle, mdatoms,
1721                       x, hist, f, enerd, fcd, top, fr->born,
1722                       bBornRadii, box,
1723                       inputrec->fepvals, lambda,
1724                       graph, &(top->excls), fr->mu_tot,
1725                       flags,
1726                       &cycles_pme);
1727
1728     cycles_force = wallcycle_stop(wcycle, ewcFORCE);
1729
1730     if (ed)
1731     {
1732         do_flood(cr, inputrec, x, f, ed, box, step, bNS);
1733     }
1734
1735     if (DOMAINDECOMP(cr))
1736     {
1737         dd_force_flop_stop(cr->dd, nrnb);
1738         if (wcycle)
1739         {
1740             dd_cycles_add(cr->dd, cycles_force-cycles_pme, ddCyclF);
1741         }
1742     }
1743
1744     if (bDoForces)
1745     {
1746         /* Compute forces due to electric field */
1747         if (fr->efield != nullptr)
1748         {
1749             fr->efield->calculateForces(cr, mdatoms, fr->f_novirsum, t);
1750         }
1751
1752         /* Communicate the forces */
1753         if (DOMAINDECOMP(cr))
1754         {
1755             wallcycle_start(wcycle, ewcMOVEF);
1756             dd_move_f(cr->dd, f, fr->fshift);
1757             /* Do we need to communicate the separate force array
1758              * for terms that do not contribute to the single sum virial?
1759              * Position restraints and electric fields do not introduce
1760              * inter-cg forces, only full electrostatics methods do.
1761              * When we do not calculate the virial, fr->f_novirsum = f,
1762              * so we have already communicated these forces.
1763              */
1764             if (EEL_FULL(fr->eeltype) && cr->dd->n_intercg_excl &&
1765                 (flags & GMX_FORCE_VIRIAL))
1766             {
1767                 dd_move_f(cr->dd, as_rvec_array(fr->f_novirsum->data()), nullptr);
1768             }
1769             wallcycle_stop(wcycle, ewcMOVEF);
1770         }
1771
1772         /* If we have NoVirSum forces, but we do not calculate the virial,
1773          * we sum fr->f_novirsum=f later.
1774          */
1775         if (vsite && !(fr->bF_NoVirSum && !(flags & GMX_FORCE_VIRIAL)))
1776         {
1777             wallcycle_start(wcycle, ewcVSITESPREAD);
1778             spread_vsite_f(vsite, x, f, fr->fshift, FALSE, nullptr, nrnb,
1779                            &top->idef, fr->ePBC, fr->bMolPBC, graph, box, cr);
1780             wallcycle_stop(wcycle, ewcVSITESPREAD);
1781         }
1782
1783         if (flags & GMX_FORCE_VIRIAL)
1784         {
1785             /* Calculation of the virial must be done after vsites! */
1786             calc_virial(0, mdatoms->homenr, x, f,
1787                         vir_force, graph, box, nrnb, fr, inputrec->ePBC);
1788         }
1789     }
1790
1791     if (inputrec->bPull && pull_have_potential(inputrec->pull_work))
1792     {
1793         pull_potential_wrapper(cr, inputrec, box, x,
1794                                f, vir_force, mdatoms, enerd, lambda, t,
1795                                wcycle);
1796     }
1797
1798     /* Add the forces from enforced rotation potentials (if any) */
1799     if (inputrec->bRot)
1800     {
1801         wallcycle_start(wcycle, ewcROTadd);
1802         enerd->term[F_COM_PULL] += add_rot_forces(inputrec->rot, f, cr, step, t);
1803         wallcycle_stop(wcycle, ewcROTadd);
1804     }
1805
1806     /* Add forces from interactive molecular dynamics (IMD), if bIMD == TRUE. */
1807     IMD_apply_forces(inputrec->bIMD, inputrec->imd, cr, f, wcycle);
1808
1809     if (PAR(cr) && !(cr->duty & DUTY_PME))
1810     {
1811         /* In case of node-splitting, the PP nodes receive the long-range
1812          * forces, virial and energy from the PME nodes here.
1813          */
1814         pme_receive_force_ener(cr, wcycle, enerd, fr);
1815     }
1816
1817     if (bDoForces)
1818     {
1819         post_process_forces(cr, step, nrnb, wcycle,
1820                             top, box, x, f, vir_force, mdatoms, graph, fr, vsite,
1821                             flags);
1822     }
1823
1824     if (flags & GMX_FORCE_ENERGY)
1825     {
1826         /* Sum the potential energy terms from group contributions */
1827         sum_epot(&(enerd->grpp), enerd->term);
1828
1829         if (!EI_TPI(inputrec->eI))
1830         {
1831             checkPotentialEnergyValidity(enerd);
1832         }
1833     }
1834
1835 }
1836
1837 void do_force(FILE *fplog, t_commrec *cr,
1838               t_inputrec *inputrec,
1839               gmx_int64_t step, t_nrnb *nrnb, gmx_wallcycle_t wcycle,
1840               gmx_localtop_t *top,
1841               gmx_groups_t *groups,
1842               matrix box, PaddedRVecVector *coordinates, history_t *hist,
1843               PaddedRVecVector *force,
1844               tensor vir_force,
1845               t_mdatoms *mdatoms,
1846               gmx_enerdata_t *enerd, t_fcdata *fcd,
1847               gmx::ArrayRef<real> lambda, t_graph *graph,
1848               t_forcerec *fr,
1849               gmx_vsite_t *vsite, rvec mu_tot,
1850               double t, gmx_edsam_t ed,
1851               gmx_bool bBornRadii,
1852               int flags)
1853 {
1854     /* modify force flag if not doing nonbonded */
1855     if (!fr->bNonbonded)
1856     {
1857         flags &= ~GMX_FORCE_NONBONDED;
1858     }
1859
1860     GMX_ASSERT(coordinates->size() >= static_cast<unsigned int>(fr->natoms_force + 1), "We might need 1 element extra for SIMD");
1861     GMX_ASSERT(force->size() >= static_cast<unsigned int>(fr->natoms_force + 1), "We might need 1 element extra for SIMD");
1862
1863     rvec *x = as_rvec_array(coordinates->data());
1864
1865     switch (inputrec->cutoff_scheme)
1866     {
1867         case ecutsVERLET:
1868             do_force_cutsVERLET(fplog, cr, inputrec,
1869                                 step, nrnb, wcycle,
1870                                 top,
1871                                 groups,
1872                                 box, x, hist,
1873                                 force, vir_force,
1874                                 mdatoms,
1875                                 enerd, fcd,
1876                                 lambda.data(), graph,
1877                                 fr, fr->ic,
1878                                 vsite, mu_tot,
1879                                 t, ed,
1880                                 bBornRadii,
1881                                 flags);
1882             break;
1883         case ecutsGROUP:
1884             do_force_cutsGROUP(fplog, cr, inputrec,
1885                                step, nrnb, wcycle,
1886                                top,
1887                                groups,
1888                                box, x, hist,
1889                                force, vir_force,
1890                                mdatoms,
1891                                enerd, fcd,
1892                                lambda.data(), graph,
1893                                fr, vsite, mu_tot,
1894                                t, ed,
1895                                bBornRadii,
1896                                flags);
1897             break;
1898         default:
1899             gmx_incons("Invalid cut-off scheme passed!");
1900     }
1901 }
1902
1903
1904 void do_constrain_first(FILE *fplog, gmx_constr_t constr,
1905                         t_inputrec *ir, t_mdatoms *md,
1906                         t_state *state, t_commrec *cr, t_nrnb *nrnb,
1907                         t_forcerec *fr, gmx_localtop_t *top)
1908 {
1909     int             i, m, start, end;
1910     gmx_int64_t     step;
1911     real            dt = ir->delta_t;
1912     real            dvdl_dum;
1913     rvec           *savex;
1914
1915     /* We need to allocate one element extra, since we might use
1916      * (unaligned) 4-wide SIMD loads to access rvec entries.
1917      */
1918     snew(savex, state->natoms + 1);
1919
1920     start = 0;
1921     end   = md->homenr;
1922
1923     if (debug)
1924     {
1925         fprintf(debug, "vcm: start=%d, homenr=%d, end=%d\n",
1926                 start, md->homenr, end);
1927     }
1928     /* Do a first constrain to reset particles... */
1929     step = ir->init_step;
1930     if (fplog)
1931     {
1932         char buf[STEPSTRSIZE];
1933         fprintf(fplog, "\nConstraining the starting coordinates (step %s)\n",
1934                 gmx_step_str(step, buf));
1935     }
1936     dvdl_dum = 0;
1937
1938     /* constrain the current position */
1939     constrain(nullptr, TRUE, FALSE, constr, &(top->idef),
1940               ir, cr, step, 0, 1.0, md,
1941               as_rvec_array(state->x.data()), as_rvec_array(state->x.data()), nullptr,
1942               fr->bMolPBC, state->box,
1943               state->lambda[efptBONDED], &dvdl_dum,
1944               nullptr, nullptr, nrnb, econqCoord);
1945     if (EI_VV(ir->eI))
1946     {
1947         /* constrain the inital velocity, and save it */
1948         /* also may be useful if we need the ekin from the halfstep for velocity verlet */
1949         constrain(nullptr, TRUE, FALSE, constr, &(top->idef),
1950                   ir, cr, step, 0, 1.0, md,
1951                   as_rvec_array(state->x.data()), as_rvec_array(state->v.data()), as_rvec_array(state->v.data()),
1952                   fr->bMolPBC, state->box,
1953                   state->lambda[efptBONDED], &dvdl_dum,
1954                   nullptr, nullptr, nrnb, econqVeloc);
1955     }
1956     /* constrain the inital velocities at t-dt/2 */
1957     if (EI_STATE_VELOCITY(ir->eI) && ir->eI != eiVV)
1958     {
1959         for (i = start; (i < end); i++)
1960         {
1961             for (m = 0; (m < DIM); m++)
1962             {
1963                 /* Reverse the velocity */
1964                 state->v[i][m] = -state->v[i][m];
1965                 /* Store the position at t-dt in buf */
1966                 savex[i][m] = state->x[i][m] + dt*state->v[i][m];
1967             }
1968         }
1969         /* Shake the positions at t=-dt with the positions at t=0
1970          * as reference coordinates.
1971          */
1972         if (fplog)
1973         {
1974             char buf[STEPSTRSIZE];
1975             fprintf(fplog, "\nConstraining the coordinates at t0-dt (step %s)\n",
1976                     gmx_step_str(step, buf));
1977         }
1978         dvdl_dum = 0;
1979         constrain(nullptr, TRUE, FALSE, constr, &(top->idef),
1980                   ir, cr, step, -1, 1.0, md,
1981                   as_rvec_array(state->x.data()), savex, nullptr,
1982                   fr->bMolPBC, state->box,
1983                   state->lambda[efptBONDED], &dvdl_dum,
1984                   as_rvec_array(state->v.data()), nullptr, nrnb, econqCoord);
1985
1986         for (i = start; i < end; i++)
1987         {
1988             for (m = 0; m < DIM; m++)
1989             {
1990                 /* Re-reverse the velocities */
1991                 state->v[i][m] = -state->v[i][m];
1992             }
1993         }
1994     }
1995     sfree(savex);
1996 }
1997
1998
1999 static void
2000 integrate_table(real vdwtab[], real scale, int offstart, int rstart, int rend,
2001                 double *enerout, double *virout)
2002 {
2003     double enersum, virsum;
2004     double invscale, invscale2, invscale3;
2005     double r, ea, eb, ec, pa, pb, pc, pd;
2006     double y0, f, g, h;
2007     int    ri, offset;
2008     double tabfactor;
2009
2010     invscale  = 1.0/scale;
2011     invscale2 = invscale*invscale;
2012     invscale3 = invscale*invscale2;
2013
2014     /* Following summation derived from cubic spline definition,
2015      * Numerical Recipies in C, second edition, p. 113-116.  Exact for
2016      * the cubic spline.  We first calculate the negative of the
2017      * energy from rvdw to rvdw_switch, assuming that g(r)=1, and then
2018      * add the more standard, abrupt cutoff correction to that result,
2019      * yielding the long-range correction for a switched function.  We
2020      * perform both the pressure and energy loops at the same time for
2021      * simplicity, as the computational cost is low. */
2022
2023     if (offstart == 0)
2024     {
2025         /* Since the dispersion table has been scaled down a factor
2026          * 6.0 and the repulsion a factor 12.0 to compensate for the
2027          * c6/c12 parameters inside nbfp[] being scaled up (to save
2028          * flops in kernels), we need to correct for this.
2029          */
2030         tabfactor = 6.0;
2031     }
2032     else
2033     {
2034         tabfactor = 12.0;
2035     }
2036
2037     enersum = 0.0;
2038     virsum  = 0.0;
2039     for (ri = rstart; ri < rend; ++ri)
2040     {
2041         r  = ri*invscale;
2042         ea = invscale3;
2043         eb = 2.0*invscale2*r;
2044         ec = invscale*r*r;
2045
2046         pa = invscale3;
2047         pb = 3.0*invscale2*r;
2048         pc = 3.0*invscale*r*r;
2049         pd = r*r*r;
2050
2051         /* this "8" is from the packing in the vdwtab array - perhaps
2052            should be defined? */
2053
2054         offset = 8*ri + offstart;
2055         y0     = vdwtab[offset];
2056         f      = vdwtab[offset+1];
2057         g      = vdwtab[offset+2];
2058         h      = vdwtab[offset+3];
2059
2060         enersum += y0*(ea/3 + eb/2 + ec) + f*(ea/4 + eb/3 + ec/2) + g*(ea/5 + eb/4 + ec/3) + h*(ea/6 + eb/5 + ec/4);
2061         virsum  +=  f*(pa/4 + pb/3 + pc/2 + pd) + 2*g*(pa/5 + pb/4 + pc/3 + pd/2) + 3*h*(pa/6 + pb/5 + pc/4 + pd/3);
2062     }
2063     *enerout = 4.0*M_PI*enersum*tabfactor;
2064     *virout  = 4.0*M_PI*virsum*tabfactor;
2065 }
2066
2067 void calc_enervirdiff(FILE *fplog, int eDispCorr, t_forcerec *fr)
2068 {
2069     double   eners[2], virs[2], enersum, virsum;
2070     double   r0, rc3, rc9;
2071     int      ri0, ri1, i;
2072     real     scale, *vdwtab;
2073
2074     fr->enershiftsix    = 0;
2075     fr->enershifttwelve = 0;
2076     fr->enerdiffsix     = 0;
2077     fr->enerdifftwelve  = 0;
2078     fr->virdiffsix      = 0;
2079     fr->virdifftwelve   = 0;
2080
2081     if (eDispCorr != edispcNO)
2082     {
2083         for (i = 0; i < 2; i++)
2084         {
2085             eners[i] = 0;
2086             virs[i]  = 0;
2087         }
2088         if ((fr->vdw_modifier == eintmodPOTSHIFT) ||
2089             (fr->vdw_modifier == eintmodPOTSWITCH) ||
2090             (fr->vdw_modifier == eintmodFORCESWITCH) ||
2091             (fr->vdwtype == evdwSHIFT) ||
2092             (fr->vdwtype == evdwSWITCH))
2093         {
2094             if (((fr->vdw_modifier == eintmodPOTSWITCH) ||
2095                  (fr->vdw_modifier == eintmodFORCESWITCH) ||
2096                  (fr->vdwtype == evdwSWITCH)) && fr->rvdw_switch == 0)
2097             {
2098                 gmx_fatal(FARGS,
2099                           "With dispersion correction rvdw-switch can not be zero "
2100                           "for vdw-type = %s", evdw_names[fr->vdwtype]);
2101             }
2102
2103             /* TODO This code depends on the logic in tables.c that
2104                constructs the table layout, which should be made
2105                explicit in future cleanup. */
2106             GMX_ASSERT(fr->dispersionCorrectionTable->interaction == GMX_TABLE_INTERACTION_VDWREP_VDWDISP,
2107                        "Dispersion-correction code needs a table with both repulsion and dispersion terms");
2108             scale  = fr->dispersionCorrectionTable->scale;
2109             vdwtab = fr->dispersionCorrectionTable->data;
2110
2111             /* Round the cut-offs to exact table values for precision */
2112             ri0  = static_cast<int>(floor(fr->rvdw_switch*scale));
2113             ri1  = static_cast<int>(ceil(fr->rvdw*scale));
2114
2115             /* The code below has some support for handling force-switching, i.e.
2116              * when the force (instead of potential) is switched over a limited
2117              * region. This leads to a constant shift in the potential inside the
2118              * switching region, which we can handle by adding a constant energy
2119              * term in the force-switch case just like when we do potential-shift.
2120              *
2121              * For now this is not enabled, but to keep the functionality in the
2122              * code we check separately for switch and shift. When we do force-switch
2123              * the shifting point is rvdw_switch, while it is the cutoff when we
2124              * have a classical potential-shift.
2125              *
2126              * For a pure potential-shift the potential has a constant shift
2127              * all the way out to the cutoff, and that is it. For other forms
2128              * we need to calculate the constant shift up to the point where we
2129              * start modifying the potential.
2130              */
2131             ri0  = (fr->vdw_modifier == eintmodPOTSHIFT) ? ri1 : ri0;
2132
2133             r0   = ri0/scale;
2134             rc3  = r0*r0*r0;
2135             rc9  = rc3*rc3*rc3;
2136
2137             if ((fr->vdw_modifier == eintmodFORCESWITCH) ||
2138                 (fr->vdwtype == evdwSHIFT))
2139             {
2140                 /* Determine the constant energy shift below rvdw_switch.
2141                  * Table has a scale factor since we have scaled it down to compensate
2142                  * for scaling-up c6/c12 with the derivative factors to save flops in analytical kernels.
2143                  */
2144                 fr->enershiftsix    = (real)(-1.0/(rc3*rc3)) - 6.0*vdwtab[8*ri0];
2145                 fr->enershifttwelve = (real)( 1.0/(rc9*rc3)) - 12.0*vdwtab[8*ri0 + 4];
2146             }
2147             else if (fr->vdw_modifier == eintmodPOTSHIFT)
2148             {
2149                 fr->enershiftsix    = (real)(-1.0/(rc3*rc3));
2150                 fr->enershifttwelve = (real)( 1.0/(rc9*rc3));
2151             }
2152
2153             /* Add the constant part from 0 to rvdw_switch.
2154              * This integration from 0 to rvdw_switch overcounts the number
2155              * of interactions by 1, as it also counts the self interaction.
2156              * We will correct for this later.
2157              */
2158             eners[0] += 4.0*M_PI*fr->enershiftsix*rc3/3.0;
2159             eners[1] += 4.0*M_PI*fr->enershifttwelve*rc3/3.0;
2160
2161             /* Calculate the contribution in the range [r0,r1] where we
2162              * modify the potential. For a pure potential-shift modifier we will
2163              * have ri0==ri1, and there will not be any contribution here.
2164              */
2165             for (i = 0; i < 2; i++)
2166             {
2167                 enersum = 0;
2168                 virsum  = 0;
2169                 integrate_table(vdwtab, scale, (i == 0 ? 0 : 4), ri0, ri1, &enersum, &virsum);
2170                 eners[i] -= enersum;
2171                 virs[i]  -= virsum;
2172             }
2173
2174             /* Alright: Above we compensated by REMOVING the parts outside r0
2175              * corresponding to the ideal VdW 1/r6 and /r12 potentials.
2176              *
2177              * Regardless of whether r0 is the point where we start switching,
2178              * or the cutoff where we calculated the constant shift, we include
2179              * all the parts we are missing out to infinity from r0 by
2180              * calculating the analytical dispersion correction.
2181              */
2182             eners[0] += -4.0*M_PI/(3.0*rc3);
2183             eners[1] +=  4.0*M_PI/(9.0*rc9);
2184             virs[0]  +=  8.0*M_PI/rc3;
2185             virs[1]  += -16.0*M_PI/(3.0*rc9);
2186         }
2187         else if (fr->vdwtype == evdwCUT ||
2188                  EVDW_PME(fr->vdwtype) ||
2189                  fr->vdwtype == evdwUSER)
2190         {
2191             if (fr->vdwtype == evdwUSER && fplog)
2192             {
2193                 fprintf(fplog,
2194                         "WARNING: using dispersion correction with user tables\n");
2195             }
2196
2197             /* Note that with LJ-PME, the dispersion correction is multiplied
2198              * by the difference between the actual C6 and the value of C6
2199              * that would produce the combination rule.
2200              * This means the normal energy and virial difference formulas
2201              * can be used here.
2202              */
2203
2204             rc3  = fr->rvdw*fr->rvdw*fr->rvdw;
2205             rc9  = rc3*rc3*rc3;
2206             /* Contribution beyond the cut-off */
2207             eners[0] += -4.0*M_PI/(3.0*rc3);
2208             eners[1] +=  4.0*M_PI/(9.0*rc9);
2209             if (fr->vdw_modifier == eintmodPOTSHIFT)
2210             {
2211                 /* Contribution within the cut-off */
2212                 eners[0] += -4.0*M_PI/(3.0*rc3);
2213                 eners[1] +=  4.0*M_PI/(3.0*rc9);
2214             }
2215             /* Contribution beyond the cut-off */
2216             virs[0]  +=  8.0*M_PI/rc3;
2217             virs[1]  += -16.0*M_PI/(3.0*rc9);
2218         }
2219         else
2220         {
2221             gmx_fatal(FARGS,
2222                       "Dispersion correction is not implemented for vdw-type = %s",
2223                       evdw_names[fr->vdwtype]);
2224         }
2225
2226         /* When we deprecate the group kernels the code below can go too */
2227         if (fr->vdwtype == evdwPME && fr->cutoff_scheme == ecutsGROUP)
2228         {
2229             /* Calculate self-interaction coefficient (assuming that
2230              * the reciprocal-space contribution is constant in the
2231              * region that contributes to the self-interaction).
2232              */
2233             fr->enershiftsix = gmx::power6(fr->ewaldcoeff_lj) / 6.0;
2234
2235             eners[0] += -gmx::power3(std::sqrt(M_PI)*fr->ewaldcoeff_lj)/3.0;
2236             virs[0]  +=  gmx::power3(std::sqrt(M_PI)*fr->ewaldcoeff_lj);
2237         }
2238
2239         fr->enerdiffsix    = eners[0];
2240         fr->enerdifftwelve = eners[1];
2241         /* The 0.5 is due to the Gromacs definition of the virial */
2242         fr->virdiffsix     = 0.5*virs[0];
2243         fr->virdifftwelve  = 0.5*virs[1];
2244     }
2245 }
2246
2247 void calc_dispcorr(t_inputrec *ir, t_forcerec *fr,
2248                    matrix box, real lambda, tensor pres, tensor virial,
2249                    real *prescorr, real *enercorr, real *dvdlcorr)
2250 {
2251     gmx_bool bCorrAll, bCorrPres;
2252     real     dvdlambda, invvol, dens, ninter, avcsix, avctwelve, enerdiff, svir = 0, spres = 0;
2253     int      m;
2254
2255     *prescorr = 0;
2256     *enercorr = 0;
2257     *dvdlcorr = 0;
2258
2259     clear_mat(virial);
2260     clear_mat(pres);
2261
2262     if (ir->eDispCorr != edispcNO)
2263     {
2264         bCorrAll  = (ir->eDispCorr == edispcAllEner ||
2265                      ir->eDispCorr == edispcAllEnerPres);
2266         bCorrPres = (ir->eDispCorr == edispcEnerPres ||
2267                      ir->eDispCorr == edispcAllEnerPres);
2268
2269         invvol = 1/det(box);
2270         if (fr->n_tpi)
2271         {
2272             /* Only correct for the interactions with the inserted molecule */
2273             dens   = (fr->numAtomsForDispersionCorrection - fr->n_tpi)*invvol;
2274             ninter = fr->n_tpi;
2275         }
2276         else
2277         {
2278             dens   = fr->numAtomsForDispersionCorrection*invvol;
2279             ninter = 0.5*fr->numAtomsForDispersionCorrection;
2280         }
2281
2282         if (ir->efep == efepNO)
2283         {
2284             avcsix    = fr->avcsix[0];
2285             avctwelve = fr->avctwelve[0];
2286         }
2287         else
2288         {
2289             avcsix    = (1 - lambda)*fr->avcsix[0]    + lambda*fr->avcsix[1];
2290             avctwelve = (1 - lambda)*fr->avctwelve[0] + lambda*fr->avctwelve[1];
2291         }
2292
2293         enerdiff   = ninter*(dens*fr->enerdiffsix - fr->enershiftsix);
2294         *enercorr += avcsix*enerdiff;
2295         dvdlambda  = 0.0;
2296         if (ir->efep != efepNO)
2297         {
2298             dvdlambda += (fr->avcsix[1] - fr->avcsix[0])*enerdiff;
2299         }
2300         if (bCorrAll)
2301         {
2302             enerdiff   = ninter*(dens*fr->enerdifftwelve - fr->enershifttwelve);
2303             *enercorr += avctwelve*enerdiff;
2304             if (fr->efep != efepNO)
2305             {
2306                 dvdlambda += (fr->avctwelve[1] - fr->avctwelve[0])*enerdiff;
2307             }
2308         }
2309
2310         if (bCorrPres)
2311         {
2312             svir = ninter*dens*avcsix*fr->virdiffsix/3.0;
2313             if (ir->eDispCorr == edispcAllEnerPres)
2314             {
2315                 svir += ninter*dens*avctwelve*fr->virdifftwelve/3.0;
2316             }
2317             /* The factor 2 is because of the Gromacs virial definition */
2318             spres = -2.0*invvol*svir*PRESFAC;
2319
2320             for (m = 0; m < DIM; m++)
2321             {
2322                 virial[m][m] += svir;
2323                 pres[m][m]   += spres;
2324             }
2325             *prescorr += spres;
2326         }
2327
2328         /* Can't currently control when it prints, for now, just print when degugging */
2329         if (debug)
2330         {
2331             if (bCorrAll)
2332             {
2333                 fprintf(debug, "Long Range LJ corr.: <C6> %10.4e, <C12> %10.4e\n",
2334                         avcsix, avctwelve);
2335             }
2336             if (bCorrPres)
2337             {
2338                 fprintf(debug,
2339                         "Long Range LJ corr.: Epot %10g, Pres: %10g, Vir: %10g\n",
2340                         *enercorr, spres, svir);
2341             }
2342             else
2343             {
2344                 fprintf(debug, "Long Range LJ corr.: Epot %10g\n", *enercorr);
2345             }
2346         }
2347
2348         if (fr->efep != efepNO)
2349         {
2350             *dvdlcorr += dvdlambda;
2351         }
2352     }
2353 }
2354
2355 void do_pbc_first(FILE *fplog, matrix box, t_forcerec *fr,
2356                   t_graph *graph, rvec x[])
2357 {
2358     if (fplog)
2359     {
2360         fprintf(fplog, "Removing pbc first time\n");
2361     }
2362     calc_shifts(box, fr->shift_vec);
2363     if (graph)
2364     {
2365         mk_mshift(fplog, graph, fr->ePBC, box, x);
2366         if (gmx_debug_at)
2367         {
2368             p_graph(debug, "do_pbc_first 1", graph);
2369         }
2370         shift_self(graph, box, x);
2371         /* By doing an extra mk_mshift the molecules that are broken
2372          * because they were e.g. imported from another software
2373          * will be made whole again. Such are the healing powers
2374          * of GROMACS.
2375          */
2376         mk_mshift(fplog, graph, fr->ePBC, box, x);
2377         if (gmx_debug_at)
2378         {
2379             p_graph(debug, "do_pbc_first 2", graph);
2380         }
2381     }
2382     if (fplog)
2383     {
2384         fprintf(fplog, "Done rmpbc\n");
2385     }
2386 }
2387
2388 static void low_do_pbc_mtop(FILE *fplog, int ePBC, matrix box,
2389                             const gmx_mtop_t *mtop, rvec x[],
2390                             gmx_bool bFirst)
2391 {
2392     t_graph        *graph;
2393     int             mb, as, mol;
2394     gmx_molblock_t *molb;
2395
2396     if (bFirst && fplog)
2397     {
2398         fprintf(fplog, "Removing pbc first time\n");
2399     }
2400
2401     snew(graph, 1);
2402     as = 0;
2403     for (mb = 0; mb < mtop->nmolblock; mb++)
2404     {
2405         molb = &mtop->molblock[mb];
2406         if (molb->natoms_mol == 1 ||
2407             (!bFirst && mtop->moltype[molb->type].cgs.nr == 1))
2408         {
2409             /* Just one atom or charge group in the molecule, no PBC required */
2410             as += molb->nmol*molb->natoms_mol;
2411         }
2412         else
2413         {
2414             /* Pass NULL iso fplog to avoid graph prints for each molecule type */
2415             mk_graph_ilist(nullptr, mtop->moltype[molb->type].ilist,
2416                            0, molb->natoms_mol, FALSE, FALSE, graph);
2417
2418             for (mol = 0; mol < molb->nmol; mol++)
2419             {
2420                 mk_mshift(fplog, graph, ePBC, box, x+as);
2421
2422                 shift_self(graph, box, x+as);
2423                 /* The molecule is whole now.
2424                  * We don't need the second mk_mshift call as in do_pbc_first,
2425                  * since we no longer need this graph.
2426                  */
2427
2428                 as += molb->natoms_mol;
2429             }
2430             done_graph(graph);
2431         }
2432     }
2433     sfree(graph);
2434 }
2435
2436 void do_pbc_first_mtop(FILE *fplog, int ePBC, matrix box,
2437                        const gmx_mtop_t *mtop, rvec x[])
2438 {
2439     low_do_pbc_mtop(fplog, ePBC, box, mtop, x, TRUE);
2440 }
2441
2442 void do_pbc_mtop(FILE *fplog, int ePBC, matrix box,
2443                  gmx_mtop_t *mtop, rvec x[])
2444 {
2445     low_do_pbc_mtop(fplog, ePBC, box, mtop, x, FALSE);
2446 }
2447
2448 void put_atoms_in_box_omp(int ePBC, const matrix box, int natoms, rvec x[])
2449 {
2450     int t, nth;
2451     nth = gmx_omp_nthreads_get(emntDefault);
2452
2453 #pragma omp parallel for num_threads(nth) schedule(static)
2454     for (t = 0; t < nth; t++)
2455     {
2456         try
2457         {
2458             int offset, len;
2459
2460             offset = (natoms*t    )/nth;
2461             len    = (natoms*(t + 1))/nth - offset;
2462             put_atoms_in_box(ePBC, box, len, x + offset);
2463         }
2464         GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
2465     }
2466 }
2467
2468 // TODO This can be cleaned up a lot, and move back to runner.cpp
2469 void finish_run(FILE *fplog, const gmx::MDLogger &mdlog, t_commrec *cr,
2470                 t_inputrec *inputrec,
2471                 t_nrnb nrnb[], gmx_wallcycle_t wcycle,
2472                 gmx_walltime_accounting_t walltime_accounting,
2473                 nonbonded_verlet_t *nbv,
2474                 gmx_bool bWriteStat)
2475 {
2476     t_nrnb *nrnb_tot = nullptr;
2477     double  delta_t  = 0;
2478     double  nbfs     = 0, mflop = 0;
2479     double  elapsed_time,
2480             elapsed_time_over_all_ranks,
2481             elapsed_time_over_all_threads,
2482             elapsed_time_over_all_threads_over_all_ranks;
2483
2484     if (cr->nnodes > 1)
2485     {
2486         snew(nrnb_tot, 1);
2487 #if GMX_MPI
2488         MPI_Allreduce(nrnb->n, nrnb_tot->n, eNRNB, MPI_DOUBLE, MPI_SUM,
2489                       cr->mpi_comm_mysim);
2490 #endif
2491     }
2492     else
2493     {
2494         nrnb_tot = nrnb;
2495     }
2496
2497     elapsed_time                                 = walltime_accounting_get_elapsed_time(walltime_accounting);
2498     elapsed_time_over_all_ranks                  = elapsed_time;
2499     elapsed_time_over_all_threads                = walltime_accounting_get_elapsed_time_over_all_threads(walltime_accounting);
2500     elapsed_time_over_all_threads_over_all_ranks = elapsed_time_over_all_threads;
2501 #if GMX_MPI
2502     if (cr->nnodes > 1)
2503     {
2504         /* reduce elapsed_time over all MPI ranks in the current simulation */
2505         MPI_Allreduce(&elapsed_time,
2506                       &elapsed_time_over_all_ranks,
2507                       1, MPI_DOUBLE, MPI_SUM,
2508                       cr->mpi_comm_mysim);
2509         elapsed_time_over_all_ranks /= cr->nnodes;
2510         /* Reduce elapsed_time_over_all_threads over all MPI ranks in the
2511          * current simulation. */
2512         MPI_Allreduce(&elapsed_time_over_all_threads,
2513                       &elapsed_time_over_all_threads_over_all_ranks,
2514                       1, MPI_DOUBLE, MPI_SUM,
2515                       cr->mpi_comm_mysim);
2516     }
2517 #endif
2518
2519     if (SIMMASTER(cr))
2520     {
2521         print_flop(fplog, nrnb_tot, &nbfs, &mflop);
2522     }
2523     if (cr->nnodes > 1)
2524     {
2525         sfree(nrnb_tot);
2526     }
2527
2528     if ((cr->duty & DUTY_PP) && DOMAINDECOMP(cr))
2529     {
2530         print_dd_statistics(cr, inputrec, fplog);
2531     }
2532
2533     /* TODO Move the responsibility for any scaling by thread counts
2534      * to the code that handled the thread region, so that there's a
2535      * mechanism to keep cycle counting working during the transition
2536      * to task parallelism. */
2537     int nthreads_pp  = gmx_omp_nthreads_get(emntNonbonded);
2538     int nthreads_pme = gmx_omp_nthreads_get(emntPME);
2539     wallcycle_scale_by_num_threads(wcycle, cr->duty == DUTY_PME, nthreads_pp, nthreads_pme);
2540     auto cycle_sum(wallcycle_sum(cr, wcycle));
2541
2542     if (SIMMASTER(cr))
2543     {
2544         struct gmx_wallclock_gpu_t* gputimes = use_GPU(nbv) ? nbnxn_gpu_get_timings(nbv->gpu_nbv) : nullptr;
2545
2546         wallcycle_print(fplog, mdlog, cr->nnodes, cr->npmenodes, nthreads_pp, nthreads_pme,
2547                         elapsed_time_over_all_ranks,
2548                         wcycle, cycle_sum, gputimes);
2549
2550         if (EI_DYNAMICS(inputrec->eI))
2551         {
2552             delta_t = inputrec->delta_t;
2553         }
2554
2555         if (fplog)
2556         {
2557             print_perf(fplog, elapsed_time_over_all_threads_over_all_ranks,
2558                        elapsed_time_over_all_ranks,
2559                        walltime_accounting_get_nsteps_done(walltime_accounting),
2560                        delta_t, nbfs, mflop);
2561         }
2562         if (bWriteStat)
2563         {
2564             print_perf(stderr, elapsed_time_over_all_threads_over_all_ranks,
2565                        elapsed_time_over_all_ranks,
2566                        walltime_accounting_get_nsteps_done(walltime_accounting),
2567                        delta_t, nbfs, mflop);
2568         }
2569     }
2570 }
2571
2572 extern void initialize_lambdas(FILE *fplog, t_inputrec *ir, int *fep_state, gmx::ArrayRef<real> lambda, double *lam0)
2573 {
2574     /* this function works, but could probably use a logic rewrite to keep all the different
2575        types of efep straight. */
2576
2577     if ((ir->efep == efepNO) && (ir->bSimTemp == FALSE))
2578     {
2579         return;
2580     }
2581
2582     t_lambda *fep = ir->fepvals;
2583     *fep_state    = fep->init_fep_state; /* this might overwrite the checkpoint
2584                                             if checkpoint is set -- a kludge is in for now
2585                                             to prevent this.*/
2586
2587     for (int i = 0; i < efptNR; i++)
2588     {
2589         /* overwrite lambda state with init_lambda for now for backwards compatibility */
2590         if (fep->init_lambda >= 0) /* if it's -1, it was never initializd */
2591         {
2592             lambda[i] = fep->init_lambda;
2593             if (lam0)
2594             {
2595                 lam0[i] = lambda[i];
2596             }
2597         }
2598         else
2599         {
2600             lambda[i] = fep->all_lambda[i][*fep_state];
2601             if (lam0)
2602             {
2603                 lam0[i] = lambda[i];
2604             }
2605         }
2606     }
2607     if (ir->bSimTemp)
2608     {
2609         /* need to rescale control temperatures to match current state */
2610         for (int i = 0; i < ir->opts.ngtc; i++)
2611         {
2612             if (ir->opts.ref_t[i] > 0)
2613             {
2614                 ir->opts.ref_t[i] = ir->simtempvals->temperatures[*fep_state];
2615             }
2616         }
2617     }
2618
2619     /* Send to the log the information on the current lambdas */
2620     if (fplog != nullptr)
2621     {
2622         fprintf(fplog, "Initial vector of lambda components:[ ");
2623         for (const auto &l : lambda)
2624         {
2625             fprintf(fplog, "%10.4f ", l);
2626         }
2627         fprintf(fplog, "]\n");
2628     }
2629     return;
2630 }
2631
2632
2633 void init_md(FILE *fplog,
2634              t_commrec *cr, t_inputrec *ir, const gmx_output_env_t *oenv,
2635              double *t, double *t0,
2636              gmx::ArrayRef<real> lambda, int *fep_state, double *lam0,
2637              t_nrnb *nrnb, gmx_mtop_t *mtop,
2638              gmx_update_t **upd,
2639              int nfile, const t_filenm fnm[],
2640              gmx_mdoutf_t *outf, t_mdebin **mdebin,
2641              tensor force_vir, tensor shake_vir, rvec mu_tot,
2642              gmx_bool *bSimAnn, t_vcm **vcm, unsigned long Flags,
2643              gmx_wallcycle_t wcycle)
2644 {
2645     int  i;
2646
2647     /* Initial values */
2648     *t = *t0       = ir->init_t;
2649
2650     *bSimAnn = FALSE;
2651     for (i = 0; i < ir->opts.ngtc; i++)
2652     {
2653         /* set bSimAnn if any group is being annealed */
2654         if (ir->opts.annealing[i] != eannNO)
2655         {
2656             *bSimAnn = TRUE;
2657         }
2658     }
2659
2660     /* Initialize lambda variables */
2661     initialize_lambdas(fplog, ir, fep_state, lambda, lam0);
2662
2663     // TODO upd is never NULL in practice, but the analysers don't know that
2664     if (upd)
2665     {
2666         *upd = init_update(ir);
2667     }
2668     if (*bSimAnn)
2669     {
2670         update_annealing_target_temp(ir, ir->init_t, upd ? *upd : nullptr);
2671     }
2672
2673     if (vcm != nullptr)
2674     {
2675         *vcm = init_vcm(fplog, &mtop->groups, ir);
2676     }
2677
2678     if (EI_DYNAMICS(ir->eI) && !(Flags & MD_APPENDFILES))
2679     {
2680         if (ir->etc == etcBERENDSEN)
2681         {
2682             please_cite(fplog, "Berendsen84a");
2683         }
2684         if (ir->etc == etcVRESCALE)
2685         {
2686             please_cite(fplog, "Bussi2007a");
2687         }
2688         if (ir->eI == eiSD1)
2689         {
2690             please_cite(fplog, "Goga2012");
2691         }
2692     }
2693     init_nrnb(nrnb);
2694
2695     if (nfile != -1)
2696     {
2697         *outf = init_mdoutf(fplog, nfile, fnm, Flags, cr, ir, mtop, oenv, wcycle);
2698
2699         *mdebin = init_mdebin((Flags & MD_APPENDFILES) ? nullptr : mdoutf_get_fp_ene(*outf),
2700                               mtop, ir, mdoutf_get_fp_dhdl(*outf));
2701     }
2702
2703     /* Initiate variables */
2704     clear_mat(force_vir);
2705     clear_mat(shake_vir);
2706     clear_rvec(mu_tot);
2707 }