5"""Black-box search across a bounded continuous family of tasks."""
7from dataclasses
import dataclass, replace
8from numbers
import Real
12from scipy.spatial
import Delaunay, QhullError
16from .modern
import _positive_int
18__all__ = [
"ParametricTaskEvaluation",
"ParametricTaskResult",
"parametric_task_map_elites"]
22 """Normalize coordinates for geometry and restore them for the evaluator."""
24 def __init__(self, bounds):
25 pairs = np.asarray(bounds, dtype=float)
26 if pairs.ndim != 2
or pairs.shape[1] != 2
or not len(pairs):
27 raise ValueError(
"Supply a nonempty sequence of (lower, upper) bounds.")
28 with np.errstate(over=
"ignore", invalid=
"ignore"):
29 spans = pairs[:, 1] - pairs[:, 0]
30 if not np.isfinite(pairs).all()
or not np.isfinite(spans).all()
or np.any(spans <= 0):
31 raise ValueError(
"Bounds must be finite, increasing, and have finite spans.")
32 self.
bounds = tuple(map(tuple, pairs.tolist()))
36 def normalize(self, values):
37 values = np.asarray(values, dtype=float)
38 if (values.ndim
not in (1, 2)
or values.shape[-1] != len(self.
span)
39 or not np.all((values >= self.
lower) & (values <= self.
upper))):
40 raise ValueError(
"Coordinates must be finite and inside their declared bounds.")
41 return np.clip((values - self.
lower) / self.
span, 0, 1)
43 def physical(self, values):
48@dataclass(frozen=True)
50 """Immutable observation in the caller's genome and task coordinates."""
52 genome: tuple[float, ...]
53 task: tuple[float, ...]
58@dataclass(frozen=True)
60 """A task repertoire and the evaluation data needed to change its resolution.
62 The archive stores genomes in physical units and feature coordinates in
63 the normalized task box. Every successful measurement appears in order
64 in evaluations. The attempts counter includes failed or invalid results.
68 evaluations: tuple[ParametricTaskEvaluation, ...]
72 tournament_attempts: dict[int, int]
73 tournament_successes: dict[int, int]
74 regression_proposals: int
78 """Return the recorded elite and its observed task, or None for an empty archive."""
81 raise ValueError(
"Supply one task at a time.")
82 occupied = [i
for i
in range(self.archive.shape[0])
if self.archive.solutions[(i,)]]
85 offsets = self.archive.cluster_centers[occupied] - point
86 index = occupied[np.argmin(np.sum(offsets ** 2, axis=1))]
87 return self.
evaluations[int(self.archive.solutions[(index,)][0].name)]
91 """Return another result using the same measurements and the new physical centroids."""
93 archive = _task_archive(coordinates, centroids)
95 _offer_task(archive, record, i, coordinates.normalize(record.task))
96 return replace(self, archive=archive)
99def _task_archive(coordinates, centroids):
100 centers = coordinates.normalize(centroids)
101 if centers.ndim != 2
or len(centers) == 0
or len(np.unique(centers, axis=0)) != len(centers):
102 raise ValueError(
"Supply a nonempty matrix of distinct task centroids.")
103 return CVTGrid(shape=len(centers), centroids=centers, features_domain=((0., 1.),) * centers.shape[1],
104 fitness_domain=((-float(
"inf"), float(
"inf")),), fitness_weights=(1.,))
107def _offer_task(archive, record, position, point):
108 cell = archive.index_grid(point)
109 before = archive.nb_added
111 fitness=
Fitness((record.fitness,), weights=(1.,)), features=
Features(point)))
112 return archive.nb_added != before
115def _task_neighbors(centers):
116 count, dimension = centers.shape
117 neighbors = [set()
for _
in centers]
119 order = np.argsort(centers[:, 0], kind=
"stable")
120 for a, b
in zip(order, order[1:]):
123 elif count > dimension:
125 simplices = Delaunay(centers).simplices
128 for simplex
in simplices:
129 for vertex
in simplex:
130 neighbors[vertex].update(i
for i
in simplex
if i != vertex)
131 return tuple(tuple(sorted(row))
for row
in neighbors)
134def _regression_child(archive, neighbors, point, genomes, rng):
135 """Predict a normalized genome from adjacent elites using through-origin least squares."""
136 cell = archive.index_grid(point)[0]
137 parents = [archive.solutions[(i,)][0]
for i
in neighbors[cell]
if archive.solutions[(i,)]]
138 if len(parents) < len(point):
140 tasks = np.asarray([elite.features.values
for elite
in parents], dtype=float)
141 samples = genomes.normalize([list(elite)
for elite
in parents])
142 fit, _, rank, _ = np.linalg.lstsq(tasks, samples, rcond=
None)
143 if rank < len(point):
145 prediction = point @ fit
146 return np.clip(prediction + rng.normal(size=len(prediction)) * samples.std(axis=0), 0, 1)
149def _sbx(first, second, rng, eta=10):
150 """Draw one simulated binary crossover child in the unit box."""
151 u = rng.random(len(first))
152 spread = np.where(u <= 0.5, 2 * u, 1 / (2 * (1 - u))) ** (1 / (eta + 1))
153 sign = rng.choice((-1, 1), size=len(first))
154 return np.clip((first + second + sign * spread * (first - second)) / 2, 0, 1)
157def _tournament_size(sizes, attempts, successes):
159 if not attempts[size]:
161 total = sum(attempts.values())
162 return max(sizes, key=
lambda size: successes[size] / attempts[size]
163 + np.sqrt(2 * np.log(total) / attempts[size]))
166def _measure_task(evaluate, genome, task):
168 fitness = evaluate(genome, task)
169 if not isinstance(fitness, Real)
or not np.isfinite(fitness):
170 raise ValueError(
"Return one finite real fitness to maximize.")
171 except Exception
as error:
172 warnings.warn(f
"PT-ME evaluation failed: {error}", stacklevel=3)
179 regression_probability=0.5, tournament_sizes=(1, 5, 10, 50, 100, 500)):
180 """Run Parametric-Task MAP-Elites with CVT task cells and one fitness per trial.
182 :param evaluate: Callable taking (genome, task) in physical units and
183 returning a finite scalar fitness to maximize.
184 :param genome_bounds: Ordered finite intervals for real genes.
185 :param task_bounds: Ordered finite intervals for continuous task parameters.
186 :param centroids: CVT centers in physical task units. Supply distinct points.
187 :param budget: Total attempts, including one seed per centroid.
188 :param seed: Seed for variation and task selection.
189 :param regression_probability: Probability of proposing by local regression.
190 :param tournament_sizes: Positive task sample sizes available to UCB1.
191 :returns: A ParametricTaskResult with the CVT archive and evaluation records.
193 The first proposal at each center samples a genome uniformly. Subsequent
194 evaluations draw tasks in the continuous domain. A regression fallback
195 applies SBX at the already selected task without crediting the tournament.
196 Each occupied cell keeps its highest recorded score. The incumbent wins ties.
198 if not callable(evaluate):
199 raise TypeError(
"evaluate must be callable.")
200 if not 0 <= regression_probability <= 1:
201 raise ValueError(
"regression_probability must be in [0, 1].")
202 sizes = sorted({_positive_int(size,
"tournament size")
for size
in tournament_sizes})
204 raise ValueError(
"Supply at least one tournament size.")
206 centroids = np.array(centroids, dtype=float, copy=
True)
207 archive = _task_archive(tasks, centroids)
208 centers = archive.cluster_centers
209 budget = _positive_int(budget,
"budget")
210 if budget < len(centers):
211 raise ValueError(
"Budget must cover an initial evaluation at every centroid.")
212 neighbors = _task_neighbors(centers)
214 rng = np.random.default_rng(seed)
215 attempts, successes = dict.fromkeys(sizes, 0), dict.fromkeys(sizes, 0)
217 failures = regressions = 0
218 for step
in range(budget):
220 if step < len(centers):
221 point = centers[step]
222 task = tuple(centroids[step].tolist())
223 child = rng.random(len(genomes.span))
225 point = rng.random(len(tasks.span))
228 if rng.random() < regression_probability:
229 child = _regression_child(archive, neighbors, point, genomes, rng)
230 regressions += child
is not None
232 arm = _tournament_size(sizes, attempts, successes)
235 first, second = (archive[i]
for i
in rng.integers(len(archive), size=2))
236 child = _sbx(genomes.normalize(first), genomes.normalize(second), rng)
238 sampled = rng.random((arm, len(tasks.span)))
239 delta = sampled - np.asarray(first.features.values)
240 point = sampled[np.argmin(np.sum(delta ** 2, axis=1))]
242 child = rng.random(len(genomes.span))
243 task = tasks.physical(point)
245 record = _measure_task(evaluate, genomes.physical(child), task)
249 accepted = _offer_task(archive, record, len(records), tasks.normalize(task))
250 records.append(record)
251 if arm
is not None and accepted:
255 attempts, successes, regressions)
A successful evaluation and the exact task that produced its fitness.
Archive, successful evaluations, and attempt counts from PT-ME.
solution_for(self, task)
Retrieve the elite in the nearest occupied cell to a physical task.
rebin(self, centroids)
Replay measured evaluations at a new CVT resolution.
:param obj: Slice indicating on which objectives the domination is tested.