模拟退火解决tsp-python

import csv
import math
import numpy as np
import random
from matplotlib import pyplot as plt

"导入数据"
filename = '题目数据.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)
    x = []
    y = []
    longtitudes=[]
    dimensionalitys=[]
    for row in reader:
        x.append(row[1])
        y.append((row[2]))
        longtitudes = [float(x) for x in x]
        dimensionalitys = [float(y) for y in y]
longtitudes.append(longtitudes[0])
dimensionalitys.append(dimensionalitys[0])

"构建距离矩阵"
d = []
rows = 31
columns = 31
pi = 3.1415926
for row in range(rows):
    d.append([])
    for column in range(columns):
        x1 = longtitudes[row] * pi/180
        y1 = dimensionalitys[row] * pi/180
        x2 = longtitudes[column]*pi/180
        y2 = dimensionalitys[column]*pi/180
        num = 6370 * math.acos((math.cos(x1-x2)*math.cos(y1)*math.cos(y2)+math.sin(y1)*math.sin(y2)))
        d[row].append(num)

"产生较好的初始路径并计算初始长度"
path = [0]
path1 = np.random.permutation(29)+1
path.extend(path1)
path.append(30)
temp = 0
for i in range(30):
    temp = temp + d[path[i]][path[i + 1]]
long = temp


"设置初始值"
t = 0.1**30
T = 1
at = 0.999
L = 10*300
a = []

"模拟退火过程"
while t < T:
    for i in range(L):
        a = random.sample(range(2, 29), 2)
        a.sort()
        a1 = a[0]
        a2 = a[1]
        r = np.random.uniform(0, 1)
        "计算新路径的差值"
        df = d[path[a1 - 2]][path[a2 - 1]] + d[path[a1 - 1]][path[a2]] - d[path[a1 - 2]][path[a1 - 1]] - d[path[a2 - 1]][path[a2]]
        if df < 0:
            long = long + df
            change_path = path[a2 - 1:a1 - 2:-1]
            path[a1 - 1:a2] = change_path
        elif math.exp(-df/T) > r:
            long = long + df
            change_path = path[a2 - 1:a1 - 2:-1]
            path[a1 - 1:a2] = change_path
        T = T*at

print(long)
print(path)

"画路线图"
plt.rcParams['font.sans-serif']=['SimHei']
xx = []
yy = []
for i in range(31):
    aa = path[i]
    aa1 = longtitudes[aa]
    aa2 = dimensionalitys[aa]
    if aa>0 & aa<30:
        plt.text(aa1, aa2, aa)
    elif aa == 0:
        plt.text(aa1,aa2,"中心城市")
    xx.append(aa1)
    yy.append(aa2)
plt.plot(xx, yy)
plt.show()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

优化大师傅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值