MAT之GA:遗传算法(GA)解决M-TSP多旅行商问题
MAT之GA:遗传算法(GA)解决M-TSP多旅行商问题
导读
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)
目录
输出结果
实现代码
输出结果
实现代码
% 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-1switch kcase 0xy = 10*rand(40,2);case 1N = size(xy,1);a = meshgrid(1:N);dmat = reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),N,N);case 2nSalesmen = 5;case 3minTour = 3;case 4popSize = 80;case 5numIter = 5e3;case 6showProg = 1;case 7showResult = 1;otherwiseend
end% Verify Inputs
[N,dims] = size(xy);
[nr,nc] = size(dmat);
if N ~= nr || N ~= ncerror('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:nBreaksaddto = 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:popSizepopRoute(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 > 5clr = 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 showProgpfig = figure('Name','MTSP_GA | Current Best Solution','Numbertitle','off');
end
for iter = 1:numIter% Evaluate Members of the Populationfor p = 1:popSized = 0;pRoute = popRoute(p,:);pBreak = popBreak(p,:);rng = [[1 pBreak+1];[pBreak n]]';for s = 1:nSalesmend = d + dmat(pRoute(rng(s,2)),pRoute(rng(s,1)));for k = rng(s,1):rng(s,2)-1d = d + dmat(pRoute(k),pRoute(k+1));endendtotalDist(p) = d;end% Find the Best Route in the Population[minDist,index] = min(totalDist);distHistory(iter) = minDist;if minDist < globalMinglobalMin = minDist;optRoute = popRoute(index,:);optBreak = popBreak(index,:);rng = [[1 optBreak+1];[optBreak n]]';if showProg% Plot the Best Routefigure(pfig);for s = 1:nSalesmenrte = 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,:)); endtitle(sprintf('Total Distance = %1.4f, Iteration = %d',minDist,iter));hold onendhold offendend% Genetic Algorithm OperatorsrandomOrder = randperm(popSize);for p = 8:8:popSizertes = popRoute(randomOrder(p-7:p),:);brks = popBreak(randomOrder(p-7:p),:);dists = totalDist(randomOrder(p-7:p));[ignore,idx] = min(dists); %#okbestOf8Route = rtes(idx,:);bestOf8Break = brks(idx,:);routeInsertionPoints = sort(ceil(n*rand(1,2)));I = routeInsertionPoints(1);J = routeInsertionPoints(2);for k = 1:8 % Generate New SolutionstmpPopRoute(k,:) = bestOf8Route;tmpPopBreak(k,:) = bestOf8Break;switch kcase 2 % FliptmpPopRoute(k,I:J) = tmpPopRoute(k,J:-1:I);case 3 % SwaptmpPopRoute(k,[I J]) = tmpPopRoute(k,[J I]);case 4 % SlidetmpPopRoute(k,I:J) = tmpPopRoute(k,[I+1:J I]);case 5 % Modify BreakstmpPopBreak(k,:) = rand_breaks();case 6 % Flip, Modify BreakstmpPopRoute(k,I:J) = tmpPopRoute(k,J:-1:I);tmpPopBreak(k,:) = rand_breaks();case 7 % Swap, Modify BreakstmpPopRoute(k,[I J]) = tmpPopRoute(k,[J I]);tmpPopBreak(k,:) = rand_breaks();case 8 % Slide, Modify BreakstmpPopRoute(k,I:J) = tmpPopRoute(k,[I+1:J I]);tmpPopBreak(k,:) = rand_breaks();otherwise % Do NothingendendnewPopRoute(p-7:p,:) = tmpPopRoute;newPopBreak(p-7:p,:) = tmpPopBreak;endpopRoute = newPopRoute;popBreak = newPopBreak;
endif showResult
% Plotsfigure('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); endtitle('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:nSalesmenrte = 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,:)); endtitle(sprintf('Total Distance = %1.4f',minDist));hold on;endsubplot(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 nargoutvarargout{1} = optRoute;varargout{2} = optBreak;varargout{3} = minDist;
end% Generate Random Set of Break Pointsfunction breaks = rand_breaks()if minTour == 1 % No Constraints on BreakstmpBreaks = randperm(n-1);breaks = sort(tmpBreaks(1:nBreaks));else % Force Breaks to be at Least the Minimum Tour LengthnAdjust = find(rand < cumProb,1)-1;spaces = ceil(nBreaks*rand(1,nAdjust));adjust = zeros(1,nBreaks);for kk = 1:nBreaksadjust(kk) = sum(spaces == kk);endbreaks = minTour*(1:nBreaks) + cumsum(adjust);endend
end
MAT之GA:遗传算法(GA)解决M-TSP多旅行商问题相关推荐
- MATLAB遗传算法GA求解TSP旅行商问题,可选PMX交叉、OX交叉及其它多种交叉方式,在算法中引入2-opt变异算子
MATLAB遗传算法GA求解TSP旅行商问题,可选PMX交叉.OX交叉及其它多种交叉方式,在算法中引入2-opt变异算子.进化逆转算子提高算法局部搜索能力,利用国际通用的TSPLIB数据集中的eil5 ...
- GA遗传算法及相关代码
GA遗传算法解决TSP问题 Matlab函数 随机数生成函数: rand(n,1):返回n个0到1随机数排列的列向量. randn(n,1):类似,服从标准正态分布. randperm(n):返回n以 ...
- 遗传算法(GA)入门知识梳理(超详细)
目录 一.遗传算法的生物背景 二.遗传算法(GA)思想 2.1遗传算法的组成 2.2编码 2.3适应度函数 2.4遗传算子 2.4 运行参数 三.基本遗传算法(SGA)伪代码 3.1算法流程图 3.2 ...
- 【优化算法】遗传算法GA求解混合流水车间调度问题(附C++代码)
[优化算法]遗传算法GA求解混合流水车间调度问题(附C++代码) 00 前言 各位读者大家好,好久没有介绍算法的推文了,感觉愧对了读者们热爱学习的心灵.于是,今天我们带来了一个神奇的优化算法--遗传算 ...
- GA遗传算法c语言,遗传算法GA(Genetic Algorithm)入门知识梳理
一.遗传算法进化论背景知识 作为遗传算法生物背景的介绍,下面内容了解即可: 种群(Population):生物的进化以群体的形式进行,这样的一个群体称为种群. 个体:组成种群的单个生物. 基因 ( G ...
- Algorithm之OP:OP之GA遗传算法思路理解相关配图资料
Optimality之GA遗传算法思路理解相关配图资料 目录 GA遗传算法思路理解 GA算法过程 1.总体思路 2.各个步骤 GA算法代码 1.伪代码 SGA实例讲解 1.求函数最值 2.求连续函数的 ...
- MAT之GA:GA优化BP神经网络的初始权值、阈值,从而增强BP神经网络的鲁棒性
MAT之GA:GA优化BP神经网络的初始权值.阈值,从而增强BP神经网络的鲁棒性 目录 输出结果 实现代码 输出结果 实现代码 global p global t global R global S1 ...
- nlm算法matlab代码_遗传算法GA的MATLAB代码
MATLAB 实现算法代码: GA (遗传算法)--整数编码 function [BestGene,aa] = GA(MaxGeneration,GeneSize,GeneNum,pcross,pmu ...
- c遗传算法的终止条件一般_Matlab2 :Matlab遗传算法(GA)优4~-r-具箱是基于基本操作 联合开发网 - pudn.com...
Matlab2 所属分类:matlab例程 开发工具:PDF 文件大小:115KB 下载次数:76 上传日期:2007-09-07 20:04:29 上 传 者:钱广 说明: :Matlab遗传算法 ...
- GA遗传算法(Genetic Algorithm)
遗传算法(Genetic Algorithm)又叫基因进化算法,或进化算法.属于启发式搜索算法一种,这个算法比较有趣,并且弄明白后很简单,写个100-200行代码就可以实现.在某些场合下简单有效.本文 ...
最新文章
- Flutter开发之布局-2-row(16)
- 递归删除父节点及所有子节点(转)
- Linux的文本字段统计方法
- Wireshark抓包—maybe caused by 'IP chechsum offload'?
- accept 阻塞怎么断开_暖气片放水就热不放水了就不热,怎么解决?
- java web 柱状图_使用JFreeChart实现基于Web的柱状图
- 基于组块设计执行开放世界等距游戏引擎
- 解答网友提问:如何构建动态表达式实现高级查询服务
- wince6.0 s5pv210 中断
- Hadoop精华问答 | NameNode的工作特点
- 控制只读_用Python控制硬件44-四位半万用表UT61E
- ArcGIS学习总结(11)——创建点要素并计算对应经纬度
- 深入学习smali语法
- 一种内嵌P2P的wifi转红外发射神器
- 用python的turtle画分形树
- 【Windows】Windows如何使用注册表修改软件默认安装路径?
- 使用python爬取高德POI数据,并转换为WGS84经纬度坐标的点矢量
- 深度分析:一次Wi-Fi入侵实录(1)
- Java实现利用QQ邮箱发送邮件
- python大神代码_求python大神写一个windows可运行的代码,学习学习。