% After the first round of GMM is done, this code finds the minimum of fval.

clear;
load 'C:/Users/LoweryR/Documents/My Dropbox/UND_research_Banking/EstBank/Est/param/GMM1st_051013_I_v28.mat'
J = logical(exitflag_opt == 1);

AB = [fval_opt, x_opt, exitflag_opt];
AB_exit1 = AB(J,:);
AB_sort = sortrows(AB,1);
AB_exit1_sort = sortrows(AB_exit1,1);

% it turned out J = [];
% so choose the loweset fval one with exitflag==2.
x_initial = AB_sort(1,2:end-1);
fval_initial = AB_sort(1,1);
exit_initial = AB_sort(1,end);

lb = [0,0,-Inf,-Inf,-Inf,-Inf,-Inf,-Inf,-Inf,-Inf];
ub = Inf*ones(1,10);
AA = []; b = []; Aeq = []; beq = []; nonlcon = [];
options = optimset('TolX',10^-24,'MaxFunEvals',2500,'TolFun',10^-24,'Algorithm','interior-point');
[x,fval,exitflag] = fmincon(@param_obj_KLW,x_initial,AA,b,Aeq,beq,lb,ub,nonlcon,options);
                                        
% x and x_initial are almost the same.

x_1stGMM = x;
fval_1stGMM = fval;
exitflag_1stGMM = exitflag;
[x1_new,f1_old,f1_new,minf,x_minf] = fn_obj_KLW(x_1stGMM);
[fval_1stGMM;f1_new;minf] % check if objectives valuse are close enough.
[x_1stGMM;x1_new] % check if argmin values are close enough.

save('C:/Users/LoweryR/Documents/My Dropbox/UND_research_Banking/EstBank/Est/param/theta_GMM1st_v28.mat','x_1stGMM','fval_1stGMM','exitflag_1stGMM');