Created
December 20, 2015 11:20
-
-
Save GloriaVictis/bc792523fc8145092c25 to your computer and use it in GitHub Desktop.
Calculation for the Chess SE question: http://chess.stackexchange.com/questions/13137/whats-the-average-piece-density
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import pgn | |
import numpy as np | |
from matplotlib import pyplot as plt | |
import sys | |
initial_piece_density = 0.5 | |
decrease_per_capture = 0.015625 | |
pgn_file = open(sys.argv[1], 'r') | |
pgn_text = pgn_file.read() | |
pgn_file.close() | |
games = pgn.loads(pgn_text) | |
results = [] | |
for game in games: | |
halfmoves = game.moves | |
densities = [0] * (len(halfmoves) + 1) | |
densities[0] = initial_piece_density | |
for index, halfmove in enumerate(halfmoves): | |
if 'x' in halfmove: | |
densities[index+1] = densities[index] - decrease_per_capture | |
else: | |
densities[index+1] = densities[index] | |
results.append(densities) | |
density_values_at_each_halfmove = dict() | |
for dens in results: | |
for indx, value in enumerate(dens): | |
if indx+1 in density_values_at_each_halfmove.keys(): | |
density_values_at_each_halfmove[indx+1].append(value) | |
else: | |
density_values_at_each_halfmove[indx+1] = [value] | |
average_densities = [round(np.mean(dens),5) for dens in density_values_at_each_halfmove.values()] | |
plt.plot(range(1, len(average_densities)+1), average_densities) | |
plt.title("Average piece densities by halfmove", size=18) | |
plt.xlabel("Halfmove", size=14) | |
plt.ylabel("Piece density", size=14) | |
plt.grid(True) | |
plt.savefig("piece_densities2.png") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment