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


相关文章
|
19天前
|
机器学习/深度学习 算法 数据安全/隐私保护
基于GA遗传优化的GroupCNN分组卷积网络时间序列预测算法matlab仿真
该算法结合了遗传算法(GA)与分组卷积神经网络(GroupCNN),利用GA优化GroupCNN的网络结构和超参数,提升时间序列预测精度与效率。遗传算法通过模拟自然选择过程中的选择、交叉和变异操作寻找最优解;分组卷积则有效减少了计算成本和参数数量。本项目使用MATLAB2022A实现,并提供完整代码及视频教程。注意:展示图含水印,完整程序运行无水印。
|
7天前
|
算法 决策智能
基于GA-PSO遗传粒子群混合优化算法的TSP问题求解matlab仿真
本文介绍了基于GA-PSO遗传粒子群混合优化算法解决旅行商问题(TSP)的方法。TSP旨在寻找访问一系列城市并返回起点的最短路径,属于NP难问题。文中详细阐述了遗传算法(GA)和粒子群优化算法(PSO)的基本原理及其在TSP中的应用,展示了如何通过编码、选择、交叉、变异及速度和位置更新等操作优化路径。算法在MATLAB2022a上实现,实验结果表明该方法能有效提高求解效率和解的质量。
|
28天前
|
算法 计算机视觉
Mat未初始化引起拼接算法结果,release版本和debug版本不一致
在OpenCV中由于Mat对象未初始化导致的拼接算法在release版本和debug版本中结果不一致的问题,并提供了通过显式初始化Mat对象为零来解决这一问题的修改方法。
|
2月前
|
算法
基于GA-PSO遗传粒子群混合优化算法的CVRP问题求解matlab仿真
本文介绍了一种基于GA-PSO混合优化算法求解带容量限制的车辆路径问题(CVRP)的方法。在MATLAB2022a环境下运行,通过遗传算法的全局搜索与粒子群算法的局部优化能力互补,高效寻找最优解。程序采用自然数编码策略,通过选择、交叉、变异操作及粒子速度和位置更新,不断迭代直至满足终止条件,旨在最小化总行驶距离的同时满足客户需求和车辆载重限制。
|
3月前
|
传感器 机器学习/深度学习 算法
基于GA遗传算法的WSN网络节点覆盖优化matlab仿真
本研究应用遗传优化算法于无线传感器网络(WSN),优化节点布局与数量,以最小化节点使用而最大化网络覆盖率。MATLAB2022a环境下,算法通过选择、交叉与变异操作,逐步改进节点配置,最终输出收敛曲线展现覆盖率、节点数及适应度值变化。无线传感器网络覆盖优化问题通过数学建模,结合遗传算法,实现目标区域有效覆盖与网络寿命延长。算法设计中,采用二进制编码表示节点状态,适应度函数考量覆盖率与连通性,通过选择、交叉和变异策略迭代优化,直至满足终止条件。
|
3月前
|
算法 数据安全/隐私保护
基于GA遗传优化算法的Okumura-Hata信道参数估计算法matlab仿真
在MATLAB 2022a中应用遗传算法进行无线通信优化,无水印仿真展示了算法性能。遗传算法源于Holland的理论,用于全局优化,常见于参数估计,如Okumura-Hata模型的传播损耗参数。该模型适用于150 MHz至1500 MHz的频段。算法流程包括选择、交叉、变异等步骤。MATLAB代码执行迭代,计算目标值,更新种群,并计算均方根误差(RMSE)以评估拟合质量。最终结果比较了优化前后的RMSE并显示了SNR估计值。
57 7
|
4月前
|
算法
基于GA遗传优化的混合发电系统优化配置算法matlab仿真
**摘要:** 该研究利用遗传算法(GA)对混合发电系统进行优化配置,旨在最小化风能、太阳能及电池储能的成本并提升系统性能。MATLAB 2022a用于实现这一算法。仿真结果展示了一系列图表,包括总成本随代数变化、最佳适应度随代数变化,以及不同数据的分布情况,如负荷、风速、太阳辐射、弃电、缺电和电池状态等。此外,代码示例展示了如何运用GA求解,并绘制了发电单元的功率输出和年变化。该系统原理基于GA的自然选择和遗传原理,通过染色体编码、初始种群生成、适应度函数、选择、交叉和变异操作来寻找最优容量配置,以平衡成本、效率和可靠性。
|
4月前
|
算法
基于GA-PSO遗传粒子群混合优化算法的VRPTW问题求解matlab仿真
摘要: 本文介绍了考虑时间窗的车辆路径问题(VRPTW),在MATLAB2022a中进行测试。VRPTW涉及车辆从配送中心出发,服务客户并返回,需在指定时间窗内完成且满足车辆容量限制,目标是最小化总行驶成本。文章探讨了遗传算法(GA)和粒子群优化(PSO)的基本原理及其在VRPTW中的应用,包括编码、适应度函数、选择、交叉、变异等步骤。同时,提出了动态惯性权重、精英策略、邻域搜索、多种群和启发式信息等优化策略,以应对时间窗限制并提升算法性能。
122 11
|
3月前
|
机器学习/深度学习 数据采集 算法
Python实现GA(遗传算法)对SVM分类模型参数的优化
Python实现GA(遗传算法)对SVM分类模型参数的优化
147 0
|
4月前
|
算法
m基于GA遗传优化的高斯白噪声信道SNR估计算法matlab仿真
**MATLAB2022a模拟展示了遗传算法在AWGN信道中估计SNR的效能。该算法利用生物进化原理全局寻优,解决通信系统中复杂环境下的SNR估计问题。核心代码执行多代选择、重组和突变操作,逐步优化SNR估计。结果以图形形式对比了真实SNR与估计值,并显示了均方根误差(RMSE),体现了算法的准确性。**
55 0

热门文章

最新文章