QDpy
Loading...
Searching...
No Matches
modern.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Real-valued QD methods with native evaluation, callbacks and logging."""
6
7from collections import defaultdict
8from math import isfinite
9from operator import index
10import random
11from timeit import default_timer as timer
12import warnings
13
14import numpy as np
15from scipy.spatial.distance import cdist
16
17from qdpy.base import registry
18from qdpy.containers import Container, CVTGrid, Grid, LocalParetoArchive, ParetoGrid
19from qdpy.tools import iso_line_cross, iso_line_dd
20from .base import QDAlgorithm
21
22__all__ = ["IsoLineMAPElites", "IsoLineCrossMAPElites", "CMAMAE", "DominatedNoveltySearch", "MOME", "MOURQD"]
23
24
25def _positive_int(value, name):
26 value = index(value)
27 if value < 1:
28 raise ValueError(f"{name} must be positive.")
29 return value
30
31
32def _bounds(bounds):
33 lower, upper = bounds
34 if not (isfinite(lower) and isfinite(upper) and lower < upper):
35 raise ValueError("Genome bounds must be finite and increasing.")
36 return lower, upper
37
38
39def _variation_settings(bounds, iso_sigma, line_sigma):
40 if not (0 <= iso_sigma < np.inf and 0 <= line_sigma < np.inf):
41 raise ValueError("Iso+LineDD scales must be finite and nonnegative.")
42 return _bounds(bounds)
43
44
45def _vary(archive, dimension, bounds, iso_sigma, line_sigma, sample, *, recorder=None):
46 if len(archive) == 0:
47 return np.random.uniform(*bounds, size=dimension)
48 first, second = sample(archive), sample(archive)
49 if recorder is not None:
50 recorder._parentage("iso_line_dd", (first, second))
51 return iso_line_dd(first, second, bounds=bounds, iso_sigma=iso_sigma, line_sigma=line_sigma)
52
53
54
55@registry.register
57 """MAP-Elites with uniform parent draws and bounded Iso+LineDD variation.
58
59 :param container: One-elite grid or CVT grid.
60 :param budget: Candidate evaluations per run.
61 :param dimension: Genome length.
62 :param ind_domain: Common lower and upper genome bounds.
63 :param batch_size: Maximum number of in-flight candidates.
64 :param iso_sigma: Independent noise scale.
65 :param line_sigma: Shared direction noise scale.
66 """
67
68 def __init__(self, container, budget, dimension, ind_domain=(0.0, 1.0), *,
69 batch_size=1, iso_sigma=0.01, line_sigma=0.2, **kwargs):
70 if not isinstance(container, Grid) or container.max_items_per_bin != 1:
71 raise ValueError("IsoLineMAPElites requires a one-elite Grid.")
72 self.ind_domain = _variation_settings(ind_domain, iso_sigma, line_sigma)
73 self.iso_sigma = iso_sigma
74 self.line_sigma = line_sigma
75 super().__init__(container, _positive_int(budget, "budget"),
76 batch_size=_positive_int(batch_size, "batch_size"),
77 dimension=_positive_int(dimension, "dimension"), **kwargs)
78
79 def _internal_ask(self, base_ind):
80 base_ind[:] = _vary(self.container, self.dimension, self.ind_domain,
81 self.iso_sigma, self.line_sigma, random.choice, recorder=self._lineage_recorder)
82 return base_ind
83
84
85
86@registry.register
88 """IsoLineCross MAP-Elites for a one-elite Grid or CVTGrid.
89
90 The two parents are drawn uniformly with replacement. Their varied
91 coordinates form contiguous segments when crossover is selected.
92
93 :param crossover_probability: Fraction of proposals using crossover.
94 :param crossover_rate: Number of sampled breakpoints per gene.
95 :param iso_sigma: Isotropic noise scale.
96 :param line_sigma: Directional noise scale. Zero selects IsoCross.
97 :param kwargs: Native IsoLineMAPElites configuration.
98 """
99
100 def __init__(self, container, budget, dimension, ind_domain=(0., 1.), *, crossover_probability=0.5,
101 crossover_rate=0.1, iso_sigma=0.005, line_sigma=0.05, **kwargs):
102 if not (0 <= crossover_probability <= 1 and 0 <= crossover_rate <= 1):
103 raise ValueError("Crossover probability and rate must be in [0, 1].")
104 self.crossover_probability = crossover_probability
105 self.crossover_rate = crossover_rate
106 super().__init__(container, budget, dimension, ind_domain, iso_sigma=iso_sigma,
107 line_sigma=line_sigma, **kwargs)
108
109 def _internal_ask(self, base_ind):
110 if not self.container or self.crossover_probability == 0:
111 return super()._internal_ask(base_ind)
112 first, second = random.choice(self.container), random.choice(self.container)
113 if self._lineage_recorder is not None:
114 self._lineage_recorder._parentage("iso_line_cross", (first, second))
115 base_ind[:] = iso_line_cross(first, second,
116 iso_sigma=self.iso_sigma, line_sigma=self.line_sigma,
117 crossover_probability=self.crossover_probability,
118 crossover_rate=self.crossover_rate, bounds=self.ind_domain)
119 return base_ind
120
121
123 """Commit ordered evaluator results in one generation before callbacks."""
124
125 _fixed_batch_feedback = True
126 _requires_proposed_genome = False
127
128 def reinit(self):
129 super().reinit()
131 self._pending_size = 0
132 self._issued = []
133 self._issued_genomes = []
134 self._staging = False
135 self._staged = None
136 self._expected_genome = None
137
138 def _start_fixed_batch(self, size):
139 if self._pending_size:
140 raise RuntimeError("The current generation is still pending.")
141 self._pending_size = size
145
146 @property
147 def current_iter(self):
148 """Number of committed generations, including partial generations."""
149 return self._completed_generations
150
151 def _clear_generation(self):
152 self._pending_size = 0
153 self._issued.clear()
154 self._issued_genomes.clear()
155 self._staging = False
156 self._staged = None
157 self._expected_genome = None
158
159 def ask(self):
160 if len(self._issued) >= self._pending_size:
161 raise RuntimeError("Use ask_batch() to start a manual generation.")
162 individual = super().ask()
163 self._issued.append(individual)
165 self._issued_genomes.append(tuple(individual))
166 return individual
167
168
169 def ask_batch(self, size=None):
170 """Return a generation of candidates to evaluate.
171
172 The default is the configured batch size. Pass a smaller size for a
173 final partial generation. Send its results to ``tell_batch()``.
174 """
175 size = self.batch_size if size is None else _positive_int(size, "size")
176 if size > self.batch_size:
177 raise ValueError("A generation cannot exceed batch_size.")
178 if self._pending_size:
179 raise RuntimeError("The current generation is still pending.")
180 try:
181 self._start_fixed_batch(size)
182 return [self.ask() for _ in range(size)]
183 except Exception:
184 self._clear_generation()
185 raise
186
187
188 def tell_batch(self, results):
189 """Commit one result per candidate, in the order returned by ask_batch.
190
191 Use any native evaluator result or ``None`` for a failed slot. Every
192 slot counts as an attempt. A cardinality error leaves the batch pending.
193 """
194 if not self._pending_size:
195 raise RuntimeError("Use ask_batch() before tell_batch().")
196 if len(results) != self._pending_size:
197 raise ValueError("Supply one result per candidate in the generation.")
198 records = [(candidate, result, None) for candidate, result in zip(self._issued, results)]
199 self._receive_fixed_batch(records, False, timer())
200
201 def tell(self, individual, fitness=None, features=None, scores=None,
202 elapsed=None, verbose=False, tell_container=True):
203 if not self._staging:
204 raise RuntimeError("Use tell_batch() to report a manual generation.")
205 if self._requires_proposed_genome and tuple(individual) != self._expected_genome:
206 raise ValueError("The evaluated genome differs from the proposal for this slot.")
207 self._attach_evaluation(individual, fitness, features, scores, elapsed)
208 self._check_candidate(individual)
209 self._staged = individual
210 return False
211
212 def _check_candidate(self, individual):
213 self._check_measurements(individual)
214 self.container._check_if_can_be_added(individual)
215
216 def _check_measurements(self, individual):
217 genome = np.asarray(individual, dtype=float)
218 if genome.shape != (self.dimension,) or not np.all(np.isfinite(genome)):
219 raise ValueError("An evaluated genome must be a finite vector of the configured length.")
220 fitness = self.container.get_ind_fitness(individual)
221 descriptors = tuple(self.container.get_ind_features(individual))
222 if not descriptors or not all(map(isfinite, descriptors)) or not all(map(isfinite, fitness.values)):
223 raise ValueError("A generation needs finite fitness and nonempty finite descriptors.")
224
225 def _generation_feedback(self, position):
226 return {}
227
228 def _offer_to_grid(self, individual, cell):
229 """Offer a measurement to a fixed grid with a separate total capacity."""
230 grid = self.container
231 if grid.free < 1 and not grid.solutions[cell]:
232 return False
233 before = grid.nb_added
234 grid.add(individual)
235 return grid.nb_added > before
236
237 def _commit_generation(self, evaluated):
238 """Offer validated measurements to a native grid in proposal order."""
239 return {slot for slot, individual in enumerate(evaluated)
240 if individual is not None and self._offer_to_grid(individual, self.container.index_grid(individual))}
241
242 def _receive_fixed_batch(self, records, verbose, batch_start_time):
243 evaluated = []
244 previous = self.nb_evaluations
245 try:
247 self._staging = True
248 for position, (candidate, result, elapsed) in enumerate(records):
250 self._expected_genome = self._issued_genomes[position]
251 self._staged = None
252 if result is not None:
253 try:
254 self._tell_evaluation_result(candidate, result, elapsed, verbose)
255 except (IndexError, KeyError, TypeError, ValueError, OverflowError) as error:
256 warnings.warn(f"Invalid generation result: {error}", stacklevel=2)
257 evaluated.append(self._staged)
258 self._staging = False
259 admitted = self._commit_generation(evaluated)
260 for position, individual in enumerate(evaluated):
261 if individual is None:
263 else:
264 self._tell_after_container_update(individual, position in admitted,
265 self._generation_feedback(position))
266 self._completed_generations += 1
267 for callback in self._callbacks.get("iteration"):
268 callback(self, timer() - batch_start_time)
269 finally:
270 remaining = len(records) - (self.nb_evaluations - previous)
271 if remaining > 0:
272 self._account_evaluations(remaining)
273 self._clear_generation()
274
275 def optimise(self, *args, **kwargs):
276 """Schedule fixed generations via the native optimiser."""
277 if self._pending_size:
278 raise RuntimeError("Complete the pending manual generation before optimise().")
279 try:
280 return super().optimise(*args, **kwargs)
281 finally:
282 self._clear_generation()
283
284
285def _cma_strategy(center, sigma, population_size, seed, bounds=None):
286 """Create pycma with a private Gaussian random stream."""
287 import cma
288
289 options = dict(popsize=population_size, verbose=-9,
290 randn=np.random.RandomState(seed).randn, seed=np.nan)
291 if bounds is not None:
292 options["bounds"] = list(bounds)
293 return cma.CMAEvolutionStrategy(list(center), sigma, options)
294
295
297 """Share ordered CMA sampling and rank adaptation across emitters."""
298
299 _requires_proposed_genome = True
300
301 def _start_fixed_batch(self, size):
302 super()._start_fixed_batch(size)
303 self._vectors = self._sample_vectors(size)
304
305 def _search_rng(self):
306 return random if self._rng is None else self._rng
307
308 def _new_strategy(self, center, *, bounded=True):
309 seed = self._search_rng().randint(1, 2**32 - 1)
310 return _cma_strategy(center, self.sigma0, self.batch_size, seed, self.ind_domain if bounded else None)
311
312 def _sample_vectors(self, size):
313 if self._strategy is None or self._strategy.stop():
314 self._strategy = self._new_strategy(self._restart_center())
315 return self._strategy.ask(number=size)
316
317 def _clear_generation(self):
318 super()._clear_generation()
319 self._vectors = ()
320 self._gains = ()
321
322 def _internal_ask(self, base_ind):
323 base_ind[:] = self._vectors[len(self._issued)]
324 return base_ind
325
326 def _check_candidate(self, individual):
327 super()._check_candidate(individual)
328 self.container.index_grid(individual)
329
330 def _generation_feedback(self, position):
331 return {"improvement": self._gains[position]}
332
333 def _adapt_strategy(self, vectors):
334 order = np.argsort(-self._gains, kind="stable")
335 losses = np.empty(len(order), dtype=int)
336 losses[order] = np.arange(len(order))
337 self._strategy.tell(vectors, losses)
338 return order
339
340
341
342@registry.register
344 """Single-objective CMA-MAE with a best-only result grid and separate search state.
345
346 Install the optional ``cma`` extra. Each generation is ranked against the
347 thresholds at its start. The final partial generation updates the grids.
348
349 :param container: Fixed, one-elite Grid or CVTGrid for reporting best solutions.
350 :param budget: Candidate evaluations per run.
351 :param x0: Starting point in genome coordinates.
352 :param sigma0: Initial CMA step size.
353 :param batch_size: CMA population size.
354 :param threshold_min: Initial threshold in signed, weighted quality units.
355 :param learning_rate: Archive learning rate between zero and one.
356 :param ind_domain: Optional common lower and upper genome bounds.
357 :param seed: Optional private seed for covariance search and restarts.
358 """
359
360 def _check_optimizer_dependency(self):
361 try:
362 import cma
363 except ImportError as error:
364 raise ImportError("CMAMAE requires the QDpy 'cma' extra.") from error
365
366 def __init__(self, container, budget, x0, sigma0, batch_size, threshold_min, *,
367 learning_rate=0.01, ind_domain=None, seed=None, **kwargs):
369 if type(container) not in (Grid, CVTGrid) or container.max_items_per_bin != 1 or len(container.fitness_domain) != 1:
370 raise ValueError("CMAMAE requires a fixed, one-elite Grid or CVTGrid with one objective.")
371 self.x0 = np.asarray(x0, dtype=float).copy()
372 if self.x0.ndim != 1 or self.x0.size < 2 or not np.all(np.isfinite(self.x0)):
373 raise ValueError("x0 must be a finite vector with at least two coordinates.")
374 if not (0 < sigma0 < np.inf and isfinite(threshold_min) and 0 <= learning_rate <= 1):
375 raise ValueError("Provide a positive finite sigma0, finite threshold and learning_rate in [0, 1].")
376 batch_size = _positive_int(batch_size, "batch_size")
377 if batch_size < 2:
378 raise ValueError("CMAMAE needs at least two candidates per population.")
379 self.ind_domain = None if ind_domain is None else _bounds(ind_domain)
380 if self.ind_domain is not None and not np.all(np.clip(self.x0, *self.ind_domain) == self.x0):
381 raise ValueError("x0 lies outside the genome bounds.")
382 self.sigma0 = sigma0
383 self.threshold_min = threshold_min
384 self.learning_rate = learning_rate
385 self.seed = seed
386 super().__init__(container, _positive_int(budget, "budget"), batch_size=batch_size,
387 dimension=len(self.x0), **kwargs)
388
389 def reinit(self):
390 """Reset the emitter and threshold state while retaining the result archive."""
391 super().reinit()
392 self._thresholds = {}
393 self._search_elites = {}
394 self._strategy = None
395 self._vectors = ()
396 self._rng = random.Random(self.seed) if self.seed is not None else None
397
398
399 def threshold(self, cell):
400 """Return the current admission threshold for a descriptor cell."""
401 return self._thresholds.get(cell, self.threshold_min)
402
403 @property
404 def search_elites(self):
405 """Return a mapping of threshold-qualified search representatives by cell."""
406 return dict(self._search_elites)
407
408 def _restart_center(self):
409 return self._search_rng().choice(list(self._search_elites.values())) if self._search_elites else self.x0
410
411 def _update_annealed_archive(self, evaluated):
412 self._gains = np.full(len(evaluated), -np.inf)
413 qualifying = defaultdict(list)
414 admitted = set()
415 for position, individual in enumerate(evaluated):
416 if individual is None:
417 continue
418 cell = self.container.index_grid(individual)
419 fitness = self.container.get_ind_fitness(individual)
420 quality = fitness.values[0] * fitness.weights[0]
421 self._gains[position] = quality - self.threshold(cell)
422 if self._gains[position] > 0:
423 qualifying[cell].append((quality, individual))
424 if self._offer_to_grid(individual, cell):
425 admitted.add(position)
426 for cell, entries in qualifying.items():
427 current = self.threshold(cell)
428 decay = (1 - self.learning_rate) ** len(entries)
429 mean = np.mean([quality for quality, _ in entries])
430 self._thresholds[cell] = decay * current + (1 - decay) * mean
431 self._search_elites[cell] = max(entries, key=lambda entry: entry[0])[1]
432 return admitted
433
434 def _commit_generation(self, evaluated):
435 admitted = self._update_annealed_archive(evaluated)
436 if len(evaluated) == self.batch_size and any(ind is not None for ind in evaluated):
437 self._adapt_strategy(self._vectors)
438 return admitted
439
440
441def _dominated_novelty(qualities, descriptors, k, block_size=128):
442 qualities = np.asarray(qualities, dtype=float)
443 descriptors = np.asarray(descriptors, dtype=float)
444 scores = np.empty(len(qualities))
445 nearest = min(k, len(qualities))
446 for start in range(0, len(qualities), block_size):
447 stop = min(start + block_size, len(qualities))
448 fitter = qualities[None, :] > qualities[start:stop, None]
449 distances = cdist(descriptors[start:stop], descriptors)
450 distances[~fitter] = np.inf
451 distances.partition(nearest - 1, axis=1)
452 selected = distances[:, :nearest]
453 count = np.minimum(fitter.sum(axis=1), nearest)
454 mask = np.arange(nearest) < count[:, None]
455 # Partition does not sort the selected prefix. Filter unavailable
456 # slots by distance and preserve the denominator for the fitter set.
457 selected = np.sort(selected, axis=1)
458 total = selected.sum(axis=1, where=mask)
459 scores[start:stop] = np.divide(total, count, out=np.full(len(count), np.inf), where=count > 0)
460 return scores
461
462
463
464@registry.register
466 """Keep candidates distant from their nearest strictly fitter neighbours.
467
468 Genome duplicates keep the first occurrence. Equal novelty scores keep
469 incumbents ahead of offspring in proposal order. Fitness values stay raw.
470
471 :param budget: Candidate evaluations per run.
472 :param dimension: Genome length.
473 :param population_size: Maximum number of survivors.
474 :param batch_size: Number of offspring per generation.
475 :param k: Maximum number of strictly fitter neighbours to score.
476 :param ind_domain: Shared genome bounds.
477 :param fitness_domain: Optional single objective interval.
478 :param iso_sigma: Independent noise scale.
479 :param line_sigma: Shared direction noise scale.
480 """
481
482 def __init__(self, budget, dimension, population_size, batch_size, *, k=5,
483 ind_domain=(0.0, 1.0), fitness_domain=None, iso_sigma=0.01, line_sigma=0.2, **kwargs):
484 self.ind_domain = _variation_settings(ind_domain, iso_sigma, line_sigma)
485 self.iso_sigma = iso_sigma
486 self.line_sigma = line_sigma
487 self.k = _positive_int(k, "k")
488 self._descriptor_size = None
489 if fitness_domain is not None and len(fitness_domain) != 1:
490 raise ValueError("DominatedNoveltySearch requires one objective.")
491 if fitness_domain is None:
492 fitness_domain = ((-np.inf, np.inf),)
493 archive = Container(capacity=_positive_int(population_size, "population_size"),
494 fitness_domain=fitness_domain)
495 super().__init__(archive, _positive_int(budget, "budget"), nb_objectives=1,
496 batch_size=_positive_int(batch_size, "batch_size"),
497 dimension=_positive_int(dimension, "dimension"), **kwargs)
498
499 def _internal_ask(self, base_ind):
500 base_ind[:] = _vary(self.container, self.dimension, self.ind_domain,
501 self.iso_sigma, self.line_sigma, random.choice)
502 return base_ind
503
504 def _check_candidate(self, individual):
505 super()._check_candidate(individual)
506 size = len(individual.features)
507 if self._descriptor_size is not None and size != self._descriptor_size:
508 raise ValueError("Descriptor length differs from earlier evaluations.")
509 self._descriptor_size = size
510
511 def _commit_generation(self, evaluated):
512 archive = self.container
513 parents = list(archive)
514 seen = {tuple(ind) for ind in parents}
515 candidates = parents.copy()
516 offspring_slots = {}
517 for slot, ind in enumerate(evaluated):
518 if ind is not None and tuple(ind) not in seen:
519 seen.add(tuple(ind))
520 candidates.append(ind)
521 offspring_slots[id(ind)] = slot
522 qualities = [fit.values[0] * fit.weights[0] for fit in map(archive.get_ind_fitness, candidates)]
523 descriptors = [tuple(archive.get_ind_features(ind)) for ind in candidates]
524 scores = _dominated_novelty(qualities, descriptors, self.k)
525 order = np.argsort(-scores, kind="stable")[:archive.capacity]
526 survivors = [candidates[position] for position in order]
527 identities = {id(ind) for ind in survivors}
528 for ind in parents:
529 if id(ind) not in identities:
530 archive.discard(ind)
531 admitted = set()
532 for ind in survivors:
533 if id(ind) in offspring_slots:
534 archive.add(ind)
535 admitted.add(offspring_slots[id(ind)])
536 recentness = {id(ind): order for ind, order in zip(archive, archive.recentness)}
537 archive.items[:] = survivors
538 archive.recentness[:] = [recentness[id(ind)] for ind in survivors]
539 archive._recompute_best()
540 return admitted
541
542
543
544@registry.register
546 """Multi-Objective MAP-Elites with uniform cell and front sampling.
547
548 The first generation uses uniform real-valued proposals. Later
549 generations recombine parents with Iso+LineDD. Inspect cell fronts
550 and hypervolume through the ParetoGrid.
551
552 :param container: ParetoGrid for the search.
553 :param budget: Candidate evaluations per run.
554 :param dimension: Genome length.
555 :param batch_size: Number of candidates in a generation.
556 :param ind_domain: Shared genome bounds.
557 :param iso_sigma: Independent noise scale.
558 :param line_sigma: Shared direction noise scale.
559 """
560
561 def __init__(self, container, budget, dimension, batch_size, *, ind_domain=(0.0, 1.0),
562 iso_sigma=0.01, line_sigma=0.2, **kwargs):
563 if not isinstance(container, ParetoGrid):
564 raise ValueError("MOME requires a ParetoGrid.")
565 self.ind_domain = _variation_settings(ind_domain, iso_sigma, line_sigma)
566 self.iso_sigma = iso_sigma
567 self.line_sigma = line_sigma
568 kwargs.setdefault("optimisation_task", container.fitness_weights)
569 super().__init__(container, _positive_int(budget, "budget"),
570 batch_size=_positive_int(batch_size, "batch_size"),
571 dimension=_positive_int(dimension, "dimension"), **kwargs)
572
573 def _start_fixed_batch(self, size):
574 super()._start_fixed_batch(size)
575 self._occupied = [front for front in self.container.solutions.values() if front]
576
577 def _sample_front(self, archive):
578 return random.choice(random.choice(self._occupied))
579
580 def _internal_ask(self, base_ind):
581 base_ind[:] = _vary(self.container, self.dimension, self.ind_domain,
582 self.iso_sigma, self.line_sigma, self._sample_front)
583 return base_ind
584
585 def _commit_generation(self, evaluated):
586 admitted = self.container._merge_fronts(ind for ind in evaluated if ind is not None)
587 return {slot for slot, ind in enumerate(evaluated) if id(ind) in admitted}
588
589
590
591@registry.register
593 """Draw parents uniformly from a LocalParetoArchive and apply Iso+LineDD.
594
595 A batch reads the current archive when drawing parents. Measurements
596 update the archive in proposal order.
597
598 :param container: LocalParetoArchive with the objective weights.
599 :param budget: Number of candidate evaluation attempts.
600 :param dimension: Number of real genome coordinates.
601 :param batch_size: Maximum number of proposals per batch.
602 :param ind_domain: Shared lower and upper genome bounds.
603 :param iso_sigma: Independent noise scale.
604 :param line_sigma: Shared direction noise scale.
605 """
606
607 def __init__(self, container, budget, dimension, batch_size=1, *,
608 ind_domain=(0., 1.), iso_sigma=0.005, line_sigma=0.05, **kwargs):
609 if not isinstance(container, LocalParetoArchive):
610 raise ValueError("MOURQD requires a LocalParetoArchive.")
611 self.ind_domain = _variation_settings(ind_domain, iso_sigma, line_sigma)
612 self.iso_sigma = iso_sigma
613 self.line_sigma = line_sigma
614 kwargs.setdefault("optimisation_task", container.fitness_weights)
615 super().__init__(container, _positive_int(budget, "budget"),
616 dimension=_positive_int(dimension, "dimension"),
617 batch_size=_positive_int(batch_size, "batch_size"), **kwargs)
618
619 def _internal_ask(self, base_ind):
620 base_ind[:] = _vary(self.container, self.dimension, self.ind_domain,
621 self.iso_sigma, self.line_sigma, random.choice)
622 return base_ind
623
624 def _commit_generation(self, evaluated):
625 admitted = set()
626 for slot, individual in enumerate(evaluated):
627 if individual is not None and self._offer_to_container(individual, False):
628 admitted.add(slot)
629 return admitted
IndividualLike ask(self)
Definition base.py:195
_offer_to_container(self, individual, verbose)
Definition base.py:561
_account_evaluations(self, count=1)
Definition base.py:642
None _attach_evaluation(self, ind, fitness, features, scores, elapsed)
Definition base.py:567
None _start_fixed_batch(self, int size)
Definition base.py:764
None _receive_fixed_batch(self, records, verbose, batch_start_time)
Definition base.py:768
bool _tell_evaluation_result(self, IndividualLike individual, Any result, float elapsed, bool verbose, *, positional_sizes=())
Definition base.py:714
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
Adapt a covariance matrix using annealed cell-level improvement.
Definition modern.py:343
_commit_generation(self, evaluated)
Definition modern.py:434
_update_annealed_archive(self, evaluated)
Definition modern.py:411
threshold(self, cell)
Read the search threshold for a descriptor cell.
Definition modern.py:399
Select a fixed-size grid-free population by dominated novelty.
Definition modern.py:465
Use stochastic segment crossover in a native MAP-Elites search.
Definition modern.py:87
Fill a one-elite grid using Iso+LineDD variation.
Definition modern.py:56
Sample occupied cells and evolve their bounded Pareto fronts.
Definition modern.py:545
_start_fixed_batch(self, size)
Definition modern.py:573
_commit_generation(self, evaluated)
Definition modern.py:585
_sample_front(self, archive)
Definition modern.py:577
_internal_ask(self, base_ind)
Definition modern.py:580
Evolve an unstructured archive of local Pareto trade-offs.
Definition modern.py:592
_commit_generation(self, evaluated)
Definition modern.py:624
_internal_ask(self, base_ind)
Definition modern.py:619
_new_strategy(self, center, *, bounded=True)
Definition modern.py:308
_check_measurements(self, individual)
Definition modern.py:216
optimise(self, *args, **kwargs)
Definition modern.py:275
_receive_fixed_batch(self, records, verbose, batch_start_time)
Definition modern.py:242
_offer_to_grid(self, individual, cell)
Definition modern.py:228
ask_batch(self, size=None)
Issue one manual generation in proposal order.
Definition modern.py:169
tell_batch(self, results)
Apply results from the outstanding manual generation.
Definition modern.py:188