5"""Pareto grid admission and two-objective hypervolume."""
7from collections
import defaultdict
8from itertools
import groupby
9from math
import dist, isfinite
10from operator
import index
17from .base
import Container
18from .grids
import Grid
20__all__ = [
"ParetoGrid",
"LocalParetoArchive"]
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))
28def _sweep_front(fitnesses):
29 """Return slots in storage order, or None for general dominance."""
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))):
40 point = fitness.weighted_values(fitness.weights)
41 if not all(map(isfinite, point)):
44 types.update(map(type, point))
45 except (FloatingPointError, OverflowError):
48 if len(types) > 1
and not (types <= _DOUBLE_SCALARS
or types <= _PYTHON_SCALARS):
52 order = sorted(range(len(points)), key=points.__getitem__, reverse=
True)
55 for _, group
in groupby(order, key=
lambda slot: points[slot][0]):
57 second = points[first][1]
58 if second > best_second:
60 front.extend(slot
for slot
in group
if points[slot][1] == second)
66def _hypervolume_2d(points, reference):
67 """Sweep the union of rectangles in maximisation coordinates."""
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.")
74 area += (x - reference[0]) * (y - height)
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)
84 while len(front) > capacity:
86 remove = max(range(len(front)), key=
lambda i: (
87 _hypervolume_2d(map(tuple, points[front[:i] + front[i + 1:]]), (0., 0.)), i))
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))
100 order = np.argsort(axis, kind=
"stable")
103 maximum = np.max(np.abs(values))
104 scaled = values / maximum
if maximum
else values
105 span = scaled[-1] - scaled[0]
107 distance[order[[0, -1]]] = np.inf
108 distance[order[1:-1]] += (scaled[2:] - scaled[:-2]) / span
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))
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]
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:])
131def _crowded_front(front, fitnesses, capacity):
132 """Evict the most crowded point repeatedly and favor incumbents on ties."""
134 while len(front) > capacity:
135 distances = _crowding_distance([fitnesses[slot].values
for slot
in front])
136 tied = np.flatnonzero(distances == distances.min())
144 """A descriptor grid with configurable truncation of overfull Pareto fronts.
146 Configure the objective directions before adding candidates. Bounds and
147 bin geometry follow Grid. This archive uses local storage without parents.
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.
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.")
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)
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.")
181 raise ValueError(
"Set the objective weights before populating a ParetoGrid.")
182 super()._set_fitness_weights(weights)
186 """Return the stored front as a tuple of live individual references."""
190 """Choose fronts before applying any removals or admissions."""
191 incoming = defaultdict(list)
193 for ind
in candidates:
194 if self.
_index_of(ind)
is None and ind
not in seen:
199 for cell, offspring
in incoming.items():
200 merged = self.
solutions[cell] + offspring
202 front = _sweep_front(fitnesses)
if len(fitnesses) >= 4
else None
205 slot
for slot, fitness
in enumerate(fitnesses)
206 if not any(other.dominates(fitness)
for other
in fitnesses)
209 truncation = getattr(self,
"truncation",
"random")
210 if truncation ==
"crowding":
212 elif truncation ==
"hypervolume":
217 retained[cell] = [merged[slot]
for slot
in front]
220 for cell, front
in retained.items():
222 old_ids = {id(ind)
for ind
in old}
223 kept_ids = {id(ind)
for ind
in front}
225 if id(ind)
not in kept_ids:
228 if id(ind)
not in old_ids:
230 admitted.add(id(ind))
233 def _add_internal(self, individual, raise_if_not_added_to_parents, only_to_parents):
237 if stored
is not None:
240 return self.
_index_of(individual)
if id(individual)
in admitted
else None
245 if not all(np.isfinite(value)
for value
in values):
246 raise ValueError(
"ParetoGrid requires finite objective values.")
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.")
254 points = [tuple(direction * self.
get_ind_fitness(ind).values)
for ind
in candidates]
255 return float(_hypervolume_2d(points, direction * ref))
259 """Return the front's hypervolume with a reference in raw objective units."""
264 """Return the sum of per-cell hypervolumes with a shared raw reference."""
269 """Return the union hypervolume across all fronts with a raw reference."""
276 """Apply the fixed-radius MOUR-QD admission rule in descriptor units.
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.
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.
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)
311 raise ValueError(
"Provide a positive capacity.")
314 super().__init__(iterable, fitness_domain=fitness_domain, fitness_weights=weights,
315 capacity=capacity, name=name)
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.")
321 raise ValueError(
"Set the objective weights before populating a LocalParetoArchive.")
322 super()._set_fitness_weights(weights)
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.")
336 def _add_internal(self, individual, raise_if_not_added_to_parents, only_to_parents):
340 if stored
is not None:
345 for slot, incumbent
in enumerate(self):
348 if other.dominates(fitness):
350 if fitness.dominates(other):
351 dominated.append(slot)
352 if self.
free < 1
and not dominated:
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):
360 return slot - len(dominated)
FitnessLike get_ind_fitness(self, IndividualLike individual, *args, **kwargs)
None discard(self, IndividualLike individual, bool also_from_parents=False)
None _discard_by_index(self, IndividualLike individual, Optional[int] idx=None, bool also_from_parents=False)
Optional[int] _index_of(self, IndividualLike individual)
GridIndexLike index_grid(self, FeaturesLike features)
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.
GridSolutionsLike solutions(self)
Store locally nondominated solutions in continuous descriptor space.
_check_if_can_be_added(self, individual)
_add_internal(self, individual, raise_if_not_added_to_parents, only_to_parents)
Check local dominance and commit the surviving measurement.
Store a bounded nondominated front in each occupied grid cell.
_hypervolume(self, candidates, reference)
global_hypervolume(self, reference)
Measure the two-objective hypervolume of all retained solutions.
cell_hypervolume(self, cell, reference)
Measure the two-objective hypervolume of one cell.
_merge_fronts(self, candidates, *, truncation_rng=random)
qd_hypervolume(self, reference)
Sum the two-objective hypervolumes across descriptor cells.
front(self, cell)
Read the nondominated entries in a descriptor cell.
_add_internal(self, individual, raise_if_not_added_to_parents, only_to_parents)
Choose a cell and apply its admission policy.
_check_if_can_be_added(self, individual)