19"""Old preliminary code. It is not documented and will be removed in the future."""
31from scipy.spatial.distance
import euclidean
32from sklearn.cluster
import KMeans
33from sklearn.gaussian_process
import GaussianProcessRegressor
35from timeit
import default_timer
as timer
39import matplotlib.pyplot
as plt
40from mpl_toolkits.axes_grid1
import make_axes_locatable
42from functools
import reduce
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])
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])
67def generateUniformInt(dimension, indBounds, nb):
68 """Generate integer genomes with both integer endpoints included."""
71 res.append(np.random.randint(indBounds[0], indBounds[1] + 1, dimension))
75def generateUniform(dimension, indBounds, nb):
76 """Generate a batch of real genomes uniformly within the given interval."""
79 res.append(np.random.uniform(indBounds[0], indBounds[1], dimension))
83def generateSparseUniform(dimension, indBounds, nb, sparsity):
84 """Generate uniform genomes and set each coordinate to zero with the given sparsity probability."""
87 base = np.random.uniform(indBounds[0], indBounds[1], dimension)
88 mask = np.random.uniform(0., 1., dimension)
89 base[mask < sparsity] = 0.
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]
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)
112 """Run the original maximising MAP-Elites API with explicit array storage.
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.
119 The native ask/tell API uses separate algorithms and containers. Use
120 the legacy result keys when working with this implementation.
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):
148 def __getstate__(self):
149 odict = self.__dict__.copy()
155 def _closePool(self):
156 if hasattr(self,
'pool'):
158 self.
pool.terminate()
160 def _initParallelism(self):
165 import multiprocessing
167 self.
pool = multiprocessing.Pool()
171 self.
map = scoop.futures.map
173 raise Exception(
"Unknown parallelismType: '%s'" % self.
parallelismType)
177 """Start a fresh legacy run with an empty archive, evaluation counters, and its configured executor."""
178 if not hasattr(self,
'_infoToSave'):
182 self.
_evalId = itertools.count()
184 self.
mutate = mutateUniformInt
209 def _valsToElitesIndex(self, vals):
211 assert(len(vals) == len(self.
nbBins))
212 for i
in range(len(vals)):
215 partial = self.
nbBins[i] - 1
217 print(
"WARNING: feature %i out of bounds: %s" % (i, vals))
220 partial = int(normalisedVal / self.
_binsSize[i])
221 index.append(partial)
224 def _asyncEvalFnWrapper(self, ind, expeId):
225 def startEval(newInd):
227 res = self.
evalFn(ind, expeId)
229 elapsed = endTime - startTime
234 elapsed, res = startEval(currentInd)
235 totalElapsed += elapsed
238 if fitness <= 0.000001:
240 print(
"Performed a Reevaluation after:%f sec" % totalElapsed)
245 return currentInd, res
247 return currentInd, res
249 def _evalFnWrapper(self, vals):
251 return self.
evalFn(ind, expeId)
253 def _evaluatePop(self, pop):
255 pop = np.unique(pop, axis=0)
256 listEvalIds = list(next(self.
_evalId)
for _
in pop)
264 popFitnesses = np.array(list(self.
evalFn(pop, listEvalIds)))
280 while gc.collect() > 0:
283 popFitnesses = np.array(list(popFitnesses))
284 popPerformances = popFitnesses[:,0]
285 popFeatures = popFitnesses[:,1:]
287 for indIndex
in range(len(pop)):
290 if elitesIndex ==
None:
292 if self.
performances[elitesIndex] < popPerformances[indIndex]:
294 self.
performances[elitesIndex] = popPerformances[indIndex]
295 self.
features[elitesIndex] = popFeatures[indIndex]
304 elapsed = endTime - startTime
309 def _evaluateIndAsync(self, ind = 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))])
320 return asyncResFromEval
322 def _evaluateIndAsyncCallback(self, param):
331 self.
features[elitesIndex] = features
369 def _defaultInitiation(self, dimension, indBounds, nb):
370 return generateUniformInt(dimension, self.
indBounds, nb)
372 def _generateInitBatch(self):
381 def _iterationMessage(self, prefixLogs, iteration, 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))
385 def _genNewIndFromElites(self):
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))])
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."""
403 if nbIterations ==
None:
412 for iteration
in range(1, nbIterations):
415 currentElites = list(self.
solutions.values())
416 if not len(currentElites):
417 raise ValueError(
"No elites were found in initial batch !")
431 while gc.collect() > 0:
437 if not disableLogs
and nbIterations > 1:
443 """Dispatch legacy evaluation through its asynchronous path and return the best result."""
448 evalsFuturesList = []
449 for i
in range(len(self.
initPop)):
463 """Collect the legacy arrays, solution mapping, settings, and supplied metadata."""
466 outputDict[
'features'] = self.
features
469 outputDict[
'nbBins'] = self.
nbBins
477 outputDict[
'initPop'] = self.
initPop
478 outputDict[
'bestEver'] = self.
bestEver
484 """Write the legacy result dictionary to a pickle file."""
486 with open(outputFile,
"wb")
as f:
487 pickle.dump(outputDict, f)
489 def addSavingInfo(self, key, value):
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),)
506 """Use nearest-centroid cells with the legacy MAP-Elites API.
508 Draw centroid fitting samples independently within each declared
509 feature interval. The fitted k-means centres define the archive cells.
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):
514 super().__init__(dimension, evalFn, nbBins, featuresBounds, initBatchSize, batchSize, nbIterations, indBounds, mutationPb, savePeriod, logBasePath, reevalTimeout, mutate, initiate, iterationFilenames, finalFilename, fitnessBounds, parallelismType, completelyNewGenomePb=completelyNewGenomePb)
527 kmeans = KMeans(init=
"k-means++", n_clusters=self.
nbClusters, n_init=1, verbose=0)
533 def _valsToElitesIndex(self, vals):
556 """Run surrogate-assisted illumination through the legacy API.
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.
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"):
589 def __getstate__(self):
590 odict = self.__dict__.copy()
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]
612 ucbVal = ucbVal[:,
None]
619 return copy.deepcopy(ucbVal)
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)
631 return copy.deepcopy(y_mean)
633 def _createGaussianRegressor(self):
636 assert(len(elitesIndexes))
639 for index
in elitesIndexes:
642 dataY.append(perfAndFeatures)
643 dataX = np.array(dataX)
644 dataY = np.array(dataY)
648 self.
gp = GaussianProcessRegressor()
649 with warnings.catch_warnings():
650 warnings.simplefilter(
"ignore")
651 self.
gp.fit(dataX, dataY)
654 def _genNewIndFromElites(self):
657 def _produceAcquisitionMap(self, disableLogs = True, prefixLogs = "#"):
659 startTimeAcquisition = timer()
675 bestEver, bestEverFitness = self.
acquisitionMapAlgo.run(pop, disableLogs = disableLogs, prefixLogs =
"Acquisition%i-%s" % (roundId, prefixLogs))
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)
684 selectedSolutions = acquisitionSolutions
693 selectedSolutions = [acquisitionSolutions[x]
for x
in indexList]
695 pop = list(selectedSolutions)
697 for i
in range(self.
batchSize - len(selectedSolutions)):
700 bestInIterationFitness, elapsedIllumination = self.
illuminationAlgo._evaluatePop(pop)
701 endTimeAcquisition = timer()
702 elapsed = elapsedIllumination + endTimeAcquisition - startTimeAcquisition
717 while gc.collect() > 0:
722 def _producePredictionMap(self, disableLogs = True, prefixLogs = "#"):
730 bestEver, bestEverFitness = self.
predictionMapAlgo.run(pop, disableLogs = disableLogs, prefixLogs =
"Prediction-" + prefixLogs)
732 def _updateConfig(self):
733 def updateEntry(entry):
737 list(map(updateEntry, [
"initiate",
"mutate",
"logBasePath",
"nbBins",
"_infoToSave",
"dimension",
"featuresBounds",
"indBounds",
"fitnessBounds"]))
746 def run(self, initBatch = None, nbIterations = None, disableLogs = False, prefixLogs = "#"):
749 self.
illuminationAlgo.run(initBatch = initBatch, nbIterations = 0, disableLogs = disableLogs, prefixLogs = prefixLogs)
763 def generateOutputDict(self):
766 outputDict[
'features'] = self.
features
769 outputDict[
'nbBins'] = self.
nbBins
780 outputDict[
'bestEver'] = self.
bestEver
785 def save(self, outputFile):
787 with open(outputFile,
"wb")
as f:
788 pickle.dump(outputDict, f)
790 def addSavingInfo(self, key, value):
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"):
830 def update(self, **kwargs):
831 for k,v
in kwargs.items():
835 raise ValueError(
"Unknown entry: '%s'" % k)
838 """Instantiate the configured legacy algorithm type."""
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)
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)
846 raise ValueError(
"Unknown algoType: '%s'" % self.
algoType)
850 def fromConfig(self, config):
851 def setIfExists(key):
855 def buildIfExists(key):
865 setIfExists(
'parallelismType')
866 setIfExists(
'algoType')
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')
883 setIfExists(
'nbAcquisitionRounds')
884 setIfExists(
'ucbStdDevFactor')
885 setIfExists(
'nbPreciseEvalsPerAcquisitionRound')
886 setIfExists(
'maintainBatchSizeWithMutatedInd')
887 setIfExists(
'preciseEvalsSelectionType')
888 buildIfExists(
'illuminationAlgo')
889 buildIfExists(
'acquisitionMapAlgo')
890 buildIfExists(
'predictionMapAlgo')
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."""
902 if len(data.shape) == 1:
903 data = data.reshape((1, data.shape[0]))
906 figsize = [2.1 + 10. * nbBins[0] / (nbBins[0] + nbBins[1]), 1. + 10. * nbBins[1] / (nbBins[0] + nbBins[1])]
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)
917 if nbBins[0] > nbBins[1]:
919 nbTicksY = int(nbTicksX * nbBins[1] / nbBins[0])
920 elif nbBins[1] > nbBins[0]:
922 nbTicksX = int(nbTicksY * nbBins[0] / nbBins[1])
924 nbTicksX = nbTicksY = nbTicks
925 if nbTicksX > nbBins[0]
or nbTicksX < 1:
927 if nbTicksY > nbBins[1]
or nbTicksY < 1:
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')
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)
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)
949 ax.set_xlabel(xlabel, fontsize=25)
950 ax.set_ylabel(ylabel, fontsize=25)
953 divider = make_axes_locatable(ax)
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)
962 fig.savefig(outputFilename)
maintainBatchSizeWithMutatedInd
preciseEvalsSelectionType
reinit(self)
Fit one centre per cell over per-axis descriptor intervals.
MAP-Elites ########### {{{1.
runAsync(self, initBatch=None)
run(self, initBatch=None, nbIterations=None, disableLogs=False, prefixLogs="#")
_evaluateIndAsync(self, ind=None)
bool callEvalFnOnEntierBatch
_evalFnWrapper(self, vals)
_asyncEvalFnWrapper(self, ind, expeId)
_iterationMessage(self, prefixLogs, iteration, batch, bestInIterationFitness, bestEverFitness, elapsed)
_defaultInitiation(self, dimension, indBounds, nb)
_evaluateIndAsyncCallback(self, param)
_genNewIndFromElites(self)
_valsToElitesIndex(self, vals)
_genNewIndFromElites(self)
_predictionEvalFn(self, inds, expeIds)
_acquisitionEvalFn(self, inds, expeIds)
nbPreciseEvalsPerAcquisitionRound
str preciseEvalsSelectionType
_produceAcquisitionMap(self, disableLogs=True, prefixLogs="#")
_createGaussianRegressor(self)
_producePredictionMap(self, disableLogs=True, prefixLogs="#")
maintainBatchSizeWithMutatedInd