AI 助理
备案 控制台
开发者社区 人工智能 文章 正文

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

本文涉及的产品
传统型负载均衡 CLB,每月750个小时 15LCU
推荐场景:
搭建高可用的微信/支付宝小程序服务
网络型负载均衡 NLB,每月750个小时 15LCU
EMR Serverless StarRocks,5000CU*H 48000GB*H
简介: 萤火虫优化算法(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电子书和数学建模资料
❤️部分理论引用网络文献,若有侵权联系博主删除


相关实践学习
SLB负载均衡实践
本场景通过使用阿里云负载均衡 SLB 以及对负载均衡 SLB 后端服务器 ECS 的权重进行修改,快速解决服务器响应速度慢的问题
负载均衡入门与产品使用指南
负载均衡(Server Load Balancer)是对多台云服务器进行流量分发的负载均衡服务,可以通过流量分发扩展应用系统对外的服务能力,通过消除单点故障提升应用系统的可用性。 本课程主要介绍负载均衡的相关技术以及阿里云负载均衡产品的使用方法。
Matlab科研工作室
目录
相关文章
软件算法开发
|
2月前
|
算法
基于GA-PSO遗传粒子群混合优化算法的CVRP问题求解matlab仿真
本文介绍了一种基于GA-PSO混合优化算法求解带容量限制的车辆路径问题(CVRP)的方法。在MATLAB2022a环境下运行,通过遗传算法的全局搜索与粒子群算法的局部优化能力互补,高效寻找最优解。程序采用自然数编码策略,通过选择、交叉、变异操作及粒子速度和位置更新,不断迭代直至满足终止条件,旨在最小化总行驶距离的同时满足客户需求和车辆载重限制。
软件算法开发
151 1
软件算法开发
|
4月前
|
算法
基于GA-PSO遗传粒子群混合优化算法的VRPTW问题求解matlab仿真
摘要: 本文介绍了考虑时间窗的车辆路径问题(VRPTW),在MATLAB2022a中进行测试。VRPTW涉及车辆从配送中心出发,服务客户并返回,需在指定时间窗内完成且满足车辆容量限制,目标是最小化总行驶成本。文章探讨了遗传算法(GA)和粒子群优化(PSO)的基本原理及其在VRPTW中的应用,包括编码、适应度函数、选择、交叉、变异等步骤。同时,提出了动态惯性权重、精英策略、邻域搜索、多种群和启发式信息等优化策略,以应对时间窗限制并提升算法性能。
软件算法开发
116 11
软件算法开发
|
4月前
|
算法 调度 决策智能
基于GA-PSO遗传粒子群混合优化算法的DVRP问题求解matlab仿真
该文介绍了车辆路径问题(VRP)的优化求解,特别是动态车辆路径问题(DVRP)。在MATLAB2022a中运用GA-PSO混合优化算法进行测试,展示了运行结果图像。核心程序包含粒子更新、交叉、距离计算等步骤。DVRP在物流配送、运输调度中有广泛应用,目标是最小化行驶距离并满足车辆容量限制。遗传算法通过选择、交叉和变异操作寻找解,而粒子群优化模拟鸟群行为更新速度和位置。GA-PSO混合算法结合两者优点,提高搜索效率。在DVRP中,算法需考虑问题特性和约束,以找到高质量解。
软件算法开发
153 1
软件算法开发
|
4月前
|
算法 安全
基于龙格库塔算法的SIR病毒扩散预测matlab仿真
该程序使用龙格库塔算法实现SIR模型预测病毒扩散,输出易感、感染和康复人群曲线。在MATLAB2022a中运行显示预测结果。核心代码设置时间区间、参数,并定义微分方程组,通过Runge-Kutta方法求解。SIR模型描述三类人群动态变化,常微分方程组刻画相互转化。模型用于预测疫情趋势,支持公共卫生决策,但也存在局限性,如忽略空间结构和人口异质性。
软件算法开发
47 0
荔枝科研社
|
算法 定位技术
【单目标优化算法】烟花优化算法(Matlab代码实现)
【单目标优化算法】烟花优化算法(Matlab代码实现)
荔枝科研社
111 0
【单目标优化算法】烟花优化算法(Matlab代码实现)
Matlab科研工作室
|
传感器 数据采集 人工智能
智能优化算法改进算法 -附matlab代码
智能优化算法改进算法 -附matlab代码
Matlab科研工作室
622 0
荔枝科研社
|
算法 数据挖掘 机器人
一种新的群体智能优化算法:麻雀搜索算法(SSA)(Matlab代码实现)
一种新的群体智能优化算法:麻雀搜索算法(SSA)(Matlab代码实现)
荔枝科研社
249 0
荔枝科研社
|
算法 机器人
基于改进PSO-ABC算法的机器人路径规划(Matlab代码实现)
基于改进PSO-ABC算法的机器人路径规划(Matlab代码实现)
荔枝科研社
91 0
荔枝科研社
|
机器学习/深度学习 算法 Serverless
基于萤火虫算法优化的BP神经网络预测模型(Matlab代码实现)
基于萤火虫算法优化的BP神经网络预测模型(Matlab代码实现)
荔枝科研社
130 0
我爱matlab
|
算法 Serverless
m基于优化算法的多车辆的路径规划matlab仿真,对比GA,PSO以及烟花算法
m基于优化算法的多车辆的路径规划matlab仿真,对比GA,PSO以及烟花算法
我爱matlab
152 0
m基于优化算法的多车辆的路径规划matlab仿真,对比GA,PSO以及烟花算法

热门文章

最新文章

  • 1
    SpringBoot前后端分离项目,打包、部署到服务器详细图文流程
  • 2
    表格存储新手指南:如何实现分页查询
  • 3
    Kubernetes全方位日志采集与管理的最佳实践 资料下载
  • 4
    高效运维之Docker持续部署图文详解
  • 5
    麒麟开源堡垒机安装部署测试及优缺点总结
  • 6
    5分钟构建API接口服务 | python小知识
  • 7
    阿里建“猫茂”线下购物中心,将实现新零售技术的真正落地
  • 8
    [20180202]脏块写盘问题.txt
  • 9
    通过扩展改善ASP.NET MVC的验证机制[实现篇]
  • 10
    下载后自动打开(更改IE下载文件后的默认处理方法)
  • 1
    14 款超赞的代码片段生成工具😍(程序员必备)
    22
  • 2
    Go语言项目高效对接SQL数据库:实践技巧与方法
    16
  • 3
    用来用去还是用回了ueditor-Vue富文本编辑器二次扩展
    19
  • 4
    uniapp uview扩展u-picker支持日历期间 年期间 月期间 时分期间组件
    20
  • 5
    electron-updater实现electron全量版本更新
    19
  • 6
    electron多标签页模式更像客户端
    15
  • 7
    UniApp低代码-颜色选择器diy-color-picker-代码生成器
    12
  • 8
    低代码开发工具-学生管理系统-老师管理增删改查实现
    12
  • 9
    Vue3商品SKU多规格编辑组件
    13
  • 10
    JavaScript中的面向对象编程(OOP) - 终极指南
    12
  • 相关课程

    更多
  • 神经网络概览及算法详解
  • 智能运维赛(复赛):利用数据和算法,快速定位系统异常并进行根因分析
  • 智能创作赛(复赛):相册应用中的视频故事生成算法介绍
  • 智能创作赛(初赛):相册应用中的故事生成算法介绍
  • 相册服务中的故事生成算法介绍
  • Go语言核心编程 - 数据结构和算法
  • 相关电子书

    更多
  • 阿里云千亿特征深度学习算法XNN实践
  • 阿里千亿特征深度学习算法XNN实践
  • 基于深度学习的广告CTR预估算法
  • 相关实验场景

    更多
  • 使用Swing算法实现商品推荐
  • RSA密码算法设计与实现
  • 欧拉图的构造性证明与算法实现
  • 推荐系统入门之使用ALS算法实现打分预测
  • 下一篇
    阿里云无影AI云电脑亮相 体验大幅升级

    深圳坪山网站建设公司seo网站优化是百度快照吗新网站应该如何做搜索引擎优化五华区网站seo优化怎样浉河网站优化网站优化方案书丰城市百度网站优化亨甲网站优化怎么做工艺品网站优化网站优化价格便宜营口专业网站优化排名东莞专业网站优化哪家好开平网站优化哪家好苏州网站关键字优化济南网站空间优化推广湛江网站优化对策网站关键词优化工资网站建设网站优化推广开发制作铁岭网站推广优化公司电商怎么优化网站济南卫浴行业网站优化推广渠道沈阳网站权重优化网站后期优化建议url优化网站多长好平凉网站优化推广公司排名商河网站优化排名海口网站优化如何常德网站优化教程长沙外贸网站优化外包网站快速优化选择火27星河源专业网站优化怎么样香港通过《维护国家安全条例》两大学生合买彩票中奖一人不认账让美丽中国“从细节出发”19岁小伙救下5人后溺亡 多方发声卫健委通报少年有偿捐血浆16次猝死汪小菲曝离婚始末何赛飞追着代拍打雅江山火三名扑火人员牺牲系谣言男子被猫抓伤后确诊“猫抓病”周杰伦一审败诉网易中国拥有亿元资产的家庭达13.3万户315晚会后胖东来又人满为患了高校汽车撞人致3死16伤 司机系学生张家界的山上“长”满了韩国人?张立群任西安交通大学校长手机成瘾是影响睡眠质量重要因素网友洛杉矶偶遇贾玲“重生之我在北大当嫡校长”单亲妈妈陷入热恋 14岁儿子报警倪萍分享减重40斤方法杨倩无缘巴黎奥运考生莫言也上北大硕士复试名单了许家印被限制高消费奥巴马现身唐宁街 黑色着装引猜测专访95后高颜值猪保姆男孩8年未见母亲被告知被遗忘七年后宇文玥被薅头发捞上岸郑州一火锅店爆改成麻辣烫店西双版纳热带植物园回应蜉蝣大爆发沉迷短剧的人就像掉进了杀猪盘当地回应沈阳致3死车祸车主疑毒驾开除党籍5年后 原水城县长再被查凯特王妃现身!外出购物视频曝光初中生遭15人围殴自卫刺伤3人判无罪事业单位女子向同事水杯投不明物质男子被流浪猫绊倒 投喂者赔24万外国人感慨凌晨的中国很安全路边卖淀粉肠阿姨主动出示声明书胖东来员工每周单休无小长假王树国卸任西安交大校长 师生送别小米汽车超级工厂正式揭幕黑马情侣提车了妈妈回应孩子在校撞护栏坠楼校方回应护栏损坏小学生课间坠楼房客欠租失踪 房东直发愁专家建议不必谈骨泥色变老人退休金被冒领16年 金额超20万西藏招商引资投资者子女可当地高考特朗普无法缴纳4.54亿美元罚金浙江一高校内汽车冲撞行人 多人受伤

    深圳坪山网站建设公司 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化