%% This script is the scheme for the EM algorithm of the whole model for estimating parameters

clear
globalvars_edgefile; % declare variables to be used globally



loaddata_localvolum_edgefile_meantrans_normtkt;

load 'TrainedExpvectorsByK1Resolution' ;  %% This is the leant variable "Expvectors" from the resolution model 
load 'TrainedW_classByK1Resolution' ;  %% This is the learnt variable "w_class" from the resolution model 


%K=4; % 4 routing strategies to consider

K=6; % 6 routing strategies to consider

convergence=-1;
iter=0;
max_iter_main=1000;
old_lhood=0;
em_convergence=0.000001;




options.Method = 'lbfgs'; 
options.maxIter =3;	  
options.maxFunEvals=3;
options.display = 'off';


l4=size(Tktvectors,2)+1+size(Expvectors,2);
l5=1;



%% Initialize phi and gamma specific to each expert


[mupara,sigmasquare, TRC_ij]=lognormaldistr(ExpTransTktFile,Expvectors,EdgeConn); % Estimate the relative knowledge difference over all transferred tasks 




%initiate_model_edgefile_opt_fixbeta;
%initiate_model_edgefile_opt_fixbeta_randC1;
%initiate_model_edgefile_opt_fixbeta_PRC1;
%initiate_model_edgefile_opt_lognormalbeta_TRC;

initiate_model_edgefile_opt_lognormalbeta_allSix;


alphaprior=ones(1,K)*1/K;
% alphaprior=alphaprior/sum(alphaprior);
% alphaprior=rand(1,K);

tempflag='localVEPR and original rand with corected testtransfile';
while ((iter<=max_iter_main)&&(convergence>em_convergence || convergence<0))
    fprintf('Now get into E-step:....\n');
  %  [lhood, terms]=Estep_Kis2_2randfactor();
    
     %lhood=Estep();
     % lhood=Estep_edgefile_maxopt();
      lhood=Estep_edgefile_lognormal();
    

    
    if (old_lhood~=0)
        convergence=(lhood-old_lhood)/abs(old_lhood);
    else
        convergence=-1;
    end
    
    if ((convergence <0) && old_lhood~=0)
        fprintf('Warning: EM iteration %d: the old likelihood %f > the new likelihood %f\n', iter, old_lhood, lhood);
        disp('old terms vs new terms');
      %  [old_terms; terms]
        break; % to check what the problem is. 
        
    else
        fprintf('Now get into M-step:....\n');
        %Mstep();
        
        %Mstep_justalpha_nooracle();
        Mstep_lognormal();
        
        %Mstep_justalpha_nooracle_alphascalor();
        %Mstep_justalpha_nooracle_alpharand();
        fprintf('EM iteration %d: the old likelihood %f the new likelihood %f\n', iter, old_lhood, lhood);     
        
        old_lhood=lhood;
%        old_terms=terms;
        iter=iter+1;        
    end
    
     %save 'K3model_onlyedgeintrain_correcttest_fixbetaByResln_1_15_alphauniforminit_iter1000.mat';
     %save 'K3model_onlyedgeintrain_correcttest_fixbetaByResln_1_22_alphauniforminit_iter1000.mat';
    
end


