基于改进遗传算法求解 TSP/MTSP 【旅行推销员问题 (TSP)、多旅行推销员问题 (M-TSP) 】(Matlab代码实现)

news/2024/4/25 5:03:53/文章来源:https://blog.csdn.net/weixin_46039719/article/details/126965982

 目录

1 概述

2 旅行商问题 

3 遗传算法

4 约束优化

5 带有罚方法的遗传算法的流程图

6 带有惩罚函数的遗传算法在TSP中的应用

7 运行结果

7.1 单旅行商问题

 7.2 多旅行商问题

8 Matlab代码实现

9 参考文献

10 写在最后


1 概述

主要研究用遗传算法解决带有约束的TSP的方法。使用贪婪交叉算子、自适应变异算子和带有精英保留策略的选择算子相结合对基本遗传算法进行了改进,针对实际TSP中的约束条件讨论了罚方法在遗传算法中的应用,提出了自适应的惩罚函数,并将其与改进后的遗传算法相结合,解决了带有时间约束的TSP。通过对实验结果的比较分析,证明了该方法的可行性和有效性。

2 旅行商问题 

3 遗传算法

遗传算法是1975年由John Holland教授提出。它借用了仿真生物遗传学和自然选择机理,通过自然选择、交叉、变异等机制实现各个个体适应性的提高。遗传算法在整个进化过程中的遗传操作是随机的;但是它呈现出来的特性却并不是完全随机的,它能够有效地利用历史信息使得下一代群体性能有所提高,一代一代不断进化,最终收敛到一个即使不是最优解,也是离最优解非常接近的解空间上。遗传算法涉及到编码方式、初始种群、适应度函数、遗传算子和控制参数五大要素。
基本遗传算法虽然具有全局搜索能力,但是在进化过程中往往容易出现收敛速度缓慢或不收敛,又或陷入局部最优的情况,加快收敛速度又有可能出现早熟现象,过或不及都不能及时准确地获得最优解。因此,学者们在这些方面进行了大量的研究,希望既能加快收敛速度,又能防止早熟收敛。
 

4 约束优化

5 带有罚方法的遗传算法的流程图

6 带有惩罚函数的遗传算法在TSP中的应用

                                    取一段路线并颠倒该段中城市的顺序

 取路线中的两个城市并按路径顺序交换它们的位置

                将一个城市拉出路线并将其重新插入另一个地方,将其他城市滑落

7 运行结果

7.1 单旅行商问题

 7.2 多旅行商问题

8 Matlab代码实现

本文仅展现部分代码,全部代码点击链接:

基于改进遗传算法求解 TSP/MTSP 【旅行推销员问题 (TSP)、多旅行推销员问题 (M-TSP) 】(Matlab代码实现)

function varargout = mtspof_ga(varargin)%% Initialize default configuration%defaultConfig.xy          = 10*rand(40,2);defaultConfig.dmat        = [];defaultConfig.nSalesmen   = 5;defaultConfig.minTour     = 1;defaultConfig.popSize     = 80;defaultConfig.numIter     = 5e3;defaultConfig.showProg    = true;defaultConfig.showStatus  = true;defaultConfig.showResult  = true;defaultConfig.showWaitbar = false;%% Interpret user configuration inputs%if ~narginuserConfig = struct();elseif isstruct(varargin{1})userConfig = varargin{1};elsetryuserConfig = struct(varargin{:});catcherror('??? Expected inputs are either a structure or parameter/value pairs');endend%% Override default configuration with user inputs%configStruct = get_config(defaultConfig,userConfig);%% Extract configuration%xy          = configStruct.xy;dmat        = configStruct.dmat;nSalesmen   = configStruct.nSalesmen;minTour     = configStruct.minTour;popSize     = configStruct.popSize;numIter     = configStruct.numIter;showProg    = configStruct.showProg;showStatus  = configStruct.showStatus;showResult  = configStruct.showResult;showWaitbar = configStruct.showWaitbar;if isempty(dmat)nPoints = size(xy,1);a = meshgrid(1:nPoints);dmat = reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),nPoints,nPoints);end%% Verify inputs%[N,dims] = size(xy);[nr,nc] = size(dmat);if (N ~= nr) || (N ~= nc)error('??? Invalid XY or DMAT inputs')endn = N - 2; % Separate start and end cities%% 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));showStatus  = logical(showStatus(1));showResult  = logical(showResult(1));showWaitbar = logical(showWaitbar(1));%% Initializations for route break point selection%nBreaks = nSalesmen-1;dof = n - minTour*nSalesmen;          % degrees of freedomaddto = ones(1,dof+1);for k = 2:nBreaksaddto = cumsum(addto);endcumProb = cumsum(addto)/sum(addto);%% Initialize the populations%popRoute = zeros(popSize,n);         % population of routespopBreak = zeros(popSize,nBreaks);   % population of breakspopRoute(1,:) = (1:n) + 1;popBreak(1,:) = rand_breaks();for k = 2:popSizepopRoute(k,:) = randperm(n) + 1;popBreak(k,:) = rand_breaks();end%% Seed the algorithm with a previous result if available%if all(isfield(userConfig,{'optRoute','optBreak'}))optRoute = userConfig.optRoute;optBreak = userConfig.optBreak;isValidRoute = isequal(popRoute(1,:),sort(optRoute));isValidBreak = all(optBreak > 0) && all(optBreak <= n) && ...(length(optBreak) == nBreaks) && ~any(mod(optBreak,1));if isValidRoute && isValidBreakpopRoute(1,:) = optRoute;popBreak(1,:) = optBreak;endend%% 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%row = zeros(popSize,n+nSalesmen);col = zeros(popSize,n+nSalesmen);isValid = false(1,n+nSalesmen);globalMin = Inf;distHistory = NaN(1,numIter);tmpPopRoute = zeros(8,n);tmpPopBreak = zeros(8,nBreaks);newPopRoute = zeros(popSize,n);newPopBreak = zeros(popSize,nBreaks);[isClosed,isStopped,isCancelled] = deal(false);if showProghFig = figure('Name','MTSPOF_GA | Current Best Solution', ...'Numbertitle','off','CloseRequestFcn',@close_request);hAx = gca;if showStatus[hStatus,isCancelled] = figstatus(0,numIter,[],hFig);endendif showWaitbarhWait = waitbar(0,'Searching for near-optimal solution ...', ...'CreateCancelBtn',@cancel_search);endisRunning = true;for iter = 1:numIter%% EVALUATE SOLUTIONS%   This section of code computes the total cost of each solution%   in the population. The actual code that gets executed uses a%   much faster (vectorized) method to calculate the route lengths%   compared to the triple for-loop below (provided for reference)%   but gives the same result.%%     totalDist = zeros(popSize,1);%     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(1,pRoute(rng(s,1)));%             for k = rng(s,1):rng(s,2)-1%                 d = d + dmat(pRoute(k),pRoute(k+1));%             end%             d = d + dmat(pRoute(rng(s,2)),N);%         end%         totalDist(p) = d;%     end%for p = 1:popSizebrk = popBreak(p,:);isValid(:) = false;isValid([1 brk+(2:nSalesmen)]) = true;row(p,isValid) = 1;row(p,~isValid) = popRoute(p,:);isValid(:) = false;isValid([brk+(1:nSalesmen-1) n+nSalesmen]) = true;col(p,isValid) = N;col(p,~isValid) = popRoute(p,:);endind = N*(col-1) + row;totalDist = sum(dmat(ind),2);%% SELECT THE BEST%   This section of code finds the best solution in the current%   population and stores it if it is better than the previous best.%[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%for s = 1:nSalesmenrte = [1 optRoute(rng(s,1):rng(s,2)) N];if (dims > 2), plot3(hAx,xy(rte,1),xy(rte,2),xy(rte,3),'.-','Color',clr(s,:));else, plot(hAx,xy(rte,1),xy(rte,2),'.-','Color',clr(s,:)); endhold(hAx,'on');endif (dims > 2), plot3(hAx,xy(1,1),xy(1,2),xy(1,3),'o','Color',pclr);plot3(hAx,xy(N,1),xy(N,2),xy(N,3),'o','Color',pclr);else, plot(hAx,xy(1,1),xy(1,2),'o','Color',pclr);plot(hAx,xy(N,1),xy(N,2),'o','Color',pclr);endtitle(hAx,sprintf('Total Distance = %1.4f, Iteration = %d',minDist,iter));hold(hAx,'off');drawnow;endend%% Update the status bar and check cancellation status%if showProg && showStatus && ~mod(iter,ceil(numIter/100))[hStatus,isCancelled] = figstatus(iter,numIter,hStatus,hFig);endif (isStopped || isCancelled)breakend%% MODIFY THE POPULATION%   This section of code invokes the genetic algorithm operators.%   In this implementation, solutions are randomly assigned to groups%   of eight and the best solution is kept (tournament selection).%   The best-of-eight solution is then mutated 3 different ways%   (flip, swap, and slide) and the four resulting solutions are%   then copied but assigned different break points to complete the%   group of eight. There is no crossover operator because it tends%   to be highly destructive and rarely improves a decent solution.%randomOrder = 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(randperm(n,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;%% Update the waitbar%if showWaitbar && ~mod(iter,ceil(numIter/325))waitbar(iter/numIter,hWait);endendif showProg && showStatusfigstatus(numIter,numIter,hStatus,hFig);endif showWaitbardelete(hWait);endisRunning = false;if isCloseddelete(hFig);end%% Append prior distance history if present%if isfield(userConfig,'distHistory')priorHistory = userConfig.distHistory;isNan = isnan(priorHistory);distHistory = [priorHistory(~isNan) distHistory];end%% Format the optimal solution%optSolution = cell(nSalesmen,1);rng = [[1 optBreak+1];[optBreak n]]';for s = 1:nSalesmenoptSolution{s} = [1 optRoute(rng(s,1):rng(s,2)) N];end%% Show the final results%if showResult%% Plot the GA results%figure('Name','MTSPOF_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([1 optRoute N],[1 optRoute N]));title('Distance Matrix');subplot(2,2,3);for s = 1:nSalesmenrte = optSolution{s};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;endif (dims > 2), plot3(xy(1,1),xy(1,2),xy(1,3),'o','Color',pclr);plot3(xy(N,1),xy(N,2),xy(N,3),'o','Color',pclr);else, plot(xy(1,1),xy(1,2),'o','Color',pclr);plot(xy(N,1),xy(N,2),'o','Color',pclr);endsubplot(2,2,4);plot(distHistory,'b','LineWidth',2);title('Best Solution History');set(gca,'XLim',[1 length(distHistory)],'YLim',[0 1.1*max([1 distHistory])]);end%% Return output%if nargout%% Create anonymous functions for plot generation%plotPoints  = @(s)plot(s.xy(:,1),s.xy(:,2),'.','Color',~get(gca,'Color'));plotResult  = @(s)cellfun(@(s,i)plot(s.xy(i,1),s.xy(i,2),'.-', ...'Color',rand(1,3)),repmat({s},size(s.optSolution)),s.optSolution);plotHistory = @(s)plot(s.distHistory,'b-','LineWidth',2);plotMatrix  = @(s)imagesc(s.dmat(cat(2,s.optSolution{:}),cat(2,s.optSolution{:})));%% Save results in output structure%resultStruct = struct( ...'xy',          xy, ...'dmat',        dmat, ...'nSalesmen',   nSalesmen, ...'minTour',     minTour, ...'popSize',     popSize, ...'numIter',     numIter, ...'showProg',    showProg, ...'showResult',  showResult, ...'showWaitbar', showWaitbar, ...'optRoute',    optRoute, ...'optBreak',    optBreak, ...'optSolution', {optSolution}, ...'plotPoints',  plotPoints, ...'plotResult',  plotResult, ...'plotHistory', plotHistory, ...'plotMatrix',  plotMatrix, ...'distHistory', distHistory, ...'minDist',     minDist);varargout = {resultStruct};end%% Generate random set of break points%function breaks = rand_breaks()if (minTour == 1) % No constraints on breaksbreaks = sort(randperm(n-1,nBreaks));else % Force breaks to be at least the minimum tour lengthnAdjust = find(rand < cumProb,1)-1;spaces = randi(nBreaks,1,nAdjust);adjust = zeros(1,nBreaks);for kk = 1:nBreaksadjust(kk) = sum(spaces == kk);endbreaks = minTour*(1:nBreaks) + cumsum(adjust);endend%% Nested function to cancel search%function cancel_search(varargin)isStopped = true;end%% Nested function to close the figure window%function close_request(varargin)if isRunning[isClosed,isStopped] = deal(true);isRunning = false;elsedelete(hFig);endendend

9 参考文献

[1]蒋泰,陈洺均,黄源.带有约束优化的遗传算法求解TSP[J].计算机应用研究,2008,25(5):1323-1325

10 写在最后

部分理论引用网络文献,如有侵权请联系删除。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_11621.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

kafka和flink的入门到精通 4 生产数据流程

参考023 - 大数据 - Kafka - 生产者 - 生产数据的准备_哔哩哔哩_bilibili 链接&#xff1a;https://pan.baidu.com/s/1QMOJVkRy4nKkjzoDryvQXw 提取码&#xff1a;fcoe 本文接着上一篇kafka和flink的入门到精通 3 组件扩展&#xff0c;kafka-生产者_水w的博客-CSDN博客 目录 …

今天是虚拟机

乌班图打开终端的方法ctrl+alt+t 接下来就是关于使用xftp来实现连接虚拟机 这儿就拿重点来讲一下 获取虚拟机的ip地址 通过打开虚拟机的终端(别的虚拟机如何打开不清楚,但是这个打开的方法我放在上面) 输入ifconfig,如果非虚拟机的话就输入ipconfig 如果没有显示虚拟机的ip…

net二手手帐

开发工具(eclipse/idea/vscode等)&#xff1a;vs2017 数据库(sqlite/mysql/sqlserver等)&#xff1a;sqlserver 功能模块(请用文字描述&#xff0c;至少200字)&#xff1a;本网站的基本内容是设计并实现一个二手手帐文具交易网&#xff0c;手帐文具爱好者们可以足不出户地交易自…

基于StarterWare的TMS320C6748裸机程序开发入门详解教程

LED裸机程序开发 本小结将讲解如何利用TI提供的StarterWare软件包开发一个基于DSP C6748的LED流水灯程序,以及如何查找芯片的技术参考手册和数据手册。文章内容主要涵盖LED裸机程序开发、工程建立、添加头文件和库文件、源代码编写和解析和按键中断裸机程序演示和解析等。 关…

Win10系统C++调用OpenCV实现网络摄像头录像和抓拍图片

1 前言 前边文章介绍了在WIN10系统上&#xff0c;分别用C和Python调用OpenCV接口&#xff0c;播放本地和网络摄像头视频。本篇我们来看一下&#xff0c;用C如何调用OpenCV接口&#xff0c;打开网络摄像头的视频&#xff0c;对其进行录像&#xff0c;并抓拍图片。 视频来源 视频…

公众号网课答案查题系统-全网都在使用

公众号网课答案查题系统-全网都在使用 本平台优点&#xff1a; 多题库查题、独立后台、响应速度快、全网平台可查、功能最全&#xff01; 1.想要给自己的公众号获得查题接口&#xff0c;只需要两步&#xff01; 2.题库&#xff1a; 题库&#xff1a;题库后台&#xff08;点击…

深度强化学习-DQN算法

论文地址&#xff1a;https://arxiv.org/abs/1312.5602 先讲下在线&#xff0c;离线&#xff0c;同策略和异策略 同策略&#xff08;on-policy&#xff09;和异策略&#xff08;off-policy&#xff09;的根本区别在于生成样本的策略和参数更新时的策略是否相同。 对于同策略&am…

产品性能测试入门秘籍

前言 在《一体化测试指标可视工程实践》中&#xff0c;我们分享了以趣链BaaS系统为例的测试实践路径&#xff0c;在后台收到读者们关于性能测试的留言。为此&#xff0c;本期将围绕如何进行产品性能测试这一话题&#xff0c;展开详细描述。 众所周知&#xff0c;一个优秀的系统…

Cobalt Strike(八)权限提升

1.BypassUAC UAC 是微软在 Windows Vista 以后版本引入的一种安全机制&#xff0c;通过 UAC&#xff0c;应用程序和任务可始终在非管理员帐户的安全上下文中运行&#xff0c;除非管理员特别授予管理员级别的系统访问权限。UAC 可以阻止未经授权的应用程序自动进行安装&#xf…

【最新计算机毕业设计】Java springboot大学生体质测评系统

基于SpringBoot的大学生体质测评系统 提供最新的计算机毕业设计源代码及帮助指导&#xff0c;公众号&#xff1a;一点毕设&#xff01; 大学生体质测试管理系统提供给用户一个简单方便体质测试管理信息&#xff0c;通过留言区互动更方便。本系统采用了B/S体系的结构&#xff0…

吔队列了你——写点单调队列优化DP

5_Lei:有没有变态一点的图啊单调队列优化DP(补) 前言: DP显然是OI中的一个重要且高频的考点,然而友善的出题人大多不会只考一个推转移方程,往往需要结合一些优化。 单调队列: 看这个的应该都会,不写了,扔个板子上去。 P1886 滑动窗口 /【模板】单调队列 优化DP: 显然…

行业话题 | 天天坐地铁,你知道BIM在地铁中的应用吗

近年来&#xff0c;随着经济水平的不断提高和城市化进程的加快&#xff0c;我国地铁建设规模也在不断加大&#xff0c;而地铁车站是地铁施工的难点和控制性工程&#xff0c;具有施工空间狭小&#xff0c;技术复杂等特点。 由于施工现场布置制约因素多&#xff0c;二维施工现场平…

究竟都是谁在使用?OpenMLDB 落地案例大起底

本文整理自第四范式资深架构师、OpenMLDB PMC 卢冕在第四范式技术日「高效落地的AI开源生态」分论坛的主题分享——《开源机器学习数据库 OpenMLDB&#xff1a;提供线上线下一致的生产特征平台》。内容包括&#xff1a; 感恩 OpenMLDB 贡献者OpenMLDB 发展历程OpenMLDB 架构设…

WinForms时代结束,报表控件FastReport.NET开启FastReport.Core.Skia 时代!

要创建高质量的报告并将其正确导出为不同的格式&#xff08;PDF、Word、Excel 等&#xff09;&#xff0c;必须使用图形引擎。从 .NET Framework 的最早版本开始&#xff0c;Microsoft 就将 GDI 及其包装器用作 System.Drawing 库的一部分。FastReport.NET长期以来一直使用相同…

第一篇文章 mybatis 综述

mybatis框架可以让程序员只需专注于写sql语句 框架就是半成品&#xff0c;将公共的部分固定下来&#xff0c;非公共的部分你自己开发就行 三层架构&#xff1a; 界面层Conttroller层&#xff1a;用来接收客户端的输入&#xff0c;调用业务逻辑层Service层&#xff0c;返回结果…

关于Facebook营销的十个常见问题,一次性讲清楚!

--- NO.1--- 为什么做Facebook营销&#xff1f; 作为全球最大的社交媒体&#xff0c;Facebook月活用户已达到了惊人的29亿&#xff0c;并且这个数据还在持续增长中&#xff0c;这意味着全球几乎一半人都会出现在Facebook上。很多企业对Facebook的关注点&#xff0c;也从是否做…

VMware Explore 大会发布重磅云上技术之外,VMware 有哪些前沿探索?

编辑 | 宋慧 出品 | CSDN 云计算 最近&#xff0c;VMware 举办了年度技术大会 VMware Explore&#xff0c;重磅发布了其在多云趋势下的多个技术产品组合&#xff0c;包含了云基础架构、云原生、网络与安全、远程混合办公等等。不过&#xff0c;在这些优势领域的产品之外&#…

系统架构与设计(1)- 权限系统的设计以及主流的五种权限模型

作者:码猿技术专栏来源:https://juejin.cn/post/7121977695197970463 ------------------------------------------------------------------- 这篇文章就来介绍一下权限系统的设计以及主流的五种权限模型。权限管控可以通俗的理解为权力限制,即不同的人由于拥有不同权力,他…

阿里云国际站代理商:FFmpeg 处理音视频文件的常用方法

阿里云代理商&#xff08;聚搜云&#xff09;专业服务于阿里云ECS服务器采购、阿里云Ddos采购、阿里云waf采购、对象存储OSS、阿里云企业邮箱采购、阿里云国际站代理商、阿里云国际站充值、云安全中心&#xff08;态势感知&#xff09;、阿里云高可用云数据库RDS、web应用云waf…

YOLO系列目标检测算法-Scaled-YOLOv4

YOLO系列目标检测算法目录 YOLO系列目标检测算法总结对比YOLOv1YOLOv2YOLOv3YOLOv4 Scaled-YOLOv4- 文章链接 YOLOv5- 文章链接 YOLOv6- 文章链接 YOLOv7- 文章链接 本文总结&#xff1a; 提出一种网络缩放方法&#xff0c;使得基于CSP的YOLOv4可以上下伸缩&#xff0c;以适…