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. """
22__all__ = [
"CMAMEOptimizingEmitter",
"CMAMERandomDirectionEmitter",
"CMAMEImprovementEmitter",
"MEMAPElitesUCB1"]
24from typing
import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, Mapping, MutableMapping, overload
30from .evolution
import *
47 """Run single-objective CMA-ES and restart from an archive entry.
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.
64 """Replace the pycma strategy and clear its buffered feedback."""
69 self.
es = cma.CMAEvolutionStrategy(init_ind, self.sigma0, self._opts)
70 self._pop_inds.clear()
71 self._pop_fitness_vals.clear()
73 def _stop(self) -> bool:
74 term_cond = self.
es.stop(check=
False)
77 return len(term_cond) > 0
87 """Use a projection of behaviour descriptors as scalar CMA feedback.
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.
94 _requires_single_objective =
False
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])
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:
108 if added_to_container:
123 self._pop_fitness_vals.clear()
128 """Adapt search using cell coverage and signed fitness gains.
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.
135 _requires_single_objective =
False
137 _novel_pop_inds: MutableSequence[IndividualLike]
138 _novel_pop_fitness_vals: MutableSequence[Any]
153 previous_fitness =
None
156 index = self.
container.index_grid(individual)
157 previous_fitness = self.
container.quality[index]
158 except (IndexError, KeyError):
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
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:
170 novel = xattr.get(
"novel",
False)
171 delta = xattr.get(
"delta", 0.)
173 if added_to_container:
179 self._pop_fitness_vals += [-1. * delta]
183 tot_pop_fitness_vals = []
186 sorted_pop_inds = [self.
_pop_inds[k]
for k
in argsort(self._pop_fitness_vals)]
190 for i, ind
in enumerate(sorted_novel_pop_inds):
192 tot_pop_fitness_vals.append(i)
193 for i, ind
in enumerate(sorted_pop_inds):
195 tot_pop_fitness_vals.append(len(sorted_novel_pop_inds) + i)
198 self.
es.tell(tot_pop, tot_pop_fitness_vals)
203 self._pop_fitness_vals.clear()
210 """Choose active child emitters with an upper confidence bound.
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``.
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.
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
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):
235 super().__init__(algorithms, **kwargs)
247 """Update the list of active emitters."""
257 random.shuffle(algos_idx)
258 total_evals = max(1, sum(algo.nb_evaluations
for algo
in self.
algorithms))
263 self.
zeta * math.sqrt(math.log(total_evals) / self.
algorithms[a].nb_evaluations)
271 def next(self, verbose: bool =
False) ->
None:
272 """Switch to the next algorithm in Sequence `self.algorithms`, if there is one."""
279 self.
switch_to(next_idx, verbose=verbose)
switch_to(self, int idx, bool verbose=False)
MutableSequence _novel_pop_fitness_vals
MutableSequence _novel_pop_inds
Tuple[MutableMapping[str, Any], bool] _tell_before_container_update(self, IndividualLike individual)
Measure novelty and quality gain against the still-current cell.
None _internal_tell(self, IndividualLike individual, bool added_to_container, Mapping[str, Any] xattr={})
IndividualLike _internal_ask(self, IndividualLike base_ind)
None _internal_tell(self, IndividualLike individual, bool added_to_container, Mapping[str, Any] xattr={})
Sequence _active_emitters_idx
None next(self, bool verbose=False)
None _up_active_emitters(self)
Rank emitters using their accumulated archive update rates.