from aco_tsp import ACO, Graph
import numpy as np
# 定义距离计算函数
def distance(x1, y1, x2, y2):
if abs(x1 - x2) > 23 or abs(y1 - y2) > 23:
return np.inf
else:
return np.lcm(x1-x2, y1-y2)
# 构建图
n_nodes = 2023
locations = np.zeros((n_nodes,2))
for i in range(n_nodes):
x = (i % 71) + 1
y = (i // 71) + 1
locations[i][0] = x
locations[i][1] = y
# 构建邻接矩阵
adj_matrix = np.zeros((n_nodes,n_nodes))
for i in range(n_nodes):
for j in range(i+1,n_nodes):
adj_matrix[i][j] = distance(locations[i][0],locations[i][1],locations[j][0],locations[j][1])
adj_matrix[j][i] = adj_matrix[i][j]
graph = Graph(adj_matrix)
# 设置ACO参数
aco = ACO(
n_ants=50,
n_iterations=200,
pheromone_deposit=0.1,
pheromone_evaporation=0.1,
alpha=1.0,
beta=2.0,
q=1.0,
greedy=True,
)
# 运行ACO算法
shortest_path, path_cost = aco.solve(graph, start_node=0)
print("最短路径长度为:", path_cost)
# 绘制路径仿真图
import matplotlib.pyplot as plt
path = shortest_path + [shortest_path[0]]
plt.figure(figsize=(8,8))
plt.plot(locations[:, 0], locations[:, 1], 'o', markersize=8)
plt.plot(locations[path, 0], locations[path, 1], 'r', linewidth=3)
plt.axis('equal')
plt.show()
# 绘制迭代变化图
plt.plot(aco.global_best_costs)
plt.ylabel('Path length')
plt.xlabel('Iterations')
plt.show()