Generalize constraints on MPI rank counts for tests
[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,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 /*! \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/ewald/pme.h"
58 #include "gromacs/hardware/detecthardware.h"
59 #include "gromacs/hardware/device_management.h"
60 #include "gromacs/hardware/hw_info.h"
61 #include "gromacs/trajectory/energyframe.h"
62 #include "gromacs/utility/basenetwork.h"
63 #include "gromacs/utility/cstringutil.h"
64 #include "gromacs/utility/gmxmpi.h"
65 #include "gromacs/utility/physicalnodecommunicator.h"
66 #include "gromacs/utility/stringutil.h"
67
68 #include "testutils/mpitest.h"
69 #include "testutils/refdata.h"
70
71 #include "energyreader.h"
72 #include "moduletest.h"
73
74 namespace gmx
75 {
76 namespace test
77 {
78 namespace
79 {
80
81 /*! \brief A basic PME runner
82  *
83  * \todo Consider also using GpuTest class. */
84 class PmeTest : public MdrunTestFixture
85 {
86 public:
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 void PmeTest::runTest(const RunModesList& runModes)
94 {
95     const std::string inputFile = "spc-and-methanol";
96     runner_.useTopGroAndNdxFromDatabase(inputFile);
97
98     // With single rank we can and will always test PP+PME as part of mdrun-test.
99     // With multiple ranks we can additionally test a single PME-only rank within mdrun-mpi-test.
100     const bool parallelRun    = (getNumberOfTestMpiRanks() > 1);
101     const bool useSeparatePme = parallelRun;
102
103     EXPECT_EQ(0, runner_.callGrompp());
104
105     TestReferenceData    refData;
106     TestReferenceChecker rootChecker(refData.rootChecker());
107     const bool           thisRankChecks = (gmx_node_rank() == 0);
108     if (!thisRankChecks)
109     {
110         EXPECT_NONFATAL_FAILURE(rootChecker.checkUnusedEntries(), ""); // skip checks on other ranks
111     }
112
113     auto hardwareInfo_ =
114             gmx_detect_hardware(PhysicalNodeCommunicator(MPI_COMM_WORLD, gmx_physicalnode_id_hash()));
115
116     for (const auto& mode : runModes)
117     {
118         SCOPED_TRACE("mdrun " + joinStrings(mode.second, " "));
119         auto modeTargetsGpus = (mode.first.find("Gpu") != std::string::npos);
120         if (modeTargetsGpus && getCompatibleDevices(hardwareInfo_->deviceInfoList).empty())
121         {
122             // This run mode will cause a fatal error from mdrun when
123             // it can't find GPUs, which is not something we're trying
124             // to test here.
125             continue;
126         }
127         auto modeTargetsPmeOnGpus = (mode.first.find("PmeOnGpu") != std::string::npos);
128         if (modeTargetsPmeOnGpus
129             && !(pme_gpu_supports_build(nullptr) && pme_gpu_supports_hardware(*hardwareInfo_, nullptr)))
130         {
131             // This run mode will cause a fatal error from mdrun when
132             // it finds an unsuitable device, which is not something
133             // we're trying to test here.
134             continue;
135         }
136
137         runner_.edrFileName_ =
138                 fileManager_.getTemporaryFilePath(inputFile + "_" + mode.first + ".edr");
139
140         CommandLine commandLine(mode.second);
141
142         const bool usePmeTuning = (mode.first.find("Tune") != std::string::npos);
143         if (usePmeTuning)
144         {
145             commandLine.append("-tunepme");
146             commandLine.addOption("-nstlist", 1); // a new grid every step
147         }
148         else
149         {
150             commandLine.append("-notunepme"); // for reciprocal energy reproducibility
151         }
152         if (useSeparatePme)
153         {
154             commandLine.addOption("-npme", 1);
155         }
156
157         ASSERT_EQ(0, runner_.callMdrun(commandLine));
158
159         if (thisRankChecks)
160         {
161             auto energyReader = openEnergyFileToReadTerms(
162                     runner_.edrFileName_, { "Coul. recip.", "Total Energy", "Kinetic En." });
163             auto conservedChecker  = rootChecker.checkCompound("Energy", "Conserved");
164             auto reciprocalChecker = rootChecker.checkCompound("Energy", "Reciprocal");
165             bool firstIteration    = true;
166             while (energyReader->readNextFrame())
167             {
168                 const EnergyFrame& frame            = energyReader->frame();
169                 const std::string  stepName         = frame.frameName();
170                 const real         conservedEnergy  = frame.at("Total Energy");
171                 const real         reciprocalEnergy = frame.at("Coul. recip.");
172                 if (firstIteration)
173                 {
174                     // use first step values as references for tolerance
175                     const real startingKineticEnergy = frame.at("Kinetic En.");
176                     const auto conservedTolerance =
177                             relativeToleranceAsFloatingPoint(startingKineticEnergy, 2e-5);
178                     const auto reciprocalTolerance =
179                             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(
198             "coulombtype     = PME\n"
199             "nstcalcenergy   = 1\n"
200             "nstenergy       = 1\n"
201             "pme-order       = 4\n"
202             "nsteps          = %d\n",
203             nsteps);
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(
226             "coulombtype     = PME\n"
227             "nstcalcenergy   = 1\n"
228             "nstenergy       = 1\n"
229             "pme-order       = 4\n"
230             "pbc             = xyz\n"
231             "nsteps          = %d\n",
232             nsteps);
233
234     runner_.useStringAsMdpFile(theMdpFile);
235
236     RunModesList runModes;
237     runModes["PmeOnCpu"]         = { "-pme", "cpu" };
238     runModes["PmeOnGpuFftOnCpu"] = { "-pme", "gpu", "-pmefft", "cpu" };
239     runModes["PmeOnGpuFftOnGpu"] = { "-pme", "gpu", "-pmefft", "gpu" };
240
241     runTest(runModes);
242 }
243
244 TEST_F(PmeTest, ScalesTheBoxWithWalls)
245 {
246     const int         nsteps     = 0;
247     const std::string theMdpFile = formatString(
248             "coulombtype     = PME\n"
249             "nstcalcenergy   = 1\n"
250             "nstenergy       = 1\n"
251             "pme-order       = 4\n"
252             "pbc             = xy\n"
253             "nwall           = 2\n"
254             "ewald-geometry  = 3dc\n"
255             "wall_atomtype   = CMet H\n"
256             "wall_density    = 9 9.0\n"
257             "wall-ewald-zfac = 5\n"
258             "nsteps          = %d\n",
259             nsteps);
260
261     runner_.useStringAsMdpFile(theMdpFile);
262
263     RunModesList runModes;
264     runModes["PmeOnCpu"]         = { "-pme", "cpu" };
265     runModes["PmeOnGpuFftOnCpu"] = { "-pme", "gpu", "-pmefft", "cpu" };
266     runModes["PmeOnGpuFftOnGpu"] = { "-pme", "gpu", "-pmefft", "gpu" };
267
268     runTest(runModes);
269 }
270
271 } // namespace
272 } // namespace test
273 } // namespace gmx