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