QDpy
Loading...
Searching...
No Matches
omg_mega.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Use the gradients of retained elites to illuminate a fixed descriptor grid."""
7
8from math import isfinite
9import warnings
10
11import numpy as np
12
13from qdpy.base import registry
14from .constrained import _validate_grid
15from .differentiable import GradientEvaluation, _gradient_basis
16from .modern import _FixedGeneration, _bounds, _positive_int
17
18__all__ = ["OMGMEGA"]
19
20_BASIS_SCORE = "omg_mega_gradient_basis"
21
22
23
24@registry.register
26 """Draw Gaussian coefficients and use the absolute coefficient for fitness.
27
28 One combined evaluator call yields a GradientEvaluation for each
29 candidate. Its normalized Jacobian is stored with the candidate if
30 admitted, so future offspring reuse the measured basis. Descriptor
31 coefficients remain signed. The fitness row follows the configured
32 optimization direction.
33
34 :param container: Empty parentless best-only Grid or CVTGrid with one objective.
35 :param budget: Combined fitness, descriptor, and Jacobian calls.
36 :param dimension: Number of decision variables.
37 :param sigma: Standard deviation of the sampled coefficients.
38 :param batch_size: Number of candidates proposed before a generation commits.
39 :param ind_domain: Shared decision bounds for sampling and clipping.
40 :param seed: Private seed for initialization, selection, and gradient coefficients.
41 :param kwargs: Native QDAlgorithm settings.
42 """
43
44 _requires_proposed_genome = True
45
46 def __init__(self, container, budget, dimension, *, sigma=.1, batch_size=1,
47 ind_domain=(0., 1.), seed=0, **kwargs):
48 _validate_grid(container)
49 if container.parents or container.fitness_score_names or container.features_score_names:
50 raise ValueError("Use a parentless archive with native fitness and descriptors.")
51 self.ind_domain = _bounds(ind_domain)
52 if not isfinite(self.ind_domain[1] - self.ind_domain[0]) or not 0. < sigma < np.inf:
53 raise ValueError("Use finite decision spans and a positive finite sigma.")
54 self.sigma, self.seed = sigma, seed
55 if container.fitness_weights is not None:
56 kwargs.setdefault("optimisation_task", tuple(container.fitness_weights))
57 super().__init__(container, _positive_int(budget, "budget"),
58 dimension=_positive_int(dimension, "dimension"),
59 batch_size=_positive_int(batch_size, "batch_size"), **kwargs)
60 if not self._fitness_weights[0]:
61 raise ValueError("A nonzero scalar fitness weight is required.")
62
63 def reinit(self):
64 """Reset the proposal stream while retaining measured elite bases."""
65 super().reinit()
66 self._rng = np.random.default_rng(self.seed)
67
68 @property
70 """Return combined evaluation attempts, including failed gradient calls."""
71 return self.nb_evaluations
72
73 def _internal_ask(self, base_ind):
74 if self.container:
75 parent = self.container[self._rng.integers(len(self.container))]
76 basis = np.asarray(parent.scores[_BASIS_SCORE])
77 coefficients = self._rng.normal(0., self.sigma, len(basis))
78 coefficients[0] = abs(coefficients[0])
79 base_ind[:] = np.clip(np.asarray(parent) + coefficients @ basis, *self.ind_domain)
80 else:
81 base_ind[:] = self._rng.uniform(*self.ind_domain, size=self.dimension)
82 return base_ind
83
84 def _payload(self, result):
85 if not isinstance(result, GradientEvaluation):
86 raise TypeError("The evaluator must return a GradientEvaluation.")
87 fitness = float(result.fitness)
88 descriptors = np.asarray(result.descriptors, dtype=float)
89 jacobian = np.asarray(result.jacobian, dtype=float)
90 width = len(self.container.features_domain)
91 if (descriptors.shape != (width,) or jacobian.shape != (width + 1, self.dimension)
92 or not isfinite(fitness) or not np.isfinite(descriptors).all() or not np.isfinite(jacobian).all()):
93 raise ValueError("Supply finite fitness, descriptors, and a Jacobian matching the archive and genome.")
94 basis = _gradient_basis(jacobian, self._fitness_weights[0])
95 return (fitness,), descriptors, {_BASIS_SCORE: tuple(tuple(row) for row in basis)}
96
97 def _check_candidate(self, individual):
98 super()._check_candidate(individual)
99 self.container.index_grid(individual)
100
101 def _receive_fixed_batch(self, records, verbose, batch_start_time):
102 staged = []
103 for individual, result, elapsed in records:
104 if result is not None:
105 try:
106 result = self._payload(result)
107 except (TypeError, ValueError, OverflowError) as error:
108 warnings.warn(f"Invalid gradient evaluation: {error}", stacklevel=2)
109 result = None
110 staged.append((individual, result, elapsed))
111 super()._receive_fixed_batch(staged, verbose, batch_start_time)
Vary an archived elite along normalized objective and descriptor gradients.
Definition omg_mega.py:25
_receive_fixed_batch(self, records, verbose, batch_start_time)
Definition omg_mega.py:101
_internal_ask(self, base_ind)
Definition omg_mega.py:73