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