Source code for qdpy.algorithms.qqd

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Tabular Q-learning for local search within MAP-Elites.
# @see https://doi.org/10.1016/j.swevo.2025.101849

"""Choose one local-search operator per candidate using QQD's cyclic Q-table."""

from collections.abc import Mapping
from dataclasses import dataclass
from math import isfinite

import numpy as np

from qdpy.containers import Grid
from qdpy.phenotype import Features, Fitness, Individual
from ._population import _attempt_budget, _finite_vector
from .modern import _positive_int

__all__ = ["QQD", "QQDStats"]


## @brief Candidate and operator accounting for a QQD search.
[docs] @dataclass(frozen=True) class QQDStats: """Count failed evaluations, archive admissions, and operator attempts.""" evaluations: int failures: int archive_updates: int q_updates: int operator_attempts: tuple[tuple[str, int], ...]
## @brief Select named local-search operators using one Q-table row per batch position.
[docs] class QQD: """Run Qin et al.'s tabular operator selector with user-defined variation. Select a parent uniformly from the archive and learn from admission to its offspring's destination cell. A new cell yields one unit of reward, improvement yields a scaled quality gain, and rejection yields zero. The controller advances through batch positions cyclically. Each operator call proposes one candidate. :param archive: Parentless best-only Grid or CVTGrid with native scalar fitness. :param sample: Callable (rng) returning a fresh genome. :param operators: Ordered mapping of names to callbacks (genome, rng). :param batch_size: Number of positions in the cyclic controller state. :param initial_samples: Warm-up attempts, defaulting to batch_size. :param controller: ``q-learning``, ``uniform``, or ``bandit``. :param learning_rate: Initial Q-table step size in (0, 1]. :param discount: Bootstrapping coefficient in [0, 1]. :param epsilon: Initial exploration probability. :param epsilon_decay: Multiplier applied after each local proposal. :param anneal_batches: Optional batch count for annealing learning_rate toward .01. :param improvement_scale: Positive denominator floor for relative improvement. :param seed: Seed for selection, variation, and evaluator calls. """ def __init__(self, archive, *, sample, operators, batch_size=16, initial_samples=None, controller="q-learning", learning_rate=.5, discount=.9, epsilon=.3, epsilon_decay=.999, anneal_batches=None, improvement_scale=1e-12, seed=0): if (not isinstance(archive, Grid) or archive.parents or archive.max_items_per_bin != 1 or archive.discard_random_on_bin_overload or archive.fitness_score_names or archive.features_score_names or len(archive.fitness_domain or ()) != 1 or len(archive.fitness_weights or ()) != 1 or not isfinite(archive.fitness_weights[0]) or not archive.fitness_weights[0]): raise ValueError("Supply a parentless best-only grid with one signed native fitness.") if (not callable(sample) 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("Supply a sampler and a nonempty mapping of named local-search operators.") if (controller not in ("q-learning", "uniform", "bandit") or not 0 < learning_rate <= 1 or not 0 <= discount <= 1 or not 0 <= epsilon <= 1 or not 0 < epsilon_decay <= 1 or not 0 < improvement_scale < np.inf): raise ValueError("Use valid controller settings and positive finite improvement_scale.") self.archive, self._sample, self._controller = archive, sample, controller self._names, self._operators = tuple(operators), tuple(operators.values()) self._size = _positive_int(batch_size, "batch_size") self._warmup = self._size if initial_samples is None else _attempt_budget(initial_samples) self._anneal = None if anneal_batches is None else _positive_int(anneal_batches, "anneal_batches") self._learning_rate, self._floor = learning_rate, min(learning_rate, .01) self._discount, self._epsilon, self._decay, self._scale = discount, epsilon, epsilon_decay, improvement_scale self._choice, self._variation, self._evaluation = map( np.random.default_rng, np.random.SeedSequence(seed).spawn(3)) self._values = np.zeros((self._size, len(self._names))) self._attempts = np.zeros(len(self._names), dtype=int) self._totals = np.zeros(len(self._names)) self._evaluations = self._failures = self._updates = self._learned = self._local = 0 @property def q_values(self): """Return a copy of the table in batch position and operator order.""" return self._values.copy() @property def stats(self): """Return cumulative work and operator counts.""" return QQDStats(self._evaluations, self._failures, self._updates, self._learned, tuple(zip(self._names, map(int, self._attempts)))) def _action(self, state): if self._controller == "uniform": return int(self._choice.integers(len(self._names))) if self._controller == "q-learning": if self._choice.random() < self._epsilon: return int(self._choice.integers(len(self._names))) scores = self._values[state] else: unseen = np.flatnonzero(self._attempts == 0) if len(unseen): return int(self._choice.choice(unseen)) scores = self._totals / self._attempts + np.sqrt(2. * np.log(self._local) / self._attempts) return int(self._choice.choice(np.flatnonzero(scores == scores.max()))) def _offer(self, genome, result): if result is None: self._failures += 1 return 0. quality, features = result descriptor = _finite_vector(features, "Behavior descriptor", len(self.archive.features_domain)) quality = float(quality) if not isfinite(quality): raise ValueError("Fitness must be finite.") grid = self.archive if not grid.in_bounds((quality,), grid.fitness_domain) or not grid.in_bounds(descriptor, grid.features_domain): return 0. occupants = grid.solutions[grid.index_grid(descriptor)] previous = grid.get_ind_fitness(occupants[0]).values[0] if occupants else None before = grid.nb_added grid.add(Individual(genome, fitness=Fitness((quality,), weights=grid.fitness_weights), features=Features(descriptor))) if grid.nb_added == before: return 0. self._updates += 1 if previous is None: return 1. scale = max(abs(previous), abs(quality), self._scale) difference = abs(previous / scale - quality / scale) denominator = max(abs(previous), self._scale) / scale return 1. if difference >= denominator else difference / denominator ## @brief Continue MAP-Elites and update the tabular controller in evaluation order. # @param evaluate Callable (genome, seed) returning (fitness, descriptor) or None. # @param budget Additional candidate evaluation attempts. # @return A QQDStats snapshot.
[docs] def run(self, evaluate, budget): """Use the same next batch position when the search is continued.""" for _ in range(_attempt_budget(budget)): action = None state = self._local % self._size if self._evaluations < self._warmup or not self.archive: genome = tuple(self._sample(self._variation)) else: parent = tuple(self.archive[int(self._choice.integers(len(self.archive)))]) action = self._action(state) genome = tuple(self._operators[action](parent, self._variation)) self._attempts[action] += 1 self._evaluations += 1 reward = self._offer(genome, evaluate(genome, int(self._evaluation.integers(2**32)))) if action is None: continue self._totals[action] += reward if self._controller == "q-learning": successor = (state + 1) % self._size expected = reward + self._discount * float(self._values[successor].max()) previous = self._values[state, action] self._values[state, action] += self._learning_rate * (expected - previous) self._epsilon *= self._decay self._learned += 1 if self._anneal is not None: progress = min((self._local // self._size + 1) / self._anneal, 1.) self._learning_rate -= (self._learning_rate - self._floor) * progress self._local += 1 return self.stats