function [fval,info,exit_flag,DLIK,Hess,model_solution] = dsge_likelihood(xparam1,dataset_,dataset_info,options_,M_,estim_params_,Prior,BoundsInfo,dr, endo_steady_state, exo_steady_state, exo_det_steady_state,smoother_info,derivatives_info,measurement_info)
% Evaluates the negative of the posterior kernel of a DSGE model using the specified
% kalman_algo; the resulting posterior includes the 2*pi constant of the
% likelihood function
%
% INPUTS
% - xparam1             [double]        current values for the estimated parameters.
% - dataset_            [structure]     dataset after transformations
% - dataset_info        [structure]     storing information about the sample
% - options_            [structure]     MATLAB's structure describing the current options
% - M_                  [structure]     MATLAB's structure describing the model
% - estim_params_       [structure]     characterizing parameters to be estimated
% - Prior               [@dprior]       prior information object
% - BoundsInfo          [structure]     containing prior bounds
% - dr                  [structure]     Reduced form model.
% - endo_steady_state   [vector]        steady state value for endogenous variables
% - exo_steady_state    [vector]        steady state value for exogenous variables
% - exo_det_steady_state [vector]       steady state value for exogenous deterministic variables
% - derivatives_info    [structure]     derivative info for identification
%
% OUTPUTS
% - fval                    [double]        scalar, value of minus the likelihood or posterior kernel.
% - info                    [integer]       4×1 vector, information on whether solution and likelihood could be computed
% - exit_flag               [integer]       scalar, equal to 1 (no issues when evaluating the likelihood) or 0 (not able to evaluate the likelihood).
% - DLIK                    [double]        Vector with score of the likelihood
% - Hess                    [double]        asymptotic Hessian matrix.
% - model_solution          [struct]        Structure containing the model solution at the current parameter
%                                           values with fields: dr, ys, trend_coeff, mf, 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).
%
% This function is called by: dynare_estimation_1, mode_check,
% initial_estimation_checks, hessian, mr_hessian, hssmc, dime, dsmh,
% calibrate_mh_scale_parameter, posterior_sampler_initialization,
% identification.analysis, TaRB_optimizer_wrapper,
% posterior_sampler_iteration, slice_sampler, tempered_likelihood
% This function calls: dynare_resolve, lyapunov_symm, lyapunov_solver, compute_Pinf_Pstar, kalman_filter_d, missing_observations_kalman_filter_d,
% univariate_kalman_filter_d, kalman_steady_state, get_perturbation_params_deriv, kalman_filter, missing_observations_kalman_filter, univariate_kalman_filter

% Copyright © 2004-2026 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/>.

% Initial author: stephane DOT adjemian AT univ DASH lemans DOT FR

% Initialization of the returned variables and others...
if nargin < 15 || isempty(measurement_info)
    measurement_info = set_measurement_info(M_, dr, options_);
end

fval        = [];
SteadyState = [];
trend_coeff = [];
model_solution = [];
exit_flag   = 1;
info        = zeros(4,1);

if options_.analytic_derivation
    DLIK        = NaN(1,length(xparam1));
else
    DLIK        = [];
end
Hess        = [];

% 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

% Set flag related to analytical derivatives.
analytic_derivation = options_.analytic_derivation;
analytic_Hessian = options_.analytic_Hessian;

if analytic_derivation
    if options_.loglinear
        error('The analytic_derivation and loglinear options are not compatible')
    end
    if options_.endogenous_prior
        error('The analytic_derivation and endogenous_prior options are not compatible')
    end
end

if nargout==1
    analytic_derivation = false;
    analytic_Hessian = '';
end

%------------------------------------------------------------------------------
% 1. Get the structural parameters & define penalties
%------------------------------------------------------------------------------
M_ = set_all_parameters(xparam1,estim_params_,M_);

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

%------------------------------------------------------------------------------
% 2. call model setup & reduction program
%------------------------------------------------------------------------------
is_restrict_state_space = true;
if options_.occbin.likelihood.status
    [occbin_options, options_.occbin.filter.state_covariance] = set_occbin_options(options_);
    if occbin_options.opts_simul.restrict_state_space
        [T,R,SteadyState,info,dr, M_.params,TTx,RRx,CCx, T0, R0] = ...
            occbin.dynare_resolve(M_,options_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state,[],'restrict');
    else
        is_restrict_state_space = false;
        oldoo.restrict_var_list = dr.restrict_var_list;
        oldoo.restrict_columns = dr.restrict_columns;
        dr.restrict_var_list = smoother_info.var_list;
        dr.restrict_columns = smoother_info.restrict_columns;

        % Linearize the model around the deterministic steady state and extract the matrices of the state equation (T and R).
        [T,R,SteadyState,info,dr, M_.params,TTx,RRx,CCx, T0, R0] = ...
            occbin.dynare_resolve(M_,options_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state);

        dr.restrict_var_list = oldoo.restrict_var_list;
        dr.restrict_columns = oldoo.restrict_columns;

    end
    occbin_.status = true;
    occbin_.info= {options_, dr,endo_steady_state,exo_steady_state,exo_det_steady_state, M_, occbin_options, TTx, RRx, CCx,T0,R0};
else
    % Linearize the model around the deterministic steady state and extract the matrices of the state equation (T and R).
    if options_.kalman_algo == 5 % pruned skewed Kalman filter
        is_restrict_state_space = false;
        [T,R,SteadyState,info,dr, M_.params] = dynare_resolve(M_,options_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
    else
        [T,R,SteadyState,info,dr, M_.params] = dynare_resolve(M_,options_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state,'restrict');
    end
    occbin_.status = false;
end

% 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 ||  info(1) == 86 || ...
                info(1) == 401 || info(1) == 402 || info(1) == 403 || ... %cycle reduction
                info(1) == 411 || info(1) == 412 || info(1) == 413 % logarithmic reduction
        %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;
        if analytic_derivation
            DLIK=ones(length(xparam1),1);
        end
        return
    else
        fval = Inf;
        info(4) = 0.1;
        exit_flag = 0;
        if analytic_derivation
            DLIK=ones(length(xparam1),1);
        end
        return
    end
end

% check endogenous prior restrictions
info=endogenous_prior_restrictions(T,R,M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
if info(1)
    fval = Inf;
    if ~isfinite(info(2))
        info(4) = 0.1;
    else
        info(4) = info(2);
    end
    exit_flag = 0;
    if analytic_derivation
        DLIK=ones(length(xparam1),1);
    end
    return
end

if is_restrict_state_space
%% Define a vector of indices for the observed variables
    mf = measurement_info.mf1;
else
%get location of observed variables and requested smoothed variables in
%decision rules
    mf = smoother_info.var_list(smoother_info.mf);
end

% Define the constant vector of the measurement equation.
if options_.noconstant
    constant = zeros(dataset_.vobs,1);
else
    if options_.loglinear
        constant = log(SteadyState(measurement_info.mfys));
    else
        constant = SteadyState(measurement_info.mfys);
    end
end

% Define the deterministic linear trend of the measurement equation.
if M_.with_trend
    [trend_addition, trend_coeff]=compute_trend_coefficients(M_,options_,dataset_.vobs,dataset_.nobs);
    trend = repmat(constant,1,dataset_.nobs)+trend_addition;
else
    trend_coeff = zeros(dataset_.vobs,1);
    trend = repmat(constant,1,dataset_.nobs);
end

% Get needed information for Kalman filter routines.
start = options_.presample+1;
Z = mf;           %selector for observed variables
no_missing_data_flag = ~dataset_info.missing.state;
mm = length(T);             %number of states
pp = dataset_.vobs;    %number of observables
rr = length(Q);             %number of shocks
kalman_tol = options_.kalman_tol;
diffuse_kalman_tol = options_.diffuse_kalman_tol;
riccati_tol = options_.riccati_tol;
Y = transpose(dataset_.data)-trend;
smpl = size(Y,2);

%------------------------------------------------------------------------------
% 3. Initial condition of the Kalman filter
%------------------------------------------------------------------------------
kalman_algo = options_.kalman_algo;


diffuse_periods = 0;
expanded_state_vector_for_univariate_filter=0;
singular_diffuse_filter = 0;
if options_.heteroskedastic_filter
    Qvec=get_Qvec_heteroskedastic_filter(Q,smpl,M_);
end

switch options_.lik_init
  case 1% Standard initialization with the steady state of the state equation.
    if (kalman_algo~=2) && (kalman_algo~=5)
        % Use standard Kalman filter except if the univariate filter or pruned skewed filter is explicitly chosen.
        kalman_algo = 1;
    end
    Pstar=lyapunov_solver(T,R,Q,options_);
    a     = zeros(mm,1);
    a=set_Kalman_starting_values(a,M_,dr,options_);
    a_0_given_tm1=T*a; %set state prediction for first Kalman step;

    if options_.occbin.likelihood.status || (kalman_algo == 5)
        Z =zeros(length(mf),size(T,1));
        for i = 1:length(mf)
            Z(i,mf(i))=1;
        end
        Zflag = 1;
    else
        Zflag = 0;
    end
  case 2% Initialization with large numbers on the diagonal of the covariance matrix of the states (for non stationary models).
    if (kalman_algo~=2) && (kalman_algo~=5)
        % Use standard Kalman filter except if the univariate filter or pruned skewed filter is explicitly chosen.
        kalman_algo = 1;
    end
    Pstar = options_.Harvey_scale_factor*eye(mm);
    a     = zeros(mm,1);
    a = set_Kalman_starting_values(a,M_,dr,options_);
    a_0_given_tm0 = a;
    if not(options_.occbin.likelihood.status && options_.occbin.likelihood.first_period_occbin_update==1)
        a_0_given_tm1 = T*a; %set state prediction for first Kalman step;
        if options_.Harvey_scale_factor==0
            Pstar = T*Pstar*T' + R*Q*R';
        end
    else
        a_0_given_tm1 = a;
    end
    if options_.occbin.likelihood.status || (kalman_algo == 5)
        Z =zeros(length(mf),size(T,1));
        for i = 1:length(mf)
            Z(i,mf(i))=1;
        end
        Zflag = 1;
    else
        Zflag = 0;
    end
  case 3% Diffuse Kalman filter (Durbin and Koopman)
    % Use standard Kalman filter except if the univariate filter is explicitly chosen.
    if kalman_algo == 0
        kalman_algo = 3;
    elseif ~( (kalman_algo==3) || (kalman_algo==4) )
        error(['The model requires Diffuse filter, but you specified a different Kalman filter. You must set options_.kalman_algo ' ...
               'to 0 (default), 3 or 4'])
    end
    if is_restrict_state_space
        [Pstar,Pinf] = compute_Pinf_Pstar(Z,T,R,Q,options_.qz_criterium, dr.restrict_columns);
    else
        [Pstar,Pinf] = compute_Pinf_Pstar(Z,T,R,Q,options_.qz_criterium);
    end
    Z =zeros(length(mf),size(T,1));
    for i = 1:length(mf)
        Z(i,mf(i))=1;
    end
    Zflag = 1;
    if options_.heteroskedastic_filter
        QQ=Qvec;
    else
        QQ=Q;
    end
    % Run diffuse Kalman filter on first periods.
    if (kalman_algo==3)
        % Multivariate Diffuse Kalman Filter
        a = zeros(mm,1);
        a = set_Kalman_starting_values(a,M_,dr,options_);
        a_0_given_tm1 = T*a; %set state prediction for first Kalman step;
        Pstar0 = Pstar; % store Pstar
        if no_missing_data_flag
            [dLIK,dlik,a_0_given_tm1,Pstar] = kalman_filter_d(Y, 1, size(Y,2), ...
                                                  a_0_given_tm1, Pinf, Pstar, ...
                                                  kalman_tol, diffuse_kalman_tol, options_.presample, ...
                                                  T,R,QQ,H,Z,pp);
        else
            [dLIK,dlik,a_0_given_tm1,Pstar] = missing_observations_kalman_filter_d(dataset_info.missing.aindex,dataset_info.missing.number_of_observations,dataset_info.missing.no_more_missing_observations, ...
                                                              Y, 1, size(Y,2), ...
                                                              a_0_given_tm1, Pinf, Pstar, ...
                                                              kalman_tol, diffuse_kalman_tol, riccati_tol, options_.presample, ...
                                                              T,R,QQ,H,Z,mm,pp,rr);
        end
        diffuse_periods = length(dlik);
        if isinf(dLIK)
            % Go to univariate diffuse filter if singularity problem.
            singular_diffuse_filter = 1;
            Pstar = Pstar0;
        end
    end
    if singular_diffuse_filter || (kalman_algo==4)
        % Univariate Diffuse Kalman Filter
        if isequal(H,0)
            H1 = zeros(pp,1);
            mmm = mm;
        else
            if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
                H1 = diag(H);
                mmm = mm;
            else
                %Augment state vector (follows Section 6.4.3 of DK (2012))
                expanded_state_vector_for_univariate_filter=1;
                if Zflag
                    Z1=Z;
                else
                    Z1=zeros(pp,size(T,2));
                    for jz=1:length(Z)
                        Z1(jz,Z(jz))=1;
                    end
                end
                Z = [Z1, eye(pp)];
                Zflag=1;
                T = blkdiag(T,zeros(pp));
                Q = blkdiag(Q,H);
                R = blkdiag(R,eye(pp));
                Pstar = blkdiag(Pstar,H);
                Pinf  = blkdiag(Pinf,zeros(pp));
                H1 = zeros(pp,1);
                mmm   = mm+pp;
                if options_.heteroskedastic_filter
                    clear QQ
                    for kv=1:size(Qvec,3)
                        QQ(:,:,kv) = blkdiag(Qvec(:,:,kv),H);
                    end
                    Qvec=QQ;
                else
                    QQ = Q;
                end
            end
        end

        a = zeros(mmm,1);
        a = set_Kalman_starting_values(a,M_,dr,options_);
        a_0_given_tm1 = T*a;
        [dLIK,dlik,a_0_given_tm1,Pstar] = univariate_kalman_filter_d(dataset_info.missing.aindex,...
                                                         Y, 1, size(Y,2), ...
                                                         a_0_given_tm1, Pinf, Pstar, ...
                                                         kalman_tol, diffuse_kalman_tol, options_.presample, ...
                                                         T,R,QQ,H1,Z,pp);
        diffuse_periods = size(dlik,1);
    end
    if isnan(dLIK)
        fval = Inf;
        info(1) = 45;
        info(4) = 0.1;
        exit_flag = 0;
        return
    end

  case 4% Start from the solution of the Riccati equation.
    if (kalman_algo~=2) && (kalman_algo~=5)
        % Use standard Kalman filter except if the univariate filter or pruned skewed filter is explicitly chosen.
        kalman_algo = 1;
    end
    try
        if isequal(H,0)
            Pstar = kalman_steady_state(transpose(T),R*Q*transpose(R),transpose(build_selection_matrix(Z,mm,length(Z))));
        else
            Pstar = kalman_steady_state(transpose(T),R*Q*transpose(R),transpose(build_selection_matrix(Z,mm,length(Z))),H);
        end
    catch ME
        disp(ME.message)
        disp('dsge_likelihood:: I am not able to solve the Riccati equation, so I switch to lik_init=1!');
        options_.lik_init = 1;
        Pstar=lyapunov_solver(T,R,Q,options_);
    end
    a     = zeros(mm,1);
    a = set_Kalman_starting_values(a,M_,dr,options_);
    a_0_given_tm1 = T*a;
    if options_.occbin.likelihood.status || (kalman_algo == 5)
        Z =zeros(length(mf),size(T,1));
        for i = 1:length(mf)
            Z(i,mf(i))=1;
        end
        Zflag = 1;
    else
        Zflag = 0;
    end
  case 5            % Old diffuse Kalman filter only for the non stationary variables
    [eigenvect, eigenv] = eig(T);
    eigenv = diag(eigenv);
    nstable = length(find(abs(abs(eigenv)-1) > 1e-7));
    V = eigenvect(:,abs(abs(eigenv)-1) < 1e-7);
    stable = find(sum(abs(V),2)<1e-5);
    nunit = length(eigenv) - nstable;
    Pstar = options_.Harvey_scale_factor*eye(nunit);
    if (kalman_algo~=2) && (kalman_algo~=5)
        % Use standard Kalman filter except if the univariate filter or pruned skewed filter is explicitly chosen.
        kalman_algo = 1;
    end
    R_tmp = R(stable, :);
    T_tmp = T(stable,stable);
    Pstar_tmp=lyapunov_solver(T_tmp,R_tmp,Q,options_);
    Pstar(stable, stable) = Pstar_tmp;
    a = zeros(mm,1);
    a = set_Kalman_starting_values(a,M_,dr,options_);
    a_0_given_tm1 = T*a;
    if options_.occbin.likelihood.status || (kalman_algo == 5)
        Z =zeros(length(mf),size(T,1));
        for i = 1:length(mf)
            Z(i,mf(i))=1;
        end
        Zflag = 1;
    else
        Zflag = 0;
    end
  otherwise
    error('dsge_likelihood:: Unknown initialization approach for the Kalman filter!')
end

if analytic_derivation
    if nargin < 14
        derivatives_info_input = [];
    else
        derivatives_info_input = derivatives_info;
    end
    [analytic_deriv_info, analytic_derivation, no_DLIK, DLIK, DH] = ...
        compute_analytic_derivation_info(analytic_derivation, analytic_Hessian, estim_params_, dr, derivatives_info_input, ...
        M_, options_, endo_steady_state, exo_steady_state, exo_det_steady_state, xparam1, H, T, Pstar);
else
    analytic_deriv_info={false, [], [], [], [], [], ''};
end

%------------------------------------------------------------------------------
% 4. Likelihood evaluation
%------------------------------------------------------------------------------
if isfield(options_,'likelihood_base_value') && not(isempty(options_.likelihood_base_value)) && options_.estimate_initial_states_endogenous_prior
    if not(options_.lik_init==2 && options_.Harvey_scale_factor==0)
        error('Init state endogenous prior not supported without conditional likelihood')
    else
        [lnpriorendoinitstate, lnpriorinitstate]  = init_state_endogenous_prior(a_0_given_tm0,T,R,Q,xparam1,Prior,options_,measurement_info);
    end
    % note lnprior has been already removed!
    options_.likelihood_base_value    = options_.likelihood_base_value-lnpriorendoinitstate +lnpriorinitstate;
    if occbin_.status
        occbin_.info{1} = options_;
    end
end

if options_.heteroskedastic_filter
    Q=Qvec;
end

singularity_has_been_detected = false;
% First test multivariate filter if specified; potentially abort and use univariate filter instead
if ((kalman_algo==1) || (kalman_algo==3)) || (kalman_algo == 5) % Multivariate Kalman Filter
    if no_missing_data_flag && ~options_.occbin.likelihood.status
        if options_.fast_kalman_filter
            if diffuse_periods
                %kalman_algo==3 requires no diffuse periods (stationary
                %observables) as otherwise FE matrix will not be positive
                %definite
                fval = Inf;
                info(1) = 55;
                info(4) = 0.1;
                exit_flag = 0;
                return
            end
            [LIK,lik] = kalman_filter_fast(Y,diffuse_periods+1,size(Y,2), ...
                                           a_0_given_tm1,Pstar, ...
                                           kalman_tol, ...
                                           options_.presample, ...
                                           T,H,Z,pp,Zflag,diffuse_periods);
        else
            if options_.kalman_algo == 5 % multivariate pruned skewed Kalman filter
                [LIK, lik] = kalman_filter_pruned_skewed(Y, diffuse_periods+1, size(Y,2), options_.presample, ... % data, start, last, presample
                                                         a, Pstar, zeros(size(Pstar)), zeros(size(a)), eye(size(a,1)), ... % initialize CSN at Gaussian distribution
                                                         T, R, Z, ... % state space matrices
                                                         M_.csn.mu_e, M_.csn.Sigma_e, M_.csn.Gamma_e, M_.csn.nu_e, M_.csn.Delta_e, H, ... % shock CSN parameters, measurement error covariance
                                                         kalman_tol, options_.rescale_prediction_error_covariance,... % Gaussian Kalman filter options
                                                         options_.skewed_kalman.prune_tol, options_.skewed_kalman.mvnlogcdf, options_.skewed_kalman.rank_deficiency_transform, options_.debug); % skewed Kalman filter options
            else % multivariate Gaussian Kalman filter
                if options_.kalman_filter_mex
                    [LIK,lik] = kalman_filter_mex(Y,a_0_given_tm1,Pstar, ...
                                                  kalman_tol, riccati_tol, ...
                                                  T,Q,R,Z,Zflag,H,diffuse_periods, ...
                                                  options_.presample);
                else
                    [LIK,lik] = kalman_filter(Y,diffuse_periods+1,size(Y,2), ...
                                              a_0_given_tm1,Pstar, ...
                                              kalman_tol, riccati_tol, ...
                                              options_.rescale_prediction_error_covariance, ...
                                              options_.presample, ...
                                              T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods, ...
                                              dataset_.name,options_.debug,...
                                              analytic_deriv_info{:});
                end
            end
        end
    else
        [LIK,lik] = missing_observations_kalman_filter(dataset_info.missing.aindex,dataset_info.missing.no_more_missing_observations,Y,diffuse_periods+1,size(Y,2), ...
                                                       a_0_given_tm1, Pstar, ...
                                                       kalman_tol, options_.riccati_tol, ...
                                                       options_.rescale_prediction_error_covariance, ...
                                                       options_.presample, ...
                                                       T,Q,R,H,Z,mm,pp,dataset_.name,options_.debug,Zflag,diffuse_periods, occbin_);
        if occbin_.status && isinf(LIK)
            fval = Inf;
            info(1) = 320;
            info(4) = 0.1;
            exit_flag = 0;
            return
        end
    end
    if analytic_derivation
        LIK1=LIK;
        LIK=LIK1{1};
        lik1=lik;
        lik=lik1{1};
    end
    if isinf(LIK)
        if options_.use_univariate_filters_if_singularity_is_detected
            singularity_has_been_detected = true;
            if kalman_algo == 1
                kalman_algo = 2;
            else
                kalman_algo = 4;
            end
        else
            fval = Inf;
            info(1) = 50;
            info(4) = 0.1;
            exit_flag = 0;
            return
        end
    else
        if options_.lik_init==3
            LIK = LIK + dLIK;
            if ~analytic_derivation && nargout>3
                if ~singular_diffuse_filter
                    lik = [dlik; lik];
                else
                    lik = [sum(dlik,2); lik];
                end
            end
        end
    end
end

if (kalman_algo==2) || (kalman_algo==4)
    % Univariate Kalman Filter
    % resetting measurement error covariance matrix when necessary following DK (2012), Section 6.4.3                                                          %
    if isequal(H,0)
        H1 = zeros(pp,1);
        mmm = mm;
        if analytic_derivation
            DH = zeros(pp,length(xparam1));
            if strcmp(analytic_Hessian, 'full')
                analytic_deriv_info{11} = zeros(pp,length(xparam1),length(xparam1));
            end
        end
    else
        if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
            H1 = diag(H);
            mmm = mm;
            clear('tmp')
            if analytic_derivation
                for j=1:pp
                    tmp(j,:)=DH(j,j,:);
                end
                DH=tmp;
                if strcmp(analytic_Hessian, 'full')
                    D2H_full = analytic_deriv_info{11};
                    nk = size(D2H_full,3);
                    D2H_uni = zeros(pp,nk,nk);
                    for j=1:pp
                        D2H_uni(j,:,:) = D2H_full(j,j,:,:);
                    end
                    analytic_deriv_info{11} = D2H_uni;
                end
            end
        else
            if ~expanded_state_vector_for_univariate_filter
                Z1=zeros(pp,size(T,2));
                for jz=1:length(Z)
                    Z1(jz,Z(jz))=1;
                end
                Z = [Z1, eye(pp)];
                T = blkdiag(T,zeros(pp));
                if options_.heteroskedastic_filter
                    clear Q
                    for kv=1:size(Qvec,3)
                        Q(:,:,kv) = blkdiag(Qvec(:,:,kv),H);
                    end
                else
                    Q = blkdiag(Q,H);
                end
                R = blkdiag(R,eye(pp));
                Pstar = blkdiag(Pstar,H);
                H1 = zeros(pp,1);
                Zflag=1;
                if analytic_derivation
                    % Augment first-derivative arrays for expanded state space.
                    % Augmented system absorbs H into the state dynamics:
                    %   T_aug = blkdiag(T, 0),  Om_aug = blkdiag(Om, H),
                    %   Pstar_aug = blkdiag(Pstar, H),  H1 = 0.
                    nk = length(xparam1);
                    DH_3D = DH;  % Save 3D DH (pp x pp x nk) before overwriting

                    DT_orig = analytic_deriv_info{2};
                    DT_aug = zeros(mm+pp, mm+pp, nk);
                    DT_aug(1:mm, 1:mm, :) = DT_orig;
                    analytic_deriv_info{2} = DT_aug;

                    DYss_orig = analytic_deriv_info{3};
                    DYss_aug = zeros(mm+pp, size(DYss_orig,2));
                    DYss_aug(1:mm, :) = DYss_orig;
                    analytic_deriv_info{3} = DYss_aug;

                    DOm_orig = analytic_deriv_info{4};
                    DOm_aug = zeros(mm+pp, mm+pp, nk);
                    DOm_aug(1:mm, 1:mm, :) = DOm_orig;
                    DOm_aug(mm+1:end, mm+1:end, :) = DH_3D;
                    analytic_deriv_info{4} = DOm_aug;

                    DP_orig = analytic_deriv_info{6};
                    DP_aug = zeros(mm+pp, mm+pp, nk);
                    DP_aug(1:mm, 1:mm, :) = DP_orig;
                    DP_aug(mm+1:end, mm+1:end, :) = DH_3D;
                    analytic_deriv_info{6} = DP_aug;

                    % DH for univariate becomes zero since H1 = 0
                    DH = zeros(pp, nk);

                    if strcmp(analytic_Hessian, 'full')
                        D2H_full = analytic_deriv_info{11};
                        % Get dimensions of original state space from D2T size
                        D2T_orig = analytic_deriv_info{8};
                        ncols = size(D2T_orig, 2);
                        mm_orig = sqrt(size(D2T_orig, 1));  % D2T is vec(T), so rows = mm^2
                        mmm_aug = mm_orig + pp;

                        % D2T: vec format. Map mm_orig x mm_orig positions into mmm_aug x mmm_aug.
                        [r_grid, c_grid] = ndgrid(1:mm_orig, 1:mm_orig);
                        aug_vec_idx = (c_grid(:)-1)*mmm_aug + r_grid(:);
                        D2T_aug = zeros(mmm_aug^2, ncols);
                        D2T_aug(aug_vec_idx,:) = D2T_orig;
                        analytic_deriv_info{8} = D2T_aug;

                        % D2Yss
                        D2Yss_orig = analytic_deriv_info{9};
                        D2Yss_aug = zeros(mmm_aug, size(D2Yss_orig,2), size(D2Yss_orig,3));
                        D2Yss_aug(1:mm_orig, :, :) = D2Yss_orig;
                        analytic_deriv_info{9} = D2Yss_aug;

                        % D2Om and D2P: vech format. Build index maps.
                        idx_vech_aug = dyn_unvech(1:mmm_aug*(mmm_aug+1)/2);
                        orig_vech_idx = dyn_vech(idx_vech_aug(1:mm_orig,1:mm_orig));
                        H_vech_idx = dyn_vech(idx_vech_aug(mm_orig+1:end,mm_orig+1:end));

                        % D2Om
                        D2Om_orig = analytic_deriv_info{10};
                        D2Om_aug = zeros(mmm_aug*(mmm_aug+1)/2, ncols);
                        D2Om_aug(orig_vech_idx,:) = D2Om_orig;
                        jcount = 0;
                        for ii = 1:nk
                            for jj = 1:ii
                                jcount = jcount + 1;
                                D2H_ij = D2H_full(:,:,jj,ii);
                                if any(D2H_ij(:))
                                    D2Om_aug(H_vech_idx, jcount) = dyn_vech(D2H_ij);
                                end
                            end
                        end
                        analytic_deriv_info{10} = D2Om_aug;

                        % D2P: same augmentation as D2Om
                        D2P_orig = analytic_deriv_info{12};
                        D2P_aug = zeros(mmm_aug*(mmm_aug+1)/2, ncols);
                        D2P_aug(orig_vech_idx,:) = D2P_orig;
                        jcount = 0;
                        for ii = 1:nk
                            for jj = 1:ii
                                jcount = jcount + 1;
                                D2H_ij = D2H_full(:,:,jj,ii);
                                if any(D2H_ij(:))
                                    D2P_aug(H_vech_idx, jcount) = dyn_vech(D2H_ij);
                                end
                            end
                        end
                        analytic_deriv_info{12} = D2P_aug;

                        % D2H for univariate = 0 since H1 = 0
                        analytic_deriv_info{11} = zeros(pp, nk, nk);
                    end
                end
            end
            mmm   = mm+pp;
            if singularity_has_been_detected
                a_tmp = zeros(mmm,1);
                a_tmp(1:length(a_0_given_tm1)) = a_0_given_tm1;
                a_0_given_tm1 = a_tmp;
            elseif ~expanded_state_vector_for_univariate_filter
                a_0_given_tm1 = [a_0_given_tm1; zeros(pp,1)];
            end
        end
    end
    if analytic_derivation
        analytic_deriv_info{5}=DH;
    end
    [LIK, lik] = univariate_kalman_filter(dataset_info.missing.aindex,dataset_info.missing.no_more_missing_observations,Y,diffuse_periods+1,size(Y,2), ...
                                          a_0_given_tm1,Pstar, ...
                                          options_.kalman_tol, ...
                                          options_.riccati_tol, ...
                                          options_.presample, ...
                                          T,Q,R,H1,Z,mmm,pp,Zflag,diffuse_periods,analytic_deriv_info{:});
    if analytic_derivation
        LIK1=LIK;
        LIK=LIK1{1};
        lik1=lik;
        lik=lik1{1};
    end
    if options_.lik_init==3
        LIK = LIK+dLIK;
        if ~analytic_derivation && nargout>3
            lik = [dlik; lik];
        end
    end
end

if analytic_derivation
    if no_DLIK==0
        DLIK = LIK1{2};
    end
    if strcmp(analytic_Hessian, 'full')
        Hess = -LIK1{3};
    end
    if strcmp(analytic_Hessian, 'asymptotic')
        Hess = LIK1{3};
    end
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
if isinf(LIK)
    fval = Inf; info(1) = 50; info(4) = 0.1; exit_flag = 0;
    return
end
likelihood = LIK;

% ------------------------------------------------------------------------------
% 5. Adds prior if necessary
% ------------------------------------------------------------------------------
if analytic_derivation
    if strcmp(analytic_Hessian, 'full')
        [lnprior, dlnprior, d2lnprior] = density(Prior, xparam1);
        Hess = Hess - d2lnprior;
    else
        [lnprior, dlnprior] = density(Prior, xparam1);
    end
    if no_DLIK==0
        DLIK = DLIK - dlnprior';
    end
    if strcmp(analytic_Hessian, 'opg')
        dlik = lik1{2};
        dlik=[- dlnprior; dlik(start:end,:)];
        Hess = dlik'*dlik;
    end
else
    lnprior = Prior.density(xparam1);
end
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

if options_.endogenous_prior==1
    if options_.lik_init==2 || options_.lik_init==3
        error('Endogenous prior not supported with non-stationary models')
    else
        [lnpriormom]  = endogenous_prior(Y,dataset_info,Pstar,H,measurement_info);
        fval    = (likelihood-lnprior-lnpriormom);
    end
elseif options_.estimate_initial_states_endogenous_prior
    if not(options_.lik_init==2 && options_.Harvey_scale_factor==0)
        error('Init state endogenous prior not supported without conditional likelihood')
    else
        [lnpriorendoinitstate, lnpriorinitstate]  = init_state_endogenous_prior(a_0_given_tm0,T,R,Q,xparam1,Prior,options_,measurement_info);
    end
    fval    = likelihood-lnpriorendoinitstate - (lnprior-lnpriorinitstate);

else
    fval    = (likelihood-lnprior);
end

if options_.prior_restrictions.status
    tmp = feval(options_.prior_restrictions.routine, M_, dr, endo_steady_state, exo_steady_state, exo_det_steady_state, options_, dataset_, dataset_info);
    fval = fval - tmp;
end

if ~analytic_derivation && nargout>3
    lik=lik(start:end,:);
    DLIK=[-lnprior; lik(:)];
end

if nargout >= 6
    model_solution.dr = dr;
    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.mf = mf;
end

function [analytic_deriv_info, analytic_derivation, no_DLIK, DLIK, DH] = ...
    compute_analytic_derivation_info(analytic_derivation, analytic_Hessian, estim_params_, dr, derivatives_info, ...
    M_, options_, endo_steady_state, exo_steady_state, exo_det_steady_state, xparam1, H, T, Pstar)
% Compute analytic derivative information for the Kalman filter.
% This builds the analytic_deriv_info cell array containing first (and
% optionally second) order derivatives of the state-space system matrices
% with respect to the estimated parameters.

offset = estim_params_.nvx + estim_params_.nvn + estim_params_.ncx + estim_params_.ncn;
no_DLIK = 0;
full_Hess = strcmp(analytic_Hessian, 'full');
DLIK = [];
iv = dr.restrict_var_list;
if isempty(derivatives_info)
    if ~isempty(estim_params_.var_exo)
        indexo=estim_params_.var_exo(:,1);
    else
        indexo=[];
    end
    if ~isempty(estim_params_.param_vals)
        indparam=estim_params_.param_vals(:,1);
    else
        indparam=[];
    end
    if ~isempty(estim_params_.corrx)
        indpcorr=estim_params_.corrx(:,1:2);
    else
        indpcorr=[];
    end

    % Compute perturbation parameter derivatives (first and optionally second order)
    DERIVS = identification.get_perturbation_params_derivs(M_, options_, estim_params_, dr, endo_steady_state, exo_steady_state, exo_det_steady_state, indparam, indexo, indpcorr, full_Hess);

    % Extract first-order derivatives
    DT = zeros(M_.endo_nbr, M_.endo_nbr, size(DERIVS.dghx,3));
    DT(:,M_.nstatic+(1:M_.nspred),:) = DERIVS.dghx;
    DT = DT(iv,iv,:);
    DOm = DERIVS.dOm(iv,iv,:);
    DYss = DERIVS.dYss(iv,:);

    % Extract second-order derivatives if computing full Hessian
    if full_Hess
        indD2T = reshape(1:M_.endo_nbr^2, M_.endo_nbr, M_.endo_nbr);
        indD2Om = dyn_unvech(1:M_.endo_nbr*(M_.endo_nbr+1)/2);
        D2T = DERIVS.d2KalmanA(indD2T(iv,iv),:);
        D2Om = DERIVS.d2Om(dyn_vech(indD2Om(iv,iv)),:);
        D2Yss = DERIVS.d2Yss(iv,:,:);
    end

else
    DT = derivatives_info.DT(iv,iv,:);
    DOm = derivatives_info.DOm(iv,iv,:);
    DYss = derivatives_info.DYss(iv,:);
    if isfield(derivatives_info,'full_Hess')
        full_Hess = derivatives_info.full_Hess;
    end
    if full_Hess
        D2T = derivatives_info.D2T;
        D2Om = derivatives_info.D2Om;
        D2Yss = derivatives_info.D2Yss;
    end
    if isfield(derivatives_info,'no_DLIK')
        no_DLIK = derivatives_info.no_DLIK;
    end
end
% The DERIVS arrays from get_perturbation_params_derivs use parameter
% ordering [stderr_shock(1:nvx), corr_shock(1:ncx), model_params(1:np)].
% The estimation ordering is [nvx, nvn, ncx, ncn, np]. T and Om do
% not depend on nvn or ncn parameters, so we insert zero slices for
% those positions.
n_inserted = estim_params_.nvn + estim_params_.ncn;
if n_inserted > 0
    DT = cat(3, DT(:,:,1:estim_params_.nvx), ...
                zeros(size(DT,1), size(DT,2), estim_params_.nvn), ...
                DT(:,:,estim_params_.nvx+1:estim_params_.nvx+estim_params_.ncx), ...
                zeros(size(DT,1), size(DT,2), estim_params_.ncn), ...
                DT(:,:,estim_params_.nvx+estim_params_.ncx+1:end));
    DOm = cat(3, DOm(:,:,1:estim_params_.nvx), ...
                 zeros(size(DOm,1), size(DOm,2), estim_params_.nvn), ...
                 DOm(:,:,estim_params_.nvx+1:estim_params_.nvx+estim_params_.ncx), ...
                 zeros(size(DOm,1), size(DOm,2), estim_params_.ncn), ...
                 DOm(:,:,estim_params_.nvx+estim_params_.ncx+1:end));
    if full_Hess
        % Remap D2T and D2Om columns from DERIVS vech-ordering
        % (nvx+ncx+np parameters) to estimation vech-ordering
        % (nvx+nvn+ncx+ncn+np parameters). Columns corresponding to
        % nvn/ncn parameter pairs are zero (T and Om do not depend
        % on them) and are left at their initialized value.
        totparam_derivs = estim_params_.nvx + estim_params_.ncx + estim_params_.np;
        totparam_estim  = totparam_derivs + n_inserted;
        % Build mapping: estimation parameter index -> DERIVS parameter index (0 = not in DERIVS)
        estim2derivs = zeros(1, totparam_estim);
        estim2derivs(1:estim_params_.nvx) = 1:estim_params_.nvx;
        % nvn positions map to 0 (not in DERIVS)
        estim2derivs(estim_params_.nvx + estim_params_.nvn + 1 : estim_params_.nvx + estim_params_.nvn + estim_params_.ncx) = estim_params_.nvx + 1 : estim_params_.nvx + estim_params_.ncx;
        % ncn positions map to 0 (not in DERIVS)
        estim2derivs(estim_params_.nvx + estim_params_.nvn + estim_params_.ncx + estim_params_.ncn + 1 : end) = estim_params_.nvx + estim_params_.ncx + 1 : totparam_derivs;
        D2T_old  = D2T;
        D2Om_old = D2Om;
        ncols_estim = totparam_estim*(totparam_estim+1)/2;
        D2T  = zeros(size(D2T_old,1),  ncols_estim);
        D2Om = zeros(size(D2Om_old,1), ncols_estim);
        jcount_estim = 0;
        for ii = 1:totparam_estim
            for jj = 1:ii
                jcount_estim = jcount_estim + 1;
                di = estim2derivs(ii);
                dj = estim2derivs(jj);
                if di > 0 && dj > 0
                    % Both parameters exist in DERIVS; look up the
                    % corresponding vech column index in the original arrays
                    di_large = max(di, dj);
                    dj_small = min(di, dj);
                    jcount_derivs = di_large*(di_large-1)/2 + dj_small;
                    D2T(:, jcount_estim)  = D2T_old(:, jcount_derivs);
                    D2Om(:, jcount_estim) = D2Om_old(:, jcount_derivs);
                end
            end
        end
    end
end
DYss = [zeros(size(DYss,1),offset) DYss];
DH=zeros([length(H),length(H),length(xparam1)]);
DP=zeros([size(T),length(xparam1)]);
if full_Hess
    tmp = zeros(size(D2Yss,1), offset+size(D2Yss,2), offset+size(D2Yss,3));
    for j=1:size(D2Yss,1)
        tmp(j,:,:) = blkdiag(zeros(offset,offset), squeeze(D2Yss(j,:,:)));
    end
    D2Yss = tmp;
    D2H=zeros([length(H),length(H),length(xparam1),length(xparam1)]);
    D2P=zeros(size(D2Om,1),size(D2Om,2));
    jcount=0;
end
if options_.lik_init==1
    for i=1:estim_params_.nvx
        dum =  lyapunov_symm(T,DOm(:,:,i),options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold,[],options_.debug);
        DP(:,:,i)=dum;
        if full_Hess
            for j=1:i
                jcount=jcount+1;
                dum =  lyapunov_symm(T,dyn_unvech(D2Om(:,jcount)),options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold,[],options_.debug);
                D2P(:,jcount)=dyn_vech(dum);
            end
        end
    end
end
offset = estim_params_.nvx;
for i=1:estim_params_.nvn
    % Use observable index (position in varobs) for H and DH, not
    % endogenous variable index from var_endo.
    k = estim_params_.nvn_observable_correspondence(i,1);
    sigma_k = sqrt(H(k,k));
    % Full derivative of H w.r.t. σ_k including off-diagonals.
    % H = diag(σ)*Corr*diag(σ), so ∂H(a,b)/∂σ_k equals:
    %   H(a,b)/σ_k  when a=k xor b=k (off-diagonal in row/col k)
    %   2σ_k         when a=b=k (diagonal)
    %   0             otherwise
    DH(k,:,i+offset) = H(k,:) / sigma_k;
    DH(:,k,i+offset) = H(:,k) / sigma_k;
    DH(k,k,i+offset) = 2 * sigma_k;
    if full_Hess
        D2H(k,k,i+offset,i+offset) = 2;
        % Advance jcount for nvn vs earlier params: D2P is zero since
        % measurement error parameters do not affect T or Om.
        % Also compute nvn-nvn cross-derivatives for off-diagonal H:
        % ∂²H(k_i,k_j)/∂σ_{k_i}∂σ_{k_j} = Corr(k_i,k_j) when k_i≠k_j
        for j=1:i+offset
            jcount=jcount+1;
            if j > estim_params_.nvx && j <= estim_params_.nvx + estim_params_.nvn && j ~= i + offset
                jj = j - estim_params_.nvx;
                kj = estim_params_.nvn_observable_correspondence(jj,1);
                if kj ~= k
                    sigma_kj = sqrt(H(kj,kj));
                    corr_val = H(k,kj) / (sigma_k * sigma_kj);
                    D2H(k,kj,i+offset,j) = corr_val;
                    D2H(kj,k,i+offset,j) = corr_val;
                    D2H(k,kj,j,i+offset) = corr_val;
                    D2H(kj,k,j,i+offset) = corr_val;
                end
            end
        end
    end
end
offset = offset + estim_params_.nvn;
% Shock correlation parameters: DOm already populated from DERIVS.
% Only DP (and D2P) need to be computed here.
for i=1:estim_params_.ncx
    if options_.lik_init==1
        dum = lyapunov_symm(T,DOm(:,:,i+offset),options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold,[],options_.debug);
        DP(:,:,i+offset) = dum;
    end
    if full_Hess
        DPi = DP(:,:,i+offset);
        for j=1:i+offset
            jcount=jcount+1;
            D2Omij = dyn_unvech(D2Om(:,jcount));
            if any(D2Omij(:))
                if options_.lik_init==1
                    DTj = DT(:,:,j);
                    % DT(:,:,i+offset) is zero for ncx, so terms
                    % with DTi drop out and DPj is not needed.
                    tmpv = DTj*DPi*T' + T*DPi*DTj' + D2Omij;
                    dum = lyapunov_symm(T,tmpv,options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold,[],options_.debug);
                    D2P(:,jcount) = dyn_vech(dum);
                end
            end
        end
    end
end
offset = offset + estim_params_.ncx;
% Measurement error correlation parameters: ∂H(k1,k2)/∂ρ = sqrt(H(k1,k1))*sqrt(H(k2,k2))
% These only affect H, not T or Om.
for i=1:estim_params_.ncn
    k1 = estim_params_.corrn_observable_correspondence(i,1);
    k2 = estim_params_.corrn_observable_correspondence(i,2);
    dHij = sqrt(H(k1,k1))*sqrt(H(k2,k2));
    DH(k1,k2,i+offset) = dHij;
    DH(k2,k1,i+offset) = dHij;
    if full_Hess
        % Cross-derivatives of H w.r.t. ncn param i and nvn params:
        % ∂²H(k1,k2)/∂ρ_{k1,k2} ∂σ_{kj} = σ_{k_other}
        for j=1:i+offset
            jcount=jcount+1;
            if j > estim_params_.nvx && j <= estim_params_.nvx + estim_params_.nvn
                jj = j - estim_params_.nvx;
                kj = estim_params_.nvn_observable_correspondence(jj,1);
                if kj == k1
                    D2H(k1,k2,j,i+offset) = sqrt(H(k2,k2));
                    D2H(k2,k1,j,i+offset) = D2H(k1,k2,j,i+offset);
                    D2H(k1,k2,i+offset,j) = D2H(k1,k2,j,i+offset);
                    D2H(k2,k1,i+offset,j) = D2H(k1,k2,j,i+offset);
                end
                if kj == k2
                    D2H(k1,k2,j,i+offset) = D2H(k1,k2,j,i+offset) + sqrt(H(k1,k1));
                    D2H(k2,k1,j,i+offset) = D2H(k1,k2,j,i+offset);
                    D2H(k1,k2,i+offset,j) = D2H(k1,k2,j,i+offset);
                    D2H(k2,k1,i+offset,j) = D2H(k1,k2,j,i+offset);
                end
            end
            % Note: ncn-ncn and ncn-ncx cross-derivatives of H are zero
            % (H is linear in each correlation param, and ncx/ncn are
            % independent parameter groups).
        end
    end
end
offset = offset + estim_params_.ncn;
if options_.lik_init==1
    for j=1:estim_params_.np
        dum =  lyapunov_symm(T,DT(:,:,j+offset)*Pstar*T'+T*Pstar*DT(:,:,j+offset)'+DOm(:,:,j+offset),options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold,[],options_.debug);
        DP(:,:,j+offset)=dum;
        if full_Hess
            DTj = DT(:,:,j+offset);
            DPj = dum;
            for i=1:j+offset
                jcount=jcount+1;
                DTi = DT(:,:,i);
                DPi = DP(:,:,i);
                D2Tij = reshape(D2T(:,jcount),size(T));
                D2Omij = dyn_unvech(D2Om(:,jcount));
                tmp = D2Tij*Pstar*T' + T*Pstar*D2Tij' + DTi*DPj*T' + DTj*DPi*T' + T*DPj*DTi' + T*DPi*DTj' + DTi*Pstar*DTj' + DTj*Pstar*DTi' + D2Omij;
                dum = lyapunov_symm(T,tmp,options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold,[],options_.debug);
                D2P(:,jcount) = dyn_vech(dum);
            end
        end
    end
end
if full_Hess
    analytic_deriv_info={analytic_derivation,DT,DYss,DOm,DH,DP,analytic_Hessian,D2T,D2Yss,D2Om,D2H,D2P};
else
    analytic_deriv_info={analytic_derivation,DT,DYss,DOm,DH,DP,analytic_Hessian};
end

function[occbin_options, occbin_filter_state_covariance] = set_occbin_options(options_)

% this builds the opts_simul options field needed by occbin.solver
occbin_options.opts_simul = options_.occbin.simul;
occbin_options.opts_simul.curb_retrench = options_.occbin.likelihood.curb_retrench;
occbin_options.opts_simul.maxit = options_.occbin.likelihood.maxit;
occbin_options.opts_simul.periods = options_.occbin.likelihood.periods;
occbin_options.opts_simul.check_ahead_periods = options_.occbin.likelihood.check_ahead_periods;
occbin_options.opts_simul.max_check_ahead_periods = options_.occbin.likelihood.max_check_ahead_periods;
occbin_options.opts_simul.periodic_solution = options_.occbin.likelihood.periodic_solution;
occbin_options.opts_simul.restrict_state_space = options_.occbin.likelihood.restrict_state_space;

occbin_options.opts_simul.full_output = options_.occbin.likelihood.full_output;
occbin_options.opts_simul.piecewise_only = options_.occbin.likelihood.piecewise_only;
occbin_options.opts_regime.init_binding_indicator = options_.occbin.likelihood.init_binding_indicator;
occbin_options.opts_regime.init_regime_history=options_.occbin.likelihood.init_regime_history;

% this checks particle filter options
if options_.occbin.filter.init_periods_using_particles || options_.occbin.filter.particle.status
    occbin_filter_state_covariance= true;
else
    occbin_filter_state_covariance= false;
end
