19"""Basic operators and tools used to design QD or evolutionary algorithms."""
23from typing
import Sequence, Callable, Tuple
24from itertools
import repeat
30from qdpy
import containers
35def sel_random(collection: Sequence[Any]) -> Sequence[Any]:
36 """Select and return one individual at random among `collection`.
40 :param collection: Sequence[Any]
41 The individuals to select from.
43 return random.choice(collection)
46def non_trivial_sel_random(container: containers.Container) -> Any:
47 """Select and return one individual at random among `container`.
48 Ignore individuals with a trivial fitness (i.e. equal to the minimum fitness value),
49 except if there are only individuals with trivial fitness.
53 :param container: Container
54 The individuals to select from.
56 fst_ind: Any = container[0]
57 min_fitness: Any = copy.deepcopy(fst_ind.fitness)
58 assert container.fitness_domain
is not None and len(min_fitness.values) == len(container.fitness_domain), f
"You must specify `fitness_domain` in Container, and use individuals with fitness values of the same length as `fitness_domain`."
59 min_fitness.values = tuple([x[0]
for x
in container.fitness_domain])
60 candidates: MutableSequence[Any] = [ind
for ind
in container
if ind.fitness.dominates(min_fitness)]
62 return random.choice(candidates)
64 return random.choice(container)
67def sel_roulette(collection: Sequence[Any]) -> Sequence[Any]:
68 """Select a member by its sum of raw objective values.
70 The supplied values should define valid nonnegative roulette
71 probabilities. A total of zero falls back to a uniform choice.
73 assert(len(collection))
74 sum_fit_val = [sum(i.fitness.values)
for i
in collection]
75 sum_all_fit = sum(sum_fit_val)
77 probs = [1. / len(collection)
for _
in sum_fit_val]
79 probs = [f / sum_all_fit
for f
in sum_fit_val]
80 return random.choices(collection, weights=probs)[0]
88def sel_roulette_score(collection, score_name: str =
"curiosity", default_score: float = 0.0):
89 """Select by a finite named score, with support for negative scores.
91 Shift all scores by the same amount when the minimum is negative.
92 If every resulting weight is zero, draw uniformly.
94 if len(collection) == 0:
95 raise ValueError(
"Cannot select from an empty collection.")
96 scores = [float(ind.scores.get(score_name, default_score))
for ind
in collection]
97 if not all(math.isfinite(score)
for score
in scores):
98 raise ValueError(f
"Roulette score {score_name!r} must be finite.")
99 scale = max(map(abs, scores))
101 return random.choice(collection)
102 offset = min(0.0, min(scores) / scale)
103 weights = [score / scale - offset
for score
in scores]
104 return random.choices(collection, weights=weights)[0]
if any(weights)
else random.choice(collection)
107def sel_grid_roulette(collection: Sequence[Any]) -> Sequence[Any]:
108 """Select a grid member and use its cell for roulette selection.
110 The first draw is uniform over stored entries, so cells with more
111 members are visited more often. The second draw applies roulette
112 weights to the chosen cell's population.
114 assert(isinstance(collection, containers.Grid))
115 assert(len(collection))
117 tmp_idx = random.randint(0, len(collection)-1)
118 tmp_ind: IndividualLike = collection[tmp_idx]
119 bin_coord = collection.index_grid(tmp_ind)
120 bin_pop = collection.solutions[bin_coord]
121 return sel_roulette(bin_pop)
127def iso_line_dd(first, second, *, iso_sigma=0.01, line_sigma=0.2, bounds=None, rng=None):
128 """Return an Iso+LineDD offspring as a new NumPy vector.
130 Each coordinate receives independent isotropic noise. One Gaussian draw
131 scales the difference between the parents for the entire offspring.
133 :param first: Base parent vector.
134 :param second: Parent defining the direction from the base.
135 :param iso_sigma: Standard deviation of independent coordinate noise.
136 :param line_sigma: Standard deviation of the shared direction coefficient.
137 :param bounds: Optional lower and upper coordinate bounds for clipping.
138 :param rng: Random generator. By default use NumPy's global random stream.
140 first = np.asarray(first, dtype=float)
141 second = np.asarray(second, dtype=float)
142 if first.ndim != 1
or first.size == 0
or first.shape != second.shape:
143 raise ValueError(
"Iso+LineDD requires two matching nonempty vectors.")
144 if not (0 <= iso_sigma < np.inf
and 0 <= line_sigma < np.inf):
145 raise ValueError(
"Iso+LineDD scales must be finite and nonnegative.")
146 rng = np.random
if rng
is None else rng
147 child = first + iso_sigma * rng.normal(size=first.size) + line_sigma * rng.normal() * (second - first)
148 return np.clip(child, *bounds)
if bounds
is not None else child
152def iso_line_cross(first, second, *, iso_sigma=0.005, line_sigma=0.05, crossover_probability=0.5,
153 crossover_rate=0.1, bounds=None, rng=None):
154 """Return one IsoLineCross offspring without changing its parents.
156 Apply Iso+LineDD in both directions and alternate parental segments at
157 the scaled cumulative exponential breakpoints. Set line_sigma to zero
158 for IsoCross. A zero crossover probability consumes the same random
161 :param first: Base parent vector.
162 :param second: Other parent vector with the same shape.
163 :param iso_sigma: Isotropic noise scale.
164 :param line_sigma: Directional noise scale.
165 :param crossover_probability: Probability of mixing the two varied vectors.
166 :param crossover_rate: Number of sampled breakpoints per gene, in [0, 1].
167 :param bounds: Optional clipping bounds.
168 :param rng: Generator or the default NumPy global stream.
170 if not (0 <= crossover_probability <= 1
and 0 <= crossover_rate <= 1):
171 raise ValueError(
"Crossover probability and rate must be in [0, 1].")
172 rng = np.random
if rng
is None else rng
173 offspring = iso_line_dd(first, second, iso_sigma=iso_sigma, line_sigma=line_sigma, bounds=bounds, rng=rng)
174 size = len(offspring)
175 if size == 1
or crossover_probability == 0
or rng.random() >= crossover_probability:
177 other = iso_line_dd(second, first, iso_sigma=iso_sigma, line_sigma=line_sigma, bounds=bounds, rng=rng)
178 spacing = np.cumsum(rng.exponential(size=max(1, int(crossover_rate * size))))
180 positions = (spacing / spacing[-1] * (size - 1)).astype(np.intp)
if spacing[-1]
else np.full(
181 len(spacing), size - 1, dtype=np.intp)
182 swap = np.searchsorted(positions, np.arange(size), side=
"right") % 2 == 1
183 return np.where(swap, other, offspring)
186def mut_gaussian(individual: MutableSequence[Any], mu: float, sigma: float, mut_pb: float, bounds: Optional[Sequence[float]] =
None) -> MutableSequence[Any]:
187 """Add Gaussian noise to selected coordinates in place.
189 :param individual: Mutable genome to vary.
190 :param mu: Mean of the perturbation.
191 :param sigma: Standard deviation of the perturbation.
192 :param mut_pb: Per-coordinate selection probability.
193 :param bounds: Optional common lower and upper clipping bounds.
194 :returns: The same mutated genome object.
196 for i
in range(len(individual)):
197 if random.random() < mut_pb:
198 individual[i] += random.gauss(mu, sigma)
199 if bounds
is not None and len(bounds) > 1:
200 individual[:] = np.clip(individual[:],bounds[0],bounds[1])
205def mut_polynomial_bounded(individual: MutableSequence[Any], eta: float, low: float, up: float, mut_pb: float,
206 *, rng=
None) -> MutableSequence[Any]:
207 """Apply bounded polynomial mutation to selected coordinates in place.
209 Use a strictly ordered interval and start with a genome inside
210 its bounds. The operator uses Deb's polynomial distribution and
211 clips the mutated coordinates to that interval.
213 :param individual: Mutable genome to vary.
214 :param eta: Distribution index controlling typical change size.
215 :param low: Lower bound shared by the coordinates.
216 :param up: Upper bound shared by the coordinates.
217 :param mut_pb: Per-coordinate selection probability.
218 :param rng: Optional random generator. Defaults to Python's random module.
219 :returns: The same mutated genome object.
221 rng = random
if rng
is None else rng
222 for i
in range(len(individual)):
223 if rng.random() < mut_pb:
225 delta_1 = (x - low) / (up - low)
226 delta_2 = (up - x) / (up - low)
228 mut_pow = 1. / (eta + 1.)
232 val = 2. * rand + (1. - 2. * rand) * xy**(eta + 1.)
233 delta_q = val**mut_pow - 1.
236 val = 2. * (1. - rand) + 2. * (rand - 0.5) * xy**(eta + 1.)
237 delta_q = 1. - val**mut_pow
239 x += delta_q * (up - low)
240 x = min(max(x, low), up)
249def sel_or_init(collection: Sequence[IndividualLike], base_ind: IndividualLike,
250 sel_fn: Callable, sel_pb: float,
251 init_fn: Callable, init_pb: float = 0., return_flag: bool =
True):
252 """Either select an individual from `collection` by using function `sel_pb`,
253 or initialise a new individual by using function `init_pb`.
254 If `collection` is empty, it will always initialise a new individual, not perform selection.
258 :param collection: Sequence[IndividualLike]
259 The individuals to select from.
260 :param base_ind: IndividualLike
261 The base individual to initialise.
262 :param sel_fn: Callable
263 The selection function.
265 The probability of performing selection.
266 :param init_fn: Callable
267 The initialisation function.
268 :param init_pb: float
269 The probability of performing initialisation.
270 :param return_flag: bool
271 If set to True, the function will return a Tuple[IndividualLike, bool] with a first item corresponding
272 to the selected or initialised individual, and the second item a flag set to True if the first item
273 was selected, and set to False if it was initialised.
274 If set to False, the function will return the selected or initialised IndividualLike.
277 return (res, f)
if return_flag
else res
278 if len(collection) == 0:
279 return ret(init_fn(base_ind),
False)
280 if type(sel_pb)
is type(init_pb)
is float
and sel_pb == init_pb == 0.5:
282 selected = np.random.random_sample() < 0.5
284 selected = np.random.choice(range(2), p=[sel_pb, init_pb]) == 0
286 return ret(sel_fn(collection),
True)
287 return ret(init_fn(base_ind),
False)
290def mut_or_cx(individuals: Union[IndividualLike, Sequence[IndividualLike]],
291 mut_fn: Callable, cx_fn: Callable) -> Sequence[IndividualLike]:
292 """Either perform a mutation (using function `mut_fn`) or a crossover (using function `cx_fn`)
293 depending on the nature and length of `individuals`.
294 If `individuals` is an IndividualLike or a Sequence of one IndividualLike, a mutation will be performed.
295 If `individuals` is a Sequence of two IndividualLike, a crossover will be performed.
299 :param individuals: Union[IndividualLike, Sequence[IndividualLike]]
300 The individual(s) to mutate or crossover.
301 :param mut_fn: Callable
302 The mutation function.
303 :param cx_fn: Callable
304 The crossover function.
308 The resulting individual(s).
310 if isinstance(individuals, IndividualLike):
311 return [mut_fn(individuals)]
312 elif isinstance(individuals, Sequence)
and len(individuals) == 1:
313 return [mut_fn(individuals[0])]
314 elif isinstance(individuals, Sequence)
and len(individuals) > 1:
315 return cx_fn(individuals)
317 raise ValueError(f
'`individuals` can be an Individual or a Sequence.')
321 """Resolve historical phenotype globals independently of import order."""
323 def find_class(self, module, name):
324 if module ==
"qdpy.base" and name
in {
"Individual",
"Fitness",
"Features",
"Score",
"ScoresDict"}:
325 module =
"qdpy.phenotype"
326 return super().find_class(module, name)
329def open_pickle_file(filename):
330 """Deserialize a trusted result file.
332 Standard native result dictionaries include the container and may
333 include evaluation and iteration tables. Recreate older runs with
334 the current version when their fitness snapshot format is unsupported.
336 with open(filename,
"rb")
as file: