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