QDpy
Loading...
Searching...
No Matches
counterexample_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Search for verified elites and use failed scenarios to screen later proposals."""
7
8from collections import Counter
9from dataclasses import dataclass
10from operator import index
11
12import numpy as np
13
14from .task_search import _measurement, _offer, _validate_grid
15
16__all__ = ["CounterexampleMAPElites", "CounterexampleQDStats"]
17
18
19def _nonnegative_limit(value, name):
20 value = index(value)
21 if value < 0:
22 raise ValueError(f"{name} must be nonnegative.")
23 return value
24
25
26
27@dataclass(frozen=True)
29 """Counters checked independently against per-run proposal and verification budgets.
30
31 :param proposals: Attempted proposals, including failures before measurement.
32 :param measurements: Attempts to measure nominal quality and descriptors.
33 :param checks: Attempts to verify a design on a single scenario.
34 :param rejected: Designs ruled out by a failing check.
35 :param verified: Designs that passed every scenario.
36 :param archive_updates: Insertions and improvements to the certified archive.
37 :param counterexamples: Newly discovered failing scenarios added to screening.
38 :param inconclusive_checks: Checks that returned None and need to be retried.
39 """
40
41 proposals: int = 0
42 measurements: int = 0
43 checks: int = 0
44 rejected: int = 0
45 verified: int = 0
46 archive_updates: int = 0
47 counterexamples: int = 0
48 inconclusive_checks: int = 0
49
50
51@dataclass
53 measurement: tuple
54 scenarios: tuple
55 position: int = 0
56
57
58
60 """Run counterexample-guided MAP-Elites over a fixed finite scenario universe.
61
62 :param archive: Empty, best-only scalar Grid or CVTGrid. This archive
63 is owned by the search for the duration of verification.
64 :param scenarios: Nonempty ordered collection of distinct hashable cases.
65 :param propose: Callback (rng) producing an initial iterable genome.
66 :param mutate: Callback (parent_tuple, rng) producing an offspring genome.
67 :param measure: Callback (genome) returning ((fitness,), descriptors).
68 The measurement fixes the candidate's niche and its quality.
69 :param verify: Callback (genome, scenario) returning True on success,
70 False on a counterexample, or None when the result is inconclusive.
71 :param initial_scenarios: Cases to check before unknown cases.
72 :param seed: Private proposal and parent selection seed.
73
74 Verification should be deterministic. Only candidates that can improve
75 the archive are checked. A candidate enters the archive only after
76 passing the complete scenario universe. A failed scenario moves ahead
77 of unseen cases for later candidates. A candidate interrupted by the
78 check budget or an inconclusive result resumes on the next run call.
79 """
80
81 def __init__(self, archive, scenarios, *, propose, mutate, measure, verify, initial_scenarios=(), seed=0):
82 _validate_grid(archive)
83 if not all(map(callable, (propose, mutate, measure, verify))):
84 raise TypeError("Supply callable propose, mutate, measure, and verify functions.")
85 cases = tuple(scenarios)
86 universe = set(cases)
87 if not cases or len(universe) != len(cases):
88 raise ValueError("scenarios must contain distinct cases.")
89 known = dict.fromkeys(initial_scenarios)
90 if not universe.issuperset(known):
91 raise ValueError("initial_scenarios must belong to the verification universe.")
92 self.archive = archive
93 self._cases, self._known = cases, known
95 self._propose, self._mutate, self._measure, self._verify = propose, mutate, measure, verify
96 self._rng = np.random.default_rng(seed)
97 self._counts = Counter()
98 self._pending = None
99 self._counterexamples = []
100
101 @property
102 def stats(self):
103 """Return an immutable snapshot of cumulative search work."""
104 return CounterexampleQDStats(**self._counts)
105
106 @property
108 """Return discovered counterexamples in first-discovery order."""
109 return tuple(self._counterexamples)
110
111 @property
112 def pending_genome(self):
113 """Return the genome awaiting verification, or None."""
114 return None if self._pending is None else tuple(self._pending.measurement[0])
115
116 def _prioritized_cases(self):
117 return (*self._known, *(case for case in self._cases if case not in self._known))
118
119 def _propose_candidate(self):
120 self._counts["proposals"] += 1
121 if self.archive:
122 parent = tuple(self.archive[int(self._rng.integers(len(self.archive)))])
123 genome = tuple(self._mutate(parent, self._rng))
124 else:
125 genome = tuple(self._propose(self._rng))
126 self._counts["measurements"] += 1
127 measurement = _measurement(self.archive, self._measure(genome), genome)
128 candidate, cell = measurement
129 if cell is None:
130 return
131 front = self.archive.solutions[cell]
132 if front:
133 if self.archive._replacement_in_bin(candidate, front) is None:
134 return
135 elif self.archive.free < 1:
136 return
137 self._pending = _Verification(measurement, self._check_order)
138
139 def _check_case(self):
140 pending = self._pending
141 case = pending.scenarios[pending.position]
142 self._counts["checks"] += 1
143 passed = self._verify(tuple(pending.measurement[0]), case)
144 if passed is None:
145 self._counts["inconclusive_checks"] += 1
146 return False
147 if not isinstance(passed, (bool, np.bool_)):
148 raise TypeError("verify must return True, False, or None.")
149 if not passed:
150 if case not in self._known:
151 self._known[case] = None
152 self._check_order = self._prioritized_cases()
153 self._counterexamples.append(case)
154 self._counts["counterexamples"] += 1
155 self._counts["rejected"] += 1
156 self._pending = None
157 else:
158 pending.position += 1
159 if pending.position == len(pending.scenarios):
160 self._pending = None
161 self._counts["verified"] += 1
162 before = self.archive.nb_added
163 _offer(self.archive, pending.measurement)
164 self._counts["archive_updates"] += self.archive.nb_added - before
165 return True
166
167
168 def run(self, *, proposals, checks):
169 """Return cumulative stats and retain a partial verification for the next call.
170
171 Zero proposals allows finishing the pending candidate. Reaching
172 an inconclusive case pauses this call. A callback exception
173 propagates after charging the attempted operation.
174 """
175 proposal_limit = self._counts["proposals"] + _nonnegative_limit(proposals, "proposals")
176 check_limit = self._counts["checks"] + _nonnegative_limit(checks, "checks")
177 while True:
178 if self._pending is None:
179 if self._counts["proposals"] >= proposal_limit:
180 break
181 self._propose_candidate()
182 elif self._counts["checks"] >= check_limit or not self._check_case():
183 break
184 return self.stats
Illuminate verified designs and prioritize known counterexamples during future checks.
run(self, *, proposals, checks)
Spend additional independent proposal and verification budgets.
Report cumulative search and verification work.