Debian Codegraph @

src/dmlc-core/include/dmlc/parameter.h

raw symbols SCIP
1 /*!
2 * Copyright (c) 2015 by Contributors
3 * \file parameter.h
4 * \brief Provide lightweight util to do parameter setup and checking.
5 */
6 #ifndef DMLC_PARAMETER_H_
7 #define DMLC_PARAMETER_H_
8
9 #include <algorithm>
10 #include <cerrno>
11 #include <cmath>
12 #include <cstddef>
13 #include <cstdlib>
14 #include <iomanip>
15 #include <iostream>
16 #include <limits>
17 #include <map>
18 #include <set>
19 #include <sstream>
20 #include <stdexcept>
21 #include <string>
22 #include <typeinfo>
23 #include <utility>
24 #include <vector>
25
26 #include "./base.h"
27 #include "./json.h"
28 #include "./logging.h"
29 #include "./optional.h"
30 #include "./strtonum.h"
31 #include "./type_traits.h"
32
33 namespace dmlc {
34 // this file is backward compatible with non-c++11
35 /*! \brief Error throwed by parameter checking */
36 struct ParamError : public dmlc::Error {
37 /*!
38 * \brief constructor
39 * \param msg error message
40 */
41 explicit ParamError(const std::string &msg) : dmlc::Error(msg) {}
42 };
43
44 /*!
45 * \brief Get environment variable with default.
46 * \param key the name of environment variable.
47 * \param default_value the default value of environment vriable.
48 * \return The value received
49 */
50 template <typename ValueType>
51 inline ValueType GetEnv(const char *key, ValueType default_value);
52 /*!
53 * \brief Set environment variable.
54 * \param key the name of environment variable.
55 * \param value the new value for key.
56 * \return The value received
57 */
58 template <typename ValueType>
59 inline void SetEnv(const char *key, ValueType value);
60
61 /*!
62 * \brief Unset environment variable.
63 * \param key the name of environment variable.
64 */
65 inline void UnsetEnv(const char *key);
66
67 /*! \brief internal namespace for parameter manangement */
68 namespace parameter {
69 // forward declare ParamManager
70 class ParamManager;
71 // forward declare FieldAccessEntry
72 class FieldAccessEntry;
73 // forward declare FieldEntry
74 template <typename DType>
75 class FieldEntry;
76 // forward declare ParamManagerSingleton
77 template <typename PType>
78 struct ParamManagerSingleton;
79
80 /*! \brief option in parameter initialization */
81 enum ParamInitOption {
82 /*! \brief allow unknown parameters */
83 kAllowUnknown,
84 /*! \brief need to match exact parameters */
85 kAllMatch,
86 /*! \brief allow unmatched hidden field with format __*__ */
87 kAllowHidden
88 };
89 } // namespace parameter
90 /*!
91 * \brief Information about a parameter field in string representations.
92 */
93 struct ParamFieldInfo {
94 /*! \brief name of the field */
95 std::string name;
96 /*! \brief type of the field in string format */
97 std::string type;
98 /*!
99 * \brief detailed type information string
100 * This include the default value, enum constran and typename.
101 */
102 std::string type_info_str;
103 /*! \brief detailed description of the type */
104 std::string description;
105 };
106
107 /*!
108 * \brief Parameter is the base type every parameter struct should inherit from
109 * The following code is a complete example to setup parameters.
110 * \code
111 * struct Param : public dmlc::Parameter<Param> {
112 * float learning_rate;
113 * int num_hidden;
114 * std::string name;
115 * // declare parameters in header file
116 * DMLC_DECLARE_PARAMETER(Param) {
117 * DMLC_DECLARE_FIELD(num_hidden).set_range(0, 1000);
118 * DMLC_DECLARE_FIELD(learning_rate).set_default(0.01f);
119 * DMLC_DECLARE_FIELD(name).set_default("hello");
120 * }
121 * };
122 * // register it in cc file
123 * DMLC_REGISTER_PARAMETER(Param);
124 * \endcode
125 *
126 * After that, the Param struct will get all the functions defined in Parameter.
127 * \tparam PType the type of parameter struct
128 *
129 * \sa DMLC_DECLARE_FIELD, DMLC_REGISTER_PARAMETER, DMLC_DECLARE_PARAMETER
130 */
131 template <typename PType>
132 struct Parameter {
133 public:
134 /*!
135 * \brief initialize the parameter by keyword arguments.
136 * This function will initialize the parameter struct, check consistency
137 * and throw error if something wrong happens.
138 *
139 * \param kwargs map of keyword arguments, or vector of pairs
140 * \parma option The option on initialization.
141 * \tparam Container container type
142 * \throw ParamError when something go wrong.
143 */
144 template <typename Container>
145 inline void Init(
146 const Container &kwargs, parameter::ParamInitOption option = parameter::kAllowHidden) {
147 PType::__MANAGER__()->RunInit(
148 static_cast<PType *>(this), kwargs.begin(), kwargs.end(), NULL, option);
149 }
150 /*!
151 * \brief initialize the parameter by keyword arguments.
152 * This is same as Init, but allow unknown arguments.
153 *
154 * \param kwargs map of keyword arguments, or vector of pairs
155 * \tparam Container container type
156 * \throw ParamError when something go wrong.
157 * \return vector of pairs of unknown arguments.
158 */
159 template <typename Container>
160 inline std::vector<std::pair<std::string, std::string>> InitAllowUnknown(
161 const Container &kwargs) {
162 std::vector<std::pair<std::string, std::string>> unknown;
163 PType::__MANAGER__()->RunInit(static_cast<PType *>(this), kwargs.begin(), kwargs.end(),
164 &unknown, parameter::kAllowUnknown);
165 return unknown;
166 }
167
168 /*!
169 * \brief Update the parameter by keyword arguments. This is same as
170 * `InitAllowUnknown', but without setting not provided parameters to their default.
171 *
172 * \tparam Container container type
173 *
174 * \param kwargs map of keyword arguments, or vector of pairs
175 *
176 * \throw ParamError when something go wrong.
177 * \return vector of pairs of unknown arguments.
178 */
179 template <typename Container>
180 std::vector<std::pair<std::string, std::string>> UpdateAllowUnknown(const Container &kwargs) {
181 std::vector<std::pair<std::string, std::string>> unknown;
182 PType::__MANAGER__()->RunUpdate(static_cast<PType *>(this), kwargs.begin(), kwargs.end(),
183 parameter::kAllowUnknown, &unknown, nullptr);
184 return unknown;
185 }
186
187 /*!
188 * \brief Update the dict with values stored in parameter.
189 *
190 * \param dict The dictionary to be updated.
191 * \tparam Container container type
192 */
193 template <typename Container>
194 inline void UpdateDict(Container *dict) const {
195 PType::__MANAGER__()->UpdateDict(this->head(), dict);
196 }
197 /*!
198 * \brief Return a dictionary representation of the parameters
199 * \return A dictionary that maps key -> value
200 */
201 inline std::map<std::string, std::string> __DICT__() const {
202 std::vector<std::pair<std::string, std::string>> vec
203 = PType::__MANAGER__()->GetDict(this->head());
204 return std::map<std::string, std::string>(vec.begin(), vec.end());
205 }
206 /*!
207 * \brief Write the parameters in JSON format.
208 * \param writer JSONWriter used for writing.
209 */
210 inline void Save(dmlc::JSONWriter *writer) const {
211 writer->Write(this->__DICT__());
212 }
213 /*!
214 * \brief Load the parameters from JSON.
215 * \param reader JSONReader used for loading.
216 * \throw ParamError when something go wrong.
217 */
218 inline void Load(dmlc::JSONReader *reader) {
219 std::map<std::string, std::string> kwargs;
220 reader->Read(&kwargs);
221 this->Init(kwargs);
222 }
223 /*!
224 * \brief Get the fields of the parameters.
225 * \return List of ParamFieldInfo of each field.
226 */
227 inline static std::vector<ParamFieldInfo> __FIELDS__() {
228 return PType::__MANAGER__()->GetFieldInfo();
229 }
230 /*!
231 * \brief Print docstring of the parameter
232 * \return the printed docstring
233 */
234 inline static std::string __DOC__() {
235 std::ostringstream os;
236 PType::__MANAGER__()->PrintDocString(os);
237 return os.str();
238 }
239
240 protected:
241 /*!
242 * \brief internal function to allow declare of a parameter memember
243 * \param manager the parameter manager
244 * \param key the key name of the parameter
245 * \param ref the reference to the parameter in the struct.
246 */
247 template <typename DType>
248 inline parameter::FieldEntry<DType> &DECLARE(parameter::ParamManagerSingleton<PType> *manager,
249 const std::string &key, DType &ref) { // NOLINT(*)
250 parameter::FieldEntry<DType> *e = new parameter::FieldEntry<DType>();
251 e->Init(key, this->head(), ref);
252 manager->manager.AddEntry(key, e);
253 return *e;
254 }
255
256 private:
257 /*! \return Get head pointer of child structure */
258 inline PType *head() const {
259 return static_cast<PType *>(const_cast<Parameter<PType> *>(this));
260 }
261 };
262
263 //! \cond Doxygen_Suppress
264 /*!
265 * \brief macro used to declare parameter
266 *
267 * Example:
268 * \code
269 * struct Param : public dmlc::Parameter<Param> {
270 * // declare parameters in header file
271 * DMLC_DECLARE_PARAMETER(Param) {
272 * // details of declarations
273 * }
274 * };
275 * \endcode
276 *
277 * This macro need to be put in a source file so that registration only happens once.
278 * Refer to example code in Parameter for details
279 *
280 * \param PType the name of parameter struct.
281 * \sa Parameter
282 */
283 #define DMLC_DECLARE_PARAMETER(PType) \
284 static ::dmlc::parameter::ParamManager *__MANAGER__(); \
285 inline void __DECLARE__(::dmlc::parameter::ParamManagerSingleton<PType> *manager)
286
287 /*!
288 * \brief macro to declare fields
289 * \param FieldName the name of the field.
290 */
291 #define DMLC_DECLARE_FIELD(FieldName) this->DECLARE(manager, #FieldName, FieldName)
292
293 /*!
294 * \brief macro to declare alias of a fields
295 * \param FieldName the name of the field.
296 * \param AliasName the name of the alias, must be declared after the field is declared.
297 */
298 #define DMLC_DECLARE_ALIAS(FieldName, AliasName) manager->manager.AddAlias(#FieldName, #AliasName)
299
300 /*!
301 * \brief Macro used to register parameter.
302 *
303 * This macro need to be put in a source file so that registeration only happens once.
304 * Refer to example code in Parameter for details
305 * \param PType the type of parameter struct.
306 * \sa Parameter
307 */
308 #define DMLC_REGISTER_PARAMETER(PType) \
309 ::dmlc::parameter::ParamManager *PType::__MANAGER__() { \
310 static ::dmlc::parameter::ParamManagerSingleton<PType> inst(#PType); \
311 return &inst.manager; \
312 } \
313 static DMLC_ATTRIBUTE_UNUSED ::dmlc::parameter::ParamManager &__make__##PType##ParamManager__ \
314 = (*PType::__MANAGER__())
315
316 //! \endcond
317 /*!
318 * \brief internal namespace for parameter management
319 * There is no need to use it directly in normal case
320 */
321 namespace parameter {
322 /*!
323 * \brief FieldAccessEntry interface to help manage the parameters
324 * Each entry can be used to access one parameter in the Parameter struct.
325 *
326 * This is an internal interface used that is used to manage parameters
327 */
328 class FieldAccessEntry {
329 public:
330 FieldAccessEntry() : has_default_(false), index_(0) {}
331 /*! \brief destructor */
332 virtual ~FieldAccessEntry() {}
333 /*!
334 * \brief set the default value.
335 * \param head the pointer to the head of the struct
336 * \throw error if no default is presented
337 */
338 virtual void SetDefault(void *head) const = 0;
339 /*!
340 * \brief set the parameter by string value
341 * \param head the pointer to the head of the struct
342 * \param value the value to be set
343 */
344 virtual void Set(void *head, const std::string &value) const = 0;
345 // check if value is OK
346 virtual void Check(void * /*head*/) const {}
347 /*!
348 * \brief get the string representation of value.
349 * \param head the pointer to the head of the struct
350 */
351 virtual std::string GetStringValue(void *head) const = 0;
352 /*!
353 * \brief Get field information
354 * \return the corresponding field information
355 */
356 virtual ParamFieldInfo GetFieldInfo() const = 0;
357
358 protected:
359 /*! \brief whether this parameter have default value */
360 bool has_default_;
361 /*! \brief positional index of parameter in struct */
362 size_t index_;
363 /*! \brief parameter key name */
364 std::string key_;
365 /*! \brief parameter type */
366 std::string type_;
367 /*! \brief description of the parameter */
368 std::string description_;
369 // internal offset of the field
370 ptrdiff_t offset_;
371 /*! \brief get pointer to parameter */
372 char *GetRawPtr(void *head) const {
373 return reinterpret_cast<char *>(head) + offset_;
374 }
375 /*!
376 * \brief print string representation of default value
377 * \parma os the stream to print the docstring to.
378 */
379 virtual void PrintDefaultValueString(std::ostream &os) const = 0; // NOLINT(*)
380 // allow ParamManager to modify self
381 friend class ParamManager;
382 };
383
384 /*!
385 * \brief manager class to handle parameter structure for each type
386 * An manager will be created for each parameter structure.
387 */
388 class ParamManager {
389 public:
390 /*! \brief destructor */
391 ~ParamManager() {
392 for (size_t i = 0; i < entry_.size(); ++i) {
393 delete entry_[i];
394 }
395 }
396 /*!
397 * \brief find the access entry by parameter key
398 * \param key the key of the parameter.
399 * \return pointer to FieldAccessEntry, NULL if nothing is found.
400 */
401 inline FieldAccessEntry *Find(const std::string &key) const {
402 std::map<std::string, FieldAccessEntry *>::const_iterator it = entry_map_.find(key);
403 if (it == entry_map_.end()) {
404 return NULL;
405 }
406 return it->second;
407 }
408 /*!
409 * \brief Set parameter by keyword arguments and default values.
410 * \param head head to the parameter field.
411 * \param begin begin iterator of original kwargs
412 * \param end end iterator of original kwargs
413 * \param unknown_args optional, used to hold unknown arguments
414 * When it is specified, unknown arguments will be stored into here, instead of raise an
415 * error
416 * \tparam RandomAccessIterator iterator type
417 * \throw ParamError when there is unknown argument and unknown_args == NULL, or required argument
418 * is missing.
419 */
420 template <typename RandomAccessIterator>
421 inline void RunInit(void *head, RandomAccessIterator begin, RandomAccessIterator end,
422 std::vector<std::pair<std::string, std::string>> *unknown_args,
423 parameter::ParamInitOption option) const {
424 std::set<FieldAccessEntry *> selected_args;
425 RunUpdate(head, begin, end, option, unknown_args, &selected_args);
426 for (const auto &kv : entry_map_) {
427 if (selected_args.find(kv.second) == selected_args.cend()) {
428 kv.second->SetDefault(head);
429 }
430 }
431 for (std::map<std::string, FieldAccessEntry *>::const_iterator it = entry_map_.begin();
432 it != entry_map_.end(); ++it) {
433 if (selected_args.count(it->second) == 0) {
434 it->second->SetDefault(head);
435 }
436 }
437 }
438 /*!
439 * \brief Update parameters by keyword arguments.
440 *
441 * \tparam RandomAccessIterator iterator type
442 * \param head head to the parameter field.
443 * \param begin begin iterator of original kwargs
444 * \param end end iterator of original kwargs
445 * \param unknown_args optional, used to hold unknown arguments
446 * When it is specified, unknown arguments will be stored into here, instead of raise an
447 * error
448 * \param selected_args The arguments used in update will be pushed into it, defaullt to nullptr.
449 * \throw ParamError when there is unknown argument and unknown_args == NULL, or required argument
450 * is missing.
451 */
452 template <typename RandomAccessIterator>
453 void RunUpdate(void *head, RandomAccessIterator begin, RandomAccessIterator end,
454 parameter::ParamInitOption option,
455 std::vector<std::pair<std::string, std::string>> *unknown_args,
456 std::set<FieldAccessEntry *> *selected_args = nullptr) const {
457 for (RandomAccessIterator it = begin; it != end; ++it) {
458 if (FieldAccessEntry *e = Find(it->first)) {
459 e->Set(head, it->second);
460 e->Check(head);
461 if (selected_args) {
462 selected_args->insert(e);
463 }
464 } else {
465 if (unknown_args != NULL) {
466 unknown_args->push_back(*it);
467 } else {
468 if (option != parameter::kAllowUnknown) {
469 if (option == parameter::kAllowHidden && it->first.length() > 4
470 && it->first.find("__") == 0 && it->first.rfind("__") == it->first.length() - 2) {
471 continue;
472 }
473 std::ostringstream os;
474 os << "Cannot find argument \'" << it->first << "\', Possible Arguments:\n";
475 os << "----------------\n";
476 PrintDocString(os);
477 throw dmlc::ParamError(os.str());
478 }
479 }
480 }
481 }
482 }
483 /*!
484 * \brief internal function to add entry to manager,
485 * The manager will take ownership of the entry.
486 * \param key the key to the parameters
487 * \param e the pointer to the new entry.
488 */
489 inline void AddEntry(const std::string &key, FieldAccessEntry *e) {
490 e->index_ = entry_.size();
491 // TODO(bing) better error message
492 if (entry_map_.count(key) != 0) {
493 LOG(FATAL) << "key " << key << " has already been registered in " << name_;
494 }
495 entry_.push_back(e);
496 entry_map_[key] = e;
497 }
498 /*!
499 * \brief internal function to add entry to manager,
500 * The manager will take ownership of the entry.
501 * \param key the key to the parameters
502 * \param e the pointer to the new entry.
503 */
504 inline void AddAlias(const std::string &field, const std::string &alias) {
505 if (entry_map_.count(field) == 0) {
506 LOG(FATAL) << "key " << field << " has not been registered in " << name_;
507 }
508 if (entry_map_.count(alias) != 0) {
509 LOG(FATAL) << "Alias " << alias << " has already been registered in " << name_;
510 }
511 entry_map_[alias] = entry_map_[field];
512 }
513 /*!
514 * \brief set the name of parameter manager
515 * \param name the name to set
516 */
517 inline void set_name(const std::string &name) {
518 name_ = name;
519 }
520 /*!
521 * \brief get field information of each field.
522 * \return field information
523 */
524 inline std::vector<ParamFieldInfo> GetFieldInfo() const {
525 std::vector<ParamFieldInfo> ret(entry_.size());
526 for (size_t i = 0; i < entry_.size(); ++i) {
527 ret[i] = entry_[i]->GetFieldInfo();
528 }
529 return ret;
530 }
531 /*!
532 * \brief Print readible docstring to ostream, add newline.
533 * \parma os the stream to print the docstring to.
534 */
535 inline void PrintDocString(std::ostream &os) const { // NOLINT(*)
536 for (size_t i = 0; i < entry_.size(); ++i) {
537 ParamFieldInfo info = entry_[i]->GetFieldInfo();
538 os << info.name << " : " << info.type_info_str << '\n';
539 if (info.description.length() != 0) {
540 os << " " << info.description << '\n';
541 }
542 }
543 }
544 /*!
545 * \brief Get internal parameters in vector of pairs.
546 * \param head the head of the struct.
547 * \param skip_default skip the values that equals default value.
548 * \return the parameter dictionary.
549 */
550 inline std::vector<std::pair<std::string, std::string>> GetDict(void *head) const {
551 std::vector<std::pair<std::string, std::string>> ret;
552 for (std::map<std::string, FieldAccessEntry *>::const_iterator it = entry_map_.begin();
553 it != entry_map_.end(); ++it) {
554 ret.push_back(std::make_pair(it->first, it->second->GetStringValue(head)));
555 }
556 return ret;
557 }
558 /*!
559 * \brief Update the dictionary with values in parameter.
560 * \param head the head of the struct.
561 * \tparam Container The container type
562 * \return the parameter dictionary.
563 */
564 template <typename Container>
565 inline void UpdateDict(void *head, Container *dict) const {
566 for (std::map<std::string, FieldAccessEntry *>::const_iterator it = entry_map_.begin();
567 it != entry_map_.end(); ++it) {
568 (*dict)[it->first] = it->second->GetStringValue(head);
569 }
570 }
571
572 private:
573 /*! \brief parameter struct name */
574 std::string name_;
575 /*! \brief positional list of entries */
576 std::vector<FieldAccessEntry *> entry_;
577 /*! \brief map from key to entry */
578 std::map<std::string, FieldAccessEntry *> entry_map_;
579 };
580
581 //! \cond Doxygen_Suppress
582
583 // The following piece of code will be template heavy and less documented
584 // singleton parameter manager for certain type, used for initialization
585 template <typename PType>
586 struct ParamManagerSingleton {
587 ParamManager manager;
588 explicit ParamManagerSingleton(const std::string &param_name) {
589 PType param;
590 manager.set_name(param_name);
591 param.__DECLARE__(this);
592 }
593 };
594
595 // Base class of FieldEntry
596 // implement set_default
597 template <typename TEntry, typename DType>
598 class FieldEntryBase : public FieldAccessEntry {
599 public:
600 // entry type
601 typedef TEntry EntryType;
602 // implement set value
603 void Set(void *head, const std::string &value) const override {
604 std::istringstream is(value);
605 is >> this->Get(head);
606 if (!is.fail()) {
607 while (!is.eof()) {
608 int ch = is.get();
609 if (ch == EOF) {
610 is.clear();
611 break;
612 }
613 if (!isspace(ch)) {
614 is.setstate(std::ios::failbit);
615 break;
616 }
617 }
618 }
619
620 if (is.fail()) {
621 std::ostringstream os;
622 os << "Invalid Parameter format for " << key_ << " expect " << type_ << " but value=\'"
623 << value << '\'';
624 throw dmlc::ParamError(os.str());
625 }
626 }
627
628 std::string GetStringValue(void *head) const override {
629 std::ostringstream os;
630 PrintValue(os, this->Get(head));
631 return os.str();
632 }
633 ParamFieldInfo GetFieldInfo() const override {
634 ParamFieldInfo info;
635 std::ostringstream os;
636 info.name = key_;
637 info.type = type_;
638 os << type_;
639 if (has_default_) {
640 os << ',' << " optional, default=";
641 PrintDefaultValueString(os);
642 } else {
643 os << ", required";
644 }
645 info.type_info_str = os.str();
646 info.description = description_;
647 return info;
648 }
649 // implement set head to default value
650 void SetDefault(void *head) const override {
651 if (!has_default_) {
652 std::ostringstream os;
653 os << "Required parameter " << key_ << " of " << type_ << " is not presented";
654 throw dmlc::ParamError(os.str());
655 } else {
656 this->Get(head) = default_value_;
657 }
658 }
659 // return reference of self as derived type
660 inline TEntry &self() {
661 return *(static_cast<TEntry *>(this));
662 }
663 // implement set_default
664 inline TEntry &set_default(const DType &default_value) {
665 default_value_ = default_value;
666 has_default_ = true;
667 // return self to allow chaining
668 return this->self();
669 }
670 // implement describe
671 inline TEntry &describe(const std::string &description) {
672 description_ = description;
673 // return self to allow chaining
674 return this->self();
675 }
676 // initialization function
677 inline void Init(const std::string &key, void *head, DType &ref) { // NOLINT(*)
678 this->key_ = key;
679 if (this->type_.length() == 0) {
680 this->type_ = dmlc::type_name<DType>();
681 }
682 this->offset_ = ((char *)&ref) - ((char *)head); // NOLINT(*)
683 }
684
685 protected:
686 // print the value
687 virtual void PrintValue(std::ostream &os, DType value) const { // NOLINT(*)
688 os << value;
689 }
690 void PrintDefaultValueString(std::ostream &os) const override { // NOLINT(*)
691 PrintValue(os, default_value_);
692 }
693 // get the internal representation of parameter
694 // for example if this entry corresponds field param.learning_rate
695 // then Get(&param) will return reference to param.learning_rate
696 inline DType &Get(void *head) const {
697 return *(DType *)this->GetRawPtr(head); // NOLINT(*)
698 }
699 // default value of field
700 DType default_value_;
701 };
702
703 // parameter base for numeric types that have range
704 template <typename TEntry, typename DType>
705 class FieldEntryNumeric : public FieldEntryBase<TEntry, DType> {
706 public:
707 FieldEntryNumeric() : has_begin_(false), has_end_(false) {}
708 // implement set_range
709 virtual TEntry &set_range(DType begin, DType end) {
710 begin_ = begin;
711 end_ = end;
712 has_begin_ = true;
713 has_end_ = true;
714 return this->self();
715 }
716 // implement set_range
717 virtual TEntry &set_lower_bound(DType begin) {
718 begin_ = begin;
719 has_begin_ = true;
720 return this->self();
721 }
722 // consistency check for numeric ranges
723 virtual void Check(void *head) const {
724 FieldEntryBase<TEntry, DType>::Check(head);
725 DType v = this->Get(head);
726 if (has_begin_ && has_end_) {
727 if (v < begin_ || v > end_) {
728 std::ostringstream os;
729 os << "value " << v << " for Parameter " << this->key_ << " exceed bound [" << begin_ << ','
730 << end_ << ']' << '\n';
731 os << this->key_ << ": " << this->description_;
732 throw dmlc::ParamError(os.str());
733 }
734 } else if (has_begin_ && v < begin_) {
735 std::ostringstream os;
736 os << "value " << v << " for Parameter " << this->key_ << " should be greater equal to "
737 << begin_ << '\n';
738 os << this->key_ << ": " << this->description_;
739 throw dmlc::ParamError(os.str());
740 } else if (has_end_ && v > end_) {
741 std::ostringstream os;
742 os << "value " << v << " for Parameter " << this->key_ << " should be smaller equal to "
743 << end_ << '\n';
744 os << this->key_ << ": " << this->description_;
745 throw dmlc::ParamError(os.str());
746 }
747 }
748
749 protected:
750 // whether it have begin and end range
751 bool has_begin_, has_end_;
752 // data bound
753 DType begin_, end_;
754 };
755
756 /*!
757 * \brief FieldEntry defines parsing and checking behavior of DType.
758 * This class can be specialized to implement specific behavior of more settings.
759 * \tparam DType the data type of the entry.
760 */
761 template <typename DType>
762 class FieldEntry :
763 public IfThenElseType<dmlc::is_arithmetic<DType>::value,
764 FieldEntryNumeric<FieldEntry<DType>, DType>,
765 FieldEntryBase<FieldEntry<DType>, DType>>::Type {};
766
767 // specialize define for int(enum)
768 template <>
769 class FieldEntry<int> : public FieldEntryNumeric<FieldEntry<int>, int> {
770 public:
771 // construct
772 FieldEntry() : is_enum_(false) {}
773 // parent
774 typedef FieldEntryNumeric<FieldEntry<int>, int> Parent;
775 // override set
776 virtual void Set(void *head, const std::string &value) const {
777 if (is_enum_) {
778 std::map<std::string, int>::const_iterator it = enum_map_.find(value);
779 std::ostringstream os;
780 if (it == enum_map_.end()) {
781 os << "Invalid Input: \'" << value;
782 os << "\', valid values are: ";
783 PrintEnums(os);
784 throw dmlc::ParamError(os.str());
785 } else {
786 os << it->second;
787 Parent::Set(head, os.str());
788 }
789 } else {
790 Parent::Set(head, value);
791 }
792 }
793 virtual ParamFieldInfo GetFieldInfo() const {
794 if (is_enum_) {
795 ParamFieldInfo info;
796 std::ostringstream os;
797 info.name = key_;
798 info.type = type_;
799 PrintEnums(os);
800 if (has_default_) {
801 os << ',' << "optional, default=";
802 PrintDefaultValueString(os);
803 } else {
804 os << ", required";
805 }
806 info.type_info_str = os.str();
807 info.description = description_;
808 return info;
809 } else {
810 return Parent::GetFieldInfo();
811 }
812 }
813 // add enum
814 inline FieldEntry<int> &add_enum(const std::string &key, int value) {
815 if ((enum_map_.size() != 0 && enum_map_.count(key) != 0) || enum_back_map_.count(value) != 0) {
816 std::ostringstream os;
817 os << "Enum " << "(" << key << ": " << value << " exisit!" << ")\n";
818 os << "Enums: ";
819 for (std::map<std::string, int>::const_iterator it = enum_map_.begin(); it != enum_map_.end();
820 ++it) {
821 os << "(" << it->first << ": " << it->second << "), ";
822 }
823 throw dmlc::ParamError(os.str());
824 }
825 enum_map_[key] = value;
826 enum_back_map_[value] = key;
827 is_enum_ = true;
828 return this->self();
829 }
830
831 protected:
832 // enum flag
833 bool is_enum_;
834 // enum map
835 std::map<std::string, int> enum_map_;
836 // enum map
837 std::map<int, std::string> enum_back_map_;
838 // override print behavior
839 virtual void PrintDefaultValueString(std::ostream &os) const { // NOLINT(*)
840 os << '\'';
841 PrintValue(os, default_value_);
842 os << '\'';
843 }
844 // override print default
845 virtual void PrintValue(std::ostream &os, int value) const { // NOLINT(*)
846 if (is_enum_) {
847 CHECK_NE(enum_back_map_.count(value), 0U) << "Value not found in enum declared";
848 os << enum_back_map_.at(value);
849 } else {
850 os << value;
851 }
852 }
853
854 private:
855 inline void PrintEnums(std::ostream &os) const { // NOLINT(*)
856 os << '{';
857 for (std::map<std::string, int>::const_iterator it = enum_map_.begin(); it != enum_map_.end();
858 ++it) {
859 if (it != enum_map_.begin()) {
860 os << ", ";
861 }
862 os << "\'" << it->first << '\'';
863 }
864 os << '}';
865 }
866 };
867
868 // specialize define for optional<int>(enum)
869 template <>
870 class FieldEntry<optional<int>> : public FieldEntryBase<FieldEntry<optional<int>>, optional<int>> {
871 public:
872 // construct
873 FieldEntry() : is_enum_(false) {}
874 // parent
875 typedef FieldEntryBase<FieldEntry<optional<int>>, optional<int>> Parent;
876 // override set
877 virtual void Set(void *head, const std::string &value) const {
878 if (is_enum_ && value != "None") {
879 std::map<std::string, int>::const_iterator it = enum_map_.find(value);
880 std::ostringstream os;
881 if (it == enum_map_.end()) {
882 os << "Invalid Input: \'" << value;
883 os << "\', valid values are: ";
884 PrintEnums(os);
885 throw dmlc::ParamError(os.str());
886 } else {
887 os << it->second;
888 Parent::Set(head, os.str());
889 }
890 } else {
891 Parent::Set(head, value);
892 }
893 }
894 virtual ParamFieldInfo GetFieldInfo() const {
895 if (is_enum_) {
896 ParamFieldInfo info;
897 std::ostringstream os;
898 info.name = key_;
899 info.type = type_;
900 PrintEnums(os);
901 if (has_default_) {
902 os << ',' << "optional, default=";
903 PrintDefaultValueString(os);
904 } else {
905 os << ", required";
906 }
907 info.type_info_str = os.str();
908 info.description = description_;
909 return info;
910 } else {
911 return Parent::GetFieldInfo();
912 }
913 }
914 // add enum
915 inline FieldEntry<optional<int>> &add_enum(const std::string &key, int value) {
916 CHECK_NE(key, "None") << "None is reserved for empty optional<int>";
917 if ((enum_map_.size() != 0 && enum_map_.count(key) != 0) || enum_back_map_.count(value) != 0) {
918 std::ostringstream os;
919 os << "Enum " << "(" << key << ": " << value << " exisit!" << ")\n";
920 os << "Enums: ";
921 for (std::map<std::string, int>::const_iterator it = enum_map_.begin(); it != enum_map_.end();
922 ++it) {
923 os << "(" << it->first << ": " << it->second << "), ";
924 }
925 throw dmlc::ParamError(os.str());
926 }
927 enum_map_[key] = value;
928 enum_back_map_[value] = key;
929 is_enum_ = true;
930 return this->self();
931 }
932
933 protected:
934 // enum flag
935 bool is_enum_;
936 // enum map
937 std::map<std::string, int> enum_map_;
938 // enum map
939 std::map<int, std::string> enum_back_map_;
940 // override print behavior
941 virtual void PrintDefaultValueString(std::ostream &os) const { // NOLINT(*)
942 os << '\'';
943 PrintValue(os, default_value_);
944 os << '\'';
945 }
946 // override print default
947 virtual void PrintValue(std::ostream &os, optional<int> value) const { // NOLINT(*)
948 if (is_enum_) {
949 if (!value) {
950 os << "None";
951 } else {
952 CHECK_NE(enum_back_map_.count(value.value()), 0U) << "Value not found in enum declared";
953 os << enum_back_map_.at(value.value());
954 }
955 } else {
956 os << value;
957 }
958 }
959
960 private:
961 inline void PrintEnums(std::ostream &os) const { // NOLINT(*)
962 os << "{None";
963 for (std::map<std::string, int>::const_iterator it = enum_map_.begin(); it != enum_map_.end();
964 ++it) {
965 os << ", ";
966 os << "\'" << it->first << '\'';
967 }
968 os << '}';
969 }
970 };
971
972 // specialize define for string
973 template <>
974 class FieldEntry<std::string> : public FieldEntryBase<FieldEntry<std::string>, std::string> {
975 public:
976 // parent class
977 typedef FieldEntryBase<FieldEntry<std::string>, std::string> Parent;
978 // override set
979 virtual void Set(void *head, const std::string &value) const {
980 this->Get(head) = value;
981 }
982 // override print default
983 virtual void PrintDefaultValueString(std::ostream &os) const { // NOLINT(*)
984 os << '\'' << default_value_ << '\'';
985 }
986 };
987
988 // specialize define for bool
989 template <>
990 class FieldEntry<bool> : public FieldEntryBase<FieldEntry<bool>, bool> {
991 public:
992 // parent class
993 typedef FieldEntryBase<FieldEntry<bool>, bool> Parent;
994 // override set
995 virtual void Set(void *head, const std::string &value) const {
996 std::string lower_case;
997 lower_case.resize(value.length());
998 std::transform(value.begin(), value.end(), lower_case.begin(), ::tolower);
999 bool &ref = this->Get(head);
1000 if (lower_case == "true") {
1001 ref = true;
1002 } else if (lower_case == "false") {
1003 ref = false;
1004 } else if (lower_case == "1") {
1005 ref = true;
1006 } else if (lower_case == "0") {
1007 ref = false;
1008 } else {
1009 std::ostringstream os;
1010 os << "Invalid Parameter format for " << key_ << " expect " << type_ << " but value=\'"
1011 << value << '\'';
1012 throw dmlc::ParamError(os.str());
1013 }
1014 }
1015
1016 protected:
1017 // print default string
1018 virtual void PrintValue(std::ostream &os, bool value) const { // NOLINT(*)
1019 os << static_cast<int>(value);
1020 }
1021 };
1022
1023 // specialize define for float. Uses stof for platform independent handling of
1024 // INF, -INF, NAN, etc.
1025 #if DMLC_USE_CXX11
1026 template <>
1027 class FieldEntry<float> : public FieldEntryNumeric<FieldEntry<float>, float> {
1028 public:
1029 // parent
1030 typedef FieldEntryNumeric<FieldEntry<float>, float> Parent;
1031 // override set
1032 virtual void Set(void *head, const std::string &value) const {
1033 size_t pos = 0; // number of characters processed by dmlc::stof()
1034 try {
1035 this->Get(head) = dmlc::stof(value, &pos);
1036 } catch (const std::invalid_argument &) {
1037 std::ostringstream os;
1038 os << "Invalid Parameter format for " << key_ << " expect " << type_ << " but value=\'"
1039 << value << '\'';
1040 throw dmlc::ParamError(os.str());
1041 } catch (const std::out_of_range &) {
1042 std::ostringstream os;
1043 os << "Out of range value for " << key_ << ", value=\'" << value << '\'';
1044 throw dmlc::ParamError(os.str());
1045 }
1046 CHECK_LE(pos, value.length()); // just in case
1047 if (pos < value.length()) {
1048 std::ostringstream os;
1049 os << "Some trailing characters could not be parsed: \'" << value.substr(pos) << "\'";
1050 throw dmlc::ParamError(os.str());
1051 }
1052 }
1053
1054 protected:
1055 // print the value
1056 virtual void PrintValue(std::ostream &os, float value) const { // NOLINT(*)
1057 os << std::setprecision(std::numeric_limits<float>::max_digits10) << value;
1058 }
1059 };
1060
1061 // specialize define for double. Uses stod for platform independent handling of
1062 // INF, -INF, NAN, etc.
1063 template <>
1064 class FieldEntry<double> : public FieldEntryNumeric<FieldEntry<double>, double> {
1065 public:
1066 // parent
1067 typedef FieldEntryNumeric<FieldEntry<double>, double> Parent;
1068 // override set
1069 virtual void Set(void *head, const std::string &value) const {
1070 size_t pos = 0; // number of characters processed by dmlc::stod()
1071 try {
1072 this->Get(head) = dmlc::stod(value, &pos);
1073 } catch (const std::invalid_argument &) {
1074 std::ostringstream os;
1075 os << "Invalid Parameter format for " << key_ << " expect " << type_ << " but value=\'"
1076 << value << '\'';
1077 throw dmlc::ParamError(os.str());
1078 } catch (const std::out_of_range &) {
1079 std::ostringstream os;
1080 os << "Out of range value for " << key_ << ", value=\'" << value << '\'';
1081 throw dmlc::ParamError(os.str());
1082 }
1083 CHECK_LE(pos, value.length()); // just in case
1084 if (pos < value.length()) {
1085 std::ostringstream os;
1086 os << "Some trailing characters could not be parsed: \'" << value.substr(pos) << "\'";
1087 throw dmlc::ParamError(os.str());
1088 }
1089 }
1090
1091 protected:
1092 // print the value
1093 virtual void PrintValue(std::ostream &os, double value) const { // NOLINT(*)
1094 os << std::setprecision(std::numeric_limits<double>::max_digits10) << value;
1095 }
1096 };
1097 #endif // DMLC_USE_CXX11
1098
1099 } // namespace parameter
1100 //! \endcond
1101
1102 // implement GetEnv
1103 template <typename ValueType>
1104 inline ValueType GetEnv(const char *key, ValueType default_value) {
1105 const char *val = getenv(key);
1106 // On some implementations, if the var is set to a blank string (i.e. "FOO="), then
1107 // a blank string will be returned instead of NULL. In order to be consistent, if
1108 // the environment var is a blank string, then also behave as if a null was returned.
1109 if (val == nullptr || !*val) {
1110 return default_value;
1111 }
1112 ValueType ret;
1113 parameter::FieldEntry<ValueType> e;
1114 e.Init(key, &ret, ret);
1115 e.Set(&ret, val);
1116 return ret;
1117 }
1118
1119 // implement SetEnv
1120 template <typename ValueType>
1121 inline void SetEnv(const char *key, ValueType value) {
1122 parameter::FieldEntry<ValueType> e;
1123 e.Init(key, &value, value);
1124 #ifdef _WIN32
1125 _putenv_s(key, e.GetStringValue(&value).c_str());
1126 #else
1127 setenv(key, e.GetStringValue(&value).c_str(), 1);
1128 #endif // _WIN32
1129 }
1130
1131 // implement UnsetEnv
1132 inline void UnsetEnv(const char *key) {
1133 #ifdef _WIN32
1134 _putenv_s(key, "");
1135 #else
1136 unsetenv(key);
1137 #endif // _WIN32
1138 }
1139 } // namespace dmlc
1140 #endif // DMLC_PARAMETER_H_