Source code for qdpy.algorithms.produqd

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Surrogate-assisted discovery and selection of design prototypes.
# @see https://doi.org/10.1007/978-3-319-99253-2_40

"""Discover design families in a surrogate repertoire and use them to steer search."""

from dataclasses import dataclass
from math import isfinite
from operator import index

import numpy as np
from scipy.spatial.distance import cdist
from scipy.stats import qmc
from sklearn.cluster import DBSCAN
from sklearn.decomposition import PCA
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import Matern
from sklearn.manifold import TSNE

from ._population import _attempt_budget, _finite_vector
from .modern import _positive_int
from .task_search import _measurement, _offer, _validate_grid

__all__ = ["PRODUQD", "PRODUQDStats", "Prototype", "PrototypePrediction"]


## @brief An unevaluated recommendation from the mean-only map.
[docs] @dataclass(frozen=True) class PrototypePrediction: """Fitness is a model prediction in the original objective units.""" genome: tuple[float, ...] descriptor: tuple[float, ...] fitness: float
## @brief A cluster of predicted elites and its representative in embedding space.
[docs] @dataclass(frozen=True) class Prototype: """The representative is a member of the cluster. All members can seed search.""" representative: PrototypePrediction members: tuple[PrototypePrediction, ...]
## @brief Cumulative simulator and surrogate work.
[docs] @dataclass(frozen=True) class PRODUQDStats: """An unsuccessful expensive call still counts against the evaluation budget.""" evaluations: int failures: int observations: int model_fits: int acquisition_predictions: int mean_predictions: int
@dataclass(frozen=True) class _MapEntry: descriptor: tuple[float, ...] fitness: float score: float def _ranges(domain, size, name): bounds = np.asarray(domain, dtype=float) if bounds.shape == (2,): bounds = np.tile(bounds, (size, 1)) if bounds.shape != (size, 2) or not np.isfinite(bounds).all(): raise ValueError(f"{name} must provide finite bounds for every coordinate.") with np.errstate(over="ignore"): widths = bounds[:, 1] - bounds[:, 0] if np.any(widths <= 0.) or not np.isfinite(widths).all(): raise ValueError(f"{name} must have finite positive widths.") return bounds[:, 0].copy(), bounds[:, 1].copy(), widths ## @brief Surrogate illuminate, cluster predicted elites, and reseed search from selected families.
[docs] class PRODUQD: """The supplied grid only stores measured elites. All valid measurements train the GP. Inspect predictions and prototypes after each run, then select any number of prototype families before resuming. Selecting families sets breeding seeds in both surrogate maps. Mutation may still visit other parts of the domain. """ ## @param archive Empty scalar best-only Grid or CVTGrid with finite descriptor bounds. # @param dimension Number of decision coordinates. # @param describe Cheap callable (genome) returning descriptors or None outside the descriptor support. # @param ind_domain Shared or per-coordinate finite parameter bounds. # @param initial_samples Real calls assigned to initial Sobol sampling. # @param acquisition_steps Offspring attempts per upper-confidence map. # @param prediction_steps Offspring attempts in the mean-only map at the end of a round. # @param evaluations_per_fit Maximum expensive calls per acquisition map. # @param kappa Positive standard-deviation coefficient for upper confidence. # @param mutation_sigma Gaussian mutation scale in unit decision coordinates. # @param embedding "pca" or "tsne" for clustering designs. # @param cluster_eps DBSCAN neighborhood radius in the embedding coordinates. # @param min_samples DBSCAN neighborhood size. # @param seed Seed for Sobol sampling, mutation, and dimensionality reduction. def __init__(self, archive, dimension, describe, *, ind_domain=(0., 1.), initial_samples=16, acquisition_steps=128, prediction_steps=256, evaluations_per_fit=4, kappa=2., mutation_sigma=.08, embedding="pca", cluster_eps=.2, min_samples=2, seed=0): _validate_grid(archive) self._dimension = _positive_int(dimension, "dimension") self._feature_count = len(archive.features_domain) self._lower, self._upper, _ = _ranges(ind_domain, self._dimension, "ind_domain") self._feature_lower, _, self._feature_width = _ranges( archive.features_domain, self._feature_count, "features_domain") if (not callable(describe) or embedding not in ("pca", "tsne") or not all(isfinite(value) and value > 0. for value in (kappa, mutation_sigma, cluster_eps))): raise ValueError("Supply a descriptor callable, PCA or t-SNE, and positive finite scales.") self._initial = _positive_int(initial_samples, "initial_samples") self._acquisition_steps = _positive_int(acquisition_steps, "acquisition_steps") self._prediction_steps = _positive_int(prediction_steps, "prediction_steps") self._batch = _positive_int(evaluations_per_fit, "evaluations_per_fit") self._min_samples = _positive_int(min_samples, "min_samples") self._describe = describe self._kappa, self._sigma, self._embedding, self._eps = kappa, mutation_sigma, embedding, cluster_eps if archive.fitness_weights is None: archive._set_fitness_weights((1.,)) self.archive = archive self._sign = np.sign(archive.fitness_weights[0]) decisions, features, variation, preview, clustering = np.random.SeedSequence(seed).spawn(5) self._designs = qmc.Sobol(self._dimension, seed=np.random.default_rng(decisions)) self._anchors = qmc.Sobol(self._feature_count, seed=np.random.default_rng(features)) self._rng = np.random.default_rng(variation) self._preview_rng = np.random.default_rng(preview) self._cluster_seed = int(clustering.generate_state(1)[0]) self._attempted = set() self._observations = {} self._model = None self._model_size = 0 self._failures = self._fits = self._acquired = self._predicted = 0 self._selected = None self._predictions = self._prototypes = self._families = () ## @brief Predicted fitness and descriptors for current mean-only map elites. @property def predictions(self): return self._predictions ## @brief Current clusters and medoids, available after two successful observations. @property def prototypes(self): return self._prototypes ## @brief Cumulative budgets from the lifetime of this search. @property def stats(self): return PRODUQDStats(len(self._attempted), self._failures, len(self._observations), self._fits, self._acquired, self._predicted) ## @brief Use the specified families from the latest round to seed both maps. # @param indices Nonempty iterable of current prototype indices. None clears the focus. def select_prototypes(self, indices=None): if indices is None: self._selected = None return indices = tuple(index(position) for position in indices) if not indices or any(not 0 <= position < len(self._families) for position in indices): raise ValueError("Select valid indices from the latest prototypes, or clear with None.") self._selected = dict.fromkeys(point for position in indices for point in self._families[position]) def _raw(self, point): # Interpolation preserves both endpoints even when the rounded span loses precision. unit = np.asarray(point) return tuple(map(float, np.clip((1. - unit) * self._lower + unit * self._upper, self._lower, self._upper))) def _descriptor(self, genome): descriptor = self._describe(genome) if descriptor is not None: return _finite_vector(descriptor, "descriptor", self._feature_count) return None def _unused_design(self): for _ in range(128): point = tuple(self._designs.random(1)[0]) if self._raw(point) not in self._attempted: return point raise RuntimeError("Could not find an unmeasured design. Check parameter bounds and numerical precision.") def _evaluate(self, evaluate, point, seeds): genome = self._raw(point) self._attempted.add(genome) fitness = evaluate(genome) if fitness is None: self._failures += 1 return if not isfinite(fitness): raise ValueError("The objective must return finite scalar fitness or None.") descriptor = self._descriptor(genome) if descriptor is not None: _offer(self.archive, _measurement(self.archive, ((fitness,), descriptor), genome)) self._observations[point] = float(fitness) if seeds is not None: seeds[point] = None def _fit(self): if self._model_size != len(self._observations): self._model = GaussianProcessRegressor( kernel=Matern(length_scale=.25, nu=2.5), alpha=1e-6, normalize_y=True, optimizer=None, ).fit(tuple(self._observations), tuple(self._observations.values())) self._model_size = len(self._observations) self._fits += 1 return self._model def _illuminate(self, model, seeds, confidence, steps, rng): # One entry per cell. A separate dictionary provides constant-time parent sampling. entries = {} cells = [] seen = set() def consider(point): genome = self._raw(point) if genome in seen: return seen.add(genome) descriptor = self._descriptor(genome) if descriptor is None or not self.archive.in_bounds(descriptor, self.archive.features_domain): return cell = self.archive.index_grid(descriptor) if confidence: mean, deviation = model.predict([point], return_std=True) score = self._sign * mean[0] + confidence * deviation[0] self._acquired += 1 else: mean = model.predict([point]) score = self._sign * mean[0] self._predicted += 1 if cell not in entries: cells.append(cell) elif entries[cell][1].score >= score: return entries[cell] = point, _MapEntry(descriptor, float(mean[0]), float(score)) for point in seeds: consider(point) for _ in range(steps): if cells: parent, _ = entries[cells[int(rng.integers(len(cells)))]] point = np.clip(parent + self._sigma * rng.standard_normal(self._dimension), 0., 1.) else: point = rng.random(self._dimension) consider(tuple(point)) return tuple(entries.values()) def _acquisition_batch(self, entries, count): available = {point: row.descriptor for point, row in entries if self._raw(point) not in self._attempted} for _ in range(count): if available: points = tuple(available) coords = (np.asarray(tuple(available.values())) - self._feature_lower) / self._feature_width anchor = self._anchors.random(1) position = cdist(anchor, coords, metric="sqeuclidean").argmin() point = points[position] del available[point] else: point = self._unused_design() # Clipped mutation can map different unit vectors to the same physical point. if self._raw(point) in self._attempted: point = self._unused_design() yield point def _preview(self, model, seeds): entries = self._illuminate(model, seeds, 0., self._prediction_steps, self._preview_rng) self._predictions = tuple(PrototypePrediction(self._raw(point), row.descriptor, row.fitness) for point, row in entries) if not entries: self._prototypes = self._families = () return points = np.asarray([point for point, _ in entries]) if self._embedding == "tsne" and len(points) >= 4: embedded = TSNE(n_components=2, perplexity=min(30, max(2, (len(points) - 1) // 3)), init="random", random_state=self._cluster_seed).fit_transform(points) embedded -= embedded.mean(axis=0) radius = np.linalg.norm(embedded, axis=1).max() if radius > 0.: embedded /= radius elif len(points) > 1 and points.shape[1] > 2: embedded = PCA(n_components=2, svd_solver="full").fit_transform(points) else: embedded = points labels = DBSCAN(eps=self._eps, min_samples=self._min_samples).fit_predict(embedded) families = {} for position, label in enumerate(labels): families.setdefault((label, position if label < 0 else -1), []).append(position) prototypes, family_points = [], [] for members in families.values(): distances = cdist(embedded[members], embedded[members]) medoid = members[distances.sum(axis=1).argmin()] prototypes.append(Prototype(self.predictions[medoid], tuple(self.predictions[i] for i in members))) family_points.append(tuple(entries[i][0] for i in members)) self._prototypes, self._families = tuple(prototypes), tuple(family_points) ## @brief Spend the supplied true-evaluation budget and refresh prototypes. # @param evaluate Expensive callable (genome) returning scalar fitness or None on failure. # @param budget Number of expensive calls to attempt in this round. def run(self, evaluate, budget): if not callable(evaluate): raise ValueError("evaluate must be callable.") remaining = _attempt_budget(budget) if remaining == 0: return self.stats seeds = self._observations if self._selected is None else self._selected while remaining and (len(self._attempted) < self._initial or len(self._observations) < 2): self._evaluate(evaluate, self._unused_design(), self._selected) remaining -= 1 while remaining: entries = self._illuminate(self._fit(), seeds, self._kappa, self._acquisition_steps, self._rng) count = min(remaining, self._batch) for point in self._acquisition_batch(entries, count): self._evaluate(evaluate, point, self._selected) remaining -= count if len(self._observations) >= 2: self._preview(self._fit(), seeds) return self.stats