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