25 """Optimal Gaussian variational posterior with fixed whitened inducing features.
27 For feature matrix Phi and normalized outputs Y, accumulate
28 I + Phi.T @ Phi / noise and Phi.T @ Y / noise. The expected likelihood
29 also contains a residual prior variance term independent of q(u).
30 Keep this variance in predictions. All outputs share the same kernel
31 and observation noise but have independent inducing posteriors.
34 def __init__(self, inducing, output_size, *, lengthscale, noise):
35 self.
inducing = np.array(inducing, dtype=float, copy=
True)
38 kernel.flat[::len(kernel) + 1] += 1e-9
39 self.
_prior = cholesky(kernel, lower=
True)
46 def _kernel(self, first, second):
47 with np.errstate(over=
"ignore"):
48 return np.exp(-.5 * np.square(cdist(first, second) / self.
lengthscale))
50 def _features(self, points):
54 def update(self, points, outputs):
58 if not np.isfinite(information).all()
or not np.isfinite(precision).all():
59 raise ValueError(
"Nonfinite sparse GP statistics. Increase output scaling or noise.")
60 factor = cholesky(precision, lower=
True)
61 weights = cho_solve((factor,
True), information)
66 def predict(self, points):
68 conditional = np.maximum(0., 1. - np.square(features).sum(axis=0))
69 projected = solve_triangular(self.
_factor, features, lower=
True, check_finite=
False)
70 variance = conditional + np.square(projected).sum(axis=0)
71 return features.T @ self.
_weights, np.sqrt(variance)
90 """Fit a fixed-budget surrogate incrementally and archive actual measurements.
92 Independent objective and descriptor posteriors use shared sparse
93 kernel features. For each candidate, sample the outputs and determine
94 the actual cell of each sampled descriptor. Average improvement over
95 those draws, with zero credit outside the descriptor domain. For a
96 batch, rank a single candidate pool against a frozen archive and
97 evaluate distinct proposals in order. Observation noise is used for
98 fitting. Acquisition draws are from the latent predictive distribution.
100 :param container: Parentless best-only Grid or CVTGrid with finite descriptor intervals.
101 :param budget: Managed-run budget in attempted true evaluations.
102 :param dimension: Number of bounded real decision variables.
103 :param ind_domain: Shared lower and upper decision bounds.
104 :param quality_floor: Improvement baseline for empty cells in signed fitness units.
105 :param quality_scale: Positive scale for objective observations in signed fitness units.
106 :param inducing_points: Number of fixed Sobol inducing points in decision space.
107 :param lengthscale: RBF length scale in normalized decision coordinates.
108 :param noise: Observation noise variance in normalized output coordinates.
109 :param initial_samples: Uniform Sobol initialization budget.
110 :param candidate_pool: Number of Sobol candidates scored per model-based generation.
111 :param posterior_samples: Monte Carlo draws per candidate.
112 :param batch_size: Maximum in-flight evaluations per generation.
113 :param seed: Private proposal and acquisition seed.
114 :param kwargs: Native optimiser options.
117 _requires_proposed_genome =
True
119 def __init__(self, container, budget, dimension, ind_domain, quality_floor, *, quality_scale=1.,
120 inducing_points=32, lengthscale=.25, noise=.01, initial_samples=None, candidate_pool=128,
121 posterior_samples=64, batch_size=1, seed=0, **kwargs):
122 if (type(container)
not in (Grid, CVTGrid)
or container.max_items_per_bin != 1
or container.parents
123 or container.discard_random_on_bin_overload
or len(container.fitness_domain
or ()) != 1
124 or not len(container.features_domain)
or container.fitness_score_names
or container.features_score_names):
125 raise ValueError(
"Supply a parentless best-only Grid or CVTGrid with direct single-objective scores.")
126 lower, upper = np.asarray(container.features_domain, dtype=float).T
127 widths = upper - lower
128 if not (np.isfinite(lower).all()
and np.isfinite(upper).all()
129 and np.isfinite(widths).all()
and (widths > 0).all()):
130 raise ValueError(
"Use finite positive descriptor intervals and widths.")
131 if not (np.isfinite(quality_floor)
and 0 < quality_scale < np.inf
132 and 0 < lengthscale < np.inf
and np.finfo(float).eps <= noise < np.inf):
133 raise ValueError(
"Use a finite quality floor, positive scales, and noise of at least machine epsilon.")
136 raise ValueError(
"Use a finite decision interval width.")
137 dimension = _positive_int(dimension,
"dimension")
138 self.
_inducing_count = _positive_int(inducing_points,
"inducing_points")
139 self.
_batch_limit = _positive_int(batch_size,
"batch_size")
140 self.
_pool_size = _positive_int(candidate_pool,
"candidate_pool")
142 raise ValueError(
"candidate_pool must be at least batch_size.")
143 self.
_initial = (max(2, dimension * 4)
if initial_samples
is None
144 else _positive_int(initial_samples,
"initial_samples"))
145 self.
_sample_count = _positive_int(posterior_samples,
"posterior_samples")
149 self.
_scales = np.r_[quality_scale, widths]
150 self.
_offsets = np.r_[quality_floor, lower + .5 * widths]
151 self.
_cells = tuple(container.solutions)
152 self.
_shape = np.asarray(container.shape, dtype=int)
153 if container.fitness_weights
is not None:
154 kwargs.setdefault(
"optimisation_task", container.fitness_weights)
155 super().__init__(container, _positive_int(budget,
"budget"), dimension=dimension,
159 """Reset the model, deterministic proposal streams, and statistics."""
161 basis, samples = np.random.SeedSequence(self.
seed).spawn(2)
163 self.
_basis = qmc.Sobol(self.
dimension, scramble=
True, seed=np.random.default_rng(basis))
164 rng = np.random.default_rng(samples)
174 """Return cumulative evaluation counts and compute times."""
175 observations = 0
if self.
_model is None else self.
_model.n_observations
183 def _raw_point(self, point):
185 return lower + (upper - lower) * point
187 def _pool(self, count):
190 for _
in range(count + 1024):
191 point = self.
_sobol.random(1)[0]
193 if key
in self.
_seen:
195 candidates.setdefault(key, point)
196 if len(candidates) == count:
197 return np.asarray(list(candidates.values()))
199 return np.asarray(list(candidates.values()))
200 raise RuntimeError(
"The Sobol stream could not find enough distinct genomes in the decision domain.")
202 def _thresholds(self):
204 return np.asarray([self.
container.get_ind_fitness(self.
container.solutions[cell][0]).values[0] * weights[0]
207 def _improvement(self, draws):
208 descriptors = draws[..., 1:].reshape(-1, len(self.
_lower))
209 valid = ((descriptors >= self.
_lower) & (descriptors <= self.
_upper)).all(axis=1)
210 values = descriptors[valid]
213 block = max(1, (1 << 18) // len(centers))
214 cells = np.empty(len(values), dtype=int)
215 for offset
in range(0, len(values), block):
216 rows = values[offset:offset + block]
217 distances = cdist(rows, centers)
218 closest = distances.argmin(axis=1)
219 minimum = distances[np.arange(len(rows)), closest]
220 for i
in np.flatnonzero(~np.isfinite(minimum) | (minimum < np.sqrt(np.finfo(float).tiny))):
221 if minimum[i] != 0.
or not np.array_equal(rows[i], centers[closest[i]]):
222 closest[i], = self.
container.index_grid(tuple(rows[i]))
223 cells[offset:offset + block] = closest
226 indices = np.minimum(self.
_shape - 1, indices.astype(np.intp))
227 cells = np.ravel_multi_index(indices.T, self.
container.shape)
228 improvement = np.zeros(len(descriptors))
229 improvement[valid] = np.maximum(draws[..., 0].ravel()[valid] - self.
_thresholds()[cells], 0.)
230 return improvement.reshape(draws.shape[:-1]).mean(axis=1)
234 observations = 0
if self.
_model is None else self.
_model.n_observations
238 start = perf_counter()
240 means, deviations = self.
_model.predict(pool)
241 draws = (means[:,
None, :] + deviations[:,
None,
None] * self.
_draws)
243 ranking = np.argsort(-self.
_improvement(draws), kind=
"stable")
247 self.
_seen.add(tuple(base_ind))
250 def _check_candidate(self, individual):
252 fitness = self.
container.get_ind_fitness(individual).values
253 descriptors = tuple(self.
container.get_ind_features(individual))
254 if (len(fitness) != 1
or not np.isfinite(fitness[0] * self.
container.fitness_weights[0])
255 or len(descriptors) != len(self.
_lower)):
256 raise ValueError(
"Use one finite signed objective and matching descriptors.")
259 indices = [i
for i, row
in enumerate(evaluated)
if row
is not None]
262 start = perf_counter()
264 values = np.asarray([(container.get_ind_fitness(evaluated[i]).values[0] * container.fitness_weights[0],
265 *container.get_ind_features(evaluated[i]))
for i
in indices])
267 if not np.isfinite(normalized).all():
268 raise ValueError(
"Surrogate observations must be finite after scaling.")
278 candidate = evaluated[i]
279 descriptors = tuple(container.get_ind_features(candidate))
280 if (container.in_bounds(descriptors, container.features_domain)
281 and container.in_bounds(container.get_ind_fitness(candidate).values, container.fitness_domain)
282 and self.
_offer_to_grid(candidate, container.index_grid(descriptors))):