# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Bilevel MAP-Elites for routing and load-dependent packing.
# @see https://arxiv.org/html/2112.08627
"""Optimize packed items exactly for each measured tour."""
from dataclasses import dataclass
from itertools import islice
from math import fsum, isfinite
from operator import index
import numpy as np
from qdpy.containers import CVTGrid, Grid
from qdpy.phenotype import Features, Fitness, Individual
from .modern import _positive_int
__all__ = ["TravelingThiefItem", "TravelingThiefProblem", "TravelingThiefSolution",
"TravelingThiefMAPElites", "TravelingThiefResult"]
## @brief An available item with a city, a positive integer weight and fixed profit.
[docs]
@dataclass(frozen=True)
class TravelingThiefItem:
"""City zero is the depot. Item indices are their positions in the input sequence."""
city: int
weight: int
profit: float
def __post_init__(self):
object.__setattr__(self, "city", index(self.city))
object.__setattr__(self, "weight", _positive_int(self.weight, "item weight"))
if self.city < 0 or not 0. <= self.profit < np.inf:
raise ValueError("Use a nonnegative city index and a finite nonnegative profit.")
## @brief A feasible tour and packing with measured time, profit, and score.
[docs]
@dataclass(frozen=True)
class TravelingThiefSolution:
"""Tours start at the depot and close implicitly. Packing uses input item IDs."""
tour: tuple[int, ...]
items: tuple[int, ...]
tour_length: float
travel_time: float
weight: int
profit: float
fitness: float
## @brief A measured route-and-packing archive with separate outer and inner work counts.
[docs]
@dataclass(frozen=True)
class TravelingThiefResult:
"""Count each packing solve and each feasible item-addition DP transition."""
archive: Grid
tour_evaluations: int
packing_transitions: int
archive_updates: int
out_of_domain: int
## @brief Score a route and packing and solve exact packing for a fixed tour.
[docs]
class TravelingThiefProblem:
"""Travel speed decreases linearly with the current carried weight.
Pick up items before leaving their cities and include the final
edge back to the depot. The objective maximizes packed profit
minus the rental cost of travel time. Both tour directions retain
their own load order.
:param distances: Square finite nonnegative distance matrix.
:param items: Sequence of TravelingThiefItem objects.
:param capacity: Positive integer weight capacity.
:param min_speed: Speed at capacity.
:param max_speed: Speed when empty.
:param rent: Nonnegative cost per travel-time unit.
"""
def __init__(self, distances, items, capacity, *, min_speed=.1, max_speed=1., rent=1.):
costs = np.array(distances, dtype=float, copy=True)
if (costs.ndim != 2 or len(costs) < 2 or costs.shape[0] != costs.shape[1]
or not np.isfinite(costs).all() or np.any(costs < 0.)):
raise ValueError("Give a finite nonnegative square distance matrix for at least two cities.")
if not 0. < min_speed <= max_speed < np.inf or not 0. <= rent < np.inf:
raise ValueError("Use finite positive speeds and a finite nonnegative rent.")
self.capacity = _positive_int(capacity, "capacity")
self.items = tuple(items)
self.cities = len(costs)
if any(not isinstance(item, TravelingThiefItem) or item.city >= self.cities for item in self.items):
raise ValueError("Every item must be a TravelingThiefItem at a known city.")
self._costs = costs
self.min_speed, self.max_speed, self.rent = min_speed, max_speed, rent
by_city = [[] for _ in range(self.cities)]
for i, item in enumerate(self.items):
by_city[item.city].append(i)
self._by_city = tuple(map(tuple, by_city))
def _tour(self, tour):
order = tuple(map(index, tour))
if len(order) != self.cities or set(order) != set(range(self.cities)):
raise ValueError("Visit every city exactly once and omit the repeated depot.")
start = order.index(0)
return order[start:] + order[:start]
def _time(self, edge, load):
remaining = (self.capacity - load) / self.capacity
speed = self.min_speed + (self.max_speed - self.min_speed) * remaining
return edge / speed
def _legs(self, tour):
for city, successor in zip(tour, tour[1:] + tour[:1], strict=True):
yield self._by_city[city], float(self._costs[city, successor])
## @brief Measure the true travel cost and reward for a feasible route and packing.
# @param tour Permutation of all cities. The final leg returns to the depot.
# @param packing Distinct zero-based item IDs from the input sequence.
[docs]
def evaluate(self, tour, packing):
"""Return the score and archive descriptors for the supplied item IDs."""
tour = self._tour(tour)
items = tuple(sorted(map(index, packing)))
selected = set(items)
if len(selected) != len(items) or any(not 0 <= i < len(self.items) for i in items):
raise ValueError("Packing must contain distinct known item IDs.")
weight = sum(self.items[i].weight for i in items)
if weight > self.capacity:
raise ValueError("Packing exceeds capacity.")
profit = fsum(self.items[i].profit for i in items)
load = 0
lengths, times = [], []
for ids, edge in self._legs(tour):
load += sum(self.items[i].weight for i in ids if i in selected)
lengths.append(edge)
times.append(self._time(edge, load))
length, duration = fsum(lengths), fsum(times)
fitness = profit - self.rent * duration
if not all(map(isfinite, (fitness, duration, length))):
raise ValueError("Route lengths, travel times, and fitness must be finite.")
return TravelingThiefSolution(tour, items, length, duration, weight, profit, fitness)
## @brief Maximize net fitness for a fixed tour using sparse weight states.
# @param tour Permutation of all cities.
# @return The best route-packing pair and number of feasible item additions considered.
[docs]
def solve_packing(self, tour):
"""Return (solution, item_transitions) for one exact packing solve.
Keep the best partial net profit for each reachable weight.
Apply the next travel cost once all items at the current city
have been considered. Count each candidate item addition that
stays within capacity, including candidates discarded by the DP.
"""
tour = self._tour(tour)
states = {0: (0., ())}
transitions = 0
for ids, edge in self._legs(tour):
for i in ids:
item = self.items[i]
for load, (score, packing) in tuple(states.items()):
new_load = load + item.weight
if new_load > self.capacity:
continue
transitions += 1
candidate = score + item.profit
if new_load not in states or candidate > states[new_load][0]:
states[new_load] = (candidate, (*packing, i))
if self.rent:
states = {load: (score - self.rent * self._time(edge, load), packing)
for load, (score, packing) in states.items()}
_, (_, packing) = max(states.items(), key=lambda row: (row[1][0], -row[0]))
return self.evaluate(tour, packing), transitions
## @brief Evolve depot-anchored tours with 2-opt and exact inner packing.
[docs]
class TravelingThiefMAPElites:
"""Store the highest measured net profit per tour-length/item-profit cell.
This small-instance bilevel variant uses 2-opt mutation and exact
packing. A tour evaluation includes one packing solve and one
measured route-and-packing pair. An out-of-domain result still
spends its tour evaluation and packing work.
:param problem: TravelingThiefProblem with integer item weights.
:param archive: Empty parentless maximizing scalar Grid or CVTGrid
with descriptors for unloaded tour length and item profit.
:param initial_tours: Number of random initial route evaluations.
:param seed: Private seed for initialization and 2-opt.
"""
def __init__(self, problem, archive, *, initial_tours=8, seed=0):
if not isinstance(problem, TravelingThiefProblem):
raise TypeError("Provide a TravelingThiefProblem.")
if (type(archive) not in (Grid, CVTGrid) or len(archive) or archive.parents
or archive.max_items_per_bin != 1 or archive.discard_random_on_bin_overload
or archive.fitness_domain is None or len(archive.fitness_domain) != 1
or len(archive.features_domain) != 2
or archive.fitness_score_names or archive.features_score_names):
raise ValueError("Use an empty parentless scalar best-only grid with two descriptors.")
weights = archive.fitness_weights
if weights is not None and (len(weights) != 1 or not 0. < weights[0] < np.inf):
raise ValueError("The archive must maximize net profit.")
self.problem, self.archive = problem, archive
self._weights = (1.,) if weights is None else tuple(weights)
self.initial_tours = _positive_int(initial_tours, "initial_tours")
self.seed = seed
## @brief Return the exact measured design associated with a stored elite.
[docs]
def solution_for(self, elite):
"""Recover the tour and packed items stored in the native archive genotype."""
split = self.problem.cities
return self.problem.evaluate(elite[:split], elite[split:])
## @brief Run the bilevel search with the specified number of tour evaluations.
# @param budget Number of tour evaluations and exact packing solves.
# @param seed_tours Optional iterable of tours to evaluate first within the budget.
# @return Reporting archive, search costs, and archive admission counters.
[docs]
def run(self, budget, *, seed_tours=()):
"""Optionally measure caller-supplied tours before random starts and offspring."""
if self.archive:
raise ValueError("Use an empty archive for each Traveling Thief run.")
budget = _positive_int(budget, "budget")
rng = np.random.default_rng(self.seed)
seeds = iter(islice(seed_tours, budget))
transitions = updates = outside = 0
cities = self.problem.cities
for attempt in range(budget):
tour = next(seeds, None)
if tour is None:
if attempt < self.initial_tours or not self.archive or cities < 3:
tour = (0, *map(int, rng.permutation(np.arange(1, cities))))
else:
parent = self.archive[int(rng.integers(len(self.archive)))][:cities]
start, end = sorted(rng.choice(np.arange(1, cities), 2, replace=False))
tour = (*parent[:start], *reversed(parent[start:end + 1]), *parent[end + 1:])
solution, count = self.problem.solve_packing(tour)
transitions += count
features = solution.tour_length, solution.profit
fitness = (solution.fitness,)
if (self.archive.in_bounds(features, self.archive.features_domain)
and self.archive.in_bounds(fitness, self.archive.fitness_domain)):
if self.archive.free >= 1 or self.archive.solutions[self.archive.index_grid(features)]:
before = self.archive.nb_added
self.archive.add(Individual((*solution.tour, *solution.items),
fitness=Fitness(fitness, weights=self._weights),
features=Features(features)))
updates += self.archive.nb_added - before
else:
outside += 1
return TravelingThiefResult(self.archive, budget, transitions, updates, outside)