QDpy
Loading...
Searching...
No Matches
medoid_map_elites.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
6
7"""Illuminate descriptor spaces with actual reference objects as niche anchors."""
8
9from dataclasses import dataclass
10from math import isfinite
11
12import numpy as np
13
14from .modern import _positive_int
15
16__all__ = ["MedoidArchive", "MedoidElite", "MedoidMAPElites"]
17
18
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.")
23 return value
24
25
26def _pam(distances, count, max_swaps):
27 """Build medoids greedily, then exchange them using cached nearest costs."""
28 size = len(distances)
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]])
36
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)
42 best = None
43 best_delta = 0.
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)
52 if best is None:
53 break
54 remove, candidate = best
55 medoids[remove] = candidate
56 return tuple(medoids)
57
58
59
60@dataclass(frozen=True)
62 """An immutable record holding a candidate and its measurement."""
63
64 genome: object
65 fitness: float
66 descriptor: object
67
68
69
71 """A best-only archive over arbitrary immutable descriptor objects.
72
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.
77 """
78
79 def __init__(self, medoids, distance, *, maximize=True):
80 self._medoids = tuple(medoids)
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.")
88 self._distance = distance
89 self._sign = 1. if maximize else -1.
90 self._cells = {}
91
92
93 @classmethod
94 def fit(cls, descriptors, count, distance, *, maximize=True, max_swaps=20):
95 """Use deterministic PAM build and swap passes on the reference panel.
96
97 Fitting uses a dense pairwise matrix. Equivalent descriptors at
98 distance zero share the first representative.
99 """
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.")
105 unique = []
106 triangle = []
107 for descriptor in descriptors:
108 row = [_distance_value(distance, descriptor, other) for other in unique]
109 if 0. not in row:
110 unique.append(descriptor)
111 triangle.append(row)
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)
121
122 @property
123 def medoids(self):
124 """Return the fixed niche anchors in tie-breaking order."""
125 return self._medoids
126
127 @property
128 def cells(self):
129 """Return a snapshot of occupied niche indices and their measured elites."""
130 return dict(self._cells)
131
132 def __len__(self):
133 return len(self._cells)
134
135 def __iter__(self):
136 return iter(self._cells.values())
137
138
139 def index(self, descriptor):
140 """Return the integer niche index of a descriptor."""
141 return min(range(len(self._medoids)),
142 key=lambda i: _distance_value(self._distance, descriptor, self._medoids[i]))
143
144
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:
153 self._cells[cell] = MedoidElite(genome, score, descriptor)
154 return True
155 return False
156
157
158
160 """Search with a medoid archive and a scalar-fitness descriptor evaluator.
161
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.
166 """
167
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.")
171 self.archive = archive
172 self._propose, self._mutate = propose, mutate
173 self._rng = np.random.default_rng(seed)
174 self.nb_evaluations = 0
175
176
177 def optimise(self, evaluate, *, budget):
178 """Call evaluate(genome) for (scalar fitness, immutable descriptor) and return the archive."""
179 for _ in range(_positive_int(budget, "budget")):
180 if self.archive:
181 parents = tuple(self.archive)
182 parent = parents[self._rng.integers(len(parents))]
183 genome = self._mutate(parent.genome, self._rng)
184 else:
185 genome = self._propose(self._rng)
186 self.nb_evaluations += 1
187 fitness, descriptor = evaluate(genome)
188 self.archive.add(genome, fitness, descriptor)
189 return self.archive
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.