QDpy
Loading...
Searching...
No Matches
entropy_tours.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Evolve a bounded portfolio of tours under a common cost ceiling."""
7
8from collections import Counter
9from dataclasses import dataclass
10from itertools import islice
11from math import fsum, isfinite, log
12from operator import index
13
14import numpy as np
15
16from .modern import _positive_int
17
18__all__ = ["EntropyTourSearch", "TourPortfolio", "TourResult", "tour_segment_entropy"]
19
20
21def _canonical(tour, size):
22 vertices = tuple(map(index, tour))
23 if len(vertices) != size or set(vertices) != set(range(size)):
24 raise ValueError("A tour must visit each vertex once, using labels 0 through n-1.")
25 start = vertices.index(0)
26 ordered = vertices[start:] + vertices[:start]
27 reverse = ordered[:1] + ordered[:0:-1]
28 return min(ordered, reverse)
29
30
31def _windows(tour, length):
32 extended = tour + tour[:length - 1]
33 return tuple(extended[start:start + length] for start in range(len(tour)))
34
35
36def _segments(tour, length):
37 windows = _windows(tour, length)
38 return windows + tuple(window[::-1] for window in windows)
39
40
41def _term(count):
42 return count * log(count) if count else 0.
43
44
45def _entropy(counts):
46 total = sum(counts.values())
47 return log(total) - fsum(map(_term, counts.values())) / total if total else 0.
48
49
50def _replacement_delta(counts, old, new):
51 """Compare entropy numerators using only segments affected by a replacement."""
52 changes = Counter(new)
53 changes.subtract(old)
54 return fsum(_term(counts[segment]) - _term(counts[segment] + change)
55 for segment, change in changes.items() if change)
56
57
58
59def tour_segment_entropy(tours, segment_length=3):
60 """Count each segment in both directions and return its population entropy in nats."""
61 length = _positive_int(segment_length, "segment_length")
62 if length < 2:
63 raise ValueError("A segment needs at least two vertices.")
64 tours = tuple(tuple(tour) for tour in tours)
65 if not tours:
66 return 0.
67 size = len(tours[0])
68 if length > size:
69 raise ValueError("segment_length cannot exceed the number of vertices.")
70 counts = Counter(segment for tour in tours for segment in _segments(_canonical(tour, size), length))
71 return _entropy(counts)
72
73
74
75@dataclass(frozen=True)
77 """The route starts at vertex zero and omits the repeated closing vertex."""
78
79 tour: tuple[int, ...]
80 cost: float
81
82
83
84@dataclass(frozen=True)
86 """Distinct tours, directed segment entropy, and all measured attempts."""
87
88 tours: tuple[TourResult, ...]
89 entropy: float
90 evaluations: int
91
92
93
95 """Generate a biased and a uniform 2-opt child and compare them with their parent.
96
97 :param distances: Square symmetric nonnegative matrix of finite edge costs.
98 :param cost_limit: Inclusive ceiling for each retained tour.
99 :param population_size: Maximum number of distinct tours to retain.
100 :param segment_length: Number of consecutive vertices in a segment.
101 :param seed: Private random stream for parent choice and cut locations.
102 """
103
104 def __init__(self, distances, cost_limit, population_size, *, segment_length=3, seed=0):
105 costs = np.array(distances, dtype=float, copy=True)
106 if (costs.ndim != 2 or costs.shape[0] != costs.shape[1] or len(costs) < 4
107 or not np.isfinite(costs).all() or np.any(costs < 0.) or not np.array_equal(costs, costs.T)):
108 raise ValueError("Provide a symmetric finite nonnegative edge-cost matrix with at least four vertices.")
109 self.population_size = _positive_int(population_size, "population_size")
110 self.segment_length = _positive_int(segment_length, "segment_length")
111 if not 2 <= self.segment_length <= len(costs) or not isfinite(cost_limit) or cost_limit < 0.:
112 raise ValueError("Use a segment length in [2, n] and a finite nonnegative cost limit.")
113 self._costs = costs
114 self.cost_limit, self.seed = float(cost_limit), seed
115
116 def _cost(self, tour):
117 return fsum(self._costs[a, b] for a, b in zip(tour, tour[1:] + tour[:1]))
118
119 def _two_opt(self, tour, rng, frequencies=None):
120 size = len(tour)
121 probability = None
122 if frequencies is not None:
123 starts = [frequencies[segment] for segment in _windows(tour, self.segment_length)]
124 # Every covered edge inherits the frequency of its segment.
125 weights = np.asarray([sum(starts[(edge - offset) % size] for offset in range(self.segment_length - 1))
126 for edge in range(size)], dtype=float)
127 probability = weights / weights.sum()
128 first = int(rng.choice(size, p=probability))
129 second = (first + int(rng.integers(2, size - 1))) % size
130 first, second = sorted((first, second))
131 return _canonical(tour[:first + 1] + tour[first + 1:second + 1][::-1] + tour[second + 1:], size)
132
133
134 def run(self, initial_tours, *, budget):
135 """Return distinct feasible tours and count every evaluated seed or child.
136
137 At least one initial tour must meet the ceiling. A single feasible
138 seed can grow to a larger portfolio as new tours are found.
139 """
140 budget = _positive_int(budget, "budget")
141 rng = np.random.default_rng(self.seed)
142 counts = Counter()
143 tours = {}
144 calls = 0
145 for initial in islice(initial_tours, budget):
146 tour = _canonical(initial, len(self._costs))
147 cost = self._cost(tour)
148 calls += 1
149 if cost <= self.cost_limit and tour not in tours:
150 tours[tour] = cost
151 counts.update(_segments(tour, self.segment_length))
152 if len(tours) == self.population_size:
153 break
154 if not tours:
155 raise ValueError("Supply at least one initial tour satisfying the cost limit within budget.")
156
157 while calls < budget:
158 parent = tuple(tours)[rng.integers(len(tours))]
159 old_segments = _segments(parent, self.segment_length)
160 # Draw both proposals against the same population and parent.
161 proposals = [self._two_opt(parent, rng, counts)]
162 if budget - calls > 1:
163 proposals.append(self._two_opt(parent, rng))
164 growing = len(tours) < self.population_size
165 choice, best_cost = parent, tours[parent]
166 best_segments = old_segments
167 best_delta = -np.inf if growing else 0.
168 for child in proposals:
169 cost = self._cost(child)
170 calls += 1
171 if child not in tours and cost <= self.cost_limit:
172 segments = _segments(child, self.segment_length)
173 delta = _replacement_delta(counts, () if growing else old_segments, segments)
174 if delta > best_delta + 1e-12:
175 choice, best_cost, best_segments, best_delta = child, cost, segments, delta
176 if choice != parent:
177 if not growing:
178 del tours[parent]
179 for segment in old_segments:
180 counts[segment] -= 1
181 if not counts[segment]:
182 del counts[segment]
183 tours[choice] = best_cost
184 counts.update(best_segments)
185
186 return TourPortfolio(tuple(TourResult(tour, cost) for tour, cost in tours.items()), _entropy(counts), calls)
Optimize high-order segment entropy among bounded-cost symmetric tours.
run(self, initial_tours, *, budget)
Evolve an exact-call-bounded portfolio from caller-supplied tours.
_two_opt(self, tour, rng, frequencies=None)
Return a feasible portfolio and its search costs.
Report one canonical tour and its exact cyclic cost.