Move densityfitting to its own directory
[alexxy/gromacs.git] / src / gromacs / applied_forces / awh / awh.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2015,2016,2017,2018,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.
8  *
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.
13  *
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.
18  *
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.
23  *
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.
31  *
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.
34  */
35
36 /*! \libinternal
37  * \defgroup module_awh Accelerated weight histogram (AWH) method
38  * \ingroup module_applied_forces
39  * \brief
40  * Implements the "accelerated weight histogram" sampling method.
41  *
42  * This class provides the interface between the AWH module and
43  * other modules using it. Currently AWH can only act on COM pull
44  * reaction coordinates, but this can easily be extended to other
45  * types of reaction coordinates.
46  *
47  * \author Viveca Lindahl
48  * \author Berk Hess <hess@kth.se>
49  * \author Magnus Lundborg
50  */
51
52 /*! \libinternal \file
53  *
54  * \brief
55  * Declares the Awh class.
56  *
57  * \author Viveca Lindahl
58  * \author Berk Hess <hess@kth.se>
59  * \inlibraryapi
60  * \ingroup module_awh
61  */
62
63 #ifndef GMX_AWH_H
64 #define GMX_AWH_H
65
66 #include <cstdio>
67
68 #include <memory>
69 #include <string>
70 #include <vector>
71
72 #include "gromacs/math/vectypes.h"
73 #include "gromacs/utility/basedefinitions.h"
74
75 struct gmx_multisim_t;
76 struct gmx_wallcycle;
77 struct pull_work_t;
78 struct pull_t;
79 class t_state;
80 struct t_commrec;
81 struct t_enxframe;
82 struct t_inputrec;
83 enum class PbcType : int;
84
85 namespace gmx
86 {
87
88 template<typename>
89 class ArrayRef;
90 struct AwhHistory;
91 struct AwhParams;
92 class Bias;
93 struct BiasCoupledToSystem;
94 class ForceWithVirial;
95
96 /*! \libinternal
97  * \brief Coupling of the accelerated weight histogram method (AWH) with the system.
98  *
99  * AWH calculates the free energy along order parameters of the system.
100  * Free energy barriers are overcome by adaptively tuning a bias potential along
101  * the order parameter such that the biased distribution along the parameter
102  * converges toward a chosen target distribution.
103  *
104  * The Awh class takes care of the coupling between the system and the AWH
105  * bias(es). The Awh class contains one or more BiasCoupledToSystem objects.
106  * The BiasCoupledToSystem class takes care of the reaction coordinate input
107  * and force output for the single Bias object it containts.
108  *
109  * \todo Update parameter reading and checkpointing, when general C++ framework is ready.
110  */
111 class Awh
112 {
113 public:
114     /*! \brief Construct an AWH at the start of a simulation.
115      *
116      * AWH will here also register itself with the pull struct as the
117      * potential provider for the pull coordinates given as AWH coordinates
118      * in the user input. This allows AWH to later apply the bias force to
119      * these coordinate in \ref Awh::applyBiasForcesAndUpdateBias.
120      *
121      * \param[in,out] fplog              General output file, normally md.log, can be nullptr.
122      * \param[in]     inputRecord        General input parameters (as set up by grompp).
123      * \param[in]     commRecord         Struct for communication, can be nullptr.
124      * \param[in]     multiSimRecord     Multi-sim handler
125      * \param[in]     awhParams          AWH input parameters, consistent with the relevant
126      * parts of \p inputRecord (as set up by grompp).
127      * \param[in]     biasInitFilename   Name of file to read PMF and target from.
128      * \param[in,out] pull_work          Pointer to a pull struct which AWH will
129      * couple to, has to be initialized, is assumed not to change during the
130      * lifetime of the Awh object.
131      * \param[in] numLambdaStates        The number of free energy lambda states.
132      * \param[in] lambdaState            The initial free energy lambda state of the system.
133      * \throws    InvalidInputError      If there is user input (or combinations thereof) that is not allowed.
134      */
135     Awh(FILE*                 fplog,
136         const t_inputrec&     inputRecord,
137         const t_commrec*      commRecord,
138         const gmx_multisim_t* multiSimRecord,
139         const AwhParams&      awhParams,
140         const std::string&    biasInitFilename,
141         pull_t*               pull_work,
142         int                   numLambdaStates,
143         int                   lambdaState);
144
145     ~Awh();
146
147     /*! \brief Peform an AWH update, to be called every MD step.
148      *
149      * An update has two tasks: apply the bias force and improve
150      * the bias and the free energy estimate that AWH keeps internally.
151      *
152      * For the first task, AWH retrieves the pull coordinate values from the pull struct.
153      * With these, the bias potential and forces are calculated.
154      * The bias force together with the atom forces and virial
155      * are passed on to pull which applies the bias force to the atoms.
156      * This is done at every step.
157      *
158      * Secondly, coordinate values are regularly sampled and kept by AWH.
159      * Convergence of the bias and free energy estimate is achieved by
160      * updating the AWH bias state after a certain number of samples has been collected.
161      *
162      * \note Requires that pull_potential from pull.h has been called first
163      * since AWH needs the current coordinate values (the pull code checks
164      * for this).
165      *
166      * \param[in]     pbcType          Type of periodic boundary conditions.
167      * \param[in]     masses           Atoms masses.
168      * \param[in]     neighborLambdaEnergies An array containing the energy of the system
169      * in neighboring lambdas. The array is of length numLambdas+1, where numLambdas is
170      * the number of free energy lambda states. Element 0 in the array is the energy
171      * of the current state and elements 1..numLambdas contain the energy of the system in the
172      * neighboring lambda states (also including the current state). When there are no free
173      * energy lambda state dimensions this can be empty.
174      * \param[in]     neighborLambdaDhdl     An array containing the dHdL at the neighboring lambda
175      * points. The array is of length numLambdas+1, where numLambdas is the number of free
176      * energy lambda states. Element 0 in the array is the dHdL
177      * of the current state and elements 1..numLambdas contain the dHdL of the system in the
178      * neighboring lambda states (also including the current state). When there are no free
179      * energy lambda state dimensions this can be empty.
180      * \param[in]     box              Box vectors.
181      * \param[in,out] forceWithVirial  Force and virial buffers, should cover at least the local atoms.
182      * \param[in]     t                Time.
183      * \param[in]     step             The current MD step.
184      * \param[in,out] wallcycle        Wallcycle counter, can be nullptr.
185      * \param[in,out] fplog            General output file, normally md.log, can be nullptr.
186      * \returns the potential energy for the bias.
187      */
188     real applyBiasForcesAndUpdateBias(PbcType                pbcType,
189                                       const real*            masses,
190                                       ArrayRef<const double> neighborLambdaEnergies,
191                                       ArrayRef<const double> neighborLambdaDhdl,
192                                       const matrix           box,
193                                       gmx::ForceWithVirial*  forceWithVirial,
194                                       double                 t,
195                                       int64_t                step,
196                                       gmx_wallcycle*         wallcycle,
197                                       FILE*                  fplog);
198
199     /*! \brief
200      * Update the AWH history in preparation for writing to checkpoint file.
201      *
202      * Should be called at least on the master rank at checkpoint steps.
203      *
204      * Should be called with a valid \p awhHistory (is checked).
205      *
206      * \param[in,out] awhHistory  AWH history to set.
207      */
208     void updateHistory(AwhHistory* awhHistory) const;
209
210     /*! \brief
211      * Allocate and initialize an AWH history with the given AWH state.
212      *
213      * This function should be called at the start of a new simulation
214      * at least on the master rank.
215      * Note that only constant data will be initialized here.
216      * History data is set by \ref Awh::updateHistory.
217      *
218      * \returns a shared pointer to the AWH history on the rank that does I/O, nullptr otherwise.
219      */
220     std::shared_ptr<AwhHistory> initHistoryFromState() const;
221
222     /*! \brief Restore the AWH state from the given history.
223      *
224      * Should be called on all ranks (for internal MPI broadcast).
225      * Should pass a point to an AwhHistory on the master rank that
226      * is compatible with the AWH setup in this simulation. Will throw
227      * an exception if it is not compatible.
228      *
229      * \param[in] awhHistory  AWH history to restore from.
230      */
231     void restoreStateFromHistory(const AwhHistory* awhHistory);
232
233     /*! \brief Fills the AWH data block of an energy frame with data at certain steps.
234      *
235      * \param[in]     step  The current MD step.
236      * \param[in,out] fr    Energy data frame.
237      */
238     void writeToEnergyFrame(int64_t step, t_enxframe* fr) const;
239
240     /*! \brief Returns string "AWH" for registering AWH as an external potential provider with the pull module.
241      */
242     static const char* externalPotentialString();
243
244     /*! \brief Register the AWH biased coordinates with pull.
245      *
246      * This function is public because it needs to be called by grompp
247      * (and is otherwise only called by Awh()).
248      * Pull requires all external potentials to register themselves
249      * before the end of pre-processing and before the first MD step.
250      * If this has not happened, pull with throw an error.
251      *
252      * \param[in]     awhParams  The AWH parameters.
253      * \param[in,out] pull_work  Pull struct which AWH will register the bias into.
254      */
255     static void registerAwhWithPull(const AwhParams& awhParams, pull_t* pull_work);
256
257     /*! \brief Get the current free energy lambda state.
258      * \returns The value of lambdaState_.
259      */
260     int fepLambdaState() const { return fepLambdaState_; }
261
262     /*! \brief Returns if foreign energy differences are required during this step.
263      * \param[in]     step             The current MD step.
264      */
265     bool needForeignEnergyDifferences(int64_t step) const;
266
267     /*! \brief Returns true if AWH has a bias with a free energy lambda state dimension at all.
268      */
269     bool hasFepLambdaDimension() const;
270
271 private:
272     /*! \brief Returns whether we need to write output at the current step.
273      *
274      * \param[in]     step             The current MD step.
275      */
276     bool isOutputStep(int64_t step) const;
277
278 private:
279     std::vector<BiasCoupledToSystem> biasCoupledToSystem_; /**< AWH biases and definitions of their coupling to the system. */
280     const int64_t    seed_;   /**< Random seed for MC jumping with umbrella type bias potential. */
281     const int        nstout_; /**< Interval in steps for writing to energy file. */
282     const t_commrec* commRecord_;          /**< Pointer to the communication record. */
283     const gmx_multisim_t* multiSimRecord_; /**< Handler for multi-simulations. */
284     pull_t*               pull_;           /**< Pointer to the pull working data. */
285     double                potentialOffset_; /**< The offset of the bias potential which changes due to bias updates. */
286     const int numFepLambdaStates_; /**< The number of free energy lambda states of the system. */
287     int       fepLambdaState_;     /**< The current free energy lambda state. */
288 };
289
290 /*! \brief Makes an Awh and prepares to use it if the user input
291  * requests that
292  *
293  * Restores state from history in checkpoint if needed.
294  *
295  * \param[in,out] fplog                   General output file, normally md.log, can be nullptr.
296  * \param[in]     inputRecord             General input parameters (as set up by grompp).
297  * \param[in]     stateGlobal             A pointer to the global state structure.
298  * \param[in]     commRecord              Struct for communication, can be nullptr.
299  * \param[in]     multiSimRecord          Multi-sim handler
300  * \param[in]     startingFromCheckpoint  Whether the simulation is starting from a checkpoint
301  * \param[in]     usingShellParticles     Whether the user requested shell particles (which is unsupported)
302  * \param[in]     biasInitFilename        Name of file to read PMF and target from.
303  * \param[in,out] pull_work               Pointer to a pull struct which AWH will couple to, has to be initialized,
304  *                                        is assumed not to change during the lifetime of the Awh object.
305  * \returns       An initialized Awh module, or nullptr if none was requested.
306  * \throws        InvalidInputError       If another active module is not supported.
307  */
308 std::unique_ptr<Awh> prepareAwhModule(FILE*                 fplog,
309                                       const t_inputrec&     inputRecord,
310                                       t_state*              stateGlobal,
311                                       const t_commrec*      commRecord,
312                                       const gmx_multisim_t* multiSimRecord,
313                                       bool                  startingFromCheckpoint,
314                                       bool                  usingShellParticles,
315                                       const std::string&    biasInitFilename,
316                                       pull_t*               pull_work);
317
318 } // namespace gmx
319
320 #endif /* GMX_AWH_H */