Source code for qdpy.metrics

#    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 Nearest-neighbour distances, novelty, and local competition.

"""Novelty and multi-archive comparison metrics."""

from collections import Counter
import numpy as np
from scipy.special import rel_entr
#from scipy.spatial.distance import euclidean
#from itertools import starmap
from typing import Sequence, Callable, Tuple

from qdpy._acceleration import kernels as _kernels
from qdpy.phenotype import *
from qdpy.base import *


########### METRICS ########### {{{1

#@jit(nopython=True)
## @brief Check descriptor dimensions before computing each distance.
# @param individual Query candidate.
# @param container Reference sequence.
# @param dist Euclidean metric name or descriptor-to-descriptor callable.
# @param get_features Optional accessor used on both sides of the comparison.
# @return Numeric distances in the original reference order.
# @throws ValueError If dimensions differ or the metric name is unknown.
[docs] def features_distances(individual: IndividualLike, container: Sequence, dist: Union[str, Callable] = "euclidean", *, get_features: Optional[Callable] = None) -> Sequence: """Measure distance from a candidate to each reference entry. :param individual: Candidate to compare. :param container: Reference entries in the order to report. :param dist: The string ``"euclidean"`` or a callable taking two descriptor vectors. :param get_features: Descriptor accessor. Defaults to the candidate's ``features`` attribute. :returns: A one-dimensional NumPy array in reference order. :raises ValueError: If a metric name is unsupported or descriptor dimensions differ. """ distances = np.zeros(len(container)) if get_features is None: get_features = lambda ind: ind.features ind_features = get_features(individual) if isinstance(dist, str) and dist != "euclidean": raise ValueError(f"Unknown `dist` type: '{dist}'.") builtin_euclidean = type(dist) is str if builtin_euclidean and _kernels is not None: _kernels.euclidean_distances(distances, ind_features, container, get_features, Features, math.dist) return distances unpack_query = builtin_euclidean and type(ind_features) is Features for i, other in enumerate(container): other_features = get_features(other) # Built-in Features delegates length and iteration to values. Read # them after the accessor call, which can update a descriptor. query = ind_features.values if unpack_query else ind_features reference = (other_features.values if builtin_euclidean and type(other_features) is Features else other_features) if len(query) != len(reference): raise ValueError("Behaviour descriptors must have the same dimension.") if builtin_euclidean or dist == "euclidean": distances[i] = math.dist(query, reference) else: distances[i] = dist(ind_features, other_features) return distances
[docs] def novelty(individual: IndividualLike, container: Sequence, k: int = 1, dist: Union[str, Callable] = "euclidean", ignore_first: bool = False, default_novelty: float = 0.1) -> float: """Return the mean distance to the nearest scored neighbours. :param individual: Candidate whose descriptors define the query. :param container: Reference entries. :param k: Maximum number of neighbours in the mean. :param dist: Metric accepted by :func:`features_distances`. :param ignore_first: Skip the closest entry before selecting neighbours. Use it when the reference includes the query. :param default_novelty: Result when no neighbours are scored. :returns: The mean over the neighbours that are available. """ start = 1 if ignore_first else 0 if len(container) <= start or k <= 0: return default_novelty distances = sorted(features_distances(individual, container, dist)) return np.mean(distances[start:start + k])
def _rank_neighbours(distances: np.ndarray, count: int) -> np.ndarray: if (_kernels is not None and len(distances) >= 64 and 0 < count <= 32 and distances.dtype == np.float64 and distances.flags.c_contiguous): return _kernels.stable_top_k(distances, count) # Reserve partitioning for a small prefix of a large reference. if len(distances) < 2048 or not 0 < count <= len(distances) // 8: return distances.argsort(kind="stable") cutoff = np.partition(distances, count - 1)[count - 1] closer = np.flatnonzero(distances < cutoff) # Partitioning can split a tie arbitrarily. Recover the tied entries # from the original sequence so the first ones come first. tied = np.flatnonzero(distances == cutoff)[:count - len(closer)] return np.concatenate((closer[distances[closer].argsort(kind="stable")], tied))
[docs] def novelty_nn(individual: IndividualLike, container: Sequence, k: int = 1, nn_size: int = 1, dist: Union[str, Callable] = "euclidean", ignore_first: bool = False, default_novelty: float = np.inf, *, get_features: Optional[Callable] = None) -> Tuple[float, Sequence]: """Return novelty and the indexes of the nearest entries. The novelty calculation uses up to ``k`` neighbours independently of the requested number of returned indexes. Ties in distance keep reference order. When ``ignore_first`` is true, both operations skip the closest entry. :param nn_size: Maximum number of neighbour indexes to return. :param default_novelty: Fallback score when the mean has no entries. :param get_features: Optional accessor for the query and reference descriptors. Archives use this to compare named descriptors. :returns: A novelty score and indexes into the reference sequence. """ start = 1 if ignore_first else 0 if len(container) <= start: return default_novelty, [] distances = features_distances(individual, container, dist, get_features=get_features) if np.isnan(distances).any(): # Python's unordered comparisons with NaN have different semantics # from NumPy's sort, which always moves NaNs to the end. ranked = sorted(range(len(distances)), key=distances.__getitem__) else: count = start + max(k, nn_size, 0) if type(k) is type(nn_size) is int else len(distances) ranked = _rank_neighbours(distances, count) score = np.mean(distances[ranked[start:start + k]]) if k > 0 else default_novelty indices = tuple(int(i) for i in ranked[start:start + max(nn_size, 0)]) return score, indices or []
[docs] def novelty_local_competition(individual: IndividualLike, container: Sequence, k: int = 1, dist: Union[str, Callable] = "euclidean", ignore_first: bool = False, default_novelty: float = 0.1, default_local_competition: float = 1.0) -> Tuple[float, float]: """Return novelty and the fraction of requested neighbours outperformed. Compare the query's fitness to each nearest neighbour using dominance. Divide the number outperformed by ``k`` even when fewer neighbours are available. The novelty mean uses the actual number of neighbours available. ``ignore_first`` skips the closest entry. Return ``(default_novelty, default_local_competition)`` when no neighbours are scored. """ start = 1 if ignore_first else 0 if len(container) <= start or k <= 0: return default_novelty, default_local_competition distances: Sequence = features_distances(individual, container, dist) nn = sorted(zip(distances, container))[start:start + k] nearest_neighbours_dists, nearest_neighbours = tuple(zip(*nn)) novelty: float = np.mean(nearest_neighbours_dists) local_competition: float = sum((individual.fitness.dominates(ind.fitness) for ind in nearest_neighbours)) / float(k) return novelty, local_competition
## @brief Fraction of each archive's distinct solutions exclusive to it. # @param archives Iterable of archives in output order. # @param key Callable mapping a candidate to a hashable identity. # @return One fraction per archive, including zero for empty archives.
[docs] def archive_originality(archives, *, key=tuple) -> tuple[float, ...]: """Return each archive's fraction of distinct solutions exclusive to it. The default identity is the genome tuple. Provide a hashable key for candidates with nested or otherwise unhashable genes. Multiple copies inside one archive count once. An empty archive contributes zero. """ memberships = [set(map(key, archive)) for archive in archives] occurrences = Counter(solution for archive in memberships for solution in archive) return tuple(sum(occurrences[solution] == 1 for solution in archive) / len(archive) if archive else 0.0 for archive in memberships)
## @brief Compare archive membership using the Jaccard index. # @param archives Iterable of archives in row and column order. # @param key Callable mapping a candidate to a hashable identity. # @return Symmetric matrix of intersection sizes divided by union sizes.
[docs] def archive_overlap(archives, *, key=tuple) -> np.ndarray: """Return pairwise Jaccard overlap in archive order. Two empty archives have overlap one. A pair with one empty and one populated archive has overlap zero. By default, compare genome tuples. """ memberships = [set(map(key, archive)) for archive in archives] overlap = np.eye(len(memberships)) for i, first in enumerate(memberships): for j, second in enumerate(memberships[:i]): shared = len(first & second) union = len(first) + len(second) - shared overlap[i, j] = overlap[j, i] = shared / union if union else 1.0 return overlap
## @brief Sum reference-to-compared KL divergences over descriptor pairs. # @param reference Nonempty matrix of reference descriptors. # @param compared Nonempty matrix in the same descriptor space. # @param coordinate_pairs Pairs of column indices, or consecutive pairs by default. # @param bins Number of bins for each coordinate. # @param ranges Optional finite (lower, upper) limits per coordinate. # @param pseudocount Positive amount to add to each histogram bin. # @return Sum of KL(reference || compared), using natural logarithms.
[docs] def pairwise_kl_coverage(reference, compared, *, coordinate_pairs=None, bins: int = 10, ranges=None, pseudocount: float = 1e-12) -> float: """Compare descriptor distributions on explicit two-dimensional projections. Use common histogram edges for both inputs. With no explicit ranges, derive the edges from both samples together. Explicit ranges must contain every observation. Smooth the counts before normalising each histogram. Smaller values indicate more similar distributions. """ reference, compared = (np.asarray(rows, dtype=float) for rows in (reference, compared)) if (reference.ndim != 2 or compared.ndim != 2 or not len(reference) or not len(compared) or reference.shape[1] != compared.shape[1] or reference.shape[1] < 2 or not np.isfinite(reference).all() or not np.isfinite(compared).all()): raise ValueError("Provide nonempty finite descriptor matrices of the same width (at least two).") if not isinstance(bins, (int, np.integer)) or bins < 1: raise ValueError("bins must be a positive integer.") if not math.isfinite(pseudocount) or pseudocount < np.finfo(float).tiny: raise ValueError("pseudocount must be a positive, finite normal float.") width = reference.shape[1] low = np.minimum(reference.min(axis=0), compared.min(axis=0)) high = np.maximum(reference.max(axis=0), compared.max(axis=0)) if ranges is None: limits = np.column_stack((low, high)) else: limits = np.asarray(ranges, dtype=float) if (limits.shape != (width, 2) or not np.isfinite(limits).all() or (limits[:, 0] >= limits[:, 1]).any() or (low < limits[:, 0]).any() or (high > limits[:, 1]).any()): raise ValueError("Provide increasing ranges containing all observations.") if coordinate_pairs is None: if width % 2: raise ValueError("Specify coordinate_pairs for an odd number of columns.") coordinate_pairs = [(i, i + 1) for i in range(0, width, 2)] pairs = tuple(coordinate_pairs) if not pairs or any(len(pair) != 2 or pair[0] == pair[1] or any( not isinstance(i, (int, np.integer)) or not 0 <= i < width for i in pair) for pair in pairs): raise ValueError("Each coordinate pair must contain two distinct column indices.") score = 0.0 for x, y in pairs: distributions = [] for sample in (reference, compared): counts = np.histogram2d(sample[:, x], sample[:, y], bins=bins, range=limits[[x, y]])[0] probabilities = counts + pseudocount probabilities /= probabilities.max() probabilities /= probabilities.sum() distributions.append(probabilities) score += rel_entr(*distributions).sum() return float(score)
# MODELINE "{{{1 # vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8 # vim:foldmethod=marker