# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Editable feasible and infeasible MAP-Elites repertoires.
# @see https://doi.org/10.1109/CIG.2019.8848022
# @see https://doi.org/10.1109/TG.2020.3046133
"""Change descriptor axes and submit edited designs during constrained search."""
from dataclasses import dataclass
from math import fsum, isfinite
import numpy as np
from qdpy.containers import Grid
from ._population import _attempt_budget, _finite_vector
from .descriptor_mutation import DescriptorMutationMAPElites
from .modern import _positive_int
__all__ = ["InteractiveConstrainedMAPElites", "InteractiveConstrainedStats"]
## @brief Attempt, admission, and redesign counters for the interactive search.
[docs]
@dataclass(frozen=True)
class InteractiveConstrainedStats:
"""Admissions count new measurements. Reprojecting existing rows has its own counter."""
evaluations: int
edits: int
failures: int
feasible_evaluations: int
feasible_admissions: int
infeasible_admissions: int
reprojections: int
## @brief Constrained MAP-Elites with a live editable design and replaceable axes.
[docs]
class InteractiveConstrainedMAPElites:
"""Keep separate subpopulations for good designs and near-feasible ones.
Positive constraint residuals indicate violations. Feasible individuals
compete on user-provided fitness, infeasible individuals on total positive
residual. Both grids retain the configured number of breeders per cell.
Use hashable genome sequences and emit measurements for prospective axes.
"""
## @param axes Named DescriptorAxis objects in display order.
# @param fitness_domain Inclusive bounds for feasible fitness.
# @param sample Callable (rng) returning a seed genome.
# @param mutate Callable (genome, rng) returning a new genome.
# @param crossover Optional callable (left, right, rng) returning a parent for mutation.
# @param maximize Whether higher raw fitness is preferable.
# @param cell_capacity Maximum number of breeders in each grid cell.
# @param initial_samples Warm-up attempts that use the initializer when the editor anchor is skipped.
# @param anchor_probability Probability of breeding from the last accepted editor input.
# @param seed Seed for proposals, evaluation seeds, and tournaments.
def __init__(self, axes, *, fitness_domain, sample, mutate, crossover=None, maximize=True, cell_capacity=4,
initial_samples=8, anchor_probability=.2, seed=0):
axes = DescriptorMutationMAPElites._checked_axes(axes)
self._capacity = _positive_int(cell_capacity, "cell_capacity")
self._initial = _attempt_budget(initial_samples)
low, high = map(float, fitness_domain)
if (not low < high or not all(map(callable, (sample, mutate)))
or crossover is not None and not callable(crossover)
or not 0. <= anchor_probability <= 1.):
raise ValueError("Supply ordered fitness bounds, callable operators, and a probability in [0, 1].")
self._domain, self._weight = (low, high), 1. if maximize else -1.
self._sample, self._mutate, self._crossover = sample, mutate, crossover
self._anchor_probability = anchor_probability
self._variation, self._rollouts = (np.random.default_rng(child)
for child in np.random.SeedSequence(seed).spawn(2))
self._axes = axes
self._archive, self._infeasible = self._grids(axes)
self._anchor = self._residual_count = None
self._evaluations = self._edits = self._failures = self._feasible_evaluations = 0
self._feasible_admissions = self._infeasible_admissions = self._reprojections = 0
def _grids(self, axes):
options = dict(shape=tuple(axis.bins for axis in axes), features_domain=tuple(axis.bounds for axis in axes),
storage_type="orderedset", max_items_per_bin=self._capacity)
return (Grid(fitness_domain=(self._domain,), fitness_weights=(self._weight,), **options),
Grid(fitness_domain=((-np.inf, 0.),), fitness_weights=(1.,), **options))
## @brief Live archive of feasible solutions, with raw fitness.
@property
def archive(self):
return self._archive
## @brief Live archive of infeasible solutions, with negative total violation as fitness.
@property
def infeasible_archive(self):
return self._infeasible
## @brief Current descriptor geometry.
@property
def axes(self):
return self._axes
## @brief Most recent successfully evaluated edited design.
@property
def anchor(self):
return self._anchor
## @brief Cumulative work across search, edits, and descriptor changes.
@property
def stats(self):
return InteractiveConstrainedStats(self._evaluations, self._edits, self._failures, self._feasible_evaluations,
self._feasible_admissions, self._infeasible_admissions, self._reprojections)
def _evaluate(self, genome, evaluate):
hash(genome)
seed = int(self._rollouts.integers(2**32))
self._evaluations += 1
result = evaluate(genome, seed)
if result is None:
self._failures += 1
return False
fitness, scores, residuals = result
residuals = _finite_vector(residuals, "constraint residuals", self._residual_count)
if not isfinite(fitness):
raise ValueError("Return finite scalar fitness.")
violation = fsum(max(0., residual) for residual in residuals)
grid = self._infeasible if violation else self._archive
before = grid.nb_added
DescriptorMutationMAPElites._put(grid, self._axes, genome, -violation if violation else fitness, scores)
self._residual_count = len(residuals)
if violation:
self._infeasible_admissions += grid.nb_added - before
else:
self._feasible_evaluations += 1
self._feasible_admissions += grid.nb_added - before
return True
## @brief Measure an edited genome immediately and make it the current breeding anchor.
# @param genome Immutable sequence representing the editor's design.
# @param evaluate Callable (genome, seed) returning (fitness, named measurements, residuals) or None.
def submit(self, genome, evaluate):
if not callable(evaluate):
raise TypeError("Supply a callable evaluator.")
genome = tuple(genome)
hash(genome)
self._edits += 1
if self._evaluate(genome, evaluate):
self._anchor = genome
return self.stats
## @brief Reassign all currently retained designs to a new set of named axes.
[docs]
def reproject(self, axes):
"""Reuse cached measurements. A failed rebuild leaves both live archives intact."""
axes = DescriptorMutationMAPElites._checked_axes(axes)
if axes == self._axes:
return self.stats
grids = self._grids(axes)
for source, destination in zip((self.archive, self.infeasible_archive), grids):
for elite in source:
DescriptorMutationMAPElites._put(destination, axes, elite, elite.fitness.values[0], elite.scores)
self._archive, self._infeasible = grids
self._axes = axes
self._reprojections += 1
return self.stats
def _parent(self, grid):
cells = np.flatnonzero(grid.nb_items_per_bin)
cell = np.unravel_index(cells[self._variation.integers(len(cells))], grid.shape)
members = grid.solutions[cell]
contestants = (members[i] for i in self._variation.integers(len(members), size=2))
return tuple(max(contestants, key=lambda row: grid.fitness_weights[0] * row.fitness.values[0]))
## @brief Run additional proposals using the current archive geometry and editor input.
# @param evaluate Callable (genome, seed) with the same contract as submit.
# @param budget Additional evaluation attempts, including failed evaluations.
def run(self, evaluate, budget):
if not callable(evaluate):
raise TypeError("Supply a callable evaluator.")
rng = self._variation
for _ in range(_attempt_budget(budget)):
available = [grid for grid in (self.archive, self.infeasible_archive) if grid]
if self._anchor is not None and (not available or rng.random() < self._anchor_probability):
genome = self._mutate(self._anchor, rng)
elif self._evaluations - self._edits < self._initial or not available:
genome = self._sample(rng)
else:
grid = available[int(rng.integers(len(available)))]
parent = self._parent(grid)
if self._crossover is not None:
parent = tuple(self._crossover(parent, self._parent(grid), rng))
genome = self._mutate(parent, rng)
self._evaluate(tuple(genome), evaluate)
return self.stats