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