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