Moved generic simulationdatabase code to testutils.
[gromacs.git] / src / programs / mdrun / tests / rerun.cpp
blobd384a151a64a46656d9672ed82e014a972b56832
1 /*
2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2013,2014,2015,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.
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.
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.
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.
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.
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.
36 /*! \internal \file
37 * \brief
38 * Tests for the mdrun -rerun functionality
40 * \author Mark Abraham <mark.j.abraham@gmail.com>
41 * \ingroup module_mdrun_integration_tests
43 #include "gmxpre.h"
45 #include "config.h"
47 #include <map>
48 #include <memory>
49 #include <string>
50 #include <tuple>
51 #include <vector>
53 #include <gtest/gtest.h>
55 #include "gromacs/compat/make_unique.h"
56 #include "gromacs/options/filenameoption.h"
57 #include "gromacs/topology/idef.h"
58 #include "gromacs/topology/ifunc.h"
59 #include "gromacs/trajectory/energyframe.h"
60 #include "gromacs/trajectory/trajectoryframe.h"
61 #include "gromacs/utility/stringutil.h"
63 #include "testutils/mpitest.h"
64 #include "testutils/simulationdatabase.h"
65 #include "testutils/testasserts.h"
67 #include "energycomparison.h"
68 #include "energyreader.h"
69 #include "mdruncomparison.h"
70 #include "moduletest.h"
71 #include "trajectorycomparison.h"
72 #include "trajectoryreader.h"
74 namespace gmx
76 namespace test
78 namespace
81 //! Functor for comparing reference and test frames on particular energies to match.
82 class EnergyComparator
84 public:
85 //! Constructor
86 EnergyComparator(const EnergyTolerances &energiesToMatch)
87 : energiesToMatch_(energiesToMatch) {}
88 //! The functor method.
89 void operator()(const EnergyFrame &reference, const EnergyFrame &test)
91 compareEnergyFrames(reference, test, energiesToMatch_);
93 //! Container of the energies to match and the tolerance required.
94 const EnergyTolerances &energiesToMatch_;
97 //! Run grompp for a normal mdrun, the run, and its rerun.
98 void executeRerunTest(TestFileManager *fileManager,
99 SimulationRunner *runner,
100 const std::string &simulationName,
101 int maxWarningsTolerated,
102 const MdpFieldValues &mdpFieldValues,
103 const EnergyTolerances &energiesToMatch)
105 // TODO At some point we should also test PME-only ranks.
106 int numRanksAvailable = getNumberOfTestMpiRanks();
107 if (!isNumberOfPpRanksSupported(simulationName, numRanksAvailable))
109 fprintf(stdout, "Test system '%s' cannot run with %d ranks.\n"
110 "The supported numbers are: %s\n",
111 simulationName.c_str(), numRanksAvailable,
112 reportNumbersOfPpRanksSupported(simulationName).c_str());
113 return;
116 auto normalRunTrajectoryFileName = fileManager->getTemporaryFilePath("normal.trr");
117 auto normalRunEdrFileName = fileManager->getTemporaryFilePath("normal.edr");
118 auto rerunTrajectoryFileName = fileManager->getTemporaryFilePath("rerun.trr");
119 auto rerunEdrFileName = fileManager->getTemporaryFilePath("rerun.edr");
121 // prepare the .tpr file
123 // TODO evolve grompp to report the number of warnings issued, so
124 // tests always expect the right number.
125 CommandLine caller;
126 caller.append("grompp");
127 caller.addOption("-maxwarn", maxWarningsTolerated);
128 runner->useTopGroAndNdxFromDatabase(simulationName);
129 runner->useStringAsMdpFile(prepareMdpFileContents(mdpFieldValues));
130 EXPECT_EQ(0, runner->callGrompp(caller));
133 // do the normal mdrun
135 runner->fullPrecisionTrajectoryFileName_ = normalRunTrajectoryFileName;
136 runner->edrFileName_ = normalRunEdrFileName;
137 CommandLine normalRunCaller;
138 normalRunCaller.append("mdrun");
139 ASSERT_EQ(0, runner->callMdrun(normalRunCaller));
142 // do a rerun on the .trr just produced
144 runner->fullPrecisionTrajectoryFileName_ = rerunTrajectoryFileName;
145 runner->edrFileName_ = rerunEdrFileName;
146 CommandLine rerunCaller;
147 rerunCaller.append("mdrun");
148 rerunCaller.addOption("-rerun", normalRunTrajectoryFileName);
149 ASSERT_EQ(0, runner->callMdrun(rerunCaller));
152 // Build the functor that will compare reference and test
153 // energy frames on the chosen energy fields.
155 // TODO It would be less code if we used a lambda for this, but either
156 // clang 3.4 or libstdc++ 5.2.1 have an issue with capturing a
157 // std::unordered_map
158 EnergyComparator energyComparator(energiesToMatch);
159 // Build the manager that will present matching pairs of frames to compare.
161 // TODO Here is an unnecessary copy of keys (ie. the energy field
162 // names), for convenience. In the future, use a range.
163 auto namesOfEnergiesToMatch = getKeys(energiesToMatch);
164 FramePairManager<EnergyFrameReader, EnergyFrame>
165 energyManager(openEnergyFileToReadFields(normalRunEdrFileName, namesOfEnergiesToMatch),
166 openEnergyFileToReadFields(rerunEdrFileName, namesOfEnergiesToMatch));
167 // Compare the energy frames.
168 energyManager.compareAllFramePairs(energyComparator);
170 // Specify how trajectory frame matching must work.
171 TrajectoryFrameMatchSettings trajectoryMatchSettings {
172 true, true, true, true, false, true
174 /* Specify the default expected tolerances for trajectory
175 * components for all simulation systems. */
176 TrajectoryTolerances trajectoryTolerances {
177 defaultRealTolerance(), // box
178 relativeToleranceAsFloatingPoint(1.0, 1.0e-3), // positions
179 defaultRealTolerance(), // velocities - unused for rerun
180 relativeToleranceAsFloatingPoint(100.0, GMX_DOUBLE ? 1.0e-7 : 1.0e-5) // forces
183 // Build the functor that will compare reference and test
184 // trajectory frames in the chosen way.
185 auto trajectoryComparator = [&trajectoryMatchSettings, &trajectoryTolerances](const TrajectoryFrame &reference, const TrajectoryFrame &test)
187 compareTrajectoryFrames(reference, test, trajectoryMatchSettings, trajectoryTolerances);
189 // Build the manager that will present matching pairs of frames to compare
190 FramePairManager<TrajectoryFrameReader, TrajectoryFrame>
191 trajectoryManager(compat::make_unique<TrajectoryFrameReader>(normalRunTrajectoryFileName),
192 compat::make_unique<TrajectoryFrameReader>(rerunTrajectoryFileName));
193 // Compare the trajectory frames.
194 trajectoryManager.compareAllFramePairs(trajectoryComparator);
197 /*! \brief Test fixture base for mdrun -rerun
199 * This test ensures mdrun can run a simulation, writing a trajectory
200 * and matching energies, and reproduce the same energies from a rerun
201 * to within a tight tolerance. It says nothing about whether a rerun
202 * can reproduce energies from a trajectory generated with older code,
203 * since that is not a useful property. Whether mdrun produced correct
204 * energies then and now needs different kinds of testing, but if
205 * true, this test ensures the rerun has the expected property.
207 * The limitations of mdrun and its output means that reproducing the
208 * same energies is currently only meaningful for integration without
209 * thermostats or barostats, however the present form of the test
210 * infrastructure has in-principle support for such, if that is ever
211 * needed/useful.
213 * We should also not compare pressure, because with constraints the
214 * non-search steps need a much larger tolerance, and per Redmine 1868
215 * we should stop computing pressure in reruns anyway.
217 * Similarly, per 1868, in the present implementation the kinetic
218 * energy quantities are not generally reproducible, either.
220 * The choices for tolerance are arbitrary but sufficient. Rerun does
221 * pair search every frame, so it cannot in general exactly reproduce
222 * quantities from a normal run, because the accumulation order
223 * differs. (Nor does it reproduce pair-search frames exactly,
224 * either). */
225 class MdrunRerunTest : public MdrunTestFixture,
226 public ::testing::WithParamInterface <
227 std::tuple < std::string, std::string>>
231 TEST_P(MdrunRerunTest, WithinTolerances)
233 auto params = GetParam();
234 auto simulationName = std::get<0>(params);
235 auto integrator = std::get<1>(params);
236 SCOPED_TRACE(formatString("Comparing normal and rerun of simulation '%s' "
237 "with integrator '%s'",
238 simulationName.c_str(), integrator.c_str()));
240 auto mdpFieldValues = prepareMdpFieldValues(simulationName.c_str(),
241 integrator.c_str(),
242 "no", "no");
244 // bd is much less reproducible in a rerun than the other integrators
245 const int toleranceScaleFactor = (integrator == "bd") ? 2 : 1;
246 EnergyTolerances energiesToMatch
249 interaction_function[F_EPOT].longname,
250 relativeToleranceAsPrecisionDependentUlp(10.0, 24 * toleranceScaleFactor, 40 * toleranceScaleFactor)
254 int numWarningsToTolerate = 0;
255 executeRerunTest(&fileManager_, &runner_,
256 simulationName, numWarningsToTolerate, mdpFieldValues,
257 energiesToMatch);
260 // TODO The time for OpenCL kernel compilation means these tests time
261 // out. Once that compilation is cached for the whole process, these
262 // tests can run in such configurations.
263 #if GMX_GPU != GMX_GPU_OPENCL
264 INSTANTIATE_TEST_CASE_P(NormalMdrunIsReproduced, MdrunRerunTest,
265 ::testing::Combine(::testing::Values("argon12", "spc5", "alanine_vsite_vacuo"),
266 ::testing::Values("md", "md-vv", "bd", "sd")));
267 #else
268 INSTANTIATE_TEST_CASE_P(DISABLED_NormalMdrunIsReproduced, MdrunRerunTest,
269 ::testing::Combine(::testing::Values("argon12", "spc5", "alanine_vsite_vacuo"),
270 ::testing::Values("md", "md-vv", "bd", "sd")));
271 #endif
273 class MdrunRerunFreeEnergyTest : public MdrunTestFixture,
274 public ::testing::WithParamInterface <
275 std::tuple < std::string, std::string, int>>
279 TEST_P(MdrunRerunFreeEnergyTest, WithinTolerances)
281 auto params = GetParam();
282 auto simulationName = std::get<0>(params);
283 auto integrator = std::get<1>(params);
284 auto initLambdaState = std::get<2>(params);
285 SCOPED_TRACE(formatString("Comparing normal and rerun of simulation '%s' "
286 "with integrator '%s' for initial lambda state %d",
287 simulationName.c_str(), integrator.c_str(), initLambdaState));
289 auto mdpFieldValues = prepareMdpFieldValues(simulationName.c_str(),
290 integrator.c_str(),
291 "no", "no");
292 mdpFieldValues["other"] += formatString("\ninit-lambda-state %d", initLambdaState);
294 EnergyTolerances energiesToMatch
297 interaction_function[F_EPOT].longname, relativeToleranceAsPrecisionDependentUlp(10.0, 24, 32)
300 interaction_function[F_DVDL_COUL].longname, relativeToleranceAsPrecisionDependentUlp(1.0, 8, 8)
303 interaction_function[F_DVDL_VDW].longname, relativeToleranceAsPrecisionDependentUlp(1.0, 8, 8)
306 interaction_function[F_DVDL_BONDED].longname, relativeToleranceAsPrecisionDependentUlp(1.0, 8, 8)
309 interaction_function[F_DVDL_RESTRAINT].longname, relativeToleranceAsPrecisionDependentUlp(1.0, 8, 8)
313 // The md integrator triggers a warning for nearly decoupled
314 // states, which we need to suppress. TODO sometimes?
315 int numWarningsToTolerate = (integrator == "md") ? 1 : 0;
316 executeRerunTest(&fileManager_, &runner_,
317 simulationName, numWarningsToTolerate, mdpFieldValues,
318 energiesToMatch);
321 // TODO The time for OpenCL kernel compilation means these tests time
322 // out. Once that compilation is cached for the whole process, these
323 // tests can run in such configurations.
324 #if GMX_GPU != GMX_GPU_OPENCL
325 INSTANTIATE_TEST_CASE_P(MdrunIsReproduced, MdrunRerunFreeEnergyTest,
326 ::testing::Combine(::testing::Values("nonanol_vacuo"),
327 ::testing::Values("md", "md-vv", "sd"),
328 ::testing::Range(0, 11)));
329 #else
330 INSTANTIATE_TEST_CASE_P(DISABLED_MdrunIsReproduced, MdrunRerunFreeEnergyTest,
331 ::testing::Combine(::testing::Values("nonanol_vacuo"),
332 ::testing::Values("md", "md-vv", "sd"),
333 ::testing::Range(0, 11)));
334 #endif
336 } // namespace
337 } // namespace test
338 } // namespace gmx