萤火虫优化算法(FA)附matlab代码

简介: 萤火虫优化算法(FA)附matlab代码


✅作者简介:热爱科研的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.

❤️ 关注我领取海量matlab电子书和数学建模资料
❤️部分理论引用网络文献,若有侵权联系博主删除


相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
相关文章
|
图形学 容器
QT chart图表(温度曲线实战)
QT chart图表(温度曲线实战)
888 0
|
2月前
|
传感器 机器学习/深度学习 算法
【无人机协同】动态环境下多无人机系统的协同路径规划与防撞研究(Matlab代码实现)
【无人机协同】动态环境下多无人机系统的协同路径规划与防撞研究(Matlab代码实现)
230 0
|
11月前
|
存储 机器学习/深度学习 人工智能
昇腾AI行业案例(六):基于 PraNet 的医疗影像分割
欢迎学习《基于 PraNet 的医疗影像分割》实验。在本实验中,你将深入了解如何运用计算机视觉(CV)领域的 AI 模型,搭建一个高效精准的医疗影像分割系统,专注于息肉分割任务,并利用开源数据集对模型效果加以验证。
318 1
|
4月前
|
机器学习/深度学习 分布式计算 算法
【升级版本】基于多目标粒子群算法的微电网优化调度【风光、储能、柴油、燃气、电网交互】(Matlab代码实现)
【升级版本】基于多目标粒子群算法的微电网优化调度【风光、储能、柴油、燃气、电网交互】(Matlab代码实现)
133 0
|
缓存 监控 Java
|
知识图谱
滚动轴承常见故障及其基本模型
滚动轴承常见故障及其基本模型
649 0
|
人工智能 自然语言处理 算法
|
Ubuntu 网络协议 数据安全/隐私保护
【Ubuntu】sudo apt-get update 无法解析域名(亲测有效)
在Ubuntu 18.04系统中,用户在执行sudo apt-get update时遇到“无法解析域名‘ip’”的错误。经分析,问题源于之前设置的网络代理配置未完全清除。解决方案是找到并重命名/etc/apt/apt.conf.d下的proxy.conf文件,使其不再生效。操作后,sudo apt-get update命令恢复正常,问题得到完美解决。
4490 4
【Ubuntu】sudo apt-get update 无法解析域名(亲测有效)
|
编解码 测试技术 Python
【Python】已解决:UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-1: ordinal not i
【Python】已解决:UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-1: ordinal not i
3094 1
|
弹性计算 安全 关系型数据库
阿里云上云解决方案参考,多种技术与行业解决方案助力企业上云
对于初次上云的用户来说,参考一份适合自己行业的解决方案可帮助自己快速上手,并根据方案的内容选择适合自己的云产品进行方案部署。阿里云发布各种解决方案是基于众多客户上云的成功案例萃取而成的最优化企业上云指导,涵盖前端Web和移动应用程序开发、网站搭建、网络组网、数据库、迁云等众多上云项目。本文为大家汇总了一些上云解决方案的详情入口,方便大家快速查询与自己场景相符的解决方案。
2176 1
阿里云上云解决方案参考,多种技术与行业解决方案助力企业上云