QDpy
Loading...
Searching...
No Matches
hill_valley.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Spend fitness calls on global sampling, line probes, and local CMA-ES."""
7
8from dataclasses import dataclass
9from math import isfinite
10
11import numpy as np
12
13from .modern import _cma_strategy, _positive_int
14
15__all__ = ["HillVallEA", "HillValleyPeak", "HillValleyResult"]
16
17
18
19@dataclass(frozen=True)
21 """Store a decision vector and its raw scalar fitness."""
22
23 genome: tuple[float, ...]
24 fitness: float
25
26
27
28@dataclass(frozen=True)
30 """Keep the evaluated best point and the near-optimal niche representatives."""
31
32 peaks: tuple[HillValleyPeak, ...]
33 best: HillValleyPeak
34 samples: int
35 probes: int
36 local_evaluations: int
37 restarts: int
38
39 @property
40 def evaluations(self):
41 """Return the total number of objective calls."""
42 return self.samples + self.probes + self.local_evaluations
43
44
45@dataclass(frozen=True, eq=False)
46class _Point:
47 vector: np.ndarray
48 quality: float
49
50
51class _BudgetExhausted(Exception):
52 """Stop before the next callback would exceed the evaluation budget."""
53
54
55class _HillValleyRun:
56 def __init__(self, search, evaluate, budget):
57 self.search = search
58 self.evaluate = evaluate
59 self.budget = budget
60 self.rng = np.random.default_rng(search.seed)
61 self.calls = [0, 0, 0]
62 self.elites = []
63 self.best = None
64 self.restarts = 0
65
66 @property
67 def remaining(self):
68 return self.budget - sum(self.calls)
69
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)))
76 if not isfinite(raw):
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:
80 self.best = point
81 return point
82
83 def _same_basin(self, first, second, probes):
84 if np.array_equal(first.vector, second.vector):
85 return True
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:
90 return False
91 return True
92
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)
99 tested = set()
100 for neighbor in np.argsort(distances, kind="stable")[:self.search.neighbors]:
101 label = labels[neighbor]
102 if label in tested:
103 continue
104 tested.add(label)
105 probes = min(self.search.max_probes, 1 + int(distances[neighbor] / edge_scale))
106 if self._same_basin(point, points[neighbor], probes):
107 break
108 else:
109 label = len(groups)
110 groups.append([])
111 groups[label].append(point)
112 labels.append(label)
113 return groups
114
115 def _local_search(self, group, limit, population):
116 if not limit:
117 return group[0]
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.))
123 best = group[0]
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:
128 best = candidate
129 if len(points) == population:
130 strategy.tell([point.vector for point in points], [-point.quality for point in points])
131 limit -= len(points)
132 return best
133
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:
138 return False
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
145 return False
146 self.elites = [*contenders, candidate]
147 return True
148
149 def optimise(self):
150 search = self.search
151 samples, population = search.initial_samples, search.local_population
152 while self.remaining:
153 self.restarts += 1
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]
160 discovered = False
161 for i, group in enumerate(pending):
162 # Leave room for duplicate-peak checks and split local search
163 # calls across the remaining clusters.
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
169 if not discovered:
170 samples = min(2 * samples, self.budget)
171 population = max(population + 1, int(1.2 * population))
172
173
174
176 """Cluster nearest-better candidates using line tests, then refine each basin.
177
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.
183
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.
194 """
195
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.")
201 self._lower, self._upper = limits.T
202 with np.errstate(over="ignore"):
203 self._span = self._upper - self._lower
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.")
207 self.dimension = len(limits)
208 self._direction = 1. if maximise else -1.
209 self.initial_samples = (16 * self.dimension if initial_samples is None else
210 _positive_int(initial_samples, "initial_samples"))
211 self.selection_fraction = selection_fraction
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")
214 self.local_population = _positive_int(local_population, "local_population")
215 if self.local_population < 2:
216 raise ValueError("local_population must be at least two.")
217 self.local_generations = _positive_int(local_generations, "local_generations")
218 self.fitness_tolerance, self.seed = fitness_tolerance, seed
219
220 def _decode(self, point):
221 return tuple(map(float, np.clip(self._lower + self._span * point, self._lower, self._upper)))
222
223
224 def run(self, evaluate, budget):
225 """Measure finite scalar fitness on raw decision vectors.
226
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.
230 """
231 budget = _positive_int(budget, "budget")
232 if not callable(evaluate):
233 raise TypeError("evaluate must be callable.")
234 try:
235 import cma # noqa: F401
236 except ImportError as error:
237 raise ImportError("HillVallEA requires qdpy[cma].") from error
238 run = _HillValleyRun(self, evaluate, budget)
239 try:
240 run.optimise()
241 except _BudgetExhausted:
242 pass
243
244 def record(point):
245 return HillValleyPeak(self._decode(point.vector), self._direction * point.quality)
246
247 peaks = tuple(record(point) for point in sorted(run.elites, key=lambda point: -point.quality))
248 return HillValleyResult(peaks, record(run.best), *run.calls, run.restarts)
Discover distinct high-quality basins from a scalar black-box objective.
run(self, evaluate, budget)
Run from scratch and return near-optima with an exact evaluation count.
A measured candidate in the original decision space.
Distinct retained basins and an exact breakdown of callback counts.