# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Diversity-Enhancing NSGA-II with application-provided dissimilarity.
# @see https://doi.org/10.1145/3712256.3726459
"""Pareto evolution with dissimilarity-based crowding."""
from dataclasses import dataclass
import numpy as np
from ._population import _attempt_budget, _finite_vector, _mean_dissimilarity, _nsga_order, _tournament
from .modern import _positive_int
__all__ = ["DiversityEnhancingNSGAII", "DissimilarityEntry", "DissimilarityStats"]
## @brief An evaluated solution with raw quality objectives and a behavior object.
[docs]
@dataclass(frozen=True)
class DissimilarityEntry:
"""The behavior object is passed to user-supplied dissimilarity functions."""
genome: tuple
objectives: tuple[float, ...]
behavior: object
## @brief Cumulative evaluation and generation counts.
[docs]
@dataclass(frozen=True)
class DissimilarityStats:
"""Separate failed measurement attempts from committed generations."""
evaluations: int
failures: int
generations: int
## @brief Rank by quality and average diversity, then crowd by dissimilarity.
[docs]
class DiversityEnhancingNSGAII:
"""Apply DE-NSGA-II to encodings with an application-defined distance.
Each merged population receives an extra objective equal to mean
behavioral dissimilarity. Its Pareto ranks guide survival and
tournament selection. To break rank ties, the default uses average
behavioral dissimilarity. A separate callback can use the genomes.
:param objective_count: Number of raw objectives.
:param sample: Callable (rng) returning a genome.
:param mutate: Callable (parent_genome, rng) returning an offspring.
:param distance: Symmetric nonnegative callable over two behavior objects.
Treat the genome elements and observed behavior as immutable.
:param crowding_distance: Optional symmetric callable over two DissimilarityEntry
instances. Omit it to share the diversity objective's distance matrix.
:param population_size: Parent and offspring population capacity.
:param maximize: A Boolean or one Boolean direction per objective.
:param standard_crowding: Use standard objective-space NSGA-II crowding for an ablation.
:param seed: Private sampling and evaluation seed.
"""
def __init__(self, objective_count, *, sample, mutate, distance, crowding_distance=None,
population_size=32, maximize=True, standard_crowding=False, seed=0):
self._objective_count = _positive_int(objective_count, "objective_count")
self._size = _positive_int(population_size, "population_size")
if not all(map(callable, (sample, mutate, distance))) or (
crowding_distance is not None and not callable(crowding_distance)):
raise TypeError("Supply callable variation and dissimilarity functions.")
directions = np.asarray(maximize)
if directions.dtype.kind != "b" or directions.shape not in ((), (self._objective_count,)):
raise ValueError("maximize must supply a Boolean or one Boolean per objective.")
self._sign = np.broadcast_to(np.where(directions, 1., -1.), (self._objective_count,))
self._sample, self._mutate = sample, mutate
self._distance, self._crowding = distance, crowding_distance
self._standard = standard_crowding
self._variation, self._evaluation = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
self._population, self._keys = (), ()
self._children = []
self._pending = self._evaluations = self._failures = self._generations = 0
@property
def population(self):
"""Return survivors from the last completed selection, in tournament order."""
return self._population
@property
def stats(self):
"""Return cumulative evaluation attempts and completed selections."""
return DissimilarityStats(self._evaluations, self._failures, self._generations)
def _commit(self):
candidates = self._population + tuple(self._children)
if candidates:
diversity = _mean_dissimilarity([row.behavior for row in candidates], self._distance)
objectives = self._sign * np.asarray([row.objectives for row in candidates])
crowding = None
if not self._standard:
crowding = diversity if self._crowding is None else _mean_dissimilarity(candidates, self._crowding)
ordered, keys = _nsga_order(np.column_stack((objectives, diversity)), self._size, crowding)
self._population = tuple(candidates[i] for i in ordered)
self._keys = keys
self._children.clear()
self._pending = 0
self._generations += 1
## @brief Breed and evaluate additional slots, then select from the merged population.
# @param evaluate Callable (genome, seed) returning (objectives, behavior) or None.
# @param budget Number of additional attempted evaluations.
# @return Cumulative DissimilarityStats.
[docs]
def run(self, evaluate, budget):
"""Spend the budget and keep an unfinished offspring batch for a later call."""
budget = _attempt_budget(budget)
if self._pending == self._size:
self._commit()
for _ in range(budget):
if self._population:
parent = _tournament(self._population, self._keys, self._variation)
genome = tuple(self._mutate(parent.genome, self._variation))
else:
genome = tuple(self._sample(self._variation))
self._evaluations += 1
result = evaluate(genome, int(self._evaluation.integers(2**32)))
if result is None:
self._failures += 1
else:
objectives, behavior = result
values = _finite_vector(objectives, "Objectives", self._objective_count)
self._children.append(DissimilarityEntry(genome, values, behavior))
self._pending += 1
if self._pending == self._size:
self._commit()
return self.stats