QDpy
Loading...
Searching...
No Matches
bayesian_batch.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
6
7"""Greedy batch expected archive improvement on a shared posterior sample."""
8
9from collections.abc import Sequence
10
11import numpy as np
12
13from qdpy.base import registry
14from .bayesian import BOPElites
15from .modern import _positive_int
16
17__all__ = ["BatchBOPElites"]
18
19
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
28
29
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))
40
41
42def _select_batch(cells, gains, size, joint):
43 """Select unique proposals by stable greedy marginal improvement."""
44 if not joint:
45 return np.argsort(-gains.mean(axis=0), kind="stable")[:size]
46 selected = []
47 current = np.zeros_like(gains)
48 for _ in range(size):
49 marginal = np.maximum(gains - current, 0.).mean(axis=0)
50 marginal[selected] = -np.inf
51 index = int(marginal.argmax())
52 selected.append(index)
53 # Keep the best selected gain for each proposal's sampled cell.
54 same_cell = cells == cells[:, index:index + 1]
55 np.maximum(current, gains[:, index:index + 1], out=current, where=same_cell)
56 return selected
57
58
59
60@registry.register
62 """Fit objective and descriptor models once per generation.
63
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.
70
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.
83 """
84
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):
88 self._bop_batch_size = _positive_int(batch_size, "batch_size")
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.")
100 self.selection = selection
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)
109
110 def reinit(self):
111 """Reset posterior draws and generation-local proposals."""
112 super().reinit()
113 self._draw_rng = np.random.default_rng(self.seed)
114 self._points = []
115
116 def _pool(self, size):
117 pool = {}
118 for _ in range(32 * size):
119 point = self._sobol_point()
120 key = tuple(self._raw_point(point))
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.")
125
126 def _start_fixed_batch(self, size):
127 super()._start_fixed_batch(size)
128 if self.nb_suggestions < self.initial_samples or self.n_observations < 2:
129 self._points = self._pool(size)
130 return
131
132 points = self._pool(self.candidate_pool)
133 draws = np.stack([_sample_posterior(model, points, self.samples, self._draw_rng)
134 for model in self._fit_models()], axis=-1)
135 grid = self.container
136 cells = _draw_cells(draws[..., 1:], grid.shape, grid.features_domain)
137 thresholds = self._thresholds()
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")
145 self._points = points[indices]
146
147 def _internal_ask(self, base_ind):
148 base_ind[:] = self._raw_point(self._points[len(self._issued)])
149 self._seen.add(tuple(base_ind))
150 return base_ind
151
152 def _commit_generation(self, evaluated):
153 admitted = set()
154 for slot, individual in enumerate(evaluated):
155 self._unit_candidate = self._points[slot]
156 # Report no single-cell prediction for a joint acquisition.
157 if super()._commit_generation((individual,)):
158 admitted.add(slot)
159 return admitted
Select one genuine evaluation with expected joint improvement of elites.
Definition bayesian.py:99
Optimize expected per-cell improvement of a whole batch.