%function [alpha, W]=Mstep(alpha,W,gammaprior)
function []=Mstep_lognormal()

%% This script is the M step for our entire model 

%% K: number of routing strategies
%% alpha: 1*K vector
%% beta: K*NumExperts*NumTkts*NumExperts sparse matrix
%% X: NumTkts*NumExperts*NumExperts sparse matrix
%% TransExpertIndex: Index for experts that have transferred some tickets and how many tickets each has transferred

%% phi: NumTkts*K*NumExperts sparse matrix
%% gamma: NumExperts*K

addpath C:\Users\huansun\Documents\InternshipAtIBM\TextsExpertiseAssociation\Autoencoder_Code\SparseAutoencoder\minFunc\
%addpath C:\Users\huansun\Documents\InternshipAtIBM\TextsExpertiseAssociation\Autoencoder_Code\SparseAutoencoder\minFunc_2012\minFunc_2012\minFunc\
%addpath C:\Users\huansun\Documents\InternshipAtIBM\EntireModelOfTicketResolution\minFunc_2012\minFunc\
globalvars_edgefile;  % This is an M-file to declare global variables

transexperts=unique(ExpTransTktFile(:,1));
max_iter_minimize=3;


 optionsalpha.Method = 'lbfgs'; 
%  optionsalpha.maxIter =3;	  
%  optionsalpha.maxFunEvals=3;
 optionsalpha.maxIter =50;	  
 optionsalpha.maxFunEvals=50;
optionsalpha.display = 'off';
	

fprintf('In M step, now optimizing alpha...\n');

logalphaprior=log(alphaprior);

fprintf('In M step, now optimizing alpha...\n');
logalphaprior1=minFunc( @(p) terms_wrt_alpha(p,gammaprior,NumExperts0, K,transexperts),logalphaprior',options);
fprintf('Finish optimizing alpha...\n');


%[W]=minFunc(@terms_wrt_W,W,X,phi);

alphaprior=exp(logalphaprior1');


fprintf('Finish optimizing alpha...\n');


%[W]=minFunc(@terms_wrt_W,W,X,phi);

 

fprintf('In M step, now optimizing W...\n');

VV = [mupara log(sigmasquare)]'; 


% numgrad = computeNumericalGradient(@(x)Associate_Overall(x,Dim,SeqExpertMapping0), VV);
% [f, df]=Associate_Overall(VV,Dim,SeqExpertMapping0);
% norm(numgrad-df,'fro')/norm(numgrad+df,'fro');

X=minFunc( @(p) Associate_Overall_lognormal_musigma(p),VV,options);


 %X = minimize(VV,'Associate_Overall',max_iter_minimize,Dim,SeqExpertMapping0);
 
 

fprintf('Finish optimizing W...\n');

mupara=X(1);
sigmasquare=exp(X(2));


%% Update the Transfer Relationship Closeness:
[sender1,receiver1]=find(EdgeConn);
senderknow1=Expvectors(sender1,:);
receiverknow1=Expvectors(receiver1,:);

variablelog1=sqrt(sum((senderknow1-receiverknow1).^2,2))./sqrt(sum(senderknow1.^2,2));
normvar1=log(variablelog1);

valfij=1./variablelog1 .*exp(-(normvar1-mupara).^2./(2*sigmasquare));

sparseTRC=sparse(sender1, receiver1, valfij, size(EdgeConn,1), size(EdgeConn,2));
TRC_ij=full(sparseTRC);

posi=find(sum(EdgeConn,2));
TRCtran=EdgeConn;
TRCtran(posi,:)=TRC_ij(posi,:)./(sum(TRC_ij(posi,:),2)*ones(1,NumExperts));
%% End updating TRC_ij and TRCtran
  
[betaparanew1]=UpdateBetaPara_speedbeta_lognormal(betaparanew, uint32(ExpTransTktFile), betaindxflag, TRC_ij);
betaparanew=betaparanew1;  %% must update the beta first






