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