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