# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Budgeted MAP-Elites with exhaustive verification over finite scenarios.
# @see https://doi.org/10.1145/1168857.1168907
"""Search for verified elites and use failed scenarios to screen later proposals."""
from collections import Counter
from dataclasses import dataclass
from operator import index
import numpy as np
from .task_search import _measurement, _offer, _validate_grid
__all__ = ["CounterexampleMAPElites", "CounterexampleQDStats"]
def _nonnegative_limit(value, name):
value = index(value)
if value < 0:
raise ValueError(f"{name} must be nonnegative.")
return value
## @brief Report cumulative search and verification work.
[docs]
@dataclass(frozen=True)
class CounterexampleQDStats:
"""Counters checked independently against per-run proposal and verification budgets.
:param proposals: Attempted proposals, including failures before measurement.
:param measurements: Attempts to measure nominal quality and descriptors.
:param checks: Attempts to verify a design on a single scenario.
:param rejected: Designs ruled out by a failing check.
:param verified: Designs that passed every scenario.
:param archive_updates: Insertions and improvements to the certified archive.
:param counterexamples: Newly discovered failing scenarios added to screening.
:param inconclusive_checks: Checks that returned None and need to be retried.
"""
proposals: int = 0
measurements: int = 0
checks: int = 0
rejected: int = 0
verified: int = 0
archive_updates: int = 0
counterexamples: int = 0
inconclusive_checks: int = 0
@dataclass
class _Verification:
measurement: tuple
scenarios: tuple
position: int = 0
## @brief Illuminate verified designs and prioritize known counterexamples during future checks.
[docs]
class CounterexampleMAPElites:
"""Run counterexample-guided MAP-Elites over a fixed finite scenario universe.
:param archive: Empty, best-only scalar Grid or CVTGrid. This archive
is owned by the search for the duration of verification.
:param scenarios: Nonempty ordered collection of distinct hashable cases.
:param propose: Callback (rng) producing an initial iterable genome.
:param mutate: Callback (parent_tuple, rng) producing an offspring genome.
:param measure: Callback (genome) returning ((fitness,), descriptors).
The measurement fixes the candidate's niche and its quality.
:param verify: Callback (genome, scenario) returning True on success,
False on a counterexample, or None when the result is inconclusive.
:param initial_scenarios: Cases to check before unknown cases.
:param seed: Private proposal and parent selection seed.
Verification should be deterministic. Only candidates that can improve
the archive are checked. A candidate enters the archive only after
passing the complete scenario universe. A failed scenario moves ahead
of unseen cases for later candidates. A candidate interrupted by the
check budget or an inconclusive result resumes on the next run call.
"""
def __init__(self, archive, scenarios, *, propose, mutate, measure, verify, initial_scenarios=(), seed=0):
_validate_grid(archive)
if not all(map(callable, (propose, mutate, measure, verify))):
raise TypeError("Supply callable propose, mutate, measure, and verify functions.")
cases = tuple(scenarios)
universe = set(cases)
if not cases or len(universe) != len(cases):
raise ValueError("scenarios must contain distinct cases.")
known = dict.fromkeys(initial_scenarios)
if not universe.issuperset(known):
raise ValueError("initial_scenarios must belong to the verification universe.")
self.archive = archive
self._cases, self._known = cases, known
self._check_order = self._prioritized_cases()
self._propose, self._mutate, self._measure, self._verify = propose, mutate, measure, verify
self._rng = np.random.default_rng(seed)
self._counts = Counter()
self._pending = None
self._counterexamples = []
@property
def stats(self):
"""Return an immutable snapshot of cumulative search work."""
return CounterexampleQDStats(**self._counts)
@property
def counterexamples(self):
"""Return discovered counterexamples in first-discovery order."""
return tuple(self._counterexamples)
@property
def pending_genome(self):
"""Return the genome awaiting verification, or None."""
return None if self._pending is None else tuple(self._pending.measurement[0])
def _prioritized_cases(self):
return (*self._known, *(case for case in self._cases if case not in self._known))
def _propose_candidate(self):
self._counts["proposals"] += 1
if self.archive:
parent = tuple(self.archive[int(self._rng.integers(len(self.archive)))])
genome = tuple(self._mutate(parent, self._rng))
else:
genome = tuple(self._propose(self._rng))
self._counts["measurements"] += 1
measurement = _measurement(self.archive, self._measure(genome), genome)
candidate, cell = measurement
if cell is None:
return
front = self.archive.solutions[cell]
if front:
if self.archive._replacement_in_bin(candidate, front) is None:
return
elif self.archive.free < 1:
return
self._pending = _Verification(measurement, self._check_order)
def _check_case(self):
pending = self._pending
case = pending.scenarios[pending.position]
self._counts["checks"] += 1
passed = self._verify(tuple(pending.measurement[0]), case)
if passed is None:
self._counts["inconclusive_checks"] += 1
return False
if not isinstance(passed, (bool, np.bool_)):
raise TypeError("verify must return True, False, or None.")
if not passed:
if case not in self._known:
self._known[case] = None
self._check_order = self._prioritized_cases()
self._counterexamples.append(case)
self._counts["counterexamples"] += 1
self._counts["rejected"] += 1
self._pending = None
else:
pending.position += 1
if pending.position == len(pending.scenarios):
self._pending = None
self._counts["verified"] += 1
before = self.archive.nb_added
_offer(self.archive, pending.measurement)
self._counts["archive_updates"] += self.archive.nb_added - before
return True
## @brief Spend additional independent proposal and verification budgets.
[docs]
def run(self, *, proposals, checks):
"""Return cumulative stats and retain a partial verification for the next call.
Zero proposals allows finishing the pending candidate. Reaching
an inconclusive case pauses this call. A callback exception
propagates after charging the attempted operation.
"""
proposal_limit = self._counts["proposals"] + _nonnegative_limit(proposals, "proposals")
check_limit = self._counts["checks"] + _nonnegative_limit(checks, "checks")
while True:
if self._pending is None:
if self._counts["proposals"] >= proposal_limit:
break
self._propose_candidate()
elif self._counts["checks"] >= check_limit or not self._check_case():
break
return self.stats