版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
人工蚂蚁算法%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%function[x,y,minvalue]=AA(func)%Example[x,y,minvalue]=AA('Foxhole')clc;tic;subplot(2,2,1);%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%plot1draw(func);title([func,'Function']);%初始化各参数Ant=100;%蚂蚁规模ECHO=200;%迭代次数step=0.01*rand(1);%局部搜索时的步长temp=[0,0];%各子区间长度start1=-100;end1=100;start2=-100;end2=100;Len1=(end1-start1)/Ant;Len2=(end2-start2)/Ant;%P=0.2;%初始化蚂蚁位置fori=1:AntX(i,1)=(start1+(end1-start1)*rand(1));X(i,2)=(start2+(end2-start2)*rand(1));%func=AA_Foxhole_Func(X(i,1),X(i,2));val=feval(func,[X(i,1),X(i,2)]);T0(i)=exp(-val);%初始信息素,随函数值大,信息素浓度小,反之亦然%%%%%*********************************************************************end;%至此初始化完成forEcho=1:ECHO%开始寻优%P0函数定义,P0为全局转移选择因子a1=0.9;b1=(1/ECHO)*2*log(1/2);f1=a1*exp(b1*Echo);a2=0.225;b2=(1/ECHO)*2*log(2);f2=a2*exp(b2*Echo);ifEcho<=(ECHO/2)P0=f1;elseP0=f2;end;%P函数定义,P为信息素蒸发系数a3=0.1;b3=(1/ECHO).*log(9);P=a3*exp(b3*Echo);lamda=0.10+(0.14-0.1)*rand(1);%全局转移步长参数Wmax=1.0+(1.4-1.0)*rand(1);%步长更新参数上限Wmin=0.2+(0.8-0.2)*rand(1);%步长更新参数下限%寻找初始最优值T_Best=T0(1);forj=1:AntifT0(j)>=T_BestT_Best=T0(j);BestIndex=j;end;end;W=Wmax-(Wmax-Wmin)*(Echo/ECHO);%局部搜索步长更新参数forj_g=1:Ant%全局转移概率求取,当该蚂蚁随在位置不是bestindex时ifj_g~=BestIndexr=T0(BestIndex)-T0(j_g);Prob(j_g)=exp(r)/exp(T0(BestIndex));else%当j_g=BestIndex的时候进行局部搜索ifrand(1)<0.5temp(1,1)=X(BestIndex,1)+W*step;temp(1,2)=X(BestIndex,2)+W*step;elsetemp(1,1)=X(BestIndex,1)-W*step;temp(1,2)=X(BestIndex,2)-W*step;end;Prob(j_g)=0;%bestindex的蚂蚁不进行全局转移end;X1_T=temp(1,1);X2_T=temp(1,2);X1_B=X(BestIndex,1);X2_B=X(BestIndex,2);%func1=AA_Foxhole_Func(X1_T,X2_T);%%%%%%%%%%%***************************************************%F1_T=func1;F1_T=feval(func,[X(i,1),X(i,2)]);F1_B=feval(func,[X1_B,X2_B]);%F1_T=(X1_T-1).^2+(X2_T-2.2).^2+1;%func2=AA_Foxhole_Func(X1_B,X2_B);%%%%%%%%%%%%%***************************************************%F1_B=func2;%F1_B=(X1_B-1).^2+(X2_B-2.2).^2+1;ifexp(-F1_T)>exp(-F1_B)X(BestIndex,1)=temp(1,1);X(BestIndex,2)=temp(1,2);end;end;forj_g_tr=1:AntifProb(j_g_tr)<P0X(j_g_tr,1)=X(j_g_tr,1)+lamda*(X(BestIndex,1)-X(j_g_tr,1));%Xi=Xi+lamda*(Xbest-Xi)X(j_g_tr,2)=X(j_g_tr,2)+lamda*(X(BestIndex,2)-X(j_g_tr,2));%Xi=Xi+lamda*(Xbest-Xi)X(j_g_tr,1)=bound(X(j_g_tr,1),start1,end1);X(j_g_tr,2)=bound(X(j_g_tr,2),start2,end2);elseX(j_g_tr,1)=X(j_g_tr,1)+((-1)+2*rand(1))*Len1;%Xi=Xi+rand(-1,1)*Len1X(j_g_tr,2)=X(j_g_tr,2)+((-1)+2*rand(1))*Len2;%Xi=Xi+rand(-1,1)*Len2X(j_g_tr,1)=bound(X(j_g_tr,1),start1,end1);X(j_g_tr,2)=bound(X(j_g_tr,2),start2,end2);end;end;%信息素更新subplot(2,2,2);%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Plot1bar([X(BestIndex,1)X(BestIndex,2)],0.25);%colormap(cool);axis([03-4040]);title({date;['Iteration',num2str(Echo)]});xlabel(['Min_x=',num2str(X(BestIndex,1)),'','Min_y=',num2str(X(BestIndex,2))]);fort_t=1:Ant%func=AA_Foxhole_Func(X(t_t,1),X(t_t,2));val1=feval(func,[X(t_t,1),X(t_t,2)]);T0(t_t)=(1-P)*T0(t_t)+(exp(-val1));%*************************************************************************end;[c_iter,i_iter]=max(T0);%求取每代全局最优解minpoint_iter=[X(i_iter,1),X(i_iter,2)];%func3=AA_Foxhole_Func(X(i_iter,1),X(i_iter,2));%%%%%%%%%***************************************************************************val2=feval(func,[X(i_iter,1),X(i_iter,2)]);minvalue_iter=val2;%minvalue_iter=(X(i_iter,1)-1).^2+(X(i_iter,2)-2.2).^2+1;min_local(Echo)=minvalue_iter;%保存每代局部最优解subplot(2,2,3);%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Plot2plot(X(BestIndex,1),X(BestIndex,2),'rs','MarkerFaceColor','r','MarkerSize',8),gridon;title(['GlobalMinValue=',num2str(minvalue_iter)]);holdon;plot(X(:,1),X(:,2),'g.'),pause(0.02);holdoff;axis([-100100-100100]);gridon;%将每代全局最优解存到min_global矩阵中ifEcho>=2ifmin_local(Echo)<min_global(Echo-1)min_global(Echo)=min_local(Echo);elsemin_global(Echo)=min_global(Echo-1);end;elsemin_global(Echo)=minvalue_iter;end;subplot(2,2,4);%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Plot3min_global=min_global';index(:,1)=1:ECHO;plot(Echo,min_global(Echo),'y*')%axis([0ECHO010]);holdon;title([func,'(X)=',num2str(minvalue_iter)],'Color','r');xlabel('iteration');ylabel('f(x)');gridon;end;%ECHO循环结束[c_max,i_max]=max(T0);minpoint=[X(i_max,1),X(i_max,2)];%func3=AA_Foxhole_Func(X(i_max,1),X(i_max,2));%%%*************************************************************************%minvalue=func3;minvalue=feval(func,[X(i_max,1),X(i_max,2)]);x=X(BestIndex,1);y=X(BestIndex,2);runtime=toc人工免疫算法function[x,y,fx,vfx,vmfit,P,vpm]=AI(func,gen,n,pm,per);%Example[x,y,fx]=AI('Foxhole')subplot(2,2,1);draw(func);title([func,'Function']);ifnargin==1,%gen=200;n=round(size(P,1)/2);pm=0.0005;per=0.0;fat=10;%gen=250;n=size(P,1);pm=0.01;per=0.0;fat=.1;P=cadeia(200,44,0,0,0);gen=40;n=size(P,1);pm=0.2;per=0.0;fat=0.1;end;whilen<=0,n=input('nhastobeatleastone.Typeanewvalueforn:');end;xmin=-100;xmax=100;ymin=-100;ymax=100;x=decode(P(:,1:22),xmin,xmax);y=decode(P(:,23:end),ymin,ymax);%fit=eval(f);%fit=AI_Foxhole_Func(x,y);%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%fit=feval(func,[x'y']);%imprime(1,vxp,vyp,vzp,x,y,fit,1,1);%Hypermutationcontrollingparameterspma=pm;itpm=gen;pmr=0.8;%Generaldefintionsvpm=[];vfx=[];vmfit=[];valfx=1;[N,L]=size(P);it=0;PRINT=1;%Generationswhileit<=gen&valfx<=100,x=decode(P(:,1:22),xmin,xmax);y=decode(P(:,23:end),ymin,ymax);T=[];cs=[];%fit=eval(f);%fit=AI_Foxhole_Func(x,y);%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%fit=feval(func,[x'y']);[a,ind]=sort(fit);valx=x(ind(end-n+1:end));valy=y(ind(end-n+1:end));fx=a(end-n+1:end);%nbestindividuals(maximization)%Reproduction[T,pcs]=reprod(n,fat,N,ind,P,T);%HypermutationM=rand(size(T,1),L)<=pm;T=T-2.*(T.*M)+M;T(pcs,:)=P(fliplr(ind(end-n+1:end)),:);%NewRe-Selection(Multi-peaksolution)x=decode(T(:,1:22),xmin,xmax);y=decode(T(:,23:end),ymin,ymax);%fit=AI_Foxhole_Func(x,y);%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%fit=feval(func,[x'y']);%fit=eval(f);pcs=[0pcs];fori=1:n,[out(i),bcs(i)]=min(fit(pcs(i)+1:pcs(i+1)));%Mimimazionproblem%%%*************************bcs(i)=bcs(i)+pcs(i);end;P(fliplr(ind(end-n+1:end)),:)=T(bcs,:);%Editing(Repertoireshift)nedit=round(per*N);it=it+1;P(ind(1:nedit),:)=cadeia(nedit,L,0,0,0);pm=pmcont(pm,pma,pmr,it,itpm);valfx=min(fx);%*************************************************************vpm=[vpmpm];vfx=[vfxvalfx];vmfit=[vmfitmean(fit)];disp(sprintf('It.:%dpm:%.4fx:%2.2fy:%2.2fAv.:%2.2ff(x,y):%2.3f',it,pm,valx(1),valy(1),vmfit(1),valfx));subplot(2,2,2);%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Plot1bar([valx(1)valy(1)],0.25);axis([03-4040]);title(['Iteration',num2str(it)]);pause(0.1);subplot(2,2,3);%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Plot2plot(valx(1),valy(1),'rs','MarkerFaceColor','r','MarkerSize',8)holdon;%plot(x(:,1),x(:,2),'k.');set(gca,'Color','g')holdoff;gridon;axis([-100100-100100]);title(['GlobalMin=',num2str(valfx)]);xlabel(['Min_x=',num2str(valx(1)),'Min_y=',num2str(valy(1))]);subplot(2,2,4);%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Plot3plot(it,valfx,'k.')axis([0gen010]);holdon;title([func,'(X)=',num2str(valfx)]);xlabel('iteration');ylabel('f(x)');gridon;end;%endwhile%imprime(PRINT,vxp,vyp,vzp,x,y,fit,it,1);x=valx(1);y=valy(1);fx=min(fx);%***********************************************************************%x=P(ind(end),1:22);y=P(ind(end),23:44);fx=max(fx);%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Plot4%---------------------%%INTERNALSUBFUNCTIONS%---------------------%%Printfunction[]=imprime(PRINT,vx,vy,vz,x,y,fx,it,mit);%x,fx->actualvalues%vxplot,vplot->original(base)functionifPRINT==1,ifrem(it,mit)==0,mesh(vx,vy,vz);holdon;axis([-100100-1001000500]);xlabel('x');ylabel('y');zlabel('f(x,y)');plot3(x,y,fx,'k*');drawnow;holdoff;end;end;%Reproductionfunction[T,pcs]=reprod(n,fat,N,ind,P,T);%n->numberofclones%fat->multiplyingfactor%ind->bestindividuals%T->temporarypopulation%pcs->finalpositionofeachcloneifn==1,cs=N;T=ones(N,1)*P(ind(1),:);else,fori=1:n,%cs(i)=round(fat*N/i);cs(i)=round(fat*N);pcs(i)=sum(cs);T=[T;ones(cs(i),1)*P(ind(end-i+1),:)];end;end;%Controlofpmfunction[pm]=pmcont(pm,pma,pmr,it,itpm);%pma->initialvalue%pmr->controlrate%itpm->iterationsforrestoringifrem(it,itpm)==0,pm=pm*pmr;ifrem(it,10*itpm)==0,pm=pma;end;end;%Decodifybitstringsfunctionx=decode(v,min,max);%x->realvalue(precision:6)%v->binarystring(length:22)v=fliplr(v);s=size(v);aux=0:1:21;aux=ones(s(1),1)*aux;x1=sum((v.*2.^aux)');x=min+(max-min)*x1./4194303;function[ab,ag]=cadeia(n1,s1,n2,s2,bip)%defaultparametervalueseetingifnargin==2,n2=n1;s2=s1;bip=1;elseifnargin==4,bip=1;end;%Antibody(Ab)chainsab=2.*rand(n1,s1)-1;%createn1rows1columnarray,itsvaluerangeisbetween-1or1ifbip==1,ab=hardlims(ab);else,ab=hardlim(ab);end;%Antigen(Ag)chainsag=2.*rand(n2,s2)-1;ifbip==1,ag=hardlims(ag);else,ag=hardlim(ag);end;%EndFunctionCADEIA%------免疫粒子群优化算法〔ArtificialImmune-ParticleSwarmOptimization〕function[x,y,Result]=PSO_AI(func)%Example[x,y,minvalue]=PSO_AI('Foxhole')clc;subplot(2,2,1);%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%plot1draw(func);title([func,'Function']);ticformatlong;%------给定初始化条件----------------------------------------------c1=1.4962;%学习因子1c2=1.4962;%学习因子2w=0.7298;%惯性权重MaxDT=200;%最大迭代次数D=2;%搜索空间维数〔未知数个数〕N=100;%初始化群体个体数目eps=10^(-20);%设置精度(在最小值时候用)DS=10;%每隔DS次循环就检查最优个体是否变优replaceP=0.6;%粒子的概率大于replaceP将被免疫替换minD=1e-015;%粒子间的最小距离Psum=0;%个体最正确的和range=100;count=0;%------初始化种群的个体------------fori=1:Nforj=1:Dx(i,j)=-range+2*range*rand;%随机初始化位置v(i,j)=randn;%随机初始化速度endend%------先计算各个粒子的适应度,并初始化Pi和Pg----------------------fori=1:N%p(i)=Foxhole(x(i,:),D);%fitness是计算各个粒子适应度的函数,见文件fitness.m%%%%%%%%*****************************************************p(i)=feval(func,x(i,:));y(i,:)=x(i,:);endpg=x(1,:);%Pg为全局最优fori=2:Niffeval(func,x(i,:))<feval(func,pg)%%%%**********************************************************************************************pg=x(i,:);endend%------进入主要循环,按照公式依次迭代,直到满足精度要求------------fort=1:MaxDTfori=1:Nv(i,:)=w*v(i,:)+c1*rand*(y(i,:)-x(i,:))+c2*rand*(pg-x(i,:));x(i,:)=x(i,:)+v(i,:);iffeval(func,x(i,:))<p(i)%%%%%%%%%%%%%%**********************************************************************************************p(i)=feval(func,x(i,:));%%%%%%%%%%%%%%%**************************************************************************************y(i,:)=x(i,:);endifp(i)<feval(func,pg)%%%%%%%%%%%%%%%%%%%%******************************************************************************************pg=y(i,:);subplot(2,2,2);%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Plot1bar(pg,0.25);axis([03-4040]);title(['Iteration',num2str(t)]);pause(0.1);subplot(2,2,3);%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Plot2plot(pg(1,1),pg(1,2),'rs','MarkerFaceColor','r','MarkerSize',8)holdon;plot(x(:,1),x(:,2),'k.');set(gca,'Color','g')holdoff;gridon;axis([-100100-100100]);title(['GlobalMin=',num2str(p(i))]);xlabel(['Min_x=',num2str(pg(1,1)),'Min_y=',num2str(pg(1,2))]);endendPbest(t)=feval(func,pg);%%%%%%%%************************************************************************************************************%ifFoxhole(pg,D)<eps%如果结果满足精度要求那么跳出循环%break;%end%-----------开始进行免疫----------------ift>DSifmod(t,DS)==0&&(Pbest(t-DS+1)-Pbest(t))<1e-020%如果连续DS代数,群体中的最优没有明显变优,那么进行免疫.%在函数测试的过程中发现,经过一定代数的更新,个体最优不完全相等,但变化非常非常小,%我认为这个时候也应用免疫了,所以我没有用“Pbest(t-DS+1)=Pbest(t)”作为判断条件,%不过“(Pbest(t-DS+1)-Pbest(t))<1e-020”是否合理也值得探讨。fori=1:N%先计算出个体最优的和Psum=Psum+p(i);endfori=1:N%免疫程序forj=1:N%计算每个个体与个体i的距离distance(j)=abs(p(j)-p(i));endnum=0;forj=1:N%计算与第i个个体距离小于minD的个数ifdistance(j)<minDnum=num+1;endendPF(i)=p(N-i+1)/Psum;%计算适应度概率PD(i)=num/N;%计算个体浓度a=rand;%随机生成计算替换概率的因子PR(i)=a*PF(i)+(1-a)*PD(i);%计算替换概率endfori=1:NifPR(i)>replacePx(i,:)=-range+2*range*rand(1,D);subplot(2,2,4);axi;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Plot4plot(x(i,1),x(i,2),'k*');gridon;axis([-100100-100100]);title(['NewMin=',num2str(feval(func,x(i,:)))]);%%%%%%%%%*******************************************************************************xlabel(['Immune',num2str(count)]);pause(0.2);count=count+1;endendendendend%------最后给出计算结果x=pg(1,1);y=pg(1,2);Result=feval(func,pg);%%%%%%%%%%%*****************************************************************************************************************toc%------算法结束-------------------------functionprobabolity(N,i)PF=p(N-i)/Psum;%适应度概率disp(PF);forjj=1:Ndistance(jj)=abs(P(jj)-P(i));endnum=0;forii=1:Nifdistance(ii)<minDnum=num+1;endendPD=num/N;%个体浓度PR=a*PF+(1-a)*PD;%替换概率%result=PR;差分进化算法function[sol]=DE(func)%%Example[sol]=DE('Foxhole')ticpopsize=100;lb=[-100-100];ub=[100100];[sol]=diffevolve(func,popsize,lb,ub);tocendfunction[sol,fval,evals]=diffevolve(varargin)%DIFFEVOLVEDifferentialEvolutionOptimization%%Usage:%sol=DIFFEVOLVE(PROBLEM)%sol=DIFFEVOLVE(func,popsize,lb,ub)%sol=DIFFEVOLVE(func,popsize,lb,ub,'option1',value1,...)%%[sol,fval]=DIFFEVOLVE(...)%[sol,fval,evals]=DIFFEVOLVE(...)%%DIFFEVOLVE(func,popsize,lb,ub)triestofindtheglobaloptimumof%thefitness-function[func],usingatransversaldifferentialevolution%strategy.Thepopulationsizesetby[popsize],andtheboundariesfor%eachdimensionaresetbythevectors[lb]and[ub],respectively.%%[sol,fval,evals]=DIFFEVOLVE(...)returnsthetrialvectorfoundto%yieldtheglobalminimumin[sol],andthecorrespondingfunctionvalue%by[fval].Thetotalamountoffunctionevaluationsthatthealgorithm%performedisreturnedin[evals].%%Thefunction[func]mustacceptavectorargumentoflength[N],equalto%thenumberofelementsinthevectors[lb]or[ub].Also,thefunction%mustbevectorizedsothatinsertingamatrixof[popsize]x[N]willreturn%avectorofsize[popsize]x[1]containingthecorrespondingfunctionvalues%forthe[N]trialvectors.%%ThedefaultcontrolparametersDIFFEVOLVEuses,are%%-1<F<1scalingparameterforthedifferencevector.%Bydefault,itisrandomlyselectedfromthe%range[-1,1]foreachindividualineach%iteration.%%crossconst=0.9Probabilityforcrossover.%%convergence=100Maximumamountofiterationsthebest%individualeverfoundshouldremainthebest%individualbeforethealgorithmconverges.%%Thesevalues,aswellasadditionaloptions,maybegivenmanuallyin%anyextrainputvariables.Additionally,DIFFEVOLVEmaybecalledas%DIFFEVOLVE(PROBLEM),where[PROBLEM]isacompleteproblem-structure%constructedbyHEURSET.%%Someoptimizationsrequirerepeatedevaluationofafunctionthattakes%intheorderofhoursperevaluation.Inthosecases,itmightbe%convenienttointerrupttheoptimizationafterafewdaysandusethe%resultsthusfarobtained.Unfortunately,usuallyafteryouinterrupta%function,itsresultsarelost.Forthatreason,DIFFEVOLVEcreatestwo%globalvariables,[DIFFEVOLVE_bestind]and[DIFFEVOLVE_bestfval],which%storethebestindividualandfunctionvaluethusfarfound.Whenthe%optimizationisinterrupted,theintermediateresultsfromthe%optmizationarestillavailable.Onceanoptimizationhassuccesfully%converged,thesevariablesaredeletedfromtheworkspaceagain.%%Seealsoheurset,genetic,swarm,simanneal,godlike.%Author:RodyP.S.Oldenhuis%DelftUniversityofTechnology%Lastedited:28/Feb/2008%%initialize&parseinput%initial(default)valuesskippop=false;options=heurset;[pop,func,popsize,lb,ub,grace,display,maxfevals,convmethod,...convvalue,crossconst,Flb,Fub,n]=parseprob(options);%temporaryglobalsglobalDIFFEVOLVE_bestindDIFFEVOLVE_bestfval%commoninputsif(nargin>=4)func=varargin{1};popsize=varargin{2};lb=varargin{3};ub=varargin{4};end%withadditionaloptionsif(nargin>=5)if~isstruct(varargin{5})options=heurset(varargin{5:end});elseoptions=varargin{5};end[dum1,dum2,dum3,dum4,dum5,grace,display,maxfevals,convmethod,...convvalue,crossconst,Flb,Fub,n]=parseprob(options);end%ifcalledfromGODLIKEif(nargin==2)problem=varargin{2};%errortrapif~isstruct(problem)error('PROBLEMshouldbeastructure.Type`helpheurset`fordetails.')end[pop,func,popsize,lb,ub,grace,display,maxfevals,convmethod,...convvalue,crossconst,Flb,Fub,n]=parseprob(problem);%makesuretheoptionsarecorrectconvmethod='maxiters';grace=0;display=false;skippop=true;end%ifgivenafullproblemstructureif(nargin==1)problem=varargin{1};%errortrapif~isstruct(problem)error('PROBLEMshouldbeastructure.Type`helpheurset`fordetails.')end[pop,func,popsize,lb,ub,grace,display,maxfevals,convmethod,...convvalue,crossconst,Flb,Fub,n]=parseprob(problem);end%initializeconvergencemethodifstrcmpi(convmethod,'exhaustive')convergence=1;maxiterinpop=convvalue;maxiters=inf;elseifstrcmpi(convmethod,'maxiters')convergence=2;maxiterinpop=inf;maxiters=convvalue;elseifstrcmpi(convmethod,'achieveFval')convergence=3;%errortrapifisempty(convvalue)error('Pleasedefinefunctionvaluetoachieve.')endmaxiterinpop=inf;maxiters=inf;elseconvergence=1;maxiterinpop=convvalue;end%problemdimensionsdims=size(lb,2);%errortrapsif((size(lb,2)~=1||size(ub,2)~=1)&&...(size(lb,2)~=dims||size(ub,2)~=dims))error('Upper-andlowerboundariesmustbethesamesize.')endif(popsize<3)error('DIFFEVOLVEneedsapopulationsizeofatleast3.')end%%initialvalues%iteration-zerovaluesoldbestfit=inf;improvement=maxiterinpop;iters=0;evals=0;sizepop=[popsize,dims];fitnew=inf(popsize,1);firsttime=true;converging1=false;converging2=false;%boundariesif(numel(lb)==1)mins=repmat(lb,popsize,dims);maxs=repmat(ub,popsize,dims);endif(numel(lb)==numel(ub)&&size(lb,2)==dims)mins=repmat(lb,popsize,1);maxs=repmat(ub,popsize,1);endrange=(maxs-mins);%initializepopulationif(~skippop)pop=repmat(ub,popsize,1)-repmat(ub-lb,popsize,1).*rand(popsize,dims);endnewpop=pop;prevpop=pop;%Displaystringsifdisplayfprintf(1,['\nNotethatwhenDIFFEVOLVEisinterrupted,thebestsolutionandfunction\n',...'valuearesavedinglobalvariablesDIFFEVOLVE_bestindandDIFFEVOLVE_bestfval.\n\n']);fprintf(1,'Optimizingwith');switchconvergencecase1fprintf(1,'exhaustiveconvergencecriterion...\n');case2fprintf(1,'maximumiterationsconvergencecriterion...\n');case3fprintf(1,'goal-attainconvergencecriterion...\n');endfprintf(1,'Currentbestsolutionhascostof-------------');overfevals1='\n\nCouldnotfindbettersolutionwithingivenmaximum';overfevals2='\noffunctionevaluations.IncreaseMaxFevalsoption.\n\n';fitbackspace='\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b';converge1bck=[fitbackspace,'\b\b\b\b\b\b\b\b\b\b\b'];converge2bck=[fitbackspace,'\b\b\b\b\b\b\b'];convergestr=',possiblyconverging:';itersstr=',iterationsleft:';end%%DifferentialEvolutionloop%loopwhileoneoftheconvergencecriteriaisnotmetwhile(improvement>0&&iters<=maxiters)%evaluatefitnessesandadjustpopulationfitold=fitnew;tryfitnew=feval(func,newpop);catcherror('diffevolve:fevalerror',...['Diffevolvecannotcontinuebecausethesuppliedcostfunction',...'gavethefollowingerror:\n%s'],lasterr);endif(numel(fitnew)~=popsize)error('diffevolve:function_not_vectorized_or_incorrect_dimensions',...['Theuser-suppliedcostfunctiondoesnotappeartogetenougharguments,\n',...'orisnotvectorizedproperly.Makesurethedimensionsofthelimits[Lb]\n',...'and[Ub]arethesameastherequiredinputvectorforthefunction,orthat\n',...'thefunctionisvectorizedproperly.'])endprevpop=newpop;pop(fitnew<fitold,:)=newpop(fitnew<fitold,:);%increasenumberoffunctionevaluationsevals=evals+numel(fitnew);%improvingsolutions[bestindfit,ind]=min(fitnew);bestind=newpop(ind,:);if(bestindfit<oldbestfit)%newbestindividualoldbestfit=bestindfit;oldbestind=bestind;improvement=maxiterinpop;%assignalsotheglobalsDIFFEVOLVE_bestind=bestind;DIFFEVOLVE_bestfval=bestindfit;%displayimprovingsolutionifdisplayifconverging1fprintf(1,converge1bck);pause(0.05)endifconverging2fprintf(1,converge2bck);pause(0.05)endif(oldbestfit<0)fprintf('\b')endfprintf(1,fitbackspace);fprintf(1,'%1.8e',oldbestfit);converging1=false;firsttime=true;pause(0.05)endend%Checkforconvergenceif(evals>maxfevals)%maximumallowedfunctionevaluationshasbeensupercededfprintf(overfevals1);fprintf(overfevals2);breakendswitchconvergence%exhaustivecase1if(oldbestfit<=bestindfit)&&(oldbestfit~=inf)if(improvement<=100)&&displayif~converging1fprintf(1,convergestr);fprintf(1,'%3.0f',improvement-1);converging1=true;pause(0.05)elsefprintf(1,'\b\b\b%3.0f',improvement-1);pause(0.05)endendimprovement=improvement-1;end%maxiterationscase2ifdisplay&&(maxiters-iters<100)iffirsttimefprintf(1,itersstr);fprintf(1,'%3.0f',maxiters-iters);pause(0.05)elsefprintf(1,'\b\b\b%3.0f',maxiters-iters);pause(0.05)endfirsttime=false;converging2=true;enditers=iters+1;%goal-attaincase3if(oldbestfit<=convvalue)break;endend%TransversalDifferentialEvolutionfori=1:popsizeforj=1:nbase=1;d1=1;d2=1;whilebase==d1||base==d2||d1==d2base=round(rand*(popsize-1))+1;d1=round(rand*(popsize-1))+1;d2=round(rand*(popsize-1))+1;endreplace=rand<crossconst|rand==i;ifreplaceF=(Fub-Flb)*rand+Flb;newpop(i,:)=pop(base,:)+F*(pop(d1,:)-pop(d2,:));elsenewpop(i,:)=pop(i,:);endendend%enforceboundariesoutsiders1=(newpop<mins);outsiders2=(newpop>maxs);ifany(outsiders1(:))||any(outsiders2(:))reinit=rand(sizepop).*range+mins;newpop(outsiders1)=reinit(outsiders1);newpop(outsiders2)=reinit(outsiders2);endend%%(pre-)endvalues%ifsolutionhasbeenfoundifisfinite(oldbestfit)%whencallednormallyif(~skippop)fval=oldbestfit;sol=oldbestind;%whencalledfromGODLIKEelsefval=
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 购销合同印花税的税率计算器版本更新
- 资产转让合同范本
- 跨学科的小学数学作业设计
- 轻松提升小学生阅读能力
- 辣椒采购单据模板
- 连带责任保证书样本
- 透水混凝土施工要点购买条款
- 酒店厨房用油烟机销售协议
- 重庆市地理探秘之旅
- 重要电梯修理招标公告
- 青岛市文化馆招聘艺术类人员笔试真题2023
- 小学一年级数学20以内的口算题(可直接打印A4)
- 2024年艾滋病日宣传
- 乙方入股甲方店铺协议书(2篇)
- 艺术团体演出人员配置方案
- 立春气候与健康
- 八年级上册物理全册知识点总结(人教)
- 数据产权:生成式人工智能训练行为版权争议的规制路径
- 《中电联团标电化学储能电站技术监督导则》
- 中华民族发展史智慧树知到期末考试答案章节答案2024年云南大学
- 30题纪检监察位岗位常见面试问题含HR问题考察点及参考回答
评论
0/150
提交评论