21__all__ = [
"qdSimple",
"DEAPQDAlgorithm"]
27from timeit
import default_timer
as timer
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.
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.
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.
60 if start_time ==
None:
62 logbook = deap.tools.Logbook()
63 logbook.header = [
"iteration",
"containerSize",
"evals",
"nbUpdated"] + (stats.fields
if stats
else []) + [
"elapsed"]
65 if len(init_batch) == 0:
66 raise ValueError(
"``init_batch`` must not be empty.")
69 invalid_ind = [ind
for ind
in init_batch
if not ind.fitness.valid]
71 fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
72 for ind, fit
in zip(invalid_ind, fitnesses):
73 ind.fitness.values = fit[0]
78 if halloffame
is not None:
79 halloffame.update(init_batch)
82 nb_updated = container.update(init_batch, issue_warning=show_warnings, ignore_exceptions=
True)
84 raise ValueError(
"No individual could be added to the container !")
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)
92 if iteration_callback !=
None:
93 iteration_callback(0, init_batch, container, logbook)
96 for i
in range(1, niter + 1):
99 batch = toolbox.select(container, batch_size)
102 offspring = deap.algorithms.varAnd(batch, toolbox, cxpb, mutpb)
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]
118 nb_updated = container.update(offspring, issue_warning=show_warnings)
121 if halloffame
is not None:
122 halloffame.update(container)
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)
128 print(logbook.stream)
131 if iteration_callback !=
None:
132 iteration_callback(i, batch, container, logbook)
134 return batch, logbook
139 """Configure and run a DEAP QD experiment with optional result snapshots.
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.
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):
165 if results_infos !=
None:
172 if container ==
None:
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)
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:
195 if init_batch_size !=
None:
197 if not hasattr(self,
"init_batch_size")
or self.
init_batch_size ==
None:
198 raise ValueError(
"Please specify 'init_batch_size'")
204 for k,v
in kwargs.items():
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":
223 def run(self, init_batch = None, **kwargs):
224 """Run the configured evolution routine and return elapsed time in seconds."""
226 if getattr(self,
"start_time",
None)
is None:
229 if init_batch ==
None:
230 if not hasattr(self,
"init_batch")
or self.
init_batch ==
None:
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)
243 """Return the archive, generation metadata, logbook, and any supplied result information."""
245 def copy_attr(obj, 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'])
256 """Write the DEAP result dictionary to a pickle file."""
258 with open(outputFile,
"wb")
as f:
259 pickle.dump(results, f)
263 """Merge a metadata mapping or set one key and value for later snapshots."""
269 raise ValueError(
"Please either pass a dictionary or key, value as parameter.")
_init_stats(self, stats=None)
_update_params(self, **kwargs)
_iteration_callback(self, iteration, batch, container, logbook)
add_results_infos(self, *args)
_init_container(self, container=None)
gen_init_batch(self, init_batch_size=None)
run(self, init_batch=None, **kwargs)