]> git.sesse.net Git - stockfish/blob - src/uci.cpp
Set UCI_ShowWDL by default to false
[stockfish] / src / uci.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-2015 Marco Costalba, Joona Kiiski, Tord Romstad
5   Copyright (C) 2015-2020 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
6
7   Stockfish is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   Stockfish is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <cassert>
22 #include <cmath>
23 #include <iostream>
24 #include <sstream>
25 #include <string>
26
27 #include "evaluate.h"
28 #include "movegen.h"
29 #include "position.h"
30 #include "search.h"
31 #include "thread.h"
32 #include "timeman.h"
33 #include "tt.h"
34 #include "uci.h"
35 #include "syzygy/tbprobe.h"
36
37 using namespace std;
38
39 extern vector<string> setup_bench(const Position&, istream&);
40
41 namespace {
42
43   // FEN string of the initial position, normal chess
44   const char* StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
45
46
47   // position() is called when engine receives the "position" UCI command.
48   // The function sets up the position described in the given FEN string ("fen")
49   // or the starting position ("startpos") and then makes the moves given in the
50   // following move list ("moves").
51
52   void position(Position& pos, istringstream& is, StateListPtr& states) {
53
54     Move m;
55     string token, fen;
56
57     is >> token;
58
59     if (token == "startpos")
60     {
61         fen = StartFEN;
62         is >> token; // Consume "moves" token if any
63     }
64     else if (token == "fen")
65         while (is >> token && token != "moves")
66             fen += token + " ";
67     else
68         return;
69
70     states = StateListPtr(new std::deque<StateInfo>(1)); // Drop old and create a new one
71     pos.set(fen, Options["UCI_Chess960"], &states->back(), Threads.main());
72
73     // Parse move list (if any)
74     while (is >> token && (m = UCI::to_move(pos, token)) != MOVE_NONE)
75     {
76         states->emplace_back();
77         pos.do_move(m, states->back());
78     }
79   }
80
81
82   // setoption() is called when engine receives the "setoption" UCI command. The
83   // function updates the UCI option ("name") to the given value ("value").
84
85   void setoption(istringstream& is) {
86
87     string token, name, value;
88
89     is >> token; // Consume "name" token
90
91     // Read option name (can contain spaces)
92     while (is >> token && token != "value")
93         name += (name.empty() ? "" : " ") + token;
94
95     // Read option value (can contain spaces)
96     while (is >> token)
97         value += (value.empty() ? "" : " ") + token;
98
99     if (Options.count(name))
100         Options[name] = value;
101     else
102         sync_cout << "No such option: " << name << sync_endl;
103   }
104
105
106   // go() is called when engine receives the "go" UCI command. The function sets
107   // the thinking time and other parameters from the input string, then starts
108   // the search.
109
110   void go(Position& pos, istringstream& is, StateListPtr& states) {
111
112     Search::LimitsType limits;
113     string token;
114     bool ponderMode = false;
115
116     limits.startTime = now(); // As early as possible!
117
118     while (is >> token)
119         if (token == "searchmoves") // Needs to be the last command on the line
120             while (is >> token)
121                 limits.searchmoves.push_back(UCI::to_move(pos, token));
122
123         else if (token == "wtime")     is >> limits.time[WHITE];
124         else if (token == "btime")     is >> limits.time[BLACK];
125         else if (token == "winc")      is >> limits.inc[WHITE];
126         else if (token == "binc")      is >> limits.inc[BLACK];
127         else if (token == "movestogo") is >> limits.movestogo;
128         else if (token == "depth")     is >> limits.depth;
129         else if (token == "nodes")     is >> limits.nodes;
130         else if (token == "movetime")  is >> limits.movetime;
131         else if (token == "mate")      is >> limits.mate;
132         else if (token == "perft")     is >> limits.perft;
133         else if (token == "infinite")  limits.infinite = 1;
134         else if (token == "ponder")    ponderMode = true;
135
136     Threads.start_thinking(pos, states, limits, ponderMode);
137   }
138
139
140   // bench() is called when engine receives the "bench" command. Firstly
141   // a list of UCI commands is setup according to bench parameters, then
142   // it is run one by one printing a summary at the end.
143
144   void bench(Position& pos, istream& args, StateListPtr& states) {
145
146     string token;
147     uint64_t num, nodes = 0, cnt = 1;
148
149     vector<string> list = setup_bench(pos, args);
150     num = count_if(list.begin(), list.end(), [](string s) { return s.find("go ") == 0 || s.find("eval") == 0; });
151
152     TimePoint elapsed = now();
153
154     for (const auto& cmd : list)
155     {
156         istringstream is(cmd);
157         is >> skipws >> token;
158
159         if (token == "go" || token == "eval")
160         {
161             cerr << "\nPosition: " << cnt++ << '/' << num << endl;
162             if (token == "go")
163             {
164                go(pos, is, states);
165                Threads.main()->wait_for_search_finished();
166                nodes += Threads.nodes_searched();
167             }
168             else
169                sync_cout << "\n" << Eval::trace(pos) << sync_endl;
170         }
171         else if (token == "setoption")  setoption(is);
172         else if (token == "position")   position(pos, is, states);
173         else if (token == "ucinewgame") { Search::clear(); elapsed = now(); } // Search::clear() may take some while
174     }
175
176     elapsed = now() - elapsed + 1; // Ensure positivity to avoid a 'divide by zero'
177
178     dbg_print(); // Just before exiting
179
180     cerr << "\n==========================="
181          << "\nTotal time (ms) : " << elapsed
182          << "\nNodes searched  : " << nodes
183          << "\nNodes/second    : " << 1000 * nodes / elapsed << endl;
184   }
185
186   // The win rate model returns the probability (per mille) of winning given an eval
187   // and a game-ply. The model fits rather accurately the LTC fishtest statistics.
188   int win_rate_model(Value v, int ply) {
189
190      // The model captures only up to 240 plies, so limit input (and rescale)
191      double m = std::min(240, ply) / 64.0;
192
193      // Coefficients of a 3rd order polynomial fit based on fishtest data
194      // for two parameters needed to transform eval to the argument of a
195      // logistic function.
196      double as[] = {-8.24404295, 64.23892342, -95.73056462, 153.86478679};
197      double bs[] = {-3.37154371, 28.44489198, -56.67657741,  72.05858751};
198      double a = (((as[0] * m + as[1]) * m + as[2]) * m) + as[3];
199      double b = (((bs[0] * m + bs[1]) * m + bs[2]) * m) + bs[3];
200
201      // Transform eval to centipawns with limited range
202      double x = Utility::clamp(double(100 * v) / PawnValueEg, -1000.0, 1000.0);
203
204      // Return win rate in per mille (rounded to nearest)
205      return int(0.5 + 1000 / (1 + std::exp((a - x) / b)));
206   }
207
208 } // namespace
209
210
211 /// UCI::loop() waits for a command from stdin, parses it and calls the appropriate
212 /// function. Also intercepts EOF from stdin to ensure gracefully exiting if the
213 /// GUI dies unexpectedly. When called with some command line arguments, e.g. to
214 /// run 'bench', once the command is executed the function returns immediately.
215 /// In addition to the UCI ones, also some additional debug commands are supported.
216
217 void UCI::loop(int argc, char* argv[]) {
218
219   Position pos;
220   string token, cmd;
221   StateListPtr states(new std::deque<StateInfo>(1));
222
223   pos.set(StartFEN, false, &states->back(), Threads.main());
224
225   for (int i = 1; i < argc; ++i)
226       cmd += std::string(argv[i]) + " ";
227
228   do {
229       if (argc == 1 && !getline(cin, cmd)) // Block here waiting for input or EOF
230           cmd = "quit";
231
232       istringstream is(cmd);
233
234       token.clear(); // Avoid a stale if getline() returns empty or blank line
235       is >> skipws >> token;
236
237       if (    token == "quit"
238           ||  token == "stop")
239           Threads.stop = true;
240
241       // The GUI sends 'ponderhit' to tell us the user has played the expected move.
242       // So 'ponderhit' will be sent if we were told to ponder on the same move the
243       // user has played. We should continue searching but switch from pondering to
244       // normal search.
245       else if (token == "ponderhit")
246           Threads.main()->ponder = false; // Switch to normal search
247
248       else if (token == "uci")
249           sync_cout << "id name " << engine_info(true)
250                     << "\n"       << Options
251                     << "\nuciok"  << sync_endl;
252
253       else if (token == "setoption")  setoption(is);
254       else if (token == "go")         go(pos, is, states);
255       else if (token == "position")   position(pos, is, states);
256       else if (token == "ucinewgame") Search::clear();
257       else if (token == "isready")    sync_cout << "readyok" << sync_endl;
258
259       // Additional custom non-UCI commands, mainly for debugging.
260       // Do not use these commands during a search!
261       else if (token == "flip")     pos.flip();
262       else if (token == "bench")    bench(pos, is, states);
263       else if (token == "d")        sync_cout << pos << sync_endl;
264       else if (token == "eval")     sync_cout << Eval::trace(pos) << sync_endl;
265       else if (token == "compiler") sync_cout << compiler_info() << sync_endl;
266       else
267           sync_cout << "Unknown command: " << cmd << sync_endl;
268
269   } while (token != "quit" && argc == 1); // Command line args are one-shot
270 }
271
272
273 /// UCI::value() converts a Value to a string suitable for use with the UCI
274 /// protocol specification:
275 ///
276 /// cp <x>    The score from the engine's point of view in centipawns.
277 /// mate <y>  Mate in y moves, not plies. If the engine is getting mated
278 ///           use negative values for y.
279
280 string UCI::value(Value v) {
281
282   assert(-VALUE_INFINITE < v && v < VALUE_INFINITE);
283
284   stringstream ss;
285
286   if (abs(v) < VALUE_MATE_IN_MAX_PLY)
287       ss << "cp " << v * 100 / PawnValueEg;
288   else
289       ss << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
290
291   return ss.str();
292 }
293
294
295 /// UCI::wdl() report WDL statistics given an evaluation and a game ply, based on
296 /// data gathered for fishtest LTC games.
297
298 string UCI::wdl(Value v, int ply) {
299
300   stringstream ss;
301
302   int wdl_w = win_rate_model( v, ply);
303   int wdl_l = win_rate_model(-v, ply);
304   int wdl_d = 1000 - wdl_w - wdl_l;
305   ss << " wdl " << wdl_w << " " << wdl_d << " " << wdl_l;
306
307   return ss.str();
308 }
309
310
311 /// UCI::square() converts a Square to a string in algebraic notation (g1, a7, etc.)
312
313 std::string UCI::square(Square s) {
314   return std::string{ char('a' + file_of(s)), char('1' + rank_of(s)) };
315 }
316
317
318 /// UCI::move() converts a Move to a string in coordinate notation (g1f3, a7a8q).
319 /// The only special case is castling, where we print in the e1g1 notation in
320 /// normal chess mode, and in e1h1 notation in chess960 mode. Internally all
321 /// castling moves are always encoded as 'king captures rook'.
322
323 string UCI::move(Move m, bool chess960) {
324
325   Square from = from_sq(m);
326   Square to = to_sq(m);
327
328   if (m == MOVE_NONE)
329       return "(none)";
330
331   if (m == MOVE_NULL)
332       return "0000";
333
334   if (type_of(m) == CASTLING && !chess960)
335       to = make_square(to > from ? FILE_G : FILE_C, rank_of(from));
336
337   string move = UCI::square(from) + UCI::square(to);
338
339   if (type_of(m) == PROMOTION)
340       move += " pnbrqk"[promotion_type(m)];
341
342   return move;
343 }
344
345
346 /// UCI::to_move() converts a string representing a move in coordinate notation
347 /// (g1f3, a7a8q) to the corresponding legal Move, if any.
348
349 Move UCI::to_move(const Position& pos, string& str) {
350
351   if (str.length() == 5) // Junior could send promotion piece in uppercase
352       str[4] = char(tolower(str[4]));
353
354   for (const auto& m : MoveList<LEGAL>(pos))
355       if (str == UCI::move(m, pos.is_chess960()))
356           return m;
357
358   return MOVE_NONE;
359 }