# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Binary particle swarm search with Hamming novelty and measured reporting.
# @see https://arxiv.org/html/2112.07875
"""Explore binary designs with novelty-guided particle swarm optimization."""
from collections import deque
from dataclasses import dataclass
from math import isfinite
import numpy as np
from scipy.special import expit
from qdpy.containers import CVTGrid, Grid
from qdpy.phenotype import Features, Fitness, Individual
from .modern import _positive_int
__all__ = ["NoveltyBinaryPSO", "BinarySwarmResult"]
## @brief Final particle positions, novelty memory, and measured search costs.
[docs]
@dataclass(frozen=True)
class BinarySwarmResult:
"""The archive retains measured fitness. The memory guides swarm novelty."""
archive: Grid
positions: tuple[tuple[int, ...], ...]
memory: tuple[tuple[int, ...], ...]
evaluations: int
archive_updates: int
out_of_domain: int
def _hamming_novelty(points, memory, neighbors):
"""Use the mean distance to the closest remembered binary designs."""
if not len(memory):
return np.zeros(len(points))
k = min(neighbors, len(memory))
return np.asarray([
np.partition(np.count_nonzero(memory != point, axis=1), k - 1)[:k].mean()
for point in points
])
## @brief Move binary particles using personal and social Hamming-novelty leaders.
[docs]
class NoveltyBinaryPSO:
"""Evaluate binary topologies and report their measured fitness and descriptors.
Recompute the novelty of current positions and personal leaders
against a common memory at each swarm iteration. The most novel
personal leader provides the social signal. A temperature schedule
controls the sigmoid used to sample bit values from their velocities.
The reporting archive receives real measurements and stays independent
of the novelty memory. Use deterministic measurements for a given bit vector.
:param archive: Empty parentless best-only scalar Grid or CVTGrid.
:param dimension: Number of bits.
:param population_size: Particle count, up to the available evaluation budget.
:param neighbors: Number of previous designs used for novelty.
:param memory_size: Maximum number of distinct recent designs.
:param inertia: Previous-velocity coefficient in the swarm update.
:param cognitive: Pull toward each particle's personal leader.
:param social: Pull toward the swarm's most novel leader.
:param velocity_limit: Absolute velocity cap.
:param temperature: Positive starting and ending sigmoid temperatures.
:param seed: Private seed for initial positions and velocity draws.
"""
def __init__(self, archive, dimension, *, population_size=16, neighbors=5, memory_size=256,
inertia=.7, cognitive=1.4, social=1.4, velocity_limit=6.,
temperature=(5., 1.), seed=0):
if (type(archive) not in (Grid, CVTGrid) or len(archive) or archive.parents
or archive.max_items_per_bin != 1 or archive.discard_random_on_bin_overload
or archive.fitness_domain is None or len(archive.fitness_domain) != 1
or archive.fitness_score_names or archive.features_score_names):
raise ValueError("Use an empty parentless scalar best-only Grid or CVTGrid.")
weights = archive.fitness_weights
if weights is not None and (len(weights) != 1 or not isfinite(weights[0]) or weights[0] == 0.):
raise ValueError("Use one finite, nonzero fitness weight.")
self._weights = (1.,) if weights is None else tuple(weights)
self.archive = archive
self.dimension = _positive_int(dimension, "dimension")
self.population_size = _positive_int(population_size, "population_size")
self.neighbors = _positive_int(neighbors, "neighbors")
self.memory_size = _positive_int(memory_size, "memory_size")
start, end = temperature
if (not all(0. <= value < np.inf for value in (inertia, cognitive, social))
or not 0. < velocity_limit < np.inf or not 0. < end <= start < np.inf):
raise ValueError("Use finite coefficients, a positive velocity limit and decreasing temperatures.")
self.inertia, self.cognitive, self.social = inertia, cognitive, social
self.velocity_limit, self.temperature, self.seed = velocity_limit, (start, end), seed
## @brief Run the swarm for at most budget objective calls.
# @param evaluate Callable mapping an immutable bit tuple to fitness and descriptors.
# @param budget Maximum number of objective calls, including out-of-domain results.
# @param repair Optional callable mapping a proposal to another bit vector.
# @return Final measured positions, novelty memory, archive, and counters.
[docs]
def optimise(self, evaluate, budget, *, repair=None):
"""Measure evaluate(bits) returning (scalar fitness, descriptors).
An optional repair(bits) supplies a feasible bit vector for
evaluation. Charge any additional work inside that callback
separately. Run with an empty reporting archive.
"""
if len(self.archive):
raise ValueError("Use an empty reporting archive for each swarm run.")
if not callable(evaluate) or (repair is not None and not callable(repair)):
raise TypeError("Supply a callable evaluator and optional repair.")
budget = _positive_int(budget, "budget")
rng = np.random.default_rng(self.seed)
width = min(self.population_size, budget)
moves = (budget - 1) // width
shape = (width, self.dimension)
positions = rng.integers(0, 2, size=shape, dtype=np.int8)
personal = positions.copy()
velocity = rng.uniform(-self.velocity_limit, self.velocity_limit, size=shape)
memory, seen = deque(), set()
calls = updates = outside = 0
while calls < budget:
count = min(budget - calls, width)
measured = []
for row in range(count):
genome = tuple(map(int, positions[row]))
if repair is not None:
fixed = np.asarray(repair(genome))
if fixed.shape != (self.dimension,) or not np.isin(fixed, (0, 1)).all():
raise ValueError("repair must return a binary vector of the configured length.")
positions[row] = fixed
genome = tuple(map(int, positions[row]))
fitness, features = evaluate(genome)
fitness = float(fitness)
features = tuple(map(float, features))
calls += 1
if (not isfinite(fitness) or len(features) != len(self.archive.features_domain)
or not all(map(isfinite, features))):
raise ValueError("Return one finite objective and finite archive descriptors.")
if (self.archive.in_bounds((fitness,), self.archive.fitness_domain)
and self.archive.in_bounds(features, self.archive.features_domain)):
if self.archive.free >= 1 or self.archive.solutions[self.archive.index_grid(features)]:
previous = self.archive.nb_added
self.archive.add(Individual(genome, fitness=Fitness((fitness,), weights=self._weights),
features=Features(features)))
updates += self.archive.nb_added - previous
else:
outside += 1
measured.append(genome)
snapshot = np.asarray(memory, dtype=np.int8)
candidates = _hamming_novelty(positions[:count], snapshot, self.neighbors)
leaders = _hamming_novelty(personal, snapshot, self.neighbors)
better = np.ones(count, dtype=bool) if not memory else candidates > leaders[:count]
np.copyto(personal[:count], positions[:count], where=better[:, None])
leaders[:count] = np.where(better, candidates, leaders[:count])
for genome in measured:
if genome not in seen:
if len(memory) == self.memory_size:
seen.remove(memory.popleft())
memory.append(genome)
seen.add(genome)
if calls < budget:
leader = personal[int(np.argmax(leaders))]
velocity = np.clip(self.inertia * velocity
+ self.cognitive * rng.random(shape) * (personal - positions)
+ self.social * rng.random(shape) * (leader - positions),
-self.velocity_limit, self.velocity_limit)
start, end = self.temperature
progress = (calls // width - 1) / max(1, moves - 1)
temperature = start + progress * (end - start)
# Update only the final batch's measured slots when the budget is short.
active = min(width, budget - calls)
positions[:active] = rng.random((active, self.dimension)) < expit(velocity[:active] / temperature)
return BinarySwarmResult(self.archive, tuple(tuple(map(int, row)) for row in positions),
tuple(memory), calls, updates, outside)