Yohaan Seth Nathan commited on
Commit
289b14d
·
1 Parent(s): 6720243

Move engine_ctrl to seperate dir

Browse files
engine_ctrl/__init__.py ADDED
File without changes
engine_ctrl.py → engine_ctrl/usi.py RENAMED
@@ -1,243 +1,256 @@
1
- import threading
2
- import subprocess
3
- import os
4
- import signal
5
- import logging
6
-
7
- logger = logging.getLogger(__name__)
8
-
9
-
10
- class Engine:
11
- def __init__(self, command, cwd=None):
12
- self.proccess = self.open_process(command)
13
- self.go_commands = None
14
- self.info = {}
15
- cwd = cwd or os.path.realpath(os.path.expanduser("."))
16
-
17
- def set_go_commands(self, go_comm):
18
- self.go_commands = go_comm
19
- logger.info(self.go_commands)
20
-
21
- def open_process(self, command, shell=True, _popen_lock=threading.Lock()):
22
- kwargs = {
23
- "shell": shell,
24
- "stdout": subprocess.PIPE,
25
- "stderr": subprocess.STDOUT,
26
- "stdin": subprocess.PIPE,
27
- "bufsize": 1, # Line buffered
28
- "universal_newlines": True,
29
- }
30
- # Prevent signal propagation from parent process
31
- try:
32
- # Windows
33
- kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
34
- except AttributeError:
35
- # Unix
36
- kwargs["preexec_fn"] = os.setpgrp
37
-
38
- with _popen_lock: # Work around Python 2 Popen race condition
39
- return subprocess.Popen(command, **kwargs)
40
-
41
- def kill_process(self):
42
- try:
43
- # Windows
44
- self.proccess.send_signal(signal.CTRL_BREAK_EVENT)
45
- except AttributeError:
46
- # Unix
47
- os.killpg(self.proccess.pid, signal.SIGKILL)
48
-
49
- def send(self, line):
50
- self.proccess.stdin.write(line + "\n")
51
- self.proccess.stdin.flush()
52
-
53
- def recv(self):
54
- while True:
55
- line = self.proccess.stdout.readline()
56
- if line == "":
57
- raise EOFError()
58
-
59
- line = line.rstrip()
60
-
61
- if line:
62
- return line
63
-
64
- def recv_usi(self):
65
- command_and_args = self.recv().split(None, 1)
66
- if len(command_and_args) == 1:
67
- return command_and_args[0], ""
68
- elif len(command_and_args) == 2:
69
- return command_and_args
70
-
71
- def usi(self):
72
- self.send("usi")
73
-
74
- engine_info = {}
75
-
76
- while True:
77
- command, arg = self.recv_usi()
78
-
79
- if command == "usiok":
80
- return engine_info
81
- elif command == "id":
82
- name_and_value = arg.split(None, 1)
83
- if len(name_and_value) == 2:
84
- engine_info[name_and_value[0]] = name_and_value[1]
85
- elif command == "option" or command.startswith("Fairy-Stockfish"): # Fixes a potention bug with Fairy Stockfish
86
- pass
87
- else:
88
- logger.error("Unexpected engine response to usi: %s %s" % (command, arg))
89
- self.id = engine_info
90
-
91
- def isready(self):
92
- self.send("isready")
93
- while True:
94
- command, arg = self.recv_usi()
95
- if command == "readyok":
96
- break
97
- elif command == "info" and arg.startswith("string Error! "):
98
- logger.error("Unexpected engine response to isready: %s %s" % (command, arg))
99
- elif command == "info" and arg.startswith("string "):
100
- pass
101
- else:
102
- logger.error("Unexpected engine response to isready: %s %s" % (command, arg))
103
-
104
- def setoption(self, name, value):
105
- if value is True:
106
- value = "true"
107
- elif value is False:
108
- value = "false"
109
- elif value is None:
110
- value = "none"
111
-
112
- self.send("setoption name %s value %s" % (name, value))
113
-
114
- def go(self, position, moves, movetime=None, btime=None, wtime=None, binc=None, winc=None, byo=None, depth=None, nodes=None, ponder=False):
115
- self.position(position, moves)
116
-
117
- builder = []
118
- builder.append("go")
119
- if ponder:
120
- builder.append("ponder")
121
- if movetime is not None:
122
- builder.append("movetime")
123
- builder.append(str(movetime))
124
- if depth is not None:
125
- builder.append("depth")
126
- builder.append(str(depth))
127
- if nodes is not None:
128
- builder.append("nodes")
129
- builder.append(str(nodes))
130
- # In Shogi and USI, black is the player to move first
131
- if btime is not None and nodes is None and depth is None and movetime is None:
132
- builder.append("btime")
133
- builder.append(str(btime))
134
- if wtime is not None and nodes is None and depth is None and movetime is None:
135
- builder.append("wtime")
136
- builder.append(str(wtime))
137
- if binc is not None and nodes is None and depth is None and movetime is None:
138
- builder.append("binc")
139
- builder.append(str(binc))
140
- if winc is not None and nodes is None and depth is None and movetime is None:
141
- builder.append("winc")
142
- builder.append(str(winc))
143
- if byo is not None and nodes is None and depth is None and movetime is None:
144
- builder.append("byoyomi")
145
- builder.append(str(byo))
146
-
147
- self.send(" ".join(builder))
148
- logger.info(" ".join(builder))
149
-
150
- info = {}
151
- info["bestmove"] = None
152
- info["pondermove"] = None
153
-
154
- while True:
155
- command, arg = self.recv_usi()
156
-
157
- if command == "bestmove":
158
- arg_split = arg.split()
159
- bestmove = arg_split[0]
160
- if bestmove and bestmove != "(none)":
161
- info["bestmove"] = bestmove
162
- if len(arg_split) == 3:
163
- if arg_split[1] == "ponder":
164
- ponder_move = arg_split[2]
165
- if ponder_move and ponder_move != "(none)":
166
- info["pondermove"] = ponder_move
167
- return (info["bestmove"], info["pondermove"])
168
-
169
- elif command == "info":
170
- arg = arg or ""
171
-
172
- # Parse all other parameters
173
- score_kind, score_value, lowerbound, upperbound = None, None, False, False
174
- current_parameter = None
175
- for token in arg.split(" "):
176
- if current_parameter == "string":
177
- # Everything until the end of line is a string
178
- if "string" in info:
179
- info["string"] += " " + token
180
- else:
181
- info["string"] = token
182
- elif token == "score":
183
- current_parameter = "score"
184
- elif token == "pv":
185
- current_parameter = "pv"
186
- if info.get("multipv", 1) == 1:
187
- info.pop("pv", None)
188
- elif token in ["depth", "seldepth", "time", "nodes", "multipv",
189
- "currmove", "currmovenumber",
190
- "hashfull", "nps", "tbhits", "cpuload",
191
- "refutation", "currline", "string"]:
192
- current_parameter = token
193
- info.pop(current_parameter, None)
194
- elif current_parameter in ["depth", "seldepth", "time",
195
- "nodes", "currmovenumber",
196
- "hashfull", "nps", "tbhits",
197
- "cpuload", "multipv"]:
198
- # Integer parameters
199
- info[current_parameter] = int(token)
200
- elif current_parameter == "score":
201
- # Score
202
- if token in ["cp", "mate"]:
203
- score_kind = token
204
- score_value = None
205
- elif token == "lowerbound":
206
- lowerbound = True
207
- elif token == "upperbound":
208
- upperbound = True
209
- else:
210
- score_value = int(token)
211
- elif current_parameter != "pv" or info.get("multipv", 1) == 1:
212
- # Strings
213
- if current_parameter in info:
214
- info[current_parameter] += " " + token
215
- else:
216
- info[current_parameter] = token
217
-
218
- # Set score. Prefer scores that are not just a bound
219
- if score_kind and score_value is not None and (not (lowerbound or upperbound) or "score" not in info or info["score"].get("lowerbound") or info["score"].get("upperbound")):
220
- info["score"] = {score_kind: score_value}
221
- if lowerbound:
222
- info["score"]["lowerbound"] = lowerbound
223
- if upperbound:
224
- info["score"]["upperbound"] = upperbound
225
- self.info = info
226
- else:
227
- logger.error("Unexpected engine response to go: %s %s" % (command, arg))
228
-
229
- def position(self, position, moves):
230
- if position != "startpos":
231
- position = "sfen " + position
232
- self.send("position %s moves %s" % (position, " ".join(moves)))
233
- logger.info("position %s moves %s" % (position, " ".join(moves)))
234
-
235
- def stop(self):
236
- self.send("stop")
237
-
238
- def quit(self):
239
- self.send("quit")
240
-
241
- def ponderhit(self):
242
- self.send("ponderhit")
243
- logger.info("ponderhit")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+ import subprocess
3
+ import os
4
+ import signal
5
+ import logging
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+
10
+ class Engine:
11
+ def __init__(self, command, cwd=None):
12
+ self.info = {}
13
+ self.id = {}
14
+ cwd = cwd or os.path.realpath(os.path.expanduser("."))
15
+ self.proccess = self.open_process(command, cwd)
16
+ self.go_commands = None
17
+
18
+ def set_go_commands(self, go_comm):
19
+ self.go_commands = go_comm
20
+ logger.info(self.go_commands)
21
+
22
+ def open_process(self, command, cwd=None, shell=True, _popen_lock=threading.Lock()):
23
+ kwargs = {
24
+ "shell": shell,
25
+ "stdout": subprocess.PIPE,
26
+ "stderr": subprocess.STDOUT,
27
+ "stdin": subprocess.PIPE,
28
+ "bufsize": 1, # Line buffered
29
+ "universal_newlines": True,
30
+ }
31
+
32
+ if cwd is not None:
33
+ kwargs["cwd"] = cwd
34
+
35
+ # Prevent signal propagation from parent process
36
+ try:
37
+ # Windows
38
+ kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
39
+ except AttributeError:
40
+ # Unix
41
+ kwargs["preexec_fn"] = os.setpgrp
42
+
43
+ with _popen_lock: # Work around Python 2 Popen race condition
44
+ return subprocess.Popen(command, **kwargs)
45
+
46
+ def kill_process(self):
47
+ try:
48
+ # Windows
49
+ self.proccess.send_signal(signal.CTRL_BREAK_EVENT)
50
+ except AttributeError:
51
+ # Unix
52
+ os.killpg(self.proccess.pid, signal.SIGKILL)
53
+
54
+ def send(self, line):
55
+ logger.debug(f"<< {line}")
56
+ assert self.proccess.stdin is not None
57
+ self.proccess.stdin.write(line + "\n")
58
+ self.proccess.stdin.flush()
59
+
60
+ def recv(self):
61
+ while True:
62
+ assert self.proccess.stdout is not None
63
+ line = self.proccess.stdout.readline()
64
+ if line == "":
65
+ raise EOFError()
66
+
67
+ line = line.rstrip()
68
+
69
+ logger.debug(f">> {line}")
70
+
71
+ if line:
72
+ return line
73
+
74
+ def recv_usi(self):
75
+ command_and_args = self.recv().split(None, 1)
76
+ if len(command_and_args) == 1:
77
+ return command_and_args[0], ""
78
+ elif len(command_and_args) == 2:
79
+ return command_and_args
80
+
81
+ def usi(self):
82
+ self.send("usi")
83
+
84
+ engine_info = {}
85
+
86
+ while True:
87
+ command, arg = self.recv_usi()
88
+
89
+ if command == "usiok":
90
+ return engine_info
91
+ elif command == "id":
92
+ name_and_value = arg.split(None, 1)
93
+ if len(name_and_value) == 2:
94
+ engine_info[name_and_value[0]] = name_and_value[1]
95
+ elif command == "option":
96
+ pass
97
+ elif command == "Fairy-Stockfish" and " by " in arg:
98
+ # Ignore identification line
99
+ pass
100
+ else:
101
+ logger.warning("Unexpected engine response to usi: %s %s" % (command, arg))
102
+ self.id = engine_info
103
+
104
+ def isready(self):
105
+ self.send("isready")
106
+ while True:
107
+ command, arg = self.recv_usi()
108
+ if command == "readyok":
109
+ break
110
+ elif command == "info" and arg.startswith("string Error! "):
111
+ logger.error("Unexpected engine response to isready: %s %s" % (command, arg))
112
+ elif command == "info" and arg.startswith("string "):
113
+ pass
114
+ else:
115
+ logger.warning("Unexpected engine response to isready: %s %s" % (command, arg))
116
+
117
+ def setoption(self, name, value):
118
+ if value is True:
119
+ value = "true"
120
+ elif value is False:
121
+ value = "false"
122
+ elif value is None:
123
+ value = "none"
124
+
125
+ self.send("setoption name %s value %s" % (name, value))
126
+
127
+ def go(self, position, moves, movetime=None, btime=None, wtime=None, binc=None, winc=None, byo=None, depth=None, nodes=None, ponder=False):
128
+ self.position(position, moves)
129
+
130
+ builder = []
131
+ builder.append("go")
132
+ if ponder:
133
+ builder.append("ponder")
134
+ if movetime is not None:
135
+ builder.append("movetime")
136
+ builder.append(str(movetime))
137
+ if nodes is not None:
138
+ builder.append("nodes")
139
+ builder.append(str(nodes))
140
+ if depth is not None:
141
+ builder.append("depth")
142
+ builder.append(str(depth))
143
+ # In Shogi and USI, black is the player to move first
144
+ if btime is not None:
145
+ builder.append("btime")
146
+ builder.append(str(btime))
147
+ if wtime is not None:
148
+ builder.append("wtime")
149
+ builder.append(str(wtime))
150
+ if binc is not None:
151
+ builder.append("binc")
152
+ builder.append(str(binc))
153
+ if winc is not None:
154
+ builder.append("winc")
155
+ builder.append(str(winc))
156
+ if byo is not None:
157
+ builder.append("byoyomi")
158
+ builder.append(str(byo))
159
+
160
+ self.send(" ".join(builder))
161
+ logger.info(" ".join(builder))
162
+
163
+ info = {}
164
+ info["bestmove"] = None
165
+ info["pondermove"] = None
166
+
167
+ while True:
168
+ command, arg = self.recv_usi()
169
+
170
+ if command == "bestmove":
171
+ arg_split = arg.split()
172
+ bestmove = arg_split[0]
173
+ if bestmove and bestmove != "(none)":
174
+ info["bestmove"] = bestmove
175
+ if len(arg_split) == 3:
176
+ if arg_split[1] == "ponder":
177
+ ponder_move = arg_split[2]
178
+ if ponder_move and ponder_move != "(none)":
179
+ info["pondermove"] = ponder_move
180
+ return (info["bestmove"], info["pondermove"])
181
+
182
+ elif command == "info":
183
+ arg = arg or ""
184
+
185
+ # Parse all other parameters
186
+ score_kind, score_value, lowerbound, upperbound = None, None, False, False
187
+ current_parameter = None
188
+ for token in arg.split(" "):
189
+ if current_parameter == "string":
190
+ # Everything until the end of line is a string
191
+ if "string" in info:
192
+ info["string"] += " " + token
193
+ else:
194
+ info["string"] = token
195
+ elif token == "score":
196
+ current_parameter = "score"
197
+ elif token == "pv":
198
+ current_parameter = "pv"
199
+ if info.get("multipv", 1) == 1:
200
+ info.pop("pv", None)
201
+ elif token in ["depth", "seldepth", "time", "nodes", "multipv",
202
+ "currmove", "currmovenumber",
203
+ "hashfull", "nps", "tbhits", "cpuload",
204
+ "refutation", "currline", "string"]:
205
+ current_parameter = token
206
+ info.pop(current_parameter, None)
207
+ elif current_parameter in ["depth", "seldepth", "time",
208
+ "nodes", "currmovenumber",
209
+ "hashfull", "nps", "tbhits",
210
+ "cpuload", "multipv"]:
211
+ # Integer parameters
212
+ info[current_parameter] = int(token)
213
+ elif current_parameter == "score":
214
+ # Score
215
+ if token in ["cp", "mate"]:
216
+ score_kind = token
217
+ score_value = None
218
+ elif token == "lowerbound":
219
+ lowerbound = True
220
+ elif token == "upperbound":
221
+ upperbound = True
222
+ else:
223
+ score_value = int(token)
224
+ elif current_parameter != "pv" or info.get("multipv", 1) == 1:
225
+ # Strings
226
+ if current_parameter in info:
227
+ info[current_parameter] += " " + token
228
+ else:
229
+ info[current_parameter] = token
230
+
231
+ # Set score. Prefer scores that are not just a bound
232
+ if score_kind and score_value is not None and (not (lowerbound or upperbound) or "score" not in info or info["score"].get("lowerbound") or info["score"].get("upperbound")):
233
+ info["score"] = {score_kind: score_value}
234
+ if lowerbound:
235
+ info["score"]["lowerbound"] = lowerbound
236
+ if upperbound:
237
+ info["score"]["upperbound"] = upperbound
238
+ self.info = info
239
+ else:
240
+ logger.error("Unexpected engine response to go: %s %s" % (command, arg))
241
+
242
+ def position(self, position, moves):
243
+ if position != "startpos":
244
+ position = "sfen " + position
245
+ self.send("position %s moves %s" % (position, " ".join(moves)))
246
+ logger.debug("position %s moves %s" % (position, " ".join(moves)))
247
+
248
+ def stop(self):
249
+ self.send("stop")
250
+
251
+ def ponderhit(self):
252
+ self.send("ponderhit")
253
+ logger.info("ponderhit")
254
+
255
+ def quit(self):
256
+ self.send("quit")
engine_wrapper.py CHANGED
@@ -5,7 +5,7 @@ from enum import Enum
5
 
6
  logger = logging.getLogger(__name__)
7
 
8
- import engine_ctrl
9
 
10
 
11
  @backoff.on_exception(backoff.expo, BaseException, max_time=120)
@@ -130,7 +130,7 @@ class USIEngine(EngineWrapper):
130
  commands = commands[0] if len(commands) == 1 else commands
131
  self.go_commands = options.pop("go_commands", {}) or {}
132
 
133
- self.engine = engine_ctrl.Engine(commands, cwd=cwd)
134
  self.engine.usi()
135
 
136
  if options:
 
5
 
6
  logger = logging.getLogger(__name__)
7
 
8
+ from engine_ctrl import usi
9
 
10
 
11
  @backoff.on_exception(backoff.expo, BaseException, max_time=120)
 
130
  commands = commands[0] if len(commands) == 1 else commands
131
  self.go_commands = options.pop("go_commands", {}) or {}
132
 
133
+ self.engine = usi.Engine(commands, cwd=cwd)
134
  self.engine.usi()
135
 
136
  if options: