QDpy
Loading...
Searching...
No Matches
pareto.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Pareto grid admission and two-objective hypervolume."""
6
7from collections import defaultdict
8from itertools import groupby
9from math import dist, isfinite
10from operator import index
11import random
12
13import numpy as np
14
15from qdpy.base import registry
16from qdpy.phenotype import Fitness
17from .base import Container
18from .grids import Grid
19
20__all__ = ["ParetoGrid", "LocalParetoArchive"]
21
22_PARETO_SCALARS = frozenset((int, float, np.float16, np.float32, np.float64))
23_DOUBLE_SCALARS = frozenset((float, np.float64))
24_PYTHON_SCALARS = frozenset((int, float))
25
26
27
28def _sweep_front(fitnesses):
29 """Return slots in storage order, or None for general dominance."""
30 points = []
31 types = set()
32 try:
33 with np.errstate(over="raise", under="raise", invalid="raise"):
34 for fitness in fitnesses:
35 if (type(fitness) is not Fitness or fitness.__dict__.keys() != {"weights", "_values"}
36 or type(fitness.values) is not tuple or type(fitness.weights) is not tuple
37 or len(fitness.values) != 2 or len(fitness.weights) != 2
38 or any(type(value) not in _PARETO_SCALARS for value in (*fitness.values, *fitness.weights))):
39 return None
40 point = fitness.weighted_values(fitness.weights)
41 if not all(map(isfinite, point)):
42 return None
43 points.append(point)
44 types.update(map(type, point))
45 except (FloatingPointError, OverflowError):
46 # Let the general comparisons apply the caller's NumPy error policy.
47 return None
48 if len(types) > 1 and not (types <= _DOUBLE_SCALARS or types <= _PYTHON_SCALARS):
49 # Mixed NumPy precisions can round the other operand during comparison.
50 return None
51
52 order = sorted(range(len(points)), key=points.__getitem__, reverse=True)
53 front = []
54 best_second = -np.inf
55 for _, group in groupby(order, key=lambda slot: points[slot][0]):
56 first = next(group)
57 second = points[first][1]
58 if second > best_second:
59 front.append(first)
60 front.extend(slot for slot in group if points[slot][1] == second)
61 best_second = second
62 # Keep the same list order for both admission and seeded random.sample().
63 return sorted(front)
64
65
66def _hypervolume_2d(points, reference):
67 """Sweep the union of rectangles in maximisation coordinates."""
68 area = 0.0
69 height = reference[1]
70 for x, y in sorted(points, reverse=True):
71 if x < reference[0] or y < reference[1]:
72 raise ValueError("The reference point must be weakly dominated by every scored point.")
73 if y > height:
74 area += (x - reference[0]) * (y - height)
75 height = y
76 return area
77
78
79def _volume_front(front, fitnesses, capacity, directions, domain):
80 domain = np.asarray(domain, dtype=float)
81 lower, upper = np.min(domain * directions[:, None], axis=1), np.max(domain * directions[:, None], axis=1)
82 points = (directions * np.asarray([fitness.values for fitness in fitnesses]) - lower) / (upper - lower)
83 front = list(front)
84 while len(front) > capacity:
85 # Removing the smallest contributor leaves the highest remaining volume.
86 remove = max(range(len(front)), key=lambda i: (
87 _hypervolume_2d(map(tuple, points[front[:i] + front[i + 1:]]), (0., 0.)), i))
88 del front[remove]
89 return front
90
91
92def _crowding_distance(points):
93 """Sum normalized neighbor gaps in objective space, preserving extremes."""
94 points = np.asarray(points, dtype=float)
95 distance = np.zeros(len(points))
96 if len(points) <= 2:
97 distance.fill(np.inf)
98 return distance
99 for axis in points.T:
100 order = np.argsort(axis, kind="stable")
101 values = axis[order]
102 # Scaling first keeps extreme finite ranges representable.
103 maximum = np.max(np.abs(values))
104 scaled = values / maximum if maximum else values
105 span = scaled[-1] - scaled[0]
106 if span:
107 distance[order[[0, -1]]] = np.inf
108 distance[order[1:-1]] += (scaled[2:] - scaled[:-2]) / span
109 return distance
110
111
112def _sampling_crowding(points):
113 """Use finite one-sided neighbour gaps at each objective's boundaries."""
114 points = np.asarray(points, dtype=float)
115 distance = np.zeros(len(points))
116 if len(points) < 2:
117 return distance
118 for axis in points.T:
119 order = np.argsort(axis, kind="stable")
120 scale = np.abs(axis).max() or 1.
121 values = axis[order] / scale
122 span = values[-1] - values[0]
123 if span:
124 gaps = np.diff(values) / span
125 distance[order[0]] += gaps[0]
126 distance[order[-1]] += gaps[-1]
127 distance[order[1:-1]] += .5 * (gaps[:-1] + gaps[1:])
128 return distance
129
130
131def _crowded_front(front, fitnesses, capacity):
132 """Evict the most crowded point repeatedly and favor incumbents on ties."""
133 front = list(front)
134 while len(front) > capacity:
135 distances = _crowding_distance([fitnesses[slot].values for slot in front])
136 tied = np.flatnonzero(distances == distances.min())
137 del front[tied[-1]]
138 return front
139
140
141
142@registry.register
144 """A descriptor grid with configurable truncation of overfull Pareto fronts.
145
146 Configure the objective directions before adding candidates. Bounds and
147 bin geometry follow Grid. This archive uses local storage without parents.
148
149 :param shape: Number of bins along each descriptor coordinate.
150 :param max_items_per_bin: Maximum number of nondominated entries per cell.
151 :param fitness_domain: One interval per objective.
152 :param features_domain: One interval per descriptor coordinate.
153 :param fitness_weights: Signed weights. The default minimises each objective.
154 :param truncation: Choose "random", normalized "crowding", or "hypervolume"
155 contribution with two objectives and finite fitness intervals.
156 """
157
158 def __init__(self, iterable=None, *, shape, max_items_per_bin, fitness_domain,
159 features_domain, fitness_weights=None, name=None, truncation="random"):
160 cap = index(max_items_per_bin)
161 if cap < 1 or len(fitness_domain) < 2:
162 raise ValueError("ParetoGrid needs positive front capacity and at least two objectives.")
163 if fitness_weights is None:
164 fitness_weights = (-1.0,) * len(fitness_domain)
165 if len(fitness_weights) != len(fitness_domain) or not all(np.isfinite(w) and w != 0 for w in fitness_weights):
166 raise ValueError("Provide one finite, nonzero weight per objective.")
167 if truncation not in ("random", "crowding", "hypervolume"):
168 raise ValueError("Choose random, crowding, or hypervolume Pareto truncation.")
169 if truncation == "hypervolume":
170 spans = [float(upper) - float(lower) for lower, upper in fitness_domain]
171 if len(spans) != 2 or not all(0. < span < np.inf for span in spans):
172 raise ValueError("Hypervolume truncation needs two finite, positive fitness spans.")
173 self.truncation = truncation
174 super().__init__(iterable, shape=shape, max_items_per_bin=cap, fitness_domain=fitness_domain,
175 features_domain=features_domain, fitness_weights=tuple(fitness_weights), name=name)
176
177 def _set_fitness_weights(self, weights):
178 if len(weights) != len(self.fitness_domain) or not all(np.isfinite(w) and w != 0 for w in weights):
179 raise ValueError("Provide one finite, nonzero weight per objective.")
180 if len(self) and tuple(weights) != tuple(self.fitness_weights):
181 raise ValueError("Set the objective weights before populating a ParetoGrid.")
182 super()._set_fitness_weights(weights)
183
184
185 def front(self, cell):
186 """Return the stored front as a tuple of live individual references."""
187 return tuple(self.solutions[cell])
188
189 def _merge_fronts(self, candidates, *, truncation_rng=random):
190 """Choose fronts before applying any removals or admissions."""
191 incoming = defaultdict(list)
192 seen = []
193 for ind in candidates:
194 if self._index_of(ind) is None and ind not in seen:
195 incoming[self.index_grid(ind)].append(ind)
196 seen.append(ind)
197
198 retained = {}
199 for cell, offspring in incoming.items():
200 merged = self.solutions[cell] + offspring
201 fitnesses = [self.get_ind_fitness(ind) for ind in merged]
202 front = _sweep_front(fitnesses) if len(fitnesses) >= 4 else None
203 if front is None:
204 front = [
205 slot for slot, fitness in enumerate(fitnesses)
206 if not any(other.dominates(fitness) for other in fitnesses)
207 ]
208 if len(front) > self.max_items_per_bin:
209 truncation = getattr(self, "truncation", "random")
210 if truncation == "crowding":
211 front = _crowded_front(front, fitnesses, self.max_items_per_bin)
212 elif truncation == "hypervolume":
213 front = _volume_front(front, fitnesses, self.max_items_per_bin,
214 np.sign(self.fitness_weights), self.fitness_domain)
215 else:
216 front = sorted(truncation_rng.sample(front, self.max_items_per_bin))
217 retained[cell] = [merged[slot] for slot in front]
218
219 admitted = set()
220 for cell, front in retained.items():
221 old = self.solutions[cell].copy()
222 old_ids = {id(ind) for ind in old}
223 kept_ids = {id(ind) for ind in front}
224 for ind in old:
225 if id(ind) not in kept_ids:
226 self.discard(ind)
227 for ind in front:
228 if id(ind) not in old_ids:
229 self._add_to_grid(ind, cell, False)
230 admitted.add(id(ind))
231 return admitted
232
233 def _add_internal(self, individual, raise_if_not_added_to_parents, only_to_parents):
234 if only_to_parents:
235 return None
236 stored = self._index_of(individual)
237 if stored is not None:
238 return stored
239 admitted = self._merge_fronts([individual])
240 return self._index_of(individual) if id(individual) in admitted else None
241
242 def _check_if_can_be_added(self, individual):
243 super()._check_if_can_be_added(individual)
244 values = self.get_ind_fitness(individual).values
245 if not all(np.isfinite(value) for value in values):
246 raise ValueError("ParetoGrid requires finite objective values.")
247 self.index_grid(individual)
248
249 def _hypervolume(self, candidates, reference):
250 ref = np.asarray(reference, dtype=float)
251 if len(self.fitness_domain) != 2 or ref.shape != (2,) or not np.all(np.isfinite(ref)):
252 raise ValueError("Hypervolume requires two objectives and a finite two-coordinate reference point.")
253 direction = np.sign(self.fitness_weights)
254 points = [tuple(direction * self.get_ind_fitness(ind).values) for ind in candidates]
255 return float(_hypervolume_2d(points, direction * ref))
256
257
258 def cell_hypervolume(self, cell, reference):
259 """Return the front's hypervolume with a reference in raw objective units."""
260 return self._hypervolume(self.solutions[cell], reference)
261
262
263 def qd_hypervolume(self, reference):
264 """Return the sum of per-cell hypervolumes with a shared raw reference."""
265 return sum(self._hypervolume(front, reference) for front in self.solutions.values())
266
267
268 def global_hypervolume(self, reference):
269 """Return the union hypervolume across all fronts with a raw reference."""
270 return self._hypervolume(self, reference)
271
272
273
274@registry.register
276 """Apply the fixed-radius MOUR-QD admission rule in descriptor units.
277
278 Each candidate competes with incumbents at Euclidean distance strictly
279 below the radius. A dominated candidate leaves the archive unchanged.
280 Otherwise it enters and removes every incumbent it dominates nearby.
281 Equal genomes keep their first retained evaluation. Distinct genomes
282 with equal objective values can coexist.
283
284 :param iterable: Initial candidates, admitted in the supplied order.
285 :param radius: Positive finite distance threshold.
286 :param descriptor_size: Number of finite descriptor coordinates.
287 :param fitness_weights: Two or more signed, finite nonzero weights.
288 :param fitness_domain: Optional intervals in raw objective units.
289 :param capacity: Optional limit on archive entries. At capacity,
290 a new entry must replace at least one incumbent.
291 :param name: Display name used by loggers.
292 """
293
294 def __init__(self, iterable=None, *, radius, descriptor_size, fitness_weights,
295 fitness_domain=None, capacity=None, name=None):
296 if not isfinite(radius) or radius <= 0:
297 raise ValueError("Provide a finite positive radius.")
298 descriptor_size = index(descriptor_size)
299 if descriptor_size < 1:
300 raise ValueError("Provide a positive descriptor size.")
301 weights = tuple(fitness_weights)
302 if len(weights) < 2 or any(not isfinite(weight) or weight == 0 for weight in weights):
303 raise ValueError("Provide at least two finite nonzero objective weights.")
304 if fitness_domain is None:
305 fitness_domain = ((-np.inf, np.inf),) * len(weights)
306 if len(fitness_domain) != len(weights):
307 raise ValueError("Provide one objective interval per weight.")
308 if capacity is not None:
309 capacity = index(capacity)
310 if capacity < 1:
311 raise ValueError("Provide a positive capacity.")
312 self.radius = radius
313 self.descriptor_size = descriptor_size
314 super().__init__(iterable, fitness_domain=fitness_domain, fitness_weights=weights,
315 capacity=capacity, name=name)
316
317 def _set_fitness_weights(self, weights):
318 if len(weights) != len(self.fitness_domain) or any(not isfinite(w) or w == 0 for w in weights):
319 raise ValueError("Provide one finite nonzero weight per objective.")
320 if len(self) and tuple(weights) != self.fitness_weights:
321 raise ValueError("Set the objective weights before populating a LocalParetoArchive.")
322 super()._set_fitness_weights(weights)
323
324 def _check_if_can_be_added(self, individual):
325 super()._check_if_can_be_added(individual)
326 fitness = self.get_ind_fitness(individual)
327 features = self.get_ind_features(individual)
328 if (len(features) != self.descriptor_size or not all(map(isfinite, features))
329 or not all(map(isfinite, fitness.weighted_values(self.fitness_weights)))):
330 raise ValueError("LocalParetoArchive requires finite objectives and descriptors of the configured size.")
331
332
336 def _add_internal(self, individual, raise_if_not_added_to_parents, only_to_parents):
337 if only_to_parents:
338 return None
339 stored = self._index_of(individual)
340 if stored is not None:
341 return stored
342 features = tuple(self.get_ind_features(individual))
343 fitness = self.get_ind_fitness(individual)
344 dominated = []
345 for slot, incumbent in enumerate(self):
346 if dist(features, self.get_ind_features(incumbent)) < self.radius:
347 other = self.get_ind_fitness(incumbent)
348 if other.dominates(fitness):
349 return None
350 if fitness.dominates(other):
351 dominated.append(slot)
352 if self.free < 1 and not dominated:
353 return None
354
355 replace_index = dominated.pop() if dominated else None
356 slot = super()._add_internal(individual, raise_if_not_added_to_parents, False,
357 replace_index=replace_index)
358 for old_slot in reversed(dominated):
359 self._discard_by_index(self.items[old_slot], old_slot)
360 return slot - len(dominated)
FitnessLike get_ind_fitness(self, IndividualLike individual, *args, **kwargs)
Definition base.py:178
None discard(self, IndividualLike individual, bool also_from_parents=False)
Definition base.py:168
None _discard_by_index(self, IndividualLike individual, Optional[int] idx=None, bool also_from_parents=False)
Definition base.py:792
Optional[int] _index_of(self, IndividualLike individual)
Definition base.py:769
GridIndexLike index_grid(self, FeaturesLike features)
Definition grids.py:253
Optional[int] _add_to_grid(self, IndividualLike individual, GridIndexLike ig, bool raise_if_not_added_to_parents, Optional[int] replacement=None)
Apply a successful storage update to per-cell bookkeeping.
Definition grids.py:382
GridSolutionsLike solutions(self)
Definition grids.py:192
Store locally nondominated solutions in continuous descriptor space.
Definition pareto.py:275
_add_internal(self, individual, raise_if_not_added_to_parents, only_to_parents)
Check local dominance and commit the surviving measurement.
Definition pareto.py:336
Store a bounded nondominated front in each occupied grid cell.
Definition pareto.py:143
_hypervolume(self, candidates, reference)
Definition pareto.py:249
global_hypervolume(self, reference)
Measure the two-objective hypervolume of all retained solutions.
Definition pareto.py:268
cell_hypervolume(self, cell, reference)
Measure the two-objective hypervolume of one cell.
Definition pareto.py:258
_merge_fronts(self, candidates, *, truncation_rng=random)
Definition pareto.py:189
qd_hypervolume(self, reference)
Sum the two-objective hypervolumes across descriptor cells.
Definition pareto.py:263
front(self, cell)
Read the nondominated entries in a descriptor cell.
Definition pareto.py:185
_add_internal(self, individual, raise_if_not_added_to_parents, only_to_parents)
Choose a cell and apply its admission policy.
Definition pareto.py:233
_check_if_can_be_added(self, individual)
Definition pareto.py:242