python繪製旅行商(TSP)問題的路線圖

用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<loc3
            if 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<valuecurrent: #接受該解

            #更新solutioncurrent 和solutionbest
            valuecurrent = valuenew
            solutioncurrent = solutionnew.copy()

            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()

效果如下:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章