-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvaluators.py
More file actions
597 lines (479 loc) · 18.3 KB
/
Copy pathvaluators.py
File metadata and controls
597 lines (479 loc) · 18.3 KB
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
import chess
import time
from tqdm import tqdm
import numpy as np
from chess.polyglot import zobrist_hash
from neural_valuator import NeuralValuator
valueTable = (
dict()
) # INFO if too much memory is used this can be done inside count material, but not resettng every time migth be good
materialValues = {
chess.PAWN: 100,
chess.BISHOP: 333,
chess.KNIGHT: 305,
chess.ROOK: 563,
chess.QUEEN: 950,
chess.KING: 9999,
}
# knigths on the rim are dim, this is 50% slower than using just the number
# fmt: off
pieceSquare = {
chess.PAWN:
[
1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00,
1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00,
1.00, 1.05, 1.10, 1.15, 1.15, 0.90, 1.00, 1.00,
1.00, 1.00, 1.20, 1.40, 1.40, 0.90, 1.00, 1.00,
1.00, 1.00, 1.20, 1.40, 1.40, 0.90, 1.00, 1.00,
1.00, 1.05, 1.10, 1.15, 1.15, 0.90, 1.00, 1.00,
1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00,
1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00,
],
chess.BISHOP: 64 * [3.33],
chess.KNIGHT:
[
2.29, 2.44, 2.5925, 2.5925, 2.5925, 2.5925, 2.44, 2.29,
2.44, 2.745, 3.05, 3.05, 3.05, 3.05, 2.745, 2.44,
2.5925, 3.05, 3.2025, 3.355, 3.355, 3.2025, 3.05, 2.5925,
2.5925, 3.2025, 3.355, 3.66, 3.66, 3.355, 3.2025, 2.5925,
2.5925, 3.2025, 3.355, 3.66, 3.66, 3.355, 3.2025, 2.5925,
2.5925, 3.05, 3.2025, 3.355, 3.355, 3.2025, 3.05, 2.5925,
2.44, 2.745, 3.05, 3.2025, 3.2025, 3.05, 2.745, 2.44,
2.29, 2.44, 2.5925, 2.5925, 2.5925, 2.5925, 2.44, 2.29
],
chess.ROOK: 64 * [5.63],
chess.QUEEN: 64 * [9.5],
chess.KING:
[
200, 201, 200, 200, 200, 200, 201, 200,
200, 200, 200, 200, 200, 200, 200, 200,
200, 200, 200, 200, 200, 200, 200, 200,
200, 200, 200, 200, 200, 200, 200, 200,
200, 200, 200, 200, 200, 200, 200, 200,
200, 200, 200, 200, 200, 200, 200, 200,
200, 200, 200, 200, 200, 200, 200, 200,
200, 201, 200, 200, 200, 200, 201, 200
]}
# castling rigths usually are evaluated as one pawn in early game
# fmt: on
def countMaterial(board):
# count material for each side using simple piece value
simpleMaterialValues = {
chess.PAWN: 1,
chess.BISHOP: 3,
chess.KNIGHT: 3,
chess.ROOK: 5,
chess.QUEEN: 9,
chess.KING: 200,
}
Bvalue, Wvalue = 0, 0
for piece in simpleMaterialValues:
for pos in board.pieces(piece, chess.BLACK):
Bvalue += simpleMaterialValues[piece]
for pos in board.pieces(piece, chess.WHITE):
Wvalue += simpleMaterialValues[piece]
return Wvalue - Bvalue
def heuristicValue(board):
# hand coded evaluation using features and domain knowledge
# Using modern valuations for pieces
# TODO: piece square table reversible
Bvalue, Wvalue, materialValue = 0, 0, 0
if board.is_stalemate() or board.is_insufficient_material():
return 0
else:
for piece in materialValues.keys():
# Bvalue += sum(map(lambda x,y:x*y, board.pieces(piece, chess.BLACK).tolist(), pieceSquare[piece] ))
# Wvalue += sum(map(lambda x,y:x*y, board.pieces(piece, chess.WHITE).tolist(), pieceSquare[piece] ))
# Bvalue += board.pieces(piece, chess.BLACK).tolist().count(True)* materialValues[piece]
# Wvalue += board.pieces(piece, chess.WHITE).tolist().count(True)* materialValues[piece]
# Bvalue += np.sum(np.multiply(board.pieces(piece, chess.BLACK).tolist(), pieceSquare[piece]))
# Wvalue += np.sum(np.multiply(board.pieces(piece, chess.WHITE).tolist(), pieceSquare[piece]))
# this is faster than combinations above
for i, pos in enumerate(board.pieces(piece, chess.BLACK).tolist()):
if pos:
Bvalue += pieceSquare[piece][i]
for i, pos in enumerate(board.pieces(piece, chess.WHITE).tolist()):
if pos:
Wvalue += pieceSquare[piece][i]
# TODO: compute values for past, conected, isoleted pawns
# https://es.wikipedia.org/wiki/Valor_relativo_de_las_piezas_de_ajedrez
# we compute the real advantage, pieces are more valuble when there is less pieces
materialValue = Wvalue - Bvalue
# using pseudolegal instead of leag because is 30% faster and gives a ok result for this
if board.turn == chess.WHITE:
WMvalue = len(list(board.pseudo_legal_moves))
board.turn = chess.BLACK
BMvalue = len(list(board.pseudo_legal_moves))
board.turn = chess.WHITE
else:
BMvalue = len(list(board.pseudo_legal_moves))
board.turn = chess.WHITE
WMvalue = len(list(board.pseudo_legal_moves))
board.turn = chess.BLACK
movilityValue = WMvalue - BMvalue
# print(f"Material Val: {materialValue} Movility Val: {max(Wvalue, Bvalue) * movilityValue}")
return materialValue + ((max(Wvalue, Bvalue) - 200) * movilityValue) / 20000
def simpleHeuristicValue(board):
# very simple heuristic
# Using modern valuations for pieces
Bvalue, Wvalue = 0, 0
for piece in materialValues:
for pos in board.pieces(piece, chess.BLACK):
Bvalue += materialValues[piece]
for pos in board.pieces(piece, chess.WHITE):
Wvalue += materialValues[piece]
return Wvalue - Bvalue
def makeMove(board):
global valueTable
global posEvaluated
global hashedPos
maxDepth = 9
maxTime = 5 # seconds
sTime = time.perf_counter()
posEvaluated, hashedPos = 0, 0
moveValues = []
for depth in range(maxDepth):
print(f"\u001b[36m-Evaluating at depth: {depth}\u001b[0m ")
moveValues = []
for i, move in enumerate(
tqdm(board.legal_moves, total=len(list(board.legal_moves)))
):
moveValues.append(moveValue(board, move, depth=depth))
print(f"Evaluated {len(valueTable)} pos | Hashed {hashedPos} pos")
if depth > 0:
print(f" ↖ Percentage: {100*hashedPos/(len(valueTable)):.2f}% ↗")
print(f"Time spent: {time.perf_counter()-sTime:.2f}s")
if (time.perf_counter() - sTime) > maxTime:
break
if board.turn == chess.WHITE:
idxMove = np.argmax(moveValues)
else:
idxMove = np.argmin(moveValues)
nextMove = list(board.legal_moves)[idxMove]
print("\nMove: Value")
for val, move in zip(moveValues, board.legal_moves):
print(f"{move}:{val:+6.2f}")
return nextMove, moveValues[idxMove]
def moveValue(board, move, depth=0):
# gives the value for a move in the given board using some evaluation
board.push(move)
value = PVSdeep(board, depth=depth)
board.pop()
return value
def quiesce(board, alpha=-np.inf, beta=np.inf, color=1):
if (
board.is_stalemate()
or board.is_insufficient_material()
or board.is_fifty_moves()
):
return 0
standPat = color * heuristicValue(board)
if standPat >= beta:
return beta
if alpha < standPat:
alpha = standPat
for (
move
) in board.legal_moves: # TODO order moves using heuristic or iterative deepening
if board.is_capture(move):
board.push(move)
value = -quiesce(board, alpha=-beta, beta=-alpha, color=-color)
board.pop()
if value >= beta:
return beta
if value > alpha:
alpha = value
return alpha
def PVSdeep(board, depth=0, alpha=-np.inf, beta=np.inf, color=1, boardHash=None):
# Negamax with alpha beta pruning, memoization and iterative deepening
if not boardHash:
boardHash = zobrist_hash(board)
global hashedPos
alphaOrig = alpha
if boardHash in valueTable: # Sepuede poner las dos cosas en la misma linea?
if valueTable[boardHash]["depth"] >= depth:
hashedPos += 1
if valueTable[boardHash]["flag"] == 0: # 0: EXACT
return valueTable[boardHash]["value"]
elif valueTable[boardHash]["flag"] == -1: # -1: LOWERBOUND
alpha = max(alpha, valueTable[boardHash]["value"])
elif valueTable[boardHash]["flag"] == 1: # 1: UPPERBOUND
beta = min(beta, valueTable[boardHash]["value"])
if alpha >= beta:
return valueTable[boardHash]["value"]
if (
board.is_stalemate()
or board.is_insufficient_material()
or board.is_fifty_moves()
):
value = 0
valueTable[boardHash] = {"depth": depth, "value": value, "flag": 0}
return value
elif depth == 0:
value = -quiesce(board, alpha=-beta, beta=-alpha, color=-color)
return value
value = -np.inf
orderedMoves = {}
hashDict = {}
for move in board.legal_moves: # order moves
board.push(move)
moveHash = zobrist_hash(board)
if moveHash in valueTable:
orderedMoves[move] = valueTable[moveHash]["value"]
else:
orderedMoves[move] = 9999 # todo this migth not be a good default value
# TODO should thos be multiplied by *color??
hashDict[move] = moveHash
board.pop()
firstNode = True
for move in sorted(orderedMoves, key=orderedMoves.get):
if firstNode:
board.push(move)
value = -PVSdeep(
board,
depth - 1,
alpha=-beta,
beta=-alpha,
color=-color,
boardHash=hashDict[move],
)
board.pop()
firstNode = False
else:
board.push(move)
value = -PVSdeep(
board,
depth - 1,
alpha=-alpha - 1,
beta=-alpha,
color=-color,
boardHash=hashDict[move],
)
board.pop()
if alpha < value < beta:
board.push(move)
value = -PVSdeep(
board,
depth - 1,
alpha=-beta,
beta=-alpha,
color=-color,
boardHash=hashDict[move],
)
board.pop()
alpha = max(alpha, value)
if alpha >= beta:
break
if value <= alphaOrig:
valueTable[boardHash] = {
"depth": alpha,
"value": value,
"flag": 1,
} # 1: UPPERBOUND
elif value >= beta:
valueTable[boardHash] = {
"depth": alpha,
"value": value,
"flag": -1,
} # -1: LOWERBOUND
else:
valueTable[boardHash] = {"depth": alpha, "value": value, "flag": 0} # 0: EXACT
return value
def negamaxABdeep(board, depth=0, alpha=-np.inf, beta=np.inf, color=1, boardHash=None):
# Negamax with alpha beta pruning, memoization and iterative deepening
# TODO: this is slooow now is hashingdict working correctly?
if not boardHash:
boardHash = zobrist_hash(board)
global hashedPos
alphaOrig = alpha
if boardHash in valueTable: # Sepuede poner las dos cosas en la misma linea?
if valueTable[boardHash]["depth"] >= depth:
hashedPos += 1
if valueTable[boardHash]["flag"] == 0: # 0: EXACT
return valueTable[boardHash]["value"]
elif valueTable[boardHash]["flag"] == -1: # -1: LOWERBOUND
alpha = max(alpha, valueTable[boardHash]["value"])
elif valueTable[boardHash]["flag"] == 1: # 1: UPPERBOUND
beta = min(beta, valueTable[boardHash]["value"])
if alpha >= beta:
return valueTable[boardHash]["value"]
if (
board.is_stalemate()
or board.is_insufficient_material()
or board.is_fifty_moves()
):
value = 0
valueTable[boardHash] = {"depth": depth, "value": value, "flag": 0}
return value
elif depth == 0:
value = color * heuristicValue(board)
valueTable[boardHash] = {"depth": depth, "value": value, "flag": 0}
return value
value = -np.inf
orderedMoves = {}
hashDict = {}
for move in board.legal_moves: # order moves
board.push(move)
moveHash = zobrist_hash(board)
if moveHash in valueTable:
orderedMoves[move] = valueTable[moveHash]["value"]
else:
orderedMoves[move] = -9999 # todo this migth not be a good default value
# TODO should thos be multiplied by *color??
hashDict[move] = moveHash * color
board.pop()
for move in sorted(orderedMoves, key=orderedMoves.get):
# for move in orderedMove1s:
board.push(move)
value = max(
value,
-negamaxABdeep(
board,
depth - 1,
alpha=-beta,
beta=-alpha,
color=-color,
boardHash=hashDict[move],
),
)
board.pop()
alpha = max(alpha, value)
if alpha >= beta:
break
if value <= alphaOrig:
valueTable[boardHash] = {
"depth": alpha,
"value": value,
"flag": 1,
} # 1: UPPERBOUND
elif value >= beta:
valueTable[boardHash] = {
"depth": alpha,
"value": value,
"flag": -1,
} # -1: LOWERBOUND
else:
valueTable[boardHash] = {"depth": alpha, "value": value, "flag": 0} # 0: EXACT
return value
def negamaxAB(board, depth=0, alpha=-np.inf, beta=np.inf, color=1):
boardHash = zobrist_hash(board)
global hashedPos
alphaOrig = alpha
if boardHash in valueTable: # Sepuede poner las dos cosas en la misma linea?
if valueTable[boardHash]["depth"] >= depth:
hashedPos += 1
if valueTable[boardHash]["flag"] == 0: # 0: EXACT
return valueTable[boardHash]["value"]
elif valueTable[boardHash]["flag"] == -1: # -1: LOWERBOUND
alpha = max(alpha, valueTable[boardHash]["value"])
elif valueTable[boardHash]["flag"] == 1: # 1: UPPERBOUND
beta = min(beta, valueTable[boardHash]["value"])
if alpha >= beta:
return valueTable[boardHash]["value"]
if (
board.is_stalemate()
or board.is_insufficient_material()
or board.is_fifty_moves()
):
value = 0
valueTable[boardHash] = {"depth": depth, "value": value, "flag": 0}
return value
elif depth == 0:
value = color * heuristicValue(board)
valueTable[boardHash] = {"depth": depth, "value": value, "flag": 0}
return value
value = -np.inf
for (
move
) in board.legal_moves: # TODO order moves using heuristic or iterative deepening
board.push(move)
value = max(
value,
-negamaxAB(
board,
depth - 1,
alpha=-beta,
beta=-alpha,
color=-color,
),
)
board.pop()
alpha = max(alpha, value)
if alpha >= beta:
break
if value <= alphaOrig:
valueTable[boardHash] = {
"depth": alpha,
"value": value,
"flag": 1,
} # 1: UPPERBOUND
elif value >= beta:
valueTable[boardHash] = {
"depth": alpha,
"value": value,
"flag": -1,
} # -1: LOWERBOUND
else:
valueTable[boardHash] = {"depth": alpha, "value": value, "flag": 0} # 0: EXACT
return value
def negamaxHash(board, depth=0, maxDepth=0, color=1):
# Negamax using zoobrist hash
boardHash = zobrist_hash(board)
global hashedPos
if boardHash in valueTable:
if valueTable[boardHash]["depth"] >= depth:
hashedPos += 1
return valueTable[boardHash]["value"]
if (
board.is_stalemate()
or board.is_insufficient_material()
or board.is_fifty_moves()
):
value = 0
valueTable[boardHash] = {"depth": depth, "value": value}
return value
elif depth == 0:
value = color * simpleHeuristicValue(board)
valueTable[boardHash] = {"depth": depth, "value": value}
return value
value = -np.inf
for move in board.legal_moves:
board.push(move)
value = max(
value, -negamaxHash(board, depth - 1, maxDepth=maxDepth, color=-color)
)
board.pop()
valueTable[boardHash] = {"depth": depth, "value": value}
return value
def negamax(board, depth=0, maxDepth=0, color=1):
# simple negamax zoobrist hash is not used, just computed so times are compararble
boardHash = zobrist_hash(board)
global hashedPos
if (
board.is_stalemate()
or board.is_insufficient_material()
or board.is_fifty_moves()
):
value = 0
valueTable[boardHash] = {"depth": depth, "value": value}
return value
elif depth == 0:
value = color * simpleHeuristicValue(board)
valueTable[boardHash] = {"depth": depth, "value": value}
return value
value = -np.inf
for move in board.legal_moves:
board.push(move)
value = max(value, -negamax(board, depth - 1, maxDepth=maxDepth, color=-color))
board.pop()
valueTable[boardHash] = {"depth": depth, "value": value}
return value
def initNeuralValuator():
# TODO This is an ugly way of doing this
global neuralValuator
neuralValuator = NeuralValuator()
if __name__ == "__main__":
# this is a test
board = chess.Board()
neuralValuator = NeuralValuator()
print(neuralValuator.NeuralValue(board))