-
-
Notifications
You must be signed in to change notification settings - Fork 512
/
engine.py
2479 lines (1993 loc) · 96.1 KB
/
engine.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# This file is part of the python-chess library.
# Copyright (C) 2012-2019 Niklas Fiekas <niklas.fiekas@backscattering.de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import abc
import asyncio
import collections
import concurrent.futures
import contextlib
import enum
import functools
import logging
import warnings
import shlex
import subprocess
import sys
import threading
import typing
import os
import re
try:
# Python 3.7
from asyncio import get_running_loop as _get_running_loop
except ImportError:
from asyncio import _get_running_loop
try:
# Python 3.7
from asyncio import all_tasks as _all_tasks
except ImportError:
_all_tasks = asyncio.Task.all_tasks
import chess
from types import TracebackType
from typing import Any, Callable, Coroutine, Dict, Generator, Generic, Iterable, Iterator, List, Mapping, MutableMapping, Optional, Text, Tuple, Type, TypeVar, Union
T = TypeVar("T")
EngineProtocolT = TypeVar("EngineProtocolT", bound="EngineProtocol")
ConfigValue = Union[str, int, bool, None]
ConfigMapping = Mapping[str, ConfigValue]
LOGGER = logging.getLogger(__name__)
MANAGED_OPTIONS = ["uci_chess960", "uci_variant", "multipv", "ponder"]
class EventLoopPolicy(asyncio.DefaultEventLoopPolicy): # type: ignore
"""
An event loop policy that ensures the event loop is capable of spawning
and watching subprocesses, even when not running in the main thread.
Windows: Creates a :class:`~asyncio.ProactorEventLoop`.
Unix: Creates a :class:`~asyncio.SelectorEventLoop`. Child watchers are
thread local. When not running on the main thread, the default child
watchers use relatively slow polling to detect process termination.
This does not affect communication.
"""
class _ThreadLocal(threading.local):
_watcher = None # type: Optional[AbstractChildWatcher]
def __init__(self) -> None:
super().__init__()
self._thread_local = self._ThreadLocal()
def get_child_watcher(self) -> "asyncio.AbstractChildWatcher":
if sys.platform == "win32" or threading.current_thread() == threading.main_thread():
return super().get_child_watcher()
class PollingChildWatcher(asyncio.SafeChildWatcher): # type: ignore
def __init__(self) -> None:
super().__init__()
self._poll_handle = None # type: Optional[asyncio.Handle]
self._poll_delay = 0.001
def attach_loop(self, loop: asyncio.AbstractEventLoop) -> None:
assert loop is None or isinstance(loop, asyncio.AbstractEventLoop)
if self._loop is not None and loop is None and self._callbacks:
warnings.warn("A loop is being detached from a child watcher with pending handlers", RuntimeWarning)
if self._poll_handle is not None:
self._poll_handle.cancel()
self._loop = loop
if loop is not None:
self._poll_handle = self._loop.call_soon(self._poll)
self._do_waitpid_all()
def _poll(self) -> None:
if self._loop:
self._do_waitpid_all()
self._poll_delay = min(self._poll_delay * 2, 1.0)
self._poll_handle = self._loop.call_later(self._poll_delay, self._poll)
if self._thread_local._watcher is None:
self._thread_local._watcher = PollingChildWatcher()
return self._thread_local._watcher
def set_child_watcher(self, watcher: "asyncio.AbstractChildWatcher") -> None:
if sys.platform == "win32" or threading.current_thread() == threading.main_thread():
return super().set_child_watcher(watcher)
assert watcher is None or isinstance(watcher, asyncio.AbstractChildWatcher)
if self._thread_local._watcher:
self._thread_local._watcher.close()
self._thread_local._watcher = watcher
def new_event_loop(self) -> asyncio.AbstractEventLoop:
return asyncio.ProactorEventLoop() if sys.platform == "win32" else asyncio.SelectorEventLoop() # type: ignore
def set_event_loop(self, loop: asyncio.AbstractEventLoop) -> None:
super().set_event_loop(loop)
if sys.platform != "win32" and threading.current_thread() != threading.main_thread():
self.get_child_watcher().attach_loop(loop)
def run_in_background(coroutine: "Callable[concurrent.futures.Future[T], Coroutine[Any, Any, None]]", *, name: Optional[str] = None, debug: bool = False, _policy_lock: threading.Lock = threading.Lock()) -> T:
"""
Runs ``coroutine(future)`` in a new event loop on a background thread.
Blocks and returns the *future* result as soon as it is resolved.
The coroutine and all remaining tasks continue running in the background
until it is complete.
Note: This installs a :class:`chess.engine.EventLoopPolicy` for the entire
process.
"""
assert asyncio.iscoroutinefunction(coroutine)
with _policy_lock:
if not isinstance(asyncio.get_event_loop_policy(), EventLoopPolicy):
asyncio.set_event_loop_policy(EventLoopPolicy())
future = concurrent.futures.Future() # type: concurrent.futures.Future[T]
def background() -> None:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.set_debug(debug)
try:
loop.run_until_complete(coroutine(future))
future.cancel()
except Exception as exc:
future.set_exception(exc)
return
finally:
try:
# Finish all remaining tasks.
pending = _all_tasks(loop)
loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
# Shutdown async generators.
try:
loop.run_until_complete(loop.shutdown_asyncgens())
except AttributeError:
# Before Python 3.6.
pass
finally:
loop.close()
threading.Thread(target=background, name=name).start()
return future.result()
class EngineError(RuntimeError):
"""Runtime error caused by a misbehaving engine or incorrect usage."""
class EngineTerminatedError(EngineError):
"""The engine process exited unexpectedly."""
class AnalysisComplete(Exception):
"""
Raised when analysis is complete, all information has been consumed, but
further information was requested.
"""
class Option(collections.namedtuple("Option", "name type default min max var")):
"""Information about an available engine option."""
if typing.TYPE_CHECKING: # Python 3.5 compatible type annotation
name = ""
type = ""
default = None # type: ConfigValue
min = None # type: Optional[int]
max = None # type: Optional[int]
var = [] # type: List[str]
def parse(self, value: ConfigValue) -> ConfigValue:
if self.type == "check":
return value and value != "false"
elif self.type == "spin":
try:
value = int(value)
except ValueError:
raise EngineError("expected integer for spin option {!r}, got: {!r}".format(self.name, value))
if self.min is not None and value < self.min:
raise EngineError("expected value for option {!r} to be at least {}, got: {}".format(self.name, self.min, value))
if self.max is not None and self.max < value:
raise EngineError("expected value for option {!r} to be at most {}, got: {}".format(self.name, self.max, value))
return value
elif self.type == "combo":
value = str(value)
if value not in (self.var or []):
raise EngineError("invalid value for combo option {!r}, got: {} (available: {})".format(self.name, value, ", ".join(self.var)))
return value
elif self.type in ["button", "reset", "save"]:
return None
elif self.type in ["string", "file", "path"]:
value = str(value)
if "\n" in value or "\r" in value:
raise EngineError("invalid line-break in string option {!r}: {!r}".format(self.name, value))
return value
else:
raise EngineError("unknown option type: {}", self.type)
def is_managed(self) -> bool:
"""
Some options are managed automatically: ``UCI_Chess960``,
``UCI_Variant``, ``MultiPV``, ``Ponder``.
"""
return self.name.lower() in MANAGED_OPTIONS
class Limit:
"""Search termination condition."""
def __init__(self, *,
time: Optional[float] = None,
depth: Optional[int] = None,
nodes: Optional[int] = None,
mate: Optional[int] = None,
white_clock: Optional[float] = None,
black_clock: Optional[float] = None,
white_inc: Optional[float] = None,
black_inc: Optional[float] = None,
remaining_moves: Optional[int] = None):
self.time = time
self.depth = depth
self.nodes = nodes
self.mate = mate
self.white_clock = white_clock
self.black_clock = black_clock
self.white_inc = white_inc
self.black_inc = black_inc
self.remaining_moves = remaining_moves
def __repr__(self) -> str:
return "{}({})".format(
type(self).__name__,
", ".join("{}={!r}".format(attr, getattr(self, attr))
for attr in ["time", "depth", "nodes", "mate", "white_clock", "black_clock", "white_inc", "black_inc", "remaining_moves"]
if getattr(self, attr) is not None))
class InfoDict(Dict[str, Union[str, int, float, "PovScore", List[chess.Move], Dict[chess.Move, List[chess.Move]], Dict[int, List[chess.Move]]]]):
"""Dictionary of extra information sent by the engine."""
@property
def score(self) -> Optional["PovScore"]:
return self.get("score")
@property
def pv(self) -> Optional[List[chess.Move]]:
return self.get("pv")
@property
def depth(self) -> Optional[int]:
return self.get("depth")
@property
def seldepth(self) -> Optional[int]:
return self.get("seldepth")
@property
def time(self) -> Optional[float]:
return self.get("time")
@property
def nodes(self) -> Optional[int]:
return self.get("nodes")
@property
def nps(self) -> Optional[int]:
return self.get("nps")
@property
def tbhits(self) -> Optional[int]:
return self.get("tbhits")
@property
def multipv(self) -> Optional[int]:
return self.get("multipv")
@property
def currmove(self) -> Optional[chess.Move]:
return self.get("currmove")
@property
def currmovenumber(self) -> Optional[int]:
return self.get("currmovenumber")
@property
def hashfull(self) -> Optional[int]:
return self.get("hashfull")
@property
def cpuload(self) -> Optional[int]:
return self.get("cpuload")
@property
def refutation(self) -> Optional[Dict[chess.Move, List[chess.Move]]]:
return self.get("refutation")
@property
def currline(self) -> Optional[Dict[int, List[chess.Move]]]:
return self.get("currline")
@property
def ebf(self) -> Optional[float]:
return self.get("ebf")
@property
def string(self) -> Optional[str]:
return self.get("string")
class PlayResult:
"""Returned by :func:`chess.engine.EngineProtocol.play()`."""
def __init__(self,
move: Optional[chess.Move],
ponder: Optional[chess.Move],
info: Optional[InfoDict] = None,
*,
draw_offered: bool = False,
resigned: bool = False) -> None:
self.move = move
self.ponder = ponder
self.info = info or {}
self.draw_offered = draw_offered
self.resigned = resigned
def __repr__(self) -> str:
return "<{} at {:#x} (move={}, ponder={}, info={}, draw_offered={}, resigned={})>".format(
type(self).__name__, id(self), self.move, self.ponder, self.info,
self.draw_offered, self.resigned)
try:
_IntFlag = enum.IntFlag # Since Python 3.6
except AttributeError:
_IntFlag = enum.IntEnum # type: ignore
class Info(_IntFlag):
"""Select information sent by the chess engine."""
NONE = 0
BASIC = 1
SCORE = 2
PV = 4
REFUTATION = 8
CURRLINE = 16
ALL = BASIC | SCORE | PV | REFUTATION | CURRLINE
INFO_NONE = Info.NONE
INFO_BASIC = Info.BASIC
INFO_SCORE = Info.SCORE
INFO_PV = Info.PV
INFO_REFUTATION = Info.REFUTATION
INFO_CURRLINE = Info.CURRLINE
INFO_ALL = Info.ALL
class PovScore:
"""A relative :class:`~chess.engine.Score` and the point of view."""
def __init__(self, relative: "Score", turn: chess.Color) -> None:
self.relative = relative # type: Score
self.turn = turn
def white(self) -> "Score":
"""Get the score from White's point of view."""
return self.pov(chess.WHITE)
def black(self) -> "Score":
"""Get the score from Black's point of view."""
return self.pov(chess.BLACK)
def pov(self, color: chess.Color) -> "Score":
"""Get the score from the point of view of the given *color*."""
return self.relative if self.turn == color else -self.relative
def is_mate(self) -> bool:
"""Tests if this is a mate score."""
return self.relative.is_mate()
def __repr__(self) -> str:
return "PovScore({!r}, {})".format(self.relative, "WHITE" if self.turn else "BLACK")
def __str__(self) -> str:
return str(self.relative)
def __eq__(self, other: object) -> bool:
if isinstance(other, PovScore):
return (self.relative, self.turn) == (other.relative, other.turn)
else:
return NotImplemented
@functools.total_ordering
class Score(abc.ABC):
"""
Evaluation of a position.
The score can be :class:`~chess.engine.Cp` (centi-pawns),
:class:`~chess.engine.Mate` or :py:data:`~chess.engine.MateGiven`.
A positive value indicates an advantage.
There is a total order defined on centi-pawn and mate scores.
>>> from chess.engine import Cp, Mate, MateGiven
>>>
>>> Mate(-0) < Mate(-1) < Cp(-50) < Cp(200) < Mate(4) < Mate(1) < MateGiven
True
Scores can be negated to change the point of view:
>>> -Cp(20)
Cp(-20)
>>> -Mate(-4)
Mate(+4)
>>> -Mate(0)
MateGiven
"""
@abc.abstractmethod
def score(self, *, mate_score: Optional[int] = None) -> Optional[int]:
"""
Returns the centi-pawn score as an integer or ``None``.
You can optionally pass a large value to convert mate scores to
centi-pawn scores.
>>> Cp(-300).score()
-300
>>> Mate(5).score() is None
True
>>> Mate(5).score(mate_score=100000)
99995
"""
@abc.abstractmethod
def mate(self) -> Optional[int]:
"""
Returns the number of plies to mate, negative if we are getting
mated, or ``None``.
:warning: This conflates ``Mate(0)`` (we lost) and ``MateGiven``
(we won) to ``0``.
"""
def is_mate(self) -> bool:
"""Tests if this is a mate score."""
return self.mate() is not None
@abc.abstractmethod
def __neg__(self) -> "Score":
pass
def _score_tuple(self) -> Tuple[bool, bool, bool, int, Optional[int]]:
return (
isinstance(self, MateGivenType),
self.is_mate() and self.mate() > 0,
not self.is_mate(),
-(self.mate() or 0),
self.score(),
)
def __eq__(self, other: object) -> bool:
if isinstance(other, Score):
return self._score_tuple() == other._score_tuple()
else:
return NotImplemented
def __lt__(self, other: object) -> bool:
if isinstance(other, Score):
return self._score_tuple() < other._score_tuple()
else:
return NotImplemented
class Cp(Score):
"""Centi-pawn score."""
def __init__(self, cp: int) -> None:
self.cp = cp
def mate(self) -> None:
return None
def score(self, *, mate_score: Optional[int] = None) -> int:
return self.cp
def __str__(self) -> str:
return "+{:d}".format(self.cp) if self.cp > 0 else str(self.cp)
def __repr__(self) -> str:
return "Cp({})".format(self)
def __neg__(self) -> "Cp":
return Cp(-self.cp)
def __pos__(self) -> "Cp":
return Cp(self.cp)
def __abs__(self) -> "Cp":
return Cp(abs(self.cp))
class Mate(Score):
"""Mate score."""
def __init__(self, moves: int) -> None:
self.moves = moves
def mate(self) -> int:
return self.moves
def score(self, *, mate_score: Optional[int] = None) -> Optional[int]:
if mate_score is None:
return None
elif self.moves > 0:
return mate_score - self.moves
else:
return -mate_score - self.moves
def __str__(self) -> str:
return "#+{}".format(self.moves) if self.moves > 0 else "#-{}".format(abs(self.moves))
def __repr__(self) -> str:
return "Mate({})".format(str(self).lstrip("#"))
def __neg__(self) -> Union["MateGivenType", "Mate"]:
return MateGiven if not self.moves else Mate(-self.moves)
def __pos__(self) -> "Mate":
return Mate(self.moves)
def __abs__(self) -> Union["MateGivenType", "Mate"]:
return MateGiven if not self.moves else Mate(abs(self.moves))
class MateGivenType(Score):
"""Winning mate score, equivalent to ``-Mate(0)``."""
def mate(self) -> int:
return 0
def score(self, *, mate_score: Optional[int] = None) -> Optional[int]:
return mate_score
def __neg__(self) -> Mate:
return Mate(0)
def __pos__(self) -> "MateGivenType":
return self
def __abs__(self) -> "MateGivenType":
return self
def __repr__(self) -> str:
return "MateGiven"
def __str__(self) -> str:
return "#+0"
MateGiven = MateGivenType()
class MockTransport:
def __init__(self, protocol: "EngineProtocol") -> None:
self.protocol = protocol
self.expectations = collections.deque() # type: typing.Deque[Tuple[str, List[str]]]
self.expected_pings = 0
self.stdin_buffer = bytearray()
self.protocol.connection_made(self)
def expect(self, expectation: str, responses: List[str] = []) -> None:
self.expectations.append((expectation, responses))
def expect_ping(self) -> None:
self.expected_pings += 1
def assert_done(self) -> None:
assert not self.expectations, "pending expectations: {}".format(self.expectations)
def get_pipe_transport(self, fd: int) -> "MockTransport":
assert fd == 0, "expected 0 for stdin, got {}".format(fd)
return self
def write(self, data: bytes) -> None:
self.stdin_buffer.extend(data)
while b"\n" in self.stdin_buffer:
line, self.stdin_buffer = self.stdin_buffer.split(b"\n", 1)
line = line.decode("utf-8")
if line.startswith("ping ") and self.expected_pings:
self.expected_pings -= 1
self.protocol.pipe_data_received(1, line.replace("ping ", "pong ").encode("utf-8") + b"\n")
else:
assert self.expectations, "unexpected: {}".format(line)
expectation, responses = self.expectations.popleft()
assert expectation == line, "expected {}, got: {}".format(expectation, line)
if responses:
self.protocol.pipe_data_received(1, "\n".join(responses).encode("utf-8") + b"\n")
def get_pid(self) -> int:
return id(self)
def get_returncode(self) -> Optional[int]:
return None if self.expectations else 0
class EngineProtocol(asyncio.SubprocessProtocol, metaclass=abc.ABCMeta):
"""Protocol for communicating with a chess engine process."""
def __init__(self) -> None:
self.loop = _get_running_loop()
self.transport = None # type: Optional[asyncio.SubprocessTransport]
self.buffer = {
1: bytearray(), # stdout
2: bytearray(), # stderr
}
self.command = None # type: Optional[BaseCommand[EngineProtocol, Any]]
self.next_command = None # type: Optional[BaseCommand[EngineProtocol, Any]]
self.initialized = False
self.returncode = asyncio.Future() # type: asyncio.Future[int]
def connection_made(self, transport: asyncio.BaseTransport) -> None:
self.transport = transport
LOGGER.debug("%s: Connection made", self)
def connection_lost(self, exc: Optional[Exception]) -> None:
code = self.transport.get_returncode()
LOGGER.debug("%s: Connection lost (exit code: %d, error: %s)", self, code, exc)
# Terminate commands.
if self.command is not None:
self.command._engine_terminated(self, code)
self.command = None
if self.next_command is not None:
self.next_command._engine_terminated(self, code)
self.next_command = None
self.returncode.set_result(code)
def process_exited(self) -> None:
LOGGER.debug("%s: Process exited", self)
def send_line(self, line: str) -> None:
LOGGER.debug("%s: << %s", self, line)
stdin = self.transport.get_pipe_transport(0)
stdin.write(line.encode("utf-8"))
stdin.write(b"\n")
def pipe_data_received(self, fd: int, data: Union[bytes, Text]) -> None:
self.buffer[fd].extend(data)
while b"\n" in self.buffer[fd]:
line, self.buffer[fd] = self.buffer[fd].split(b"\n", 1)
if line.endswith(b"\r"):
line = line[:-1]
line = line.decode("utf-8")
if fd == 1:
self.loop.call_soon(self._line_received, line)
else:
self.loop.call_soon(self.error_line_received, line)
def error_line_received(self, line: str) -> None:
LOGGER.warning("%s: stderr >> %s", self, line)
def _line_received(self, line: str) -> None:
LOGGER.debug("%s: >> %s", self, line)
self.line_received(line)
if self.command:
self.command._line_received(self, line)
def line_received(self, line: str) -> None:
pass
async def communicate(self: EngineProtocolT, command_factory: Callable[[], "BaseCommand[EngineProtocolT, T]"]) -> T:
command = command_factory()
if self.returncode.done():
raise EngineTerminatedError("engine process dead (exit code: {})".format(self.returncode.result()))
assert command.state == CommandState.New
if self.next_command is not None:
self.next_command.result.cancel()
self.next_command.finished.cancel()
self.next_command._done()
self.next_command = command
def previous_command_finished(_: "asyncio.Future[None]") -> None:
if self.command is not None:
self.command._done()
self.command, self.next_command = self.next_command, None
if self.command is not None:
cmd = self.command
cmd.result.add_done_callback(lambda result: cmd._cancel(self) if cmd.result.cancelled() else None)
cmd.finished.add_done_callback(previous_command_finished)
cmd._start(self)
if self.command is None:
previous_command_finished(None)
elif not self.command.result.done():
self.command.result.cancel()
elif not self.command.result.cancelled():
self.command._cancel(self)
return await command.result
def __repr__(self) -> str:
pid = self.transport.get_pid() if self.transport is not None else "?"
return "<{} (pid={})>".format(type(self).__name__, pid)
@abc.abstractmethod
async def initialize(self) -> None:
"""Initializes the engine."""
@abc.abstractmethod
async def ping(self) -> None:
"""
Pings the engine and waits for a response. Used to ensure the engine
is still alive and idle.
"""
@abc.abstractmethod
async def configure(self, options: ConfigMapping) -> None:
"""
Configures global engine options.
:param options: A dictionary of engine options, where the keys are
names of :py:attr:`~options`. Do not set options that are
managed automatically (:func:`chess.engine.Option.is_managed()`).
"""
@abc.abstractmethod
async def play(self, board: chess.Board, limit: Limit, *, game: object = None, info: Info = INFO_NONE, ponder: bool = False, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}) -> PlayResult:
"""
Play a position.
:param board: The position. The entire move stack will be sent to the
engine.
:param limit: An instance of :class:`chess.engine.Limit` that
determines when to stop thinking.
:param game: Optional. An arbitrary object that identifies the game.
Will automatically inform the engine if the object is not equal
to the previous game (e.g. ``ucinewgame``, ``new``).
:param info: Selects which additional information to retrieve from the
engine. ``INFO_NONE``, ``INFO_BASE`` (basic information that is
trivial to obtain), ``INFO_SCORE``, ``INFO_PV``,
``INFO_REFUTATION``, ``INFO_CURRLINE``, ``INFO_ALL`` or any
bitwise combination. Some overhead is associated with parsing
extra information.
:param ponder: Whether the engine should keep analysing in the
background even after the result has been returned.
:param root_moves: Optional. Consider only root moves from this list.
:param options: Optional. A dictionary of engine options for the
analysis. The previous configuration will be restored after the
analysis is complete. You can permanently apply a configuration
with :func:`~chess.engine.EngineProtocol.configure()`.
"""
async def analyse(self, board: chess.Board, limit: Limit, *, multipv: Optional[int] = None, game: object = None, info: Info = INFO_ALL, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}) -> Union[List[InfoDict], InfoDict]:
"""
Analyses a position and returns a dictionary of
`information <#chess.engine.PlayResult.info>`_.
:param board: The position to analyse. The entire move stack will be
sent to the engine.
:param limit: An instance of :class:`chess.engine.Limit` that
determines when to stop the analysis.
:param multipv: Optional. Analyse multiple root moves. Will return a list of
at most *multipv* dictionaries rather than just a single
info dictionary.
:param game: Optional. An arbitrary object that identifies the game.
Will automatically inform the engine if the object is not equal
to the previous game (e.g. ``ucinewgame``, ``new``).
:param info: Selects which information to retrieve from the
engine. ``INFO_NONE``, ``INFO_BASE`` (basic information that is
trivial to obtain), ``INFO_SCORE``, ``INFO_PV``,
``INFO_REFUTATION``, ``INFO_CURRLINE``, ``INFO_ALL`` or any
bitwise combination. Some overhead is associated with parsing
extra information.
:param root_moves: Optional. Limit analysis to a list of root moves.
:param options: Optional. A dictionary of engine options for the
analysis. The previous configuration will be restored after the
analysis is complete. You can permanently apply a configuration
with :func:`~chess.engine.EngineProtocol.configure()`.
"""
analysis = await self.analysis(board, limit, multipv=multipv, game=game, info=info, root_moves=root_moves, options=options)
with analysis:
await analysis.wait()
return analysis.info if multipv is None else analysis.multipv
@abc.abstractmethod
async def analysis(self, board: chess.Board, limit: Optional[Limit] = None, *, multipv: Optional[int] = None, game: object = None, info: Info = INFO_ALL, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}) -> "AnalysisResult":
"""
Starts analysing a position.
:param board: The position to analyse. The entire move stack will be
sent to the engine.
:param limit: Optional. An instance of :class:`chess.engine.Limit`
that determines when to stop the analysis. Analysis is infinite
by default.
:param multipv: Optional. Analyse multiple root moves.
:param game: Optional. An arbitrary object that identifies the game.
Will automatically inform the engine if the object is not equal
to the previous game (e.g. ``ucinewgame``, ``new``).
:param info: Selects which information to retrieve from the
engine. ``INFO_NONE``, ``INFO_BASE`` (basic information that is
trivial to obtain), ``INFO_SCORE``, ``INFO_PV``,
``INFO_REFUTATION``, ``INFO_CURRLINE``, ``INFO_ALL`` or any
bitwise combination. Some overhead is associated with parsing
extra information.
:param root_moves: Optional. Limit analysis to a list of root moves.
:param options: Optional. A dictionary of engine options for the
analysis. The previous configuration will be restored after the
analysis is complete. You can permanently apply a configuration
with :func:`~chess.engine.EngineProtocol.configure()`.
Returns :class:`~chess.engine.AnalysisResult`, a handle that allows
asynchronously iterating over the information sent by the engine
and stopping the the analysis at any time.
"""
@abc.abstractmethod
async def quit(self) -> None:
"""Asks the engine to shut down."""
@classmethod
async def popen(cls: Type[EngineProtocolT], command: Union[str, List[str]], *, setpgrp: bool = False, **kwargs: Any) -> Tuple[asyncio.SubprocessTransport, EngineProtocolT]:
if not isinstance(command, list):
command = [command]
popen_args = {}
if setpgrp:
try:
# Windows.
popen_args["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore
except AttributeError:
# Unix.
popen_args["preexec_fn"] = os.setpgrp # type: ignore
popen_args.update(kwargs)
return await _get_running_loop().subprocess_exec(cls, *command, **popen_args)
class CommandState(enum.Enum):
New = 1
Active = 2
Cancelling = 3
Done = 4
class BaseCommand(Generic[EngineProtocolT, T]):
def __init__(self) -> None:
self.state = CommandState.New
self.result = asyncio.Future() # type: asyncio.Future[T]
self.finished = asyncio.Future() # type: asyncio.Future[None]
def _engine_terminated(self, engine: EngineProtocolT, code: int) -> None:
exc = EngineTerminatedError("engine process died unexpectedly (exit code: {})".format(code))
if self.state == CommandState.Active:
self.engine_terminated(engine, exc)
elif self.state == CommandState.Cancelling:
self.finished.set_result(None)
elif self.state == CommandState.New:
self._handle_exception(engine, exc)
def _handle_exception(self, engine: EngineProtocolT, exc: Exception) -> None:
if not self.result.done():
self.result.set_exception(exc)
else:
engine.loop.call_exception_handler({
"message": "engine command failed after returning preliminary result ({!r})".format(self.result),
"exception": exc,
"protocol": engine,
"transport": engine.transport,
})
if not self.finished.done():
self.finished.set_result(None)
def set_finished(self: "BaseCommand[EngineProtocolT, None]") -> None:
assert self.state in [CommandState.Active, CommandState.Cancelling]
if not self.result.done():
self.result.set_result(None)
self.finished.set_result(None)
def _cancel(self, engine: EngineProtocolT) -> None:
assert self.state == CommandState.Active
self.state = CommandState.Cancelling
self.cancel(engine)
def _start(self, engine: EngineProtocolT) -> None:
assert self.state == CommandState.New
self.state = CommandState.Active
try:
self.check_initialized(engine)
self.start(engine)
except EngineError as err:
self._handle_exception(engine, err)
def _done(self) -> None:
assert self.state != CommandState.Done
self.state = CommandState.Done
def _line_received(self, engine: EngineProtocolT, line: str) -> None:
assert self.state in [CommandState.Active, CommandState.Cancelling]
try:
self.line_received(engine, line)
except EngineError as err:
self._handle_exception(engine, err)
def cancel(self, engine: EngineProtocolT) -> None:
pass
def check_initialized(self, engine: EngineProtocolT) -> None:
if not engine.initialized:
raise EngineError("tried to run command, but engine is not initialized")
def start(self, engine: EngineProtocolT) -> None:
raise NotImplementedError
def line_received(self, engine: EngineProtocolT, line: str) -> None:
pass
def engine_terminated(self, engine: EngineProtocolT, exc: Exception) -> None:
self._handle_exception(engine, exc)
def __repr__(self) -> str:
return "<{} at {:#x} (state={}, result={}, finished={}>".format(type(self).__name__, id(self), self.state, self.result, self.finished)
class UciProtocol(EngineProtocol):
"""
An implementation of the
`Universal Chess Interface <https://www.chessprogramming.org/UCI>`_
protocol.
"""
def __init__(self) -> None:
super().__init__()
self.options = UciOptionMap() # type: UciOptionMap[Option]
self.config = UciOptionMap() # type: UciOptionMap[ConfigValue]
self.target_config = UciOptionMap() # type: UciOptionMap[ConfigValue]
self.id = {} # type: Dict[str, str]
self.board = chess.Board()
self.game = None # type: object
self.first_game = True