# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief User-controlled MAP-Elites with a movable parent-selection window.
# @see https://doi.org/10.1145/3583133.3590616
"""Move a search window in descriptor space after a user choice."""
from math import isfinite
from operator import index
from random import Random
import numpy as np
from scipy.spatial.distance import cdist
from qdpy.base import registry
from ._population import _finite_vector
from .constrained import ConstrainedMAPElites
from .medoid_map_elites import _pam
from .modern import _positive_int
__all__ = ["WindowedMAPElites"]
## @brief Show local alternatives and restrict breeding to the selected neighborhood.
[docs]
@registry.register
class WindowedMAPElites(ConstrainedMAPElites):
"""User-Controlled MAP-Elites for real, integer, and categorical variables.
Initially breed across the full archive. Call ``choose()`` to display
nearby feasible elites and center the window on the chosen elite.
While focused, parents come from inside the window. Offspring may
populate any descriptor cell. When both pools have eligible parents,
alternate between feasible and infeasible elites.
:param container: Empty best-only Grid or CVTGrid with finite descriptor bounds.
:param budget: Evaluation budget for one managed optimisation call.
:param variables: Variable specifications in genome order.
:param window_radius: Positive half-width, scalar or one per archive descriptor.
:param constraint_names: Optional inequality residual names, where g(x) <= 0 is feasible.
:param seed: Private seed for parent sampling and variation.
:param batch_size: Number of proposals between archive updates.
:param real_sigma: Mutation scale as a fraction of each real variable's width.
:param optimisation_task: Native scalar objective direction or weight.
"""
_allows_no_constraints = True
def __init__(self, container, budget, variables, *, window_radius, constraint_names=(), seed=0,
batch_size=1, real_sigma=.1, optimisation_task=None):
domain = np.asarray(container.features_domain, dtype=float)
if (domain.ndim != 2 or domain.shape[1] != 2 or not len(domain)
or not np.isfinite(domain).all() or not np.isfinite(domain[:, 1] - domain[:, 0]).all()):
raise ValueError("Windowed search needs finite descriptor bounds and spans.")
if np.ndim(window_radius) == 0:
window_radius = (window_radius,) * len(domain)
self.window_radius = _finite_vector(window_radius, "Window radius", len(domain))
if not all(radius > 0. for radius in self.window_radius):
raise ValueError("Window radii must be positive.")
self.seed = index(seed)
self._domain = domain
direction = container.fitness_weights if optimisation_task is None else optimisation_task
super().__init__(container, budget, variables, constraint_names=constraint_names,
batch_size=batch_size, real_sigma=real_sigma, optimisation_task=direction)
def reinit(self):
"""Reset the round-robin parent choice and clear the window."""
super().reinit()
self._variation_rng = Random(self.seed)
self._window_center = None
self._select_infeasible = False
self._local_feasible = self._local_infeasible = ()
@property
def window_center(self):
"""Return the selected descriptor or None during global search."""
return self._window_center
def _in_window(self, individual):
if self._window_center is None:
return True
descriptor = self.container.get_ind_features(individual)
return all(abs(float(x) - c) <= r for x, c, r in zip(descriptor, self._window_center, self.window_radius))
def _start_fixed_batch(self, size):
super()._start_fixed_batch(size)
self._local_feasible = tuple(row for row in self.container if self._in_window(row))
self._local_infeasible = tuple(row for _, row in self._infeasible.values() if self._in_window(row))
def _clear_generation(self):
super()._clear_generation()
self._local_feasible = self._local_infeasible = ()
def _select_parent(self, rng):
feasible, infeasible = self._local_feasible, self._local_infeasible
if feasible and infeasible:
pool = infeasible if self._select_infeasible else feasible
self._select_infeasible = not self._select_infeasible
else:
pool = feasible or infeasible
return rng.choice(pool) if pool else None
## @brief Display distinct feasible elites inside the current selection window.
# @param count Maximum number of displayed alternatives.
# @param sampling "medoids" for PAM or "corners" for nearest-corner representatives.
# @return Tuple of live feasible elites in display order.
[docs]
def alternatives(self, count=4, *, sampling="medoids"):
"""Use descriptor distances scaled by window widths for display selection."""
count = _positive_int(count, "count")
if sampling not in ("medoids", "corners"):
raise ValueError("Choose medoids or corners sampling.")
if sampling == "corners":
corners = 1 << len(self.window_radius)
count = min(count, corners)
panel = tuple(row for row in self.container if self._in_window(row))
if len(panel) <= count:
return panel
points = np.asarray([tuple(self.container.get_ind_features(row)) for row in panel])
lower, upper = self._domain.T
if self._window_center is not None:
with np.errstate(over="ignore"):
lower = np.maximum(lower, np.asarray(self._window_center) - self.window_radius)
upper = np.minimum(upper, np.asarray(self._window_center) + self.window_radius)
widths = upper - lower
normalized = (points - lower) / np.where(widths > 0., widths, 1.)
if sampling == "medoids":
selected = _pam(cdist(normalized, normalized), count, max_swaps=20)
else:
selected = []
for i in range(count):
code = i * (corners - 1) // max(count - 1, 1)
corner = [(code >> axis) & 1 for axis in range(len(widths))]
distance = np.square(normalized - corner).sum(axis=1)
distance[selected] = np.inf
selected.append(int(np.argmin(distance)))
return tuple(panel[i] for i in selected)
## @brief Center the window on a live feasible elite or clear it with None.
# @param elite An elite from the current archive.
[docs]
def focus(self, elite):
"""Apply a selection between completed ask/tell batches."""
if self._pending_size:
raise RuntimeError("Complete the current batch before changing the focus.")
if elite is None:
self._window_center = None
return
if not any(row is elite for row in self.container):
raise ValueError("Focus requires a live feasible elite.")
descriptor = tuple(map(float, self.container.get_ind_features(elite)))
if not all(map(isfinite, descriptor)):
raise ValueError("Focus requires finite descriptors.")
self._window_center = descriptor
## @brief Show alternatives to a chooser and recenter on its zero-based selection.
# @param chooser Callable receiving the tuple of elite alternatives and returning an index.
# @param count Maximum number of offered alternatives.
# @param sampling Procedure used to select alternatives from the archive.
# @return Chosen elite or None if the display is empty.
[docs]
def choose(self, chooser, count=4, *, sampling="medoids"):
"""Call the chooser only when a feasible alternative is available."""
if self._pending_size:
raise RuntimeError("Complete the current batch before asking for a choice.")
panel = self.alternatives(count, sampling=sampling)
if not panel:
return None
decision = index(chooser(panel))
if not 0 <= decision < len(panel):
raise ValueError("The chooser must return a displayed zero-based index.")
self.focus(panel[decision])
return panel[decision]