function [PredPaths,PredMean,PredEventData,KernelX,KernelY] = BVARPredictionPathsPostMode(Psi,Pi,Omega,DSGEModel,CurrINI,DPred,h,NumPaths,AnnualizeData)
% BVARPredictionPathsPostMode: Computes prediction paths of a certain length for the Bayesian VAR model using
%                              given estimates of the parameters.
%
% USAGE:
%
%       [PredPaths,PredMean,PredEventData,KernelX,KernelY] = BVARPredictionPathsPostMode(Psi,Pi,Omega,DSGEModel,CurrINI,DPred,h,NumPaths,AnnualizeData)
%
% REQUIRED INPUT:  Psi (pxq) matrix with steady state parameters.
%
%                  Pi (pxpk) matrix with the parameters on lagged enogenous variables.
%
%                  Omega (pxp) covariance matrix of the VAR residuals.
%
%                  DSGEModel (structure) with fields containing all the information about a DSGE Model for YADA.
%
%                  CurrINI (structure= with initialization information.
%
%                  DPred (matrix) of dimension qxh with data for the exogenous variables over the prediction sample.
%
%                  h (integer) with the length of the prediction sample.
%
%                  NumPaths (integer) with the number of prediction paths to compute
%
%                  AnnualizeData (boolean) that is 1 if the prediction paths should be annualized and 0 otherwise.
%
% REQUIRED OUTPUT: PredPaths (p x h x NumPaths) 3D matrix with the NumPaths possible paths for the p
%                                 endogenous variables.
%
%                  PredMean (pxh) matrix with the mean predictions at the posterior mode for the p
%                                 endogenous variables.
%
%                  PredEventData (p x 3) matrix where the first column holds the number of times
%                                 the PredPaths data satisfies the event, the second hold the number
%                                 of times the PredPaths data is greater than the event, while the
%                                 third column holds the number of times the event has been tested.
%
%                  KernelX (3D matrix) of dimension p x 2^8 x h with the x-axis values.
%
%                  KernelY (3D matrix) of dimension p x 2^8 x h with the y-axis values.
%
%
%                       Written by: Anders Warne
%                                   New Area Wide Model Project
%                                   DG-R/EMO
%                                   European Central Bank (ECB)
%                                   Email: anders.warne@ecb.europa.eu
%                                   Copyright © 2006-2009 European Central Bank.
%
%                       First version: May 8, 2007.
%                        This version: March 3, 2009.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% 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:
%
% * 10-05-2007: Updated the documentation.
%
% * 14-05-2007: Fixed a bug when constructing the "Xinit" matrix. Moreover, the vectors "DSGEModel.annual" and
%               "DSGEModel.annualscale" didn't properly take the dimension of the BVAR model into account.
%
% * 15-05-2007: Added an extra "drawnow" after shutting down the progress dialog.
%
% * 06-06-2007: Changed "predictive paths" to "prediction paths" in the title for the progress dialog.
%
% * 06-07-2007: Added an output-directory creation check.
%
% * 21-08-2007: Added the output "PredMean".
%
% * 25-10-2007: The prediction event calculations now take the "AdjustPredictionPaths" boolean variable into
%               account.
%
% * 13-11-2007: Updated the documentation.
%
% * 02-01-2008: Removed code using "DSGEModel.InitializeKalman".
%
% * 10-01-2008: Changed the last drawnow call to pause(0.02).
%
% * 23-05-2008: Updated the documentation.
%
% * 19-12-2008: Updated the documentation.
%
% * 03-03-2009: Added the "KernelX" and "KernelY" output variables.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%

%
% initialize
%
PredPaths = [];
PredMean = [];
PredEventData = [];
KernelX = [];
KernelY = [];
%
% set up the data matrices
%
p = length(DSGEModel.BVARY);
k = DSGEModel.BVARLags;
q = length(DSGEModel.BVARX);
%
% create the output directory
%
stat = MakeDir(DSGEModel.OutputDirectory,'predictions');
if stat~=1;
   txt = ['YADA was for some reason unable to create the directory "' DSGEModel.OutputDirectory '\predictions". The computation of predictive distributions has therefore been aborted.'];
   About(txt,'information','YADA - Directory Creation Problem',180,500,CurrINI);
   return;
end;
%
% Determine the sample
%
[FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%
% Determine the first observation to use when computing log-likelihood with the Kalman filter
%
KalmanFirstObservation = DSGEModel.KalmanFirstObservation;
%
% Check if we should adjust this based on k, the lag order
%
if FirstPeriod+KalmanFirstObservation-1<k+1;
   KalmanFirstObservation = k+2-FirstPeriod;
end;
%
% rewrite the VAR on VAR form
%
if k>1;
   B = [Pi;eye(p*(k-1)) zeros(p*(k-1),p)];
   J = [eye(p) zeros(p,p*(k-1))];
else;
   B = Pi;
   J = eye(p);
end;
%
% setup the initial value for Y at period T
%
T = LastPeriod-(FirstPeriod+KalmanFirstObservation-1)+1;
X_T = zeros(p*k,1);
for i=1:k;
   X_T(1+(p*(i-1)):p*i,1) = DSGEModel.Y(DSGEModel.BVARY,LastPeriod-i+1);
end;
%
% and now for the exogenous variables
%
if isempty(DSGEModel.BVARX)==0;
   d = DPred;
   dLags = zeros(q*k,1);
   for i=1:k;
      dLags(1+(q*(i-1)):q*i,:) = DSGEModel.X(DSGEModel.BVARX,LastPeriod-i+1);
   end;
   Y_T = X_T-(kron(eye(k),Psi)*dLags);
else;
   d = [];
   Y_T = X_T;
end;
%
% setup an initialization data for the endogenous variables
%
Xinit = [];
if AnnualizeData==1;
   if strcmp(DSGEModel.DataFrequency,'q')==1;
      Xinit = DSGEModel.Y(DSGEModel.BVARY,LastPeriod-2:LastPeriod);
   elseif strcmp(DSGEModel.DataFrequency,'m')==1;
      Xinit = DSGEModel.Y(DSGEModel.BVARY,LastPeriod-10:LastPeriod);
   end;
end;
%
% compute the mean predictions at the posterior mode
%
PredMean = zeros(p,h);
%
% initialize the Y-vector
%
Y = Y_T;
for i=1:h;
   %
   % update the Y-vector
   %
   Y = (B*Y);
   %
   % calculate the PredMean
   %
   if isempty(d)==0;
      PredMean(:,i) = (Psi*d(:,i))+(J*Y);
   else;
      PredMean(:,i) = J*Y;
   end;
end;
if AnnualizeData==1;
   PredMean = Annualize([Xinit PredMean],DSGEModel.annual(DSGEModel.BVARY),DSGEModel.annualscale(DSGEModel.BVARY));
end;
%
% set up the output matrix
%
PredPaths = zeros(p,h,NumPaths);
%
% and the covariance matrix
%
OmegaStMat = chol(Omega)';
%
% check if we should setup a wait handle
%
if DSGEModel.ShowProgress==1;
   ProgressStructure.title = ['Progress for ' num2str(NumPaths,'%0.0f') ' Prediction Paths'];
   ProgressStructure.facecolor = CurrINI.progress_facecolor;
   ProgressStructure.startfacecolor = CurrINI.progress_startfacecolor;
   ProgressStructure.edgecolor = CurrINI.progress_edgecolor;
   ProgressStructure.bgcolor = CurrINI.progress_bgcolor;
   ProgressStructure.stop = 0;
   ProgressStructure.clock = DSGEModel.ShowProgressClock;
   ProgressStructure.label = 'Path Number:';
   %
   ProgressStructure.name = 'BVAR Predictive Distribution - Posterior Mode';
   ProgressStructure.CurrINI = CurrINI;
   WaitHandle = ProgressDLG(0,ProgressStructure);
   set(WaitHandle,'Color',get(0,'defaultuicontrolbackgroundcolor'));
   drawnow;
end;
%
% start the iterations
%
it = 1;
abort = '';
for it=1:NumPaths
   %
   % check if we should update the progress dialog
   %
   if DSGEModel.ShowProgress==1;
      abort = get(WaitHandle,'UserData');
      if (strcmp(abort,'cancel')==1)|(strcmp(abort,'done')==1);
         PredPaths = [];
         break;
      else;
         ProgressDLG([it/NumPaths it]);
      end;
   end;
   %
   % initialize the Y-vector
   %
   Y = Y_T;
   %
   % draw the residuals
   %
   EpsilonMat = OmegaStMat*randn(p,h);
   X = zeros(p,h);
   %
   % create the path
   %
   i=1;
   for i=1:h;
      %
      % update the Y-vector
      %
      Y = (B*Y)+(J'*EpsilonMat(:,i));
      %
      % calculate the X-vector
      %
      if isempty(d)==0;
         X(:,i) = (Psi*d(:,i))+(J*Y);
      else;
         X(:,i) = J*Y;
      end;
   end;
   if AnnualizeData==0;
      PredPaths(:,:,it) = X;
   else;
      PredPaths(:,:,it) = Annualize([Xinit X],DSGEModel.annual(DSGEModel.BVARY),DSGEModel.annualscale(DSGEModel.BVARY));
   end;
   drawnow;
end;
%
% close the wait handle
%
if DSGEModel.ShowProgress==1;
   set(WaitHandle,'UserData','done');
   close(WaitHandle);
   drawnow;
   pause(0.02);
end;
if (strcmp(abort,'cancel')==0)&(DSGEModel.RunPredictionEvent==1);
   if DSGEModel.AdjustPredictionPaths==1;
      %
      % we need to fix the paths such that the mean is correct
      %
      MeanPrediction = zeros(p,h);
      for i=1:NumPaths;
         MeanPrediction = MeanPrediction+((1/NumPaths)*PredPaths(:,:,i));
      end;
      AdjustMean = PredMean-MeanPrediction;
      for i=1:NumPaths;
         PEPredPaths(:,:,i) = PredPaths(:,:,i)+AdjustMean;
      end;
   else;
      PEPredPaths = PredPaths;
   end;
   %
   % compute the prediction events results
   %
   PredEventData = CalculatePredictionEvents(PEPredPaths,DSGEModel.PredictionEvent(DSGEModel.BVARY,:));
end;
%
% check if we should compute kernel density estimates
%
if (strcmp(abort,'cancel')==0)&(NumPaths>=500);
   if DSGEModel.RunPredictionEvent==0;
      if DSGEModel.AdjustPredictionPaths==1;
         MeanPrediction = zeros(p,h);
         for i=1:NumPaths;
            MeanPrediction = MeanPrediction+((1/NumPaths)*PredPaths(:,:,i));
         end;
         AdjustMean = PredMean-MeanPrediction;
         for i=1:NumPaths;
            PEPredPaths(:,:,i) = PredPaths(:,:,i)+AdjustMean;
         end;
      else;
         PEPredPaths = PredPaths;
      end;
   end;
   %
   [KernelX,KernelY] = PredictionKernelDensity(PEPredPaths);
end;

%
% end of BVARPredictionPathsPostMode.m
%
