7"""Illuminate descriptor spaces with actual reference objects as niche anchors."""
9from dataclasses
import dataclass
10from math
import isfinite
14from .modern
import _positive_int
16__all__ = [
"MedoidArchive",
"MedoidElite",
"MedoidMAPElites"]
19def _distance_value(distance, first, second):
20 value = float(distance(first, second))
21 if not isfinite(value)
or value < 0.:
22 raise ValueError(
"distance must return a finite nonnegative value.")
26def _pam(distances, count, max_swaps):
27 """Build medoids greedily, then exchange them using cached nearest costs."""
29 medoids = [int(np.argmin(distances.sum(axis=0)))]
30 nearest = distances[:, medoids[0]]
31 while len(medoids) < count:
32 costs = np.minimum(nearest[:,
None], distances).sum(axis=0)
33 costs[medoids] = np.inf
34 medoids.append(int(np.argmin(costs)))
35 nearest = np.minimum(nearest, distances[:, medoids[-1]])
37 for _
in range(max_swaps):
38 current = distances[:, medoids]
39 owner = np.argmin(current, axis=1)
40 nearest = np.min(current, axis=1)
41 second = np.partition(current, 1, axis=1)[:, 1]
if count > 1
else np.full(size, np.inf)
44 for candidate
in sorted(set(range(size)).difference(medoids)):
45 costs = distances[:, candidate]
46 base = np.minimum(costs, nearest)
47 penalty = np.minimum(costs, second) - base
48 deltas = (base - nearest).sum() + np.bincount(owner, weights=penalty, minlength=count)
49 remove = int(np.argmin(deltas))
50 if deltas[remove] < best_delta - 1e-12:
51 best_delta, best = deltas[remove], (remove, candidate)
54 remove, candidate = best
55 medoids[remove] = candidate
60@dataclass(frozen=True)
62 """An immutable record holding a candidate and its measurement."""
71 """A best-only archive over arbitrary immutable descriptor objects.
73 :param medoids: Distinct ordered representatives in the descriptor space.
74 :param distance: Callable symmetric dissimilarity. It must be finite and
75 nonnegative, with zero for identical objects.
76 :param maximize: Whether higher fitness is preferred.
79 def __init__(self, medoids, distance, *, maximize=True):
81 if not self.
_medoids or not callable(distance):
82 raise ValueError(
"Supply at least one medoid and a callable distance.")
83 for i, first
in enumerate(self.
_medoids):
84 if _distance_value(distance, first, first) != 0.:
85 raise ValueError(
"A medoid must be at zero distance from itself.")
86 if any(_distance_value(distance, first, other) == 0.
for other
in self.
_medoids[:i]):
87 raise ValueError(
"Medoids must be distinct under the chosen distance.")
89 self.
_sign = 1.
if maximize
else -1.
94 def fit(cls, descriptors, count, distance, *, maximize=True, max_swaps=20):
95 """Use deterministic PAM build and swap passes on the reference panel.
97 Fitting uses a dense pairwise matrix. Equivalent descriptors at
98 distance zero share the first representative.
100 count = _positive_int(count,
"count")
101 if not callable(distance):
102 raise TypeError(
"distance must be callable.")
103 if isinstance(max_swaps, bool)
or not isinstance(max_swaps, (int, np.integer))
or max_swaps < 0:
104 raise ValueError(
"max_swaps must be a nonnegative integer.")
107 for descriptor
in descriptors:
108 row = [_distance_value(distance, descriptor, other)
for other
in unique]
110 unique.append(descriptor)
112 if count > len(unique):
113 raise ValueError(
"The reference panel has fewer distinct descriptors than requested niches.")
114 matrix = np.zeros((len(unique), len(unique)))
115 for index, row
in enumerate(triangle):
116 matrix[index, :index] = row
117 matrix[:index, index] = row
118 matrix /= matrix.max()
or 1.
119 selected = _pam(matrix, count, max_swaps)
120 return cls((unique[index]
for index
in selected), distance, maximize=maximize)
124 """Return the fixed niche anchors in tie-breaking order."""
129 """Return a snapshot of occupied niche indices and their measured elites."""
136 return iter(self.
_cells.values())
140 """Return the integer niche index of a descriptor."""
141 return min(range(len(self.
_medoids)),
145 def add(self, genome, fitness, descriptor):
146 """Return whether the candidate filled its niche or strictly improved its elite."""
147 score = float(fitness)
148 if not isfinite(score):
149 raise ValueError(
"fitness must be finite.")
150 cell = self.
index(descriptor)
151 incumbent = self.
_cells.get(cell)
152 if incumbent
is None or self.
_sign * score > self.
_sign * incumbent.fitness:
160 """Search with a medoid archive and a scalar-fitness descriptor evaluator.
162 :param archive: A MedoidArchive, optionally seeded with measured elites.
163 :param propose: Callback (rng) producing a fresh immutable genome.
164 :param mutate: Callback (parent_genome, rng) producing an immutable offspring.
165 :param seed: Independent proposal and parent selection seed.
168 def __init__(self, archive, *, propose, mutate, seed=0):
169 if not isinstance(archive, MedoidArchive)
or not callable(propose)
or not callable(mutate):
170 raise TypeError(
"Supply a MedoidArchive and callable proposal and mutation operators.")
173 self.
_rng = np.random.default_rng(seed)
178 """Call evaluate(genome) for (scalar fitness, immutable descriptor) and return the archive."""
179 for _
in range(_positive_int(budget,
"budget")):
182 parent = parents[self.
_rng.integers(len(parents))]
187 fitness, descriptor = evaluate(genome)
188 self.
archive.add(genome, fitness, descriptor)
Assign descriptors to the nearest fixed medoid and keep the best candidate there.
add(self, genome, fitness, descriptor)
Try to admit a measured candidate at its descriptor's niche.
fit(cls, descriptors, count, distance, *, maximize=True, max_swaps=20)
Fit the archive's fixed medoids on reference descriptors.
index(self, descriptor)
Resolve the nearest medoid, with ties going to the first anchor.
Store a measured genome, descriptor, and scalar fitness.
Draw parents from occupied medoid niches and mutate with caller-defined operators.
optimise(self, evaluate, *, budget)
Run an additional budget of candidate evaluations.