Source code for qdpy.algorithms.hill_valley

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Hill-Valley clustering and independent continuous searches for distinct optima.
# @see https://doi.org/10.1145/3205455.3205477

"""Spend fitness calls on global sampling, line probes, and local CMA-ES."""

from dataclasses import dataclass
from math import isfinite

import numpy as np

from .modern import _cma_strategy, _positive_int

__all__ = ["HillVallEA", "HillValleyPeak", "HillValleyResult"]


## @brief A measured candidate in the original decision space.
[docs] @dataclass(frozen=True) class HillValleyPeak: """Store a decision vector and its raw scalar fitness.""" genome: tuple[float, ...] fitness: float
## @brief Distinct retained basins and an exact breakdown of callback counts.
[docs] @dataclass(frozen=True) class HillValleyResult: """Keep the evaluated best point and the near-optimal niche representatives.""" peaks: tuple[HillValleyPeak, ...] best: HillValleyPeak samples: int probes: int local_evaluations: int restarts: int @property def evaluations(self): """Return the total number of objective calls.""" return self.samples + self.probes + self.local_evaluations
@dataclass(frozen=True, eq=False) class _Point: vector: np.ndarray quality: float class _BudgetExhausted(Exception): """Stop before the next callback would exceed the evaluation budget.""" class _HillValleyRun: def __init__(self, search, evaluate, budget): self.search = search self.evaluate = evaluate self.budget = budget self.rng = np.random.default_rng(search.seed) self.calls = [0, 0, 0] self.elites = [] self.best = None self.restarts = 0 @property def remaining(self): return self.budget - sum(self.calls) def _measure(self, vector, phase): if not self.remaining: raise _BudgetExhausted vector = np.clip(vector, 0., 1.) self.calls[phase] += 1 raw = float(self.evaluate(self.search._decode(vector))) if not isfinite(raw): raise ValueError("HillVallEA needs a finite scalar fitness.") point = _Point(vector, self.search._direction * raw) if self.best is None or point.quality > self.best.quality: self.best = point return point def _same_basin(self, first, second, probes): if np.array_equal(first.vector, second.vector): return True floor = min(first.quality, second.quality) for fraction in np.arange(1, probes + 1) / (probes + 1): check = (1. - fraction) * first.vector + fraction * second.vector if self._measure(check, 1).quality < floor: return False return True def _cluster(self, points): groups, labels = [], [] vectors = np.asarray([point.vector for point in points]) edge_scale = len(points) ** (-1. / self.search.dimension) for i, point in enumerate(points): distances = np.linalg.norm(vectors[:i] - point.vector, axis=1) tested = set() for neighbor in np.argsort(distances, kind="stable")[:self.search.neighbors]: label = labels[neighbor] if label in tested: continue tested.add(label) probes = min(self.search.max_probes, 1 + int(distances[neighbor] / edge_scale)) if self._same_basin(point, points[neighbor], probes): break else: label = len(groups) groups.append([]) groups[label].append(point) labels.append(label) return groups def _local_search(self, group, limit, population): if not limit: return group[0] vectors = np.asarray([point.vector for point in group]) center = vectors.mean(axis=0) spread = np.sqrt(np.mean((vectors - center)**2)) sigma = float(np.clip(spread, .035, .25)) strategy = _cma_strategy(center, sigma, population, int(self.rng.integers(1, 2**32)), (0., 1.)) best = group[0] while limit and not strategy.stop(): points = [self._measure(vector, 2) for vector in strategy.ask(number=min(population, limit))] candidate = max(points, key=lambda point: point.quality) if candidate.quality > best.quality: best = candidate if len(points) == population: strategy.tell([point.vector for point in points], [-point.quality for point in points]) limit -= len(points) return best def _retain(self, candidate): quality = max([candidate.quality, *(point.quality for point in self.elites)]) tolerance = self.search.fitness_tolerance if candidate.quality < quality - tolerance: return False contenders = [point for point in self.elites if point.quality >= quality - tolerance] for j, point in enumerate(contenders): if self._same_basin(candidate, point, self.search.max_probes): if candidate.quality > point.quality: contenders[j] = candidate self.elites = contenders return False self.elites = [*contenders, candidate] return True def optimise(self): search = self.search samples, population = search.initial_samples, search.local_population while self.remaining: self.restarts += 1 points = self.elites + [self._measure(self.rng.random(search.dimension), 0) for _ in range(min(samples, self.remaining))] points.sort(key=lambda point: -point.quality) selected = max(1, int(search.selection_fraction * len(points))) groups = self._cluster(points[:selected]) pending = [group for group in groups if group[0] not in self.elites] discovered = False for i, group in enumerate(pending): # Leave room for duplicate-peak checks and split local search # calls across the remaining clusters. count = len(pending) - i reserve = search.max_probes * (len(self.elites) + count - 1) available = max(0, (self.remaining - reserve) // count) candidate = self._local_search(group, min(available, population * search.local_generations), population) discovered = self._retain(candidate) or discovered if not discovered: samples = min(2 * samples, self.budget) population = max(population + 1, int(1.2 * population)) ## @brief Discover distinct high-quality basins from a scalar black-box objective.
[docs] class HillVallEA: """Cluster nearest-better candidates using line tests, then refine each basin. This bounded variant uses CMA-ES for local search. Restart populations include the retained near-optima and grow when a restart finds no new basin. Every evaluation, including intermediate tests for clustering and duplicate-peak checks, reduces the same hard budget. Requires the optional cma extra at run time. :param bounds: Finite increasing (lower, upper) pairs per decision coordinate. :param maximise: Maximize fitness if true, otherwise minimize it. :param initial_samples: Number of random candidates at the first restart (default 16 per dimension). :param selection_fraction: Fraction of sampled and retained points to cluster. :param neighbors: Number of earlier nearest points to consider during clustering. :param max_probes: Maximum interpolation points per line test. :param local_population: Starting population size for each local CMA-ES. :param local_generations: Maximum number of CMA-ES generations per cluster. :param fitness_tolerance: Retain niche representatives within this fitness gap of the best retained peak. :param seed: Private seed. """ def __init__(self, bounds, *, maximise=True, initial_samples=None, selection_fraction=.5, neighbors=None, max_probes=5, local_population=6, local_generations=12, fitness_tolerance=1e-3, seed=0): limits = np.array(bounds, dtype=float, copy=True) if limits.ndim != 2 or limits.shape[1] != 2 or not len(limits) or not np.isfinite(limits).all(): raise ValueError("Provide finite lower and upper decision bounds.") self._lower, self._upper = limits.T with np.errstate(over="ignore"): self._span = self._upper - self._lower if (not np.isfinite(self._span).all() or np.any(self._span <= 0.) or not 0. < selection_fraction <= 1. or not 0. <= fitness_tolerance < np.inf): raise ValueError("Use positive finite decision spans, a selection fraction in (0, 1], and a finite tolerance.") self.dimension = len(limits) self._direction = 1. if maximise else -1. self.initial_samples = (16 * self.dimension if initial_samples is None else _positive_int(initial_samples, "initial_samples")) self.selection_fraction = selection_fraction self.neighbors = self.dimension + 1 if neighbors is None else _positive_int(neighbors, "neighbors") self.max_probes = _positive_int(max_probes, "max_probes") self.local_population = _positive_int(local_population, "local_population") if self.local_population < 2: raise ValueError("local_population must be at least two.") self.local_generations = _positive_int(local_generations, "local_generations") self.fitness_tolerance, self.seed = fitness_tolerance, seed def _decode(self, point): return tuple(map(float, np.clip(self._lower + self._span * point, self._lower, self._upper))) ## @brief Run from scratch and return near-optima with an exact evaluation count.
[docs] def run(self, evaluate, budget): """Measure finite scalar fitness on raw decision vectors. If the final budget interrupts a comparison, retain completed niche updates. The result also exposes the best measured point, even if its basin could not be checked before the budget stopped. """ budget = _positive_int(budget, "budget") if not callable(evaluate): raise TypeError("evaluate must be callable.") try: import cma # noqa: F401 except ImportError as error: raise ImportError("HillVallEA requires qdpy[cma].") from error run = _HillValleyRun(self, evaluate, budget) try: run.optimise() except _BudgetExhausted: pass def record(point): return HillValleyPeak(self._decode(point.vector), self._direction * point.quality) peaks = tuple(record(point) for point in sorted(run.elites, key=lambda point: -point.quality)) return HillValleyResult(peaks, record(run.best), *run.calls, run.restarts)