"""
A factorial benchmark with simulated users
==========================================

Claims about IEC algorithms should rest on many runs, several problems and an
honest statistical comparison. :func:`~easyiec.validation.run_benchmark` runs
every combination of problems, strategies, simulated users and seeds and
returns curves and a summary table; the Friedman test with the Nemenyi critical
difference (Demšar, 2006) compares the strategies over the problem–seed blocks,
and Vargha and Delaney's A12 effect size quantifies pairwise differences.
"""

# %%
# Six strategies, three landscapes, eight seeds
# ---------------------------------------------
import matplotlib.pyplot as plt

import easyiec as ei
from easyiec.problems import SyntheticPreference
from easyiec.strategies import EasyIEC, InteractiveCMAES, InteractiveDE, InteractiveGA, InteractivePSO, RandomSearch
from easyiec.validation import compare_groups, friedman, nemenyi_cd, run_benchmark
bench = run_benchmark(
    problems={k: (lambda k=k: SyntheticPreference(dim=6, kind=k, seed=5)) for k in ["sphere", "ellipsoid", "multimodal"]},
    strategies={"GA": lambda: InteractiveGA(pop_size=9), "EASY-IEC": lambda: EasyIEC(pop_size=9),
                "CMA-ES": lambda: InteractiveCMAES(pop_size=9), "IPSO": lambda: InteractivePSO(pop_size=9),
                "DE": lambda: InteractiveDE(pop_size=8), "random": lambda: RandomSearch(pop_size=9)},
    users={"user": lambda p, s: ei.SimulatedUser(p, target="random", noise=0.05, seed=s)},
    seeds=range(8), max_items=135, generations=None)
M = bench.summary.pivot_table(index=["problem", "seed"], columns="strategy", values="best_true")
fr = friedman(M.to_numpy())
cd = nemenyi_cd(M.shape[1], M.shape[0])
print(f"Friedman p = {fr['p_value']:.2g}, Nemenyi CD = {cd:.2f}")
table = bench.summary.assign(block=bench.summary["problem"] + "/" + bench.summary["seed"].astype(str))
print(compare_groups(table, "best_true", "strategy", block="block", reference="random").round(3).to_string())
ei.viz.plot_critical_difference(fr["avg_ranks"], list(M.columns), cd,
                                title="average ranks over 24 problem–seed blocks (135 images each)")

# %%
# Curves per landscape
# --------------------
fig, axes = plt.subplots(1, 3, figsize=(13, 3.4), sharey=True)
for ax, (prob, df) in zip(axes, bench.curves.groupby("problem")):
    ei.viz.plot_convergence(df, by="strategy", ax=ax, title=prob)
    if ax is not axes[0]:
        ax.get_legend().remove()
plt.show()
