Hello everyone and welcome. In this post, I’m going to show you how to solve travelling salesman problems (TSP) using 2-opt algorithm in Python with the city locations are imported from Excel file. This method is very simple but very effective. To solve new TSP instances, you just need to update the data in the Excel file. The rest of the Python code can be kept the same.
Here is the format of the data related to city locations in Excel. Please keep in mind that the Excel file and the Python file must be put in the same folder.
If you want some basic information about 2 opt algorithm, please have a look at this page.
Let’s see how it works:
For more videos like this, check my YouTube channel here.
Python Code
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_excel('TSP Data.xlsx',index_col=0)
city_list =np.array(data)
solution = np.arange(city_list.shape[0])
city_locations = ...
plt.scatter(city_list[:,0],city_list[:,1])
plt.plot(city_locations[:,0],city_locations[:,1])
plt.title("Initial solution")
plt.show()
distance_calculation = ...
swap_algorithm = ...
current_best_distance = distance_calculation(solution,city_list)
for swap1 in range(1,len(solution)-2):
for swap2 in range(swap1+1,len(solution)):
new_solution = swap_algorithm(solution,swap1,swap2)
new_distance = distance_calculation(new_solution,city_list)
if new_distance < current_best_distance:
solution = new_solution
current_best_distance = new_distance
plt.figure()
city_locations = ...
plt.scatter(city_list[:,0],city_list[:,1])
plt.plot(city_locations[:,0],city_locations[:,1])
plt.title("Final solution")
plt.show()
print('final solution', solution)
print('best distance: ', distance_calculation(solution,city_list))
.
.
.
Sorry! This is only a half of the Python code.
Notice: It would take you from 1 to 3 hours to re-type the Python code yourself; or with just €2.99 (the cost of a cup of coffee), you can download/copy the whole Python code within 2 minutes. It’s your choice to make.
Original price is €4.99 but today it’s only €2.99 (save €2 today – available for a limited time only)
Download the whole Python code here (Membership Code ID: 023)
No need to build the Python code from scratch because it’s very time-consuming. My idol, Jim Rohn, once said: “Time is more value than money. You can get more money, but you cannot get more time”. If you think this code can be used in your research/teaching work, you should download it and then customize/modify/apply it to your work, without any obligation of citing the original source if you don’t want. However, redistribution (i.e., downloading the code/script here and then making it available on another site on the Internet) is strictly prohibited.
If you have any question or problem, please contact Dr. Panda by email: learnwithpanda2018@gmail.com
Thank you very much and good luck with your research!