# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Binary Pareto search with diversity tie-breaking.
# @see https://doi.org/10.1162/EVCO.a.376
"""Keep one representative per nondominated objective vector."""
from dataclasses import dataclass
from operator import index
import numpy as np
from ._population import _attempt_budget, _finite_vector
from .modern import _positive_int
__all__ = ["GSEMOD", "GSEMODStats", "BinaryParetoPoint"]
## @brief An evaluated binary solution and its maximization objectives.
[docs]
@dataclass(frozen=True, slots=True)
class BinaryParetoPoint:
"""An immutable snapshot of one Pareto representative."""
genome: tuple[int, ...]
objectives: tuple[float, ...]
## @brief Track Pareto admissions and per-locus population imbalance.
[docs]
@dataclass(frozen=True, slots=True)
class GSEMODStats:
"""Unevaluated or failed candidates do not contribute to imbalance."""
evaluations: int
failures: int
admissions: int
tie_replacements: int
population_size: int
imbalance: tuple[int, ...]
@property
def total_imbalance(self):
"""Return the sum of absolute zero/one count differences."""
return sum(self.imbalance)
def _dominates(left, right):
"""Compare different objective vectors by weak coordinate dominance."""
return all(a >= b for a, b in zip(left, right))
## @brief Run GSEMO and choose objective ties using the diversity of the complete population.
[docs]
class GSEMOD:
"""Run Antipov et al.'s GSEMO with diversity-aware tie replacement.
Sample a parent uniformly and flip each bit independently with
probability 1/dimension. For a previously seen objective vector,
replace its incumbent if population imbalance improves or ties.
For other vectors, use Pareto dominance on maximization objectives.
:param dimension: Number of bits per solution.
:param diversity: ``total`` minimizes summed imbalance and ``lexicographic``
minimizes the sorted imbalance vector. ``none`` is the GSEMO control.
:param initial: Optional binary starting genome.
:param seed: Seed for variation, parent selection, and evaluator calls.
"""
def __init__(self, dimension, *, diversity="total", initial=None, seed=0):
self._dimension = _positive_int(dimension, "dimension")
if diversity not in ("total", "lexicographic", "none"):
raise ValueError("Choose total, lexicographic, or none diversity.")
self._diversity = diversity
self._initial = None if initial is None else tuple(map(index, initial))
if self._initial is not None and (len(self._initial) != self._dimension or set(self._initial) - {0, 1}):
raise ValueError("initial must match dimension and contain only zero or one.")
self._rng, self._evaluation = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
self._population = {}
self._ones = np.zeros(dimension, dtype=int)
self._objectives = None
self._evaluations = self._failures = self._admissions = self._ties = 0
@property
def population(self):
"""Return the nondominated representatives in admission order."""
return tuple(BinaryParetoPoint(bits, objectives) for objectives, bits in self._population.items())
@property
def stats(self):
"""Return a snapshot of attempted evaluations and population diversity."""
return GSEMODStats(self._evaluations, self._failures, self._admissions, self._ties,
len(self._population), tuple(map(int, self._imbalance(self._ones))))
def _imbalance(self, ones):
return np.abs(ones * 2 - len(self._population))
def _diversity_key(self, ones):
imbalance = self._imbalance(ones)
return int(imbalance.sum()) if self._diversity == "total" else tuple(sorted(imbalance, reverse=True))
def _offer(self, genome, objectives):
previous = self._population.get(objectives)
if previous is not None:
if genome == previous:
return
replacement = self._ones + np.asarray(genome) - np.asarray(previous)
if self._diversity != "none" and self._diversity_key(replacement) > self._diversity_key(self._ones):
return
self._population[objectives], self._ones = genome, replacement
self._ties += 1
elif not any(_dominates(other, objectives) for other in self._population):
for other in [other for other in self._population if _dominates(objectives, other)]:
self._ones -= self._population.pop(other)
self._population[objectives] = genome
self._ones += genome
self._admissions += 1
## @brief Grow or diversify the Pareto population within an additional evaluation budget.
# @param evaluate Callable (binary genome, seed) returning a finite objective vector or None.
# @param budget Additional evaluation attempts.
# @return Current GSEMODStats.
[docs]
def run(self, evaluate, budget):
"""Continue from the last Pareto population and random state."""
for _ in range(_attempt_budget(budget)):
if self._population:
parents = tuple(self._population.values())
parent = parents[self._rng.integers(len(parents))]
changed = self._rng.random(self._dimension) < 1. / self._dimension
genome = tuple(map(int, np.bitwise_xor(parent, changed)))
elif self._initial is not None:
genome = self._initial
else:
genome = tuple(map(int, self._rng.integers(2, size=self._dimension)))
self._evaluations += 1
result = evaluate(genome, int(self._evaluation.integers(2**32)))
if result is None:
self._failures += 1
continue
objectives = _finite_vector(result, "Objective vector", self._objectives)
self._objectives = len(objectives)
self._offer(genome, objectives)
return self.stats