# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief MAP-Elites with competing genotype representations.
# @see https://doi.org/10.1145/3583131.3590381
"""Use multiple genotype representations in one phenotype archive."""
from collections.abc import Callable, Iterable
from dataclasses import dataclass
from operator import index
import numpy as np
from ._population import _attempt_budget
from .task_search import _measurement, _offer, _validate_grid
__all__ = ["GenomeEncoding", "MultiEncodingMAPElites", "MultiEncodingStats"]
## @brief Sampling, mutation, and decoding for one representation.
[docs]
@dataclass(frozen=True)
class GenomeEncoding:
"""The genotype is a sequence. The decoded phenotype can be any object."""
name: str
sample: Callable[[np.random.Generator], Iterable]
mutate: Callable[[tuple, np.random.Generator], Iterable]
decode: Callable[[tuple], object]
## @brief Cumulative proposals, failed decodes, objective calls, and admissions by encoding.
[docs]
@dataclass(frozen=True)
class MultiEncodingStats:
"""Counter tuples follow the configured encoding order."""
proposals: tuple[int, ...]
failed_decodes: tuple[int, ...]
objective_calls: tuple[int, ...]
admissions: tuple[int, ...]
## @brief Illuminate a shared phenotype space with several genotype encodings.
[docs]
class MultiEncodingMAPElites:
"""Sample each encoding evenly, then mutate uniformly drawn archive elites.
Archived genotypes start with the zero-based encoding index, followed by
the encoding's genome. All encodings compete in the same descriptor cells.
"""
## @param archive Empty parentless, scalar, best-only Grid or CVTGrid.
# @param encodings Ordered GenomeEncoding objects with unique names.
# @param initial_samples Number of initial proposals per encoding.
# @param seed Seed for sampling, parent selection, and mutation.
def __init__(self, archive, encodings, *, initial_samples=8, seed=0):
_validate_grid(archive)
encodings = tuple(encodings)
if not encodings or any(
not isinstance(encoding, GenomeEncoding) or not isinstance(encoding.name, str)
or not encoding.name or not all(map(callable, (encoding.sample, encoding.mutate, encoding.decode)))
for encoding in encodings):
raise ValueError("Supply named encodings with sampling, mutation, and decoding callables.")
if len({encoding.name for encoding in encodings}) != len(encodings):
raise ValueError("Encoding names must be unique.")
self._initial = _attempt_budget(initial_samples) * len(encodings)
self._rng = np.random.default_rng(seed)
self.archive, self.encodings = archive, encodings
if archive.fitness_weights is None:
archive._set_fitness_weights((1.,))
self._proposed = 0
self._proposals = [0] * len(encodings)
self._failures = [0] * len(encodings)
self._objectives = [0] * len(encodings)
self._admissions = [0] * len(encodings)
## @brief Cumulative counters from all runs.
@property
def stats(self):
return MultiEncodingStats(tuple(self._proposals), tuple(self._failures),
tuple(self._objectives), tuple(self._admissions))
## @brief Decode an individual from this archive, without recording an objective call.
def decode(self, elite):
slot = index(elite[0])
if not 0 <= slot < len(self.encodings):
raise ValueError("Elite has an invalid encoding index.")
return self.encodings[slot].decode(tuple(elite[1:]))
## @brief Spend a budget of proposal attempts and return cumulative counters.
# @param evaluate Callable (phenotype) returning (scalar fitness, descriptors) or None.
# @param budget Number of proposals, including unsuccessful decodes and measurements.
def run(self, evaluate, budget):
if not callable(evaluate):
raise ValueError("evaluate must be callable.")
for _ in range(_attempt_budget(budget)):
if self._proposed < self._initial or not self.archive:
slot = self._proposed % len(self.encodings)
genome = tuple(self.encodings[slot].sample(self._rng))
else:
slot, *parent = self.archive[int(self._rng.integers(len(self.archive)))]
genome = tuple(self.encodings[slot].mutate(tuple(parent), self._rng))
self._proposed += 1
self._proposals[slot] += 1
phenotype = self.encodings[slot].decode(genome)
if phenotype is None:
self._failures[slot] += 1
continue
self._objectives[slot] += 1
measurement = evaluate(phenotype)
if measurement is not None:
quality, descriptors = measurement
before = self.archive.nb_added
_offer(self.archive, _measurement(self.archive, ((quality,), descriptors), (slot, *genome)))
self._admissions[slot] += self.archive.nb_added - before
return self.stats