徐涛 3 years ago
parent 68a400df8a
commit f00eb9ab98

Binary file not shown.

@ -1,11 +1,10 @@
import matplotlib
import numpy as np import numpy as np
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import pdb import matplotlib.animation as animation
import random as rd import random as rd
from math import sqrt, exp from math import sqrt, exp
from os import path import os
from matplotlib.lines import Line2D
import matplotlib.animation as animation
"旅行商问题 ( TSP , Traveling Salesman Problem )" "旅行商问题 ( TSP , Traveling Salesman Problem )"
''' '''
编写模拟退火算法解旅行商问题 编写模拟退火算法解旅行商问题
@ -17,9 +16,8 @@ import matplotlib.animation as animation
# input # input
def loadin_data(): def loadin_data():
local_path = path.dirname(__file__) local_path = os.path.dirname(__file__)
with open(local_path + '/../testdata/1.txt', 'r') as f: with open(local_path + '/../testdata/1.txt', 'r') as f:
data = f.read() data = f.read()
data = data.split() data = data.split()
@ -34,30 +32,12 @@ def loadin_data():
return x, y return x, y
loadin_data()
x, y = loadin_data()
#print(x, y)
path = [x, y]
def distance(path, i, j): def distance(path, i, j):
a = path[0][i]-path[0][j] a = path[0][i]-path[0][j]
b = path[1][i]-path[1][j] b = path[1][i]-path[1][j]
return sqrt(a**2+b**2) return sqrt(a**2+b**2)
# distance_matrix = []
# for i in range(len(x)):
# distance_matrix.append([])
# # print(distance_matrix)
# for i in range(2):
# for j in range(len(x)):
# distance_matrix[i].append(distance(path, i, j))
# print(distance_matrix[1])
# print(len(distance_matrix[0]))
def exchange(path, a, b): def exchange(path, a, b):
path[0][a], path[0][b] = path[0][b], path[0][a] path[0][a], path[0][b] = path[0][b], path[0][a]
path[1][a], path[1][b] = path[1][b], path[1][a] path[1][a], path[1][b] = path[1][b], path[1][a]
@ -72,21 +52,11 @@ def sum_distance(path):
return sum return sum
x, y = loadin_data()
path = [x, y]
ax1 = plt.axes([0,0,1,1]) plt.figure(figsize=(10,5))
# ax2 = plt.axes([0.55,0.05,0.95,0.9]) ax1 = plt.axes([0.05, 0.05, 0.4, 0.9])
fig, ax = plt.subplots() ax2 = plt.axes([0.55, 0.05, 0.4, 0.9])
def draw_line(path):
for j in range(len(path[0])-1):
line1 = [(path[0][j], path[1][j]), (path[0][j+1], path[1][j+1])]
(line1_xs, line1_ys) = zip(*line1)
ax.add_line(Line2D(line1_xs, line1_ys, linewidth=1, color='blue'))
line1 = [(path[0][0], path[1][0]),
(path[0][len(path[0])-1], path[1][len(path[0])-1])]
(line1_xs, line1_ys) = zip(*line1)
ax.add_line(Line2D(line1_xs, line1_ys,linewidth=1, color='blue'))
T = 100 T = 100
alpha = 0.95 alpha = 0.95
@ -95,18 +65,18 @@ current = sum_distance(path)
print(current, '\n') print(current, '\n')
next = 0 next = 0
count = 0 count = 0
xl=[] xl = []
yl=[] yl = []
plt.cla() plt.cla()
plt.ion() plt.ion() # 打开交互模式
while(True): while(True):
if(T < 0.05): if(T < 0.05):
break break
oldcurrent = current oldcurrent = current
for i in range(iters): for i in range(iters):
a, b = rd.sample(range(0, len(path[0])), 2) a, b = rd.sample(range(0, len(path[0])), 2)
newpath=[[],[]] newpath = [[], []]
for x,y in zip(path[0],path[1]): for x, y in zip(path[0], path[1]):
newpath[0].append(x) newpath[0].append(x)
newpath[1].append(y) newpath[1].append(y)
# print(newpath) # print(newpath)
@ -122,22 +92,23 @@ while(True):
elif (rd.random() < exp(-(next - current)/T)): elif (rd.random() < exp(-(next - current)/T)):
current = next current = next
path = newpath.copy() path = newpath.copy()
plt.cla() plt.cla() # 清除画板
draw_line(path) ax2.plot(path[0], path[1], 'b.-')
ax.plot(path[0], path[1],'ro') ax2.plot([path[0][0], path[0][-1]], [path[1][0], path[1][-1]], 'b.-')
ax2.plot(path[0], path[1], 'ro')
plt.pause(0.05) plt.pause(0.05)
if(oldcurrent!=current): if(oldcurrent != current):
# print(count) # print(count)
count += 1 count += 1
xl.append(count) xl.append(count)
yl.append(current) yl.append(current)
ax1.plot(xl,yl) ax1.plot(xl, yl)
oldcurrent=current oldcurrent = current
T = alpha * T T = alpha * T
print(T) print(T)
for x,y in zip(path[0],path[1]): for x, y in zip(path[0], path[1]):
print("(",x,y,")-->",end='') print("(", x, y, ")-->", end='')
print(current) print(current)
plt.ioff() plt.ioff()
plt.show() plt.show()

Loading…
Cancel
Save