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) 2013,2014,2015,2016,2017 by the GROMACS development team.
7 * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by
8 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
9 * and including many others, as listed in the AUTHORS file in the
10 * top-level source directory and at http://www.gromacs.org.
12 * GROMACS is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public License
14 * as published by the Free Software Foundation; either version 2.1
15 * of the License, or (at your option) any later version.
17 * GROMACS is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with GROMACS; if not, see
24 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
25 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 * If you want to redistribute modifications to GROMACS, please
28 * consider that scientific software is very special. Version
29 * control is crucial - bugs must be traceable. We will be happy to
30 * consider code for inclusion in the official distribution, but
31 * derived work must not be called official GROMACS. Details are found
32 * in the README & COPYING files - if they are missing, get the
33 * official version at http://www.gromacs.org.
35 * To help us fund GROMACS development, we humbly ask that you cite
36 * the research papers on the package. Check out http://www.gromacs.org.
41 #include "md_support.h"
48 #include "gromacs/domdec/domdec.h"
49 #include "gromacs/gmxlib/network.h"
50 #include "gromacs/gmxlib/nrnb.h"
51 #include "gromacs/math/vec.h"
52 #include "gromacs/mdlib/dispersioncorrection.h"
53 #include "gromacs/mdlib/simulationsignal.h"
54 #include "gromacs/mdlib/stat.h"
55 #include "gromacs/mdlib/tgroup.h"
56 #include "gromacs/mdlib/update.h"
57 #include "gromacs/mdlib/vcm.h"
58 #include "gromacs/mdrunutility/multisim.h"
59 #include "gromacs/mdtypes/commrec.h"
60 #include "gromacs/mdtypes/df_history.h"
61 #include "gromacs/mdtypes/enerdata.h"
62 #include "gromacs/mdtypes/energyhistory.h"
63 #include "gromacs/mdtypes/forcerec.h"
64 #include "gromacs/mdtypes/group.h"
65 #include "gromacs/mdtypes/inputrec.h"
66 #include "gromacs/mdtypes/md_enums.h"
67 #include "gromacs/mdtypes/state.h"
68 #include "gromacs/pbcutil/pbc.h"
69 #include "gromacs/pulling/pull.h"
70 #include "gromacs/timing/wallcycle.h"
71 #include "gromacs/topology/mtop_util.h"
72 #include "gromacs/trajectory/trajectoryframe.h"
73 #include "gromacs/utility/arrayref.h"
74 #include "gromacs/utility/cstringutil.h"
75 #include "gromacs/utility/fatalerror.h"
76 #include "gromacs/utility/gmxassert.h"
77 #include "gromacs/utility/logger.h"
78 #include "gromacs/utility/smalloc.h"
79 #include "gromacs/utility/snprintf.h"
81 // TODO move this to multi-sim module
82 bool multisim_int_all_are_equal(const gmx_multisim_t* ms, int64_t value)
84 bool allValuesAreEqual = true;
87 GMX_RELEASE_ASSERT(ms, "Invalid use of multi-simulation pointer");
90 /* send our value to all other master ranks, receive all of theirs */
92 gmx_sumli_sim(ms->nsim, buf, ms);
94 for (int s = 0; s < ms->nsim; s++)
98 allValuesAreEqual = false;
105 return allValuesAreEqual;
108 int multisim_min(const gmx_multisim_t* ms, int nmin, int n)
111 gmx_bool bPos, bEqual;
116 gmx_sumi_sim(ms->nsim, buf, ms);
119 for (s = 0; s < ms->nsim; s++)
121 bPos = bPos && (buf[s] > 0);
122 bEqual = bEqual && (buf[s] == buf[0]);
128 nmin = std::min(nmin, buf[0]);
132 /* Find the least common multiple */
133 for (d = 2; d < nmin; d++)
136 while (s < ms->nsim && d % buf[s] == 0)
142 /* We found the LCM and it is less than nmin */
154 /* TODO Specialize this routine into init-time and loop-time versions?
155 e.g. bReadEkin is only true when restoring from checkpoint */
156 void compute_globals(gmx_global_stat* gstat,
158 const t_inputrec* ir,
160 gmx_ekindata_t* ekind,
165 const t_mdatoms* mdatoms,
168 gmx_wallcycle_t wcycle,
169 gmx_enerdata_t* enerd,
175 gmx::Constraints* constr,
176 gmx::SimulationSignaller* signalCoordinator,
177 const matrix lastbox,
178 int* totalNumberOfBondedInteractions,
179 gmx_bool* bSumEkinhOld,
182 gmx_bool bEner, bPres, bTemp;
183 gmx_bool bStopCM, bGStat, bReadEkin, bEkinAveVel, bScaleEkin, bConstrain;
184 gmx_bool bCheckNumberOfBondedInteractions;
187 /* translate CGLO flags to gmx_booleans */
188 bStopCM = ((flags & CGLO_STOPCM) != 0);
189 bGStat = ((flags & CGLO_GSTAT) != 0);
190 bReadEkin = ((flags & CGLO_READEKIN) != 0);
191 bScaleEkin = ((flags & CGLO_SCALEEKIN) != 0);
192 bEner = ((flags & CGLO_ENERGY) != 0);
193 bTemp = ((flags & CGLO_TEMPERATURE) != 0);
194 bPres = ((flags & CGLO_PRESSURE) != 0);
195 bConstrain = ((flags & CGLO_CONSTRAINT) != 0);
196 bCheckNumberOfBondedInteractions = ((flags & CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS) != 0);
198 /* we calculate a full state kinetic energy either with full-step velocity verlet
199 or half step where we need the pressure */
201 bEkinAveVel = (ir->eI == eiVV || (ir->eI == eiVVAK && bPres) || bReadEkin);
203 /* in initalization, it sums the shake virial in vv, and to
204 sums ekinh_old in leapfrog (or if we are calculating ekinh_old) for other reasons */
206 /* ########## Kinetic energy ############## */
210 /* Non-equilibrium MD: this is parallellized, but only does communication
211 * when there really is NEMD.
214 if (PAR(cr) && (ekind->bNEMD))
216 accumulate_u(cr, &(ir->opts), ekind);
220 calc_ke_part(x, v, box, &(ir->opts), mdatoms, ekind, nrnb, bEkinAveVel);
224 /* Calculate center of mass velocity if necessary, also parallellized */
227 calc_vcm_grp(*mdatoms, x, v, vcm);
230 if (bTemp || bStopCM || bPres || bEner || bConstrain || bCheckNumberOfBondedInteractions)
234 /* We will not sum ekinh_old,
235 * so signal that we still have to do it.
237 *bSumEkinhOld = TRUE;
241 gmx::ArrayRef<real> signalBuffer = signalCoordinator->getCommunicationBuffer();
244 wallcycle_start(wcycle, ewcMoveE);
245 global_stat(gstat, cr, enerd, force_vir, shake_vir, mu_tot, ir, ekind, constr,
246 bStopCM ? vcm : nullptr, signalBuffer.size(), signalBuffer.data(),
247 totalNumberOfBondedInteractions, *bSumEkinhOld, flags);
248 wallcycle_stop(wcycle, ewcMoveE);
250 signalCoordinator->finalizeSignals();
251 *bSumEkinhOld = FALSE;
257 /* Calculate the amplitude of the cosine velocity profile */
258 ekind->cosacc.vcos = ekind->cosacc.mvcos / mdatoms->tmass;
263 /* Sum the kinetic energies of the groups & calc temp */
264 /* compute full step kinetic energies if vv, or if vv-avek and we are computing the pressure with inputrecNptTrotter */
265 /* three maincase: VV with AveVel (md-vv), vv with AveEkin (md-vv-avek), leap with AveEkin (md).
266 Leap with AveVel is not supported; it's not clear that it will actually work.
267 bEkinAveVel: If TRUE, we simply multiply ekin by ekinscale to get a full step kinetic energy.
268 If FALSE, we average ekinh_old and ekinh*ekinscale_nhc to get an averaged half step kinetic energy.
270 enerd->term[F_TEMP] = sum_ekin(&(ir->opts), ekind, &dvdl_ekin, bEkinAveVel, bScaleEkin);
271 enerd->dvdl_lin[efptMASS] = static_cast<double>(dvdl_ekin);
273 enerd->term[F_EKIN] = trace(ekind->ekin);
276 /* ########## Now pressure ############## */
277 // TODO: For the VV integrator bConstrain is needed in the conditional. This is confusing, so get rid of this.
278 if (bPres || bConstrain)
280 m_add(force_vir, shake_vir, total_vir);
282 /* Calculate pressure and apply LR correction if PPPM is used.
283 * Use the box from last timestep since we already called update().
286 enerd->term[F_PRES] = calc_pres(fr->ePBC, ir->nwall, lastbox, ekind->ekin, total_vir, pres);
289 /* ########## Long range energy information ###### */
290 if ((bEner || bPres) && fr->dispersionCorrection)
292 /* Calculate long range corrections to pressure and energy */
293 /* this adds to enerd->term[F_PRES] and enerd->term[F_ETOT],
294 and computes enerd->term[F_DISPCORR]. Also modifies the
295 total_vir and pres tensors */
297 const DispersionCorrection::Correction correction =
298 fr->dispersionCorrection->calculate(lastbox, vdwLambda);
302 enerd->term[F_DISPCORR] = correction.energy;
303 enerd->term[F_EPOT] += correction.energy;
304 enerd->term[F_DVDL_VDW] += correction.dvdl;
308 correction.correctVirial(total_vir);
309 correction.correctPressure(pres);
310 enerd->term[F_PDISPCORR] = correction.pressure;
311 enerd->term[F_PRES] += correction.pressure;
316 void setCurrentLambdasRerun(int64_t step,
317 const t_lambda* fepvals,
318 const t_trxframe* rerun_fr,
320 t_state* globalState)
322 GMX_RELEASE_ASSERT(globalState != nullptr,
323 "setCurrentLambdasGlobalRerun should be called with a valid state object");
325 if (rerun_fr->bLambda)
327 if (fepvals->delta_lambda == 0)
329 globalState->lambda[efptFEP] = rerun_fr->lambda;
333 /* find out between which two value of lambda we should be */
334 real frac = step * fepvals->delta_lambda;
335 int fep_state = static_cast<int>(std::floor(frac * fepvals->n_lambda));
336 /* interpolate between this state and the next */
337 /* this assumes that the initial lambda corresponds to lambda==0, which is verified in grompp */
338 frac = frac * fepvals->n_lambda - fep_state;
339 for (int i = 0; i < efptNR; i++)
341 globalState->lambda[i] =
342 lam0[i] + (fepvals->all_lambda[i][fep_state])
343 + frac * (fepvals->all_lambda[i][fep_state + 1] - fepvals->all_lambda[i][fep_state]);
347 else if (rerun_fr->bFepState)
349 globalState->fep_state = rerun_fr->fep_state;
350 for (int i = 0; i < efptNR; i++)
352 globalState->lambda[i] = fepvals->all_lambda[i][globalState->fep_state];
357 void setCurrentLambdasLocal(const int64_t step,
358 const t_lambda* fepvals,
360 gmx::ArrayRef<real> lambda,
361 const int currentFEPState)
362 /* find the current lambdas. If rerunning, we either read in a state, or a lambda value,
363 requiring different logic. */
365 if (fepvals->delta_lambda != 0)
367 /* find out between which two value of lambda we should be */
368 real frac = step * fepvals->delta_lambda;
369 if (fepvals->n_lambda > 0)
371 int fep_state = static_cast<int>(std::floor(frac * fepvals->n_lambda));
372 /* interpolate between this state and the next */
373 /* this assumes that the initial lambda corresponds to lambda==0, which is verified in grompp */
374 frac = frac * fepvals->n_lambda - fep_state;
375 for (int i = 0; i < efptNR; i++)
377 lambda[i] = lam0[i] + (fepvals->all_lambda[i][fep_state])
378 + frac * (fepvals->all_lambda[i][fep_state + 1] - fepvals->all_lambda[i][fep_state]);
383 for (int i = 0; i < efptNR; i++)
385 lambda[i] = lam0[i] + frac;
391 /* if < 0, fep_state was never defined, and we should not set lambda from the state */
392 if (currentFEPState > -1)
394 for (int i = 0; i < efptNR; i++)
396 lambda[i] = fepvals->all_lambda[i][currentFEPState];
402 static void min_zero(int* n, int i)
404 if (i > 0 && (*n == 0 || i < *n))
410 static int lcd4(int i1, int i2, int i3, int i4)
421 gmx_incons("All 4 inputs for determining nstglobalcomm are <= 0");
425 && ((i1 > 0 && i1 % nst != 0) || (i2 > 0 && i2 % nst != 0) || (i3 > 0 && i3 % nst != 0)
426 || (i4 > 0 && i4 % nst != 0)))
434 int computeGlobalCommunicationPeriod(const gmx::MDLogger& mdlog, t_inputrec* ir, const t_commrec* cr)
438 // Set up the default behaviour
439 if (!(ir->nstcalcenergy > 0 || ir->nstlist > 0 || ir->etc != etcNO || ir->epc != epcNO))
441 /* The user didn't choose the period for anything
442 important, so we just make sure we can send signals and
443 write output suitably. */
445 if (ir->nstenergy > 0 && ir->nstenergy < nstglobalcomm)
447 nstglobalcomm = ir->nstenergy;
452 /* The user has made a choice (perhaps implicitly), so we
453 * ensure that we do timely intra-simulation communication
454 * for (possibly) each of the four parts that care.
456 * TODO Does the Verlet scheme (+ DD) need any
457 * communication at nstlist steps? Is the use of nstlist
458 * here a leftover of the twin-range scheme? Can we remove
459 * nstlist when we remove the group scheme?
461 nstglobalcomm = lcd4(ir->nstcalcenergy, ir->nstlist, ir->etc != etcNO ? ir->nsttcouple : 0,
462 ir->epc != epcNO ? ir->nstpcouple : 0);
466 // TODO change this behaviour. Instead grompp should print
467 // a (performance) note and mdrun should not change ir.
468 if (ir->comm_mode != ecmNO && ir->nstcomm < nstglobalcomm)
470 GMX_LOG(mdlog.warning)
472 .appendTextFormatted("WARNING: Changing nstcomm from %d to %d", ir->nstcomm, nstglobalcomm);
473 ir->nstcomm = nstglobalcomm;
479 .appendTextFormatted("Intra-simulation communication will occur every %d steps.\n",
482 return nstglobalcomm;
485 void rerun_parallel_comm(t_commrec* cr, t_trxframe* fr, gmx_bool* bLastStep)
489 if (MASTER(cr) && *bLastStep)
495 gmx_bcast(sizeof(*fr), fr, cr);
499 *bLastStep = (fr->natoms < 0);
502 // TODO Most of this logic seems to belong in the respective modules
503 void set_state_entries(t_state* state, const t_inputrec* ir)
505 /* The entries in the state in the tpx file might not correspond
506 * with what is needed, so we correct this here.
509 if (ir->efep != efepNO || ir->bExpanded)
511 state->flags |= (1 << estLAMBDA);
512 state->flags |= (1 << estFEPSTATE);
514 state->flags |= (1 << estX);
515 GMX_RELEASE_ASSERT(state->x.size() == state->natoms,
516 "We should start a run with an initialized state->x");
517 if (EI_DYNAMICS(ir->eI))
519 state->flags |= (1 << estV);
523 if (ir->ePBC != epbcNONE)
525 state->flags |= (1 << estBOX);
526 if (inputrecPreserveShape(ir))
528 state->flags |= (1 << estBOX_REL);
530 if ((ir->epc == epcPARRINELLORAHMAN) || (ir->epc == epcMTTK))
532 state->flags |= (1 << estBOXV);
533 state->flags |= (1 << estPRES_PREV);
535 if (inputrecNptTrotter(ir) || (inputrecNphTrotter(ir)))
538 state->flags |= (1 << estNHPRES_XI);
539 state->flags |= (1 << estNHPRES_VXI);
540 state->flags |= (1 << estSVIR_PREV);
541 state->flags |= (1 << estFVIR_PREV);
542 state->flags |= (1 << estVETA);
543 state->flags |= (1 << estVOL0);
545 if (ir->epc == epcBERENDSEN)
547 state->flags |= (1 << estBAROS_INT);
551 if (ir->etc == etcNOSEHOOVER)
553 state->flags |= (1 << estNH_XI);
554 state->flags |= (1 << estNH_VXI);
557 if (ir->etc == etcVRESCALE || ir->etc == etcBERENDSEN)
559 state->flags |= (1 << estTHERM_INT);
562 init_gtc_state(state, state->ngtc, state->nnhpres,
563 ir->opts.nhchainlength); /* allocate the space for nose-hoover chains */
564 init_ekinstate(&state->ekinstate, ir);
568 snew(state->dfhist, 1);
569 init_df_history(state->dfhist, ir->fepvals->n_lambda);
572 if (ir->pull && ir->pull->bSetPbcRefToPrevStepCOM)
574 state->flags |= (1 << estPULLCOMPREVSTEP);