2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2019,2020, by the GROMACS development team, led by
5 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 * and including many others, as listed in the AUTHORS file in the
7 * top-level source directory and at http://www.gromacs.org.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
36 * \brief Defines the state for the modular simulator
38 * \author Pascal Merz <pascal.merz@me.com>
39 * \ingroup module_modularsimulator
44 #include "statepropagatordata.h"
46 #include "gromacs/commandline/filenm.h"
47 #include "gromacs/domdec/collect.h"
48 #include "gromacs/domdec/domdec.h"
49 #include "gromacs/fileio/confio.h"
50 #include "gromacs/math/vec.h"
51 #include "gromacs/mdlib/gmx_omp_nthreads.h"
52 #include "gromacs/mdlib/mdatoms.h"
53 #include "gromacs/mdlib/mdoutf.h"
54 #include "gromacs/mdlib/stat.h"
55 #include "gromacs/mdlib/update.h"
56 #include "gromacs/mdtypes/checkpointdata.h"
57 #include "gromacs/mdtypes/commrec.h"
58 #include "gromacs/mdtypes/forcebuffers.h"
59 #include "gromacs/mdtypes/forcerec.h"
60 #include "gromacs/mdtypes/inputrec.h"
61 #include "gromacs/mdtypes/mdatom.h"
62 #include "gromacs/mdtypes/mdrunoptions.h"
63 #include "gromacs/mdtypes/state.h"
64 #include "gromacs/pbcutil/pbc.h"
65 #include "gromacs/topology/atoms.h"
66 #include "gromacs/topology/topology.h"
67 #include "gromacs/trajectory/trajectoryframe.h"
69 #include "freeenergyperturbationdata.h"
70 #include "modularsimulator.h"
71 #include "simulatoralgorithm.h"
75 StatePropagatorData::StatePropagatorData(int numAtoms,
80 bool canMoleculesBeDistributedOverPBC,
81 bool writeFinalConfiguration,
82 const std::string& finalConfigurationFilename,
83 const t_inputrec* inputrec,
84 const t_mdatoms* mdatoms,
85 const gmx_mtop_t* globalTop) :
86 totalNumAtoms_(numAtoms),
89 previousBox_{ { 0 } },
91 element_(std::make_unique<Element>(this,
97 inputrec->nstxout_compressed,
98 canMoleculesBeDistributedOverPBC,
99 writeFinalConfiguration,
100 finalConfigurationFilename,
103 vvResetVelocities_(false),
104 isRegularSimulationEnd_(false),
106 globalState_(globalState)
108 bool stateHasVelocities;
109 // Local state only becomes valid now.
110 if (DOMAINDECOMP(cr))
112 auto localState = std::make_unique<t_state>();
113 dd_init_local_state(cr->dd, globalState, localState.get());
114 stateHasVelocities = ((static_cast<unsigned int>(localState->flags) & (1U << estV)) != 0U);
115 setLocalState(std::move(localState));
119 state_change_natoms(globalState, globalState->natoms);
120 f_.resize(globalState->natoms);
121 localNAtoms_ = globalState->natoms;
124 copy_mat(globalState->box, box_);
125 stateHasVelocities = ((static_cast<unsigned int>(globalState->flags) & (1U << estV)) != 0U);
126 previousX_.resizeWithPadding(localNAtoms_);
127 ddpCount_ = globalState->ddp_count;
132 changePinningPolicy(&x_, gmx::PinningPolicy::PinnedIfSupported);
135 if (DOMAINDECOMP(cr) && MASTER(cr))
137 xGlobal_.resizeWithPadding(totalNumAtoms_);
138 previousXGlobal_.resizeWithPadding(totalNumAtoms_);
139 vGlobal_.resizeWithPadding(totalNumAtoms_);
140 fGlobal_.resizeWithPadding(totalNumAtoms_);
143 if (!inputrec->bContinuation)
145 if (stateHasVelocities)
147 auto v = velocitiesView().paddedArrayRef();
148 // Set the velocities of vsites, shells and frozen atoms to zero
149 for (int i = 0; i < mdatoms->homenr; i++)
151 if (mdatoms->ptype[i] == eptVSite || mdatoms->ptype[i] == eptShell)
155 else if (mdatoms->cFREEZE)
157 for (int m = 0; m < DIM; m++)
159 if (inputrec->opts.nFreeze[mdatoms->cFREEZE[i]][m])
167 if (inputrec->eI == eiVV)
169 vvResetVelocities_ = true;
174 StatePropagatorData::Element* StatePropagatorData::element()
176 return element_.get();
179 void StatePropagatorData::setup()
183 element_->elementSetup();
187 ArrayRefWithPadding<RVec> StatePropagatorData::positionsView()
189 return x_.arrayRefWithPadding();
192 ArrayRefWithPadding<const RVec> StatePropagatorData::constPositionsView() const
194 return x_.constArrayRefWithPadding();
197 ArrayRefWithPadding<RVec> StatePropagatorData::previousPositionsView()
199 return previousX_.arrayRefWithPadding();
202 ArrayRefWithPadding<const RVec> StatePropagatorData::constPreviousPositionsView() const
204 return previousX_.constArrayRefWithPadding();
207 ArrayRefWithPadding<RVec> StatePropagatorData::velocitiesView()
209 return v_.arrayRefWithPadding();
212 ArrayRefWithPadding<const RVec> StatePropagatorData::constVelocitiesView() const
214 return v_.constArrayRefWithPadding();
217 ForceBuffersView& StatePropagatorData::forcesView()
222 const ForceBuffersView& StatePropagatorData::constForcesView() const
227 rvec* StatePropagatorData::box()
232 const rvec* StatePropagatorData::constBox() const
237 rvec* StatePropagatorData::previousBox()
242 const rvec* StatePropagatorData::constPreviousBox() const
247 int StatePropagatorData::localNumAtoms() const
252 int StatePropagatorData::totalNumAtoms() const
254 return totalNumAtoms_;
257 std::unique_ptr<t_state> StatePropagatorData::localState()
259 auto state = std::make_unique<t_state>();
260 state->flags = (1U << estX) | (1U << estV) | (1U << estBOX);
261 state_change_natoms(state.get(), localNAtoms_);
264 copy_mat(box_, state->box);
265 state->ddp_count = ddpCount_;
266 state->ddp_count_cg_gl = ddpCountCgGl_;
267 state->cg_gl = cgGl_;
271 void StatePropagatorData::setLocalState(std::unique_ptr<t_state> state)
273 localNAtoms_ = state->natoms;
274 x_.resizeWithPadding(localNAtoms_);
275 previousX_.resizeWithPadding(localNAtoms_);
276 v_.resizeWithPadding(localNAtoms_);
279 copy_mat(state->box, box_);
281 ddpCount_ = state->ddp_count;
282 ddpCountCgGl_ = state->ddp_count_cg_gl;
283 cgGl_ = state->cg_gl;
285 if (vvResetVelocities_)
287 /* DomDec runs twice early in the simulation, once at setup time, and once before the first
288 * step. Every time DD runs, it sets a new local state here. We are saving a backup during
289 * setup time (ok for non-DD cases), so we need to update our backup to the DD state before
290 * the first step here to avoid resetting to an earlier DD state. This is done before any
291 * propagation that needs to be reset, so it's not very safe but correct for now.
292 * TODO: Get rid of this once input is assumed to be at half steps
294 velocityBackup_ = v_;
298 t_state* StatePropagatorData::globalState()
303 ForceBuffers* StatePropagatorData::forcePointer()
308 void StatePropagatorData::copyPosition()
310 int nth = gmx_omp_nthreads_get(emntUpdate);
312 #pragma omp parallel for num_threads(nth) schedule(static) default(none) shared(nth)
313 for (int th = 0; th < nth; th++)
315 int start_th, end_th;
316 getThreadAtomRange(nth, th, localNAtoms_, &start_th, &end_th);
317 copyPosition(start_th, end_th);
320 /* Box is changed in update() when we do pressure coupling,
321 * but we should still use the old box for energy corrections and when
322 * writing it to the energy file, so it matches the trajectory files for
323 * the same timestep above. Make a copy in a separate array.
325 copy_mat(box_, previousBox_);
328 void StatePropagatorData::copyPosition(int start, int end)
330 for (int i = start; i < end; ++i)
332 previousX_[i] = x_[i];
336 void StatePropagatorData::Element::scheduleTask(Step step,
337 Time gmx_unused time,
338 const RegisterRunFunction& registerRunFunction)
340 if (statePropagatorData_->vvResetVelocities_)
342 statePropagatorData_->vvResetVelocities_ = false;
343 registerRunFunction([this]() { statePropagatorData_->resetVelocities(); });
345 // copy x -> previousX
346 registerRunFunction([this]() { statePropagatorData_->copyPosition(); });
347 // if it's a write out step, keep a copy for writeout
348 if (step == writeOutStep_ || (step == lastStep_ && writeFinalConfiguration_))
350 registerRunFunction([this]() { saveState(); });
354 void StatePropagatorData::Element::saveState()
356 GMX_ASSERT(!localStateBackup_, "Save state called again before previous state was written.");
357 localStateBackup_ = statePropagatorData_->localState();
358 if (freeEnergyPerturbationData_)
360 localStateBackup_->fep_state = freeEnergyPerturbationData_->currentFEPState();
361 for (unsigned long i = 0; i < localStateBackup_->lambda.size(); ++i)
363 localStateBackup_->lambda[i] = freeEnergyPerturbationData_->constLambdaView()[i];
365 localStateBackup_->flags |= (1U << estLAMBDA) | (1U << estFEPSTATE);
369 std::optional<SignallerCallback> StatePropagatorData::Element::registerTrajectorySignallerCallback(TrajectoryEvent event)
371 if (event == TrajectoryEvent::StateWritingStep)
373 return [this](Step step, Time /*unused*/) { this->writeOutStep_ = step; };
378 std::optional<ITrajectoryWriterCallback>
379 StatePropagatorData::Element::registerTrajectoryWriterCallback(TrajectoryEvent event)
381 if (event == TrajectoryEvent::StateWritingStep)
383 return [this](gmx_mdoutf* outf, Step step, Time time, bool writeTrajectory, bool gmx_unused writeLog) {
386 write(outf, step, time);
393 void StatePropagatorData::Element::write(gmx_mdoutf_t outf, Step currentStep, Time currentTime)
395 wallcycle_start(mdoutf_get_wcycle(outf), ewcTRAJ);
396 unsigned int mdof_flags = 0;
397 if (do_per_step(currentStep, nstxout_))
399 mdof_flags |= MDOF_X;
401 if (do_per_step(currentStep, nstvout_))
403 mdof_flags |= MDOF_V;
405 if (do_per_step(currentStep, nstfout_))
407 mdof_flags |= MDOF_F;
409 if (do_per_step(currentStep, nstxout_compressed_))
411 mdof_flags |= MDOF_X_COMPRESSED;
413 if (do_per_step(currentStep, mdoutf_get_tng_box_output_interval(outf)))
415 mdof_flags |= MDOF_BOX;
417 if (do_per_step(currentStep, mdoutf_get_tng_lambda_output_interval(outf)))
419 mdof_flags |= MDOF_LAMBDA;
421 if (do_per_step(currentStep, mdoutf_get_tng_compressed_box_output_interval(outf)))
423 mdof_flags |= MDOF_BOX_COMPRESSED;
425 if (do_per_step(currentStep, mdoutf_get_tng_compressed_lambda_output_interval(outf)))
427 mdof_flags |= MDOF_LAMBDA_COMPRESSED;
432 wallcycle_stop(mdoutf_get_wcycle(outf), ewcTRAJ);
435 GMX_ASSERT(localStateBackup_, "Trajectory writing called, but no state saved.");
437 // TODO: This is only used for CPT - needs to be filled when we turn CPT back on
438 ObservablesHistory* observablesHistory = nullptr;
440 mdoutf_write_to_trajectory_files(
441 fplog_, cr_, outf, static_cast<int>(mdof_flags), statePropagatorData_->totalNumAtoms_,
442 currentStep, currentTime, localStateBackup_.get(), statePropagatorData_->globalState_,
443 observablesHistory, statePropagatorData_->f_.view().force(), &dummyCheckpointDataHolder_);
445 if (currentStep != lastStep_ || !isRegularSimulationEnd_)
447 localStateBackup_.reset();
449 wallcycle_stop(mdoutf_get_wcycle(outf), ewcTRAJ);
452 void StatePropagatorData::Element::elementSetup()
454 if (statePropagatorData_->vvResetVelocities_)
456 // MD-VV does the first velocity half-step only to calculate the constraint virial,
457 // then resets the velocities since the input is assumed to be positions and velocities
458 // at full time step. TODO: Change this to have input at half time steps.
459 statePropagatorData_->velocityBackup_ = statePropagatorData_->v_;
463 void StatePropagatorData::resetVelocities()
465 v_ = velocityBackup_;
471 * \brief Enum describing the contents StatePropagatorData::Element writes to modular checkpoint
473 * When changing the checkpoint content, add a new element just above Count, and adjust the
474 * checkpoint functionality.
476 enum class CheckpointVersion
478 Base, //!< First version of modular checkpointing
479 Count //!< Number of entries. Add new versions right above this!
481 constexpr auto c_currentVersion = CheckpointVersion(int(CheckpointVersion::Count) - 1);
484 template<CheckpointDataOperation operation>
485 void StatePropagatorData::doCheckpointData(CheckpointData<operation>* checkpointData)
487 checkpointVersion(checkpointData, "StatePropagatorData version", c_currentVersion);
488 checkpointData->scalar("numAtoms", &totalNumAtoms_);
490 if (operation == CheckpointDataOperation::Read)
492 xGlobal_.resizeWithPadding(totalNumAtoms_);
493 vGlobal_.resizeWithPadding(totalNumAtoms_);
496 checkpointData->arrayRef("positions", makeCheckpointArrayRef<operation>(xGlobal_));
497 checkpointData->arrayRef("velocities", makeCheckpointArrayRef<operation>(vGlobal_));
498 checkpointData->tensor("box", box_);
499 checkpointData->scalar("ddpCount", &ddpCount_);
500 checkpointData->scalar("ddpCountCgGl", &ddpCountCgGl_);
501 checkpointData->arrayRef("cgGl", makeCheckpointArrayRef<operation>(cgGl_));
504 void StatePropagatorData::Element::saveCheckpointState(std::optional<WriteCheckpointData> checkpointData,
507 if (DOMAINDECOMP(cr))
509 // Collect state from all ranks into global vectors
510 dd_collect_vec(cr->dd, statePropagatorData_->ddpCount_, statePropagatorData_->ddpCountCgGl_,
511 statePropagatorData_->cgGl_, statePropagatorData_->x_,
512 statePropagatorData_->xGlobal_);
513 dd_collect_vec(cr->dd, statePropagatorData_->ddpCount_, statePropagatorData_->ddpCountCgGl_,
514 statePropagatorData_->cgGl_, statePropagatorData_->v_,
515 statePropagatorData_->vGlobal_);
519 // Everything is local - copy local vectors into global ones
520 statePropagatorData_->xGlobal_.resizeWithPadding(statePropagatorData_->totalNumAtoms());
521 statePropagatorData_->vGlobal_.resizeWithPadding(statePropagatorData_->totalNumAtoms());
522 std::copy(statePropagatorData_->x_.begin(), statePropagatorData_->x_.end(),
523 statePropagatorData_->xGlobal_.begin());
524 std::copy(statePropagatorData_->v_.begin(), statePropagatorData_->v_.end(),
525 statePropagatorData_->vGlobal_.begin());
529 statePropagatorData_->doCheckpointData<CheckpointDataOperation::Write>(&checkpointData.value());
534 * \brief Update the legacy global state
536 * When restoring from checkpoint, data will be distributed during domain decomposition at setup stage.
537 * Domain decomposition still uses the legacy global t_state object so make sure it's up-to-date.
539 static void updateGlobalState(t_state* globalState,
540 const PaddedHostVector<RVec>& x,
541 const PaddedHostVector<RVec>& v,
545 const std::vector<int>& cgGl)
549 copy_mat(box, globalState->box);
550 globalState->ddp_count = ddpCount;
551 globalState->ddp_count_cg_gl = ddpCountCgGl;
552 globalState->cg_gl = cgGl;
555 void StatePropagatorData::Element::restoreCheckpointState(std::optional<ReadCheckpointData> checkpointData,
560 statePropagatorData_->doCheckpointData<CheckpointDataOperation::Read>(&checkpointData.value());
563 // Copy data to global state to be distributed by DD at setup stage
564 if (DOMAINDECOMP(cr) && MASTER(cr))
566 updateGlobalState(statePropagatorData_->globalState_, statePropagatorData_->xGlobal_,
567 statePropagatorData_->vGlobal_, statePropagatorData_->box_,
568 statePropagatorData_->ddpCount_, statePropagatorData_->ddpCountCgGl_,
569 statePropagatorData_->cgGl_);
571 // Everything is local - copy global vectors to local ones
572 if (!DOMAINDECOMP(cr))
574 statePropagatorData_->x_.resizeWithPadding(statePropagatorData_->totalNumAtoms_);
575 statePropagatorData_->v_.resizeWithPadding(statePropagatorData_->totalNumAtoms_);
576 std::copy(statePropagatorData_->xGlobal_.begin(), statePropagatorData_->xGlobal_.end(),
577 statePropagatorData_->x_.begin());
578 std::copy(statePropagatorData_->vGlobal_.begin(), statePropagatorData_->vGlobal_.end(),
579 statePropagatorData_->v_.begin());
583 const std::string& StatePropagatorData::Element::clientID()
585 return StatePropagatorData::checkpointID();
588 void StatePropagatorData::Element::trajectoryWriterTeardown(gmx_mdoutf* gmx_unused outf)
590 // Note that part of this code is duplicated in do_md_trajectory_writing.
591 // This duplication is needed while both legacy and modular code paths are in use.
592 // TODO: Remove duplication asap, make sure to keep in sync in the meantime.
593 if (!writeFinalConfiguration_ || !isRegularSimulationEnd_)
598 GMX_ASSERT(localStateBackup_, "Final trajectory writing called, but no state saved.");
600 wallcycle_start(mdoutf_get_wcycle(outf), ewcTRAJ);
601 if (DOMAINDECOMP(cr_))
604 MASTER(cr_) ? statePropagatorData_->globalState_->x : gmx::ArrayRef<gmx::RVec>();
605 dd_collect_vec(cr_->dd, localStateBackup_->ddp_count, localStateBackup_->ddp_count_cg_gl,
606 localStateBackup_->cg_gl, localStateBackup_->x, globalXRef);
608 MASTER(cr_) ? statePropagatorData_->globalState_->v : gmx::ArrayRef<gmx::RVec>();
609 dd_collect_vec(cr_->dd, localStateBackup_->ddp_count, localStateBackup_->ddp_count_cg_gl,
610 localStateBackup_->cg_gl, localStateBackup_->v, globalVRef);
614 // We have the whole state locally: copy the local state pointer
615 statePropagatorData_->globalState_ = localStateBackup_.get();
620 fprintf(stderr, "\nWriting final coordinates.\n");
621 if (canMoleculesBeDistributedOverPBC_ && !systemHasPeriodicMolecules_)
623 // Make molecules whole only for confout writing
624 do_pbc_mtop(pbcType_, localStateBackup_->box, top_global_,
625 statePropagatorData_->globalState_->x.rvec_array());
627 write_sto_conf_mtop(finalConfigurationFilename_.c_str(), *top_global_->name, top_global_,
628 statePropagatorData_->globalState_->x.rvec_array(),
629 statePropagatorData_->globalState_->v.rvec_array(), pbcType_,
630 localStateBackup_->box);
632 wallcycle_stop(mdoutf_get_wcycle(outf), ewcTRAJ);
635 std::optional<SignallerCallback> StatePropagatorData::Element::registerLastStepCallback()
637 return [this](Step step, Time /*time*/) {
639 isRegularSimulationEnd_ = (step == lastPlannedStep_);
643 StatePropagatorData::Element::Element(StatePropagatorData* statePropagatorData,
649 int nstxout_compressed,
650 bool canMoleculesBeDistributedOverPBC,
651 bool writeFinalConfiguration,
652 std::string finalConfigurationFilename,
653 const t_inputrec* inputrec,
654 const gmx_mtop_t* globalTop) :
655 statePropagatorData_(statePropagatorData),
659 nstxout_compressed_(nstxout_compressed),
661 freeEnergyPerturbationData_(nullptr),
662 isRegularSimulationEnd_(false),
664 canMoleculesBeDistributedOverPBC_(canMoleculesBeDistributedOverPBC),
665 systemHasPeriodicMolecules_(inputrec->bPeriodicMols),
666 pbcType_(inputrec->pbcType),
667 lastPlannedStep_(inputrec->nsteps + inputrec->init_step),
668 writeFinalConfiguration_(writeFinalConfiguration),
669 finalConfigurationFilename_(std::move(finalConfigurationFilename)),
672 top_global_(globalTop)
675 void StatePropagatorData::Element::setFreeEnergyPerturbationData(FreeEnergyPerturbationData* freeEnergyPerturbationData)
677 freeEnergyPerturbationData_ = freeEnergyPerturbationData;
680 ISimulatorElement* StatePropagatorData::Element::getElementPointerImpl(
681 LegacySimulatorData gmx_unused* legacySimulatorData,
682 ModularSimulatorAlgorithmBuilderHelper gmx_unused* builderHelper,
683 StatePropagatorData* statePropagatorData,
684 EnergyData gmx_unused* energyData,
685 FreeEnergyPerturbationData* freeEnergyPerturbationData,
686 GlobalCommunicationHelper gmx_unused* globalCommunicationHelper)
688 statePropagatorData->element()->setFreeEnergyPerturbationData(freeEnergyPerturbationData);
689 return statePropagatorData->element();
692 void StatePropagatorData::readCheckpointToTrxFrame(t_trxframe* trxFrame, ReadCheckpointData readCheckpointData)
694 StatePropagatorData statePropagatorData;
695 statePropagatorData.doCheckpointData(&readCheckpointData);
697 trxFrame->natoms = statePropagatorData.totalNumAtoms_;
699 trxFrame->x = makeRvecArray(statePropagatorData.xGlobal_, statePropagatorData.totalNumAtoms_);
701 trxFrame->v = makeRvecArray(statePropagatorData.vGlobal_, statePropagatorData.totalNumAtoms_);
702 trxFrame->bF = false;
703 trxFrame->bBox = true;
704 copy_mat(statePropagatorData.box_, trxFrame->box);
707 const std::string& StatePropagatorData::checkpointID()
709 static const std::string identifier = "StatePropagatorData";