function [BestTourLength, BestTour] = ACSTSP(distances_matrix, number_of_ants, MaxIterations, alpha, beta, rho, target_length) % Ant Colony System for the TSP % % ACSTSP(distances_matrix, number_of_ants, MaxIterations, alpha, beta, rho, target_length) % % distances_matrix: symmeric real (NrOfNodes x NrOfNodes)-matrix containing distances % between all nodes: d[i,i] =0, d[i,j]=d[j,i] % MaxIterations: maximum number of iterations to run % target_length: if a tour is found with less than target_length, the function returns % stops and returns this tour. % % parameter standard values: % number_of_ants = NrOfNodes % alpha =1 % beta =9 % rho =0.9 % % returns [BestTourLength, BestTour] clc; load distances_matrix.mat %d = distances_matrix; %define d 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 =========================================================== % pheromone trails %c =1/ (n * L_nn); c =10^-6; tau = ones(n,n) * c; % place m ants in n nodes ant_tours = zeros(m, n+1); ant_tours(:,1) = randint(m,1,[1,48]); t =1; while ((t <= t_max) & (L_target < L_best)) % CREATE TOURS ============================================================= 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,:); % update pheromone trails; 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