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