clear
clf

np=1000000;				% number of tries to take
ns=1000;				% number of models to keep
T0=1.;
alpha=0.600;
T=T0;
P=0;
% 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)));

surf(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);
   P=pdf(xcur(1),xcur(2));
       disp(sprintf(' Starting point is [%i,%i]', xcur(1),xcur(2))) 

imagesc(pdf'),

while (is<=ns&T>0.),

	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));
    
   T=alpha*T;
   
   if (Pnew > Pcur&T>0.), 
      xcur=xnew;
      is=is+1;
      disp(sprintf(' Made the %i-th move to [%i,%i] P= %g T=%g np1=%i', is,xcur(1),xcur(2),P,T,np1)) 
      np1=0;
      if (xcur(1)==77&xcur(2)==50) is=ns+1;end;
      
      % display move graphically
      
		imagesc(pdf'), hold on, plot(xnew(1),xnew(2),'k+'), hold off
      drawnow
      
   end
   
   if (Pnew < Pcur&T>0.), 
      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] P= %g T=%g np1=%i', is,xcur(1),xcur(2),P,T,np1)) 
      np1=0;
      if (xcur(1)==77&xcur(2)==50) is=ns+1;end;
      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

     disp(sprintf(' np= %i ',np)) 

hold off

% Final sampling

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

imagesc(pdf'), 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

