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