Source code for qdpy.algorithms.hierarchical

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Coarse-to-fine MAP-Elites with lazily allocated subarchives.
# @see https://doi.org/10.1145/3795101.3805462

"""Retain a repertoire of fine alternatives within each coarse niche."""

from math import isfinite

import numpy as np

from .modern import _positive_int
from .task_search import _measurement, _offer, _validate_grid

__all__ = ["HierarchicalArchive", "HierarchicalMAPElites"]


## @brief Route one measured genome to its coarse niche and local archive.
[docs] class HierarchicalArchive: """Use a fixed coarse geometry and one best-only archive per occupied niche. :param coarse: Empty best-only Grid or CVTGrid. Its descriptors locate a branch, and its fitness bounds and objective direction apply to each branch. The geometry stays empty. :param make_fine: Callback (coarse_index) constructing a fresh empty best-only Grid or CVTGrid for that branch. Fine geometry and capacity may differ across branches. Treat returned grids as views when reading them through this archive. """ def __init__(self, coarse, make_fine): _validate_grid(coarse) if not callable(make_fine): raise TypeError("Supply a factory for fine archives.") if coarse.fitness_weights is None: coarse._set_fitness_weights((1.,)) self.coarse = coarse self._make_fine = make_fine self._branches = {} @property def subarchives(self): """Return the occupied coarse indices and their fine archives.""" return dict(self._branches) def __iter__(self): for branch in self._branches.values(): yield from branch def __len__(self): return sum(map(len, self._branches.values())) ## @brief Find the coarse niche for a descriptor vector.
[docs] def index(self, descriptor): """Return the coarse Grid or CVTGrid index.""" return self.coarse.index_grid(tuple(descriptor))
## @brief Return alternatives for the coarse cell containing a requested descriptor.
[docs] def alternatives(self, descriptor): """Return the measured fine elites as a tuple, or an empty tuple for an empty branch.""" return tuple(self._branches.get(self.index(descriptor), ()))
## @brief Return exact coarse measurements associated with a fine elite.
[docs] def coarse_descriptor(self, elite): """Return the coarse descriptor stored when this elite was measured.""" return elite._hierarchical_descriptor
## @brief Filter retained elites by inclusive coarse descriptor bounds.
[docs] def query(self, bounds): """Return alternatives matching one (lower, upper) pair per coarse axis.""" bounds = tuple(tuple(map(float, pair)) for pair in bounds) if (len(bounds) != len(self.coarse.features_domain) or any(len(pair) != 2 or not all(map(isfinite, pair)) or pair[0] > pair[1] for pair in bounds)): raise ValueError("Supply one finite inclusive interval per coarse descriptor.") return tuple(elite for elite in self if all(lower <= value <= upper for value, (lower, upper) in zip(self.coarse_descriptor(elite), bounds)))
def _new_branch(self, index): branch = self._make_fine(index) _validate_grid(branch) if (branch is self.coarse or id(branch) in {id(other) for other in self._branches.values()} or tuple(branch.fitness_domain) != tuple(self.coarse.fitness_domain) or branch.fitness_weights not in (None, self.coarse.fitness_weights)): raise ValueError("Each branch needs its own grid and the coarse fitness domain and weights.") branch._set_fitness_weights(self.coarse.fitness_weights) return branch ## @brief Try to admit a measured alternative at a coarse-to-fine path.
[docs] def add(self, genome, fitness, coarse_descriptor, fine_descriptor): """Return True if the candidate fills or improves a fine cell. Genomes are immutable and hashable. Fine archive entries store the original genome at index zero, its measured fine features, and the coarse descriptor used to route it. Measurements outside either descriptor domain are skipped. """ hash(genome) coarse_descriptor = tuple(coarse_descriptor) _, index = _measurement(self.coarse, ((fitness,), coarse_descriptor), (genome,)) if index is None: return False branch = self._branches.get(index) if branch is None: branch = self._new_branch(index) measurement = _measurement(branch, ((fitness,), fine_descriptor), (genome,)) measurement[0]._hierarchical_descriptor = tuple(map(float, coarse_descriptor)) previous = branch.nb_added _offer(branch, measurement) if branch.nb_added != previous: self._branches[index] = branch return True return False
## @brief Select a branch uniformly, then sample a fine elite.
[docs] def sample(self, rng): """Return an elite using a NumPy generator.""" if not self._branches: raise ValueError("The hierarchy needs at least one elite to sample.") branches = tuple(self._branches.values()) branch = branches[int(rng.integers(len(branches)))] return branch[int(rng.integers(len(branch)))]
## @brief Evolve a hierarchical repertoire with branch-uniform parent selection.
[docs] class HierarchicalMAPElites: """Search with caller-defined initialization, mutation and evaluation. :param archive: HierarchicalArchive, optionally seeded. :param propose: Callback (rng) returning a new genome. :param mutate: Callback (parent_genome, rng) returning an offspring. :param random_fraction: Probability of drawing a fresh genome when parents are available. :param seed: Seed for parent selection and genome proposals. """ def __init__(self, archive, *, propose, mutate, random_fraction=.1, seed=0): if not isinstance(archive, HierarchicalArchive) or not callable(propose) or not callable(mutate): raise TypeError("Supply a HierarchicalArchive and callable proposal and mutation.") if not 0. <= random_fraction <= 1.: raise ValueError("random_fraction must be in [0, 1].") self.archive = archive self._propose, self._mutate = propose, mutate self._rng = np.random.default_rng(seed) self._random_fraction = random_fraction self.nb_evaluations = 0 self.nb_failures = 0 ## @brief Add an evaluation budget to the current repertoire.
[docs] def run(self, evaluate, *, budget): """Evaluate genomes for (fitness, coarse descriptor, fine descriptor). A failed evaluation returned as None still consumes an attempt. """ for _ in range(_positive_int(budget, "budget")): if self.archive._branches and self._rng.random() >= self._random_fraction: genome = self._mutate(self.archive.sample(self._rng)[0], self._rng) else: genome = self._propose(self._rng) self.nb_evaluations += 1 result = evaluate(genome) if result is None: self.nb_failures += 1 else: self.archive.add(genome, *result) return self.archive