import math
import random
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
from numpy.matlib import rand
from matplotlib.artist import getp
import copy
from test.test__locale import candidate_locales
from cProfile import run
import city
import scipy.stats as stats def greedy():
#通过贪婪算法确定初始r值,也就是初始信息素浓度
sum = 0.0
#必须实例化一个一个赋值,不然只是把地址赋值,牵一发而动全身
dis = [[0 for col in range(n)] for raw in range(n)]
for i in range(n):
for j in range(n):
dis[i][j] = distance[i][j] visited = []
#进行贪婪选择——每次都选择距离最近的
id = 0
for i in range(n):
for j in range(n):
dis[j][id] = sys.maxsize
minvalue = min(dis[id])
if i != 29:
sum += minvalue
visited.append(id)
id = dis[id].index(minvalue)
sum += distance[0][visited[n-1]]
return visited #构建初始参考距离矩阵
def getdistance():
for i in range(n):
for j in range(n):
x = pow(city_x[i] - city_x[j], 2)
y = pow(city_y[i] - city_y[j], 2)
distance[i][j] = pow(x + y, 0.5)
for i in range(n):
for j in range(n):
if distance[i][j] == 0:
distance[i][j] = sys.maxsize #计算总距离
def cacl_best(rou):
sumdis = 0.0
for i in range(n-1):
sumdis += distance[rou[i]][rou[i+1]]
sumdis += distance[rou[n-1]][rou[0]]
return sumdis #初始设置
def setup(methods=1):
global best_route
global best_distance
global tabu_time
global current_tabu_num
global current_distance
global current_route
global tabu_list
#得到初始解以及初始距离
if methods==1:
current_route = greedy()
else:
current_route = random.sample(range(0, n), n)
best_route = copy.copy(current_route)
#函数内部修改全局变量的值
current_distance = cacl_best(current_route)
best_distance = current_distance
#置禁忌表为空
tabu_list.clear()
tabu_time.clear()
current_tabu_num = 0
return current_distance #交换数组两个元素
def exchange(index1, index2, arr):
current_list = copy.copy(arr)
current = current_list[index1]
current_list[index1] = current_list[index2]
current_list[index2] = current
return current_list #得到邻域候选解
def get_candidate():
global best_route
global best_distance
global current_tabu_num
global current_distance
global current_route
global tabu_list
#存储两个交换的位置
exchange_position = []
temp = 0
#随机选取邻域
while True:
current = random.sample(range(0, n), 2)
#print(current)
if current not in exchange_position:
exchange_position.append(current)
candidate[temp] = exchange(current[0], current[1], current_route)
if candidate[temp] not in tabu_list:
#print(temp)
candidate_distance[temp] = cacl_best(candidate[temp])
temp += 1
if temp >= 200:
break
#得到候选解中的最优解
candidate_best = min(candidate_distance)
best_index = candidate_distance.index(candidate_best)
current_distance = candidate_best
current_route = copy.copy(candidate[best_index])
#与当前最优解进行比较
if current_distance < best_distance:
best_distance = current_distance
best_route = copy.copy(current_route)
#加入禁忌表
tabu_list.append(candidate[best_index])
tabu_time.append(tabu_limit)
current_tabu_num += 1 #更新禁忌表以及禁忌期限
def update_tabu():
global current_tabu_num
global tabu_time
global tabu_list del_num = 0
temp = [0 for col in range(n)]
#更新步长
tabu_time = [x-1 for x in tabu_time]
#如果达到期限,释放
for i in range(current_tabu_num):
if tabu_time[i] == 0:
del_num += 1
tabu_list[i] = temp current_tabu_num -= del_num
while 0 in tabu_time:
tabu_time.remove(0) while temp in tabu_list:
tabu_list.remove(temp) def draw():
result_x = [0 for col in range(n+1)]
result_y = [0 for col in range(n+1)] for i in range(n):
result_x[i] = city_x[best_route[i]]
result_y[i] = city_y[best_route[i]]
result_x[n] = result_x[0]
result_y[n] = result_y[0]
print(result_x)
print(result_y)
plt.xlim(0, 100) # 限定横轴的范围
plt.ylim(0, 100) # 限定纵轴的范围
plt.plot(result_x, result_y, marker='>', mec='r', mfc='w',label=u'Route')
plt.legend() # 让图例生效
plt.margins(0)
plt.subplots_adjust(bottom=0.15)
plt.xlabel(u"x") #X轴标签
plt.ylabel(u"y") #Y轴标签
plt.title("TSP Solution") #标题 plt.show()
plt.close(0) def solve(runtime=500):
getdistance()
setup()
for i in range(runtime):
get_candidate()
update_tabu() def TSA_TSP(runtime):
'''遗传算法、禁忌搜索算法和微粒群算法收敛速度的对比'''
getdistance()
setup()
a = []
for j in range(runtime):
get_candidate()
update_tabu()
a.append(best_distance)
return a def TSA_better(runtime):
'''遗传算法、禁忌搜索算法和微粒群算法收敛速度的对比'''
global tabu_limit
getdistance()
setup()
a = []
for j in range(runtime):
tabu_limit = int(100*(j/runtime)+1)
get_candidate()
update_tabu()
a.append(best_distance)
return a def main():
global city_x, city_y, distance, n, tabu_limit, tabu_list, tabu_time, current_tabu_num, candidate, candidate_distance
global best_route, best_distance, current_distance, current_route
if(1):
city_x = []
city_y = []
a = dict.values(city.china)
a = list(a)
for i in range(100):
city_x.append(a[i][0])
city_y.append(a[i][1])
# 城市数量
n = len(city_x)
distance = [[0 for col in range(n)] for raw in range(n)]
#禁忌表
tabu_list = []
tabu_time = []
#当前禁忌对象数量
current_tabu_num = 0
#禁忌长度,即禁忌期限
tabu_limit = 50
#候选集
candidate = [[0 for col in range(n)] for raw in range(200)]
candidate_distance = [0 for col in range(200)]
#最佳路径以及最佳距离
best_route = []
best_distance = sys.maxsize
current_route = []
current_distance = 0.0
getdistance()
setup()
k = 6
if k==1:
'''不同初始样本对结果的影响'''
init = []
x = []
y = []
for i in range(20):
print(i)
getdistance()
x.append(i)
init.append(setup(methods=2))
for epoch in range(500):
get_candidate()
update_tabu()
y.append(best_distance)
r,p = stats.pearsonr(init,y) # 相关系数和P值
print('相关系数r=%.3f,p值=%.3f'%(r,p))
plt.figure(figsize = (6,6)) # 图片像素大小
plt.scatter(init,y,color="blue") # 散点图绘制
plt.grid() # 显示网格线
plt.xlabel('init')
plt.ylabel('result')
plt.show() # 显示图片
plt.plot(x,init,color='blue',label='init_distance')
plt.plot(x,y,color='red',label='result_distance')
plt.xlabel('times')
plt.ylabel('distance')
plt.title('The effect of the initial route on the distance')
elif k==2:
'''禁忌表长度对于结果的影响'''
x = []
y = []
for i in range(10,200,10):
print(i)
distance = [[0 for col in range(n)] for raw in range(n)]
#禁忌表
tabu_list = []
tabu_time = []
#当前禁忌对象数量
current_tabu_num = 0
#候选集
candidate = [[0 for col in range(n)] for raw in range(200)]
candidate_distance = [0 for col in range(200)]
#最佳路径以及最佳距离
best_route = []
best_distance = sys.maxsize
current_route = []
current_distance = 0.0
getdistance()
setup()
tabu_limit = i # 禁忌长度
for j in range(2500):
get_candidate()
update_tabu()
x.append(i)
y.append(best_distance)
plt.plot(x,y)
plt.xlabel('Tabu_len')
plt.ylabel('distance')
plt.title('The effect of the length of tabu list on the distance')
elif k==3:
'''不同禁忌表长度的情况下的最佳迭代次数'''
x = []
y = []
for i in range(1,21):
distance = [[0 for col in range(n)] for raw in range(n)]
#禁忌表
tabu_list = []
tabu_time = []
#当前禁忌对象数量
current_tabu_num = 0
#候选集
candidate = [[0 for col in range(n)] for raw in range(200)]
candidate_distance = [0 for col in range(200)]
#最佳路径以及最佳距离
best_route = []
best_distance = sys.maxsize
current_route = []
current_distance = 0.0
getdistance()
setup()
tabu_limit = i*10
best = []
for epoch in range(25000):
get_candidate()
update_tabu()
best.append(best_distance)
if(epoch>500 and len(set(best[epoch-500:epoch]))==1):
break
x.append(tabu_limit)
y.append(epoch-500)
print(tabu_limit,epoch-500)
plt.plot(x,y)
plt.xlabel('tabu_len')
plt.ylabel('best_epochs')
plt.title('The best number of epochs in different length of tabu list')
elif k==4:
'''遗传算法与禁忌搜索算法在不同迭代次数上的比较'''
from 遗传TSP import GA_TSP
i = 500
epoch = [x for x in range(1,i+1)]
plt.plot(epoch,TSA_better(i),color='red',label='Better')
plt.plot(epoch,GA_TSP(epochs=i),color='blue',label='GA')
plt.plot(epoch,TSA_TSP(i),color='red',label='TSA')
plt.xlabel('epochs')
plt.ylabel('distance')
plt.title('The effect of the difference methods on the distance')
elif k==5:
'''禁忌长度自适应改进算法与标准算法的对比'''
i = 1500
epoch = [x for x in range(1,i+1)]
plt.plot(epoch,TSA_TSP(i),color='blue',label='Simple')
plt.plot(epoch,TSA_better(i),color='red',label='Better')
plt.xlabel('epochs')
plt.ylabel('distance')
plt.title('The different arithmetic')
elif k==6:
'''遗传算法与禁忌搜索算法在不同城市规模上的比较'''
epoch = []
GA = []
TSA = []
for scale in range(20,151,10):
from 遗传TSP import GA_TSP
city_x = []
city_y = []
a = dict.values(city.china)
a = list(a)
for i in range(scale):
city_x.append(a[i][0])
city_y.append(a[i][1])
# 城市数量
n = len(city_x)
distance = [[0 for col in range(n)] for raw in range(n)]
#禁忌表
tabu_list = []
tabu_time = []
#当前禁忌对象数量
current_tabu_num = 0
#禁忌长度,即禁忌期限
tabu_limit = 50
#候选集
candidate = [[0 for col in range(n)] for raw in range(200)]
candidate_distance = [0 for col in range(200)]
#最佳路径以及最佳距离
best_route = []
best_distance = sys.maxsize
current_route = []
current_distance = 0.0
getdistance()
setup()
epoch.append(scale)
TSA.append(min(TSA_better(1000)))
GA.append(min(GA_TSP(scale=scale,epochs=5000+scale*100)))
print(scale) plt.plot(epoch,GA,color='blue',label='GA')
plt.plot(epoch,TSA,color='red',label='TSA')
plt.xlabel('city_scale')
plt.ylabel('distance')
plt.title('The effect of the scale of cities on the distance') plt.legend()
plt.show() if __name__=="__main__":
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. 从 Airflow 到 Apache DolphinScheduler,有赞大数据开发平台的调度系统演进

    点击上方 蓝字关注我们 作者 | 宋哲琦 ✎ 编 者 按 在不久前的 Apache  DolphinScheduler Meetup 2021 上,有赞大数据开发平台负责人 宋哲琦 带来了平台调度系统 ...

  2. java-集合排序,队列,散列表map以及如何遍历

    1.1集合排序 可以通过集合的工具类java.util.Collections的静态方法sort需要注意的时,只能对List排序,因为它有序. Collections.sort(list); 排序字符 ...

  3. java学习第一天.day06

    方法 方法的优点 1. 使程序变得更简短而清晰. 2. 有利于程序维护. 3. 可以提高程序开发的效率. 4. 提高了代码的重用性. static的作用 static在方法中如果没有添加就只能用对象调 ...

  4. 定语从句关系代词只能用 that 的情况

    当先行词被形容词最高级.序数词,以及 the only.the very.the right 等修饰时,关系代词只能用 that. This is the most interesting movie ...

  5. Excel 运算符(一):算术运算符

    算术运算符用于最基本的加.减.乘.除运算. 运算符 含义 实例 结果 + 加法运算 =2+3 5 - 减法运算 =5-2 3 * 乘法运算 =5*2 10 / 除法运算 =4/2 2 % 百分数 =5 ...

  6. CAD二次开发---关于JoinEntity出现eNotApplicable的问题

    作者在使用JoinEntity时出现eNotApplicable的问题,查阅了Autodesk论坛的相关帖子,发现大多数人都有遇到这个问题,但没有找到合适的解决方法,可能原因是进行Join时两Curv ...

  7. [Golang] cgo 调用 .so 捕获异常问题

    最近需要在 go 中去调用 .so 库去完成一些事情,go 方面,利用 cgo 可以顺利的调用 .so 中的方法,但是有个问题是 go 没法捕获 .so 那边出现的异常.如果 .so 那边异常了,那么 ...

  8. 2-2 selenium IDE自动化实战

    Selenium IDE 自动化实战 任务1: 自动在百度搜索"我要自学网" 然后在搜索结果页面点击进入自学网主页 任务2 实现自学网自动登录个人账号 Test2017 12345 ...

  9. 虚拟机里做LUN映射(RHEL系统和centos系统皆可)(Linux版)

    紧接着Windows的LUN映射之后 参考 (https://www.cnblogs.com/zhengyan6/p/16121268.html) 先删除部分配置(没有做之前的LUN映射则不用) 进网 ...

  10. 微软出品自动化神器Playwright,不用写一行代码(Playwright+Java)系列(一) 之 环境搭建及脚本录制

    一.前言 半年前,偶然在视频号刷到某机构正在直播讲解Playwright框架的使用,就看了一会,感觉还不错,便被种草,就想着自己有时间也可以自己学一下,这一想着就半年多过去了. 读到这,你可能就去百度 ...