QDpy
Loading...
Searching...
No Matches
me_es.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Evaluate perturbation batches and separately admit measured ES centers."""
6
7from math import isfinite
8
9import numpy as np
10from scipy.spatial.distance import cdist
11from scipy.stats import rankdata
12
13from qdpy.containers import Grid
14from qdpy.phenotype import Features, Fitness, Individual
15from .modern import _bounds, _positive_int
16
17__all__ = ["MEES"]
18
19
20def _rank_gradient(noise, scores, sigma):
21 """Compute the ascent direction from paired scores and centered ranks."""
22 ranks = (rankdata(scores, method="average") - 1) / (len(scores) - 1) - .5
23 first, second = np.split(ranks, 2)
24 return (first - second) @ noise / (len(scores) * sigma)
25
26
27
28class MEES:
29 """Black-box MAP-Elites with Evolution Strategies.
30
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.
34
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.
47 """
48
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.")
64 self.archive, self.mode = archive, mode
65 self.pairs, self.block_steps = _positive_int(pairs, "pairs"), _positive_int(block_steps, "block_steps")
66 self.evaluations_per_center = _positive_int(evaluations_per_center, "evaluations_per_center")
67 self.novelty_neighbors = _positive_int(novelty_neighbors, "novelty_neighbors")
68 self.sigma, self.learning_rate, self.l2 = sigma, learning_rate, l2
69 self._bounds = None if ind_domain is None else _bounds(ind_domain)
70 if not np.array_equal(self._bounded(self._x0), self._x0):
71 raise ValueError("x0 lies outside ind_domain.")
72 for elite in archive:
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(
75 self._bounded(vector), vector):
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]
80 self._center = None
81 self._step = self._completed = self._perturbations = self._center_calls = 0
82
83 @property
84 def evaluations(self):
85 """Return attempted perturbation and center evaluations combined."""
86 return self._perturbations + self._center_calls
87
88 @property
90 """Return attempted center rollouts, including initialization."""
91 return self._center_calls
92
93 @property
94 def updates(self):
95 """Return the number of completed ES steps."""
96 return self._completed
97
98 def _bounded(self, point):
99 return point if self._bounds is None else np.clip(point, *self._bounds)
100
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"
104 submitted = []
105 for genome in genomes:
106 if executor is None:
107 setattr(self, counter, getattr(self, counter) + 1)
108 submitted.append(evaluate(genome))
109 else:
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]
113 measured = []
114 for result in results:
115 if result is None:
116 measured.append(None)
117 continue
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))
127 return measured
128
129 def _record(self, evaluate, point, executor):
130 results = self._measure(evaluate, [point] * self.evaluations_per_center, executor, center=True)
131 if any(row is None for row in results):
132 return
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))
136 self._history.append(descriptors)
137 if (self.archive.in_bounds((value,), self.archive.fitness_domain)
138 and self.archive.in_bounds(descriptors, self.archive.features_domain)):
139 cell = self.archive.index_grid(descriptors)
140 if self.archive.free > 0 or self.archive.solutions[cell]:
141 self.archive.add(Individual(point.tolist(), fitness=Fitness((value,), weights=self.archive.fitness_weights),
142 features=Features(descriptors)))
143
144 def _novelty(self, descriptors):
145 if not self._history:
146 return np.zeros(len(descriptors))
147 distances = cdist(descriptors, self._history)
148 count = min(self.novelty_neighbors, len(self._history))
149 return np.partition(distances, count - 1, axis=1)[:, :count].mean(axis=1)
150
151 def _start_block(self):
152 self._exploring = self.mode == "explore" or (
153 self.mode == "explore-exploit" and self._completed // self.block_steps % 2 == 0)
154 elites = list(self.archive)
155 if not elites:
156 self._center = self._x0.copy() if self._center is None else self._center
157 elif self._exploring:
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)
164 else:
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],
169 reverse=True)
170 self._center = np.asarray(ranked[self._rng.integers(min(2, len(ranked)))], dtype=float)
171 self._first = np.zeros_like(self._center)
172 self._second = np.zeros_like(self._center)
173 self._step = 0
174
175 def _update(self, evaluate, executor):
176 noise = self._rng.normal(size=(self.pairs, len(self._center)))
177 points = self._bounded(self._center + self.sigma * np.concatenate((noise, -noise)))
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]
180 self._step += 1
181 if paired:
182 feedback = [rows[i + offset] for offset in (0, self.pairs) for i in paired]
183 quality, descriptors = zip(*feedback)
184 scores = self._novelty(descriptors) if self._exploring else self._direction * np.array(quality)
185 grad = _rank_gradient(noise[paired], scores, self.sigma) - self.l2 * self._center
186 self._first += .1 * (grad - self._first)
187 self._second += .001 * (grad ** 2 - self._second)
188 first = self._first / (1 - .9 ** self._step)
189 second = self._second / (1 - .999 ** self._step)
190 self._center = self._bounded(self._center + self.learning_rate * first / (np.sqrt(second) + 1e-8))
191 self._record(evaluate, self._center, executor)
192 self._completed += 1
193
194
195 def run(self, evaluate, budget, *, executor=None):
196 """Return the result archive after using at most budget evaluator calls.
197
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.
201 """
202 stop = self.evaluations + _positive_int(budget, "budget")
203 if self._center is None and stop - self.evaluations >= self.evaluations_per_center:
204 self._center = self._x0.copy()
205 self._record(evaluate, self._center, executor)
206 cost = 2 * self.pairs + self.evaluations_per_center
207 while self.evaluations + cost <= stop:
208 if self._completed % self.block_steps == 0:
209 self._start_block()
210 self._update(evaluate, executor)
211 return self.archive
Alternate ES quality and novelty updates from an archive of measured centers.
Definition me_es.py:28
_measure(self, evaluate, points, executor, *, center)
Definition me_es.py:101
_bounded(self, point)
Definition me_es.py:98
_record(self, evaluate, point, executor)
Definition me_es.py:129
run(self, evaluate, budget, *, executor=None)
Spend an additional budget on whole ES and center evaluation batches.
Definition me_es.py:195
_novelty(self, descriptors)
Definition me_es.py:144
_update(self, evaluate, executor)
Definition me_es.py:175
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405