QDpy
Loading...
Searching...
No Matches
surrogate.py
Go to the documentation of this file.
1# This file is part of qdpy.
2#
3# qdpy is free software: you can redistribute it and/or modify
4# it under the terms of the GNU Lesser General Public License as
5# published by the Free Software Foundation, either version 3 of
6# the License, or (at your option) any later version.
7#
8# qdpy is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11# GNU Lesser General Public License for more details.
12#
13# You should have received a copy of the GNU Lesser General Public
14# License along with qdpy. If not, see <http://www.gnu.org/licenses/>.
15
16
18
19"""TODO""" # TODO
20
21__all__ = ["SurrogateAssistedAlg", "SAIL"]
22
23
24
25
26import abc
27from timeit import default_timer as timer
28from typing import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, Mapping, MutableMapping, overload
29import warnings
30import numpy as np
31import random
32import copy
33from functools import partial
34from sklearn.gaussian_process import GaussianProcessRegressor
35
36
37from .base import *
38from .evolution import *
39from qdpy.utils import *
40from qdpy.phenotype import *
41from qdpy.base import *
42from qdpy.containers import *
43from qdpy import tools
44
45
46
47
48
50 """Combine an evaluator-facing search with one or more surrogate searches.
51
52 The illumination algorithm provides initial and fallback candidates.
53 The acquisition algorithm searches using surrogate predictions. The
54 wrapper keeps evaluated candidates in the illumination archive and
55 forwards feedback to the illumination algorithm.
56
57 :param illumination_algo: Algorithm to receive genuine evaluations.
58 :param acquisition_algo: Search used to propose surrogate candidates.
59 :param prediction_algo: Predictor-side search. Defaults to a copy of
60 the acquisition configuration.
61 :param max_selected_acquisition_suggestions: Cap on proposals selected
62 from an acquisition result.
63 :param budget_not_suggested_by_surrogate: Number of initial
64 evaluations supplied by the illumination algorithm.
65 """
66
67 _illumination_algo: QDAlgorithm
68 _acquisition_algo: QDAlgorithm
69 _prediction_algo: Optional[QDAlgorithm]
70 max_selected_acquisition_suggestions: float # float instead of int to allow `np.inf`
71 budget_not_suggested_by_surrogate: float # float instead of int to allow `np.inf`
72
73
74 def __init__(self,
75 illumination_algo: QDAlgorithm,
76 acquisition_algo: QDAlgorithm,
77 prediction_algo: Optional[QDAlgorithm] = None,
78 max_selected_acquisition_suggestions: float = np.inf,
79 budget_not_suggested_by_surrogate: float = np.inf,
80 **kwargs):
81 self._illumination_algo = illumination_algo
82 self._acquisition_algo = acquisition_algo
83 self._prediction_algo = prediction_algo if prediction_algo else copy.deepcopy(self._acquisition_algo)
84 self.max_selected_acquisition_suggestions = max_selected_acquisition_suggestions
85 self.budget_not_suggested_by_surrogate = budget_not_suggested_by_surrogate
86
87 kwargs2 = copy.deepcopy(kwargs)
88 def del_if_exists(keys: Sequence[str]) -> None:
89 for k in keys:
90 if k in kwargs2:
91 del kwargs2[k]
92 del_if_exists(["container", "budget", "dimension", "batch_size", "nb_objectives", "optimisation_task", "base_ind_gen"])
93
94 super().__init__(illumination_algo.container, illumination_algo.budget,
95 dimension=illumination_algo.dimension, batch_size=illumination_algo.batch_size,
96 nb_objectives=illumination_algo._nb_objectives, optimisation_task=illumination_algo.optimisation_task,
97 base_ind_gen=illumination_algo._base_ind_gen, **kwargs2)
98
99
100 @property
101 def illumination_algo(self) -> QDAlgorithm:
102 """Search that supplies native candidates and consumes true evaluation feedback."""
103 return self._illumination_algo
104
105 @property
106 def acquisition_algo(self) -> QDAlgorithm:
107 """Search that explores the acquisition function."""
108 return self._acquisition_algo
109
110 @property
111 def prediction_algo(self) -> Optional[QDAlgorithm]:
112 """Configured prediction-side search, if available."""
113 return self._prediction_algo
114
115
116 @abc.abstractmethod
117 def _compute_acquisition(self) -> List[IndividualLike]:
118 """Compile and return acquisition suggestions."""
119 raise NotImplementedError("`self._compute_acquisition` must be implemented by sub-classes")
120
121
122 def _select_suggestions_from_acquisition(self, acquisition_suggestions: List[IndividualLike],
123 nb_suggestions: int) -> List[IndividualLike]:
124 """Select `nb_suggestions` from `acquisition_suggestions` to be used as suggestions for `self._illumination_algo`.
125 By default, select randomly (uniformly) `self.max_selected_acquisition_suggestions` individuals among `acquisition_suggestions`.
126
127 Parameters
128 ----------
129 :param acquisition_suggestions: Sequence[IndividualLike]
130 The sequence of proposed suggestions from acquisition.
131 :param nb_suggestions: int
132 The maximal number of suggestions to include in the resulting sequence of suggestions.
133 """
134 nb = int(min(nb_suggestions, self.max_selected_acquisition_suggestions))
135 if len(acquisition_suggestions) <= nb:
136 return acquisition_suggestions
137 else:
138 random.shuffle(acquisition_suggestions)
139 return acquisition_suggestions[:nb]
140
141
143 """Compute all suggestions for the current batch and store them in `self._batch_inds`."""
144 # Compute acquisition if the container is not empty
145 acquisition_suggestions: List[IndividualLike] = self._compute_acquisition() if len(self.container) > 0 else []
146 # Select suggestions from the acquisition container
147 self._batch_inds.extend(self._select_suggestions_from_acquisition(acquisition_suggestions, self.batch_size))
148 # If not enough suggestions were obtained from acquisition, ask `self._illumination_algo` for suggestions.
149 nb_not_suggested_by_surrogate = int(min(self.budget_not_suggested_by_surrogate, self.batch_size - len(self._batch_inds)))
150 for _ in range(nb_not_suggested_by_surrogate):
151 self._batch_inds.append(self._illumination_algo.ask())
152
153
154 def _internal_tell(self, individual: IndividualLike, added_to_container: bool, xattr: Mapping[str, Any] = {}) -> None:
155 self._illumination_algo._tell_after_container_update(individual, added_to_container, xattr)
156
157
158
159@registry.register
161 """Use a Gaussian process to propose candidates for expensive evaluation.
162
163 Fit the regressor on retained genomes and concatenate each genome's
164 objective and descriptor values as the training targets. For
165 acquisition, combine each predicted mean with ``ucb_stddev`` times
166 its predictive standard deviation. Evaluate the selected acquisition
167 proposals with the original evaluator before final admission.
168
169 Supply enough genuine evaluations to populate the illumination
170 archive before the first surrogate fit.
171 """
172
173 ucb_stddev: float
174 _gp: Any
175
176 def __init__(self, ucb_stddev: float = 1.0, **kwargs):
177 super().__init__(**kwargs)
178 self.ucb_stddev = ucb_stddev
179 self._gp = None
180
181 def __getstate__(self):
182 odict = super().__getstate__()
183 del odict['_gp']
184 return odict
185
186
187
193 def _acquisition_eval_fn(self, inds: Sequence[IndividualLike]) -> Sequence[Tuple[FitnessValuesLike, FeaturesValuesLike]]:
194 with warnings.catch_warnings():
195 warnings.simplefilter("ignore")
196 y_mean, y_std = self._gp.predict(np.array(inds), return_std = True)
197 if y_std.ndim == 1 and y_mean.ndim == 2:
198 y_std = y_std[:, None]
199 ucb_val = y_mean + self.ucb_stddev * y_std
200 if ucb_val.ndim == 1:
201 ucb_val = ucb_val[:, None]
202 res = []
203 for i in range(len(inds)):
204 fitness = []
205 for j in range(self._nb_objectives):
206 fitness.append(ucb_val[i, j])
207 features = []
208 for j in range(ucb_val.shape[1] - self._nb_objectives):
209 features.append(ucb_val[i, j + self._nb_objectives])
210 res.append((fitness, features))
211 return res
212
213
214 def _create_gaussian_regressor(self) -> None:
215 # Create dataset
216 dataX = []
217 dataY = []
218 for ind in self.container:
219 dataX.append(ind)
220 fitness = self.container.get_ind_fitness(ind)
221 descriptors = self.container.get_ind_features(ind)
222 dataY.append(list(fitness.values) + list(descriptors))
223 # Fit gaussian process on the dataset
224 self._gp = GaussianProcessRegressor()
225 with warnings.catch_warnings():
226 warnings.simplefilter("ignore")
227 self._gp.fit(dataX, dataY)
228
229
230 def _compute_acquisition(self) -> List[IndividualLike]:
231 """Compile and return acquisition suggestions."""
232 # Reinit `self._acquisition_algo`
233 self._acquisition_algo.container.clear()
234 # TODO reinit ??
235
236 # Create gaussian regressor
238 # Run `self._acquisition_algo` optimisation process
239 try:
240 self._acquisition_algo.optimise(self._acquisition_eval_fn, executor=None, send_several_suggestions_to_fn=True)
241 except RuntimeError:
242 pass
243 # Retrieve new suggestions
244 suggestions = copy.deepcopy(list(set(self._acquisition_algo.container) - set(self.container)))
245 for ind in suggestions:
246 ind.reset()
247 #del ind.fitness.values
248 #ind.features = ()
249 #print("DEBUG _compute_acquisition", len(suggestions))
250 return suggestions
251
252
253 # TODO sobol
254 def _select_suggestions_from_acquisition(self, acquisition_suggestions: List[IndividualLike],
255 nb_suggestions: int) -> List[IndividualLike]:
256 """Select `nb_suggestions` from `acquisition_suggestions` to be used as suggestions for `self._illumination_algo`.
257 By default, select randomly (uniformly) `self.max_selected_acquisition_suggestions` individuals among `acquisition_suggestions`.
258
259 Parameters
260 ----------
261 :param acquisition_suggestions: Sequence[IndividualLike]
262 The sequence of proposed suggestions from acquisition.
263 :param nb_suggestions: int
264 The maximal number of suggestions to include in the resulting sequence of suggestions.
265 """
266 nb = int(min(nb_suggestions, self.max_selected_acquisition_suggestions))
267 if len(acquisition_suggestions) <= nb:
268 return acquisition_suggestions
269 else:
270 random.shuffle(acquisition_suggestions)
271 return acquisition_suggestions[:nb]
272
273
274
275
276# MODELINE "{{{1
277# vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8
278# vim:foldmethod=marker
IndividualLike optimise(self, Callable evaluate, Optional[int] budget=None, bool batch_mode=True, Optional[ExecutorLike] executor=None, bool send_several_suggestions_to_fn=False, int max_nb_suggestions_per_call=10, bool verbose=False)
Definition base.py:779
IndividualLike ask(self)
Definition base.py:481
None _tell_after_container_update(self, IndividualLike individual, bool added, Mapping[str, Any] xattr={})
Account for a completed tell and send feedback.
Definition base.py:630
List[IndividualLike] _select_suggestions_from_acquisition(self, List[IndividualLike] acquisition_suggestions, int nb_suggestions)
Definition surrogate.py:255
List[IndividualLike] _compute_acquisition(self)
Definition surrogate.py:230
SURROGATE-ASSISTED ALGORITHMS ########### {{{1.
Definition surrogate.py:49
List[IndividualLike] _select_suggestions_from_acquisition(self, List[IndividualLike] acquisition_suggestions, int nb_suggestions)
Definition surrogate.py:123
List[IndividualLike] _compute_acquisition(self)
Definition surrogate.py:117
Optional[QDAlgorithm] prediction_algo(self)
Definition surrogate.py:111
None _internal_tell(self, IndividualLike individual, bool added_to_container, Mapping[str, Any] xattr={})
Definition surrogate.py:154