无人机在复杂三维环境中的路径规划一直是业界难题。传统方法如A*、RRT等算法在应对高维度、动态变化的环境时往往捉襟见肘。这个项目创新性地将遗传算法(GA)与生成对抗网络(GAN)相结合,构建了一套完整的无人机三维路径规划解决方案。
我在实际开发中发现,单纯使用遗传算法虽然能保证全局搜索能力,但容易陷入局部最优;而单独使用GAN生成的路径又难以满足严格的物理约束。通过反复实验验证,最终确定了GA-GAN协同优化的架构:GA负责全局路径的初步筛选,GAN则对路径进行深度优化和特征学习,二者形成互补。
遗传算法作为全局优化器,其设计直接影响最终路径质量。在MATLAB中我们这样实现:
matlab复制function population = initPopulation(popSize, geneLen, mapSize, start, goal)
% 初始化种群
population = cell(popSize, 1);
for i = 1:popSize
path = zeros(geneLen, 3);
path(1,:) = start; % 固定起点
path(end,:) = goal; % 固定终点
% 随机生成中间路径点
for j = 2:geneLen-1
path(j,1) = randi([1, mapSize(1)]);
path(j,2) = randi([1, mapSize(2)]);
path(j,3) = randi([1, mapSize(3)]);
end
population{i} = path;
end
end
适应度函数设计是GA的核心,我们综合考虑了多个关键指标:
matlab复制function fitness = pathFitness(path, obstacleMap)
totalLength = 0; % 路径总长度
collisionPenalty = 0; % 碰撞惩罚项
smoothness = 0; % 平滑度指标
for i = 1:size(path,1)-1
% 计算线段长度
segment = path(i+1,:) - path(i,:);
totalLength = totalLength + norm(segment);
% 碰撞检测
[collision, ~] = checkCollision(path(i,:), path(i+1,:), obstacleMap);
if collision
collisionPenalty = collisionPenalty + 100; % 每碰撞一次加100惩罚
end
% 计算平滑度(相邻线段夹角)
if i > 1
v1 = path(i,:) - path(i-1,:);
v2 = path(i+1,:) - path(i,:);
angle = acos(dot(v1,v2)/(norm(v1)*norm(v2)));
smoothness = smoothness + rad2deg(angle);
end
end
% 综合适应度计算(越小越好)
fitness = totalLength + collisionPenalty + smoothness*0.5;
end
GAN网络的设计直接影响路径生成的质量。我们采用了以下结构:
matlab复制function [generator, discriminator] = buildGAN(inputDim, latentDim)
% 生成器网络
generator = [
featureInputLayer(latentDim,'Name','input','Normalization','none')
fullyConnectedLayer(256,'Name','fc1')
leakyReluLayer(0.2,'Name','lrelu1')
fullyConnectedLayer(128,'Name','fc2')
leakyReluLayer(0.2,'Name','lrelu2')
fullyConnectedLayer(inputDim,'Name','output')
tanhLayer('Name','tanh') % 输出归一化到[-1,1]
];
% 判别器网络
discriminator = [
featureInputLayer(inputDim,'Name','input','Normalization','none')
fullyConnectedLayer(128,'Name','fc1')
leakyReluLayer(0.2,'Name','lrelu1')
fullyConnectedLayer(64,'Name','fc2')
leakyReluLayer(0.2,'Name','lrelu2')
fullyConnectedLayer(1,'Name','output')
sigmoidLayer('Name','sigmoid') % 输出概率
];
end
在实际训练中,我们发现以下几个关键点:
GA和GAN的协同是项目的核心创新点,具体流程如下:
matlab复制function [bestPath, fitnessHistory] = gaGanCooptimization(map, params)
% 初始化
population = initPopulation(params.popSize, params.geneLen, map.size, map.start, map.goal);
[generator, discriminator] = buildGAN(params.inputDim, params.latentDim);
fitnessHistory = zeros(params.maxGen, 1);
for gen = 1:params.maxGen
% GA进化
population = gaEvolution(population, map.obstacles, params);
% 定期用GAN增强
if mod(gen, params.ganInterval) == 0
% 训练GAN
[generator, discriminator] = trainGAN(generator, discriminator, population, params);
% 用GAN生成新样本
newPaths = generatePaths(generator, params);
population = [population; newPaths];
% 保持种群规模
population = selectBest(population, map.obstacles, params.popSize);
end
% 记录最佳适应度
fitnessHistory(gen) = evaluateBest(population, map.obstacles);
end
bestPath = selectBest(population, map.obstacles, 1);
end
无人机路径规划需要考虑多个目标,我们采用加权求和法:
matlab复制function score = multiObjectiveScore(path, obstacles)
% 1. 路径长度
lengthScore = pathLength(path);
% 2. 安全指标(碰撞检测)
[collision, risk] = pathSafety(path, obstacles);
% 3. 能耗估计
energyScore = energyEstimate(path);
% 4. 平滑度
smoothScore = smoothness(path);
% 加权综合(权重可调)
weights = [0.4, 0.3, 0.2, 0.1]; % 长度权重最高
score = weights(1)*lengthScore + weights(2)*risk + ...
weights(3)*energyScore + weights(4)*smoothScore;
% 硬约束: 如有碰撞则大幅惩罚
if collision
score = score + 1000;
end
end
我们开发了直观的GUI界面,主要包含以下区域:
matlab复制function createGUI()
fig = figure('Name','无人机路径规划系统','NumberTitle','off',...
'Position',[200,200,1000,700]);
% 环境显示区域
ax = axes('Parent',fig,'Units','pixels','Position',[50,250,600,400]);
% 控制面板
uipanel('Parent',fig,'Title','参数设置','Position',[0.7,0.6,0.28,0.35]);
% 算法选择
uicontrol('Style','popup','String',{'GA','GA-GAN','RRT*'},...
'Position',[720,550,150,25],'Tag','algorithm');
% 开始按钮
uicontrol('Style','pushbutton','String','开始规划',...
'Position',[720,500,150,40],'Callback',@startPlanning);
% 结果显示区域
uitable('Parent',fig,'Position',[700,200,250,200],...
'ColumnName',{'指标','数值'},'Tag','resultTable');
end
路径可视化采用MATLAB强大的3D绘图功能:
matlab复制function plotPath(ax, path, obstacles, start, goal)
cla(ax);
hold(ax,'on');
% 绘制障碍物
[x,y,z] = ind2sub(size(obstacles),find(obstacles==1));
scatter3(ax,x,y,z,20,'red','filled');
% 绘制路径
plot3(ax,path(:,1),path(:,2),path(:,3),'b-o','LineWidth',2);
% 标记起点终点
scatter3(ax,start(1),start(2),start(3),100,'green','filled');
scatter3(ax,goal(1),goal(2),goal(3),100,'magenta','filled');
grid(ax,'on');
xlabel(ax,'X'); ylabel(ax,'Y'); zlabel(ax,'Z');
title(ax,'无人机三维路径规划结果');
view(ax,45,30);
hold(ax,'off');
end
城市物流配送:
电力巡检:
农业植保:
通过项目实践,我总结了以下优化经验:
matlab复制% 开启并行池
if isempty(gcp('nocreate'))
parpool('local',4); % 使用4个worker
end
% 并行计算适应度
parfor i = 1:popSize
fitness(i) = pathFitness(population{i}, obstacles);
end
matlab复制% 缓存常用计算结果
persistent cache
if isempty(cache)
cache = containers.Map;
end
key = num2str(path(:)');
if isKey(cache,key)
fitness = cache(key);
else
fitness = calculateFitness(path);
cache(key) = fitness;
end
matlab复制% 根据进化情况调整变异率
if std(fitness) < threshold
mutationRate = min(mutationRate*1.2, 0.3); % 增加多样性
else
mutationRate = max(mutationRate*0.9, 0.01);
end
在实际开发中遇到的一些典型问题及解决方法:
路径不连续问题:
收敛过早问题:
GAN模式坍塌问题:
实时性不足问题:
我们支持多种部署方式:
matlab复制function paths = multiUAVPlanning(startPoints, goalPoints, map)
paths = cell(length(startPoints),1);
for i = 1:length(startPoints)
paths{i} = gaGanOptimize(map, startPoints{i}, goalPoints{i});
% 将已规划路径作为动态障碍物
if i > 1
map = addDynamicObstacle(map, paths{i});
end
end
end
matlab复制function path = dynamicReplanning(oldPath, newObstacles)
% 检查原路径是否仍然可行
if checkCollision(oldPath, newObstacles)
% 从当前位置重新规划
currentPos = getUAVPosition();
remainingPath = oldPath(find(oldPath==currentPos):end,:);
path = localOptimization(remainingPath, newObstacles);
else
path = oldPath;
end
end
matlab复制function hardwareInLoopTest()
% 连接硬件
uav = connectUAV('COM3');
while true
% 获取实时环境数据
[pos, obstacles] = getSensorData(uav);
% 实时规划
path = realtimePlanning(pos, goal, obstacles);
% 发送控制指令
sendCommand(uav, path(1,:));
pause(0.1); % 控制频率10Hz
end
end
这个项目从理论到实践完整地实现了基于GA-GAN的无人机三维路径规划系统。通过MATLAB的强大功能,我们不仅实现了核心算法,还开发了友好的GUI界面,使技术能够真正落地应用。在实际测试中,相比传统方法,我们的方案在路径质量、计算效率和适应性方面都展现出明显优势。