7"""Greedy batch expected archive improvement on a shared posterior sample."""
9from collections.abc
import Sequence
14from .bayesian
import BOPElites
15from .modern
import _positive_int
17__all__ = [
"BatchBOPElites"]
20def _sample_posterior(model, points, samples, rng):
21 mean, cov = model.predict(points, return_cov=
True)
22 eig, directions = np.linalg.eigh((cov + cov.T) * .5)
23 tolerance = max(np.max(abs(eig)), np.finfo(float).tiny) * 1e-7
24 if eig.min() < -tolerance:
25 raise ValueError(
"A Gaussian-process posterior covariance is not positive semidefinite.")
26 noise = rng.normal(size=(samples, len(points)))
27 return mean + (noise * np.sqrt(eig.clip(min=0.))) @ directions.T
30def _draw_cells(descriptors, shape, domain):
31 """Use native rectangular grid geometry and reserve an invalid-cell sentinel."""
32 lo, hi = np.asarray(domain, dtype=float).T
33 span = (hi - lo) / shape
34 finite = np.isfinite(descriptors).all(axis=-1)
35 valid = finite & ((descriptors >= lo) & (descriptors <= hi)).all(axis=-1)
36 clipped = np.where(valid[...,
None], descriptors, lo)
37 bins = np.minimum(((clipped - lo) / span).astype(int), np.asarray(shape) - 1)
38 indices = np.ravel_multi_index(tuple(np.moveaxis(bins, -1, 0)), shape)
39 return np.where(valid, indices, np.prod(shape))
42def _select_batch(cells, gains, size, joint):
43 """Select unique proposals by stable greedy marginal improvement."""
45 return np.argsort(-gains.mean(axis=0), kind=
"stable")[:size]
47 current = np.zeros_like(gains)
49 marginal = np.maximum(gains - current, 0.).mean(axis=0)
50 marginal[selected] = -np.inf
51 index = int(marginal.argmax())
52 selected.append(index)
54 same_cell = cells == cells[:, index:index + 1]
55 np.maximum(current, gains[:, index:index + 1], out=current, where=same_cell)
62 """Fit objective and descriptor models once per generation.
64 Draw correlated samples across the Sobol candidate pool for each
65 independent output GP. Greedily select a batch that maximizes the
66 expected sum of the largest improvement in each cell. Outside-grid
67 samples have zero gain. Only measured candidates can update
68 the archive. This variant works with native scalar fitness and
69 one or two direct descriptors.
71 :param container: Parentless best-only rectangular Grid.
72 :param budget: Maximum true-evaluation attempts.
73 :param dimension: Number of bounded decision variables.
74 :param ind_domain: Common finite decision interval.
75 :param quality_floor: Empty-cell threshold in signed weighted quality units.
76 :param batch_size: Maximum number of candidates in a generation.
77 :param candidates: Number of Sobol proposals scored jointly.
78 :param samples: Number of joint normal posterior draws per generation.
79 :param selection: Joint marginal improvement or independent top-k.
80 :param initial_samples: Minimum number of initial Sobol proposals.
81 :param seed: Seed for Sobol proposals and posterior draws.
82 :param kwargs: Native optimiser options.
85 def __init__(self, container, budget, dimension, ind_domain, quality_floor, *,
86 batch_size=4, candidates=96, samples=128, selection="joint",
87 initial_samples=None, seed=None, **kwargs):
89 candidates = _positive_int(candidates,
"candidates")
90 self.
samples = _positive_int(samples,
"samples")
91 if (selection
not in (
"joint",
"independent")
or candidates < self.
_bop_batch_size
92 or container.parents
or container.discard_random_on_bin_overload
93 or container.fitness_score_names
or container.features_score_names
94 or kwargs.keys() & {
"model_feasibility",
"descriptor_transform",
"latent_size",
"restarts",
95 "candidate_pool",
"posterior_samples"}):
96 raise ValueError(
"Use direct measurements, candidates >= batch_size, and joint or independent selection.")
97 task = kwargs.get(
"optimisation_task")
98 if isinstance(task, Sequence)
and not isinstance(task, str)
and tuple(task) == (0.,):
99 raise ValueError(
"Batch expected improvement needs a nonzero objective weight.")
101 lower, upper = map(float, ind_domain)
102 if not np.isfinite(upper - lower):
103 raise ValueError(
"The decision interval must have a finite width.")
104 spans = np.ptp(np.asarray(container.features_domain, dtype=float), axis=1)
105 if not (np.isfinite(spans).all()
and (spans / container.shape > 0.).all()):
106 raise ValueError(
"The descriptor grid must have finite positive cell widths.")
107 super().__init__(container, budget, dimension, (lower, upper), quality_floor, initial_samples=initial_samples,
108 candidate_pool=candidates, seed=seed, **kwargs)
111 """Reset posterior draws and generation-local proposals."""
116 def _pool(self, size):
118 for _
in range(32 * size):
121 pool.setdefault(key, point)
122 if len(pool) == size:
123 return np.asarray(tuple(pool.values()))
124 raise RuntimeError(
"Could not draw enough distinct Sobol candidates in the chosen decision interval.")
133 draws = np.stack([_sample_posterior(model, points, self.
samples, self.
_draw_rng)
136 cells = _draw_cells(draws[..., 1:], grid.shape, grid.features_domain)
138 cell_count = len(thresholds)
139 signed = draws[..., 0]
140 low, high = sorted(bound * grid.fitness_weights[0]
for bound
in grid.fitness_domain[0])
141 valid = (cells < cell_count) & (signed >= low) & (signed <= high)
142 gains = np.maximum(signed - np.r_[thresholds, 0.][cells], 0.)
143 gains = np.where(valid, gains, 0.)
144 indices = _select_batch(cells, gains, size, self.
selection ==
"joint")
149 self.
_seen.add(tuple(base_ind))
154 for slot, individual
in enumerate(evaluated):
Select one genuine evaluation with expected joint improvement of elites.
Optimize expected per-cell improvement of a whole batch.
_internal_ask(self, base_ind)
_commit_generation(self, evaluated)
_start_fixed_batch(self, size)