# This file is part of qdpy.
#
# qdpy is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# qdpy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with qdpy. If not, see <http://www.gnu.org/licenses/>.
## @file
# @brief Novelty-based admission and local competition against parent history.
"""Novelty-based archives and optional adaptive thresholds."""
__all__ = ["NoveltyArchive", "SelfAdaptiveNoveltyArchive"]
########### IMPORTS ########### {{{1
from typing import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, MutableMapping, Mapping, overload
import random
import numpy as np
from scipy.spatial import cKDTree
from scipy.spatial.distance import cdist
from qdpy.utils import *
from qdpy.phenotype import *
from qdpy.base import *
from qdpy.metrics import novelty, novelty_local_competition, novelty_nn
from .base import *
########### ARCHIVE-BASED CLASSES ########### {{{1
## @brief Cache an exact Euclidean index over a stable prefix of parent descriptors.
class _EuclideanNoveltyIndex:
"""Keep a small tail for new entries and rebuild if older rows change."""
def __init__(self):
self._rows = None
self._tree = None
## @brief Expose coordinates without copying a built-in feature tuple.
@staticmethod
def _coordinates(features):
return features.values if type(features) is Features else tuple(features)
## @brief Return the mean of the k nearest distances and the first reference index.
# @details Recompute distances with math.dist and break ties in parent order.
# @return None when the scalar path should handle the inputs.
def query(self, individual, parents, k, get_features):
if len(parents) < 64 or type(k) is not int or k >= len(parents) // 2:
return None
try:
query = np.asarray(self._coordinates(get_features(individual)), dtype=float)
rows = np.asarray([self._coordinates(get_features(parent)) for parent in parents], dtype=float)
except (TypeError, ValueError, OverflowError):
return None
if (rows.ndim != 2 or rows.shape[1:] != query.shape or not query.size
or not np.isfinite(rows).all() or not np.isfinite(query).all()
or max(np.abs(rows).max(), np.abs(query).max()) > 1e100):
return None
prefix = 0 if self._rows is None else len(self._rows)
if (not prefix or len(rows) < prefix or len(rows) - prefix >= 128
or not np.array_equal(rows[:prefix], self._rows)):
self._rows = rows
self._tree = cKDTree(rows)
prefix = len(rows)
last_distance = np.max(self._tree.query(query, k=min(max(k, 1), prefix))[0])
# Include cutoff ties even if the tree's accumulated distance differs
# slightly from the scalar norm used below.
tolerance = 8 * query.size * np.finfo(float).eps
radius = np.nextafter(last_distance * (1.0 + tolerance), np.inf)
candidates = self._tree.query_ball_point(query, radius)
candidates.extend(range(prefix, len(rows)))
ranked = sorted((math.dist(query, rows[i]), i) for i in candidates)
if len(ranked) < max(k, 1):
return None
novelty_score = np.mean([dist for dist, _ in ranked[:k]]) if k > 0 else np.inf
return novelty_score, (ranked[0][1],)
[docs]
@registry.register
class NoveltyArchive(Container):
"""Retain novel or locally better candidates using parent history.
Compute novelty from up to ``k`` nearest reference entries. The
archive's descriptor accessor is used on both sides of the distance,
including when the descriptor vector comes from named scores. With
no neighbours, admit a valid candidate. Otherwise admit when mean
distance exceeds ``threshold_novelty`` or the candidate dominates its
nearest neighbour.
A dominating candidate can replace the neighbour in the child only
when that neighbour has a local entry. The parent keeps its record.
Attach a parent archive before adding to a result restored without
parent links.
:param indexed: Enable an exact Euclidean parent index. The index
validates live descriptors and reuses an unchanged prefix between
queries. Other metrics continue to use the ordinary scan.
"""
#depot: BackendLike[IndividualLike]
k: int
threshold_novelty: float
novelty_distance: Union[str, Callable]
def __init__(self, iterable: Optional[Iterable] = None,
k: int = 15, threshold_novelty: float = 0.01, novelty_distance: Union[str, Callable] = "euclidean",
parents: Sequence[ContainerLike] = [], *, indexed: bool = False, **kwargs: Any) -> None:
self.k = k
self.threshold_novelty = threshold_novelty
self.novelty_distance = novelty_distance
self.indexed = indexed
self._novelty_index = None
if len(parents) == 0:
raise ValueError("``parents`` must contain at least one parent container to create an archive container.")
super().__init__(iterable, parents=parents, **kwargs)
## @brief Omit the transient search index from result files.
def __getstate__(self):
state = super().__getstate__()
state["_novelty_index"] = None
return state
## @brief Score admission against the same reference set in either search mode.
def _admission_neighbours(self, individual, parents):
if getattr(self, "indexed", False) and self.novelty_distance == "euclidean":
if self._novelty_index is None:
self._novelty_index = _EuclideanNoveltyIndex()
result = self._novelty_index.query(individual, parents, self.k, self.get_ind_features)
if result is not None:
return result
return novelty_nn(individual, parents, k=self.k, dist=self.novelty_distance,
get_features=self.get_ind_features)
## @brief Apply the novelty gate or compare the nearest reference fitness.
# @param individual Candidate to admit.
# @param raise_if_not_added_to_parents Whether parent failures propagate.
# @param only_to_parents Bypass the child's novelty and admission checks.
# @return A child storage index, or None for parent-only routing.
# @details Parent neighbour indexes refer to the flattened parent
# sequence. Look up the neighbour by membership before using a
# replacement index in the child.
def _add_internal(self, individual: IndividualLike, raise_if_not_added_to_parents: bool, only_to_parents: bool) -> Optional[int]:
if not self.parents:
raise RuntimeError("NoveltyArchive needs a parent archive before adding candidates.")
if only_to_parents:
return super()._add_internal(individual, raise_if_not_added_to_parents, True)
all_parents = self.all_parents_inds()
novelty, nn = self._admission_neighbours(individual, all_parents)
if not nn or novelty > self.threshold_novelty:
return super()._add_internal(individual, raise_if_not_added_to_parents, False)
neighbour = all_parents[nn[0]]
if self.get_ind_fitness(individual).dominates(self.get_ind_fitness(neighbour)):
return super()._add_internal(
individual, raise_if_not_added_to_parents, False, replace_index=self._index_of(neighbour)
)
return super()._add_internal(individual, raise_if_not_added_to_parents, True)
## @brief Scale the novelty threshold from a bounded sample of parent history.
[docs]
@registry.register
class SelfAdaptiveNoveltyArchive(NoveltyArchive):
"""Re-estimate an NSLC novelty threshold as the reference set grows.
Use the sampled Euclidean diameter divided by the square root of
``k_resolution``, floored by ``min_threshold``. The initial threshold is
used until two parent entries are available. Recompute before every
``threshold_update_period``-th valid local query. The default Euclidean
admission rule and parent replacement semantics still apply.
:param k_resolution: Positive scale parameter for the diameter heuristic.
:param threshold_update_period: Valid query count between updates. Zero disables them.
:param max_threshold_samples: Maximum number of parents used in a diameter estimate.
:param min_threshold: Lower bound for the computed threshold.
:param seed: Seed for sampling parents, independent of the search RNG.
"""
def __init__(self, iterable=None, *, k_resolution: float = 60000,
threshold_update_period: int = 256, max_threshold_samples: int = 2048,
min_threshold: float = 1e-12, seed: int = 0, **kwargs):
if not math.isfinite(k_resolution) or k_resolution <= 0:
raise ValueError("k_resolution must be finite and positive.")
if (not isinstance(threshold_update_period, int) or threshold_update_period < 0
or not isinstance(max_threshold_samples, int) or max_threshold_samples < 2):
raise ValueError("Use a nonnegative update period and a sample size of at least two.")
if not math.isfinite(min_threshold) or min_threshold < 0:
raise ValueError("min_threshold must be finite and nonnegative.")
if kwargs.get("novelty_distance", "euclidean") != "euclidean":
raise ValueError("Adaptive novelty thresholds use Euclidean distances.")
self.k_resolution = k_resolution
self.threshold_update_period = threshold_update_period
self.max_threshold_samples = max_threshold_samples
self.min_threshold = min_threshold
self._threshold_rng = random.Random(seed)
self._valid_queries = 0
super().__init__(iterable, **kwargs)
## @brief Update the threshold from the largest sampled descriptor distance.
# @return The current threshold, retained when there are fewer than two parents.
[docs]
def recompute_threshold(self) -> float:
"""Recompute the threshold from the current parent archive."""
if not self.parents:
raise RuntimeError("An adaptive novelty threshold needs a parent archive.")
return self._recompute_threshold(self.all_parents_inds())
## @brief Limit pairwise-distance memory by scanning blocks of rows.
def _recompute_threshold(self, parents):
if len(parents) < 2:
return self.threshold_novelty
if len(parents) > self.max_threshold_samples:
parents = self._threshold_rng.sample(parents, self.max_threshold_samples)
descriptors = np.asarray([tuple(self.get_ind_features(parent)) for parent in parents], dtype=float)
if descriptors.ndim != 2 or not descriptors.shape[1] or not np.isfinite(descriptors).all():
raise ValueError("Adaptive novelty requires finite descriptors of the same dimension.")
# Center before scaling so a large constant coordinate cannot mask
# variation on another axis. Halve the extrema before summing.
descriptors -= descriptors.min(axis=0) / 2 + descriptors.max(axis=0) / 2
scale = float(np.max(np.abs(descriptors))) or 1.0
descriptors /= scale
diameter = 0.0
for start in range(0, len(descriptors), 128):
block = descriptors[start:start + 128]
diameter = max(diameter, float(cdist(block, descriptors[start:]).max()))
threshold = (diameter / math.sqrt(self.k_resolution)) * scale
if not math.isfinite(threshold):
raise ValueError("The adaptive novelty threshold exceeds the finite float range.")
self.threshold_novelty = max(self.min_threshold, threshold)
return self.threshold_novelty
## @brief Update the threshold before a scheduled admission query.
def _admission_neighbours(self, individual, parents):
next_query = self._valid_queries + 1
if self.threshold_update_period and next_query % self.threshold_update_period == 0:
self._recompute_threshold(parents)
result = super()._admission_neighbours(individual, parents)
self._valid_queries = next_query
return result
## MODELINE "{{{1
## vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8
## vim:foldmethod=marker