f640d099adc343970b778827bbbbd7ce09fe485b
[alexxy/gromacs.git] / src / programs / mdrun / md.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  * Gallium Rubidium Oxygen Manganese Argon Carbon Silicon
35  */
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39
40 #if ((defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64) && !defined __CYGWIN__ && !defined __CYGWIN32__)
41 /* _isnan() */
42 #include <float.h>
43 #endif
44
45 #include "typedefs.h"
46 #include "smalloc.h"
47 #include "sysstuff.h"
48 #include "vec.h"
49 #include "statutil.h"
50 #include "vcm.h"
51 #include "mdebin.h"
52 #include "nrnb.h"
53 #include "calcmu.h"
54 #include "index.h"
55 #include "vsite.h"
56 #include "update.h"
57 #include "ns.h"
58 #include "trnio.h"
59 #include "xtcio.h"
60 #include "mdrun.h"
61 #include "confio.h"
62 #include "network.h"
63 #include "pull.h"
64 #include "xvgr.h"
65 #include "physics.h"
66 #include "names.h"
67 #include "xmdrun.h"
68 #include "ionize.h"
69 #include "disre.h"
70 #include "orires.h"
71 #include "dihre.h"
72 #include "pppm.h"
73 #include "pme.h"
74 #include "mdatoms.h"
75 #include "repl_ex.h"
76 #include "qmmm.h"
77 #include "mpelogging.h"
78 #include "domdec.h"
79 #include "partdec.h"
80 #include "topsort.h"
81 #include "coulomb.h"
82 #include "constr.h"
83 #include "shellfc.h"
84 #include "compute_io.h"
85 #include "mvdata.h"
86 #include "checkpoint.h"
87 #include "mtop_util.h"
88 #include "sighandler.h"
89 #include "membed.h"
90 #include "string2.h"
91
92 #ifdef GMX_LIB_MPI
93 #include <mpi.h>
94 #endif
95 #ifdef GMX_THREADS
96 #include "tmpi.h"
97 #endif
98
99 #ifdef GMX_FAHCORE
100 #include "corewrap.h"
101 #endif
102
103
104 double do_md(FILE *fplog,t_commrec *cr,int nfile,const t_filenm fnm[],
105              const output_env_t oenv, gmx_bool bVerbose,gmx_bool bCompact,
106              int nstglobalcomm,
107              gmx_vsite_t *vsite,gmx_constr_t constr,
108              int stepout,t_inputrec *ir,
109              gmx_mtop_t *top_global,
110              t_fcdata *fcd,
111              t_state *state_global,
112              t_mdatoms *mdatoms,
113              t_nrnb *nrnb,gmx_wallcycle_t wcycle,
114              gmx_edsam_t ed,t_forcerec *fr,
115              int repl_ex_nst,int repl_ex_seed,gmx_membed_t *membed,
116              real cpt_period,real max_hours,
117              const char *deviceOptions,
118              unsigned long Flags,
119              gmx_runtime_t *runtime)
120 {
121     gmx_mdoutf_t *outf;
122     gmx_large_int_t step,step_rel;
123     double     run_time;
124     double     t,t0,lam0;
125     gmx_bool       bGStatEveryStep,bGStat,bNstEner,bCalcEnerPres;
126     gmx_bool       bNS,bNStList,bSimAnn,bStopCM,bRerunMD,bNotLastFrame=FALSE,
127                bFirstStep,bStateFromTPX,bInitStep,bLastStep,
128                bBornRadii,bStartingFromCpt;
129     gmx_bool       bDoDHDL=FALSE;
130     gmx_bool       do_ene,do_log,do_verbose,bRerunWarnNoV=TRUE,
131                bForceUpdate=FALSE,bCPT;
132     int        mdof_flags;
133     gmx_bool       bMasterState;
134     int        force_flags,cglo_flags;
135     tensor     force_vir,shake_vir,total_vir,tmp_vir,pres;
136     int        i,m;
137     t_trxstatus *status;
138     rvec       mu_tot;
139     t_vcm      *vcm;
140     t_state    *bufstate=NULL;   
141     matrix     *scale_tot,pcoupl_mu,M,ebox;
142     gmx_nlheur_t nlh;
143     t_trxframe rerun_fr;
144     gmx_repl_ex_t repl_ex=NULL;
145     int        nchkpt=1;
146
147     gmx_localtop_t *top;        
148     t_mdebin *mdebin=NULL;
149     t_state    *state=NULL;
150     rvec       *f_global=NULL;
151     int        n_xtc=-1;
152     rvec       *x_xtc=NULL;
153     gmx_enerdata_t *enerd;
154     rvec       *f=NULL;
155     gmx_global_stat_t gstat;
156     gmx_update_t upd=NULL;
157     t_graph    *graph=NULL;
158     globsig_t   gs;
159
160     gmx_bool        bFFscan;
161     gmx_groups_t *groups;
162     gmx_ekindata_t *ekind, *ekind_save;
163     gmx_shellfc_t shellfc;
164     int         count,nconverged=0;
165     real        timestep=0;
166     double      tcount=0;
167     gmx_bool        bIonize=FALSE;
168     gmx_bool        bTCR=FALSE,bConverged=TRUE,bOK,bSumEkinhOld,bExchanged;
169     gmx_bool        bAppend;
170     gmx_bool        bResetCountersHalfMaxH=FALSE;
171     gmx_bool        bVV,bIterations,bFirstIterate,bTemp,bPres,bTrotter;
172     real        temp0,mu_aver=0,dvdl;
173     int         a0,a1,gnx=0,ii;
174     atom_id     *grpindex=NULL;
175     char        *grpname;
176     t_coupl_rec *tcr=NULL;
177     rvec        *xcopy=NULL,*vcopy=NULL,*cbuf=NULL;
178     matrix      boxcopy={{0}},lastbox;
179         tensor      tmpvir;
180         real        fom,oldfom,veta_save,pcurr,scalevir,tracevir;
181         real        vetanew = 0;
182     double      cycles;
183         real        saved_conserved_quantity = 0;
184     real        last_ekin = 0;
185         int         iter_i;
186         t_extmass   MassQ;
187     int         **trotter_seq; 
188     char        sbuf[STEPSTRSIZE],sbuf2[STEPSTRSIZE];
189     int         handled_stop_condition=gmx_stop_cond_none; /* compare to get_stop_condition*/
190     gmx_iterate_t iterate;
191     gmx_large_int_t multisim_nsteps=-1; /* number of steps to do  before first multisim 
192                                           simulation stops. If equal to zero, don't
193                                           communicate any more between multisims.*/
194 #ifdef GMX_FAHCORE
195     /* Temporary addition for FAHCORE checkpointing */
196     int chkpt_ret;
197 #endif
198
199     /* Check for special mdrun options */
200     bRerunMD = (Flags & MD_RERUN);
201     bIonize  = (Flags & MD_IONIZE);
202     bFFscan  = (Flags & MD_FFSCAN);
203     bAppend  = (Flags & MD_APPENDFILES);
204     if (Flags & MD_RESETCOUNTERSHALFWAY)
205     {
206         if (ir->nsteps > 0)
207         {
208             /* Signal to reset the counters half the simulation steps. */
209             wcycle_set_reset_counters(wcycle,ir->nsteps/2);
210         }
211         /* Signal to reset the counters halfway the simulation time. */
212         bResetCountersHalfMaxH = (max_hours > 0);
213     }
214
215     /* md-vv uses averaged full step velocities for T-control 
216        md-vv-avek uses averaged half step velocities for T-control (but full step ekin for P control)
217        md uses averaged half step kinetic energies to determine temperature unless defined otherwise by GMX_EKIN_AVE_VEL; */
218     bVV = EI_VV(ir->eI);
219     if (bVV) /* to store the initial velocities while computing virial */
220     {
221         snew(cbuf,top_global->natoms);
222     }
223     /* all the iteratative cases - only if there are constraints */ 
224     bIterations = ((IR_NPT_TROTTER(ir)) && (constr) && (!bRerunMD));
225     bTrotter = (bVV && (IR_NPT_TROTTER(ir) || (IR_NVT_TROTTER(ir))));        
226     
227     if (bRerunMD)
228     {
229         /* Since we don't know if the frames read are related in any way,
230          * rebuild the neighborlist at every step.
231          */
232         ir->nstlist       = 1;
233         ir->nstcalcenergy = 1;
234         nstglobalcomm     = 1;
235     }
236
237     check_ir_old_tpx_versions(cr,fplog,ir,top_global);
238
239     nstglobalcomm = check_nstglobalcomm(fplog,cr,nstglobalcomm,ir);
240     bGStatEveryStep = (nstglobalcomm == 1);
241
242     if (!bGStatEveryStep && ir->nstlist == -1 && fplog != NULL)
243     {
244         fprintf(fplog,
245                 "To reduce the energy communication with nstlist = -1\n"
246                 "the neighbor list validity should not be checked at every step,\n"
247                 "this means that exact integration is not guaranteed.\n"
248                 "The neighbor list validity is checked after:\n"
249                 "  <n.list life time> - 2*std.dev.(n.list life time)  steps.\n"
250                 "In most cases this will result in exact integration.\n"
251                 "This reduces the energy communication by a factor of 2 to 3.\n"
252                 "If you want less energy communication, set nstlist > 3.\n\n");
253     }
254
255     if (bRerunMD || bFFscan)
256     {
257         ir->nstxtcout = 0;
258     }
259     groups = &top_global->groups;
260
261     /* Initial values */
262     init_md(fplog,cr,ir,oenv,&t,&t0,&state_global->lambda,&lam0,
263             nrnb,top_global,&upd,
264             nfile,fnm,&outf,&mdebin,
265             force_vir,shake_vir,mu_tot,&bSimAnn,&vcm,state_global,Flags);
266
267     clear_mat(total_vir);
268     clear_mat(pres);
269     /* Energy terms and groups */
270     snew(enerd,1);
271     init_enerdata(top_global->groups.grps[egcENER].nr,ir->n_flambda,enerd);
272     if (DOMAINDECOMP(cr))
273     {
274         f = NULL;
275     }
276     else
277     {
278         snew(f,top_global->natoms);
279     }
280
281     /* Kinetic energy data */
282     snew(ekind,1);
283     init_ekindata(fplog,top_global,&(ir->opts),ekind);
284     /* needed for iteration of constraints */
285     snew(ekind_save,1);
286     init_ekindata(fplog,top_global,&(ir->opts),ekind_save);
287     /* Copy the cos acceleration to the groups struct */    
288     ekind->cosacc.cos_accel = ir->cos_accel;
289
290     gstat = global_stat_init(ir);
291     debug_gmx();
292
293     /* Check for polarizable models and flexible constraints */
294     shellfc = init_shell_flexcon(fplog,
295                                  top_global,n_flexible_constraints(constr),
296                                  (ir->bContinuation || 
297                                   (DOMAINDECOMP(cr) && !MASTER(cr))) ?
298                                  NULL : state_global->x);
299
300     if (DEFORM(*ir))
301     {
302 #ifdef GMX_THREADS
303         tMPI_Thread_mutex_lock(&deform_init_box_mutex);
304 #endif
305         set_deform_reference_box(upd,
306                                  deform_init_init_step_tpx,
307                                  deform_init_box_tpx);
308 #ifdef GMX_THREADS
309         tMPI_Thread_mutex_unlock(&deform_init_box_mutex);
310 #endif
311     }
312
313     {
314         double io = compute_io(ir,top_global->natoms,groups,mdebin->ebin->nener,1);
315         if ((io > 2000) && MASTER(cr))
316             fprintf(stderr,
317                     "\nWARNING: This run will generate roughly %.0f Mb of data\n\n",
318                     io);
319     }
320
321     if (DOMAINDECOMP(cr)) {
322         top = dd_init_local_top(top_global);
323
324         snew(state,1);
325         dd_init_local_state(cr->dd,state_global,state);
326
327         if (DDMASTER(cr->dd) && ir->nstfout) {
328             snew(f_global,state_global->natoms);
329         }
330     } else {
331         if (PAR(cr)) {
332             /* Initialize the particle decomposition and split the topology */
333             top = split_system(fplog,top_global,ir,cr);
334
335             pd_cg_range(cr,&fr->cg0,&fr->hcg);
336             pd_at_range(cr,&a0,&a1);
337         } else {
338             top = gmx_mtop_generate_local_top(top_global,ir);
339
340             a0 = 0;
341             a1 = top_global->natoms;
342         }
343
344         state = partdec_init_local_state(cr,state_global);
345         f_global = f;
346
347         atoms2md(top_global,ir,0,NULL,a0,a1-a0,mdatoms);
348
349         if (vsite) {
350             set_vsite_top(vsite,top,mdatoms,cr);
351         }
352
353         if (ir->ePBC != epbcNONE && !ir->bPeriodicMols) {
354             graph = mk_graph(fplog,&(top->idef),0,top_global->natoms,FALSE,FALSE);
355         }
356
357         if (shellfc) {
358             make_local_shells(cr,mdatoms,shellfc);
359         }
360
361         if (ir->pull && PAR(cr)) {
362             dd_make_local_pull_groups(NULL,ir->pull,mdatoms);
363         }
364     }
365
366     if (DOMAINDECOMP(cr))
367     {
368         /* Distribute the charge groups over the nodes from the master node */
369         dd_partition_system(fplog,ir->init_step,cr,TRUE,1,
370                             state_global,top_global,ir,
371                             state,&f,mdatoms,top,fr,
372                             vsite,shellfc,constr,
373                             nrnb,wcycle,FALSE);
374     }
375
376     update_mdatoms(mdatoms,state->lambda);
377
378     if (MASTER(cr))
379     {
380         if (opt2bSet("-cpi",nfile,fnm))
381         {
382             /* Update mdebin with energy history if appending to output files */
383             if ( Flags & MD_APPENDFILES )
384             {
385                 restore_energyhistory_from_state(mdebin,&state_global->enerhist);
386             }
387             else
388             {
389                 /* We might have read an energy history from checkpoint,
390                  * free the allocated memory and reset the counts.
391                  */
392                 done_energyhistory(&state_global->enerhist);
393                 init_energyhistory(&state_global->enerhist);
394             }
395         }
396         /* Set the initial energy history in state by updating once */
397         update_energyhistory(&state_global->enerhist,mdebin);
398     }   
399
400     if ((state->flags & (1<<estLD_RNG)) && (Flags & MD_READ_RNG)) {
401         /* Set the random state if we read a checkpoint file */
402         set_stochd_state(upd,state);
403     }
404
405     /* Initialize constraints */
406     if (constr) {
407         if (!DOMAINDECOMP(cr))
408             set_constraints(constr,top,ir,mdatoms,cr);
409     }
410
411     /* Check whether we have to GCT stuff */
412     bTCR = ftp2bSet(efGCT,nfile,fnm);
413     if (bTCR) {
414         if (MASTER(cr)) {
415             fprintf(stderr,"Will do General Coupling Theory!\n");
416         }
417         gnx = top_global->mols.nr;
418         snew(grpindex,gnx);
419         for(i=0; (i<gnx); i++) {
420             grpindex[i] = i;
421         }
422     }
423
424     if (repl_ex_nst > 0)
425     {
426         /* We need to be sure replica exchange can only occur
427          * when the energies are current */
428         check_nst_param(fplog,cr,"nstcalcenergy",ir->nstcalcenergy,
429                         "repl_ex_nst",&repl_ex_nst);
430         /* This check needs to happen before inter-simulation
431          * signals are initialized, too */
432     }
433     if (repl_ex_nst > 0 && MASTER(cr))
434         repl_ex = init_replica_exchange(fplog,cr->ms,state_global,ir,
435                                         repl_ex_nst,repl_ex_seed);
436
437     if (!ir->bContinuation && !bRerunMD)
438     {
439         if (mdatoms->cFREEZE && (state->flags & (1<<estV)))
440         {
441             /* Set the velocities of frozen particles to zero */
442             for(i=mdatoms->start; i<mdatoms->start+mdatoms->homenr; i++)
443             {
444                 for(m=0; m<DIM; m++)
445                 {
446                     if (ir->opts.nFreeze[mdatoms->cFREEZE[i]][m])
447                     {
448                         state->v[i][m] = 0;
449                     }
450                 }
451             }
452         }
453
454         if (constr)
455         {
456             /* Constrain the initial coordinates and velocities */
457             do_constrain_first(fplog,constr,ir,mdatoms,state,f,
458                                graph,cr,nrnb,fr,top,shake_vir);
459         }
460         if (vsite)
461         {
462             /* Construct the virtual sites for the initial configuration */
463             construct_vsites(fplog,vsite,state->x,nrnb,ir->delta_t,NULL,
464                              top->idef.iparams,top->idef.il,
465                              fr->ePBC,fr->bMolPBC,graph,cr,state->box);
466         }
467     }
468
469     debug_gmx();
470   
471     /* I'm assuming we need global communication the first time! MRS */
472     cglo_flags = (CGLO_TEMPERATURE | CGLO_GSTAT
473                   | (bVV ? CGLO_PRESSURE:0)
474                   | (bVV ? CGLO_CONSTRAINT:0)
475                   | (bRerunMD ? CGLO_RERUNMD:0)
476                   | ((Flags & MD_READ_EKIN) ? CGLO_READEKIN:0));
477     
478     bSumEkinhOld = FALSE;
479     compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
480                     wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
481                     constr,NULL,FALSE,state->box,
482                     top_global,&pcurr,top_global->natoms,&bSumEkinhOld,cglo_flags);
483     if (ir->eI == eiVVAK) {
484         /* a second call to get the half step temperature initialized as well */ 
485         /* we do the same call as above, but turn the pressure off -- internally to 
486            compute_globals, this is recognized as a velocity verlet half-step 
487            kinetic energy calculation.  This minimized excess variables, but 
488            perhaps loses some logic?*/
489         
490         compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
491                         wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
492                         constr,NULL,FALSE,state->box,
493                         top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
494                         cglo_flags &~ CGLO_PRESSURE);
495     }
496     
497     /* Calculate the initial half step temperature, and save the ekinh_old */
498     if (!(Flags & MD_STARTFROMCPT)) 
499     {
500         for(i=0; (i<ir->opts.ngtc); i++) 
501         {
502             copy_mat(ekind->tcstat[i].ekinh,ekind->tcstat[i].ekinh_old);
503         } 
504     }
505     if (ir->eI != eiVV) 
506     {
507         enerd->term[F_TEMP] *= 2; /* result of averages being done over previous and current step,
508                                      and there is no previous step */
509     }
510     temp0 = enerd->term[F_TEMP];
511     
512     /* if using an iterative algorithm, we need to create a working directory for the state. */
513     if (bIterations) 
514     {
515             bufstate = init_bufstate(state);
516     }
517     if (bFFscan) 
518     {
519         snew(xcopy,state->natoms);
520         snew(vcopy,state->natoms);
521         copy_rvecn(state->x,xcopy,0,state->natoms);
522         copy_rvecn(state->v,vcopy,0,state->natoms);
523         copy_mat(state->box,boxcopy);
524     } 
525     
526     /* need to make an initiation call to get the Trotter variables set, as well as other constants for non-trotter
527        temperature control */
528     trotter_seq = init_npt_vars(ir,state,&MassQ,bTrotter);
529     
530     if (MASTER(cr))
531     {
532         if (constr && !ir->bContinuation && ir->eConstrAlg == econtLINCS)
533         {
534             fprintf(fplog,
535                     "RMS relative constraint deviation after constraining: %.2e\n",
536                     constr_rmsd(constr,FALSE));
537         }
538         fprintf(fplog,"Initial temperature: %g K\n",enerd->term[F_TEMP]);
539         if (bRerunMD)
540         {
541             fprintf(stderr,"starting md rerun '%s', reading coordinates from"
542                     " input trajectory '%s'\n\n",
543                     *(top_global->name),opt2fn("-rerun",nfile,fnm));
544             if (bVerbose)
545             {
546                 fprintf(stderr,"Calculated time to finish depends on nsteps from "
547                         "run input file,\nwhich may not correspond to the time "
548                         "needed to process input trajectory.\n\n");
549             }
550         }
551         else
552         {
553             char tbuf[20];
554             fprintf(stderr,"starting mdrun '%s'\n",
555                     *(top_global->name));
556             if (ir->nsteps >= 0)
557             {
558                 sprintf(tbuf,"%8.1f",(ir->init_step+ir->nsteps)*ir->delta_t);
559             }
560             else
561             {
562                 sprintf(tbuf,"%s","infinite");
563             }
564             if (ir->init_step > 0)
565             {
566                 fprintf(stderr,"%s steps, %s ps (continuing from step %s, %8.1f ps).\n",
567                         gmx_step_str(ir->init_step+ir->nsteps,sbuf),tbuf,
568                         gmx_step_str(ir->init_step,sbuf2),
569                         ir->init_step*ir->delta_t);
570             }
571             else
572             {
573                 fprintf(stderr,"%s steps, %s ps.\n",
574                         gmx_step_str(ir->nsteps,sbuf),tbuf);
575             }
576         }
577         fprintf(fplog,"\n");
578     }
579
580     /* Set and write start time */
581     runtime_start(runtime);
582     print_date_and_time(fplog,cr->nodeid,"Started mdrun",runtime);
583     wallcycle_start(wcycle,ewcRUN);
584     if (fplog)
585         fprintf(fplog,"\n");
586
587     /* safest point to do file checkpointing is here.  More general point would be immediately before integrator call */
588 #ifdef GMX_FAHCORE
589     chkpt_ret=fcCheckPointParallel( cr->nodeid,
590                                     NULL,0);
591     if ( chkpt_ret == 0 ) 
592         gmx_fatal( 3,__FILE__,__LINE__, "Checkpoint error on step %d\n", 0 );
593 #endif
594
595     debug_gmx();
596     /***********************************************************
597      *
598      *             Loop over MD steps 
599      *
600      ************************************************************/
601
602     /* if rerunMD then read coordinates and velocities from input trajectory */
603     if (bRerunMD)
604     {
605         if (getenv("GMX_FORCE_UPDATE"))
606         {
607             bForceUpdate = TRUE;
608         }
609
610         rerun_fr.natoms = 0;
611         if (MASTER(cr))
612         {
613             bNotLastFrame = read_first_frame(oenv,&status,
614                                              opt2fn("-rerun",nfile,fnm),
615                                              &rerun_fr,TRX_NEED_X | TRX_READ_V);
616             if (rerun_fr.natoms != top_global->natoms)
617             {
618                 gmx_fatal(FARGS,
619                           "Number of atoms in trajectory (%d) does not match the "
620                           "run input file (%d)\n",
621                           rerun_fr.natoms,top_global->natoms);
622             }
623             if (ir->ePBC != epbcNONE)
624             {
625                 if (!rerun_fr.bBox)
626                 {
627                     gmx_fatal(FARGS,"Rerun trajectory frame step %d time %f does not contain a box, while pbc is used",rerun_fr.step,rerun_fr.time);
628                 }
629                 if (max_cutoff2(ir->ePBC,rerun_fr.box) < sqr(fr->rlistlong))
630                 {
631                     gmx_fatal(FARGS,"Rerun trajectory frame step %d time %f has too small box dimensions",rerun_fr.step,rerun_fr.time);
632                 }
633             }
634         }
635
636         if (PAR(cr))
637         {
638             rerun_parallel_comm(cr,&rerun_fr,&bNotLastFrame);
639         }
640
641         if (ir->ePBC != epbcNONE)
642         {
643             /* Set the shift vectors.
644              * Necessary here when have a static box different from the tpr box.
645              */
646             calc_shifts(rerun_fr.box,fr->shift_vec);
647         }
648     }
649
650     /* loop over MD steps or if rerunMD to end of input trajectory */
651     bFirstStep = TRUE;
652     /* Skip the first Nose-Hoover integration when we get the state from tpx */
653     bStateFromTPX = !opt2bSet("-cpi",nfile,fnm);
654     bInitStep = bFirstStep && (bStateFromTPX || bVV);
655     bStartingFromCpt = (Flags & MD_STARTFROMCPT) && bInitStep;
656     bLastStep    = FALSE;
657     bSumEkinhOld = FALSE;
658     bExchanged   = FALSE;
659
660     init_global_signals(&gs,cr,ir,repl_ex_nst);
661
662     step = ir->init_step;
663     step_rel = 0;
664
665     if (ir->nstlist == -1)
666     {
667         init_nlistheuristics(&nlh,bGStatEveryStep,step);
668     }
669
670     if (MULTISIM(cr) && (repl_ex_nst <=0 ))
671     {
672         /* check how many steps are left in other sims */
673         multisim_nsteps=get_multisim_nsteps(cr, ir->nsteps);
674     }
675
676
677     /* and stop now if we should */
678     bLastStep = (bRerunMD || (ir->nsteps >= 0 && step_rel > ir->nsteps) ||
679                  ((multisim_nsteps >= 0) && (step_rel >= multisim_nsteps )));
680     while (!bLastStep || (bRerunMD && bNotLastFrame)) {
681
682         wallcycle_start(wcycle,ewcSTEP);
683
684         GMX_MPE_LOG(ev_timestep1);
685
686         if (bRerunMD) {
687             if (rerun_fr.bStep) {
688                 step = rerun_fr.step;
689                 step_rel = step - ir->init_step;
690             }
691             if (rerun_fr.bTime) {
692                 t = rerun_fr.time;
693             }
694             else
695             {
696                 t = step;
697             }
698         } 
699         else 
700         {
701             bLastStep = (step_rel == ir->nsteps);
702             t = t0 + step*ir->delta_t;
703         }
704
705         if (ir->efep != efepNO)
706         {
707             if (bRerunMD && rerun_fr.bLambda && (ir->delta_lambda!=0))
708             {
709                 state_global->lambda = rerun_fr.lambda;
710             }
711             else
712             {
713                 state_global->lambda = lam0 + step*ir->delta_lambda;
714             }
715             state->lambda = state_global->lambda;
716             bDoDHDL = do_per_step(step,ir->nstdhdl);
717         }
718
719         if (bSimAnn) 
720         {
721             update_annealing_target_temp(&(ir->opts),t);
722         }
723
724         if (bRerunMD)
725         {
726             if (!(DOMAINDECOMP(cr) && !MASTER(cr)))
727             {
728                 for(i=0; i<state_global->natoms; i++)
729                 {
730                     copy_rvec(rerun_fr.x[i],state_global->x[i]);
731                 }
732                 if (rerun_fr.bV)
733                 {
734                     for(i=0; i<state_global->natoms; i++)
735                     {
736                         copy_rvec(rerun_fr.v[i],state_global->v[i]);
737                     }
738                 }
739                 else
740                 {
741                     for(i=0; i<state_global->natoms; i++)
742                     {
743                         clear_rvec(state_global->v[i]);
744                     }
745                     if (bRerunWarnNoV)
746                     {
747                         fprintf(stderr,"\nWARNING: Some frames do not contain velocities.\n"
748                                 "         Ekin, temperature and pressure are incorrect,\n"
749                                 "         the virial will be incorrect when constraints are present.\n"
750                                 "\n");
751                         bRerunWarnNoV = FALSE;
752                     }
753                 }
754             }
755             copy_mat(rerun_fr.box,state_global->box);
756             copy_mat(state_global->box,state->box);
757
758             if (vsite && (Flags & MD_RERUN_VSITE))
759             {
760                 if (DOMAINDECOMP(cr))
761                 {
762                     gmx_fatal(FARGS,"Vsite recalculation with -rerun is not implemented for domain decomposition, use particle decomposition");
763                 }
764                 if (graph)
765                 {
766                     /* Following is necessary because the graph may get out of sync
767                      * with the coordinates if we only have every N'th coordinate set
768                      */
769                     mk_mshift(fplog,graph,fr->ePBC,state->box,state->x);
770                     shift_self(graph,state->box,state->x);
771                 }
772                 construct_vsites(fplog,vsite,state->x,nrnb,ir->delta_t,state->v,
773                                  top->idef.iparams,top->idef.il,
774                                  fr->ePBC,fr->bMolPBC,graph,cr,state->box);
775                 if (graph)
776                 {
777                     unshift_self(graph,state->box,state->x);
778                 }
779             }
780         }
781
782         /* Stop Center of Mass motion */
783         bStopCM = (ir->comm_mode != ecmNO && do_per_step(step,ir->nstcomm));
784
785         /* Copy back starting coordinates in case we're doing a forcefield scan */
786         if (bFFscan)
787         {
788             for(ii=0; (ii<state->natoms); ii++)
789             {
790                 copy_rvec(xcopy[ii],state->x[ii]);
791                 copy_rvec(vcopy[ii],state->v[ii]);
792             }
793             copy_mat(boxcopy,state->box);
794         }
795
796         if (bRerunMD)
797         {
798             /* for rerun MD always do Neighbour Searching */
799             bNS = (bFirstStep || ir->nstlist != 0);
800             bNStList = bNS;
801         }
802         else
803         {
804             /* Determine whether or not to do Neighbour Searching and LR */
805             bNStList = (ir->nstlist > 0  && step % ir->nstlist == 0);
806             
807             bNS = (bFirstStep || bExchanged || bNStList ||
808                    (ir->nstlist == -1 && nlh.nabnsb > 0));
809
810             if (bNS && ir->nstlist == -1)
811             {
812                 set_nlistheuristics(&nlh,bFirstStep || bExchanged,step);
813             }
814         } 
815
816         /* check whether we should stop because another simulation has 
817            stopped. */
818         if (MULTISIM(cr))
819         {
820             if ( (multisim_nsteps >= 0) &&  (step_rel >= multisim_nsteps)  &&  
821                  (multisim_nsteps != ir->nsteps) )  
822             {
823                 if (bNS)
824                 {
825                     if (MASTER(cr))
826                     {
827                         fprintf(stderr, 
828                                 "Stopping simulation %d because another one has finished\n",
829                                 cr->ms->sim);
830                     }
831                     bLastStep=TRUE;
832                     gs.sig[eglsCHKPT] = 1;
833                 }
834             }
835         }
836
837         /* < 0 means stop at next step, > 0 means stop at next NS step */
838         if ( (gs.set[eglsSTOPCOND] < 0 ) ||
839              ( (gs.set[eglsSTOPCOND] > 0 ) && ( bNS || ir->nstlist==0)) )
840         {
841             bLastStep = TRUE;
842         }
843
844         /* Determine whether or not to update the Born radii if doing GB */
845         bBornRadii=bFirstStep;
846         if (ir->implicit_solvent && (step % ir->nstgbradii==0))
847         {
848             bBornRadii=TRUE;
849         }
850         
851         do_log = do_per_step(step,ir->nstlog) || bFirstStep || bLastStep;
852         do_verbose = bVerbose &&
853                   (step % stepout == 0 || bFirstStep || bLastStep);
854
855         if (bNS && !(bFirstStep && ir->bContinuation && !bRerunMD))
856         {
857             if (bRerunMD)
858             {
859                 bMasterState = TRUE;
860             }
861             else
862             {
863                 bMasterState = FALSE;
864                 /* Correct the new box if it is too skewed */
865                 if (DYNAMIC_BOX(*ir))
866                 {
867                     if (correct_box(fplog,step,state->box,graph))
868                     {
869                         bMasterState = TRUE;
870                     }
871                 }
872                 if (DOMAINDECOMP(cr) && bMasterState)
873                 {
874                     dd_collect_state(cr->dd,state,state_global);
875                 }
876             }
877
878             if (DOMAINDECOMP(cr))
879             {
880                 /* Repartition the domain decomposition */
881                 wallcycle_start(wcycle,ewcDOMDEC);
882                 dd_partition_system(fplog,step,cr,
883                                     bMasterState,nstglobalcomm,
884                                     state_global,top_global,ir,
885                                     state,&f,mdatoms,top,fr,
886                                     vsite,shellfc,constr,
887                                     nrnb,wcycle,do_verbose);
888                 wallcycle_stop(wcycle,ewcDOMDEC);
889                 /* If using an iterative integrator, reallocate space to match the decomposition */
890             }
891         }
892
893         if (MASTER(cr) && do_log && !bFFscan)
894         {
895             print_ebin_header(fplog,step,t,state->lambda);
896         }
897
898         if (ir->efep != efepNO)
899         {
900             update_mdatoms(mdatoms,state->lambda); 
901         }
902
903         if (bRerunMD && rerun_fr.bV)
904         {
905             
906             /* We need the kinetic energy at minus the half step for determining
907              * the full step kinetic energy and possibly for T-coupling.*/
908             /* This may not be quite working correctly yet . . . . */
909             compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
910                             wcycle,enerd,NULL,NULL,NULL,NULL,mu_tot,
911                             constr,NULL,FALSE,state->box,
912                             top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
913                             CGLO_RERUNMD | CGLO_GSTAT | CGLO_TEMPERATURE);
914         }
915         clear_mat(force_vir);
916         
917         /* Ionize the atoms if necessary */
918         if (bIonize)
919         {
920             ionize(fplog,oenv,mdatoms,top_global,t,ir,state->x,state->v,
921                    mdatoms->start,mdatoms->start+mdatoms->homenr,state->box,cr);
922         }
923         
924         /* Update force field in ffscan program */
925         if (bFFscan)
926         {
927             if (update_forcefield(fplog,
928                                   nfile,fnm,fr,
929                                   mdatoms->nr,state->x,state->box)) {
930                 if (gmx_parallel_env_initialized())
931                 {
932                     gmx_finalize();
933                 }
934                 exit(0);
935             }
936         }
937
938         GMX_MPE_LOG(ev_timestep2);
939
940         /* We write a checkpoint at this MD step when:
941          * either at an NS step when we signalled through gs,
942          * or at the last step (but not when we do not want confout),
943          * but never at the first step or with rerun.
944          */
945         bCPT = (((gs.set[eglsCHKPT] && (bNS || ir->nstlist == 0)) ||
946                  (bLastStep && (Flags & MD_CONFOUT))) &&
947                 step > ir->init_step && !bRerunMD);
948         if (bCPT)
949         {
950             gs.set[eglsCHKPT] = 0;
951         }
952
953         /* Determine the energy and pressure:
954          * at nstcalcenergy steps and at energy output steps (set below).
955          */
956         bNstEner = do_per_step(step,ir->nstcalcenergy);
957         bCalcEnerPres =
958             (bNstEner ||
959              (ir->epc != epcNO && do_per_step(step,ir->nstpcouple)));
960
961         /* Do we need global communication ? */
962         bGStat = (bCalcEnerPres || bStopCM ||
963                   do_per_step(step,nstglobalcomm) ||
964                   (ir->nstlist == -1 && !bRerunMD && step >= nlh.step_nscheck));
965
966         do_ene = (do_per_step(step,ir->nstenergy) || bLastStep);
967
968         if (do_ene || do_log)
969         {
970             bCalcEnerPres = TRUE;
971             bGStat        = TRUE;
972         }
973         
974         /* these CGLO_ options remain the same throughout the iteration */
975         cglo_flags = ((bRerunMD ? CGLO_RERUNMD : 0) |
976                       (bStopCM ? CGLO_STOPCM : 0) |
977                       (bGStat ? CGLO_GSTAT : 0)
978             );
979         
980         force_flags = (GMX_FORCE_STATECHANGED |
981                        ((DYNAMIC_BOX(*ir) || bRerunMD) ? GMX_FORCE_DYNAMICBOX : 0) |
982                        GMX_FORCE_ALLFORCES |
983                        (bNStList ? GMX_FORCE_DOLR : 0) |
984                        GMX_FORCE_SEPLRF |
985                        (bCalcEnerPres ? GMX_FORCE_VIRIAL : 0) |
986                        (bDoDHDL ? GMX_FORCE_DHDL : 0)
987             );
988         
989         if (shellfc)
990         {
991             /* Now is the time to relax the shells */
992             count=relax_shell_flexcon(fplog,cr,bVerbose,bFFscan ? step+1 : step,
993                                       ir,bNS,force_flags,
994                                       bStopCM,top,top_global,
995                                       constr,enerd,fcd,
996                                       state,f,force_vir,mdatoms,
997                                       nrnb,wcycle,graph,groups,
998                                       shellfc,fr,bBornRadii,t,mu_tot,
999                                       state->natoms,&bConverged,vsite,
1000                                       outf->fp_field);
1001             tcount+=count;
1002
1003             if (bConverged)
1004             {
1005                 nconverged++;
1006             }
1007         }
1008         else
1009         {
1010             /* The coordinates (x) are shifted (to get whole molecules)
1011              * in do_force.
1012              * This is parallellized as well, and does communication too. 
1013              * Check comments in sim_util.c
1014              */
1015         
1016             do_force(fplog,cr,ir,step,nrnb,wcycle,top,top_global,groups,
1017                      state->box,state->x,&state->hist,
1018                      f,force_vir,mdatoms,enerd,fcd,
1019                      state->lambda,graph,
1020                      fr,vsite,mu_tot,t,outf->fp_field,ed,bBornRadii,
1021                      (bNS ? GMX_FORCE_NS : 0) | force_flags);
1022         }
1023     
1024         GMX_BARRIER(cr->mpi_comm_mygroup);
1025         
1026         if (bTCR)
1027         {
1028             mu_aver = calc_mu_aver(cr,state->x,mdatoms->chargeA,
1029                                    mu_tot,&top_global->mols,mdatoms,gnx,grpindex);
1030         }
1031         
1032         if (bTCR && bFirstStep)
1033         {
1034             tcr=init_coupling(fplog,nfile,fnm,cr,fr,mdatoms,&(top->idef));
1035             fprintf(fplog,"Done init_coupling\n"); 
1036             fflush(fplog);
1037         }
1038         
1039         if (bVV && !bStartingFromCpt && !bRerunMD)
1040         /*  ############### START FIRST UPDATE HALF-STEP FOR VV METHODS############### */
1041         {
1042             if (ir->eI==eiVV && bInitStep) 
1043             {
1044                 /* if using velocity verlet with full time step Ekin,
1045                  * take the first half step only to compute the 
1046                  * virial for the first step. From there,
1047                  * revert back to the initial coordinates
1048                  * so that the input is actually the initial step.
1049                  */
1050                 copy_rvecn(state->v,cbuf,0,state->natoms); /* should make this better for parallelizing? */
1051             } else {
1052                 /* this is for NHC in the Ekin(t+dt/2) version of vv */
1053                 trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ1);            
1054             }
1055
1056             update_coords(fplog,step,ir,mdatoms,state,
1057                           f,fr->bTwinRange && bNStList,fr->f_twin,fcd,
1058                           ekind,M,wcycle,upd,bInitStep,etrtVELOCITY1,
1059                           cr,nrnb,constr,&top->idef);
1060             
1061             if (bIterations)
1062             {
1063                 gmx_iterate_init(&iterate,bIterations && !bInitStep);
1064             }
1065             /* for iterations, we save these vectors, as we will be self-consistently iterating
1066                the calculations */
1067
1068             /*#### UPDATE EXTENDED VARIABLES IN TROTTER FORMULATION */
1069             
1070             /* save the state */
1071             if (bIterations && iterate.bIterate) { 
1072                 copy_coupling_state(state,bufstate,ekind,ekind_save,&(ir->opts));
1073             }
1074             
1075             bFirstIterate = TRUE;
1076             while (bFirstIterate || (bIterations && iterate.bIterate))
1077             {
1078                 if (bIterations && iterate.bIterate) 
1079                 {
1080                     copy_coupling_state(bufstate,state,ekind_save,ekind,&(ir->opts));
1081                     if (bFirstIterate && bTrotter) 
1082                     {
1083                         /* The first time through, we need a decent first estimate
1084                            of veta(t+dt) to compute the constraints.  Do
1085                            this by computing the box volume part of the
1086                            trotter integration at this time. Nothing else
1087                            should be changed by this routine here.  If
1088                            !(first time), we start with the previous value
1089                            of veta.  */
1090                         
1091                         veta_save = state->veta;
1092                         trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ0);
1093                         vetanew = state->veta;
1094                         state->veta = veta_save;
1095                     } 
1096                 } 
1097                 
1098                 bOK = TRUE;
1099                 if ( !bRerunMD || rerun_fr.bV || bForceUpdate) {  /* Why is rerun_fr.bV here?  Unclear. */
1100                     dvdl = 0;
1101                     
1102                     update_constraints(fplog,step,&dvdl,ir,ekind,mdatoms,state,graph,f,
1103                                        &top->idef,shake_vir,NULL,
1104                                        cr,nrnb,wcycle,upd,constr,
1105                                        bInitStep,TRUE,bCalcEnerPres,vetanew);
1106                     
1107                     if (!bOK && !bFFscan)
1108                     {
1109                         gmx_fatal(FARGS,"Constraint error: Shake, Lincs or Settle could not solve the constrains");
1110                     }
1111                     
1112                 } 
1113                 else if (graph)
1114                 { /* Need to unshift here if a do_force has been
1115                      called in the previous step */
1116                     unshift_self(graph,state->box,state->x);
1117                 }
1118                 
1119                 
1120                 /* if VV, compute the pressure and constraints */
1121                 /* For VV2, we strictly only need this if using pressure
1122                  * control, but we really would like to have accurate pressures
1123                  * printed out.
1124                  * Think about ways around this in the future?
1125                  * For now, keep this choice in comments.
1126                  */
1127                 /*bPres = (ir->eI==eiVV || IR_NPT_TROTTER(ir)); */
1128                     /*bTemp = ((ir->eI==eiVV &&(!bInitStep)) || (ir->eI==eiVVAK && IR_NPT_TROTTER(ir)));*/
1129                 bPres = TRUE;
1130                 bTemp = ((ir->eI==eiVV &&(!bInitStep)) || (ir->eI==eiVVAK));
1131                 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
1132                                 wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
1133                                 constr,NULL,FALSE,state->box,
1134                                 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
1135                                 cglo_flags 
1136                                 | CGLO_ENERGY 
1137                                 | (bTemp ? CGLO_TEMPERATURE:0) 
1138                                 | (bPres ? CGLO_PRESSURE : 0) 
1139                                 | (bPres ? CGLO_CONSTRAINT : 0)
1140                                 | ((bIterations && iterate.bIterate) ? CGLO_ITERATE : 0)  
1141                                 | (bFirstIterate ? CGLO_FIRSTITERATE : 0)
1142                                 | CGLO_SCALEEKIN 
1143                     );
1144                 /* explanation of above: 
1145                    a) We compute Ekin at the full time step
1146                    if 1) we are using the AveVel Ekin, and it's not the
1147                    initial step, or 2) if we are using AveEkin, but need the full
1148                    time step kinetic energy for the pressure (always true now, since we want accurate statistics).
1149                    b) If we are using EkinAveEkin for the kinetic energy for the temperture control, we still feed in 
1150                    EkinAveVel because it's needed for the pressure */
1151                 
1152                 /* temperature scaling and pressure scaling to produce the extended variables at t+dt */
1153                 if (!bInitStep) 
1154                 {
1155                     if (bTrotter)
1156                     {
1157                         trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ2);
1158                     } 
1159                     else 
1160                     {
1161                         update_tcouple(fplog,step,ir,state,ekind,wcycle,upd,&MassQ,mdatoms);
1162                     }
1163                 }
1164                 
1165                 if (bIterations &&
1166                     done_iterating(cr,fplog,step,&iterate,bFirstIterate,
1167                                    state->veta,&vetanew)) 
1168                 {
1169                     break;
1170                 }
1171                 bFirstIterate = FALSE;
1172             }
1173
1174             if (bTrotter && !bInitStep) {
1175                 copy_mat(shake_vir,state->svir_prev);
1176                 copy_mat(force_vir,state->fvir_prev);
1177                 if (IR_NVT_TROTTER(ir) && ir->eI==eiVV) {
1178                     /* update temperature and kinetic energy now that step is over - this is the v(t+dt) point */
1179                     enerd->term[F_TEMP] = sum_ekin(&(ir->opts),ekind,NULL,(ir->eI==eiVV),FALSE,FALSE);
1180                     enerd->term[F_EKIN] = trace(ekind->ekin);
1181                 }
1182             }
1183             /* if it's the initial step, we performed this first step just to get the constraint virial */
1184             if (bInitStep && ir->eI==eiVV) {
1185                 copy_rvecn(cbuf,state->v,0,state->natoms);
1186             }
1187             
1188             if (fr->bSepDVDL && fplog && do_log) 
1189             {
1190                 fprintf(fplog,sepdvdlformat,"Constraint",0.0,dvdl);
1191             }
1192             enerd->term[F_DHDL_CON] += dvdl;
1193             
1194             GMX_MPE_LOG(ev_timestep1);
1195         }
1196     
1197         /* MRS -- now done iterating -- compute the conserved quantity */
1198         if (bVV) {
1199             saved_conserved_quantity = compute_conserved_from_auxiliary(ir,state,&MassQ);
1200             if (ir->eI==eiVV) 
1201             {
1202                 last_ekin = enerd->term[F_EKIN]; /* does this get preserved through checkpointing? */
1203             }
1204             if ((ir->eDispCorr != edispcEnerPres) && (ir->eDispCorr != edispcAllEnerPres)) 
1205             {
1206                 saved_conserved_quantity -= enerd->term[F_DISPCORR];
1207             }
1208         }
1209         
1210         /* ########  END FIRST UPDATE STEP  ############## */
1211         /* ########  If doing VV, we now have v(dt) ###### */
1212         
1213         /* ################## START TRAJECTORY OUTPUT ################# */
1214         
1215         /* Now we have the energies and forces corresponding to the 
1216          * coordinates at time t. We must output all of this before
1217          * the update.
1218          * for RerunMD t is read from input trajectory
1219          */
1220         GMX_MPE_LOG(ev_output_start);
1221
1222         mdof_flags = 0;
1223         if (do_per_step(step,ir->nstxout)) { mdof_flags |= MDOF_X; }
1224         if (do_per_step(step,ir->nstvout)) { mdof_flags |= MDOF_V; }
1225         if (do_per_step(step,ir->nstfout)) { mdof_flags |= MDOF_F; }
1226         if (do_per_step(step,ir->nstxtcout)) { mdof_flags |= MDOF_XTC; }
1227         if (bCPT) { mdof_flags |= MDOF_CPT; };
1228
1229 #if defined(GMX_FAHCORE) || defined(GMX_WRITELASTSTEP)
1230         if (bLastStep)
1231         {
1232             /* Enforce writing positions and velocities at end of run */
1233             mdof_flags |= (MDOF_X | MDOF_V);
1234         }
1235 #endif
1236 #ifdef GMX_FAHCORE
1237         if (MASTER(cr))
1238             fcReportProgress( ir->nsteps, step );
1239
1240         /* sync bCPT and fc record-keeping */
1241         if (bCPT && MASTER(cr))
1242             fcRequestCheckPoint();
1243 #endif
1244         
1245         if (mdof_flags != 0)
1246         {
1247             wallcycle_start(wcycle,ewcTRAJ);
1248             if (bCPT)
1249             {
1250                 if (state->flags & (1<<estLD_RNG))
1251                 {
1252                     get_stochd_state(upd,state);
1253                 }
1254                 if (MASTER(cr))
1255                 {
1256                     if (bSumEkinhOld)
1257                     {
1258                         state_global->ekinstate.bUpToDate = FALSE;
1259                     }
1260                     else
1261                     {
1262                         update_ekinstate(&state_global->ekinstate,ekind);
1263                         state_global->ekinstate.bUpToDate = TRUE;
1264                     }
1265                     update_energyhistory(&state_global->enerhist,mdebin);
1266                 }
1267             }
1268             write_traj(fplog,cr,outf,mdof_flags,top_global,
1269                        step,t,state,state_global,f,f_global,&n_xtc,&x_xtc);
1270             if (bCPT)
1271             {
1272                 nchkpt++;
1273                 bCPT = FALSE;
1274             }
1275             debug_gmx();
1276             if (bLastStep && step_rel == ir->nsteps &&
1277                 (Flags & MD_CONFOUT) && MASTER(cr) &&
1278                 !bRerunMD && !bFFscan)
1279             {
1280                 /* x and v have been collected in write_traj,
1281                  * because a checkpoint file will always be written
1282                  * at the last step.
1283                  */
1284                 fprintf(stderr,"\nWriting final coordinates.\n");
1285                 if (ir->ePBC != epbcNONE && !ir->bPeriodicMols &&
1286                     DOMAINDECOMP(cr))
1287                 {
1288                     /* Make molecules whole only for confout writing */
1289                     do_pbc_mtop(fplog,ir->ePBC,state->box,top_global,state_global->x);
1290                 }
1291                 write_sto_conf_mtop(ftp2fn(efSTO,nfile,fnm),
1292                                     *top_global->name,top_global,
1293                                     state_global->x,state_global->v,
1294                                     ir->ePBC,state->box);
1295                 debug_gmx();
1296             }
1297             wallcycle_stop(wcycle,ewcTRAJ);
1298         }
1299         GMX_MPE_LOG(ev_output_finish);
1300         
1301         /* kludge -- virial is lost with restart for NPT control. Must restart */
1302         if (bStartingFromCpt && bVV) 
1303         {
1304             copy_mat(state->svir_prev,shake_vir);
1305             copy_mat(state->fvir_prev,force_vir);
1306         }
1307         /*  ################## END TRAJECTORY OUTPUT ################ */
1308         
1309         /* Determine the wallclock run time up till now */
1310         run_time = gmx_gettime() - (double)runtime->real;
1311
1312         /* Check whether everything is still allright */    
1313         if (((int)gmx_get_stop_condition() > handled_stop_condition)
1314 #ifdef GMX_THREADS
1315             && MASTER(cr)
1316 #endif
1317             )
1318         {
1319             /* this is just make gs.sig compatible with the hack 
1320                of sending signals around by MPI_Reduce with together with
1321                other floats */
1322             if ( gmx_get_stop_condition() == gmx_stop_cond_next_ns )
1323                 gs.sig[eglsSTOPCOND]=1;
1324             if ( gmx_get_stop_condition() == gmx_stop_cond_next )
1325                 gs.sig[eglsSTOPCOND]=-1;
1326             /* < 0 means stop at next step, > 0 means stop at next NS step */
1327             if (fplog)
1328             {
1329                 fprintf(fplog,
1330                         "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
1331                         gmx_get_signal_name(),
1332                         gs.sig[eglsSTOPCOND]==1 ? "NS " : "");
1333                 fflush(fplog);
1334             }
1335             fprintf(stderr,
1336                     "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
1337                     gmx_get_signal_name(),
1338                     gs.sig[eglsSTOPCOND]==1 ? "NS " : "");
1339             fflush(stderr);
1340             handled_stop_condition=(int)gmx_get_stop_condition();
1341         }
1342         else if (MASTER(cr) && (bNS || ir->nstlist <= 0) &&
1343                  (max_hours > 0 && run_time > max_hours*60.0*60.0*0.99) &&
1344                  gs.sig[eglsSTOPCOND] == 0 && gs.set[eglsSTOPCOND] == 0)
1345         {
1346             /* Signal to terminate the run */
1347             gs.sig[eglsSTOPCOND] = 1;
1348             if (fplog)
1349             {
1350                 fprintf(fplog,"\nStep %s: Run time exceeded %.3f hours, will terminate the run\n",gmx_step_str(step,sbuf),max_hours*0.99);
1351             }
1352             fprintf(stderr, "\nStep %s: Run time exceeded %.3f hours, will terminate the run\n",gmx_step_str(step,sbuf),max_hours*0.99);
1353         }
1354
1355         if (bResetCountersHalfMaxH && MASTER(cr) &&
1356             run_time > max_hours*60.0*60.0*0.495)
1357         {
1358             gs.sig[eglsRESETCOUNTERS] = 1;
1359         }
1360
1361         if (ir->nstlist == -1 && !bRerunMD)
1362         {
1363             /* When bGStatEveryStep=FALSE, global_stat is only called
1364              * when we check the atom displacements, not at NS steps.
1365              * This means that also the bonded interaction count check is not
1366              * performed immediately after NS. Therefore a few MD steps could
1367              * be performed with missing interactions.
1368              * But wrong energies are never written to file,
1369              * since energies are only written after global_stat
1370              * has been called.
1371              */
1372             if (step >= nlh.step_nscheck)
1373             {
1374                 nlh.nabnsb = natoms_beyond_ns_buffer(ir,fr,&top->cgs,
1375                                                      nlh.scale_tot,state->x);
1376             }
1377             else
1378             {
1379                 /* This is not necessarily true,
1380                  * but step_nscheck is determined quite conservatively.
1381                  */
1382                 nlh.nabnsb = 0;
1383             }
1384         }
1385
1386         /* In parallel we only have to check for checkpointing in steps
1387          * where we do global communication,
1388          *  otherwise the other nodes don't know.
1389          */
1390         if (MASTER(cr) && ((bGStat || !PAR(cr)) &&
1391                            cpt_period >= 0 &&
1392                            (cpt_period == 0 || 
1393                             run_time >= nchkpt*cpt_period*60.0)) &&
1394             gs.set[eglsCHKPT] == 0)
1395         {
1396             gs.sig[eglsCHKPT] = 1;
1397         }
1398   
1399         if (bIterations)
1400         {
1401             gmx_iterate_init(&iterate,bIterations);
1402         }
1403     
1404         /* for iterations, we save these vectors, as we will be redoing the calculations */
1405         if (bIterations && iterate.bIterate) 
1406         {
1407             copy_coupling_state(state,bufstate,ekind,ekind_save,&(ir->opts));
1408         }
1409         bFirstIterate = TRUE;
1410         while (bFirstIterate || (bIterations && iterate.bIterate))
1411         {
1412             /* We now restore these vectors to redo the calculation with improved extended variables */    
1413             if (bIterations) 
1414             { 
1415                 copy_coupling_state(bufstate,state,ekind_save,ekind,&(ir->opts));
1416             }
1417
1418             /* We make the decision to break or not -after- the calculation of Ekin and Pressure,
1419                so scroll down for that logic */
1420             
1421             /* #########   START SECOND UPDATE STEP ################# */
1422             GMX_MPE_LOG(ev_update_start);
1423             /* Box is changed in update() when we do pressure coupling,
1424              * but we should still use the old box for energy corrections and when
1425              * writing it to the energy file, so it matches the trajectory files for
1426              * the same timestep above. Make a copy in a separate array.
1427              */
1428             copy_mat(state->box,lastbox);
1429
1430             bOK = TRUE;
1431             if (!(bRerunMD && !rerun_fr.bV && !bForceUpdate))
1432             {
1433                 wallcycle_start(wcycle,ewcUPDATE);
1434                 dvdl = 0;
1435                 /* UPDATE PRESSURE VARIABLES IN TROTTER FORMULATION WITH CONSTRAINTS */
1436                 if (bTrotter) 
1437                 {
1438                     if (bIterations && iterate.bIterate) 
1439                     {
1440                         if (bFirstIterate) 
1441                         {
1442                             scalevir = 1;
1443                         }
1444                         else 
1445                         {
1446                             /* we use a new value of scalevir to converge the iterations faster */
1447                             scalevir = tracevir/trace(shake_vir);
1448                         }
1449                         msmul(shake_vir,scalevir,shake_vir); 
1450                         m_add(force_vir,shake_vir,total_vir);
1451                         clear_mat(shake_vir);
1452                     }
1453                     trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ3);
1454                 /* We can only do Berendsen coupling after we have summed
1455                  * the kinetic energy or virial. Since the happens
1456                  * in global_state after update, we should only do it at
1457                  * step % nstlist = 1 with bGStatEveryStep=FALSE.
1458                  */
1459                 }
1460                 else 
1461                 {
1462                     update_tcouple(fplog,step,ir,state,ekind,wcycle,upd,&MassQ,mdatoms);
1463                     update_pcouple(fplog,step,ir,state,pcoupl_mu,M,wcycle,
1464                                    upd,bInitStep);
1465                 }
1466
1467                 if (bVV)
1468                 {
1469                     /* velocity half-step update */
1470                     update_coords(fplog,step,ir,mdatoms,state,f,
1471                                   fr->bTwinRange && bNStList,fr->f_twin,fcd,
1472                                   ekind,M,wcycle,upd,FALSE,etrtVELOCITY2,
1473                                   cr,nrnb,constr,&top->idef);
1474                 }
1475
1476                 /* Above, initialize just copies ekinh into ekin,
1477                  * it doesn't copy position (for VV),
1478                  * and entire integrator for MD.
1479                  */
1480                 
1481                 if (ir->eI==eiVVAK) 
1482                 {
1483                     copy_rvecn(state->x,cbuf,0,state->natoms);
1484                 }
1485                 
1486                 update_coords(fplog,step,ir,mdatoms,state,f,fr->bTwinRange && bNStList,fr->f_twin,fcd,
1487                               ekind,M,wcycle,upd,bInitStep,etrtPOSITION,cr,nrnb,constr,&top->idef);
1488                 wallcycle_stop(wcycle,ewcUPDATE);
1489
1490                 update_constraints(fplog,step,&dvdl,ir,ekind,mdatoms,state,graph,f,
1491                                    &top->idef,shake_vir,force_vir,
1492                                    cr,nrnb,wcycle,upd,constr,
1493                                    bInitStep,FALSE,bCalcEnerPres,state->veta);  
1494                 
1495                 if (ir->eI==eiVVAK) 
1496                 {
1497                     /* erase F_EKIN and F_TEMP here? */
1498                     /* just compute the kinetic energy at the half step to perform a trotter step */
1499                     compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
1500                                     wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
1501                                     constr,NULL,FALSE,lastbox,
1502                                     top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
1503                                     cglo_flags | CGLO_TEMPERATURE    
1504                         );
1505                     wallcycle_start(wcycle,ewcUPDATE);
1506                     trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ4);            
1507                     /* now we know the scaling, we can compute the positions again again */
1508                     copy_rvecn(cbuf,state->x,0,state->natoms);
1509
1510                     update_coords(fplog,step,ir,mdatoms,state,f,fr->bTwinRange && bNStList,fr->f_twin,fcd,
1511                                   ekind,M,wcycle,upd,bInitStep,etrtPOSITION,cr,nrnb,constr,&top->idef);
1512                     wallcycle_stop(wcycle,ewcUPDATE);
1513
1514                     /* do we need an extra constraint here? just need to copy out of state->v to upd->xp? */
1515                     /* are the small terms in the shake_vir here due
1516                      * to numerical errors, or are they important
1517                      * physically? I'm thinking they are just errors, but not completely sure. 
1518                      * For now, will call without actually constraining, constr=NULL*/
1519                     update_constraints(fplog,step,&dvdl,ir,ekind,mdatoms,state,graph,f,
1520                                        &top->idef,tmp_vir,force_vir,
1521                                        cr,nrnb,wcycle,upd,NULL,
1522                                        bInitStep,FALSE,bCalcEnerPres,
1523                                        state->veta);  
1524                 }
1525                 if (!bOK && !bFFscan) 
1526                 {
1527                     gmx_fatal(FARGS,"Constraint error: Shake, Lincs or Settle could not solve the constrains");
1528                 }
1529                 
1530                 if (fr->bSepDVDL && fplog && do_log) 
1531                 {
1532                     fprintf(fplog,sepdvdlformat,"Constraint",0.0,dvdl);
1533                 }
1534                 enerd->term[F_DHDL_CON] += dvdl;
1535             } 
1536             else if (graph) 
1537             {
1538                 /* Need to unshift here */
1539                 unshift_self(graph,state->box,state->x);
1540             }
1541             
1542             GMX_BARRIER(cr->mpi_comm_mygroup);
1543             GMX_MPE_LOG(ev_update_finish);
1544
1545             if (vsite != NULL) 
1546             {
1547                 wallcycle_start(wcycle,ewcVSITECONSTR);
1548                 if (graph != NULL) 
1549                 {
1550                     shift_self(graph,state->box,state->x);
1551                 }
1552                 construct_vsites(fplog,vsite,state->x,nrnb,ir->delta_t,state->v,
1553                                  top->idef.iparams,top->idef.il,
1554                                  fr->ePBC,fr->bMolPBC,graph,cr,state->box);
1555                 
1556                 if (graph != NULL) 
1557                 {
1558                     unshift_self(graph,state->box,state->x);
1559                 }
1560                 wallcycle_stop(wcycle,ewcVSITECONSTR);
1561             }
1562             
1563             /* ############## IF NOT VV, Calculate globals HERE, also iterate constraints ############ */
1564             if (ir->nstlist == -1 && bFirstIterate)
1565             {
1566                 gs.sig[eglsNABNSB] = nlh.nabnsb;
1567             }
1568             compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
1569                             wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
1570                             constr,
1571                             bFirstIterate ? &gs : NULL, 
1572                             (step_rel % gs.nstms == 0) && 
1573                                 (multisim_nsteps<0 || (step_rel<multisim_nsteps)),
1574                             lastbox,
1575                             top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
1576                             cglo_flags 
1577                             | (!EI_VV(ir->eI) ? CGLO_ENERGY : 0) 
1578                             | (!EI_VV(ir->eI) ? CGLO_TEMPERATURE : 0) 
1579                             | (!EI_VV(ir->eI) || bRerunMD ? CGLO_PRESSURE : 0) 
1580                             | (bIterations && iterate.bIterate ? CGLO_ITERATE : 0) 
1581                             | (bFirstIterate ? CGLO_FIRSTITERATE : 0)
1582                             | CGLO_CONSTRAINT 
1583                 );
1584             if (ir->nstlist == -1 && bFirstIterate)
1585             {
1586                 nlh.nabnsb = gs.set[eglsNABNSB];
1587                 gs.set[eglsNABNSB] = 0;
1588             }
1589             /* bIterate is set to keep it from eliminating the old ekin kinetic energy terms */
1590             /* #############  END CALC EKIN AND PRESSURE ################# */
1591         
1592             /* Note: this is OK, but there are some numerical precision issues with using the convergence of
1593                the virial that should probably be addressed eventually. state->veta has better properies,
1594                but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could
1595                generate the new shake_vir, but test the veta value for convergence.  This will take some thought. */
1596
1597             if (bIterations && 
1598                 done_iterating(cr,fplog,step,&iterate,bFirstIterate,
1599                                trace(shake_vir),&tracevir)) 
1600             {
1601                 break;
1602             }
1603             bFirstIterate = FALSE;
1604         }
1605
1606         update_box(fplog,step,ir,mdatoms,state,graph,f,
1607                    ir->nstlist==-1 ? &nlh.scale_tot : NULL,pcoupl_mu,nrnb,wcycle,upd,bInitStep,FALSE);
1608         
1609         /* ################# END UPDATE STEP 2 ################# */
1610         /* #### We now have r(t+dt) and v(t+dt/2)  ############# */
1611     
1612         /* The coordinates (x) were unshifted in update */
1613         if (bFFscan && (shellfc==NULL || bConverged))
1614         {
1615             if (print_forcefield(fplog,enerd->term,mdatoms->homenr,
1616                                  f,NULL,xcopy,
1617                                  &(top_global->mols),mdatoms->massT,pres))
1618             {
1619                 if (gmx_parallel_env_initialized())
1620                 {
1621                     gmx_finalize();
1622                 }
1623                 fprintf(stderr,"\n");
1624                 exit(0);
1625             }
1626         }
1627         if (!bGStat)
1628         {
1629             /* We will not sum ekinh_old,                                                            
1630              * so signal that we still have to do it.                                                
1631              */
1632             bSumEkinhOld = TRUE;
1633         }
1634         
1635         if (bTCR)
1636         {
1637             /* Only do GCT when the relaxation of shells (minimization) has converged,
1638              * otherwise we might be coupling to bogus energies. 
1639              * In parallel we must always do this, because the other sims might
1640              * update the FF.
1641              */
1642
1643             /* Since this is called with the new coordinates state->x, I assume
1644              * we want the new box state->box too. / EL 20040121
1645              */
1646             do_coupling(fplog,oenv,nfile,fnm,tcr,t,step,enerd->term,fr,
1647                         ir,MASTER(cr),
1648                         mdatoms,&(top->idef),mu_aver,
1649                         top_global->mols.nr,cr,
1650                         state->box,total_vir,pres,
1651                         mu_tot,state->x,f,bConverged);
1652             debug_gmx();
1653         }
1654
1655         /* #########  BEGIN PREPARING EDR OUTPUT  ###########  */
1656         
1657         /* sum up the foreign energy and dhdl terms */
1658         sum_dhdl(enerd,state->lambda,ir);
1659
1660         /* use the directly determined last velocity, not actually the averaged half steps */
1661         if (bTrotter && ir->eI==eiVV) 
1662         {
1663             enerd->term[F_EKIN] = last_ekin;
1664         }
1665         enerd->term[F_ETOT] = enerd->term[F_EPOT] + enerd->term[F_EKIN];
1666         
1667         if (bVV)
1668         {
1669             enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + saved_conserved_quantity;
1670         }
1671         else 
1672         {
1673             enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + compute_conserved_from_auxiliary(ir,state,&MassQ);
1674         }
1675         /* Check for excessively large energies */
1676         if (bIonize) 
1677         {
1678 #ifdef GMX_DOUBLE
1679             real etot_max = 1e200;
1680 #else
1681             real etot_max = 1e30;
1682 #endif
1683             if (fabs(enerd->term[F_ETOT]) > etot_max) 
1684             {
1685                 fprintf(stderr,"Energy too large (%g), giving up\n",
1686                         enerd->term[F_ETOT]);
1687             }
1688         }
1689         /* #########  END PREPARING EDR OUTPUT  ###########  */
1690         
1691         /* Time for performance */
1692         if (((step % stepout) == 0) || bLastStep) 
1693         {
1694             runtime_upd_proc(runtime);
1695         }
1696         
1697         /* Output stuff */
1698         if (MASTER(cr))
1699         {
1700             gmx_bool do_dr,do_or;
1701             
1702             if (!(bStartingFromCpt && (EI_VV(ir->eI)))) 
1703             {
1704                 if (bNstEner)
1705                 {
1706                     upd_mdebin(mdebin,bDoDHDL, TRUE,
1707                                t,mdatoms->tmass,enerd,state,lastbox,
1708                                shake_vir,force_vir,total_vir,pres,
1709                                ekind,mu_tot,constr);
1710                 }
1711                 else
1712                 {
1713                     upd_mdebin_step(mdebin);
1714                 }
1715                 
1716                 do_dr  = do_per_step(step,ir->nstdisreout);
1717                 do_or  = do_per_step(step,ir->nstorireout);
1718                 
1719                 print_ebin(outf->fp_ene,do_ene,do_dr,do_or,do_log?fplog:NULL,
1720                            step,t,
1721                            eprNORMAL,bCompact,mdebin,fcd,groups,&(ir->opts));
1722             }
1723             if (ir->ePull != epullNO)
1724             {
1725                 pull_print_output(ir->pull,step,t);
1726             }
1727             
1728             if (do_per_step(step,ir->nstlog))
1729             {
1730                 if(fflush(fplog) != 0)
1731                 {
1732                     gmx_fatal(FARGS,"Cannot flush logfile - maybe you are out of quota?");
1733                 }
1734             }
1735         }
1736
1737
1738         /* Remaining runtime */
1739         if (MULTIMASTER(cr) && (do_verbose || gmx_got_usr_signal() ))
1740         {
1741             if (shellfc) 
1742             {
1743                 fprintf(stderr,"\n");
1744             }
1745             print_time(stderr,runtime,step,ir,cr);
1746         }
1747
1748         /* Replica exchange */
1749         bExchanged = FALSE;
1750         if ((repl_ex_nst > 0) && (step > 0) && !bLastStep &&
1751             do_per_step(step,repl_ex_nst)) 
1752         {
1753             bExchanged = replica_exchange(fplog,cr,repl_ex,
1754                                           state_global,enerd->term,
1755                                           state,step,t);
1756
1757             if (bExchanged && DOMAINDECOMP(cr)) 
1758             {
1759                 dd_partition_system(fplog,step,cr,TRUE,1,
1760                                     state_global,top_global,ir,
1761                                     state,&f,mdatoms,top,fr,
1762                                     vsite,shellfc,constr,
1763                                     nrnb,wcycle,FALSE);
1764             }
1765         }
1766         
1767         bFirstStep = FALSE;
1768         bInitStep = FALSE;
1769         bStartingFromCpt = FALSE;
1770
1771         /* #######  SET VARIABLES FOR NEXT ITERATION IF THEY STILL NEED IT ###### */
1772         /* With all integrators, except VV, we need to retain the pressure
1773          * at the current step for coupling at the next step.
1774          */
1775         if ((state->flags & (1<<estPRES_PREV)) &&
1776             (bGStatEveryStep ||
1777              (ir->nstpcouple > 0 && step % ir->nstpcouple == 0)))
1778         {
1779             /* Store the pressure in t_state for pressure coupling
1780              * at the next MD step.
1781              */
1782             copy_mat(pres,state->pres_prev);
1783         }
1784         
1785         /* #######  END SET VARIABLES FOR NEXT ITERATION ###### */
1786
1787         if ( (membed!=NULL) && (!bLastStep) )
1788             rescale_membed(step_rel,membed,state_global->x);
1789         
1790         if (bRerunMD) 
1791         {
1792             if (MASTER(cr))
1793             {
1794                 /* read next frame from input trajectory */
1795                 bNotLastFrame = read_next_frame(oenv,status,&rerun_fr);
1796             }
1797
1798             if (PAR(cr))
1799             {
1800                 rerun_parallel_comm(cr,&rerun_fr,&bNotLastFrame);
1801             }
1802         }
1803         
1804         if (!bRerunMD || !rerun_fr.bStep)
1805         {
1806             /* increase the MD step number */
1807             step++;
1808             step_rel++;
1809         }
1810         
1811         cycles = wallcycle_stop(wcycle,ewcSTEP);
1812         if (DOMAINDECOMP(cr) && wcycle)
1813         {
1814             dd_cycles_add(cr->dd,cycles,ddCyclStep);
1815         }
1816         
1817         if (step_rel == wcycle_get_reset_counters(wcycle) ||
1818             gs.set[eglsRESETCOUNTERS] != 0)
1819         {
1820             /* Reset all the counters related to performance over the run */
1821             reset_all_counters(fplog,cr,step,&step_rel,ir,wcycle,nrnb,runtime);
1822             wcycle_set_reset_counters(wcycle,-1);
1823             /* Correct max_hours for the elapsed time */
1824             max_hours -= run_time/(60.0*60.0);
1825             bResetCountersHalfMaxH = FALSE;
1826             gs.set[eglsRESETCOUNTERS] = 0;
1827         }
1828
1829     }
1830     /* End of main MD loop */
1831     debug_gmx();
1832     
1833     /* Stop the time */
1834     runtime_end(runtime);
1835     
1836     if (bRerunMD && MASTER(cr))
1837     {
1838         close_trj(status);
1839     }
1840     
1841     if (!(cr->duty & DUTY_PME))
1842     {
1843         /* Tell the PME only node to finish */
1844         gmx_pme_finish(cr);
1845     }
1846     
1847     if (MASTER(cr))
1848     {
1849         if (ir->nstcalcenergy > 0 && !bRerunMD) 
1850         {
1851             print_ebin(outf->fp_ene,FALSE,FALSE,FALSE,fplog,step,t,
1852                        eprAVER,FALSE,mdebin,fcd,groups,&(ir->opts));
1853         }
1854     }
1855
1856     done_mdoutf(outf);
1857
1858     debug_gmx();
1859
1860     if (ir->nstlist == -1 && nlh.nns > 0 && fplog)
1861     {
1862         fprintf(fplog,"Average neighborlist lifetime: %.1f steps, std.dev.: %.1f steps\n",nlh.s1/nlh.nns,sqrt(nlh.s2/nlh.nns - sqr(nlh.s1/nlh.nns)));
1863         fprintf(fplog,"Average number of atoms that crossed the half buffer length: %.1f\n\n",nlh.ab/nlh.nns);
1864     }
1865     
1866     if (shellfc && fplog)
1867     {
1868         fprintf(fplog,"Fraction of iterations that converged:           %.2f %%\n",
1869                 (nconverged*100.0)/step_rel);
1870         fprintf(fplog,"Average number of force evaluations per MD step: %.2f\n\n",
1871                 tcount/step_rel);
1872     }
1873     
1874     if (repl_ex_nst > 0 && MASTER(cr))
1875     {
1876         print_replica_exchange_statistics(fplog,repl_ex);
1877     }
1878     
1879     runtime->nsteps_done = step_rel;
1880     
1881     return 0;
1882 }