2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5 * Copyright (c) 2001-2004, The GROMACS development team.
6 * Copyright (c) 2011,2012,2013,2014,2015,2016, by the GROMACS development team, led by
7 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8 * and including many others, as listed in the AUTHORS file in the
9 * top-level source directory and at http://www.gromacs.org.
11 * GROMACS is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public License
13 * as published by the Free Software Foundation; either version 2.1
14 * of the License, or (at your option) any later version.
16 * GROMACS is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with GROMACS; if not, see
23 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 * If you want to redistribute modifications to GROMACS, please
27 * consider that scientific software is very special. Version
28 * control is crucial - bugs must be traceable. We will be happy to
29 * consider code for inclusion in the official distribution, but
30 * derived work must not be called official GROMACS. Details are found
31 * in the README & COPYING files - if they are missing, get the
32 * official version at http://www.gromacs.org.
34 * To help us fund GROMACS development, we humbly ask that you cite
35 * the research papers on the package. Check out http://www.gromacs.org.
47 #include "thread_mpi/threads.h"
49 #include "gromacs/commandline/filenm.h"
50 #include "gromacs/domdec/domdec.h"
51 #include "gromacs/domdec/domdec_network.h"
52 #include "gromacs/domdec/domdec_struct.h"
53 #include "gromacs/ewald/pme.h"
54 #include "gromacs/ewald/pme-load-balancing.h"
55 #include "gromacs/fileio/trxio.h"
56 #include "gromacs/gmxlib/md_logging.h"
57 #include "gromacs/gmxlib/network.h"
58 #include "gromacs/gmxlib/nrnb.h"
59 #include "gromacs/imd/imd.h"
60 #include "gromacs/listed-forces/manage-threading.h"
61 #include "gromacs/math/functions.h"
62 #include "gromacs/math/utilities.h"
63 #include "gromacs/math/vec.h"
64 #include "gromacs/math/vectypes.h"
65 #include "gromacs/mdlib/compute_io.h"
66 #include "gromacs/mdlib/constr.h"
67 #include "gromacs/mdlib/ebin.h"
68 #include "gromacs/mdlib/force.h"
69 #include "gromacs/mdlib/force_flags.h"
70 #include "gromacs/mdlib/forcerec.h"
71 #include "gromacs/mdlib/md_support.h"
72 #include "gromacs/mdlib/mdatoms.h"
73 #include "gromacs/mdlib/mdebin.h"
74 #include "gromacs/mdlib/mdoutf.h"
75 #include "gromacs/mdlib/mdrun.h"
76 #include "gromacs/mdlib/mdrun_signalling.h"
77 #include "gromacs/mdlib/nb_verlet.h"
78 #include "gromacs/mdlib/nbnxn_gpu_data_mgmt.h"
79 #include "gromacs/mdlib/ns.h"
80 #include "gromacs/mdlib/shellfc.h"
81 #include "gromacs/mdlib/sighandler.h"
82 #include "gromacs/mdlib/sim_util.h"
83 #include "gromacs/mdlib/tgroup.h"
84 #include "gromacs/mdlib/trajectory_writing.h"
85 #include "gromacs/mdlib/update.h"
86 #include "gromacs/mdlib/vcm.h"
87 #include "gromacs/mdlib/vsite.h"
88 #include "gromacs/mdtypes/commrec.h"
89 #include "gromacs/mdtypes/df_history.h"
90 #include "gromacs/mdtypes/energyhistory.h"
91 #include "gromacs/mdtypes/fcdata.h"
92 #include "gromacs/mdtypes/forcerec.h"
93 #include "gromacs/mdtypes/group.h"
94 #include "gromacs/mdtypes/inputrec.h"
95 #include "gromacs/mdtypes/interaction_const.h"
96 #include "gromacs/mdtypes/md_enums.h"
97 #include "gromacs/mdtypes/mdatom.h"
98 #include "gromacs/mdtypes/state.h"
99 #include "gromacs/pbcutil/mshift.h"
100 #include "gromacs/pbcutil/pbc.h"
101 #include "gromacs/pulling/pull.h"
102 #include "gromacs/swap/swapcoords.h"
103 #include "gromacs/timing/wallcycle.h"
104 #include "gromacs/timing/walltime_accounting.h"
105 #include "gromacs/topology/atoms.h"
106 #include "gromacs/topology/idef.h"
107 #include "gromacs/topology/mtop_util.h"
108 #include "gromacs/topology/topology.h"
109 #include "gromacs/trajectory/trajectoryframe.h"
110 #include "gromacs/utility/basedefinitions.h"
111 #include "gromacs/utility/cstringutil.h"
112 #include "gromacs/utility/fatalerror.h"
113 #include "gromacs/utility/real.h"
114 #include "gromacs/utility/smalloc.h"
121 #include "corewrap.h"
124 /*! \brief Check whether bonded interactions are missing, if appropriate
126 * \param[in] fplog Log file pointer
127 * \param[in] cr Communication object
128 * \param[in] totalNumberOfBondedInteractions Result of the global reduction over the number of bonds treated in each domain
129 * \param[in] top_global Global topology for the error message
130 * \param[in] top_local Local topology for the error message
131 * \param[in] state Global state for the error message
132 * \param[inout] shouldCheckNumberOfBondedInteractions Whether we should do the check.
134 * \return Nothing, except that shouldCheckNumberOfBondedInteractions
135 * is always set to false after exit.
137 static void checkNumberOfBondedInteractions(FILE *fplog, t_commrec *cr, int totalNumberOfBondedInteractions,
138 gmx_mtop_t *top_global, gmx_localtop_t *top_local, t_state *state,
139 bool *shouldCheckNumberOfBondedInteractions)
141 if (*shouldCheckNumberOfBondedInteractions)
143 if (totalNumberOfBondedInteractions != cr->dd->nbonded_global)
145 dd_print_missing_interactions(fplog, cr, totalNumberOfBondedInteractions, top_global, top_local, state); // Does not return
147 *shouldCheckNumberOfBondedInteractions = false;
151 static void reset_all_counters(FILE *fplog, t_commrec *cr,
153 gmx_int64_t *step_rel, t_inputrec *ir,
154 gmx_wallcycle_t wcycle, t_nrnb *nrnb,
155 gmx_walltime_accounting_t walltime_accounting,
156 struct nonbonded_verlet_t *nbv)
158 char sbuf[STEPSTRSIZE];
160 /* Reset all the counters related to performance over the run */
161 md_print_warn(cr, fplog, "step %s: resetting all time and cycle counters\n",
162 gmx_step_str(step, sbuf));
166 nbnxn_gpu_reset_timings(nbv);
169 wallcycle_stop(wcycle, ewcRUN);
170 wallcycle_reset_all(wcycle);
171 if (DOMAINDECOMP(cr))
173 reset_dd_statistics_counters(cr->dd);
176 ir->init_step += *step_rel;
177 ir->nsteps -= *step_rel;
179 wallcycle_start(wcycle, ewcRUN);
180 walltime_accounting_start(walltime_accounting);
181 print_date_and_time(fplog, cr->nodeid, "Restarted time", gmx_gettime());
185 \copydoc integrator_t (FILE *fplog, t_commrec *cr,
186 int nfile, const t_filenm fnm[],
187 const gmx_output_env_t *oenv, gmx_bool bVerbose,
189 gmx_vsite_t *vsite, gmx_constr_t constr,
191 t_inputrec *inputrec,
192 gmx_mtop_t *top_global, t_fcdata *fcd,
193 t_state *state_global,
195 t_nrnb *nrnb, gmx_wallcycle_t wcycle,
198 int repl_ex_nst, int repl_ex_nex, int repl_ex_seed,
199 gmx_membed_t *membed,
200 real cpt_period, real max_hours,
203 gmx_walltime_accounting_t walltime_accounting)
205 double gmx::do_md(FILE *fplog, t_commrec *cr, int nfile, const t_filenm fnm[],
206 const gmx_output_env_t *oenv, gmx_bool bVerbose,
208 gmx_vsite_t *vsite, gmx_constr_t constr,
209 int stepout, t_inputrec *ir,
210 gmx_mtop_t *top_global,
212 t_state *state_global,
214 t_nrnb *nrnb, gmx_wallcycle_t wcycle,
215 gmx_edsam_t ed, t_forcerec *fr,
216 int repl_ex_nst, int repl_ex_nex, int repl_ex_seed, gmx_membed_t *membed,
217 real cpt_period, real max_hours,
220 gmx_walltime_accounting_t walltime_accounting)
222 gmx_mdoutf_t outf = NULL;
223 gmx_int64_t step, step_rel;
225 double t, t0, lam0[efptNR];
226 gmx_bool bGStatEveryStep, bGStat, bCalcVir, bCalcEnerStep, bCalcEner;
227 gmx_bool bNS, bNStList, bSimAnn, bStopCM, bRerunMD, bNotLastFrame = FALSE,
228 bFirstStep, startingFromCheckpoint, bInitStep, bLastStep,
230 gmx_bool bDoDHDL = FALSE, bDoFEP = FALSE, bDoExpanded = FALSE;
231 gmx_bool do_ene, do_log, do_verbose, bRerunWarnNoV = TRUE,
232 bForceUpdate = FALSE, bCPT;
233 gmx_bool bMasterState;
234 int force_flags, cglo_flags;
235 tensor force_vir, shake_vir, total_vir, tmp_vir, pres;
242 gmx_repl_ex_t repl_ex = NULL;
245 t_mdebin *mdebin = NULL;
246 t_state *state = NULL;
247 gmx_enerdata_t *enerd;
249 gmx_global_stat_t gstat;
250 gmx_update_t *upd = NULL;
251 t_graph *graph = NULL;
253 gmx_groups_t *groups;
254 gmx_ekindata_t *ekind;
255 gmx_shellfc_t *shellfc;
256 gmx_bool bSumEkinhOld, bDoReplEx, bExchanged, bNeedRepartition;
257 gmx_bool bResetCountersHalfMaxH = FALSE;
258 gmx_bool bTemp, bPres, bTrotter;
267 real saved_conserved_quantity = 0;
271 char sbuf[STEPSTRSIZE], sbuf2[STEPSTRSIZE];
272 int handled_stop_condition = gmx_stop_cond_none; /* compare to get_stop_condition*/
273 gmx_int64_t multisim_nsteps = -1; /* number of steps to do before first multisim
274 simulation stops. If equal to zero, don't
275 communicate any more between multisims.*/
276 /* PME load balancing data for GPU kernels */
277 pme_load_balancing_t *pme_loadbal = NULL;
278 gmx_bool bPMETune = FALSE;
279 gmx_bool bPMETunePrinting = FALSE;
282 gmx_bool bIMDstep = FALSE;
285 /* Temporary addition for FAHCORE checkpointing */
288 /* Domain decomposition could incorrectly miss a bonded
289 interaction, but checking for that requires a global
290 communication stage, which does not otherwise happen in DD
291 code. So we do that alongside the first global energy reduction
292 after a new DD is made. These variables handle whether the
293 check happens, and the result it returns. */
294 bool shouldCheckNumberOfBondedInteractions = false;
295 int totalNumberOfBondedInteractions = -1;
297 /* Check for special mdrun options */
298 bRerunMD = (Flags & MD_RERUN);
299 if (Flags & MD_RESETCOUNTERSHALFWAY)
303 /* Signal to reset the counters half the simulation steps. */
304 wcycle_set_reset_counters(wcycle, ir->nsteps/2);
306 /* Signal to reset the counters halfway the simulation time. */
307 bResetCountersHalfMaxH = (max_hours > 0);
310 /* md-vv uses averaged full step velocities for T-control
311 md-vv-avek uses averaged half step velocities for T-control (but full step ekin for P control)
312 md uses averaged half step kinetic energies to determine temperature unless defined otherwise by GMX_EKIN_AVE_VEL; */
313 bTrotter = (EI_VV(ir->eI) && (inputrecNptTrotter(ir) || inputrecNphTrotter(ir) || inputrecNvtTrotter(ir)));
317 /* Since we don't know if the frames read are related in any way,
318 * rebuild the neighborlist at every step.
321 ir->nstcalcenergy = 1;
325 nstglobalcomm = check_nstglobalcomm(fplog, cr, nstglobalcomm, ir);
326 bGStatEveryStep = (nstglobalcomm == 1);
330 ir->nstxout_compressed = 0;
332 groups = &top_global->groups;
335 init_md(fplog, cr, ir, oenv, &t, &t0, state_global->lambda,
336 &(state_global->fep_state), lam0,
337 nrnb, top_global, &upd,
338 nfile, fnm, &outf, &mdebin,
339 force_vir, shake_vir, mu_tot, &bSimAnn, &vcm, Flags, wcycle);
341 clear_mat(total_vir);
343 /* Energy terms and groups */
345 init_enerdata(top_global->groups.grps[egcENER].nr, ir->fepvals->n_lambda,
347 if (DOMAINDECOMP(cr))
353 snew(f, top_global->natoms);
356 /* Kinetic energy data */
358 init_ekindata(fplog, top_global, &(ir->opts), ekind);
359 /* Copy the cos acceleration to the groups struct */
360 ekind->cosacc.cos_accel = ir->cos_accel;
362 gstat = global_stat_init(ir);
364 /* Check for polarizable models and flexible constraints */
365 shellfc = init_shell_flexcon(fplog,
366 top_global, n_flexible_constraints(constr),
367 ir->nstcalcenergy, DOMAINDECOMP(cr));
369 if (shellfc && ir->nstcalcenergy != 1)
371 gmx_fatal(FARGS, "You have nstcalcenergy set to a value (%d) that is different from 1.\nThis is not supported in combinations with shell particles.\nPlease make a new tpr file.", ir->nstcalcenergy);
373 if (shellfc && DOMAINDECOMP(cr))
375 gmx_fatal(FARGS, "Shell particles are not implemented with domain decomposition, use a single rank");
378 if (inputrecDeform(ir))
380 tMPI_Thread_mutex_lock(&deform_init_box_mutex);
381 set_deform_reference_box(upd,
382 deform_init_init_step_tpx,
383 deform_init_box_tpx);
384 tMPI_Thread_mutex_unlock(&deform_init_box_mutex);
388 double io = compute_io(ir, top_global->natoms, groups, mdebin->ebin->nener, 1);
389 if ((io > 2000) && MASTER(cr))
392 "\nWARNING: This run will generate roughly %.0f Mb of data\n\n",
397 if (DOMAINDECOMP(cr))
399 top = dd_init_local_top(top_global);
402 dd_init_local_state(cr->dd, state_global, state);
406 top = gmx_mtop_generate_local_top(top_global, ir->efep != efepNO);
408 forcerec_set_excl_load(fr, top);
410 state = serial_init_local_state(state_global);
412 atoms2md(top_global, ir, 0, NULL, top_global->natoms, mdatoms);
416 set_vsite_top(vsite, top, mdatoms, cr);
419 if (ir->ePBC != epbcNONE && !fr->bMolPBC)
421 graph = mk_graph(fplog, &(top->idef), 0, top_global->natoms, FALSE, FALSE);
426 make_local_shells(cr, mdatoms, shellfc);
429 setup_bonded_threading(fr, &top->idef);
432 /* Set up interactive MD (IMD) */
433 init_IMD(ir, cr, top_global, fplog, ir->nstcalcenergy, state_global->x,
434 nfile, fnm, oenv, imdport, Flags);
436 if (DOMAINDECOMP(cr))
438 /* Distribute the charge groups over the nodes from the master node */
439 dd_partition_system(fplog, ir->init_step, cr, TRUE, 1,
440 state_global, top_global, ir,
441 state, &f, mdatoms, top, fr,
444 shouldCheckNumberOfBondedInteractions = true;
447 update_mdatoms(mdatoms, state->lambda[efptMASS]);
449 startingFromCheckpoint = Flags & MD_STARTFROMCPT;
453 init_expanded_ensemble(startingFromCheckpoint, ir, &state->dfhist);
458 if (startingFromCheckpoint)
460 /* Update mdebin with energy history if appending to output files */
461 if (Flags & MD_APPENDFILES)
463 restore_energyhistory_from_state(mdebin, state_global->enerhist);
467 /* We might have read an energy history from checkpoint,
468 * free the allocated memory and reset the counts.
470 done_energyhistory(state_global->enerhist);
471 init_energyhistory(state_global->enerhist);
474 /* Set the initial energy history in state by updating once */
475 update_energyhistory(state_global->enerhist, mdebin);
478 /* Initialize constraints */
479 if (constr && !DOMAINDECOMP(cr))
481 set_constraints(constr, top, ir, mdatoms, cr);
484 if (repl_ex_nst > 0 && MASTER(cr))
486 repl_ex = init_replica_exchange(fplog, cr->ms, state_global, ir,
487 repl_ex_nst, repl_ex_nex, repl_ex_seed);
490 /* PME tuning is only supported with PME for Coulomb. Is is not supported
491 * with only LJ PME, or for reruns.
493 bPMETune = ((Flags & MD_TUNEPME) && EEL_PME(fr->eeltype) && !bRerunMD &&
494 !(Flags & MD_REPRODUCIBLE));
497 pme_loadbal_init(&pme_loadbal, cr, fplog, ir, state->box,
498 fr->ic, fr->pmedata, use_GPU(fr->nbv),
502 if (!ir->bContinuation && !bRerunMD)
504 if (mdatoms->cFREEZE && (state->flags & (1<<estV)))
506 /* Set the velocities of frozen particles to zero */
507 for (i = 0; i < mdatoms->homenr; i++)
509 for (m = 0; m < DIM; m++)
511 if (ir->opts.nFreeze[mdatoms->cFREEZE[i]][m])
521 /* Constrain the initial coordinates and velocities */
522 do_constrain_first(fplog, constr, ir, mdatoms, state,
527 /* Construct the virtual sites for the initial configuration */
528 construct_vsites(vsite, state->x, ir->delta_t, NULL,
529 top->idef.iparams, top->idef.il,
530 fr->ePBC, fr->bMolPBC, cr, state->box);
534 if (ir->efep != efepNO)
536 /* Set free energy calculation frequency as the greatest common
537 * denominator of nstdhdl and repl_ex_nst. */
538 nstfep = ir->fepvals->nstdhdl;
541 nstfep = gmx_greatest_common_divisor(ir->expandedvals->nstexpanded, nstfep);
545 nstfep = gmx_greatest_common_divisor(repl_ex_nst, nstfep);
549 /* Be REALLY careful about what flags you set here. You CANNOT assume
550 * this is the first step, since we might be restarting from a checkpoint,
551 * and in that case we should not do any modifications to the state.
553 bStopCM = (ir->comm_mode != ecmNO && !ir->bContinuation);
555 if (Flags & MD_READ_EKIN)
557 restore_ekinstate_from_state(cr, ekind, &state_global->ekinstate);
560 cglo_flags = (CGLO_TEMPERATURE | CGLO_GSTAT
561 | (bStopCM ? CGLO_STOPCM : 0)
562 | (EI_VV(ir->eI) ? CGLO_PRESSURE : 0)
563 | (EI_VV(ir->eI) ? CGLO_CONSTRAINT : 0)
564 | ((Flags & MD_READ_EKIN) ? CGLO_READEKIN : 0));
566 bSumEkinhOld = FALSE;
567 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
568 NULL, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
569 constr, NULL, FALSE, state->box,
570 &totalNumberOfBondedInteractions, &bSumEkinhOld, cglo_flags
571 | (shouldCheckNumberOfBondedInteractions ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS : 0));
572 checkNumberOfBondedInteractions(fplog, cr, totalNumberOfBondedInteractions,
573 top_global, top, state,
574 &shouldCheckNumberOfBondedInteractions);
575 if (ir->eI == eiVVAK)
577 /* a second call to get the half step temperature initialized as well */
578 /* we do the same call as above, but turn the pressure off -- internally to
579 compute_globals, this is recognized as a velocity verlet half-step
580 kinetic energy calculation. This minimized excess variables, but
581 perhaps loses some logic?*/
583 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
584 NULL, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
585 constr, NULL, FALSE, state->box,
587 cglo_flags &~(CGLO_STOPCM | CGLO_PRESSURE));
590 /* Calculate the initial half step temperature, and save the ekinh_old */
591 if (!(Flags & MD_STARTFROMCPT))
593 for (i = 0; (i < ir->opts.ngtc); i++)
595 copy_mat(ekind->tcstat[i].ekinh, ekind->tcstat[i].ekinh_old);
600 enerd->term[F_TEMP] *= 2; /* result of averages being done over previous and current step,
601 and there is no previous step */
604 /* need to make an initiation call to get the Trotter variables set, as well as other constants for non-trotter
605 temperature control */
606 trotter_seq = init_npt_vars(ir, state, &MassQ, bTrotter);
610 if (constr && !ir->bContinuation && ir->eConstrAlg == econtLINCS)
613 "RMS relative constraint deviation after constraining: %.2e\n",
614 constr_rmsd(constr));
616 if (EI_STATE_VELOCITY(ir->eI))
618 fprintf(fplog, "Initial temperature: %g K\n", enerd->term[F_TEMP]);
622 fprintf(stderr, "starting md rerun '%s', reading coordinates from"
623 " input trajectory '%s'\n\n",
624 *(top_global->name), opt2fn("-rerun", nfile, fnm));
627 fprintf(stderr, "Calculated time to finish depends on nsteps from "
628 "run input file,\nwhich may not correspond to the time "
629 "needed to process input trajectory.\n\n");
635 fprintf(stderr, "starting mdrun '%s'\n",
636 *(top_global->name));
639 sprintf(tbuf, "%8.1f", (ir->init_step+ir->nsteps)*ir->delta_t);
643 sprintf(tbuf, "%s", "infinite");
645 if (ir->init_step > 0)
647 fprintf(stderr, "%s steps, %s ps (continuing from step %s, %8.1f ps).\n",
648 gmx_step_str(ir->init_step+ir->nsteps, sbuf), tbuf,
649 gmx_step_str(ir->init_step, sbuf2),
650 ir->init_step*ir->delta_t);
654 fprintf(stderr, "%s steps, %s ps.\n",
655 gmx_step_str(ir->nsteps, sbuf), tbuf);
658 fprintf(fplog, "\n");
661 walltime_accounting_start(walltime_accounting);
662 wallcycle_start(wcycle, ewcRUN);
663 print_start(fplog, cr, walltime_accounting, "mdrun");
665 /* safest point to do file checkpointing is here. More general point would be immediately before integrator call */
667 chkpt_ret = fcCheckPointParallel( cr->nodeid,
671 gmx_fatal( 3, __FILE__, __LINE__, "Checkpoint error on step %d\n", 0 );
675 /***********************************************************
679 ************************************************************/
681 /* if rerunMD then read coordinates and velocities from input trajectory */
684 if (getenv("GMX_FORCE_UPDATE"))
692 bNotLastFrame = read_first_frame(oenv, &status,
693 opt2fn("-rerun", nfile, fnm),
694 &rerun_fr, TRX_NEED_X | TRX_READ_V);
695 if (rerun_fr.natoms != top_global->natoms)
698 "Number of atoms in trajectory (%d) does not match the "
699 "run input file (%d)\n",
700 rerun_fr.natoms, top_global->natoms);
702 if (ir->ePBC != epbcNONE)
706 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);
708 if (max_cutoff2(ir->ePBC, rerun_fr.box) < gmx::square(fr->rlist))
710 gmx_fatal(FARGS, "Rerun trajectory frame step %d time %f has too small box dimensions", rerun_fr.step, rerun_fr.time);
717 rerun_parallel_comm(cr, &rerun_fr, &bNotLastFrame);
720 if (ir->ePBC != epbcNONE)
722 /* Set the shift vectors.
723 * Necessary here when have a static box different from the tpr box.
725 calc_shifts(rerun_fr.box, fr->shift_vec);
729 /* loop over MD steps or if rerunMD to end of input trajectory */
731 /* Skip the first Nose-Hoover integration when we get the state from tpx */
732 bInitStep = !startingFromCheckpoint || EI_VV(ir->eI);
733 bSumEkinhOld = FALSE;
735 bNeedRepartition = FALSE;
737 init_global_signals(&gs, cr, ir, repl_ex_nst);
739 step = ir->init_step;
742 if (MULTISIM(cr) && (repl_ex_nst <= 0 ))
744 /* check how many steps are left in other sims */
745 multisim_nsteps = get_multisim_nsteps(cr, ir->nsteps);
749 /* and stop now if we should */
750 bLastStep = (bRerunMD || (ir->nsteps >= 0 && step_rel > ir->nsteps) ||
751 ((multisim_nsteps >= 0) && (step_rel >= multisim_nsteps )));
752 while (!bLastStep || (bRerunMD && bNotLastFrame))
755 /* Determine if this is a neighbor search step */
756 bNStList = (ir->nstlist > 0 && step % ir->nstlist == 0);
758 if (bPMETune && bNStList)
760 /* PME grid + cut-off optimization with GPUs or PME nodes */
761 pme_loadbal_do(pme_loadbal, cr,
762 (bVerbose && MASTER(cr)) ? stderr : NULL,
770 wallcycle_start(wcycle, ewcSTEP);
776 step = rerun_fr.step;
777 step_rel = step - ir->init_step;
790 bLastStep = (step_rel == ir->nsteps);
791 t = t0 + step*ir->delta_t;
794 if (ir->efep != efepNO || ir->bSimTemp)
796 /* find and set the current lambdas. If rerunning, we either read in a state, or a lambda value,
797 requiring different logic. */
799 set_current_lambdas(step, ir->fepvals, bRerunMD, &rerun_fr, state_global, state, lam0);
800 bDoDHDL = do_per_step(step, ir->fepvals->nstdhdl);
801 bDoFEP = ((ir->efep != efepNO) && do_per_step(step, nstfep));
802 bDoExpanded = (do_per_step(step, ir->expandedvals->nstexpanded)
803 && (ir->bExpanded) && (step > 0) && (!startingFromCheckpoint));
806 bDoReplEx = ((repl_ex_nst > 0) && (step > 0) && !bLastStep &&
807 do_per_step(step, repl_ex_nst));
811 update_annealing_target_temp(ir, t, upd);
816 if (!DOMAINDECOMP(cr) || MASTER(cr))
818 for (i = 0; i < state_global->natoms; i++)
820 copy_rvec(rerun_fr.x[i], state_global->x[i]);
824 for (i = 0; i < state_global->natoms; i++)
826 copy_rvec(rerun_fr.v[i], state_global->v[i]);
831 for (i = 0; i < state_global->natoms; i++)
833 clear_rvec(state_global->v[i]);
837 fprintf(stderr, "\nWARNING: Some frames do not contain velocities.\n"
838 " Ekin, temperature and pressure are incorrect,\n"
839 " the virial will be incorrect when constraints are present.\n"
841 bRerunWarnNoV = FALSE;
845 copy_mat(rerun_fr.box, state_global->box);
846 copy_mat(state_global->box, state->box);
848 if (vsite && (Flags & MD_RERUN_VSITE))
850 if (DOMAINDECOMP(cr))
852 gmx_fatal(FARGS, "Vsite recalculation with -rerun is not implemented with domain decomposition, use a single rank");
856 /* Following is necessary because the graph may get out of sync
857 * with the coordinates if we only have every N'th coordinate set
859 mk_mshift(fplog, graph, fr->ePBC, state->box, state->x);
860 shift_self(graph, state->box, state->x);
862 construct_vsites(vsite, state->x, ir->delta_t, state->v,
863 top->idef.iparams, top->idef.il,
864 fr->ePBC, fr->bMolPBC, cr, state->box);
867 unshift_self(graph, state->box, state->x);
872 /* Stop Center of Mass motion */
873 bStopCM = (ir->comm_mode != ecmNO && do_per_step(step, ir->nstcomm));
877 /* for rerun MD always do Neighbour Searching */
878 bNS = (bFirstStep || ir->nstlist != 0);
883 /* Determine whether or not to do Neighbour Searching */
884 bNS = (bFirstStep || bNStList || bExchanged || bNeedRepartition);
887 /* check whether we should stop because another simulation has
891 if ( (multisim_nsteps >= 0) && (step_rel >= multisim_nsteps) &&
892 (multisim_nsteps != ir->nsteps) )
899 "Stopping simulation %d because another one has finished\n",
903 gs.sig[eglsCHKPT] = 1;
908 /* < 0 means stop at next step, > 0 means stop at next NS step */
909 if ( (gs.set[eglsSTOPCOND] < 0) ||
910 ( (gs.set[eglsSTOPCOND] > 0) && (bNStList || ir->nstlist == 0) ) )
915 /* Determine whether or not to update the Born radii if doing GB */
916 bBornRadii = bFirstStep;
917 if (ir->implicit_solvent && (step % ir->nstgbradii == 0))
922 /* do_log triggers energy and virial calculation. Because this leads
923 * to different code paths, forces can be different. Thus for exact
924 * continuation we should avoid extra log output.
925 * Note that the || bLastStep can result in non-exact continuation
926 * beyond the last step. But we don't consider that to be an issue.
928 do_log = do_per_step(step, ir->nstlog) || (bFirstStep && !startingFromCheckpoint) || bLastStep;
929 do_verbose = bVerbose &&
930 (step % stepout == 0 || bFirstStep || bLastStep);
932 if (bNS && !(bFirstStep && ir->bContinuation && !bRerunMD))
940 bMasterState = FALSE;
941 /* Correct the new box if it is too skewed */
942 if (inputrecDynamicBox(ir))
944 if (correct_box(fplog, step, state->box, graph))
949 if (DOMAINDECOMP(cr) && bMasterState)
951 dd_collect_state(cr->dd, state, state_global);
955 if (DOMAINDECOMP(cr))
957 /* Repartition the domain decomposition */
958 dd_partition_system(fplog, step, cr,
959 bMasterState, nstglobalcomm,
960 state_global, top_global, ir,
961 state, &f, mdatoms, top, fr,
964 do_verbose && !bPMETunePrinting);
965 shouldCheckNumberOfBondedInteractions = true;
969 if (MASTER(cr) && do_log)
971 print_ebin_header(fplog, step, t); /* can we improve the information printed here? */
974 if (ir->efep != efepNO)
976 update_mdatoms(mdatoms, state->lambda[efptMASS]);
979 if ((bRerunMD && rerun_fr.bV) || bExchanged)
982 /* We need the kinetic energy at minus the half step for determining
983 * the full step kinetic energy and possibly for T-coupling.*/
984 /* This may not be quite working correctly yet . . . . */
985 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
986 wcycle, enerd, NULL, NULL, NULL, NULL, mu_tot,
987 constr, NULL, FALSE, state->box,
988 &totalNumberOfBondedInteractions, &bSumEkinhOld,
989 CGLO_GSTAT | CGLO_TEMPERATURE | CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS);
990 checkNumberOfBondedInteractions(fplog, cr, totalNumberOfBondedInteractions,
991 top_global, top, state,
992 &shouldCheckNumberOfBondedInteractions);
994 clear_mat(force_vir);
996 /* We write a checkpoint at this MD step when:
997 * either at an NS step when we signalled through gs,
998 * or at the last step (but not when we do not want confout),
999 * but never at the first step or with rerun.
1001 bCPT = (((gs.set[eglsCHKPT] && (bNS || ir->nstlist == 0)) ||
1002 (bLastStep && (Flags & MD_CONFOUT))) &&
1003 step > ir->init_step && !bRerunMD);
1006 gs.set[eglsCHKPT] = 0;
1009 /* Determine the energy and pressure:
1010 * at nstcalcenergy steps and at energy output steps (set below).
1012 if (EI_VV(ir->eI) && (!bInitStep))
1014 /* for vv, the first half of the integration actually corresponds
1015 to the previous step. bCalcEner is only required to be evaluated on the 'next' step,
1016 but the virial needs to be calculated on both the current step and the 'next' step. Future
1017 reorganization may be able to get rid of one of the bCalcVir=TRUE steps. */
1019 /* TODO: This is probably not what we want, we will write to energy file one step after nstcalcenergy steps. */
1020 bCalcEnerStep = do_per_step(step - 1, ir->nstcalcenergy);
1021 bCalcVir = bCalcEnerStep ||
1022 (ir->epc != epcNO && (do_per_step(step, ir->nstpcouple) || do_per_step(step-1, ir->nstpcouple)));
1026 bCalcEnerStep = do_per_step(step, ir->nstcalcenergy);
1027 bCalcVir = bCalcEnerStep ||
1028 (ir->epc != epcNO && do_per_step(step, ir->nstpcouple));
1030 bCalcEner = bCalcEnerStep;
1032 do_ene = (do_per_step(step, ir->nstenergy) || bLastStep);
1034 if (do_ene || do_log || bDoReplEx)
1040 /* Do we need global communication ? */
1041 bGStat = (bCalcVir || bCalcEner || bStopCM ||
1042 do_per_step(step, nstglobalcomm) ||
1043 (EI_VV(ir->eI) && inputrecNvtTrotter(ir) && do_per_step(step-1, nstglobalcomm)));
1045 force_flags = (GMX_FORCE_STATECHANGED |
1046 ((inputrecDynamicBox(ir) || bRerunMD) ? GMX_FORCE_DYNAMICBOX : 0) |
1047 GMX_FORCE_ALLFORCES |
1048 (bCalcVir ? GMX_FORCE_VIRIAL : 0) |
1049 (bCalcEner ? GMX_FORCE_ENERGY : 0) |
1050 (bDoFEP ? GMX_FORCE_DHDL : 0)
1055 /* Now is the time to relax the shells */
1056 relax_shell_flexcon(fplog, cr, bVerbose, step,
1057 ir, bNS, force_flags, top,
1059 state, f, force_vir, mdatoms,
1060 nrnb, wcycle, graph, groups,
1061 shellfc, fr, bBornRadii, t, mu_tot,
1062 vsite, mdoutf_get_fp_field(outf));
1066 /* The coordinates (x) are shifted (to get whole molecules)
1068 * This is parallellized as well, and does communication too.
1069 * Check comments in sim_util.c
1071 do_force(fplog, cr, ir, step, nrnb, wcycle, top, groups,
1072 state->box, state->x, &state->hist,
1073 f, force_vir, mdatoms, enerd, fcd,
1074 state->lambda, graph,
1075 fr, vsite, mu_tot, t, mdoutf_get_fp_field(outf), ed, bBornRadii,
1076 (bNS ? GMX_FORCE_NS : 0) | force_flags);
1079 if (EI_VV(ir->eI) && !startingFromCheckpoint && !bRerunMD)
1080 /* ############### START FIRST UPDATE HALF-STEP FOR VV METHODS############### */
1084 wallcycle_start(wcycle, ewcUPDATE);
1085 if (ir->eI == eiVV && bInitStep)
1087 /* if using velocity verlet with full time step Ekin,
1088 * take the first half step only to compute the
1089 * virial for the first step. From there,
1090 * revert back to the initial coordinates
1091 * so that the input is actually the initial step.
1093 snew(vbuf, state->natoms);
1094 copy_rvecn(state->v, vbuf, 0, state->natoms); /* should make this better for parallelizing? */
1098 /* this is for NHC in the Ekin(t+dt/2) version of vv */
1099 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ1);
1102 update_coords(fplog, step, ir, mdatoms, state, f, fcd,
1103 ekind, M, upd, etrtVELOCITY1,
1106 if (!bRerunMD || rerun_fr.bV || bForceUpdate) /* Why is rerun_fr.bV here? Unclear. */
1108 wallcycle_stop(wcycle, ewcUPDATE);
1109 update_constraints(fplog, step, NULL, ir, mdatoms,
1110 state, fr->bMolPBC, graph, f,
1111 &top->idef, shake_vir,
1112 cr, nrnb, wcycle, upd, constr,
1114 wallcycle_start(wcycle, ewcUPDATE);
1118 /* Need to unshift here if a do_force has been
1119 called in the previous step */
1120 unshift_self(graph, state->box, state->x);
1122 /* if VV, compute the pressure and constraints */
1123 /* For VV2, we strictly only need this if using pressure
1124 * control, but we really would like to have accurate pressures
1126 * Think about ways around this in the future?
1127 * For now, keep this choice in comments.
1129 /*bPres = (ir->eI==eiVV || inputrecNptTrotter(ir)); */
1130 /*bTemp = ((ir->eI==eiVV &&(!bInitStep)) || (ir->eI==eiVVAK && inputrecNptTrotter(ir)));*/
1132 bTemp = ((ir->eI == eiVV && (!bInitStep)) || (ir->eI == eiVVAK));
1133 if (bCalcEner && ir->eI == eiVVAK)
1135 bSumEkinhOld = TRUE;
1137 /* for vv, the first half of the integration actually corresponds to the previous step.
1138 So we need information from the last step in the first half of the integration */
1139 if (bGStat || do_per_step(step-1, nstglobalcomm))
1141 wallcycle_stop(wcycle, ewcUPDATE);
1142 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
1143 wcycle, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
1144 constr, NULL, FALSE, state->box,
1145 &totalNumberOfBondedInteractions, &bSumEkinhOld,
1146 (bGStat ? CGLO_GSTAT : 0)
1148 | (bTemp ? CGLO_TEMPERATURE : 0)
1149 | (bPres ? CGLO_PRESSURE : 0)
1150 | (bPres ? CGLO_CONSTRAINT : 0)
1151 | (bStopCM ? CGLO_STOPCM : 0)
1152 | (shouldCheckNumberOfBondedInteractions ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS : 0)
1155 /* explanation of above:
1156 a) We compute Ekin at the full time step
1157 if 1) we are using the AveVel Ekin, and it's not the
1158 initial step, or 2) if we are using AveEkin, but need the full
1159 time step kinetic energy for the pressure (always true now, since we want accurate statistics).
1160 b) If we are using EkinAveEkin for the kinetic energy for the temperature control, we still feed in
1161 EkinAveVel because it's needed for the pressure */
1162 checkNumberOfBondedInteractions(fplog, cr, totalNumberOfBondedInteractions,
1163 top_global, top, state,
1164 &shouldCheckNumberOfBondedInteractions);
1165 wallcycle_start(wcycle, ewcUPDATE);
1167 /* temperature scaling and pressure scaling to produce the extended variables at t+dt */
1172 m_add(force_vir, shake_vir, total_vir); /* we need the un-dispersion corrected total vir here */
1173 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ2);
1175 copy_mat(shake_vir, state->svir_prev);
1176 copy_mat(force_vir, state->fvir_prev);
1177 if (inputrecNvtTrotter(ir) && ir->eI == eiVV)
1179 /* update temperature and kinetic energy now that step is over - this is the v(t+dt) point */
1180 enerd->term[F_TEMP] = sum_ekin(&(ir->opts), ekind, NULL, (ir->eI == eiVV), FALSE);
1181 enerd->term[F_EKIN] = trace(ekind->ekin);
1184 else if (bExchanged)
1186 wallcycle_stop(wcycle, ewcUPDATE);
1187 /* We need the kinetic energy at minus the half step for determining
1188 * the full step kinetic energy and possibly for T-coupling.*/
1189 /* This may not be quite working correctly yet . . . . */
1190 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
1191 wcycle, enerd, NULL, NULL, NULL, NULL, mu_tot,
1192 constr, NULL, FALSE, state->box,
1193 NULL, &bSumEkinhOld,
1194 CGLO_GSTAT | CGLO_TEMPERATURE);
1195 wallcycle_start(wcycle, ewcUPDATE);
1198 /* if it's the initial step, we performed this first step just to get the constraint virial */
1199 if (ir->eI == eiVV && bInitStep)
1201 copy_rvecn(vbuf, state->v, 0, state->natoms);
1204 wallcycle_stop(wcycle, ewcUPDATE);
1207 /* compute the conserved quantity */
1210 saved_conserved_quantity = compute_conserved_from_auxiliary(ir, state, &MassQ);
1213 last_ekin = enerd->term[F_EKIN];
1215 if ((ir->eDispCorr != edispcEnerPres) && (ir->eDispCorr != edispcAllEnerPres))
1217 saved_conserved_quantity -= enerd->term[F_DISPCORR];
1219 /* sum up the foreign energy and dhdl terms for vv. currently done every step so that dhdl is correct in the .edr */
1220 if (ir->efep != efepNO && !bRerunMD)
1222 sum_dhdl(enerd, state->lambda, ir->fepvals);
1226 /* ######## END FIRST UPDATE STEP ############## */
1227 /* ######## If doing VV, we now have v(dt) ###### */
1230 /* perform extended ensemble sampling in lambda - we don't
1231 actually move to the new state before outputting
1232 statistics, but if performing simulated tempering, we
1233 do update the velocities and the tau_t. */
1235 lamnew = ExpandedEnsembleDynamics(fplog, ir, enerd, state, &MassQ, state->fep_state, &state->dfhist, step, state->v, mdatoms);
1236 /* history is maintained in state->dfhist, but state_global is what is sent to trajectory and log output */
1237 copy_df_history(&state_global->dfhist, &state->dfhist);
1240 /* Now we have the energies and forces corresponding to the
1241 * coordinates at time t. We must output all of this before
1244 do_md_trajectory_writing(fplog, cr, nfile, fnm, step, step_rel, t,
1245 ir, state, state_global, top_global, fr,
1246 outf, mdebin, ekind, f,
1248 bCPT, bRerunMD, bLastStep, (Flags & MD_CONFOUT),
1250 /* Check if IMD step and do IMD communication, if bIMD is TRUE. */
1251 bIMDstep = do_IMD(ir->bIMD, step, cr, bNS, state->box, state->x, ir, t, wcycle);
1253 /* kludge -- virial is lost with restart for MTTK NPT control. Must reload (saved earlier). */
1254 if (startingFromCheckpoint && bTrotter)
1256 copy_mat(state->svir_prev, shake_vir);
1257 copy_mat(state->fvir_prev, force_vir);
1260 elapsed_time = walltime_accounting_get_current_elapsed_time(walltime_accounting);
1262 /* Check whether everything is still allright */
1263 if (((int)gmx_get_stop_condition() > handled_stop_condition)
1269 /* this is just make gs.sig compatible with the hack
1270 of sending signals around by MPI_Reduce with together with
1272 if (gmx_get_stop_condition() == gmx_stop_cond_next_ns)
1274 gs.sig[eglsSTOPCOND] = 1;
1276 if (gmx_get_stop_condition() == gmx_stop_cond_next)
1278 gs.sig[eglsSTOPCOND] = -1;
1280 /* < 0 means stop at next step, > 0 means stop at next NS step */
1284 "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
1285 gmx_get_signal_name(),
1286 gs.sig[eglsSTOPCOND] == 1 ? "NS " : "");
1290 "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
1291 gmx_get_signal_name(),
1292 gs.sig[eglsSTOPCOND] == 1 ? "NS " : "");
1294 handled_stop_condition = (int)gmx_get_stop_condition();
1296 else if (MASTER(cr) && (bNS || ir->nstlist <= 0) &&
1297 (max_hours > 0 && elapsed_time > max_hours*60.0*60.0*0.99) &&
1298 gs.sig[eglsSTOPCOND] == 0 && gs.set[eglsSTOPCOND] == 0)
1300 /* Signal to terminate the run */
1301 gs.sig[eglsSTOPCOND] = 1;
1304 fprintf(fplog, "\nStep %s: Run time exceeded %.3f hours, will terminate the run\n", gmx_step_str(step, sbuf), max_hours*0.99);
1306 fprintf(stderr, "\nStep %s: Run time exceeded %.3f hours, will terminate the run\n", gmx_step_str(step, sbuf), max_hours*0.99);
1309 if (bResetCountersHalfMaxH && MASTER(cr) &&
1310 elapsed_time > max_hours*60.0*60.0*0.495)
1312 /* Set flag that will communicate the signal to all ranks in the simulation */
1313 gs.sig[eglsRESETCOUNTERS] = 1;
1316 /* In parallel we only have to check for checkpointing in steps
1317 * where we do global communication,
1318 * otherwise the other nodes don't know.
1320 if (MASTER(cr) && ((bGStat || !PAR(cr)) &&
1323 elapsed_time >= nchkpt*cpt_period*60.0)) &&
1324 gs.set[eglsCHKPT] == 0)
1326 gs.sig[eglsCHKPT] = 1;
1329 /* ######### START SECOND UPDATE STEP ################# */
1331 /* at the start of step, randomize or scale the velocities ((if vv. Restriction of Andersen controlled
1334 if (ETC_ANDERSEN(ir->etc)) /* keep this outside of update_tcouple because of the extra info required to pass */
1336 gmx_bool bIfRandomize;
1337 bIfRandomize = update_randomize_velocities(ir, step, cr, mdatoms, state, upd, constr);
1338 /* if we have constraints, we have to remove the kinetic energy parallel to the bonds */
1339 if (constr && bIfRandomize)
1341 update_constraints(fplog, step, NULL, ir, mdatoms,
1342 state, fr->bMolPBC, graph, f,
1343 &top->idef, tmp_vir,
1344 cr, nrnb, wcycle, upd, constr,
1348 /* Box is changed in update() when we do pressure coupling,
1349 * but we should still use the old box for energy corrections and when
1350 * writing it to the energy file, so it matches the trajectory files for
1351 * the same timestep above. Make a copy in a separate array.
1353 copy_mat(state->box, lastbox);
1357 if (!bRerunMD || rerun_fr.bV || bForceUpdate)
1359 wallcycle_start(wcycle, ewcUPDATE);
1360 /* UPDATE PRESSURE VARIABLES IN TROTTER FORMULATION WITH CONSTRAINTS */
1363 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ3);
1364 /* We can only do Berendsen coupling after we have summed
1365 * the kinetic energy or virial. Since the happens
1366 * in global_state after update, we should only do it at
1367 * step % nstlist = 1 with bGStatEveryStep=FALSE.
1372 update_tcouple(step, ir, state, ekind, &MassQ, mdatoms);
1373 update_pcouple(fplog, step, ir, state, pcoupl_mu, M, bInitStep);
1378 /* velocity half-step update */
1379 update_coords(fplog, step, ir, mdatoms, state, f, fcd,
1380 ekind, M, upd, etrtVELOCITY2,
1384 /* Above, initialize just copies ekinh into ekin,
1385 * it doesn't copy position (for VV),
1386 * and entire integrator for MD.
1389 if (ir->eI == eiVVAK)
1391 /* We probably only need md->homenr, not state->natoms */
1392 if (state->natoms > cbuf_nalloc)
1394 cbuf_nalloc = state->natoms;
1395 srenew(cbuf, cbuf_nalloc);
1397 copy_rvecn(state->x, cbuf, 0, state->natoms);
1400 update_coords(fplog, step, ir, mdatoms, state, f, fcd,
1401 ekind, M, upd, etrtPOSITION, cr, constr);
1402 wallcycle_stop(wcycle, ewcUPDATE);
1404 update_constraints(fplog, step, &dvdl_constr, ir, mdatoms, state,
1405 fr->bMolPBC, graph, f,
1406 &top->idef, shake_vir,
1407 cr, nrnb, wcycle, upd, constr,
1410 if (ir->eI == eiVVAK)
1412 /* erase F_EKIN and F_TEMP here? */
1413 /* just compute the kinetic energy at the half step to perform a trotter step */
1414 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
1415 wcycle, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
1416 constr, NULL, FALSE, lastbox,
1417 NULL, &bSumEkinhOld,
1418 (bGStat ? CGLO_GSTAT : 0) | CGLO_TEMPERATURE
1420 wallcycle_start(wcycle, ewcUPDATE);
1421 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ4);
1422 /* now we know the scaling, we can compute the positions again again */
1423 copy_rvecn(cbuf, state->x, 0, state->natoms);
1425 update_coords(fplog, step, ir, mdatoms, state, f, fcd,
1426 ekind, M, upd, etrtPOSITION, cr, constr);
1427 wallcycle_stop(wcycle, ewcUPDATE);
1429 /* do we need an extra constraint here? just need to copy out of state->v to upd->xp? */
1430 /* are the small terms in the shake_vir here due
1431 * to numerical errors, or are they important
1432 * physically? I'm thinking they are just errors, but not completely sure.
1433 * For now, will call without actually constraining, constr=NULL*/
1434 update_constraints(fplog, step, NULL, ir, mdatoms,
1435 state, fr->bMolPBC, graph, f,
1436 &top->idef, tmp_vir,
1437 cr, nrnb, wcycle, upd, NULL,
1442 /* this factor or 2 correction is necessary
1443 because half of the constraint force is removed
1444 in the vv step, so we have to double it. See
1445 the Redmine issue #1255. It is not yet clear
1446 if the factor of 2 is exact, or just a very
1447 good approximation, and this will be
1448 investigated. The next step is to see if this
1449 can be done adding a dhdl contribution from the
1450 rattle step, but this is somewhat more
1451 complicated with the current code. Will be
1452 investigated, hopefully for 4.6.3. However,
1453 this current solution is much better than
1454 having it completely wrong.
1456 enerd->term[F_DVDL_CONSTR] += 2*dvdl_constr;
1460 enerd->term[F_DVDL_CONSTR] += dvdl_constr;
1465 /* Need to unshift here */
1466 unshift_self(graph, state->box, state->x);
1471 wallcycle_start(wcycle, ewcVSITECONSTR);
1474 shift_self(graph, state->box, state->x);
1476 construct_vsites(vsite, state->x, ir->delta_t, state->v,
1477 top->idef.iparams, top->idef.il,
1478 fr->ePBC, fr->bMolPBC, cr, state->box);
1482 unshift_self(graph, state->box, state->x);
1484 wallcycle_stop(wcycle, ewcVSITECONSTR);
1487 /* ############## IF NOT VV, Calculate globals HERE ############ */
1488 /* With Leap-Frog we can skip compute_globals at
1489 * non-communication steps, but we need to calculate
1490 * the kinetic energy one step before communication.
1492 if (bGStat || (!EI_VV(ir->eI) && do_per_step(step+1, nstglobalcomm)))
1494 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
1495 wcycle, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
1497 (step_rel % gs.nstms == 0) &&
1498 (multisim_nsteps < 0 || (step_rel < multisim_nsteps)),
1500 &totalNumberOfBondedInteractions, &bSumEkinhOld,
1501 (bGStat ? CGLO_GSTAT : 0)
1502 | (!EI_VV(ir->eI) || bRerunMD ? CGLO_ENERGY : 0)
1503 | (!EI_VV(ir->eI) && bStopCM ? CGLO_STOPCM : 0)
1504 | (!EI_VV(ir->eI) ? CGLO_TEMPERATURE : 0)
1505 | (!EI_VV(ir->eI) || bRerunMD ? CGLO_PRESSURE : 0)
1507 | (shouldCheckNumberOfBondedInteractions ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS : 0)
1509 checkNumberOfBondedInteractions(fplog, cr, totalNumberOfBondedInteractions,
1510 top_global, top, state,
1511 &shouldCheckNumberOfBondedInteractions);
1514 /* ############# END CALC EKIN AND PRESSURE ################# */
1516 /* Note: this is OK, but there are some numerical precision issues with using the convergence of
1517 the virial that should probably be addressed eventually. state->veta has better properies,
1518 but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could
1519 generate the new shake_vir, but test the veta value for convergence. This will take some thought. */
1521 if (ir->efep != efepNO && (!EI_VV(ir->eI) || bRerunMD))
1523 /* Sum up the foreign energy and dhdl terms for md and sd.
1524 Currently done every step so that dhdl is correct in the .edr */
1525 sum_dhdl(enerd, state->lambda, ir->fepvals);
1527 update_box(fplog, step, ir, mdatoms, state, f,
1528 pcoupl_mu, nrnb, upd);
1530 /* ################# END UPDATE STEP 2 ################# */
1531 /* #### We now have r(t+dt) and v(t+dt/2) ############# */
1533 /* The coordinates (x) were unshifted in update */
1536 /* We will not sum ekinh_old,
1537 * so signal that we still have to do it.
1539 bSumEkinhOld = TRUE;
1542 /* ######### BEGIN PREPARING EDR OUTPUT ########### */
1544 /* use the directly determined last velocity, not actually the averaged half steps */
1545 if (bTrotter && ir->eI == eiVV)
1547 enerd->term[F_EKIN] = last_ekin;
1549 enerd->term[F_ETOT] = enerd->term[F_EPOT] + enerd->term[F_EKIN];
1553 enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + saved_conserved_quantity;
1557 enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + compute_conserved_from_auxiliary(ir, state, &MassQ);
1559 /* ######### END PREPARING EDR OUTPUT ########### */
1564 if (fplog && do_log && bDoExpanded)
1566 /* only needed if doing expanded ensemble */
1567 PrintFreeEnergyInfoToFile(fplog, ir->fepvals, ir->expandedvals, ir->bSimTemp ? ir->simtempvals : NULL,
1568 &state_global->dfhist, state->fep_state, ir->nstlog, step);
1572 upd_mdebin(mdebin, bDoDHDL, bCalcEnerStep,
1573 t, mdatoms->tmass, enerd, state,
1574 ir->fepvals, ir->expandedvals, lastbox,
1575 shake_vir, force_vir, total_vir, pres,
1576 ekind, mu_tot, constr);
1580 upd_mdebin_step(mdebin);
1583 gmx_bool do_dr = do_per_step(step, ir->nstdisreout);
1584 gmx_bool do_or = do_per_step(step, ir->nstorireout);
1586 print_ebin(mdoutf_get_fp_ene(outf), do_ene, do_dr, do_or, do_log ? fplog : NULL,
1588 eprNORMAL, mdebin, fcd, groups, &(ir->opts));
1592 pull_print_output(ir->pull_work, step, t);
1595 if (do_per_step(step, ir->nstlog))
1597 if (fflush(fplog) != 0)
1599 gmx_fatal(FARGS, "Cannot flush logfile - maybe you are out of disk space?");
1605 /* Have to do this part _after_ outputting the logfile and the edr file */
1606 /* Gets written into the state at the beginning of next loop*/
1607 state->fep_state = lamnew;
1609 /* Print the remaining wall clock time for the run */
1610 if (MULTIMASTER(cr) &&
1611 (do_verbose || gmx_got_usr_signal()) &&
1616 fprintf(stderr, "\n");
1618 print_time(stderr, walltime_accounting, step, ir, cr);
1621 /* Ion/water position swapping.
1622 * Not done in last step since trajectory writing happens before this call
1623 * in the MD loop and exchanges would be lost anyway. */
1624 bNeedRepartition = FALSE;
1625 if ((ir->eSwapCoords != eswapNO) && (step > 0) && !bLastStep &&
1626 do_per_step(step, ir->swap->nstswap))
1628 bNeedRepartition = do_swapcoords(cr, step, t, ir, wcycle,
1629 bRerunMD ? rerun_fr.x : state->x,
1630 bRerunMD ? rerun_fr.box : state->box,
1631 top_global, MASTER(cr) && bVerbose, bRerunMD);
1633 if (bNeedRepartition && DOMAINDECOMP(cr))
1635 dd_collect_state(cr->dd, state, state_global);
1639 /* Replica exchange */
1643 bExchanged = replica_exchange(fplog, cr, repl_ex,
1644 state_global, enerd,
1648 if ( (bExchanged || bNeedRepartition) && DOMAINDECOMP(cr) )
1650 dd_partition_system(fplog, step, cr, TRUE, 1,
1651 state_global, top_global, ir,
1652 state, &f, mdatoms, top, fr,
1654 nrnb, wcycle, FALSE);
1655 shouldCheckNumberOfBondedInteractions = true;
1660 startingFromCheckpoint = FALSE;
1662 /* ####### SET VARIABLES FOR NEXT ITERATION IF THEY STILL NEED IT ###### */
1663 /* With all integrators, except VV, we need to retain the pressure
1664 * at the current step for coupling at the next step.
1666 if ((state->flags & (1<<estPRES_PREV)) &&
1668 (ir->nstpcouple > 0 && step % ir->nstpcouple == 0)))
1670 /* Store the pressure in t_state for pressure coupling
1671 * at the next MD step.
1673 copy_mat(pres, state->pres_prev);
1676 /* ####### END SET VARIABLES FOR NEXT ITERATION ###### */
1678 if ( (membed != NULL) && (!bLastStep) )
1680 rescale_membed(step_rel, membed, state_global->x);
1687 /* read next frame from input trajectory */
1688 bNotLastFrame = read_next_frame(oenv, status, &rerun_fr);
1693 rerun_parallel_comm(cr, &rerun_fr, &bNotLastFrame);
1697 cycles = wallcycle_stop(wcycle, ewcSTEP);
1698 if (DOMAINDECOMP(cr) && wcycle)
1700 dd_cycles_add(cr->dd, cycles, ddCyclStep);
1703 if (!bRerunMD || !rerun_fr.bStep)
1705 /* increase the MD step number */
1710 /* TODO make a counter-reset module */
1711 /* If it is time to reset counters, set a flag that remains
1712 true until counters actually get reset */
1713 if (step_rel == wcycle_get_reset_counters(wcycle) ||
1714 gs.set[eglsRESETCOUNTERS] != 0)
1716 if (pme_loadbal_is_active(pme_loadbal))
1718 /* Do not permit counter reset while PME load
1719 * balancing is active. The only purpose for resetting
1720 * counters is to measure reliable performance data,
1721 * and that can't be done before balancing
1724 * TODO consider fixing this by delaying the reset
1725 * until after load balancing completes,
1726 * e.g. https://gerrit.gromacs.org/#/c/4964/2 */
1727 gmx_fatal(FARGS, "PME tuning was still active when attempting to "
1728 "reset mdrun counters at step %" GMX_PRId64 ". Try "
1729 "resetting counters later in the run, e.g. with gmx "
1730 "mdrun -resetstep.", step);
1732 reset_all_counters(fplog, cr, step, &step_rel, ir, wcycle, nrnb, walltime_accounting,
1733 use_GPU(fr->nbv) ? fr->nbv : NULL);
1734 wcycle_set_reset_counters(wcycle, -1);
1735 if (!(cr->duty & DUTY_PME))
1737 /* Tell our PME node to reset its counters */
1738 gmx_pme_send_resetcounters(cr, step);
1740 /* Correct max_hours for the elapsed time */
1741 max_hours -= elapsed_time/(60.0*60.0);
1742 /* If mdrun -maxh -resethway was active, it can only trigger once */
1743 bResetCountersHalfMaxH = FALSE; /* TODO move this to where gs.sig[eglsRESETCOUNTERS] is set */
1744 /* Reset can only happen once, so clear the triggering flag. */
1745 gs.set[eglsRESETCOUNTERS] = 0;
1748 /* If bIMD is TRUE, the master updates the IMD energy record and sends positions to VMD client */
1749 IMD_prep_energies_send_positions(ir->bIMD && MASTER(cr), bIMDstep, ir->imd, enerd, step, bCalcEner, wcycle);
1752 /* End of main MD loop */
1754 /* Closing TNG files can include compressing data. Therefore it is good to do that
1755 * before stopping the time measurements. */
1756 mdoutf_tng_close(outf);
1758 /* Stop measuring walltime */
1759 walltime_accounting_end(walltime_accounting);
1761 if (bRerunMD && MASTER(cr))
1766 if (!(cr->duty & DUTY_PME))
1768 /* Tell the PME only node to finish */
1769 gmx_pme_send_finish(cr);
1774 if (ir->nstcalcenergy > 0 && !bRerunMD)
1776 print_ebin(mdoutf_get_fp_ene(outf), FALSE, FALSE, FALSE, fplog, step, t,
1777 eprAVER, mdebin, fcd, groups, &(ir->opts));
1785 pme_loadbal_done(pme_loadbal, cr, fplog, use_GPU(fr->nbv));
1788 done_shellfc(fplog, shellfc, step_rel);
1790 if (repl_ex_nst > 0 && MASTER(cr))
1792 print_replica_exchange_statistics(fplog, repl_ex);
1795 /* IMD cleanup, if bIMD is TRUE. */
1796 IMD_finalize(ir->bIMD, ir->imd);
1798 walltime_accounting_set_nsteps_done(walltime_accounting, step_rel);