Source code for qdpy.algorithms.cpdea

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Multimodal multiobjective evolution with convergence-penalized density.
# @see https://doi.org/10.1109/TEVC.2019.2938557

"""CPDEA for finding distinct decision-space realizations of a Pareto front."""

from dataclasses import dataclass
from math import isfinite, pi, sqrt

import numpy as np
from scipy.spatial.distance import cdist

from qdpy.tools import mut_polynomial_bounded

from .modern import _positive_int
from .parametric import _Coordinates, _sbx

__all__ = ["CPDEA", "CPDEAPoint", "CPDEAResult"]


## @brief Measured decision vector and objective values in original units.
[docs] @dataclass(frozen=True) class CPDEAPoint: """Store a decision vector and its raw objective vector.""" genome: tuple[float, ...] fitness: tuple[float, ...]
## @brief Bounded nondominated archive, final breeding population, and exact work.
[docs] @dataclass(frozen=True) class CPDEAResult: """The final nondominated archive and final population are independent views.""" archive: tuple[CPDEAPoint, ...] population: tuple[CPDEAPoint, ...] evaluations: int
def _dominates(values): """Return a matrix entry (i, j) if i dominates j in maximization units.""" return (np.all(values[:, None] >= values[None, :], axis=-1) & np.any(values[:, None] > values[None, :], axis=-1)) def _distance(points): matrix = cdist(points, points) if not np.isfinite(matrix).all(): raise ValueError("CPDEA requires finite pairwise distances. Rescale the problem coordinates.") return matrix def _nearest(distances, neighbors): """Take the closest other entries for each point, even with duplicate coordinates.""" matrix = distances.copy() np.fill_diagonal(matrix, np.inf) k = min(neighbors, len(matrix) - 1) return np.partition(matrix, k, axis=1)[:, :k] ## @brief Compute Gaussian-weighted local convergence and the penalized kNN density. def _cpd(distances, dominates, sigma, neighbors): with np.errstate(over="ignore", under="ignore"): weights = np.exp(-.5 * (distances / sigma) ** 2) / (sigma * sqrt(2 * pi)) convergence = np.sum(np.where(dominates.T, weights, 0.), axis=1) adjusted = distances / (1. + .5 * convergence[:, None] + .5 * convergence[None, :]) return 1. / (1. + _nearest(adjusted, neighbors).sum(axis=1)) ## @brief Compute double kNN density with separate objective and decision scales. def _dkn(genomes, objectives, neighbors): total = np.zeros(len(genomes)) for coordinates in (genomes, objectives): closest = _nearest(_distance(coordinates), neighbors) if closest.size and (scale := closest.max()) > 0.: normalized = closest / scale total += normalized.sum(axis=1) / normalized.mean() return 1. / (1. + total) ## @brief Search without descriptors using a CPD population and a nondominated archive.
[docs] class CPDEA: """Run the steady-state algorithm of Liu et al. on bounded real decisions. Penalize decision distances by the local presence of objective-space dominators. Update a separate nondominated archive using both decision and objective distances. Use population tournaments in the first half of the budget, then also mate sparse archive elites with nearby designs. :param genome_bounds: Finite increasing (lower, upper) intervals, one per variable. :param fitness_weights: At least two signs. Positive maximizes and negative minimizes. :param population_size: Size of the breeding population and cap of the archive. :param neighbors: Number of nearest other solutions used in either density. :param eta: Scale of the local-convergence bandwidth in Eq. 17. :param seed: Private seed for initialization, mating, and variation. """ def __init__(self, genome_bounds, fitness_weights, *, population_size=60, neighbors=3, eta=2., seed=0): self._coordinates = _Coordinates(genome_bounds) self._direction = np.sign(np.asarray(fitness_weights, dtype=float)) if (self._direction.ndim != 1 or len(self._direction) < 2 or not np.isfinite(fitness_weights).all() or np.any(self._direction == 0)): raise ValueError("Provide at least two finite, nonzero fitness weights.") self.population_size = _positive_int(population_size, "population_size") self.neighbors = _positive_int(neighbors, "neighbors") if self.population_size < 2 or not 0 < eta < np.inf: raise ValueError("Use a population of at least two and finite positive eta.") self.seed = seed dimension = len(self._coordinates.span) self._sigma = np.exp(np.log(eta) + np.log(self._coordinates.span).mean() - np.log(self.population_size + 1) / dimension) if not isfinite(self._sigma * sqrt(2 * pi)) or not 0 < self._sigma or not isfinite(1. / self._sigma): raise ValueError("Use bounds and eta that give a finite nonzero convergence bandwidth.") def _measure(self, evaluate, normalized): genome = self._coordinates.physical(normalized) objectives = np.asarray(evaluate(genome), dtype=float) if objectives.shape != self._direction.shape or not np.isfinite(objectives).all(): raise ValueError("Return one finite value per configured objective.") return CPDEAPoint(genome, tuple(map(float, objectives))) def _objectives(self, points): return np.asarray([point.fitness for point in points]) * self._direction def _archive_update(self, archive, candidate): if candidate in archive: return pool = [*archive, candidate] front = [point for point, dominated in zip(pool, _dominates(self._objectives(pool)).any(axis=0)) if not dominated] if len(front) > self.population_size: density = _dkn([point.genome for point in front], self._objectives(front), self.neighbors) # Preserve older measurements on exact density ties. front.pop(len(front) - 1 - np.argmax(density[::-1])) archive[:] = front def _mating(self, population, archive, rng, explore): if explore: distance = _distance([point.genome for point in population]) costs = _cpd(distance, _dominates(self._objectives(population)), self._sigma, self.neighbors) tournaments = rng.integers(len(population), size=(2, 2)) return tuple(population[contest[np.argmin(costs[contest])]] for contest in tournaments) density = _dkn([point.genome for point in archive], self._objectives(archive), self.neighbors) first = archive[np.argmin(density)] pool = tuple(point for point in dict.fromkeys([*population, *archive]) if point.genome != first.genome) if not pool: return first, first distances = cdist([first.genome], [point.genome for point in pool])[0] closest = np.argsort(distances, kind="stable")[:len(first.genome)] return first, pool[rng.choice(closest)] ## @brief Run CPDEA with exactly the specified number of evaluator calls.
[docs] def optimise(self, evaluate, budget): """Call evaluate(genome) for raw objectives and return a :class:`CPDEAResult`.""" if not callable(evaluate): raise TypeError("evaluate must be callable.") budget = _positive_int(budget, "budget") if budget < self.population_size: raise ValueError("The budget must cover the entire initial population.") rng = np.random.default_rng(self.seed) dimension = len(self._coordinates.span) population = [self._measure(evaluate, point) for point in rng.random((self.population_size, dimension))] archive = [] for point in population: self._archive_update(archive, point) for used in range(self.population_size, budget): first, second = self._mating(population, archive, rng, used < budget / 2 or rng.random() < .5) parents = self._coordinates.normalize([first.genome, second.genome]) child = _sbx(*parents, rng, eta=20) mut_polynomial_bounded(child, 20, 0., 1., 1. / dimension, rng=rng) candidate = self._measure(evaluate, child) population.append(candidate) distance = _distance([point.genome for point in population]) costs = _cpd(distance, _dominates(self._objectives(population)), self._sigma, self.neighbors) population.pop(len(population) - 1 - np.argmax(costs[::-1])) self._archive_update(archive, candidate) return CPDEAResult(tuple(archive), tuple(population), budget)