|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +def graph(pgn, engine, location): |
| 4 | + import chess.pgn |
| 5 | + print('Loading everything...') |
| 6 | + |
| 7 | + # for i in range(1, 3): |
| 8 | + act_game = chess.pgn.read_game(open(pgn)) |
| 9 | + |
| 10 | + headers = chess.pgn.read_headers(open(pgn)) |
| 11 | + |
| 12 | + print('Analyzing this game_in_question: ' + headers["Event"] + " | " + headers["White"] + |
| 13 | + " - " + headers["Black"] + " " + headers["Result"] + |
| 14 | + " | " + headers["Date"]) |
| 15 | + |
| 16 | + # import chess.engine |
| 17 | + # |
| 18 | + # engine = chess.engine.SimpleEngine.popen_uci("C:/Users/iitda/Chess_analysis/stockfish_9_x64.exe") |
| 19 | + |
| 20 | + import chess.engine |
| 21 | + |
| 22 | + engine = chess.engine.SimpleEngine.popen_uci(engine) |
| 23 | + |
| 24 | + board = act_game.board() |
| 25 | + board.fen() |
| 26 | + |
| 27 | + import numpy as np |
| 28 | + |
| 29 | + print('Making functions...') |
| 30 | + |
| 31 | + def fentotensor(inputstr): |
| 32 | + pieces_str = "PNBRQK" |
| 33 | + pieces_str += pieces_str.lower() |
| 34 | + pieces = set(pieces_str) |
| 35 | + valid_spaces = set(range(1, 9)) |
| 36 | + pieces_dict = {pieces_str[0]: 1, pieces_str[1]: 2, pieces_str[2]: 3, pieces_str[3]: 4, |
| 37 | + pieces_str[4]: 5, pieces_str[5]: 6, |
| 38 | + pieces_str[6]: -1, pieces_str[7]: -2, pieces_str[8]: -3, pieces_str[9]: -4, |
| 39 | + pieces_str[10]: -5, pieces_str[11]: -6} |
| 40 | + |
| 41 | + boardtensor = np.zeros((8, 8, 6)) |
| 42 | + |
| 43 | + inputliste = inputstr.split() |
| 44 | + rownr = 0 |
| 45 | + colnr = 0 |
| 46 | + for i, c in enumerate(inputliste[0]): |
| 47 | + if c in pieces: |
| 48 | + boardtensor[rownr, colnr, np.abs(pieces_dict[c]) - 1] = np.sign(pieces_dict[c]) |
| 49 | + colnr = colnr + 1 |
| 50 | + elif c == '/': # new row |
| 51 | + rownr = rownr + 1 |
| 52 | + colnr = 0 |
| 53 | + elif int(c) in valid_spaces: |
| 54 | + colnr = colnr + int(c) |
| 55 | + else: |
| 56 | + raise ValueError("invalid fenstr at index: {} char: {}".format(i, c)) |
| 57 | + |
| 58 | + return boardtensor |
| 59 | + |
| 60 | + def countpieces(fen): |
| 61 | + boardtensor = fentotensor(fen) |
| 62 | + count = np.sum(np.abs(boardtensor)) |
| 63 | + return count |
| 64 | + |
| 65 | + # print(countpieces(board.fen())) |
| 66 | + countpieces(board.fen()) |
| 67 | + |
| 68 | + # print(fentotensor(board.fen())) |
| 69 | + |
| 70 | + def pawnending(fen): |
| 71 | + boardtensor = fentotensor(fen) |
| 72 | + counts_1 = np.sum(np.abs(boardtensor), axis=(0, 1)) |
| 73 | + if counts_1[1] == 0 and counts_1[2] == 0 and counts_1[3] == 0 and counts_1[4] == 0: |
| 74 | + return True |
| 75 | + else: |
| 76 | + return False |
| 77 | + |
| 78 | + def rookending(fen): |
| 79 | + boardtensor = fentotensor(fen) |
| 80 | + counts_2 = np.sum(np.abs(boardtensor), axis=(0, 1)) |
| 81 | + if counts_2[1] == 0 and counts_2[2] == 0 and counts_2[4] == 0 and counts_2[3] > 0: |
| 82 | + return True |
| 83 | + else: |
| 84 | + return False |
| 85 | + |
| 86 | + # Register a standard info handler. |
| 87 | + # info_handler = chess.uci.InfoHandler() |
| 88 | + # engine.info_handlers.append(info_handler) |
| 89 | + |
| 90 | + counts = {"movecount": [], "scores": [], "check": [], "bestdiff": [], "pawnending": [], "rookending": []} |
| 91 | + |
| 92 | + # Iterate through all moves and play them on a board. |
| 93 | + board = act_game.board() |
| 94 | + |
| 95 | + print('Analyzing game_in_question...') |
| 96 | + |
| 97 | + for move in act_game.mainline_moves(): |
| 98 | + board.push(move) |
| 99 | + cnt = len([i for i in board.legal_moves]) |
| 100 | + counts["movecount"].append(cnt) |
| 101 | + counts["check"].append(board.is_check()) |
| 102 | + counts["pawnending"].append(pawnending(board.fen())) |
| 103 | + counts["rookending"].append(rookending(board.fen())) |
| 104 | + |
| 105 | + # Start a search. |
| 106 | + info = engine.analyse(board, chess.engine.Limit(time=0.1)) |
| 107 | + if board.turn == chess.WHITE: |
| 108 | + counts["scores"].append(int(str(info["score"].white().score(mate_score=10000))) / 100) |
| 109 | + else: |
| 110 | + counts["scores"].append(int(str(info["score"].white().score(mate_score=10000))) / 100) |
| 111 | + nextmovescores = [] |
| 112 | + |
| 113 | + for mov in board.legal_moves: |
| 114 | + board.push(mov) |
| 115 | + info = engine.analyse(board, chess.engine.Limit(time=0.02)) |
| 116 | + if board.turn == chess.WHITE: |
| 117 | + if str(info["score"].white().score(mate_score=10000)) is not None: |
| 118 | + try: |
| 119 | + nextmovescores.append(int(str(info["score"].white().score(mate_score=10000)))) |
| 120 | + except: |
| 121 | + nextmovescores.append(+99) |
| 122 | + elif board.turn == chess.BLACK: |
| 123 | + if str(info["score"].white().score(mate_score=10000)) is not None: |
| 124 | + try: |
| 125 | + nextmovescores.append(int(str(info["score"].white().score(mate_score=10000)))) |
| 126 | + except: |
| 127 | + nextmovescores.append(-99) |
| 128 | + board.pop() |
| 129 | + |
| 130 | + if len(nextmovescores) > 1: |
| 131 | + nextmovescores.sort(reverse=True) |
| 132 | + counts["bestdiff"].append(nextmovescores[0] - nextmovescores[1]) |
| 133 | + else: |
| 134 | + counts["bestdiff"].append(0) |
| 135 | + |
| 136 | + engine.quit() |
| 137 | + |
| 138 | + import plotly |
| 139 | + import plotly.graph_objs as go |
| 140 | + |
| 141 | + print('Creating graph...') |
| 142 | + |
| 143 | + # username = 'iitdanand' # Replace with YOUR USERNAME |
| 144 | + # api_key = 'SxRczLKT7c4RV4QStrMu' # Replace with YOUR API KEY |
| 145 | + |
| 146 | + # auth = HTTPBasicAuth(username, api_key) |
| 147 | + |
| 148 | + # py.sign_in('iitdanand', 'SxRczLKT7c4RV4QStrMu') |
| 149 | + |
| 150 | + # py.sign_in('PythonAPI', 'SxRczLKT7c4RV4QStrMu') |
| 151 | + |
| 152 | + checkcolor = ['red' if i else 'white' for i in counts["check"]] |
| 153 | + checknr = [i for (i, s) in enumerate(counts["check"]) if s] |
| 154 | + bubble = [s / 2 for s in counts["movecount"]] |
| 155 | + best = [np.log(s + 1) for s in counts["bestdiff"]] |
| 156 | + |
| 157 | + rookcolor = ['blue' if i else 'white' for i in counts["rookending"]] |
| 158 | + pawncolor = ['green' if i else 'white' for i in counts["pawnending"]] |
| 159 | + |
| 160 | + shapes = [] |
| 161 | + lists = [checkcolor, rookcolor, pawncolor] |
| 162 | + for (i, list_num) in enumerate(lists): |
| 163 | + shapes = shapes + [ |
| 164 | + dict( |
| 165 | + type='rect', |
| 166 | + # x-reference is assigned to the x-values |
| 167 | + xref='x', |
| 168 | + # y-reference is assigned to the plot paper [0,1] |
| 169 | + yref='paper', |
| 170 | + x0=i, |
| 171 | + y0=0, |
| 172 | + x1=i + 1, |
| 173 | + y1=1, |
| 174 | + fillcolor=s, |
| 175 | + opacity=0.2, |
| 176 | + line=dict( |
| 177 | + width=0, |
| 178 | + ) |
| 179 | + ) |
| 180 | + for (i, s) in enumerate(list_num)] |
| 181 | + |
| 182 | + annotations = [dict( |
| 183 | + xref='x', |
| 184 | + yref='paper', |
| 185 | + x=s, |
| 186 | + y=(0.05 + i * 0.2) % 1, |
| 187 | + text='Check!', |
| 188 | + opacity=0.8, |
| 189 | + xanchor='left', |
| 190 | + showarrow=False, |
| 191 | + ax=20, |
| 192 | + ay=-30, |
| 193 | + font=dict( |
| 194 | + family='Courier New, monospace', |
| 195 | + size=16, |
| 196 | + color='red' |
| 197 | + ), |
| 198 | + ) |
| 199 | + for (i, s) in enumerate(checknr)] |
| 200 | + |
| 201 | + # print(counts_1["scores"]) |
| 202 | + |
| 203 | + trace1 = go.Scatter( |
| 204 | + mode='markers+lines', |
| 205 | + y=counts["scores"], |
| 206 | + name='Scores', |
| 207 | + |
| 208 | + line=dict( |
| 209 | + color='black', |
| 210 | + width=4, |
| 211 | + ), |
| 212 | + marker=dict( |
| 213 | + size=bubble, |
| 214 | + line=dict(color='rgb(231, 99, 250)', width=1), |
| 215 | + cmax=max(best), |
| 216 | + cmin=min(best), |
| 217 | + color=best, |
| 218 | + colorbar=dict(title='Criticality'), |
| 219 | + colorscale='Jet' |
| 220 | + ) |
| 221 | + ) |
| 222 | + |
| 223 | + data = [trace1] |
| 224 | + |
| 225 | + ht = headers["Event"] + " || " + headers["White"] + " - " + headers["Black"] + " " + \ |
| 226 | + headers["Result"] + " || " + headers["Date"] |
| 227 | + |
| 228 | + layout = dict(title=ht, |
| 229 | + xaxis=dict(title='Half Move'), |
| 230 | + yaxis=dict(title='Score'), |
| 231 | + shapes=shapes, |
| 232 | + annotations=annotations |
| 233 | + ) |
| 234 | + |
| 235 | + fig = { |
| 236 | + 'data': data, |
| 237 | + 'layout': layout, |
| 238 | + } |
| 239 | + |
| 240 | + # plotly.plot(fig, filename='chessviz{}'.format('New2'), kind=) |
| 241 | + plotly.offline.plot(fig, filename=location.format(headers["White"] + ' vs ' + headers["Black"])) |
0 commit comments