QDpy
Loading...
Searching...
No Matches
deap.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"""
20
21__all__ = ["qdSimple", "DEAPQDAlgorithm"]
22
23import os
24import deap.tools
25import deap.algorithms
26import numpy as np
27from timeit import default_timer as timer
28import pickle
29import copy
30
31from qdpy.phenotype import *
32from qdpy.containers import *
33
34
35def qdSimple(init_batch, toolbox, container, batch_size, niter, cxpb = 0.0, mutpb = 1.0, stats = None, halloffame = None, verbose = False, show_warnings = False, start_time = None, iteration_callback = None):
36 """Evaluate and vary a DEAP population with a QD container.
37
38 Evaluate invalid fitness entries and use the evaluator's first two
39 result elements as fitness and descriptors. Admit the initial batch,
40 then run ``niter`` generations of toolbox selection and DEAP variation.
41 A pre-evaluated batch can warm-start the search. Zero generations
42 returns the evaluated initial batch and its log.
43
44 :param init_batch: Nonempty initial candidate sequence.
45 :param toolbox: DEAP toolbox with applicable evaluator and operators.
46 :param container: QD container to receive each evaluated batch.
47 :param batch_size: Number of selected candidates per generation.
48 :param niter: Number of generations after the initial batch.
49 :param cxpb: Crossover probability for variation.
50 :param mutpb: Mutation probability for variation.
51 :param stats: Optional DEAP statistics collected over the archive.
52 :param halloffame: Optional DEAP hall of fame.
53 :param verbose: Print generation statistics.
54 :param show_warnings: Report archive validation warnings.
55 :param start_time: Start timestamp for initial elapsed-time accounting.
56 :param iteration_callback: Callback receiving iteration, evaluated
57 batch, container, and logbook.
58 :returns: Final evaluated batch and DEAP logbook.
59 """
60 if start_time == None:
61 start_time = timer()
62 logbook = deap.tools.Logbook()
63 logbook.header = ["iteration", "containerSize", "evals", "nbUpdated"] + (stats.fields if stats else []) + ["elapsed"]
64
65 if len(init_batch) == 0:
66 raise ValueError("``init_batch`` must not be empty.")
67
68 # Evaluate the individuals with an invalid fitness
69 invalid_ind = [ind for ind in init_batch if not ind.fitness.valid]
70 if invalid_ind:
71 fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
72 for ind, fit in zip(invalid_ind, fitnesses):
73 ind.fitness.values = fit[0]
74 ind.features = fit[1]
75 batch = init_batch
76
77 # Update halloffame
78 if halloffame is not None:
79 halloffame.update(init_batch)
80
81 # Store batch in container
82 nb_updated = container.update(init_batch, issue_warning=show_warnings, ignore_exceptions=True)
83 if nb_updated == 0:
84 raise ValueError("No individual could be added to the container !")
85
86 # Compile stats and update logs
87 record = stats.compile(container) if stats else {}
88 logbook.record(iteration=0, containerSize=container.size_str(), evals=len(invalid_ind), nbUpdated=nb_updated, elapsed=timer()-start_time, **record)
89 if verbose:
90 print(logbook.stream)
91 # Call callback function
92 if iteration_callback != None:
93 iteration_callback(0, init_batch, container, logbook)
94
95 # Begin the generational process
96 for i in range(1, niter + 1):
97 start_time = timer()
98 # Select the next batch individuals
99 batch = toolbox.select(container, batch_size)
100
101
102 offspring = deap.algorithms.varAnd(batch, toolbox, cxpb, mutpb)
103 #offspring = []
104 #for o in batch:
105 # newO = toolbox.clone(o)
106 # ind, = toolbox.mutate(newO)
107 # del ind.fitness.values
108 # offspring.append(ind)
109
110 # Evaluate the individuals with an invalid fitness
111 invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
112 fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
113 for ind, fit in zip(invalid_ind, fitnesses):
114 ind.fitness.values = fit[0]
115 ind.features = fit[1]
116
117 # Replace the current population by the offspring
118 nb_updated = container.update(offspring, issue_warning=show_warnings)
119
120 # Update the hall of fame with the generated individuals
121 if halloffame is not None:
122 halloffame.update(container)
123
124 # Append the current generation statistics to the logbook
125 record = stats.compile(container) if stats else {}
126 logbook.record(iteration=i, containerSize=container.size_str(), evals=len(invalid_ind), nbUpdated=nb_updated, elapsed=timer()-start_time, **record)
127 if verbose:
128 print(logbook.stream)
129 # Call callback function
130 batch = offspring
131 if iteration_callback != None:
132 iteration_callback(i, batch, container, logbook)
133
134 return batch, logbook
135
136
137
138class DEAPQDAlgorithm(object):
139 """Configure and run a DEAP QD experiment with optional result snapshots.
140
141 The toolbox supplies evaluation and variation. The container
142 determines archive admission. Set ``init_batch_size`` to generate a
143 population or pass a batch directly to run.
144 """
145
146 def __init__(self, toolbox, container = None, stats = None, halloffame = None,
147 iteration_filename = "iteration-%i.p", final_filename = "final.p",
148 ea_fn = qdSimple, cxpb = 0.0, mutpb = 1.0, verbose = False, results_infos = None, log_base_path = ".",
149 save_period = None, iteration_callback_fn = None, **kwargs):
150 self._update_params(**kwargs)
151 self.toolbox = toolbox
152 self.halloffame = halloffame
153 self.iteration_filename = iteration_filename
154 self.final_filename = final_filename
155 self.ea_fn = ea_fn
156 self.cxpb = cxpb
157 self.mutpb = mutpb
158 self.verbose = verbose
159 self.log_base_path = log_base_path
160 self.save_period = save_period
161 self.iteration_callback_fn = iteration_callback_fn
162 self._init_container(container)
163 self._init_stats(stats)
164 self._results_infos = {}
165 if results_infos != None:
166 self.add_results_infos(results_infos)
167 self.total_elapsed = 0.
168
169
170 def _init_container(self, container = None):
171 """TODO"""
172 if container == None:
173 self.container = Container()
174 else:
175 self.container = container
176
177
178 def _init_stats(self, stats = None):
179 """TODO"""
180 if stats == None:
181 # Default stats
182 self.stats = deap.tools.Statistics(lambda ind: ind.fitness.values)
183 self.stats.register("avg", np.mean, axis=0)
184 self.stats.register("std", np.std, axis=0)
185 self.stats.register("min", np.min, axis=0)
186 self.stats.register("max", np.max, axis=0)
187 else:
188 self.stats = stats
189
190
191 def gen_init_batch(self, init_batch_size = None):
192 """Generate and store an initial batch through the DEAP toolbox's population factory."""
193 if not hasattr(self, "start_time") or self.start_time == None:
194 self.start_time = timer()
195 if init_batch_size != None:
196 self.init_batch_size = init_batch_size
197 if not hasattr(self, "init_batch_size") or self.init_batch_size == None:
198 raise ValueError("Please specify 'init_batch_size'")
199 self.init_batch = self.toolbox.population(n = self.init_batch_size)
200
201
202 def _update_params(self, **kwargs):
203 """TODO"""
204 for k,v in kwargs.items():
205 if v != None:
206 if k == "init_batch_size" or k == "batch_size" or k == "niter" or k == "start_time" or k == "save_period" or k == "iteration_filename" or k == "final_filename" or k == "log_base_path":
207 setattr(self, k, v)
208
209
210 def _iteration_callback(self, iteration, batch, container, logbook):
211 """TODO"""
212 self.current_iteration = iteration
213 self.current_batch = batch
214 self.logbook = logbook
215 if self.iteration_callback_fn is not None:
216 self.iteration_callback_fn(iteration, batch, container, logbook)
217 if self.save_period == None or self.save_period == 0:
218 return
219 if iteration % self.save_period == 0 and iteration != self.niter and self.iteration_filename != None and self.iteration_filename != "":
220 self.save(os.path.join(self.log_base_path, self.iteration_filename % self.current_iteration))
221
222
223 def run(self, init_batch = None, **kwargs):
224 """Run the configured evolution routine and return elapsed time in seconds."""
225 self._update_params(**kwargs)
226 if getattr(self, "start_time", None) is None:
227 self.start_time = timer()
228 # If needed, generate the initial batch
229 if init_batch == None:
230 if not hasattr(self, "init_batch") or self.init_batch == None:
231 self.gen_init_batch()
232 else:
233 self.init_batch = init_batch
234 # Run the illumination process !
235 batch, logbook = self.ea_fn(self.init_batch, self.toolbox, self.container, self.batch_size, self.niter, cxpb = self.cxpb, mutpb = self.mutpb, stats = self.stats, halloffame = self.halloffame, verbose = self.verbose, start_time = self.start_time, iteration_callback = self._iteration_callback)
236 if self.final_filename != None and self.final_filename != "":
237 self.save(os.path.join(self.log_base_path, self.final_filename))
238 self.total_elapsed = timer() - self.start_time
239 return self.total_elapsed
240
241
242 def data_archive(self):
243 """Return the archive, generation metadata, logbook, and any supplied result information."""
244 results = {}
245 def copy_attr(obj, names):
246 for name in names:
247 if hasattr(obj, name):
248 results[name] = getattr(obj, name)
249 copy_attr(self, ['init_batch_size', 'batch_size', 'niter', 'container', 'current_iteration', 'current_batch', 'logbook', 'container'])
250 #copy_attr(self.container, ['features_domain', 'fitness_domain', 'solutions', 'fitness', 'features', 'best_fitness', 'best_fitness_array'])
251 results = {**results, **self._results_infos}
252 return results
253
254
255 def save(self, outputFile):
256 """Write the DEAP result dictionary to a pickle file."""
257 results = self.data_archive()
258 with open(outputFile, "wb") as f:
259 pickle.dump(results, f)
260
261
262 def add_results_infos(self, *args):
263 """Merge a metadata mapping or set one key and value for later snapshots."""
264 if len(args) == 1:
265 self._results_infos = {**self._results_infos, **args[0]}
266 elif len(args) == 2:
267 self._results_infos[args[0]] = args[1]
268 else:
269 raise ValueError("Please either pass a dictionary or key, value as parameter.")
270
271
272
273
274# MODELINE "{{{1
275# vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8
276# vim:foldmethod=marker
_init_stats(self, stats=None)
Definition deap.py:178
_iteration_callback(self, iteration, batch, container, logbook)
Definition deap.py:210
_init_container(self, container=None)
Definition deap.py:170
gen_init_batch(self, init_batch_size=None)
Definition deap.py:191
run(self, init_batch=None, **kwargs)
Definition deap.py:223