蚁群算法用python代码实现蚂蚁移动的动画过程,给出代码
时间: 2024-02-28 15:57:09 浏览: 174
蚁群算法的python代码
4星 · 用户满意度95%
以下是使用 Python 实现蚁群算法的蚂蚁移动动画过程的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# 定义蚂蚁的数量、城市数量和迭代次数
num_ants = 10
num_cities = 20
num_iterations = 100
# 定义城市的坐标
cities = np.random.rand(num_cities, 2)
# 计算城市之间的距离
distances = np.zeros((num_cities, num_cities))
for i in range(num_cities):
for j in range(num_cities):
distances[i, j] = np.sqrt((cities[i, 0] - cities[j, 0]) ** 2 + (cities[i, 1] - cities[j, 1]) ** 2)
# 初始化信息素矩阵
pheromones = np.ones((num_cities, num_cities))
# 定义蚂蚁类
class Ant:
def __init__(self, start_city):
self.current_city = start_city
self.visited_cities = [start_city]
self.path_length = 0
def choose_next_city(self):
# 计算当前城市与其他未访问城市之间的信息素和距离的乘积
unvisited_cities = [city for city in range(num_cities) if city not in self.visited_cities]
product = np.zeros(len(unvisited_cities))
for i, city in enumerate(unvisited_cities):
product[i] = pheromones[self.current_city, city] ** 0.5 * (1 / distances[self.current_city, city])
# 根据概率选择下一个城市
probabilities = product / np.sum(product)
next_city = np.random.choice(unvisited_cities, p=probabilities)
# 更新路径长度和已访问城市列表
self.path_length += distances[self.current_city, next_city]
self.current_city = next_city
self.visited_cities.append(next_city)
# 定义蚂蚁群类
class AntColony:
def __init__(self):
self.ants = [Ant(start_city=np.random.randint(num_cities)) for i in range(num_ants)]
def update_pheromones(self):
# 计算每只蚂蚁留下的信息素
delta_pheromones = np.zeros((num_cities, num_cities))
for ant in self.ants:
for i in range(len(ant.visited_cities) - 1):
current_city = ant.visited_cities[i]
next_city = ant.visited_cities[i+1]
delta_pheromones[current_city, next_city] += 1 / ant.path_length
# 更新信息素矩阵
pheromones *= 0.5
pheromones += delta_pheromones
def run(self):
# 迭代指定次数
for i in range(num_iterations):
# 每只蚂蚁移动一步
for ant in self.ants:
ant.choose_next_city()
# 更新信息素
self.update_pheromones()
# 重置所有蚂蚁的状态
for ant in self.ants:
ant.current_city = np.random.randint(num_cities)
ant.visited_cities = [ant.current_city]
ant.path_length = 0
def get_best_path(self):
# 找到最短路径
best_ant = self.ants[0]
for ant in self.ants:
if ant.path_length < best_ant.path_length:
best_ant = ant
return best_ant.visited_cities, best_ant.path_length
# 定义动画函数
def animate(i):
ax.clear()
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_title('Iteration {}'.format(i))
# 运行蚂蚁群算法
colony = AntColony()
colony.run()
# 绘制城市
for j in range(num_cities):
ax.plot(cities[j, 0], cities[j, 1], 'bo')
# 绘制路径
path, path_length = colony.get_best_path()
for j in range(len(path) - 1):
ax.plot([cities[path[j], 0], cities[path[j+1], 0]],
[cities[path[j], 1], cities[path[j+1], 1]], 'r-')
# 显示路径长度
ax.text(0.1, 0.9, 'Path length: {:.2f}'.format(path_length), transform=ax.transAxes)
# 创建动画
fig, ax = plt.subplots()
ani = animation.FuncAnimation(fig, animate, frames=num_iterations, interval=500)
plt.show()
```
在运行该代码时,会生成一个动画,展示蚂蚁在城市之间移动的过程,并在每次迭代后绘制最佳路径。在动画的右上角,会显示当前迭代次数和最佳路径的长度。
阅读全文