【TSP问题】基于粒子群算法求解旅行商问题matlab代码

223 阅读4分钟

1 算法介绍

1.1 TSP介绍

“旅行商问题”(Traveling Salesman Problem,TSP)可简单描述为:一位销售商从n个城市中的某一城市出发,不重复地走完其余n-1个城市并回到原出发点,在所有可能路径中求出路径长度最短的一条。

旅行商的路线可以看作是对n城市所设计的一个环形,或者是对一列n个城市的排列。由于对n个城市所有可能的遍历数目可达(n-1)!个,因此解决这个问题需要O(n!)的计算时间。而由美国密执根大学的Holland教授发展起来的遗传算法,是一种求解问题的高效并行全局搜索方法,能够解决复杂的全局优化问题,解决TSP问题也成为遗传算法界的一个目标。

1.2 粒子群算法

粒子群优化算法(PSO)是由心理学家Kennedy和Eberhart博士在1995年共同提出的一种新的模仿鸟群行为的智能优化算法。该算法概念简单、实现方便、收敛速度快、参数设置少,是一种高效的搜索算法,目前被广泛应用于函数优化、神经网络训练等领域。粒子群优化算法通过粒子之间的集体协作使群体达到最优。在粒子群优化算法中,每个个体称为一个“粒 子”,代表一个潜在的解。粒子在飞行过程中能够记住自己找到的最好位置,称为“局部最优pbest”,此外还记住群体中所有粒子找到的最好位置,称为“全局最优gbest”,然后根据这两个最优来调整自己的飞行方向与飞行速度,即粒子群中的粒子根据式(1)和式(2)来更新自己的飞行速度与飞行距离。

图片

2 部分代码

function [BestSol,BestCost]=pso(N,Range,MaxIt,nPop)

global X Y

%% Problem Definition

CostFunction=@(x) Sphere(x);        % Cost Function

nVar=N;            % Number of Decision Variables

VarSize=[1 nVar];   % Size of Decision Variables Matrix

VarMin=Range(1);         % Lower Bound of Variables
VarMax=Range(2);         % Upper Bound of Variables


%% PSO Parameters

%MaxIt=1000;     % Maximum Number of Iterations

%nPop=100;       % Population Size (Swarm Size)

% PSO Parameters
w=.0;            % Inertia Weight
wdamp=.03;     % Inertia Weight Damping Ratio
c1=2.33;         % Personal Learning Coefficient
c2=1.33;         % Global Learning Coefficient

% If you would like to use Constriction Coefficients for PSO,
% uncomment the following block and comment the above set of parameters.

% % Constriction Coefficients
% phi1=0.05;
% phi2=0.05;
% phi=phi1+phi2;
% chi=2/(phi-2+sqrt(phi^2-4*phi));
% w=chi;         % Inertia Weight
% wdamp=.1;       % Inertia Weight Damping Ratio
% c1=chi*phi1;   % Personal Learning Coefficient
% c2=chi*phi2;   % Global Learning Coefficient

% Velocity Limits
VelMax=1*(VarMax-VarMin);
VelMin=-VelMax;

%% Initialization

empty_particle.Position=[];
empty_particle.Cost=[];
empty_particle.Velocity=[];
empty_particle.Best.Position=[];
empty_particle.Best.Cost=[];

particle=repmat(empty_particle,nPop,1);

GlobalBest.Cost=inf;

for i=1:nPop
   
   % Initialize Position
   iv=0;
%     while(iv<=10000)
   m=unifrnd(VarMin,VarMax,VarSize);
   
%     m1=zeros(rows, columns, 'double');
%     randRows = randperm(rows);
%     for col = 1 : columns % Pick out "onesPerColumn" rows that will be set to 1.
%       m1(randRows(col), col) = 1;
%     end
% 
%     m=m1(:);
%     
%     
%     con1=subconstraint(m);
%     if(sum(con1)==2)
%         break;
%     end
%     iv=iv+1;
%     end
   particle(i).Position=m;
   
   % Initialize Velocity
   particle(i).Velocity=zeros(VarSize);
   
   % Evaluation
   particle(i).Cost=CostFunction(particle(i).Position);
   
   % Update Personal Best
   particle(i).Best.Position=particle(i).Position;
   particle(i).Best.Cost=particle(i).Cost;
   
   % Update Global Best
   if particle(i).Best.Cost<GlobalBest.Cost
       
       GlobalBest=particle(i).Best;
       
   end
   
end

BestCost=zeros(MaxIt,1);

%% PSO Main Loop

for it=1:MaxIt
   
   for i=1:nPop
       
       % Update Velocity
       %A=GlobalBest.Position;
       %GlobalBest.Position=reshape(A,1,nVar);
%         size(GlobalBest.Position)
%         size(particle(i).Position)

       particle(i).Velocity = w.*particle(i).Velocity ...
           +c1*rand(VarSize).*(particle(i).Best.Position-particle(i).Position) ...
           +c2*rand(VarSize).*(GlobalBest.Position-particle(i).Position);
       
       % Apply Velocity Limits
       particle(i).Velocity = max(particle(i).Velocity,VelMin);
       particle(i).Velocity = min(particle(i).Velocity,VelMax);
       
       % Update Position
       particle(i).Position = particle(i).Position + particle(i).Velocity;
       
       %% obey constarint
  
   end
   
   BestCost(it)=GlobalBest.Cost;
   
   disp(['Iteration ' num2str(it) ': Best Cost = ' num2str(BestCost(it))]);
   
   w=w*wdamp;
   
   %%
   m1 =GlobalBest.Position;
  [val,ind]=sort(m1,'descend');
   path=[ind ind(1)];
  
   


%clf;
 cla;
 hold on
for p =1:(size(path,2))-1
line([X(path(p)) X(path(p+1))], [Y(path(p)) Y(path(p+1))], 'Color','m','LineWidth',2, 'LineStyle','-') 
arrow([X(path(p)) Y(path(p)) ], [X(path(p+1)) Y(path(p+1)) ])
end 
hold on 
              
for i2 = 1:nVar
 plot(X(i2),Y(i2),'o','LineWidth',1,...
              'MarkerEdgeColor','k',...
              'MarkerFaceColor','w',...
              'MarkerSize',8)
          xlabel('X in m')
          ylabel('Y in m')
    text(X(i2)+2, Y(i2), num2str(i2),'FontSize',10)
hold on

plot(X(path(1)),Y(path(1)),'o','LineWidth',1,...
              'MarkerEdgeColor','k',...
              'MarkerFaceColor','g',...
              'MarkerSize',10)
          xlabel('X in m')
          ylabel('Y in m')
         

end 
pause(0.05);

end

BestSol = GlobalBest;

%% Results

% figure;
% %plot(BestCost,'LineWidth',2);
% semilogy(BestCost,'LineWidth',2);
% xlabel('Iteration');
% ylabel('Best Cost');
% grid on;

3 仿真结果

4 参考文献

[1]沈继红, 王侃. 求解旅行商问题的混合粒子群优化算法[J]. 智能系统学报, 2012(02):84-92.

部分理论引用网络文献,若有侵权联系博主删除。