6"""Evolve a bounded portfolio of tours under a common cost ceiling."""
8from collections
import Counter
9from dataclasses
import dataclass
10from itertools
import islice
11from math
import fsum, isfinite, log
12from operator
import index
16from .modern
import _positive_int
18__all__ = [
"EntropyTourSearch",
"TourPortfolio",
"TourResult",
"tour_segment_entropy"]
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)
31def _windows(tour, length):
32 extended = tour + tour[:length - 1]
33 return tuple(extended[start:start + length]
for start
in range(len(tour)))
36def _segments(tour, length):
37 windows = _windows(tour, length)
38 return windows + tuple(window[::-1]
for window
in windows)
42 return count * log(count)
if count
else 0.
46 total = sum(counts.values())
47 return log(total) - fsum(map(_term, counts.values())) / total
if total
else 0.
50def _replacement_delta(counts, old, new):
51 """Compare entropy numerators using only segments affected by a replacement."""
52 changes = Counter(new)
54 return fsum(_term(counts[segment]) - _term(counts[segment] + change)
55 for segment, change
in changes.items()
if change)
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")
63 raise ValueError(
"A segment needs at least two vertices.")
64 tours = tuple(tuple(tour)
for tour
in tours)
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)
75@dataclass(frozen=True)
77 """The route starts at vertex zero and omits the repeated closing vertex."""
84@dataclass(frozen=True)
86 """Distinct tours, directed segment entropy, and all measured attempts."""
88 tours: tuple[TourResult, ...]
95 """Generate a biased and a uniform 2-opt child and compare them with their parent.
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.
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.")
116 def _cost(self, tour):
117 return fsum(self.
_costs[a, b]
for a, b
in zip(tour, tour[1:] + tour[:1]))
119 def _two_opt(self, tour, rng, frequencies=None):
122 if frequencies
is not None:
123 starts = [frequencies[segment]
for segment
in _windows(tour, self.
segment_length)]
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)
134 def run(self, initial_tours, *, budget):
135 """Return distinct feasible tours and count every evaluated seed or child.
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.
140 budget = _positive_int(budget,
"budget")
141 rng = np.random.default_rng(self.
seed)
145 for initial
in islice(initial_tours, budget):
146 tour = _canonical(initial, len(self.
_costs))
147 cost = self.
_cost(tour)
149 if cost <= self.
cost_limit and tour
not in tours:
155 raise ValueError(
"Supply at least one initial tour satisfying the cost limit within budget.")
157 while calls < budget:
158 parent = tuple(tours)[rng.integers(len(tours))]
161 proposals = [self.
_two_opt(parent, rng, counts)]
162 if budget - calls > 1:
163 proposals.append(self.
_two_opt(parent, rng))
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)
171 if child
not in tours
and cost <= self.
cost_limit:
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
179 for segment
in old_segments:
181 if not counts[segment]:
183 tours[choice] = best_cost
184 counts.update(best_segments)
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.