QDpy
Loading...
Searching...
No Matches
ideagent.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Provider-independent IDEAgent controller and exact thresholded Yield."""
7
8from collections import Counter, deque
9from dataclasses import dataclass
10from itertools import combinations
11from operator import index
12
13import numpy as np
14
15from .modern import _positive_int
16
17__all__ = ["IDEAgent", "IdeaAssessment", "IdeaEntry", "IdeaRequest", "IdeaStats", "idea_yield"]
18
19
20
21@dataclass(frozen=True)
23 """Scores lie in [0, 1]. Feedback can carry observations from the evaluator."""
24
25 signature: str
26 non_obviousness: float
27 soundness: float
28 clarity: float
29 feasibility: float
30 feedback: str = ""
31 valid: bool = True
32 disputed: bool = False
33
34 @property
35 def scores(self):
36 """Return the three scores that determine qualification."""
37 return self.non_obviousness, self.soundness, self.clarity
38
39 @property
40 def quality(self):
41 """Use the paper's weighted quality, with feasibility as a separate tie-break."""
42 return .7 * self.non_obviousness + .2 * self.soundness + .1 * self.clarity
43
44
45
46@dataclass(frozen=True)
48 """Keep the caller's immutable candidate and its measurements."""
49
50 idea: object
51 assessment: IdeaAssessment
52 lineage: int
53
54
55
56@dataclass(frozen=True)
58 """Pass active ideas and compact historical and rejection memory."""
59
60 stage: str
61 parent: IdeaEntry | None
62 active: tuple[IdeaEntry, ...]
63 historical: tuple[tuple[int, str], ...]
64 rejected: tuple[str, ...]
65
66
67
68@dataclass(frozen=True)
70 """Track every attempted callback and archive admission."""
71
72 proposals: int = 0
73 evaluations: int = 0
74 comparisons: int = 0
75 repairs: int = 0
76 refinements: int = 0
77 refinement_checks: int = 0
78 admissions: int = 0
79 rejected: int = 0
80
81
82def _thresholds(values):
83 values = tuple(map(float, values))
84 if len(values) != 3 or any(not 0. <= value <= 1. for value in values):
85 raise ValueError("Supply three thresholds in [0, 1].")
86 return values
87
88
89def _qualified(assessment, thresholds):
90 return (assessment.valid and not assessment.disputed
91 and all(score >= threshold for score, threshold in zip(assessment.scores, thresholds, strict=True)))
92
93
94def _similarity(similarity, first, second):
95 score = float(similarity(first, second))
96 if not 0. <= score <= 1.:
97 raise ValueError("Return finite similarity in [0, 1].")
98 return score
99
100
101
102def idea_yield(assessments, similarity, *, thresholds=(.6, .6, .6), duplicate_threshold=.8):
103 """Return the exact cardinality for a small evaluated set.
104
105 Each pair in the selected set must have similarity strictly below
106 duplicate_threshold. The maximum clique search can be exponential.
107 The similarity callback should be symmetric and accept signatures.
108 """
109 thresholds = _thresholds(thresholds)
110 if not callable(similarity) or not 0. <= duplicate_threshold <= 1.:
111 raise ValueError("Supply a similarity callback and a duplicate threshold in [0, 1].")
112 signatures = [row.signature for row in assessments if _qualified(row, thresholds)]
113 neighbors = [set() for _ in signatures]
114 for first, second in combinations(range(len(signatures)), 2):
115 if _similarity(similarity, signatures[first], signatures[second]) < duplicate_threshold:
116 neighbors[first].add(second)
117 neighbors[second].add(first)
118 best = 0
119
120 def visit(remaining, size):
121 nonlocal best
122 best = max(best, size)
123 while size + len(remaining) > best:
124 candidate = remaining.pop()
125 visit(remaining & neighbors[candidate], size + 1)
126
127 visit(set(range(len(signatures))), 0)
128 return best
129
130
131
133 """Run the IDEAgent lineage workflow with caller-supplied proposal and evaluation.
134
135 :param capacity: Maximum accepted lineages.
136 :param thresholds: Inclusive non-obviousness, soundness and clarity gates.
137 :param refinement_targets: Try improving accepted entries below these scores.
138 :param repair_margin: Maximum deficit for a draft eligible for repair.
139 :param duplicate_threshold: Similarity at which two signatures share a mechanism.
140 :param auxiliary_attempts: Total repairs and refinements allowed per fresh draft.
141 :param memory_size: Maximum history signatures and rejected signatures in each store.
142 :param seed: Private seed supplied to the proposer.
143 """
144
145 def __init__(self, *, capacity=10, thresholds=(.6, .6, .6), refinement_targets=(.9, .8, .8),
146 repair_margin=.2, duplicate_threshold=.8, auxiliary_attempts=2, memory_size=32, seed=0):
147 self._capacity = _positive_int(capacity, "capacity")
148 self._thresholds, self._targets = _thresholds(thresholds), _thresholds(refinement_targets)
149 self._auxiliary = index(auxiliary_attempts)
150 if not (0. <= repair_margin <= 1. and 0. <= duplicate_threshold <= 1. and self._auxiliary >= 0):
151 raise ValueError("Use thresholds and margins in [0, 1] and a nonnegative auxiliary cap.")
152 self._margin, self._duplicate = repair_margin, duplicate_threshold
153 memory_size = _positive_int(memory_size, "memory_size")
154 self._history, self._rejected = deque(maxlen=memory_size), deque(maxlen=memory_size)
155 self._active = {}
156 self._counts = Counter()
157 self._rng = np.random.default_rng(seed)
158
159 @property
160 def entries(self):
161 """Return accepted ideas in lineage admission order."""
162 return tuple(self._active.values())
163
164 @property
165 def stats(self):
166 """Return cumulative call and admission counts."""
167 return IdeaStats(**self._counts)
168
169 def _draft(self, stage, parent, propose, evaluate, lineage):
170 request = IdeaRequest(stage, parent, self.entries, tuple(self._history), tuple(self._rejected))
171 self._counts["proposals"] += 1
172 if stage != "seed":
173 self._counts["repairs" if stage == "repair" else "refinements"] += 1
174 idea = propose(request, self._rng)
175 if idea is None:
176 self._reject()
177 return None
178 self._counts["evaluations"] += 1
179 result = evaluate(idea)
180 if (not isinstance(result, IdeaAssessment) or not isinstance(result.signature, str)
181 or not result.signature or any(not 0. <= score <= 1. for score in (*result.scores, result.feasibility))):
182 raise ValueError("Return an IdeaAssessment with a signature and scores in [0, 1].")
183 return IdeaEntry(idea, result, lineage)
184
185 def _matches(self, signature, other, similarity):
186 self._counts["comparisons"] += 1
187 return _similarity(similarity, signature, other) >= self._duplicate
188
189 def _reject(self, entry=None):
190 self._counts["rejected"] += 1
191 if entry is not None:
192 self._rejected.append(entry.assessment.signature)
193
194 @staticmethod
195 def _rank(entry):
196 return entry.assessment.quality, entry.assessment.feasibility
197
198 def _admit(self, draft):
199 old = self._active.get(draft.lineage)
200 if old is None and len(self._active) == self._capacity:
201 old = min(self.entries, key=self._rank)
202 if old is not None:
203 if self._rank(draft) <= self._rank(old):
204 return False
205 self._history.append((old.lineage, old.assessment.signature))
206 if old.lineage != draft.lineage:
207 del self._active[old.lineage]
208 self._active[draft.lineage] = draft
209 self._counts["admissions"] += 1
210 return True
211
212 def _route(self, draft, similarity, parent=None):
213 if not draft.assessment.valid:
214 return None
215 signature = draft.assessment.signature
216 matches = [old.lineage for old in self.entries
217 if self._matches(signature, old.assessment.signature, similarity)]
218 if parent is not None:
219 if (any(lineage != parent.lineage for lineage in matches)
220 or parent.lineage not in matches
221 and not self._matches(signature, parent.assessment.signature, similarity)):
222 return None
223 elif len(matches) > 1:
224 return None
225 if not matches and any(lineage != draft.lineage and self._matches(signature, old, similarity)
226 for lineage, old in self._history):
227 return None
228 lineage = matches[0] if matches else draft.lineage
229 return IdeaEntry(draft.idea, draft.assessment, lineage)
230
231
232 def run(self, propose, evaluate, similarity, *, budget, refinement_preference=None):
233 """Continue search with an exact cap covering every proposal stage.
234
235 :param propose: Callback (IdeaRequest, rng) returning an immutable draft or None.
236 :param evaluate: Callback (draft) returning an IdeaAssessment. Fitness
237 scores, judgment panels and compact signatures are evaluator concerns.
238 :param similarity: Symmetric callback (signature, signature) returning [0, 1].
239 :param budget: Maximum additional drafts, including repairs and refinements.
240 :param refinement_preference: Optional callback (parent, revision) returning
241 whether an otherwise eligible refinement should replace its parent.
242 Use it for an independent comparison, such as judging both presentation orders.
243 """
244 if not all(map(callable, (propose, evaluate, similarity))):
245 raise ValueError("Supply proposal, assessment and similarity callbacks.")
246 if refinement_preference is not None and not callable(refinement_preference):
247 raise ValueError("Supply a callable refinement preference.")
248 stop = self.stats.proposals + _positive_int(budget, "budget")
249 while self.stats.proposals < stop:
250 seed = self._draft("seed", None, propose, evaluate, self.stats.proposals)
251 if seed is None:
252 continue
253 draft = self._route(seed, similarity)
254 auxiliary = self._auxiliary
255 if (draft is not None and draft.lineage == seed.lineage
256 and draft.assessment.valid and not _qualified(draft.assessment, self._thresholds)
257 and auxiliary and self.stats.proposals < stop
258 and all(score + self._margin >= threshold or (index == 1 and draft.assessment.disputed)
259 for index, (score, threshold) in enumerate(zip(draft.assessment.scores, self._thresholds)))):
260 repair = self._draft("repair", draft, propose, evaluate, draft.lineage)
261 auxiliary -= 1
262 if repair is None:
263 continue
264 draft = self._route(repair, similarity, draft)
265 seed = repair
266 if draft is None or not _qualified(draft.assessment, self._thresholds) or not self._admit(draft):
267 self._reject(seed)
268 continue
269 for _ in range(auxiliary):
270 if (self.stats.proposals == stop or all(score >= target for score, target in
271 zip(draft.assessment.scores, self._targets))):
272 break
273 child = self._draft("refine", draft, propose, evaluate, draft.lineage)
274 if child is None:
275 break
276 measured = self._route(child, similarity, draft)
277 if (measured is None or not _qualified(measured.assessment, self._thresholds)
278 or measured.assessment.non_obviousness < draft.assessment.non_obviousness
279 or self._rank(measured) <= self._rank(draft)):
280 self._reject(child)
281 break
282 if refinement_preference is not None:
283 self._counts["refinement_checks"] += 1
284 if not refinement_preference(draft, measured):
285 self._reject(child)
286 break
287 self._admit(measured)
288 draft = measured
289 return self.stats
Maintain qualified mechanisms and improve them with measured revisions.
Definition ideagent.py:132
run(self, propose, evaluate, similarity, *, budget, refinement_preference=None)
Spend proposal calls on seeds and their bounded repair/refinement chains.
Definition ideagent.py:232
_draft(self, stage, parent, propose, evaluate, lineage)
Definition ideagent.py:169
_route(self, draft, similarity, parent=None)
Definition ideagent.py:212
_matches(self, signature, other, similarity)
Definition ideagent.py:185
Record comparable scores and a signature of the central mechanism.
Definition ideagent.py:22
One measured draft and the lineage to which it belongs.
Definition ideagent.py:47
Input to the proposer for a seed, repair or refinement.
Definition ideagent.py:57
Account for proposal, evaluation and similarity calls.
Definition ideagent.py:69