''' Created on Jun 21, 2016 @author: Brett Paufler (c) Copyright Brett Paufler Output for Website Presentation Scratch Pad Graphs grow ever more non-backwards compatible None type no longer effective Only saving at surrender (no interval data) ''' ######################## # # Disposable Graphs for Odds, first Section # ######################## import matplotlib.pyplot as plt import pandas as pd from collections import OrderedDict, Counter from os import listdir def convert_units_to_factors(num_units): if num_units == 0: factor = 0 else: factor = pow(0.9, num_units) * 5 * num_units #THis seems right, 90% + 90% that it's good #OTherwise it's 10% or 10% that it's bad return factor def graph_units_to_factors(): '''Outputs both bar and line graph for the Unit to Factor Converstion.''' for units in [50]: numbers = range(0, units) data = [convert_units_to_factors(num) for num in numbers] graphs = {'bar': plt.bar, 'line': plt.plot} for name, graph in graphs.items(): graph(numbers, data, color='black') plt.ylabel('Average Attack Factor') plt.xlabel('Number of Units') #\nfactor = pow(0.9, num_units) * 5 * num_units') plt.title('Unit to Factor\nExpected Conversion') plt.figsize=(10,5) plt.savefig('./output/units_to_factor_%s_graph_%d.png' % (name, units)) plt.clf() graph_units_to_factors() def graph_factor_analysis(): '''Outputs both bar and line graph for the Unit to Factor Converstion.''' numbers = range(0, 50) factors = [num * 5 for num in numbers] loss_factors = [(1 - pow(0.9, num)) * num * 5 for num in numbers] #data = [convert_units_to_factors(num) for num in numbers] #graphs = {'bar': plt.bar, 'line': plt.plot} #for name, graph in graphs.items(): plt.plot(numbers, factors, color='green') plt.bar(numbers, factors, color='black') plt.bar(numbers, loss_factors, color='red') plt.plot(numbers, loss_factors, color='yellow') plt.ylabel('Attack Factor with Ratio Zero') plt.xlabel('Number of Units') #\nfactor = pow(0.9, num_units) * 5 * num_units') plt.title('Factor Analysis') plt.figsize=(10,5) plt.savefig('./output/factor_analysis.png') plt.clf() graph_factor_analysis() ###################################### # # SQLITE3 Database Creator # ###################################### def create_data_db(csv_file_path='./data/tourney_random.txt', data_save_name='./data/tourney.db'): ''' If old database exists, must be removed manually ''' import csv import sqlite3 #Loads csv, strips header info with open(csv_file_path, 'rb') as f: csv_data = list(csv.reader(f)) csv_data = csv_data[1:] #New database is created: note schema conn = sqlite3.connect(data_save_name) c = conn.cursor() c.execute('''CREATE TABLE snapshots (game_num, turn_num, player, units, squares, attacker, defender)''') data_list = csv_data for data in data_list: data = ', '.join(data) data = data.replace('None', '99') sql_command = 'INSERT INTO snapshots VALUES (%s)' % data c.execute(sql_command) conn.commit() print '\nCreated: %s' % data_save_name #create_data_db() ############################ # # Pandas Work # PLT Graphs # ############################ #(game_num, turn_num, player, units, squares, attacker, defender)''') #import numpy as np #COLORS = ['pink', 'cyan', 'yellow', 'green'] player_colors = OrderedDict([ ('pink', (255, 192, 203)), ('cyan', (0, 255, 255)), ('yellow', (255, 255, 0)), ('green', (0, 255, 0)) ]) def graph_relative_wins(data_file): save_name = data_file[:-4] save_name = save_name.replace('data', 'output') save_name_img = save_name + '_relative_wins.png' save_name_text = save_name + '_relative_wins.txt' #Finds the current player on the last turn_num dF = pd.read_csv(data_file) #dF = dF[dF.defender != 'None'] dF = dF.groupby(dF.game_num).apply(lambda t: t[t.turn_num==t.turn_num.max()]) #Number of times each player won player_wins = dF.groupby(dF.player).size() #Output Text text = 'Game Length\nMean: %.2f\nStd Dev: %.2f\nMax: %d\nMin: %d\n\n' % ( dF.turn_num.mean(), dF.turn_num.std(), dF.turn_num.max(), dF.turn_num.min()) for i, win in enumerate(player_wins.values): text += 'Player %d Won %d\n' % (i, win) with open(save_name_text, 'w') as f: f.write(text) print text #Make Graph bar_list = plt.bar(range(1, 5), player_wins.values, align='center') for i, color in enumerate(player_colors.keys()): bar_list[i].set_color(color) plt.xticks(range(1, 5), player_colors.keys()) plt.ylabel('Number of Wins') plt.xlabel('Player') plt.title('Relative Wins') plt.figsize=(10,5) plt.savefig(save_name_img) plt.clf() #RELATIVE WINS #graph_relative_wins(data_file='./data/risk_it_random_1000_2.txt' #RANK ORDER def graph_win_place_show(file_in): save_name = file_in.replace('data', 'output') save_name_img = save_name[:-4] + '_rank_order.png' save_name_txt = save_name_img[:-3] + 'txt' #Pandas less 'None', provides knock out condition dF = pd.read_csv(file_in) #dF = dF[dF.defender != 'None'] print 'Making the aggregate list of survivors at start...winner' players_remaining = [[],[],[],[]] for n in range(dF.game_num.max() + 1): d_temp = dF[dF.game_num == n] players_knock_out_order = list(d_temp.player) #THESE SLICES ARE NOT BACKWARDS COMPATIBLE (7-5-16) #First Turn used to default to NONE for Attacker, #Based on when snapshot was taken players_remaining[0] += [1, 2, 3, 4] players_remaining[1] += players_knock_out_order[0:3] players_remaining[2] += players_knock_out_order[3:5] players_remaining[3] += players_knock_out_order[5:] #print players_knock_out_order print players_remaining for i in players_remaining: print 'Data Points: %d, data %s' % (len(i), str(i)) count_of_remaining = [Counter(i) for i in players_remaining] print 'Counter Object', count_of_remaining #Ranked Order List ranking = [[],[],[],[]] for count in count_of_remaining: for i in range(0, 4): ranking[i].append(count[i + 1]) #output text text = 'Ranked List, Players 0-4 [start, third, second, winner]\n\n' text += str(ranking) print text with open(save_name_txt, 'w') as f: f.write(text) #Make the Graph and Output for i, color in enumerate(player_colors): plt.plot(range(0, 4), ranking[i], color=color) plt.ylabel('Number of Trials') plt.title('Still in Game') plt.xticks(range(0, 4), ['Start', 'Final Three', 'Final Two', 'Winner']) plt.figsize=(10,5) plt.savefig(save_name_img) print 'Graph saved:', save_name_img plt.clf() #Win Place Show #Does somebody come in second or third more often (as well as win) #graph_win_place_show(file_in='./data/risk_it_random_1000.txt') def graph_knock_outs(file_in): '''Is the player who knocks out the first and second, the same as who wins.''' save_name = file_in.replace('data', 'output') save_name_img = save_name[:-4] + '_knock_outs.png' save_name_txt = save_name_img[:-3] + 'txt' #Pandas less 'None', provides knock out condition dF = pd.read_csv(file_in) #dF = dF[dF.defender != 'None'] print 'Three values, number times winner knocks out first, second, and then wins.' print 'Last value should alway equal number of games.' same_player = [[],[],[]] for n in range(dF.game_num.max() + 1): d_temp = dF[dF.game_num == n] attacker = list(d_temp.attacker) same_player[0].append(attacker[0] == attacker[5]) same_player[1].append(attacker[4] == attacker[5]) same_player[2].append(attacker[5] == attacker[5]) same_player = [sum(values) for values in same_player] print same_player with open(save_name_txt, 'w') as f: f.write('Successive Knock outs, first, second, winner (win=num games)\n') f.write(str(same_player)) #Make Graph plt.bar(range(0, 3), same_player, align='center') plt.xticks(range(0, 3), ['First', 'Second', 'Final']) #player_colors.keys()) plt.ylabel('Number of Times') #plt.xlabel('Player') plt.title('Successive Knock Outs by Winner') plt.figsize=(10,5) plt.savefig(save_name_img) plt.clf() #Who knocked out who, does winner knock out first and second #graph_knock_outs(file_in='./data/risk_it_random_100.txt') def graph_all_game_graphs(): dir_in = './data/' input_files = [dir_in + file_in for file_in in listdir(dir_in)] for file_in in input_files: #graph_factor_analysis() graph_knock_outs(file_in) graph_relative_wins(file_in) graph_win_place_show(file_in) print 'Graph All Finished' #graph_all_game_graphs()