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