Apply clang-format to source tree
[alexxy/gromacs.git] / src / gromacs / utility / keyvaluetree.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2016,2017,2018,2019, 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 #include "gmxpre.h"
36
37 #include "keyvaluetree.h"
38
39 #include <string>
40 #include <vector>
41
42 #include "gromacs/utility/compare.h"
43 #include "gromacs/utility/gmxassert.h"
44 #include "gromacs/utility/strconvert.h"
45 #include "gromacs/utility/stringutil.h"
46 #include "gromacs/utility/textwriter.h"
47
48 namespace gmx
49 {
50
51 namespace
52 {
53
54 //! Helper function to split a KeyValueTreePath to its components
55 std::vector<std::string> splitPathElements(const std::string& path)
56 {
57     GMX_ASSERT(!path.empty() && path[0] == '/', "Paths to KeyValueTree should start with '/'");
58     return splitDelimitedString(path.substr(1), '/');
59 }
60
61 } // namespace
62
63 /********************************************************************
64  * KeyValueTreePath
65  */
66
67 KeyValueTreePath::KeyValueTreePath(const char* path) : path_(splitPathElements(path)) {}
68
69 KeyValueTreePath::KeyValueTreePath(const std::string& path) : path_(splitPathElements(path)) {}
70
71 std::string KeyValueTreePath::toString() const
72 {
73     return "/" + joinStrings(path_, "/");
74 }
75
76 /********************************************************************
77  * KeyValueTreeObject
78  */
79
80 bool KeyValueTreeObject::hasDistinctProperties(const KeyValueTreeObject& obj) const
81 {
82     for (const auto& prop : obj.values_)
83     {
84         if (keyExists(prop.key()))
85         {
86             GMX_RELEASE_ASSERT(!prop.value().isArray(), "Comparison of arrays not implemented");
87             if (prop.value().isObject() && valueMap_.at(prop.key()).isObject())
88             {
89                 return valueMap_.at(prop.key()).asObject().hasDistinctProperties(prop.value().asObject());
90             }
91             return false;
92         }
93     }
94     return true;
95 }
96
97 /********************************************************************
98  * Key value tree dump
99  */
100
101 //! \cond libapi
102 void dumpKeyValueTree(TextWriter* writer, const KeyValueTreeObject& tree)
103 {
104     for (const auto& prop : tree.properties())
105     {
106         const auto& value = prop.value();
107         if (value.isObject())
108         {
109             writer->writeString(prop.key());
110             writer->writeLine(":");
111             int oldIndent = writer->wrapperSettings().indent();
112             writer->wrapperSettings().setIndent(oldIndent + 2);
113             dumpKeyValueTree(writer, value.asObject());
114             writer->wrapperSettings().setIndent(oldIndent);
115         }
116         else
117         {
118             int indent = writer->wrapperSettings().indent();
119             writer->writeString(formatString("%*s", -(33 - indent), prop.key().c_str()));
120             writer->writeString(" = ");
121             if (value.isArray())
122             {
123                 writer->writeString("[");
124                 for (const auto& elem : value.asArray().values())
125                 {
126                     GMX_RELEASE_ASSERT(!elem.isObject() && !elem.isArray(),
127                                        "Arrays of objects not currently implemented");
128                     writer->writeString(" ");
129                     writer->writeString(simpleValueToString(elem));
130                 }
131                 writer->writeString(" ]");
132             }
133             else
134             {
135                 writer->writeString(simpleValueToString(value));
136             }
137             writer->writeLine();
138         }
139     }
140 }
141 //! \endcond
142
143 /********************************************************************
144  * Key value tree comparison
145  */
146
147 namespace
148 {
149
150 class CompareHelper
151 {
152 public:
153     CompareHelper(TextWriter* writer, real ftol, real abstol) :
154         writer_(writer),
155         ftol_(ftol),
156         abstol_(abstol)
157     {
158     }
159
160     void compareObjects(const KeyValueTreeObject& obj1, const KeyValueTreeObject& obj2)
161     {
162         for (const auto& prop1 : obj1.properties())
163         {
164             currentPath_.append(prop1.key());
165             if (obj2.keyExists(prop1.key()))
166             {
167                 compareValues(prop1.value(), obj2[prop1.key()]);
168             }
169             else
170             {
171                 handleMissingKeyInSecondObject(prop1.value());
172             }
173             currentPath_.pop_back();
174         }
175         for (const auto& prop2 : obj2.properties())
176         {
177             currentPath_.append(prop2.key());
178             if (!obj1.keyExists(prop2.key()))
179             {
180                 handleMissingKeyInFirstObject(prop2.value());
181             }
182             currentPath_.pop_back();
183         }
184     }
185
186 private:
187     void compareValues(const KeyValueTreeValue& value1, const KeyValueTreeValue& value2)
188     {
189         if (value1.type() == value2.type())
190         {
191             if (value1.isObject())
192             {
193                 compareObjects(value1.asObject(), value2.asObject());
194             }
195             else if (value1.isArray())
196             {
197                 GMX_RELEASE_ASSERT(false, "Array comparison not implemented");
198             }
199             else if (!areSimpleValuesOfSameTypeEqual(value1, value2))
200             {
201                 writer_->writeString(currentPath_.toString());
202                 writer_->writeLine(formatString(" (%s - %s)", simpleValueToString(value1).c_str(),
203                                                 simpleValueToString(value2).c_str()));
204             }
205         }
206         else if ((value1.isType<double>() && value2.isType<float>())
207                  || (value1.isType<float>() && value2.isType<double>()))
208         {
209             const bool  firstIsDouble = value1.isType<double>();
210             const float v1 = firstIsDouble ? value1.cast<double>() : value1.cast<float>();
211             const float v2 = firstIsDouble ? value2.cast<float>() : value2.cast<double>();
212             if (!equal_float(v1, v2, ftol_, abstol_))
213             {
214                 writer_->writeString(currentPath_.toString());
215                 writer_->writeLine(formatString(" (%e - %e)", v1, v2));
216             }
217         }
218         else
219         {
220             handleMismatchingTypes(value1, value2);
221         }
222     }
223
224     bool areSimpleValuesOfSameTypeEqual(const KeyValueTreeValue& value1, const KeyValueTreeValue& value2)
225     {
226         GMX_ASSERT(value1.type() == value2.type(), "Caller should ensure that types are equal");
227         if (value1.isType<bool>())
228         {
229             return value1.cast<bool>() == value2.cast<bool>();
230         }
231         else if (value1.isType<int>())
232         {
233             return value1.cast<int>() == value2.cast<int>();
234         }
235         else if (value1.isType<int64_t>())
236         {
237             return value1.cast<int64_t>() == value2.cast<int64_t>();
238         }
239         else if (value1.isType<double>())
240         {
241             return equal_double(value1.cast<double>(), value2.cast<double>(), ftol_, abstol_);
242         }
243         else if (value1.isType<float>())
244         {
245             return equal_float(value1.cast<float>(), value2.cast<float>(), ftol_, abstol_);
246         }
247         else if (value1.isType<std::string>())
248         {
249             return value1.cast<std::string>() == value2.cast<std::string>();
250         }
251         else
252         {
253             GMX_RELEASE_ASSERT(false, "Unknown value type");
254             return false;
255         }
256     }
257
258     void handleMismatchingTypes(const KeyValueTreeValue& /* value1 */,
259                                 const KeyValueTreeValue& /* value2 */)
260     {
261         writer_->writeString(currentPath_.toString());
262         writer_->writeString(" type mismatch");
263     }
264
265     void handleMissingKeyInFirstObject(const KeyValueTreeValue& value)
266     {
267         const std::string message = formatString("%s (missing - %s)", currentPath_.toString().c_str(),
268                                                  formatValueForMissingMessage(value).c_str());
269         writer_->writeLine(message);
270     }
271     void handleMissingKeyInSecondObject(const KeyValueTreeValue& value)
272     {
273         const std::string message = formatString("%s (%s - missing)", currentPath_.toString().c_str(),
274                                                  formatValueForMissingMessage(value).c_str());
275         writer_->writeLine(message);
276     }
277
278     std::string formatValueForMissingMessage(const KeyValueTreeValue& value)
279     {
280         if (value.isObject() || value.isArray())
281         {
282             return "present";
283         }
284         return simpleValueToString(value);
285     }
286
287     KeyValueTreePath currentPath_;
288     TextWriter*      writer_;
289     real             ftol_;
290     real             abstol_;
291 };
292
293 } // namespace
294
295 //! \cond libapi
296 void compareKeyValueTrees(TextWriter*               writer,
297                           const KeyValueTreeObject& tree1,
298                           const KeyValueTreeObject& tree2,
299                           real                      ftol,
300                           real                      abstol)
301 {
302     CompareHelper helper(writer, ftol, abstol);
303     helper.compareObjects(tree1, tree2);
304 }
305 //! \endcond
306
307 } // namespace gmx