
clear
clf

np=1000000;				% number of tries to take
ns=100;				% number of models to keep
T0=1e-5;
alpha=0.995;
T=T0;

% Let's define a pdf

n=100;				% number of dimension in x and y
pdf=peaks(n);
pdf=sqrt(pdf.*pdf);
pdf=pdf/(sum(sum(pdf)));
pdf=pdf/(max(max(pdf)));

% Random walk

% find an initial vector x

xcur=round([rand rand]*100);

% Let s get moving

is=0;
np=0;
np1=0;
xa(1,1)=xcur(1);
xa(1,2)=xcur(2);
Pa=0;
P=0;
       disp(sprintf(' Starting point is [%i,%i]', xcur(1),xcur(2))) 

imagesc(pdf'),

   while max(Pa)<1.,

	np=np+1;   
	np1=np1+1;   
   % make a random choice for the next move
   xnew=round([rand rand]*100);
   xnew(find(xnew==0))=xnew(find(xnew==0))+1;
   
   % compare probabilities
   Pcur=pdf(xcur(1),xcur(2));
   Pnew=pdf(xnew(1),xnew(2));
   
   if Pnew >= Pcur, 
      xcur=xnew;
      is=is+1;
       disp(sprintf(' Made the %i-th move to [%i,%i], np1= %i', is,xcur(1),xcur(2),np1)) 
      np1=0;
      
      % display move graphically
      
		imagesc(pdf'), hold on, plot(xnew(1),xnew(2),'k+'), hold off
      drawnow
      
   end
   
   if Pnew < Pcur, 
      deltaP=Pcur-Pnew;
      P=exp(-deltaP/T);
      test=rand;
      if test<=P, 
      xcur=xnew;
      is=is+1;       
        
      disp(sprintf(' Made the %i-th move to [%i,%i], np1= %i', is,xcur(1),xcur(2),np1)) 
      np1=0;
      imagesc(pdf'), hold on, plot(xnew(1),xnew(2),'k+'), hold off
      drawnow
      
   end
end

   Pa(np)=Pnew;
   xa(np,1)=xcur(1);
   xa(np,2)=xcur(2);
   
end

np,is

hold off

% Final sampling

[y,i]=max(Pa);  		% index of the best model

imagesc(pdf'), axis square, hold on
xlabel('x')
ylabel('y')
plot(xa(1:np,1),xa(1:np,2),'w+')
plot(xa(i,1),xa(i,2),'w+','LineWidth',4)
hold off
