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;
188 for my $move (@$moves) {
189 my ($from_row, $from_col, $to_row, $to_col, $promo) = $pos->parse_pretty_move($move);
190 push @uci_moves, Board::move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
191 $pos = $pos->make_move($from_row, $from_col, $to_row, $to_col, $promo);
193 $pos->{'history'} = \@uci_moves;
194 $pos->{'pretty_history'} = $moves;
195 handle_position($pos);
198 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
199 AnyEvent::HTTP::http_get($url, sub {
200 handle_pgn(@_, $url);
205 sub handle_position {
208 # if this is already in the queue, ignore it
209 return if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
211 # if we're already chewing on this and there's nothing else in the queue,
213 return if (!defined($pos_waiting) && defined($pos_calculating) &&
214 $pos->fen() eq $pos_calculating->fen());
216 # if we're already thinking on something, stop and wait for the engine
218 if (defined($pos_calculating)) {
219 if (!defined($pos_waiting)) {
220 uciprint($engine, "stop");
222 if ($remoteglotconf::uci_assume_full_compliance) {
225 uciprint($engine, "position fen " . $pos->fen());
226 uciprint($engine, "go infinite");
227 $pos_calculating = $pos;
230 # it's wrong just to give the FEN (the move history is useful,
231 # and per the UCI spec, we should really have sent "ucinewgame"),
233 uciprint($engine, "position fen " . $pos->fen());
234 uciprint($engine, "go infinite");
235 $pos_calculating = $pos;
238 if (defined($engine2)) {
239 if (defined($pos_calculating_second_engine)) {
240 uciprint($engine2, "stop");
242 uciprint($engine2, "position fen " . $pos->fen());
243 uciprint($engine2, "go infinite");
244 $pos_calculating_second_engine = $pos;
246 $engine2->{'info'} = {};
249 $engine->{'info'} = {};
253 # Output a command every move to note that we're
254 # still paying attention -- this is a good tradeoff,
255 # since if no move has happened in the last half
256 # hour, the analysis/relay has most likely stopped
257 # and we should stop hogging server resources.
263 my ($engine, @x) = @_;
266 my $info = $engine->{'info'};
268 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
269 for my $i (0..$#x - 1) {
270 if ($x[$i] eq 'multipv') {
276 while (scalar @x > 0) {
277 if ($x[0] eq 'multipv') {
283 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
285 my $value = shift @x;
286 $info->{$key} = $value;
289 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
290 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
293 my $value = shift @x;
294 $info->{$key . $mpv} = $value;
297 if ($x[0] eq 'score') {
300 delete $info->{'score_cp' . $mpv};
301 delete $info->{'score_mate' . $mpv};
303 while ($x[0] eq 'cp' || $x[0] eq 'mate' || $x[0] eq 'lowerbound' || $x[0] eq 'upperbound') {
306 $info->{'score_cp' . $mpv} = shift @x;
307 } elsif ($x[0] eq 'mate') {
309 $info->{'score_mate' . $mpv} = shift @x;
317 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
320 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
324 #print "unknown info '$x[0]', trying to recover...\n";
326 die "Unknown info '" . join(',', @x) . "'";
332 my ($engine, @x) = @_;
334 while (scalar @x > 0) {
335 if ($x[0] =~ /^(name|author)$/) {
337 my $value = join(' ', @x);
338 $engine->{'id'}{$key} = $value;
347 sub prettyprint_pv_no_cache {
348 my ($board, @pvs) = @_;
350 if (scalar @pvs == 0 || !defined($pvs[0])) {
355 my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
356 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
357 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
361 my ($pos, @pvs) = @_;
363 my $cachekey = join('', @pvs);
364 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
365 return @{$pos->{'prettyprint_cache'}{$cachekey}};
367 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
368 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
376 return if (!defined($pos_calculating));
378 # Don't update too often.
379 my $age = Time::HiRes::tv_interval($latest_update);
380 if ($age < $remoteglotconf::update_max_interval) {
381 Time::HiRes::alarm($remoteglotconf::update_max_interval + 0.01 - $age);
385 my $info = $engine->{'info'};
388 # Some programs _always_ report MultiPV, even with only one PV.
389 # In this case, we simply use that data as if MultiPV was never
392 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
393 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
394 if (exists($info->{$key . '1'})) {
395 $info->{$key} = $info->{$key . '1'};
401 # Check the PVs first. if they're invalid, just wait, as our data
402 # is most likely out of sync. This isn't a very good solution, as
403 # it can frequently miss stuff, but it's good enough for most users.
407 if (exists($info->{'pv'})) {
408 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
412 while (exists($info->{'pv' . $mpv})) {
413 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
418 $engine->{'info'} = {};
424 $latest_update = [Time::HiRes::gettimeofday];
428 my $info = $engine->{'info'};
429 my $id = $engine->{'id'};
431 my $text = 'Analysis';
432 if ($pos_calculating->{'last_move'} ne 'none') {
433 if ($pos_calculating->{'toplay'} eq 'W') {
434 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
436 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
438 if (exists($id->{'name'})) {
443 if (exists($id->{'name'})) {
444 $text .= " by $id->{'name'}:\n\n";
449 return unless (exists($pos_calculating->{'board'}));
451 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
454 while (exists($info->{'pv' . $mpv})) {
455 $text .= sprintf " PV%2u", $mpv;
456 my $score = short_score($info, $pos_calculating, $mpv);
457 $text .= " ($score)" if (defined($score));
460 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
461 if ($info->{'tbhits' . $mpv} == 1) {
462 $tbhits = ", 1 tbhit";
464 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
468 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
469 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
470 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
474 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
480 my $score = long_score($info, $pos_calculating, '');
481 $text .= " $score\n" if defined($score);
482 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
485 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
486 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
487 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
489 if (exists($info->{'seldepth'})) {
490 $text .= sprintf " (%u selective)", $info->{'seldepth'};
492 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
493 if ($info->{'tbhits'} == 1) {
494 $text .= ", one Syzygy hit";
496 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
502 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
504 my @refutation_lines = ();
505 if (defined($engine2)) {
506 for (my $mpv = 1; $mpv < 500; ++$mpv) {
507 my $info = $engine2->{'info'};
508 last if (!exists($info->{'pv' . $mpv}));
510 my $pv = $info->{'pv' . $mpv};
512 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
513 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
514 if (scalar @pretty_pv > 5) {
515 @pretty_pv = @pretty_pv[0..4];
516 push @pretty_pv, "...";
518 my $key = $pretty_move;
519 my $line = sprintf(" %-6s %6s %3s %s",
521 short_score($info, $pos_calculating_second_engine, $mpv, 0),
522 "d" . $info->{'depth' . $mpv},
523 join(', ', @pretty_pv));
524 push @refutation_lines, [ $key, $line ];
529 if ($#refutation_lines >= 0) {
530 $text .= "Shallow search of all legal moves:\n\n";
531 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
532 $text .= $line->[1] . "\n";
537 if ($last_text ne $text) {
538 print "
\e[H
\e[2J"; # clear the screen
545 my $info = $engine->{'info'};
548 $json->{'position'} = $pos_calculating->to_json_hash();
549 $json->{'id'} = $engine->{'id'};
550 $json->{'score'} = long_score($info, $pos_calculating, '');
552 $json->{'nodes'} = $info->{'nodes'};
553 $json->{'nps'} = $info->{'nps'};
554 $json->{'depth'} = $info->{'depth'};
555 $json->{'tbhits'} = $info->{'tbhits'};
556 $json->{'seldepth'} = $info->{'seldepth'};
558 # single-PV only for now
559 $json->{'pv_uci'} = $info->{'pv'};
560 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
562 my %refutation_lines = ();
563 my @refutation_lines = ();
564 if (defined($engine2)) {
565 for (my $mpv = 1; $mpv < 500; ++$mpv) {
566 my $info = $engine2->{'info'};
567 my $pretty_move = "";
569 last if (!exists($info->{'pv' . $mpv}));
572 my $pv = $info->{'pv' . $mpv};
573 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
574 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
575 $refutation_lines{$pv->[0]} = {
576 sort_key => $pretty_move,
577 depth => $info->{'depth' . $mpv},
578 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
579 pretty_score => short_score($info, $pos_calculating, $mpv, 0),
580 pretty_move => $pretty_move,
581 pv_pretty => \@pretty_pv,
583 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
587 $json->{'refutation_lines'} = \%refutation_lines;
589 open my $fh, ">/srv/analysis.sesse.net/www/analysis.json.tmp"
591 print $fh JSON::XS::encode_json($json);
593 rename("/srv/analysis.sesse.net/www/analysis.json.tmp", "/srv/analysis.sesse.net/www/analysis.json");
597 my ($engine, $msg) = @_;
598 $engine->print($msg);
599 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
603 my ($info, $pos, $mpv, $invert) = @_;
606 if ($pos->{'toplay'} eq 'B') {
610 if (defined($info->{'score_mate' . $mpv})) {
612 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
614 return sprintf "M%3d", $info->{'score_mate' . $mpv};
617 if (exists($info->{'score_cp' . $mpv})) {
618 my $score = $info->{'score_cp' . $mpv} * 0.01;
625 return sprintf "%+5.2f", $score;
633 my ($info, $pos, $mpv, $invert) = @_;
635 if (defined($info->{'score_mate' . $mpv})) {
637 return 99999 - $info->{'score_mate' . $mpv};
639 return -(99999 - $info->{'score_mate' . $mpv});
642 if (exists($info->{'score_cp' . $mpv})) {
643 my $score = $info->{'score_cp' . $mpv};
655 my ($info, $pos, $mpv) = @_;
657 if (defined($info->{'score_mate' . $mpv})) {
658 my $mate = $info->{'score_mate' . $mpv};
659 if ($pos->{'toplay'} eq 'B') {
663 return sprintf "White mates in %u", $mate;
665 return sprintf "Black mates in %u", -$mate;
668 if (exists($info->{'score_cp' . $mpv})) {
669 my $score = $info->{'score_cp' . $mpv} * 0.01;
671 return "Score: 0.00";
673 if ($pos->{'toplay'} eq 'B') {
676 return sprintf "Score: %+5.2f", $score;
685 my ($fen, $board, $toplay) = @_;
687 if (exists($book_cache{$fen})) {
688 return $book_cache{$fen};
691 my $ret = `./booklook $fen`;
692 return "" if ($ret =~ /Not found/ || $ret eq '');
696 for my $m (split /\n/, $ret) {
697 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
701 $pmove = '(current)';
703 ($pmove) = prettyprint_pv_no_cache($board, $move);
704 $pmove .= $annotation;
708 if ($toplay eq 'W') {
709 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
711 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
713 my $n = $win + $draw + $lose;
719 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
722 push @moves, [ $pmove, $n, $percent, $rating ];
725 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
727 my $text = "Book moves:\n\n Perf. N Rating\n\n";
729 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
736 my ($cmdline, $tag, $cb) = @_;
737 return undef if (!defined($cmdline));
738 return Engine->open($cmdline, $tag, $cb);
741 sub col_letter_to_num {
742 return ord(shift) - ord('a');
745 sub row_letter_to_num {
746 return 7 - (ord(shift) - ord('1'));
751 my $from_col = col_letter_to_num(substr($move, 0, 1));
752 my $from_row = row_letter_to_num(substr($move, 1, 1));
753 my $to_col = col_letter_to_num(substr($move, 2, 1));
754 my $to_row = row_letter_to_num(substr($move, 3, 1));
755 my $promo = substr($move, 4, 1);
756 return ($from_col, $from_row, $to_col, $to_row, $promo);