# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Search Pareto niches with categorical variation-operator choices.
# @see https://doi.org/10.1080/0305215X.2026.2637656
"""Uniform and bandit controls for state-aware variation in MOME."""
from collections import Counter
from collections.abc import Mapping
from dataclasses import dataclass
import numpy as np
from qdpy.containers import ParetoGrid
from qdpy.phenotype import Features, Fitness, Individual
from .modern import _positive_int
from .sampling import _rollout_seed
__all__ = ["OperatorMOME", "OperatorMOMEStats"]
## @brief Real evaluation attempts and separately counted controller work.
[docs]
@dataclass(frozen=True)
class OperatorMOMEStats:
"""The operator tuples follow the supplied mapping's iteration order."""
evaluations: int
initial_evaluations: int
archive_updates: int
out_of_domain: int
operator_attempts: tuple[tuple[str, int], ...]
operator_admissions: tuple[tuple[str, int], ...]
optimizer_steps: int
target_syncs: int
## @brief Illuminate a ParetoGrid using user-defined operators and archive feedback.
[docs]
class OperatorMOME:
"""Use uniform or UCB1 operator choices with native two-objective fronts.
Sample descriptor cells uniformly and then parents uniformly within
their fronts. An admitted child earns 1 for space in its target
front or .8 for entering a full front. A rejected child earns zero.
Keep cumulative evaluation accounting and resume with the same next
parent context when another search budget is supplied.
:param archive: Empty two-objective ParetoGrid with hypervolume truncation.
:param initializer: Callback returning a genome from a private generator.
:param operators: Mapping of names to callbacks taking (parent, donor, rng).
Parents and donors are tuples copied from the archive.
:param controller: Uniform or bandit.
:param initial_samples: Minimum number of warm-up evaluations.
:param seed: Private seed for decisions, mutations, and evaluations.
"""
def __init__(self, archive, *, initializer, operators, controller="uniform", initial_samples=16, seed=0):
if (not isinstance(archive, ParetoGrid) or len(archive) or archive.truncation != "hypervolume"
or archive.features_score_names or archive.fitness_score_names
or archive.capacity < len(archive.solutions) * archive.max_items_per_bin):
raise ValueError("Use an empty hypervolume ParetoGrid with native scores and room for every front.")
if (not callable(initializer) or not isinstance(operators, Mapping) or not operators
or any(not isinstance(name, str) or not name or not callable(op) for name, op in operators.items())):
raise ValueError("Provide an initializer and a mapping of named variation callbacks.")
if controller not in ("uniform", "bandit"):
raise ValueError("Choose uniform or bandit operator selection.")
self.archive, self._initializer = archive, initializer
self._names, self._operators = tuple(operators), tuple(operators.values())
self._controller = controller
self._warmup = _positive_int(initial_samples, "initial_samples")
streams = np.random.SeedSequence(seed).spawn(4)
self._selection, self._choice, self._variation = map(np.random.default_rng, streams[:3])
self._evaluation_seed = int(streams[3].generate_state(1, dtype=np.uint64)[0])
self._counts = Counter()
self._pulls = np.zeros(len(operators), dtype=int)
self._admissions = np.zeros(len(operators), dtype=int)
self._rewards = np.zeros(len(operators))
self._recent = 0.
self._context = None
self._cells = []
self._quality = np.asarray(archive.fitness_domain, dtype=float)
self._directions = np.sign(archive.fitness_weights)
bounds = np.asarray(archive.features_domain, dtype=float)
self._low, self._span = bounds[:, 0], bounds[:, 1] - bounds[:, 0]
if not (np.isfinite(self._span).all() and (self._span > 0.).all()):
raise ValueError("Use finite, increasing descriptor intervals.")
@property
def stats(self):
"""Return costs, per-operator outcomes, and archive updates."""
return OperatorMOMEStats(
self._counts["evaluations"], self._counts["initial"], self._counts["updates"],
self._counts["outside"], tuple(zip(self._names, map(int, self._pulls))),
tuple(zip(self._names, map(int, self._admissions))),
self._counts["optimizer_steps"], self._counts["target_syncs"],
)
def _parent(self):
cell = self._cells[int(self._selection.integers(len(self._cells)))]
front = self.archive.solutions[cell]
return front[int(self._selection.integers(len(front)))], len(front)
def _state(self):
parent, occupancy = self._parent()
qualities = (np.asarray(parent.fitness.values) - self._quality[:, 0]) / np.ptp(self._quality, axis=1)
qualities = np.where(self._directions > 0., qualities, 1. - qualities)
descriptor = (np.asarray(parent.features.values) - self._low) / self._span
values = np.asarray((len(self._cells) / len(self.archive.solutions),
occupancy / self.archive.max_items_per_bin, self._recent,
*qualities, *descriptor), dtype=np.float32)
return parent, values
def _choose_operator(self, state):
if self._controller == "uniform":
return int(self._choice.integers(len(self._operators)))
unseen = np.flatnonzero(self._pulls == 0)
if len(unseen):
return int(self._choice.choice(unseen))
mean = self._rewards / self._pulls
bonus = np.sqrt(2 * np.log(self._pulls.sum()) / self._pulls)
return int((mean + bonus).argmax())
def _observe(self, state, action, reward, successor):
"""The uniform and bandit controls use the counters updated by run()."""
def _offer(self, point, objectives, descriptors):
quality, descriptors = tuple(map(float, objectives)), tuple(map(float, descriptors))
archive = self.archive
if (len(quality) != 2 or len(descriptors) != len(archive.features_domain)
or not np.isfinite((*quality, *descriptors)).all()):
raise ValueError("The evaluator must return two finite objectives and its finite descriptor vector.")
if not (archive.in_bounds(quality, archive.fitness_domain)
and archive.in_bounds(descriptors, archive.features_domain)):
self._counts["outside"] += 1
return 0.
cell = archive.index_grid(descriptors)
previous = len(archive.solutions[cell])
candidate = Individual(point, fitness=Fitness(quality, weights=archive.fitness_weights),
features=Features(descriptors))
before = archive.nb_added
archive.add(candidate)
if archive.nb_added == before:
return 0.
self._counts["updates"] += 1
if not previous:
self._cells.append(cell)
return .8 if previous == archive.max_items_per_bin else 1.
## @brief Run additional evaluator calls with persistent controller state.
# @param evaluate Callable taking (genome, seed) and returning objectives and descriptors.
# @param budget Maximum additional evaluator calls.
# @return Cumulative accounting for the search and controller.
[docs]
def run(self, evaluate, budget):
"""Charge failed evaluator calls and propagate their errors."""
if not callable(evaluate):
raise TypeError("Supply a callable evaluator.")
for _ in range(_positive_int(budget, "budget")):
evaluation = self._counts["evaluations"]
initialize = evaluation < self._warmup or not self._cells
if initialize:
point = tuple(self._initializer(self._variation))
self._counts["initial"] += 1
else:
parent, state = self._state() if self._context is None else self._context
action = self._choose_operator(state)
donor, _ = self._parent()
point = tuple(self._operators[action](tuple(parent), tuple(donor), self._variation))
self._context = None
self._pulls[action] += 1
self._counts["evaluations"] += 1
reward = self._offer(point, *evaluate(point, _rollout_seed(self._evaluation_seed, 0, evaluation)))
self._recent = .95 * self._recent + .05 * reward
if not initialize:
self._admissions[action] += reward > 0.
self._rewards[action] += reward
self._context = self._state()
self._observe(state, action, reward, self._context[1])
return self.stats