function Xeval=evaluation(X);
  [Npop,n2]=size(X);n=n2-1;
  Xeval=X;
  for i=1:Npop;
    Xeval(i,$)=sum(X(i,1:n).^2-cos(2*%pi*X(i,1:n)))+n;
end
endfunction
///////////////////////////////
function bestX=best(X);
[Npop,n2]=size(X);
[y,k]=sort(-X(:,$))
bestX=X(k(1),:);
endfunction
//////////////////////////////
function X=elitism(X,oldbestpar)
[Npop,n2]=size(X);
bestpar=best(X);
if(oldbestpar(:,$)<bestpar(:,$)) then
i=int(Npop*rand())+1;
X(i,:)=oldbestpar;
end
endfunction
//////////////////////////////// 
function Xsel=selection(X)  // selection par le rang
[Npop,n2]=size(X);
[y,k]=sort(X(:,$))  
X=X(k,:);  
p=1:Npop;
roulette=cumsum(p)/sum(p);
Xsel=[];
for i=1:Npop
  u=rand();
  w=find(u<roulette);
  n1=w(1);
  xsel=X(n1,:);
  Xsel=[Xsel;xsel];
end  
endfunction
////////////////////////////////// 
function xcrois=croisement(x)
// x: 2 lignes
xcrois=x;
u=rand();
xcrois(1,:)=u*x(1,:)+(1-u)*x(2,:);
xcrois(2,:)=(1-u)*x(1,:)+u*x(2,:);
endfunction
//////////////////////////////////
function xmut=mutation(x,gen,Ngen,xmin,xmax)
// x: 1 ligne
bet=5;
if (rand()<1/2) then
   xmut=x+rand()*(xmax-x)*(1-(gen-1)/Ngen)^bet;
else
   xmut=x-rand()*(x-xmin)*(1-(gen-1)/Ngen)^bet;
end
endfunction

//////////MAIN //////////////////////////
Npop=50;
Ngen=30;
n=2;
pc=0.9;
pm=0.6;
xmin=-5;xmax=5;
//
X=xmin+(xmax-xmin)*rand(Npop,n+1);
bestX=[];
for gen=1:Ngen
X=evaluation(X);   // evaluation
X=selection(X);    // selection
if (gen>1) then X=elitism(X,oldbestpar);end // elitism
bestX=[bestX;best(X)];
oldbestpar=best(X);
Xnew=[];
for j=1:Npop/2
   u1=int(Npop*rand())+1;
   u2=int(Npop*rand())+1;
   if (rand()<pc) then 
     Xnew=[Xnew;croisement(X([u1,u2],:))]; //croisement  
   else
     Xnew=[Xnew;X([u1,u2],:)];
   end  
end
for j=1:Npop
  if (rand()<pm) then
    Xnew(j,:)=mutation(Xnew(j,:),gen,Ngen,xmin,xmax);  // mutation
  end 
end  
X=Xnew;
end
//////////TRACE //////////////////////////
xbasc()
plot2d(Npop*(1:Ngen),bestX(:,$))
disp('meilleur individu:');disp(bestX($,1:n))
  
  
  
  
  
  
 
  
  
  
  
  
  
  
  




