MAT之GA:遗传算法(GA)解决M-TSP多旅行商问题

本文涉及的产品
全球加速 GA,每月750个小时 15CU
简介: MTSP_GA Multiple Traveling Salesmen Problem (M-TSP) Genetic Algorithm (GA). Finds a (near) optimal solution to the M-TSP by setting up a GA to search for the shortest route (least distance needed for the salesmen to travel to each city exactly once and return to their starting locations)—————————

输出结果

image.png



实现代码


% MTSP_GA Multiple Traveling Salesmen Problem (M-TSP) Genetic Algorithm (GA)

%   Finds a (near) optimal solution to the M-TSP by setting up a GA to search

%   for the shortest route (least distance needed for the salesmen to travel

%   to each city exactly once and return to their starting locations)

%

% Summary:

%     1. Each salesman travels to a unique set of cities and completes the

%        route by returning to the city he started from

%     2. Each city is visited by exactly one salesman

%

% Input:

%     XY (float) is an Nx2 matrix of city locations, where N is the number of cities

%     DMAT (float) is an NxN matrix of city-to-city distances or costs

%     NSALESMEN (scalar integer) is the number of salesmen to visit the cities

%     MINTOUR (scalar integer) is the minimum tour length for any of the salesmen

%     POPSIZE (scalar integer) is the size of the population (should be divisible by 8)

%     NUMITER (scalar integer) is the number of desired iterations for the algorithm to run

%     SHOWPROG (scalar logical) shows the GA progress if true

%     SHOWRESULT (scalar logical) shows the GA results if true

%

% Output:

%     OPTROUTE (integer array) is the best route found by the algorithm

%     OPTBREAK (integer array) is the list of route break points (these specify the indices

%         into the route used to obtain the individual salesman routes)

%     MINDIST (scalar float) is the total distance traveled by the salesmen

%

% Route/Breakpoint Details:

%     If there are 10 cities and 3 salesmen, a possible route/break

%     combination might be: rte = [5 6 9 1 4 2 8 10 3 7], brks = [3 7]

%     Taken together, these represent the solution [5 6 9][1 4 2 8][10 3 7],

%     which designates the routes for the 3 salesmen as follows:

%         . Salesman 1 travels from city 5 to 6 to 9 and back to 5

%         . Salesman 2 travels from city 1 to 4 to 2 to 8 and back to 1

%         . Salesman 3 travels from city 10 to 3 to 7 and back to 10

%

% Example:

%     n = 35;

%     xy = 10*rand(n,2);

%     nSalesmen = 5;

%     minTour = 3;

%     popSize = 80;

%     numIter = 5e3;

%     a = meshgrid(1:n);

%     dmat = reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),n,n);

%     [optRoute,optBreak,minDist] = mtsp_ga(xy,dmat,nSalesmen,minTour, ...

%         popSize,numIter,1,1);

%

% Example:

%     n = 50;

%     phi = (sqrt(5)-1)/2;

%     theta = 2*pi*phi*(0:n-1);

%     rho = (1:n).^phi;

%     [x,y] = pol2cart(theta(:),rho(:));

%     xy = 10*([x y]-min([x;y]))/(max([x;y])-min([x;y]));

%     nSalesmen = 5;

%     minTour = 3;

%     popSize = 80;

%     numIter = 1e4;

%     a = meshgrid(1:n);

%     dmat = reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),n,n);

%     [optRoute,optBreak,minDist] = mtsp_ga(xy,dmat,nSalesmen,minTour, ...

%         popSize,numIter,1,1);

%

% Example:

%     n = 35;

%     xyz = 10*rand(n,3);

%     nSalesmen = 5;

%     minTour = 3;

%     popSize = 80;

%     numIter = 5e3;

%     a = meshgrid(1:n);

%     dmat = reshape(sqrt(sum((xyz(a,:)-xyz(a',:)).^2,2)),n,n);

%     [optRoute,optBreak,minDist] = mtsp_ga(xyz,dmat,nSalesmen,minTour, ...

%         popSize,numIter,1,1);

%

%

function varargout = mtsp_ga(xy,dmat,nSalesmen,minTour,popSize,numIter,showProg,showResult)


% Process Inputs and Initialize Defaults

nargs = 8;

for k = nargin:nargs-1

   switch k

       case 0

           xy = 10*rand(40,2);

       case 1

           N = size(xy,1);

           a = meshgrid(1:N);

           dmat = reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),N,N);

       case 2

           nSalesmen = 5;

       case 3

           minTour = 3;

       case 4

           popSize = 80;

       case 5

           numIter = 5e3;

       case 6

           showProg = 1;

       case 7

           showResult = 1;

       otherwise

   end

end


% Verify Inputs

[N,dims] = size(xy);

[nr,nc] = size(dmat);

if N ~= nr || N ~= nc

   error('Invalid XY or DMAT inputs!')

end

n = N;


% Sanity Checks

nSalesmen = max(1,min(n,round(real(nSalesmen(1)))));

minTour = max(1,min(floor(n/nSalesmen),round(real(minTour(1)))));

popSize = max(8,8*ceil(popSize(1)/8));

numIter = max(1,round(real(numIter(1))));

showProg = logical(showProg(1));

showResult = logical(showResult(1));


% Initializations for Route Break Point Selection

nBreaks = nSalesmen-1;

dof = n - minTour*nSalesmen;          % degrees of freedom

addto = ones(1,dof+1);

for k = 2:nBreaks

   addto = cumsum(addto);

end

cumProb = cumsum(addto)/sum(addto);


% Initialize the Populations

popRoute = zeros(popSize,n);         % population of routes

popBreak = zeros(popSize,nBreaks);   % population of breaks

popRoute(1,:) = (1:n);

popBreak(1,:) = rand_breaks();

for k = 2:popSize

   popRoute(k,:) = randperm(n);

   popBreak(k,:) = rand_breaks();

end


% Select the Colors for the Plotted Routes

pclr = ~get(0,'DefaultAxesColor');

clr = [1 0 0; 0 0 1; 0.67 0 1; 0 1 0; 1 0.5 0];

if nSalesmen > 5

   clr = hsv(nSalesmen);

end


% Run the GA

globalMin = Inf;

totalDist = zeros(1,popSize);

distHistory = zeros(1,numIter);

tmpPopRoute = zeros(8,n);

tmpPopBreak = zeros(8,nBreaks);

newPopRoute = zeros(popSize,n);

newPopBreak = zeros(popSize,nBreaks);

if showProg

   pfig = figure('Name','MTSP_GA | Current Best Solution','Numbertitle','off');

end

for iter = 1:numIter

   % Evaluate Members of the Population

   for p = 1:popSize

       d = 0;

       pRoute = popRoute(p,:);

       pBreak = popBreak(p,:);

       rng = [[1 pBreak+1];[pBreak n]]';

       for s = 1:nSalesmen

           d = d + dmat(pRoute(rng(s,2)),pRoute(rng(s,1)));

           for k = rng(s,1):rng(s,2)-1

               d = d + dmat(pRoute(k),pRoute(k+1));

           end

       end

       totalDist(p) = d;

   end


   % Find the Best Route in the Population

   [minDist,index] = min(totalDist);

   distHistory(iter) = minDist;

   if minDist < globalMin

       globalMin = minDist;

       optRoute = popRoute(index,:);

       optBreak = popBreak(index,:);

       rng = [[1 optBreak+1];[optBreak n]]';

       if showProg

           % Plot the Best Route

           figure(pfig);

           for s = 1:nSalesmen

               rte = optRoute([rng(s,1):rng(s,2) rng(s,1)]);

               if dims > 2, plot3(xy(rte,1),xy(rte,2),xy(rte,3),'.-','Color',clr(s,:));

               else plot(xy(rte,1),xy(rte,2),'.-','Color',clr(s,:)); end

               title(sprintf('Total Distance = %1.4f, Iteration = %d',minDist,iter));

               hold on

           end

           hold off

       end

   end


   % Genetic Algorithm Operators

   randomOrder = randperm(popSize);

   for p = 8:8:popSize

       rtes = popRoute(randomOrder(p-7:p),:);

       brks = popBreak(randomOrder(p-7:p),:);

       dists = totalDist(randomOrder(p-7:p));

       [ignore,idx] = min(dists); %#ok

       bestOf8Route = rtes(idx,:);

       bestOf8Break = brks(idx,:);

       routeInsertionPoints = sort(ceil(n*rand(1,2)));

       I = routeInsertionPoints(1);

       J = routeInsertionPoints(2);

       for k = 1:8 % Generate New Solutions

           tmpPopRoute(k,:) = bestOf8Route;

           tmpPopBreak(k,:) = bestOf8Break;

           switch k

               case 2 % Flip

                   tmpPopRoute(k,I:J) = tmpPopRoute(k,J:-1:I);

               case 3 % Swap

                   tmpPopRoute(k,[I J]) = tmpPopRoute(k,[J I]);

               case 4 % Slide

                   tmpPopRoute(k,I:J) = tmpPopRoute(k,[I+1:J I]);

               case 5 % Modify Breaks

                   tmpPopBreak(k,:) = rand_breaks();

               case 6 % Flip, Modify Breaks

                   tmpPopRoute(k,I:J) = tmpPopRoute(k,J:-1:I);

                   tmpPopBreak(k,:) = rand_breaks();

               case 7 % Swap, Modify Breaks

                   tmpPopRoute(k,[I J]) = tmpPopRoute(k,[J I]);

                   tmpPopBreak(k,:) = rand_breaks();

               case 8 % Slide, Modify Breaks

                   tmpPopRoute(k,I:J) = tmpPopRoute(k,[I+1:J I]);

                   tmpPopBreak(k,:) = rand_breaks();

               otherwise % Do Nothing

           end

       end

       newPopRoute(p-7:p,:) = tmpPopRoute;

       newPopBreak(p-7:p,:) = tmpPopBreak;

   end

   popRoute = newPopRoute;

   popBreak = newPopBreak;

end


if showResult

% Plots

   figure('Name','MTSP_GA | Results','Numbertitle','off');

   subplot(2,2,1);

   if dims > 2, plot3(xy(:,1),xy(:,2),xy(:,3),'.','Color',pclr);

   else plot(xy(:,1),xy(:,2),'.','Color',pclr); end

   title('City Locations');

   subplot(2,2,2);

   imagesc(dmat(optRoute,optRoute));

   title('Distance Matrix');

   subplot(2,2,3);

   rng = [[1 optBreak+1];[optBreak n]]';

   for s = 1:nSalesmen

       rte = optRoute([rng(s,1):rng(s,2) rng(s,1)]);

       if dims > 2, plot3(xy(rte,1),xy(rte,2),xy(rte,3),'.-','Color',clr(s,:));

       else plot(xy(rte,1),xy(rte,2),'.-','Color',clr(s,:)); end

       title(sprintf('Total Distance = %1.4f',minDist));

       hold on;

   end

   subplot(2,2,4);

   plot(distHistory,'b','LineWidth',2);

   title('Best Solution History');

   set(gca,'XLim',[0 numIter+1],'YLim',[0 1.1*max([1 distHistory])]);

end


% Return Outputs

if nargout

   varargout{1} = optRoute;

   varargout{2} = optBreak;

   varargout{3} = minDist;

end


   % Generate Random Set of Break Points

   function breaks = rand_breaks()

       if minTour == 1 % No Constraints on Breaks

           tmpBreaks = randperm(n-1);

           breaks = sort(tmpBreaks(1:nBreaks));

       else % Force Breaks to be at Least the Minimum Tour Length

           nAdjust = find(rand < cumProb,1)-1;

           spaces = ceil(nBreaks*rand(1,nAdjust));

           adjust = zeros(1,nBreaks);

           for kk = 1:nBreaks

               adjust(kk) = sum(spaces == kk);

           end

           breaks = minTour*(1:nBreaks) + cumsum(adjust);

       end

   end

end


相关文章
|
2月前
|
算法 安全 定位技术
【创新未发表】【无人机路径巡检】三维地图路径规划无人机路径巡检GWO孙发、IGWO、GA、PSO、NRBO五种智能算法对比版灰狼算法遗传研究(Matlab代码实现)
【创新未发表】【无人机路径巡检】三维地图路径规划无人机路径巡检GWO孙发、IGWO、GA、PSO、NRBO五种智能算法对比版灰狼算法遗传研究(Matlab代码实现)
232 40
|
5月前
|
机器学习/深度学习 算法 数据安全/隐私保护
基于GA遗传优化的BiLSTM双向长短期记忆网络序列预测算法matlab仿真,对比BiLSTM和LSTM
本内容包含基于BiLSTM与遗传算法(GA)的算法介绍及实现。算法通过MATLAB2022a/2024b运行,核心为优化BiLSTM超参数(如学习率、神经元数量),提升预测性能。LSTM解决传统RNN梯度问题,捕捉长期依赖;BiLSTM双向处理序列,融合前文后文信息,适合全局信息任务。附完整代码(含注释)、操作视频及无水印运行效果预览,适用于股票预测等场景,精度优于单向LSTM。
|
6月前
|
算法 数据安全/隐私保护
基于GA遗传算法的悬索桥静载试验车辆最优布载matlab仿真
本程序基于遗传算法(GA)实现悬索桥静载试验车辆最优布载的MATLAB仿真(2022A版)。目标是自动化确定车辆位置,使加载效率ηq满足0.95≤ηq≤1.05且尽量接近1,同时减少车辆数量与布载时间。核心原理通过优化模型平衡最小车辆使用与ηq接近1的目标,并考虑桥梁载荷、车辆间距等约束条件。测试结果展示布载方案的有效性,适用于悬索桥承载能力评估及性能检测场景。
|
2月前
|
机器学习/深度学习 边缘计算 并行计算
【无人机三维路径规划】基于遗传算法GA结合粒子群算法PSO无人机复杂环境避障三维路径规划(含GA和PSO对比)研究(Matlab代码代码实现)
【无人机三维路径规划】基于遗传算法GA结合粒子群算法PSO无人机复杂环境避障三维路径规划(含GA和PSO对比)研究(Matlab代码代码实现)
244 2
|
6月前
|
算法 JavaScript 数据安全/隐私保护
基于GA遗传优化的最优阈值计算认知异构网络(CHN)能量检测算法matlab仿真
本内容介绍了一种基于GA遗传优化的阈值计算方法在认知异构网络(CHN)中的应用。通过Matlab2022a实现算法,完整代码含中文注释与操作视频。能量检测算法用于感知主用户信号,其性能依赖检测阈值。传统固定阈值方法易受噪声影响,而GA算法通过模拟生物进化,在复杂环境中自动优化阈值,提高频谱感知准确性,增强CHN的通信效率与资源利用率。预览效果无水印,核心程序部分展示,适合研究频谱感知与优化算法的学者参考。
|
3月前
|
机器学习/深度学习 算法 调度
基于遗传算法GA算法优化BP神经网络(Python代码实现)
基于遗传算法GA算法优化BP神经网络(Python代码实现)
265 0
|
3月前
|
机器学习/深度学习 数据采集 算法
【遗传算法(GA)和模拟退火(SA)对翼型升阻比进行优化】基于神经网络和无导数算法的翼型优化(Matlab代码实现)
【遗传算法(GA)和模拟退火(SA)对翼型升阻比进行优化】基于神经网络和无导数算法的翼型优化(Matlab代码实现)
123 0
|
3月前
|
机器学习/深度学习 算法 安全
【无人机协同】基于APSO PSO CS-PSO MP_PSO A-PSO GA多种算法实现无人机路径协同规划研究(Matlab代码复现)
【无人机协同】基于APSO PSO CS-PSO MP_PSO A-PSO GA多种算法实现无人机路径协同规划研究(Matlab代码复现)
139 0
|
3月前
|
算法 Java 调度
【车间调度】基于GA、PSO、SA、ACO、TS优化算法的车间调度比较研究(Matlab代码实现)
【车间调度】基于GA、PSO、SA、ACO、TS优化算法的车间调度比较研究(Matlab代码实现)
187 0
|
6月前
|
传感器 算法 数据安全/隐私保护
基于GA遗传优化的三维空间WSN网络最优节点部署算法matlab仿真
本程序基于遗传算法(GA)优化三维空间无线传感网络(WSN)的节点部署,通过MATLAB2022A实现仿真。算法旨在以最少的节点实现最大覆盖度,综合考虑空间覆盖、连通性、能耗管理及成本控制等关键问题。核心思想包括染色体编码节点位置、适应度函数评估性能,并采用网格填充法近似计算覆盖率。该方法可显著提升WSN在三维空间中的部署效率与经济性,为实际应用提供有力支持。

热门文章

最新文章