以下是为路径规划、选址优化问题提供的Matlab和Python代码示例,涵盖遗传算法(GA)、粒子群优化(PSO)和蚁群算法(ACO)的实现:
1. 遗传算法(GA)路径规划(Matlab)
场景:解决TSP(旅行商问题)
matlab
% 遗传算法参数设置 | |
numCities = 20; | |
popSize = 100; | |
maxGen = 500; | |
mutationRate = 0.02; | |
% 初始化城市坐标(随机生成) | |
cities = rand(numCities, 2) * 100; | |
% 定义适应度函数(路径长度倒数) | |
fitnessFcn = @(x) 1 / pathLength(x, cities); | |
% 运行遗传算法 | |
options = optimoptions('ga', 'PopulationSize', popSize, 'MaxGenerations', maxGen, 'MutationFcn', @mutationAdaptive); | |
[bestRoute, ~] = ga(fitnessFcn, numCities, [], [], [], [], 1, numCities, [], options); | |
% 绘制结果 | |
plot(cities(:,1), cities(:,2), 'o'); | |
hold on; | |
plot(cities([bestRoute, bestRoute(1)],1), cities([bestRoute, bestRoute(1)],2), '-r'); | |
title('GA路径规划结果'); | |
% 路径长度计算函数 | |
function len = pathLength(route, cities) | |
len = 0; | |
for i = 1:length(route)-1 | |
len = len + norm(cities(route(i),:) - cities(route(i+1),:)); | |
end | |
end |
2. 粒子群优化(PSO)选址优化(Python)
场景:优化仓库位置以最小化运输成本
python
import numpy as np | |
import matplotlib.pyplot as plt | |
# 参数设置 | |
num_particles = 30 | |
max_iter = 100 | |
demand_points = np.random.rand(10, 2) * 100 # 需求点坐标 | |
# PSO初始化 | |
particles = np.random.rand(num_particles, 2) * 100 | |
velocities = np.random.rand(num_particles, 2) * 0.1 | |
pbest = particles.copy() | |
gbest = particles[np.argmin([cost(p, demand_points) for p in particles])] | |
# 迭代优化 | |
for _ in range(max_iter): | |
for i in range(num_particles): | |
# 更新速度和位置 | |
velocities[i] = 0.5 * velocities[i] + 0.8 * np.random.rand(2) * (pbest[i] - particles[i]) + 0.2 * np.random.rand(2) * (gbest - particles[i]) | |
particles[i] += velocities[i] | |
# 更新个体最优和全局最优 | |
if cost(particles[i], demand_points) < cost(pbest[i], demand_points): | |
pbest[i] = particles[i] | |
if cost(particles[i], demand_points) < cost(gbest, demand_points): | |
gbest = particles[i] | |
# 成本函数(欧氏距离总和) | |
def cost(warehouse, points): | |
return np.sum(np.sqrt(np.sum((points - warehouse)**2, axis=1))) | |
# 可视化 | |
plt.scatter(demand_points[:,0], demand_points[:,1], c='red', label='需求点') | |
plt.scatter(gbest[0], gbest[1], c='blue', marker='*', s=200, label='最优仓库位置') | |
plt.legend(); plt.show() |
3. 蚁群算法(ACO)路径规划(Python)
场景:解决TSP问题
python
import numpy as np | |
# 参数设置 | |
num_ants = 20 | |
num_iterations = 100 | |
alpha = 1.0 # 信息素重要程度 | |
beta = 2.0 # 启发式信息重要程度 | |
evaporation = 0.5 | |
# 初始化信息素矩阵 | |
cities = np.random.rand(20, 2) * 100 | |
distance_matrix = np.sqrt(np.sum((cities[:, np.newaxis] - cities)**2, axis=2)) | |
pheromone = np.ones_like(distance_matrix) | |
# ACO主循环 | |
for _ in range(num_iterations): | |
paths = [] | |
for _ in range(num_ants): | |
path = [0] # 起点 | |
unvisited = set(range(1, len(cities))) | |
while unvisited: | |
current = path[-1] | |
probs = [] | |
for city in unvisited: | |
heuristic = 1 / distance_matrix[current, city] | |
prob = (pheromone[current, city]**alpha) * (heuristic**beta) | |
probs.append(prob) | |
probs = np.array(probs) / sum(probs) | |
next_city = np.random.choice(list(unvisited), p=probs) | |
path.append(next_city) | |
unvisited.remove(next_city) | |
paths.append(path) | |
# 更新信息素 | |
pheromone *= evaporation | |
for path in paths: | |
path_length = sum(distance_matrix[path[i], path[i+1]] for i in range(len(path)-1)) | |
for i in range(len(path)-1): | |
pheromone[path[i], path[i+1]] += 1 / path_length | |
# 输出最优路径 | |
best_path = min(paths, key=lambda x: sum(distance_matrix[x[i], x[i+1]] for i in range(len(x)-1))) | |
print("最优路径:", best_path) |
关键说明
- 算法选择:
- GA:适合离散问题(如TSP),全局搜索能力强。
- PSO:适合连续空间优化(如选址),收敛速度快。
- ACO:适合动态路径问题,依赖信息素更新机制。
- 扩展建议:
- 添加约束条件(如容量限制、障碍物避障)。
- 使用更高效的数据结构(如邻接矩阵)加速距离计算。
- 工具库推荐:
- Python:
DEAP
(GA)、PySwarms
(PSO) - Matlab:Global Optimization Toolbox(内置GA和PSO)
- Python:
如需特定场景的完整实现(如多仓库选址或动态路径规划),可进一步说明需求! 🐜🌍