基于遗传算法(GA)的多旅行商问题(MTSP)

news2024/10/7 9:16:16

matlab2016b可运行,输入城市位置,可以动态显示规划过程 

 

% MTSPF_GA Fixed Multiple Traveling Salesmen Problem (M-TSP) Genetic Algorithm (GA)
%   Finds a (near) optimal solution to a variation of the M-TSP by setting
%   up a GA to search for the shortest route (least distance needed for
%   each salesman to travel from the start location to individual cities
%   and back to the original starting place)
%
% Summary:
%     1. Each salesman starts at the first point, and ends at the first
%        point, but travels to a unique set of cities in between
%     2. Except for the first, each city is visited by exactly one salesman
%
% Note: The Fixed Start/End location is taken to be the first XY point
%
% Input:
%     USERCONFIG (structure) with zero or more of the following fields:
%     - 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, NOT including the start/end point
%     - 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
%     - SHOWWAITBAR (scalar logical) shows a waitbar if true
%
% Input Notes:
%     1. Rather than passing in a structure containing these fields, any/all of
%        these inputs can be passed in as parameter/value pairs in any order instead.
%     2. Field/parameter names are case insensitive but must match exactly otherwise.
%
% Output:
%     RESULTSTRUCT (structure) with the following fields:
%         (in addition to a record of the algorithm configuration)
%     - 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 4 2 8 10 3 7], brks = [3 7]
%     Taken together, these represent the solution [1 5 6 9 1][1 4 2 8 10 1][1 3 7 1],
%     which designates the routes for the 3 salesmen as follows:
%         . Salesman 1 travels from city 1 to 5 to 6 to 9 and back to 1
%         . Salesman 2 travels from city 1 to 4 to 2 to 8 to 10 and back to 1
%         . Salesman 3 travels from city 1 to 3 to 7 and back to 1
%
% Usage:
%     mtspf_ga
%       -or-
%     mtspf_ga(userConfig)
%       -or-
%     resultStruct = mtspf_ga;
%       -or-
%     resultStruct = mtspf_ga(userConfig);
%       -or-
%     [...] = mtspf_ga('Param1',Value1,'Param2',Value2, ...);
%
% Example:
%     % Let the function create an example problem to solve
%     mtspf_ga;
%
% Example:
%     % Request the output structure from the solver
%     resultStruct = mtspf_ga;
%
% Example:
%     % Pass a random set of user-defined XY points to the solver
%     userConfig = struct('xy',10*rand(35,2));
%     resultStruct = mtspf_ga(userConfig);
%
% Example:
%     % Pass a more interesting set of XY points to the solver
%     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]));
%     userConfig = struct('xy',xy);
%     resultStruct = mtspf_ga(userConfig);
%
% Example:
%     % Pass a random set of 3D (XYZ) points to the solver
%     xyz = 10*rand(35,3);
%     userConfig = struct('xy',xyz);
%     resultStruct = mtspf_ga(userConfig);
%
% Example:
%     % Change the defaults for GA population size and number of iterations
%     userConfig = struct('popSize',200,'numIter',1e4);
%     resultStruct = mtspf_ga(userConfig);
%
% Example:
%     % Turn off the plots but show a waitbar
%     userConfig = struct('showProg',false,'showResult',false,'showWaitbar',true);
%     resultStruct = mtspf_ga(userConfig);
%
% See also: mtsp_ga, mtspo_ga, mtspof_ga, mtspofs_ga, mtspv_ga, distmat
%
% Author: Joseph Kirk
% Email: jdkirk630@gmail.com
% Release: 2.0
% Release Date: 05/01/2014
function varargout = mtspf_ga(varargin)

    % Initialize default configuration
    defaultConfig.xy          = 10*rand(80,2)
    defaultConfig.dmat        = [];  % N*N距离矩阵
    defaultConfig.nSalesmen   = 8;
    defaultConfig.minTour     = 3;
    defaultConfig.popSize     = 80;
    defaultConfig.numIter     = 5e3;
    defaultConfig.showProg    = true;
    defaultConfig.showResult  = true;
    defaultConfig.showWaitbar = false;

    % Interpret user configuration inputs
    if ~nargin
        userConfig = struct();
    elseif isstruct(varargin{1})
        userConfig = varargin{1};
    else
        try
            userConfig = struct(varargin{:});
        catch
            error('Expected inputs are either a structure or parameter/value pairs');
        end
    end

    % 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;
    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!')
    end
    n = N - 1; % Separate Start/End City

    % 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));
    showWaitbar = logical(showWaitbar(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) + 1;
    popBreak(1,:) = rand_breaks();
    for k = 2:popSize
        popRoute(k,:) = randperm(n) + 1;
        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
        figure('Name','MTSPF_GA | Current Best Solution','Numbertitle','off');
        hAx = gca;
    end
    if showWaitbar
        hWait = waitbar(0,'Searching for near-optimal solution ...');
    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(1,pRoute(rng(s,1))); % Add Start Distance
                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)),1); % Add End Distance
            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   实时展示最优路径
                for s = 1:nSalesmen
                    rte = [1 optRoute(rng(s,1):rng(s,2)) 1];
                    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,:)); end
                    hold(hAx,'on');
                end
                if dims > 2, plot3(hAx,xy(1,1),xy(1,2),xy(1,3),'o','Color',pclr);
                else plot(hAx,xy(1,1),xy(1,2),'o','Color',pclr); end
                title(hAx,sprintf('Total Distance = %1.4f, Iteration = %d',minDist,iter));
                hold(hAx,'off');
                drawnow;
            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;

        % Update the waitbar
        if showWaitbar && ~mod(iter,ceil(numIter/325))
            waitbar(iter/numIter,hWait);
        end

    end
    if showWaitbar
        close(hWait);
    end

    if showResult
        % Plots     画图
        figure('Name','MTSPF_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([1 optRoute],[1 optRoute]));
        title('Distance Matrix');
        subplot(2,2,3);
        rng = [[1 optBreak+1];[optBreak n]]';
        for s = 1:nSalesmen
            rte = [1 optRoute(rng(s,1):rng(s,2)) 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
        if dims > 2, plot3(xy(1,1),xy(1,2),xy(1,3),'o','Color',pclr);
        else plot(xy(1,1),xy(1,2),'o','Color',pclr); 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 Output
    if nargout
        resultStruct = struct( ...
            'xy',          xy, ...
            'dmat',        dmat, ...
            'nSalesmen',   nSalesmen, ...
            'minTour',     minTour, ...
            'popSize',     popSize, ...
            'numIter',     numIter, ...
            'showProg',    showProg, ...
            'showResult',  showResult, ...
            'showWaitbar', showWaitbar, ...
            'optRoute',    optRoute, ...
            'optBreak',    optBreak, ...
            'minDist',     minDist);

        varargout = {resultStruct};
    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

% Subfunction to override the default configuration with user inputs
% 将输入初始化,什么都不输入,就用这个应该是
function config = get_config(defaultConfig,userConfig)

    % Initialize the configuration structure as the default
    config = defaultConfig;

    % Extract the field names of the default configuration structure
    defaultFields = fieldnames(defaultConfig);

    % Extract the field names of the user configuration structure
    userFields = fieldnames(userConfig);
    nUserFields = length(userFields);

    % Override any default configuration fields with user values
    for i = 1:nUserFields
        userField = userFields{i};
        isField = strcmpi(defaultFields,userField);
        if nnz(isField) == 1
            thisField = defaultFields{isField};
            config.(thisField) = userConfig.(userField);
        end
    end

end

 

 

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

前后端分离,通用分页js处理模板

截图&#xff1a; 步骤&#xff1a; 第一步&#xff1a;创建一个index.html引入 <script src"./jquery-3.7.0.js"></script><link rel"stylesheet" href"https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstra…

想要wav转换mp3软件?看我给你分享将wav转换成mp3的软件

你是否曾经遇到过这样的情况&#xff1a;下载了一首你喜爱的音乐&#xff0c;却发现它的格式是wma&#xff0c;无法在你的设备或播放器上正常播放&#xff1f;别担心&#xff0c;今天我将向你介绍几款wma转换器&#xff0c;让你能够轻松转换音频格式&#xff0c;不再困惑于wma转…

Samba协议实现视频上传、远程播放

一、效果演示 扫码打开上传页面&#xff0c;上传进度可以全局筛选订单查看&#xff0c;上传过程中查看视频是本地视频&#xff08;速度快&#xff09;&#xff0c;上传完成后再次打开是smb服务器视频&#xff08;打开慢&#xff09; 本文涉及demo参考下载 二、集成smbj 1、集…

写毕业论文之前一定要看的经验总结!!!

本文为笔者关于毕业论文的经验总结 如果本文有错误的地方 或者关于论文有什么更好的经验分享欢迎私信或者评论指出 打开word的格式标记 打开标尺 摘要 标题 目录 分页 页码 图片 表格 参考文献 打开word的格式标记 word格式标记并不是真的存在&#xff0c;只是帮你你修改word时…

嵌入式工作的前景:为什么嵌入式系统需求仍在增长

嵌入式系统的需求在过去几十年中一直稳步增长&#xff0c;并且预计在未来仍然会继续增加。嵌入式系统是指嵌入到其他设备或系统中的计算机系统&#xff0c;它们具有特定的功能和任务。这些系统广泛应用于汽车、消费电子产品、医疗设备、智能家居、工业自动化等领域。 随着科技…

Quiz 10: Tuples | Python for Everybody 配套练习_解题记录

文章目录 课程简介Quiz 10: Tuples 单选题&#xff08;1-11&#xff09;编程题Exercise 10.2 课程简介 Python for Everybody 零基础程序设计&#xff08;Python 入门&#xff09; This course aims to teach everyone the basics of programming computers using Python. 本课…

【软件测试】Java+selenium环境搭建

目录 1.下载Chrome浏览器&#xff0c;查看浏览器的版本 2.根据浏览器版本下载驱动 根据电脑版本下载驱动&#xff1a; 3.去maven仓库寻找selenium驱动 4.在idea中创建一个项目 1.在pom.xml中添加依赖 2.点击右侧刷新按钮 3.在Java下创建一个类Main 4.将以下代码写入 5.…

B061-ES6 NodeJS npm Vue

目录 ECMAScript6什么是ECMAScriptECMAScript历史语法申明变量解构表达式箭头函数模块化 npm引出nodejs安装VUEvue简介配置Terminalvue入门vue属性-elvue属性-datavue属性-methods vue架构认识vue表达式vue-表达式-基础vue-表达式-操作对象&数组 vue-指令v-text & v-ht…

软件工程师,入门下深度学习吧

概述 ChatGPT,英文全称为Chat Generative Pre-trained Transformer,是OpenAI研发的聊天机器人程序。ChatGPT是人工智能技术驱动的自然语言处理工具,它能够通过理解和学习人类的语言来进行对话,还能根据聊天的上下文进行互动,真正像人类一样来聊天交流。除此之外,还能进行…

kettle架构图

2、架构说明 1&#xff09;最底层的是kettle的核心引擎层&#xff0c;相关的jar在lib目录下。 2&#xff09;中间是开发层&#xff0c;在开发阶段我们接触最多的就是通过spoon进行开发&#xff0c;通过Spoon.bat或者spoon.sh即可启动客户端&#xff0c;开发文件调试之前要先保…

使用vtk创建立方体,设置顶点为不同颜色

引言 改示例为官网上的例子。创建了一个顶点是不同颜色的立方体。 示例 开发环境 使用QtCreator4.11.2,Qt5.14.2。使用的vtk9.2的库及其头文件。创建空项目。 示例代码 其pro文件中的内容&#xff1a; QT core guigreaterThan(QT_MAJOR_VERSION, 4): QT widgets…

【半监督图像分类 ICLR 2023】FreeMatch

【半监督图像分类 ICLR 2023】FreeMatch 论文题目&#xff1a;FREEMATCH: SELF-ADAPTIVE THRESHOLDING FOR SEMI-SUPERVISED LEARNING 中文题目&#xff1a;Freematch&#xff1a;用于半监督学习的自适应阈值 论文链接&#xff1a;https://arxiv.org/abs/2205.07246 论文代码&a…

数字经济下的架构新图景—2023架构·可持续未来峰会(北京主会场)成功举办!

2023 年 6 月 29日&#xff0c;由The Open Group主办的2023架构可持续未来峰会&#xff08;北京主会场&#xff09;在机械工业出版社圆满落幕。 本次大会以“可持续未来”为主题&#xff0c;采取13&#xff0c;即北京主会场上海/成都/深圳三个城市峰会场模式&#xff0c;聚焦架…

android h5 宿舍报修管理系统myeclipse开发mysql数据库编程服务端java计算机程序设计

一、源码特点 android h5 宿舍报修管理系统是一套完善的WEBandroid设计系统&#xff0c;对理解JSP java&#xff0c;安卓app编程开发语言有帮助&#xff08;系统采用web服务端APP端 综合模式进行设计开发&#xff09;&#xff0c;系统具有完整的 源代码和数据库&#xff0c;系…

idea 修改Tool Windows后新建项目又恢复默认设置

我们可能会根据自己的喜好修改idea的工具窗口,但是每次新建项目它又会重置了,解决办法如下:

vscode C++开发记录

vscode C开发记录 插件管理Linux 平台针对编译好的程序进行 Dedug 插件管理 Linux 平台 针对编译好的程序进行 Dedug 右击源文件后&#xff0c;添加debug 配置 Add Debug Configuration 这是一个示例的调试配置文件&#xff0c;用于在VS Code中使用GDB调试已经编译好的程序 …

Sublime Text 初步使用

Sublime Text &#xff0c;最初被设计为一个具有丰富扩展功能的Vim。 Sublime Text具有漂亮的用户界面和强大的功能&#xff0c;例如代码缩略图&#xff0c;Python的插件&#xff0c;代码段等。还可自定义键绑定&#xff0c;菜单和工具栏。Sublime Text 的主要功能包括&#xf…

Vue常见面试题整理

一、对于MVVM的理解&#xff1f; MVVM是Model-View-ViewModel的缩写。 Model&#xff1a;代表数据模型&#xff0c;也可以在Model中定义数据修改和操作的业务逻辑。View&#xff1a;代表UI组件&#xff0c;它负责将数据模型转化成UI展现出来。ViewModel&#xff1a;监听模型数…

Equivariant Graph Neural Networks

论文链接&#xff1a;https://arxiv.org/abs/2102.09844 一种新模型来学习与旋转、平移、反射和排列等变的图神经网络&#xff0c;称为 E(n)-等变图神经网络 (EGNN) 尽管深度学习在很大程度上取代了手工制作的特征&#xff0c;但许多进步严重依赖于深度神经网络中的归纳偏差。…

linux watch命令

在Linux中&#xff0c;有时需要每隔一段时间比如一秒或者两秒刷新一次&#xff0c;这时就可以使用watch 命令。如图&#xff1a; 每隔两秒刷新查看一下磁盘使用情况。