from fully_mixed_games_utils import *
import matplotlib.pyplot as plt


figures_path = 'figures/'
########################################## PARAMETERS ##############################################
# Initializing true parameters of a fully mixed game
A1, A2, B1, B2, C1, C2, D1, D2 = 2, -1, -1, 1, -1, 3, 1, -1
A1_manip, A2_manip, B1_manip, B2_manip, C1_manip, C2_manip, D1_manip, D2_manip = A1, A2, B1, B2, C1, C2, D1, D2
# conditions of a fully-mixed game
assert (A1 > C1 and D1 > B1 and B2 > A2 and C2 > D2) or (A1 < C1 and D1 < B1 and B2 < A2 and C2 < D2)

# agent parameters:
eta = 0.01
A1_manip_vect = [2]
C2_manip_vect = [3]

# simulation parameters
start_count_t = 1
sample_size = 1

game = create_game(A1, A2, B1, B2, C1, C2, D1, D2)
manipulated_utilities = [A1_manip, A2, B1, B2, C1, C2_manip, D1, D2]

####################################################################################################

# measure action distribution deviations from Nash equilibrium
MAPE_vect = []
p_vect = []
q_vect = []
T_vect = [1000, 2000, 5000,10000,20000,30000,40000,50000,60000,70000,80000,90000,100000]
p1_NE = 2 / 3 * 2 / 5
p2_NE = 2 / 3 * 3 / 5
p3_NE = 1 / 3 * 2 / 5
p4_NE = 1 / 3 * 3 / 5
for T in T_vect:
    MAPE = []
    for samp in range(sample_size):
        actual_user_payoffs_by_c0, manipulated_baseline_payoffs_by_c0, \
        game_final_manipulated, agents_final_manipulated = run_simulation(eta, game, manipulated_utilities, total_time=T, start_count_t=1)

        # generic formula for the NE (as long as the game is mixed)
        q_manipulated = 1 / (1 + (np.array(A1_manip_vect) - C1) / (D1 - B1))
        p_manipulated = 1 / (1 + (A2 - B2) / (D2 - np.array(C2_manip_vect)))
        u1_manipulated_NE = p_manipulated * (q_manipulated * A1 + (1 - q_manipulated) * B1) + \
                            (1 - p_manipulated) * (q_manipulated * C1 + (1 - q_manipulated) * D1)
        u2_manipulated_NE = q_manipulated * (p_manipulated * A2 + (1 - p_manipulated) * C2) + \
                            (1 - q_manipulated) * (p_manipulated * B2 + (1 - p_manipulated) * D2)

        # action distribution
        history = game_final_manipulated.get_history()[start_count_t:]
        p1, p2, p3, p4, p, q = 0, 0, 0, 0, 0, 0
        z = 0
        for a in history:
            z += 1
            if a == [0, 0]:
                p1 += 1; p += 1; q += 1
            elif a == [0, 1]:
                p2 += 1; p += 1
            elif a == [1, 0]:
                p3 += 1; q += 1
            elif a == [1, 1]:
                p4 += 1
        p1 /= z; p2 /= z; p3 /= z; p4 /= z; p /= z; q /= z

        p1_error = np.abs(p1-p1_NE)/p1_NE
        p2_error = np.abs(p2-p2_NE)/p2_NE
        p3_error = np.abs(p3-p3_NE)/p3_NE
        p4_error = np.abs(p4-p4_NE)/p4_NE
        simulation_MAPE = np.sum([p1_NE*p1_error, p2_NE*p2_error, p3_NE*p3_error, p4_NE*p4_error])
        MAPE.append(simulation_MAPE)
        p_vect.append(p)
        q_vect.append(q)
    print('T =',T,'\tMAPE =',np.mean(MAPE))
    MAPE_vect.append(np.mean(MAPE))

plt.figure()
plt.hist(p_vect, bins=30,label='$p  \quad(\sigma = ' + "{:.4f}".format(np.std(p_vect))+', N = '+str(sample_size)+')$')
plt.hist(q_vect, bins=30, label='$q \quad(\sigma = ' + "{:.4f}".format(np.std(q_vect))+', N = '+str(sample_size)+'$)')
plt.xlabel('Mixed strategies $p$ and $q$', fontsize=13)
plt.ylabel('# Occurrences', fontsize=13)
plt.legend(fontsize=13)
plt.savefig(figures_path + 'fully_mixed_game_p_q_histogram')
plt.show()

#  plot deviations from equilibrium vs. simulation time
plt.figure()
plt.plot(T_vect, MAPE_vect, label='MAPE')
x = np.arange(1000,100000)
plt.plot(x, 2/np.sqrt(np.array(x)),':', label='$2/\sqrt{T}$')
plt.xlabel('T (game repetitions)', fontsize=13)
plt.ylabel('Mean Absolute Percentage Error (MAPE)', fontsize=13)
plt.legend(fontsize=11)
plt.savefig(figures_path + 'fully_mixed_game_MAPE_vs_T')
plt.show()

#  plot p,q histograms
plt.figure()
plt.hist(p_vect, bins=30,label='$p  \quad(\sigma = ' + "{:.4f}".format(np.std(p_vect))+', N = '+str(sample_size)+')$')
plt.hist(q_vect, bins=30, label='$q \quad(\sigma = ' + "{:.4f}".format(np.std(q_vect))+', N = '+str(sample_size)+'$)')
plt.xlabel('Mixed strategies $p$ and $q$', fontsize=13)
plt.ylabel('# Occurrences', fontsize=13)
plt.legend(fontsize=13)
plt.savefig(figures_path + 'fully_mixed_game_p_q_histogram')
plt.show()
