QDpy
Loading...
Searching...
No Matches
archives.py
Go to the documentation of this file.
1# This file is part of qdpy.
2#
3# qdpy is free software: you can redistribute it and/or modify
4# it under the terms of the GNU Lesser General Public License as
5# published by the Free Software Foundation, either version 3 of
6# the License, or (at your option) any later version.
7#
8# qdpy is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11# GNU Lesser General Public License for more details.
12#
13# You should have received a copy of the GNU Lesser General Public
14# License along with qdpy. If not, see <http://www.gnu.org/licenses/>.
15
16
18
19"""Novelty-based archives and optional adaptive thresholds."""
20
21__all__ = ["NoveltyArchive", "SelfAdaptiveNoveltyArchive"]
22
23
24from typing import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, MutableMapping, Mapping, overload
25import random
26
27import numpy as np
28from scipy.spatial import cKDTree
29from scipy.spatial.distance import cdist
30
31from qdpy.utils import *
32from qdpy.phenotype import *
33from qdpy.base import *
34from qdpy.metrics import novelty, novelty_local_competition, novelty_nn
35from .base import *
36
37
38
39
40
41
42
44 """Keep a small tail for new entries and rebuild if older rows change."""
45
46 def __init__(self):
47 self._rows = None
48 self._tree = None
49
50
51 @staticmethod
52 def _coordinates(features):
53 return features.values if type(features) is Features else tuple(features)
54
55
58 def query(self, individual, parents, k, get_features):
59 if len(parents) < 64 or type(k) is not int or k >= len(parents) // 2:
60 return None
61 try:
62 query = np.asarray(self._coordinates(get_features(individual)), dtype=float)
63 rows = np.asarray([self._coordinates(get_features(parent)) for parent in parents], dtype=float)
64 except (TypeError, ValueError, OverflowError):
65 return None
66 if (rows.ndim != 2 or rows.shape[1:] != query.shape or not query.size
67 or not np.isfinite(rows).all() or not np.isfinite(query).all()
68 or max(np.abs(rows).max(), np.abs(query).max()) > 1e100):
69 return None
70
71 prefix = 0 if self._rows is None else len(self._rows)
72 if (not prefix or len(rows) < prefix or len(rows) - prefix >= 128
73 or not np.array_equal(rows[:prefix], self._rows)):
74 self._rows = rows
75 self._tree = cKDTree(rows)
76 prefix = len(rows)
77
78 last_distance = np.max(self._tree.query(query, k=min(max(k, 1), prefix))[0])
79 # Include cutoff ties even if the tree's accumulated distance differs
80 # slightly from the scalar norm used below.
81 tolerance = 8 * query.size * np.finfo(float).eps
82 radius = np.nextafter(last_distance * (1.0 + tolerance), np.inf)
83 candidates = self._tree.query_ball_point(query, radius)
84 candidates.extend(range(prefix, len(rows)))
85 ranked = sorted((math.dist(query, rows[i]), i) for i in candidates)
86 if len(ranked) < max(k, 1):
87 return None
88 novelty_score = np.mean([dist for dist, _ in ranked[:k]]) if k > 0 else np.inf
89 return novelty_score, (ranked[0][1],)
90
91
92@registry.register
94 """Retain novel or locally better candidates using parent history.
95
96 Compute novelty from up to ``k`` nearest reference entries. The
97 archive's descriptor accessor is used on both sides of the distance,
98 including when the descriptor vector comes from named scores. With
99 no neighbours, admit a valid candidate. Otherwise admit when mean
100 distance exceeds ``threshold_novelty`` or the candidate dominates its
101 nearest neighbour.
102
103 A dominating candidate can replace the neighbour in the child only
104 when that neighbour has a local entry. The parent keeps its record.
105 Attach a parent archive before adding to a result restored without
106 parent links.
107
108 :param indexed: Enable an exact Euclidean parent index. The index
109 validates live descriptors and reuses an unchanged prefix between
110 queries. Other metrics continue to use the ordinary scan.
111 """
112
113 #depot: BackendLike[IndividualLike]
114
115 k: int
116 threshold_novelty: float
117 novelty_distance: Union[str, Callable]
118
119 def __init__(self, iterable: Optional[Iterable] = None,
120 k: int = 15, threshold_novelty: float = 0.01, novelty_distance: Union[str, Callable] = "euclidean",
121 parents: Sequence[ContainerLike] = [], *, indexed: bool = False, **kwargs: Any) -> None:
122 self.k = k
123 self.threshold_novelty = threshold_novelty
124 self.novelty_distance = novelty_distance
125 self.indexed = indexed
126 self._novelty_index = None
127 if len(parents) == 0:
128 raise ValueError("``parents`` must contain at least one parent container to create an archive container.")
129 super().__init__(iterable, parents=parents, **kwargs)
130
131
132 def __getstate__(self):
133 state = super().__getstate__()
134 state["_novelty_index"] = None
135 return state
136
137
138 def _admission_neighbours(self, individual, parents):
139 if getattr(self, "indexed", False) and self.novelty_distance == "euclidean":
140 if self._novelty_index is None:
142 result = self._novelty_index.query(individual, parents, self.k, self.get_ind_features)
143 if result is not None:
144 return result
145 return novelty_nn(individual, parents, k=self.k, dist=self.novelty_distance,
146 get_features=self.get_ind_features)
147
148
156 def _add_internal(self, individual: IndividualLike, raise_if_not_added_to_parents: bool, only_to_parents: bool) -> Optional[int]:
157 if not self.parents:
158 raise RuntimeError("NoveltyArchive needs a parent archive before adding candidates.")
159 if only_to_parents:
160 return super()._add_internal(individual, raise_if_not_added_to_parents, True)
161
162 all_parents = self.all_parents_inds()
163 novelty, nn = self._admission_neighbours(individual, all_parents)
164 if not nn or novelty > self.threshold_novelty:
165 return super()._add_internal(individual, raise_if_not_added_to_parents, False)
166
167 neighbour = all_parents[nn[0]]
168 if self.get_ind_fitness(individual).dominates(self.get_ind_fitness(neighbour)):
169 return super()._add_internal(
170 individual, raise_if_not_added_to_parents, False, replace_index=self._index_of(neighbour)
171 )
172 return super()._add_internal(individual, raise_if_not_added_to_parents, True)
173
174
175
176@registry.register
178 """Re-estimate an NSLC novelty threshold as the reference set grows.
179
180 Use the sampled Euclidean diameter divided by the square root of
181 ``k_resolution``, floored by ``min_threshold``. The initial threshold is
182 used until two parent entries are available. Recompute before every
183 ``threshold_update_period``-th valid local query. The default Euclidean
184 admission rule and parent replacement semantics still apply.
185
186 :param k_resolution: Positive scale parameter for the diameter heuristic.
187 :param threshold_update_period: Valid query count between updates. Zero disables them.
188 :param max_threshold_samples: Maximum number of parents used in a diameter estimate.
189 :param min_threshold: Lower bound for the computed threshold.
190 :param seed: Seed for sampling parents, independent of the search RNG.
191 """
192
193 def __init__(self, iterable=None, *, k_resolution: float = 60000,
194 threshold_update_period: int = 256, max_threshold_samples: int = 2048,
195 min_threshold: float = 1e-12, seed: int = 0, **kwargs):
196 if not math.isfinite(k_resolution) or k_resolution <= 0:
197 raise ValueError("k_resolution must be finite and positive.")
198 if (not isinstance(threshold_update_period, int) or threshold_update_period < 0
199 or not isinstance(max_threshold_samples, int) or max_threshold_samples < 2):
200 raise ValueError("Use a nonnegative update period and a sample size of at least two.")
201 if not math.isfinite(min_threshold) or min_threshold < 0:
202 raise ValueError("min_threshold must be finite and nonnegative.")
203 if kwargs.get("novelty_distance", "euclidean") != "euclidean":
204 raise ValueError("Adaptive novelty thresholds use Euclidean distances.")
205 self.k_resolution = k_resolution
206 self.threshold_update_period = threshold_update_period
207 self.max_threshold_samples = max_threshold_samples
208 self.min_threshold = min_threshold
209 self._threshold_rng = random.Random(seed)
210 self._valid_queries = 0
211 super().__init__(iterable, **kwargs)
212
213
215 def recompute_threshold(self) -> float:
216 """Recompute the threshold from the current parent archive."""
217 if not self.parents:
218 raise RuntimeError("An adaptive novelty threshold needs a parent archive.")
219 return self._recompute_threshold(self.all_parents_inds())
220
221
222 def _recompute_threshold(self, parents):
223 if len(parents) < 2:
224 return self.threshold_novelty
225 if len(parents) > self.max_threshold_samples:
226 parents = self._threshold_rng.sample(parents, self.max_threshold_samples)
227 descriptors = np.asarray([tuple(self.get_ind_features(parent)) for parent in parents], dtype=float)
228 if descriptors.ndim != 2 or not descriptors.shape[1] or not np.isfinite(descriptors).all():
229 raise ValueError("Adaptive novelty requires finite descriptors of the same dimension.")
230
231 # Center before scaling so a large constant coordinate cannot mask
232 # variation on another axis. Halve the extrema before summing.
233 descriptors -= descriptors.min(axis=0) / 2 + descriptors.max(axis=0) / 2
234 scale = float(np.max(np.abs(descriptors))) or 1.0
235 descriptors /= scale
236 diameter = 0.0
237 for start in range(0, len(descriptors), 128):
238 block = descriptors[start:start + 128]
239 diameter = max(diameter, float(cdist(block, descriptors[start:]).max()))
240 threshold = (diameter / math.sqrt(self.k_resolution)) * scale
241 if not math.isfinite(threshold):
242 raise ValueError("The adaptive novelty threshold exceeds the finite float range.")
243 self.threshold_novelty = max(self.min_threshold, threshold)
244 return self.threshold_novelty
245
246
247 def _admission_neighbours(self, individual, parents):
248 next_query = self._valid_queries + 1
249 if self.threshold_update_period and next_query % self.threshold_update_period == 0:
250 self._recompute_threshold(parents)
251 result = super()._admission_neighbours(individual, parents)
252 self._valid_queries = next_query
253 return result
254
255
256
257
_admission_neighbours(self, individual, parents)
Score admission against the same reference set in either search mode.
Definition archives.py:138
Optional[int] _add_internal(self, IndividualLike individual, bool raise_if_not_added_to_parents, bool only_to_parents)
Apply the novelty gate or compare the nearest reference fitness.
Definition archives.py:156
__getstate__(self)
Omit the transient search index from result files.
Definition archives.py:132
Scale the novelty threshold from a bounded sample of parent history.
Definition archives.py:177
_recompute_threshold(self, parents)
Limit pairwise-distance memory by scanning blocks of rows.
Definition archives.py:222
_admission_neighbours(self, individual, parents)
Update the threshold before a scheduled admission query.
Definition archives.py:247
float recompute_threshold(self)
Update the threshold from the largest sampled descriptor distance.
Definition archives.py:215
ARCHIVE-BASED CLASSES ########### {{{1.
Definition archives.py:43
query(self, individual, parents, k, get_features)
Return the mean of the k nearest distances and the first reference index.
Definition archives.py:58
_coordinates(features)
Expose coordinates without copying a built-in feature tuple.
Definition archives.py:52
FitnessLike get_ind_fitness(self, IndividualLike individual, *args, **kwargs)
Definition base.py:178
Sequence[IndividualLike] all_parents_inds(self)
Definition base.py:165
Optional[int] _index_of(self, IndividualLike individual)
Definition base.py:769