%  Program to test Markov-field convergence with blurring kernel
%  Lars Kai Hansen Oct 1997
%

% Lets define some variables
%randn('seed',1000);
N=50;             % size of picture
T=12;	          % number of temperatures
Steps=5;         % number of iterations at each temperature  

mfa=1;

m=zeros(N);     % mean fields
k=[0 1 0; 1 0 1; 0 1 0]



beta1=1;          %  final beta
beta0=0.001;	  %  initial beta

h0=-ones(N);
h0(10:20,10:20)=ones(11);
h1=h0+2*randn(N);
S=sign(randn(size(h1)));

figure(1), hold off,clg 
figure(2), hold off,clg
figure(3), hold off, clg
indx=zeros(N);
indx(1:2:N,1:2:N)=ones(N/2);
indx1=indx >0.5;
indx2=indx < 0.5;
S=sign(randn(size(h1)));
m=0.01*randn(N);
for t=1:T,

   beta = ((beta1-beta0)/(T-1))*(t-1) + beta0;
   beta_arr(t)=beta;
  if mfa==0,
    m=zeros(size(S));
  end; 

 for j=1:Steps,
  if(mfa==0) 
   prop=1./(1+exp(2*beta*S.*(conv2(S,k,'same')+0.2*h1)));
   S(indx1)=sign(rand(size(S(indx1))) - prop(indx1)).*S(indx1);
   prop=1./(1+exp(2*beta*S.*(conv2(S,k,'same')+0.2*h1)));
   S(indx2)=sign(rand(size(S(indx2))) - prop(indx2)).*S(indx2);
   m = m + S/Steps;
  else
   m=0.7*m+0.3*tanh(beta*(conv2(m,k,'same')+0.2*h1));
  end,
 end  
   m_arr(t)=mean(mean( abs(m) ));
   beta_arr(t)=beta;
   errors(t)=sum(sum(1 - sign(m).*sign(h0)))/2;
   figure(1), plot( beta_arr(1:t), m_arr(1:t) ),
   xlabel('1/T (BETA)')
   ylabel('AVERAGE MAGNETIZATION')
   figure(2), subplot(4,3,t), mat2gray(m);
   figure(3), plot(beta_arr(1:t),errors(1:t))
   xlabel('1/T (beta)') 
   ylabel('IMAGE MISMATCH')
end


