# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief MAP-Elites with fixed-task transfer and time-dependent measurements.
"""Sequential MAP-Elites runners for fixed tasks and changing environments."""
from collections import deque
from collections.abc import Mapping
from dataclasses import dataclass
from math import isfinite
from numbers import Real
import warnings
import numpy as np
from qdpy.containers import CVTGrid, Grid
from qdpy.containers.base import _IndexedOrderedSet
from qdpy.phenotype import Features, Fitness, Individual, ScoresDict
from qdpy.tools import iso_line_dd
from .modern import _bounds, _positive_int
__all__ = ["MultiTaskResult", "DynamicResult", "mtmb_search", "dynamic_map_elites"]
_GRID_ADMISSION_HOOKS = frozenset((
"add", "discard", "index_grid", "_add_internal", "_add_to_grid", "_replacement_in_bin",
"_add_to_collection", "_add_to_parents", "_consider_for_best", "_check_if_can_be_added",
"get_ind_fitness", "get_ind_features", "in_bounds", "_fitness_with_container_weights",
))
## @brief Live task archives and counters from a fixed-task search.
[docs]
@dataclass(frozen=True)
class MultiTaskResult:
"""Per-task attempt and failure counts alongside the supplied grids."""
archives: dict
attempts_by_task: dict
failures_by_task: dict
## @brief A dynamic archive and the evaluator calls spent maintaining it.
[docs]
@dataclass(frozen=True)
class DynamicResult:
"""Search and refresh attempts include failed and discarded measurements."""
archive: Grid
offspring_attempts: int
refresh_attempts: int
failures: int
detected_change_ticks: tuple[int, ...]
incomplete_updates: int
def _search_bounds(domain):
lower, upper = _bounds(tuple(map(float, domain)))
if not isfinite(upper - lower):
raise ValueError("Genome bounds must have a finite span.")
return lower, upper
def _validate_grid(archive, *, empty=True):
if (type(archive) not in (Grid, CVTGrid) or (empty and len(archive)) or archive.parents
or len(archive.fitness_domain) != 1 or archive.max_items_per_bin != 1
or archive.discard_random_on_bin_overload):
condition = "an empty" if empty else "a"
raise ValueError(f"Supply {condition} parentless, best-only Grid or CVTGrid with one objective.")
weights = archive.fitness_weights
if weights is not None and (len(weights) != 1 or not isfinite(weights[0]) or weights[0] == 0):
raise ValueError("Supply a finite nonzero objective weight.")
if len(archive.fitness_score_names) not in (0, 1) or len(archive.features_score_names) not in (
0, len(archive.features_domain)):
raise ValueError("Named scores must match the grid's objective and descriptor counts.")
def _measurement(archive, result, genome):
"""Validate measurements and resolve their cell before admission."""
(fitness,), descriptors = result
descriptors = tuple(descriptors)
if len(descriptors) != len(archive.features_domain):
raise ValueError("Descriptor length must match the grid.")
if not all(isinstance(value, Real) and isfinite(value) for value in (fitness, *descriptors)):
raise ValueError("Fitness and descriptors must be finite real numbers.")
fitness = float(fitness)
descriptors = tuple(map(float, descriptors))
scores = ScoresDict()
for name, value in [*zip(archive.fitness_score_names, (fitness,)),
*zip(archive.features_score_names, descriptors)]:
if scores.setdefault(name, value) != value:
raise ValueError(f"Conflicting measurements for score {name!r}.")
candidate = Individual(genome, fitness=Fitness((fitness,), weights=archive.fitness_weights),
features=Features(descriptors), scores=scores)
if (archive.in_bounds(descriptors, archive.features_domain)
and archive.in_bounds((fitness,), archive.fitness_domain)):
return candidate, archive.index_grid(descriptors)
return candidate, None
def _measure(archive, evaluate, args, genome):
"""Build a fresh grid entry and resolve its destination before admission."""
try:
return _measurement(archive, evaluate(*args), genome)
except Exception as error:
warnings.warn(f"MAP-Elites evaluation failed: {error}", stacklevel=3)
return None
def _offer(archive, measurement):
candidate, cell = measurement
if cell is not None and (archive.solutions[cell] or archive.free >= 1):
archive.add(candidate)
## @brief Maintain ages on admission to an ordinary best-only grid.
def _offer_with_age(archive, measurement, last_touched, step):
candidate, cell = measurement
if cell is None:
return
front = archive.solutions[cell]
previous = front[0] if front else None
nb_added = archive.nb_added
_offer(archive, measurement)
if archive.nb_added != nb_added:
if previous is not None:
del last_touched[id(previous)]
last_touched[id(candidate)] = step
## @brief Share parents among independent task archives.
[docs]
def mtmb_search(archives, evaluate, *, dimension, budget, ind_domain=(0, 1), seed=0, share_parents=True,
on_step=None):
"""Run fixed-task Multi-Task Multi-Behavior MAP-Elites.
Each proposal is evaluated for one task and can only enter that task's
grid. After warm-up, select each parent by first drawing a populated task
and then drawing an elite from it.
:param archives: Mapping from task IDs to distinct, empty best-only grids.
:param evaluate: Callable taking a task ID and a tuple of real coordinates.
Return a one-value fitness tuple followed by the descriptors.
:param dimension: Number of genome coordinates.
:param budget: Total attempted evaluations across all tasks.
:param ind_domain: Shared inclusive genome bounds.
:param seed: Seed for independent task-selection and variation streams.
:param share_parents: Draw from all populated tasks. False limits the
parent pool to the task being evaluated.
:param on_step: Optional callback receiving the task archives and the
keyword arguments ``iteration`` and ``evaluations`` after each attempt.
:returns: The live task archives and their attempt and failure counts.
"""
if not isinstance(archives, Mapping) or not archives:
raise ValueError("Supply a nonempty mapping of task IDs to grids.")
archives = dict(archives)
if len({id(archive) for archive in archives.values()}) != len(archives):
raise ValueError("Use a distinct archive for each task.")
for archive in archives.values():
_validate_grid(archive)
if not callable(evaluate):
raise TypeError("evaluate must be callable.")
if on_step is not None and not callable(on_step):
raise TypeError("on_step must be callable.")
dimension = _positive_int(dimension, "dimension")
budget = _positive_int(budget, "budget")
bounds = _search_bounds(ind_domain)
task_seed, variation_seed = np.random.SeedSequence(seed).spawn(2)
tasks_rng = np.random.default_rng(task_seed)
rng = np.random.default_rng(variation_seed)
tasks = tuple(archives)
attempts = dict.fromkeys(tasks, 0)
failures = dict.fromkeys(tasks, 0)
iso_sigma = 0.01 * (bounds[1] - bounds[0])
for step in range(1, budget + 1):
task = tasks[tasks_rng.integers(len(tasks))]
archive = archives[task]
populated = [grid for grid in archives.values() if grid]
parents = populated if share_parents else ([archive] if archive else [])
if parents and sum(map(len, populated)) >= len(tasks):
first, second = (parents[i] for i in rng.integers(len(parents), size=2))
child = iso_line_dd(first[rng.integers(len(first))], second[rng.integers(len(second))],
iso_sigma=iso_sigma, bounds=bounds, rng=rng)
else:
child = rng.uniform(*bounds, size=dimension)
genome = tuple(map(float, child))
attempts[task] += 1
measurement = _measure(archive, evaluate, (task, genome), genome)
if measurement is None:
failures[task] += 1
else:
_offer(archive, measurement)
if on_step is not None:
on_step(archives, iteration=step, evaluations=step)
return MultiTaskResult(archives, attempts, failures)
def _stage_refresh(archive, incumbent, refresh, remeasure):
"""Follow occupied destinations with the original grid still in place."""
pending = deque([incumbent])
visited = {id(incumbent)}
staged = {}
changed = False
while pending:
old = pending.popleft()
fresh = remeasure(old)
if fresh is None:
return None, changed
new, cell = fresh
different = (
archive.get_ind_fitness(new).values != archive.get_ind_fitness(old).values
or tuple(archive.get_ind_features(new)) != tuple(archive.get_ind_features(old))
)
changed |= different
staged[id(old)] = fresh
if refresh == "all" and old is incumbent and different:
pending.extend(elite for elite in archive if elite is not incumbent)
elif refresh == "local" and cell is not None and archive.solutions[cell]:
neighbour = archive.solutions[cell][0]
if id(neighbour) not in visited:
visited.add(id(neighbour))
pending.append(neighbour)
return staged, changed
## @brief Search while rechecking elites whose measurements may have changed.
[docs]
def dynamic_map_elites(archive, evaluate, *, dimension, budget, ind_domain=(0, 1), seed=0, refresh="local",
on_step=None):
"""Run sequential Dynamic MAP-Elites with a shared attempt budget.
The evaluator receives a frozen tick for the offspring and its refresh
chain. Publish a step only after all required refresh calls succeed.
A finite measurement outside the archive domain is valid and unstorable.
:param archive: Empty, parentless, best-only Grid or CVTGrid.
:param evaluate: Callable accepting a genome and the attempts already
spent at the start of the step. Return ``((fitness,), descriptors)``.
:param dimension: Number of real genome coordinates.
:param budget: Attempt limit inclusive of incumbent refreshes.
:param ind_domain: Shared inclusive genome bounds.
:param seed: Seed for parent selection and mutation.
:param refresh: Use local cascading refresh, refresh all on a change,
or perform no refresh (``"local"``, ``"all"``, ``"none"``).
:param on_step: Optional callback receiving the archive and the keyword
arguments ``iteration`` and ``evaluations`` after each search step.
:returns: The live archive and counts for search, refreshes and failures.
"""
_validate_grid(archive)
if refresh not in ("local", "all", "none"):
raise ValueError("refresh must be 'local', 'all', or 'none'.")
if not callable(evaluate):
raise TypeError("evaluate must be callable.")
if on_step is not None and not callable(on_step):
raise TypeError("on_step must be callable.")
dimension = _positive_int(dimension, "dimension")
budget = _positive_int(budget, "budget")
bounds = _search_bounds(ind_domain)
sigma = 0.1 * (bounds[1] - bounds[0])
rng = np.random.default_rng(seed)
last_touched = {}
offspring_attempts = refresh_attempts = failures = incomplete_updates = step = 0
change_ticks = []
track_ages = type(archive) is Grid and on_step is None
def measure(args, genome):
nonlocal track_ages
revision = archive.nb_operations if track_ages else None
result = _measure(archive, evaluate, args, genome)
if revision is not None and (revision != archive.nb_operations or archive.parents
or archive.max_items_per_bin != 1
or archive.discard_random_on_bin_overload
or type(archive.items) not in (list, _IndexedOrderedSet)
or not vars(archive).keys().isdisjoint(_GRID_ADMISSION_HOOKS)):
# An evaluator can close over the archive and change its members.
track_ages = False
return result
def offer(measurement):
if track_ages:
_offer_with_age(archive, measurement, last_touched, step)
else:
_offer(archive, measurement)
while offspring_attempts + refresh_attempts < budget:
tick = offspring_attempts + refresh_attempts
step += 1
if archive:
scales = [1 + step - last_touched[id(elite)] for elite in archive]
parent = archive[rng.exponential(scales).argmax()]
last_touched[id(parent)] = step
child = np.clip(np.asarray(parent) + rng.normal(0, sigma, size=dimension), *bounds)
else:
child = rng.uniform(*bounds, size=dimension)
genome = tuple(map(float, child))
offspring_attempts += 1
offspring = measure((genome, tick), genome)
complete = True
if offspring is None:
failures += 1
complete = False
elif (cell := offspring[1]) is not None and refresh != "none" and archive.solutions[cell]:
def remeasure(elite):
nonlocal refresh_attempts, failures
if offspring_attempts + refresh_attempts >= budget:
return None
genome = tuple(elite)
refresh_attempts += 1
result = measure((genome, tick), genome)
failures += result is None
return result
staged, changed = _stage_refresh(archive, archive.solutions[cell][0], refresh, remeasure)
if changed:
change_ticks.append(tick)
if staged is None:
incomplete_updates += 1
complete = False
else:
original_order = [elite for elite in archive if id(elite) in staged]
for old in original_order:
archive.discard(old)
del last_touched[id(old)]
for old in original_order:
offer(staged[id(old)])
if complete and offspring[1] is not None:
offer(offspring)
if not track_ages:
last_touched = {id(elite): last_touched.get(id(elite), step) for elite in archive}
if on_step is not None:
on_step(archive, iteration=step, evaluations=offspring_attempts + refresh_attempts)
return DynamicResult(archive, offspring_attempts, refresh_attempts, failures,
tuple(change_ticks), incomplete_updates)