2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2019,2020,2021, 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 global reduction element for the modular simulator
38 * \author Pascal Merz <pascal.merz@me.com>
39 * \ingroup module_modularsimulator
44 #include "computeglobalselement.h"
46 #include "gromacs/domdec/domdec.h"
47 #include "gromacs/gmxlib/network.h"
48 #include "gromacs/gmxlib/nrnb.h"
49 #include "gromacs/math/vec.h"
50 #include "gromacs/mdlib/constr.h"
51 #include "gromacs/mdlib/md_support.h"
52 #include "gromacs/mdlib/mdatoms.h"
53 #include "gromacs/mdlib/stat.h"
54 #include "gromacs/mdlib/update.h"
55 #include "gromacs/mdlib/vcm.h"
56 #include "gromacs/mdtypes/commrec.h"
57 #include "gromacs/mdtypes/group.h"
58 #include "gromacs/mdtypes/inputrec.h"
59 #include "gromacs/mdtypes/mdatom.h"
60 #include "gromacs/topology/topology.h"
62 #include "freeenergyperturbationdata.h"
63 #include "modularsimulator.h"
64 #include "simulatoralgorithm.h"
68 template<ComputeGlobalsAlgorithm algorithm>
69 ComputeGlobalsElement<algorithm>::ComputeGlobalsElement(StatePropagatorData* statePropagatorData,
70 EnergyData* energyData,
71 FreeEnergyPerturbationData* freeEnergyPerturbationData,
72 SimulationSignals* signals,
75 const MDLogger& mdlog,
77 const t_inputrec* inputrec,
78 const MDAtoms* mdAtoms,
80 gmx_wallcycle* wcycle,
82 const gmx_mtop_t& global_top,
83 Constraints* constr) :
84 energyReductionStep_(-1),
85 virialReductionStep_(-1),
86 vvSchedulingStep_(-1),
87 doStopCM_(inputrec->comm_mode != ComRemovalAlgorithm::No),
88 nstcomm_(inputrec->nstcomm),
89 nstglobalcomm_(nstglobalcomm),
90 lastStep_(inputrec->nsteps + inputrec->init_step),
91 initStep_(inputrec->init_step),
92 nullSignaller_(std::make_unique<SimulationSignaller>(nullptr, nullptr, nullptr, false, false)),
93 statePropagatorData_(statePropagatorData),
94 energyData_(energyData),
95 localTopology_(nullptr),
96 freeEnergyPerturbationData_(freeEnergyPerturbationData),
97 vcm_(global_top.groups, *inputrec),
103 top_global_(global_top),
110 reportComRemovalInfo(fplog, vcm_);
111 gstat_ = global_stat_init(inputrec_);
114 template<ComputeGlobalsAlgorithm algorithm>
115 ComputeGlobalsElement<algorithm>::~ComputeGlobalsElement()
117 global_stat_destroy(gstat_);
120 template<ComputeGlobalsAlgorithm algorithm>
121 void ComputeGlobalsElement<algorithm>::elementSetup()
123 GMX_ASSERT(localTopology_, "Setup called before local topology was set.");
125 if (doStopCM_ && !inputrec_->bContinuation)
127 // To minimize communication, compute_globals computes the COM velocity
128 // and the kinetic energy for the velocities without COM motion removed.
129 // Thus to get the kinetic energy without the COM contribution, we need
130 // to call compute_globals twice.
132 compute(-1, CGLO_GSTAT | CGLO_STOPCM, nullSignaller_.get(), false, true);
134 auto v = statePropagatorData_->velocitiesView();
135 // At initialization, do not pass x with acceleration-correction mode
136 // to avoid (incorrect) correction of the initial coordinates.
137 auto x = vcm_.mode == ComRemovalAlgorithm::LinearAccelerationCorrection
138 ? ArrayRefWithPadding<RVec>()
139 : statePropagatorData_->positionsView();
140 process_and_stopcm_grp(
141 fplog_, &vcm_, *mdAtoms_->mdatoms(), x.unpaddedArrayRef(), v.unpaddedArrayRef());
142 inc_nrnb(nrnb_, eNR_STOPCM, mdAtoms_->mdatoms()->homenr);
145 unsigned int cglo_flags = (CGLO_TEMPERATURE | CGLO_GSTAT
146 | (energyData_->hasReadEkinFromCheckpoint() ? CGLO_READEKIN : 0));
148 if (algorithm == ComputeGlobalsAlgorithm::VelocityVerlet)
150 cglo_flags |= CGLO_PRESSURE | CGLO_CONSTRAINT;
153 compute(-1, cglo_flags, nullSignaller_.get(), false, true);
155 // Calculate the initial half step temperature, and save the ekinh_old
156 for (int i = 0; (i < inputrec_->opts.ngtc); i++)
158 copy_mat(energyData_->ekindata()->tcstat[i].ekinh, energyData_->ekindata()->tcstat[i].ekinh_old);
162 template<ComputeGlobalsAlgorithm algorithm>
163 void ComputeGlobalsElement<algorithm>::scheduleTask(Step step,
164 Time gmx_unused time,
165 const RegisterRunFunction& registerRunFunction)
167 const bool needComReduction = doStopCM_ && do_per_step(step, nstcomm_);
168 const bool needGlobalReduction = step == energyReductionStep_ || step == virialReductionStep_
169 || needComReduction || do_per_step(step, nstglobalcomm_);
171 // TODO: CGLO_GSTAT is only used for needToSumEkinhOld_, i.e. to signal that we do or do not
172 // sum the previous kinetic energy. We should simplify / clarify this.
174 if (algorithm == ComputeGlobalsAlgorithm::LeapFrog)
176 // With Leap-Frog we can skip compute_globals at
177 // non-communication steps, but we need to calculate
178 // the kinetic energy one step before communication.
180 // With leap-frog we also need to compute the half-step
181 // kinetic energy at the step before we need to write
182 // the full-step kinetic energy
183 const bool needEkinAtNextStep = (do_per_step(step + 1, nstglobalcomm_) || step + 1 == lastStep_);
185 if (!needGlobalReduction && !needEkinAtNextStep)
190 const bool doEnergy = step == energyReductionStep_;
191 int flags = (needGlobalReduction ? CGLO_GSTAT : 0) | (doEnergy ? CGLO_ENERGY : 0)
192 | (needComReduction ? CGLO_STOPCM : 0) | CGLO_TEMPERATURE | CGLO_PRESSURE
195 // Since we're already communicating at this step, we
196 // can propagate intra-simulation signals. Note that
197 // check_nstglobalcomm has the responsibility for
198 // choosing the value of nstglobalcomm which satisfies
199 // the need of the different signallers.
200 const bool doIntraSimSignal = true;
201 // Disable functionality
202 const bool doInterSimSignal = false;
204 // Make signaller to signal stop / reset / checkpointing signals
205 auto signaller = std::make_shared<SimulationSignaller>(
206 signals_, cr_, nullptr, doInterSimSignal, doIntraSimSignal);
208 registerRunFunction([this, step, flags, signaller = std::move(signaller)]() {
209 compute(step, flags, signaller.get(), true);
212 else if (algorithm == ComputeGlobalsAlgorithm::VelocityVerlet)
214 // For VV, we schedule two calls to compute globals per step.
215 if (step != vvSchedulingStep_)
217 // This is the first scheduling call for this step (positions & velocities at full time
218 // step) Set this as the current scheduling step
219 vvSchedulingStep_ = step;
221 // For vv, the state at the beginning of the step is positions at time t, velocities at time t - dt/2
222 // The first velocity propagation (+dt/2) therefore actually corresponds to the previous step.
223 // So we need information from the last step in the first half of the integration
224 if (!needGlobalReduction && !do_per_step(step - 1, nstglobalcomm_))
229 const bool doTemperature = step != initStep_ || inputrec_->bContinuation;
230 const bool doEnergy = step == energyReductionStep_;
232 int flags = (needGlobalReduction ? CGLO_GSTAT : 0) | (doEnergy ? CGLO_ENERGY : 0)
233 | (doTemperature ? CGLO_TEMPERATURE : 0) | CGLO_PRESSURE | CGLO_CONSTRAINT
234 | (needComReduction ? CGLO_STOPCM : 0) | CGLO_SCALEEKIN;
237 [this, step, flags]() { compute(step, flags, nullSignaller_.get(), false); });
241 // second call to compute_globals for this step
242 // Reset the scheduling step to avoid confusion if scheduling needs
243 // to be repeated (in case of unexpected simulation termination)
244 vvSchedulingStep_ = -1;
246 if (!needGlobalReduction)
250 int flags = CGLO_GSTAT | CGLO_CONSTRAINT;
252 // Since we're already communicating at this step, we
253 // can propagate intra-simulation signals. Note that
254 // check_nstglobalcomm has the responsibility for
255 // choosing the value of nstglobalcomm which satisfies
256 // the need of the different signallers.
257 const bool doIntraSimSignal = true;
258 // Disable functionality
259 const bool doInterSimSignal = false;
261 auto signaller = std::make_shared<SimulationSignaller>(
262 signals_, cr_, nullptr, doInterSimSignal, doIntraSimSignal);
264 registerRunFunction([this, step, flags, signaller = std::move(signaller)]() {
265 compute(step, flags, signaller.get(), true);
271 template<ComputeGlobalsAlgorithm algorithm>
272 void ComputeGlobalsElement<algorithm>::compute(gmx::Step step,
274 SimulationSignaller* signaller,
278 auto x = statePropagatorData_->positionsView().unpaddedArrayRef();
279 auto v = statePropagatorData_->velocitiesView().unpaddedArrayRef();
280 const auto* box = statePropagatorData_->constBox();
281 const auto* lastbox = useLastBox ? statePropagatorData_->constPreviousBox()
282 : statePropagatorData_->constBox();
284 if (DOMAINDECOMP(cr_) && shouldCheckNumberOfBondedInteractions(*cr_->dd))
286 flags |= CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS;
288 compute_globals(gstat_,
292 energyData_->ekindata(),
299 step != -1 ? wcycle_ : nullptr,
300 energyData_->enerdata(),
301 energyData_->forceVirial(step),
302 energyData_->constraintVirial(step),
303 energyData_->totalVirial(step),
304 energyData_->pressure(step),
305 (((flags & CGLO_ENERGY) != 0) && constr_ != nullptr) ? constr_->rmsdData()
306 : gmx::ArrayRef<real>{},
309 energyData_->needToSumEkinhOld(),
311 if (DOMAINDECOMP(cr_))
313 checkNumberOfBondedInteractions(mdlog_, cr_, top_global_, localTopology_, x, box);
315 if (flags & CGLO_STOPCM && !isInit)
317 process_and_stopcm_grp(fplog_, &vcm_, *mdAtoms_->mdatoms(), x, v);
318 inc_nrnb(nrnb_, eNR_STOPCM, mdAtoms_->mdatoms()->homenr);
322 template<ComputeGlobalsAlgorithm algorithm>
323 void ComputeGlobalsElement<algorithm>::setTopology(const gmx_localtop_t* top)
325 localTopology_ = top;
328 template<ComputeGlobalsAlgorithm algorithm>
329 std::optional<SignallerCallback> ComputeGlobalsElement<algorithm>::registerEnergyCallback(EnergySignallerEvent event)
331 if (event == EnergySignallerEvent::EnergyCalculationStep)
333 return [this](Step step, Time /*unused*/) { energyReductionStep_ = step; };
335 if (event == EnergySignallerEvent::VirialCalculationStep)
337 return [this](Step step, Time /*unused*/) { virialReductionStep_ = step; };
342 template<ComputeGlobalsAlgorithm algorithm>
343 std::optional<SignallerCallback>
344 ComputeGlobalsElement<algorithm>::registerTrajectorySignallerCallback(TrajectoryEvent event)
346 if (event == TrajectoryEvent::EnergyWritingStep)
348 return [this](Step step, Time /*unused*/) { energyReductionStep_ = step; };
353 //! Explicit template instantiation
355 template class ComputeGlobalsElement<ComputeGlobalsAlgorithm::LeapFrog>;
356 template class ComputeGlobalsElement<ComputeGlobalsAlgorithm::VelocityVerlet>;
360 ISimulatorElement* ComputeGlobalsElement<ComputeGlobalsAlgorithm::LeapFrog>::getElementPointerImpl(
361 LegacySimulatorData* legacySimulatorData,
362 ModularSimulatorAlgorithmBuilderHelper* builderHelper,
363 StatePropagatorData* statePropagatorData,
364 EnergyData* energyData,
365 FreeEnergyPerturbationData* freeEnergyPerturbationData,
366 GlobalCommunicationHelper* globalCommunicationHelper)
368 auto* element = builderHelper->storeElement(
369 std::make_unique<ComputeGlobalsElement<ComputeGlobalsAlgorithm::LeapFrog>>(
372 freeEnergyPerturbationData,
373 globalCommunicationHelper->simulationSignals(),
374 globalCommunicationHelper->nstglobalcomm(),
375 legacySimulatorData->fplog,
376 legacySimulatorData->mdlog,
377 legacySimulatorData->cr,
378 legacySimulatorData->inputrec,
379 legacySimulatorData->mdAtoms,
380 legacySimulatorData->nrnb,
381 legacySimulatorData->wcycle,
382 legacySimulatorData->fr,
383 legacySimulatorData->top_global,
384 legacySimulatorData->constr));
390 ISimulatorElement* ComputeGlobalsElement<ComputeGlobalsAlgorithm::VelocityVerlet>::getElementPointerImpl(
391 LegacySimulatorData* simulator,
392 ModularSimulatorAlgorithmBuilderHelper* builderHelper,
393 StatePropagatorData* statePropagatorData,
394 EnergyData* energyData,
395 FreeEnergyPerturbationData* freeEnergyPerturbationData,
396 GlobalCommunicationHelper* globalCommunicationHelper)
398 // We allow this element to be added multiple times to the call list, but we only want one
399 // actual element built
400 static const std::string key("vvComputeGlobalsElement");
402 const std::optional<std::any> cachedValue = builderHelper->builderData(key);
406 return std::any_cast<ISimulatorElement*>(cachedValue.value());
410 ISimulatorElement* vvComputeGlobalsElement = builderHelper->storeElement(
411 std::make_unique<ComputeGlobalsElement<ComputeGlobalsAlgorithm::VelocityVerlet>>(
414 freeEnergyPerturbationData,
415 globalCommunicationHelper->simulationSignals(),
416 globalCommunicationHelper->nstglobalcomm(),
425 simulator->top_global,
427 builderHelper->storeBuilderData(key, vvComputeGlobalsElement);
428 return vvComputeGlobalsElement;