QDpy
Loading...
Searching...
No Matches
differential.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Differential MAP-Elites with ordered native evaluation feedback."""
7
8from math import isfinite
9from operator import index
10
11import numpy as np
12
13from qdpy.base import registry
14from qdpy.containers import CVTGrid, Grid
15from .constrained import _check_measurements
16from .modern import _FixedGeneration, _bounds, _positive_int
17
18__all__ = ["DifferentialMAPElites"]
19
20
21def _differential_trial(parents, scale, rate, bounds, rng):
22 target, base, first, second = np.asarray(parents, dtype=float)
23 mask = rng.random(len(target)) < rate
24 mask[rng.integers(len(target))] = True
25 # Limit overflow to donor coordinates, which saturate at the bounds.
26 with np.errstate(over="ignore"):
27 donor = np.clip(base + scale * (first - second), *bounds)
28 return np.where(mask, donor, target)
29
30
31
32@registry.register
34 """Run Differential MAP-Elites on a best-only Grid or CVTGrid.
35
36 Sample random candidates until the configured initial design has
37 been evaluated and at least four different cells are occupied.
38 Select one target and three distinct donors uniformly by cell.
39 Carry at least one donor coordinate into every offspring. Admission
40 competes in the measured cell, including when it differs from the
41 source target's cell.
42
43 :param container: Parentless best-only Grid or CVTGrid with at least four cells.
44 :param budget: Number of candidate evaluation attempts per managed run.
45 :param dimension: Number of real coordinates in a candidate.
46 :param ind_domain: Finite shared bounds for the real coordinates.
47 :param scaling_factor: Weight of the difference between two donors.
48 :param crossover_rate: Probability that a coordinate takes the donor value.
49 :param initial_samples: Number of uniform proposals before breeding.
50 :param batch_size: Proposals generated from the same archive snapshot.
51 :param seed: Private proposal RNG seed.
52 :param kwargs: Native QDAlgorithm options, including objective direction.
53 """
54
55 _requires_proposed_genome = True
56
57 def __init__(self, container, budget, dimension, ind_domain=(0., 1.), *, scaling_factor=.5,
58 crossover_rate=.9, initial_samples=16, batch_size=1, seed=0, **kwargs):
59 if type(container) not in (Grid, CVTGrid):
60 raise TypeError("Use a QDpy Grid or CVTGrid.")
61 if (container.max_items_per_bin != 1 or container.parents or len(container.solutions) < 4
62 or container.capacity < 4 or container.discard_random_on_bin_overload):
63 raise ValueError("Use a parentless best-only grid with room for at least four distinct elites.")
64 self.ind_domain = _bounds(ind_domain)
65 if not (isfinite(self.ind_domain[1] - self.ind_domain[0]) and 0 < scaling_factor < np.inf
66 and 0 <= crossover_rate <= 1):
67 raise ValueError("Use a finite-width interval, positive scaling_factor, and crossover_rate in [0, 1].")
68 self.scaling_factor, self.crossover_rate, self.seed = scaling_factor, crossover_rate, seed
69 self.initial_samples = index(initial_samples)
70 if self.initial_samples < 0:
71 raise ValueError("initial_samples must be nonnegative.")
72 if container.fitness_weights is not None:
73 kwargs.setdefault("optimisation_task", tuple(container.fitness_weights))
74 super().__init__(container, _positive_int(budget, "budget"),
75 dimension=_positive_int(dimension, "dimension"),
76 batch_size=_positive_int(batch_size, "batch_size"), **kwargs)
77 for elite in container:
78 self._check_vector(elite)
79
80 def reinit(self):
81 """Reset generations and the private proposal stream."""
82 super().reinit()
83 self._rng = np.random.default_rng(self.seed)
85
86 @property
88 """Return the number of proposals produced from four distinct elites."""
89 return self._differential_proposals
90
91 def _check_vector(self, vector):
92 coords = np.asarray(vector, dtype=float)
93 if (coords.shape != (self.dimension,) or not np.isfinite(coords).all()
94 or np.any(coords < self.ind_domain[0]) or np.any(coords > self.ind_domain[1])):
95 raise ValueError("The genome must contain finite coordinates within ind_domain.")
96
97 def _check_candidate(self, individual):
98 self._check_vector(individual)
99 _check_measurements(self.container, individual)
100
101 def _internal_ask(self, base_ind):
102 archive = self.container
103 if len(archive) < 4 or self.nb_suggestions < self.initial_samples:
104 child = self._rng.uniform(*self.ind_domain, size=self.dimension)
105 else:
106 parents = [archive[i] for i in self._rng.choice(len(archive), 4, replace=False)]
107 child = _differential_trial(parents, self.scaling_factor, self.crossover_rate, self.ind_domain, self._rng)
109 base_ind[:] = child.tolist()
110 return base_ind
Sample four distinct elites, recombine them, and perform local competition.