|
22 | 22 | import numpy as np |
23 | 23 | import numpy.typing |
24 | 24 |
|
25 | | -from dwave.optimization.mathematical import add, logical_or, maximum, where |
| 25 | +from dwave.optimization.mathematical import add, logical_or, maximum, roll, where |
26 | 26 | from dwave.optimization.model import Model |
27 | 27 |
|
28 | 28 | __all__ = [ |
@@ -1079,26 +1079,14 @@ def traveling_salesperson(distance_matrix: numpy.typing.ArrayLike, |
1079 | 1079 | # Add the constants |
1080 | 1080 | DISTANCE_MATRIX = tsp_model.constant(distance_matrix) |
1081 | 1081 |
|
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() |
1102 | 1090 |
|
1103 | 1091 | # Minimize the total travel distance. |
1104 | 1092 | tsp_model.minimize(travel_distance) |
|
0 commit comments