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