"""
Seven ways to answer: feedback protocols
========================================

IEC systems ask very different questions. EASY-IEC asks the user to *select*
the good candidates; Picbreeder-like systems ask for one favourite; Bayesian
methods ask for *pairwise* comparisons or for the best point on a *line*;
questionnaires ask for *ratings*. easyiec supports seven protocols and converts
every answer into weighted pairwise preferences, so that every strategy and
every preference model can learn from every kind of answer.
"""

# %%
# One gallery, seven questions
# ----------------------------
# Six harmonograph drawings are evaluated by the same simulated user under each
# protocol. ``Feedback.to_pairs`` turns each answer into (winner, loser, weight)
# triples; :func:`~easyiec.core.feedback.information_bits` bounds the
# information one answer can carry.
import matplotlib.pyplot as plt
import numpy as np

import easyiec as ei
from easyiec.core.feedback import information_bits
from easyiec.problems import Harmonograph
from easyiec.validation import make_individuals

problem = Harmonograph()
rng = np.random.default_rng(0)
items = make_individuals(problem.random(rng, 6))
user = ei.SimulatedUser(problem, target="random", noise=0.03, seed=5)
queries = {
    "select": ei.Query("select", items),
    "select k=2": ei.Query("select", items, n_select=2),
    "rank": ei.Query("rank", items),
    "rate 1-10": ei.Query("rate", items, scale=(1, 10)),
    "pairs": ei.Query("pairs", items, pairs=[(0, 1), (2, 3), (4, 5), (0, 5)]),
    "best-worst": ei.Query("best_worst", items),
}
rows = []
for name, q in queries.items():
    fb = user.evaluate(q)
    pairs = fb.to_pairs(q)
    rows.append((name, information_bits(q), q.n_decisions(), len(pairs)))
    print(f"{name:11s} {fb.summary():45s} -> {len(pairs):2d} pairs")
# %%
# The gallery and the true utilities
# ----------------------------------
# The numbers under the drawings are the user's hidden utilities; the ranking
# answer should follow them up to noise.
u = [problem.utility(it.genome, user.target) for it in items]
ei.viz.plot_gallery(problem, items, labels=[f"{x:.2f}" for x in u], ncols=6, size=1.3)

# %%
# Information and effort per answer
# ---------------------------------
# A ranking carries the most information but costs the most elementary
# decisions; best–worst scaling is cheap and still yields nine pairs — one reason
# it is popular in sensory science (Louviere et al., 2015).
names, bits, dec, npairs = zip(*rows)
fig, ax = plt.subplots(figsize=(6.4, 3.0))
x = np.arange(len(names))
ax.bar(x - 0.27, bits, 0.27, label="information bound (bits)", color="#285780")
ax.bar(x, dec, 0.27, label="elementary decisions", color="#D55E00")
ax.bar(x + 0.27, npairs, 0.27, label="implied pairs", color="#009E73")
ax.set_xticks(x, names, fontsize=8)
ax.legend(frameon=False, fontsize=8)
ax.set_title("what one answer is worth")
plt.show()
