ChessViz — graphs of chess games
ChessViz reads a chess game as pgn-file and generates a visual representation of the game as chart. The chart shows how the game developed, who was in front, which moves were critical, which moves were forced and different sections (like rookending) of the game are marked.
Import the chess package and open a file with games from the “London Chess Classics 2017”.
Read in a game (game number 15 in this example) and print out some metadata of the event and the game.
London Chess Classic 2017 / Carlsen, Magnus - Nepomniachtchi, Ian 0-1 / 2017.12.10
Loading the open source chess engine “Stockfish” (stockfishchess.org), which we use to evaluate the board positions of the games. The connection is done via the “Universal Chess Interface” communication protocol (http://wbec-ridderkerk.nl/html/UCIProtocol.html).
A Chess board can be represented as a string in the Forsyth–Edwards Notation (FEN) http://kirill-kryukov.com/chess/doc/fen.html. You can see an Example which represents the starting position below.
'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
For some counting operations on the board we need a little helper function, which converts FEN notation to a tensor representation of the board.
With this function we can for example count all pieces on board.
We use this function to detect sections of the game like rook- or pawn-endings.
Now we use the chess-engine and the counting functions to analyze the game. The results are stored in the dictionary “counts”.
Print out the final position of the game.
Now let us construct the data to plot the graphs. Import the plotly package and prepare some lists with color and count information. “bubble” is used to set the size the markers and it is devided by 2 to scale down the size.
“best” is the difference of the best move in a position and the second best move and is therefore a measure how critical a position is. We use it on a logarithmic scale.
We prepare lists of shapes to show the different phases of the game and if the king is in check.
And prepeare some annotations for the plot.
Generate the plot
A scatterplot for the scores with the size of the markers representing the number of possible moves in a position is plotted. The color of the markers shows how critical a position was.
The plot shows that after a good start for white black got almost a winning position, but with the beginning of the rook-ending the advantage vanished, and the game ended in a draw.
In the same way as in this article you can derive additional features of a chess game by using the engine and counts of different sorts of pieces.
The first game of the 2018 world championship.
Carlson had a winning position in the middle game but could not convert it to a win.