4 # remoteglot - Connects an abitrary UCI-speaking engine to ICS for easier post-game
5 # analysis, or for live analysis of relayed games. (Do not use for
6 # cheating! Cheating is bad for your karma, and your abuser flag.)
8 # Copyright 2007 Steinar H. Gunderson <sgunderson@bigfoot.com>
9 # Licensed under the GNU General Public License, version 2.
20 require 'Position.pm';
26 my $server = "freechess.org";
27 my $target = "GMCarlsen";
28 my $engine_cmdline = "'./Deep Rybka 4 SSE42 x64'";
29 my $engine2_cmdline = "./stockfish_13111119_x64_modern_sse42"; # undef for none
30 my $uci_assume_full_compliance = 0; # dangerous :-)
31 my $update_max_interval = 1.0;
41 $SIG{ALRM} = sub { output(); };
42 my $latest_update = undef;
46 open(FICSLOG, ">ficslog.txt")
47 or die "ficslog.txt: $!";
48 print FICSLOG "Log starting.\n";
52 open(UCILOG, ">ucilog.txt")
53 or die "ucilog.txt: $!";
54 print UCILOG "Log starting.\n";
59 # open the chess engine
60 my $engine = open_engine($engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
61 my $engine2 = open_engine($engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
64 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
66 uciprint($engine, "setoption name UCI_AnalyseMode value true");
67 # uciprint($engine, "setoption name NalimovPath value /srv/tablebase");
68 uciprint($engine, "setoption name NalimovUsage value Rarely");
69 uciprint($engine, "setoption name Hash value 1024");
70 # uciprint($engine, "setoption name MultiPV value 2");
71 uciprint($engine, "ucinewgame");
73 if (defined($engine2)) {
74 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
75 # uciprint($engine2, "setoption name NalimovPath value /srv/tablebase");
76 uciprint($engine2, "setoption name NalimovUsage value Rarely");
77 uciprint($engine2, "setoption name Hash value 1024");
78 uciprint($engine2, "setoption name Threads value 8");
79 uciprint($engine2, "setoption name MultiPV value 500");
80 uciprint($engine2, "ucinewgame");
83 print "Chess engine ready.\n";
86 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
87 $t->input_log(\*FICSLOG);
89 $t->print("SesseBOT");
90 $t->waitfor('/Press return to enter the server/');
94 $t->cmd("set shout 0");
95 $t->cmd("set seek 0");
96 $t->cmd("set style 12");
97 $t->cmd("observe $target");
98 print "FICS ready.\n";
100 my $ev1 = AnyEvent->io(
103 cb => sub { # what callback to execute
105 my $line = $t->getline(Timeout => 0, errmode => 'return');
106 return if (!defined($line));
114 # Engine events have already been set up by Engine.pm.
118 my ($engine, $line, $primary) = @_;
120 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
121 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
122 if ($line =~ /^info/) {
123 my (@infos) = split / /, $line;
126 parse_infos($engine, @infos);
128 if ($line =~ /^id/) {
129 my (@ids) = split / /, $line;
132 parse_ids($engine, @ids);
134 if ($line =~ /^bestmove/) {
136 return if (!$uci_assume_full_compliance);
137 if (defined($pos_waiting)) {
138 uciprint($engine, "position fen " . $pos_waiting->fen());
139 uciprint($engine, "go infinite");
141 $pos_calculating = $pos_waiting;
142 $pos_waiting = undef;
145 $engine2->{'info'} = {};
146 my $pos = $pos_waiting // $pos_calculating;
147 uciprint($engine2, "position fen " . $pos->fen());
148 uciprint($engine2, "go infinite");
149 $pos_calculating_second_engine = $pos;
157 if ($line =~ /^<12> /) {
158 my $pos = Position->new($line);
160 # if this is already in the queue, ignore it
161 next if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
163 # if we're already chewing on this and there's nothing else in the queue,
165 next if (!defined($pos_waiting) && defined($pos_calculating) &&
166 $pos->fen() eq $pos_calculating->fen());
168 # if we're already thinking on something, stop and wait for the engine
170 if (defined($pos_calculating)) {
171 if (!defined($pos_waiting)) {
172 uciprint($engine, "stop");
174 if ($uci_assume_full_compliance) {
177 uciprint($engine, "position fen " . $pos->fen());
178 uciprint($engine, "go infinite");
179 $pos_calculating = $pos;
182 # it's wrong just to give the FEN (the move history is useful,
183 # and per the UCI spec, we should really have sent "ucinewgame"),
185 uciprint($engine, "position fen " . $pos->fen());
186 uciprint($engine, "go infinite");
187 $pos_calculating = $pos;
190 if (defined($engine2)) {
191 if (defined($pos_calculating_second_engine)) {
192 uciprint($engine2, "stop");
194 uciprint($engine2, "position fen " . $pos->fen());
195 uciprint($engine2, "go infinite");
196 $pos_calculating_second_engine = $pos;
198 $engine2->{'info'} = {};
201 $engine->{'info'} = {};
205 # Output a command every move to note that we're
206 # still paying attention -- this is a good tradeoff,
207 # since if no move has happened in the last half
208 # hour, the analysis/relay has most likely stopped
209 # and we should stop hogging server resources.
213 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
214 my ($who, $msg) = ($1, $2);
216 next if (grep { $_ eq $who } (@masters) == 0);
218 if ($msg =~ /^fics (.*?)$/) {
219 $t->cmd("tell $who Executing '$1' on FICS.");
221 } elsif ($msg =~ /^uci (.*?)$/) {
222 $t->cmd("tell $who Sending '$1' to the engine.");
223 print { $engine->{'write'} } "$1\n";
225 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
228 #print "FICS: [$line]\n";
232 my ($engine, @x) = @_;
235 my $info = $engine->{'info'};
237 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
238 for my $i (0..$#x - 1) {
239 if ($x[$i] =~ 'multipv') {
245 while (scalar @x > 0) {
246 if ($x[0] =~ 'multipv') {
252 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
254 my $value = shift @x;
255 $info->{$key} = $value;
258 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
260 my $value = shift @x;
261 $info->{$key . $mpv} = $value;
264 if ($x[0] eq 'score') {
267 delete $info->{'score_cp' . $mpv};
268 delete $info->{'score_mate' . $mpv};
270 while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
273 $info->{'score_cp' . $mpv} = shift @x;
274 } elsif ($x[0] eq 'mate') {
276 $info->{'score_mate' . $mpv} = shift @x;
284 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
287 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
291 #print "unknown info '$x[0]', trying to recover...\n";
293 die "Unknown info '" . join(',', @x) . "'";
299 my ($engine, @x) = @_;
301 while (scalar @x > 0) {
302 if ($x[0] =~ /^(name|author)$/) {
304 my $value = join(' ', @x);
305 $engine->{'id'}{$key} = $value;
315 my ($board, @pvs) = @_;
317 if (scalar @pvs == 0 || !defined($pvs[0])) {
322 my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
323 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
324 return ($pretty, prettyprint_pv($nb, @pvs));
330 return if (!defined($pos_calculating));
332 # Don't update too often.
333 my $age = Time::HiRes::tv_interval($latest_update);
334 if ($age < $update_max_interval) {
335 Time::HiRes::alarm($update_max_interval + 0.01 - $age);
339 my $info = $engine->{'info'};
342 # Some programs _always_ report MultiPV, even with only one PV.
343 # In this case, we simply use that data as if MultiPV was never
346 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
347 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
348 if (exists($info->{$key . '1'})) {
349 $info->{$key} = $info->{$key . '1'};
355 # Check the PVs first. if they're invalid, just wait, as our data
356 # is most likely out of sync. This isn't a very good solution, as
357 # it can frequently miss stuff, but it's good enough for most users.
361 if (exists($info->{'pv'})) {
362 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
366 while (exists($info->{'pv' . $mpv})) {
367 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
372 $engine->{'info'} = {};
378 $latest_update = [Time::HiRes::gettimeofday];
382 my $info = $engine->{'info'};
383 my $id = $engine->{'id'};
385 my $text = 'Analysis';
386 if ($pos_calculating->{'last_move'} ne 'none') {
387 if ($pos_calculating->{'toplay'} eq 'W') {
388 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
390 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
392 if (exists($id->{'name'})) {
397 if (exists($id->{'name'})) {
398 $text .= " by $id->{'name'}:\n\n";
403 return unless (exists($pos_calculating->{'board'}));
405 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
408 while (exists($info->{'pv' . $mpv})) {
409 $text .= sprintf " PV%2u", $mpv;
410 my $score = short_score($info, $pos_calculating, $mpv);
411 $text .= " ($score)" if (defined($score));
414 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
415 if ($info->{'tbhits' . $mpv} == 1) {
416 $tbhits = ", 1 tbhit";
418 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
422 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
423 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
424 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
428 $text .= " " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
434 my $score = long_score($info, $pos_calculating, '');
435 $text .= " $score\n" if defined($score);
436 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
439 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
440 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
441 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
443 if (exists($info->{'seldepth'})) {
444 $text .= sprintf " (%u selective)", $info->{'seldepth'};
446 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
447 if ($info->{'tbhits'} == 1) {
448 $text .= ", one Syzygy hit";
450 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
456 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
458 my @refutation_lines = ();
459 if (defined($engine2)) {
460 for (my $mpv = 1; $mpv < 500; ++$mpv) {
461 my $info = $engine2->{'info'};
462 last if (!exists($info->{'pv' . $mpv}));
464 my $pv = $info->{'pv' . $mpv};
466 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine->{'board'}, $pv->[0]));
467 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine->{'board'}, @$pv);
468 if (scalar @pretty_pv > 5) {
469 @pretty_pv = @pretty_pv[0..4];
470 push @pretty_pv, "...";
472 my $key = $pretty_move;
473 my $line = sprintf(" %-6s %6s %3s %s",
475 short_score($info, $pos_calculating_second_engine, $mpv, 0),
476 "d" . $info->{'depth' . $mpv},
477 join(', ', @pretty_pv));
478 push @refutation_lines, [ $key, $line ];
483 if ($#refutation_lines >= 0) {
484 $text .= "Shallow search of all legal moves:\n\n";
485 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
486 $text .= $line->[1] . "\n";
491 if ($last_text ne $text) {
492 print "
\e[H
\e[2J"; # clear the screen
499 my $info = $engine->{'info'};
502 $json->{'position'} = $pos_calculating->to_json_hash();
503 $json->{'id'} = $engine->{'id'};
504 $json->{'score'} = long_score($info, $pos_calculating, '');
506 $json->{'nodes'} = $info->{'nodes'};
507 $json->{'nps'} = $info->{'nps'};
508 $json->{'depth'} = $info->{'depth'};
509 $json->{'tbhits'} = $info->{'tbhits'};
510 $json->{'seldepth'} = $info->{'seldepth'};
512 # single-PV only for now
513 $json->{'pv_uci'} = $info->{'pv'};
514 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}) ];
516 my %refutation_lines = ();
517 my @refutation_lines = ();
518 if (defined($engine2)) {
519 for (my $mpv = 1; $mpv < 500; ++$mpv) {
520 my $info = $engine2->{'info'};
521 my $pretty_move = "";
523 last if (!exists($info->{'pv' . $mpv}));
526 my $pv = $info->{'pv' . $mpv};
527 my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $pv->[0]));
528 my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, @$pv);
529 $refutation_lines{$pv->[0]} = {
530 sort_key => $pretty_move,
531 depth => $info->{'depth' . $mpv},
532 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
533 pretty_score => short_score($info, $pos_calculating, $mpv, 0),
534 pretty_move => $pretty_move,
535 pv_pretty => \@pretty_pv,
537 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
541 $json->{'refutation_lines'} = \%refutation_lines;
543 open my $fh, ">/srv/analysis.sesse.net/www/analysis.json.tmp"
545 print $fh JSON::XS::encode_json($json);
547 rename("/srv/analysis.sesse.net/www/analysis.json.tmp", "/srv/analysis.sesse.net/www/analysis.json");
551 my ($engine, $msg) = @_;
552 $engine->print($msg);
553 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
557 my ($info, $pos, $mpv, $invert) = @_;
560 if ($pos->{'toplay'} eq 'B') {
564 if (defined($info->{'score_mate' . $mpv})) {
566 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
568 return sprintf "M%3d", $info->{'score_mate' . $mpv};
571 if (exists($info->{'score_cp' . $mpv})) {
572 my $score = $info->{'score_cp' . $mpv} * 0.01;
579 return sprintf "%+5.2f", $score;
587 my ($info, $pos, $mpv, $invert) = @_;
589 if (defined($info->{'score_mate' . $mpv})) {
591 return 99999 - $info->{'score_mate' . $mpv};
593 return -(99999 - $info->{'score_mate' . $mpv});
596 if (exists($info->{'score_cp' . $mpv})) {
597 my $score = $info->{'score_cp' . $mpv};
609 my ($info, $pos, $mpv) = @_;
611 if (defined($info->{'score_mate' . $mpv})) {
612 my $mate = $info->{'score_mate' . $mpv};
613 if ($pos->{'toplay'} eq 'B') {
617 return sprintf "White mates in %u", $mate;
619 return sprintf "Black mates in %u", -$mate;
622 if (exists($info->{'score_cp' . $mpv})) {
623 my $score = $info->{'score_cp' . $mpv} * 0.01;
625 return "Score: 0.00";
627 if ($pos->{'toplay'} eq 'B') {
630 return sprintf "Score: %+5.2f", $score;
639 my ($fen, $board, $toplay) = @_;
641 if (exists($book_cache{$fen})) {
642 return $book_cache{$fen};
645 my $ret = `./booklook $fen`;
646 return "" if ($ret =~ /Not found/ || $ret eq '');
650 for my $m (split /\n/, $ret) {
651 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
655 $pmove = '(current)';
657 ($pmove) = prettyprint_pv($board, $move);
658 $pmove .= $annotation;
662 if ($toplay eq 'W') {
663 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
665 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
667 my $n = $win + $draw + $lose;
673 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
676 push @moves, [ $pmove, $n, $percent, $rating ];
679 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
681 my $text = "Book moves:\n\n Perf. N Rating\n\n";
683 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
690 my ($cmdline, $tag, $cb) = @_;
691 return undef if (!defined($cmdline));
692 return Engine->open($cmdline, $tag, $cb);
695 sub col_letter_to_num {
696 return ord(shift) - ord('a');
699 sub row_letter_to_num {
700 return 7 - (ord(shift) - ord('1'));
705 my $from_col = col_letter_to_num(substr($move, 0, 1));
706 my $from_row = row_letter_to_num(substr($move, 1, 1));
707 my $to_col = col_letter_to_num(substr($move, 2, 1));
708 my $to_row = row_letter_to_num(substr($move, 3, 1));
709 my $promo = substr($move, 4, 1);
710 return ($from_col, $from_row, $to_col, $to_row, $promo);