-
Notifications
You must be signed in to change notification settings - Fork 3
/
fa.m
87 lines (79 loc) · 2.3 KB
/
fa.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
function [x,err,BestCost]=fa(CostFunction,nVar,MaxIt,nPop)
%% Variables
VarSize = [1 nVar]; % Decision Variables Matrix Size
VarMin = -5; % Decision Variables Lower Bound
VarMax = 5; % Decision Variables Upper Bound
%% Firefly Algorithm Parameters
MaxIt = MaxIt; % Maximum Number of Iterations
nPop = nPop; % Number of Fireflies (Swarm Size)
gamma = 2; % Light Absorption Coefficient
beta0 = 4; % Attraction Coefficient Base Value
alpha = 0.2; % Mutation Coefficient
alpha_damp = 0.98; % Mutation Coefficient Damping Ratio
delta = 0.05*(VarMax-VarMin); % Uniform Mutation Range
m = 2;
if isscalar(VarMin) && isscalar(VarMax)
dmax = (VarMax-VarMin)*sqrt(nVar);
else
dmax = norm(VarMax-VarMin);
end
%% Start
% Empty Firefly Structure
firefly.Position = [];
firefly.Cost = [];
% Initialize Population Array
pop = repmat(firefly, nPop, 1);
% Initialize Best Solution Ever Found
BestSol.Cost = inf;
% Create Initial Fireflies
for i = 1:nPop
pop(i).Position = unifrnd(VarMin, VarMax, VarSize);
pop(i).Cost = CostFunction(pop(i).Position);
if pop(i).Cost <= BestSol.Cost
BestSol = pop(i);
end
end
% Array to Hold Best Cost Values
BestCost = zeros(MaxIt, 1);
%% Firefly Algorithm Body
for it = 1:MaxIt
newpop = repmat(firefly, nPop, 1);
for i = 1:nPop
newpop(i).Cost = inf;
for j = 1:nPop
if pop(j).Cost < pop(i).Cost
rij = norm(pop(i).Position-pop(j).Position)/dmax;
beta = beta0*exp(-gamma*rij^m);
e = delta*unifrnd(-1, +1, VarSize);
newsol.Position = pop(i).Position ...
+ beta*rand(VarSize).*(pop(j).Position-pop(i).Position) ...
+ alpha*e;
newsol.Position = max(newsol.Position, VarMin);
newsol.Position = min(newsol.Position, VarMax);
newsol.Cost = CostFunction(newsol.Position);
if newsol.Cost <= newpop(i).Cost
newpop(i) = newsol;
if newpop(i).Cost <= BestSol.Cost
BestSol = newpop(i);
end
end
end
end
end
% Merge
pop = [pop
newpop];
% Sort
[~, SortOrder] = sort([pop.Cost]);
pop = pop(SortOrder);
% Truncate
pop = pop(1:nPop);
% Store Best Cost Ever Found
BestCost(it) = BestSol.Cost;
% Show Iteration Information
disp(['In Iteration ' num2str(it) ': FA Cost Is = ' num2str(BestCost(it))]);
% Damp Mutation Coefficient
alpha = alpha*alpha_damp;
end
x=BestSol.Position';
err=BestSol.Cost;