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