Skip to content

Commit df56f38

Browse files
committed
Update TSP generator to use Roll Symbol.
Roll symbol recently implemented here: #430.
1 parent d1b5555 commit df56f38

File tree

1 file changed

+9
-21
lines changed

1 file changed

+9
-21
lines changed

dwave/optimization/generators.py

Lines changed: 9 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
import numpy as np
2323
import numpy.typing
2424

25-
from dwave.optimization.mathematical import add, logical_or, maximum, where
25+
from dwave.optimization.mathematical import add, logical_or, maximum, roll, where
2626
from dwave.optimization.model import Model
2727

2828
__all__ = [
@@ -1079,26 +1079,14 @@ def traveling_salesperson(distance_matrix: numpy.typing.ArrayLike,
10791079
# Add the constants
10801080
DISTANCE_MATRIX = tsp_model.constant(distance_matrix)
10811081

1082-
# The objective is to minimize the distance traveled.
1083-
# The first elements of the pairs of cities traveled between are the
1084-
# permuted indices excluding the last and the second elements are these
1085-
# indices excluding the first.
1086-
1087-
# Python represents this slicing of a list with slice indices ``[:-1]`` and ``[1:]``,
1088-
# respectively, because Python slices are defined in the format of a
1089-
# mathematical interval (see https://en.wikipedia.org/wiki/Interval_(mathematics))
1090-
# [a, b) and list indices start at zero. For example, ``ordered_cities[:-1]``
1091-
# excludes the last element of the sliced list.
1092-
1093-
# Adding the return to the city of origin add the distance between the first
1094-
# element of the list, or slice ``[0]``, and the last city visited, or slice
1095-
# ``[-1]``
1096-
1097-
itinerary = DISTANCE_MATRIX[ordered_cities[:-1], ordered_cities[1:]]
1098-
return_to_origin = DISTANCE_MATRIX[ordered_cities[-1], ordered_cities[0]]
1099-
1100-
# Sum the distances along the full route traveled.
1101-
travel_distance = itinerary.sum() + return_to_origin.sum()
1082+
# Sum the distances along the full route traveled using
1083+
# :func:`dwave.optimization.mathematical.roll` function.
1084+
#
1085+
# With :math:`shift=-1`, this ensures that the distance between the
1086+
# :math:`i`th city and the :math:`(i+1)`th city on the route (where
1087+
# addition is taken modulo :math:`num_cities`) is included for
1088+
# :math:`i \in [0, num_cities-1]`.
1089+
travel_distance = DISTANCE_MATRIX[ordered_cities, roll(ordered_cities, shift=-1)].sum()
11021090

11031091
# Minimize the total travel distance.
11041092
tsp_model.minimize(travel_distance)

0 commit comments

Comments
 (0)