Merge branch release-4-6
[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,2013,2014, 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 /*! \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/legacyheaders/string2.h"
54
55 #include "gromacs/utility/exceptions.h"
56 #include "gromacs/utility/stringutil.h"
57
58 namespace
59 {
60
61 /*! \brief
62  * Expands a single value to a vector by copying the value.
63  *
64  * \tparam        ValueType  Type of values to process.
65  * \param[in]     length     Length of the resulting vector.
66  * \param[in,out] values     Values to process.
67  * \throws   std::bad_alloc    if out of memory.
68  * \throws   InvalidInputError if \p values has an invalid number of values.
69  *
70  * \p values should have 0, 1, or \p length values.
71  * If \p values has 1 value, it is expanded such that it has \p length
72  * identical values.  In other valid cases, nothing is done.
73  */
74 template <typename ValueType>
75 void expandVector(size_t length, std::vector<ValueType> *values)
76 {
77     if (length > 0 && !values->empty() && values->size() != length)
78     {
79         if (values->size() != 1)
80         {
81             GMX_THROW(gmx::InvalidInputError(gmx::formatString(
82                                                      "Expected 1 or %d values, got %d", length, values->size())));
83         }
84         const ValueType &value = (*values)[0];
85         values->resize(length, value);
86     }
87 }
88
89 } // namespace
90
91 namespace gmx
92 {
93
94 /********************************************************************
95  * BooleanOptionStorage
96  */
97
98 std::string BooleanOptionStorage::formatSingleValue(const bool &value) const
99 {
100     return value ? "yes" : "no";
101 }
102
103 void BooleanOptionStorage::convertValue(const std::string &value)
104 {
105     // TODO: Case-independence
106     if (value == "1" || value == "yes" || value == "true")
107     {
108         addValue(true);
109         return;
110     }
111     else if (value == "0" || value == "no" || value == "false")
112     {
113         addValue(false);
114         return;
115     }
116     GMX_THROW(InvalidInputError("Invalid value: '" + value + "'; supported values are: 1, 0, yes, no, true, false"));
117 }
118
119 /********************************************************************
120  * BooleanOptionInfo
121  */
122
123 BooleanOptionInfo::BooleanOptionInfo(BooleanOptionStorage *option)
124     : OptionInfo(option)
125 {
126 }
127
128 const BooleanOptionStorage &BooleanOptionInfo::option() const
129 {
130     return static_cast<const BooleanOptionStorage &>(OptionInfo::option());
131 }
132
133 bool BooleanOptionInfo::defaultValue() const
134 {
135     return option().defaultValue();
136 }
137
138 /********************************************************************
139  * BooleanOption
140  */
141
142 AbstractOptionStoragePointer BooleanOption::createStorage() const
143 {
144     return AbstractOptionStoragePointer(new BooleanOptionStorage(*this));
145 }
146
147
148 /********************************************************************
149  * IntegerOptionStorage
150  */
151
152 std::string IntegerOptionStorage::formatSingleValue(const int &value) const
153 {
154     return formatString("%d", value);
155 }
156
157 void IntegerOptionStorage::convertValue(const std::string &value)
158 {
159     const char *ptr = value.c_str();
160     char       *endptr;
161     errno = 0;
162     long int    ival = std::strtol(ptr, &endptr, 10);
163     if (errno == ERANGE
164         || ival < std::numeric_limits<int>::min()
165         || ival > std::numeric_limits<int>::max())
166     {
167         GMX_THROW(InvalidInputError("Invalid value: '" + value
168                                     + "'; it causes an integer overflow"));
169     }
170     if (*ptr == '\0' || *endptr != '\0')
171     {
172         GMX_THROW(InvalidInputError("Invalid value: '" + value
173                                     + "'; expected an integer"));
174     }
175     addValue(ival);
176 }
177
178 void IntegerOptionStorage::processSetValues(ValueList *values)
179 {
180     if (isVector())
181     {
182         expandVector(maxValueCount(), values);
183     }
184 }
185
186 /********************************************************************
187  * IntegerOptionInfo
188  */
189
190 IntegerOptionInfo::IntegerOptionInfo(IntegerOptionStorage *option)
191     : OptionInfo(option)
192 {
193 }
194
195 /********************************************************************
196  * IntegerOption
197  */
198
199 AbstractOptionStoragePointer IntegerOption::createStorage() const
200 {
201     return AbstractOptionStoragePointer(new IntegerOptionStorage(*this));
202 }
203
204
205 /********************************************************************
206  * Int64OptionStorage
207  */
208
209 std::string Int64OptionStorage::formatSingleValue(const gmx_int64_t &value) const
210 {
211     return formatString("%" GMX_PRId64, value);
212 }
213
214 void Int64OptionStorage::convertValue(const std::string &value)
215 {
216     const char       *ptr = value.c_str();
217     char             *endptr;
218     errno = 0;
219     const gmx_int64_t ival = str_to_int64_t(ptr, &endptr);
220     if (errno == ERANGE)
221     {
222         GMX_THROW(InvalidInputError("Invalid value: '" + value
223                                     + "'; it causes an integer overflow"));
224     }
225     if (*ptr == '\0' || *endptr != '\0')
226     {
227         GMX_THROW(InvalidInputError("Invalid value: '" + value
228                                     + "'; expected an integer"));
229     }
230     addValue(ival);
231 }
232
233 /********************************************************************
234  * Int64OptionInfo
235  */
236
237 Int64OptionInfo::Int64OptionInfo(Int64OptionStorage *option)
238     : OptionInfo(option)
239 {
240 }
241
242 /********************************************************************
243  * Int64Option
244  */
245
246 AbstractOptionStoragePointer Int64Option::createStorage() const
247 {
248     return AbstractOptionStoragePointer(new Int64OptionStorage(*this));
249 }
250
251
252 /********************************************************************
253  * DoubleOptionStorage
254  */
255
256 DoubleOptionStorage::DoubleOptionStorage(const DoubleOption &settings)
257     : MyBase(settings), info_(this), bTime_(settings.bTime_), factor_(1.0)
258 {
259 }
260
261 std::string DoubleOptionStorage::typeString() const
262 {
263     return isVector() ? "vector" : (isTime() ? "time" : "real");
264 }
265
266 std::string DoubleOptionStorage::formatSingleValue(const double &value) const
267 {
268     return formatString("%g", value / factor_);
269 }
270
271 void DoubleOptionStorage::convertValue(const std::string &value)
272 {
273     const char *ptr = value.c_str();
274     char       *endptr;
275     errno = 0;
276     double      dval = std::strtod(ptr, &endptr);
277     if (errno == ERANGE)
278     {
279         GMX_THROW(InvalidInputError("Invalid value: '" + value
280                                     + "'; it causes an overflow/underflow"));
281     }
282     if (*ptr == '\0' || *endptr != '\0')
283     {
284         GMX_THROW(InvalidInputError("Invalid value: '" + value
285                                     + "'; expected a number"));
286     }
287     addValue(dval * factor_);
288 }
289
290 void DoubleOptionStorage::processSetValues(ValueList *values)
291 {
292     if (isVector())
293     {
294         expandVector(maxValueCount(), values);
295     }
296 }
297
298 void DoubleOptionStorage::setScaleFactor(double factor)
299 {
300     GMX_RELEASE_ASSERT(factor > 0.0, "Invalid scaling factor");
301     if (!hasFlag(efOption_HasDefaultValue))
302     {
303         double              scale = factor / factor_;
304         ValueList::iterator i;
305         for (i = values().begin(); i != values().end(); ++i)
306         {
307             (*i) *= scale;
308         }
309         refreshValues();
310     }
311     factor_ = factor;
312 }
313
314 /********************************************************************
315  * DoubleOptionInfo
316  */
317
318 DoubleOptionInfo::DoubleOptionInfo(DoubleOptionStorage *option)
319     : OptionInfo(option)
320 {
321 }
322
323 DoubleOptionStorage &DoubleOptionInfo::option()
324 {
325     return static_cast<DoubleOptionStorage &>(OptionInfo::option());
326 }
327
328 const DoubleOptionStorage &DoubleOptionInfo::option() const
329 {
330     return static_cast<const DoubleOptionStorage &>(OptionInfo::option());
331 }
332
333 bool DoubleOptionInfo::isTime() const
334 {
335     return option().isTime();
336 }
337
338 void DoubleOptionInfo::setScaleFactor(double factor)
339 {
340     option().setScaleFactor(factor);
341 }
342
343 /********************************************************************
344  * DoubleOption
345  */
346
347 AbstractOptionStoragePointer DoubleOption::createStorage() const
348 {
349     return AbstractOptionStoragePointer(new DoubleOptionStorage(*this));
350 }
351
352
353 /********************************************************************
354  * FloatOptionStorage
355  */
356
357 FloatOptionStorage::FloatOptionStorage(const FloatOption &settings)
358     : MyBase(settings), info_(this), bTime_(settings.bTime_), factor_(1.0)
359 {
360 }
361
362 std::string FloatOptionStorage::typeString() const
363 {
364     return isVector() ? "vector" : (isTime() ? "time" : "real");
365 }
366
367 std::string FloatOptionStorage::formatSingleValue(const float &value) const
368 {
369     return formatString("%g", value / factor_);
370 }
371
372 void FloatOptionStorage::convertValue(const std::string &value)
373 {
374     const char *ptr = value.c_str();
375     char       *endptr;
376     errno = 0;
377     double      dval = std::strtod(ptr, &endptr);
378     if (errno == ERANGE
379         || dval * factor_ < -std::numeric_limits<float>::max()
380         || dval * factor_ > -std::numeric_limits<float>::max())
381     {
382         GMX_THROW(InvalidInputError("Invalid value: '" + value
383                                     + "'; it causes an overflow/underflow"));
384     }
385     if (*ptr == '\0' || *endptr != '\0')
386     {
387         GMX_THROW(InvalidInputError("Invalid value: '" + value
388                                     + "'; expected a number"));
389     }
390     addValue(dval * factor_);
391 }
392
393 void FloatOptionStorage::processSetValues(ValueList *values)
394 {
395     if (isVector())
396     {
397         expandVector(maxValueCount(), values);
398     }
399 }
400
401 void FloatOptionStorage::setScaleFactor(double factor)
402 {
403     GMX_RELEASE_ASSERT(factor > 0.0, "Invalid scaling factor");
404     if (!hasFlag(efOption_HasDefaultValue))
405     {
406         double              scale = factor / factor_;
407         ValueList::iterator i;
408         for (i = values().begin(); i != values().end(); ++i)
409         {
410             (*i) *= scale;
411         }
412         refreshValues();
413     }
414     factor_ = factor;
415 }
416
417 /********************************************************************
418  * FloatOptionInfo
419  */
420
421 FloatOptionInfo::FloatOptionInfo(FloatOptionStorage *option)
422     : OptionInfo(option)
423 {
424 }
425
426 FloatOptionStorage &FloatOptionInfo::option()
427 {
428     return static_cast<FloatOptionStorage &>(OptionInfo::option());
429 }
430
431 const FloatOptionStorage &FloatOptionInfo::option() const
432 {
433     return static_cast<const FloatOptionStorage &>(OptionInfo::option());
434 }
435
436 bool FloatOptionInfo::isTime() const
437 {
438     return option().isTime();
439 }
440
441 void FloatOptionInfo::setScaleFactor(double factor)
442 {
443     option().setScaleFactor(factor);
444 }
445
446 /********************************************************************
447  * FloatOption
448  */
449
450 AbstractOptionStoragePointer FloatOption::createStorage() const
451 {
452     return AbstractOptionStoragePointer(new FloatOptionStorage(*this));
453 }
454
455
456 /********************************************************************
457  * StringOptionStorage
458  */
459
460 StringOptionStorage::StringOptionStorage(const StringOption &settings)
461     : MyBase(settings), info_(this), enumIndexStore_(NULL)
462 {
463     if (settings.defaultEnumIndex_ >= 0 && settings.enumValues_ == NULL)
464     {
465         GMX_THROW(APIError("Cannot set default enum index without enum values"));
466     }
467     if (settings.enumIndexStore_ != NULL && settings.enumValues_ == NULL)
468     {
469         GMX_THROW(APIError("Cannot set enum index store without enum values"));
470     }
471     if (settings.enumIndexStore_ != NULL && settings.maxValueCount_ < 0)
472     {
473         GMX_THROW(APIError("Cannot set enum index store with arbitrary number of values"));
474     }
475     if (settings.enumValues_ != NULL)
476     {
477         enumIndexStore_ = settings.enumIndexStore_;
478         const std::string *defaultValue = settings.defaultValue();
479         int                match        = -1;
480         int                count        = settings.enumValuesCount_;
481         if (count < 0)
482         {
483             count = 0;
484             while (settings.enumValues_[count] != NULL)
485             {
486                 ++count;
487             }
488         }
489         for (int i = 0; i < count; ++i)
490         {
491             if (settings.enumValues_[i] == NULL)
492             {
493                 GMX_THROW(APIError("Enumeration value cannot be NULL"));
494             }
495             if (defaultValue != NULL && settings.enumValues_[i] == *defaultValue)
496             {
497                 match = i;
498             }
499             allowed_.push_back(settings.enumValues_[i]);
500         }
501         if (defaultValue != NULL)
502         {
503             if (match < 0)
504             {
505                 GMX_THROW(APIError("Default value is not one of allowed values"));
506             }
507         }
508         if (settings.defaultEnumIndex_ >= 0)
509         {
510             if (settings.defaultEnumIndex_ >= static_cast<int>(allowed_.size()))
511             {
512                 GMX_THROW(APIError("Default enumeration index is out of range"));
513             }
514             if (defaultValue != NULL && *defaultValue != allowed_[settings.defaultEnumIndex_])
515             {
516                 GMX_THROW(APIError("Conflicting default values"));
517             }
518         }
519         // If there is no default value, match is still -1.
520         if (enumIndexStore_ != NULL)
521         {
522             *enumIndexStore_ = match;
523         }
524     }
525     if (settings.defaultEnumIndex_ >= 0)
526     {
527         clear();
528         addValue(allowed_[settings.defaultEnumIndex_]);
529         commitValues();
530     }
531 }
532
533 std::string StringOptionStorage::formatExtraDescription() const
534 {
535     std::string result;
536     if (!allowed_.empty())
537     {
538         result.append(": ");
539         ValueList::const_iterator i;
540         for (i = allowed_.begin(); i != allowed_.end(); ++i)
541         {
542             if (i != allowed_.begin())
543             {
544                 result.append(", ");
545             }
546             result.append(*i);
547         }
548     }
549     return result;
550 }
551
552 std::string StringOptionStorage::formatSingleValue(const std::string &value) const
553 {
554     return value;
555 }
556
557 void StringOptionStorage::convertValue(const std::string &value)
558 {
559     if (allowed_.size() == 0)
560     {
561         addValue(value);
562     }
563     else
564     {
565         ValueList::const_iterator  i;
566         ValueList::const_iterator  match = allowed_.end();
567         for (i = allowed_.begin(); i != allowed_.end(); ++i)
568         {
569             // TODO: Case independence.
570             if (i->find(value) == 0)
571             {
572                 if (match == allowed_.end() || i->size() < match->size())
573                 {
574                     match = i;
575                 }
576             }
577         }
578         if (match == allowed_.end())
579         {
580             GMX_THROW(InvalidInputError("Invalid value: " + value));
581         }
582         addValue(*match);
583     }
584 }
585
586 void StringOptionStorage::refreshValues()
587 {
588     MyBase::refreshValues();
589     if (enumIndexStore_ != NULL)
590     {
591         for (size_t i = 0; i < values().size(); ++i)
592         {
593             ValueList::const_iterator match =
594                 std::find(allowed_.begin(), allowed_.end(), values()[i]);
595             GMX_ASSERT(match != allowed_.end(),
596                        "Enum value not found (internal error)");
597             enumIndexStore_[i] = static_cast<int>(match - allowed_.begin());
598         }
599     }
600 }
601
602 /********************************************************************
603  * StringOptionInfo
604  */
605
606 StringOptionInfo::StringOptionInfo(StringOptionStorage *option)
607     : OptionInfo(option)
608 {
609 }
610
611 StringOptionStorage &StringOptionInfo::option()
612 {
613     return static_cast<StringOptionStorage &>(OptionInfo::option());
614 }
615
616 const StringOptionStorage &StringOptionInfo::option() const
617 {
618     return static_cast<const StringOptionStorage &>(OptionInfo::option());
619 }
620
621 bool StringOptionInfo::isEnumerated() const
622 {
623     return !allowedValues().empty();
624 }
625
626 const std::vector<std::string> &StringOptionInfo::allowedValues() const
627 {
628     return option().allowedValues();
629 }
630
631 /********************************************************************
632  * StringOption
633  */
634
635 AbstractOptionStoragePointer StringOption::createStorage() const
636 {
637     return AbstractOptionStoragePointer(new StringOptionStorage(*this));
638 }
639
640 } // namespace gmx