41 """Use the NS–NSLC objectives described by Pugh, Soros, and Stanley.
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.
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.
63 _requires_proposed_genome =
True
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.")
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.")
76 self.
k = _positive_int(k,
"k")
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)
84 raise ValueError(
"A nonzero scalar fitness weight is required.")
87 """Reset the two reference histories and the proposal stream."""
89 self.
_rng = np.random.default_rng(self.
seed)
96 """Return the sizes of the exploration and reporting memories, in order."""
104 parent = tuple(ranked[min(self.
_rng.integers(len(ranked), size=2))])
108 genome = np.asarray(self.
mutate(parent, self.
_rng), dtype=float)
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.")
115 def _exploration(self, individual):
118 def _check_candidate(self, individual):
119 super()._check_candidate(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)
125 raise ValueError(
"Descriptor widths must remain fixed in both views.")
128 def _neighbors(self, points, reference, view):
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))
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]
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)
149 def _update_memory(self, points, offspring, view):
151 for candidate
in offspring:
152 memory.setdefault(tuple(candidate), candidate)
154 entries = tuple(memory.values())
155 novelty, _ = self.
_neighbors(entries, {tuple(item): item
for item
in points}, view)
158 memory.update((tuple(entries[i]), entries[i])
for i
in sorted(selected))
162 parents = tuple(archive)
163 pool = {tuple(parent): parent
for parent
in parents}
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
171 points = tuple(pool.values())
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}
179 if id(item)
not in keep:
180 archive.discard(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):