29 """Black-box MAP-Elites with Evolution Strategies.
31 Perturbation measurements guide an Adam update. Independently evaluate
32 the resulting center before offering it to the grid. Novelty uses the
33 descriptors of previously evaluated centers, including rejected ones.
35 :param archive: Best-only Grid or CVTGrid with one finite nonzero fitness weight.
36 :param x0: Initial parameter vector.
37 :param pairs: Number of antithetic Gaussian pairs per ES step.
38 :param block_steps: Number of ES steps before selecting a new elite.
39 :param mode: "exploit", "explore", or "explore-exploit" (alternating blocks).
40 :param evaluations_per_center: Number of rollouts averaged per center.
41 :param sigma: Gaussian standard deviation.
42 :param learning_rate: Adam step size.
43 :param l2: Parameter decay included in the ascent gradient.
44 :param novelty_neighbors: Number of nearest center descriptors for novelty.
45 :param ind_domain: Optional common lower and upper parameter bounds.
46 :param seed: Private random seed.
49 def __init__(self, archive, x0, *, pairs=16, block_steps=5, mode="explore-exploit",
50 evaluations_per_center=1, sigma=.05, learning_rate=.03, l2=.005,
51 novelty_neighbors=10, ind_domain=None, seed=0):
52 if (
not isinstance(archive, Grid)
or archive.max_items_per_bin != 1
or archive.parents
53 or archive.discard_random_on_bin_overload
or len(archive.fitness_domain
or ()) != 1
54 or not archive.fitness_weights
or len(archive.fitness_weights) != 1
55 or not isfinite(archive.fitness_weights[0])
or not archive.fitness_weights[0]):
56 raise ValueError(
"Supply a parentless best-only grid with one signed fitness objective.")
57 self.
_x0 = np.asarray(x0, dtype=float).copy()
58 if self.
_x0.ndim != 1
or not self.
_x0.size
or not np.isfinite(self.
_x0).all():
59 raise ValueError(
"x0 must be a nonempty finite vector.")
60 if not (0 < sigma < np.inf
and 0 < learning_rate < np.inf
and 0 <= l2 < np.inf):
61 raise ValueError(
"Use positive finite sigma and learning rate and a nonnegative penalty.")
62 if mode
not in (
"exploit",
"explore",
"explore-exploit"):
63 raise ValueError(
"Choose exploit, explore, or explore-exploit.")
65 self.
pairs, self.
block_steps = _positive_int(pairs,
"pairs"), _positive_int(block_steps,
"block_steps")
69 self.
_bounds =
None if ind_domain
is None else _bounds(ind_domain)
71 raise ValueError(
"x0 lies outside ind_domain.")
73 vector = np.asarray(elite, dtype=float)
74 if vector.shape != self.
_x0.shape
or not np.isfinite(vector).all()
or not np.array_equal(
76 raise ValueError(
"Warm-start elites must match x0 and its bounds.")
77 self.
_direction = np.sign(archive.fitness_weights[0])
78 self.
_rng = np.random.default_rng(seed)
79 self.
_history = [tuple(archive.get_ind_features(ind))
for ind
in archive]
81 self.
_step = self._completed = self._perturbations = self._center_calls = 0
85 """Return attempted perturbation and center evaluations combined."""
86 return self._perturbations + self._center_calls
90 """Return attempted center rollouts, including initialization."""
91 return self._center_calls
95 """Return the number of completed ES steps."""
96 return self._completed
98 def _bounded(self, point):
99 return point
if self.
_bounds is None else np.clip(point, *self.
_bounds)
101 def _measure(self, evaluate, points, executor, *, center):
102 genomes = [tuple(map(float, point))
for point
in points]
103 counter =
"_center_calls" if center
else "_perturbations"
105 for genome
in genomes:
107 setattr(self, counter, getattr(self, counter) + 1)
108 submitted.append(evaluate(genome))
110 submitted.append(executor.submit(evaluate, genome))
111 setattr(self, counter, getattr(self, counter) + 1)
112 results = submitted
if executor
is None else [future.result()
for future
in submitted]
114 for result
in results:
116 measured.append(
None)
118 fitness, features = result
119 values = np.asarray(fitness)
120 if values.shape
not in ((), (1,)):
121 raise ValueError(
"MEES requires one fitness objective.")
122 fitness, features = float(values.item()), tuple(map(float, features))
123 if (len(features) != len(self.
archive.features_domain)
or not np.isfinite(features).all()
124 or not isfinite(fitness)):
125 raise ValueError(
"Use finite measurements matching the archive or return None.")
126 measured.append((fitness, features))
129 def _record(self, evaluate, point, executor):
131 if any(row
is None for row
in results):
133 fitness, features = zip(*results)
134 value = sum(raw / len(fitness)
for raw
in fitness)
135 descriptors = tuple(np.sum(np.asarray(features) / len(features), axis=0))
138 and self.
archive.in_bounds(descriptors, self.
archive.features_domain)):
139 cell = self.
archive.index_grid(descriptors)
144 def _novelty(self, descriptors):
146 return np.zeros(len(descriptors))
147 distances = cdist(descriptors, self.
_history)
149 return np.partition(distances, count - 1, axis=1)[:, :count].mean(axis=1)
151 def _start_block(self):
153 self.
mode ==
"explore-exploit" and self._completed // self.
block_steps % 2 == 0)
158 descriptors = [tuple(self.
archive.get_ind_features(ind))
for ind
in elites]
159 novelty = self.
_novelty(descriptors)
160 top = np.argsort(-novelty, kind=
"stable")[:5]
161 weights = novelty[top]
162 choice = self.
_rng.choice(top, p=weights / weights.sum()
if np.any(weights)
else None)
163 self.
_center = np.asarray(elites[choice], dtype=float)
165 if self.
_rng.random() < .5:
166 elites = [row[1]
for row
in sorted(zip(self.
archive.recentness, elites),
167 key=
lambda row: -row[0])[:5]]
168 ranked = sorted(elites, key=
lambda ind: self.
_direction * self.
archive.get_ind_fitness(ind).values[0],
170 self.
_center = np.asarray(ranked[self.
_rng.integers(min(2, len(ranked)))], dtype=float)
175 def _update(self, evaluate, executor):
178 rows = self.
_measure(evaluate, points, executor, center=
False)
179 paired = [i
for i
in range(self.
pairs)
if rows[i]
is not None and rows[i + self.
pairs]
is not None]
182 feedback = [rows[i + offset]
for offset
in (0, self.
pairs)
for i
in paired]
183 quality, descriptors = zip(*feedback)
185 grad = _rank_gradient(noise[paired], scores, self.
sigma) - self.
l2 * self.
_center
195 def run(self, evaluate, budget, *, executor=None):
196 """Return the result archive after using at most budget evaluator calls.
198 Return (scalar fitness, descriptors) or None for a failed rollout.
199 A caller-owned executor must support submit and Future.result.
200 Feedback order follows submission order.
202 stop = self.
evaluations + _positive_int(budget,
"budget")
210 self.
_update(evaluate, executor)