1a15c721a9db9d08296836959a08b0c7d157e9e9
[alexxy/gromacs.git] / src / programs / mdrun / tests / moduletest.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2013,2014,2015,2016,2017 by the GROMACS development team.
5  * Copyright (c) 2018,2019,2020,2021, by the GROMACS development team, led by
6  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7  * and including many others, as listed in the AUTHORS file in the
8  * top-level source directory and at http://www.gromacs.org.
9  *
10  * GROMACS is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public License
12  * as published by the Free Software Foundation; either version 2.1
13  * of the License, or (at your option) any later version.
14  *
15  * GROMACS is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with GROMACS; if not, see
22  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
24  *
25  * If you want to redistribute modifications to GROMACS, please
26  * consider that scientific software is very special. Version
27  * control is crucial - bugs must be traceable. We will be happy to
28  * consider code for inclusion in the official distribution, but
29  * derived work must not be called official GROMACS. Details are found
30  * in the README & COPYING files - if they are missing, get the
31  * official version at http://www.gromacs.org.
32  *
33  * To help us fund GROMACS development, we humbly ask that you cite
34  * the research papers on the package. Check out http://www.gromacs.org.
35  */
36 /*! \internal \file
37  * \brief
38  * Implements classes in moduletest.h.
39  *
40  * \author Mark Abraham <mark.j.abraham@gmail.com>
41  * \ingroup module_mdrun_integration_tests
42  */
43 #include "gmxpre.h"
44
45 #include "moduletest.h"
46
47 #include "config.h"
48
49 #include <cstdio>
50
51 #include <utility>
52
53 #include "gromacs/gmxana/gmx_ana.h"
54 #include "gromacs/gmxpreprocess/grompp.h"
55 #include "gromacs/hardware/detecthardware.h"
56 #include "gromacs/hardware/hw_info.h"
57 #include "gromacs/options/basicoptions.h"
58 #include "gromacs/options/ioptionscontainer.h"
59 #include "gromacs/tools/convert_tpr.h"
60 #include "gromacs/utility/basedefinitions.h"
61 #include "gromacs/utility/basenetwork.h"
62 #include "gromacs/utility/gmxmpi.h"
63 #include "gromacs/utility/physicalnodecommunicator.h"
64 #include "gromacs/utility/textwriter.h"
65 #include "programs/mdrun/mdrun_main.h"
66
67 #include "testutils/cmdlinetest.h"
68 #include "testutils/mpitest.h"
69 #include "testutils/testfilemanager.h"
70 #include "testutils/testoptions.h"
71
72 namespace gmx
73 {
74 namespace test
75 {
76
77 /********************************************************************
78  * MdrunTestFixture
79  */
80
81 namespace
82 {
83
84 #if GMX_OPENMP || defined(DOXYGEN)
85 //! Number of OpenMP threads for child mdrun call.
86 // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
87 int g_numOpenMPThreads = 1;
88 #endif
89 //! \cond
90 // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
91 GMX_TEST_OPTIONS(MdrunTestOptions, options)
92 {
93     GMX_UNUSED_VALUE(options);
94 #if GMX_OPENMP
95     options->addOption(
96             IntegerOption("ntomp").store(&g_numOpenMPThreads).description("Number of OpenMP threads for child mdrun calls"));
97 #endif
98 }
99 //! \endcond
100
101 } // namespace
102
103 SimulationRunner::SimulationRunner(TestFileManager* fileManager) :
104     fullPrecisionTrajectoryFileName_(fileManager->getTemporaryFilePath(".trr")),
105     mdpOutputFileName_(fileManager->getTemporaryFilePath("output.mdp")),
106     tprFileName_(fileManager->getTemporaryFilePath(".tpr")),
107     logFileName_(fileManager->getTemporaryFilePath(".log")),
108     edrFileName_(fileManager->getTemporaryFilePath(".edr")),
109     mtxFileName_(fileManager->getTemporaryFilePath(".mtx")),
110
111     nsteps_(-2),
112     mdpSource_(SimulationRunnerMdpSource::Undefined),
113     fileManager_(*fileManager)
114 {
115 #if GMX_LIB_MPI
116     GMX_RELEASE_ASSERT(gmx_mpi_initialized(), "MPI system not initialized for mdrun tests");
117
118     // It would be better to also detect this in a thread-MPI build,
119     // but there is no way to do that currently, and it is also not a
120     // problem for such a build. Any code based on such an invalid
121     // test fixture will be found in CI testing, however.
122     GMX_RELEASE_ASSERT(MdrunTestFixtureBase::communicator_ != MPI_COMM_NULL,
123                        "SimulationRunner may only be used from a test fixture that inherits from "
124                        "MdrunTestFixtureBase");
125 #endif
126 }
127
128 // TODO The combination of defaulting to Verlet cut-off scheme, NVE,
129 // and verlet-buffer-tolerance = -1 gives a grompp error. If we keep
130 // things that way, this function should be renamed. For now,
131 // we use the Verlet scheme and hard-code a tolerance.
132 // TODO There is possible outstanding unexplained behaviour of mdp
133 // input parsing e.g. Issue #2074, so this particular set of mdp
134 // contents is also tested with GetIrTest in gmxpreprocess-test.
135 void SimulationRunner::useEmptyMdpFile()
136 {
137     useStringAsMdpFile("");
138 }
139
140 void SimulationRunner::useStringAsMdpFile(const char* mdpString)
141 {
142     useStringAsMdpFile(std::string(mdpString));
143 }
144
145 void SimulationRunner::useStringAsMdpFile(const std::string& mdpString)
146 {
147     GMX_RELEASE_ASSERT(mdpSource_ != SimulationRunnerMdpSource::File,
148                        "Cannot mix .mdp file from database with options set via string.");
149     mdpSource_        = SimulationRunnerMdpSource::String;
150     mdpInputContents_ = mdpString;
151 }
152
153 void SimulationRunner::useStringAsNdxFile(const char* ndxString) const
154 {
155     gmx::TextWriter::writeFileFromString(ndxFileName_, ndxString);
156 }
157
158 void SimulationRunner::useTopG96AndNdxFromDatabase(const std::string& name)
159 {
160     topFileName_ = gmx::test::TestFileManager::getInputFilePath(name + ".top");
161     groFileName_ = gmx::test::TestFileManager::getInputFilePath(name + ".g96");
162     ndxFileName_ = gmx::test::TestFileManager::getInputFilePath(name + ".ndx");
163 }
164
165 void SimulationRunner::useTopGroAndNdxFromDatabase(const std::string& name)
166 {
167     topFileName_ = gmx::test::TestFileManager::getInputFilePath(name + ".top");
168     groFileName_ = gmx::test::TestFileManager::getInputFilePath(name + ".gro");
169     ndxFileName_ = gmx::test::TestFileManager::getInputFilePath(name + ".ndx");
170 }
171
172 void SimulationRunner::useGroFromDatabase(const char* name)
173 {
174     groFileName_ = gmx::test::TestFileManager::getInputFilePath((std::string(name) + ".gro").c_str());
175 }
176
177 void SimulationRunner::useTopGroAndMdpFromFepTestDatabase(const std::string& name)
178 {
179     GMX_RELEASE_ASSERT(mdpSource_ != SimulationRunnerMdpSource::String,
180                        "Cannot mix .mdp file from database with options set via string.");
181     mdpSource_   = SimulationRunnerMdpSource::File;
182     topFileName_ = gmx::test::TestFileManager::getInputFilePath("freeenergy/" + name + "/topol.top");
183     groFileName_ = gmx::test::TestFileManager::getInputFilePath("freeenergy/" + name + "/conf.gro");
184     mdpFileName_ =
185             gmx::test::TestFileManager::getInputFilePath("freeenergy/" + name + "/grompp.mdp");
186 }
187
188 int SimulationRunner::callGromppOnThisRank(const CommandLine& callerRef)
189 {
190     std::string mdpInputFileName;
191     if (mdpSource_ == SimulationRunnerMdpSource::File)
192     {
193         mdpInputFileName = mdpFileName_;
194     }
195     else
196     {
197         mdpInputFileName = fileManager_.getTemporaryFilePath("input.mdp");
198         gmx::TextWriter::writeFileFromString(mdpInputFileName, mdpInputContents_);
199     }
200
201     CommandLine caller;
202     caller.append("grompp");
203     caller.merge(callerRef);
204     caller.addOption("-f", mdpInputFileName);
205     if (!ndxFileName_.empty())
206     {
207         caller.addOption("-n", ndxFileName_);
208     }
209     caller.addOption("-p", topFileName_);
210     caller.addOption("-c", groFileName_);
211     caller.addOption("-r", groFileName_);
212
213     caller.addOption("-po", mdpOutputFileName_);
214     caller.addOption("-o", tprFileName_);
215
216     return gmx_grompp(caller.argc(), caller.argv());
217 }
218
219 int SimulationRunner::callGromppOnThisRank()
220 {
221     return callGromppOnThisRank(CommandLine());
222 }
223
224 int SimulationRunner::callGrompp(const CommandLine& callerRef)
225 {
226     int returnValue = 0;
227 #if GMX_LIB_MPI
228     // When compiled with external MPI, we're trying to run mdrun with
229     // MPI, but we need to make sure that we only do grompp on one
230     // rank
231     if (0 == gmx_node_rank())
232 #endif
233     {
234         returnValue = callGromppOnThisRank(callerRef);
235     }
236 #if GMX_LIB_MPI
237     // Make sure rank zero has written the .tpr file before other
238     // ranks try to read it. Thread-MPI and serial do this just fine
239     // on their own.
240     MPI_Barrier(MdrunTestFixtureBase::communicator_);
241 #endif
242     return returnValue;
243 }
244
245 int SimulationRunner::callGrompp()
246 {
247     return callGrompp(CommandLine());
248 }
249
250 int SimulationRunner::changeTprNsteps(int nsteps) const
251 {
252     CommandLine caller;
253     caller.append("convert-tpr");
254     caller.addOption("-nsteps", nsteps);
255     // Because the operation is to change the .tpr, we replace the
256     // file. TODO Do we need to delete an automatic backup?
257     caller.addOption("-s", tprFileName_);
258     caller.addOption("-o", tprFileName_);
259
260     return gmx::test::CommandLineTestHelper::runModuleFactory(&gmx::ConvertTprInfo::create, &caller);
261 }
262
263 int SimulationRunner::callNmeig() const
264 {
265     /* Conforming to style guide by not passing a non-const reference
266        to this function. Passing a non-const reference might make it
267        easier to write code that incorrectly re-uses callerRef after
268        the call to this function. */
269
270     CommandLine caller;
271     caller.append("nmeig");
272     caller.addOption("-s", tprFileName_);
273     caller.addOption("-f", mtxFileName_);
274     // Ignore the overall translation and rotation in the
275     // first six eigenvectors.
276     caller.addOption("-first", "7");
277     // No need to check more than a number of output values.
278     caller.addOption("-last", "50");
279     caller.addOption("-xvg", "none");
280
281     return gmx_nmeig(caller.argc(), caller.argv());
282 }
283
284 int SimulationRunner::callMdrun(const CommandLine& callerRef)
285 {
286     /* Conforming to style guide by not passing a non-const reference
287        to this function. Passing a non-const reference might make it
288        easier to write code that incorrectly re-uses callerRef after
289        the call to this function. */
290
291     CommandLine caller;
292     caller.append("mdrun");
293     caller.merge(callerRef);
294     caller.addOption("-s", tprFileName_);
295
296     caller.addOption("-g", logFileName_);
297     caller.addOption("-e", edrFileName_);
298     caller.addOption("-mtx", mtxFileName_);
299     caller.addOption("-o", fullPrecisionTrajectoryFileName_);
300     caller.addOption("-x", reducedPrecisionTrajectoryFileName_);
301     if (!dhdlFileName_.empty())
302     {
303         caller.addOption("-dhdl", dhdlFileName_);
304     }
305
306     caller.addOption("-deffnm", fileManager_.getTemporaryFilePath("state"));
307
308     if (nsteps_ > -2)
309     {
310         caller.addOption("-nsteps", nsteps_);
311     }
312
313 #if GMX_THREAD_MPI
314     caller.addOption("-ntmpi", getNumberOfTestMpiRanks());
315 #endif
316
317 #if GMX_OPENMP
318     caller.addOption("-ntomp", g_numOpenMPThreads);
319 #endif
320
321     return gmx_mdrun(MdrunTestFixtureBase::communicator_,
322                      *MdrunTestFixtureBase::hwinfo_,
323                      caller.argc(),
324                      caller.argv());
325 }
326
327 int SimulationRunner::callMdrun()
328 {
329     return callMdrun(CommandLine());
330 }
331
332 // ====
333
334 // static
335 // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
336 MPI_Comm MdrunTestFixtureBase::communicator_ = MPI_COMM_NULL;
337 // static
338 // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
339 std::unique_ptr<gmx_hw_info_t> MdrunTestFixtureBase::hwinfo_;
340
341 // static
342 void MdrunTestFixtureBase::SetUpTestCase()
343 {
344     communicator_ = MPI_COMM_WORLD;
345     auto newHwinfo =
346             gmx_detect_hardware(PhysicalNodeCommunicator{ communicator_, gmx_physicalnode_id_hash() });
347     std::swap(hwinfo_, newHwinfo);
348 }
349
350 // static
351 void MdrunTestFixtureBase::TearDownTestCase()
352 {
353     hwinfo_.reset(nullptr);
354 }
355
356 MdrunTestFixtureBase::MdrunTestFixtureBase()
357 {
358 #if GMX_LIB_MPI
359     GMX_RELEASE_ASSERT(gmx_mpi_initialized(), "MPI system not initialized for mdrun tests");
360 #endif
361 }
362
363 MdrunTestFixtureBase::~MdrunTestFixtureBase() {}
364
365 // ====
366
367 MdrunTestFixture::MdrunTestFixture() : runner_(&fileManager_) {}
368
369 MdrunTestFixture::~MdrunTestFixture()
370 {
371 #if GMX_LIB_MPI
372     // fileManager_ should only clean up after all the ranks are done.
373     MPI_Barrier(MdrunTestFixtureBase::communicator_);
374 #endif
375 }
376
377 } // namespace test
378 } // namespace gmx