function PlotMargLikeChib(LogPsiDensity,LogPiDensity,NumBurnin,DSGEModel,CurrINI)
% PlotMargLikeChib: Calculates sequentially the Chib marginal likelihood identity based estimator
%                   of the log marginal likelihood in a Bayesian VAR with three groups of parameters.
%
% USAGE:
%
%       PlotMargLikeChib(LogPsiDensity,LogPiDensity,NumBurnin,DSGEModel,CurrINI)
%
% REQUIRED INPUT: LogPsiDensity (vector) of dimension NumIter with values of log p(PsiMode|Omega(j),PiMode,Data).
%                               This data is used for estimating the marginal likelihood.
%
%                 LogPiDensity (vector) of dimension NumIter with values of log p(PiMode|Psi(i),Omega(i),Data).
%                               This data is used for estimating the marginal likelihood.
%
%                 NumBurnin (integer), with the number of burn-in draws.
%
%                 DSGEModel (structure) whose fields contain all required information
%                               about the model, such as input files, variable and sample
%                               data. Actual observations are not stored in this file.
%
%                 CurrINI (structure) with initialization information.
%
%
%                       Written by: Anders Warne
%                                   New Area Wide Model Project
%                                   DG-R/EMO
%                                   European Central Bank (ECB)
%                                   Email: anders.warne@ecb.europa.eu
%                                   Copyright © 2006-2008 European Central Bank.
%
%                       First version: February 5, 2007.
%                        This version: December 19, 2008.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LICENSE INFORMATION:
%
%      YADA is free software: you can redistribute it and/or modify
%      it under the terms of the GNU General Public License as published by
%      the Free Software Foundation, either version 3 of the License, or
%      (at your option) any later version.
%
%      This program is distributed in the hope that it will be useful,
%      but WITHOUT ANY WARRANTY; without even the implied warranty of
%      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%      GNU General Public License for more details.
%
%      You should have received a copy of the GNU General Public License
%      along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%      YADA is released under the GNU General Public License, Version 3,
%      29 June 2007 <http://www.gnu.org/licenses/>. The current release of
%      the program was last modified by the ECB on the "This version" date
%      above.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CHANGELOG:
%
% * 6-2-2007:   Fixed the wait dialog.
%
% * 8-2-2007:   Removed calls to the SetLogText function.
%
% * 9-11-2007:  Updated the documentation.
%
% * 23-5-2008:  Updated the documentation.
%
% * 28-5-2008:  Changed name text on figure window.
%
% * 19-12-2008: Updated the documentation.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%

%
% Try to load the posterior mode estimates
%
ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-BVAR-' DSGEModel.NameOfModel '-' num2str(DSGEModel.PriorType,'%0.0f') '.' num2str(DSGEModel.OmegaPriorType,'%0.0f') '.mat'];
ErrorStr = '';
try;
   ModeData = load(ModeFile);
catch;
   ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
end;
if isempty(ErrorStr)==0;
   About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
   return;
end;
%
% data loaded fine
%
PsiMode = ModeData.Psi;
PiMode = ModeData.Pi;
OmegaMode = ModeData.Omega;
if isfield(ModeData,'Amatrix')==0;
   txt = 'There are missing data in the posterior mode results file for your Bayesian VAR model. Please run the posterior mode estimation routine again.';
   About(txt,'information','YADA - Bad MAT File',120,500,CurrINI);
   return;
end;
Amatrix = ModeData.Amatrix;
qDF = ModeData.qDF;
thetaPsi = ModeData.thetaPsi;
OmegaPsi = ModeData.OmegaPsi;
thetaPi = ModeData.thetaPi;
OmegaPi = ModeData.OmegaPi;
x = ModeData.x;
X = ModeData.X;
d = ModeData.d;
dLag = ModeData.dLag;
T = size(x,2);
%
% locate the controls structure
%
maingui = findobj('Type','figure','Tag','YADA');
controls = get(maingui,'UserData');
%
% Collect the number of lags and number of variables
%
p = length(DSGEModel.BVARY);
k = DSGEModel.BVARLags;
q = length(DSGEModel.BVARX);
%
% Number of posterior draws
%
DrawsStr = get(controls.posterior.draws,'String');
NumPostDraws = str2num(StringTrim(strrep(DrawsStr(DSGEModel.PosteriorDrawsValue,:),',','')));
%
% sequential marginal likelihood start value and step length
%
SeqStartStr = get(controls.dsge.sequentialstart,'String');
DSGEModel.SequentialStartIterationValue = str2num(strrep(StringTrim(SeqStartStr(DSGEModel.SequentialStartIteration,:)),',',''));
SeqStepStr = get(controls.dsge.sequentialstep,'String');
DSGEModel.SequentialStepLengthValue = str2num(strrep(StringTrim(SeqStepStr(DSGEModel.SequentialStepLength,:)),',',''));
%
% compute the value of the log posterior
%
if DSGEModel.PriorType==1;
   %
   % Minnesota-style prior on Pi
   %
   df = T+qDF;
   %
   % compute the value of the log likelihood + the log prior at the posterior mode
   %
   LogPosterior = BVARLogPosteriorMinnesota(OmegaMode,PiMode,PsiMode,Amatrix,qDF,thetaPsi,OmegaPsi,thetaPi,OmegaPi,x,X,d,dLag);
   %
   % Calculate the log of the full conditional posterior of Omega at the mode
   %
   LogOmegaDensity = logInverseWishartPDF(OmegaMode,(df+p+1)*BVAROmegaMinnesota(PiMode,PsiMode,Amatrix,qDF,x,X,d,dLag),df);
elseif DSGEModel.PriorType==2;
   %
   % Normal conditional on covariance matrix on Pi
   %
   invOmegaPi = inv(OmegaPi);
   ThetaPi = reshape(thetaPi,p,p*k);
   df = T+qDF+(p*k);
   %
   % compute the value of the log likelihood + the log prior at the posterior mode
   %
   LogPosterior = BVARLogPosteriorNormalCond(OmegaMode,PiMode,PsiMode,Amatrix,qDF,thetaPsi,OmegaPsi,ThetaPi,OmegaPi,x,X,d,dLag);
   %
   % Calculate the log of the full conditional posterior of Omega at the mode
   %
   LogOmegaDensity = logInverseWishartPDF(OmegaMode,(df+p+1)*BVAROmegaNormal(PiMode,PsiMode,Amatrix,qDF,ThetaPi,invOmegaPi,x,X,d,dLag),df);
else;
   %
   % diffuse prior on Pi
   %
   df = T+qDF;
   %
   % compute the value of the log likelihood + the log prior at the posterior mode
   %
   LogPosterior = BVARLogPosteriorDiffuse(OmegaMode,PiMode,PsiMode,Amatrix,qDF,thetaPsi,OmegaPsi,x,X,d,dLag);
   %
   % Calculate the log of the full conditional posterior of Omega at the mode
   %
   LogOmegaDensity = logInverseWishartPDF(OmegaMode,(df+p+1)*BVAROmegaMinnesota(PiMode,PsiMode,Amatrix,qDF,x,X,d,dLag),df);
end;
%
% Open up a wait dialog.
%
txt = ['Please wait while YADA computes Chib''s marginal likelihood identity based estimator of the log marginal likelihood. Estimation started at: ' StringTrim(datestr(now,14)) '. This will take some time!'];
WaitHandle = WaitDLG(txt,'information','Sequential Marginal Likelihood',500,150,CurrINI,1);
WaitControls = get(WaitHandle,'UserData');
%
LogMargs = MargLikeChib(LogPiDensity,LogPsiDensity,LogPosterior,LogOmegaDensity,q,NumBurnin,1,DSGEModel.SequentialStartIterationValue,DSGEModel.SequentialStepLengthValue,WaitControls.cancel);
%
% shut down the wait dialog
%
set(WaitControls.text,'UserData','done');
delete(WaitHandle);
drawnow;
pause(0.02);
%
GraphDirectory = [DSGEModel.OutputDirectory '\graphs'];
if isempty(LogMargs)==0;
   FigHandle =figure('Visible','off', ...
          'Position',[(CurrINI.scrsz(3)-700)/2 (CurrINI.scrsz(4)-500)/2 700 500], ...
          'Tag','MargLikeChib', ...
          'Name','Sequential Marginal Likelihood - Chib');
   %
   SetFigureProperties(FigHandle,CurrINI);
   %
   Xvalues = LogMargs(:,1)+NumBurnin;
   Yvalues = LogMargs(:,2);
   %
   plot(Xvalues,Yvalues,'LineStyle','-','Color',[0.75 0 0],'LineWidth',2,'Marker','.');
   hold('off');
   SetAxesFonts(CurrINI,'Title','Chib estimator','XLabel',['Gibbs draw number (with ' num2str(NumBurnin,'%0.0f') ' burn-in draws)'],'YLabel','Log marginal likelihood');
   axis('tight');
   %
   % check the YLim
   %
   ylim = get(gca,'YLim');
   add_on = 0.1*(ylim(2)-ylim(1));
   ylim = [ylim(1)-add_on ylim(2)+add_on];
   set(gca,'YLim',ylim);
   %
   % save the grasph
   %
   if DirExist(GraphDirectory);
      file = [GraphDirectory '\LogMarginalLikelihood-BVAR-Chib-' num2str(DSGEModel.PriorType,'%0.0f') '.' num2str(DSGEModel.OmegaPriorType,'%0.0f') '-' num2str(NumPostDraws,'%0.0f') '.fig'];
      saveas(FigHandle,file);
   end;
   %
   % display the graph
   %
   SetToolbarImages(FigHandle,CurrINI.images);
   set(FigHandle,'Visible','on','CloseRequestFcn','delete(gcf); drawnow; pause(0.02);');
   drawnow;
   pause(0.02);
end;

%
% end of PlotMargLikeChib.m
%
