QDpy
Loading...
Searching...
No Matches
legacy.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"""Old preliminary code. It is not documented and will be removed in the future."""
20
21
22
23import math
24import numpy as np
25import sys
26import copy
27import os
28import pickle
29import time
30import gc
31from scipy.spatial.distance import euclidean
32from sklearn.cluster import KMeans
33from sklearn.gaussian_process import GaussianProcessRegressor
34import itertools
35from timeit import default_timer as timer
36
37#import matplotlib as mpl
38#mpl.use('Agg')
39import matplotlib.pyplot as plt
40from mpl_toolkits.axes_grid1 import make_axes_locatable
41
42from functools import reduce
43import operator
44import random
45import warnings
46
47import qdpy.hdsobol as hdsobol
48from qdpy.utils import *
49
50
51
52@jit(nopython=True)
53def mutateUniformInt(ind, mutationPb, indBounds):
54 """Replace selected coordinates in place with integers drawn from a half-open interval."""
55 for i in range(len(ind)):
56 if np.random.random() < mutationPb:
57 ind[i] = np.random.randint(indBounds[0], indBounds[1])
58
59@jit(nopython=True)
60def mutateUniform(ind, mutationPb, indBounds):
61 """Replace selected coordinates in place with uniformly drawn real values."""
62 for i in range(len(ind)):
63 if np.random.random() < mutationPb:
64 ind[i] = np.random.uniform(indBounds[0], indBounds[1])
65
66@jit(nopython=True)
67def generateUniformInt(dimension, indBounds, nb):
68 """Generate integer genomes with both integer endpoints included."""
69 res = []
70 for i in range(nb):
71 res.append(np.random.randint(indBounds[0], indBounds[1] + 1, dimension))
72 return res
73
74@jit(nopython=True)
75def generateUniform(dimension, indBounds, nb):
76 """Generate a batch of real genomes uniformly within the given interval."""
77 res = []
78 for i in range(nb):
79 res.append(np.random.uniform(indBounds[0], indBounds[1], dimension))
80 return res
81
82@jit(nopython=True)
83def generateSparseUniform(dimension, indBounds, nb, sparsity):
84 """Generate uniform genomes and set each coordinate to zero with the given sparsity probability."""
85 res = []
86 for i in range(nb):
87 base = np.random.uniform(indBounds[0], indBounds[1], dimension)
88 mask = np.random.uniform(0., 1., dimension)
89 base[mask < sparsity] = 0.
90 res.append(base)
91 return res
92
93def generateSobol(dimension, indBounds, nb):
94 """Generate and scale the requested number of origin-free Sobol genomes."""
95 res = hdsobol.gen_sobol_vectors(nb, dimension)
96 res = res * (indBounds[1] - indBounds[0]) + indBounds[0]
97 return res
98
99def generateBinarySobol(dimension, indBounds, nb, cutoff = 0.50):
100 """Threshold the requested number of Sobol vectors to generate binary genomes."""
101 res = hdsobol.gen_sobol_vectors(nb, dimension)
102 res = (res > cutoff).astype(int)
103 return res
104
105
106
107
108
109
110
111class MapElites(object):
112 """Run the original maximising MAP-Elites API with explicit array storage.
113
114 An evaluator receives a genome and evaluation ID, then returns
115 fitness followed by the descriptor coordinates. The algorithm uses
116 fitter entries to replace cell incumbents and exposes arrays of
117 performances and features plus a mapping of retained solutions.
118
119 The native ask/tell API uses separate algorithms and containers. Use
120 the legacy result keys when working with this implementation.
121 """
122 def __init__(self, dimension, evalFn, nbBins, featuresBounds = [(0., 1.)], initBatchSize = 120, batchSize=40, nbIterations = 10, indBounds = (0, 100), mutationPb = 0.2, savePeriod = 0, logBasePath = ".", reevalTimeout = None, mutate = None, initiate = None, iterationFilenames = "iteration-%i.p", finalFilename = "final.p", fitnessBounds = (0., 1.), parallelismType = "multiprocessing", completelyNewGenomePb = 0.0):
123 self.dimension = dimension
124 self.evalFn = evalFn
125 self.nbBins = nbBins
126 self.featuresBounds = featuresBounds
127 self.initBatchSize = initBatchSize
128 self.nbIterations = nbIterations
129 self.batchSize = batchSize
130 self.indBounds = indBounds
131 self.mutationPb = mutationPb
132 self.savePeriod = savePeriod
133 self.logBasePath = logBasePath
134 self.reevalTimeout = reevalTimeout
135 self.mutate = mutate
136 self.initiate = initiate
137 self.iterationFilenames = iterationFilenames
138 self.finalFilename = finalFilename
139 self.fitnessBounds = fitnessBounds
140 self.callEvalFnOnEntierBatch = False
141 self.parallelismType = parallelismType
142 self.completelyNewGenomePb = completelyNewGenomePb
143 self.reinit()
144
145 def __del__(self):
146 self._closePool()
147
148 def __getstate__(self):
149 odict = self.__dict__.copy()
150 if 'pool' in odict:
151 del odict['pool']
152 del odict['map']
153 return odict
154
155 def _closePool(self):
156 if hasattr(self, 'pool'):
157 self.pool.close()
158 self.pool.terminate()
159
160 def _initParallelism(self):
161 if self.parallelismType == "none":
162 #import itertools
163 self.map = map #itertools.starmap
164 elif self.parallelismType == "multiprocessing":
165 import multiprocessing
166 self._closePool()
167 self.pool = multiprocessing.Pool()
168 self.map = self.pool.map #self.pool.starmap
169 elif self.parallelismType == "scoop":
170 import scoop
171 self.map = scoop.futures.map
172 else:
173 raise Exception("Unknown parallelismType: '%s'" % self.parallelismType)
174
175
176 def reinit(self):
177 """Start a fresh legacy run with an empty archive, evaluation counters, and its configured executor."""
178 if not hasattr(self, '_infoToSave'):
179 self._infoToSave = {}
180 self._initParallelism()
181 self._unfinishedEvals = 0
182 self._evalId = itertools.count()
183 if not self.mutate:
184 self.mutate = mutateUniformInt
185 if not self.initiate:
186 self.initiate = self._defaultInitiation
187 self.totalElapsed = 0.
188
189 self.initPop = []
190 assert(self.nbIterations > 0)
191 self.currentIteration = 0
192 self.currentEvaluation = 0
193 if self.nbBins == None:
194 self.nbBins = np.repeat(10, len(self.featuresBounds))
195 assert(len(self.featuresBounds) == len(self.nbBins))
196 #self._binsSize = [(self.featuresBounds[1] - self.featuresBounds[0]) / float(b) for b in self.nbBins]
197 self._binsSize = [(self.featuresBounds[bi][1] - self.featuresBounds[bi][0]) / float(self.nbBins[bi]) for bi in range(len(self.nbBins))]
198 assert(len(self.nbBins))
199 self.performances = np.full(self.nbBins, self.fitnessBounds[0]) #np.zeros(shape=self.nbBins)
200 self.features = np.zeros(shape=list(self.nbBins) + [len(self.nbBins)])
201 self.solutions = {}
202 self.bestInIteration = None
204 self.bestEver = None
205 self.bestEverFitness = self.fitnessBounds[0]
206 self.containerSize = reduce(operator.mul, self.nbBins)
207 self.nbEmptyBins = self.containerSize
208
209 def _valsToElitesIndex(self, vals):
210 index = []
211 assert(len(vals) == len(self.nbBins))
212 for i in range(len(vals)):
213 normalisedVal = vals[i] - self.featuresBounds[i][0]
214 if normalisedVal == self.featuresBounds[i][1] - self.featuresBounds[i][0]:
215 partial = self.nbBins[i] - 1
216 elif not 0 <= normalisedVal < self.featuresBounds[i][1] - self.featuresBounds[i][0]:
217 print("WARNING: feature %i out of bounds: %s" % (i, vals))
218 return None
219 else:
220 partial = int(normalisedVal / self._binsSize[i])
221 index.append(partial)
222 return tuple(index)
223
224 def _asyncEvalFnWrapper(self, ind, expeId):
225 def startEval(newInd):
226 startTime = timer()
227 res = self.evalFn(ind, expeId)
228 endTime = timer()
229 elapsed = endTime - startTime
230 return elapsed, res
231 totalElapsed = 0.
232 currentInd = ind
233 while(True): # XXX bad !
234 elapsed, res = startEval(currentInd)
235 totalElapsed += elapsed
236 if self.reevalTimeout and self.reevalTimeout > totalElapsed:
237 fitness = res[0]
238 if fitness <= 0.000001:
239 # Perform a reevaluation
240 print("Performed a Reevaluation after:%f sec" % totalElapsed)
241 self.mutate(currentInd, self.mutationPb, self.indBounds)
242 sys.stdout.flush()
243 continue
244 else:
245 return currentInd, res
246 else:
247 return currentInd, res
248
249 def _evalFnWrapper(self, vals):
250 ind, expeId = vals
251 return self.evalFn(ind, expeId)
252
253 def _evaluatePop(self, pop):
254 startTime = timer()
255 pop = np.unique(pop, axis=0)
256 listEvalIds = list(next(self._evalId) for _ in pop)
257 # Evaluate the individuals
258 #popFitnesses = np.array(self.map(self.evalFn, pop)) #self.toolbox.map(self.toolbox.evaluate, pop)
259 #popFitnesses = np.array(self.map(self.evalFn, list(zip(pop, listEvalIds)))) #self.toolbox.map(self.toolbox.evaluate, pop)
260 #resFromEvals = self.map(self._evalFnWrapper, list(zip(pop, listEvalIds)))
261 #popFinalInds, popFitnesses = zip(*resFromEvals)
262
264 popFitnesses = np.array(list(self.evalFn(pop, listEvalIds)))
265 else:
266 #popFitnesses = self.map(self.evalFn, list(zip(pop, listEvalIds)))
267 popFitnesses = self.map(self._evalFnWrapper, list(zip(pop, listEvalIds)))
268 #nbMaxEvalsPerRound = 1000
269 #if len(listEvalIds) > nbMaxEvalsPerRound:
270 # nbRounds = int(len(listEvalIds) / nbMaxEvalsPerRound)
271 # popFitnesses = []
272 # for i in range(nbRounds):
273 # fitList = self.map(self.evalFn, list(zip(pop[i * nbMaxEvalsPerRound: (i+1) * nbMaxEvalsPerRound], listEvalIds[i * nbMaxEvalsPerRound: (i+1) * nbMaxEvalsPerRound])))
274 # popFitnesses += fitList
275 # # Perform garbage collection
276 # while gc.collect() > 0:
277 # pass
278 #else:
279 # popFitnesses = self.map(self.evalFn, list(zip(pop, listEvalIds)))
280 while gc.collect() > 0:
281 pass
282
283 popFitnesses = np.array(list(popFitnesses))
284 popPerformances = popFitnesses[:,0]
285 popFeatures = popFitnesses[:,1:]
286 # Record individuals
287 for indIndex in range(len(pop)):
288 ind = pop[indIndex]
289 elitesIndex = self._valsToElitesIndex(popFeatures[indIndex])
290 if elitesIndex == None:
291 continue
292 if self.performances[elitesIndex] < popPerformances[indIndex]:
293 self.solutions[elitesIndex] = ind
294 self.performances[elitesIndex] = popPerformances[indIndex]
295 self.features[elitesIndex] = popFeatures[indIndex]
296 if popPerformances[indIndex] > self.bestInIterationFitness:
297 self.bestInIterationFitness = popPerformances[indIndex]
298 self.bestInIteration = ind
301 self.bestEver = self.bestInIteration
302 self.nbEmptyBins = self.containerSize - len(self.solutions.keys())
303 endTime = timer()
304 elapsed = endTime - startTime
305 #return popFinalInds, self.bestInIterationFitness, elapsed
306 return self.bestInIterationFitness, elapsed
307
308
309 def _evaluateIndAsync(self, ind = None):
310 if ind is None:
311 currentElites = list(self.solutions.values())
312 if not len(currentElites):
313 raise ValueError("No elites were found in initial batch !")
314 ind = copy.deepcopy(currentElites[np.random.randint(0, len(currentElites))])
315 self.mutate(ind, self.mutationPb, self.indBounds)
316 #print("DEBUGasync: ", ind)
317 evalId = next(self._evalId)
318 self._unfinishedEvals += 1
319 asyncResFromEval = self.pool.apply_async(self._asyncEvalFnWrapper, [ind, evalId], callback = self._evaluateIndAsyncCallback)
320 return asyncResFromEval
321
322 def _evaluateIndAsyncCallback(self, param):
323 ind, res = param
324 #print("DEBUGasyncC1: ", res)
325 performance = res[0]
326 features = res[1:]
327 elitesIndex = self._valsToElitesIndex(features)
328 if self.performances[elitesIndex] < performance:
329 self.solutions[elitesIndex] = ind
330 self.performances[elitesIndex] = performance
331 self.features[elitesIndex] = features
332 if performance > self.bestInIterationFitness:
333 self.bestInIterationFitness = performance
334 self.bestInIteration = ind
335 # Update bestever
338 self.bestEver = self.bestInIteration
339 self.nbEmptyBins = self.containerSize - len(self.solutions.keys())
340
341 self._unfinishedEvals -= 1
342 self.currentEvaluation += 1
343 #print("DEBUGasyncC2: ", self._unfinishedEvals, self.currentEvaluation, (self.currentEvaluation - self.initBatchSize) % self.batchSize)
344 sys.stdout.flush()
345 if self.currentEvaluation == self.initBatchSize:
346 # Verify if the initial batch is finished
347 print("#0 bestInBatch:%f bestEver:%f" % (self.bestInIterationFitness, self.bestInIterationFitness))
348 sys.stdout.flush()
349 elif self.currentEvaluation > self.initBatchSize and (self.currentEvaluation - self.initBatchSize) % self.batchSize == 0:
350 # Verify if this iteration is finished
351 self.currentIteration += 1
352 print("#%i bestInBatch:%f bestEver:%f" % (self.currentIteration, self.bestInIterationFitness, self.bestEverFitness))
353 sys.stdout.flush()
354 if self.savePeriod and np.mod(self.currentIteration, self.savePeriod) == 0:
355 #print("DEBUGasyncC3: ", self.iterationFilenames, self.currentIteration)
356 self.save(os.path.join(self.logBasePath, self.iterationFilenames % self.currentIteration))
357
358 # Verify if a new eval must be launched
359 if self.currentEvaluation + self._unfinishedEvals >= self.initBatchSize + self.nbIterations * self.batchSize:
360 if self._unfinishedEvals == 0:
361 # All evaluation are finished
362 self.save(os.path.join(self.logBasePath, self.finalFilename))
363 else:
364 # Launch new eval
365 self._evaluateIndAsync()
366
367
368
369 def _defaultInitiation(self, dimension, indBounds, nb):
370 return generateUniformInt(dimension, self.indBounds, nb)
371
372 def _generateInitBatch(self):
373 self.initPop = np.unique(self.initiate(self.dimension, self.indBounds, self.initBatchSize), axis=0)
374 #self.initPop = []
375 #for i in range(self.initBatchSize):
376 # #self.initPop.append(np.random.randint(self.indBounds[0], self.indBounds[1], self.dimension))
377 # #self.initPop.append(np.random.uniform(self.indBounds[0], self.indBounds[1], self.dimension))
378 # self.initPop.append(self.initiate(self.dimension, self.indBounds))
379 return self.initPop
380
381 def _iterationMessage(self, prefixLogs, iteration, batch, bestInIterationFitness, bestEverFitness, elapsed):
382 #print("%s%i batchSize:%i bestInBatch:%f bestEver:%f elapsed:%f" % (prefixLogs, iteration, len(batch), bestInIterationFitness, bestEverFitness, elapsed))
383 print("%s%i batchSize:%i bestEver:%f emptyBins:%i/%i elapsed:%f" % (prefixLogs, iteration, len(batch), bestEverFitness, self.nbEmptyBins, self.containerSize, elapsed))
384
385 def _genNewIndFromElites(self):
386 if self.completelyNewGenomePb > 0.0 and np.random.random() < self.completelyNewGenomePb:
387 return self.initiate(self.dimension, self.indBounds, 1)[0]
388 else:
389 currentElites = list(self.solutions.values())
390 if not len(currentElites):
391 raise ValueError("No elites were found !")
392 ind = copy.deepcopy(currentElites[np.random.randint(0, len(currentElites))])
393 self.mutate(ind, self.mutationPb, self.indBounds)
394 return ind
395
396 def run(self, initBatch = None, nbIterations = None, disableLogs = False, prefixLogs = "#"):
397 """Evaluate the initial batch, evolve through the iterations, and return the best genome and fitness."""
398 startTime = timer()
399 if initBatch:
400 self.initPop = initBatch
401 else:
402 self._generateInitBatch()
403 if nbIterations == None:
404 nbIterations = self.nbIterations
405 #self.initPop, self.bestInIterationFitness, elapsed = self._evaluatePop(self.initPop)
406 self.bestInIterationFitness, elapsed = self._evaluatePop(self.initPop)
408 self.currentEvaluation = len(self.initPop)
409 if not disableLogs:
410 self._iterationMessage(prefixLogs, 0, self.initPop, self.bestInIterationFitness, self.bestEverFitness, elapsed)
411 sys.stdout.flush()
412 for iteration in range(1, nbIterations):
413 self.currentIteration = iteration
414 self.currentEvaluation += self.batchSize
415 currentElites = list(self.solutions.values())
416 if not len(currentElites):
417 raise ValueError("No elites were found in initial batch !")
418 newPop = []
419 for i in range(self.batchSize):
420 ind = self._genNewIndFromElites()
421 newPop.append(ind)
422 #newPop, self.bestInIterationFitness, elapsed = self._evaluatePop(newPop)
423 self.bestInIterationFitness, elapsed = self._evaluatePop(newPop)
424 #print("%s%i bestInBatch:%f bestEver:%f elapsed:%f elapsedPerInd:%f" % (prefixLogs, iteration, self.bestInIterationFitness, self.bestEverFitness, elapsed, elapsed / len(newPop)))
425 if not disableLogs:
426 self._iterationMessage(prefixLogs, iteration, newPop, self.bestInIterationFitness, self.bestEverFitness, elapsed)
427 sys.stdout.flush()
428 if not disableLogs and self.savePeriod and np.mod(self.currentIteration, self.savePeriod) == 0:
429 self.save(os.path.join(self.logBasePath, self.iterationFilenames % iteration))
430 # Perform garbage collection
431 while gc.collect() > 0:
432 pass
433 if not disableLogs and self.finalFilename:
434 self.save(os.path.join(self.logBasePath, self.finalFilename))
435 endTime = timer()
436 self.totalElapsed += endTime - startTime
437 if not disableLogs and nbIterations > 1:
438 print("Total elapsed:%f" % (self.totalElapsed))
439 return (self.bestEver, self.bestEverFitness)
440
441
442 def runAsync(self, initBatch = None):
443 """Dispatch legacy evaluation through its asynchronous path and return the best result."""
444 if initBatch:
445 self.initPop = initBatch
446 else:
447 self._generateInitBatch()
448 evalsFuturesList = []
449 for i in range(len(self.initPop)):
450 evalsFuturesList.append(self._evaluateIndAsync(self.initPop[i]))
451 #self._evaluateIndAsync(self.initPop[i])
452 # Main loop
453 while(True):
454 #print("DEBUG1:", self.currentEvaluation, self.initBatchSize + self.nbIterations * self.batchSize)
455 #print("DEBUG1b: ", [x.ready() for x in evalsFuturesList])
456 if self.currentEvaluation >= self.initBatchSize + self.nbIterations * self.batchSize:
457 break
458 time.sleep(1)
459 return (self.bestEver, self.bestEverFitness)
460
461
463 """Collect the legacy arrays, solution mapping, settings, and supplied metadata."""
464 outputDict = {}
465 outputDict['performances'] = self.performances
466 outputDict['features'] = self.features
467 outputDict['solutions'] = self.solutions
468 outputDict['dimension'] = self.dimension
469 outputDict['nbBins'] = self.nbBins
470 outputDict['featuresBounds'] = self.featuresBounds
471 outputDict['initBatchSize'] = self.initBatchSize
472 outputDict['nbIterations'] = self.nbIterations
473 outputDict['batchSize'] = self.batchSize
474 outputDict['indBounds'] = self.indBounds
475 outputDict['mutationPb'] = self.mutationPb
476 outputDict['currentIteration'] = self.currentIteration
477 outputDict['initPop'] = self.initPop
478 outputDict['bestEver'] = self.bestEver
479 outputDict['bestEverFitness'] = self.bestEverFitness
480 outputDict = {**outputDict, **self._infoToSave}
481 return outputDict
482
483 def save(self, outputFile):
484 """Write the legacy result dictionary to a pickle file."""
485 outputDict = self.generateOutputDict()
486 with open(outputFile, "wb") as f:
487 pickle.dump(outputDict, f)
488
489 def addSavingInfo(self, key, value):
490 self._infoToSave[key] = value
491
492
493
494
495
496#@jit(nopython=True)
497@jit(nopython=True, parallel=True)
498def _cvtMapElites_valsToElitesIndex(clusterCenters, vals):
499 dists = np.empty((clusterCenters.shape[0]))
500 for i in range(len(dists)):
501 dists[i] = math.sqrt(np.sum(np.square(clusterCenters[i] - vals)))
502 return (np.argmin(dists),)
503
504
506 """Use nearest-centroid cells with the legacy MAP-Elites API.
507
508 Draw centroid fitting samples independently within each declared
509 feature interval. The fitted k-means centres define the archive cells.
510 """
511 def __init__(self, dimension, evalFn, nbBins, nbClusters, featuresBounds = [(0.0, 1.0)], initBatchSize = 120, batchSize=40, nbIterations = 10, indBounds = (0, 100), mutationPb = 0.2, savePeriod = 0, logBasePath = ".", nbSampledPoints = 50000, reevalTimeout = 5., mutate = None, initiate = None, iterationFilenames = "iteration-%i.p", finalFilename = "final.p", fitnessBounds = (0., 1.), parallelismType = "multiprocessing", completelyNewGenomePb = 0.0):
512 self.nbClusters = nbClusters
513 self.nbSampledPoints = nbSampledPoints
514 super().__init__(dimension, evalFn, nbBins, featuresBounds, initBatchSize, batchSize, nbIterations, indBounds, mutationPb, savePeriod, logBasePath, reevalTimeout, mutate, initiate, iterationFilenames, finalFilename, fitnessBounds, parallelismType, completelyNewGenomePb=completelyNewGenomePb)
515
516
520 def reinit(self):
521 super().reinit()
522 self.performances = np.full(self.nbClusters, self.fitnessBounds[0])
523 self.features = np.zeros(shape=[self.nbClusters, len(self.nbBins)])
524 # Init clusters
525 lower, upper = np.asarray(self.featuresBounds).T
526 sample = np.random.uniform(lower, upper, (self.nbSampledPoints, len(self.nbBins)))
527 kmeans = KMeans(init="k-means++", n_clusters=self.nbClusters, n_init=1, verbose=0)
528 kmeans.fit(sample)
529 self.clusterCenters = kmeans.cluster_centers_
530 self.containerSize = self.nbClusters
531 self.nbEmptyBins = self.containerSize
532
533 def _valsToElitesIndex(self, vals):
534 return _cvtMapElites_valsToElitesIndex(self.clusterCenters, vals)
535 #closestDist = float("inf")
536 #closestCluster = 0
537 #for i in range(len(self.clusterCenters)):
538 # dist = euclidean(self.clusterCenters[i], vals)
539 # if dist < closestDist:
540 # closestDist = dist
541 # closestCluster = i
542 #return (closestCluster,)
543
545 outputDict = super().generateOutputDict()
546 outputDict['nbClusters'] = self.nbClusters
547 outputDict['nbSampledPoints'] = self.nbSampledPoints
548 outputDict['clusterCenters'] = self.clusterCenters
549 outputDict = {**outputDict, **self._infoToSave}
550 return outputDict
551
552
553
554
555class SAIL(object):
556 """Run surrogate-assisted illumination through the legacy API.
557
558 Fit a Gaussian process from the illumination archive. Use separate
559 acquisition and prediction algorithms during the optimisation.
560 The evaluator and output fields follow the original legacy interface.
561 """
562 def __init__(self, dimension, evalFn, nbBins, illuminationAlgo, acquisitionMapAlgo, predictionMapAlgo, featuresBounds = [(0.0, 1.0)], initBatchSize = 120, batchSize=40, indBounds = (0, 100), mutationPb = 0.2, savePeriod = 0, logBasePath = ".", mutate = None, initiate = None, nbAcquisitionRounds = 10, ucbStdDevFactor = 1.0, nbPreciseEvalsPerAcquisitionRound = 10, instanceName = "", fitnessBounds = (0., 1.), finalFilename = "final.p", parallelismType = "multiprocessing", maintainBatchSizeWithMutatedInd = False, preciseEvalsSelectionType = "sobol"):
563 self.dimension = dimension
564 self.evalFn = evalFn
565 self.nbBins = nbBins
566 self.illuminationAlgo = illuminationAlgo
567 self.acquisitionMapAlgo = acquisitionMapAlgo
568 self.predictionMapAlgo = predictionMapAlgo
569 self.featuresBounds = featuresBounds
570 self.initBatchSize = initBatchSize
571 self.batchSize = batchSize
572 self.indBounds = indBounds
573 self.mutationPb = mutationPb
574 self.savePeriod = savePeriod
575 self.logBasePath = logBasePath
576 self.mutate = mutate
577 self.initiate = initiate
578 self.nbAcquisitionRounds = nbAcquisitionRounds
579 self.ucbStdDevFactor = ucbStdDevFactor
580 self.nbPreciseEvalsPerAcquisitionRound = nbPreciseEvalsPerAcquisitionRound
581 self.instanceName = instanceName
582 self.fitnessBounds = fitnessBounds
583 self.finalFilename = finalFilename
584 self.parallelismType = parallelismType
585 self.maintainBatchSizeWithMutatedInd = maintainBatchSizeWithMutatedInd
586 self.preciseEvalsSelectionType = preciseEvalsSelectionType
587 self.reinit()
588
589 def __getstate__(self):
590 odict = self.__dict__.copy()
591 del odict['gp']
592 return odict
593
594
595 def reinit(self):
596 self._infoToSave = {}
597 self.acquisitionMapAlgo.evalFn = self._acquisitionEvalFn
598 self.predictionMapAlgo.evalFn = self._predictionEvalFn
599 self.acquisitionMapAlgo.parallelismType = "none" # Disable multiprocessing
600 self.predictionMapAlgo.parallelismType = "none" # Disable multiprocessing
601 self.currentRound = 0
602
603
604 def _acquisitionEvalFn(self, inds, expeIds):
605 with warnings.catch_warnings():
606 warnings.simplefilter("ignore")
607 y_mean, y_std = self.gp.predict(np.array(inds), return_std = True)
608 if y_std.ndim == 1 and y_mean.ndim == 2:
609 y_std = y_std[:, None]
610 ucbVal = y_mean + self.ucbStdDevFactor * y_std
611 if ucbVal.ndim == 1:
612 ucbVal = ucbVal[:, None]
613 # Normalise ucbVal
614 ucbVal[:,0][ucbVal[:,0] < self.fitnessBounds[0]] = self.fitnessBounds[0]
615 ucbVal[:,0][ucbVal[:,0] > self.fitnessBounds[1]] = self.fitnessBounds[1]
616 for i in range(len(self.featuresBounds)):
617 ucbVal[:,i+1][ucbVal[:,i+1] < self.featuresBounds[i][0]] = self.featuresBounds[i][0]
618 ucbVal[:,i+1][ucbVal[:,i+1] > self.featuresBounds[i][1]] = self.featuresBounds[i][1]
619 return copy.deepcopy(ucbVal)
620
621 def _predictionEvalFn(self, inds, expeIds):
622 with warnings.catch_warnings():
623 warnings.simplefilter("ignore")
624 y_mean, y_std = self.gp.predict(np.array(inds), return_std = True)
625 # Normalise y_mean
626 y_mean[:,0][y_mean[:,0] < self.fitnessBounds[0]] = self.fitnessBounds[0]
627 y_mean[:,0][y_mean[:,0] > self.fitnessBounds[1]] = self.fitnessBounds[1]
628 for i in range(len(self.featuresBounds)):
629 y_mean[:,i+1][y_mean[:,i+1] < self.featuresBounds[i][0]] = self.featuresBounds[i][0]
630 y_mean[:,i+1][y_mean[:,i+1] > self.featuresBounds[i][1]] = self.featuresBounds[i][1]
631 return copy.deepcopy(y_mean)
632
633 def _createGaussianRegressor(self):
634 # Create dataset
635 elitesIndexes = list(self.illuminationAlgo.solutions.keys())
636 assert(len(elitesIndexes))
637 dataX = []
638 dataY = []
639 for index in elitesIndexes:
640 dataX.append(self.illuminationAlgo.solutions[index])
641 perfAndFeatures = [self.illuminationAlgo.performances[index]] + list(self.illuminationAlgo.features[index])
642 dataY.append(perfAndFeatures)
643 dataX = np.array(dataX)
644 dataY = np.array(dataY)
645
646 # Fit gaussian process on the dataset
647 #print("DEBUGii", dataX, dataY, self.fitnessBounds, np.min(self.illuminationAlgo.performances), elitesIndexes)
648 self.gp = GaussianProcessRegressor()
649 with warnings.catch_warnings():
650 warnings.simplefilter("ignore")
651 self.gp.fit(dataX, dataY)
652 return self.gp
653
654 def _genNewIndFromElites(self):
655 return self.illuminationAlgo._genNewIndFromElites()
656
657 def _produceAcquisitionMap(self, disableLogs = True, prefixLogs = "#"):
658 for roundId in range(1, self.nbAcquisitionRounds):
659 startTimeAcquisition = timer()
660 self.currentRound += 1
661 # Reset acquisitionMapAlgo
662 self.acquisitionMapAlgo.reinit()
663
665 pop = list(self.illuminationAlgo.solutions.values())
666 #print("DEBUGAC:", len(pop))
667 # Launch map-elites using the gp as surrogate model
668 if self.savePeriod and np.mod(roundId, self.savePeriod) == 0:
669 self.acquisitionMapAlgo.iterationFilenames = "iterationAcquisition-%i-%s_%s.p" % (roundId, "%i", self.instanceName)
670 self.acquisitionMapAlgo.finalFilename = "finalAcquisition-%i_%s.p" % (roundId, self.instanceName)
671 else:
672 self.acquisitionMapAlgo.iterationFilenames = None
673 self.acquisitionMapAlgo.finalFilename = None
674 self.acquisitionMapAlgo.initBatchSize = len(pop)
675 bestEver, bestEverFitness = self.acquisitionMapAlgo.run(pop, disableLogs = disableLogs, prefixLogs = "Acquisition%i-%s" % (roundId, prefixLogs))
676
677 # Select bins from acquisitionMapAlgo map
678 #acquisitionSolutions = list(self.acquisitionMapAlgo.solutions.values())
679 acquisitionSolutions = set([tuple(x) for x in self.acquisitionMapAlgo.solutions.values()])
680 acquisitionSolutions -= set([tuple(x) for x in pop])
681 if len(acquisitionSolutions):
682 acquisitionSolutions = np.unique([np.array(x) for x in list(acquisitionSolutions)], axis=0)
683 if len(acquisitionSolutions) <= self.nbPreciseEvalsPerAcquisitionRound:
684 selectedSolutions = acquisitionSolutions
685 else:
686 # Select how the index is generated (random uniform sampling vs sobol sampling)
687 if self.preciseEvalsSelectionType == "sobol":
688 indexList = np.unique((hdsobol.gen_sobol_vectors(self.nbPreciseEvalsPerAcquisitionRound, 1) * len(acquisitionSolutions)).astype(int))
689 elif self.preciseEvalsSelectionType == "uniform":
690 indexList = random.sample(range(len(acquisitionSolutions)), self.nbPreciseEvalsPerAcquisitionRound)
691 else:
692 raise ValueError("Unknown value '%s' for entry 'preciseEvalsSelectionType'" % self.preciseEvalsSelectionType)
693 selectedSolutions = [acquisitionSolutions[x] for x in indexList]
694
695 pop = list(selectedSolutions)
697 for i in range(self.batchSize - len(selectedSolutions)):
698 pop.append(self._genNewIndFromElites())
699
700 bestInIterationFitness, elapsedIllumination = self.illuminationAlgo._evaluatePop(pop)
701 endTimeAcquisition = timer()
702 elapsed = elapsedIllumination + endTimeAcquisition - startTimeAcquisition
703 self.illuminationAlgo._iterationMessage(prefixLogs, roundId, pop, self.illuminationAlgo.bestInIterationFitness, self.illuminationAlgo.bestEverFitness, elapsed)
704 if self.savePeriod and np.mod(roundId, self.savePeriod) == 0:
705 self.illuminationAlgo.iterationFilenames = "iteration-%i-%s_%s.p" % (roundId, "%i", self.instanceName)
706 self.illuminationAlgo.save(os.path.join(self.logBasePath, self.illuminationAlgo.iterationFilenames % roundId))
707
708 self.bestEverFitness = self.illuminationAlgo.bestEverFitness
709 self.bestEver = self.illuminationAlgo.bestEver
710 self.containerSize = self.illuminationAlgo.containerSize
711 self.nbEmptyBins = self.illuminationAlgo.nbEmptyBins
712 self.performances = self.illuminationAlgo.performances
713 self.solutions = self.illuminationAlgo.solutions
714 self.features = self.illuminationAlgo.features
715
716 # Perform garbage collection
717 while gc.collect() > 0:
718 pass
719
720
721
722 def _producePredictionMap(self, disableLogs = True, prefixLogs = "#"):
723 self.predictionMapAlgo.reinit()
725 pop = list(self.illuminationAlgo.solutions.values())
726 # Launch map-elites using the gp as surrogate model
727 self.predictionMapAlgo.iterationFilenames = "iterationPrediction-%s_%s.p" % ("%i", self.instanceName)
728 self.predictionMapAlgo.finalFilename = "finalPrediction_%s.p" % self.instanceName
729 self.predictionMapAlgo.initBatchSize = len(pop)
730 bestEver, bestEverFitness = self.predictionMapAlgo.run(pop, disableLogs = disableLogs, prefixLogs = "Prediction-" + prefixLogs)
731
732 def _updateConfig(self):
733 def updateEntry(entry):
734 self.illuminationAlgo.__dict__[entry] = self.__dict__[entry]
735 self.acquisitionMapAlgo.__dict__[entry] = self.__dict__[entry]
736 self.predictionMapAlgo.__dict__[entry] = self.__dict__[entry]
737 list(map(updateEntry, ["initiate", "mutate", "logBasePath", "nbBins", "_infoToSave", "dimension", "featuresBounds", "indBounds", "fitnessBounds"]))
738 self.illuminationAlgo.evalFn = self.evalFn
739 self.illuminationAlgo.iterationFilenames = None
740 self.illuminationAlgo.finalFilename = None
741 self.illuminationAlgo.initBatchSize = self.initBatchSize
742 self.acquisitionMapAlgo.callEvalFnOnEntierBatch = True
743 self.predictionMapAlgo.callEvalFnOnEntierBatch = True
744 self.illuminationAlgo.reinit()
745
746 def run(self, initBatch = None, nbIterations = None, disableLogs = False, prefixLogs = "#"):
747 self._updateConfig()
748 # Generate initial population
749 self.illuminationAlgo.run(initBatch = initBatch, nbIterations = 0, disableLogs = disableLogs, prefixLogs = prefixLogs) #, prefixLogs="Init-#")
750 # Create maps
751 if len(list(self.illuminationAlgo.solutions.keys())):
752 self._produceAcquisitionMap(disableLogs = True, prefixLogs = prefixLogs)
753 self._producePredictionMap(disableLogs = True, prefixLogs = prefixLogs)
754 # Save
755 #self.illuminationAlgo.finalFilename = "final_%s.p" % (self.instanceName)
756 #self.illuminationAlgo.save(os.path.join(self.logBasePath, self.illuminationAlgo.finalFilename))
757 #self.finalFilename = "final_%s.p" % (self.instanceName)
758 if self.finalFilename:
759 self.save(os.path.join(self.logBasePath, self.finalFilename))
760 return (self.illuminationAlgo.bestEver, self.illuminationAlgo.bestEverFitness)
761
762
763 def generateOutputDict(self):
764 outputDict = {}
765 outputDict['performances'] = self.performances
766 outputDict['features'] = self.features
767 outputDict['solutions'] = self.solutions
768 outputDict['dimension'] = self.dimension
769 outputDict['nbBins'] = self.nbBins
770 outputDict['featuresBounds'] = self.featuresBounds
771 outputDict['initBatchSize'] = self.initBatchSize
772 outputDict['batchSize'] = self.batchSize
773 outputDict['indBounds'] = self.indBounds
774 outputDict['mutationPb'] = self.mutationPb
775 outputDict['currentRound'] = self.currentRound
776 outputDict['fitnessBounds'] = self.fitnessBounds
777 outputDict['illuminationAlgo'] = self.illuminationAlgo.generateOutputDict()
778 outputDict['acquisitionMapAlgo'] = self.acquisitionMapAlgo.generateOutputDict()
779 outputDict['predictionMapAlgo'] = self.predictionMapAlgo.generateOutputDict()
780 outputDict['bestEver'] = self.bestEver
781 outputDict['bestEverFitness'] = self.bestEverFitness
782 outputDict = {**outputDict, **self._infoToSave}
783 return outputDict
784
785 def save(self, outputFile):
786 outputDict = self.generateOutputDict()
787 with open(outputFile, "wb") as f:
788 pickle.dump(outputDict, f)
789
790 def addSavingInfo(self, key, value):
791 self._infoToSave[key] = value
792
793
794
795
796
797
798
799class AlgorithmFactory(object):
800 """Construct legacy MAP-Elites, CVT, or SAIL algorithms from legacy configuration fields."""
801 def __init__(self, algoType = "map-elites", nbDim = 50, evalFn = None, nbBins = None, nbClusters = 30, nbSampledPoints = 50000, featuresBounds = [(0., 1.)], indBounds = (0, 100), initBatchSize = 10000, batchSize = 4000, nbIterations = 500, mutationPb = 0.2, nbCenters = 20, savePeriod = 0, logBasePath = ".", reevalTimeout = None, mutate = None, initiate = None, iterationFilenames = "iteration-%i.p", finalFilename = "final.p", instanceName = "", fitnessBounds = (0., 1.), parallelismType = "multiprocessing", maintainBatchSizeWithMutatedInd = False, completelyNewGenomePb = 0.0, preciseEvalsSelectionType = "sobol"):
802 self.algoType = algoType
803 self.nbDim = nbDim
804 self.evalFn = evalFn
805 self.nbBins = nbBins
806 self.nbClusters = nbClusters
807 self.nbSampledPoints = nbSampledPoints
808 self.featuresBounds = featuresBounds
809 self.indBounds = indBounds
810 self.initBatchSize = initBatchSize
811 self.batchSize = batchSize
812 self.nbIterations = nbIterations
813 self.mutationPb = mutationPb
814 self.nbCenters = nbCenters
815 self.savePeriod = savePeriod
816 self.logBasePath = logBasePath
817 self.reevalTimeout = reevalTimeout
818 self.mutate = mutate
819 self.initiate = initiate
820 self.iterationFilenames = iterationFilenames
821 self.finalFilename = finalFilename
822 self.instanceName = instanceName
823 self.fitnessBounds = fitnessBounds
824 self.parallelismType = parallelismType
825 self.maintainBatchSizeWithMutatedInd = maintainBatchSizeWithMutatedInd
826 self.completelyNewGenomePb = completelyNewGenomePb
827 self.preciseEvalsSelectionType = preciseEvalsSelectionType
828 self.algo = None
829
830 def update(self, **kwargs):
831 for k,v in kwargs.items():
832 if k in self.__dict__:
833 self.__dict__[k] = v
834 else:
835 raise ValueError("Unknown entry: '%s'" % k)
836
837 def build(self):
838 """Instantiate the configured legacy algorithm type."""
839 if self.algoType == "map-elites":
840 self.algo = MapElites(self.nbDim, self.evalFn, self.nbBins, self.featuresBounds, self.initBatchSize, self.batchSize, self.nbIterations, self.indBounds, self.mutationPb, self.savePeriod, self.logBasePath, self.reevalTimeout, self.mutate, self.initiate, self.iterationFilenames, self.finalFilename, fitnessBounds = self.fitnessBounds, parallelismType = self.parallelismType, completelyNewGenomePb = self.completelyNewGenomePb)
841 elif self.algoType == "cvt-map-elites":
842 self.algo = CVTMapElites(self.nbDim, self.evalFn, self.nbBins, self.nbClusters, self.featuresBounds, self.initBatchSize, self.batchSize, self.nbIterations, self.indBounds, self.mutationPb, self.savePeriod, self.logBasePath, self.nbSampledPoints, self.reevalTimeout, self.mutate, self.initiate, self.iterationFilenames, self.finalFilename, fitnessBounds = self.fitnessBounds, parallelismType = self.parallelismType, completelyNewGenomePb = self.completelyNewGenomePb)
843 elif self.algoType == "sail":
844 self.algo = SAIL(self.nbDim, self.evalFn, self.nbBins, self.illuminationAlgo, self.acquisitionMapAlgo, self.predictionMapAlgo, self.featuresBounds, self.initBatchSize, self.batchSize, self.indBounds, self.mutationPb, self.savePeriod, self.logBasePath, self.mutate, self.initiate, self.nbAcquisitionRounds, self.ucbStdDevFactor, self.nbPreciseEvalsPerAcquisitionRound, instanceName=self.instanceName, fitnessBounds = self.fitnessBounds, finalFilename = self.finalFilename, parallelismType = self.parallelismType, maintainBatchSizeWithMutatedInd = self.maintainBatchSizeWithMutatedInd, preciseEvalsSelectionType = self.preciseEvalsSelectionType)
845 else:
846 raise ValueError("Unknown algoType: '%s'" % self.algoType)
847 return self.algo
848
849
850 def fromConfig(self, config):
851 def setIfExists(key):
852 o = config.get(key)
853 if o:
854 self.__dict__[key] = o
855 def buildIfExists(key):
856 o = config.get(key)
857 if o:
858 fact = AlgorithmFactory()
859 fact.fromConfig(o)
860 fact.update(evalFn = self.evalFn, featuresBounds = self.featuresBounds, \
861 fitnessBounds = self.fitnessBounds, indBounds = self.indBounds, \
862 nbDim = self.nbDim, nbClusters = self.nbClusters, mutationPb = self.mutationPb, \
863 parallelismType = self.parallelismType, completelyNewGenomePb = self.completelyNewGenomePb)
864 self.__dict__[key] = fact.build()
865 setIfExists('parallelismType')
866 setIfExists('algoType')
867 setIfExists('nbDim')
868 setIfExists('nbBins')
869 setIfExists('nbClusters')
870 setIfExists('nbSampledPoints')
871 setIfExists('featuresBounds')
872 setIfExists('indBounds')
873 setIfExists('fitnessBounds')
874 setIfExists('initBatchSize')
875 setIfExists('batchSize')
876 setIfExists('nbIterations')
877 setIfExists('mutationPb')
878 setIfExists('nbCenters')
879 setIfExists('savePeriod')
880 setIfExists('reevalTimeout')
881 setIfExists('completelyNewGenomePb')
882 # SAIL config
883 setIfExists('nbAcquisitionRounds')
884 setIfExists('ucbStdDevFactor')
885 setIfExists('nbPreciseEvalsPerAcquisitionRound')
886 setIfExists('maintainBatchSizeWithMutatedInd')
887 setIfExists('preciseEvalsSelectionType')
888 buildIfExists('illuminationAlgo')
889 buildIfExists('acquisitionMapAlgo')
890 buildIfExists('predictionMapAlgo')
891
892
893
894
895
896
897
898
899def plotMAP(performances, outputFilename, cmap, featuresBounds=[(0., 1.), (0., 1.)], fitnessBounds=(0., 1.), drawCbar = True, xlabel = "", ylabel = "", cBarLabel = "", nbTicks = 10):
900 """Write a plot of the legacy performance array."""
901 data = performances
902 if len(data.shape) == 1:
903 data = data.reshape((1, data.shape[0]))
904 nbBins = data.shape
905
906 figsize = [2.1 + 10. * nbBins[0] / (nbBins[0] + nbBins[1]), 1. + 10. * nbBins[1] / (nbBins[0] + nbBins[1])]
907 aspect = "equal"
908 if figsize[1] < 2:
909 figsize[1] = 2.
910 aspect = "auto"
911
912 fig, ax = plt.subplots(figsize=figsize)
913 cax = ax.imshow(data.T, interpolation="none", cmap=cmap, vmin=fitnessBounds[0], vmax=fitnessBounds[1], aspect=aspect)
914 #ax.set_aspect('equal')
915 ax.invert_yaxis()
916
917 if nbBins[0] > nbBins[1]:
918 nbTicksX = nbTicks
919 nbTicksY = int(nbTicksX * nbBins[1] / nbBins[0])
920 elif nbBins[1] > nbBins[0]:
921 nbTicksY = nbTicks
922 nbTicksX = int(nbTicksY * nbBins[0] / nbBins[1])
923 else:
924 nbTicksX = nbTicksY = nbTicks
925 if nbTicksX > nbBins[0] or nbTicksX < 1:
926 nbTicksX = nbBins[0]
927 if nbTicksY > nbBins[1] or nbTicksY < 1:
928 nbTicksY = nbBins[1]
929
930 # Set ticks
931 ax.xaxis.set_tick_params(which='major', left=False, bottom=False, top=False, right=False)
932 ax.yaxis.set_tick_params(which='major', left=False, bottom=False, top=False, right=False)
933 xticks = list(np.arange(0, data.shape[0] + 1, data.shape[0] / nbTicksX))
934 yticks = list(np.arange(0, data.shape[1] + 1, data.shape[1] / nbTicksY))
935 plt.xticks(xticks, rotation='vertical')
936 plt.yticks(yticks)
937 deltaFeature0 = featuresBounds[0][1] - featuresBounds[0][0]
938 deltaFeature1 = featuresBounds[1][1] - featuresBounds[1][0]
939 ax.set_xticklabels([round(float(x / float(data.shape[0]) * deltaFeature0 + featuresBounds[0][0]), 2) for x in xticks], fontsize=20)
940 ax.set_yticklabels([round(float(y / float(data.shape[1]) * deltaFeature1 + featuresBounds[1][0]), 2) for y in yticks], fontsize=20)
941
942 # Draw grid
943 ax.xaxis.set_tick_params(which='minor', direction="in", left=True, bottom=True, top=True, right=True)
944 ax.yaxis.set_tick_params(which='minor', direction="in", left=True, bottom=True, top=True, right=True)
945 ax.set_xticks(np.arange(-.5, data.shape[0], 1), minor=True)
946 ax.set_yticks(np.arange(-.5, data.shape[1], 1), minor=True)
947 ax.grid(which='minor', color=(0.8,0.8,0.8,0.5), linestyle='-', linewidth=0.1)
948
949 ax.set_xlabel(xlabel, fontsize=25)
950 ax.set_ylabel(ylabel, fontsize=25)
951
952 if drawCbar:
953 divider = make_axes_locatable(ax)
954 #cax2 = divider.append_axes("right", size="5%", pad=0.15)
955 cax2 = divider.append_axes("right", size=0.5, pad=0.15)
956 cbar = fig.colorbar(cax, cax=cax2, format="%.2f")
957 cbar.ax.tick_params(labelsize=20)
958 cbar.ax.set_ylabel(cBarLabel, fontsize=22)
959
960 ax.autoscale_view()
961 plt.tight_layout()
962 fig.savefig(outputFilename)
963
964
965
966
967
968# MODELINE "{{{1
969# vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8
970# vim:foldmethod=marker
reinit(self)
Fit one centre per cell over per-axis descriptor intervals.
Definition legacy.py:520
MAP-Elites ########### {{{1.
Definition legacy.py:111
runAsync(self, initBatch=None)
Definition legacy.py:442
save(self, outputFile)
Definition legacy.py:483
run(self, initBatch=None, nbIterations=None, disableLogs=False, prefixLogs="#")
Definition legacy.py:396
_evaluateIndAsync(self, ind=None)
Definition legacy.py:309
bool callEvalFnOnEntierBatch
Definition legacy.py:140
_evalFnWrapper(self, vals)
Definition legacy.py:249
_asyncEvalFnWrapper(self, ind, expeId)
Definition legacy.py:224
_iterationMessage(self, prefixLogs, iteration, batch, bestInIterationFitness, bestEverFitness, elapsed)
Definition legacy.py:381
_defaultInitiation(self, dimension, indBounds, nb)
Definition legacy.py:369
_evaluateIndAsyncCallback(self, param)
Definition legacy.py:322
_genNewIndFromElites(self)
Definition legacy.py:385
_valsToElitesIndex(self, vals)
Definition legacy.py:209
_evaluatePop(self, pop)
Definition legacy.py:253
_genNewIndFromElites(self)
Definition legacy.py:654
_predictionEvalFn(self, inds, expeIds)
Definition legacy.py:621
save(self, outputFile)
Definition legacy.py:785
_acquisitionEvalFn(self, inds, expeIds)
Definition legacy.py:604
nbPreciseEvalsPerAcquisitionRound
Definition legacy.py:580
str preciseEvalsSelectionType
Definition legacy.py:586
_produceAcquisitionMap(self, disableLogs=True, prefixLogs="#")
Definition legacy.py:657
_createGaussianRegressor(self)
Definition legacy.py:633
_updateConfig(self)
Definition legacy.py:732
_producePredictionMap(self, disableLogs=True, prefixLogs="#")
Definition legacy.py:722
maintainBatchSizeWithMutatedInd
Definition legacy.py:585
generateOutputDict(self)
Definition legacy.py:763