%========================================================%%Files of the Matlab programs included in the book:%%Xin-SheYang,Nature-InspiredMetaheuristicAlgorithms,%%SecondEdition,LuniverPress,(2010). www.luniver.com %%========================================================%%=========================================================%%FireflyAlgorithm by XSYang(CambridgeUniversity)%%Usage:firefly_simple([number_of_fireflies,MaxGeneration])% eg:firefly_simple([12,50]);%%========================================================%%This is a demo for2D functions;for higher dimenions,%% you should use fa_ndim.m or fa_mincon.m %%Parameters choice:%Gamma should be linked withscales.Otherwise, the FA %% the efficiency will be significantly reduced because %% the beta term may be too small.%%Similarly, alpha should also be linked withscales,%% the steps should not too large or too small, often %% steps are about 1/10to1/100 of the domain size.%%In addition, alpha should be reduced gradually %% using alpha=alpha_0 delta^t during eteration t.%%Typically, delta=0.9to0.99 will be a good choice.%%========================================================%function [best]=firefly_simple(instr)% n=number of fireflies
%MaxGeneration=number of pseudo time steps
if nargin<1%%不知道這個nargin是干嘛的 也不知道是這個if是干嘛的,應該有無都無所謂 確定的是instr=[1250]中12是螢火蟲個數,50是迭代次數instr=[1250];
end
n=instr(1);MaxGeneration=instr(2);%Show info
help firefly_simple.m %%沒啥用
rand('state',0);%Reset the random generator 產生一個隨機數,"state"的意思有下標地創建隨機數,如果換一個下標比如從0換成1則重新隨機,如果不換下標則隨機數無論怎么rand都還是這個不會變化
%------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);%Convertingtoan inline function
f=vectorize(inline(funstr));%%inline把串轉化為函數 vectorize將函數的標量運算轉換為函數運算:如矩陣相乘*轉換為.*點乘 ^2轉換為.^2 前者是矩陣乘矩陣 后者是對矩陣中每個元素進行平方
% range=[xmin xmax ymin ymax];
range=[-55-55];%------------------------------------------------
alpha=0.2;%Randomness0--1(highly random)
gamma=1.0;%Absorption coefficient
delta=0.97;%Randomness reduction (similar to% an annealing schedule)%------------------------------------------------%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));%%生成一個三維圖像 并對x、y軸-5~5進行分格 間隔為0.1 再加上零點所以一共101個點
z=f(x,y);%z為計算此四峰函數在不同分隔點上對應的函數值
%Display the shape of the objective function 作出此四峰函數的圖像
figure(1);surfc(x,y,z);%------------------------------------------------% generating the initial locations of n fireflies 對12個螢火蟲的初始位置進行初始化
[xn,yn,Lightn]=init_ffa(n,range);%%使用init_ffa函數進行初始化并返回值,xn為螢火蟲的x軸初始坐標、yn為螢火蟲的y軸初始坐標,lightn為
%Display the paths of fireflies in a figure with% contours of the function tobe optimizedfigure(2);%Iterations or pseudo time marching
for i=1:MaxGeneration,%%%%% start iterations 開始迭代
%Show the contours of the functioncontour(x,y,z,15); hold on;%創建等高線圖 15條等高線,函數x軸為x矩陣,y軸為y矩陣,函數值大小為z矩陣,顏色由藍變淺,越淺說明函數值越大
%Evaluatenew solutions 計算xn,yn坐標下的函數值zn
zn=f(xn,yn);%Ranking the fireflies by their light intensity 比較不同螢火蟲的亮度
[Lightn,Index]=sort(zn);%lightn中存儲的是zn進行升序排序之后的矩陣,Index存儲的是進行升序排序之后lightn中每個元素對應于排序前zn中每個元素的位置如A={19,23,12} 排序后lightn={12,19,23},Index={3,1,2}
xn=xn(Index); yn=yn(Index);%排序之后xn=xn(Index); yn=yn(Index);意味著xn中存儲的是對應函數值升序排序的x坐標,比如第一個xn(1)存的就是函數值zn最小的那個螢火蟲的x坐標,y同理
xo=xn; yo=yn;Lighto=Lightn;%使用新的xo、yo、lightno存儲,作用是作為參數傳入ffa_move來進行螢火蟲每次迭代的吸引與隨機移動工作,移動之后的新坐標再傳回xn、yn
%Trace the paths of all roaming fireflies
plot(xn,yn,'.','markersize',10,'markerfacecolor','g');%畫螢火蟲 表示為一個小綠點
%Move all fireflies tothe better locations
[xn,yn]=ffa_move(xn,yn,Lightn,xo,yo,Lighto,alpha,gamma,range);%通過ffa_move函數進行吸引與隨機移動
drawnow;%Use"hold on"toshow the paths of fireflieshold off;%Reduce randomness as iterations proceed 隨著迭代次數增加減少隨機性alpha
alpha=newalpha(alpha,delta);end %%%%% end of iterations
%迭代完成之后,獲取最終的答案
%best中存的就是螢火蟲(x,y)處對應的函數值第一列存的是x,第二列存的y,第三列存的函數值
best(:,1)=xo';best(:,2)=yo';best(:,3)=Lighto';end %%end for firfly_simple%-----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));
end%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);ifLightn(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);
endend % end for j
end % end for i
[xn,yn]=findrange(xn,yn,range);
end%Reduce the randomness during iterations
function alpha=newalpha(alpha,delta)
alpha=alpha*delta;
end %Make sure the fireflies are within the range
function [xn,yn]=findrange(xn,yn,range)for i=1:length(yn),ifxn(i)<=range(1),xn(i)=range(1); endifxn(i)>=range(2),xn(i)=range(2); endifyn(i)<=range(3),yn(i)=range(3); endifyn(i)>=range(4),yn(i)=range(4); end
end
end
%============== end =====================================
%========================================================%%Files of the Matlab programs included in the book:%%Xin-SheYang,Nature-InspiredMetaheuristicAlgorithms,%%SecondEdition,LuniverPress,(2010). www.luniver.com %%========================================================%%--------------------------------------------------------%%FireflyAlgorithmfor constrained optimization using %%for the design of a spring (benchmark)%% by Xin-SheYang(CambridgeUniversity)Copyright@2009%%--------------------------------------------------------%function fa_mincon
% parameters [n N_iteration alpha betamin gamma]
para=[405000.50.21];
format long;help fa_mincon.m
%This demo usestheFireflyAlgorithmtosolve the
%[SpringDesignProblem as described by Cagnina et al.,%Informatica, vol.32,319-326(2008).]%Simple bounds/limits
disp('Solve the simple spring design problem ...');Lb=[0.050.252.0];Ub=[2.01.315.0];%Initial random guess 隨機猜一個解(x1,x2,x3)
u0=Lb+(Ub-Lb).*rand(size(Lb));[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 functionfunction z=cost(x)
z=(2+x(3))*x(1)^2*x(2);%Constrained optimization using penalty methods
% by changing f toF=f+ \sum lam_j*g^2_j*H_j(g_j)% where H(g)=0if g<=0(true),=1if 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=[];
geq=[];%%%End of the part tobe modified -------------------%%%%%%--------------------------------------------------%%%%%%Do not modify the following codes unless you want %%%%%%toimprove its performance etc %%%%-------------------------------------------------------%===Start of the FireflyAlgorithmImplementation======%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 (tocontrol 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 toreduce the randomness)%---------------------------------------------------------%Start FA
function [nbest,fbest,NumEval]...=ffa_mincon(fhandle,nonhandle,u0,Lb,Ub, para)%Check input parameters (otherwise set as default values)%nargin為關鍵字:代表本函數輸入的參數個數
if nargin<6, para=[20500.250.201]; 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;%Randomness0--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;%Checkif the upper bound & lower bound are the same size
iflength(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);%ns為初始化后的各個螢火蟲坐標%Iterations or pseudo time marching
for k=1:MaxGeneration,%%%%% start iterations%This line of reducing alpha is optionalalpha=alpha_new(alpha,MaxGeneration);%Evaluatenew 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);% lightn是排序后的函數值
ns_tmp=ns;for i=1:n,ns(i,:)=ns_tmp(Index(i),:);%對ns也按照lightn排序后的順序重新對應索引
end%%Find the current best
nso=ns;Lighto=Lightn;
nbest=ns(1,:);Lightbest=Lightn(1);%nbest為最佳的螢火蟲的坐標 Lightbest為最佳的螢火蟲的適應度函數值%For output only
fbest=Lightbest;%Move all fireflies tothe better locations
[ns]=ffa_move(n,d,ns,Lightn,nso,Lighto,nbest,...Lightbest,alpha,betamin,gamma,Lb,Ub);7end %%%%% 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)%n螢火蟲個數,d維度,u0隨機猜的一個解,ns初始解空間,lightn是排序后的函數值%if there are bounds/limits,有上下限就在上下限之間進行生成隨機解
iflength(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
ifLightn(i)>Lighto(j),%Brighter and more attractivebeta0=1; beta=(beta0-betamin)*exp(-gamma*r.^2)+betamin;%這里beta為什么是需要計算的呢,而且與firefly_simple不同?tmpf=alpha.*(rand(1,d)-0.5).*scale;ns(i,:)=ns(i,:).*(1-beta)+nso(j,:).*beta+tmpf;%移動endend % end for jend % end for i%Checkif 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 toreduce randomness is toincrease the convergence,% however,if you reduce randomness too quickly, then premature
% convergence can occur. So use withcare.
function alpha=alpha_new(alpha,NGen)% alpha_n=alpha_0(1-delta)^NGen=10^(-4);% alpha_0=0.9
delta=1-(10^(-4)/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 boundns_tmp=ns(i,:);I=ns_tmp<Lb;ns_tmp(I)=Lb(I);%Apply the upper boundsJ=ns_tmp>Ub;ns_tmp(J)=Ub(J);%Updatethisnew movens(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)%%這里有約束的情況其實就是把約束帶上,直接求整體的函數值,因為約束前面的系數極大10^15所以如果要整體最小的話,那么必然要讓約束趨近于0才可以,那么當整體最小的時候,約束也必然被滿足,這就是懲罰法
Z=0;%Penalty constant >>1
lam=10^15; lameq=10^15;%Get nonlinear constraints
[g,geq]=nonhandle(u)%g是非等式約束求出的約束值 geq是什么等式約束求出的約束值%Apply inequality constraints as a penalty function
%%加上不等式約束條件
for k=1:length(g),Z=Z+ lam*g(k)^2*getH(g(k))%lam應該是對應的懲罰法中的ui(u),lameq對應vi(v)
end
%Apply equality constraints (when geq=[], length->0)%加上等式約束條件
for k=1:length(geq),Z=Z+lameq*geq(k)^2*geteqH(geq(k));
end%Testif inequalities hold
%H(g) which is something like an index function
function H=getH(g)if g<=0,H=0;elseH=1;
end%Testif equalities hold
function H=geteqH(g)if g==0,H=0;elseH=1;
end
%%====End of FireflyAlgorithm implementation ======