# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Archive-Sampling with a fitness–reproducibility admission rule.
# @see https://arxiv.org/abs/2409.13315
"""Adaptive repeats and depth-ranked delta comparison for noisy illumination."""
from math import isfinite
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 _fresh, _stage_archive
from .uncertain import _Rollouts, _cell
__all__ = ["ASDelta"]
## @brief Compare signed fitness and reproducibility with Eq. 5 of Flageat et al.
def _delta_preferred(candidate, incumbent, delta_f, delta_r):
fitness, reproducibility = candidate
previous_fitness, previous_reproducibility = incumbent
if candidate == incumbent:
return False
gain = fitness - previous_fitness
if gain >= delta_f:
return True
if gain >= 0. and reproducibility >= previous_reproducibility:
return True
return gain >= -delta_f and reproducibility - previous_reproducibility >= delta_r
## @brief Estimate negative mean population standard deviation in descriptor units.
def _negative_mean_std(rows):
scales = np.max(np.abs(rows), axis=0)
normalized = rows / np.where(scales == 0., 1., scales)
spread = np.std(normalized, axis=0).clip(max=1.) * scales
return -float(np.sum(spread / len(spread)))
## @brief Apply adaptive Archive-Sampling with bounded cascade replacement.
[docs]
class ASDelta:
"""Maintain a preference-ordered depth in every occupied descriptor cell.
Refresh every incumbent once per generation before selecting new parents.
An offspring requires a complete initial repeat group. Failed refreshes
retain the last estimate and every attempted rollout counts. Rebuild the
rankings from refreshed measurements, including changes of niche. A
final generation needs room for all refreshes and one offspring group.
:param container: Empty standalone Grid or CVTGrid with one objective.
Its max_items_per_bin sets the depth. Leave it under the search's control.
:param budget: Total raw rollout attempts, including incumbent refreshes.
:param dimension: Number of bounded real decision variables.
:param delta_f: Fitness tolerance in raw fitness units.
:param delta_r: Reproducibility improvement required to accept a performance loss.
:param sampling_size: Maximum raw rollout attempts per generation. It must
allow a full archive refresh and at least one new candidate.
:param initial_samples: Number of repeated measurements for new candidates.
:param estimator: "mean" or "median" for both measurements, or a pair
selecting the fitness and descriptor estimators independently.
:param reproducibility: Optional callable taking the matrix of raw descriptors
and returning a finite scalar to maximize. Defaults to negative mean
population standard deviation across the descriptor coordinates.
:param ind_domain: Shared decision bounds.
:param iso_sigma: Independent Iso+LineDD noise scale.
:param line_sigma: Directional Iso+LineDD noise scale.
:param seed: Seed for variation and the independent rollout stream.
"""
def __init__(self, container, budget, dimension, *, delta_f, delta_r,
sampling_size=128, initial_samples=2, estimator="median", reproducibility=None,
ind_domain=(0., 1.), iso_sigma=.01, line_sigma=.2, seed=0):
if (type(container) not in (Grid, CVTGrid) or len(container) or container.parents
or len(container.fitness_domain) != 1 or not len(container.features_domain)
or container.fitness_score_names or container.features_score_names):
raise ValueError("Use an empty standalone scalar Grid or CVTGrid with direct measurements.")
weights = container.fitness_weights
if weights is not None and (len(weights) != 1 or not isfinite(weights[0]) or weights[0] == 0):
raise ValueError("Use one finite nonzero fitness weight.")
if not all(0 <= value < np.inf for value in (delta_f, delta_r)):
raise ValueError("Both delta tolerances must be finite and nonnegative.")
reducers = {"mean": np.mean, "median": np.median}
estimators = (estimator, estimator) if isinstance(estimator, str) else tuple(estimator)
if len(estimators) != 2 or any(name not in reducers for name in estimators):
raise ValueError("Choose 'mean' or 'median' for each estimator.")
if reproducibility is not None and not callable(reproducibility):
raise TypeError("reproducibility must be callable.")
self.container = container
self.budget = _positive_int(budget, "budget")
self.dimension = _positive_int(dimension, "dimension")
self.sampling_size = _positive_int(sampling_size, "sampling_size")
self.initial_samples = _positive_int(initial_samples, "initial_samples")
if (self.sampling_size < container.capacity + self.initial_samples
or not 2 <= self.initial_samples <= self.budget):
raise ValueError("Fit all refreshes and a new group of at least two rollouts within the limits.")
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 finite decision spans.")
self.delta_f, self.delta_r = delta_f, delta_r
self.iso_sigma, self.line_sigma = iso_sigma, line_sigma
self._direction = -1. if weights is None else float(np.sign(weights[0]))
self._fitness_estimator, self._descriptor_estimator = (reducers[name] for name in estimators)
self._reproducibility = _negative_mean_std if reproducibility is None else reproducibility
self.seed = int(np.random.SeedSequence(seed).generate_state(1, dtype=np.uint64)[0])
self._rng = np.random.default_rng(self.seed)
self._fronts = {}
self.nb_evaluations = self.failed_evaluations = self.completed_candidates = 0
self.incumbent_evaluations = self.offspring_evaluations = 0
## @brief Return the live entries in cascade order, with the preferred elite first.
[docs]
def front(self, cell):
"""Return the most-to-least preferred members of one descriptor cell."""
return tuple(self._fronts.get(cell, ()))
def _measurement(self, candidate, observations):
rows = np.asarray([(*obs.fitness, *obs.features) for obs in observations], dtype=float)
scale = np.max(np.abs(rows), axis=0)
normalized = rows / np.where(scale == 0., 1., scale)
fitness = self._fitness_estimator(normalized[:, 0]) * scale[0]
descriptors = self._descriptor_estimator(normalized[:, 1:], axis=0) * scale[1:]
score = float(self._reproducibility(rows[:, 1:]))
if not isfinite(score):
raise ValueError("The reproducibility estimator must return a finite scalar.")
measured = Individual(candidate, name=candidate.name,
fitness=Fitness((fitness,), weights=(self._direction,)),
features=Features(descriptors))
measured.elapsed = sum(row.elapsed for row in observations)
measured._observations = observations
measured.scores.update(reproducibility=score, rollout_count=len(rows))
return measured
def _scores(self, item):
return self._direction * item.fitness.values[0], item.scores["reproducibility"]
def _cascade(self, fronts, seen, candidate):
cell = _cell(self.container, candidate)
genome = tuple(candidate)
if (genome in seen or cell is None
or not self.container.in_bounds(candidate.fitness.values, self.container.fitness_domain)):
return
seen.add(genome)
front = fronts.setdefault(cell, [])
for i, incumbent in enumerate(front):
if _delta_preferred(self._scores(candidate), self._scores(incumbent), self.delta_f, self.delta_r):
front[i], candidate = candidate, incumbent
if len(front) < self.container.max_items_per_bin:
front.append(candidate)
def _propose(self, count, fronts):
occupied = tuple(fronts.values())
if not occupied:
return [Individual(self._rng.uniform(*self.ind_domain, self.dimension)) for _ in range(count)]
def parent():
return occupied[self._rng.integers(len(occupied))][0]
return [Individual(iso_line_dd(parent(), parent(), iso_sigma=self.iso_sigma,
line_sigma=self.line_sigma, bounds=self.ind_domain, rng=self._rng))
for _ in range(count)]
def _publish(self, fronts):
staged = _stage_archive(self.container)
retained = {id(item) for front in fronts.values() for item in front}
for item in self.container:
if id(item) not in retained:
staged.discard(item)
previous = {id(item) for item in staged}
for cell, front in fronts.items():
for item in front:
if id(item) not in previous:
staged._add_to_grid(item, cell, False)
self.container.__dict__.update(staged.__dict__)
self._fronts = fronts
## @brief Run ordered raw evaluations and return the native reporting grid.
[docs]
def optimise(self, evaluate, *, executor=None, seeded=False):
"""Supply evaluate(candidate) or evaluate(candidate, seed) with seeded=True."""
if self.nb_evaluations or len(self.container):
raise RuntimeError("Construct a fresh ASDelta search and archive for each run.")
if not callable(evaluate):
raise TypeError("evaluate must be callable.")
rollouts = _Rollouts(self.container, evaluate, executor, self.seed, seeded=seeded)
try:
while True:
incumbents = [entry for front in self._fronts.values() for entry in front]
slots = min(self.sampling_size, self.budget - rollouts.attempted)
count = (slots - len(incumbents)) // self.initial_samples
if count < 1:
break
fronts, seen = {}, set()
self.incumbent_evaluations += len(incumbents)
refreshed = rollouts.evaluate_groups([(item, 1) for item in incumbents])
for item, observations in zip(incumbents, refreshed, strict=True):
revised = self._measurement(_fresh(item), item._observations + observations) if observations else item
self._cascade(fronts, seen, revised)
offspring = self._propose(count, fronts)
self.offspring_evaluations += count * self.initial_samples
measured = rollouts.evaluate_groups([(item, self.initial_samples) for item in offspring])
for item, observations in zip(offspring, measured, strict=True):
if len(observations) == self.initial_samples:
self.completed_candidates += 1
self._cascade(fronts, seen, self._measurement(item, observations))
self._publish(fronts)
finally:
self.nb_evaluations, self.failed_evaluations = rollouts.attempted, rollouts.failed
return self.container