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