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.
17 require 'Position.pm';
23 my $server = "freechess.org";
24 my $target = "GMCarlsen";
25 my $engine_cmdline = "'./Deep Rybka 4 SSE42 x64'";
26 my $engine2_cmdline = "./stockfish_13111119_x64_modern_sse42"; # undef for none
27 my $uci_assume_full_compliance = 0; # dangerous :-)
28 my $update_max_interval = 1.0;
38 $SIG{ALRM} = sub { output(); };
39 my $latest_update = undef;
43 open(FICSLOG, ">ficslog.txt")
44 or die "ficslog.txt: $!";
45 print FICSLOG "Log starting.\n";
49 open(UCILOG, ">ucilog.txt")
50 or die "ucilog.txt: $!";
51 print UCILOG "Log starting.\n";
56 # open the chess engine
57 my $engine = open_engine($engine_cmdline, 'E1');
58 my $engine2 = open_engine($engine2_cmdline, 'E2');
61 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
63 uciprint($engine, "setoption name UCI_AnalyseMode value true");
64 # uciprint($engine, "setoption name NalimovPath value /srv/tablebase");
65 uciprint($engine, "setoption name NalimovUsage value Rarely");
66 uciprint($engine, "setoption name Hash value 1024");
67 # uciprint($engine, "setoption name MultiPV value 2");
68 uciprint($engine, "ucinewgame");
70 if (defined($engine2)) {
71 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
72 # uciprint($engine2, "setoption name NalimovPath value /srv/tablebase");
73 uciprint($engine2, "setoption name NalimovUsage value Rarely");
74 uciprint($engine2, "setoption name Hash value 1024");
75 uciprint($engine2, "setoption name Threads value 8");
76 uciprint($engine2, "setoption name MultiPV value 500");
77 uciprint($engine2, "ucinewgame");
80 print "Chess engine ready.\n";
83 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
84 $t->input_log(\*FICSLOG);
86 $t->print("SesseBOT");
87 $t->waitfor('/Press return to enter the server/');
91 $t->cmd("set shout 0");
92 $t->cmd("set seek 0");
93 $t->cmd("set style 12");
94 $t->cmd("observe $target");
97 print "FICS ready.\n";
101 vec($rin, fileno($engine->{'read'}), 1) = 1;
102 if (defined($engine2)) {
103 vec($rin, fileno($engine2->{'read'}), 1) = 1;
105 vec($rin, fileno($t), 1) = 1;
107 my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
111 my $line = $t->getline(Timeout => 0, errmode => 'return');
112 last if (!defined($line));
120 # any fun on the UCI channel?
121 if ($nfound > 0 && vec($rout, fileno($engine->{'read'}), 1) == 1) {
122 my @lines = $engine->read_lines();
123 for my $line (@lines) {
124 next if $line =~ /(upper|lower)bound/;
125 handle_uci($engine, $line, 1);
131 if (defined($engine2) && $nfound > 0 && vec($rout, fileno($engine2->{'read'}), 1) == 1) {
132 my @lines = $engine2->read_lines();
133 for my $line (@lines) {
134 next if $line =~ /(upper|lower)bound/;
135 handle_uci($engine2, $line, 0);
146 my ($engine, $line, $primary) = @_;
150 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
151 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
152 if ($line =~ /^info/) {
153 my (@infos) = split / /, $line;
156 parse_infos($engine, @infos);
158 if ($line =~ /^id/) {
159 my (@ids) = split / /, $line;
162 parse_ids($engine, @ids);
164 if ($line =~ /^bestmove/) {
166 return if (!$uci_assume_full_compliance);
167 if (defined($pos_waiting)) {
168 uciprint($engine, "position fen " . $pos_waiting->fen());
169 uciprint($engine, "go infinite");
171 $pos_calculating = $pos_waiting;
172 $pos_waiting = undef;
175 $engine2->{'info'} = {};
176 my $pos = $pos_waiting // $pos_calculating;
177 uciprint($engine2, "position fen " . $pos->fen());
178 uciprint($engine2, "go infinite");
179 $pos_calculating_second_engine = $pos;
186 if ($line =~ /^<12> /) {
187 my $pos = Position->new($line);
189 # if this is already in the queue, ignore it
190 next if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
192 # if we're already chewing on this and there's nothing else in the queue,
194 next if (!defined($pos_waiting) && defined($pos_calculating) &&
195 $pos->fen() eq $pos_calculating->fen());
197 # if we're already thinking on something, stop and wait for the engine
199 if (defined($pos_calculating)) {
200 if (!defined($pos_waiting)) {
201 uciprint($engine, "stop");
203 if ($uci_assume_full_compliance) {
206 uciprint($engine, "position fen " . $pos->fen());
207 uciprint($engine, "go infinite");
208 $pos_calculating = $pos;
211 # it's wrong just to give the FEN (the move history is useful,
212 # and per the UCI spec, we should really have sent "ucinewgame"),
214 uciprint($engine, "position fen " . $pos->fen());
215 uciprint($engine, "go infinite");
216 $pos_calculating = $pos;
219 if (defined($engine2)) {
220 if (defined($pos_calculating_second_engine)) {
221 uciprint($engine2, "stop");
223 uciprint($engine2, "position fen " . $pos->fen());
224 uciprint($engine2, "go infinite");
225 $pos_calculating_second_engine = $pos;
227 $engine2->{'info'} = {};
230 $engine->{'info'} = {};
234 # Output a command every move to note that we're
235 # still paying attention -- this is a good tradeoff,
236 # since if no move has happened in the last half
237 # hour, the analysis/relay has most likely stopped
238 # and we should stop hogging server resources.
242 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
243 my ($who, $msg) = ($1, $2);
245 next if (grep { $_ eq $who } (@masters) == 0);
247 if ($msg =~ /^fics (.*?)$/) {
248 $t->cmd("tell $who Executing '$1' on FICS.");
250 } elsif ($msg =~ /^uci (.*?)$/) {
251 $t->cmd("tell $who Sending '$1' to the engine.");
252 print { $engine->{'write'} } "$1\n";
254 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
257 #print "FICS: [$line]\n";
261 my ($engine, @x) = @_;
264 my $info = $engine->{'info'};
266 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
267 for my $i (0..$#x - 1) {
268 if ($x[$i] =~ 'multipv') {
274 while (scalar @x > 0) {
275 if ($x[0] =~ 'multipv') {
281 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
283 my $value = shift @x;
284 $info->{$key} = $value;
287 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
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] =~ /^(cp|mate|lowerbound|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;
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($nb, @pvs));
359 return if (!defined($pos_calculating));
361 # Don't update too often.
362 my $age = Time::HiRes::tv_interval($latest_update);
363 if ($age < $update_max_interval) {
364 Time::HiRes::alarm($update_max_interval + 0.01 - $age);
368 my $info = $engine->{'info'};
371 # Some programs _always_ report MultiPV, even with only one PV.
372 # In this case, we simply use that data as if MultiPV was never
375 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
376 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
377 if (exists($info->{$key . '1'})) {
378 $info->{$key} = $info->{$key . '1'};
384 # Check the PVs first. if they're invalid, just wait, as our data
385 # is most likely out of sync. This isn't a very good solution, as
386 # it can frequently miss stuff, but it's good enough for most users.
390 if (exists($info->{'pv'})) {
391 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
395 while (exists($info->{'pv' . $mpv})) {
396 $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
401 $engine->{'info'} = {};
407 $latest_update = [Time::HiRes::gettimeofday];
411 my $info = $engine->{'info'};
412 my $id = $engine->{'id'};
414 my $text = 'Analysis';
415 if ($pos_calculating->{'last_move'} ne 'none') {
416 if ($pos_calculating->{'toplay'} eq 'W') {
417 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
419 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
421 if (exists($id->{'name'})) {
426 if (exists($id->{'name'})) {
427 $text .= " by $id->{'name'}:\n\n";
432 return unless (exists($pos_calculating->{'board'}));
434 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
437 while (exists($info->{'pv' . $mpv})) {
438 $text .= sprintf " PV%2u", $mpv;
439 my $score = short_score($info, $pos_calculating, $mpv);
440 $text .= " ($score)" if (defined($score));
443 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
444 if ($info->{'tbhits' . $mpv} == 1) {
445 $tbhits = ", 1 tbhit";
447 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
451 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
452 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
453 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
457 $text .= " " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
463 my $score = long_score($info, $pos_calculating, '');
464 $text .= " $score\n" if defined($score);
465 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
468 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
469 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
470 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
472 if (exists($info->{'seldepth'})) {
473 $text .= sprintf " (%u selective)", $info->{'seldepth'};
475 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
476 if ($info->{'tbhits'} == 1) {
477 $text .= ", one Syzygy hit";
479 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
485 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
487 my @refutation_lines = ();
488 if (defined($engine2)) {
489 for (my $mpv = 1; $mpv < 500; ++$mpv) {
490 my $info = $engine2->{'info'};
491 last if (!exists($info->{'pv' . $mpv}));
493 my $pv = $info->{'pv' . $mpv};
495 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine->{'board'}, $pv->[0]));
496 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine->{'board'}, @$pv);
497 if (scalar @pretty_pv > 5) {
498 @pretty_pv = @pretty_pv[0..4];
499 push @pretty_pv, "...";
501 my $key = $pretty_move;
502 my $line = sprintf(" %-6s %6s %3s %s",
504 short_score($info, $pos_calculating_second_engine, $mpv, 0),
505 "d" . $info->{'depth' . $mpv},
506 join(', ', @pretty_pv));
507 push @refutation_lines, [ $key, $line ];
512 if ($#refutation_lines >= 0) {
513 $text .= "Shallow search of all legal moves:\n\n";
514 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
515 $text .= $line->[1] . "\n";
520 if ($last_text ne $text) {
521 print "
\e[H
\e[2J"; # clear the screen
528 my $info = $engine->{'info'};
531 $json->{'position'} = $pos_calculating->to_json_hash();
532 $json->{'id'} = $engine->{'id'};
533 $json->{'score'} = long_score($info, $pos_calculating, '');
535 $json->{'nodes'} = $info->{'nodes'};
536 $json->{'nps'} = $info->{'nps'};
537 $json->{'depth'} = $info->{'depth'};
538 $json->{'tbhits'} = $info->{'tbhits'};
539 $json->{'seldepth'} = $info->{'seldepth'};
541 # single-PV only for now
542 $json->{'pv_uci'} = $info->{'pv'};
543 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}) ];
545 my %refutation_lines = ();
546 my @refutation_lines = ();
547 if (defined($engine2)) {
548 for (my $mpv = 1; $mpv < 500; ++$mpv) {
549 my $info = $engine2->{'info'};
550 my $pretty_move = "";
552 last if (!exists($info->{'pv' . $mpv}));
555 my $pv = $info->{'pv' . $mpv};
556 my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $pv->[0]));
557 my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, @$pv);
558 $refutation_lines{$pv->[0]} = {
559 sort_key => $pretty_move,
560 depth => $info->{'depth' . $mpv},
561 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
562 pretty_score => short_score($info, $pos_calculating, $mpv, 0),
563 pretty_move => $pretty_move,
564 pv_pretty => \@pretty_pv,
566 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
570 $json->{'refutation_lines'} = \%refutation_lines;
572 open my $fh, ">/srv/analysis.sesse.net/www/analysis.json.tmp"
574 print $fh JSON::XS::encode_json($json);
576 rename("/srv/analysis.sesse.net/www/analysis.json.tmp", "/srv/analysis.sesse.net/www/analysis.json");
580 my ($engine, $msg) = @_;
581 $engine->print($msg);
582 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
586 my ($info, $pos, $mpv, $invert) = @_;
589 if ($pos->{'toplay'} eq 'B') {
593 if (defined($info->{'score_mate' . $mpv})) {
595 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
597 return sprintf "M%3d", $info->{'score_mate' . $mpv};
600 if (exists($info->{'score_cp' . $mpv})) {
601 my $score = $info->{'score_cp' . $mpv} * 0.01;
608 return sprintf "%+5.2f", $score;
616 my ($info, $pos, $mpv, $invert) = @_;
618 if (defined($info->{'score_mate' . $mpv})) {
620 return 99999 - $info->{'score_mate' . $mpv};
622 return -(99999 - $info->{'score_mate' . $mpv});
625 if (exists($info->{'score_cp' . $mpv})) {
626 my $score = $info->{'score_cp' . $mpv};
638 my ($info, $pos, $mpv) = @_;
640 if (defined($info->{'score_mate' . $mpv})) {
641 my $mate = $info->{'score_mate' . $mpv};
642 if ($pos->{'toplay'} eq 'B') {
646 return sprintf "White mates in %u", $mate;
648 return sprintf "Black mates in %u", -$mate;
651 if (exists($info->{'score_cp' . $mpv})) {
652 my $score = $info->{'score_cp' . $mpv} * 0.01;
654 return "Score: 0.00";
656 if ($pos->{'toplay'} eq 'B') {
659 return sprintf "Score: %+5.2f", $score;
668 my ($fen, $board, $toplay) = @_;
670 if (exists($book_cache{$fen})) {
671 return $book_cache{$fen};
674 my $ret = `./booklook $fen`;
675 return "" if ($ret =~ /Not found/ || $ret eq '');
679 for my $m (split /\n/, $ret) {
680 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
684 $pmove = '(current)';
686 ($pmove) = prettyprint_pv($board, $move);
687 $pmove .= $annotation;
691 if ($toplay eq 'W') {
692 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
694 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
696 my $n = $win + $draw + $lose;
702 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
705 push @moves, [ $pmove, $n, $percent, $rating ];
708 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
710 my $text = "Book moves:\n\n Perf. N Rating\n\n";
712 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
719 my ($cmdline, $tag) = @_;
720 return undef if (!defined($cmdline));
721 my $engine = Engine->open($cmdline, $tag);
723 uciprint($engine, "uci");
727 while (!$seen_uciok) {
728 for my $line ($engine->read_lines()) {
729 if ($line =~ /uciok/) {
732 handle_uci($engine, $line);
739 sub col_letter_to_num {
740 return ord(shift) - ord('a');
743 sub row_letter_to_num {
744 return 7 - (ord(shift) - ord('1'));
749 my $from_col = col_letter_to_num(substr($move, 0, 1));
750 my $from_row = row_letter_to_num(substr($move, 1, 1));
751 my $to_col = col_letter_to_num(substr($move, 2, 1));
752 my $to_row = row_letter_to_num(substr($move, 3, 1));
753 my $promo = substr($move, 4, 1);
754 return ($from_col, $from_row, $to_col, $to_row, $promo);