使用python禁忌搜索算法实现TSP旅行商问题

计算智能课程作业,使用python实现禁忌搜索算法实现TSP旅行商问题
问题简介:
给定一系列城市和每对城市之间的距离,求解访问每一座城市一次并回到起始城市的最短回路。它是组合优化中的一个NP困难问题。

代码如下:

#!/usr/bin/python
#_*_ coding:utf-8 _*_
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.mlab import dist
from matplotlib.artist import getp
import copy
from test.test__locale import candidate_locales
from cProfile import run#初始三十个城市坐标
city_x = [41,37,54,25,7,2,68,71,54,83,64,18,22,83,91,25,24,58,71,74,87,18,13,82,62,58,45,41,44,4]
city_y = [94,84,67,62,64,99,58,44,62,69,60,54,60,46,38,38,42,69,71,78,76,40,40,7,32,35,21,26,35,50]
#城市数量
n = 30
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.0def 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 = 0for i in range(n):for j in range(n):dis[j][id] = sys.maxsizeminvalue = min(dis[id])if i != 29:sum += minvaluevisited.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.0for i in range(n-1):sumdis += distance[rou[i]][rou[i+1]]sumdis += distance[rou[n-1]][rou[0]]     return sumdis#初始设置
def setup():global best_routeglobal best_distanceglobal tabu_timeglobal current_tabu_numglobal current_distanceglobal current_routeglobal tabu_list#得到初始解以及初始距离#current_route = random.sample(range(0, n), n) current_route = greedy()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#交换数组两个元素
def exchange(index1, index2, arr):current_list = copy.copy(arr)current = current_list[index1]current_list[index1] = current_list[index2]current_list[index2] = currentreturn current_list#得到邻域 候选解
def get_candidate():global best_routeglobal best_distanceglobal current_tabu_numglobal current_distanceglobal current_routeglobal 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:candidate_distance[temp] = cacl_best(candidate[temp])temp += 1if temp >= 200:break#得到候选解中的最优解candidate_best = min(candidate_distance)best_index = candidate_distance.index(candidate_best)current_distance = candidate_bestcurrent_route = copy.copy(candidate[best_index])#与当前最优解进行比较 if current_distance < best_distance:best_distance = current_distancebest_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_numglobal tabu_timeglobal tabu_listdel_num = 0temp = [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 += 1tabu_list[i] = tempcurrent_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():getdistance()runtime = int(input("迭代次数:"))setup()for rt in range(runtime):get_candidate()update_tabu()print("当前距离:")print(current_distance)print(current_route)print("最优距离:")    print(best_route)print(best_distance)draw()    if __name__=="__main__":solve()

实现效果

python用禁忌搜索算法实现TSP旅行商问题相关推荐

  1. 禁忌搜索算法求解TSP旅行商问题Matlab实现

    一. 禁忌搜索算法 禁忌搜索算法是一种全局性邻域搜索算法,模拟人类具有记忆功能的寻优特征.它通过局部邻域搜索机制和相应的禁忌准则来避免迂回搜索,并通过破禁水平来释放一些被禁忌的优良状态,进而保证多样化 ...

  2. 禁忌搜索算法求解TSP旅行商问题C++(2020.11.19)

    TS算法求解TSP问题C++ 1.禁忌搜索算法 1.1 基本思想及主要特点 1.2 基本概念 1.3 算法流程 2. TS求解TSP问题的C++实现 2.1 输入数据文件:bayg29.tsp 2.2 ...

  3. 实验10 禁忌搜索算法求解tsp问题

    传送门(所有的实验都使用python实现) 实验1 BP神经网络实验 实验2 som网实验 实验3 hopfield实现八皇后问题 实验4 模糊搜索算法预测薄冰厚度 实验5 遗传算法求解tsp问题 实 ...

  4. 领域搜索算法java_使用JAVA实现算法——禁忌搜索算法解决TSP问题

    packageBasePart;importjava.io.BufferedReader;importjava.io.FileInputStream;importjava.io.IOException ...

  5. 遗传-粒子群算法遗传-禁忌搜索算法求解TSP问题

    1. 前言 上一篇博文[五种常见启发式算法求解TSP问题-总结篇]中,总结了五种常见启发式算法在求解TSP问题上的效果,其中遗传算法的求解质量最差,而粒子群算法和禁忌搜索算法的求解效果最佳,因此本文计 ...

  6. 禁忌搜索算法解决TSP问题

    禁忌搜索算法解决TSP问题 流程图 数据集 关键要素 代码 部分结果展示 流程图 数据集 att48.tsp.eil76.tsp.lin105.tsp[下载链接] 关键要素 初始解产生:采用基于最近邻 ...

  7. 基于改进禁忌搜索算法求解TSP问题(Matlab代码实现)

    目录 1 概述 2 改进禁忌搜索算法 3 运行结果 4 参考文献 5 Matlab代码实现 1 概述 当城市数量较少时,理论上可以通过穷举法来列举出最优方案,然而当城市数量较多时,所有路线之和将呈指数 ...

  8. 禁忌搜索算法实例——TSP

    算法思想 禁忌搜索算法的两大核心就是渴望水平和禁忌表,即Tabu表.通过禁止之前的产生新解得操作从而避免落入局部最优的概率,同时算法还应有一个渴望水平,也就是迭代过程中最优水平,一旦新解超过最优水平, ...

  9. 基于禁忌搜索算法的TSP问题求解matlab仿真

    目录 1.算法概述 2.仿真效果 3.matlab仿真源码 1.算法概述 禁忌搜索(Tabu Search,TS)算法是组合优化算法的一种,是局部搜索算法的扩展.禁忌搜索算法是人工智能在组合优化算法中 ...

最新文章

  1. delphi开发的小技巧----------------http://www.cto360.com/a/5000086716.shtml
  2. js 删除对象某个属性_JS里的数据类型
  3. 开始使用vue.js
  4. android 画布控件,Android canvas画图操作之切割画布实现方法(clipRect)
  5. Java 微服务框架对比:Dubbo 和 Spring Cloud
  6. 后端根据百度地图真实路径距离_百度地图开放平台介绍--路线规划
  7. 基于神念TGAM的脑波小车(1)
  8. cocos2d Labels and Fonts 标签和字体
  9. 1、BimRevit 二次开发配置和环境搭建
  10. matlab前馈仿真,前馈-反馈控制系统的具体分析及其MATLAB/Simulink.PDF
  11. 奥维互动地图自建服务器,免费开通奥维互动地图企业服务器
  12. C# amr转mp3 (ffmpeg)
  13. 服务器显示器无法调节分辨率,显示器无法设置分辨率怎么办
  14. [Vue warn]: You may have an infinite update loop in watcher with express
  15. 汉诺塔问题的递归求解
  16. 利用beef盗取浏览器cookie,并实现页面跳转
  17. 使用you-get工具下载MP4视频
  18. Qt Qml 开发超高清视频回放监控客户端
  19. 新近手机测试工具速递
  20. shell 脚本处理多行文本的记录 -- awk

热门文章

  1. JdbcTemplate查询与批量更新
  2. 如何长高在青春期 - 它可以是实际上可提高你的身高在青春期
  3. MySql Povit_MySQL pivot row成动态列数
  4. Mysql间隙锁实战
  5. STM32启动文件的分析
  6. 朱有鹏嵌入式核心课程路线图
  7. 依据经度纬度计算距离方式
  8. MatLab画贝塞尔函数曲线
  9. Mathematica入门教程
  10. linux切换用户报错timeout,Linux切换用户卡