===== CELL 0 (markdown) =====
# Figure 4

The code uses the following notation

g $\to \gamma$, l $\to \lambda$, a $\to \alpha$, z $\to \pi$,
w $\to \theta$, q $\to p$, n $\to m$

"x_hat" variables describe the estimates of the RL agent

"y" corresponds to observations of RL agent

===== CELL 1 (code) =====
import random
import math
import numpy as np
import scipy.optimize as spo
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

%config InlineBackend.figure_format = 'retina'

===== CELL 2 (code) =====
def sign(x):
    return (x > 0) - (x < 0)


def clip(x, a, b):
    return min(max(x, a), b)

===== CELL 3 (markdown) =====
# One-period, slow, episodic (see Algorithm 1)

===== CELL 4 (code) =====
def sim_greedy_action(a_hat, z_hat, a, z, n):
    # optimal action
    if a_hat < 0.5:
        w = clip((1 - abs(a)) * z_hat / (1-2*a_hat), -0.5, 0.5)
    else:
        w = sign(z_hat) / 2

    # performative response
    q_new = a * w + (1 - abs(a)) * z

    y = random.binomialvariate(n, q_new + 0.5)
    loss = w**2 - 2 * w * q_new
    return w, y, loss

===== CELL 5 (code) =====
def get_grids_for_a_z_reward(a_size, z_size, eps=1e-6):
    a_grid = np.linspace(-1, 1, a_size)[:, None]
    z_grid = np.linspace(-0.5, 0.5, z_size)[None, :]
    w_grid = (1 - np.abs(a_grid)) * z_grid / np.maximum(1 - 2 * a_grid, eps)
    w_grid = w_grid.clip(-0.5, 0.5)
    w_grid[a_grid[:, 0] >= 0.5] = np.sign(z_grid) / 2
    p_grid = a_grid * w_grid + (1 - np.abs(a_grid)) * z_grid
    reward_grid = -w_grid**2 + 2 * w_grid * p_grid
    return a_grid, z_grid, reward_grid


# find appropriate log-likelihoods (see Alg. 1)
def opt_ll(w, y, n, a_grid, z_grid, reward_grid, beta, eps=1e-6):
    p = a_grid[:, :, None] * w[None, None, :]\
        + ((1 - np.abs(a_grid)) * z_grid + 0.5)[:, :, None]

    ll_grid = -np.dot(np.log2(np.maximum(p, eps)), y)\
        - np.dot(np.log2(np.maximum(1 - p, eps)), n - y)
    ll_grid /= n
    ll_grid -= ll_grid.min()
    ok = ll_grid < beta

    i_max, j_max = np.unravel_index(np.argmax((reward_grid + ok)), ok.shape)
    return a_grid[i_max, 0].item(), z_grid[0, j_max].item()

===== CELL 6 (code) =====
def get_path(a, z, n, n_steps, a_size, z_size, beta, seed=42):
    random.seed(seed)
    w = np.empty(n_steps)
    y = np.empty(n_steps)
    loss = np.empty(n_steps)
    a_grid, z_grid, r_grid = get_grids_for_a_z_reward(a_size, z_size)
    for t in range(n_steps):
        a_hat, z_hat = opt_ll(w[:t], y[:t], n, a_grid, z_grid, r_grid, beta)
        w[t], y[t], loss[t] = sim_greedy_action(a_hat, z_hat, a, z, n)
    a_hat, z_hat = opt_ll(w, y, n, a_grid, z_grid, r_grid, beta)
    return w, y, loss, a_hat, z_hat

===== CELL 7 (code) =====
a, z, n = 0.15, 0.2, 100
n_steps = 2**6
a_size, z_size = 81, 41
beta = 2**(-8)

# find an optimal action
if a >= 0.5:
    w1_opt = sign(z) / 2
else:
    w1_opt = clip((1 - abs(a)) * z / (1 - 2 * a), -0.5, 0.5)
p1_opt = a * w1_opt + (1 - abs(a)) * z

# get exploration-exploitation path
w1, y1, loss1, a1_hat, z1_hat =\
    get_path(a, z, n, n_steps, a_size, z_size, beta)
p1 = a * w1 + (1 - abs(a)) * z

===== CELL 8 (markdown) =====
# Infinite horizon, slow (see Algorithm 2)

===== CELL 9 (code) =====
# find value function and theoretical prediction for q

def get_perf_response_and_loss(a, z, l, w_grid, q_grid, slow):
    next_q = (a * w_grid + (1-abs(a)) * (l*q_grid + (1-l)*z))
    next_q = np.round(next_q * (len(q_grid)-1)).astype(int) + len(q_grid)//2
    if slow:
        loss = -w_grid**2 + 2 * w_grid * q_grid[next_q]
    else:
        loss = -w_grid**2 + 2 * w_grid * q_grid
    return next_q, loss


def solve_inf_horizon(a, z, l, g, w_grid, q_grid, slow=True, n_iter=2**3):
    next_q, loss = get_perf_response_and_loss(a, z, l, w_grid, q_grid, slow)
    v = loss.diagonal() * 0
    for _ in range(n_iter):
        v = (loss + g * v[next_q]).max(axis=0)
    br_w = (loss + g * v[next_q]).argmax(axis=0)
    return br_w


def get_opt_and_eq_q(br_w, a, z, l, w_grid, q_grid, slow=True):
    next_q, loss = get_perf_response_and_loss(a, z, l, w_grid, q_grid, slow)
    br_q = next_q[br_w, np.arange(len(q_grid))]
    eq_q = br_q
    for _ in range(2*2**4):
        eq_q = br_q[eq_q]
    return br_q, eq_q

===== CELL 10 (code) =====
def sim_explore_step(q, a, z, l, n):
    w = sign(random.random() - 0.5) / 2
    q_new = a * w + (1 - abs(a)) * (l*q + (1-l)*z)
    y = random.binomialvariate(n, q_new + 0.5)
    loss = w**2 - 2 * w * q_new
    return w, q_new, y, loss


def sim_greedy_step(q_hat, a_hat, z_hat, l_hat, q, a, z, l, g, n, w_grid, q_grid):
    # optimal action
    br_w = solve_inf_horizon(a_hat, z_hat, l_hat, g, w_grid, q_grid)
    q0 = np.round(q_hat * (w_grid.shape[0]-1)).astype(int) + w_grid.shape[0]//2
    w = w_grid[br_w[q0]].item()

    # performative response
    q_new = a * w + (1 - abs(a)) * (l*q + (1-l)*z)

    y = random.binomialvariate(n, q_new + 0.5)
    loss = w**2 - 2 * w * q_new
    return w, q_new, y, loss

===== CELL 11 (code) =====
def ll_loss(x, w, y, n, eps=1e-6):
    q0, a, z, l = x
    q = np.empty(len(y))
    q[0] = q0
    b = (1 - abs(a)) * l
    d = (1 - abs(a)) * (1 - l) * z
    for t in range(len(w)):
        q[t+1] = a * w[t] + b * q[t] + d
    ll = -np.dot(y, np.log2(np.maximum(0.5 + q, eps)))\
        - np.dot((n - y), np.log2(np.maximum(0.5 - q, eps)))
    return ll


def est_pomdp(q0, a_hat, z_hat, l_hat, w, y, n, eps=1e-6):
    q0, a_hat, z_hat, l_hat = spo.minimize(
        ll_loss, np.array([q0, a_hat, z_hat, l_hat]), (w, y, n, eps),
        bounds=((-0.5, 0.5), (-1, 1), (-0.5, 0.5), (0, 1))).x.tolist()
    q_hat = q0
    b_hat = (1 - abs(a_hat)) * l_hat
    d_hat = (1 - abs(a_hat)) * (1 - l_hat) * z_hat
    for t in range(len(w)):
        q_hat = a_hat * w[t] + b_hat * q_hat + d_hat
    return q0, q_hat, a_hat, z_hat, l_hat

===== CELL 12 (code) =====
def sim_path(a, z, l, g, n, w_grid, q_grid, n_explore, n_steps, seed=42):
    random.seed(seed)
    np.random.seed(seed)

    w = np.empty(n_steps)
    y = np.empty(n_steps+1)
    q = np.empty(n_steps+1)
    loss = np.empty(n_steps)

    q[0] = random.random()-0.5
    y[0] = random.binomialvariate(n, q[0] + 0.5)

    t = 0
    for _ in range(n_explore):
        w[t], q[t+1], y[t+1], loss[t] =\
            sim_explore_step(q[t], a, z, l, n)
        t += 1

    q0, a_hat, z_hat, l_hat = 0, 0, 0, 0
    for _ in range(n_steps-n_explore):
        q0, q_hat, a_hat, z_hat, l_hat =\
            est_pomdp(q0, a_hat, z_hat, l_hat, w[:t], y[:t+1], n)
        w[t], q[t+1], y[t+1], loss[t] = sim_greedy_step(
            q_hat, a_hat, z_hat, l_hat,
            q[t], a, z, l, g, n, w_grid, q_grid)
        t += 1
    q0, q_hat, a_hat, z_hat, l_hat =\
        est_pomdp(q0, a_hat, z_hat, l_hat, w, y, n)
    return w, q, y, loss, q0, a_hat, z_hat, l_hat

===== CELL 13 (code) =====
a, z, l, g, n = 0.15, 0.2, 0.3, 0.9, 100

# create grid for q and w
n_grid = 401
q_grid = np.linspace(-0.5, 0.5, n_grid)
w_grid = np.linspace(-0.5, 0.5, n_grid).reshape(-1, 1)

n_explore, n_steps = 2**2, 2**6

# simulate exploration-exploitation path
w_inf, q_inf, y_inf, loss_inf, q0, a_hat_inf, z_hat_inf, l_hat_inf =\
    sim_path(a, z, l, g, n, w_grid, q_grid, n_explore, n_steps)

# find a theoretical prediction
br_w = solve_inf_horizon(a, z, l, g, w_grid, q_grid)
br_q, eq_q = get_opt_and_eq_q(br_w, a, z, l, w_grid, q_grid)
q0_pos = np.round(q_inf[n_explore] * (w_grid.shape[0]-1)).astype(int)\
    + w_grid.shape[0]//2
q_eq_pos = eq_q[q0_pos]
w_eq_pos = br_w[q_eq_pos]

===== CELL 14 (markdown) =====
# Figure 4

===== CELL 15 (code) =====
matplotlib.use("pgf")
matplotlib.rcParams.update({
    'pgf.texsystem': 'pdflatex',
    'text.usetex': True,
})

===== CELL 16 (code) =====
fig, ax = plt.subplots(1, 2, constrained_layout=True)
fig.set_size_inches(h=1.5, w=3.3)

t_fontsize = 7
l_fontsize = 6
p_linewidth = 0.8
t_labelsize, t_length, t_width, t_linewidth = 6, 2, 0.5, 0.5

ax[0].axhline(
    y=w1_opt, color='r', linestyle='-', label=r"$\theta^*_0$",
    linewidth=p_linewidth)
ax[0].axhline(
    y=p1_opt, color='g', linestyle='-', label=r"$p^*_1$",
    linewidth=p_linewidth)
ax[0].plot(np.arange(len(w1)), w1, label=r"$\theta_0$", linewidth=p_linewidth)
ax[0].plot(np.arange(len(p1)), p1, label=r"$p_1$", linewidth=p_linewidth)
ax[0].set_ylim(-0.55, 0.55)
ax[0].set_title(r"$T=1$, Slow", fontsize=t_fontsize)
ax[0].set_xlabel(r"Episode", fontsize=l_fontsize)
ax[0].legend(fontsize=l_fontsize)
ax[0].tick_params(
    axis='both', labelsize=t_labelsize, length=t_length, width=t_width)
plt.setp(ax[0].spines.values(), linewidth=t_width)

ax[1].axhline(
    y=w_grid[w_eq_pos], color='r', linestyle='-', label=r"$\theta^*_\infty$",
    linewidth=p_linewidth)
ax[1].axhline(
    y=q_grid[q_eq_pos], color='g', linestyle='-', label=r"$p^*_\infty$",
    linewidth=p_linewidth)
ax[1].plot(np.arange(len(w_inf)), w_inf, label=r"$\theta_t$", linewidth=p_linewidth)
ax[1].plot(np.arange(len(q_inf)), q_inf, label=r"$p_t$", linewidth=p_linewidth)
ax[1].set_ylim(-0.55, 0.55)
ax[1].set_xlabel(r"t", fontsize=l_fontsize)
ax[1].set_title(r"$T=\infty$, Slow", fontsize=t_fontsize)
ax[1].legend(fontsize=l_fontsize)
ax[1].tick_params(
    axis='both', labelsize=t_labelsize, length=t_length, width=t_width)
plt.setp(ax[1].spines.values(), linewidth=t_width)

plt.gcf()
plt.savefig('fig4-rl.pgf', bbox_inches='tight', pad_inches=0)
plt.close()

===== CELL 17 (code) =====

