clear all

filenames=['figa.d'; 'figb.d'; 'figc.d'];
filenames1=['figa.eps'; 'figb.eps'; 'figc.eps'];
filenames2=['figamse.eps'; 'figbmse.eps'; 'figcmse.eps'];

numsim=1000;
logkrange=2:0.5:7;
krange=ceil(2.^logkrange);
s = 1.5;
epsilon=1.0e-7;


for f=1:3,
  fid = fopen(filenames(f,:),'w');
  fprintf(fid,' Vote HT     Markov  MinPair  PKPD \n');


  total=[];
  msetotal=[];
  p=[];
  for k=krange,
    if f==1,
      p(1,1) = s/k;
      p(2:k,1) = (1-s/k)/(k-1);
    elseif f==2,
      a = ceil(k/2);
      p(1,1) = 0.95 * s/a;
      p(2:a,1) = (0.95-p(1,1))/(a-1);
      p(a+1:k,1) = (0.05)/(k-a);
    elseif f==3,
      p(1,1) = 0.95 * s/2;
      p(2,1) = 0.95 -p(1,1);
      p(3:k,1) = (0.05)/(k-2);
    end

    accuracy=[]; mse=[];

    for iter=1:numsim
      r=zeros(k,k);
      for i =1:k
        r(i,i+1:k) = min(max(epsilon,p(i) ./ (p(i)+p(i+1:k,1)')+0.1*randn(1,k-i)),1-epsilon) ;
        r(i+1:k,i) = 1 - r(i,i+1:k)';
      end

      % voting 
      D = r > 0.5; votes=sum(D,2);
      [p2, B] = method2(r);
      result = [method0(r,400) method1(r) p2 method3(r) method4(r) method5(r)];
      % randomly select the vote winner
      winners=find(votes==max(votes)) ;
      winner=randperm(size(winners,1)) ;
      votesprob=2*votes/k/(k-1);
      tmp=[votesprob result]-repmat(p,1,size(result,2)+1);
      mse=[mse; sum(tmp.*tmp,1)/k];
      accuracy=[accuracy; winners(winner(1))==1, max(result(2:k,:),[],1) < result(1,:)];
    end
    total=[total; sum(accuracy,1)/numsim];
    msetotal=[msetotal; mean(mse,1)];
  end

  fprintf(fid,'%5.4f  %5.4f  %5.4f  %5.4f  %5.4f  %5.4f %5.4f\n', total');

  figure(f+3)
  plot(...
      logkrange, msetotal(:,1), 'k--s',...	%Voting-randomized
      logkrange, msetotal(:,2), 'k-x',...	%HT
      logkrange, msetotal(:,3), 'k:o',...	%Markov
      logkrange, msetotal(:,4), 'k--*',...	%minpair
      logkrange, msetotal(:,5), 'k-.d'); ,...	%PKPD
%      logkrange, msetotal(:,6), 'k--^'); ,	... %platt
%      logkrange, msetotal(:,7), 'k--d');	%prod
  set(gca, 'fontsize', 18) ; 
  set(findobj('Type', 'line'), 'markersize', 12)    
  axis([logkrange(1) logkrange(size(logkrange,2)) 0 0.035]);
  xlabel('log_2 k');
  ylabel('MSE');
  print('-deps',filenames2(f,:))

  figure(f);
  plot(...
      logkrange, total(:,1), 'k--s',...	%Voting-randomized      
      logkrange, total(:,2), 'k-x',...	%HT
      logkrange, total(:,3), 'k:o',...	%Markov
      logkrange, total(:,4), 'k--*',...	%minpair
      logkrange, total(:,5), 'k-.d'); %,...	%PKPD
%      logkrange, total(:,6), 'k--^'); ,...	%platt
%      logkrange, total(:,7), 'k--d');	%prod
  fclose(fid);
  axis([logkrange(1) logkrange(size(logkrange,2)) 0.6 1.05]);
  set(gca, 'fontsize', 18) ; 
  set(findobj('Type', 'line'), 'markersize', 12)  
  xlabel('log_2 k');
  ylabel('Accuracy Rates');
%  title(strcat('P(Class 1)=',num2str(s),'/K'))
  print('-deps',filenames1(f,:))
end

