Revert "Eliminate mdlib/mdrun.h"
[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,2018,2019, 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 <cmath>
44 #include <cstdint>
45 #include <cstdio>
46 #include <cstring>
47
48 #include <array>
49
50 #include "gromacs/awh/awh.h"
51 #include "gromacs/domdec/dlbtiming.h"
52 #include "gromacs/domdec/domdec.h"
53 #include "gromacs/domdec/domdec_struct.h"
54 #include "gromacs/domdec/partition.h"
55 #include "gromacs/essentialdynamics/edsam.h"
56 #include "gromacs/ewald/pme.h"
57 #include "gromacs/gmxlib/chargegroup.h"
58 #include "gromacs/gmxlib/network.h"
59 #include "gromacs/gmxlib/nrnb.h"
60 #include "gromacs/gmxlib/nonbonded/nb_free_energy.h"
61 #include "gromacs/gmxlib/nonbonded/nb_kernel.h"
62 #include "gromacs/gmxlib/nonbonded/nonbonded.h"
63 #include "gromacs/gpu_utils/gpu_utils.h"
64 #include "gromacs/imd/imd.h"
65 #include "gromacs/listed_forces/bonded.h"
66 #include "gromacs/listed_forces/disre.h"
67 #include "gromacs/listed_forces/gpubonded.h"
68 #include "gromacs/listed_forces/manage_threading.h"
69 #include "gromacs/listed_forces/orires.h"
70 #include "gromacs/math/arrayrefwithpadding.h"
71 #include "gromacs/math/functions.h"
72 #include "gromacs/math/units.h"
73 #include "gromacs/math/vec.h"
74 #include "gromacs/math/vecdump.h"
75 #include "gromacs/mdlib/calcmu.h"
76 #include "gromacs/mdlib/calcvir.h"
77 #include "gromacs/mdlib/constr.h"
78 #include "gromacs/mdlib/force.h"
79 #include "gromacs/mdlib/forcerec.h"
80 #include "gromacs/mdlib/gmx_omp_nthreads.h"
81 #include "gromacs/mdlib/mdrun.h"
82 #include "gromacs/mdlib/ppforceworkload.h"
83 #include "gromacs/mdlib/qmmm.h"
84 #include "gromacs/mdlib/update.h"
85 #include "gromacs/mdtypes/commrec.h"
86 #include "gromacs/mdtypes/enerdata.h"
87 #include "gromacs/mdtypes/forceoutput.h"
88 #include "gromacs/mdtypes/iforceprovider.h"
89 #include "gromacs/mdtypes/inputrec.h"
90 #include "gromacs/mdtypes/md_enums.h"
91 #include "gromacs/mdtypes/state.h"
92 #include "gromacs/nbnxm/atomdata.h"
93 #include "gromacs/nbnxm/gpu_data_mgmt.h"
94 #include "gromacs/nbnxm/nbnxm.h"
95 #include "gromacs/pbcutil/ishift.h"
96 #include "gromacs/pbcutil/mshift.h"
97 #include "gromacs/pbcutil/pbc.h"
98 #include "gromacs/pulling/pull.h"
99 #include "gromacs/pulling/pull_rotation.h"
100 #include "gromacs/timing/cyclecounter.h"
101 #include "gromacs/timing/gpu_timing.h"
102 #include "gromacs/timing/wallcycle.h"
103 #include "gromacs/timing/wallcyclereporting.h"
104 #include "gromacs/timing/walltime_accounting.h"
105 #include "gromacs/topology/topology.h"
106 #include "gromacs/utility/arrayref.h"
107 #include "gromacs/utility/basedefinitions.h"
108 #include "gromacs/utility/cstringutil.h"
109 #include "gromacs/utility/exceptions.h"
110 #include "gromacs/utility/fatalerror.h"
111 #include "gromacs/utility/gmxassert.h"
112 #include "gromacs/utility/gmxmpi.h"
113 #include "gromacs/utility/logger.h"
114 #include "gromacs/utility/smalloc.h"
115 #include "gromacs/utility/strconvert.h"
116 #include "gromacs/utility/sysinfo.h"
117
118 // TODO: this environment variable allows us to verify before release
119 // that on less common architectures the total cost of polling is not larger than
120 // a blocking wait (so polling does not introduce overhead when the static
121 // PME-first ordering would suffice).
122 static const bool c_disableAlternatingWait = (getenv("GMX_DISABLE_ALTERNATING_GPU_WAIT") != nullptr);
123
124
125 static void sum_forces(rvec f[], gmx::ArrayRef<const gmx::RVec> forceToAdd)
126 {
127     const int      end = forceToAdd.size();
128
129     int gmx_unused nt = gmx_omp_nthreads_get(emntDefault);
130 #pragma omp parallel for num_threads(nt) schedule(static)
131     for (int i = 0; i < end; i++)
132     {
133         rvec_inc(f[i], forceToAdd[i]);
134     }
135 }
136
137 static void calc_virial(int start, int homenr, const rvec x[], const rvec f[],
138                         tensor vir_part, const t_graph *graph, const matrix box,
139                         t_nrnb *nrnb, const t_forcerec *fr, int ePBC)
140 {
141     /* The short-range virial from surrounding boxes */
142     calc_vir(SHIFTS, fr->shift_vec, fr->fshift, vir_part, ePBC == epbcSCREW, box);
143     inc_nrnb(nrnb, eNR_VIRIAL, SHIFTS);
144
145     /* Calculate partial virial, for local atoms only, based on short range.
146      * Total virial is computed in global_stat, called from do_md
147      */
148     f_calc_vir(start, start+homenr, x, f, vir_part, graph, box);
149     inc_nrnb(nrnb, eNR_VIRIAL, homenr);
150
151     if (debug)
152     {
153         pr_rvecs(debug, 0, "vir_part", vir_part, DIM);
154     }
155 }
156
157 static void pull_potential_wrapper(const t_commrec *cr,
158                                    const t_inputrec *ir,
159                                    const matrix box, gmx::ArrayRef<const gmx::RVec> x,
160                                    gmx::ForceWithVirial *force,
161                                    const t_mdatoms *mdatoms,
162                                    gmx_enerdata_t *enerd,
163                                    const real *lambda,
164                                    double t,
165                                    gmx_wallcycle_t wcycle)
166 {
167     t_pbc  pbc;
168     real   dvdl;
169
170     /* Calculate the center of mass forces, this requires communication,
171      * which is why pull_potential is called close to other communication.
172      */
173     wallcycle_start(wcycle, ewcPULLPOT);
174     set_pbc(&pbc, ir->ePBC, box);
175     dvdl                     = 0;
176     enerd->term[F_COM_PULL] +=
177         pull_potential(ir->pull_work, mdatoms, &pbc,
178                        cr, t, lambda[efptRESTRAINT], as_rvec_array(x.data()), force, &dvdl);
179     enerd->dvdl_lin[efptRESTRAINT] += dvdl;
180     wallcycle_stop(wcycle, ewcPULLPOT);
181 }
182
183 static void pme_receive_force_ener(const t_commrec      *cr,
184                                    gmx::ForceWithVirial *forceWithVirial,
185                                    gmx_enerdata_t       *enerd,
186                                    gmx_wallcycle_t       wcycle)
187 {
188     real   e_q, e_lj, dvdl_q, dvdl_lj;
189     float  cycles_ppdpme, cycles_seppme;
190
191     cycles_ppdpme = wallcycle_stop(wcycle, ewcPPDURINGPME);
192     dd_cycles_add(cr->dd, cycles_ppdpme, ddCyclPPduringPME);
193
194     /* In case of node-splitting, the PP nodes receive the long-range
195      * forces, virial and energy from the PME nodes here.
196      */
197     wallcycle_start(wcycle, ewcPP_PMEWAITRECVF);
198     dvdl_q  = 0;
199     dvdl_lj = 0;
200     gmx_pme_receive_f(cr, forceWithVirial, &e_q, &e_lj, &dvdl_q, &dvdl_lj,
201                       &cycles_seppme);
202     enerd->term[F_COUL_RECIP] += e_q;
203     enerd->term[F_LJ_RECIP]   += e_lj;
204     enerd->dvdl_lin[efptCOUL] += dvdl_q;
205     enerd->dvdl_lin[efptVDW]  += dvdl_lj;
206
207     if (wcycle)
208     {
209         dd_cycles_add(cr->dd, cycles_seppme, ddCyclPME);
210     }
211     wallcycle_stop(wcycle, ewcPP_PMEWAITRECVF);
212 }
213
214 static void print_large_forces(FILE            *fp,
215                                const t_mdatoms *md,
216                                const t_commrec *cr,
217                                int64_t          step,
218                                real             forceTolerance,
219                                const rvec      *x,
220                                const rvec      *f)
221 {
222     real           force2Tolerance = gmx::square(forceTolerance);
223     gmx::index     numNonFinite    = 0;
224     for (int i = 0; i < md->homenr; i++)
225     {
226         real force2    = norm2(f[i]);
227         bool nonFinite = !std::isfinite(force2);
228         if (force2 >= force2Tolerance || nonFinite)
229         {
230             fprintf(fp, "step %" PRId64 " atom %6d  x %8.3f %8.3f %8.3f  force %12.5e\n",
231                     step,
232                     ddglatnr(cr->dd, i), x[i][XX], x[i][YY], x[i][ZZ], std::sqrt(force2));
233         }
234         if (nonFinite)
235         {
236             numNonFinite++;
237         }
238     }
239     if (numNonFinite > 0)
240     {
241         /* Note that with MPI this fatal call on one rank might interrupt
242          * the printing on other ranks. But we can only avoid that with
243          * an expensive MPI barrier that we would need at each step.
244          */
245         gmx_fatal(FARGS, "At step %" PRId64 " detected non-finite forces on %td atoms", step, numNonFinite);
246     }
247 }
248
249 static void post_process_forces(const t_commrec           *cr,
250                                 int64_t                    step,
251                                 t_nrnb                    *nrnb,
252                                 gmx_wallcycle_t            wcycle,
253                                 const gmx_localtop_t      *top,
254                                 const matrix               box,
255                                 const rvec                 x[],
256                                 rvec                       f[],
257                                 gmx::ForceWithVirial      *forceWithVirial,
258                                 tensor                     vir_force,
259                                 const t_mdatoms           *mdatoms,
260                                 const t_graph             *graph,
261                                 const t_forcerec          *fr,
262                                 const gmx_vsite_t         *vsite,
263                                 int                        flags)
264 {
265     if (fr->haveDirectVirialContributions)
266     {
267         rvec *fDirectVir = as_rvec_array(forceWithVirial->force_.data());
268
269         if (vsite)
270         {
271             /* Spread the mesh force on virtual sites to the other particles...
272              * This is parallellized. MPI communication is performed
273              * if the constructing atoms aren't local.
274              */
275             matrix virial = { { 0 } };
276             spread_vsite_f(vsite, x, fDirectVir, nullptr,
277                            (flags & GMX_FORCE_VIRIAL) != 0, virial,
278                            nrnb,
279                            &top->idef, fr->ePBC, fr->bMolPBC, graph, box, cr, wcycle);
280             forceWithVirial->addVirialContribution(virial);
281         }
282
283         if (flags & GMX_FORCE_VIRIAL)
284         {
285             /* Now add the forces, this is local */
286             sum_forces(f, forceWithVirial->force_);
287
288             /* Add the direct virial contributions */
289             GMX_ASSERT(forceWithVirial->computeVirial_, "forceWithVirial should request virial computation when we request the virial");
290             m_add(vir_force, forceWithVirial->getVirial(), vir_force);
291
292             if (debug)
293             {
294                 pr_rvecs(debug, 0, "vir_force", vir_force, DIM);
295             }
296         }
297     }
298
299     if (fr->print_force >= 0)
300     {
301         print_large_forces(stderr, mdatoms, cr, step, fr->print_force, x, f);
302     }
303 }
304
305 static void do_nb_verlet(t_forcerec                       *fr,
306                          const interaction_const_t        *ic,
307                          gmx_enerdata_t                   *enerd,
308                          const int                         flags,
309                          const Nbnxm::InteractionLocality  ilocality,
310                          const int                         clearF,
311                          const int64_t                     step,
312                          t_nrnb                           *nrnb,
313                          gmx_wallcycle_t                   wcycle)
314 {
315     if (!(flags & GMX_FORCE_NONBONDED))
316     {
317         /* skip non-bonded calculation */
318         return;
319     }
320
321     nonbonded_verlet_t *nbv  = fr->nbv.get();
322
323     /* GPU kernel launch overhead is already timed separately */
324     if (fr->cutoff_scheme != ecutsVERLET)
325     {
326         gmx_incons("Invalid cut-off scheme passed!");
327     }
328
329     if (!nbv->useGpu())
330     {
331         /* When dynamic pair-list  pruning is requested, we need to prune
332          * at nstlistPrune steps.
333          */
334         if (nbv->pairlistSets().isDynamicPruningStepCpu(step))
335         {
336             /* Prune the pair-list beyond fr->ic->rlistPrune using
337              * the current coordinates of the atoms.
338              */
339             wallcycle_sub_start(wcycle, ewcsNONBONDED_PRUNING);
340             nbv->dispatchPruneKernelCpu(ilocality, fr->shift_vec);
341             wallcycle_sub_stop(wcycle, ewcsNONBONDED_PRUNING);
342         }
343
344         wallcycle_sub_start(wcycle, ewcsNONBONDED);
345     }
346
347     nbv->dispatchNonbondedKernel(ilocality, *ic, flags, clearF, fr, enerd, nrnb);
348
349     if (!nbv->useGpu())
350     {
351         wallcycle_sub_stop(wcycle, ewcsNONBONDED);
352     }
353 }
354
355 gmx_bool use_GPU(const nonbonded_verlet_t *nbv)
356 {
357     return nbv != nullptr && nbv->useGpu();
358 }
359
360 static inline void clear_rvecs_omp(int n, rvec v[])
361 {
362     int nth = gmx_omp_nthreads_get_simple_rvec_task(emntDefault, n);
363
364     /* Note that we would like to avoid this conditional by putting it
365      * into the omp pragma instead, but then we still take the full
366      * omp parallel for overhead (at least with gcc5).
367      */
368     if (nth == 1)
369     {
370         for (int i = 0; i < n; i++)
371         {
372             clear_rvec(v[i]);
373         }
374     }
375     else
376     {
377 #pragma omp parallel for num_threads(nth) schedule(static)
378         for (int i = 0; i < n; i++)
379         {
380             clear_rvec(v[i]);
381         }
382     }
383 }
384
385 /*! \brief Return an estimate of the average kinetic energy or 0 when unreliable
386  *
387  * \param groupOptions  Group options, containing T-coupling options
388  */
389 static real averageKineticEnergyEstimate(const t_grpopts &groupOptions)
390 {
391     real nrdfCoupled   = 0;
392     real nrdfUncoupled = 0;
393     real kineticEnergy = 0;
394     for (int g = 0; g < groupOptions.ngtc; g++)
395     {
396         if (groupOptions.tau_t[g] >= 0)
397         {
398             nrdfCoupled   += groupOptions.nrdf[g];
399             kineticEnergy += groupOptions.nrdf[g]*0.5*groupOptions.ref_t[g]*BOLTZ;
400         }
401         else
402         {
403             nrdfUncoupled += groupOptions.nrdf[g];
404         }
405     }
406
407     /* This conditional with > also catches nrdf=0 */
408     if (nrdfCoupled > nrdfUncoupled)
409     {
410         return kineticEnergy*(nrdfCoupled + nrdfUncoupled)/nrdfCoupled;
411     }
412     else
413     {
414         return 0;
415     }
416 }
417
418 /*! \brief This routine checks that the potential energy is finite.
419  *
420  * Always checks that the potential energy is finite. If step equals
421  * inputrec.init_step also checks that the magnitude of the potential energy
422  * is reasonable. Terminates with a fatal error when a check fails.
423  * Note that passing this check does not guarantee finite forces,
424  * since those use slightly different arithmetics. But in most cases
425  * there is just a narrow coordinate range where forces are not finite
426  * and energies are finite.
427  *
428  * \param[in] step      The step number, used for checking and printing
429  * \param[in] enerd     The energy data; the non-bonded group energies need to be added to enerd.term[F_EPOT] before calling this routine
430  * \param[in] inputrec  The input record
431  */
432 static void checkPotentialEnergyValidity(int64_t               step,
433                                          const gmx_enerdata_t &enerd,
434                                          const t_inputrec     &inputrec)
435 {
436     /* Threshold valid for comparing absolute potential energy against
437      * the kinetic energy. Normally one should not consider absolute
438      * potential energy values, but with a factor of one million
439      * we should never get false positives.
440      */
441     constexpr real c_thresholdFactor = 1e6;
442
443     bool           energyIsNotFinite    = !std::isfinite(enerd.term[F_EPOT]);
444     real           averageKineticEnergy = 0;
445     /* We only check for large potential energy at the initial step,
446      * because that is by far the most likely step for this too occur
447      * and because computing the average kinetic energy is not free.
448      * Note: nstcalcenergy >> 1 often does not allow to catch large energies
449      * before they become NaN.
450      */
451     if (step == inputrec.init_step && EI_DYNAMICS(inputrec.eI))
452     {
453         averageKineticEnergy = averageKineticEnergyEstimate(inputrec.opts);
454     }
455
456     if (energyIsNotFinite || (averageKineticEnergy > 0 &&
457                               enerd.term[F_EPOT] > c_thresholdFactor*averageKineticEnergy))
458     {
459         gmx_fatal(FARGS, "Step %" PRId64 ": The total potential energy is %g, which is %s. The LJ and electrostatic contributions to the energy are %g and %g, respectively. A %s potential energy can be caused by overlapping interactions in bonded interactions or very large%s coordinate values. Usually this is caused by a badly- or non-equilibrated initial configuration, incorrect interactions or parameters in the topology.",
460                   step,
461                   enerd.term[F_EPOT],
462                   energyIsNotFinite ? "not finite" : "extremely high",
463                   enerd.term[F_LJ],
464                   enerd.term[F_COUL_SR],
465                   energyIsNotFinite ? "non-finite" : "very high",
466                   energyIsNotFinite ? " or Nan" : "");
467     }
468 }
469
470 /*! \brief Compute forces and/or energies for special algorithms
471  *
472  * The intention is to collect all calls to algorithms that compute
473  * forces on local atoms only and that do not contribute to the local
474  * virial sum (but add their virial contribution separately).
475  * Eventually these should likely all become ForceProviders.
476  * Within this function the intention is to have algorithms that do
477  * global communication at the end, so global barriers within the MD loop
478  * are as close together as possible.
479  *
480  * \param[in]     fplog            The log file
481  * \param[in]     cr               The communication record
482  * \param[in]     inputrec         The input record
483  * \param[in]     awh              The Awh module (nullptr if none in use).
484  * \param[in]     enforcedRotation Enforced rotation module.
485  * \param[in]     step             The current MD step
486  * \param[in]     t                The current time
487  * \param[in,out] wcycle           Wallcycle accounting struct
488  * \param[in,out] forceProviders   Pointer to a list of force providers
489  * \param[in]     box              The unit cell
490  * \param[in]     x                The coordinates
491  * \param[in]     mdatoms          Per atom properties
492  * \param[in]     lambda           Array of free-energy lambda values
493  * \param[in]     forceFlags       Flags that tell whether we should compute forces/energies/virial
494  * \param[in,out] forceWithVirial  Force and virial buffers
495  * \param[in,out] enerd            Energy buffer
496  * \param[in,out] ed               Essential dynamics pointer
497  * \param[in]     bNS              Tells if we did neighbor searching this step, used for ED sampling
498  *
499  * \todo Remove bNS, which is used incorrectly.
500  * \todo Convert all other algorithms called here to ForceProviders.
501  */
502 static void
503 computeSpecialForces(FILE                          *fplog,
504                      const t_commrec               *cr,
505                      const t_inputrec              *inputrec,
506                      gmx::Awh                      *awh,
507                      gmx_enfrot                    *enforcedRotation,
508                      int64_t                        step,
509                      double                         t,
510                      gmx_wallcycle_t                wcycle,
511                      ForceProviders                *forceProviders,
512                      matrix                         box,
513                      gmx::ArrayRef<const gmx::RVec> x,
514                      const t_mdatoms               *mdatoms,
515                      real                          *lambda,
516                      int                            forceFlags,
517                      gmx::ForceWithVirial          *forceWithVirial,
518                      gmx_enerdata_t                *enerd,
519                      gmx_edsam                     *ed,
520                      gmx_bool                       bNS)
521 {
522     const bool computeForces = (forceFlags & GMX_FORCE_FORCES) != 0;
523
524     /* NOTE: Currently all ForceProviders only provide forces.
525      *       When they also provide energies, remove this conditional.
526      */
527     if (computeForces)
528     {
529         gmx::ForceProviderInput  forceProviderInput(x, *mdatoms, t, box, *cr);
530         gmx::ForceProviderOutput forceProviderOutput(forceWithVirial, enerd);
531
532         /* Collect forces from modules */
533         forceProviders->calculateForces(forceProviderInput, &forceProviderOutput);
534     }
535
536     if (inputrec->bPull && pull_have_potential(inputrec->pull_work))
537     {
538         pull_potential_wrapper(cr, inputrec, box, x,
539                                forceWithVirial,
540                                mdatoms, enerd, lambda, t,
541                                wcycle);
542
543         if (awh)
544         {
545             enerd->term[F_COM_PULL] +=
546                 awh->applyBiasForcesAndUpdateBias(inputrec->ePBC, *mdatoms, box,
547                                                   forceWithVirial,
548                                                   t, step, wcycle, fplog);
549         }
550     }
551
552     rvec *f = as_rvec_array(forceWithVirial->force_.data());
553
554     /* Add the forces from enforced rotation potentials (if any) */
555     if (inputrec->bRot)
556     {
557         wallcycle_start(wcycle, ewcROTadd);
558         enerd->term[F_COM_PULL] += add_rot_forces(enforcedRotation, f, cr, step, t);
559         wallcycle_stop(wcycle, ewcROTadd);
560     }
561
562     if (ed)
563     {
564         /* Note that since init_edsam() is called after the initialization
565          * of forcerec, edsam doesn't request the noVirSum force buffer.
566          * Thus if no other algorithm (e.g. PME) requires it, the forces
567          * here will contribute to the virial.
568          */
569         do_flood(cr, inputrec, as_rvec_array(x.data()), f, ed, box, step, bNS);
570     }
571
572     /* Add forces from interactive molecular dynamics (IMD), if bIMD == TRUE. */
573     if (inputrec->bIMD && computeForces)
574     {
575         IMD_apply_forces(inputrec->bIMD, inputrec->imd, cr, f, wcycle);
576     }
577 }
578
579 /*! \brief Launch the prepare_step and spread stages of PME GPU.
580  *
581  * \param[in]  pmedata       The PME structure
582  * \param[in]  box           The box matrix
583  * \param[in]  x             Coordinate array
584  * \param[in]  flags         Force flags
585  * \param[in]  pmeFlags      PME flags
586  * \param[in]  wcycle        The wallcycle structure
587  */
588 static inline void launchPmeGpuSpread(gmx_pme_t      *pmedata,
589                                       matrix          box,
590                                       rvec            x[],
591                                       int             flags,
592                                       int             pmeFlags,
593                                       gmx_wallcycle_t wcycle)
594 {
595     pme_gpu_prepare_computation(pmedata, (flags & GMX_FORCE_DYNAMICBOX) != 0, box, wcycle, pmeFlags);
596     pme_gpu_launch_spread(pmedata, x, wcycle);
597 }
598
599 /*! \brief Launch the FFT and gather stages of PME GPU
600  *
601  * This function only implements setting the output forces (no accumulation).
602  *
603  * \param[in]  pmedata        The PME structure
604  * \param[in]  wcycle         The wallcycle structure
605  */
606 static void launchPmeGpuFftAndGather(gmx_pme_t        *pmedata,
607                                      gmx_wallcycle_t   wcycle)
608 {
609     pme_gpu_launch_complex_transforms(pmedata, wcycle);
610     pme_gpu_launch_gather(pmedata, wcycle, PmeForceOutputHandling::Set);
611 }
612
613 /*! \brief
614  *  Polling wait for either of the PME or nonbonded GPU tasks.
615  *
616  * Instead of a static order in waiting for GPU tasks, this function
617  * polls checking which of the two tasks completes first, and does the
618  * associated force buffer reduction overlapped with the other task.
619  * By doing that, unlike static scheduling order, it can always overlap
620  * one of the reductions, regardless of the GPU task completion order.
621  *
622  * \param[in]     nbv              Nonbonded verlet structure
623  * \param[in,out] pmedata          PME module data
624  * \param[in,out] force            Force array to reduce task outputs into.
625  * \param[in,out] forceWithVirial  Force and virial buffers
626  * \param[in,out] fshift           Shift force output vector results are reduced into
627  * \param[in,out] enerd            Energy data structure results are reduced into
628  * \param[in]     flags            Force flags
629  * \param[in]     pmeFlags         PME flags
630  * \param[in]     haveOtherWork    Tells whether there is other work than non-bonded in the stream(s)
631  * \param[in]     wcycle           The wallcycle structure
632  */
633 static void alternatePmeNbGpuWaitReduce(nonbonded_verlet_t                  *nbv,
634                                         gmx_pme_t                           *pmedata,
635                                         gmx::ArrayRefWithPadding<gmx::RVec> *force,
636                                         gmx::ForceWithVirial                *forceWithVirial,
637                                         rvec                                 fshift[],
638                                         gmx_enerdata_t                      *enerd,
639                                         int                                  flags,
640                                         int                                  pmeFlags,
641                                         bool                                 haveOtherWork,
642                                         gmx_wallcycle_t                      wcycle)
643 {
644     bool isPmeGpuDone = false;
645     bool isNbGpuDone  = false;
646
647
648     gmx::ArrayRef<const gmx::RVec> pmeGpuForces;
649
650     while (!isPmeGpuDone || !isNbGpuDone)
651     {
652         if (!isPmeGpuDone)
653         {
654             GpuTaskCompletion completionType = (isNbGpuDone) ? GpuTaskCompletion::Wait : GpuTaskCompletion::Check;
655             isPmeGpuDone = pme_gpu_try_finish_task(pmedata, pmeFlags, wcycle, forceWithVirial, enerd, completionType);
656         }
657
658         if (!isNbGpuDone)
659         {
660             GpuTaskCompletion completionType = (isPmeGpuDone) ? GpuTaskCompletion::Wait : GpuTaskCompletion::Check;
661             wallcycle_start_nocount(wcycle, ewcWAIT_GPU_NB_L);
662             isNbGpuDone = Nbnxm::gpu_try_finish_task(nbv->gpu_nbv,
663                                                      flags,
664                                                      Nbnxm::AtomLocality::Local,
665                                                      haveOtherWork,
666                                                      enerd->grpp.ener[egLJSR], enerd->grpp.ener[egCOULSR],
667                                                      fshift, completionType);
668             wallcycle_stop(wcycle, ewcWAIT_GPU_NB_L);
669             // To get the call count right, when the task finished we
670             // issue a start/stop.
671             // TODO: move the ewcWAIT_GPU_NB_L cycle counting into nbnxn_gpu_try_finish_task()
672             // and ewcNB_XF_BUF_OPS counting into nbnxn_atomdata_add_nbat_f_to_f().
673             if (isNbGpuDone)
674             {
675                 wallcycle_start(wcycle, ewcWAIT_GPU_NB_L);
676                 wallcycle_stop(wcycle, ewcWAIT_GPU_NB_L);
677
678                 nbv->atomdata_add_nbat_f_to_f(Nbnxm::AtomLocality::Local,
679                                               as_rvec_array(force->unpaddedArrayRef().data()), wcycle);
680             }
681         }
682     }
683 }
684
685 /*! \brief Hack structure with force ouput buffers for do_force */
686 struct ForceOutputs
687 {
688     //! Constructor
689     ForceOutputs(rvec *f, gmx::ForceWithVirial const forceWithVirial) :
690         f(f),
691         forceWithVirial(forceWithVirial) {}
692
693     //! Force output buffer used by legacy modules
694     rvec                 *const f;
695     //! Force with direct virial contribution (if there are any)
696     gmx::ForceWithVirial        forceWithVirial;
697 };
698
699 /*! \brief Set up the different force buffers; also does clearing.
700  *
701  * \param[in] fr        force record pointer
702  * \param[in] inputrec  input record
703  * \param[in] force     force array
704  * \param[in] bDoForces True if force are computed this step
705  * \param[in] doVirial  True if virial is computed this step
706  * \param[out] wcycle   wallcycle recording structure
707  *
708  * \returns             Cleared force output structure
709  */
710 static ForceOutputs
711 setupForceOutputs(const t_forcerec                    *fr,
712                   const t_inputrec                    &inputrec,
713                   gmx::ArrayRefWithPadding<gmx::RVec>  force,
714                   const bool                           bDoForces,
715                   const bool                           doVirial,
716                   gmx_wallcycle_t                      wcycle)
717 {
718     wallcycle_sub_start(wcycle, ewcsCLEAR_FORCE_BUFFER);
719
720     /* Temporary solution until all routines take PaddedRVecVector */
721     rvec *const f = as_rvec_array(force.unpaddedArrayRef().data());
722     if (bDoForces)
723     {
724         /* Clear the short- and long-range forces */
725         clear_rvecs_omp(fr->natoms_force_constr, f);
726     }
727
728     /* If we need to compute the virial, we might need a separate
729      * force buffer for algorithms for which the virial is calculated
730      * directly, such as PME. Otherwise, forceWithVirial uses the
731      * the same force (f in legacy calls) buffer as other algorithms.
732      */
733     const bool useSeparateForceWithVirialBuffer = (bDoForces && (doVirial && fr->haveDirectVirialContributions));
734
735
736     /* forceWithVirial uses the local atom range only */
737     gmx::ForceWithVirial forceWithVirial (useSeparateForceWithVirialBuffer ?
738                                           *fr->forceBufferForDirectVirialContributions : force.unpaddedArrayRef(),
739                                           doVirial);
740
741     if (useSeparateForceWithVirialBuffer)
742     {
743         /* TODO: update comment
744          * We only compute forces on local atoms. Note that vsites can
745          * spread to non-local atoms, but that part of the buffer is
746          * cleared separately in the vsite spreading code.
747          */
748         clear_rvecs_omp(forceWithVirial.force_.size(), as_rvec_array(forceWithVirial.force_.data()));
749     }
750
751     if (inputrec.bPull && pull_have_constraint(inputrec.pull_work))
752     {
753         clear_pull_forces(inputrec.pull_work);
754     }
755
756     wallcycle_sub_stop(wcycle, ewcsCLEAR_FORCE_BUFFER);
757
758     return ForceOutputs(f, forceWithVirial);
759 }
760
761
762 static void do_force_cutsVERLET(FILE *fplog,
763                                 const t_commrec *cr,
764                                 const gmx_multisim_t *ms,
765                                 const t_inputrec *inputrec,
766                                 gmx::Awh *awh,
767                                 gmx_enfrot *enforcedRotation,
768                                 int64_t step,
769                                 t_nrnb *nrnb,
770                                 gmx_wallcycle_t wcycle,
771                                 const gmx_localtop_t *top,
772                                 const gmx_groups_t * /* groups */,
773                                 matrix box, gmx::ArrayRefWithPadding<gmx::RVec> x,
774                                 history_t *hist,
775                                 gmx::ArrayRefWithPadding<gmx::RVec> force,
776                                 tensor vir_force,
777                                 const t_mdatoms *mdatoms,
778                                 gmx_enerdata_t *enerd, t_fcdata *fcd,
779                                 real *lambda,
780                                 t_graph *graph,
781                                 t_forcerec *fr,
782                                 gmx::PpForceWorkload *ppForceWorkload,
783                                 interaction_const_t *ic,
784                                 const gmx_vsite_t *vsite,
785                                 rvec mu_tot,
786                                 double t,
787                                 gmx_edsam *ed,
788                                 const int flags,
789                                 const DDBalanceRegionHandler &ddBalanceRegionHandler)
790 {
791     int                 cg1, i, j;
792     double              mu[2*DIM];
793     gmx_bool            bStateChanged, bNS, bFillGrid, bCalcCGCM;
794     gmx_bool            bDoForces, bUseGPU, bUseOrEmulGPU;
795     rvec                vzero, box_diag;
796     float               cycles_pme, cycles_wait_gpu;
797     nonbonded_verlet_t *nbv = fr->nbv.get();
798
799     bStateChanged = ((flags & GMX_FORCE_STATECHANGED) != 0);
800     bNS           = ((flags & GMX_FORCE_NS) != 0);
801     bFillGrid     = (bNS && bStateChanged);
802     bCalcCGCM     = (bFillGrid && !DOMAINDECOMP(cr));
803     bDoForces     = ((flags & GMX_FORCE_FORCES) != 0);
804     bUseGPU       = fr->nbv->useGpu();
805     bUseOrEmulGPU = bUseGPU || fr->nbv->emulateGpu();
806
807     const auto pmeRunMode = fr->pmedata ? pme_run_mode(fr->pmedata) : PmeRunMode::CPU;
808     // TODO slim this conditional down - inputrec and duty checks should mean the same in proper code!
809     const bool useGpuPme  = EEL_PME(fr->ic->eeltype) && thisRankHasDuty(cr, DUTY_PME) &&
810         ((pmeRunMode == PmeRunMode::GPU) || (pmeRunMode == PmeRunMode::Mixed));
811     const int  pmeFlags = GMX_PME_SPREAD | GMX_PME_SOLVE |
812         ((flags & GMX_FORCE_VIRIAL) ? GMX_PME_CALC_ENER_VIR : 0) |
813         ((flags & GMX_FORCE_ENERGY) ? GMX_PME_CALC_ENER_VIR : 0) |
814         ((flags & GMX_FORCE_FORCES) ? GMX_PME_CALC_F : 0);
815
816     /* At a search step we need to start the first balancing region
817      * somewhere early inside the step after communication during domain
818      * decomposition (and not during the previous step as usual).
819      */
820     if (bNS)
821     {
822         ddBalanceRegionHandler.openBeforeForceComputationCpu(DdAllowBalanceRegionReopen::yes);
823     }
824
825     cycles_wait_gpu = 0;
826
827     const int start  = 0;
828     const int homenr = mdatoms->homenr;
829
830     clear_mat(vir_force);
831
832     if (DOMAINDECOMP(cr))
833     {
834         cg1 = cr->dd->globalAtomGroupIndices.size();
835     }
836     else
837     {
838         cg1 = top->cgs.nr;
839     }
840     if (fr->n_tpi > 0)
841     {
842         cg1--;
843     }
844
845     if (bStateChanged)
846     {
847         update_forcerec(fr, box);
848
849         if (inputrecNeedMutot(inputrec))
850         {
851             /* Calculate total (local) dipole moment in a temporary common array.
852              * This makes it possible to sum them over nodes faster.
853              */
854             calc_mu(start, homenr,
855                     x.unpaddedArrayRef(), mdatoms->chargeA, mdatoms->chargeB, mdatoms->nChargePerturbed,
856                     mu, mu+DIM);
857         }
858     }
859
860     if (fr->ePBC != epbcNONE)
861     {
862         /* Compute shift vectors every step,
863          * because of pressure coupling or box deformation!
864          */
865         if ((flags & GMX_FORCE_DYNAMICBOX) && bStateChanged)
866         {
867             calc_shifts(box, fr->shift_vec);
868         }
869
870         if (bCalcCGCM)
871         {
872             put_atoms_in_box_omp(fr->ePBC, box, x.unpaddedArrayRef().subArray(0, homenr));
873             inc_nrnb(nrnb, eNR_SHIFTX, homenr);
874         }
875         else if (EI_ENERGY_MINIMIZATION(inputrec->eI) && graph)
876         {
877             unshift_self(graph, box, as_rvec_array(x.unpaddedArrayRef().data()));
878         }
879     }
880
881     nbnxn_atomdata_copy_shiftvec((flags & GMX_FORCE_DYNAMICBOX) != 0,
882                                  fr->shift_vec, nbv->nbat.get());
883
884 #if GMX_MPI
885     if (!thisRankHasDuty(cr, DUTY_PME))
886     {
887         /* Send particle coordinates to the pme nodes.
888          * Since this is only implemented for domain decomposition
889          * and domain decomposition does not use the graph,
890          * we do not need to worry about shifting.
891          */
892         gmx_pme_send_coordinates(cr, box, as_rvec_array(x.unpaddedArrayRef().data()),
893                                  lambda[efptCOUL], lambda[efptVDW],
894                                  (flags & (GMX_FORCE_VIRIAL | GMX_FORCE_ENERGY)) != 0,
895                                  step, wcycle);
896     }
897 #endif /* GMX_MPI */
898
899     if (useGpuPme)
900     {
901         launchPmeGpuSpread(fr->pmedata, box, as_rvec_array(x.unpaddedArrayRef().data()), flags, pmeFlags, wcycle);
902     }
903
904     /* do gridding for pair search */
905     if (bNS)
906     {
907         if (graph && bStateChanged)
908         {
909             /* Calculate intramolecular shift vectors to make molecules whole */
910             mk_mshift(fplog, graph, fr->ePBC, box, as_rvec_array(x.unpaddedArrayRef().data()));
911         }
912
913         clear_rvec(vzero);
914         box_diag[XX] = box[XX][XX];
915         box_diag[YY] = box[YY][YY];
916         box_diag[ZZ] = box[ZZ][ZZ];
917
918         wallcycle_start(wcycle, ewcNS);
919         if (!DOMAINDECOMP(cr))
920         {
921             wallcycle_sub_start(wcycle, ewcsNBS_GRID_LOCAL);
922             nbnxn_put_on_grid(nbv, box,
923                               0, vzero, box_diag,
924                               nullptr, 0, mdatoms->homenr, -1,
925                               fr->cginfo, x.unpaddedArrayRef(),
926                               0, nullptr);
927             wallcycle_sub_stop(wcycle, ewcsNBS_GRID_LOCAL);
928         }
929         else
930         {
931             wallcycle_sub_start(wcycle, ewcsNBS_GRID_NONLOCAL);
932             nbnxn_put_on_grid_nonlocal(nbv, domdec_zones(cr->dd),
933                                        fr->cginfo, x.unpaddedArrayRef());
934             wallcycle_sub_stop(wcycle, ewcsNBS_GRID_NONLOCAL);
935         }
936
937         nbnxn_atomdata_set(nbv->nbat.get(), nbv->nbs.get(), mdatoms, fr->cginfo);
938
939         wallcycle_stop(wcycle, ewcNS);
940     }
941
942     /* initialize the GPU atom data and copy shift vector */
943     if (bUseGPU)
944     {
945         wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
946         wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
947
948         if (bNS)
949         {
950             Nbnxm::gpu_init_atomdata(nbv->gpu_nbv, nbv->nbat.get());
951         }
952
953         Nbnxm::gpu_upload_shiftvec(nbv->gpu_nbv, nbv->nbat.get());
954
955         wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
956
957         if (bNS && fr->gpuBonded)
958         {
959             /* Now we put all atoms on the grid, we can assign bonded
960              * interactions to the GPU, where the grid order is
961              * needed. Also the xq, f and fshift device buffers have
962              * been reallocated if needed, so the bonded code can
963              * learn about them. */
964             // TODO the xq, f, and fshift buffers are now shared
965             // resources, so they should be maintained by a
966             // higher-level object than the nb module.
967             fr->gpuBonded->updateInteractionListsAndDeviceBuffers(nbnxn_get_gridindices(fr->nbv->nbs.get()),
968                                                                   top->idef,
969                                                                   Nbnxm::gpu_get_xq(nbv->gpu_nbv),
970                                                                   Nbnxm::gpu_get_f(nbv->gpu_nbv),
971                                                                   Nbnxm::gpu_get_fshift(nbv->gpu_nbv));
972             ppForceWorkload->haveGpuBondedWork = fr->gpuBonded->haveInteractions();
973         }
974
975         wallcycle_stop(wcycle, ewcLAUNCH_GPU);
976     }
977
978     /* do local pair search */
979     if (bNS)
980     {
981         wallcycle_start_nocount(wcycle, ewcNS);
982         wallcycle_sub_start(wcycle, ewcsNBS_SEARCH_LOCAL);
983         /* Note that with a GPU the launch overhead of the list transfer is not timed separately */
984         nbv->constructPairlist(Nbnxm::InteractionLocality::Local,
985                                &top->excls, step, nrnb);
986         wallcycle_sub_stop(wcycle, ewcsNBS_SEARCH_LOCAL);
987         wallcycle_stop(wcycle, ewcNS);
988     }
989     else
990     {
991         nbnxn_atomdata_copy_x_to_nbat_x(nbv->nbs.get(), Nbnxm::AtomLocality::Local,
992                                         FALSE, as_rvec_array(x.unpaddedArrayRef().data()),
993                                         nbv->nbat.get(), wcycle);
994     }
995
996     if (bUseGPU)
997     {
998         ddBalanceRegionHandler.openBeforeForceComputationGpu();
999
1000         wallcycle_start(wcycle, ewcLAUNCH_GPU);
1001
1002         wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1003         Nbnxm::gpu_copy_xq_to_gpu(nbv->gpu_nbv, nbv->nbat.get(),
1004                                   Nbnxm::AtomLocality::Local,
1005                                   ppForceWorkload->haveGpuBondedWork);
1006         wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1007
1008         // bonded work not split into separate local and non-local, so with DD
1009         // we can only launch the kernel after non-local coordinates have been received.
1010         if (ppForceWorkload->haveGpuBondedWork && !havePPDomainDecomposition(cr))
1011         {
1012             wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_BONDED);
1013             fr->gpuBonded->launchKernels(fr, flags, box);
1014             wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_BONDED);
1015         }
1016
1017         /* launch local nonbonded work on GPU */
1018         wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1019         do_nb_verlet(fr, ic, enerd, flags, Nbnxm::InteractionLocality::Local, enbvClearFNo,
1020                      step, nrnb, wcycle);
1021         wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1022         wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1023     }
1024
1025     if (useGpuPme)
1026     {
1027         // In PME GPU and mixed mode we launch FFT / gather after the
1028         // X copy/transform to allow overlap as well as after the GPU NB
1029         // launch to avoid FFT launch overhead hijacking the CPU and delaying
1030         // the nonbonded kernel.
1031         launchPmeGpuFftAndGather(fr->pmedata, wcycle);
1032     }
1033
1034     /* Communicate coordinates and sum dipole if necessary +
1035        do non-local pair search */
1036     if (havePPDomainDecomposition(cr))
1037     {
1038         if (bNS)
1039         {
1040             wallcycle_start_nocount(wcycle, ewcNS);
1041             wallcycle_sub_start(wcycle, ewcsNBS_SEARCH_NONLOCAL);
1042             /* Note that with a GPU the launch overhead of the list transfer is not timed separately */
1043             nbv->constructPairlist(Nbnxm::InteractionLocality::NonLocal,
1044                                    &top->excls, step, nrnb);
1045             wallcycle_sub_stop(wcycle, ewcsNBS_SEARCH_NONLOCAL);
1046             wallcycle_stop(wcycle, ewcNS);
1047         }
1048         else
1049         {
1050             dd_move_x(cr->dd, box, x.unpaddedArrayRef(), wcycle);
1051
1052             nbnxn_atomdata_copy_x_to_nbat_x(nbv->nbs.get(), Nbnxm::AtomLocality::NonLocal,
1053                                             FALSE, as_rvec_array(x.unpaddedArrayRef().data()),
1054                                             nbv->nbat.get(), wcycle);
1055         }
1056
1057         if (bUseGPU)
1058         {
1059             wallcycle_start(wcycle, ewcLAUNCH_GPU);
1060
1061             /* launch non-local nonbonded tasks on GPU */
1062             wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1063             Nbnxm::gpu_copy_xq_to_gpu(nbv->gpu_nbv, nbv->nbat.get(),
1064                                       Nbnxm::AtomLocality::NonLocal,
1065                                       ppForceWorkload->haveGpuBondedWork);
1066             wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1067
1068             if (ppForceWorkload->haveGpuBondedWork)
1069             {
1070                 wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_BONDED);
1071                 fr->gpuBonded->launchKernels(fr, flags, box);
1072                 wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_BONDED);
1073             }
1074
1075             wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1076             do_nb_verlet(fr, ic, enerd, flags, Nbnxm::InteractionLocality::NonLocal, enbvClearFNo,
1077                          step, nrnb, wcycle);
1078             wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1079
1080             wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1081         }
1082     }
1083
1084     if (bUseGPU)
1085     {
1086         /* launch D2H copy-back F */
1087         wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
1088         wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1089         if (havePPDomainDecomposition(cr))
1090         {
1091             Nbnxm::gpu_launch_cpyback(nbv->gpu_nbv, nbv->nbat.get(),
1092                                       flags, Nbnxm::AtomLocality::NonLocal, ppForceWorkload->haveGpuBondedWork);
1093         }
1094         Nbnxm::gpu_launch_cpyback(nbv->gpu_nbv, nbv->nbat.get(),
1095                                   flags, Nbnxm::AtomLocality::Local, ppForceWorkload->haveGpuBondedWork);
1096         wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1097
1098         if (ppForceWorkload->haveGpuBondedWork && (flags & GMX_FORCE_ENERGY))
1099         {
1100             wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_BONDED);
1101             fr->gpuBonded->launchEnergyTransfer();
1102             wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_BONDED);
1103         }
1104         wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1105     }
1106
1107     if (bStateChanged && inputrecNeedMutot(inputrec))
1108     {
1109         if (PAR(cr))
1110         {
1111             gmx_sumd(2*DIM, mu, cr);
1112
1113             ddBalanceRegionHandler.reopenRegionCpu();
1114         }
1115
1116         for (i = 0; i < 2; i++)
1117         {
1118             for (j = 0; j < DIM; j++)
1119             {
1120                 fr->mu_tot[i][j] = mu[i*DIM + j];
1121             }
1122         }
1123     }
1124     if (fr->efep == efepNO)
1125     {
1126         copy_rvec(fr->mu_tot[0], mu_tot);
1127     }
1128     else
1129     {
1130         for (j = 0; j < DIM; j++)
1131         {
1132             mu_tot[j] =
1133                 (1.0 - lambda[efptCOUL])*fr->mu_tot[0][j] +
1134                 lambda[efptCOUL]*fr->mu_tot[1][j];
1135         }
1136     }
1137
1138     /* Reset energies */
1139     reset_enerdata(enerd);
1140     clear_rvecs(SHIFTS, fr->fshift);
1141
1142     if (DOMAINDECOMP(cr) && !thisRankHasDuty(cr, DUTY_PME))
1143     {
1144         wallcycle_start(wcycle, ewcPPDURINGPME);
1145         dd_force_flop_start(cr->dd, nrnb);
1146     }
1147
1148     if (inputrec->bRot)
1149     {
1150         wallcycle_start(wcycle, ewcROT);
1151         do_rotation(cr, enforcedRotation, box, as_rvec_array(x.unpaddedArrayRef().data()), t, step, bNS);
1152         wallcycle_stop(wcycle, ewcROT);
1153     }
1154
1155     /* Start the force cycle counter.
1156      * Note that a different counter is used for dynamic load balancing.
1157      */
1158     wallcycle_start(wcycle, ewcFORCE);
1159
1160     // set up and clear force outputs
1161     struct ForceOutputs forceOut = setupForceOutputs(fr, *inputrec, force, bDoForces, ((flags & GMX_FORCE_VIRIAL) != 0), wcycle);
1162
1163     /* We calculate the non-bonded forces, when done on the CPU, here.
1164      * We do this before calling do_force_lowlevel, because in that
1165      * function, the listed forces are calculated before PME, which
1166      * does communication.  With this order, non-bonded and listed
1167      * force calculation imbalance can be balanced out by the domain
1168      * decomposition load balancing.
1169      */
1170
1171     if (!bUseOrEmulGPU)
1172     {
1173         do_nb_verlet(fr, ic, enerd, flags, Nbnxm::InteractionLocality::Local, enbvClearFYes,
1174                      step, nrnb, wcycle);
1175     }
1176
1177     if (fr->efep != efepNO)
1178     {
1179         /* Calculate the local and non-local free energy interactions here.
1180          * Happens here on the CPU both with and without GPU.
1181          */
1182         wallcycle_sub_start(wcycle, ewcsNONBONDED);
1183         nbv->dispatchFreeEnergyKernel(Nbnxm::InteractionLocality::Local,
1184                                       fr, as_rvec_array(x.unpaddedArrayRef().data()), forceOut.f, *mdatoms,
1185                                       inputrec->fepvals, lambda,
1186                                       enerd, flags, nrnb);
1187
1188         if (havePPDomainDecomposition(cr))
1189         {
1190             nbv->dispatchFreeEnergyKernel(Nbnxm::InteractionLocality::NonLocal,
1191                                           fr, as_rvec_array(x.unpaddedArrayRef().data()), forceOut.f, *mdatoms,
1192                                           inputrec->fepvals, lambda,
1193                                           enerd, flags, nrnb);
1194         }
1195         wallcycle_sub_stop(wcycle, ewcsNONBONDED);
1196     }
1197
1198     if (!bUseOrEmulGPU)
1199     {
1200         if (havePPDomainDecomposition(cr))
1201         {
1202             do_nb_verlet(fr, ic, enerd, flags, Nbnxm::InteractionLocality::NonLocal, enbvClearFNo,
1203                          step, nrnb, wcycle);
1204         }
1205
1206         /* Add all the non-bonded force to the normal force array.
1207          * This can be split into a local and a non-local part when overlapping
1208          * communication with calculation with domain decomposition.
1209          */
1210         wallcycle_stop(wcycle, ewcFORCE);
1211
1212         nbv->atomdata_add_nbat_f_to_f(Nbnxm::AtomLocality::All, forceOut.f, wcycle);
1213
1214         wallcycle_start_nocount(wcycle, ewcFORCE);
1215
1216         /* If there are multiple fshift output buffers we need to reduce them */
1217         if (flags & GMX_FORCE_VIRIAL)
1218         {
1219             /* This is not in a subcounter because it takes a
1220                negligible and constant-sized amount of time */
1221             nbnxn_atomdata_add_nbat_fshift_to_fshift(nbv->nbat.get(),
1222                                                      fr->fshift);
1223         }
1224     }
1225
1226     /* update QMMMrec, if necessary */
1227     if (fr->bQMMM)
1228     {
1229         update_QMMMrec(cr, fr, as_rvec_array(x.unpaddedArrayRef().data()), mdatoms, box);
1230     }
1231
1232     /* Compute the bonded and non-bonded energies and optionally forces */
1233     do_force_lowlevel(fr, inputrec, &(top->idef),
1234                       cr, ms, nrnb, wcycle, mdatoms,
1235                       as_rvec_array(x.unpaddedArrayRef().data()), hist, forceOut.f, &forceOut.forceWithVirial, enerd, fcd,
1236                       box, inputrec->fepvals, lambda, graph, &(top->excls), fr->mu_tot,
1237                       flags,
1238                       &cycles_pme, ddBalanceRegionHandler);
1239
1240     wallcycle_stop(wcycle, ewcFORCE);
1241
1242     computeSpecialForces(fplog, cr, inputrec, awh, enforcedRotation,
1243                          step, t, wcycle,
1244                          fr->forceProviders, box, x.unpaddedArrayRef(), mdatoms, lambda,
1245                          flags, &forceOut.forceWithVirial, enerd,
1246                          ed, bNS);
1247
1248     if (bUseOrEmulGPU)
1249     {
1250         /* wait for non-local forces (or calculate in emulation mode) */
1251         if (havePPDomainDecomposition(cr))
1252         {
1253             if (bUseGPU)
1254             {
1255                 wallcycle_start(wcycle, ewcWAIT_GPU_NB_NL);
1256                 Nbnxm::gpu_wait_finish_task(nbv->gpu_nbv,
1257                                             flags, Nbnxm::AtomLocality::NonLocal,
1258                                             ppForceWorkload->haveGpuBondedWork,
1259                                             enerd->grpp.ener[egLJSR], enerd->grpp.ener[egCOULSR],
1260                                             fr->fshift);
1261                 cycles_wait_gpu += wallcycle_stop(wcycle, ewcWAIT_GPU_NB_NL);
1262             }
1263             else
1264             {
1265                 wallcycle_start_nocount(wcycle, ewcFORCE);
1266                 do_nb_verlet(fr, ic, enerd, flags, Nbnxm::InteractionLocality::NonLocal, enbvClearFYes,
1267                              step, nrnb, wcycle);
1268                 wallcycle_stop(wcycle, ewcFORCE);
1269             }
1270
1271             nbv->atomdata_add_nbat_f_to_f(Nbnxm::AtomLocality::NonLocal,
1272                                           forceOut.f, wcycle);
1273         }
1274     }
1275
1276     if (havePPDomainDecomposition(cr))
1277     {
1278         /* We are done with the CPU compute.
1279          * We will now communicate the non-local forces.
1280          * If we use a GPU this will overlap with GPU work, so in that case
1281          * we do not close the DD force balancing region here.
1282          */
1283         ddBalanceRegionHandler.closeAfterForceComputationCpu();
1284
1285         if (bDoForces)
1286         {
1287             dd_move_f(cr->dd, force.unpaddedArrayRef(), fr->fshift, wcycle);
1288         }
1289     }
1290
1291     // With both nonbonded and PME offloaded a GPU on the same rank, we use
1292     // an alternating wait/reduction scheme.
1293     bool alternateGpuWait = (!c_disableAlternatingWait && useGpuPme && bUseGPU && !DOMAINDECOMP(cr));
1294     if (alternateGpuWait)
1295     {
1296         alternatePmeNbGpuWaitReduce(fr->nbv.get(), fr->pmedata, &force, &forceOut.forceWithVirial, fr->fshift, enerd,
1297                                     flags, pmeFlags, ppForceWorkload->haveGpuBondedWork, wcycle);
1298     }
1299
1300     if (!alternateGpuWait && useGpuPme)
1301     {
1302         pme_gpu_wait_and_reduce(fr->pmedata, pmeFlags, wcycle, &forceOut.forceWithVirial, enerd);
1303     }
1304
1305     /* Wait for local GPU NB outputs on the non-alternating wait path */
1306     if (!alternateGpuWait && bUseGPU)
1307     {
1308         /* Measured overhead on CUDA and OpenCL with(out) GPU sharing
1309          * is between 0.5 and 1.5 Mcycles. So 2 MCycles is an overestimate,
1310          * but even with a step of 0.1 ms the difference is less than 1%
1311          * of the step time.
1312          */
1313         const float gpuWaitApiOverheadMargin = 2e6f; /* cycles */
1314
1315         wallcycle_start(wcycle, ewcWAIT_GPU_NB_L);
1316         Nbnxm::gpu_wait_finish_task(nbv->gpu_nbv,
1317                                     flags, Nbnxm::AtomLocality::Local, ppForceWorkload->haveGpuBondedWork,
1318                                     enerd->grpp.ener[egLJSR], enerd->grpp.ener[egCOULSR],
1319                                     fr->fshift);
1320         float cycles_tmp = wallcycle_stop(wcycle, ewcWAIT_GPU_NB_L);
1321
1322         if (ddBalanceRegionHandler.useBalancingRegion())
1323         {
1324             DdBalanceRegionWaitedForGpu waitedForGpu = DdBalanceRegionWaitedForGpu::yes;
1325             if (bDoForces && cycles_tmp <= gpuWaitApiOverheadMargin)
1326             {
1327                 /* We measured few cycles, it could be that the kernel
1328                  * and transfer finished earlier and there was no actual
1329                  * wait time, only API call overhead.
1330                  * Then the actual time could be anywhere between 0 and
1331                  * cycles_wait_est. We will use half of cycles_wait_est.
1332                  */
1333                 waitedForGpu = DdBalanceRegionWaitedForGpu::no;
1334             }
1335             ddBalanceRegionHandler.closeAfterForceComputationGpu(cycles_wait_gpu, waitedForGpu);
1336         }
1337     }
1338
1339     if (fr->nbv->emulateGpu())
1340     {
1341         // NOTE: emulation kernel is not included in the balancing region,
1342         // but emulation mode does not target performance anyway
1343         wallcycle_start_nocount(wcycle, ewcFORCE);
1344         do_nb_verlet(fr, ic, enerd, flags, Nbnxm::InteractionLocality::Local,
1345                      DOMAINDECOMP(cr) ? enbvClearFNo : enbvClearFYes,
1346                      step, nrnb, wcycle);
1347         wallcycle_stop(wcycle, ewcFORCE);
1348     }
1349
1350     if (useGpuPme)
1351     {
1352         pme_gpu_reinit_computation(fr->pmedata, wcycle);
1353     }
1354
1355     if (bUseGPU)
1356     {
1357         /* now clear the GPU outputs while we finish the step on the CPU */
1358         wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
1359         wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1360         Nbnxm::gpu_clear_outputs(nbv->gpu_nbv, flags);
1361
1362         if (nbv->pairlistSets().isDynamicPruningStepGpu(step))
1363         {
1364             nbv->dispatchPruneKernelGpu(step);
1365         }
1366         wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED);
1367         wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1368     }
1369
1370     if (ppForceWorkload->haveGpuBondedWork && (flags & GMX_FORCE_ENERGY))
1371     {
1372         wallcycle_start(wcycle, ewcWAIT_GPU_BONDED);
1373         // in principle this should be included in the DD balancing region,
1374         // but generally it is infrequent so we'll omit it for the sake of
1375         // simpler code
1376         fr->gpuBonded->accumulateEnergyTerms(enerd);
1377         wallcycle_stop(wcycle, ewcWAIT_GPU_BONDED);
1378
1379         wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU);
1380         wallcycle_sub_start_nocount(wcycle, ewcsLAUNCH_GPU_BONDED);
1381         fr->gpuBonded->clearEnergies();
1382         wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_BONDED);
1383         wallcycle_stop(wcycle, ewcLAUNCH_GPU);
1384     }
1385
1386     /* Do the nonbonded GPU (or emulation) force buffer reduction
1387      * on the non-alternating path. */
1388     if (bUseOrEmulGPU && !alternateGpuWait)
1389     {
1390         nbv->atomdata_add_nbat_f_to_f(Nbnxm::AtomLocality::Local,
1391                                       forceOut.f, wcycle);
1392     }
1393     if (DOMAINDECOMP(cr))
1394     {
1395         dd_force_flop_stop(cr->dd, nrnb);
1396     }
1397
1398     if (bDoForces)
1399     {
1400         /* If we have NoVirSum forces, but we do not calculate the virial,
1401          * we sum fr->f_novirsum=forceOut.f later.
1402          */
1403         if (vsite && !(fr->haveDirectVirialContributions && !(flags & GMX_FORCE_VIRIAL)))
1404         {
1405             spread_vsite_f(vsite, as_rvec_array(x.unpaddedArrayRef().data()), forceOut.f, fr->fshift, FALSE, nullptr, nrnb,
1406                            &top->idef, fr->ePBC, fr->bMolPBC, graph, box, cr, wcycle);
1407         }
1408
1409         if (flags & GMX_FORCE_VIRIAL)
1410         {
1411             /* Calculation of the virial must be done after vsites! */
1412             calc_virial(0, mdatoms->homenr, as_rvec_array(x.unpaddedArrayRef().data()), forceOut.f,
1413                         vir_force, graph, box, nrnb, fr, inputrec->ePBC);
1414         }
1415     }
1416
1417     if (PAR(cr) && !thisRankHasDuty(cr, DUTY_PME))
1418     {
1419         /* In case of node-splitting, the PP nodes receive the long-range
1420          * forces, virial and energy from the PME nodes here.
1421          */
1422         pme_receive_force_ener(cr, &forceOut.forceWithVirial, enerd, wcycle);
1423     }
1424
1425     if (bDoForces)
1426     {
1427         post_process_forces(cr, step, nrnb, wcycle,
1428                             top, box, as_rvec_array(x.unpaddedArrayRef().data()), forceOut.f, &forceOut.forceWithVirial,
1429                             vir_force, mdatoms, graph, fr, vsite,
1430                             flags);
1431     }
1432
1433     if (flags & GMX_FORCE_ENERGY)
1434     {
1435         /* Sum the potential energy terms from group contributions */
1436         sum_epot(&(enerd->grpp), enerd->term);
1437
1438         if (!EI_TPI(inputrec->eI))
1439         {
1440             checkPotentialEnergyValidity(step, *enerd, *inputrec);
1441         }
1442     }
1443 }
1444
1445 static void do_force_cutsGROUP(FILE *fplog,
1446                                const t_commrec *cr,
1447                                const gmx_multisim_t *ms,
1448                                const t_inputrec *inputrec,
1449                                gmx::Awh *awh,
1450                                gmx_enfrot *enforcedRotation,
1451                                int64_t step,
1452                                t_nrnb *nrnb,
1453                                gmx_wallcycle_t wcycle,
1454                                gmx_localtop_t *top,
1455                                const gmx_groups_t *groups,
1456                                matrix box, gmx::ArrayRefWithPadding<gmx::RVec> x,
1457                                history_t *hist,
1458                                gmx::ArrayRefWithPadding<gmx::RVec> force,
1459                                tensor vir_force,
1460                                const t_mdatoms *mdatoms,
1461                                gmx_enerdata_t *enerd,
1462                                t_fcdata *fcd,
1463                                real *lambda,
1464                                t_graph *graph,
1465                                t_forcerec *fr,
1466                                const gmx_vsite_t *vsite,
1467                                rvec mu_tot,
1468                                double t,
1469                                gmx_edsam *ed,
1470                                int flags,
1471                                const DDBalanceRegionHandler &ddBalanceRegionHandler)
1472 {
1473     int        cg0, cg1, i, j;
1474     double     mu[2*DIM];
1475     gmx_bool   bStateChanged, bNS, bFillGrid, bCalcCGCM;
1476     gmx_bool   bDoForces;
1477     float      cycles_pme;
1478
1479     const int  start  = 0;
1480     const int  homenr = mdatoms->homenr;
1481
1482     clear_mat(vir_force);
1483
1484     cg0 = 0;
1485     if (DOMAINDECOMP(cr))
1486     {
1487         cg1 = cr->dd->globalAtomGroupIndices.size();
1488     }
1489     else
1490     {
1491         cg1 = top->cgs.nr;
1492     }
1493     if (fr->n_tpi > 0)
1494     {
1495         cg1--;
1496     }
1497
1498     bStateChanged  = ((flags & GMX_FORCE_STATECHANGED) != 0);
1499     bNS            = ((flags & GMX_FORCE_NS) != 0);
1500     /* Should we perform the long-range nonbonded evaluation inside the neighborsearching? */
1501     bFillGrid      = (bNS && bStateChanged);
1502     bCalcCGCM      = (bFillGrid && !DOMAINDECOMP(cr));
1503     bDoForces      = ((flags & GMX_FORCE_FORCES) != 0);
1504
1505     if (bStateChanged)
1506     {
1507         update_forcerec(fr, box);
1508
1509         if (inputrecNeedMutot(inputrec))
1510         {
1511             /* Calculate total (local) dipole moment in a temporary common array.
1512              * This makes it possible to sum them over nodes faster.
1513              */
1514             calc_mu(start, homenr,
1515                     x.unpaddedArrayRef(), mdatoms->chargeA, mdatoms->chargeB, mdatoms->nChargePerturbed,
1516                     mu, mu+DIM);
1517         }
1518     }
1519
1520     if (fr->ePBC != epbcNONE)
1521     {
1522         /* Compute shift vectors every step,
1523          * because of pressure coupling or box deformation!
1524          */
1525         if ((flags & GMX_FORCE_DYNAMICBOX) && bStateChanged)
1526         {
1527             calc_shifts(box, fr->shift_vec);
1528         }
1529
1530         if (bCalcCGCM)
1531         {
1532             put_charge_groups_in_box(fplog, cg0, cg1, fr->ePBC, box,
1533                                      &(top->cgs), as_rvec_array(x.unpaddedArrayRef().data()), fr->cg_cm);
1534             inc_nrnb(nrnb, eNR_CGCM, homenr);
1535             inc_nrnb(nrnb, eNR_RESETX, cg1-cg0);
1536         }
1537         else if (EI_ENERGY_MINIMIZATION(inputrec->eI) && graph)
1538         {
1539             unshift_self(graph, box, as_rvec_array(x.unpaddedArrayRef().data()));
1540         }
1541     }
1542     else if (bCalcCGCM)
1543     {
1544         calc_cgcm(fplog, cg0, cg1, &(top->cgs), as_rvec_array(x.unpaddedArrayRef().data()), fr->cg_cm);
1545         inc_nrnb(nrnb, eNR_CGCM, homenr);
1546     }
1547
1548     if (bCalcCGCM && gmx_debug_at)
1549     {
1550         pr_rvecs(debug, 0, "cgcm", fr->cg_cm, top->cgs.nr);
1551     }
1552
1553 #if GMX_MPI
1554     if (!thisRankHasDuty(cr, DUTY_PME))
1555     {
1556         /* Send particle coordinates to the pme nodes.
1557          * Since this is only implemented for domain decomposition
1558          * and domain decomposition does not use the graph,
1559          * we do not need to worry about shifting.
1560          */
1561         gmx_pme_send_coordinates(cr, box, as_rvec_array(x.unpaddedArrayRef().data()),
1562                                  lambda[efptCOUL], lambda[efptVDW],
1563                                  (flags & (GMX_FORCE_VIRIAL | GMX_FORCE_ENERGY)) != 0,
1564                                  step, wcycle);
1565     }
1566 #endif /* GMX_MPI */
1567
1568     /* Communicate coordinates and sum dipole if necessary */
1569     if (DOMAINDECOMP(cr))
1570     {
1571         dd_move_x(cr->dd, box, x.unpaddedArrayRef(), wcycle);
1572
1573         /* No GPU support, no move_x overlap, so reopen the balance region here */
1574         ddBalanceRegionHandler.reopenRegionCpu();
1575     }
1576
1577     if (inputrecNeedMutot(inputrec))
1578     {
1579         if (bStateChanged)
1580         {
1581             if (PAR(cr))
1582             {
1583                 gmx_sumd(2*DIM, mu, cr);
1584
1585                 ddBalanceRegionHandler.reopenRegionCpu();
1586             }
1587             for (i = 0; i < 2; i++)
1588             {
1589                 for (j = 0; j < DIM; j++)
1590                 {
1591                     fr->mu_tot[i][j] = mu[i*DIM + j];
1592                 }
1593             }
1594         }
1595         if (fr->efep == efepNO)
1596         {
1597             copy_rvec(fr->mu_tot[0], mu_tot);
1598         }
1599         else
1600         {
1601             for (j = 0; j < DIM; j++)
1602             {
1603                 mu_tot[j] =
1604                     (1.0 - lambda[efptCOUL])*fr->mu_tot[0][j] + lambda[efptCOUL]*fr->mu_tot[1][j];
1605             }
1606         }
1607     }
1608
1609     /* Reset energies */
1610     reset_enerdata(enerd);
1611     clear_rvecs(SHIFTS, fr->fshift);
1612
1613     if (bNS)
1614     {
1615         wallcycle_start(wcycle, ewcNS);
1616
1617         if (graph && bStateChanged)
1618         {
1619             /* Calculate intramolecular shift vectors to make molecules whole */
1620             mk_mshift(fplog, graph, fr->ePBC, box, as_rvec_array(x.unpaddedArrayRef().data()));
1621         }
1622
1623         /* Do the actual neighbour searching */
1624         ns(fplog, fr, box,
1625            groups, top, mdatoms,
1626            cr, nrnb, bFillGrid);
1627
1628         wallcycle_stop(wcycle, ewcNS);
1629     }
1630
1631     if (DOMAINDECOMP(cr) && !thisRankHasDuty(cr, DUTY_PME))
1632     {
1633         wallcycle_start(wcycle, ewcPPDURINGPME);
1634         dd_force_flop_start(cr->dd, nrnb);
1635     }
1636
1637     if (inputrec->bRot)
1638     {
1639         wallcycle_start(wcycle, ewcROT);
1640         do_rotation(cr, enforcedRotation, box, as_rvec_array(x.unpaddedArrayRef().data()), t, step, bNS);
1641         wallcycle_stop(wcycle, ewcROT);
1642     }
1643
1644
1645     /* Start the force cycle counter.
1646      * Note that a different counter is used for dynamic load balancing.
1647      */
1648     wallcycle_start(wcycle, ewcFORCE);
1649
1650     // set up and clear force outputs
1651     struct ForceOutputs forceOut = setupForceOutputs(fr, *inputrec, force, bDoForces, ((flags & GMX_FORCE_VIRIAL) != 0), wcycle);
1652
1653     if (inputrec->bPull && pull_have_constraint(inputrec->pull_work))
1654     {
1655         clear_pull_forces(inputrec->pull_work);
1656     }
1657
1658     /* update QMMMrec, if necessary */
1659     if (fr->bQMMM)
1660     {
1661         update_QMMMrec(cr, fr, as_rvec_array(x.unpaddedArrayRef().data()), mdatoms, box);
1662     }
1663
1664     /* Compute the bonded and non-bonded energies and optionally forces */
1665     do_force_lowlevel(fr, inputrec, &(top->idef),
1666                       cr, ms, nrnb, wcycle, mdatoms,
1667                       as_rvec_array(x.unpaddedArrayRef().data()), hist, forceOut.f, &forceOut.forceWithVirial, enerd, fcd,
1668                       box, inputrec->fepvals, lambda,
1669                       graph, &(top->excls), fr->mu_tot,
1670                       flags,
1671                       &cycles_pme, ddBalanceRegionHandler);
1672
1673     wallcycle_stop(wcycle, ewcFORCE);
1674
1675     if (DOMAINDECOMP(cr))
1676     {
1677         dd_force_flop_stop(cr->dd, nrnb);
1678
1679         ddBalanceRegionHandler.closeAfterForceComputationCpu();
1680     }
1681
1682     computeSpecialForces(fplog, cr, inputrec, awh, enforcedRotation,
1683                          step, t, wcycle,
1684                          fr->forceProviders, box, x.unpaddedArrayRef(), mdatoms, lambda,
1685                          flags, &forceOut.forceWithVirial, enerd,
1686                          ed, bNS);
1687
1688     if (bDoForces)
1689     {
1690         /* Communicate the forces */
1691         if (DOMAINDECOMP(cr))
1692         {
1693             dd_move_f(cr->dd, force.unpaddedArrayRef(), fr->fshift, wcycle);
1694             /* Do we need to communicate the separate force array
1695              * for terms that do not contribute to the single sum virial?
1696              * Position restraints and electric fields do not introduce
1697              * inter-cg forces, only full electrostatics methods do.
1698              * When we do not calculate the virial, fr->f_novirsum = forceOut.f,
1699              * so we have already communicated these forces.
1700              */
1701             if (EEL_FULL(fr->ic->eeltype) && cr->dd->n_intercg_excl &&
1702                 (flags & GMX_FORCE_VIRIAL))
1703             {
1704                 dd_move_f(cr->dd, forceOut.forceWithVirial.force_, nullptr, wcycle);
1705             }
1706         }
1707
1708         /* If we have NoVirSum forces, but we do not calculate the virial,
1709          * we sum fr->f_novirsum=forceOut.f later.
1710          */
1711         if (vsite && !(fr->haveDirectVirialContributions && !(flags & GMX_FORCE_VIRIAL)))
1712         {
1713             spread_vsite_f(vsite, as_rvec_array(x.unpaddedArrayRef().data()), forceOut.f, fr->fshift, FALSE, nullptr, nrnb,
1714                            &top->idef, fr->ePBC, fr->bMolPBC, graph, box, cr, wcycle);
1715         }
1716
1717         if (flags & GMX_FORCE_VIRIAL)
1718         {
1719             /* Calculation of the virial must be done after vsites! */
1720             calc_virial(0, mdatoms->homenr, as_rvec_array(x.unpaddedArrayRef().data()), forceOut.f,
1721                         vir_force, graph, box, nrnb, fr, inputrec->ePBC);
1722         }
1723     }
1724
1725     if (PAR(cr) && !thisRankHasDuty(cr, DUTY_PME))
1726     {
1727         /* In case of node-splitting, the PP nodes receive the long-range
1728          * forces, virial and energy from the PME nodes here.
1729          */
1730         pme_receive_force_ener(cr, &forceOut.forceWithVirial, enerd, wcycle);
1731     }
1732
1733     if (bDoForces)
1734     {
1735         post_process_forces(cr, step, nrnb, wcycle,
1736                             top, box, as_rvec_array(x.unpaddedArrayRef().data()), forceOut.f, &forceOut.forceWithVirial,
1737                             vir_force, mdatoms, graph, fr, vsite,
1738                             flags);
1739     }
1740
1741     if (flags & GMX_FORCE_ENERGY)
1742     {
1743         /* Sum the potential energy terms from group contributions */
1744         sum_epot(&(enerd->grpp), enerd->term);
1745
1746         if (!EI_TPI(inputrec->eI))
1747         {
1748             checkPotentialEnergyValidity(step, *enerd, *inputrec);
1749         }
1750     }
1751
1752 }
1753
1754 void do_force(FILE                                     *fplog,
1755               const t_commrec                          *cr,
1756               const gmx_multisim_t                     *ms,
1757               const t_inputrec                         *inputrec,
1758               gmx::Awh                                 *awh,
1759               gmx_enfrot                               *enforcedRotation,
1760               int64_t                                   step,
1761               t_nrnb                                   *nrnb,
1762               gmx_wallcycle_t                           wcycle,
1763               gmx_localtop_t                           *top,
1764               const gmx_groups_t                       *groups,
1765               matrix                                    box,
1766               gmx::ArrayRefWithPadding<gmx::RVec>       x,     //NOLINT(performance-unnecessary-value-param)
1767               history_t                                *hist,
1768               gmx::ArrayRefWithPadding<gmx::RVec>       force, //NOLINT(performance-unnecessary-value-param)
1769               tensor                                    vir_force,
1770               const t_mdatoms                          *mdatoms,
1771               gmx_enerdata_t                           *enerd,
1772               t_fcdata                                 *fcd,
1773               gmx::ArrayRef<real>                       lambda,
1774               t_graph                                  *graph,
1775               t_forcerec                               *fr,
1776               gmx::PpForceWorkload                     *ppForceWorkload,
1777               const gmx_vsite_t                        *vsite,
1778               rvec                                      mu_tot,
1779               double                                    t,
1780               gmx_edsam                                *ed,
1781               int                                       flags,
1782               const DDBalanceRegionHandler             &ddBalanceRegionHandler)
1783 {
1784     /* modify force flag if not doing nonbonded */
1785     if (!fr->bNonbonded)
1786     {
1787         flags &= ~GMX_FORCE_NONBONDED;
1788     }
1789
1790     switch (inputrec->cutoff_scheme)
1791     {
1792         case ecutsVERLET:
1793             do_force_cutsVERLET(fplog, cr, ms, inputrec,
1794                                 awh, enforcedRotation, step, nrnb, wcycle,
1795                                 top,
1796                                 groups,
1797                                 box, x, hist,
1798                                 force, vir_force,
1799                                 mdatoms,
1800                                 enerd, fcd,
1801                                 lambda.data(), graph,
1802                                 fr,
1803                                 ppForceWorkload,
1804                                 fr->ic,
1805                                 vsite, mu_tot,
1806                                 t, ed,
1807                                 flags,
1808                                 ddBalanceRegionHandler);
1809             break;
1810         case ecutsGROUP:
1811             do_force_cutsGROUP(fplog, cr, ms, inputrec,
1812                                awh, enforcedRotation, step, nrnb, wcycle,
1813                                top,
1814                                groups,
1815                                box, x, hist,
1816                                force, vir_force,
1817                                mdatoms,
1818                                enerd, fcd,
1819                                lambda.data(), graph,
1820                                fr, vsite, mu_tot,
1821                                t, ed,
1822                                flags,
1823                                ddBalanceRegionHandler);
1824             break;
1825         default:
1826             gmx_incons("Invalid cut-off scheme passed!");
1827     }
1828
1829     /* In case we don't have constraints and are using GPUs, the next balancing
1830      * region starts here.
1831      * Some "special" work at the end of do_force_cuts?, such as vsite spread,
1832      * virial calculation and COM pulling, is not thus not included in
1833      * the balance timing, which is ok as most tasks do communication.
1834      */
1835     ddBalanceRegionHandler.openBeforeForceComputationCpu(DdAllowBalanceRegionReopen::no);
1836 }
1837
1838
1839 void do_constrain_first(FILE *fplog, gmx::Constraints *constr,
1840                         const t_inputrec *ir, const t_mdatoms *md,
1841                         t_state *state)
1842 {
1843     int             i, m, start, end;
1844     int64_t         step;
1845     real            dt = ir->delta_t;
1846     real            dvdl_dum;
1847     rvec           *savex;
1848
1849     /* We need to allocate one element extra, since we might use
1850      * (unaligned) 4-wide SIMD loads to access rvec entries.
1851      */
1852     snew(savex, state->natoms + 1);
1853
1854     start = 0;
1855     end   = md->homenr;
1856
1857     if (debug)
1858     {
1859         fprintf(debug, "vcm: start=%d, homenr=%d, end=%d\n",
1860                 start, md->homenr, end);
1861     }
1862     /* Do a first constrain to reset particles... */
1863     step = ir->init_step;
1864     if (fplog)
1865     {
1866         char buf[STEPSTRSIZE];
1867         fprintf(fplog, "\nConstraining the starting coordinates (step %s)\n",
1868                 gmx_step_str(step, buf));
1869     }
1870     dvdl_dum = 0;
1871
1872     /* constrain the current position */
1873     constr->apply(TRUE, FALSE,
1874                   step, 0, 1.0,
1875                   state->x.rvec_array(), state->x.rvec_array(), nullptr,
1876                   state->box,
1877                   state->lambda[efptBONDED], &dvdl_dum,
1878                   nullptr, nullptr, gmx::ConstraintVariable::Positions);
1879     if (EI_VV(ir->eI))
1880     {
1881         /* constrain the inital velocity, and save it */
1882         /* also may be useful if we need the ekin from the halfstep for velocity verlet */
1883         constr->apply(TRUE, FALSE,
1884                       step, 0, 1.0,
1885                       state->x.rvec_array(), state->v.rvec_array(), state->v.rvec_array(),
1886                       state->box,
1887                       state->lambda[efptBONDED], &dvdl_dum,
1888                       nullptr, nullptr, gmx::ConstraintVariable::Velocities);
1889     }
1890     /* constrain the inital velocities at t-dt/2 */
1891     if (EI_STATE_VELOCITY(ir->eI) && ir->eI != eiVV)
1892     {
1893         auto x = makeArrayRef(state->x).subArray(start, end);
1894         auto v = makeArrayRef(state->v).subArray(start, end);
1895         for (i = start; (i < end); i++)
1896         {
1897             for (m = 0; (m < DIM); m++)
1898             {
1899                 /* Reverse the velocity */
1900                 v[i][m] = -v[i][m];
1901                 /* Store the position at t-dt in buf */
1902                 savex[i][m] = x[i][m] + dt*v[i][m];
1903             }
1904         }
1905         /* Shake the positions at t=-dt with the positions at t=0
1906          * as reference coordinates.
1907          */
1908         if (fplog)
1909         {
1910             char buf[STEPSTRSIZE];
1911             fprintf(fplog, "\nConstraining the coordinates at t0-dt (step %s)\n",
1912                     gmx_step_str(step, buf));
1913         }
1914         dvdl_dum = 0;
1915         constr->apply(TRUE, FALSE,
1916                       step, -1, 1.0,
1917                       state->x.rvec_array(), savex, nullptr,
1918                       state->box,
1919                       state->lambda[efptBONDED], &dvdl_dum,
1920                       state->v.rvec_array(), nullptr, gmx::ConstraintVariable::Positions);
1921
1922         for (i = start; i < end; i++)
1923         {
1924             for (m = 0; m < DIM; m++)
1925             {
1926                 /* Re-reverse the velocities */
1927                 v[i][m] = -v[i][m];
1928             }
1929         }
1930     }
1931     sfree(savex);
1932 }
1933
1934 void put_atoms_in_box_omp(int ePBC, const matrix box, gmx::ArrayRef<gmx::RVec> x)
1935 {
1936     int t, nth;
1937     nth = gmx_omp_nthreads_get(emntDefault);
1938
1939 #pragma omp parallel for num_threads(nth) schedule(static)
1940     for (t = 0; t < nth; t++)
1941     {
1942         try
1943         {
1944             size_t natoms = x.size();
1945             size_t offset = (natoms*t    )/nth;
1946             size_t len    = (natoms*(t + 1))/nth - offset;
1947             put_atoms_in_box(ePBC, box, x.subArray(offset, len));
1948         }
1949         GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
1950     }
1951 }
1952
1953 void initialize_lambdas(FILE               *fplog,
1954                         const t_inputrec   &ir,
1955                         bool                isMaster,
1956                         int                *fep_state,
1957                         gmx::ArrayRef<real> lambda,
1958                         double             *lam0)
1959 {
1960     /* TODO: Clean up initialization of fep_state and lambda in
1961        t_state.  This function works, but could probably use a logic
1962        rewrite to keep all the different types of efep straight. */
1963
1964     if ((ir.efep == efepNO) && (!ir.bSimTemp))
1965     {
1966         return;
1967     }
1968
1969     const t_lambda *fep = ir.fepvals;
1970     if (isMaster)
1971     {
1972         *fep_state = fep->init_fep_state; /* this might overwrite the checkpoint
1973                                              if checkpoint is set -- a kludge is in for now
1974                                              to prevent this.*/
1975     }
1976
1977     for (int i = 0; i < efptNR; i++)
1978     {
1979         double thisLambda;
1980         /* overwrite lambda state with init_lambda for now for backwards compatibility */
1981         if (fep->init_lambda >= 0) /* if it's -1, it was never initialized */
1982         {
1983             thisLambda = fep->init_lambda;
1984         }
1985         else
1986         {
1987             thisLambda = fep->all_lambda[i][fep->init_fep_state];
1988         }
1989         if (isMaster)
1990         {
1991             lambda[i] = thisLambda;
1992         }
1993         if (lam0 != nullptr)
1994         {
1995             lam0[i] = thisLambda;
1996         }
1997     }
1998     if (ir.bSimTemp)
1999     {
2000         /* need to rescale control temperatures to match current state */
2001         for (int i = 0; i < ir.opts.ngtc; i++)
2002         {
2003             if (ir.opts.ref_t[i] > 0)
2004             {
2005                 ir.opts.ref_t[i] = ir.simtempvals->temperatures[fep->init_fep_state];
2006             }
2007         }
2008     }
2009
2010     /* Send to the log the information on the current lambdas */
2011     if (fplog != nullptr)
2012     {
2013         fprintf(fplog, "Initial vector of lambda components:[ ");
2014         for (const auto &l : lambda)
2015         {
2016             fprintf(fplog, "%10.4f ", l);
2017         }
2018         fprintf(fplog, "]\n");
2019     }
2020 }