function [fval,info,exit_flag,grad,hess,model_solution] = dsge_var_likelihood(xparam1,dataset_,dataset_info,options_,M_,estim_params_,Prior,BoundsInfo,dr, endo_steady_state, exo_steady_state, exo_det_steady_state, ~, measurement_info)
% Evaluates the posterior kernel of the BVAR-DSGE model.
%
% INPUTS
%   o xparam1               [double]    Vector of model's parameters.
%   o dataset_              [dseries]   object storing the dataset
%   o dataset_info          [structure] storing information about the sample.
%   o options_              [structure] describing the options
%   o M_                    [structure] describing the model
%   o estim_params_         [structure] characterizing parameters to be estimated
%   o Prior                 [@dprior]   prior information object
%   o BoundsInfo            [structure] containing prior bounds
%   o dr                    [structure] Reduced form model.
%   o endo_steady_state     [vector]    steady state value for endogenous variables
%   o exo_steady_state      [vector]    steady state value for exogenous variables
%   o exo_det_steady_state  [vector]    steady state value for exogenous deterministic variables
%
% OUTPUTS
%   o fval              [double]     Value of the posterior kernel at xparam1.
%   o info              [integer]    Vector of information about the penalty.
%   o exit_flag         [integer]    Zero if the function returns a penalty, one otherwise.
%   o grad              [double]     place holder for gradient of the likelihood
%                                    currently not supported by dsge_var
%   o hess              [double]     place holder for Hessian matrix of the likelihood
%                                    currently not supported by dsge_var
%   o model_solution    [struct]     Structure containing the model solution at the current parameter
%                                    values with fields: ys, trend_coeff, and the M_ fields set by
%                                    set_all_parameters (params, Sigma_e, Correlation_matrix, H,
%                                    Correlation_matrix_ME, Skew_e, endo_initial_state_values, csn),
%                                    plus DSGE-VAR specific fields:
%                                    - PHI_tilde: Stacked BVAR-DSGE autoregressive matrices, formula (28), DS (2004)
%                                    - SIGMA_u_tilde: Covariance matrix of the BVAR-DSGE, formula (29), DS (2004)
%                                    - iXX: inv(lambda*T*Gamma_XX^*+ X'*X)
%                                    - prior: structure with SIGMA_u_star, PHI_star, ArtificialSampleSize, DF, iGXX_star
%
% ALGORITHMS
%   Follows the computations outlined in Del Negro/Schorfheide (2004):
%   Priors from general equilibrium models for VARs, International Economic
%   Review, 45(2), pp. 643-673
%
% SPECIAL REQUIREMENTS
%   None.

% Copyright © 2006-2025 Dynare Team
%
% This file is part of Dynare.
%
% Dynare 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.
%
% Dynare 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 Dynare.  If not, see <https://www.gnu.org/licenses/>.

if nargin < 15 || isempty(measurement_info)
    measurement_info = set_measurement_info(M_, dr, options_);
end

% Initialize some of the output arguments.
fval = [];
exit_flag = 1;
grad=[];
hess=[];
info = zeros(4,1);
PHI_tilde = [];
SIGMA_u_tilde = [];
iXX = [];
prior = [];
trend_coeff=[];
model_solution = [];

% Ensure that xparam1 is a column vector.
% (Don't do the transformation if xparam1 is empty, otherwise it would become a
%  0×1 matrix, which create issues with older MATLABs when comparing with [] in
%  check_bounds_and_definiteness_estimation)
if ~isempty(xparam1)
    xparam1 = xparam1(:);
end

% Initialization of of the index for parameter dsge_prior_weight in M_.params.
dsge_prior_weight_idx = strmatch('dsge_prior_weight', M_.param_names,'exact');

% Get the number of observed variables in the VAR model.
NumberOfObservedVariables = dataset_.vobs;

% Get the number of observations.
NumberOfObservations = dataset_.nobs;


% Get the number of lags in the VAR model.
NumberOfLags = options_.dsge_varlag;

% Get the number of parameters in the VAR model.
NumberOfParameters = NumberOfObservedVariables*NumberOfLags ;
if ~options_.noconstant
    NumberOfParameters = NumberOfParameters + 1;
end

% Get empirical second order moments for the observed variables.
mYY= dataset_info.mYY;
mYX= dataset_info.mYX;
mXX= dataset_info.mXX;

M_ = set_all_parameters(xparam1,estim_params_,M_);

[fval,info,exit_flag,Q]=check_bounds_and_definiteness_estimation(xparam1, M_, estim_params_, BoundsInfo);
if info(1)
    return
end

% Get the weight of the DSGE prior.
dsge_prior_weight = M_.params(dsge_prior_weight_idx);

% Is the DSGE prior proper?
if dsge_prior_weight<(NumberOfParameters+NumberOfObservedVariables)/NumberOfObservations
    fval = Inf;
    exit_flag = 0;
    info(1) = 51;
    info(2)=dsge_prior_weight;
    info(3)=(NumberOfParameters+NumberOfObservedVariables)/dataset_.nobs;
    info(4)=abs(NumberOfObservations*dsge_prior_weight-(NumberOfParameters+NumberOfObservedVariables));
    return
end

%------------------------------------------------------------------------------
% 2. call model setup & reduction program
%------------------------------------------------------------------------------

% Solve the DSGE model and get the matrices of the reduced form solution. T and R are the matrices of the
% state equation
[T,R,SteadyState,info] = dynare_resolve(M_,options_, dr, endo_steady_state, exo_steady_state, exo_det_steady_state,'restrict');

% Return, with endogenous penalty when possible, if dynare_resolve issues an error code (defined in resol).
if info(1)
    if info(1) == 3 || info(1) == 4 || info(1) == 5 || info(1)==6 ||info(1) == 19 ||...
                info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ...
                info(1) == 81 || info(1) == 84 ||  info(1) == 85
        %meaningful second entry of output that can be used
        fval = Inf;
        if ~isfinite(info(2))
            info(4) = 0.1;
        else
            info(4) = info(2);
        end
        exit_flag = 0;
        return
    else
        fval = Inf;
        info(4) = 0.1;
        exit_flag = 0;
        return
    end
end

% Define the mean/steady state vector.
if ~options_.noconstant
    if options_.loglinear
        constant = transpose(log(SteadyState(measurement_info.mfys)));
    else
        constant = transpose(SteadyState(measurement_info.mfys));
    end
else
    constant = zeros(1,NumberOfObservedVariables);
end


%------------------------------------------------------------------------------
% 3. theoretical moments (second order)
%------------------------------------------------------------------------------

% Compute the theoretical second order moments
tmp0 = lyapunov_symm(T,R*Q*R',options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold, [], options_.debug);
mf  = measurement_info.mf1;

% Get the non centered second order moments
TheoreticalAutoCovarianceOfTheObservedVariables = zeros(NumberOfObservedVariables,NumberOfObservedVariables,NumberOfLags+1);
TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1) = tmp0(mf,mf)+constant'*constant;
for lag = 1:NumberOfLags
    tmp0 = T*tmp0;
    TheoreticalAutoCovarianceOfTheObservedVariables(:,:,lag+1) = tmp0(mf,mf) + constant'*constant;
end

% Build the theoretical "covariance" between Y and X
GYX = zeros(NumberOfObservedVariables,NumberOfParameters);
for i=1:NumberOfLags
    GYX(:,(i-1)*NumberOfObservedVariables+1:i*NumberOfObservedVariables) = TheoreticalAutoCovarianceOfTheObservedVariables(:,:,i+1);
end
if ~options_.noconstant
    GYX(:,end) = constant';
end

% Build the theoretical "covariance" between X and X
GXX = kron(eye(NumberOfLags), TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1));
for i = 1:NumberOfLags-1
    tmp1 = diag(ones(NumberOfLags-i,1),i);
    tmp2 = diag(ones(NumberOfLags-i,1),-i);
    GXX = GXX + kron(tmp1,TheoreticalAutoCovarianceOfTheObservedVariables(:,:,i+1));
    GXX = GXX + kron(tmp2,TheoreticalAutoCovarianceOfTheObservedVariables(:,:,i+1)');
end

if ~options_.noconstant
    % Add one row and one column to GXX
    GXX = [GXX , kron(ones(NumberOfLags,1),constant') ; [  kron(ones(1,NumberOfLags),constant) , 1] ];
end

GYY = TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1);

iGXX = inv(GXX);
PHI_star = iGXX*transpose(GYX); %formula (22), DS (2004)
SIGMA_u_star=GYY - GYX*PHI_star; %formula (23), DS (2004)
[SIGMA_u_star_is_positive_definite, penalty] = ispd(SIGMA_u_star);
if ~SIGMA_u_star_is_positive_definite
    fval = Inf;
    info(1) = 53;
    info(4) = penalty;
    exit_flag = 0;
    return
end

if ~isinf(dsge_prior_weight)% Evaluation of the likelihood of the DSGE-VAR model when the DSGE prior weight is finite.
    tmp0 = dsge_prior_weight*NumberOfObservations*TheoreticalAutoCovarianceOfTheObservedVariables(:,:,1) + mYY ;  %first term of square bracket in formula (29), DS (2004)
    tmp1 = dsge_prior_weight*NumberOfObservations*GYX + mYX;        %first element of second term of square bracket in formula (29), DS (2004)
    tmp2 = inv(dsge_prior_weight*NumberOfObservations*GXX+mXX);     %middle element of second term of square bracket in formula (29), DS (2004)
    SIGMA_u_tilde = tmp0 - tmp1*tmp2*tmp1';                               %square bracket term in formula (29), DS (2004)
    clear('tmp0');
    [SIGMAu_is_positive_definite, penalty] = ispd(SIGMA_u_tilde);
    if ~SIGMAu_is_positive_definite
        fval = Inf;
        info(1) = 52;
        info(4) = penalty;
        exit_flag = 0;
        return
    end
    SIGMA_u_tilde = SIGMA_u_tilde / (NumberOfObservations*(1+dsge_prior_weight));   %prefactor of formula (29), DS (2004)
    PHI_tilde = tmp2*tmp1';                                                   %formula (28), DS (2004)
    clear('tmp1');
    prodlng1 = sum(gammaln(.5*((1+dsge_prior_weight)*NumberOfObservations- ...
                               NumberOfParameters ...
                               +1-(1:NumberOfObservedVariables)')));    %last term in numerator of third line of (A.2), DS (2004)
    prodlng2 = sum(gammaln(.5*(dsge_prior_weight*NumberOfObservations- ...
                               NumberOfParameters ...
                               +1-(1:NumberOfObservedVariables)')));    %last term in denominator of third line of (A.2), DS (2004)
                                                                        %Compute minus log likelihood according to (A.2), DS (2004)
    lik = .5*NumberOfObservedVariables*log(det(dsge_prior_weight*NumberOfObservations*GXX+mXX)) ... %first term in numerator of second line of (A.2), DS (2004)
          + .5*((dsge_prior_weight+1)*NumberOfObservations-NumberOfParameters)*log(det((dsge_prior_weight+1)*NumberOfObservations*SIGMA_u_tilde)) ... %second term in numerator of second line of (A.2), DS (2004)
          - .5*NumberOfObservedVariables*log(det(dsge_prior_weight*NumberOfObservations*GXX)) ... %first term in denominator of second line of (A.2), DS (2004)
          - .5*(dsge_prior_weight*NumberOfObservations-NumberOfParameters)*log(det(dsge_prior_weight*NumberOfObservations*SIGMA_u_star)) ... %second term in denominator of second line of (A.2), DS (2004)
          + .5*NumberOfObservedVariables*NumberOfObservations*log(2*pi)  ... %first term in numerator of third line of (A.2), DS (2004)
          - .5*log(2)*NumberOfObservedVariables*((dsge_prior_weight+1)*NumberOfObservations-NumberOfParameters) ... %second term in numerator of third line of (A.2), DS (2004)
          + .5*log(2)*NumberOfObservedVariables*(dsge_prior_weight*NumberOfObservations-NumberOfParameters) ... %first term in denominator of third line of (A.2), DS (2004)
          - prodlng1 + prodlng2;
else% Evaluation of the likelihood of the dsge-var model when the dsge prior weight is infinite.
    PHI_star = iGXX*transpose(GYX);
    %Compute minus log likelihood according to (33), DS (2004) (where the last term in the trace operator has been multiplied out)
    lik = NumberOfObservations * ( log(det(SIGMA_u_star)) + NumberOfObservedVariables*log(2*pi) +  ...
                                   trace(inv(SIGMA_u_star)*(mYY - transpose(mYX*PHI_star) - mYX*PHI_star + transpose(PHI_star)*mXX*PHI_star)/NumberOfObservations));
    lik = .5*lik;% Minus likelihood
    SIGMA_u_tilde=SIGMA_u_star;
    PHI_tilde=PHI_star;
end

if isinf(lik)
    fval = Inf; info(1) = 50; info(4) = 0.1; exit_flag = 0;
    return
end
if isnan(lik)
    fval = Inf; info(1) = 45; info(4) = 0.1; exit_flag = 0;
    return
end
if imag(lik)~=0
    fval = Inf; info(1) = 46; info(4) = 0.1; exit_flag = 0;
    return
end

% Add the (logged) prior density for the dsge-parameters.
lnprior = Prior.density(xparam1);
if isinf(lnprior)
    fval = Inf; info(1) = 40; info(4) = 0.1; exit_flag = 0;
    return
end
if isnan(lnprior)
    fval = Inf; info(1) = 47; info(4) = 0.1; exit_flag = 0;
    return
end
if imag(lnprior)~=0
    fval = Inf; info(1) = 48; info(4) = 0.1; exit_flag = 0;
    return
end

fval = (lik-lnprior);

if nargout >= 6
    if isinf(dsge_prior_weight)
        iXX = iGXX;
    else
        iXX = tmp2;
    end
    prior.SIGMA_u_star = SIGMA_u_star;
    prior.PHI_star = PHI_star;
    prior.ArtificialSampleSize = fix(dsge_prior_weight*NumberOfObservations);
    prior.DF = prior.ArtificialSampleSize - NumberOfParameters - NumberOfObservedVariables;
    prior.iGXX_star = iGXX;
    model_solution.ys = SteadyState;
    model_solution.trend_coeff = trend_coeff;
    model_solution.params = M_.params;
    model_solution.Sigma_e = M_.Sigma_e;
    model_solution.Correlation_matrix = M_.Correlation_matrix;
    model_solution.H = M_.H;
    model_solution.Correlation_matrix_ME = M_.Correlation_matrix_ME;
    model_solution.Skew_e = M_.Skew_e;
    if isfield(M_,'endo_initial_state')
        model_solution.endo_initial_state_values = M_.endo_initial_state.values;
    end
    if isfield(M_,'csn')
        model_solution.csn = M_.csn;
    end
    model_solution.PHI_tilde = PHI_tilde;
    model_solution.SIGMA_u_tilde = SIGMA_u_tilde;
    model_solution.iXX = iXX;
    model_solution.prior = prior;
end
