19"""Novelty-based archives and optional adaptive thresholds."""
21__all__ = [
"NoveltyArchive",
"SelfAdaptiveNoveltyArchive"]
24from typing
import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, MutableMapping, Mapping, overload
28from scipy.spatial
import cKDTree
29from scipy.spatial.distance
import cdist
34from qdpy.metrics import novelty, novelty_local_competition, novelty_nn
44 """Keep a small tail for new entries and rebuild if older rows change."""
53 return features.values
if type(features)
is Features
else tuple(features)
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:
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):
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):
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)):
75 self.
_tree = cKDTree(rows)
78 last_distance = np.max(self.
_tree.
query(query, k=min(max(k, 1), prefix))[0])
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):
88 novelty_score = np.mean([dist
for dist, _
in ranked[:k]])
if k > 0
else np.inf
89 return novelty_score, (ranked[0][1],)
94 """Retain novel or locally better candidates using parent history.
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
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
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.
116 threshold_novelty: float
117 novelty_distance: Union[str, Callable]
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:
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)
134 state[
"_novelty_index"] =
None
139 if getattr(self,
"indexed",
False)
and self.
novelty_distance ==
"euclidean":
143 if result
is not None:
156 def _add_internal(self, individual: IndividualLike, raise_if_not_added_to_parents: bool, only_to_parents: bool) -> Optional[int]:
158 raise RuntimeError(
"NoveltyArchive needs a parent archive before adding candidates.")
160 return super().
_add_internal(individual, raise_if_not_added_to_parents,
True)
165 return super().
_add_internal(individual, raise_if_not_added_to_parents,
False)
167 neighbour = all_parents[nn[0]]
170 individual, raise_if_not_added_to_parents,
False, replace_index=self.
_index_of(neighbour)
172 return super().
_add_internal(individual, raise_if_not_added_to_parents,
True)
178 """Re-estimate an NSLC novelty threshold as the reference set grows.
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.
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.
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.")
211 super().__init__(iterable, **kwargs)
216 """Recompute the threshold from the current parent archive."""
218 raise RuntimeError(
"An adaptive novelty threshold needs a parent archive.")
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.")
233 descriptors -= descriptors.min(axis=0) / 2 + descriptors.max(axis=0) / 2
234 scale = float(np.max(np.abs(descriptors)))
or 1.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.")
_admission_neighbours(self, individual, parents)
Score admission against the same reference set in either search mode.
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.
__getstate__(self)
Omit the transient search index from result files.
Scale the novelty threshold from a bounded sample of parent history.
_recompute_threshold(self, parents)
Limit pairwise-distance memory by scanning blocks of rows.
_admission_neighbours(self, individual, parents)
Update the threshold before a scheduled admission query.
int threshold_update_period
float recompute_threshold(self)
Update the threshold from the largest sampled descriptor distance.
ARCHIVE-BASED CLASSES ########### {{{1.
query(self, individual, parents, k, get_features)
Return the mean of the k nearest distances and the first reference index.
_coordinates(features)
Expose coordinates without copying a built-in feature tuple.
FitnessLike get_ind_fitness(self, IndividualLike individual, *args, **kwargs)
Sequence[IndividualLike] all_parents_inds(self)
Optional[int] _index_of(self, IndividualLike individual)