当前位置:   article > 正文

各类路径规划算法python 代码_python全覆盖路径规划模板

python全覆盖路径规划模板

一、人工势场法

  1. # 初始化参数设置
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. import copy
  5. from celluloid import Camera # 保存动图时用,pip install celluloid
  6. %matplotlib qt5
  7. ## 初始化车的参数
  8. d = 3.5 #道路标准宽度
  9. W = 1.8 # 汽车宽度
  10. L = 4.7 # 车长
  11. P0 = np.array([0, - d / 2, 1, 1]) #车辆起点位置,分别代表x,y,vx,vy
  12. Pg = np.array([99, d / 2, 0, 0]) # 目标位置
  13. # 障碍物位置
  14. Pobs = np.array([
  15. [15, 7 / 4, 0, 0],
  16. [30, - 3 / 2, 0, 0],
  17. [45, 3 / 2, 0, 0],
  18. [60, - 3 / 4, 0, 0],
  19. [80, 3/2, 0, 0]])
  20. P = np.vstack((Pg,Pobs)) # 将目标位置和障碍物位置合放在一起
  21. Eta_att = 5 # 引力的增益系数
  22. Eta_rep_ob = 15 # 斥力的增益系数
  23. Eta_rep_edge = 50 # 道路边界斥力的增益系数
  24. d0 = 20 # 障碍影响的最大距离
  25. num = P.shape[0] #障碍与目标总计个数
  26. len_step = 0.5 # 步长
  27. n=1
  28. Num_iter = 300 # 最大循环迭代次数
  29. # 数据存储变量定义
  30. path = [] # 保存车走过的每个点的坐标
  31. delta = np.zeros((num,2)) # 保存车辆当前位置与障碍物的方向向量,方向指向车辆;以及保存车辆当前位置与目标点的方向向量,方向指向目标点
  32. dists = [] # 保存车辆当前位置与障碍物的距离以及车辆当前位置与目标点的距离
  33. unite_vec = np.zeros((num,2)) # 保存车辆当前位置与障碍物的单位方向向量,方向指向车辆;以及保存车辆当前位置与目标点的单位方向向量,方向指向目标点
  34. F_rep_ob = np.zeros((len(Pobs),2)) # 存储每一个障碍到车辆的斥力,带方向
  35. v=np.linalg.norm(P0[2:4]) # 设车辆速度为常值
  36. ## ***************初始化结束,开始主体循环******************人工势场法核心代码
  37. Pi = P0[0:2] # 当前车辆位置
  38. # count=0
  39. for i in range(Num_iter):
  40. if ((Pi[0] - Pg[0]) ** 2 + (Pi[1] - Pg[1]) ** 2) ** 0.5 < 1:
  41. break
  42. dists=[]
  43. path.append(Pi)
  44. # print(count)
  45. # count+=1
  46. #计算车辆当前位置与障碍物的单位方向向量
  47. for j in range(len(Pobs)):
  48. delta[j]=Pi[0:2] - Pobs[j, 0:2]
  49. dists.append(np.linalg.norm(delta[j]))
  50. unite_vec[j]=delta[j]/dists[j]
  51. #计算车辆当前位置与目标的单位方向向量
  52. delta[len(Pobs)]=Pg[0:2] - Pi[0:2]
  53. dists.append(np.linalg.norm(delta[len(Pobs)]))
  54. unite_vec[len(Pobs)] = delta[len(Pobs)]/dists[len(Pobs)]
  55. ## 计算引力
  56. F_att = Eta_att*dists[len(Pobs)]*unite_vec[len(Pobs)]
  57. ## 计算斥力
  58. # 在原斥力势场函数增加目标调节因子(即车辆至目标距离),以使车辆到达目标点后斥力也为0
  59. for j in range(len(Pobs)):
  60. if dists[j] >= d0:
  61. F_rep_ob[j] = np.array([0, 0])
  62. else:
  63. # 障碍物的斥力1,方向由障碍物指向车辆
  64. F_rep_ob1_abs = Eta_rep_ob * (1 / dists[j] - 1 / d0) * (dists[len(Pobs)])**n / dists[j] ** 2 # 斥力大小
  65. F_rep_ob1 = F_rep_ob1_abs*unite_vec[j] # 斥力向量
  66. # 障碍物的斥力2,方向由车辆指向目标点
  67. F_rep_ob2_abs = n/2 * Eta_rep_ob * (1 / dists[j] - 1 / d0) **2 *(dists[len(Pobs)])**(n-1) # 斥力大小
  68. F_rep_ob2 = F_rep_ob2_abs * unite_vec[len(Pobs)] # 斥力向量
  69. # 改进后的障碍物合斥力计算
  70. F_rep_ob[j] = F_rep_ob1 + F_rep_ob2
  71. # 增加道路边界斥力势场,根据车辆当前位置,选择对应的斥力函数
  72. if Pi[1] > - d + W / 2 and Pi[1] <= - d / 2:
  73. F_rep_edge = [0, Eta_rep_edge * v * np.exp(-d / 2 - Pi[1])] # 下道路边界区域斥力势场,方向指向y轴正向
  74. elif Pi[1] > - d / 2 and Pi[1] <= - W / 2:
  75. F_rep_edge = np.array([0, 1 / 3 * Eta_rep_edge * Pi[1] ** 2])
  76. elif Pi[1] > W / 2 and Pi[1] <= d / 2:
  77. F_rep_edge = np.array([0, - 1 / 3 * Eta_rep_edge * Pi[1] ** 2])
  78. elif Pi[1] > d / 2 and Pi[1] <= d - W / 2:
  79. F_rep_edge = np.array([0, Eta_rep_edge * v * (np.exp(Pi[1] - d / 2))])
  80. ## 计算合力和方向
  81. F_rep = np.sum(F_rep_ob, axis=0)+F_rep_edge
  82. F_sum = F_att+F_rep
  83. UnitVec_Fsum = 1 / np.linalg.norm(F_sum) * F_sum
  84. #计算车的下一步位置
  85. Pi = copy.deepcopy(Pi+ len_step * UnitVec_Fsum)
  86. # Pi[0:2] = Pi[0:2] + len_step * UnitVec_Fsum
  87. # print(Pi)
  88. path.append(Pg[0:2]) # 最后把目标点也添加进路径中
  89. path=np.array(path) # 转为numpy
  90. ## 画图
  91. fig=plt.figure(1)
  92. # plt.ylim(-4, 4)
  93. plt.axis([-10,100,-15,15])
  94. camera = Camera(fig)
  95. len_line = 100
  96. # 画灰色路面图
  97. GreyZone = np.array([[- 5, - d - 0.5], [- 5, d + 0.5],
  98. [len_line, d + 0.5], [len_line, - d - 0.5]])
  99. for i in range(len(path)):
  100. plt.fill(GreyZone[:, 0], GreyZone[:, 1], 'gray')
  101. plt.fill(np.array([P0[0], P0[0], P0[0] - L, P0[0] - L]), np.array([- d /
  102. 2 - W / 2, - d / 2 + W / 2, - d / 2 + W / 2, - d / 2 - W / 2]), 'b')
  103. # 画分界线
  104. plt.plot(np.array([- 5, len_line]), np.array([0, 0]), 'w--')
  105. plt.plot(np.array([- 5, len_line]), np.array([d, d]), 'w')
  106. plt.plot(np.array([- 5, len_line]), np.array([- d, - d]), 'w')
  107. # 设置坐标轴显示范围
  108. # plt.axis('equal')
  109. # plt.gca().set_aspect('equal')
  110. # 绘制路径
  111. plt.plot(Pobs[:,0],Pobs[:,1], 'ro') #障碍物位置
  112. plt.plot(Pg[0],Pg[1], 'gv') # 目标位置
  113. plt.plot(P0[0],P0[1], 'bs') # 起点位置
  114. # plt.cla()
  115. plt.plot(path[0:i,0],path[0:i,1], 'k') # 路径点
  116. plt.pause(0.001)
  117. # camera.snap()
  118. # animation = camera.animate()
  119. # animation.save('trajectory.gif')

参考:https://blog.csdn.net/weixin_42301220/article/details/125155505

二、D*算法

  1. # 首次搜索
  2. # coding=utf-8
  3. import matplotlib.pyplot as plt
  4. import numpy as np
  5. import math
  6. map_grid = [[1 for j in range(0, 8)] for i in range(0, 8)] # 定义列表
  7. map_grid = np.array(map_grid) # 将列表转化为数组,因为只有数组才有维度的概念,方便切片
  8. map_grid[3:6, 1] = 0 # 障碍物
  9. map_grid[3:6, 5] = 0
  10. map_grid[0, 3] = 5 # 起点
  11. map_grid[7, 3] = 6 # 终点
  12. def draw_effect(map_grid,second_path):
  13. plt.imshow(map_grid, cmap=plt.cm.hot, interpolation='nearest', vmin=0, vmax=10) # 绘制热力图
  14. plt.colorbar()
  15. plt.xlim(-1, 8) # x轴的范围
  16. plt.ylim(-1, 8)
  17. my_x_ticks = np.arange(0, 8, 1) # x轴标号的范围
  18. my_y_ticks = np.arange(0, 8, 1)
  19. plt.xticks(my_x_ticks)
  20. plt.yticks(my_y_ticks)
  21. second_path = np.array(second_path)
  22. plt.plot(second_path[:, 1:2],second_path[:, 0:1],'-')
  23. # plt.grid(True) # 开启栅格 可以不开启
  24. plt.show() # 可视化
  25. open_list = [[7, 3, 0, 0, None, None]] # 将终点置于open列表中列表中分别有x0,y0坐标,h值,父节点X、Y坐标
  26. close_list = []
  27. # draw_effect(map_grid)
  28. # 将邻域放入open_list中
  29. def open_list_append(x0, y0, x1, y1, h0, h1, map_grid, open_list):
  30. if 0 <= x1 <= 7 and 0 <= y1 <= 7 and map_grid[x1, y1] != 4 and map_grid[x1, y1] != 0: # 左边没有越界并且没有在closelist里面
  31. if map_grid[x1, y1] == 3: # 如果是在open_list中,h要更新
  32. open_list = np.array(open_list)
  33. if (h1 + h0) < open_list[np.where((open_list[:, 0] == x1) & (open_list[:, 1] == y1)), 2]:
  34. h = h1 + h0
  35. k = h1 + h0
  36. open_list[np.where((open_list[:, 0] == x1) & (open_list[:, 1] == y1)), 2] = h
  37. open_list[np.where((open_list[:, 0] == x1) & (open_list[:, 1] == y1)), 3] = k
  38. open_list[np.where((open_list[:, 0] == x1) & (open_list[:, 1] == y1)), 4] = x0
  39. open_list[np.where((open_list[:, 0] == x1) & (open_list[:, 1] == y1)), 4] = y0
  40. open_list = list(open_list.tolist())
  41. else: # 是new节点
  42. h = h1 + h0
  43. k = h1 + h0
  44. # open_list = list(open_list)
  45. open_list.append([x1, y1, h, k, x0, y0])
  46. map_grid[x1, y1] = 3
  47. return open_list
  48. # 首次搜索
  49. def first_search(open_list, close_list, map_grid): # 给出终点坐标,完成首次遍历
  50. # 采用D算法遍历
  51. # 选openlist中h最小的,将openlist按照h排序,取第一个,并删除第一个,将它放到close_list里面
  52. open_list = list(open_list)
  53. open_list.sort(key=lambda x: x[2])
  54. # open_list.pop(0)
  55. insert_list = open_list[0] # 引入中间列表,用来存储每一次被选中的遍历的点
  56. x0 = int(insert_list[0])
  57. y0 = int(insert_list[1])
  58. open_list.pop(0)
  59. close_list.append(list(insert_list))
  60. map_grid[x0, y0] = 4 # 被加入到close_list里面
  61. # 找insert_list的邻域 ----->寻找顺序:从左边开始逆时针
  62. h0 = int(insert_list[2])
  63. x1 = x0
  64. y1 = y0 - 1
  65. h1 = 10
  66. open_list = open_list_append(x0, y0, x1, y1, h0, h1, map_grid, open_list)
  67. x1 = x0 - 1
  68. y1 = y0 - 1
  69. h1 = 14
  70. open_list = open_list_append(x0, y0, x1, y1, h0, h1, map_grid, open_list)
  71. x1 = x0 - 1
  72. y1 = y0
  73. h1 = 10
  74. open_list = open_list_append(x0, y0, x1, y1, h0, h1, map_grid, open_list)
  75. x1 = x0 - 1
  76. y1 = y0 + 1
  77. h1 = 14
  78. open_list = open_list_append(x0, y0, x1, y1, h0, h1, map_grid, open_list)
  79. x1 = x0
  80. y1 = y0 + 1
  81. h1 = 10
  82. open_list = open_list_append(x0, y0, x1, y1, h0, h1, map_grid, open_list)
  83. x1 = x0 + 1
  84. y1 = y0 + 1
  85. h1 = 14
  86. open_list = open_list_append(x0, y0, x1, y1, h0, h1, map_grid, open_list)
  87. x1 = x0 + 1
  88. y1 = y0
  89. h1 = 10
  90. open_list = open_list_append(x0, y0, x1, y1, h0, h1, map_grid, open_list)
  91. x1 = x0 + 1
  92. y1 = y0 - 1
  93. h1 = 14
  94. open_list = open_list_append(x0, y0, x1, y1, h0, h1, map_grid, open_list)
  95. return [open_list, close_list, map_grid]
  96. while map_grid[0, 3] != 4 and open_list != []:
  97. [open_list, close_list, map_grid] = first_search(open_list, close_list, map_grid)
  98. # 首次搜索完成
  99. first_path = []
  100. close_list = np.array(close_list)
  101. xn = 0
  102. yn = 3
  103. while xn != 7 or yn != 3:
  104. list1 = list(close_list[np.where((close_list[:, 0] == xn) & (close_list[:, 1] == yn))][0])
  105. xn = int(list1[4])
  106. yn = int(list1[5])
  107. first_path.append(list1)
  108. first_path.append([7, 3, 0, 0, None, None])
  109. # 第二次搜索
  110. # 通过上面的程序已经找到了一条路径,完成了第一次的搜索,此时每个节点的h和k是相等的。此时开始点在close list里面,最短路径在firstpath中。
  111. # 可以看出,每个节点的父节点都是该节点的八个邻节点中k值最小的哪个。
  112. # 当出现动态变化时,我们可以利用这个图尽快修正我们的路径,而不是重新规划。
  113. # 当我们检测到某点被阻碍了:1、修改这个点的h值,h变为inf,把它放入openlist中。注意此时该节点的k还是小值,是原来哪个h的值,因此它将立即被取出
  114. # 2、把这个修改扩散出去,直到kmin >=h
  115. # 设置一个突然出现的障碍
  116. map_grid[3, 3] = 0
  117. close_list[np.where((close_list[:, 4] == 3) & (close_list[:, 5] == 3)), 2] = math.inf
  118. close_list[np.where((close_list[:, 0] == 3) & (close_list[:, 1] == 3)), 2] = math.inf
  119. insertRow = list(close_list[np.where((close_list[:, 4] == 3) & (close_list[:, 5] == 3))][0])
  120. x = int(insertRow[0])
  121. y = int(insertRow[1])
  122. open_list.append(insertRow) # ->>>>>>open_list是列表格式
  123. map_grid[x, y] = 3
  124. close_list = list(close_list.tolist()) # ----->>>>>close_list是列表格式
  125. close_list.remove(insertRow)
  126. open_list.sort(key=lambda x: x[3]) # 先排序,选择k最小的节点
  127. k_min = open_list[0][3] #
  128. hx = open_list[0][2]
  129. # 接下来把这个点扩散出去
  130. def find_neighbor(x0, y0, x1, y1, k_old, hx, h1, close_list):
  131. close_list = np.array(close_list)
  132. hy = close_list[np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1)), 2][0]
  133. if (hy <= k_old) and (hx > hy + h1):
  134. close_list[np.where((close_list[:, 0] == x0) & (close_list[:, 1] == y0)), 4] = x1
  135. close_list[np.where((close_list[:, 0] == x0) & (close_list[:, 1] == y0)), 5] = y1
  136. close_list[np.where((close_list[:, 0] == x0) & (close_list[:, 1] == y0)), 2] = hy + h1
  137. hx = hy + h1
  138. return [hx, list(close_list.tolist())]
  139. def find_neighbor2(x0, y0, x1, y1, k_old, hx, h1, close_list, open_list, map_grid):
  140. close_list = np.array(close_list)
  141. hy = close_list[np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1)), 2][0]
  142. if (close_list[np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1)), 4] == x0 and close_list[
  143. np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1)), 5] == y0 and (hy != hx + h1)) or (
  144. (hy > hx + h1) and (
  145. (close_list[np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1)), 4] != x0) or (
  146. close_list[np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1)), 5] != y0))):
  147. close_list[np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1)), 4] = x0
  148. close_list[np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1)), 5] = y0
  149. close_list[np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1)), 2] = hx + h1
  150. Y = list(close_list[np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1))][0])
  151. # 把Y放入open_list中
  152. close_list = list(close_list.tolist())
  153. close_list.remove(Y)
  154. open_list.append(Y)
  155. map_grid[x1, y1] = 3
  156. return [open_list, close_list, map_grid]
  157. def find_neighbor3(x0, y0, x1, y1, k_old, hx, h1, close_list, open_list, map_grid):
  158. close_list = np.array(close_list)
  159. hy = close_list[np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1)), 2][0]
  160. if (close_list[np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1)), 4] == x0 and close_list[
  161. np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1)), 5] == y0 and (hy != hx + h1)):
  162. close_list[np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1)), 4] = x0
  163. close_list[np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1)), 5] = y0
  164. close_list[np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1)), 2] = hx + h1
  165. Y = list(close_list[np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1))][0])
  166. # 把Y放入open_list中
  167. close_list = list(close_list.tolist())
  168. close_list.remove(Y)
  169. open_list.append(Y)
  170. map_grid[x1, y1] = 3
  171. else:
  172. if ((close_list[np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1)), 4] != x0 or close_list[
  173. np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1)), 5] != y0) and (hy > hx + h1)):
  174. #print(list(close_list[np.where((close_list[:, 0] == x0) & (close_list[:, 1] == y0))][0]))
  175. if map_grid[x0,y0]!=3:
  176. X = list(close_list[np.where((close_list[:, 0] == x0) & (close_list[:, 1] == y0))][0])
  177. close_list = list(close_list.tolist())
  178. close_list.remove(X)
  179. open_list.append(X)
  180. else:
  181. open_list = np.array(open_list)
  182. X = list(open_list[np.where((open_list[:, 0] == x0) & (open_list[:, 1] == y0))][0])
  183. open_list = list(open_list.tolist())
  184. # # 把Y放入open_list中
  185. map_grid[x0, y0] = 3
  186. else:
  187. if ((close_list[np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1)), 4] != x0 or close_list[
  188. np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1)), 5] != y0) and (hx > hy + h1)) and \
  189. map_grid[x1, y1] == 4 and hy > k_old:
  190. if map_grid[x1, y1] != 3:
  191. Y = list(close_list[np.where((close_list[:, 0] == x1) & (close_list[:, 1] == y1))][0])
  192. close_list = list(close_list.tolist())
  193. close_list.remove(Y)
  194. open_list.append(Y)
  195. else:
  196. open_list = np.array(open_list)
  197. Y = list(open_list[np.where((open_list[:, 0] == x1) & (open_list[:, 1] == y1))][0])
  198. open_list = list(open_list.tolist())
  199. # 把Y放入open_list中
  200. map_grid[x1, y1] = 3
  201. return [open_list, close_list, map_grid]
  202. # 扩散程序 process-state:先弹出openlist列表中k最小的节点,并删除这个节点。然后分类处理:
  203. def process_state(open_list, close_list, map_grid):
  204. # 修改这个点的h值
  205. open_list.sort(key=lambda x: x[3]) # 先排序,选择k最小的节点
  206. X = open_list[0] # X表示k最小的节点
  207. x0 = int(X[0])
  208. y0 = int(X[1])
  209. close_list.append(X) # 将它放入closelist
  210. map_grid[x0, y0] = 4
  211. open_list.remove(X)
  212. # 从openlist中删除这个节点
  213. # 分类处理:(该节点处于lower状态,该节点处于lower状态)
  214. k_old = X[3]
  215. hx = X[2]
  216. # print(close_list)
  217. if k_old < hx: # k_old是上升状态
  218. x1 = x0
  219. y1 = y0 - 1
  220. h1 = 10
  221. [hx, close_list] = find_neighbor(x0, y0, x1, y1, k_old, hx, h1, close_list)
  222. x1 = x0 - 1
  223. y1 = y0 - 1
  224. h1 = 14
  225. [hx, close_list] = find_neighbor(x0, y0, x1, y1, k_old, hx, h1, close_list)
  226. x1 = x0 - 1
  227. y1 = y0
  228. h1 = 10
  229. [hx, close_list] = find_neighbor(x0, y0, x1, y1, k_old, hx, h1, close_list)
  230. x1 = x0 - 1
  231. y1 = y0 + 1
  232. h1 = 14
  233. [hx, close_list] = find_neighbor(x0, y0, x1, y1, k_old, hx, h1, close_list)
  234. x1 = x0
  235. y1 = y0 + 1
  236. h1 = 10
  237. [hx, close_list] = find_neighbor(x0, y0, x1, y1, k_old, hx, h1, close_list)
  238. x1 = x0 + 1
  239. y1 = y0 + 1
  240. h1 = 14
  241. [hx, close_list] = find_neighbor(x0, y0, x1, y1, k_old, hx, h1, close_list)
  242. x1 = x0 + 1
  243. y1 = y0
  244. h1 = 10
  245. [hx, close_list] = find_neighbor(x0, y0, x1, y1, k_old, hx, h1, close_list)
  246. x1 = x0 + 1
  247. y1 = y0 - 1
  248. h1 = 14
  249. [hx, close_list] = find_neighbor(x0, y0, x1, y1, k_old, hx, h1, close_list)
  250. # 找它的邻节点,看能不能让它的h降低
  251. #print(hx)
  252. # if k_old == hx: # 该节点x处于lower状态
  253. # x1 = x0
  254. # y1 = y0 - 1
  255. # h1 = 10
  256. # [open_list, close_list, map_grid] = find_neighbor2(x0, y0, x1, y1, k_old, hx, h1, close_list, open_list,
  257. # map_grid)
  258. #
  259. # x1 = x0 - 1
  260. # y1 = y0 - 1
  261. # h1 = 14
  262. # [open_list, close_list, map_grid] = find_neighbor2(x0, y0, x1, y1, k_old, hx, h1, close_list, open_list,
  263. # map_grid)
  264. #
  265. # x1 = x0 - 1
  266. # y1 = y0
  267. # h1 = 10
  268. # [open_list, close_list, map_grid] = find_neighbor2(x0, y0, x1, y1, k_old, hx, h1, close_list, open_list,
  269. # map_grid)
  270. #
  271. # x1 = x0 - 1
  272. # y1 = y0 + 1
  273. # h1 = 14
  274. # [open_list, close_list, map_grid] = find_neighbor2(x0, y0, x1, y1, k_old, hx, h1, close_list, open_list,
  275. # map_grid)
  276. #
  277. # x1 = x0
  278. # y1 = y0 + 1
  279. # h1 = 10
  280. # [open_list, close_list, map_grid] = find_neighbor2(x0, y0, x1, y1, k_old, hx, h1, close_list, open_list,
  281. # map_grid)
  282. #
  283. # x1 = x0 + 1
  284. # y1 = y0 + 1
  285. # h1 = 14
  286. # [open_list, close_list, map_grid] = find_neighbor2(x0, y0, x1, y1, k_old, hx, h1, close_list, open_list,
  287. # map_grid)
  288. #
  289. # x1 = x0 + 1
  290. # y1 = y0
  291. # h1 = 10
  292. # [open_list, close_list, map_grid] = find_neighbor2(x0, y0, x1, y1, k_old, hx, h1, close_list, open_list,
  293. # map_grid)
  294. #
  295. # x1 = x0 + 1
  296. # y1 = y0 - 1
  297. # h1 = 14
  298. # [open_list, close_list, map_grid] = find_neighbor2(x0, y0, x1, y1, k_old, hx, h1, close_list, open_list,
  299. # map_grid)
  300. #
  301. # else:
  302. # x1 = x0
  303. # y1 = y0 - 1
  304. # h1 = 10
  305. # [open_list, close_list, map_grid] = find_neighbor3(x0, y0, x1, y1, k_old, hx, h1, close_list, open_list,
  306. # map_grid)
  307. #
  308. # x1 = x0 - 1
  309. # y1 = y0 - 1
  310. # h1 = 14
  311. # [open_list, close_list, map_grid] = find_neighbor3(x0, y0, x1, y1, k_old, hx, h1, close_list, open_list,
  312. # map_grid)
  313. # #
  314. # x1 = x0 - 1
  315. # y1 = y0
  316. # h1 = 10
  317. # [open_list, close_list, map_grid] = find_neighbor3(x0, y0, x1, y1, k_old, hx, h1, close_list, open_list,
  318. # map_grid)
  319. # #
  320. # x1 = x0 - 1
  321. # y1 = y0 + 1
  322. # h1 = 14
  323. # [open_list, close_list, map_grid] = find_neighbor3(x0, y0, x1, y1, k_old, hx, h1, close_list, open_list,
  324. # map_grid)
  325. # #
  326. # x1 = x0
  327. # y1 = y0 + 1
  328. # h1 = 10
  329. # [open_list, close_list, map_grid] = find_neighbor3(x0, y0, x1, y1, k_old, hx, h1, close_list, open_list,
  330. # map_grid)
  331. # x1 = x0 + 1
  332. # y1 = y0 + 1
  333. # h1 = 14
  334. # [open_list, close_list, map_grid] = find_neighbor3(x0, y0, x1, y1, k_old, hx, h1, close_list, open_list,
  335. # map_grid)
  336. #
  337. # x1 = x0 + 1
  338. # y1 = y0
  339. # h1 = 10
  340. # [open_list, close_list, map_grid] = find_neighbor3(x0, y0, x1, y1, k_old, hx, h1, close_list, open_list,
  341. # map_grid)
  342. # x1 = x0 + 1
  343. # y1 = y0 - 1
  344. # h1 = 14
  345. # [open_list, close_list, map_grid] = find_neighbor3(x0, y0, x1, y1, k_old, hx, h1, close_list, open_list,
  346. # map_grid)
  347. open_list.sort(key=lambda x: x[3]) # 先排序,选择k最小的节点
  348. k_min = open_list[0][3] #
  349. return [open_list, list(close_list), map_grid,k_min,hx]
  350. while k_min<hx:
  351. [open_list, close_list, map_grid,k_min,hx] = process_state(open_list, close_list, map_grid)
  352. #避障
  353. second_path = []
  354. close_list = np.array(close_list)
  355. xn = 0
  356. yn = 3
  357. while xn != 7 or yn != 3:
  358. list1 = list(close_list[np.where((close_list[:, 0] == xn) & (close_list[:, 1] == yn))][0])
  359. xn = int(list1[4])
  360. yn = int(list1[5])
  361. second_path.append(list1)
  362. second_path.append([7, 3, 0, 0, None, None])
  363. draw_effect(map_grid,second_path)
  364. print("Find it")
'
运行

三、遗传算法

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib import cm
  4. from mpl_toolkits.mplot3d import Axes3D
  5. DNA_SIZE = 24
  6. POP_SIZE = 200
  7. CROSSOVER_RATE = 0.8
  8. MUTATION_RATE = 0.005
  9. N_GENERATIONS = 50
  10. X_BOUND = [-3, 3]
  11. Y_BOUND = [-3, 3]
  12. def F(x, y):
  13. return 3*(1-x)**2*np.exp(-(x**2)-(y+1)**2)- 10*(x/5 - x**3 - y**5)*np.exp(-x**2-y**2)- 1/3**np.exp(-(x+1)**2 - y**2)
  14. def plot_3d(ax):
  15. X = np.linspace(*X_BOUND, 100)
  16. Y = np.linspace(*Y_BOUND, 100)
  17. X,Y = np.meshgrid(X, Y)
  18. Z = F(X, Y)
  19. ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=cm.coolwarm)
  20. ax.set_zlim(-10,10)
  21. ax.set_xlabel('x')
  22. ax.set_ylabel('y')
  23. ax.set_zlabel('z')
  24. plt.pause(3)
  25. plt.show()
  26. def get_fitness(pop):
  27. x,y = translateDNA(pop)
  28. pred = F(x, y)
  29. return (pred - np.min(pred)) + 1e-3 #减去最小的适应度是为了防止适应度出现负数,通过这一步fitness的范围为[0, np.max(pred)-np.min(pred)],最后在加上一个很小的数防止出现为0的适应度
  30. def translateDNA(pop): #pop表示种群矩阵,一行表示一个二进制编码表示的DNA,矩阵的行数为种群数目
  31. x_pop = pop[:,1::2]#奇数列表示X
  32. y_pop = pop[:,::2] #偶数列表示y
  33. #pop:(POP_SIZE,DNA_SIZE)*(DNA_SIZE,1) --> (POP_SIZE,1)
  34. x = x_pop.dot(2**np.arange(DNA_SIZE)[::-1])/float(2**DNA_SIZE-1)*(X_BOUND[1]-X_BOUND[0])+X_BOUND[0]
  35. y = y_pop.dot(2**np.arange(DNA_SIZE)[::-1])/float(2**DNA_SIZE-1)*(Y_BOUND[1]-Y_BOUND[0])+Y_BOUND[0]
  36. return x,y
  37. def crossover_and_mutation(pop, CROSSOVER_RATE = 0.8):
  38. new_pop = []
  39. for father in pop: #遍历种群中的每一个个体,将该个体作为父亲
  40. child = father #孩子先得到父亲的全部基因(这里我把一串二进制串的那些0,1称为基因)
  41. if np.random.rand() < CROSSOVER_RATE: #产生子代时不是必然发生交叉,而是以一定的概率发生交叉
  42. mother = pop[np.random.randint(POP_SIZE)] #再种群中选择另一个个体,并将该个体作为母亲
  43. cross_points = np.random.randint(low=0, high=DNA_SIZE*2) #随机产生交叉的点
  44. child[cross_points:] = mother[cross_points:] #孩子得到位于交叉点后的母亲的基因
  45. mutation(child) #每个后代有一定的机率发生变异
  46. new_pop.append(child)
  47. return new_pop
  48. def mutation(child, MUTATION_RATE=0.003):
  49. if np.random.rand() < MUTATION_RATE: #以MUTATION_RATE的概率进行变异
  50. mutate_point = np.random.randint(0, DNA_SIZE*2) #随机产生一个实数,代表要变异基因的位置
  51. child[mutate_point] = child[mutate_point]^1 #将变异点的二进制为反转
  52. def select(pop, fitness): # nature selection wrt pop's fitness
  53. idx = np.random.choice(np.arange(POP_SIZE), size=POP_SIZE, replace=True,
  54. p=(fitness)/(fitness.sum()) )
  55. return pop[idx]
  56. def print_info(pop):
  57. fitness = get_fitness(pop)
  58. max_fitness_index = np.argmax(fitness)
  59. print("max_fitness:", fitness[max_fitness_index])
  60. x,y = translateDNA(pop)
  61. print("最优的基因型:", pop[max_fitness_index])
  62. print("(x, y):", (x[max_fitness_index], y[max_fitness_index]))
  63. if __name__ == "__main__":
  64. fig = plt.figure()
  65. ax = Axes3D(fig)
  66. plt.ion()#将画图模式改为交互模式,程序遇到plt.show不会暂停,而是继续执行
  67. plot_3d(ax)
  68. pop = np.random.randint(2, size=(POP_SIZE, DNA_SIZE*2)) #matrix (POP_SIZE, DNA_SIZE)
  69. for _ in range(N_GENERATIONS):#迭代N代
  70. x,y = translateDNA(pop)
  71. if 'sca' in locals():
  72. sca.remove()
  73. sca = ax.scatter(x, y, F(x,y), c='black', marker='o');plt.show();plt.pause(0.1)
  74. pop = np.array(crossover_and_mutation(pop, CROSSOVER_RATE))
  75. #F_values = F(translateDNA(pop)[0], translateDNA(pop)[1])#x, y --> Z matrix
  76. fitness = get_fitness(pop)
  77. pop = select(pop, fitness) #选择生成新的种群
  78. print_info(pop)
  79. plt.ioff()
  80. plot_3d(ax)

参考;https://blog.csdn.net/ha_ha_ha233/article/details/91364937 

四、粒子群算法

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from mpl_toolkits.mplot3d import Axes3D
  4. def fit_fun(x): # 适应函数
  5. return sum(100.0 * (x[0][1:] - x[0][:-1] ** 2.0) ** 2.0 + (1 - x[0][:-1]) ** 2.0)
  6. class Particle:
  7. # 初始化
  8. def __init__(self, x_max, max_vel, dim):
  9. self.__pos = np.random.uniform(-x_max, x_max, (1, dim)) # 粒子的位置
  10. self.__vel = np.random.uniform(-max_vel, max_vel, (1, dim)) # 粒子的速度
  11. self.__bestPos = np.zeros((1, dim)) # 粒子最好的位置
  12. self.__fitnessValue = fit_fun(self.__pos) # 适应度函数值
  13. def set_pos(self, value):
  14. self.__pos = value
  15. def get_pos(self):
  16. return self.__pos
  17. def set_best_pos(self, value):
  18. self.__bestPos = value
  19. def get_best_pos(self):
  20. return self.__bestPos
  21. def set_vel(self, value):
  22. self.__vel = value
  23. def get_vel(self):
  24. return self.__vel
  25. def set_fitness_value(self, value):
  26. self.__fitnessValue = value
  27. def get_fitness_value(self):
  28. return self.__fitnessValue
  29. class PSO:
  30. def __init__(self, dim, size, iter_num, x_max, max_vel, tol, best_fitness_value=float('Inf'), C1=2, C2=2, W=1):
  31. self.C1 = C1
  32. self.C2 = C2
  33. self.W = W
  34. self.dim = dim # 粒子的维度
  35. self.size = size # 粒子个数
  36. self.iter_num = iter_num # 迭代次数
  37. self.x_max = x_max
  38. self.max_vel = max_vel # 粒子最大速度
  39. self.tol = tol # 截至条件
  40. self.best_fitness_value = best_fitness_value
  41. self.best_position = np.zeros((1, dim)) # 种群最优位置
  42. self.fitness_val_list = [] # 每次迭代最优适应值
  43. # 对种群进行初始化
  44. self.Particle_list = [Particle(self.x_max, self.max_vel, self.dim) for i in range(self.size)]
  45. def set_bestFitnessValue(self, value):
  46. self.best_fitness_value = value
  47. def get_bestFitnessValue(self):
  48. return self.best_fitness_value
  49. def set_bestPosition(self, value):
  50. self.best_position = value
  51. def get_bestPosition(self):
  52. return self.best_position
  53. # 更新速度
  54. def update_vel(self, part):
  55. vel_value = self.W * part.get_vel() + self.C1 * np.random.rand() * (part.get_best_pos() - part.get_pos()) \
  56. + self.C2 * np.random.rand() * (self.get_bestPosition() - part.get_pos())
  57. vel_value[vel_value > self.max_vel] = self.max_vel
  58. vel_value[vel_value < -self.max_vel] = -self.max_vel
  59. part.set_vel(vel_value)
  60. # 更新位置
  61. def update_pos(self, part):
  62. pos_value = part.get_pos() + part.get_vel()
  63. part.set_pos(pos_value)
  64. value = fit_fun(part.get_pos())
  65. if value < part.get_fitness_value():
  66. part.set_fitness_value(value)
  67. part.set_best_pos(pos_value)
  68. if value < self.get_bestFitnessValue():
  69. self.set_bestFitnessValue(value)
  70. self.set_bestPosition(pos_value)
  71. def update_ndim(self):
  72. for i in range(self.iter_num):
  73. for part in self.Particle_list:
  74. self.update_vel(part) # 更新速度
  75. self.update_pos(part) # 更新位置
  76. self.fitness_val_list.append(self.get_bestFitnessValue()) # 每次迭代完把当前的最优适应度存到列表
  77. print('第{}次最佳适应值为{}'.format(i, self.get_bestFitnessValue()))
  78. if self.get_bestFitnessValue() < self.tol:
  79. break
  80. return self.fitness_val_list, self.get_bestPosition()
  81. if __name__ == '__main__':
  82. # test 香蕉函数
  83. pso = PSO(4, 5, 10000, 30, 60, 1e-4, C1=2, C2=2, W=1)
  84. fit_var_list, best_pos = pso.update_ndim()
  85. print("最优位置:" + str(best_pos))
  86. print("最优解:" + str(fit_var_list[-1]))
  87. plt.plot(range(len(fit_var_list)), fit_var_list, alpha=0.5)
'
运行

参考:https://zhuanlan.zhihu.com/p/378904190 

五、蚁群算法

  1. # -*- coding: utf-8 -*-
  2. import random
  3. import copy
  4. import time
  5. import sys
  6. import math
  7. import tkinter #//GUI模块
  8. import threading
  9. from functools import reduce
  10. # 参数
  11. '''
  12. ALPHA:信息启发因子,值越大,则蚂蚁选择之前走过的路径可能性就越大
  13. ,值越小,则蚁群搜索范围就会减少,容易陷入局部最优
  14. BETA:Beta值越大,蚁群越就容易选择局部较短路径,这时算法收敛速度会
  15. 加快,但是随机性不高,容易得到局部的相对最优
  16. '''
  17. (ALPHA, BETA, RHO, Q) = (1.0,2.0,0.5,100.0)
  18. # 城市数,蚁群
  19. (city_num, ant_num) = (50,50)
  20. distance_x = [
  21. 178,272,176,171,650,499,267,703,408,437,491,74,532,
  22. 416,626,42,271,359,163,508,229,576,147,560,35,714,
  23. 757,517,64,314,675,690,391,628,87,240,705,699,258,
  24. 428,614,36,360,482,666,597,209,201,492,294]
  25. distance_y = [
  26. 170,395,198,151,242,556,57,401,305,421,267,105,525,
  27. 381,244,330,395,169,141,380,153,442,528,329,232,48,
  28. 498,265,343,120,165,50,433,63,491,275,348,222,288,
  29. 490,213,524,244,114,104,552,70,425,227,331]
  30. #城市距离和信息素
  31. distance_graph = [ [0.0 for col in range(city_num)] for raw in range(city_num)]
  32. pheromone_graph = [ [1.0 for col in range(city_num)] for raw in range(city_num)]
  33. #----------- 蚂蚁 -----------
  34. class Ant(object):
  35. # 初始化
  36. def __init__(self,ID):
  37. self.ID = ID # ID
  38. self.__clean_data() # 随机初始化出生点
  39. # 初始数据
  40. def __clean_data(self):
  41. self.path = [] # 当前蚂蚁的路径
  42. self.total_distance = 0.0 # 当前路径的总距离
  43. self.move_count = 0 # 移动次数
  44. self.current_city = -1 # 当前停留的城市
  45. self.open_table_city = [True for i in range(city_num)] # 探索城市的状态
  46. city_index = random.randint(0,city_num-1) # 随机初始出生点
  47. self.current_city = city_index
  48. self.path.append(city_index)
  49. self.open_table_city[city_index] = False
  50. self.move_count = 1
  51. # 选择下一个城市
  52. def __choice_next_city(self):
  53. next_city = -1
  54. select_citys_prob = [0.0 for i in range(city_num)] #存储去下个城市的概率
  55. total_prob = 0.0
  56. # 获取去下一个城市的概率
  57. for i in range(city_num):
  58. if self.open_table_city[i]:
  59. try :
  60. # 计算概率:与信息素浓度成正比,与距离成反比
  61. select_citys_prob[i] = pow(pheromone_graph[self.current_city][i], ALPHA) * pow((1.0/distance_graph[self.current_city][i]), BETA)
  62. total_prob += select_citys_prob[i]
  63. except ZeroDivisionError as e:
  64. print ('Ant ID: {ID}, current city: {current}, target city: {target}'.format(ID = self.ID, current = self.current_city, target = i))
  65. sys.exit(1)
  66. # 轮盘选择城市
  67. if total_prob > 0.0:
  68. # 产生一个随机概率,0.0-total_prob
  69. temp_prob = random.uniform(0.0, total_prob)
  70. for i in range(city_num):
  71. if self.open_table_city[i]:
  72. # 轮次相减
  73. temp_prob -= select_citys_prob[i]
  74. if temp_prob < 0.0:
  75. next_city = i
  76. break
  77. # 未从概率产生,顺序选择一个未访问城市
  78. # if next_city == -1:
  79. # for i in range(city_num):
  80. # if self.open_table_city[i]:
  81. # next_city = i
  82. # break
  83. if (next_city == -1):
  84. next_city = random.randint(0, city_num - 1)
  85. while ((self.open_table_city[next_city]) == False): # if==False,说明已经遍历过了
  86. next_city = random.randint(0, city_num - 1)
  87. # 返回下一个城市序号
  88. return next_city
  89. # 计算路径总距离
  90. def __cal_total_distance(self):
  91. temp_distance = 0.0
  92. for i in range(1, city_num):
  93. start, end = self.path[i], self.path[i-1]
  94. temp_distance += distance_graph[start][end]
  95. # 回路
  96. end = self.path[0]
  97. temp_distance += distance_graph[start][end]
  98. self.total_distance = temp_distance
  99. # 移动操作
  100. def __move(self, next_city):
  101. self.path.append(next_city)
  102. self.open_table_city[next_city] = False
  103. self.total_distance += distance_graph[self.current_city][next_city]
  104. self.current_city = next_city
  105. self.move_count += 1
  106. # 搜索路径
  107. def search_path(self):
  108. # 初始化数据
  109. self.__clean_data()
  110. # 搜素路径,遍历完所有城市为止
  111. while self.move_count < city_num:
  112. # 移动到下一个城市
  113. next_city = self.__choice_next_city()
  114. self.__move(next_city)
  115. # 计算路径总长度
  116. self.__cal_total_distance()
  117. #----------- TSP问题 -----------
  118. class TSP(object):
  119. def __init__(self, root, width = 800, height = 600, n = city_num):
  120. # 创建画布
  121. self.root = root
  122. self.width = width
  123. self.height = height
  124. # 城市数目初始化为city_num
  125. self.n = n
  126. # tkinter.Canvas
  127. self.canvas = tkinter.Canvas(
  128. root,
  129. width = self.width,
  130. height = self.height,
  131. bg = "#EBEBEB", # 背景白色
  132. xscrollincrement = 1,
  133. yscrollincrement = 1
  134. )
  135. self.canvas.pack(expand = tkinter.YES, fill = tkinter.BOTH)
  136. self.title("TSP蚁群算法(n:初始化 e:开始搜索 s:停止搜索 q:退出程序)")
  137. self.__r = 5
  138. self.__lock = threading.RLock() # 线程锁
  139. self.__bindEvents()
  140. self.new()
  141. # 计算城市之间的距离
  142. for i in range(city_num):
  143. for j in range(city_num):
  144. temp_distance = pow((distance_x[i] - distance_x[j]), 2) + pow((distance_y[i] - distance_y[j]), 2)
  145. temp_distance = pow(temp_distance, 0.5)
  146. distance_graph[i][j] =float(int(temp_distance + 0.5))
  147. # 按键响应程序
  148. def __bindEvents(self):
  149. self.root.bind("q", self.quite) # 退出程序
  150. self.root.bind("n", self.new) # 初始化
  151. self.root.bind("e", self.search_path) # 开始搜索
  152. self.root.bind("s", self.stop) # 停止搜索
  153. # 更改标题
  154. def title(self, s):
  155. self.root.title(s)
  156. # 初始化
  157. def new(self, evt = None):
  158. # 停止线程
  159. self.__lock.acquire()
  160. self.__running = False
  161. self.__lock.release()
  162. self.clear() # 清除信息
  163. self.nodes = [] # 节点坐标
  164. self.nodes2 = [] # 节点对象
  165. # 初始化城市节点
  166. for i in range(len(distance_x)):
  167. # 在画布上随机初始坐标
  168. x = distance_x[i]
  169. y = distance_y[i]
  170. self.nodes.append((x, y))
  171. # 生成节点椭圆,半径为self.__r
  172. node = self.canvas.create_oval(x - self.__r,
  173. y - self.__r, x + self.__r, y + self.__r,
  174. fill = "#ff0000", # 填充红色
  175. outline = "#000000", # 轮廓白色
  176. tags = "node",
  177. )
  178. self.nodes2.append(node)
  179. # 显示坐标
  180. self.canvas.create_text(x,y-10, # 使用create_text方法在坐标(302,77)处绘制文字
  181. text = '('+str(x)+','+str(y)+')', # 所绘制文字的内容
  182. fill = 'black' # 所绘制文字的颜色为灰色
  183. )
  184. # 顺序连接城市
  185. #self.line(range(city_num))
  186. # 初始城市之间的距离和信息素
  187. for i in range(city_num):
  188. for j in range(city_num):
  189. pheromone_graph[i][j] = 1.0
  190. self.ants = [Ant(ID) for ID in range(ant_num)] # 初始蚁群
  191. self.best_ant = Ant(-1) # 初始最优解
  192. self.best_ant.total_distance = 1 << 31 # 初始最大距离
  193. self.iter = 1 # 初始化迭代次数
  194. # 将节点按order顺序连线
  195. def line(self, order):
  196. # 删除原线
  197. self.canvas.delete("line")
  198. def line2(i1, i2):
  199. p1, p2 = self.nodes[i1], self.nodes[i2]
  200. self.canvas.create_line(p1, p2, fill = "#000000", tags = "line")
  201. return i2
  202. # order[-1]为初始值
  203. reduce(line2, order, order[-1])
  204. # 清除画布
  205. def clear(self):
  206. for item in self.canvas.find_all():
  207. self.canvas.delete(item)
  208. # 退出程序
  209. def quite(self, evt):
  210. self.__lock.acquire()
  211. self.__running = False
  212. self.__lock.release()
  213. self.root.destroy()
  214. print (u"\n程序已退出...")
  215. sys.exit()
  216. # 停止搜索
  217. def stop(self, evt):
  218. self.__lock.acquire()
  219. self.__running = False
  220. self.__lock.release()
  221. # 开始搜索
  222. def search_path(self, evt = None):
  223. # 开启线程
  224. self.__lock.acquire()
  225. self.__running = True
  226. self.__lock.release()
  227. while self.__running:
  228. # 遍历每一只蚂蚁
  229. for ant in self.ants:
  230. # 搜索一条路径
  231. ant.search_path()
  232. # 与当前最优蚂蚁比较
  233. if ant.total_distance < self.best_ant.total_distance:
  234. # 更新最优解
  235. self.best_ant = copy.deepcopy(ant)
  236. # 更新信息素
  237. self.__update_pheromone_gragh()
  238. print (u"迭代次数:",self.iter,u"最佳路径总距离:",int(self.best_ant.total_distance))
  239. # 连线
  240. self.line(self.best_ant.path)
  241. # 设置标题
  242. self.title("TSP蚁群算法(n:随机初始 e:开始搜索 s:停止搜索 q:退出程序) 迭代次数: %d" % self.iter)
  243. # 更新画布
  244. self.canvas.update()
  245. self.iter += 1
  246. # 更新信息素
  247. def __update_pheromone_gragh(self):
  248. # 获取每只蚂蚁在其路径上留下的信息素
  249. temp_pheromone = [[0.0 for col in range(city_num)] for raw in range(city_num)]
  250. for ant in self.ants:
  251. for i in range(1,city_num):
  252. start, end = ant.path[i-1], ant.path[i]
  253. # 在路径上的每两个相邻城市间留下信息素,与路径总距离反比
  254. temp_pheromone[start][end] += Q / ant.total_distance
  255. temp_pheromone[end][start] = temp_pheromone[start][end]
  256. # 更新所有城市之间的信息素,旧信息素衰减加上新迭代信息素
  257. for i in range(city_num):
  258. for j in range(city_num):
  259. pheromone_graph[i][j] = pheromone_graph[i][j] * RHO + temp_pheromone[i][j]
  260. # 主循环
  261. def mainloop(self):
  262. self.root.mainloop()
  263. #----------- 程序的入口处 -----------
  264. if __name__ == '__main__':
  265. print (u"""
  266. --------------------------------------------------------
  267. 程序:蚁群算法解决TPS问题程序
  268. 作者:许彬
  269. 日期:2015-12-10
  270. 语言:Python 2.7
  271. --------------------------------------------------------
  272. """)
  273. TSP(tkinter.Tk()).mainloop()

参考;https://blog.csdn.net/fanxin_i/article/details/80380733

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/848813
推荐阅读
相关标签
  

闽ICP备14008679号