1. import math
  2. import random
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. from mpl_toolkits.mplot3d import Axes3D
  6. import sys
  7. from numpy.matlib import rand
  8. from matplotlib.artist import getp
  9. import copy
  10. from test.test__locale import candidate_locales
  11. from cProfile import run
  12. import city
  13. import scipy.stats as stats
  14. def greedy():
  15. #通过贪婪算法确定初始r值,也就是初始信息素浓度
  16. sum = 0.0
  17. #必须实例化一个一个赋值,不然只是把地址赋值,牵一发而动全身
  18. dis = [[0 for col in range(n)] for raw in range(n)]
  19. for i in range(n):
  20. for j in range(n):
  21. dis[i][j] = distance[i][j]
  22. visited = []
  23. #进行贪婪选择——每次都选择距离最近的
  24. id = 0
  25. for i in range(n):
  26. for j in range(n):
  27. dis[j][id] = sys.maxsize
  28. minvalue = min(dis[id])
  29. if i != 29:
  30. sum += minvalue
  31. visited.append(id)
  32. id = dis[id].index(minvalue)
  33. sum += distance[0][visited[n-1]]
  34. return visited
  35. #构建初始参考距离矩阵
  36. def getdistance():
  37. for i in range(n):
  38. for j in range(n):
  39. x = pow(city_x[i] - city_x[j], 2)
  40. y = pow(city_y[i] - city_y[j], 2)
  41. distance[i][j] = pow(x + y, 0.5)
  42. for i in range(n):
  43. for j in range(n):
  44. if distance[i][j] == 0:
  45. distance[i][j] = sys.maxsize
  46. #计算总距离
  47. def cacl_best(rou):
  48. sumdis = 0.0
  49. for i in range(n-1):
  50. sumdis += distance[rou[i]][rou[i+1]]
  51. sumdis += distance[rou[n-1]][rou[0]]
  52. return sumdis
  53. #初始设置
  54. def setup(methods=1):
  55. global best_route
  56. global best_distance
  57. global tabu_time
  58. global current_tabu_num
  59. global current_distance
  60. global current_route
  61. global tabu_list
  62. #得到初始解以及初始距离
  63. if methods==1:
  64. current_route = greedy()
  65. else:
  66. current_route = random.sample(range(0, n), n)
  67. best_route = copy.copy(current_route)
  68. #函数内部修改全局变量的值
  69. current_distance = cacl_best(current_route)
  70. best_distance = current_distance
  71. #置禁忌表为空
  72. tabu_list.clear()
  73. tabu_time.clear()
  74. current_tabu_num = 0
  75. return current_distance
  76. #交换数组两个元素
  77. def exchange(index1, index2, arr):
  78. current_list = copy.copy(arr)
  79. current = current_list[index1]
  80. current_list[index1] = current_list[index2]
  81. current_list[index2] = current
  82. return current_list
  83. #得到邻域候选解
  84. def get_candidate():
  85. global best_route
  86. global best_distance
  87. global current_tabu_num
  88. global current_distance
  89. global current_route
  90. global tabu_list
  91. #存储两个交换的位置
  92. exchange_position = []
  93. temp = 0
  94. #随机选取邻域
  95. while True:
  96. current = random.sample(range(0, n), 2)
  97. #print(current)
  98. if current not in exchange_position:
  99. exchange_position.append(current)
  100. candidate[temp] = exchange(current[0], current[1], current_route)
  101. if candidate[temp] not in tabu_list:
  102. #print(temp)
  103. candidate_distance[temp] = cacl_best(candidate[temp])
  104. temp += 1
  105. if temp >= 200:
  106. break
  107. #得到候选解中的最优解
  108. candidate_best = min(candidate_distance)
  109. best_index = candidate_distance.index(candidate_best)
  110. current_distance = candidate_best
  111. current_route = copy.copy(candidate[best_index])
  112. #与当前最优解进行比较
  113. if current_distance < best_distance:
  114. best_distance = current_distance
  115. best_route = copy.copy(current_route)
  116. #加入禁忌表
  117. tabu_list.append(candidate[best_index])
  118. tabu_time.append(tabu_limit)
  119. current_tabu_num += 1
  120. #更新禁忌表以及禁忌期限
  121. def update_tabu():
  122. global current_tabu_num
  123. global tabu_time
  124. global tabu_list
  125. del_num = 0
  126. temp = [0 for col in range(n)]
  127. #更新步长
  128. tabu_time = [x-1 for x in tabu_time]
  129. #如果达到期限,释放
  130. for i in range(current_tabu_num):
  131. if tabu_time[i] == 0:
  132. del_num += 1
  133. tabu_list[i] = temp
  134. current_tabu_num -= del_num
  135. while 0 in tabu_time:
  136. tabu_time.remove(0)
  137. while temp in tabu_list:
  138. tabu_list.remove(temp)
  139. def draw():
  140. result_x = [0 for col in range(n+1)]
  141. result_y = [0 for col in range(n+1)]
  142. for i in range(n):
  143. result_x[i] = city_x[best_route[i]]
  144. result_y[i] = city_y[best_route[i]]
  145. result_x[n] = result_x[0]
  146. result_y[n] = result_y[0]
  147. print(result_x)
  148. print(result_y)
  149. plt.xlim(0, 100) # 限定横轴的范围
  150. plt.ylim(0, 100) # 限定纵轴的范围
  151. plt.plot(result_x, result_y, marker='>', mec='r', mfc='w',label=u'Route')
  152. plt.legend() # 让图例生效
  153. plt.margins(0)
  154. plt.subplots_adjust(bottom=0.15)
  155. plt.xlabel(u"x") #X轴标签
  156. plt.ylabel(u"y") #Y轴标签
  157. plt.title("TSP Solution") #标题
  158. plt.show()
  159. plt.close(0)
  160. def solve(runtime=500):
  161. getdistance()
  162. setup()
  163. for i in range(runtime):
  164. get_candidate()
  165. update_tabu()
  166. def TSA_TSP(runtime):
  167. '''遗传算法、禁忌搜索算法和微粒群算法收敛速度的对比'''
  168. getdistance()
  169. setup()
  170. a = []
  171. for j in range(runtime):
  172. get_candidate()
  173. update_tabu()
  174. a.append(best_distance)
  175. return a
  176. def TSA_better(runtime):
  177. '''遗传算法、禁忌搜索算法和微粒群算法收敛速度的对比'''
  178. global tabu_limit
  179. getdistance()
  180. setup()
  181. a = []
  182. for j in range(runtime):
  183. tabu_limit = int(100*(j/runtime)+1)
  184. get_candidate()
  185. update_tabu()
  186. a.append(best_distance)
  187. return a
  188. def main():
  189. global city_x, city_y, distance, n, tabu_limit, tabu_list, tabu_time, current_tabu_num, candidate, candidate_distance
  190. global best_route, best_distance, current_distance, current_route
  191. if(1):
  192. city_x = []
  193. city_y = []
  194. a = dict.values(city.china)
  195. a = list(a)
  196. for i in range(100):
  197. city_x.append(a[i][0])
  198. city_y.append(a[i][1])
  199. # 城市数量
  200. n = len(city_x)
  201. distance = [[0 for col in range(n)] for raw in range(n)]
  202. #禁忌表
  203. tabu_list = []
  204. tabu_time = []
  205. #当前禁忌对象数量
  206. current_tabu_num = 0
  207. #禁忌长度,即禁忌期限
  208. tabu_limit = 50
  209. #候选集
  210. candidate = [[0 for col in range(n)] for raw in range(200)]
  211. candidate_distance = [0 for col in range(200)]
  212. #最佳路径以及最佳距离
  213. best_route = []
  214. best_distance = sys.maxsize
  215. current_route = []
  216. current_distance = 0.0
  217. getdistance()
  218. setup()
  219. k = 6
  220. if k==1:
  221. '''不同初始样本对结果的影响'''
  222. init = []
  223. x = []
  224. y = []
  225. for i in range(20):
  226. print(i)
  227. getdistance()
  228. x.append(i)
  229. init.append(setup(methods=2))
  230. for epoch in range(500):
  231. get_candidate()
  232. update_tabu()
  233. y.append(best_distance)
  234. r,p = stats.pearsonr(init,y) # 相关系数和P值
  235. print('相关系数r=%.3f,p值=%.3f'%(r,p))
  236. plt.figure(figsize = (6,6)) # 图片像素大小
  237. plt.scatter(init,y,color="blue") # 散点图绘制
  238. plt.grid() # 显示网格线
  239. plt.xlabel('init')
  240. plt.ylabel('result')
  241. plt.show() # 显示图片
  242. plt.plot(x,init,color='blue',label='init_distance')
  243. plt.plot(x,y,color='red',label='result_distance')
  244. plt.xlabel('times')
  245. plt.ylabel('distance')
  246. plt.title('The effect of the initial route on the distance')
  247. elif k==2:
  248. '''禁忌表长度对于结果的影响'''
  249. x = []
  250. y = []
  251. for i in range(10,200,10):
  252. print(i)
  253. distance = [[0 for col in range(n)] for raw in range(n)]
  254. #禁忌表
  255. tabu_list = []
  256. tabu_time = []
  257. #当前禁忌对象数量
  258. current_tabu_num = 0
  259. #候选集
  260. candidate = [[0 for col in range(n)] for raw in range(200)]
  261. candidate_distance = [0 for col in range(200)]
  262. #最佳路径以及最佳距离
  263. best_route = []
  264. best_distance = sys.maxsize
  265. current_route = []
  266. current_distance = 0.0
  267. getdistance()
  268. setup()
  269. tabu_limit = i # 禁忌长度
  270. for j in range(2500):
  271. get_candidate()
  272. update_tabu()
  273. x.append(i)
  274. y.append(best_distance)
  275. plt.plot(x,y)
  276. plt.xlabel('Tabu_len')
  277. plt.ylabel('distance')
  278. plt.title('The effect of the length of tabu list on the distance')
  279. elif k==3:
  280. '''不同禁忌表长度的情况下的最佳迭代次数'''
  281. x = []
  282. y = []
  283. for i in range(1,21):
  284. distance = [[0 for col in range(n)] for raw in range(n)]
  285. #禁忌表
  286. tabu_list = []
  287. tabu_time = []
  288. #当前禁忌对象数量
  289. current_tabu_num = 0
  290. #候选集
  291. candidate = [[0 for col in range(n)] for raw in range(200)]
  292. candidate_distance = [0 for col in range(200)]
  293. #最佳路径以及最佳距离
  294. best_route = []
  295. best_distance = sys.maxsize
  296. current_route = []
  297. current_distance = 0.0
  298. getdistance()
  299. setup()
  300. tabu_limit = i*10
  301. best = []
  302. for epoch in range(25000):
  303. get_candidate()
  304. update_tabu()
  305. best.append(best_distance)
  306. if(epoch>500 and len(set(best[epoch-500:epoch]))==1):
  307. break
  308. x.append(tabu_limit)
  309. y.append(epoch-500)
  310. print(tabu_limit,epoch-500)
  311. plt.plot(x,y)
  312. plt.xlabel('tabu_len')
  313. plt.ylabel('best_epochs')
  314. plt.title('The best number of epochs in different length of tabu list')
  315. elif k==4:
  316. '''遗传算法与禁忌搜索算法在不同迭代次数上的比较'''
  317. from 遗传TSP import GA_TSP
  318. i = 500
  319. epoch = [x for x in range(1,i+1)]
  320. plt.plot(epoch,TSA_better(i),color='red',label='Better')
  321. plt.plot(epoch,GA_TSP(epochs=i),color='blue',label='GA')
  322. plt.plot(epoch,TSA_TSP(i),color='red',label='TSA')
  323. plt.xlabel('epochs')
  324. plt.ylabel('distance')
  325. plt.title('The effect of the difference methods on the distance')
  326. elif k==5:
  327. '''禁忌长度自适应改进算法与标准算法的对比'''
  328. i = 1500
  329. epoch = [x for x in range(1,i+1)]
  330. plt.plot(epoch,TSA_TSP(i),color='blue',label='Simple')
  331. plt.plot(epoch,TSA_better(i),color='red',label='Better')
  332. plt.xlabel('epochs')
  333. plt.ylabel('distance')
  334. plt.title('The different arithmetic')
  335. elif k==6:
  336. '''遗传算法与禁忌搜索算法在不同城市规模上的比较'''
  337. epoch = []
  338. GA = []
  339. TSA = []
  340. for scale in range(20,151,10):
  341. from 遗传TSP import GA_TSP
  342. city_x = []
  343. city_y = []
  344. a = dict.values(city.china)
  345. a = list(a)
  346. for i in range(scale):
  347. city_x.append(a[i][0])
  348. city_y.append(a[i][1])
  349. # 城市数量
  350. n = len(city_x)
  351. distance = [[0 for col in range(n)] for raw in range(n)]
  352. #禁忌表
  353. tabu_list = []
  354. tabu_time = []
  355. #当前禁忌对象数量
  356. current_tabu_num = 0
  357. #禁忌长度,即禁忌期限
  358. tabu_limit = 50
  359. #候选集
  360. candidate = [[0 for col in range(n)] for raw in range(200)]
  361. candidate_distance = [0 for col in range(200)]
  362. #最佳路径以及最佳距离
  363. best_route = []
  364. best_distance = sys.maxsize
  365. current_route = []
  366. current_distance = 0.0
  367. getdistance()
  368. setup()
  369. epoch.append(scale)
  370. TSA.append(min(TSA_better(1000)))
  371. GA.append(min(GA_TSP(scale=scale,epochs=5000+scale*100)))
  372. print(scale)
  373. plt.plot(epoch,GA,color='blue',label='GA')
  374. plt.plot(epoch,TSA,color='red',label='TSA')
  375. plt.xlabel('city_scale')
  376. plt.ylabel('distance')
  377. plt.title('The effect of the scale of cities on the distance')
  378. plt.legend()
  379. plt.show()
  380. if __name__=="__main__":
  381. main()

禁忌搜索算法TSA 旅行商问题TSP python的更多相关文章

  1. 原创:TSP问题解决方案-----禁忌搜索算法C实现

    本文着重于算法的实现,对于理论部分可自行查看有关资料可以简略参考该博文:http://blog.csdn.net/u013007900/article/details/50379135 本文代码部分基 ...

  2. 【算法】禁忌搜索算法(Tabu Search,TS)超详细通俗解析附C++代码实例

    01 什么是禁忌搜索算法? 1.1 先从爬山算法说起 爬山算法从当前的节点开始,和周围的邻居节点的值进行比较. 如果当前节点是最大的,那么返回当前节点,作为最大值 (既山峰最高点):反之就用最高的邻居 ...

  3. 【智能算法】用模拟退火(SA, Simulated Annealing)算法解决旅行商问题 (TSP, Traveling Salesman Problem)

    喜欢的话可以扫码关注我们的公众号哦,更多精彩尽在微信公众号[程序猿声] 文章声明 此文章部分资料和代码整合自网上,来源太多已经无法查明出处,如侵犯您的权利,请联系我删除. 01 什么是旅行商问题(TS ...

  4. 【高级算法】禁忌搜索算法解决3SAT问题(C++实现)

    转载请注明出处:http://blog.csdn.net/zhoubin1992/article/details/46440389 近期梳理,翻出了当年高级算法课程做的题目.禁忌搜索算法解决3SAT问 ...

  5. 【优化算法】变邻域搜索算法(VNS)求解TSP(附C++详细代码及注释)

    00 前言 上次变邻域搜索的推文发出来以后,看过的小伙伴纷纷叫好.小编大受鼓舞,连夜赶工,总算是完成了手头上的一份关于变邻域搜索算法解TSP问题的代码.今天,就在此给大家双手奉上啦,希望大家能ENJO ...

  6. 遗传算法解决旅行商问题(TSP)

    这次的文章是以一份报告的形式贴上来,代码只是简单实现,难免有漏洞,比如循环输入的控制条件,说是要求输入1,只要输入非0就行.希望会帮到以后的同学(*^-^*) 一.问题描述 旅行商问题(Traveli ...

  7. 遗传算法 TSP(Python代码)

    该代码是本人根据B站up主侯昶曦的代码所修改的. 原代码github地址:https://github.com/Houchangxi/heuristic-algorithm/blob/master/T ...

  8. 07_旅行商问题(TSP问题,货郎担问题,经典NPC难题)

    问题来源:刘汝佳<算法竞赛入门经典--训练指南> P61 问题9: 问题描述:有n(n<=15)个城市,两两之间均有道路直接相连,给出每两个城市i和j之间的道路长度L[i][j],求 ...

  9. 三进制状态压缩DP(旅行商问题TSP)HDU3001

    http://acm.hdu.edu.cn/showproblem.php?pid=3001 Travelling Time Limit: 6000/3000 MS (Java/Others)     ...

随机推荐

  1. 基于UiAutomator2+PageObject模式开展APP自动化测试实战

    前言 在上一篇<APP自动化测试框架-UiAutomator2基础>中,重点介绍了uiautomator2的项目组成.运行原理.环境搭建及元素定位等基础入门知识,本篇将介绍如何基于uiau ...

  2. LuoguP1456 Monkey King (左偏树)

    struct LeftTree{ int l,r,val,dis; }t[N]; int fa[N]; inline int Find(int x){ return x == fa[x] ? x : ...

  3. 在.NET 6.0中使用不同的托管模型

    大家好,我是张飞洪,感谢您的阅读,我会不定期和你分享学习心得,希望我的文章能成为你成长路上的垫脚石,让我们一起精进. 本章是<定制ASP NET 6.0框架系列文章>的第六篇.在本章中,我 ...

  4. HC32L110 在 Ubuntu 下使用 J-Link 烧录

    目录 HC32L110(一) HC32L110芯片介绍和Win10下的烧录 HC32L110(二) HC32L110在Ubuntu下的烧录 HC32L110 在 Ubuntu 下使用 J-Link 烧 ...

  5. Vue组件的继承用法

    Vue组件的继承用法 点击打开视频讲解 vue组件的继承适用于UI几乎一样,只是数据不一样的情况下,但是这种情况通过统一封装组件也是能实现的,小功能建议用封装,大功能建议用组件继承,因为大功能在结合搜 ...

  6. Linux—进程管理

    Linux 进程管理 1.进程管理介绍 1.1 什么是进程? 进程(Process)是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础. 简而言之 ...

  7. JSP中的EL 表达式

    JSP中的EL 表达式 什么是 EL 表达式,EL 表达式的作用? EL 表达式的全称是:Expression Language.是表达式语言. EL 表达式的什么作用:EL 表达式主要是代替 jsp ...

  8. 【java】学习路径17-用户注册登录实例(Scanner)

    要学会使用接口.继承.多态.构造方法.包等知识编写出一个用户登录注册的事例.

  9. 大家都能看得懂的源码之 ahooks useVirtualList 封装虚拟滚动列表

    本文是深入浅出 ahooks 源码系列文章的第十八篇,该系列已整理成文档-地址.觉得还不错,给个 star 支持一下哈,Thanks. 简介 提供虚拟化列表能力的 Hook,用于解决展示海量数据渲染时 ...

  10. QT学习(五)----360界面制作(2终结)

    继续上一章的360新特性界面.源代码:http://download.csdn.net/detail/zhangyang1990828/5241242 上一章中实现了整个界面的纯UI设计,这次我们让它 ...