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