39 """Use uniform or UCB1 operator choices with native two-objective fronts.
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.
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.
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.")
69 self.
_warmup = _positive_int(initial_samples,
"initial_samples")
70 streams = np.random.SeedSequence(seed).spawn(4)
72 self.
_evaluation_seed = int(streams[3].generate_state(1, dtype=np.uint64)[0])
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))
80 self.
_quality = np.asarray(archive.fitness_domain, dtype=float)
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.")
89 """Return costs, per-operator outcomes, and archive updates."""
99 front = self.
archive.solutions[cell]
100 return front[int(self.
_selection.integers(len(front)))], len(front)
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),
109 *qualities, *descriptor), dtype=np.float32)
110 return parent, values
112 def _choose_operator(self, state):
115 unseen = np.flatnonzero(self.
_pulls == 0)
117 return int(self.
_choice.choice(unseen))
119 bonus = np.sqrt(2 * np.log(self.
_pulls.sum()) / self.
_pulls)
120 return int((mean + bonus).argmax())
122 def _observe(self, state, action, reward, successor):
123 """The uniform and bandit controls use the counters updated by run()."""
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
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:
143 self._counts[
"updates"] += 1
145 self._cells.append(cell)
146 return .8
if previous == archive.max_items_per_bin
else 1.
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"]
169 self.
_counts[
"evaluations"] += 1