Prepare legacy checkpoint for modular simulator checkpointing
[gromacs.git] / src / gromacs / modularsimulator / statepropagatordata.h
blob2bafcfad8ad6ee4a5a373d3c83b8e7f3fa211acc
1 /*
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.
35 /*! \internal \file
36 * \brief Declares the state 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_MODULARSIMULATOR_STATEPROPAGATORDATA_H
45 #define GMX_MODULARSIMULATOR_STATEPROPAGATORDATA_H
47 #include "gromacs/gpu_utils/hostallocator.h"
48 #include "gromacs/math/paddedvector.h"
49 #include "gromacs/math/vectypes.h"
50 #include "gromacs/mdtypes/checkpointdata.h"
51 #include "gromacs/mdtypes/forcebuffers.h"
53 #include "modularsimulatorinterfaces.h"
54 #include "topologyholder.h"
56 struct gmx_mdoutf;
57 enum class PbcType : int;
58 struct t_commrec;
59 struct t_inputrec;
60 class t_state;
61 struct t_mdatoms;
63 namespace gmx
65 enum class ConstraintVariable;
66 class EnergyData;
67 class FreeEnergyPerturbationData;
68 class GlobalCommunicationHelper;
69 class LegacySimulatorData;
70 class ModularSimulatorAlgorithmBuilderHelper;
72 /*! \internal
73 * \ingroup module_modularsimulator
74 * \brief StatePropagatorData and associated data
76 * The `StatePropagatorData` contains a little more than the pure
77 * statistical-physical micro state, namely the positions,
78 * velocities, forces, and box matrix, as well as a backup of
79 * the positions and box of the last time step. While it takes
80 * part in the simulator loop via its member class `Element`
81 * to be able to backup positions /
82 * boxes and save the current state if needed, it's main purpose
83 * is to offer access to its data via getter methods. All elements
84 * reading or writing to this data need a pointer to the
85 * `StatePropagatorData` and need to request their data explicitly. This
86 * will later simplify the understanding of data dependencies
87 * between elements.
89 * Note that the `StatePropagatorData` can be converted to and from the
90 * legacy `t_state` object. This is useful when dealing with
91 * functionality which has not yet been adapted to use the new
92 * data approach - of the elements currently implemented, only
93 * domain decomposition, PME load balancing, and the initial
94 * constraining are using this.
96 class StatePropagatorData final
98 public:
99 //! Constructor
100 StatePropagatorData(int numAtoms,
101 FILE* fplog,
102 const t_commrec* cr,
103 t_state* globalState,
104 bool useGPU,
105 bool canMoleculesBeDistributedOverPBC,
106 bool writeFinalConfiguration,
107 const std::string& finalConfigurationFilename,
108 const t_inputrec* inputrec,
109 const t_mdatoms* mdatoms,
110 const gmx_mtop_t* globalTop);
112 // Allow access to state
113 //! Get write access to position vector
114 ArrayRefWithPadding<RVec> positionsView();
115 //! Get read access to position vector
116 ArrayRefWithPadding<const RVec> constPositionsView() const;
117 //! Get write access to previous position vector
118 ArrayRefWithPadding<RVec> previousPositionsView();
119 //! Get read access to previous position vector
120 ArrayRefWithPadding<const RVec> constPreviousPositionsView() const;
121 //! Get write access to velocity vector
122 ArrayRefWithPadding<RVec> velocitiesView();
123 //! Get read access to velocity vector
124 ArrayRefWithPadding<const RVec> constVelocitiesView() const;
125 //! Get write access to force vector
126 ForceBuffersView& forcesView();
127 //! Get read access to force vector
128 const ForceBuffersView& constForcesView() const;
129 //! Get pointer to box
130 rvec* box();
131 //! Get const pointer to box
132 const rvec* constBox() const;
133 //! Get pointer to previous box
134 rvec* previousBox();
135 //! Get const pointer to previous box
136 const rvec* constPreviousBox() const;
137 //! Get the local number of atoms
138 int localNumAtoms() const;
139 //! Get the total number of atoms
140 int totalNumAtoms() const;
142 //! The element taking part in the simulator loop
143 class Element;
144 //! Get pointer to element (whose lifetime is managed by this)
145 Element* element();
146 //! Initial set up for the associated element
147 void setup();
149 //! \cond
150 // (doxygen doesn't like these)
151 // Classes which need access to legacy state
152 friend class DomDecHelper;
153 //! \endcond
155 private:
156 //! The total number of atoms in the system
157 int totalNumAtoms_;
158 //! The local number of atoms
159 int localNAtoms_;
160 //! The position vector
161 PaddedHostVector<RVec> x_;
162 //! The position vector of the previous step
163 PaddedHostVector<RVec> previousX_;
164 //! The velocity vector
165 PaddedHostVector<RVec> v_;
166 //! The force vector
167 ForceBuffers f_;
168 //! The box matrix
169 matrix box_;
170 //! The box matrix of the previous step
171 matrix previousBox_;
172 //! The DD partitioning count for legacy t_state compatibility
173 int ddpCount_;
175 //! The element
176 std::unique_ptr<Element> element_;
178 //! Move x_ to previousX_
179 void copyPosition();
180 //! OMP helper to move x_ to previousX_
181 void copyPosition(int start, int end);
183 // Access to legacy state
184 //! Get a deep copy of the current state in legacy format
185 std::unique_ptr<t_state> localState();
186 //! Update the current state with a state in legacy format
187 void setLocalState(std::unique_ptr<t_state> state);
188 //! Get a pointer to the global state
189 t_state* globalState();
190 //! Get a force pointer
191 ForceBuffers* forcePointer();
193 //! Whether we're doing VV and need to reset velocities after the first half step
194 bool vvResetVelocities_;
195 //! Velocities backup for VV
196 PaddedHostVector<RVec> velocityBackup_;
197 //! Function resetting the velocities
198 void resetVelocities();
200 //! Whether planned total number of steps was reached (used for final output only)
201 bool isRegularSimulationEnd_;
202 //! The signalled last step (used for final output only)
203 Step lastStep_;
205 // Access to ISimulator data
206 //! Full simulation state (only non-nullptr on master rank).
207 t_state* globalState_;
210 /*! \internal
211 * \ingroup module_modularsimulator
212 * \brief Element for StatePropagatorData
214 * The `StatePropagatorData::Element` takes part in the simulator run, as it might
215 * have to save a valid state at the right moment during the
216 * integration. Placing the StatePropagatorData::Element correctly is the
217 * duty of the simulator builder - this might be automatized later
218 * if we have enough meta-data of the variables (i.e., if
219 * `StatePropagatorData` knows at which time the variables currently are,
220 * and can decide when a valid state (full-time step of all
221 * variables) is reached. The `StatePropagatorData::Element` is also a client of
222 * both the trajectory signaller and writer - it will save a
223 * state for later writeout during the simulator step if it
224 * knows that trajectory writing will occur later in the step,
225 * and it knows how to write to file given a file pointer by
226 * the `TrajectoryElement`. It is also responsible to store
227 * the state for checkpointing.
230 class StatePropagatorData::Element final :
231 public ISimulatorElement,
232 public ITrajectoryWriterClient,
233 public ITrajectorySignallerClient,
234 public ICheckpointHelperClient,
235 public ILastStepSignallerClient
237 public:
238 //! Constructor
239 Element(StatePropagatorData* statePropagatorData,
240 FILE* fplog,
241 const t_commrec* cr,
242 int nstxout,
243 int nstvout,
244 int nstfout,
245 int nstxout_compressed,
246 bool canMoleculesBeDistributedOverPBC,
247 bool writeFinalConfiguration,
248 std::string finalConfigurationFilename,
249 const t_inputrec* inputrec,
250 const gmx_mtop_t* globalTop);
252 /*! \brief Register run function for step / time
254 * This needs to be called during the integration part of the simulator,
255 * at the moment at which the state is at a full time step. Positioning
256 * this element is the responsibility of the programmer writing the
257 * integration algorithm! If the current step is a trajectory writing
258 * step, StatePropagatorData will save a backup for later writeout.
260 * This is also the place at which the current state becomes the previous
261 * state.
263 * \param step The step number
264 * \param time The time
265 * \param registerRunFunction Function allowing to register a run function
267 void scheduleTask(Step step, Time time, const RegisterRunFunction& registerRunFunction) override;
269 /*! \brief Backup starting velocities
271 * This is only needed for vv, where the first (velocity) half step is only
272 * used to compute the constraint virial, but the velocities need to be reset
273 * after.
274 * TODO: There must be a more elegant solution to this!
276 void elementSetup() override;
278 //! No element teardown needed
279 void elementTeardown() override {}
281 //! Set free energy data
282 void setFreeEnergyPerturbationData(FreeEnergyPerturbationData* freeEnergyPerturbationData);
284 /*! \brief Factory method implementation
286 * \param legacySimulatorData Pointer allowing access to simulator level data
287 * \param builderHelper ModularSimulatorAlgorithmBuilder helper object
288 * \param statePropagatorData Pointer to the \c StatePropagatorData object
289 * \param energyData Pointer to the \c EnergyData object
290 * \param freeEnergyPerturbationData Pointer to the \c FreeEnergyPerturbationData object
291 * \param globalCommunicationHelper Pointer to the \c GlobalCommunicationHelper object
293 * \return Pointer to the element to be added. Element needs to have been stored using \c storeElement
295 static ISimulatorElement* getElementPointerImpl(LegacySimulatorData* legacySimulatorData,
296 ModularSimulatorAlgorithmBuilderHelper* builderHelper,
297 StatePropagatorData* statePropagatorData,
298 EnergyData* energyData,
299 FreeEnergyPerturbationData* freeEnergyPerturbationData,
300 GlobalCommunicationHelper* globalCommunicationHelper);
302 private:
303 //! Pointer to the associated StatePropagatorData
304 StatePropagatorData* statePropagatorData_;
306 //! The position writeout frequency
307 const int nstxout_;
308 //! The velocity writeout frequency
309 const int nstvout_;
310 //! The force writeout frequency
311 const int nstfout_;
312 //! The compressed position writeout frequency
313 const int nstxout_compressed_;
315 //! Pointer to keep a backup of the state for later writeout
316 std::unique_ptr<t_state> localStateBackup_;
317 //! Step at which next writeout occurs
318 Step writeOutStep_;
319 //! Backup current state
320 void saveState();
322 //! ITrajectorySignallerClient implementation
323 std::optional<SignallerCallback> registerTrajectorySignallerCallback(TrajectoryEvent event) override;
325 //! ITrajectoryWriterClient implementation
326 std::optional<ITrajectoryWriterCallback> registerTrajectoryWriterCallback(TrajectoryEvent event) override;
328 //! ICheckpointHelperClient implementation
329 void writeCheckpoint(t_state* localState, t_state* globalState) override;
331 //! ILastStepSignallerClient implementation (used for final output only)
332 std::optional<SignallerCallback> registerLastStepCallback() override;
334 //! Callback writing the state to file
335 void write(gmx_mdoutf* outf, Step step, Time time);
337 // TODO: Clarify relationship to data objects and find a more robust alternative to raw pointers (#3583)
338 //! Pointer to the free energy perturbation data (for trajectory writing only)
339 FreeEnergyPerturbationData* freeEnergyPerturbationData_;
341 //! No trajectory writer setup needed
342 void trajectoryWriterSetup(gmx_mdoutf gmx_unused* outf) override {}
343 //! Trajectory writer teardown - write final coordinates
344 void trajectoryWriterTeardown(gmx_mdoutf* outf) override;
345 //! A dummy CheckpointData - remove when we stop using the legacy trajectory writing function
346 WriteCheckpointDataHolder dummyCheckpointDataHolder_;
348 //! Whether planned total number of steps was reached (used for final output only)
349 bool isRegularSimulationEnd_;
350 //! The signalled last step (used for final output only)
351 Step lastStep_;
352 //! Whether system can have molecules distributed over PBC boundaries (used for final output only)
353 const bool canMoleculesBeDistributedOverPBC_;
354 //! Whether system has molecules self-interacting through PBC (used for final output only)
355 const bool systemHasPeriodicMolecules_;
356 //! The PBC type (used for final output only)
357 const PbcType pbcType_;
358 //! The (planned) last step - determines whether final configuration is written (used for final output only)
359 const Step lastPlannedStep_;
360 //! Whether final configuration was chosen in mdrun options (used for final output only)
361 const bool writeFinalConfiguration_;
362 //! The filename of the final configuration file (used for final output only)
363 const std::string finalConfigurationFilename_;
365 // Access to ISimulator data
366 //! Handles logging.
367 FILE* fplog_;
368 //! Handles communication.
369 const t_commrec* cr_;
370 //! Full system topology.
371 const gmx_mtop_t* top_global_;
374 } // namespace gmx
376 #endif // GMX_MODULARSIMULATOR_STATEPROPAGATORDATA_H