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