"""
Preferential Bayesian optimization, line search and gallery
===========================================================

When every answer is expensive, a statistical model of the evaluator's
preferences pays off. A Gaussian process is fitted to pairwise answers with the
probit likelihood of Chu and Ghahramani (2005); the next comparison is chosen by
an acquisition function (González et al., 2017). Sequential line search (Koyama
et al., 2017) asks for the best point on a slider through the incumbent, and
the sequential gallery (Koyama et al., 2020) for the best cell of a 2-D grid —
far more information per question than a single pair.
"""

# %%
# Three model-based strategies on a two-dimensional landscape
# -----------------------------------------------------------
import matplotlib.pyplot as plt
import numpy as np

import easyiec as ei
from easyiec.problems import SyntheticPreference
from easyiec.strategies import PreferentialBO, SequentialGallery, SequentialLineSearch

problem = SyntheticPreference(dim=2, kind="ellipsoid", seed=4)
runs = {}
for name, strategy in {"PBO (pairs)": PreferentialBO(), "line search (slider)": SequentialLineSearch(n_samples=7),
                       "gallery (3×3 grid)": SequentialGallery(grid=3)}.items():
    user = ei.SimulatedUser(problem, target="random", noise=0.03, seed=8)
    runs[name] = (strategy, user, ei.run(problem, strategy, user, generations=15, seed=8))
    print(f"{name:22s} best utility {runs[name][2].best_true:.3f} after {runs[name][2].summary()['queries']} questions")
# %%
# Learned utility versus the hidden one
# -------------------------------------
# Top left: the hidden utility of the simulated user. The other panels show the
# GP posterior mean of each strategy with the shown points (white) and the
# chosen ones (circles).
fig, axes = plt.subplots(2, 2, figsize=(9.4, 8))
g = np.linspace(0, 1, 70)
A, B = np.meshgrid(g, g)
user = runs["PBO (pairs)"][1]
U = np.array([problem.utility(problem.space.denormalize(np.array([a, b])), user.target)
              for a, b in zip(A.ravel(), B.ravel())]).reshape(A.shape)
cs = axes[0, 0].contourf(A, B, U, levels=20, cmap="viridis")
plt.colorbar(cs, ax=axes[0, 0], shrink=0.85, label="hidden utility")
axes[0, 0].set_title("hidden utility of the simulated user", fontsize=9)
for ax, (name, (strategy, _, res)) in zip(axes.flat[1:], runs.items()):
    ei.viz.plot_preference_landscape(strategy.model, problem, log=res.log, ax=ax)
    ax.set_title(name, fontsize=9)
fig.tight_layout()

# %%
# Utility per question
# --------------------
# A line or gallery answer carries several pairwise preferences at once.
fig, ax = plt.subplots(figsize=(6.4, 3.4))
for k, (name, (_, _, res)) in enumerate(runs.items()):
    ei.viz.plot_anytime(res, ax=ax, x="n_queries", label=name, color=["#285780", "#D55E00", "#009E73"][k],
                        show_shown=False)
ax.legend(frameon=False, fontsize=8)
ax.set_title("best utility vs. number of questions", fontsize=9)
plt.show()
