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