QDpy
Loading...
Searching...
No Matches
multi_descriptor_nslc.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Breed one population using two novelty views and local fitness competition."""
7
8from math import isfinite
9
10import numpy as np
11from scipy.spatial.distance import cdist
12
13from qdpy.base import registry
14from qdpy.containers import Container
15from qdpy.containers.pareto import _crowding_distance
16from .modern import _FixedGeneration, _bounds, _positive_int
17
18__all__ = ["MultiDescriptorNSLC"]
19
20
21def _pareto_survivors(scores, capacity, rng):
22 """Order the required survivor fronts by rank and crowding."""
23 first, second = scores[:, None], scores[None, :]
24 dominates = np.all(first >= second, axis=2) & np.any(first > second, axis=2)
25 remaining = np.sum(dominates, axis=0)
26 ordered = []
27 while len(ordered) < capacity:
28 front = np.flatnonzero(remaining == 0)
29 points, inverse = np.unique(scores[front], axis=0, return_inverse=True)
30 spread = _crowding_distance(points)[inverse.reshape(-1)]
31 order = np.lexsort((rng.random(len(front)), -spread))
32 ordered.extend(front[order][:capacity - len(ordered)])
33 remaining -= np.sum(dominates[front], axis=0)
34 remaining[front] = -1
35 return ordered
36
37
38
39@registry.register
41 """Use the NS–NSLC objectives described by Pugh, Soros, and Stanley.
42
43 The evaluator returns (fitness, reporting_descriptors, scores). A
44 named score holds the independent exploration descriptor vector.
45 The reporting view defines the neighbors for local competition.
46 Each novelty view keeps a separate bounded memory. The objective
47 direction for local competition is the raw scalar fitness direction.
48
49 :param budget: Candidate evaluation attempts.
50 :param dimension: Number of real-valued genes.
51 :param population_size: Maximum size of the current breeding population.
52 :param batch_size: Number of offspring before committing feedback.
53 :param exploration_score_name: Score containing the exploration descriptor.
54 :param reference_capacity: Maximum entries in each novelty memory.
55 :param k: Number of nearest neighbors for novelty and local competition.
56 :param ind_domain: Shared bounds on genome coordinates.
57 :param sigma: Standard deviation of default bounded Gaussian variation.
58 :param mutate: Optional callback taking (parent_genome, rng).
59 :param seed: Private proposal and tie-breaking seed.
60 :param kwargs: Native settings including optimization direction.
61 """
62
63 _requires_proposed_genome = True
64
65 def __init__(self, budget, dimension, population_size, batch_size=1, *, exploration_score_name="exploration",
66 reference_capacity=128, k=15, ind_domain=(0., 1.), sigma=.1, mutate=None, seed=0, **kwargs):
67 if not isinstance(exploration_score_name, str) or not exploration_score_name:
68 raise ValueError("Supply a nonempty exploration descriptor score name.")
69 self.ind_domain = _bounds(ind_domain)
70 if not isfinite(self.ind_domain[1] - self.ind_domain[0]) or not 0. <= sigma < np.inf:
71 raise ValueError("Use finite decision spans and finite nonnegative sigma.")
72 if mutate is not None and not callable(mutate):
73 raise TypeError("mutate must be callable.")
74 self.exploration_score_name = exploration_score_name
75 self.reference_capacity = _positive_int(reference_capacity, "reference_capacity")
76 self.k = _positive_int(k, "k")
77 self.sigma, self.mutate, self.seed = sigma, mutate, seed
78 archive = Container(capacity=_positive_int(population_size, "population_size"),
79 fitness_domain=((-np.inf, np.inf),))
80 super().__init__(archive, _positive_int(budget, "budget"), nb_objectives=1,
81 batch_size=_positive_int(batch_size, "batch_size"),
82 dimension=_positive_int(dimension, "dimension"), **kwargs)
83 if not self._fitness_weights[0]:
84 raise ValueError("A nonzero scalar fitness weight is required.")
85
86 def reinit(self):
87 """Reset the two reference histories and the proposal stream."""
88 super().reinit()
89 self._rng = np.random.default_rng(self.seed)
90 self._widths = None
91 self._memories = ({}, {})
92 self._ranked = ()
93
94 @property
95 def reference_sizes(self):
96 """Return the sizes of the exploration and reporting memories, in order."""
97 return tuple(map(len, self._memories))
98
99 def _internal_ask(self, base_ind):
100 if not self.container:
101 base_ind[:] = self._rng.uniform(*self.ind_domain, size=self.dimension)
102 return base_ind
103 ranked = self._ranked or tuple(self.container)
104 parent = tuple(ranked[min(self._rng.integers(len(ranked), size=2))])
105 if self.mutate is None:
106 genome = np.clip(np.asarray(parent) + self._rng.normal(0., self.sigma, self.dimension), *self.ind_domain)
107 else:
108 genome = np.asarray(self.mutate(parent, self._rng), dtype=float)
109 lower, upper = self.ind_domain
110 if genome.shape != (self.dimension,) or not np.all((genome >= lower) & (genome <= upper)):
111 raise ValueError("Mutation must return a bounded real genome of the configured length.")
112 base_ind[:] = genome
113 return base_ind
114
115 def _exploration(self, individual):
116 return np.asarray(individual.scores[self.exploration_score_name], dtype=float)
117
118 def _check_candidate(self, individual):
119 super()._check_candidate(individual)
120 vector = self._exploration(individual)
121 if vector.ndim != 1 or not vector.size or not np.isfinite(vector).all():
122 raise ValueError("Provide a nonempty finite vector for the exploration descriptor.")
123 widths = vector.size, len(individual.features)
124 if self._widths is not None and self._widths != widths:
125 raise ValueError("Descriptor widths must remain fixed in both views.")
126 self._widths = widths
127
128 def _neighbors(self, points, reference, view):
129 # The prefix is the query population itself. Ignore its diagonal,
130 # and keep only one entry per genome in the reference.
131 entries = {tuple(item): item for item in points}
132 for key, item in reference.items():
133 entries.setdefault(key, item)
134 entries = tuple(entries.values())
135 data = np.asarray([self._exploration(item) if view == 0 else tuple(item.features) for item in entries])
136 scale = np.max(np.abs(data))
137 if scale > 1e140:
138 data = data / scale
139 distances = cdist(data[:len(points)], data)
140 np.fill_diagonal(distances, np.inf)
141 count = min(self.k, len(entries) - 1)
142 indices = np.argsort(distances, axis=1, kind="stable")[:, :count]
143 if not count:
144 return np.zeros(len(points)), np.zeros(len(points))
145 novelty = np.take_along_axis(distances, indices, axis=1).mean(axis=1)
146 quality = np.sign(self._fitness_weights[0]) * np.asarray([item.fitness.values[0] for item in entries])
147 return novelty, (quality[:len(points), None] > quality[indices]).mean(axis=1)
148
149 def _update_memory(self, points, offspring, view):
150 memory = self._memories[view]
151 for candidate in offspring:
152 memory.setdefault(tuple(candidate), candidate)
153 if len(memory) > self.reference_capacity:
154 entries = tuple(memory.values())
155 novelty, _ = self._neighbors(entries, {tuple(item): item for item in points}, view)
156 selected = np.argsort(-novelty, kind="stable")[:self.reference_capacity]
157 memory.clear()
158 memory.update((tuple(entries[i]), entries[i]) for i in sorted(selected))
159
160 def _commit_generation(self, evaluated):
161 archive = self.container
162 parents = tuple(archive)
163 pool = {tuple(parent): parent for parent in parents}
164 offspring = {}
165 for slot, individual in enumerate(evaluated):
166 if individual is not None and tuple(individual) not in pool:
167 pool[tuple(individual)] = individual
168 offspring[id(individual)] = slot
169 if not pool:
170 return set()
171 points = tuple(pool.values())
172 first, _ = self._neighbors(points, self._memories[0], 0)
173 second, competition = self._neighbors(points, self._memories[1], 1)
174 scores = np.column_stack((first, second, competition))
175 order = _pareto_survivors(scores, min(len(points), archive.capacity), self._rng)
176 self._ranked = tuple(points[i] for i in order)
177 keep = {id(item) for item in self._ranked}
178 for item in parents:
179 if id(item) not in keep:
180 archive.discard(item)
181 admitted = set()
182 for item in self._ranked:
183 key = id(item)
184 if key in offspring:
185 archive.add(item)
186 admitted.add(offspring[key])
187 children = tuple(item for item in points if id(item) in offspring)
188 for view in range(2):
189 self._update_memory(points, children, view)
190 return admitted
Preserve two kinds of novelty and compete locally in the reporting view.