Skip to content

Instantly share code, notes, and snippets.

@GloriaVictis
Created December 20, 2015 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save GloriaVictis/18e069d9492f143646c7 to your computer and use it in GitHub Desktop.
Save GloriaVictis/18e069d9492f143646c7 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
from __future__ import division
from collections import Counter
import pgn
import operator
import os
from matplotlib import pyplot as plt
from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})
import numpy as np
PGN_DIR = 'pgns'
PGN_SUBDIRS = {'men', 'women'}
def calculate_draw_rates(directory):
pgn_files = os.listdir(os.path.join(PGN_DIR, directory))
draw_rates = dict()
for fname in pgn_files:
pgn_file = open(os.path.join(PGN_DIR, directory, fname), 'r')
player_name = fname.split('.')[0]
pgn_text = pgn_file.read()
pgn_file.close()
games = pgn.loads(pgn_text)
results = [game.result for game in games]
num_games = len(results)
counts = Counter(results)
num_draws = counts['1/2-1/2']
draw_rate = round(num_draws / num_games, 3)
draw_rates[player_name] = draw_rate
return draw_rates
def plot_draw_rates(draw_rates, directory):
sorted_results = sorted(draw_rates.items(), key=operator.itemgetter(1))
player_names = [item[0] for item in sorted_results]
draws = [item[1] for item in sorted_results]
average_draw_rate = np.mean(draws)
plt.bar(range(0, len(player_names)), draws)
plt.axhline(y=average_draw_rate, color='red', linewidth='4', label='Average')
plt.xticks(range(0, len(player_names)), player_names, rotation=90)
plt.title("Draw rates " + directory, size=18)
plt.xlabel("Player name", size=14)
plt.ylabel("Draw rate", size=14)
plt.grid(True)
plt.legend(loc=2)
plt.savefig("draw_rates_"+directory+".png")
plt.clf()
plt.close()
for dir_entry in PGN_SUBDIRS:
data = calculate_draw_rates(dir_entry)
plot_draw_rates(data, dir_entry)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment