Source code for qdpy.algorithms.ideagent

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Evolve distinct ideas through bounded lineage repair and refinement.
# @see https://arxiv.org/abs/2607.22375

"""Provider-independent IDEAgent controller and exact thresholded Yield."""

from collections import Counter, deque
from dataclasses import dataclass
from itertools import combinations
from operator import index

import numpy as np

from .modern import _positive_int

__all__ = ["IDEAgent", "IdeaAssessment", "IdeaEntry", "IdeaRequest", "IdeaStats", "idea_yield"]


## @brief Record comparable scores and a signature of the central mechanism.
[docs] @dataclass(frozen=True) class IdeaAssessment: """Scores lie in [0, 1]. Feedback can carry observations from the evaluator.""" signature: str non_obviousness: float soundness: float clarity: float feasibility: float feedback: str = "" valid: bool = True disputed: bool = False @property def scores(self): """Return the three scores that determine qualification.""" return self.non_obviousness, self.soundness, self.clarity @property def quality(self): """Use the paper's weighted quality, with feasibility as a separate tie-break.""" return .7 * self.non_obviousness + .2 * self.soundness + .1 * self.clarity
## @brief One measured draft and the lineage to which it belongs.
[docs] @dataclass(frozen=True) class IdeaEntry: """Keep the caller's immutable candidate and its measurements.""" idea: object assessment: IdeaAssessment lineage: int
## @brief Input to the proposer for a seed, repair or refinement.
[docs] @dataclass(frozen=True) class IdeaRequest: """Pass active ideas and compact historical and rejection memory.""" stage: str parent: IdeaEntry | None active: tuple[IdeaEntry, ...] historical: tuple[tuple[int, str], ...] rejected: tuple[str, ...]
## @brief Account for proposal, evaluation and similarity calls.
[docs] @dataclass(frozen=True) class IdeaStats: """Track every attempted callback and archive admission.""" proposals: int = 0 evaluations: int = 0 comparisons: int = 0 repairs: int = 0 refinements: int = 0 refinement_checks: int = 0 admissions: int = 0 rejected: int = 0
def _thresholds(values): values = tuple(map(float, values)) if len(values) != 3 or any(not 0. <= value <= 1. for value in values): raise ValueError("Supply three thresholds in [0, 1].") return values def _qualified(assessment, thresholds): return (assessment.valid and not assessment.disputed and all(score >= threshold for score, threshold in zip(assessment.scores, thresholds, strict=True))) def _similarity(similarity, first, second): score = float(similarity(first, second)) if not 0. <= score <= 1.: raise ValueError("Return finite similarity in [0, 1].") return score ## @brief Compute the largest mutually diverse subset of qualified assessments.
[docs] def idea_yield(assessments, similarity, *, thresholds=(.6, .6, .6), duplicate_threshold=.8): """Return the exact cardinality for a small evaluated set. Each pair in the selected set must have similarity strictly below duplicate_threshold. The maximum clique search can be exponential. The similarity callback should be symmetric and accept signatures. """ thresholds = _thresholds(thresholds) if not callable(similarity) or not 0. <= duplicate_threshold <= 1.: raise ValueError("Supply a similarity callback and a duplicate threshold in [0, 1].") signatures = [row.signature for row in assessments if _qualified(row, thresholds)] neighbors = [set() for _ in signatures] for first, second in combinations(range(len(signatures)), 2): if _similarity(similarity, signatures[first], signatures[second]) < duplicate_threshold: neighbors[first].add(second) neighbors[second].add(first) best = 0 def visit(remaining, size): nonlocal best best = max(best, size) while size + len(remaining) > best: candidate = remaining.pop() visit(remaining & neighbors[candidate], size + 1) visit(set(range(len(signatures))), 0) return best
## @brief Maintain qualified mechanisms and improve them with measured revisions.
[docs] class IDEAgent: """Run the IDEAgent lineage workflow with caller-supplied proposal and evaluation. :param capacity: Maximum accepted lineages. :param thresholds: Inclusive non-obviousness, soundness and clarity gates. :param refinement_targets: Try improving accepted entries below these scores. :param repair_margin: Maximum deficit for a draft eligible for repair. :param duplicate_threshold: Similarity at which two signatures share a mechanism. :param auxiliary_attempts: Total repairs and refinements allowed per fresh draft. :param memory_size: Maximum history signatures and rejected signatures in each store. :param seed: Private seed supplied to the proposer. """ def __init__(self, *, capacity=10, thresholds=(.6, .6, .6), refinement_targets=(.9, .8, .8), repair_margin=.2, duplicate_threshold=.8, auxiliary_attempts=2, memory_size=32, seed=0): self._capacity = _positive_int(capacity, "capacity") self._thresholds, self._targets = _thresholds(thresholds), _thresholds(refinement_targets) self._auxiliary = index(auxiliary_attempts) if not (0. <= repair_margin <= 1. and 0. <= duplicate_threshold <= 1. and self._auxiliary >= 0): raise ValueError("Use thresholds and margins in [0, 1] and a nonnegative auxiliary cap.") self._margin, self._duplicate = repair_margin, duplicate_threshold memory_size = _positive_int(memory_size, "memory_size") self._history, self._rejected = deque(maxlen=memory_size), deque(maxlen=memory_size) self._active = {} self._counts = Counter() self._rng = np.random.default_rng(seed) @property def entries(self): """Return accepted ideas in lineage admission order.""" return tuple(self._active.values()) @property def stats(self): """Return cumulative call and admission counts.""" return IdeaStats(**self._counts) def _draft(self, stage, parent, propose, evaluate, lineage): request = IdeaRequest(stage, parent, self.entries, tuple(self._history), tuple(self._rejected)) self._counts["proposals"] += 1 if stage != "seed": self._counts["repairs" if stage == "repair" else "refinements"] += 1 idea = propose(request, self._rng) if idea is None: self._reject() return None self._counts["evaluations"] += 1 result = evaluate(idea) if (not isinstance(result, IdeaAssessment) or not isinstance(result.signature, str) or not result.signature or any(not 0. <= score <= 1. for score in (*result.scores, result.feasibility))): raise ValueError("Return an IdeaAssessment with a signature and scores in [0, 1].") return IdeaEntry(idea, result, lineage) def _matches(self, signature, other, similarity): self._counts["comparisons"] += 1 return _similarity(similarity, signature, other) >= self._duplicate def _reject(self, entry=None): self._counts["rejected"] += 1 if entry is not None: self._rejected.append(entry.assessment.signature) @staticmethod def _rank(entry): return entry.assessment.quality, entry.assessment.feasibility def _admit(self, draft): old = self._active.get(draft.lineage) if old is None and len(self._active) == self._capacity: old = min(self.entries, key=self._rank) if old is not None: if self._rank(draft) <= self._rank(old): return False self._history.append((old.lineage, old.assessment.signature)) if old.lineage != draft.lineage: del self._active[old.lineage] self._active[draft.lineage] = draft self._counts["admissions"] += 1 return True def _route(self, draft, similarity, parent=None): if not draft.assessment.valid: return None signature = draft.assessment.signature matches = [old.lineage for old in self.entries if self._matches(signature, old.assessment.signature, similarity)] if parent is not None: if (any(lineage != parent.lineage for lineage in matches) or parent.lineage not in matches and not self._matches(signature, parent.assessment.signature, similarity)): return None elif len(matches) > 1: return None if not matches and any(lineage != draft.lineage and self._matches(signature, old, similarity) for lineage, old in self._history): return None lineage = matches[0] if matches else draft.lineage return IdeaEntry(draft.idea, draft.assessment, lineage) ## @brief Spend proposal calls on seeds and their bounded repair/refinement chains.
[docs] def run(self, propose, evaluate, similarity, *, budget, refinement_preference=None): """Continue search with an exact cap covering every proposal stage. :param propose: Callback (IdeaRequest, rng) returning an immutable draft or None. :param evaluate: Callback (draft) returning an IdeaAssessment. Fitness scores, judgment panels and compact signatures are evaluator concerns. :param similarity: Symmetric callback (signature, signature) returning [0, 1]. :param budget: Maximum additional drafts, including repairs and refinements. :param refinement_preference: Optional callback (parent, revision) returning whether an otherwise eligible refinement should replace its parent. Use it for an independent comparison, such as judging both presentation orders. """ if not all(map(callable, (propose, evaluate, similarity))): raise ValueError("Supply proposal, assessment and similarity callbacks.") if refinement_preference is not None and not callable(refinement_preference): raise ValueError("Supply a callable refinement preference.") stop = self.stats.proposals + _positive_int(budget, "budget") while self.stats.proposals < stop: seed = self._draft("seed", None, propose, evaluate, self.stats.proposals) if seed is None: continue draft = self._route(seed, similarity) auxiliary = self._auxiliary if (draft is not None and draft.lineage == seed.lineage and draft.assessment.valid and not _qualified(draft.assessment, self._thresholds) and auxiliary and self.stats.proposals < stop and all(score + self._margin >= threshold or (index == 1 and draft.assessment.disputed) for index, (score, threshold) in enumerate(zip(draft.assessment.scores, self._thresholds)))): repair = self._draft("repair", draft, propose, evaluate, draft.lineage) auxiliary -= 1 if repair is None: continue draft = self._route(repair, similarity, draft) seed = repair if draft is None or not _qualified(draft.assessment, self._thresholds) or not self._admit(draft): self._reject(seed) continue for _ in range(auxiliary): if (self.stats.proposals == stop or all(score >= target for score, target in zip(draft.assessment.scores, self._targets))): break child = self._draft("refine", draft, propose, evaluate, draft.lineage) if child is None: break measured = self._route(child, similarity, draft) if (measured is None or not _qualified(measured.assessment, self._thresholds) or measured.assessment.non_obviousness < draft.assessment.non_obviousness or self._rank(measured) <= self._rank(draft)): self._reject(child) break if refinement_preference is not None: self._counts["refinement_checks"] += 1 if not refinement_preference(draft, measured): self._reject(child) break self._admit(measured) draft = measured return self.stats