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