56 def __init__(self, search, evaluate, budget):
58 self.evaluate = evaluate
60 self.rng = np.random.default_rng(search.seed)
61 self.calls = [0, 0, 0]
68 return self.budget - sum(self.calls)
70 def _measure(self, vector, phase):
71 if not self.remaining:
72 raise _BudgetExhausted
73 vector = np.clip(vector, 0., 1.)
74 self.calls[phase] += 1
75 raw = float(self.evaluate(self.search._decode(vector)))
77 raise ValueError(
"HillVallEA needs a finite scalar fitness.")
78 point = _Point(vector, self.search._direction * raw)
79 if self.best
is None or point.quality > self.best.quality:
83 def _same_basin(self, first, second, probes):
84 if np.array_equal(first.vector, second.vector):
86 floor = min(first.quality, second.quality)
87 for fraction
in np.arange(1, probes + 1) / (probes + 1):
88 check = (1. - fraction) * first.vector + fraction * second.vector
89 if self._measure(check, 1).quality < floor:
93 def _cluster(self, points):
94 groups, labels = [], []
95 vectors = np.asarray([point.vector
for point
in points])
96 edge_scale = len(points) ** (-1. / self.search.dimension)
97 for i, point
in enumerate(points):
98 distances = np.linalg.norm(vectors[:i] - point.vector, axis=1)
100 for neighbor
in np.argsort(distances, kind=
"stable")[:self.search.neighbors]:
101 label = labels[neighbor]
105 probes = min(self.search.max_probes, 1 + int(distances[neighbor] / edge_scale))
106 if self._same_basin(point, points[neighbor], probes):
111 groups[label].append(point)
115 def _local_search(self, group, limit, population):
118 vectors = np.asarray([point.vector
for point
in group])
119 center = vectors.mean(axis=0)
120 spread = np.sqrt(np.mean((vectors - center)**2))
121 sigma = float(np.clip(spread, .035, .25))
122 strategy = _cma_strategy(center, sigma, population, int(self.rng.integers(1, 2**32)), (0., 1.))
124 while limit
and not strategy.stop():
125 points = [self._measure(vector, 2)
for vector
in strategy.ask(number=min(population, limit))]
126 candidate = max(points, key=
lambda point: point.quality)
127 if candidate.quality > best.quality:
129 if len(points) == population:
130 strategy.tell([point.vector
for point
in points], [-point.quality
for point
in points])
134 def _retain(self, candidate):
135 quality = max([candidate.quality, *(point.quality
for point
in self.elites)])
136 tolerance = self.search.fitness_tolerance
137 if candidate.quality < quality - tolerance:
139 contenders = [point
for point
in self.elites
if point.quality >= quality - tolerance]
140 for j, point
in enumerate(contenders):
141 if self._same_basin(candidate, point, self.search.max_probes):
142 if candidate.quality > point.quality:
143 contenders[j] = candidate
144 self.elites = contenders
146 self.elites = [*contenders, candidate]
151 samples, population = search.initial_samples, search.local_population
152 while self.remaining:
154 points = self.elites + [self._measure(self.rng.random(search.dimension), 0)
155 for _
in range(min(samples, self.remaining))]
156 points.sort(key=
lambda point: -point.quality)
157 selected = max(1, int(search.selection_fraction * len(points)))
158 groups = self._cluster(points[:selected])
159 pending = [group
for group
in groups
if group[0]
not in self.elites]
161 for i, group
in enumerate(pending):
164 count = len(pending) - i
165 reserve = search.max_probes * (len(self.elites) + count - 1)
166 available = max(0, (self.remaining - reserve) // count)
167 candidate = self._local_search(group, min(available, population * search.local_generations), population)
168 discovered = self._retain(candidate)
or discovered
170 samples = min(2 * samples, self.budget)
171 population = max(population + 1, int(1.2 * population))
176 """Cluster nearest-better candidates using line tests, then refine each basin.
178 This bounded variant uses CMA-ES for local search. Restart populations
179 include the retained near-optima and grow when a restart finds no new
180 basin. Every evaluation, including intermediate tests for clustering
181 and duplicate-peak checks, reduces the same hard budget. Requires the
182 optional cma extra at run time.
184 :param bounds: Finite increasing (lower, upper) pairs per decision coordinate.
185 :param maximise: Maximize fitness if true, otherwise minimize it.
186 :param initial_samples: Number of random candidates at the first restart (default 16 per dimension).
187 :param selection_fraction: Fraction of sampled and retained points to cluster.
188 :param neighbors: Number of earlier nearest points to consider during clustering.
189 :param max_probes: Maximum interpolation points per line test.
190 :param local_population: Starting population size for each local CMA-ES.
191 :param local_generations: Maximum number of CMA-ES generations per cluster.
192 :param fitness_tolerance: Retain niche representatives within this fitness gap of the best retained peak.
193 :param seed: Private seed.
196 def __init__(self, bounds, *, maximise=True, initial_samples=None, selection_fraction=.5, neighbors=None,
197 max_probes=5, local_population=6, local_generations=12, fitness_tolerance=1e-3, seed=0):
198 limits = np.array(bounds, dtype=float, copy=
True)
199 if limits.ndim != 2
or limits.shape[1] != 2
or not len(limits)
or not np.isfinite(limits).all():
200 raise ValueError(
"Provide finite lower and upper decision bounds.")
202 with np.errstate(over=
"ignore"):
204 if (
not np.isfinite(self.
_span).all()
or np.any(self.
_span <= 0.)
205 or not 0. < selection_fraction <= 1.
or not 0. <= fitness_tolerance < np.inf):
206 raise ValueError(
"Use positive finite decision spans, a selection fraction in (0, 1], and a finite tolerance.")
210 _positive_int(initial_samples,
"initial_samples"))
212 self.
neighbors = self.
dimension + 1
if neighbors
is None else _positive_int(neighbors,
"neighbors")
213 self.
max_probes = _positive_int(max_probes,
"max_probes")
216 raise ValueError(
"local_population must be at least two.")
220 def _decode(self, point):
224 def run(self, evaluate, budget):
225 """Measure finite scalar fitness on raw decision vectors.
227 If the final budget interrupts a comparison, retain completed
228 niche updates. The result also exposes the best measured point,
229 even if its basin could not be checked before the budget stopped.
231 budget = _positive_int(budget,
"budget")
232 if not callable(evaluate):
233 raise TypeError(
"evaluate must be callable.")
236 except ImportError
as error:
237 raise ImportError(
"HillVallEA requires qdpy[cma].")
from error
241 except _BudgetExhausted:
247 peaks = tuple(record(point)
for point
in sorted(run.elites, key=
lambda point: -point.quality))