# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Coevolutionary MAP-Elites for two complementary solution components.
# @see https://doi.org/10.1007/s10710-025-09520-x
"""Search two component descriptor spaces with adaptive partner selection."""
from dataclasses import dataclass
import numpy as np
from qdpy.containers import Grid
from qdpy.phenotype import Features, Fitness, Individual
from .modern import _positive_int
__all__ = ["CoME", "CoMEStats"]
## @brief Counts from one CoME run call.
[docs]
@dataclass(frozen=True)
class CoMEStats:
"""Count complete pair evaluations, evaluated generations, and archive insertions.
:ivar evaluations: Number of complete pairs scored, including initialization.
:ivar generations: Number of batches committed.
:ivar archive_updates: Number of successful insertions into either archive.
"""
evaluations: int
generations: int
archive_updates: int
## @brief Coevolve two specialized archives using separate coupling maps.
[docs]
class CoME:
"""Mutate one component and evaluate it with neighbors of a chosen partner cell.
The two rectangular grids have identical shapes. Each is indexed by one
component's descriptors and stores the complete pair and its measured
fitness. Each archive competes independently. Partner selection reads
that side's component from the pair at the chosen cell.
:param archives: Two distinct empty, parentless, best-only grids with the
same shape and the same finite, nonzero scalar fitness weight.
:param initialize: Two callbacks returning a component given the Generator.
:param mutations: Two callbacks taking (component, rng) and returning a component.
:param descriptors: Two callbacks taking a component and returning its finite,
in-bounds descriptor vector. Components are immutable and hashable.
:param evaluate: Callback returning scalar fitness from a complete pair.
:param coupling: One of "local-best", "global-best", "identity", "center", or "random".
:param partners: Maximum number of distinct neighbor cells sampled per mutation.
:param radius: Strict Euclidean radius in cell-index units around the partner cell.
:param initial_samples: Number of independently initialized pairs to score.
:param batch_size: Maximum number of scored pairs between archive updates.
:param seed: Private proposal seed.
"""
def __init__(self, archives, *, initialize, mutations, descriptors, evaluate,
coupling="local-best", partners=2, radius=2., initial_samples=8,
batch_size=16, seed=0):
self.archives = tuple(archives)
self._initializers, self._mutations, self._descriptors = map(tuple, (initialize, mutations, descriptors))
if (len(self.archives) != 2 or self.archives[0] is self.archives[1]
or any(type(grid) is not Grid or grid.parents or len(grid)
or grid.max_items_per_bin != 1 or grid.discard_random_on_bin_overload
or grid.fitness_score_names or grid.features_score_names
or len(grid.fitness_domain or ()) != 1 or len(grid.fitness_weights or ()) != 1
or not np.isfinite(grid.fitness_weights[0]) or not grid.fitness_weights[0]
for grid in self.archives)):
raise ValueError("Supply two empty, parentless, native best-only grids with signed fitness.")
first, second = self.archives
if (first.shape != second.shape or first.fitness_weights != second.fitness_weights
or first.fitness_domain != second.fitness_domain):
raise ValueError("The two grids need matching shapes, objective directions, and fitness bounds.")
if (any(len(callbacks) != 2 for callbacks in (self._initializers, self._mutations, self._descriptors))
or not all(map(callable, (*self._initializers, *self._mutations, *self._descriptors, evaluate)))):
raise ValueError("Provide one initializer, mutation, and descriptor callback per component.")
if coupling not in ("local-best", "global-best", "identity", "center", "random"):
raise ValueError("Unknown CoME coupling strategy.")
if not 0. < radius < np.inf:
raise ValueError("radius must be finite and positive.")
self._weight = first.fitness_weights[0]
self._evaluate, self.coupling, self.radius = evaluate, coupling, radius
self.partners = _positive_int(partners, "partners")
self.initial_samples = _positive_int(initial_samples, "initial_samples")
self.batch_size = _positive_int(batch_size, "batch_size")
self._rng = np.random.default_rng(seed)
self._local = ({}, {})
self._global = None
self._initial_evaluations = self._next_side = 0
def _describe(self, side, part):
hash(part)
features = tuple(map(float, self._descriptors[side](part)))
grid = self.archives[side]
if (len(features) != len(grid.shape) or not np.isfinite(features).all()
or not grid.in_bounds(features, grid.features_domain)):
raise ValueError("Use finite component descriptors within the corresponding grid bounds.")
return features, grid.index_grid(features)
def _partner_indices(self, side, source_cell, partner_cells, count):
if self.coupling == "random":
center = partner_cells[self._rng.integers(len(partner_cells))]
else:
target = source_cell
if self.coupling == "center":
target = tuple((n - 1) // 2 for n in self.archives[1 - side].shape)
elif self.coupling == "global-best" and self._global is not None:
target = self._global[1][1 - side]
elif self.coupling == "local-best" and source_cell in self._local[side]:
target = self._local[side][source_cell][1]
distances = np.sum((partner_cells - target) ** 2, axis=1)
center = partner_cells[self._rng.choice(np.flatnonzero(distances == distances.min()))]
distances = np.linalg.norm(partner_cells - center, axis=1)
nearby = np.flatnonzero(distances < self.radius)
return self._rng.choice(nearby, min(count, len(nearby)), replace=False)
def _offspring(self, size):
entries = [tuple((grid.index_grid(item), item) for item in grid) for grid in self.archives]
cells = [np.asarray([cell for cell, _ in side]) for side in entries]
produced = 0
while produced < size:
side = self._next_side
self._next_side = 1 - side
source = entries[side]
parent = source[self._rng.integers(len(source))][1][side]
part = self._mutations[side](parent, self._rng)
features, cell = self._describe(side, part)
indices = self._partner_indices(side, cell, cells[1 - side], min(self.partners, size - produced))
for index in indices:
other_cell, other = entries[1 - side][index]
records = ((part, features, cell), (other[1 - side], tuple(other.features), other_cell))
produced += 1
yield records if side == 0 else records[::-1]
def _commit(self, measured):
updates = 0
for records, quality in measured:
parts, descriptors, cells = zip(*records)
signed = self._weight * quality
if self.coupling == "global-best" and (self._global is None or signed > self._global[0]):
self._global = signed, cells
for side, (grid, features, cell) in enumerate(zip(self.archives, descriptors, cells)):
if self.coupling == "local-best":
previous = self._local[side].get(cell)
if previous is None or signed > previous[0]:
self._local[side][cell] = signed, cells[1 - side]
if grid.free or grid.solutions[cell]:
elite = Individual(list(parts), fitness=Fitness((quality,), weights=(self._weight,)),
features=Features(features))
updates += grid.add(elite) is not None
return updates
## @brief Score exactly the requested number of complete pairs.
[docs]
def run(self, budget):
"""Continue from the live archives and coupling maps for budget pair evaluations."""
budget = _positive_int(budget, "budget")
evaluations = generations = updates = 0
while evaluations < budget:
size = min(self.batch_size, budget - evaluations)
if self._initial_evaluations < self.initial_samples or not all(map(len, self.archives)):
remaining_warmup = self.initial_samples - self._initial_evaluations
if remaining_warmup > 0:
size = min(size, remaining_warmup)
proposals = (tuple((part, *self._describe(side, part)) for side, part in enumerate(parts))
for parts in (tuple(init(self._rng) for init in self._initializers) for _ in range(size)))
initializing = True
else:
proposals = self._offspring(size)
initializing = False
measured = []
for records in proposals:
quality = float(self._evaluate(tuple(record[0] for record in records)))
if not np.isfinite(quality):
raise ValueError("CoME needs finite pair fitness.")
if self.archives[0].in_bounds((quality,), self.archives[0].fitness_domain):
measured.append((records, quality))
updates += self._commit(measured)
self._initial_evaluations += size if initializing else 0
evaluations += size
generations += 1
return CoMEStats(evaluations, generations, updates)