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;
57 struct SimulationGroups;
61 enum class StartingBehavior;
64 class FreeEnergyPerturbationData;
65 class GlobalCommunicationHelper;
66 class LegacySimulatorData;
68 class ModularSimulatorAlgorithmBuilderHelper;
69 class ParrinelloRahmanBarostat;
70 class StatePropagatorData;
71 class VelocityScalingTemperatureCoupling;
72 struct MdModulesNotifier;
74 //! Function type for elements contributing energy
75 using EnergyContribution = std::function<real(Step, Time)>;
78 * \ingroup module_modularsimulator
79 * \brief Data class managing energies
81 * The EnergyData owns the EnergyObject,
82 * the tensors for the different virials and the pressure as well as
83 * the total dipole vector. It has a member class which is part of the
84 * simulator loop and and is responsible
85 * for saving energy data and writing it to trajectory.
87 * The EnergyData offers an interface to add virial contributions,
88 * but also allows access to the raw pointers to tensor data, the
89 * dipole vector, and the legacy energy data structures.
91 * The EnergyData owns an object of type EnergyData::Element,
92 * which takes part in the simulation loop, allowing to record
93 * and output energies during the simulation.
95 class EnergyData final
99 EnergyData(StatePropagatorData* statePropagatorData,
100 FreeEnergyPerturbationData* freeEnergyPerturbationData,
101 const gmx_mtop_t& globalTopology,
102 const t_inputrec* inputrec,
103 const MDAtoms* mdAtoms,
104 gmx_enerdata_t* enerd,
105 gmx_ekindata_t* ekind,
106 const Constraints* constr,
109 const MdModulesNotifier& mdModulesNotifier,
111 ObservablesHistory* observablesHistory,
112 StartingBehavior startingBehavior,
113 bool simulationsShareState);
115 /*! \brief Final output
117 * Prints the averages to log. This is called from ModularSimulatorAlgorithm.
119 * \see ModularSimulatorAlgorithm::teardown
123 /*! \brief Add contribution to force virial
125 * This automatically resets the tensor if the step is higher
126 * than the current step, starting the tensor calculation for
127 * a new step at zero. Otherwise, it adds the new contribution
128 * to the existing virial.
130 void addToForceVirial(const tensor virial, Step step);
132 /*! \brief Add contribution to constraint virial
134 * This automatically resets the tensor if the step is higher
135 * than the current step, starting the tensor calculation for
136 * a new step at zero. Otherwise, it adds the new contribution
137 * to the existing virial.
139 void addToConstraintVirial(const tensor virial, Step step);
141 /*! \brief Get pointer to force virial tensor
143 * Allows access to the raw pointer to the tensor.
145 rvec* forceVirial(Step step);
147 /*! \brief Get pointer to constraint virial tensor
149 * Allows access to the raw pointer to the tensor.
151 rvec* constraintVirial(Step step);
153 /*! \brief Get pointer to total virial tensor
155 * Allows access to the raw pointer to the tensor.
157 rvec* totalVirial(Step step);
159 /*! \brief Get pointer to pressure tensor
161 * Allows access to the raw pointer to the tensor.
163 rvec* pressure(Step step);
165 /*! \brief Get pointer to mu_tot
167 * Allows access to the raw pointer to the dipole vector.
171 /*! \brief Get pointer to energy structure
174 gmx_enerdata_t* enerdata();
176 /*! \brief Get pointer to kinetic energy structure
179 gmx_ekindata_t* ekindata();
181 /*! \brief Get pointer to needToSumEkinhOld
184 bool* needToSumEkinhOld();
186 /*! \brief Whether kinetic energy was read from checkpoint
188 * This is needed by the compute globals element
189 * TODO: Remove this when moving global reduction to client system (#3421)
191 [[nodiscard]] bool hasReadEkinFromCheckpoint() const;
193 /*! \brief Add conserved energy contribution
195 * This allows other elements to register callbacks for contributions to
196 * the conserved energy term.
198 void addConservedEnergyContribution(EnergyContribution&& energyContribution);
200 /*! \brief set Parrinello-Rahman barostat
202 * This allows to set a pointer to the Parrinello-Rahman barostat used to
203 * print the box velocities.
205 void setParrinelloRahmanBoxVelocities(std::function<const rvec*()>&& parrinelloRahmanBoxVelocities);
207 /*! \brief Initialize energy history
209 * Kept as a static function to allow usage from legacy code
210 * \todo Make member function once legacy use is not needed anymore
212 static void initializeEnergyHistory(StartingBehavior startingBehavior,
213 ObservablesHistory* observablesHistory,
214 EnergyOutput* energyOutput);
216 //! The element taking part in the simulator loop
218 //! Get pointer to element (whose lifetime is managed by this)
222 /*! \brief Setup (needs file pointer)
224 * Initializes the EnergyOutput object, and does some logging output.
226 * \param mdoutf File pointer
228 void setup(gmx_mdoutf* mdoutf);
230 /*! \brief Save data at energy steps
232 * \param time The current time
233 * \param isEnergyCalculationStep Whether the current step is an energy calculation step
234 * \param isFreeEnergyCalculationStep Whether the current step is a free energy calculation step
236 void doStep(Step step, Time time, bool isEnergyCalculationStep, bool isFreeEnergyCalculationStep);
238 /*! \brief Write to energy trajectory
240 * This is only called by master - writes energy to trajectory and to log.
242 void write(gmx_mdoutf* outf, Step step, Time time, bool writeTrajectory, bool writeLog);
245 * Data owned by EnergyData
248 std::unique_ptr<Element> element_;
249 //! The energy output object
250 std::unique_ptr<EnergyOutput> energyOutput_;
251 //! Helper object to checkpoint kinetic energy data
252 ekinstate_t ekinstate_;
254 //! Whether this is the master rank
255 const bool isMasterRank_;
257 //! The force virial tensor
259 //! The constraint virial tensor
261 //! The total virial tensor
263 //! The pressure tensor
265 //! The total dipole moment
268 //! The step number of the current force virial tensor
269 Step forceVirialStep_;
270 //! The step number of the current constraint virial tensor
271 Step shakeVirialStep_;
272 //! The step number of the current total virial tensor
273 Step totalVirialStep_;
274 //! The step number of the current pressure tensor
277 //! Whether ekinh_old needs to be summed up (set by compute globals)
278 bool needToSumEkinhOld_;
279 //! Whether we have read ekin from checkpoint
280 bool hasReadEkinFromCheckpoint_;
282 //! Describes how the simulation (re)starts
283 const StartingBehavior startingBehavior_;
286 * Pointers to Simulator data
288 // TODO: Clarify relationship to data objects and find a more robust alternative to raw pointers (#3583)
289 //! Pointer to the state propagator data
290 StatePropagatorData* statePropagatorData_;
291 //! Pointer to the free energy perturbation data
292 FreeEnergyPerturbationData* freeEnergyPerturbationData_;
294 //! Callbacks contributing to the conserved energy term
295 std::vector<EnergyContribution> conservedEnergyContributions_;
296 //! Callback to the Parrinello-Rahman box velocities
297 std::function<const rvec*()> parrinelloRahmanBoxVelocities_;
299 //! Contains user input mdp options.
300 const t_inputrec* inputrec_;
301 //! Full system topology.
302 const gmx_mtop_t& top_global_;
303 //! Atom parameters for this domain.
304 const MDAtoms* mdAtoms_;
305 //! Energy data structure
306 gmx_enerdata_t* enerd_;
307 //! Kinetic energy data
308 gmx_ekindata_t* ekind_;
309 //! Handles constraints.
310 const Constraints* constr_;
313 //! Helper struct for force calculations.
315 //! Notification to MD modules
316 const MdModulesNotifier& mdModulesNotifier_;
317 //! Global topology groups
318 const SimulationGroups* groups_;
319 //! History of simulation observables.
320 ObservablesHistory* observablesHistory_;
321 //! Whether simulations share the state
322 bool simulationsShareState_;
326 * \ingroup module_modularsimulator
327 * \brief Element for EnergyData
329 * This member class allows EnergyData to take part in the simulator
332 * It subscribes to the trajectory signaller, the energy signaller,
333 * and the logging signaller to know when an energy calculation is
334 * needed and when a non-recording step is enough. The simulator
335 * builder is responsible to place the element in a location at
336 * which a valid energy state is available. The EnergyData::Element is
337 * also a subscriber to the trajectory writer element, as it is
338 * responsible to write energy data to trajectory.
340 class EnergyData::Element final :
341 public ISimulatorElement,
342 public ITrajectoryWriterClient,
343 public ITrajectorySignallerClient,
344 public IEnergySignallerClient,
345 public ICheckpointHelperClient
349 Element(EnergyData* energyData, bool isMasterRank);
351 /*! \brief Register run function for step / time
353 * This needs to be called when the energies are at a full time step.
354 * Positioning this element is the responsibility of the programmer.
356 * This is also the place at which the current state becomes the previous
359 * \param step The step number
360 * \param time The time
361 * \param registerRunFunction Function allowing to register a run function
363 void scheduleTask(Step step, Time time, const RegisterRunFunction& registerRunFunction) override;
365 //! No element setup needed
366 void elementSetup() override {}
368 //! No element teardown needed
369 void elementTeardown() override {}
371 //! ICheckpointHelperClient write checkpoint implementation
372 void saveCheckpointState(std::optional<WriteCheckpointData> checkpointData, const t_commrec* cr) override;
373 //! ICheckpointHelperClient read checkpoint implementation
374 void restoreCheckpointState(std::optional<ReadCheckpointData> checkpointData, const t_commrec* cr) override;
375 //! ICheckpointHelperClient key implementation
376 const std::string& clientID() override;
378 /*! \brief Factory method implementation
380 * \param legacySimulatorData Pointer allowing access to simulator level data
381 * \param builderHelper ModularSimulatorAlgorithmBuilder helper object
382 * \param statePropagatorData Pointer to the \c StatePropagatorData object
383 * \param energyData Pointer to the \c EnergyData object
384 * \param freeEnergyPerturbationData Pointer to the \c FreeEnergyPerturbationData object
385 * \param globalCommunicationHelper Pointer to the \c GlobalCommunicationHelper object
387 * \return Pointer to the element to be added. Element needs to have been stored using \c storeElement
389 static ISimulatorElement* getElementPointerImpl(LegacySimulatorData* legacySimulatorData,
390 ModularSimulatorAlgorithmBuilderHelper* builderHelper,
391 StatePropagatorData* statePropagatorData,
392 EnergyData* energyData,
393 FreeEnergyPerturbationData* freeEnergyPerturbationData,
394 GlobalCommunicationHelper* globalCommunicationHelper);
397 EnergyData* energyData_;
399 /*! \brief Setup (needs file pointer)
401 * ITrajectoryWriterClient implementation.
403 * Initializes the EnergyOutput object, and does some logging output.
405 * \param mdoutf File pointer
407 void trajectoryWriterSetup(gmx_mdoutf* mdoutf) override;
408 //! No trajectory writer teardown needed
409 void trajectoryWriterTeardown(gmx_mdoutf gmx_unused* outf) override {}
411 //! ITrajectoryWriterClient implementation.
412 std::optional<SignallerCallback> registerTrajectorySignallerCallback(TrajectoryEvent event) override;
413 //! ITrajectorySignallerClient implementation
414 std::optional<ITrajectoryWriterCallback> registerTrajectoryWriterCallback(TrajectoryEvent event) override;
415 //! IEnergySignallerClient implementation
416 std::optional<SignallerCallback> registerEnergyCallback(EnergySignallerEvent event) override;
419 //! CheckpointHelper identifier
420 const std::string identifier_ = "EnergyElement";
421 //! Helper function to read from / write to CheckpointData
422 template<CheckpointDataOperation operation>
423 void doCheckpointData(CheckpointData<operation>* checkpointData);
425 //! Whether this is the master rank
426 const bool isMasterRank_;
427 //! The next communicated energy writing step
428 Step energyWritingStep_;
429 //! The next communicated energy calculation step
430 Step energyCalculationStep_;
431 //! The next communicated free energy calculation step
432 Step freeEnergyCalculationStep_;
437 #endif // GMX_ENERGYELEMENT_MICROSTATE_H