from function import get_distances, get_value, result_plot, get_neighbors
from random import choice, random, randint
# 算法参数
N = 20000 # 迭代次数
gama = 2 # 逃逸系数
# 城市坐标数据,城市序号为0,1,2,3...
city_coordinates = [(41, 94), (37, 84), (54, 67), (25, 62), (7, 64), (2, 99), (68, 58), (71, 44), (54, 62),
(83, 69),(64, 60), (18, 54), (22, 60), (83, 46), (91, 38), (25, 38), (24, 42), (58, 69),
(71, 71),(74, 78),(87, 76), (18, 40), (13, 40), (82, 7), (62, 32), (58, 35), (45, 21),
(41, 26), (4, 35), (4, 50)]
city_number = len(city_coordinates) # 城市数量
distances = get_distances(city_coordinates)
# 随机生成初始解
path = list(range(city_number))
value = get_value(path, distances)
# 存储当前最优
best_value, best_path = value, path[:]
# 进行迭代
result = []
x1, x2 = 0.001, 0.002
iterate_result = [] # 存储每一代达到的最优值
n = 0
while n <= N:
n += 1
print(f"当前迭代次数为:{n},最优值为:{best_value}")
iterate_result.append(best_value)
# 更新混沌变量
while True:
x1 = 4 * x1 * (1 - x1)
x2 = 4 * x2 * (1 - x2)
row1 = int(x1 * city_number)
row2 = int(x2 * city_number)
if row1 != row2:
break
now_path = path[:]
# 进行交换策略
if random() > 0.5:
now_path[row1], now_path[row2] = path[row2], path[row1]
# 进行移位策略
else:
row1, row2 = min(row1, row2), max(row1, row2)
del now_path[row1]
now_path.insert(row2, path[row1])
now_value = get_value(now_path, distances)
if now_value < best_value:
best_path = now_path
best_value = now_value
elif now_value < gama * best_value:
now_path = path[:]
path = now_path[:]
print(best_path)
print(get_value(best_path, distances))
result_plot(iterate_result)
基于混沌优化算法求解TSP问题
于 2022-03-22 16:22:10 首次发布