⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sga_test.m

📁 人工免疫算法基于遗传MATLAB代码很有用哦
💻 M
字号:
function [x,endPop,bPop,traceInfo] = sga(bounds, evalFN, startPop,...
  selectFN, xOverFNs, mutFNs, opts)
% GA run a genetic algorithm
% function [x,endPop,bPop,traceInfo]=sga(bounds,evalFN,evalOps,startPop,opts,
%                                       termFN,termOps,selectFN,selectOps,
%                                       xOverFNs,xOverOps,mutFNs,mutOps)


% Output Arguments:
%   x            - the best solution found during the course of the run
%   endPop       - the final population 
%   bPop         - a trace of the best population
%   traceInfo    - a matrix of best and means of the ga for each generation
%
% Input Arguments:
%   bounds       - a matrix of upper and lower bounds on the variables
%   evalFN       - the name of the evaluation .m function
%   evalOps      - options to pass to the evaluation function ([NULL])
%   startPop     - a matrix of solutions that can be initialized
%                  from initialize.m
%   opts         - [epsilon prob_ops display] change required to consider two 
%                  solutions different, prob_ops 0 if you want to apply the
%                  genetic operators probabilisticly to each solution, 1 if
%                  you are supplying a deterministic number of operator
%                  applications and display is 1 to output progress 0 for
%                  quiet. ([1e-6 1 0])
%   termFN       - name of the .m termination function (['maxGenTerm'])
%   termOps      - options string to be passed to the termination function
%                  ([100]).
%   selectFN     - name of the .m selection function (['normGeomSelect'])
%   selectOpts   - options string to be passed to select after
%                  select(pop,#,opts) ([0.08])
%   xOverFNS     - a string containing blank seperated names of Xover.m
%                  files (['arithXover heuristicXover simpleXover']) 
%   xOverOps     - A matrix of options to pass to Xover.m files with the
%                  first column being the number of that xOver to perform
%                  similiarly for mutation ([2 0;2 3;2 0])
%   mutFNs       - a string containing blank seperated names of mutation.m 
%                  files (['boundaryMutation multiNonUnifMutation ...
%                           nonUnifMutation unifMutation'])
%   mutOps       - A matrix of options to pass to Xover.m files with the
%                  first column being the number of that xOver to perform
%                  similiarly for mutation ([4 0 0;6 100 3;4 100 3;4 0 0])

% Binary and Real-Valued Simulation Evolution for Matlab 
% Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay 
%

n=nargin;
if n<2 | n==4 | n==6
  disp('Insufficient arguements') 
end

%if isempty(opts)
  opts= [1e-6 0.8 0.05 50];
%end

    num=20;
    bounds=[0 9];
    evalFN='gademo1eval';
    selectFN=['select_Roulette'];
    mutFNs=['binaryMutation'];
    xOverFNs=['simpleCross'];

if any(evalFN<48) %Not using a .m file
    %Binary ga
    e1str=['x=b2f(endPop(j,:),bounds,bits); endPop(j,xZomeLength)=',...
	evalFN ';'];
else %Are using a .m file
    %Binary ga
    e1str=['x=b2f(endPop(j,:),bounds,bits);[x v]=' evalFN ...
	'(x,[gen ]); endPop(j,:)=[f2b(x,bounds,bits) v];'];  
end
   
if n<1 %No starting population passed given
  startPop=[];
end

if isempty(startPop) %Generate a population at random
  %startPop=zeros(80,size(bounds,1)+1);
  startPop=initpop(80,bounds,evalFN,opts);
end

bits=ceil(log2((bounds(:,2)-bounds(:,1))' ./opts(1)));
%startPop=initpop(num,bounds,evalFN)

xZomeLength  = size(startPop,2); 	%Length of the xzome=numVars+fittness
numVar       = xZomeLength-1; 		%Number of variables
popSize      = size(startPop,1); 	%Number of individuals in the pop
endPop       = zeros(popSize,xZomeLength); %A secondary population matrix
c1           = zeros(1,xZomeLength); 	%An individual
c2           = zeros(1,xZomeLength); 	%An individual
numXOvers    = opts(2); 	%Number of Crossover operators
numMuts      = opts(3); 		%Number of Mutation operators
termOps      = opts(4);
epsilon      = opts(1);                 %Threshold for two fittness to differ
oval         = max(startPop(:,xZomeLength)); %Best value in start pop
bFoundIn     = 1; 		        	%Number of times best has changed
done         = 0;                       %Done with simulated evolution
gen          = 1; 			       %Current Generation Number
collectTrace = (nargout>3); 		%Should we collect info every gen
display      = 0;                 %Display progress 


while(~done)
  %Elitist Model
  [bval,bindx] = max(startPop(:,xZomeLength)); %Best of current pop
   best =  startPop(bindx,:);

  if collectTrace
    traceInfo(gen,1)=gen; 		          %current generation
    traceInfo(gen,2)=startPop(bindx,xZomeLength);       %Best fittness
    traceInfo(gen,3)=mean(startPop(:,xZomeLength));     %Avg fittness
    traceInfo(gen,4)=std(startPop(:,xZomeLength));      %标准差
  end
  
  if ( (abs(bval - oval)>epsilon) | (gen==1)) %If we have a new best sol
    if display
      fprintf(1,'\n%d %f\n',gen,bval);          %Update the display
    end
      bPop(bFoundIn,:)=[gen b2f(startPop(bindx,1:numVar),bounds,bits)...
	  startPop(bindx,xZomeLength)];
   
    bFoundIn=bFoundIn+1;                      %Update number of changes
    oval=bval;                                %Update the best val
  else
    if display
      fprintf(1,'%d ',gen);	              %Otherwise just update num gen
    end
  end
  
  endPop = feval(selectFN,startPop);      %Select operator
  
    %We are running a probabilistic model of crossover operator

      xN=deblank(xOverFNs); 	%Get the name of crossover function
      cp=find(rand(popSize,1)< numXOvers==1);
      if rem(size(cp,1),2) cp=cp(1:(size(cp,1)-1)); end
      cp=reshape(cp,size(cp,1)/2,2);
      for j=1:size(cp,1)
	    a=cp(j,1); b=cp(j,2); 
	    [endPop(a,:) endPop(b,:)] = feval(xN,endPop(a,:),endPop(b,:),bounds);
      end
 
    %We are running a probabilistic model of mutation operator 

      mN=deblank(mutFNs);
      for j=1:popSize
	  endPop(j,:) = feval(mN,endPop(j,:),bounds,opts(3));
	  eval(e1str);
      end
      
  gen=gen+1;

 % 判断终止条件 
  if gen>=opts(4)
      done=1;              %See if the ga is done
  end
 
  startPop=endPop; 			%Swap the populations
  [bval,bindx] = min(startPop(:,xZomeLength)); %Keep the best solution
  startPop(bindx,:) = best; 		%replace it with the worst

end

  [bval,bindx] = max(startPop(:,xZomeLength));
  if display 
  fprintf(1,'\n%d %f\n',gen,bval);	  
  end

  x=b2f(startPop(bindx,:),bounds,bits)
  y=startPop(bindx,xZomeLength)
  
  bPop(bFoundIn,:)=[gen b2f(startPop(bindx,1:numVar),bounds,bits)...
      startPop(bindx,xZomeLength)];   %bPop  最佳个体【最佳代 最佳解 最大适应度】

  if collectTrace
%  traceInfo(gen,1)=gen		%current generation
%  traceInfo(gen,2)=startPop(bindx,xZomeLength); %Best fittness
%  traceInfo(gen,3)=mean(startPop(:,xZomeLength)); %Avg fittness
  end

 fplot('x + 10*sin(5*x)+7*cos(4*x)',[0,9]);   %画出函数曲线

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -