QDpy
Loading...
Searching...
No Matches
operator_mome.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Uniform and bandit controls for state-aware variation in MOME."""
7
8from collections import Counter
9from collections.abc import Mapping
10from dataclasses import dataclass
11
12import numpy as np
13
14from qdpy.containers import ParetoGrid
15from qdpy.phenotype import Features, Fitness, Individual
16from .modern import _positive_int
17from .sampling import _rollout_seed
18
19__all__ = ["OperatorMOME", "OperatorMOMEStats"]
20
21
22
23@dataclass(frozen=True)
25 """The operator tuples follow the supplied mapping's iteration order."""
26
27 evaluations: int
28 initial_evaluations: int
29 archive_updates: int
30 out_of_domain: int
31 operator_attempts: tuple[tuple[str, int], ...]
32 operator_admissions: tuple[tuple[str, int], ...]
33 optimizer_steps: int
34 target_syncs: int
35
36
37
39 """Use uniform or UCB1 operator choices with native two-objective fronts.
40
41 Sample descriptor cells uniformly and then parents uniformly within
42 their fronts. An admitted child earns 1 for space in its target
43 front or .8 for entering a full front. A rejected child earns zero.
44 Keep cumulative evaluation accounting and resume with the same next
45 parent context when another search budget is supplied.
46
47 :param archive: Empty two-objective ParetoGrid with hypervolume truncation.
48 :param initializer: Callback returning a genome from a private generator.
49 :param operators: Mapping of names to callbacks taking (parent, donor, rng).
50 Parents and donors are tuples copied from the archive.
51 :param controller: Uniform or bandit.
52 :param initial_samples: Minimum number of warm-up evaluations.
53 :param seed: Private seed for decisions, mutations, and evaluations.
54 """
55
56 def __init__(self, archive, *, initializer, operators, controller="uniform", initial_samples=16, seed=0):
57 if (not isinstance(archive, ParetoGrid) or len(archive) or archive.truncation != "hypervolume"
58 or archive.features_score_names or archive.fitness_score_names
59 or archive.capacity < len(archive.solutions) * archive.max_items_per_bin):
60 raise ValueError("Use an empty hypervolume ParetoGrid with native scores and room for every front.")
61 if (not callable(initializer) or not isinstance(operators, Mapping) or not operators
62 or any(not isinstance(name, str) or not name or not callable(op) for name, op in operators.items())):
63 raise ValueError("Provide an initializer and a mapping of named variation callbacks.")
64 if controller not in ("uniform", "bandit"):
65 raise ValueError("Choose uniform or bandit operator selection.")
66 self.archive, self._initializer = archive, initializer
67 self._names, self._operators = tuple(operators), tuple(operators.values())
68 self._controller = controller
69 self._warmup = _positive_int(initial_samples, "initial_samples")
70 streams = np.random.SeedSequence(seed).spawn(4)
71 self._selection, self._choice, self._variation = map(np.random.default_rng, streams[:3])
72 self._evaluation_seed = int(streams[3].generate_state(1, dtype=np.uint64)[0])
73 self._counts = Counter()
74 self._pulls = np.zeros(len(operators), dtype=int)
75 self._admissions = np.zeros(len(operators), dtype=int)
76 self._rewards = np.zeros(len(operators))
77 self._recent = 0.
78 self._context = None
79 self._cells = []
80 self._quality = np.asarray(archive.fitness_domain, dtype=float)
81 self._directions = np.sign(archive.fitness_weights)
82 bounds = np.asarray(archive.features_domain, dtype=float)
83 self._low, self._span = bounds[:, 0], bounds[:, 1] - bounds[:, 0]
84 if not (np.isfinite(self._span).all() and (self._span > 0.).all()):
85 raise ValueError("Use finite, increasing descriptor intervals.")
86
87 @property
88 def stats(self):
89 """Return costs, per-operator outcomes, and archive updates."""
90 return OperatorMOMEStats(
91 self._counts["evaluations"], self._counts["initial"], self._counts["updates"],
92 self._counts["outside"], tuple(zip(self._names, map(int, self._pulls))),
93 tuple(zip(self._names, map(int, self._admissions))),
94 self._counts["optimizer_steps"], self._counts["target_syncs"],
95 )
96
97 def _parent(self):
98 cell = self._cells[int(self._selection.integers(len(self._cells)))]
99 front = self.archive.solutions[cell]
100 return front[int(self._selection.integers(len(front)))], len(front)
101
102 def _state(self):
103 parent, occupancy = self._parent()
104 qualities = (np.asarray(parent.fitness.values) - self._quality[:, 0]) / np.ptp(self._quality, axis=1)
105 qualities = np.where(self._directions > 0., qualities, 1. - qualities)
106 descriptor = (np.asarray(parent.features.values) - self._low) / self._span
107 values = np.asarray((len(self._cells) / len(self.archive.solutions),
108 occupancy / self.archive.max_items_per_bin, self._recent,
109 *qualities, *descriptor), dtype=np.float32)
110 return parent, values
111
112 def _choose_operator(self, state):
113 if self._controller == "uniform":
114 return int(self._choice.integers(len(self._operators)))
115 unseen = np.flatnonzero(self._pulls == 0)
116 if len(unseen):
117 return int(self._choice.choice(unseen))
118 mean = self._rewards / self._pulls
119 bonus = np.sqrt(2 * np.log(self._pulls.sum()) / self._pulls)
120 return int((mean + bonus).argmax())
121
122 def _observe(self, state, action, reward, successor):
123 """The uniform and bandit controls use the counters updated by run()."""
124
125 def _offer(self, point, objectives, descriptors):
126 quality, descriptors = tuple(map(float, objectives)), tuple(map(float, descriptors))
127 archive = self.archive
128 if (len(quality) != 2 or len(descriptors) != len(archive.features_domain)
129 or not np.isfinite((*quality, *descriptors)).all()):
130 raise ValueError("The evaluator must return two finite objectives and its finite descriptor vector.")
131 if not (archive.in_bounds(quality, archive.fitness_domain)
132 and archive.in_bounds(descriptors, archive.features_domain)):
133 self._counts["outside"] += 1
134 return 0.
135 cell = archive.index_grid(descriptors)
136 previous = len(archive.solutions[cell])
137 candidate = Individual(point, fitness=Fitness(quality, weights=archive.fitness_weights),
138 features=Features(descriptors))
139 before = archive.nb_added
140 archive.add(candidate)
141 if archive.nb_added == before:
142 return 0.
143 self._counts["updates"] += 1
144 if not previous:
145 self._cells.append(cell)
146 return .8 if previous == archive.max_items_per_bin else 1.
147
148
152 def run(self, evaluate, budget):
153 """Charge failed evaluator calls and propagate their errors."""
154 if not callable(evaluate):
155 raise TypeError("Supply a callable evaluator.")
156 for _ in range(_positive_int(budget, "budget")):
157 evaluation = self._counts["evaluations"]
158 initialize = evaluation < self._warmup or not self._cells
159 if initialize:
160 point = tuple(self._initializer(self._variation))
161 self._counts["initial"] += 1
162 else:
163 parent, state = self._state() if self._context is None else self._context
164 action = self._choose_operator(state)
165 donor, _ = self._parent()
166 point = tuple(self._operators[action](tuple(parent), tuple(donor), self._variation))
167 self._context = None
168 self._pulls[action] += 1
169 self._counts["evaluations"] += 1
170 reward = self._offer(point, *evaluate(point, _rollout_seed(self._evaluation_seed, 0, evaluation)))
171 self._recent = .95 * self._recent + .05 * reward
172 if not initialize:
173 self._admissions[action] += reward > 0.
174 self._rewards[action] += reward
175 self._context = self._state()
176 self._observe(state, action, reward, self._context[1])
177 return self.stats
Real evaluation attempts and separately counted controller work.
Illuminate a ParetoGrid using user-defined operators and archive feedback.
run(self, evaluate, budget)
Run additional evaluator calls with persistent controller state.
_observe(self, state, action, reward, successor)
_offer(self, point, objectives, descriptors)