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