QDpy
Loading...
Searching...
No Matches
metrics.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 and multi-archive comparison metrics."""
20
21from collections import Counter
22import numpy as np
23from scipy.special import rel_entr
24#from scipy.spatial.distance import euclidean
25#from itertools import starmap
26from typing import Sequence, Callable, Tuple
27
28from qdpy._acceleration import kernels as _kernels
29from qdpy.phenotype import *
30from qdpy.base import *
31
32
33
34
35#@jit(nopython=True)
36
43def features_distances(individual: IndividualLike, container: Sequence, dist: Union[str, Callable] = "euclidean",
44 *, get_features: Optional[Callable] = None) -> Sequence:
45 """Measure distance from a candidate to each reference entry.
46
47 :param individual: Candidate to compare.
48 :param container: Reference entries in the order to report.
49 :param dist: The string ``"euclidean"`` or a callable taking two
50 descriptor vectors.
51 :param get_features: Descriptor accessor. Defaults to the
52 candidate's ``features`` attribute.
53 :returns: A one-dimensional NumPy array in reference order.
54 :raises ValueError: If a metric name is unsupported or descriptor
55 dimensions differ.
56 """
57 distances = np.zeros(len(container))
58 if get_features is None:
59 get_features = lambda ind: ind.features
60 ind_features = get_features(individual)
61 if isinstance(dist, str) and dist != "euclidean":
62 raise ValueError(f"Unknown `dist` type: '{dist}'.")
63 builtin_euclidean = type(dist) is str
64 if builtin_euclidean and _kernels is not None:
65 _kernels.euclidean_distances(distances, ind_features, container, get_features, Features, math.dist)
66 return distances
67 unpack_query = builtin_euclidean and type(ind_features) is Features
68 for i, other in enumerate(container):
69 other_features = get_features(other)
70 # Built-in Features delegates length and iteration to values. Read
71 # them after the accessor call, which can update a descriptor.
72 query = ind_features.values if unpack_query else ind_features
73 reference = (other_features.values if builtin_euclidean and type(other_features) is Features
74 else other_features)
75 if len(query) != len(reference):
76 raise ValueError("Behaviour descriptors must have the same dimension.")
77 if builtin_euclidean or dist == "euclidean":
78 distances[i] = math.dist(query, reference)
79 else:
80 distances[i] = dist(ind_features, other_features)
81 return distances
82
83def novelty(individual: IndividualLike, container: Sequence, k: int = 1, dist: Union[str, Callable] = "euclidean", ignore_first: bool = False, default_novelty: float = 0.1) -> float:
84 """Return the mean distance to the nearest scored neighbours.
85
86 :param individual: Candidate whose descriptors define the query.
87 :param container: Reference entries.
88 :param k: Maximum number of neighbours in the mean.
89 :param dist: Metric accepted by :func:`features_distances`.
90 :param ignore_first: Skip the closest entry before selecting
91 neighbours. Use it when the reference includes the query.
92 :param default_novelty: Result when no neighbours are scored.
93 :returns: The mean over the neighbours that are available.
94 """
95 start = 1 if ignore_first else 0
96 if len(container) <= start or k <= 0:
97 return default_novelty
98 distances = sorted(features_distances(individual, container, dist))
99 return np.mean(distances[start:start + k])
100
101
102def _rank_neighbours(distances: np.ndarray, count: int) -> np.ndarray:
103 if (_kernels is not None and len(distances) >= 64 and 0 < count <= 32
104 and distances.dtype == np.float64 and distances.flags.c_contiguous):
105 return _kernels.stable_top_k(distances, count)
106 # Reserve partitioning for a small prefix of a large reference.
107 if len(distances) < 2048 or not 0 < count <= len(distances) // 8:
108 return distances.argsort(kind="stable")
109 cutoff = np.partition(distances, count - 1)[count - 1]
110 closer = np.flatnonzero(distances < cutoff)
111 # Partitioning can split a tie arbitrarily. Recover the tied entries
112 # from the original sequence so the first ones come first.
113 tied = np.flatnonzero(distances == cutoff)[:count - len(closer)]
114 return np.concatenate((closer[distances[closer].argsort(kind="stable")], tied))
115
116
117def 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]:
118 """Return novelty and the indexes of the nearest entries.
119
120 The novelty calculation uses up to ``k`` neighbours independently
121 of the requested number of returned indexes. Ties in distance
122 keep reference order. When ``ignore_first`` is true, both operations
123 skip the closest entry.
124
125 :param nn_size: Maximum number of neighbour indexes to return.
126 :param default_novelty: Fallback score when the mean has no entries.
127 :param get_features: Optional accessor for the query and reference
128 descriptors. Archives use this to compare named descriptors.
129 :returns: A novelty score and indexes into the reference sequence.
130 """
131 start = 1 if ignore_first else 0
132 if len(container) <= start:
133 return default_novelty, []
134 distances = features_distances(individual, container, dist, get_features=get_features)
135 if np.isnan(distances).any():
136 # Python's unordered comparisons with NaN have different semantics
137 # from NumPy's sort, which always moves NaNs to the end.
138 ranked = sorted(range(len(distances)), key=distances.__getitem__)
139 else:
140 count = start + max(k, nn_size, 0) if type(k) is type(nn_size) is int else len(distances)
141 ranked = _rank_neighbours(distances, count)
142 score = np.mean(distances[ranked[start:start + k]]) if k > 0 else default_novelty
143 indices = tuple(int(i) for i in ranked[start:start + max(nn_size, 0)])
144 return score, indices or []
145
146
147def 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]:
148 """Return novelty and the fraction of requested neighbours outperformed.
149
150 Compare the query's fitness to each nearest neighbour using
151 dominance. Divide the number outperformed by ``k`` even when fewer
152 neighbours are available. The novelty mean uses the actual number
153 of neighbours available. ``ignore_first`` skips the closest entry.
154
155 Return ``(default_novelty, default_local_competition)`` when no
156 neighbours are scored.
157 """
158 start = 1 if ignore_first else 0
159 if len(container) <= start or k <= 0:
160 return default_novelty, default_local_competition
161 distances: Sequence = features_distances(individual, container, dist)
162 nn = sorted(zip(distances, container))[start:start + k]
163 nearest_neighbours_dists, nearest_neighbours = tuple(zip(*nn))
164 novelty: float = np.mean(nearest_neighbours_dists)
165 local_competition: float = sum((individual.fitness.dominates(ind.fitness) for ind in nearest_neighbours)) / float(k)
166 return novelty, local_competition
167
168
169
173def archive_originality(archives, *, key=tuple) -> tuple[float, ...]:
174 """Return each archive's fraction of distinct solutions exclusive to it.
175
176 The default identity is the genome tuple. Provide a hashable key for
177 candidates with nested or otherwise unhashable genes. Multiple copies
178 inside one archive count once. An empty archive contributes zero.
179 """
180 memberships = [set(map(key, archive)) for archive in archives]
181 occurrences = Counter(solution for archive in memberships for solution in archive)
182 return tuple(sum(occurrences[solution] == 1 for solution in archive) / len(archive)
183 if archive else 0.0 for archive in memberships)
184
185
186
190def archive_overlap(archives, *, key=tuple) -> np.ndarray:
191 """Return pairwise Jaccard overlap in archive order.
192
193 Two empty archives have overlap one. A pair with one empty and one
194 populated archive has overlap zero. By default, compare genome tuples.
195 """
196 memberships = [set(map(key, archive)) for archive in archives]
197 overlap = np.eye(len(memberships))
198 for i, first in enumerate(memberships):
199 for j, second in enumerate(memberships[:i]):
200 shared = len(first & second)
201 union = len(first) + len(second) - shared
202 overlap[i, j] = overlap[j, i] = shared / union if union else 1.0
203 return overlap
204
205
206
214def pairwise_kl_coverage(reference, compared, *, coordinate_pairs=None,
215 bins: int = 10, ranges=None, pseudocount: float = 1e-12) -> float:
216 """Compare descriptor distributions on explicit two-dimensional projections.
217
218 Use common histogram edges for both inputs. With no explicit ranges,
219 derive the edges from both samples together. Explicit ranges must
220 contain every observation. Smooth the counts before normalising each
221 histogram. Smaller values indicate more similar distributions.
222 """
223 reference, compared = (np.asarray(rows, dtype=float) for rows in (reference, compared))
224 if (reference.ndim != 2 or compared.ndim != 2 or not len(reference) or not len(compared)
225 or reference.shape[1] != compared.shape[1] or reference.shape[1] < 2
226 or not np.isfinite(reference).all() or not np.isfinite(compared).all()):
227 raise ValueError("Provide nonempty finite descriptor matrices of the same width (at least two).")
228 if not isinstance(bins, (int, np.integer)) or bins < 1:
229 raise ValueError("bins must be a positive integer.")
230 if not math.isfinite(pseudocount) or pseudocount < np.finfo(float).tiny:
231 raise ValueError("pseudocount must be a positive, finite normal float.")
232 width = reference.shape[1]
233 low = np.minimum(reference.min(axis=0), compared.min(axis=0))
234 high = np.maximum(reference.max(axis=0), compared.max(axis=0))
235 if ranges is None:
236 limits = np.column_stack((low, high))
237 else:
238 limits = np.asarray(ranges, dtype=float)
239 if (limits.shape != (width, 2) or not np.isfinite(limits).all()
240 or (limits[:, 0] >= limits[:, 1]).any()
241 or (low < limits[:, 0]).any() or (high > limits[:, 1]).any()):
242 raise ValueError("Provide increasing ranges containing all observations.")
243 if coordinate_pairs is None:
244 if width % 2:
245 raise ValueError("Specify coordinate_pairs for an odd number of columns.")
246 coordinate_pairs = [(i, i + 1) for i in range(0, width, 2)]
247 pairs = tuple(coordinate_pairs)
248 if not pairs or any(len(pair) != 2 or pair[0] == pair[1] or any(
249 not isinstance(i, (int, np.integer)) or not 0 <= i < width for i in pair) for pair in pairs):
250 raise ValueError("Each coordinate pair must contain two distinct column indices.")
251
252 score = 0.0
253 for x, y in pairs:
254 distributions = []
255 for sample in (reference, compared):
256 counts = np.histogram2d(sample[:, x], sample[:, y], bins=bins, range=limits[[x, y]])[0]
257 probabilities = counts + pseudocount
258 probabilities /= probabilities.max()
259 probabilities /= probabilities.sum()
260 distributions.append(probabilities)
261 score += rel_entr(*distributions).sum()
262 return float(score)
263
264
265
266
267# MODELINE "{{{1
268# vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8
269# vim:foldmethod=marker