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