]> git.sesse.net Git - stockfish/blob - src/ucioption.cpp
Check bounds in set_option_value()
[stockfish] / src / ucioption.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2009 Marco Costalba
5
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   Stockfish is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20
21 ////
22 //// Includes
23 ////
24
25 #include <algorithm>
26 #include <cassert>
27 #include <map>
28 #include <string>
29 #include <sstream>
30 #include <vector>
31
32 #include "misc.h"
33 #include "thread.h"
34 #include "ucioption.h"
35
36 using std::string;
37
38 ////
39 //// Local definitions
40 ////
41
42 namespace {
43
44   ///
45   /// Types
46   ///
47
48   enum OptionType { SPIN, COMBO, CHECK, STRING, BUTTON };
49
50   typedef std::vector<string> ComboValues;
51
52   struct Option {
53
54     string name, defaultValue, currentValue;
55     OptionType type;
56     size_t idx;
57     int minValue, maxValue;
58     ComboValues comboValues;
59
60     Option();
61     Option(const char* defaultValue, OptionType = STRING);
62     Option(bool defaultValue, OptionType = CHECK);
63     Option(int defaultValue, int minValue, int maxValue);
64
65     bool operator<(const Option& o) const { return this->idx < o.idx; }
66   };
67
68   typedef std::map<string, Option> Options;
69
70   ///
71   /// Constants
72   ///
73
74   // load_defaults populates the options map with the hard
75   // coded names and default values.
76
77   void load_defaults(Options& o) {
78
79     o["Use Search Log"] = Option(false);
80     o["Search Log Filename"] = Option("SearchLog.txt");
81     o["Book File"] = Option("book.bin");
82     o["Mobility (Middle Game)"] = Option(100, 0, 200);
83     o["Mobility (Endgame)"] = Option(100, 0, 200);
84     o["Pawn Structure (Middle Game)"] = Option(100, 0, 200);
85     o["Pawn Structure (Endgame)"] = Option(100, 0, 200);
86     o["Passed Pawns (Middle Game)"] = Option(100, 0, 200);
87     o["Passed Pawns (Endgame)"] = Option(100, 0, 200);
88     o["Space"] = Option(100, 0, 200);
89     o["Aggressiveness"] = Option(100, 0, 200);
90     o["Cowardice"] = Option(100, 0, 200);
91     o["King Safety Curve"] = Option("Quadratic", COMBO);
92
93        o["King Safety Curve"].comboValues.push_back("Quadratic");
94        o["King Safety Curve"].comboValues.push_back("Linear");  /*, "From File"*/
95
96     o["King Safety Coefficient"] = Option(40, 1, 100);
97     o["King Safety X Intercept"] = Option(0, 0, 20);
98     o["King Safety Max Slope"] = Option(30, 10, 100);
99     o["King Safety Max Value"] = Option(500, 100, 1000);
100     o["Queen Contact Check Bonus"] = Option(3, 0, 8);
101     o["Queen Check Bonus"] = Option(2, 0, 4);
102     o["Rook Check Bonus"] = Option(1, 0, 4);
103     o["Bishop Check Bonus"] = Option(1, 0, 4);
104     o["Knight Check Bonus"] = Option(1, 0, 4);
105     o["Discovered Check Bonus"] = Option(3, 0, 8);
106     o["Mate Threat Bonus"] = Option(3, 0, 8);
107     o["Check Extension (PV nodes)"] = Option(2, 0, 2);
108     o["Check Extension (non-PV nodes)"] = Option(1, 0, 2);
109     o["Single Evasion Extension (PV nodes)"] = Option(2, 0, 2);
110     o["Single Evasion Extension (non-PV nodes)"] = Option(2, 0, 2);
111     o["Mate Threat Extension (PV nodes)"] = Option(0, 0, 2);
112     o["Mate Threat Extension (non-PV nodes)"] = Option(0, 0, 2);
113     o["Pawn Push to 7th Extension (PV nodes)"] = Option(1, 0, 2);
114     o["Pawn Push to 7th Extension (non-PV nodes)"] = Option(1, 0, 2);
115     o["Passed Pawn Extension (PV nodes)"] = Option(1, 0, 2);
116     o["Passed Pawn Extension (non-PV nodes)"] = Option(0, 0, 2);
117     o["Pawn Endgame Extension (PV nodes)"] = Option(2, 0, 2);
118     o["Pawn Endgame Extension (non-PV nodes)"] = Option(2, 0, 2);
119     o["Threat Depth"] = Option(5, 0, 100);
120     o["Randomness"] = Option(0, 0, 10);
121     o["Minimum Split Depth"] = Option(4, 4, 7);
122     o["Maximum Number of Threads per Split Point"] = Option(5, 4, 8);
123     o["Threads"] = Option(1, 1, THREAD_MAX);
124     o["Hash"] = Option(32, 4, 2048);
125     o["Clear Hash"] = Option(false, BUTTON);
126     o["New Game"] = Option(false, BUTTON);
127     o["Ponder"] = Option(true);
128     o["OwnBook"] = Option(true);
129     o["MultiPV"] = Option(1, 1, 500);
130     o["UCI_ShowCurrLine"] = Option(false);
131     o["UCI_Chess960"] = Option(false);
132     o["UCI_AnalyseMode"] = Option(false);
133
134     // Any option should know its name so to be easily printed
135     for (Options::iterator it = o.begin(); it != o.end(); ++it)
136         it->second.name = it->first;
137   }
138
139   ///
140   /// Variables
141   ///
142
143   Options options;
144
145   // stringify converts a value of type T to a std::string
146   template<typename T>
147   string stringify(const T& v) {
148
149      std::ostringstream ss;
150      ss << v;
151      return ss.str();
152   }
153
154
155   // get_option_value implements the various get_option_value_<type>
156   // functions defined later, because only the option value
157   // type changes a template seems a proper solution.
158
159   template<typename T>
160   T get_option_value(const string& optionName) {
161
162       T ret = T();
163       if (options.find(optionName) == options.end())
164           return ret;
165
166       std::istringstream ss(options[optionName].currentValue);
167       ss >> ret;
168       return ret;
169   }
170
171   // Specialization for std::string where instruction 'ss >> ret;'
172   // would erroneusly tokenize a string with spaces.
173
174   template<>
175   string get_option_value<string>(const string& optionName) {
176
177       if (options.find(optionName) == options.end())
178           return string();
179
180       return options[optionName].currentValue;
181   }
182
183 }
184
185 ////
186 //// Functions
187 ////
188
189 /// init_uci_options() initializes the UCI options.  Currently, the only
190 /// thing this function does is to initialize the default value of the
191 /// "Threads" parameter to the number of available CPU cores.
192
193 void init_uci_options() {
194
195   load_defaults(options);
196
197   // Set optimal value for parameter "Minimum Split Depth"
198   // according to number of available cores.
199   assert(options.find("Threads") != options.end());
200   assert(options.find("Minimum Split Depth") != options.end());
201
202   Option& thr = options["Threads"];
203   Option& msd = options["Minimum Split Depth"];
204
205   thr.defaultValue = thr.currentValue = stringify(cpu_count());
206
207   if (cpu_count() >= 8)
208       msd.defaultValue = msd.currentValue = stringify(7);
209 }
210
211
212 /// print_uci_options() prints all the UCI options to the standard output,
213 /// in the format defined by the UCI protocol.
214
215 void print_uci_options() {
216
217   static const char optionTypeName[][16] = {
218     "spin", "combo", "check", "string", "button"
219   };
220
221   // Build up a vector out of the options map and sort it according to idx
222   // field, that is the chronological insertion order in options map.
223   std::vector<Option> vec;
224   for (Options::const_iterator it = options.begin(); it != options.end(); ++it)
225       vec.push_back(it->second);
226
227   std::sort(vec.begin(), vec.end());
228
229   for (std::vector<Option>::const_iterator it = vec.begin(); it != vec.end(); ++it)
230   {
231       std::cout << "\noption name " << it->name
232                 << " type "         << optionTypeName[it->type];
233
234       if (it->type == BUTTON)
235           continue;
236
237       if (it->type == CHECK)
238           std::cout << " default " << (it->defaultValue == "1" ? "true" : "false");
239       else
240           std::cout << " default " << it->defaultValue;
241
242       if (it->type == SPIN)
243           std::cout << " min " << it->minValue << " max " << it->maxValue;
244       else if (it->type == COMBO)
245           for (ComboValues::const_iterator itc = it->comboValues.begin();
246               itc != it->comboValues.end(); ++itc)
247               std::cout << " var " << *itc;
248   }
249   std::cout << std::endl;
250 }
251
252
253 /// get_option_value_bool() returns the current value of a UCI parameter of
254 /// type "check".
255
256 bool get_option_value_bool(const string& optionName) {
257
258   return get_option_value<bool>(optionName);
259 }
260
261
262 /// get_option_value_int() returns the value of a UCI parameter as an integer.
263 /// Normally, this function will be used for a parameter of type "spin", but
264 /// it could also be used with a "combo" parameter, where all the available
265 /// values are integers.
266
267 int get_option_value_int(const string& optionName) {
268
269   return get_option_value<int>(optionName);
270 }
271
272
273 /// get_option_value_string() returns the current value of a UCI parameter as
274 /// a string. It is used with parameters of type "combo" and "string".
275
276 string get_option_value_string(const string& optionName) {
277
278    return get_option_value<string>(optionName);
279 }
280
281
282 /// set_option_value() inserts a new value for a UCI parameter. Note that
283 /// the function does not check that the new value is legal for the given
284 /// parameter: This is assumed to be the responsibility of the GUI.
285
286 void set_option_value(const string& name, const string& value) {
287
288   // UCI protocol uses "true" and "false" instead of "1" and "0", so convert
289   // value according to standard C++ convention before to store it.
290   string v(value);
291   if (v == "true")
292       v = "1";
293   else if (v == "false")
294       v = "0";
295
296   if (options.find(name) == options.end())
297   {
298       std::cout << "No such option: " << name << std::endl;
299       return;
300   }
301
302   // Normally it's up to the GUI to check for option's limits,
303   // but we could receive the new value directly from the user
304   // by teminal window. So let's check the bounds anyway.
305   Option& opt = options[name];
306
307   if (opt.type == CHECK && v != "0" && v != "1")
308       return;
309
310   else if (opt.type == SPIN)
311   {
312       int val = atoi(v.c_str());
313       if (val < opt.minValue || val > opt.maxValue)
314           return;
315   }
316
317   opt.currentValue = v;
318 }
319
320
321 /// push_button() is used to tell the engine that a UCI parameter of type
322 /// "button" has been selected:
323
324 void push_button(const string& buttonName) {
325
326   set_option_value(buttonName, "true");
327 }
328
329
330 /// button_was_pressed() tests whether a UCI parameter of type "button" has
331 /// been selected since the last time the function was called, in this case
332 /// it also resets the button.
333
334 bool button_was_pressed(const string& buttonName) {
335
336   if (!get_option_value<bool>(buttonName))
337       return false;
338
339   set_option_value(buttonName, "false");
340   return true;
341 }
342
343
344 namespace {
345
346   // Define constructors of Option class.
347
348   Option::Option() {} // To allow insertion in a std::map
349
350   Option::Option(const char* def, OptionType t)
351   : defaultValue(def), currentValue(def), type(t), idx(options.size()), minValue(0), maxValue(0) {}
352
353   Option::Option(bool def, OptionType t)
354   : defaultValue(stringify(def)), currentValue(stringify(def)), type(t), idx(options.size()), minValue(0), maxValue(0) {}
355
356   Option::Option(int def, int minv, int maxv)
357   : defaultValue(stringify(def)), currentValue(stringify(def)), type(SPIN), idx(options.size()), minValue(minv), maxValue(maxv) {}
358
359 }