6"""Unstructured archive used by Voronoi-Elites."""
8from itertools
import combinations
9from math
import dist, isfinite
10from operator
import index
13from scipy.spatial.distance
import pdist
17from .base
import Container
19__all__ = [
"VoronoiArchive"]
21_MIN_STABLE_DISTANCE = np.sqrt(np.finfo(float).tiny)
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])):
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]]))
43 """Retain boundedly many measured elites with no fixed grid or radius.
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
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.
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)
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)
83 or not all(map(isfinite, (*fitness, *descriptors)))):
84 raise ValueError(
"Use finite scalar fitness and finite descriptors matching the archive.")
86 def _better(self, left, right):
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
100 """Apply closest-pair competition until at most size elites remain."""
103 raise ValueError(
"Keep at least one elite when pruning.")
104 removed = max(0, len(self) - size)
105 for _
in range(removed):
115 def _add_internal(self, individual, raise_if_not_added_to_parents, only_to_parents):
117 return super().
_add_internal(individual, raise_if_not_added_to_parents, only_to_parents)
119 if victim
is not None and not self.
_better(individual, self[victim]):
121 if victim
is None and self.
free < 1:
122 pool = [*self, individual]
124 if victim == len(self):
127 return super().
_add_internal(individual, raise_if_not_added_to_parents,
False, victim)
FitnessLike get_ind_fitness(self, IndividualLike individual, *args, **kwargs)
None _discard_by_index(self, IndividualLike individual, Optional[int] idx=None, bool also_from_parents=False)
Optional[int] _index_of(self, IndividualLike individual)
Evict the lower-quality member of the closest descriptor pair at capacity.
_closest_pair_victim(self, pool)
_add_internal(self, individual, raise_if_not_added_to_parents, only_to_parents)
Choose the victim before committing the native container update.
prune_to(self, size)
Shrink live membership by repeatedly applying closest-pair competition.
_better(self, left, right)
_check_if_can_be_added(self, individual)