# optimal score ~ 0.67366

import matplotlib.pyplot as plt
import matplotlib.cm as cm

import numpy as np
import math
import random
import time

plt.ion()
plt.style.use('ggplot')
fig, (ax_contour, ax_score) = plt.subplots(1,2)

score_line, = ax_score.plot([], [])
xdata = []
ydata = []

explore_line, = ax_contour.plot([], [], linestyle='-', marker='.', color='red')
xline = []
yline = []
best = 0


plt.subplots_adjust(bottom=0.15)
ax_contour.set_title("Contour Plot", fontsize=20)
ax_score.set_title("Value", fontsize=20)
plt.show(block=False)

props = dict(boxstyle="round", facecolor="blue", alpha=0.5)
text = ax_score.text(
    0,
    -0.1,
    f"Best Score: {best}",
    transform=ax_score.transAxes,
    fontsize=14,
    verticalalignment="top",
    bbox=props,
)

delta = 0.01
x = np.arange(-6.0, 6.0, delta)
y = np.arange(-6.0, 6.0, delta)
X, Y = np.meshgrid(x, y)
Z = np.sin(X-Y)**2 * np.sin(X+Y)**2 / np.sqrt(X**2 + Y**2)
levels = np.arange(0, 0.7, 0.03)


CS = ax_contour.contour(X, Y, Z, levels=levels)

plt.pause(0.0001)
first = True

while True:
    pt_x = random.random() * 12 - 6
    pt_y = random.random() * 12 - 6
    xline.append(pt_x)
    yline.append(pt_y)
    explore_line.set_data(xline, yline)
    value = math.sin(pt_x - pt_y)**2 * math.sin(pt_x+pt_y)**2 / math.sqrt(pt_x**2 + pt_y ** 2)
    if value > best:
        best = value
        text.remove()
        text = ax_score.text(
            0,
            -0.05,
            f"Best Score: {best}",
            transform=ax_score.transAxes,
            fontsize=14,
            verticalalignment="top",
            bbox=props,
        )


    xdata.append(len(xdata))
    ydata.append(value)
    score_line.set_data(xdata, ydata)
    cur_x = ax_score.get_xlim()
    cur_y = ax_score.get_ylim()

    if xdata[-1] > cur_x[1]:
        ax_score.set_xlim((0, cur_x[1] + 100))
    if ydata[-1] > cur_y[1]:
        ax_score.set_ylim((0, max(ydata)))

    if first:
        time.sleep(2)
        first = False
    time.sleep(.2)
    plt.pause(0.0001)# ax_contour.clabel(CS, inline=True, fontsize=10)