-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathACO.m
117 lines (98 loc) · 3.01 KB
/
ACO.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
%% Ant colony optimization
clc
close all
clear
%% ACO paramters
n_iter=10; %number of iteration
NA=30; % Number of Ants
alpha=0.8; % alpha
beta=0.2; % beta
roh=0.7; % Evaporation rate
n_param=6; % Number of paramters
LB=[0.1 0.5 0.01 1 0.5 1]; % lower bound
UB=[1 1.5 0.5 6 5 6]; % upper bound
n_node=1000; % number of nodes for each param
%% intializing some variables
cost_best_prev=inf;
ant = zeros(NA,n_param);
cost = zeros(NA,1);
tour_selected_param = zeros(1,n_param);
param_mat = zeros(n_iter,n_param);
Nodes = zeros(n_node,n_param);
prob = zeros(n_node, n_param);
%% Generating Nodes
T=ones(n_node,n_param).*eps; % Phormone Matrix
dT=zeros(n_node,n_param); % Change of Phormone
for i=1:n_param
Nodes(:,i) =linspace(LB(i),UB(i),n_node); % Node generation at equal spaced points
end
%% Iteration loop
for iter=1:n_iter
for tour_i=1:n_param
prob(:,tour_i)= (T(:,tour_i).^alpha) .* ((1./Nodes(:,tour_i)).^beta);
prob(:,tour_i)=prob(:,tour_i)./sum(prob(:,tour_i));
end
for A=1:NA
for tour_i=1:n_param
node_sel=rand;
node_ind=1;
prob_sum=0;
for j=1:n_node
prob_sum=prob_sum+prob(j,tour_i);
if prob_sum>=node_sel
node_ind=j;
break
end
end
ant(A,tour_i)=node_ind;
tour_selected_param(tour_i) = Nodes(node_ind, tour_i);
end
cost(A)=cost_func(tour_selected_param);
clc
disp(['Ant number: ' num2str(A)])
disp(['Ant Cost: ' num2str(cost(A))])
disp(['Ant Paramters: ' num2str(tour_selected_param)])
if iter~=1
disp(['iteration: ' num2str(iter)])
disp('_________________')
disp(['Best cost: ' num2str(cost_best)])
for i=1:n_param
tour_selected_param(i) = Nodes(ant(cost_best_ind,i), i);
end
disp(['Best paramters: ' num2str(tour_selected_param)])
end
end
[cost_best,cost_best_ind]=min(cost);
% Elitsem
if (cost_best>cost_best_prev) && (iter~=1)
[cost_worst,cost_worst_ind]=max(cost);
ant(cost_worst_ind,:)=best_prev_ant;
cost_best=cost_best_prev;
cost_best_ind=cost_worst_ind;
else
cost_best_prev=cost_best;
best_prev_ant=ant(cost_best_ind,:);
end
dT=zeros(n_node,n_param); % Change of Phormone
for tour_i=1:n_param
for A=1:NA
dT(ant(A,tour_i),tour_i)=dT(ant(A,tour_i),tour_i)+cost_best/cost(A);
end
end
T= roh.*T + dT;
%% Plots , this section will not effect the algorithem
% you can remove it to speed up the run
cost_mat(iter)=cost_best;
figure(1)
plot(cost_mat)
% figure(2)
% for i=1:n_param
% tour_selected_param(i) = Nodes(ant(cost_best_ind,i), i);
% end
% % cost_func(tour_selected_param,1);
% %% store data
% param_mat(iter,:) = tour_selected_param;
% save('ACO_data.mat','cost_mat','param_mat')
% drawnow
% end
end