I am trying to solve TSP using the nearest algorithm, but I got stuck at the IndexError: boolean index did not match indexed array along dimension 0; dimension is 1 but corresponding boolean dimension is 38. For my algorithm I'm using a distance matrix 38x38 that was transformed from .tsp format.
import numpy as np
import tsplib95
import networkx
# load the tsplib problem
problem = tsplib95.load('dj38.tsp')
# convert into a networkx.Graph
graph = problem.get_graph()
# convert into a numpy distance matrix
distance_matrix = networkx.to_numpy_matrix(graph)
def NN(A, start):
"""Nearest neighbor algorithm.
A is an NxN array indicating distance between N locations
start is the index of the starting location
Returns the path and cost of the found solution
"""
path = [start]
cost = 0
n = A.shape[0]
mask = np.ones(n, dtype=bool) # boolean values indicating which locations have not been visited
mask[start] = False
for i in range(n-1):
last = path[-1]
next_ind = np.argmin(A[last][mask]) # find minimum of remaining locations
next_loc = np.arange(n)[mask][next_ind] # convert to original location
path.append(next_loc)
mask[next_loc] = False
cost += A[last, next_loc]
return path, cost
#print(distance_matrix)
#print(distance_matrix.shape)
print(NN(distance_matrix,1))
the distance matrix is 38x38 and looks like this
[[ 0. 291. 794. ... 1852. 1625. 1858.]
[ 291. 0. 513. ... 1599. 1413. 1649.]
[ 794. 513. 0. ... 1331. 1288. 1514.]
...
[1852. 1599. 1331. ... 0. 441. 444.]
[1625. 1413. 1288. ... 441. 0. 236.]
[1858. 1649. 1514. ... 444. 236. 0.]]
and the error I'm getting is the following
Traceback (most recent call last):
File "/Users/Irina/PycharmProjects/pythonProject/main.py", line 51, in <module>
print(NN(distance_matrix,1))
^^^^^^^^^^^^^^^^^^^^^
File "/Users/Irina/PycharmProjects/pythonProject/main.py", line 36, in NN
next_ind = np.argmin(A[last][mask]) # find minimum of remaining locations
~~~~~~~^^^^^^
File "/Users/Irina/PycharmProjects/pythonProject/venv/lib/python3.11/site-packages/numpy/matrixlib/defmatrix.py", line 193, in __getitem__
out = N.ndarray.__getitem__(self, index)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
IndexError: boolean index did not match indexed array along dimension 0; dimension is 1 but corresponding boolean dimension is 38
Any help will be much appreciated. Thanks.