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