Source code for qdpy.algorithms.jedi

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Use a behavior surrogate to target high-fitness evolution strategies.

"""Quality with Just Enough Diversity for bounded real genomes."""

from collections import Counter, deque
from itertools import groupby
from math import log

import numpy as np
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import Matern

from qdpy.base import registry
from qdpy.containers import CVTGrid, Grid
from .lm_ma_mae import _LMMAES
from .modern import _FixedGeneration, _bounds, _positive_int

__all__ = ["JEDi"]


def _target_front(means, deviations):
    """Return all nondominated target indices, including exact objective ties."""
    order = np.lexsort((-deviations, -means))
    front = []
    best_deviation = -np.inf
    for _, rows in groupby(order, key=means.__getitem__):
        first, *remaining = rows
        deviation = deviations[first]
        if deviation > best_deviation:
            front.append(first)
            front.extend(row for row in remaining if deviations[row] == deviation)
            best_deviation = deviation
    return front


def _unit_range(values):
    """Normalize a finite vector without subtracting opposite extreme values."""
    scale = np.max(np.abs(values))
    if scale == 0:
        return np.zeros_like(values)
    scaled = values / scale
    low, high = scaled.min(), scaled.max()
    return np.zeros_like(values) if high == low else (scaled - low) / (high - low)


## @brief Combine visit-weighted behavior modeling with interleaved target-specific ES batches.
[docs] @registry.register class JEDi(_FixedGeneration): """Quality with Just Enough Diversity, following Templier et al. (GECCO 2024). A Matérn Gaussian process models elite fitness over normalized descriptor coordinates. Each occupied cell's noise is inversely proportional to its number of visits. Sample target cells without replacement from the posterior mean and deviation Pareto front. Start one LM-MA-ES per target from the closest elite and rank proposals by normalized fitness and target proximity. Every valid measurement can enter the reporting grid. :param container: Fixed best-only Grid or CVTGrid with a scalar objective. :param budget: Number of evaluation attempts. :param dimension: Length of the real genome, at least two. :param ind_domain: Common lower and upper genome bounds. :param batch_size: Population size per target. :param warmup: Minimum initialization attempts before using the GP. :param targets_per_cycle: Maximum concurrent target strategies. :param generations_per_target: Complete generations attempted per target. :param sigma0: Initial genome step size. :param proximity_weight: Weight of target proximity in [0, 1]. :param length_scale: Fixed Matérn kernel length in normalized descriptor units. :param noise: Positive base observation variance in scaled fitness units. :param seed: Private search seed. :param kwargs: Common QDAlgorithm options, including optimisation_task. """ _requires_proposed_genome = True def __init__(self, container, budget, dimension, ind_domain=(0., 1.), *, batch_size=16, warmup=32, targets_per_cycle=3, generations_per_target=4, sigma0=.1, proximity_weight=.5, length_scale=.25, noise=.01, seed=0, **kwargs): if (type(container) not in (Grid, CVTGrid) or container.max_items_per_bin != 1 or container.discard_random_on_bin_overload or container.fitness_domain is None or len(container.fitness_domain) != 1 or not len(container.features_domain)): raise ValueError("JEDi requires a fixed, best-only Grid or CVTGrid with one objective.") domain = np.asarray(container.features_domain, dtype=float) self._descriptor_low = domain[:, 0] self._descriptor_width = domain[:, 1] - domain[:, 0] if not np.isfinite(self._descriptor_width).all() or np.any(self._descriptor_width <= 0): raise ValueError("JEDi requires finite descriptor intervals with positive widths.") self._cells = tuple(container.solutions) if isinstance(container, CVTGrid): self._centers = self._normalize(container.cluster_centers) else: self._centers = (np.asarray(self._cells, dtype=float) + .5) / container.shape self._positions = {cell: pos for pos, cell in enumerate(self._cells)} self.ind_domain = _bounds(ind_domain) if not np.isfinite(self.ind_domain[1] - self.ind_domain[0]): raise ValueError("The genome interval must have a finite width.") if not (0 < sigma0 < np.inf and 0 <= proximity_weight <= 1 and 0 < length_scale < np.inf and 0 < noise < np.inf): raise ValueError("Invalid sigma0, proximity_weight, length_scale, or noise.") self.sigma0, self.proximity_weight = sigma0, proximity_weight self.length_scale, self.noise, self.seed = length_scale, noise, seed self.warmup = _positive_int(warmup, "warmup") self.targets_per_cycle = _positive_int(targets_per_cycle, "targets_per_cycle") self.generations_per_target = _positive_int(generations_per_target, "generations_per_target") dimension, batch_size = _positive_int(dimension, "dimension"), _positive_int(batch_size, "batch_size") if dimension < 2 or batch_size < 2: raise ValueError("JEDi needs at least two genome coordinates and two proposals per target.") self._memory = min(dimension, 4 + int(3 * log(dimension))) super().__init__(container, _positive_int(budget, "budget"), dimension=dimension, batch_size=batch_size, **kwargs) if not self._fitness_weights[0]: raise ValueError("JEDi requires a nonzero objective direction.") def reinit(self): """Reset target scheduling and visit counters while retaining the archive.""" super().reinit() self._rng = np.random.default_rng(self.seed) self._visits = Counter() self._agents = deque() self._target_history = [] self._agent = None def _normalize(self, descriptors): return (np.asarray(descriptors, dtype=float) - self._descriptor_low) / self._descriptor_width @property def cell_visits(self): """Return a copy of the per-cell counts of valid evaluations.""" return dict(self._visits) @property def target_history(self): """Return the cell indices selected for each completed target draw.""" return tuple(self._target_history) def _start_cycle(self): occupied = [cell for cell in self._cells if self.container.solutions[cell]] elites = [self.container.solutions[cell][0] for cell in occupied] features = self._normalize([tuple(self.container.get_ind_features(elite)) for elite in elites]) direction = np.sign(self._fitness_weights[0]) if not direction: raise ValueError("JEDi requires a nonzero objective direction.") scores = direction * np.asarray([self.container.get_ind_fitness(elite).values[0] for elite in elites]) variance = self.noise / np.array([max(1, self._visits[cell]) for cell in occupied]) gp = GaussianProcessRegressor(kernel=Matern(self.length_scale, length_scale_bounds="fixed", nu=2.5), alpha=np.maximum(variance, 1e-12), optimizer=None) gp.fit(self._centers[[self._positions[cell] for cell in occupied]], _unit_range(scores)) means, deviations = gp.predict(self._centers, return_std=True) front = _target_front(means, deviations) draw = self._rng.choice(front, size=min(len(front), self.targets_per_cycle), replace=False) self._target_history.append(tuple(self._cells[row] for row in draw)) for row in draw: target = self._centers[row] closest = np.argmin(np.linalg.norm(features - target, axis=1)) center = np.asarray(elites[closest], dtype=float) if (center.shape != (self.dimension,) or not np.isfinite(center).all() or np.any(center < self.ind_domain[0]) or np.any(center > self.ind_domain[1])): raise ValueError("JEDi requires finite archive genomes inside ind_domain.") strategy = _LMMAES(center, self.sigma0, self.batch_size, self._memory, self.ind_domain, self._rng) self._agents.append((strategy, row, self.generations_per_target)) def _start_fixed_batch(self, size): super()._start_fixed_batch(size) self._agent = None if self.nb_evaluations >= self.warmup and self.container: if not self._agents: self._start_cycle() self._agent = self._agents[0] self._vectors = (self._rng.uniform(*self.ind_domain, size=(size, self.dimension)) if self._agent is None else self._agent[0].ask(size)) def _internal_ask(self, individual): individual[:] = self._vectors[len(self._issued)] return individual def _check_candidate(self, individual): super()._check_candidate(individual) self.container.index_grid(individual) def _generation_feedback(self, position): if self._agent is None: return {} return {"target_cell": self._cells[self._agent[1]]} def _commit_generation(self, evaluated): admitted = set() valid = [] for position, individual in enumerate(evaluated): if individual is not None: cell = self.container.index_grid(individual) self._visits[cell] += 1 valid.append(position) if self._offer_to_grid(individual, cell): admitted.add(position) if self._agent is not None: strategy, row, remaining = self._agents.popleft() if len(evaluated) == self.batch_size and valid: elites = [evaluated[position] for position in valid] fitness = np.asarray([self.container.get_ind_fitness(elite).values[0] for elite in elites]) features = self._normalize([tuple(self.container.get_ind_features(elite)) for elite in elites]) distances = np.linalg.norm(features - self._centers[row], axis=1) score = ((1 - self.proximity_weight) * _unit_range(np.sign(self._fitness_weights[0]) * fitness) + self.proximity_weight * _unit_range(-distances)) strategy.adapt(self._vectors, np.asarray(valid)[np.argsort(-score, kind="stable")]) if remaining > 1 and not strategy.stop(): self._agents.append((strategy, row, remaining - 1)) return admitted