eb4d9d72a88eaa04dad4679f67b672a205c8b849
[alexxy/gromacs.git] / src / programs / mdrun / tests / energyreader.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
36 /*! \internal \file
37  * \brief Implementions of related classes for tests that want to
38  * inspect energies produced by mdrun.
39  *
40  * \author Mark Abraham <mark.j.abraham@gmail.com>
41  * \ingroup module_mdrun_integration_tests
42  */
43 #include "gmxpre.h"
44
45 #include "energyreader.h"
46
47 #include <algorithm>
48 #include <map>
49 #include <memory>
50 #include <string>
51 #include <vector>
52
53 #include "gromacs/compat/make_unique.h"
54 #include "gromacs/fileio/enxio.h"
55 #include "gromacs/trajectory/energyframe.h"
56 #include "gromacs/utility/exceptions.h"
57 #include "gromacs/utility/stringutil.h"
58
59 #include "testutils/testasserts.h"
60
61 namespace gmx
62 {
63 namespace test
64 {
65
66 EnergyFrameReaderPtr
67 openEnergyFileToReadFields(const std::string              &filename,
68                            const std::vector<std::string> &namesOfRequiredEnergyFields)
69 {
70     ener_file_ptr energyFile(open_enx(filename.c_str(), "r"));
71
72     if (!energyFile)
73     {
74         GMX_THROW(FileIOError("Could not open energy file " + filename + " for reading"));
75     }
76
77     /* Read in the names of energy fields used in this file. The
78      * resulting data structure would leak if an exception was thrown,
79      * so transfer the contents that we actually need to a map we can
80      * keep.
81      *
82      * TODO Technically, the insertions into the map could throw
83      * std::bad_alloc and we could leak memory allocated by
84      * do_enxnms(), but there's nothing we can do about this right
85      * now. */
86     std::map<std::string, int> indicesOfEnergyFields;
87     {
88         int          numEnergyTerms;
89         gmx_enxnm_t *energyNames = nullptr;
90         do_enxnms(energyFile.get(), &numEnergyTerms, &energyNames);
91         for (int i = 0; i != numEnergyTerms; ++i)
92         {
93             const char *name           = energyNames[i].name;
94             auto        requiredEnergy = std::find_if(std::begin(namesOfRequiredEnergyFields),
95                                                       std::end(namesOfRequiredEnergyFields),
96                                                       [name](const std::string &n){
97                                                           return name == n;
98                                                       });
99             if (requiredEnergy != namesOfRequiredEnergyFields.end())
100             {
101                 indicesOfEnergyFields[name] = i;
102             }
103         }
104         // Clean up old data structures
105         free_enxnms(numEnergyTerms, energyNames);
106     }
107
108     // Throw if we failed to find the fields we need
109     if (indicesOfEnergyFields.size() != namesOfRequiredEnergyFields.size())
110     {
111         std::string requiredEnergiesNotFound = "Did not find the following required energies in mdrun output:\n";
112         for (auto &name : namesOfRequiredEnergyFields)
113         {
114             auto possibleIndex = indicesOfEnergyFields.find(name);
115             if (possibleIndex == indicesOfEnergyFields.end())
116             {
117                 requiredEnergiesNotFound += name + "\n";
118             }
119         }
120         GMX_THROW(APIError(requiredEnergiesNotFound));
121     }
122
123     return EnergyFrameReaderPtr(compat::make_unique<EnergyFrameReader>(indicesOfEnergyFields,
124                                                                        energyFile.release()));
125 }
126
127 //! Helper function to obtain resources
128 static t_enxframe *make_enxframe()
129 {
130     t_enxframe *frame;
131
132     snew(frame, 1);
133     init_enxframe(frame);
134
135     return frame;
136 }
137
138 //! Helper function to clean up resources
139 void done_enxframe(t_enxframe *fr)
140 {
141     // Free the contents, then the pointer itself
142     free_enxframe(fr);
143     sfree(fr);
144 }
145
146 // === EnergyFrameReader ===
147
148 EnergyFrameReader::EnergyFrameReader(const std::map<std::string, int> &indicesOfEnergyFields,
149                                      ener_file *energyFile)
150     : indicesOfEnergyFields_(indicesOfEnergyFields),
151       energyFileGuard_(energyFile),
152       enxframeGuard_(make_enxframe()),
153       haveProbedForNextFrame_(false),
154       nextFrameExists_(false)
155 {
156 }
157
158 bool
159 EnergyFrameReader::readNextFrame()
160 {
161     if (haveProbedForNextFrame_)
162     {
163         if (nextFrameExists_)
164         {
165             GMX_THROW(APIError("This frame has already been probed for, it should be used before probing again."));
166         }
167         else
168         {
169             GMX_THROW(APIError("This frame has already been probed for, it doesn't exist, so there should not be subsequent attempts to probe for it."));
170         }
171     }
172     haveProbedForNextFrame_ = true;
173     // If there's a next frame, read it into enxframe_, and report the result.
174     return nextFrameExists_ = do_enx(energyFileGuard_.get(), enxframeGuard_.get());
175 }
176
177 EnergyFrame
178 EnergyFrameReader::frame()
179 {
180     if (!haveProbedForNextFrame_)
181     {
182         readNextFrame();
183     }
184     if (!nextFrameExists_)
185     {
186         GMX_THROW(APIError("There is no next frame, so there should have been no attempt to use the data, e.g. by reacting to a call to readNextFrame()."));
187     }
188
189     // Prepare for reading future frames
190     haveProbedForNextFrame_ = false;
191     nextFrameExists_        = false;
192
193     // The probe filled enxframe_ with new data, so now we use that data to fill energyFrame
194     return EnergyFrame(*enxframeGuard_.get(), indicesOfEnergyFields_);
195 }
196
197 }  // namespace test
198 }  // namespace gmx