QDpy
Loading...
Searching...
No Matches
monte_carlo.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Credit each proposal to the arm that produced it."""
6
7from dataclasses import dataclass
8from math import log, sqrt
9
10import numpy as np
11
12from qdpy.base import registry
13from qdpy.containers import Grid
14from .base import QDAlgorithm, _CallbacksManager
15from .modern import _bounds, _positive_int
16
17__all__ = ["MonteCarloElites"]
18
19
20@dataclass
21class _Arm:
22 draws: int = 0
23 successes: int = 0
24
25
26def _ucb(arm, total, exploration):
27 return (arm.successes / arm.draws + exploration * sqrt(log(max(total, 1)) / arm.draws)
28 if arm.draws else float("inf"))
29
30
31
32@registry.register
34 """Run MAP-Elites with UCB parent selection and one-parent variation.
35
36 :param container: Grid with one retained elite per cell.
37 :param budget: Candidate evaluation budget.
38 :param dimension: Number of real genome coordinates.
39 :param arms: Use an independent history per "individual" or retain
40 counts by "cell" as elites are replaced.
41 :param exploration: Nonnegative coefficient of the UCB exploration term.
42 :param mutate: Optional callable taking an immutable parent genome and
43 the private generator. The default adds bounded Gaussian noise.
44 :param seed: Seed for initialization, mutation and tie breaks.
45 """
46
47 def __init__(self, container, budget, dimension, *, arms="individual", exploration=1 / np.sqrt(2),
48 sigma=.05, ind_domain=(0., 1.), mutate=None, seed=0, **kwargs):
49 if not isinstance(container, Grid) or container.max_items_per_bin != 1:
50 raise ValueError("MonteCarloElites needs a best-only Grid or CVTGrid.")
51 if arms not in ("individual", "cell") or not 0 <= exploration < np.inf or not 0 <= sigma < np.inf:
52 raise ValueError("Use individual or cell arms and finite nonnegative exploration and sigma.")
53 if mutate is not None and not callable(mutate):
54 raise TypeError("mutate must be callable.")
55 self.arms, self.exploration, self.sigma = arms, exploration, sigma
56 self.ind_domain, self.mutate, self.seed = _bounds(ind_domain), mutate, seed
57 if container.fitness_weights is not None:
58 kwargs.setdefault("optimisation_task", container.fitness_weights)
59 super().__init__(container, _positive_int(budget, "budget"),
60 dimension=_positive_int(dimension, "dimension"), **kwargs)
61
62 def reinit(self):
63 """Reset arm histories and the seeded generator while retaining elites."""
64 super().reinit()
65 self._rng = np.random.default_rng(self.seed)
66 self._individual_arms, self._cell_arms, self._pending = {}, {}, {}
67 self._draws = 0
68
69 def _internal_ask(self, base_ind):
70 if not len(self.container):
71 base_ind[:] = self._rng.uniform(*self.ind_domain, size=self.dimension)
72 return base_ind
73 elites = tuple(self.container)
74 if self.arms == "cell":
75 arms = [self._cell_arms.setdefault(self.container.index_grid(elite), _Arm()) for elite in elites]
76 else:
77 self._individual_arms = {id(elite): self._individual_arms.get(id(elite), (elite, _Arm()))
78 for elite in elites}
79 arms = [self._individual_arms[id(elite)][1] for elite in elites]
80 scores = np.array([_ucb(arm, self._draws, self.exploration) for arm in arms])
81 choice = self._rng.choice(np.flatnonzero(scores == scores.max()))
82 parent, arm = tuple(elites[choice]), arms[choice]
83 if self.mutate is None:
84 genome = np.clip(np.asarray(parent) + self._rng.normal(0, self.sigma, self.dimension),
85 *self.ind_domain)
86 else:
87 genome = np.asarray(self.mutate(parent, self._rng), dtype=float)
88 if genome.shape != (self.dimension,) or not np.all(
89 (genome >= self.ind_domain[0]) & (genome <= self.ind_domain[1])):
90 raise ValueError("Mutation must return a finite genome in the configured bounds.")
91 base_ind[:] = genome
92 arm.draws += 1
93 self._draws += 1
94 self._pending[id(base_ind)] = (base_ind, arm)
95 return base_ind
96
97 def _transfer_suggestion(self, individual, evaluated):
98 arm = self._pending.pop(id(individual), None)
99 if arm is not None:
100 self._pending[id(evaluated)] = (evaluated, arm[1])
101
102 def _forget_suggestion(self, individual):
103 self._pending.pop(id(individual), None)
104
105 def _internal_tell(self, individual, added_to_container, xattr=None):
106 arm = self._pending.pop(id(individual), None)
107 if arm is not None and added_to_container:
108 cell = self.container.index_grid(individual)
109 arm[1].successes += any(elite is individual for elite in self.container.solutions[cell])
110
111 def __getstate__(self):
112 state = super().__getstate__()
113 state["_pending"] = {}
114 # Object IDs change when the archive is unpickled.
115 state["_individual_arms"] = list(self._individual_arms.values())
116 return state
117
118 def __setstate__(self, state):
119 self.__dict__.update(state)
120 self._base_ind_gen = None
122 self._individual_arms = {id(elite): (elite, arm) for elite, arm in self._individual_arms}
Select parents using the upper confidence bound on offspring survival.
_transfer_suggestion(self, individual, evaluated)
Transfer coordinator-side metadata when evaluation returns a new object.
_internal_tell(self, individual, added_to_container, xattr=None)