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