Fix constraint virial with multiple time stepping
[alexxy/gromacs.git] / src / kernel / md.c
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team,
6  * check out http://www.gromacs.org for more information.
7  * Copyright (c) 2012,2013, by the GROMACS development team, led by
8  * David van der Spoel, Berk Hess, Erik Lindahl, and including many
9  * others, as listed in the AUTHORS file in the top-level source
10  * directory and at http://www.gromacs.org.
11  *
12  * GROMACS is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public License
14  * as published by the Free Software Foundation; either version 2.1
15  * of the License, or (at your option) any later version.
16  *
17  * GROMACS is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with GROMACS; if not, see
24  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
26  *
27  * If you want to redistribute modifications to GROMACS, please
28  * consider that scientific software is very special. Version
29  * control is crucial - bugs must be traceable. We will be happy to
30  * consider code for inclusion in the official distribution, but
31  * derived work must not be called official GROMACS. Details are found
32  * in the README & COPYING files - if they are missing, get the
33  * official version at http://www.gromacs.org.
34  *
35  * To help us fund GROMACS development, we humbly ask that you cite
36  * the research papers on the package. Check out http://www.gromacs.org.
37  */
38 #ifdef HAVE_CONFIG_H
39 #include <config.h>
40 #endif
41
42 #include "typedefs.h"
43 #include "smalloc.h"
44 #include "sysstuff.h"
45 #include "vec.h"
46 #include "statutil.h"
47 #include "vcm.h"
48 #include "mdebin.h"
49 #include "nrnb.h"
50 #include "calcmu.h"
51 #include "index.h"
52 #include "vsite.h"
53 #include "update.h"
54 #include "ns.h"
55 #include "trnio.h"
56 #include "xtcio.h"
57 #include "mdrun.h"
58 #include "md_support.h"
59 #include "md_logging.h"
60 #include "confio.h"
61 #include "network.h"
62 #include "pull.h"
63 #include "xvgr.h"
64 #include "physics.h"
65 #include "names.h"
66 #include "xmdrun.h"
67 #include "ionize.h"
68 #include "disre.h"
69 #include "orires.h"
70 #include "pme.h"
71 #include "mdatoms.h"
72 #include "repl_ex.h"
73 #include "qmmm.h"
74 #include "mpelogging.h"
75 #include "domdec.h"
76 #include "domdec_network.h"
77 #include "partdec.h"
78 #include "topsort.h"
79 #include "coulomb.h"
80 #include "constr.h"
81 #include "shellfc.h"
82 #include "compute_io.h"
83 #include "mvdata.h"
84 #include "checkpoint.h"
85 #include "mtop_util.h"
86 #include "sighandler.h"
87 #include "txtdump.h"
88 #include "string2.h"
89 #include "pme_loadbal.h"
90 #include "bondf.h"
91 #include "membed.h"
92 #include "types/nlistheuristics.h"
93 #include "types/iteratedconstraints.h"
94 #include "nbnxn_cuda_data_mgmt.h"
95
96 #ifdef GMX_LIB_MPI
97 #include <mpi.h>
98 #endif
99 #ifdef GMX_THREAD_MPI
100 #include "tmpi.h"
101 #endif
102
103 #ifdef GMX_FAHCORE
104 #include "corewrap.h"
105 #endif
106
107 static void reset_all_counters(FILE *fplog, t_commrec *cr,
108                                gmx_large_int_t step,
109                                gmx_large_int_t *step_rel, t_inputrec *ir,
110                                gmx_wallcycle_t wcycle, t_nrnb *nrnb,
111                                gmx_runtime_t *runtime,
112                                nbnxn_cuda_ptr_t cu_nbv)
113 {
114     char sbuf[STEPSTRSIZE];
115
116     /* Reset all the counters related to performance over the run */
117     md_print_warn(cr, fplog, "step %s: resetting all time and cycle counters\n",
118                   gmx_step_str(step, sbuf));
119
120     if (cu_nbv)
121     {
122         nbnxn_cuda_reset_timings(cu_nbv);
123     }
124
125     wallcycle_stop(wcycle, ewcRUN);
126     wallcycle_reset_all(wcycle);
127     if (DOMAINDECOMP(cr))
128     {
129         reset_dd_statistics_counters(cr->dd);
130     }
131     init_nrnb(nrnb);
132     ir->init_step += *step_rel;
133     ir->nsteps    -= *step_rel;
134     *step_rel      = 0;
135     wallcycle_start(wcycle, ewcRUN);
136     runtime_start(runtime);
137     print_date_and_time(fplog, cr->nodeid, "Restarted time", runtime);
138 }
139
140 double do_md(FILE *fplog, t_commrec *cr, int nfile, const t_filenm fnm[],
141              const output_env_t oenv, gmx_bool bVerbose, gmx_bool bCompact,
142              int nstglobalcomm,
143              gmx_vsite_t *vsite, gmx_constr_t constr,
144              int stepout, t_inputrec *ir,
145              gmx_mtop_t *top_global,
146              t_fcdata *fcd,
147              t_state *state_global,
148              t_mdatoms *mdatoms,
149              t_nrnb *nrnb, gmx_wallcycle_t wcycle,
150              gmx_edsam_t ed, t_forcerec *fr,
151              int repl_ex_nst, int repl_ex_nex, int repl_ex_seed, gmx_membed_t membed,
152              real cpt_period, real max_hours,
153              const char *deviceOptions,
154              unsigned long Flags,
155              gmx_runtime_t *runtime)
156 {
157     gmx_mdoutf_t   *outf;
158     gmx_large_int_t step, step_rel;
159     double          run_time;
160     double          t, t0, lam0[efptNR];
161     gmx_bool        bGStatEveryStep, bGStat, bCalcVir, bCalcEner;
162     gmx_bool        bNS, bNStList, bSimAnn, bStopCM, bRerunMD, bNotLastFrame = FALSE,
163                     bFirstStep, bStateFromCP, bStateFromTPX, bInitStep, bLastStep,
164                     bBornRadii, bStartingFromCpt;
165     gmx_bool          bDoDHDL = FALSE, bDoFEP = FALSE, bDoExpanded = FALSE;
166     gmx_bool          do_ene, do_log, do_verbose, bRerunWarnNoV = TRUE,
167                       bForceUpdate = FALSE, bCPT;
168     int               mdof_flags;
169     gmx_bool          bMasterState;
170     int               force_flags, cglo_flags;
171     tensor            force_vir, shake_vir, total_vir, tmp_vir, pres;
172     int               i, m;
173     t_trxstatus      *status;
174     rvec              mu_tot;
175     t_vcm            *vcm;
176     t_state          *bufstate = NULL;
177     matrix           *scale_tot, pcoupl_mu, M, ebox;
178     gmx_nlheur_t      nlh;
179     t_trxframe        rerun_fr;
180     gmx_repl_ex_t     repl_ex = NULL;
181     int               nchkpt  = 1;
182     gmx_localtop_t   *top;
183     t_mdebin         *mdebin = NULL;
184     t_state          *state    = NULL;
185     rvec             *f_global = NULL;
186     int               n_xtc    = -1;
187     rvec             *x_xtc    = NULL;
188     gmx_enerdata_t   *enerd;
189     rvec             *f = NULL;
190     gmx_global_stat_t gstat;
191     gmx_update_t      upd   = NULL;
192     t_graph          *graph = NULL;
193     globsig_t         gs;
194     gmx_rng_t         mcrng = NULL;
195     gmx_bool          bFFscan;
196     gmx_groups_t     *groups;
197     gmx_ekindata_t   *ekind, *ekind_save;
198     gmx_shellfc_t     shellfc;
199     int               count, nconverged = 0;
200     real              timestep = 0;
201     double            tcount   = 0;
202     gmx_bool          bIonize  = FALSE;
203     gmx_bool          bTCR     = FALSE, bConverged = TRUE, bOK, bSumEkinhOld, bExchanged;
204     gmx_bool          bAppend;
205     gmx_bool          bResetCountersHalfMaxH = FALSE;
206     gmx_bool          bVV, bIterativeCase, bFirstIterate, bTemp, bPres, bTrotter;
207     gmx_bool          bUpdateDoLR;
208     real              mu_aver = 0, dvdl_constr;
209     int               a0, a1, gnx = 0, ii;
210     atom_id          *grpindex = NULL;
211     char             *grpname;
212     t_coupl_rec      *tcr     = NULL;
213     rvec             *xcopy   = NULL, *vcopy = NULL, *cbuf = NULL;
214     matrix            boxcopy = {{0}}, lastbox;
215     tensor            tmpvir;
216     real              fom, oldfom, veta_save, pcurr, scalevir, tracevir;
217     real              vetanew = 0;
218     int               lamnew  = 0;
219     /* for FEP */
220     int               nstfep;
221     real              rate;
222     double            cycles;
223     real              saved_conserved_quantity = 0;
224     real              last_ekin                = 0;
225     int               iter_i;
226     t_extmass         MassQ;
227     int             **trotter_seq;
228     char              sbuf[STEPSTRSIZE], sbuf2[STEPSTRSIZE];
229     int               handled_stop_condition = gmx_stop_cond_none; /* compare to get_stop_condition*/
230     gmx_iterate_t     iterate;
231     gmx_large_int_t   multisim_nsteps = -1;                        /* number of steps to do  before first multisim
232                                                                       simulation stops. If equal to zero, don't
233                                                                       communicate any more between multisims.*/
234     /* PME load balancing data for GPU kernels */
235     pme_load_balancing_t pme_loadbal = NULL;
236     double               cycles_pmes;
237     gmx_bool             bPMETuneTry = FALSE, bPMETuneRunning = FALSE;
238
239 #ifdef GMX_FAHCORE
240     /* Temporary addition for FAHCORE checkpointing */
241     int chkpt_ret;
242 #endif
243
244     /* Check for special mdrun options */
245     bRerunMD = (Flags & MD_RERUN);
246     bIonize  = (Flags & MD_IONIZE);
247     bFFscan  = (Flags & MD_FFSCAN);
248     bAppend  = (Flags & MD_APPENDFILES);
249     if (Flags & MD_RESETCOUNTERSHALFWAY)
250     {
251         if (ir->nsteps > 0)
252         {
253             /* Signal to reset the counters half the simulation steps. */
254             wcycle_set_reset_counters(wcycle, ir->nsteps/2);
255         }
256         /* Signal to reset the counters halfway the simulation time. */
257         bResetCountersHalfMaxH = (max_hours > 0);
258     }
259
260     /* md-vv uses averaged full step velocities for T-control
261        md-vv-avek uses averaged half step velocities for T-control (but full step ekin for P control)
262        md uses averaged half step kinetic energies to determine temperature unless defined otherwise by GMX_EKIN_AVE_VEL; */
263     bVV = EI_VV(ir->eI);
264     if (bVV) /* to store the initial velocities while computing virial */
265     {
266         snew(cbuf, top_global->natoms);
267     }
268     /* all the iteratative cases - only if there are constraints */
269     bIterativeCase = ((IR_NPH_TROTTER(ir) || IR_NPT_TROTTER(ir)) && (constr) && (!bRerunMD));
270     gmx_iterate_init(&iterate, FALSE); /* The default value of iterate->bIterationActive is set to
271                                           false in this step.  The correct value, true or false,
272                                           is set at each step, as it depends on the frequency of temperature
273                                           and pressure control.*/
274     bTrotter = (bVV && (IR_NPT_TROTTER(ir) || IR_NPH_TROTTER(ir) || IR_NVT_TROTTER(ir)));
275
276     if (bRerunMD)
277     {
278         /* Since we don't know if the frames read are related in any way,
279          * rebuild the neighborlist at every step.
280          */
281         ir->nstlist       = 1;
282         ir->nstcalcenergy = 1;
283         nstglobalcomm     = 1;
284     }
285
286     check_ir_old_tpx_versions(cr, fplog, ir, top_global);
287
288     nstglobalcomm   = check_nstglobalcomm(fplog, cr, nstglobalcomm, ir);
289     bGStatEveryStep = (nstglobalcomm == 1);
290
291     if (!bGStatEveryStep && ir->nstlist == -1 && fplog != NULL)
292     {
293         fprintf(fplog,
294                 "To reduce the energy communication with nstlist = -1\n"
295                 "the neighbor list validity should not be checked at every step,\n"
296                 "this means that exact integration is not guaranteed.\n"
297                 "The neighbor list validity is checked after:\n"
298                 "  <n.list life time> - 2*std.dev.(n.list life time)  steps.\n"
299                 "In most cases this will result in exact integration.\n"
300                 "This reduces the energy communication by a factor of 2 to 3.\n"
301                 "If you want less energy communication, set nstlist > 3.\n\n");
302     }
303
304     if (bRerunMD || bFFscan)
305     {
306         ir->nstxtcout = 0;
307     }
308     groups = &top_global->groups;
309
310     /* Initial values */
311     init_md(fplog, cr, ir, oenv, &t, &t0, state_global->lambda,
312             &(state_global->fep_state), lam0,
313             nrnb, top_global, &upd,
314             nfile, fnm, &outf, &mdebin,
315             force_vir, shake_vir, mu_tot, &bSimAnn, &vcm, state_global, Flags);
316
317     clear_mat(total_vir);
318     clear_mat(pres);
319     /* Energy terms and groups */
320     snew(enerd, 1);
321     init_enerdata(top_global->groups.grps[egcENER].nr, ir->fepvals->n_lambda,
322                   enerd);
323     if (DOMAINDECOMP(cr))
324     {
325         f = NULL;
326     }
327     else
328     {
329         snew(f, top_global->natoms);
330     }
331
332     /* Kinetic energy data */
333     snew(ekind, 1);
334     init_ekindata(fplog, top_global, &(ir->opts), ekind);
335     /* needed for iteration of constraints */
336     snew(ekind_save, 1);
337     init_ekindata(fplog, top_global, &(ir->opts), ekind_save);
338     /* Copy the cos acceleration to the groups struct */
339     ekind->cosacc.cos_accel = ir->cos_accel;
340
341     gstat = global_stat_init(ir);
342     debug_gmx();
343
344     /* Check for polarizable models and flexible constraints */
345     shellfc = init_shell_flexcon(fplog, fr->cutoff_scheme == ecutsVERLET,
346                                  top_global, n_flexible_constraints(constr),
347                                  (ir->bContinuation ||
348                                   (DOMAINDECOMP(cr) && !MASTER(cr))) ?
349                                  NULL : state_global->x);
350
351     if (shellfc && ir->eI == eiNM)
352     {
353         /* Currently shells don't work with Normal Modes */
354         gmx_fatal(FARGS, "Normal Mode analysis is not supported with shells.\nIf you'd like to help with adding support, we have an open discussion at http://redmine.gromacs.org/issues/879\n");
355     }
356
357     if (vsite && ir->eI == eiNM)
358     {
359         /* Currently virtual sites don't work with Normal Modes */
360         gmx_fatal(FARGS, "Normal Mode analysis is not supported with virtual sites.\nIf you'd like to help with adding support, we have an open discussion at http://redmine.gromacs.org/issues/879\n");
361     }
362
363     if (DEFORM(*ir))
364     {
365 #ifdef GMX_THREAD_MPI
366         tMPI_Thread_mutex_lock(&deform_init_box_mutex);
367 #endif
368         set_deform_reference_box(upd,
369                                  deform_init_init_step_tpx,
370                                  deform_init_box_tpx);
371 #ifdef GMX_THREAD_MPI
372         tMPI_Thread_mutex_unlock(&deform_init_box_mutex);
373 #endif
374     }
375
376     {
377         double io = compute_io(ir, top_global->natoms, groups, mdebin->ebin->nener, 1);
378         if ((io > 2000) && MASTER(cr))
379         {
380             fprintf(stderr,
381                     "\nWARNING: This run will generate roughly %.0f Mb of data\n\n",
382                     io);
383         }
384     }
385
386     if (DOMAINDECOMP(cr))
387     {
388         top = dd_init_local_top(top_global);
389
390         snew(state, 1);
391         dd_init_local_state(cr->dd, state_global, state);
392
393         if (DDMASTER(cr->dd) && ir->nstfout)
394         {
395             snew(f_global, state_global->natoms);
396         }
397     }
398     else
399     {
400         if (PAR(cr))
401         {
402             /* Initialize the particle decomposition and split the topology */
403             top = split_system(fplog, top_global, ir, cr);
404
405             pd_cg_range(cr, &fr->cg0, &fr->hcg);
406             pd_at_range(cr, &a0, &a1);
407         }
408         else
409         {
410             top = gmx_mtop_generate_local_top(top_global, ir);
411
412             a0 = 0;
413             a1 = top_global->natoms;
414         }
415
416         forcerec_set_excl_load(fr, top, cr);
417
418         state    = partdec_init_local_state(cr, state_global);
419         f_global = f;
420
421         atoms2md(top_global, ir, 0, NULL, a0, a1-a0, mdatoms);
422
423         if (vsite)
424         {
425             set_vsite_top(vsite, top, mdatoms, cr);
426         }
427
428         if (ir->ePBC != epbcNONE && !fr->bMolPBC)
429         {
430             graph = mk_graph(fplog, &(top->idef), 0, top_global->natoms, FALSE, FALSE);
431         }
432
433         if (shellfc)
434         {
435             make_local_shells(cr, mdatoms, shellfc);
436         }
437
438         setup_bonded_threading(fr, &top->idef);
439
440         if (ir->pull && PAR(cr))
441         {
442             dd_make_local_pull_groups(NULL, ir->pull, mdatoms);
443         }
444     }
445
446     if (DOMAINDECOMP(cr))
447     {
448         /* Distribute the charge groups over the nodes from the master node */
449         dd_partition_system(fplog, ir->init_step, cr, TRUE, 1,
450                             state_global, top_global, ir,
451                             state, &f, mdatoms, top, fr,
452                             vsite, shellfc, constr,
453                             nrnb, wcycle, FALSE);
454
455     }
456
457     update_mdatoms(mdatoms, state->lambda[efptMASS]);
458
459     if (opt2bSet("-cpi", nfile, fnm))
460     {
461         bStateFromCP = gmx_fexist_master(opt2fn_master("-cpi", nfile, fnm, cr), cr);
462     }
463     else
464     {
465         bStateFromCP = FALSE;
466     }
467
468     if (ir->bExpanded)
469     {
470         init_expanded_ensemble(bStateFromCP,ir,&mcrng,&state->dfhist);
471     }
472
473     if (MASTER(cr))
474     {
475         if (bStateFromCP)
476         {
477             /* Update mdebin with energy history if appending to output files */
478             if (Flags & MD_APPENDFILES)
479             {
480                 restore_energyhistory_from_state(mdebin, &state_global->enerhist);
481             }
482             else
483             {
484                 /* We might have read an energy history from checkpoint,
485                  * free the allocated memory and reset the counts.
486                  */
487                 done_energyhistory(&state_global->enerhist);
488                 init_energyhistory(&state_global->enerhist);
489             }
490         }
491         /* Set the initial energy history in state by updating once */
492         update_energyhistory(&state_global->enerhist, mdebin);
493     }
494
495     if ((state->flags & (1<<estLD_RNG)) && (Flags & MD_READ_RNG))
496     {
497         /* Set the random state if we read a checkpoint file */
498         set_stochd_state(upd, state);
499     }
500
501     if (state->flags & (1<<estMC_RNG))
502     {
503         set_mc_state(mcrng, state);
504     }
505
506     /* Initialize constraints */
507     if (constr)
508     {
509         if (!DOMAINDECOMP(cr))
510         {
511             set_constraints(constr, top, ir, mdatoms, cr);
512         }
513     }
514
515     /* Check whether we have to GCT stuff */
516     bTCR = ftp2bSet(efGCT, nfile, fnm);
517     if (bTCR)
518     {
519         if (MASTER(cr))
520         {
521             fprintf(stderr, "Will do General Coupling Theory!\n");
522         }
523         gnx = top_global->mols.nr;
524         snew(grpindex, gnx);
525         for (i = 0; (i < gnx); i++)
526         {
527             grpindex[i] = i;
528         }
529     }
530
531     if (repl_ex_nst > 0)
532     {
533         /* We need to be sure replica exchange can only occur
534          * when the energies are current */
535         check_nst_param(fplog, cr, "nstcalcenergy", ir->nstcalcenergy,
536                         "repl_ex_nst", &repl_ex_nst);
537         /* This check needs to happen before inter-simulation
538          * signals are initialized, too */
539     }
540     if (repl_ex_nst > 0 && MASTER(cr))
541     {
542         repl_ex = init_replica_exchange(fplog, cr->ms, state_global, ir,
543                                         repl_ex_nst, repl_ex_nex, repl_ex_seed);
544     }
545
546     /* PME tuning is only supported with GPUs or PME nodes and not with rerun.
547      * With perturbed charges with soft-core we should not change the cut-off.
548      */
549     if ((Flags & MD_TUNEPME) &&
550         EEL_PME(fr->eeltype) &&
551         ( (fr->cutoff_scheme == ecutsVERLET && fr->nbv->bUseGPU) || !(cr->duty & DUTY_PME)) &&
552         !(ir->efep != efepNO && mdatoms->nChargePerturbed > 0 && ir->fepvals->bScCoul) &&
553         !bRerunMD)
554     {
555         pme_loadbal_init(&pme_loadbal, ir, state->box, fr->ic, fr->pmedata);
556         cycles_pmes = 0;
557         if (cr->duty & DUTY_PME)
558         {
559             /* Start tuning right away, as we can't measure the load */
560             bPMETuneRunning = TRUE;
561         }
562         else
563         {
564             /* Separate PME nodes, we can measure the PP/PME load balance */
565             bPMETuneTry = TRUE;
566         }
567     }
568
569     if (!ir->bContinuation && !bRerunMD)
570     {
571         if (mdatoms->cFREEZE && (state->flags & (1<<estV)))
572         {
573             /* Set the velocities of frozen particles to zero */
574             for (i = mdatoms->start; i < mdatoms->start+mdatoms->homenr; i++)
575             {
576                 for (m = 0; m < DIM; m++)
577                 {
578                     if (ir->opts.nFreeze[mdatoms->cFREEZE[i]][m])
579                     {
580                         state->v[i][m] = 0;
581                     }
582                 }
583             }
584         }
585
586         if (constr)
587         {
588             /* Constrain the initial coordinates and velocities */
589             do_constrain_first(fplog, constr, ir, mdatoms, state, f,
590                                graph, cr, nrnb, fr, top, shake_vir);
591         }
592         if (vsite)
593         {
594             /* Construct the virtual sites for the initial configuration */
595             construct_vsites(fplog, vsite, state->x, nrnb, ir->delta_t, NULL,
596                              top->idef.iparams, top->idef.il,
597                              fr->ePBC, fr->bMolPBC, graph, cr, state->box);
598         }
599     }
600
601     debug_gmx();
602
603     /* set free energy calculation frequency as the minimum
604        greatest common denominator of nstdhdl, nstexpanded, and repl_ex_nst*/
605     nstfep = ir->fepvals->nstdhdl;
606     if (ir->bExpanded)
607     {
608         nstfep = gmx_greatest_common_divisor(ir->fepvals->nstdhdl,nstfep);
609     }
610     if (repl_ex_nst > 0)
611     {
612         nstfep = gmx_greatest_common_divisor(repl_ex_nst,nstfep);
613     }
614
615     /* I'm assuming we need global communication the first time! MRS */
616     cglo_flags = (CGLO_TEMPERATURE | CGLO_GSTAT
617                   | ((ir->comm_mode != ecmNO) ? CGLO_STOPCM : 0)
618                   | (bVV ? CGLO_PRESSURE : 0)
619                   | (bVV ? CGLO_CONSTRAINT : 0)
620                   | (bRerunMD ? CGLO_RERUNMD : 0)
621                   | ((Flags & MD_READ_EKIN) ? CGLO_READEKIN : 0));
622
623     bSumEkinhOld = FALSE;
624     compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
625                     NULL, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
626                     constr, NULL, FALSE, state->box,
627                     top_global, &pcurr, top_global->natoms, &bSumEkinhOld, cglo_flags);
628     if (ir->eI == eiVVAK)
629     {
630         /* a second call to get the half step temperature initialized as well */
631         /* we do the same call as above, but turn the pressure off -- internally to
632            compute_globals, this is recognized as a velocity verlet half-step
633            kinetic energy calculation.  This minimized excess variables, but
634            perhaps loses some logic?*/
635
636         compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
637                         NULL, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
638                         constr, NULL, FALSE, state->box,
639                         top_global, &pcurr, top_global->natoms, &bSumEkinhOld,
640                         cglo_flags &~(CGLO_STOPCM | CGLO_PRESSURE));
641     }
642
643     /* Calculate the initial half step temperature, and save the ekinh_old */
644     if (!(Flags & MD_STARTFROMCPT))
645     {
646         for (i = 0; (i < ir->opts.ngtc); i++)
647         {
648             copy_mat(ekind->tcstat[i].ekinh, ekind->tcstat[i].ekinh_old);
649         }
650     }
651     if (ir->eI != eiVV)
652     {
653         enerd->term[F_TEMP] *= 2; /* result of averages being done over previous and current step,
654                                      and there is no previous step */
655     }
656
657     /* if using an iterative algorithm, we need to create a working directory for the state. */
658     if (bIterativeCase)
659     {
660         bufstate = init_bufstate(state);
661     }
662     if (bFFscan)
663     {
664         snew(xcopy, state->natoms);
665         snew(vcopy, state->natoms);
666         copy_rvecn(state->x, xcopy, 0, state->natoms);
667         copy_rvecn(state->v, vcopy, 0, state->natoms);
668         copy_mat(state->box, boxcopy);
669     }
670
671     /* need to make an initiation call to get the Trotter variables set, as well as other constants for non-trotter
672        temperature control */
673     trotter_seq = init_npt_vars(ir, state, &MassQ, bTrotter);
674
675     if (MASTER(cr))
676     {
677         if (constr && !ir->bContinuation && ir->eConstrAlg == econtLINCS)
678         {
679             fprintf(fplog,
680                     "RMS relative constraint deviation after constraining: %.2e\n",
681                     constr_rmsd(constr, FALSE));
682         }
683         if (EI_STATE_VELOCITY(ir->eI))
684         {
685             fprintf(fplog, "Initial temperature: %g K\n", enerd->term[F_TEMP]);
686         }
687         if (bRerunMD)
688         {
689             fprintf(stderr, "starting md rerun '%s', reading coordinates from"
690                     " input trajectory '%s'\n\n",
691                     *(top_global->name), opt2fn("-rerun", nfile, fnm));
692             if (bVerbose)
693             {
694                 fprintf(stderr, "Calculated time to finish depends on nsteps from "
695                         "run input file,\nwhich may not correspond to the time "
696                         "needed to process input trajectory.\n\n");
697             }
698         }
699         else
700         {
701             char tbuf[20];
702             fprintf(stderr, "starting mdrun '%s'\n",
703                     *(top_global->name));
704             if (ir->nsteps >= 0)
705             {
706                 sprintf(tbuf, "%8.1f", (ir->init_step+ir->nsteps)*ir->delta_t);
707             }
708             else
709             {
710                 sprintf(tbuf, "%s", "infinite");
711             }
712             if (ir->init_step > 0)
713             {
714                 fprintf(stderr, "%s steps, %s ps (continuing from step %s, %8.1f ps).\n",
715                         gmx_step_str(ir->init_step+ir->nsteps, sbuf), tbuf,
716                         gmx_step_str(ir->init_step, sbuf2),
717                         ir->init_step*ir->delta_t);
718             }
719             else
720             {
721                 fprintf(stderr, "%s steps, %s ps.\n",
722                         gmx_step_str(ir->nsteps, sbuf), tbuf);
723             }
724         }
725         fprintf(fplog, "\n");
726     }
727
728     print_start(fplog, cr, runtime, "mdrun");
729     runtime_start(runtime);
730     wallcycle_start(wcycle, ewcRUN);
731
732     /* safest point to do file checkpointing is here.  More general point would be immediately before integrator call */
733 #ifdef GMX_FAHCORE
734     chkpt_ret = fcCheckPointParallel( cr->nodeid,
735                                       NULL, 0);
736     if (chkpt_ret == 0)
737     {
738         gmx_fatal( 3, __FILE__, __LINE__, "Checkpoint error on step %d\n", 0 );
739     }
740 #endif
741
742     debug_gmx();
743     /***********************************************************
744      *
745      *             Loop over MD steps
746      *
747      ************************************************************/
748
749     /* if rerunMD then read coordinates and velocities from input trajectory */
750     if (bRerunMD)
751     {
752         if (getenv("GMX_FORCE_UPDATE"))
753         {
754             bForceUpdate = TRUE;
755         }
756
757         rerun_fr.natoms = 0;
758         if (MASTER(cr))
759         {
760             bNotLastFrame = read_first_frame(oenv, &status,
761                                              opt2fn("-rerun", nfile, fnm),
762                                              &rerun_fr, TRX_NEED_X | TRX_READ_V);
763             if (rerun_fr.natoms != top_global->natoms)
764             {
765                 gmx_fatal(FARGS,
766                           "Number of atoms in trajectory (%d) does not match the "
767                           "run input file (%d)\n",
768                           rerun_fr.natoms, top_global->natoms);
769             }
770             if (ir->ePBC != epbcNONE)
771             {
772                 if (!rerun_fr.bBox)
773                 {
774                     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);
775                 }
776                 if (max_cutoff2(ir->ePBC, rerun_fr.box) < sqr(fr->rlistlong))
777                 {
778                     gmx_fatal(FARGS, "Rerun trajectory frame step %d time %f has too small box dimensions", rerun_fr.step, rerun_fr.time);
779                 }
780             }
781         }
782
783         if (PAR(cr))
784         {
785             rerun_parallel_comm(cr, &rerun_fr, &bNotLastFrame);
786         }
787
788         if (ir->ePBC != epbcNONE)
789         {
790             /* Set the shift vectors.
791              * Necessary here when have a static box different from the tpr box.
792              */
793             calc_shifts(rerun_fr.box, fr->shift_vec);
794         }
795     }
796
797     /* loop over MD steps or if rerunMD to end of input trajectory */
798     bFirstStep = TRUE;
799     /* Skip the first Nose-Hoover integration when we get the state from tpx */
800     bStateFromTPX    = !bStateFromCP;
801     bInitStep        = bFirstStep && (bStateFromTPX || bVV);
802     bStartingFromCpt = (Flags & MD_STARTFROMCPT) && bInitStep;
803     bLastStep        = FALSE;
804     bSumEkinhOld     = FALSE;
805     bExchanged       = FALSE;
806
807     init_global_signals(&gs, cr, ir, repl_ex_nst);
808
809     step     = ir->init_step;
810     step_rel = 0;
811
812     if (ir->nstlist == -1)
813     {
814         init_nlistheuristics(&nlh, bGStatEveryStep, step);
815     }
816
817     if (MULTISIM(cr) && (repl_ex_nst <= 0 ))
818     {
819         /* check how many steps are left in other sims */
820         multisim_nsteps = get_multisim_nsteps(cr, ir->nsteps);
821     }
822
823
824     /* and stop now if we should */
825     bLastStep = (bRerunMD || (ir->nsteps >= 0 && step_rel > ir->nsteps) ||
826                  ((multisim_nsteps >= 0) && (step_rel >= multisim_nsteps )));
827     while (!bLastStep || (bRerunMD && bNotLastFrame))
828     {
829
830         wallcycle_start(wcycle, ewcSTEP);
831
832         GMX_MPE_LOG(ev_timestep1);
833
834         if (bRerunMD)
835         {
836             if (rerun_fr.bStep)
837             {
838                 step     = rerun_fr.step;
839                 step_rel = step - ir->init_step;
840             }
841             if (rerun_fr.bTime)
842             {
843                 t = rerun_fr.time;
844             }
845             else
846             {
847                 t = step;
848             }
849         }
850         else
851         {
852             bLastStep = (step_rel == ir->nsteps);
853             t         = t0 + step*ir->delta_t;
854         }
855
856         if (ir->efep != efepNO || ir->bSimTemp)
857         {
858             /* find and set the current lambdas.  If rerunning, we either read in a state, or a lambda value,
859                requiring different logic. */
860
861             set_current_lambdas(step, ir->fepvals, bRerunMD, &rerun_fr, state_global, state, lam0);
862             bDoDHDL      = do_per_step(step, ir->fepvals->nstdhdl);
863             bDoFEP       = (do_per_step(step, nstfep) && (ir->efep != efepNO));
864             bDoExpanded  = (do_per_step(step, ir->expandedvals->nstexpanded)
865                             && (ir->bExpanded) && (step > 0) && (!bStartingFromCpt));
866         }
867
868         if (bSimAnn)
869         {
870             update_annealing_target_temp(&(ir->opts), t);
871         }
872
873         if (bRerunMD)
874         {
875             if (!(DOMAINDECOMP(cr) && !MASTER(cr)))
876             {
877                 for (i = 0; i < state_global->natoms; i++)
878                 {
879                     copy_rvec(rerun_fr.x[i], state_global->x[i]);
880                 }
881                 if (rerun_fr.bV)
882                 {
883                     for (i = 0; i < state_global->natoms; i++)
884                     {
885                         copy_rvec(rerun_fr.v[i], state_global->v[i]);
886                     }
887                 }
888                 else
889                 {
890                     for (i = 0; i < state_global->natoms; i++)
891                     {
892                         clear_rvec(state_global->v[i]);
893                     }
894                     if (bRerunWarnNoV)
895                     {
896                         fprintf(stderr, "\nWARNING: Some frames do not contain velocities.\n"
897                                 "         Ekin, temperature and pressure are incorrect,\n"
898                                 "         the virial will be incorrect when constraints are present.\n"
899                                 "\n");
900                         bRerunWarnNoV = FALSE;
901                     }
902                 }
903             }
904             copy_mat(rerun_fr.box, state_global->box);
905             copy_mat(state_global->box, state->box);
906
907             if (vsite && (Flags & MD_RERUN_VSITE))
908             {
909                 if (DOMAINDECOMP(cr))
910                 {
911                     gmx_fatal(FARGS, "Vsite recalculation with -rerun is not implemented for domain decomposition, use particle decomposition");
912                 }
913                 if (graph)
914                 {
915                     /* Following is necessary because the graph may get out of sync
916                      * with the coordinates if we only have every N'th coordinate set
917                      */
918                     mk_mshift(fplog, graph, fr->ePBC, state->box, state->x);
919                     shift_self(graph, state->box, state->x);
920                 }
921                 construct_vsites(fplog, vsite, state->x, nrnb, ir->delta_t, state->v,
922                                  top->idef.iparams, top->idef.il,
923                                  fr->ePBC, fr->bMolPBC, graph, cr, state->box);
924                 if (graph)
925                 {
926                     unshift_self(graph, state->box, state->x);
927                 }
928             }
929         }
930
931         /* Stop Center of Mass motion */
932         bStopCM = (ir->comm_mode != ecmNO && do_per_step(step, ir->nstcomm));
933
934         /* Copy back starting coordinates in case we're doing a forcefield scan */
935         if (bFFscan)
936         {
937             for (ii = 0; (ii < state->natoms); ii++)
938             {
939                 copy_rvec(xcopy[ii], state->x[ii]);
940                 copy_rvec(vcopy[ii], state->v[ii]);
941             }
942             copy_mat(boxcopy, state->box);
943         }
944
945         if (bRerunMD)
946         {
947             /* for rerun MD always do Neighbour Searching */
948             bNS      = (bFirstStep || ir->nstlist != 0);
949             bNStList = bNS;
950         }
951         else
952         {
953             /* Determine whether or not to do Neighbour Searching and LR */
954             bNStList = (ir->nstlist > 0  && step % ir->nstlist == 0);
955
956             bNS = (bFirstStep || bExchanged || bNStList || bDoFEP ||
957                    (ir->nstlist == -1 && nlh.nabnsb > 0));
958
959             if (bNS && ir->nstlist == -1)
960             {
961                 set_nlistheuristics(&nlh, bFirstStep || bExchanged || bDoFEP, step);
962             }
963         }
964
965         /* check whether we should stop because another simulation has
966            stopped. */
967         if (MULTISIM(cr))
968         {
969             if ( (multisim_nsteps >= 0) &&  (step_rel >= multisim_nsteps)  &&
970                  (multisim_nsteps != ir->nsteps) )
971             {
972                 if (bNS)
973                 {
974                     if (MASTER(cr))
975                     {
976                         fprintf(stderr,
977                                 "Stopping simulation %d because another one has finished\n",
978                                 cr->ms->sim);
979                     }
980                     bLastStep         = TRUE;
981                     gs.sig[eglsCHKPT] = 1;
982                 }
983             }
984         }
985
986         /* < 0 means stop at next step, > 0 means stop at next NS step */
987         if ( (gs.set[eglsSTOPCOND] < 0) ||
988              ( (gs.set[eglsSTOPCOND] > 0) && (bNStList || ir->nstlist == 0) ) )
989         {
990             bLastStep = TRUE;
991         }
992
993         /* Determine whether or not to update the Born radii if doing GB */
994         bBornRadii = bFirstStep;
995         if (ir->implicit_solvent && (step % ir->nstgbradii == 0))
996         {
997             bBornRadii = TRUE;
998         }
999
1000         do_log     = do_per_step(step, ir->nstlog) || bFirstStep || bLastStep;
1001         do_verbose = bVerbose &&
1002             (step % stepout == 0 || bFirstStep || bLastStep);
1003
1004         if (bNS && !(bFirstStep && ir->bContinuation && !bRerunMD))
1005         {
1006             if (bRerunMD)
1007             {
1008                 bMasterState = TRUE;
1009             }
1010             else
1011             {
1012                 bMasterState = FALSE;
1013                 /* Correct the new box if it is too skewed */
1014                 if (DYNAMIC_BOX(*ir))
1015                 {
1016                     if (correct_box(fplog, step, state->box, graph))
1017                     {
1018                         bMasterState = TRUE;
1019                     }
1020                 }
1021                 if (DOMAINDECOMP(cr) && bMasterState)
1022                 {
1023                     dd_collect_state(cr->dd, state, state_global);
1024                 }
1025             }
1026
1027             if (DOMAINDECOMP(cr))
1028             {
1029                 /* Repartition the domain decomposition */
1030                 wallcycle_start(wcycle, ewcDOMDEC);
1031                 dd_partition_system(fplog, step, cr,
1032                                     bMasterState, nstglobalcomm,
1033                                     state_global, top_global, ir,
1034                                     state, &f, mdatoms, top, fr,
1035                                     vsite, shellfc, constr,
1036                                     nrnb, wcycle,
1037                                     do_verbose && !bPMETuneRunning);
1038                 wallcycle_stop(wcycle, ewcDOMDEC);
1039                 /* If using an iterative integrator, reallocate space to match the decomposition */
1040             }
1041         }
1042
1043         if (MASTER(cr) && do_log && !bFFscan)
1044         {
1045             print_ebin_header(fplog, step, t, state->lambda[efptFEP]); /* can we improve the information printed here? */
1046         }
1047
1048         if (ir->efep != efepNO)
1049         {
1050             update_mdatoms(mdatoms, state->lambda[efptMASS]);
1051         }
1052
1053         if ((bRerunMD && rerun_fr.bV) || bExchanged)
1054         {
1055
1056             /* We need the kinetic energy at minus the half step for determining
1057              * the full step kinetic energy and possibly for T-coupling.*/
1058             /* This may not be quite working correctly yet . . . . */
1059             compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
1060                             wcycle, enerd, NULL, NULL, NULL, NULL, mu_tot,
1061                             constr, NULL, FALSE, state->box,
1062                             top_global, &pcurr, top_global->natoms, &bSumEkinhOld,
1063                             CGLO_RERUNMD | CGLO_GSTAT | CGLO_TEMPERATURE);
1064         }
1065         clear_mat(force_vir);
1066
1067         /* Ionize the atoms if necessary */
1068         if (bIonize)
1069         {
1070             ionize(fplog, oenv, mdatoms, top_global, t, ir, state->x, state->v,
1071                    mdatoms->start, mdatoms->start+mdatoms->homenr, state->box, cr);
1072         }
1073
1074         /* Update force field in ffscan program */
1075         if (bFFscan)
1076         {
1077             if (update_forcefield(fplog,
1078                                   nfile, fnm, fr,
1079                                   mdatoms->nr, state->x, state->box))
1080             {
1081                 gmx_finalize_par();
1082
1083                 exit(0);
1084             }
1085         }
1086
1087         GMX_MPE_LOG(ev_timestep2);
1088
1089         /* We write a checkpoint at this MD step when:
1090          * either at an NS step when we signalled through gs,
1091          * or at the last step (but not when we do not want confout),
1092          * but never at the first step or with rerun.
1093          */
1094         bCPT = (((gs.set[eglsCHKPT] && (bNS || ir->nstlist == 0)) ||
1095                  (bLastStep && (Flags & MD_CONFOUT))) &&
1096                 step > ir->init_step && !bRerunMD);
1097         if (bCPT)
1098         {
1099             gs.set[eglsCHKPT] = 0;
1100         }
1101
1102         /* Determine the energy and pressure:
1103          * at nstcalcenergy steps and at energy output steps (set below).
1104          */
1105         if (EI_VV(ir->eI) && (!bInitStep))
1106         {
1107             /* for vv, the first half of the integration actually corresponds
1108                to the previous step.  bCalcEner is only required to be evaluated on the 'next' step,
1109                but the virial needs to be calculated on both the current step and the 'next' step. Future
1110                reorganization may be able to get rid of one of the bCalcVir=TRUE steps. */
1111
1112             bCalcEner = do_per_step(step-1, ir->nstcalcenergy);
1113             bCalcVir  = bCalcEner ||
1114                 (ir->epc != epcNO && (do_per_step(step, ir->nstpcouple) || do_per_step(step-1, ir->nstpcouple)));
1115         }
1116         else
1117         {
1118             bCalcEner = do_per_step(step, ir->nstcalcenergy);
1119             bCalcVir  = bCalcEner ||
1120                 (ir->epc != epcNO && do_per_step(step, ir->nstpcouple));
1121         }
1122
1123         /* Do we need global communication ? */
1124         bGStat = (bCalcVir || bCalcEner || bStopCM ||
1125                   do_per_step(step, nstglobalcomm) || (bVV && IR_NVT_TROTTER(ir) && do_per_step(step-1, nstglobalcomm)) ||
1126                   (ir->nstlist == -1 && !bRerunMD && step >= nlh.step_nscheck));
1127
1128         do_ene = (do_per_step(step, ir->nstenergy) || bLastStep);
1129
1130         if (do_ene || do_log)
1131         {
1132             bCalcVir  = TRUE;
1133             bCalcEner = TRUE;
1134             bGStat    = TRUE;
1135         }
1136
1137         /* these CGLO_ options remain the same throughout the iteration */
1138         cglo_flags = ((bRerunMD ? CGLO_RERUNMD : 0) |
1139                       (bGStat ? CGLO_GSTAT : 0)
1140                       );
1141
1142         force_flags = (GMX_FORCE_STATECHANGED |
1143                        ((DYNAMIC_BOX(*ir) || bRerunMD) ? GMX_FORCE_DYNAMICBOX : 0) |
1144                        GMX_FORCE_ALLFORCES |
1145                        GMX_FORCE_SEPLRF |
1146                        (bCalcVir ? GMX_FORCE_VIRIAL : 0) |
1147                        (bCalcEner ? GMX_FORCE_ENERGY : 0) |
1148                        (bDoFEP ? GMX_FORCE_DHDL : 0)
1149                        );
1150
1151         if (fr->bTwinRange)
1152         {
1153             if (do_per_step(step, ir->nstcalclr))
1154             {
1155                 force_flags |= GMX_FORCE_DO_LR;
1156             }
1157         }
1158
1159         if (shellfc)
1160         {
1161             /* Now is the time to relax the shells */
1162             count = relax_shell_flexcon(fplog, cr, bVerbose, bFFscan ? step+1 : step,
1163                                         ir, bNS, force_flags,
1164                                         bStopCM, top, top_global,
1165                                         constr, enerd, fcd,
1166                                         state, f, force_vir, mdatoms,
1167                                         nrnb, wcycle, graph, groups,
1168                                         shellfc, fr, bBornRadii, t, mu_tot,
1169                                         state->natoms, &bConverged, vsite,
1170                                         outf->fp_field);
1171             tcount += count;
1172
1173             if (bConverged)
1174             {
1175                 nconverged++;
1176             }
1177         }
1178         else
1179         {
1180             /* The coordinates (x) are shifted (to get whole molecules)
1181              * in do_force.
1182              * This is parallellized as well, and does communication too.
1183              * Check comments in sim_util.c
1184              */
1185             do_force(fplog, cr, ir, step, nrnb, wcycle, top, top_global, groups,
1186                      state->box, state->x, &state->hist,
1187                      f, force_vir, mdatoms, enerd, fcd,
1188                      state->lambda, graph,
1189                      fr, vsite, mu_tot, t, outf->fp_field, ed, bBornRadii,
1190                      (bNS ? GMX_FORCE_NS : 0) | force_flags);
1191         }
1192
1193         GMX_BARRIER(cr->mpi_comm_mygroup);
1194
1195         if (bTCR)
1196         {
1197             mu_aver = calc_mu_aver(cr, state->x, mdatoms->chargeA,
1198                                    mu_tot, &top_global->mols, mdatoms, gnx, grpindex);
1199         }
1200
1201         if (bTCR && bFirstStep)
1202         {
1203             tcr = init_coupling(fplog, nfile, fnm, cr, fr, mdatoms, &(top->idef));
1204             fprintf(fplog, "Done init_coupling\n");
1205             fflush(fplog);
1206         }
1207
1208         if (bVV && !bStartingFromCpt && !bRerunMD)
1209         /*  ############### START FIRST UPDATE HALF-STEP FOR VV METHODS############### */
1210         {
1211             if (ir->eI == eiVV && bInitStep)
1212             {
1213                 /* if using velocity verlet with full time step Ekin,
1214                  * take the first half step only to compute the
1215                  * virial for the first step. From there,
1216                  * revert back to the initial coordinates
1217                  * so that the input is actually the initial step.
1218                  */
1219                 copy_rvecn(state->v, cbuf, 0, state->natoms); /* should make this better for parallelizing? */
1220             }
1221             else
1222             {
1223                 /* this is for NHC in the Ekin(t+dt/2) version of vv */
1224                 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ1);
1225             }
1226
1227             /* If we are using twin-range interactions where the long-range component
1228              * is only evaluated every nstcalclr>1 steps, we should do a special update
1229              * step to combine the long-range forces on these steps.
1230              * For nstcalclr=1 this is not done, since the forces would have been added
1231              * directly to the short-range forces already.
1232              *
1233              * TODO Remove various aspects of VV+twin-range in master
1234              * branch, because VV integrators did not ever support
1235              * twin-range multiple time stepping with constraints.
1236              */
1237             bUpdateDoLR = (fr->bTwinRange && do_per_step(step, ir->nstcalclr));
1238
1239             update_coords(fplog, step, ir, mdatoms, state, fr->bMolPBC,
1240                           f, bUpdateDoLR, fr->f_twin, bCalcVir ? &fr->vir_twin_constr : NULL, fcd,
1241                           ekind, M, wcycle, upd, bInitStep, etrtVELOCITY1,
1242                           cr, nrnb, constr, &top->idef);
1243
1244             if (bIterativeCase && do_per_step(step-1, ir->nstpcouple) && !bInitStep)
1245             {
1246                 gmx_iterate_init(&iterate, TRUE);
1247             }
1248             /* for iterations, we save these vectors, as we will be self-consistently iterating
1249                the calculations */
1250
1251             /*#### UPDATE EXTENDED VARIABLES IN TROTTER FORMULATION */
1252
1253             /* save the state */
1254             if (iterate.bIterationActive)
1255             {
1256                 copy_coupling_state(state, bufstate, ekind, ekind_save, &(ir->opts));
1257             }
1258
1259             bFirstIterate = TRUE;
1260             while (bFirstIterate || iterate.bIterationActive)
1261             {
1262                 if (iterate.bIterationActive)
1263                 {
1264                     copy_coupling_state(bufstate, state, ekind_save, ekind, &(ir->opts));
1265                     if (bFirstIterate && bTrotter)
1266                     {
1267                         /* The first time through, we need a decent first estimate
1268                            of veta(t+dt) to compute the constraints.  Do
1269                            this by computing the box volume part of the
1270                            trotter integration at this time. Nothing else
1271                            should be changed by this routine here.  If
1272                            !(first time), we start with the previous value
1273                            of veta.  */
1274
1275                         veta_save = state->veta;
1276                         trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ0);
1277                         vetanew     = state->veta;
1278                         state->veta = veta_save;
1279                     }
1280                 }
1281
1282                 bOK = TRUE;
1283                 if (!bRerunMD || rerun_fr.bV || bForceUpdate)     /* Why is rerun_fr.bV here?  Unclear. */
1284                 {
1285                     update_constraints(fplog, step, NULL, ir, ekind, mdatoms,
1286                                        state, fr->bMolPBC, graph, f,
1287                                        &top->idef, shake_vir, NULL,
1288                                        cr, nrnb, wcycle, upd, constr,
1289                                        bInitStep, TRUE, bCalcVir, vetanew);
1290
1291                     if (bCalcVir && bUpdateDoLR && ir->nstcalclr > 1)
1292                     {
1293                         /* Correct the virial for multiple time stepping */
1294                         m_sub(shake_vir, fr->vir_twin_constr, shake_vir);
1295                     }
1296
1297                     if (!bOK && !bFFscan)
1298                     {
1299                         gmx_fatal(FARGS, "Constraint error: Shake, Lincs or Settle could not solve the constrains");
1300                     }
1301
1302                 }
1303                 else if (graph)
1304                 {
1305                     /* Need to unshift here if a do_force has been
1306                        called in the previous step */
1307                     unshift_self(graph, state->box, state->x);
1308                 }
1309
1310                 /* if VV, compute the pressure and constraints */
1311                 /* For VV2, we strictly only need this if using pressure
1312                  * control, but we really would like to have accurate pressures
1313                  * printed out.
1314                  * Think about ways around this in the future?
1315                  * For now, keep this choice in comments.
1316                  */
1317                 /*bPres = (ir->eI==eiVV || IR_NPT_TROTTER(ir)); */
1318                 /*bTemp = ((ir->eI==eiVV &&(!bInitStep)) || (ir->eI==eiVVAK && IR_NPT_TROTTER(ir)));*/
1319                 bPres = TRUE;
1320                 bTemp = ((ir->eI == eiVV && (!bInitStep)) || (ir->eI == eiVVAK));
1321                 if (bCalcEner && ir->eI == eiVVAK)  /*MRS:  7/9/2010 -- this still doesn't fix it?*/
1322                 {
1323                     bSumEkinhOld = TRUE;
1324                 }
1325                 /* for vv, the first half of the integration actually corresponds to the previous step.
1326                    So we need information from the last step in the first half of the integration */
1327                 if (bGStat || do_per_step(step-1, nstglobalcomm))
1328                 {
1329                     compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
1330                                     wcycle, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
1331                                     constr, NULL, FALSE, state->box,
1332                                     top_global, &pcurr, top_global->natoms, &bSumEkinhOld,
1333                                     cglo_flags
1334                                     | CGLO_ENERGY
1335                                     | (bTemp ? CGLO_TEMPERATURE : 0)
1336                                     | (bPres ? CGLO_PRESSURE : 0)
1337                                     | (bPres ? CGLO_CONSTRAINT : 0)
1338                                     | ((iterate.bIterationActive) ? CGLO_ITERATE : 0)
1339                                     | (bFirstIterate ? CGLO_FIRSTITERATE : 0)
1340                                     | CGLO_SCALEEKIN
1341                                     );
1342                     /* explanation of above:
1343                        a) We compute Ekin at the full time step
1344                        if 1) we are using the AveVel Ekin, and it's not the
1345                        initial step, or 2) if we are using AveEkin, but need the full
1346                        time step kinetic energy for the pressure (always true now, since we want accurate statistics).
1347                        b) If we are using EkinAveEkin for the kinetic energy for the temperature control, we still feed in
1348                        EkinAveVel because it's needed for the pressure */
1349                 }
1350                 /* temperature scaling and pressure scaling to produce the extended variables at t+dt */
1351                 if (!bInitStep)
1352                 {
1353                     if (bTrotter)
1354                     {
1355                         m_add(force_vir, shake_vir, total_vir); /* we need the un-dispersion corrected total vir here */
1356                         trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ2);
1357                     }
1358                     else
1359                     {
1360                         if (bExchanged)
1361                         {
1362
1363                             /* We need the kinetic energy at minus the half step for determining
1364                              * the full step kinetic energy and possibly for T-coupling.*/
1365                             /* This may not be quite working correctly yet . . . . */
1366                             compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
1367                                             wcycle, enerd, NULL, NULL, NULL, NULL, mu_tot,
1368                                             constr, NULL, FALSE, state->box,
1369                                             top_global, &pcurr, top_global->natoms, &bSumEkinhOld,
1370                                             CGLO_RERUNMD | CGLO_GSTAT | CGLO_TEMPERATURE);
1371                         }
1372                     }
1373                 }
1374
1375                 if (iterate.bIterationActive &&
1376                     done_iterating(cr, fplog, step, &iterate, bFirstIterate,
1377                                    state->veta, &vetanew))
1378                 {
1379                     break;
1380                 }
1381                 bFirstIterate = FALSE;
1382             }
1383
1384             if (bTrotter && !bInitStep)
1385             {
1386                 copy_mat(shake_vir, state->svir_prev);
1387                 copy_mat(force_vir, state->fvir_prev);
1388                 if (IR_NVT_TROTTER(ir) && ir->eI == eiVV)
1389                 {
1390                     /* update temperature and kinetic energy now that step is over - this is the v(t+dt) point */
1391                     enerd->term[F_TEMP] = sum_ekin(&(ir->opts), ekind, NULL, (ir->eI == eiVV), FALSE, FALSE);
1392                     enerd->term[F_EKIN] = trace(ekind->ekin);
1393                 }
1394             }
1395             /* if it's the initial step, we performed this first step just to get the constraint virial */
1396             if (bInitStep && ir->eI == eiVV)
1397             {
1398                 copy_rvecn(cbuf, state->v, 0, state->natoms);
1399             }
1400
1401             GMX_MPE_LOG(ev_timestep1);
1402         }
1403
1404         /* MRS -- now done iterating -- compute the conserved quantity */
1405         if (bVV)
1406         {
1407             saved_conserved_quantity = compute_conserved_from_auxiliary(ir, state, &MassQ);
1408             if (ir->eI == eiVV)
1409             {
1410                 last_ekin = enerd->term[F_EKIN];
1411             }
1412             if ((ir->eDispCorr != edispcEnerPres) && (ir->eDispCorr != edispcAllEnerPres))
1413             {
1414                 saved_conserved_quantity -= enerd->term[F_DISPCORR];
1415             }
1416             /* sum up the foreign energy and dhdl terms for vv.  currently done every step so that dhdl is correct in the .edr */
1417             if (!bRerunMD)
1418             {
1419                 sum_dhdl(enerd, state->lambda, ir->fepvals);
1420             }
1421         }
1422
1423         /* ########  END FIRST UPDATE STEP  ############## */
1424         /* ########  If doing VV, we now have v(dt) ###### */
1425         if (bDoExpanded)
1426         {
1427             /* perform extended ensemble sampling in lambda - we don't
1428                actually move to the new state before outputting
1429                statistics, but if performing simulated tempering, we
1430                do update the velocities and the tau_t. */
1431
1432             lamnew = ExpandedEnsembleDynamics(fplog, ir, enerd, state, &MassQ, state->fep_state, &state->dfhist, step, mcrng, state->v, mdatoms);
1433             /* history is maintained in state->dfhist, but state_global is what is sent to trajectory and log output */
1434             copy_df_history(&state_global->dfhist,&state->dfhist);
1435         }
1436         /* ################## START TRAJECTORY OUTPUT ################# */
1437
1438         /* Now we have the energies and forces corresponding to the
1439          * coordinates at time t. We must output all of this before
1440          * the update.
1441          * for RerunMD t is read from input trajectory
1442          */
1443         GMX_MPE_LOG(ev_output_start);
1444
1445         mdof_flags = 0;
1446         if (do_per_step(step, ir->nstxout))
1447         {
1448             mdof_flags |= MDOF_X;
1449         }
1450         if (do_per_step(step, ir->nstvout))
1451         {
1452             mdof_flags |= MDOF_V;
1453         }
1454         if (do_per_step(step, ir->nstfout))
1455         {
1456             mdof_flags |= MDOF_F;
1457         }
1458         if (do_per_step(step, ir->nstxtcout))
1459         {
1460             mdof_flags |= MDOF_XTC;
1461         }
1462         if (bCPT)
1463         {
1464             mdof_flags |= MDOF_CPT;
1465         }
1466         ;
1467
1468 #if defined(GMX_FAHCORE) || defined(GMX_WRITELASTSTEP)
1469         if (bLastStep)
1470         {
1471             /* Enforce writing positions and velocities at end of run */
1472             mdof_flags |= (MDOF_X | MDOF_V);
1473         }
1474 #endif
1475 #ifdef GMX_FAHCORE
1476         if (MASTER(cr))
1477         {
1478             fcReportProgress( ir->nsteps, step );
1479         }
1480
1481 #if defined(__native_client__)
1482         fcCheckin(MASTER(cr));
1483 #endif
1484
1485         /* sync bCPT and fc record-keeping */
1486         if (bCPT && MASTER(cr))
1487         {
1488             fcRequestCheckPoint();
1489         }
1490 #endif
1491
1492         if (mdof_flags != 0)
1493         {
1494             wallcycle_start(wcycle, ewcTRAJ);
1495             if (bCPT)
1496             {
1497                 if (state->flags & (1<<estLD_RNG))
1498                 {
1499                     get_stochd_state(upd, state);
1500                 }
1501                 if (state->flags  & (1<<estMC_RNG))
1502                 {
1503                     get_mc_state(mcrng, state);
1504                 }
1505                 if (MASTER(cr))
1506                 {
1507                     if (bSumEkinhOld)
1508                     {
1509                         state_global->ekinstate.bUpToDate = FALSE;
1510                     }
1511                     else
1512                     {
1513                         update_ekinstate(&state_global->ekinstate, ekind);
1514                         state_global->ekinstate.bUpToDate = TRUE;
1515                     }
1516                     update_energyhistory(&state_global->enerhist, mdebin);
1517                 }
1518             }
1519             write_traj(fplog, cr, outf, mdof_flags, top_global,
1520                        step, t, state, state_global, f, f_global, &n_xtc, &x_xtc);
1521             if (bCPT)
1522             {
1523                 nchkpt++;
1524                 bCPT = FALSE;
1525             }
1526             debug_gmx();
1527             if (bLastStep && step_rel == ir->nsteps &&
1528                 (Flags & MD_CONFOUT) && MASTER(cr) &&
1529                 !bRerunMD && !bFFscan)
1530             {
1531                 /* x and v have been collected in write_traj,
1532                  * because a checkpoint file will always be written
1533                  * at the last step.
1534                  */
1535                 fprintf(stderr, "\nWriting final coordinates.\n");
1536                 if (fr->bMolPBC)
1537                 {
1538                     /* Make molecules whole only for confout writing */
1539                     do_pbc_mtop(fplog, ir->ePBC, state->box, top_global, state_global->x);
1540                 }
1541                 write_sto_conf_mtop(ftp2fn(efSTO, nfile, fnm),
1542                                     *top_global->name, top_global,
1543                                     state_global->x, state_global->v,
1544                                     ir->ePBC, state->box);
1545                 debug_gmx();
1546             }
1547             wallcycle_stop(wcycle, ewcTRAJ);
1548         }
1549         GMX_MPE_LOG(ev_output_finish);
1550
1551         /* kludge -- virial is lost with restart for NPT control. Must restart */
1552         if (bStartingFromCpt && bVV)
1553         {
1554             copy_mat(state->svir_prev, shake_vir);
1555             copy_mat(state->fvir_prev, force_vir);
1556         }
1557         /*  ################## END TRAJECTORY OUTPUT ################ */
1558
1559         /* Determine the wallclock run time up till now */
1560         run_time = gmx_gettime() - (double)runtime->real;
1561
1562         /* Check whether everything is still allright */
1563         if (((int)gmx_get_stop_condition() > handled_stop_condition)
1564 #ifdef GMX_THREAD_MPI
1565             && MASTER(cr)
1566 #endif
1567             )
1568         {
1569             /* this is just make gs.sig compatible with the hack
1570                of sending signals around by MPI_Reduce with together with
1571                other floats */
1572             if (gmx_get_stop_condition() == gmx_stop_cond_next_ns)
1573             {
1574                 gs.sig[eglsSTOPCOND] = 1;
1575             }
1576             if (gmx_get_stop_condition() == gmx_stop_cond_next)
1577             {
1578                 gs.sig[eglsSTOPCOND] = -1;
1579             }
1580             /* < 0 means stop at next step, > 0 means stop at next NS step */
1581             if (fplog)
1582             {
1583                 fprintf(fplog,
1584                         "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
1585                         gmx_get_signal_name(),
1586                         gs.sig[eglsSTOPCOND] == 1 ? "NS " : "");
1587                 fflush(fplog);
1588             }
1589             fprintf(stderr,
1590                     "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
1591                     gmx_get_signal_name(),
1592                     gs.sig[eglsSTOPCOND] == 1 ? "NS " : "");
1593             fflush(stderr);
1594             handled_stop_condition = (int)gmx_get_stop_condition();
1595         }
1596         else if (MASTER(cr) && (bNS || ir->nstlist <= 0) &&
1597                  (max_hours > 0 && run_time > max_hours*60.0*60.0*0.99) &&
1598                  gs.sig[eglsSTOPCOND] == 0 && gs.set[eglsSTOPCOND] == 0)
1599         {
1600             /* Signal to terminate the run */
1601             gs.sig[eglsSTOPCOND] = 1;
1602             if (fplog)
1603             {
1604                 fprintf(fplog, "\nStep %s: Run time exceeded %.3f hours, will terminate the run\n", gmx_step_str(step, sbuf), max_hours*0.99);
1605             }
1606             fprintf(stderr, "\nStep %s: Run time exceeded %.3f hours, will terminate the run\n", gmx_step_str(step, sbuf), max_hours*0.99);
1607         }
1608
1609         if (bResetCountersHalfMaxH && MASTER(cr) &&
1610             run_time > max_hours*60.0*60.0*0.495)
1611         {
1612             gs.sig[eglsRESETCOUNTERS] = 1;
1613         }
1614
1615         if (ir->nstlist == -1 && !bRerunMD)
1616         {
1617             /* When bGStatEveryStep=FALSE, global_stat is only called
1618              * when we check the atom displacements, not at NS steps.
1619              * This means that also the bonded interaction count check is not
1620              * performed immediately after NS. Therefore a few MD steps could
1621              * be performed with missing interactions.
1622              * But wrong energies are never written to file,
1623              * since energies are only written after global_stat
1624              * has been called.
1625              */
1626             if (step >= nlh.step_nscheck)
1627             {
1628                 nlh.nabnsb = natoms_beyond_ns_buffer(ir, fr, &top->cgs,
1629                                                      nlh.scale_tot, state->x);
1630             }
1631             else
1632             {
1633                 /* This is not necessarily true,
1634                  * but step_nscheck is determined quite conservatively.
1635                  */
1636                 nlh.nabnsb = 0;
1637             }
1638         }
1639
1640         /* In parallel we only have to check for checkpointing in steps
1641          * where we do global communication,
1642          *  otherwise the other nodes don't know.
1643          */
1644         if (MASTER(cr) && ((bGStat || !PAR(cr)) &&
1645                            cpt_period >= 0 &&
1646                            (cpt_period == 0 ||
1647                             run_time >= nchkpt*cpt_period*60.0)) &&
1648             gs.set[eglsCHKPT] == 0)
1649         {
1650             gs.sig[eglsCHKPT] = 1;
1651         }
1652
1653         /* at the start of step, randomize or scale the velocities (trotter done elsewhere) */
1654         if (EI_VV(ir->eI))
1655         {
1656             if (!bInitStep)
1657             {
1658                 update_tcouple(fplog, step, ir, state, ekind, wcycle, upd, &MassQ, mdatoms);
1659             }
1660             if (ETC_ANDERSEN(ir->etc)) /* keep this outside of update_tcouple because of the extra info required to pass */
1661             {
1662                 gmx_bool bIfRandomize;
1663                 bIfRandomize = update_randomize_velocities(ir, step, mdatoms, state, upd, &top->idef, constr, DOMAINDECOMP(cr));
1664                 /* if we have constraints, we have to remove the kinetic energy parallel to the bonds */
1665                 if (constr && bIfRandomize)
1666                 {
1667                     update_constraints(fplog, step, NULL, ir, ekind, mdatoms,
1668                                        state, fr->bMolPBC, graph, f,
1669                                        &top->idef, tmp_vir, NULL,
1670                                        cr, nrnb, wcycle, upd, constr,
1671                                        bInitStep, TRUE, bCalcVir, vetanew);
1672                 }
1673             }
1674         }
1675
1676         if (bIterativeCase && do_per_step(step, ir->nstpcouple))
1677         {
1678             gmx_iterate_init(&iterate, TRUE);
1679             /* for iterations, we save these vectors, as we will be redoing the calculations */
1680             copy_coupling_state(state, bufstate, ekind, ekind_save, &(ir->opts));
1681         }
1682
1683         bFirstIterate = TRUE;
1684         while (bFirstIterate || iterate.bIterationActive)
1685         {
1686             /* We now restore these vectors to redo the calculation with improved extended variables */
1687             if (iterate.bIterationActive)
1688             {
1689                 copy_coupling_state(bufstate, state, ekind_save, ekind, &(ir->opts));
1690             }
1691
1692             /* We make the decision to break or not -after- the calculation of Ekin and Pressure,
1693                so scroll down for that logic */
1694
1695             /* #########   START SECOND UPDATE STEP ################# */
1696             GMX_MPE_LOG(ev_update_start);
1697             /* Box is changed in update() when we do pressure coupling,
1698              * but we should still use the old box for energy corrections and when
1699              * writing it to the energy file, so it matches the trajectory files for
1700              * the same timestep above. Make a copy in a separate array.
1701              */
1702             copy_mat(state->box, lastbox);
1703
1704             bOK = TRUE;
1705             dvdl_constr = 0;
1706
1707             if (!(bRerunMD && !rerun_fr.bV && !bForceUpdate))
1708             {
1709                 wallcycle_start(wcycle, ewcUPDATE);
1710                 /* UPDATE PRESSURE VARIABLES IN TROTTER FORMULATION WITH CONSTRAINTS */
1711                 if (bTrotter)
1712                 {
1713                     if (iterate.bIterationActive)
1714                     {
1715                         if (bFirstIterate)
1716                         {
1717                             scalevir = 1;
1718                         }
1719                         else
1720                         {
1721                             /* we use a new value of scalevir to converge the iterations faster */
1722                             scalevir = tracevir/trace(shake_vir);
1723                         }
1724                         msmul(shake_vir, scalevir, shake_vir);
1725                         m_add(force_vir, shake_vir, total_vir);
1726                         clear_mat(shake_vir);
1727                     }
1728                     trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ3);
1729                     /* We can only do Berendsen coupling after we have summed
1730                      * the kinetic energy or virial. Since the happens
1731                      * in global_state after update, we should only do it at
1732                      * step % nstlist = 1 with bGStatEveryStep=FALSE.
1733                      */
1734                 }
1735                 else
1736                 {
1737                     update_tcouple(fplog, step, ir, state, ekind, wcycle, upd, &MassQ, mdatoms);
1738                     update_pcouple(fplog, step, ir, state, pcoupl_mu, M, wcycle,
1739                                    upd, bInitStep);
1740                 }
1741
1742                 if (bVV)
1743                 {
1744                     bUpdateDoLR = (fr->bTwinRange && do_per_step(step, ir->nstcalclr));
1745
1746                     /* velocity half-step update */
1747                     update_coords(fplog, step, ir, mdatoms, state, fr->bMolPBC, f,
1748                                   bUpdateDoLR, fr->f_twin, bCalcVir ? &fr->vir_twin_constr : NULL, fcd,
1749                                   ekind, M, wcycle, upd, FALSE, etrtVELOCITY2,
1750                                   cr, nrnb, constr, &top->idef);
1751                 }
1752
1753                 /* Above, initialize just copies ekinh into ekin,
1754                  * it doesn't copy position (for VV),
1755                  * and entire integrator for MD.
1756                  */
1757
1758                 if (ir->eI == eiVVAK)
1759                 {
1760                     copy_rvecn(state->x, cbuf, 0, state->natoms);
1761                 }
1762                 bUpdateDoLR = (fr->bTwinRange && do_per_step(step, ir->nstcalclr));
1763
1764                 update_coords(fplog, step, ir, mdatoms, state, fr->bMolPBC, f,
1765                               bUpdateDoLR, fr->f_twin, bCalcVir ? &fr->vir_twin_constr : NULL, fcd,
1766                               ekind, M, wcycle, upd, bInitStep, etrtPOSITION, cr, nrnb, constr, &top->idef);
1767                 wallcycle_stop(wcycle, ewcUPDATE);
1768
1769                 update_constraints(fplog, step, &dvdl_constr, ir, ekind, mdatoms, state,
1770                                    fr->bMolPBC, graph, f,
1771                                    &top->idef, shake_vir, force_vir,
1772                                    cr, nrnb, wcycle, upd, constr,
1773                                    bInitStep, FALSE, bCalcVir, state->veta);
1774
1775                 if (bCalcVir && bUpdateDoLR && ir->nstcalclr > 1)
1776                 {
1777                     /* Correct the virial for multiple time stepping */
1778                     m_sub(shake_vir, fr->vir_twin_constr, shake_vir);
1779                 }
1780
1781                 if (ir->eI == eiVVAK)
1782                 {
1783                     /* erase F_EKIN and F_TEMP here? */
1784                     /* just compute the kinetic energy at the half step to perform a trotter step */
1785                     compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
1786                                     wcycle, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
1787                                     constr, NULL, FALSE, lastbox,
1788                                     top_global, &pcurr, top_global->natoms, &bSumEkinhOld,
1789                                     cglo_flags | CGLO_TEMPERATURE
1790                                     );
1791                     wallcycle_start(wcycle, ewcUPDATE);
1792                     trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ4);
1793                     /* now we know the scaling, we can compute the positions again again */
1794                     copy_rvecn(cbuf, state->x, 0, state->natoms);
1795
1796                     bUpdateDoLR = (fr->bTwinRange && do_per_step(step, ir->nstcalclr));
1797
1798                     update_coords(fplog, step, ir, mdatoms, state, fr->bMolPBC, f,
1799                                   bUpdateDoLR, fr->f_twin, bCalcVir ? &fr->vir_twin_constr : NULL, fcd,
1800                                   ekind, M, wcycle, upd, bInitStep, etrtPOSITION, cr, nrnb, constr, &top->idef);
1801                     wallcycle_stop(wcycle, ewcUPDATE);
1802
1803                     /* do we need an extra constraint here? just need to copy out of state->v to upd->xp? */
1804                     /* are the small terms in the shake_vir here due
1805                      * to numerical errors, or are they important
1806                      * physically? I'm thinking they are just errors, but not completely sure.
1807                      * For now, will call without actually constraining, constr=NULL*/
1808                     update_constraints(fplog, step, NULL, ir, ekind, mdatoms,
1809                                        state, fr->bMolPBC, graph, f,
1810                                        &top->idef, tmp_vir, force_vir,
1811                                        cr, nrnb, wcycle, upd, NULL,
1812                                        bInitStep, FALSE, bCalcVir,
1813                                        state->veta);
1814                 }
1815                 if (!bOK && !bFFscan)
1816                 {
1817                     gmx_fatal(FARGS, "Constraint error: Shake, Lincs or Settle could not solve the constrains");
1818                 }
1819
1820                 if (fr->bSepDVDL && fplog && do_log)
1821                 {
1822                     fprintf(fplog, sepdvdlformat, "Constraint dV/dl", 0.0, dvdl_constr);
1823                 }
1824                 if (bVV)
1825                 {
1826                     /* this factor or 2 correction is necessary
1827                        because half of the constraint force is removed
1828                        in the vv step, so we have to double it.  See
1829                        the Redmine issue #1255.  It is not yet clear
1830                        if the factor of 2 is exact, or just a very
1831                        good approximation, and this will be
1832                        investigated.  The next step is to see if this
1833                        can be done adding a dhdl contribution from the
1834                        rattle step, but this is somewhat more
1835                        complicated with the current code. Will be
1836                        investigated, hopefully for 4.6.3. However,
1837                        this current solution is much better than
1838                        having it completely wrong.
1839                     */
1840                     enerd->term[F_DVDL_CONSTR] += 2*dvdl_constr;
1841                 }
1842                 else
1843                 {
1844                     enerd->term[F_DVDL_CONSTR] += dvdl_constr;
1845                 }
1846             }
1847             else if (graph)
1848             {
1849                 /* Need to unshift here */
1850                 unshift_self(graph, state->box, state->x);
1851             }
1852
1853             GMX_BARRIER(cr->mpi_comm_mygroup);
1854             GMX_MPE_LOG(ev_update_finish);
1855
1856             if (vsite != NULL)
1857             {
1858                 wallcycle_start(wcycle, ewcVSITECONSTR);
1859                 if (graph != NULL)
1860                 {
1861                     shift_self(graph, state->box, state->x);
1862                 }
1863                 construct_vsites(fplog, vsite, state->x, nrnb, ir->delta_t, state->v,
1864                                  top->idef.iparams, top->idef.il,
1865                                  fr->ePBC, fr->bMolPBC, graph, cr, state->box);
1866
1867                 if (graph != NULL)
1868                 {
1869                     unshift_self(graph, state->box, state->x);
1870                 }
1871                 wallcycle_stop(wcycle, ewcVSITECONSTR);
1872             }
1873
1874             /* ############## IF NOT VV, Calculate globals HERE, also iterate constraints  ############ */
1875             /* With Leap-Frog we can skip compute_globals at
1876              * non-communication steps, but we need to calculate
1877              * the kinetic energy one step before communication.
1878              */
1879             if (bGStat || (!EI_VV(ir->eI) && do_per_step(step+1, nstglobalcomm)))
1880             {
1881                 if (ir->nstlist == -1 && bFirstIterate)
1882                 {
1883                     gs.sig[eglsNABNSB] = nlh.nabnsb;
1884                 }
1885                 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
1886                                 wcycle, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
1887                                 constr,
1888                                 bFirstIterate ? &gs : NULL,
1889                                 (step_rel % gs.nstms == 0) &&
1890                                 (multisim_nsteps < 0 || (step_rel < multisim_nsteps)),
1891                                 lastbox,
1892                                 top_global, &pcurr, top_global->natoms, &bSumEkinhOld,
1893                                 cglo_flags
1894                                 | (!EI_VV(ir->eI) || bRerunMD ? CGLO_ENERGY : 0)
1895                                 | (!EI_VV(ir->eI) && bStopCM ? CGLO_STOPCM : 0)
1896                                 | (!EI_VV(ir->eI) ? CGLO_TEMPERATURE : 0)
1897                                 | (!EI_VV(ir->eI) || bRerunMD ? CGLO_PRESSURE : 0)
1898                                 | (iterate.bIterationActive ? CGLO_ITERATE : 0)
1899                                 | (bFirstIterate ? CGLO_FIRSTITERATE : 0)
1900                                 | CGLO_CONSTRAINT
1901                                 );
1902                 if (ir->nstlist == -1 && bFirstIterate)
1903                 {
1904                     nlh.nabnsb         = gs.set[eglsNABNSB];
1905                     gs.set[eglsNABNSB] = 0;
1906                 }
1907             }
1908             /* bIterate is set to keep it from eliminating the old ekin kinetic energy terms */
1909             /* #############  END CALC EKIN AND PRESSURE ################# */
1910
1911             /* Note: this is OK, but there are some numerical precision issues with using the convergence of
1912                the virial that should probably be addressed eventually. state->veta has better properies,
1913                but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could
1914                generate the new shake_vir, but test the veta value for convergence.  This will take some thought. */
1915
1916             if (iterate.bIterationActive &&
1917                 done_iterating(cr, fplog, step, &iterate, bFirstIterate,
1918                                trace(shake_vir), &tracevir))
1919             {
1920                 break;
1921             }
1922             bFirstIterate = FALSE;
1923         }
1924
1925         if (!bVV || bRerunMD)
1926         {
1927             /* sum up the foreign energy and dhdl terms for md and sd. currently done every step so that dhdl is correct in the .edr */
1928             sum_dhdl(enerd, state->lambda, ir->fepvals);
1929         }
1930         update_box(fplog, step, ir, mdatoms, state, graph, f,
1931                    ir->nstlist == -1 ? &nlh.scale_tot : NULL, pcoupl_mu, nrnb, wcycle, upd, bInitStep, FALSE);
1932
1933         /* ################# END UPDATE STEP 2 ################# */
1934         /* #### We now have r(t+dt) and v(t+dt/2)  ############# */
1935
1936         /* The coordinates (x) were unshifted in update */
1937         if (bFFscan && (shellfc == NULL || bConverged))
1938         {
1939             if (print_forcefield(fplog, enerd->term, mdatoms->homenr,
1940                                  f, NULL, xcopy,
1941                                  &(top_global->mols), mdatoms->massT, pres))
1942             {
1943                 gmx_finalize_par();
1944
1945                 fprintf(stderr, "\n");
1946                 exit(0);
1947             }
1948         }
1949         if (!bGStat)
1950         {
1951             /* We will not sum ekinh_old,
1952              * so signal that we still have to do it.
1953              */
1954             bSumEkinhOld = TRUE;
1955         }
1956
1957         if (bTCR)
1958         {
1959             /* Only do GCT when the relaxation of shells (minimization) has converged,
1960              * otherwise we might be coupling to bogus energies.
1961              * In parallel we must always do this, because the other sims might
1962              * update the FF.
1963              */
1964
1965             /* Since this is called with the new coordinates state->x, I assume
1966              * we want the new box state->box too. / EL 20040121
1967              */
1968             do_coupling(fplog, oenv, nfile, fnm, tcr, t, step, enerd->term, fr,
1969                         ir, MASTER(cr),
1970                         mdatoms, &(top->idef), mu_aver,
1971                         top_global->mols.nr, cr,
1972                         state->box, total_vir, pres,
1973                         mu_tot, state->x, f, bConverged);
1974             debug_gmx();
1975         }
1976
1977         /* #########  BEGIN PREPARING EDR OUTPUT  ###########  */
1978
1979         /* use the directly determined last velocity, not actually the averaged half steps */
1980         if (bTrotter && ir->eI == eiVV)
1981         {
1982             enerd->term[F_EKIN] = last_ekin;
1983         }
1984         enerd->term[F_ETOT] = enerd->term[F_EPOT] + enerd->term[F_EKIN];
1985
1986         if (bVV)
1987         {
1988             enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + saved_conserved_quantity;
1989         }
1990         else
1991         {
1992             enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + compute_conserved_from_auxiliary(ir, state, &MassQ);
1993         }
1994         /* Check for excessively large energies */
1995         if (bIonize)
1996         {
1997 #ifdef GMX_DOUBLE
1998             real etot_max = 1e200;
1999 #else
2000             real etot_max = 1e30;
2001 #endif
2002             if (fabs(enerd->term[F_ETOT]) > etot_max)
2003             {
2004                 fprintf(stderr, "Energy too large (%g), giving up\n",
2005                         enerd->term[F_ETOT]);
2006             }
2007         }
2008         /* #########  END PREPARING EDR OUTPUT  ###########  */
2009
2010         /* Time for performance */
2011         if (((step % stepout) == 0) || bLastStep)
2012         {
2013             runtime_upd_proc(runtime);
2014         }
2015
2016         /* Output stuff */
2017         if (MASTER(cr))
2018         {
2019             gmx_bool do_dr, do_or;
2020
2021             if (fplog && do_log && bDoExpanded)
2022             {
2023                 /* only needed if doing expanded ensemble */
2024                 PrintFreeEnergyInfoToFile(fplog, ir->fepvals, ir->expandedvals, ir->bSimTemp ? ir->simtempvals : NULL,
2025                                           &state_global->dfhist, state->fep_state, ir->nstlog, step);
2026             }
2027             if (!(bStartingFromCpt && (EI_VV(ir->eI))))
2028             {
2029                 if (bCalcEner)
2030                 {
2031                     upd_mdebin(mdebin, bDoDHDL, TRUE,
2032                                t, mdatoms->tmass, enerd, state,
2033                                ir->fepvals, ir->expandedvals, lastbox,
2034                                shake_vir, force_vir, total_vir, pres,
2035                                ekind, mu_tot, constr);
2036                 }
2037                 else
2038                 {
2039                     upd_mdebin_step(mdebin);
2040                 }
2041
2042                 do_dr  = do_per_step(step, ir->nstdisreout);
2043                 do_or  = do_per_step(step, ir->nstorireout);
2044
2045                 print_ebin(outf->fp_ene, do_ene, do_dr, do_or, do_log ? fplog : NULL,
2046                            step, t,
2047                            eprNORMAL, bCompact, mdebin, fcd, groups, &(ir->opts));
2048             }
2049             if (ir->ePull != epullNO)
2050             {
2051                 pull_print_output(ir->pull, step, t);
2052             }
2053
2054             if (do_per_step(step, ir->nstlog))
2055             {
2056                 if (fflush(fplog) != 0)
2057                 {
2058                     gmx_fatal(FARGS, "Cannot flush logfile - maybe you are out of disk space?");
2059                 }
2060             }
2061         }
2062         if (bDoExpanded)
2063         {
2064             /* Have to do this part _after_ outputting the logfile and the edr file */
2065             /* Gets written into the state at the beginning of next loop*/
2066             state->fep_state = lamnew;
2067         }
2068
2069         /* Remaining runtime */
2070         if (MULTIMASTER(cr) && (do_verbose || gmx_got_usr_signal()) && !bPMETuneRunning)
2071         {
2072             if (shellfc)
2073             {
2074                 fprintf(stderr, "\n");
2075             }
2076             print_time(stderr, runtime, step, ir, cr);
2077         }
2078
2079         /* Replica exchange */
2080         bExchanged = FALSE;
2081         if ((repl_ex_nst > 0) && (step > 0) && !bLastStep &&
2082             do_per_step(step, repl_ex_nst))
2083         {
2084             bExchanged = replica_exchange(fplog, cr, repl_ex,
2085                                           state_global, enerd,
2086                                           state, step, t);
2087
2088             if (bExchanged && DOMAINDECOMP(cr))
2089             {
2090                 dd_partition_system(fplog, step, cr, TRUE, 1,
2091                                     state_global, top_global, ir,
2092                                     state, &f, mdatoms, top, fr,
2093                                     vsite, shellfc, constr,
2094                                     nrnb, wcycle, FALSE);
2095             }
2096         }
2097
2098         bFirstStep       = FALSE;
2099         bInitStep        = FALSE;
2100         bStartingFromCpt = FALSE;
2101
2102         /* #######  SET VARIABLES FOR NEXT ITERATION IF THEY STILL NEED IT ###### */
2103         /* With all integrators, except VV, we need to retain the pressure
2104          * at the current step for coupling at the next step.
2105          */
2106         if ((state->flags & (1<<estPRES_PREV)) &&
2107             (bGStatEveryStep ||
2108              (ir->nstpcouple > 0 && step % ir->nstpcouple == 0)))
2109         {
2110             /* Store the pressure in t_state for pressure coupling
2111              * at the next MD step.
2112              */
2113             copy_mat(pres, state->pres_prev);
2114         }
2115
2116         /* #######  END SET VARIABLES FOR NEXT ITERATION ###### */
2117
2118         if ( (membed != NULL) && (!bLastStep) )
2119         {
2120             rescale_membed(step_rel, membed, state_global->x);
2121         }
2122
2123         if (bRerunMD)
2124         {
2125             if (MASTER(cr))
2126             {
2127                 /* read next frame from input trajectory */
2128                 bNotLastFrame = read_next_frame(oenv, status, &rerun_fr);
2129             }
2130
2131             if (PAR(cr))
2132             {
2133                 rerun_parallel_comm(cr, &rerun_fr, &bNotLastFrame);
2134             }
2135         }
2136
2137         if (!bRerunMD || !rerun_fr.bStep)
2138         {
2139             /* increase the MD step number */
2140             step++;
2141             step_rel++;
2142         }
2143
2144         cycles = wallcycle_stop(wcycle, ewcSTEP);
2145         if (DOMAINDECOMP(cr) && wcycle)
2146         {
2147             dd_cycles_add(cr->dd, cycles, ddCyclStep);
2148         }
2149
2150         if (bPMETuneRunning || bPMETuneTry)
2151         {
2152             /* PME grid + cut-off optimization with GPUs or PME nodes */
2153
2154             /* Count the total cycles over the last steps */
2155             cycles_pmes += cycles;
2156
2157             /* We can only switch cut-off at NS steps */
2158             if (step % ir->nstlist == 0)
2159             {
2160                 /* PME grid + cut-off optimization with GPUs or PME nodes */
2161                 if (bPMETuneTry)
2162                 {
2163                     if (DDMASTER(cr->dd))
2164                     {
2165                         /* PME node load is too high, start tuning */
2166                         bPMETuneRunning = (dd_pme_f_ratio(cr->dd) >= 1.05);
2167                     }
2168                     dd_bcast(cr->dd, sizeof(gmx_bool), &bPMETuneRunning);
2169
2170                     if (bPMETuneRunning || step_rel > ir->nstlist*50)
2171                     {
2172                         bPMETuneTry     = FALSE;
2173                     }
2174                 }
2175                 if (bPMETuneRunning)
2176                 {
2177                     /* init_step might not be a multiple of nstlist,
2178                      * but the first cycle is always skipped anyhow.
2179                      */
2180                     bPMETuneRunning =
2181                         pme_load_balance(pme_loadbal, cr,
2182                                          (bVerbose && MASTER(cr)) ? stderr : NULL,
2183                                          fplog,
2184                                          ir, state, cycles_pmes,
2185                                          fr->ic, fr->nbv, &fr->pmedata,
2186                                          step);
2187
2188                     /* Update constants in forcerec/inputrec to keep them in sync with fr->ic */
2189                     fr->ewaldcoeff = fr->ic->ewaldcoeff;
2190                     fr->rlist      = fr->ic->rlist;
2191                     fr->rlistlong  = fr->ic->rlistlong;
2192                     fr->rcoulomb   = fr->ic->rcoulomb;
2193                     fr->rvdw       = fr->ic->rvdw;
2194                 }
2195                 cycles_pmes = 0;
2196             }
2197         }
2198
2199         if (step_rel == wcycle_get_reset_counters(wcycle) ||
2200             gs.set[eglsRESETCOUNTERS] != 0)
2201         {
2202             /* Reset all the counters related to performance over the run */
2203             reset_all_counters(fplog, cr, step, &step_rel, ir, wcycle, nrnb, runtime,
2204                                fr->nbv != NULL && fr->nbv->bUseGPU ? fr->nbv->cu_nbv : NULL);
2205             wcycle_set_reset_counters(wcycle, -1);
2206             if (!(cr->duty & DUTY_PME))
2207             {
2208                 /* Tell our PME node to reset its counters */
2209                 gmx_pme_send_resetcounters(cr, step);
2210             }
2211             /* Correct max_hours for the elapsed time */
2212             max_hours                -= run_time/(60.0*60.0);
2213             bResetCountersHalfMaxH    = FALSE;
2214             gs.set[eglsRESETCOUNTERS] = 0;
2215         }
2216
2217     }
2218     /* End of main MD loop */
2219     debug_gmx();
2220
2221     /* Stop the time */
2222     runtime_end(runtime);
2223
2224     if (bRerunMD && MASTER(cr))
2225     {
2226         close_trj(status);
2227     }
2228
2229     if (!(cr->duty & DUTY_PME))
2230     {
2231         /* Tell the PME only node to finish */
2232         gmx_pme_send_finish(cr);
2233     }
2234
2235     if (MASTER(cr))
2236     {
2237         if (ir->nstcalcenergy > 0 && !bRerunMD)
2238         {
2239             print_ebin(outf->fp_ene, FALSE, FALSE, FALSE, fplog, step, t,
2240                        eprAVER, FALSE, mdebin, fcd, groups, &(ir->opts));
2241         }
2242     }
2243
2244     done_mdoutf(outf);
2245
2246     debug_gmx();
2247
2248     if (ir->nstlist == -1 && nlh.nns > 0 && fplog)
2249     {
2250         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)));
2251         fprintf(fplog, "Average number of atoms that crossed the half buffer length: %.1f\n\n", nlh.ab/nlh.nns);
2252     }
2253
2254     if (pme_loadbal != NULL)
2255     {
2256         pme_loadbal_done(pme_loadbal, cr, fplog,
2257                          fr->nbv != NULL && fr->nbv->bUseGPU);
2258     }
2259
2260     if (shellfc && fplog)
2261     {
2262         fprintf(fplog, "Fraction of iterations that converged:           %.2f %%\n",
2263                 (nconverged*100.0)/step_rel);
2264         fprintf(fplog, "Average number of force evaluations per MD step: %.2f\n\n",
2265                 tcount/step_rel);
2266     }
2267
2268     if (repl_ex_nst > 0 && MASTER(cr))
2269     {
2270         print_replica_exchange_statistics(fplog, repl_ex);
2271     }
2272
2273     runtime->nsteps_done = step_rel;
2274
2275     return 0;
2276 }