# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief LUCIE-style confidence races for fixed-niche, noisy MAP-Elites.
# @see https://erwanlecarpentier.github.io/pdf/lecarpentier22lucie.pdf
"""Race a challenger against the incumbent in a fixed descriptor cell."""
from dataclasses import dataclass
from math import isfinite, log, pi, sqrt
import numpy as np
from qdpy.containers import CVTGrid, Grid
from qdpy.phenotype import Features, Fitness, Individual
from qdpy.tools import iso_line_dd
from .modern import _positive_int, _variation_settings
from .sampling import _rollout_seed
__all__ = ["LUCIEMAPElites", "LUCIESearchStats"]
## @brief Raw rollout costs and the outcomes of two-elite confidence races.
[docs]
@dataclass(frozen=True)
class LUCIESearchStats:
"""Counters refer to an individual run call."""
evaluations: int
incumbent_evaluations: int
proposals: int
out_of_domain: int
certified_races: int
unresolved_races: int
replacements: int
@dataclass(frozen=True)
class _Arm:
genome: tuple
features: tuple
identifier: int
samples: int = 0
mean: float = 0.
def observe(self, quality):
count = self.samples + 1
return _Arm(self.genome, self.features, self.identifier,
count, self.mean + (quality - self.mean) / count)
## @brief Compute a run-wide confidence interval for a bounded [0, 1] arm.
def _confidence(arm, delta):
# Spend delta across arms and across sample counts with two summable
# inverse-square schedules. The leading factor two is two-sided Hoeffding.
log_term = log(pi**4 / 18.) + 2 * log(arm.identifier) + 2 * log(arm.samples) - log(delta)
radius = sqrt(log_term / (2 * arm.samples))
return max(0., arm.mean - radius), min(1., arm.mean + radius)
## @brief Use paired confidence bounds to resolve local replacement under a rollout budget.
[docs]
class LUCIEMAPElites:
"""Assume deterministic descriptors and independent bounded fitness observations.
Race against an incumbent only within the challenger's predetermined
cell. Reuse the incumbent's earlier observations. Once the outsider's
upper bound is within epsilon of the leader's lower bound, the leader
is an epsilon-accurate choice under the confidence event. If the
rollout or pair budget ends first, use the empirical leader and
record an unresolved race. Exact ties retain the incumbent.
:param archive: Empty standalone best-only Grid or CVTGrid, with one
finite fitness interval covering the support of every observation.
Unweighted archives maximize fitness.
:param dimension: Real genome length.
:param delta: Total confidence error allowance across arms and sample counts.
:param epsilon: Additive fitness tolerance in original units.
:param initial_samples: Number of fitness observations for a new arm.
:param max_pairs: Maximum extra pairs per local race.
:param ind_domain: Shared finite, increasing genome bounds.
:param iso_sigma: Isotropic mutation scale.
:param line_sigma: Directional mutation scale.
:param seed: Private variation and evaluator seed.
"""
def __init__(self, archive, dimension, *, delta=.05, epsilon=0., initial_samples=2,
max_pairs=16, ind_domain=(0., 1.), iso_sigma=.03, line_sigma=.2, seed=0):
if (type(archive) not in (Grid, CVTGrid) or len(archive) or archive.parents
or archive.max_items_per_bin != 1 or archive.discard_random_on_bin_overload
or archive.fitness_domain is None or len(archive.fitness_domain) != 1
or archive.fitness_score_names or archive.features_score_names):
raise ValueError("Use an empty standalone scalar best-only Grid or CVTGrid.")
low, high = archive.fitness_domain[0]
span = high - low
weights = archive.fitness_weights
if weights is None:
weights = (1.,)
if (not 0. < span < np.inf or len(weights) != 1 or not isfinite(weights[0]) or weights[0] == 0.
or not 0. < delta < 1. or not 0. <= epsilon <= span):
raise ValueError("Supply a finite fitness span, nonzero weight, delta in (0, 1), and epsilon within the span.")
self.archive = archive
self.dimension = _positive_int(dimension, "dimension")
self.initial_samples = _positive_int(initial_samples, "initial_samples")
self.max_pairs = _positive_int(max_pairs, "max_pairs")
self.ind_domain = _variation_settings(ind_domain, iso_sigma, line_sigma)
if not isfinite(self.ind_domain[1] - self.ind_domain[0]):
raise ValueError("Use a finite genome span.")
self._low, self._high, self._span = low, high, span
self._weights = tuple(weights)
self._maximizing = weights[0] > 0
self._epsilon, self._delta = epsilon / span, delta
self.iso_sigma, self.line_sigma = iso_sigma, line_sigma
self.seed = int(np.random.SeedSequence(seed).generate_state(1, dtype=np.uint64)[0])
self._rng = np.random.default_rng(self.seed)
self._evaluations = self._arms = 0
def _propose(self):
if not self.archive:
return tuple(self._rng.uniform(*self.ind_domain, size=self.dimension))
slots = self._rng.integers(len(self.archive), size=2)
return tuple(iso_line_dd(self.archive[int(slots[0])], self.archive[int(slots[1])],
iso_sigma=self.iso_sigma, line_sigma=self.line_sigma,
bounds=self.ind_domain, rng=self._rng))
def _observe(self, evaluate, arm):
seed = _rollout_seed(self.seed, 0, self._evaluations)
self._evaluations += 1
fitness = float(evaluate(arm.genome, seed))
if not self._low <= fitness <= self._high:
raise ValueError("Fitness observations must be finite and within the declared support.")
fraction = (fitness - self._low) / self._span
return arm.observe(fraction if self._maximizing else 1. - fraction)
def _select(self, incumbent, challenger):
keep = incumbent.mean >= challenger.mean
leader, outsider = (incumbent, challenger) if keep else (challenger, incumbent)
lower, _ = _confidence(leader, self._delta)
_, upper = _confidence(outsider, self._delta)
return leader, upper - lower <= self._epsilon
def _admit(self, winner, old=None):
quality = (self._low + self._span * winner.mean if self._maximizing
else self._high - self._span * winner.mean)
elite = Individual(winner.genome, fitness=Fitness((float(np.clip(quality, self._low, self._high)),),
weights=self._weights),
features=Features(winner.features))
elite._lucie_arm = winner
elite.scores["rollout_count"] = winner.samples
if old is not None:
self.archive.discard(old)
self.archive.add(elite)
## @brief Spend an additional hard budget of scalar fitness calls.
# @param evaluate Callable receiving a genome and a fresh seed and returning one bounded draw.
# @param descriptor Deterministic function returning the genome's archive coordinates.
# @param budget Maximum number of fitness calls in this run.
# @param proposal_limit Cap on descriptor proposals, including out-of-domain ones.
# @return Raw rollout and race counters for this call.
[docs]
def run(self, evaluate, descriptor, budget, *, proposal_limit=None):
"""Use evaluate(genome, seed) for fitness and descriptor(genome) for a fixed cell."""
if not callable(evaluate) or not callable(descriptor):
raise TypeError("Supply callable evaluate and descriptor functions.")
budget = _positive_int(budget, "budget")
limit = 10 * budget if proposal_limit is None else _positive_int(proposal_limit, "proposal_limit")
start = self._evaluations
end = start + budget
incumbent_calls = proposals = outside = certified = unresolved = replacements = 0
while self._evaluations < end and proposals < limit:
proposals += 1
genome = self._propose()
features = tuple(map(float, descriptor(genome)))
if len(features) != len(self.archive.features_domain) or not all(map(isfinite, features)):
raise ValueError("Return a finite descriptor of the configured length.")
if not self.archive.in_bounds(features, self.archive.features_domain):
outside += 1
continue
cell = self.archive.index_grid(features)
front = self.archive.solutions[cell]
prior = front[0] if front else None
if prior is not None and tuple(prior) == genome:
revised = self._observe(evaluate, prior._lucie_arm)
incumbent_calls += 1
self._admit(revised, prior)
continue
self._arms += 1
challenger = _Arm(genome, features, self._arms)
for _ in range(min(self.initial_samples, end - self._evaluations)):
challenger = self._observe(evaluate, challenger)
if prior is None:
if self.archive.free >= 1:
self._admit(challenger)
continue
incumbent = prior._lucie_arm
winner, complete = self._select(incumbent, challenger)
for _ in range(self.max_pairs):
if complete or self._evaluations + 2 > end:
break
incumbent = self._observe(evaluate, incumbent)
challenger = self._observe(evaluate, challenger)
incumbent_calls += 1
winner, complete = self._select(incumbent, challenger)
certified += complete
unresolved += not complete
replacements += winner is challenger
if winner is challenger or winner is not prior._lucie_arm:
self._admit(winner, prior)
return LUCIESearchStats(self._evaluations - start, incumbent_calls, proposals, outside,
certified, unresolved, replacements)