47 """Maintain a preference-ordered depth in every occupied descriptor cell.
49 Refresh every incumbent once per generation before selecting new parents.
50 An offspring requires a complete initial repeat group. Failed refreshes
51 retain the last estimate and every attempted rollout counts. Rebuild the
52 rankings from refreshed measurements, including changes of niche. A
53 final generation needs room for all refreshes and one offspring group.
55 :param container: Empty standalone Grid or CVTGrid with one objective.
56 Its max_items_per_bin sets the depth. Leave it under the search's control.
57 :param budget: Total raw rollout attempts, including incumbent refreshes.
58 :param dimension: Number of bounded real decision variables.
59 :param delta_f: Fitness tolerance in raw fitness units.
60 :param delta_r: Reproducibility improvement required to accept a performance loss.
61 :param sampling_size: Maximum raw rollout attempts per generation. It must
62 allow a full archive refresh and at least one new candidate.
63 :param initial_samples: Number of repeated measurements for new candidates.
64 :param estimator: "mean" or "median" for both measurements, or a pair
65 selecting the fitness and descriptor estimators independently.
66 :param reproducibility: Optional callable taking the matrix of raw descriptors
67 and returning a finite scalar to maximize. Defaults to negative mean
68 population standard deviation across the descriptor coordinates.
69 :param ind_domain: Shared decision bounds.
70 :param iso_sigma: Independent Iso+LineDD noise scale.
71 :param line_sigma: Directional Iso+LineDD noise scale.
72 :param seed: Seed for variation and the independent rollout stream.
75 def __init__(self, container, budget, dimension, *, delta_f, delta_r,
76 sampling_size=128, initial_samples=2, estimator="median", reproducibility=None,
77 ind_domain=(0., 1.), iso_sigma=.01, line_sigma=.2, seed=0):
78 if (type(container)
not in (Grid, CVTGrid)
or len(container)
or container.parents
79 or len(container.fitness_domain) != 1
or not len(container.features_domain)
80 or container.fitness_score_names
or container.features_score_names):
81 raise ValueError(
"Use an empty standalone scalar Grid or CVTGrid with direct measurements.")
82 weights = container.fitness_weights
83 if weights
is not None and (len(weights) != 1
or not isfinite(weights[0])
or weights[0] == 0):
84 raise ValueError(
"Use one finite nonzero fitness weight.")
85 if not all(0 <= value < np.inf
for value
in (delta_f, delta_r)):
86 raise ValueError(
"Both delta tolerances must be finite and nonnegative.")
87 reducers = {
"mean": np.mean,
"median": np.median}
88 estimators = (estimator, estimator)
if isinstance(estimator, str)
else tuple(estimator)
89 if len(estimators) != 2
or any(name
not in reducers
for name
in estimators):
90 raise ValueError(
"Choose 'mean' or 'median' for each estimator.")
91 if reproducibility
is not None and not callable(reproducibility):
92 raise TypeError(
"reproducibility must be callable.")
94 self.
budget = _positive_int(budget,
"budget")
95 self.
dimension = _positive_int(dimension,
"dimension")
96 self.
sampling_size = _positive_int(sampling_size,
"sampling_size")
97 self.
initial_samples = _positive_int(initial_samples,
"initial_samples")
100 raise ValueError(
"Fit all refreshes and a new group of at least two rollouts within the limits.")
101 self.
ind_domain = _variation_settings(ind_domain, iso_sigma, line_sigma)
103 raise ValueError(
"Use finite decision spans.")
106 self.
_direction = -1.
if weights
is None else float(np.sign(weights[0]))
108 self.
_reproducibility = _negative_mean_std
if reproducibility
is None else reproducibility
109 self.
seed = int(np.random.SeedSequence(seed).generate_state(1, dtype=np.uint64)[0])
110 self.
_rng = np.random.default_rng(self.
seed)
117 """Return the most-to-least preferred members of one descriptor cell."""
118 return tuple(self.
_fronts.get(cell, ()))
120 def _measurement(self, candidate, observations):
121 rows = np.asarray([(*obs.fitness, *obs.features)
for obs
in observations], dtype=float)
122 scale = np.max(np.abs(rows), axis=0)
123 normalized = rows / np.where(scale == 0., 1., scale)
127 if not isfinite(score):
128 raise ValueError(
"The reproducibility estimator must return a finite scalar.")
129 measured =
Individual(candidate, name=candidate.name,
132 measured.elapsed = sum(row.elapsed
for row
in observations)
133 measured._observations = observations
134 measured.scores.update(reproducibility=score, rollout_count=len(rows))
137 def _scores(self, item):
138 return self.
_direction * item.fitness.values[0], item.scores[
"reproducibility"]
140 def _cascade(self, fronts, seen, candidate):
142 genome = tuple(candidate)
143 if (genome
in seen
or cell
is None
144 or not self.
container.in_bounds(candidate.fitness.values, self.
container.fitness_domain)):
147 front = fronts.setdefault(cell, [])
148 for i, incumbent
in enumerate(front):
150 front[i], candidate = candidate, incumbent
151 if len(front) < self.
container.max_items_per_bin:
152 front.append(candidate)
154 def _propose(self, count, fronts):
155 occupied = tuple(fronts.values())
160 return occupied[self.
_rng.integers(len(occupied))][0]
164 for _
in range(count)]
166 def _publish(self, fronts):
168 retained = {id(item)
for front
in fronts.values()
for item
in front}
170 if id(item)
not in retained:
172 previous = {id(item)
for item
in staged}
173 for cell, front
in fronts.items():
175 if id(item)
not in previous:
176 staged._add_to_grid(item, cell,
False)
177 self.
container.__dict__.update(staged.__dict__)
181 def optimise(self, evaluate, *, executor=None, seeded=False):
182 """Supply evaluate(candidate) or evaluate(candidate, seed) with seeded=True."""
184 raise RuntimeError(
"Construct a fresh ASDelta search and archive for each run.")
185 if not callable(evaluate):
186 raise TypeError(
"evaluate must be callable.")
190 incumbents = [entry
for front
in self.
_fronts.values()
for entry
in front]
195 fronts, seen = {}, set()
197 refreshed = rollouts.evaluate_groups([(item, 1)
for item
in incumbents])
198 for item, observations
in zip(incumbents, refreshed, strict=
True):
199 revised = self.
_measurement(_fresh(item), item._observations + observations)
if observations
else item
200 self.
_cascade(fronts, seen, revised)
202 offspring = self.
_propose(count, fronts)
204 measured = rollouts.evaluate_groups([(item, self.
initial_samples)
for item
in offspring])
205 for item, observations
in zip(offspring, measured, strict=
True):
207 self.completed_candidates += 1