用python繪制旅行商問(wèn)題路線圖
最近在研究TSP問(wèn)題,然后在最后需要繪制旅游路線,自己摸索了一會(huì)兒最終整理出來(lái)供自己將來(lái)備用【防止自己又忘記】
附TSP程序,備注已經(jīng)很詳細(xì)了,應(yīng)該完全可以看懂!
import numpy as np
import matplotlib.pyplot as plt
import pdb
"旅行商問(wèn)題 ( 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]])
#得到距離矩陣的函數(shù)
def getdistmat(coordinates):
num = coordinates.shape[0] #52個(gè)坐標(biāo)點(diǎn)
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范數(shù),即距離
# print('距離矩陣', distmat)
return distmat # 對(duì)稱距離矩陣
# 初始化參數(shù)
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],即當(dāng)前路線圖
valuecurrent = 99000 # np.max這樣的源代碼可能同樣是因?yàn)榘姹締?wèn)題被當(dāng)做函數(shù)不能正確使用,應(yīng)取一個(gè)較大值作為初始值
# print(valuecurrent)
solutionbest = solutionnew.copy()
valuebest = 99000 # np.max
alpha,t2,markovlen = initpara()
t = t2[1] # t=100
t_min = t2[0]
result = [] # 記錄迭代過(guò)程中的最優(yōu)距離解
while t > t_min:
for i in np.arange(markovlen):
# 下面的兩交換和三角換是兩種擾動(dòng)方式,用于產(chǎn)生新解
if np.random.rand() > 0.5: # 交換路徑中的這2個(gè)節(jié)點(diǎn)的順序
# np.random.rand()產(chǎn)生[0, 1)區(qū)間的均勻隨機(jī)數(shù)
while True: # 產(chǎn)生兩個(gè)不同的隨機(jī)數(shù)
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
# 下面的三個(gè)判斷語(yǔ)句使得loc1
loc2:
loc1,loc2 = loc2,loc1
if loc2 > loc3:
loc2,loc3 = loc3,loc2
if loc1 > loc2:
loc1,loc2 = loc2,loc1
#下面的三行代碼將[loc1,loc2)區(qū)間的數(shù)據(jù)插入到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) #程序運(yùn)行時(shí)間較長(zhǎng),打印t來(lái)監(jiān)視程序進(jìn)展速度
#用來(lái)顯示結(jié)果
# plt.plot(
plot_x_set = []
plot_y_set = []
print(solutioncurrent+1) # 輸出最優(yōu)路徑圖
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): # 標(biāo)注每個(gè)點(diǎn)的序號(hào)
plt.annotate(txt, (plot_x_set[i],plot_y_set[i]))
# 首尾2個(gè)點(diǎn)的連線
x = [plot_x_set[0],plot_x_set[-1]]
y = [plot_y_set[0],plot_y_set[-1]]
plt.plot(x, y, 'k') # 用黑色標(biāo)識(shí)
plt.show()
# 繪制迭代次數(shù)與最短距離圖片
plt.plot(np.array(result))
plt.ylabel("bestvalue")
plt.xlabel("t")
plt.show()
最終結(jié)果如下:
迭代效果如下:
其中繪制路線圖的代碼如下:
plot_x_set = []
plot_y_set = []
print(solutioncurrent+1) # 輸出最優(yōu)路徑圖
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): # 標(biāo)注每個(gè)點(diǎn)的序號(hào)
plt.annotate(txt, (plot_x_set[i],plot_y_set[i]))
# 首尾2個(gè)點(diǎn)的連線
x = [plot_x_set[0],plot_x_set[-1]]
y = [plot_y_set[0],plot_y_set[-1]]
plt.plot(x, y, 'k') # 用黑色標(biāo)識(shí)
plt.show()
如果去掉TSP實(shí)際背景,單純繪制路線圖的并標(biāo)注各個(gè)點(diǎn)的序號(hào)的話,代碼如下:
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()
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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