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