easyiec 1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. easyiec/__init__.py +25 -0
  2. easyiec/compat/__init__.py +20 -0
  3. easyiec/compat/matlab.py +95 -0
  4. easyiec/core/__init__.py +11 -0
  5. easyiec/core/feedback.py +437 -0
  6. easyiec/core/individual.py +99 -0
  7. easyiec/core/log.py +228 -0
  8. easyiec/core/operators.py +114 -0
  9. easyiec/core/problem.py +245 -0
  10. easyiec/core/session.py +295 -0
  11. easyiec/core/space.py +175 -0
  12. easyiec/evaluators/__init__.py +14 -0
  13. easyiec/evaluators/base.py +166 -0
  14. easyiec/evaluators/human.py +101 -0
  15. easyiec/evaluators/hybrid.py +262 -0
  16. easyiec/evaluators/llm/__init__.py +24 -0
  17. easyiec/evaluators/llm/clients.py +432 -0
  18. easyiec/evaluators/llm/judge.py +419 -0
  19. easyiec/evaluators/llm/mock.py +141 -0
  20. easyiec/evaluators/llm/parsing.py +84 -0
  21. easyiec/evaluators/llm/prompts.py +110 -0
  22. easyiec/evaluators/panel.py +161 -0
  23. easyiec/evaluators/simulated.py +236 -0
  24. easyiec/evaluators/steering.py +167 -0
  25. easyiec/imaging.py +253 -0
  26. easyiec/preference/__init__.py +7 -0
  27. easyiec/preference/aggregation.py +162 -0
  28. easyiec/preference/models.py +252 -0
  29. easyiec/problems/__init__.py +73 -0
  30. easyiec/problems/benchmark.py +128 -0
  31. easyiec/problems/control.py +399 -0
  32. easyiec/problems/design.py +380 -0
  33. easyiec/problems/engineering.py +233 -0
  34. easyiec/problems/fermentation.py +197 -0
  35. easyiec/problems/fractals.py +353 -0
  36. easyiec/problems/generative.py +425 -0
  37. easyiec/problems/image.py +232 -0
  38. easyiec/problems/music.py +152 -0
  39. easyiec/problems/text.py +209 -0
  40. easyiec/strategies/__init__.py +22 -0
  41. easyiec/strategies/base.py +175 -0
  42. easyiec/strategies/bayesian.py +251 -0
  43. easyiec/strategies/continuous.py +302 -0
  44. easyiec/strategies/diversity.py +239 -0
  45. easyiec/strategies/evolutionary.py +363 -0
  46. easyiec/strategies/multiobjective.py +158 -0
  47. easyiec/strategies/surrogate.py +243 -0
  48. easyiec/ui/__init__.py +13 -0
  49. easyiec/ui/controller.py +178 -0
  50. easyiec/ui/jupyter.py +275 -0
  51. easyiec/ui/mpl.py +202 -0
  52. easyiec/validation/__init__.py +53 -0
  53. easyiec/validation/agreement.py +193 -0
  54. easyiec/validation/experiments.py +210 -0
  55. easyiec/validation/inference.py +175 -0
  56. easyiec/validation/judges.py +360 -0
  57. easyiec/validation/runs.py +128 -0
  58. easyiec/validation/stats.py +108 -0
  59. easyiec/viz/__init__.py +37 -0
  60. easyiec/viz/_style.py +55 -0
  61. easyiec/viz/evaluation.py +214 -0
  62. easyiec/viz/process.py +464 -0
  63. easyiec/viz/report.py +103 -0
  64. easyiec-1.0.dist-info/METADATA +204 -0
  65. easyiec-1.0.dist-info/RECORD +67 -0
  66. easyiec-1.0.dist-info/WHEEL +4 -0
  67. easyiec-1.0.dist-info/licenses/LICENSE +21 -0
easyiec/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ """easyiec — interactive evolutionary computation with human, simulated and AI evaluators.
2
+
3
+ The successor of the EASY-IEC MATLAB toolbox (Madár, Abonyi and Szeifert,
4
+ 2005), extended with modern interactive search algorithms, preference
5
+ learning, LLM/VLM judges, panels and risk-controlled human escalation, and with
6
+ tools to validate, benchmark and visualize interactive optimization processes.
7
+ """
8
+
9
+ from . import core, evaluators, imaging, preference, strategies
10
+ from .core import Box, Budget, Feedback, Individual, NeedsHuman, Problem, Query, Result, Session, run
11
+ from .evaluators import SimulatedUser
12
+
13
+ __version__ = "1.0"
14
+
15
+ __all__ = ["Box", "Individual", "Query", "Feedback", "NeedsHuman", "Problem", "Session", "Budget", "Result", "run",
16
+ "SimulatedUser", "core", "strategies", "evaluators", "preference", "imaging", "__version__"]
17
+
18
+
19
+ def __getattr__(name): # lazy subpackages with heavier imports
20
+ import importlib
21
+ if name in ("problems", "validation", "viz", "ui", "llm", "compat", "benchmark"):
22
+ mod = importlib.import_module(f".{name}" if name != "llm" else ".evaluators.llm", __name__)
23
+ globals()[name] = mod
24
+ return mod
25
+ raise AttributeError(f"module 'easyiec' has no attribute {name!r}")
@@ -0,0 +1,20 @@
1
+ """Compatibility with the EASY-IEC MATLAB toolbox (Madár, Abonyi and Szeifert, 2005).
2
+
3
+ The MATLAB toolbox represented a population by a structure ``popu`` with the
4
+ fields ``nvar`` (number of variables), ``nind`` (population size), ``LB`` and
5
+ ``UB`` (bounds), ``devi`` (strategy parameters, one row per individual) and
6
+ ``chrom`` (real-coded chromosomes, one row per individual). The user wrote a
7
+ *user function* that drew each individual into a column of subplots, and
8
+ ``popu = ies_main(popu, subfigrows, 'userfun')`` ran the interactive loop.
9
+ This module offers the same workflow in Python:
10
+
11
+ >>> import numpy as np
12
+ >>> from easyiec.compat import popu_init, ies_main, UserFunctionProblem
13
+ >>> popu = popu_init([0, 0, -1], [5, 10, 1], nind=9, init_chrom=[2.5, 5, 0], seed=0)
14
+ >>> popu["chrom"].shape
15
+ (9, 3)
16
+ """
17
+
18
+ from .matlab import UserFunctionProblem, ies_main, popu_from_strategy, popu_init
19
+
20
+ __all__ = ["popu_init", "ies_main", "UserFunctionProblem", "popu_from_strategy"]
@@ -0,0 +1,95 @@
1
+ """The EASY-IEC MATLAB workflow (``popu`` structure, user function, ``ies_main``) in Python."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ from ..core.problem import Problem
8
+ from ..core.session import Budget, Session
9
+ from ..core.space import Box
10
+ from ..strategies.evolutionary import EasyIEC
11
+
12
+ __all__ = ["popu_init", "ies_main", "UserFunctionProblem", "popu_from_strategy"]
13
+
14
+
15
+ def popu_init(LB, UB, nind: int = 9, init_chrom=None, seed: int | None = None) -> dict:
16
+ """Initialize a population structure as in the EASY-IEC help.
17
+
18
+ ``devi = (UB-LB)/sqrt(nvar)/2`` for every individual and
19
+ ``chrom = init_chrom + randn .* devi`` (clipped to the bounds; infinite
20
+ bounds are replaced by ±10 standard deviations around ``init_chrom``).
21
+ """
22
+ LB = np.asarray(LB, float)
23
+ UB = np.asarray(UB, float)
24
+ nvar = LB.size
25
+ c = np.asarray(init_chrom, float) if init_chrom is not None else np.where(np.isfinite(LB + UB), (LB + UB) / 2, 0.0)
26
+ span = np.where(np.isfinite(UB - LB), UB - LB, 20.0)
27
+ devi = np.tile(span / np.sqrt(nvar) / 2, (nind, 1))
28
+ rng = np.random.default_rng(seed)
29
+ chrom = np.clip(c + rng.standard_normal((nind, nvar)) * devi, np.where(np.isfinite(LB), LB, -np.inf),
30
+ np.where(np.isfinite(UB), UB, np.inf))
31
+ return {"nvar": nvar, "nind": nind, "LB": LB, "UB": UB, "devi": devi, "chrom": chrom, "generation": 1}
32
+
33
+
34
+ class UserFunctionProblem(Problem):
35
+ """Wrap a MATLAB-style user function ``userfun(chrom, axes)`` as a problem.
36
+
37
+ ``userfun`` receives one chromosome and a list of ``subfigrows`` axes (the
38
+ column of subplots of that individual) and draws on them, exactly like the
39
+ user functions of EASY-IEC.
40
+ """
41
+
42
+ name = "userfun"
43
+ title = "User-defined problem"
44
+ domain = "user"
45
+
46
+ def __init__(self, LB, UB, userfun, subfigrows: int = 1, names=None, goal: str | None = None):
47
+ LB = np.asarray(LB, float)
48
+ UB = np.asarray(UB, float)
49
+ LB = np.where(np.isfinite(LB), LB, -1e6)
50
+ UB = np.where(np.isfinite(UB), UB, 1e6)
51
+ self.space = Box(LB, UB, names=names)
52
+ self.userfun = userfun
53
+ self.subplot_rows = subfigrows
54
+ if goal:
55
+ self.goal = goal
56
+
57
+ def draw_column(self, x, axes):
58
+ self.userfun(np.asarray(x, float), axes)
59
+
60
+ def _image(self, x, size):
61
+ import matplotlib.pyplot as plt
62
+
63
+ from ..imaging import fig_to_array
64
+ fig, axes = plt.subplots(self.subplot_rows, 1, figsize=(size / 100, size / 100), dpi=100, squeeze=False)
65
+ self.draw_column(x, list(axes[:, 0]))
66
+ fig.tight_layout(pad=0.2)
67
+ return fig_to_array(fig)
68
+
69
+
70
+ def popu_from_strategy(strategy: EasyIEC, generation: int) -> dict:
71
+ pop = strategy.population()
72
+ chrom = np.array([p.genome for p in pop])
73
+ devi = np.array([strategy.space.denormalize(np.clip(strategy.z(p) + p.params["sigma"], 0, 1)) - p.genome
74
+ for p in pop])
75
+ return {"nvar": chrom.shape[1], "nind": chrom.shape[0], "LB": strategy.space.lower, "UB": strategy.space.upper,
76
+ "devi": np.abs(devi), "chrom": chrom, "generation": generation}
77
+
78
+
79
+ def ies_main(popu: dict, subfigrows: int, userfun, *, evaluator=None, generations: int | None = None,
80
+ goal: str | None = None, seed: int | None = None) -> dict:
81
+ """Run the interactive loop on a ``popu`` structure; returns the resulting population.
82
+
83
+ Without ``evaluator`` the blocking :class:`~easyiec.ui.MatplotlibGallery`
84
+ is used (click once = parent, twice = offspring kept unchanged; *Stop*
85
+ ends the loop, like the Exit button of EASY-IEC). Any evaluator (a
86
+ simulated user, an LLM judge) can be passed instead.
87
+ """
88
+ from ..ui.mpl import MatplotlibGallery
89
+ prob = UserFunctionProblem(popu["LB"], popu["UB"], userfun, subfigrows, goal=goal)
90
+ strat = EasyIEC(pop_size=int(popu["nind"]))
91
+ ev = evaluator or MatplotlibGallery(prob, ncols=int(popu["nind"]), subplot_rows=subfigrows)
92
+ sess = Session(prob, strat, ev, budget=Budget(max_generations=generations or 10_000), seed=seed,
93
+ initial=[np.asarray(c, float) for c in popu["chrom"]])
94
+ sess.run()
95
+ return popu_from_strategy(strat, int(popu.get("generation", 1)) + strat.generation)
@@ -0,0 +1,11 @@
1
+ """Core data structures of easyiec: spaces, individuals, queries, feedback, problems, sessions."""
2
+
3
+ from .feedback import KINDS, Feedback, NeedsHuman, Query, information_bits
4
+ from .individual import IdFactory, Individual
5
+ from .log import Record, SessionLog
6
+ from .problem import Problem
7
+ from .session import Budget, Result, Session, run
8
+ from .space import Box
9
+
10
+ __all__ = ["Box", "Individual", "IdFactory", "Query", "Feedback", "KINDS", "NeedsHuman", "information_bits",
11
+ "Problem", "Session", "Budget", "Result", "run", "SessionLog", "Record"]
@@ -0,0 +1,437 @@
1
+ """Queries and feedback: the evaluation protocols of interactive evolution.
2
+
3
+ A strategy asks a :class:`Query`; an evaluator (a person, a simulated user, an
4
+ LLM judge, a panel or a hybrid of these) answers with a :class:`Feedback`.
5
+ Seven protocols cover the IEC literature (Takagi, 2001; Pei and Takagi, 2018):
6
+
7
+ ``select`` choose the best ``k`` of ``n`` (EASY-IEC v1, Picbreeder)
8
+ ``rank`` order the candidates (possibly partially)
9
+ ``rate`` give a score on a numeric scale (Likert style)
10
+ ``pairs`` compare pairs (2AFC with optional ties)
11
+ ``best_worst`` pick the best and the worst (MaxDiff)
12
+ ``line`` choose a point on a one-dimensional slider (sequential line search)
13
+ ``edit`` modify a candidate directly (EASY-IEC v2, Lamarckian edits)
14
+
15
+ Every feedback can be turned into weighted pairwise preferences
16
+ (:meth:`Feedback.to_pairs`) and into a utility score per candidate
17
+ (:meth:`Feedback.utilities`), so any strategy can consume any protocol and any
18
+ two evaluators can be compared on the same footing.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import itertools
24
+ import math
25
+ import time
26
+ from dataclasses import dataclass, field
27
+ from typing import Any
28
+
29
+ import numpy as np
30
+
31
+ from .individual import Individual
32
+
33
+ __all__ = ["KINDS", "Query", "Feedback", "information_bits", "NeedsHuman"]
34
+
35
+ KINDS = ("select", "rank", "rate", "pairs", "best_worst", "line", "edit")
36
+
37
+ _query_ids = itertools.count()
38
+
39
+
40
+ class NeedsHuman(Exception): # noqa: N818 - control-flow signal, not an error
41
+ """Raised by an evaluator that must hand the query over to a person.
42
+
43
+ Front ends (the Jupyter gallery, the matplotlib gallery) catch it, show the
44
+ query, optionally prefilled with the AI suggestion, and answer with
45
+ :meth:`easyiec.Session.tell`.
46
+ """
47
+
48
+ def __init__(self, query: Query, suggestion: Feedback | None = None, reason: str = ""):
49
+ super().__init__(reason or "human evaluation required")
50
+ self.query = query
51
+ self.suggestion = suggestion
52
+ self.reason = reason
53
+
54
+
55
+ @dataclass
56
+ class Query:
57
+ """A request for evaluation.
58
+
59
+ Attributes
60
+ ----------
61
+ kind : str
62
+ One of :data:`KINDS`.
63
+ items : list of Individual
64
+ The candidates (for ``pairs`` the distinct individuals involved).
65
+ pairs : list of (int, int), optional
66
+ Index pairs into ``items`` for ``kind="pairs"``.
67
+ n_select : int, optional
68
+ Number of candidates to choose for ``select`` (``None``: free choice,
69
+ at least one).
70
+ scale : (float, float)
71
+ Rating scale for ``rate``.
72
+ line_t : array, optional
73
+ Positions in ``[0, 1]`` of the samples (``items``) along the line of a
74
+ ``line`` query.
75
+ goal : str, optional
76
+ Natural-language goal shown to people and to LLM judges.
77
+ generation : int
78
+ Strategy iteration that issued the query.
79
+ meta : dict
80
+ Strategy-specific annotations (e.g. ``{"role": "challenger"}``).
81
+ """
82
+
83
+ kind: str
84
+ items: list[Individual]
85
+ pairs: list[tuple[int, int]] | None = None
86
+ n_select: int | None = None
87
+ scale: tuple[float, float] = (1.0, 10.0)
88
+ line_t: np.ndarray | None = None
89
+ goal: str | None = None
90
+ generation: int = 0
91
+ meta: dict = field(default_factory=dict)
92
+ id: int = field(default_factory=lambda: next(_query_ids))
93
+
94
+ def __post_init__(self):
95
+ if self.kind not in KINDS:
96
+ raise ValueError(f"unknown query kind {self.kind!r}; expected one of {KINDS}")
97
+ if self.kind == "pairs" and not self.pairs:
98
+ if len(self.items) == 2:
99
+ self.pairs = [(0, 1)]
100
+ else:
101
+ raise ValueError("a 'pairs' query needs explicit index pairs")
102
+
103
+ @property
104
+ def ids(self) -> list[int]:
105
+ return [it.id for it in self.items]
106
+
107
+ def __len__(self) -> int:
108
+ return len(self.items)
109
+
110
+ def item(self, ident: int) -> Individual:
111
+ for it in self.items:
112
+ if it.id == ident:
113
+ return it
114
+ raise KeyError(ident)
115
+
116
+ def n_decisions(self) -> int:
117
+ """Elementary judgments a careful evaluator makes (a burden proxy)."""
118
+ n = len(self.items)
119
+ if self.kind == "select":
120
+ return n
121
+ if self.kind == "rank":
122
+ return max(n - 1, 0) + (n * (n - 1) // 4)
123
+ if self.kind == "rate":
124
+ return n
125
+ if self.kind == "pairs":
126
+ return len(self.pairs or [])
127
+ if self.kind == "best_worst":
128
+ return 2
129
+ if self.kind == "line":
130
+ return 1
131
+ return 1
132
+
133
+ def __repr__(self) -> str:
134
+ return f"Query(id={self.id}, kind={self.kind!r}, n={len(self.items)}, generation={self.generation})"
135
+
136
+
137
+ def information_bits(query: Query) -> float:
138
+ """Upper bound of the information (bits) one answer to ``query`` can carry.
139
+
140
+ ``select`` with fixed ``k``: :math:`\\log_2\\binom nk`; free selection:
141
+ :math:`n` bits; ``rank``: :math:`\\log_2 n!`; ``rate`` with :math:`m` levels:
142
+ :math:`n\\log_2 m`; ``pairs`` with ties: :math:`\\log_2 3` per pair;
143
+ ``best_worst``: :math:`\\log_2 n(n-1)`; ``line`` with :math:`K` samples:
144
+ :math:`\\log_2 K`.
145
+ """
146
+ n = len(query.items)
147
+ if query.kind == "select":
148
+ if query.n_select:
149
+ return math.log2(math.comb(n, query.n_select))
150
+ return float(n)
151
+ if query.kind == "rank":
152
+ return math.log2(math.factorial(n)) if n > 0 else 0.0
153
+ if query.kind == "rate":
154
+ m = int(round(query.scale[1] - query.scale[0])) + 1
155
+ return n * math.log2(max(m, 2))
156
+ if query.kind == "pairs":
157
+ return len(query.pairs or []) * math.log2(3)
158
+ if query.kind == "best_worst":
159
+ return math.log2(n * (n - 1)) if n > 1 else 0.0
160
+ if query.kind == "line":
161
+ return math.log2(max(n, 2))
162
+ return 1.0
163
+
164
+
165
+ @dataclass
166
+ class Feedback:
167
+ """An evaluator's answer to a :class:`Query`.
168
+
169
+ Only the fields of the query's protocol need to be filled in; the remaining
170
+ ones stay empty. Identifiers refer to :attr:`Individual.id`.
171
+
172
+ Attributes
173
+ ----------
174
+ selected : list of int
175
+ Chosen candidates (``select``; parents in EASY-IEC terms).
176
+ keep : list of int
177
+ Candidates to be carried over unchanged (user-driven elitism).
178
+ ranking : list of int
179
+ Best-to-worst order; a partial ranking lists the top only.
180
+ ratings : dict
181
+ ``{id: score}`` on the query scale.
182
+ pair_results : list of (int, int, float)
183
+ ``(id_a, id_b, outcome)`` with outcome 1 (a wins), 0 (b wins), 0.5 (tie).
184
+ best, worst : int, optional
185
+ ``best_worst`` answers.
186
+ line_index : int, optional
187
+ Index of the chosen sample of a ``line`` query.
188
+ edits : dict
189
+ ``{id: new_genome}`` direct modifications.
190
+ comment : str
191
+ Free text ("brighter, less cluttered"); used for verbal steering.
192
+ confidence : float, optional
193
+ Self-reported confidence in ``[0, 1]``.
194
+ uncertainty : float, optional
195
+ Evaluator-estimated uncertainty in ``[0, 1]`` (disagreement of panel
196
+ members, inconsistency over permutations, ...).
197
+ rationale : str
198
+ Explanation (LLM judges, people who type one).
199
+ stop : bool
200
+ The evaluator is satisfied and ends the session.
201
+ escalated : bool
202
+ The answer was produced by a person after an AI escalation.
203
+ positions : list of int
204
+ Identifiers in the order in which they were displayed.
205
+ cost : dict
206
+ Effort spent (``queries``, ``decisions``, ``tokens_in``, ``tokens_out``,
207
+ ``usd``, ``seconds``, ``human``).
208
+ meta : dict
209
+ Anything else (``true_utility`` of simulated users, raw LLM output,
210
+ member answers of a panel).
211
+ """
212
+
213
+ query_id: int
214
+ kind: str
215
+ evaluator: str = "unknown"
216
+ selected: list[int] = field(default_factory=list)
217
+ keep: list[int] = field(default_factory=list)
218
+ ranking: list[int] = field(default_factory=list)
219
+ ratings: dict[int, float] = field(default_factory=dict)
220
+ pair_results: list[tuple[int, int, float]] = field(default_factory=list)
221
+ best: int | None = None
222
+ worst: int | None = None
223
+ line_index: int | None = None
224
+ edits: dict[int, Any] = field(default_factory=dict)
225
+ comment: str = ""
226
+ confidence: float | None = None
227
+ uncertainty: float | None = None
228
+ rationale: str = ""
229
+ stop: bool = False
230
+ escalated: bool = False
231
+ positions: list[int] = field(default_factory=list)
232
+ cost: dict = field(default_factory=dict)
233
+ meta: dict = field(default_factory=dict)
234
+ timestamp: float = field(default_factory=time.time)
235
+
236
+ # ------------------------------------------------------------------ validation
237
+ def validate(self, query: Query) -> Feedback:
238
+ """Check consistency with ``query`` and return ``self``."""
239
+ if self.kind != query.kind and not (self.kind == "edit" or query.kind == "edit"):
240
+ raise ValueError(f"feedback of kind {self.kind!r} does not answer a {query.kind!r} query")
241
+ ids = set(query.ids)
242
+ for name in ("selected", "keep", "ranking"):
243
+ bad = [i for i in getattr(self, name) if i not in ids]
244
+ if bad:
245
+ raise ValueError(f"{name} refers to unknown individuals {bad}")
246
+ for i in self.ratings:
247
+ if i not in ids:
248
+ raise ValueError(f"rating for unknown individual {i}")
249
+ if self.kind == "select" and query.n_select and not self.stop:
250
+ if len(self.selected) + len(self.keep) == 0:
251
+ raise ValueError("select feedback must choose at least one candidate")
252
+ if self.kind == "line" and self.line_index is not None and not 0 <= self.line_index < len(query.items):
253
+ raise ValueError("line_index out of range")
254
+ return self
255
+
256
+ # ------------------------------------------------------------------ conversions
257
+ def to_pairs(self, query: Query) -> list[tuple[int, int, float]]:
258
+ """Weighted pairwise preferences ``(winner, loser, weight)``.
259
+
260
+ Ties appear in both directions with weight 0.5. ``select`` yields every
261
+ chosen ≻ every unchosen; ``rank`` all ordered pairs of the ranked prefix
262
+ and ranked ≻ unranked; ``rate`` every pair with different scores
263
+ (weight proportional to the score difference); ``best_worst`` best ≻
264
+ others ≻ worst; ``line`` the chosen sample ≻ the other samples; edits add
265
+ edited ≻ original (the edited individual carries ``meta['edited_from']``).
266
+ """
267
+ ids = query.ids
268
+ out: list[tuple[int, int, float]] = []
269
+ k = self.kind
270
+ if k in ("select", "edit"):
271
+ chosen = list(dict.fromkeys(list(self.keep) + list(self.selected)))
272
+ rest = [i for i in ids if i not in chosen]
273
+ out += [(a, b, 1.0) for a in chosen for b in rest]
274
+ elif k == "rank":
275
+ r = [i for i in self.ranking if i in ids]
276
+ rest = [i for i in ids if i not in r]
277
+ out += [(r[a], r[b], 1.0) for a in range(len(r)) for b in range(a + 1, len(r))]
278
+ out += [(a, b, 1.0) for a in r for b in rest]
279
+ elif k == "rate":
280
+ lo, hi = query.scale
281
+ span = max(hi - lo, 1e-12)
282
+ items = [(i, self.ratings[i]) for i in ids if i in self.ratings]
283
+ for (a, ra), (b, rb) in itertools.combinations(items, 2):
284
+ if ra > rb:
285
+ out.append((a, b, (ra - rb) / span))
286
+ elif rb > ra:
287
+ out.append((b, a, (rb - ra) / span))
288
+ elif k == "pairs":
289
+ for a, b, o in self.pair_results:
290
+ if o >= 0.75:
291
+ out.append((a, b, 1.0))
292
+ elif o <= 0.25:
293
+ out.append((b, a, 1.0))
294
+ else:
295
+ out += [(a, b, 0.5), (b, a, 0.5)]
296
+ elif k == "best_worst":
297
+ if self.best is not None:
298
+ out += [(self.best, i, 1.0) for i in ids if i != self.best]
299
+ if self.worst is not None:
300
+ out += [(i, self.worst, 1.0) for i in ids if i not in (self.worst, self.best)]
301
+ elif k == "line":
302
+ if self.line_index is not None:
303
+ w = ids[self.line_index]
304
+ out += [(w, i, 1.0) for i in ids if i != w]
305
+ edited = self.meta.get("edited_individuals", {})
306
+ for old, new in edited.items():
307
+ nid = new.id if isinstance(new, Individual) else int(new)
308
+ out.append((nid, int(old), 1.0))
309
+ return out
310
+
311
+ def utilities(self, query: Query) -> dict[int, float]:
312
+ """A utility in ``[0, 1]`` for every candidate of ``query``.
313
+
314
+ ``select``: 1 for chosen and kept, 0 otherwise; ``rank``: normalized
315
+ Borda score (unranked candidates share the lowest score); ``rate``:
316
+ normalized score; ``pairs``: Copeland score (wins + ties/2 over
317
+ comparisons); ``best_worst``: 1, 0.5, 0; ``line``: closeness in ``t``
318
+ to the chosen sample.
319
+ """
320
+ ids = query.ids
321
+ n = len(ids)
322
+ u = {i: 0.0 for i in ids}
323
+ k = self.kind
324
+ if k in ("select", "edit"):
325
+ for i in list(self.selected) + list(self.keep):
326
+ if i in u:
327
+ u[i] = 1.0
328
+ elif k == "rank":
329
+ r = [i for i in self.ranking if i in u]
330
+ m = len(r)
331
+ for pos, i in enumerate(r):
332
+ u[i] = 1.0 - pos / max(n - 1, 1)
333
+ low = 1.0 - m / max(n - 1, 1) if m < n else 0.0
334
+ for i in ids:
335
+ if i not in r:
336
+ u[i] = max(low, 0.0) * 0.5
337
+ elif k == "rate":
338
+ lo, hi = query.scale
339
+ vals = {i: self.ratings.get(i, np.nan) for i in ids}
340
+ fill = np.nanmean(list(vals.values())) if any(not np.isnan(v) for v in vals.values()) else (lo + hi) / 2
341
+ for i in ids:
342
+ v = vals[i] if not np.isnan(vals[i]) else fill
343
+ u[i] = float(np.clip((v - lo) / max(hi - lo, 1e-12), 0, 1))
344
+ elif k == "pairs":
345
+ wins = {i: 0.0 for i in ids}
346
+ cnt = {i: 0 for i in ids}
347
+ for a, b, o in self.pair_results:
348
+ wins[a] = wins.get(a, 0.0) + o
349
+ wins[b] = wins.get(b, 0.0) + (1.0 - o)
350
+ cnt[a] = cnt.get(a, 0) + 1
351
+ cnt[b] = cnt.get(b, 0) + 1
352
+ for i in ids:
353
+ u[i] = wins[i] / cnt[i] if cnt[i] else 0.5
354
+ elif k == "best_worst":
355
+ for i in ids:
356
+ u[i] = 0.5
357
+ if self.best is not None:
358
+ u[self.best] = 1.0
359
+ if self.worst is not None:
360
+ u[self.worst] = 0.0
361
+ elif k == "line":
362
+ t = query.line_t if query.line_t is not None else np.linspace(0, 1, n)
363
+ if self.line_index is not None:
364
+ t0 = t[self.line_index]
365
+ for j, i in enumerate(ids):
366
+ u[i] = float(1.0 - abs(t[j] - t0))
367
+ return u
368
+
369
+ def order(self, query: Query) -> list[int]:
370
+ """Candidates from best to worst (ties broken by display order)."""
371
+ u = self.utilities(query)
372
+ ids = query.ids
373
+ if self.kind == "rank" and self.ranking:
374
+ r = [i for i in self.ranking if i in u]
375
+ return r + [i for i in ids if i not in r]
376
+ return sorted(ids, key=lambda i: (-u[i], ids.index(i)))
377
+
378
+ def chosen(self, query: Query) -> list[int]:
379
+ """The 'winners': selected/kept, the ranked top, the best, the line choice, pair winners."""
380
+ if self.kind in ("select", "edit"):
381
+ return list(dict.fromkeys(list(self.keep) + list(self.selected)))
382
+ if self.kind == "rank":
383
+ return self.ranking[: max(1, len(self.ranking) // 2)] if self.ranking else []
384
+ if self.kind == "best_worst":
385
+ return [self.best] if self.best is not None else []
386
+ if self.kind == "line":
387
+ return [query.ids[self.line_index]] if self.line_index is not None else []
388
+ u = self.utilities(query)
389
+ m = max(u.values()) if u else 0
390
+ return [i for i in query.ids if u[i] >= m - 1e-12]
391
+
392
+ def summary(self) -> str:
393
+ parts = [f"{self.kind} by {self.evaluator}"]
394
+ if self.selected:
395
+ parts.append(f"selected={self.selected}")
396
+ if self.keep:
397
+ parts.append(f"keep={self.keep}")
398
+ if self.ranking:
399
+ parts.append(f"ranking={self.ranking[:6]}")
400
+ if self.ratings:
401
+ parts.append(f"ratings={{{', '.join(f'{k}: {v:.3g}' for k, v in list(self.ratings.items())[:6])}}}")
402
+ if self.pair_results:
403
+ parts.append(f"{len(self.pair_results)} pairs")
404
+ if self.best is not None:
405
+ parts.append(f"best={self.best} worst={self.worst}")
406
+ if self.line_index is not None:
407
+ parts.append(f"line_index={self.line_index}")
408
+ if self.uncertainty is not None:
409
+ parts.append(f"uncertainty={self.uncertainty:.2f}")
410
+ if self.escalated:
411
+ parts.append("escalated")
412
+ return ", ".join(parts)
413
+
414
+ def to_dict(self) -> dict:
415
+ def conv(v):
416
+ if isinstance(v, np.ndarray):
417
+ return v.tolist()
418
+ if isinstance(v, (np.floating, np.integer)):
419
+ return v.item()
420
+ if isinstance(v, Individual):
421
+ return v.id
422
+ if isinstance(v, dict):
423
+ return {str(k): conv(x) for k, x in v.items()}
424
+ if isinstance(v, (list, tuple)):
425
+ return [conv(x) for x in v]
426
+ return v
427
+ d = {k: conv(getattr(self, k)) for k in self.__dataclass_fields__}
428
+ d["meta"] = {k: conv(v) for k, v in self.meta.items() if not k.startswith("_") and k != "members"}
429
+ return d
430
+
431
+ @classmethod
432
+ def from_dict(cls, d: dict) -> Feedback:
433
+ d = dict(d)
434
+ d["ratings"] = {int(k): float(v) for k, v in d.get("ratings", {}).items()}
435
+ d["edits"] = {int(k): (np.asarray(v) if isinstance(v, list) else v) for k, v in d.get("edits", {}).items()}
436
+ d["pair_results"] = [tuple(p) for p in d.get("pair_results", [])]
437
+ return cls(**{k: v for k, v in d.items() if k in cls.__dataclass_fields__})