I have been working on an implementation of a solution for the TSP based on:
https://github.com/lmarti/evolutionary-computation-course/blob/master/AEC.03%20-%20Solving%20the%20TSP%20with%20GAs.ipynb
So for my implementation I have an initial list of cities, called 'cities', and I represent each individual as a list of indices that correspond to the position of each city in the initial list. That means that for generating new individuals the mechanism is according to the numpy's random.permutation function. But there are two cases, one is when the starting and ending point are not fixed so we declare the mechanisms in the toolbox as follows:
toolbox.register("indices", numpy.random.permutation, len(cities))
toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.indices)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
But, just in case that the first and last locations of the initial list of 'cities' are fixed then you need to permutate through the rest of the locations except for the first and the last. So you declare the mechanisms like this:
permutableList = []
for row in range(1, len(cities)-1):
permutableList.append(row-1)
toolbox.register("indices", numpy.random.permutation, permutableList)
toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.indices)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
Then you just need to change the evaluation function to include the first and the last points of the initial list of "cities", as follows:
def create_tour(individual):
listOfLocations = [list(cities)[e+1] for e in individual]
# Adding first and last points to the tour
listOfLocations.insert(0, cities[0])
listOfLocations.append(cities[len(cities)-1])
return listOfLocations
And then you calculate the distance based on the listOfLocations list.