1 importnumpy as np2 importmatplotlib.pyplot as plt3

4

5 #建立“蚂蚁”类

6 classAnt(object):7 def __init__(self, path):8 self.path = path #蚂蚁当前迭代整体路径

9 self.length = self.calc_length(path) #蚂蚁当前迭代整体路径长度

10

11 def calc_length(self, path_): #path=[A, B, C, D, A]注意路径闭环

12 length_ =013 for i in range(len(path_)-1):14 delta = (path_[i].x - path_[i+1].x, path_[i].y - path_[i+1].y)15 length_ +=np.linalg.norm(delta)16 returnlength_17

18 @staticmethod19 def calc_len(A, B): #静态方法,计算城市A与城市B之间的距离

20 return np.linalg.norm((A.x - B.x, A.y -B.y))21

22

23 #建立“城市”类

24 classCity(object):25 def __init__(self, x, y):26 self.x =x27 self.y =y28

29

30 #建立“路径”类

31 classPath(object):32 def __init__(self, A): #A为起始城市

33 self.path =[A, A]34

35 def add_path(self, B): #追加路径信息,方便计算整体路径长度

36 self.path.append(B)37 self.path[-1], self.path[-2] = self.path[-2], self.path[-1]38

39

40 #构建“蚁群算法”的主体

41 classACO(object):42 def __init__(self, ant_num=50, maxIter=300, alpha=1, beta=5, rho=0.1, Q=1):43 self.ants_num = ant_num #蚂蚁个数

44 self.maxIter = maxIter #蚁群最大迭代次数

45 self.alpha = alpha #信息启发式因子

46 self.beta = beta #期望启发式因子

47 self.rho = rho #信息素挥发速度

48 self.Q = Q #信息素强度

49 ###########################

50 self.deal_data('coordinates.dat') #提取所有城市的坐标信息

51 ###########################

52 self.path_seed = np.zeros(self.ants_num).astype(int) #记录一次迭代过程中每个蚂蚁的初始城市下标

53 self.ants_info = np.zeros((self.maxIter, self.ants_num)) #记录每次迭代后所有蚂蚁的路径长度信息

54 self.best_path = np.zeros(self.maxIter) #记录每次迭代后整个蚁群的“历史”最短路径长度

55 ###########################

56 self.solve() #完成算法的迭代更新

57 self.display() #数据可视化展示

58

59 defdeal_data(self, filename):60 with open(filename, 'rt') as f:61 temp_list = list(line.split() for line in f) #临时存储提取出来的坐标信息

62 self.cities_num = len(temp_list) #1. 获取城市个数

63 self.cities = list(City(float(item[0]), float(item[1])) for item in temp_list) #2. 构建城市列表

64 self.city_dist_mat = np.zeros((self.cities_num, self.cities_num)) #3. 构建城市距离矩阵

65 for i inrange(self.cities_num):66 A =self.cities[i]67 for j inrange(i, self.cities_num):68 B =self.cities[j]69 self.city_dist_mat[i][j] = self.city_dist_mat[j][i] =Ant.calc_len(A, B)70 self.phero_mat = np.ones((self.cities_num, self.cities_num)) #4. 初始化信息素矩阵

71 #self.phero_upper_bound = self.phero_mat.max() * 1.2 ###信息素浓度上限

72 self.eta_mat = 1/(self.city_dist_mat + np.diag([np.inf]*self.cities_num)) #5. 初始化启发函数矩阵

73

74 defsolve(self):75 iterNum = 0 #当前迭代次数

76 while iterNum <77 self.random_seed>

78 delta_phero_mat = np.zeros((self.cities_num, self.cities_num)) #初始化每次迭代后信息素矩阵的增量

79 ##########################################################################

80 for i inrange(self.ants_num):81 city_index1 = self.path_seed[i] #每只蚂蚁访问的第一个城市下标

82 ant_path = Path(self.cities[city_index1]) #记录每只蚂蚁访问过的城市

83 tabu = [city_index1] #记录每只蚂蚁访问过的城市下标,禁忌城市下标列表

84 non_tabu = list(set(range(self.cities_num)) -set(tabu))85 for j in range(self.cities_num-1): #对余下的城市进行访问

86 up_proba = np.zeros(self.cities_num-len(tabu)) #初始化状态迁移概率的分子

87 for k in range(self.cities_num-len(tabu)):88 up_proba[k] = np.power(self.phero_mat[city_index1][non_tabu[k]], self.alpha) *\89 np.power(self.eta_mat[city_index1][non_tabu[k]], self.beta)90 proba = up_proba/sum(up_proba) #每条可能子路径上的状态迁移概率

91 while True: #提取出下一个城市的下标

92 random_num =np.random.rand()93 index_need = np.where(proba >random_num)[0]94 if len(index_need) >0:95 city_index2 =non_tabu[index_need[0]]96 break

97 ant_path.add_path(self.cities[city_index2])98 tabu.append(city_index2)99 non_tabu = list(set(range(self.cities_num)) -set(tabu))100 city_index1 =city_index2101 self.ants_info[iterNum][i] =Ant(ant_path.path).length102 if iterNum == 0 and i == 0: #完成对最佳路径城市的记录

103 self.best_cities =ant_path.path104 else:105 if self.ants_info[iterNum][i] < Ant(self.best_cities).length: self.best_cities =ant_path.path106 tabu.append(tabu[0]) #每次迭代完成后,使禁忌城市下标列表形成完整闭环

107 for l inrange(self.cities_num):108 delta_phero_mat[tabu[l]][tabu[l+1]] += self.Q/self.ants_info[iterNum][i]109

110 self.best_path[iterNum] =Ant(self.best_cities).length111

112 self.update_phero_mat(delta_phero_mat) #更新信息素矩阵

113 iterNum += 1

114

115 defupdate_phero_mat(self, delta):116 self.phero_mat = (1 - self.rho) * self.phero_mat +delta117 #self.phero_mat = np.where(self.phero_mat > self.phero_upper_bound, self.phero_upper_bound, self.phero_mat) # 判断是否超过浓度上限

118

119 def random_seed(self): #产生随机的起始点下表,尽量保证所有蚂蚁的起始点不同

120 if self.ants_num <= self.cities_num: #蚂蚁数 <= 城市数

121 self.path_seed[:] =np.random.permutation(range(self.cities_num))[:self.ants_num]122 else: #蚂蚁数 > 城市数

123 self.path_seed[:self.cities_num] =np.random.permutation(range(self.cities_num))124 temp_index =self.cities_num125 while temp_index + self.cities_num <=self.ants_num:126 self.path_seed[temp_index:temp_index + self.cities_num] =np.random.permutation(range(self.cities_num))127 temp_index +=self.cities_num128 temp_left = self.ants_num %self.cities_num129 if temp_left !=0:130 self.path_seed[temp_index:] =np.random.permutation(range(self.cities_num))[:temp_left]131

132 def display(self): #数据可视化展示

133 plt.figure(figsize=(6, 10))134 plt.subplot(211)135 plt.plot(self.ants_info, 'g.')136 plt.plot(self.best_path, 'r-', label='history_best')137 plt.xlabel('Iteration')138 plt.ylabel('length')139 plt.legend()140 plt.subplot(212)141 plt.plot(list(city.x for city in self.best_cities), list(city.y for city in self.best_cities), 'g-')142 plt.plot(list(city.x for city in self.best_cities), list(city.y for city in self.best_cities), 'r.')143 plt.xlabel('x')144 plt.ylabel('y')145 plt.savefig('ACO.png', dpi=500)146 plt.show()147 plt.close()148

149

150 ACO()

77>

python蚁群算法 路径规划_蚁群算法(1) - Python实现相关推荐

  1. 机器人路径规划_人工蜂群算法

    机器人路径规划_人工蜂群算法 原理 ABC(Artificial BeesColony)算法最先由Basturk等人提出并应用于函数优化问题,蜂群采蜜行为与函数优化问题对应关系如表1所示.由表1可知, ...

  2. matlab蚁群算法 路径规划,基于蚁群算法的机器人路径规划MATLAB源码

    基于蚁群算法的机器人路径规划MA TLAB源码 使用网格离散化的方法对带有障碍物的环境建模,使用邻接矩阵存储该环境,使得问题转化为蚁群算法寻找最短路径. function [ROUTES,PL,Tau ...

  3. python蚁群算法路径规划_使用python实现蚁群算法

    此次使用python实现蚁群算法是仿照蚁群优化算法的JAVA实现中的蚁群算法实现方法,使用的也是其中的数据(此处为上传数据),如需更深一步了解蚁群算法原理和具体实现过程,请参考蚁群优化算法的JAVA实 ...

  4. 多目标蚁群算法路径规划(四)------多目标约束过程常规流程框架

    多目标蚁群算法路径规划(四) 文章目录 多目标蚁群算法路径规划(四) 零.系列前言(一定要看) 一.内容说明 1.1 本章内容说明 1.2 本章主要分享内容简介(摘要) 二. 多目标计算预先准备 2. ...

  5. 【Matlab路径规划】蚁群算法机器人大规模栅格地图最短路径规划【含源码 1860期】

    一.代码运行视频(哔哩哔哩) [Matlab路径规划]蚁群算法机器人大规模栅格地图最短路径规划[含源码 1860期] 二.蚁群算法及栅格地图简介 随着机器人技术在诸多领域的应用, 如机器人协作焊接.灾 ...

  6. 基于MATLAB GUI的蚁群算法路径规划实现电动汽车充电站与换电站协调

    基于MATLAB GUI的蚁群算法路径规划实现电动汽车充电站与换电站协调 摘要: 随着电动汽车的普及和发展,电动汽车充电站与换电站的布局和规划变得尤为重要.本文基于MATLAB GUI平台,结合蚁群算 ...

  7. 【Matlab路径规划】蚁群算法求解机器人栅格地图最短路径规划问题【含源码 1580期】

    一.代码运行视频(哔哩哔哩) [Matlab路径规划]蚁群算法求解机器人栅格地图最短路径规划问题[含源码 1580期] 二.matlab版本及参考文献 1 matlab版本 2014a 2 参考文献 ...

  8. 【路径规划】(1) Dijkstra 算法求解最短路,附python完整代码

    好久不见,我又回来了,这段时间把路径规划的一系列算法整理一下,感兴趣的点个关注.今天介绍一下机器人路径规划算法中最基础的 Dijkstra 算法,文末有 python 完整代码,那我们开始吧. 1. ...

  9. 算法学习之模拟退火算法路径规划(python代码实现)

    模拟退火算法路径规划(python代码实现) 一.引言 二.算法介绍以及伪代码 1.算法通俗介绍 2.路径规划算法伪代码 三.算法流程及代码实现 1.地图创建 2.初始化路径 小结 3.计算适应度值 ...

最新文章

  1. JS---设计简易日历
  2. Android Service下载文件并自定义通知提示下载
  3. C语言成绩abc,C语言常用经典代码:求三角形的面积、把百分制成绩转换为ABC等级制、其两个自然数的最大公约数和最小公倍数...
  4. python函数装饰器参数 参数_【转】python 装饰器功能以及函数参数使用
  5. boost::fusion::traits::deduce_sequence用法的测试程序
  6. 交换机的特点及工作原理
  7. 一元线性回归决定系数_回归分析|笔记整理(1)——引入,一元线性回归(上)...
  8. 诗与远方:无题(二十)
  9. json 解析_json爬坑1:yajl解析json
  10. mysql relay log参数汇总
  11. 我的double array trie
  12. android期末课设选题_Android课程设计报告书.doc
  13. js基础之六种继承方式
  14. 数学分析教程(科大)——6.4笔记+习题
  15. 【英语语法入门】第04讲 代词的主格和宾格
  16. yaourt/yay 安装软件出现 parse “XXX“: first path segment in URL cannot contain colon 错误
  17. ArcGIS Pro 3.0学习版安装教程
  18. 关于笔试遇到的题 1
  19. 怎么制作升温曲线图_炉温曲线图是怎么看的啊!
  20. iOS多级列表 - XQMultistageTableView

热门文章

  1. MySQL普通索引与唯一索引__mysql中唯一索引和普通索引的用途及区别
  2. vue 调用webservice_js跨域调用WebService的简单实例
  3. 查看论坛隐藏链接_软连接与硬链接的区别
  4. DOM操作获取标签方法、数据类型
  5. python一个函数调用另一个函数的返回值_在python函数中使用True,False和None作为返回值...
  6. updatepanel失效怎么办_【点滴积累】解决jQuery绑定事件在updatepanel更新后失效的方法...
  7. python转二进制字符串_python如何将二进制串(UTF-8)转换为字符串?
  8. 服务器主机启动不显示,服务器主机不启动怎么回事
  9. c语言各个英文的作用,C语言最重要的知识点复习资料(国外英文资料).doc
  10. adb server is out of date. linux,adb server is out of date. killing完美解决