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