Toadofsky commited on
Commit
bfceb5b
·
1 Parent(s): 289b14d

Auto detect text files and perform LF normalization (#114)

Browse files

* Auto detect text files and perform LF normalization

* Remove CR characters

Files changed (2) hide show
  1. .gitattributes +2 -0
  2. engine_ctrl/usi.py +255 -255
.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
engine_ctrl/usi.py CHANGED
@@ -1,256 +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.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")
 
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")