# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Rotate active descriptor spaces and carry measured elites across CVT maps.
# @see https://doi.org/10.1162/isal_a_00617
"""Switch CVT descriptor spaces on a fixed evaluation schedule."""
from collections.abc import Mapping
from dataclasses import dataclass
import numpy as np
from qdpy.containers import CVTGrid
from qdpy.tools import iso_line_dd
from .modern import _positive_int, _variation_settings
from .sampling import _rollout_seed
from .task_search import _measurement, _offer, _search_bounds, _validate_grid
__all__ = ["ScheduledCVTMAPElites", "ScheduledCVTStats", "CVTViewSwitch"]
## @brief Log one descriptor-space switch at a completed evaluation count.
[docs]
@dataclass(frozen=True)
class CVTViewSwitch:
"""Transfer admissions include both empty-cell insertions and replacements."""
after_evaluations: int
source: str
destination: str
transfer_admissions: int
## @brief Snapshot parent selection counts and measured transfers by phase.
[docs]
@dataclass(frozen=True)
class ScheduledCVTStats:
"""Report cumulative attempts and the current view."""
evaluations: int
active_view: str
evaluations_by_view: tuple[tuple[str, int], ...]
switches: tuple[CVTViewSwitch, ...]
## @brief Run a phase-based search over complete descriptor spaces.
[docs]
class ScheduledCVTMAPElites:
"""Use the active CVT archive as the parent pool for one phase.
At a phase boundary, re-bin each current elite into the incoming
archive using the measurements cached on the original evaluation.
The incoming archive also keeps any elites already found in earlier
phases. Transfer costs zero evaluator calls. Each view owns its
fitness weights and descriptor geometry.
:param archives: Ordered mapping of names to empty, distinct scalar CVT grids.
:param dimension: Number of real decision coordinates.
:param phase_evaluations: Number of evaluation attempts per active view.
:param shared_feedback: Also offer each evaluation to inactive views for a control.
:param ind_domain: Increasing finite genome bounds shared by all coordinates.
:param iso_sigma: Independent Iso+LineDD mutation scale.
:param line_sigma: Directional Iso+LineDD mutation scale.
:param seed: Seed for private variation and evaluator streams.
"""
def __init__(self, archives, dimension, *, phase_evaluations, shared_feedback=False,
ind_domain=(0., 1.), iso_sigma=.03, line_sigma=.2, seed=0):
if (not isinstance(archives, Mapping) or not archives
or any(not isinstance(name, str) or not name for name in archives)
or len({id(grid) for grid in archives.values()}) != len(archives)):
raise ValueError("Provide a nonempty mapping of names to distinct CVTGrid instances.")
for archive in archives.values():
if type(archive) is not CVTGrid:
raise ValueError("Each view must be a CVTGrid.")
_validate_grid(archive)
if type(shared_feedback) is not bool:
raise TypeError("shared_feedback must be a bool.")
self._archives = dict(archives)
self._names = tuple(archives)
self._dimension = _positive_int(dimension, "dimension")
self._phase = _positive_int(phase_evaluations, "phase_evaluations")
self._bounds = _search_bounds(_variation_settings(ind_domain, iso_sigma, line_sigma))
self._iso, self._line, self._shared = iso_sigma, line_sigma, shared_feedback
variation, measurement = np.random.SeedSequence(seed).spawn(2)
self._rng = np.random.default_rng(variation)
self._seed = int(measurement.generate_state(1, dtype=np.uint64)[0])
self._active = self._evaluations = 0
self._view_counts = dict.fromkeys(self._names, 0)
self._switches = []
@property
def archives(self):
"""Return a mapping of names to the live CVT grids owned by the search."""
return dict(self._archives)
@property
def current_archive(self):
"""Return the active parent pool."""
return self._archives[self._names[self._active]]
@property
def stats(self):
"""Return cumulative evaluator and phase counts."""
return ScheduledCVTStats(self._evaluations, self._names[self._active],
tuple(self._view_counts.items()), tuple(self._switches))
@staticmethod
def _project(archive, view, genome, fitness, views):
measured = _measurement(archive, ((fitness,), views[view]), genome)
measured[0]._descriptor_views = views
return measured
def _switch(self):
source = self._names[self._active]
slot = (self._active + 1) % len(self._names)
target = self._names[slot]
archive = self._archives[target]
previous = archive.nb_added
for elite in self._archives[source]:
fitness = self._archives[source].get_ind_fitness(elite).values[0]
_offer(archive, self._project(archive, target, elite, fitness, elite._descriptor_views))
self._active = slot
self._switches.append(CVTViewSwitch(self._evaluations, source, target, archive.nb_added - previous))
## @brief Run additional evaluator calls without changing the phase schedule.
# @param evaluate Callable taking (genome, seed) and returning (fitness, descriptor_views).
# @param budget Number of additional calls on this invocation.
# @return Cumulative evaluation and phase counts.
[docs]
def run(self, evaluate, budget):
"""Return a scalar fitness and one descriptor vector per configured view."""
if not callable(evaluate):
raise TypeError("Supply a callable evaluator.")
for _ in range(_positive_int(budget, "budget")):
if len(self._names) > 1 and self._evaluations and self._evaluations % self._phase == 0:
# A failed evaluation still spends its attempt. Switching occurs before the next call.
if not self._switches or self._switches[-1].after_evaluations != self._evaluations:
self._switch()
active = self._names[self._active]
archive = self.current_archive
if archive:
a, b = self._rng.integers(len(archive), size=2)
point = iso_line_dd(archive[int(a)], archive[int(b)], bounds=self._bounds,
iso_sigma=self._iso, line_sigma=self._line, rng=self._rng)
else:
point = self._rng.uniform(*self._bounds, size=self._dimension)
genome = tuple(map(float, point))
seed = _rollout_seed(self._seed, 0, self._evaluations)
self._evaluations += 1
self._view_counts[active] += 1
fitness, reported = evaluate(genome, seed)
if not isinstance(reported, Mapping) or reported.keys() != self._archives.keys():
raise ValueError("Return descriptors for each configured view.")
views = {name: tuple(row) for name, row in reported.items()}
measurements = {name: self._project(grid, name, genome, fitness, views)
for name, grid in self._archives.items()}
if self._shared:
for name, grid in self._archives.items():
_offer(grid, measurements[name])
else:
_offer(archive, measurements[active])
return self.stats