# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief MAP-Elites with fixed representative niches and caller-defined dissimilarity.
# @see https://arxiv.org/abs/1610.05729
# @see https://arxiv.org/abs/2008.05171
"""Illuminate descriptor spaces with actual reference objects as niche anchors."""
from dataclasses import dataclass
from math import isfinite
import numpy as np
from .modern import _positive_int
__all__ = ["MedoidArchive", "MedoidElite", "MedoidMAPElites"]
def _distance_value(distance, first, second):
value = float(distance(first, second))
if not isfinite(value) or value < 0.:
raise ValueError("distance must return a finite nonnegative value.")
return value
def _pam(distances, count, max_swaps):
"""Build medoids greedily, then exchange them using cached nearest costs."""
size = len(distances)
medoids = [int(np.argmin(distances.sum(axis=0)))]
nearest = distances[:, medoids[0]]
while len(medoids) < count:
costs = np.minimum(nearest[:, None], distances).sum(axis=0)
costs[medoids] = np.inf
medoids.append(int(np.argmin(costs)))
nearest = np.minimum(nearest, distances[:, medoids[-1]])
for _ in range(max_swaps):
current = distances[:, medoids]
owner = np.argmin(current, axis=1)
nearest = np.min(current, axis=1)
second = np.partition(current, 1, axis=1)[:, 1] if count > 1 else np.full(size, np.inf)
best = None
best_delta = 0.
for candidate in sorted(set(range(size)).difference(medoids)):
costs = distances[:, candidate]
base = np.minimum(costs, nearest)
penalty = np.minimum(costs, second) - base
deltas = (base - nearest).sum() + np.bincount(owner, weights=penalty, minlength=count)
remove = int(np.argmin(deltas))
if deltas[remove] < best_delta - 1e-12:
best_delta, best = deltas[remove], (remove, candidate)
if best is None:
break
remove, candidate = best
medoids[remove] = candidate
return tuple(medoids)
## @brief Store a measured genome, descriptor, and scalar fitness.
[docs]
@dataclass(frozen=True)
class MedoidElite:
"""An immutable record holding a candidate and its measurement."""
genome: object
fitness: float
descriptor: object
## @brief Assign descriptors to the nearest fixed medoid and keep the best candidate there.
[docs]
class MedoidArchive:
"""A best-only archive over arbitrary immutable descriptor objects.
:param medoids: Distinct ordered representatives in the descriptor space.
:param distance: Callable symmetric dissimilarity. It must be finite and
nonnegative, with zero for identical objects.
:param maximize: Whether higher fitness is preferred.
"""
def __init__(self, medoids, distance, *, maximize=True):
self._medoids = tuple(medoids)
if not self._medoids or not callable(distance):
raise ValueError("Supply at least one medoid and a callable distance.")
for i, first in enumerate(self._medoids):
if _distance_value(distance, first, first) != 0.:
raise ValueError("A medoid must be at zero distance from itself.")
if any(_distance_value(distance, first, other) == 0. for other in self._medoids[:i]):
raise ValueError("Medoids must be distinct under the chosen distance.")
self._distance = distance
self._sign = 1. if maximize else -1.
self._cells = {}
## @brief Fit the archive's fixed medoids on reference descriptors.
[docs]
@classmethod
def fit(cls, descriptors, count, distance, *, maximize=True, max_swaps=20):
"""Use deterministic PAM build and swap passes on the reference panel.
Fitting uses a dense pairwise matrix. Equivalent descriptors at
distance zero share the first representative.
"""
count = _positive_int(count, "count")
if not callable(distance):
raise TypeError("distance must be callable.")
if isinstance(max_swaps, bool) or not isinstance(max_swaps, (int, np.integer)) or max_swaps < 0:
raise ValueError("max_swaps must be a nonnegative integer.")
unique = []
triangle = []
for descriptor in descriptors:
row = [_distance_value(distance, descriptor, other) for other in unique]
if 0. not in row:
unique.append(descriptor)
triangle.append(row)
if count > len(unique):
raise ValueError("The reference panel has fewer distinct descriptors than requested niches.")
matrix = np.zeros((len(unique), len(unique)))
for index, row in enumerate(triangle):
matrix[index, :index] = row
matrix[:index, index] = row
matrix /= matrix.max() or 1.
selected = _pam(matrix, count, max_swaps)
return cls((unique[index] for index in selected), distance, maximize=maximize)
@property
def medoids(self):
"""Return the fixed niche anchors in tie-breaking order."""
return self._medoids
@property
def cells(self):
"""Return a snapshot of occupied niche indices and their measured elites."""
return dict(self._cells)
def __len__(self):
return len(self._cells)
def __iter__(self):
return iter(self._cells.values())
## @brief Resolve the nearest medoid, with ties going to the first anchor.
[docs]
def index(self, descriptor):
"""Return the integer niche index of a descriptor."""
return min(range(len(self._medoids)),
key=lambda i: _distance_value(self._distance, descriptor, self._medoids[i]))
## @brief Try to admit a measured candidate at its descriptor's niche.
[docs]
def add(self, genome, fitness, descriptor):
"""Return whether the candidate filled its niche or strictly improved its elite."""
score = float(fitness)
if not isfinite(score):
raise ValueError("fitness must be finite.")
cell = self.index(descriptor)
incumbent = self._cells.get(cell)
if incumbent is None or self._sign * score > self._sign * incumbent.fitness:
self._cells[cell] = MedoidElite(genome, score, descriptor)
return True
return False
## @brief Draw parents from occupied medoid niches and mutate with caller-defined operators.
[docs]
class MedoidMAPElites:
"""Search with a medoid archive and a scalar-fitness descriptor evaluator.
:param archive: A MedoidArchive, optionally seeded with measured elites.
:param propose: Callback (rng) producing a fresh immutable genome.
:param mutate: Callback (parent_genome, rng) producing an immutable offspring.
:param seed: Independent proposal and parent selection seed.
"""
def __init__(self, archive, *, propose, mutate, seed=0):
if not isinstance(archive, MedoidArchive) or not callable(propose) or not callable(mutate):
raise TypeError("Supply a MedoidArchive and callable proposal and mutation operators.")
self.archive = archive
self._propose, self._mutate = propose, mutate
self._rng = np.random.default_rng(seed)
self.nb_evaluations = 0
## @brief Run an additional budget of candidate evaluations.
[docs]
def optimise(self, evaluate, *, budget):
"""Call evaluate(genome) for (scalar fitness, immutable descriptor) and return the archive."""
for _ in range(_positive_int(budget, "budget")):
if self.archive:
parents = tuple(self.archive)
parent = parents[self._rng.integers(len(parents))]
genome = self._mutate(parent.genome, self._rng)
else:
genome = self._propose(self._rng)
self.nb_evaluations += 1
fitness, descriptor = evaluate(genome)
self.archive.add(genome, fitness, descriptor)
return self.archive