"""
Panels: several evaluators, one decision
========================================

Design decisions are often taken by groups, and a single LLM can be asked to
speak with several *personas*. A :class:`~easyiec.evaluators.Panel` asks every
member and aggregates: vote shares for selections, Borda, Copeland, Kemeny or
Bradley–Terry consensus for rankings. The disagreement of the members — one
minus Kendall's coefficient of concordance *W* for rankings, one minus the mean
Jaccard overlap for selections — is reported as the panel's uncertainty.
"""

# %%
# A crowd of seven simulated users with related tastes
# ----------------------------------------------------
# :func:`~easyiec.evaluators.make_crowd` scatters the members' targets around a
# common one; ``spread`` controls how much they disagree.
import matplotlib.pyplot as plt
import numpy as np

import easyiec as ei
from easyiec.evaluators import Panel, make_crowd
from easyiec.problems import ColorPalette
from easyiec.strategies import InteractiveGA
from easyiec.validation import make_individuals

problem = ColorPalette()
items = make_individuals(problem.random(np.random.default_rng(3), 8))
spreads = [0.02, 0.05, 0.1, 0.2, 0.35]
W = []
for spread in spreads:
    w = []
    for s in range(10):
        crowd = make_crowd(problem, n=7, spread=spread, seed=s, noise=0.03)
        w.append(1 - Panel(crowd).evaluate(ei.Query("rank", items)).uncertainty)
    W.append(np.mean(w))
fig, ax = plt.subplots(figsize=(4.8, 3))
ax.plot(spreads, W, "o-", color="#285780", lw=2)
ax.set_xlabel("spread of the members' targets", fontsize=8)
ax.set_ylabel("Kendall's W", fontsize=8)
ax.set_title("concordance of a seven-member panel (mean of 10 crowds)", fontsize=9)

# %%
# Vote shares on one gallery
# --------------------------
crowd = make_crowd(problem, n=7, spread=0.15, seed=4, noise=0.03)
panel = Panel(crowd)
q = ei.Query("select", items)
fb = panel.evaluate(q)
fig, axes = plt.subplots(2, 1, figsize=(8, 4.4), gridspec_kw={"height_ratios": [1, 1.2]})
for k, it in enumerate(items):
    axes[0].imshow(problem.to_image(it.genome, 120), extent=(k - 0.45, k + 0.45, 0, 1))
axes[0].set_xlim(-0.5, len(items) - 0.5)
axes[0].axis("off")
ei.viz.plot_member_votes(fb, q, ax=axes[1])

# %%
# Evolving for the group
# ----------------------
# The panel steers the GA towards palettes the whole group likes. The curves
# show the mean utility over the members (the group's ground truth), averaged
# over six crowds, for the panel and for a single member deciding alone. The
# gain is modest but consistent: a lone member optimizes their own taste.
from easyiec.validation import curve_frame  # noqa: E402
results, labels = [], []
for s in range(6):
    crowd = make_crowd(problem, n=7, spread=0.15, seed=10 + s, noise=0.03)
    group = lambda g, crowd=crowd: float(np.mean([u.true_utility(g) for u in crowd]))  # noqa: E731
    results.append(ei.run(problem, InteractiveGA(pop_size=9), Panel(crowd), generations=15, seed=s, oracle=group))
    results.append(ei.run(problem, InteractiveGA(pop_size=9), crowd[0], generations=15, seed=s, oracle=group))
    labels += ["panel of 7 (Borda)", "one member alone"]
ax = ei.viz.plot_convergence(curve_frame(results, labels=labels), title="six crowds, spread 0.15")
ax.set_ylabel("best mean utility over the group", fontsize=8)
plt.show()
