Source code for qdpy.algorithms.symmetry_qd
# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief MAP-Elites over canonical representatives of declared design symmetries.
# @see https://doi.org/10.1016/j.jsc.2013.09.003
"""Evaluate each canonical design at most once in a deterministic search."""
from collections import Counter
from dataclasses import dataclass
import numpy as np
from .modern import _positive_int
from .task_search import _measurement, _offer, _validate_grid
__all__ = ["SymmetryAwareMAPElites", "SymmetryQDStats"]
## @brief Separate proposals, expensive evaluations, and repeated representatives.
[docs]
@dataclass(frozen=True)
class SymmetryQDStats:
"""Cumulative proposals, evaluator attempts, repeats, and accepted archive updates."""
proposals: int = 0
evaluations: int = 0
duplicates: int = 0
archive_updates: int = 0
## @brief Canonicalize each design before evaluation and archive admission.
[docs]
class SymmetryAwareMAPElites:
"""Search only distinct canonical representatives in a best-only Grid or CVTGrid.
:param archive: Empty reporting archive with scalar fitness.
:param canonicalize: Callback (genome_tuple) producing a canonical
genome iterable with hashable entries. It must be deterministic and
idempotent, and preserve fitness, descriptors, and feasibility.
:param propose: Callback (rng) producing an initial iterable genome.
:param mutate: Callback (parent_tuple, rng) producing an offspring genome.
:param seed: Private proposal and parent selection seed.
The search owns a cache of successfully evaluated representatives,
including measurements outside the reporting domain. Keep the
evaluator, geometry, and canonicalization fixed across calls.
"""
def __init__(self, archive, *, canonicalize, propose, mutate, seed=0):
_validate_grid(archive)
if not all(map(callable, (canonicalize, propose, mutate))):
raise TypeError("Supply callable canonicalize, propose, and mutate functions.")
self.archive = archive
self._canonicalize, self._propose, self._mutate = canonicalize, propose, mutate
self._rng = np.random.default_rng(seed)
self._seen = set()
self._counts = Counter()
@property
def stats(self):
"""Return an immutable snapshot of proposal and evaluation costs."""
return SymmetryQDStats(**self._counts)
## @brief Run additional proposals, skipping evaluation of repeated canonical designs.
[docs]
def run(self, evaluate, *, proposals, max_evaluations=None):
"""Return cumulative stats. The optional evaluation limit applies to this call.
Evaluate the canonical tuple and return ((fitness,), descriptors).
Failed or invalid measurements propagate and leave the candidate
eligible for a later attempt.
"""
if not callable(evaluate):
raise TypeError("evaluate must be callable.")
proposals = _positive_int(proposals, "proposals")
limit = (None if max_evaluations is None
else self._counts["evaluations"] + _positive_int(max_evaluations, "max_evaluations"))
for _ in range(proposals):
if limit is not None and self._counts["evaluations"] >= limit:
break
self._counts["proposals"] += 1
if self.archive:
parent = tuple(self.archive[int(self._rng.integers(len(self.archive)))])
genome = self._mutate(parent, self._rng)
else:
genome = self._propose(self._rng)
canonical = tuple(self._canonicalize(tuple(genome)))
if canonical in self._seen:
self._counts["duplicates"] += 1
continue
self._counts["evaluations"] += 1
measurement = _measurement(self.archive, evaluate(canonical), canonical)
before = self.archive.nb_added
_offer(self.archive, measurement)
self._seen.add(canonical)
self._counts["archive_updates"] += self.archive.nb_added - before
return self.stats