-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanalyze.py
408 lines (342 loc) · 13.5 KB
/
analyze.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
import sys
import time
import traceback
from multiprocessing import Pool, cpu_count, Manager
from board import Board
from pieces import WHITE, BLACK, PIECES
from utils import color_sign
def pool_dfs_wrapper(pool_arg):
'''
Wraps dfs in try/except, multiprocessing doesn't provide actual stack trace.
'''
analyzer, args, kwargs = pool_arg
try:
return analyzer.dfs(*args, **kwargs)
except Exception:
raise Exception("".join(traceback.format_exception(*sys.exc_info())))
class Analyzer(object):
def __init__(self, max_deep, evaluation_func, lines=1):
'''
max_deep - 2*n for checkmate in `n` moves
'''
if max_deep <= 0:
raise ValueError('Max deep should be more or equal than one')
self.max_deep = max_deep
self.lines = lines
self.evaluation_func = evaluation_func
def analyze(self, board):
stats = {
'nodes': 0
}
result = self.dfs(board, stats)
return {
'result': result,
'stats': stats
}
def board_evaluation(self, board):
evaluation = self.evaluation_func(board)
return [{
'evaluation': evaluation['evaluation'],
'moves': []
}]
class SimpleAnalyzer(Analyzer):
def dfs(self, board, stats, deep=0):
stats['nodes'] += 1
if deep == self.max_deep:
return self.board_evaluation(board)
move_color = board.move_color
result = []
lines = self.lines if deep == 0 else 1
for move in board.get_board_moves():
revert_info = board.make_move(move)
if revert_info is None:
continue
cand = self.dfs(
board, stats, deep=deep + 1)
board.revert_move(revert_info)
result.append(cand[0])
result[-1]['moves'].append(move)
result.sort(
key=lambda x: x['evaluation'], reverse=(move_color==WHITE))
result = result[:lines]
sign = color_sign(move_color)
if not result:
if board.is_check(opposite=True):
# Checkmate
result = [{
'evaluation': -sign * (Board.MAX_EVALUATION - deep),
'moves': []
}]
else:
# Draw
result = [{
'evaluation': 0,
'moves': []
}]
return result
class AlphaAnalyzer(Analyzer):
def dfs(self, board, stats, alpha=None, deep=0):
'''
alpha - to reduce brute force
if alpha is None dfs will return always list not 0-length
'''
stats['nodes'] += 1
if deep == self.max_deep:
return self.board_evaluation(board)
move_color = board.move_color
result = []
lines = self.lines if deep == 0 else 1
for move in board.get_board_moves():
revert_info = board.make_move(move)
if revert_info is None:
continue
cand = self.dfs(
board, stats,
alpha=result[-1]['evaluation'] if len(result) == lines else None, deep=deep + 1)
board.revert_move(revert_info)
if cand is None:
# Not found better move
continue
result.append(cand[0])
result[-1]['moves'].append(move)
result.sort(
key=lambda x: x['evaluation'], reverse=(move_color==WHITE))
result = result[:lines]
# TODO: (kosteev) cut two deep recursion
if alpha is not None:
if (move_color == BLACK and result[0]['evaluation'] <= alpha or
move_color == WHITE and result[0]['evaluation'] >= alpha):
return None
sign = color_sign(move_color)
if not result:
if board.is_check(opposite=True):
# Checkmate
result = [{
'evaluation': -sign * (Board.MAX_EVALUATION - deep),
'moves': []
}]
else:
# Draw
result = [{
'evaluation': 0,
'moves': []
}]
return result
class AlphaBetaAnalyzer(Analyzer):
def __init__(self, *args, **kwargs):
self.max_time = kwargs.pop('max_time', 999999)
self.max_deep_captures = kwargs.pop('max_deep_captures', 0)
self.max_deep_one_capture = kwargs.pop('max_deep_one_capture', 0)
super(AlphaBetaAnalyzer, self).__init__(*args, **kwargs)
@classmethod
def pool(cls):
if not hasattr(cls, '_pool'):
cls._pool = Pool(processes=cpu_count())
return cls._pool
@classmethod
def manager(cls):
# Initialize pool
# ??? Should we do it?
cls.pool()
if not hasattr(cls, '_manager'):
cls._manager = Manager()
return cls._manager
def analyze(self, board, alpha=-Board.MAX_EVALUATION - 1, beta=Board.MAX_EVALUATION + 1,
moves_to_consider=None):
'''
If evaluation between (alpha, beta) returns it,
otherwise if less returns less or equal alpha
if more returns more or equal beta
Alpha-beta pruning
if alpha and beta not passed it will return always true evaluation
'''
result, _ = self.dfs_parallel(
board, alpha, beta, time.time(), moves_to_consider=moves_to_consider)
stats = {'nodes': 1}
return {
'result': result,
'stats': stats
}
def dfs(self, board, alpha, beta, analyze_launch_time, moves_to_consider=None,
deep=0, max_material_diff=999,
parent_alpha_beta=None, parent_ind=None):
'''
!!!! This function should be multi-thread safe.
!!!! It always returns result of non-zero length
`moves_to_consider` - moves to consider, if None than all valid moves are considered
only if deep < max_deep
deep < max_deep
- all moves
max_deep <= deep < max_deep + max_deep_captures
- captures (if check then all moves)
max_deep + max_deep_captures <= deep < max_deep + max_deep_captures + max_deep_one_capture
- one capture
'''
if time.time() - analyze_launch_time > self.max_time:
# If alpha or beta is determined here, than there is calculated one variant already
if alpha >= -Board.MAX_EVALUATION:
return [{
'evaluation': alpha, # Return evaluation that will not affect result
'moves': []
}], parent_ind
if beta <= Board.MAX_EVALUATION:
return [{
'evaluation': beta, # Return evaluation that will not affect result
'moves': []
}], parent_ind
result = []
move_color = board.move_color
sign = color_sign(move_color)
lines = self.lines if deep == 0 else 1
is_any_move = False
if deep >= self.max_deep:
if (deep < self.max_deep + self.max_deep_captures
and board.is_check(opposite=True)):
moves = board.get_board_moves(capture_sort_key=Board.sort_take_by_value)
else:
result = self.board_evaluation(board)
is_any_move = True
if len(result) == lines:
if move_color == WHITE:
alpha = max(alpha, result[-1]['evaluation'])
else:
beta = min(beta, result[-1]['evaluation'])
if (alpha >= beta or
deep == self.max_deep + self.max_deep_captures + self.max_deep_one_capture):
# No moves should be considered
moves = []
else:
moves = board.get_board_captures(capture_sort_key=Board.sort_take_by_value)
else:
moves = board.get_board_moves(
capture_sort_key=Board.sort_take_by_value) if moves_to_consider is None else moves_to_consider
for move in moves:
revert_info = board.make_move(move)
if revert_info is None:
continue
is_any_move = True
kwargs = {
'deep': deep + 1
}
if deep >= self.max_deep + self.max_deep_captures:
material_diff = 0
if move['captured_piece']:
material_diff += PIECES[move['captured_piece']]['value']
if move['new_piece'] != move['piece']:
material_diff += PIECES[move['new_piece']]['value']
if material_diff > max_material_diff:
board.revert_move(revert_info)
# Break recursion, do not consider line if opponent takes more valuable piece or
# promote something valuable or neither both of this
# Return something that will not affect result
result = [{
'evaluation': sign * (Board.MAX_EVALUATION + 1),
'moves': []
}]
break
kwargs['max_material_diff'] = material_diff
cand, _ = self.dfs(
board, alpha, beta, analyze_launch_time, **kwargs)
board.revert_move(revert_info)
result.append(cand[0])
result[-1]['moves'].append(move)
# XXX: sorting is stable, it will never get newer variant
# (which can be with wrong evaluation).
result.sort(
key=lambda x: x['evaluation'], reverse=(move_color==WHITE))
result = result[:lines]
if len(result) == lines:
if move_color == WHITE:
alpha = max(alpha, result[-1]['evaluation'])
else:
beta = min(beta, result[-1]['evaluation'])
# Refresh alpha/beta according to parent
if parent_alpha_beta is not None:
if move_color == WHITE:
beta = parent_alpha_beta.value
else:
alpha = parent_alpha_beta.value
if alpha >= beta:
break
if deep >= self.max_deep + self.max_deep_captures:
# Consider only one take/promotion
break
if not is_any_move:
if board.is_check(opposite=True):
# Checkmate
result = [{
'evaluation': -sign * (Board.MAX_EVALUATION - deep),
'moves': []
}]
else:
# Draw
result = [{
'evaluation': 0,
'moves': []
}]
return result, parent_ind
def dfs_parallel(self, board, alpha, beta, analyze_launch_time, moves_to_consider=None):
'''
!!!! It always returns result of non-zero length
`moves_to_consider` - moves to consider, if None than all valid moves are considered
'''
move_color = board.move_color
result = []
is_any_move = False
pool_args = []
moves = []
board_moves = board.get_board_moves() if moves_to_consider is None else moves_to_consider
if move_color == WHITE:
parent_alpha_beta = self.manager().Value('i', alpha)
else:
parent_alpha_beta = self.manager().Value('i', beta)
for move in board_moves:
revert_info = board.make_move(move)
if revert_info is None:
continue
is_any_move = True
args = (board.copy(), alpha, beta, analyze_launch_time)
kwargs = {
'deep': 1,
'parent_alpha_beta': parent_alpha_beta,
'parent_ind': len(moves)
}
pool_args.append((self, args, kwargs))
moves.append(move)
board.revert_move(revert_info)
for cand, ind in self.pool().imap_unordered(
pool_dfs_wrapper, pool_args):
result.append(cand[0])
result[-1]['moves'].append(moves[ind])
# XXX: sorting is stable, it will never get newer variant
# (which can be with wrong evaluation).
result.sort(
key=lambda x: x['evaluation'], reverse=(move_color==WHITE))
result = result[:self.lines]
if len(result) == self.lines:
if move_color == WHITE:
parent_alpha_beta.value = max(parent_alpha_beta.value, result[-1]['evaluation'])
else:
parent_alpha_beta.value = min(parent_alpha_beta.value, result[-1]['evaluation'])
# Here is the first time it could happen
if move_color == WHITE:
if parent_alpha_beta.value >= beta:
break
else:
if alpha >= parent_alpha_beta.value:
break
if not is_any_move:
sign = color_sign(move_color)
if board.is_check(opposite=True):
# Checkmate
result = [{
'evaluation': -sign * Board.MAX_EVALUATION,
'moves': []
}]
else:
# Draw
result = [{
'evaluation': 0,
'moves': []
}]
return result, None