模拟退火算法求解TSP问题(Python实现)

TSP问题:假设有六个城市,一销售商从其中的某一城市出发,不重复地走完其余5个城市并回到原出发点,在所有可能的路径中求出路径长度最短的一条。六个城市坐标为:城市1(87,7)、城市2(91,38)、城市3(83,46)、城市4(71,44)、城市5(64,60)、城市6(68,58)。

import math
import random
import numpy as np
import copy
import matplotlib.pyplot as plt
city={'x':[87,91,83,71,64,68],'y':[7,38,46,44,60,58]}
n=len(city['x'])
x=city['x']
y=city['y']
distance=np.zeros((n,n))
for i in range(n):
    for j in range(n):
        distance[i,j] = math.sqrt(pow(x[i]-x[j],2)+pow(y[i]-y[j],2))

#随机生成一个初始解
aa=[i for i in range(n)]
a=np.random.permutation(aa)
dis=0
for i in range(len(a)-1):
    dis=dis+distance[a[i],a[i+1]]
dis=dis+distance[a[i+1],a[0]]
#print(path)
path=copy.deepcopy(a)
path_long=copy.deepcopy(dis)
T=1000
Te=1e-4
alpha=0.99
t=T
while t>=Te:
    r=np.random.randint(0,5,2)
    #print(r)
    r=sorted(r)
    if r[0]==r[1]:
        r[1]=r[1]+1
    temp=a[r[0]]
    a[r[0]]=a[r[1]]
    a[r[1]]=temp
    dis=0
    for i in range(len(a)-1):
        dis=dis+distance[a[i],a[i+1]]
    dis=dis+distance[a[i+1],a[0]]
    df=dis-path_long
    if df<0:
        path_long=copy.deepcopy(dis)
        path=copy.deepcopy(a)
    else:
        p=math.exp(-df/t)
        if p>=random.random():
            path_long=copy.deepcopy(dis)
            path=copy.deepcopy(a)
    t=t*alpha
    a=copy.deepcopy(path)
print('最优路径:',path)
print('最优路径长度:',path_long)
#绘图
#p1=[83,68,64,71,87,91]
#p2=[46,58,60,44,7,38]
p1=[]
p2=[]
for i in path:
    p1.append( x[i] )
    p2.append( y[i] )
for i in range(n):
    plt.plot( p1,p2, color='r')
    plt.scatter( p1[i], p2[i], color='b' )
plt.show()

你可能感兴趣的:(python,模拟退火算法)