Ant Colony System for the TSP (Matlab Code)

function [BestTourLength,BestTour] = ACSTSP(distances_matrix,number_of_ants,MaxIterations,alpha,beta,rho,target_length)


%AntColonySystem
for theTSP
%
%ACSTSP(distances_matrix,number_of_ants,MaxIterations,alpha,beta,rho,target_length)
%
%distances_matrix:symmericreal(NrOfNodesxNrOfNodes)
- matrixcontainingdistances
%betweenallnodes:d[i,i]
= 0 ,d[i,j] = d[j,i]
%MaxIterations:maximumnumberofiterations
to run
%target_length:
if atour is found with lessthantarget_length,the function returns
%stops
and returnsthistour.
%
%parameterstandardvalues:
%number_of_ants
= NrOfNodes
%alpha
= 1
%beta
= 9
%rho
= 0.9
%
%returns[BestTourLength,BestTour]


clc;


loaddistances_matrix.mat
%d
= distances_matrix;%defined
d
= dis;
n
= max(size(d));
%m
= number_of_ants;
m
= 48 ;
%t_max
= MaxIterations;
t_max
= 100 ;
%L_target
= target_length;
L_target
= 32000 ;


alpha
= 1
beta
= 9
rho
= 0.9


%[L_nn,P_nn]
= NearestNeighborTSP(d);


L_best
= inf;
T_best
= 0 ;


%INITIALIZATION
===========================================================


%pheromonetrails
%c
= 1 / (n * L_nn);
c
= 10 ^- 6 ;
tau
= ones(n,n) * c;


%placemantsinnnodes
ant_tours
= zeros(m,n + 1 );
ant_tours(:,
1 ) = randint(m, 1 ,[ 1 , 48 ]);


t
= 1 ;
while ((t <= t_max) & (L_target < L_best))


%CREATETOURS
=============================================================


for s = 2 :n
for k = 1 :m
current_node
= ant_tours(k,s - 1 );
visited
= ant_tours(k,:);
to_visit
= setdiff([ 1 :n],visited);
c_tv
= length(to_visit);
p
= zeros( 1 ,c_tv);
for i = 1 :c_tv
p(i)
= (tau(current_node,to_visit(i))) ^ alpha * ( 1 / d(current_node,to_visit(i))) ^ beta;
end
sum_p
= sum(p);
p
= p / sum_p;
for i = 2 :c_tv
p(i)
= p(i) + p(i - 1 );
end
r
= rand;
select = to_visit(c_tv);
for i = 1 :c_tv
if (r <= p(i))
select = to_visit(i);
break;
end
end
city_to_visit
= select ;
ant_tours(k,s)
= city_to_visit;
tau(current_node,city_to_visit)
= ( 1 - rho) * tau(current_node,city_to_visit) + c;
end
end


%UPDATE
===================================================================


ant_tours(:,n
+ 1 ) = ant_tours(:, 1 );
L_T
= zeros( 1 ,m);
best_ant
= 1 ;
for k = 1 :m
P
= ant_tours(k,:);
L
= 0 ;
for i = 1 :n
L
= L + d(P(i),P(i + 1 ));
end
L_T(k)
= L;
if (L_T(k) < L_T(best_ant))
best_ant
= k;
end
end
L_min
= min(L_T);
T_min
= ant_tours(best_ant,:);


%updatepheromonetrails;
for i = 1 :n
tau(T_min(i),T_min(i
+ 1 )) = ( 1 - rho) * tau(T_min(i),T_min(i + 1 )) + rho / L_min;
end


%COMPLETE
================================================================
clc;
t
= t + 1
current_cities
= ant_tours(:,n);
ant_tours
= zeros(m,n + 1 );
ant_tours(:,
1 ) = current_cities;
if (L_min < L_best)
L_best
= L_min;
T_best
= T_min;
end
L_best


end %ends while


clc;
t
BestTourLength
= L_best
BestTour
= T_best


你可能感兴趣的:(C++,c,ant,C#,matlab)