Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
official-stockfish
GitHub Repository: official-stockfish/Stockfish
Path: blob/master/src/uci.cpp
629 views
1
/*
2
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3
Copyright (C) 2004-2026 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 <cctype>
23
#include <cmath>
24
#include <cstdint>
25
#include <iterator>
26
#include <optional>
27
#include <sstream>
28
#include <string_view>
29
#include <utility>
30
#include <vector>
31
32
#include "benchmark.h"
33
#include "engine.h"
34
#include "memory.h"
35
#include "movegen.h"
36
#include "position.h"
37
#include "score.h"
38
#include "search.h"
39
#include "types.h"
40
#include "ucioption.h"
41
42
namespace Stockfish {
43
44
constexpr auto BenchmarkCommand = "speedtest";
45
46
constexpr auto StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
47
template<typename... Ts>
48
struct overload: Ts... {
49
using Ts::operator()...;
50
};
51
52
template<typename... Ts>
53
overload(Ts...) -> overload<Ts...>;
54
55
void UCIEngine::print_info_string(std::string_view str) {
56
sync_cout_start();
57
for (auto& line : split(str, "\n"))
58
{
59
if (!is_whitespace(line))
60
{
61
std::cout << "info string " << line << '\n';
62
}
63
}
64
sync_cout_end();
65
}
66
67
UCIEngine::UCIEngine(int argc, char** argv) :
68
engine(argv[0]),
69
cli(argc, argv) {
70
71
engine.get_options().add_info_listener([](const std::optional<std::string>& str) {
72
if (str.has_value())
73
print_info_string(*str);
74
});
75
76
init_search_update_listeners();
77
}
78
79
void UCIEngine::init_search_update_listeners() {
80
engine.set_on_iter([](const auto& i) { on_iter(i); });
81
engine.set_on_update_no_moves([](const auto& i) { on_update_no_moves(i); });
82
engine.set_on_update_full(
83
[this](const auto& i) { on_update_full(i, engine.get_options()["UCI_ShowWDL"]); });
84
engine.set_on_bestmove([](const auto& bm, const auto& p) { on_bestmove(bm, p); });
85
engine.set_on_verify_networks([](const auto& s) { print_info_string(s); });
86
}
87
88
void UCIEngine::loop() {
89
std::string token, cmd;
90
91
for (int i = 1; i < cli.argc; ++i)
92
cmd += std::string(cli.argv[i]) + " ";
93
94
do
95
{
96
if (cli.argc == 1
97
&& !getline(std::cin, cmd)) // Wait for an input or an end-of-file (EOF) indication
98
cmd = "quit";
99
100
std::istringstream is(cmd);
101
102
token.clear(); // Avoid a stale if getline() returns nothing or a blank line
103
is >> std::skipws >> token;
104
105
if (token == "quit" || token == "stop")
106
engine.stop();
107
108
// The GUI sends 'ponderhit' to tell that the user has played the expected move.
109
// So, 'ponderhit' is sent if pondering was done on the same move that the user
110
// has played. The search should continue, but should also switch from pondering
111
// to the normal search.
112
else if (token == "ponderhit")
113
engine.set_ponderhit(false);
114
115
else if (token == "uci")
116
{
117
sync_cout << "id name " << engine_info(true) << "\n"
118
<< engine.get_options() << sync_endl;
119
120
sync_cout << "uciok" << sync_endl;
121
}
122
123
else if (token == "setoption")
124
setoption(is);
125
else if (token == "go")
126
{
127
// send info strings after the go command is sent for old GUIs and python-chess
128
print_info_string(engine.numa_config_information_as_string());
129
print_info_string(engine.thread_allocation_information_as_string());
130
go(is);
131
}
132
else if (token == "position")
133
position(is);
134
else if (token == "ucinewgame")
135
engine.search_clear();
136
else if (token == "isready")
137
sync_cout << "readyok" << sync_endl;
138
139
// Add custom non-UCI commands, mainly for debugging purposes.
140
// These commands must not be used during a search!
141
else if (token == "flip")
142
engine.flip();
143
else if (token == "bench")
144
bench(is);
145
else if (token == BenchmarkCommand)
146
benchmark(is);
147
else if (token == "d")
148
sync_cout << engine.visualize() << sync_endl;
149
else if (token == "eval")
150
engine.trace_eval();
151
else if (token == "compiler")
152
sync_cout << compiler_info() << sync_endl;
153
else if (token == "export_net")
154
{
155
std::pair<std::optional<std::string>, std::string> files[2];
156
157
if (is >> std::skipws >> files[0].second)
158
files[0].first = files[0].second;
159
160
if (is >> std::skipws >> files[1].second)
161
files[1].first = files[1].second;
162
163
engine.save_network(files);
164
}
165
else if (token == "--help" || token == "help" || token == "--license" || token == "license")
166
sync_cout
167
<< "\nStockfish is a powerful chess engine for playing and analyzing."
168
"\nIt is released as free software licensed under the GNU GPLv3 License."
169
"\nStockfish is normally used with a graphical user interface (GUI) and implements"
170
"\nthe Universal Chess Interface (UCI) protocol to communicate with a GUI, an API, etc."
171
"\nFor any further information, visit https://github.com/official-stockfish/Stockfish#readme"
172
"\nor read the corresponding README.md and Copying.txt files distributed along with this program.\n"
173
<< sync_endl;
174
else if (!token.empty() && token[0] != '#')
175
sync_cout << "Unknown command: '" << cmd << "'. Type help for more information."
176
<< sync_endl;
177
178
} while (token != "quit" && cli.argc == 1); // The command-line arguments are one-shot
179
}
180
181
Search::LimitsType UCIEngine::parse_limits(std::istream& is) {
182
Search::LimitsType limits;
183
std::string token;
184
185
limits.startTime = now(); // The search starts as early as possible
186
187
while (is >> token)
188
if (token == "searchmoves") // Needs to be the last command on the line
189
while (is >> token)
190
limits.searchmoves.push_back(to_lower(token));
191
192
else if (token == "wtime")
193
is >> limits.time[WHITE];
194
else if (token == "btime")
195
is >> limits.time[BLACK];
196
else if (token == "winc")
197
is >> limits.inc[WHITE];
198
else if (token == "binc")
199
is >> limits.inc[BLACK];
200
else if (token == "movestogo")
201
is >> limits.movestogo;
202
else if (token == "depth")
203
is >> limits.depth;
204
else if (token == "nodes")
205
is >> limits.nodes;
206
else if (token == "movetime")
207
is >> limits.movetime;
208
else if (token == "mate")
209
is >> limits.mate;
210
else if (token == "perft")
211
is >> limits.perft;
212
else if (token == "infinite")
213
limits.infinite = 1;
214
else if (token == "ponder")
215
limits.ponderMode = true;
216
217
return limits;
218
}
219
220
void UCIEngine::go(std::istringstream& is) {
221
222
Search::LimitsType limits = parse_limits(is);
223
224
if (limits.perft)
225
perft(limits);
226
else
227
engine.go(limits);
228
}
229
230
void UCIEngine::bench(std::istream& args) {
231
std::string token;
232
uint64_t num, nodes = 0, cnt = 1;
233
uint64_t nodesSearched = 0;
234
const auto& options = engine.get_options();
235
236
engine.set_on_update_full([&](const auto& i) {
237
nodesSearched = i.nodes;
238
on_update_full(i, options["UCI_ShowWDL"]);
239
});
240
241
std::vector<std::string> list = Benchmark::setup_bench(engine.fen(), args);
242
243
num = count_if(list.begin(), list.end(),
244
[](const std::string& s) { return s.find("go ") == 0 || s.find("eval") == 0; });
245
246
TimePoint elapsed = now();
247
248
for (const auto& cmd : list)
249
{
250
std::istringstream is(cmd);
251
is >> std::skipws >> token;
252
253
if (token == "go" || token == "eval")
254
{
255
std::cerr << "\nPosition: " << cnt++ << '/' << num << " (" << engine.fen() << ")"
256
<< std::endl;
257
if (token == "go")
258
{
259
Search::LimitsType limits = parse_limits(is);
260
261
if (limits.perft)
262
nodesSearched = perft(limits);
263
else
264
{
265
engine.go(limits);
266
engine.wait_for_search_finished();
267
}
268
269
nodes += nodesSearched;
270
nodesSearched = 0;
271
}
272
else
273
engine.trace_eval();
274
}
275
else if (token == "setoption")
276
setoption(is);
277
else if (token == "position")
278
position(is);
279
else if (token == "ucinewgame")
280
{
281
engine.search_clear(); // search_clear may take a while
282
elapsed = now();
283
}
284
}
285
286
elapsed = now() - elapsed + 1; // Ensure positivity to avoid a 'divide by zero'
287
288
dbg_print();
289
290
std::cerr << "\n===========================" //
291
<< "\nTotal time (ms) : " << elapsed //
292
<< "\nNodes searched : " << nodes //
293
<< "\nNodes/second : " << 1000 * nodes / elapsed << std::endl;
294
295
// reset callback, to not capture a dangling reference to nodesSearched
296
engine.set_on_update_full([&](const auto& i) { on_update_full(i, options["UCI_ShowWDL"]); });
297
}
298
299
void UCIEngine::benchmark(std::istream& args) {
300
// Probably not very important for a test this long, but include for completeness and sanity.
301
static constexpr int NUM_WARMUP_POSITIONS = 3;
302
303
std::string token;
304
uint64_t nodes = 0, cnt = 1;
305
uint64_t nodesSearched = 0;
306
307
engine.set_on_update_full([&](const Engine::InfoFull& i) { nodesSearched = i.nodes; });
308
309
engine.set_on_iter([](const auto&) {});
310
engine.set_on_update_no_moves([](const auto&) {});
311
engine.set_on_bestmove([](const auto&, const auto&) {});
312
engine.set_on_verify_networks([](const auto&) {});
313
314
Benchmark::BenchmarkSetup setup = Benchmark::setup_benchmark(args);
315
316
const auto numGoCommands = count_if(setup.commands.begin(), setup.commands.end(),
317
[](const std::string& s) { return s.find("go ") == 0; });
318
319
TimePoint totalTime = 0;
320
321
// Set options once at the start.
322
auto ss = std::istringstream("name Threads value " + std::to_string(setup.threads));
323
setoption(ss);
324
ss = std::istringstream("name Hash value " + std::to_string(setup.ttSize));
325
setoption(ss);
326
ss = std::istringstream("name UCI_Chess960 value false");
327
setoption(ss);
328
329
// Warmup
330
for (const auto& cmd : setup.commands)
331
{
332
std::istringstream is(cmd);
333
is >> std::skipws >> token;
334
335
if (token == "go")
336
{
337
// One new line is produced by the search, so omit it here
338
std::cerr << "\rWarmup position " << cnt++ << '/' << NUM_WARMUP_POSITIONS;
339
340
Search::LimitsType limits = parse_limits(is);
341
342
// Run with silenced network verification
343
engine.go(limits);
344
engine.wait_for_search_finished();
345
}
346
else if (token == "position")
347
position(is);
348
else if (token == "ucinewgame")
349
{
350
engine.search_clear(); // search_clear may take a while
351
}
352
353
if (cnt > NUM_WARMUP_POSITIONS)
354
break;
355
}
356
357
std::cerr << "\n";
358
359
cnt = 1;
360
nodes = 0;
361
362
int numHashfullReadings = 0;
363
constexpr int hashfullAges[] = {0, 999}; // Only normal hashfull and touched hash.
364
constexpr int hashfullAgeCount = std::size(hashfullAges);
365
int totalHashfull[hashfullAgeCount] = {0};
366
int maxHashfull[hashfullAgeCount] = {0};
367
368
auto updateHashfullReadings = [&]() {
369
numHashfullReadings += 1;
370
371
for (int i = 0; i < hashfullAgeCount; ++i)
372
{
373
const int hashfull = engine.get_hashfull(hashfullAges[i]);
374
maxHashfull[i] = std::max(maxHashfull[i], hashfull);
375
totalHashfull[i] += hashfull;
376
}
377
};
378
379
engine.search_clear(); // search_clear may take a while
380
381
for (const auto& cmd : setup.commands)
382
{
383
std::istringstream is(cmd);
384
is >> std::skipws >> token;
385
386
if (token == "go")
387
{
388
// One new line is produced by the search, so omit it here
389
std::cerr << "\rPosition " << cnt++ << '/' << numGoCommands;
390
391
Search::LimitsType limits = parse_limits(is);
392
393
nodesSearched = 0;
394
TimePoint elapsed = now();
395
396
// Run with silenced network verification
397
engine.go(limits);
398
engine.wait_for_search_finished();
399
400
totalTime += now() - elapsed;
401
402
updateHashfullReadings();
403
404
nodes += nodesSearched;
405
}
406
else if (token == "position")
407
position(is);
408
else if (token == "ucinewgame")
409
{
410
engine.search_clear(); // search_clear may take a while
411
}
412
}
413
414
totalTime = std::max<TimePoint>(totalTime, 1); // Ensure positivity to avoid a 'divide by zero'
415
416
dbg_print();
417
418
std::cerr << "\n";
419
420
static_assert(
421
std::size(hashfullAges) == 2 && hashfullAges[0] == 0 && hashfullAges[1] == 999,
422
"Hardcoded for display. Would complicate the code needlessly in the current state.");
423
424
std::string threadBinding = engine.thread_binding_information_as_string();
425
if (threadBinding.empty())
426
threadBinding = "none";
427
428
// clang-format off
429
430
std::cerr << "==========================="
431
<< "\nVersion : "
432
<< engine_version_info()
433
// "\nCompiled by : "
434
<< compiler_info()
435
<< "Large pages : " << (has_large_pages() ? "yes" : "no")
436
<< "\nUser invocation : " << BenchmarkCommand << " "
437
<< setup.originalInvocation << "\nFilled invocation : " << BenchmarkCommand
438
<< " " << setup.filledInvocation
439
<< "\nAvailable processors : " << engine.get_numa_config_as_string()
440
<< "\nThread count : " << setup.threads
441
<< "\nThread binding : " << threadBinding
442
<< "\nTT size [MiB] : " << setup.ttSize
443
<< "\nHash max, avg [per mille] : "
444
<< "\n single search : " << maxHashfull[0] << ", "
445
<< totalHashfull[0] / numHashfullReadings
446
<< "\n single game : " << maxHashfull[1] << ", "
447
<< totalHashfull[1] / numHashfullReadings
448
<< "\nTotal nodes searched : " << nodes
449
<< "\nTotal search time [s] : " << totalTime / 1000.0
450
<< "\nNodes/second : " << 1000 * nodes / totalTime << std::endl;
451
452
// clang-format on
453
454
init_search_update_listeners();
455
}
456
457
void UCIEngine::setoption(std::istringstream& is) {
458
engine.wait_for_search_finished();
459
engine.get_options().setoption(is);
460
}
461
462
std::uint64_t UCIEngine::perft(const Search::LimitsType& limits) {
463
auto nodes = engine.perft(engine.fen(), limits.perft, engine.get_options()["UCI_Chess960"]);
464
sync_cout << "\nNodes searched: " << nodes << "\n" << sync_endl;
465
return nodes;
466
}
467
468
void UCIEngine::position(std::istringstream& is) {
469
std::string token, fen;
470
471
is >> token;
472
473
if (token == "startpos")
474
{
475
fen = StartFEN;
476
is >> token; // Consume the "moves" token, if any
477
}
478
else if (token == "fen")
479
while (is >> token && token != "moves")
480
fen += token + " ";
481
else
482
return;
483
484
std::vector<std::string> moves;
485
486
while (is >> token)
487
{
488
moves.push_back(token);
489
}
490
491
engine.set_position(fen, moves);
492
}
493
494
namespace {
495
496
struct WinRateParams {
497
double a;
498
double b;
499
};
500
501
WinRateParams win_rate_params(const Position& pos) {
502
503
int material = pos.count<PAWN>() + 3 * pos.count<KNIGHT>() + 3 * pos.count<BISHOP>()
504
+ 5 * pos.count<ROOK>() + 9 * pos.count<QUEEN>();
505
506
// The fitted model only uses data for material counts in [17, 78], and is anchored at count 58.
507
double m = std::clamp(material, 17, 78) / 58.0;
508
509
// Return a = p_a(material) and b = p_b(material), see github.com/official-stockfish/WDL_model
510
constexpr double as[] = {-72.32565836, 185.93832038, -144.58862193, 416.44950446};
511
constexpr double bs[] = {83.86794042, -136.06112997, 69.98820887, 47.62901433};
512
513
double a = (((as[0] * m + as[1]) * m + as[2]) * m) + as[3];
514
double b = (((bs[0] * m + bs[1]) * m + bs[2]) * m) + bs[3];
515
516
return {a, b};
517
}
518
519
// The win rate model is 1 / (1 + exp((a - eval) / b)), where a = p_a(material) and b = p_b(material).
520
// It fits the LTC fishtest statistics rather accurately.
521
int win_rate_model(Value v, const Position& pos) {
522
523
auto [a, b] = win_rate_params(pos);
524
525
// Return the win rate in per mille units, rounded to the nearest integer.
526
return int(0.5 + 1000 / (1 + std::exp((a - double(v)) / b)));
527
}
528
}
529
530
std::string UCIEngine::format_score(const Score& s) {
531
constexpr int TB_CP = 20000;
532
const auto format =
533
overload{[](Score::Mate mate) -> std::string {
534
auto m = (mate.plies > 0 ? (mate.plies + 1) : mate.plies) / 2;
535
return std::string("mate ") + std::to_string(m);
536
},
537
[](Score::Tablebase tb) -> std::string {
538
return std::string("cp ")
539
+ std::to_string((tb.win ? TB_CP - tb.plies : -TB_CP - tb.plies));
540
},
541
[](Score::InternalUnits units) -> std::string {
542
return std::string("cp ") + std::to_string(units.value);
543
}};
544
545
return s.visit(format);
546
}
547
548
// Turns a Value to an integer centipawn number,
549
// without treatment of mate and similar special scores.
550
int UCIEngine::to_cp(Value v, const Position& pos) {
551
552
// In general, the score can be defined via the WDL as
553
// (log(1/L - 1) - log(1/W - 1)) / (log(1/L - 1) + log(1/W - 1)).
554
// Based on our win_rate_model, this simply yields v / a.
555
556
auto [a, b] = win_rate_params(pos);
557
558
return int(std::round(100 * int(v) / a));
559
}
560
561
std::string UCIEngine::wdl(Value v, const Position& pos) {
562
std::stringstream ss;
563
564
int wdl_w = win_rate_model(v, pos);
565
int wdl_l = win_rate_model(-v, pos);
566
int wdl_d = 1000 - wdl_w - wdl_l;
567
ss << wdl_w << " " << wdl_d << " " << wdl_l;
568
569
return ss.str();
570
}
571
572
std::string UCIEngine::square(Square s) {
573
return std::string{char('a' + file_of(s)), char('1' + rank_of(s))};
574
}
575
576
std::string UCIEngine::move(Move m, bool chess960) {
577
if (m == Move::none())
578
return "(none)";
579
580
if (m == Move::null())
581
return "0000";
582
583
Square from = m.from_sq();
584
Square to = m.to_sq();
585
586
if (m.type_of() == CASTLING && !chess960)
587
to = make_square(to > from ? FILE_G : FILE_C, rank_of(from));
588
589
std::string move = square(from) + square(to);
590
591
if (m.type_of() == PROMOTION)
592
move += " pnbrqk"[m.promotion_type()];
593
594
return move;
595
}
596
597
598
std::string UCIEngine::to_lower(std::string str) {
599
std::transform(str.begin(), str.end(), str.begin(), [](auto c) { return std::tolower(c); });
600
601
return str;
602
}
603
604
Move UCIEngine::to_move(const Position& pos, std::string str) {
605
str = to_lower(str);
606
607
for (const auto& m : MoveList<LEGAL>(pos))
608
if (str == move(m, pos.is_chess960()))
609
return m;
610
611
return Move::none();
612
}
613
614
void UCIEngine::on_update_no_moves(const Engine::InfoShort& info) {
615
sync_cout << "info depth " << info.depth << " score " << format_score(info.score) << sync_endl;
616
}
617
618
void UCIEngine::on_update_full(const Engine::InfoFull& info, bool showWDL) {
619
std::stringstream ss;
620
621
ss << "info";
622
ss << " depth " << info.depth //
623
<< " seldepth " << info.selDepth //
624
<< " multipv " << info.multiPV //
625
<< " score " << format_score(info.score); //
626
627
if (!info.bound.empty())
628
ss << " " << info.bound;
629
630
if (showWDL)
631
ss << " wdl " << info.wdl;
632
633
ss << " nodes " << info.nodes //
634
<< " nps " << info.nps //
635
<< " hashfull " << info.hashfull //
636
<< " tbhits " << info.tbHits //
637
<< " time " << info.timeMs //
638
<< " pv " << info.pv; //
639
640
sync_cout << ss.str() << sync_endl;
641
}
642
643
void UCIEngine::on_iter(const Engine::InfoIter& info) {
644
std::stringstream ss;
645
646
ss << "info";
647
ss << " depth " << info.depth //
648
<< " currmove " << info.currmove //
649
<< " currmovenumber " << info.currmovenumber; //
650
651
sync_cout << ss.str() << sync_endl;
652
}
653
654
void UCIEngine::on_bestmove(std::string_view bestmove, std::string_view ponder) {
655
sync_cout << "bestmove " << bestmove;
656
if (!ponder.empty())
657
std::cout << " ponder " << ponder;
658
std::cout << sync_endl;
659
}
660
661
} // namespace Stockfish
662
663