6"""Search structured descriptor spaces using only pairwise dissimilarities."""
8from itertools
import islice
9from math
import isfinite, log
12from scipy.linalg
import cho_factor, cho_solve
14from .medoid_map_elites
import MedoidElite, _distance_value
15from .modern
import _positive_int
17__all__ = [
"MagnitudeArchive",
"MagnitudeGoExplore",
"magnitude_weights"]
20def _choose_scale(distances):
21 """Find a scale where each kernel row has off-diagonal sum at most 0.95."""
22 count = len(distances)
25 unit = distances[distances > 0].min()
26 with np.errstate(over=
"ignore"):
27 ratios = distances / unit
28 low, high = 0., log((count - 1) / .95)
30 mid = (low + high) / 2
31 if np.exp(-mid * ratios).sum(axis=1).max() <= 1.95:
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.)
48def magnitude_weights(distances, *, scale=None):
49 """Return the unnormalized weights of exp(-scale * distances).
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.
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.")
67 unit, scale = _choose_scale(distances)
68 elif not isfinite(scale)
or scale <= 0.:
69 raise ValueError(
"scale must be finite and positive.")
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
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
88 """Keep one elite per occupied landmark signature and cache elite distances.
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.
101 def __init__(self, landmarks, distance, *, rank=2, capacity=256, maximize=True):
103 self.
_rank = _positive_int(rank,
"rank")
104 self.
_capacity = _positive_int(capacity,
"capacity")
107 raise ValueError(
"Supply distinct landmarks and one callable distance with enough anchors for rank.")
116 """Fit landmarks by trying magnitude-increasing swaps at a fixed kernel scale.
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.
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)
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
142 trial_weights = _kernel_weights(trial, unit, scale)
143 except (np.linalg.LinAlgError, ValueError):
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)
152 """Return the fixed landmarks in tie-breaking order."""
157 """Return a copy of the occupied signatures and their measured elites."""
162 """Return a copy of the unnormalized magnitude weights by signature."""
169 return iter(self.
_cells.values())
173 """Return the ordered indices of its rank nearest landmarks."""
176 return tuple(ordered[:self.
_rank])
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)
188 kept = [i
for i, key
in enumerate(self.
_cells)
if key != cell]
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)
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]
205 mask = np.arange(len(entries)) != slot
206 matrix = matrix[np.ix_(mask, mask)]
207 weights = magnitude_weights(matrix)
214 """Use Huntsman's landmark and magnitude selection with direct evaluation.
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.
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.")
237 self.
_rng = np.random.default_rng(seed)
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.
249 return elites[int(self.
_rng.choice(len(elites), p=probability / probability.sum()))]
253 """Call evaluate(genome) for (scalar fitness, descriptor) and return the archive."""
254 for _
in range(_positive_int(budget,
"budget")):
260 fitness, descriptor = evaluate(genome)
261 self.
archive.add(genome, fitness, descriptor)
Archive best measured candidates by their ordered closest landmarks.
add(self, genome, fitness, descriptor)
Admit a measured elite and update cached weights.
index(self, descriptor)
Map a descriptor to a tuple of landmark indices.
from_reference(cls, reference, distance, *, count, **kwargs)
Revisit diverse elites and explore with a caller-defined mutation.
optimise(self, evaluate, *, budget)
Spend an additional budget of true objective evaluations.
Store a measured genome, descriptor, and scalar fitness.