===== CELL 0 (code) =====
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import scipy.stats as stats

===== CELL 1 (code) =====
def expectation_theta(m, alpha, p_0):
    """
    First moment of the performative estimator for given alpha, m, p_0
    """
    if alpha <=0:
        return p_0 * (1 + alpha) / (1 - 2 * alpha)
    
    if alpha >= 0.5:
        return 0.5 - stats.binom.cdf(m / 2, m, p_0 + 0.5)
    
    if alpha < 0.5 and alpha > 0:
        s = 0
        for i in range(0, m+1):
            if i > alpha * m / (2 - 2 * alpha) and i <= (2 - 3*alpha) * m / (2 - 2 * alpha):
                
                s += (1 - alpha) / (1 - 2*alpha) * (i / m - 0.5) * stats.binom.pmf(i, m, p_0 + 0.5)

        return s + 0.5  - 0.5 * stats. binom.cdf((2 - 3 * alpha) / (2 - 2 * alpha) * m, m, p_0+0.5)  - 0.5 * stats. binom.cdf(alpha * m / (2 - 2*alpha), m, p_0+0.5)
    
def expectation_theta_squared(m, alpha, p_0):
    """
    Second moment of the performative estimator for given alpha, m, p_0
    """
    if alpha <=0:

        return (1 + alpha)**2 / (1 - 2 * alpha)**2 * (p_0**2 + (0.25 - p_0**2) / m)
    
    if alpha >= 0.5:

        return 0.25
    
    if alpha < 0.5 and alpha > 0:
        s = 0
        for i in range(0, m+1):
            if i > alpha * m / (2 - 2 * alpha) and i <= (2 - 3*alpha) * m / (2 - 2 * alpha):
                
                s += (1 - np.abs(alpha))**2 / (1 - 2*alpha)**2 * (i / m - 0.5)**2 * stats.binom.pmf(i, m, p_0 + 0.5)

        return s + 1/4 - 1/4 * stats. binom.cdf((2 - 3 * alpha) / (2 - 2 * alpha) * m, m, p_0+0.5) + 1/4 * stats. binom.cdf(alpha * m / (2 - 2*alpha), m, p_0+0.5)

def variance_theta(m, alpha, p_0):
    """
    Variance of the performativ estimator
    """

    return expectation_theta_squared(m, alpha, p_0) - (expectation_theta(m, alpha, p_0))**2

def expected_loss_performative(m, alpha, p_0):
    """
    Expected loss for performative estimator
    """

    return (1 - 2*alpha) * expectation_theta_squared(m, alpha, p_0) - 2 * (1 - np.abs(alpha)) * p_0 * expectation_theta(m, alpha, p_0) + 1/4

def expectation_loss_naive(m, alpha, p_0):
    """
    Expected loss for naive estimator
    """
    return (1 - 2*alpha) * (p_0**2 + (1/4 - p_0**2) / m) - 2 * ( 1 - np.abs(alpha)) * p_0**2 + 1/4

def bias_performative(m, alpha, p_0):
    """
    Bias for performative estimator
    """
    return (1 - alpha) * expectation_theta(m, alpha, p_0) - (1 - np.abs(alpha)) * p_0

def shift_performative(m, alpha, p_0):
    """
    Shift for performative estimator
    """
    
    return alpha * expectation_theta(m, alpha, p_0) - np.abs(alpha) * p_0



===== CELL 2 (code) =====
def check(m ,alpha, p_0):
    """
    Expected loss for performative estimator in one function, as a check for the theoretical result
    """
    if alpha <= 0:
        return 1/4 + (1 + alpha)**2 / (1 - 2 * alpha) * ((1/4 - p_0**2) / m - p_0**2)
    
    if alpha >= 0.5:
        return p_0 * (1 - alpha) * (2 * stats.binom.cdf(m / 2, m, p_0 + 0.5) - 1) + (1 - alpha) / 2
    
    else:
        s = 0
        for i in range(0, m+1):
            if i > alpha * m / (2 - 2 * alpha) and i <= (2 - 3*alpha) * m / (2 - 2 * alpha):
                
                g_i = (1 - alpha) / (1 - 2 * alpha) * (i / m - 1/2)
                s += stats.binom.pmf(i, m, p_0 + 0.5) * ((1 - 2*alpha) * g_i**2 - 2 * (1 - alpha) * p_0 * g_i)

        s += (p_0 * (1 - alpha) - (1 - 2*alpha) / 4) * stats. binom.cdf((2 - 3 * alpha) / (2 - 2 * alpha) * m, m, p_0+0.5) + (p_0 * (1 - alpha) + (1 - 2*alpha) / 4) * stats. binom.cdf(alpha * m / (2 - 2*alpha), m, p_0+0.5) - p_0 * (1 - alpha) + (1 - alpha) / 2
        return s

===== CELL 3 (code) =====
# Plot of the difference of expected losses between performative and naive estimators
fig, axes = plt.subplots(1, 3, figsize=(20, 8))

# Define the range for alpha p_0 and m
alpha_values = np.linspace(-0.99, 0.99, 200)
p_0_values = np.linspace(-1/2, 1/2, 200)
m_values = [5, 15, 50]
alpha_grid, p_0_grid = np.meshgrid(alpha_values, p_0_values)

for idx, (m, ax) in enumerate(zip(m_values, axes)):

    # Expected performative loss 
    expectation_values = np.vectorize(check)(m, alpha_grid, p_0_grid)
    # Expected naive loss 
    expectation_grid = np.vectorize(expectation_loss_naive)(m, alpha_grid, p_0_grid)
    
    # Calculate the difference between the two surfaces
    diff = expectation_values - expectation_grid

    # Explicitly set vmin and vmax based on the data
    vmin = np.min(diff)
    vmax = np.max(diff)

    # Set up normalization centered at zero
    norm = matplotlib.colors.TwoSlopeNorm(vmin=vmin, vcenter=0, vmax=vmax)

    # Plot the heatmap for the difference
    c = ax.pcolormesh(alpha_grid, p_0_grid, diff, cmap='coolwarm', norm=norm, shading='auto')

    # Add color bar with ticks that include both positive and negative ranges
    cbar = fig.colorbar(c, ax=ax)
    ticks = np.array([vmin, vmin/2, 0.0, vmax/2, vmax])
    cbar.set_ticks(ticks)
    cbar.ax.tick_params(labelsize=13)
    
    # Labels and title for each plot
    ax.set_xlabel(r'$\alpha$', fontsize=30)
    ax.set_ylabel(r'$p_0$', fontsize=30)
    ax.set_title(f'm = {m}', fontsize=30)

    ax.tick_params(axis='both', labelsize=20)

plt.tight_layout()
plt.show()

===== CELL 4 (code) =====
# Set values of alpha and m
alpha_values = [0.3, -0.4]
m_values = [10, 1000]

# Create a figure with 2 rows and 4 columns of subplots
fig, axes = plt.subplots(2, 4, figsize=(25, 10))

# Create a set of plots for each combination of alpha and m
for i, alpha in enumerate(alpha_values):
    for j, m in enumerate(m_values):
        # Compute p_0_values
        p_0_values = np.linspace(-1/2, 1/2, 1000)
        
        # Compute bias
        sigma_vals_bias = (1 - alpha) * np.sqrt(variance_theta(m, alpha, p_0_values))
        exp_vals_bias = bias_performative(m, alpha, p_0_values)

        # Compute shift
        sigma_vals_shift = (1 - alpha) * np.sqrt(variance_theta(m, alpha, p_0_values)) 
        exp_vals_shift = shift_performative(m, alpha, p_0_values)

        # Plot the bias line
        axes[i, j].plot(p_0_values, exp_vals_bias, 'k--', label='Bias')
        
        # Plot the confidence interval for bias
        axes[i, j].fill_between(p_0_values, exp_vals_bias - sigma_vals_bias, 
                                 exp_vals_bias + sigma_vals_bias, color='lightblue', alpha=0.5, label='CI')

        # Set titles and labels for bias plots
        axes[i, j].set_title(fr'Bias for $m$ = {m}, $\alpha$ = {alpha}', size=25)
        axes[i, j].set_xlabel(r'$p_0$', size=25)
        axes[i, j].tick_params(axis='both', labelsize=15)
        axes[i, j].legend(fontsize=15)

        # Plot the shift
        axes[i, j + 2].plot(p_0_values, exp_vals_shift, 'k--', label='Shift')

        # Plot the confidence interval for shift
        axes[i, j + 2].fill_between(p_0_values, exp_vals_shift - sigma_vals_shift,
                                     exp_vals_shift + sigma_vals_shift, color='lightcoral', alpha=0.5, label='CI')

        # Set titles and labels for shift plots
        axes[i, j + 2].set_title(fr'Shift for $m$ = {m}, $\alpha$ = {alpha}', size=25)
        axes[i, j + 2].set_xlabel(r'$p_0$', size=25)
        axes[i, j + 2].tick_params(axis='both', labelsize=15)
        axes[i, j + 2].legend(fontsize=15)

plt.tight_layout(rect=[0, 0, 1, 0.95])
plt.show()

===== CELL 5 (code) =====

