"""
Tuning an image-segmentation pipeline with a ground truth
=========================================================

Segmentation pipelines (smoothing, background removal, thresholding,
morphology, size filtering) have many interacting parameters, and their quality
is usually judged by looking at the outlines. The synthetic microscopy scene
of :class:`~easyiec.problems.ImageSegmentation` comes with the true mask, so
the Dice coefficient tells how good each judgment-driven tuning really is — the
setting used in the Claude case study of the book.
"""

# %%
# The scene and three random pipelines
# ------------------------------------
import matplotlib.pyplot as plt
import numpy as np

import easyiec as ei
from easyiec.problems import ImageSegmentation
from easyiec.strategies import InteractiveCMAES, InteractiveGA, RandomSearch
from easyiec.validation import curve_frame

problem = ImageSegmentation()
rng = np.random.default_rng(0)
fig, axes = plt.subplots(1, 4, figsize=(11, 3))
axes[0].imshow(problem.img, cmap="gray")
axes[0].set_title("synthetic cells (true outlines in the oracle)", fontsize=8)
for ax in axes[1:]:
    x = problem.random(rng)
    problem.render(x, ax=ax)
    ax.set_title(f"Dice {problem.objectives(x)['dice']:.2f}", fontsize=8)
for ax in axes:
    ax.axis("off")

# %%
# Three strategies, a careful simulated observer
# ----------------------------------------------
# The observer prefers outlines that match the cells (its utility is a smooth
# function of the Dice coefficient and of the error in the number of cells).
results, labels = [], []
for name, factory in {"GA": lambda: InteractiveGA(pop_size=9), "CMA-ES": lambda: InteractiveCMAES(pop_size=9),
                      "random": lambda: RandomSearch(pop_size=9)}.items():
    for seed in range(5):
        user = ei.SimulatedUser(problem, target=None, noise=0.03, seed=seed)
        results.append(ei.run(problem, factory(), user, generations=12, seed=seed))
        labels.append(name)
ei.viz.plot_convergence(curve_frame(results, labels=labels), title="segmentation tuning, five seeds")

# %%
# The best segmentation of the GA
# -------------------------------
best = max((r for r, lab in zip(results, labels) if lab == "GA"), key=lambda r: r.best_true)
fig, ax = plt.subplots(figsize=(4, 4))
problem.render(best.best.genome, ax=ax)
ax.set_title(f"Dice {problem.objectives(best.best.genome)['dice']:.2f}", fontsize=9)
plt.show()
