# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Reuse measured designs as constraints change.
# @see https://doi.org/10.1145/3795101.3805378
"""Maintain a feasible MAP-Elites repertoire under changing score limits."""
from collections import deque
from collections.abc import Mapping
from math import isfinite
from operator import index
import numpy as np
from .modern import _positive_int
from .task_search import _measurement, _offer, _validate_grid
__all__ = ["VariableConstraintMAPElites"]
## @brief Rebuild a feasible repertoire from cached measurements.
[docs]
class VariableConstraintMAPElites:
"""Search and replay measured designs under inclusive score bounds.
:param archive: Empty parentless, best-only Grid or CVTGrid with a
single objective and native fitness and descriptors.
:param score_names: Names of the finite scalar measurements returned
by every successful evaluation, including currently unused scores.
:param constraints: Mapping from score names to (lower, upper). Use
None for an open end. Omit a name to remove its constraint.
:param history_size: Number of recent valid measurements to remember
alongside the live elites. Zero keeps only the live elites.
:param propose: Callback (rng) returning an immutable hashable genome.
:param mutate: Callback (parent_genome, rng) returning an offspring.
:param seed: Seed for proposal and parent selection.
"""
def __init__(self, archive, *, score_names, constraints, history_size=1024,
propose, mutate, seed=0):
_validate_grid(archive)
if archive.fitness_score_names or archive.features_score_names:
raise ValueError("Supply a grid with native fitness and descriptors.")
names = (score_names,) if isinstance(score_names, str) else tuple(score_names)
if (not names or any(not isinstance(name, str) or not name for name in names)
or len(set(names)) != len(names)):
raise ValueError("Use distinct nonempty score names.")
if not callable(propose) or not callable(mutate):
raise TypeError("Supply callable proposal and mutation operators.")
self._score_names = frozenset(names)
self._constraints = self._validate_constraints(constraints)
self._history = deque(maxlen=index(history_size))
if archive.fitness_weights is None:
archive._set_fitness_weights((1.,))
self.archive = archive
self._propose, self._mutate = propose, mutate
self._rng = np.random.default_rng(seed)
self.nb_evaluations = 0
self.nb_failures = 0
@property
def constraints(self):
"""Return a copy of the active score bounds."""
return dict(self._constraints)
def _validate_constraints(self, constraints):
if not isinstance(constraints, Mapping) or constraints.keys() - self._score_names:
raise ValueError("Constrain only declared measurement names.")
bounds = {}
for key, (lower, upper) in constraints.items():
lower = None if lower is None else float(lower)
upper = None if upper is None else float(upper)
if ((lower is not None and not isfinite(lower))
or (upper is not None and not isfinite(upper))
or (lower is not None and upper is not None and lower > upper)):
raise ValueError("Constraint bounds must be ordered and finite or None.")
bounds[key] = lower, upper
return bounds
@staticmethod
def _feasible(candidate, constraints):
return all((lower is None or candidate.scores[name] >= lower)
and (upper is None or candidate.scores[name] <= upper)
for name, (lower, upper) in constraints.items())
## @brief Rebuild the live archive without new evaluator calls.
[docs]
def set_constraints(self, constraints):
"""Apply new bounds to live and remembered designs and return the archive."""
bounds = self._validate_constraints(constraints)
if bounds == self._constraints:
return self.archive
archive = self.archive
eligible = {elite[0]: (elite, archive.index_grid(elite)) for elite in archive}
eligible.update((candidate[0], (candidate, cell)) for candidate, cell in self._history)
feasible = [pair for pair in eligible.values() if self._feasible(pair[0], bounds)]
direction = np.sign(archive.fitness_weights[0])
feasible.sort(key=lambda pair: direction * pair[0].fitness.values[0], reverse=True)
archive.clear()
for measurement in feasible:
_offer(archive, measurement)
self._constraints = bounds
return archive
## @brief Continue the search under the current score limits.
[docs]
def run(self, evaluate, *, budget):
"""Evaluate new genomes and return the live archive.
Return (scalar fitness, descriptors, scores) from evaluate(genome).
Scores must contain every declared measurement. Return None to report
a failed attempt. Use stable measurements for repeated genomes.
"""
for _ in range(_positive_int(budget, "budget")):
if len(self.archive):
parent = self.archive[int(self._rng.integers(len(self.archive)))]
genome = self._mutate(parent[0], self._rng)
else:
genome = self._propose(self._rng)
hash(genome)
self.nb_evaluations += 1
result = evaluate(genome)
if result is None:
self.nb_failures += 1
continue
fitness, descriptors, measured = result
if not isinstance(measured, Mapping) or self._score_names != measured.keys():
raise ValueError("Return exactly the declared scores for every measured genome.")
scores = {name: float(value) for name, value in measured.items()}
if not all(map(isfinite, scores.values())):
raise ValueError("Constraint measurements must be finite.")
candidate, cell = _measurement(self.archive, ((fitness,), descriptors), (genome,))
if cell is None:
continue
candidate.scores.update(scores)
measurement = (candidate, cell)
self._history.append(measurement)
if self._feasible(candidate, self._constraints):
_offer(self.archive, measurement)
return self.archive