Fixed bug #714: deprecated structure in gettimeofday
[alexxy/gromacs.git] / src / mdlib / sim_util.c
1 /* -*- mode: c; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup"; -*-
2  *
3  * 
4  *                This source code is part of
5  * 
6  *                 G   R   O   M   A   C   S
7  * 
8  *          GROningen MAchine for Chemical Simulations
9  * 
10  *                        VERSION 3.2.0
11  * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
12  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
13  * Copyright (c) 2001-2004, The GROMACS development team,
14  * check out http://www.gromacs.org for more information.
15
16  * This program is free software; you can redistribute it and/or
17  * modify it under the terms of the GNU General Public License
18  * as published by the Free Software Foundation; either version 2
19  * of the License, or (at your option) any later version.
20  * 
21  * If you want to redistribute modifications, please consider that
22  * scientific software is very special. Version control is crucial -
23  * bugs must be traceable. We will be happy to consider code for
24  * inclusion in the official distribution, but derived work must not
25  * be called official GROMACS. Details are found in the README & COPYING
26  * files - if they are missing, get the official version at www.gromacs.org.
27  * 
28  * To help us fund GROMACS development, we humbly ask that you cite
29  * the papers on the package - you can find them in the top README file.
30  * 
31  * For more info, check our website at http://www.gromacs.org
32  * 
33  * And Hey:
34  * GROwing Monsters And Cloning Shrimps
35  */
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39
40 #ifdef GMX_CRAY_XT3
41 #include<catamount/dclock.h>
42 #endif
43
44
45 #include <stdio.h>
46 #include <time.h>
47 #ifdef HAVE_SYS_TIME_H
48 #include <sys/time.h>
49 #endif
50 #include <math.h>
51 #include "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 "update.h"
67 #include "physics.h"
68 #include "main.h"
69 #include "mdatoms.h"
70 #include "force.h"
71 #include "bondf.h"
72 #include "pme.h"
73 #include "pppm.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
84 #include "mpelogging.h"
85 #include "domdec.h"
86 #include "partdec.h"
87 #include "gmx_wallcycle.h"
88 #include "genborn.h"
89
90 #ifdef GMX_LIB_MPI
91 #include <mpi.h>
92 #endif
93 #ifdef GMX_THREADS
94 #include "tmpi.h"
95 #endif
96
97 #include "qmmm.h"
98
99 #if 0
100 typedef struct gmx_timeprint {
101     
102 } t_gmx_timeprint;
103 #endif
104
105 /* Portable version of ctime_r implemented in src/gmxlib/string2.c, but we do not want it declared in public installed headers */
106 char *
107 gmx_ctime_r(const time_t *clock,char *buf, int n);
108
109
110 double
111 gmx_gettime()
112 {
113 #ifdef HAVE_GETTIMEOFDAY
114         struct timeval t;
115         double seconds;
116         
117         gettimeofday(&t,NULL);
118         
119         seconds = (double) t.tv_sec + 1e-6*(double)t.tv_usec;
120         
121         return seconds;
122 #else
123         double  seconds;
124         
125         seconds = time(NULL);
126         
127         return seconds;
128 #endif
129 }
130
131
132 #define difftime(end,start) ((double)(end)-(double)(start))
133
134 void print_time(FILE *out,gmx_runtime_t *runtime,gmx_large_int_t step,   
135                 t_inputrec *ir, t_commrec *cr)
136 {
137     time_t finish;
138     char   timebuf[STRLEN];
139     double dt;
140     char buf[48];
141     
142 #ifndef GMX_THREADS
143     if (!PAR(cr))
144 #endif
145     {
146         fprintf(out,"\r");
147     }
148     fprintf(out,"step %s",gmx_step_str(step,buf));
149     if ((step >= ir->nstlist))
150     {
151         if ((ir->nstlist == 0) || ((step % ir->nstlist) == 0))
152         {
153             /* We have done a full cycle let's update time_per_step */
154             runtime->last = gmx_gettime();
155             dt = difftime(runtime->last,runtime->real);
156             runtime->time_per_step = dt/(step - ir->init_step + 1);
157         }
158         dt = (ir->nsteps + ir->init_step - step)*runtime->time_per_step;
159         
160         if (ir->nsteps >= 0)
161         {
162             if (dt >= 300)
163             {    
164                 finish = (time_t) (runtime->last + dt);
165                 gmx_ctime_r(&finish,timebuf,STRLEN);
166                 sprintf(buf,"%s",timebuf);
167                 buf[strlen(buf)-1]='\0';
168                 fprintf(out,", will finish %s",buf);
169             }
170             else
171                 fprintf(out,", remaining runtime: %5d s          ",(int)dt);
172         }
173         else
174         {
175             fprintf(out," performance: %.1f ns/day    ",
176                     ir->delta_t/1000*24*60*60/runtime->time_per_step);
177         }
178     }
179 #ifndef GMX_THREADS
180     if (PAR(cr))
181     {
182         fprintf(out,"\n");
183     }
184 #endif
185
186     fflush(out);
187 }
188
189 #ifdef NO_CLOCK 
190 #define clock() -1
191 #endif
192
193 static double set_proctime(gmx_runtime_t *runtime)
194 {
195     double diff;
196 #ifdef GMX_CRAY_XT3
197     double prev;
198
199     prev = runtime->proc;
200     runtime->proc = dclock();
201     
202     diff = runtime->proc - prev;
203 #else
204     clock_t prev;
205
206     prev = runtime->proc;
207     runtime->proc = clock();
208
209     diff = (double)(runtime->proc - prev)/(double)CLOCKS_PER_SEC;
210 #endif
211     if (diff < 0)
212     {
213         /* The counter has probably looped, ignore this data */
214         diff = 0;
215     }
216
217     return diff;
218 }
219
220 void runtime_start(gmx_runtime_t *runtime)
221 {
222     runtime->real = gmx_gettime();
223     runtime->proc          = 0;
224     set_proctime(runtime);
225     runtime->realtime      = 0;
226     runtime->proctime      = 0;
227     runtime->last          = 0;
228     runtime->time_per_step = 0;
229 }
230
231 void runtime_end(gmx_runtime_t *runtime)
232 {
233     double now;
234     
235     now = gmx_gettime();
236     
237     runtime->proctime += set_proctime(runtime);
238     runtime->realtime  = now - runtime->real;
239     runtime->real      = now;
240 }
241
242 void runtime_upd_proc(gmx_runtime_t *runtime)
243 {
244     runtime->proctime += set_proctime(runtime);
245 }
246
247 void print_date_and_time(FILE *fplog,int nodeid,const char *title,
248                          const gmx_runtime_t *runtime)
249 {
250     int i;
251     char timebuf[STRLEN];
252     char time_string[STRLEN];
253     time_t tmptime;
254
255     if (fplog)
256     {
257         if (runtime != NULL)
258         {
259             tmptime = (time_t) runtime->real;
260             gmx_ctime_r(&tmptime,timebuf,STRLEN);
261         }
262         else
263         {
264             tmptime = (time_t) gmx_gettime();
265             gmx_ctime_r(&tmptime,timebuf,STRLEN);
266         }
267         for(i=0; timebuf[i]>=' '; i++)
268         {
269             time_string[i]=timebuf[i];
270         }
271         time_string[i]='\0';
272
273         fprintf(fplog,"%s on node %d %s\n",title,nodeid,time_string);
274     }
275 }
276
277 static void sum_forces(int start,int end,rvec f[],rvec flr[])
278 {
279   int i;
280   
281   if (gmx_debug_at) {
282     pr_rvecs(debug,0,"fsr",f+start,end-start);
283     pr_rvecs(debug,0,"flr",flr+start,end-start);
284   }
285   for(i=start; (i<end); i++)
286     rvec_inc(f[i],flr[i]);
287 }
288
289 /* 
290  * calc_f_el calculates forces due to an electric field.
291  *
292  * force is kJ mol^-1 nm^-1 = e * kJ mol^-1 nm^-1 / e 
293  *
294  * Et[] contains the parameters for the time dependent 
295  * part of the field (not yet used). 
296  * Ex[] contains the parameters for
297  * the spatial dependent part of the field. You can have cool periodic
298  * fields in principle, but only a constant field is supported
299  * now. 
300  * The function should return the energy due to the electric field
301  * (if any) but for now returns 0.
302  *
303  * WARNING:
304  * There can be problems with the virial.
305  * Since the field is not self-consistent this is unavoidable.
306  * For neutral molecules the virial is correct within this approximation.
307  * For neutral systems with many charged molecules the error is small.
308  * But for systems with a net charge or a few charged molecules
309  * the error can be significant when the field is high.
310  * Solution: implement a self-consitent electric field into PME.
311  */
312 static void calc_f_el(FILE *fp,int  start,int homenr,
313                       real charge[],rvec x[],rvec f[],
314                       t_cosines Ex[],t_cosines Et[],double t)
315 {
316     rvec Ext;
317     real t0;
318     int  i,m;
319     
320     for(m=0; (m<DIM); m++)
321     {
322         if (Et[m].n > 0)
323         {
324             if (Et[m].n == 3)
325             {
326                 t0 = Et[m].a[1];
327                 Ext[m] = cos(Et[m].a[0]*(t-t0))*exp(-sqr(t-t0)/(2.0*sqr(Et[m].a[2])));
328             }
329             else
330             {
331                 Ext[m] = cos(Et[m].a[0]*t);
332             }
333         }
334         else
335         {
336             Ext[m] = 1.0;
337         }
338         if (Ex[m].n > 0)
339         {
340             /* Convert the field strength from V/nm to MD-units */
341             Ext[m] *= Ex[m].a[0]*FIELDFAC;
342             for(i=start; (i<start+homenr); i++)
343                 f[i][m] += charge[i]*Ext[m];
344         }
345         else
346         {
347             Ext[m] = 0;
348         }
349     }
350     if (fp != NULL)
351     {
352         fprintf(fp,"%10g  %10g  %10g  %10g #FIELD\n",t,
353                 Ext[XX]/FIELDFAC,Ext[YY]/FIELDFAC,Ext[ZZ]/FIELDFAC);
354     }
355 }
356
357 static void calc_virial(FILE *fplog,int start,int homenr,rvec x[],rvec f[],
358                         tensor vir_part,t_graph *graph,matrix box,
359                         t_nrnb *nrnb,const t_forcerec *fr,int ePBC)
360 {
361   int i,j;
362   tensor virtest;
363
364   /* The short-range virial from surrounding boxes */
365   clear_mat(vir_part);
366   calc_vir(fplog,SHIFTS,fr->shift_vec,fr->fshift,vir_part,ePBC==epbcSCREW,box);
367   inc_nrnb(nrnb,eNR_VIRIAL,SHIFTS);
368   
369   /* Calculate partial virial, for local atoms only, based on short range. 
370    * Total virial is computed in global_stat, called from do_md 
371    */
372   f_calc_vir(fplog,start,start+homenr,x,f,vir_part,graph,box);
373   inc_nrnb(nrnb,eNR_VIRIAL,homenr);
374
375   /* Add position restraint contribution */
376   for(i=0; i<DIM; i++) {
377     vir_part[i][i] += fr->vir_diag_posres[i];
378   }
379
380   /* Add wall contribution */
381   for(i=0; i<DIM; i++) {
382     vir_part[i][ZZ] += fr->vir_wall_z[i];
383   }
384
385   if (debug)
386     pr_rvecs(debug,0,"vir_part",vir_part,DIM);
387 }
388
389 static void print_large_forces(FILE *fp,t_mdatoms *md,t_commrec *cr,
390                                gmx_large_int_t step,real pforce,rvec *x,rvec *f)
391 {
392   int  i;
393   real pf2,fn2;
394   char buf[STEPSTRSIZE];
395
396   pf2 = sqr(pforce);
397   for(i=md->start; i<md->start+md->homenr; i++) {
398     fn2 = norm2(f[i]);
399     /* We also catch NAN, if the compiler does not optimize this away. */
400     if (fn2 >= pf2 || fn2 != fn2) {
401       fprintf(fp,"step %s  atom %6d  x %8.3f %8.3f %8.3f  force %12.5e\n",
402               gmx_step_str(step,buf),
403               ddglatnr(cr->dd,i),x[i][XX],x[i][YY],x[i][ZZ],sqrt(fn2));
404     }
405   }
406 }
407
408 void do_force(FILE *fplog,t_commrec *cr,
409               t_inputrec *inputrec,
410               gmx_large_int_t step,t_nrnb *nrnb,gmx_wallcycle_t wcycle,
411               gmx_localtop_t *top,
412               gmx_mtop_t *mtop,
413               gmx_groups_t *groups,
414               matrix box,rvec x[],history_t *hist,
415               rvec f[],
416               tensor vir_force,
417               t_mdatoms *mdatoms,
418               gmx_enerdata_t *enerd,t_fcdata *fcd,
419               real lambda,t_graph *graph,
420               t_forcerec *fr,gmx_vsite_t *vsite,rvec mu_tot,
421               double t,FILE *field,gmx_edsam_t ed,
422               gmx_bool bBornRadii,
423               int flags)
424 {
425     int    cg0,cg1,i,j;
426     int    start,homenr;
427     double mu[2*DIM]; 
428     gmx_bool   bSepDVDL,bStateChanged,bNS,bFillGrid,bCalcCGCM,bBS;
429     gmx_bool   bDoLongRange,bDoForces,bSepLRF;
430     matrix boxs;
431     real   e,v,dvdl;
432     t_pbc  pbc;
433     float  cycles_ppdpme,cycles_pme,cycles_seppme,cycles_force;
434   
435     start  = mdatoms->start;
436     homenr = mdatoms->homenr;
437
438     bSepDVDL = (fr->bSepDVDL && do_per_step(step,inputrec->nstlog));
439
440     clear_mat(vir_force);
441
442     if (PARTDECOMP(cr))
443     {
444         pd_cg_range(cr,&cg0,&cg1);
445     }
446     else
447     {
448         cg0 = 0;
449         if (DOMAINDECOMP(cr))
450         {
451             cg1 = cr->dd->ncg_tot;
452         }
453         else
454         {
455             cg1 = top->cgs.nr;
456         }
457         if (fr->n_tpi > 0)
458         {
459             cg1--;
460         }
461     }
462
463     bStateChanged = (flags & GMX_FORCE_STATECHANGED);
464     bNS           = (flags & GMX_FORCE_NS) && (fr->bAllvsAll==FALSE); 
465     bFillGrid     = (bNS && bStateChanged);
466     bCalcCGCM     = (bFillGrid && !DOMAINDECOMP(cr));
467     bDoLongRange  = (fr->bTwinRange && bNS && (flags & GMX_FORCE_DOLR));
468     bDoForces     = (flags & GMX_FORCE_FORCES);
469     bSepLRF       = (bDoLongRange && bDoForces && (flags & GMX_FORCE_SEPLRF));
470
471     if (bStateChanged)
472     {
473         update_forcerec(fplog,fr,box);
474         
475         /* Calculate total (local) dipole moment in a temporary common array. 
476          * This makes it possible to sum them over nodes faster.
477          */
478         calc_mu(start,homenr,
479                 x,mdatoms->chargeA,mdatoms->chargeB,mdatoms->nChargePerturbed,
480                 mu,mu+DIM);
481     }
482   
483   if (fr->ePBC != epbcNONE) { 
484     /* Compute shift vectors every step,
485      * because of pressure coupling or box deformation!
486      */
487     if ((flags & GMX_FORCE_DYNAMICBOX) && bStateChanged)
488       calc_shifts(box,fr->shift_vec);
489     
490     if (bCalcCGCM) { 
491       put_charge_groups_in_box(fplog,cg0,cg1,fr->ePBC,box,
492                                &(top->cgs),x,fr->cg_cm);
493       inc_nrnb(nrnb,eNR_CGCM,homenr);
494       inc_nrnb(nrnb,eNR_RESETX,cg1-cg0);
495     } 
496     else if (EI_ENERGY_MINIMIZATION(inputrec->eI) && graph) {
497       unshift_self(graph,box,x);
498     }
499   } 
500   else if (bCalcCGCM) {
501     calc_cgcm(fplog,cg0,cg1,&(top->cgs),x,fr->cg_cm);
502     inc_nrnb(nrnb,eNR_CGCM,homenr);
503   }
504   
505   if (bCalcCGCM) {
506     if (PAR(cr)) {
507       move_cgcm(fplog,cr,fr->cg_cm);
508     }
509     if (gmx_debug_at)
510       pr_rvecs(debug,0,"cgcm",fr->cg_cm,top->cgs.nr);
511   }
512
513 #ifdef GMX_MPI
514   if (!(cr->duty & DUTY_PME)) {
515     /* Send particle coordinates to the pme nodes.
516      * Since this is only implemented for domain decomposition
517      * and domain decomposition does not use the graph,
518      * we do not need to worry about shifting.
519      */    
520
521     wallcycle_start(wcycle,ewcPP_PMESENDX);
522     GMX_MPE_LOG(ev_send_coordinates_start);
523
524     bBS = (inputrec->nwall == 2);
525     if (bBS) {
526       copy_mat(box,boxs);
527       svmul(inputrec->wall_ewald_zfac,boxs[ZZ],boxs[ZZ]);
528     }
529
530     gmx_pme_send_x(cr,bBS ? boxs : box,x,
531                    mdatoms->nChargePerturbed,lambda,
532                    ( flags & GMX_FORCE_VIRIAL),step);
533
534     GMX_MPE_LOG(ev_send_coordinates_finish);
535     wallcycle_stop(wcycle,ewcPP_PMESENDX);
536   }
537 #endif /* GMX_MPI */
538
539     /* Communicate coordinates and sum dipole if necessary */
540     if (PAR(cr))
541     {
542         wallcycle_start(wcycle,ewcMOVEX);
543         if (DOMAINDECOMP(cr))
544         {
545             dd_move_x(cr->dd,box,x);
546         }
547         else
548         {
549             move_x(fplog,cr,GMX_LEFT,GMX_RIGHT,x,nrnb);
550         }
551         /* When we don't need the total dipole we sum it in global_stat */
552         if (bStateChanged && NEED_MUTOT(*inputrec))
553         {
554             gmx_sumd(2*DIM,mu,cr);
555         }
556         wallcycle_stop(wcycle,ewcMOVEX);
557     }
558     if (bStateChanged)
559     {
560         for(i=0; i<2; i++)
561         {
562             for(j=0;j<DIM;j++)
563             {
564                 fr->mu_tot[i][j] = mu[i*DIM + j];
565             }
566         }
567     }
568     if (fr->efep == efepNO)
569     {
570         copy_rvec(fr->mu_tot[0],mu_tot);
571     }
572     else
573     {
574         for(j=0; j<DIM; j++)
575         {
576             mu_tot[j] =
577                 (1.0 - lambda)*fr->mu_tot[0][j] + lambda*fr->mu_tot[1][j];
578         }
579     }
580
581     /* Reset energies */
582     reset_enerdata(&(inputrec->opts),fr,bNS,enerd,MASTER(cr));
583     clear_rvecs(SHIFTS,fr->fshift);
584
585     if (bNS)
586     {
587         wallcycle_start(wcycle,ewcNS);
588         
589         if (graph && bStateChanged)
590         {
591             /* Calculate intramolecular shift vectors to make molecules whole */
592             mk_mshift(fplog,graph,fr->ePBC,box,x);
593         }
594
595         /* Reset long range forces if necessary */
596         if (fr->bTwinRange)
597         {
598             /* Reset the (long-range) forces if necessary */
599             clear_rvecs(fr->natoms_force_constr,bSepLRF ? fr->f_twin : f);
600         }
601
602         /* Do the actual neighbour searching and if twin range electrostatics
603          * also do the calculation of long range forces and energies.
604          */
605         dvdl = 0; 
606         ns(fplog,fr,x,box,
607            groups,&(inputrec->opts),top,mdatoms,
608            cr,nrnb,lambda,&dvdl,&enerd->grpp,bFillGrid,
609            bDoLongRange,bDoForces,bSepLRF ? fr->f_twin : f);
610         if (bSepDVDL)
611         {
612             fprintf(fplog,sepdvdlformat,"LR non-bonded",0.0,dvdl);
613         }
614         enerd->dvdl_lin += dvdl;
615         
616         wallcycle_stop(wcycle,ewcNS);
617     }
618         
619     if (inputrec->implicit_solvent && bNS) 
620     {
621         make_gb_nblist(cr,inputrec->gb_algorithm,inputrec->rlist,
622                        x,box,fr,&top->idef,graph,fr->born);
623     }
624         
625     if (DOMAINDECOMP(cr))
626     {
627         if (!(cr->duty & DUTY_PME))
628         {
629             wallcycle_start(wcycle,ewcPPDURINGPME);
630             dd_force_flop_start(cr->dd,nrnb);
631         }
632     }
633         
634     /* Start the force cycle counter.
635      * This counter is stopped in do_forcelow_level.
636      * No parallel communication should occur while this counter is running,
637      * since that will interfere with the dynamic load balancing.
638      */
639     wallcycle_start(wcycle,ewcFORCE);
640     
641     if (bDoForces)
642     {
643         /* Reset forces for which the virial is calculated separately:
644          * PME/Ewald forces if necessary */
645         if (fr->bF_NoVirSum) 
646         {
647             if (flags & GMX_FORCE_VIRIAL)
648             {
649                 fr->f_novirsum = fr->f_novirsum_alloc;
650                 GMX_BARRIER(cr->mpi_comm_mygroup);
651                 if (fr->bDomDec)
652                 {
653                     clear_rvecs(fr->f_novirsum_n,fr->f_novirsum);
654                 }
655                 else
656                 {
657                     clear_rvecs(homenr,fr->f_novirsum+start);
658                 }
659                 GMX_BARRIER(cr->mpi_comm_mygroup);
660             }
661             else
662             {
663                 /* We are not calculating the pressure so we do not need
664                  * a separate array for forces that do not contribute
665                  * to the pressure.
666                  */
667                 fr->f_novirsum = f;
668             }
669         }
670
671         if (bSepLRF)
672         {
673             /* Add the long range forces to the short range forces */
674             for(i=0; i<fr->natoms_force_constr; i++)
675             {
676                 copy_rvec(fr->f_twin[i],f[i]);
677             }
678         }
679         else if (!(fr->bTwinRange && bNS))
680         {
681             /* Clear the short-range forces */
682             clear_rvecs(fr->natoms_force_constr,f);
683         }
684
685         clear_rvec(fr->vir_diag_posres);
686
687         GMX_BARRIER(cr->mpi_comm_mygroup);
688     }
689     if (inputrec->ePull == epullCONSTRAINT)
690     {
691         clear_pull_forces(inputrec->pull);
692     }
693
694     /* update QMMMrec, if necessary */
695     if(fr->bQMMM)
696     {
697         update_QMMMrec(cr,fr,x,mdatoms,box,top);
698     }
699
700     if ((flags & GMX_FORCE_BONDED) && top->idef.il[F_POSRES].nr > 0)
701     {
702         /* Position restraints always require full pbc */
703         set_pbc(&pbc,inputrec->ePBC,box);
704         v = posres(top->idef.il[F_POSRES].nr,top->idef.il[F_POSRES].iatoms,
705                    top->idef.iparams_posres,
706                    (const rvec*)x,fr->f_novirsum,fr->vir_diag_posres,
707                    inputrec->ePBC==epbcNONE ? NULL : &pbc,lambda,&dvdl,
708                    fr->rc_scaling,fr->ePBC,fr->posres_com,fr->posres_comB);
709         if (bSepDVDL)
710         {
711             fprintf(fplog,sepdvdlformat,
712                     interaction_function[F_POSRES].longname,v,dvdl);
713         }
714         enerd->term[F_POSRES] += v;
715         /* This linear lambda dependence assumption is only correct
716          * when only k depends on lambda,
717          * not when the reference position depends on lambda.
718          * grompp checks for this.
719          */
720         enerd->dvdl_lin += dvdl;
721         inc_nrnb(nrnb,eNR_POSRES,top->idef.il[F_POSRES].nr/2);
722     }
723
724     /* Compute the bonded and non-bonded energies and optionally forces */    
725     do_force_lowlevel(fplog,step,fr,inputrec,&(top->idef),
726                       cr,nrnb,wcycle,mdatoms,&(inputrec->opts),
727                       x,hist,f,enerd,fcd,mtop,top,fr->born,
728                       &(top->atomtypes),bBornRadii,box,
729                       lambda,graph,&(top->excls),fr->mu_tot,
730                       flags,&cycles_pme);
731     
732     cycles_force = wallcycle_stop(wcycle,ewcFORCE);
733     GMX_BARRIER(cr->mpi_comm_mygroup);
734     
735     if (ed)
736     {
737         do_flood(fplog,cr,x,f,ed,box,step);
738     }
739         
740     if (DOMAINDECOMP(cr))
741     {
742         dd_force_flop_stop(cr->dd,nrnb);
743         if (wcycle)
744         {
745             dd_cycles_add(cr->dd,cycles_force-cycles_pme,ddCyclF);
746         }
747     }
748     
749     if (bDoForces)
750     {
751         if (IR_ELEC_FIELD(*inputrec))
752         {
753             /* Compute forces due to electric field */
754             calc_f_el(MASTER(cr) ? field : NULL,
755                       start,homenr,mdatoms->chargeA,x,fr->f_novirsum,
756                       inputrec->ex,inputrec->et,t);
757         }
758         
759         /* Communicate the forces */
760         if (PAR(cr))
761         {
762             wallcycle_start(wcycle,ewcMOVEF);
763             if (DOMAINDECOMP(cr))
764             {
765                 dd_move_f(cr->dd,f,fr->fshift);
766                 /* Do we need to communicate the separate force array
767                  * for terms that do not contribute to the single sum virial?
768                  * Position restraints and electric fields do not introduce
769                  * inter-cg forces, only full electrostatics methods do.
770                  * When we do not calculate the virial, fr->f_novirsum = f,
771                  * so we have already communicated these forces.
772                  */
773                 if (EEL_FULL(fr->eeltype) && cr->dd->n_intercg_excl &&
774                     (flags & GMX_FORCE_VIRIAL))
775                 {
776                     dd_move_f(cr->dd,fr->f_novirsum,NULL);
777                 }
778                 if (bSepLRF)
779                 {
780                     /* We should not update the shift forces here,
781                      * since f_twin is already included in f.
782                      */
783                     dd_move_f(cr->dd,fr->f_twin,NULL);
784                 }
785             }
786             else
787             {
788                 pd_move_f(cr,f,nrnb);
789                 if (bSepLRF)
790                 {
791                     pd_move_f(cr,fr->f_twin,nrnb);
792                 }
793             }
794             wallcycle_stop(wcycle,ewcMOVEF);
795         }
796
797         /* If we have NoVirSum forces, but we do not calculate the virial,
798          * we sum fr->f_novirum=f later.
799          */
800         if (vsite && !(fr->bF_NoVirSum && !(flags & GMX_FORCE_VIRIAL)))
801         {
802             wallcycle_start(wcycle,ewcVSITESPREAD);
803             spread_vsite_f(fplog,vsite,x,f,fr->fshift,nrnb,
804                            &top->idef,fr->ePBC,fr->bMolPBC,graph,box,cr);
805             wallcycle_stop(wcycle,ewcVSITESPREAD);
806
807             if (bSepLRF)
808             {
809                 wallcycle_start(wcycle,ewcVSITESPREAD);
810                 spread_vsite_f(fplog,vsite,x,fr->f_twin,NULL,
811                                nrnb,
812                                &top->idef,fr->ePBC,fr->bMolPBC,graph,box,cr);
813                 wallcycle_stop(wcycle,ewcVSITESPREAD);
814             }
815         }
816         
817         if (flags & GMX_FORCE_VIRIAL)
818         {
819             /* Calculation of the virial must be done after vsites! */
820             calc_virial(fplog,mdatoms->start,mdatoms->homenr,x,f,
821                         vir_force,graph,box,nrnb,fr,inputrec->ePBC);
822         }
823     }
824
825     if (inputrec->ePull == epullUMBRELLA || inputrec->ePull == epullCONST_F)
826     {
827         /* Calculate the center of mass forces, this requires communication,
828          * which is why pull_potential is called close to other communication.
829          * The virial contribution is calculated directly,
830          * which is why we call pull_potential after calc_virial.
831          */
832         set_pbc(&pbc,inputrec->ePBC,box);
833         dvdl = 0; 
834         enerd->term[F_COM_PULL] =
835             pull_potential(inputrec->ePull,inputrec->pull,mdatoms,&pbc,
836                            cr,t,lambda,x,f,vir_force,&dvdl);
837         if (bSepDVDL)
838         {
839             fprintf(fplog,sepdvdlformat,"Com pull",enerd->term[F_COM_PULL],dvdl);
840         }
841         enerd->dvdl_lin += dvdl;
842     }
843
844     if (PAR(cr) && !(cr->duty & DUTY_PME))
845     {
846         cycles_ppdpme = wallcycle_stop(wcycle,ewcPPDURINGPME);
847         dd_cycles_add(cr->dd,cycles_ppdpme,ddCyclPPduringPME);
848
849         /* In case of node-splitting, the PP nodes receive the long-range 
850          * forces, virial and energy from the PME nodes here.
851          */    
852         wallcycle_start(wcycle,ewcPP_PMEWAITRECVF);
853         dvdl = 0;
854         gmx_pme_receive_f(cr,fr->f_novirsum,fr->vir_el_recip,&e,&dvdl,
855                           &cycles_seppme);
856         if (bSepDVDL)
857         {
858             fprintf(fplog,sepdvdlformat,"PME mesh",e,dvdl);
859         }
860         enerd->term[F_COUL_RECIP] += e;
861         enerd->dvdl_lin += dvdl;
862         if (wcycle)
863         {
864             dd_cycles_add(cr->dd,cycles_seppme,ddCyclPME);
865         }
866         wallcycle_stop(wcycle,ewcPP_PMEWAITRECVF);
867     }
868
869     if (bDoForces && fr->bF_NoVirSum)
870     {
871         if (vsite)
872         {
873             /* Spread the mesh force on virtual sites to the other particles... 
874              * This is parallellized. MPI communication is performed
875              * if the constructing atoms aren't local.
876              */
877             wallcycle_start(wcycle,ewcVSITESPREAD);
878             spread_vsite_f(fplog,vsite,x,fr->f_novirsum,NULL,nrnb,
879                            &top->idef,fr->ePBC,fr->bMolPBC,graph,box,cr);
880             wallcycle_stop(wcycle,ewcVSITESPREAD);
881         }
882         if (flags & GMX_FORCE_VIRIAL)
883         {
884             /* Now add the forces, this is local */
885             if (fr->bDomDec)
886             {
887                 sum_forces(0,fr->f_novirsum_n,f,fr->f_novirsum);
888             }
889             else
890             {
891                 sum_forces(start,start+homenr,f,fr->f_novirsum);
892             }
893             if (EEL_FULL(fr->eeltype))
894             {
895                 /* Add the mesh contribution to the virial */
896                 m_add(vir_force,fr->vir_el_recip,vir_force);
897             }
898             if (debug)
899             {
900                 pr_rvecs(debug,0,"vir_force",vir_force,DIM);
901             }
902         }
903     }
904     
905     /* Sum the potential energy terms from group contributions */
906     sum_epot(&(inputrec->opts),enerd);
907     
908     if (fr->print_force >= 0 && bDoForces)
909     {
910         print_large_forces(stderr,mdatoms,cr,step,fr->print_force,x,f);
911     }
912 }
913
914 void do_constrain_first(FILE *fplog,gmx_constr_t constr,
915                         t_inputrec *ir,t_mdatoms *md,
916                         t_state *state,rvec *f,
917                         t_graph *graph,t_commrec *cr,t_nrnb *nrnb,
918                         t_forcerec *fr, gmx_localtop_t *top, tensor shake_vir)
919 {
920     int    i,m,start,end;
921     gmx_large_int_t step;
922     double mass,tmass,vcm[4];
923     real   dt=ir->delta_t;
924     real   dvdlambda;
925     rvec   *savex;
926     
927     snew(savex,state->natoms);
928
929     start = md->start;
930     end   = md->homenr + start;
931     
932     if (debug)
933         fprintf(debug,"vcm: start=%d, homenr=%d, end=%d\n",
934                 start,md->homenr,end);
935     /* Do a first constrain to reset particles... */
936     step = ir->init_step;
937     if (fplog)
938     {
939         char buf[STEPSTRSIZE];
940         fprintf(fplog,"\nConstraining the starting coordinates (step %s)\n",
941                 gmx_step_str(step,buf));
942     }
943     dvdlambda = 0;
944     
945     /* constrain the current position */
946     constrain(NULL,TRUE,FALSE,constr,&(top->idef),
947               ir,NULL,cr,step,0,md,
948               state->x,state->x,NULL,
949               state->box,state->lambda,&dvdlambda,
950               NULL,NULL,nrnb,econqCoord,ir->epc==epcMTTK,state->veta,state->veta);
951     if (EI_VV(ir->eI)) 
952     {
953         /* constrain the inital velocity, and save it */
954         /* also may be useful if we need the ekin from the halfstep for velocity verlet */
955         /* might not yet treat veta correctly */
956         constrain(NULL,TRUE,FALSE,constr,&(top->idef),
957                   ir,NULL,cr,step,0,md,
958                   state->x,state->v,state->v,
959                   state->box,state->lambda,&dvdlambda,
960                   NULL,NULL,nrnb,econqVeloc,ir->epc==epcMTTK,state->veta,state->veta);
961     }
962     /* constrain the inital velocities at t-dt/2 */
963     if (EI_STATE_VELOCITY(ir->eI) && ir->eI!=eiVV)
964     {
965         for(i=start; (i<end); i++) 
966         {
967             for(m=0; (m<DIM); m++) 
968             {
969                 /* Reverse the velocity */
970                 state->v[i][m] = -state->v[i][m];
971                 /* Store the position at t-dt in buf */
972                 savex[i][m] = state->x[i][m] + dt*state->v[i][m];
973             }
974         }
975     /* Shake the positions at t=-dt with the positions at t=0                        
976      * as reference coordinates.                                                     
977          */
978         if (fplog)
979         {
980             char buf[STEPSTRSIZE];
981             fprintf(fplog,"\nConstraining the coordinates at t0-dt (step %s)\n",
982                     gmx_step_str(step,buf));
983         }
984         dvdlambda = 0;
985         constrain(NULL,TRUE,FALSE,constr,&(top->idef),
986                   ir,NULL,cr,step,-1,md,
987                   state->x,savex,NULL,
988                   state->box,state->lambda,&dvdlambda,
989                   state->v,NULL,nrnb,econqCoord,ir->epc==epcMTTK,state->veta,state->veta);
990         
991         for(i=start; i<end; i++) {
992             for(m=0; m<DIM; m++) {
993                 /* Re-reverse the velocities */
994                 state->v[i][m] = -state->v[i][m];
995             }
996         }
997     }
998     
999     for(m=0; (m<4); m++)
1000         vcm[m] = 0;
1001     for(i=start; i<end; i++) {
1002         mass = md->massT[i];
1003         for(m=0; m<DIM; m++) {
1004             vcm[m] += state->v[i][m]*mass;
1005         }
1006         vcm[3] += mass;
1007     }
1008     
1009     if (ir->nstcomm != 0 || debug) {
1010         /* Compute the global sum of vcm */
1011         if (debug)
1012             fprintf(debug,"vcm: %8.3f  %8.3f  %8.3f,"
1013                     " total mass = %12.5e\n",vcm[XX],vcm[YY],vcm[ZZ],vcm[3]);
1014         if (PAR(cr))
1015             gmx_sumd(4,vcm,cr);
1016         tmass = vcm[3];
1017         for(m=0; (m<DIM); m++)
1018             vcm[m] /= tmass;
1019         if (debug) 
1020             fprintf(debug,"vcm: %8.3f  %8.3f  %8.3f,"
1021                     " total mass = %12.5e\n",vcm[XX],vcm[YY],vcm[ZZ],tmass);
1022         if (ir->nstcomm != 0) {
1023             /* Now we have the velocity of center of mass, let's remove it */
1024             for(i=start; (i<end); i++) {
1025                 for(m=0; (m<DIM); m++)
1026                     state->v[i][m] -= vcm[m];
1027             }
1028
1029         }
1030     }
1031     sfree(savex);
1032 }
1033
1034 void calc_enervirdiff(FILE *fplog,int eDispCorr,t_forcerec *fr)
1035 {
1036   double eners[2],virs[2],enersum,virsum,y0,f,g,h;
1037   double r0,r1,r,rc3,rc9,ea,eb,ec,pa,pb,pc,pd;
1038   double invscale,invscale2,invscale3;
1039   int    ri0,ri1,ri,i,offstart,offset;
1040   real   scale,*vdwtab; 
1041
1042   fr->enershiftsix = 0;
1043   fr->enershifttwelve = 0;
1044   fr->enerdiffsix = 0;
1045   fr->enerdifftwelve = 0;
1046   fr->virdiffsix = 0;
1047   fr->virdifftwelve = 0;
1048
1049   if (eDispCorr != edispcNO) {
1050     for(i=0; i<2; i++) {
1051       eners[i] = 0;
1052       virs[i]  = 0;
1053     }
1054     if ((fr->vdwtype == evdwSWITCH) || (fr->vdwtype == evdwSHIFT)) {
1055       if (fr->rvdw_switch == 0)
1056         gmx_fatal(FARGS,
1057                   "With dispersion correction rvdw-switch can not be zero "
1058                   "for vdw-type = %s",evdw_names[fr->vdwtype]);
1059
1060       scale  = fr->nblists[0].tab.scale;
1061       vdwtab = fr->nblists[0].vdwtab;
1062
1063       /* Round the cut-offs to exact table values for precision */
1064       ri0 = floor(fr->rvdw_switch*scale);
1065       ri1 = ceil(fr->rvdw*scale);
1066       r0  = ri0/scale;
1067       r1  = ri1/scale;
1068       rc3 = r0*r0*r0;
1069       rc9  = rc3*rc3*rc3;
1070
1071       if (fr->vdwtype == evdwSHIFT) {
1072         /* Determine the constant energy shift below rvdw_switch */
1073         fr->enershiftsix    = (real)(-1.0/(rc3*rc3)) - vdwtab[8*ri0];
1074         fr->enershifttwelve = (real)( 1.0/(rc9*rc3)) - vdwtab[8*ri0 + 4];
1075       }
1076       /* Add the constant part from 0 to rvdw_switch.
1077        * This integration from 0 to rvdw_switch overcounts the number
1078        * of interactions by 1, as it also counts the self interaction.
1079        * We will correct for this later.
1080        */
1081       eners[0] += 4.0*M_PI*fr->enershiftsix*rc3/3.0;
1082       eners[1] += 4.0*M_PI*fr->enershifttwelve*rc3/3.0;
1083       
1084       invscale = 1.0/(scale);  
1085       invscale2 = invscale*invscale;
1086       invscale3 = invscale*invscale2;
1087
1088       /* following summation derived from cubic spline definition,
1089         Numerical Recipies in C, second edition, p. 113-116.  Exact
1090         for the cubic spline.  We first calculate the negative of
1091         the energy from rvdw to rvdw_switch, assuming that g(r)=1,
1092         and then add the more standard, abrupt cutoff correction to
1093         that result, yielding the long-range correction for a
1094         switched function.  We perform both the pressure and energy
1095         loops at the same time for simplicity, as the computational
1096         cost is low. */
1097       
1098       for (i=0;i<2;i++) {
1099         enersum = 0.0; virsum = 0.0;
1100         if (i==0)
1101           offstart = 0;
1102         else
1103           offstart = 4;
1104         for (ri=ri0; ri<ri1; ri++) {
1105           r = ri*invscale;
1106           ea = invscale3;
1107           eb = 2.0*invscale2*r;
1108           ec = invscale*r*r;
1109           
1110           pa = invscale3;
1111           pb = 3.0*invscale2*r;
1112           pc = 3.0*invscale*r*r;
1113           pd = r*r*r;
1114           
1115           /* this "8" is from the packing in the vdwtab array - perhaps
1116             should be #define'ed? */
1117           offset = 8*ri + offstart;
1118           y0 = vdwtab[offset];
1119           f = vdwtab[offset+1];
1120           g = vdwtab[offset+2];
1121           h = vdwtab[offset+3];
1122           
1123           enersum += y0*(ea/3 + eb/2 + ec) + f*(ea/4 + eb/3 + ec/2)+
1124             g*(ea/5 + eb/4 + ec/3) + h*(ea/6 + eb/5 + ec/4);  
1125           virsum  +=  f*(pa/4 + pb/3 + pc/2 + pd) + 
1126             2*g*(pa/5 + pb/4 + pc/3 + pd/2) + 3*h*(pa/6 + pb/5 + pc/4 + pd/3);
1127           
1128         }
1129         enersum *= 4.0*M_PI;
1130         virsum  *= 4.0*M_PI; 
1131         eners[i] -= enersum;
1132         virs[i]  -= virsum;
1133       }
1134
1135       /* now add the correction for rvdw_switch to infinity */
1136       eners[0] += -4.0*M_PI/(3.0*rc3);
1137       eners[1] +=  4.0*M_PI/(9.0*rc9);
1138       virs[0]  +=  8.0*M_PI/rc3;
1139       virs[1]  += -16.0*M_PI/(3.0*rc9);
1140     } 
1141     else if ((fr->vdwtype == evdwCUT) || (fr->vdwtype == evdwUSER)) {
1142       if (fr->vdwtype == evdwUSER && fplog)
1143         fprintf(fplog,
1144                 "WARNING: using dispersion correction with user tables\n");
1145       rc3  = fr->rvdw*fr->rvdw*fr->rvdw;
1146       rc9  = rc3*rc3*rc3;
1147       eners[0] += -4.0*M_PI/(3.0*rc3);
1148       eners[1] +=  4.0*M_PI/(9.0*rc9);
1149       virs[0]  +=  8.0*M_PI/rc3;
1150       virs[1]  += -16.0*M_PI/(3.0*rc9);
1151     } else {
1152       gmx_fatal(FARGS,
1153                 "Dispersion correction is not implemented for vdw-type = %s",
1154                 evdw_names[fr->vdwtype]);
1155     }
1156     fr->enerdiffsix    = eners[0];
1157     fr->enerdifftwelve = eners[1];
1158     /* The 0.5 is due to the Gromacs definition of the virial */
1159     fr->virdiffsix     = 0.5*virs[0];
1160     fr->virdifftwelve  = 0.5*virs[1];
1161   }
1162 }
1163
1164 void calc_dispcorr(FILE *fplog,t_inputrec *ir,t_forcerec *fr,
1165                    gmx_large_int_t step,int natoms,
1166                    matrix box,real lambda,tensor pres,tensor virial,
1167                    real *prescorr, real *enercorr, real *dvdlcorr)
1168 {
1169     gmx_bool bCorrAll,bCorrPres;
1170     real dvdlambda,invvol,dens,ninter,avcsix,avctwelve,enerdiff,svir=0,spres=0;
1171     int  m;
1172     
1173     *prescorr = 0;
1174     *enercorr = 0;
1175     *dvdlcorr = 0;
1176     
1177     clear_mat(virial);
1178     clear_mat(pres);
1179     
1180     if (ir->eDispCorr != edispcNO) {
1181         bCorrAll  = (ir->eDispCorr == edispcAllEner ||
1182                      ir->eDispCorr == edispcAllEnerPres);
1183         bCorrPres = (ir->eDispCorr == edispcEnerPres ||
1184                      ir->eDispCorr == edispcAllEnerPres);
1185         
1186         invvol = 1/det(box);
1187         if (fr->n_tpi) 
1188         {
1189             /* Only correct for the interactions with the inserted molecule */
1190             dens = (natoms - fr->n_tpi)*invvol;
1191             ninter = fr->n_tpi;
1192         } 
1193         else 
1194         {
1195             dens = natoms*invvol;
1196             ninter = 0.5*natoms;
1197         }
1198         
1199         if (ir->efep == efepNO) 
1200         {
1201             avcsix    = fr->avcsix[0];
1202             avctwelve = fr->avctwelve[0];
1203         } 
1204         else 
1205         {
1206             avcsix    = (1 - lambda)*fr->avcsix[0]    + lambda*fr->avcsix[1];
1207             avctwelve = (1 - lambda)*fr->avctwelve[0] + lambda*fr->avctwelve[1];
1208         }
1209         
1210         enerdiff = ninter*(dens*fr->enerdiffsix - fr->enershiftsix);
1211         *enercorr += avcsix*enerdiff;
1212         dvdlambda = 0.0;
1213         if (ir->efep != efepNO) 
1214         {
1215             dvdlambda += (fr->avcsix[1] - fr->avcsix[0])*enerdiff;
1216         }
1217         if (bCorrAll) 
1218         {
1219             enerdiff = ninter*(dens*fr->enerdifftwelve - fr->enershifttwelve);
1220             *enercorr += avctwelve*enerdiff;
1221             if (fr->efep != efepNO) 
1222             {
1223                 dvdlambda += (fr->avctwelve[1] - fr->avctwelve[0])*enerdiff;
1224             }
1225         }
1226         
1227         if (bCorrPres) 
1228         {
1229             svir = ninter*dens*avcsix*fr->virdiffsix/3.0;
1230             if (ir->eDispCorr == edispcAllEnerPres)
1231             {
1232                 svir += ninter*dens*avctwelve*fr->virdifftwelve/3.0;
1233             }
1234             /* The factor 2 is because of the Gromacs virial definition */
1235             spres = -2.0*invvol*svir*PRESFAC;
1236             
1237             for(m=0; m<DIM; m++) {
1238                 virial[m][m] += svir;
1239                 pres[m][m] += spres;
1240             }
1241             *prescorr += spres;
1242         }
1243         
1244         /* Can't currently control when it prints, for now, just print when degugging */
1245         if (debug)
1246         {
1247             if (bCorrAll) {
1248                 fprintf(debug,"Long Range LJ corr.: <C6> %10.4e, <C12> %10.4e\n",
1249                         avcsix,avctwelve);
1250             }
1251             if (bCorrPres) 
1252             {
1253                 fprintf(debug,
1254                         "Long Range LJ corr.: Epot %10g, Pres: %10g, Vir: %10g\n",
1255                         *enercorr,spres,svir);
1256             }
1257             else
1258             {
1259                 fprintf(debug,"Long Range LJ corr.: Epot %10g\n",*enercorr);
1260             }
1261         }
1262         
1263         if (fr->bSepDVDL && do_per_step(step,ir->nstlog))
1264         {
1265             fprintf(fplog,sepdvdlformat,"Dispersion correction",
1266                     *enercorr,dvdlambda);
1267         }
1268         if (fr->efep != efepNO) 
1269         {
1270             *dvdlcorr += dvdlambda;
1271         }
1272     }
1273 }
1274
1275 void do_pbc_first(FILE *fplog,matrix box,t_forcerec *fr,
1276                   t_graph *graph,rvec x[])
1277 {
1278   if (fplog)
1279     fprintf(fplog,"Removing pbc first time\n");
1280   calc_shifts(box,fr->shift_vec);
1281   if (graph) {
1282     mk_mshift(fplog,graph,fr->ePBC,box,x);
1283     if (gmx_debug_at)
1284       p_graph(debug,"do_pbc_first 1",graph);
1285     shift_self(graph,box,x);
1286     /* By doing an extra mk_mshift the molecules that are broken
1287      * because they were e.g. imported from another software
1288      * will be made whole again. Such are the healing powers
1289      * of GROMACS.
1290      */
1291     mk_mshift(fplog,graph,fr->ePBC,box,x);
1292     if (gmx_debug_at)
1293       p_graph(debug,"do_pbc_first 2",graph);
1294   }
1295   if (fplog)
1296     fprintf(fplog,"Done rmpbc\n");
1297 }
1298
1299 static void low_do_pbc_mtop(FILE *fplog,int ePBC,matrix box,
1300                             gmx_mtop_t *mtop,rvec x[],
1301                             gmx_bool bFirst)
1302 {
1303   t_graph *graph;
1304   int mb,as,mol;
1305   gmx_molblock_t *molb;
1306
1307   if (bFirst && fplog)
1308     fprintf(fplog,"Removing pbc first time\n");
1309
1310   snew(graph,1);
1311   as = 0;
1312   for(mb=0; mb<mtop->nmolblock; mb++) {
1313     molb = &mtop->molblock[mb];
1314     if (molb->natoms_mol == 1 || 
1315         (!bFirst && mtop->moltype[molb->type].cgs.nr == 1)) {
1316       /* Just one atom or charge group in the molecule, no PBC required */
1317       as += molb->nmol*molb->natoms_mol;
1318     } else {
1319       /* Pass NULL iso fplog to avoid graph prints for each molecule type */
1320       mk_graph_ilist(NULL,mtop->moltype[molb->type].ilist,
1321                      0,molb->natoms_mol,FALSE,FALSE,graph);
1322       
1323       for(mol=0; mol<molb->nmol; mol++) {
1324         mk_mshift(fplog,graph,ePBC,box,x+as);
1325         
1326         shift_self(graph,box,x+as);
1327         /* The molecule is whole now.
1328          * We don't need the second mk_mshift call as in do_pbc_first,
1329          * since we no longer need this graph.
1330          */
1331         
1332         as += molb->natoms_mol;
1333       }
1334       done_graph(graph);
1335     }
1336   }
1337   sfree(graph);
1338 }
1339
1340 void do_pbc_first_mtop(FILE *fplog,int ePBC,matrix box,
1341                        gmx_mtop_t *mtop,rvec x[])
1342 {
1343   low_do_pbc_mtop(fplog,ePBC,box,mtop,x,TRUE);
1344 }
1345
1346 void do_pbc_mtop(FILE *fplog,int ePBC,matrix box,
1347                  gmx_mtop_t *mtop,rvec x[])
1348 {
1349   low_do_pbc_mtop(fplog,ePBC,box,mtop,x,FALSE);
1350 }
1351
1352 void finish_run(FILE *fplog,t_commrec *cr,const char *confout,
1353                 t_inputrec *inputrec,
1354                 t_nrnb nrnb[],gmx_wallcycle_t wcycle,
1355                 gmx_runtime_t *runtime,
1356                 gmx_bool bWriteStat)
1357 {
1358   int    i,j;
1359   t_nrnb *nrnb_tot=NULL;
1360   real   delta_t;
1361   double nbfs,mflop;
1362   double cycles[ewcNR];
1363
1364   wallcycle_sum(cr,wcycle,cycles);
1365
1366   if (cr->nnodes > 1) {
1367     if (SIMMASTER(cr))
1368       snew(nrnb_tot,1);
1369 #ifdef GMX_MPI
1370     MPI_Reduce(nrnb->n,nrnb_tot->n,eNRNB,MPI_DOUBLE,MPI_SUM,
1371                MASTERRANK(cr),cr->mpi_comm_mysim);
1372 #endif  
1373   } else {
1374     nrnb_tot = nrnb;
1375   }
1376     
1377   if (SIMMASTER(cr)) {
1378     print_flop(fplog,nrnb_tot,&nbfs,&mflop);
1379     if (cr->nnodes > 1) {
1380       sfree(nrnb_tot);
1381     }
1382   }
1383
1384   if ((cr->duty & DUTY_PP) && DOMAINDECOMP(cr)) {
1385     print_dd_statistics(cr,inputrec,fplog);
1386   }
1387
1388 #ifdef GMX_MPI
1389     if (PARTDECOMP(cr))
1390     {
1391         if (MASTER(cr))
1392         {
1393             t_nrnb     *nrnb_all;
1394             int        s;
1395             MPI_Status stat;
1396
1397             snew(nrnb_all,cr->nnodes);
1398             nrnb_all[0] = *nrnb;
1399             for(s=1; s<cr->nnodes; s++)
1400             {
1401                 MPI_Recv(nrnb_all[s].n,eNRNB,MPI_DOUBLE,s,0,
1402                          cr->mpi_comm_mysim,&stat);
1403             }
1404             pr_load(fplog,cr,nrnb_all);
1405             sfree(nrnb_all);
1406         }
1407         else
1408         {
1409             MPI_Send(nrnb->n,eNRNB,MPI_DOUBLE,MASTERRANK(cr),0,
1410                      cr->mpi_comm_mysim);
1411         }
1412     }
1413 #endif  
1414
1415   if (SIMMASTER(cr)) {
1416     wallcycle_print(fplog,cr->nnodes,cr->npmenodes,runtime->realtime,
1417                     wcycle,cycles);
1418
1419     if (EI_DYNAMICS(inputrec->eI)) {
1420       delta_t = inputrec->delta_t;
1421     } else {
1422       delta_t = 0;
1423     }
1424     
1425     if (fplog) {
1426         print_perf(fplog,runtime->proctime,runtime->realtime,
1427                    cr->nnodes-cr->npmenodes,
1428                    runtime->nsteps_done,delta_t,nbfs,mflop);
1429     }
1430     if (bWriteStat) {
1431         print_perf(stderr,runtime->proctime,runtime->realtime,
1432                    cr->nnodes-cr->npmenodes,
1433                    runtime->nsteps_done,delta_t,nbfs,mflop);
1434     }
1435
1436     /*
1437     runtime=inputrec->nsteps*inputrec->delta_t;
1438     if (bWriteStat) {
1439       if (cr->nnodes == 1)
1440         fprintf(stderr,"\n\n");
1441       print_perf(stderr,nodetime,realtime,runtime,&ntot,
1442                  cr->nnodes-cr->npmenodes,FALSE);
1443     }
1444     wallcycle_print(fplog,cr->nnodes,cr->npmenodes,realtime,wcycle,cycles);
1445     print_perf(fplog,nodetime,realtime,runtime,&ntot,cr->nnodes-cr->npmenodes,
1446                TRUE);
1447     if (PARTDECOMP(cr))
1448       pr_load(fplog,cr,nrnb_all);
1449     if (cr->nnodes > 1)
1450       sfree(nrnb_all);
1451     */
1452   }
1453 }
1454
1455 void init_md(FILE *fplog,
1456              t_commrec *cr,t_inputrec *ir,const output_env_t oenv,
1457              double *t,double *t0,
1458              real *lambda,double *lam0,
1459              t_nrnb *nrnb,gmx_mtop_t *mtop,
1460              gmx_update_t *upd,
1461              int nfile,const t_filenm fnm[],
1462              gmx_mdoutf_t **outf,t_mdebin **mdebin,
1463              tensor force_vir,tensor shake_vir,rvec mu_tot,
1464              gmx_bool *bSimAnn,t_vcm **vcm, t_state *state, unsigned long Flags)
1465 {
1466     int  i,j,n;
1467     real tmpt,mod;
1468         
1469     /* Initial values */
1470     *t = *t0       = ir->init_t;
1471     if (ir->efep != efepNO)
1472     {
1473         *lam0 = ir->init_lambda;
1474         *lambda = *lam0 + ir->init_step*ir->delta_lambda;
1475     }
1476     else
1477     {
1478         *lambda = *lam0   = 0.0;
1479     } 
1480
1481     *bSimAnn=FALSE;
1482     for(i=0;i<ir->opts.ngtc;i++)
1483     {
1484         /* set bSimAnn if any group is being annealed */
1485         if(ir->opts.annealing[i]!=eannNO)
1486         {
1487             *bSimAnn = TRUE;
1488         }
1489     }
1490     if (*bSimAnn)
1491     {
1492         update_annealing_target_temp(&(ir->opts),ir->init_t);
1493     }
1494     
1495     if (upd)
1496     {
1497         *upd = init_update(fplog,ir);
1498     }
1499     
1500     if (vcm != NULL)
1501     {
1502         *vcm = init_vcm(fplog,&mtop->groups,ir);
1503     }
1504     
1505     if (EI_DYNAMICS(ir->eI) && !(Flags & MD_APPENDFILES))
1506     {
1507         if (ir->etc == etcBERENDSEN)
1508         {
1509             please_cite(fplog,"Berendsen84a");
1510         }
1511         if (ir->etc == etcVRESCALE)
1512         {
1513             please_cite(fplog,"Bussi2007a");
1514         }
1515     }
1516     
1517     init_nrnb(nrnb);
1518     
1519     if (nfile != -1)
1520     {
1521         *outf = init_mdoutf(nfile,fnm,Flags,cr,ir,oenv);
1522
1523         *mdebin = init_mdebin((Flags & MD_APPENDFILES) ? NULL : (*outf)->fp_ene,
1524                               mtop,ir, (*outf)->fp_dhdl);
1525     }
1526     
1527     /* Initiate variables */  
1528     clear_mat(force_vir);
1529     clear_mat(shake_vir);
1530     clear_rvec(mu_tot);
1531     
1532     debug_gmx();
1533 }
1534