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