人工蜂群算法求解TSP问题,给出代码
时间: 2023-08-06 12:13:47 浏览: 130
以下是一个简单的Python实现:
```python
import random
# 计算两点之间的距离
def distance(city1, city2):
x1, y1 = city1
x2, y2 = city2
return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
# 创建TSP问题的初始城市列表
def create_cities(n):
cities = []
for i in range(n):
x = random.random()
y = random.random()
cities.append((x, y))
return cities
# 计算一条路径的总距离
def path_distance(path, cities):
distance = 0
for i in range(len(path)):
j = (i + 1) % len(path)
city1 = cities[path[i]]
city2 = cities[path[j]]
distance += distance(city1, city2)
return distance
# 初始化一群蜜蜂
def create_bees(num_bees, num_sites):
bees = []
for i in range(num_bees):
site = random.randint(0, num_sites - 1)
bees.append((site, path_distance([site], cities)))
return bees
# 找到最优路径
def optimize(num_epochs, num_bees, num_sites, elite_sites, patch_size):
cities = create_cities(num_sites)
bees = create_bees(num_bees, num_sites)
best_path = None
best_distance = None
for epoch in range(num_epochs):
# 计算每个位置的相对重要性
fitnesses = [1.0 / bee[1] for bee in bees]
total_fitness = sum(fitnesses)
probs = [fitness / total_fitness for fitness in fitnesses]
# 选择精英位置
elite_indices = sorted(range(num_bees), key=lambda i: bees[i][1])[:elite_sites]
elite_sites = [bees[i][0] for i in elite_indices]
# 在精英位置周围搜索新位置
for site in elite_sites:
for i in range(patch_size):
new_site = (site + i) % num_sites
new_path = [new_site]
for j in range(num_sites - 1):
# 选择随机蜜蜂
probs_cumulative = [sum(probs[:k+1]) for k in range(num_bees)]
random_num = random.random()
bee_index = next(i for i, prob in enumerate(probs_cumulative) if prob >= random_num)
bee_path = bees[bee_index][0]
new_path.append(bee_path)
new_distance = path_distance(new_path, cities)
# 更新位置和距离
if new_distance < bees[site][1]:
bees[site] = (new_site, new_distance)
# 找到最优路径
for bee in bees:
if best_distance is None or bee[1] < best_distance:
best_path = [bee[0]]
best_distance = bee[1]
return best_path, best_distance
```
使用示例:
```python
num_epochs = 100
num_bees = 10
num_sites = 20
elite_sites = 3
patch_size = 5
best_path, best_distance = optimize(num_epochs, num_bees, num_sites, elite_sites, patch_size)
print("Best path:", best_path)
print("Best distance:", best_distance)
```
阅读全文