Source code for qdpy.algorithms.magnitude

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Dissimilarity-based niches and magnitude-weighted Go-Explore.
# @see https://doi.org/10.1145/3583131.3590409

"""Search structured descriptor spaces using only pairwise dissimilarities."""

from itertools import islice
from math import isfinite, log

import numpy as np
from scipy.linalg import cho_factor, cho_solve

from .medoid_map_elites import MedoidElite, _distance_value
from .modern import _positive_int

__all__ = ["MagnitudeArchive", "MagnitudeGoExplore", "magnitude_weights"]


def _choose_scale(distances):
    """Find a scale where each kernel row has off-diagonal sum at most 0.95."""
    count = len(distances)
    if count == 1:
        return 1., 1.
    unit = distances[distances > 0].min()
    with np.errstate(over="ignore"):
        ratios = distances / unit
    low, high = 0., log((count - 1) / .95)
    for _ in range(24):
        mid = (low + high) / 2
        if np.exp(-mid * ratios).sum(axis=1).max() <= 1.95:
            high = mid
        else:
            low = mid
    return unit, high


def _kernel_weights(distances, unit, scale):
    with np.errstate(over="ignore"):
        kernel = np.exp(-(distances / unit) * scale)
    weights = cho_solve(cho_factor(kernel), np.ones(len(distances)))
    if weights.min() < -1e-10 or not np.isfinite(weights).all():
        raise ValueError("Use a scale with nonnegative finite magnitude weights.")
    return np.maximum(weights, 0.)


## @brief Solve the magnitude weighting system for a finite dissimilarity matrix.
[docs] def magnitude_weights(distances, *, scale=None): """Return the unnormalized weights of exp(-scale * distances). :param distances: Nonempty square symmetric array with a zero diagonal and finite positive off-diagonal values. :param scale: Positive kernel scale. By default choose a scale with strict diagonal dominance and nonnegative weights. :raises ValueError: If the matrix is invalid or the requested kernel lacks a positive-definite solve with nonnegative weights. """ distances = np.asarray(distances, dtype=float) if (distances.ndim != 2 or not len(distances) or distances.shape[0] != distances.shape[1] or not np.isfinite(distances).all() or (distances < 0.).any() or not np.array_equal(distances, distances.T) or np.count_nonzero(distances) != len(distances) * (len(distances) - 1)): raise ValueError("Use finite symmetric distances, positive away from a zero diagonal.") if np.any(distances.diagonal() != 0.): raise ValueError("The distance diagonal must be zero.") if scale is None: unit, scale = _choose_scale(distances) elif not isfinite(scale) or scale <= 0.: raise ValueError("scale must be finite and positive.") else: unit = 1. try: return _kernel_weights(distances, unit, scale) except np.linalg.LinAlgError as error: raise ValueError("The magnitude kernel must be positive definite.") from error
def _distance_matrix(points, distance): matrix = np.zeros((len(points), len(points))) for i, point in enumerate(points): row = [_distance_value(distance, point, previous) for previous in points[:i]] matrix[i, :i] = matrix[:i, i] = row return matrix ## @brief Archive best measured candidates by their ordered closest landmarks.
[docs] class MagnitudeArchive: """Keep one elite per occupied landmark signature and cache elite distances. :param landmarks: Ordered distinct immutable and hashable descriptors. :param distance: Symmetric, finite dissimilarity, zero for equal points and strictly positive for distinct points. :param rank: Number of closest landmarks in each signature. Equal distances are ordered by the supplied landmark order. :param capacity: Maximum number of occupied signatures. If a new niche would exceed it, evict the least magnitude-weighted candidate in the expanded set, breaking ties by fitness and admission order. :param maximize: Compare larger scalar fitness values as better. """ def __init__(self, landmarks, distance, *, rank=2, capacity=256, maximize=True): self._landmarks = tuple(landmarks) self._rank = _positive_int(rank, "rank") self._capacity = _positive_int(capacity, "capacity") if (len(set(self._landmarks)) != len(self._landmarks) or self._rank > len(self._landmarks) or not callable(distance)): raise ValueError("Supply distinct landmarks and one callable distance with enough anchors for rank.") self._distance = distance self._direction = 1. if maximize else -1. self._cells = {} self._distances = np.zeros((0, 0)) self._weights = np.empty(0)
[docs] @classmethod def from_reference(cls, reference, distance, *, count, **kwargs): """Fit landmarks by trying magnitude-increasing swaps at a fixed kernel scale. Use the first count distinct descriptors as the initial set, then try each remaining descriptor in place of the least-weighted one. The ordered reference panel is consumed once and needs no fitness. """ count = _positive_int(count, "count") points = iter(dict.fromkeys(reference)) landmarks = tuple(islice(points, count)) if len(landmarks) != count: raise ValueError("The reference panel needs at least count distinct descriptors.") matrix = _distance_matrix(landmarks, distance) if np.count_nonzero(matrix) != count * (count - 1): raise ValueError("Distinct landmarks need strictly positive distances.") unit, scale = _choose_scale(matrix) weights = _kernel_weights(matrix, unit, scale) landmarks = list(landmarks) for point in points: slot = int(np.argmin(weights)) row = np.array([0. if i == slot else _distance_value(distance, point, anchor) for i, anchor in enumerate(landmarks)]) if np.count_nonzero(row) != count - 1: raise ValueError("Distinct landmarks need strictly positive distances.") trial = matrix.copy() trial[slot, :] = trial[:, slot] = row try: trial_weights = _kernel_weights(trial, unit, scale) except (np.linalg.LinAlgError, ValueError): continue if trial_weights.sum() > weights.sum() + 1e-12: landmarks[slot] = point matrix, weights = trial, trial_weights return cls(landmarks, distance, **kwargs)
@property def landmarks(self): """Return the fixed landmarks in tie-breaking order.""" return self._landmarks @property def cells(self): """Return a copy of the occupied signatures and their measured elites.""" return dict(self._cells) @property def weights(self): """Return a copy of the unnormalized magnitude weights by signature.""" return dict(zip(self._cells, map(float, self._weights))) def __len__(self): return len(self._cells) def __iter__(self): return iter(self._cells.values()) ## @brief Map a descriptor to a tuple of landmark indices.
[docs] def index(self, descriptor): """Return the ordered indices of its rank nearest landmarks.""" ordered = sorted(range(len(self._landmarks)), key=lambda i: _distance_value(self._distance, descriptor, self._landmarks[i])) return tuple(ordered[:self._rank])
## @brief Admit a measured elite and update cached weights.
[docs] def add(self, genome, fitness, descriptor): """Return whether the candidate filled or improved its niche.""" fitness = float(fitness) if not isfinite(fitness): raise ValueError("fitness must be finite.") cell = self.index(descriptor) incumbent = self._cells.get(cell) if incumbent is not None and self._direction * fitness <= self._direction * incumbent.fitness: return False kept = [i for i, key in enumerate(self._cells) if key != cell] cells = dict(self._cells) cells.pop(cell, None) matrix = np.zeros((len(kept) + 1, len(kept) + 1)) matrix[:-1, :-1] = self._distances[np.ix_(kept, kept)] row = [_distance_value(self._distance, descriptor, elite.descriptor) for elite in cells.values()] matrix[:-1, -1] = matrix[-1, :-1] = row cells[cell] = MedoidElite(genome, fitness, descriptor) weights = magnitude_weights(matrix) if len(cells) > self._capacity: entries = tuple(cells.items()) candidates = np.flatnonzero(weights <= weights.min() + 1e-12) slot = min(candidates, key=lambda i: (self._direction * entries[i][1].fitness, -i)) removed = entries[slot][0] if removed == cell: return False del cells[removed] mask = np.arange(len(entries)) != slot matrix = matrix[np.ix_(mask, mask)] weights = magnitude_weights(matrix) self._cells, self._distances, self._weights = cells, matrix, weights return True
## @brief Revisit diverse elites and explore with a caller-defined mutation.
[docs] class MagnitudeGoExplore: """Use Huntsman's landmark and magnitude selection with direct evaluation. :param archive: MagnitudeArchive to fill. :param propose: Callback (rng) returning a new genome. :param mutate: Callback (parent_genome, rng) returning an offspring. :param selection: Use "magnitude" or the "uniform" parent control. :param quality_weight: Weight of normalized fitness in parent logits. :param random_fraction: Fraction of proposals sampled without a parent. :param seed: Private seed for proposals and parent selection. """ def __init__(self, archive, *, propose, mutate, selection="magnitude", quality_weight=1., random_fraction=.1, seed=0): if not isinstance(archive, MagnitudeArchive) or not callable(propose) or not callable(mutate): raise TypeError("Supply a MagnitudeArchive and two callable search operators.") if (selection not in ("magnitude", "uniform") or not isfinite(quality_weight) or quality_weight < 0. or not 0. <= random_fraction <= 1.): raise ValueError("Use a supported selection, finite nonnegative quality weight and valid fraction.") self.archive = archive self._propose, self._mutate = propose, mutate self._selection = selection self._quality_weight = quality_weight self._random_fraction = random_fraction self._rng = np.random.default_rng(seed) self.nb_evaluations = 0 def _parent(self): elites = tuple(self.archive) if self._selection == "uniform": return elites[int(self._rng.integers(len(elites)))] quality = self.archive._direction * np.array([elite.fitness for elite in elites]) quality /= max(1., np.abs(quality).max()) span = np.ptp(quality) boost = (quality - quality.max()) / span if span else quality * 0. probability = self.archive._weights * np.exp(self._quality_weight * boost) return elites[int(self._rng.choice(len(elites), p=probability / probability.sum()))] ## @brief Spend an additional budget of true objective evaluations.
[docs] def optimise(self, evaluate, *, budget): """Call evaluate(genome) for (scalar fitness, descriptor) and return the archive.""" for _ in range(_positive_int(budget, "budget")): if self.archive and self._rng.random() >= self._random_fraction: genome = self._mutate(self._parent().genome, self._rng) else: genome = self._propose(self._rng) self.nb_evaluations += 1 fitness, descriptor = evaluate(genome) self.archive.add(genome, fitness, descriptor) return self.archive