QDpy
Loading...
Searching...
No Matches
repertoire_selection.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Greedy determinantal point process inference on measured candidates."""
7
8from dataclasses import dataclass
9from math import isfinite
10from operator import attrgetter
11
12import numpy as np
13
14from qdpy.containers import Container
15
16from .modern import _positive_int
17
18__all__ = ["select_dpp", "DPPRepertoire"]
19
20
21
22@dataclass(frozen=True)
24 """Members reference the input objects. Indices retain greedy selection order."""
25
26 indices: tuple[int, ...]
27 members: tuple
28 similarity_logdet: float
29 objective_logdet: float
30
31
32def _scalar_quality(fitness):
33 values, weights = fitness.values, fitness.weights
34 if len(values) != 1 or len(weights) != 1:
35 raise ValueError("Use scalar weighted fitness or supply a quality callback.")
36 return values[0] * weights[0] if weights[0] != 0 else 0.
37
38
39
48def select_dpp(candidates, size, *, embedding=None, quality=None,
49 bandwidth=1., quality_strength=1., ridge=1e-8):
50 """Select a compact repertoire without modifying or reevaluating candidates.
51
52 The defaults use each elite's feature vector and its scalar weighted
53 fitness, resolving named scores and weights when given a container.
54 Rescale features before selection when axes have different units.
55 The maximum quality gets zero log penalty and the minimum gets
56 a penalty of quality_strength. Set
57 quality_strength to zero for diversity-only selection. An incremental
58 Cholesky update needs only one kernel column per selected member.
59 """
60 pool = tuple(candidates)
61 size = _positive_int(size, "size")
62 if size > len(pool):
63 raise ValueError("size cannot exceed the candidate count.")
64 if (not isfinite(bandwidth) or bandwidth <= 0. or not isfinite(quality_strength)
65 or quality_strength < 0. or not np.finfo(float).eps <= ridge <= 1.):
66 raise ValueError("Use positive finite bandwidth, nonnegative finite quality strength, and ridge in [eps, 1].")
67 archive = candidates if isinstance(candidates, Container) else None
68 if embedding is None:
69 get_features = archive.get_ind_features if archive is not None else attrgetter("features")
70 embedding = lambda member: get_features(member).values
71 points = np.asarray([embedding(member) for member in pool], dtype=float)
72 if points.ndim != 2 or not points.shape[1] or not np.isfinite(points).all():
73 raise ValueError("Embeddings must be finite nonempty vectors of the same length.")
74 normalized = np.zeros(len(pool))
75 if quality_strength:
76 if quality is None:
77 get_fitness = archive.get_ind_fitness if archive is not None else attrgetter("fitness")
78 quality = lambda member: _scalar_quality(get_fitness(member))
79 values = np.asarray([quality(member) for member in pool], dtype=float)
80 if values.shape != (len(pool),) or not np.isfinite(values).all():
81 raise ValueError("Quality must return one finite scalar per member.")
82 # Rescale first so that the finite quality span cannot overflow.
83 scaled = values / max(float(np.abs(values).max()), np.finfo(float).tiny)
84 low, high = scaled.min(), scaled.max()
85 if low < high:
86 normalized = (scaled - high) / (high - low)
87 bonus = quality_strength * normalized
88 diagonal = np.full(len(pool), 1. + ridge)
89 eligible = np.ones(len(pool), dtype=bool)
90 factors = np.empty((size - 1, len(pool)))
91 indices = []
92 diversity = objective = 0.
93 for row in range(size):
94 residuals = np.maximum(diagonal, np.finfo(float).tiny)
95 scores = np.where(eligible, np.log(residuals) + bonus, -np.inf)
96 pick = int(np.argmax(scores))
97 indices.append(pick)
98 diversity += float(np.log(residuals[pick]))
99 objective += float(scores[pick])
100 eligible[pick] = False
101 if row == size - 1:
102 break
103 with np.errstate(over="ignore", under="ignore"):
104 # In the rare overflow cases halve the operands before subtraction.
105 delta = points - points[pick]
106 scale = np.isinf(delta)
107 offsets = delta / bandwidth
108 offsets[scale] = ((points / 2 - points[pick] / 2)[scale] / bandwidth) * 2
109 distances = np.hypot.reduce(offsets, axis=1)
110 similarities = np.exp(-.5 * distances**2)
111 projection = factors[:row, pick] @ factors[:row]
112 factors[row] = (similarities - projection) / np.sqrt(residuals[pick])
113 factors[row, ~eligible] = 0.
114 diagonal -= factors[row] ** 2
115 return DPPRepertoire(tuple(indices), tuple(pool[i] for i in indices), diversity, objective)
Selected archive members with comparable diversity and quality scores.