-
Notifications
You must be signed in to change notification settings - Fork 1
/
katago.py
204 lines (164 loc) · 5.53 KB
/
katago.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
import enum
import io
import jsons
import os
import subprocess
from collections import namedtuple
from dataclasses import dataclass, field
from enum import auto, Enum
from threading import Thread
from typing import List, Optional
from dataclasses_json import dataclass_json
class LineType(Enum):
error = auto()
output = auto()
class KataGo:
def __init__(self, executable, configuration, model, analysis_threads=10, search_threads=1, output=False):
self.output = output
if output:
print(' Launching KataGo...')
def read_stream(name, stream, type_, buffer):
if output:
print(f' {name} thread has begun.')
while True:
line = stream.readline().rstrip()
if (
not self._ready and
type_ is LineType.error and
line.endswith('Started, ready to begin handling requests')
):
self._ready = True
if output:
print(' KataGo is ready to accept inputs.')
if output:
print(f' {name} read: {line}')
if line:
buffer.append((type_, line))
else:
if output:
print(f' {name} thread has finished.')
break
command = f'{executable} analysis -config {configuration} -model {model} -analysis-threads {analysis_threads} ' \
f'-override-config numSearchThreads={search_threads}'
self._process = subprocess.Popen(
command,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE
)
self._buffer = []
self._ready = False
stderr = io.TextIOWrapper(self._process.stderr, encoding='utf-8', errors='strict')
self._errors = Thread(target=read_stream, args=('ERR', stderr, LineType.error, self._buffer))
self._errors.daemon = True
self._errors.start()
stdout = io.TextIOWrapper(self._process.stdout, encoding='utf-8', errors='strict')
self._outputs = Thread(target=read_stream, args=('OUT', stdout, LineType.output, self._buffer))
self._outputs.daemon = True
self._outputs.start()
if output:
print(' KataGo has launched.')
@property
def ready(self):
return self._ready
def write_message(self, message):
if self.output:
print(f' KataGo::write_message() called...')
if not self._ready:
raise Exception('KataGo is not ready! Learn some damn patience.')
command = jsons.dumps(message, strip_nulls=True) + os.linesep
# print('??', command)
encoded = command.encode('utf-8')
self._process.stdin.write(encoded)
self._process.stdin.flush()
if self.output:
print(f' Passed message to KataGo: {encoded}')
def next_line(self):
return self._buffer.pop(0) if self._buffer else None
def kill(self):
if self.output:
print(' KataGo::kill() called...')
self._process.kill()
if self.output:
print(' KataGo::kill() call complete.')
class KataGoPlayer(enum.Enum):
b = 'b'
w = 'w'
@property
def opposite(self):
return KataGoPlayer.b if self is KataGoPlayer.w else KataGoPlayer.w
def __str__(self):
return 'B' if self is KataGoPlayer.b else 'W'
def __repr__(self):
return self.__str__()
class MoveInfo(namedtuple('MoveInfo', 'player location')):
pass
@dataclass
class SearchFocus:
player: KataGoPlayer
moves: List[str]
untilDepth: int
@dataclass_json
@dataclass(init=False)
class Command:
id: str
initialPlayer: KataGoPlayer
initialStones: List[MoveInfo]
moves: List[MoveInfo]
rules: str
boardXSize: int = 19
boardYSize: int = 19
includePolicy: Optional[bool] = True
allowMoves: Optional[SearchFocus] = None
analyzeTurns: Optional[List[int]] = None
avoidMoves: Optional[SearchFocus] = None
includeMovesOwnership: Optional[bool] = None
includeOwnership: Optional[bool] = None
includePVVisits: Optional[bool] = None
komi: Optional[float] = None
maxVisits: Optional[int] = None
overrideSettings: Optional[dict] = None
priority: Optional[int] = None
priorities: Optional[List[int]] = None
reportDuringSearchEvery: Optional[float] = None
rootPolicyTemperature: Optional[float] = None
whiteHandicapBonus: Optional[str] = None
@dataclass_json
@dataclass()
class RootAnalysis:
scoreSelfplay: float
scoreLead: float
utility: float
winrate: float
visits: int
def negate(self):
return RootAnalysis(
-self.scoreSelfplay,
-self.scoreLead,
-self.utility,
1. - self.winrate,
self.visits
)
@dataclass_json
@dataclass()
class MoveAnalysis(RootAnalysis):
lcb: float
move: str
order: int
prior: float
pv: List[str]
scoreMean: float
scoreStdev: float
utilityLcb: float
pvVisits: Optional[List[int]] = None
ownership: Optional[List[float]] = None
@dataclass_json
@dataclass()
class Response:
id: str
rootInfo: RootAnalysis
moveInfos: List[MoveAnalysis] = field(default_factory=list)
turnNumber: Optional[int] = 0
isDuringSearch: Optional[bool] = None
ownership: Optional[List[float]] = field(default_factory=list)
policy: Optional[List[float]] = field(default_factory=list)