Merge branch release-2016
[gromacs/AngularHB.git] / src / programs / mdrun / md.cpp
blob27722563a45771d416464e64c1449596d5f75433
1 /*
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.
37 #include "gmxpre.h"
39 #include "md.h"
41 #include "config.h"
43 #include <math.h>
44 #include <stdio.h>
45 #include <stdlib.h>
47 #include <algorithm>
49 #include "thread_mpi/threads.h"
51 #include "gromacs/commandline/filenm.h"
52 #include "gromacs/domdec/domdec.h"
53 #include "gromacs/domdec/domdec_network.h"
54 #include "gromacs/domdec/domdec_struct.h"
55 #include "gromacs/ewald/pme.h"
56 #include "gromacs/ewald/pme-load-balancing.h"
57 #include "gromacs/fileio/trxio.h"
58 #include "gromacs/gmxlib/network.h"
59 #include "gromacs/gmxlib/nrnb.h"
60 #include "gromacs/gpu_utils/gpu_utils.h"
61 #include "gromacs/imd/imd.h"
62 #include "gromacs/listed-forces/manage-threading.h"
63 #include "gromacs/math/functions.h"
64 #include "gromacs/math/utilities.h"
65 #include "gromacs/math/vec.h"
66 #include "gromacs/math/vectypes.h"
67 #include "gromacs/mdlib/compute_io.h"
68 #include "gromacs/mdlib/constr.h"
69 #include "gromacs/mdlib/ebin.h"
70 #include "gromacs/mdlib/force.h"
71 #include "gromacs/mdlib/force_flags.h"
72 #include "gromacs/mdlib/forcerec.h"
73 #include "gromacs/mdlib/md_support.h"
74 #include "gromacs/mdlib/mdatoms.h"
75 #include "gromacs/mdlib/mdebin.h"
76 #include "gromacs/mdlib/mdoutf.h"
77 #include "gromacs/mdlib/mdrun.h"
78 #include "gromacs/mdlib/nb_verlet.h"
79 #include "gromacs/mdlib/nbnxn_gpu_data_mgmt.h"
80 #include "gromacs/mdlib/ns.h"
81 #include "gromacs/mdlib/shellfc.h"
82 #include "gromacs/mdlib/sighandler.h"
83 #include "gromacs/mdlib/sim_util.h"
84 #include "gromacs/mdlib/simulationsignal.h"
85 #include "gromacs/mdlib/tgroup.h"
86 #include "gromacs/mdlib/trajectory_writing.h"
87 #include "gromacs/mdlib/update.h"
88 #include "gromacs/mdlib/vcm.h"
89 #include "gromacs/mdlib/vsite.h"
90 #include "gromacs/mdtypes/commrec.h"
91 #include "gromacs/mdtypes/df_history.h"
92 #include "gromacs/mdtypes/energyhistory.h"
93 #include "gromacs/mdtypes/fcdata.h"
94 #include "gromacs/mdtypes/forcerec.h"
95 #include "gromacs/mdtypes/group.h"
96 #include "gromacs/mdtypes/inputrec.h"
97 #include "gromacs/mdtypes/interaction_const.h"
98 #include "gromacs/mdtypes/md_enums.h"
99 #include "gromacs/mdtypes/mdatom.h"
100 #include "gromacs/mdtypes/state.h"
101 #include "gromacs/pbcutil/mshift.h"
102 #include "gromacs/pbcutil/pbc.h"
103 #include "gromacs/pulling/pull.h"
104 #include "gromacs/swap/swapcoords.h"
105 #include "gromacs/timing/wallcycle.h"
106 #include "gromacs/timing/walltime_accounting.h"
107 #include "gromacs/topology/atoms.h"
108 #include "gromacs/topology/idef.h"
109 #include "gromacs/topology/mtop_util.h"
110 #include "gromacs/topology/topology.h"
111 #include "gromacs/trajectory/trajectoryframe.h"
112 #include "gromacs/utility/basedefinitions.h"
113 #include "gromacs/utility/cstringutil.h"
114 #include "gromacs/utility/fatalerror.h"
115 #include "gromacs/utility/logger.h"
116 #include "gromacs/utility/real.h"
117 #include "gromacs/utility/smalloc.h"
119 #include "deform.h"
120 #include "membed.h"
121 #include "repl_ex.h"
123 #ifdef GMX_FAHCORE
124 #include "corewrap.h"
125 #endif
127 using gmx::SimulationSignaller;
129 /*! \brief Check whether bonded interactions are missing, if appropriate
131 * \param[in] fplog Log file pointer
132 * \param[in] cr Communication object
133 * \param[in] totalNumberOfBondedInteractions Result of the global reduction over the number of bonds treated in each domain
134 * \param[in] top_global Global topology for the error message
135 * \param[in] top_local Local topology for the error message
136 * \param[in] state Global state for the error message
137 * \param[inout] shouldCheckNumberOfBondedInteractions Whether we should do the check.
139 * \return Nothing, except that shouldCheckNumberOfBondedInteractions
140 * is always set to false after exit.
142 static void checkNumberOfBondedInteractions(FILE *fplog, t_commrec *cr, int totalNumberOfBondedInteractions,
143 gmx_mtop_t *top_global, gmx_localtop_t *top_local, t_state *state,
144 bool *shouldCheckNumberOfBondedInteractions)
146 if (*shouldCheckNumberOfBondedInteractions)
148 if (totalNumberOfBondedInteractions != cr->dd->nbonded_global)
150 dd_print_missing_interactions(fplog, cr, totalNumberOfBondedInteractions, top_global, top_local, state); // Does not return
152 *shouldCheckNumberOfBondedInteractions = false;
156 static void reset_all_counters(FILE *fplog, const gmx::MDLogger &mdlog, t_commrec *cr,
157 gmx_int64_t step,
158 gmx_int64_t *step_rel, t_inputrec *ir,
159 gmx_wallcycle_t wcycle, t_nrnb *nrnb,
160 gmx_walltime_accounting_t walltime_accounting,
161 struct nonbonded_verlet_t *nbv)
163 char sbuf[STEPSTRSIZE];
165 /* Reset all the counters related to performance over the run */
166 GMX_LOG(mdlog.warning).asParagraph().appendTextFormatted(
167 "step %s: resetting all time and cycle counters",
168 gmx_step_str(step, sbuf));
170 if (use_GPU(nbv))
172 nbnxn_gpu_reset_timings(nbv);
173 resetGpuProfiler();
176 wallcycle_stop(wcycle, ewcRUN);
177 wallcycle_reset_all(wcycle);
178 if (DOMAINDECOMP(cr))
180 reset_dd_statistics_counters(cr->dd);
182 init_nrnb(nrnb);
183 ir->init_step += *step_rel;
184 ir->nsteps -= *step_rel;
185 *step_rel = 0;
186 wallcycle_start(wcycle, ewcRUN);
187 walltime_accounting_start(walltime_accounting);
188 print_date_and_time(fplog, cr->nodeid, "Restarted time", gmx_gettime());
191 /*! \libinternal
192 \copydoc integrator_t (FILE *fplog, t_commrec *cr, const gmx::MDLogger &mdlog,
193 int nfile, const t_filenm fnm[],
194 const gmx_output_env_t *oenv, gmx_bool bVerbose,
195 int nstglobalcomm,
196 gmx_vsite_t *vsite, gmx_constr_t constr,
197 int stepout,
198 t_inputrec *inputrec,
199 gmx_mtop_t *top_global, t_fcdata *fcd,
200 t_state *state_global,
201 t_mdatoms *mdatoms,
202 t_nrnb *nrnb, gmx_wallcycle_t wcycle,
203 gmx_edsam_t ed,
204 t_forcerec *fr,
205 int repl_ex_nst, int repl_ex_nex, int repl_ex_seed,
206 real cpt_period, real max_hours,
207 int imdport,
208 unsigned long Flags,
209 gmx_walltime_accounting_t walltime_accounting)
211 double gmx::do_md(FILE *fplog, t_commrec *cr, const gmx::MDLogger &mdlog,
212 int nfile, const t_filenm fnm[],
213 const gmx_output_env_t *oenv, gmx_bool bVerbose,
214 int nstglobalcomm,
215 gmx_vsite_t *vsite, gmx_constr_t constr,
216 int stepout, t_inputrec *ir,
217 gmx_mtop_t *top_global,
218 t_fcdata *fcd,
219 t_state *state_global,
220 t_mdatoms *mdatoms,
221 t_nrnb *nrnb, gmx_wallcycle_t wcycle,
222 gmx_edsam_t ed, t_forcerec *fr,
223 int repl_ex_nst, int repl_ex_nex, int repl_ex_seed,
224 gmx_membed_t *membed,
225 real cpt_period, real max_hours,
226 int imdport,
227 unsigned long Flags,
228 gmx_walltime_accounting_t walltime_accounting)
230 gmx_mdoutf_t outf = NULL;
231 gmx_int64_t step, step_rel;
232 double elapsed_time;
233 double t, t0, lam0[efptNR];
234 gmx_bool bGStatEveryStep, bGStat, bCalcVir, bCalcEnerStep, bCalcEner;
235 gmx_bool bNS, bNStList, bSimAnn, bStopCM, bRerunMD,
236 bFirstStep, startingFromCheckpoint, bInitStep, bLastStep = FALSE,
237 bBornRadii, bUsingEnsembleRestraints;
238 gmx_bool bDoDHDL = FALSE, bDoFEP = FALSE, bDoExpanded = FALSE;
239 gmx_bool do_ene, do_log, do_verbose, bRerunWarnNoV = TRUE,
240 bForceUpdate = FALSE, bCPT;
241 gmx_bool bMasterState;
242 int force_flags, cglo_flags;
243 tensor force_vir, shake_vir, total_vir, tmp_vir, pres;
244 int i, m;
245 t_trxstatus *status;
246 rvec mu_tot;
247 t_vcm *vcm;
248 matrix pcoupl_mu, M;
249 t_trxframe rerun_fr;
250 gmx_repl_ex_t repl_ex = NULL;
251 int nchkpt = 1;
252 gmx_localtop_t *top;
253 t_mdebin *mdebin = NULL;
254 t_state *state = NULL;
255 gmx_enerdata_t *enerd;
256 rvec *f = NULL;
257 gmx_global_stat_t gstat;
258 gmx_update_t *upd = NULL;
259 t_graph *graph = NULL;
260 gmx_groups_t *groups;
261 gmx_ekindata_t *ekind;
262 gmx_shellfc_t *shellfc;
263 gmx_bool bSumEkinhOld, bDoReplEx, bExchanged, bNeedRepartition;
264 gmx_bool bResetCountersHalfMaxH = FALSE;
265 gmx_bool bTemp, bPres, bTrotter;
266 real dvdl_constr;
267 rvec *cbuf = NULL;
268 int cbuf_nalloc = 0;
269 matrix lastbox;
270 int lamnew = 0;
271 /* for FEP */
272 int nstfep = 0;
273 double cycles;
274 real saved_conserved_quantity = 0;
275 real last_ekin = 0;
276 t_extmass MassQ;
277 int **trotter_seq;
278 char sbuf[STEPSTRSIZE], sbuf2[STEPSTRSIZE];
279 int handled_stop_condition = gmx_stop_cond_none; /* compare to get_stop_condition*/
282 /* PME load balancing data for GPU kernels */
283 pme_load_balancing_t *pme_loadbal = NULL;
284 gmx_bool bPMETune = FALSE;
285 gmx_bool bPMETunePrinting = FALSE;
287 /* Interactive MD */
288 gmx_bool bIMDstep = FALSE;
290 #ifdef GMX_FAHCORE
291 /* Temporary addition for FAHCORE checkpointing */
292 int chkpt_ret;
293 #endif
294 /* Domain decomposition could incorrectly miss a bonded
295 interaction, but checking for that requires a global
296 communication stage, which does not otherwise happen in DD
297 code. So we do that alongside the first global energy reduction
298 after a new DD is made. These variables handle whether the
299 check happens, and the result it returns. */
300 bool shouldCheckNumberOfBondedInteractions = false;
301 int totalNumberOfBondedInteractions = -1;
303 SimulationSignals signals;
304 // Most global communnication stages don't propagate mdrun
305 // signals, and will use this object to achieve that.
306 SimulationSignaller nullSignaller(nullptr, nullptr, false, false);
308 /* Check for special mdrun options */
309 bRerunMD = (Flags & MD_RERUN);
310 if (Flags & MD_RESETCOUNTERSHALFWAY)
312 if (ir->nsteps > 0)
314 /* Signal to reset the counters half the simulation steps. */
315 wcycle_set_reset_counters(wcycle, ir->nsteps/2);
317 /* Signal to reset the counters halfway the simulation time. */
318 bResetCountersHalfMaxH = (max_hours > 0);
321 /* md-vv uses averaged full step velocities for T-control
322 md-vv-avek uses averaged half step velocities for T-control (but full step ekin for P control)
323 md uses averaged half step kinetic energies to determine temperature unless defined otherwise by GMX_EKIN_AVE_VEL; */
324 bTrotter = (EI_VV(ir->eI) && (inputrecNptTrotter(ir) || inputrecNphTrotter(ir) || inputrecNvtTrotter(ir)));
326 if (bRerunMD)
328 /* Since we don't know if the frames read are related in any way,
329 * rebuild the neighborlist at every step.
331 ir->nstlist = 1;
332 ir->nstcalcenergy = 1;
333 nstglobalcomm = 1;
336 nstglobalcomm = check_nstglobalcomm(mdlog, nstglobalcomm, ir);
337 bGStatEveryStep = (nstglobalcomm == 1);
339 if (bRerunMD)
341 ir->nstxout_compressed = 0;
343 groups = &top_global->groups;
345 if (ir->eSwapCoords != eswapNO)
347 /* Initialize ion swapping code */
348 init_swapcoords(fplog, bVerbose, ir, opt2fn_master("-swap", nfile, fnm, cr),
349 top_global, state_global->x, state_global->box, &state_global->swapstate, cr, oenv, Flags);
352 /* Initial values */
353 init_md(fplog, cr, ir, oenv, &t, &t0, state_global->lambda,
354 &(state_global->fep_state), lam0,
355 nrnb, top_global, &upd,
356 nfile, fnm, &outf, &mdebin,
357 force_vir, shake_vir, mu_tot, &bSimAnn, &vcm, Flags, wcycle);
359 clear_mat(total_vir);
360 clear_mat(pres);
361 /* Energy terms and groups */
362 snew(enerd, 1);
363 init_enerdata(top_global->groups.grps[egcENER].nr, ir->fepvals->n_lambda,
364 enerd);
365 if (DOMAINDECOMP(cr))
367 f = NULL;
369 else
371 snew(f, top_global->natoms);
374 /* Kinetic energy data */
375 snew(ekind, 1);
376 init_ekindata(fplog, top_global, &(ir->opts), ekind);
377 /* Copy the cos acceleration to the groups struct */
378 ekind->cosacc.cos_accel = ir->cos_accel;
380 gstat = global_stat_init(ir);
382 /* Check for polarizable models and flexible constraints */
383 shellfc = init_shell_flexcon(fplog,
384 top_global, n_flexible_constraints(constr),
385 ir->nstcalcenergy, DOMAINDECOMP(cr));
387 if (shellfc && ir->nstcalcenergy != 1)
389 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);
391 if (shellfc && DOMAINDECOMP(cr))
393 gmx_fatal(FARGS, "Shell particles are not implemented with domain decomposition, use a single rank");
396 if (inputrecDeform(ir))
398 tMPI_Thread_mutex_lock(&deform_init_box_mutex);
399 set_deform_reference_box(upd,
400 deform_init_init_step_tpx,
401 deform_init_box_tpx);
402 tMPI_Thread_mutex_unlock(&deform_init_box_mutex);
406 double io = compute_io(ir, top_global->natoms, groups, mdebin->ebin->nener, 1);
407 if ((io > 2000) && MASTER(cr))
409 fprintf(stderr,
410 "\nWARNING: This run will generate roughly %.0f Mb of data\n\n",
411 io);
415 if (DOMAINDECOMP(cr))
417 top = dd_init_local_top(top_global);
419 snew(state, 1);
420 dd_init_local_state(cr->dd, state_global, state);
422 else
424 top = gmx_mtop_generate_local_top(top_global, ir->efep != efepNO);
426 state = serial_init_local_state(state_global);
428 atoms2md(top_global, ir, 0, NULL, top_global->natoms, mdatoms);
430 if (vsite)
432 set_vsite_top(vsite, top, mdatoms, cr);
435 if (ir->ePBC != epbcNONE && !fr->bMolPBC)
437 graph = mk_graph(fplog, &(top->idef), 0, top_global->natoms, FALSE, FALSE);
440 if (shellfc)
442 make_local_shells(cr, mdatoms, shellfc);
445 setup_bonded_threading(fr, &top->idef);
447 update_realloc(upd, state->nalloc);
450 /* Set up interactive MD (IMD) */
451 init_IMD(ir, cr, top_global, fplog, ir->nstcalcenergy, state_global->x,
452 nfile, fnm, oenv, imdport, Flags);
454 if (DOMAINDECOMP(cr))
456 /* Distribute the charge groups over the nodes from the master node */
457 dd_partition_system(fplog, ir->init_step, cr, TRUE, 1,
458 state_global, top_global, ir,
459 state, &f, mdatoms, top, fr,
460 vsite, constr,
461 nrnb, NULL, FALSE);
462 shouldCheckNumberOfBondedInteractions = true;
463 update_realloc(upd, state->nalloc);
466 update_mdatoms(mdatoms, state->lambda[efptMASS]);
468 startingFromCheckpoint = Flags & MD_STARTFROMCPT;
470 if (ir->bExpanded)
472 init_expanded_ensemble(startingFromCheckpoint, ir, &state->dfhist);
475 if (MASTER(cr))
477 if (startingFromCheckpoint)
479 /* Update mdebin with energy history if appending to output files */
480 if (Flags & MD_APPENDFILES)
482 restore_energyhistory_from_state(mdebin, state_global->enerhist);
484 else
486 /* We might have read an energy history from checkpoint,
487 * free the allocated memory and reset the counts.
489 done_energyhistory(state_global->enerhist);
490 init_energyhistory(state_global->enerhist);
493 /* Set the initial energy history in state by updating once */
494 update_energyhistory(state_global->enerhist, mdebin);
497 /* Initialize constraints */
498 if (constr && !DOMAINDECOMP(cr))
500 set_constraints(constr, top, ir, mdatoms, cr);
503 if (repl_ex_nst > 0 && MASTER(cr))
505 repl_ex = init_replica_exchange(fplog, cr->ms, state_global, ir,
506 repl_ex_nst, repl_ex_nex, repl_ex_seed);
509 /* PME tuning is only supported with PME for Coulomb. Is is not supported
510 * with only LJ PME, or for reruns.
512 bPMETune = ((Flags & MD_TUNEPME) && EEL_PME(fr->eeltype) && !bRerunMD &&
513 !(Flags & MD_REPRODUCIBLE));
514 if (bPMETune)
516 pme_loadbal_init(&pme_loadbal, cr, mdlog, ir, state->box,
517 fr->ic, fr->pmedata, use_GPU(fr->nbv),
518 &bPMETunePrinting);
521 if (!ir->bContinuation && !bRerunMD)
523 if (mdatoms->cFREEZE && (state->flags & (1<<estV)))
525 /* Set the velocities of frozen particles to zero */
526 for (i = 0; i < mdatoms->homenr; i++)
528 for (m = 0; m < DIM; m++)
530 if (ir->opts.nFreeze[mdatoms->cFREEZE[i]][m])
532 state->v[i][m] = 0;
538 if (constr)
540 /* Constrain the initial coordinates and velocities */
541 do_constrain_first(fplog, constr, ir, mdatoms, state,
542 cr, nrnb, fr, top);
544 if (vsite)
546 /* Construct the virtual sites for the initial configuration */
547 construct_vsites(vsite, state->x, ir->delta_t, NULL,
548 top->idef.iparams, top->idef.il,
549 fr->ePBC, fr->bMolPBC, cr, state->box);
553 if (ir->efep != efepNO)
555 /* Set free energy calculation frequency as the greatest common
556 * denominator of nstdhdl and repl_ex_nst. */
557 nstfep = ir->fepvals->nstdhdl;
558 if (ir->bExpanded)
560 nstfep = gmx_greatest_common_divisor(ir->expandedvals->nstexpanded, nstfep);
562 if (repl_ex_nst > 0)
564 nstfep = gmx_greatest_common_divisor(repl_ex_nst, nstfep);
568 /* Be REALLY careful about what flags you set here. You CANNOT assume
569 * this is the first step, since we might be restarting from a checkpoint,
570 * and in that case we should not do any modifications to the state.
572 bStopCM = (ir->comm_mode != ecmNO && !ir->bContinuation);
574 if (Flags & MD_READ_EKIN)
576 restore_ekinstate_from_state(cr, ekind, &state_global->ekinstate);
579 cglo_flags = (CGLO_TEMPERATURE | CGLO_GSTAT
580 | (bStopCM ? CGLO_STOPCM : 0)
581 | (EI_VV(ir->eI) ? CGLO_PRESSURE : 0)
582 | (EI_VV(ir->eI) ? CGLO_CONSTRAINT : 0)
583 | ((Flags & MD_READ_EKIN) ? CGLO_READEKIN : 0));
585 bSumEkinhOld = FALSE;
586 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
587 NULL, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
588 constr, &nullSignaller, state->box,
589 &totalNumberOfBondedInteractions, &bSumEkinhOld, cglo_flags
590 | (shouldCheckNumberOfBondedInteractions ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS : 0));
591 checkNumberOfBondedInteractions(fplog, cr, totalNumberOfBondedInteractions,
592 top_global, top, state,
593 &shouldCheckNumberOfBondedInteractions);
594 if (ir->eI == eiVVAK)
596 /* a second call to get the half step temperature initialized as well */
597 /* we do the same call as above, but turn the pressure off -- internally to
598 compute_globals, this is recognized as a velocity verlet half-step
599 kinetic energy calculation. This minimized excess variables, but
600 perhaps loses some logic?*/
602 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
603 NULL, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
604 constr, &nullSignaller, state->box,
605 NULL, &bSumEkinhOld,
606 cglo_flags &~(CGLO_STOPCM | CGLO_PRESSURE));
609 /* Calculate the initial half step temperature, and save the ekinh_old */
610 if (!(Flags & MD_STARTFROMCPT))
612 for (i = 0; (i < ir->opts.ngtc); i++)
614 copy_mat(ekind->tcstat[i].ekinh, ekind->tcstat[i].ekinh_old);
617 if (ir->eI != eiVV)
619 enerd->term[F_TEMP] *= 2; /* result of averages being done over previous and current step,
620 and there is no previous step */
623 /* need to make an initiation call to get the Trotter variables set, as well as other constants for non-trotter
624 temperature control */
625 trotter_seq = init_npt_vars(ir, state, &MassQ, bTrotter);
627 if (MASTER(cr))
629 if (constr && !ir->bContinuation && ir->eConstrAlg == econtLINCS)
631 fprintf(fplog,
632 "RMS relative constraint deviation after constraining: %.2e\n",
633 constr_rmsd(constr));
635 if (EI_STATE_VELOCITY(ir->eI))
637 fprintf(fplog, "Initial temperature: %g K\n", enerd->term[F_TEMP]);
639 if (bRerunMD)
641 fprintf(stderr, "starting md rerun '%s', reading coordinates from"
642 " input trajectory '%s'\n\n",
643 *(top_global->name), opt2fn("-rerun", nfile, fnm));
644 if (bVerbose)
646 fprintf(stderr, "Calculated time to finish depends on nsteps from "
647 "run input file,\nwhich may not correspond to the time "
648 "needed to process input trajectory.\n\n");
651 else
653 char tbuf[20];
654 fprintf(stderr, "starting mdrun '%s'\n",
655 *(top_global->name));
656 if (ir->nsteps >= 0)
658 sprintf(tbuf, "%8.1f", (ir->init_step+ir->nsteps)*ir->delta_t);
660 else
662 sprintf(tbuf, "%s", "infinite");
664 if (ir->init_step > 0)
666 fprintf(stderr, "%s steps, %s ps (continuing from step %s, %8.1f ps).\n",
667 gmx_step_str(ir->init_step+ir->nsteps, sbuf), tbuf,
668 gmx_step_str(ir->init_step, sbuf2),
669 ir->init_step*ir->delta_t);
671 else
673 fprintf(stderr, "%s steps, %s ps.\n",
674 gmx_step_str(ir->nsteps, sbuf), tbuf);
677 fprintf(fplog, "\n");
680 walltime_accounting_start(walltime_accounting);
681 wallcycle_start(wcycle, ewcRUN);
682 print_start(fplog, cr, walltime_accounting, "mdrun");
684 /* safest point to do file checkpointing is here. More general point would be immediately before integrator call */
685 #ifdef GMX_FAHCORE
686 chkpt_ret = fcCheckPointParallel( cr->nodeid,
687 NULL, 0);
688 if (chkpt_ret == 0)
690 gmx_fatal( 3, __FILE__, __LINE__, "Checkpoint error on step %d\n", 0 );
692 #endif
694 /***********************************************************
696 * Loop over MD steps
698 ************************************************************/
700 /* if rerunMD then read coordinates and velocities from input trajectory */
701 if (bRerunMD)
703 if (getenv("GMX_FORCE_UPDATE"))
705 bForceUpdate = TRUE;
708 rerun_fr.natoms = 0;
709 if (MASTER(cr))
711 bLastStep = !read_first_frame(oenv, &status,
712 opt2fn("-rerun", nfile, fnm),
713 &rerun_fr, TRX_NEED_X | TRX_READ_V);
714 if (rerun_fr.natoms != top_global->natoms)
716 gmx_fatal(FARGS,
717 "Number of atoms in trajectory (%d) does not match the "
718 "run input file (%d)\n",
719 rerun_fr.natoms, top_global->natoms);
721 if (ir->ePBC != epbcNONE)
723 if (!rerun_fr.bBox)
725 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);
727 if (max_cutoff2(ir->ePBC, rerun_fr.box) < gmx::square(fr->rlist))
729 gmx_fatal(FARGS, "Rerun trajectory frame step %d time %f has too small box dimensions", rerun_fr.step, rerun_fr.time);
734 if (PAR(cr))
736 rerun_parallel_comm(cr, &rerun_fr, &bLastStep);
739 if (ir->ePBC != epbcNONE)
741 /* Set the shift vectors.
742 * Necessary here when have a static box different from the tpr box.
744 calc_shifts(rerun_fr.box, fr->shift_vec);
748 /* loop over MD steps or if rerunMD to end of input trajectory */
749 bFirstStep = TRUE;
750 /* Skip the first Nose-Hoover integration when we get the state from tpx */
751 bInitStep = !startingFromCheckpoint || EI_VV(ir->eI);
752 bSumEkinhOld = FALSE;
753 bExchanged = FALSE;
754 bNeedRepartition = FALSE;
755 // TODO This implementation of ensemble orientation restraints is nasty because
756 // a user can't just do multi-sim with single-sim orientation restraints.
757 bUsingEnsembleRestraints = (fcd->disres.nsystems > 1) || (cr->ms && fcd->orires.nr);
760 // Replica exchange and ensemble restraints need all
761 // simulations to remain synchronized, so they need
762 // checkpoints and stop conditions to act on the same step, so
763 // the propagation of such signals must take place between
764 // simulations, not just within simulations.
765 bool checkpointIsLocal = (repl_ex_nst <= 0) && !bUsingEnsembleRestraints;
766 bool stopConditionIsLocal = (repl_ex_nst <= 0) && !bUsingEnsembleRestraints;
767 bool resetCountersIsLocal = true;
768 signals[eglsCHKPT] = SimulationSignal(checkpointIsLocal);
769 signals[eglsSTOPCOND] = SimulationSignal(stopConditionIsLocal);
770 signals[eglsRESETCOUNTERS] = SimulationSignal(resetCountersIsLocal);
773 step = ir->init_step;
774 step_rel = 0;
776 // TODO extract this to new multi-simulation module
777 if (MASTER(cr) && MULTISIM(cr) && (repl_ex_nst <= 0 ))
779 if (!multisim_int_all_are_equal(cr->ms, ir->nsteps))
781 GMX_LOG(mdlog.warning).appendText(
782 "Note: The number of steps is not consistent across multi simulations,\n"
783 "but we are proceeding anyway!");
785 if (!multisim_int_all_are_equal(cr->ms, ir->init_step))
787 GMX_LOG(mdlog.warning).appendText(
788 "Note: The initial step is not consistent across multi simulations,\n"
789 "but we are proceeding anyway!");
793 /* and stop now if we should */
794 bLastStep = (bLastStep || (ir->nsteps >= 0 && step_rel > ir->nsteps));
795 while (!bLastStep)
798 /* Determine if this is a neighbor search step */
799 bNStList = (ir->nstlist > 0 && step % ir->nstlist == 0);
801 if (bPMETune && bNStList)
803 /* PME grid + cut-off optimization with GPUs or PME nodes */
804 pme_loadbal_do(pme_loadbal, cr,
805 (bVerbose && MASTER(cr)) ? stderr : NULL,
806 fplog, mdlog,
807 ir, fr, state,
808 wcycle,
809 step, step_rel,
810 &bPMETunePrinting);
813 wallcycle_start(wcycle, ewcSTEP);
815 if (bRerunMD)
817 if (rerun_fr.bStep)
819 step = rerun_fr.step;
820 step_rel = step - ir->init_step;
822 if (rerun_fr.bTime)
824 t = rerun_fr.time;
826 else
828 t = step;
831 else
833 bLastStep = (step_rel == ir->nsteps);
834 t = t0 + step*ir->delta_t;
837 // TODO Refactor this, so that nstfep does not need a default value of zero
838 if (ir->efep != efepNO || ir->bSimTemp)
840 /* find and set the current lambdas. If rerunning, we either read in a state, or a lambda value,
841 requiring different logic. */
843 set_current_lambdas(step, ir->fepvals, bRerunMD, &rerun_fr, state_global, state, lam0);
844 bDoDHDL = do_per_step(step, ir->fepvals->nstdhdl);
845 bDoFEP = ((ir->efep != efepNO) && do_per_step(step, nstfep));
846 bDoExpanded = (do_per_step(step, ir->expandedvals->nstexpanded)
847 && (ir->bExpanded) && (step > 0) && (!startingFromCheckpoint));
850 bDoReplEx = ((repl_ex_nst > 0) && (step > 0) && !bLastStep &&
851 do_per_step(step, repl_ex_nst));
853 if (bSimAnn)
855 update_annealing_target_temp(ir, t, upd);
858 if (bRerunMD)
860 if (!DOMAINDECOMP(cr) || MASTER(cr))
862 for (i = 0; i < state_global->natoms; i++)
864 copy_rvec(rerun_fr.x[i], state_global->x[i]);
866 if (rerun_fr.bV)
868 for (i = 0; i < state_global->natoms; i++)
870 copy_rvec(rerun_fr.v[i], state_global->v[i]);
873 else
875 for (i = 0; i < state_global->natoms; i++)
877 clear_rvec(state_global->v[i]);
879 if (bRerunWarnNoV)
881 fprintf(stderr, "\nWARNING: Some frames do not contain velocities.\n"
882 " Ekin, temperature and pressure are incorrect,\n"
883 " the virial will be incorrect when constraints are present.\n"
884 "\n");
885 bRerunWarnNoV = FALSE;
889 copy_mat(rerun_fr.box, state_global->box);
890 copy_mat(state_global->box, state->box);
892 if (vsite && (Flags & MD_RERUN_VSITE))
894 if (DOMAINDECOMP(cr))
896 gmx_fatal(FARGS, "Vsite recalculation with -rerun is not implemented with domain decomposition, use a single rank");
898 if (graph)
900 /* Following is necessary because the graph may get out of sync
901 * with the coordinates if we only have every N'th coordinate set
903 mk_mshift(fplog, graph, fr->ePBC, state->box, state->x);
904 shift_self(graph, state->box, state->x);
906 construct_vsites(vsite, state->x, ir->delta_t, state->v,
907 top->idef.iparams, top->idef.il,
908 fr->ePBC, fr->bMolPBC, cr, state->box);
909 if (graph)
911 unshift_self(graph, state->box, state->x);
916 /* Stop Center of Mass motion */
917 bStopCM = (ir->comm_mode != ecmNO && do_per_step(step, ir->nstcomm));
919 if (bRerunMD)
921 /* for rerun MD always do Neighbour Searching */
922 bNS = (bFirstStep || ir->nstlist != 0);
924 else
926 /* Determine whether or not to do Neighbour Searching */
927 bNS = (bFirstStep || bNStList || bExchanged || bNeedRepartition);
930 /* < 0 means stop at next step, > 0 means stop at next NS step */
931 if ( (signals[eglsSTOPCOND].set < 0) ||
932 ( (signals[eglsSTOPCOND].set > 0 ) && ( bNS || ir->nstlist == 0)))
934 bLastStep = TRUE;
937 /* Determine whether or not to update the Born radii if doing GB */
938 bBornRadii = bFirstStep;
939 if (ir->implicit_solvent && (step % ir->nstgbradii == 0))
941 bBornRadii = TRUE;
944 /* do_log triggers energy and virial calculation. Because this leads
945 * to different code paths, forces can be different. Thus for exact
946 * continuation we should avoid extra log output.
947 * Note that the || bLastStep can result in non-exact continuation
948 * beyond the last step. But we don't consider that to be an issue.
950 do_log = do_per_step(step, ir->nstlog) || (bFirstStep && !startingFromCheckpoint) || bLastStep || bRerunMD;
951 do_verbose = bVerbose &&
952 (step % stepout == 0 || bFirstStep || bLastStep || bRerunMD);
954 if (bNS && !(bFirstStep && ir->bContinuation && !bRerunMD))
956 if (bRerunMD)
958 bMasterState = TRUE;
960 else
962 bMasterState = FALSE;
963 /* Correct the new box if it is too skewed */
964 if (inputrecDynamicBox(ir))
966 if (correct_box(fplog, step, state->box, graph))
968 bMasterState = TRUE;
971 if (DOMAINDECOMP(cr) && bMasterState)
973 dd_collect_state(cr->dd, state, state_global);
977 if (DOMAINDECOMP(cr))
979 /* Repartition the domain decomposition */
980 dd_partition_system(fplog, step, cr,
981 bMasterState, nstglobalcomm,
982 state_global, top_global, ir,
983 state, &f, mdatoms, top, fr,
984 vsite, constr,
985 nrnb, wcycle,
986 do_verbose && !bPMETunePrinting);
987 shouldCheckNumberOfBondedInteractions = true;
988 update_realloc(upd, state->nalloc);
992 if (MASTER(cr) && do_log)
994 print_ebin_header(fplog, step, t); /* can we improve the information printed here? */
997 if (ir->efep != efepNO)
999 update_mdatoms(mdatoms, state->lambda[efptMASS]);
1002 if ((bRerunMD && rerun_fr.bV) || bExchanged)
1005 /* We need the kinetic energy at minus the half step for determining
1006 * the full step kinetic energy and possibly for T-coupling.*/
1007 /* This may not be quite working correctly yet . . . . */
1008 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
1009 wcycle, enerd, NULL, NULL, NULL, NULL, mu_tot,
1010 constr, &nullSignaller, state->box,
1011 &totalNumberOfBondedInteractions, &bSumEkinhOld,
1012 CGLO_GSTAT | CGLO_TEMPERATURE | CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS);
1013 checkNumberOfBondedInteractions(fplog, cr, totalNumberOfBondedInteractions,
1014 top_global, top, state,
1015 &shouldCheckNumberOfBondedInteractions);
1017 clear_mat(force_vir);
1019 /* We write a checkpoint at this MD step when:
1020 * either at an NS step when we signalled through gs,
1021 * or at the last step (but not when we do not want confout),
1022 * but never at the first step or with rerun.
1024 bCPT = (((signals[eglsCHKPT].set && (bNS || ir->nstlist == 0)) ||
1025 (bLastStep && (Flags & MD_CONFOUT))) &&
1026 step > ir->init_step && !bRerunMD);
1027 if (bCPT)
1029 signals[eglsCHKPT].set = 0;
1032 /* Determine the energy and pressure:
1033 * at nstcalcenergy steps and at energy output steps (set below).
1035 if (EI_VV(ir->eI) && (!bInitStep))
1037 /* for vv, the first half of the integration actually corresponds
1038 to the previous step. bCalcEner is only required to be evaluated on the 'next' step,
1039 but the virial needs to be calculated on both the current step and the 'next' step. Future
1040 reorganization may be able to get rid of one of the bCalcVir=TRUE steps. */
1042 /* TODO: This is probably not what we want, we will write to energy file one step after nstcalcenergy steps. */
1043 bCalcEnerStep = do_per_step(step - 1, ir->nstcalcenergy);
1044 bCalcVir = bCalcEnerStep ||
1045 (ir->epc != epcNO && (do_per_step(step, ir->nstpcouple) || do_per_step(step-1, ir->nstpcouple)));
1047 else
1049 bCalcEnerStep = do_per_step(step, ir->nstcalcenergy);
1050 bCalcVir = bCalcEnerStep ||
1051 (ir->epc != epcNO && do_per_step(step, ir->nstpcouple));
1053 bCalcEner = bCalcEnerStep;
1055 do_ene = (do_per_step(step, ir->nstenergy) || bLastStep || bRerunMD);
1057 if (do_ene || do_log || bDoReplEx)
1059 bCalcVir = TRUE;
1060 bCalcEner = TRUE;
1063 /* Do we need global communication ? */
1064 bGStat = (bCalcVir || bCalcEner || bStopCM ||
1065 do_per_step(step, nstglobalcomm) ||
1066 (EI_VV(ir->eI) && inputrecNvtTrotter(ir) && do_per_step(step-1, nstglobalcomm)));
1068 force_flags = (GMX_FORCE_STATECHANGED |
1069 ((inputrecDynamicBox(ir) || bRerunMD) ? GMX_FORCE_DYNAMICBOX : 0) |
1070 GMX_FORCE_ALLFORCES |
1071 (bCalcVir ? GMX_FORCE_VIRIAL : 0) |
1072 (bCalcEner ? GMX_FORCE_ENERGY : 0) |
1073 (bDoFEP ? GMX_FORCE_DHDL : 0)
1076 if (shellfc)
1078 /* Now is the time to relax the shells */
1079 relax_shell_flexcon(fplog, cr, bVerbose, step,
1080 ir, bNS, force_flags, top,
1081 constr, enerd, fcd,
1082 state, f, force_vir, mdatoms,
1083 nrnb, wcycle, graph, groups,
1084 shellfc, fr, bBornRadii, t, mu_tot,
1085 vsite, mdoutf_get_fp_field(outf));
1087 else
1089 /* The coordinates (x) are shifted (to get whole molecules)
1090 * in do_force.
1091 * This is parallellized as well, and does communication too.
1092 * Check comments in sim_util.c
1094 do_force(fplog, cr, ir, step, nrnb, wcycle, top, groups,
1095 state->box, state->x, &state->hist,
1096 f, force_vir, mdatoms, enerd, fcd,
1097 state->lambda, graph,
1098 fr, vsite, mu_tot, t, mdoutf_get_fp_field(outf), ed, bBornRadii,
1099 (bNS ? GMX_FORCE_NS : 0) | force_flags);
1102 if (EI_VV(ir->eI) && !startingFromCheckpoint && !bRerunMD)
1103 /* ############### START FIRST UPDATE HALF-STEP FOR VV METHODS############### */
1105 rvec *vbuf = NULL;
1107 wallcycle_start(wcycle, ewcUPDATE);
1108 if (ir->eI == eiVV && bInitStep)
1110 /* if using velocity verlet with full time step Ekin,
1111 * take the first half step only to compute the
1112 * virial for the first step. From there,
1113 * revert back to the initial coordinates
1114 * so that the input is actually the initial step.
1116 snew(vbuf, state->natoms);
1117 copy_rvecn(state->v, vbuf, 0, state->natoms); /* should make this better for parallelizing? */
1119 else
1121 /* this is for NHC in the Ekin(t+dt/2) version of vv */
1122 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ1);
1125 update_coords(fplog, step, ir, mdatoms, state, f, fcd,
1126 ekind, M, upd, etrtVELOCITY1,
1127 cr, constr);
1129 if (!bRerunMD || rerun_fr.bV || bForceUpdate) /* Why is rerun_fr.bV here? Unclear. */
1131 wallcycle_stop(wcycle, ewcUPDATE);
1132 update_constraints(fplog, step, NULL, ir, mdatoms,
1133 state, fr->bMolPBC, graph, f,
1134 &top->idef, shake_vir,
1135 cr, nrnb, wcycle, upd, constr,
1136 TRUE, bCalcVir);
1137 wallcycle_start(wcycle, ewcUPDATE);
1139 else if (graph)
1141 /* Need to unshift here if a do_force has been
1142 called in the previous step */
1143 unshift_self(graph, state->box, state->x);
1145 /* if VV, compute the pressure and constraints */
1146 /* For VV2, we strictly only need this if using pressure
1147 * control, but we really would like to have accurate pressures
1148 * printed out.
1149 * Think about ways around this in the future?
1150 * For now, keep this choice in comments.
1152 /*bPres = (ir->eI==eiVV || inputrecNptTrotter(ir)); */
1153 /*bTemp = ((ir->eI==eiVV &&(!bInitStep)) || (ir->eI==eiVVAK && inputrecNptTrotter(ir)));*/
1154 bPres = TRUE;
1155 bTemp = ((ir->eI == eiVV && (!bInitStep)) || (ir->eI == eiVVAK));
1156 if (bCalcEner && ir->eI == eiVVAK)
1158 bSumEkinhOld = TRUE;
1160 /* for vv, the first half of the integration actually corresponds to the previous step.
1161 So we need information from the last step in the first half of the integration */
1162 if (bGStat || do_per_step(step-1, nstglobalcomm))
1164 wallcycle_stop(wcycle, ewcUPDATE);
1165 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
1166 wcycle, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
1167 constr, &nullSignaller, state->box,
1168 &totalNumberOfBondedInteractions, &bSumEkinhOld,
1169 (bGStat ? CGLO_GSTAT : 0)
1170 | CGLO_ENERGY
1171 | (bTemp ? CGLO_TEMPERATURE : 0)
1172 | (bPres ? CGLO_PRESSURE : 0)
1173 | (bPres ? CGLO_CONSTRAINT : 0)
1174 | (bStopCM ? CGLO_STOPCM : 0)
1175 | (shouldCheckNumberOfBondedInteractions ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS : 0)
1176 | CGLO_SCALEEKIN
1178 /* explanation of above:
1179 a) We compute Ekin at the full time step
1180 if 1) we are using the AveVel Ekin, and it's not the
1181 initial step, or 2) if we are using AveEkin, but need the full
1182 time step kinetic energy for the pressure (always true now, since we want accurate statistics).
1183 b) If we are using EkinAveEkin for the kinetic energy for the temperature control, we still feed in
1184 EkinAveVel because it's needed for the pressure */
1185 checkNumberOfBondedInteractions(fplog, cr, totalNumberOfBondedInteractions,
1186 top_global, top, state,
1187 &shouldCheckNumberOfBondedInteractions);
1188 wallcycle_start(wcycle, ewcUPDATE);
1190 /* temperature scaling and pressure scaling to produce the extended variables at t+dt */
1191 if (!bInitStep)
1193 if (bTrotter)
1195 m_add(force_vir, shake_vir, total_vir); /* we need the un-dispersion corrected total vir here */
1196 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ2);
1198 copy_mat(shake_vir, state->svir_prev);
1199 copy_mat(force_vir, state->fvir_prev);
1200 if (inputrecNvtTrotter(ir) && ir->eI == eiVV)
1202 /* update temperature and kinetic energy now that step is over - this is the v(t+dt) point */
1203 enerd->term[F_TEMP] = sum_ekin(&(ir->opts), ekind, NULL, (ir->eI == eiVV), FALSE);
1204 enerd->term[F_EKIN] = trace(ekind->ekin);
1207 else if (bExchanged)
1209 wallcycle_stop(wcycle, ewcUPDATE);
1210 /* We need the kinetic energy at minus the half step for determining
1211 * the full step kinetic energy and possibly for T-coupling.*/
1212 /* This may not be quite working correctly yet . . . . */
1213 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
1214 wcycle, enerd, NULL, NULL, NULL, NULL, mu_tot,
1215 constr, &nullSignaller, state->box,
1216 NULL, &bSumEkinhOld,
1217 CGLO_GSTAT | CGLO_TEMPERATURE);
1218 wallcycle_start(wcycle, ewcUPDATE);
1221 /* if it's the initial step, we performed this first step just to get the constraint virial */
1222 if (ir->eI == eiVV && bInitStep)
1224 copy_rvecn(vbuf, state->v, 0, state->natoms);
1225 sfree(vbuf);
1227 wallcycle_stop(wcycle, ewcUPDATE);
1230 /* compute the conserved quantity */
1231 if (EI_VV(ir->eI))
1233 saved_conserved_quantity = compute_conserved_from_auxiliary(ir, state, &MassQ);
1234 if (ir->eI == eiVV)
1236 last_ekin = enerd->term[F_EKIN];
1238 if ((ir->eDispCorr != edispcEnerPres) && (ir->eDispCorr != edispcAllEnerPres))
1240 saved_conserved_quantity -= enerd->term[F_DISPCORR];
1242 /* sum up the foreign energy and dhdl terms for vv. currently done every step so that dhdl is correct in the .edr */
1243 if (ir->efep != efepNO && !bRerunMD)
1245 sum_dhdl(enerd, state->lambda, ir->fepvals);
1249 /* ######## END FIRST UPDATE STEP ############## */
1250 /* ######## If doing VV, we now have v(dt) ###### */
1251 if (bDoExpanded)
1253 /* perform extended ensemble sampling in lambda - we don't
1254 actually move to the new state before outputting
1255 statistics, but if performing simulated tempering, we
1256 do update the velocities and the tau_t. */
1258 lamnew = ExpandedEnsembleDynamics(fplog, ir, enerd, state, &MassQ, state->fep_state, &state->dfhist, step, state->v, mdatoms);
1259 /* history is maintained in state->dfhist, but state_global is what is sent to trajectory and log output */
1260 copy_df_history(&state_global->dfhist, &state->dfhist);
1263 /* Now we have the energies and forces corresponding to the
1264 * coordinates at time t. We must output all of this before
1265 * the update.
1267 do_md_trajectory_writing(fplog, cr, nfile, fnm, step, step_rel, t,
1268 ir, state, state_global, top_global, fr,
1269 outf, mdebin, ekind, f,
1270 &nchkpt,
1271 bCPT, bRerunMD, bLastStep, (Flags & MD_CONFOUT),
1272 bSumEkinhOld);
1273 /* Check if IMD step and do IMD communication, if bIMD is TRUE. */
1274 bIMDstep = do_IMD(ir->bIMD, step, cr, bNS, state->box, state->x, ir, t, wcycle);
1276 /* kludge -- virial is lost with restart for MTTK NPT control. Must reload (saved earlier). */
1277 if (startingFromCheckpoint && bTrotter)
1279 copy_mat(state->svir_prev, shake_vir);
1280 copy_mat(state->fvir_prev, force_vir);
1283 elapsed_time = walltime_accounting_get_current_elapsed_time(walltime_accounting);
1285 /* Check whether everything is still allright */
1286 if (((int)gmx_get_stop_condition() > handled_stop_condition)
1287 #if GMX_THREAD_MPI
1288 && MASTER(cr)
1289 #endif
1292 int nsteps_stop = -1;
1294 /* this just makes signals[].sig compatible with the hack
1295 of sending signals around by MPI_Reduce together with
1296 other floats */
1297 if (gmx_get_stop_condition() == gmx_stop_cond_next_ns)
1299 signals[eglsSTOPCOND].sig = 1;
1300 nsteps_stop = std::max(ir->nstlist, 2*nstglobalcomm);
1302 if (gmx_get_stop_condition() == gmx_stop_cond_next)
1304 signals[eglsSTOPCOND].sig = -1;
1305 nsteps_stop = nstglobalcomm + 1;
1307 if (fplog)
1309 fprintf(fplog,
1310 "\n\nReceived the %s signal, stopping within %d steps\n\n",
1311 gmx_get_signal_name(), nsteps_stop);
1312 fflush(fplog);
1314 fprintf(stderr,
1315 "\n\nReceived the %s signal, stopping within %d steps\n\n",
1316 gmx_get_signal_name(), nsteps_stop);
1317 fflush(stderr);
1318 handled_stop_condition = (int)gmx_get_stop_condition();
1320 else if (MASTER(cr) && (bNS || ir->nstlist <= 0) &&
1321 (max_hours > 0 && elapsed_time > max_hours*60.0*60.0*0.99) &&
1322 signals[eglsSTOPCOND].sig == 0 && signals[eglsSTOPCOND].set == 0)
1324 /* Signal to terminate the run */
1325 signals[eglsSTOPCOND].sig = 1;
1326 if (fplog)
1328 fprintf(fplog, "\nStep %s: Run time exceeded %.3f hours, will terminate the run\n", gmx_step_str(step, sbuf), max_hours*0.99);
1330 fprintf(stderr, "\nStep %s: Run time exceeded %.3f hours, will terminate the run\n", gmx_step_str(step, sbuf), max_hours*0.99);
1333 if (bResetCountersHalfMaxH && MASTER(cr) &&
1334 elapsed_time > max_hours*60.0*60.0*0.495)
1336 /* Set flag that will communicate the signal to all ranks in the simulation */
1337 signals[eglsRESETCOUNTERS].sig = 1;
1340 /* In parallel we only have to check for checkpointing in steps
1341 * where we do global communication,
1342 * otherwise the other nodes don't know.
1344 if (MASTER(cr) && ((bGStat || !PAR(cr)) &&
1345 cpt_period >= 0 &&
1346 (cpt_period == 0 ||
1347 elapsed_time >= nchkpt*cpt_period*60.0)) &&
1348 signals[eglsCHKPT].set == 0)
1350 signals[eglsCHKPT].sig = 1;
1353 /* ######### START SECOND UPDATE STEP ################# */
1355 /* at the start of step, randomize or scale the velocities ((if vv. Restriction of Andersen controlled
1356 in preprocessing */
1358 if (ETC_ANDERSEN(ir->etc)) /* keep this outside of update_tcouple because of the extra info required to pass */
1360 gmx_bool bIfRandomize;
1361 bIfRandomize = update_randomize_velocities(ir, step, cr, mdatoms, state, upd, constr);
1362 /* if we have constraints, we have to remove the kinetic energy parallel to the bonds */
1363 if (constr && bIfRandomize)
1365 update_constraints(fplog, step, NULL, ir, mdatoms,
1366 state, fr->bMolPBC, graph, f,
1367 &top->idef, tmp_vir,
1368 cr, nrnb, wcycle, upd, constr,
1369 TRUE, bCalcVir);
1372 /* Box is changed in update() when we do pressure coupling,
1373 * but we should still use the old box for energy corrections and when
1374 * writing it to the energy file, so it matches the trajectory files for
1375 * the same timestep above. Make a copy in a separate array.
1377 copy_mat(state->box, lastbox);
1379 dvdl_constr = 0;
1381 if (!bRerunMD || rerun_fr.bV || bForceUpdate)
1383 wallcycle_start(wcycle, ewcUPDATE);
1384 /* UPDATE PRESSURE VARIABLES IN TROTTER FORMULATION WITH CONSTRAINTS */
1385 if (bTrotter)
1387 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ3);
1388 /* We can only do Berendsen coupling after we have summed
1389 * the kinetic energy or virial. Since the happens
1390 * in global_state after update, we should only do it at
1391 * step % nstlist = 1 with bGStatEveryStep=FALSE.
1394 else
1396 update_tcouple(step, ir, state, ekind, &MassQ, mdatoms);
1397 update_pcouple(fplog, step, ir, state, pcoupl_mu, M, bInitStep);
1400 if (EI_VV(ir->eI))
1402 /* velocity half-step update */
1403 update_coords(fplog, step, ir, mdatoms, state, f, fcd,
1404 ekind, M, upd, etrtVELOCITY2,
1405 cr, constr);
1408 /* Above, initialize just copies ekinh into ekin,
1409 * it doesn't copy position (for VV),
1410 * and entire integrator for MD.
1413 if (ir->eI == eiVVAK)
1415 /* We probably only need md->homenr, not state->natoms */
1416 if (state->natoms > cbuf_nalloc)
1418 cbuf_nalloc = state->natoms;
1419 srenew(cbuf, cbuf_nalloc);
1421 copy_rvecn(state->x, cbuf, 0, state->natoms);
1424 update_coords(fplog, step, ir, mdatoms, state, f, fcd,
1425 ekind, M, upd, etrtPOSITION, cr, constr);
1426 wallcycle_stop(wcycle, ewcUPDATE);
1428 update_constraints(fplog, step, &dvdl_constr, ir, mdatoms, state,
1429 fr->bMolPBC, graph, f,
1430 &top->idef, shake_vir,
1431 cr, nrnb, wcycle, upd, constr,
1432 FALSE, bCalcVir);
1434 if (ir->eI == eiVVAK)
1436 /* erase F_EKIN and F_TEMP here? */
1437 /* just compute the kinetic energy at the half step to perform a trotter step */
1438 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
1439 wcycle, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
1440 constr, &nullSignaller, lastbox,
1441 NULL, &bSumEkinhOld,
1442 (bGStat ? CGLO_GSTAT : 0) | CGLO_TEMPERATURE
1444 wallcycle_start(wcycle, ewcUPDATE);
1445 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ4);
1446 /* now we know the scaling, we can compute the positions again again */
1447 copy_rvecn(cbuf, state->x, 0, state->natoms);
1449 update_coords(fplog, step, ir, mdatoms, state, f, fcd,
1450 ekind, M, upd, etrtPOSITION, cr, constr);
1451 wallcycle_stop(wcycle, ewcUPDATE);
1453 /* do we need an extra constraint here? just need to copy out of state->v to upd->xp? */
1454 /* are the small terms in the shake_vir here due
1455 * to numerical errors, or are they important
1456 * physically? I'm thinking they are just errors, but not completely sure.
1457 * For now, will call without actually constraining, constr=NULL*/
1458 update_constraints(fplog, step, NULL, ir, mdatoms,
1459 state, fr->bMolPBC, graph, f,
1460 &top->idef, tmp_vir,
1461 cr, nrnb, wcycle, upd, NULL,
1462 FALSE, bCalcVir);
1464 if (EI_VV(ir->eI))
1466 /* this factor or 2 correction is necessary
1467 because half of the constraint force is removed
1468 in the vv step, so we have to double it. See
1469 the Redmine issue #1255. It is not yet clear
1470 if the factor of 2 is exact, or just a very
1471 good approximation, and this will be
1472 investigated. The next step is to see if this
1473 can be done adding a dhdl contribution from the
1474 rattle step, but this is somewhat more
1475 complicated with the current code. Will be
1476 investigated, hopefully for 4.6.3. However,
1477 this current solution is much better than
1478 having it completely wrong.
1480 enerd->term[F_DVDL_CONSTR] += 2*dvdl_constr;
1482 else
1484 enerd->term[F_DVDL_CONSTR] += dvdl_constr;
1487 else if (graph)
1489 /* Need to unshift here */
1490 unshift_self(graph, state->box, state->x);
1493 if (vsite != NULL)
1495 wallcycle_start(wcycle, ewcVSITECONSTR);
1496 if (graph != NULL)
1498 shift_self(graph, state->box, state->x);
1500 construct_vsites(vsite, state->x, ir->delta_t, state->v,
1501 top->idef.iparams, top->idef.il,
1502 fr->ePBC, fr->bMolPBC, cr, state->box);
1504 if (graph != NULL)
1506 unshift_self(graph, state->box, state->x);
1508 wallcycle_stop(wcycle, ewcVSITECONSTR);
1511 /* ############## IF NOT VV, Calculate globals HERE ############ */
1512 /* With Leap-Frog we can skip compute_globals at
1513 * non-communication steps, but we need to calculate
1514 * the kinetic energy one step before communication.
1517 // Organize to do inter-simulation signalling on steps if
1518 // and when algorithms require it.
1519 bool doInterSimSignal = (!bFirstStep && bDoReplEx) || bUsingEnsembleRestraints;
1521 if (bGStat || (!EI_VV(ir->eI) && do_per_step(step+1, nstglobalcomm)) || doInterSimSignal)
1523 // Since we're already communicating at this step, we
1524 // can propagate intra-simulation signals. Note that
1525 // check_nstglobalcomm has the responsibility for
1526 // choosing the value of nstglobalcomm that is one way
1527 // bGStat becomes true, so we can't get into a
1528 // situation where e.g. checkpointing can't be
1529 // signalled.
1530 bool doIntraSimSignal = true;
1531 SimulationSignaller signaller(&signals, cr, doInterSimSignal, doIntraSimSignal);
1533 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
1534 wcycle, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
1535 constr, &signaller,
1536 lastbox,
1537 &totalNumberOfBondedInteractions, &bSumEkinhOld,
1538 (bGStat ? CGLO_GSTAT : 0)
1539 | (!EI_VV(ir->eI) || bRerunMD ? CGLO_ENERGY : 0)
1540 | (!EI_VV(ir->eI) && bStopCM ? CGLO_STOPCM : 0)
1541 | (!EI_VV(ir->eI) ? CGLO_TEMPERATURE : 0)
1542 | (!EI_VV(ir->eI) || bRerunMD ? CGLO_PRESSURE : 0)
1543 | CGLO_CONSTRAINT
1544 | (shouldCheckNumberOfBondedInteractions ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS : 0)
1546 checkNumberOfBondedInteractions(fplog, cr, totalNumberOfBondedInteractions,
1547 top_global, top, state,
1548 &shouldCheckNumberOfBondedInteractions);
1552 /* ############# END CALC EKIN AND PRESSURE ################# */
1554 /* Note: this is OK, but there are some numerical precision issues with using the convergence of
1555 the virial that should probably be addressed eventually. state->veta has better properies,
1556 but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could
1557 generate the new shake_vir, but test the veta value for convergence. This will take some thought. */
1559 if (ir->efep != efepNO && (!EI_VV(ir->eI) || bRerunMD))
1561 /* Sum up the foreign energy and dhdl terms for md and sd.
1562 Currently done every step so that dhdl is correct in the .edr */
1563 sum_dhdl(enerd, state->lambda, ir->fepvals);
1565 update_box(fplog, step, ir, mdatoms, state, f,
1566 pcoupl_mu, nrnb, upd);
1568 /* ################# END UPDATE STEP 2 ################# */
1569 /* #### We now have r(t+dt) and v(t+dt/2) ############# */
1571 /* The coordinates (x) were unshifted in update */
1572 if (!bGStat)
1574 /* We will not sum ekinh_old,
1575 * so signal that we still have to do it.
1577 bSumEkinhOld = TRUE;
1580 /* ######### BEGIN PREPARING EDR OUTPUT ########### */
1582 /* use the directly determined last velocity, not actually the averaged half steps */
1583 if (bTrotter && ir->eI == eiVV)
1585 enerd->term[F_EKIN] = last_ekin;
1587 enerd->term[F_ETOT] = enerd->term[F_EPOT] + enerd->term[F_EKIN];
1589 if (EI_VV(ir->eI))
1591 enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + saved_conserved_quantity;
1593 else
1595 enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + compute_conserved_from_auxiliary(ir, state, &MassQ);
1597 /* ######### END PREPARING EDR OUTPUT ########### */
1599 /* Output stuff */
1600 if (MASTER(cr))
1602 if (fplog && do_log && bDoExpanded)
1604 /* only needed if doing expanded ensemble */
1605 PrintFreeEnergyInfoToFile(fplog, ir->fepvals, ir->expandedvals, ir->bSimTemp ? ir->simtempvals : NULL,
1606 &state_global->dfhist, state->fep_state, ir->nstlog, step);
1608 if (bCalcEner)
1610 upd_mdebin(mdebin, bDoDHDL, bCalcEnerStep,
1611 t, mdatoms->tmass, enerd, state,
1612 ir->fepvals, ir->expandedvals, lastbox,
1613 shake_vir, force_vir, total_vir, pres,
1614 ekind, mu_tot, constr);
1616 else
1618 upd_mdebin_step(mdebin);
1621 gmx_bool do_dr = do_per_step(step, ir->nstdisreout);
1622 gmx_bool do_or = do_per_step(step, ir->nstorireout);
1624 print_ebin(mdoutf_get_fp_ene(outf), do_ene, do_dr, do_or, do_log ? fplog : NULL,
1625 step, t,
1626 eprNORMAL, mdebin, fcd, groups, &(ir->opts));
1628 if (ir->bPull)
1630 pull_print_output(ir->pull_work, step, t);
1633 if (do_per_step(step, ir->nstlog))
1635 if (fflush(fplog) != 0)
1637 gmx_fatal(FARGS, "Cannot flush logfile - maybe you are out of disk space?");
1641 if (bDoExpanded)
1643 /* Have to do this part _after_ outputting the logfile and the edr file */
1644 /* Gets written into the state at the beginning of next loop*/
1645 state->fep_state = lamnew;
1647 /* Print the remaining wall clock time for the run */
1648 if (MULTIMASTER(cr) &&
1649 (do_verbose || gmx_got_usr_signal()) &&
1650 !bPMETunePrinting)
1652 if (shellfc)
1654 fprintf(stderr, "\n");
1656 print_time(stderr, walltime_accounting, step, ir, cr);
1659 /* Ion/water position swapping.
1660 * Not done in last step since trajectory writing happens before this call
1661 * in the MD loop and exchanges would be lost anyway. */
1662 bNeedRepartition = FALSE;
1663 if ((ir->eSwapCoords != eswapNO) && (step > 0) && !bLastStep &&
1664 do_per_step(step, ir->swap->nstswap))
1666 bNeedRepartition = do_swapcoords(cr, step, t, ir, wcycle,
1667 bRerunMD ? rerun_fr.x : state->x,
1668 bRerunMD ? rerun_fr.box : state->box,
1669 top_global, MASTER(cr) && bVerbose, bRerunMD);
1671 if (bNeedRepartition && DOMAINDECOMP(cr))
1673 dd_collect_state(cr->dd, state, state_global);
1677 /* Replica exchange */
1678 bExchanged = FALSE;
1679 if (bDoReplEx)
1681 bExchanged = replica_exchange(fplog, cr, repl_ex,
1682 state_global, enerd,
1683 state, step, t);
1686 if ( (bExchanged || bNeedRepartition) && DOMAINDECOMP(cr) )
1688 dd_partition_system(fplog, step, cr, TRUE, 1,
1689 state_global, top_global, ir,
1690 state, &f, mdatoms, top, fr,
1691 vsite, constr,
1692 nrnb, wcycle, FALSE);
1693 shouldCheckNumberOfBondedInteractions = true;
1694 update_realloc(upd, state->nalloc);
1697 bFirstStep = FALSE;
1698 bInitStep = FALSE;
1699 startingFromCheckpoint = FALSE;
1701 /* ####### SET VARIABLES FOR NEXT ITERATION IF THEY STILL NEED IT ###### */
1702 /* With all integrators, except VV, we need to retain the pressure
1703 * at the current step for coupling at the next step.
1705 if ((state->flags & (1<<estPRES_PREV)) &&
1706 (bGStatEveryStep ||
1707 (ir->nstpcouple > 0 && step % ir->nstpcouple == 0)))
1709 /* Store the pressure in t_state for pressure coupling
1710 * at the next MD step.
1712 copy_mat(pres, state->pres_prev);
1715 /* ####### END SET VARIABLES FOR NEXT ITERATION ###### */
1717 if ( (membed != NULL) && (!bLastStep) )
1719 rescale_membed(step_rel, membed, state_global->x);
1722 if (bRerunMD)
1724 if (MASTER(cr))
1726 /* read next frame from input trajectory */
1727 bLastStep = !read_next_frame(oenv, status, &rerun_fr);
1730 if (PAR(cr))
1732 rerun_parallel_comm(cr, &rerun_fr, &bLastStep);
1736 cycles = wallcycle_stop(wcycle, ewcSTEP);
1737 if (DOMAINDECOMP(cr) && wcycle)
1739 dd_cycles_add(cr->dd, cycles, ddCyclStep);
1742 if (!bRerunMD || !rerun_fr.bStep)
1744 /* increase the MD step number */
1745 step++;
1746 step_rel++;
1749 /* TODO make a counter-reset module */
1750 /* If it is time to reset counters, set a flag that remains
1751 true until counters actually get reset */
1752 if (step_rel == wcycle_get_reset_counters(wcycle) ||
1753 signals[eglsRESETCOUNTERS].set != 0)
1755 if (pme_loadbal_is_active(pme_loadbal))
1757 /* Do not permit counter reset while PME load
1758 * balancing is active. The only purpose for resetting
1759 * counters is to measure reliable performance data,
1760 * and that can't be done before balancing
1761 * completes.
1763 * TODO consider fixing this by delaying the reset
1764 * until after load balancing completes,
1765 * e.g. https://gerrit.gromacs.org/#/c/4964/2 */
1766 gmx_fatal(FARGS, "PME tuning was still active when attempting to "
1767 "reset mdrun counters at step %" GMX_PRId64 ". Try "
1768 "resetting counters later in the run, e.g. with gmx "
1769 "mdrun -resetstep.", step);
1771 reset_all_counters(fplog, mdlog, cr, step, &step_rel, ir, wcycle, nrnb, walltime_accounting,
1772 use_GPU(fr->nbv) ? fr->nbv : NULL);
1773 wcycle_set_reset_counters(wcycle, -1);
1774 if (!(cr->duty & DUTY_PME))
1776 /* Tell our PME node to reset its counters */
1777 gmx_pme_send_resetcounters(cr, step);
1779 /* Correct max_hours for the elapsed time */
1780 max_hours -= elapsed_time/(60.0*60.0);
1781 /* If mdrun -maxh -resethway was active, it can only trigger once */
1782 bResetCountersHalfMaxH = FALSE; /* TODO move this to where signals[eglsRESETCOUNTERS].sig is set */
1783 /* Reset can only happen once, so clear the triggering flag. */
1784 signals[eglsRESETCOUNTERS].set = 0;
1787 /* If bIMD is TRUE, the master updates the IMD energy record and sends positions to VMD client */
1788 IMD_prep_energies_send_positions(ir->bIMD && MASTER(cr), bIMDstep, ir->imd, enerd, step, bCalcEner, wcycle);
1791 /* End of main MD loop */
1793 /* Closing TNG files can include compressing data. Therefore it is good to do that
1794 * before stopping the time measurements. */
1795 mdoutf_tng_close(outf);
1797 /* Stop measuring walltime */
1798 walltime_accounting_end(walltime_accounting);
1800 if (bRerunMD && MASTER(cr))
1802 close_trj(status);
1805 if (!(cr->duty & DUTY_PME))
1807 /* Tell the PME only node to finish */
1808 gmx_pme_send_finish(cr);
1811 if (MASTER(cr))
1813 if (ir->nstcalcenergy > 0 && !bRerunMD)
1815 print_ebin(mdoutf_get_fp_ene(outf), FALSE, FALSE, FALSE, fplog, step, t,
1816 eprAVER, mdebin, fcd, groups, &(ir->opts));
1820 done_mdoutf(outf);
1822 if (bPMETune)
1824 pme_loadbal_done(pme_loadbal, fplog, mdlog, use_GPU(fr->nbv));
1827 done_shellfc(fplog, shellfc, step_rel);
1829 if (repl_ex_nst > 0 && MASTER(cr))
1831 print_replica_exchange_statistics(fplog, repl_ex);
1834 // Clean up swapcoords
1835 if (ir->eSwapCoords != eswapNO)
1837 finish_swapcoords(ir->swap);
1840 /* IMD cleanup, if bIMD is TRUE. */
1841 IMD_finalize(ir->bIMD, ir->imd);
1843 walltime_accounting_set_nsteps_done(walltime_accounting, step_rel);
1845 return 0;