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