]> git.sesse.net Git - stockfish/blob - src/uci.cpp
Smooth improving
[stockfish] / src / uci.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2021 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 "evaluate.h"
26 #include "movegen.h"
27 #include "position.h"
28 #include "search.h"
29 #include "thread.h"
30 #include "timeman.h"
31 #include "tt.h"
32 #include "uci.h"
33 #include "syzygy/tbprobe.h"
34
35 using namespace std;
36
37 namespace Stockfish {
38
39 extern vector<string> setup_bench(const Position&, istream&);
40
41 namespace {
42
43   // FEN string of the initial position, normal chess
44   const char* StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
45
46
47   // position() is called when engine receives the "position" UCI command.
48   // The function sets up the position described in the given FEN string ("fen")
49   // or the starting position ("startpos") and then makes the moves given in the
50   // following 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 "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 old and create a new one
71     pos.set(fen, Options["UCI_Chess960"], &states->back(), Threads.main());
72
73     // Parse 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 for the current position, consistent with the UCI
82   // 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 engine receives the "setoption" UCI command. The
97   // function updates the UCI option ("name") to the given value ("value").
98
99   void setoption(istringstream& is) {
100
101     string token, name, value;
102
103     is >> token; // Consume "name" token
104
105     // Read option name (can contain spaces)
106     while (is >> token && token != "value")
107         name += (name.empty() ? "" : " ") + token;
108
109     // Read option value (can contain spaces)
110     while (is >> token)
111         value += (value.empty() ? "" : " ") + token;
112
113     if (Options.count(name))
114         Options[name] = value;
115     else
116         sync_cout << "No such option: " << name << sync_endl;
117   }
118
119
120   // go() is called when engine receives the "go" UCI command. The function sets
121   // the thinking time and other parameters from the input string, then starts
122   // the search.
123
124   void go(Position& pos, istringstream& is, StateListPtr& states) {
125
126     Search::LimitsType limits;
127     string token;
128     bool ponderMode = false;
129
130     limits.startTime = now(); // As early as possible!
131
132     while (is >> token)
133         if (token == "searchmoves") // Needs to be the last command on the line
134             while (is >> token)
135                 limits.searchmoves.push_back(UCI::to_move(pos, token));
136
137         else if (token == "wtime")     is >> limits.time[WHITE];
138         else if (token == "btime")     is >> limits.time[BLACK];
139         else if (token == "winc")      is >> limits.inc[WHITE];
140         else if (token == "binc")      is >> limits.inc[BLACK];
141         else if (token == "movestogo") is >> limits.movestogo;
142         else if (token == "depth")     is >> limits.depth;
143         else if (token == "nodes")     is >> limits.nodes;
144         else if (token == "movetime")  is >> limits.movetime;
145         else if (token == "mate")      is >> limits.mate;
146         else if (token == "perft")     is >> limits.perft;
147         else if (token == "infinite")  limits.infinite = 1;
148         else if (token == "ponder")    ponderMode = true;
149
150     Threads.start_thinking(pos, states, limits, ponderMode);
151   }
152
153
154   // bench() is called when engine receives the "bench" command. Firstly
155   // a list of UCI commands is setup according to bench parameters, then
156   // it is run one by one printing a summary at the end.
157
158   void bench(Position& pos, istream& args, StateListPtr& states) {
159
160     string token;
161     uint64_t num, nodes = 0, cnt = 1;
162
163     vector<string> list = setup_bench(pos, args);
164     num = count_if(list.begin(), list.end(), [](string s) { return s.find("go ") == 0 || s.find("eval") == 0; });
165
166     TimePoint elapsed = now();
167
168     for (const auto& cmd : list)
169     {
170         istringstream is(cmd);
171         is >> skipws >> token;
172
173         if (token == "go" || token == "eval")
174         {
175             cerr << "\nPosition: " << cnt++ << '/' << num << " (" << pos.fen() << ")" << endl;
176             if (token == "go")
177             {
178                go(pos, is, states);
179                Threads.main()->wait_for_search_finished();
180                nodes += Threads.nodes_searched();
181             }
182             else
183                trace_eval(pos);
184         }
185         else if (token == "setoption")  setoption(is);
186         else if (token == "position")   position(pos, is, states);
187         else if (token == "ucinewgame") { Search::clear(); elapsed = now(); } // Search::clear() may take some while
188     }
189
190     elapsed = now() - elapsed + 1; // Ensure positivity to avoid a 'divide by zero'
191
192     dbg_print(); // Just before exiting
193
194     cerr << "\n==========================="
195          << "\nTotal time (ms) : " << elapsed
196          << "\nNodes searched  : " << nodes
197          << "\nNodes/second    : " << 1000 * nodes / elapsed << endl;
198   }
199
200   // The win rate model returns the probability (per mille) of winning given an eval
201   // and a game-ply. The model fits rather accurately the LTC fishtest statistics.
202   int win_rate_model(Value v, int ply) {
203
204      // The model captures only up to 240 plies, so limit input (and rescale)
205      double m = std::min(240, ply) / 64.0;
206
207      // Coefficients of a 3rd order polynomial fit based on fishtest data
208      // for two parameters needed to transform eval to the argument of a
209      // logistic function.
210      double as[] = {-3.68389304,  30.07065921, -60.52878723, 149.53378557};
211      double bs[] = {-2.0181857,   15.85685038, -29.83452023,  47.59078827};
212      double a = (((as[0] * m + as[1]) * m + as[2]) * m) + as[3];
213      double b = (((bs[0] * m + bs[1]) * m + bs[2]) * m) + bs[3];
214
215      // Transform eval to centipawns with limited range
216      double x = std::clamp(double(100 * v) / PawnValueEg, -2000.0, 2000.0);
217
218      // Return win rate in per mille (rounded to nearest)
219      return int(0.5 + 1000 / (1 + std::exp((a - x) / b)));
220   }
221
222 } // namespace
223
224
225 /// UCI::loop() waits for a command from stdin, parses it and calls the appropriate
226 /// function. Also intercepts EOF from stdin to ensure gracefully exiting if the
227 /// GUI dies unexpectedly. When called with some command line arguments, e.g. to
228 /// run 'bench', once the command is executed the function returns immediately.
229 /// In addition to the UCI ones, also some additional debug commands are supported.
230
231 void UCI::loop(int argc, char* argv[]) {
232
233   Position pos;
234   string token, cmd;
235   StateListPtr states(new std::deque<StateInfo>(1));
236
237   pos.set(StartFEN, false, &states->back(), Threads.main());
238
239   for (int i = 1; i < argc; ++i)
240       cmd += std::string(argv[i]) + " ";
241
242   do {
243       if (argc == 1 && !getline(cin, cmd)) // Block here waiting for input or EOF
244           cmd = "quit";
245
246       istringstream is(cmd);
247
248       token.clear(); // Avoid a stale if getline() returns empty or blank line
249       is >> skipws >> token;
250
251       if (    token == "quit"
252           ||  token == "stop")
253           Threads.stop = true;
254
255       // The GUI sends 'ponderhit' to tell us the user has played the expected move.
256       // So 'ponderhit' will be sent if we were told to ponder on the same move the
257       // user has played. We should continue searching but switch from pondering to
258       // normal search.
259       else if (token == "ponderhit")
260           Threads.main()->ponder = false; // Switch to normal search
261
262       else if (token == "uci")
263           sync_cout << "id name " << engine_info(true)
264                     << "\n"       << Options
265                     << "\nuciok"  << sync_endl;
266
267       else if (token == "setoption")  setoption(is);
268       else if (token == "go")         go(pos, is, states);
269       else if (token == "position")   position(pos, is, states);
270       else if (token == "ucinewgame") Search::clear();
271       else if (token == "isready")    sync_cout << "readyok" << sync_endl;
272
273       // Additional custom non-UCI commands, mainly for debugging.
274       // Do not use these commands during a search!
275       else if (token == "flip")     pos.flip();
276       else if (token == "bench")    bench(pos, is, states);
277       else if (token == "d")        sync_cout << pos << sync_endl;
278       else if (token == "eval")     trace_eval(pos);
279       else if (token == "compiler") sync_cout << compiler_info() << sync_endl;
280       else if (token == "export_net")
281       {
282           std::optional<std::string> filename;
283           std::string f;
284           if (is >> skipws >> f)
285               filename = f;
286           Eval::NNUE::save_eval(filename);
287       }
288       else if (!token.empty() && token[0] != '#')
289           sync_cout << "Unknown command: " << cmd << sync_endl;
290
291   } while (token != "quit" && argc == 1); // Command line args are one-shot
292 }
293
294
295 /// UCI::value() converts a Value to a string suitable for use with the UCI
296 /// protocol specification:
297 ///
298 /// cp <x>    The score from the engine's point of view in centipawns.
299 /// mate <y>  Mate in y moves, not plies. If the engine is getting mated
300 ///           use negative values for y.
301
302 string UCI::value(Value v) {
303
304   assert(-VALUE_INFINITE < v && v < VALUE_INFINITE);
305
306   stringstream ss;
307
308   if (abs(v) < VALUE_MATE_IN_MAX_PLY)
309       ss << "cp " << v * 100 / PawnValueEg;
310   else
311       ss << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
312
313   return ss.str();
314 }
315
316
317 /// UCI::wdl() report WDL statistics given an evaluation and a game ply, based on
318 /// data gathered for fishtest LTC games.
319
320 string UCI::wdl(Value v, int ply) {
321
322   stringstream ss;
323
324   int wdl_w = win_rate_model( v, ply);
325   int wdl_l = win_rate_model(-v, ply);
326   int wdl_d = 1000 - wdl_w - wdl_l;
327   ss << " wdl " << wdl_w << " " << wdl_d << " " << wdl_l;
328
329   return ss.str();
330 }
331
332
333 /// UCI::square() converts a Square to a string in algebraic notation (g1, a7, etc.)
334
335 std::string UCI::square(Square s) {
336   return std::string{ char('a' + file_of(s)), char('1' + rank_of(s)) };
337 }
338
339
340 /// UCI::move() converts a Move to a string in coordinate notation (g1f3, a7a8q).
341 /// The only special case is castling, where we print in the e1g1 notation in
342 /// normal chess mode, and in e1h1 notation in chess960 mode. Internally all
343 /// castling moves are always encoded as 'king captures rook'.
344
345 string UCI::move(Move m, bool chess960) {
346
347   Square from = from_sq(m);
348   Square to = to_sq(m);
349
350   if (m == MOVE_NONE)
351       return "(none)";
352
353   if (m == MOVE_NULL)
354       return "0000";
355
356   if (type_of(m) == CASTLING && !chess960)
357       to = make_square(to > from ? FILE_G : FILE_C, rank_of(from));
358
359   string move = UCI::square(from) + UCI::square(to);
360
361   if (type_of(m) == PROMOTION)
362       move += " pnbrqk"[promotion_type(m)];
363
364   return move;
365 }
366
367
368 /// UCI::to_move() converts a string representing a move in coordinate notation
369 /// (g1f3, a7a8q) to the corresponding legal Move, if any.
370
371 Move UCI::to_move(const Position& pos, string& str) {
372
373   if (str.length() == 5) // Junior could send promotion piece in uppercase
374       str[4] = char(tolower(str[4]));
375
376   for (const auto& m : MoveList<LEGAL>(pos))
377       if (str == UCI::move(m, pos.is_chess960()))
378           return m;
379
380   return MOVE_NONE;
381 }
382
383 } // namespace Stockfish