Source code for qdpy.algorithms.entropy_tours

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Entropy-based evolutionary diversity optimization for symmetric tours.
# @see https://arxiv.org/abs/2104.13538

"""Evolve a bounded portfolio of tours under a common cost ceiling."""

from collections import Counter
from dataclasses import dataclass
from itertools import islice
from math import fsum, isfinite, log
from operator import index

import numpy as np

from .modern import _positive_int

__all__ = ["EntropyTourSearch", "TourPortfolio", "TourResult", "tour_segment_entropy"]


def _canonical(tour, size):
    vertices = tuple(map(index, tour))
    if len(vertices) != size or set(vertices) != set(range(size)):
        raise ValueError("A tour must visit each vertex once, using labels 0 through n-1.")
    start = vertices.index(0)
    ordered = vertices[start:] + vertices[:start]
    reverse = ordered[:1] + ordered[:0:-1]
    return min(ordered, reverse)


def _windows(tour, length):
    extended = tour + tour[:length - 1]
    return tuple(extended[start:start + length] for start in range(len(tour)))


def _segments(tour, length):
    windows = _windows(tour, length)
    return windows + tuple(window[::-1] for window in windows)


def _term(count):
    return count * log(count) if count else 0.


def _entropy(counts):
    total = sum(counts.values())
    return log(total) - fsum(map(_term, counts.values())) / total if total else 0.


def _replacement_delta(counts, old, new):
    """Compare entropy numerators using only segments affected by a replacement."""
    changes = Counter(new)
    changes.subtract(old)
    return fsum(_term(counts[segment]) - _term(counts[segment] + change)
                for segment, change in changes.items() if change)


## @brief Measure the Shannon entropy of directed cyclic k-vertex segments.
[docs] def tour_segment_entropy(tours, segment_length=3): """Count each segment in both directions and return its population entropy in nats.""" length = _positive_int(segment_length, "segment_length") if length < 2: raise ValueError("A segment needs at least two vertices.") tours = tuple(tuple(tour) for tour in tours) if not tours: return 0. size = len(tours[0]) if length > size: raise ValueError("segment_length cannot exceed the number of vertices.") counts = Counter(segment for tour in tours for segment in _segments(_canonical(tour, size), length)) return _entropy(counts)
## @brief Report one canonical tour and its exact cyclic cost.
[docs] @dataclass(frozen=True) class TourResult: """The route starts at vertex zero and omits the repeated closing vertex.""" tour: tuple[int, ...] cost: float
## @brief Return a feasible portfolio and its search costs.
[docs] @dataclass(frozen=True) class TourPortfolio: """Distinct tours, directed segment entropy, and all measured attempts.""" tours: tuple[TourResult, ...] entropy: float evaluations: int
## @brief Optimize high-order segment entropy among bounded-cost symmetric tours.
[docs] class EntropyTourSearch: """Generate a biased and a uniform 2-opt child and compare them with their parent. :param distances: Square symmetric nonnegative matrix of finite edge costs. :param cost_limit: Inclusive ceiling for each retained tour. :param population_size: Maximum number of distinct tours to retain. :param segment_length: Number of consecutive vertices in a segment. :param seed: Private random stream for parent choice and cut locations. """ def __init__(self, distances, cost_limit, population_size, *, segment_length=3, seed=0): costs = np.array(distances, dtype=float, copy=True) if (costs.ndim != 2 or costs.shape[0] != costs.shape[1] or len(costs) < 4 or not np.isfinite(costs).all() or np.any(costs < 0.) or not np.array_equal(costs, costs.T)): raise ValueError("Provide a symmetric finite nonnegative edge-cost matrix with at least four vertices.") self.population_size = _positive_int(population_size, "population_size") self.segment_length = _positive_int(segment_length, "segment_length") if not 2 <= self.segment_length <= len(costs) or not isfinite(cost_limit) or cost_limit < 0.: raise ValueError("Use a segment length in [2, n] and a finite nonnegative cost limit.") self._costs = costs self.cost_limit, self.seed = float(cost_limit), seed def _cost(self, tour): return fsum(self._costs[a, b] for a, b in zip(tour, tour[1:] + tour[:1])) def _two_opt(self, tour, rng, frequencies=None): size = len(tour) probability = None if frequencies is not None: starts = [frequencies[segment] for segment in _windows(tour, self.segment_length)] # Every covered edge inherits the frequency of its segment. weights = np.asarray([sum(starts[(edge - offset) % size] for offset in range(self.segment_length - 1)) for edge in range(size)], dtype=float) probability = weights / weights.sum() first = int(rng.choice(size, p=probability)) second = (first + int(rng.integers(2, size - 1))) % size first, second = sorted((first, second)) return _canonical(tour[:first + 1] + tour[first + 1:second + 1][::-1] + tour[second + 1:], size) ## @brief Evolve an exact-call-bounded portfolio from caller-supplied tours.
[docs] def run(self, initial_tours, *, budget): """Return distinct feasible tours and count every evaluated seed or child. At least one initial tour must meet the ceiling. A single feasible seed can grow to a larger portfolio as new tours are found. """ budget = _positive_int(budget, "budget") rng = np.random.default_rng(self.seed) counts = Counter() tours = {} calls = 0 for initial in islice(initial_tours, budget): tour = _canonical(initial, len(self._costs)) cost = self._cost(tour) calls += 1 if cost <= self.cost_limit and tour not in tours: tours[tour] = cost counts.update(_segments(tour, self.segment_length)) if len(tours) == self.population_size: break if not tours: raise ValueError("Supply at least one initial tour satisfying the cost limit within budget.") while calls < budget: parent = tuple(tours)[rng.integers(len(tours))] old_segments = _segments(parent, self.segment_length) # Draw both proposals against the same population and parent. proposals = [self._two_opt(parent, rng, counts)] if budget - calls > 1: proposals.append(self._two_opt(parent, rng)) growing = len(tours) < self.population_size choice, best_cost = parent, tours[parent] best_segments = old_segments best_delta = -np.inf if growing else 0. for child in proposals: cost = self._cost(child) calls += 1 if child not in tours and cost <= self.cost_limit: segments = _segments(child, self.segment_length) delta = _replacement_delta(counts, () if growing else old_segments, segments) if delta > best_delta + 1e-12: choice, best_cost, best_segments, best_delta = child, cost, segments, delta if choice != parent: if not growing: del tours[parent] for segment in old_segments: counts[segment] -= 1 if not counts[segment]: del counts[segment] tours[choice] = best_cost counts.update(best_segments) return TourPortfolio(tuple(TourResult(tour, cost) for tour, cost in tours.items()), _entropy(counts), calls)