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';
30 $SIG{ALRM} = sub { output(); };
31 my $latest_update = undef;
32 my $http_timer = undef;
36 open(FICSLOG, ">ficslog.txt")
37 or die "ficslog.txt: $!";
38 print FICSLOG "Log starting.\n";
42 open(UCILOG, ">ucilog.txt")
43 or die "ucilog.txt: $!";
44 print UCILOG "Log starting.\n";
49 # open the chess engine
50 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
51 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
54 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
56 uciprint($engine, "setoption name UCI_AnalyseMode value true");
57 while (my ($key, $value) = each %remoteglotconf::engine_config) {
58 uciprint($engine, "setoption name $key value $value");
60 uciprint($engine, "ucinewgame");
62 if (defined($engine2)) {
63 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
64 while (my ($key, $value) = each %remoteglotconf::engine2_config) {
65 uciprint($engine2, "setoption name $key value $value");
67 uciprint($engine2, "setoption name MultiPV value 500");
68 uciprint($engine2, "ucinewgame");
71 print "Chess engine ready.\n";
74 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
75 $t->input_log(\*FICSLOG);
76 $t->open($remoteglotconf::server);
77 $t->print($remoteglotconf::nick);
78 $t->waitfor('/Press return to enter the server/');
82 $t->cmd("set shout 0");
83 $t->cmd("set seek 0");
84 $t->cmd("set style 12");
85 $t->cmd("observe $remoteglotconf::target");
86 print "FICS ready.\n";
88 my $ev1 = AnyEvent->io(
91 cb => sub { # what callback to execute
93 my $line = $t->getline(Timeout => 0, errmode => 'return');
94 return if (!defined($line));
102 # Engine events have already been set up by Engine.pm.
106 my ($engine, $line, $primary) = @_;
108 return if $line =~ /(upper|lower)bound/;
110 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
111 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
112 if ($line =~ /^info/) {
113 my (@infos) = split / /, $line;
116 parse_infos($engine, @infos);
118 if ($line =~ /^id/) {
119 my (@ids) = split / /, $line;
122 parse_ids($engine, @ids);
124 if ($line =~ /^bestmove/) {
126 return if (!$remoteglotconf::uci_assume_full_compliance);
127 if (defined($pos_waiting)) {
128 uciprint($engine, "position fen " . $pos_waiting->fen());
129 uciprint($engine, "go infinite");
131 $pos_calculating = $pos_waiting;
132 $pos_waiting = undef;
135 $engine2->{'info'} = {};
136 my $pos = $pos_waiting // $pos_calculating;
137 uciprint($engine2, "position fen " . $pos->fen());
138 uciprint($engine2, "go infinite");
139 $pos_calculating_second_engine = $pos;
147 if ($line =~ /^<12> /) {
148 handle_position(Position->new($line));
150 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
151 my ($who, $msg) = ($1, $2);
153 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
155 if ($msg =~ /^fics (.*?)$/) {
156 $t->cmd("tell $who Executing '$1' on FICS.");
158 } elsif ($msg =~ /^uci (.*?)$/) {
159 $t->cmd("tell $who Sending '$1' to the engine.");
160 print { $engine->{'write'} } "$1\n";
161 } elsif ($msg =~ /^pgn (.*?)$/) {
163 $t->cmd("tell $who Starting to poll '$url'.");
164 AnyEvent::HTTP::http_get($url, sub {
165 handle_pgn(@_, $url);
167 } elsif ($msg =~ /^stoppgn$/) {
168 $t->cmd("tell $who Stopping poll.");
170 } elsif ($msg =~ /^quit$/) {
171 $t->cmd("tell $who Bye bye.");
174 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
177 #print "FICS: [$line]\n";
181 my ($body, $header, $url) = @_;
182 my $pgn = Chess::PGN::Parse->new(undef, $body);
183 if (!defined($pgn) || !$pgn->read_game()) {
184 warn "Error in parsing PGN from $url\n";
186 $pgn->quick_parse_game;
187 my $pos = Position->start_pos($pgn->white, $pgn->black);
188 my $moves = $pgn->moves;
190 for my $move (@$moves) {
191 my ($from_row, $from_col, $to_row, $to_col, $promo) = $pos->parse_pretty_move($move);
192 push @uci_moves, Board::move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
193 $pos = $pos->make_move($from_row, $from_col, $to_row, $to_col, $promo);
195 $pos->{'history'} = \@uci_moves;
196 $pos->{'pretty_history'} = $moves;
197 handle_position($pos);
200 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
201 AnyEvent::HTTP::http_get($url, sub {
202 handle_pgn(@_, $url);
207 sub handle_position {
210 # if this is already in the queue, ignore it
211 return if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
213 # if we're already chewing on this and there's nothing else in the queue,
215 return if (!defined($pos_waiting) && defined($pos_calculating) &&
216 $pos->fen() eq $pos_calculating->fen());
218 # if we're already thinking on something, stop and wait for the engine
220 if (defined($pos_calculating)) {
221 if (!defined($pos_waiting)) {
222 uciprint($engine, "stop");
224 if ($remoteglotconf::uci_assume_full_compliance) {
227 uciprint($engine, "position fen " . $pos->fen());
228 uciprint($engine, "go infinite");
229 $pos_calculating = $pos;
232 # it's wrong just to give the FEN (the move history is useful,
233 # and per the UCI spec, we should really have sent "ucinewgame"),
235 uciprint($engine, "position fen " . $pos->fen());
236 uciprint($engine, "go infinite");
237 $pos_calculating = $pos;
240 if (defined($engine2)) {
241 if (defined($pos_calculating_second_engine)) {
242 uciprint($engine2, "stop");
244 uciprint($engine2, "position fen " . $pos->fen());
245 uciprint($engine2, "go infinite");
246 $pos_calculating_second_engine = $pos;
248 $engine2->{'info'} = {};
251 $engine->{'info'} = {};
255 # Output a command every move to note that we're
256 # still paying attention -- this is a good tradeoff,
257 # since if no move has happened in the last half
258 # hour, the analysis/relay has most likely stopped
259 # and we should stop hogging server resources.
265 my ($engine, @x) = @_;
268 my $info = $engine->{'info'};
270 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
271 for my $i (0..$#x - 1) {
272 if ($x[$i] eq 'multipv') {
278 while (scalar @x > 0) {
279 if ($x[0] eq 'multipv') {
285 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
287 my $value = shift @x;
288 $info->{$key} = $value;
291 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
292 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
295 my $value = shift @x;
296 $info->{$key . $mpv} = $value;
299 if ($x[0] eq 'score') {
302 delete $info->{'score_cp' . $mpv};
303 delete $info->{'score_mate' . $mpv};
305 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
308 $info->{'score_cp' . $mpv} = shift @x;
309 } elsif ($x[0] eq 'mate') {
311 $info->{'score_mate' . $mpv} = shift @x;
319 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
322 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
326 #print "unknown info '$x[0]', trying to recover...\n";
328 die "Unknown info '" . join(',', @x) . "'";
334 my ($engine, @x) = @_;
336 while (scalar @x > 0) {
337 if ($x[0] =~ /^(name|author)$/) {
339 my $value = join(' ', @x);
340 $engine->{'id'}{$key} = $value;
349 sub prettyprint_pv_no_cache {
350 my ($board, @pvs) = @_;
352 if (scalar @pvs == 0 || !defined($pvs[0])) {
357 my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
358 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
359 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
363 my ($pos, @pvs) = @_;
365 my $cachekey = join('', @pvs);
366 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
367 return @{$pos->{'prettyprint_cache'}{$cachekey}};
369 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
370 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
378 return if (!defined($pos_calculating));
380 # Don't update too often.
381 my $age = Time::HiRes::tv_interval($latest_update);
382 if ($age < $remoteglotconf::update_max_interval) {
383 Time::HiRes::alarm($remoteglotconf::update_max_interval + 0.01 - $age);
387 my $info = $engine->{'info'};
390 # Some programs _always_ report MultiPV, even with only one PV.
391 # In this case, we simply use that data as if MultiPV was never
394 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
395 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
396 if (exists($info->{$key . '1'})) {
397 $info->{$key} = $info->{$key . '1'};
403 # Check the PVs first. if they're invalid, just wait, as our data
404 # is most likely out of sync. This isn't a very good solution, as
405 # it can frequently miss stuff, but it's good enough for most users.
409 if (exists($info->{'pv'})) {
410 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
414 while (exists($info->{'pv' . $mpv})) {
415 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
420 $engine->{'info'} = {};
426 $latest_update = [Time::HiRes::gettimeofday];
430 my $info = $engine->{'info'};
431 my $id = $engine->{'id'};
433 my $text = 'Analysis';
434 if ($pos_calculating->{'last_move'} ne 'none') {
435 if ($pos_calculating->{'toplay'} eq 'W') {
436 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
438 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
440 if (exists($id->{'name'})) {
445 if (exists($id->{'name'})) {
446 $text .= " by $id->{'name'}:\n\n";
451 return unless (exists($pos_calculating->{'board'}));
453 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
456 while (exists($info->{'pv' . $mpv})) {
457 $text .= sprintf " PV%2u", $mpv;
458 my $score = short_score($info, $pos_calculating, $mpv);
459 $text .= " ($score)" if (defined($score));
462 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
463 if ($info->{'tbhits' . $mpv} == 1) {
464 $tbhits = ", 1 tbhit";
466 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
470 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
471 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
472 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
476 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
482 my $score = long_score($info, $pos_calculating, '');
483 $text .= " $score\n" if defined($score);
484 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
487 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
488 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
489 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
491 if (exists($info->{'seldepth'})) {
492 $text .= sprintf " (%u selective)", $info->{'seldepth'};
494 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
495 if ($info->{'tbhits'} == 1) {
496 $text .= ", one Syzygy hit";
498 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
504 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
506 my @refutation_lines = ();
507 if (defined($engine2)) {
508 for (my $mpv = 1; $mpv < 500; ++$mpv) {
509 my $info = $engine2->{'info'};
510 last if (!exists($info->{'pv' . $mpv}));
512 my $pv = $info->{'pv' . $mpv};
514 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
515 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
516 if (scalar @pretty_pv > 5) {
517 @pretty_pv = @pretty_pv[0..4];
518 push @pretty_pv, "...";
520 my $key = $pretty_move;
521 my $line = sprintf(" %-6s %6s %3s %s",
523 short_score($info, $pos_calculating_second_engine, $mpv, 0),
524 "d" . $info->{'depth' . $mpv},
525 join(', ', @pretty_pv));
526 push @refutation_lines, [ $key, $line ];
531 if ($#refutation_lines >= 0) {
532 $text .= "Shallow search of all legal moves:\n\n";
533 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
534 $text .= $line->[1] . "\n";
539 if ($last_text ne $text) {
540 print "
\e[H
\e[2J"; # clear the screen
547 my $info = $engine->{'info'};
550 $json->{'position'} = $pos_calculating->to_json_hash();
551 $json->{'id'} = $engine->{'id'};
552 $json->{'score'} = long_score($info, $pos_calculating, '');
554 $json->{'nodes'} = $info->{'nodes'};
555 $json->{'nps'} = $info->{'nps'};
556 $json->{'depth'} = $info->{'depth'};
557 $json->{'tbhits'} = $info->{'tbhits'};
558 $json->{'seldepth'} = $info->{'seldepth'};
560 # single-PV only for now
561 $json->{'pv_uci'} = $info->{'pv'};
562 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
564 my %refutation_lines = ();
565 my @refutation_lines = ();
566 if (defined($engine2)) {
567 for (my $mpv = 1; $mpv < 500; ++$mpv) {
568 my $info = $engine2->{'info'};
569 my $pretty_move = "";
571 last if (!exists($info->{'pv' . $mpv}));
574 my $pv = $info->{'pv' . $mpv};
575 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
576 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
577 $refutation_lines{$pv->[0]} = {
578 sort_key => $pretty_move,
579 depth => $info->{'depth' . $mpv},
580 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
581 pretty_score => short_score($info, $pos_calculating, $mpv, 0),
582 pretty_move => $pretty_move,
583 pv_pretty => \@pretty_pv,
585 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
589 $json->{'refutation_lines'} = \%refutation_lines;
591 open my $fh, ">/srv/analysis.sesse.net/www/analysis.json.tmp"
593 print $fh JSON::XS::encode_json($json);
595 rename("/srv/analysis.sesse.net/www/analysis.json.tmp", "/srv/analysis.sesse.net/www/analysis.json");
599 my ($engine, $msg) = @_;
600 $engine->print($msg);
601 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
605 my ($info, $pos, $mpv, $invert) = @_;
608 if ($pos->{'toplay'} eq 'B') {
612 if (defined($info->{'score_mate' . $mpv})) {
614 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
616 return sprintf "M%3d", $info->{'score_mate' . $mpv};
619 if (exists($info->{'score_cp' . $mpv})) {
620 my $score = $info->{'score_cp' . $mpv} * 0.01;
627 return sprintf "%+5.2f", $score;
635 my ($info, $pos, $mpv, $invert) = @_;
637 if (defined($info->{'score_mate' . $mpv})) {
638 my $mate = $info->{'score_mate' . $mpv};
642 $mate = 99999 - $mate;
644 # Side to move is getting mated (note the double negative for $mate)
645 $mate = -99999 - $mate;
652 if (exists($info->{'score_cp' . $mpv})) {
653 my $score = $info->{'score_cp' . $mpv};
665 my ($info, $pos, $mpv) = @_;
667 if (defined($info->{'score_mate' . $mpv})) {
668 my $mate = $info->{'score_mate' . $mpv};
669 if ($pos->{'toplay'} eq 'B') {
673 return sprintf "White mates in %u", $mate;
675 return sprintf "Black mates in %u", -$mate;
678 if (exists($info->{'score_cp' . $mpv})) {
679 my $score = $info->{'score_cp' . $mpv} * 0.01;
681 return "Score: 0.00";
683 if ($pos->{'toplay'} eq 'B') {
686 return sprintf "Score: %+5.2f", $score;
695 my ($fen, $board, $toplay) = @_;
697 if (exists($book_cache{$fen})) {
698 return $book_cache{$fen};
701 my $ret = `./booklook $fen`;
702 return "" if ($ret =~ /Not found/ || $ret eq '');
706 for my $m (split /\n/, $ret) {
707 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
711 $pmove = '(current)';
713 ($pmove) = prettyprint_pv_no_cache($board, $move);
714 $pmove .= $annotation;
718 if ($toplay eq 'W') {
719 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
721 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
723 my $n = $win + $draw + $lose;
729 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
732 push @moves, [ $pmove, $n, $percent, $rating ];
735 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
737 my $text = "Book moves:\n\n Perf. N Rating\n\n";
739 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
746 my ($cmdline, $tag, $cb) = @_;
747 return undef if (!defined($cmdline));
748 return Engine->open($cmdline, $tag, $cb);
751 sub col_letter_to_num {
752 return ord(shift) - ord('a');
755 sub row_letter_to_num {
756 return 7 - (ord(shift) - ord('1'));
761 my $from_col = col_letter_to_num(substr($move, 0, 1));
762 my $from_row = row_letter_to_num(substr($move, 1, 1));
763 my $to_col = col_letter_to_num(substr($move, 2, 1));
764 my $to_row = row_letter_to_num(substr($move, 3, 1));
765 my $promo = substr($move, 4, 1);
766 return ($from_col, $from_row, $to_col, $to_row, $promo);