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