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