QDpy
Loading...
Searching...
No Matches
div_turbo.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Sequential and interleaved diversity-constrained TuRBO1."""
7
8from dataclasses import dataclass
9from math import isfinite
10
11import numpy as np
12from scipy.linalg import cholesky
13from scipy.stats import qmc
14from sklearn.gaussian_process import GaussianProcessRegressor
15from sklearn.gaussian_process.kernels import Matern
16
17from .modern import _positive_int
18from .parametric import _Coordinates
19
20__all__ = ["DivTuRBO1", "DivTuRBOResult", "DivTuRBOPoint"]
21
22
23
24@dataclass(frozen=True)
26 """Store the evaluated design and its raw fitness."""
27
28 genome: tuple[float, ...]
29 fitness: float
30
31
32
33@dataclass(frozen=True)
35 """Minimum distance is None for a singleton portfolio."""
36
37 solutions: tuple[DivTuRBOPoint, ...]
38 evaluations_by_slot: tuple[int, ...]
39 restarts_by_slot: tuple[int, ...]
40 minimum_distance: float | None
41 violating_pairs: int
42
43 @property
44 def evaluations(self):
45 """Return the total number of objective calls."""
46 return sum(self.evaluations_by_slot)
47
48
49def _distances(points, references):
50 if not len(references):
51 return np.full(len(points), np.inf)
52 with np.errstate(over="ignore"):
53 return np.hypot.reduce(np.asarray(points)[:, None, :] - references, axis=2).min(axis=1)
54
55
56def _selection(quality, distances, threshold):
57 feasible = np.flatnonzero(distances >= threshold)
58 if len(feasible):
59 return int(feasible[np.argmax(quality[feasible])]), True
60 farthest = np.flatnonzero(distances == distances.max())
61 return int(farthest[np.argmax(quality[farthest])]), False
62
63
64def _thompson(points, observed, objectives, rng):
65 """Draw a correlated posterior sample over one trust-region candidate pool."""
66 kernel = Matern(length_scale=np.full(points.shape[1], .25), nu=2.5)
67 scale = max(np.max(np.abs(objectives)), np.finfo(float).tiny)
68 model = GaussianProcessRegressor(kernel=kernel, alpha=1e-6, optimizer=None, normalize_y=True)
69 model.fit(observed, objectives / scale)
70 mean, cov = model.predict(points, return_cov=True)
71 # Repeated coordinates can make the latent posterior singular.
72 diagonal = np.diag_indices(len(cov))
73 cov[diagonal] += max(np.max(cov[diagonal]), 1.) * 1e-10
74 return mean + cholesky(cov, lower=True) @ rng.standard_normal(len(points))
75
76
78 def __init__(self, search, rng, evaluate):
79 self.search, self.rng, self.evaluate = search, rng, evaluate
80 self.dimension = len(search._coordinates.bounds)
81 self._sobol = qmc.Sobol(self.dimension, scramble=True, seed=int(rng.integers(2**32)))
82 self.history = []
83 self.restarts = 0
84 self._reset()
85
86 def _reset(self):
87 self.local = []
88 self.length = .8
89 self.successes = self.failures = self.no_centre = 0
90
91 def _measure(self, point):
92 genome = self.search._coordinates.physical(point)
93 fitness = float(self.evaluate(genome))
94 if not isfinite(fitness):
95 raise ValueError("Return one finite scalar objective.")
96 record = (point, DivTuRBOPoint(genome, fitness))
97 self.history.append(record)
98 self.local.append(record)
99
100 def _select_measured(self, records, references):
101 points = [record[1].genome for record in records]
102 quality = np.asarray([record[1].fitness for record in records]) * self.search._direction
103 distances = _distances(points, references)
104 best, feasible = _selection(quality, distances, self.search.distance)
105 return best, (feasible, quality[best] if feasible else distances[best])
106
107 def _propose(self, centre, references):
108 lower = np.maximum(centre - self.length / 2, 0.)
109 upper = np.minimum(centre + self.length / 2, 1.)
110 pool = self.rng.uniform(lower, upper, size=(self.search.candidate_pool, self.dimension))
111 mask = self.rng.random(pool.shape) < min(20 / self.dimension, 1.)
112 empty = np.flatnonzero(~mask.any(axis=1))
113 mask[empty, self.rng.integers(self.dimension, size=len(empty))] = True
114 pool = np.unique(np.where(mask, pool, centre), axis=0)
115 coordinates = self.search._coordinates
116 physical = np.clip(coordinates.lower + pool * coordinates.span,
117 coordinates.lower, coordinates.upper)
118 distances = _distances(physical, references)
119 eligible = distances >= self.search.distance
120 if not eligible.any():
121 return pool[int(np.argmax(distances))]
122 pool = pool[eligible]
123 observed, measured = zip(*self.local)
124 quality = self.search._direction * np.asarray([record.fitness for record in measured])
125 sampled = _thompson(pool, observed, quality, self.rng)
126 return pool[int(np.argmax(sampled))]
127
128 def _resize(self, improved):
129 if improved:
130 self.successes += 1
131 self.failures = 0
132 if self.successes == 3:
133 self.length = min(1.6, 2 * self.length)
134 self.successes = 0
135 else:
136 self.successes = 0
137 self.failures += 1
138 if self.failures == max(4, self.dimension):
139 self.length /= 2
140 self.failures = 0
141
142 def advance(self, budget, representatives):
143 references = np.asarray([point.genome for point in representatives])
144 for _ in range(budget):
145 if len(self.local) < self.search.initial_samples:
146 self._measure(self._sobol.random(1)[0])
147 continue
148 centre, before = self._select_measured(self.local, references)
149 self.no_centre = 0 if before[0] else self.no_centre + 1
150 if self.no_centre == 3:
151 self.restarts += 1
152 self._reset()
153 self._measure(self._sobol.random(1)[0])
154 continue
155 self._measure(self._propose(self.local[centre][0], references))
156 _, after = self._select_measured(self.local, references)
157 self._resize(after > before)
158 if self.length < 2. ** -7:
159 self.restarts += 1
160 self._reset()
161 index, _ = self._select_measured(self.history, references)
162 return self.history[index][1]
163
164
165
167 """Implement the sequential and interleaved schedules of Perera et al.
168
169 Fit a local Matérn GP and sample from its posterior over a perturbed
170 candidate pool. Fit only the current region's measurements and keep
171 all measurements for final selection. Choose the best feasible
172 centre and prefer feasible candidates. If no point meets the
173 separation requirement, favor the one farthest from its nearest
174 reference. Check the returned minimum distance and violation count.
175
176 :param genome_bounds: One finite increasing interval per decision coordinate.
177 :param population_size: Number of portfolio members to search for.
178 :param distance: Minimum Euclidean separation in the original decision units.
179 :param phases: One for the sequential method. Use more for interleaving.
180 :param fitness_weight: Sign of the objective direction. Positive maximizes.
181 :param initial_samples: Global Sobol calls when starting or restarting a region.
182 :param candidate_pool: Maximum number of local candidates per evaluation.
183 :param seed: Private seed for the independent trust regions.
184 """
185
186 def __init__(self, genome_bounds, *, population_size, distance, phases=1, fitness_weight=-1.,
187 initial_samples=5, candidate_pool=64, seed=0):
188 self._coordinates = _Coordinates(genome_bounds)
189 self.population_size = _positive_int(population_size, "population_size")
190 self.phases = _positive_int(phases, "phases")
191 self.initial_samples = _positive_int(initial_samples, "initial_samples")
192 self.candidate_pool = _positive_int(candidate_pool, "candidate_pool")
193 if not 0. <= distance < np.inf or not isfinite(fitness_weight) or fitness_weight == 0.:
194 raise ValueError("Use finite nonnegative distance and a finite nonzero fitness weight.")
195 self.distance, self._direction = float(distance), float(np.sign(fitness_weight))
196 self.seed = seed
197
198
199 def optimise(self, evaluate, budget):
200 """Call evaluate(genome) for each raw objective and return measured points."""
201 if not callable(evaluate):
202 raise TypeError("evaluate must be callable.")
203 budget = _positive_int(budget, "budget")
204 slots = self.population_size * self.phases
205 if budget < slots:
206 raise ValueError("The budget must cover at least one evaluation per slot and phase.")
207 blocks, extra = divmod(budget, slots)
208 streams = np.random.SeedSequence(self.seed).spawn(self.population_size)
209 regions = [_TrustRegion(self, np.random.default_rng(stream), evaluate) for stream in streams]
210 portfolio = [None] * len(regions)
211 for phase in range(self.phases):
212 for index, region in enumerate(regions):
213 references = [point for i, point in enumerate(portfolio) if i != index and point is not None]
214 steps = blocks + (phase * len(regions) + index < extra)
215 portfolio[index] = region.advance(steps, references)
216 distances = [float(np.hypot.reduce(np.subtract(point.genome, prior.genome)))
217 for i, point in enumerate(portfolio) for prior in portfolio[:i]]
218 return DivTuRBOResult(tuple(portfolio), tuple(len(region.history) for region in regions),
219 tuple(region.restarts for region in regions), min(distances, default=None),
220 sum(distance < self.distance for distance in distances))
Build a small separated portfolio with independent Bayesian trust regions.
Definition div_turbo.py:166
optimise(self, evaluate, budget)
Allocate the exact objective budget across portfolio slots and phases.
Definition div_turbo.py:199
A measured portfolio member in the original decision and objective units.
Definition div_turbo.py:25
A portfolio with exact search costs and measured separation.
Definition div_turbo.py:34
_propose(self, centre, references)
Definition div_turbo.py:107
_select_measured(self, records, references)
Definition div_turbo.py:100