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.");
183 } elsif ($msg =~ /^quit$/) {
184 $t->cmd("tell $who Bye bye.");
187 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
190 #print "FICS: [$line]\n";
194 my ($body, $header, $url) = @_;
195 my $pgn = Chess::PGN::Parse->new(undef, $body);
196 if (!defined($pgn) || !$pgn->read_game()) {
197 warn "Error in parsing PGN from $url\n";
199 $pgn->quick_parse_game;
200 my $pos = Position->start_pos($pgn->white, $pgn->black);
201 my $moves = $pgn->moves;
202 for my $move (@$moves) {
203 my ($from_row, $from_col, $to_row, $to_col, $promo) = $pos->parse_pretty_move($move);
204 $pos = $pos->make_move($from_row, $from_col, $to_row, $to_col, $promo);
206 handle_position($pos);
209 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
210 AnyEvent::HTTP::http_get($url, sub {
211 handle_pgn(@_, $url);
216 sub handle_position {
219 # if this is already in the queue, ignore it
220 return if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
222 # if we're already chewing on this and there's nothing else in the queue,
224 return if (!defined($pos_waiting) && defined($pos_calculating) &&
225 $pos->fen() eq $pos_calculating->fen());
227 # if we're already thinking on something, stop and wait for the engine
229 if (defined($pos_calculating)) {
230 if (!defined($pos_waiting)) {
231 uciprint($engine, "stop");
233 if ($uci_assume_full_compliance) {
236 uciprint($engine, "position fen " . $pos->fen());
237 uciprint($engine, "go infinite");
238 $pos_calculating = $pos;
241 # it's wrong just to give the FEN (the move history is useful,
242 # and per the UCI spec, we should really have sent "ucinewgame"),
244 uciprint($engine, "position fen " . $pos->fen());
245 uciprint($engine, "go infinite");
246 $pos_calculating = $pos;
249 if (defined($engine2)) {
250 if (defined($pos_calculating_second_engine)) {
251 uciprint($engine2, "stop");
253 uciprint($engine2, "position fen " . $pos->fen());
254 uciprint($engine2, "go infinite");
255 $pos_calculating_second_engine = $pos;
257 $engine2->{'info'} = {};
260 $engine->{'info'} = {};
264 # Output a command every move to note that we're
265 # still paying attention -- this is a good tradeoff,
266 # since if no move has happened in the last half
267 # hour, the analysis/relay has most likely stopped
268 # and we should stop hogging server resources.
274 my ($engine, @x) = @_;
277 my $info = $engine->{'info'};
279 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
280 for my $i (0..$#x - 1) {
281 if ($x[$i] =~ 'multipv') {
287 while (scalar @x > 0) {
288 if ($x[0] =~ 'multipv') {
294 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
296 my $value = shift @x;
297 $info->{$key} = $value;
300 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
302 my $value = shift @x;
303 $info->{$key . $mpv} = $value;
306 if ($x[0] eq 'score') {
309 delete $info->{'score_cp' . $mpv};
310 delete $info->{'score_mate' . $mpv};
312 while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
315 $info->{'score_cp' . $mpv} = shift @x;
316 } elsif ($x[0] eq 'mate') {
318 $info->{'score_mate' . $mpv} = shift @x;
326 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
329 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
333 #print "unknown info '$x[0]', trying to recover...\n";
335 die "Unknown info '" . join(',', @x) . "'";
341 my ($engine, @x) = @_;
343 while (scalar @x > 0) {
344 if ($x[0] =~ /^(name|author)$/) {
346 my $value = join(' ', @x);
347 $engine->{'id'}{$key} = $value;
356 sub prettyprint_pv_no_cache {
357 my ($board, @pvs) = @_;
359 if (scalar @pvs == 0 || !defined($pvs[0])) {
364 my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
365 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
366 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
370 my ($pos, @pvs) = @_;
372 my $cachekey = join('', @pvs);
373 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
374 return @{$pos->{'prettyprint_cache'}{$cachekey}};
376 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
377 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
385 return if (!defined($pos_calculating));
387 # Don't update too often.
388 my $age = Time::HiRes::tv_interval($latest_update);
389 if ($age < $update_max_interval) {
390 Time::HiRes::alarm($update_max_interval + 0.01 - $age);
394 my $info = $engine->{'info'};
397 # Some programs _always_ report MultiPV, even with only one PV.
398 # In this case, we simply use that data as if MultiPV was never
401 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
402 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
403 if (exists($info->{$key . '1'})) {
404 $info->{$key} = $info->{$key . '1'};
410 # Check the PVs first. if they're invalid, just wait, as our data
411 # is most likely out of sync. This isn't a very good solution, as
412 # it can frequently miss stuff, but it's good enough for most users.
416 if (exists($info->{'pv'})) {
417 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
421 while (exists($info->{'pv' . $mpv})) {
422 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
427 $engine->{'info'} = {};
433 $latest_update = [Time::HiRes::gettimeofday];
437 my $info = $engine->{'info'};
438 my $id = $engine->{'id'};
440 my $text = 'Analysis';
441 if ($pos_calculating->{'last_move'} ne 'none') {
442 if ($pos_calculating->{'toplay'} eq 'W') {
443 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
445 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
447 if (exists($id->{'name'})) {
452 if (exists($id->{'name'})) {
453 $text .= " by $id->{'name'}:\n\n";
458 return unless (exists($pos_calculating->{'board'}));
460 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
463 while (exists($info->{'pv' . $mpv})) {
464 $text .= sprintf " PV%2u", $mpv;
465 my $score = short_score($info, $pos_calculating, $mpv);
466 $text .= " ($score)" if (defined($score));
469 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
470 if ($info->{'tbhits' . $mpv} == 1) {
471 $tbhits = ", 1 tbhit";
473 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
477 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
478 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
479 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
483 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
489 my $score = long_score($info, $pos_calculating, '');
490 $text .= " $score\n" if defined($score);
491 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
494 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
495 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
496 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
498 if (exists($info->{'seldepth'})) {
499 $text .= sprintf " (%u selective)", $info->{'seldepth'};
501 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
502 if ($info->{'tbhits'} == 1) {
503 $text .= ", one Syzygy hit";
505 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
511 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
513 my @refutation_lines = ();
514 if (defined($engine2)) {
515 for (my $mpv = 1; $mpv < 500; ++$mpv) {
516 my $info = $engine2->{'info'};
517 last if (!exists($info->{'pv' . $mpv}));
519 my $pv = $info->{'pv' . $mpv};
521 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
522 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
523 if (scalar @pretty_pv > 5) {
524 @pretty_pv = @pretty_pv[0..4];
525 push @pretty_pv, "...";
527 my $key = $pretty_move;
528 my $line = sprintf(" %-6s %6s %3s %s",
530 short_score($info, $pos_calculating_second_engine, $mpv, 0),
531 "d" . $info->{'depth' . $mpv},
532 join(', ', @pretty_pv));
533 push @refutation_lines, [ $key, $line ];
538 if ($#refutation_lines >= 0) {
539 $text .= "Shallow search of all legal moves:\n\n";
540 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
541 $text .= $line->[1] . "\n";
546 if ($last_text ne $text) {
547 print "
\e[H
\e[2J"; # clear the screen
554 my $info = $engine->{'info'};
557 $json->{'position'} = $pos_calculating->to_json_hash();
558 $json->{'id'} = $engine->{'id'};
559 $json->{'score'} = long_score($info, $pos_calculating, '');
561 $json->{'nodes'} = $info->{'nodes'};
562 $json->{'nps'} = $info->{'nps'};
563 $json->{'depth'} = $info->{'depth'};
564 $json->{'tbhits'} = $info->{'tbhits'};
565 $json->{'seldepth'} = $info->{'seldepth'};
567 # single-PV only for now
568 $json->{'pv_uci'} = $info->{'pv'};
569 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
571 my %refutation_lines = ();
572 my @refutation_lines = ();
573 if (defined($engine2)) {
574 for (my $mpv = 1; $mpv < 500; ++$mpv) {
575 my $info = $engine2->{'info'};
576 my $pretty_move = "";
578 last if (!exists($info->{'pv' . $mpv}));
581 my $pv = $info->{'pv' . $mpv};
582 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
583 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
584 $refutation_lines{$pv->[0]} = {
585 sort_key => $pretty_move,
586 depth => $info->{'depth' . $mpv},
587 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
588 pretty_score => short_score($info, $pos_calculating, $mpv, 0),
589 pretty_move => $pretty_move,
590 pv_pretty => \@pretty_pv,
592 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
596 $json->{'refutation_lines'} = \%refutation_lines;
598 open my $fh, ">/srv/analysis.sesse.net/www/analysis.json.tmp"
600 print $fh JSON::XS::encode_json($json);
602 rename("/srv/analysis.sesse.net/www/analysis.json.tmp", "/srv/analysis.sesse.net/www/analysis.json");
606 my ($engine, $msg) = @_;
607 $engine->print($msg);
608 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
612 my ($info, $pos, $mpv, $invert) = @_;
615 if ($pos->{'toplay'} eq 'B') {
619 if (defined($info->{'score_mate' . $mpv})) {
621 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
623 return sprintf "M%3d", $info->{'score_mate' . $mpv};
626 if (exists($info->{'score_cp' . $mpv})) {
627 my $score = $info->{'score_cp' . $mpv} * 0.01;
634 return sprintf "%+5.2f", $score;
642 my ($info, $pos, $mpv, $invert) = @_;
644 if (defined($info->{'score_mate' . $mpv})) {
646 return 99999 - $info->{'score_mate' . $mpv};
648 return -(99999 - $info->{'score_mate' . $mpv});
651 if (exists($info->{'score_cp' . $mpv})) {
652 my $score = $info->{'score_cp' . $mpv};
664 my ($info, $pos, $mpv) = @_;
666 if (defined($info->{'score_mate' . $mpv})) {
667 my $mate = $info->{'score_mate' . $mpv};
668 if ($pos->{'toplay'} eq 'B') {
672 return sprintf "White mates in %u", $mate;
674 return sprintf "Black mates in %u", -$mate;
677 if (exists($info->{'score_cp' . $mpv})) {
678 my $score = $info->{'score_cp' . $mpv} * 0.01;
680 return "Score: 0.00";
682 if ($pos->{'toplay'} eq 'B') {
685 return sprintf "Score: %+5.2f", $score;
694 my ($fen, $board, $toplay) = @_;
696 if (exists($book_cache{$fen})) {
697 return $book_cache{$fen};
700 my $ret = `./booklook $fen`;
701 return "" if ($ret =~ /Not found/ || $ret eq '');
705 for my $m (split /\n/, $ret) {
706 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
710 $pmove = '(current)';
712 ($pmove) = prettyprint_pv_no_cache($board, $move);
713 $pmove .= $annotation;
717 if ($toplay eq 'W') {
718 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
720 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
722 my $n = $win + $draw + $lose;
728 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
731 push @moves, [ $pmove, $n, $percent, $rating ];
734 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
736 my $text = "Book moves:\n\n Perf. N Rating\n\n";
738 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
745 my ($cmdline, $tag, $cb) = @_;
746 return undef if (!defined($cmdline));
747 return Engine->open($cmdline, $tag, $cb);
750 sub col_letter_to_num {
751 return ord(shift) - ord('a');
754 sub row_letter_to_num {
755 return 7 - (ord(shift) - ord('1'));
760 my $from_col = col_letter_to_num(substr($move, 0, 1));
761 my $from_row = row_letter_to_num(substr($move, 1, 1));
762 my $to_col = col_letter_to_num(substr($move, 2, 1));
763 my $to_row = row_letter_to_num(substr($move, 3, 1));
764 my $promo = substr($move, 4, 1);
765 return ($from_col, $from_row, $to_col, $to_row, $promo);