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 Declares the energy element for the modular simulator
38 * \author Pascal Merz <pascal.merz@me.com>
39 * \ingroup module_modularsimulator
41 * This header is only used within the modular simulator module
44 #ifndef GMX_ENERGYELEMENT_MICROSTATE_H
45 #define GMX_ENERGYELEMENT_MICROSTATE_H
47 #include "gromacs/mdtypes/state.h"
49 #include "modularsimulatorinterfaces.h"
52 struct gmx_enerdata_t;
54 struct ObservablesHistory;
58 struct SimulationGroups;
62 enum class StartingBehavior;
65 class FreeEnergyPerturbationData;
66 class GlobalCommunicationHelper;
67 class LegacySimulatorData;
69 class ModularSimulatorAlgorithmBuilderHelper;
70 class ObservablesReducer;
71 class ParrinelloRahmanBarostat;
72 class StatePropagatorData;
73 class VelocityScalingTemperatureCoupling;
74 struct MDModulesNotifiers;
76 //! Function type for elements contributing energy
77 using EnergyContribution = std::function<real(Step, Time)>;
80 * \ingroup module_modularsimulator
81 * \brief Data class managing energies
83 * The EnergyData owns the EnergyObject,
84 * the tensors for the different virials and the pressure as well as
85 * the total dipole vector. It has a member class which is part of the
86 * simulator loop and and is responsible
87 * for saving energy data and writing it to trajectory.
89 * The EnergyData offers an interface to add virial contributions,
90 * but also allows access to the raw pointers to tensor data, the
91 * dipole vector, and the legacy energy data structures.
93 * The EnergyData owns an object of type EnergyData::Element,
94 * which takes part in the simulation loop, allowing to record
95 * and output energies during the simulation.
97 class EnergyData final
101 EnergyData(StatePropagatorData* statePropagatorData,
102 FreeEnergyPerturbationData* freeEnergyPerturbationData,
103 const gmx_mtop_t& globalTopology,
104 const t_inputrec* inputrec,
105 const MDAtoms* mdAtoms,
106 gmx_enerdata_t* enerd,
107 gmx_ekindata_t* ekind,
108 const Constraints* constr,
111 const MDModulesNotifiers& mdModulesNotifiers,
113 ObservablesHistory* observablesHistory,
114 StartingBehavior startingBehavior,
115 bool simulationsShareState,
118 /*! \brief Final output
120 * Prints the averages to log. This is called from ModularSimulatorAlgorithm.
122 * \see ModularSimulatorAlgorithm::teardown
126 /*! \brief Add contribution to force virial
128 * This automatically resets the tensor if the step is higher
129 * than the current step, starting the tensor calculation for
130 * a new step at zero. Otherwise, it adds the new contribution
131 * to the existing virial.
133 void addToForceVirial(const tensor virial, Step step);
135 /*! \brief Add contribution to constraint virial
137 * This automatically resets the tensor if the step is higher
138 * than the current step, starting the tensor calculation for
139 * a new step at zero. Otherwise, it adds the new contribution
140 * to the existing virial.
142 void addToConstraintVirial(const tensor virial, Step step);
144 /*! \brief Get pointer to force virial tensor
146 * Allows access to the raw pointer to the tensor.
148 rvec* forceVirial(Step step);
150 /*! \brief Get pointer to constraint virial tensor
152 * Allows access to the raw pointer to the tensor.
154 rvec* constraintVirial(Step step);
156 /*! \brief Get pointer to total virial tensor
158 * Allows access to the raw pointer to the tensor.
160 rvec* totalVirial(Step step);
162 /*! \brief Get pointer to pressure tensor
164 * Allows access to the raw pointer to the tensor.
166 rvec* pressure(Step step);
168 /*! \brief Get pointer to mu_tot
170 * Allows access to the raw pointer to the dipole vector.
174 /*! \brief Get pointer to energy structure
177 gmx_enerdata_t* enerdata();
179 /*! \brief Get const pointer to energy structure
182 const gmx_enerdata_t* enerdata() const;
184 /*! \brief Get pointer to kinetic energy structure
187 gmx_ekindata_t* ekindata();
189 /*! \brief Get pointer to needToSumEkinhOld
192 bool* needToSumEkinhOld();
194 /*! \brief Whether kinetic energy was read from checkpoint
196 * This is needed by the compute globals element
197 * TODO: Remove this when moving global reduction to client system (#3421)
199 [[nodiscard]] bool hasReadEkinFromCheckpoint() const;
201 /*! \brief Add conserved energy contribution
203 * This allows other elements to register callbacks for contributions to
204 * the conserved energy term.
206 void addConservedEnergyContribution(EnergyContribution&& energyContribution);
208 /*! \brief set Parrinello-Rahman barostat
210 * This allows to set a pointer to the Parrinello-Rahman barostat used to
211 * print the box velocities.
213 void setParrinelloRahmanBoxVelocities(std::function<const rvec*()>&& parrinelloRahmanBoxVelocities);
215 /*! \brief Initialize energy history
217 * Kept as a static function to allow usage from legacy code
218 * \todo Make member function once legacy use is not needed anymore
220 static void initializeEnergyHistory(StartingBehavior startingBehavior,
221 ObservablesHistory* observablesHistory,
222 EnergyOutput* energyOutput);
224 /*! \brief Request (local) kinetic energy update
226 void updateKineticEnergy();
228 //! The element taking part in the simulator loop
230 //! Get pointer to element (whose lifetime is managed by this)
234 /*! \brief Setup (needs file pointer)
236 * Initializes the EnergyOutput object, and does some logging output.
238 * \param mdoutf File pointer
240 void setup(gmx_mdoutf* mdoutf);
242 /*! \brief Save data at energy steps
244 * \param step The current step
245 * \param time The current time
246 * \param isEnergyCalculationStep Whether the current step is an energy calculation step
247 * \param isFreeEnergyCalculationStep Whether the current step is a free energy calculation step
249 void doStep(Step step, Time time, bool isEnergyCalculationStep, bool isFreeEnergyCalculationStep);
251 /*! \brief Write to energy trajectory
253 * This is only called by master - writes energy to trajectory and to log.
255 void write(gmx_mdoutf* outf, Step step, Time time, bool writeTrajectory, bool writeLog);
258 * Data owned by EnergyData
261 std::unique_ptr<Element> element_;
262 //! The energy output object
263 std::unique_ptr<EnergyOutput> energyOutput_;
264 //! Helper object to checkpoint kinetic energy data
265 ekinstate_t ekinstate_;
267 //! Whether this is the master rank
268 const bool isMasterRank_;
270 //! The force virial tensor
272 //! The constraint virial tensor
274 //! The total virial tensor
276 //! The pressure tensor
278 //! The total dipole moment
281 //! The step number of the current force virial tensor
282 Step forceVirialStep_;
283 //! The step number of the current constraint virial tensor
284 Step shakeVirialStep_;
285 //! The step number of the current total virial tensor
286 Step totalVirialStep_;
287 //! The step number of the current pressure tensor
290 //! Whether ekinh_old needs to be summed up (set by compute globals)
291 bool needToSumEkinhOld_;
292 //! Whether we have read ekin from checkpoint
293 bool hasReadEkinFromCheckpoint_;
295 //! Describes how the simulation (re)starts
296 const StartingBehavior startingBehavior_;
299 * Pointers to Simulator data
301 // TODO: Clarify relationship to data objects and find a more robust alternative to raw pointers (#3583)
302 //! Pointer to the state propagator data
303 StatePropagatorData* statePropagatorData_;
304 //! Pointer to the free energy perturbation data
305 FreeEnergyPerturbationData* freeEnergyPerturbationData_;
307 //! Callbacks contributing to the conserved energy term
308 std::vector<EnergyContribution> conservedEnergyContributions_;
309 //! Callback to the Parrinello-Rahman box velocities
310 std::function<const rvec*()> parrinelloRahmanBoxVelocities_;
312 //! Contains user input mdp options.
313 const t_inputrec* inputrec_;
314 //! Full system topology.
315 const gmx_mtop_t& top_global_;
316 //! Atom parameters for this domain.
317 const MDAtoms* mdAtoms_;
318 //! Energy data structure
319 gmx_enerdata_t* enerd_;
320 //! Kinetic energy data
321 gmx_ekindata_t* ekind_;
322 //! Handles constraints.
323 const Constraints* constr_;
326 //! Helper struct for force calculations.
328 //! Notifiers to MD modules
329 const MDModulesNotifiers& mdModulesNotifiers_;
330 //! Global topology groups
331 const SimulationGroups* groups_;
332 //! History of simulation observables.
333 ObservablesHistory* observablesHistory_;
334 //! Whether simulations share the state
335 bool simulationsShareState_;
336 //! The pull work object.
341 * \ingroup module_modularsimulator
342 * \brief Element for EnergyData
344 * This member class allows EnergyData to take part in the simulator
347 * It subscribes to the trajectory signaller, the energy signaller,
348 * and the logging signaller to know when an energy calculation is
349 * needed and when a non-recording step is enough. The simulator
350 * builder is responsible to place the element in a location at
351 * which a valid energy state is available. The EnergyData::Element is
352 * also a subscriber to the trajectory writer element, as it is
353 * responsible to write energy data to trajectory.
355 class EnergyData::Element final :
356 public ISimulatorElement,
357 public ITrajectoryWriterClient,
358 public ITrajectorySignallerClient,
359 public IEnergySignallerClient,
360 public ICheckpointHelperClient
364 Element(EnergyData* energyData, bool isMasterRank);
366 /*! \brief Register run function for step / time
368 * This needs to be called when the energies are at a full time step.
369 * Positioning this element is the responsibility of the programmer.
371 * This is also the place at which the current state becomes the previous
374 * \param step The step number
375 * \param time The time
376 * \param registerRunFunction Function allowing to register a run function
378 void scheduleTask(Step step, Time time, const RegisterRunFunction& registerRunFunction) override;
380 //! No element setup needed
381 void elementSetup() override {}
383 //! No element teardown needed
384 void elementTeardown() override {}
386 //! ICheckpointHelperClient write checkpoint implementation
387 void saveCheckpointState(std::optional<WriteCheckpointData> checkpointData, const t_commrec* cr) override;
388 //! ICheckpointHelperClient read checkpoint implementation
389 void restoreCheckpointState(std::optional<ReadCheckpointData> checkpointData, const t_commrec* cr) override;
390 //! ICheckpointHelperClient key implementation
391 const std::string& clientID() override;
393 /*! \brief Factory method implementation
395 * \param legacySimulatorData Pointer allowing access to simulator level data
396 * \param builderHelper ModularSimulatorAlgorithmBuilder helper object
397 * \param statePropagatorData Pointer to the \c StatePropagatorData object
398 * \param energyData Pointer to the \c EnergyData object
399 * \param freeEnergyPerturbationData Pointer to the \c FreeEnergyPerturbationData object
400 * \param globalCommunicationHelper Pointer to the \c GlobalCommunicationHelper object
401 * \param observablesReducer Pointer to the \c ObservablesReducer object
403 * \return Pointer to the element to be added. Element needs to have been stored using \c storeElement
405 static ISimulatorElement* getElementPointerImpl(LegacySimulatorData* legacySimulatorData,
406 ModularSimulatorAlgorithmBuilderHelper* builderHelper,
407 StatePropagatorData* statePropagatorData,
408 EnergyData* energyData,
409 FreeEnergyPerturbationData* freeEnergyPerturbationData,
410 GlobalCommunicationHelper* globalCommunicationHelper,
411 ObservablesReducer* observablesReducer);
414 EnergyData* energyData_;
416 /*! \brief Setup (needs file pointer)
418 * ITrajectoryWriterClient implementation.
420 * Initializes the EnergyOutput object, and does some logging output.
422 * \param mdoutf File pointer
424 void trajectoryWriterSetup(gmx_mdoutf* mdoutf) override;
425 //! No trajectory writer teardown needed
426 void trajectoryWriterTeardown(gmx_mdoutf gmx_unused* outf) override {}
428 //! ITrajectoryWriterClient implementation.
429 std::optional<SignallerCallback> registerTrajectorySignallerCallback(TrajectoryEvent event) override;
430 //! ITrajectorySignallerClient implementation
431 std::optional<ITrajectoryWriterCallback> registerTrajectoryWriterCallback(TrajectoryEvent event) override;
432 //! IEnergySignallerClient implementation
433 std::optional<SignallerCallback> registerEnergyCallback(EnergySignallerEvent event) override;
436 //! CheckpointHelper identifier
437 const std::string identifier_ = "EnergyElement";
438 //! Helper function to read from / write to CheckpointData
439 template<CheckpointDataOperation operation>
440 void doCheckpointData(CheckpointData<operation>* checkpointData);
442 //! Whether this is the master rank
443 const bool isMasterRank_;
444 //! The next communicated energy writing step
445 Step energyWritingStep_;
446 //! The next communicated energy calculation step
447 Step energyCalculationStep_;
448 //! The next communicated free energy calculation step
449 Step freeEnergyCalculationStep_;
454 #endif // GMX_ENERGYELEMENT_MICROSTATE_H