# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: keras
#     language: python
#     name: keras
# ---

# # Instructions

# +
#
# BEFORE RUNNING
#
# Preprocess data in a terminal from this directory using
#
# $ python ./process-data.py
#
# Note: This script may take several hours on a modern computing device.
#
# -

# # Imports

# +
# %matplotlib inline

import pandas as pd
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

import sys
sys.path.append("../")

import game_utils

# -

# # Performance by Group Size

# ## Config

data_dir = '../../data/experiment3/'

# ## Load Data

# +
games = []
games += game_utils.get_games(data_dir, 'experiment')

data = game_utils.get_data(data_dir, games)

#
# only one game had six players
#
data = data[data['active_n_players'] < 6]

data.rename(columns={'difficulty': 'Noise Level'}, inplace=True)
data["Noise Level"].replace({'1en01':'Low', '2en01':'High'}, inplace=True)

# -

with pd.option_context('display.max_rows', None):
    print(data.groupby('game')['score'].mean())

data.groupby(['active_n_players','Noise Level'])['score'].count()/data.groupby(['active_n_players','Noise Level'])['active_n_players'].mean()

data[data['active_n_players'] == 5].groupby('game')['score'].mean()

len(set(data[(data['active_n_players'] == 5) & (data['Noise Level'] == 'Low')]['game']))

np.mean(data['Noise Level'] == 'High')

# ## Plot Performance

# +

sns.set(font = "serif", context = "poster", style = "white")
sns.despine()       

sns.factorplot("active_n_players", "second_half_score", hue = "Noise Level", markers = ["o", "s"], linestyles = ["-","--"], data = data, kind="point", dodge = 0.15, units = "game", order = [1,2,3,4,5,6])

plt.xlabel('Number of Players')
plt.ylabel('Mean Score')

plt.savefig('../../plots/performance-summary.pdf')
    
# -

# # State Analysis

# ## Plot State Frequency by Score

def state_analysis(score, states, subset, group_size):
    sns.set(font = "serif", context = "poster", style = "white")

    fig, ax = plt.subplots()
    #plt.rcParams.update(pd.tools.plotting.mpl_stylesheet)                                                                                                                   
    #ax.set_color_cycle(['b', 'g', 'y'])                                                                                                                                     
    #mpl.rc('font',family='Times New Roman')

    from seaborn import color_palette

    with color_palette("colorblind"):
        for s in states:
            plt.plot(score,states[s],label = s, lw = 10)
    #mpl.rc('font',family='Times New Roman')
    plt.xlabel('Score', fontsize=50)
    plt.ylabel('Probability', fontsize=50)
    if subset == '1en01':
        noise_level = "Low"
    elif subset == '2en01':
        noise_level = "High"
    plt.title('Noise Level: ' + noise_level + ', Group Size: ' + str(group_size), fontsize = 30)
    plt.xlim((0,1))
    plt.ylim((0,1))
    plt.legend(loc='upper left')
    plt.setp(plt.gca().get_legend().get_texts(), fontsize='40')
    ax.tick_params(axis='x', labelsize=40)
    ax.tick_params(axis='y', labelsize=40)


    fig = plt.gcf()
    fig.set_size_inches(12.5,12.5)
    fig.savefig('../../plots/states-'+subset+'-'+str(group_size)+'.pdf')#,dpi=100)   


# ## Low Noise

in_dir = '../../processed/'
state_df = []
for subset in ['1en01','2en01']:
    for n in range(2,6):
        score, states = game_utils.get_state_scores(in_dir, subset, n)
        for i in range(len(score)):
            for s in ['exploring', 'exploiting', 'copying']:
                state_df += [[subset, n, s, score[i], states[s][i]]]

state_df = pd.DataFrame(state_df)
state_df.columns = ['Noise Level', 'Num Players', 'State', 'Score', 'Proportion']

# +
#sns.set(font = "serif", context = "poster", style = "white")
sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 0.1})

sns.factorplot('Score', 'Proportion', hue = 'Noise Level', col = 'State', row = 'Num Players', kind = 'point', data = state_df)
# -

in_dir = '../../processed/'
subset = '1en01'

for n in range(2,6):
    score, states = game_utils.get_state_scores(in_dir, subset, n)
    state_analysis(score, states, subset, n)



# ## High Noise

in_dir = '../../processed/'
subset = '2en01'

score, states = game_utils.get_state_scores(in_dir, subset)

state_analysis(score, states, subset)



StarcoderdataJupyterScriptsDedupFiltered