Source code for qdpy.algorithms.age_layered

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Age-layered MAP-Elites with distinct descriptors for successive layers.
# @see https://doi.org/10.1109/CEC53210.2023.10254093

"""Send measured lineages through archive layers as they age."""

from bisect import bisect_right
from dataclasses import dataclass
from heapq import heappop, heappush

import numpy as np

from ._population import _attempt_budget, _finite_vector
from .modern import _positive_int
from .task_search import _measurement, _offer, _validate_grid

__all__ = ["AgeLayeredResult", "age_layered_map_elites"]


## @brief Report the live layers, measurement budget, and age-driven migrations.
[docs] @dataclass(frozen=True) class AgeLayeredResult: """Admission and promotion counts are reported separately for each layer.""" archives: tuple evaluations: int immigrants: int admissions: tuple[int, ...] promotions: tuple[int, ...] expired: int
## @brief Compete in separate feature maps as the age of a lineage increases. # @param archives Ordered empty best-only grids or CVTs with a common objective direction. # @param evaluate Callable (genome) returning (scalar quality, one descriptor per layer). # @param sample Callable (rng) returning a fresh genome. # @param mutate Callable (parent, rng) returning a single descendant genome. # @param max_ages Strictly increasing exclusive age limits, one per layer except the last. # @param budget Number of evaluation attempts. # @param immigrant_interval Draw an age-zero immigrant at this interval. # @param seed Private search seed. # @return AgeLayeredResult with layers and counts.
[docs] def age_layered_map_elites(archives, evaluate, *, sample, mutate, max_ages, budget, immigrant_interval=8, seed=0): """Inherit the parent's birth evaluation and compete in the current age layer. At the first evaluation whose age reaches a layer limit, move or expire the individual using its cached measurement. Promotions count successful arrivals and expirations include rejected moves. The last layer has no age limit. """ archives = tuple(archives) limits = tuple(_positive_int(age, "max_ages") for age in max_ages) if (len(archives) < 2 or len({id(archive) for archive in archives}) != len(archives) or len(limits) != len(archives) - 1 or any(a >= b for a, b in zip(limits, limits[1:]))): raise ValueError("Supply distinct archives and strictly increasing ages for the bounded layers.") if not all(map(callable, (sample, mutate, evaluate))): raise TypeError("Supply callable sampling, mutation and evaluation.") for archive in archives: _validate_grid(archive) if {"alme_birth", "alme_descriptors"}.intersection((*archive.fitness_score_names, *archive.features_score_names)): raise ValueError("Use score names distinct from the ALME age and descriptor metadata.") direction = next((archive.fitness_weights[0] for archive in archives if archive.fitness_weights), 1.) if any(archive.fitness_weights and (archive.fitness_weights[0] > 0) != (direction > 0) for archive in archives): raise ValueError("Every layer must use the same objective direction.") budget = _attempt_budget(budget) interval = _positive_int(immigrant_interval, "immigrant_interval") for archive in archives: if archive.fitness_weights is None: archive._set_fitness_weights((direction,)) rng = np.random.default_rng(seed) admissions, promotions = [0] * len(archives), [0] * len(archives) immigrants = expired = 0 queue, pending = [], {} def place(layer, token, genome, fitness, descriptions, birth): archive = archives[layer] measurement = _measurement(archive, ((fitness,), descriptions[layer]), genome) candidate, cell = measurement if cell is None: return False previous = archive.solutions[cell][0] if archive.solutions[cell] else None candidate.name = str(token) candidate.scores["alme_birth"] = birth candidate.scores["alme_descriptors"] = descriptions before = archive.nb_added _offer(archive, measurement) if archive.nb_added == before: return False if layer < len(limits): if previous is not None: pending.pop(int(previous.name), None) pending[token] = layer, candidate heappush(queue, (birth + limits[layer], token)) return True for step in range(budget): while queue and queue[0][0] <= step: _, token = heappop(queue) entry = pending.pop(token, None) if entry is None: continue source, elite = entry birth = elite.scores["alme_birth"] destination = bisect_right(limits, step - birth) moved = place(destination, token, tuple(elite), elite.fitness.values[0], elite.scores["alme_descriptors"], birth) archives[source].discard(elite) promotions[destination] += moved expired += 1 occupied = [layer for layer in archives if layer] if step % interval == 0 or not occupied: genome, birth = tuple(sample(rng)), step immigrants += 1 else: source = occupied[int(rng.integers(len(occupied)))] parent = source[int(rng.integers(len(source)))] genome, birth = tuple(mutate(tuple(parent), rng)), parent.scores["alme_birth"] fitness, descriptions = evaluate(genome) descriptions = tuple(descriptions) if len(descriptions) != len(archives): raise ValueError("Return a descriptor vector for every layer.") measured = tuple(_finite_vector(point, "Layer descriptors", len(archive.features_domain)) for archive, point in zip(archives, descriptions)) layer = bisect_right(limits, step - birth) admissions[layer] += place(layer, step, genome, fitness, measured, birth) return AgeLayeredResult(archives, budget, immigrants, tuple(admissions), tuple(promotions), expired)