6"""Generate benchmark functions with varied local-optima network topology."""
8from dataclasses
import dataclass, field
9from math
import ceil, log2
10from operator
import index
13from scipy.sparse.csgraph
import shortest_path
14from scipy.spatial.distance
import cdist
15from scipy.stats
import qmc
17__all__ = [
"MaxGaussianLandscape",
"LocalOptimaNetwork",
"LandscapeBenchmarkResult",
18 "local_optima_network",
"generate_local_optima_benchmarks"]
21def _count(value, label, minimum=1):
24 raise ValueError(f
"{label} must be at least {minimum}.")
29@dataclass(frozen=True)
31 """Keep distinct center rows, positive heights, and positive standard deviations."""
33 centers: tuple[tuple[float, ...], ...]
34 heights: tuple[float, ...]
35 scales: tuple[float, ...]
36 _centers: np.ndarray = field(init=
False, repr=
False, compare=
False)
37 _log_heights: np.ndarray = field(init=
False, repr=
False, compare=
False)
38 _scales: np.ndarray = field(init=
False, repr=
False, compare=
False)
40 def __post_init__(self):
41 centers, heights, scales = (np.asarray(v, dtype=float)
for v
in (self.
centers, self.
heights, self.
scales))
42 if (centers.ndim != 2
or not centers.size
or not np.all((0 <= centers) & (centers <= 1))
43 or len(np.unique(centers, axis=0)) != len(centers)
44 or heights.shape != (len(centers),)
or scales.shape != heights.shape
45 or not np.all((0 < heights) & (heights <= 1.))
46 or not np.all((0 < scales) & (scales < np.inf))):
47 raise ValueError(
"Use distinct centers on the unit box, heights in (0, 1], and finite positive scales.")
48 object.__setattr__(self,
"centers", tuple(tuple(row)
for row
in centers.tolist()))
49 object.__setattr__(self,
"heights", tuple(heights.tolist()))
50 object.__setattr__(self,
"scales", tuple(scales.tolist()))
51 object.__setattr__(self,
"_centers", centers.copy())
52 object.__setattr__(self,
"_log_heights", np.log(heights))
53 object.__setattr__(self,
"_scales", scales.copy())
55 def _scores(self, points):
57 with np.errstate(over=
"ignore"):
61 def _points(self, points):
62 points = np.asarray(points, dtype=float)
63 if (points.ndim
not in (1, 2)
or points.shape[-1] != self.
_centers.shape[1]
64 or not np.all((0 <= points) & (points <= 1.))):
65 raise ValueError(
"Positions must be rows in the landscape's unit box.")
70 dominant = values.argmax(axis=1)
71 roots = np.arange(len(dominant))
73 if values[i, dominant[i]] > values[i, i]:
74 roots[i] = roots[dominant[i]]
79 """Return max-Gaussian fitness in (0, 1], with underflow rounded to zero."""
81 scores = np.exp(self.
_scores(np.atleast_2d(points)).max(axis=1))
82 return float(scores[0])
if points.ndim == 1
else scores
86 """Assign a point or a matrix of points to the final dominant centers."""
88 indices = self.
_roots()[self.
_scores(np.atleast_2d(points)).argmax(axis=1)]
89 return int(indices[0])
if points.ndim == 1
else indices
93@dataclass(frozen=True)
95 """Transition rows include returns to the original optimum and sum to one."""
97 nodes: tuple[int, ...]
98 transitions: tuple[tuple[float, ...], ...]
100 descriptors: tuple[float, ...]
104def _graph_features(transition, heights, optimum):
106 increasing = np.where(heights[:,
None] < heights[
None, :], transition, 0.)
107 edge = increasing > 0.
108 strength = increasing.sum(axis=0)
109 sinks = np.flatnonzero(~edge.any(axis=1))
110 distances = shortest_path(edge, directed=
True, unweighted=
True)
111 to_optimum = distances[:, optimum]
112 root = np.arange(size)
113 for i
in np.argsort(-heights, kind=
"stable"):
115 root[i] = root[int(np.argmax(increasing[i]))]
116 return (float(size), float(edge.sum() / max(1, size * (size - 1))), float(len(sinks)),
117 float(to_optimum[np.isfinite(to_optimum)].mean()),
118 float(distances[:, sinks].min(axis=1).mean()), float(strength[optimum]),
119 float(strength[sinks].mean()), float(np.mean(root == optimum)))
128def local_optima_network(landscape, *, samples=64, radius=None, seed=0):
129 """Follow dominated center chains, then assign sampled escape points without local search."""
130 if not isinstance(landscape, MaxGaussianLandscape):
131 raise TypeError(
"Supply a MaxGaussianLandscape.")
132 samples = _count(samples,
"samples")
133 width = landscape._centers.shape[1]
134 radius = len(landscape.centers) ** (-1. / width)
if radius
is None else float(radius)
135 if not 0 < radius <= np.sqrt(width):
136 raise ValueError(
"Specify a positive radius no larger than the unit-box diameter.")
137 rng = np.random.default_rng(seed)
138 directions = rng.normal(size=(samples, width))
139 lengths = np.linalg.norm(directions, axis=1, keepdims=
True)
140 offsets = radius * (directions / lengths) * rng.random((samples, 1)) ** (1. / width)
141 roots = landscape._roots()
142 nodes = np.flatnonzero(roots == np.arange(len(roots)))
143 rank = np.zeros(len(roots), dtype=int)
144 rank[nodes] = np.arange(len(nodes))
145 transition = np.empty((len(nodes), len(nodes)))
146 for i, center
in enumerate(landscape._centers[nodes]):
147 scores = landscape._scores(np.clip(center + offsets, 0., 1.))
148 hits = rank[roots[scores.argmax(axis=1)]]
149 transition[i] = np.bincount(hits, minlength=len(nodes)) / samples
150 heights = np.asarray(landscape.heights)[nodes]
151 best = int(np.argmax(heights))
152 return LocalOptimaNetwork(tuple(map(int, nodes)), tuple(tuple(row)
for row
in transition.tolist()),
153 int(nodes[best]), _graph_features(transition, heights, best), len(nodes) * samples)
157@dataclass(frozen=True)
159 """Each evaluated landscape is paired with one estimated network."""
161 landscapes: tuple[MaxGaussianLandscape, ...]
162 networks: tuple[LocalOptimaNetwork, ...]
163 population: tuple[int, ...]
164 novelty_archive: tuple[int, ...]
183def generate_local_optima_benchmarks(*, dimension=2, peaks=12, budget=64, population_size=12, offspring=12,
184 samples=64, neighbors=5, threshold=.03, archive_capacity=256,
185 mutation_scale=.15, novelty=True, seed=0):
186 """Search heights and scales under a common escape-probe panel.
188 Use novelty-ranked parent-plus-child survival in the eight graph
189 features. Normalize size-dependent features by the component count.
190 Keep all measured landscapes for downstream benchmarks independently
191 of the bounded search memory.
193 dimension, peaks, budget = _count(dimension,
"dimension"), _count(peaks,
"peaks"), _count(budget,
"budget", 0)
194 population_size = _count(population_size,
"population_size")
195 offspring, samples = _count(offspring,
"offspring"), _count(samples,
"samples")
196 neighbors, capacity = _count(neighbors,
"neighbors"), _count(archive_capacity,
"archive_capacity")
197 if not 0 <= threshold < np.inf
or not 0 < mutation_scale <= 1.:
198 raise ValueError(
"Use a nonnegative novelty threshold and mutation scale in (0, 1].")
199 rng = np.random.default_rng(seed)
200 centers = qmc.Sobol(dimension, seed=rng).random_base2(ceil(log2(peaks)))[:peaks]
201 network_seed = int(rng.integers(2**32))
202 radius = peaks ** (-1. / dimension)
203 divisor = np.array((peaks, 1., peaks, peaks, peaks, peaks, peaks, 1.))
204 landscapes, networks, genomes = [], [], []
207 heights, scales = np.split(genome, 2)
208 landscape =
MaxGaussianLandscape(centers, np.maximum(1e-6, heights), radius * (.25 + 2.75 * scales))
209 network = local_optima_network(landscape, samples=samples, radius=radius, seed=network_seed)
210 landscapes.append(landscape)
211 networks.append(network)
212 genomes.append(genome)
213 return len(genomes) - 1
215 parents = [measure(rng.random(2 * peaks))
for _
in range(min(population_size, budget))]
216 memory = parents[-capacity:]
if novelty
else []
217 while len(genomes) < budget:
218 amount = min(offspring, budget - len(genomes))
220 for _
in range(amount):
221 measure(rng.random(2 * peaks))
224 for parent
in rng.choice(parents, size=amount):
225 genomes_new = np.clip(genomes[parent] + rng.normal(0., mutation_scale, 2 * peaks), 0., 1.)
226 children.append(measure(genomes_new))
227 pool = parents + children
228 reference = list(dict.fromkeys(pool + memory))
229 points = np.asarray([networks[i].descriptors
for i
in reference]) / divisor
230 distances = cdist(points[:len(pool)], points)
231 np.fill_diagonal(distances[:, :len(pool)], np.inf)
232 n = min(neighbors, len(reference) - 1)
233 scores = np.partition(distances, n - 1, axis=1)[:, :n].mean(axis=1)
234 memory = (memory + [i
for i, score
in zip(children, scores[len(parents):])
if score > threshold])[-capacity:]
235 parents = [pool[i]
for i
in np.argsort(-scores, kind=
"stable")[:population_size]]
237 sum(row.basin_probes
for row
in networks))
Benchmark sequence and indices retained by novelty search.
Sampled directed escape network with rows indexed by visible Gaussian centers.
Pointwise maximum of positive isotropic Gaussian peaks on the unit box.
__call__(self, points)
Evaluate one point or a batch of unit-box positions.
basin(self, points)
Resolve dominant Gaussian regions to their visible local-optimum indices.