用python繪制旅行商問題路線圖
最近在研究TSP問題,然后在最后需要繪制旅游路線,自己摸索了一會兒最終整理出來供自己將來備用【防止自己又忘記】
附TSP程序,備注已經很詳細了,應該完全可以看懂!
import numpy as np
import matplotlib.pyplot as plt
import pdb
"旅行商問題 ( TSP , Traveling Salesman Problem )"
coordinates = np.array([[66.83,25.36], [61.95,26.34], [40,44.39], [24.39,14.63], [17.07,22.93], [22.93,76.1 ],
[51.71,94.14], [87.32,65.36], [68.78,52.19], [84.88,36.09], [50,30 ],[40,20 ],[25,26]])
#得到距離矩陣的函數
def getdistmat(coordinates):
num = coordinates.shape[0] #52個坐標點
distmat = np.zeros((num,num)) #52X52距離矩陣
for i in range(num):
for j in range(i,num):
distmat[i][j] = distmat[j][i]=np.linalg.norm((coordinates[i]-coordinates[j]), ord=2) # 求2范數,即距離
# print('距離矩陣', distmat)
return distmat # 對稱距離矩陣
# 初始化參數
def initpara():
alpha = 0.99
t = (1,100) # 元祖
markovlen = 1000
return alpha,t,markovlen
num = coordinates.shape[0]
distmat = getdistmat(coordinates) #得到距離矩陣
solutionnew = np.arange(num) # [0,1,...,num-1],即新路線圖
#valuenew = np.max(num)
solutioncurrent = solutionnew.copy() # [0,1,...,num-1],即當前路線圖
valuecurrent = 99000 # np.max這樣的源代碼可能同樣是因為版本問題被當做函數不能正確使用,應取一個較大值作為初始值
# print(valuecurrent)
solutionbest = solutionnew.copy()
valuebest = 99000 # np.max
alpha,t2,markovlen = initpara()
t = t2[1] # t=100
t_min = t2[0]
result = [] # 記錄迭代過程中的最優距離解
while t > t_min:
for i in np.arange(markovlen):
# 下面的兩交換和三角換是兩種擾動方式,用于產生新解
if np.random.rand() > 0.5: # 交換路徑中的這2個節點的順序
# np.random.rand()產生[0, 1)區間的均勻隨機數
while True: # 產生兩個不同的隨機數
loc1 = np.int(np.ceil(np.random.rand()*(num-1))) # np.ceil表示向大于等于該值的向上取整;np.floor:向下取整
loc2 = np.int(np.ceil(np.random.rand()*(num-1)))
## print(loc1,loc2)
if loc1 != loc2:
break
solutionnew[loc1],solutionnew[loc2] = solutionnew[loc2],solutionnew[loc1]
else: #三交換
while True:
loc1 = np.int(np.ceil(np.random.rand()*(num-1)))
loc2 = np.int(np.ceil(np.random.rand()*(num-1)))
loc3 = np.int(np.ceil(np.random.rand()*(num-1)))
if((loc1 != loc2)&(loc2 != loc3)&(loc1 != loc3)):
break
# 下面的三個判斷語句使得loc1
loc2:
loc1,loc2 = loc2,loc1
if loc2 > loc3:
loc2,loc3 = loc3,loc2
if loc1 > loc2:
loc1,loc2 = loc2,loc1
#下面的三行代碼將[loc1,loc2)區間的數據插入到loc3之后
tmplist = solutionnew[loc1:loc2].copy()
solutionnew[loc1:loc3-loc2+1+loc1] = solutionnew[loc2:loc3+1].copy()
solutionnew[loc3-loc2+1+loc1:loc3+1] = tmplist.copy()
valuenew = 0
for i in range(num-1):
valuenew += distmat[solutionnew[i]][solutionnew[i+1]]
valuenew += distmat[solutionnew[0]][solutionnew[num-1]]
# print (valuenew)
if valuenew
< valuebest:
valuebest = valuenew
solutionbest = solutionnew.copy()
else:#按一定的概率接受該解
if np.random.rand() < np.exp(-(valuenew-valuecurrent)/t):
valuecurrent = valuenew
solutioncurrent = solutionnew.copy()
else:
solutionnew = solutioncurrent.copy()
t = alpha*t
result.append(valuebest)
# print(t) #程序運行時間較長,打印t來監視程序進展速度
#用來顯示結果
# plt.plot(
plot_x_set = []
plot_y_set = []
print(solutioncurrent+1) # 輸出最優路徑圖
for i in solutioncurrent:
# plt.plot(coordinates[i])
plot_x_set.append(coordinates[i][0])
plot_y_set.append(coordinates[i][1])
plt.plot(plot_x_set,plot_y_set,'r')
plt.scatter(plot_x_set,plot_y_set,)
for i,txt in enumerate(solutionnew+1): # 標注每個點的序號
plt.annotate(txt, (plot_x_set[i],plot_y_set[i]))
# 首尾2個點的連線
x = [plot_x_set[0],plot_x_set[-1]]
y = [plot_y_set[0],plot_y_set[-1]]
plt.plot(x, y, 'k') # 用黑色標識
plt.show()
# 繪制迭代次數與最短距離圖片
plt.plot(np.array(result))
plt.ylabel("bestvalue")
plt.xlabel("t")
plt.show()
plot_x_set = []
plot_y_set = []
print(solutioncurrent+1) # 輸出最優路徑圖
for i in solutioncurrent:
# plt.plot(coordinates[i])
plot_x_set.append(coordinates[i][0])
plot_y_set.append(coordinates[i][1])
plt.plot(plot_x_set,plot_y_set,'r')
plt.scatter(plot_x_set,plot_y_set,)
for i,txt in enumerate(solutionnew+1): # 標注每個點的序號
plt.annotate(txt, (plot_x_set[i],plot_y_set[i]))
# 首尾2個點的連線
x = [plot_x_set[0],plot_x_set[-1]]
y = [plot_y_set[0],plot_y_set[-1]]
plt.plot(x, y, 'k') # 用黑色標識
plt.show()
如果去掉TSP實際背景,單純繪制路線圖的并標注各個點的序號的話,代碼如下:
import numpy as np
import matplotlib.pyplot as plt
x = [2.3, 4.5, 3, 7, 6.5, 4, 5.3]
y = [5, 4, 7, 5, 5.3, 5.5, 6.2]
n = np.arange(len(x))
plt.scatter(x, y, c='r')
for i, txt in enumerate(n):
plt.annotate(txt, (x[i], y[i]))
plt.show()
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
