58 """Combine task fitness and within-bin behavioral diversity.
60 Every evaluated offspring competes in each bin using its original
61 vector of task scores. Survival uses NSGA-II front ranks and
62 crowding for the aggregate task score and mean behavioral distance.
63 Parent sampling is uniform over occupied bins and then their members.
65 :param task_count: Number of task scores returned per evaluation.
66 :param sample: Callable (rng) returning an initial genome iterable.
67 :param mutate: Callable (genome, rng) returning an offspring genome.
68 Treat genome elements as immutable.
69 :param bin_capacity: Maximum number of survivors in each task subset.
70 :param batch_size: New candidate evaluations before the next competition.
71 :param max_bins: Cap on automatically generated subsets, defaulting
72 to max(64, 2 * task_count). Large families retain all singletons,
73 the full task, and a seeded selection of other subsets.
74 :param subsets: Optional explicit collection of task index subsets.
75 Include the full task subset. This overrides automatic bin selection.
76 :param aggregate: "mean" or "product" for fitness within each subset.
77 :param seed: Seed for selection, variation, and evaluator seeds.
80 def __init__(self, task_count, *, sample, mutate, bin_capacity=8, batch_size=16,
81 max_bins=None, subsets=None, aggregate="mean", seed=0):
82 self.
task_count = _positive_int(task_count,
"task_count")
83 self.
_capacity = _positive_int(bin_capacity,
"bin_capacity")
84 self.
_batch_size = _positive_int(batch_size,
"batch_size")
85 if not callable(sample)
or not callable(mutate):
86 raise TypeError(
"sample and mutate must be callable.")
87 if aggregate
not in (
"mean",
"product"):
88 raise ValueError(
"Choose 'mean' or 'product' task-score aggregation.")
92 np.random.default_rng, np.random.SeedSequence(seed).spawn(4))
95 cap = max(64, 2 * self.
task_count)
if max_bins
is None else _positive_int(max_bins,
"max_bins")
96 subsets = _choose_subsets(self.
task_count, cap, geometry)
98 subsets = tuple(tuple(sorted(index(task)
for task
in subset))
for subset
in subsets)
99 if (self.
_full not in subsets
or len(set(subsets)) != len(subsets)
100 or any(
not subset
or len(set(subset)) != len(subset)
101 or subset[0] < 0
or subset[-1] >= self.
task_count for subset
in subsets)):
102 raise ValueError(
"Use distinct nonempty task subsets in range, including the full subset.")
103 self.
_bins = dict.fromkeys(subsets, ())
110 """Return a read-only live view of each subset and its survivors."""
111 return MappingProxyType(self.
_bins)
116 """Return the best measured candidate in the full subset, or None."""
117 return max(self.
_bins[self.
_full], key=
lambda row: self.
_fitness(np.asarray(row.task_scores)), default=
None)
121 """Return cumulative attempts, failures, and generations."""
124 def _fitness(self, scores):
126 return scores.mean(axis=-1)
128 with np.errstate(divide=
"ignore"):
129 return np.log(scores).sum(axis=-1)
131 def _measure(self, evaluate, genome):
133 result = evaluate(genome, int(self.
_evaluation.integers(2**32)))
137 scores, descriptor = (np.asarray(row, dtype=float)
for row
in result)
138 if scores.shape != (self.
task_count,)
or not np.all((scores >= 0.) & (scores <= 1.)):
139 raise ValueError(
"Return one normalized task score in [0, 1] per task.")
140 if descriptor.ndim != 1
or not len(descriptor)
or not np.isfinite(descriptor).all():
141 raise ValueError(
"Return a nonempty finite behavioral descriptor.")
145 raise ValueError(
"Descriptor dimensions must remain fixed throughout the search.")
146 return CMOEARecord(genome, tuple(scores), tuple(descriptor))
148 def _survive(self, candidates, subset):
151 scores = np.asarray([row.task_scores
for row
in candidates])[:, subset]
157 quality = np.exp(quality - best)
if np.isfinite(best)
else np.zeros_like(quality)
158 descriptors = np.asarray([row.descriptor
for row
in candidates])
159 descriptors /= np.abs(descriptors).max()
or 1.
160 diversity = cdist(descriptors, descriptors).sum(axis=1) / (len(candidates) - 1)
161 utilities = _pareto_utilities(quality, diversity)
162 survivors = np.argsort(-utilities, kind=
"stable")[:self.
_capacity]
163 return tuple(candidates[int(slot)]
for slot
in survivors)
169 def run(self, evaluate, budget):
170 """Use all requested attempts, including a shorter final generation."""
171 budget = index(budget)
173 raise ValueError(
"budget must be nonnegative.")
175 parents = [members
for members
in self.
_bins.values()
if members]
177 for _
in range(min(budget - start, self.
_batch_size)):
179 source = parents[int(self.
_selection.integers(len(parents)))]
180 parent = source[int(self.
_selection.integers(len(source)))]
184 record = self.
_measure(evaluate, genome)
185 if record
is not None:
186 measured.append(record)
188 children = tuple(measured)
189 for subset, members
in self.
_bins.items():
190 self.
_bins[subset] = self.
_survive(members + children, subset)