function bestpar=CSAES
%
% ----------------------------------------------------
%
% parametres LD
%
%n=5;mu=8;lambda=25; siginit=1;  Ngen=200;  xmin0=0;xmax0=4;     %% MICH 5
n=10;mu=12;lambda=36; siginit=1; Ngen=200; xmin0=0;xmax0=4;    %% MICH 10
%
%
% ------- parameters for CSA adaptation-------------
c=1/sqrt(n);
chiN=sqrt(n)*(1-1/(4*n)+1/(21*n^2));
D=sqrt(n);
%
% ----------------------------------------------------
%
xmin=xmin0*ones(1,n);
xmax=xmax0*ones(1,n);
Xmin=ones(mu,1)*xmin;
Xmax=ones(mu,1)*xmax;
u=rand(mu,n);
pop=Xmin+(Xmax-Xmin).*u;  % random initialisation of the population
Xpar=[pop,rand(mu,1)];  Xoldpar=Xpar;
Xoff=Xpar;min=[];Ntot=[];
mineval=0;newval=zeros(mu,1);itfct=0;fmin=[];
%
%-----------------------------------------------------
%-----------------------------------------------------
%
sigma=siginit;
V=zeros(1,n);
Xpar=evaluation(Xpar);
Y=1/mu*sum(Xpar(:,1:n),1);
Nevalf=mu;
%
% ---- MAIN LOOP : BEGINNING---------------------------
%------------------------------------------------------
%
for gen=1:(Ngen-1)
%
W=[];
  for i=1:lambda
    w=sigma*randn(1,n);  % mutation       
    W=[W;w];
    xoff=Y+w;   
    Xoff(i,1:n)=xoff;
end
%
Xoff=evaluation(Xoff);          % evaluation 
Nevalf=Nevalf+lambda;
%
[Xpar,ind]=selection(Xpar,Xoff); % selection
%
fmin=[fmin,Xpar(1,end)];
bestpar=Xpar(1,1:n);
Ntot=[Ntot,Nevalf];
%
% ---  adaptativity of sigma-----------------
%
Z=1/mu*sum(W(ind,:),1);
Y=Y+Z;
V=(1-c)*V+sqrt(c*(2-c))*sqrt(mu)/sigma*Z;
sigma=sigma*exp((norm(V)-chiN)/(D*chiN));
%
%------------------------------------------------------
%-------MAIN LOOP : ENDING-----------------------------
%
end
%-----------------------------------------------------
%-----------------------------------------------------
%
%
%
plot(Ntot,fmin);
disp('minimum obtained:');disp(bestpar(1:n));
disp('corresponding value by f:');disp(fmin(end));
disp('evaluation number:');disp(Nevalf);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
function y = f(x)        % the function to minimize
n=prod(size(x));
%
%%%%% Michalewicz %%%%%%%%%%%%
 m = 10;y = 0;
 for i = 1:n;
    y = y-sin(x(i))*(sin(i*x(i)^2/pi))^(2*10);
end
%%%%% Rosenbrock %%%%%%%%%%%%
%y = 0;
%for j = 1:n-1;
%    y = y+100*(x(j)^2-x(j+1))^2+(x(j)-1)^2;
%end
%
%
%-----------------------------------------------------
function Xpar=evaluation(X);  % evaluation of a whole population
Xpar=X;
[Npo,n]=size(X);n=n-1;
evalpop=zeros(Npo,1);
for i=1:Npo;
 evalpop(i)=f(X(i,1:n));
end
Xpar(:,n+1)=evalpop;
%
%-----------------------------------------------------
function [Xparnew,indbest]=selection(Xpar,Xoff)   % selection comma
[mu,n]=size(Xpar);
[lambda,n]=size(Xoff);
n=n-1; 
Xtot=Xoff;                 
[Fsort,ind]=sort(Xtot(:,n+1));
indbest=ind(1:mu);
Xparnew=Xtot(indbest,:);
%


