QDpy
Loading...
Searching...
No Matches
windowed_map_elites.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Move a search window in descriptor space after a user choice."""
7
8from math import isfinite
9from operator import index
10from random import Random
11
12import numpy as np
13from scipy.spatial.distance import cdist
14
15from qdpy.base import registry
16
17from ._population import _finite_vector
18from .constrained import ConstrainedMAPElites
19from .medoid_map_elites import _pam
20from .modern import _positive_int
21
22__all__ = ["WindowedMAPElites"]
23
24
25
26@registry.register
28 """User-Controlled MAP-Elites for real, integer, and categorical variables.
29
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.
35
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.
45 """
46
47 _allows_no_constraints = True
48
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))
58 if not all(radius > 0. for radius in self.window_radius):
59 raise ValueError("Window radii must be positive.")
60 self.seed = index(seed)
61 self._domain = domain
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)
65
66 def reinit(self):
67 """Reset the round-robin parent choice and clear the window."""
68 super().reinit()
69 self._variation_rng = Random(self.seed)
70 self._window_center = None
71 self._select_infeasible = False
72 self._local_feasible = self._local_infeasible = ()
73
74 @property
75 def window_center(self):
76 """Return the selected descriptor or None during global search."""
77 return self._window_center
78
79 def _in_window(self, individual):
80 if self._window_center is None:
81 return True
82 descriptor = self.container.get_ind_features(individual)
83 return all(abs(float(x) - c) <= r for x, c, r in zip(descriptor, self._window_center, self.window_radius))
84
85 def _start_fixed_batch(self, size):
86 super()._start_fixed_batch(size)
87 self._local_feasible = tuple(row for row in self.container if self._in_window(row))
88 self._local_infeasible = tuple(row for _, row in self._infeasible.values() if self._in_window(row))
89
90 def _clear_generation(self):
91 super()._clear_generation()
92 self._local_feasible = self._local_infeasible = ()
93
94 def _select_parent(self, rng):
95 feasible, infeasible = self._local_feasible, self._local_infeasible
96 if feasible and infeasible:
97 pool = infeasible if self._select_infeasible else feasible
99 else:
100 pool = feasible or infeasible
101 return rng.choice(pool) if pool else None
102
103
107 def alternatives(self, count=4, *, sampling="medoids"):
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":
113 corners = 1 << len(self.window_radius)
114 count = min(count, corners)
115 panel = tuple(row for row in self.container if self._in_window(row))
116 if len(panel) <= count:
117 return panel
118 points = np.asarray([tuple(self.container.get_ind_features(row)) for row in panel])
119 lower, upper = self._domain.T
120 if self._window_center is not None:
121 with np.errstate(over="ignore"):
122 lower = np.maximum(lower, np.asarray(self._window_center) - self.window_radius)
123 upper = np.minimum(upper, np.asarray(self._window_center) + self.window_radius)
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)
128 else:
129 selected = []
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)
137
138
140 def focus(self, elite):
141 """Apply a selection between completed ask/tell batches."""
142 if self._pending_size:
143 raise RuntimeError("Complete the current batch before changing the focus.")
144 if elite is None:
145 self._window_center = None
146 return
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.")
152 self._window_center = descriptor
153
154
159 def choose(self, chooser, count=4, *, sampling="medoids"):
160 """Call the chooser only when a feasible alternative is available."""
161 if self._pending_size:
162 raise RuntimeError("Complete the current batch before asking for a choice.")
163 panel = self.alternatives(count, sampling=sampling)
164 if not panel:
165 return None
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]
Search for feasible elites with real, integer, and categorical coordinates.
Show local alternatives and restrict breeding to the selected neighborhood.
choose(self, chooser, count=4, *, sampling="medoids")
Show alternatives to a chooser and recenter on its zero-based selection.
focus(self, elite)
Center the window on a live feasible elite or clear it with None.
alternatives(self, count=4, *, sampling="medoids")
Display distinct feasible elites inside the current selection window.