]> git.sesse.net Git - stockfish/blob - src/uci.cpp
add clang-format
[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 namespace Stockfish {
45
46 namespace {
47
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";
50
51
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").
56
57 void position(Position& pos, std::istringstream& is, StateListPtr& states) {
58
59     Move        m;
60     std::string token, fen;
61
62     is >> token;
63
64     if (token == "startpos")
65     {
66         fen = StartFEN;
67         is >> token;  // Consume the "moves" token, if any
68     }
69     else if (token == "fen")
70         while (is >> token && token != "moves")
71             fen += token + " ";
72     else
73         return;
74
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());
77
78     // Parse the move list, if any
79     while (is >> token && (m = UCI::to_move(pos, token)) != MOVE_NONE)
80     {
81         states->emplace_back();
82         pos.do_move(m, states->back());
83     }
84 }
85
86 // trace_eval() prints the evaluation of the current position, consistent with
87 // the UCI options set so far.
88
89 void trace_eval(Position& pos) {
90
91     StateListPtr states(new std::deque<StateInfo>(1));
92     Position     p;
93     p.set(pos.fen(), Options["UCI_Chess960"], &states->back(), Threads.main());
94
95     Eval::NNUE::verify();
96
97     sync_cout << "\n" << Eval::trace(p) << sync_endl;
98 }
99
100
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").
103
104 void setoption(std::istringstream& is) {
105
106     Threads.main()->wait_for_search_finished();
107
108     std::string token, name, value;
109
110     is >> token;  // Consume the "name" token
111
112     // Read the option name (can contain spaces)
113     while (is >> token && token != "value")
114         name += (name.empty() ? "" : " ") + token;
115
116     // Read the option value (can contain spaces)
117     while (is >> token)
118         value += (value.empty() ? "" : " ") + token;
119
120     if (Options.count(name))
121         Options[name] = value;
122     else
123         sync_cout << "No such option: " << name << sync_endl;
124 }
125
126
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
129 // with a search.
130
131 void go(Position& pos, std::istringstream& is, StateListPtr& states) {
132
133     Search::LimitsType limits;
134     std::string        token;
135     bool               ponderMode = false;
136
137     limits.startTime = now();  // The search starts as early as possible
138
139     while (is >> token)
140         if (token == "searchmoves")  // Needs to be the last command on the line
141             while (is >> token)
142                 limits.searchmoves.push_back(UCI::to_move(pos, token));
143
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")
155             is >> limits.depth;
156         else if (token == "nodes")
157             is >> limits.nodes;
158         else if (token == "movetime")
159             is >> limits.movetime;
160         else if (token == "mate")
161             is >> limits.mate;
162         else if (token == "perft")
163             is >> limits.perft;
164         else if (token == "infinite")
165             limits.infinite = 1;
166         else if (token == "ponder")
167             ponderMode = true;
168
169     Threads.start_thinking(pos, states, limits, ponderMode);
170 }
171
172
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.
176
177 void bench(Position& pos, std::istream& args, StateListPtr& states) {
178
179     std::string token;
180     uint64_t    num, nodes = 0, cnt = 1;
181
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; });
185
186     TimePoint elapsed = now();
187
188     for (const auto& cmd : list)
189     {
190         std::istringstream is(cmd);
191         is >> std::skipws >> token;
192
193         if (token == "go" || token == "eval")
194         {
195             std::cerr << "\nPosition: " << cnt++ << '/' << num << " (" << pos.fen() << ")"
196                       << std::endl;
197             if (token == "go")
198             {
199                 go(pos, is, states);
200                 Threads.main()->wait_for_search_finished();
201                 nodes += Threads.nodes_searched();
202             }
203             else
204                 trace_eval(pos);
205         }
206         else if (token == "setoption")
207             setoption(is);
208         else if (token == "position")
209             position(pos, is, states);
210         else if (token == "ucinewgame")
211         {
212             Search::clear();
213             elapsed = now();
214         }  // Search::clear() may take a while
215     }
216
217     elapsed = now() - elapsed + 1;  // Ensure positivity to avoid a 'divide by zero'
218
219     dbg_print();
220
221     std::cerr << "\n==========================="
222               << "\nTotal time (ms) : " << elapsed << "\nNodes searched  : " << nodes
223               << "\nNodes/second    : " << 1000 * nodes / elapsed << std::endl;
224 }
225
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) {
229
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;
232
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
235     // function.
236     constexpr double as[] = {0.38036525, -2.82015070, 23.17882135, 307.36768407};
237     constexpr double bs[] = {-2.29434733, 13.27689788, -14.26828904, 63.45318330};
238
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]));
241
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];
244
245     // Transform the eval to centipawns with limited range
246     double x = std::clamp(double(v), -4000.0, 4000.0);
247
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)));
250 }
251
252 }  // namespace
253
254
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.
260
261 void UCI::loop(int argc, char* argv[]) {
262
263     Position     pos;
264     std::string  token, cmd;
265     StateListPtr states(new std::deque<StateInfo>(1));
266
267     pos.set(StartFEN, false, &states->back(), Threads.main());
268
269     for (int i = 1; i < argc; ++i)
270         cmd += std::string(argv[i]) + " ";
271
272     do
273     {
274         if (argc == 1
275             && !getline(std::cin, cmd))  // Wait for an input or an end-of-file (EOF) indication
276             cmd = "quit";
277
278         std::istringstream is(cmd);
279
280         token.clear();  // Avoid a stale if getline() returns nothing or a blank line
281         is >> std::skipws >> token;
282
283         if (token == "quit" || token == "stop")
284             Threads.stop = true;
285
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
292
293         else if (token == "uci")
294             sync_cout << "id name " << engine_info(true) << "\n"
295                       << Options << "\nuciok" << sync_endl;
296
297         else if (token == "setoption")
298             setoption(is);
299         else if (token == "go")
300             go(pos, is, states);
301         else if (token == "position")
302             position(pos, is, states);
303         else if (token == "ucinewgame")
304             Search::clear();
305         else if (token == "isready")
306             sync_cout << "readyok" << sync_endl;
307
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")
311             pos.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")
317             trace_eval(pos);
318         else if (token == "compiler")
319             sync_cout << compiler_info() << sync_endl;
320         else if (token == "export_net")
321         {
322             std::optional<std::string> filename;
323             std::string                f;
324             if (is >> std::skipws >> f)
325                 filename = f;
326             Eval::NNUE::save_eval(filename);
327         }
328         else if (token == "--help" || token == "help" || token == "--license" || token == "license")
329             sync_cout
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"
336               << sync_endl;
337         else if (!token.empty() && token[0] != '#')
338             sync_cout << "Unknown command: '" << cmd << "'. Type help for more information."
339                       << sync_endl;
340
341     } while (token != "quit" && argc == 1);  // The command-line arguments are one-shot
342 }
343
344
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; }
348
349 // UCI::value() converts a Value to a string by adhering to the UCI protocol specification:
350 //
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'.
354
355 std::string UCI::value(Value v) {
356
357     assert(-VALUE_INFINITE < v && v < VALUE_INFINITE);
358
359     std::stringstream ss;
360
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)
364     {
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);
367     }
368     else
369         ss << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
370
371     return ss.str();
372 }
373
374
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.
377
378 std::string UCI::wdl(Value v, int ply) {
379
380     std::stringstream ss;
381
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;
386
387     return ss.str();
388 }
389
390
391 // UCI::square() converts a Square to a string in algebraic notation (g1, a7, etc.)
392
393 std::string UCI::square(Square s) {
394     return std::string{char('a' + file_of(s)), char('1' + rank_of(s))};
395 }
396
397
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'.
402
403 std::string UCI::move(Move m, bool chess960) {
404
405     if (m == MOVE_NONE)
406         return "(none)";
407
408     if (m == MOVE_NULL)
409         return "0000";
410
411     Square from = from_sq(m);
412     Square to   = to_sq(m);
413
414     if (type_of(m) == CASTLING && !chess960)
415         to = make_square(to > from ? FILE_G : FILE_C, rank_of(from));
416
417     std::string move = UCI::square(from) + UCI::square(to);
418
419     if (type_of(m) == PROMOTION)
420         move += " pnbrqk"[promotion_type(m)];
421
422     return move;
423 }
424
425
426 // UCI::to_move() converts a string representing a move in coordinate notation
427 // (g1f3, a7a8q) to the corresponding legal Move, if any.
428
429 Move UCI::to_move(const Position& pos, std::string& str) {
430
431     if (str.length() == 5)
432         str[4] = char(tolower(str[4]));  // The promotion piece character must be lowercased
433
434     for (const auto& m : MoveList<LEGAL>(pos))
435         if (str == UCI::move(m, pos.is_chess960()))
436             return m;
437
438     return MOVE_NONE;
439 }
440
441 }  // namespace Stockfish