QDpy
Loading...
Searching...
No Matches
qdaif.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Illuminate qualitative text using separate proposal and judgment callbacks."""
6
7from dataclasses import dataclass
8from math import isfinite
9from operator import index
10
11import numpy as np
12
13from qdpy.containers import CVTGrid, Grid
14from qdpy.phenotype import Features, Fitness, Individual
15
16__all__ = ["QDAIF", "QDAIFStats"]
17
18
19
20@dataclass(frozen=True)
22 """Cumulative counts across runs, including callbacks that raise."""
23
24 proposals: int
25 judgments: int
26 duplicates: int
27 admissions: int
28
29
30
31class QDAIF:
32 """QDAIF with caller-supplied generation and grading.
33
34 Use a one-elite Grid or CVTGrid with one maximized objective. Each
35 archived individual contains one string. Propose receives a tuple
36 of parent texts and this search's NumPy generator. Judge returns a
37 scalar quality and a descriptor vector. Exact text matches reuse
38 the first successful judgment. Keep the rubric fixed across calls.
39
40 Set parent_count to zero for independent sampling. Otherwise
41 parents are sampled uniformly from occupied cells without
42 replacement, up to the requested number.
43 """
44
45 def __init__(self, archive, *, parent_count=1, seed=None):
46 if (type(archive) not in (Grid, CVTGrid) or archive.max_items_per_bin != 1
47 or len(archive.fitness_domain) != 1 or archive.parents):
48 raise ValueError("Provide a parentless scalar, one-elite Grid or CVTGrid.")
49 self.archive = archive
50 self.parent_count = index(parent_count)
51 if self.parent_count < 0:
52 raise ValueError("parent_count must be nonnegative.")
53 self._seen = set()
54 for entry in archive:
55 if len(entry) != 1 or tuple(entry.fitness.weights) != (1.,):
56 raise ValueError("Existing elites must contain one text and maximize fitness.")
57 self._seen.add(self._text(entry[0]))
58 archive._set_fitness_weights((1.,))
59 self._rng = np.random.default_rng(seed)
60 self._proposals = self._judgments = self._duplicates = self._admissions = 0
61
62 @staticmethod
63 def _text(text):
64 if not isinstance(text, str) or not text.strip():
65 raise ValueError("Each candidate must be a nonempty string.")
66 return text
67
68 @property
69 def stats(self):
70 """Return immutable accounting through the latest callback."""
71 return QDAIFStats(self._proposals, self._judgments, self._duplicates, self._admissions)
72
73 @property
74 def best(self):
75 """Return the best archived text, or None for an empty archive."""
76 return self.archive.best[0] if len(self.archive) else None
77
78 def _judge(self, text, judge):
79 text = self._text(text)
80 if text in self._seen:
81 self._duplicates += 1
82 return
83 self._judgments += 1
84 quality, descriptor = judge(text)
85 quality, descriptor = float(quality), tuple(map(float, descriptor))
86 if not isfinite(quality) or not all(map(isfinite, descriptor)):
87 raise ValueError("Judge must return finite quality and descriptors.")
88 individual = Individual([text], fitness=Fitness((quality,), weights=(1.,)), features=Features(descriptor))
89 self.archive._check_if_can_be_added(individual)
90 cell = self.archive.index_grid(individual)
91 before = self.archive.nb_added
92 if self.archive.free or self.archive.solutions[cell]:
93 self.archive.add(individual)
94 self._admissions += self.archive.nb_added - before
95 self._seen.add(text)
96
97
98 def run(self, propose, judge, *, proposal_budget, judgment_budget, initial=()):
99 """Evaluate seed texts first, then propose and judge new texts.
100
101 Seeds spend judgment calls only. Duplicate proposals still
102 spend proposal calls. Stop when either call budget is exhausted.
103 Malformed feedback or a callback error propagates to the caller.
104 """
105 proposals, judgments = index(proposal_budget), index(judgment_budget)
106 if min(proposals, judgments) < 0 or not callable(propose) or not callable(judge):
107 raise ValueError("Use nonnegative budgets and callable propose and judge.")
108 if isinstance(initial, str):
109 raise TypeError("initial must be a sequence of candidate texts.")
110 initial = tuple(map(self._text, initial))
111 if len(set(initial) - self._seen) > judgments:
112 raise ValueError("The judgment budget cannot cover all new seed texts.")
113 start = self._judgments
114 for text in initial:
115 self._judge(text, judge)
116 for _ in range(proposals):
117 if self._judgments - start == judgments:
118 break
119 count = min(self.parent_count, len(self.archive))
120 slots = self._rng.choice(len(self.archive), size=count, replace=False) if count else ()
121 parents = tuple(self.archive[i][0] for i in slots)
122 self._proposals += 1
123 self._judge(propose(parents, self._rng), judge)
124 return self.stats
Count proposal calls, judgment calls, duplicate texts, and admissions.
Definition qdaif.py:21
Evolve text under a fixed qualitative rubric.
Definition qdaif.py:31
_judge(self, text, judge)
Definition qdaif.py:78
run(self, propose, judge, *, proposal_budget, judgment_budget, initial=())
Spend additional proposal and judgment call budgets.
Definition qdaif.py:98
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405