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 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
109 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
110 if ($line =~ /^info/) {
111 my (@infos) = split / /, $line;
114 parse_infos($engine, @infos);
116 if ($line =~ /^id/) {
117 my (@ids) = split / /, $line;
120 parse_ids($engine, @ids);
122 if ($line =~ /^bestmove/) {
124 return if (!$remoteglotconf::uci_assume_full_compliance);
125 if (defined($pos_waiting)) {
126 uciprint($engine, "position fen " . $pos_waiting->fen());
127 uciprint($engine, "go infinite");
129 $pos_calculating = $pos_waiting;
130 $pos_waiting = undef;
133 $engine2->{'info'} = {};
134 my $pos = $pos_waiting // $pos_calculating;
135 uciprint($engine2, "position fen " . $pos->fen());
136 uciprint($engine2, "go infinite");
137 $pos_calculating_second_engine = $pos;
145 if ($line =~ /^<12> /) {
146 handle_position(Position->new($line));
148 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
149 my ($who, $msg) = ($1, $2);
151 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
153 if ($msg =~ /^fics (.*?)$/) {
154 $t->cmd("tell $who Executing '$1' on FICS.");
156 } elsif ($msg =~ /^uci (.*?)$/) {
157 $t->cmd("tell $who Sending '$1' to the engine.");
158 print { $engine->{'write'} } "$1\n";
159 } elsif ($msg =~ /^pgn (.*?)$/) {
161 $t->cmd("tell $who Starting to poll '$url'.");
162 AnyEvent::HTTP::http_get($url, sub {
163 handle_pgn(@_, $url);
165 } elsif ($msg =~ /^stoppgn$/) {
166 $t->cmd("tell $who Stopping poll.");
168 } elsif ($msg =~ /^quit$/) {
169 $t->cmd("tell $who Bye bye.");
172 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
175 #print "FICS: [$line]\n";
179 my ($body, $header, $url) = @_;
180 my $pgn = Chess::PGN::Parse->new(undef, $body);
181 if (!defined($pgn) || !$pgn->read_game()) {
182 warn "Error in parsing PGN from $url\n";
184 $pgn->quick_parse_game;
185 my $pos = Position->start_pos($pgn->white, $pgn->black);
186 my $moves = $pgn->moves;
187 for my $move (@$moves) {
188 my ($from_row, $from_col, $to_row, $to_col, $promo) = $pos->parse_pretty_move($move);
189 $pos = $pos->make_move($from_row, $from_col, $to_row, $to_col, $promo);
191 handle_position($pos);
194 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
195 AnyEvent::HTTP::http_get($url, sub {
196 handle_pgn(@_, $url);
201 sub handle_position {
204 # if this is already in the queue, ignore it
205 return if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
207 # if we're already chewing on this and there's nothing else in the queue,
209 return if (!defined($pos_waiting) && defined($pos_calculating) &&
210 $pos->fen() eq $pos_calculating->fen());
212 # if we're already thinking on something, stop and wait for the engine
214 if (defined($pos_calculating)) {
215 if (!defined($pos_waiting)) {
216 uciprint($engine, "stop");
218 if ($remoteglotconf::uci_assume_full_compliance) {
221 uciprint($engine, "position fen " . $pos->fen());
222 uciprint($engine, "go infinite");
223 $pos_calculating = $pos;
226 # it's wrong just to give the FEN (the move history is useful,
227 # and per the UCI spec, we should really have sent "ucinewgame"),
229 uciprint($engine, "position fen " . $pos->fen());
230 uciprint($engine, "go infinite");
231 $pos_calculating = $pos;
234 if (defined($engine2)) {
235 if (defined($pos_calculating_second_engine)) {
236 uciprint($engine2, "stop");
238 uciprint($engine2, "position fen " . $pos->fen());
239 uciprint($engine2, "go infinite");
240 $pos_calculating_second_engine = $pos;
242 $engine2->{'info'} = {};
245 $engine->{'info'} = {};
249 # Output a command every move to note that we're
250 # still paying attention -- this is a good tradeoff,
251 # since if no move has happened in the last half
252 # hour, the analysis/relay has most likely stopped
253 # and we should stop hogging server resources.
259 my ($engine, @x) = @_;
262 my $info = $engine->{'info'};
264 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
265 for my $i (0..$#x - 1) {
266 if ($x[$i] eq 'multipv') {
272 while (scalar @x > 0) {
273 if ($x[0] eq 'multipv') {
279 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
281 my $value = shift @x;
282 $info->{$key} = $value;
285 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
286 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
289 my $value = shift @x;
290 $info->{$key . $mpv} = $value;
293 if ($x[0] eq 'score') {
296 delete $info->{'score_cp' . $mpv};
297 delete $info->{'score_mate' . $mpv};
299 while ($x[0] eq 'cp' || $x[0] eq 'mate' || $x[0] eq 'lowerbound' || $x[0] eq 'upperbound') {
302 $info->{'score_cp' . $mpv} = shift @x;
303 } elsif ($x[0] eq 'mate') {
305 $info->{'score_mate' . $mpv} = shift @x;
313 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
316 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
320 #print "unknown info '$x[0]', trying to recover...\n";
322 die "Unknown info '" . join(',', @x) . "'";
328 my ($engine, @x) = @_;
330 while (scalar @x > 0) {
331 if ($x[0] =~ /^(name|author)$/) {
333 my $value = join(' ', @x);
334 $engine->{'id'}{$key} = $value;
343 sub prettyprint_pv_no_cache {
344 my ($board, @pvs) = @_;
346 if (scalar @pvs == 0 || !defined($pvs[0])) {
351 my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
352 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
353 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
357 my ($pos, @pvs) = @_;
359 my $cachekey = join('', @pvs);
360 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
361 return @{$pos->{'prettyprint_cache'}{$cachekey}};
363 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
364 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
372 return if (!defined($pos_calculating));
374 # Don't update too often.
375 my $age = Time::HiRes::tv_interval($latest_update);
376 if ($age < $remoteglotconf::update_max_interval) {
377 Time::HiRes::alarm($remoteglotconf::update_max_interval + 0.01 - $age);
381 my $info = $engine->{'info'};
384 # Some programs _always_ report MultiPV, even with only one PV.
385 # In this case, we simply use that data as if MultiPV was never
388 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
389 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
390 if (exists($info->{$key . '1'})) {
391 $info->{$key} = $info->{$key . '1'};
397 # Check the PVs first. if they're invalid, just wait, as our data
398 # is most likely out of sync. This isn't a very good solution, as
399 # it can frequently miss stuff, but it's good enough for most users.
403 if (exists($info->{'pv'})) {
404 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
408 while (exists($info->{'pv' . $mpv})) {
409 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
414 $engine->{'info'} = {};
420 $latest_update = [Time::HiRes::gettimeofday];
424 my $info = $engine->{'info'};
425 my $id = $engine->{'id'};
427 my $text = 'Analysis';
428 if ($pos_calculating->{'last_move'} ne 'none') {
429 if ($pos_calculating->{'toplay'} eq 'W') {
430 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
432 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
434 if (exists($id->{'name'})) {
439 if (exists($id->{'name'})) {
440 $text .= " by $id->{'name'}:\n\n";
445 return unless (exists($pos_calculating->{'board'}));
447 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
450 while (exists($info->{'pv' . $mpv})) {
451 $text .= sprintf " PV%2u", $mpv;
452 my $score = short_score($info, $pos_calculating, $mpv);
453 $text .= " ($score)" if (defined($score));
456 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
457 if ($info->{'tbhits' . $mpv} == 1) {
458 $tbhits = ", 1 tbhit";
460 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
464 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
465 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
466 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
470 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
476 my $score = long_score($info, $pos_calculating, '');
477 $text .= " $score\n" if defined($score);
478 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
481 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
482 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
483 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
485 if (exists($info->{'seldepth'})) {
486 $text .= sprintf " (%u selective)", $info->{'seldepth'};
488 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
489 if ($info->{'tbhits'} == 1) {
490 $text .= ", one Syzygy hit";
492 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
498 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
500 my @refutation_lines = ();
501 if (defined($engine2)) {
502 for (my $mpv = 1; $mpv < 500; ++$mpv) {
503 my $info = $engine2->{'info'};
504 last if (!exists($info->{'pv' . $mpv}));
506 my $pv = $info->{'pv' . $mpv};
508 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
509 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
510 if (scalar @pretty_pv > 5) {
511 @pretty_pv = @pretty_pv[0..4];
512 push @pretty_pv, "...";
514 my $key = $pretty_move;
515 my $line = sprintf(" %-6s %6s %3s %s",
517 short_score($info, $pos_calculating_second_engine, $mpv, 0),
518 "d" . $info->{'depth' . $mpv},
519 join(', ', @pretty_pv));
520 push @refutation_lines, [ $key, $line ];
525 if ($#refutation_lines >= 0) {
526 $text .= "Shallow search of all legal moves:\n\n";
527 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
528 $text .= $line->[1] . "\n";
533 if ($last_text ne $text) {
534 print "
\e[H
\e[2J"; # clear the screen
541 my $info = $engine->{'info'};
544 $json->{'position'} = $pos_calculating->to_json_hash();
545 $json->{'id'} = $engine->{'id'};
546 $json->{'score'} = long_score($info, $pos_calculating, '');
548 $json->{'nodes'} = $info->{'nodes'};
549 $json->{'nps'} = $info->{'nps'};
550 $json->{'depth'} = $info->{'depth'};
551 $json->{'tbhits'} = $info->{'tbhits'};
552 $json->{'seldepth'} = $info->{'seldepth'};
554 # single-PV only for now
555 $json->{'pv_uci'} = $info->{'pv'};
556 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
558 my %refutation_lines = ();
559 my @refutation_lines = ();
560 if (defined($engine2)) {
561 for (my $mpv = 1; $mpv < 500; ++$mpv) {
562 my $info = $engine2->{'info'};
563 my $pretty_move = "";
565 last if (!exists($info->{'pv' . $mpv}));
568 my $pv = $info->{'pv' . $mpv};
569 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
570 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
571 $refutation_lines{$pv->[0]} = {
572 sort_key => $pretty_move,
573 depth => $info->{'depth' . $mpv},
574 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
575 pretty_score => short_score($info, $pos_calculating, $mpv, 0),
576 pretty_move => $pretty_move,
577 pv_pretty => \@pretty_pv,
579 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
583 $json->{'refutation_lines'} = \%refutation_lines;
585 open my $fh, ">/srv/analysis.sesse.net/www/analysis.json.tmp"
587 print $fh JSON::XS::encode_json($json);
589 rename("/srv/analysis.sesse.net/www/analysis.json.tmp", "/srv/analysis.sesse.net/www/analysis.json");
593 my ($engine, $msg) = @_;
594 $engine->print($msg);
595 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
599 my ($info, $pos, $mpv, $invert) = @_;
602 if ($pos->{'toplay'} eq 'B') {
606 if (defined($info->{'score_mate' . $mpv})) {
608 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
610 return sprintf "M%3d", $info->{'score_mate' . $mpv};
613 if (exists($info->{'score_cp' . $mpv})) {
614 my $score = $info->{'score_cp' . $mpv} * 0.01;
621 return sprintf "%+5.2f", $score;
629 my ($info, $pos, $mpv, $invert) = @_;
631 if (defined($info->{'score_mate' . $mpv})) {
633 return 99999 - $info->{'score_mate' . $mpv};
635 return -(99999 - $info->{'score_mate' . $mpv});
638 if (exists($info->{'score_cp' . $mpv})) {
639 my $score = $info->{'score_cp' . $mpv};
651 my ($info, $pos, $mpv) = @_;
653 if (defined($info->{'score_mate' . $mpv})) {
654 my $mate = $info->{'score_mate' . $mpv};
655 if ($pos->{'toplay'} eq 'B') {
659 return sprintf "White mates in %u", $mate;
661 return sprintf "Black mates in %u", -$mate;
664 if (exists($info->{'score_cp' . $mpv})) {
665 my $score = $info->{'score_cp' . $mpv} * 0.01;
667 return "Score: 0.00";
669 if ($pos->{'toplay'} eq 'B') {
672 return sprintf "Score: %+5.2f", $score;
681 my ($fen, $board, $toplay) = @_;
683 if (exists($book_cache{$fen})) {
684 return $book_cache{$fen};
687 my $ret = `./booklook $fen`;
688 return "" if ($ret =~ /Not found/ || $ret eq '');
692 for my $m (split /\n/, $ret) {
693 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
697 $pmove = '(current)';
699 ($pmove) = prettyprint_pv_no_cache($board, $move);
700 $pmove .= $annotation;
704 if ($toplay eq 'W') {
705 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
707 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
709 my $n = $win + $draw + $lose;
715 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
718 push @moves, [ $pmove, $n, $percent, $rating ];
721 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
723 my $text = "Book moves:\n\n Perf. N Rating\n\n";
725 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
732 my ($cmdline, $tag, $cb) = @_;
733 return undef if (!defined($cmdline));
734 return Engine->open($cmdline, $tag, $cb);
737 sub col_letter_to_num {
738 return ord(shift) - ord('a');
741 sub row_letter_to_num {
742 return 7 - (ord(shift) - ord('1'));
747 my $from_col = col_letter_to_num(substr($move, 0, 1));
748 my $from_row = row_letter_to_num(substr($move, 1, 1));
749 my $to_col = col_letter_to_num(substr($move, 2, 1));
750 my $to_row = row_letter_to_num(substr($move, 3, 1));
751 my $promo = substr($move, 4, 1);
752 return ($from_col, $from_row, $to_col, $to_row, $promo);