# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Parametric-Task MAP-Elites and rebinning of measured tasks.
"""Black-box search across a bounded continuous family of tasks."""
from dataclasses import dataclass, replace
from numbers import Real
import warnings
import numpy as np
from scipy.spatial import Delaunay, QhullError
from qdpy.containers import CVTGrid
from qdpy.phenotype import Features, Fitness, _CellIndividual
from .modern import _positive_int
__all__ = ["ParametricTaskEvaluation", "ParametricTaskResult", "parametric_task_map_elites"]
class _Coordinates:
"""Normalize coordinates for geometry and restore them for the evaluator."""
def __init__(self, bounds):
pairs = np.asarray(bounds, dtype=float)
if pairs.ndim != 2 or pairs.shape[1] != 2 or not len(pairs):
raise ValueError("Supply a nonempty sequence of (lower, upper) bounds.")
with np.errstate(over="ignore", invalid="ignore"):
spans = pairs[:, 1] - pairs[:, 0]
if not np.isfinite(pairs).all() or not np.isfinite(spans).all() or np.any(spans <= 0):
raise ValueError("Bounds must be finite, increasing, and have finite spans.")
self.bounds = tuple(map(tuple, pairs.tolist()))
self.lower, self.upper = pairs.T
self.span = spans
def normalize(self, values):
values = np.asarray(values, dtype=float)
if (values.ndim not in (1, 2) or values.shape[-1] != len(self.span)
or not np.all((values >= self.lower) & (values <= self.upper))):
raise ValueError("Coordinates must be finite and inside their declared bounds.")
return np.clip((values - self.lower) / self.span, 0, 1)
def physical(self, values):
return tuple(np.clip(self.lower + self.span * values, self.lower, self.upper).tolist())
## @brief A successful evaluation and the exact task that produced its fitness.
[docs]
@dataclass(frozen=True)
class ParametricTaskEvaluation:
"""Immutable observation in the caller's genome and task coordinates."""
genome: tuple[float, ...]
task: tuple[float, ...]
fitness: float
## @brief Archive, successful evaluations, and attempt counts from PT-ME.
[docs]
@dataclass(frozen=True)
class ParametricTaskResult:
"""A task repertoire and the evaluation data needed to change its resolution.
The archive stores genomes in physical units and feature coordinates in
the normalized task box. Every successful measurement appears in order
in evaluations. The attempts counter includes failed or invalid results.
"""
archive: CVTGrid
evaluations: tuple[ParametricTaskEvaluation, ...]
attempts: int
failures: int
task_bounds: tuple
tournament_attempts: dict[int, int]
tournament_successes: dict[int, int]
regression_proposals: int
## @brief Retrieve the elite in the nearest occupied cell to a physical task.
[docs]
def solution_for(self, task):
"""Return the recorded elite and its observed task, or None for an empty archive."""
point = _Coordinates(self.task_bounds).normalize(task)
if point.ndim != 1:
raise ValueError("Supply one task at a time.")
occupied = [i for i in range(self.archive.shape[0]) if self.archive.solutions[(i,)]]
if not occupied:
return None
offsets = self.archive.cluster_centers[occupied] - point
index = occupied[np.argmin(np.sum(offsets ** 2, axis=1))]
return self.evaluations[int(self.archive.solutions[(index,)][0].name)]
## @brief Replay measured evaluations at a new CVT resolution.
[docs]
def rebin(self, centroids):
"""Return another result using the same measurements and the new physical centroids."""
coordinates = _Coordinates(self.task_bounds)
archive = _task_archive(coordinates, centroids)
for i, record in enumerate(self.evaluations):
_offer_task(archive, record, i, coordinates.normalize(record.task))
return replace(self, archive=archive)
def _task_archive(coordinates, centroids):
centers = coordinates.normalize(centroids)
if centers.ndim != 2 or len(centers) == 0 or len(np.unique(centers, axis=0)) != len(centers):
raise ValueError("Supply a nonempty matrix of distinct task centroids.")
return CVTGrid(shape=len(centers), centroids=centers, features_domain=((0., 1.),) * centers.shape[1],
fitness_domain=((-float("inf"), float("inf")),), fitness_weights=(1.,))
def _offer_task(archive, record, position, point):
cell = archive.index_grid(point)
before = archive.nb_added
archive.add(_CellIndividual(record.genome, cell, name=str(position),
fitness=Fitness((record.fitness,), weights=(1.,)), features=Features(point)))
return archive.nb_added != before
def _task_neighbors(centers):
count, dimension = centers.shape
neighbors = [set() for _ in centers]
if dimension == 1:
order = np.argsort(centers[:, 0], kind="stable")
for a, b in zip(order, order[1:]):
neighbors[a].add(b)
neighbors[b].add(a)
elif count > dimension:
try:
simplices = Delaunay(centers).simplices
except QhullError:
simplices = ()
for simplex in simplices:
for vertex in simplex:
neighbors[vertex].update(i for i in simplex if i != vertex)
return tuple(tuple(sorted(row)) for row in neighbors)
def _regression_child(archive, neighbors, point, genomes, rng):
"""Predict a normalized genome from adjacent elites using through-origin least squares."""
cell = archive.index_grid(point)[0]
parents = [archive.solutions[(i,)][0] for i in neighbors[cell] if archive.solutions[(i,)]]
if len(parents) < len(point):
return None
tasks = np.asarray([elite.features.values for elite in parents], dtype=float)
samples = genomes.normalize([list(elite) for elite in parents])
fit, _, rank, _ = np.linalg.lstsq(tasks, samples, rcond=None)
if rank < len(point):
return None
prediction = point @ fit
return np.clip(prediction + rng.normal(size=len(prediction)) * samples.std(axis=0), 0, 1)
def _sbx(first, second, rng, eta=10):
"""Draw one simulated binary crossover child in the unit box."""
u = rng.random(len(first))
spread = np.where(u <= 0.5, 2 * u, 1 / (2 * (1 - u))) ** (1 / (eta + 1))
sign = rng.choice((-1, 1), size=len(first))
return np.clip((first + second + sign * spread * (first - second)) / 2, 0, 1)
def _tournament_size(sizes, attempts, successes):
for size in sizes:
if not attempts[size]:
return size
total = sum(attempts.values())
return max(sizes, key=lambda size: successes[size] / attempts[size]
+ np.sqrt(2 * np.log(total) / attempts[size]))
def _measure_task(evaluate, genome, task):
try:
fitness = evaluate(genome, task)
if not isinstance(fitness, Real) or not np.isfinite(fitness):
raise ValueError("Return one finite real fitness to maximize.")
except Exception as error:
warnings.warn(f"PT-ME evaluation failed: {error}", stacklevel=3)
return None
return ParametricTaskEvaluation(genome, task, float(fitness))
## @brief Search over new continuous task parameters using PT-ME.
[docs]
def parametric_task_map_elites(evaluate, *, genome_bounds, task_bounds, centroids, budget, seed=0,
regression_probability=0.5, tournament_sizes=(1, 5, 10, 50, 100, 500)):
"""Run Parametric-Task MAP-Elites with CVT task cells and one fitness per trial.
:param evaluate: Callable taking (genome, task) in physical units and
returning a finite scalar fitness to maximize.
:param genome_bounds: Ordered finite intervals for real genes.
:param task_bounds: Ordered finite intervals for continuous task parameters.
:param centroids: CVT centers in physical task units. Supply distinct points.
:param budget: Total attempts, including one seed per centroid.
:param seed: Seed for variation and task selection.
:param regression_probability: Probability of proposing by local regression.
:param tournament_sizes: Positive task sample sizes available to UCB1.
:returns: A ParametricTaskResult with the CVT archive and evaluation records.
The first proposal at each center samples a genome uniformly. Subsequent
evaluations draw tasks in the continuous domain. A regression fallback
applies SBX at the already selected task without crediting the tournament.
Each occupied cell keeps its highest recorded score. The incumbent wins ties.
"""
if not callable(evaluate):
raise TypeError("evaluate must be callable.")
if not 0 <= regression_probability <= 1:
raise ValueError("regression_probability must be in [0, 1].")
sizes = sorted({_positive_int(size, "tournament size") for size in tournament_sizes})
if not sizes:
raise ValueError("Supply at least one tournament size.")
genomes, tasks = _Coordinates(genome_bounds), _Coordinates(task_bounds)
centroids = np.array(centroids, dtype=float, copy=True)
archive = _task_archive(tasks, centroids)
centers = archive.cluster_centers
budget = _positive_int(budget, "budget")
if budget < len(centers):
raise ValueError("Budget must cover an initial evaluation at every centroid.")
neighbors = _task_neighbors(centers)
rng = np.random.default_rng(seed)
attempts, successes = dict.fromkeys(sizes, 0), dict.fromkeys(sizes, 0)
records = []
failures = regressions = 0
for step in range(budget):
arm = None
if step < len(centers):
point = centers[step]
task = tuple(centroids[step].tolist())
child = rng.random(len(genomes.span))
else:
point = rng.random(len(tasks.span))
child = None
if archive:
if rng.random() < regression_probability:
child = _regression_child(archive, neighbors, point, genomes, rng)
regressions += child is not None
else:
arm = _tournament_size(sizes, attempts, successes)
attempts[arm] += 1
if child is None:
first, second = (archive[i] for i in rng.integers(len(archive), size=2))
child = _sbx(genomes.normalize(first), genomes.normalize(second), rng)
if arm is not None:
sampled = rng.random((arm, len(tasks.span)))
delta = sampled - np.asarray(first.features.values)
point = sampled[np.argmin(np.sum(delta ** 2, axis=1))]
else:
child = rng.random(len(genomes.span))
task = tasks.physical(point)
record = _measure_task(evaluate, genomes.physical(child), task)
if record is None:
failures += 1
continue
accepted = _offer_task(archive, record, len(records), tasks.normalize(task))
records.append(record)
if arm is not None and accepted:
successes[arm] += 1
return ParametricTaskResult(archive, tuple(records), budget, failures, tasks.bounds,
attempts, successes, regressions)