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