Fix copyright notices for new C++ code.
[alexxy/gromacs.git] / src / gromacs / options / basicoptions.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2010,2011,2012, by the GROMACS development team, led by
5  * David van der Spoel, Berk Hess, Erik Lindahl, and including many
6  * others, as listed in the AUTHORS file in the top-level source
7  * 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  * Implements classes in basicoptions.h and basicoptionstorage.h.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_options
41  */
42 #include "basicoptions.h"
43 #include "basicoptionstorage.h"
44
45 #include <cerrno>
46 #include <cstdio>
47 #include <cstdlib>
48
49 #include <limits>
50 #include <string>
51 #include <vector>
52
53 #include "gromacs/utility/exceptions.h"
54 #include "gromacs/utility/stringutil.h"
55
56 namespace
57 {
58
59 /*! \brief
60  * Expands a single value to a vector by copying the value.
61  *
62  * \tparam        ValueType  Type of values to process.
63  * \param[in]     length     Length of the resulting vector.
64  * \param[in,out] values     Values to process.
65  * \throws   std::bad_alloc    if out of memory.
66  * \throws   InvalidInputError if \p values has an invalid number of values.
67  *
68  * \p values should have 0, 1, or \p length values.
69  * If \p values has 1 value, it is expanded such that it has \p length
70  * identical values.  In other valid cases, nothing is done.
71  */
72 template <typename ValueType>
73 void expandVector(size_t length, std::vector<ValueType> *values)
74 {
75     if (length > 0 && values->size() > 0 && values->size() != length)
76     {
77         if (values->size() != 1)
78         {
79             GMX_THROW(gmx::InvalidInputError(gmx::formatString(
80                                                      "Expected 1 or %d values, got %d", length, values->size())));
81         }
82         const ValueType &value = (*values)[0];
83         values->resize(length, value);
84     }
85 }
86
87 } // namespace
88
89 namespace gmx
90 {
91
92 /********************************************************************
93  * BooleanOptionStorage
94  */
95
96 std::string BooleanOptionStorage::formatSingleValue(const bool &value) const
97 {
98     return value ? "yes" : "no";
99 }
100
101 void BooleanOptionStorage::convertValue(const std::string &value)
102 {
103     // TODO: Case-independence
104     if (value == "1" || value == "yes" || value == "true")
105     {
106         addValue(true);
107         return;
108     }
109     else if (value == "0" || value == "no" || value == "false")
110     {
111         addValue(false);
112         return;
113     }
114     GMX_THROW(InvalidInputError("Invalid value: '" + value + "'; supported values are: 1, 0, yes, no, true, false"));
115 }
116
117 /********************************************************************
118  * BooleanOptionInfo
119  */
120
121 BooleanOptionInfo::BooleanOptionInfo(BooleanOptionStorage *option)
122     : OptionInfo(option)
123 {
124 }
125
126 /********************************************************************
127  * BooleanOption
128  */
129
130 AbstractOptionStoragePointer BooleanOption::createStorage() const
131 {
132     return AbstractOptionStoragePointer(new BooleanOptionStorage(*this));
133 }
134
135
136 /********************************************************************
137  * IntegerOptionStorage
138  */
139
140 std::string IntegerOptionStorage::formatSingleValue(const int &value) const
141 {
142     return formatString("%d", value);
143 }
144
145 void IntegerOptionStorage::convertValue(const std::string &value)
146 {
147     const char *ptr = value.c_str();
148     char       *endptr;
149     errno = 0;
150     long int    ival = std::strtol(ptr, &endptr, 10);
151     if (errno == ERANGE
152         || ival < std::numeric_limits<int>::min()
153         || ival > std::numeric_limits<int>::max())
154     {
155         GMX_THROW(InvalidInputError("Invalid value: '" + value
156                                     + "'; it causes an integer overflow"));
157     }
158     if (*ptr == '\0' || *endptr != '\0')
159     {
160         GMX_THROW(InvalidInputError("Invalid value: '" + value
161                                     + "'; expected an integer"));
162     }
163     addValue(ival);
164 }
165
166 void IntegerOptionStorage::processSetValues(ValueList *values)
167 {
168     if (isVector())
169     {
170         expandVector(maxValueCount(), values);
171     }
172 }
173
174 /********************************************************************
175  * IntegerOptionInfo
176  */
177
178 IntegerOptionInfo::IntegerOptionInfo(IntegerOptionStorage *option)
179     : OptionInfo(option)
180 {
181 }
182
183 /********************************************************************
184  * IntegerOption
185  */
186
187 AbstractOptionStoragePointer IntegerOption::createStorage() const
188 {
189     return AbstractOptionStoragePointer(new IntegerOptionStorage(*this));
190 }
191
192
193 /********************************************************************
194  * DoubleOptionStorage
195  */
196
197 DoubleOptionStorage::DoubleOptionStorage(const DoubleOption &settings)
198     : MyBase(settings), info_(this), bTime_(settings.bTime_), factor_(1.0)
199 {
200 }
201
202 const char *DoubleOptionStorage::typeString() const
203 {
204     return isVector() ? "vector" : (isTime() ? "time" : "double");
205 }
206
207 std::string DoubleOptionStorage::formatSingleValue(const double &value) const
208 {
209     return formatString("%g", value / factor_);
210 }
211
212 void DoubleOptionStorage::convertValue(const std::string &value)
213 {
214     const char *ptr = value.c_str();
215     char       *endptr;
216     errno = 0;
217     double      dval = std::strtod(ptr, &endptr);
218     if (errno == ERANGE)
219     {
220         GMX_THROW(InvalidInputError("Invalid value: '" + value
221                                     + "'; it causes an overflow/underflow"));
222     }
223     if (*ptr == '\0' || *endptr != '\0')
224     {
225         GMX_THROW(InvalidInputError("Invalid value: '" + value
226                                     + "'; expected a number"));
227     }
228     addValue(dval * factor_);
229 }
230
231 void DoubleOptionStorage::processSetValues(ValueList *values)
232 {
233     if (isVector())
234     {
235         expandVector(maxValueCount(), values);
236     }
237 }
238
239 void DoubleOptionStorage::processAll()
240 {
241 }
242
243 void DoubleOptionStorage::setScaleFactor(double factor)
244 {
245     GMX_RELEASE_ASSERT(factor > 0.0, "Invalid scaling factor");
246     if (!hasFlag(efOption_HasDefaultValue))
247     {
248         double              scale = factor / factor_;
249         ValueList::iterator i;
250         for (i = values().begin(); i != values().end(); ++i)
251         {
252             (*i) *= scale;
253         }
254         refreshValues();
255     }
256     factor_ = factor;
257 }
258
259 /********************************************************************
260  * DoubleOptionInfo
261  */
262
263 DoubleOptionInfo::DoubleOptionInfo(DoubleOptionStorage *option)
264     : OptionInfo(option)
265 {
266 }
267
268 DoubleOptionStorage &DoubleOptionInfo::option()
269 {
270     return static_cast<DoubleOptionStorage &>(OptionInfo::option());
271 }
272
273 const DoubleOptionStorage &DoubleOptionInfo::option() const
274 {
275     return static_cast<const DoubleOptionStorage &>(OptionInfo::option());
276 }
277
278 bool DoubleOptionInfo::isTime() const
279 {
280     return option().isTime();
281 }
282
283 void DoubleOptionInfo::setScaleFactor(double factor)
284 {
285     option().setScaleFactor(factor);
286 }
287
288 /********************************************************************
289  * DoubleOption
290  */
291
292 AbstractOptionStoragePointer DoubleOption::createStorage() const
293 {
294     return AbstractOptionStoragePointer(new DoubleOptionStorage(*this));
295 }
296
297
298 /********************************************************************
299  * StringOptionStorage
300  */
301
302 StringOptionStorage::StringOptionStorage(const StringOption &settings)
303     : MyBase(settings), info_(this), enumIndexStore_(NULL)
304 {
305     if (settings.defaultEnumIndex_ >= 0 && settings.enumValues_ == NULL)
306     {
307         GMX_THROW(APIError("Cannot set default enum index without enum values"));
308     }
309     if (settings.enumIndexStore_ != NULL && settings.enumValues_ == NULL)
310     {
311         GMX_THROW(APIError("Cannot set enum index store without enum values"));
312     }
313     if (settings.enumIndexStore_ != NULL && settings.maxValueCount_ < 0)
314     {
315         GMX_THROW(APIError("Cannot set enum index store with arbitrary number of values"));
316     }
317     if (settings.enumValues_ != NULL)
318     {
319         enumIndexStore_ = settings.enumIndexStore_;
320         const std::string *defaultValue = settings.defaultValue();
321         int                match        = -1;
322         for (int i = 0; settings.enumValues_[i] != NULL; ++i)
323         {
324             if (defaultValue != NULL && settings.enumValues_[i] == *defaultValue)
325             {
326                 match = i;
327             }
328             allowed_.push_back(settings.enumValues_[i]);
329         }
330         if (defaultValue != NULL)
331         {
332             if (match < 0)
333             {
334                 GMX_THROW(APIError("Default value is not one of allowed values"));
335             }
336         }
337         if (settings.defaultEnumIndex_ >= 0)
338         {
339             if (settings.defaultEnumIndex_ >= static_cast<int>(allowed_.size()))
340             {
341                 GMX_THROW(APIError("Default enumeration index is out of range"));
342             }
343             if (defaultValue != NULL && *defaultValue != allowed_[settings.defaultEnumIndex_])
344             {
345                 GMX_THROW(APIError("Conflicting default values"));
346             }
347         }
348         // If there is no default value, match is still -1.
349         if (enumIndexStore_ != NULL)
350         {
351             *enumIndexStore_ = match;
352         }
353     }
354     if (settings.defaultEnumIndex_ >= 0)
355     {
356         clear();
357         addValue(allowed_[settings.defaultEnumIndex_]);
358         commitValues();
359     }
360 }
361
362 std::string StringOptionStorage::formatSingleValue(const std::string &value) const
363 {
364     return value;
365 }
366
367 void StringOptionStorage::convertValue(const std::string &value)
368 {
369     if (allowed_.size() == 0)
370     {
371         addValue(value);
372     }
373     else
374     {
375         ValueList::const_iterator  i;
376         ValueList::const_iterator  match = allowed_.end();
377         for (i = allowed_.begin(); i != allowed_.end(); ++i)
378         {
379             // TODO: Case independence.
380             if (i->find(value) == 0)
381             {
382                 if (match == allowed_.end() || i->size() < match->size())
383                 {
384                     match = i;
385                 }
386             }
387         }
388         if (match == allowed_.end())
389         {
390             GMX_THROW(InvalidInputError("Invalid value: " + value));
391         }
392         addValue(*match);
393     }
394 }
395
396 void StringOptionStorage::refreshValues()
397 {
398     MyBase::refreshValues();
399     if (enumIndexStore_ != NULL)
400     {
401         for (size_t i = 0; i < values().size(); ++i)
402         {
403             ValueList::const_iterator match =
404                 std::find(allowed_.begin(), allowed_.end(), values()[i]);
405             GMX_ASSERT(match != allowed_.end(),
406                        "Enum value not found (internal error)");
407             enumIndexStore_[i] = static_cast<int>(match - allowed_.begin());
408         }
409     }
410 }
411
412 /********************************************************************
413  * StringOptionInfo
414  */
415
416 StringOptionInfo::StringOptionInfo(StringOptionStorage *option)
417     : OptionInfo(option)
418 {
419 }
420
421 /********************************************************************
422  * StringOption
423  */
424
425 AbstractOptionStoragePointer StringOption::createStorage() const
426 {
427     return AbstractOptionStoragePointer(new StringOptionStorage(*this));
428 }
429
430 std::string StringOption::createDescription() const
431 {
432     std::string value(MyBase::createDescription());
433
434     if (enumValues_ != NULL)
435     {
436         value.append(": ");
437         for (int i = 0; enumValues_[i] != NULL; ++i)
438         {
439             value.append(enumValues_[i]);
440             if (enumValues_[i + 1] != NULL)
441             {
442                 value.append(enumValues_[i + 2] != NULL ? ", " : ", or ");
443             }
444         }
445     }
446     return value;
447 }
448
449 } // namespace gmx