5"""CMA-MAEGA with separate centre and offspring evaluation phases."""
7from dataclasses
import dataclass
8from math
import isfinite
9from typing
import Sequence
15from .constrained
import _validate_grid
16from .modern
import CMAMAE
18__all__ = [
"GradientEvaluation",
"CMAMAEGA",
"CMAMEGA"]
22@dataclass(frozen=True)
24 """Measurements from a single gradient evaluation.
26 The Jacobian has one row for the objective followed by a row for each
27 descriptor. Columns follow the order of the genome coordinates.
31 descriptors: Sequence[float]
35def _gradient_basis(jacobian, objective_weight):
38 scale = np.max(np.abs(jacobian), axis=1, keepdims=
True)
39 rows = np.divide(jacobian, scale, out=np.zeros_like(jacobian), where=scale != 0)
40 rows[0] *= np.sign(objective_weight)
41 norms = np.linalg.norm(rows, axis=1, keepdims=
True)
42 return np.divide(rows, norms, out=rows, where=norms != 0)
48 """CMA-MAE with a gradient arborescence over the current centre.
50 Install the optional ``cma`` extra. Each centre evaluation consumes one
51 candidate slot. Subsequent offspring use the ordinary QDpy evaluator.
52 The centre and offspring batches each emit an iteration callback.
54 :param gradient_evaluate: Callable returning a GradientEvaluation.
55 :param step_size: Multiplier for the rank-weighted centre displacement.
56 :param sigma0: Initial step size in gradient coefficient coordinates.
57 :param kwargs: CMA-MAE options, including the reporting grid, bounds,
58 budget, initial point, batch size, threshold and archive learning rate.
61 def __init__(self, container, budget, x0, sigma0, batch_size, threshold_min, *,
62 gradient_evaluate, step_size=1.0, **kwargs):
63 if not callable(gradient_evaluate):
64 raise TypeError(
"gradient_evaluate must be callable.")
65 if not 0 < step_size < np.inf:
66 raise ValueError(
"step_size must be finite and positive.")
69 super().__init__(container, budget, x0, sigma0, batch_size, threshold_min, **kwargs)
72 """Reset the centre, coefficient strategy, and gradient evaluation count."""
81 """Return a copy of the current gradient search point."""
86 """Number of attempted centre evaluations, including failed calls."""
92 return size, evaluate, packed
96 """Return the centre, ready for a report through ``tell_dqd()``."""
97 if self.
_basis is not None:
98 raise RuntimeError(
"Complete an offspring batch before requesting another gradient.")
103 """Report a GradientEvaluation or ``None`` for a failed centre call."""
105 raise RuntimeError(
"Use ask_dqd() before tell_dqd().")
109 """Issue offspring after a successful centre evaluation."""
111 raise RuntimeError(
"Use ask_dqd() and tell_dqd() before asking for offspring.")
115 """Commit the pending offspring in proposal order."""
117 raise RuntimeError(
"Use tell_dqd() to report a centre evaluation.")
120 def _sample_vectors(self, size):
130 def _bounded(self, vectors):
133 def _centre_payload(self, result):
134 if not isinstance(result, GradientEvaluation):
135 raise TypeError(
"The centre evaluator must return a GradientEvaluation.")
136 count = len(self.
container.features_domain)
137 jacobian = np.asarray(result.jacobian, dtype=float)
138 descriptors = np.asarray(result.descriptors, dtype=float)
139 if jacobian.shape != (count + 1, self.
dimension)
or not np.all(np.isfinite(jacobian)):
140 raise ValueError(
"The centre Jacobian must be finite and match the objective and descriptors.")
141 if descriptors.shape != (count,)
or not np.all(np.isfinite(descriptors))
or not isfinite(result.fitness):
142 raise ValueError(
"The centre fitness and descriptor vector must be finite and match the grid.")
144 return (result.fitness,), descriptors
148 candidate, result, elapsed = records[0]
150 if result
is not None:
153 except (TypeError, ValueError, OverflowError)
as error:
154 warnings.warn(f
"Invalid gradient evaluation: {error}", stacklevel=2)
156 records = [(candidate, result, elapsed)]
159 def _restart_arborescence(self):
163 def _clear_generation(self):
164 super()._clear_generation()
170 if evaluated[0]
is None:
175 if len(evaluated) == self.
batch_size and any(ind
is not None for ind
in evaluated):
178 selected = selected[np.isfinite(self.
_gains[selected])]
180 weights = np.asarray(self.
_strategy.sp.weights[:len(selected)])
193 """Analytic CMA-MEGA, with Adam for the centre update by default.
195 Each branch generation uses one measured Jacobian at the centre.
196 New cells rank above same-cell improvements. Rejected offspring rank
197 below both. Offspring use the ordinary QDpy evaluator.
199 :param container: Empty best-only scalar Grid or CVTGrid without parents.
200 :param budget: Total candidate calls, including centre Jacobians.
201 :param x0: Starting point in genome coordinates.
202 :param sigma0: Initial standard deviation in coefficient space.
203 :param batch_size: Number of candidate branches per Jacobian.
204 :param gradient_evaluate: Callable returning a GradientEvaluation.
205 :param step_size: Learning rate for the centre update.
206 :param centre_optimizer: "adam" or the paper's plain "gradient" update.
207 :param kwargs: Native algorithm settings, including ind_domain and seed.
210 def __init__(self, container, budget, x0, sigma0, batch_size, *, gradient_evaluate,
211 step_size=.05, centre_optimizer="adam", **kwargs):
212 _validate_grid(container)
213 if container.parents:
214 raise ValueError(
"Use an empty parentless best-only archive for CMA-MEGA.")
215 if centre_optimizer
not in (
"adam",
"gradient"):
216 raise ValueError(
"centre_optimizer must be 'adam' or 'gradient'.")
218 if container.fitness_weights
is not None:
219 kwargs.setdefault(
"optimisation_task", tuple(container.fitness_weights))
220 super().__init__(container, budget, x0, sigma0, batch_size, 0.,
221 gradient_evaluate=gradient_evaluate, step_size=step_size, **kwargs)
223 def _reset_moments(self):
224 self.
_first = np.zeros_like(self.
x0)
229 """Reset the coefficient distribution, centre, and Adam state."""
233 def _restart_arborescence(self):
236 if self.
container else self.
x0, dtype=float)).copy()
239 def _move_centre(self, direction):
246 direction = first / (np.sqrt(second) + 1e-8)
251 """Return the best measured candidate in each occupied cell."""
252 return {cell: front[0]
for cell, front
in self.
container.solutions.items()
if front}
255 """Return signed incumbent fitness, or negative infinity for an empty cell."""
260 self.
_gains = np.full(len(evaluated), -np.inf)
261 statuses = np.zeros(len(evaluated), dtype=int)
264 for index, candidate
in enumerate(evaluated):
265 if candidate
is None:
267 cell = self.
container.index_grid(candidate)
269 value = direction * self.
container.get_ind_fitness(candidate).values[0]
271 self.
_gains[index] = value
if new_cell
else value - self.
threshold(cell)
273 statuses[index] = 2
if new_cell
else 1
277 if evaluated[0]
is None:
284 order = np.lexsort((-self.
_gains, -statuses))
285 losses = np.empty(len(order), dtype=int)
286 losses[order] = np.arange(len(order))
288 selected = selected[np.isfinite(self.
_gains[selected])]
290 weights = np.asarray(self.
_strategy.sp.weights[:len(selected)])
292 self.
_move_centre(np.average(moves, axis=0, weights=weights))
294 if not admitted
or self.
_strategy.stop():
Adapt coefficients on a basis of objective and descriptor gradients.
ask_batch(self, size=None)
_receive_fixed_batch(self, records, verbose, batch_start_time)
_commit_generation(self, evaluated)
gradient_evaluations(self)
_centre_payload(self, result)
_fixed_batch_plan(self, size, evaluate, packed)
tell_dqd(self, result)
Report the gradient evaluation for the pending centre.
tell_batch(self, results)
int _gradient_evaluations
_restart_arborescence(self)
ask_dqd(self)
Issue the current centre for a gradient evaluation.
Adapt gradient coefficient samples by best-only archive improvement.
_move_centre(self, direction)
_commit_generation(self, evaluated)
Raw objective, descriptors, and their derivatives at a search point.
Adapt a covariance matrix using annealed cell-level improvement.
_update_annealed_archive(self, evaluated)
_adapt_strategy(self, vectors)
_new_strategy(self, center, *, bounded=True)
_offer_to_grid(self, individual, cell)