QDpy
Loading...
Searching...
No Matches
traveling_thief.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Optimize packed items exactly for each measured tour."""
7
8from dataclasses import dataclass
9from itertools import islice
10from math import fsum, isfinite
11from operator import index
12
13import numpy as np
14
15from qdpy.containers import CVTGrid, Grid
16from qdpy.phenotype import Features, Fitness, Individual
17
18from .modern import _positive_int
19
20__all__ = ["TravelingThiefItem", "TravelingThiefProblem", "TravelingThiefSolution",
21 "TravelingThiefMAPElites", "TravelingThiefResult"]
22
23
24
25@dataclass(frozen=True)
27 """City zero is the depot. Item indices are their positions in the input sequence."""
28
29 city: int
30 weight: int
31 profit: float
32
33 def __post_init__(self):
34 object.__setattr__(self, "city", index(self.city))
35 object.__setattr__(self, "weight", _positive_int(self.weight, "item weight"))
36 if self.city < 0 or not 0. <= self.profit < np.inf:
37 raise ValueError("Use a nonnegative city index and a finite nonnegative profit.")
38
39
40
41@dataclass(frozen=True)
43 """Tours start at the depot and close implicitly. Packing uses input item IDs."""
44
45 tour: tuple[int, ...]
46 items: tuple[int, ...]
47 tour_length: float
48 travel_time: float
49 weight: int
50 profit: float
51 fitness: float
52
53
54
55@dataclass(frozen=True)
57 """Count each packing solve and each feasible item-addition DP transition."""
58
59 archive: Grid
60 tour_evaluations: int
61 packing_transitions: int
62 archive_updates: int
63 out_of_domain: int
64
65
66
68 """Travel speed decreases linearly with the current carried weight.
69
70 Pick up items before leaving their cities and include the final
71 edge back to the depot. The objective maximizes packed profit
72 minus the rental cost of travel time. Both tour directions retain
73 their own load order.
74
75 :param distances: Square finite nonnegative distance matrix.
76 :param items: Sequence of TravelingThiefItem objects.
77 :param capacity: Positive integer weight capacity.
78 :param min_speed: Speed at capacity.
79 :param max_speed: Speed when empty.
80 :param rent: Nonnegative cost per travel-time unit.
81 """
82
83 def __init__(self, distances, items, capacity, *, min_speed=.1, max_speed=1., rent=1.):
84 costs = np.array(distances, dtype=float, copy=True)
85 if (costs.ndim != 2 or len(costs) < 2 or costs.shape[0] != costs.shape[1]
86 or not np.isfinite(costs).all() or np.any(costs < 0.)):
87 raise ValueError("Give a finite nonnegative square distance matrix for at least two cities.")
88 if not 0. < min_speed <= max_speed < np.inf or not 0. <= rent < np.inf:
89 raise ValueError("Use finite positive speeds and a finite nonnegative rent.")
90 self.capacity = _positive_int(capacity, "capacity")
91 self.items = tuple(items)
92 self.cities = len(costs)
93 if any(not isinstance(item, TravelingThiefItem) or item.city >= self.cities for item in self.items):
94 raise ValueError("Every item must be a TravelingThiefItem at a known city.")
95 self._costs = costs
96 self.min_speed, self.max_speed, self.rent = min_speed, max_speed, rent
97 by_city = [[] for _ in range(self.cities)]
98 for i, item in enumerate(self.items):
99 by_city[item.city].append(i)
100 self._by_city = tuple(map(tuple, by_city))
101
102 def _tour(self, tour):
103 order = tuple(map(index, tour))
104 if len(order) != self.cities or set(order) != set(range(self.cities)):
105 raise ValueError("Visit every city exactly once and omit the repeated depot.")
106 start = order.index(0)
107 return order[start:] + order[:start]
108
109 def _time(self, edge, load):
110 remaining = (self.capacity - load) / self.capacity
111 speed = self.min_speed + (self.max_speed - self.min_speed) * remaining
112 return edge / speed
113
114 def _legs(self, tour):
115 for city, successor in zip(tour, tour[1:] + tour[:1], strict=True):
116 yield self._by_city[city], float(self._costs[city, successor])
117
118
121 def evaluate(self, tour, packing):
122 """Return the score and archive descriptors for the supplied item IDs."""
123 tour = self._tour(tour)
124 items = tuple(sorted(map(index, packing)))
125 selected = set(items)
126 if len(selected) != len(items) or any(not 0 <= i < len(self.items) for i in items):
127 raise ValueError("Packing must contain distinct known item IDs.")
128 weight = sum(self.items[i].weight for i in items)
129 if weight > self.capacity:
130 raise ValueError("Packing exceeds capacity.")
131 profit = fsum(self.items[i].profit for i in items)
132 load = 0
133 lengths, times = [], []
134 for ids, edge in self._legs(tour):
135 load += sum(self.items[i].weight for i in ids if i in selected)
136 lengths.append(edge)
137 times.append(self._time(edge, load))
138 length, duration = fsum(lengths), fsum(times)
139 fitness = profit - self.rent * duration
140 if not all(map(isfinite, (fitness, duration, length))):
141 raise ValueError("Route lengths, travel times, and fitness must be finite.")
142 return TravelingThiefSolution(tour, items, length, duration, weight, profit, fitness)
143
144
147 def solve_packing(self, tour):
148 """Return (solution, item_transitions) for one exact packing solve.
149
150 Keep the best partial net profit for each reachable weight.
151 Apply the next travel cost once all items at the current city
152 have been considered. Count each candidate item addition that
153 stays within capacity, including candidates discarded by the DP.
154 """
155 tour = self._tour(tour)
156 states = {0: (0., ())}
157 transitions = 0
158 for ids, edge in self._legs(tour):
159 for i in ids:
160 item = self.items[i]
161 for load, (score, packing) in tuple(states.items()):
162 new_load = load + item.weight
163 if new_load > self.capacity:
164 continue
165 transitions += 1
166 candidate = score + item.profit
167 if new_load not in states or candidate > states[new_load][0]:
168 states[new_load] = (candidate, (*packing, i))
169 if self.rent:
170 states = {load: (score - self.rent * self._time(edge, load), packing)
171 for load, (score, packing) in states.items()}
172 _, (_, packing) = max(states.items(), key=lambda row: (row[1][0], -row[0]))
173 return self.evaluate(tour, packing), transitions
174
175
176
178 """Store the highest measured net profit per tour-length/item-profit cell.
179
180 This small-instance bilevel variant uses 2-opt mutation and exact
181 packing. A tour evaluation includes one packing solve and one
182 measured route-and-packing pair. An out-of-domain result still
183 spends its tour evaluation and packing work.
184
185 :param problem: TravelingThiefProblem with integer item weights.
186 :param archive: Empty parentless maximizing scalar Grid or CVTGrid
187 with descriptors for unloaded tour length and item profit.
188 :param initial_tours: Number of random initial route evaluations.
189 :param seed: Private seed for initialization and 2-opt.
190 """
191
192 def __init__(self, problem, archive, *, initial_tours=8, seed=0):
193 if not isinstance(problem, TravelingThiefProblem):
194 raise TypeError("Provide a TravelingThiefProblem.")
195 if (type(archive) not in (Grid, CVTGrid) or len(archive) or archive.parents
196 or archive.max_items_per_bin != 1 or archive.discard_random_on_bin_overload
197 or archive.fitness_domain is None or len(archive.fitness_domain) != 1
198 or len(archive.features_domain) != 2
199 or archive.fitness_score_names or archive.features_score_names):
200 raise ValueError("Use an empty parentless scalar best-only grid with two descriptors.")
201 weights = archive.fitness_weights
202 if weights is not None and (len(weights) != 1 or not 0. < weights[0] < np.inf):
203 raise ValueError("The archive must maximize net profit.")
204 self.problem, self.archive = problem, archive
205 self._weights = (1.,) if weights is None else tuple(weights)
206 self.initial_tours = _positive_int(initial_tours, "initial_tours")
207 self.seed = seed
208
209
210 def solution_for(self, elite):
211 """Recover the tour and packed items stored in the native archive genotype."""
212 split = self.problem.cities
213 return self.problem.evaluate(elite[:split], elite[split:])
214
215
219 def run(self, budget, *, seed_tours=()):
220 """Optionally measure caller-supplied tours before random starts and offspring."""
221 if self.archive:
222 raise ValueError("Use an empty archive for each Traveling Thief run.")
223 budget = _positive_int(budget, "budget")
224 rng = np.random.default_rng(self.seed)
225 seeds = iter(islice(seed_tours, budget))
226 transitions = updates = outside = 0
227 cities = self.problem.cities
228 for attempt in range(budget):
229 tour = next(seeds, None)
230 if tour is None:
231 if attempt < self.initial_tours or not self.archive or cities < 3:
232 tour = (0, *map(int, rng.permutation(np.arange(1, cities))))
233 else:
234 parent = self.archive[int(rng.integers(len(self.archive)))][:cities]
235 start, end = sorted(rng.choice(np.arange(1, cities), 2, replace=False))
236 tour = (*parent[:start], *reversed(parent[start:end + 1]), *parent[end + 1:])
237 solution, count = self.problem.solve_packing(tour)
238 transitions += count
239 features = solution.tour_length, solution.profit
240 fitness = (solution.fitness,)
241 if (self.archive.in_bounds(features, self.archive.features_domain)
242 and self.archive.in_bounds(fitness, self.archive.fitness_domain)):
243 if self.archive.free >= 1 or self.archive.solutions[self.archive.index_grid(features)]:
244 before = self.archive.nb_added
245 self.archive.add(Individual((*solution.tour, *solution.items),
246 fitness=Fitness(fitness, weights=self._weights),
247 features=Features(features)))
248 updates += self.archive.nb_added - before
249 else:
250 outside += 1
251 return TravelingThiefResult(self.archive, budget, transitions, updates, outside)
An available item with a city, a positive integer weight and fixed profit.
Evolve depot-anchored tours with 2-opt and exact inner packing.
run(self, budget, *, seed_tours=())
Run the bilevel search with the specified number of tour evaluations.
solution_for(self, elite)
Return the exact measured design associated with a stored elite.
Score a route and packing and solve exact packing for a fixed tour.
evaluate(self, tour, packing)
Measure the true travel cost and reward for a feasible route and packing.
solve_packing(self, tour)
Maximize net fitness for a fixed tour using sparse weight states.
A measured route-and-packing archive with separate outer and inner work counts.
A feasible tour and packing with measured time, profit, and score.
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405