5"""Real-valued QD methods with native evaluation, callbacks and logging."""
7from collections
import defaultdict
8from math
import isfinite
9from operator
import index
11from timeit
import default_timer
as timer
15from scipy.spatial.distance
import cdist
18from qdpy.containers import Container, CVTGrid, Grid, LocalParetoArchive, ParetoGrid
19from qdpy.tools import iso_line_cross, iso_line_dd
20from .base
import QDAlgorithm
22__all__ = [
"IsoLineMAPElites",
"IsoLineCrossMAPElites",
"CMAMAE",
"DominatedNoveltySearch",
"MOME",
"MOURQD"]
25def _positive_int(value, name):
28 raise ValueError(f
"{name} must be positive.")
34 if not (isfinite(lower)
and isfinite(upper)
and lower < upper):
35 raise ValueError(
"Genome bounds must be finite and increasing.")
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)
45def _vary(archive, dimension, bounds, iso_sigma, line_sigma, sample, *, recorder=None):
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)
57 """MAP-Elites with uniform parent draws and bounded Iso+LineDD variation.
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.
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)
75 super().__init__(container, _positive_int(budget,
"budget"),
76 batch_size=_positive_int(batch_size,
"batch_size"),
77 dimension=_positive_int(dimension,
"dimension"), **kwargs)
88 """IsoLineCross MAP-Elites for a one-elite Grid or CVTGrid.
90 The two parents are drawn uniformly with replacement. Their varied
91 coordinates form contiguous segments when crossover is selected.
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.
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].")
106 super().__init__(container, budget, dimension, ind_domain, iso_sigma=iso_sigma,
107 line_sigma=line_sigma, **kwargs)
123 """Commit ordered evaluator results in one generation before callbacks."""
125 _fixed_batch_feedback =
True
126 _requires_proposed_genome =
False
140 raise RuntimeError(
"The current generation is still pending.")
148 """Number of committed generations, including partial generations."""
151 def _clear_generation(self):
161 raise RuntimeError(
"Use ask_batch() to start a manual generation.")
162 individual = super().
ask()
163 self.
_issued.append(individual)
170 """Return a generation of candidates to evaluate.
172 The default is the configured batch size. Pass a smaller size for a
173 final partial generation. Send its results to ``tell_batch()``.
175 size = self.
batch_size if size
is None else _positive_int(size,
"size")
177 raise ValueError(
"A generation cannot exceed batch_size.")
179 raise RuntimeError(
"The current generation is still pending.")
182 return [self.
ask()
for _
in range(size)]
189 """Commit one result per candidate, in the order returned by ask_batch.
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.
195 raise RuntimeError(
"Use ask_batch() before tell_batch().")
197 raise ValueError(
"Supply one result per candidate in the generation.")
198 records = [(candidate, result,
None)
for candidate, result
in zip(self.
_issued, results)]
201 def tell(self, individual, fitness=None, features=None, scores=None,
202 elapsed=None, verbose=False, tell_container=True):
204 raise RuntimeError(
"Use tell_batch() to report a manual generation.")
206 raise ValueError(
"The evaluated genome differs from the proposal for this slot.")
212 def _check_candidate(self, individual):
214 self.
container._check_if_can_be_added(individual)
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.")
225 def _generation_feedback(self, position):
229 """Offer a measurement to a fixed grid with a separate total capacity."""
231 if grid.free < 1
and not grid.solutions[cell]:
233 before = grid.nb_added
235 return grid.nb_added > before
238 """Offer validated measurements to a native grid in proposal order."""
239 return {slot
for slot, individual
in enumerate(evaluated)
248 for position, (candidate, result, elapsed)
in enumerate(records):
252 if result
is not None:
255 except (IndexError, KeyError, TypeError, ValueError, OverflowError)
as error:
256 warnings.warn(f
"Invalid generation result: {error}", stacklevel=2)
260 for position, individual
in enumerate(evaluated):
261 if individual
is None:
267 for callback
in self.
_callbacks.get(
"iteration"):
268 callback(self, timer() - batch_start_time)
276 """Schedule fixed generations via the native optimiser."""
278 raise RuntimeError(
"Complete the pending manual generation before optimise().")
280 return super().
optimise(*args, **kwargs)
285def _cma_strategy(center, sigma, population_size, seed, bounds=None):
286 """Create pycma with a private Gaussian random stream."""
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)
297 """Share ordered CMA sampling and rank adaptation across emitters."""
299 _requires_proposed_genome =
True
305 def _search_rng(self):
306 return random
if self._rng
is None else self._rng
308 def _new_strategy(self, center, *, bounded=True):
310 return _cma_strategy(center, self.
sigma0, self.
batch_size, seed, self.ind_domain
if bounded
else None)
312 def _sample_vectors(self, size):
317 def _clear_generation(self):
318 super()._clear_generation()
326 def _check_candidate(self, individual):
327 super()._check_candidate(individual)
330 def _generation_feedback(self, position):
331 return {
"improvement": self.
_gains[position]}
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))
344 """Single-objective CMA-MAE with a best-only result grid and separate search state.
346 Install the optional ``cma`` extra. Each generation is ranked against the
347 thresholds at its start. The final partial generation updates the grids.
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.
360 def _check_optimizer_dependency(self):
363 except ImportError
as error:
364 raise ImportError(
"CMAMAE requires the QDpy 'cma' extra.")
from error
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")
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)
381 raise ValueError(
"x0 lies outside the genome bounds.")
386 super().__init__(container, _positive_int(budget,
"budget"), batch_size=batch_size,
387 dimension=len(self.
x0), **kwargs)
390 """Reset the emitter and threshold state while retaining the result archive."""
396 self.
_rng = random.Random(self.
seed)
if self.
seed is not None else None
400 """Return the current admission threshold for a descriptor cell."""
405 """Return a mapping of threshold-qualified search representatives by cell."""
408 def _restart_center(self):
411 def _update_annealed_archive(self, evaluated):
412 self.
_gains = np.full(len(evaluated), -np.inf)
413 qualifying = defaultdict(list)
415 for position, individual
in enumerate(evaluated):
416 if individual
is None:
418 cell = self.
container.index_grid(individual)
419 fitness = self.
container.get_ind_fitness(individual)
420 quality = fitness.values[0] * fitness.weights[0]
422 if self.
_gains[position] > 0:
423 qualifying[cell].append((quality, individual))
425 admitted.add(position)
426 for cell, entries
in qualifying.items():
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]
436 if len(evaluated) == self.
batch_size and any(ind
is not None for ind
in evaluated):
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]
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)
466 """Keep candidates distant from their nearest strictly fitter neighbours.
468 Genome duplicates keep the first occurrence. Equal novelty scores keep
469 incumbents ahead of offspring in proposal order. Fitness values stay raw.
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.
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)
487 self.
k = _positive_int(k,
"k")
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)
504 def _check_candidate(self, individual):
505 super()._check_candidate(individual)
506 size = len(individual.features)
508 raise ValueError(
"Descriptor length differs from earlier evaluations.")
513 parents = list(archive)
514 seen = {tuple(ind)
for ind
in parents}
515 candidates = parents.copy()
517 for slot, ind
in enumerate(evaluated):
518 if ind
is not None and tuple(ind)
not in seen:
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}
529 if id(ind)
not in identities:
532 for ind
in survivors:
533 if id(ind)
in offspring_slots:
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()
546 """Multi-Objective MAP-Elites with uniform cell and front sampling.
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.
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.
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)
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)
577 def _sample_front(self, archive):
578 return random.choice(random.choice(self.
_occupied))
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}
593 """Draw parents uniformly from a LocalParetoArchive and apply Iso+LineDD.
595 A batch reads the current archive when drawing parents. Measurements
596 update the archive in proposal order.
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.
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)
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)
626 for slot, individual
in enumerate(evaluated):
_offer_to_container(self, individual, verbose)
_check_archive_weights(self)
_account_evaluations(self, count=1)
int _nb_updated_in_iteration
None _attach_evaluation(self, ind, fitness, features, scores, elapsed)
int _nb_evaluations_in_iteration
None _start_fixed_batch(self, int size)
None _receive_fixed_batch(self, records, verbose, batch_start_time)
int _nb_suggestions_in_iteration
bool _tell_evaluation_result(self, IndividualLike individual, Any result, float elapsed, bool verbose, *, positional_sizes=())
None _tell_after_container_update(self, IndividualLike individual, bool added, Mapping[str, Any] xattr={})
Account for a completed tell and send feedback.
Adapt a covariance matrix using annealed cell-level improvement.
_commit_generation(self, evaluated)
_update_annealed_archive(self, evaluated)
threshold(self, cell)
Read the search threshold for a descriptor cell.
_check_optimizer_dependency(self)
Select a fixed-size grid-free population by dominated novelty.
_commit_generation(self, evaluated)
_internal_ask(self, base_ind)
Use stochastic segment crossover in a native MAP-Elites search.
int crossover_probability
_internal_ask(self, base_ind)
Fill a one-elite grid using Iso+LineDD variation.
_internal_ask(self, base_ind)
Sample occupied cells and evolve their bounded Pareto fronts.
_start_fixed_batch(self, size)
_commit_generation(self, evaluated)
_sample_front(self, archive)
_internal_ask(self, base_ind)
Evolve an unstructured archive of local Pareto trade-offs.
_commit_generation(self, evaluated)
_internal_ask(self, base_ind)
_sample_vectors(self, size)
_start_fixed_batch(self, size)
_adapt_strategy(self, vectors)
_internal_ask(self, base_ind)
_new_strategy(self, center, *, bounded=True)
_check_measurements(self, individual)
optimise(self, *args, **kwargs)
_receive_fixed_batch(self, records, verbose, batch_start_time)
int _completed_generations
_generation_feedback(self, position)
_offer_to_grid(self, individual, cell)
bool _requires_proposed_genome
_start_fixed_batch(self, size)
ask_batch(self, size=None)
Issue one manual generation in proposal order.
tell_batch(self, results)
Apply results from the outstanding manual generation.
_check_candidate(self, individual)
_commit_generation(self, evaluated)