# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief History-based multiobjective ranking for one representative per descriptor cell.
"""Tournament Dominance Objective (T-DominO) for native rectangular grids."""
from collections import deque
from itertools import product
from math import isfinite, prod
from operator import index
import numpy as np
from qdpy.base import registry
from .grids import Grid
__all__ = ["TDominOGrid"]
[docs]
@registry.register
## @brief Keep a single balanced elite per grid cell using historical objective vectors.
class TDominOGrid(Grid):
"""T-DominO admission following Gaier et al. (PPSN 2022).
Compare challenger and incumbent to the challenger and to present
and historical elites in the cell and its neighborhood. For each
objective count how many anchors the
candidate matches or beats, then multiply the counts. The incumbent
remains on a tie. Store the raw multiobjective measurements for reporting.
:param iterable: Optional measured individuals to offer in order.
:param shape: Number of cells along each descriptor axis.
:param fitness_domain: Raw bounds for at least two objectives.
:param features_domain: Bounds for each descriptor axis.
:param anchor_capacity: Maximum displaced objective vectors retained per cell.
:param neighbor_radius: Maximum coordinate difference in bins to include.
:param kwargs: Other Grid configuration, including fitness_weights.
"""
def __init__(self, iterable=None, *, shape, fitness_domain, features_domain,
anchor_capacity=10, neighbor_radius=4, **kwargs):
self.anchor_capacity = index(anchor_capacity)
self.neighbor_radius = index(neighbor_radius)
if self.anchor_capacity < 1 or self.neighbor_radius < 0 or len(fitness_domain) < 2:
raise ValueError("T-DominO requires positive anchor capacity, nonnegative radius and multiple objectives.")
if kwargs.pop("max_items_per_bin", 1) != 1 or kwargs.get("discard_random_on_bin_overload"):
raise ValueError("T-DominO requires one elite and tournament-based admission.")
weights = kwargs.get("fitness_weights")
if weights is not None and (len(weights) != len(fitness_domain)
or not all(isfinite(w) and w != 0 for w in weights)):
raise ValueError("Supply one finite, nonzero direction per objective.")
self._anchors = {}
super().__init__(None, shape, max_items_per_bin=1, fitness_domain=fitness_domain,
features_domain=features_domain, **kwargs)
if iterable is not None:
self.update(iterable)
def _set_fitness_weights(self, weights):
if len(weights) != len(self.fitness_domain) or not all(isfinite(w) and w != 0 for w in weights):
raise ValueError("Supply one finite, nonzero direction per objective.")
super()._set_fitness_weights(weights)
def _check_if_can_be_added(self, individual):
super()._check_if_can_be_added(individual)
fitness = self.get_ind_fitness(individual)
if (not all(map(isfinite, fitness.values)) or
not all(isfinite(w) and w != 0 for w in fitness.weights)):
raise ValueError("T-DominO requires finite objectives and finite, nonzero objective directions.")
## @brief Return an immutable snapshot of a cell's raw reference objectives.
[docs]
def anchors(self, cell):
"""Return current and displaced objective vectors from the cell neighborhood."""
cell = tuple(cell)
if cell not in self.solutions:
raise IndexError("Unknown T-DominO grid cell.")
radius = self.neighbor_radius
spans = [range(max(0, value - radius), min(size, value + radius + 1))
for value, size in zip(cell, self.shape)]
anchors = []
for neighbor in product(*spans):
anchors.extend(self._anchors.get(neighbor, ()))
anchors.extend(tuple(self.get_ind_fitness(elite).values) for elite in self.solutions[neighbor])
return tuple(anchors)
## @brief Compute a raw candidate's contextual score against the current cell anchors.
[docs]
def tournament_score(self, cell, objectives, *, challenger=None, weights=None):
"""Return the integer product of win counts, optionally including a challenger anchor."""
return self._score(objectives, self.anchors(cell), challenger, weights)
def _score(self, objectives, anchors, challenger, weights):
objectives = np.asarray(objectives, dtype=float)
if objectives.shape != (len(self.fitness_domain),) or not np.isfinite(objectives).all():
raise ValueError("Supply one finite value per objective.")
if challenger is not None:
challenger = np.asarray(challenger, dtype=float)
if challenger.shape != objectives.shape or not np.isfinite(challenger).all():
raise ValueError("Challenger must have one finite value per objective.")
anchors = (*anchors, challenger)
if not anchors:
return 0
if weights is None:
weights = self.fitness_weights
directions = np.ones_like(objectives) if weights is None else np.sign(weights)
if directions.shape != objectives.shape or not np.all(np.abs(directions) == 1):
raise ValueError("Supply one finite, nonzero direction per objective.")
wins = objectives * directions >= np.asarray(anchors) * directions
return prod(map(int, wins.sum(axis=0)))
def _replacement_in_bin(self, individual, solutions):
incumbent = solutions[0]
cell = self.index_grid(individual)
challenger_fit = self.get_ind_fitness(individual)
incumbent_fit = self.get_ind_fitness(incumbent)
anchors = self.anchors(cell)
challenger = self._score(challenger_fit.values, anchors, challenger_fit.values, incumbent_fit.weights)
current = self._score(incumbent_fit.values, anchors, challenger_fit.values, incumbent_fit.weights)
return 0 if challenger > current else None
def _add_to_grid(self, individual, ig, raise_if_not_added_to_parents, replacement=None):
before = self.nb_added
displaced = (None if replacement is None else
tuple(self.get_ind_fitness(self.solutions[ig][replacement]).values))
result = super()._add_to_grid(individual, ig, raise_if_not_added_to_parents, replacement)
if displaced is not None and self.nb_added > before:
history = self._anchors.setdefault(ig, deque(maxlen=self.anchor_capacity))
history.append(displaced)
return result
def clear(self, also_from_parents=False):
"""Clear both retained solutions and historical reference vectors."""
super().clear(also_from_parents)
self._anchors.clear()