Merge branch release-2018
[alexxy/gromacs.git] / src / programs / mdrun / tests / pmetest.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2016,2017,2018, 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 /*! \internal \file
36  * \brief
37  * This implements basic PME sanity tests.
38  * It runs the input system with PME for several steps (on CPU and GPU, if available),
39  * and checks the reciprocal and conserved energies.
40  * As part of mdrun-test, this will always run single rank PME simulation.
41  * As part of mdrun-mpi-test, this will run same as above when a single rank is requested,
42  * or a simulation with a single separate PME rank ("-npme 1") when multiple ranks are requested.
43  * \todo Extend and generalize this for more multi-rank tests (-npme 0, -npme 2, etc).
44  * \todo Implement death tests (e.g. for PME GPU decomposition).
45  *
46  * \author Aleksei Iupinov <a.yupinov@gmail.com>
47  * \ingroup module_mdrun_integration_tests
48  */
49 #include "gmxpre.h"
50
51 #include "config.h"
52
53 #include <map>
54 #include <string>
55 #include <vector>
56
57 #include <gtest/gtest-spi.h>
58
59 #include "gromacs/gpu_utils/gpu_utils.h"
60 #include "gromacs/hardware/gpu_hw_info.h"
61 #include "gromacs/utility/cstringutil.h"
62 #include "gromacs/utility/gmxmpi.h"
63 #include "gromacs/utility/stringutil.h"
64
65 #include "testutils/mpitest.h"
66 #include "testutils/refdata.h"
67
68 #include "energyreader.h"
69 #include "moduletest.h"
70
71 namespace gmx
72 {
73 namespace test
74 {
75 namespace
76 {
77
78 /*! \brief A basic PME runner
79  *
80  * \todo Consider also using GpuTest class. */
81 class PmeTest : public MdrunTestFixture
82 {
83     public:
84         //! Before any test is run, work out whether any compatible GPUs exist.
85         static void SetUpTestCase();
86         //! Store whether any compatible GPUs exist.
87         static bool s_hasCompatibleCudaGpus;
88         //! Convenience typedef
89         using RunModesList = std::map < std::string, std::vector < const char *>>;
90         //! Runs the test with the given inputs
91         void runTest(const RunModesList &runModes);
92 };
93
94 bool PmeTest::s_hasCompatibleCudaGpus = false;
95
96 void PmeTest::SetUpTestCase()
97 {
98     gmx_gpu_info_t gpuInfo {};
99     // It would be nicer to do this detection once and have mdrun
100     // re-use it, but this is OK. Note that this also caters for when
101     // there is no GPU support in the build.
102     //
103     // TODO report any error messages gracefully.
104     if (GMX_GPU == GMX_GPU_CUDA &&
105         canDetectGpus(nullptr))
106     {
107         findGpus(&gpuInfo);
108         s_hasCompatibleCudaGpus = (gpuInfo.n_dev_compatible > 0);
109     }
110     free_gpu_info(&gpuInfo);
111 }
112
113 void PmeTest::runTest(const RunModesList &runModes)
114 {
115     const std::string inputFile = "spc-and-methanol";
116     runner_.useTopGroAndNdxFromDatabase(inputFile.c_str());
117
118     // With single rank we can and will always test PP+PME as part of mdrun-test.
119     // With multiple ranks we can additionally test a single PME-only rank within mdrun-mpi-test.
120     const bool parallelRun    = (getNumberOfTestMpiRanks() > 1);
121     const bool useSeparatePme = parallelRun;
122
123     EXPECT_EQ(0, runner_.callGrompp());
124
125     TestReferenceData    refData;
126     TestReferenceChecker rootChecker(refData.rootChecker());
127     const bool           thisRankChecks = (gmx_node_rank() == 0);
128     if (!thisRankChecks)
129     {
130         EXPECT_NONFATAL_FAILURE(rootChecker.checkUnusedEntries(), ""); // skip checks on other ranks
131     }
132     for (const auto &mode : runModes)
133     {
134         auto modeTargetsGpus = (mode.first.find("Gpu") != std::string::npos);
135         if (modeTargetsGpus && !s_hasCompatibleCudaGpus)
136         {
137             // This run mode will cause a fatal error from mdrun when
138             // it can't find GPUs, which is not something we're trying
139             // to test here.
140             continue;
141         }
142
143         runner_.edrFileName_ = fileManager_.getTemporaryFilePath(inputFile + "_" + mode.first + ".edr");
144
145         CommandLine commandLine(mode.second);
146
147         const bool  usePmeTuning = (mode.first.find("Tune") != std::string::npos);
148         if (usePmeTuning)
149         {
150             commandLine.append("-tunepme");
151             commandLine.addOption("-nstlist", 1); // a new grid every step
152         }
153         else
154         {
155             commandLine.append("-notunepme"); // for reciprocal energy reproducibility
156         }
157         if (useSeparatePme)
158         {
159             commandLine.addOption("-npme", 1);
160         }
161
162         ASSERT_EQ(0, runner_.callMdrun(commandLine));
163
164         if (thisRankChecks)
165         {
166             auto energyReader      = openEnergyFileToReadFields(runner_.edrFileName_, {"Coul. recip.", "Total Energy", "Kinetic En."});
167             auto conservedChecker  = rootChecker.checkCompound("Energy", "Conserved");
168             auto reciprocalChecker = rootChecker.checkCompound("Energy", "Reciprocal");
169             bool firstIteration    = true;
170             while (energyReader->readNextFrame())
171             {
172                 const EnergyFrame &frame            = energyReader->frame();
173                 const std::string  stepName         = frame.getFrameName();
174                 const real         conservedEnergy  = frame.at("Total Energy");
175                 const real         reciprocalEnergy = frame.at("Coul. recip.");
176                 if (firstIteration)
177                 {
178                     // use first step values as references for tolerance
179                     const real startingKineticEnergy = frame.at("Kinetic En.");
180                     const auto conservedTolerance    = relativeToleranceAsFloatingPoint(startingKineticEnergy, 2e-5);
181                     const auto reciprocalTolerance   = relativeToleranceAsFloatingPoint(reciprocalEnergy, 3e-5);
182                     reciprocalChecker.setDefaultTolerance(reciprocalTolerance);
183                     conservedChecker.setDefaultTolerance(conservedTolerance);
184                     firstIteration = false;
185                 }
186                 conservedChecker.checkReal(conservedEnergy, stepName.c_str());
187                 if (!usePmeTuning) // with PME tuning come differing grids and differing reciprocal energy
188                 {
189                     reciprocalChecker.checkReal(reciprocalEnergy, stepName.c_str());
190                 }
191             }
192         }
193     }
194 }
195
196 TEST_F(PmeTest, ReproducesEnergies)
197 {
198     const int         nsteps     = 20;
199     const std::string theMdpFile = formatString("coulombtype     = PME\n"
200                                                 "nstcalcenergy   = 1\n"
201                                                 "nstenergy       = 1\n"
202                                                 "pme-order       = 4\n"
203                                                 "nsteps          = %d\n",
204                                                 nsteps
205                                                 );
206
207     runner_.useStringAsMdpFile(theMdpFile);
208
209     //TODO test all proper/improper combinations in more thorough way?
210     RunModesList runModes;
211     runModes["PmeOnCpu"]         = {"-pme", "cpu"};
212     runModes["PmeAuto"]          = {"-pme", "auto"};
213     runModes["PmeOnGpuFftOnCpu"] = {"-pme", "gpu", "-pmefft", "cpu"};
214     runModes["PmeOnGpuFftOnGpu"] = {"-pme", "gpu", "-pmefft", "gpu"};
215     runModes["PmeOnGpuFftAuto"]  = {"-pme", "gpu", "-pmefft", "auto"};
216     // same manual modes but marked for PME tuning
217     runModes["PmeOnCpuTune"]         = {"-pme", "cpu"};
218     runModes["PmeOnGpuFftOnCpuTune"] = {"-pme", "gpu", "-pmefft", "cpu"};
219     runModes["PmeOnGpuFftOnGpuTune"] = {"-pme", "gpu", "-pmefft", "gpu"};
220
221     runTest(runModes);
222 }
223
224 TEST_F(PmeTest, ScalesTheBox)
225 {
226     const int         nsteps     = 0;
227     const std::string theMdpFile = formatString("coulombtype     = PME\n"
228                                                 "nstcalcenergy   = 1\n"
229                                                 "nstenergy       = 1\n"
230                                                 "pme-order       = 4\n"
231                                                 "pbc             = xy\n"
232                                                 "nwall           = 2\n"
233                                                 "ewald-geometry  = 3dc\n"
234                                                 "wall_atomtype   = OMet CMet\n"
235                                                 "wall_density    = 9 9.0\n"
236                                                 "wall-ewald-zfac = 5\n"
237                                                 "nsteps          = %d\n",
238                                                 nsteps
239                                                 );
240
241     runner_.useStringAsMdpFile(theMdpFile);
242
243     RunModesList runModes;
244     runModes["PmeOnCpu"]         = {"-pme", "cpu"};
245     runModes["PmeOnGpuFftOnCpu"] = {"-pme", "gpu", "-pmefft", "cpu"};
246     runModes["PmeOnGpuFftOnGpu"] = {"-pme", "gpu", "-pmefft", "gpu"};
247
248     runTest(runModes);
249 }
250
251 }
252 }
253 }