QDpy
Loading...
Searching...
No Matches
voronoi.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Unstructured archive used by Voronoi-Elites."""
7
8from itertools import combinations
9from math import dist, isfinite
10from operator import index
11
12import numpy as np
13from scipy.spatial.distance import pdist
14
15from qdpy.base import registry
16
17from .base import Container
18
19__all__ = ["VoronoiArchive"]
20
21_MIN_STABLE_DISTANCE = np.sqrt(np.finfo(float).tiny)
22
23
24def _closest_pair(points):
25 distances = pdist(points)
26 position = int(np.argmin(distances))
27 rows = np.arange(len(points))
28 starts = rows * (2 * len(points) - rows - 1) // 2
29 first = int(np.searchsorted(starts, position, side="right") - 1)
30 second = first + 1 + position - starts[first]
31 gap = distances[position]
32 overflow = not isfinite(gap)
33 if overflow or (gap < _MIN_STABLE_DISTANCE and not np.array_equal(points[first], points[second])):
34 if overflow:
35 points = points / np.max(np.abs(points))
36 return min(combinations(range(len(points)), 2), key=lambda pair: dist(points[pair[0]], points[pair[1]]))
37 return first, second
38
39
40
41@registry.register
43 """Retain boundedly many measured elites with no fixed grid or radius.
44
45 When full, consider the candidate together with every incumbent.
46 Choose the globally closest Euclidean descriptor pair. Remove its
47 less fit member. Equal fitness keeps the older member and distance
48 ties use archive order. Equal genomes compete directly as repeat
49 measurements.
50
51 :param capacity: Positive maximum number of elites.
52 :param features_domain: One interval per descriptor coordinate.
53 :param fitness_domain: Interval for the single raw objective.
54 :param fitness_weights: One finite nonzero comparison weight.
55 :param kwargs: Native Container options. Use a parentless archive.
56 """
57
58 def __init__(self, capacity, *, features_domain, fitness_domain=((-np.inf, np.inf),),
59 fitness_weights=(1.,), **kwargs):
60 capacity = index(capacity)
61 features_domain = tuple(tuple(bounds) for bounds in features_domain)
62 fitness_domain = tuple(tuple(bounds) for bounds in fitness_domain)
63 fitness_weights = tuple(fitness_weights)
64 if (capacity <= 0 or not features_domain or len(fitness_domain) != 1
65 or not all(len(bounds) == 2 and bounds[0] <= bounds[1] for bounds in
66 (*features_domain, *fitness_domain))
67 or len(fitness_weights) != 1 or not isfinite(fitness_weights[0]) or not fitness_weights[0]
68 or kwargs.get("parents")):
69 raise ValueError("Supply positive capacity, valid domains, and one signed objective with no parents.")
70 super().__init__(capacity=capacity, features_domain=features_domain, fitness_domain=fitness_domain,
71 fitness_weights=fitness_weights, **kwargs)
72
73 def _set_fitness_weights(self, weights):
74 if len(weights) != 1 or not isfinite(weights[0]) or not weights[0]:
75 raise ValueError("Voronoi-Elites needs one finite nonzero objective weight.")
76 super()._set_fitness_weights(weights)
77
78 def _check_if_can_be_added(self, individual):
79 super()._check_if_can_be_added(individual)
80 fitness = self.get_ind_fitness(individual).values
81 descriptors = self.get_ind_features(individual)
82 if (len(fitness) != 1 or len(descriptors) != len(self.features_domain)
83 or not all(map(isfinite, (*fitness, *descriptors)))):
84 raise ValueError("Use finite scalar fitness and finite descriptors matching the archive.")
85
86 def _better(self, left, right):
87 a = self.get_ind_fitness(left).values[0]
88 b = self.get_ind_fitness(right).values[0]
89 return a > b if self.fitness_weights[0] > 0 else a < b
90
91 def _closest_pair_victim(self, pool):
92 points = np.asarray([tuple(self.get_ind_features(candidate)) for candidate in pool], dtype=float)
93 first, second = _closest_pair(points)
94 return first if self._better(pool[second], pool[first]) else second
95
96
99 def prune_to(self, size):
100 """Apply closest-pair competition until at most size elites remain."""
101 size = index(size)
102 if size < 1:
103 raise ValueError("Keep at least one elite when pruning.")
104 removed = max(0, len(self) - size)
105 for _ in range(removed):
106 victim = self._closest_pair_victim(self)
107 self._discard_by_index(self[victim], idx=victim)
108 return removed
109
110
115 def _add_internal(self, individual, raise_if_not_added_to_parents, only_to_parents):
116 if only_to_parents:
117 return super()._add_internal(individual, raise_if_not_added_to_parents, only_to_parents)
118 victim = self._index_of(individual)
119 if victim is not None and not self._better(individual, self[victim]):
120 return victim
121 if victim is None and self.free < 1:
122 pool = [*self, individual]
123 victim = self._closest_pair_victim(pool)
124 if victim == len(self):
125 self._nb_rejected += 1
126 return None
127 return super()._add_internal(individual, raise_if_not_added_to_parents, False, victim)
FitnessLike get_ind_fitness(self, IndividualLike individual, *args, **kwargs)
Definition base.py:178
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
Evict the lower-quality member of the closest descriptor pair at capacity.
Definition voronoi.py:42
_add_internal(self, individual, raise_if_not_added_to_parents, only_to_parents)
Choose the victim before committing the native container update.
Definition voronoi.py:115
prune_to(self, size)
Shrink live membership by repeatedly applying closest-pair competition.
Definition voronoi.py:99
_check_if_can_be_added(self, individual)
Definition voronoi.py:78