# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Search-free escape networks and novelty-generated Gaussian landscapes.
# @see https://doi.org/10.1007/978-3-032-36229-2_20
"""Generate benchmark functions with varied local-optima network topology."""
from dataclasses import dataclass, field
from math import ceil, log2
from operator import index
import numpy as np
from scipy.sparse.csgraph import shortest_path
from scipy.spatial.distance import cdist
from scipy.stats import qmc
__all__ = ["MaxGaussianLandscape", "LocalOptimaNetwork", "LandscapeBenchmarkResult",
"local_optima_network", "generate_local_optima_benchmarks"]
def _count(value, label, minimum=1):
value = index(value)
if value < minimum:
raise ValueError(f"{label} must be at least {minimum}.")
return value
## @brief Pointwise maximum of positive isotropic Gaussian peaks on the unit box.
[docs]
@dataclass(frozen=True)
class MaxGaussianLandscape:
"""Keep distinct center rows, positive heights, and positive standard deviations."""
centers: tuple[tuple[float, ...], ...]
heights: tuple[float, ...]
scales: tuple[float, ...]
_centers: np.ndarray = field(init=False, repr=False, compare=False)
_log_heights: np.ndarray = field(init=False, repr=False, compare=False)
_scales: np.ndarray = field(init=False, repr=False, compare=False)
def __post_init__(self):
centers, heights, scales = (np.asarray(v, dtype=float) for v in (self.centers, self.heights, self.scales))
if (centers.ndim != 2 or not centers.size or not np.all((0 <= centers) & (centers <= 1))
or len(np.unique(centers, axis=0)) != len(centers)
or heights.shape != (len(centers),) or scales.shape != heights.shape
or not np.all((0 < heights) & (heights <= 1.))
or not np.all((0 < scales) & (scales < np.inf))):
raise ValueError("Use distinct centers on the unit box, heights in (0, 1], and finite positive scales.")
object.__setattr__(self, "centers", tuple(tuple(row) for row in centers.tolist()))
object.__setattr__(self, "heights", tuple(heights.tolist()))
object.__setattr__(self, "scales", tuple(scales.tolist()))
object.__setattr__(self, "_centers", centers.copy())
object.__setattr__(self, "_log_heights", np.log(heights))
object.__setattr__(self, "_scales", scales.copy())
def _scores(self, points):
# Log heights preserve ownership even when all peaks underflow.
with np.errstate(over="ignore"):
distance = cdist(points, self._centers) / self._scales
return self._log_heights - .5 * distance ** 2
def _points(self, points):
points = np.asarray(points, dtype=float)
if (points.ndim not in (1, 2) or points.shape[-1] != self._centers.shape[1]
or not np.all((0 <= points) & (points <= 1.))):
raise ValueError("Positions must be rows in the landscape's unit box.")
return points
def _roots(self):
values = self._scores(self._centers)
dominant = values.argmax(axis=1)
roots = np.arange(len(dominant))
for i in np.argsort(-self._log_heights, kind="stable"):
if values[i, dominant[i]] > values[i, i]:
roots[i] = roots[dominant[i]]
return roots
## @brief Evaluate one point or a batch of unit-box positions.
[docs]
def __call__(self, points):
"""Return max-Gaussian fitness in (0, 1], with underflow rounded to zero."""
points = self._points(points)
scores = np.exp(self._scores(np.atleast_2d(points)).max(axis=1))
return float(scores[0]) if points.ndim == 1 else scores
## @brief Resolve dominant Gaussian regions to their visible local-optimum indices.
[docs]
def basin(self, points):
"""Assign a point or a matrix of points to the final dominant centers."""
points = self._points(points)
indices = self._roots()[self._scores(np.atleast_2d(points)).argmax(axis=1)]
return int(indices[0]) if points.ndim == 1 else indices
## @brief Sampled directed escape network with rows indexed by visible Gaussian centers.
[docs]
@dataclass(frozen=True)
class LocalOptimaNetwork:
"""Transition rows include returns to the original optimum and sum to one."""
nodes: tuple[int, ...]
transitions: tuple[tuple[float, ...], ...]
optimum: int
descriptors: tuple[float, ...]
basin_probes: int
def _graph_features(transition, heights, optimum):
size = len(heights)
increasing = np.where(heights[:, None] < heights[None, :], transition, 0.)
edge = increasing > 0.
strength = increasing.sum(axis=0)
sinks = np.flatnonzero(~edge.any(axis=1))
distances = shortest_path(edge, directed=True, unweighted=True)
to_optimum = distances[:, optimum]
root = np.arange(size)
for i in np.argsort(-heights, kind="stable"):
if edge[i].any():
root[i] = root[int(np.argmax(increasing[i]))]
return (float(size), float(edge.sum() / max(1, size * (size - 1))), float(len(sinks)),
float(to_optimum[np.isfinite(to_optimum)].mean()),
float(distances[:, sinks].min(axis=1).mean()), float(strength[optimum]),
float(strength[sinks].mean()), float(np.mean(root == optimum)))
## @brief Estimate escape transition probabilities using a ball around each visible optimum.
# @param landscape MaxGaussianLandscape on the unit box.
# @param samples Number of probes per visible optimum.
# @param radius Perturbation radius, defaulting to the inverse density scale of the centers.
# @param seed Private seed for a common perturbation panel.
# @return LocalOptimaNetwork with the eight monotonic-network descriptors of Mizuta et al.
[docs]
def local_optima_network(landscape, *, samples=64, radius=None, seed=0):
"""Follow dominated center chains, then assign sampled escape points without local search."""
if not isinstance(landscape, MaxGaussianLandscape):
raise TypeError("Supply a MaxGaussianLandscape.")
samples = _count(samples, "samples")
width = landscape._centers.shape[1]
radius = len(landscape.centers) ** (-1. / width) if radius is None else float(radius)
if not 0 < radius <= np.sqrt(width):
raise ValueError("Specify a positive radius no larger than the unit-box diameter.")
rng = np.random.default_rng(seed)
directions = rng.normal(size=(samples, width))
lengths = np.linalg.norm(directions, axis=1, keepdims=True)
offsets = radius * (directions / lengths) * rng.random((samples, 1)) ** (1. / width)
roots = landscape._roots()
nodes = np.flatnonzero(roots == np.arange(len(roots)))
rank = np.zeros(len(roots), dtype=int)
rank[nodes] = np.arange(len(nodes))
transition = np.empty((len(nodes), len(nodes)))
for i, center in enumerate(landscape._centers[nodes]):
scores = landscape._scores(np.clip(center + offsets, 0., 1.))
hits = rank[roots[scores.argmax(axis=1)]]
transition[i] = np.bincount(hits, minlength=len(nodes)) / samples
heights = np.asarray(landscape.heights)[nodes]
best = int(np.argmax(heights))
return LocalOptimaNetwork(tuple(map(int, nodes)), tuple(tuple(row) for row in transition.tolist()),
int(nodes[best]), _graph_features(transition, heights, best), len(nodes) * samples)
## @brief Benchmark sequence and indices retained by novelty search.
[docs]
@dataclass(frozen=True)
class LandscapeBenchmarkResult:
"""Each evaluated landscape is paired with one estimated network."""
landscapes: tuple[MaxGaussianLandscape, ...]
networks: tuple[LocalOptimaNetwork, ...]
population: tuple[int, ...]
novelty_archive: tuple[int, ...]
evaluations: int
basin_probes: int
## @brief Generate benchmarks with a bounded novelty archive and fixed Sobol centers.
# @param dimension Landscape dimension.
# @param peaks Number of isotropic Gaussian components.
# @param budget Number of landscapes whose network is built.
# @param population_size Maximum survivor population.
# @param offspring Number of new landscapes per generation.
# @param samples Escape probes per visible optimum.
# @param neighbors Number of nearest graph descriptors in the novelty calculation.
# @param threshold Minimum novelty for adding a child to memory.
# @param archive_capacity Maximum novelty memory, evicted in arrival order.
# @param mutation_scale Gaussian mutation scale in normalized genotype coordinates.
# @param novelty Use novelty selection or a matched independent random control.
# @param seed Root sampling and network seed.
# @return LandscapeBenchmarkResult containing every measured landscape.
[docs]
def generate_local_optima_benchmarks(*, dimension=2, peaks=12, budget=64, population_size=12, offspring=12,
samples=64, neighbors=5, threshold=.03, archive_capacity=256,
mutation_scale=.15, novelty=True, seed=0):
"""Search heights and scales under a common escape-probe panel.
Use novelty-ranked parent-plus-child survival in the eight graph
features. Normalize size-dependent features by the component count.
Keep all measured landscapes for downstream benchmarks independently
of the bounded search memory.
"""
dimension, peaks, budget = _count(dimension, "dimension"), _count(peaks, "peaks"), _count(budget, "budget", 0)
population_size = _count(population_size, "population_size")
offspring, samples = _count(offspring, "offspring"), _count(samples, "samples")
neighbors, capacity = _count(neighbors, "neighbors"), _count(archive_capacity, "archive_capacity")
if not 0 <= threshold < np.inf or not 0 < mutation_scale <= 1.:
raise ValueError("Use a nonnegative novelty threshold and mutation scale in (0, 1].")
rng = np.random.default_rng(seed)
centers = qmc.Sobol(dimension, seed=rng).random_base2(ceil(log2(peaks)))[:peaks]
network_seed = int(rng.integers(2**32))
radius = peaks ** (-1. / dimension)
divisor = np.array((peaks, 1., peaks, peaks, peaks, peaks, peaks, 1.))
landscapes, networks, genomes = [], [], []
def measure(genome):
heights, scales = np.split(genome, 2)
landscape = MaxGaussianLandscape(centers, np.maximum(1e-6, heights), radius * (.25 + 2.75 * scales))
network = local_optima_network(landscape, samples=samples, radius=radius, seed=network_seed)
landscapes.append(landscape)
networks.append(network)
genomes.append(genome)
return len(genomes) - 1
parents = [measure(rng.random(2 * peaks)) for _ in range(min(population_size, budget))]
memory = parents[-capacity:] if novelty else []
while len(genomes) < budget:
amount = min(offspring, budget - len(genomes))
if not novelty:
for _ in range(amount):
measure(rng.random(2 * peaks))
continue
children = []
for parent in rng.choice(parents, size=amount):
genomes_new = np.clip(genomes[parent] + rng.normal(0., mutation_scale, 2 * peaks), 0., 1.)
children.append(measure(genomes_new))
pool = parents + children
reference = list(dict.fromkeys(pool + memory))
points = np.asarray([networks[i].descriptors for i in reference]) / divisor
distances = cdist(points[:len(pool)], points)
np.fill_diagonal(distances[:, :len(pool)], np.inf)
n = min(neighbors, len(reference) - 1)
scores = np.partition(distances, n - 1, axis=1)[:, :n].mean(axis=1)
memory = (memory + [i for i, score in zip(children, scores[len(parents):]) if score > threshold])[-capacity:]
parents = [pool[i] for i in np.argsort(-scores, kind="stable")[:population_size]]
return LandscapeBenchmarkResult(tuple(landscapes), tuple(networks), tuple(parents), tuple(memory), budget,
sum(row.basin_probes for row in networks))