QDpy
Loading...
Searching...
No Matches
offline.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""MAP-Elites using only pre-existing numeric measurements during search."""
7
8from dataclasses import dataclass
9
10import numpy as np
11from sklearn.gaussian_process import GaussianProcessRegressor
12from sklearn.gaussian_process.kernels import Matern
13
14from qdpy.containers import CVTGrid, Grid
15from qdpy.phenotype import Features, Fitness, Individual
16from qdpy.tools import iso_line_dd
17from .modern import _positive_int, _variation_settings
18from .sampling import _aggregate, _stage_archive
19from .uncertain import _Rollouts
20
21__all__ = ["OfflineMAPElites", "OfflineSearchResult", "OfflineVerification"]
22
23
24
25@dataclass(frozen=True)
27 """Fitness stores the acquisition score. Raw means and uncertainties are in scores."""
28
29 archive: Grid
30 predictions: int
31
32
33
34@dataclass(frozen=True)
36 """Report measured elites, failed evaluations, and agreement on descriptor cells."""
37
38 archive: Grid
39 evaluations: int
40 failed_evaluations: int
41 cell_matches: int
42 out_of_domain: int
43
44
45def _empty_geometry(archive):
46 result = _stage_archive(archive)
47 result.clear()
48 return result
49
50
51def _insert(archive, candidate):
52 features, fitness = candidate.features.values, candidate.fitness.values
53 if not (archive.in_bounds(features, archive.features_domain)
54 and archive.in_bounds(fitness, archive.fitness_domain)):
55 return None
56 cell = archive.index_grid(features)
57 if archive.free >= 1 or archive.solutions[cell]:
58 archive.add(candidate)
59 return cell
60
61
62def _frozen_matern(points, responses, length_scale, noise):
63 model = GaussianProcessRegressor(kernel=Matern(length_scale=length_scale, nu=2.5),
64 alpha=noise, normalize_y=True, optimizer=None)
65 return model.fit(points, responses)
66
67
68
70 """Fit independent GP output columns once and search over their predictions.
71
72 Logged genomes are numerical vectors in a shared real interval.
73 Their measured fitness and descriptor columns train the surrogate.
74 Predicted elites compete by signed mean fitness plus uncertainty
75 weight times standard deviation. A separate verification call uses
76 true measurements and can relocate verified elites to other cells.
77
78 :param archive: Empty parentless best-only Grid or CVTGrid with one signed objective.
79 :param genomes: Matrix with one logged genome per row.
80 :param fitnesses: One measured scalar fitness per row.
81 :param descriptors: Matrix of measured behavior coordinates in row order.
82 :param ind_domain: Shared closed interval for the real genome coordinates.
83 :param uncertainty_weight: Signed standard-deviation multiplier in acquisition.
84 :param length_scale: Fixed Matérn length scale in normalized genome coordinates.
85 :param noise: Positive GP covariance nugget in standardized output units.
86 :param iso_sigma: Independent Iso+LineDD mutation scale.
87 :param line_sigma: Shared Iso+LineDD direction scale.
88 :param seed: Private seed for search and initial proposals.
89 """
90
91 def __init__(self, archive, genomes, fitnesses, descriptors, *, ind_domain=(0., 1.),
92 uncertainty_weight=0., length_scale=.3, noise=1e-6, iso_sigma=.05,
93 line_sigma=.2, seed=0):
94 if (type(archive) not in (Grid, CVTGrid) or len(archive) or archive.parents
95 or archive.max_items_per_bin != 1 or archive.discard_random_on_bin_overload
96 or len(archive.fitness_domain or ()) != 1 or len(archive.fitness_weights or ()) != 1
97 or not np.isfinite(archive.fitness_weights[0]) or not archive.fitness_weights[0]
98 or archive.fitness_score_names or archive.features_score_names):
99 raise ValueError("Use an empty parentless best-only Grid or CVTGrid with native signed fitness.")
100 self.ind_domain = _variation_settings(ind_domain, iso_sigma, line_sigma)
101 self._width = self.ind_domain[1] - self.ind_domain[0]
102 if (not np.isfinite(self._width) or not np.isfinite(uncertainty_weight)
103 or not 0. < length_scale < np.inf or not 0. < noise < np.inf):
104 raise ValueError("Use finite bounds and uncertainty weight and positive finite GP settings.")
105 genomes, fitnesses, descriptors = (np.asarray(values, dtype=float) for values in (
106 genomes, fitnesses, descriptors))
107 if (genomes.ndim != 2 or len(genomes) < 2 or not genomes.shape[1]
108 or fitnesses.shape != (len(genomes),)
109 or descriptors.shape != (len(genomes), len(archive.features_domain))
110 or not all(np.isfinite(values).all() for values in (genomes, fitnesses, descriptors))
111 or np.any(genomes < self.ind_domain[0]) or np.any(genomes > self.ind_domain[1])):
112 raise ValueError("Supply at least two aligned finite measurement rows with in-bounds genomes.")
113 self._model = _frozen_matern(self._normalized(genomes), np.column_stack((fitnesses, descriptors)),
114 length_scale, noise)
115 self._source = _empty_geometry(archive)
116 self._genomes = genomes.copy()
117 self.seed = seed
118 self._direction = np.sign(archive.fitness_weights[0])
119 self._uncertainty_weight, self._iso_sigma, self._line_sigma = uncertainty_weight, iso_sigma, line_sigma
120
121 def _normalized(self, rows):
122 return (rows - self.ind_domain[0]) / self._width
123
124
128 def run(self, budget, *, initial_samples=16):
129 """Return an independent predicted grid using a fixed seed."""
130 budget = _positive_int(budget, "budget")
131 initial = min(_positive_int(initial_samples, "initial_samples"), len(self._genomes), budget)
132 archive = _empty_geometry(self._source)
133 rng = np.random.default_rng(self.seed)
134 seeds = self._genomes[rng.permutation(len(self._genomes))[:initial]]
135 for step in range(budget):
136 if step < initial:
137 point = seeds[step]
138 elif len(archive):
139 first, second = rng.integers(len(archive), size=2)
140 point = iso_line_dd(archive[first], archive[second], bounds=self.ind_domain,
141 iso_sigma=self._iso_sigma, line_sigma=self._line_sigma, rng=rng)
142 else:
143 point = rng.uniform(*self.ind_domain, size=self._genomes.shape[1])
144 means, deviations = self._model.predict(self._normalized(np.asarray(point)[None]), return_std=True)
145 mean, *features = means[0]
146 deviation = deviations[0, 0]
147 score = mean + self._direction * self._uncertainty_weight * deviation
148 if not np.isfinite((score, deviation, *features)).all():
149 raise ValueError("The frozen surrogate produced a nonfinite prediction.")
150 _insert(archive, Individual(list(point), fitness=Fitness((score,), weights=archive.fitness_weights),
151 features=Features(features),
152 scores={"predicted_fitness": float(mean), "prediction_std": float(deviation)}))
153 return OfflineSearchResult(archive, budget)
154
155
162 @staticmethod
163 def verify(result, evaluate, budget, *, seed=0, executor=None):
164 """Keep measured outcomes separate. Observed descriptor cells decide placement."""
165 budget = _positive_int(budget, "budget")
166 if not isinstance(result, OfflineSearchResult) or not callable(evaluate):
167 raise TypeError("Pass an OfflineSearchResult and an evaluator.")
168 predicted = result.archive
169 measured = _empty_geometry(predicted)
170 selected = np.random.default_rng(seed).permutation(len(predicted))[:budget]
171 candidates = [predicted[i] for i in selected]
172 runner = _Rollouts(measured, evaluate, executor, seed, stream=5, seeded=True)
173 observations = runner.evaluate_groups([(candidate, 1) for candidate in candidates])
174 matches = outside = 0
175 for candidate, rows in zip(candidates, observations):
176 if rows:
177 exact = _aggregate(measured, Individual(list(candidate)), rows)
178 destination = _insert(measured, exact)
179 matches += destination == predicted.index_grid(candidate)
180 outside += destination is None
181 return OfflineVerification(measured, runner.attempted, runner.failed, matches, outside)
Generate a predicted repertoire from a fixed dataset.
Definition offline.py:69
verify(result, evaluate, budget, *, seed=0, executor=None)
Verify a uniform shortlist of predicted elites under an independent exact budget.
Definition offline.py:163
run(self, budget, *, initial_samples=16)
Run bounded search without any calls to an exact evaluator.
Definition offline.py:128
Predicted elites and number of proposals assessed by the frozen model.
Definition offline.py:26
Independent exact evaluations of selected predicted elites.
Definition offline.py:35
Dispatch rollouts and resolve them in submission order.
Definition uncertain.py:95
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405