]> git.sesse.net Git - stockfish/blob - src/tune.h
Simplify MCP in QS
[stockfish] / src / tune.h
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2020 The Stockfish developers (see AUTHORS file)
4
5   Stockfish is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9
10   Stockfish is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #ifndef TUNE_H_INCLUDED
20 #define TUNE_H_INCLUDED
21
22 #include <memory>
23 #include <string>
24 #include <type_traits>
25 #include <vector>
26
27 typedef std::pair<int, int> Range; // Option's min-max values
28 typedef Range (RangeFun) (int);
29
30 // Default Range function, to calculate Option's min-max values
31 inline Range default_range(int v) {
32   return v > 0 ? Range(0, 2 * v) : Range(2 * v, 0);
33 }
34
35 struct SetRange {
36   explicit SetRange(RangeFun f) : fun(f) {}
37   SetRange(int min, int max) : fun(nullptr), range(min, max) {}
38   Range operator()(int v) const { return fun ? fun(v) : range; }
39
40   RangeFun* fun;
41   Range range;
42 };
43
44 #define SetDefaultRange SetRange(default_range)
45
46
47 /// BoolConditions struct is used to tune boolean conditions in the
48 /// code by toggling them on/off according to a probability that
49 /// depends on the value of a tuned integer parameter: for high
50 /// values of the parameter condition is always disabled, for low
51 /// values is always enabled, otherwise it is enabled with a given
52 /// probability that depnends on the parameter under tuning.
53
54 struct BoolConditions {
55   void init(size_t size) { values.resize(size, defaultValue), binary.resize(size, 0); }
56   void set();
57
58   std::vector<int> binary, values;
59   int defaultValue = 465, variance = 40, threshold = 500;
60   SetRange range = SetRange(0, 1000);
61 };
62
63 extern BoolConditions Conditions;
64
65 inline void set_conditions() { Conditions.set(); }
66
67
68 /// Tune class implements the 'magic' code that makes the setup of a fishtest
69 /// tuning session as easy as it can be. Mainly you have just to remove const
70 /// qualifiers from the variables you want to tune and flag them for tuning, so
71 /// if you have:
72 ///
73 ///   const Score myScore = S(10, 15);
74 ///   const Value myValue[][2] = { { V(100), V(20) }, { V(7), V(78) } };
75 ///
76 /// If you have a my_post_update() function to run after values have been updated,
77 /// and a my_range() function to set custom Option's min-max values, then you just
78 /// remove the 'const' qualifiers and write somewhere below in the file:
79 ///
80 ///   TUNE(SetRange(my_range), myScore, myValue, my_post_update);
81 ///
82 /// You can also set the range directly, and restore the default at the end
83 ///
84 ///   TUNE(SetRange(-100, 100), myScore, SetDefaultRange);
85 ///
86 /// In case update function is slow and you have many parameters, you can add:
87 ///
88 ///   UPDATE_ON_LAST();
89 ///
90 /// And the values update, including post update function call, will be done only
91 /// once, after the engine receives the last UCI option, that is the one defined
92 /// and created as the last one, so the GUI should send the options in the same
93 /// order in which have been defined.
94
95 class Tune {
96
97   typedef void (PostUpdate) (); // Post-update function
98
99   Tune() { read_results(); }
100   Tune(const Tune&) = delete;
101   void operator=(const Tune&) = delete;
102   void read_results();
103
104   static Tune& instance() { static Tune t; return t; } // Singleton
105
106   // Use polymorphism to accomodate Entry of different types in the same vector
107   struct EntryBase {
108     virtual ~EntryBase() = default;
109     virtual void init_option() = 0;
110     virtual void read_option() = 0;
111   };
112
113   template<typename T>
114   struct Entry : public EntryBase {
115
116     static_assert(!std::is_const<T>::value, "Parameter cannot be const!");
117
118     static_assert(   std::is_same<T,   int>::value
119                   || std::is_same<T, Value>::value
120                   || std::is_same<T, Score>::value
121                   || std::is_same<T, PostUpdate>::value, "Parameter type not supported!");
122
123     Entry(const std::string& n, T& v, const SetRange& r) : name(n), value(v), range(r) {}
124     void operator=(const Entry&) = delete; // Because 'value' is a reference
125     void init_option() override;
126     void read_option() override;
127
128     std::string name;
129     T& value;
130     SetRange range;
131   };
132
133   // Our facilty to fill the container, each Entry corresponds to a parameter to tune.
134   // We use variadic templates to deal with an unspecified number of entries, each one
135   // of a possible different type.
136   static std::string next(std::string& names, bool pop = true);
137
138   int add(const SetRange&, std::string&&) { return 0; }
139
140   template<typename T, typename... Args>
141   int add(const SetRange& range, std::string&& names, T& value, Args&&... args) {
142     list.push_back(std::unique_ptr<EntryBase>(new Entry<T>(next(names), value, range)));
143     return add(range, std::move(names), args...);
144   }
145
146   // Template specialization for arrays: recursively handle multi-dimensional arrays
147   template<typename T, size_t N, typename... Args>
148   int add(const SetRange& range, std::string&& names, T (&value)[N], Args&&... args) {
149     for (size_t i = 0; i < N; i++)
150         add(range, next(names, i == N - 1) + "[" + std::to_string(i) + "]", value[i]);
151     return add(range, std::move(names), args...);
152   }
153
154   // Template specialization for SetRange
155   template<typename... Args>
156   int add(const SetRange&, std::string&& names, SetRange& value, Args&&... args) {
157     return add(value, (next(names), std::move(names)), args...);
158   }
159
160   // Template specialization for BoolConditions
161   template<typename... Args>
162   int add(const SetRange& range, std::string&& names, BoolConditions& cond, Args&&... args) {
163     for (size_t size = cond.values.size(), i = 0; i < size; i++)
164         add(cond.range, next(names, i == size - 1) + "_" + std::to_string(i), cond.values[i]);
165     return add(range, std::move(names), args...);
166   }
167
168   std::vector<std::unique_ptr<EntryBase>> list;
169
170 public:
171   template<typename... Args>
172   static int add(const std::string& names, Args&&... args) {
173     return instance().add(SetDefaultRange, names.substr(1, names.size() - 2), args...); // Remove trailing parenthesis
174   }
175   static void init() { for (auto& e : instance().list) e->init_option(); read_options(); } // Deferred, due to UCI::Options access
176   static void read_options() { for (auto& e : instance().list) e->read_option(); }
177   static bool update_on_last;
178 };
179
180 // Some macro magic :-) we define a dummy int variable that compiler initializes calling Tune::add()
181 #define STRINGIFY(x) #x
182 #define UNIQUE2(x, y) x ## y
183 #define UNIQUE(x, y) UNIQUE2(x, y) // Two indirection levels to expand __LINE__
184 #define TUNE(...) int UNIQUE(p, __LINE__) = Tune::add(STRINGIFY((__VA_ARGS__)), __VA_ARGS__)
185
186 #define UPDATE_ON_LAST() bool UNIQUE(p, __LINE__) = Tune::update_on_last = true
187
188 // Some macro to tune toggling of boolean conditions
189 #define CONDITION(x) (Conditions.binary[__COUNTER__] || (x))
190 #define TUNE_CONDITIONS() int UNIQUE(c, __LINE__) = (Conditions.init(__COUNTER__), 0); \
191                           TUNE(Conditions, set_conditions)
192
193 #endif // #ifndef TUNE_H_INCLUDED