QDpy
Loading...
Searching...
No Matches
magnitude.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Search structured descriptor spaces using only pairwise dissimilarities."""
7
8from itertools import islice
9from math import isfinite, log
10
11import numpy as np
12from scipy.linalg import cho_factor, cho_solve
13
14from .medoid_map_elites import MedoidElite, _distance_value
15from .modern import _positive_int
16
17__all__ = ["MagnitudeArchive", "MagnitudeGoExplore", "magnitude_weights"]
18
19
20def _choose_scale(distances):
21 """Find a scale where each kernel row has off-diagonal sum at most 0.95."""
22 count = len(distances)
23 if count == 1:
24 return 1., 1.
25 unit = distances[distances > 0].min()
26 with np.errstate(over="ignore"):
27 ratios = distances / unit
28 low, high = 0., log((count - 1) / .95)
29 for _ in range(24):
30 mid = (low + high) / 2
31 if np.exp(-mid * ratios).sum(axis=1).max() <= 1.95:
32 high = mid
33 else:
34 low = mid
35 return unit, high
36
37
38def _kernel_weights(distances, unit, scale):
39 with np.errstate(over="ignore"):
40 kernel = np.exp(-(distances / unit) * scale)
41 weights = cho_solve(cho_factor(kernel), np.ones(len(distances)))
42 if weights.min() < -1e-10 or not np.isfinite(weights).all():
43 raise ValueError("Use a scale with nonnegative finite magnitude weights.")
44 return np.maximum(weights, 0.)
45
46
47
48def magnitude_weights(distances, *, scale=None):
49 """Return the unnormalized weights of exp(-scale * distances).
50
51 :param distances: Nonempty square symmetric array with a zero diagonal
52 and finite positive off-diagonal values.
53 :param scale: Positive kernel scale. By default choose a scale with
54 strict diagonal dominance and nonnegative weights.
55 :raises ValueError: If the matrix is invalid or the requested kernel
56 lacks a positive-definite solve with nonnegative weights.
57 """
58 distances = np.asarray(distances, dtype=float)
59 if (distances.ndim != 2 or not len(distances) or distances.shape[0] != distances.shape[1]
60 or not np.isfinite(distances).all() or (distances < 0.).any()
61 or not np.array_equal(distances, distances.T)
62 or np.count_nonzero(distances) != len(distances) * (len(distances) - 1)):
63 raise ValueError("Use finite symmetric distances, positive away from a zero diagonal.")
64 if np.any(distances.diagonal() != 0.):
65 raise ValueError("The distance diagonal must be zero.")
66 if scale is None:
67 unit, scale = _choose_scale(distances)
68 elif not isfinite(scale) or scale <= 0.:
69 raise ValueError("scale must be finite and positive.")
70 else:
71 unit = 1.
72 try:
73 return _kernel_weights(distances, unit, scale)
74 except np.linalg.LinAlgError as error:
75 raise ValueError("The magnitude kernel must be positive definite.") from error
76
77
78def _distance_matrix(points, distance):
79 matrix = np.zeros((len(points), len(points)))
80 for i, point in enumerate(points):
81 row = [_distance_value(distance, point, previous) for previous in points[:i]]
82 matrix[i, :i] = matrix[:i, i] = row
83 return matrix
84
85
86
88 """Keep one elite per occupied landmark signature and cache elite distances.
89
90 :param landmarks: Ordered distinct immutable and hashable descriptors.
91 :param distance: Symmetric, finite dissimilarity, zero for equal points
92 and strictly positive for distinct points.
93 :param rank: Number of closest landmarks in each signature. Equal
94 distances are ordered by the supplied landmark order.
95 :param capacity: Maximum number of occupied signatures. If a new niche
96 would exceed it, evict the least magnitude-weighted candidate in
97 the expanded set, breaking ties by fitness and admission order.
98 :param maximize: Compare larger scalar fitness values as better.
99 """
100
101 def __init__(self, landmarks, distance, *, rank=2, capacity=256, maximize=True):
102 self._landmarks = tuple(landmarks)
103 self._rank = _positive_int(rank, "rank")
104 self._capacity = _positive_int(capacity, "capacity")
105 if (len(set(self._landmarks)) != len(self._landmarks)
106 or self._rank > len(self._landmarks) or not callable(distance)):
107 raise ValueError("Supply distinct landmarks and one callable distance with enough anchors for rank.")
108 self._distance = distance
109 self._direction = 1. if maximize else -1.
110 self._cells = {}
111 self._distances = np.zeros((0, 0))
112 self._weights = np.empty(0)
113
114 @classmethod
115 def from_reference(cls, reference, distance, *, count, **kwargs):
116 """Fit landmarks by trying magnitude-increasing swaps at a fixed kernel scale.
117
118 Use the first count distinct descriptors as the initial set, then
119 try each remaining descriptor in place of the least-weighted one.
120 The ordered reference panel is consumed once and needs no fitness.
121 """
122 count = _positive_int(count, "count")
123 points = iter(dict.fromkeys(reference))
124 landmarks = tuple(islice(points, count))
125 if len(landmarks) != count:
126 raise ValueError("The reference panel needs at least count distinct descriptors.")
127 matrix = _distance_matrix(landmarks, distance)
128 if np.count_nonzero(matrix) != count * (count - 1):
129 raise ValueError("Distinct landmarks need strictly positive distances.")
130 unit, scale = _choose_scale(matrix)
131 weights = _kernel_weights(matrix, unit, scale)
132 landmarks = list(landmarks)
133 for point in points:
134 slot = int(np.argmin(weights))
135 row = np.array([0. if i == slot else _distance_value(distance, point, anchor)
136 for i, anchor in enumerate(landmarks)])
137 if np.count_nonzero(row) != count - 1:
138 raise ValueError("Distinct landmarks need strictly positive distances.")
139 trial = matrix.copy()
140 trial[slot, :] = trial[:, slot] = row
141 try:
142 trial_weights = _kernel_weights(trial, unit, scale)
143 except (np.linalg.LinAlgError, ValueError):
144 continue
145 if trial_weights.sum() > weights.sum() + 1e-12:
146 landmarks[slot] = point
147 matrix, weights = trial, trial_weights
148 return cls(landmarks, distance, **kwargs)
149
150 @property
151 def landmarks(self):
152 """Return the fixed landmarks in tie-breaking order."""
153 return self._landmarks
154
155 @property
156 def cells(self):
157 """Return a copy of the occupied signatures and their measured elites."""
158 return dict(self._cells)
159
160 @property
161 def weights(self):
162 """Return a copy of the unnormalized magnitude weights by signature."""
163 return dict(zip(self._cells, map(float, self._weights)))
164
165 def __len__(self):
166 return len(self._cells)
167
168 def __iter__(self):
169 return iter(self._cells.values())
170
171
172 def index(self, descriptor):
173 """Return the ordered indices of its rank nearest landmarks."""
174 ordered = sorted(range(len(self._landmarks)),
175 key=lambda i: _distance_value(self._distance, descriptor, self._landmarks[i]))
176 return tuple(ordered[:self._rank])
177
178
179 def add(self, genome, fitness, descriptor):
180 """Return whether the candidate filled or improved its niche."""
181 fitness = float(fitness)
182 if not isfinite(fitness):
183 raise ValueError("fitness must be finite.")
184 cell = self.index(descriptor)
185 incumbent = self._cells.get(cell)
186 if incumbent is not None and self._direction * fitness <= self._direction * incumbent.fitness:
187 return False
188 kept = [i for i, key in enumerate(self._cells) if key != cell]
189 cells = dict(self._cells)
190 cells.pop(cell, None)
191 matrix = np.zeros((len(kept) + 1, len(kept) + 1))
192 matrix[:-1, :-1] = self._distances[np.ix_(kept, kept)]
193 row = [_distance_value(self._distance, descriptor, elite.descriptor) for elite in cells.values()]
194 matrix[:-1, -1] = matrix[-1, :-1] = row
195 cells[cell] = MedoidElite(genome, fitness, descriptor)
196 weights = magnitude_weights(matrix)
197 if len(cells) > self._capacity:
198 entries = tuple(cells.items())
199 candidates = np.flatnonzero(weights <= weights.min() + 1e-12)
200 slot = min(candidates, key=lambda i: (self._direction * entries[i][1].fitness, -i))
201 removed = entries[slot][0]
202 if removed == cell:
203 return False
204 del cells[removed]
205 mask = np.arange(len(entries)) != slot
206 matrix = matrix[np.ix_(mask, mask)]
207 weights = magnitude_weights(matrix)
208 self._cells, self._distances, self._weights = cells, matrix, weights
209 return True
210
211
212
214 """Use Huntsman's landmark and magnitude selection with direct evaluation.
215
216 :param archive: MagnitudeArchive to fill.
217 :param propose: Callback (rng) returning a new genome.
218 :param mutate: Callback (parent_genome, rng) returning an offspring.
219 :param selection: Use "magnitude" or the "uniform" parent control.
220 :param quality_weight: Weight of normalized fitness in parent logits.
221 :param random_fraction: Fraction of proposals sampled without a parent.
222 :param seed: Private seed for proposals and parent selection.
223 """
224
225 def __init__(self, archive, *, propose, mutate, selection="magnitude",
226 quality_weight=1., random_fraction=.1, seed=0):
227 if not isinstance(archive, MagnitudeArchive) or not callable(propose) or not callable(mutate):
228 raise TypeError("Supply a MagnitudeArchive and two callable search operators.")
229 if (selection not in ("magnitude", "uniform") or not isfinite(quality_weight)
230 or quality_weight < 0. or not 0. <= random_fraction <= 1.):
231 raise ValueError("Use a supported selection, finite nonnegative quality weight and valid fraction.")
232 self.archive = archive
233 self._propose, self._mutate = propose, mutate
234 self._selection = selection
235 self._quality_weight = quality_weight
236 self._random_fraction = random_fraction
237 self._rng = np.random.default_rng(seed)
238 self.nb_evaluations = 0
239
240 def _parent(self):
241 elites = tuple(self.archive)
242 if self._selection == "uniform":
243 return elites[int(self._rng.integers(len(elites)))]
244 quality = self.archive._direction * np.array([elite.fitness for elite in elites])
245 quality /= max(1., np.abs(quality).max())
246 span = np.ptp(quality)
247 boost = (quality - quality.max()) / span if span else quality * 0.
248 probability = self.archive._weights * np.exp(self._quality_weight * boost)
249 return elites[int(self._rng.choice(len(elites), p=probability / probability.sum()))]
250
251
252 def optimise(self, evaluate, *, budget):
253 """Call evaluate(genome) for (scalar fitness, descriptor) and return the archive."""
254 for _ in range(_positive_int(budget, "budget")):
255 if self.archive and self._rng.random() >= self._random_fraction:
256 genome = self._mutate(self._parent().genome, self._rng)
257 else:
258 genome = self._propose(self._rng)
259 self.nb_evaluations += 1
260 fitness, descriptor = evaluate(genome)
261 self.archive.add(genome, fitness, descriptor)
262 return self.archive
Archive best measured candidates by their ordered closest landmarks.
Definition magnitude.py:87
add(self, genome, fitness, descriptor)
Admit a measured elite and update cached weights.
Definition magnitude.py:179
index(self, descriptor)
Map a descriptor to a tuple of landmark indices.
Definition magnitude.py:172
from_reference(cls, reference, distance, *, count, **kwargs)
Definition magnitude.py:115
Revisit diverse elites and explore with a caller-defined mutation.
Definition magnitude.py:213
optimise(self, evaluate, *, budget)
Spend an additional budget of true objective evaluations.
Definition magnitude.py:252
Store a measured genome, descriptor, and scalar fitness.