✅作者简介:热爱科研的Matlab仿真开发者,修心和技术同步精进,matlab项目合作可私信。
🍎个人主页:Matlab科研工作室
🍊个人信条:格物致知。
更多Matlab仿真内容点击👇
⛄ 内容介绍
FA算法的基本思想是,低亮度的萤火虫会被绝对亮度比它大的萤火虫吸引并向其靠笼,根据位置更新公式更新自身位置,使所有萤火虫向亮度高的萤火虫移动从而实现寻优的目的。由于FA算法中的最优是根据䖵火虫的绝对亮度来定的,因此,需要建立苗火虫的绝对亮度与目标函数值之间的关系。萤火虫对萤火虫的相对亮度的定义式为
FA算法的基本流程如图1所示。算法初始化阶段主要将萤火虫均匀随机分布于搜索空间内,并根据亮度公式计算出每个萤火虫的亮度,然后亮度低的萤火虫被亮度高的萤火虫所吸引并向其移动,按式(7)更新位置,重新计算萤火虫亮度,最后在达到精度要求或最大迭代次数后结束。
⛄ 完整代码
% Usage: firefly_simple([number_of_fireflies,MaxGeneration])
% eg: firefly_simple([12,50]);
function [best]=firefly_simple(instr)
% n=number of fireflies
% MaxGeneration=number of pseudo time steps
if nargin<1, instr=[12 50]; end
n=instr(1); MaxGeneration=instr(2);
rand('state',0); % Reset the random generator
% ------ Four peak functions ---------------------
str1='exp(-(x-4)^2-(y-4)^2)+exp(-(x+4)^2-(y-4)^2)';
str2='+2*exp(-x^2-(y+4)^2)+2*exp(-x^2-y^2)';
funstr=strcat(str1,str2);
% Converting to an inline function
f=vectorize(inline(funstr));
% range=[xmin xmax ymin ymax];
range=[-5 5 -5 5];
% ------------------------------------------------
alpha=0.2; % Randomness 0--1 (highly random)
gamma=1.0; % Absorption coefficient
% ------------------------------------------------
% Grid values are used for display only
Ngrid=100;
dx=(range(2)-range(1))/Ngrid;
dy=(range(4)-range(3))/Ngrid;
[x,y]=meshgrid(range(1):dx:range(2),...
range(3):dy:range(4));
z=f(x,y);
% Display the shape of the objective function
figure(1); surfc(x,y,z);
% ------------------------------------------------
% generating the initial locations of n fireflies
[xn,yn,Lightn]=init_ffa(n,range);
% Display the paths of fireflies in a figure with
% contours of the function to be optimized
figure(2);
% Iterations or pseudo time marching
for i=1:MaxGeneration, %%%%% start iterations
% Show the contours of the function
contour(x,y,z,15); hold on;
% Evaluate new solutions
zn=f(xn,yn);
% Ranking the fireflies by their light intensity
[Lightn,Index]=sort(zn);
xn=xn(Index); yn=yn(Index);
xo=xn; yo=yn; Lighto=Lightn;
% Trace the paths of all roaming fireflies
plot(xn,yn,'.','markersize',10,'markerfacecolor','g');
% Move all fireflies to the better locations
[xn,yn]=ffa_move(xn,yn,Lightn,xo,yo,Lighto,alpha,gamma,range);
drawnow;
% Use "hold on" to show the paths of fireflies
hold off;
end %%%%% end of iterations
best(:,1)=xo'; best(:,2)=yo'; best(:,3)=Lighto';
% ----- All subfunctions are listed here ---------
% The initial locations of n fireflies
function [xn,yn,Lightn]=init_ffa(n,range)
xrange=range(2)-range(1);
yrange=range(4)-range(3);
xn=rand(1,n)*xrange+range(1);
yn=rand(1,n)*yrange+range(3);
Lightn=zeros(size(yn));
% Move all fireflies toward brighter ones
function [xn,yn]=ffa_move(xn,yn,Lightn,xo,yo,...
Lighto,alpha,gamma,range)
ni=size(yn,2); nj=size(yo,2);
for i=1:ni,
% The attractiveness parameter beta=exp(-gamma*r)
for j=1:nj,
r=sqrt((xn(i)-xo(j))^2+(yn(i)-yo(j))^2);
if Lightn(i)<Lighto(j), % Brighter and more attractive
beta0=1; beta=beta0*exp(-gamma*r.^2);
xn(i)=xn(i).*(1-beta)+xo(j).*beta+alpha.*(rand-0.5);
yn(i)=yn(i).*(1-beta)+yo(j).*beta+alpha.*(rand-0.5);
end
end % end for j
end % end for i
[xn,yn]=findrange(xn,yn,range);
% Make sure the fireflies are within the range
function [xn,yn]=findrange(xn,yn,range)
for i=1:length(yn),
if xn(i)<=range(1), xn(i)=range(1); end
if xn(i)>=range(2), xn(i)=range(2); end
if yn(i)<=range(3), yn(i)=range(3); end
if yn(i)>=range(4), yn(i)=range(4); end
end
% ============== end =====================================
% ======================================================== %
% Files of the Matlab programs included in the book: %
function fa_mincon
% parameters [n N_iteration alpha betamin gamma]
para=[40 150 0.5 0.2 1];
help fa_mincon.m
% This demo uses the Firefly Algorithm to solve the
% [Spring Design Problem as described by Cagnina et al.,
% Informatica, vol. 32, 319-326 (2008). ]
% Simple bounds/limits
disp('Solve the simple spring design problem ...');
Lb=[0.05 0.25 2.0];
Ub=[2.0 1.3 15.0];
% Initial random guess
u0=(Lb+Ub)/2;
[u,fval,NumEval]=ffa_mincon(@cost,@constraint,u0,Lb,Ub,para);
% Display results
bestsolution=u
bestojb=fval
total_number_of_function_evaluations=NumEval
%%% Put your own cost/objective function here --------%%%
%% Cost or Objective function
function z=cost(x)
z=(2+x(3))*x(1)^2*x(2);
% Constrained optimization using penalty methods
% by changing f to F=f+ \sum lam_j*g^2_j*H_j(g_j)
% where H(g)=0 if g<=0 (true), =1 if g is false
%%% Put your own constraints here --------------------%%%
function [g,geq]=constraint(x)
% All nonlinear inequality constraints should be here
% If no inequality constraint at all, simple use g=[];
g(1)=1-x(2)^3*x(3)/(71785*x(1)^4);
% There was a typo in Cagnina et al.'s paper,
% the factor should 71785 insteady of 7178 !
tmpf=(4*x(2)^2-x(1)*x(2))/(12566*(x(2)*x(1)^3-x(1)^4));
g(2)=tmpf+1/(5108*x(1)^2)-1;
g(3)=1-140.45*x(1)/(x(2)^2*x(3));
g(4)=x(1)+x(2)-1.5;
% all nonlinear equality constraints should be here
% If no equality constraint at all, put geq=[] as follows
geq=[];
%%% End of the part to be modified -------------------%%%
%%% --------------------------------------------------%%%
%%% Do not modify the following codes unless you want %%%
%%% to improve its performance etc %%%
% -------------------------------------------------------
% ===Start of the Firefly Algorithm Implementation ======
% Inputs: fhandle => @cost (your own cost function,
% can be an external file )
% nonhandle => @constraint, all nonlinear constraints
% can be an external file or a function
% Lb = lower bounds/limits
% Ub = upper bounds/limits
% para == optional (to control the Firefly algorithm)
% Outputs: nbest = the best solution found so far
% fbest = the best objective value
% NumEval = number of evaluations: n*MaxGeneration
% Optional:
% The alpha can be reduced (as to reduce the randomness)
% ---------------------------------------------------------
% Start FA
function [nbest,fbest,NumEval]...
=ffa_mincon(fhandle,nonhandle,u0, Lb, Ub, para)
% Check input parameters (otherwise set as default values)
if nargin<6, para=[20 50 0.25 0.20 1]; end
if nargin<5, Ub=[]; end
if nargin<4, Lb=[]; end
if nargin<3,
disp('Usuage: FA_mincon(@cost, @constraint,u0,Lb,Ub,para)');
end
% n=number of fireflies
% MaxGeneration=number of pseudo time steps
% ------------------------------------------------
% alpha=0.25; % Randomness 0--1 (highly random)
% betamn=0.20; % minimum value of beta
% gamma=1; % Absorption coefficient
% ------------------------------------------------
n=para(1); MaxGeneration=para(2);
alpha=para(3); betamin=para(4); gamma=para(5);
% Total number of function evaluations
NumEval=n*MaxGeneration;
% Check if the upper bound & lower bound are the same size
if length(Lb) ~=length(Ub),
disp('Simple bounds/limits are improper!');
return
end
% Calcualte dimension
d=length(u0);
% Initial values of an array
zn=ones(n,1)*10^100;
% ------------------------------------------------
% generating the initial locations of n fireflies
[ns,Lightn]=init_ffa(n,d,Lb,Ub,u0);
% Iterations or pseudo time marching
for k=1:MaxGeneration, %%%%% start iterations
% This line of reducing alpha is optional
alpha=alpha_new(alpha,MaxGeneration);
% Evaluate new solutions (for all n fireflies)
for i=1:n,
zn(i)=Fun(fhandle,nonhandle,ns(i,:));
Lightn(i)=zn(i);
end
% Ranking fireflies by their light intensity/objectives
[Lightn,Index]=sort(zn);
ns_tmp=ns;
for i=1:n,
ns(i,:)=ns_tmp(Index(i),:);
end
%% Find the current best
nso=ns; Lighto=Lightn;
nbest=ns(1,:); Lightbest=Lightn(1);
% For output only
fbest=Lightbest;
% Move all fireflies to the better locations
[ns]=ffa_move(n,d,ns,Lightn,nso,Lighto,nbest,...
Lightbest,alpha,betamin,gamma,Lb,Ub);
end %%%%% end of iterations
% -------------------------------------------------------
% ----- All the subfunctions are listed here ------------
% The initial locations of n fireflies
function [ns,Lightn]=init_ffa(n,d,Lb,Ub,u0)
% if there are bounds/limits,
if length(Lb)>0,
for i=1:n,
ns(i,:)=Lb+(Ub-Lb).*rand(1,d);
end
else
% generate solutions around the random guess
for i=1:n,
ns(i,:)=u0+randn(1,d);
end
end
% initial value before function evaluations
Lightn=ones(n,1)*10^100;
% Move all fireflies toward brighter ones
function [ns]=ffa_move(n,d,ns,Lightn,nso,Lighto,...
nbest,Lightbest,alpha,betamin,gamma,Lb,Ub)
% Scaling of the system
scale=abs(Ub-Lb);
% Updating fireflies
for i=1:n,
% The attractiveness parameter beta=exp(-gamma*r)
for j=1:n,
r=sqrt(sum((ns(i,:)-ns(j,:)).^2));
% Update moves
if Lightn(i)>Lighto(j), % Brighter and more attractive
beta0=1; beta=(beta0-betamin)*exp(-gamma*r.^2)+betamin;
tmpf=alpha.*(rand(1,d)-0.5).*scale;
ns(i,:)=ns(i,:).*(1-beta)+nso(j,:).*beta+tmpf;
end
end % end for j
end % end for i
% Check if the updated solutions/locations are within limits
[ns]=findlimits(n,ns,Lb,Ub);
% This function is optional, as it is not in the original FA
% The idea to reduce randomness is to increase the convergence,
% however, if you reduce randomness too quickly, then premature
% convergence can occur. So use with care.
function alpha=alpha_new(alpha,NGen)
% alpha_n=alpha_0(1-delta)^NGen=0.005
% alpha_0=0.9
delta=1-(0.005/0.9)^(1/NGen);
alpha=(1-delta)*alpha;
% Make sure the fireflies are within the bounds/limits
function [ns]=findlimits(n,ns,Lb,Ub)
for i=1:n,
% Apply the lower bound
ns_tmp=ns(i,:);
I=ns_tmp<Lb;
ns_tmp(I)=Lb(I);
% Apply the upper bounds
J=ns_tmp>Ub;
ns_tmp(J)=Ub(J);
% Update this new move
ns(i,:)=ns_tmp;
end
% -----------------------------------------
% d-dimensional objective function
function z=Fun(fhandle,nonhandle,u)
% Objective
z=fhandle(u);
% Apply nonlinear constraints by the penalty method
% Z=f+sum_k=1^N lam_k g_k^2 *H(g_k) where lam_k >> 1
z=z+getnonlinear(nonhandle,u);
function Z=getnonlinear(nonhandle,u)
Z=0;
% Penalty constant >> 1
lam=10^15; lameq=10^15;
% Get nonlinear constraints
[g,geq]=nonhandle(u);
% Apply inequality constraints as a penalty function
for k=1:length(g),
Z=Z+ lam*g(k)^2*getH(g(k));
end
% Apply equality constraints (when geq=[], length->0)
for k=1:length(geq),
Z=Z+lameq*geq(k)^2*geteqH(geq(k));
end
% Test if inequalities hold
% H(g) which is something like an index function
function H=getH(g)
if g<=0,
H=0;
else
H=1;
end
% Test if equalities hold
function H=geteqH(g)
if g==0,
H=0;
else
H=1;
end
%% ==== End of Firefly Algorithm implementation ======
⛄ 运行结果
⛄ 参考文献
[1]唐宏, 冯平, 陈镜伯,等. 萤火虫算法优化SVR参数在短期电力负荷预测中的应用[J]. 西华大学学报:自然科学版, 2017, 36(1):4.