# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Provider-independent quality-diversity through AI feedback.
"""Illuminate qualitative text using separate proposal and judgment callbacks."""
from dataclasses import dataclass
from math import isfinite
from operator import index
import numpy as np
from qdpy.containers import CVTGrid, Grid
from qdpy.phenotype import Features, Fitness, Individual
__all__ = ["QDAIF", "QDAIFStats"]
## @brief Count proposal calls, judgment calls, duplicate texts, and admissions.
[docs]
@dataclass(frozen=True)
class QDAIFStats:
"""Cumulative counts across runs, including callbacks that raise."""
proposals: int
judgments: int
duplicates: int
admissions: int
## @brief Evolve text under a fixed qualitative rubric.
[docs]
class QDAIF:
"""QDAIF with caller-supplied generation and grading.
Use a one-elite Grid or CVTGrid with one maximized objective. Each
archived individual contains one string. Propose receives a tuple
of parent texts and this search's NumPy generator. Judge returns a
scalar quality and a descriptor vector. Exact text matches reuse
the first successful judgment. Keep the rubric fixed across calls.
Set parent_count to zero for independent sampling. Otherwise
parents are sampled uniformly from occupied cells without
replacement, up to the requested number.
"""
def __init__(self, archive, *, parent_count=1, seed=None):
if (type(archive) not in (Grid, CVTGrid) or archive.max_items_per_bin != 1
or len(archive.fitness_domain) != 1 or archive.parents):
raise ValueError("Provide a parentless scalar, one-elite Grid or CVTGrid.")
self.archive = archive
self.parent_count = index(parent_count)
if self.parent_count < 0:
raise ValueError("parent_count must be nonnegative.")
self._seen = set()
for entry in archive:
if len(entry) != 1 or tuple(entry.fitness.weights) != (1.,):
raise ValueError("Existing elites must contain one text and maximize fitness.")
self._seen.add(self._text(entry[0]))
archive._set_fitness_weights((1.,))
self._rng = np.random.default_rng(seed)
self._proposals = self._judgments = self._duplicates = self._admissions = 0
@staticmethod
def _text(text):
if not isinstance(text, str) or not text.strip():
raise ValueError("Each candidate must be a nonempty string.")
return text
@property
def stats(self):
"""Return immutable accounting through the latest callback."""
return QDAIFStats(self._proposals, self._judgments, self._duplicates, self._admissions)
@property
def best(self):
"""Return the best archived text, or None for an empty archive."""
return self.archive.best[0] if len(self.archive) else None
def _judge(self, text, judge):
text = self._text(text)
if text in self._seen:
self._duplicates += 1
return
self._judgments += 1
quality, descriptor = judge(text)
quality, descriptor = float(quality), tuple(map(float, descriptor))
if not isfinite(quality) or not all(map(isfinite, descriptor)):
raise ValueError("Judge must return finite quality and descriptors.")
individual = Individual([text], fitness=Fitness((quality,), weights=(1.,)), features=Features(descriptor))
self.archive._check_if_can_be_added(individual)
cell = self.archive.index_grid(individual)
before = self.archive.nb_added
if self.archive.free or self.archive.solutions[cell]:
self.archive.add(individual)
self._admissions += self.archive.nb_added - before
self._seen.add(text)
## @brief Spend additional proposal and judgment call budgets.
[docs]
def run(self, propose, judge, *, proposal_budget, judgment_budget, initial=()):
"""Evaluate seed texts first, then propose and judge new texts.
Seeds spend judgment calls only. Duplicate proposals still
spend proposal calls. Stop when either call budget is exhausted.
Malformed feedback or a callback error propagates to the caller.
"""
proposals, judgments = index(proposal_budget), index(judgment_budget)
if min(proposals, judgments) < 0 or not callable(propose) or not callable(judge):
raise ValueError("Use nonnegative budgets and callable propose and judge.")
if isinstance(initial, str):
raise TypeError("initial must be a sequence of candidate texts.")
initial = tuple(map(self._text, initial))
if len(set(initial) - self._seen) > judgments:
raise ValueError("The judgment budget cannot cover all new seed texts.")
start = self._judgments
for text in initial:
self._judge(text, judge)
for _ in range(proposals):
if self._judgments - start == judgments:
break
count = min(self.parent_count, len(self.archive))
slots = self._rng.choice(len(self.archive), size=count, replace=False) if count else ()
parents = tuple(self.archive[i][0] for i in slots)
self._proposals += 1
self._judge(propose(parents, self._rng), judge)
return self.stats