QDpy
Loading...
Searching...
No Matches
parametric.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Black-box search across a bounded continuous family of tasks."""
6
7from dataclasses import dataclass, replace
8from numbers import Real
9import warnings
10
11import numpy as np
12from scipy.spatial import Delaunay, QhullError
13
14from qdpy.containers import CVTGrid
15from qdpy.phenotype import Features, Fitness, _CellIndividual
16from .modern import _positive_int
17
18__all__ = ["ParametricTaskEvaluation", "ParametricTaskResult", "parametric_task_map_elites"]
19
20
22 """Normalize coordinates for geometry and restore them for the evaluator."""
23
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()))
33 self.lower, self.upper = pairs.T
34 self.span = spans
35
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)
42
43 def physical(self, values):
44 return tuple(np.clip(self.lower + self.span * values, self.lower, self.upper).tolist())
45
46
47
48@dataclass(frozen=True)
50 """Immutable observation in the caller's genome and task coordinates."""
51
52 genome: tuple[float, ...]
53 task: tuple[float, ...]
54 fitness: float
55
56
57
58@dataclass(frozen=True)
60 """A task repertoire and the evaluation data needed to change its resolution.
61
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.
65 """
66
67 archive: CVTGrid
68 evaluations: tuple[ParametricTaskEvaluation, ...]
69 attempts: int
70 failures: int
71 task_bounds: tuple
72 tournament_attempts: dict[int, int]
73 tournament_successes: dict[int, int]
74 regression_proposals: int
75
76
77 def solution_for(self, task):
78 """Return the recorded elite and its observed task, or None for an empty archive."""
79 point = _Coordinates(self.task_bounds).normalize(task)
80 if point.ndim != 1:
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,)]]
83 if not occupied:
84 return None
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)]
88
89
90 def rebin(self, centroids):
91 """Return another result using the same measurements and the new physical centroids."""
92 coordinates = _Coordinates(self.task_bounds)
93 archive = _task_archive(coordinates, centroids)
94 for i, record in enumerate(self.evaluations):
95 _offer_task(archive, record, i, coordinates.normalize(record.task))
96 return replace(self, archive=archive)
97
98
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.,))
105
106
107def _offer_task(archive, record, position, point):
108 cell = archive.index_grid(point)
109 before = archive.nb_added
110 archive.add(_CellIndividual(record.genome, cell, name=str(position),
111 fitness=Fitness((record.fitness,), weights=(1.,)), features=Features(point)))
112 return archive.nb_added != before
113
114
115def _task_neighbors(centers):
116 count, dimension = centers.shape
117 neighbors = [set() for _ in centers]
118 if dimension == 1:
119 order = np.argsort(centers[:, 0], kind="stable")
120 for a, b in zip(order, order[1:]):
121 neighbors[a].add(b)
122 neighbors[b].add(a)
123 elif count > dimension:
124 try:
125 simplices = Delaunay(centers).simplices
126 except QhullError:
127 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)
132
133
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):
139 return None
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):
144 return None
145 prediction = point @ fit
146 return np.clip(prediction + rng.normal(size=len(prediction)) * samples.std(axis=0), 0, 1)
147
148
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)
155
156
157def _tournament_size(sizes, attempts, successes):
158 for size in sizes:
159 if not attempts[size]:
160 return 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]))
164
165
166def _measure_task(evaluate, genome, task):
167 try:
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)
173 return None
174 return ParametricTaskEvaluation(genome, task, float(fitness))
175
176
177
178def parametric_task_map_elites(evaluate, *, genome_bounds, task_bounds, centroids, budget, seed=0,
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.
181
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.
192
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.
197 """
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})
203 if not sizes:
204 raise ValueError("Supply at least one tournament size.")
205 genomes, tasks = _Coordinates(genome_bounds), _Coordinates(task_bounds)
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)
213
214 rng = np.random.default_rng(seed)
215 attempts, successes = dict.fromkeys(sizes, 0), dict.fromkeys(sizes, 0)
216 records = []
217 failures = regressions = 0
218 for step in range(budget):
219 arm = None
220 if step < len(centers):
221 point = centers[step]
222 task = tuple(centroids[step].tolist())
223 child = rng.random(len(genomes.span))
224 else:
225 point = rng.random(len(tasks.span))
226 child = None
227 if archive:
228 if rng.random() < regression_probability:
229 child = _regression_child(archive, neighbors, point, genomes, rng)
230 regressions += child is not None
231 else:
232 arm = _tournament_size(sizes, attempts, successes)
233 attempts[arm] += 1
234 if child is None:
235 first, second = (archive[i] for i in rng.integers(len(archive), size=2))
236 child = _sbx(genomes.normalize(first), genomes.normalize(second), rng)
237 if arm is not None:
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))]
241 else:
242 child = rng.random(len(genomes.span))
243 task = tasks.physical(point)
244
245 record = _measure_task(evaluate, genomes.physical(child), task)
246 if record is None:
247 failures += 1
248 continue
249 accepted = _offer_task(archive, record, len(records), tasks.normalize(task))
250 records.append(record)
251 if arm is not None and accepted:
252 successes[arm] += 1
253
254 return ParametricTaskResult(archive, tuple(records), budget, failures, tasks.bounds,
255 attempts, successes, regressions)
A successful evaluation and the exact task that produced its fitness.
Definition parametric.py:49
Archive, successful evaluations, and attempt counts from PT-ME.
Definition parametric.py:59
solution_for(self, task)
Retrieve the elite in the nearest occupied cell to a physical task.
Definition parametric.py:77
rebin(self, centroids)
Replay measured evaluations at a new CVT resolution.
Definition parametric.py:90
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405