Matlab simulation for solving TSP business travel optimization problem based on simulated annealing algorithm

Table of contents

1. Introduction to simulated annealing algorithm theory

2.MATLAB core program

3.MATLAB simulation results


1. Introduction to simulated annealing algorithm theory

        The simulated annealing algorithm is an optimization algorithm based on the physical annealing process, which can effectively solve the TSP business travel optimization problem. The basic idea of ​​this algorithm is to find the global optimal solution by simulating the physical annealing process, conducting random searches in the solution space, and controlling the search process by adjusting the temperature parameters.
       The basic idea of ​​the simulated annealing algorithm is to introduce the physical annealing process into the optimization problem, and perform optimization search by simulating the characteristics of the physical annealing process. Specifically, this algorithm treats the TSP problem as a combinatorial optimization problem, and finds the optimal solution by continuously searching and optimizing feasible solutions. During the search process, the algorithm uses the characteristics of the physical annealing process to conduct random searches in the solution space and controls the search process by adjusting the temperature parameters. Initially, the algorithm starts randomly searching in the solution space at a higher temperature. As the temperature continues to decrease, the search range gradually shrinks, and finally the global optimal solution is found.
       In the simulated annealing algorithm, we mainly involve the calculation of the following formulas:

  1. Objective function: f(x) = sum_{i=1}^{n-1} d(x_i,x_{i+1}) + d(x_n,x_1) where x represents a feasible solution, that is, a traveling
    salesman Path, d(x_i,x_j) represents the distance between city x_i and city x_j.

  2. Initial temperature: T_0 = f(x_0) / ln(1/p)
    where, x_0 represents the initial solution, and p represents the probability of accepting an inferior solution.

  3. Cooling coefficient: alpha = 0.95
    The cooling coefficient determines the degree of temperature change after each cooling.

  4. New solution generation: x' = random_permutation(x)
    randomly generates a new solution x', which is obtained by randomly arranging the current solution x.

  5. Metropolis criterion: If f(x') < f(x), accept the new solution x'; otherwise, accept the new solution x' with probability exp((f(x)-f(x'))/T).
    The Metropolis criterion determines the acceptance probability of a new solution. If the objective function value of the new solution is better than the current solution, the new solution is accepted directly; otherwise, the new solution is accepted with a certain probability, which is determined by the current temperature and the objective function value of the new solution.

  6. Cooling: T = alpha * T
    After each iteration, the temperature is cooled according to the cooling coefficient.

  7. Termination condition: T < epsilon or the maximum number of iterations is reached.
    When the temperature is less than a set threshold epsilon or the maximum number of iterations is reached, the algorithm terminates.

       It should be noted that in practical applications, we need to select appropriate parameters and settings based on specific problem characteristics and scale, such as initial temperature, cooling coefficient, maximum number of iterations, etc. At the same time, when searching using the simulated annealing algorithm, we also need to pay attention to avoid falling into local optimal solutions and other problems. In addition, the simulated annealing algorithm is a heuristic algorithm, and its solution results may deviate from the optimal solution to the actual problem. Therefore, in practical applications, we need to conduct comprehensive analysis and comparison in combination with other algorithms and methods to obtain better solutions.

2.MATLAB core program

close all;
clc,clear                               %清空环境中的变量
tic
iter = 1;                               %迭代次数初值
a=0.99;                                 %温度衰减系数
t0=97;                                  %初始温度
tf=3;                                   %最后温度
t=t0;
Markov=500;                           %Markov链长度
load posi.txt                          %读入城市的坐标
city=posi;
n = size(city,1);                       %城市数目
D = zeros(n,n);                                                    
for i = 1:n                             
    for j = 1:n
        D(i,j) = sqrt(sum((city(i,:) - city(j,:)).^2));    
    end    
end                                                                                
route=1:n;         %产生初始解,route是每次产生的新解                     
route_new=route;   %route_new是当前解
best_route=route;  %best_route是冷却中的最好解
Length=Inf;        %Length是当前解对应的回路距离
best_length=Inf;   %best_length是最优解

%%
while t>=tf
    for j=1:Markov
	%产生随机扰动,长成新的序列route_new;
        if (rand<0.7)
        %交换两个数的顺序
            ind1=0;ind2=0;
            while(ind1==ind2&&ind1>=ind2)
                ind1=ceil(rand*n);          %进一取整
                ind2=ceil(rand*n);
            end                      
            temp=route_new(ind1);
            route_new(ind1)=route_new(ind2);
            route_new(ind2)=temp;
        else
            %三交换
            ind=zeros(3,1);
            L_ind=length(unique(ind));
            while (L_ind<3)
                ind=ceil([rand*n rand*n rand*n]);
                L_ind=length(unique(ind));
            end
            ind0=sort(ind);
            a1=ind0(1);b1=ind0(2);c1=ind0(3);
            route0=route_new;
            route0(a1:a1+c1-b1-1)=route_new(b1+1:c1);
            route0(a1+c1-b1:c1)=route_new(a1:b1);
            route_new=route0;    
        end 
        %计算路径的距离,Length_new 
        length_new = 0;
        Route=[route_new route_new(1)];%route_new(1)指第一个城市
        for j = 1:n
            length_new = length_new+ D(Route(j),Route(j + 1));
        end
        if length_new<Length      
            Length=length_new;
            route=route_new;
            %对最优路线和距离更新
            if length_new<best_length
                iter = iter + 1;    
                best_length=length_new;
                best_route=route_new;
            end
        else
            %若新解的目标函数值大于当前解,
            %则仅以一定概率接受新解
            if rand<exp(-(length_new-Length)/t)
                route=route_new;
                Length=length_new;
            end
        end
        route_new=route; 
    end              
	t=t*a;  %控制参数t(温度)减少为原来的a倍
end

%% 结果显示 
toc
Route=[best_route best_route(1)];
xy=[(city(Route ,1)),(city(Route ,2))]
fid=fopen('save1.txt','w+');
fprintf(fid,'%g  %g\n\t\t',xy)
plot([city(Route ,1)], [city(Route ,2)],'o-');
    disp('最优解为:')
    disp(best_route)
    disp('最短距离:')
    disp(best_length)
    disp('最优解迭代次数:')
    disp(iter)

for i = 1:n
    %对每个城市进行标号
%     xy=[city(i,1),city(i,2)]
    text(city(i,1),city(i,2),['   ' num2str(i)]);
end
xlabel('城市位置横坐标')
ylabel('城市位置纵坐标')
title(['模拟退火算法(最短距离):' num2str(best_length) ''])
up2229

3.MATLAB simulation results

       In MATLAB, the initial parameters of the simulated annealing algorithm are first set, including the number of cities, initial solution, initial temperature, cooling coefficient, maximum number of iterations, temperature threshold and probability of accepting inferior solutions. Then, the distance matrix between cities was randomly generated and the objective function was defined. Next, the main part of the simulated annealing algorithm is implemented using a while loop, including steps such as generating a new solution, calculating the objective function value, accepting the new solution or maintaining the current solution according to the Metropolis criterion, and cooling down. Finally, the optimal solution obtained by the algorithm and the objective function value of the optimal solution are output.

       In practical applications, we need to select appropriate parameters and settings based on specific problem characteristics and scale, such as initial temperature, cooling coefficient, maximum number of iterations, etc. At the same time, when searching using the simulated annealing algorithm, we also need to pay attention to avoid falling into local optimal solutions and other problems. In addition, the simulated annealing algorithm is a heuristic algorithm, and its solution results may deviate from the optimal solution to the actual problem.

Guess you like

Origin blog.csdn.net/ccsss22/article/details/133532799