QDpy
Loading...
Searching...
No Matches
t_domino.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Tournament Dominance Objective (T-DominO) for native rectangular grids."""
6
7from collections import deque
8from itertools import product
9from math import isfinite, prod
10from operator import index
11
12import numpy as np
13
14from qdpy.base import registry
15from .grids import Grid
16
17__all__ = ["TDominOGrid"]
18
19
20@registry.register
21
23 """T-DominO admission following Gaier et al. (PPSN 2022).
24
25 Compare challenger and incumbent to the challenger and to present
26 and historical elites in the cell and its neighborhood. For each
27 objective count how many anchors the
28 candidate matches or beats, then multiply the counts. The incumbent
29 remains on a tie. Store the raw multiobjective measurements for reporting.
30
31 :param iterable: Optional measured individuals to offer in order.
32 :param shape: Number of cells along each descriptor axis.
33 :param fitness_domain: Raw bounds for at least two objectives.
34 :param features_domain: Bounds for each descriptor axis.
35 :param anchor_capacity: Maximum displaced objective vectors retained per cell.
36 :param neighbor_radius: Maximum coordinate difference in bins to include.
37 :param kwargs: Other Grid configuration, including fitness_weights.
38 """
39
40 def __init__(self, iterable=None, *, shape, fitness_domain, features_domain,
41 anchor_capacity=10, neighbor_radius=4, **kwargs):
42 self.anchor_capacity = index(anchor_capacity)
43 self.neighbor_radius = index(neighbor_radius)
44 if self.anchor_capacity < 1 or self.neighbor_radius < 0 or len(fitness_domain) < 2:
45 raise ValueError("T-DominO requires positive anchor capacity, nonnegative radius and multiple objectives.")
46 if kwargs.pop("max_items_per_bin", 1) != 1 or kwargs.get("discard_random_on_bin_overload"):
47 raise ValueError("T-DominO requires one elite and tournament-based admission.")
48 weights = kwargs.get("fitness_weights")
49 if weights is not None and (len(weights) != len(fitness_domain)
50 or not all(isfinite(w) and w != 0 for w in weights)):
51 raise ValueError("Supply one finite, nonzero direction per objective.")
52 self._anchors = {}
53 super().__init__(None, shape, max_items_per_bin=1, fitness_domain=fitness_domain,
54 features_domain=features_domain, **kwargs)
55 if iterable is not None:
56 self.update(iterable)
57
58 def _set_fitness_weights(self, weights):
59 if len(weights) != len(self.fitness_domain) or not all(isfinite(w) and w != 0 for w in weights):
60 raise ValueError("Supply one finite, nonzero direction per objective.")
61 super()._set_fitness_weights(weights)
62
63 def _check_if_can_be_added(self, individual):
64 super()._check_if_can_be_added(individual)
65 fitness = self.get_ind_fitness(individual)
66 if (not all(map(isfinite, fitness.values)) or
67 not all(isfinite(w) and w != 0 for w in fitness.weights)):
68 raise ValueError("T-DominO requires finite objectives and finite, nonzero objective directions.")
69
70
71 def anchors(self, cell):
72 """Return current and displaced objective vectors from the cell neighborhood."""
73 cell = tuple(cell)
74 if cell not in self.solutions:
75 raise IndexError("Unknown T-DominO grid cell.")
76 radius = self.neighbor_radius
77 spans = [range(max(0, value - radius), min(size, value + radius + 1))
78 for value, size in zip(cell, self.shape)]
79 anchors = []
80 for neighbor in product(*spans):
81 anchors.extend(self._anchors.get(neighbor, ()))
82 anchors.extend(tuple(self.get_ind_fitness(elite).values) for elite in self.solutions[neighbor])
83 return tuple(anchors)
84
85
86 def tournament_score(self, cell, objectives, *, challenger=None, weights=None):
87 """Return the integer product of win counts, optionally including a challenger anchor."""
88 return self._score(objectives, self.anchors(cell), challenger, weights)
89
90 def _score(self, objectives, anchors, challenger, weights):
91 objectives = np.asarray(objectives, dtype=float)
92 if objectives.shape != (len(self.fitness_domain),) or not np.isfinite(objectives).all():
93 raise ValueError("Supply one finite value per objective.")
94 if challenger is not None:
95 challenger = np.asarray(challenger, dtype=float)
96 if challenger.shape != objectives.shape or not np.isfinite(challenger).all():
97 raise ValueError("Challenger must have one finite value per objective.")
98 anchors = (*anchors, challenger)
99 if not anchors:
100 return 0
101 if weights is None:
102 weights = self.fitness_weights
103 directions = np.ones_like(objectives) if weights is None else np.sign(weights)
104 if directions.shape != objectives.shape or not np.all(np.abs(directions) == 1):
105 raise ValueError("Supply one finite, nonzero direction per objective.")
106 wins = objectives * directions >= np.asarray(anchors) * directions
107 return prod(map(int, wins.sum(axis=0)))
108
109 def _replacement_in_bin(self, individual, solutions):
110 incumbent = solutions[0]
111 cell = self.index_grid(individual)
112 challenger_fit = self.get_ind_fitness(individual)
113 incumbent_fit = self.get_ind_fitness(incumbent)
114 anchors = self.anchors(cell)
115 challenger = self._score(challenger_fit.values, anchors, challenger_fit.values, incumbent_fit.weights)
116 current = self._score(incumbent_fit.values, anchors, challenger_fit.values, incumbent_fit.weights)
117 return 0 if challenger > current else None
118
119 def _add_to_grid(self, individual, ig, raise_if_not_added_to_parents, replacement=None):
120 before = self.nb_added
121 displaced = (None if replacement is None else
122 tuple(self.get_ind_fitness(self.solutions[ig][replacement]).values))
123 result = super()._add_to_grid(individual, ig, raise_if_not_added_to_parents, replacement)
124 if displaced is not None and self.nb_added > before:
125 history = self._anchors.setdefault(ig, deque(maxlen=self.anchor_capacity))
126 history.append(displaced)
127 return result
128
129 def clear(self, also_from_parents=False):
130 """Clear both retained solutions and historical reference vectors."""
131 super().clear(also_from_parents)
132 self._anchors.clear()
FitnessLike get_ind_fitness(self, IndividualLike individual, *args, **kwargs)
Definition base.py:178
int update(self, Iterable iterable, bool ignore_exceptions=True, bool issue_warning=False)
Definition base.py:169
GridIndexLike index_grid(self, FeaturesLike features)
Definition grids.py:253
Keep a single balanced elite per grid cell using historical objective vectors.
Definition t_domino.py:22
_add_to_grid(self, individual, ig, raise_if_not_added_to_parents, replacement=None)
Apply a successful storage update to per-cell bookkeeping.
Definition t_domino.py:119
anchors(self, cell)
Return an immutable snapshot of a cell's raw reference objectives.
Definition t_domino.py:71
tournament_score(self, cell, objectives, *, challenger=None, weights=None)
Compute a raw candidate's contextual score against the current cell anchors.
Definition t_domino.py:86
clear(self, also_from_parents=False)
Definition t_domino.py:129
_check_if_can_be_added(self, individual)
Definition t_domino.py:63
_score(self, objectives, anchors, challenger, weights)
Definition t_domino.py:90