]> git.sesse.net Git - stockfish/blob - src/uci.cpp
Cleanup includes
[stockfish] / src / uci.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2023 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 "uci.h"
20
21 #include <algorithm>
22 #include <cassert>
23 #include <cctype>
24 #include <cmath>
25 #include <cstdint>
26 #include <cstdlib>
27 #include <deque>
28 #include <iostream>
29 #include <memory>
30 #include <optional>
31 #include <sstream>
32 #include <string>
33 #include <vector>
34
35 #include "benchmark.h"
36 #include "evaluate.h"
37 #include "misc.h"
38 #include "movegen.h"
39 #include "nnue/evaluate_nnue.h"
40 #include "position.h"
41 #include "search.h"
42 #include "thread.h"
43
44 using namespace std;
45
46 namespace Stockfish {
47
48 namespace {
49
50   // FEN string for the initial position in standard chess
51   const char* StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
52
53
54   // position() is called when the engine receives the "position" UCI command.
55   // It sets up the position that is described in the given FEN string ("fen") or
56   // the initial position ("startpos") and then makes the moves given in the following
57   // move list ("moves").
58
59   void position(Position& pos, istringstream& is, StateListPtr& states) {
60
61     Move m;
62     string token, fen;
63
64     is >> token;
65
66     if (token == "startpos")
67     {
68         fen = StartFEN;
69         is >> token; // Consume the "moves" token, if any
70     }
71     else if (token == "fen")
72         while (is >> token && token != "moves")
73             fen += token + " ";
74     else
75         return;
76
77     states = StateListPtr(new std::deque<StateInfo>(1)); // Drop the old state and create a new one
78     pos.set(fen, Options["UCI_Chess960"], &states->back(), Threads.main());
79
80     // Parse the move list, if any
81     while (is >> token && (m = UCI::to_move(pos, token)) != MOVE_NONE)
82     {
83         states->emplace_back();
84         pos.do_move(m, states->back());
85     }
86   }
87
88   // trace_eval() prints the evaluation of the current position, consistent with
89   // the UCI options set so far.
90
91   void trace_eval(Position& pos) {
92
93     StateListPtr states(new std::deque<StateInfo>(1));
94     Position p;
95     p.set(pos.fen(), Options["UCI_Chess960"], &states->back(), Threads.main());
96
97     Eval::NNUE::verify();
98
99     sync_cout << "\n" << Eval::trace(p) << sync_endl;
100   }
101
102
103   // setoption() is called when the engine receives the "setoption" UCI command.
104   // The function updates the UCI option ("name") to the given value ("value").
105
106   void setoption(istringstream& is) {
107
108     Threads.main()->wait_for_search_finished();
109
110     string token, name, value;
111
112     is >> token; // Consume the "name" token
113
114     // Read the option name (can contain spaces)
115     while (is >> token && token != "value")
116         name += (name.empty() ? "" : " ") + token;
117
118     // Read the option value (can contain spaces)
119     while (is >> token)
120         value += (value.empty() ? "" : " ") + token;
121
122     if (Options.count(name))
123         Options[name] = value;
124     else
125         sync_cout << "No such option: " << name << sync_endl;
126   }
127
128
129   // go() is called when the engine receives the "go" UCI command. The function
130   // sets the thinking time and other parameters from the input string, then starts
131   // with a search.
132
133   void go(Position& pos, istringstream& is, StateListPtr& states) {
134
135     Search::LimitsType limits;
136     string token;
137     bool ponderMode = false;
138
139     limits.startTime = now(); // The search starts as early as possible
140
141     while (is >> token)
142         if (token == "searchmoves") // Needs to be the last command on the line
143             while (is >> token)
144                 limits.searchmoves.push_back(UCI::to_move(pos, token));
145
146         else if (token == "wtime")     is >> limits.time[WHITE];
147         else if (token == "btime")     is >> limits.time[BLACK];
148         else if (token == "winc")      is >> limits.inc[WHITE];
149         else if (token == "binc")      is >> limits.inc[BLACK];
150         else if (token == "movestogo") is >> limits.movestogo;
151         else if (token == "depth")     is >> limits.depth;
152         else if (token == "nodes")     is >> limits.nodes;
153         else if (token == "movetime")  is >> limits.movetime;
154         else if (token == "mate")      is >> limits.mate;
155         else if (token == "perft")     is >> limits.perft;
156         else if (token == "infinite")  limits.infinite = 1;
157         else if (token == "ponder")    ponderMode = true;
158
159     Threads.start_thinking(pos, states, limits, ponderMode);
160   }
161
162
163   // bench() is called when the engine receives the "bench" command.
164   // Firstly, a list of UCI commands is set up according to the bench
165   // parameters, then it is run one by one, printing a summary at the end.
166
167   void bench(Position& pos, istream& args, StateListPtr& states) {
168
169     string token;
170     uint64_t num, nodes = 0, cnt = 1;
171
172     vector<string> list = setup_bench(pos, args);
173     num = count_if(list.begin(), list.end(), [](const string& s) { return s.find("go ") == 0 || s.find("eval") == 0; });
174
175     TimePoint elapsed = now();
176
177     for (const auto& cmd : list)
178     {
179         istringstream is(cmd);
180         is >> skipws >> token;
181
182         if (token == "go" || token == "eval")
183         {
184             cerr << "\nPosition: " << cnt++ << '/' << num << " (" << pos.fen() << ")" << endl;
185             if (token == "go")
186             {
187                go(pos, is, states);
188                Threads.main()->wait_for_search_finished();
189                nodes += Threads.nodes_searched();
190             }
191             else
192                trace_eval(pos);
193         }
194         else if (token == "setoption")  setoption(is);
195         else if (token == "position")   position(pos, is, states);
196         else if (token == "ucinewgame") { Search::clear(); elapsed = now(); } // Search::clear() may take a while
197     }
198
199     elapsed = now() - elapsed + 1; // Ensure positivity to avoid a 'divide by zero'
200
201     dbg_print();
202
203     cerr << "\n==========================="
204          << "\nTotal time (ms) : " << elapsed
205          << "\nNodes searched  : " << nodes
206          << "\nNodes/second    : " << 1000 * nodes / elapsed << endl;
207   }
208
209   // The win rate model returns the probability of winning (in per mille units) given an
210   // eval and a game ply. It fits the LTC fishtest statistics rather accurately.
211   int win_rate_model(Value v, int ply) {
212
213      // The model only captures up to 240 plies, so limit the input and then rescale
214      double m = std::min(240, ply) / 64.0;
215
216      // The coefficients of a third-order polynomial fit is based on the fishtest data
217      // for two parameters that need to transform eval to the argument of a logistic
218      // function.
219      constexpr double as[] = {   0.38036525,   -2.82015070,   23.17882135,  307.36768407};
220      constexpr double bs[] = {  -2.29434733,   13.27689788,  -14.26828904,   63.45318330 };
221
222      // Enforce that NormalizeToPawnValue corresponds to a 50% win rate at ply 64
223      static_assert(UCI::NormalizeToPawnValue == int(as[0] + as[1] + as[2] + as[3]));
224
225      double a = (((as[0] * m + as[1]) * m + as[2]) * m) + as[3];
226      double b = (((bs[0] * m + bs[1]) * m + bs[2]) * m) + bs[3];
227
228      // Transform the eval to centipawns with limited range
229      double x = std::clamp(double(v), -4000.0, 4000.0);
230
231      // Return the win rate in per mille units rounded to the nearest value
232      return int(0.5 + 1000 / (1 + std::exp((a - x) / b)));
233   }
234
235 } // namespace
236
237
238 /// UCI::loop() waits for a command from the stdin, parses it and then calls the appropriate
239 /// function. It also intercepts an end-of-file (EOF) indication from the stdin to ensure a
240 /// graceful exit if the GUI dies unexpectedly. When called with some command-line arguments,
241 /// like running 'bench', the function returns immediately after the command is executed.
242 /// In addition to the UCI ones, some additional debug commands are also supported.
243
244 void UCI::loop(int argc, char* argv[]) {
245
246   Position pos;
247   string token, cmd;
248   StateListPtr states(new std::deque<StateInfo>(1));
249
250   pos.set(StartFEN, false, &states->back(), Threads.main());
251
252   for (int i = 1; i < argc; ++i)
253       cmd += std::string(argv[i]) + " ";
254
255   do {
256       if (argc == 1 && !getline(cin, cmd)) // Wait for an input or an end-of-file (EOF) indication
257           cmd = "quit";
258
259       istringstream is(cmd);
260
261       token.clear(); // Avoid a stale if getline() returns nothing or a blank line
262       is >> skipws >> token;
263
264       if (    token == "quit"
265           ||  token == "stop")
266           Threads.stop = true;
267
268       // The GUI sends 'ponderhit' to tell that the user has played the expected move.
269       // So, 'ponderhit' is sent if pondering was done on the same move that the user
270       // has played. The search should continue, but should also switch from pondering
271       // to the normal search.
272       else if (token == "ponderhit")
273           Threads.main()->ponder = false; // Switch to the normal search
274
275       else if (token == "uci")
276           sync_cout << "id name " << engine_info(true)
277                     << "\n"       << Options
278                     << "\nuciok"  << sync_endl;
279
280       else if (token == "setoption")  setoption(is);
281       else if (token == "go")         go(pos, is, states);
282       else if (token == "position")   position(pos, is, states);
283       else if (token == "ucinewgame") Search::clear();
284       else if (token == "isready")    sync_cout << "readyok" << sync_endl;
285
286       // Add custom non-UCI commands, mainly for debugging purposes.
287       // These commands must not be used during a search!
288       else if (token == "flip")     pos.flip();
289       else if (token == "bench")    bench(pos, is, states);
290       else if (token == "d")        sync_cout << pos << sync_endl;
291       else if (token == "eval")     trace_eval(pos);
292       else if (token == "compiler") sync_cout << compiler_info() << sync_endl;
293       else if (token == "export_net")
294       {
295           std::optional<std::string> filename;
296           std::string f;
297           if (is >> skipws >> f)
298               filename = f;
299           Eval::NNUE::save_eval(filename);
300       }
301       else if (token == "--help" || token == "help" || token == "--license" || token == "license")
302           sync_cout << "\nStockfish is a powerful chess engine for playing and analyzing."
303                        "\nIt is released as free software licensed under the GNU GPLv3 License."
304                        "\nStockfish is normally used with a graphical user interface (GUI) and implements"
305                        "\nthe Universal Chess Interface (UCI) protocol to communicate with a GUI, an API, etc."
306                        "\nFor any further information, visit https://github.com/official-stockfish/Stockfish#readme"
307                        "\nor read the corresponding README.md and Copying.txt files distributed along with this program.\n" << sync_endl;
308       else if (!token.empty() && token[0] != '#')
309           sync_cout << "Unknown command: '" << cmd << "'. Type help for more information." << sync_endl;
310
311   } while (token != "quit" && argc == 1); // The command-line arguments are one-shot
312 }
313
314
315 /// Turns a Value to an integer centipawn number,
316 /// without treatment of mate and similar special scores.
317 int UCI::to_cp(Value v) {
318
319   return 100 * v / UCI::NormalizeToPawnValue;
320 }
321
322 /// UCI::value() converts a Value to a string by adhering to the UCI protocol specification:
323 ///
324 /// cp <x>    The score from the engine's point of view in centipawns.
325 /// mate <y>  Mate in 'y' moves (not plies). If the engine is getting mated,
326 ///           uses negative values for 'y'.
327
328 string UCI::value(Value v) {
329
330   assert(-VALUE_INFINITE < v && v < VALUE_INFINITE);
331
332   stringstream ss;
333
334   if (abs(v) < VALUE_TB_WIN_IN_MAX_PLY)
335       ss << "cp " << UCI::to_cp(v);
336   else if (abs(v) < VALUE_MATE_IN_MAX_PLY)
337   {
338       const int ply = VALUE_MATE_IN_MAX_PLY - 1 - std::abs(v);  // recompute ss->ply
339       ss << "cp " << (v > 0 ? 20000 - ply : -20000 + ply);
340   }
341   else
342       ss << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
343
344   return ss.str();
345 }
346
347
348 /// UCI::wdl() reports the win-draw-loss (WDL) statistics given an evaluation
349 /// and a game ply based on the data gathered for fishtest LTC games.
350
351 string UCI::wdl(Value v, int ply) {
352
353   stringstream ss;
354
355   int wdl_w = win_rate_model( v, ply);
356   int wdl_l = win_rate_model(-v, ply);
357   int wdl_d = 1000 - wdl_w - wdl_l;
358   ss << " wdl " << wdl_w << " " << wdl_d << " " << wdl_l;
359
360   return ss.str();
361 }
362
363
364 /// UCI::square() converts a Square to a string in algebraic notation (g1, a7, etc.)
365
366 std::string UCI::square(Square s) {
367   return std::string{ char('a' + file_of(s)), char('1' + rank_of(s)) };
368 }
369
370
371 /// UCI::move() converts a Move to a string in coordinate notation (g1f3, a7a8q).
372 /// The only special case is castling where the e1g1 notation is printed in
373 /// standard chess mode and in e1h1 notation it is printed in Chess960 mode.
374 /// Internally, all castling moves are always encoded as 'king captures rook'.
375
376 string UCI::move(Move m, bool chess960) {
377
378   if (m == MOVE_NONE)
379       return "(none)";
380
381   if (m == MOVE_NULL)
382       return "0000";
383
384   Square from = from_sq(m);
385   Square to = to_sq(m);
386
387   if (type_of(m) == CASTLING && !chess960)
388       to = make_square(to > from ? FILE_G : FILE_C, rank_of(from));
389
390   string move = UCI::square(from) + UCI::square(to);
391
392   if (type_of(m) == PROMOTION)
393       move += " pnbrqk"[promotion_type(m)];
394
395   return move;
396 }
397
398
399 /// UCI::to_move() converts a string representing a move in coordinate notation
400 /// (g1f3, a7a8q) to the corresponding legal Move, if any.
401
402 Move UCI::to_move(const Position& pos, string& str) {
403
404   if (str.length() == 5)
405       str[4] = char(tolower(str[4])); // The promotion piece character must be lowercased
406
407   for (const auto& m : MoveList<LEGAL>(pos))
408       if (str == UCI::move(m, pos.is_chess960()))
409           return m;
410
411   return MOVE_NONE;
412 }
413
414 } // namespace Stockfish