禁忌搜索算法解决旅行商问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import math
import random

matplotlib.rcParams['font.family'] = 'STSong'
np.set_printoptions(linewidth=400)
np.set_printoptions(threshold=np.inf)

"""
data.txt数据载入
-----------------
重庆,106.54,29.59
拉萨,91.11,29.97
乌鲁木齐,87.68,43.77
银川,106.27,38.47
呼和浩特,111.65,40.82
南宁,108.33,22.84
哈尔滨,126.63,45.75
长春,125.35,43.88
沈阳,123.38,41.8
石家庄,114.48,38.03
太原,112.53,37.87
西宁,101.74,36.56
济南,117,36.65
郑州,113.6,34.76
南京,118.78,32.04
合肥,117.27,31.86
杭州,120.19,30.26
福州,119.3,26.08
南昌,115.89,28.68
长沙,113,28.21
武汉,114.31,30.52
广州,113.23,23.16
台北,121.5,25.05
海口,110.35,20.02
兰州,103.73,36.03
西安,108.95,34.27
成都,104.06,30.67
贵阳,106.71,26.57
昆明,102.73,25.04
香港,114.1,22.2
澳门,113.33,22.13
"""
city_name = []
city_condition = []
with open('data.txt','r',encoding='UTF-8') as f:
lines = f.readlines()
for line in lines:
line = line.split('\n')[0]
line = line.split(',')
city_name.append(line[0])
city_condition.append([float(line[1]), float(line[2])])
city_condition = np.array(city_condition)
"""
地图展示
"""
def map_show():
fig = plt.figure()
ax1 = fig.add_subplot()
ax1.set_title('城市分布图')
for i in range(city_count):
plt.annotate(i+1,xy=(city_condition[i][0], city_condition[i][1]), xytext=(city_condition[i][0] + 0.3, city_condition[i][1] + 0.3))
plt.scatter(city_condition[:, 0], city_condition[:, 1])
plt.xlabel('经度')
plt.ylabel('纬度')
plt.show()

"""
距离矩阵和总距离的计算
"""
#距离矩阵
city_count = len(city_name)
Distance = np.zeros((city_count+1, city_count+1))
for i in range(1,city_count+1):
for j in range(1,city_count+1):
Distance[i][j] = math.sqrt((city_condition[i-1][0] - city_condition[j-1][0]) ** 2 + (city_condition[i-1][1] - city_condition[j-1][1]) ** 2)
#适应度计算
def get_total_distance(path_new):
distance = 0
for i in range(city_count-1):
#count为30,意味着回到了开始的点,此时的值应该为0.
distance += Distance[int(path_new[i])][int(path_new[i+1])]
distance += Distance[int(path_new[-1])][int(path_new[0])]
return distance

"""
全局参数设计
1.禁忌表长度设置
2.候选集长度设置
3.迭代次数的设置
"""
#禁忌长度
tabu_limit = 100
#禁忌表
tabu_list = []
#候选集
del_list = []
candidate_length = 200
#候选集列表
candidate = np.zeros((candidate_length,city_count))#存放候选集的列表
candidate_distance = np.zeros(candidate_length)#存放候选集的适应度
iteration = 200
#存放最优值
distance_best = []

"""
用贪婪算法求出初始解
"""
def greedy():
i = 1
n = city_count
j = 0
# 当前总距离
distance_sum = 0
s = []#已经遍历过得城市
s.append(1)
while True:
k = 1#从1开始编城市编号
# 当前最小距离
Detemp = 99000
while True:
flag = 0
if k in s:
flag = 1
if (flag == 0) and Distance[k][s[i-1]]<Detemp:
j = k
Detemp = Distance[k][s[i-1]]
k += 1
if k > n:
break
s.append(j)
i += 1
distance_sum += Detemp
#返回执行k = 1
if i >= n:
break
return s

"""
核心思想
1.创建一张禁忌表,设置禁忌表的长度。
2.设置候选集合的长度。
3.设置迭代次数。
4.用贪心算法求出当前最优路径和当前最优值,分别赋值给当前路径和当前值。
"""
"""
为什么要设置禁忌表?防止循环搜索
为什么要解禁呢?比当前解好但是呢,却被禁忌了。
"""
"""
变异操作
"""
#两个基因交换的原理,用于领域解集的产生
def exchange(index1,index2,arr):
current_list = arr.copy()
current_list[index1] = arr[index2]
current_list[index2] = arr[index1]
return current_list
"""
领域操作,产生200个候选值
"""
#领域集合,生成200个候选集合
#在200个领域的集合生成中,随机生成交换的片段索引值exchage_position,判断生成的这个值在不在禁忌表中,
def get_candidate(p):
exchange_position = []
i = 0
while i < candidate_length:
current = random.sample(range(0,city_count),2)
if current not in exchange_position:
exchange_position.append(current)
candidate[i] = exchange(current[0],current[1],p)
candidate_distance[i] = get_total_distance(candidate[i])
i += 1
return candidate,candidate_distance,exchange_position


"""
禁忌表操作,首先根据领域找到候选集中适应度高的参数,对最优值和当前值操作,迭代
"""
def main():
global candidate,candidate_distance,exchange_position,del_list
global value_best,value_current,path_best,path_current_
path_current = greedy()
value_best = 9900

for rt in range(iteration):
candidate,candidate_distance,exchange_position = get_candidate(path_current)
#找到候选解集的当前最优解
#逻辑:如果当前最小值比全局存在的最优值还要小,那么就用当前的最小值替换为全局的最优值,当前path。
min_index = np.argmin(candidate_distance)#z最小的元素的索引值
#是否要更新全局最优呢?就要判断之前选择的全局最优和迭代后的全局最优
if exchange_position[min_index] not in tabu_list:
if candidate_distance[min_index] < value_best:
value_best = candidate_distance[min_index]
path_best = candidate[min_index].copy()
path_current = candidate[min_index].copy()
value_current = candidate_distance[min_index]
# 增加当前禁忌表长度
tabu_list.append(exchange_position[min_index])
# 存放每次迭代的全局最优用于画图
distance_best.append(value_best)
else:#在禁忌表中,但是比当前最优要小,替换当前值,不替换最优值。
# 替换当前状态和最优状态
path_current = candidate[min_index].copy()
value_current = candidate_distance[min_index]
# 增加当前禁忌表长度
tabu_list.append(exchange_position[min_index])
distance_best.append(value_best)
# 存放每次迭代的全局最优用于画图
else:#当前领域中最小值在禁忌表中,可能这个值比当前值小,那么释放;如果没有当前最优值大,那么找下一个替代值。
if candidate_distance[min_index] < value_best:
c = tabu_list.index(exchange_position[min_index])
# print("禁忌表", tabu_list)
# print("想要删除的点", exchange_position[min_index])
# print("想要删除的点在禁忌表中的索引", c)
# print("用索引代表的索引值", tabu_list[c])
# del_list.append(tabu_list[(tabu_list.index([exchange_position[min_index]]))])
# del tabu_list[(tabu_list.index([exchange_position[min_index]]))]
del_list.append(tabu_list[tabu_list.index(exchange_position[min_index])])
del tabu_list[tabu_list.index(exchange_position[min_index])]
# print(tabu_list)
# 替换当前状态和最优状态
value_best = candidate_distance[min_index]
path_best = candidate[min_index].copy()
path_current = candidate[min_index].copy()
value_current = candidate_distance[min_index]
# 存放每次迭代的全局最优用于画图
distance_best.append(value_best)
else:#如果在禁忌表中,且比起当前值要大,那么忽略这一个,则搜索下一个
candidate_distance[min_index] = 99000
b = True
while b :
min_index = np.argmin(candidate_distance)
if exchange_position[min_index] not in tabu_list:
b = False
else:
candidate_distance[min_index] = 99000
path_current = candidate[min_index].copy()
value_current = candidate_distance[min_index]
tabu_list.append(exchange_position[min_index])
distance_best.append(value_best)
if len(tabu_list) > tabu_limit:
# tabu_distance = []
# tabu_distance = get_total_distance(tabu_list)
# print("禁忌表",tabu_distance)
del tabu_list[0]
print("禁忌搜索算法解决tsp问题")
print("当前路径:", path_current)
print("当前值", value_current)
print("全局最优值为:", value_best)
print("全局最优路径:", path_best)
draw(distance_best,path_best)

def draw(distance_best,path_best):
map_show()

# 距离迭代图
fig = plt.figure()
ax3 = fig.add_subplot()
ax3.set_title('距离迭代图')
plt.plot(np.array(distance_best))
plt.xlabel('迭代次数')
plt.ylabel('距离值')
plt.show()
# # 路线图绘制
fig = plt.figure()
ax2 = fig.add_subplot()
ax2.set_title('最佳路线图')
x = []
y = []
path = []
for i in range(city_count):
x.append(city_condition[int(path_best[i])- 1][0])
y.append(city_condition[int(path_best[i])- 1][1])
path.append(int(path_best[i]))
x.append(x[0])
y.append(y[0])
path.append(path[0])
for i in range(len(x)):
plt.annotate(path[i], xy=(x[i], y[i]), xytext=(x[i] + 0.3, y[i] + 0.3))
plt.plot(x, y,'-o')
plt.show()
if __name__ =="__main__":
main()
0%