-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaco.m
125 lines (71 loc) · 2.16 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
112
113
114
115
116
117
118
119
120
121
122
123
124
clc;
clear;
close all;
%% Problem Definition
model = CreateModel();
CostFunction = @(tour) TourLength(tour, model);
nVar = model.n;
%% ACO Parameters
MaxIt = 300; % Maximum Number of Iterations
nAnt = 40; % Number of Ants (Population Size)
Q = 1;
tau0 = 10*Q/(nVar*mean(model.D(:))); % Initial Phromone
alpha = 1; % Phromone Exponential Weight
beta = 1; % Heuristic Exponential Weight
rho = 0.05; % Evaporation Rate
%% Initialization
eta = 1./model.D; % Heuristic Information Matrix
tau = tau0*ones(nVar, nVar); % Phromone Matrix
BestCost = zeros(MaxIt, 1); % Array to Hold Best Cost Values
% Empty Ant
empty_ant.Tour = [];
empty_ant.Cost = [];
% Ant Colony Matrix
ant = repmat(empty_ant, nAnt, 1);
% Best Ant
BestSol.Cost = inf;
%% ACO Main Loop
for it = 1:MaxIt
% Move Ants
for k = 1:nAnt
ant(k).Tour = randi([1 nVar]);
for l = 2:nVar
i = ant(k).Tour(end);
P = tau(i, :).^alpha.*eta(i, :).^beta;
P(ant(k).Tour) = 0;
P = P/sum(P);
j = RouletteWheelSelection(P);
ant(k).Tour = [ant(k).Tour j];
end
ant(k).Cost = CostFunction(ant(k).Tour);
if ant(k).Cost<BestSol.Cost
BestSol = ant(k);
end
end
% Update Phromones
for k = 1:nAnt
tour = ant(k).Tour;
tour = [tour tour(1)]; %#ok
for l = 1:nVar
i = tour(l);
j = tour(l+1);
tau(i, j) = tau(i, j)+Q/ant(k).Cost;
end
end
% Evaporation
tau = (1-rho)*tau;
% Store Best Cost
BestCost(it) = BestSol.Cost;
% Show Iteration Information
disp(['Iteration ' num2str(it) ': Best Cost = ' num2str(BestCost(it))]);
% Plot Solution
figure(1);
PlotSolution(BestSol.Tour, model);
pause(0.01);
end
%% Results
figure;
plot(BestCost, 'LineWidth', 2);
xlabel('Iteration');
ylabel('Best Cost');
grid on;