Remove obsolete braces in do_md()
[gromacs.git] / src / gromacs / mdrun / md.cpp
blob1834e633aaa23b868b5bb8276974f80c65502936
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,2017,2018, 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 /*! \internal \file
39 * \brief Implements the integrator for normal molecular dynamics simulations
41 * \author David van der Spoel <david.vanderspoel@icm.uu.se>
42 * \ingroup module_mdrun
44 #include "gmxpre.h"
46 #include <cinttypes>
47 #include <cmath>
48 #include <cstdio>
49 #include <cstdlib>
51 #include <algorithm>
52 #include <memory>
54 #include "gromacs/awh/awh.h"
55 #include "gromacs/commandline/filenm.h"
56 #include "gromacs/compat/make_unique.h"
57 #include "gromacs/domdec/collect.h"
58 #include "gromacs/domdec/domdec.h"
59 #include "gromacs/domdec/domdec_network.h"
60 #include "gromacs/domdec/domdec_struct.h"
61 #include "gromacs/domdec/partition.h"
62 #include "gromacs/essentialdynamics/edsam.h"
63 #include "gromacs/ewald/pme.h"
64 #include "gromacs/ewald/pme-load-balancing.h"
65 #include "gromacs/fileio/trxio.h"
66 #include "gromacs/gmxlib/network.h"
67 #include "gromacs/gmxlib/nrnb.h"
68 #include "gromacs/gpu_utils/gpu_utils.h"
69 #include "gromacs/imd/imd.h"
70 #include "gromacs/listed-forces/manage-threading.h"
71 #include "gromacs/math/functions.h"
72 #include "gromacs/math/utilities.h"
73 #include "gromacs/math/vec.h"
74 #include "gromacs/math/vectypes.h"
75 #include "gromacs/mdlib/checkpointhandler.h"
76 #include "gromacs/mdlib/compute_io.h"
77 #include "gromacs/mdlib/constr.h"
78 #include "gromacs/mdlib/ebin.h"
79 #include "gromacs/mdlib/expanded.h"
80 #include "gromacs/mdlib/force.h"
81 #include "gromacs/mdlib/force_flags.h"
82 #include "gromacs/mdlib/forcerec.h"
83 #include "gromacs/mdlib/md_support.h"
84 #include "gromacs/mdlib/mdatoms.h"
85 #include "gromacs/mdlib/mdebin.h"
86 #include "gromacs/mdlib/mdoutf.h"
87 #include "gromacs/mdlib/mdrun.h"
88 #include "gromacs/mdlib/mdsetup.h"
89 #include "gromacs/mdlib/membed.h"
90 #include "gromacs/mdlib/nb_verlet.h"
91 #include "gromacs/mdlib/nbnxn_gpu_data_mgmt.h"
92 #include "gromacs/mdlib/ns.h"
93 #include "gromacs/mdlib/resethandler.h"
94 #include "gromacs/mdlib/shellfc.h"
95 #include "gromacs/mdlib/sighandler.h"
96 #include "gromacs/mdlib/sim_util.h"
97 #include "gromacs/mdlib/simulationsignal.h"
98 #include "gromacs/mdlib/stophandler.h"
99 #include "gromacs/mdlib/tgroup.h"
100 #include "gromacs/mdlib/trajectory_writing.h"
101 #include "gromacs/mdlib/update.h"
102 #include "gromacs/mdlib/vcm.h"
103 #include "gromacs/mdlib/vsite.h"
104 #include "gromacs/mdtypes/awh-history.h"
105 #include "gromacs/mdtypes/awh-params.h"
106 #include "gromacs/mdtypes/commrec.h"
107 #include "gromacs/mdtypes/df_history.h"
108 #include "gromacs/mdtypes/energyhistory.h"
109 #include "gromacs/mdtypes/fcdata.h"
110 #include "gromacs/mdtypes/forcerec.h"
111 #include "gromacs/mdtypes/group.h"
112 #include "gromacs/mdtypes/inputrec.h"
113 #include "gromacs/mdtypes/interaction_const.h"
114 #include "gromacs/mdtypes/md_enums.h"
115 #include "gromacs/mdtypes/mdatom.h"
116 #include "gromacs/mdtypes/observableshistory.h"
117 #include "gromacs/mdtypes/state.h"
118 #include "gromacs/pbcutil/mshift.h"
119 #include "gromacs/pbcutil/pbc.h"
120 #include "gromacs/pulling/pull.h"
121 #include "gromacs/swap/swapcoords.h"
122 #include "gromacs/timing/wallcycle.h"
123 #include "gromacs/timing/walltime_accounting.h"
124 #include "gromacs/topology/atoms.h"
125 #include "gromacs/topology/idef.h"
126 #include "gromacs/topology/mtop_util.h"
127 #include "gromacs/topology/topology.h"
128 #include "gromacs/trajectory/trajectoryframe.h"
129 #include "gromacs/utility/basedefinitions.h"
130 #include "gromacs/utility/cstringutil.h"
131 #include "gromacs/utility/fatalerror.h"
132 #include "gromacs/utility/logger.h"
133 #include "gromacs/utility/real.h"
134 #include "gromacs/utility/smalloc.h"
136 #include "integrator.h"
137 #include "replicaexchange.h"
139 #ifdef GMX_FAHCORE
140 #include "corewrap.h"
141 #endif
143 using gmx::SimulationSignaller;
145 void gmx::Integrator::do_md()
147 // TODO Historically, the EM and MD "integrators" used different
148 // names for the t_inputrec *parameter, but these must have the
149 // same name, now that it's a member of a struct. We use this ir
150 // alias to avoid a large ripple of nearly useless changes.
151 // t_inputrec is being replaced by IMdpOptionsProvider, so this
152 // will go away eventually.
153 t_inputrec *ir = inputrec;
154 gmx_mdoutf *outf = nullptr;
155 int64_t step, step_rel;
156 double t, t0, lam0[efptNR];
157 gmx_bool bGStatEveryStep, bGStat, bCalcVir, bCalcEnerStep, bCalcEner;
158 gmx_bool bNS, bNStList, bSimAnn, bStopCM,
159 bFirstStep, bInitStep, bLastStep = FALSE;
160 gmx_bool bDoDHDL = FALSE, bDoFEP = FALSE, bDoExpanded = FALSE;
161 gmx_bool do_ene, do_log, do_verbose;
162 gmx_bool bMasterState;
163 int force_flags, cglo_flags;
164 tensor force_vir, shake_vir, total_vir, tmp_vir, pres;
165 int i, m;
166 rvec mu_tot;
167 t_vcm *vcm;
168 matrix parrinellorahmanMu, M;
169 gmx_repl_ex_t repl_ex = nullptr;
170 gmx_localtop_t *top;
171 t_mdebin *mdebin = nullptr;
172 gmx_enerdata_t *enerd;
173 PaddedRVecVector f {};
174 gmx_global_stat_t gstat;
175 gmx_update_t *upd = nullptr;
176 t_graph *graph = nullptr;
177 gmx_groups_t *groups;
178 gmx_ekindata_t *ekind;
179 gmx_shellfc_t *shellfc;
180 gmx_bool bSumEkinhOld, bDoReplEx, bExchanged, bNeedRepartition;
181 gmx_bool bTemp, bPres, bTrotter;
182 real dvdl_constr;
183 rvec *cbuf = nullptr;
184 int cbuf_nalloc = 0;
185 matrix lastbox;
186 int lamnew = 0;
187 /* for FEP */
188 int nstfep = 0;
189 double cycles;
190 real saved_conserved_quantity = 0;
191 real last_ekin = 0;
192 t_extmass MassQ;
193 int **trotter_seq;
194 char sbuf[STEPSTRSIZE], sbuf2[STEPSTRSIZE];
196 /* PME load balancing data for GPU kernels */
197 pme_load_balancing_t *pme_loadbal = nullptr;
198 gmx_bool bPMETune = FALSE;
199 gmx_bool bPMETunePrinting = FALSE;
201 /* Interactive MD */
202 gmx_bool bIMDstep = FALSE;
204 #ifdef GMX_FAHCORE
205 /* Temporary addition for FAHCORE checkpointing */
206 int chkpt_ret;
207 #endif
208 /* Domain decomposition could incorrectly miss a bonded
209 interaction, but checking for that requires a global
210 communication stage, which does not otherwise happen in DD
211 code. So we do that alongside the first global energy reduction
212 after a new DD is made. These variables handle whether the
213 check happens, and the result it returns. */
214 bool shouldCheckNumberOfBondedInteractions = false;
215 int totalNumberOfBondedInteractions = -1;
217 SimulationSignals signals;
218 // Most global communnication stages don't propagate mdrun
219 // signals, and will use this object to achieve that.
220 SimulationSignaller nullSignaller(nullptr, nullptr, nullptr, false, false);
222 if (!mdrunOptions.writeConfout)
224 // This is on by default, and the main known use case for
225 // turning it off is for convenience in benchmarking, which is
226 // something that should not show up in the general user
227 // interface.
228 GMX_LOG(mdlog.info).asParagraph().
229 appendText("The -noconfout functionality is deprecated, and may be removed in a future version.");
232 /* md-vv uses averaged full step velocities for T-control
233 md-vv-avek uses averaged half step velocities for T-control (but full step ekin for P control)
234 md uses averaged half step kinetic energies to determine temperature unless defined otherwise by GMX_EKIN_AVE_VEL; */
235 bTrotter = (EI_VV(ir->eI) && (inputrecNptTrotter(ir) || inputrecNphTrotter(ir) || inputrecNvtTrotter(ir)));
237 const bool bRerunMD = false;
238 int nstglobalcomm = mdrunOptions.globalCommunicationInterval;
240 nstglobalcomm = check_nstglobalcomm(mdlog, nstglobalcomm, ir);
241 bGStatEveryStep = (nstglobalcomm == 1);
243 groups = &top_global->groups;
245 std::unique_ptr<EssentialDynamics> ed = nullptr;
246 if (opt2bSet("-ei", nfile, fnm) || observablesHistory->edsamHistory != nullptr)
248 /* Initialize essential dynamics sampling */
249 ed = init_edsam(opt2fn_null("-ei", nfile, fnm), opt2fn("-eo", nfile, fnm),
250 top_global,
251 ir, cr, constr,
252 state_global, observablesHistory,
253 oenv, mdrunOptions.continuationOptions.appendFiles);
256 /* Initial values */
257 init_md(fplog, cr, outputProvider, ir, oenv, mdrunOptions,
258 &t, &t0, state_global, lam0,
259 nrnb, top_global, &upd, deform,
260 nfile, fnm, &outf, &mdebin,
261 force_vir, shake_vir, total_vir, pres, mu_tot, &bSimAnn, &vcm, wcycle);
263 /* Energy terms and groups */
264 snew(enerd, 1);
265 init_enerdata(top_global->groups.grps[egcENER].nr, ir->fepvals->n_lambda,
266 enerd);
268 /* Kinetic energy data */
269 snew(ekind, 1);
270 init_ekindata(fplog, top_global, &(ir->opts), ekind);
271 /* Copy the cos acceleration to the groups struct */
272 ekind->cosacc.cos_accel = ir->cos_accel;
274 gstat = global_stat_init(ir);
276 /* Check for polarizable models and flexible constraints */
277 shellfc = init_shell_flexcon(fplog,
278 top_global, constr ? constr->numFlexibleConstraints() : 0,
279 ir->nstcalcenergy, DOMAINDECOMP(cr));
282 double io = compute_io(ir, top_global->natoms, groups, mdebin->ebin->nener, 1);
283 if ((io > 2000) && MASTER(cr))
285 fprintf(stderr,
286 "\nWARNING: This run will generate roughly %.0f Mb of data\n\n",
287 io);
291 /* Set up interactive MD (IMD) */
292 init_IMD(ir, cr, ms, top_global, fplog, ir->nstcalcenergy,
293 MASTER(cr) ? as_rvec_array(state_global->x.data()) : nullptr,
294 nfile, fnm, oenv, mdrunOptions);
296 // Local state only becomes valid now.
297 std::unique_ptr<t_state> stateInstance;
298 t_state * state;
300 if (DOMAINDECOMP(cr))
302 top = dd_init_local_top(top_global);
304 stateInstance = compat::make_unique<t_state>();
305 state = stateInstance.get();
306 dd_init_local_state(cr->dd, state_global, state);
308 /* Distribute the charge groups over the nodes from the master node */
309 dd_partition_system(fplog, mdlog, ir->init_step, cr, TRUE, 1,
310 state_global, top_global, ir,
311 state, &f, mdAtoms, top, fr,
312 vsite, constr,
313 nrnb, nullptr, FALSE);
314 shouldCheckNumberOfBondedInteractions = true;
315 update_realloc(upd, state->natoms);
317 else
319 state_change_natoms(state_global, state_global->natoms);
320 /* We need to allocate one element extra, since we might use
321 * (unaligned) 4-wide SIMD loads to access rvec entries.
323 f.resize(gmx::paddedRVecVectorSize(state_global->natoms));
324 /* Copy the pointer to the global state */
325 state = state_global;
327 snew(top, 1);
328 mdAlgorithmsSetupAtomData(cr, ir, top_global, top, fr,
329 &graph, mdAtoms, constr, vsite, shellfc);
331 update_realloc(upd, state->natoms);
334 auto mdatoms = mdAtoms->mdatoms();
336 // NOTE: The global state is no longer used at this point.
337 // But state_global is still used as temporary storage space for writing
338 // the global state to file and potentially for replica exchange.
339 // (Global topology should persist.)
341 update_mdatoms(mdatoms, state->lambda[efptMASS]);
343 const ContinuationOptions &continuationOptions = mdrunOptions.continuationOptions;
344 bool startingFromCheckpoint = continuationOptions.startedFromCheckpoint;
346 if (ir->bExpanded)
348 init_expanded_ensemble(startingFromCheckpoint, ir, state->dfhist);
351 if (MASTER(cr))
353 if (startingFromCheckpoint)
355 /* Update mdebin with energy history if appending to output files */
356 if (continuationOptions.appendFiles)
358 restore_energyhistory_from_state(mdebin, observablesHistory->energyHistory.get());
360 else if (observablesHistory->energyHistory != nullptr)
362 /* We might have read an energy history from checkpoint.
363 * As we are not appending, we want to restart the statistics.
364 * Free the allocated memory and reset the counts.
366 observablesHistory->energyHistory = {};
369 if (observablesHistory->energyHistory == nullptr)
371 observablesHistory->energyHistory = compat::make_unique<energyhistory_t>();
373 /* Set the initial energy history in state by updating once */
374 update_energyhistory(observablesHistory->energyHistory.get(), mdebin);
377 // TODO: Remove this by converting AWH into a ForceProvider
378 auto awh = prepareAwhModule(fplog, *ir, state_global, cr, ms, startingFromCheckpoint,
379 shellfc != nullptr,
380 opt2fn("-awh", nfile, fnm), ir->pull_work);
382 const bool useReplicaExchange = (replExParams.exchangeInterval > 0);
383 if (useReplicaExchange && MASTER(cr))
385 repl_ex = init_replica_exchange(fplog, ms, top_global->natoms, ir,
386 replExParams);
388 /* PME tuning is only supported in the Verlet scheme, with PME for
389 * Coulomb. It is not supported with only LJ PME. */
390 bPMETune = (mdrunOptions.tunePme && EEL_PME(fr->ic->eeltype) &&
391 !mdrunOptions.reproducible && ir->cutoff_scheme != ecutsGROUP);
392 if (bPMETune)
394 pme_loadbal_init(&pme_loadbal, cr, mdlog, *ir, state->box,
395 *fr->ic, *fr->nbv->listParams, fr->pmedata, use_GPU(fr->nbv),
396 &bPMETunePrinting);
399 if (!ir->bContinuation)
401 if (state->flags & (1 << estV))
403 /* Set the velocities of vsites, shells and frozen atoms to zero */
404 for (i = 0; i < mdatoms->homenr; i++)
406 if (mdatoms->ptype[i] == eptVSite ||
407 mdatoms->ptype[i] == eptShell)
409 clear_rvec(state->v[i]);
411 else if (mdatoms->cFREEZE)
413 for (m = 0; m < DIM; m++)
415 if (ir->opts.nFreeze[mdatoms->cFREEZE[i]][m])
417 state->v[i][m] = 0;
424 if (constr)
426 /* Constrain the initial coordinates and velocities */
427 do_constrain_first(fplog, constr, ir, mdatoms, state);
429 if (vsite)
431 /* Construct the virtual sites for the initial configuration */
432 construct_vsites(vsite, as_rvec_array(state->x.data()), ir->delta_t, nullptr,
433 top->idef.iparams, top->idef.il,
434 fr->ePBC, fr->bMolPBC, cr, state->box);
438 if (ir->efep != efepNO)
440 /* Set free energy calculation frequency as the greatest common
441 * denominator of nstdhdl and repl_ex_nst. */
442 nstfep = ir->fepvals->nstdhdl;
443 if (ir->bExpanded)
445 nstfep = gmx_greatest_common_divisor(ir->expandedvals->nstexpanded, nstfep);
447 if (useReplicaExchange)
449 nstfep = gmx_greatest_common_divisor(replExParams.exchangeInterval, nstfep);
453 /* Be REALLY careful about what flags you set here. You CANNOT assume
454 * this is the first step, since we might be restarting from a checkpoint,
455 * and in that case we should not do any modifications to the state.
457 bStopCM = (ir->comm_mode != ecmNO && !ir->bContinuation);
459 if (continuationOptions.haveReadEkin)
461 restore_ekinstate_from_state(cr, ekind, &state_global->ekinstate);
464 cglo_flags = (CGLO_INITIALIZATION | CGLO_TEMPERATURE | CGLO_GSTAT
465 | (EI_VV(ir->eI) ? CGLO_PRESSURE : 0)
466 | (EI_VV(ir->eI) ? CGLO_CONSTRAINT : 0)
467 | (continuationOptions.haveReadEkin ? CGLO_READEKIN : 0));
469 bSumEkinhOld = FALSE;
470 /* To minimize communication, compute_globals computes the COM velocity
471 * and the kinetic energy for the velocities without COM motion removed.
472 * Thus to get the kinetic energy without the COM contribution, we need
473 * to call compute_globals twice.
475 for (int cgloIteration = 0; cgloIteration < (bStopCM ? 2 : 1); cgloIteration++)
477 int cglo_flags_iteration = cglo_flags;
478 if (bStopCM && cgloIteration == 0)
480 cglo_flags_iteration |= CGLO_STOPCM;
481 cglo_flags_iteration &= ~CGLO_TEMPERATURE;
483 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
484 nullptr, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
485 constr, &nullSignaller, state->box,
486 &totalNumberOfBondedInteractions, &bSumEkinhOld, cglo_flags_iteration
487 | (shouldCheckNumberOfBondedInteractions ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS : 0));
489 checkNumberOfBondedInteractions(mdlog, cr, totalNumberOfBondedInteractions,
490 top_global, top, state,
491 &shouldCheckNumberOfBondedInteractions);
492 if (ir->eI == eiVVAK)
494 /* a second call to get the half step temperature initialized as well */
495 /* we do the same call as above, but turn the pressure off -- internally to
496 compute_globals, this is recognized as a velocity verlet half-step
497 kinetic energy calculation. This minimized excess variables, but
498 perhaps loses some logic?*/
500 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
501 nullptr, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
502 constr, &nullSignaller, state->box,
503 nullptr, &bSumEkinhOld,
504 cglo_flags & ~CGLO_PRESSURE);
507 /* Calculate the initial half step temperature, and save the ekinh_old */
508 if (!continuationOptions.startedFromCheckpoint)
510 for (i = 0; (i < ir->opts.ngtc); i++)
512 copy_mat(ekind->tcstat[i].ekinh, ekind->tcstat[i].ekinh_old);
516 /* need to make an initiation call to get the Trotter variables set, as well as other constants for non-trotter
517 temperature control */
518 trotter_seq = init_npt_vars(ir, state, &MassQ, bTrotter);
520 if (MASTER(cr))
522 if (!ir->bContinuation)
524 if (constr && ir->eConstrAlg == econtLINCS)
526 fprintf(fplog,
527 "RMS relative constraint deviation after constraining: %.2e\n",
528 constr->rmsd());
530 if (EI_STATE_VELOCITY(ir->eI))
532 real temp = enerd->term[F_TEMP];
533 if (ir->eI != eiVV)
535 /* Result of Ekin averaged over velocities of -half
536 * and +half step, while we only have -half step here.
538 temp *= 2;
540 fprintf(fplog, "Initial temperature: %g K\n", temp);
544 char tbuf[20];
545 fprintf(stderr, "starting mdrun '%s'\n",
546 *(top_global->name));
547 if (ir->nsteps >= 0)
549 sprintf(tbuf, "%8.1f", (ir->init_step+ir->nsteps)*ir->delta_t);
551 else
553 sprintf(tbuf, "%s", "infinite");
555 if (ir->init_step > 0)
557 fprintf(stderr, "%s steps, %s ps (continuing from step %s, %8.1f ps).\n",
558 gmx_step_str(ir->init_step+ir->nsteps, sbuf), tbuf,
559 gmx_step_str(ir->init_step, sbuf2),
560 ir->init_step*ir->delta_t);
562 else
564 fprintf(stderr, "%s steps, %s ps.\n",
565 gmx_step_str(ir->nsteps, sbuf), tbuf);
567 fprintf(fplog, "\n");
570 walltime_accounting_start_time(walltime_accounting);
571 wallcycle_start(wcycle, ewcRUN);
572 print_start(fplog, cr, walltime_accounting, "mdrun");
574 /* safest point to do file checkpointing is here. More general point would be immediately before integrator call */
575 #ifdef GMX_FAHCORE
576 chkpt_ret = fcCheckPointParallel( cr->nodeid,
577 NULL, 0);
578 if (chkpt_ret == 0)
580 gmx_fatal( 3, __FILE__, __LINE__, "Checkpoint error on step %d\n", 0 );
582 #endif
584 /***********************************************************
586 * Loop over MD steps
588 ************************************************************/
590 bFirstStep = TRUE;
591 /* Skip the first Nose-Hoover integration when we get the state from tpx */
592 bInitStep = !startingFromCheckpoint || EI_VV(ir->eI);
593 bSumEkinhOld = FALSE;
594 bExchanged = FALSE;
595 bNeedRepartition = FALSE;
597 bool simulationsShareState = false;
598 int nstSignalComm = nstglobalcomm;
600 // TODO This implementation of ensemble orientation restraints is nasty because
601 // a user can't just do multi-sim with single-sim orientation restraints.
602 bool usingEnsembleRestraints = (fcd->disres.nsystems > 1) || ((ms != nullptr) && (fcd->orires.nr != 0));
603 bool awhUsesMultiSim = (ir->bDoAwh && ir->awhParams->shareBiasMultisim && (ms != nullptr));
605 // Replica exchange, ensemble restraints and AWH need all
606 // simulations to remain synchronized, so they need
607 // checkpoints and stop conditions to act on the same step, so
608 // the propagation of such signals must take place between
609 // simulations, not just within simulations.
610 // TODO: Make algorithm initializers set these flags.
611 simulationsShareState = useReplicaExchange || usingEnsembleRestraints || awhUsesMultiSim;
613 if (simulationsShareState)
615 // Inter-simulation signal communication does not need to happen
616 // often, so we use a minimum of 200 steps to reduce overhead.
617 const int c_minimumInterSimulationSignallingInterval = 200;
618 nstSignalComm = ((c_minimumInterSimulationSignallingInterval + nstglobalcomm - 1)/nstglobalcomm)*nstglobalcomm;
622 auto stopHandler = stopHandlerBuilder->getStopHandlerMD(
623 compat::not_null<SimulationSignal*>(&signals[eglsSTOPCOND]), simulationsShareState,
624 MASTER(cr), ir->nstlist, mdrunOptions.reproducible, nstSignalComm,
625 mdrunOptions.maximumHoursToRun, ir->nstlist == 0, fplog, step, bNS, walltime_accounting);
627 auto checkpointHandler = compat::make_unique<CheckpointHandler>(
628 compat::make_not_null<SimulationSignal*>(&signals[eglsCHKPT]),
629 simulationsShareState, ir->nstlist == 0, MASTER(cr),
630 mdrunOptions.writeConfout, mdrunOptions.checkpointOptions.period);
632 const bool resetCountersIsLocal = true;
633 auto resetHandler = compat::make_unique<ResetHandler>(
634 compat::make_not_null<SimulationSignal*>(&signals[eglsRESETCOUNTERS]), !resetCountersIsLocal,
635 ir->nsteps, MASTER(cr), mdrunOptions.timingOptions.resetHalfway,
636 mdrunOptions.maximumHoursToRun, mdlog, wcycle, walltime_accounting);
638 DdOpenBalanceRegionBeforeForceComputation ddOpenBalanceRegion = (DOMAINDECOMP(cr) ? DdOpenBalanceRegionBeforeForceComputation::yes : DdOpenBalanceRegionBeforeForceComputation::no);
639 DdCloseBalanceRegionAfterForceComputation ddCloseBalanceRegion = (DOMAINDECOMP(cr) ? DdCloseBalanceRegionAfterForceComputation::yes : DdCloseBalanceRegionAfterForceComputation::no);
641 step = ir->init_step;
642 step_rel = 0;
644 // TODO extract this to new multi-simulation module
645 if (MASTER(cr) && isMultiSim(ms) && !useReplicaExchange)
647 if (!multisim_int_all_are_equal(ms, ir->nsteps))
649 GMX_LOG(mdlog.warning).appendText(
650 "Note: The number of steps is not consistent across multi simulations,\n"
651 "but we are proceeding anyway!");
653 if (!multisim_int_all_are_equal(ms, ir->init_step))
655 GMX_LOG(mdlog.warning).appendText(
656 "Note: The initial step is not consistent across multi simulations,\n"
657 "but we are proceeding anyway!");
661 /* and stop now if we should */
662 bLastStep = (bLastStep || (ir->nsteps >= 0 && step_rel > ir->nsteps));
663 while (!bLastStep)
666 /* Determine if this is a neighbor search step */
667 bNStList = (ir->nstlist > 0 && step % ir->nstlist == 0);
669 if (bPMETune && bNStList)
671 /* PME grid + cut-off optimization with GPUs or PME nodes */
672 pme_loadbal_do(pme_loadbal, cr,
673 (mdrunOptions.verbose && MASTER(cr)) ? stderr : nullptr,
674 fplog, mdlog,
675 *ir, fr, *state,
676 wcycle,
677 step, step_rel,
678 &bPMETunePrinting);
681 wallcycle_start(wcycle, ewcSTEP);
683 bLastStep = (step_rel == ir->nsteps);
684 t = t0 + step*ir->delta_t;
686 // TODO Refactor this, so that nstfep does not need a default value of zero
687 if (ir->efep != efepNO || ir->bSimTemp)
689 /* find and set the current lambdas */
690 setCurrentLambdasLocal(step, ir->fepvals, lam0, state);
692 bDoDHDL = do_per_step(step, ir->fepvals->nstdhdl);
693 bDoFEP = ((ir->efep != efepNO) && do_per_step(step, nstfep));
694 bDoExpanded = (do_per_step(step, ir->expandedvals->nstexpanded)
695 && (ir->bExpanded) && (step > 0) && (!startingFromCheckpoint));
698 bDoReplEx = (useReplicaExchange && (step > 0) && !bLastStep &&
699 do_per_step(step, replExParams.exchangeInterval));
701 if (bSimAnn)
703 update_annealing_target_temp(ir, t, upd);
706 /* Stop Center of Mass motion */
707 bStopCM = (ir->comm_mode != ecmNO && do_per_step(step, ir->nstcomm));
709 /* Determine whether or not to do Neighbour Searching */
710 bNS = (bFirstStep || bNStList || bExchanged || bNeedRepartition);
712 bLastStep = bLastStep || stopHandler->stoppingAfterCurrentStep(bNS);
714 /* do_log triggers energy and virial calculation. Because this leads
715 * to different code paths, forces can be different. Thus for exact
716 * continuation we should avoid extra log output.
717 * Note that the || bLastStep can result in non-exact continuation
718 * beyond the last step. But we don't consider that to be an issue.
720 do_log = do_per_step(step, ir->nstlog) || (bFirstStep && !startingFromCheckpoint) || bLastStep;
721 do_verbose = mdrunOptions.verbose &&
722 (step % mdrunOptions.verboseStepPrintInterval == 0 || bFirstStep || bLastStep);
724 if (bNS && !(bFirstStep && ir->bContinuation))
726 bMasterState = FALSE;
727 /* Correct the new box if it is too skewed */
728 if (inputrecDynamicBox(ir))
730 if (correct_box(fplog, step, state->box, graph))
732 bMasterState = TRUE;
735 if (DOMAINDECOMP(cr) && bMasterState)
737 dd_collect_state(cr->dd, state, state_global);
740 if (DOMAINDECOMP(cr))
742 /* Repartition the domain decomposition */
743 dd_partition_system(fplog, mdlog, step, cr,
744 bMasterState, nstglobalcomm,
745 state_global, top_global, ir,
746 state, &f, mdAtoms, top, fr,
747 vsite, constr,
748 nrnb, wcycle,
749 do_verbose && !bPMETunePrinting);
750 shouldCheckNumberOfBondedInteractions = true;
751 update_realloc(upd, state->natoms);
755 if (MASTER(cr) && do_log)
757 print_ebin_header(fplog, step, t); /* can we improve the information printed here? */
760 if (ir->efep != efepNO)
762 update_mdatoms(mdatoms, state->lambda[efptMASS]);
765 if (bExchanged)
768 /* We need the kinetic energy at minus the half step for determining
769 * the full step kinetic energy and possibly for T-coupling.*/
770 /* This may not be quite working correctly yet . . . . */
771 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
772 wcycle, enerd, nullptr, nullptr, nullptr, nullptr, mu_tot,
773 constr, &nullSignaller, state->box,
774 &totalNumberOfBondedInteractions, &bSumEkinhOld,
775 CGLO_GSTAT | CGLO_TEMPERATURE | CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS);
776 checkNumberOfBondedInteractions(mdlog, cr, totalNumberOfBondedInteractions,
777 top_global, top, state,
778 &shouldCheckNumberOfBondedInteractions);
780 clear_mat(force_vir);
782 checkpointHandler->decideIfCheckpointingThisStep(bNS, bFirstStep, bLastStep);
784 /* Determine the energy and pressure:
785 * at nstcalcenergy steps and at energy output steps (set below).
787 if (EI_VV(ir->eI) && (!bInitStep))
789 /* for vv, the first half of the integration actually corresponds
790 to the previous step. bCalcEner is only required to be evaluated on the 'next' step,
791 but the virial needs to be calculated on both the current step and the 'next' step. Future
792 reorganization may be able to get rid of one of the bCalcVir=TRUE steps. */
794 /* TODO: This is probably not what we want, we will write to energy file one step after nstcalcenergy steps. */
795 bCalcEnerStep = do_per_step(step - 1, ir->nstcalcenergy);
796 bCalcVir = bCalcEnerStep ||
797 (ir->epc != epcNO && (do_per_step(step, ir->nstpcouple) || do_per_step(step-1, ir->nstpcouple)));
799 else
801 bCalcEnerStep = do_per_step(step, ir->nstcalcenergy);
802 bCalcVir = bCalcEnerStep ||
803 (ir->epc != epcNO && do_per_step(step, ir->nstpcouple));
805 bCalcEner = bCalcEnerStep;
807 do_ene = (do_per_step(step, ir->nstenergy) || bLastStep);
809 if (do_ene || do_log || bDoReplEx)
811 bCalcVir = TRUE;
812 bCalcEner = TRUE;
815 /* Do we need global communication ? */
816 bGStat = (bCalcVir || bCalcEner || bStopCM ||
817 do_per_step(step, nstglobalcomm) ||
818 (EI_VV(ir->eI) && inputrecNvtTrotter(ir) && do_per_step(step-1, nstglobalcomm)));
820 force_flags = (GMX_FORCE_STATECHANGED |
821 ((inputrecDynamicBox(ir)) ? GMX_FORCE_DYNAMICBOX : 0) |
822 GMX_FORCE_ALLFORCES |
823 (bCalcVir ? GMX_FORCE_VIRIAL : 0) |
824 (bCalcEner ? GMX_FORCE_ENERGY : 0) |
825 (bDoFEP ? GMX_FORCE_DHDL : 0)
828 if (shellfc)
830 /* Now is the time to relax the shells */
831 relax_shell_flexcon(fplog, cr, ms, mdrunOptions.verbose,
832 enforcedRotation, step,
833 ir, bNS, force_flags, top,
834 constr, enerd, fcd,
835 state, f, force_vir, mdatoms,
836 nrnb, wcycle, graph, groups,
837 shellfc, fr, t, mu_tot,
838 vsite,
839 ddOpenBalanceRegion, ddCloseBalanceRegion);
841 else
843 /* The AWH history need to be saved _before_ doing force calculations where the AWH bias is updated
844 (or the AWH update will be performed twice for one step when continuing). It would be best to
845 call this update function from do_md_trajectory_writing but that would occur after do_force.
846 One would have to divide the update_awh function into one function applying the AWH force
847 and one doing the AWH bias update. The update AWH bias function could then be called after
848 do_md_trajectory_writing (then containing update_awh_history).
849 The checkpointing will in the future probably moved to the start of the md loop which will
850 rid of this issue. */
851 if (awh && checkpointHandler->isCheckpointingStep() && MASTER(cr))
853 awh->updateHistory(state_global->awhHistory.get());
856 /* The coordinates (x) are shifted (to get whole molecules)
857 * in do_force.
858 * This is parallellized as well, and does communication too.
859 * Check comments in sim_util.c
861 do_force(fplog, cr, ms, ir, awh.get(), enforcedRotation,
862 step, nrnb, wcycle, top, groups,
863 state->box, state->x, &state->hist,
864 f, force_vir, mdatoms, enerd, fcd,
865 state->lambda, graph,
866 fr, vsite, mu_tot, t, ed ? ed->getLegacyED() : nullptr,
867 (bNS ? GMX_FORCE_NS : 0) | force_flags,
868 ddOpenBalanceRegion, ddCloseBalanceRegion);
871 if (EI_VV(ir->eI) && !startingFromCheckpoint)
872 /* ############### START FIRST UPDATE HALF-STEP FOR VV METHODS############### */
874 rvec *vbuf = nullptr;
876 wallcycle_start(wcycle, ewcUPDATE);
877 if (ir->eI == eiVV && bInitStep)
879 /* if using velocity verlet with full time step Ekin,
880 * take the first half step only to compute the
881 * virial for the first step. From there,
882 * revert back to the initial coordinates
883 * so that the input is actually the initial step.
885 snew(vbuf, state->natoms);
886 copy_rvecn(as_rvec_array(state->v.data()), vbuf, 0, state->natoms); /* should make this better for parallelizing? */
888 else
890 /* this is for NHC in the Ekin(t+dt/2) version of vv */
891 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ1);
894 update_coords(step, ir, mdatoms, state, f, fcd,
895 ekind, M, upd, etrtVELOCITY1,
896 cr, constr);
898 wallcycle_stop(wcycle, ewcUPDATE);
899 constrain_velocities(step, nullptr,
900 state,
901 shake_vir,
902 wcycle, constr,
903 bCalcVir, do_log, do_ene);
904 wallcycle_start(wcycle, ewcUPDATE);
905 /* if VV, compute the pressure and constraints */
906 /* For VV2, we strictly only need this if using pressure
907 * control, but we really would like to have accurate pressures
908 * printed out.
909 * Think about ways around this in the future?
910 * For now, keep this choice in comments.
912 /*bPres = (ir->eI==eiVV || inputrecNptTrotter(ir)); */
913 /*bTemp = ((ir->eI==eiVV &&(!bInitStep)) || (ir->eI==eiVVAK && inputrecNptTrotter(ir)));*/
914 bPres = TRUE;
915 bTemp = ((ir->eI == eiVV && (!bInitStep)) || (ir->eI == eiVVAK));
916 if (bCalcEner && ir->eI == eiVVAK)
918 bSumEkinhOld = TRUE;
920 /* for vv, the first half of the integration actually corresponds to the previous step.
921 So we need information from the last step in the first half of the integration */
922 if (bGStat || do_per_step(step-1, nstglobalcomm))
924 wallcycle_stop(wcycle, ewcUPDATE);
925 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
926 wcycle, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
927 constr, &nullSignaller, state->box,
928 &totalNumberOfBondedInteractions, &bSumEkinhOld,
929 (bGStat ? CGLO_GSTAT : 0)
930 | CGLO_ENERGY
931 | (bTemp ? CGLO_TEMPERATURE : 0)
932 | (bPres ? CGLO_PRESSURE : 0)
933 | (bPres ? CGLO_CONSTRAINT : 0)
934 | (bStopCM ? CGLO_STOPCM : 0)
935 | (shouldCheckNumberOfBondedInteractions ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS : 0)
936 | CGLO_SCALEEKIN
938 /* explanation of above:
939 a) We compute Ekin at the full time step
940 if 1) we are using the AveVel Ekin, and it's not the
941 initial step, or 2) if we are using AveEkin, but need the full
942 time step kinetic energy for the pressure (always true now, since we want accurate statistics).
943 b) If we are using EkinAveEkin for the kinetic energy for the temperature control, we still feed in
944 EkinAveVel because it's needed for the pressure */
945 checkNumberOfBondedInteractions(mdlog, cr, totalNumberOfBondedInteractions,
946 top_global, top, state,
947 &shouldCheckNumberOfBondedInteractions);
948 wallcycle_start(wcycle, ewcUPDATE);
950 /* temperature scaling and pressure scaling to produce the extended variables at t+dt */
951 if (!bInitStep)
953 if (bTrotter)
955 m_add(force_vir, shake_vir, total_vir); /* we need the un-dispersion corrected total vir here */
956 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ2);
958 /* TODO This is only needed when we're about to write
959 * a checkpoint, because we use it after the restart
960 * (in a kludge?). But what should we be doing if
961 * startingFromCheckpoint or bInitStep are true? */
962 if (inputrecNptTrotter(ir) || inputrecNphTrotter(ir))
964 copy_mat(shake_vir, state->svir_prev);
965 copy_mat(force_vir, state->fvir_prev);
967 if (inputrecNvtTrotter(ir) && ir->eI == eiVV)
969 /* update temperature and kinetic energy now that step is over - this is the v(t+dt) point */
970 enerd->term[F_TEMP] = sum_ekin(&(ir->opts), ekind, nullptr, (ir->eI == eiVV), FALSE);
971 enerd->term[F_EKIN] = trace(ekind->ekin);
974 else if (bExchanged)
976 wallcycle_stop(wcycle, ewcUPDATE);
977 /* We need the kinetic energy at minus the half step for determining
978 * the full step kinetic energy and possibly for T-coupling.*/
979 /* This may not be quite working correctly yet . . . . */
980 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
981 wcycle, enerd, nullptr, nullptr, nullptr, nullptr, mu_tot,
982 constr, &nullSignaller, state->box,
983 nullptr, &bSumEkinhOld,
984 CGLO_GSTAT | CGLO_TEMPERATURE);
985 wallcycle_start(wcycle, ewcUPDATE);
988 /* if it's the initial step, we performed this first step just to get the constraint virial */
989 if (ir->eI == eiVV && bInitStep)
991 copy_rvecn(vbuf, as_rvec_array(state->v.data()), 0, state->natoms);
992 sfree(vbuf);
994 wallcycle_stop(wcycle, ewcUPDATE);
997 /* compute the conserved quantity */
998 if (EI_VV(ir->eI))
1000 saved_conserved_quantity = NPT_energy(ir, state, &MassQ);
1001 if (ir->eI == eiVV)
1003 last_ekin = enerd->term[F_EKIN];
1005 if ((ir->eDispCorr != edispcEnerPres) && (ir->eDispCorr != edispcAllEnerPres))
1007 saved_conserved_quantity -= enerd->term[F_DISPCORR];
1009 /* sum up the foreign energy and dhdl terms for vv. currently done every step so that dhdl is correct in the .edr */
1010 if (ir->efep != efepNO)
1012 sum_dhdl(enerd, state->lambda, ir->fepvals);
1016 /* ######## END FIRST UPDATE STEP ############## */
1017 /* ######## If doing VV, we now have v(dt) ###### */
1018 if (bDoExpanded)
1020 /* perform extended ensemble sampling in lambda - we don't
1021 actually move to the new state before outputting
1022 statistics, but if performing simulated tempering, we
1023 do update the velocities and the tau_t. */
1025 lamnew = ExpandedEnsembleDynamics(fplog, ir, enerd, state, &MassQ, state->fep_state, state->dfhist, step, as_rvec_array(state->v.data()), mdatoms);
1026 /* history is maintained in state->dfhist, but state_global is what is sent to trajectory and log output */
1027 if (MASTER(cr))
1029 copy_df_history(state_global->dfhist, state->dfhist);
1033 /* Now we have the energies and forces corresponding to the
1034 * coordinates at time t. We must output all of this before
1035 * the update.
1037 do_md_trajectory_writing(fplog, cr, nfile, fnm, step, step_rel, t,
1038 ir, state, state_global, observablesHistory,
1039 top_global, fr,
1040 outf, mdebin, ekind, f,
1041 checkpointHandler->isCheckpointingStep(),
1042 bRerunMD, bLastStep,
1043 mdrunOptions.writeConfout,
1044 bSumEkinhOld);
1045 /* Check if IMD step and do IMD communication, if bIMD is TRUE. */
1046 bIMDstep = do_IMD(ir->bIMD, step, cr, bNS, state->box, as_rvec_array(state->x.data()), ir, t, wcycle);
1048 /* kludge -- virial is lost with restart for MTTK NPT control. Must reload (saved earlier). */
1049 if (startingFromCheckpoint && (inputrecNptTrotter(ir) || inputrecNphTrotter(ir)))
1051 copy_mat(state->svir_prev, shake_vir);
1052 copy_mat(state->fvir_prev, force_vir);
1055 stopHandler->setSignal();
1056 resetHandler->setSignal(walltime_accounting);
1058 if (bGStat || !PAR(cr))
1060 /* In parallel we only have to check for checkpointing in steps
1061 * where we do global communication,
1062 * otherwise the other nodes don't know.
1064 checkpointHandler->setSignal(walltime_accounting);
1067 /* ######### START SECOND UPDATE STEP ################# */
1069 /* at the start of step, randomize or scale the velocities ((if vv. Restriction of Andersen controlled
1070 in preprocessing */
1072 if (ETC_ANDERSEN(ir->etc)) /* keep this outside of update_tcouple because of the extra info required to pass */
1074 gmx_bool bIfRandomize;
1075 bIfRandomize = update_randomize_velocities(ir, step, cr, mdatoms, state, upd, constr);
1076 /* if we have constraints, we have to remove the kinetic energy parallel to the bonds */
1077 if (constr && bIfRandomize)
1079 constrain_velocities(step, nullptr,
1080 state,
1081 tmp_vir,
1082 wcycle, constr,
1083 bCalcVir, do_log, do_ene);
1086 /* Box is changed in update() when we do pressure coupling,
1087 * but we should still use the old box for energy corrections and when
1088 * writing it to the energy file, so it matches the trajectory files for
1089 * the same timestep above. Make a copy in a separate array.
1091 copy_mat(state->box, lastbox);
1093 dvdl_constr = 0;
1095 wallcycle_start(wcycle, ewcUPDATE);
1096 /* UPDATE PRESSURE VARIABLES IN TROTTER FORMULATION WITH CONSTRAINTS */
1097 if (bTrotter)
1099 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ3);
1100 /* We can only do Berendsen coupling after we have summed
1101 * the kinetic energy or virial. Since the happens
1102 * in global_state after update, we should only do it at
1103 * step % nstlist = 1 with bGStatEveryStep=FALSE.
1106 else
1108 update_tcouple(step, ir, state, ekind, &MassQ, mdatoms);
1109 update_pcouple_before_coordinates(fplog, step, ir, state,
1110 parrinellorahmanMu, M,
1111 bInitStep);
1114 if (EI_VV(ir->eI))
1116 /* velocity half-step update */
1117 update_coords(step, ir, mdatoms, state, f, fcd,
1118 ekind, M, upd, etrtVELOCITY2,
1119 cr, constr);
1122 /* Above, initialize just copies ekinh into ekin,
1123 * it doesn't copy position (for VV),
1124 * and entire integrator for MD.
1127 if (ir->eI == eiVVAK)
1129 /* We probably only need md->homenr, not state->natoms */
1130 if (state->natoms > cbuf_nalloc)
1132 cbuf_nalloc = state->natoms;
1133 srenew(cbuf, cbuf_nalloc);
1135 copy_rvecn(as_rvec_array(state->x.data()), cbuf, 0, state->natoms);
1138 update_coords(step, ir, mdatoms, state, f, fcd,
1139 ekind, M, upd, etrtPOSITION, cr, constr);
1140 wallcycle_stop(wcycle, ewcUPDATE);
1142 constrain_coordinates(step, &dvdl_constr, state,
1143 shake_vir,
1144 wcycle, upd, constr,
1145 bCalcVir, do_log, do_ene);
1146 update_sd_second_half(step, &dvdl_constr, ir, mdatoms, state,
1147 cr, nrnb, wcycle, upd, constr, do_log, do_ene);
1148 finish_update(ir, mdatoms,
1149 state, graph,
1150 nrnb, wcycle, upd, constr);
1152 if (ir->eI == eiVVAK)
1154 /* erase F_EKIN and F_TEMP here? */
1155 /* just compute the kinetic energy at the half step to perform a trotter step */
1156 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
1157 wcycle, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
1158 constr, &nullSignaller, lastbox,
1159 nullptr, &bSumEkinhOld,
1160 (bGStat ? CGLO_GSTAT : 0) | CGLO_TEMPERATURE
1162 wallcycle_start(wcycle, ewcUPDATE);
1163 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ4);
1164 /* now we know the scaling, we can compute the positions again again */
1165 copy_rvecn(cbuf, as_rvec_array(state->x.data()), 0, state->natoms);
1167 update_coords(step, ir, mdatoms, state, f, fcd,
1168 ekind, M, upd, etrtPOSITION, cr, constr);
1169 wallcycle_stop(wcycle, ewcUPDATE);
1171 /* do we need an extra constraint here? just need to copy out of as_rvec_array(state->v.data()) to upd->xp? */
1172 /* are the small terms in the shake_vir here due
1173 * to numerical errors, or are they important
1174 * physically? I'm thinking they are just errors, but not completely sure.
1175 * For now, will call without actually constraining, constr=NULL*/
1176 finish_update(ir, mdatoms,
1177 state, graph,
1178 nrnb, wcycle, upd, nullptr);
1180 if (EI_VV(ir->eI))
1182 /* this factor or 2 correction is necessary
1183 because half of the constraint force is removed
1184 in the vv step, so we have to double it. See
1185 the Redmine issue #1255. It is not yet clear
1186 if the factor of 2 is exact, or just a very
1187 good approximation, and this will be
1188 investigated. The next step is to see if this
1189 can be done adding a dhdl contribution from the
1190 rattle step, but this is somewhat more
1191 complicated with the current code. Will be
1192 investigated, hopefully for 4.6.3. However,
1193 this current solution is much better than
1194 having it completely wrong.
1196 enerd->term[F_DVDL_CONSTR] += 2*dvdl_constr;
1198 else
1200 enerd->term[F_DVDL_CONSTR] += dvdl_constr;
1203 if (vsite != nullptr)
1205 wallcycle_start(wcycle, ewcVSITECONSTR);
1206 if (graph != nullptr)
1208 shift_self(graph, state->box, as_rvec_array(state->x.data()));
1210 construct_vsites(vsite, as_rvec_array(state->x.data()), ir->delta_t, as_rvec_array(state->v.data()),
1211 top->idef.iparams, top->idef.il,
1212 fr->ePBC, fr->bMolPBC, cr, state->box);
1214 if (graph != nullptr)
1216 unshift_self(graph, state->box, as_rvec_array(state->x.data()));
1218 wallcycle_stop(wcycle, ewcVSITECONSTR);
1221 /* ############## IF NOT VV, Calculate globals HERE ############ */
1222 /* With Leap-Frog we can skip compute_globals at
1223 * non-communication steps, but we need to calculate
1224 * the kinetic energy one step before communication.
1227 // Organize to do inter-simulation signalling on steps if
1228 // and when algorithms require it.
1229 bool doInterSimSignal = (simulationsShareState && do_per_step(step, nstSignalComm));
1231 if (bGStat || (!EI_VV(ir->eI) && do_per_step(step+1, nstglobalcomm)) || doInterSimSignal)
1233 // Since we're already communicating at this step, we
1234 // can propagate intra-simulation signals. Note that
1235 // check_nstglobalcomm has the responsibility for
1236 // choosing the value of nstglobalcomm that is one way
1237 // bGStat becomes true, so we can't get into a
1238 // situation where e.g. checkpointing can't be
1239 // signalled.
1240 bool doIntraSimSignal = true;
1241 SimulationSignaller signaller(&signals, cr, ms, doInterSimSignal, doIntraSimSignal);
1243 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, mdatoms, nrnb, vcm,
1244 wcycle, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
1245 constr, &signaller,
1246 lastbox,
1247 &totalNumberOfBondedInteractions, &bSumEkinhOld,
1248 (bGStat ? CGLO_GSTAT : 0)
1249 | (!EI_VV(ir->eI) ? CGLO_ENERGY : 0)
1250 | (!EI_VV(ir->eI) && bStopCM ? CGLO_STOPCM : 0)
1251 | (!EI_VV(ir->eI) ? CGLO_TEMPERATURE : 0)
1252 | (!EI_VV(ir->eI) ? CGLO_PRESSURE : 0)
1253 | CGLO_CONSTRAINT
1254 | (shouldCheckNumberOfBondedInteractions ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS : 0)
1256 checkNumberOfBondedInteractions(mdlog, cr, totalNumberOfBondedInteractions,
1257 top_global, top, state,
1258 &shouldCheckNumberOfBondedInteractions);
1262 /* ############# END CALC EKIN AND PRESSURE ################# */
1264 /* Note: this is OK, but there are some numerical precision issues with using the convergence of
1265 the virial that should probably be addressed eventually. state->veta has better properies,
1266 but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could
1267 generate the new shake_vir, but test the veta value for convergence. This will take some thought. */
1269 if (ir->efep != efepNO && !EI_VV(ir->eI))
1271 /* Sum up the foreign energy and dhdl terms for md and sd.
1272 Currently done every step so that dhdl is correct in the .edr */
1273 sum_dhdl(enerd, state->lambda, ir->fepvals);
1276 update_pcouple_after_coordinates(fplog, step, ir, mdatoms,
1277 pres, force_vir, shake_vir,
1278 parrinellorahmanMu,
1279 state, nrnb, upd);
1281 /* ################# END UPDATE STEP 2 ################# */
1282 /* #### We now have r(t+dt) and v(t+dt/2) ############# */
1284 /* The coordinates (x) were unshifted in update */
1285 if (!bGStat)
1287 /* We will not sum ekinh_old,
1288 * so signal that we still have to do it.
1290 bSumEkinhOld = TRUE;
1293 if (bCalcEner)
1295 /* ######### BEGIN PREPARING EDR OUTPUT ########### */
1297 /* use the directly determined last velocity, not actually the averaged half steps */
1298 if (bTrotter && ir->eI == eiVV)
1300 enerd->term[F_EKIN] = last_ekin;
1302 enerd->term[F_ETOT] = enerd->term[F_EPOT] + enerd->term[F_EKIN];
1304 if (integratorHasConservedEnergyQuantity(ir))
1306 if (EI_VV(ir->eI))
1308 enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + saved_conserved_quantity;
1310 else
1312 enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + NPT_energy(ir, state, &MassQ);
1315 /* ######### END PREPARING EDR OUTPUT ########### */
1318 /* Output stuff */
1319 if (MASTER(cr))
1321 if (fplog && do_log && bDoExpanded)
1323 /* only needed if doing expanded ensemble */
1324 PrintFreeEnergyInfoToFile(fplog, ir->fepvals, ir->expandedvals, ir->bSimTemp ? ir->simtempvals : nullptr,
1325 state_global->dfhist, state->fep_state, ir->nstlog, step);
1327 if (bCalcEner)
1329 upd_mdebin(mdebin, bDoDHDL, bCalcEnerStep,
1330 t, mdatoms->tmass, enerd, state,
1331 ir->fepvals, ir->expandedvals, lastbox,
1332 shake_vir, force_vir, total_vir, pres,
1333 ekind, mu_tot, constr);
1335 else
1337 upd_mdebin_step(mdebin);
1340 gmx_bool do_dr = do_per_step(step, ir->nstdisreout);
1341 gmx_bool do_or = do_per_step(step, ir->nstorireout);
1343 print_ebin(mdoutf_get_fp_ene(outf), do_ene, do_dr, do_or, do_log ? fplog : nullptr,
1344 step, t,
1345 eprNORMAL, mdebin, fcd, groups, &(ir->opts), awh.get());
1347 if (ir->bPull)
1349 pull_print_output(ir->pull_work, step, t);
1352 if (do_per_step(step, ir->nstlog))
1354 if (fflush(fplog) != 0)
1356 gmx_fatal(FARGS, "Cannot flush logfile - maybe you are out of disk space?");
1360 if (bDoExpanded)
1362 /* Have to do this part _after_ outputting the logfile and the edr file */
1363 /* Gets written into the state at the beginning of next loop*/
1364 state->fep_state = lamnew;
1366 /* Print the remaining wall clock time for the run */
1367 if (isMasterSimMasterRank(ms, cr) &&
1368 (do_verbose || gmx_got_usr_signal()) &&
1369 !bPMETunePrinting)
1371 if (shellfc)
1373 fprintf(stderr, "\n");
1375 print_time(stderr, walltime_accounting, step, ir, cr);
1378 /* Ion/water position swapping.
1379 * Not done in last step since trajectory writing happens before this call
1380 * in the MD loop and exchanges would be lost anyway. */
1381 bNeedRepartition = FALSE;
1382 if ((ir->eSwapCoords != eswapNO) && (step > 0) && !bLastStep &&
1383 do_per_step(step, ir->swap->nstswap))
1385 bNeedRepartition = do_swapcoords(cr, step, t, ir, wcycle,
1386 as_rvec_array(state->x.data()),
1387 state->box,
1388 MASTER(cr) && mdrunOptions.verbose,
1389 bRerunMD);
1391 if (bNeedRepartition && DOMAINDECOMP(cr))
1393 dd_collect_state(cr->dd, state, state_global);
1397 /* Replica exchange */
1398 bExchanged = FALSE;
1399 if (bDoReplEx)
1401 bExchanged = replica_exchange(fplog, cr, ms, repl_ex,
1402 state_global, enerd,
1403 state, step, t);
1406 if ( (bExchanged || bNeedRepartition) && DOMAINDECOMP(cr) )
1408 dd_partition_system(fplog, mdlog, step, cr, TRUE, 1,
1409 state_global, top_global, ir,
1410 state, &f, mdAtoms, top, fr,
1411 vsite, constr,
1412 nrnb, wcycle, FALSE);
1413 shouldCheckNumberOfBondedInteractions = true;
1414 update_realloc(upd, state->natoms);
1417 bFirstStep = FALSE;
1418 bInitStep = FALSE;
1419 startingFromCheckpoint = false;
1421 /* ####### SET VARIABLES FOR NEXT ITERATION IF THEY STILL NEED IT ###### */
1422 /* With all integrators, except VV, we need to retain the pressure
1423 * at the current step for coupling at the next step.
1425 if ((state->flags & (1<<estPRES_PREV)) &&
1426 (bGStatEveryStep ||
1427 (ir->nstpcouple > 0 && step % ir->nstpcouple == 0)))
1429 /* Store the pressure in t_state for pressure coupling
1430 * at the next MD step.
1432 copy_mat(pres, state->pres_prev);
1435 /* ####### END SET VARIABLES FOR NEXT ITERATION ###### */
1437 if ( (membed != nullptr) && (!bLastStep) )
1439 rescale_membed(step_rel, membed, as_rvec_array(state_global->x.data()));
1442 cycles = wallcycle_stop(wcycle, ewcSTEP);
1443 if (DOMAINDECOMP(cr) && wcycle)
1445 dd_cycles_add(cr->dd, cycles, ddCyclStep);
1448 /* increase the MD step number */
1449 step++;
1450 step_rel++;
1452 resetHandler->resetCounters(
1453 step, step_rel, mdlog, fplog, cr, (use_GPU(fr->nbv) ? fr->nbv : nullptr),
1454 nrnb, fr->pmedata, pme_loadbal, wcycle, walltime_accounting);
1456 /* If bIMD is TRUE, the master updates the IMD energy record and sends positions to VMD client */
1457 IMD_prep_energies_send_positions(ir->bIMD && MASTER(cr), bIMDstep, ir->imd, enerd, step, bCalcEner, wcycle);
1460 /* End of main MD loop */
1462 /* Closing TNG files can include compressing data. Therefore it is good to do that
1463 * before stopping the time measurements. */
1464 mdoutf_tng_close(outf);
1466 /* Stop measuring walltime */
1467 walltime_accounting_end_time(walltime_accounting);
1469 if (!thisRankHasDuty(cr, DUTY_PME))
1471 /* Tell the PME only node to finish */
1472 gmx_pme_send_finish(cr);
1475 if (MASTER(cr))
1477 if (ir->nstcalcenergy > 0)
1479 print_ebin(mdoutf_get_fp_ene(outf), FALSE, FALSE, FALSE, fplog, step, t,
1480 eprAVER, mdebin, fcd, groups, &(ir->opts), awh.get());
1483 done_mdebin(mdebin);
1484 done_mdoutf(outf);
1486 if (bPMETune)
1488 pme_loadbal_done(pme_loadbal, fplog, mdlog, use_GPU(fr->nbv));
1491 done_shellfc(fplog, shellfc, step_rel);
1493 if (useReplicaExchange && MASTER(cr))
1495 print_replica_exchange_statistics(fplog, repl_ex);
1498 // Clean up swapcoords
1499 if (ir->eSwapCoords != eswapNO)
1501 finish_swapcoords(ir->swap);
1504 /* IMD cleanup, if bIMD is TRUE. */
1505 IMD_finalize(ir->bIMD, ir->imd);
1507 walltime_accounting_set_nsteps_done(walltime_accounting, step_rel);
1509 destroy_enerdata(enerd);
1510 sfree(enerd);
1511 sfree(top);