QDpy
Loading...
Searching...
No Matches
cmame.py
Go to the documentation of this file.
1# This file is part of qdpy.
2#
3# qdpy is free software: you can redistribute it and/or modify
4# it under the terms of the GNU Lesser General Public License as
5# published by the Free Software Foundation, either version 3 of
6# the License, or (at your option) any later version.
7#
8# qdpy is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11# GNU Lesser General Public License for more details.
12#
13# You should have received a copy of the GNU Lesser General Public
14# License along with qdpy. If not, see <http://www.gnu.org/licenses/>.
15
16
17
19
20"""This file contains the CMA-ME emitters, as defined in paper "Covariance Matrix Adaptation for the Rapid Illumination of Behavior Space"(https://arxiv.org/abs/1912.02400). Additional algorithms are also included, notably the ME-MAP-Elites algorithm (Multi-Emitter MAP-Elites), as presented in the paper "Multi-Emitter MAP-Elites: Improving quality, diversity and convergence speed with heterogeneous sets of emitters". All emitters are implemented as subclasses of the CMA-ES class, so the library "cma" needs to be installed to use them. """
21
22__all__ = ["CMAMEOptimizingEmitter", "CMAMERandomDirectionEmitter", "CMAMEImprovementEmitter", "MEMAPElitesUCB1"]
23
24from typing import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, Mapping, MutableMapping, overload
25import numpy as np
26import random
27
28
29from .base import *
30from .evolution import *
31from qdpy.utils import *
32from qdpy.phenotype import *
33from qdpy.base import *
34from qdpy.containers import *
35from qdpy import tools
36
37
38try:
39 import cma
40except ImportError:
41 pass
42
43
44
45@registry.register
47 """Run single-objective CMA-ES and restart from an archive entry.
48
49 Use the ``cma`` extra. When the backend reaches a stopping
50 condition, select a centre uniformly from the retained genomes.
51 An empty archive uses the zero genome. The objective and loss
52 conventions are the same as those of CMAES.
53 """
54
55# def __init__(self, container: Container, budget: int,
56# dimension: int, **kwargs):
57# super().__init__(container, budget, dimension=dimension, **kwargs)
58
59 def reinit(self) -> None:
60 super().reinit()
61 self.restart()
62
63 def restart(self):
64 """Replace the pycma strategy and clear its buffered feedback."""
65 if len(self.container):
66 init_ind = random.choice(self.container)
67 else:
68 init_ind = [0.] * self.dimension
69 self.es = cma.CMAEvolutionStrategy(init_ind, self.sigma0, self._opts)
70 self._pop_inds.clear()
71 self._pop_fitness_vals.clear()
72
73 def _stop(self) -> bool:
74 term_cond = self.es.stop(check=False)
75 #if len(term_cond) > 0:
76 # print(f"RESTART!!!: {term_cond}")
77 return len(term_cond) > 0
78
79 def _internal_ask(self, base_ind: IndividualLike) -> IndividualLike:
80 if self._stop():
81 self.restart()
82 return super()._internal_ask(base_ind)
83
84
85@registry.register
87 """Use a projection of behaviour descriptors as scalar CMA feedback.
88
89 A restart samples a direction using the descriptor domain. The
90 feedback population is formed from locally admitted candidates and
91 passed to pycma after projection. This emitter uses descriptor
92 values on the individuals and supports a multiobjective archive.
93 """
94 _requires_single_objective = False
95
96 def restart(self):
97 super().restart()
98 features_domain = np.array(self.container.features_domain)
99 self._direction = np.random.normal(0., 1., features_domain.shape[0])
100 self._direction = features_domain[:,0] + self._direction * (features_domain[:,1] - features_domain[:,0])
101 self._features_mean = np.zeros(features_domain.shape[0])
102
103 def _internal_tell(self, individual: IndividualLike, added_to_container: bool, xattr: Mapping[str, Any] = {}) -> None:
104 if self.ignore_if_not_added_to_container and not added_to_container:
105 return
106
107 self._features_mean += np.array(individual.features)
108 if added_to_container:
109 self._pop_inds += [individual]
110
111 if len(self._pop_inds) >= self.es.popsize:
112 self._features_mean /= self.es.popsize
113 _pop_delta = []
114 for ind in self._pop_inds:
115 dv = ind.features - self._features_mean
116 _pop_delta.append(self._direction.dot(dv))
117 try:
118 self.es.tell(self._pop_inds, _pop_delta)
119 except RuntimeError:
120 pass
121 else:
122 self._pop_inds.clear()
123 self._pop_fitness_vals.clear()
124
125
126@registry.register
128 """Adapt search using cell coverage and signed fitness gains.
129
130 Read the previous cell representative before insertion. A candidate
131 that fills an empty cell receives priority. For a filled cell, use
132 the difference between candidate and previous weighted objectives.
133 Sum weighted objectives into scalar feedback for pycma.
134 """
135 _requires_single_objective = False
136
137 _novel_pop_inds: MutableSequence[IndividualLike]
138 _novel_pop_fitness_vals: MutableSequence[Any]
139
140 def restart(self):
141 super().restart()
142 self._novel_pop_inds = []
144
145
151 def _tell_before_container_update(self, individual: IndividualLike) -> Tuple[MutableMapping[str, Any], bool]:
152 novel = False
153 previous_fitness = None
154 if hasattr(self.container, "index_grid") and hasattr(self.container, "quality"):
155 try:
156 index = self.container.index_grid(individual)
157 previous_fitness = self.container.quality[index]
158 except (IndexError, KeyError):
159 pass
160 else:
161 novel = previous_fitness is None
162 delta = sum(self._weighted_fitness(self.container.get_ind_fitness(individual)))
163 if previous_fitness is not None:
164 delta -= sum(self._weighted_fitness(previous_fitness))
165 return {"novel": novel, "delta": delta}, True
166
167 def _internal_tell(self, individual: IndividualLike, added_to_container: bool, xattr: Mapping[str, Any] = {}) -> None:
168 if self.ignore_if_not_added_to_container and not added_to_container:
169 return
170 novel = xattr.get("novel", False)
171 delta = xattr.get("delta", 0.)
172
173 if added_to_container:
174 if novel:
175 self._novel_pop_inds += [individual]
176 self._novel_pop_fitness_vals += [-1. * delta]
177 else:
178 self._pop_inds += [individual]
179 self._pop_fitness_vals += [-1. * delta]
180
181 if len(self._pop_inds) + len(self._novel_pop_inds) >= self.es.popsize:
182 tot_pop = []
183 tot_pop_fitness_vals = []
184
185 # Sort individuals
186 sorted_pop_inds = [self._pop_inds[k] for k in argsort(self._pop_fitness_vals)]
187 #sorted_pop_fitness_vals = sorted(self._pop_fitness_vals)
188 sorted_novel_pop_inds = [self._novel_pop_inds[k] for k in argsort(self._novel_pop_fitness_vals)]
189 #sorted_novel_pop_fitness_vals = sorted(self._novel_pop_fitness_vals)
190 for i, ind in enumerate(sorted_novel_pop_inds):
191 tot_pop.append(ind)
192 tot_pop_fitness_vals.append(i)
193 for i, ind in enumerate(sorted_pop_inds):
194 tot_pop.append(ind)
195 tot_pop_fitness_vals.append(len(sorted_novel_pop_inds) + i)
196
197 try:
198 self.es.tell(tot_pop, tot_pop_fitness_vals)
199 except RuntimeError:
200 pass
201 else:
202 self._pop_inds.clear()
203 self._pop_fitness_vals.clear()
204 self._novel_pop_inds.clear()
205 self._novel_pop_fitness_vals.clear()
206
207
208@registry.register
210 """Choose active child emitters with an upper confidence bound.
211
212 The reward estimate combines each emitter's fraction of evaluations
213 that updated the archive with an exploration term based on evaluation
214 counts. Untried emitters receive ``initial_expected_rwds``.
215
216 :param algorithms: Available child emitters.
217 :param zeta: Coefficient of the UCB1 exploration term.
218 :param nb_active_emitters: Number of emitters retained per selection.
219 :param initial_expected_rwds: Reward estimate for a child with no evaluations.
220 :param shuffle_emitters: Shuffle the candidate order before ranking.
221 """
222 zeta: float
223 nb_active_emitters: int
224 _active_emitters_idx: Sequence[int]
225 current_active_idx: int
226 initial_expected_rwds: float
227 shuffle_emitters: bool
228
229 def __init__(self, algorithms: Any, zeta: float = 0.0005, nb_active_emitters: int = 1, initial_expected_rwds: float = 1.,
230 shuffle_emitters: bool = True, **kwargs):
231 self.zeta = zeta
232 self.nb_active_emitters = nb_active_emitters
233 self.initial_expected_rwds = initial_expected_rwds
234 self.shuffle_emitters = shuffle_emitters
235 super().__init__(algorithms, **kwargs)
236
237 def reinit(self) -> None:
238 super().reinit()
240 self.current_active_idx = 0
241
242
246 def _up_active_emitters(self) -> None:
247 """Update the list of active emitters."""
248 #expected_rwds = [
249 # self.initial_expected_rwds if alg.nb_evaluations == 0 else
250 # float(alg.nb_updated) / float(alg.nb_evaluations) + self.zeta * math.sqrt(math.log(self.nb_evaluations) / float(alg.nb_evaluations))
251 # for alg in self.algorithms]
252 #self._active_emitters_idx = argsort(expected_rwds, reverse=True)[:self.nb_active_emitters]
253
254 algos_idx = list(range(len(self.algorithms)))
255 if self.shuffle_emitters:
256 # Shuffle algorithm list
257 random.shuffle(algos_idx)
258 total_evals = max(1, sum(algo.nb_evaluations for algo in self.algorithms))
259 # Compute expected rewards
260 expected_rwds = [
261 self.initial_expected_rwds if self.algorithms[a].nb_evaluations == 0 else
262 float(self.algorithms[a].nb_updated) / float(self.algorithms[a].nb_evaluations) +
263 self.zeta * math.sqrt(math.log(total_evals) / self.algorithms[a].nb_evaluations)
264 for a in algos_idx]
265 # Update active emitters indexes list
266 self._active_emitters_idx = [algos_idx[a] for a in argsort(expected_rwds, reverse=True)][:self.nb_active_emitters]
267 #print(f"DEBUG _up_active_emitters: {argsort(expected_rwds, reverse=True)}")
268 #print(f"DEBUG _up_active_emitters: {expected_rwds}")
269 #print(f"DEBUG _up_active_emitters: {self._active_emitters_idx}")
270
271 def next(self, verbose: bool = False) -> None:
272 """Switch to the next algorithm in Sequence `self.algorithms`, if there is one."""
273 if self.current_active_idx < len(self._active_emitters_idx) - 1:
274 self.current_active_idx += 1
275 else:
277 self.current_active_idx = 0
278 next_idx = self._active_emitters_idx[self.current_active_idx]
279 self.switch_to(next_idx, verbose=verbose)
280 #print(f"NEXT: {next_idx}")
281
282
283
284
285
286
287# MODELINE "{{{1
288# vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8
289# vim:foldmethod=marker
switch_to(self, int idx, bool verbose=False)
Definition base.py:1123
Tuple[MutableMapping[str, Any], bool] _tell_before_container_update(self, IndividualLike individual)
Measure novelty and quality gain against the still-current cell.
Definition cmame.py:151
None _internal_tell(self, IndividualLike individual, bool added_to_container, Mapping[str, Any] xattr={})
Definition cmame.py:167
IndividualLike _internal_ask(self, IndividualLike base_ind)
Definition cmame.py:79
None _internal_tell(self, IndividualLike individual, bool added_to_container, Mapping[str, Any] xattr={})
Definition cmame.py:103
None next(self, bool verbose=False)
Definition cmame.py:271
None _up_active_emitters(self)
Rank emitters using their accumulated archive update rates.
Definition cmame.py:246