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.
15 use Chess::PGN::Parse;
22 require 'Position.pm';
28 my $server = "freechess.org";
29 my $target = "GMCarlsen";
30 my $engine_cmdline = "'./Deep Rybka 4 SSE42 x64'";
31 my $engine2_cmdline = "./stockfish_13111119_x64_modern_sse42"; # undef for none
32 my $uci_assume_full_compliance = 0; # dangerous :-)
33 my $update_max_interval = 1.0;
43 $SIG{ALRM} = sub { output(); };
44 my $latest_update = undef;
45 my $http_timer = undef;
49 open(FICSLOG, ">ficslog.txt")
50 or die "ficslog.txt: $!";
51 print FICSLOG "Log starting.\n";
55 open(UCILOG, ">ucilog.txt")
56 or die "ucilog.txt: $!";
57 print UCILOG "Log starting.\n";
62 # open the chess engine
63 my $engine = open_engine($engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
64 my $engine2 = open_engine($engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
67 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
69 uciprint($engine, "setoption name UCI_AnalyseMode value true");
70 # uciprint($engine, "setoption name NalimovPath value /srv/tablebase");
71 uciprint($engine, "setoption name NalimovUsage value Rarely");
72 uciprint($engine, "setoption name Hash value 1024");
73 # uciprint($engine, "setoption name MultiPV value 2");
74 uciprint($engine, "ucinewgame");
76 if (defined($engine2)) {
77 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
78 # uciprint($engine2, "setoption name NalimovPath value /srv/tablebase");
79 uciprint($engine2, "setoption name NalimovUsage value Rarely");
80 uciprint($engine2, "setoption name Hash value 1024");
81 uciprint($engine2, "setoption name Threads value 8");
82 uciprint($engine2, "setoption name MultiPV value 500");
83 uciprint($engine2, "ucinewgame");
86 print "Chess engine ready.\n";
89 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
90 $t->input_log(\*FICSLOG);
92 $t->print("SesseBOT");
93 $t->waitfor('/Press return to enter the server/');
97 $t->cmd("set shout 0");
98 $t->cmd("set seek 0");
99 $t->cmd("set style 12");
100 $t->cmd("observe $target");
101 print "FICS ready.\n";
103 my $ev1 = AnyEvent->io(
106 cb => sub { # what callback to execute
108 my $line = $t->getline(Timeout => 0, errmode => 'return');
109 return if (!defined($line));
117 # Engine events have already been set up by Engine.pm.
121 my ($engine, $line, $primary) = @_;
123 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
124 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
125 if ($line =~ /^info/) {
126 my (@infos) = split / /, $line;
129 parse_infos($engine, @infos);
131 if ($line =~ /^id/) {
132 my (@ids) = split / /, $line;
135 parse_ids($engine, @ids);
137 if ($line =~ /^bestmove/) {
139 return if (!$uci_assume_full_compliance);
140 if (defined($pos_waiting)) {
141 uciprint($engine, "position fen " . $pos_waiting->fen());
142 uciprint($engine, "go infinite");
144 $pos_calculating = $pos_waiting;
145 $pos_waiting = undef;
148 $engine2->{'info'} = {};
149 my $pos = $pos_waiting // $pos_calculating;
150 uciprint($engine2, "position fen " . $pos->fen());
151 uciprint($engine2, "go infinite");
152 $pos_calculating_second_engine = $pos;
160 if ($line =~ /^<12> /) {
161 handle_position(Position->new($line));
163 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
164 my ($who, $msg) = ($1, $2);
166 next if (grep { $_ eq $who } (@masters) == 0);
168 if ($msg =~ /^fics (.*?)$/) {
169 $t->cmd("tell $who Executing '$1' on FICS.");
171 } elsif ($msg =~ /^uci (.*?)$/) {
172 $t->cmd("tell $who Sending '$1' to the engine.");
173 print { $engine->{'write'} } "$1\n";
174 } elsif ($msg =~ /^pgn (.*?)$/) {
176 $t->cmd("tell $who Starting to poll '$url'.");
177 AnyEvent::HTTP::http_get($url, sub {
178 handle_pgn(@_, $url);
180 } elsif ($msg =~ /^stoppgn$/) {
181 $t->cmd("tell $who Stopping poll.");
184 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
187 #print "FICS: [$line]\n";
191 my ($body, $header, $url) = @_;
192 my $pgn = Chess::PGN::Parse->new(undef, $body);
193 if (!defined($pgn) || !$pgn->read_game()) {
194 warn "Error in parsing PGN from $url\n";
196 $pgn->quick_parse_game;
197 my $pos = Position->start_pos($pgn->white, $pgn->black);
198 my $moves = $pgn->moves;
199 for my $move (@$moves) {
200 my ($from_row, $from_col, $to_row, $to_col, $promo) = $pos->parse_pretty_move($move);
201 $pos = $pos->make_move($from_row, $from_col, $to_row, $to_col, $promo);
203 handle_position($pos);
206 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
207 AnyEvent::HTTP::http_get($url, sub {
208 handle_pgn(@_, $url);
213 sub handle_position {
216 # if this is already in the queue, ignore it
217 return if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
219 # if we're already chewing on this and there's nothing else in the queue,
221 return if (!defined($pos_waiting) && defined($pos_calculating) &&
222 $pos->fen() eq $pos_calculating->fen());
224 # if we're already thinking on something, stop and wait for the engine
226 if (defined($pos_calculating)) {
227 if (!defined($pos_waiting)) {
228 uciprint($engine, "stop");
230 if ($uci_assume_full_compliance) {
233 uciprint($engine, "position fen " . $pos->fen());
234 uciprint($engine, "go infinite");
235 $pos_calculating = $pos;
238 # it's wrong just to give the FEN (the move history is useful,
239 # and per the UCI spec, we should really have sent "ucinewgame"),
241 uciprint($engine, "position fen " . $pos->fen());
242 uciprint($engine, "go infinite");
243 $pos_calculating = $pos;
246 if (defined($engine2)) {
247 if (defined($pos_calculating_second_engine)) {
248 uciprint($engine2, "stop");
250 uciprint($engine2, "position fen " . $pos->fen());
251 uciprint($engine2, "go infinite");
252 $pos_calculating_second_engine = $pos;
254 $engine2->{'info'} = {};
257 $engine->{'info'} = {};
261 # Output a command every move to note that we're
262 # still paying attention -- this is a good tradeoff,
263 # since if no move has happened in the last half
264 # hour, the analysis/relay has most likely stopped
265 # and we should stop hogging server resources.
271 my ($engine, @x) = @_;
274 my $info = $engine->{'info'};
276 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
277 for my $i (0..$#x - 1) {
278 if ($x[$i] =~ 'multipv') {
284 while (scalar @x > 0) {
285 if ($x[0] =~ 'multipv') {
291 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
293 my $value = shift @x;
294 $info->{$key} = $value;
297 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
299 my $value = shift @x;
300 $info->{$key . $mpv} = $value;
303 if ($x[0] eq 'score') {
306 delete $info->{'score_cp' . $mpv};
307 delete $info->{'score_mate' . $mpv};
309 while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
312 $info->{'score_cp' . $mpv} = shift @x;
313 } elsif ($x[0] eq 'mate') {
315 $info->{'score_mate' . $mpv} = shift @x;
323 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
326 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
330 #print "unknown info '$x[0]', trying to recover...\n";
332 die "Unknown info '" . join(',', @x) . "'";
338 my ($engine, @x) = @_;
340 while (scalar @x > 0) {
341 if ($x[0] =~ /^(name|author)$/) {
343 my $value = join(' ', @x);
344 $engine->{'id'}{$key} = $value;
354 my ($board, @pvs) = @_;
356 if (scalar @pvs == 0 || !defined($pvs[0])) {
361 my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
362 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
363 return ($pretty, prettyprint_pv($nb, @pvs));
369 return if (!defined($pos_calculating));
371 # Don't update too often.
372 my $age = Time::HiRes::tv_interval($latest_update);
373 if ($age < $update_max_interval) {
374 Time::HiRes::alarm($update_max_interval + 0.01 - $age);
378 my $info = $engine->{'info'};
381 # Some programs _always_ report MultiPV, even with only one PV.
382 # In this case, we simply use that data as if MultiPV was never
385 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
386 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
387 if (exists($info->{$key . '1'})) {
388 $info->{$key} = $info->{$key . '1'};
394 # Check the PVs first. if they're invalid, just wait, as our data
395 # is most likely out of sync. This isn't a very good solution, as
396 # it can frequently miss stuff, but it's good enough for most users.
400 if (exists($info->{'pv'})) {
401 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
405 while (exists($info->{'pv' . $mpv})) {
406 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
411 $engine->{'info'} = {};
417 $latest_update = [Time::HiRes::gettimeofday];
421 my $info = $engine->{'info'};
422 my $id = $engine->{'id'};
424 my $text = 'Analysis';
425 if ($pos_calculating->{'last_move'} ne 'none') {
426 if ($pos_calculating->{'toplay'} eq 'W') {
427 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
429 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
431 if (exists($id->{'name'})) {
436 if (exists($id->{'name'})) {
437 $text .= " by $id->{'name'}:\n\n";
442 return unless (exists($pos_calculating->{'board'}));
444 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
447 while (exists($info->{'pv' . $mpv})) {
448 $text .= sprintf " PV%2u", $mpv;
449 my $score = short_score($info, $pos_calculating, $mpv);
450 $text .= " ($score)" if (defined($score));
453 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
454 if ($info->{'tbhits' . $mpv} == 1) {
455 $tbhits = ", 1 tbhit";
457 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
461 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
462 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
463 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
467 $text .= " " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
473 my $score = long_score($info, $pos_calculating, '');
474 $text .= " $score\n" if defined($score);
475 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
478 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
479 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
480 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
482 if (exists($info->{'seldepth'})) {
483 $text .= sprintf " (%u selective)", $info->{'seldepth'};
485 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
486 if ($info->{'tbhits'} == 1) {
487 $text .= ", one Syzygy hit";
489 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
495 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
497 my @refutation_lines = ();
498 if (defined($engine2)) {
499 for (my $mpv = 1; $mpv < 500; ++$mpv) {
500 my $info = $engine2->{'info'};
501 last if (!exists($info->{'pv' . $mpv}));
503 my $pv = $info->{'pv' . $mpv};
505 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine->{'board'}, $pv->[0]));
506 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine->{'board'}, @$pv);
507 if (scalar @pretty_pv > 5) {
508 @pretty_pv = @pretty_pv[0..4];
509 push @pretty_pv, "...";
511 my $key = $pretty_move;
512 my $line = sprintf(" %-6s %6s %3s %s",
514 short_score($info, $pos_calculating_second_engine, $mpv, 0),
515 "d" . $info->{'depth' . $mpv},
516 join(', ', @pretty_pv));
517 push @refutation_lines, [ $key, $line ];
522 if ($#refutation_lines >= 0) {
523 $text .= "Shallow search of all legal moves:\n\n";
524 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
525 $text .= $line->[1] . "\n";
530 if ($last_text ne $text) {
531 print "
\e[H
\e[2J"; # clear the screen
538 my $info = $engine->{'info'};
541 $json->{'position'} = $pos_calculating->to_json_hash();
542 $json->{'id'} = $engine->{'id'};
543 $json->{'score'} = long_score($info, $pos_calculating, '');
545 $json->{'nodes'} = $info->{'nodes'};
546 $json->{'nps'} = $info->{'nps'};
547 $json->{'depth'} = $info->{'depth'};
548 $json->{'tbhits'} = $info->{'tbhits'};
549 $json->{'seldepth'} = $info->{'seldepth'};
551 # single-PV only for now
552 $json->{'pv_uci'} = $info->{'pv'};
553 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}) ];
555 my %refutation_lines = ();
556 my @refutation_lines = ();
557 if (defined($engine2)) {
558 for (my $mpv = 1; $mpv < 500; ++$mpv) {
559 my $info = $engine2->{'info'};
560 my $pretty_move = "";
562 last if (!exists($info->{'pv' . $mpv}));
565 my $pv = $info->{'pv' . $mpv};
566 my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $pv->[0]));
567 my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, @$pv);
568 $refutation_lines{$pv->[0]} = {
569 sort_key => $pretty_move,
570 depth => $info->{'depth' . $mpv},
571 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
572 pretty_score => short_score($info, $pos_calculating, $mpv, 0),
573 pretty_move => $pretty_move,
574 pv_pretty => \@pretty_pv,
576 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
580 $json->{'refutation_lines'} = \%refutation_lines;
582 open my $fh, ">/srv/analysis.sesse.net/www/analysis.json.tmp"
584 print $fh JSON::XS::encode_json($json);
586 rename("/srv/analysis.sesse.net/www/analysis.json.tmp", "/srv/analysis.sesse.net/www/analysis.json");
590 my ($engine, $msg) = @_;
591 $engine->print($msg);
592 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
596 my ($info, $pos, $mpv, $invert) = @_;
599 if ($pos->{'toplay'} eq 'B') {
603 if (defined($info->{'score_mate' . $mpv})) {
605 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
607 return sprintf "M%3d", $info->{'score_mate' . $mpv};
610 if (exists($info->{'score_cp' . $mpv})) {
611 my $score = $info->{'score_cp' . $mpv} * 0.01;
618 return sprintf "%+5.2f", $score;
626 my ($info, $pos, $mpv, $invert) = @_;
628 if (defined($info->{'score_mate' . $mpv})) {
630 return 99999 - $info->{'score_mate' . $mpv};
632 return -(99999 - $info->{'score_mate' . $mpv});
635 if (exists($info->{'score_cp' . $mpv})) {
636 my $score = $info->{'score_cp' . $mpv};
648 my ($info, $pos, $mpv) = @_;
650 if (defined($info->{'score_mate' . $mpv})) {
651 my $mate = $info->{'score_mate' . $mpv};
652 if ($pos->{'toplay'} eq 'B') {
656 return sprintf "White mates in %u", $mate;
658 return sprintf "Black mates in %u", -$mate;
661 if (exists($info->{'score_cp' . $mpv})) {
662 my $score = $info->{'score_cp' . $mpv} * 0.01;
664 return "Score: 0.00";
666 if ($pos->{'toplay'} eq 'B') {
669 return sprintf "Score: %+5.2f", $score;
678 my ($fen, $board, $toplay) = @_;
680 if (exists($book_cache{$fen})) {
681 return $book_cache{$fen};
684 my $ret = `./booklook $fen`;
685 return "" if ($ret =~ /Not found/ || $ret eq '');
689 for my $m (split /\n/, $ret) {
690 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
694 $pmove = '(current)';
696 ($pmove) = prettyprint_pv($board, $move);
697 $pmove .= $annotation;
701 if ($toplay eq 'W') {
702 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
704 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
706 my $n = $win + $draw + $lose;
712 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
715 push @moves, [ $pmove, $n, $percent, $rating ];
718 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
720 my $text = "Book moves:\n\n Perf. N Rating\n\n";
722 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
729 my ($cmdline, $tag, $cb) = @_;
730 return undef if (!defined($cmdline));
731 return Engine->open($cmdline, $tag, $cb);
734 sub col_letter_to_num {
735 return ord(shift) - ord('a');
738 sub row_letter_to_num {
739 return 7 - (ord(shift) - ord('1'));
744 my $from_col = col_letter_to_num(substr($move, 0, 1));
745 my $from_row = row_letter_to_num(substr($move, 1, 1));
746 my $to_col = col_letter_to_num(substr($move, 2, 1));
747 my $to_row = row_letter_to_num(substr($move, 3, 1));
748 my $promo = substr($move, 4, 1);
749 return ($from_col, $from_row, $to_col, $to_row, $promo);