purecmaes.m 8.77 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
  function [xmin]=purecmaes(strfitnessfct)
  % CMA-ES: Evolution Strategy with Covariance Matrix Adaptation for
  % nonlinear function minimization. To be used under the terms of the
  % GNU General Public License (http://www.gnu.org/copyleft/gpl.html).
  %
  % This code is an excerpt from cmaes.m and implements the key parts
  % of the algorithm. It is intendend to be used for READING and
  % UNDERSTANDING the basic flow and all details of the CMA
  % *algorithm*. Use the cmaes.m code to run serious simulations. It
  % is somewhat longer but it is supposed to be saver, faster and,
  % after all, more practicable.
  %
  % Author: Nikolaus Hansen, 2003. 
  % e-mail: hansen[at]bionik.tu-berlin.de
  % URL: http://www.bionik.tu-berlin.de/user/niko
  % References: See end of file. Last change: October, 27, 2004


  % --------------------  Initialization --------------------------------  

  % User defined input parameters (need to be edited)
  %strfitnessfct = 'frastrigin10'; % name of objective/fitness function
  N = 25;                  % number of objective variables/problem dimension
  xmean = pi*ones(N,1);       % objective variables initial point
  sigma = 1;             % coordinate wise standard deviation (step size)
  stopfitness = 1e-10;     % stop if fitness < stopfitness (minimization)
  stopeval = 2e2*N^2;      % stop after stopeval number of function evaluations
  
  % Strategy parameter setting: Selection  
  lambda = 4+floor(3*log(N));  % population size, offspring number
  mu = floor(lambda/2);        % number of parents/points for recombination
  weights = log(mu+1)-log(1:mu)'; % muXone array for weighted recombination
  % lambda=12; mu=3; weights = ones(mu,1); % uncomment for (3_I,12)-ES
  weights = weights/sum(weights);     % normalize recombination weights array
  mueff=sum(weights)^2/sum(weights.^2); % variance-effective size of mu

  % Strategy parameter setting: Adaptation
  cc = 4/(N+4);    % time constant for cumulation for covariance matrix
  cs = (mueff+2)/(N+mueff+3); % t-const for cumulation for sigma control
  mucov = mueff;   % size of mu used for calculating learning rate ccov
  ccov = (1/mucov) * 2/(N+1.4)^2 + (1-1/mucov) * ...  % learning rate for
         ((2*mueff-1)/((N+2)^2+2*mueff));             % covariance matrix
  damps = 1 + 2*max(0, sqrt((mueff-1)/(N+1))-1) + cs; % damping for sigma 
                                                      % usually close to 1
                                                    % former damp == damps/cs
  
  % Initialize dynamic (internal) strategy parameters and constants
  pc = zeros(N,1); ps = zeros(N,1);   % evolution paths for C and sigma
  B = eye(N);                         % B defines the coordinate system
  D = eye(N);                         % diagonal matrix D defines the scaling
  C = B*D*(B*D)';                     % covariance matrix
  chiN=N^0.5*(1-1/(4*N)+1/(21*N^2));  % expectation of 
                                      %   ||N(0,I)|| == norm(randn(N,1))
  
                                      
  % compute function for plotting
  
  x=[0:0.1:2*pi];
  y=[0:0.1:2*pi];
  f=zeros(size(x,1),size(y,1));
  i=1;
  j=1;
  for i=1:size(x,2)
      i
      for j=1:size(y,2)
          f(i,j)=feval(strfitnessfct, [x(i);y(j)]);  
      end
  end
  
  figure
  [X,Y]=meshgrid(x,y);
  mesh(Y,X,f)
  view(90,90)
  hold
  
  bestF=1000;
  
  % -------------------- Generation Loop --------------------------------

  counteval = 0;  % the next 40 lines contain the 20 lines of interesting code 
  while counteval < stopeval
         
    error_ellipse('C',sigma^2*C(1:2,1:2),'mu',xmean(1:2),'style','r')
    pause(0.1)   
    % Generate and evaluate lambda offspring
    arz = randn(N,lambda);  % array of normally distributed mutation vectors
    for k=1:lambda,
      arx(:,k) = mod(xmean + sigma * (B*D * arz(:,k)),2*pi);   % add mutation  % Eq. (1)
      arfitness(k) = feval(strfitnessfct, arx(:,k)); % objective function call
      stunfitness(k) = 1-exp(-(arfitness(k)-bestF));
      counteval = counteval+1;
    end
    
    % Sort by fitness and compute weighted mean into xmean
    [arfitness, arindex] = sort(arfitness); % minimization
    % [stunfitness, arindex] = sort(stunfitness); % minimization
    xmean = arx(:,arindex(1:mu))*weights;   % recombination, new mean value
    zmean = arz(:,arindex(1:mu))*weights;   % == sigma^-1*D^-1*B'*(xmean-xold)
    
    % Cumulation: Update evolution paths
    ps = (1-cs)*ps + sqrt(cs*(2-cs)*mueff) * (B * zmean);            % Eq. (4)
    hsig = norm(ps)/sqrt(1-(1-cs)^(2*counteval/lambda))/chiN < 1.5 + 1/(N+1);
    pc = (1-cc)*pc ...
          + hsig * sqrt(cc*(2-cc)*mueff) * (B * D * zmean);          % Eq. (2)

    % Adapt covariance matrix C
    C = (1-ccov) * C ...                    % regard old matrix      % Eq. (3)
         + ccov * (1/mucov) * (pc*pc' ...   % plus rank one update
                               + (1-hsig) * cc*(2-cc) * C) ...
         + ccov * (1-1/mucov) ...           % plus rank mu update 
           * (B*D*arz(:,arindex(1:mu))) ...
           *  diag(weights) * (B*D*arz(:,arindex(1:mu)))';               

    % Adapt step size sigma
    sigma = sigma * exp((cs/damps)*(norm(ps)/chiN - 1));             % Eq. (5)
    
    % Update B and D from C
    % This is O(N^3). When strategy internal CPU-time is critical, the
    % next three lines can be executed only every (alpha/ccov/N)-th
    % iteration step, where alpha is e.g. between 0.1 and 10 
    C=triu(C)+triu(C,1)'; % enforce symmetry
    [B,D] = eig(C);       % eigen decomposition, B==normalized eigenvectors
    D = diag(sqrt(diag(D))); % D contains standard deviations now

    % Remmeber best fitness
    if arfitness(1)<bestF
        bestF=arfitness(1);
        bestX=arx;
    end
    
    % Break, if fitness is good enough
    if arfitness(1) <= stopfitness 
      break;
    end

    disp([num2str(counteval) ': ' num2str(arfitness(1))]);
    disp([' Volume of covariance: ' num2str(det(eye(N)*sigma^2*C))]);


  end % while, end generation loop

  % -------------------- Ending Message ---------------------------------

  disp([num2str(counteval) ': ' num2str(bestF)]);
  xmin = arx(:, arindex(1)); % Return best point of last generation.
                             % Notice that xmean is expected to be even
                             % better.
  
% ---------------------------------------------------------------  
function f=fsphere(x)
  f=sum(x.^2);
  
function f=fschwefel(x)
  f = 0;
  for i = 1:size(x,1),
    f = f+sum(x(1:i))^2;
  end

function f=fcigar(x)
  f = x(1)^2 + 1e6*sum(x(2:end).^2);
  
function f=fcigtab(x)
  f = x(1)^2 + 1e8*x(end)^2 + 1e4*sum(x(2:(end-1)).^2);
  
function f=ftablet(x)
  f = 1e6*x(1)^2 + sum(x(2:end).^2);
  
function f=felli(x)
  N = size(x,1); if N < 2 error('dimension must be greater one'); end
  f=1e6.^((0:N-1)/(N-1)) * x.^2;

function f=felli100(x)
  N = size(x,1); if N < 2 error('dimension must be greater one'); end
  f=1e4.^((0:N-1)/(N-1)) * x.^2;

function f=fplane(x)
  f=x(1);

function f=ftwoaxes(x)
  f = sum(x(1:floor(end/2)).^2) + 1e6*sum(x(floor(1+end/2):end).^2);

function f=fparabR(x)
  f = -x(1) + 100*sum(x(2:end).^2);

function f=fsharpR(x)
  f = -x(1) + 100*norm(x(2:end));
  
function f=frosen(x)
  if size(x,1) < 2 error('dimension must be greater one'); end
  f = 100*sum((x(1:end-1).^2 - x(2:end)).^2) + sum((x(1:end-1)-1).^2);

function f=fdiffpow(x)
  N = size(x,1); if N < 2 error('dimension must be greater one'); end
  f=sum(abs(x).^(2+10*(0:N-1)'/(N-1)));
  
function f=frastrigin(x)
  N = size(x,1); if N < 2 error('dimension must be greater one'); end
  f = 10.0 * size(x,1) + sum(x .^2 - 10.0 * cos(2 * pi .* x),1);
  
  
function f=fkjellstrom1(x)
  N = size(x,1); if N < 2 error('dimension must be greater one'); end
  f = 20.0 - sum((x+0.5).^2) + exp(25*(sum(x.^2)-N)); 
  
function f=fkjellstrom2(x)
  N = size(x,1);
  h = 0.01*((cos(x+1.982) + cos(x+5.720) + cos(3*x + 1.621) + cos(4*x + 0.823) + cos(5*x + 3.222))); 
  f = prod(1+h(:));
  

function f=frand(x)
  f=rand;

% ---------------------------------------------------------------  
%%% REFERENCES
%
% The equation numbers refer to 
% Hansen, N. and S. Kern (2004). Evaluating the CMA Evolution
% Strategy on Multimodal Test Functions.  Eighth International
% Conference on Parallel Problem Solving from Nature PPSN VIII,
% Proceedings, pp. 282-291, Berlin: Springer. 
% (http://www.bionik.tu-berlin.de/user/niko/ppsn2004hansenkern.pdf)
% 
% Further references:
% Hansen, N. and A. Ostermeier (2001). Completely Derandomized
% Self-Adaptation in Evolution Strategies. Evolutionary Computation,
% 9(2), pp. 159-195.
% (http://www.bionik.tu-berlin.de/user/niko/cmaartic.pdf).
%
% Hansen, N., S.D. Mueller and P. Koumoutsakos (2003). Reducing the
% Time Complexity of the Derandomized Evolution Strategy with
% Covariance Matrix Adaptation (CMA-ES). Evolutionary Computation,
% 11(1).  (http://mitpress.mit.edu/journals/pdf/evco_11_1_1_0.pdf).
%