28 """User-Controlled MAP-Elites for real, integer, and categorical variables.
30 Initially breed across the full archive. Call ``choose()`` to display
31 nearby feasible elites and center the window on the chosen elite.
32 While focused, parents come from inside the window. Offspring may
33 populate any descriptor cell. When both pools have eligible parents,
34 alternate between feasible and infeasible elites.
36 :param container: Empty best-only Grid or CVTGrid with finite descriptor bounds.
37 :param budget: Evaluation budget for one managed optimisation call.
38 :param variables: Variable specifications in genome order.
39 :param window_radius: Positive half-width, scalar or one per archive descriptor.
40 :param constraint_names: Optional inequality residual names, where g(x) <= 0 is feasible.
41 :param seed: Private seed for parent sampling and variation.
42 :param batch_size: Number of proposals between archive updates.
43 :param real_sigma: Mutation scale as a fraction of each real variable's width.
44 :param optimisation_task: Native scalar objective direction or weight.
47 _allows_no_constraints =
True
49 def __init__(self, container, budget, variables, *, window_radius, constraint_names=(), seed=0,
50 batch_size=1, real_sigma=.1, optimisation_task=
None):
51 domain = np.asarray(container.features_domain, dtype=float)
52 if (domain.ndim != 2
or domain.shape[1] != 2
or not len(domain)
53 or not np.isfinite(domain).all()
or not np.isfinite(domain[:, 1] - domain[:, 0]).all()):
54 raise ValueError(
"Windowed search needs finite descriptor bounds and spans.")
55 if np.ndim(window_radius) == 0:
56 window_radius = (window_radius,) * len(domain)
57 self.
window_radius = _finite_vector(window_radius,
"Window radius", len(domain))
59 raise ValueError(
"Window radii must be positive.")
60 self.
seed = index(seed)
62 direction = container.fitness_weights
if optimisation_task
is None else optimisation_task
63 super().__init__(container, budget, variables, constraint_names=constraint_names,
64 batch_size=batch_size, real_sigma=real_sigma, optimisation_task=direction)
67 """Reset the round-robin parent choice and clear the window."""
76 """Return the selected descriptor or None during global search."""
79 def _in_window(self, individual):
82 descriptor = self.
container.get_ind_features(individual)
90 def _clear_generation(self):
91 super()._clear_generation()
94 def _select_parent(self, rng):
96 if feasible
and infeasible:
100 pool = feasible
or infeasible
101 return rng.choice(pool)
if pool
else None
108 """Use descriptor distances scaled by window widths for display selection."""
109 count = _positive_int(count,
"count")
110 if sampling
not in (
"medoids",
"corners"):
111 raise ValueError(
"Choose medoids or corners sampling.")
112 if sampling ==
"corners":
114 count = min(count, corners)
116 if len(panel) <= count:
118 points = np.asarray([tuple(self.
container.get_ind_features(row))
for row
in panel])
121 with np.errstate(over=
"ignore"):
124 widths = upper - lower
125 normalized = (points - lower) / np.where(widths > 0., widths, 1.)
126 if sampling ==
"medoids":
127 selected = _pam(cdist(normalized, normalized), count, max_swaps=20)
130 for i
in range(count):
131 code = i * (corners - 1) // max(count - 1, 1)
132 corner = [(code >> axis) & 1
for axis
in range(len(widths))]
133 distance = np.square(normalized - corner).sum(axis=1)
134 distance[selected] = np.inf
135 selected.append(int(np.argmin(distance)))
136 return tuple(panel[i]
for i
in selected)
141 """Apply a selection between completed ask/tell batches."""
143 raise RuntimeError(
"Complete the current batch before changing the focus.")
147 if not any(row
is elite
for row
in self.
container):
148 raise ValueError(
"Focus requires a live feasible elite.")
149 descriptor = tuple(map(float, self.
container.get_ind_features(elite)))
150 if not all(map(isfinite, descriptor)):
151 raise ValueError(
"Focus requires finite descriptors.")
159 def choose(self, chooser, count=4, *, sampling="medoids"):
160 """Call the chooser only when a feasible alternative is available."""
162 raise RuntimeError(
"Complete the current batch before asking for a choice.")
166 decision = index(chooser(panel))
167 if not 0 <= decision < len(panel):
168 raise ValueError(
"The chooser must return a displayed zero-based index.")
169 self.
focus(panel[decision])
170 return panel[decision]