function mcheck = mode_check(fun,xparam,hessian_mat,options_,M_,estim_params_,bayestopt_,bounds,isMinimum, varargin)
% function mcheck = mode_check(fun,xparam,hessian_mat,options_,M_,estim_params_,bayestopt_,bounds,isMinimum, varargin)
% -------------------------------------------------------------------------
% Checks the estimated ML or Posterior mode/minimum by plotting sections of
% the likelihood/posterior kernel. Each plot shows the variation of the
% function implied by the variations of a single parameter ( ceteris paribus)
% -------------------------------------------------------------------------
% INPUTS
% - fun: [func_handle] objective function
% - xparam: [vector] estimated mode/minimum
% - hessian_mat: [matrix] hessian of the objective function at the estimated mode/minimum
% - options_: [structure] Dynare options structure
% - M_: [structure] Dynare model structure
% - estim_params_: [structure] Dynare estimated parameters structure
% - bayestopt_: [structure] information on the priors
% - bounds: [structure] information on the bounds
% - isMinimum: [boolean] true if xparam is a minimum, false if it is a mode
% - varargin: [cell] additional arguments to be passed to fun
% -------------------------------------------------------------------------
% OUTPUTS
% - mcheck: [structure] structure containing the data for the check plots
% - Saves the plots in the graphs folder and the data in a mat file
% -------------------------------------------------------------------------
% This function is called by
% - dynare_estimation_1
% - mom.run
% -------------------------------------------------------------------------
% Copyright © 2023 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 .
tolBounds = 1e-8;
fval = feval(fun,xparam,varargin{:});
if ~isempty(hessian_mat)
[ s_min, k ] = min(diag(hessian_mat));
if isMinimum
fprintf('\nMINIMUM CHECK\n\nFval obtained by the optimization routine: %f\n', fval)
else
fprintf('\nMODE CHECK\n\nFval obtained by the optimization routine: %f\n', fval)
end
if s_min(1-ll)*xparam(kk)) && (xparam(kk)+(xparam(kk)-l1)