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