2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2021 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/>.
34 #include "syzygy/tbprobe.h"
40 extern vector<string> setup_bench(const Position&, istream&);
44 // FEN string of the initial position, normal chess
45 const char* StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
48 // position() is called when engine receives the "position" UCI command.
49 // The function sets up the position described in the given FEN string ("fen")
50 // or the starting position ("startpos") and then makes the moves given in the
51 // following move list ("moves").
53 void position(Position& pos, istringstream& is, StateListPtr& states) {
60 if (token == "startpos")
63 is >> token; // Consume "moves" token if any
65 else if (token == "fen")
66 while (is >> token && token != "moves")
71 states = StateListPtr(new std::deque<StateInfo>(1)); // Drop old and create a new one
72 pos.set(fen, Options["UCI_Chess960"], &states->back(), Threads.main());
74 // Parse move list (if any)
75 while (is >> token && (m = UCI::to_move(pos, token)) != MOVE_NONE)
77 states->emplace_back();
78 pos.do_move(m, states->back());
82 // trace_eval() prints the evaluation for the current position, consistent with the UCI
83 // options set so far.
85 void trace_eval(Position& pos) {
87 StateListPtr states(new std::deque<StateInfo>(1));
89 p.set(pos.fen(), Options["UCI_Chess960"], &states->back(), Threads.main());
93 sync_cout << "\n" << Eval::trace(p) << sync_endl;
97 // setoption() is called when engine receives the "setoption" UCI command. The
98 // function updates the UCI option ("name") to the given value ("value").
100 void setoption(istringstream& is) {
102 string token, name, value;
104 is >> token; // Consume "name" token
106 // Read option name (can contain spaces)
107 while (is >> token && token != "value")
108 name += (name.empty() ? "" : " ") + token;
110 // Read option value (can contain spaces)
112 value += (value.empty() ? "" : " ") + token;
114 if (Options.count(name))
115 Options[name] = value;
116 else if (Cluster::is_root())
117 sync_cout << "No such option: " << name << sync_endl;
121 // go() is called when engine receives the "go" UCI command. The function sets
122 // the thinking time and other parameters from the input string, then starts
125 void go(Position& pos, istringstream& is, StateListPtr& states) {
127 Search::LimitsType limits;
129 bool ponderMode = false;
131 limits.startTime = now(); // As early as possible!
134 if (token == "searchmoves") // Needs to be the last command on the line
136 limits.searchmoves.push_back(UCI::to_move(pos, token));
138 else if (token == "wtime") is >> limits.time[WHITE];
139 else if (token == "btime") is >> limits.time[BLACK];
140 else if (token == "winc") is >> limits.inc[WHITE];
141 else if (token == "binc") is >> limits.inc[BLACK];
142 else if (token == "movestogo") is >> limits.movestogo;
143 else if (token == "depth") is >> limits.depth;
144 else if (token == "nodes") is >> limits.nodes;
145 else if (token == "movetime") is >> limits.movetime;
146 else if (token == "mate") is >> limits.mate;
147 else if (token == "perft") is >> limits.perft;
148 else if (token == "infinite") limits.infinite = 1;
149 else if (token == "ponder") ponderMode = true;
151 Threads.start_thinking(pos, states, limits, ponderMode);
155 // bench() is called when engine receives the "bench" command. Firstly
156 // a list of UCI commands is setup according to bench parameters, then
157 // it is run one by one printing a summary at the end.
159 void bench(Position& pos, istream& args, StateListPtr& states) {
162 uint64_t num, nodes = 0, cnt = 1;
164 vector<string> list = setup_bench(pos, args);
165 num = count_if(list.begin(), list.end(), [](string s) { return s.find("go ") == 0 || s.find("eval") == 0; });
167 TimePoint elapsed = now();
169 for (const auto& cmd : list)
171 istringstream is(cmd);
172 is >> skipws >> token;
174 if (token == "go" || token == "eval")
176 if (Cluster::is_root())
177 cerr << "\nPosition: " << cnt++ << '/' << num << " (" << pos.fen() << ")" << endl;
182 Threads.main()->wait_for_search_finished();
183 nodes += Threads.nodes_searched();
185 else if (Cluster::is_root())
188 else if (token == "setoption") setoption(is);
189 else if (token == "position") position(pos, is, states);
190 else if (token == "ucinewgame") { Search::clear(); elapsed = now(); } // Search::clear() may take some while
193 elapsed = now() - elapsed + 1; // Ensure positivity to avoid a 'divide by zero'
195 dbg_print(); // Just before exiting
197 if (Cluster::is_root())
198 cerr << "\n==========================="
199 << "\nTotal time (ms) : " << elapsed
200 << "\nNodes searched : " << nodes
201 << "\nNodes/second : " << 1000 * nodes / elapsed << endl;
204 // The win rate model returns the probability (per mille) of winning given an eval
205 // and a game-ply. The model fits rather accurately the LTC fishtest statistics.
206 int win_rate_model(Value v, int ply) {
208 // The model captures only up to 240 plies, so limit input (and rescale)
209 double m = std::min(240, ply) / 64.0;
211 // Coefficients of a 3rd order polynomial fit based on fishtest data
212 // for two parameters needed to transform eval to the argument of a
213 // logistic function.
214 double as[] = {-3.68389304, 30.07065921, -60.52878723, 149.53378557};
215 double bs[] = {-2.0181857, 15.85685038, -29.83452023, 47.59078827};
216 double a = (((as[0] * m + as[1]) * m + as[2]) * m) + as[3];
217 double b = (((bs[0] * m + bs[1]) * m + bs[2]) * m) + bs[3];
219 // Transform eval to centipawns with limited range
220 double x = std::clamp(double(100 * v) / PawnValueEg, -2000.0, 2000.0);
222 // Return win rate in per mille (rounded to nearest)
223 return int(0.5 + 1000 / (1 + std::exp((a - x) / b)));
229 /// UCI::loop() waits for a command from stdin, parses it and calls the appropriate
230 /// function. Also intercepts EOF from stdin to ensure gracefully exiting if the
231 /// GUI dies unexpectedly. When called with some command line arguments, e.g. to
232 /// run 'bench', once the command is executed the function returns immediately.
233 /// In addition to the UCI ones, also some additional debug commands are supported.
235 void UCI::loop(int argc, char* argv[]) {
239 StateListPtr states(new std::deque<StateInfo>(1));
241 pos.set(StartFEN, false, &states->back(), Threads.main());
243 for (int i = 1; i < argc; ++i)
244 cmd += std::string(argv[i]) + " ";
247 if (argc == 1 && !Cluster::getline(cin, cmd)) // Block here waiting for input or EOF
250 istringstream is(cmd);
252 token.clear(); // Avoid a stale if getline() returns empty or blank line
253 is >> skipws >> token;
259 // The GUI sends 'ponderhit' to tell us the user has played the expected move.
260 // So 'ponderhit' will be sent if we were told to ponder on the same move the
261 // user has played. We should continue searching but switch from pondering to
263 else if (token == "ponderhit")
264 Threads.main()->ponder = false; // Switch to normal search
266 else if (token == "uci" && Cluster::is_root())
267 sync_cout << "id name " << engine_info(true)
269 << "\nuciok" << sync_endl;
271 else if (token == "setoption") setoption(is);
272 else if (token == "go") go(pos, is, states);
273 else if (token == "position") position(pos, is, states);
274 else if (token == "ucinewgame") Search::clear();
275 else if (token == "isready" && Cluster::is_root())
276 sync_cout << "readyok" << sync_endl;
278 // Additional custom non-UCI commands, mainly for debugging.
279 // Do not use these commands during a search!
280 else if (token == "flip") pos.flip();
281 else if (token == "bench") bench(pos, is, states);
282 else if (token == "d" && Cluster::is_root())
283 sync_cout << pos << sync_endl;
284 else if (token == "eval" && Cluster::is_root())
286 else if (token == "compiler" && Cluster::is_root())
287 sync_cout << compiler_info() << sync_endl;
288 else if (token == "export_net" && Cluster::is_root())
290 std::optional<std::string> filename;
292 if (is >> skipws >> f)
294 Eval::NNUE::save_eval(filename);
296 else if (!token.empty() && token[0] != '#' && Cluster::is_root())
297 sync_cout << "Unknown command: " << cmd << sync_endl;
299 } while (token != "quit" && argc == 1); // Command line args are one-shot
303 /// UCI::value() converts a Value to a string suitable for use with the UCI
304 /// protocol specification:
306 /// cp <x> The score from the engine's point of view in centipawns.
307 /// mate <y> Mate in y moves, not plies. If the engine is getting mated
308 /// use negative values for y.
310 string UCI::value(Value v) {
312 assert(-VALUE_INFINITE < v && v < VALUE_INFINITE);
316 if (abs(v) < VALUE_MATE_IN_MAX_PLY)
317 ss << "cp " << v * 100 / PawnValueEg;
319 ss << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
325 /// UCI::wdl() report WDL statistics given an evaluation and a game ply, based on
326 /// data gathered for fishtest LTC games.
328 string UCI::wdl(Value v, int ply) {
332 int wdl_w = win_rate_model( v, ply);
333 int wdl_l = win_rate_model(-v, ply);
334 int wdl_d = 1000 - wdl_w - wdl_l;
335 ss << " wdl " << wdl_w << " " << wdl_d << " " << wdl_l;
341 /// UCI::square() converts a Square to a string in algebraic notation (g1, a7, etc.)
343 std::string UCI::square(Square s) {
344 return std::string{ char('a' + file_of(s)), char('1' + rank_of(s)) };
348 /// UCI::move() converts a Move to a string in coordinate notation (g1f3, a7a8q).
349 /// The only special case is castling, where we print in the e1g1 notation in
350 /// normal chess mode, and in e1h1 notation in chess960 mode. Internally all
351 /// castling moves are always encoded as 'king captures rook'.
353 string UCI::move(Move m, bool chess960) {
355 Square from = from_sq(m);
356 Square to = to_sq(m);
364 if (type_of(m) == CASTLING && !chess960)
365 to = make_square(to > from ? FILE_G : FILE_C, rank_of(from));
367 string move = UCI::square(from) + UCI::square(to);
369 if (type_of(m) == PROMOTION)
370 move += " pnbrqk"[promotion_type(m)];
376 /// UCI::to_move() converts a string representing a move in coordinate notation
377 /// (g1f3, a7a8q) to the corresponding legal Move, if any.
379 Move UCI::to_move(const Position& pos, string& str) {
381 if (str.length() == 5) // Junior could send promotion piece in uppercase
382 str[4] = char(tolower(str[4]));
384 for (const auto& m : MoveList<LEGAL>(pos))
385 if (str == UCI::move(m, pos.is_chess960()))
391 } // namespace Stockfish