-
Notifications
You must be signed in to change notification settings - Fork 4
/
chessgraph.py
686 lines (593 loc) · 19.9 KB
/
chessgraph.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
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
import requests
import pickle
import platform
import argparse
import chess
import chess.engine
import chess.svg
import math
import sys
import concurrent.futures
import multiprocessing
import hashlib
import cairosvg
import graphviz
from os.path import exists
from urllib import parse
class ChessGraph:
def __init__(
self,
networkstyle,
depth,
concurrency,
source,
lichessdb,
engine,
enginedepth,
enginemaxmoves,
boardstyle,
boardedges,
):
self.networkstyle = networkstyle
self.depth = depth
self.source = source
self.lichessdb = lichessdb
self.engine = engine
self.enginedepth = enginedepth
self.enginemaxmoves = enginemaxmoves
self.boardstyle = boardstyle
self.boardedges = boardedges
self.executorgraph = [
concurrent.futures.ThreadPoolExecutor(max_workers=concurrency)
for i in range(0, depth + 1)
]
self.executorwork = concurrent.futures.ThreadPoolExecutor(
max_workers=concurrency
)
self.visited = set()
self.session = requests.Session()
self.graph = graphviz.Digraph("ChessGraph", format="svg")
self.cache = {}
# We fix lichessbeta by giving the startpos a score of 0.35
if self.source == "lichess":
w, d, l, moves = self.lichess_api_call(
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -"
)
self.lichessbeta = (1 - 0.35) / math.log((w + d + l) / w - 1)
else:
self.lichessbeta = None
def load_cache(self):
try:
with open("chessgraph.cache.pyc", "rb") as f:
self.cache = pickle.load(f)
except:
self.cache = {}
def store_cache(self):
with open("chessgraph.cache.pyc", "wb") as f:
pickle.dump(self.cache, f)
def get_moves(self, epd):
if self.source == "chessdb":
return self.get_moves_chessdb(epd)
elif self.source == "engine":
return self.get_moves_engine(epd)
elif self.source == "lichess":
return self.get_moves_lichess(epd)
else:
assert False
def get_bestscore_and_moves(self, board):
if board.is_checkmate():
moves = []
bestscore = -30000
elif (
board.is_stalemate()
or board.is_insufficient_material()
or board.can_claim_draw()
):
moves = []
bestscore = 0
else:
moves = self.executorwork.submit(self.get_moves, board.epd()).result()
if self.source != "chessdb":
moves.sort(key=lambda item: item["score"], reverse=True)
bestscore = int(moves[0]["score"]) if moves else None
return bestscore, moves
def get_moves_engine(self, epd):
key = (epd, self.engine, self.enginedepth, self.enginemaxmoves)
if key in self.cache:
return self.cache[key]
moves = []
engine = chess.engine.SimpleEngine.popen_uci(self.engine)
board = chess.Board(epd)
info = engine.analyse(
board,
chess.engine.Limit(depth=self.enginedepth),
multipv=self.enginemaxmoves,
info=chess.engine.INFO_SCORE | chess.engine.INFO_PV,
)
engine.quit()
for i in info:
moves.append(
{
"score": i["score"].pov(board.turn).score(mate_score=30000),
"uci": chess.Move.uci(i["pv"][0]),
}
)
self.cache[key] = moves
return moves
def get_moves_chessdb(self, epd):
key = (epd, "chessdb")
if key in self.cache:
stdmoves = self.cache[key]
if len(stdmoves) > 0:
return stdmoves
api = "http://www.chessdb.cn/cdb.php"
url = api + "?action=queryall&board=" + parse.quote(epd) + "&json=1"
timeout = 3
moves = []
try:
response = self.session.get(url, timeout=timeout)
response.raise_for_status()
data = response.json()
if data["status"] == "ok":
moves = data["moves"]
elif data["status"] == "unknown":
pass
elif data["status"] == "rate limited exceeded":
sys.stderr.write("rate")
else:
sys.stderr.write(data)
except:
pass
stdmoves = []
for m in moves:
stdmoves.append({"score": m["score"], "uci": m["uci"]})
self.cache[key] = stdmoves
return stdmoves
def lichess_wdl_to_score(self, w, d, l):
total = w + d + l
if w == l:
return 0.0
if w == total:
return 10000
if l == total:
return -10000
if w > l:
return min(
10000, int(100 - 100 * self.lichessbeta * math.log(total / w - 1))
)
else:
return max(
-10000, -int(100 - 100 * self.lichessbeta * math.log(total / l - 1))
)
def lichess_api_call(self, epd):
if self.lichessdb == "masters":
specifics = "&topGames=0"
else:
specifics = (
"variant=standard"
+ "&speeds=blitz"
+ "&ratings=2000,2200,2500"
+ "&topGames=0&recentGames=0"
)
url = (
"https://explorer.lichess.ovh/{}?".format(self.lichessdb)
+ specifics
+ "&moves={}".format(self.enginemaxmoves)
+ "&fen={}".format(parse.quote(epd))
)
timeout = 3
try:
response = self.session.get(url, timeout=timeout)
response.raise_for_status()
data = response.json()
if epd.split()[1] == "w":
w, d, l = int(data["white"]), int(data["draws"]), int(data["black"])
else:
l, d, w = int(data["white"]), int(data["draws"]), int(data["black"])
moves = data["moves"]
except:
w = d = l = 0
moves = []
return (w, d, l, moves)
def get_moves_lichess(self, epd):
key = (epd, "lichess", self.enginemaxmoves, self.lichessdb)
if key in self.cache:
stdmoves = self.cache[key]
if len(stdmoves) > 0:
return stdmoves
w, d, l, moves = self.lichess_api_call(epd)
stdmoves = []
for m in moves:
if epd.split()[1] == "w":
w, d, l = int(m["white"]), int(m["draws"]), int(m["black"])
else:
l, d, w = int(m["white"]), int(m["draws"]), int(m["black"])
total = w + d + l
# A parameter that ensures we have sufficient games to get a score
lichessmingames = 10
if total > lichessmingames:
score = self.lichess_wdl_to_score(w, d, l)
stdmoves.append({"score": score, "uci": m["uci"]})
self.cache[key] = stdmoves
return stdmoves
def node_name(self, board):
if self.networkstyle == "graph":
name = "graph - " + board.epd()
elif self.networkstyle == "tree":
movelist = []
while True:
try:
move = board.pop()
movelist.append(move)
except:
break
name = board.epd() + " moves "
for move in reversed(movelist):
board.push(move)
name = name + " " + move.uci()
else:
raise ()
return name
def write_node(self, board, score, showboard, pvNode, tooltip):
epd = board.epd()
nodename = self.node_name(board)
color = "gold" if board.turn == chess.WHITE else "burlywood4"
penwidth = "3" if pvNode else "1"
epdweb = parse.quote(epd)
URL = "https://www.chessdb.cn/queryc_en/?" + epdweb
image = None
if showboard and not self.boardstyle == "none":
if self.boardstyle == "unicode":
label = board.unicode(empty_square="\u00B7")
elif self.boardstyle == "svg":
filename = (
"node-" + hashlib.sha256(epd.encode("utf-8")).hexdigest() + ".svg"
)
if not exists(filename):
cairosvg.svg2svg(
bytestring=chess.svg.board(board, size="200px").encode("utf-8"),
write_to=filename,
)
image = filename
label = ""
else:
label = (
"None"
if score is None
else str(score if board.turn == chess.WHITE else -score)
)
if image:
self.graph.node(
nodename,
label=label,
shape="box",
color=color,
penwidth=penwidth,
URL=URL,
image=image,
tooltip=tooltip,
)
else:
self.graph.node(
nodename,
label=label,
shape="box",
color=color,
penwidth=penwidth,
fontname="Courier",
URL=URL,
tooltip=tooltip,
)
def write_edge(
self, nodefrom, nodeto, sanmove, ucimove, turn, score, pvEdge, lateEdge
):
color = "gold" if turn == chess.WHITE else "burlywood4"
penwidth = "3" if pvEdge else "1"
fontname = "Helvetica-bold" if pvEdge else "Helvectica"
style = "dashed" if lateEdge else "solid"
labeltooltip = "{} ({}) : {}".format(
sanmove,
ucimove,
"None" if score is None else str(score if turn == chess.WHITE else -score),
)
tooltip = labeltooltip
self.graph.edge(
nodefrom,
nodeto,
label=sanmove,
color=color,
penwidth=penwidth,
fontname=fontname,
tooltip=tooltip,
edgetooltip=tooltip,
labeltooltip=labeltooltip,
style=style,
)
def recurse(self, board, depth, alpha, beta, pvNode, plyFromRoot):
nodenamefrom = self.node_name(board)
# terminate recursion if visited
if nodenamefrom in self.visited:
return
else:
self.visited.add(nodenamefrom)
bestscore, moves = self.get_bestscore_and_moves(board)
edgesfound = 0
edgesdrawn = 0
futures = []
turn = board.turn
tooltip = board.epd() + "
"
# loop through the (sorted) moves that are within delta of the bestmove
for m in moves:
score = int(m["score"])
if score <= alpha:
break
ucimove = m["uci"]
move = chess.Move.from_uci(ucimove)
sanmove = board.san(move)
board.push(move)
nodenameto = self.node_name(board)
edgesfound += 1
pvEdge = pvNode and score == bestscore
lateEdge = score != bestscore
# no loops, otherwise recurse
if score == bestscore:
newDepth = depth - 1
else:
newDepth = depth - int(1.5 + math.log2(edgesfound))
if newDepth >= 0:
if nodenameto not in self.visited:
futures.append(
self.executorgraph[depth].submit(
self.recurse,
board.copy(),
newDepth,
-beta,
-alpha,
pvEdge,
plyFromRoot + 1,
)
)
edgesdrawn += 1
tooltip += "{} : {}
".format(
sanmove, str(score if turn == chess.WHITE else -score)
)
self.write_edge(
nodenamefrom,
nodenameto,
sanmove,
ucimove,
turn,
score,
pvEdge,
lateEdge,
)
board.pop()
concurrent.futures.wait(futures)
remainingMoves = board.legal_moves.count() - edgesdrawn
tooltip += "{} remaining {}
".format(
remainingMoves, "move" if remainingMoves == 1 else "moves"
)
if edgesdrawn == 0:
tooltip += "terminal: {}".format(
"None"
if bestscore is None
else str(bestscore if turn == chess.WHITE else -bestscore)
)
self.write_node(
board,
bestscore,
edgesdrawn >= self.boardedges
or (pvNode and edgesdrawn == 0)
or plyFromRoot == 0,
pvNode,
tooltip,
)
def generate_graph(self, epd, alpha, beta, ralpha, rbeta, salpha, sbeta):
# set initial board
board = chess.Board(epd)
score, _ = self.get_bestscore_and_moves(board)
score = score if board.turn == chess.WHITE else -score
if ralpha is not None:
alpha = int(ralpha * score)
elif salpha is not None:
alpha = score - salpha
if rbeta is not None:
beta = int(rbeta * score)
elif sbeta is not None:
beta = score + sbeta
print("root position epd : ", epd)
print(
f"alpha : {alpha}{' (alpha > eval!)' if alpha > score else ''}"
)
print("eval : ", score)
print(
f"beta : {beta}{' (beta < eval!)' if beta < score else ''}"
)
print("depth : ", self.depth)
if board.turn == chess.WHITE:
initialAlpha, initialBeta = alpha, beta
else:
initialAlpha, initialBeta = -beta, -alpha
self.recurse(
board, self.depth, initialAlpha, initialBeta, pvNode=True, plyFromRoot=0
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description="A utility to create a graph of moves from a specified chess position.",
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--position",
type=str,
default=chess.STARTING_FEN,
help="FEN of the root position.",
)
group.add_argument(
"--san",
help='Moves in SAN notation that lead to the root position. E.g. "1. g4".',
)
groupa = parser.add_mutually_exclusive_group()
groupa.add_argument(
"--alpha",
type=int,
default=0,
help="Lower bound on the score of variations to be followed (for white).",
)
groupa.add_argument(
"--ralpha",
type=float,
help="Set ALPHA = EVAL * RALPHA , where EVAL is the eval of the root position.",
)
groupa.add_argument(
"--salpha",
type=int,
help="Set ALPHA = EVAL - SALPHA.",
)
groupb = parser.add_mutually_exclusive_group()
groupb.add_argument(
"--beta",
type=int,
default=15,
help="Lower bound on the score of variations to be followed (for black).",
)
groupb.add_argument(
"--rbeta",
type=float,
help="Set BETA = EVAL * RBETA.",
)
groupb.add_argument(
"--sbeta",
type=int,
help="Set BETA = EVAL + SBETA.",
)
parser.add_argument(
"--depth",
type=int,
default=6,
help="Maximum depth (in plies) of a followed variation.",
)
parser.add_argument(
"--concurrency",
type=int,
default=multiprocessing.cpu_count(),
help="Number of cores to use for work / requests.",
)
parser.add_argument(
"--source",
choices=["chessdb", "lichess", "engine"],
type=str,
default="chessdb",
help="Use chessdb, lichess or an engine to score and rank moves.",
)
parser.add_argument(
"--lichessdb",
choices=["masters", "lichess"],
type=str,
default="masters",
help="Which lichess database to access: masters, or lichess players.",
)
parser.add_argument(
"--engine",
type=str,
default="stockfish.exe"
if "windows" in platform.system().lower()
else "stockfish",
help="Name of the engine binary (with path as needed).",
)
parser.add_argument(
"--enginedepth",
type=int,
default=20,
help="Depth of the search used by the engine in evaluation.",
)
parser.add_argument(
"--enginemaxmoves",
type=int,
default=10,
help="Maximum number of moves (MultiPV) considered by the engine in evaluation.",
)
parser.add_argument(
"--networkstyle",
choices=["graph", "tree"],
type=str,
default="graph",
help="Selects the representation of the network as a graph (shows transpositions, compact) or a tree (simpler to follow, extended).",
)
parser.add_argument(
"--boardstyle",
choices=["unicode", "svg", "none"],
type=str,
default="unicode",
help="Which style to use to visualize a board.",
)
parser.add_argument(
"--boardedges",
type=int,
default=3,
help="Minimum number of edges needed before a board is visualized in the node.",
)
parser.add_argument(
"--output",
"-o",
type=str,
default="chess.svg",
help="Name of the output file (image in .svg format).",
)
parser.add_argument(
"--embed",
action=argparse.BooleanOptionalAction,
default=False,
help="If the individual svg boards should be embedded in the final .svg image. Unfortunately URLs are not preserved.",
)
parser.add_argument(
"--purgecache",
action=argparse.BooleanOptionalAction,
default=False,
help="Do no use, and later overwrite, the cache file stored on disk (chessgraph.cache.pyc).",
)
args = parser.parse_args()
chessgraph = ChessGraph(
networkstyle=args.networkstyle,
depth=args.depth,
concurrency=args.concurrency,
source=args.source,
lichessdb=args.lichessdb,
engine=args.engine,
enginedepth=args.enginedepth,
enginemaxmoves=args.enginemaxmoves,
boardstyle=args.boardstyle,
boardedges=args.boardedges,
)
# load previously computed nodes in a cache
if not args.purgecache:
chessgraph.load_cache()
if args.san is not None:
import chess.pgn, io
if args.san:
pgn = io.StringIO(args.san)
fen = chess.pgn.read_game(pgn).end().board().fen()
else:
fen = chess.STARTING_FEN # passing empty string to --san gives startpos
else:
fen = args.position
# generate the content of the dotfile
chessgraph.generate_graph(
fen, args.alpha, args.beta, args.ralpha, args.rbeta, args.salpha, args.sbeta
)
# store updated cache
chessgraph.store_cache()
# generate the svg image (calls graphviz under the hood)
svgpiped = chessgraph.graph.pipe()
if args.embed:
# this embeds the images of the boards generated.
# Unfortunately, does remove the URLs that link to chessdb.
# probably some smarter manipulation directly on the xml
# would also allow to shrink the image size (each board embeds pieces etc.)
cairosvg.svg2svg(
bytestring=svgpiped,
write_to=args.output,
)
else:
with open(args.output, "w", encoding="utf-8") as f:
f.write(svgpiped.decode("utf-8"))