2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2023 The Stockfish developers (see AUTHORS file)
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.
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.
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/>.
35 #include "benchmark.h"
39 #include "nnue/evaluate_nnue.h"
48 // FEN string for the initial position in standard chess
49 const char* StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
52 // position() is called when the engine receives the "position" UCI command.
53 // It sets up the position that is described in the given FEN string ("fen") or
54 // the initial position ("startpos") and then makes the moves given in the following
55 // move list ("moves").
57 void position(Position& pos, std::istringstream& is, StateListPtr& states) {
60 std::string token, fen;
64 if (token == "startpos")
67 is >> token; // Consume the "moves" token, if any
69 else if (token == "fen")
70 while (is >> token && token != "moves")
75 states = StateListPtr(new std::deque<StateInfo>(1)); // Drop the old state and create a new one
76 pos.set(fen, Options["UCI_Chess960"], &states->back(), Threads.main());
78 // Parse the move list, if any
79 while (is >> token && (m = UCI::to_move(pos, token)) != MOVE_NONE)
81 states->emplace_back();
82 pos.do_move(m, states->back());
86 // trace_eval() prints the evaluation of the current position, consistent with
87 // the UCI options set so far.
89 void trace_eval(Position& pos) {
91 StateListPtr states(new std::deque<StateInfo>(1));
93 p.set(pos.fen(), Options["UCI_Chess960"], &states->back(), Threads.main());
97 sync_cout << "\n" << Eval::trace(p) << sync_endl;
101 // setoption() is called when the engine receives the "setoption" UCI command.
102 // The function updates the UCI option ("name") to the given value ("value").
104 void setoption(std::istringstream& is) {
106 Threads.main()->wait_for_search_finished();
108 std::string token, name, value;
110 is >> token; // Consume the "name" token
112 // Read the option name (can contain spaces)
113 while (is >> token && token != "value")
114 name += (name.empty() ? "" : " ") + token;
116 // Read the option value (can contain spaces)
118 value += (value.empty() ? "" : " ") + token;
120 if (Options.count(name))
121 Options[name] = value;
123 sync_cout << "No such option: " << name << sync_endl;
127 // go() is called when the engine receives the "go" UCI command. The function
128 // sets the thinking time and other parameters from the input string, then starts
131 void go(Position& pos, std::istringstream& is, StateListPtr& states) {
133 Search::LimitsType limits;
135 bool ponderMode = false;
137 limits.startTime = now(); // The search starts as early as possible
140 if (token == "searchmoves") // Needs to be the last command on the line
142 limits.searchmoves.push_back(UCI::to_move(pos, token));
144 else if (token == "wtime")
145 is >> limits.time[WHITE];
146 else if (token == "btime")
147 is >> limits.time[BLACK];
148 else if (token == "winc")
149 is >> limits.inc[WHITE];
150 else if (token == "binc")
151 is >> limits.inc[BLACK];
152 else if (token == "movestogo")
153 is >> limits.movestogo;
154 else if (token == "depth")
156 else if (token == "nodes")
158 else if (token == "movetime")
159 is >> limits.movetime;
160 else if (token == "mate")
162 else if (token == "perft")
164 else if (token == "infinite")
166 else if (token == "ponder")
169 Threads.start_thinking(pos, states, limits, ponderMode);
173 // bench() is called when the engine receives the "bench" command.
174 // First, a list of UCI commands is set up according to the bench
175 // parameters, then it is run one by one, printing a summary at the end.
177 void bench(Position& pos, std::istream& args, StateListPtr& states) {
180 uint64_t num, nodes = 0, cnt = 1;
182 std::vector<std::string> list = setup_bench(pos, args);
183 num = count_if(list.begin(), list.end(),
184 [](const std::string& s) { return s.find("go ") == 0 || s.find("eval") == 0; });
186 TimePoint elapsed = now();
188 for (const auto& cmd : list)
190 std::istringstream is(cmd);
191 is >> std::skipws >> token;
193 if (token == "go" || token == "eval")
195 std::cerr << "\nPosition: " << cnt++ << '/' << num << " (" << pos.fen() << ")"
200 Threads.main()->wait_for_search_finished();
201 nodes += Threads.nodes_searched();
206 else if (token == "setoption")
208 else if (token == "position")
209 position(pos, is, states);
210 else if (token == "ucinewgame")
214 } // Search::clear() may take a while
217 elapsed = now() - elapsed + 1; // Ensure positivity to avoid a 'divide by zero'
221 std::cerr << "\n==========================="
222 << "\nTotal time (ms) : " << elapsed << "\nNodes searched : " << nodes
223 << "\nNodes/second : " << 1000 * nodes / elapsed << std::endl;
226 // The win rate model returns the probability of winning (in per mille units) given an
227 // eval and a game ply. It fits the LTC fishtest statistics rather accurately.
228 int win_rate_model(Value v, int ply) {
230 // The model only captures up to 240 plies, so limit the input and then rescale
231 double m = std::min(240, ply) / 64.0;
233 // The coefficients of a third-order polynomial fit is based on the fishtest data
234 // for two parameters that need to transform eval to the argument of a logistic
236 constexpr double as[] = {0.38036525, -2.82015070, 23.17882135, 307.36768407};
237 constexpr double bs[] = {-2.29434733, 13.27689788, -14.26828904, 63.45318330};
239 // Enforce that NormalizeToPawnValue corresponds to a 50% win rate at ply 64
240 static_assert(UCI::NormalizeToPawnValue == int(as[0] + as[1] + as[2] + as[3]));
242 double a = (((as[0] * m + as[1]) * m + as[2]) * m) + as[3];
243 double b = (((bs[0] * m + bs[1]) * m + bs[2]) * m) + bs[3];
245 // Transform the eval to centipawns with limited range
246 double x = std::clamp(double(v), -4000.0, 4000.0);
248 // Return the win rate in per mille units, rounded to the nearest integer
249 return int(0.5 + 1000 / (1 + std::exp((a - x) / b)));
255 // UCI::loop() waits for a command from the stdin, parses it, and then calls the appropriate
256 // function. It also intercepts an end-of-file (EOF) indication from the stdin to ensure a
257 // graceful exit if the GUI dies unexpectedly. When called with some command-line arguments,
258 // like running 'bench', the function returns immediately after the command is executed.
259 // In addition to the UCI ones, some additional debug commands are also supported.
261 void UCI::loop(int argc, char* argv[]) {
264 std::string token, cmd;
265 StateListPtr states(new std::deque<StateInfo>(1));
267 pos.set(StartFEN, false, &states->back(), Threads.main());
269 for (int i = 1; i < argc; ++i)
270 cmd += std::string(argv[i]) + " ";
275 && !getline(std::cin, cmd)) // Wait for an input or an end-of-file (EOF) indication
278 std::istringstream is(cmd);
280 token.clear(); // Avoid a stale if getline() returns nothing or a blank line
281 is >> std::skipws >> token;
283 if (token == "quit" || token == "stop")
286 // The GUI sends 'ponderhit' to tell that the user has played the expected move.
287 // So, 'ponderhit' is sent if pondering was done on the same move that the user
288 // has played. The search should continue, but should also switch from pondering
289 // to the normal search.
290 else if (token == "ponderhit")
291 Threads.main()->ponder = false; // Switch to the normal search
293 else if (token == "uci")
294 sync_cout << "id name " << engine_info(true) << "\n"
295 << Options << "\nuciok" << sync_endl;
297 else if (token == "setoption")
299 else if (token == "go")
301 else if (token == "position")
302 position(pos, is, states);
303 else if (token == "ucinewgame")
305 else if (token == "isready")
306 sync_cout << "readyok" << sync_endl;
308 // Add custom non-UCI commands, mainly for debugging purposes.
309 // These commands must not be used during a search!
310 else if (token == "flip")
312 else if (token == "bench")
313 bench(pos, is, states);
314 else if (token == "d")
315 sync_cout << pos << sync_endl;
316 else if (token == "eval")
318 else if (token == "compiler")
319 sync_cout << compiler_info() << sync_endl;
320 else if (token == "export_net")
322 std::optional<std::string> filename;
324 if (is >> std::skipws >> f)
326 Eval::NNUE::save_eval(filename);
328 else if (token == "--help" || token == "help" || token == "--license" || token == "license")
330 << "\nStockfish is a powerful chess engine for playing and analyzing."
331 "\nIt is released as free software licensed under the GNU GPLv3 License."
332 "\nStockfish is normally used with a graphical user interface (GUI) and implements"
333 "\nthe Universal Chess Interface (UCI) protocol to communicate with a GUI, an API, etc."
334 "\nFor any further information, visit https://github.com/official-stockfish/Stockfish#readme"
335 "\nor read the corresponding README.md and Copying.txt files distributed along with this program.\n"
337 else if (!token.empty() && token[0] != '#')
338 sync_cout << "Unknown command: '" << cmd << "'. Type help for more information."
341 } while (token != "quit" && argc == 1); // The command-line arguments are one-shot
345 // Turns a Value to an integer centipawn number,
346 // without treatment of mate and similar special scores.
347 int UCI::to_cp(Value v) { return 100 * v / UCI::NormalizeToPawnValue; }
349 // UCI::value() converts a Value to a string by adhering to the UCI protocol specification:
351 // cp <x> The score from the engine's point of view in centipawns.
352 // mate <y> Mate in 'y' moves (not plies). If the engine is getting mated,
353 // uses negative values for 'y'.
355 std::string UCI::value(Value v) {
357 assert(-VALUE_INFINITE < v && v < VALUE_INFINITE);
359 std::stringstream ss;
361 if (abs(v) < VALUE_TB_WIN_IN_MAX_PLY)
362 ss << "cp " << UCI::to_cp(v);
363 else if (abs(v) < VALUE_MATE_IN_MAX_PLY)
365 const int ply = VALUE_MATE_IN_MAX_PLY - 1 - std::abs(v); // recompute ss->ply
366 ss << "cp " << (v > 0 ? 20000 - ply : -20000 + ply);
369 ss << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
375 // UCI::wdl() reports the win-draw-loss (WDL) statistics given an evaluation
376 // and a game ply based on the data gathered for fishtest LTC games.
378 std::string UCI::wdl(Value v, int ply) {
380 std::stringstream ss;
382 int wdl_w = win_rate_model(v, ply);
383 int wdl_l = win_rate_model(-v, ply);
384 int wdl_d = 1000 - wdl_w - wdl_l;
385 ss << " wdl " << wdl_w << " " << wdl_d << " " << wdl_l;
391 // UCI::square() converts a Square to a string in algebraic notation (g1, a7, etc.)
393 std::string UCI::square(Square s) {
394 return std::string{char('a' + file_of(s)), char('1' + rank_of(s))};
398 // UCI::move() converts a Move to a string in coordinate notation (g1f3, a7a8q).
399 // The only special case is castling where the e1g1 notation is printed in
400 // standard chess mode and in e1h1 notation it is printed in Chess960 mode.
401 // Internally, all castling moves are always encoded as 'king captures rook'.
403 std::string UCI::move(Move m, bool chess960) {
411 Square from = from_sq(m);
412 Square to = to_sq(m);
414 if (type_of(m) == CASTLING && !chess960)
415 to = make_square(to > from ? FILE_G : FILE_C, rank_of(from));
417 std::string move = UCI::square(from) + UCI::square(to);
419 if (type_of(m) == PROMOTION)
420 move += " pnbrqk"[promotion_type(m)];
426 // UCI::to_move() converts a string representing a move in coordinate notation
427 // (g1f3, a7a8q) to the corresponding legal Move, if any.
429 Move UCI::to_move(const Position& pos, std::string& str) {
431 if (str.length() == 5)
432 str[4] = char(tolower(str[4])); // The promotion piece character must be lowercased
434 for (const auto& m : MoveList<LEGAL>(pos))
435 if (str == UCI::move(m, pos.is_chess960()))
441 } // namespace Stockfish