b53777cfd84f38dc2b9dd3a96445468a56ad247f
[alexxy/gromacs.git] / src / gromacs / applied_forces / awh / tests / bias_fep_lambda_state.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2017,2018,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.
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 #include "gmxpre.h"
36
37 #include <cmath>
38
39 #include <memory>
40 #include <tuple>
41 #include <vector>
42
43 #include <gmock/gmock.h>
44 #include <gtest/gtest.h>
45
46 #include "gromacs/applied_forces/awh/bias.h"
47 #include "gromacs/applied_forces/awh/correlationgrid.h"
48 #include "gromacs/applied_forces/awh/pointstate.h"
49 #include "gromacs/mdtypes/awh_params.h"
50 #include "gromacs/utility/stringutil.h"
51
52 #include "testutils/refdata.h"
53 #include "testutils/testasserts.h"
54
55 namespace gmx
56 {
57
58 namespace test
59 {
60
61 //! The number of lambda states to use in the tests.
62 const int numLambdaStates = 16;
63
64 /*! \internal \brief
65  * Struct that gathers all input for setting up and using a Bias
66  */
67 struct AwhFepLambdaStateTestParameters
68 {
69     AwhFepLambdaStateTestParameters() = default;
70     //! Move constructor
71     AwhFepLambdaStateTestParameters(AwhFepLambdaStateTestParameters&& o) noexcept :
72         beta(o.beta),
73         awhDimParams(o.awhDimParams),
74         awhBiasParams(o.awhBiasParams),
75         awhParams(o.awhParams),
76         dimParams(std::move(o.dimParams))
77     {
78         awhBiasParams.dimParams = &awhDimParams;
79         awhParams.awhBiasParams = &awhBiasParams;
80     }
81     double beta; //!< 1/(kB*T)
82
83     AwhDimParams  awhDimParams;  //!< Dimension parameters pointed to by \p awhBiasParams
84     AwhBiasParams awhBiasParams; //!< Bias parameters pointed to by \[ awhParams
85     AwhParams     awhParams;     //!< AWH parameters, this is the struct to actually use
86
87     std::vector<DimParams> dimParams; //!< Dimension parameters for setting up Bias
88 };
89
90 //! Helper function to set up the C-style AWH parameters for the test
91 static AwhFepLambdaStateTestParameters getAwhFepLambdaTestParameters(AwhHistogramGrowthType eawhgrowth,
92                                                                      AwhPotentialType eawhpotential)
93 {
94     AwhFepLambdaStateTestParameters params;
95
96     params.beta = 0.4;
97
98     AwhDimParams& awhDimParams = params.awhDimParams;
99
100     awhDimParams.period = 0;
101     // Correction for removal of GaussianGeometryFactor/2 in histogram size
102     awhDimParams.diffusion      = 1e-4 / (0.12927243028700 * 2);
103     awhDimParams.origin         = 0;
104     awhDimParams.end            = numLambdaStates - 1;
105     awhDimParams.coordValueInit = awhDimParams.origin;
106     awhDimParams.coverDiameter  = 0;
107     awhDimParams.eCoordProvider = AwhCoordinateProviderType::FreeEnergyLambda;
108
109     AwhBiasParams& awhBiasParams = params.awhBiasParams;
110
111     awhBiasParams.ndim                 = 1;
112     awhBiasParams.dimParams            = &awhDimParams;
113     awhBiasParams.eTarget              = AwhTargetType::Constant;
114     awhBiasParams.targetBetaScaling    = 0;
115     awhBiasParams.targetCutoff         = 0;
116     awhBiasParams.eGrowth              = eawhgrowth;
117     awhBiasParams.bUserData            = FALSE;
118     awhBiasParams.errorInitial         = 1.0 / params.beta;
119     awhBiasParams.shareGroup           = 0;
120     awhBiasParams.equilibrateHistogram = FALSE;
121
122     int64_t seed = 93471803;
123
124     params.dimParams.push_back(DimParams::fepLambdaDimParams(numLambdaStates, params.beta));
125
126     AwhParams& awhParams = params.awhParams;
127
128     awhParams.numBias                    = 1;
129     awhParams.awhBiasParams              = &awhBiasParams;
130     awhParams.seed                       = seed;
131     awhParams.nstOut                     = 0;
132     awhParams.nstSampleCoord             = 1;
133     awhParams.numSamplesUpdateFreeEnergy = 10;
134     awhParams.ePotential                 = eawhpotential;
135     awhParams.shareBiasMultisim          = FALSE;
136
137     return params;
138 }
139
140 //! Convenience typedef: growth type enum, potential type enum, disable update skips
141 typedef std::tuple<AwhHistogramGrowthType, AwhPotentialType, BiasParams::DisableUpdateSkips> BiasTestParameters;
142
143 /*! \brief Test fixture for testing Bias updates
144  */
145 class BiasFepLambdaStateTest : public ::testing::TestWithParam<BiasTestParameters>
146 {
147 public:
148     //! Random seed for AWH MC sampling
149     int64_t seed_;
150
151     //! The awh Bias
152     std::unique_ptr<Bias> bias_;
153
154     BiasFepLambdaStateTest()
155     {
156         /* We test all combinations of:
157          *   eawhgrowth:
158          *     eawhgrowthLINEAR:     final, normal update phase
159          *     ewahgrowthEXP_LINEAR: intial phase, updated size is constant
160          *   eawhpotential (test both, but for the FEP lambda state dimension MC will in practice be used,
161          *                  except that eawhpotentialCONVOLVED also gives a potential output):
162          *     eawhpotentialUMBRELLA:  MC on lambda state
163          *     eawhpotentialCONVOLVED: MD on a convolved potential landscape (falling back to MC on lambda state)
164          *   disableUpdateSkips (should not affect the results):
165          *     BiasParams::DisableUpdateSkips::yes: update the point state for every sample
166          *     BiasParams::DisableUpdateSkips::no:  update the point state at an interval > 1 sample
167          *
168          * Note: It would be nice to explicitly check that eawhpotential
169          *       and disableUpdateSkips do not affect the point state.
170          *       But the reference data will also ensure this.
171          */
172         AwhHistogramGrowthType         eawhgrowth;
173         AwhPotentialType               eawhpotential;
174         BiasParams::DisableUpdateSkips disableUpdateSkips;
175         std::tie(eawhgrowth, eawhpotential, disableUpdateSkips) = GetParam();
176
177         /* Set up a basic AWH setup with a single, 1D bias with parameters
178          * such that we can measure the effects of different parameters.
179          */
180         const AwhFepLambdaStateTestParameters params =
181                 getAwhFepLambdaTestParameters(eawhgrowth, eawhpotential);
182
183         seed_ = params.awhParams.seed;
184
185         double mdTimeStep = 0.1;
186
187         bias_ = std::make_unique<Bias>(-1,
188                                        params.awhParams,
189                                        params.awhBiasParams,
190                                        params.dimParams,
191                                        params.beta,
192                                        mdTimeStep,
193                                        1,
194                                        "",
195                                        Bias::ThisRankWillDoIO::No,
196                                        disableUpdateSkips);
197     }
198 };
199
200 TEST_P(BiasFepLambdaStateTest, ForcesBiasPmf)
201 {
202     gmx::test::TestReferenceData    data;
203     gmx::test::TestReferenceChecker checker(data.rootChecker());
204
205     Bias& bias = *bias_;
206
207     /* Make strings with the properties we expect to be different in the tests.
208      * These also helps to interpret the reference data.
209      */
210     std::vector<std::string> props;
211     props.push_back(formatString("stage:           %s", bias.state().inInitialStage() ? "initial" : "final"));
212     props.push_back(formatString("convolve forces: %s", bias.params().convolveForce ? "yes" : "no"));
213     props.push_back(formatString("skip updates:    %s", bias.params().skipUpdates() ? "yes" : "no"));
214
215     SCOPED_TRACE(gmx::formatString("%s, %s, %s", props[0].c_str(), props[1].c_str(), props[2].c_str()));
216
217     std::vector<double> force, pot;
218
219     double potentialJump = 0;
220     double mdTimeStep    = 0.1;
221     int    nSteps        = 501;
222
223     /* Some energies to use as base values (to which some noise is added later on). */
224     std::vector<double> neighborLambdaEnergies(numLambdaStates);
225     std::vector<double> neighborLambdaDhdl(numLambdaStates);
226     const double        magnitude = 12.0;
227     for (int i = 0; i < numLambdaStates; i++)
228     {
229         neighborLambdaEnergies[i] = magnitude * std::sin(i * 0.1);
230         neighborLambdaDhdl[i]     = magnitude * std::cos(i * 0.1);
231     }
232
233     for (int step = 0; step < nSteps; step++)
234     {
235         int      umbrellaGridpointIndex = bias.state().coordState().umbrellaGridpoint();
236         awh_dvec coordValue = { bias.getGridCoordValue(umbrellaGridpointIndex)[0], 0, 0, 0 };
237         double   potential  = 0;
238         gmx::ArrayRef<const double> biasForce = bias.calcForceAndUpdateBias(coordValue,
239                                                                             neighborLambdaEnergies,
240                                                                             neighborLambdaDhdl,
241                                                                             &potential,
242                                                                             &potentialJump,
243                                                                             nullptr,
244                                                                             nullptr,
245                                                                             step * mdTimeStep,
246                                                                             step,
247                                                                             seed_,
248                                                                             nullptr);
249
250         force.push_back(biasForce[0]);
251         pot.push_back(potential);
252     }
253
254     /* When skipping updates, ensure all skipped updates are performed here.
255      * This should result in the same bias state as at output in a normal run.
256      */
257     if (bias.params().skipUpdates())
258     {
259         bias.doSkippedUpdatesForAllPoints();
260     }
261
262     std::vector<double> pointBias, logPmfsum;
263     for (auto& point : bias.state().points())
264     {
265         pointBias.push_back(point.bias());
266         logPmfsum.push_back(point.logPmfSum());
267     }
268
269     constexpr int ulpTol = 10;
270
271     checker.checkSequence(props.begin(), props.end(), "Properties");
272     checker.setDefaultTolerance(absoluteTolerance(magnitude * GMX_DOUBLE_EPS * ulpTol));
273     checker.checkSequence(force.begin(), force.end(), "Force");
274     checker.checkSequence(pot.begin(), pot.end(), "Potential");
275     checker.setDefaultTolerance(relativeToleranceAsUlp(1.0, ulpTol));
276     checker.checkSequence(pointBias.begin(), pointBias.end(), "PointBias");
277     checker.checkSequence(logPmfsum.begin(), logPmfsum.end(), "PointLogPmfsum");
278 }
279
280 /* Scan initial/final phase, MC/convolved force and update skip (not) allowed
281  * Both the convolving and skipping should not affect the bias and PMF.
282  * It would be nice if the test would explicitly check for this.
283  * Currently this is tested through identical reference data.
284  */
285 INSTANTIATE_TEST_CASE_P(WithParameters,
286                         BiasFepLambdaStateTest,
287                         ::testing::Combine(::testing::Values(AwhHistogramGrowthType::Linear,
288                                                              AwhHistogramGrowthType::ExponentialLinear),
289                                            ::testing::Values(AwhPotentialType::Umbrella,
290                                                              AwhPotentialType::Convolved),
291                                            ::testing::Values(BiasParams::DisableUpdateSkips::yes,
292                                                              BiasParams::DisableUpdateSkips::no)));
293
294 // Test that we detect coverings and exit the initial stage at the correct step
295 TEST(BiasFepLambdaStateTest, DetectsCovering)
296 {
297     const AwhFepLambdaStateTestParameters params = getAwhFepLambdaTestParameters(
298             AwhHistogramGrowthType::ExponentialLinear, AwhPotentialType::Convolved);
299
300     const double mdTimeStep = 0.1;
301
302     Bias bias(-1,
303               params.awhParams,
304               params.awhBiasParams,
305               params.dimParams,
306               params.beta,
307               mdTimeStep,
308               1,
309               "",
310               Bias::ThisRankWillDoIO::No);
311
312     const int64_t exitStepRef = 320;
313
314     bool inInitialStage = bias.state().inInitialStage();
315
316     /* Some energies to use as base values (to which some noise is added later on). */
317     std::vector<double> neighborLambdaEnergies(numLambdaStates);
318     std::vector<double> neighborLambdaDhdl(numLambdaStates);
319     const double        magnitude = 12.0;
320     for (int i = 0; i < numLambdaStates; i++)
321     {
322         neighborLambdaEnergies[i] = magnitude * std::sin(i * 0.1);
323         neighborLambdaDhdl[i]     = magnitude * std::cos(i * 0.1);
324     }
325
326     int64_t step;
327     /* Normally this loop exits at exitStepRef, but we extend with failure */
328     for (step = 0; step <= 2 * exitStepRef; step++)
329     {
330         int      umbrellaGridpointIndex = bias.state().coordState().umbrellaGridpoint();
331         awh_dvec coordValue = { bias.getGridCoordValue(umbrellaGridpointIndex)[0], 0, 0, 0 };
332
333         double potential     = 0;
334         double potentialJump = 0;
335         bias.calcForceAndUpdateBias(coordValue,
336                                     neighborLambdaEnergies,
337                                     neighborLambdaDhdl,
338                                     &potential,
339                                     &potentialJump,
340                                     nullptr,
341                                     nullptr,
342                                     step,
343                                     step,
344                                     params.awhParams.seed,
345                                     nullptr);
346
347         inInitialStage = bias.state().inInitialStage();
348         if (!inInitialStage)
349         {
350             break;
351         }
352     }
353
354     EXPECT_EQ(false, inInitialStage);
355     if (!inInitialStage)
356     {
357         EXPECT_EQ(exitStepRef, step);
358     }
359 }
360
361 } // namespace test
362 } // namespace gmx