带画图的多无人机路径规划粒子群算法 python源程序
时间: 2023-08-02 13:06:29 浏览: 91
面向无人机路径规划的多目标粒子群优化算法.pdf
5星 · 资源好评率100%
以下是带画图的多无人机路径规划粒子群算法 Python 源程序:
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义常量
POP_SIZE = 30 # 种群数量
N_DIM = 2 # 维度数
N_STEP = 100 # 迭代次数
N_DRONE = 3 # 无人机数量
X_RANGE = [-10, 10] # x 范围
Y_RANGE = [-10, 10] # y 范围
V_MAX = 1 # 最大速度
C1 = 2 # 学习因子1
C2 = 2 # 学习因子2
W_MAX = 0.9 # 最大惯性因子
W_MIN = 0.4 # 最小惯性因子
# 初始化位置和速度
def init_pos_vel():
pos = np.zeros((POP_SIZE, N_DRONE*N_DIM))
vel = np.zeros((POP_SIZE, N_DRONE*N_DIM))
for i in range(POP_SIZE):
for j in range(N_DRONE):
pos[i][j*N_DIM:(j+1)*N_DIM] = np.array([np.random.uniform(X_RANGE[0], X_RANGE[1]), np.random.uniform(Y_RANGE[0], Y_RANGE[1])])
vel[i][j*N_DIM:(j+1)*N_DIM] = np.array([np.random.uniform(-V_MAX, V_MAX), np.random.uniform(-V_MAX, V_MAX)])
return pos, vel
# 适应度函数
def fitness(pos):
fitness_list = np.zeros(POP_SIZE)
for i in range(POP_SIZE):
for j in range(N_DRONE):
x = pos[i][j*N_DIM]
y = pos[i][j*N_DIM+1]
fitness_list[i] += (x-1)**2 + (y-1)**2 # 以 (1,1) 为目标点
return fitness_list
# 粒子群算法
def PSO():
pos, vel = init_pos_vel()
p_best_pos = pos.copy()
p_best_fitness = fitness(pos).copy()
g_best_pos = pos[p_best_fitness.argmin()].copy()
g_best_fitness = p_best_fitness.min().copy()
w = W_MAX
for i in range(N_STEP):
# 更新速度和位置
for j in range(POP_SIZE):
vel[j] = w * vel[j] + C1 * np.random.rand(N_DRONE*N_DIM) * (p_best_pos[j] - pos[j]) + C2 * np.random.rand(N_DRONE*N_DIM) * (g_best_pos - pos[j])
pos[j] += vel[j]
# 边界处理
for k in range(N_DRONE):
if pos[j][k*N_DIM] < X_RANGE[0]:
pos[j][k*N_DIM] = X_RANGE[0]
vel[j][k*N_DIM] = -vel[j][k*N_DIM]
elif pos[j][k*N_DIM] > X_RANGE[1]:
pos[j][k*N_DIM] = X_RANGE[1]
vel[j][k*N_DIM] = -vel[j][k*N_DIM]
if pos[j][k*N_DIM+1] < Y_RANGE[0]:
pos[j][k*N_DIM+1] = Y_RANGE[0]
vel[j][k*N_DIM+1] = -vel[j][k*N_DIM+1]
elif pos[j][k*N_DIM+1] > Y_RANGE[1]:
pos[j][k*N_DIM+1] = Y_RANGE[1]
vel[j][k*N_DIM+1] = -vel[j][k*N_DIM+1]
# 更新个体最优解和群体最优解
fitness_list = fitness(pos)
for j in range(POP_SIZE):
if fitness_list[j] < p_best_fitness[j]:
p_best_fitness[j] = fitness_list[j]
p_best_pos[j] = pos[j].copy()
if fitness_list[j] < g_best_fitness:
g_best_fitness = fitness_list[j]
g_best_pos = pos[j].copy()
# 缩小惯性因子
w = W_MAX - i * (W_MAX - W_MIN) / N_STEP
# 画图
plt.clf()
plt.xlim(X_RANGE)
plt.ylim(Y_RANGE)
plt.title('PSO')
for j in range(N_DRONE):
x = [pos[k][j*N_DIM] for k in range(POP_SIZE)]
y = [pos[k][j*N_DIM+1] for k in range(POP_SIZE)]
plt.scatter(x, y, marker='.')
plt.pause(0.01)
return g_best_pos, g_best_fitness
# 主函数
if __name__ == '__main__':
best_pos, best_fitness = PSO()
print('最优解:', best_pos)
print('最优适应度:', best_fitness)
plt.show()
```
程序中的 `init_pos_vel` 函数用于初始化位置和速度,`fitness` 函数是适应度函数,`PSO` 函数是粒子群算法的核心部分。程序中通过 `matplotlib` 库实现了动态画图,可以直观地观察算法的运行过程。在算法结束后,程序输出最优解和最优适应度,并在图像中标出最优解。
阅读全文