"""
Photo enhancement: grading an image by eye
==========================================

Image enhancement was one of the earliest IEC applications in image processing
(Takagi, 2001; Poli and Cagnoni, 1997). Eleven genes — exposure, contrast,
saturation, white balance, gamma, highlights, shadows, vignette, sharpening and
hue — process a photograph. The simulated user's ideal grade is hidden; it
compares the image features of each candidate with those of its ideal.
"""

# %%
# Starting point and the effect of single genes
# ---------------------------------------------
import matplotlib.pyplot as plt
import numpy as np

import easyiec as ei
from easyiec.problems import ImageEnhancement
from easyiec.strategies import SequentialGallery

problem = ImageEnhancement()
mid = problem.space.denormalize(np.full(problem.dim, 0.5))
fig, axes = plt.subplots(2, 5, figsize=(10, 4.4))
for ax, (name, z) in zip(axes.flat, [(None, 0.5)] + [(n, v) for n in ["exposure", "contrast", "saturation",
                                                                         "temperature", "shadows"] for v in (0.1, 0.9)][:9]):
    x = mid.copy()
    if name:
        i = problem.space.names.index(name)
        x[i] = problem.space.denormalize(np.where(np.arange(problem.dim) == i, z, 0.5))[i]
    ax.imshow(problem.to_image(x, 160))
    ax.set_title("neutral" if name is None else f"{name} {'low' if z < 0.5 else 'high'}", fontsize=8)
    ax.axis("off")

# %%
# The sequential gallery
# ----------------------
# Koyama et al. (2020) designed the sequential gallery for exactly this task:
# each query is a 3×3 grid in a plane through the current best, the user picks
# the best cell, and a Bayesian model chooses the next plane.
ideal = problem.space.denormalize(problem.ideal)
user = ei.SimulatedUser(problem, target=ideal, noise=0.03, seed=5)
res = ei.run(problem, SequentialGallery(grid=3), user, generations=10, seed=5)
print(f"best utility {res.best_true:.3f} after {res.summary()['queries']} grid choices")
fig, axes = plt.subplots(1, 3, figsize=(9, 3.2))
for ax, (lab, x) in zip(axes, [("neutral", mid), ("hidden ideal", ideal), ("after 10 grids", res.best.genome)]):
    ax.imshow(problem.to_image(x, 200))
    ax.set_title(lab, fontsize=9)
    ax.axis("off")
plt.show()
